blob: 5086c2842ed6638e52e02122ccb376b3f1d7b887 [file] [log] [blame]
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001//===-- Args.cpp ------------------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Daniel Malea93a64302012-12-05 00:20:57 +000010#include "lldb/lldb-python.h"
11
Chris Lattner30fdc8d2010-06-08 16:52:24 +000012// C Includes
13#include <getopt.h>
Eli Friedman5661f922010-06-09 10:59:23 +000014#include <cstdlib>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000015// C++ Includes
16// Other libraries and framework includes
17// Project includes
Jim Ingham40af72e2010-06-15 19:49:27 +000018#include "lldb/Interpreter/Args.h"
Greg Claytonbb7f31f2011-06-23 21:22:24 +000019#include "lldb/Core/FormatManager.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000020#include "lldb/Core/Stream.h"
21#include "lldb/Core/StreamFile.h"
22#include "lldb/Core/StreamString.h"
Jim Ingham40af72e2010-06-15 19:49:27 +000023#include "lldb/Interpreter/Options.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000024#include "lldb/Interpreter/CommandReturnObject.h"
25
Chris Lattner30fdc8d2010-06-08 16:52:24 +000026using namespace lldb;
27using namespace lldb_private;
28
Chris Lattner30fdc8d2010-06-08 16:52:24 +000029//----------------------------------------------------------------------
30// Args constructor
31//----------------------------------------------------------------------
32Args::Args (const char *command) :
33 m_args(),
Greg Clayton8b82f082011-04-12 05:54:46 +000034 m_argv(),
35 m_args_quote_char()
Chris Lattner30fdc8d2010-06-08 16:52:24 +000036{
Greg Clayton6ad07dd2010-12-19 03:41:24 +000037 if (command)
38 SetCommandString (command);
Chris Lattner30fdc8d2010-06-08 16:52:24 +000039}
40
41
42Args::Args (const char *command, size_t len) :
43 m_args(),
Greg Clayton8b82f082011-04-12 05:54:46 +000044 m_argv(),
45 m_args_quote_char()
Chris Lattner30fdc8d2010-06-08 16:52:24 +000046{
Greg Clayton6ad07dd2010-12-19 03:41:24 +000047 if (command && len)
48 SetCommandString (command, len);
Chris Lattner30fdc8d2010-06-08 16:52:24 +000049}
50
Chris Lattner30fdc8d2010-06-08 16:52:24 +000051//----------------------------------------------------------------------
Greg Clayton8b82f082011-04-12 05:54:46 +000052// We have to be very careful on the copy constructor of this class
53// to make sure we copy all of the string values, but we can't copy the
54// rhs.m_argv into m_argv since it will point to the "const char *" c
55// strings in rhs.m_args. We need to copy the string list and update our
56// own m_argv appropriately.
57//----------------------------------------------------------------------
58Args::Args (const Args &rhs) :
59 m_args (rhs.m_args),
60 m_argv (),
61 m_args_quote_char(rhs.m_args_quote_char)
62{
63 UpdateArgvFromArgs();
64}
65
66//----------------------------------------------------------------------
67// We have to be very careful on the copy constructor of this class
68// to make sure we copy all of the string values, but we can't copy the
69// rhs.m_argv into m_argv since it will point to the "const char *" c
70// strings in rhs.m_args. We need to copy the string list and update our
71// own m_argv appropriately.
72//----------------------------------------------------------------------
73const Args &
74Args::operator= (const Args &rhs)
75{
76 // Make sure we aren't assigning to self
77 if (this != &rhs)
78 {
79 m_args = rhs.m_args;
80 m_args_quote_char = rhs.m_args_quote_char;
81 UpdateArgvFromArgs();
82 }
83 return *this;
84}
85
86//----------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +000087// Destructor
88//----------------------------------------------------------------------
89Args::~Args ()
90{
91}
92
93void
94Args::Dump (Stream *s)
95{
Chris Lattner30fdc8d2010-06-08 16:52:24 +000096 const int argc = m_argv.size();
97 for (int i=0; i<argc; ++i)
98 {
99 s->Indent();
100 const char *arg_cstr = m_argv[i];
101 if (arg_cstr)
102 s->Printf("argv[%i]=\"%s\"\n", i, arg_cstr);
103 else
104 s->Printf("argv[%i]=NULL\n", i);
105 }
106 s->EOL();
107}
108
109bool
Greg Claytonda91b172012-04-25 22:30:32 +0000110Args::GetCommandString (std::string &command) const
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000111{
112 command.clear();
113 int argc = GetArgumentCount();
114 for (int i=0; i<argc; ++i)
115 {
116 if (i > 0)
117 command += ' ';
118 command += m_argv[i];
119 }
120 return argc > 0;
121}
122
Caroline Tice2d5289d2010-12-10 00:26:54 +0000123bool
Greg Claytonda91b172012-04-25 22:30:32 +0000124Args::GetQuotedCommandString (std::string &command) const
Caroline Tice2d5289d2010-12-10 00:26:54 +0000125{
126 command.clear ();
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000127 size_t argc = GetArgumentCount ();
128 for (size_t i = 0; i < argc; ++i)
Caroline Tice2d5289d2010-12-10 00:26:54 +0000129 {
130 if (i > 0)
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000131 command.append (1, ' ');
132 char quote_char = GetArgumentQuoteCharAtIndex(i);
133 if (quote_char)
Caroline Tice2d5289d2010-12-10 00:26:54 +0000134 {
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000135 command.append (1, quote_char);
136 command.append (m_argv[i]);
137 command.append (1, quote_char);
Caroline Tice2d5289d2010-12-10 00:26:54 +0000138 }
139 else
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000140 command.append (m_argv[i]);
Caroline Tice2d5289d2010-12-10 00:26:54 +0000141 }
142 return argc > 0;
143}
144
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000145void
146Args::SetCommandString (const char *command, size_t len)
147{
148 // Use std::string to make sure we get a NULL terminated string we can use
149 // as "command" could point to a string within a large string....
150 std::string null_terminated_command(command, len);
151 SetCommandString(null_terminated_command.c_str());
152}
153
154void
155Args::SetCommandString (const char *command)
156{
157 m_args.clear();
158 m_argv.clear();
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000159 m_args_quote_char.clear();
160
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000161 if (command && command[0])
162 {
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000163 static const char *k_space_separators = " \t";
Johnny Chena28b89c2012-01-19 19:22:41 +0000164 static const char *k_space_separators_with_slash_and_quotes = " \t \\'\"";
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000165 const char *arg_end = NULL;
166 const char *arg_pos;
167 for (arg_pos = command;
168 arg_pos && arg_pos[0];
169 arg_pos = arg_end)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000170 {
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000171 // Skip any leading space separators
172 const char *arg_start = ::strspn (arg_pos, k_space_separators) + arg_pos;
173
174 // If there were only space separators to the end of the line, then
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000175 // we're done.
176 if (*arg_start == '\0')
177 break;
178
Greg Clayton710dd5a2011-01-08 20:28:42 +0000179 // Arguments can be split into multiple discontiguous pieces,
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000180 // for example:
181 // "Hello ""World"
182 // this would result in a single argument "Hello World" (without/
183 // the quotes) since the quotes would be removed and there is
184 // not space between the strings. So we need to keep track of the
185 // current start of each argument piece in "arg_piece_start"
186 const char *arg_piece_start = arg_start;
187 arg_pos = arg_piece_start;
188
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000189 std::string arg;
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000190 // Since we can have multiple quotes that form a single command
191 // in a command like: "Hello "world'!' (which will make a single
192 // argument "Hello world!") we remember the first quote character
193 // we encounter and use that for the quote character.
194 char first_quote_char = '\0';
195 char quote_char = '\0';
196 bool arg_complete = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000197
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000198 do
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000199 {
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000200 arg_end = ::strcspn (arg_pos, k_space_separators_with_slash_and_quotes) + arg_pos;
201
202 switch (arg_end[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000203 {
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000204 default:
205 assert (!"Unhandled case statement, we must handle this...");
206 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000207
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000208 case '\0':
209 // End of C string
210 if (arg_piece_start && arg_piece_start[0])
211 arg.append (arg_piece_start);
212 arg_complete = true;
213 break;
214
215 case '\\':
216 // Backslash character
217 switch (arg_end[1])
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000218 {
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000219 case '\0':
220 arg.append (arg_piece_start);
Greg Clayton0c943132012-03-15 17:10:48 +0000221 ++arg_end;
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000222 arg_complete = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000223 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000224
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000225 default:
Jim Inghama39fb7a2012-07-21 00:12:58 +0000226 if (quote_char == '\0')
227 {
228 arg.append (arg_piece_start, arg_end - arg_piece_start);
229 if (arg_end + 1 != '\0')
230 {
231 arg.append (arg_end + 1, 1);
232 arg_pos = arg_end + 2;
233 arg_piece_start = arg_pos;
234 }
235 }
236 else
237 arg_pos = arg_end + 2;
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000238 break;
239 }
240 break;
241
242 case '"':
243 case '\'':
244 case '`':
245 // Quote characters
246 if (quote_char)
247 {
248 // We found a quote character while inside a quoted
249 // character argument. If it matches our current quote
250 // character, this ends the effect of the quotes. If it
251 // doesn't we ignore it.
252 if (quote_char == arg_end[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000253 {
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000254 arg.append (arg_piece_start, arg_end - arg_piece_start);
255 // Clear the quote character and let parsing
256 // continue (we need to watch for things like:
257 // "Hello ""World"
258 // "Hello "World
259 // "Hello "'World'
260 // All of which will result in a single argument "Hello World"
261 quote_char = '\0'; // Note that we are no longer inside quotes
262 arg_pos = arg_end + 1; // Skip the quote character
263 arg_piece_start = arg_pos; // Note we are starting from later in the string
264 }
265 else
266 {
267 // different quote, skip it and keep going
268 arg_pos = arg_end + 1;
269 }
270 }
271 else
272 {
273 // We found the start of a quote scope.
Greg Clayton710dd5a2011-01-08 20:28:42 +0000274 // Make sure there isn't a string that precedes
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000275 // the start of a quote scope like:
276 // Hello" World"
277 // If so, then add the "Hello" to the arg
278 if (arg_end > arg_piece_start)
279 arg.append (arg_piece_start, arg_end - arg_piece_start);
280
281 // Enter into a quote scope
282 quote_char = arg_end[0];
283
284 if (first_quote_char == '\0')
285 first_quote_char = quote_char;
286
287 arg_pos = arg_end;
Johnny Chena28b89c2012-01-19 19:22:41 +0000288 ++arg_pos; // Skip the quote character
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000289 arg_piece_start = arg_pos; // Note we are starting from later in the string
290
291 // Skip till the next quote character
292 const char *end_quote = ::strchr (arg_piece_start, quote_char);
293 while (end_quote && end_quote[-1] == '\\')
294 {
295 // Don't skip the quote character if it is
296 // preceded by a '\' character
297 end_quote = ::strchr (end_quote + 1, quote_char);
298 }
299
300 if (end_quote)
301 {
302 if (end_quote > arg_piece_start)
Johnny Chena28b89c2012-01-19 19:22:41 +0000303 arg.append (arg_piece_start, end_quote - arg_piece_start);
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000304
305 // If the next character is a space or the end of
306 // string, this argument is complete...
307 if (end_quote[1] == ' ' || end_quote[1] == '\t' || end_quote[1] == '\0')
308 {
309 arg_complete = true;
310 arg_end = end_quote + 1;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000311 }
312 else
313 {
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000314 arg_pos = end_quote + 1;
315 arg_piece_start = arg_pos;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000316 }
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000317 quote_char = '\0';
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000318 }
Greg Clayton0c943132012-03-15 17:10:48 +0000319 else
320 {
321 // Consume the rest of the string as there was no terminating quote
322 arg.append(arg_piece_start);
323 arg_end = arg_piece_start + strlen(arg_piece_start);
324 arg_complete = true;
325 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000326 }
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000327 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000328
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000329 case ' ':
330 case '\t':
331 if (quote_char)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000332 {
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000333 // We are currently processing a quoted character and found
334 // a space character, skip any spaces and keep trying to find
335 // the end of the argument.
336 arg_pos = ::strspn (arg_end, k_space_separators) + arg_end;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000337 }
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000338 else
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000339 {
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000340 // We are not inside any quotes, we just found a space after an
341 // argument
342 if (arg_end > arg_piece_start)
343 arg.append (arg_piece_start, arg_end - arg_piece_start);
344 arg_complete = true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000345 }
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000346 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000347 }
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000348 } while (!arg_complete);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000349
350 m_args.push_back(arg);
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000351 m_args_quote_char.push_back (first_quote_char);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000352 }
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000353 UpdateArgvFromArgs();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000354 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000355}
356
357void
358Args::UpdateArgsAfterOptionParsing()
359{
360 // Now m_argv might be out of date with m_args, so we need to fix that
361 arg_cstr_collection::const_iterator argv_pos, argv_end = m_argv.end();
362 arg_sstr_collection::iterator args_pos;
363 arg_quote_char_collection::iterator quotes_pos;
364
365 for (argv_pos = m_argv.begin(), args_pos = m_args.begin(), quotes_pos = m_args_quote_char.begin();
366 argv_pos != argv_end && args_pos != m_args.end();
367 ++argv_pos)
368 {
369 const char *argv_cstr = *argv_pos;
370 if (argv_cstr == NULL)
371 break;
372
373 while (args_pos != m_args.end())
374 {
375 const char *args_cstr = args_pos->c_str();
376 if (args_cstr == argv_cstr)
377 {
378 // We found the argument that matches the C string in the
379 // vector, so we can now look for the next one
380 ++args_pos;
381 ++quotes_pos;
382 break;
383 }
384 else
385 {
386 quotes_pos = m_args_quote_char.erase (quotes_pos);
387 args_pos = m_args.erase (args_pos);
388 }
389 }
390 }
391
392 if (args_pos != m_args.end())
393 m_args.erase (args_pos, m_args.end());
394
395 if (quotes_pos != m_args_quote_char.end())
396 m_args_quote_char.erase (quotes_pos, m_args_quote_char.end());
397}
398
399void
400Args::UpdateArgvFromArgs()
401{
402 m_argv.clear();
403 arg_sstr_collection::const_iterator pos, end = m_args.end();
404 for (pos = m_args.begin(); pos != end; ++pos)
405 m_argv.push_back(pos->c_str());
406 m_argv.push_back(NULL);
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000407 // Make sure we have enough arg quote chars in the array
408 if (m_args_quote_char.size() < m_args.size())
409 m_args_quote_char.resize (m_argv.size());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000410}
411
412size_t
413Args::GetArgumentCount() const
414{
415 if (m_argv.empty())
416 return 0;
417 return m_argv.size() - 1;
418}
419
420const char *
421Args::GetArgumentAtIndex (size_t idx) const
422{
423 if (idx < m_argv.size())
424 return m_argv[idx];
425 return NULL;
426}
427
428char
429Args::GetArgumentQuoteCharAtIndex (size_t idx) const
430{
431 if (idx < m_args_quote_char.size())
432 return m_args_quote_char[idx];
433 return '\0';
434}
435
436char **
437Args::GetArgumentVector()
438{
439 if (!m_argv.empty())
440 return (char **)&m_argv[0];
441 return NULL;
442}
443
444const char **
445Args::GetConstArgumentVector() const
446{
447 if (!m_argv.empty())
448 return (const char **)&m_argv[0];
449 return NULL;
450}
451
452void
453Args::Shift ()
454{
455 // Don't pop the last NULL terminator from the argv array
456 if (m_argv.size() > 1)
457 {
458 m_argv.erase(m_argv.begin());
459 m_args.pop_front();
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000460 if (!m_args_quote_char.empty())
461 m_args_quote_char.erase(m_args_quote_char.begin());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000462 }
463}
464
465const char *
466Args::Unshift (const char *arg_cstr, char quote_char)
467{
468 m_args.push_front(arg_cstr);
469 m_argv.insert(m_argv.begin(), m_args.front().c_str());
470 m_args_quote_char.insert(m_args_quote_char.begin(), quote_char);
471 return GetArgumentAtIndex (0);
472}
473
474void
475Args::AppendArguments (const Args &rhs)
476{
477 const size_t rhs_argc = rhs.GetArgumentCount();
478 for (size_t i=0; i<rhs_argc; ++i)
479 AppendArgument(rhs.GetArgumentAtIndex(i));
480}
481
Greg Clayton982c9762011-11-03 21:22:33 +0000482void
483Args::AppendArguments (const char **argv)
484{
485 if (argv)
486 {
487 for (uint32_t i=0; argv[i]; ++i)
488 AppendArgument(argv[i]);
489 }
490}
491
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000492const char *
493Args::AppendArgument (const char *arg_cstr, char quote_char)
494{
495 return InsertArgumentAtIndex (GetArgumentCount(), arg_cstr, quote_char);
496}
497
498const char *
499Args::InsertArgumentAtIndex (size_t idx, const char *arg_cstr, char quote_char)
500{
501 // Since we are using a std::list to hold onto the copied C string and
502 // we don't have direct access to the elements, we have to iterate to
503 // find the value.
504 arg_sstr_collection::iterator pos, end = m_args.end();
505 size_t i = idx;
506 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
507 --i;
508
509 pos = m_args.insert(pos, arg_cstr);
510
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000511 if (idx >= m_args_quote_char.size())
512 {
513 m_args_quote_char.resize(idx + 1);
514 m_args_quote_char[idx] = quote_char;
515 }
516 else
517 m_args_quote_char.insert(m_args_quote_char.begin() + idx, quote_char);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000518
519 UpdateArgvFromArgs();
520 return GetArgumentAtIndex(idx);
521}
522
523const char *
524Args::ReplaceArgumentAtIndex (size_t idx, const char *arg_cstr, char quote_char)
525{
526 // Since we are using a std::list to hold onto the copied C string and
527 // we don't have direct access to the elements, we have to iterate to
528 // find the value.
529 arg_sstr_collection::iterator pos, end = m_args.end();
530 size_t i = idx;
531 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
532 --i;
533
534 if (pos != end)
535 {
536 pos->assign(arg_cstr);
537 assert(idx < m_argv.size() - 1);
538 m_argv[idx] = pos->c_str();
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000539 if (idx >= m_args_quote_char.size())
540 m_args_quote_char.resize(idx + 1);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000541 m_args_quote_char[idx] = quote_char;
542 return GetArgumentAtIndex(idx);
543 }
544 return NULL;
545}
546
547void
548Args::DeleteArgumentAtIndex (size_t idx)
549{
550 // Since we are using a std::list to hold onto the copied C string and
551 // we don't have direct access to the elements, we have to iterate to
552 // find the value.
553 arg_sstr_collection::iterator pos, end = m_args.end();
554 size_t i = idx;
555 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
556 --i;
557
558 if (pos != end)
559 {
560 m_args.erase (pos);
561 assert(idx < m_argv.size() - 1);
562 m_argv.erase(m_argv.begin() + idx);
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000563 if (idx < m_args_quote_char.size())
564 m_args_quote_char.erase(m_args_quote_char.begin() + idx);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000565 }
566}
567
568void
569Args::SetArguments (int argc, const char **argv)
570{
571 // m_argv will be rebuilt in UpdateArgvFromArgs() below, so there is
572 // no need to clear it here.
573 m_args.clear();
574 m_args_quote_char.clear();
575
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000576 // First copy each string
Greg Clayton982c9762011-11-03 21:22:33 +0000577 for (size_t i=0; i<argc; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000578 {
579 m_args.push_back (argv[i]);
Greg Clayton6ad07dd2010-12-19 03:41:24 +0000580 if ((argv[i][0] == '\'') || (argv[i][0] == '"') || (argv[i][0] == '`'))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000581 m_args_quote_char.push_back (argv[i][0]);
582 else
583 m_args_quote_char.push_back ('\0');
584 }
585
586 UpdateArgvFromArgs();
587}
588
Greg Clayton982c9762011-11-03 21:22:33 +0000589void
590Args::SetArguments (const char **argv)
591{
592 // m_argv will be rebuilt in UpdateArgvFromArgs() below, so there is
593 // no need to clear it here.
594 m_args.clear();
595 m_args_quote_char.clear();
596
597 if (argv)
598 {
599 // First copy each string
600 for (size_t i=0; argv[i]; ++i)
601 {
602 m_args.push_back (argv[i]);
603 if ((argv[i][0] == '\'') || (argv[i][0] == '"') || (argv[i][0] == '`'))
604 m_args_quote_char.push_back (argv[i][0]);
605 else
606 m_args_quote_char.push_back ('\0');
607 }
608 }
609
610 UpdateArgvFromArgs();
611}
612
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000613
614Error
615Args::ParseOptions (Options &options)
616{
617 StreamString sstr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000618 Error error;
619 struct option *long_options = options.GetLongOptions();
620 if (long_options == NULL)
621 {
Greg Clayton86edbf42011-10-26 00:56:27 +0000622 error.SetErrorStringWithFormat("invalid long options");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000623 return error;
624 }
625
Greg Claytonb1320972010-07-14 00:18:15 +0000626 for (int i=0; long_options[i].name != NULL; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000627 {
628 if (long_options[i].flag == NULL)
629 {
Greg Clayton3bcdfc02012-12-04 00:32:51 +0000630 if (isprint(long_options[i].val))
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000631 {
Greg Clayton3bcdfc02012-12-04 00:32:51 +0000632 sstr << (char)long_options[i].val;
633 switch (long_options[i].has_arg)
634 {
635 default:
636 case no_argument: break;
637 case required_argument: sstr << ':'; break;
638 case optional_argument: sstr << "::"; break;
639 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000640 }
641 }
642 }
Eli Friedmanadb35022010-06-13 19:18:49 +0000643#ifdef __GLIBC__
644 optind = 0;
645#else
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000646 optreset = 1;
647 optind = 1;
Eli Friedmanadb35022010-06-13 19:18:49 +0000648#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000649 int val;
650 while (1)
651 {
652 int long_options_index = -1;
Greg Clayton3bcdfc02012-12-04 00:32:51 +0000653 val = ::getopt_long(GetArgumentCount(),
654 GetArgumentVector(),
655 sstr.GetData(),
656 long_options,
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000657 &long_options_index);
658 if (val == -1)
659 break;
660
661 // Did we get an error?
662 if (val == '?')
663 {
Greg Clayton86edbf42011-10-26 00:56:27 +0000664 error.SetErrorStringWithFormat("unknown or ambiguous option");
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000665 break;
666 }
667 // The option auto-set itself
668 if (val == 0)
669 continue;
670
671 ((Options *) &options)->OptionSeen (val);
672
673 // Lookup the long option index
674 if (long_options_index == -1)
675 {
676 for (int i=0;
677 long_options[i].name || long_options[i].has_arg || long_options[i].flag || long_options[i].val;
678 ++i)
679 {
680 if (long_options[i].val == val)
681 {
682 long_options_index = i;
683 break;
684 }
685 }
686 }
687 // Call the callback with the option
688 if (long_options_index >= 0)
689 {
690 error = options.SetOptionValue(long_options_index,
691 long_options[long_options_index].has_arg == no_argument ? NULL : optarg);
692 }
693 else
694 {
Greg Clayton86edbf42011-10-26 00:56:27 +0000695 error.SetErrorStringWithFormat("invalid option with value '%i'", val);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000696 }
697 if (error.Fail())
698 break;
699 }
700
701 // Update our ARGV now that get options has consumed all the options
702 m_argv.erase(m_argv.begin(), m_argv.begin() + optind);
703 UpdateArgsAfterOptionParsing ();
704 return error;
705}
706
707void
708Args::Clear ()
709{
710 m_args.clear ();
711 m_argv.clear ();
712 m_args_quote_char.clear();
713}
714
715int32_t
716Args::StringToSInt32 (const char *s, int32_t fail_value, int base, bool *success_ptr)
717{
718 if (s && s[0])
719 {
720 char *end = NULL;
721 int32_t uval = ::strtol (s, &end, base);
722 if (*end == '\0')
723 {
724 if (success_ptr) *success_ptr = true;
725 return uval; // All characters were used, return the result
726 }
727 }
728 if (success_ptr) *success_ptr = false;
729 return fail_value;
730}
731
732uint32_t
733Args::StringToUInt32 (const char *s, uint32_t fail_value, int base, bool *success_ptr)
734{
735 if (s && s[0])
736 {
737 char *end = NULL;
738 uint32_t uval = ::strtoul (s, &end, base);
739 if (*end == '\0')
740 {
741 if (success_ptr) *success_ptr = true;
742 return uval; // All characters were used, return the result
743 }
744 }
745 if (success_ptr) *success_ptr = false;
746 return fail_value;
747}
748
749
750int64_t
751Args::StringToSInt64 (const char *s, int64_t fail_value, int base, bool *success_ptr)
752{
753 if (s && s[0])
754 {
755 char *end = NULL;
756 int64_t uval = ::strtoll (s, &end, base);
757 if (*end == '\0')
758 {
759 if (success_ptr) *success_ptr = true;
760 return uval; // All characters were used, return the result
761 }
762 }
763 if (success_ptr) *success_ptr = false;
764 return fail_value;
765}
766
767uint64_t
768Args::StringToUInt64 (const char *s, uint64_t fail_value, int base, bool *success_ptr)
769{
770 if (s && s[0])
771 {
772 char *end = NULL;
773 uint64_t uval = ::strtoull (s, &end, base);
774 if (*end == '\0')
775 {
776 if (success_ptr) *success_ptr = true;
777 return uval; // All characters were used, return the result
778 }
779 }
780 if (success_ptr) *success_ptr = false;
781 return fail_value;
782}
783
784lldb::addr_t
785Args::StringToAddress (const char *s, lldb::addr_t fail_value, bool *success_ptr)
786{
787 if (s && s[0])
788 {
789 char *end = NULL;
790 lldb::addr_t addr = ::strtoull (s, &end, 0);
791 if (*end == '\0')
792 {
793 if (success_ptr) *success_ptr = true;
794 return addr; // All characters were used, return the result
795 }
796 // Try base 16 with no prefix...
797 addr = ::strtoull (s, &end, 16);
798 if (*end == '\0')
799 {
800 if (success_ptr) *success_ptr = true;
801 return addr; // All characters were used, return the result
802 }
803 }
804 if (success_ptr) *success_ptr = false;
805 return fail_value;
806}
807
808bool
809Args::StringToBoolean (const char *s, bool fail_value, bool *success_ptr)
810{
811 if (s && s[0])
812 {
813 if (::strcasecmp (s, "false") == 0 ||
814 ::strcasecmp (s, "off") == 0 ||
815 ::strcasecmp (s, "no") == 0 ||
816 ::strcmp (s, "0") == 0)
817 {
818 if (success_ptr)
819 *success_ptr = true;
820 return false;
821 }
822 else
823 if (::strcasecmp (s, "true") == 0 ||
824 ::strcasecmp (s, "on") == 0 ||
825 ::strcasecmp (s, "yes") == 0 ||
826 ::strcmp (s, "1") == 0)
827 {
828 if (success_ptr) *success_ptr = true;
829 return true;
830 }
831 }
832 if (success_ptr) *success_ptr = false;
833 return fail_value;
834}
835
Greg Claytonded470d2011-03-19 01:12:21 +0000836const char *
837Args::StringToVersion (const char *s, uint32_t &major, uint32_t &minor, uint32_t &update)
838{
839 major = UINT32_MAX;
840 minor = UINT32_MAX;
841 update = UINT32_MAX;
842
843 if (s && s[0])
844 {
845 char *pos = NULL;
846 uint32_t uval32;
847 uval32 = ::strtoul (s, &pos, 0);
848 if (pos == s)
849 return s;
850 major = uval32;
851 if (*pos == '\0')
852 {
853 return pos; // Decoded major and got end of string
854 }
855 else if (*pos == '.')
856 {
857 const char *minor_cstr = pos + 1;
858 uval32 = ::strtoul (minor_cstr, &pos, 0);
859 if (pos == minor_cstr)
860 return pos; // Didn't get any digits for the minor version...
861 minor = uval32;
862 if (*pos == '.')
863 {
864 const char *update_cstr = pos + 1;
865 uval32 = ::strtoul (update_cstr, &pos, 0);
866 if (pos == update_cstr)
867 return pos;
868 update = uval32;
869 }
870 return pos;
871 }
872 }
873 return 0;
874}
875
Greg Clayton144f3a92011-11-15 03:53:30 +0000876const char *
877Args::GetShellSafeArgument (const char *unsafe_arg, std::string &safe_arg)
878{
879 safe_arg.assign (unsafe_arg);
880 size_t prev_pos = 0;
881 while (prev_pos < safe_arg.size())
882 {
883 // Escape spaces and quotes
884 size_t pos = safe_arg.find_first_of(" '\"", prev_pos);
885 if (pos != std::string::npos)
886 {
887 safe_arg.insert (pos, 1, '\\');
888 prev_pos = pos + 2;
889 }
890 else
891 break;
892 }
893 return safe_arg.c_str();
894}
895
Greg Claytonded470d2011-03-19 01:12:21 +0000896
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000897int32_t
Greg Claytoncf0e4f02011-10-07 18:58:12 +0000898Args::StringToOptionEnum (const char *s, OptionEnumValueElement *enum_values, int32_t fail_value, Error &error)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000899{
Greg Claytoncf0e4f02011-10-07 18:58:12 +0000900 if (enum_values)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000901 {
Greg Claytoncf0e4f02011-10-07 18:58:12 +0000902 if (s && s[0])
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000903 {
Greg Claytoncf0e4f02011-10-07 18:58:12 +0000904 for (int i = 0; enum_values[i].string_value != NULL ; i++)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000905 {
Greg Claytoncf0e4f02011-10-07 18:58:12 +0000906 if (strstr(enum_values[i].string_value, s) == enum_values[i].string_value)
907 {
908 error.Clear();
909 return enum_values[i].value;
910 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000911 }
912 }
Greg Claytoncf0e4f02011-10-07 18:58:12 +0000913
914 StreamString strm;
915 strm.PutCString ("invalid enumeration value, valid values are: ");
916 for (int i = 0; enum_values[i].string_value != NULL; i++)
917 {
918 strm.Printf ("%s\"%s\"",
919 i > 0 ? ", " : "",
920 enum_values[i].string_value);
921 }
922 error.SetErrorString(strm.GetData());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000923 }
Greg Claytoncf0e4f02011-10-07 18:58:12 +0000924 else
925 {
926 error.SetErrorString ("invalid enumeration argument");
927 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000928 return fail_value;
929}
930
931ScriptLanguage
932Args::StringToScriptLanguage (const char *s, ScriptLanguage fail_value, bool *success_ptr)
933{
934 if (s && s[0])
935 {
936 if ((::strcasecmp (s, "python") == 0) ||
937 (::strcasecmp (s, "default") == 0 && eScriptLanguagePython == eScriptLanguageDefault))
938 {
939 if (success_ptr) *success_ptr = true;
940 return eScriptLanguagePython;
941 }
942 if (::strcasecmp (s, "none"))
943 {
944 if (success_ptr) *success_ptr = true;
945 return eScriptLanguageNone;
946 }
947 }
948 if (success_ptr) *success_ptr = false;
949 return fail_value;
950}
951
952Error
953Args::StringToFormat
954(
955 const char *s,
Greg Clayton68ebae62011-04-28 20:55:26 +0000956 lldb::Format &format,
957 uint32_t *byte_size_ptr
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000958)
959{
960 format = eFormatInvalid;
961 Error error;
962
963 if (s && s[0])
964 {
Greg Clayton68ebae62011-04-28 20:55:26 +0000965 if (byte_size_ptr)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000966 {
Greg Clayton68ebae62011-04-28 20:55:26 +0000967 if (isdigit (s[0]))
968 {
969 char *format_char = NULL;
970 unsigned long byte_size = ::strtoul (s, &format_char, 0);
971 if (byte_size != ULONG_MAX)
972 *byte_size_ptr = byte_size;
973 s = format_char;
974 }
975 else
976 *byte_size_ptr = 0;
977 }
978
Greg Claytonbb7f31f2011-06-23 21:22:24 +0000979 const bool partial_match_ok = true;
980 if (!FormatManager::GetFormatFromCString (s, partial_match_ok, format))
Greg Clayton68ebae62011-04-28 20:55:26 +0000981 {
Greg Claytonbb7f31f2011-06-23 21:22:24 +0000982 StreamString error_strm;
983 error_strm.Printf ("Invalid format character or name '%s'. Valid values are:\n", s);
Peter Collingbourne44c9b372011-06-24 01:12:22 +0000984 for (Format f = eFormatDefault; f < kNumFormats; f = Format(f+1))
Greg Clayton68ebae62011-04-28 20:55:26 +0000985 {
Greg Claytonbb7f31f2011-06-23 21:22:24 +0000986 char format_char = FormatManager::GetFormatAsFormatChar(f);
987 if (format_char)
988 error_strm.Printf ("'%c' or ", format_char);
989
990 error_strm.Printf ("\"%s\"", FormatManager::GetFormatAsCString(f));
991 error_strm.EOL();
Greg Clayton68ebae62011-04-28 20:55:26 +0000992 }
Greg Claytonbb7f31f2011-06-23 21:22:24 +0000993
994 if (byte_size_ptr)
995 error_strm.PutCString ("An optional byte size can precede the format character.\n");
996 error.SetErrorString(error_strm.GetString().c_str());
Greg Clayton68ebae62011-04-28 20:55:26 +0000997 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000998
999 if (error.Fail())
1000 return error;
1001 }
1002 else
1003 {
Greg Clayton86edbf42011-10-26 00:56:27 +00001004 error.SetErrorStringWithFormat("%s option string", s ? "empty" : "invalid");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001005 }
1006 return error;
1007}
1008
Greg Clayton2443cbd2012-08-24 01:42:50 +00001009lldb::Encoding
1010Args::StringToEncoding (const char *s, lldb::Encoding fail_value)
1011{
1012 if (s && s[0])
1013 {
1014 if (strcmp(s, "uint") == 0)
1015 return eEncodingUint;
1016 else if (strcmp(s, "sint") == 0)
1017 return eEncodingSint;
1018 else if (strcmp(s, "ieee754") == 0)
1019 return eEncodingIEEE754;
1020 else if (strcmp(s, "vector") == 0)
1021 return eEncodingVector;
1022 }
1023 return fail_value;
1024}
1025
1026uint32_t
1027Args::StringToGenericRegister (const char *s)
1028{
1029 if (s && s[0])
1030 {
1031 if (strcmp(s, "pc") == 0)
1032 return LLDB_REGNUM_GENERIC_PC;
1033 else if (strcmp(s, "sp") == 0)
1034 return LLDB_REGNUM_GENERIC_SP;
1035 else if (strcmp(s, "fp") == 0)
1036 return LLDB_REGNUM_GENERIC_FP;
1037 else if (strcmp(s, "ra") == 0)
1038 return LLDB_REGNUM_GENERIC_RA;
1039 else if (strcmp(s, "flags") == 0)
1040 return LLDB_REGNUM_GENERIC_FLAGS;
1041 else if (strncmp(s, "arg", 3) == 0)
1042 {
1043 if (s[3] && s[4] == '\0')
1044 {
1045 switch (s[3])
1046 {
1047 case '1': return LLDB_REGNUM_GENERIC_ARG1;
1048 case '2': return LLDB_REGNUM_GENERIC_ARG2;
1049 case '3': return LLDB_REGNUM_GENERIC_ARG3;
1050 case '4': return LLDB_REGNUM_GENERIC_ARG4;
1051 case '5': return LLDB_REGNUM_GENERIC_ARG5;
1052 case '6': return LLDB_REGNUM_GENERIC_ARG6;
1053 case '7': return LLDB_REGNUM_GENERIC_ARG7;
1054 case '8': return LLDB_REGNUM_GENERIC_ARG8;
1055 }
1056 }
1057 }
1058 }
1059 return LLDB_INVALID_REGNUM;
1060}
1061
1062
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001063void
1064Args::LongestCommonPrefix (std::string &common_prefix)
1065{
1066 arg_sstr_collection::iterator pos, end = m_args.end();
1067 pos = m_args.begin();
1068 if (pos == end)
1069 common_prefix.clear();
1070 else
1071 common_prefix = (*pos);
1072
1073 for (++pos; pos != end; ++pos)
1074 {
Greg Claytonc982c762010-07-09 20:39:50 +00001075 size_t new_size = (*pos).size();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001076
1077 // First trim common_prefix if it is longer than the current element:
1078 if (common_prefix.size() > new_size)
1079 common_prefix.erase (new_size);
1080
1081 // Then trim it at the first disparity:
1082
Greg Claytonc982c762010-07-09 20:39:50 +00001083 for (size_t i = 0; i < common_prefix.size(); i++)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001084 {
1085 if ((*pos)[i] != common_prefix[i])
1086 {
1087 common_prefix.erase(i);
1088 break;
1089 }
1090 }
1091
1092 // If we've emptied the common prefix, we're done.
1093 if (common_prefix.empty())
1094 break;
1095 }
1096}
1097
Caroline Ticed9d63362010-12-07 19:58:26 +00001098size_t
1099Args::FindArgumentIndexForOption (struct option *long_options, int long_options_index)
1100{
1101 char short_buffer[3];
1102 char long_buffer[255];
Greg Clayton3bcdfc02012-12-04 00:32:51 +00001103 ::snprintf (short_buffer, sizeof (short_buffer), "-%c", long_options[long_options_index].val);
Caroline Ticed9d63362010-12-07 19:58:26 +00001104 ::snprintf (long_buffer, sizeof (long_buffer), "--%s", long_options[long_options_index].name);
1105 size_t end = GetArgumentCount ();
1106 size_t idx = 0;
1107 while (idx < end)
1108 {
1109 if ((::strncmp (GetArgumentAtIndex (idx), short_buffer, strlen (short_buffer)) == 0)
1110 || (::strncmp (GetArgumentAtIndex (idx), long_buffer, strlen (long_buffer)) == 0))
1111 {
1112 return idx;
1113 }
1114 ++idx;
1115 }
1116
1117 return end;
1118}
1119
1120bool
1121Args::IsPositionalArgument (const char *arg)
1122{
1123 if (arg == NULL)
1124 return false;
1125
1126 bool is_positional = true;
1127 char *cptr = (char *) arg;
1128
1129 if (cptr[0] == '%')
1130 {
1131 ++cptr;
1132 while (isdigit (cptr[0]))
1133 ++cptr;
1134 if (cptr[0] != '\0')
1135 is_positional = false;
1136 }
1137 else
1138 is_positional = false;
1139
1140 return is_positional;
1141}
1142
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001143void
Caroline Tice636d6ed2010-10-12 17:45:19 +00001144Args::ParseAliasOptions (Options &options,
1145 CommandReturnObject &result,
Caroline Tice844d2302010-12-09 22:52:49 +00001146 OptionArgVector *option_arg_vector,
1147 std::string &raw_input_string)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001148{
1149 StreamString sstr;
1150 int i;
1151 struct option *long_options = options.GetLongOptions();
1152
1153 if (long_options == NULL)
1154 {
1155 result.AppendError ("invalid long options");
1156 result.SetStatus (eReturnStatusFailed);
1157 return;
1158 }
1159
1160 for (i = 0; long_options[i].name != NULL; ++i)
1161 {
1162 if (long_options[i].flag == NULL)
1163 {
1164 sstr << (char) long_options[i].val;
1165 switch (long_options[i].has_arg)
1166 {
1167 default:
1168 case no_argument:
1169 break;
1170 case required_argument:
1171 sstr << ":";
1172 break;
1173 case optional_argument:
1174 sstr << "::";
1175 break;
1176 }
1177 }
1178 }
1179
Eli Friedmanadb35022010-06-13 19:18:49 +00001180#ifdef __GLIBC__
1181 optind = 0;
1182#else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001183 optreset = 1;
1184 optind = 1;
Eli Friedmanadb35022010-06-13 19:18:49 +00001185#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001186 int val;
1187 while (1)
1188 {
1189 int long_options_index = -1;
1190 val = ::getopt_long (GetArgumentCount(), GetArgumentVector(), sstr.GetData(), long_options,
1191 &long_options_index);
1192
1193 if (val == -1)
1194 break;
1195
1196 if (val == '?')
1197 {
1198 result.AppendError ("unknown or ambiguous option");
1199 result.SetStatus (eReturnStatusFailed);
1200 break;
1201 }
1202
1203 if (val == 0)
1204 continue;
1205
1206 ((Options *) &options)->OptionSeen (val);
1207
1208 // Look up the long option index
1209 if (long_options_index == -1)
1210 {
1211 for (int j = 0;
1212 long_options[j].name || long_options[j].has_arg || long_options[j].flag || long_options[j].val;
1213 ++j)
1214 {
1215 if (long_options[j].val == val)
1216 {
1217 long_options_index = j;
1218 break;
1219 }
1220 }
1221 }
1222
1223 // See if the option takes an argument, and see if one was supplied.
1224 if (long_options_index >= 0)
1225 {
1226 StreamString option_str;
Greg Clayton3bcdfc02012-12-04 00:32:51 +00001227 option_str.Printf ("-%c", val);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001228
1229 switch (long_options[long_options_index].has_arg)
1230 {
1231 case no_argument:
Caroline Ticed9d63362010-12-07 19:58:26 +00001232 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
1233 OptionArgValue (no_argument, "<no-argument>")));
Caroline Tice5172e6c2010-09-12 04:48:45 +00001234 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001235 break;
1236 case required_argument:
1237 if (optarg != NULL)
1238 {
1239 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
Caroline Ticed9d63362010-12-07 19:58:26 +00001240 OptionArgValue (required_argument,
1241 std::string (optarg))));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001242 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1243 }
1244 else
1245 {
1246 result.AppendErrorWithFormat ("Option '%s' is missing argument specifier.\n",
1247 option_str.GetData());
1248 result.SetStatus (eReturnStatusFailed);
1249 }
1250 break;
1251 case optional_argument:
1252 if (optarg != NULL)
1253 {
1254 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
Caroline Ticed9d63362010-12-07 19:58:26 +00001255 OptionArgValue (optional_argument,
1256 std::string (optarg))));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001257 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1258 }
1259 else
1260 {
1261 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
Caroline Ticed9d63362010-12-07 19:58:26 +00001262 OptionArgValue (optional_argument, "<no-argument>")));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001263 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1264 }
1265 break;
1266 default:
Greg Clayton3bcdfc02012-12-04 00:32:51 +00001267 result.AppendErrorWithFormat ("error with options table; invalid value in has_arg field for option '%c'.\n", val);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001268 result.SetStatus (eReturnStatusFailed);
1269 break;
1270 }
1271 }
1272 else
1273 {
Greg Clayton3bcdfc02012-12-04 00:32:51 +00001274 result.AppendErrorWithFormat ("Invalid option with value '%c'.\n", val);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001275 result.SetStatus (eReturnStatusFailed);
1276 }
Caroline Tice636d6ed2010-10-12 17:45:19 +00001277
1278 if (long_options_index >= 0)
1279 {
1280 // Find option in the argument list; also see if it was supposed to take an argument and if one was
Caroline Tice844d2302010-12-09 22:52:49 +00001281 // supplied. Remove option (and argument, if given) from the argument list. Also remove them from
1282 // the raw_input_string, if one was passed in.
Caroline Ticed9d63362010-12-07 19:58:26 +00001283 size_t idx = FindArgumentIndexForOption (long_options, long_options_index);
1284 if (idx < GetArgumentCount())
1285 {
Caroline Tice844d2302010-12-09 22:52:49 +00001286 if (raw_input_string.size() > 0)
1287 {
1288 const char *tmp_arg = GetArgumentAtIndex (idx);
1289 size_t pos = raw_input_string.find (tmp_arg);
1290 if (pos != std::string::npos)
1291 raw_input_string.erase (pos, strlen (tmp_arg));
1292 }
Caroline Ticed9d63362010-12-07 19:58:26 +00001293 ReplaceArgumentAtIndex (idx, "");
1294 if ((long_options[long_options_index].has_arg != no_argument)
1295 && (optarg != NULL)
1296 && (idx+1 < GetArgumentCount())
1297 && (strcmp (optarg, GetArgumentAtIndex(idx+1)) == 0))
Caroline Tice844d2302010-12-09 22:52:49 +00001298 {
1299 if (raw_input_string.size() > 0)
1300 {
1301 const char *tmp_arg = GetArgumentAtIndex (idx+1);
1302 size_t pos = raw_input_string.find (tmp_arg);
1303 if (pos != std::string::npos)
1304 raw_input_string.erase (pos, strlen (tmp_arg));
1305 }
Caroline Ticed9d63362010-12-07 19:58:26 +00001306 ReplaceArgumentAtIndex (idx+1, "");
Caroline Tice844d2302010-12-09 22:52:49 +00001307 }
Caroline Ticed9d63362010-12-07 19:58:26 +00001308 }
Caroline Tice636d6ed2010-10-12 17:45:19 +00001309 }
1310
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001311 if (!result.Succeeded())
1312 break;
1313 }
1314}
1315
1316void
1317Args::ParseArgsForCompletion
1318(
1319 Options &options,
Jim Inghamd43e0092010-06-24 20:31:04 +00001320 OptionElementVector &option_element_vector,
1321 uint32_t cursor_index
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001322)
1323{
1324 StreamString sstr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001325 struct option *long_options = options.GetLongOptions();
1326 option_element_vector.clear();
1327
1328 if (long_options == NULL)
1329 {
1330 return;
1331 }
1332
1333 // Leading : tells getopt to return a : for a missing option argument AND
1334 // to suppress error messages.
1335
1336 sstr << ":";
Greg Claytonb1320972010-07-14 00:18:15 +00001337 for (int i = 0; long_options[i].name != NULL; ++i)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001338 {
1339 if (long_options[i].flag == NULL)
1340 {
1341 sstr << (char) long_options[i].val;
1342 switch (long_options[i].has_arg)
1343 {
1344 default:
1345 case no_argument:
1346 break;
1347 case required_argument:
1348 sstr << ":";
1349 break;
1350 case optional_argument:
1351 sstr << "::";
1352 break;
1353 }
1354 }
1355 }
1356
Eli Friedmanadb35022010-06-13 19:18:49 +00001357#ifdef __GLIBC__
1358 optind = 0;
1359#else
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001360 optreset = 1;
1361 optind = 1;
Eli Friedmanadb35022010-06-13 19:18:49 +00001362#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001363 opterr = 0;
1364
1365 int val;
1366 const OptionDefinition *opt_defs = options.GetDefinitions();
1367
Jim Inghamd43e0092010-06-24 20:31:04 +00001368 // Fooey... getopt_long permutes the GetArgumentVector to move the options to the front.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001369 // So we have to build another Arg and pass that to getopt_long so it doesn't
Jim Inghamd43e0092010-06-24 20:31:04 +00001370 // change the one we have.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001371
Greg Claytonc982c762010-07-09 20:39:50 +00001372 std::vector<const char *> dummy_vec (GetArgumentVector(), GetArgumentVector() + GetArgumentCount() + 1);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001373
Jim Inghamd43e0092010-06-24 20:31:04 +00001374 bool failed_once = false;
1375 uint32_t dash_dash_pos = -1;
1376
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001377 while (1)
1378 {
1379 bool missing_argument = false;
1380 int parse_start = optind;
1381 int long_options_index = -1;
Jim Inghamd43e0092010-06-24 20:31:04 +00001382
Greg Claytonc982c762010-07-09 20:39:50 +00001383 val = ::getopt_long (dummy_vec.size() - 1,
Greg Clayton471b31c2010-07-20 22:52:08 +00001384 (char *const *) &dummy_vec.front(),
Greg Claytonc982c762010-07-09 20:39:50 +00001385 sstr.GetData(),
1386 long_options,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001387 &long_options_index);
1388
1389 if (val == -1)
Jim Inghamd43e0092010-06-24 20:31:04 +00001390 {
1391 // When we're completing a "--" which is the last option on line,
1392 if (failed_once)
1393 break;
1394
1395 failed_once = true;
1396
1397 // If this is a bare "--" we mark it as such so we can complete it successfully later.
1398 // Handling the "--" is a little tricky, since that may mean end of options or arguments, or the
1399 // user might want to complete options by long name. I make this work by checking whether the
1400 // cursor is in the "--" argument, and if so I assume we're completing the long option, otherwise
1401 // I let it pass to getopt_long which will terminate the option parsing.
1402 // Note, in either case we continue parsing the line so we can figure out what other options
1403 // were passed. This will be useful when we come to restricting completions based on what other
1404 // options we've seen on the line.
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001405
Jim Inghamd43e0092010-06-24 20:31:04 +00001406 if (optind < dummy_vec.size() - 1
1407 && (strcmp (dummy_vec[optind-1], "--") == 0))
1408 {
1409 dash_dash_pos = optind - 1;
1410 if (optind - 1 == cursor_index)
1411 {
1412 option_element_vector.push_back (OptionArgElement (OptionArgElement::eBareDoubleDash, optind - 1,
1413 OptionArgElement::eBareDoubleDash));
1414 continue;
1415 }
1416 else
1417 break;
1418 }
1419 else
1420 break;
1421 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001422 else if (val == '?')
1423 {
Jim Inghamd43e0092010-06-24 20:31:04 +00001424 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1425 OptionArgElement::eUnrecognizedArg));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001426 continue;
1427 }
1428 else if (val == 0)
1429 {
1430 continue;
1431 }
1432 else if (val == ':')
1433 {
1434 // This is a missing argument.
1435 val = optopt;
1436 missing_argument = true;
1437 }
1438
1439 ((Options *) &options)->OptionSeen (val);
1440
1441 // Look up the long option index
1442 if (long_options_index == -1)
1443 {
1444 for (int j = 0;
1445 long_options[j].name || long_options[j].has_arg || long_options[j].flag || long_options[j].val;
1446 ++j)
1447 {
1448 if (long_options[j].val == val)
1449 {
1450 long_options_index = j;
1451 break;
1452 }
1453 }
1454 }
1455
1456 // See if the option takes an argument, and see if one was supplied.
1457 if (long_options_index >= 0)
1458 {
1459 int opt_defs_index = -1;
1460 for (int i = 0; ; i++)
1461 {
1462 if (opt_defs[i].short_option == 0)
1463 break;
1464 else if (opt_defs[i].short_option == val)
1465 {
1466 opt_defs_index = i;
1467 break;
1468 }
1469 }
1470
1471 switch (long_options[long_options_index].has_arg)
1472 {
1473 case no_argument:
1474 option_element_vector.push_back (OptionArgElement (opt_defs_index, parse_start, 0));
1475 break;
1476 case required_argument:
1477 if (optarg != NULL)
1478 {
1479 int arg_index;
1480 if (missing_argument)
1481 arg_index = -1;
1482 else
Jim Inghamd43e0092010-06-24 20:31:04 +00001483 arg_index = optind - 1;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001484
Jim Inghamd43e0092010-06-24 20:31:04 +00001485 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, arg_index));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001486 }
1487 else
1488 {
Jim Inghamd43e0092010-06-24 20:31:04 +00001489 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 1, -1));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001490 }
1491 break;
1492 case optional_argument:
1493 if (optarg != NULL)
1494 {
Jim Inghamd43e0092010-06-24 20:31:04 +00001495 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, optind - 1));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001496 }
1497 else
1498 {
Jim Inghamd43e0092010-06-24 20:31:04 +00001499 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, optind - 1));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001500 }
1501 break;
1502 default:
1503 // The options table is messed up. Here we'll just continue
Jim Inghamd43e0092010-06-24 20:31:04 +00001504 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1505 OptionArgElement::eUnrecognizedArg));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001506 break;
1507 }
1508 }
1509 else
1510 {
Jim Inghamd43e0092010-06-24 20:31:04 +00001511 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1512 OptionArgElement::eUnrecognizedArg));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001513 }
1514 }
Jim Inghamd43e0092010-06-24 20:31:04 +00001515
1516 // Finally we have to handle the case where the cursor index points at a single "-". We want to mark that in
1517 // the option_element_vector, but only if it is not after the "--". But it turns out that getopt_long just ignores
1518 // an isolated "-". So we have to look it up by hand here. We only care if it is AT the cursor position.
1519
1520 if ((dash_dash_pos == -1 || cursor_index < dash_dash_pos)
1521 && strcmp (GetArgumentAtIndex(cursor_index), "-") == 0)
1522 {
1523 option_element_vector.push_back (OptionArgElement (OptionArgElement::eBareDash, cursor_index,
1524 OptionArgElement::eBareDash));
1525
1526 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001527}
Greg Clayton4c054102012-09-01 00:38:36 +00001528
1529void
1530Args::EncodeEscapeSequences (const char *src, std::string &dst)
1531{
1532 dst.clear();
1533 if (src)
1534 {
1535 for (const char *p = src; *p != '\0'; ++p)
1536 {
1537 size_t non_special_chars = ::strcspn (p, "\\");
1538 if (non_special_chars > 0)
1539 {
1540 dst.append(p, non_special_chars);
1541 p += non_special_chars;
1542 if (*p == '\0')
1543 break;
1544 }
1545
1546 if (*p == '\\')
1547 {
1548 ++p; // skip the slash
1549 switch (*p)
1550 {
1551 case 'a' : dst.append(1, '\a'); break;
1552 case 'b' : dst.append(1, '\b'); break;
1553 case 'f' : dst.append(1, '\f'); break;
1554 case 'n' : dst.append(1, '\n'); break;
1555 case 'r' : dst.append(1, '\r'); break;
1556 case 't' : dst.append(1, '\t'); break;
1557 case 'v' : dst.append(1, '\v'); break;
1558 case '\\': dst.append(1, '\\'); break;
1559 case '\'': dst.append(1, '\''); break;
1560 case '"' : dst.append(1, '"'); break;
1561 case '0' :
1562 // 1 to 3 octal chars
1563 {
1564 // Make a string that can hold onto the initial zero char,
1565 // up to 3 octal digits, and a terminating NULL.
1566 char oct_str[5] = { '\0', '\0', '\0', '\0', '\0' };
1567
1568 int i;
1569 for (i=0; (p[i] >= '0' && p[i] <= '7') && i<4; ++i)
1570 oct_str[i] = p[i];
1571
1572 // We don't want to consume the last octal character since
1573 // the main for loop will do this for us, so we advance p by
1574 // one less than i (even if i is zero)
1575 p += i - 1;
1576 unsigned long octal_value = ::strtoul (oct_str, NULL, 8);
1577 if (octal_value <= UINT8_MAX)
1578 {
1579 const char octal_char = octal_value;
1580 dst.append(1, octal_char);
1581 }
1582 }
1583 break;
1584
1585 case 'x':
1586 // hex number in the format
1587 if (isxdigit(p[1]))
1588 {
1589 ++p; // Skip the 'x'
1590
1591 // Make a string that can hold onto two hex chars plus a
1592 // NULL terminator
1593 char hex_str[3] = { *p, '\0', '\0' };
1594 if (isxdigit(p[1]))
1595 {
1596 ++p; // Skip the first of the two hex chars
1597 hex_str[1] = *p;
1598 }
1599
1600 unsigned long hex_value = strtoul (hex_str, NULL, 16);
1601 if (hex_value <= UINT8_MAX)
1602 dst.append (1, (char)hex_value);
1603 }
1604 else
1605 {
1606 dst.append(1, 'x');
1607 }
1608 break;
1609
1610 default:
1611 // Just desensitize any other character by just printing what
1612 // came after the '\'
1613 dst.append(1, *p);
1614 break;
1615
1616 }
1617 }
1618 }
1619 }
1620}
1621
1622
1623void
1624Args::ExpandEscapedCharacters (const char *src, std::string &dst)
1625{
1626 dst.clear();
1627 if (src)
1628 {
1629 for (const char *p = src; *p != '\0'; ++p)
1630 {
1631 if (isprint(*p))
1632 dst.append(1, *p);
1633 else
1634 {
1635 switch (*p)
1636 {
1637 case '\a': dst.append("\\a"); break;
1638 case '\b': dst.append("\\b"); break;
1639 case '\f': dst.append("\\f"); break;
1640 case '\n': dst.append("\\n"); break;
1641 case '\r': dst.append("\\r"); break;
1642 case '\t': dst.append("\\t"); break;
1643 case '\v': dst.append("\\v"); break;
1644 case '\'': dst.append("\\'"); break;
1645 case '"': dst.append("\\\""); break;
1646 case '\\': dst.append("\\\\"); break;
1647 default:
1648 {
1649 // Just encode as octal
1650 dst.append("\\0");
1651 char octal_str[32];
1652 snprintf(octal_str, sizeof(octal_str), "%o", *p);
1653 dst.append(octal_str);
1654 }
1655 break;
1656 }
1657 }
1658 }
1659 }
1660}
1661