* Makefile: Suppress compiler warning cs:618 for test dll.
[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         int ret;
126
127         if(old_len>=new_len) {
128                 return(mem);
129         }
130         
131         munmap (mem, old_len);
132         
133         fd=open (filename, O_RDWR, 0600);
134         if(fd==-1) {
135                 g_critical (G_GNUC_PRETTY_FUNCTION
136                             ": shared file [%s] open error: %s", filename,
137                             g_strerror (errno));
138                 return(NULL);
139         }
140
141         if(lseek (fd, new_len-1, SEEK_SET)==-1) {
142                 g_critical (G_GNUC_PRETTY_FUNCTION
143                             ": shared file [%s] lseek error: %s", filename,
144                             g_strerror (errno));
145                 return(NULL);
146         }
147         
148         do {
149                 ret=write (fd, "", 1);
150         }
151         while (ret==-1 && errno==EINTR);
152
153         if(ret==-1) {
154                 g_critical (G_GNUC_PRETTY_FUNCTION
155                             ": shared file [%s] write error: %s", filename,
156                             g_strerror (errno));
157                 return(NULL);
158         }
159
160         close (fd);
161         
162         new_mem=_wapi_shm_file_map (type, segment, NULL, NULL);
163         
164         return(new_mem);
165 }
166
167 static int _wapi_shm_file_open (const guchar *filename, _wapi_shm_t type,
168                                 gboolean *created)
169 {
170         int fd;
171         struct stat statbuf;
172         guint32 wanted_size = 0;
173         int ret;
174         
175         if(created) {
176                 *created=FALSE;
177         }
178         
179         if(type==WAPI_SHM_DATA) {
180                 wanted_size=sizeof(struct _WapiHandleShared_list);
181         } else if (type==WAPI_SHM_SCRATCH) {
182                 wanted_size=sizeof(struct _WapiHandleScratch) + 
183                                 (_WAPI_SHM_SCRATCH_SIZE - MONO_ZERO_ARRAY_LENGTH);
184         } else {
185                 g_assert_not_reached ();
186         }
187         
188 try_again:
189         /* No O_CREAT yet, because we need to initialise the file if
190          * we have to create it.
191          */
192         fd=open (filename, O_RDWR, 0600);
193         if(fd==-1 && errno==ENOENT) {
194                 /* OK, its up to us to create it.  O_EXCL to avoid a
195                  * race condition where two processes can
196                  * simultaneously try and create the file
197                  */
198                 fd=open (filename, O_CREAT|O_EXCL|O_RDWR, 0600);
199                 if(fd==-1 && errno==EEXIST) {
200                         /* It's possible that the file was created in
201                          * between finding it didn't exist, and trying
202                          * to create it.  Just try opening it again
203                          */
204                         goto try_again;
205                 } else if (fd==-1) {
206                         g_critical (G_GNUC_PRETTY_FUNCTION
207                                     ": shared file [%s] open error: %s",
208                                     filename, g_strerror (errno));
209                         return(-1);
210                 } else {
211                         /* We created the file, so we need to expand
212                          * the file and inform the caller so it can
213                          * fork the handle daemon too.
214                          *
215                          * (wanted_size-1, because we're about to
216                          * write the other byte to actually expand the
217                          * file.)
218                          */
219                         if(lseek (fd, wanted_size-1, SEEK_SET)==-1) {
220                                 g_critical (G_GNUC_PRETTY_FUNCTION ": shared file [%s] lseek error: %s", filename, g_strerror (errno));
221                                 close (fd);
222                                 unlink (filename);
223                                 return(-1);
224                         }
225                         
226                         do {
227                                 ret=write (fd, "", 1);
228                         }
229                         while (ret==-1 && errno==EINTR);
230                                 
231                         if(ret==-1) {
232                                 g_critical (G_GNUC_PRETTY_FUNCTION ": shared file [%s] write error: %s", filename, g_strerror (errno));
233                                 close (fd);
234                                 unlink (filename);
235                                 return(-1);
236                         }
237                         
238                         if(created) {
239                                 *created=TRUE;
240                         }
241
242                         /* The contents of the file is set to all
243                          * zero, because it is opened up with lseek,
244                          * so we don't need to do any more
245                          * initialisation here
246                          */
247                 }
248         } else if(fd==-1) {
249                 g_critical (G_GNUC_PRETTY_FUNCTION
250                             ": shared file [%s] open error: %s", filename,
251                             g_strerror (errno));
252                 return(-1);
253         }
254         
255         /* From now on, we need to delete the file before exiting on
256          * error if we created it (ie, if *created==TRUE)
257          */
258
259         /* Use stat to find the file size (instead of hard coding it)
260          * because we can expand the file later if needed (for more
261          * handles or scratch space.)
262          */
263         if(fstat (fd, &statbuf)==-1) {
264                 g_critical (G_GNUC_PRETTY_FUNCTION ": fstat error: %s",
265                             g_strerror (errno));
266                 if(created && *created==TRUE) {
267                         unlink (filename);
268                 }
269                 close (fd);
270                 return(-1);
271         }
272
273         if(statbuf.st_size < wanted_size) {
274                 close (fd);
275                 if(created && *created==TRUE) {
276 #ifdef HAVE_LARGE_FILE_SUPPORT
277                         /* Keep gcc quiet... */
278                         g_critical (G_GNUC_PRETTY_FUNCTION ": shared file [%s] is not big enough! (found %lld, need %d bytes)", filename, statbuf.st_size, wanted_size);
279 #else
280                         g_critical (G_GNUC_PRETTY_FUNCTION ": shared file [%s] is not big enough! (found %ld, need %d bytes)", filename, statbuf.st_size, wanted_size);
281 #endif
282                         unlink (filename);
283                         return(-1);
284                 } else {
285                         /* We didn't create it, so just try opening it again */
286                         goto try_again;
287                 }
288         }
289         
290         return(fd);
291 }
292
293 gpointer _wapi_shm_file_map (_wapi_shm_t type, guint32 segment,
294                              gboolean *created, off_t *size)
295 {
296         gpointer shm_seg;
297         int fd;
298         struct stat statbuf;
299         guchar *filename=_wapi_shm_file (type, segment);
300         
301         fd=_wapi_shm_file_open (filename, type, created);
302         if(fd==-1) {
303                 g_critical (G_GNUC_PRETTY_FUNCTION
304                             ": shared file [%s] open error", filename);
305                 return(NULL);
306         }
307         
308         if(fstat (fd, &statbuf)==-1) {
309                 g_critical (G_GNUC_PRETTY_FUNCTION ": fstat error: %s",
310                             g_strerror (errno));
311                 close (fd);
312                 return(NULL);
313         }
314         if(size) {
315                 *size=statbuf.st_size;
316         }
317         
318         shm_seg=mmap (NULL, statbuf.st_size, PROT_READ|PROT_WRITE, MAP_SHARED,
319                       fd, 0);
320         if(shm_seg==MAP_FAILED) {
321                 g_critical (G_GNUC_PRETTY_FUNCTION ": mmap error: %s",
322                             g_strerror (errno));
323                 close (fd);
324                 return(NULL);
325         }
326                 
327         close (fd);
328         return(shm_seg);
329 }
330
331 /*
332  * _wapi_shm_attach:
333  * @success: Was it a success
334  *
335  * Attach to the shared memory file or create it if it did not
336  * exist. If it was created and daemon was FALSE a new daemon is
337  * forked into existence. Returns the memory area the file was mmapped
338  * to.
339  */
340 gboolean _wapi_shm_attach (struct _WapiHandleShared_list **data,
341                            struct _WapiHandleScratch **scratch)
342 {
343         gboolean data_created=FALSE, scratch_created=FALSE;
344         off_t data_size, scratch_size;
345         int tries, closing_tries=0;
346
347 map_again:
348         *data=_wapi_shm_file_map (WAPI_SHM_DATA, 0, &data_created, &data_size);
349         if(*data==NULL) {
350                 return(FALSE);
351         }
352         
353         *scratch=_wapi_shm_file_map (WAPI_SHM_SCRATCH, 0, &scratch_created,
354                                      &scratch_size);
355         if(*scratch==NULL) {
356                 if(data_created) {
357                         _wapi_shm_destroy ();
358                 }
359                 return(FALSE);
360         }
361
362         if(scratch_created)
363                 (*scratch)->data_len = scratch_size - 
364                                 (sizeof(struct _WapiHandleScratch) - MONO_ZERO_ARRAY_LENGTH);
365
366         if(data_created==FALSE && (*data)->daemon_running==DAEMON_CLOSING) {
367                 /* Daemon is closing down, give it a few ms and try
368                  * again.
369                  */
370                 
371                 struct timespec sleepytime;
372                         
373                 /* Something must have gone wrong, so delete the
374                  * shared segments and try again.
375                  */
376                 _wapi_shm_destroy ();
377                 
378                 munmap (*data, data_size);
379                 munmap (*scratch, scratch_size);
380                 
381                 if(closing_tries++ == 5) {
382                         /* Still can't get going, so bail out */
383                         g_warning ("The handle daemon is stuck closing");
384                         return(FALSE);
385                 }
386                 
387                 sleepytime.tv_sec=0;
388                 sleepytime.tv_nsec=10000000;    /* 10ms */
389                         
390                 nanosleep (&sleepytime, NULL);
391                 goto map_again;
392         }
393         
394         if(data_created==TRUE) {
395 #ifdef VALGRINDING
396                 /* _wapi_daemon_main() does not return */
397                 _wapi_daemon_main (*data, *scratch);
398                         
399                 /* But just in case... */
400                 (*data)->daemon_running=DAEMON_DIED_AT_STARTUP;
401                 exit (-1);
402 #else
403                 pid_t pid;
404                         
405                 pid=fork ();
406                 if(pid==-1) {
407                         g_critical (G_GNUC_PRETTY_FUNCTION ": fork error: %s",
408                                     strerror (errno));
409                         _wapi_shm_destroy ();
410                         return(FALSE);
411                 } else if (pid==0) {
412                         int i;
413                         
414                         /* child */
415                         setsid ();
416                         
417                         /* FIXME: Set process title to something
418                          * informative
419                          */
420
421                         /* Start the daemon with a clean sheet of file
422                          * descriptors
423                          */
424                         for(i=3; i<getdtablesize (); i++) {
425                                 close (i);
426                         }
427                         
428                         /* _wapi_daemon_main() does not return */
429                         _wapi_daemon_main (*data, *scratch);
430                         
431                         /* But just in case... */
432                         (*data)->daemon_running=DAEMON_DIED_AT_STARTUP;
433                         exit (-1);
434                 }
435                 /* parent carries on */
436 #ifdef DEBUG
437                 g_message (G_GNUC_PRETTY_FUNCTION ": Daemon pid %d", pid);
438 #endif
439 #endif /* !VALGRINDING */
440         }
441                 
442         for(tries=0; (*data)->daemon_running==DAEMON_STARTING && tries < 100;
443             tries++) {
444                 /* wait for the daemon to sort itself out.  To be
445                  * completely safe, we should have a timeout before
446                  * giving up.
447                  */
448                 struct timespec sleepytime;
449                         
450                 sleepytime.tv_sec=0;
451                 sleepytime.tv_nsec=10000000;    /* 10ms */
452                         
453                 nanosleep (&sleepytime, NULL);
454         }
455         if(tries==100 && (*data)->daemon_running==DAEMON_STARTING) {
456                 /* Daemon didnt get going */
457                 struct timespec sleepytime;
458                         
459                 /* Something must have gone wrong, so delete the
460                  * shared segments and try again.
461                  */
462                 _wapi_shm_destroy ();
463
464                 /* Daemon didn't get going, give it a few ms and try
465                  * again.
466                  */
467                 
468                 munmap (*data, data_size);
469                 munmap (*scratch, scratch_size);
470                 
471                 if(closing_tries++ == 5) {
472                         /* Still can't get going, so bail out */
473                         g_warning ("The handle daemon didnt start up properly");
474                         return(FALSE);
475                 }
476                 
477                 sleepytime.tv_sec=0;
478                 sleepytime.tv_nsec=10000000;    /* 10ms */
479                         
480                 nanosleep (&sleepytime, NULL);
481                 goto map_again;
482         }
483         
484         if((*data)->daemon_running==DAEMON_DIED_AT_STARTUP) {
485                 /* Oh dear, the daemon had an error starting up */
486                 if(data_created==TRUE) {
487                         _wapi_shm_destroy ();
488                 }
489                 g_warning ("Handle daemon failed to start");
490                 return(FALSE);
491         }
492
493         /* Do some sanity checking on the shared memory we
494          * attached
495          */
496         if(((*data)->daemon_running!=DAEMON_RUNNING) ||
497 #ifdef NEED_LINK_UNLINK
498            (strncmp ((*data)->daemon, "/tmp/mono-handle-daemon-",
499                      24)!=0)) {
500 #else
501            (strncmp ((*data)->daemon+1, "mono-handle-daemon-", 19)!=0)) {
502 #endif
503                 g_warning ("Shared memory sanity check failed.");
504                 g_warning("status: %d", (*data)->daemon_running);
505 #ifdef NEED_LINK_UNLINK
506                 g_warning("daemon: [%s]", (*data)->daemon);
507 #else
508                 g_warning("daemon: [%s]", (*data)->daemon+1);
509 #endif
510                 return(FALSE);
511         }
512                 
513         /* From now on, it's up to the daemon to delete the shared
514          * memory segment
515          */
516         
517         return(TRUE);
518 }
519
520 void _wapi_shm_destroy (void)
521 {
522 #ifndef DISABLE_SHARED_HANDLES
523 #ifdef DEBUG
524         g_message (G_GNUC_PRETTY_FUNCTION ": unlinking shared data");
525 #endif
526         /* Only delete the first segments.  The daemon will destroy
527          * any others when it exits
528          */
529         unlink (_wapi_shm_file (WAPI_SHM_DATA, 0));
530         unlink (_wapi_shm_file (WAPI_SHM_SCRATCH, 0));
531 #endif /* DISABLE_SHARED_HANDLES */
532 }
533