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);
111 static size_t page_mask;
113 #define ROUND_SIZE(size) (((size) + page_mask) & ~page_mask)
116 /* extend a file beyond the current end of file */
117 static int grow_file( int unix_fd, file_pos_t new_size )
119 static const char zero;
120 off_t size = new_size;
122 if (sizeof(new_size) > sizeof(size) && size != new_size)
124 set_error( STATUS_INVALID_PARAMETER );
127 /* extend the file one byte beyond the requested size and then truncate it */
128 /* this should work around ftruncate implementations that can't extend files */
129 if (pwrite( unix_fd, &zero, 1, size ) != -1)
131 ftruncate( unix_fd, size );
138 /* check if the current directory allows exec mappings */
139 static int check_current_dir_for_exec(void)
142 char tmpfn[] = "anonmap.XXXXXX";
143 void *ret = MAP_FAILED;
145 fd = mkstemps( tmpfn, 0 );
146 if (fd == -1) return 0;
147 if (grow_file( fd, 1 ))
149 ret = mmap( NULL, get_page_size(), PROT_READ | PROT_EXEC, MAP_PRIVATE, fd, 0 );
150 if (ret != MAP_FAILED) munmap( ret, get_page_size() );
154 return (ret != MAP_FAILED);
157 /* create a temp file for anonymous mappings */
158 static int create_temp_file( file_pos_t size )
160 static int temp_dir_fd = -1;
161 char tmpfn[] = "anonmap.XXXXXX";
164 if (temp_dir_fd == -1)
166 temp_dir_fd = server_dir_fd;
167 if (!check_current_dir_for_exec())
169 /* the server dir is noexec, try the config dir instead */
170 fchdir( config_dir_fd );
171 if (check_current_dir_for_exec())
172 temp_dir_fd = config_dir_fd;
173 else /* neither works, fall back to server dir */
174 fchdir( server_dir_fd );
177 else if (temp_dir_fd != server_dir_fd) fchdir( temp_dir_fd );
179 fd = mkstemps( tmpfn, 0 );
182 if (!grow_file( fd, size ))
189 else file_set_error();
191 if (temp_dir_fd != server_dir_fd) fchdir( server_dir_fd );
195 /* find the shared PE mapping for a given mapping */
196 static struct file *get_shared_file( struct mapping *mapping )
200 LIST_FOR_EACH_ENTRY( ptr, &shared_list, struct mapping, shared_entry )
201 if (is_same_file_fd( ptr->fd, mapping->fd ))
202 return (struct file *)grab_object( ptr->shared_file );
206 /* return the size of the memory mapping and file range of a given section */
207 static inline void get_section_sizes( const IMAGE_SECTION_HEADER *sec, size_t *map_size,
208 off_t *file_start, size_t *file_size )
210 static const unsigned int sector_align = 0x1ff;
212 if (!sec->Misc.VirtualSize) *map_size = ROUND_SIZE( sec->SizeOfRawData );
213 else *map_size = ROUND_SIZE( sec->Misc.VirtualSize );
215 *file_start = sec->PointerToRawData & ~sector_align;
216 *file_size = (sec->SizeOfRawData + (sec->PointerToRawData & sector_align) + sector_align) & ~sector_align;
217 if (*file_size > *map_size) *file_size = *map_size;
220 /* add a range to the committed list */
221 static void add_committed_range( struct mapping *mapping, file_pos_t start, file_pos_t end )
224 struct range *ranges;
226 if (!mapping->committed) return; /* everything committed already */
228 for (i = 0, ranges = mapping->committed->ranges; i < mapping->committed->count; i++)
230 if (ranges[i].start > end) break;
231 if (ranges[i].end < start) continue;
232 if (ranges[i].start > start) ranges[i].start = start; /* extend downwards */
233 if (ranges[i].end < end) /* extend upwards and maybe merge with next */
235 for (j = i + 1; j < mapping->committed->count; j++)
237 if (ranges[j].start > end) break;
238 if (ranges[j].end > end) end = ranges[j].end;
242 memmove( &ranges[i + 1], &ranges[j], (mapping->committed->count - j) * sizeof(*ranges) );
243 mapping->committed->count -= j - (i + 1);
250 /* now add a new range */
252 if (mapping->committed->count == mapping->committed->max)
254 unsigned int new_size = mapping->committed->max * 2;
255 struct ranges *new_ptr = realloc( mapping->committed, offsetof( struct ranges, ranges[new_size] ));
256 if (!new_ptr) return;
257 new_ptr->max = new_size;
258 ranges = new_ptr->ranges;
259 mapping->committed = new_ptr;
261 memmove( &ranges[i + 1], &ranges[i], (mapping->committed->count - i) * sizeof(*ranges) );
262 ranges[i].start = start;
264 mapping->committed->count++;
267 /* find the range containing start and return whether it's committed */
268 static int find_committed_range( struct mapping *mapping, file_pos_t start, mem_size_t *size )
271 struct range *ranges;
273 if (!mapping->committed) /* everything is committed */
275 *size = mapping->size - start;
278 for (i = 0, ranges = mapping->committed->ranges; i < mapping->committed->count; i++)
280 if (ranges[i].start > start)
282 *size = ranges[i].start - start;
285 if (ranges[i].end > start)
287 *size = ranges[i].end - start;
291 *size = mapping->size - start;
295 /* allocate and fill the temp file for a shared PE image mapping */
296 static int build_shared_mapping( struct mapping *mapping, int fd,
297 IMAGE_SECTION_HEADER *sec, unsigned int nb_sec )
300 mem_size_t total_size;
301 size_t file_size, map_size, max_size;
302 off_t shared_pos, read_pos, write_pos;
307 /* compute the total size of the shared mapping */
309 total_size = max_size = 0;
310 for (i = 0; i < nb_sec; i++)
312 if ((sec[i].Characteristics & IMAGE_SCN_MEM_SHARED) &&
313 (sec[i].Characteristics & IMAGE_SCN_MEM_WRITE))
315 get_section_sizes( &sec[i], &map_size, &read_pos, &file_size );
316 if (file_size > max_size) max_size = file_size;
317 total_size += map_size;
320 if (!total_size) return 1; /* nothing to do */
322 if ((mapping->shared_file = get_shared_file( mapping ))) return 1;
324 /* create a temp file for the mapping */
326 if ((shared_fd = create_temp_file( total_size )) == -1) return 0;
327 if (!(mapping->shared_file = create_file_for_fd( shared_fd, FILE_GENERIC_READ|FILE_GENERIC_WRITE, 0 )))
330 if (!(buffer = malloc( max_size ))) goto error;
332 /* copy the shared sections data into the temp file */
335 for (i = 0; i < nb_sec; i++)
337 if (!(sec[i].Characteristics & IMAGE_SCN_MEM_SHARED)) continue;
338 if (!(sec[i].Characteristics & IMAGE_SCN_MEM_WRITE)) continue;
339 get_section_sizes( &sec[i], &map_size, &read_pos, &file_size );
340 write_pos = shared_pos;
341 shared_pos += map_size;
342 if (!sec[i].PointerToRawData || !file_size) continue;
346 long res = pread( fd, buffer + file_size - toread, toread, read_pos );
347 if (!res && toread < 0x200) /* partial sector at EOF is not an error */
352 if (res <= 0) goto error;
356 if (pwrite( shared_fd, buffer, file_size, write_pos ) != file_size) goto error;
362 release_object( mapping->shared_file );
363 mapping->shared_file = NULL;
368 /* retrieve the mapping parameters for an executable (PE) image */
369 static int get_image_params( struct mapping *mapping, int unix_fd, int protect )
371 IMAGE_DOS_HEADER dos;
372 IMAGE_SECTION_HEADER *sec = NULL;
376 IMAGE_FILE_HEADER FileHeader;
379 IMAGE_OPTIONAL_HEADER32 hdr32;
380 IMAGE_OPTIONAL_HEADER64 hdr64;
386 /* load the headers */
388 if (pread( unix_fd, &dos, sizeof(dos), 0 ) != sizeof(dos)) goto error;
389 if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto error;
392 size = pread( unix_fd, &nt, sizeof(nt), pos );
393 if (size < sizeof(nt.Signature) + sizeof(nt.FileHeader)) goto error;
394 /* zero out Optional header in the case it's not present or partial */
395 if (size < sizeof(nt)) memset( (char *)&nt + size, 0, sizeof(nt) - size );
396 if (nt.Signature != IMAGE_NT_SIGNATURE) goto error;
398 switch (nt.opt.hdr32.Magic)
400 case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
401 mapping->size = ROUND_SIZE( nt.opt.hdr32.SizeOfImage );
402 mapping->base = nt.opt.hdr32.ImageBase;
403 mapping->header_size = nt.opt.hdr32.SizeOfHeaders;
405 case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
406 mapping->size = ROUND_SIZE( nt.opt.hdr64.SizeOfImage );
407 mapping->base = nt.opt.hdr64.ImageBase;
408 mapping->header_size = nt.opt.hdr64.SizeOfHeaders;
414 /* load the section headers */
416 pos += sizeof(nt.Signature) + sizeof(nt.FileHeader) + nt.FileHeader.SizeOfOptionalHeader;
417 size = sizeof(*sec) * nt.FileHeader.NumberOfSections;
418 if (pos + size > mapping->size) goto error;
419 if (pos + size > mapping->header_size) mapping->header_size = pos + size;
420 if (!(sec = malloc( size ))) goto error;
421 if (pread( unix_fd, sec, size, pos ) != size) goto error;
423 if (!build_shared_mapping( mapping, unix_fd, sec, nt.FileHeader.NumberOfSections )) goto error;
425 if (mapping->shared_file) list_add_head( &shared_list, &mapping->shared_entry );
427 mapping->protect = protect;
433 set_error( STATUS_INVALID_FILE_FOR_SECTION );
437 static struct object *create_mapping( struct directory *root, const struct unicode_str *name,
438 unsigned int attr, mem_size_t size, int protect,
439 obj_handle_t handle, const struct security_descriptor *sd )
441 struct mapping *mapping;
448 if (!page_mask) page_mask = sysconf( _SC_PAGESIZE ) - 1;
450 if (!(mapping = create_named_object_dir( root, name, attr, &mapping_ops )))
452 if (get_error() == STATUS_OBJECT_NAME_EXISTS)
453 return &mapping->obj; /* Nothing else to do */
455 if (sd) default_set_sd( &mapping->obj, sd, OWNER_SECURITY_INFORMATION|
456 GROUP_SECURITY_INFORMATION|
457 DACL_SECURITY_INFORMATION|
458 SACL_SECURITY_INFORMATION );
459 mapping->header_size = 0;
462 mapping->shared_file = NULL;
463 mapping->committed = NULL;
465 if (protect & VPROT_READ) access |= FILE_READ_DATA;
466 if (protect & VPROT_WRITE) access |= FILE_WRITE_DATA;
470 const unsigned int sharing = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE;
471 unsigned int mapping_access = FILE_MAPPING_ACCESS;
473 if (!(protect & VPROT_COMMITTED))
475 set_error( STATUS_INVALID_PARAMETER );
478 if (!(file = get_file_obj( current->process, handle, access ))) goto error;
479 fd = get_obj_fd( (struct object *)file );
481 /* file sharing rules for mappings are different so we use magic the access rights */
482 if (protect & VPROT_IMAGE) mapping_access |= FILE_MAPPING_IMAGE;
483 else if (protect & VPROT_WRITE) mapping_access |= FILE_MAPPING_WRITE;
485 if (!(mapping->fd = get_fd_object_for_mapping( fd, mapping_access, sharing )))
487 mapping->fd = dup_fd_object( fd, mapping_access, sharing, FILE_SYNCHRONOUS_IO_NONALERT );
488 if (mapping->fd) set_fd_user( mapping->fd, &mapping_fd_ops, NULL );
490 release_object( file );
491 release_object( fd );
492 if (!mapping->fd) goto error;
494 if ((unix_fd = get_unix_fd( mapping->fd )) == -1) goto error;
495 if (protect & VPROT_IMAGE)
497 if (!get_image_params( mapping, unix_fd, protect )) goto error;
498 return &mapping->obj;
500 if (fstat( unix_fd, &st ) == -1)
507 if (!(size = st.st_size))
509 set_error( STATUS_MAPPED_FILE_SIZE_ZERO );
513 else if (st.st_size < size && !grow_file( unix_fd, size )) goto error;
515 else /* Anonymous mapping (no associated file) */
517 if (!size || (protect & VPROT_IMAGE))
519 set_error( STATUS_INVALID_PARAMETER );
522 if (!(protect & VPROT_COMMITTED))
524 if (!(mapping->committed = mem_alloc( offsetof(struct ranges, ranges[8]) ))) goto error;
525 mapping->committed->count = 0;
526 mapping->committed->max = 8;
528 if ((unix_fd = create_temp_file( size )) == -1) goto error;
529 if (!(mapping->fd = create_anonymous_fd( &mapping_fd_ops, unix_fd, &mapping->obj,
530 FILE_SYNCHRONOUS_IO_NONALERT ))) goto error;
531 allow_fd_caching( mapping->fd );
533 mapping->size = (size + page_mask) & ~((mem_size_t)page_mask);
534 mapping->protect = protect;
535 return &mapping->obj;
538 release_object( mapping );
542 struct mapping *get_mapping_obj( struct process *process, obj_handle_t handle, unsigned int access )
544 return (struct mapping *)get_handle_obj( process, handle, access, &mapping_ops );
547 /* open a new file handle to the file backing the mapping */
548 obj_handle_t open_mapping_file( struct process *process, struct mapping *mapping,
549 unsigned int access, unsigned int sharing )
552 struct file *file = create_file_for_fd_obj( mapping->fd, access, sharing );
555 handle = alloc_handle( process, file, access, 0 );
556 release_object( file );
560 struct mapping *grab_mapping_unless_removable( struct mapping *mapping )
562 if (is_fd_removable( mapping->fd )) return NULL;
563 return (struct mapping *)grab_object( mapping );
566 static void mapping_dump( struct object *obj, int verbose )
568 struct mapping *mapping = (struct mapping *)obj;
569 assert( obj->ops == &mapping_ops );
570 fprintf( stderr, "Mapping size=%08x%08x prot=%08x fd=%p header_size=%08x base=%08lx "
572 (unsigned int)(mapping->size >> 32), (unsigned int)mapping->size,
573 mapping->protect, mapping->fd, mapping->header_size,
574 (unsigned long)mapping->base, mapping->shared_file );
575 dump_object_name( &mapping->obj );
576 fputc( '\n', stderr );
579 static struct object_type *mapping_get_type( struct object *obj )
581 static const WCHAR name[] = {'S','e','c','t','i','o','n'};
582 static const struct unicode_str str = { name, sizeof(name) };
583 return get_object_type( &str );
586 static struct fd *mapping_get_fd( struct object *obj )
588 struct mapping *mapping = (struct mapping *)obj;
589 return (struct fd *)grab_object( mapping->fd );
592 static unsigned int mapping_map_access( struct object *obj, unsigned int access )
594 if (access & GENERIC_READ) access |= STANDARD_RIGHTS_READ | SECTION_QUERY | SECTION_MAP_READ;
595 if (access & GENERIC_WRITE) access |= STANDARD_RIGHTS_WRITE | SECTION_MAP_WRITE;
596 if (access & GENERIC_EXECUTE) access |= STANDARD_RIGHTS_EXECUTE | SECTION_MAP_EXECUTE;
597 if (access & GENERIC_ALL) access |= SECTION_ALL_ACCESS;
598 return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
601 static void mapping_destroy( struct object *obj )
603 struct mapping *mapping = (struct mapping *)obj;
604 assert( obj->ops == &mapping_ops );
605 if (mapping->fd) release_object( mapping->fd );
606 if (mapping->shared_file)
608 release_object( mapping->shared_file );
609 list_remove( &mapping->shared_entry );
611 free( mapping->committed );
614 static enum server_fd_type mapping_get_fd_type( struct fd *fd )
619 int get_page_size(void)
621 if (!page_mask) page_mask = sysconf( _SC_PAGESIZE ) - 1;
622 return page_mask + 1;
625 /* create a file mapping */
626 DECL_HANDLER(create_mapping)
629 struct unicode_str name;
630 struct directory *root = NULL;
631 const struct object_attributes *objattr = get_req_data();
632 const struct security_descriptor *sd;
636 if (!objattr_is_valid( objattr, get_req_data_size() ))
639 sd = objattr->sd_len ? (const struct security_descriptor *)(objattr + 1) : NULL;
640 objattr_get_name( objattr, &name );
642 if (objattr->rootdir && !(root = get_directory_obj( current->process, objattr->rootdir, 0 )))
645 if ((obj = create_mapping( root, &name, req->attributes, req->size, req->protect, req->file_handle, sd )))
647 if (get_error() == STATUS_OBJECT_NAME_EXISTS)
648 reply->handle = alloc_handle( current->process, obj, req->access, req->attributes );
650 reply->handle = alloc_handle_no_access_check( current->process, obj, req->access, req->attributes );
651 release_object( obj );
654 if (root) release_object( root );
657 /* open a handle to a mapping */
658 DECL_HANDLER(open_mapping)
660 struct unicode_str name;
661 struct directory *root = NULL;
662 struct mapping *mapping;
664 get_req_unicode_str( &name );
665 if (req->rootdir && !(root = get_directory_obj( current->process, req->rootdir, 0 )))
668 if ((mapping = open_object_dir( root, &name, req->attributes, &mapping_ops )))
670 reply->handle = alloc_handle( current->process, &mapping->obj, req->access, req->attributes );
671 release_object( mapping );
674 if (root) release_object( root );
677 /* get a mapping information */
678 DECL_HANDLER(get_mapping_info)
680 struct mapping *mapping;
683 if ((mapping = get_mapping_obj( current->process, req->handle, req->access )))
685 reply->size = mapping->size;
686 reply->protect = mapping->protect;
687 reply->header_size = mapping->header_size;
688 reply->base = mapping->base;
689 reply->shared_file = 0;
690 if ((fd = get_obj_fd( &mapping->obj )))
692 if (!is_fd_removable(fd))
693 reply->mapping = alloc_handle( current->process, mapping, 0, 0 );
694 release_object( fd );
696 if (mapping->shared_file)
698 if (!(reply->shared_file = alloc_handle( current->process, mapping->shared_file,
699 GENERIC_READ|GENERIC_WRITE, 0 )))
701 if (reply->mapping) close_handle( current->process, reply->mapping );
704 release_object( mapping );
708 /* get a range of committed pages in a file mapping */
709 DECL_HANDLER(get_mapping_committed_range)
711 struct mapping *mapping;
713 if ((mapping = get_mapping_obj( current->process, req->handle, 0 )))
715 if (!(req->offset & page_mask) && req->offset < mapping->size)
716 reply->committed = find_committed_range( mapping, req->offset, &reply->size );
718 set_error( STATUS_INVALID_PARAMETER );
720 release_object( mapping );
724 /* add a range to the committed pages in a file mapping */
725 DECL_HANDLER(add_mapping_committed_range)
727 struct mapping *mapping;
729 if ((mapping = get_mapping_obj( current->process, req->handle, 0 )))
731 if (!(req->size & page_mask) &&
732 !(req->offset & page_mask) &&
733 req->offset < mapping->size &&
735 req->size <= mapping->size - req->offset)
736 add_committed_range( mapping, req->offset, req->offset + req->size );
738 set_error( STATUS_INVALID_PARAMETER );
740 release_object( mapping );