New test.
[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 #ifdef NEXT_VERSION_INC
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 #endif
301         
302         defs.array = def_vals;
303         
304         /* Temporarily attach the shared data so we can read the
305          * semaphore key.  We release this mapping and attach again
306          * after getting the semaphores to avoid a race condition
307          * where a terminating process can delete the shared files
308          * between a new process attaching the file and getting access
309          * to the semaphores (which increments the process count,
310          * preventing destruction of the shared data...)
311          */
312         tmp_shared = _wapi_shm_attach (WAPI_SHM_DATA);
313         g_assert (tmp_shared != NULL);
314         
315         key = ftok (_wapi_shm_file (WAPI_SHM_DATA), 'M');
316
317 again:
318         retries++;
319         oldkey = tmp_shared->sem_key;
320
321         if (oldkey == 0) {
322 #ifdef DEBUG
323                 g_message ("%s: Creating with new key (0x%x)", __func__, key);
324 #endif
325
326                 /* The while loop attempts to make some sense of the
327                  * bonkers 'think of a random number' method of
328                  * picking a key without collision with other
329                  * applications
330                  */
331                 while ((_wapi_sem_id = semget (key, _WAPI_SHARED_SEM_COUNT,
332                                                IPC_CREAT | IPC_EXCL | 0600)) == -1) {
333                         if (errno == ENOMEM) {
334                                 g_critical ("%s: semget error: %s", __func__,
335                                             g_strerror (errno));
336                         } else if (errno == ENOSPC) {
337                                 g_critical ("%s: semget error: %s.  Try deleting some semaphores with ipcs and ipcrm", __func__, g_strerror (errno));
338                         } else if (errno != EEXIST) {
339                                 if (retries > 3)
340                                         g_warning ("%s: semget error: %s key 0x%x - trying again", __func__,
341                                                         g_strerror (errno), key);
342                         }
343                         
344                         key++;
345 #ifdef DEBUG
346                         g_message ("%s: Got (%s), trying with new key (0x%x)",
347                                    __func__, g_strerror (errno), key);
348 #endif
349                 }
350                 /* Got a semaphore array, so initialise it and install
351                  * the key into the shared memory
352                  */
353                 
354                 if (semctl (_wapi_sem_id, 0, SETALL, defs) == -1) {
355                         if (retries > 3)
356                                 g_warning ("%s: semctl init error: %s - trying again", __func__, g_strerror (errno));
357
358                         /* Something went horribly wrong, so try
359                          * getting a new set from scratch
360                          */
361                         semctl (_wapi_sem_id, 0, IPC_RMID);
362                         goto again;
363                 }
364
365                 if (InterlockedCompareExchange (&tmp_shared->sem_key,
366                                                 key, 0) != 0) {
367                         /* Someone else created one and installed the
368                          * key while we were working, so delete the
369                          * array we created and fall through to the
370                          * 'key already known' case.
371                          */
372                         semctl (_wapi_sem_id, 0, IPC_RMID);
373                         oldkey = tmp_shared->sem_key;
374                 } else {
375                         /* We've installed this semaphore set's key into
376                          * the shared memory
377                          */
378                         goto done;
379                 }
380         }
381         
382 #ifdef DEBUG
383         g_message ("%s: Trying with old key 0x%x", __func__, oldkey);
384 #endif
385
386         _wapi_sem_id = semget (oldkey, _WAPI_SHARED_SEM_COUNT, 0600);
387         if (_wapi_sem_id == -1) {
388                 if (retries > 3)
389                         g_warning ("%s: semget error opening old key 0x%x (%s) - trying again",
390                                         __func__, oldkey,g_strerror (errno));
391
392                 /* Someone must have deleted the semaphore set, so
393                  * blow away the bad key and try again
394                  */
395                 InterlockedCompareExchange (&tmp_shared->sem_key, 0, oldkey);
396                 
397                 goto again;
398         }
399
400   done:
401         /* Increment the usage count of this semaphore set */
402         thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
403         g_assert (thr_ret == 0);
404         
405 #ifdef DEBUG
406         g_message ("%s: Incrementing the process count (%d)", __func__, _wapi_getpid ());
407 #endif
408
409         /* We only ever _unlock_ this semaphore, letting the kernel
410          * restore (ie decrement) this unlock when this process exits.
411          * We lock another semaphore around it so we can serialise
412          * access when we're testing the value of this semaphore when
413          * we exit cleanly, so we can delete the whole semaphore set.
414          */
415         _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT);
416
417 #ifdef DEBUG
418         g_message ("%s: Process count is now %d (%d)", __func__, semctl (_wapi_sem_id, _WAPI_SHARED_SEM_PROCESS_COUNT, GETVAL), _wapi_getpid ());
419 #endif
420         
421         _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
422
423         munmap (tmp_shared, sizeof(struct _WapiHandleSharedLayout));
424 }
425
426 void _wapi_shm_semaphores_remove (void)
427 {
428         int thr_ret;
429         int proc_count;
430         
431 #ifdef DEBUG
432         g_message ("%s: Checking process count (%d)", __func__,
433                    _wapi_getpid ());
434 #endif
435         
436         thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
437         g_assert (thr_ret == 0);
438         
439         proc_count = semctl (_wapi_sem_id, _WAPI_SHARED_SEM_PROCESS_COUNT,
440                              GETVAL);
441 #ifdef NEXT_VERSION_INC
442         g_assert (proc_count > 0);
443         if (proc_count == 1) {
444 #else
445         /* Compatibility - the semaphore was initialised to '1' (which
446          * normally means 'unlocked'.  Instead of fixing that right
447          * now, which would mean a shared file version increment, just
448          * cope with the value starting too high for now.  Fix this
449          * next time I have to change the file version.
450          */
451         g_assert (proc_count > 1);
452         if (proc_count == 2) {
453 #endif
454                 /* Just us, so blow away the semaphores and the shared
455                  * files
456                  */
457 #ifdef DEBUG
458                 g_message ("%s: Removing semaphores! (%d)", __func__,
459                            _wapi_getpid ());
460 #endif
461
462                 semctl (_wapi_sem_id, 0, IPC_RMID);
463                 unlink (_wapi_shm_file (WAPI_SHM_DATA));
464                 unlink (_wapi_shm_file (WAPI_SHM_FILESHARE));
465         } else {
466                 /* "else" clause, because there's no point unlocking
467                  * the semaphore if we've just blown it away...
468                  */
469                 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
470         }
471 }
472
473 int _wapi_shm_sem_lock (int sem)
474 {
475         struct sembuf ops;
476         int ret;
477         
478 #ifdef DEBUG
479         g_message ("%s: locking sem %d", __func__, sem);
480 #endif
481
482         ops.sem_num = sem;
483         ops.sem_op = -1;
484         ops.sem_flg = SEM_UNDO;
485         
486   retry:
487         do {
488                 ret = semop (_wapi_sem_id, &ops, 1);
489         } while (ret == -1 && errno == EINTR);
490
491         if (ret == -1) {
492                 /* EINVAL covers the case when the semaphore was
493                  * deleted before we started the semop
494                  */
495                 if (errno == EIDRM || errno == EINVAL) {
496                         /* Someone blew away this semaphore set, so
497                          * get a new one and try again
498                          */
499 #ifdef DEBUG
500                         g_message ("%s: Reinitialising the semaphores!",
501                                    __func__);
502 #endif
503
504                         _wapi_shm_semaphores_init ();
505                         goto retry;
506                 }
507                 
508                 /* Turn this into a pthreads-style return value */
509                 ret = errno;
510         }
511         
512 #ifdef DEBUG
513         g_message ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
514 #endif
515         
516         return(ret);
517 }
518
519 int _wapi_shm_sem_trylock (int sem)
520 {
521         struct sembuf ops;
522         int ret;
523         
524 #ifdef DEBUG
525         g_message ("%s: trying to lock sem %d", __func__, sem);
526 #endif
527         
528         ops.sem_num = sem;
529         ops.sem_op = -1;
530         ops.sem_flg = IPC_NOWAIT | SEM_UNDO;
531         
532   retry:
533         do {
534                 ret = semop (_wapi_sem_id, &ops, 1);
535         } while (ret == -1 && errno == EINTR);
536
537         if (ret == -1) {
538                 /* EINVAL covers the case when the semaphore was
539                  * deleted before we started the semop
540                  */
541                 if (errno == EIDRM || errno == EINVAL) {
542                         /* Someone blew away this semaphore set, so
543                          * get a new one and try again
544                          */
545 #ifdef DEBUG
546                         g_message ("%s: Reinitialising the semaphores!",
547                                    __func__);
548 #endif
549
550                         _wapi_shm_semaphores_init ();
551                         goto retry;
552                 }
553                 
554                 /* Turn this into a pthreads-style return value */
555                 ret = errno;
556         }
557         
558         if (ret == EAGAIN) {
559                 /* But pthreads uses this code instead */
560                 ret = EBUSY;
561         }
562         
563 #ifdef DEBUG
564         g_message ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
565 #endif
566         
567         return(ret);
568 }
569
570 int _wapi_shm_sem_unlock (int sem)
571 {
572         struct sembuf ops;
573         int ret;
574         
575 #ifdef DEBUG
576         g_message ("%s: unlocking sem %d", __func__, sem);
577 #endif
578         
579         ops.sem_num = sem;
580         ops.sem_op = 1;
581         ops.sem_flg = SEM_UNDO;
582         
583   retry:
584         do {
585                 ret = semop (_wapi_sem_id, &ops, 1);
586         } while (ret == -1 && errno == EINTR);
587
588         if (ret == -1) {
589                 /* EINVAL covers the case when the semaphore was
590                  * deleted before we started the semop
591                  */
592                 if (errno == EIDRM || errno == EINVAL) {
593                         /* Someone blew away this semaphore set, so
594                          * get a new one and try again (we can't just
595                          * assume that the semaphore is now unlocked)
596                          */
597 #ifdef DEBUG
598                         g_message ("%s: Reinitialising the semaphores!",
599                                    __func__);
600 #endif
601
602                         _wapi_shm_semaphores_init ();
603                         goto retry;
604                 }
605                 
606                 /* Turn this into a pthreads-style return value */
607                 ret = errno;
608         }
609         
610 #ifdef DEBUG
611         g_message ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
612 #endif
613
614         return(ret);
615 }
616