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 )
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 = VPROT_IMAGE;
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 unsigned int mapping_access = FILE_MAPPING_ACCESS;
501 if (!(protect & VPROT_COMMITTED))
503 set_error( STATUS_INVALID_PARAMETER );
506 if (!(file = get_file_obj( current->process, handle, access ))) goto error;
507 fd = get_obj_fd( (struct object *)file );
509 /* file sharing rules for mappings are different so we use magic the access rights */
510 if (protect & VPROT_IMAGE) mapping_access |= FILE_MAPPING_IMAGE;
511 else if (protect & VPROT_WRITE) mapping_access |= FILE_MAPPING_WRITE;
512 mapping->fd = dup_fd_object( fd, mapping_access,
513 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
514 FILE_SYNCHRONOUS_IO_NONALERT );
515 release_object( file );
516 release_object( fd );
517 if (!mapping->fd) goto error;
519 set_fd_user( mapping->fd, &mapping_fd_ops, &mapping->obj );
520 if ((unix_fd = get_unix_fd( mapping->fd )) == -1) goto error;
521 if (protect & VPROT_IMAGE)
523 if (!get_image_params( mapping, unix_fd )) goto error;
524 return &mapping->obj;
526 if (fstat( unix_fd, &st ) == -1)
533 if (!(size = st.st_size))
535 set_error( STATUS_MAPPED_FILE_SIZE_ZERO );
539 else if (st.st_size < size && !grow_file( unix_fd, size )) goto error;
541 else /* Anonymous mapping (no associated file) */
543 if (!size || (protect & VPROT_IMAGE))
545 set_error( STATUS_INVALID_PARAMETER );
548 if (!(protect & VPROT_COMMITTED))
550 if (!(mapping->committed = mem_alloc( offsetof(struct ranges, ranges[8]) ))) goto error;
551 mapping->committed->count = 0;
552 mapping->committed->max = 8;
554 if ((unix_fd = create_temp_file( size )) == -1) goto error;
555 if (!(mapping->fd = create_anonymous_fd( &mapping_fd_ops, unix_fd, &mapping->obj,
556 FILE_SYNCHRONOUS_IO_NONALERT ))) goto error;
557 allow_fd_caching( mapping->fd );
559 mapping->size = (size + page_mask) & ~((mem_size_t)page_mask);
560 mapping->protect = protect;
561 return &mapping->obj;
564 release_object( mapping );
568 static void mapping_dump( struct object *obj, int verbose )
570 struct mapping *mapping = (struct mapping *)obj;
571 assert( obj->ops == &mapping_ops );
572 fprintf( stderr, "Mapping size=%08x%08x prot=%08x fd=%p header_size=%08x base=%08lx "
574 (unsigned int)(mapping->size >> 32), (unsigned int)mapping->size,
575 mapping->protect, mapping->fd, mapping->header_size,
576 (unsigned long)mapping->base, mapping->shared_file );
577 dump_object_name( &mapping->obj );
578 fputc( '\n', stderr );
581 static struct object_type *mapping_get_type( struct object *obj )
583 static const WCHAR name[] = {'S','e','c','t','i','o','n'};
584 static const struct unicode_str str = { name, sizeof(name) };
585 return get_object_type( &str );
588 static struct fd *mapping_get_fd( struct object *obj )
590 struct mapping *mapping = (struct mapping *)obj;
591 return (struct fd *)grab_object( mapping->fd );
594 static unsigned int mapping_map_access( struct object *obj, unsigned int access )
596 if (access & GENERIC_READ) access |= STANDARD_RIGHTS_READ | SECTION_QUERY | SECTION_MAP_READ;
597 if (access & GENERIC_WRITE) access |= STANDARD_RIGHTS_WRITE | SECTION_MAP_WRITE;
598 if (access & GENERIC_EXECUTE) access |= STANDARD_RIGHTS_EXECUTE | SECTION_MAP_EXECUTE;
599 if (access & GENERIC_ALL) access |= SECTION_ALL_ACCESS;
600 return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
603 static void mapping_destroy( struct object *obj )
605 struct mapping *mapping = (struct mapping *)obj;
606 assert( obj->ops == &mapping_ops );
607 if (mapping->fd) release_object( mapping->fd );
608 if (mapping->shared_file)
610 release_object( mapping->shared_file );
611 list_remove( &mapping->shared_entry );
613 free( mapping->committed );
616 static enum server_fd_type mapping_get_fd_type( struct fd *fd )
621 int get_page_size(void)
623 if (!page_mask) init_page_size();
624 return page_mask + 1;
627 /* create a file mapping */
628 DECL_HANDLER(create_mapping)
631 struct unicode_str name;
632 struct directory *root = NULL;
633 const struct object_attributes *objattr = get_req_data();
634 const struct security_descriptor *sd;
638 if (!objattr_is_valid( objattr, get_req_data_size() ))
641 sd = objattr->sd_len ? (const struct security_descriptor *)(objattr + 1) : NULL;
642 objattr_get_name( objattr, &name );
644 if (objattr->rootdir && !(root = get_directory_obj( current->process, objattr->rootdir, 0 )))
647 if ((obj = create_mapping( root, &name, req->attributes, req->size, req->protect, req->file_handle, sd )))
649 if (get_error() == STATUS_OBJECT_NAME_EXISTS)
650 reply->handle = alloc_handle( current->process, obj, req->access, req->attributes );
652 reply->handle = alloc_handle_no_access_check( current->process, obj, req->access, req->attributes );
653 release_object( obj );
656 if (root) release_object( root );
659 /* open a handle to a mapping */
660 DECL_HANDLER(open_mapping)
662 struct unicode_str name;
663 struct directory *root = NULL;
664 struct mapping *mapping;
666 get_req_unicode_str( &name );
667 if (req->rootdir && !(root = get_directory_obj( current->process, req->rootdir, 0 )))
670 if ((mapping = open_object_dir( root, &name, req->attributes, &mapping_ops )))
672 reply->handle = alloc_handle( current->process, &mapping->obj, req->access, req->attributes );
673 release_object( mapping );
676 if (root) release_object( root );
679 /* get a mapping information */
680 DECL_HANDLER(get_mapping_info)
682 struct mapping *mapping;
685 if ((mapping = (struct mapping *)get_handle_obj( current->process, req->handle,
686 req->access, &mapping_ops )))
688 reply->size = mapping->size;
689 reply->protect = mapping->protect;
690 reply->header_size = mapping->header_size;
691 reply->base = mapping->base;
692 reply->shared_file = 0;
693 if ((fd = get_obj_fd( &mapping->obj )))
695 if (!is_fd_removable(fd))
696 reply->mapping = alloc_handle( current->process, mapping, 0, 0 );
697 release_object( fd );
699 if (mapping->shared_file)
701 if (!(reply->shared_file = alloc_handle( current->process, mapping->shared_file,
702 GENERIC_READ|GENERIC_WRITE, 0 )))
704 if (reply->mapping) close_handle( current->process, reply->mapping );
707 release_object( mapping );
711 /* get a range of committed pages in a file mapping */
712 DECL_HANDLER(get_mapping_committed_range)
714 struct mapping *mapping;
716 if ((mapping = (struct mapping *)get_handle_obj( current->process, req->handle, 0, &mapping_ops )))
718 if (!(req->offset & page_mask) && req->offset < mapping->size)
719 reply->committed = find_committed_range( mapping, req->offset, &reply->size );
721 set_error( STATUS_INVALID_PARAMETER );
723 release_object( mapping );
727 /* add a range to the committed pages in a file mapping */
728 DECL_HANDLER(add_mapping_committed_range)
730 struct mapping *mapping;
732 if ((mapping = (struct mapping *)get_handle_obj( current->process, req->handle, 0, &mapping_ops )))
734 if (!(req->size & page_mask) &&
735 !(req->offset & page_mask) &&
736 req->offset < mapping->size &&
738 req->size <= mapping->size - req->offset)
739 add_committed_range( mapping, req->offset, req->offset + req->size );
741 set_error( STATUS_INVALID_PARAMETER );
743 release_object( mapping );