1 /* Generate a file containing some preset patterns.
2 Print statistics for existing files.
4 Copyright (C) 1995, 1996, 1997, 2001, 2003, 2004, 2005, 2006, 2007,
5 2008, 2009 Free Software Foundation, Inc.
7 François Pinard <pinard@iro.umontreal.ca>, 1995.
8 Sergey Poznyakoff <gray@mirddin.farlep.net>, 2004, 2005, 2006, 2007, 2008.
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3, or (at your option)
15 This program is distributed in the hope that it will be useful, but
16 WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software Foundation,
22 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
31 #include <parse-datetime.h>
35 #define obstack_chunk_alloc malloc
36 #define obstack_chunk_free free
40 # define EXIT_SUCCESS 0
43 # define EXIT_FAILURE 1
46 #if ! defined SIGCHLD && defined SIGCLD
47 # define SIGCHLD SIGCLD
56 /* The name this program was run with. */
57 const char *program_name;
59 /* Name of file to generate */
60 static char *file_name;
62 /* Name of the file-list file: */
63 static char *files_from;
64 static char filename_terminator = '\n';
66 /* Length of file to generate. */
67 static off_t file_length = 0;
68 static off_t seek_offset = 0;
70 /* Pattern to generate. */
71 static enum pattern pattern = DEFAULT_PATTERN;
73 /* Next checkpoint number */
84 enum genfile_mode mode = mode_generate;
86 #define DEFAULT_STAT_FORMAT \
87 "name,dev,ino,mode,nlink,uid,gid,size,blksize,blocks,atime,mtime,ctime"
89 /* Format for --stat option */
90 static char *stat_format = DEFAULT_STAT_FORMAT;
92 /* Size of a block for sparse file */
93 size_t block_size = 512;
95 /* Block buffer for sparse file */
98 /* Number of arguments and argument vector for mode == mode_exec */
101 char *checkpoint_option;
103 /* Time for --touch option */
104 struct timespec touch_time;
109 const char *argp_program_version = "genfile (" PACKAGE ") " VERSION;
110 const char *argp_program_bug_address = "<" PACKAGE_BUGREPORT ">";
111 static char doc[] = N_("genfile manipulates data files for GNU paxutils test suite.\n"
114 #define OPT_CHECKPOINT 256
115 #define OPT_TOUCH 257
116 #define OPT_APPEND 258
117 #define OPT_TRUNCATE 259
120 #define OPT_VERBOSE 262
122 #define OPT_UNLINK 264
124 static struct argp_option options[] = {
127 N_("File creation options:"), GRP},
128 {"length", 'l', N_("SIZE"), 0,
129 N_("Create file of the given SIZE"), GRP+1 },
130 {"file", 'f', N_("NAME"), 0,
131 N_("Write to file NAME, instead of standard output"), GRP+1},
132 {"files-from", 'T', N_("FILE"), 0,
133 N_("Read file names from FILE"), GRP+1},
134 {"null", '0', NULL, 0,
135 N_("-T reads null-terminated names"), GRP+1},
136 {"pattern", 'p', N_("PATTERN"), 0,
137 N_("Fill the file with the given PATTERN. PATTERN is 'default' or 'zeros'"),
139 {"block-size", 'b', N_("SIZE"), 0,
140 N_("Size of a block for sparse file"), GRP+1},
141 {"sparse", 's', NULL, 0,
142 N_("Generate sparse file. Rest of the command line gives the file map."),
144 {"seek", OPT_SEEK, N_("OFFSET"), 0,
145 N_("Seek to the given offset before writing data"),
151 N_("File statistics options:"), GRP},
153 {"stat", 'S', N_("FORMAT"), OPTION_ARG_OPTIONAL,
154 N_("Print contents of struct stat for each given file. Default FORMAT is: ")
161 N_("Synchronous execution options:"), GRP},
163 {"run", 'r', N_("OPTION"), OPTION_ARG_OPTIONAL,
164 N_("Execute ARGS. Useful with --checkpoint and one of --cut, --append, --touch, --unlink"),
166 {"checkpoint", OPT_CHECKPOINT, N_("NUMBER"), 0,
167 N_("Perform given action (see below) upon reaching checkpoint NUMBER"),
169 {"date", OPT_DATE, N_("STRING"), 0,
170 N_("Set date for next --touch option"),
172 {"verbose", OPT_VERBOSE, NULL, 0,
173 N_("Display executed checkpoints and exit status of COMMAND"),
178 N_("Synchronous execution actions. These are executed when checkpoint number given by --checkpoint option is reached."), GRP},
180 {"cut", OPT_TRUNCATE, N_("FILE"), 0,
181 N_("Truncate FILE to the size specified by previous --length option (or 0, if it is not given)"),
183 {"truncate", 0, NULL, OPTION_ALIAS, NULL, GRP+1 },
184 {"append", OPT_APPEND, N_("FILE"), 0,
185 N_("Append SIZE bytes to FILE. SIZE is given by previous --length option."),
187 {"touch", OPT_TOUCH, N_("FILE"), 0,
188 N_("Update the access and modification times of FILE"),
190 {"exec", OPT_EXEC, N_("COMMAND"), 0,
191 N_("Execute COMMAND"),
193 {"unlink", OPT_UNLINK, N_("FILE"), 0,
200 static char const * const pattern_args[] = { "default", "zeros", 0 };
201 static enum pattern const pattern_types[] = {DEFAULT_PATTERN, ZEROS_PATTERN};
204 xlat_suffix (off_t *vp, const char *p)
232 get_size (const char *str, int allow_zero)
237 for (p = str; *p; p++)
239 int digit = *p - '0';
241 if (9 < (unsigned) digit)
243 if (xlat_suffix (&v, p))
244 error (EXIT_FAILURE, 0, _("Invalid size: %s"), str);
248 else if (x / 10 != v)
249 error (EXIT_FAILURE, 0, _("Number out of allowed range: %s"), str);
252 error (EXIT_FAILURE, 0, _("Negative size: %s"), str);
258 verify_file (char *file_name)
264 if (stat (file_name, &st))
265 error (0, errno, _("stat(%s) failed"), file_name);
267 if (st.st_size != file_length + seek_offset)
268 error (1, 0, _("requested file length %lu, actual %lu"),
269 (unsigned long)st.st_size, (unsigned long)file_length);
271 if (mode == mode_sparse && !ST_IS_SPARSE (st))
272 error (1, 0, _("created file is not sparse"));
283 enum pattern pattern;
287 static struct action *action_list;
290 reg_action (int action, char *arg)
292 struct action *act = xmalloc (sizeof (*act));
293 act->checkpoint = checkpoint;
294 act->action = action;
295 act->pattern = pattern;
296 act->ts = touch_time;
297 act->size = file_length;
299 act->next = action_list;
304 parse_opt (int key, char *arg, struct argp_state *state)
309 filename_terminator = 0;
317 file_length = get_size (arg, 1);
321 pattern = XARGMATCH ("--pattern", arg, pattern_args, pattern_types);
325 block_size = get_size (arg, 0);
342 argcv_get (arg, "", NULL, &exec_argc, &exec_argv);
343 checkpoint_option = "--checkpoint";
352 seek_offset = get_size (arg, 0);
359 checkpoint = strtoul (arg, &p, 0);
361 argp_error (state, _("Error parsing number near `%s'"), p);
366 if (! parse_datetime (&touch_time, arg, NULL))
367 argp_error (state, _("Unknown date format"));
375 reg_action (key, arg);
383 return ARGP_ERR_UNKNOWN;
388 static struct argp argp = {
400 fill (FILE *fp, off_t length, enum pattern pattern)
406 case DEFAULT_PATTERN:
407 for (i = 0; i < length; i++)
412 for (i = 0; i < length; i++)
418 /* Generate Mode: usual files */
420 generate_simple_file (char *filename)
426 fp = fopen (filename, seek_offset ? "rb+" : "wb");
428 error (EXIT_FAILURE, errno, _("cannot open `%s'"), filename);
433 if (fseeko (fp, seek_offset, 0))
434 error (EXIT_FAILURE, errno, "%s", _("cannot seek"));
436 fill (fp, file_length, pattern);
441 /* A simplified version of the same function from tar */
443 read_name_from_file (FILE *fp, struct obstack *stk)
448 for (c = getc (fp); c != EOF && c != filename_terminator; c = getc (fp))
451 error (EXIT_FAILURE, 0, _("file name contains null character"));
452 obstack_1grow (stk, c);
456 obstack_1grow (stk, 0);
458 return (counter == 0 && c == EOF);
462 generate_files_from_list ()
464 FILE *fp = strcmp (files_from, "-") ? fopen (files_from, "rb") : stdin;
468 error (EXIT_FAILURE, errno, _("cannot open `%s'"), files_from);
471 while (!read_name_from_file (fp, &stk))
473 char *name = obstack_finish (&stk);
474 generate_simple_file (name);
476 obstack_free (&stk, name);
479 obstack_free (&stk, NULL);
483 /* Generate Mode: sparse files */
486 mkhole (int fd, off_t displ)
488 if (lseek (fd, displ, SEEK_CUR) == -1)
489 error (EXIT_FAILURE, errno, "lseek");
490 ftruncate (fd, lseek (fd, 0, SEEK_CUR));
494 mksparse (int fd, off_t displ, char *marks)
496 if (lseek (fd, displ, SEEK_CUR) == -1)
497 error (EXIT_FAILURE, errno, "lseek");
499 for (; *marks; marks++)
501 memset (buffer, *marks, block_size);
502 if (write (fd, buffer, block_size) != block_size)
503 error (EXIT_FAILURE, errno, "write");
508 generate_sparse_file (int argc, char **argv)
512 int flags = O_CREAT | O_RDWR | O_BINARY;
515 error (EXIT_FAILURE, 0,
516 _("cannot generate sparse files on standard output, use --file option"));
519 fd = open (file_name, flags, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
521 error (EXIT_FAILURE, errno, _("cannot open `%s'"), file_name);
523 buffer = xmalloc (block_size);
527 for (i = 0; i < argc; i += 2)
529 off_t displ = get_size (argv[i], 1);
530 file_length += displ;
539 file_length += block_size * strlen (argv[i+1]);
540 mksparse (fd, displ, argv[i+1]);
551 print_time (time_t t)
553 char buf[20]; /* ccyy-mm-dd HH:MM:SS\0 */
554 strftime (buf, sizeof buf, "%Y-%m-%d %H:%M:%S", gmtime (&t));
559 print_stat (const char *name)
563 char buf[UINTMAX_STRSIZE_BOUND];
565 if (stat (name, &st))
567 error (0, errno, _("stat(%s) failed"), name);
571 fmt = strdup (stat_format);
572 for (p = strtok (fmt, ","); p; )
574 if (memcmp (p, "st_", 3) == 0)
576 if (strcmp (p, "name") == 0)
578 else if (strcmp (p, "dev") == 0)
579 printf ("%lu", (unsigned long) st.st_dev);
580 else if (strcmp (p, "ino") == 0)
581 printf ("%lu", (unsigned long) st.st_ino);
582 else if (strncmp (p, "mode", 4) == 0)
584 unsigned val = st.st_mode;
586 if (ispunct ((unsigned char) p[4]))
590 val &= strtoul (p + 5, &q, 8);
594 error (EXIT_FAILURE, 0, _("incorrect mask (near `%s')"), q);
600 error (EXIT_FAILURE, 0, _("Unknown field `%s'"), p);
604 else if (strcmp (p, "nlink") == 0)
605 printf ("%lu", (unsigned long) st.st_nlink);
606 else if (strcmp (p, "uid") == 0)
607 printf ("%ld", (long unsigned) st.st_uid);
608 else if (strcmp (p, "gid") == 0)
609 printf ("%lu", (unsigned long) st.st_gid);
610 else if (strcmp (p, "size") == 0)
611 printf ("%s", umaxtostr (st.st_size, buf));
612 else if (strcmp (p, "blksize") == 0)
613 printf ("%s", umaxtostr (st.st_blksize, buf));
614 else if (strcmp (p, "blocks") == 0)
615 printf ("%s", umaxtostr (st.st_blocks, buf));
616 else if (strcmp (p, "atime") == 0)
617 printf ("%lu", (unsigned long) st.st_atime);
618 else if (strcmp (p, "atimeH") == 0)
619 print_time (st.st_atime);
620 else if (strcmp (p, "mtime") == 0)
621 printf ("%lu", (unsigned long) st.st_mtime);
622 else if (strcmp (p, "mtimeH") == 0)
623 print_time (st.st_mtime);
624 else if (strcmp (p, "ctime") == 0)
625 printf ("%lu", (unsigned long) st.st_ctime);
626 else if (strcmp (p, "ctimeH") == 0)
627 print_time (st.st_ctime);
628 else if (strcmp (p, "sparse") == 0)
629 printf ("%d", ST_IS_SPARSE (st));
633 error (EXIT_FAILURE, 0, _("Unknown field `%s'"), p);
635 p = strtok (NULL, ",");
647 exec_checkpoint (struct action *p)
650 printf ("processing checkpoint %lu\n", (unsigned long) p->checkpoint);
655 struct timespec ts[2];
657 ts[0] = ts[1] = p->ts;
658 if (utimensat (AT_FDCWD, p->name, ts, 0) != 0)
660 error (0, errno, _("cannot set time on `%s'"), p->name);
668 FILE *fp = fopen (p->name, "ab");
671 error (0, errno, _("cannot open `%s'"), p->name);
675 fill (fp, p->size, p->pattern);
682 int fd = open (p->name, O_RDWR | O_BINARY);
685 error (0, errno, _("cannot open `%s'"), p->name);
688 ftruncate (fd, p->size);
698 if (unlink (p->name))
699 error (0, errno, _("cannot unlink `%s'"), p->name);
708 process_checkpoint (size_t n)
710 struct action *p, *prev = NULL;
712 for (p = action_list; p; )
714 struct action *next = p->next;
716 if (p->checkpoint <= n)
719 /* Remove the item from the list */
733 #define CHECKPOINT_TEXT "Write checkpoint"
745 /* Insert --checkpoint option.
746 FIXME: This assumes that exec_argv does not use traditional tar options
748 FIXME: There is no way to set checkpoint argument (granularity).
750 if (checkpoint_option)
753 exec_argv = xrealloc (exec_argv, (exec_argc + 1) * sizeof (*exec_argv));
754 memmove (exec_argv+2, exec_argv+1,
755 (exec_argc - 1) * sizeof (*exec_argv));
756 exec_argv[1] = checkpoint_option;
760 /* System V fork+wait does not work if SIGCHLD is ignored. */
761 signal (SIGCHLD, SIG_DFL);
768 error (EXIT_FAILURE, errno, "fork");
779 /* Make sure POSIX locale is used */
780 setenv ("LC_ALL", "POSIX", 1);
782 execvp (exec_argv[0], exec_argv);
783 error (EXIT_FAILURE, errno, "execvp %s", exec_argv[0]);
788 fp = fdopen (fd[0], "rb");
790 error (EXIT_FAILURE, errno, "fdopen");
792 while ((p = fgets (buf, sizeof buf, fp)))
794 while (*p && !isspace ((unsigned char) *p) && *p != ':')
799 for (p++; *p && isspace ((unsigned char) *p); p++)
803 && memcmp (p, CHECKPOINT_TEXT, sizeof CHECKPOINT_TEXT - 1) == 0)
806 size_t n = strtoul (p + sizeof CHECKPOINT_TEXT - 1, &end, 10);
807 if (!(*end && !isspace ((unsigned char) *end)))
809 process_checkpoint (n);
814 fprintf (stderr, "%s", buf);
817 /* Collect exit status */
818 waitpid (pid, &status, 0);
822 if (WIFEXITED (status))
824 if (WEXITSTATUS (status) == 0)
825 printf (_("Command exited successfully\n"));
827 printf (_("Command failed with status %d\n"),
828 WEXITSTATUS (status));
830 else if (WIFSIGNALED (status))
831 printf (_("Command terminated on signal %d\n"), WTERMSIG (status));
832 else if (WIFSTOPPED (status))
833 printf (_("Command stopped on signal %d\n"), WSTOPSIG (status));
835 else if (WCOREDUMP (status))
836 printf (_("Command dumped core\n"));
839 printf(_("Command terminated\n"));
842 if (WIFEXITED (status))
843 exit (WEXITSTATUS (status));
848 main (int argc, char **argv)
852 program_name = argv[0];
853 setlocale (LC_ALL, "");
854 bindtextdomain (PACKAGE, LOCALEDIR);
855 textdomain (PACKAGE);
857 parse_datetime (&touch_time, "now", NULL);
859 /* Decode command options. */
861 if (argp_parse (&argp, argc, argv, 0, &index, NULL))
871 error (EXIT_FAILURE, 0, _("--stat requires file names"));
874 print_stat (*argv++);
878 generate_sparse_file (argc, argv);
879 verify_file (file_name);
884 error (EXIT_FAILURE, 0, _("too many arguments"));
886 generate_files_from_list ();
889 generate_simple_file (file_name);
890 verify_file (file_name);
895 if (!checkpoint_option)
901 error (EXIT_FAILURE, 0, _("too many arguments"));