utils.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /*
  2. * Copyright 1999-2008 by Marco d'Itri <md@linux.it>.
  3. *
  4. * do_nofail and merge_args come from the module-init-tools package.
  5. * Copyright 2001 by Rusty Russell.
  6. * Copyright 2002, 2003 by Rusty Russell, IBM Corporation.
  7. *
  8. * This program is free software; you can redistribute it and/or modify
  9. * it under the terms of the GNU General Public License as published by
  10. * the Free Software Foundation; either version 2 of the License, or
  11. * (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. */
  22. /* for strdup */
  23. #define _XOPEN_SOURCE 500
  24. /* System library */
  25. #include <stdio.h>
  26. #include <stdlib.h>
  27. #include <stdarg.h>
  28. #include <string.h>
  29. #include <errno.h>
  30. /* Application-specific */
  31. #include "utils.h"
  32. void *do_nofail(void *ptr, const char *file, const int line)
  33. {
  34. if (ptr)
  35. return ptr;
  36. err_quit("Memory allocation failure at %s:%d.", file, line);
  37. }
  38. /* Prepend options from a string. */
  39. char **merge_args(char *args, char *argv[], int *argc)
  40. {
  41. char *arg, *argstring;
  42. char **newargs = NULL;
  43. unsigned int i, num_env = 0;
  44. if (!args)
  45. return argv;
  46. argstring = NOFAIL(strdup(args));
  47. for (arg = strtok(argstring, " "); arg; arg = strtok(NULL, " ")) {
  48. num_env++;
  49. newargs = NOFAIL(realloc(newargs,
  50. sizeof(newargs[0]) * (num_env + *argc + 1)));
  51. newargs[num_env] = arg;
  52. }
  53. if (!newargs)
  54. return argv;
  55. /* Append commandline args */
  56. newargs[0] = argv[0];
  57. for (i = 1; i <= *argc; i++)
  58. newargs[num_env + i] = argv[i];
  59. *argc += num_env;
  60. return newargs;
  61. }
  62. /* Error routines */
  63. void err_sys(const char *fmt, ...)
  64. {
  65. va_list ap;
  66. va_start(ap, fmt);
  67. vfprintf(stderr, fmt, ap);
  68. fprintf(stderr, ": %s\n", strerror(errno));
  69. va_end(ap);
  70. exit(2);
  71. }
  72. void err_quit(const char *fmt, ...)
  73. {
  74. va_list ap;
  75. va_start(ap, fmt);
  76. vfprintf(stderr, fmt, ap);
  77. fputs("\n", stderr);
  78. va_end(ap);
  79. exit(2);
  80. }