updated browser capabilities file
[mono.git] / mono / io-layer / shared.c
1 /*
2  * shared.c:  Shared memory handling, and daemon launching
3  *
4  * Author:
5  *      Dick Porter (dick@ximian.com)
6  *
7  * (C) 2002 Ximian, Inc.
8  */
9
10 /*
11  * Code to support inter-process sharing of handles.
12  *
13  * I thought of using an mmap()ed file for this.  If linuxthreads
14  * supported PTHREAD_PROCESS_SHARED I would have done; however without
15  * that pthread support the only other inter-process IPC
16  * synchronisation option is a sysV semaphore, and if I'm going to use
17  * that I may as well take advantage of sysV shared memory too.
18  * Actually, semaphores seem to be buggy, or I was using them
19  * incorrectly :-).  I've replaced the sysV semaphore with a shared
20  * integer controlled with Interlocked functions.  And I've since
21  * replaced that with a separate process to serialise access to the
22  * shared memory, to avoid the possibility of DOS by leaving the
23  * shared memory locked, and also to allow the shared memory to be
24  * cleaned up.
25  *
26  * mmap() files have the advantage of avoiding namespace collisions,
27  * but have the disadvantage of needing cleaning up, and also msync().
28  * sysV shared memory has a really stupid way of getting random key
29  * IDs, which can lead to collisions.
30  *
31  * Having tried sysv shm, I tested mmap() and found that MAP_SHARED
32  * makes msync() irrelevent, and both types need cleaning up.  Seeing
33  * as mmap() doesn't suffer from the bonkers method of allocating
34  * segments, it seems to be the best method.
35  *
36  * This shared memory is needed because w32 processes do not have the
37  * POSIX parent-child relationship, so a process handle is available
38  * to any other process to find out exit status.  Handles are
39  * destroyed when the last reference to them is closed.  New handles
40  * can be created for long lasting items such as processes or threads,
41  * and also for named synchronisation objects so long as these haven't
42  * been deleted by having the last referencing handle closed.
43  */
44
45
46 #include <config.h>
47 #include <glib.h>
48 #include <stdio.h>
49 #include <fcntl.h>
50 #include <unistd.h>
51 #include <sys/mman.h>
52 #include <sys/types.h>
53 #include <sys/stat.h>
54 #include <errno.h>
55 #include <string.h>
56
57 #include <mono/io-layer/wapi.h>
58 #include <mono/io-layer/wapi-private.h>
59 #include <mono/io-layer/shared.h>
60 #include <mono/io-layer/daemon-private.h>
61
62 #undef DEBUG
63
64 /* Define this to make it easier to run valgrind on the daemon.  Then
65  * the first process to start will turn into a daemon without forking
66  * (the debug utility mono/handles/hps is ideal for this.)
67  */
68 #undef VALGRINDING
69
70 guchar *_wapi_shm_file (_wapi_shm_t type, guint32 segment)
71 {
72         static guchar file[_POSIX_PATH_MAX];
73         guchar *name, *filename, *dir, *wapi_dir;
74         gchar machine_name[256];
75
76         if (gethostname(machine_name, sizeof(machine_name)) != 0)
77                 machine_name[0] = '\0';
78         
79         /* Change the filename whenever the format of the contents
80          * changes
81          */
82         if(type==WAPI_SHM_DATA) {
83                 name=g_strdup_printf ("shared_data-%s-%d-%d",
84                                       machine_name, _WAPI_HANDLE_VERSION, segment);
85         } else if (type==WAPI_SHM_SCRATCH) {
86                 name=g_strdup_printf ("shared_scratch-%s-%d-%d",
87                                       machine_name, _WAPI_HANDLE_VERSION, segment);
88         } else {
89                 g_assert_not_reached ();
90         }
91
92         /* I don't know how nfs affects mmap.  If mmap() of files on
93          * nfs mounts breaks, then there should be an option to set
94          * the directory.
95          */
96         wapi_dir=getenv ("MONO_SHARED_DIR");
97         if(wapi_dir==NULL) {
98                 filename=g_build_filename (g_get_home_dir (), ".wapi", name,
99                                            NULL);
100         } else {
101                 filename=g_build_filename (wapi_dir, ".wapi", name, NULL);
102         }
103         g_free (name);
104
105         g_snprintf (file, _POSIX_PATH_MAX, "%s", filename);
106                 
107         /* No need to check if the dir already exists or check
108          * mkdir() errors, because on any error the open() call will
109          * report the problem.
110          */
111         dir=g_path_get_dirname (file);
112         mkdir (dir, 0755);
113         g_free (dir);
114         
115         return(file);
116 }
117
118 gpointer _wapi_shm_file_expand (gpointer mem, _wapi_shm_t type,
119                                 guint32 segment, guint32 old_len,
120                                 guint32 new_len)
121 {
122         int fd;
123         gpointer new_mem;
124         guchar *filename=_wapi_shm_file (type, segment);
125
126         if(old_len>=new_len) {
127                 return(mem);
128         }
129         
130         munmap (mem, old_len);
131         
132         fd=open (filename, O_RDWR, 0600);
133         if(fd==-1) {
134                 g_critical (G_GNUC_PRETTY_FUNCTION
135                             ": shared file [%s] open error: %s", filename,
136                             g_strerror (errno));
137                 return(NULL);
138         }
139
140         if(lseek (fd, new_len-1, SEEK_SET)==-1) {
141                 g_critical (G_GNUC_PRETTY_FUNCTION
142                             ": shared file [%s] lseek error: %s", filename,
143                             g_strerror (errno));
144                 return(NULL);
145         }
146         
147         if(write (fd, "", 1)==-1) {
148                 g_critical (G_GNUC_PRETTY_FUNCTION
149                             ": shared file [%s] write error: %s", filename,
150                             g_strerror (errno));
151                 return(NULL);
152         }
153         close (fd);
154         
155         new_mem=_wapi_shm_file_map (type, segment, NULL, NULL);
156         
157         return(new_mem);
158 }
159
160 static int _wapi_shm_file_open (const guchar *filename, _wapi_shm_t type,
161                                 gboolean *created)
162 {
163         int fd;
164         struct stat statbuf;
165         guint32 wanted_size;
166         
167         if(created) {
168                 *created=FALSE;
169         }
170         
171         if(type==WAPI_SHM_DATA) {
172                 wanted_size=sizeof(struct _WapiHandleShared_list);
173         } else if (type==WAPI_SHM_SCRATCH) {
174                 wanted_size=sizeof(struct _WapiHandleScratch) + 
175                                 (_WAPI_SHM_SCRATCH_SIZE - MONO_ZERO_ARRAY_LENGTH);
176         } else {
177                 g_assert_not_reached ();
178         }
179         
180 try_again:
181         /* No O_CREAT yet, because we need to initialise the file if
182          * we have to create it.
183          */
184         fd=open (filename, O_RDWR, 0600);
185         if(fd==-1 && errno==ENOENT) {
186                 /* OK, its up to us to create it.  O_EXCL to avoid a
187                  * race condition where two processes can
188                  * simultaneously try and create the file
189                  */
190                 fd=open (filename, O_CREAT|O_EXCL|O_RDWR, 0600);
191                 if(fd==-1 && errno==EEXIST) {
192                         /* It's possible that the file was created in
193                          * between finding it didn't exist, and trying
194                          * to create it.  Just try opening it again
195                          */
196                         goto try_again;
197                 } else if (fd==-1) {
198                         g_critical (G_GNUC_PRETTY_FUNCTION
199                                     ": shared file [%s] open error: %s",
200                                     filename, g_strerror (errno));
201                         return(-1);
202                 } else {
203                         /* We created the file, so we need to expand
204                          * the file and inform the caller so it can
205                          * fork the handle daemon too.
206                          *
207                          * (wanted_size-1, because we're about to
208                          * write the other byte to actually expand the
209                          * file.)
210                          */
211                         if(lseek (fd, wanted_size-1, SEEK_SET)==-1) {
212                                 g_critical (G_GNUC_PRETTY_FUNCTION ": shared file [%s] lseek error: %s", filename, g_strerror (errno));
213                                 close (fd);
214                                 unlink (filename);
215                                 return(-1);
216                         }
217                         
218                         if(write (fd, "", 1)==-1) {
219                                 g_critical (G_GNUC_PRETTY_FUNCTION ": shared file [%s] write error: %s", filename, g_strerror (errno));
220                                 close (fd);
221                                 unlink (filename);
222                                 return(-1);
223                         }
224                         
225                         if(created) {
226                                 *created=TRUE;
227                         }
228
229                         /* The contents of the file is set to all
230                          * zero, because it is opened up with lseek,
231                          * so we don't need to do any more
232                          * initialisation here
233                          */
234                 }
235         } else if(fd==-1) {
236                 g_critical (G_GNUC_PRETTY_FUNCTION
237                             ": shared file [%s] open error: %s", filename,
238                             g_strerror (errno));
239                 return(-1);
240         }
241         
242         /* From now on, we need to delete the file before exiting on
243          * error if we created it (ie, if *created==TRUE)
244          */
245
246         /* Use stat to find the file size (instead of hard coding it)
247          * because we can expand the file later if needed (for more
248          * handles or scratch space.)
249          */
250         if(fstat (fd, &statbuf)==-1) {
251                 g_critical (G_GNUC_PRETTY_FUNCTION ": fstat error: %s",
252                             g_strerror (errno));
253                 if(created && *created==TRUE) {
254                         unlink (filename);
255                 }
256                 close (fd);
257                 return(-1);
258         }
259
260         if(statbuf.st_size < wanted_size) {
261 #ifdef HAVE_LARGE_FILE_SUPPORT
262                 /* Keep gcc quiet... */
263                 g_critical (G_GNUC_PRETTY_FUNCTION ": shared file [%s] is not big enough! (found %lld, need %d bytes)", filename, statbuf.st_size, wanted_size);
264 #else
265                 g_critical (G_GNUC_PRETTY_FUNCTION ": shared file [%s] is not big enough! (found %ld, need %d bytes)", filename, statbuf.st_size, wanted_size);
266 #endif
267                 if(created && *created==TRUE) {
268                         unlink (filename);
269                 }
270                 close (fd);
271                 return(-1);
272         }
273         
274         return(fd);
275 }
276
277 gpointer _wapi_shm_file_map (_wapi_shm_t type, guint32 segment,
278                              gboolean *created, off_t *size)
279 {
280         gpointer shm_seg;
281         int fd;
282         struct stat statbuf;
283         guchar *filename=_wapi_shm_file (type, segment);
284         
285         fd=_wapi_shm_file_open (filename, type, created);
286         if(fd==-1) {
287                 g_critical (G_GNUC_PRETTY_FUNCTION
288                             ": shared file [%s] open error", filename);
289                 return(NULL);
290         }
291         
292         if(fstat (fd, &statbuf)==-1) {
293                 g_critical (G_GNUC_PRETTY_FUNCTION ": fstat error: %s",
294                             g_strerror (errno));
295                 close (fd);
296                 return(NULL);
297         }
298         if(size) {
299                 *size=statbuf.st_size;
300         }
301         
302         shm_seg=mmap (NULL, statbuf.st_size, PROT_READ|PROT_WRITE, MAP_SHARED,
303                       fd, 0);
304         if(shm_seg==MAP_FAILED) {
305                 g_critical (G_GNUC_PRETTY_FUNCTION ": mmap error: %s",
306                             g_strerror (errno));
307                 close (fd);
308                 return(NULL);
309         }
310                 
311         close (fd);
312         return(shm_seg);
313 }
314
315 /*
316  * _wapi_shm_attach:
317  * @success: Was it a success
318  *
319  * Attach to the shared memory file or create it if it did not
320  * exist. If it was created and daemon was FALSE a new daemon is
321  * forked into existence. Returns the memory area the file was mmapped
322  * to.
323  */
324 gboolean _wapi_shm_attach (struct _WapiHandleShared_list **data,
325                            struct _WapiHandleScratch **scratch)
326 {
327         gboolean data_created=FALSE, scratch_created=FALSE;
328         off_t data_size, scratch_size;
329         int tries, closing_tries=0;
330
331 map_again:
332         *data=_wapi_shm_file_map (WAPI_SHM_DATA, 0, &data_created, &data_size);
333         if(*data==NULL) {
334                 return(FALSE);
335         }
336         
337         *scratch=_wapi_shm_file_map (WAPI_SHM_SCRATCH, 0, &scratch_created,
338                                      &scratch_size);
339         if(*scratch==NULL) {
340                 if(data_created) {
341                         _wapi_shm_destroy ();
342                 }
343                 return(FALSE);
344         }
345
346         if(scratch_created)
347                 (*scratch)->data_len = scratch_size - 
348                                 (sizeof(struct _WapiHandleScratch) - MONO_ZERO_ARRAY_LENGTH);
349
350         if(data_created==FALSE && (*data)->daemon_running==DAEMON_CLOSING) {
351                 /* Daemon is closing down, give it a few ms and try
352                  * again.
353                  */
354                 
355                 struct timespec sleepytime;
356                         
357                 munmap (*data, data_size);
358                 munmap (*scratch, scratch_size);
359                 
360                 if(closing_tries++ == 5) {
361                         /* Something must have gone wrong, so bail
362                          * out.  This will let the calling code delete
363                          * the shared segments and try again.
364                          */
365                         return(FALSE);
366                 }
367                 
368                 sleepytime.tv_sec=0;
369                 sleepytime.tv_nsec=10000000;    /* 10ms */
370                         
371                 nanosleep (&sleepytime, NULL);
372                 goto map_again;
373         }
374         
375         if(data_created==TRUE) {
376 #ifdef VALGRINDING
377                 /* _wapi_daemon_main() does not return */
378                 _wapi_daemon_main (*data, *scratch);
379                         
380                 /* But just in case... */
381                 (*data)->daemon_running=DAEMON_DIED_AT_STARTUP;
382                 exit (-1);
383 #else
384                 pid_t pid;
385                         
386                 pid=fork ();
387                 if(pid==-1) {
388                         g_critical (G_GNUC_PRETTY_FUNCTION ": fork error: %s",
389                                     strerror (errno));
390                         _wapi_shm_destroy ();
391                         return(FALSE);
392                 } else if (pid==0) {
393                         int i;
394                         
395                         /* child */
396                         setsid ();
397                         
398                         /* FIXME: Set process title to something
399                          * informative
400                          */
401
402                         /* Start the daemon with a clean sheet of file
403                          * descriptors
404                          */
405                         for(i=3; i<getdtablesize (); i++) {
406                                 close (i);
407                         }
408                         
409                         /* _wapi_daemon_main() does not return */
410                         _wapi_daemon_main (*data, *scratch);
411                         
412                         /* But just in case... */
413                         (*data)->daemon_running=DAEMON_DIED_AT_STARTUP;
414                         exit (-1);
415                 }
416                 /* parent carries on */
417 #ifdef DEBUG
418                 g_message (G_GNUC_PRETTY_FUNCTION ": Daemon pid %d", pid);
419 #endif
420 #endif /* !VALGRINDING */
421         } else {
422                 /* Do some sanity checking on the shared memory we
423                  * attached
424                  */
425                 if(!((*data)->daemon_running==DAEMON_STARTING || 
426                      (*data)->daemon_running==DAEMON_RUNNING ||
427                      (*data)->daemon_running==DAEMON_DIED_AT_STARTUP) ||
428 #ifdef NEED_LINK_UNLINK
429                    (strncmp ((*data)->daemon, "/tmp/mono-handle-daemon-",
430                              24)!=0)) {
431 #else
432                    (strncmp ((*data)->daemon+1, "mono-handle-daemon-", 19)!=0)) {
433 #endif
434                         g_warning ("Shared memory sanity check failed.");
435                         return(FALSE);
436                 }
437         }
438                 
439         for(tries=0; (*data)->daemon_running==DAEMON_STARTING && tries < 100;
440             tries++) {
441                 /* wait for the daemon to sort itself out.  To be
442                  * completely safe, we should have a timeout before
443                  * giving up.
444                  */
445                 struct timespec sleepytime;
446                         
447                 sleepytime.tv_sec=0;
448                 sleepytime.tv_nsec=10000000;    /* 10ms */
449                         
450                 nanosleep (&sleepytime, NULL);
451         }
452         if(tries==100 && (*data)->daemon_running==DAEMON_STARTING) {
453                 /* Daemon didnt get going */
454                 if(data_created==TRUE) {
455                         _wapi_shm_destroy ();
456                 }
457                 g_warning ("The handle daemon didnt start up properly");
458                 return(FALSE);
459         }
460         
461         if((*data)->daemon_running==DAEMON_DIED_AT_STARTUP) {
462                 /* Oh dear, the daemon had an error starting up */
463                 if(data_created==TRUE) {
464                         _wapi_shm_destroy ();
465                 }
466                 g_warning ("Handle daemon failed to start");
467                 return(FALSE);
468         }
469                 
470         /* From now on, it's up to the daemon to delete the shared
471          * memory segment
472          */
473         
474         return(TRUE);
475 }
476
477 void _wapi_shm_destroy (void)
478 {
479 #ifndef DISABLE_SHARED_HANDLES
480 #ifdef DEBUG
481         g_message (G_GNUC_PRETTY_FUNCTION ": unlinking shared data");
482 #endif
483         /* Only delete the first segments.  The daemon will destroy
484          * any others when it exits
485          */
486         unlink (_wapi_shm_file (WAPI_SHM_DATA, 0));
487         unlink (_wapi_shm_file (WAPI_SHM_SCRATCH, 0));
488 #endif /* DISABLE_SHARED_HANDLES */
489 }
490