blob: a6eb1f01bef4491e62c23cabbbdae3f9db20fd6c [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:
233 arg_pos = arg_end + 2;
234 break;
235 }
236 break;
237
238 case '"':
239 case '\'':
240 case '`':
241 // Quote characters
242 if (quote_char)
243 {
244 // We found a quote character while inside a quoted
245 // character argument. If it matches our current quote
246 // character, this ends the effect of the quotes. If it
247 // doesn't we ignore it.
248 if (quote_char == arg_end[0])
Chris Lattner24943d22010-06-08 16:52:24 +0000249 {
Greg Clayton928d1302010-12-19 03:41:24 +0000250 arg.append (arg_piece_start, arg_end - arg_piece_start);
251 // Clear the quote character and let parsing
252 // continue (we need to watch for things like:
253 // "Hello ""World"
254 // "Hello "World
255 // "Hello "'World'
256 // All of which will result in a single argument "Hello World"
257 quote_char = '\0'; // Note that we are no longer inside quotes
258 arg_pos = arg_end + 1; // Skip the quote character
259 arg_piece_start = arg_pos; // Note we are starting from later in the string
260 }
261 else
262 {
263 // different quote, skip it and keep going
264 arg_pos = arg_end + 1;
265 }
266 }
267 else
268 {
269 // We found the start of a quote scope.
Greg Clayton5d187e52011-01-08 20:28:42 +0000270 // Make sure there isn't a string that precedes
Greg Clayton928d1302010-12-19 03:41:24 +0000271 // the start of a quote scope like:
272 // Hello" World"
273 // If so, then add the "Hello" to the arg
274 if (arg_end > arg_piece_start)
275 arg.append (arg_piece_start, arg_end - arg_piece_start);
276
277 // Enter into a quote scope
278 quote_char = arg_end[0];
279
280 if (first_quote_char == '\0')
281 first_quote_char = quote_char;
282
283 arg_pos = arg_end;
Johnny Chena1b0ce12012-01-19 19:22:41 +0000284 ++arg_pos; // Skip the quote character
Greg Clayton928d1302010-12-19 03:41:24 +0000285 arg_piece_start = arg_pos; // Note we are starting from later in the string
286
287 // Skip till the next quote character
288 const char *end_quote = ::strchr (arg_piece_start, quote_char);
289 while (end_quote && end_quote[-1] == '\\')
290 {
291 // Don't skip the quote character if it is
292 // preceded by a '\' character
293 end_quote = ::strchr (end_quote + 1, quote_char);
294 }
295
296 if (end_quote)
297 {
298 if (end_quote > arg_piece_start)
Johnny Chena1b0ce12012-01-19 19:22:41 +0000299 arg.append (arg_piece_start, end_quote - arg_piece_start);
Greg Clayton928d1302010-12-19 03:41:24 +0000300
301 // If the next character is a space or the end of
302 // string, this argument is complete...
303 if (end_quote[1] == ' ' || end_quote[1] == '\t' || end_quote[1] == '\0')
304 {
305 arg_complete = true;
306 arg_end = end_quote + 1;
Chris Lattner24943d22010-06-08 16:52:24 +0000307 }
308 else
309 {
Greg Clayton928d1302010-12-19 03:41:24 +0000310 arg_pos = end_quote + 1;
311 arg_piece_start = arg_pos;
Chris Lattner24943d22010-06-08 16:52:24 +0000312 }
Greg Clayton928d1302010-12-19 03:41:24 +0000313 quote_char = '\0';
Chris Lattner24943d22010-06-08 16:52:24 +0000314 }
Greg Clayton03e498e2012-03-15 17:10:48 +0000315 else
316 {
317 // Consume the rest of the string as there was no terminating quote
318 arg.append(arg_piece_start);
319 arg_end = arg_piece_start + strlen(arg_piece_start);
320 arg_complete = true;
321 }
Chris Lattner24943d22010-06-08 16:52:24 +0000322 }
Greg Clayton928d1302010-12-19 03:41:24 +0000323 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000324
Greg Clayton928d1302010-12-19 03:41:24 +0000325 case ' ':
326 case '\t':
327 if (quote_char)
Chris Lattner24943d22010-06-08 16:52:24 +0000328 {
Greg Clayton928d1302010-12-19 03:41:24 +0000329 // We are currently processing a quoted character and found
330 // a space character, skip any spaces and keep trying to find
331 // the end of the argument.
332 arg_pos = ::strspn (arg_end, k_space_separators) + arg_end;
Chris Lattner24943d22010-06-08 16:52:24 +0000333 }
Greg Clayton928d1302010-12-19 03:41:24 +0000334 else
Chris Lattner24943d22010-06-08 16:52:24 +0000335 {
Greg Clayton928d1302010-12-19 03:41:24 +0000336 // We are not inside any quotes, we just found a space after an
337 // argument
338 if (arg_end > arg_piece_start)
339 arg.append (arg_piece_start, arg_end - arg_piece_start);
340 arg_complete = true;
Chris Lattner24943d22010-06-08 16:52:24 +0000341 }
Greg Clayton928d1302010-12-19 03:41:24 +0000342 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000343 }
Greg Clayton928d1302010-12-19 03:41:24 +0000344 } while (!arg_complete);
Chris Lattner24943d22010-06-08 16:52:24 +0000345
346 m_args.push_back(arg);
Greg Clayton928d1302010-12-19 03:41:24 +0000347 m_args_quote_char.push_back (first_quote_char);
Chris Lattner24943d22010-06-08 16:52:24 +0000348 }
Greg Clayton928d1302010-12-19 03:41:24 +0000349 UpdateArgvFromArgs();
Chris Lattner24943d22010-06-08 16:52:24 +0000350 }
Chris Lattner24943d22010-06-08 16:52:24 +0000351}
352
353void
354Args::UpdateArgsAfterOptionParsing()
355{
356 // Now m_argv might be out of date with m_args, so we need to fix that
357 arg_cstr_collection::const_iterator argv_pos, argv_end = m_argv.end();
358 arg_sstr_collection::iterator args_pos;
359 arg_quote_char_collection::iterator quotes_pos;
360
361 for (argv_pos = m_argv.begin(), args_pos = m_args.begin(), quotes_pos = m_args_quote_char.begin();
362 argv_pos != argv_end && args_pos != m_args.end();
363 ++argv_pos)
364 {
365 const char *argv_cstr = *argv_pos;
366 if (argv_cstr == NULL)
367 break;
368
369 while (args_pos != m_args.end())
370 {
371 const char *args_cstr = args_pos->c_str();
372 if (args_cstr == argv_cstr)
373 {
374 // We found the argument that matches the C string in the
375 // vector, so we can now look for the next one
376 ++args_pos;
377 ++quotes_pos;
378 break;
379 }
380 else
381 {
382 quotes_pos = m_args_quote_char.erase (quotes_pos);
383 args_pos = m_args.erase (args_pos);
384 }
385 }
386 }
387
388 if (args_pos != m_args.end())
389 m_args.erase (args_pos, m_args.end());
390
391 if (quotes_pos != m_args_quote_char.end())
392 m_args_quote_char.erase (quotes_pos, m_args_quote_char.end());
393}
394
395void
396Args::UpdateArgvFromArgs()
397{
398 m_argv.clear();
399 arg_sstr_collection::const_iterator pos, end = m_args.end();
400 for (pos = m_args.begin(); pos != end; ++pos)
401 m_argv.push_back(pos->c_str());
402 m_argv.push_back(NULL);
Greg Clayton928d1302010-12-19 03:41:24 +0000403 // Make sure we have enough arg quote chars in the array
404 if (m_args_quote_char.size() < m_args.size())
405 m_args_quote_char.resize (m_argv.size());
Chris Lattner24943d22010-06-08 16:52:24 +0000406}
407
408size_t
409Args::GetArgumentCount() const
410{
411 if (m_argv.empty())
412 return 0;
413 return m_argv.size() - 1;
414}
415
416const char *
417Args::GetArgumentAtIndex (size_t idx) const
418{
419 if (idx < m_argv.size())
420 return m_argv[idx];
421 return NULL;
422}
423
424char
425Args::GetArgumentQuoteCharAtIndex (size_t idx) const
426{
427 if (idx < m_args_quote_char.size())
428 return m_args_quote_char[idx];
429 return '\0';
430}
431
432char **
433Args::GetArgumentVector()
434{
435 if (!m_argv.empty())
436 return (char **)&m_argv[0];
437 return NULL;
438}
439
440const char **
441Args::GetConstArgumentVector() const
442{
443 if (!m_argv.empty())
444 return (const char **)&m_argv[0];
445 return NULL;
446}
447
448void
449Args::Shift ()
450{
451 // Don't pop the last NULL terminator from the argv array
452 if (m_argv.size() > 1)
453 {
454 m_argv.erase(m_argv.begin());
455 m_args.pop_front();
Greg Clayton928d1302010-12-19 03:41:24 +0000456 if (!m_args_quote_char.empty())
457 m_args_quote_char.erase(m_args_quote_char.begin());
Chris Lattner24943d22010-06-08 16:52:24 +0000458 }
459}
460
461const char *
462Args::Unshift (const char *arg_cstr, char quote_char)
463{
464 m_args.push_front(arg_cstr);
465 m_argv.insert(m_argv.begin(), m_args.front().c_str());
466 m_args_quote_char.insert(m_args_quote_char.begin(), quote_char);
467 return GetArgumentAtIndex (0);
468}
469
470void
471Args::AppendArguments (const Args &rhs)
472{
473 const size_t rhs_argc = rhs.GetArgumentCount();
474 for (size_t i=0; i<rhs_argc; ++i)
475 AppendArgument(rhs.GetArgumentAtIndex(i));
476}
477
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000478void
479Args::AppendArguments (const char **argv)
480{
481 if (argv)
482 {
483 for (uint32_t i=0; argv[i]; ++i)
484 AppendArgument(argv[i]);
485 }
486}
487
Chris Lattner24943d22010-06-08 16:52:24 +0000488const char *
489Args::AppendArgument (const char *arg_cstr, char quote_char)
490{
491 return InsertArgumentAtIndex (GetArgumentCount(), arg_cstr, quote_char);
492}
493
494const char *
495Args::InsertArgumentAtIndex (size_t idx, const char *arg_cstr, char quote_char)
496{
497 // Since we are using a std::list to hold onto the copied C string and
498 // we don't have direct access to the elements, we have to iterate to
499 // find the value.
500 arg_sstr_collection::iterator pos, end = m_args.end();
501 size_t i = idx;
502 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
503 --i;
504
505 pos = m_args.insert(pos, arg_cstr);
506
Greg Clayton928d1302010-12-19 03:41:24 +0000507 if (idx >= m_args_quote_char.size())
508 {
509 m_args_quote_char.resize(idx + 1);
510 m_args_quote_char[idx] = quote_char;
511 }
512 else
513 m_args_quote_char.insert(m_args_quote_char.begin() + idx, quote_char);
Chris Lattner24943d22010-06-08 16:52:24 +0000514
515 UpdateArgvFromArgs();
516 return GetArgumentAtIndex(idx);
517}
518
519const char *
520Args::ReplaceArgumentAtIndex (size_t idx, const char *arg_cstr, char quote_char)
521{
522 // Since we are using a std::list to hold onto the copied C string and
523 // we don't have direct access to the elements, we have to iterate to
524 // find the value.
525 arg_sstr_collection::iterator pos, end = m_args.end();
526 size_t i = idx;
527 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
528 --i;
529
530 if (pos != end)
531 {
532 pos->assign(arg_cstr);
533 assert(idx < m_argv.size() - 1);
534 m_argv[idx] = pos->c_str();
Greg Clayton928d1302010-12-19 03:41:24 +0000535 if (idx >= m_args_quote_char.size())
536 m_args_quote_char.resize(idx + 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000537 m_args_quote_char[idx] = quote_char;
538 return GetArgumentAtIndex(idx);
539 }
540 return NULL;
541}
542
543void
544Args::DeleteArgumentAtIndex (size_t idx)
545{
546 // Since we are using a std::list to hold onto the copied C string and
547 // we don't have direct access to the elements, we have to iterate to
548 // find the value.
549 arg_sstr_collection::iterator pos, end = m_args.end();
550 size_t i = idx;
551 for (pos = m_args.begin(); i > 0 && pos != end; ++pos)
552 --i;
553
554 if (pos != end)
555 {
556 m_args.erase (pos);
557 assert(idx < m_argv.size() - 1);
558 m_argv.erase(m_argv.begin() + idx);
Greg Clayton928d1302010-12-19 03:41:24 +0000559 if (idx < m_args_quote_char.size())
560 m_args_quote_char.erase(m_args_quote_char.begin() + idx);
Chris Lattner24943d22010-06-08 16:52:24 +0000561 }
562}
563
564void
565Args::SetArguments (int argc, const char **argv)
566{
567 // m_argv will be rebuilt in UpdateArgvFromArgs() below, so there is
568 // no need to clear it here.
569 m_args.clear();
570 m_args_quote_char.clear();
571
Chris Lattner24943d22010-06-08 16:52:24 +0000572 // First copy each string
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000573 for (size_t i=0; i<argc; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +0000574 {
575 m_args.push_back (argv[i]);
Greg Clayton928d1302010-12-19 03:41:24 +0000576 if ((argv[i][0] == '\'') || (argv[i][0] == '"') || (argv[i][0] == '`'))
Chris Lattner24943d22010-06-08 16:52:24 +0000577 m_args_quote_char.push_back (argv[i][0]);
578 else
579 m_args_quote_char.push_back ('\0');
580 }
581
582 UpdateArgvFromArgs();
583}
584
Greg Clayton36bc5ea2011-11-03 21:22:33 +0000585void
586Args::SetArguments (const char **argv)
587{
588 // m_argv will be rebuilt in UpdateArgvFromArgs() below, so there is
589 // no need to clear it here.
590 m_args.clear();
591 m_args_quote_char.clear();
592
593 if (argv)
594 {
595 // First copy each string
596 for (size_t i=0; argv[i]; ++i)
597 {
598 m_args.push_back (argv[i]);
599 if ((argv[i][0] == '\'') || (argv[i][0] == '"') || (argv[i][0] == '`'))
600 m_args_quote_char.push_back (argv[i][0]);
601 else
602 m_args_quote_char.push_back ('\0');
603 }
604 }
605
606 UpdateArgvFromArgs();
607}
608
Chris Lattner24943d22010-06-08 16:52:24 +0000609
610Error
611Args::ParseOptions (Options &options)
612{
613 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +0000614 Error error;
615 struct option *long_options = options.GetLongOptions();
616 if (long_options == NULL)
617 {
Greg Clayton9c236732011-10-26 00:56:27 +0000618 error.SetErrorStringWithFormat("invalid long options");
Chris Lattner24943d22010-06-08 16:52:24 +0000619 return error;
620 }
621
Greg Claytonbef15832010-07-14 00:18:15 +0000622 for (int i=0; long_options[i].name != NULL; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +0000623 {
624 if (long_options[i].flag == NULL)
625 {
626 sstr << (char)long_options[i].val;
627 switch (long_options[i].has_arg)
628 {
629 default:
630 case no_argument: break;
631 case required_argument: sstr << ':'; break;
632 case optional_argument: sstr << "::"; break;
633 }
634 }
635 }
Eli Friedmanef2bc872010-06-13 19:18:49 +0000636#ifdef __GLIBC__
637 optind = 0;
638#else
Chris Lattner24943d22010-06-08 16:52:24 +0000639 optreset = 1;
640 optind = 1;
Eli Friedmanef2bc872010-06-13 19:18:49 +0000641#endif
Chris Lattner24943d22010-06-08 16:52:24 +0000642 int val;
643 while (1)
644 {
645 int long_options_index = -1;
646 val = ::getopt_long(GetArgumentCount(), GetArgumentVector(), sstr.GetData(), long_options,
647 &long_options_index);
648 if (val == -1)
649 break;
650
651 // Did we get an error?
652 if (val == '?')
653 {
Greg Clayton9c236732011-10-26 00:56:27 +0000654 error.SetErrorStringWithFormat("unknown or ambiguous option");
Chris Lattner24943d22010-06-08 16:52:24 +0000655 break;
656 }
657 // The option auto-set itself
658 if (val == 0)
659 continue;
660
661 ((Options *) &options)->OptionSeen (val);
662
663 // Lookup the long option index
664 if (long_options_index == -1)
665 {
666 for (int i=0;
667 long_options[i].name || long_options[i].has_arg || long_options[i].flag || long_options[i].val;
668 ++i)
669 {
670 if (long_options[i].val == val)
671 {
672 long_options_index = i;
673 break;
674 }
675 }
676 }
677 // Call the callback with the option
678 if (long_options_index >= 0)
679 {
680 error = options.SetOptionValue(long_options_index,
681 long_options[long_options_index].has_arg == no_argument ? NULL : optarg);
682 }
683 else
684 {
Greg Clayton9c236732011-10-26 00:56:27 +0000685 error.SetErrorStringWithFormat("invalid option with value '%i'", val);
Chris Lattner24943d22010-06-08 16:52:24 +0000686 }
687 if (error.Fail())
688 break;
689 }
690
691 // Update our ARGV now that get options has consumed all the options
692 m_argv.erase(m_argv.begin(), m_argv.begin() + optind);
693 UpdateArgsAfterOptionParsing ();
694 return error;
695}
696
697void
698Args::Clear ()
699{
700 m_args.clear ();
701 m_argv.clear ();
702 m_args_quote_char.clear();
703}
704
705int32_t
706Args::StringToSInt32 (const char *s, int32_t fail_value, int base, bool *success_ptr)
707{
708 if (s && s[0])
709 {
710 char *end = NULL;
711 int32_t uval = ::strtol (s, &end, base);
712 if (*end == '\0')
713 {
714 if (success_ptr) *success_ptr = true;
715 return uval; // All characters were used, return the result
716 }
717 }
718 if (success_ptr) *success_ptr = false;
719 return fail_value;
720}
721
722uint32_t
723Args::StringToUInt32 (const char *s, uint32_t fail_value, int base, bool *success_ptr)
724{
725 if (s && s[0])
726 {
727 char *end = NULL;
728 uint32_t uval = ::strtoul (s, &end, base);
729 if (*end == '\0')
730 {
731 if (success_ptr) *success_ptr = true;
732 return uval; // All characters were used, return the result
733 }
734 }
735 if (success_ptr) *success_ptr = false;
736 return fail_value;
737}
738
739
740int64_t
741Args::StringToSInt64 (const char *s, int64_t fail_value, int base, bool *success_ptr)
742{
743 if (s && s[0])
744 {
745 char *end = NULL;
746 int64_t uval = ::strtoll (s, &end, base);
747 if (*end == '\0')
748 {
749 if (success_ptr) *success_ptr = true;
750 return uval; // All characters were used, return the result
751 }
752 }
753 if (success_ptr) *success_ptr = false;
754 return fail_value;
755}
756
757uint64_t
758Args::StringToUInt64 (const char *s, uint64_t fail_value, int base, bool *success_ptr)
759{
760 if (s && s[0])
761 {
762 char *end = NULL;
763 uint64_t uval = ::strtoull (s, &end, base);
764 if (*end == '\0')
765 {
766 if (success_ptr) *success_ptr = true;
767 return uval; // All characters were used, return the result
768 }
769 }
770 if (success_ptr) *success_ptr = false;
771 return fail_value;
772}
773
774lldb::addr_t
775Args::StringToAddress (const char *s, lldb::addr_t fail_value, bool *success_ptr)
776{
777 if (s && s[0])
778 {
779 char *end = NULL;
780 lldb::addr_t addr = ::strtoull (s, &end, 0);
781 if (*end == '\0')
782 {
783 if (success_ptr) *success_ptr = true;
784 return addr; // All characters were used, return the result
785 }
786 // Try base 16 with no prefix...
787 addr = ::strtoull (s, &end, 16);
788 if (*end == '\0')
789 {
790 if (success_ptr) *success_ptr = true;
791 return addr; // All characters were used, return the result
792 }
793 }
794 if (success_ptr) *success_ptr = false;
795 return fail_value;
796}
797
798bool
799Args::StringToBoolean (const char *s, bool fail_value, bool *success_ptr)
800{
801 if (s && s[0])
802 {
803 if (::strcasecmp (s, "false") == 0 ||
804 ::strcasecmp (s, "off") == 0 ||
805 ::strcasecmp (s, "no") == 0 ||
806 ::strcmp (s, "0") == 0)
807 {
808 if (success_ptr)
809 *success_ptr = true;
810 return false;
811 }
812 else
813 if (::strcasecmp (s, "true") == 0 ||
814 ::strcasecmp (s, "on") == 0 ||
815 ::strcasecmp (s, "yes") == 0 ||
816 ::strcmp (s, "1") == 0)
817 {
818 if (success_ptr) *success_ptr = true;
819 return true;
820 }
821 }
822 if (success_ptr) *success_ptr = false;
823 return fail_value;
824}
825
Greg Claytonb1888f22011-03-19 01:12:21 +0000826const char *
827Args::StringToVersion (const char *s, uint32_t &major, uint32_t &minor, uint32_t &update)
828{
829 major = UINT32_MAX;
830 minor = UINT32_MAX;
831 update = UINT32_MAX;
832
833 if (s && s[0])
834 {
835 char *pos = NULL;
836 uint32_t uval32;
837 uval32 = ::strtoul (s, &pos, 0);
838 if (pos == s)
839 return s;
840 major = uval32;
841 if (*pos == '\0')
842 {
843 return pos; // Decoded major and got end of string
844 }
845 else if (*pos == '.')
846 {
847 const char *minor_cstr = pos + 1;
848 uval32 = ::strtoul (minor_cstr, &pos, 0);
849 if (pos == minor_cstr)
850 return pos; // Didn't get any digits for the minor version...
851 minor = uval32;
852 if (*pos == '.')
853 {
854 const char *update_cstr = pos + 1;
855 uval32 = ::strtoul (update_cstr, &pos, 0);
856 if (pos == update_cstr)
857 return pos;
858 update = uval32;
859 }
860 return pos;
861 }
862 }
863 return 0;
864}
865
Greg Clayton527154d2011-11-15 03:53:30 +0000866const char *
867Args::GetShellSafeArgument (const char *unsafe_arg, std::string &safe_arg)
868{
869 safe_arg.assign (unsafe_arg);
870 size_t prev_pos = 0;
871 while (prev_pos < safe_arg.size())
872 {
873 // Escape spaces and quotes
874 size_t pos = safe_arg.find_first_of(" '\"", prev_pos);
875 if (pos != std::string::npos)
876 {
877 safe_arg.insert (pos, 1, '\\');
878 prev_pos = pos + 2;
879 }
880 else
881 break;
882 }
883 return safe_arg.c_str();
884}
885
Greg Claytonb1888f22011-03-19 01:12:21 +0000886
Chris Lattner24943d22010-06-08 16:52:24 +0000887int32_t
Greg Clayton61aca5d2011-10-07 18:58:12 +0000888Args::StringToOptionEnum (const char *s, OptionEnumValueElement *enum_values, int32_t fail_value, Error &error)
Chris Lattner24943d22010-06-08 16:52:24 +0000889{
Greg Clayton61aca5d2011-10-07 18:58:12 +0000890 if (enum_values)
Chris Lattner24943d22010-06-08 16:52:24 +0000891 {
Greg Clayton61aca5d2011-10-07 18:58:12 +0000892 if (s && s[0])
Chris Lattner24943d22010-06-08 16:52:24 +0000893 {
Greg Clayton61aca5d2011-10-07 18:58:12 +0000894 for (int i = 0; enum_values[i].string_value != NULL ; i++)
Chris Lattner24943d22010-06-08 16:52:24 +0000895 {
Greg Clayton61aca5d2011-10-07 18:58:12 +0000896 if (strstr(enum_values[i].string_value, s) == enum_values[i].string_value)
897 {
898 error.Clear();
899 return enum_values[i].value;
900 }
Chris Lattner24943d22010-06-08 16:52:24 +0000901 }
902 }
Greg Clayton61aca5d2011-10-07 18:58:12 +0000903
904 StreamString strm;
905 strm.PutCString ("invalid enumeration value, valid values are: ");
906 for (int i = 0; enum_values[i].string_value != NULL; i++)
907 {
908 strm.Printf ("%s\"%s\"",
909 i > 0 ? ", " : "",
910 enum_values[i].string_value);
911 }
912 error.SetErrorString(strm.GetData());
Chris Lattner24943d22010-06-08 16:52:24 +0000913 }
Greg Clayton61aca5d2011-10-07 18:58:12 +0000914 else
915 {
916 error.SetErrorString ("invalid enumeration argument");
917 }
Chris Lattner24943d22010-06-08 16:52:24 +0000918 return fail_value;
919}
920
921ScriptLanguage
922Args::StringToScriptLanguage (const char *s, ScriptLanguage fail_value, bool *success_ptr)
923{
924 if (s && s[0])
925 {
926 if ((::strcasecmp (s, "python") == 0) ||
927 (::strcasecmp (s, "default") == 0 && eScriptLanguagePython == eScriptLanguageDefault))
928 {
929 if (success_ptr) *success_ptr = true;
930 return eScriptLanguagePython;
931 }
932 if (::strcasecmp (s, "none"))
933 {
934 if (success_ptr) *success_ptr = true;
935 return eScriptLanguageNone;
936 }
937 }
938 if (success_ptr) *success_ptr = false;
939 return fail_value;
940}
941
942Error
943Args::StringToFormat
944(
945 const char *s,
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000946 lldb::Format &format,
947 uint32_t *byte_size_ptr
Chris Lattner24943d22010-06-08 16:52:24 +0000948)
949{
950 format = eFormatInvalid;
951 Error error;
952
953 if (s && s[0])
954 {
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000955 if (byte_size_ptr)
Chris Lattner24943d22010-06-08 16:52:24 +0000956 {
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000957 if (isdigit (s[0]))
958 {
959 char *format_char = NULL;
960 unsigned long byte_size = ::strtoul (s, &format_char, 0);
961 if (byte_size != ULONG_MAX)
962 *byte_size_ptr = byte_size;
963 s = format_char;
964 }
965 else
966 *byte_size_ptr = 0;
967 }
968
Greg Clayton3182eff2011-06-23 21:22:24 +0000969 const bool partial_match_ok = true;
970 if (!FormatManager::GetFormatFromCString (s, partial_match_ok, format))
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000971 {
Greg Clayton3182eff2011-06-23 21:22:24 +0000972 StreamString error_strm;
973 error_strm.Printf ("Invalid format character or name '%s'. Valid values are:\n", s);
Peter Collingbournef4d4fcc2011-06-24 01:12:22 +0000974 for (Format f = eFormatDefault; f < kNumFormats; f = Format(f+1))
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000975 {
Greg Clayton3182eff2011-06-23 21:22:24 +0000976 char format_char = FormatManager::GetFormatAsFormatChar(f);
977 if (format_char)
978 error_strm.Printf ("'%c' or ", format_char);
979
980 error_strm.Printf ("\"%s\"", FormatManager::GetFormatAsCString(f));
981 error_strm.EOL();
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000982 }
Greg Clayton3182eff2011-06-23 21:22:24 +0000983
984 if (byte_size_ptr)
985 error_strm.PutCString ("An optional byte size can precede the format character.\n");
986 error.SetErrorString(error_strm.GetString().c_str());
Greg Clayton56bbdaf2011-04-28 20:55:26 +0000987 }
Chris Lattner24943d22010-06-08 16:52:24 +0000988
989 if (error.Fail())
990 return error;
991 }
992 else
993 {
Greg Clayton9c236732011-10-26 00:56:27 +0000994 error.SetErrorStringWithFormat("%s option string", s ? "empty" : "invalid");
Chris Lattner24943d22010-06-08 16:52:24 +0000995 }
996 return error;
997}
998
999void
1000Args::LongestCommonPrefix (std::string &common_prefix)
1001{
1002 arg_sstr_collection::iterator pos, end = m_args.end();
1003 pos = m_args.begin();
1004 if (pos == end)
1005 common_prefix.clear();
1006 else
1007 common_prefix = (*pos);
1008
1009 for (++pos; pos != end; ++pos)
1010 {
Greg Clayton54e7afa2010-07-09 20:39:50 +00001011 size_t new_size = (*pos).size();
Chris Lattner24943d22010-06-08 16:52:24 +00001012
1013 // First trim common_prefix if it is longer than the current element:
1014 if (common_prefix.size() > new_size)
1015 common_prefix.erase (new_size);
1016
1017 // Then trim it at the first disparity:
1018
Greg Clayton54e7afa2010-07-09 20:39:50 +00001019 for (size_t i = 0; i < common_prefix.size(); i++)
Chris Lattner24943d22010-06-08 16:52:24 +00001020 {
1021 if ((*pos)[i] != common_prefix[i])
1022 {
1023 common_prefix.erase(i);
1024 break;
1025 }
1026 }
1027
1028 // If we've emptied the common prefix, we're done.
1029 if (common_prefix.empty())
1030 break;
1031 }
1032}
1033
Caroline Tice44c841d2010-12-07 19:58:26 +00001034size_t
1035Args::FindArgumentIndexForOption (struct option *long_options, int long_options_index)
1036{
1037 char short_buffer[3];
1038 char long_buffer[255];
1039 ::snprintf (short_buffer, sizeof (short_buffer), "-%c", (char) long_options[long_options_index].val);
1040 ::snprintf (long_buffer, sizeof (long_buffer), "--%s", long_options[long_options_index].name);
1041 size_t end = GetArgumentCount ();
1042 size_t idx = 0;
1043 while (idx < end)
1044 {
1045 if ((::strncmp (GetArgumentAtIndex (idx), short_buffer, strlen (short_buffer)) == 0)
1046 || (::strncmp (GetArgumentAtIndex (idx), long_buffer, strlen (long_buffer)) == 0))
1047 {
1048 return idx;
1049 }
1050 ++idx;
1051 }
1052
1053 return end;
1054}
1055
1056bool
1057Args::IsPositionalArgument (const char *arg)
1058{
1059 if (arg == NULL)
1060 return false;
1061
1062 bool is_positional = true;
1063 char *cptr = (char *) arg;
1064
1065 if (cptr[0] == '%')
1066 {
1067 ++cptr;
1068 while (isdigit (cptr[0]))
1069 ++cptr;
1070 if (cptr[0] != '\0')
1071 is_positional = false;
1072 }
1073 else
1074 is_positional = false;
1075
1076 return is_positional;
1077}
1078
Chris Lattner24943d22010-06-08 16:52:24 +00001079void
Caroline Tice5e0894e2010-10-12 17:45:19 +00001080Args::ParseAliasOptions (Options &options,
1081 CommandReturnObject &result,
Caroline Ticee0da7a52010-12-09 22:52:49 +00001082 OptionArgVector *option_arg_vector,
1083 std::string &raw_input_string)
Chris Lattner24943d22010-06-08 16:52:24 +00001084{
1085 StreamString sstr;
1086 int i;
1087 struct option *long_options = options.GetLongOptions();
1088
1089 if (long_options == NULL)
1090 {
1091 result.AppendError ("invalid long options");
1092 result.SetStatus (eReturnStatusFailed);
1093 return;
1094 }
1095
1096 for (i = 0; long_options[i].name != NULL; ++i)
1097 {
1098 if (long_options[i].flag == NULL)
1099 {
1100 sstr << (char) long_options[i].val;
1101 switch (long_options[i].has_arg)
1102 {
1103 default:
1104 case no_argument:
1105 break;
1106 case required_argument:
1107 sstr << ":";
1108 break;
1109 case optional_argument:
1110 sstr << "::";
1111 break;
1112 }
1113 }
1114 }
1115
Eli Friedmanef2bc872010-06-13 19:18:49 +00001116#ifdef __GLIBC__
1117 optind = 0;
1118#else
Chris Lattner24943d22010-06-08 16:52:24 +00001119 optreset = 1;
1120 optind = 1;
Eli Friedmanef2bc872010-06-13 19:18:49 +00001121#endif
Chris Lattner24943d22010-06-08 16:52:24 +00001122 int val;
1123 while (1)
1124 {
1125 int long_options_index = -1;
1126 val = ::getopt_long (GetArgumentCount(), GetArgumentVector(), sstr.GetData(), long_options,
1127 &long_options_index);
1128
1129 if (val == -1)
1130 break;
1131
1132 if (val == '?')
1133 {
1134 result.AppendError ("unknown or ambiguous option");
1135 result.SetStatus (eReturnStatusFailed);
1136 break;
1137 }
1138
1139 if (val == 0)
1140 continue;
1141
1142 ((Options *) &options)->OptionSeen (val);
1143
1144 // Look up the long option index
1145 if (long_options_index == -1)
1146 {
1147 for (int j = 0;
1148 long_options[j].name || long_options[j].has_arg || long_options[j].flag || long_options[j].val;
1149 ++j)
1150 {
1151 if (long_options[j].val == val)
1152 {
1153 long_options_index = j;
1154 break;
1155 }
1156 }
1157 }
1158
1159 // See if the option takes an argument, and see if one was supplied.
1160 if (long_options_index >= 0)
1161 {
1162 StreamString option_str;
1163 option_str.Printf ("-%c", (char) val);
1164
1165 switch (long_options[long_options_index].has_arg)
1166 {
1167 case no_argument:
Caroline Tice44c841d2010-12-07 19:58:26 +00001168 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
1169 OptionArgValue (no_argument, "<no-argument>")));
Caroline Tice2160c3f2010-09-12 04:48:45 +00001170 result.SetStatus (eReturnStatusSuccessFinishNoResult);
Chris Lattner24943d22010-06-08 16:52:24 +00001171 break;
1172 case required_argument:
1173 if (optarg != NULL)
1174 {
1175 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
Caroline Tice44c841d2010-12-07 19:58:26 +00001176 OptionArgValue (required_argument,
1177 std::string (optarg))));
Chris Lattner24943d22010-06-08 16:52:24 +00001178 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1179 }
1180 else
1181 {
1182 result.AppendErrorWithFormat ("Option '%s' is missing argument specifier.\n",
1183 option_str.GetData());
1184 result.SetStatus (eReturnStatusFailed);
1185 }
1186 break;
1187 case optional_argument:
1188 if (optarg != NULL)
1189 {
1190 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
Caroline Tice44c841d2010-12-07 19:58:26 +00001191 OptionArgValue (optional_argument,
1192 std::string (optarg))));
Chris Lattner24943d22010-06-08 16:52:24 +00001193 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1194 }
1195 else
1196 {
1197 option_arg_vector->push_back (OptionArgPair (std::string (option_str.GetData()),
Caroline Tice44c841d2010-12-07 19:58:26 +00001198 OptionArgValue (optional_argument, "<no-argument>")));
Chris Lattner24943d22010-06-08 16:52:24 +00001199 result.SetStatus (eReturnStatusSuccessFinishNoResult);
1200 }
1201 break;
1202 default:
1203 result.AppendErrorWithFormat
1204 ("error with options table; invalid value in has_arg field for option '%c'.\n",
1205 (char) val);
1206 result.SetStatus (eReturnStatusFailed);
1207 break;
1208 }
1209 }
1210 else
1211 {
1212 result.AppendErrorWithFormat ("Invalid option with value '%c'.\n", (char) val);
1213 result.SetStatus (eReturnStatusFailed);
1214 }
Caroline Tice5e0894e2010-10-12 17:45:19 +00001215
1216 if (long_options_index >= 0)
1217 {
1218 // 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 +00001219 // supplied. Remove option (and argument, if given) from the argument list. Also remove them from
1220 // the raw_input_string, if one was passed in.
Caroline Tice44c841d2010-12-07 19:58:26 +00001221 size_t idx = FindArgumentIndexForOption (long_options, long_options_index);
1222 if (idx < GetArgumentCount())
1223 {
Caroline Ticee0da7a52010-12-09 22:52:49 +00001224 if (raw_input_string.size() > 0)
1225 {
1226 const char *tmp_arg = GetArgumentAtIndex (idx);
1227 size_t pos = raw_input_string.find (tmp_arg);
1228 if (pos != std::string::npos)
1229 raw_input_string.erase (pos, strlen (tmp_arg));
1230 }
Caroline Tice44c841d2010-12-07 19:58:26 +00001231 ReplaceArgumentAtIndex (idx, "");
1232 if ((long_options[long_options_index].has_arg != no_argument)
1233 && (optarg != NULL)
1234 && (idx+1 < GetArgumentCount())
1235 && (strcmp (optarg, GetArgumentAtIndex(idx+1)) == 0))
Caroline Ticee0da7a52010-12-09 22:52:49 +00001236 {
1237 if (raw_input_string.size() > 0)
1238 {
1239 const char *tmp_arg = GetArgumentAtIndex (idx+1);
1240 size_t pos = raw_input_string.find (tmp_arg);
1241 if (pos != std::string::npos)
1242 raw_input_string.erase (pos, strlen (tmp_arg));
1243 }
Caroline Tice44c841d2010-12-07 19:58:26 +00001244 ReplaceArgumentAtIndex (idx+1, "");
Caroline Ticee0da7a52010-12-09 22:52:49 +00001245 }
Caroline Tice44c841d2010-12-07 19:58:26 +00001246 }
Caroline Tice5e0894e2010-10-12 17:45:19 +00001247 }
1248
Chris Lattner24943d22010-06-08 16:52:24 +00001249 if (!result.Succeeded())
1250 break;
1251 }
1252}
1253
1254void
1255Args::ParseArgsForCompletion
1256(
1257 Options &options,
Jim Inghamadb84292010-06-24 20:31:04 +00001258 OptionElementVector &option_element_vector,
1259 uint32_t cursor_index
Chris Lattner24943d22010-06-08 16:52:24 +00001260)
1261{
1262 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001263 struct option *long_options = options.GetLongOptions();
1264 option_element_vector.clear();
1265
1266 if (long_options == NULL)
1267 {
1268 return;
1269 }
1270
1271 // Leading : tells getopt to return a : for a missing option argument AND
1272 // to suppress error messages.
1273
1274 sstr << ":";
Greg Claytonbef15832010-07-14 00:18:15 +00001275 for (int i = 0; long_options[i].name != NULL; ++i)
Chris Lattner24943d22010-06-08 16:52:24 +00001276 {
1277 if (long_options[i].flag == NULL)
1278 {
1279 sstr << (char) long_options[i].val;
1280 switch (long_options[i].has_arg)
1281 {
1282 default:
1283 case no_argument:
1284 break;
1285 case required_argument:
1286 sstr << ":";
1287 break;
1288 case optional_argument:
1289 sstr << "::";
1290 break;
1291 }
1292 }
1293 }
1294
Eli Friedmanef2bc872010-06-13 19:18:49 +00001295#ifdef __GLIBC__
1296 optind = 0;
1297#else
Chris Lattner24943d22010-06-08 16:52:24 +00001298 optreset = 1;
1299 optind = 1;
Eli Friedmanef2bc872010-06-13 19:18:49 +00001300#endif
Chris Lattner24943d22010-06-08 16:52:24 +00001301 opterr = 0;
1302
1303 int val;
1304 const OptionDefinition *opt_defs = options.GetDefinitions();
1305
Jim Inghamadb84292010-06-24 20:31:04 +00001306 // Fooey... getopt_long permutes the GetArgumentVector to move the options to the front.
Chris Lattner24943d22010-06-08 16:52:24 +00001307 // So we have to build another Arg and pass that to getopt_long so it doesn't
Jim Inghamadb84292010-06-24 20:31:04 +00001308 // change the one we have.
Chris Lattner24943d22010-06-08 16:52:24 +00001309
Greg Clayton54e7afa2010-07-09 20:39:50 +00001310 std::vector<const char *> dummy_vec (GetArgumentVector(), GetArgumentVector() + GetArgumentCount() + 1);
Chris Lattner24943d22010-06-08 16:52:24 +00001311
Jim Inghamadb84292010-06-24 20:31:04 +00001312 bool failed_once = false;
1313 uint32_t dash_dash_pos = -1;
1314
Chris Lattner24943d22010-06-08 16:52:24 +00001315 while (1)
1316 {
1317 bool missing_argument = false;
1318 int parse_start = optind;
1319 int long_options_index = -1;
Jim Inghamadb84292010-06-24 20:31:04 +00001320
Greg Clayton54e7afa2010-07-09 20:39:50 +00001321 val = ::getopt_long (dummy_vec.size() - 1,
Greg Clayton53d68e72010-07-20 22:52:08 +00001322 (char *const *) &dummy_vec.front(),
Greg Clayton54e7afa2010-07-09 20:39:50 +00001323 sstr.GetData(),
1324 long_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001325 &long_options_index);
1326
1327 if (val == -1)
Jim Inghamadb84292010-06-24 20:31:04 +00001328 {
1329 // When we're completing a "--" which is the last option on line,
1330 if (failed_once)
1331 break;
1332
1333 failed_once = true;
1334
1335 // If this is a bare "--" we mark it as such so we can complete it successfully later.
1336 // Handling the "--" is a little tricky, since that may mean end of options or arguments, or the
1337 // user might want to complete options by long name. I make this work by checking whether the
1338 // cursor is in the "--" argument, and if so I assume we're completing the long option, otherwise
1339 // I let it pass to getopt_long which will terminate the option parsing.
1340 // Note, in either case we continue parsing the line so we can figure out what other options
1341 // were passed. This will be useful when we come to restricting completions based on what other
1342 // options we've seen on the line.
Chris Lattner24943d22010-06-08 16:52:24 +00001343
Jim Inghamadb84292010-06-24 20:31:04 +00001344 if (optind < dummy_vec.size() - 1
1345 && (strcmp (dummy_vec[optind-1], "--") == 0))
1346 {
1347 dash_dash_pos = optind - 1;
1348 if (optind - 1 == cursor_index)
1349 {
1350 option_element_vector.push_back (OptionArgElement (OptionArgElement::eBareDoubleDash, optind - 1,
1351 OptionArgElement::eBareDoubleDash));
1352 continue;
1353 }
1354 else
1355 break;
1356 }
1357 else
1358 break;
1359 }
Chris Lattner24943d22010-06-08 16:52:24 +00001360 else if (val == '?')
1361 {
Jim Inghamadb84292010-06-24 20:31:04 +00001362 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1363 OptionArgElement::eUnrecognizedArg));
Chris Lattner24943d22010-06-08 16:52:24 +00001364 continue;
1365 }
1366 else if (val == 0)
1367 {
1368 continue;
1369 }
1370 else if (val == ':')
1371 {
1372 // This is a missing argument.
1373 val = optopt;
1374 missing_argument = true;
1375 }
1376
1377 ((Options *) &options)->OptionSeen (val);
1378
1379 // Look up the long option index
1380 if (long_options_index == -1)
1381 {
1382 for (int j = 0;
1383 long_options[j].name || long_options[j].has_arg || long_options[j].flag || long_options[j].val;
1384 ++j)
1385 {
1386 if (long_options[j].val == val)
1387 {
1388 long_options_index = j;
1389 break;
1390 }
1391 }
1392 }
1393
1394 // See if the option takes an argument, and see if one was supplied.
1395 if (long_options_index >= 0)
1396 {
1397 int opt_defs_index = -1;
1398 for (int i = 0; ; i++)
1399 {
1400 if (opt_defs[i].short_option == 0)
1401 break;
1402 else if (opt_defs[i].short_option == val)
1403 {
1404 opt_defs_index = i;
1405 break;
1406 }
1407 }
1408
1409 switch (long_options[long_options_index].has_arg)
1410 {
1411 case no_argument:
1412 option_element_vector.push_back (OptionArgElement (opt_defs_index, parse_start, 0));
1413 break;
1414 case required_argument:
1415 if (optarg != NULL)
1416 {
1417 int arg_index;
1418 if (missing_argument)
1419 arg_index = -1;
1420 else
Jim Inghamadb84292010-06-24 20:31:04 +00001421 arg_index = optind - 1;
Chris Lattner24943d22010-06-08 16:52:24 +00001422
Jim Inghamadb84292010-06-24 20:31:04 +00001423 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, arg_index));
Chris Lattner24943d22010-06-08 16:52:24 +00001424 }
1425 else
1426 {
Jim Inghamadb84292010-06-24 20:31:04 +00001427 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 1, -1));
Chris Lattner24943d22010-06-08 16:52:24 +00001428 }
1429 break;
1430 case optional_argument:
1431 if (optarg != NULL)
1432 {
Jim Inghamadb84292010-06-24 20:31:04 +00001433 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, optind - 1));
Chris Lattner24943d22010-06-08 16:52:24 +00001434 }
1435 else
1436 {
Jim Inghamadb84292010-06-24 20:31:04 +00001437 option_element_vector.push_back (OptionArgElement (opt_defs_index, optind - 2, optind - 1));
Chris Lattner24943d22010-06-08 16:52:24 +00001438 }
1439 break;
1440 default:
1441 // The options table is messed up. Here we'll just continue
Jim Inghamadb84292010-06-24 20:31:04 +00001442 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1443 OptionArgElement::eUnrecognizedArg));
Chris Lattner24943d22010-06-08 16:52:24 +00001444 break;
1445 }
1446 }
1447 else
1448 {
Jim Inghamadb84292010-06-24 20:31:04 +00001449 option_element_vector.push_back (OptionArgElement (OptionArgElement::eUnrecognizedArg, optind - 1,
1450 OptionArgElement::eUnrecognizedArg));
Chris Lattner24943d22010-06-08 16:52:24 +00001451 }
1452 }
Jim Inghamadb84292010-06-24 20:31:04 +00001453
1454 // Finally we have to handle the case where the cursor index points at a single "-". We want to mark that in
1455 // the option_element_vector, but only if it is not after the "--". But it turns out that getopt_long just ignores
1456 // an isolated "-". So we have to look it up by hand here. We only care if it is AT the cursor position.
1457
1458 if ((dash_dash_pos == -1 || cursor_index < dash_dash_pos)
1459 && strcmp (GetArgumentAtIndex(cursor_index), "-") == 0)
1460 {
1461 option_element_vector.push_back (OptionArgElement (OptionArgElement::eBareDash, cursor_index,
1462 OptionArgElement::eBareDash));
1463
1464 }
Chris Lattner24943d22010-06-08 16:52:24 +00001465}