You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

124 lines
2.9 KiB

  1. /*
  2. * zzuf - general purpose fuzzer
  3. * Copyright (c) 2002, 2007 Sam Hocevar <sam@zoy.org>
  4. * All Rights Reserved
  5. *
  6. * $Id: mygetopt.c 271 2007-02-02 11:58:06Z sam $
  7. *
  8. * This program is free software. It comes without any warranty, to
  9. * the extent permitted by applicable law. You can redistribute it
  10. * and/or modify it under the terms of the Do What The Fuck You Want
  11. * To Public License, Version 2, as published by Sam Hocevar. See
  12. * http://sam.zoy.org/wtfpl/COPYING for more details.
  13. */
  14. /*
  15. * mygetopt.c: getopt_long reimplementation
  16. */
  17. #include "config.h"
  18. #include "common.h"
  19. #if defined HAVE_STDINT_H
  20. # include <stdint.h>
  21. #elif defined HAVE_INTTYPES_H
  22. # include <inttypes.h>
  23. #endif
  24. #include <stdio.h>
  25. #include <string.h>
  26. #include "mygetopt.h"
  27. int myoptind = 1;
  28. char *myoptarg = NULL;
  29. /* XXX: this getopt_long implementation should not be trusted for other
  30. * applications without any serious peer reviewing. It “just works” with
  31. * zzuf but may fail miserably in other programs. */
  32. int mygetopt(int argc, char * const _argv[], const char *optstring,
  33. const struct myoption *longopts, int *longindex)
  34. {
  35. char **argv = (char **)(uintptr_t)_argv;
  36. char *flag;
  37. int i;
  38. if(myoptind >= argc)
  39. return -1;
  40. flag = argv[myoptind];
  41. if(flag[0] == '-' && flag[1] != '-')
  42. {
  43. char *tmp;
  44. int ret = flag[1];
  45. if(ret == '\0')
  46. return -1;
  47. tmp = strchr(optstring, ret);
  48. if(!tmp || ret == ':')
  49. return '?';
  50. myoptind++;
  51. if(tmp[1] == ':')
  52. {
  53. if(flag[2] != '\0')
  54. myoptarg = tmp + 2;
  55. else
  56. myoptarg = argv[myoptind++];
  57. return ret;
  58. }
  59. if(flag[2] != '\0')
  60. {
  61. flag[1] = '-';
  62. myoptind--;
  63. argv[myoptind]++;
  64. }
  65. return ret;
  66. }
  67. if(flag[0] == '-' && flag[1] == '-')
  68. {
  69. if(flag[2] == '\0')
  70. return -1;
  71. for(i = 0; longopts[i].name; i++)
  72. {
  73. size_t l = strlen(longopts[i].name);
  74. if(strncmp(flag + 2, longopts[i].name, l))
  75. continue;
  76. switch(flag[2 + l])
  77. {
  78. case '=':
  79. if(!longopts[i].has_arg)
  80. goto bad_opt;
  81. if(longindex)
  82. *longindex = i;
  83. myoptind++;
  84. myoptarg = flag + 2 + l + 1;
  85. return longopts[i].val;
  86. case '\0':
  87. if(longindex)
  88. *longindex = i;
  89. myoptind++;
  90. if(longopts[i].has_arg)
  91. myoptarg = argv[myoptind++];
  92. return longopts[i].val;
  93. default:
  94. break;
  95. }
  96. }
  97. bad_opt:
  98. fprintf(stderr, "%s: unrecognized option `%s'\n", argv[0], flag);
  99. return '?';
  100. }
  101. return -1;
  102. }