Avoid dup'ing file descriptors when not necessary.
[wine] / server / mapping.c
1 /*
2  * Server-side file mapping management
3  *
4  * Copyright (C) 1999 Alexandre Julliard
5  */
6
7 #include <assert.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <unistd.h>
11
12 #include "config.h"
13 #include "winnt.h"
14 #include "winbase.h"
15
16 #include "handle.h"
17 #include "thread.h"
18 #include "request.h"
19
20 struct mapping
21 {
22     struct object  obj;             /* object header */
23     int            size_high;       /* mapping size */
24     int            size_low;        /* mapping size */
25     int            protect;         /* protection flags */
26     struct file   *file;            /* file mapped */
27     int            header_size;     /* size of headers (for PE image mapping) */
28     void          *base;            /* default base addr (for PE image mapping) */
29     struct file   *shared_file;     /* temp file for shared PE mapping */
30     int            shared_size;     /* shared mapping total size */
31 };
32
33 static int mapping_get_fd( struct object *obj );
34 static void mapping_dump( struct object *obj, int verbose );
35 static void mapping_destroy( struct object *obj );
36
37 static const struct object_ops mapping_ops =
38 {
39     sizeof(struct mapping),      /* size */
40     mapping_dump,                /* dump */
41     no_add_queue,                /* add_queue */
42     NULL,                        /* remove_queue */
43     NULL,                        /* signaled */
44     NULL,                        /* satisfied */
45     NULL,                        /* get_poll_events */
46     NULL,                        /* poll_event */
47     mapping_get_fd,              /* get_fd */
48     no_flush,                    /* flush */
49     no_get_file_info,            /* get_file_info */
50     mapping_destroy              /* destroy */
51 };
52
53 #ifdef __i386__
54
55 /* These are always the same on an i386, and it will be faster this way */
56 # define page_mask  0xfff
57 # define page_shift 12
58 # define init_page_size() do { /* nothing */ } while(0)
59
60 #else  /* __i386__ */
61
62 static int page_shift, page_mask;
63
64 static void init_page_size(void)
65 {
66     int page_size;
67 # ifdef HAVE_GETPAGESIZE
68     page_size = getpagesize();
69 # else
70 #  ifdef __svr4__
71     page_size = sysconf(_SC_PAGESIZE);
72 #  else
73 #   error Cannot get the page size on this platform
74 #  endif
75 # endif
76     page_mask = page_size - 1;
77     /* Make sure we have a power of 2 */
78     assert( !(page_size & page_mask) );
79     page_shift = 0;
80     while ((1 << page_shift) != page_size) page_shift++;
81 }
82 #endif  /* __i386__ */
83
84 #define ROUND_ADDR(addr) \
85    ((int)(addr) & ~page_mask)
86
87 #define ROUND_SIZE(addr,size) \
88    (((int)(size) + ((int)(addr) & page_mask) + page_mask) & ~page_mask)
89
90 /* get the fd to use for mmaping a file */
91 inline static int get_mmap_fd( struct file *file )
92 {
93     struct object *obj;
94     if (!(obj = (struct object *)file))
95     {
96         set_error( STATUS_INVALID_HANDLE );
97         return -1;
98     }
99     return obj->ops->get_fd( obj );
100 }
101
102 /* allocate and fill the temp file for a shared PE image mapping */
103 static int build_shared_mapping( struct mapping *mapping, int fd,
104                                  IMAGE_SECTION_HEADER *sec, int nb_sec )
105 {
106     int i, max_size, total_size, pos;
107     char *buffer = NULL;
108     int shared_fd;
109     long toread;
110
111     /* compute the total size of the shared mapping */
112
113     total_size = max_size = 0;
114     for (i = 0; i < nb_sec; i++)
115     {
116         if ((sec[i].Characteristics & IMAGE_SCN_MEM_SHARED) &&
117             (sec[i].Characteristics & IMAGE_SCN_MEM_WRITE))
118         {
119             int size = ROUND_SIZE( 0, sec[i].Misc.VirtualSize );
120             if (size > max_size) max_size = size;
121             total_size += size;
122         }
123     }
124     if (!(mapping->shared_size = total_size)) return 1;  /* nothing to do */
125
126     /* create a temp file for the mapping */
127
128     if (!(mapping->shared_file = create_temp_file( GENERIC_READ|GENERIC_WRITE ))) goto error;
129     if (!grow_file( mapping->shared_file, 0, total_size )) goto error;
130     if ((shared_fd = get_mmap_fd( mapping->shared_file )) == -1) goto error;
131
132     if (!(buffer = malloc( max_size ))) goto error;
133
134     /* copy the shared sections data into the temp file */
135
136     for (i = pos = 0; i < nb_sec; i++)
137     {
138         if (!(sec[i].Characteristics & IMAGE_SCN_MEM_SHARED)) continue;
139         if (!(sec[i].Characteristics & IMAGE_SCN_MEM_WRITE)) continue;
140         if (lseek( shared_fd, pos, SEEK_SET ) != pos) goto error;
141         pos += ROUND_SIZE( 0, sec[i].Misc.VirtualSize );
142         if (sec[i].Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA) continue;
143         if (!sec[i].PointerToRawData || !sec[i].SizeOfRawData) continue;
144         if (lseek( fd, sec[i].PointerToRawData, SEEK_SET ) != sec[i].PointerToRawData) goto error;
145         toread = sec[i].SizeOfRawData;
146         while (toread)
147         {
148             long res = read( fd, buffer + sec[i].SizeOfRawData - toread, toread );
149             if (res <= 0) goto error;
150             toread -= res;
151         }
152         if (write( shared_fd, buffer, sec[i].SizeOfRawData ) != sec[i].SizeOfRawData) goto error;
153     }
154     free( buffer );
155     return 1;
156
157  error:
158     if (buffer) free( buffer );
159     return 0;
160 }
161
162 /* retrieve the mapping parameters for an executable (PE) image */
163 static int get_image_params( struct mapping *mapping )
164 {
165     IMAGE_DOS_HEADER dos;
166     IMAGE_NT_HEADERS nt;
167     IMAGE_SECTION_HEADER *sec = NULL;
168     int fd, filepos, size;
169
170     /* load the headers */
171
172     if ((fd = get_mmap_fd( mapping->file )) == -1) return 0;
173     filepos = lseek( fd, 0, SEEK_SET );
174     if (read( fd, &dos, sizeof(dos) ) != sizeof(dos)) goto error;
175     if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto error;
176     if (lseek( fd, dos.e_lfanew, SEEK_SET ) == -1) goto error;
177     if (read( fd, &nt, sizeof(nt) ) != sizeof(nt)) goto error;
178     if (nt.Signature != IMAGE_NT_SIGNATURE) goto error;
179
180     /* load the section headers */
181
182     size = sizeof(*sec) * nt.FileHeader.NumberOfSections;
183     if (!(sec = malloc( size ))) goto error;
184     if (read( fd, sec, size ) != size) goto error;
185
186     if (!build_shared_mapping( mapping, fd, sec, nt.FileHeader.NumberOfSections )) goto error;
187
188     mapping->size_low    = ROUND_SIZE( 0, nt.OptionalHeader.SizeOfImage );
189     mapping->size_high   = 0;
190     mapping->base        = (void *)nt.OptionalHeader.ImageBase;
191     mapping->header_size = ROUND_SIZE( mapping->base, nt.OptionalHeader.SizeOfHeaders );
192     mapping->protect     = VPROT_IMAGE;
193
194     /* sanity check */
195     if (mapping->header_size > mapping->size_low) goto error;
196
197     lseek( fd, filepos, SEEK_SET );
198     free( sec );
199     return 1;
200
201  error:
202     lseek( fd, filepos, SEEK_SET );
203     if (sec) free( sec );
204     set_error( STATUS_INVALID_FILE_FOR_SECTION );
205     return 0;
206 }
207
208
209 static struct object *create_mapping( int size_high, int size_low, int protect,
210                                       int handle, const WCHAR *name, size_t len )
211 {
212     struct mapping *mapping;
213     int access = 0;
214
215     if (!page_mask) init_page_size();
216
217     if (!(mapping = create_named_object( &mapping_ops, name, len )))
218         return NULL;
219     if (get_error() == STATUS_OBJECT_NAME_COLLISION)
220         return &mapping->obj;  /* Nothing else to do */
221
222     mapping->header_size = 0;
223     mapping->base        = NULL;
224     mapping->shared_file = NULL;
225     mapping->shared_size = 0;
226
227     if (protect & VPROT_READ) access |= GENERIC_READ;
228     if (protect & VPROT_WRITE) access |= GENERIC_WRITE;
229
230     if (handle != -1)
231     {
232         if (!(mapping->file = get_file_obj( current->process, handle, access ))) goto error;
233         if (protect & VPROT_IMAGE)
234         {
235             if (!get_image_params( mapping )) goto error;
236             return &mapping->obj;
237         }
238         if (!size_high && !size_low)
239         {
240             struct get_file_info_request req;
241             struct object *obj = (struct object *)mapping->file;
242             obj->ops->get_file_info( obj, &req );
243             size_high = req.size_high;
244             size_low  = ROUND_SIZE( 0, req.size_low );
245         }
246         else if (!grow_file( mapping->file, size_high, size_low )) goto error;
247     }
248     else  /* Anonymous mapping (no associated file) */
249     {
250         if ((!size_high && !size_low) || (protect & VPROT_IMAGE))
251         {
252             set_error( STATUS_INVALID_PARAMETER );
253             mapping->file = NULL;
254             goto error;
255         }
256         if (!(mapping->file = create_temp_file( access ))) goto error;
257         if (!grow_file( mapping->file, size_high, size_low )) goto error;
258     }
259     mapping->size_high = size_high;
260     mapping->size_low  = ROUND_SIZE( 0, size_low );
261     mapping->protect   = protect;
262     return &mapping->obj;
263
264  error:
265     release_object( mapping );
266     return NULL;
267 }
268
269 static void mapping_dump( struct object *obj, int verbose )
270 {
271     struct mapping *mapping = (struct mapping *)obj;
272     assert( obj->ops == &mapping_ops );
273     fprintf( stderr, "Mapping size=%08x%08x prot=%08x file=%p header_size=%08x base=%p "
274              "shared_file=%p shared_size=%08x ",
275              mapping->size_high, mapping->size_low, mapping->protect, mapping->file,
276              mapping->header_size, mapping->base, mapping->shared_file, mapping->shared_size );
277     dump_object_name( &mapping->obj );
278     fputc( '\n', stderr );
279 }
280
281 static int mapping_get_fd( struct object *obj )
282 {
283     struct mapping *mapping = (struct mapping *)obj;
284     assert( obj->ops == &mapping_ops );
285     return get_mmap_fd( mapping->file );
286 }
287
288 static void mapping_destroy( struct object *obj )
289 {
290     struct mapping *mapping = (struct mapping *)obj;
291     assert( obj->ops == &mapping_ops );
292     if (mapping->file) release_object( mapping->file );
293     if (mapping->shared_file) release_object( mapping->shared_file );
294 }
295
296 int get_page_size(void)
297 {
298     if (!page_mask) init_page_size();
299     return page_mask + 1;
300 }
301
302 /* create a file mapping */
303 DECL_HANDLER(create_mapping)
304 {
305     struct object *obj;
306
307     req->handle = -1;
308     if ((obj = create_mapping( req->size_high, req->size_low,
309                                req->protect, req->file_handle,
310                                get_req_data(req), get_req_data_size(req) )))
311     {
312         int access = FILE_MAP_ALL_ACCESS;
313         if (!(req->protect & VPROT_WRITE)) access &= ~FILE_MAP_WRITE;
314         req->handle = alloc_handle( current->process, obj, access, req->inherit );
315         release_object( obj );
316     }
317 }
318
319 /* open a handle to a mapping */
320 DECL_HANDLER(open_mapping)
321 {
322     req->handle = open_object( get_req_data(req), get_req_data_size(req),
323                                &mapping_ops, req->access, req->inherit );
324 }
325
326 /* get a mapping information */
327 DECL_HANDLER(get_mapping_info)
328 {
329     struct mapping *mapping;
330
331     if ((mapping = (struct mapping *)get_handle_obj( current->process, req->handle,
332                                                      0, &mapping_ops )))
333     {
334         req->size_high   = mapping->size_high;
335         req->size_low    = mapping->size_low;
336         req->protect     = mapping->protect;
337         req->header_size = mapping->header_size;
338         req->base        = mapping->base;
339         req->shared_file = -1;
340         req->shared_size = mapping->shared_size;
341         req->anonymous   = !mapping->file;
342         if (mapping->shared_file)
343             req->shared_file = alloc_handle( current->process, mapping->shared_file,
344                                              GENERIC_READ|GENERIC_WRITE, 0 );
345         release_object( mapping );
346     }
347 }