Added an unmount_device request that invalidates all file descriptors
[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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  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 "windef.h"
32
33 #include "file.h"
34 #include "handle.h"
35 #include "thread.h"
36 #include "request.h"
37
38 struct mapping
39 {
40     struct object   obj;             /* object header */
41     file_pos_t      size;            /* mapping size */
42     int             protect;         /* protection flags */
43     struct file    *file;            /* file mapped */
44     int             header_size;     /* size of headers (for PE image mapping) */
45     void           *base;            /* default base addr (for PE image mapping) */
46     struct file    *shared_file;     /* temp file for shared PE mapping */
47     int             shared_size;     /* shared mapping total size */
48     struct list     shared_entry;    /* entry in global shared PE mappings list */
49 };
50
51 static void mapping_dump( struct object *obj, int verbose );
52 static struct fd *mapping_get_fd( struct object *obj );
53 static void mapping_destroy( struct object *obj );
54
55 static const struct object_ops mapping_ops =
56 {
57     sizeof(struct mapping),      /* size */
58     mapping_dump,                /* dump */
59     no_add_queue,                /* add_queue */
60     NULL,                        /* remove_queue */
61     NULL,                        /* signaled */
62     NULL,                        /* satisfied */
63     no_signal,                   /* signal */
64     mapping_get_fd,              /* get_fd */
65     no_close_handle,             /* close_handle */
66     mapping_destroy              /* destroy */
67 };
68
69 static struct list shared_list = LIST_INIT(shared_list);
70
71 #ifdef __i386__
72
73 /* These are always the same on an i386, and it will be faster this way */
74 # define page_mask  0xfff
75 # define page_shift 12
76 # define init_page_size() do { /* nothing */ } while(0)
77
78 #else  /* __i386__ */
79
80 static int page_shift, page_mask;
81
82 static void init_page_size(void)
83 {
84     int page_size;
85 # ifdef HAVE_GETPAGESIZE
86     page_size = getpagesize();
87 # else
88 #  ifdef __svr4__
89     page_size = sysconf(_SC_PAGESIZE);
90 #  else
91 #   error Cannot get the page size on this platform
92 #  endif
93 # endif
94     page_mask = page_size - 1;
95     /* Make sure we have a power of 2 */
96     assert( !(page_size & page_mask) );
97     page_shift = 0;
98     while ((1 << page_shift) != page_size) page_shift++;
99 }
100 #endif  /* __i386__ */
101
102 #define ROUND_SIZE_MASK(addr,size,mask) \
103    (((int)(size) + ((int)(addr) & (mask)) + (mask)) & ~(mask))
104
105 #define ROUND_SIZE(size)  (((size) + page_mask) & ~page_mask)
106
107
108 /* find the shared PE mapping for a given mapping */
109 static struct file *get_shared_file( struct mapping *mapping )
110 {
111     struct mapping *ptr;
112
113     LIST_FOR_EACH_ENTRY( ptr, &shared_list, struct mapping, shared_entry )
114         if (is_same_file( ptr->file, mapping->file ))
115             return (struct file *)grab_object( ptr->shared_file );
116     return NULL;
117 }
118
119 /* allocate and fill the temp file for a shared PE image mapping */
120 static int build_shared_mapping( struct mapping *mapping, int fd,
121                                  IMAGE_SECTION_HEADER *sec, unsigned int nb_sec )
122 {
123     unsigned int i, max_size, total_size;
124     off_t shared_pos, read_pos, write_pos;
125     char *buffer = NULL;
126     int shared_fd;
127     long toread;
128
129     /* compute the total size of the shared mapping */
130
131     total_size = max_size = 0;
132     for (i = 0; i < nb_sec; i++)
133     {
134         if ((sec[i].Characteristics & IMAGE_SCN_MEM_SHARED) &&
135             (sec[i].Characteristics & IMAGE_SCN_MEM_WRITE))
136         {
137             unsigned int size = ROUND_SIZE( sec[i].Misc.VirtualSize );
138             if (size > max_size) max_size = size;
139             total_size += size;
140         }
141     }
142     if (!(mapping->shared_size = total_size)) return 1;  /* nothing to do */
143
144     if ((mapping->shared_file = get_shared_file( mapping ))) return 1;
145
146     /* create a temp file for the mapping */
147
148     if (!(mapping->shared_file = create_temp_file( GENERIC_READ|GENERIC_WRITE ))) return 0;
149     if (!grow_file( mapping->shared_file, total_size )) goto error;
150     if ((shared_fd = get_file_unix_fd( mapping->shared_file )) == -1) goto error;
151
152     if (!(buffer = malloc( max_size ))) goto error;
153
154     /* copy the shared sections data into the temp file */
155
156     shared_pos = 0;
157     for (i = 0; i < nb_sec; i++)
158     {
159         if (!(sec[i].Characteristics & IMAGE_SCN_MEM_SHARED)) continue;
160         if (!(sec[i].Characteristics & IMAGE_SCN_MEM_WRITE)) continue;
161         write_pos = shared_pos;
162         shared_pos += ROUND_SIZE( sec[i].Misc.VirtualSize );
163         if (!sec[i].PointerToRawData || !sec[i].SizeOfRawData) continue;
164         read_pos = sec[i].PointerToRawData;
165         toread = sec[i].SizeOfRawData;
166         while (toread)
167         {
168             long res = pread( fd, buffer + sec[i].SizeOfRawData - toread, toread, read_pos );
169             if (res <= 0) goto error;
170             toread -= res;
171             read_pos += res;
172         }
173         if (pwrite( shared_fd, buffer, sec[i].SizeOfRawData, write_pos ) != sec[i].SizeOfRawData)
174             goto error;
175     }
176     free( buffer );
177     return 1;
178
179  error:
180     release_object( mapping->shared_file );
181     mapping->shared_file = NULL;
182     if (buffer) free( buffer );
183     return 0;
184 }
185
186 /* retrieve the mapping parameters for an executable (PE) image */
187 static int get_image_params( struct mapping *mapping )
188 {
189     IMAGE_DOS_HEADER dos;
190     IMAGE_NT_HEADERS nt;
191     IMAGE_SECTION_HEADER *sec = NULL;
192     struct fd *fd;
193     off_t pos;
194     int unix_fd, size;
195
196     /* load the headers */
197
198     if (!(fd = mapping_get_fd( &mapping->obj ))) return 0;
199     if ((unix_fd = get_unix_fd( fd )) == -1) goto error;
200     if (pread( unix_fd, &dos, sizeof(dos), 0 ) != sizeof(dos)) goto error;
201     if (dos.e_magic != IMAGE_DOS_SIGNATURE) goto error;
202     pos = dos.e_lfanew;
203
204     if (pread( unix_fd, &nt.Signature, sizeof(nt.Signature), pos ) != sizeof(nt.Signature))
205         goto error;
206     pos += sizeof(nt.Signature);
207     if (nt.Signature != IMAGE_NT_SIGNATURE) goto error;
208     if (pread( unix_fd, &nt.FileHeader, sizeof(nt.FileHeader), pos ) != sizeof(nt.FileHeader))
209         goto error;
210     pos += sizeof(nt.FileHeader);
211     /* zero out Optional header in the case it's not present or partial */
212     memset(&nt.OptionalHeader, 0, sizeof(nt.OptionalHeader));
213     if (pread( unix_fd, &nt.OptionalHeader, nt.FileHeader.SizeOfOptionalHeader,
214                pos ) != nt.FileHeader.SizeOfOptionalHeader) goto error;
215     pos += nt.FileHeader.SizeOfOptionalHeader;
216
217     /* load the section headers */
218
219     size = sizeof(*sec) * nt.FileHeader.NumberOfSections;
220     if (!(sec = malloc( size ))) goto error;
221     if (pread( unix_fd, sec, size, pos ) != size) goto error;
222
223     if (!build_shared_mapping( mapping, unix_fd, sec, nt.FileHeader.NumberOfSections )) goto error;
224
225     if (mapping->shared_file) list_add_head( &shared_list, &mapping->shared_entry );
226
227     mapping->size        = ROUND_SIZE( nt.OptionalHeader.SizeOfImage );
228     mapping->base        = (void *)nt.OptionalHeader.ImageBase;
229     mapping->header_size = ROUND_SIZE_MASK( mapping->base, nt.OptionalHeader.SizeOfHeaders,
230                                             nt.OptionalHeader.SectionAlignment - 1 );
231     mapping->protect     = VPROT_IMAGE;
232
233     /* sanity check */
234     if (mapping->header_size > mapping->size) goto error;
235
236     free( sec );
237     release_object( fd );
238     return 1;
239
240  error:
241     if (sec) free( sec );
242     release_object( fd );
243     set_error( STATUS_INVALID_FILE_FOR_SECTION );
244     return 0;
245 }
246
247 /* get the size of the unix file associated with the mapping */
248 inline static int get_file_size( struct file *file, file_pos_t *size )
249 {
250     struct stat st;
251     int unix_fd = get_file_unix_fd( file );
252
253     if (unix_fd == -1 || fstat( unix_fd, &st ) == -1) return 0;
254     *size = st.st_size;
255     return 1;
256 }
257
258 static struct object *create_mapping( file_pos_t size, int protect, obj_handle_t handle,
259                                       const WCHAR *name, size_t len )
260 {
261     struct mapping *mapping;
262     int access = 0;
263
264     if (!page_mask) init_page_size();
265
266     if (!(mapping = create_named_object( sync_namespace, &mapping_ops, name, len )))
267         return NULL;
268     if (get_error() == STATUS_OBJECT_NAME_COLLISION)
269         return &mapping->obj;  /* Nothing else to do */
270
271     mapping->header_size = 0;
272     mapping->base        = NULL;
273     mapping->shared_file = NULL;
274     mapping->shared_size = 0;
275
276     if (protect & VPROT_READ) access |= GENERIC_READ;
277     if (protect & VPROT_WRITE) access |= GENERIC_WRITE;
278
279     if (handle)
280     {
281         if (!(mapping->file = get_file_obj( current->process, handle, access ))) goto error;
282         if (protect & VPROT_IMAGE)
283         {
284             if (!get_image_params( mapping )) goto error;
285             return &mapping->obj;
286         }
287         if (!size)
288         {
289             if (!get_file_size( mapping->file, &size )) goto error;
290             if (!size)
291             {
292                 set_error( STATUS_FILE_INVALID );
293                 goto error;
294             }
295         }
296         else
297         {
298             if (!grow_file( mapping->file, size )) goto error;
299         }
300     }
301     else  /* Anonymous mapping (no associated file) */
302     {
303         if (!size || (protect & VPROT_IMAGE))
304         {
305             set_error( STATUS_INVALID_PARAMETER );
306             mapping->file = NULL;
307             goto error;
308         }
309         if (!(mapping->file = create_temp_file( access ))) goto error;
310         if (!grow_file( mapping->file, size )) goto error;
311     }
312     mapping->size    = (size + page_mask) & ~((file_pos_t)page_mask);
313     mapping->protect = protect;
314     return &mapping->obj;
315
316  error:
317     release_object( mapping );
318     return NULL;
319 }
320
321 static void mapping_dump( struct object *obj, int verbose )
322 {
323     struct mapping *mapping = (struct mapping *)obj;
324     assert( obj->ops == &mapping_ops );
325     fprintf( stderr, "Mapping size=%08x%08x prot=%08x file=%p header_size=%08x base=%p "
326              "shared_file=%p shared_size=%08x ",
327              (unsigned int)(mapping->size >> 32), (unsigned int)mapping->size,
328              mapping->protect, mapping->file, mapping->header_size,
329              mapping->base, mapping->shared_file, mapping->shared_size );
330     dump_object_name( &mapping->obj );
331     fputc( '\n', stderr );
332 }
333
334 static struct fd *mapping_get_fd( struct object *obj )
335 {
336     struct mapping *mapping = (struct mapping *)obj;
337     return get_obj_fd( (struct object *)mapping->file );
338 }
339
340 static void mapping_destroy( struct object *obj )
341 {
342     struct mapping *mapping = (struct mapping *)obj;
343     assert( obj->ops == &mapping_ops );
344     if (mapping->file) release_object( mapping->file );
345     if (mapping->shared_file)
346     {
347         release_object( mapping->shared_file );
348         list_remove( &mapping->shared_entry );
349     }
350 }
351
352 int get_page_size(void)
353 {
354     if (!page_mask) init_page_size();
355     return page_mask + 1;
356 }
357
358 /* create a file mapping */
359 DECL_HANDLER(create_mapping)
360 {
361     struct object *obj;
362     file_pos_t size = ((file_pos_t)req->size_high << 32) | req->size_low;
363
364     reply->handle = 0;
365     if ((obj = create_mapping( size, req->protect, req->file_handle,
366                                get_req_data(), get_req_data_size() )))
367     {
368         reply->handle = alloc_handle( current->process, obj, req->access, req->inherit );
369         release_object( obj );
370     }
371 }
372
373 /* open a handle to a mapping */
374 DECL_HANDLER(open_mapping)
375 {
376     reply->handle = open_object( sync_namespace, get_req_data(), get_req_data_size(),
377                                  &mapping_ops, req->access, req->inherit );
378 }
379
380 /* get a mapping information */
381 DECL_HANDLER(get_mapping_info)
382 {
383     struct mapping *mapping;
384
385     if ((mapping = (struct mapping *)get_handle_obj( current->process, req->handle,
386                                                      0, &mapping_ops )))
387     {
388         reply->size_high   = (unsigned int)(mapping->size >> 32);
389         reply->size_low    = (unsigned int)mapping->size;
390         reply->protect     = mapping->protect;
391         reply->header_size = mapping->header_size;
392         reply->base        = mapping->base;
393         reply->shared_file = 0;
394         reply->shared_size = mapping->shared_size;
395         if (mapping->shared_file)
396             reply->shared_file = alloc_handle( current->process, mapping->shared_file,
397                                                GENERIC_READ|GENERIC_WRITE, 0 );
398         release_object( mapping );
399     }
400 }