blob: 63bcb8785b35ab86c9e2723dc224feab530b60d9 [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
Greg Clayton431d26d2012-04-25 22:30:32 +0000117Args::GetCommandString (std::string &command) const
Chris Lattner24943d22010-06-08 16:52:24 +0000118{
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
Greg Clayton431d26d2012-04-25 22:30:32 +0000131Args::GetQuotedCommandString (std::string &command) const
Caroline Ticed9105c22010-12-10 00:26:54 +0000132{
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";
Johnny Chena1b0ce12012-01-19 19:22:41 +0000171 static const char *k_space_separators_with_slash_and_quotes = " \t \\'\"";
Greg Clayton928d1302010-12-19 03:41:24 +0000172 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);
Greg Clayton03e498e2012-03-15 17:10:48 +0000228 ++arg_end;
Greg Clayton928d1302010-12-19 03:41:24 +0000229 arg_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000230 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000231
Greg Clayton928d1302010-12-19 03:41:24 +0000232 default:
Jim Ingham4078a302012-07-21 00:12:58 +0000233 if (quote_char == '\0')
234 {
235 arg.append (arg_piece_start, arg_end - arg_piece_start);
236 if (arg_end + 1 != '\0')
237 {
238 arg.append (arg_end + 1, 1);
239 arg_pos = arg_end + 2;
240 arg_piece_start = arg_pos;
241 }
242 }
243 else
244 arg_pos = arg_end + 2;
Greg Clayton928d1302010-12-19 03:41:24 +0000245 break;
246 }
247 break;
248
249 case '"':
250 case '\'':
251 case '`':
252 // Quote characters
253 if (quote_char)
254 {
255 // We found a quote character while inside a quoted
256 // character argument. If it matches our current quote
257 // character, this ends the effect of the quotes. If it
258 // doesn't we ignore it.
259 if (quote_char == arg_end[0])
Chris Lattner24943d22010-06-08 16:52:24 +0000260 {
Greg Clayton928d1302010-12-19 03:41:24 +0000261 arg.append (arg_piece_start, arg_end - arg_piece_start);
262 // Clear the quote character and let parsing
263 // continue (we need to watch for things like:
264 // "Hello ""World"
265 // "Hello "World
266 // "Hello "'World'
267 // All of which will result in a single argument "Hello World"
268 quote_char = '\0'; // Note that we are no longer inside quotes
269 arg_pos = arg_end + 1; // Skip the quote character
270 arg_piece_start = arg_pos; // Note we are starting from later in the string
271 }
272 else
273 {
274 // different quote, skip it and keep going
275 arg_pos = arg_end + 1;
276 }
277 }
278 else
279 {
280 // We found the start of a quote scope.
Greg Clayton5d187e52011-01-08 20:28:42 +0000281 // Make sure there isn't a string that precedes
Greg Clayton928d1302010-12-19 03:41:24 +0000282 // the start of a quote scope like:
283 // Hello" World"
284 // If so, then add the "Hello" to the arg
285 if (arg_end > arg_piece_start)
286 arg.append (arg_piece_start, arg_end - arg_piece_start);
287
288 // Enter into a quote scope
289 quote_char = arg_end[0];
290
291 if (first_quote_char == '\0')
292 first_quote_char = quote_char;
293
294 arg_pos = arg_end;
Johnny Chena1b0ce12012-01-19 19:22:41 +0000295 ++arg_pos; // Skip the quote character
Greg Clayton928d1302010-12-19 03:41:24 +0000296 arg_piece_start = arg_pos; // Note we are starting from later in the string
297
298 // Skip till the next quote character
299 const char *end_quote = ::strchr (arg_piece_start, quote_char);
300 while (end_quote && end_quote[-1] == '\\')
301 {
302 // Don't skip the quote character if it is
303 // preceded by a '\' character
304 end_quote = ::strchr (end_quote + 1, quote_char);
305 }
306
307 if (end_quote)
308 {
309 if (end_quote > arg_piece_start)
Johnny Chena1b0ce12012-01-19 19:22:41 +0000310 arg.append (arg_piece_start, end_quote - arg_piece_start);
Greg Clayton928d1302010-12-19 03:41:24 +0000311
312 // If the next character is a space or the end of
313 // string, this argument is complete...
314 if (end_quote[1] == ' ' || end_quote[1] == '\t' || end_quote[1] == '\0')
315 {
316 arg_complete = true;
317 arg_end = end_quote + 1;
Chris Lattner24943d22010-06-08 16:52:24 +0000318 }
319 else
320 {
Greg Clayton928d1302010-12-19 03:41:24 +0000321 arg_pos = end_quote + 1;
322 arg_piece_start = arg_pos;
Chris Lattner24943d22010-06-08 16:52:24 +0000323 }
Greg Clayton928d1302010-12-19 03:41:24 +0000324 quote_char = '\0';
Chris Lattner24943d22010-06-08 16:52:24 +0000325 }
Greg Clayton03e498e2012-03-15 17:10:48 +0000326 else
327 {
328 // Consume the rest of the string as there was no terminating quote
329 arg.append(arg_piece_start);
330 arg_end = arg_piece_start + strlen(arg_piece_start);
331 arg_complete = true;
332 }
Chris Lattner24943d22010-06-08 16:52:24 +0000333 }
Greg Clayton928d1302010-12-19 03:41:24 +0000334 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000335
Greg Clayton928d1302010-12-19 03:41:24 +0000336 case ' ':
337 case '\t':
338 if (quote_char)
Chris Lattner24943d22010-06-08 16:52:24 +0000339 {
Greg Clayton928d1302010-12-19 03:41:24 +0000340 // We are currently processing a quoted character and found
341 // a space character, skip any spaces and keep trying to find
342 // the end of the argument.
343 arg_pos = ::strspn (arg_end, k_space_separators) + arg_end;
Chris Lattner24943d22010-06-08 16:52:24 +0000344 }
Greg Clayton928d1302010-12-19 03:41:24 +0000345 else
Chris Lattner24943d22010-06-08 16:52:24 +0000346 {
Greg Clayton928d1302010-12-19 03:41:24 +0000347 // We are not inside any quotes, we just found a space after an
348 // argument
349 if (arg_end > arg_piece_start)
350 arg.append (arg_piece_start, arg_end - arg_piece_start);
351 arg_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000352 }
Greg Clayton928d1302010-12-19 03:41:24 +0000353 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000354 }
Greg Clayton928d1302010-12-19 03:41:24 +0000355 } while (!arg_complete);
Chris Lattner24943d22010-06-08 16:52:24 +0000356
357 m_args.push_back(arg);
Greg Clayton928d1302010-12-19 03:41:24 +0000358 m_args_quote_char.push_back (first_quote_char);
Chris Lattner24943d22010-06-08 16:52:24 +0000359 }
Greg Clayton928d1302010-12-19 03:41:24 +0000360 UpdateArgvFromArgs();
Chris Lattner24943d22010-06-08 16:52:24 +0000361 }
Chris Lattner24943d22010-06-08 16:52:24 +0000362}
363
364void
365Args::UpdateArgsAfterOptionParsing()
366{
367 // Now m_argv might be out of date with m_args, so we need to fix that
368 arg_cstr_collection::const_iterator argv_pos, argv_end = m_argv.end();
369 arg_sstr_collection::iterator args_pos;
370 arg_quote_char_collection::iterator quotes_pos;
371
372 for (argv_pos = m_argv.begin(), args_pos = m_args.begin(), quotes_pos = m_args_quote_char.begin();
373 argv_pos != argv_end && args_pos != m_args.end();
374 ++argv_pos)
375 {
376 const char *argv_cstr = *argv_pos;
377 if (argv_cstr == NULL)
378 break;
379
380 while (args_pos != m_args.end())
381 {
382 const char *args_cstr = args_pos->c_str();
383 if (args_cstr == argv_cstr)
384 {
385 // We found the argument that matches the C string in the
386 // vector, so we can now look for the next one
387 ++args_pos;
388 ++quotes_pos;
389 break;
390 }
391 else
392 {
393 quotes_pos = m_args_quote_char.erase (quotes_pos);
394 args_pos = m_args.erase (args_pos);
395 }
396 }
397 }
398
399 if (args_pos != m_args.end())
400 m_args.erase (args_pos, m_args.end());
401
402 if (quotes_pos != m_args_quote_char.end())
403 m_args_quote_char.erase (quotes_pos, m_args_quote_char.end());
404}
405
406void
407Args::UpdateArgvFromArgs()
408{
409 m_argv.clear();
410 arg_sstr_collection::const_iterator pos, end = m_args.end();
411 for (pos = m_args.begin(); pos != end; ++pos)
412 m_argv.push_back(pos->c_str());
413 m_argv.push_back(NULL);
Greg Clayton928d1302010-12-19 03:41:24 +0000414 // Make sure we have enough arg quote chars in the array
415 if (m_args_quote_char.size() < m_args.size())
416 m_args_quote_char.resize (m_argv.size());
Chris Lattner24943d22010-06-08 16:52:24 +0000417}
418
419size_t
420Args::GetArgumentCount() const
421{
422 if (m_argv.empty())
423 return 0;
424 return m_argv.size() - 1;
425}
426
427const char *
428Args::GetArgumentAtIndex (size_t idx) const
429{
430 if (idx < m_argv.size())
431 return m_argv[idx];
432 return NULL;
433}
434
435char
436Args::GetArgumentQuoteCharAtIndex (size_t idx) const
437{
438 if (idx < m_args_quote_char.size())
439 return m_args_quote_char[idx];
440 return '\0';
441}
442
443char **
444Args::GetArgumentVector()
445{
446 if (!m_argv.empty())
447 return (char **)&m_argv[0];
448 return NULL;
449}
450
451const char **
452Args::GetConstArgumentVector() const
453{
454 if (!m_argv.empty())
455 return (const char **)&m_argv[0];
456 return NULL;
457}
458
459void
460Args::Shift ()
461{
462 // Don't pop the last NULL terminator from the argv array
463 if (m_argv.size() > 1)
464 {
465 m_argv.erase(m_argv.begin());
466 m_args.pop_front();
Greg Clayton928d1302010-12-19 03:41:24 +0000467 if (!m_args_quote_char.empty())
468 m_args_quote_char.erase(m_args_quote_char.begin());
Chris Lattner24943d22010-06-08 16:52:24 +0000469 }
470}
471
472const char *
473Args::Unshift (const char *arg_cstr, char quote_char)
474{
475 m_args.push_front(arg_cstr);
476 m_argv.insert(m_argv.begin(), m_args.front().c_str());
477 m_args_quote_char.insert(m_args_quote_char.begin(), quote_char);
478 return GetArgumentAtIndex (0);
479}
480
481void
482Args::AppendArguments (const Args &rhs)
483{
484 const size_t rhs_argc = rhs.GetArgumentCount();
485 for (size_t i=0; i<rhs_argc; ++i)
486 AppendArgument(rhs.GetArgumentAtIndex(i));
487}
488
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000489void
490Args::AppendArguments (const char **argv)
491{
492 if (argv)
493 {
494 for (uint32_t i=0; argv[i]; ++i)
495 AppendArgument(argv[i]);
496 }
497}
498
Chris Lattner24943d22010-06-08 16:52:24 +0000499const char *
500Args::AppendArgument (const char *arg_cstr, char quote_char)
501{
502 return InsertArgumentAtIndex (GetArgumentCount(), arg_cstr, quote_char);
503}
504
505const char *
506Args::InsertArgumentAtIndex (size_t idx, const char *arg_cstr, char quote_char)
507{
508 // Since we are using a std::list to hold onto the copied C string and
509 // we don't have direct access to the elements, we have to iterate to
510 // find the value.
511 arg_sstr_collection::iterator pos, end = m_args.end();
512 size_t i = idx;
513 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
514 --i;
515
516 pos = m_args.insert(pos, arg_cstr);
517
Greg Clayton928d1302010-12-19 03:41:24 +0000518 if (idx >= m_args_quote_char.size())
519 {
520 m_args_quote_char.resize(idx + 1);
521 m_args_quote_char[idx] = quote_char;
522 }
523 else
524 m_args_quote_char.insert(m_args_quote_char.begin() + idx, quote_char);
Chris Lattner24943d22010-06-08 16:52:24 +0000525
526 UpdateArgvFromArgs();
527 return GetArgumentAtIndex(idx);
528}
529
530const char *
531Args::ReplaceArgumentAtIndex (size_t idx, const char *arg_cstr, char quote_char)
532{
533 // Since we are using a std::list to hold onto the copied C string and
534 // we don't have direct access to the elements, we have to iterate to
535 // find the value.
536 arg_sstr_collection::iterator pos, end = m_args.end();
537 size_t i = idx;
538 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
539 --i;
540
541 if (pos != end)
542 {
543 pos->assign(arg_cstr);
544 assert(idx < m_argv.size() - 1);
545 m_argv[idx] = pos->c_str();
Greg Clayton928d1302010-12-19 03:41:24 +0000546 if (idx >= m_args_quote_char.size())
547 m_args_quote_char.resize(idx + 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000548 m_args_quote_char[idx] = quote_char;
549 return GetArgumentAtIndex(idx);
550 }
551 return NULL;
552}
553
554void
555Args::DeleteArgumentAtIndex (size_t idx)
556{
557 // Since we are using a std::list to hold onto the copied C string and
558 // we don't have direct access to the elements, we have to iterate to
559 // find the value.
560 arg_sstr_collection::iterator pos, end = m_args.end();
561 size_t i = idx;
562 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
563 --i;
564
565 if (pos != end)
566 {
567 m_args.erase (pos);
568 assert(idx < m_argv.size() - 1);
569 m_argv.erase(m_argv.begin() + idx);
Greg Clayton928d1302010-12-19 03:41:24 +0000570 if (idx < m_args_quote_char.size())
571 m_args_quote_char.erase(m_args_quote_char.begin() + idx);
Chris Lattner24943d22010-06-08 16:52:24 +0000572 }
573}
574
575void
576Args::SetArguments (int argc, const char **argv)
577{
578 // m_argv will be rebuilt in UpdateArgvFromArgs() below, so there is
579 // no need to clear it here.
580 m_args.clear();
581 m_args_quote_char.clear();
582
Chris Lattner24943d22010-06-08 16:52:24 +0000583 // First copy each string
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000584 for (size_t i=0; i<argc; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +0000585 {
586 m_args.push_back (argv[i]);
Greg Clayton928d1302010-12-19 03:41:24 +0000587 if ((argv[i][0] == '\'') || (argv[i][0] == '"') || (argv[i][0] == '`'))
Chris Lattner24943d22010-06-08 16:52:24 +0000588 m_args_quote_char.push_back (argv[i][0]);
589 else
590 m_args_quote_char.push_back ('\0');
591 }
592
593 UpdateArgvFromArgs();
594}
595
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000596void
597Args::SetArguments (const char **argv)
598{
599 // m_argv will be rebuilt in UpdateArgvFromArgs() below, so there is
600 // no need to clear it here.
601 m_args.clear();
602 m_args_quote_char.clear();
603
604 if (argv)
605 {
606 // First copy each string
607 for (size_t i=0; argv[i]; ++i)
608 {
609 m_args.push_back (argv[i]);
610 if ((argv[i][0] == '\'') || (argv[i][0] == '"') || (argv[i][0] == '`'))
611 m_args_quote_char.push_back (argv[i][0]);
612 else
613 m_args_quote_char.push_back ('\0');
614 }
615 }
616
617 UpdateArgvFromArgs();
618}
619
Chris Lattner24943d22010-06-08 16:52:24 +0000620
621Error
622Args::ParseOptions (Options &options)
623{
624 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +0000625 Error error;
626 struct option *long_options = options.GetLongOptions();
627 if (long_options == NULL)
628 {
Greg Clayton9c236732011-10-26 00:56:27 +0000629 error.SetErrorStringWithFormat("invalid long options");
Chris Lattner24943d22010-06-08 16:52:24 +0000630 return error;
631 }
632
Greg Claytonbef15832010-07-14 00:18:15 +0000633 for (int i=0; long_options[i].name != NULL; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +0000634 {
635 if (long_options[i].flag == NULL)
636 {
637 sstr << (char)long_options[i].val;
638 switch (long_options[i].has_arg)
639 {
640 default:
641 case no_argument: break;
642 case required_argument: sstr << ':'; break;
643 case optional_argument: sstr << "::"; break;
644 }
645 }
646 }
Eli Friedmanef2bc872010-06-13 19:18:49 +0000647#ifdef __GLIBC__
648 optind = 0;
649#else
Chris Lattner24943d22010-06-08 16:52:24 +0000650 optreset = 1;
651 optind = 1;
Eli Friedmanef2bc872010-06-13 19:18:49 +0000652#endif
Chris Lattner24943d22010-06-08 16:52:24 +0000653 int val;
654 while (1)
655 {
656 int long_options_index = -1;
657 val = ::getopt_long(GetArgumentCount(), GetArgumentVector(), sstr.GetData(), long_options,
658 &long_options_index);
659 if (val == -1)
660 break;
661
662 // Did we get an error?
663 if (val == '?')
664 {
Greg Clayton9c236732011-10-26 00:56:27 +0000665 error.SetErrorStringWithFormat("unknown or ambiguous option");
Chris Lattner24943d22010-06-08 16:52:24 +0000666 break;
667 }
668 // The option auto-set itself
669 if (val == 0)
670 continue;
671
672 ((Options *) &options)->OptionSeen (val);
673
674 // Lookup the long option index
675 if (long_options_index == -1)
676 {
677 for (int i=0;
678 long_options[i].name || long_options[i].has_arg || long_options[i].flag || long_options[i].val;
679 ++i)
680 {
681 if (long_options[i].val == val)
682 {
683 long_options_index = i;
684 break;
685 }
686 }
687 }
688 // Call the callback with the option
689 if (long_options_index >= 0)
690 {
691 error = options.SetOptionValue(long_options_index,
692 long_options[long_options_index].has_arg == no_argument ? NULL : optarg);
693 }
694 else
695 {
Greg Clayton9c236732011-10-26 00:56:27 +0000696 error.SetErrorStringWithFormat("invalid option with value '%i'", val);
Chris Lattner24943d22010-06-08 16:52:24 +0000697 }
698 if (error.Fail())
699 break;
700 }
701
702 // Update our ARGV now that get options has consumed all the options
703 m_argv.erase(m_argv.begin(), m_argv.begin() + optind);
704 UpdateArgsAfterOptionParsing ();
705 return error;
706}
707
708void
709Args::Clear ()
710{
711 m_args.clear ();
712 m_argv.clear ();
713 m_args_quote_char.clear();
714}
715
716int32_t
717Args::StringToSInt32 (const char *s, int32_t fail_value, int base, bool *success_ptr)
718{
719 if (s && s[0])
720 {
721 char *end = NULL;
722 int32_t uval = ::strtol (s, &end, base);
723 if (*end == '\0')
724 {
725 if (success_ptr) *success_ptr = true;
726 return uval; // All characters were used, return the result
727 }
728 }
729 if (success_ptr) *success_ptr = false;
730 return fail_value;
731}
732
733uint32_t
734Args::StringToUInt32 (const char *s, uint32_t fail_value, int base, bool *success_ptr)
735{
736 if (s && s[0])
737 {
738 char *end = NULL;
739 uint32_t uval = ::strtoul (s, &end, base);
740 if (*end == '\0')
741 {
742 if (success_ptr) *success_ptr = true;
743 return uval; // All characters were used, return the result
744 }
745 }
746 if (success_ptr) *success_ptr = false;
747 return fail_value;
748}
749
750
751int64_t
752Args::StringToSInt64 (const char *s, int64_t fail_value, int base, bool *success_ptr)
753{
754 if (s && s[0])
755 {
756 char *end = NULL;
757 int64_t uval = ::strtoll (s, &end, base);
758 if (*end == '\0')
759 {
760 if (success_ptr) *success_ptr = true;
761 return uval; // All characters were used, return the result
762 }
763 }
764 if (success_ptr) *success_ptr = false;
765 return fail_value;
766}
767
768uint64_t
769Args::StringToUInt64 (const char *s, uint64_t fail_value, int base, bool *success_ptr)
770{
771 if (s && s[0])
772 {
773 char *end = NULL;
774 uint64_t uval = ::strtoull (s, &end, base);
775 if (*end == '\0')
776 {
777 if (success_ptr) *success_ptr = true;
778 return uval; // All characters were used, return the result
779 }
780 }
781 if (success_ptr) *success_ptr = false;
782 return fail_value;
783}
784
785lldb::addr_t
786Args::StringToAddress (const char *s, lldb::addr_t fail_value, bool *success_ptr)
787{
788 if (s && s[0])
789 {
790 char *end = NULL;
791 lldb::addr_t addr = ::strtoull (s, &end, 0);
792 if (*end == '\0')
793 {
794 if (success_ptr) *success_ptr = true;
795 return addr; // All characters were used, return the result
796 }
797 // Try base 16 with no prefix...
798 addr = ::strtoull (s, &end, 16);
799 if (*end == '\0')
800 {
801 if (success_ptr) *success_ptr = true;
802 return addr; // All characters were used, return the result
803 }
804 }
805 if (success_ptr) *success_ptr = false;
806 return fail_value;
807}
808
809bool
810Args::StringToBoolean (const char *s, bool fail_value, bool *success_ptr)
811{
812 if (s && s[0])
813 {
814 if (::strcasecmp (s, "false") == 0 ||
815 ::strcasecmp (s, "off") == 0 ||
816 ::strcasecmp (s, "no") == 0 ||
817 ::strcmp (s, "0") == 0)
818 {
819 if (success_ptr)
820 *success_ptr = true;
821 return false;
822 }
823 else
824 if (::strcasecmp (s, "true") == 0 ||
825 ::strcasecmp (s, "on") == 0 ||
826 ::strcasecmp (s, "yes") == 0 ||
827 ::strcmp (s, "1") == 0)
828 {
829 if (success_ptr) *success_ptr = true;
830 return true;
831 }
832 }
833 if (success_ptr) *success_ptr = false;
834 return fail_value;
835}
836
Greg Claytonb1888f22011-03-19 01:12:21 +0000837const char *
838Args::StringToVersion (const char *s, uint32_t &major, uint32_t &minor, uint32_t &update)
839{
840 major = UINT32_MAX;
841 minor = UINT32_MAX;
842 update = UINT32_MAX;
843
844 if (s && s[0])
845 {
846 char *pos = NULL;
847 uint32_t uval32;
848 uval32 = ::strtoul (s, &pos, 0);
849 if (pos == s)
850 return s;
851 major = uval32;
852 if (*pos == '\0')
853 {
854 return pos; // Decoded major and got end of string
855 }
856 else if (*pos == '.')
857 {
858 const char *minor_cstr = pos + 1;
859 uval32 = ::strtoul (minor_cstr, &pos, 0);
860 if (pos == minor_cstr)
861 return pos; // Didn't get any digits for the minor version...
862 minor = uval32;
863 if (*pos == '.')
864 {
865 const char *update_cstr = pos + 1;
866 uval32 = ::strtoul (update_cstr, &pos, 0);
867 if (pos == update_cstr)
868 return pos;
869 update = uval32;
870 }
871 return pos;
872 }
873 }
874 return 0;
875}
876
Greg Clayton527154d2011-11-15 03:53:30 +0000877const char *
878Args::GetShellSafeArgument (const char *unsafe_arg, std::string &safe_arg)
879{
880 safe_arg.assign (unsafe_arg);
881 size_t prev_pos = 0;
882 while (prev_pos < safe_arg.size())
883 {
884 // Escape spaces and quotes
885 size_t pos = safe_arg.find_first_of(" '\"", prev_pos);
886 if (pos != std::string::npos)
887 {
888 safe_arg.insert (pos, 1, '\\');
889 prev_pos = pos + 2;
890 }
891 else
892 break;
893 }
894 return safe_arg.c_str();
895}
896
Greg Claytonb1888f22011-03-19 01:12:21 +0000897
Chris Lattner24943d22010-06-08 16:52:24 +0000898int32_t
Greg Clayton61aca5d2011-10-07 18:58:12 +0000899Args::StringToOptionEnum (const char *s, OptionEnumValueElement *enum_values, int32_t fail_value, Error &error)
Chris Lattner24943d22010-06-08 16:52:24 +0000900{
Greg Clayton61aca5d2011-10-07 18:58:12 +0000901 if (enum_values)
Chris Lattner24943d22010-06-08 16:52:24 +0000902 {
Greg Clayton61aca5d2011-10-07 18:58:12 +0000903 if (s && s[0])
Chris Lattner24943d22010-06-08 16:52:24 +0000904 {
Greg Clayton61aca5d2011-10-07 18:58:12 +0000905 for (int i = 0; enum_values[i].string_value != NULL ; i++)
Chris Lattner24943d22010-06-08 16:52:24 +0000906 {
Greg Clayton61aca5d2011-10-07 18:58:12 +0000907 if (strstr(enum_values[i].string_value, s) == enum_values[i].string_value)
908 {
909 error.Clear();
910 return enum_values[i].value;
911 }
Chris Lattner24943d22010-06-08 16:52:24 +0000912 }
913 }
Greg Clayton61aca5d2011-10-07 18:58:12 +0000914
915 StreamString strm;
916 strm.PutCString ("invalid enumeration value, valid values are: ");
917 for (int i = 0; enum_values[i].string_value != NULL; i++)
918 {
919 strm.Printf ("%s\"%s\"",
920 i > 0 ? ", " : "",
921 enum_values[i].string_value);
922 }
923 error.SetErrorString(strm.GetData());
Chris Lattner24943d22010-06-08 16:52:24 +0000924 }
Greg Clayton61aca5d2011-10-07 18:58:12 +0000925 else
926 {
927 error.SetErrorString ("invalid enumeration argument");
928 }
Chris Lattner24943d22010-06-08 16:52:24 +0000929 return fail_value;
930}
931
932ScriptLanguage
933Args::StringToScriptLanguage (const char *s, ScriptLanguage fail_value, bool *success_ptr)
934{
935 if (s && s[0])
936 {
937 if ((::strcasecmp (s, "python") == 0) ||
938 (::strcasecmp (s, "default") == 0 && eScriptLanguagePython == eScriptLanguageDefault))
939 {
940 if (success_ptr) *success_ptr = true;
941 return eScriptLanguagePython;
942 }
943 if (::strcasecmp (s, "none"))
944 {
945 if (success_ptr) *success_ptr = true;
946 return eScriptLanguageNone;
947 }
948 }
949 if (success_ptr) *success_ptr = false;
950 return fail_value;
951}
952
953Error
954Args::StringToFormat
955(
956 const char *s,
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000957 lldb::Format &format,
958 uint32_t *byte_size_ptr
Chris Lattner24943d22010-06-08 16:52:24 +0000959)
960{
961 format = eFormatInvalid;
962 Error error;
963
964 if (s && s[0])
965 {
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000966 if (byte_size_ptr)
Chris Lattner24943d22010-06-08 16:52:24 +0000967 {
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000968 if (isdigit (s[0]))
969 {
970 char *format_char = NULL;
971 unsigned long byte_size = ::strtoul (s, &format_char, 0);
972 if (byte_size != ULONG_MAX)
973 *byte_size_ptr = byte_size;
974 s = format_char;
975 }
976 else
977 *byte_size_ptr = 0;
978 }
979
Greg Clayton3182eff2011-06-23 21:22:24 +0000980 const bool partial_match_ok = true;
981 if (!FormatManager::GetFormatFromCString (s, partial_match_ok, format))
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000982 {
Greg Clayton3182eff2011-06-23 21:22:24 +0000983 StreamString error_strm;
984 error_strm.Printf ("Invalid format character or name '%s'. Valid values are:\n", s);
Peter Collingbournef4d4fcc2011-06-24 01:12:22 +0000985 for (Format f = eFormatDefault; f < kNumFormats; f = Format(f+1))
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000986 {
Greg Clayton3182eff2011-06-23 21:22:24 +0000987 char format_char = FormatManager::GetFormatAsFormatChar(f);
988 if (format_char)
989 error_strm.Printf ("'%c' or ", format_char);
990
991 error_strm.Printf ("\"%s\"", FormatManager::GetFormatAsCString(f));
992 error_strm.EOL();
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000993 }
Greg Clayton3182eff2011-06-23 21:22:24 +0000994
995 if (byte_size_ptr)
996 error_strm.PutCString ("An optional byte size can precede the format character.\n");
997 error.SetErrorString(error_strm.GetString().c_str());
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000998 }
Chris Lattner24943d22010-06-08 16:52:24 +0000999
1000 if (error.Fail())
1001 return error;
1002 }
1003 else
1004 {
Greg Clayton9c236732011-10-26 00:56:27 +00001005 error.SetErrorStringWithFormat("%s option string", s ? "empty" : "invalid");
Chris Lattner24943d22010-06-08 16:52:24 +00001006 }
1007 return error;
1008}
1009
Greg Clayton88b980b2012-08-24 01:42:50 +00001010lldb::Encoding
1011Args::StringToEncoding (const char *s, lldb::Encoding fail_value)
1012{
1013 if (s && s[0])
1014 {
1015 if (strcmp(s, "uint") == 0)
1016 return eEncodingUint;
1017 else if (strcmp(s, "sint") == 0)
1018 return eEncodingSint;
1019 else if (strcmp(s, "ieee754") == 0)
1020 return eEncodingIEEE754;
1021 else if (strcmp(s, "vector") == 0)
1022 return eEncodingVector;
1023 }
1024 return fail_value;
1025}
1026
1027uint32_t
1028Args::StringToGenericRegister (const char *s)
1029{
1030 if (s && s[0])
1031 {
1032 if (strcmp(s, "pc") == 0)
1033 return LLDB_REGNUM_GENERIC_PC;
1034 else if (strcmp(s, "sp") == 0)
1035 return LLDB_REGNUM_GENERIC_SP;
1036 else if (strcmp(s, "fp") == 0)
1037 return LLDB_REGNUM_GENERIC_FP;
1038 else if (strcmp(s, "ra") == 0)
1039 return LLDB_REGNUM_GENERIC_RA;
1040 else if (strcmp(s, "flags") == 0)
1041 return LLDB_REGNUM_GENERIC_FLAGS;
1042 else if (strncmp(s, "arg", 3) == 0)
1043 {
1044 if (s[3] && s[4] == '\0')
1045 {
1046 switch (s[3])
1047 {
1048 case '1': return LLDB_REGNUM_GENERIC_ARG1;
1049 case '2': return LLDB_REGNUM_GENERIC_ARG2;
1050 case '3': return LLDB_REGNUM_GENERIC_ARG3;
1051 case '4': return LLDB_REGNUM_GENERIC_ARG4;
1052 case '5': return LLDB_REGNUM_GENERIC_ARG5;
1053 case '6': return LLDB_REGNUM_GENERIC_ARG6;
1054 case '7': return LLDB_REGNUM_GENERIC_ARG7;
1055 case '8': return LLDB_REGNUM_GENERIC_ARG8;
1056 }
1057 }
1058 }
1059 }
1060 return LLDB_INVALID_REGNUM;
1061}
1062
1063
Chris Lattner24943d22010-06-08 16:52:24 +00001064void
1065Args::LongestCommonPrefix (std::string &common_prefix)
1066{
1067 arg_sstr_collection::iterator pos, end = m_args.end();
1068 pos = m_args.begin();
1069 if (pos == end)
1070 common_prefix.clear();
1071 else
1072 common_prefix = (*pos);
1073
1074 for (++pos; pos != end; ++pos)
1075 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00001076 size_t new_size = (*pos).size();
Chris Lattner24943d22010-06-08 16:52:24 +00001077
1078 // First trim common_prefix if it is longer than the current element:
1079 if (common_prefix.size() > new_size)
1080 common_prefix.erase (new_size);
1081
1082 // Then trim it at the first disparity:
1083
Greg Clayton54e7afa2010-07-09 20:39:50 +00001084 for (size_t i = 0; i < common_prefix.size(); i++)
Chris Lattner24943d22010-06-08 16:52:24 +00001085 {
1086 if ((*pos)[i] != common_prefix[i])
1087 {
1088 common_prefix.erase(i);
1089 break;
1090 }
1091 }
1092
1093 // If we've emptied the common prefix, we're done.
1094 if (common_prefix.empty())
1095 break;
1096 }
1097}
1098
Caroline Tice44c841d2010-12-07 19:58:26 +00001099size_t
1100Args::FindArgumentIndexForOption (struct option *long_options, int long_options_index)
1101{
1102 char short_buffer[3];
1103 char long_buffer[255];
1104 ::snprintf (short_buffer, sizeof (short_buffer), "-%c", (char) long_options[long_options_index].val);
1105 ::snprintf (long_buffer, sizeof (long_buffer), "--%s", long_options[long_options_index].name);
1106 size_t end = GetArgumentCount ();
1107 size_t idx = 0;
1108 while (idx < end)
1109 {
1110 if ((::strncmp (GetArgumentAtIndex (idx), short_buffer, strlen (short_buffer)) == 0)
1111 || (::strncmp (GetArgumentAtIndex (idx), long_buffer, strlen (long_buffer)) == 0))
1112 {
1113 return idx;
1114 }
1115 ++idx;
1116 }
1117
1118 return end;
1119}
1120
1121bool
1122Args::IsPositionalArgument (const char *arg)
1123{
1124 if (arg == NULL)
1125 return false;
1126
1127 bool is_positional = true;
1128 char *cptr = (char *) arg;
1129
1130 if (cptr[0] == '%')
1131 {
1132 ++cptr;
1133 while (isdigit (cptr[0]))
1134 ++cptr;
1135 if (cptr[0] != '\0')
1136 is_positional = false;
1137 }
1138 else
1139 is_positional = false;
1140
1141 return is_positional;
1142}
1143
Chris Lattner24943d22010-06-08 16:52:24 +00001144void
Caroline Tice5e0894e2010-10-12 17:45:19 +00001145Args::ParseAliasOptions (Options &options,
1146 CommandReturnObject &result,
Caroline Ticee0da7a52010-12-09 22:52:49 +00001147 OptionArgVector *option_arg_vector,
1148 std::string &raw_input_string)
Chris Lattner24943d22010-06-08 16:52:24 +00001149{
1150 StreamString sstr;
1151 int i;
1152 struct option *long_options = options.GetLongOptions();
1153
1154 if (long_options == NULL)
1155 {
1156 result.AppendError ("invalid long options");
1157 result.SetStatus (eReturnStatusFailed);
1158 return;
1159 }
1160
1161 for (i = 0; long_options[i].name != NULL; ++i)
1162 {
1163 if (long_options[i].flag == NULL)
1164 {
1165 sstr << (char) long_options[i].val;
1166 switch (long_options[i].has_arg)
1167 {
1168 default:
1169 case no_argument:
1170 break;
1171 case required_argument:
1172 sstr << ":";
1173 break;
1174 case optional_argument:
1175 sstr << "::";
1176 break;
1177 }
1178 }
1179 }
1180
Eli Friedmanef2bc872010-06-13 19:18:49 +00001181#ifdef __GLIBC__
1182 optind = 0;
1183#else
Chris Lattner24943d22010-06-08 16:52:24 +00001184 optreset = 1;
1185 optind = 1;
Eli Friedmanef2bc872010-06-13 19:18:49 +00001186#endif
Chris Lattner24943d22010-06-08 16:52:24 +00001187 int val;
1188 while (1)
1189 {
1190 int long_options_index = -1;
1191 val = ::getopt_long (GetArgumentCount(), GetArgumentVector(), sstr.GetData(), long_options,
1192 &long_options_index);
1193
1194 if (val == -1)
1195 break;
1196
1197 if (val == '?')
1198 {
1199 result.AppendError ("unknown or ambiguous option");
1200 result.SetStatus (eReturnStatusFailed);
1201 break;
1202 }
1203
1204 if (val == 0)
1205 continue;
1206
1207 ((Options *) &options)->OptionSeen (val);
1208
1209 // Look up the long option index
1210 if (long_options_index == -1)
1211 {
1212 for (int j = 0;
1213 long_options[j].name || long_options[j].has_arg || long_options[j].flag || long_options[j].val;
1214 ++j)
1215 {
1216 if (long_options[j].val == val)
1217 {
1218 long_options_index = j;
1219 break;
1220 }
1221 }
1222 }
1223
1224 // See if the option takes an argument, and see if one was supplied.
1225 if (long_options_index >= 0)
1226 {
1227 StreamString option_str;
1228 option_str.Printf ("-%c", (char) val);
1229
1230 switch (long_options[long_options_index].has_arg)
1231 {
1232 case no_argument:
Caroline Tice44c841d2010-12-07 19:58:26 +00001233 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
1234 OptionArgValue (no_argument, "<no-argument>")));
Caroline Tice2160c3f2010-09-12 04:48:45 +00001235 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Chris Lattner24943d22010-06-08 16:52:24 +00001236 break;
1237 case required_argument:
1238 if (optarg != NULL)
1239 {
1240 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
Caroline Tice44c841d2010-12-07 19:58:26 +00001241 OptionArgValue (required_argument,
1242 std::string (optarg))));
Chris Lattner24943d22010-06-08 16:52:24 +00001243 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1244 }
1245 else
1246 {
1247 result.AppendErrorWithFormat ("Option '%s' is missing argument specifier.\n",
1248 option_str.GetData());
1249 result.SetStatus (eReturnStatusFailed);
1250 }
1251 break;
1252 case optional_argument:
1253 if (optarg != NULL)
1254 {
1255 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
Caroline Tice44c841d2010-12-07 19:58:26 +00001256 OptionArgValue (optional_argument,
1257 std::string (optarg))));
Chris Lattner24943d22010-06-08 16:52:24 +00001258 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1259 }
1260 else
1261 {
1262 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
Caroline Tice44c841d2010-12-07 19:58:26 +00001263 OptionArgValue (optional_argument, "<no-argument>")));
Chris Lattner24943d22010-06-08 16:52:24 +00001264 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1265 }
1266 break;
1267 default:
1268 result.AppendErrorWithFormat
1269 ("error with options table; invalid value in has_arg field for option '%c'.\n",
1270 (char) val);
1271 result.SetStatus (eReturnStatusFailed);
1272 break;
1273 }
1274 }
1275 else
1276 {
1277 result.AppendErrorWithFormat ("Invalid option with value '%c'.\n", (char) val);
1278 result.SetStatus (eReturnStatusFailed);
1279 }
Caroline Tice5e0894e2010-10-12 17:45:19 +00001280
1281 if (long_options_index >= 0)
1282 {
1283 // 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 +00001284 // supplied. Remove option (and argument, if given) from the argument list. Also remove them from
1285 // the raw_input_string, if one was passed in.
Caroline Tice44c841d2010-12-07 19:58:26 +00001286 size_t idx = FindArgumentIndexForOption (long_options, long_options_index);
1287 if (idx < GetArgumentCount())
1288 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001289 if (raw_input_string.size() > 0)
1290 {
1291 const char *tmp_arg = GetArgumentAtIndex (idx);
1292 size_t pos = raw_input_string.find (tmp_arg);
1293 if (pos != std::string::npos)
1294 raw_input_string.erase (pos, strlen (tmp_arg));
1295 }
Caroline Tice44c841d2010-12-07 19:58:26 +00001296 ReplaceArgumentAtIndex (idx, "");
1297 if ((long_options[long_options_index].has_arg != no_argument)
1298 && (optarg != NULL)
1299 && (idx+1 < GetArgumentCount())
1300 && (strcmp (optarg, GetArgumentAtIndex(idx+1)) == 0))
Caroline Ticee0da7a52010-12-09 22:52:49 +00001301 {
1302 if (raw_input_string.size() > 0)
1303 {
1304 const char *tmp_arg = GetArgumentAtIndex (idx+1);
1305 size_t pos = raw_input_string.find (tmp_arg);
1306 if (pos != std::string::npos)
1307 raw_input_string.erase (pos, strlen (tmp_arg));
1308 }
Caroline Tice44c841d2010-12-07 19:58:26 +00001309 ReplaceArgumentAtIndex (idx+1, "");
Caroline Ticee0da7a52010-12-09 22:52:49 +00001310 }
Caroline Tice44c841d2010-12-07 19:58:26 +00001311 }
Caroline Tice5e0894e2010-10-12 17:45:19 +00001312 }
1313
Chris Lattner24943d22010-06-08 16:52:24 +00001314 if (!result.Succeeded())
1315 break;
1316 }
1317}
1318
1319void
1320Args::ParseArgsForCompletion
1321(
1322 Options &options,
Jim Inghamadb84292010-06-24 20:31:04 +00001323 OptionElementVector &option_element_vector,
1324 uint32_t cursor_index
Chris Lattner24943d22010-06-08 16:52:24 +00001325)
1326{
1327 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001328 struct option *long_options = options.GetLongOptions();
1329 option_element_vector.clear();
1330
1331 if (long_options == NULL)
1332 {
1333 return;
1334 }
1335
1336 // Leading : tells getopt to return a : for a missing option argument AND
1337 // to suppress error messages.
1338
1339 sstr << ":";
Greg Claytonbef15832010-07-14 00:18:15 +00001340 for (int i = 0; long_options[i].name != NULL; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001341 {
1342 if (long_options[i].flag == NULL)
1343 {
1344 sstr << (char) long_options[i].val;
1345 switch (long_options[i].has_arg)
1346 {
1347 default:
1348 case no_argument:
1349 break;
1350 case required_argument:
1351 sstr << ":";
1352 break;
1353 case optional_argument:
1354 sstr << "::";
1355 break;
1356 }
1357 }
1358 }
1359
Eli Friedmanef2bc872010-06-13 19:18:49 +00001360#ifdef __GLIBC__
1361 optind = 0;
1362#else
Chris Lattner24943d22010-06-08 16:52:24 +00001363 optreset = 1;
1364 optind = 1;
Eli Friedmanef2bc872010-06-13 19:18:49 +00001365#endif
Chris Lattner24943d22010-06-08 16:52:24 +00001366 opterr = 0;
1367
1368 int val;
1369 const OptionDefinition *opt_defs = options.GetDefinitions();
1370
Jim Inghamadb84292010-06-24 20:31:04 +00001371 // Fooey... getopt_long permutes the GetArgumentVector to move the options to the front.
Chris Lattner24943d22010-06-08 16:52:24 +00001372 // So we have to build another Arg and pass that to getopt_long so it doesn't
Jim Inghamadb84292010-06-24 20:31:04 +00001373 // change the one we have.
Chris Lattner24943d22010-06-08 16:52:24 +00001374
Greg Clayton54e7afa2010-07-09 20:39:50 +00001375 std::vector<const char *> dummy_vec (GetArgumentVector(), GetArgumentVector() + GetArgumentCount() + 1);
Chris Lattner24943d22010-06-08 16:52:24 +00001376
Jim Inghamadb84292010-06-24 20:31:04 +00001377 bool failed_once = false;
1378 uint32_t dash_dash_pos = -1;
1379
Chris Lattner24943d22010-06-08 16:52:24 +00001380 while (1)
1381 {
1382 bool missing_argument = false;
1383 int parse_start = optind;
1384 int long_options_index = -1;
Jim Inghamadb84292010-06-24 20:31:04 +00001385
Greg Clayton54e7afa2010-07-09 20:39:50 +00001386 val = ::getopt_long (dummy_vec.size() - 1,
Greg Clayton53d68e72010-07-20 22:52:08 +00001387 (char *const *) &dummy_vec.front(),
Greg Clayton54e7afa2010-07-09 20:39:50 +00001388 sstr.GetData(),
1389 long_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001390 &long_options_index);
1391
1392 if (val == -1)
Jim Inghamadb84292010-06-24 20:31:04 +00001393 {
1394 // When we're completing a "--" which is the last option on line,
1395 if (failed_once)
1396 break;
1397
1398 failed_once = true;
1399
1400 // If this is a bare "--" we mark it as such so we can complete it successfully later.
1401 // Handling the "--" is a little tricky, since that may mean end of options or arguments, or the
1402 // user might want to complete options by long name. I make this work by checking whether the
1403 // cursor is in the "--" argument, and if so I assume we're completing the long option, otherwise
1404 // I let it pass to getopt_long which will terminate the option parsing.
1405 // Note, in either case we continue parsing the line so we can figure out what other options
1406 // were passed. This will be useful when we come to restricting completions based on what other
1407 // options we've seen on the line.
Chris Lattner24943d22010-06-08 16:52:24 +00001408
Jim Inghamadb84292010-06-24 20:31:04 +00001409 if (optind < dummy_vec.size() - 1
1410 && (strcmp (dummy_vec[optind-1], "--") == 0))
1411 {
1412 dash_dash_pos = optind - 1;
1413 if (optind - 1 == cursor_index)
1414 {
1415 option_element_vector.push_back (OptionArgElement (OptionArgElement::eBareDoubleDash, optind - 1,
1416 OptionArgElement::eBareDoubleDash));
1417 continue;
1418 }
1419 else
1420 break;
1421 }
1422 else
1423 break;
1424 }
Chris Lattner24943d22010-06-08 16:52:24 +00001425 else if (val == '?')
1426 {
Jim Inghamadb84292010-06-24 20:31:04 +00001427 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1428 OptionArgElement::eUnrecognizedArg));
Chris Lattner24943d22010-06-08 16:52:24 +00001429 continue;
1430 }
1431 else if (val == 0)
1432 {
1433 continue;
1434 }
1435 else if (val == ':')
1436 {
1437 // This is a missing argument.
1438 val = optopt;
1439 missing_argument = true;
1440 }
1441
1442 ((Options *) &options)->OptionSeen (val);
1443
1444 // Look up the long option index
1445 if (long_options_index == -1)
1446 {
1447 for (int j = 0;
1448 long_options[j].name || long_options[j].has_arg || long_options[j].flag || long_options[j].val;
1449 ++j)
1450 {
1451 if (long_options[j].val == val)
1452 {
1453 long_options_index = j;
1454 break;
1455 }
1456 }
1457 }
1458
1459 // See if the option takes an argument, and see if one was supplied.
1460 if (long_options_index >= 0)
1461 {
1462 int opt_defs_index = -1;
1463 for (int i = 0; ; i++)
1464 {
1465 if (opt_defs[i].short_option == 0)
1466 break;
1467 else if (opt_defs[i].short_option == val)
1468 {
1469 opt_defs_index = i;
1470 break;
1471 }
1472 }
1473
1474 switch (long_options[long_options_index].has_arg)
1475 {
1476 case no_argument:
1477 option_element_vector.push_back (OptionArgElement (opt_defs_index, parse_start, 0));
1478 break;
1479 case required_argument:
1480 if (optarg != NULL)
1481 {
1482 int arg_index;
1483 if (missing_argument)
1484 arg_index = -1;
1485 else
Jim Inghamadb84292010-06-24 20:31:04 +00001486 arg_index = optind - 1;
Chris Lattner24943d22010-06-08 16:52:24 +00001487
Jim Inghamadb84292010-06-24 20:31:04 +00001488 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, arg_index));
Chris Lattner24943d22010-06-08 16:52:24 +00001489 }
1490 else
1491 {
Jim Inghamadb84292010-06-24 20:31:04 +00001492 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 1, -1));
Chris Lattner24943d22010-06-08 16:52:24 +00001493 }
1494 break;
1495 case optional_argument:
1496 if (optarg != NULL)
1497 {
Jim Inghamadb84292010-06-24 20:31:04 +00001498 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, optind - 1));
Chris Lattner24943d22010-06-08 16:52:24 +00001499 }
1500 else
1501 {
Jim Inghamadb84292010-06-24 20:31:04 +00001502 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, optind - 1));
Chris Lattner24943d22010-06-08 16:52:24 +00001503 }
1504 break;
1505 default:
1506 // The options table is messed up. Here we'll just continue
Jim Inghamadb84292010-06-24 20:31:04 +00001507 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1508 OptionArgElement::eUnrecognizedArg));
Chris Lattner24943d22010-06-08 16:52:24 +00001509 break;
1510 }
1511 }
1512 else
1513 {
Jim Inghamadb84292010-06-24 20:31:04 +00001514 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1515 OptionArgElement::eUnrecognizedArg));
Chris Lattner24943d22010-06-08 16:52:24 +00001516 }
1517 }
Jim Inghamadb84292010-06-24 20:31:04 +00001518
1519 // Finally we have to handle the case where the cursor index points at a single "-". We want to mark that in
1520 // the option_element_vector, but only if it is not after the "--". But it turns out that getopt_long just ignores
1521 // an isolated "-". So we have to look it up by hand here. We only care if it is AT the cursor position.
1522
1523 if ((dash_dash_pos == -1 || cursor_index < dash_dash_pos)
1524 && strcmp (GetArgumentAtIndex(cursor_index), "-") == 0)
1525 {
1526 option_element_vector.push_back (OptionArgElement (OptionArgElement::eBareDash, cursor_index,
1527 OptionArgElement::eBareDash));
1528
1529 }
Chris Lattner24943d22010-06-08 16:52:24 +00001530}