added missing dependencies to fix failing unistr/ tests
[gnulib.git] / lib / ttyname_r.c
1 /* Determine name of a terminal.
2
3    Copyright (C) 2010 Free Software Foundation, Inc.
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3 of the License, or
8    (at your option) any later version.
9
10    This program 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
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17
18 /* Written by Bruno Haible <bruno@clisp.org>, 2010.  */
19
20 #include <config.h>
21
22 #include <unistd.h>
23
24 #include <errno.h>
25 #include <limits.h>
26 #include <string.h>
27
28 int
29 ttyname_r (int fd, char *buf, size_t buflen)
30 #undef ttyname_r
31 {
32   /* When ttyname_r exists, use it.  */
33 #if HAVE_TTYNAME_R
34   /* This code is multithread-safe.  */
35   /* On Solaris, ttyname_r always fails if buflen < 128.  So provide a buffer
36      that is large enough.  */
37   char largerbuf[512];
38 # if HAVE_POSIXDECL_TTYNAME_R
39   int err =
40     (buflen < sizeof (largerbuf)
41      ? ttyname_r (fd, largerbuf, sizeof (largerbuf))
42      : ttyname_r (fd, buf, buflen <= INT_MAX ? buflen : INT_MAX));
43   if (err != 0)
44     return err;
45   if (buflen < sizeof (largerbuf))
46     {
47       size_t namelen = strlen (largerbuf);
48       if (namelen > buflen)
49         return ERANGE;
50       memcpy (buf, largerbuf, namelen);
51     }
52 # else
53   char *name =
54     (buflen < sizeof (largerbuf)
55      ? ttyname_r (fd, largerbuf, sizeof (largerbuf))
56      : ttyname_r (fd, buf, buflen <= INT_MAX ? buflen : INT_MAX));
57   if (name == NULL)
58     return errno;
59   if (name != buf)
60     {
61       size_t namelen = strlen (name) + 1;
62       if (namelen > buflen)
63         return ERANGE;
64       memmove (buf, name, namelen);
65     }
66 # endif
67   return 0;
68 #elif HAVE_TTYNAME
69   /* Note: This is not multithread-safe.  */
70   char *name;
71   size_t namelen;
72
73   name = ttyname (fd);
74   if (name == NULL)
75     return errno;
76   namelen = strlen (name) + 1;
77   if (namelen > buflen)
78     return ERANGE;
79   memcpy (buf, name, namelen);
80   return 0;
81 #else
82   /* Platforms like mingw: no ttys exist at all.  */
83   return ENOTTY;
84 #endif
85 }