blob: f32b25c9127ebd28d34e4195fa2ed25b6f3545ad [file] [log] [blame]
Chris Lattner24943d22010-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 Friedman27cd8892010-06-09 10:59:23 +000012#include <cstdlib>
Chris Lattner24943d22010-06-08 16:52:24 +000013// C++ Includes
14// Other libraries and framework includes
15// Project includes
Jim Ingham84cdc152010-06-15 19:49:27 +000016#include "lldb/Interpreter/Args.h"
Greg Clayton3182eff2011-06-23 21:22:24 +000017#include "lldb/Core/FormatManager.h"
Chris Lattner24943d22010-06-08 16:52:24 +000018#include "lldb/Core/Stream.h"
19#include "lldb/Core/StreamFile.h"
20#include "lldb/Core/StreamString.h"
Jim Ingham84cdc152010-06-15 19:49:27 +000021#include "lldb/Interpreter/Options.h"
Chris Lattner24943d22010-06-08 16:52:24 +000022#include "lldb/Interpreter/CommandReturnObject.h"
23
Chris Lattner24943d22010-06-08 16:52:24 +000024using namespace lldb;
25using namespace lldb_private;
26
Chris Lattner24943d22010-06-08 16:52:24 +000027//----------------------------------------------------------------------
28// Args constructor
29//----------------------------------------------------------------------
30Args::Args (const char *command) :
31 m_args(),
Greg Claytonb72d0f02011-04-12 05:54:46 +000032 m_argv(),
33 m_args_quote_char()
Chris Lattner24943d22010-06-08 16:52:24 +000034{
Greg Clayton928d1302010-12-19 03:41:24 +000035 if (command)
36 SetCommandString (command);
Chris Lattner24943d22010-06-08 16:52:24 +000037}
38
39
40Args::Args (const char *command, size_t len) :
41 m_args(),
Greg Claytonb72d0f02011-04-12 05:54:46 +000042 m_argv(),
43 m_args_quote_char()
Chris Lattner24943d22010-06-08 16:52:24 +000044{
Greg Clayton928d1302010-12-19 03:41:24 +000045 if (command && len)
46 SetCommandString (command, len);
Chris Lattner24943d22010-06-08 16:52:24 +000047}
48
Chris Lattner24943d22010-06-08 16:52:24 +000049//----------------------------------------------------------------------
Greg Claytonb72d0f02011-04-12 05:54:46 +000050// We have to be very careful on the copy constructor of this class
51// to make sure we copy all of the string values, but we can't copy the
52// rhs.m_argv into m_argv since it will point to the "const char *" c
53// strings in rhs.m_args. We need to copy the string list and update our
54// own m_argv appropriately.
55//----------------------------------------------------------------------
56Args::Args (const Args &rhs) :
57 m_args (rhs.m_args),
58 m_argv (),
59 m_args_quote_char(rhs.m_args_quote_char)
60{
61 UpdateArgvFromArgs();
62}
63
64//----------------------------------------------------------------------
65// We have to be very careful on the copy constructor of this class
66// to make sure we copy all of the string values, but we can't copy the
67// rhs.m_argv into m_argv since it will point to the "const char *" c
68// strings in rhs.m_args. We need to copy the string list and update our
69// own m_argv appropriately.
70//----------------------------------------------------------------------
71const Args &
72Args::operator= (const Args &rhs)
73{
74 // Make sure we aren't assigning to self
75 if (this != &rhs)
76 {
77 m_args = rhs.m_args;
78 m_args_quote_char = rhs.m_args_quote_char;
79 UpdateArgvFromArgs();
80 }
81 return *this;
82}
83
84//----------------------------------------------------------------------
Chris Lattner24943d22010-06-08 16:52:24 +000085// Destructor
86//----------------------------------------------------------------------
87Args::~Args ()
88{
89}
90
91void
92Args::Dump (Stream *s)
93{
94// int argc = GetArgumentCount();
95//
96// arg_sstr_collection::const_iterator pos, begin = m_args.begin(), end = m_args.end();
97// for (pos = m_args.begin(); pos != end; ++pos)
98// {
99// s->Indent();
100// s->Printf("args[%zu]=%s\n", std::distance(begin, pos), pos->c_str());
101// }
102// s->EOL();
103 const int argc = m_argv.size();
104 for (int i=0; i<argc; ++i)
105 {
106 s->Indent();
107 const char *arg_cstr = m_argv[i];
108 if (arg_cstr)
109 s->Printf("argv[%i]=\"%s\"\n", i, arg_cstr);
110 else
111 s->Printf("argv[%i]=NULL\n", i);
112 }
113 s->EOL();
114}
115
116bool
117Args::GetCommandString (std::string &command)
118{
119 command.clear();
120 int argc = GetArgumentCount();
121 for (int i=0; i<argc; ++i)
122 {
123 if (i > 0)
124 command += ' ';
125 command += m_argv[i];
126 }
127 return argc > 0;
128}
129
Caroline Ticed9105c22010-12-10 00:26:54 +0000130bool
131Args::GetQuotedCommandString (std::string &command)
132{
133 command.clear ();
Greg Clayton928d1302010-12-19 03:41:24 +0000134 size_t argc = GetArgumentCount ();
135 for (size_t i = 0; i < argc; ++i)
Caroline Ticed9105c22010-12-10 00:26:54 +0000136 {
137 if (i > 0)
Greg Clayton928d1302010-12-19 03:41:24 +0000138 command.append (1, ' ');
139 char quote_char = GetArgumentQuoteCharAtIndex(i);
140 if (quote_char)
Caroline Ticed9105c22010-12-10 00:26:54 +0000141 {
Greg Clayton928d1302010-12-19 03:41:24 +0000142 command.append (1, quote_char);
143 command.append (m_argv[i]);
144 command.append (1, quote_char);
Caroline Ticed9105c22010-12-10 00:26:54 +0000145 }
146 else
Greg Clayton928d1302010-12-19 03:41:24 +0000147 command.append (m_argv[i]);
Caroline Ticed9105c22010-12-10 00:26:54 +0000148 }
149 return argc > 0;
150}
151
Chris Lattner24943d22010-06-08 16:52:24 +0000152void
153Args::SetCommandString (const char *command, size_t len)
154{
155 // Use std::string to make sure we get a NULL terminated string we can use
156 // as "command" could point to a string within a large string....
157 std::string null_terminated_command(command, len);
158 SetCommandString(null_terminated_command.c_str());
159}
160
161void
162Args::SetCommandString (const char *command)
163{
164 m_args.clear();
165 m_argv.clear();
Greg Clayton928d1302010-12-19 03:41:24 +0000166 m_args_quote_char.clear();
167
Chris Lattner24943d22010-06-08 16:52:24 +0000168 if (command && command[0])
169 {
Greg Clayton928d1302010-12-19 03:41:24 +0000170 static const char *k_space_separators = " \t";
171 static const char *k_space_separators_with_slash_and_quotes = " \t \\'\"`";
172 const char *arg_end = NULL;
173 const char *arg_pos;
174 for (arg_pos = command;
175 arg_pos && arg_pos[0];
176 arg_pos = arg_end)
Chris Lattner24943d22010-06-08 16:52:24 +0000177 {
Greg Clayton928d1302010-12-19 03:41:24 +0000178 // Skip any leading space separators
179 const char *arg_start = ::strspn (arg_pos, k_space_separators) + arg_pos;
180
181 // If there were only space separators to the end of the line, then
Chris Lattner24943d22010-06-08 16:52:24 +0000182 // we're done.
183 if (*arg_start == '\0')
184 break;
185
Greg Clayton5d187e52011-01-08 20:28:42 +0000186 // Arguments can be split into multiple discontiguous pieces,
Greg Clayton928d1302010-12-19 03:41:24 +0000187 // for example:
188 // "Hello ""World"
189 // this would result in a single argument "Hello World" (without/
190 // the quotes) since the quotes would be removed and there is
191 // not space between the strings. So we need to keep track of the
192 // current start of each argument piece in "arg_piece_start"
193 const char *arg_piece_start = arg_start;
194 arg_pos = arg_piece_start;
195
Chris Lattner24943d22010-06-08 16:52:24 +0000196 std::string arg;
Greg Clayton928d1302010-12-19 03:41:24 +0000197 // Since we can have multiple quotes that form a single command
198 // in a command like: "Hello "world'!' (which will make a single
199 // argument "Hello world!") we remember the first quote character
200 // we encounter and use that for the quote character.
201 char first_quote_char = '\0';
202 char quote_char = '\0';
203 bool arg_complete = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000204
Greg Clayton928d1302010-12-19 03:41:24 +0000205 do
Chris Lattner24943d22010-06-08 16:52:24 +0000206 {
Greg Clayton928d1302010-12-19 03:41:24 +0000207 arg_end = ::strcspn (arg_pos, k_space_separators_with_slash_and_quotes) + arg_pos;
208
209 switch (arg_end[0])
Chris Lattner24943d22010-06-08 16:52:24 +0000210 {
Greg Clayton928d1302010-12-19 03:41:24 +0000211 default:
212 assert (!"Unhandled case statement, we must handle this...");
213 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000214
Greg Clayton928d1302010-12-19 03:41:24 +0000215 case '\0':
216 // End of C string
217 if (arg_piece_start && arg_piece_start[0])
218 arg.append (arg_piece_start);
219 arg_complete = true;
220 break;
221
222 case '\\':
223 // Backslash character
224 switch (arg_end[1])
Chris Lattner24943d22010-06-08 16:52:24 +0000225 {
Greg Clayton928d1302010-12-19 03:41:24 +0000226 case '\0':
227 arg.append (arg_piece_start);
228 arg_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000229 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000230
Greg Clayton928d1302010-12-19 03:41:24 +0000231 default:
232 arg_pos = arg_end + 2;
233 break;
234 }
235 break;
236
237 case '"':
238 case '\'':
239 case '`':
240 // Quote characters
241 if (quote_char)
242 {
243 // We found a quote character while inside a quoted
244 // character argument. If it matches our current quote
245 // character, this ends the effect of the quotes. If it
246 // doesn't we ignore it.
247 if (quote_char == arg_end[0])
Chris Lattner24943d22010-06-08 16:52:24 +0000248 {
Greg Clayton928d1302010-12-19 03:41:24 +0000249 arg.append (arg_piece_start, arg_end - arg_piece_start);
250 // Clear the quote character and let parsing
251 // continue (we need to watch for things like:
252 // "Hello ""World"
253 // "Hello "World
254 // "Hello "'World'
255 // All of which will result in a single argument "Hello World"
256 quote_char = '\0'; // Note that we are no longer inside quotes
257 arg_pos = arg_end + 1; // Skip the quote character
258 arg_piece_start = arg_pos; // Note we are starting from later in the string
259 }
260 else
261 {
262 // different quote, skip it and keep going
263 arg_pos = arg_end + 1;
264 }
265 }
266 else
267 {
268 // We found the start of a quote scope.
Greg Clayton5d187e52011-01-08 20:28:42 +0000269 // Make sure there isn't a string that precedes
Greg Clayton928d1302010-12-19 03:41:24 +0000270 // the start of a quote scope like:
271 // Hello" World"
272 // If so, then add the "Hello" to the arg
273 if (arg_end > arg_piece_start)
274 arg.append (arg_piece_start, arg_end - arg_piece_start);
275
276 // Enter into a quote scope
277 quote_char = arg_end[0];
278
279 if (first_quote_char == '\0')
280 first_quote_char = quote_char;
281
282 arg_pos = arg_end;
283
284 if (quote_char != '`')
285 ++arg_pos; // Skip the quote character if it is not a backtick
286
287 arg_piece_start = arg_pos; // Note we are starting from later in the string
288
289 // Skip till the next quote character
290 const char *end_quote = ::strchr (arg_piece_start, quote_char);
291 while (end_quote && end_quote[-1] == '\\')
292 {
293 // Don't skip the quote character if it is
294 // preceded by a '\' character
295 end_quote = ::strchr (end_quote + 1, quote_char);
296 }
297
298 if (end_quote)
299 {
300 if (end_quote > arg_piece_start)
Chris Lattner24943d22010-06-08 16:52:24 +0000301 {
Greg Clayton928d1302010-12-19 03:41:24 +0000302 // Keep the backtick quote on commands
303 if (quote_char == '`')
304 arg.append (arg_piece_start, end_quote + 1 - arg_piece_start);
305 else
306 arg.append (arg_piece_start, end_quote - arg_piece_start);
307 }
308
309 // If the next character is a space or the end of
310 // string, this argument is complete...
311 if (end_quote[1] == ' ' || end_quote[1] == '\t' || end_quote[1] == '\0')
312 {
313 arg_complete = true;
314 arg_end = end_quote + 1;
Chris Lattner24943d22010-06-08 16:52:24 +0000315 }
316 else
317 {
Greg Clayton928d1302010-12-19 03:41:24 +0000318 arg_pos = end_quote + 1;
319 arg_piece_start = arg_pos;
Chris Lattner24943d22010-06-08 16:52:24 +0000320 }
Greg Clayton928d1302010-12-19 03:41:24 +0000321 quote_char = '\0';
Chris Lattner24943d22010-06-08 16:52:24 +0000322 }
323 }
Greg Clayton928d1302010-12-19 03:41:24 +0000324 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000325
Greg Clayton928d1302010-12-19 03:41:24 +0000326 case ' ':
327 case '\t':
328 if (quote_char)
Chris Lattner24943d22010-06-08 16:52:24 +0000329 {
Greg Clayton928d1302010-12-19 03:41:24 +0000330 // We are currently processing a quoted character and found
331 // a space character, skip any spaces and keep trying to find
332 // the end of the argument.
333 arg_pos = ::strspn (arg_end, k_space_separators) + arg_end;
Chris Lattner24943d22010-06-08 16:52:24 +0000334 }
Greg Clayton928d1302010-12-19 03:41:24 +0000335 else
Chris Lattner24943d22010-06-08 16:52:24 +0000336 {
Greg Clayton928d1302010-12-19 03:41:24 +0000337 // We are not inside any quotes, we just found a space after an
338 // argument
339 if (arg_end > arg_piece_start)
340 arg.append (arg_piece_start, arg_end - arg_piece_start);
341 arg_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000342 }
Greg Clayton928d1302010-12-19 03:41:24 +0000343 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000344 }
Greg Clayton928d1302010-12-19 03:41:24 +0000345 } while (!arg_complete);
Chris Lattner24943d22010-06-08 16:52:24 +0000346
347 m_args.push_back(arg);
Greg Clayton928d1302010-12-19 03:41:24 +0000348 m_args_quote_char.push_back (first_quote_char);
Chris Lattner24943d22010-06-08 16:52:24 +0000349 }
Greg Clayton928d1302010-12-19 03:41:24 +0000350 UpdateArgvFromArgs();
Chris Lattner24943d22010-06-08 16:52:24 +0000351 }
Chris Lattner24943d22010-06-08 16:52:24 +0000352}
353
354void
355Args::UpdateArgsAfterOptionParsing()
356{
357 // Now m_argv might be out of date with m_args, so we need to fix that
358 arg_cstr_collection::const_iterator argv_pos, argv_end = m_argv.end();
359 arg_sstr_collection::iterator args_pos;
360 arg_quote_char_collection::iterator quotes_pos;
361
362 for (argv_pos = m_argv.begin(), args_pos = m_args.begin(), quotes_pos = m_args_quote_char.begin();
363 argv_pos != argv_end && args_pos != m_args.end();
364 ++argv_pos)
365 {
366 const char *argv_cstr = *argv_pos;
367 if (argv_cstr == NULL)
368 break;
369
370 while (args_pos != m_args.end())
371 {
372 const char *args_cstr = args_pos->c_str();
373 if (args_cstr == argv_cstr)
374 {
375 // We found the argument that matches the C string in the
376 // vector, so we can now look for the next one
377 ++args_pos;
378 ++quotes_pos;
379 break;
380 }
381 else
382 {
383 quotes_pos = m_args_quote_char.erase (quotes_pos);
384 args_pos = m_args.erase (args_pos);
385 }
386 }
387 }
388
389 if (args_pos != m_args.end())
390 m_args.erase (args_pos, m_args.end());
391
392 if (quotes_pos != m_args_quote_char.end())
393 m_args_quote_char.erase (quotes_pos, m_args_quote_char.end());
394}
395
396void
397Args::UpdateArgvFromArgs()
398{
399 m_argv.clear();
400 arg_sstr_collection::const_iterator pos, end = m_args.end();
401 for (pos = m_args.begin(); pos != end; ++pos)
402 m_argv.push_back(pos->c_str());
403 m_argv.push_back(NULL);
Greg Clayton928d1302010-12-19 03:41:24 +0000404 // Make sure we have enough arg quote chars in the array
405 if (m_args_quote_char.size() < m_args.size())
406 m_args_quote_char.resize (m_argv.size());
Chris Lattner24943d22010-06-08 16:52:24 +0000407}
408
409size_t
410Args::GetArgumentCount() const
411{
412 if (m_argv.empty())
413 return 0;
414 return m_argv.size() - 1;
415}
416
417const char *
418Args::GetArgumentAtIndex (size_t idx) const
419{
420 if (idx < m_argv.size())
421 return m_argv[idx];
422 return NULL;
423}
424
425char
426Args::GetArgumentQuoteCharAtIndex (size_t idx) const
427{
428 if (idx < m_args_quote_char.size())
429 return m_args_quote_char[idx];
430 return '\0';
431}
432
433char **
434Args::GetArgumentVector()
435{
436 if (!m_argv.empty())
437 return (char **)&m_argv[0];
438 return NULL;
439}
440
441const char **
442Args::GetConstArgumentVector() const
443{
444 if (!m_argv.empty())
445 return (const char **)&m_argv[0];
446 return NULL;
447}
448
449void
450Args::Shift ()
451{
452 // Don't pop the last NULL terminator from the argv array
453 if (m_argv.size() > 1)
454 {
455 m_argv.erase(m_argv.begin());
456 m_args.pop_front();
Greg Clayton928d1302010-12-19 03:41:24 +0000457 if (!m_args_quote_char.empty())
458 m_args_quote_char.erase(m_args_quote_char.begin());
Chris Lattner24943d22010-06-08 16:52:24 +0000459 }
460}
461
462const char *
463Args::Unshift (const char *arg_cstr, char quote_char)
464{
465 m_args.push_front(arg_cstr);
466 m_argv.insert(m_argv.begin(), m_args.front().c_str());
467 m_args_quote_char.insert(m_args_quote_char.begin(), quote_char);
468 return GetArgumentAtIndex (0);
469}
470
471void
472Args::AppendArguments (const Args &rhs)
473{
474 const size_t rhs_argc = rhs.GetArgumentCount();
475 for (size_t i=0; i<rhs_argc; ++i)
476 AppendArgument(rhs.GetArgumentAtIndex(i));
477}
478
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000479void
480Args::AppendArguments (const char **argv)
481{
482 if (argv)
483 {
484 for (uint32_t i=0; argv[i]; ++i)
485 AppendArgument(argv[i]);
486 }
487}
488
Chris Lattner24943d22010-06-08 16:52:24 +0000489const char *
490Args::AppendArgument (const char *arg_cstr, char quote_char)
491{
492 return InsertArgumentAtIndex (GetArgumentCount(), arg_cstr, quote_char);
493}
494
495const char *
496Args::InsertArgumentAtIndex (size_t idx, const char *arg_cstr, char quote_char)
497{
498 // Since we are using a std::list to hold onto the copied C string and
499 // we don't have direct access to the elements, we have to iterate to
500 // find the value.
501 arg_sstr_collection::iterator pos, end = m_args.end();
502 size_t i = idx;
503 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
504 --i;
505
506 pos = m_args.insert(pos, arg_cstr);
507
Greg Clayton928d1302010-12-19 03:41:24 +0000508 if (idx >= m_args_quote_char.size())
509 {
510 m_args_quote_char.resize(idx + 1);
511 m_args_quote_char[idx] = quote_char;
512 }
513 else
514 m_args_quote_char.insert(m_args_quote_char.begin() + idx, quote_char);
Chris Lattner24943d22010-06-08 16:52:24 +0000515
516 UpdateArgvFromArgs();
517 return GetArgumentAtIndex(idx);
518}
519
520const char *
521Args::ReplaceArgumentAtIndex (size_t idx, const char *arg_cstr, char quote_char)
522{
523 // Since we are using a std::list to hold onto the copied C string and
524 // we don't have direct access to the elements, we have to iterate to
525 // find the value.
526 arg_sstr_collection::iterator pos, end = m_args.end();
527 size_t i = idx;
528 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
529 --i;
530
531 if (pos != end)
532 {
533 pos->assign(arg_cstr);
534 assert(idx < m_argv.size() - 1);
535 m_argv[idx] = pos->c_str();
Greg Clayton928d1302010-12-19 03:41:24 +0000536 if (idx >= m_args_quote_char.size())
537 m_args_quote_char.resize(idx + 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000538 m_args_quote_char[idx] = quote_char;
539 return GetArgumentAtIndex(idx);
540 }
541 return NULL;
542}
543
544void
545Args::DeleteArgumentAtIndex (size_t idx)
546{
547 // Since we are using a std::list to hold onto the copied C string and
548 // we don't have direct access to the elements, we have to iterate to
549 // find the value.
550 arg_sstr_collection::iterator pos, end = m_args.end();
551 size_t i = idx;
552 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
553 --i;
554
555 if (pos != end)
556 {
557 m_args.erase (pos);
558 assert(idx < m_argv.size() - 1);
559 m_argv.erase(m_argv.begin() + idx);
Greg Clayton928d1302010-12-19 03:41:24 +0000560 if (idx < m_args_quote_char.size())
561 m_args_quote_char.erase(m_args_quote_char.begin() + idx);
Chris Lattner24943d22010-06-08 16:52:24 +0000562 }
563}
564
565void
566Args::SetArguments (int argc, const char **argv)
567{
568 // m_argv will be rebuilt in UpdateArgvFromArgs() below, so there is
569 // no need to clear it here.
570 m_args.clear();
571 m_args_quote_char.clear();
572
Chris Lattner24943d22010-06-08 16:52:24 +0000573 // First copy each string
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000574 for (size_t i=0; i<argc; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +0000575 {
576 m_args.push_back (argv[i]);
Greg Clayton928d1302010-12-19 03:41:24 +0000577 if ((argv[i][0] == '\'') || (argv[i][0] == '"') || (argv[i][0] == '`'))
Chris Lattner24943d22010-06-08 16:52:24 +0000578 m_args_quote_char.push_back (argv[i][0]);
579 else
580 m_args_quote_char.push_back ('\0');
581 }
582
583 UpdateArgvFromArgs();
584}
585
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000586void
587Args::SetArguments (const char **argv)
588{
589 // m_argv will be rebuilt in UpdateArgvFromArgs() below, so there is
590 // no need to clear it here.
591 m_args.clear();
592 m_args_quote_char.clear();
593
594 if (argv)
595 {
596 // First copy each string
597 for (size_t i=0; argv[i]; ++i)
598 {
599 m_args.push_back (argv[i]);
600 if ((argv[i][0] == '\'') || (argv[i][0] == '"') || (argv[i][0] == '`'))
601 m_args_quote_char.push_back (argv[i][0]);
602 else
603 m_args_quote_char.push_back ('\0');
604 }
605 }
606
607 UpdateArgvFromArgs();
608}
609
Chris Lattner24943d22010-06-08 16:52:24 +0000610
611Error
612Args::ParseOptions (Options &options)
613{
614 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +0000615 Error error;
616 struct option *long_options = options.GetLongOptions();
617 if (long_options == NULL)
618 {
Greg Clayton9c236732011-10-26 00:56:27 +0000619 error.SetErrorStringWithFormat("invalid long options");
Chris Lattner24943d22010-06-08 16:52:24 +0000620 return error;
621 }
622
Greg Claytonbef15832010-07-14 00:18:15 +0000623 for (int i=0; long_options[i].name != NULL; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +0000624 {
625 if (long_options[i].flag == NULL)
626 {
627 sstr << (char)long_options[i].val;
628 switch (long_options[i].has_arg)
629 {
630 default:
631 case no_argument: break;
632 case required_argument: sstr << ':'; break;
633 case optional_argument: sstr << "::"; break;
634 }
635 }
636 }
Eli Friedmanef2bc872010-06-13 19:18:49 +0000637#ifdef __GLIBC__
638 optind = 0;
639#else
Chris Lattner24943d22010-06-08 16:52:24 +0000640 optreset = 1;
641 optind = 1;
Eli Friedmanef2bc872010-06-13 19:18:49 +0000642#endif
Chris Lattner24943d22010-06-08 16:52:24 +0000643 int val;
644 while (1)
645 {
646 int long_options_index = -1;
647 val = ::getopt_long(GetArgumentCount(), GetArgumentVector(), sstr.GetData(), long_options,
648 &long_options_index);
649 if (val == -1)
650 break;
651
652 // Did we get an error?
653 if (val == '?')
654 {
Greg Clayton9c236732011-10-26 00:56:27 +0000655 error.SetErrorStringWithFormat("unknown or ambiguous option");
Chris Lattner24943d22010-06-08 16:52:24 +0000656 break;
657 }
658 // The option auto-set itself
659 if (val == 0)
660 continue;
661
662 ((Options *) &options)->OptionSeen (val);
663
664 // Lookup the long option index
665 if (long_options_index == -1)
666 {
667 for (int i=0;
668 long_options[i].name || long_options[i].has_arg || long_options[i].flag || long_options[i].val;
669 ++i)
670 {
671 if (long_options[i].val == val)
672 {
673 long_options_index = i;
674 break;
675 }
676 }
677 }
678 // Call the callback with the option
679 if (long_options_index >= 0)
680 {
681 error = options.SetOptionValue(long_options_index,
682 long_options[long_options_index].has_arg == no_argument ? NULL : optarg);
683 }
684 else
685 {
Greg Clayton9c236732011-10-26 00:56:27 +0000686 error.SetErrorStringWithFormat("invalid option with value '%i'", val);
Chris Lattner24943d22010-06-08 16:52:24 +0000687 }
688 if (error.Fail())
689 break;
690 }
691
692 // Update our ARGV now that get options has consumed all the options
693 m_argv.erase(m_argv.begin(), m_argv.begin() + optind);
694 UpdateArgsAfterOptionParsing ();
695 return error;
696}
697
698void
699Args::Clear ()
700{
701 m_args.clear ();
702 m_argv.clear ();
703 m_args_quote_char.clear();
704}
705
706int32_t
707Args::StringToSInt32 (const char *s, int32_t fail_value, int base, bool *success_ptr)
708{
709 if (s && s[0])
710 {
711 char *end = NULL;
712 int32_t uval = ::strtol (s, &end, base);
713 if (*end == '\0')
714 {
715 if (success_ptr) *success_ptr = true;
716 return uval; // All characters were used, return the result
717 }
718 }
719 if (success_ptr) *success_ptr = false;
720 return fail_value;
721}
722
723uint32_t
724Args::StringToUInt32 (const char *s, uint32_t fail_value, int base, bool *success_ptr)
725{
726 if (s && s[0])
727 {
728 char *end = NULL;
729 uint32_t uval = ::strtoul (s, &end, base);
730 if (*end == '\0')
731 {
732 if (success_ptr) *success_ptr = true;
733 return uval; // All characters were used, return the result
734 }
735 }
736 if (success_ptr) *success_ptr = false;
737 return fail_value;
738}
739
740
741int64_t
742Args::StringToSInt64 (const char *s, int64_t fail_value, int base, bool *success_ptr)
743{
744 if (s && s[0])
745 {
746 char *end = NULL;
747 int64_t uval = ::strtoll (s, &end, base);
748 if (*end == '\0')
749 {
750 if (success_ptr) *success_ptr = true;
751 return uval; // All characters were used, return the result
752 }
753 }
754 if (success_ptr) *success_ptr = false;
755 return fail_value;
756}
757
758uint64_t
759Args::StringToUInt64 (const char *s, uint64_t fail_value, int base, bool *success_ptr)
760{
761 if (s && s[0])
762 {
763 char *end = NULL;
764 uint64_t uval = ::strtoull (s, &end, base);
765 if (*end == '\0')
766 {
767 if (success_ptr) *success_ptr = true;
768 return uval; // All characters were used, return the result
769 }
770 }
771 if (success_ptr) *success_ptr = false;
772 return fail_value;
773}
774
775lldb::addr_t
776Args::StringToAddress (const char *s, lldb::addr_t fail_value, bool *success_ptr)
777{
778 if (s && s[0])
779 {
780 char *end = NULL;
781 lldb::addr_t addr = ::strtoull (s, &end, 0);
782 if (*end == '\0')
783 {
784 if (success_ptr) *success_ptr = true;
785 return addr; // All characters were used, return the result
786 }
787 // Try base 16 with no prefix...
788 addr = ::strtoull (s, &end, 16);
789 if (*end == '\0')
790 {
791 if (success_ptr) *success_ptr = true;
792 return addr; // All characters were used, return the result
793 }
794 }
795 if (success_ptr) *success_ptr = false;
796 return fail_value;
797}
798
799bool
800Args::StringToBoolean (const char *s, bool fail_value, bool *success_ptr)
801{
802 if (s && s[0])
803 {
804 if (::strcasecmp (s, "false") == 0 ||
805 ::strcasecmp (s, "off") == 0 ||
806 ::strcasecmp (s, "no") == 0 ||
807 ::strcmp (s, "0") == 0)
808 {
809 if (success_ptr)
810 *success_ptr = true;
811 return false;
812 }
813 else
814 if (::strcasecmp (s, "true") == 0 ||
815 ::strcasecmp (s, "on") == 0 ||
816 ::strcasecmp (s, "yes") == 0 ||
817 ::strcmp (s, "1") == 0)
818 {
819 if (success_ptr) *success_ptr = true;
820 return true;
821 }
822 }
823 if (success_ptr) *success_ptr = false;
824 return fail_value;
825}
826
Greg Claytonb1888f22011-03-19 01:12:21 +0000827const char *
828Args::StringToVersion (const char *s, uint32_t &major, uint32_t &minor, uint32_t &update)
829{
830 major = UINT32_MAX;
831 minor = UINT32_MAX;
832 update = UINT32_MAX;
833
834 if (s && s[0])
835 {
836 char *pos = NULL;
837 uint32_t uval32;
838 uval32 = ::strtoul (s, &pos, 0);
839 if (pos == s)
840 return s;
841 major = uval32;
842 if (*pos == '\0')
843 {
844 return pos; // Decoded major and got end of string
845 }
846 else if (*pos == '.')
847 {
848 const char *minor_cstr = pos + 1;
849 uval32 = ::strtoul (minor_cstr, &pos, 0);
850 if (pos == minor_cstr)
851 return pos; // Didn't get any digits for the minor version...
852 minor = uval32;
853 if (*pos == '.')
854 {
855 const char *update_cstr = pos + 1;
856 uval32 = ::strtoul (update_cstr, &pos, 0);
857 if (pos == update_cstr)
858 return pos;
859 update = uval32;
860 }
861 return pos;
862 }
863 }
864 return 0;
865}
866
Greg Clayton527154d2011-11-15 03:53:30 +0000867const char *
868Args::GetShellSafeArgument (const char *unsafe_arg, std::string &safe_arg)
869{
870 safe_arg.assign (unsafe_arg);
871 size_t prev_pos = 0;
872 while (prev_pos < safe_arg.size())
873 {
874 // Escape spaces and quotes
875 size_t pos = safe_arg.find_first_of(" '\"", prev_pos);
876 if (pos != std::string::npos)
877 {
878 safe_arg.insert (pos, 1, '\\');
879 prev_pos = pos + 2;
880 }
881 else
882 break;
883 }
884 return safe_arg.c_str();
885}
886
Greg Claytonb1888f22011-03-19 01:12:21 +0000887
Chris Lattner24943d22010-06-08 16:52:24 +0000888int32_t
Greg Clayton61aca5d2011-10-07 18:58:12 +0000889Args::StringToOptionEnum (const char *s, OptionEnumValueElement *enum_values, int32_t fail_value, Error &error)
Chris Lattner24943d22010-06-08 16:52:24 +0000890{
Greg Clayton61aca5d2011-10-07 18:58:12 +0000891 if (enum_values)
Chris Lattner24943d22010-06-08 16:52:24 +0000892 {
Greg Clayton61aca5d2011-10-07 18:58:12 +0000893 if (s && s[0])
Chris Lattner24943d22010-06-08 16:52:24 +0000894 {
Greg Clayton61aca5d2011-10-07 18:58:12 +0000895 for (int i = 0; enum_values[i].string_value != NULL ; i++)
Chris Lattner24943d22010-06-08 16:52:24 +0000896 {
Greg Clayton61aca5d2011-10-07 18:58:12 +0000897 if (strstr(enum_values[i].string_value, s) == enum_values[i].string_value)
898 {
899 error.Clear();
900 return enum_values[i].value;
901 }
Chris Lattner24943d22010-06-08 16:52:24 +0000902 }
903 }
Greg Clayton61aca5d2011-10-07 18:58:12 +0000904
905 StreamString strm;
906 strm.PutCString ("invalid enumeration value, valid values are: ");
907 for (int i = 0; enum_values[i].string_value != NULL; i++)
908 {
909 strm.Printf ("%s\"%s\"",
910 i > 0 ? ", " : "",
911 enum_values[i].string_value);
912 }
913 error.SetErrorString(strm.GetData());
Chris Lattner24943d22010-06-08 16:52:24 +0000914 }
Greg Clayton61aca5d2011-10-07 18:58:12 +0000915 else
916 {
917 error.SetErrorString ("invalid enumeration argument");
918 }
Chris Lattner24943d22010-06-08 16:52:24 +0000919 return fail_value;
920}
921
922ScriptLanguage
923Args::StringToScriptLanguage (const char *s, ScriptLanguage fail_value, bool *success_ptr)
924{
925 if (s && s[0])
926 {
927 if ((::strcasecmp (s, "python") == 0) ||
928 (::strcasecmp (s, "default") == 0 && eScriptLanguagePython == eScriptLanguageDefault))
929 {
930 if (success_ptr) *success_ptr = true;
931 return eScriptLanguagePython;
932 }
933 if (::strcasecmp (s, "none"))
934 {
935 if (success_ptr) *success_ptr = true;
936 return eScriptLanguageNone;
937 }
938 }
939 if (success_ptr) *success_ptr = false;
940 return fail_value;
941}
942
943Error
944Args::StringToFormat
945(
946 const char *s,
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000947 lldb::Format &format,
948 uint32_t *byte_size_ptr
Chris Lattner24943d22010-06-08 16:52:24 +0000949)
950{
951 format = eFormatInvalid;
952 Error error;
953
954 if (s && s[0])
955 {
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000956 if (byte_size_ptr)
Chris Lattner24943d22010-06-08 16:52:24 +0000957 {
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000958 if (isdigit (s[0]))
959 {
960 char *format_char = NULL;
961 unsigned long byte_size = ::strtoul (s, &format_char, 0);
962 if (byte_size != ULONG_MAX)
963 *byte_size_ptr = byte_size;
964 s = format_char;
965 }
966 else
967 *byte_size_ptr = 0;
968 }
969
Greg Clayton3182eff2011-06-23 21:22:24 +0000970 const bool partial_match_ok = true;
971 if (!FormatManager::GetFormatFromCString (s, partial_match_ok, format))
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000972 {
Greg Clayton3182eff2011-06-23 21:22:24 +0000973 StreamString error_strm;
974 error_strm.Printf ("Invalid format character or name '%s'. Valid values are:\n", s);
Peter Collingbournef4d4fcc2011-06-24 01:12:22 +0000975 for (Format f = eFormatDefault; f < kNumFormats; f = Format(f+1))
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000976 {
Greg Clayton3182eff2011-06-23 21:22:24 +0000977 char format_char = FormatManager::GetFormatAsFormatChar(f);
978 if (format_char)
979 error_strm.Printf ("'%c' or ", format_char);
980
981 error_strm.Printf ("\"%s\"", FormatManager::GetFormatAsCString(f));
982 error_strm.EOL();
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000983 }
Greg Clayton3182eff2011-06-23 21:22:24 +0000984
985 if (byte_size_ptr)
986 error_strm.PutCString ("An optional byte size can precede the format character.\n");
987 error.SetErrorString(error_strm.GetString().c_str());
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000988 }
Chris Lattner24943d22010-06-08 16:52:24 +0000989
990 if (error.Fail())
991 return error;
992 }
993 else
994 {
Greg Clayton9c236732011-10-26 00:56:27 +0000995 error.SetErrorStringWithFormat("%s option string", s ? "empty" : "invalid");
Chris Lattner24943d22010-06-08 16:52:24 +0000996 }
997 return error;
998}
999
1000void
1001Args::LongestCommonPrefix (std::string &common_prefix)
1002{
1003 arg_sstr_collection::iterator pos, end = m_args.end();
1004 pos = m_args.begin();
1005 if (pos == end)
1006 common_prefix.clear();
1007 else
1008 common_prefix = (*pos);
1009
1010 for (++pos; pos != end; ++pos)
1011 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00001012 size_t new_size = (*pos).size();
Chris Lattner24943d22010-06-08 16:52:24 +00001013
1014 // First trim common_prefix if it is longer than the current element:
1015 if (common_prefix.size() > new_size)
1016 common_prefix.erase (new_size);
1017
1018 // Then trim it at the first disparity:
1019
Greg Clayton54e7afa2010-07-09 20:39:50 +00001020 for (size_t i = 0; i < common_prefix.size(); i++)
Chris Lattner24943d22010-06-08 16:52:24 +00001021 {
1022 if ((*pos)[i] != common_prefix[i])
1023 {
1024 common_prefix.erase(i);
1025 break;
1026 }
1027 }
1028
1029 // If we've emptied the common prefix, we're done.
1030 if (common_prefix.empty())
1031 break;
1032 }
1033}
1034
Caroline Tice44c841d2010-12-07 19:58:26 +00001035size_t
1036Args::FindArgumentIndexForOption (struct option *long_options, int long_options_index)
1037{
1038 char short_buffer[3];
1039 char long_buffer[255];
1040 ::snprintf (short_buffer, sizeof (short_buffer), "-%c", (char) long_options[long_options_index].val);
1041 ::snprintf (long_buffer, sizeof (long_buffer), "--%s", long_options[long_options_index].name);
1042 size_t end = GetArgumentCount ();
1043 size_t idx = 0;
1044 while (idx < end)
1045 {
1046 if ((::strncmp (GetArgumentAtIndex (idx), short_buffer, strlen (short_buffer)) == 0)
1047 || (::strncmp (GetArgumentAtIndex (idx), long_buffer, strlen (long_buffer)) == 0))
1048 {
1049 return idx;
1050 }
1051 ++idx;
1052 }
1053
1054 return end;
1055}
1056
1057bool
1058Args::IsPositionalArgument (const char *arg)
1059{
1060 if (arg == NULL)
1061 return false;
1062
1063 bool is_positional = true;
1064 char *cptr = (char *) arg;
1065
1066 if (cptr[0] == '%')
1067 {
1068 ++cptr;
1069 while (isdigit (cptr[0]))
1070 ++cptr;
1071 if (cptr[0] != '\0')
1072 is_positional = false;
1073 }
1074 else
1075 is_positional = false;
1076
1077 return is_positional;
1078}
1079
Chris Lattner24943d22010-06-08 16:52:24 +00001080void
Caroline Tice5e0894e2010-10-12 17:45:19 +00001081Args::ParseAliasOptions (Options &options,
1082 CommandReturnObject &result,
Caroline Ticee0da7a52010-12-09 22:52:49 +00001083 OptionArgVector *option_arg_vector,
1084 std::string &raw_input_string)
Chris Lattner24943d22010-06-08 16:52:24 +00001085{
1086 StreamString sstr;
1087 int i;
1088 struct option *long_options = options.GetLongOptions();
1089
1090 if (long_options == NULL)
1091 {
1092 result.AppendError ("invalid long options");
1093 result.SetStatus (eReturnStatusFailed);
1094 return;
1095 }
1096
1097 for (i = 0; long_options[i].name != NULL; ++i)
1098 {
1099 if (long_options[i].flag == NULL)
1100 {
1101 sstr << (char) long_options[i].val;
1102 switch (long_options[i].has_arg)
1103 {
1104 default:
1105 case no_argument:
1106 break;
1107 case required_argument:
1108 sstr << ":";
1109 break;
1110 case optional_argument:
1111 sstr << "::";
1112 break;
1113 }
1114 }
1115 }
1116
Eli Friedmanef2bc872010-06-13 19:18:49 +00001117#ifdef __GLIBC__
1118 optind = 0;
1119#else
Chris Lattner24943d22010-06-08 16:52:24 +00001120 optreset = 1;
1121 optind = 1;
Eli Friedmanef2bc872010-06-13 19:18:49 +00001122#endif
Chris Lattner24943d22010-06-08 16:52:24 +00001123 int val;
1124 while (1)
1125 {
1126 int long_options_index = -1;
1127 val = ::getopt_long (GetArgumentCount(), GetArgumentVector(), sstr.GetData(), long_options,
1128 &long_options_index);
1129
1130 if (val == -1)
1131 break;
1132
1133 if (val == '?')
1134 {
1135 result.AppendError ("unknown or ambiguous option");
1136 result.SetStatus (eReturnStatusFailed);
1137 break;
1138 }
1139
1140 if (val == 0)
1141 continue;
1142
1143 ((Options *) &options)->OptionSeen (val);
1144
1145 // Look up the long option index
1146 if (long_options_index == -1)
1147 {
1148 for (int j = 0;
1149 long_options[j].name || long_options[j].has_arg || long_options[j].flag || long_options[j].val;
1150 ++j)
1151 {
1152 if (long_options[j].val == val)
1153 {
1154 long_options_index = j;
1155 break;
1156 }
1157 }
1158 }
1159
1160 // See if the option takes an argument, and see if one was supplied.
1161 if (long_options_index >= 0)
1162 {
1163 StreamString option_str;
1164 option_str.Printf ("-%c", (char) val);
1165
1166 switch (long_options[long_options_index].has_arg)
1167 {
1168 case no_argument:
Caroline Tice44c841d2010-12-07 19:58:26 +00001169 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
1170 OptionArgValue (no_argument, "<no-argument>")));
Caroline Tice2160c3f2010-09-12 04:48:45 +00001171 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Chris Lattner24943d22010-06-08 16:52:24 +00001172 break;
1173 case required_argument:
1174 if (optarg != NULL)
1175 {
1176 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
Caroline Tice44c841d2010-12-07 19:58:26 +00001177 OptionArgValue (required_argument,
1178 std::string (optarg))));
Chris Lattner24943d22010-06-08 16:52:24 +00001179 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1180 }
1181 else
1182 {
1183 result.AppendErrorWithFormat ("Option '%s' is missing argument specifier.\n",
1184 option_str.GetData());
1185 result.SetStatus (eReturnStatusFailed);
1186 }
1187 break;
1188 case optional_argument:
1189 if (optarg != NULL)
1190 {
1191 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
Caroline Tice44c841d2010-12-07 19:58:26 +00001192 OptionArgValue (optional_argument,
1193 std::string (optarg))));
Chris Lattner24943d22010-06-08 16:52:24 +00001194 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1195 }
1196 else
1197 {
1198 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
Caroline Tice44c841d2010-12-07 19:58:26 +00001199 OptionArgValue (optional_argument, "<no-argument>")));
Chris Lattner24943d22010-06-08 16:52:24 +00001200 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1201 }
1202 break;
1203 default:
1204 result.AppendErrorWithFormat
1205 ("error with options table; invalid value in has_arg field for option '%c'.\n",
1206 (char) val);
1207 result.SetStatus (eReturnStatusFailed);
1208 break;
1209 }
1210 }
1211 else
1212 {
1213 result.AppendErrorWithFormat ("Invalid option with value '%c'.\n", (char) val);
1214 result.SetStatus (eReturnStatusFailed);
1215 }
Caroline Tice5e0894e2010-10-12 17:45:19 +00001216
1217 if (long_options_index >= 0)
1218 {
1219 // Find option in the argument list; also see if it was supposed to take an argument and if one was
Caroline Ticee0da7a52010-12-09 22:52:49 +00001220 // supplied. Remove option (and argument, if given) from the argument list. Also remove them from
1221 // the raw_input_string, if one was passed in.
Caroline Tice44c841d2010-12-07 19:58:26 +00001222 size_t idx = FindArgumentIndexForOption (long_options, long_options_index);
1223 if (idx < GetArgumentCount())
1224 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001225 if (raw_input_string.size() > 0)
1226 {
1227 const char *tmp_arg = GetArgumentAtIndex (idx);
1228 size_t pos = raw_input_string.find (tmp_arg);
1229 if (pos != std::string::npos)
1230 raw_input_string.erase (pos, strlen (tmp_arg));
1231 }
Caroline Tice44c841d2010-12-07 19:58:26 +00001232 ReplaceArgumentAtIndex (idx, "");
1233 if ((long_options[long_options_index].has_arg != no_argument)
1234 && (optarg != NULL)
1235 && (idx+1 < GetArgumentCount())
1236 && (strcmp (optarg, GetArgumentAtIndex(idx+1)) == 0))
Caroline Ticee0da7a52010-12-09 22:52:49 +00001237 {
1238 if (raw_input_string.size() > 0)
1239 {
1240 const char *tmp_arg = GetArgumentAtIndex (idx+1);
1241 size_t pos = raw_input_string.find (tmp_arg);
1242 if (pos != std::string::npos)
1243 raw_input_string.erase (pos, strlen (tmp_arg));
1244 }
Caroline Tice44c841d2010-12-07 19:58:26 +00001245 ReplaceArgumentAtIndex (idx+1, "");
Caroline Ticee0da7a52010-12-09 22:52:49 +00001246 }
Caroline Tice44c841d2010-12-07 19:58:26 +00001247 }
Caroline Tice5e0894e2010-10-12 17:45:19 +00001248 }
1249
Chris Lattner24943d22010-06-08 16:52:24 +00001250 if (!result.Succeeded())
1251 break;
1252 }
1253}
1254
1255void
1256Args::ParseArgsForCompletion
1257(
1258 Options &options,
Jim Inghamadb84292010-06-24 20:31:04 +00001259 OptionElementVector &option_element_vector,
1260 uint32_t cursor_index
Chris Lattner24943d22010-06-08 16:52:24 +00001261)
1262{
1263 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001264 struct option *long_options = options.GetLongOptions();
1265 option_element_vector.clear();
1266
1267 if (long_options == NULL)
1268 {
1269 return;
1270 }
1271
1272 // Leading : tells getopt to return a : for a missing option argument AND
1273 // to suppress error messages.
1274
1275 sstr << ":";
Greg Claytonbef15832010-07-14 00:18:15 +00001276 for (int i = 0; long_options[i].name != NULL; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001277 {
1278 if (long_options[i].flag == NULL)
1279 {
1280 sstr << (char) long_options[i].val;
1281 switch (long_options[i].has_arg)
1282 {
1283 default:
1284 case no_argument:
1285 break;
1286 case required_argument:
1287 sstr << ":";
1288 break;
1289 case optional_argument:
1290 sstr << "::";
1291 break;
1292 }
1293 }
1294 }
1295
Eli Friedmanef2bc872010-06-13 19:18:49 +00001296#ifdef __GLIBC__
1297 optind = 0;
1298#else
Chris Lattner24943d22010-06-08 16:52:24 +00001299 optreset = 1;
1300 optind = 1;
Eli Friedmanef2bc872010-06-13 19:18:49 +00001301#endif
Chris Lattner24943d22010-06-08 16:52:24 +00001302 opterr = 0;
1303
1304 int val;
1305 const OptionDefinition *opt_defs = options.GetDefinitions();
1306
Jim Inghamadb84292010-06-24 20:31:04 +00001307 // Fooey... getopt_long permutes the GetArgumentVector to move the options to the front.
Chris Lattner24943d22010-06-08 16:52:24 +00001308 // So we have to build another Arg and pass that to getopt_long so it doesn't
Jim Inghamadb84292010-06-24 20:31:04 +00001309 // change the one we have.
Chris Lattner24943d22010-06-08 16:52:24 +00001310
Greg Clayton54e7afa2010-07-09 20:39:50 +00001311 std::vector<const char *> dummy_vec (GetArgumentVector(), GetArgumentVector() + GetArgumentCount() + 1);
Chris Lattner24943d22010-06-08 16:52:24 +00001312
Jim Inghamadb84292010-06-24 20:31:04 +00001313 bool failed_once = false;
1314 uint32_t dash_dash_pos = -1;
1315
Chris Lattner24943d22010-06-08 16:52:24 +00001316 while (1)
1317 {
1318 bool missing_argument = false;
1319 int parse_start = optind;
1320 int long_options_index = -1;
Jim Inghamadb84292010-06-24 20:31:04 +00001321
Greg Clayton54e7afa2010-07-09 20:39:50 +00001322 val = ::getopt_long (dummy_vec.size() - 1,
Greg Clayton53d68e72010-07-20 22:52:08 +00001323 (char *const *) &dummy_vec.front(),
Greg Clayton54e7afa2010-07-09 20:39:50 +00001324 sstr.GetData(),
1325 long_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001326 &long_options_index);
1327
1328 if (val == -1)
Jim Inghamadb84292010-06-24 20:31:04 +00001329 {
1330 // When we're completing a "--" which is the last option on line,
1331 if (failed_once)
1332 break;
1333
1334 failed_once = true;
1335
1336 // If this is a bare "--" we mark it as such so we can complete it successfully later.
1337 // Handling the "--" is a little tricky, since that may mean end of options or arguments, or the
1338 // user might want to complete options by long name. I make this work by checking whether the
1339 // cursor is in the "--" argument, and if so I assume we're completing the long option, otherwise
1340 // I let it pass to getopt_long which will terminate the option parsing.
1341 // Note, in either case we continue parsing the line so we can figure out what other options
1342 // were passed. This will be useful when we come to restricting completions based on what other
1343 // options we've seen on the line.
Chris Lattner24943d22010-06-08 16:52:24 +00001344
Jim Inghamadb84292010-06-24 20:31:04 +00001345 if (optind < dummy_vec.size() - 1
1346 && (strcmp (dummy_vec[optind-1], "--") == 0))
1347 {
1348 dash_dash_pos = optind - 1;
1349 if (optind - 1 == cursor_index)
1350 {
1351 option_element_vector.push_back (OptionArgElement (OptionArgElement::eBareDoubleDash, optind - 1,
1352 OptionArgElement::eBareDoubleDash));
1353 continue;
1354 }
1355 else
1356 break;
1357 }
1358 else
1359 break;
1360 }
Chris Lattner24943d22010-06-08 16:52:24 +00001361 else if (val == '?')
1362 {
Jim Inghamadb84292010-06-24 20:31:04 +00001363 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1364 OptionArgElement::eUnrecognizedArg));
Chris Lattner24943d22010-06-08 16:52:24 +00001365 continue;
1366 }
1367 else if (val == 0)
1368 {
1369 continue;
1370 }
1371 else if (val == ':')
1372 {
1373 // This is a missing argument.
1374 val = optopt;
1375 missing_argument = true;
1376 }
1377
1378 ((Options *) &options)->OptionSeen (val);
1379
1380 // Look up the long option index
1381 if (long_options_index == -1)
1382 {
1383 for (int j = 0;
1384 long_options[j].name || long_options[j].has_arg || long_options[j].flag || long_options[j].val;
1385 ++j)
1386 {
1387 if (long_options[j].val == val)
1388 {
1389 long_options_index = j;
1390 break;
1391 }
1392 }
1393 }
1394
1395 // See if the option takes an argument, and see if one was supplied.
1396 if (long_options_index >= 0)
1397 {
1398 int opt_defs_index = -1;
1399 for (int i = 0; ; i++)
1400 {
1401 if (opt_defs[i].short_option == 0)
1402 break;
1403 else if (opt_defs[i].short_option == val)
1404 {
1405 opt_defs_index = i;
1406 break;
1407 }
1408 }
1409
1410 switch (long_options[long_options_index].has_arg)
1411 {
1412 case no_argument:
1413 option_element_vector.push_back (OptionArgElement (opt_defs_index, parse_start, 0));
1414 break;
1415 case required_argument:
1416 if (optarg != NULL)
1417 {
1418 int arg_index;
1419 if (missing_argument)
1420 arg_index = -1;
1421 else
Jim Inghamadb84292010-06-24 20:31:04 +00001422 arg_index = optind - 1;
Chris Lattner24943d22010-06-08 16:52:24 +00001423
Jim Inghamadb84292010-06-24 20:31:04 +00001424 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, arg_index));
Chris Lattner24943d22010-06-08 16:52:24 +00001425 }
1426 else
1427 {
Jim Inghamadb84292010-06-24 20:31:04 +00001428 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 1, -1));
Chris Lattner24943d22010-06-08 16:52:24 +00001429 }
1430 break;
1431 case optional_argument:
1432 if (optarg != NULL)
1433 {
Jim Inghamadb84292010-06-24 20:31:04 +00001434 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, optind - 1));
Chris Lattner24943d22010-06-08 16:52:24 +00001435 }
1436 else
1437 {
Jim Inghamadb84292010-06-24 20:31:04 +00001438 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, optind - 1));
Chris Lattner24943d22010-06-08 16:52:24 +00001439 }
1440 break;
1441 default:
1442 // The options table is messed up. Here we'll just continue
Jim Inghamadb84292010-06-24 20:31:04 +00001443 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1444 OptionArgElement::eUnrecognizedArg));
Chris Lattner24943d22010-06-08 16:52:24 +00001445 break;
1446 }
1447 }
1448 else
1449 {
Jim Inghamadb84292010-06-24 20:31:04 +00001450 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1451 OptionArgElement::eUnrecognizedArg));
Chris Lattner24943d22010-06-08 16:52:24 +00001452 }
1453 }
Jim Inghamadb84292010-06-24 20:31:04 +00001454
1455 // Finally we have to handle the case where the cursor index points at a single "-". We want to mark that in
1456 // the option_element_vector, but only if it is not after the "--". But it turns out that getopt_long just ignores
1457 // an isolated "-". So we have to look it up by hand here. We only care if it is AT the cursor position.
1458
1459 if ((dash_dash_pos == -1 || cursor_index < dash_dash_pos)
1460 && strcmp (GetArgumentAtIndex(cursor_index), "-") == 0)
1461 {
1462 option_element_vector.push_back (OptionArgElement (OptionArgElement::eBareDash, cursor_index,
1463 OptionArgElement::eBareDash));
1464
1465 }
Chris Lattner24943d22010-06-08 16:52:24 +00001466}