2004-05-11 Dick Porter <dick@ximian.com>
[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 = NULL, *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 = 0;
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                 close (fd);
262                 if(created && *created==TRUE) {
263 #ifdef HAVE_LARGE_FILE_SUPPORT
264                         /* Keep gcc quiet... */
265                         g_critical (G_GNUC_PRETTY_FUNCTION ": shared file [%s] is not big enough! (found %lld, need %d bytes)", filename, statbuf.st_size, wanted_size);
266 #else
267                         g_critical (G_GNUC_PRETTY_FUNCTION ": shared file [%s] is not big enough! (found %ld, need %d bytes)", filename, statbuf.st_size, wanted_size);
268 #endif
269                         unlink (filename);
270                         return(-1);
271                 } else {
272                         /* We didn't create it, so just try opening it again */
273                         goto try_again;
274                 }
275         }
276         
277         return(fd);
278 }
279
280 gpointer _wapi_shm_file_map (_wapi_shm_t type, guint32 segment,
281                              gboolean *created, off_t *size)
282 {
283         gpointer shm_seg;
284         int fd;
285         struct stat statbuf;
286         guchar *filename=_wapi_shm_file (type, segment);
287         
288         fd=_wapi_shm_file_open (filename, type, created);
289         if(fd==-1) {
290                 g_critical (G_GNUC_PRETTY_FUNCTION
291                             ": shared file [%s] open error", filename);
292                 return(NULL);
293         }
294         
295         if(fstat (fd, &statbuf)==-1) {
296                 g_critical (G_GNUC_PRETTY_FUNCTION ": fstat error: %s",
297                             g_strerror (errno));
298                 close (fd);
299                 return(NULL);
300         }
301         if(size) {
302                 *size=statbuf.st_size;
303         }
304         
305         shm_seg=mmap (NULL, statbuf.st_size, PROT_READ|PROT_WRITE, MAP_SHARED,
306                       fd, 0);
307         if(shm_seg==MAP_FAILED) {
308                 g_critical (G_GNUC_PRETTY_FUNCTION ": mmap error: %s",
309                             g_strerror (errno));
310                 close (fd);
311                 return(NULL);
312         }
313                 
314         close (fd);
315         return(shm_seg);
316 }
317
318 /*
319  * _wapi_shm_attach:
320  * @success: Was it a success
321  *
322  * Attach to the shared memory file or create it if it did not
323  * exist. If it was created and daemon was FALSE a new daemon is
324  * forked into existence. Returns the memory area the file was mmapped
325  * to.
326  */
327 gboolean _wapi_shm_attach (struct _WapiHandleShared_list **data,
328                            struct _WapiHandleScratch **scratch)
329 {
330         gboolean data_created=FALSE, scratch_created=FALSE;
331         off_t data_size, scratch_size;
332         int tries, closing_tries=0;
333
334 map_again:
335         *data=_wapi_shm_file_map (WAPI_SHM_DATA, 0, &data_created, &data_size);
336         if(*data==NULL) {
337                 return(FALSE);
338         }
339         
340         *scratch=_wapi_shm_file_map (WAPI_SHM_SCRATCH, 0, &scratch_created,
341                                      &scratch_size);
342         if(*scratch==NULL) {
343                 if(data_created) {
344                         _wapi_shm_destroy ();
345                 }
346                 return(FALSE);
347         }
348
349         if(scratch_created)
350                 (*scratch)->data_len = scratch_size - 
351                                 (sizeof(struct _WapiHandleScratch) - MONO_ZERO_ARRAY_LENGTH);
352
353         if(data_created==FALSE && (*data)->daemon_running==DAEMON_CLOSING) {
354                 /* Daemon is closing down, give it a few ms and try
355                  * again.
356                  */
357                 
358                 struct timespec sleepytime;
359                         
360                 /* Something must have gone wrong, so delete the
361                  * shared segments and try again.
362                  */
363                 _wapi_shm_destroy ();
364                 
365                 munmap (*data, data_size);
366                 munmap (*scratch, scratch_size);
367                 
368                 if(closing_tries++ == 5) {
369                         /* Still can't get going, so bail out */
370                         g_warning ("The handle daemon is stuck closing");
371                         return(FALSE);
372                 }
373                 
374                 sleepytime.tv_sec=0;
375                 sleepytime.tv_nsec=10000000;    /* 10ms */
376                         
377                 nanosleep (&sleepytime, NULL);
378                 goto map_again;
379         }
380         
381         if(data_created==TRUE) {
382 #ifdef VALGRINDING
383                 /* _wapi_daemon_main() does not return */
384                 _wapi_daemon_main (*data, *scratch);
385                         
386                 /* But just in case... */
387                 (*data)->daemon_running=DAEMON_DIED_AT_STARTUP;
388                 exit (-1);
389 #else
390                 pid_t pid;
391                         
392                 pid=fork ();
393                 if(pid==-1) {
394                         g_critical (G_GNUC_PRETTY_FUNCTION ": fork error: %s",
395                                     strerror (errno));
396                         _wapi_shm_destroy ();
397                         return(FALSE);
398                 } else if (pid==0) {
399                         int i;
400                         
401                         /* child */
402                         setsid ();
403                         
404                         /* FIXME: Set process title to something
405                          * informative
406                          */
407
408                         /* Start the daemon with a clean sheet of file
409                          * descriptors
410                          */
411                         for(i=3; i<getdtablesize (); i++) {
412                                 close (i);
413                         }
414                         
415                         /* _wapi_daemon_main() does not return */
416                         _wapi_daemon_main (*data, *scratch);
417                         
418                         /* But just in case... */
419                         (*data)->daemon_running=DAEMON_DIED_AT_STARTUP;
420                         exit (-1);
421                 }
422                 /* parent carries on */
423 #ifdef DEBUG
424                 g_message (G_GNUC_PRETTY_FUNCTION ": Daemon pid %d", pid);
425 #endif
426 #endif /* !VALGRINDING */
427         }
428                 
429         for(tries=0; (*data)->daemon_running==DAEMON_STARTING && tries < 100;
430             tries++) {
431                 /* wait for the daemon to sort itself out.  To be
432                  * completely safe, we should have a timeout before
433                  * giving up.
434                  */
435                 struct timespec sleepytime;
436                         
437                 sleepytime.tv_sec=0;
438                 sleepytime.tv_nsec=10000000;    /* 10ms */
439                         
440                 nanosleep (&sleepytime, NULL);
441         }
442         if(tries==100 && (*data)->daemon_running==DAEMON_STARTING) {
443                 /* Daemon didnt get going */
444                 struct timespec sleepytime;
445                         
446                 /* Something must have gone wrong, so delete the
447                  * shared segments and try again.
448                  */
449                 _wapi_shm_destroy ();
450
451                 /* Daemon didn't get going, give it a few ms and try
452                  * again.
453                  */
454                 
455                 munmap (*data, data_size);
456                 munmap (*scratch, scratch_size);
457                 
458                 if(closing_tries++ == 5) {
459                         /* Still can't get going, so bail out */
460                         g_warning ("The handle daemon didnt start up properly");
461                         return(FALSE);
462                 }
463                 
464                 sleepytime.tv_sec=0;
465                 sleepytime.tv_nsec=10000000;    /* 10ms */
466                         
467                 nanosleep (&sleepytime, NULL);
468                 goto map_again;
469         }
470         
471         if((*data)->daemon_running==DAEMON_DIED_AT_STARTUP) {
472                 /* Oh dear, the daemon had an error starting up */
473                 if(data_created==TRUE) {
474                         _wapi_shm_destroy ();
475                 }
476                 g_warning ("Handle daemon failed to start");
477                 return(FALSE);
478         }
479
480         /* Do some sanity checking on the shared memory we
481          * attached
482          */
483         if(((*data)->daemon_running!=DAEMON_RUNNING) ||
484 #ifdef NEED_LINK_UNLINK
485            (strncmp ((*data)->daemon, "/tmp/mono-handle-daemon-",
486                      24)!=0)) {
487 #else
488            (strncmp ((*data)->daemon+1, "mono-handle-daemon-", 19)!=0)) {
489 #endif
490                 g_warning ("Shared memory sanity check failed.");
491                 g_warning("status: %d", (*data)->daemon_running);
492 #ifdef NEED_LINK_UNLINK
493                 g_warning("daemon: [%s]", (*data)->daemon);
494 #else
495                 g_warning("daemon: [%s]", (*data)->daemon+1);
496 #endif
497                 return(FALSE);
498         }
499                 
500         /* From now on, it's up to the daemon to delete the shared
501          * memory segment
502          */
503         
504         return(TRUE);
505 }
506
507 void _wapi_shm_destroy (void)
508 {
509 #ifndef DISABLE_SHARED_HANDLES
510 #ifdef DEBUG
511         g_message (G_GNUC_PRETTY_FUNCTION ": unlinking shared data");
512 #endif
513         /* Only delete the first segments.  The daemon will destroy
514          * any others when it exits
515          */
516         unlink (_wapi_shm_file (WAPI_SHM_DATA, 0));
517         unlink (_wapi_shm_file (WAPI_SHM_SCRATCH, 0));
518 #endif /* DISABLE_SHARED_HANDLES */
519 }
520