b5a5de4eeb2a7b387c8ae86f3929fc853395aa4d
[platform/upstream/glibc.git] / nptl / sem_open.c
1 /* Copyright (C) 2002-2015 Free Software Foundation, Inc.
2    This file is part of the GNU C Library.
3    Contributed by Ulrich Drepper <drepper@redhat.com>, 2002.
4
5    The GNU C Library is free software; you can redistribute it and/or
6    modify it under the terms of the GNU Lesser General Public
7    License as published by the Free Software Foundation; either
8    version 2.1 of the License, or (at your option) any later version.
9
10    The GNU C Library is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    Lesser General Public License for more details.
14
15    You should have received a copy of the GNU Lesser General Public
16    License along with the GNU C Library; if not, see
17    <http://www.gnu.org/licenses/>.  */
18
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <pthread.h>
22 #include <search.h>
23 #include <semaphore.h>
24 #include <stdarg.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <unistd.h>
29 #include <sys/mman.h>
30 #include <sys/stat.h>
31 #include "semaphoreP.h"
32 #include <shm-directory.h>
33
34
35 /* Comparison function for search of existing mapping.  */
36 int
37 attribute_hidden
38 __sem_search (const void *a, const void *b)
39 {
40   const struct inuse_sem *as = (const struct inuse_sem *) a;
41   const struct inuse_sem *bs = (const struct inuse_sem *) b;
42
43   if (as->ino != bs->ino)
44     /* Cannot return the difference the type is larger than int.  */
45     return as->ino < bs->ino ? -1 : (as->ino == bs->ino ? 0 : 1);
46
47   if (as->dev != bs->dev)
48     /* Cannot return the difference the type is larger than int.  */
49     return as->dev < bs->dev ? -1 : (as->dev == bs->dev ? 0 : 1);
50
51   return strcmp (as->name, bs->name);
52 }
53
54
55 /* The search tree for existing mappings.  */
56 void *__sem_mappings attribute_hidden;
57
58 /* Lock to protect the search tree.  */
59 int __sem_mappings_lock attribute_hidden = LLL_LOCK_INITIALIZER;
60
61
62 /* Search for existing mapping and if possible add the one provided.  */
63 static sem_t *
64 check_add_mapping (const char *name, size_t namelen, int fd, sem_t *existing)
65 {
66   sem_t *result = SEM_FAILED;
67
68   /* Get the information about the file.  */
69   struct stat64 st;
70   if (__fxstat64 (_STAT_VER, fd, &st) == 0)
71     {
72       /* Get the lock.  */
73       lll_lock (__sem_mappings_lock, LLL_PRIVATE);
74
75       /* Search for an existing mapping given the information we have.  */
76       struct inuse_sem *fake;
77       fake = (struct inuse_sem *) alloca (sizeof (*fake) + namelen);
78       memcpy (fake->name, name, namelen);
79       fake->dev = st.st_dev;
80       fake->ino = st.st_ino;
81
82       struct inuse_sem **foundp = tfind (fake, &__sem_mappings, __sem_search);
83       if (foundp != NULL)
84         {
85           /* There is already a mapping.  Use it.  */
86           result = (*foundp)->sem;
87           ++(*foundp)->refcnt;
88         }
89       else
90         {
91           /* We haven't found a mapping.  Install ione.  */
92           struct inuse_sem *newp;
93
94           newp = (struct inuse_sem *) malloc (sizeof (*newp) + namelen);
95           if (newp != NULL)
96             {
97               /* If the caller hasn't provided any map it now.  */
98               if (existing == SEM_FAILED)
99                 existing = (sem_t *) mmap (NULL, sizeof (sem_t),
100                                            PROT_READ | PROT_WRITE, MAP_SHARED,
101                                            fd, 0);
102
103               newp->dev = st.st_dev;
104               newp->ino = st.st_ino;
105               newp->refcnt = 1;
106               newp->sem = existing;
107               memcpy (newp->name, name, namelen);
108
109               /* Insert the new value.  */
110               if (existing != MAP_FAILED
111                   && tsearch (newp, &__sem_mappings, __sem_search) != NULL)
112                 /* Successful.  */
113                 result = existing;
114               else
115                 /* Something went wrong while inserting the new
116                    value.  We fail completely.  */
117                 free (newp);
118             }
119         }
120
121       /* Release the lock.  */
122       lll_unlock (__sem_mappings_lock, LLL_PRIVATE);
123     }
124
125   if (result != existing && existing != SEM_FAILED && existing != MAP_FAILED)
126     {
127       /* Do not disturb errno.  */
128       int save = errno;
129       munmap (existing, sizeof (sem_t));
130       errno = save;
131     }
132
133   return result;
134 }
135
136
137 sem_t *
138 sem_open (const char *name, int oflag, ...)
139 {
140   int fd;
141   sem_t *result;
142
143   /* Create the name of the final file in local variable SHM_NAME.  */
144   SHM_GET_NAME (EINVAL, SEM_FAILED, SEM_SHM_PREFIX);
145
146   /* If the semaphore object has to exist simply open it.  */
147   if ((oflag & O_CREAT) == 0 || (oflag & O_EXCL) == 0)
148     {
149     try_again:
150       fd = __libc_open (shm_name,
151                         (oflag & ~(O_CREAT|O_ACCMODE)) | O_NOFOLLOW | O_RDWR);
152
153       if (fd == -1)
154         {
155           /* If we are supposed to create the file try this next.  */
156           if ((oflag & O_CREAT) != 0 && errno == ENOENT)
157             goto try_create;
158
159           /* Return.  errno is already set.  */
160         }
161       else
162         /* Check whether we already have this semaphore mapped and
163            create one if necessary.  */
164         result = check_add_mapping (name, namelen, fd, SEM_FAILED);
165     }
166   else
167     {
168       /* We have to open a temporary file first since it must have the
169          correct form before we can start using it.  */
170       char *tmpfname;
171       mode_t mode;
172       unsigned int value;
173       va_list ap;
174
175     try_create:
176       va_start (ap, oflag);
177
178       mode = va_arg (ap, mode_t);
179       value = va_arg (ap, unsigned int);
180
181       va_end (ap);
182
183       if (value > SEM_VALUE_MAX)
184         {
185           __set_errno (EINVAL);
186           return SEM_FAILED;
187         }
188
189       /* Create the initial file content.  */
190       union
191       {
192         sem_t initsem;
193         struct new_sem newsem;
194       } sem;
195
196       sem.newsem.value = value;
197       sem.newsem.private = 0;
198       sem.newsem.nwaiters = 0;
199
200       /* Initialize the remaining bytes as well.  */
201       memset ((char *) &sem.initsem + sizeof (struct new_sem), '\0',
202               sizeof (sem_t) - sizeof (struct new_sem));
203
204       tmpfname = __alloca (shm_dirlen + sizeof SEM_SHM_PREFIX + 6);
205       char *xxxxxx = __mempcpy (tmpfname, shm_dir, shm_dirlen);
206
207       int retries = 0;
208 #define NRETRIES 50
209       while (1)
210         {
211           /* Add the suffix for mktemp.  */
212           strcpy (xxxxxx, "XXXXXX");
213
214           /* We really want to use mktemp here.  We cannot use mkstemp
215              since the file must be opened with a specific mode.  The
216              mode cannot later be set since then we cannot apply the
217              file create mask.  */
218           if (__mktemp (tmpfname) == NULL)
219             return SEM_FAILED;
220
221           /* Open the file.  Make sure we do not overwrite anything.  */
222           fd = __libc_open (tmpfname, O_RDWR | O_CREAT | O_EXCL, mode);
223           if (fd == -1)
224             {
225               if (errno == EEXIST)
226                 {
227                   if (++retries < NRETRIES)
228                     continue;
229
230                   __set_errno (EAGAIN);
231                 }
232
233               return SEM_FAILED;
234             }
235
236           /* We got a file.  */
237           break;
238         }
239
240       if (TEMP_FAILURE_RETRY (__libc_write (fd, &sem.initsem, sizeof (sem_t)))
241           == sizeof (sem_t)
242           /* Map the sem_t structure from the file.  */
243           && (result = (sem_t *) mmap (NULL, sizeof (sem_t),
244                                        PROT_READ | PROT_WRITE, MAP_SHARED,
245                                        fd, 0)) != MAP_FAILED)
246         {
247           /* Create the file.  Don't overwrite an existing file.  */
248           if (link (tmpfname, shm_name) != 0)
249             {
250               /* Undo the mapping.  */
251               (void) munmap (result, sizeof (sem_t));
252
253               /* Reinitialize 'result'.  */
254               result = SEM_FAILED;
255
256               /* This failed.  If O_EXCL is not set and the problem was
257                  that the file exists, try again.  */
258               if ((oflag & O_EXCL) == 0 && errno == EEXIST)
259                 {
260                   /* Remove the file.  */
261                   (void) unlink (tmpfname);
262
263                   /* Close the file.  */
264                   (void) __libc_close (fd);
265
266                   goto try_again;
267                 }
268             }
269           else
270             /* Insert the mapping into the search tree.  This also
271                determines whether another thread sneaked by and already
272                added such a mapping despite the fact that we created it.  */
273             result = check_add_mapping (name, namelen, fd, result);
274         }
275
276       /* Now remove the temporary name.  This should never fail.  If
277          it fails we leak a file name.  Better fix the kernel.  */
278       (void) unlink (tmpfname);
279     }
280
281   /* Map the mmap error to the error we need.  */
282   if (MAP_FAILED != (void *) SEM_FAILED && result == MAP_FAILED)
283     result = SEM_FAILED;
284
285   /* We don't need the file descriptor anymore.  */
286   if (fd != -1)
287     {
288       /* Do not disturb errno.  */
289       int save = errno;
290       __libc_close (fd);
291       errno = save;
292     }
293
294   return result;
295 }