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