Remove excessive shortcut key matching in ToolStrip
[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 <sys/types.h>
16 #include <sys/stat.h>
17 #include <errno.h>
18 #include <string.h>
19 #include <unistd.h>
20
21 #if defined(HAVE_SYS_SEM_H) && !(defined(__native_client__) && defined(__GLIBC__))
22 #  include <sys/sem.h>
23 #else
24 #  define DISABLE_SHARED_HANDLES
25 #endif
26
27 #ifndef DISABLE_SHARED_HANDLES
28 #  include <sys/mman.h>
29 #  include <sys/ipc.h>
30 #  ifdef HAVE_SYS_UTSNAME_H
31 #    include <sys/utsname.h>
32 #  endif
33 #endif
34
35 #include <mono/io-layer/wapi.h>
36 #include <mono/io-layer/wapi-private.h>
37 #include <mono/io-layer/shared.h>
38 #include <mono/io-layer/handles-private.h>
39
40 #define DEBUGLOG(...)
41 //#define DEBUGLOG(...) g_message(__VA_ARGS__);
42
43 // Semaphores used when no-shared-memory use is in use
44
45 static mono_mutex_t noshm_sems[_WAPI_SHARED_SEM_COUNT];
46
47 gboolean _wapi_shm_disabled = TRUE;
48
49 static gpointer wapi_storage [16];
50
51 static void
52 noshm_semaphores_init (void)
53 {
54         int i;
55
56         for (i = 0; i < _WAPI_SHARED_SEM_COUNT; i++) 
57                 mono_mutex_init (&noshm_sems [i]);
58 }
59
60 static int
61 noshm_sem_lock (int sem)
62 {
63         int ret;
64         
65         DEBUGLOG ("%s: locking nosem %d", __func__, sem);
66         
67         ret = mono_mutex_lock (&noshm_sems[sem]);
68         
69         return ret;
70 }
71
72 static int
73 noshm_sem_trylock (int sem)
74 {
75         int ret;
76         
77         DEBUGLOG ("%s: trying to lock nosem %d", __func__, sem);
78         
79         ret = mono_mutex_trylock (&noshm_sems[sem]);
80         
81         return ret;
82 }
83
84 static int
85 noshm_sem_unlock (int sem)
86 {
87         int ret;
88         
89         DEBUGLOG ("%s: unlocking nosem %d", __func__, sem);
90         
91         ret = mono_mutex_unlock (&noshm_sems[sem]);
92         
93         return ret;
94 }
95
96 #ifdef DISABLE_SHARED_HANDLES
97 void
98 _wapi_shm_semaphores_init (void)
99 {
100         noshm_semaphores_init ();
101 }
102
103 void
104 _wapi_shm_semaphores_remove (void)
105 {
106         /* Nothing */
107 }
108
109 int
110 _wapi_shm_sem_lock (int sem)
111 {
112         return noshm_sem_lock (sem);
113 }
114
115 int
116 _wapi_shm_sem_trylock (int sem)
117 {
118         return noshm_sem_trylock (sem);
119 }
120
121 int
122 _wapi_shm_sem_unlock (int sem)
123 {
124         return noshm_sem_unlock (sem);
125 }
126
127 gpointer
128 _wapi_shm_attach (_wapi_shm_t type)
129 {
130         gpointer res;
131
132         switch(type) {
133         case WAPI_SHM_DATA:
134                 res = g_malloc0 (sizeof(struct _WapiHandleSharedLayout));
135                 break;
136         case WAPI_SHM_FILESHARE:
137                 res = g_malloc0 (sizeof(struct _WapiFileShareLayout));
138                 break;
139         default:
140                 g_error ("Invalid type in _wapi_shm_attach ()");
141                 return NULL;
142         }
143
144         wapi_storage [type] = res;
145         return res;
146 }
147
148 void
149 _wapi_shm_detach (_wapi_shm_t type)
150 {
151         g_free (wapi_storage [type]);
152 }
153
154 gboolean
155 _wapi_shm_enabled (void)
156 {
157         return FALSE;
158 }
159
160 #else
161 /*
162  * Use POSIX shared memory if possible, it is simpler, and it has the advantage that 
163  * writes to the shared area does not need to be written to disk, avoiding spinning up 
164  * the disk every x secs on laptops.
165  */
166 #ifdef HAVE_SHM_OPEN
167 #define USE_SHM 1
168 #endif
169
170 static gchar *
171 _wapi_shm_base_name (_wapi_shm_t type)
172 {
173         gchar *name = NULL;
174         gchar machine_name[256];
175         const gchar *fake_name;
176         struct utsname ubuf;
177         int ret;
178         int len;
179         
180         ret = uname (&ubuf);
181         if (ret == -1) {
182                 ubuf.machine[0] = '\0';
183                 ubuf.sysname[0] = '\0';
184         } else {
185                 g_strdelimit (ubuf.sysname, "/", '_');
186                 g_strdelimit (ubuf.machine, "/", '_');
187         }
188
189         fake_name = g_getenv ("MONO_SHARED_HOSTNAME");
190         if (fake_name == NULL) {
191                 if (gethostname(machine_name, sizeof(machine_name)) != 0)
192                         machine_name[0] = '\0';
193         } else {
194                 len = MIN (strlen (fake_name), sizeof (machine_name) - 1);
195                 strncpy (machine_name, fake_name, len);
196                 machine_name [len] = '\0';
197         }
198         
199         switch (type) {
200         case WAPI_SHM_DATA:
201                 name = g_strdup_printf ("shared_data-%s-%s-%s-%d-%d-%d",
202                                         machine_name, ubuf.sysname,
203                                         ubuf.machine,
204                                         (int) sizeof(struct _WapiHandleShared),
205                                         _WAPI_HANDLE_VERSION, 0);
206                 break;
207                 
208         case WAPI_SHM_FILESHARE:
209                 name = g_strdup_printf ("shared_fileshare-%s-%s-%s-%d-%d-%d",
210                                         machine_name, ubuf.sysname,
211                                         ubuf.machine,
212                                         (int) sizeof(struct _WapiFileShare),
213                                         _WAPI_HANDLE_VERSION, 0);
214                 break;
215         }
216
217         return name;
218 }
219
220 #ifdef USE_SHM
221
222 static gchar *_wapi_shm_shm_name (_wapi_shm_t type)
223 {
224         char *base_name = _wapi_shm_base_name (type);
225
226         /* Also add the uid to avoid permission problems */
227         char *res = g_strdup_printf ("/mono-shared-%d-%s", getuid (), base_name);
228
229         g_free (base_name);
230
231         return res;
232 }
233
234 static int
235 _wapi_shm_open (const char *filename, int size)
236 {
237         int fd;
238
239         fd = shm_open (filename, O_CREAT|O_RDWR, S_IRUSR|S_IWUSR|S_IRGRP);
240         if (fd == -1)
241                 /* Maybe /dev/shm is not mounted */
242                 return -1;
243         if (ftruncate (fd, size) != 0) {
244                 perror ("_wapi_shm_open (): ftruncate ()");
245                 g_assert_not_reached ();
246         }
247
248         return fd;
249 }
250
251 #endif
252
253 static gchar *
254 _wapi_shm_file (_wapi_shm_t type)
255 {
256         static gchar file[_POSIX_PATH_MAX];
257         gchar *name = NULL, *filename;
258         const gchar *wapi_dir;
259
260         name = _wapi_shm_base_name (type);
261
262         /* I don't know how nfs affects mmap.  If mmap() of files on
263          * nfs mounts breaks, then there should be an option to set
264          * the directory.
265          */
266         wapi_dir = g_getenv ("MONO_SHARED_DIR");
267         if (wapi_dir == NULL) {
268                 filename = g_build_filename (g_get_home_dir (), ".wapi", name,
269                                              NULL);
270         } else {
271                 filename = g_build_filename (wapi_dir, ".wapi", name, NULL);
272         }
273         g_free (name);
274
275         g_snprintf (file, _POSIX_PATH_MAX, "%s", filename);
276         g_free (filename);
277         
278         return file;
279 }
280
281 static int
282 _wapi_shm_file_open (const gchar *filename, guint32 wanted_size)
283 {
284         int fd;
285         struct stat statbuf;
286         int ret, tries = 0;
287         gboolean created = FALSE;
288         mode_t oldmask;
289         gchar *dir;
290                 
291         /* No need to check if the dir already exists or check
292          * mkdir() errors, because on any error the open() call will
293          * report the problem.
294          */
295         dir = g_path_get_dirname (filename);
296         mkdir (dir, 0755);
297         g_free (dir);
298
299 try_again:
300         if (tries++ > 10) {
301                 /* Just give up */
302                 return (-1);
303         } else if (tries > 5) {
304                 /* Break out of a loop */
305                 unlink (filename);
306         }
307         
308         /* Make sure future processes can open the shared data files */
309         oldmask = umask (066);
310
311         /* No O_CREAT yet, because we need to initialise the file if
312          * we have to create it.
313          */
314         fd = open (filename, O_RDWR, 0600);
315         umask (oldmask);
316         
317         if (fd == -1 && errno == ENOENT) {
318                 /* OK, its up to us to create it.  O_EXCL to avoid a
319                  * race condition where two processes can
320                  * simultaneously try and create the file
321                  */
322                 oldmask = umask (066);
323                 fd = open (filename, O_CREAT|O_EXCL|O_RDWR, 0600);
324                 umask (oldmask);
325                 
326                 if (fd == -1 && errno == EEXIST) {
327                         /* It's possible that the file was created in
328                          * between finding it didn't exist, and trying
329                          * to create it.  Just try opening it again
330                          */
331                         goto try_again;
332                 } else if (fd == -1) {
333                         g_critical ("%s: shared file [%s] open error: %s",
334                                     __func__, filename, g_strerror (errno));
335                         return -1;
336                 } else {
337                         /* We created the file, so we need to expand
338                          * the file.
339                          *
340                          * (wanted_size-1, because we're about to
341                          * write the other byte to actually expand the
342                          * file.)
343                          */
344                         if (lseek (fd, wanted_size-1, SEEK_SET) == -1) {
345                                 g_critical ("%s: shared file [%s] lseek error: %s", __func__, filename, g_strerror (errno));
346                                 close (fd);
347                                 unlink (filename);
348                                 return -1;
349                         }
350                         
351                         do {
352                                 ret = write (fd, "", 1);
353                         } while (ret == -1 && errno == EINTR);
354                                 
355                         if (ret == -1) {
356                                 g_critical ("%s: shared file [%s] write error: %s", __func__, filename, g_strerror (errno));
357                                 close (fd);
358                                 unlink (filename);
359                                 return -1;
360                         }
361                         
362                         created = TRUE;
363
364                         /* The contents of the file is set to all
365                          * zero, because it is opened up with lseek,
366                          * so we don't need to do any more
367                          * initialisation here
368                          */
369                 }
370         } else if (fd == -1) {
371                 g_critical ("%s: shared file [%s] open error: %s", __func__,
372                             filename, g_strerror (errno));
373                 return -1;
374         }
375         
376         /* Use stat to find the file size (instead of hard coding it)
377          * because we can expand the file later if needed (for more
378          * handles or scratch space.)
379          */
380         if (fstat (fd, &statbuf) == -1) {
381                 g_critical ("%s: fstat error: %s", __func__,
382                             g_strerror (errno));
383                 if (created == TRUE) {
384                         unlink (filename);
385                 }
386                 close (fd);
387                 return -1;
388         }
389
390         if (statbuf.st_size < wanted_size) {
391                 close (fd);
392                 if (created == TRUE) {
393                         g_critical ("%s: shared file [%s] is not big enough! (found %ld, need %d bytes)", __func__, filename, (long)statbuf.st_size, wanted_size);
394                         unlink (filename);
395                         return -1;
396                 } else {
397                         /* We didn't create it, so just try opening it again */
398                         _wapi_handle_spin (100);
399                         goto try_again;
400                 }
401         }
402         
403         return fd;
404 }
405
406 gboolean
407 _wapi_shm_enabled (void)
408 {
409         static gboolean env_checked;
410
411         if (!env_checked) {
412                 if (g_getenv ("MONO_ENABLE_SHM"))
413                         _wapi_shm_disabled = FALSE;
414                 env_checked = TRUE;
415         }
416
417         return !_wapi_shm_disabled;
418 }
419
420 /*
421  * _wapi_shm_attach:
422  * @success: Was it a success
423  *
424  * Attach to the shared memory file or create it if it did not exist.
425  * Returns the memory area the file was mmapped to.
426  */
427 gpointer
428 _wapi_shm_attach (_wapi_shm_t type)
429 {
430         gpointer shm_seg;
431         int fd;
432         struct stat statbuf;
433         gchar *filename = _wapi_shm_file (type), *shm_name;
434         guint32 size;
435         
436         switch(type) {
437         case WAPI_SHM_DATA:
438                 size = sizeof(struct _WapiHandleSharedLayout);
439                 break;
440                 
441         case WAPI_SHM_FILESHARE:
442                 size = sizeof(struct _WapiFileShareLayout);
443                 break;
444         default:
445                 g_error ("Invalid type in _wapi_shm_attach ()");
446                 return NULL;
447         }
448
449         if (!_wapi_shm_enabled ()) {
450                 wapi_storage [type] = g_malloc0 (size);
451                 return wapi_storage [type];
452         }
453
454 #ifdef USE_SHM
455         shm_name = _wapi_shm_shm_name (type);
456         fd = _wapi_shm_open (shm_name, size);
457         g_free (shm_name);
458 #else
459         fd = -1;
460 #endif
461
462         /* Fall back to files if POSIX shm fails (for example, because /dev/shm is not mounted */
463         if (fd == -1)
464                 fd = _wapi_shm_file_open (filename, size);
465         if (fd == -1) {
466                 g_critical ("%s: shared file [%s] open error", __func__,
467                             filename);
468                 return NULL;
469         }
470
471         if (fstat (fd, &statbuf)==-1) {
472                 g_critical ("%s: fstat error: %s", __func__,
473                             g_strerror (errno));
474                 close (fd);
475                 return NULL;
476         }
477         
478         shm_seg = mmap (NULL, statbuf.st_size, PROT_READ|PROT_WRITE,
479                         MAP_SHARED, fd, 0);
480         if (shm_seg == MAP_FAILED) {
481                 shm_seg = mmap (NULL, statbuf.st_size, PROT_READ|PROT_WRITE,
482                         MAP_PRIVATE, fd, 0);
483                 if (shm_seg == MAP_FAILED) {
484                         g_critical ("%s: mmap error: %s", __func__, g_strerror (errno));
485                         close (fd);
486                         return NULL;
487                 }
488         }
489                 
490         close (fd);
491         return shm_seg;
492 }
493
494 void
495 _wapi_shm_detach (_wapi_shm_t type)
496 {
497         if (!_wapi_shm_enabled ())
498                 g_free (wapi_storage [type]);
499 }
500
501 static void
502 shm_semaphores_init (void)
503 {
504         key_t key;
505         key_t oldkey;
506         int thr_ret;
507         struct _WapiHandleSharedLayout *tmp_shared;
508         gchar *ftmp;
509         gchar *filename;
510         
511         /*
512          * Yet more barmy API - this union is a well-defined parameter
513          * in a syscall, yet I still have to define it here as it
514          * doesn't appear in a header
515          */
516         union semun {
517                 int val;
518                 struct semid_ds *buf;
519                 ushort *array;
520         } defs;
521         ushort def_vals[_WAPI_SHARED_SEM_COUNT];
522         int i;
523         int retries = 0;
524         
525         for (i = 0; i < _WAPI_SHARED_SEM_COUNT; i++) {
526                 def_vals[i] = 1;
527         }
528
529         /*
530          * Process count must start at '0' - the 1 for all the others
531          * sets the semaphore to "unlocked"
532          */
533         def_vals[_WAPI_SHARED_SEM_PROCESS_COUNT] = 0;
534         
535         defs.array = def_vals;
536         
537         /*
538          *Temporarily attach the shared data so we can read the
539          * semaphore key.  We release this mapping and attach again
540          * after getting the semaphores to avoid a race condition
541          * where a terminating process can delete the shared files
542          * between a new process attaching the file and getting access
543          * to the semaphores (which increments the process count,
544          * preventing destruction of the shared data...)
545          */
546         tmp_shared = _wapi_shm_attach (WAPI_SHM_DATA);
547         g_assert (tmp_shared != NULL);
548         
549 #ifdef USE_SHM
550         ftmp=_wapi_shm_shm_name (WAPI_SHM_DATA);
551         filename = g_build_filename ("/dev/shm", ftmp, NULL);
552         g_assert (filename!=NULL);
553         key = ftok (filename, 'M');
554         g_free (ftmp);
555         g_free (filename);
556 #else
557         key = ftok ( _wapi_shm_file (WAPI_SHM_DATA), 'M');
558 #endif
559
560 again:
561         retries++;
562         oldkey = tmp_shared->sem_key;
563
564         if (oldkey == 0) {
565                 DEBUGLOG ("%s: Creating with new key (0x%x)", __func__, key);
566
567                 /*
568                  * The while loop attempts to make some sense of the
569                  * bonkers 'think of a random number' method of
570                  * picking a key without collision with other
571                  * applications
572                  */
573                 while ((_wapi_sem_id = semget (key, _WAPI_SHARED_SEM_COUNT,
574                                                IPC_CREAT | IPC_EXCL | 0600)) == -1) {
575                         if (errno == ENOMEM) {
576                                 g_error ("%s: semget error: %s", __func__,
577                                             g_strerror (errno));
578                         } else if (errno == ENOSPC) {
579                                 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));
580                         } else if (errno != EEXIST) {
581                                 if (retries > 3)
582                                         g_warning ("%s: semget error: %s key 0x%x - trying again", __func__,
583                                                         g_strerror (errno), key);
584                         }
585                         
586                         key++;
587                         DEBUGLOG ("%s: Got (%s), trying with new key (0x%x)", __func__, g_strerror (errno), key);
588                 }
589                 /*
590                  * Got a semaphore array, so initialise it and install
591                  * the key into the shared memory
592                  */
593                 
594                 if (semctl (_wapi_sem_id, 0, SETALL, defs) == -1) {
595                         if (retries > 3)
596                                 g_warning ("%s: semctl init error: %s - trying again", __func__, g_strerror (errno));
597
598                         /*
599                          * Something went horribly wrong, so try
600                          * getting a new set from scratch
601                          */
602                         semctl (_wapi_sem_id, 0, IPC_RMID);
603                         goto again;
604                 }
605
606                 if (InterlockedCompareExchange (&tmp_shared->sem_key,
607                                                 key, 0) != 0) {
608                         /*
609                          * Someone else created one and installed the
610                          * key while we were working, so delete the
611                          * array we created and fall through to the
612                          * 'key already known' case.
613                          */
614                         semctl (_wapi_sem_id, 0, IPC_RMID);
615                         oldkey = tmp_shared->sem_key;
616                 } else {
617                         /*
618                          * We've installed this semaphore set's key into
619                          * the shared memory
620                          */
621                         goto done;
622                 }
623         }
624         
625         DEBUGLOG ("%s: Trying with old key 0x%x", __func__, oldkey);
626
627         _wapi_sem_id = semget (oldkey, _WAPI_SHARED_SEM_COUNT, 0600);
628         if (_wapi_sem_id == -1) {
629                 if (retries > 3)
630                         g_warning ("%s: semget error opening old key 0x%x (%s) - trying again",
631                                         __func__, oldkey,g_strerror (errno));
632
633                 /*
634                  * Someone must have deleted the semaphore set, so
635                  * blow away the bad key and try again
636                  */
637                 InterlockedCompareExchange (&tmp_shared->sem_key, 0, oldkey);
638                 
639                 goto again;
640         }
641
642   done:
643         /* Increment the usage count of this semaphore set */
644         thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
645         g_assert (thr_ret == 0);
646         
647         DEBUGLOG ("%s: Incrementing the process count (%d)", __func__, _wapi_getpid ());
648
649         /*
650          * We only ever _unlock_ this semaphore, letting the kernel
651          * restore (ie decrement) this unlock when this process exits.
652          * We lock another semaphore around it so we can serialise
653          * access when we're testing the value of this semaphore when
654          * we exit cleanly, so we can delete the whole semaphore set.
655          */
656         _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT);
657
658         DEBUGLOG ("%s: Process count is now %d (%d)", __func__, semctl (_wapi_sem_id, _WAPI_SHARED_SEM_PROCESS_COUNT, GETVAL), _wapi_getpid ());
659         
660         _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
661
662         if (_wapi_shm_disabled)
663                 g_free (tmp_shared);
664         else
665                 munmap (tmp_shared, sizeof(struct _WapiHandleSharedLayout));
666 }
667
668 static void
669 shm_semaphores_remove (void)
670 {
671         int thr_ret;
672         int proc_count;
673         gchar *shm_name;
674         
675         DEBUGLOG ("%s: Checking process count (%d)", __func__, _wapi_getpid ());
676         
677         thr_ret = _wapi_shm_sem_lock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
678         g_assert (thr_ret == 0);
679         
680         proc_count = semctl (_wapi_sem_id, _WAPI_SHARED_SEM_PROCESS_COUNT,
681                              GETVAL);
682
683         g_assert (proc_count > 0);
684         if (proc_count == 1) {
685                 /*
686                  * Just us, so blow away the semaphores and the shared
687                  * files
688                  */
689                 DEBUGLOG ("%s: Removing semaphores! (%d)", __func__, _wapi_getpid ());
690
691                 semctl (_wapi_sem_id, 0, IPC_RMID);
692 #ifdef USE_SHM
693                 shm_name = _wapi_shm_shm_name (WAPI_SHM_DATA);
694                 shm_unlink (shm_name);
695                 g_free (shm_name);
696
697                 shm_name = _wapi_shm_shm_name (WAPI_SHM_FILESHARE);
698                 shm_unlink (shm_name);
699                 g_free (shm_name);
700 #endif
701                 unlink (_wapi_shm_file (WAPI_SHM_DATA));
702                 unlink (_wapi_shm_file (WAPI_SHM_FILESHARE));
703         } else {
704                 /*
705                  * "else" clause, because there's no point unlocking
706                  * the semaphore if we've just blown it away...
707                  */
708                 _wapi_shm_sem_unlock (_WAPI_SHARED_SEM_PROCESS_COUNT_LOCK);
709         }
710 }
711
712 static int
713 shm_sem_lock (int sem)
714 {
715         struct sembuf ops;
716         int ret;
717         
718         DEBUGLOG ("%s: locking sem %d", __func__, sem);
719
720         ops.sem_num = sem;
721         ops.sem_op = -1;
722         ops.sem_flg = SEM_UNDO;
723         
724   retry:
725         do {
726                 ret = semop (_wapi_sem_id, &ops, 1);
727         } while (ret == -1 && errno == EINTR);
728
729         if (ret == -1) {
730                 /*
731                  * EINVAL covers the case when the semaphore was
732                  * deleted before we started the semop
733                  */
734                 if (errno == EIDRM || errno == EINVAL) {
735                         /*
736                          * Someone blew away this semaphore set, so
737                          * get a new one and try again
738                          */
739                         DEBUGLOG ("%s: Reinitialising the semaphores!", __func__);
740
741                         _wapi_shm_semaphores_init ();
742                         goto retry;
743                 }
744                 
745                 /* Turn this into a pthreads-style return value */
746                 ret = errno;
747         }
748         
749         DEBUGLOG ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
750         
751         return ret;
752 }
753
754 static int
755 shm_sem_trylock (int sem)
756 {
757         struct sembuf ops;
758         int ret;
759         
760         DEBUGLOG ("%s: trying to lock sem %d", __func__, sem);
761         
762         ops.sem_num = sem;
763         ops.sem_op = -1;
764         ops.sem_flg = IPC_NOWAIT | SEM_UNDO;
765         
766   retry:
767         do {
768                 ret = semop (_wapi_sem_id, &ops, 1);
769         } while (ret == -1 && errno == EINTR);
770
771         if (ret == -1) {
772                 /*
773                  * EINVAL covers the case when the semaphore was
774                  * deleted before we started the semop
775                  */
776                 if (errno == EIDRM || errno == EINVAL) {
777                         /*
778                          * Someone blew away this semaphore set, so
779                          * get a new one and try again
780                          */
781                         DEBUGLOG ("%s: Reinitialising the semaphores!", __func__);
782
783                         _wapi_shm_semaphores_init ();
784                         goto retry;
785                 }
786                 
787                 /* Turn this into a pthreads-style return value */
788                 ret = errno;
789         }
790         
791         if (ret == EAGAIN) {
792                 /* But pthreads uses this code instead */
793                 ret = EBUSY;
794         }
795         
796         DEBUGLOG ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
797         
798         return ret;
799 }
800
801 static int
802 shm_sem_unlock (int sem)
803 {
804         struct sembuf ops;
805         int ret;
806         
807         DEBUGLOG ("%s: unlocking sem %d", __func__, sem);
808         
809         ops.sem_num = sem;
810         ops.sem_op = 1;
811         ops.sem_flg = SEM_UNDO;
812         
813   retry:
814         do {
815                 ret = semop (_wapi_sem_id, &ops, 1);
816         } while (ret == -1 && errno == EINTR);
817
818         if (ret == -1) {
819                 /* EINVAL covers the case when the semaphore was
820                  * deleted before we started the semop
821                  */
822                 if (errno == EIDRM || errno == EINVAL) {
823                         /* Someone blew away this semaphore set, so
824                          * get a new one and try again (we can't just
825                          * assume that the semaphore is now unlocked)
826                          */
827                         DEBUGLOG ("%s: Reinitialising the semaphores!", __func__);
828
829                         _wapi_shm_semaphores_init ();
830                         goto retry;
831                 }
832                 
833                 /* Turn this into a pthreads-style return value */
834                 ret = errno;
835         }
836         
837         DEBUGLOG ("%s: returning %d (%s)", __func__, ret, g_strerror (ret));
838
839         return ret;
840 }
841
842 void
843 _wapi_shm_semaphores_init (void)
844 {
845         if (!_wapi_shm_enabled ())
846                 noshm_semaphores_init ();
847         else
848                 shm_semaphores_init ();
849 }
850
851 void
852 _wapi_shm_semaphores_remove (void)
853 {
854         if (!_wapi_shm_disabled) 
855                 shm_semaphores_remove ();
856 }
857
858 int
859 _wapi_shm_sem_lock (int sem)
860 {
861         if (_wapi_shm_disabled) 
862                 return noshm_sem_lock (sem);
863         else
864                 return shm_sem_lock (sem);
865 }
866
867 int
868 _wapi_shm_sem_trylock (int sem)
869 {
870         if (_wapi_shm_disabled) 
871                 return noshm_sem_trylock (sem);
872         else 
873                 return shm_sem_trylock (sem);
874 }
875
876 int
877 _wapi_shm_sem_unlock (int sem)
878 {
879         if (_wapi_shm_disabled) 
880                 return noshm_sem_unlock (sem);
881         else 
882                 return shm_sem_unlock (sem);
883 }
884 #endif /* !DISABLE_SHARED_HANDLES */