split: port ‘split -n N /dev/null’ better to macOS
[coreutils.git] / src / stdbuf.c
blob0372eda32067ef4c6a6e186241f2db894b1f710b
1 /* stdbuf -- setup the standard streams for a command
2 Copyright (C) 2009-2023 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 <https://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, "EGkKMPQRTYZ0");
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,R,Q.\n\
114 Binary prefixes can be used, too: KiB=K, MiB=M, and so on.\n\
115 In this case the corresponding stream will be fully buffered with the buffer\n\
116 size set to MODE bytes.\n\
117 "), stdout);
118 fputs (_("\n\
119 NOTE: If COMMAND adjusts the buffering of its standard streams ('tee' does\n\
120 for example) then that will override corresponding changes by 'stdbuf'.\n\
121 Also some filters (like 'dd' and 'cat' etc.) don't use streams for I/O,\n\
122 and are thus unaffected by 'stdbuf' settings.\n\
123 "), stdout);
124 emit_exec_status (PROGRAM_NAME);
125 emit_ancillary_info (PROGRAM_NAME);
127 exit (status);
130 /* argv[0] can be anything really, but generally it contains
131 the path to the executable or just a name if it was executed
132 using $PATH. In the latter case to get the path we can:
133 search getenv("PATH"), readlink("/prof/self/exe"), getenv("_"),
134 dladdr(), pstat_getpathname(), etc. */
136 static void
137 set_program_path (char const *arg)
139 if (strchr (arg, '/')) /* Use absolute or relative paths directly. */
141 program_path = dir_name (arg);
143 else
145 char *path = xreadlink ("/proc/self/exe");
146 if (path)
147 program_path = dir_name (path);
148 else if ((path = getenv ("PATH")))
150 char *dir;
151 path = xstrdup (path);
152 for (dir = strtok (path, ":"); dir != NULL; dir = strtok (NULL, ":"))
154 char *candidate = file_name_concat (dir, arg, NULL);
155 if (access (candidate, X_OK) == 0)
157 program_path = dir_name (candidate);
158 free (candidate);
159 break;
161 free (candidate);
164 free (path);
168 static int
169 optc_to_fileno (int c)
171 int ret = -1;
173 switch (c)
175 case 'e':
176 ret = STDERR_FILENO;
177 break;
178 case 'i':
179 ret = STDIN_FILENO;
180 break;
181 case 'o':
182 ret = STDOUT_FILENO;
183 break;
186 return ret;
189 static void
190 set_LD_PRELOAD (void)
192 int ret;
193 #ifdef __APPLE__
194 char const *preload_env = "DYLD_INSERT_LIBRARIES";
195 #else
196 char const *preload_env = "LD_PRELOAD";
197 #endif
198 char *old_libs = getenv (preload_env);
199 char *LD_PRELOAD;
201 /* Note this would auto add the appropriate search path for "libstdbuf.so":
202 gcc stdbuf.c -Wl,-rpath,'$ORIGIN' -Wl,-rpath,$PKGLIBEXECDIR
203 However we want the lookup done for the exec'd command not stdbuf.
205 Since we don't link against libstdbuf.so add it to PKGLIBEXECDIR
206 rather than to LIBDIR.
208 Note we could add "" as the penultimate item in the following list
209 to enable searching for libstdbuf.so in the default system lib paths.
210 However that would not indicate an error if libstdbuf.so was not found.
211 Also while this could support auto selecting the right arch in a multilib
212 environment, what we really want is to auto select based on the arch of the
213 command being run, rather than that of stdbuf itself. This is currently
214 not supported due to the unusual need for controlling the stdio buffering
215 of programs that are a different architecture to the default on the
216 system (and that of stdbuf itself). */
217 char const *const search_path[] = {
218 program_path,
219 PKGLIBEXECDIR,
220 NULL
223 char const *const *path = search_path;
224 char *libstdbuf;
226 while (true)
228 struct stat sb;
230 if (!**path) /* system default */
232 libstdbuf = xstrdup (LIB_NAME);
233 break;
235 ret = asprintf (&libstdbuf, "%s/%s", *path, LIB_NAME);
236 if (ret < 0)
237 xalloc_die ();
238 if (stat (libstdbuf, &sb) == 0) /* file_exists */
239 break;
240 free (libstdbuf);
242 ++path;
243 if ( ! *path)
244 die (EXIT_CANCELED, 0, _("failed to find %s"), quote (LIB_NAME));
247 /* FIXME: Do we need to support libstdbuf.dll, c:, '\' separators etc? */
249 if (old_libs)
250 ret = asprintf (&LD_PRELOAD, "%s=%s:%s", preload_env, old_libs, libstdbuf);
251 else
252 ret = asprintf (&LD_PRELOAD, "%s=%s", preload_env, libstdbuf);
254 if (ret < 0)
255 xalloc_die ();
257 free (libstdbuf);
259 ret = putenv (LD_PRELOAD);
260 #ifdef __APPLE__
261 if (ret == 0)
262 ret = setenv ("DYLD_FORCE_FLAT_NAMESPACE", "y", 1);
263 #endif
265 if (ret != 0)
267 die (EXIT_CANCELED, errno,
268 _("failed to update the environment with %s"),
269 quote (LD_PRELOAD));
273 /* Populate environ with _STDBUF_I=$MODE _STDBUF_O=$MODE _STDBUF_E=$MODE.
274 Return TRUE if any environment variables set. */
276 static bool
277 set_libstdbuf_options (void)
279 bool env_set = false;
281 for (size_t i = 0; i < ARRAY_CARDINALITY (stdbuf); i++)
283 if (stdbuf[i].optarg)
285 char *var;
286 int ret;
288 if (*stdbuf[i].optarg == 'L')
289 ret = asprintf (&var, "%s%c=L", "_STDBUF_",
290 toupper (stdbuf[i].optc));
291 else
292 ret = asprintf (&var, "%s%c=%" PRIuMAX, "_STDBUF_",
293 toupper (stdbuf[i].optc),
294 (uintmax_t) stdbuf[i].size);
295 if (ret < 0)
296 xalloc_die ();
298 if (putenv (var) != 0)
300 die (EXIT_CANCELED, errno,
301 _("failed to update the environment with %s"),
302 quote (var));
305 env_set = true;
309 return env_set;
313 main (int argc, char **argv)
315 int c;
317 initialize_main (&argc, &argv);
318 set_program_name (argv[0]);
319 setlocale (LC_ALL, "");
320 bindtextdomain (PACKAGE, LOCALEDIR);
321 textdomain (PACKAGE);
323 initialize_exit_failure (EXIT_CANCELED);
324 atexit (close_stdout);
326 while ((c = getopt_long (argc, argv, "+i:o:e:", longopts, NULL)) != -1)
328 int opt_fileno;
330 switch (c)
332 /* Old McDonald had a farm ei... */
333 case 'e':
334 case 'i':
335 case 'o':
336 opt_fileno = optc_to_fileno (c);
337 assert (0 <= opt_fileno && opt_fileno < ARRAY_CARDINALITY (stdbuf));
338 stdbuf[opt_fileno].optc = c;
339 while (c_isspace (*optarg))
340 optarg++;
341 stdbuf[opt_fileno].optarg = optarg;
342 if (c == 'i' && *optarg == 'L')
344 /* -oL will be by far the most common use of this utility,
345 but one could easily think -iL might have the same affect,
346 so disallow it as it could be confusing. */
347 error (0, 0, _("line buffering stdin is meaningless"));
348 usage (EXIT_CANCELED);
351 if (!STREQ (optarg, "L")
352 && parse_size (optarg, &stdbuf[opt_fileno].size) == -1)
353 die (EXIT_CANCELED, errno, _("invalid mode %s"), quote (optarg));
355 break;
357 case_GETOPT_HELP_CHAR;
359 case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS);
361 default:
362 usage (EXIT_CANCELED);
366 argv += optind;
367 argc -= optind;
369 /* must specify at least 1 command. */
370 if (argc < 1)
372 error (0, 0, _("missing operand"));
373 usage (EXIT_CANCELED);
376 if (! set_libstdbuf_options ())
378 error (0, 0, _("you must specify a buffering mode option"));
379 usage (EXIT_CANCELED);
382 /* Try to preload libstdbuf first from the same path as
383 stdbuf is running from. */
384 set_program_path (program_name);
385 if (!program_path)
386 program_path = xstrdup (PKGLIBDIR); /* Need to init to non-NULL. */
387 set_LD_PRELOAD ();
388 free (program_path);
390 execvp (*argv, argv);
392 int exit_status = errno == ENOENT ? EXIT_ENOENT : EXIT_CANNOT_INVOKE;
393 error (0, errno, _("failed to run command %s"), quote (argv[0]));
394 return exit_status;