Grasshopper project system now uses csproj extension
[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-2006 Novell, Inc.
8  */
9
10
11 #include <config.h>
12 #include <glib.h>
13 #include <stdio.h>
14 #include <fcntl.h>
15 #include <unistd.h>
16 #include <sys/mman.h>
17 #include <sys/types.h>
18 #include <sys/stat.h>
19 #include <errno.h>
20 #include <string.h>
21 #include <sys/ipc.h>
22 #include <sys/sem.h>
23 #include <sys/utsname.h>
24
25 #include <mono/io-layer/wapi.h>
26 #include <mono/io-layer/wapi-private.h>
27 #include <mono/io-layer/shared.h>
28 #include <mono/io-layer/handles-private.h>
29
30 #undef DEBUG
31
32 static gchar *_wapi_shm_file (_wapi_shm_t type)
33 {
34         static gchar file[_POSIX_PATH_MAX];
35         gchar *name = NULL, *filename, *dir, *wapi_dir;
36         gchar machine_name[256];
37         const gchar *fake_name;
38         struct utsname ubuf;
39         int ret;
40         int len;
41         
42         ret = uname (&ubuf);
43         if (ret == -1) {
44                 ubuf.machine[0] = '\0';
45                 ubuf.sysname[0] = '\0';
46         } else {
47                 g_strdelimit (ubuf.sysname, "/", '_');
48                 g_strdelimit (ubuf.machine, "/", '_');
49         }
50
51         fake_name = g_getenv ("MONO_SHARED_HOSTNAME");
52         if (fake_name == NULL) {
53                 if (gethostname(machine_name, sizeof(machine_name)) != 0)
54                         machine_name[0] = '\0';
55         } else {
56                 len = MIN (strlen (fake_name), sizeof (machine_name) - 1);
57                 strncpy (machine_name, fake_name, len);
58                 machine_name [len] = '\0';
59         }
60         
61         switch (type) {
62         case WAPI_SHM_DATA:
63                 name = g_strdup_printf ("shared_data-%s-%s-%s-%d-%d-%d",
64                                         machine_name, ubuf.sysname,
65                                         ubuf.machine,
66                                         (int) sizeof(struct _WapiHandleShared),
67                                         _WAPI_HANDLE_VERSION, 0);
68                 break;
69                 
70         case WAPI_SHM_FILESHARE:
71                 name = g_strdup_printf ("shared_fileshare-%s-%s-%s-%d-%d-%d",
72                                         machine_name, ubuf.sysname,
73                                         ubuf.machine,
74                                         (int) sizeof(struct _WapiFileShare),
75                                         _WAPI_HANDLE_VERSION, 0);
76                 break;
77         }
78
79         /* I don't know how nfs affects mmap.  If mmap() of files on
80          * nfs mounts breaks, then there should be an option to set
81          * the directory.
82          */
83         wapi_dir = getenv ("MONO_SHARED_DIR");
84         if (wapi_dir == NULL) {
85                 filename = g_build_filename (g_get_home_dir (), ".wapi", name,
86                                              NULL);
87         } else {
88                 filename = g_build_filename (wapi_dir, ".wapi", name, NULL);
89         }
90         g_free (name);
91
92         g_snprintf (file, _POSIX_PATH_MAX, "%s", filename);
93         g_free (filename);
94                 
95         /* No need to check if the dir already exists or check
96          * mkdir() errors, because on any error the open() call will
97          * report the problem.
98          */
99         dir = g_path_get_dirname (file);
100         mkdir (dir, 0755);
101         g_free (dir);
102         
103         return(file);
104 }
105
106 static int _wapi_shm_file_open (const gchar *filename, guint32 wanted_size)
107 {
108         int fd;
109         struct stat statbuf;
110         int ret, tries = 0;
111         gboolean created = FALSE;
112         
113 try_again:
114         if (tries++ > 10) {
115                 /* Just give up */
116                 return (-1);
117         } else if (tries > 5) {
118                 /* Break out of a loop */
119                 unlink (filename);
120         }
121         
122         /* No O_CREAT yet, because we need to initialise the file if
123          * we have to create it.
124          */
125         fd = open (filename, O_RDWR, 0600);
126         if (fd == -1 && errno == ENOENT) {
127                 /* OK, its up to us to create it.  O_EXCL to avoid a
128                  * race condition where two processes can
129                  * simultaneously try and create the file
130                  */
131                 fd = open (filename, O_CREAT|O_EXCL|O_RDWR, 0600);
132                 if (fd == -1 && errno == EEXIST) {
133                         /* It's possible that the file was created in
134                          * between finding it didn't exist, and trying
135                          * to create it.  Just try opening it again
136                          */
137                         goto try_again;
138                 } else if (fd == -1) {
139                         g_critical ("%s: shared file [%s] open error: %s",
140                                     __func__, filename, g_strerror (errno));
141                         return(-1);
142                 } else {
143                         /* We created the file, so we need to expand
144                          * the file.
145                          *
146                          * (wanted_size-1, because we're about to
147                          * write the other byte to actually expand the
148                          * file.)
149                          */
150                         if (lseek (fd, wanted_size-1, SEEK_SET) == -1) {
151                                 g_critical ("%s: shared file [%s] lseek error: %s", __func__, filename, g_strerror (errno));
152                                 close (fd);
153                                 unlink (filename);
154                                 return(-1);
155                         }
156                         
157                         do {
158                                 ret = write (fd, "", 1);
159                         } while (ret == -1 && errno == EINTR);
160                                 
161                         if (ret == -1) {
162                                 g_critical ("%s: shared file [%s] write error: %s", __func__, filename, g_strerror (errno));
163                                 close (fd);
164                                 unlink (filename);
165                                 return(-1);
166                         }
167                         
168                         created = TRUE;
169
170                         /* The contents of the file is set to all
171                          * zero, because it is opened up with lseek,
172                          * so we don't need to do any more
173                          * initialisation here
174                          */
175                 }
176         } else if (fd == -1) {
177                 g_critical ("%s: shared file [%s] open error: %s", __func__,
178                             filename, g_strerror (errno));
179                 return(-1);
180         }
181         
182         /* Use stat to find the file size (instead of hard coding it)
183          * because we can expand the file later if needed (for more
184          * handles or scratch space.)
185          */
186         if (fstat (fd, &statbuf) == -1) {
187                 g_critical ("%s: fstat error: %s", __func__,
188                             g_strerror (errno));
189                 if (created == TRUE) {
190                         unlink (filename);
191                 }
192                 close (fd);
193                 return(-1);
194         }
195
196         if (statbuf.st_size < wanted_size) {
197                 close (fd);
198                 if (created == TRUE) {
199 #ifdef HAVE_LARGE_FILE_SUPPORT
200                         /* Keep gcc quiet... */
201                         g_critical ("%s: shared file [%s] is not big enough! (found %lld, need %d bytes)", __func__, filename, statbuf.st_size, wanted_size);
202 #else
203                         g_critical ("%s: shared file [%s] is not big enough! (found %ld, need %d bytes)", __func__, filename, statbuf.st_size, wanted_size);
204 #endif
205                         unlink (filename);
206                         return(-1);
207                 } else {
208                         /* We didn't create it, so just try opening it again */
209                         _wapi_handle_spin (100);
210                         goto try_again;
211                 }
212         }
213         
214         return(fd);
215 }
216
217 /*
218  * _wapi_shm_attach:
219  * @success: Was it a success
220  *
221  * Attach to the shared memory file or create it if it did not exist.
222  * Returns the memory area the file was mmapped to.
223  */
224 gpointer _wapi_shm_attach (_wapi_shm_t type)
225 {
226         gpointer shm_seg;
227         int fd;
228         struct stat statbuf;
229         gchar *filename=_wapi_shm_file (type);
230         guint32 size;
231         
232         switch(type) {
233         case WAPI_SHM_DATA:
234                 size = sizeof(struct _WapiHandleSharedLayout);
235                 break;
236                 
237         case WAPI_SHM_FILESHARE:
238                 size = sizeof(struct _WapiFileShareLayout);
239                 break;
240         }
241         
242         fd = _wapi_shm_file_open (filename, size);
243         if (fd == -1) {
244                 g_critical ("%s: shared file [%s] open error", __func__,
245                             filename);
246                 return(NULL);
247         }
248         
249         if (fstat (fd, &statbuf)==-1) {
250                 g_critical ("%s: fstat error: %s", __func__,
251                             g_strerror (errno));
252                 close (fd);
253                 return(NULL);
254         }
255         
256         shm_seg = mmap (NULL, statbuf.st_size, PROT_READ|PROT_WRITE,
257                         MAP_SHARED, fd, 0);
258         if (shm_seg == MAP_FAILED) {
259                 shm_seg = mmap (NULL, statbuf.st_size, PROT_READ|PROT_WRITE,
260                         MAP_PRIVATE, fd, 0);
261                 if (shm_seg == MAP_FAILED) {
262                         g_critical ("%s: mmap error: %s", __func__, g_strerror (errno));
263                         close (fd);
264                         return(NULL);
265                 }
266         }
267                 
268         close (fd);
269         return(shm_seg);
270 }
271
272 void _wapi_shm_semaphores_init ()
273 {
274         key_t key;
275         key_t oldkey;
276         int thr_ret;
277         struct _WapiHandleSharedLayout *tmp_shared;
278         
279         /* Yet more barmy API - this union is a well-defined parameter
280          * in a syscall, yet I still have to define it here as it
281          * doesn't appear in a header
282          */
283         union semun {
284                 int val;
285                 struct semid_ds *buf;
286                 ushort *array;
287         } defs;
288         ushort def_vals[_WAPI_SHARED_SEM_COUNT];
289         int i;
290         int retries = 0;
291         
292         for (i = 0; i < _WAPI_SHARED_SEM_COUNT; i++) {
293                 def_vals[i] = 1;
294         }
295
296         /* Process count must start at '0' - the 1 for all the others
297          * sets the semaphore to "unlocked"
298          */
299         def_vals[_WAPI_SHARED_SEM_PROCESS_COUNT] = 0;
300         
301         defs.array = def_vals;
302         
303         /* Temporarily attach the shared data so we can read the
304          * semaphore key.  We release this mapping and attach again
305          * after getting the semaphores to avoid a race condition
306          * where a terminating process can delete the shared files
307          * between a new process attaching the file and getting access
308          * to the semaphores (which increments the process count,
309          * preventing destruction of the shared data...)
310          */
311         tmp_shared = _wapi_shm_attach (WAPI_SHM_DATA);
312         g_assert (tmp_shared != NULL);
313         
314         key = ftok (_wapi_shm_file (WAPI_SHM_DATA), 'M');
315
316 again:
317         retries++;
318         oldkey = tmp_shared->sem_key;
319
320         if (oldkey == 0) {
321 #ifdef DEBUG
322                 g_message ("%s: Creating with new key (0x%x)", __func__, key);
323 #endif
324
325                 /* The while loop attempts to make some sense of the
326                  * bonkers 'think of a random number' method of
327                  * picking a key without collision with other
328                  * applications
329                  */
330                 while ((_wapi_sem_id = semget (key, _WAPI_SHARED_SEM_COUNT,
331                                                IPC_CREAT | IPC_EXCL | 0600)) == -1) {
332                         if (errno == ENOMEM) {
333                                 g_error ("%s: semget error: %s", __func__,
334                                             g_strerror (errno));
335                         } else if (errno == ENOSPC) {
336                                 g_error ("%s: semget error: %s.  Try deleting some semaphores with ipcs and ipcrm\nor increase the maximum number of semaphore in the system.", __func__, g_strerror (errno));
337                         } else if (errno != EEXIST) {
338                                 if (retries > 3)
339                                         g_warning ("%s: semget error: %s key 0x%x - trying again", __func__,
340                                                         g_strerror (errno), key);
341                         }
342                         
343                         key++;
344 #ifdef DEBUG
345                         g_message ("%s: Got (%s), trying with new key (0x%x)",
346                                    __func__, g_strerror (errno), key);
347 #endif
348                 }
349                 /* Got a semaphore array, so initialise it and install
350                  * the key into the shared memory
351                  */
352                 
353                 if (semctl (_wapi_sem_id, 0, SETALL, defs) == -1) {
354                         if (retries > 3)
355                                 g_warning ("%s: semctl init error: %s - trying again", __func__, g_strerror (errno));
356
357                         /* Something went horribly wrong, so try
358                          * getting a new set from scratch
359                          */
360                         semctl (_wapi_sem_id, 0, IPC_RMID);
361                         goto again;
362                 }
363
364                 if (InterlockedCompareExchange (&tmp_shared->sem_key,
365                                                 key, 0) != 0) {
366                         /* Someone else created one and installed the
367                          * key while we were working, so delete the
368                          * array we created and fall through to the
369                          * 'key already known' case.
370                          */
371                         semctl (_wapi_sem_id, 0, IPC_RMID);
372                         oldkey = tmp_shared->sem_key;
373                 } else {
374                         /* We've installed this semaphore set's key into
375                          * the shared memory
376                          */
377                         goto done;
378                 }
379         }
380         
381 #ifdef DEBUG
382         g_message ("%s: Trying with old key 0x%x", __func__, oldkey);
383 #endif
384
385         _wapi_sem_id = semget (oldkey, _WAPI_SHARED_SEM_COUNT, 0600);
386         if (_wapi_sem_id == -1) {
387                 if (retries > 3)
388                         g_warning ("%s: semget error opening old key 0x%x (%s) - trying again",
389                                         __func__, oldkey,g_strerror (errno));
390
391                 /* Someone must have deleted the semaphore set, so
392                  * blow away the bad key and try again
393                  */
394                 InterlockedCompareExchange (&tmp_shared->sem_key, 0, oldkey);
395                 
396                 goto again;
397         }
398
399   done:
400         /* Increment the usage count of this semaphore set */
401         thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
402         g_assert (thr_ret == 0);
403         
404 #ifdef DEBUG
405         g_message ("%s: Incrementing the process count (%d)", __func__, _wapi_getpid ());
406 #endif
407
408         /* We only ever _unlock_ this semaphore, letting the kernel
409          * restore (ie decrement) this unlock when this process exits.
410          * We lock another semaphore around it so we can serialise
411          * access when we're testing the value of this semaphore when
412          * we exit cleanly, so we can delete the whole semaphore set.
413          */
414         _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT);
415
416 #ifdef DEBUG
417         g_message ("%s: Process count is now %d (%d)", __func__, semctl (_wapi_sem_id, _WAPI_SHARED_SEM_PROCESS_COUNT, GETVAL), _wapi_getpid ());
418 #endif
419         
420         _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
421
422         munmap (tmp_shared, sizeof(struct _WapiHandleSharedLayout));
423 }
424
425 void _wapi_shm_semaphores_remove (void)
426 {
427         int thr_ret;
428         int proc_count;
429         
430 #ifdef DEBUG
431         g_message ("%s: Checking process count (%d)", __func__,
432                    _wapi_getpid ());
433 #endif
434         
435         thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
436         g_assert (thr_ret == 0);
437         
438         proc_count = semctl (_wapi_sem_id, _WAPI_SHARED_SEM_PROCESS_COUNT,
439                              GETVAL);
440
441         g_assert (proc_count > 0);
442         if (proc_count == 1) {
443                 /* Just us, so blow away the semaphores and the shared
444                  * files
445                  */
446 #ifdef DEBUG
447                 g_message ("%s: Removing semaphores! (%d)", __func__,
448                            _wapi_getpid ());
449 #endif
450
451                 semctl (_wapi_sem_id, 0, IPC_RMID);
452                 unlink (_wapi_shm_file (WAPI_SHM_DATA));
453                 unlink (_wapi_shm_file (WAPI_SHM_FILESHARE));
454         } else {
455                 /* "else" clause, because there's no point unlocking
456                  * the semaphore if we've just blown it away...
457                  */
458                 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
459         }
460 }
461
462 int _wapi_shm_sem_lock (int sem)
463 {
464         struct sembuf ops;
465         int ret;
466         
467 #ifdef DEBUG
468         g_message ("%s: locking sem %d", __func__, sem);
469 #endif
470
471         ops.sem_num = sem;
472         ops.sem_op = -1;
473         ops.sem_flg = SEM_UNDO;
474         
475   retry:
476         do {
477                 ret = semop (_wapi_sem_id, &ops, 1);
478         } while (ret == -1 && errno == EINTR);
479
480         if (ret == -1) {
481                 /* EINVAL covers the case when the semaphore was
482                  * deleted before we started the semop
483                  */
484                 if (errno == EIDRM || errno == EINVAL) {
485                         /* Someone blew away this semaphore set, so
486                          * get a new one and try again
487                          */
488 #ifdef DEBUG
489                         g_message ("%s: Reinitialising the semaphores!",
490                                    __func__);
491 #endif
492
493                         _wapi_shm_semaphores_init ();
494                         goto retry;
495                 }
496                 
497                 /* Turn this into a pthreads-style return value */
498                 ret = errno;
499         }
500         
501 #ifdef DEBUG
502         g_message ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
503 #endif
504         
505         return(ret);
506 }
507
508 int _wapi_shm_sem_trylock (int sem)
509 {
510         struct sembuf ops;
511         int ret;
512         
513 #ifdef DEBUG
514         g_message ("%s: trying to lock sem %d", __func__, sem);
515 #endif
516         
517         ops.sem_num = sem;
518         ops.sem_op = -1;
519         ops.sem_flg = IPC_NOWAIT | SEM_UNDO;
520         
521   retry:
522         do {
523                 ret = semop (_wapi_sem_id, &ops, 1);
524         } while (ret == -1 && errno == EINTR);
525
526         if (ret == -1) {
527                 /* EINVAL covers the case when the semaphore was
528                  * deleted before we started the semop
529                  */
530                 if (errno == EIDRM || errno == EINVAL) {
531                         /* Someone blew away this semaphore set, so
532                          * get a new one and try again
533                          */
534 #ifdef DEBUG
535                         g_message ("%s: Reinitialising the semaphores!",
536                                    __func__);
537 #endif
538
539                         _wapi_shm_semaphores_init ();
540                         goto retry;
541                 }
542                 
543                 /* Turn this into a pthreads-style return value */
544                 ret = errno;
545         }
546         
547         if (ret == EAGAIN) {
548                 /* But pthreads uses this code instead */
549                 ret = EBUSY;
550         }
551         
552 #ifdef DEBUG
553         g_message ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
554 #endif
555         
556         return(ret);
557 }
558
559 int _wapi_shm_sem_unlock (int sem)
560 {
561         struct sembuf ops;
562         int ret;
563         
564 #ifdef DEBUG
565         g_message ("%s: unlocking sem %d", __func__, sem);
566 #endif
567         
568         ops.sem_num = sem;
569         ops.sem_op = 1;
570         ops.sem_flg = SEM_UNDO;
571         
572   retry:
573         do {
574                 ret = semop (_wapi_sem_id, &ops, 1);
575         } while (ret == -1 && errno == EINTR);
576
577         if (ret == -1) {
578                 /* EINVAL covers the case when the semaphore was
579                  * deleted before we started the semop
580                  */
581                 if (errno == EIDRM || errno == EINVAL) {
582                         /* Someone blew away this semaphore set, so
583                          * get a new one and try again (we can't just
584                          * assume that the semaphore is now unlocked)
585                          */
586 #ifdef DEBUG
587                         g_message ("%s: Reinitialising the semaphores!",
588                                    __func__);
589 #endif
590
591                         _wapi_shm_semaphores_init ();
592                         goto retry;
593                 }
594                 
595                 /* Turn this into a pthreads-style return value */
596                 ret = errno;
597         }
598         
599 #ifdef DEBUG
600         g_message ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
601 #endif
602
603         return(ret);
604 }
605