blob: 3e38692c944a932acebb3254809a0070277321a5 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Args.cpp ------------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// C Includes
11#include <getopt.h>
Eli Friedman5661f922010-06-09 10:59:23 +000012#include <cstdlib>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000013// C++ Includes
14// Other libraries and framework includes
15// Project includes
16#include "lldb/Core/Args.h"
17#include "lldb/Core/Stream.h"
18#include "lldb/Core/StreamFile.h"
19#include "lldb/Core/StreamString.h"
20#include "lldb/Core/Options.h"
21#include "lldb/Interpreter/CommandReturnObject.h"
22
Chris Lattner30fdc8d2010-06-08 16:52:24 +000023using namespace lldb;
24using namespace lldb_private;
25
26static const char *k_space_characters = "\t\n\v\f\r ";
27static const char *k_space_characters_with_slash = "\t\n\v\f\r \\";
28
29
30//----------------------------------------------------------------------
31// Args constructor
32//----------------------------------------------------------------------
33Args::Args (const char *command) :
34 m_args(),
35 m_argv()
36{
37 SetCommandString (command);
38}
39
40
41Args::Args (const char *command, size_t len) :
42 m_args(),
43 m_argv()
44{
45 SetCommandString (command, len);
46}
47
48
49
50//----------------------------------------------------------------------
51// Destructor
52//----------------------------------------------------------------------
53Args::~Args ()
54{
55}
56
57void
58Args::Dump (Stream *s)
59{
60// int argc = GetArgumentCount();
61//
62// arg_sstr_collection::const_iterator pos, begin = m_args.begin(), end = m_args.end();
63// for (pos = m_args.begin(); pos != end; ++pos)
64// {
65// s->Indent();
66// s->Printf("args[%zu]=%s\n", std::distance(begin, pos), pos->c_str());
67// }
68// s->EOL();
69 const int argc = m_argv.size();
70 for (int i=0; i<argc; ++i)
71 {
72 s->Indent();
73 const char *arg_cstr = m_argv[i];
74 if (arg_cstr)
75 s->Printf("argv[%i]=\"%s\"\n", i, arg_cstr);
76 else
77 s->Printf("argv[%i]=NULL\n", i);
78 }
79 s->EOL();
80}
81
82bool
83Args::GetCommandString (std::string &command)
84{
85 command.clear();
86 int argc = GetArgumentCount();
87 for (int i=0; i<argc; ++i)
88 {
89 if (i > 0)
90 command += ' ';
91 command += m_argv[i];
92 }
93 return argc > 0;
94}
95
96void
97Args::SetCommandString (const char *command, size_t len)
98{
99 // Use std::string to make sure we get a NULL terminated string we can use
100 // as "command" could point to a string within a large string....
101 std::string null_terminated_command(command, len);
102 SetCommandString(null_terminated_command.c_str());
103}
104
105void
106Args::SetCommandString (const char *command)
107{
108 m_args.clear();
109 m_argv.clear();
110 if (command && command[0])
111 {
112 const char *arg_start;
113 const char *next_arg_start;
114 for (arg_start = command, next_arg_start = NULL;
115 arg_start && arg_start[0];
116 arg_start = next_arg_start, next_arg_start = NULL)
117 {
118 // Skip any leading space characters
119 arg_start = ::strspn (arg_start, k_space_characters) + arg_start;
120
121 // If there were only space characters to the end of the line, then
122 // we're done.
123 if (*arg_start == '\0')
124 break;
125
126 std::string arg;
127 const char *arg_end = NULL;
128
129 switch (*arg_start)
130 {
131 case '\'':
132 case '"':
133 case '`':
134 {
135 // Look for either a quote character, or the backslash
136 // character
137 const char quote_char = *arg_start;
138 char find_chars[3] = { quote_char, '\\' , '\0'};
139 bool is_backtick = (quote_char == '`');
140 if (quote_char == '"' || quote_char == '`')
141 m_args_quote_char.push_back(quote_char);
142 else
143 m_args_quote_char.push_back('\0');
144
145 while (*arg_start != '\0')
146 {
147 arg_end = ::strcspn (arg_start + 1, find_chars) + arg_start + 1;
148
149 if (*arg_end == '\0')
150 {
151 arg.append (arg_start);
152 break;
153 }
154
155 // Watch out for quote characters prefixed with '\'
156 if (*arg_end == '\\')
157 {
158 if (arg_end[1] == quote_char)
159 {
160 // The character following the '\' is our quote
161 // character so strip the backslash character
162 arg.append (arg_start, arg_end);
163 }
164 else
165 {
166 // The character following the '\' is NOT our
167 // quote character, so include the backslash
168 // and continue
169 arg.append (arg_start, arg_end + 1);
170 }
171 arg_start = arg_end + 1;
172 continue;
173 }
174 else
175 {
176 arg.append (arg_start, arg_end + 1);
177 next_arg_start = arg_end + 1;
178 break;
179 }
180 }
181
182 // Skip single and double quotes, but leave backtick quotes
183 if (!is_backtick)
184 {
185 char first_c = arg[0];
186 arg.erase(0,1);
187 // Only erase the last character if it is the same as the first.
188 // Otherwise, we're parsing an incomplete command line, and we
189 // would be stripping off the last character of that string.
190 if (arg[arg.size() - 1] == first_c)
191 arg.erase(arg.size() - 1, 1);
192 }
193 }
194 break;
195 default:
196 {
197 m_args_quote_char.push_back('\0');
198 // Look for the next non-escaped space character
199 while (*arg_start != '\0')
200 {
201 arg_end = ::strcspn (arg_start, k_space_characters_with_slash) + arg_start;
202
203 if (arg_end == NULL)
204 {
205 arg.append(arg_start);
206 break;
207 }
208
209 if (*arg_end == '\\')
210 {
211 // Append up to the '\' char
212 arg.append (arg_start, arg_end);
213
214 if (arg_end[1] == '\0')
215 break;
216
217 // Append the character following the '\' if it isn't
218 // the end of the string
219 arg.append (1, arg_end[1]);
220 arg_start = arg_end + 2;
221 continue;
222 }
223 else
224 {
225 arg.append (arg_start, arg_end);
226 next_arg_start = arg_end;
227 break;
228 }
229 }
230 }
231 break;
232 }
233
234 m_args.push_back(arg);
235 }
236 }
237 UpdateArgvFromArgs();
238}
239
240void
241Args::UpdateArgsAfterOptionParsing()
242{
243 // Now m_argv might be out of date with m_args, so we need to fix that
244 arg_cstr_collection::const_iterator argv_pos, argv_end = m_argv.end();
245 arg_sstr_collection::iterator args_pos;
246 arg_quote_char_collection::iterator quotes_pos;
247
248 for (argv_pos = m_argv.begin(), args_pos = m_args.begin(), quotes_pos = m_args_quote_char.begin();
249 argv_pos != argv_end && args_pos != m_args.end();
250 ++argv_pos)
251 {
252 const char *argv_cstr = *argv_pos;
253 if (argv_cstr == NULL)
254 break;
255
256 while (args_pos != m_args.end())
257 {
258 const char *args_cstr = args_pos->c_str();
259 if (args_cstr == argv_cstr)
260 {
261 // We found the argument that matches the C string in the
262 // vector, so we can now look for the next one
263 ++args_pos;
264 ++quotes_pos;
265 break;
266 }
267 else
268 {
269 quotes_pos = m_args_quote_char.erase (quotes_pos);
270 args_pos = m_args.erase (args_pos);
271 }
272 }
273 }
274
275 if (args_pos != m_args.end())
276 m_args.erase (args_pos, m_args.end());
277
278 if (quotes_pos != m_args_quote_char.end())
279 m_args_quote_char.erase (quotes_pos, m_args_quote_char.end());
280}
281
282void
283Args::UpdateArgvFromArgs()
284{
285 m_argv.clear();
286 arg_sstr_collection::const_iterator pos, end = m_args.end();
287 for (pos = m_args.begin(); pos != end; ++pos)
288 m_argv.push_back(pos->c_str());
289 m_argv.push_back(NULL);
290}
291
292size_t
293Args::GetArgumentCount() const
294{
295 if (m_argv.empty())
296 return 0;
297 return m_argv.size() - 1;
298}
299
300const char *
301Args::GetArgumentAtIndex (size_t idx) const
302{
303 if (idx < m_argv.size())
304 return m_argv[idx];
305 return NULL;
306}
307
308char
309Args::GetArgumentQuoteCharAtIndex (size_t idx) const
310{
311 if (idx < m_args_quote_char.size())
312 return m_args_quote_char[idx];
313 return '\0';
314}
315
316char **
317Args::GetArgumentVector()
318{
319 if (!m_argv.empty())
320 return (char **)&m_argv[0];
321 return NULL;
322}
323
324const char **
325Args::GetConstArgumentVector() const
326{
327 if (!m_argv.empty())
328 return (const char **)&m_argv[0];
329 return NULL;
330}
331
332void
333Args::Shift ()
334{
335 // Don't pop the last NULL terminator from the argv array
336 if (m_argv.size() > 1)
337 {
338 m_argv.erase(m_argv.begin());
339 m_args.pop_front();
340 m_args_quote_char.erase(m_args_quote_char.begin());
341 }
342}
343
344const char *
345Args::Unshift (const char *arg_cstr, char quote_char)
346{
347 m_args.push_front(arg_cstr);
348 m_argv.insert(m_argv.begin(), m_args.front().c_str());
349 m_args_quote_char.insert(m_args_quote_char.begin(), quote_char);
350 return GetArgumentAtIndex (0);
351}
352
353void
354Args::AppendArguments (const Args &rhs)
355{
356 const size_t rhs_argc = rhs.GetArgumentCount();
357 for (size_t i=0; i<rhs_argc; ++i)
358 AppendArgument(rhs.GetArgumentAtIndex(i));
359}
360
361const char *
362Args::AppendArgument (const char *arg_cstr, char quote_char)
363{
364 return InsertArgumentAtIndex (GetArgumentCount(), arg_cstr, quote_char);
365}
366
367const char *
368Args::InsertArgumentAtIndex (size_t idx, const char *arg_cstr, char quote_char)
369{
370 // Since we are using a std::list to hold onto the copied C string and
371 // we don't have direct access to the elements, we have to iterate to
372 // find the value.
373 arg_sstr_collection::iterator pos, end = m_args.end();
374 size_t i = idx;
375 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
376 --i;
377
378 pos = m_args.insert(pos, arg_cstr);
379
380
381 m_args_quote_char.insert(m_args_quote_char.begin() + idx, quote_char);
382
383 UpdateArgvFromArgs();
384 return GetArgumentAtIndex(idx);
385}
386
387const char *
388Args::ReplaceArgumentAtIndex (size_t idx, const char *arg_cstr, char quote_char)
389{
390 // Since we are using a std::list to hold onto the copied C string and
391 // we don't have direct access to the elements, we have to iterate to
392 // find the value.
393 arg_sstr_collection::iterator pos, end = m_args.end();
394 size_t i = idx;
395 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
396 --i;
397
398 if (pos != end)
399 {
400 pos->assign(arg_cstr);
401 assert(idx < m_argv.size() - 1);
402 m_argv[idx] = pos->c_str();
403 m_args_quote_char[idx] = quote_char;
404 return GetArgumentAtIndex(idx);
405 }
406 return NULL;
407}
408
409void
410Args::DeleteArgumentAtIndex (size_t idx)
411{
412 // Since we are using a std::list to hold onto the copied C string and
413 // we don't have direct access to the elements, we have to iterate to
414 // find the value.
415 arg_sstr_collection::iterator pos, end = m_args.end();
416 size_t i = idx;
417 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
418 --i;
419
420 if (pos != end)
421 {
422 m_args.erase (pos);
423 assert(idx < m_argv.size() - 1);
424 m_argv.erase(m_argv.begin() + idx);
425 m_args_quote_char.erase(m_args_quote_char.begin() + idx);
426 }
427}
428
429void
430Args::SetArguments (int argc, const char **argv)
431{
432 // m_argv will be rebuilt in UpdateArgvFromArgs() below, so there is
433 // no need to clear it here.
434 m_args.clear();
435 m_args_quote_char.clear();
436
437 // Make a copy of the arguments in our internal buffer
438 size_t i;
439 // First copy each string
440 for (i=0; i<argc; ++i)
441 {
442 m_args.push_back (argv[i]);
443 if ((argv[i][0] == '"') || (argv[i][0] == '`'))
444 m_args_quote_char.push_back (argv[i][0]);
445 else
446 m_args_quote_char.push_back ('\0');
447 }
448
449 UpdateArgvFromArgs();
450}
451
452
453Error
454Args::ParseOptions (Options &options)
455{
456 StreamString sstr;
457 int i;
458 Error error;
459 struct option *long_options = options.GetLongOptions();
460 if (long_options == NULL)
461 {
462 error.SetErrorStringWithFormat("Invalid long options.\n");
463 return error;
464 }
465
466 for (i=0; long_options[i].name != NULL; ++i)
467 {
468 if (long_options[i].flag == NULL)
469 {
470 sstr << (char)long_options[i].val;
471 switch (long_options[i].has_arg)
472 {
473 default:
474 case no_argument: break;
475 case required_argument: sstr << ':'; break;
476 case optional_argument: sstr << "::"; break;
477 }
478 }
479 }
480 optreset = 1;
481 optind = 1;
482 int val;
483 while (1)
484 {
485 int long_options_index = -1;
486 val = ::getopt_long(GetArgumentCount(), GetArgumentVector(), sstr.GetData(), long_options,
487 &long_options_index);
488 if (val == -1)
489 break;
490
491 // Did we get an error?
492 if (val == '?')
493 {
494 error.SetErrorStringWithFormat("Unknown or ambiguous option.\n");
495 break;
496 }
497 // The option auto-set itself
498 if (val == 0)
499 continue;
500
501 ((Options *) &options)->OptionSeen (val);
502
503 // Lookup the long option index
504 if (long_options_index == -1)
505 {
506 for (int i=0;
507 long_options[i].name || long_options[i].has_arg || long_options[i].flag || long_options[i].val;
508 ++i)
509 {
510 if (long_options[i].val == val)
511 {
512 long_options_index = i;
513 break;
514 }
515 }
516 }
517 // Call the callback with the option
518 if (long_options_index >= 0)
519 {
520 error = options.SetOptionValue(long_options_index,
521 long_options[long_options_index].has_arg == no_argument ? NULL : optarg);
522 }
523 else
524 {
525 error.SetErrorStringWithFormat("Invalid option with value '%i'.\n", val);
526 }
527 if (error.Fail())
528 break;
529 }
530
531 // Update our ARGV now that get options has consumed all the options
532 m_argv.erase(m_argv.begin(), m_argv.begin() + optind);
533 UpdateArgsAfterOptionParsing ();
534 return error;
535}
536
537void
538Args::Clear ()
539{
540 m_args.clear ();
541 m_argv.clear ();
542 m_args_quote_char.clear();
543}
544
545int32_t
546Args::StringToSInt32 (const char *s, int32_t fail_value, int base, bool *success_ptr)
547{
548 if (s && s[0])
549 {
550 char *end = NULL;
551 int32_t uval = ::strtol (s, &end, base);
552 if (*end == '\0')
553 {
554 if (success_ptr) *success_ptr = true;
555 return uval; // All characters were used, return the result
556 }
557 }
558 if (success_ptr) *success_ptr = false;
559 return fail_value;
560}
561
562uint32_t
563Args::StringToUInt32 (const char *s, uint32_t fail_value, int base, bool *success_ptr)
564{
565 if (s && s[0])
566 {
567 char *end = NULL;
568 uint32_t uval = ::strtoul (s, &end, base);
569 if (*end == '\0')
570 {
571 if (success_ptr) *success_ptr = true;
572 return uval; // All characters were used, return the result
573 }
574 }
575 if (success_ptr) *success_ptr = false;
576 return fail_value;
577}
578
579
580int64_t
581Args::StringToSInt64 (const char *s, int64_t fail_value, int base, bool *success_ptr)
582{
583 if (s && s[0])
584 {
585 char *end = NULL;
586 int64_t uval = ::strtoll (s, &end, base);
587 if (*end == '\0')
588 {
589 if (success_ptr) *success_ptr = true;
590 return uval; // All characters were used, return the result
591 }
592 }
593 if (success_ptr) *success_ptr = false;
594 return fail_value;
595}
596
597uint64_t
598Args::StringToUInt64 (const char *s, uint64_t fail_value, int base, bool *success_ptr)
599{
600 if (s && s[0])
601 {
602 char *end = NULL;
603 uint64_t uval = ::strtoull (s, &end, base);
604 if (*end == '\0')
605 {
606 if (success_ptr) *success_ptr = true;
607 return uval; // All characters were used, return the result
608 }
609 }
610 if (success_ptr) *success_ptr = false;
611 return fail_value;
612}
613
614lldb::addr_t
615Args::StringToAddress (const char *s, lldb::addr_t fail_value, bool *success_ptr)
616{
617 if (s && s[0])
618 {
619 char *end = NULL;
620 lldb::addr_t addr = ::strtoull (s, &end, 0);
621 if (*end == '\0')
622 {
623 if (success_ptr) *success_ptr = true;
624 return addr; // All characters were used, return the result
625 }
626 // Try base 16 with no prefix...
627 addr = ::strtoull (s, &end, 16);
628 if (*end == '\0')
629 {
630 if (success_ptr) *success_ptr = true;
631 return addr; // All characters were used, return the result
632 }
633 }
634 if (success_ptr) *success_ptr = false;
635 return fail_value;
636}
637
638bool
639Args::StringToBoolean (const char *s, bool fail_value, bool *success_ptr)
640{
641 if (s && s[0])
642 {
643 if (::strcasecmp (s, "false") == 0 ||
644 ::strcasecmp (s, "off") == 0 ||
645 ::strcasecmp (s, "no") == 0 ||
646 ::strcmp (s, "0") == 0)
647 {
648 if (success_ptr)
649 *success_ptr = true;
650 return false;
651 }
652 else
653 if (::strcasecmp (s, "true") == 0 ||
654 ::strcasecmp (s, "on") == 0 ||
655 ::strcasecmp (s, "yes") == 0 ||
656 ::strcmp (s, "1") == 0)
657 {
658 if (success_ptr) *success_ptr = true;
659 return true;
660 }
661 }
662 if (success_ptr) *success_ptr = false;
663 return fail_value;
664}
665
666int32_t
667Args::StringToOptionEnum (const char *s, lldb::OptionEnumValueElement *enum_values, int32_t fail_value, bool *success_ptr)
668{
669 if (enum_values && s && s[0])
670 {
671 for (int i = 0; enum_values[i].string_value != NULL ; i++)
672 {
673 if (strstr(enum_values[i].string_value, s) == enum_values[i].string_value)
674 {
675 if (success_ptr) *success_ptr = true;
676 return enum_values[i].value;
677 }
678 }
679 }
680 if (success_ptr) *success_ptr = false;
681
682 return fail_value;
683}
684
685ScriptLanguage
686Args::StringToScriptLanguage (const char *s, ScriptLanguage fail_value, bool *success_ptr)
687{
688 if (s && s[0])
689 {
690 if ((::strcasecmp (s, "python") == 0) ||
691 (::strcasecmp (s, "default") == 0 && eScriptLanguagePython == eScriptLanguageDefault))
692 {
693 if (success_ptr) *success_ptr = true;
694 return eScriptLanguagePython;
695 }
696 if (::strcasecmp (s, "none"))
697 {
698 if (success_ptr) *success_ptr = true;
699 return eScriptLanguageNone;
700 }
701 }
702 if (success_ptr) *success_ptr = false;
703 return fail_value;
704}
705
706Error
707Args::StringToFormat
708(
709 const char *s,
710 lldb::Format &format
711)
712{
713 format = eFormatInvalid;
714 Error error;
715
716 if (s && s[0])
717 {
718 switch (s[0])
719 {
720 case 'y': format = eFormatBytes; break;
721 case 'Y': format = eFormatBytesWithASCII; break;
722 case 'b': format = eFormatBinary; break;
723 case 'B': format = eFormatBoolean; break;
724 case 'c': format = eFormatChar; break;
725 case 'C': format = eFormatCharPrintable; break;
726 case 'o': format = eFormatOctal; break;
727 case 'i':
728 case 'd': format = eFormatDecimal; break;
729 case 'u': format = eFormatUnsigned; break;
730 case 'x': format = eFormatHex; break;
731 case 'f':
732 case 'e':
733 case 'g': format = eFormatFloat; break;
734 case 'p': format = eFormatPointer; break;
735 case 's': format = eFormatCString; break;
736 default:
737 error.SetErrorStringWithFormat("Invalid format character '%c'. Valid values are:\n"
738 " b - binary\n"
739 " B - boolean\n"
740 " c - char\n"
741 " C - printable char\n"
742 " d - signed decimal\n"
743 " e - float\n"
744 " f - float\n"
745 " g - float\n"
746 " i - signed decimal\n"
747 " o - octal\n"
748 " s - c-string\n"
749 " u - unsigned decimal\n"
750 " x - hex\n"
751 " y - bytes\n"
752 " Y - bytes with ASCII\n", s[0]);
753 break;
754 }
755
756 if (error.Fail())
757 return error;
758 }
759 else
760 {
761 error.SetErrorStringWithFormat("%s option string.\n", s ? "empty" : "invalid");
762 }
763 return error;
764}
765
766void
767Args::LongestCommonPrefix (std::string &common_prefix)
768{
769 arg_sstr_collection::iterator pos, end = m_args.end();
770 pos = m_args.begin();
771 if (pos == end)
772 common_prefix.clear();
773 else
774 common_prefix = (*pos);
775
776 for (++pos; pos != end; ++pos)
777 {
778 int new_size = (*pos).size();
779
780 // First trim common_prefix if it is longer than the current element:
781 if (common_prefix.size() > new_size)
782 common_prefix.erase (new_size);
783
784 // Then trim it at the first disparity:
785
786 for (int i = 0; i < common_prefix.size(); i++)
787 {
788 if ((*pos)[i] != common_prefix[i])
789 {
790 common_prefix.erase(i);
791 break;
792 }
793 }
794
795 // If we've emptied the common prefix, we're done.
796 if (common_prefix.empty())
797 break;
798 }
799}
800
801void
802Args::ParseAliasOptions
803(
804 Options &options,
805 CommandReturnObject &result,
806 OptionArgVector *option_arg_vector
807)
808{
809 StreamString sstr;
810 int i;
811 struct option *long_options = options.GetLongOptions();
812
813 if (long_options == NULL)
814 {
815 result.AppendError ("invalid long options");
816 result.SetStatus (eReturnStatusFailed);
817 return;
818 }
819
820 for (i = 0; long_options[i].name != NULL; ++i)
821 {
822 if (long_options[i].flag == NULL)
823 {
824 sstr << (char) long_options[i].val;
825 switch (long_options[i].has_arg)
826 {
827 default:
828 case no_argument:
829 break;
830 case required_argument:
831 sstr << ":";
832 break;
833 case optional_argument:
834 sstr << "::";
835 break;
836 }
837 }
838 }
839
840 optreset = 1;
841 optind = 1;
842 int val;
843 while (1)
844 {
845 int long_options_index = -1;
846 val = ::getopt_long (GetArgumentCount(), GetArgumentVector(), sstr.GetData(), long_options,
847 &long_options_index);
848
849 if (val == -1)
850 break;
851
852 if (val == '?')
853 {
854 result.AppendError ("unknown or ambiguous option");
855 result.SetStatus (eReturnStatusFailed);
856 break;
857 }
858
859 if (val == 0)
860 continue;
861
862 ((Options *) &options)->OptionSeen (val);
863
864 // Look up the long option index
865 if (long_options_index == -1)
866 {
867 for (int j = 0;
868 long_options[j].name || long_options[j].has_arg || long_options[j].flag || long_options[j].val;
869 ++j)
870 {
871 if (long_options[j].val == val)
872 {
873 long_options_index = j;
874 break;
875 }
876 }
877 }
878
879 // See if the option takes an argument, and see if one was supplied.
880 if (long_options_index >= 0)
881 {
882 StreamString option_str;
883 option_str.Printf ("-%c", (char) val);
884
885 switch (long_options[long_options_index].has_arg)
886 {
887 case no_argument:
888 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()), "<no-argument>"));
889 break;
890 case required_argument:
891 if (optarg != NULL)
892 {
893 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
894 std::string (optarg)));
895 result.SetStatus (eReturnStatusSuccessFinishNoResult);
896 }
897 else
898 {
899 result.AppendErrorWithFormat ("Option '%s' is missing argument specifier.\n",
900 option_str.GetData());
901 result.SetStatus (eReturnStatusFailed);
902 }
903 break;
904 case optional_argument:
905 if (optarg != NULL)
906 {
907 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
908 std::string (optarg)));
909 result.SetStatus (eReturnStatusSuccessFinishNoResult);
910 }
911 else
912 {
913 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
914 "<no-argument>"));
915 result.SetStatus (eReturnStatusSuccessFinishNoResult);
916 }
917 break;
918 default:
919 result.AppendErrorWithFormat
920 ("error with options table; invalid value in has_arg field for option '%c'.\n",
921 (char) val);
922 result.SetStatus (eReturnStatusFailed);
923 break;
924 }
925 }
926 else
927 {
928 result.AppendErrorWithFormat ("Invalid option with value '%c'.\n", (char) val);
929 result.SetStatus (eReturnStatusFailed);
930 }
931 if (!result.Succeeded())
932 break;
933 }
934}
935
936void
937Args::ParseArgsForCompletion
938(
939 Options &options,
940 OptionElementVector &option_element_vector
941)
942{
943 StreamString sstr;
944 int i;
945 struct option *long_options = options.GetLongOptions();
946 option_element_vector.clear();
947
948 if (long_options == NULL)
949 {
950 return;
951 }
952
953 // Leading : tells getopt to return a : for a missing option argument AND
954 // to suppress error messages.
955
956 sstr << ":";
957 for (i = 0; long_options[i].name != NULL; ++i)
958 {
959 if (long_options[i].flag == NULL)
960 {
961 sstr << (char) long_options[i].val;
962 switch (long_options[i].has_arg)
963 {
964 default:
965 case no_argument:
966 break;
967 case required_argument:
968 sstr << ":";
969 break;
970 case optional_argument:
971 sstr << "::";
972 break;
973 }
974 }
975 }
976
977 optreset = 1;
978 optind = 1;
979 opterr = 0;
980
981 int val;
982 const OptionDefinition *opt_defs = options.GetDefinitions();
983
984 // Fooey... getopt_long permutes the GetArgumentVector for no apparent reason.
985 // So we have to build another Arg and pass that to getopt_long so it doesn't
986 // screw up the one we have.
987
988 std::vector<const char *> dummy_vec(GetArgumentVector(), GetArgumentVector() + GetArgumentCount() + 1);
989
990 while (1)
991 {
992 bool missing_argument = false;
993 int parse_start = optind;
994 int long_options_index = -1;
995 val = ::getopt_long (dummy_vec.size() - 1,(char *const *) dummy_vec.data(), sstr.GetData(), long_options,
996 &long_options_index);
997
998 if (val == -1)
999 break;
1000
1001 else if (val == '?')
1002 {
1003 option_element_vector.push_back (OptionArgElement (-1, parse_start, -1));
1004 continue;
1005 }
1006 else if (val == 0)
1007 {
1008 continue;
1009 }
1010 else if (val == ':')
1011 {
1012 // This is a missing argument.
1013 val = optopt;
1014 missing_argument = true;
1015 }
1016
1017 ((Options *) &options)->OptionSeen (val);
1018
1019 // Look up the long option index
1020 if (long_options_index == -1)
1021 {
1022 for (int j = 0;
1023 long_options[j].name || long_options[j].has_arg || long_options[j].flag || long_options[j].val;
1024 ++j)
1025 {
1026 if (long_options[j].val == val)
1027 {
1028 long_options_index = j;
1029 break;
1030 }
1031 }
1032 }
1033
1034 // See if the option takes an argument, and see if one was supplied.
1035 if (long_options_index >= 0)
1036 {
1037 int opt_defs_index = -1;
1038 for (int i = 0; ; i++)
1039 {
1040 if (opt_defs[i].short_option == 0)
1041 break;
1042 else if (opt_defs[i].short_option == val)
1043 {
1044 opt_defs_index = i;
1045 break;
1046 }
1047 }
1048
1049 switch (long_options[long_options_index].has_arg)
1050 {
1051 case no_argument:
1052 option_element_vector.push_back (OptionArgElement (opt_defs_index, parse_start, 0));
1053 break;
1054 case required_argument:
1055 if (optarg != NULL)
1056 {
1057 int arg_index;
1058 if (missing_argument)
1059 arg_index = -1;
1060 else
1061 arg_index = parse_start + 1;
1062
1063 option_element_vector.push_back (OptionArgElement (opt_defs_index, parse_start, arg_index));
1064 }
1065 else
1066 {
1067 option_element_vector.push_back (OptionArgElement (opt_defs_index, parse_start, -1));
1068 }
1069 break;
1070 case optional_argument:
1071 if (optarg != NULL)
1072 {
1073 option_element_vector.push_back (OptionArgElement (opt_defs_index, parse_start, 0));
1074 }
1075 else
1076 {
1077 option_element_vector.push_back (OptionArgElement (opt_defs_index, parse_start, parse_start + 1));
1078 }
1079 break;
1080 default:
1081 // The options table is messed up. Here we'll just continue
1082 option_element_vector.push_back (OptionArgElement (-1, parse_start, -1));
1083 break;
1084 }
1085 }
1086 else
1087 {
1088 option_element_vector.push_back (OptionArgElement (-1, parse_start, -1));
1089 }
1090 }
1091}