2 * Server-side file mapping management
4 * Copyright (C) 1999 Alexandre Julliard
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #include "wine/port.h"
29 #ifdef HAVE_SYS_MMAN_H
30 # include <sys/mman.h>
35 #define WIN32_NO_STATUS
45 /* list of memory ranges, used to store committed info */
59 struct object obj; /* object header */
60 mem_size_t size; /* mapping size */
61 int protect; /* protection flags */
62 struct fd *fd; /* fd for mapped file */
63 int header_size; /* size of headers (for PE image mapping) */
64 client_ptr_t base; /* default base addr (for PE image mapping) */
65 struct ranges *committed; /* list of committed ranges in this mapping */
66 struct file *shared_file; /* temp file for shared PE mapping */
67 struct list shared_entry; /* entry in global shared PE mappings list */
70 static void mapping_dump( struct object *obj, int verbose );
71 static struct object_type *mapping_get_type( struct object *obj );
72 static struct fd *mapping_get_fd( struct object *obj );
73 static unsigned int mapping_map_access( struct object *obj, unsigned int access );
74 static void mapping_destroy( struct object *obj );
75 static enum server_fd_type mapping_get_fd_type( struct fd *fd );
77 static const struct object_ops mapping_ops =
79 sizeof(struct mapping), /* size */
80 mapping_dump, /* dump */
81 mapping_get_type, /* get_type */
82 no_add_queue, /* add_queue */
83 NULL, /* remove_queue */
86 no_signal, /* signal */
87 mapping_get_fd, /* get_fd */
88 mapping_map_access, /* map_access */
89 default_get_sd, /* get_sd */
90 default_set_sd, /* set_sd */
91 no_lookup_name, /* lookup_name */
92 no_open_file, /* open_file */
93 fd_close_handle, /* close_handle */
94 mapping_destroy /* destroy */
97 static const struct fd_ops mapping_fd_ops =
99 default_fd_get_poll_events, /* get_poll_events */
100 default_poll_event, /* poll_event */
101 no_flush, /* flush */
102 mapping_get_fd_type, /* get_fd_type */
103 no_fd_ioctl, /* ioctl */
104 no_fd_queue_async, /* queue_async */
105 default_fd_reselect_async, /* reselect_async */
106 default_fd_cancel_async /* cancel_async */
109 static struct list shared_list = LIST_INIT(shared_list);
113 /* These are always the same on an i386, and it will be faster this way */
114 # define page_mask 0xfff
115 # define page_shift 12
116 # define init_page_size() do { /* nothing */ } while(0)
120 static int page_shift, page_mask;
122 static void init_page_size(void)
125 # ifdef HAVE_GETPAGESIZE
126 page_size = getpagesize();
129 page_size = sysconf(_SC_PAGESIZE);
131 # error Cannot get the page size on this platform
134 page_mask = page_size - 1;
135 /* Make sure we have a power of 2 */
136 assert( !(page_size & page_mask) );
138 while ((1 << page_shift) != page_size) page_shift++;
140 #endif /* __i386__ */
142 #define ROUND_SIZE(size) (((size) + page_mask) & ~page_mask)
145 /* extend a file beyond the current end of file */
146 static int grow_file( int unix_fd, file_pos_t new_size )
148 static const char zero;
149 off_t size = new_size;
151 if (sizeof(new_size) > sizeof(size) && size != new_size)
153 set_error( STATUS_INVALID_PARAMETER );
156 /* extend the file one byte beyond the requested size and then truncate it */
157 /* this should work around ftruncate implementations that can't extend files */
158 if (pwrite( unix_fd, &zero, 1, size ) != -1)
160 ftruncate( unix_fd, size );
167 /* check if the current directory allows exec mappings */
168 static int check_current_dir_for_exec(void)
171 char tmpfn[] = "anonmap.XXXXXX";
172 void *ret = MAP_FAILED;
174 fd = mkstemps( tmpfn, 0 );
175 if (fd == -1) return 0;
176 if (grow_file( fd, 1 ))
178 ret = mmap( NULL, get_page_size(), PROT_READ | PROT_EXEC, MAP_PRIVATE, fd, 0 );
179 if (ret != MAP_FAILED) munmap( ret, get_page_size() );
183 return (ret != MAP_FAILED);
186 /* create a temp file for anonymous mappings */
187 static int create_temp_file( file_pos_t size )
189 static int temp_dir_fd = -1;
190 char tmpfn[] = "anonmap.XXXXXX";
193 if (temp_dir_fd == -1)
195 temp_dir_fd = server_dir_fd;
196 if (!check_current_dir_for_exec())
198 /* the server dir is noexec, try the config dir instead */
199 fchdir( config_dir_fd );
200 if (check_current_dir_for_exec())
201 temp_dir_fd = config_dir_fd;
202 else /* neither works, fall back to server dir */
203 fchdir( server_dir_fd );
206 else if (temp_dir_fd != server_dir_fd) fchdir( temp_dir_fd );
208 fd = mkstemps( tmpfn, 0 );
211 if (!grow_file( fd, size ))
218 else file_set_error();
220 if (temp_dir_fd != server_dir_fd) fchdir( server_dir_fd );
224 /* find the shared PE mapping for a given mapping */
225 static struct file *get_shared_file( struct mapping *mapping )
229 LIST_FOR_EACH_ENTRY( ptr, &shared_list, struct mapping, shared_entry )
230 if (is_same_file_fd( ptr->fd, mapping->fd ))
231 return (struct file *)grab_object( ptr->shared_file );
235 /* return the size of the memory mapping and file range of a given section */
236 static inline void get_section_sizes( const IMAGE_SECTION_HEADER *sec, size_t *map_size,
237 off_t *file_start, size_t *file_size )
239 static const unsigned int sector_align = 0x1ff;
241 if (!sec->Misc.VirtualSize) *map_size = ROUND_SIZE( sec->SizeOfRawData );
242 else *map_size = ROUND_SIZE( sec->Misc.VirtualSize );
244 *file_start = sec->PointerToRawData & ~sector_align;
245 *file_size = (sec->SizeOfRawData + (sec->PointerToRawData & sector_align) + sector_align) & ~sector_align;
246 if (*file_size > *map_size) *file_size = *map_size;
249 /* add a range to the committed list */
250 static void add_committed_range( struct mapping *mapping, file_pos_t start, file_pos_t end )
253 struct range *ranges;
255 if (!mapping->committed) return; /* everything committed already */
257 for (i = 0, ranges = mapping->committed->ranges; i < mapping->committed->count; i++)
259 if (ranges[i].start > end) break;
260 if (ranges[i].end < start) continue;
261 if (ranges[i].start > start) ranges[i].start = start; /* extend downwards */
262 if (ranges[i].end < end) /* extend upwards and maybe merge with next */
264 for (j = i + 1; j < mapping->committed->count; j++)
266 if (ranges[j].start > end) break;
267 if (ranges[j].end > end) end = ranges[j].end;
271 memmove( &ranges[i + 1], &ranges[j], (mapping->committed->count - j) * sizeof(*ranges) );
272 mapping->committed->count -= j - (i + 1);
279 /* now add a new range */
281 if (mapping->committed->count == mapping->committed->max)
283 unsigned int new_size = mapping->committed->max * 2;
284 struct ranges *new_ptr = realloc( mapping->committed, offsetof( struct ranges, ranges[new_size] ));
285 if (!new_ptr) return;
286 new_ptr->max = new_size;
287 ranges = new_ptr->ranges;
288 mapping->committed = new_ptr;
290 memmove( &ranges[i + 1], &ranges[i], (mapping->committed->count - i) * sizeof(*ranges) );
291 ranges[i].start = start;
293 mapping->committed->count++;
296 /* find the range containing start and return whether it's committed */
297 static int find_committed_range( struct mapping *mapping, file_pos_t start, mem_size_t *size )
300 struct range *ranges;
302 if (!mapping->committed) /* everything is committed */
304 *size = mapping->size - start;
307 for (i = 0, ranges = mapping->committed->ranges; i < mapping->committed->count; i++)
309 if (ranges[i].start > start)
311 *size = ranges[i].start - start;
314 if (ranges[i].end > start)
316 *size = ranges[i].end - start;
320 *size = mapping->size - start;
324 /* allocate and fill the temp file for a shared PE image mapping */
325 static int build_shared_mapping( struct mapping *mapping, int fd,
326 IMAGE_SECTION_HEADER *sec, unsigned int nb_sec )
329 mem_size_t total_size;
330 size_t file_size, map_size, max_size;
331 off_t shared_pos, read_pos, write_pos;
336 /* compute the total size of the shared mapping */
338 total_size = max_size = 0;
339 for (i = 0; i < nb_sec; i++)
341 if ((sec[i].Characteristics & IMAGE_SCN_MEM_SHARED) &&
342 (sec[i].Characteristics & IMAGE_SCN_MEM_WRITE))
344 get_section_sizes( &sec[i], &map_size, &read_pos, &file_size );
345 if (file_size > max_size) max_size = file_size;
346 total_size += map_size;
349 if (!total_size) return 1; /* nothing to do */
351 if ((mapping->shared_file = get_shared_file( mapping ))) return 1;
353 /* create a temp file for the mapping */
355 if ((shared_fd = create_temp_file( total_size )) == -1) return 0;
356 if (!(mapping->shared_file = create_file_for_fd( shared_fd, FILE_GENERIC_READ|FILE_GENERIC_WRITE, 0 )))
359 if (!(buffer = malloc( max_size ))) goto error;
361 /* copy the shared sections data into the temp file */
364 for (i = 0; i < nb_sec; i++)
366 if (!(sec[i].Characteristics & IMAGE_SCN_MEM_SHARED)) continue;
367 if (!(sec[i].Characteristics & IMAGE_SCN_MEM_WRITE)) continue;
368 get_section_sizes( &sec[i], &map_size, &read_pos, &file_size );
369 write_pos = shared_pos;
370 shared_pos += map_size;
371 if (!sec[i].PointerToRawData || !file_size) continue;
375 long res = pread( fd, buffer + file_size - toread, toread, read_pos );
376 if (!res && toread < 0x200) /* partial sector at EOF is not an error */
381 if (res <= 0) goto error;
385 if (pwrite( shared_fd, buffer, file_size, write_pos ) != file_size) goto error;
391 release_object( mapping->shared_file );
392 mapping->shared_file = NULL;
397 /* retrieve the mapping parameters for an executable (PE) image */
398 static int get_image_params( struct mapping *mapping, int unix_fd, int protect )
400 IMAGE_DOS_HEADER dos;
401 IMAGE_SECTION_HEADER *sec = NULL;
405 IMAGE_FILE_HEADER FileHeader;
408 IMAGE_OPTIONAL_HEADER32 hdr32;
409 IMAGE_OPTIONAL_HEADER64 hdr64;
415 /* load the headers */
417 if (pread( unix_fd, &dos, sizeof(dos), 0 ) != sizeof(dos)) goto error;
418 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto error;
421 size = pread( unix_fd, &nt, sizeof(nt), pos );
422 if (size < sizeof(nt.Signature) + sizeof(nt.FileHeader)) goto error;
423 /* zero out Optional header in the case it's not present or partial */
424 if (size < sizeof(nt)) memset( (char *)&nt + size, 0, sizeof(nt) - size );
425 if (nt.Signature != IMAGE_NT_SIGNATURE) goto error;
427 switch (nt.opt.hdr32.Magic)
429 case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
430 mapping->size = ROUND_SIZE( nt.opt.hdr32.SizeOfImage );
431 mapping->base = nt.opt.hdr32.ImageBase;
432 mapping->header_size = nt.opt.hdr32.SizeOfHeaders;
434 case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
435 mapping->size = ROUND_SIZE( nt.opt.hdr64.SizeOfImage );
436 mapping->base = nt.opt.hdr64.ImageBase;
437 mapping->header_size = nt.opt.hdr64.SizeOfHeaders;
443 /* load the section headers */
445 pos += sizeof(nt.Signature) + sizeof(nt.FileHeader) + nt.FileHeader.SizeOfOptionalHeader;
446 size = sizeof(*sec) * nt.FileHeader.NumberOfSections;
447 if (pos + size > mapping->size) goto error;
448 if (pos + size > mapping->header_size) mapping->header_size = pos + size;
449 if (!(sec = malloc( size ))) goto error;
450 if (pread( unix_fd, sec, size, pos ) != size) goto error;
452 if (!build_shared_mapping( mapping, unix_fd, sec, nt.FileHeader.NumberOfSections )) goto error;
454 if (mapping->shared_file) list_add_head( &shared_list, &mapping->shared_entry );
456 mapping->protect = protect;
462 set_error( STATUS_INVALID_FILE_FOR_SECTION );
466 static struct object *create_mapping( struct directory *root, const struct unicode_str *name,
467 unsigned int attr, mem_size_t size, int protect,
468 obj_handle_t handle, const struct security_descriptor *sd )
470 struct mapping *mapping;
477 if (!page_mask) init_page_size();
479 if (!(mapping = create_named_object_dir( root, name, attr, &mapping_ops )))
481 if (get_error() == STATUS_OBJECT_NAME_EXISTS)
482 return &mapping->obj; /* Nothing else to do */
484 if (sd) default_set_sd( &mapping->obj, sd, OWNER_SECURITY_INFORMATION|
485 GROUP_SECURITY_INFORMATION|
486 DACL_SECURITY_INFORMATION|
487 SACL_SECURITY_INFORMATION );
488 mapping->header_size = 0;
491 mapping->shared_file = NULL;
492 mapping->committed = NULL;
494 if (protect & VPROT_READ) access |= FILE_READ_DATA;
495 if (protect & VPROT_WRITE) access |= FILE_WRITE_DATA;
499 const unsigned int sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
500 unsigned int mapping_access = FILE_MAPPING_ACCESS;
502 if (!(protect & VPROT_COMMITTED))
504 set_error( STATUS_INVALID_PARAMETER );
507 if (!(file = get_file_obj( current->process, handle, access ))) goto error;
508 fd = get_obj_fd( (struct object *)file );
510 /* file sharing rules for mappings are different so we use magic the access rights */
511 if (protect & VPROT_IMAGE) mapping_access |= FILE_MAPPING_IMAGE;
512 else if (protect & VPROT_WRITE) mapping_access |= FILE_MAPPING_WRITE;
514 if (!(mapping->fd = get_fd_object_for_mapping( fd, mapping_access, sharing )))
516 mapping->fd = dup_fd_object( fd, mapping_access, sharing, FILE_SYNCHRONOUS_IO_NONALERT );
517 if (mapping->fd) set_fd_user( mapping->fd, &mapping_fd_ops, NULL );
519 release_object( file );
520 release_object( fd );
521 if (!mapping->fd) goto error;
523 if ((unix_fd = get_unix_fd( mapping->fd )) == -1) goto error;
524 if (protect & VPROT_IMAGE)
526 if (!get_image_params( mapping, unix_fd, protect )) goto error;
527 return &mapping->obj;
529 if (fstat( unix_fd, &st ) == -1)
536 if (!(size = st.st_size))
538 set_error( STATUS_MAPPED_FILE_SIZE_ZERO );
542 else if (st.st_size < size && !grow_file( unix_fd, size )) goto error;
544 else /* Anonymous mapping (no associated file) */
546 if (!size || (protect & VPROT_IMAGE))
548 set_error( STATUS_INVALID_PARAMETER );
551 if (!(protect & VPROT_COMMITTED))
553 if (!(mapping->committed = mem_alloc( offsetof(struct ranges, ranges[8]) ))) goto error;
554 mapping->committed->count = 0;
555 mapping->committed->max = 8;
557 if ((unix_fd = create_temp_file( size )) == -1) goto error;
558 if (!(mapping->fd = create_anonymous_fd( &mapping_fd_ops, unix_fd, &mapping->obj,
559 FILE_SYNCHRONOUS_IO_NONALERT ))) goto error;
560 allow_fd_caching( mapping->fd );
562 mapping->size = (size + page_mask) & ~((mem_size_t)page_mask);
563 mapping->protect = protect;
564 return &mapping->obj;
567 release_object( mapping );
571 struct mapping *get_mapping_obj( struct process *process, obj_handle_t handle, unsigned int access )
573 return (struct mapping *)get_handle_obj( process, handle, access, &mapping_ops );
576 /* open a new file handle to the file backing the mapping */
577 obj_handle_t open_mapping_file( struct process *process, struct mapping *mapping,
578 unsigned int access, unsigned int sharing )
581 struct file *file = create_file_for_fd_obj( mapping->fd, access, sharing );
584 handle = alloc_handle( process, file, access, 0 );
585 release_object( file );
589 struct mapping *grab_mapping_unless_removable( struct mapping *mapping )
591 if (is_fd_removable( mapping->fd )) return NULL;
592 return (struct mapping *)grab_object( mapping );
595 static void mapping_dump( struct object *obj, int verbose )
597 struct mapping *mapping = (struct mapping *)obj;
598 assert( obj->ops == &mapping_ops );
599 fprintf( stderr, "Mapping size=%08x%08x prot=%08x fd=%p header_size=%08x base=%08lx "
601 (unsigned int)(mapping->size >> 32), (unsigned int)mapping->size,
602 mapping->protect, mapping->fd, mapping->header_size,
603 (unsigned long)mapping->base, mapping->shared_file );
604 dump_object_name( &mapping->obj );
605 fputc( '\n', stderr );
608 static struct object_type *mapping_get_type( struct object *obj )
610 static const WCHAR name[] = {'S','e','c','t','i','o','n'};
611 static const struct unicode_str str = { name, sizeof(name) };
612 return get_object_type( &str );
615 static struct fd *mapping_get_fd( struct object *obj )
617 struct mapping *mapping = (struct mapping *)obj;
618 return (struct fd *)grab_object( mapping->fd );
621 static unsigned int mapping_map_access( struct object *obj, unsigned int access )
623 if (access & GENERIC_READ) access |= STANDARD_RIGHTS_READ | SECTION_QUERY | SECTION_MAP_READ;
624 if (access & GENERIC_WRITE) access |= STANDARD_RIGHTS_WRITE | SECTION_MAP_WRITE;
625 if (access & GENERIC_EXECUTE) access |= STANDARD_RIGHTS_EXECUTE | SECTION_MAP_EXECUTE;
626 if (access & GENERIC_ALL) access |= SECTION_ALL_ACCESS;
627 return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
630 static void mapping_destroy( struct object *obj )
632 struct mapping *mapping = (struct mapping *)obj;
633 assert( obj->ops == &mapping_ops );
634 if (mapping->fd) release_object( mapping->fd );
635 if (mapping->shared_file)
637 release_object( mapping->shared_file );
638 list_remove( &mapping->shared_entry );
640 free( mapping->committed );
643 static enum server_fd_type mapping_get_fd_type( struct fd *fd )
648 int get_page_size(void)
650 if (!page_mask) init_page_size();
651 return page_mask + 1;
654 /* create a file mapping */
655 DECL_HANDLER(create_mapping)
658 struct unicode_str name;
659 struct directory *root = NULL;
660 const struct object_attributes *objattr = get_req_data();
661 const struct security_descriptor *sd;
665 if (!objattr_is_valid( objattr, get_req_data_size() ))
668 sd = objattr->sd_len ? (const struct security_descriptor *)(objattr + 1) : NULL;
669 objattr_get_name( objattr, &name );
671 if (objattr->rootdir && !(root = get_directory_obj( current->process, objattr->rootdir, 0 )))
674 if ((obj = create_mapping( root, &name, req->attributes, req->size, req->protect, req->file_handle, sd )))
676 if (get_error() == STATUS_OBJECT_NAME_EXISTS)
677 reply->handle = alloc_handle( current->process, obj, req->access, req->attributes );
679 reply->handle = alloc_handle_no_access_check( current->process, obj, req->access, req->attributes );
680 release_object( obj );
683 if (root) release_object( root );
686 /* open a handle to a mapping */
687 DECL_HANDLER(open_mapping)
689 struct unicode_str name;
690 struct directory *root = NULL;
691 struct mapping *mapping;
693 get_req_unicode_str( &name );
694 if (req->rootdir && !(root = get_directory_obj( current->process, req->rootdir, 0 )))
697 if ((mapping = open_object_dir( root, &name, req->attributes, &mapping_ops )))
699 reply->handle = alloc_handle( current->process, &mapping->obj, req->access, req->attributes );
700 release_object( mapping );
703 if (root) release_object( root );
706 /* get a mapping information */
707 DECL_HANDLER(get_mapping_info)
709 struct mapping *mapping;
712 if ((mapping = get_mapping_obj( current->process, req->handle, req->access )))
714 reply->size = mapping->size;
715 reply->protect = mapping->protect;
716 reply->header_size = mapping->header_size;
717 reply->base = mapping->base;
718 reply->shared_file = 0;
719 if ((fd = get_obj_fd( &mapping->obj )))
721 if (!is_fd_removable(fd))
722 reply->mapping = alloc_handle( current->process, mapping, 0, 0 );
723 release_object( fd );
725 if (mapping->shared_file)
727 if (!(reply->shared_file = alloc_handle( current->process, mapping->shared_file,
728 GENERIC_READ|GENERIC_WRITE, 0 )))
730 if (reply->mapping) close_handle( current->process, reply->mapping );
733 release_object( mapping );
737 /* get a range of committed pages in a file mapping */
738 DECL_HANDLER(get_mapping_committed_range)
740 struct mapping *mapping;
742 if ((mapping = get_mapping_obj( current->process, req->handle, 0 )))
744 if (!(req->offset & page_mask) && req->offset < mapping->size)
745 reply->committed = find_committed_range( mapping, req->offset, &reply->size );
747 set_error( STATUS_INVALID_PARAMETER );
749 release_object( mapping );
753 /* add a range to the committed pages in a file mapping */
754 DECL_HANDLER(add_mapping_committed_range)
756 struct mapping *mapping;
758 if ((mapping = get_mapping_obj( current->process, req->handle, 0 )))
760 if (!(req->size & page_mask) &&
761 !(req->offset & page_mask) &&
762 req->offset < mapping->size &&
764 req->size <= mapping->size - req->offset)
765 add_committed_range( mapping, req->offset, req->offset + req->size );
767 set_error( STATUS_INVALID_PARAMETER );
769 release_object( mapping );