blob: 5b3b6797891468026184d41cfcc2efe0eba20c6f [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
1010void
1011Args::LongestCommonPrefix (std::string &common_prefix)
1012{
1013 arg_sstr_collection::iterator pos, end = m_args.end();
1014 pos = m_args.begin();
1015 if (pos == end)
1016 common_prefix.clear();
1017 else
1018 common_prefix = (*pos);
1019
1020 for (++pos; pos != end; ++pos)
1021 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00001022 size_t new_size = (*pos).size();
Chris Lattner24943d22010-06-08 16:52:24 +00001023
1024 // First trim common_prefix if it is longer than the current element:
1025 if (common_prefix.size() > new_size)
1026 common_prefix.erase (new_size);
1027
1028 // Then trim it at the first disparity:
1029
Greg Clayton54e7afa2010-07-09 20:39:50 +00001030 for (size_t i = 0; i < common_prefix.size(); i++)
Chris Lattner24943d22010-06-08 16:52:24 +00001031 {
1032 if ((*pos)[i] != common_prefix[i])
1033 {
1034 common_prefix.erase(i);
1035 break;
1036 }
1037 }
1038
1039 // If we've emptied the common prefix, we're done.
1040 if (common_prefix.empty())
1041 break;
1042 }
1043}
1044
Caroline Tice44c841d2010-12-07 19:58:26 +00001045size_t
1046Args::FindArgumentIndexForOption (struct option *long_options, int long_options_index)
1047{
1048 char short_buffer[3];
1049 char long_buffer[255];
1050 ::snprintf (short_buffer, sizeof (short_buffer), "-%c", (char) long_options[long_options_index].val);
1051 ::snprintf (long_buffer, sizeof (long_buffer), "--%s", long_options[long_options_index].name);
1052 size_t end = GetArgumentCount ();
1053 size_t idx = 0;
1054 while (idx < end)
1055 {
1056 if ((::strncmp (GetArgumentAtIndex (idx), short_buffer, strlen (short_buffer)) == 0)
1057 || (::strncmp (GetArgumentAtIndex (idx), long_buffer, strlen (long_buffer)) == 0))
1058 {
1059 return idx;
1060 }
1061 ++idx;
1062 }
1063
1064 return end;
1065}
1066
1067bool
1068Args::IsPositionalArgument (const char *arg)
1069{
1070 if (arg == NULL)
1071 return false;
1072
1073 bool is_positional = true;
1074 char *cptr = (char *) arg;
1075
1076 if (cptr[0] == '%')
1077 {
1078 ++cptr;
1079 while (isdigit (cptr[0]))
1080 ++cptr;
1081 if (cptr[0] != '\0')
1082 is_positional = false;
1083 }
1084 else
1085 is_positional = false;
1086
1087 return is_positional;
1088}
1089
Chris Lattner24943d22010-06-08 16:52:24 +00001090void
Caroline Tice5e0894e2010-10-12 17:45:19 +00001091Args::ParseAliasOptions (Options &options,
1092 CommandReturnObject &result,
Caroline Ticee0da7a52010-12-09 22:52:49 +00001093 OptionArgVector *option_arg_vector,
1094 std::string &raw_input_string)
Chris Lattner24943d22010-06-08 16:52:24 +00001095{
1096 StreamString sstr;
1097 int i;
1098 struct option *long_options = options.GetLongOptions();
1099
1100 if (long_options == NULL)
1101 {
1102 result.AppendError ("invalid long options");
1103 result.SetStatus (eReturnStatusFailed);
1104 return;
1105 }
1106
1107 for (i = 0; long_options[i].name != NULL; ++i)
1108 {
1109 if (long_options[i].flag == NULL)
1110 {
1111 sstr << (char) long_options[i].val;
1112 switch (long_options[i].has_arg)
1113 {
1114 default:
1115 case no_argument:
1116 break;
1117 case required_argument:
1118 sstr << ":";
1119 break;
1120 case optional_argument:
1121 sstr << "::";
1122 break;
1123 }
1124 }
1125 }
1126
Eli Friedmanef2bc872010-06-13 19:18:49 +00001127#ifdef __GLIBC__
1128 optind = 0;
1129#else
Chris Lattner24943d22010-06-08 16:52:24 +00001130 optreset = 1;
1131 optind = 1;
Eli Friedmanef2bc872010-06-13 19:18:49 +00001132#endif
Chris Lattner24943d22010-06-08 16:52:24 +00001133 int val;
1134 while (1)
1135 {
1136 int long_options_index = -1;
1137 val = ::getopt_long (GetArgumentCount(), GetArgumentVector(), sstr.GetData(), long_options,
1138 &long_options_index);
1139
1140 if (val == -1)
1141 break;
1142
1143 if (val == '?')
1144 {
1145 result.AppendError ("unknown or ambiguous option");
1146 result.SetStatus (eReturnStatusFailed);
1147 break;
1148 }
1149
1150 if (val == 0)
1151 continue;
1152
1153 ((Options *) &options)->OptionSeen (val);
1154
1155 // Look up the long option index
1156 if (long_options_index == -1)
1157 {
1158 for (int j = 0;
1159 long_options[j].name || long_options[j].has_arg || long_options[j].flag || long_options[j].val;
1160 ++j)
1161 {
1162 if (long_options[j].val == val)
1163 {
1164 long_options_index = j;
1165 break;
1166 }
1167 }
1168 }
1169
1170 // See if the option takes an argument, and see if one was supplied.
1171 if (long_options_index >= 0)
1172 {
1173 StreamString option_str;
1174 option_str.Printf ("-%c", (char) val);
1175
1176 switch (long_options[long_options_index].has_arg)
1177 {
1178 case no_argument:
Caroline Tice44c841d2010-12-07 19:58:26 +00001179 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
1180 OptionArgValue (no_argument, "<no-argument>")));
Caroline Tice2160c3f2010-09-12 04:48:45 +00001181 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Chris Lattner24943d22010-06-08 16:52:24 +00001182 break;
1183 case required_argument:
1184 if (optarg != NULL)
1185 {
1186 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
Caroline Tice44c841d2010-12-07 19:58:26 +00001187 OptionArgValue (required_argument,
1188 std::string (optarg))));
Chris Lattner24943d22010-06-08 16:52:24 +00001189 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1190 }
1191 else
1192 {
1193 result.AppendErrorWithFormat ("Option '%s' is missing argument specifier.\n",
1194 option_str.GetData());
1195 result.SetStatus (eReturnStatusFailed);
1196 }
1197 break;
1198 case optional_argument:
1199 if (optarg != NULL)
1200 {
1201 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
Caroline Tice44c841d2010-12-07 19:58:26 +00001202 OptionArgValue (optional_argument,
1203 std::string (optarg))));
Chris Lattner24943d22010-06-08 16:52:24 +00001204 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1205 }
1206 else
1207 {
1208 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
Caroline Tice44c841d2010-12-07 19:58:26 +00001209 OptionArgValue (optional_argument, "<no-argument>")));
Chris Lattner24943d22010-06-08 16:52:24 +00001210 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1211 }
1212 break;
1213 default:
1214 result.AppendErrorWithFormat
1215 ("error with options table; invalid value in has_arg field for option '%c'.\n",
1216 (char) val);
1217 result.SetStatus (eReturnStatusFailed);
1218 break;
1219 }
1220 }
1221 else
1222 {
1223 result.AppendErrorWithFormat ("Invalid option with value '%c'.\n", (char) val);
1224 result.SetStatus (eReturnStatusFailed);
1225 }
Caroline Tice5e0894e2010-10-12 17:45:19 +00001226
1227 if (long_options_index >= 0)
1228 {
1229 // 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 +00001230 // supplied. Remove option (and argument, if given) from the argument list. Also remove them from
1231 // the raw_input_string, if one was passed in.
Caroline Tice44c841d2010-12-07 19:58:26 +00001232 size_t idx = FindArgumentIndexForOption (long_options, long_options_index);
1233 if (idx < GetArgumentCount())
1234 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001235 if (raw_input_string.size() > 0)
1236 {
1237 const char *tmp_arg = GetArgumentAtIndex (idx);
1238 size_t pos = raw_input_string.find (tmp_arg);
1239 if (pos != std::string::npos)
1240 raw_input_string.erase (pos, strlen (tmp_arg));
1241 }
Caroline Tice44c841d2010-12-07 19:58:26 +00001242 ReplaceArgumentAtIndex (idx, "");
1243 if ((long_options[long_options_index].has_arg != no_argument)
1244 && (optarg != NULL)
1245 && (idx+1 < GetArgumentCount())
1246 && (strcmp (optarg, GetArgumentAtIndex(idx+1)) == 0))
Caroline Ticee0da7a52010-12-09 22:52:49 +00001247 {
1248 if (raw_input_string.size() > 0)
1249 {
1250 const char *tmp_arg = GetArgumentAtIndex (idx+1);
1251 size_t pos = raw_input_string.find (tmp_arg);
1252 if (pos != std::string::npos)
1253 raw_input_string.erase (pos, strlen (tmp_arg));
1254 }
Caroline Tice44c841d2010-12-07 19:58:26 +00001255 ReplaceArgumentAtIndex (idx+1, "");
Caroline Ticee0da7a52010-12-09 22:52:49 +00001256 }
Caroline Tice44c841d2010-12-07 19:58:26 +00001257 }
Caroline Tice5e0894e2010-10-12 17:45:19 +00001258 }
1259
Chris Lattner24943d22010-06-08 16:52:24 +00001260 if (!result.Succeeded())
1261 break;
1262 }
1263}
1264
1265void
1266Args::ParseArgsForCompletion
1267(
1268 Options &options,
Jim Inghamadb84292010-06-24 20:31:04 +00001269 OptionElementVector &option_element_vector,
1270 uint32_t cursor_index
Chris Lattner24943d22010-06-08 16:52:24 +00001271)
1272{
1273 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001274 struct option *long_options = options.GetLongOptions();
1275 option_element_vector.clear();
1276
1277 if (long_options == NULL)
1278 {
1279 return;
1280 }
1281
1282 // Leading : tells getopt to return a : for a missing option argument AND
1283 // to suppress error messages.
1284
1285 sstr << ":";
Greg Claytonbef15832010-07-14 00:18:15 +00001286 for (int i = 0; long_options[i].name != NULL; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001287 {
1288 if (long_options[i].flag == NULL)
1289 {
1290 sstr << (char) long_options[i].val;
1291 switch (long_options[i].has_arg)
1292 {
1293 default:
1294 case no_argument:
1295 break;
1296 case required_argument:
1297 sstr << ":";
1298 break;
1299 case optional_argument:
1300 sstr << "::";
1301 break;
1302 }
1303 }
1304 }
1305
Eli Friedmanef2bc872010-06-13 19:18:49 +00001306#ifdef __GLIBC__
1307 optind = 0;
1308#else
Chris Lattner24943d22010-06-08 16:52:24 +00001309 optreset = 1;
1310 optind = 1;
Eli Friedmanef2bc872010-06-13 19:18:49 +00001311#endif
Chris Lattner24943d22010-06-08 16:52:24 +00001312 opterr = 0;
1313
1314 int val;
1315 const OptionDefinition *opt_defs = options.GetDefinitions();
1316
Jim Inghamadb84292010-06-24 20:31:04 +00001317 // Fooey... getopt_long permutes the GetArgumentVector to move the options to the front.
Chris Lattner24943d22010-06-08 16:52:24 +00001318 // So we have to build another Arg and pass that to getopt_long so it doesn't
Jim Inghamadb84292010-06-24 20:31:04 +00001319 // change the one we have.
Chris Lattner24943d22010-06-08 16:52:24 +00001320
Greg Clayton54e7afa2010-07-09 20:39:50 +00001321 std::vector<const char *> dummy_vec (GetArgumentVector(), GetArgumentVector() + GetArgumentCount() + 1);
Chris Lattner24943d22010-06-08 16:52:24 +00001322
Jim Inghamadb84292010-06-24 20:31:04 +00001323 bool failed_once = false;
1324 uint32_t dash_dash_pos = -1;
1325
Chris Lattner24943d22010-06-08 16:52:24 +00001326 while (1)
1327 {
1328 bool missing_argument = false;
1329 int parse_start = optind;
1330 int long_options_index = -1;
Jim Inghamadb84292010-06-24 20:31:04 +00001331
Greg Clayton54e7afa2010-07-09 20:39:50 +00001332 val = ::getopt_long (dummy_vec.size() - 1,
Greg Clayton53d68e72010-07-20 22:52:08 +00001333 (char *const *) &dummy_vec.front(),
Greg Clayton54e7afa2010-07-09 20:39:50 +00001334 sstr.GetData(),
1335 long_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001336 &long_options_index);
1337
1338 if (val == -1)
Jim Inghamadb84292010-06-24 20:31:04 +00001339 {
1340 // When we're completing a "--" which is the last option on line,
1341 if (failed_once)
1342 break;
1343
1344 failed_once = true;
1345
1346 // If this is a bare "--" we mark it as such so we can complete it successfully later.
1347 // Handling the "--" is a little tricky, since that may mean end of options or arguments, or the
1348 // user might want to complete options by long name. I make this work by checking whether the
1349 // cursor is in the "--" argument, and if so I assume we're completing the long option, otherwise
1350 // I let it pass to getopt_long which will terminate the option parsing.
1351 // Note, in either case we continue parsing the line so we can figure out what other options
1352 // were passed. This will be useful when we come to restricting completions based on what other
1353 // options we've seen on the line.
Chris Lattner24943d22010-06-08 16:52:24 +00001354
Jim Inghamadb84292010-06-24 20:31:04 +00001355 if (optind < dummy_vec.size() - 1
1356 && (strcmp (dummy_vec[optind-1], "--") == 0))
1357 {
1358 dash_dash_pos = optind - 1;
1359 if (optind - 1 == cursor_index)
1360 {
1361 option_element_vector.push_back (OptionArgElement (OptionArgElement::eBareDoubleDash, optind - 1,
1362 OptionArgElement::eBareDoubleDash));
1363 continue;
1364 }
1365 else
1366 break;
1367 }
1368 else
1369 break;
1370 }
Chris Lattner24943d22010-06-08 16:52:24 +00001371 else if (val == '?')
1372 {
Jim Inghamadb84292010-06-24 20:31:04 +00001373 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1374 OptionArgElement::eUnrecognizedArg));
Chris Lattner24943d22010-06-08 16:52:24 +00001375 continue;
1376 }
1377 else if (val == 0)
1378 {
1379 continue;
1380 }
1381 else if (val == ':')
1382 {
1383 // This is a missing argument.
1384 val = optopt;
1385 missing_argument = true;
1386 }
1387
1388 ((Options *) &options)->OptionSeen (val);
1389
1390 // Look up the long option index
1391 if (long_options_index == -1)
1392 {
1393 for (int j = 0;
1394 long_options[j].name || long_options[j].has_arg || long_options[j].flag || long_options[j].val;
1395 ++j)
1396 {
1397 if (long_options[j].val == val)
1398 {
1399 long_options_index = j;
1400 break;
1401 }
1402 }
1403 }
1404
1405 // See if the option takes an argument, and see if one was supplied.
1406 if (long_options_index >= 0)
1407 {
1408 int opt_defs_index = -1;
1409 for (int i = 0; ; i++)
1410 {
1411 if (opt_defs[i].short_option == 0)
1412 break;
1413 else if (opt_defs[i].short_option == val)
1414 {
1415 opt_defs_index = i;
1416 break;
1417 }
1418 }
1419
1420 switch (long_options[long_options_index].has_arg)
1421 {
1422 case no_argument:
1423 option_element_vector.push_back (OptionArgElement (opt_defs_index, parse_start, 0));
1424 break;
1425 case required_argument:
1426 if (optarg != NULL)
1427 {
1428 int arg_index;
1429 if (missing_argument)
1430 arg_index = -1;
1431 else
Jim Inghamadb84292010-06-24 20:31:04 +00001432 arg_index = optind - 1;
Chris Lattner24943d22010-06-08 16:52:24 +00001433
Jim Inghamadb84292010-06-24 20:31:04 +00001434 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, arg_index));
Chris Lattner24943d22010-06-08 16:52:24 +00001435 }
1436 else
1437 {
Jim Inghamadb84292010-06-24 20:31:04 +00001438 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 1, -1));
Chris Lattner24943d22010-06-08 16:52:24 +00001439 }
1440 break;
1441 case optional_argument:
1442 if (optarg != NULL)
1443 {
Jim Inghamadb84292010-06-24 20:31:04 +00001444 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, optind - 1));
Chris Lattner24943d22010-06-08 16:52:24 +00001445 }
1446 else
1447 {
Jim Inghamadb84292010-06-24 20:31:04 +00001448 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, optind - 1));
Chris Lattner24943d22010-06-08 16:52:24 +00001449 }
1450 break;
1451 default:
1452 // The options table is messed up. Here we'll just continue
Jim Inghamadb84292010-06-24 20:31:04 +00001453 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1454 OptionArgElement::eUnrecognizedArg));
Chris Lattner24943d22010-06-08 16:52:24 +00001455 break;
1456 }
1457 }
1458 else
1459 {
Jim Inghamadb84292010-06-24 20:31:04 +00001460 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1461 OptionArgElement::eUnrecognizedArg));
Chris Lattner24943d22010-06-08 16:52:24 +00001462 }
1463 }
Jim Inghamadb84292010-06-24 20:31:04 +00001464
1465 // Finally we have to handle the case where the cursor index points at a single "-". We want to mark that in
1466 // the option_element_vector, but only if it is not after the "--". But it turns out that getopt_long just ignores
1467 // an isolated "-". So we have to look it up by hand here. We only care if it is AT the cursor position.
1468
1469 if ((dash_dash_pos == -1 || cursor_index < dash_dash_pos)
1470 && strcmp (GetArgumentAtIndex(cursor_index), "-") == 0)
1471 {
1472 option_element_vector.push_back (OptionArgElement (OptionArgElement::eBareDash, cursor_index,
1473 OptionArgElement::eBareDash));
1474
1475 }
Chris Lattner24943d22010-06-08 16:52:24 +00001476}