tests: fix false failure with spaces in $PWD
[coreutils.git] / src / stdbuf.c
blobf583c6ab7ebc129fb1861bf9ab0f09de8ef82929
1 /* stdbuf -- setup the standard streams for a command
2 Copyright (C) 2009-2016 Free Software Foundation, Inc.
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program. If not, see <http://www.gnu.org/licenses/>. */
17 /* Written by Pádraig Brady. */
19 #include <config.h>
20 #include <stdio.h>
21 #include <getopt.h>
22 #include <sys/types.h>
23 #include <assert.h>
25 #include "system.h"
26 #include "die.h"
27 #include "error.h"
28 #include "filenamecat.h"
29 #include "quote.h"
30 #include "xreadlink.h"
31 #include "xstrtol.h"
32 #include "c-ctype.h"
34 /* The official name of this program (e.g., no 'g' prefix). */
35 #define PROGRAM_NAME "stdbuf"
36 #define LIB_NAME "libstdbuf.so" /* FIXME: don't hardcode */
38 #define AUTHORS proper_name ("Padraig Brady")
40 static char *program_path;
42 static struct
44 size_t size;
45 int optc;
46 char *optarg;
47 } stdbuf[3];
49 static struct option const longopts[] =
51 {"input", required_argument, NULL, 'i'},
52 {"output", required_argument, NULL, 'o'},
53 {"error", required_argument, NULL, 'e'},
54 {GETOPT_HELP_OPTION_DECL},
55 {GETOPT_VERSION_OPTION_DECL},
56 {NULL, 0, NULL, 0}
59 /* Set size to the value of STR, interpreted as a decimal integer,
60 optionally multiplied by various values.
61 Return -1 on error, 0 on success.
63 This supports dd BLOCK size suffixes.
64 Note we don't support dd's b=512, c=1, w=2 or 21x512MiB formats. */
65 static int
66 parse_size (char const *str, size_t *size)
68 uintmax_t tmp_size;
69 enum strtol_error e = xstrtoumax (str, NULL, 10, &tmp_size, "EGkKMPTYZ0");
70 if (e == LONGINT_OK && SIZE_MAX < tmp_size)
71 e = LONGINT_OVERFLOW;
73 if (e == LONGINT_OK)
75 errno = 0;
76 *size = tmp_size;
77 return 0;
80 errno = (e == LONGINT_OVERFLOW ? EOVERFLOW : errno);
81 return -1;
84 void
85 usage (int status)
87 if (status != EXIT_SUCCESS)
88 emit_try_help ();
89 else
91 printf (_("Usage: %s OPTION... COMMAND\n"), program_name);
92 fputs (_("\
93 Run COMMAND, with modified buffering operations for its standard streams.\n\
94 "), stdout);
96 emit_mandatory_arg_note ();
98 fputs (_("\
99 -i, --input=MODE adjust standard input stream buffering\n\
100 -o, --output=MODE adjust standard output stream buffering\n\
101 -e, --error=MODE adjust standard error stream buffering\n\
102 "), stdout);
103 fputs (HELP_OPTION_DESCRIPTION, stdout);
104 fputs (VERSION_OPTION_DESCRIPTION, stdout);
105 fputs (_("\n\
106 If MODE is 'L' the corresponding stream will be line buffered.\n\
107 This option is invalid with standard input.\n"), stdout);
108 fputs (_("\n\
109 If MODE is '0' the corresponding stream will be unbuffered.\n\
110 "), stdout);
111 fputs (_("\n\
112 Otherwise MODE is a number which may be followed by one of the following:\n\
113 KB 1000, K 1024, MB 1000*1000, M 1024*1024, and so on for G, T, P, E, Z, Y.\n\
114 In this case the corresponding stream will be fully buffered with the buffer\n\
115 size set to MODE bytes.\n\
116 "), stdout);
117 fputs (_("\n\
118 NOTE: If COMMAND adjusts the buffering of its standard streams ('tee' does\n\
119 for example) then that will override corresponding changes by 'stdbuf'.\n\
120 Also some filters (like 'dd' and 'cat' etc.) don't use streams for I/O,\n\
121 and are thus unaffected by 'stdbuf' settings.\n\
122 "), stdout);
123 emit_ancillary_info (PROGRAM_NAME);
125 exit (status);
128 /* argv[0] can be anything really, but generally it contains
129 the path to the executable or just a name if it was executed
130 using $PATH. In the latter case to get the path we can:
131 search getenv("PATH"), readlink("/prof/self/exe"), getenv("_"),
132 dladdr(), pstat_getpathname(), etc. */
134 static void
135 set_program_path (const char *arg)
137 if (strchr (arg, '/')) /* Use absolute or relative paths directly. */
139 program_path = dir_name (arg);
141 else
143 char *path = xreadlink ("/proc/self/exe");
144 if (path)
145 program_path = dir_name (path);
146 else if ((path = getenv ("PATH")))
148 char *dir;
149 path = xstrdup (path);
150 for (dir = strtok (path, ":"); dir != NULL; dir = strtok (NULL, ":"))
152 char *candidate = file_name_concat (dir, arg, NULL);
153 if (access (candidate, X_OK) == 0)
155 program_path = dir_name (candidate);
156 free (candidate);
157 break;
159 free (candidate);
162 free (path);
166 static int
167 optc_to_fileno (int c)
169 int ret = -1;
171 switch (c)
173 case 'e':
174 ret = STDERR_FILENO;
175 break;
176 case 'i':
177 ret = STDIN_FILENO;
178 break;
179 case 'o':
180 ret = STDOUT_FILENO;
181 break;
184 return ret;
187 static void
188 set_LD_PRELOAD (void)
190 int ret;
191 #ifdef __APPLE__
192 char const *preload_env = "DYLD_INSERT_LIBRARIES";
193 #else
194 char const *preload_env = "LD_PRELOAD";
195 #endif
196 char *old_libs = getenv (preload_env);
197 char *LD_PRELOAD;
199 /* Note this would auto add the appropriate search path for "libstdbuf.so":
200 gcc stdbuf.c -Wl,-rpath,'$ORIGIN' -Wl,-rpath,$PKGLIBEXECDIR
201 However we want the lookup done for the exec'd command not stdbuf.
203 Since we don't link against libstdbuf.so add it to PKGLIBEXECDIR
204 rather than to LIBDIR.
206 Note we could add "" as the penultimate item in the following list
207 to enable searching for libstdbuf.so in the default system lib paths.
208 However that would not indicate an error if libstdbuf.so was not found.
209 Also while this could support auto selecting the right arch in a multilib
210 environment, what we really want is to auto select based on the arch of the
211 command being run, rather than that of stdbuf itself. This is currently
212 not supported due to the unusual need for controlling the stdio buffering
213 of programs that are a different architecture to the default on the
214 system (and that of stdbuf itself). */
215 char const *const search_path[] = {
216 program_path,
217 PKGLIBEXECDIR,
218 NULL
221 char const *const *path = search_path;
222 char *libstdbuf;
224 while (true)
226 struct stat sb;
228 if (!**path) /* system default */
230 libstdbuf = xstrdup (LIB_NAME);
231 break;
233 ret = asprintf (&libstdbuf, "%s/%s", *path, LIB_NAME);
234 if (ret < 0)
235 xalloc_die ();
236 if (stat (libstdbuf, &sb) == 0) /* file_exists */
237 break;
238 free (libstdbuf);
240 ++path;
241 if ( ! *path)
242 die (EXIT_CANCELED, 0, _("failed to find %s"), quote (LIB_NAME));
245 /* FIXME: Do we need to support libstdbuf.dll, c:, '\' separators etc? */
247 if (old_libs)
248 ret = asprintf (&LD_PRELOAD, "%s=%s:%s", preload_env, old_libs, libstdbuf);
249 else
250 ret = asprintf (&LD_PRELOAD, "%s=%s", preload_env, libstdbuf);
252 if (ret < 0)
253 xalloc_die ();
255 free (libstdbuf);
257 ret = putenv (LD_PRELOAD);
258 #ifdef __APPLE__
259 if (ret == 0)
260 ret = setenv ("DYLD_FORCE_FLAT_NAMESPACE", "y", 1);
261 #endif
263 if (ret != 0)
265 die (EXIT_CANCELED, errno,
266 _("failed to update the environment with %s"),
267 quote (LD_PRELOAD));
271 /* Populate environ with _STDBUF_I=$MODE _STDBUF_O=$MODE _STDBUF_E=$MODE.
272 Return TRUE if any environment variables set. */
274 static bool
275 set_libstdbuf_options (void)
277 bool env_set = false;
278 size_t i;
280 for (i = 0; i < ARRAY_CARDINALITY (stdbuf); i++)
282 if (stdbuf[i].optarg)
284 char *var;
285 int ret;
287 if (*stdbuf[i].optarg == 'L')
288 ret = asprintf (&var, "%s%c=L", "_STDBUF_",
289 toupper (stdbuf[i].optc));
290 else
291 ret = asprintf (&var, "%s%c=%" PRIuMAX, "_STDBUF_",
292 toupper (stdbuf[i].optc),
293 (uintmax_t) stdbuf[i].size);
294 if (ret < 0)
295 xalloc_die ();
297 if (putenv (var) != 0)
299 die (EXIT_CANCELED, errno,
300 _("failed to update the environment with %s"),
301 quote (var));
304 env_set = true;
308 return env_set;
312 main (int argc, char **argv)
314 int c;
316 initialize_main (&argc, &argv);
317 set_program_name (argv[0]);
318 setlocale (LC_ALL, "");
319 bindtextdomain (PACKAGE, LOCALEDIR);
320 textdomain (PACKAGE);
322 initialize_exit_failure (EXIT_CANCELED);
323 atexit (close_stdout);
325 while ((c = getopt_long (argc, argv, "+i:o:e:", longopts, NULL)) != -1)
327 int opt_fileno;
329 switch (c)
331 /* Old McDonald had a farm ei... */
332 case 'e':
333 case 'i':
334 case 'o':
335 opt_fileno = optc_to_fileno (c);
336 assert (0 <= opt_fileno && opt_fileno < ARRAY_CARDINALITY (stdbuf));
337 stdbuf[opt_fileno].optc = c;
338 while (c_isspace (*optarg))
339 optarg++;
340 stdbuf[opt_fileno].optarg = optarg;
341 if (c == 'i' && *optarg == 'L')
343 /* -oL will be by far the most common use of this utility,
344 but one could easily think -iL might have the same affect,
345 so disallow it as it could be confusing. */
346 error (0, 0, _("line buffering stdin is meaningless"));
347 usage (EXIT_CANCELED);
350 if (!STREQ (optarg, "L")
351 && parse_size (optarg, &stdbuf[opt_fileno].size) == -1)
352 die (EXIT_CANCELED, errno, _("invalid mode %s"), quote (optarg));
354 break;
356 case_GETOPT_HELP_CHAR;
358 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
360 default:
361 usage (EXIT_CANCELED);
365 argv += optind;
366 argc -= optind;
368 /* must specify at least 1 command. */
369 if (argc < 1)
371 error (0, 0, _("missing operand"));
372 usage (EXIT_CANCELED);
375 if (! set_libstdbuf_options ())
377 error (0, 0, _("you must specify a buffering mode option"));
378 usage (EXIT_CANCELED);
381 /* Try to preload libstdbuf first from the same path as
382 stdbuf is running from. */
383 set_program_path (program_name);
384 if (!program_path)
385 program_path = xstrdup (PKGLIBDIR); /* Need to init to non-NULL. */
386 set_LD_PRELOAD ();
387 free (program_path);
389 execvp (*argv, argv);
391 int exit_status = errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE;
392 error (0, errno, _("failed to run command %s"), quote (argv[0]));
393 return exit_status;