2 Copyright © 1995-2013, The AROS Development Team. All rights reserved.
10 #include <aros/debug.h>
12 #include <exec/memory.h>
13 #include <proto/exec.h>
14 #include <dos/rdargs.h>
15 #include <dos/dosextens.h>
16 #include <proto/utility.h>
18 #include "dos_intern.h"
22 # include <proto/dos.h>
25 # define AROS_LH3(t,fn,a1,a2,a3,bt,bn,o,lib) t fn (a1,a2,a3)
27 # define AROS_LHA(t,n,r) t n
28 # undef AROS_LIBFUNC_INIT
29 # define AROS_LIBFUNC_INIT
30 # undef AROS_LIBFUNC_EXIT
31 # define AROS_LIBFUNC_EXIT
34 /* Fix the end-of-buffer ReadItem() 'well known' bug
35 * where it "ungets" non-terminator (' ','=','\t','\n')
36 * characters at the end of a non-\n terminated buffer.
38 #define READITEM(buff, bufflen, cs) \
39 ({ LONG ret = ReadItem(buff, bufflen, cs); \
40 if (ret == ITEM_UNQUOTED && (cs->CS_CurChr+1) == cs->CS_Length) \
45 /* Returns 0 if this is not a '?' line, otherwise
46 * returns the length between the '?' and the '\n'
49 static inline LONG
is_question(BYTE
* buff
, LONG buffsize
)
55 seen_question
= FALSE
;
57 /* Reach end of line */
58 for (i
= 0; i
< buffsize
; i
++)
60 /* Only spaces and return are allowed at the end of the line after the
61 * question mark for it to lead to reprompting. BTW, AmigaOS allowed
62 * only one space then... but do we need to be _that_ compatible?
86 if ((!quoted
) && (seen_space
))
93 seen_question
= FALSE
;
102 seen_question
= seen_space
= FALSE
;
108 /*****************************************************************************
111 #include <proto/dos.h>
113 AROS_LH3(struct RDArgs
*, ReadArgs
,
116 AROS_LHA(CONST_STRPTR
, template, D1
),
117 AROS_LHA(IPTR
*, array
, D2
),
118 AROS_LHA(struct RDArgs
*, rdargs
, D3
),
121 struct DosLibrary
*, DOSBase
, 133, Dos
)
124 Parses the commandline, a given string or Input() and fills
125 an argument array according to the options template given.
126 The array must be initialized to the wanted defaults before
127 each call to ReadArgs(). If the rdargs argument is NULL
128 ReadArgs() tries to parse the commandline and continues
129 on the input channel if it just consists of a single '?',
130 prompting the user for input.
133 template - Template string. The template string is given as
134 a number of options separated by ',' and modified
135 by '/' modifiers, e.g. 'NAME,WIDTH/N,HEIGHT/N'
136 means get a name string and two numbers (width and
137 height). The possible modifiers are:
138 /S Option is a switch. It may be either set or
140 /T Option is a boolean value. Requires an argument
141 which may be "ON", "YES" (setting the respective
142 argument to 1), "OFF" or "NO" (setting the
143 respective argument to 0).
144 /N Option is a number. Strings are not allowed.
145 If the option is optional, a pointer to the
146 actual number is returned. This is how you know
147 if it was really given. The number is always of type
149 /A Argument is required. If it is left out ReadArgs()
151 /K The keyword must be given when filling the option.
152 Normally it's skipped.
153 /M Multiple strings or, when used in combination with /N,
154 numbers. The result is returned as an array of pointers
155 to strings or LONGs, and is terminated with NULL. /M
156 eats all strings that don't fit into any other option.
157 If there are unfilled /A arguments after parsing they
158 steal strings from /M. This makes it possible to, for
159 example, write a Copy command template like
160 'FROM/A/M,TO/A'. There may be only one /M option in a
162 /F Eats the rest of the line even if there are option
164 array - Array to be filled with the result values. The array must
165 be intialized to the default values before calling
167 rdargs - An optional RDArgs structure determining the type of
171 A handle for the memory allocated by ReadArgs(). Must be freed
172 with FreeArgs() later.
177 *****************************************************************************/
181 /* Allocated resources */
182 struct DAList
*dalist
= NULL
;
184 STRPTR strbuf
= NULL
, iline
= NULL
;
185 STRPTR
*multvec
= NULL
, *argbuf
= NULL
;
187 ULONG multnum
= 0, multmax
= 0;
192 STRPTR s1
, s2
, *newmult
;
193 ULONG arg
, numargs
, nextarg
;
194 LONG it
, item
, chars
, delthis
;
195 struct CSource lcs
, *cs
;
196 BOOL is_file_not_buffer
;
197 TEXT argbuff
[256 + 1]; /* Maximum BCPL string length + injected \n + ASCIIZ */
199 ASSERT_VALID_PTR(template);
200 ASSERT_VALID_PTR(array
);
201 ASSERT_VALID_PTR_OR_NULL(rdargs
);
203 D(bug("[ReadArgs] Template: \"%s\"\n", template));
204 /* Get pointer to process structure. */
205 struct Process
*me
= (struct Process
*) FindTask(NULL
);
207 ASSERT_VALID_PROCESS(me
);
209 /* Error recovery. C has no exceptions. This is a simple replacement. */
213 #define ERROR(a) { error=a; goto end; }
215 /* Template options */
216 #define REQUIRED 0x80 /* /A */
217 #define KEYWORD 0x40 /* /K */
218 #define MULTIPLE 0x20 /* /M */
219 #define TYPEMASK 0x07
220 #define NORMAL 0x00 /* No option */
221 #define SWITCH 0x01 /* /S, implies /K */
222 #define TOGGLE 0x02 /* /T, implies /K */
223 #define NUMERIC 0x03 /* /N */
224 #define REST 0x04 /* /F */
226 /* Flags for each possible character. */
227 static const UBYTE argflags
[] =
229 REQUIRED
, 0, 0, 0, 0, REST
, 0, 0, 0, 0, KEYWORD
, 0, MULTIPLE
,
230 NUMERIC
, 0, 0, 0, 0, SWITCH
| KEYWORD
, TOGGLE
| KEYWORD
, 0, 0,
234 /* Allocate readargs structure (and private internal one) */
237 rdargs
= (struct RDArgs
*) AllocVec(sizeof(struct RDArgs
),
238 MEMF_ANY
| MEMF_CLEAR
);
241 rdargs
->RDA_Flags
|= RDAF_ALLOCATED_BY_READARGS
;
245 dalist
= (struct DAList
*) AllocVec(sizeof(struct DAList
),
246 MEMF_ANY
| MEMF_CLEAR
);
248 if (rdargs
== NULL
|| dalist
== NULL
)
250 ERROR(ERROR_NO_FREE_STORE
);
253 /* Init character source. */
254 if (rdargs
->RDA_Source
.CS_Buffer
)
256 cs
= &rdargs
->RDA_Source
;
257 D(bug("[ReadArgs] Buffer: \"%s\"\n", cs
->CS_Buffer
));
258 is_file_not_buffer
= FALSE
;
262 BOOL notempty
= TRUE
;
263 BPTR input
= Input();
265 D(bug("[ReadArgs] Input: 0x%p\n", input
));
266 is_file_not_buffer
= TRUE
;
269 * Take arguments from input stream. They were injected there by either
270 * runcommand.c or createnewproc.c (see vbuf_inject() routine).
271 * This is described in Guru Book.
274 lcs
.CS_Buffer
= &argbuff
[0];
277 * Special kludge for interactive filehandles (i. e. CLI windows).
278 * Read data only if filehandle's buffer is not empty. Otherwise
279 * read will cause opening CLI window and waiting for user's input.
280 * As a consequence we still can use ReadArgs() on input redirected
281 * from a file, even if we are started from Workbench (hypothetical
283 * This prevents opening a CLI window if the program was started from
284 * Workbench and redirected its Input() and Output() to own window,
285 * but still called ReadArgs() after redirection for some reason.
286 * Streams redirection is widely used in AROS startup code.
288 if (IsInteractive(input
))
290 struct FileHandle
*fh
= BADDR(input
);
292 notempty
= (fh
->fh_Pos
!= fh
->fh_End
);
296 FGets(input
, lcs
.CS_Buffer
, sizeof(argbuff
));
298 D(bug("[ReadArgs] Line: %s\n", argbuff
));
302 for (; *cs1
!= '\0'; ++cs1
);
304 lcs
.CS_Length
= cs1
- lcs
.CS_Buffer
;
310 /* Check for optional reprompting */
311 if (!(rdargs
->RDA_Flags
& RDAF_NOPROMPT
))
313 if ((delthis
= is_question(cs
->CS_Buffer
, cs
->CS_Length
)))
315 /* '?' was found on the commandline. */
316 BPTR input
= Input();
317 BPTR output
= Output();
318 ULONG isize
= 0, ibuf
= 0;
320 ULONG helpdisplayed
= FALSE
;
322 /* Prompt for more input */
324 D(bug("[ReadArgs] '?' found, %d chars to be removed\n", delthis
));
325 D(bug("[ReadArgs] rdargs=0x%p\n", rdargs
));
326 D(if (rdargs
) bug ("[ReadArds] rdargs->RDA_ExtHelp=0x%p\n", rdargs
->RDA_ExtHelp
);)
328 if (FPuts(output
, template) || FPuts(output
, ": "))
330 ERROR(me
->pr_Result2
);
335 ERROR(me
->pr_Result2
);
338 cs
->CS_Length
-= delthis
;
339 ULONG memsize
= isize
= ibuf
= cs
->CS_Length
;
340 iline
= (STRPTR
) AllocVec(ibuf
, MEMF_ANY
);
341 CopyMem(cs
->CS_Buffer
, iline
, isize
);
345 /* Read a line in. */
351 iline
[isize
] = '\0'; /* end of string */
356 /* Buffer too small. Get a new one. */
361 newiline
= (STRPTR
) AllocVec(ibuf
, MEMF_ANY
);
362 if (newiline
== NULL
)
364 ERROR(ERROR_NO_FREE_STORE
);
368 CopyMem(iline
, newiline
, isize
);
376 if (is_file_not_buffer
)
384 if (cs
->CS_CurChr
>= cs
->CS_Length
)
387 c
= cs
->CS_Buffer
[cs
->CS_CurChr
++];
390 /* Check and write it. */
391 if (c
== EOF
&& me
->pr_Result2
)
393 ERROR(me
->pr_Result2
);
396 /* Fix short buffers to have a trailing '\n' */
397 if (c
== EOF
|| c
== '\0')
402 iline
[isize
] = '\0'; /* end of string */
404 D(iline
[isize
] = 0; bug("[ReadArgs] Size %d, line: '%s'\n", isize
, iline
));
406 /* if user entered single ? again or some string ending
407 with space and ? either display template again or
408 extended help if it's available */
409 if ( (delthis
= is_question(iline
, isize
))
410 && (memsize
<= (isize
- delthis
))
413 helpdisplayed
= TRUE
;
415 memsize
= isize
-= delthis
;
417 if(rdargs
->RDA_ExtHelp
!= NULL
)
419 if (FPuts(output
, rdargs
->RDA_ExtHelp
) || FPuts(output
, ": "))
420 ERROR(me
->pr_Result2
);
422 else if (FPuts(output
, template) || FPuts(output
, ": "))
424 ERROR(me
->pr_Result2
);
429 ERROR(me
->pr_Result2
);
433 helpdisplayed
= FALSE
;
434 } while(helpdisplayed
);
436 /* Prepare input source for new line. */
437 cs
->CS_Buffer
= iline
;
438 cs
->CS_Length
= isize
;
444 * Get enough space for string buffer.
445 * It's always smaller than the size of the input line+1.
448 strbuflen
= cs
->CS_Length
+ 1;
449 strbuf
= (STRPTR
) AllocVec(strbuflen
, MEMF_ANY
);
453 ERROR(ERROR_NO_FREE_STORE
);
456 /* Count the number of items in the template (number of ','+1). */
468 /* Use this count to get space for temporary flag array and result
470 flags
= (UBYTE
*) AllocVec(numargs
+ 1, MEMF_CLEAR
);
472 argbuf
= (STRPTR
*) AllocVec((numargs
+ 1) * sizeof(STRPTR
), MEMF_CLEAR
);
474 if (flags
== NULL
|| argbuf
== NULL
)
476 ERROR(ERROR_NO_FREE_STORE
);
479 /* Fill the flag array. */
485 /* A ',' means: goto next item. */
491 /* In case of a '/' use the next character as option. */
494 UBYTE argc
= ToUpper(*cs1
);
495 if (argc
>= 'A' && argc
<= 'Z')
496 *s2
|= argflags
[argc
- 'A'];
500 /* Add a dummy so that the whole line is processed (see below). */
504 * Now process commandline for the first time:
505 * Go from left to right and fill all items that need filling.
506 * If an item is given as 'OPTION=VALUE' or 'OPTION VALUE' fill
508 * NOTE: '<=' comparison is intentional here. When we allocated argbuf, we added one
509 * to the number of arguments. And right above we added fictional MULTIPLE flag.
510 * This is actually needed to make /S and /K working.
514 for (arg
= 0; arg
<= numargs
; arg
= nextarg
)
518 D(bug("[ReadArgs] Arg %d (0x%x) s1=&strbuf[%d], %d left\n", arg
, flags
[arg
], s1
-strbuf
, strbuflen
));
520 /* Out of buffer space?
521 * This should not have happened, some internal logic
524 if (strbuflen
== 0) {
525 D(bug("[ReadArgs] %d: INTERNAL ERROR: Ran out of buffer space.\n", arg
));
529 /* Skip /K options and options that are already done. */
530 if (flags
[arg
] & KEYWORD
|| argbuf
[arg
] != NULL
)
535 #if 0 /* stegerg: if so a template of CLOSE/S,QUICK/S,COMMAND/F would
536 not work correctly if command line for example is
537 "CLOSE QUICK" it would all end up being eaten by COMMAND/F
540 /* If the current option is of type /F do not look for keywords */
541 if ((flags
[arg
] & TYPEMASK
) != REST
)
545 /* Get item. Quoted items are never keywords. */
546 it
= READITEM(s1
, strbuflen
, cs
);
547 D(bug("[ReadArgs] Item %s type %d\n", s1
, it
));
549 if (it
== ITEM_UNQUOTED
)
551 /* Not quoted. Check if it's a keyword. */
552 item
= FindArg(template, s1
);
554 if (item
>= 0 && item
< numargs
&& argbuf
[item
] == NULL
)
556 D(bug("[ReadArgs] %d: Keyword \"%s\" (%d)\n", arg
, s1
, item
));
558 * It's a keyword. Fill it and retry the current option
564 /* /S /T may not be given as 'OPTION=VALUE'. */
565 if ((flags
[item
] & TYPEMASK
) != SWITCH
566 && (flags
[item
] & TYPEMASK
) != TOGGLE
)
569 it
= READITEM(s1
, strbuflen
, cs
);
571 if (it
== ITEM_EQUAL
)
573 it
= READITEM(s1
, strbuflen
, cs
);
574 } else if (it
!= ITEM_QUOTED
&& it
!= ITEM_UNQUOTED
) {
575 ERROR(ERROR_KEY_NEEDS_ARG
);
581 /* Check returncode of ReadItem(). */
582 if (it
== ITEM_EQUAL
)
584 ERROR(ERROR_BAD_TEMPLATE
);
586 else if (it
== ITEM_ERROR
)
588 ERROR(me
->pr_Result2
);
590 else if (it
== ITEM_NOTHING
)
596 /* /F takes all the rest, including extra spaces, =, and '"'
597 * NOTE: If the item was quoted, this will strip off the
598 * next '"' mark it sees.
600 if ((flags
[arg
] & TYPEMASK
) == REST
)
602 BOOL eat_quote
= (it
== ITEM_QUOTED
) ? TRUE
: FALSE
;
605 /* Skip past what ReadItem() just read.
607 while (*s1
&& strbuflen
> 0) {
613 * Put the rest into the buffer, including the separator
614 * ReadItem() actually ungets '\n' terminator. So if CurChr points to it,
615 * we don't need to adjust it. Otherwise we duplicate last character of arguments line.
617 if (cs
->CS_Buffer
[cs
->CS_CurChr
] != '\n')
619 s2
= &cs
->CS_Buffer
[cs
->CS_CurChr
];
621 while (cs
->CS_CurChr
< cs
->CS_Length
&&
628 if (eat_quote
&& *s2
== '"')
641 D(bug("[ReadArgs] /F copy: \"%s\" left=%d, CS_CurChr=%d, CS_Length=%d\n", argbuf
[arg
], strbuflen
, cs
->CS_CurChr
, cs
->CS_Length
));
646 if (flags
[arg
] & MULTIPLE
)
648 /* All /M arguments are stored in a buffer. */
649 if (multnum
>= multmax
)
651 /* Buffer too small. Get a new one. */
654 newmult
= (STRPTR
*) AllocVec(multmax
* sizeof(char *),
658 ERROR(ERROR_NO_FREE_STORE
);
661 CopyMemQuick((ULONG
*) multvec
, (ULONG
*) newmult
,
662 multnum
* sizeof(char *));
669 /* Put string into the buffer. */
670 multvec
[multnum
++] = s1
;
672 D(bug("[ReadArgs] %d: Multiple +\"%s\"\n", arg
, s1
));
675 /* Account for the \000 at the end. */
678 /* /M takes more than one argument, so retry. */
681 else if ((flags
[arg
] & TYPEMASK
) == SWITCH
682 || (flags
[arg
] & TYPEMASK
) == TOGGLE
)
684 /* /S or /T just set a flag */
685 argbuf
[arg
] = (char *) ~0;
686 D(bug("[ReadArgs] %d: Toggle\n", arg
));
688 else /* NORMAL || NUMERIC */
690 /* Put argument into argument buffer. */
692 D(bug("[ReadArgs] %d: Normal: \"%s\"\n", arg
, s1
));
696 /* Account for the \000 at the end. */
700 if (cs
->CS_CurChr
>= cs
->CS_Length
)
701 break; /* end of input */
704 /* Unfilled /A options steal Arguments from /M */
705 for (arg
= numargs
; arg
-- > 0;)
707 if (flags
[arg
] & REQUIRED
&& argbuf
[arg
] == NULL
708 && !(flags
[arg
] & MULTIPLE
))
710 if (flags
[arg
] & KEYWORD
)
712 /* /K/A argument, which insists on keyword
713 * being used, cannot be satisfied */
715 ERROR(ERROR_TOO_MANY_ARGS
); /* yes, strange error number,
716 * but it translates to "wrong
717 * number of arguments" */
723 /* No arguments left? Oh dear! */
724 ERROR(ERROR_REQUIRED_ARG_MISSING
);
727 argbuf
[arg
] = multvec
[--multnum
];
731 /* Put the rest of /M where it belongs */
732 for (arg
= 0; arg
< numargs
; arg
++)
734 if (flags
[arg
] & MULTIPLE
)
736 if (flags
[arg
] & REQUIRED
&& multnum
== 0)
738 ERROR(ERROR_REQUIRED_ARG_MISSING
);
743 /* NULL terminate it. */
744 if (multnum
>= multmax
)
748 newmult
= (STRPTR
*) AllocVec(multmax
* sizeof(STRPTR
),
753 ERROR(ERROR_NO_FREE_STORE
);
756 CopyMemQuick((ULONG
*) multvec
, (ULONG
*) newmult
,
757 multnum
* sizeof(char *));
764 multvec
[multnum
++] = NULL
;
765 argbuf
[arg
] = (STRPTR
) multvec
;
769 /* Shouldn't be necessary, but some buggy software relies on this */
777 /* There are some arguments left? Return error. */
778 if (multnum
!= 0 && arg
== numargs
)
780 ERROR(ERROR_TOO_MANY_ARGS
);
784 * The commandline is processed now. Put the results in the result array.
785 * Convert /N arguments by the way.
787 for (arg
= 0; arg
< numargs
; arg
++)
789 /* Just for the arguments given. */
790 if (argbuf
[arg
] != NULL
)
792 if (flags
[arg
] & MULTIPLE
)
794 array
[arg
] = (IPTR
) argbuf
[arg
];
796 if ((flags
[arg
] & TYPEMASK
) == NUMERIC
)
801 if (multnum
* 2 > multmax
)
803 multmax
= multnum
* 2;
804 newmult
= (STRPTR
*) AllocVec(multmax
* sizeof(STRPTR
),
809 ERROR(ERROR_NO_FREE_STORE
);
812 CopyMemQuick((ULONG
*) multvec
, (ULONG
*) newmult
,
813 multnum
* sizeof(char *));
820 array
[arg
] = (IPTR
) multvec
;
822 q
= (LONG
*) (multvec
+ multnum
);
826 /* Convert /N argument. */
827 chars
= StrToLong(*p
, q
);
829 if (chars
<= 0 || (*p
)[chars
])
831 /* Conversion failed. */
832 ERROR(ERROR_BAD_NUMBER
);
835 /* Put the result where it belongs. */
838 q
+= sizeof(IPTR
) / sizeof(LONG
);
844 switch (flags
[arg
] & TYPEMASK
)
849 /* Simple arguments are just copied. */
850 array
[arg
] = (IPTR
) argbuf
[arg
];
854 /* /T logically inverts the argument. */
855 array
[arg
] = array
[arg
] ? 0 : ~0;
859 /* Convert /N argument. */
860 /* Abuse the argbuf buffer. It's not needed anymore. */
861 numstr
= (CONST_STRPTR
)argbuf
[arg
];
862 chars
= StrToLong(numstr
, (LONG
*)&argbuf
[arg
]);
864 if (chars
<= 0 || numstr
[chars
] != '\0')
866 /* Conversion failed. */
867 ERROR(ERROR_BAD_NUMBER
);
870 /* Put the result where it belongs. */
871 array
[arg
] = (IPTR
) &argbuf
[arg
];
878 if (flags
[arg
] & MULTIPLE
)
880 /* Shouldn't be necessary, but some buggy software relies on this.
881 * IBrowse's URL field isn't set to zero.
883 array
[arg
] = (IPTR
)NULL
;
891 /* Cleanup and return. */
897 /* ReadArgs() failed. Clean everything up. */
900 if (rdargs
->RDA_Flags
& RDAF_ALLOCATED_BY_READARGS
)
911 me
->pr_Result2
= error
;
917 /* All went well. Prepare result and return. */
918 rdargs
->RDA_DAList
= (IPTR
) dalist
;
919 dalist
->ArgBuf
= argbuf
;
920 dalist
->StrBuf
= strbuf
;
921 dalist
->MultVec
= multvec
;
928 # include <dos/dos.h>
929 # include <dos/rdargs.h>
930 # include <utility/tagitem.h>
932 # include <proto/dos.h>
934 char cmlargs
[] = "TEST/A";
937 "This is exthelp for test\n"
943 LONG cmlvec
[CML_END
];
946 main(int argc
, char **argv
)
948 struct RDArgs
*rdargs
;
950 if ((rdargs
= AllocDosObject(DOS_RDARGS
, NULL
)))
952 rdargs
->RDA_ExtHelp
= usage
; /* FIX: why doesn't this work? */
954 if (!(ReadArgs(cmlargs
, cmlvec
, rdargs
)))
956 PrintFault(IoErr(), "AROS boot");
957 FreeDosObject(DOS_RDARGS
, rdargs
);
963 PrintFault(ERROR_NO_FREE_STORE
, "AROS boot");
968 FreeDosObject(DOS_RDARGS
, rdargs
);