3 Copyright © 1995-2012, The AROS Development Team. All rights reserved.
11 #include <aros/debug.h>
13 #include <exec/memory.h>
14 #include <proto/exec.h>
15 #include <dos/rdargs.h>
16 #include <dos/dosextens.h>
17 #include <proto/utility.h>
19 #include "dos_intern.h"
23 # include <proto/dos.h>
26 # define AROS_LH3(t,fn,a1,a2,a3,bt,bn,o,lib) t fn (a1,a2,a3)
28 # define AROS_LHA(t,n,r) t n
29 # undef AROS_LIBFUNC_INIT
30 # define AROS_LIBFUNC_INIT
31 # undef AROS_LIBFUNC_EXIT
32 # define AROS_LIBFUNC_EXIT
35 /* Fix the end-of-buffer ReadItem() 'well known' bug
36 * where it "ungets" non-terminator (' ','=','\t','\n')
37 * characters at the end of a non-\n terminated buffer.
39 #define READITEM(buff, bufflen, cs) \
40 ({ LONG ret = ReadItem(buff, bufflen, cs); \
41 if (ret == ITEM_UNQUOTED && (cs->CS_CurChr+1) == cs->CS_Length) \
46 /* Returns 0 if this is not a '?' line, otherwise
47 * returns the length between the '?' and the '\n'
50 static inline LONG
is_question(BYTE
* buff
, LONG buffsize
)
56 seen_question
= FALSE
;
58 /* Reach end of line */
59 for (i
= 0; i
< buffsize
; i
++)
61 /* Only spaces and return are allowed at the end of the line after the
62 * question mark for it to lead to reprompting. BTW, AmigaOS allowed
63 * only one space then... but do we need to be _that_ compatible?
87 if ((!quoted
) && (seen_space
))
94 seen_question
= FALSE
;
103 seen_question
= seen_space
= FALSE
;
109 /*****************************************************************************
112 #include <proto/dos.h>
114 AROS_LH3(struct RDArgs
*, ReadArgs
,
117 AROS_LHA(CONST_STRPTR
, template, D1
),
118 AROS_LHA(IPTR
*, array
, D2
),
119 AROS_LHA(struct RDArgs
*, rdargs
, D3
),
122 struct DosLibrary
*, DOSBase
, 133, Dos
)
125 Parses the commandline, a given string or Input() and fills
126 an argument array according to the options template given.
127 The array must be initialized to the wanted defaults before
128 each call to ReadArgs(). If the rdargs argument is NULL
129 ReadArgs() tries to parse the commandline and continues
130 on the input channel if it just consists of a single '?',
131 prompting the user for input.
134 template - Template string. The template string is given as
135 a number of options separated by ',' and modified
136 by '/' modifiers, e.g. 'NAME,WIDTH/N,HEIGHT/N'
137 means get a name string and two numbers (width and
138 height). The possible modifiers are:
139 /S Option is a switch. It may be either set or
141 /T Option is a boolean value. Requires an argument
142 which may be "ON", "YES" (setting the respective
143 argument to 1), "OFF" or "NO" (setting the
144 respective argument to 0).
145 /N Option is a number. Strings are not allowed.
146 If the option is optional, a pointer to the
147 actual number is returned. This is how you know
148 if it was really given. The number is always of type
150 /A Argument is required. If it is left out ReadArgs()
152 /K The keyword must be given when filling the option.
153 Normally it's skipped.
154 /M Multiple strings or, when used in combination with /N,
155 numbers. The result is returned as an array of pointers
156 to strings or LONGs, and is terminated with NULL. /M
157 eats all strings that don't fit into any other option.
158 If there are unfilled /A arguments after parsing they
159 steal strings from /M. This makes it possible to, for
160 example, write a Copy command template like
161 'FROM/A/M,TO/A'. There may be only one /M option in a
163 /F Eats the rest of the line even if there are option
165 array - Array to be filled with the result values. The array must
166 be intialized to the default values before calling
168 rdargs - An optional RDArgs structure determining the type of
172 A handle for the memory allocated by ReadArgs(). Must be freed
173 with FreeArgs() later.
178 *****************************************************************************/
182 /* Allocated resources */
183 struct DAList
*dalist
= NULL
;
185 STRPTR strbuf
= NULL
, iline
= NULL
;
186 STRPTR
*multvec
= NULL
, *argbuf
= NULL
;
188 ULONG multnum
= 0, multmax
= 0;
193 STRPTR s1
, s2
, *newmult
;
194 ULONG arg
, numargs
, nextarg
;
195 LONG it
, item
, chars
, delthis
;
196 struct CSource lcs
, *cs
;
197 BOOL is_file_not_buffer
;
198 TEXT argbuff
[256 + 1]; /* Maximum BCPL string length + injected \n + ASCIIZ */
200 ASSERT_VALID_PTR(template);
201 ASSERT_VALID_PTR(array
);
202 ASSERT_VALID_PTR_OR_NULL(rdargs
);
204 D(bug("[ReadArgs] Template: \"%s\"\n", template));
205 /* Get pointer to process structure. */
206 struct Process
*me
= (struct Process
*) FindTask(NULL
);
208 ASSERT_VALID_PROCESS(me
);
210 /* Error recovery. C has no exceptions. This is a simple replacement. */
214 #define ERROR(a) { error=a; goto end; }
216 /* Template options */
217 #define REQUIRED 0x80 /* /A */
218 #define KEYWORD 0x40 /* /K */
219 #define MULTIPLE 0x20 /* /M */
220 #define TYPEMASK 0x07
221 #define NORMAL 0x00 /* No option */
222 #define SWITCH 0x01 /* /S, implies /K */
223 #define TOGGLE 0x02 /* /T, implies /K */
224 #define NUMERIC 0x03 /* /N */
225 #define REST 0x04 /* /F */
227 /* Flags for each possible character. */
228 static const UBYTE argflags
[] =
230 REQUIRED
, 0, 0, 0, 0, REST
, 0, 0, 0, 0, KEYWORD
, 0, MULTIPLE
,
231 NUMERIC
, 0, 0, 0, 0, SWITCH
| KEYWORD
, TOGGLE
| KEYWORD
, 0, 0,
235 /* Allocate readargs structure (and private internal one) */
238 rdargs
= (struct RDArgs
*) AllocVec(sizeof(struct RDArgs
),
239 MEMF_ANY
| MEMF_CLEAR
);
242 rdargs
->RDA_Flags
|= RDAF_ALLOCATED_BY_READARGS
;
246 dalist
= (struct DAList
*) AllocVec(sizeof(struct DAList
),
247 MEMF_ANY
| MEMF_CLEAR
);
249 if (rdargs
== NULL
|| dalist
== NULL
)
251 ERROR(ERROR_NO_FREE_STORE
);
254 /* Init character source. */
255 if (rdargs
->RDA_Source
.CS_Buffer
)
257 cs
= &rdargs
->RDA_Source
;
258 D(bug("[ReadArgs] Buffer: \"%s\"\n", cs
->CS_Buffer
));
259 is_file_not_buffer
= FALSE
;
263 BOOL notempty
= TRUE
;
264 BPTR input
= Input();
266 D(bug("[ReadArgs] Input: 0x%p\n", input
));
267 is_file_not_buffer
= TRUE
;
270 * Take arguments from input stream. They were injected there by either
271 * runcommand.c or createnewproc.c (see vbuf_inject() routine).
272 * This is described in Guru Book.
275 lcs
.CS_Buffer
= &argbuff
[0];
278 * Special kludge for interactive filehandles (i. e. CLI windows).
279 * Read data only if filehandle's buffer is not empty. Otherwise
280 * read will cause opening CLI window and waiting for user's input.
281 * As a consequence we still can use ReadArgs() on input redirected
282 * from a file, even if we are started from Workbench (hypothetical
284 * This prevents opening a CLI window if the program was started from
285 * Workbench and redirected its Input() and Output() to own window,
286 * but still called ReadArgs() after redirection for some reason.
287 * Streams redirection is widely used in AROS startup code.
289 if (IsInteractive(input
))
291 struct FileHandle
*fh
= BADDR(input
);
293 notempty
= (fh
->fh_Pos
!= fh
->fh_End
);
297 FGets(input
, lcs
.CS_Buffer
, sizeof(argbuff
));
299 D(bug("[ReadArgs] Line: %s\n", argbuff
));
302 * If "!GETTEMPLATE!" is given as argument print the template and
303 * exit with an error code. This makes a "R" like tool more reliable.
307 !(rdargs
->RDA_Flags
& RDAF_NOPROMPT
)
309 (strncmp(argbuff
, "!GETTEMPLATE!", 13) == 0)
312 D(bug("[ReadArgs] !GETTEMPLATE! found\n"));
314 BPTR output
= Output();
316 if (FPuts(output
, template) || FPuts(output
, ": "))
318 ERROR(me
->pr_Result2
);
323 ERROR(me
->pr_Result2
);
326 ERROR(ERROR_BAD_TEMPLATE
);
331 for (; *cs1
!= '\0'; ++cs1
);
333 lcs
.CS_Length
= cs1
- lcs
.CS_Buffer
;
339 /* Check for optional reprompting */
340 if (!(rdargs
->RDA_Flags
& RDAF_NOPROMPT
))
342 if ((delthis
= is_question(cs
->CS_Buffer
, cs
->CS_Length
)))
344 /* '?' was found on the commandline. */
345 BPTR input
= Input();
346 BPTR output
= Output();
347 ULONG isize
= 0, ibuf
= 0;
349 ULONG helpdisplayed
= FALSE
;
351 /* Prompt for more input */
353 D(bug("[ReadArgs] '?' found, %d chars to be removed\n", delthis
));
354 D(bug("[ReadArgs] rdargs=0x%p\n", rdargs
));
355 D(if (rdargs
) bug ("[ReadArds] rdargs->RDA_ExtHelp=0x%p\n", rdargs
->RDA_ExtHelp
);)
357 if (FPuts(output
, template) || FPuts(output
, ": "))
359 ERROR(me
->pr_Result2
);
364 ERROR(me
->pr_Result2
);
367 cs
->CS_Length
-= delthis
;
368 ULONG memsize
= isize
= ibuf
= cs
->CS_Length
;
369 iline
= (STRPTR
) AllocVec(ibuf
, MEMF_ANY
);
370 CopyMem(cs
->CS_Buffer
, iline
, isize
);
374 /* Read a line in. */
380 iline
[isize
] = '\0'; /* end of string */
385 /* Buffer too small. Get a new one. */
390 newiline
= (STRPTR
) AllocVec(ibuf
, MEMF_ANY
);
391 if (newiline
== NULL
)
393 ERROR(ERROR_NO_FREE_STORE
);
397 CopyMem(iline
, newiline
, isize
);
405 if (is_file_not_buffer
)
413 if (cs
->CS_CurChr
>= cs
->CS_Length
)
416 c
= cs
->CS_Buffer
[cs
->CS_CurChr
++];
419 /* Check and write it. */
420 if (c
== EOF
&& me
->pr_Result2
)
422 ERROR(me
->pr_Result2
);
425 /* Fix short buffers to have a trailing '\n' */
426 if (c
== EOF
|| c
== '\0')
431 iline
[isize
] = '\0'; /* end of string */
433 D(iline
[isize
] = 0; bug("[ReadArgs] Size %d, line: '%s'\n", isize
, iline
));
435 /* if user entered single ? again or some string ending
436 with space and ? either display template again or
437 extended help if it's available */
438 if ( (delthis
= is_question(iline
, isize
))
439 && (memsize
<= (isize
- delthis
))
442 helpdisplayed
= TRUE
;
444 memsize
= isize
-= delthis
;
446 if(rdargs
->RDA_ExtHelp
!= NULL
)
448 if (FPuts(output
, rdargs
->RDA_ExtHelp
) || FPuts(output
, ": "))
449 ERROR(me
->pr_Result2
);
451 else if (FPuts(output
, template) || FPuts(output
, ": "))
453 ERROR(me
->pr_Result2
);
458 ERROR(me
->pr_Result2
);
462 helpdisplayed
= FALSE
;
463 } while(helpdisplayed
);
465 /* Prepare input source for new line. */
466 cs
->CS_Buffer
= iline
;
467 cs
->CS_Length
= isize
;
473 * Get enough space for string buffer.
474 * It's always smaller than the size of the input line+1.
477 strbuflen
= cs
->CS_Length
+ 1;
478 strbuf
= (STRPTR
) AllocVec(strbuflen
, MEMF_ANY
);
482 ERROR(ERROR_NO_FREE_STORE
);
485 /* Count the number of items in the template (number of ','+1). */
497 /* Use this count to get space for temporary flag array and result
499 flags
= (UBYTE
*) AllocVec(numargs
+ 1, MEMF_CLEAR
);
501 argbuf
= (STRPTR
*) AllocVec((numargs
+ 1) * sizeof(STRPTR
), MEMF_CLEAR
);
503 if (flags
== NULL
|| argbuf
== NULL
)
505 ERROR(ERROR_NO_FREE_STORE
);
508 /* Fill the flag array. */
514 /* A ',' means: goto next item. */
520 /* In case of a '/' use the next character as option. */
523 UBYTE argc
= ToUpper(*cs1
);
524 if (argc
>= 'A' && argc
<= 'Z')
525 *s2
|= argflags
[argc
- 'A'];
529 /* Add a dummy so that the whole line is processed (see below). */
533 * Now process commandline for the first time:
534 * Go from left to right and fill all items that need filling.
535 * If an item is given as 'OPTION=VALUE' or 'OPTION VALUE' fill
537 * NOTE: '<=' comparison is intentional here. When we allocated argbuf, we added one
538 * to the number of arguments. And right above we added fictional MULTIPLE flag.
539 * This is actually needed to make /S and /K working.
543 for (arg
= 0; arg
<= numargs
; arg
= nextarg
)
547 D(bug("[ReadArgs] Arg %d (0x%x) s1=&strbuf[%d], %d left\n", arg
, flags
[arg
], s1
-strbuf
, strbuflen
));
549 /* Out of buffer space?
550 * This should not have happened, some internal logic
553 if (strbuflen
== 0) {
554 D(bug("[ReadArgs] %d: INTERNAL ERROR: Ran out of buffer space.\n", arg
));
558 /* Skip /K options and options that are already done. */
559 if (flags
[arg
] & KEYWORD
|| argbuf
[arg
] != NULL
)
564 #if 0 /* stegerg: if so a template of CLOSE/S,QUICK/S,COMMAND/F would
565 not work correctly if command line for example is
566 "CLOSE QUICK" it would all end up being eaten by COMMAND/F
569 /* If the current option is of type /F do not look for keywords */
570 if ((flags
[arg
] & TYPEMASK
) != REST
)
574 /* Get item. Quoted items are never keywords. */
575 it
= READITEM(s1
, strbuflen
, cs
);
576 D(bug("[ReadArgs] Item %s type %d\n", s1
, it
));
578 if (it
== ITEM_UNQUOTED
)
580 /* Not quoted. Check if it's a keyword. */
581 item
= FindArg(template, s1
);
583 if (item
>= 0 && item
< numargs
&& argbuf
[item
] == NULL
)
585 D(bug("[ReadArgs] %d: Keyword \"%s\" (%d)\n", arg
, s1
, item
));
587 * It's a keyword. Fill it and retry the current option
593 /* /S /T may not be given as 'OPTION=VALUE'. */
594 if ((flags
[item
] & TYPEMASK
) != SWITCH
595 && (flags
[item
] & TYPEMASK
) != TOGGLE
)
598 it
= READITEM(s1
, strbuflen
, cs
);
600 if (it
== ITEM_EQUAL
)
602 it
= READITEM(s1
, strbuflen
, cs
);
603 } else if (it
!= ITEM_QUOTED
&& it
!= ITEM_UNQUOTED
) {
604 ERROR(ERROR_KEY_NEEDS_ARG
);
610 /* Check returncode of ReadItem(). */
611 if (it
== ITEM_EQUAL
)
613 ERROR(ERROR_BAD_TEMPLATE
);
615 else if (it
== ITEM_ERROR
)
617 ERROR(me
->pr_Result2
);
619 else if (it
== ITEM_NOTHING
)
625 /* /F takes all the rest, including extra spaces, =, and '"'
626 * NOTE: If the item was quoted, this will strip off the
627 * next '"' mark it sees.
629 if ((flags
[arg
] & TYPEMASK
) == REST
)
631 BOOL eat_quote
= (it
== ITEM_QUOTED
) ? TRUE
: FALSE
;
634 /* Skip past what ReadItem() just read.
636 while (*s1
&& strbuflen
> 0) {
642 * Put the rest into the buffer, including the separator
643 * ReadItem() actually ungets '\n' terminator. So if CurChr points to it,
644 * we don't need to adjust it. Otherwise we duplicate last character of arguments line.
646 if (cs
->CS_Buffer
[cs
->CS_CurChr
] != '\n')
648 s2
= &cs
->CS_Buffer
[cs
->CS_CurChr
];
650 while (cs
->CS_CurChr
< cs
->CS_Length
&&
657 if (eat_quote
&& *s2
== '"')
670 D(bug("[ReadArgs] /F copy: \"%s\" left=%d, CS_CurChr=%d, CS_Length=%d\n", argbuf
[arg
], strbuflen
, cs
->CS_CurChr
, cs
->CS_Length
));
675 if (flags
[arg
] & MULTIPLE
)
677 /* All /M arguments are stored in a buffer. */
678 if (multnum
>= multmax
)
680 /* Buffer too small. Get a new one. */
683 newmult
= (STRPTR
*) AllocVec(multmax
* sizeof(char *),
687 ERROR(ERROR_NO_FREE_STORE
);
690 CopyMemQuick((ULONG
*) multvec
, (ULONG
*) newmult
,
691 multnum
* sizeof(char *));
698 /* Put string into the buffer. */
699 multvec
[multnum
++] = s1
;
701 D(bug("[ReadArgs] %d: Multiple +\"%s\"\n", arg
, s1
));
704 /* Account for the \000 at the end. */
707 /* /M takes more than one argument, so retry. */
710 else if ((flags
[arg
] & TYPEMASK
) == SWITCH
711 || (flags
[arg
] & TYPEMASK
) == TOGGLE
)
713 /* /S or /T just set a flag */
714 argbuf
[arg
] = (char *) ~0;
715 D(bug("[ReadArgs] %d: Toggle\n", arg
));
717 else /* NORMAL || NUMERIC */
719 /* Put argument into argument buffer. */
721 D(bug("[ReadArgs] %d: Normal: \"%s\"\n", arg
, s1
));
725 /* Account for the \000 at the end. */
729 if (cs
->CS_CurChr
>= cs
->CS_Length
)
730 break; /* end of input */
733 /* Unfilled /A options steal Arguments from /M */
734 for (arg
= numargs
; arg
-- > 0;)
736 if (flags
[arg
] & REQUIRED
&& argbuf
[arg
] == NULL
737 && !(flags
[arg
] & MULTIPLE
))
739 if (flags
[arg
] & KEYWORD
)
741 /* /K/A argument, which insists on keyword
742 * being used, cannot be satisfied */
744 ERROR(ERROR_TOO_MANY_ARGS
); /* yes, strange error number,
745 * but it translates to "wrong
746 * number of arguments" */
752 /* No arguments left? Oh dear! */
753 ERROR(ERROR_REQUIRED_ARG_MISSING
);
756 argbuf
[arg
] = multvec
[--multnum
];
760 /* Put the rest of /M where it belongs */
761 for (arg
= 0; arg
< numargs
; arg
++)
763 if (flags
[arg
] & MULTIPLE
)
765 if (flags
[arg
] & REQUIRED
&& multnum
== 0)
767 ERROR(ERROR_REQUIRED_ARG_MISSING
);
772 /* NULL terminate it. */
773 if (multnum
>= multmax
)
777 newmult
= (STRPTR
*) AllocVec(multmax
* sizeof(STRPTR
),
782 ERROR(ERROR_NO_FREE_STORE
);
785 CopyMemQuick((ULONG
*) multvec
, (ULONG
*) newmult
,
786 multnum
* sizeof(char *));
793 multvec
[multnum
++] = NULL
;
794 argbuf
[arg
] = (STRPTR
) multvec
;
798 /* Shouldn't be necessary, but some buggy software relies on this */
806 /* There are some arguments left? Return error. */
807 if (multnum
!= 0 && arg
== numargs
)
809 ERROR(ERROR_TOO_MANY_ARGS
);
813 * The commandline is processed now. Put the results in the result array.
814 * Convert /N arguments by the way.
816 for (arg
= 0; arg
< numargs
; arg
++)
818 /* Just for the arguments given. */
819 if (argbuf
[arg
] != NULL
)
821 if (flags
[arg
] & MULTIPLE
)
823 array
[arg
] = (IPTR
) argbuf
[arg
];
825 if ((flags
[arg
] & TYPEMASK
) == NUMERIC
)
830 if (multnum
* 2 > multmax
)
832 multmax
= multnum
* 2;
833 newmult
= (STRPTR
*) AllocVec(multmax
* sizeof(STRPTR
),
838 ERROR(ERROR_NO_FREE_STORE
);
841 CopyMemQuick((ULONG
*) multvec
, (ULONG
*) newmult
,
842 multnum
* sizeof(char *));
849 array
[arg
] = (IPTR
) multvec
;
851 q
= (LONG
*) (multvec
+ multnum
);
855 /* Convert /N argument. */
856 chars
= StrToLong(*p
, q
);
858 if (chars
<= 0 || (*p
)[chars
])
860 /* Conversion failed. */
861 ERROR(ERROR_BAD_NUMBER
);
864 /* Put the result where it belongs. */
867 q
+= sizeof(IPTR
) / sizeof(LONG
);
873 switch (flags
[arg
] & TYPEMASK
)
878 /* Simple arguments are just copied. */
879 array
[arg
] = (IPTR
) argbuf
[arg
];
883 /* /T logically inverts the argument. */
884 array
[arg
] = array
[arg
] ? 0 : ~0;
888 /* Convert /N argument. */
889 /* Abuse the argbuf buffer. It's not needed anymore. */
890 numstr
= (CONST_STRPTR
)argbuf
[arg
];
891 chars
= StrToLong(numstr
, (LONG
*)&argbuf
[arg
]);
893 if (chars
<= 0 || numstr
[chars
] != '\0')
895 /* Conversion failed. */
896 ERROR(ERROR_BAD_NUMBER
);
899 /* Put the result where it belongs. */
900 array
[arg
] = (IPTR
) &argbuf
[arg
];
907 if (flags
[arg
] & MULTIPLE
)
909 /* Shouldn't be necessary, but some buggy software relies on this.
910 * IBrowse's URL field isn't set to zero.
912 array
[arg
] = (IPTR
)NULL
;
920 /* Cleanup and return. */
926 /* ReadArgs() failed. Clean everything up. */
929 if (rdargs
->RDA_Flags
& RDAF_ALLOCATED_BY_READARGS
)
940 me
->pr_Result2
= error
;
946 /* All went well. Prepare result and return. */
947 rdargs
->RDA_DAList
= (IPTR
) dalist
;
948 dalist
->ArgBuf
= argbuf
;
949 dalist
->StrBuf
= strbuf
;
950 dalist
->MultVec
= multvec
;
957 # include <dos/dos.h>
958 # include <dos/rdargs.h>
959 # include <utility/tagitem.h>
961 # include <proto/dos.h>
963 char cmlargs
[] = "TEST/A";
966 "This is exthelp for test\n"
972 LONG cmlvec
[CML_END
];
975 main(int argc
, char **argv
)
977 struct RDArgs
*rdargs
;
979 if ((rdargs
= AllocDosObject(DOS_RDARGS
, NULL
)))
981 rdargs
->RDA_ExtHelp
= usage
; /* FIX: why doesn't this work? */
983 if (!(ReadArgs(cmlargs
, cmlvec
, rdargs
)))
985 PrintFault(IoErr(), "AROS boot");
986 FreeDosObject(DOS_RDARGS
, rdargs
);
992 PrintFault(ERROR_NO_FREE_STORE
, "AROS boot");
997 FreeDosObject(DOS_RDARGS
, rdargs
);