server: Use the file descriptor instead of the file object where possible in memory...
[wine] / server / mapping.c
1 /*
2  * Server-side file mapping management
3  *
4  * Copyright (C) 1999 Alexandre Julliard
5  *
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.
10  *
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.
15  *
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
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <assert.h>
25 #include <stdarg.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <sys/stat.h>
29 #include <unistd.h>
30
31 #include "ntstatus.h"
32 #define WIN32_NO_STATUS
33 #include "windef.h"
34 #include "winternl.h"
35
36 #include "file.h"
37 #include "handle.h"
38 #include "thread.h"
39 #include "request.h"
40 #include "security.h"
41
42 /* list of memory ranges, used to store committed info */
43 struct ranges
44 {
45     unsigned int count;
46     unsigned int max;
47     struct range
48     {
49         file_pos_t  start;
50         file_pos_t  end;
51     } ranges[1];
52 };
53
54 struct mapping
55 {
56     struct object   obj;             /* object header */
57     mem_size_t      size;            /* mapping size */
58     int             protect;         /* protection flags */
59     struct fd      *fd;              /* fd for mapped file */
60     struct file    *file;            /* file mapped */
61     int             header_size;     /* size of headers (for PE image mapping) */
62     client_ptr_t    base;            /* default base addr (for PE image mapping) */
63     struct ranges  *committed;       /* list of committed ranges in this mapping */
64     struct file    *shared_file;     /* temp file for shared PE mapping */
65     struct list     shared_entry;    /* entry in global shared PE mappings list */
66 };
67
68 static void mapping_dump( struct object *obj, int verbose );
69 static struct object_type *mapping_get_type( struct object *obj );
70 static struct fd *mapping_get_fd( struct object *obj );
71 static unsigned int mapping_map_access( struct object *obj, unsigned int access );
72 static void mapping_destroy( struct object *obj );
73
74 static const struct object_ops mapping_ops =
75 {
76     sizeof(struct mapping),      /* size */
77     mapping_dump,                /* dump */
78     mapping_get_type,            /* get_type */
79     no_add_queue,                /* add_queue */
80     NULL,                        /* remove_queue */
81     NULL,                        /* signaled */
82     NULL,                        /* satisfied */
83     no_signal,                   /* signal */
84     mapping_get_fd,              /* get_fd */
85     mapping_map_access,          /* map_access */
86     default_get_sd,              /* get_sd */
87     default_set_sd,              /* set_sd */
88     no_lookup_name,              /* lookup_name */
89     no_open_file,                /* open_file */
90     fd_close_handle,             /* close_handle */
91     mapping_destroy              /* destroy */
92 };
93
94 static struct list shared_list = LIST_INIT(shared_list);
95
96 #ifdef __i386__
97
98 /* These are always the same on an i386, and it will be faster this way */
99 # define page_mask  0xfff
100 # define page_shift 12
101 # define init_page_size() do { /* nothing */ } while(0)
102
103 #else  /* __i386__ */
104
105 static int page_shift, page_mask;
106
107 static void init_page_size(void)
108 {
109     int page_size;
110 # ifdef HAVE_GETPAGESIZE
111     page_size = getpagesize();
112 # else
113 #  ifdef __svr4__
114     page_size = sysconf(_SC_PAGESIZE);
115 #  else
116 #   error Cannot get the page size on this platform
117 #  endif
118 # endif
119     page_mask = page_size - 1;
120     /* Make sure we have a power of 2 */
121     assert( !(page_size & page_mask) );
122     page_shift = 0;
123     while ((1 << page_shift) != page_size) page_shift++;
124 }
125 #endif  /* __i386__ */
126
127 #define ROUND_SIZE(size)  (((size) + page_mask) & ~page_mask)
128
129
130 /* extend a file beyond the current end of file */
131 static int grow_file( int unix_fd, file_pos_t new_size )
132 {
133     static const char zero;
134     off_t size = new_size;
135
136     if (sizeof(new_size) > sizeof(size) && size != new_size)
137     {
138         set_error( STATUS_INVALID_PARAMETER );
139         return 0;
140     }
141     /* extend the file one byte beyond the requested size and then truncate it */
142     /* this should work around ftruncate implementations that can't extend files */
143     if (pwrite( unix_fd, &zero, 1, size ) != -1)
144     {
145         ftruncate( unix_fd, size );
146         return 1;
147     }
148     file_set_error();
149     return 0;
150 }
151
152 /* find the shared PE mapping for a given mapping */
153 static struct file *get_shared_file( struct mapping *mapping )
154 {
155     struct mapping *ptr;
156
157     LIST_FOR_EACH_ENTRY( ptr, &shared_list, struct mapping, shared_entry )
158         if (is_same_file_fd( ptr->fd, mapping->fd ))
159             return (struct file *)grab_object( ptr->shared_file );
160     return NULL;
161 }
162
163 /* return the size of the memory mapping and file range of a given section */
164 static inline void get_section_sizes( const IMAGE_SECTION_HEADER *sec, size_t *map_size,
165                                       off_t *file_start, size_t *file_size )
166 {
167     static const unsigned int sector_align = 0x1ff;
168
169     if (!sec->Misc.VirtualSize) *map_size = ROUND_SIZE( sec->SizeOfRawData );
170     else *map_size = ROUND_SIZE( sec->Misc.VirtualSize );
171
172     *file_start = sec->PointerToRawData & ~sector_align;
173     *file_size = (sec->SizeOfRawData + (sec->PointerToRawData & sector_align) + sector_align) & ~sector_align;
174     if (*file_size > *map_size) *file_size = *map_size;
175 }
176
177 /* add a range to the committed list */
178 static void add_committed_range( struct mapping *mapping, file_pos_t start, file_pos_t end )
179 {
180     unsigned int i, j;
181     struct range *ranges;
182
183     if (!mapping->committed) return;  /* everything committed already */
184
185     for (i = 0, ranges = mapping->committed->ranges; i < mapping->committed->count; i++)
186     {
187         if (ranges[i].start > end) break;
188         if (ranges[i].end < start) continue;
189         if (ranges[i].start > start) ranges[i].start = start;   /* extend downwards */
190         if (ranges[i].end < end)  /* extend upwards and maybe merge with next */
191         {
192             for (j = i + 1; j < mapping->committed->count; j++)
193             {
194                 if (ranges[j].start > end) break;
195                 if (ranges[j].end > end) end = ranges[j].end;
196             }
197             if (j > i + 1)
198             {
199                 memmove( &ranges[i + 1], &ranges[j], (mapping->committed->count - j) * sizeof(*ranges) );
200                 mapping->committed->count -= j - (i + 1);
201             }
202             ranges[i].end = end;
203         }
204         return;
205     }
206
207     /* now add a new range */
208
209     if (mapping->committed->count == mapping->committed->max)
210     {
211         unsigned int new_size = mapping->committed->max * 2;
212         struct ranges *new_ptr = realloc( mapping->committed, offsetof( struct ranges, ranges[new_size] ));
213         if (!new_ptr) return;
214         new_ptr->max = new_size;
215         ranges = new_ptr->ranges;
216         mapping->committed = new_ptr;
217     }
218     memmove( &ranges[i + 1], &ranges[i], (mapping->committed->count - i) * sizeof(*ranges) );
219     ranges[i].start = start;
220     ranges[i].end = end;
221     mapping->committed->count++;
222 }
223
224 /* find the range containing start and return whether it's committed */
225 static int find_committed_range( struct mapping *mapping, file_pos_t start, mem_size_t *size )
226 {
227     unsigned int i;
228     struct range *ranges;
229
230     if (!mapping->committed)  /* everything is committed */
231     {
232         *size = mapping->size - start;
233         return 1;
234     }
235     for (i = 0, ranges = mapping->committed->ranges; i < mapping->committed->count; i++)
236     {
237         if (ranges[i].start > start)
238         {
239             *size = ranges[i].start - start;
240             return 0;
241         }
242         if (ranges[i].end > start)
243         {
244             *size = ranges[i].end - start;
245             return 1;
246         }
247     }
248     *size = mapping->size - start;
249     return 0;
250 }
251
252 /* allocate and fill the temp file for a shared PE image mapping */
253 static int build_shared_mapping( struct mapping *mapping, int fd,
254                                  IMAGE_SECTION_HEADER *sec, unsigned int nb_sec )
255 {
256     unsigned int i;
257     mem_size_t total_size;
258     size_t file_size, map_size, max_size;
259     off_t shared_pos, read_pos, write_pos;
260     char *buffer = NULL;
261     int shared_fd;
262     long toread;
263
264     /* compute the total size of the shared mapping */
265
266     total_size = max_size = 0;
267     for (i = 0; i < nb_sec; i++)
268     {
269         if ((sec[i].Characteristics & IMAGE_SCN_MEM_SHARED) &&
270             (sec[i].Characteristics & IMAGE_SCN_MEM_WRITE))
271         {
272             get_section_sizes( &sec[i], &map_size, &read_pos, &file_size );
273             if (file_size > max_size) max_size = file_size;
274             total_size += map_size;
275         }
276     }
277     if (!total_size) return 1;  /* nothing to do */
278
279     if ((mapping->shared_file = get_shared_file( mapping ))) return 1;
280
281     /* create a temp file for the mapping */
282
283     if (!(mapping->shared_file = create_temp_file( FILE_GENERIC_READ|FILE_GENERIC_WRITE ))) return 0;
284     if ((shared_fd = get_file_unix_fd( mapping->shared_file )) == -1) goto error;
285     if (!grow_file( shared_fd, total_size )) goto error;
286
287     if (!(buffer = malloc( max_size ))) goto error;
288
289     /* copy the shared sections data into the temp file */
290
291     shared_pos = 0;
292     for (i = 0; i < nb_sec; i++)
293     {
294         if (!(sec[i].Characteristics & IMAGE_SCN_MEM_SHARED)) continue;
295         if (!(sec[i].Characteristics & IMAGE_SCN_MEM_WRITE)) continue;
296         get_section_sizes( &sec[i], &map_size, &read_pos, &file_size );
297         write_pos = shared_pos;
298         shared_pos += map_size;
299         if (!sec[i].PointerToRawData || !file_size) continue;
300         toread = file_size;
301         while (toread)
302         {
303             long res = pread( fd, buffer + file_size - toread, toread, read_pos );
304             if (!res && toread < 0x200)  /* partial sector at EOF is not an error */
305             {
306                 file_size -= toread;
307                 break;
308             }
309             if (res <= 0) goto error;
310             toread -= res;
311             read_pos += res;
312         }
313         if (pwrite( shared_fd, buffer, file_size, write_pos ) != file_size) goto error;
314     }
315     free( buffer );
316     return 1;
317
318  error:
319     release_object( mapping->shared_file );
320     mapping->shared_file = NULL;
321     free( buffer );
322     return 0;
323 }
324
325 /* retrieve the mapping parameters for an executable (PE) image */
326 static int get_image_params( struct mapping *mapping, int unix_fd )
327 {
328     IMAGE_DOS_HEADER dos;
329     IMAGE_SECTION_HEADER *sec = NULL;
330     struct
331     {
332         DWORD Signature;
333         IMAGE_FILE_HEADER FileHeader;
334         union
335         {
336             IMAGE_OPTIONAL_HEADER32 hdr32;
337             IMAGE_OPTIONAL_HEADER64 hdr64;
338         } opt;
339     } nt;
340     off_t pos;
341     int size;
342
343     /* load the headers */
344
345     if (pread( unix_fd, &dos, sizeof(dos), 0 ) != sizeof(dos)) goto error;
346     if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto error;
347     pos = dos.e_lfanew;
348
349     size = pread( unix_fd, &nt, sizeof(nt), pos );
350     if (size < sizeof(nt.Signature) + sizeof(nt.FileHeader)) goto error;
351     /* zero out Optional header in the case it's not present or partial */
352     if (size < sizeof(nt)) memset( (char *)&nt + size, 0, sizeof(nt) - size );
353     if (nt.Signature != IMAGE_NT_SIGNATURE) goto error;
354
355     switch (nt.opt.hdr32.Magic)
356     {
357     case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
358         mapping->size        = ROUND_SIZE( nt.opt.hdr32.SizeOfImage );
359         mapping->base        = nt.opt.hdr32.ImageBase;
360         mapping->header_size = nt.opt.hdr32.SizeOfHeaders;
361         break;
362     case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
363         mapping->size        = ROUND_SIZE( nt.opt.hdr64.SizeOfImage );
364         mapping->base        = nt.opt.hdr64.ImageBase;
365         mapping->header_size = nt.opt.hdr64.SizeOfHeaders;
366         break;
367     default:
368         goto error;
369     }
370
371     /* load the section headers */
372
373     pos += sizeof(nt.Signature) + sizeof(nt.FileHeader) + nt.FileHeader.SizeOfOptionalHeader;
374     size = sizeof(*sec) * nt.FileHeader.NumberOfSections;
375     if (pos + size > mapping->size) goto error;
376     if (pos + size > mapping->header_size) mapping->header_size = pos + size;
377     if (!(sec = malloc( size ))) goto error;
378     if (pread( unix_fd, sec, size, pos ) != size) goto error;
379
380     if (!build_shared_mapping( mapping, unix_fd, sec, nt.FileHeader.NumberOfSections )) goto error;
381
382     if (mapping->shared_file) list_add_head( &shared_list, &mapping->shared_entry );
383
384     mapping->protect = VPROT_IMAGE;
385     free( sec );
386     return 1;
387
388  error:
389     free( sec );
390     set_error( STATUS_INVALID_FILE_FOR_SECTION );
391     return 0;
392 }
393
394 static struct object *create_mapping( struct directory *root, const struct unicode_str *name,
395                                       unsigned int attr, mem_size_t size, int protect,
396                                       obj_handle_t handle, const struct security_descriptor *sd )
397 {
398     struct mapping *mapping;
399     int access = 0;
400     int unix_fd;
401     struct stat st;
402
403     if (!page_mask) init_page_size();
404
405     if (!(mapping = create_named_object_dir( root, name, attr, &mapping_ops )))
406         return NULL;
407     if (get_error() == STATUS_OBJECT_NAME_EXISTS)
408         return &mapping->obj;  /* Nothing else to do */
409
410     if (sd) default_set_sd( &mapping->obj, sd, OWNER_SECURITY_INFORMATION|
411                                                GROUP_SECURITY_INFORMATION|
412                                                DACL_SECURITY_INFORMATION|
413                                                SACL_SECURITY_INFORMATION );
414     mapping->header_size = 0;
415     mapping->base        = 0;
416     mapping->fd          = NULL;
417     mapping->file        = NULL;
418     mapping->shared_file = NULL;
419     mapping->committed   = NULL;
420
421     if (protect & VPROT_READ) access |= FILE_READ_DATA;
422     if (protect & VPROT_WRITE) access |= FILE_WRITE_DATA;
423
424     if (handle)
425     {
426         if (!(protect & VPROT_COMMITTED))
427         {
428             set_error( STATUS_INVALID_PARAMETER );
429             goto error;
430         }
431         if (!(mapping->file = get_file_obj( current->process, handle, access ))) goto error;
432         mapping->fd = get_obj_fd( (struct object *)mapping->file );
433         if ((unix_fd = get_unix_fd( mapping->fd )) == -1) goto error;
434         if (protect & VPROT_IMAGE)
435         {
436             if (!get_image_params( mapping, unix_fd )) goto error;
437             return &mapping->obj;
438         }
439         if (fstat( unix_fd, &st ) == -1)
440         {
441             file_set_error();
442             goto error;
443         }
444         if (!size)
445         {
446             if (!(size = st.st_size))
447             {
448                 set_error( STATUS_MAPPED_FILE_SIZE_ZERO );
449                 goto error;
450             }
451         }
452         else if (st.st_size < size && !grow_file( unix_fd, size )) goto error;
453     }
454     else  /* Anonymous mapping (no associated file) */
455     {
456         if (!size || (protect & VPROT_IMAGE))
457         {
458             set_error( STATUS_INVALID_PARAMETER );
459             goto error;
460         }
461         if (!(protect & VPROT_COMMITTED))
462         {
463             if (!(mapping->committed = mem_alloc( offsetof(struct ranges, ranges[8]) ))) goto error;
464             mapping->committed->count = 0;
465             mapping->committed->max   = 8;
466         }
467         if (!(mapping->file = create_temp_file( access ))) goto error;
468         mapping->fd = get_obj_fd( (struct object *)mapping->file );
469         if ((unix_fd = get_unix_fd( mapping->fd )) == -1) goto error;
470         if (!grow_file( unix_fd, size )) goto error;
471     }
472     mapping->size    = (size + page_mask) & ~((mem_size_t)page_mask);
473     mapping->protect = protect;
474     return &mapping->obj;
475
476  error:
477     release_object( mapping );
478     return NULL;
479 }
480
481 static void mapping_dump( struct object *obj, int verbose )
482 {
483     struct mapping *mapping = (struct mapping *)obj;
484     assert( obj->ops == &mapping_ops );
485     fprintf( stderr, "Mapping size=%08x%08x prot=%08x fd=%p header_size=%08x base=%08lx "
486              "shared_file=%p ",
487              (unsigned int)(mapping->size >> 32), (unsigned int)mapping->size,
488              mapping->protect, mapping->fd, mapping->header_size,
489              (unsigned long)mapping->base, mapping->shared_file );
490     dump_object_name( &mapping->obj );
491     fputc( '\n', stderr );
492 }
493
494 static struct object_type *mapping_get_type( struct object *obj )
495 {
496     static const WCHAR name[] = {'S','e','c','t','i','o','n'};
497     static const struct unicode_str str = { name, sizeof(name) };
498     return get_object_type( &str );
499 }
500
501 static struct fd *mapping_get_fd( struct object *obj )
502 {
503     struct mapping *mapping = (struct mapping *)obj;
504     return (struct fd *)grab_object( mapping->fd );
505 }
506
507 static unsigned int mapping_map_access( struct object *obj, unsigned int access )
508 {
509     if (access & GENERIC_READ)    access |= STANDARD_RIGHTS_READ | SECTION_QUERY | SECTION_MAP_READ;
510     if (access & GENERIC_WRITE)   access |= STANDARD_RIGHTS_WRITE | SECTION_MAP_WRITE;
511     if (access & GENERIC_EXECUTE) access |= STANDARD_RIGHTS_EXECUTE | SECTION_MAP_EXECUTE;
512     if (access & GENERIC_ALL)     access |= SECTION_ALL_ACCESS;
513     return access & ~(GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL);
514 }
515
516 static void mapping_destroy( struct object *obj )
517 {
518     struct mapping *mapping = (struct mapping *)obj;
519     assert( obj->ops == &mapping_ops );
520     if (mapping->file) release_object( mapping->file );
521     if (mapping->fd) release_object( mapping->fd );
522     if (mapping->shared_file)
523     {
524         release_object( mapping->shared_file );
525         list_remove( &mapping->shared_entry );
526     }
527     free( mapping->committed );
528 }
529
530 int get_page_size(void)
531 {
532     if (!page_mask) init_page_size();
533     return page_mask + 1;
534 }
535
536 /* create a file mapping */
537 DECL_HANDLER(create_mapping)
538 {
539     struct object *obj;
540     struct unicode_str name;
541     struct directory *root = NULL;
542     const struct object_attributes *objattr = get_req_data();
543     const struct security_descriptor *sd;
544
545     reply->handle = 0;
546
547     if (!objattr_is_valid( objattr, get_req_data_size() ))
548         return;
549
550     sd = objattr->sd_len ? (const struct security_descriptor *)(objattr + 1) : NULL;
551     objattr_get_name( objattr, &name );
552
553     if (objattr->rootdir && !(root = get_directory_obj( current->process, objattr->rootdir, 0 )))
554         return;
555
556     if ((obj = create_mapping( root, &name, req->attributes, req->size, req->protect, req->file_handle, sd )))
557     {
558         if (get_error() == STATUS_OBJECT_NAME_EXISTS)
559             reply->handle = alloc_handle( current->process, obj, req->access, req->attributes );
560         else
561             reply->handle = alloc_handle_no_access_check( current->process, obj, req->access, req->attributes );
562         release_object( obj );
563     }
564
565     if (root) release_object( root );
566 }
567
568 /* open a handle to a mapping */
569 DECL_HANDLER(open_mapping)
570 {
571     struct unicode_str name;
572     struct directory *root = NULL;
573     struct mapping *mapping;
574
575     get_req_unicode_str( &name );
576     if (req->rootdir && !(root = get_directory_obj( current->process, req->rootdir, 0 )))
577         return;
578
579     if ((mapping = open_object_dir( root, &name, req->attributes, &mapping_ops )))
580     {
581         reply->handle = alloc_handle( current->process, &mapping->obj, req->access, req->attributes );
582         release_object( mapping );
583     }
584
585     if (root) release_object( root );
586 }
587
588 /* get a mapping information */
589 DECL_HANDLER(get_mapping_info)
590 {
591     struct mapping *mapping;
592     struct fd *fd;
593
594     if ((mapping = (struct mapping *)get_handle_obj( current->process, req->handle,
595                                                      req->access, &mapping_ops )))
596     {
597         reply->size        = mapping->size;
598         reply->protect     = mapping->protect;
599         reply->header_size = mapping->header_size;
600         reply->base        = mapping->base;
601         reply->shared_file = 0;
602         if ((fd = get_obj_fd( &mapping->obj )))
603         {
604             if (!is_fd_removable(fd))
605                 reply->mapping = alloc_handle( current->process, mapping, 0, 0 );
606             release_object( fd );
607         }
608         if (mapping->shared_file)
609         {
610             if (!(reply->shared_file = alloc_handle( current->process, mapping->shared_file,
611                                                      GENERIC_READ|GENERIC_WRITE, 0 )))
612             {
613                 if (reply->mapping) close_handle( current->process, reply->mapping );
614             }
615         }
616         release_object( mapping );
617     }
618 }
619
620 /* get a range of committed pages in a file mapping */
621 DECL_HANDLER(get_mapping_committed_range)
622 {
623     struct mapping *mapping;
624
625     if ((mapping = (struct mapping *)get_handle_obj( current->process, req->handle, 0, &mapping_ops )))
626     {
627         if (!(req->offset & page_mask) && req->offset < mapping->size)
628             reply->committed = find_committed_range( mapping, req->offset, &reply->size );
629         else
630             set_error( STATUS_INVALID_PARAMETER );
631
632         release_object( mapping );
633     }
634 }
635
636 /* add a range to the committed pages in a file mapping */
637 DECL_HANDLER(add_mapping_committed_range)
638 {
639     struct mapping *mapping;
640
641     if ((mapping = (struct mapping *)get_handle_obj( current->process, req->handle, 0, &mapping_ops )))
642     {
643         if (!(req->size & page_mask) &&
644             !(req->offset & page_mask) &&
645             req->offset < mapping->size &&
646             req->size > 0 &&
647             req->size <= mapping->size - req->offset)
648             add_committed_range( mapping, req->offset, req->offset + req->size );
649         else
650             set_error( STATUS_INVALID_PARAMETER );
651
652         release_object( mapping );
653     }
654 }