News:

Masm32 SDK description, downloads and other helpful links
Message to All Guests
NB: Posting URL's See here: Posted URL Change

Main Menu

Command Line Options

Started by Biterider, July 17, 2024, 05:32:33 PM

Previous topic - Next topic

Biterider

Managing the command line options turned out to be a repetitive task that can be greatly simplified with some procedures I have come up with that I would like to share.

Starting from the following command line format:
MyApplication.exe -MyOption1 -MyOption2 ...
where MyOption can be a number, a quoted string, a bit position, a boolean or a single character, e.g.
MyApplication.exe -I:".\Windows Drivers\" -s:1 -W:42
There are 2 pieces of information needed. The first is the target structure where the options are stored and the second is the definition where the procedures take their information to process the switches.

Here I used a fictional structure that could look like this:
OPTIONS struct
  bShowUsage          BYTE      FALSE         ;-? command line switch
  pIncludeDirs        PSTRINGW  NULL          ;-I command line switch
  dSelectiveOutput    DWORD     0             ;-s command line switch
  dWarningLevel       DWORD     0             ;-W command line switch
OPTIONS ends

And the second one, in accordance with the first structure, could be like this:
OptionDefTable label OPTION_ENTRY
  OPTION_ENTRY <$OfsTBStr("-?"),  OPT_IS_BOOL,    offset OPTIONS.bShowUsage>
  OPTION_ENTRY <$OfsTBStr("-I:"), OPT_IS_STRING,  offset OPTIONS.pIncludeDirs>
  OPTION_ENTRY <$OfsTBStr("-s:"), OPT_IS_BIT,     offset OPTIONS.dSelectiveOutput>
  OPTION_ENTRY <$OfsTBStr("-W:"), OPT_IS_DECIMAL, offset OPTIONS.dWarningLevel>
  PSTRINGW NULL


Once this is done, only 3 procs need to be called:
.data
Options OPTIONS {}
.code
invoke GetCommandLine
invoke ParseCmdLineArgs, xax
mov pCmdLineArgList, xax
lea xdx, Options
invoke GetOptions, offset OptionDefTable, xdx, xax

Finally when you are done, free the allocated argument list (pCmdLineArgList) and all option strings.
MemFree pCmdLineArgList
invoke StrDispose Options.pIncludeDirs

The workhorses are the ParseCmdLineArgs and GetOptions procedures.
They can be downloaded fromof from the attachment or from https://github.com/ObjAsm/ObjAsm-C.2/blob/master/Code/ObjMem/Common/


Some definitions must be added:
OPT_IS_BOOL     equ 0
OPT_IS_BIT      equ 1
OPT_IS_CHAR     equ 2
OPT_IS_DECIMAL  equ 3
OPT_IS_STRING   equ 4

;Option table entry
OPTION_ENTRY struct
  pSwitch  PSTRINGW ?     ;BSTR
  bType    BYTE     ?
  xOffset  XWORD    ?
OPTION_ENTRY ends
POPTION_ENTRY typedef ptr OPTION_ENTRY

Notes:
- pSwitch points to a BSTR in the alt .const segment and can be created using the $OfsTBStr macro.
- The created option strings are WIDE (unicode) und must be disposed when no longer needed.


Regards, Biterider