home *** CD-ROM | disk | FTP | other *** search
/ Skunkware 98 / Skunkware 98.iso / osr5 / sco / scripts / admin / vectors < prev   
Encoding:
AWK Script  |  1997-08-26  |  37.5 KB  |  1,097 lines

  1. #!/usr/local/bin/gawk -f
  2. #!/usr/bin/awk -f
  3. # @(#) vectors.gawk 2.1 97/01/06
  4. # 93/10/21 John H. DuBois III (john@armory.com)
  5. # 94/03/09 Use gawk so - options can be given
  6. # 94/08/21 Warn about device name/filename mismatch
  7. # 94/09/27 Warn about multiple drivers using a vector.  Print cfg name.
  8. # 96/06/17 Deal with drivers that have multiple sdevice lines giving same intr
  9. # 96/06/23 Ignore cfg declarations of vec 0 (like hwconfig does).
  10. #          Changed s option to S; added ces options.
  11. # 96/11/25 Fixed recognition of sdevice comment lines.
  12.  
  13. # todo: Look at 'type' field for hwconfig name=adapter
  14. BEGIN {
  15.     Name = "vectors"
  16.     Usage = "Usage: " Name " [-acehsS] [sdevice-dir]"
  17.     Opts(Name,Usage,"acehsSx",0)
  18.     if ("h" in Options) {
  19.     printf \
  20. "%s: show vectors used in current kernel configuration\n"\
  21. "%s\n"\
  22. "For each vector used, %s prints the vector number, the name of the\n"\
  23. "driver that uses the vector according to the sdevice files, and the name\n"\
  24. "of the device that declared the vector at boot time.  For some vectors\n"\
  25. "that are in use, a driver name may not be printed because the driver the\n"\
  26. "interrupt should be delivered to autoconfigures it.  Also, for some\n"\
  27. "vectors a configuring-device name may not be printed because the driver\n"\
  28. "does not print a configuration line at boot time.\n"\
  29. "Options:\n"\
  30. "-a: Print status of all vectors (explicitly list those that are free)\n"\
  31. "-c: Print status only for vectors that are declared at boot time.\n"\
  32. "-s: Print status only for vectors that are enabled in sdevice files.\n"\
  33. "    The c and s options may be used together for greater exclusion.\n"\
  34. "-e: Print status only for external vectors.  This excludes vectors that\n"\
  35. "    are always used by the motherboard (clock, rtc, cn, and int2 chaining)\n"\
  36. "-h: Print this help.\n"\
  37. "-S: Show entire sdevice line for each vector in use.\n",
  38.     Name,Usage,Name
  39.     exit 0
  40.     }
  41.  
  42.     Debug = "x" in Options
  43.     sdevOnly = "s" in Options
  44.     cfgOnly = "c" in Options
  45.  
  46.     SdevDir = "/etc/conf/sdevice.d"
  47.     cmd = "cd " SdevDir "; for f in *; do echo $f; done"
  48.     ndev = 0
  49.     while (cmd | getline)
  50.     ReadSdev(SdevDir,$0)
  51.     close(cmd)
  52.     ReadCfg("/dev/string/cfg")
  53.  
  54.     if (!(cfgOnly || sdevOnly)) {
  55.     # Artificially add clock & rtc vectors
  56.     vectors[++ndev] = 0
  57.     vec2ind[0] = ndev
  58.     devices[ndev] = "[clock]"
  59.     sdevice[ndev] = "[clock]"
  60.     vectors[++ndev] = 8
  61.     vec2ind[8] = ndev
  62.     devices[ndev] = "[rtc]"
  63.     sdevice[ndev] = "[rtc]"
  64.  
  65.     # 9 & 2 are the same vector on ISA machines.  Show their chaining.
  66.     if (!(9 in vec2ind)) {
  67.         vectors[++ndev] = 9
  68.         vec2ind[9] = ndev
  69.         devices[ndev] = "[int2]"
  70.         sdevice[ndev] = "[int2]"
  71.     }
  72.     else if (!(2 in vec2ind)) {
  73.         vectors[++ndev] = 2
  74.         vec2ind[2] = ndev
  75.         devices[ndev] = "[int9]"
  76.         sdevice[ndev] = "[int9]"
  77.     }
  78.     }
  79.  
  80.     if ("e" in Options)
  81.     MakeSet(Exclude,"[clock],[rtc],[int9],[int2],cn",",")
  82.  
  83.     # Add 'free' line to unused vectors
  84.     if ("a" in Options) {
  85.     for (i = 2; i <= 15; i++)
  86.         if (!(i in vec2ind)) {
  87.         vectors[++ndev] = i
  88.         devices[ndev] = sdevice[ndev] = "** free"
  89.         }
  90.     }
  91.  
  92.     qsortArbIndByValue(vectors,k)
  93.     if ("S" in Options) {
  94.     print \
  95. "Device\tConfig\tUnit\tIPL\tIntType\tIntrupt\tStartIO\tEndIO\tStrtMem\tEndMem"
  96.     for (i = 1; i <= ndev; i++) {
  97.         sdev = sdevice[k[i]]
  98.         if (sdev in Exclude)
  99.         continue
  100.         if (sdev !~ "\t") {
  101.         if (!sdevOnly)
  102.             printf "%s\t\t\t\t\t%d\n",sdev,vectors[k[i]]
  103.         }
  104.         else
  105.         print sdev
  106.     }
  107.     }
  108.     else {
  109.     Fmt = "%3s  %-8s  %s\n"
  110.     printf Fmt,"Vec","Driver","Cfg-name"
  111.     for (i = 1; i <= ndev; i++) {
  112.         sdev = devices[k[i]]
  113.         cfg = CfgName[k[i]]
  114.         if (!(sdevOnly && cfg == "" || cfgOnly && sdev == "" ||
  115.         sdev in Exclude))
  116.         printf Fmt,vectors[k[i]],sdev,cfg
  117.     }
  118.     }
  119. }
  120.  
  121. # Sets CfgName[]
  122. function ReadCfg(File,  Vec,Device,ret,Cmd) {
  123.     # Output of /dev/string/cfg (which may not exist) looks like this:
  124.     # cfgname    base addr    vec    dma    other
  125.     # %floppy   0x03F2-0x03F7    6    2    unit=0 type=135ds18
  126.     if (Debug)
  127.     printf "Reading file <%s>\n",File > "/dev/stderr"
  128.  
  129.     # gawk cannot read /dev/string/cfg for some reason.  Use cat.
  130.     Cmd = "cat " File
  131.     while ((ret = (Cmd | getline)) == 1) {
  132.     Device = $1
  133.     sub("^%","",Device)
  134.     Vec = $3
  135.     if (Vec != "-" && Vec != "0") {
  136.         if (Vec !~ /^[0-9]+$/) {
  137.         printf "%s: Warning: Bad vector '%s' given on this line:\n%s\n",
  138.         Name,Vec,$0
  139.         continue
  140.         }
  141.         if (Debug)
  142.         printf "cfg name for vec %s is %s\n",
  143.         Vec,Device > "/dev/stderr"
  144.         if (!(0 <= Vec && Vec <= 15)) {
  145.         printf "Invalid vector %s for device %s (file %s)\n",
  146.         Vec,Device,File > "/dev/stderr"
  147.         continue
  148.         }
  149.         if (Vec in vec2ind)
  150.         CfgName[vec2ind[Vec]] = Device
  151.         else {
  152.         vectors[++ndev] = Vec
  153.         CfgName[ndev] = Device
  154.         vec2ind[Vec] = ndev
  155.         }
  156.     }
  157.     }
  158.     if (Debug)
  159.     printf "Read of %s returned %d\n",File,ret
  160.     close(File)
  161. }
  162.  
  163. # Stores sdevice data into these global arrays:
  164. # vectors[i]    Vector
  165. # devices[i]    Driver name
  166. # sdevice[i]    Sdevice line
  167. # vec2ind[vec]    Vector to index map
  168. # Also uses global Warned[].
  169. function ReadSdev(Dir,File,  InFile,Vec,Device) {
  170.     InFile = Dir "/" File
  171.     while ((getline < InFile) == 1) {
  172.     Vec = $6
  173.     Device = $1
  174.     # Process sdevice lines for drivers that are enabled & use an interrupt
  175.     if (Device !~ /^\*/ && $2 == "Y" && Vec != 0) {
  176.         if (!(0 <= Vec && Vec <= 15)) {
  177.         printf "Invalid vector %s for device %s (file %s)\n",
  178.         Vec,Device,File > "/dev/stderr"
  179.         continue
  180.         }
  181.         if (Vec in vec2ind) {
  182.         if (devices[vec2ind[Vec]] == Device) {
  183.             # driver that has multiple sdevice lines giving same
  184.             # interrupt
  185.             sdevice[ndev] = sdevice[ndev] "\n" $0
  186.         }
  187.         else
  188.             printf \
  189.     "Warning: vector %d, used by driver '%s', also used driver '%s'.\n",
  190.             Vec,devices[vec2ind[Vec]],Device  > "/dev/stderr"
  191.         continue
  192.         }
  193.         if (Device != File && !((Device,File) in Warned)) {
  194.         printf \
  195.         "Note: Device name '%s' does not match filename '%s'\n",
  196.         Device,File  > "/dev/stderr"
  197.         Warned[Device,File]    # Only warn once
  198.         }
  199.         vectors[++ndev] = Vec
  200.         vec2ind[Vec] = ndev
  201.         devices[ndev] = Device
  202.         sdevice[ndev] = $0
  203.     }
  204.     }
  205.     close(InFile)
  206. }
  207.  
  208. ### Start of ProcArgs library
  209. # @(#) ProcArgs 1.11 96/12/08
  210. # 92/02/29 john h. dubois iii (john@armory.com)
  211. # 93/07/18 Added "#" arg type
  212. # 93/09/26 Do not count -h against MinArgs
  213. # 94/01/01 Stop scanning at first non-option arg.  Added ">" option type.
  214. #          Removed meaning of "+" or "-" by itself.
  215. # 94/03/08 Added & option and *()< option types.
  216. # 94/04/02 Added NoRCopt to Opts()
  217. # 94/06/11 Mark numeric variables as such.
  218. # 94/07/08 Opts(): Do not require any args if h option is given.
  219. # 95/01/22 Record options given more than once.  Record option num in argv.
  220. # 95/06/08 Added ExclusiveOptions().
  221. # 96/01/20 Let rcfiles be a colon-separated list of filenames.
  222. #          Expand $VARNAME at the start of its filenames.
  223. #          Let varname=0 and -option- turn off an option.
  224. # 96/05/05 Changed meaning of 7th arg to Opts; now can specify exactly how many
  225. #          of the vars should be searched for in the environment.
  226. #          Check for duplicate rcfiles.
  227. # 96/05/13 Return more specific error values.  Note: ProcArgs() and InitOpts()
  228. #          now return various negatives values on error, not just -1, and
  229. #          Opts() may set Err to various positive values, not just 1.
  230. #          Added AllowUnrecOpt.
  231. # 96/05/23 Check type given for & option
  232. # 96/06/15 Re-port to awk
  233. # 96/10/01 Moved file-reading code into ReadConfFile(), so that it can be
  234. #          used by other functions.
  235. # 96/10/15 Added OptChars
  236. # 96/11/01 Added exOpts arg to Opts()
  237. # 96/11/16 Added ; type
  238. # 96/12/08 Added Opt2Set() & Opt2Sets()
  239. # 96/12/27 Added CmdLineOpt()
  240.  
  241. # optlist is a string which contains all of the possible command line options.
  242. # A character followed by certain characters indicates that the option takes
  243. # an argument, with type as follows:
  244. # :    String argument
  245. # ;    Non-empty string argument
  246. # *    Floating point argument
  247. # (    Non-negative floating point argument
  248. # )    Positive floating point argument
  249. # #    Integer argument
  250. # <    Non-negative integer argument
  251. # >    Positive integer argument
  252. # The only difference the type of argument makes is in the runtime argument
  253. # error checking that is done.
  254.  
  255. # The & option is a special case used to get numeric options without the
  256. # user having to give an option character.  It is shorthand for [-+.0-9].
  257. # If & is included in optlist and an option string that begins with one of
  258. # these characters is seen, the value given to "&" will include the first
  259. # char of the option.  & must be followed by a type character other than ":"
  260. # or ";".
  261. # Note that if e.g. &> is given, an option of -.5 will produce an error.
  262.  
  263. # Strings in argv[] which begin with "-" or "+" are taken to be
  264. # strings of options, except that a string which consists solely of "-"
  265. # or "+" is taken to be a non-option string; like other non-option strings,
  266. # it stops the scanning of argv and is left in argv[].
  267. # An argument of "--" or "++" also stops the scanning of argv[] but is removed.
  268. # If an option takes an argument, the argument may either immediately
  269. # follow it or be given separately.
  270. # "-" and "+" options are treated the same.  "+" is allowed because most awks
  271. # take any -options to be arguments to themselves.  gawk 2.15 was enhanced to
  272. # stop scanning when it encounters an unrecognized option, though until 2.15.5
  273. # this feature had a flaw that caused problems in some cases.  See the OptChars
  274. # parameter to explicitly set the option-specifier characters.
  275.  
  276. # If an option that does not take an argument is given,
  277. # an index with its name is created in Options and its value is set to the
  278. # number of times it occurs in argv[].
  279.  
  280. # If an option that does take an argument is given, an index with its name is
  281. # created in Options and its value is set to the value of the argument given
  282. # for it, and Options[option-name,"count"] is (initially) set to the 1.
  283. # If an option that takes an argument is given more than once,
  284. # Options[option-name,"count"] is incremented, and the value is assigned to
  285. # the index (option-name,instance) where instance is 2 for the second occurance
  286. # of the option, etc.
  287. # In other words, the first time an option with a value is encountered, the
  288. # value is assigned to an index consisting only of its name; for any further
  289. # occurances of the option, the value index has an extra (count) dimension.
  290.  
  291. # The sequence number for each option found in argv[] is stored in
  292. # Options[option-name,"num",instance], where instance is 1 for the first
  293. # occurance of the option, etc.  The sequence number starts at 1 and is
  294. # incremented for each option, both those that have a value and those that
  295. # do not.  Options set from a config file have a value of 0 assigned to this.
  296.  
  297. # Options and their arguments are deleted from argv.
  298. # Note that this means that there may be gaps left in the indices of argv[].
  299. # If compress is nonzero, argv[] is packed by moving its elements so that
  300. # they have contiguous integer indices starting with 0.
  301. # Option processing will stop with the first unrecognized option, just as
  302. # though -- was given except that unlike -- the unrecognized option will not be
  303. # removed from ARGV[].  Normally, an error value is returned in this case.
  304. # If AllowUnrecOpt is true, it is not an error for an unrecognized option to
  305. # be found, so the number of remaining arguments is returned instead.
  306. # If OptChars is not a null string, it is the set of characters that indicate
  307. # that an argument is an option string if the string begins with one of the
  308. # characters.  A string consisting solely of two of the same option-indicator
  309. # characters stops the scanning of argv[].  The default is "-+".
  310. # argv[0] is not examined.
  311. # The number of arguments left in argc is returned.
  312. # If an error occurs, the global string OptErr is set to an error message
  313. # and a negative value is returned.
  314. # Current error values:
  315. # -1: option that required an argument did not get it.
  316. # -2: argument of incorrect type supplied for an option.
  317. # -3: unrecognized (invalid) option.
  318. function ProcArgs(argc,argv,OptList,Options,compress,AllowUnrecOpt,OptChars,
  319. ArgNum,ArgsLeft,Arg,ArgLen,ArgInd,Option,Pos,NumOpt,Value,HadValue,specGiven,
  320. NeedNextOpt,GotValue,OptionNum,Escape,dest,src,count,c,OptTerm,OptCharSet)
  321. {
  322. # ArgNum is the index of the argument being processed.
  323. # ArgsLeft is the number of arguments left in argv.
  324. # Arg is the argument being processed.
  325. # ArgLen is the length of the argument being processed.
  326. # ArgInd is the position of the character in Arg being processed.
  327. # Option is the character in Arg being processed.
  328. # Pos is the position in OptList of the option being processed.
  329. # NumOpt is true if a numeric option may be given.
  330.     ArgsLeft = argc
  331.     NumOpt = index(OptList,"&")
  332.     OptionNum = 0
  333.     if (OptChars == "")
  334.     OptChars = "-+"
  335.     while (OptChars != "") {
  336.     c = substr(OptChars,1,1)
  337.     OptChars = substr(OptChars,2)
  338.     OptCharSet[c]
  339.     OptTerm[c c]
  340.     }
  341.     for (ArgNum = 1; ArgNum < argc; ArgNum++) {
  342.     Arg = argv[ArgNum]
  343.     if (length(Arg) < 2 || !((specGiven = substr(Arg,1,1)) in OptCharSet))
  344.         break    # Not an option; quit
  345.     if (Arg in OptTerm) {
  346.         delete argv[ArgNum]
  347.         ArgsLeft--
  348.         break
  349.     }
  350.     ArgLen = length(Arg)
  351.     for (ArgInd = 2; ArgInd <= ArgLen; ArgInd++) {
  352.         Option = substr(Arg,ArgInd,1)
  353.         if (NumOpt && Option ~ /[-+.0-9]/) {
  354.         # If this option is a numeric option, make its flag be & and
  355.         # its option string flag position be the position of & in
  356.         # the option string.
  357.         Option = "&"
  358.         Pos = NumOpt
  359.         # Prefix Arg with a char so that ArgInd will point to the
  360.         # first char of the numeric option.
  361.         Arg = "&" Arg
  362.         ArgLen++
  363.         }
  364.         # Find position of flag in option string, to get its type (if any).
  365.         # Disallow & as literal flag.
  366.         else if (!(Pos = index(OptList,Option)) || Option == "&") {
  367.         if (AllowUnrecOpt) {
  368.             Escape = 1
  369.             break
  370.         }
  371.         else {
  372.             OptErr = "Invalid option: " specGiven Option
  373.             return -3
  374.         }
  375.         }
  376.  
  377.         # Find what the value of the option will be if it takes one.
  378.         # NeedNextOpt is true if the option specifier is the last char of
  379.         # this arg, which means that if the option requires a value it is
  380.         # the next arg.
  381.         if (NeedNextOpt = (ArgInd >= ArgLen)) { # Value is the next arg
  382.         if (GotValue = ArgNum + 1 < argc)
  383.             Value = argv[ArgNum+1]
  384.         }
  385.         else {    # Value is included with option
  386.         Value = substr(Arg,ArgInd + 1)
  387.         GotValue = 1
  388.         }
  389.  
  390.         if (HadValue = AssignVal(Option,Value,Options,
  391.         substr(OptList,Pos + 1,1),GotValue,"",++OptionNum,!NeedNextOpt,
  392.         specGiven)) {
  393.         if (HadValue < 0)    # error occured
  394.             return HadValue
  395.         if (HadValue == 2)
  396.             ArgInd++    # Account for the single-char value we used.
  397.         else {
  398.             if (NeedNextOpt) {    # option took next arg as value
  399.             delete argv[++ArgNum]
  400.             ArgsLeft--
  401.             }
  402.             break    # This option has been used up
  403.         }
  404.         }
  405.     }
  406.     if (Escape)
  407.         break
  408.     # Do not delete arg until after processing of it, so that if it is not
  409.     # recognized it can be left in ARGV[].
  410.     delete argv[ArgNum]
  411.     ArgsLeft--
  412.     }
  413.     if (compress != 0) {
  414.     dest = 1
  415.     src = argc - ArgsLeft + 1
  416.     for (count = ArgsLeft - 1; count; count--) {
  417.         ARGV[dest] = ARGV[src]
  418.         dest++
  419.         src++
  420.     }
  421.     }
  422.     return ArgsLeft
  423. }
  424.  
  425. # Assignment to values in Options[] occurs only in this function.
  426. # Option: Option specifier character.
  427. # Value: Value to be assigned to option, if it takes a value.
  428. # Options[]: Options array to return values in.
  429. # ArgType: Argument type specifier character.
  430. # GotValue: Whether any value is available to be assigned to this option.
  431. # Name: Name of option being processed.
  432. # OptionNum: Number of this option (starting with 1) if set in argv[],
  433. #     or 0 if it was given in a config file or in the environment.
  434. # SingleOpt: true if the value (if any) that is available for this option was
  435. #     given as part of the same command line arg as the option.  Used only for
  436. #     options from the command line.
  437. # specGiven is the option specifier character use, if any (e.g. - or +),
  438. # for use in error messages.
  439. # Global variables: OptErr
  440. # Return value: negative value on error, 0 if option did not require an
  441. # argument, 1 if it did & used the whole arg, 2 if it required just one char of
  442. # the arg.
  443. # Current error values:
  444. # -1: Option that required an argument did not get it.
  445. # -2: Value of incorrect type supplied for option.
  446. # -3: Bad type given for option &
  447. function AssignVal(Option,Value,Options,ArgType,GotValue,Name,OptionNum,
  448. SingleOpt,specGiven,  UsedValue,Err,NumTypes) {
  449.     # If option takes a value...    [
  450.     NumTypes = "*()#<>]"
  451.     if (Option == "&" && ArgType !~ "[" NumTypes) {    # ]
  452.     OptErr = "Bad type given for & option"
  453.     return -3
  454.     }
  455.  
  456.     if (UsedValue = (ArgType ~ "[:;" NumTypes)) {    # ]
  457.     if (!GotValue) {
  458.         if (Name != "")
  459.         OptErr = "Variable requires a value -- " Name
  460.         else
  461.         OptErr = "option requires an argument -- " Option
  462.         return -1
  463.     }
  464.     if ((Err = CheckType(ArgType,Value,Option,Name,specGiven)) != "") {
  465.         OptErr = Err
  466.         return -2
  467.     }
  468.     # Mark this as a numeric variable; will be propogated to Options[] val.
  469.     if (ArgType != ":" && ArgType != ";")
  470.         Value += 0
  471.     if ((Instance = ++Options[Option,"count"]) > 1)
  472.         Options[Option,Instance] = Value
  473.     else
  474.         Options[Option] = Value
  475.     }
  476.     # If this is an environ or rcfile assignment & it was given a value...
  477.     else if (!OptionNum && Value != "") {
  478.     UsedValue = 1
  479.     # If the value is "0" or "-" and this is the first instance of it,
  480.     # do not set Options[Option]; this allows an assignment in an rcfile to
  481.     # turn off an option (for the simple "Option in Options" test) in such
  482.     # a way that it cannot be turned on in a later file.
  483.     if (!(Option in Options) && (Value == "0" || Value == "-"))
  484.         Instance = 1
  485.     else
  486.         Instance = ++Options[Option]
  487.     # Save the value even though this is a flag
  488.     Options[Option,Instance] = Value
  489.     }
  490.     # If this is a command line flag and has a - following it in the same arg,
  491.     # it is being turned off.
  492.     else if (OptionNum && SingleOpt && substr(Value,1,1) == "-") {
  493.     UsedValue = 2
  494.     if (Option in Options)
  495.         Instance = ++Options[Option]
  496.     else
  497.         Instance = 1
  498.     Options[Option,Instance]
  499.     }
  500.     # If this is a flag assignment without a value, increment the count for the
  501.     # flag unless it was turned off.  The indicator for a flag being turned off
  502.     # is that the flag index has not been set in Options[] but it has an
  503.     # instance count.
  504.     else if (Option in Options || !((Option,1) in Options))
  505.     # Increment number of times this flag seen; will inc null value to 1
  506.     Instance = ++Options[Option]
  507.     Options[Option,"num",Instance] = OptionNum
  508.     return UsedValue
  509. }
  510.  
  511. # Option is the option letter
  512. # Value is the value being assigned
  513. # Name is the var name of the option, if any
  514. # ArgType is one of:
  515. # :    String argument
  516. # ;    Non-null string argument
  517. # *    Floating point argument
  518. # (    Non-negative floating point argument
  519. # )    Positive floating point argument
  520. # #    Integer argument
  521. # <    Non-negative integer argument
  522. # >    Positive integer argument
  523. # specGiven is the option specifier character use, if any (e.g. - or +),
  524. # for use in error messages.
  525. # Returns null on success, err string on error
  526. function CheckType(ArgType,Value,Option,Name,specGiven,  Err,ErrStr) {
  527.     if (ArgType == ":")
  528.     return ""
  529.     if (ArgType == ";") {
  530.     if (Value == "")
  531.         Err = "must be a non-empty string"
  532.     }
  533.     # A number begins with optional + or -, and is followed by a string of
  534.     # digits or a decimal with digits before it, after it, or both
  535.     else if (Value !~ /^[-+]?([0-9]+|[0-9]*\.[0-9]+|[0-9]+\.)$/)
  536.     Err = "must be a number"
  537.     else if (ArgType ~ "[#<>]" && Value ~ /\./)
  538.     Err = "may not include a fraction"
  539.     else if (ArgType ~ "[()<>]" && Value < 0)
  540.     Err = "may not be negative"
  541.     # (
  542.     else if (ArgType ~ "[)>]" && Value == 0)
  543.     Err = "must be a positive number"
  544.     if (Err != "") {
  545.     ErrStr = "Bad value \"" Value "\".  Value assigned to "
  546.     if (Name != "")
  547.         return ErrStr "variable " substr(Name,1,1) " " Err
  548.     else {
  549.         if (Option == "&")
  550.         Option = Value
  551.         return ErrStr "option " specGiven substr(Option,1,1) " " Err
  552.     }
  553.     }
  554.     else
  555.     return ""
  556. }
  557.  
  558. # Note: only the above functions are needed by ProcArgs.
  559. # The rest of these functions call ProcArgs() and also do other
  560. # option-processing stuff.
  561.  
  562. # Opts: Process command line arguments.
  563. # Opts processes command line arguments using ProcArgs()
  564. # and checks for errors.  If an error occurs, a message is printed
  565. # and the program is exited.
  566. #
  567. # Input variables:
  568. # Name is the name of the program, for error messages.
  569. # Usage is a usage message, for error messages.
  570. # OptList the option description string, as used by ProcArgs().
  571. # MinArgs is the minimum number of non-option arguments that this
  572. # program should have, non including ARGV[0] and +h.
  573. # If the program does not require any non-option arguments,
  574. # MinArgs should be omitted or given as 0.
  575. # rcFiles, if given, is a colon-seprated list of filenames to read for
  576. # variable initialization.  If a filename begins with ~/, the ~ is replaced
  577. # by the value of the environment variable HOME.  If a filename begins with
  578. # $, the part from the character after the $ up until (but not including)
  579. # the first character not in [a-zA-Z0-9_] will be searched for in the
  580. # environment; if found its value will be substituted, if not the filename will
  581. # be discarded.
  582. # rcfiles are read in the order given.
  583. # Values given in them will not override values given on the command line,
  584. # and values given in later files will not override those set in earlier
  585. # files, because AssignVal() will store each with a different instance index.
  586. # The first instance of each variable, either on the command line or in an
  587. # rcfile, will be stored with no instance index, and this is the value
  588. # normally used by programs that call this function.
  589. # VarNames is a comma-separated list of variable names to map to options,
  590. # in the same order as the options are given in OptList.
  591. # If EnvSearch is given and nonzero, the first EnvSearch variables will also be
  592. # searched for in the environment.  If set to -1, all values will be searched
  593. # for in the environment.  Values given in the environment will override
  594. # those given in the rcfiles but not those given on the command line.
  595. # NoRCopt, if given, is an additional letter option that if given on the
  596. # command line prevents the rcfiles from being read.
  597. # See ProcArgs() for a description of AllowUnRecOpt and optChars, and
  598. # ExclusiveOptions() for a description of exOpts.
  599. # Special options:
  600. # If x is made an option and is given, some debugging info is output.
  601. # h is assumed to be the help option.
  602.  
  603. # Global variables:
  604. # The command line arguments are taken from ARGV[].
  605. # The arguments that are option specifiers and values are removed from
  606. # ARGV[], leaving only ARGV[0] and the non-option arguments.
  607. # The number of elements in ARGV[] should be in ARGC.
  608. # After processing, ARGC is set to the number of elements left in ARGV[].
  609. # The option values are put in Options[].
  610. # On error, Err is set to a positive integer value so it can be checked for in
  611. # an END block.
  612. # Return value: The number of elements left in ARGV is returned.
  613. # Must keep OptErr global since it may be set by InitOpts().
  614. function Opts(Name,Usage,OptList,MinArgs,rcFiles,VarNames,EnvSearch,NoRCopt,
  615. AllowUnrecOpt,optChars,exOpts,  ArgsLeft,e) {
  616.     if (MinArgs == "")
  617.     MinArgs = 0
  618.     ArgsLeft = ProcArgs(ARGC,ARGV,OptList NoRCopt,Options,1,AllowUnrecOpt,
  619.     optChars)
  620.     if (ArgsLeft < (MinArgs+1) && !("h" in Options)) {
  621.     if (ArgsLeft >= 0) {
  622.         OptErr = "Not enough arguments"
  623.         Err = 4
  624.     }
  625.     else
  626.         Err = -ArgsLeft
  627.     printf "%s: %s.\nUse -h for help.\n%s\n",
  628.     Name,OptErr,Usage > "/dev/stderr"
  629.     exit 1
  630.     }
  631.     if (rcFiles != "" && (NoRCopt == "" || !(NoRCopt in Options)) &&
  632.     (e = InitOpts(rcFiles,Options,OptList,VarNames,EnvSearch)) < 0)
  633.     {
  634.     print Name ": " OptErr ".\nUse -h for help." > "/dev/stderr"
  635.     Err = -e
  636.     exit 1
  637.     }
  638.     if ((exOpts != "") && ((OptErr = ExclusiveOptions(exOpts,Options)) != ""))
  639.     {
  640.     printf "%s: Error: %s\n",Name,OptErr > "/dev/stderr"
  641.     Err = 1
  642.     exit 1
  643.     }
  644.     return ArgsLeft
  645. }
  646.  
  647. # ReadConfFile(): Read a file containing var/value assignments, in the form
  648. # <variable-name><assignment-char><value>.
  649. # Whitespace (spaces and tabs) around a variable (leading whitespace on the
  650. # line and whitespace between the variable name and the assignment character) 
  651. # is stripped.  Lines that do not contain an assignment operator or which
  652. # contain a null variable name are ignored, other than possibly being noted in
  653. # the return value.  If more than one assignment is made to a variable, the
  654. # first assignment is used.
  655. # Input variables:
  656. # File is the file to read.
  657. # Comment is the line-comment character.  If it is found as the first non-
  658. #     whitespace character on a line, the line is ignored.
  659. # Assign is the assignment string.  The first instance of Assign on a line
  660. #     separates the variable name from its value.
  661. # If StripWhite is true, whitespace around the value (whitespace between the
  662. #     assignment char and trailing whitespace on the line) is stripped.
  663. # VarPat is a pattern that variable names must match.  
  664. #     Example: "^[a-zA-Z][a-zA-Z0-9]+$"
  665. # If FlagsOK is true, variables are allowed to be "set" by being put alone on
  666. #     a line; no assignment operator is needed.  These variables are set in
  667. #     the output array with a null value.  Lines containing nothing but
  668. #     whitespace are still ignored.
  669. # Output variables:
  670. # Values[] contains the assignments, with the indexes being the variable names
  671. #     and the values being the assigned values.
  672. # Lines[] contains the line number that each variable occured on.  A flag set
  673. #     is record by giving it an index in Lines[] but not in Values[].
  674. # Return value:
  675. # If any errors occur, a string consisting of descriptions of the errors
  676. # separated by newlines is returned.  In no case will the string start with a
  677. # numeric value.  If no errors occur,  the number of lines read is returned.
  678. function ReadConfigFile(Values,Lines,File,Comment,Assign,StripWhite,VarPat,
  679. FlagsOK,
  680. Line,Status,Errs,AssignLen,LineNum,Var,Val) {
  681.     if (Comment != "")
  682.     Comment = "^" Comment
  683.     AssignLen = length(Assign)
  684.     if (VarPat == "")
  685.     VarPat = "."    # null varname not allowed
  686.     while ((Status = (getline Line < File)) == 1) {
  687.     LineNum++
  688.     sub("^[ \t]+","",Line)
  689.     if (Line == "")        # blank line
  690.         continue
  691.     if (Comment != "" && Line ~ Comment)
  692.         continue
  693.     if (Pos = index(Line,Assign)) {
  694.         Var = substr(Line,1,Pos-1)
  695.         Val = substr(Line,Pos+AssignLen)
  696.         if (StripWhite) {
  697.         sub("^[ \t]+","",Val)
  698.         sub("[ \t]+$","",Val)
  699.         }
  700.     }
  701.     else {
  702.         Var = Line    # If no value, var is entire line
  703.         Val = ""
  704.     }
  705.     if (!FlagsOK && Val == "") {
  706.         Errs = Errs \
  707.         sprintf("\nBad assignment on line %d of file %s: %s",
  708.         LineNum,File,Line)
  709.         continue
  710.     }
  711.     sub("[ \t]+$","",Var)
  712.     if (Var !~ VarPat) {
  713.         Errs = Errs sprintf("\nBad variable name on line %d of file %s: %s",
  714.         LineNum,File,Var)
  715.         continue
  716.     }
  717.     if (!(Var in Lines)) {
  718.         Lines[Var] = LineNum
  719.         if (Pos)
  720.         Values[Var] = Val
  721.     }
  722.     }
  723.     if (Status)
  724.     Errs = Errs "\nCould not read file " File
  725.     close(File)
  726.     return Errs == "" ? LineNum : substr(Errs,2)    # Skip first newline
  727. }
  728.  
  729. # Variables:
  730. # Data is stored in Options[].
  731. # rcFiles, OptList, VarNames, and EnvSearch are as as described for Opts().
  732. # Global vars:
  733. # Sets OptErr.  Uses ENVIRON[].
  734. # If anything is read from any of the rcfiles, sets READ_RCFILE to 1.
  735. function InitOpts(rcFiles,Options,OptList,VarNames,EnvSearch,
  736. Line,Var,Pos,Vars,Map,CharOpt,NumVars,TypesInd,Types,Type,Ret,i,rcFile,
  737. fNames,numrcFiles,filesRead,Err,Values,retStr) {
  738.     split("",filesRead,"")    # make awk know this is an array
  739.     NumVars = split(VarNames,Vars,",")
  740.     TypesInd = Ret = 0
  741.     if (EnvSearch == -1)
  742.     EnvSearch = NumVars
  743.     for (i = 1; i <= NumVars; i++) {
  744.     Var = Vars[i]
  745.     CharOpt = substr(OptList,++TypesInd,1)
  746.     if (CharOpt ~ "^[:;*()#<>&]$")
  747.         CharOpt = substr(OptList,++TypesInd,1)
  748.     Map[Var] = CharOpt
  749.     Types[Var] = Type = substr(OptList,TypesInd+1,1)
  750.     # Do not overwrite entries from environment
  751.     if (i <= EnvSearch && Var in ENVIRON &&
  752.     (Err = AssignVal(CharOpt,ENVIRON[Var],Options,Type,1,Var,0)) < 0)
  753.         return Err
  754.     }
  755.  
  756.     numrcFiles = split(rcFiles,fNames,":")
  757.     for (i = 1; i <= numrcFiles; i++) {
  758.     rcFile = fNames[i]
  759.     if (rcFile ~ "^~/")
  760.         rcFile = ENVIRON["HOME"] substr(rcFile,2)
  761.     else if (rcFile ~ /^\$/) {
  762.         rcFile = substr(rcFile,2)
  763.         match(rcFile,"^[a-zA-Z0-9_]*")
  764.         envvar = substr(rcFile,1,RLENGTH)
  765.         if (envvar in ENVIRON)
  766.         rcFile = ENVIRON[envvar] substr(rcFile,RLENGTH+1)
  767.         else
  768.         continue
  769.     }
  770.     if (rcFile in filesRead)
  771.         continue
  772.     # rcfiles are liable to be given more than once, e.g. UHOME and HOME
  773.     # may be the same
  774.     filesRead[rcFile]
  775.     if ("x" in Options)
  776.         printf "Reading configuration file %s\n",rcFile > "/dev/stderr"
  777.     retStr = ReadConfigFile(Values,Lines,rcFile,"#","=",0,"",1)
  778.     if (retStr > 0)
  779.         READ_RCFILE = 1
  780.     else if (ret != "") {
  781.         OptErr = retStr
  782.         Ret = -1
  783.     }
  784.     for (Var in Lines)
  785.         if (Var in Map) {
  786.         if ((Err = AssignVal(Map[Var],
  787.         Var in Values ? Values[Var] : "",Options,Types[Var],
  788.         Var in Values,Var,0)) < 0)
  789.             return Err
  790.         }
  791.         else {
  792.         OptErr = sprintf(\
  793.         "Unknown var \"%s\" assigned to on line %d\nof file %s",Var,
  794.         Lines[Var],rcFile)
  795.         Ret = -1
  796.         }
  797.     }
  798.  
  799.     if ("x" in Options)
  800.     for (Var in Map)
  801.         if (Map[Var] in Options)
  802.         printf "(%s) %s=%s\n",Map[Var],Var,Options[Map[Var]] > \
  803.         "/dev/stderr"
  804.         else
  805.         printf "(%s) %s not set\n",Map[Var],Var > "/dev/stderr"
  806.     return Ret
  807. }
  808.  
  809. # OptSets is a semicolon-separated list of sets of option sets.
  810. # Within a list of option sets, the option sets are separated by commas.  For
  811. # each set of sets, if any option in one of the sets is in Options[] AND any
  812. # option in one of the other sets is in Options[], an error string is returned.
  813. # If no conflicts are found, nothing is returned.
  814. # Example: if OptSets = "ab,def,g;i,j", an error will be returned due to
  815. # the exclusions presented by the first set of sets (ab,def,g) if:
  816. # (a or b is in Options[]) AND (d, e, or f is in Options[]) OR
  817. # (a or b is in Options[]) AND (g is in Options) OR
  818. # (d, e, or f is in Options[]) AND (g is in Options)
  819. # An error will be returned due to the exclusions presented by the second set
  820. # of sets (i,j) if: (i is in Options[]) AND (j is in Options[]).
  821. # todo: make options given on command line unset options given in config file
  822. # todo: that they conflict with.
  823. function ExclusiveOptions(OptSets,Options,
  824. Sets,SetSet,NumSets,Pos1,Pos2,Len,s1,s2,c1,c2,ErrStr,L1,L2,SetSets,NumSetSets,
  825. SetNum,OSetNum) {
  826.     NumSetSets = split(OptSets,SetSets,";")
  827.     # For each set of sets...
  828.     for (SetSet = 1; SetSet <= NumSetSets; SetSet++) {
  829.     # NumSets is the number of sets in this set of sets.
  830.     NumSets = split(SetSets[SetSet],Sets,",")
  831.     # For each set in a set of sets except the last...
  832.     for (SetNum = 1; SetNum < NumSets; SetNum++) {
  833.         s1 = Sets[SetNum]
  834.         L1 = length(s1)
  835.         for (Pos1 = 1; Pos1 <= L1; Pos1++)
  836.         # If any of the options in this set was given, check whether
  837.         # any of the options in the other sets was given.  Only check
  838.         # later sets since earlier sets will have already been checked
  839.         # against this set.
  840.         if ((c1 = substr(s1,Pos1,1)) in Options)
  841.             for (OSetNum = SetNum+1; OSetNum <= NumSets; OSetNum++) {
  842.             s2 = Sets[OSetNum]
  843.             L2 = length(s2)
  844.             for (Pos2 = 1; Pos2 <= L2; Pos2++)
  845.                 if ((c2 = substr(s2,Pos2,1)) in Options)
  846.                 ErrStr = ErrStr "\n"\
  847.                 sprintf("Cannot give both %s and %s options.",
  848.                 c1,c2)
  849.             }
  850.     }
  851.     }
  852.     if (ErrStr != "")
  853.     return substr(ErrStr,2)
  854.     return ""
  855. }
  856.  
  857. # The value of each instance of option Opt that occurs in Options[] is made an
  858. # index of Set[].
  859. # The return value is the number of instances of Opt in Options.
  860. function Opt2Set(Options,Opt,Set,  count) {
  861.     if (!(Opt in Options))
  862.     return 0
  863.     Set[Options[Opt]]
  864.     count = Options[Opt,"count"]
  865.     for (; count > 1; count--)
  866.     Set[Options[Opt,count]]
  867.     return count
  868. }
  869.  
  870. # The value of each instance of option Opt that occurs in Options[] that
  871. # begins with "!" is made an index of nSet[] (with the ! stripped from it).
  872. # Other values are made indexes of Set[].
  873. # The return value is the number of instances of Opt in Options.
  874. function Opt2Sets(Options,Opt,Set,nSet,  count,aSet,ret) {
  875.     ret = Opt2Set(Options,Opt,aSet)
  876.     for (value in aSet)
  877.     if (substr(value,1,1) == "!")
  878.         nSet[substr(value,2)]
  879.     else
  880.         Set[value]
  881.     return ret
  882. }
  883.  
  884. # Returns true if option Opt was given on the command line.
  885. function CmdLineOpt(Options,Opt,  i) {
  886.     for (i = 1; (Opt,"num",i) in Options; i++)
  887.     if (Options[Opt,"num",i] != 0)
  888.         return 1
  889.     return 0
  890. }
  891. ### End of ProcArgs library
  892.  
  893. ### Begin set library
  894. # 96/05/23 added return values  jhdiii
  895. # 96/05/25 added set2list()
  896.  
  897. # Return value: the number of new elements added to Inter
  898. function Intersection(A,B,Inter,  Elem,Count) {
  899.     for (Elem in A)
  900.     if (Elem in B && !(Elem in Inter)) {
  901.         Inter[Elem]
  902.         Count++
  903.     }
  904.     return Count
  905. }
  906.  
  907. # Return value: the number of new elements added to Both
  908. function Union(A,B,Both) {
  909.     return CopySet(A,Both) + CopySet(B,Both)
  910. }
  911.  
  912. # Deletes any elements that are in both Minuend and Subtrahend from Minuend.
  913. # Return value: the number of elements deleted.
  914. function SubtractSet(Minuend,Subtrahend,  Elem,nDel) {
  915.     for (Elem in Subtrahend)
  916.     if (Elem in Minuend) {
  917.         delete Minuend[Elem]
  918.         nDel++
  919.     }
  920.     return nDel
  921. }
  922.  
  923. # Return value: the number of new elements added to To
  924. function CopySet(From,To,  Elem,n) {
  925.     for (Elem in From)
  926.     if (!(Elem in To)) {
  927.         To[Elem]
  928.         n++
  929.     }
  930.     return n
  931. }
  932.  
  933. # Returns 1 if Set is empty, 0 if not.
  934. function IsEmpty(Set,  i) {
  935.     for (i in Set)
  936.     return 0
  937.     return 1
  938. }
  939.  
  940. # MakeSet: make a set from a list.
  941. # An index with the name of each element of the list is created in the given
  942. # array.
  943. # Input variables: 
  944. # Elements is a string containing the list of elements.
  945. # Sep is the character that separates the elements of the list.
  946. # Output variables:
  947. # Set is the array.
  948. # Return value: the number of new elements added to the set.
  949. function MakeSet(Set,Elements,Sep,  i,Num,Names,nFound,ind) {
  950.     nFound = 0
  951.     Num = split(Elements,Names,Sep)
  952.     for (i = 1; i <= Num; i++) {
  953.     ind = Names[i]
  954.     if (!(ind in Set)) {
  955.         Set[ind]
  956.         nFound++
  957.     }
  958.     }
  959.     return nFound
  960. }
  961.  
  962. # Returns the number of elements in set Set
  963. function NumElem(Set,  elem,Num) {
  964.     for (elem in Set)
  965.     Num++
  966.     return Num
  967. }
  968.  
  969. # Remove all elements from Set
  970. function DeleteAll(Set,  i) {
  971.     split("",Set,",")
  972. }
  973.  
  974. # Returns a list of all of the elements in Set[], with each pair of elements
  975. # separated by Sep.
  976. function set2list(Set,Sep,  list,elem) {
  977.     for (elem in Set)
  978.     list = list Sep elem
  979.     return substr(list,2)    # skip 1st separator
  980. }
  981. ### End set library
  982. ### Begin qsort routines
  983.  
  984. # Arr[] is an array of values with arbitrary indices.
  985. # k[] is returned with numeric indices 1..n.
  986. # The values in k[] are the indices of Arr[],
  987. # ordered so that if Arr[] is stepped through
  988. # in the order Arr[k[1]] .. Arr[k[n]], it will be stepped
  989. # through in order of the values of its elements.
  990. # The return value is the number of elements in the arrays (n).
  991. function qsortArbIndByValue(Arr,k,  ArrInd,ElNum) {
  992.     ElNum = 0
  993.     for (ArrInd in Arr)
  994.     k[++ElNum] = ArrInd
  995.     qsortSegment(Arr,k,1,ElNum)
  996.     return ElNum
  997. }
  998.  
  999. # Sort a segment of an array.
  1000. # Arr[] contains data with arbitrary indices.
  1001. # k[] has indices 1..nelem, with the indices of arr[] as values.
  1002. # This function sorts the elements of arr that are pointed to by
  1003. # k[start..end], swapping the values of elements of k[] so that
  1004. # when this function returns arr[k[start..end]] will be in order.
  1005. function qsortSegment(Arr,k,start,end,  left,right,sepval,tmp,tmpe,tmps) {
  1006.     # handle two-element case explicitly for a tiny speedup
  1007.     if ((end - start) == 1) {
  1008.     if (Arr[tmps = k[start]] > Arr[tmpe = k[end]]) {
  1009.         k[start] = tmpe
  1010.         k[end] = tmps
  1011.     }
  1012.     return
  1013.     }
  1014.     # Make sure comparisons act on these as numbers
  1015.     left = start+0
  1016.     right = end+0
  1017.     sepval = Arr[k[int((left + right) / 2)]]
  1018.     # Make every element <= sepval be to the left of every element > sepval
  1019.     while (left < right) {
  1020.     while (Arr[k[left]] < sepval)
  1021.         left++
  1022.     while (Arr[k[right]] > sepval)
  1023.         right--
  1024.     if (left < right) {
  1025.         tmp = k[left]
  1026.         k[left++] = k[right]
  1027.         k[right--] = tmp
  1028.     }
  1029.     }
  1030.     if (left == right)
  1031.     if (Arr[k[left]] < sepval)
  1032.         left++
  1033.     else
  1034.         right--
  1035.     if (start < right)
  1036.     qsortSegment(Arr,k,start,right)
  1037.     if (left < end)
  1038.     qsortSegment(Arr,k,left,end)
  1039. }
  1040.  
  1041. # Arr[] is an array of values with arbitrary indices.
  1042. # k[] is returned with numeric indices 1..n.
  1043. # The values in k are the indices of Arr[],
  1044. # ordered so that if Arr[] is stepped through
  1045. # in the order Arr[k[1]] .. Arr[k[n]], it will be stepped
  1046. # through in order of the values of its indices.
  1047. # The return value is the number of elements in the arrays (n).
  1048. # If the indexes are numeric, Numeric should be true, so that they can be
  1049. # compared as such rather than as strings.  Numeric indexes do not have to be
  1050. # contiguous.
  1051. function qsortByArbIndex(Arr,k,Numeric,  ArrInd,ElNum) {
  1052.     ElNum = 0
  1053.     if (Numeric)
  1054.     # Indexes do not preserve numeric type, so must be forced
  1055.     for (ArrInd in Arr)
  1056.         k[++ElNum] = ArrInd+0
  1057.     else
  1058.     for (ArrInd in Arr)
  1059.         k[++ElNum] = ArrInd
  1060.     qsortNumIndByValue(k,1,ElNum)
  1061.     return ElNum
  1062. }
  1063.  
  1064. # Arr is an array of elements with contiguous numeric indexes to be sorted
  1065. # by value.
  1066. # start and end are the starting and ending indexes of the range to be sorted.
  1067. function qsortNumIndByValue(Arr,start,end,  left,right,sepval,tmp,tmpe,tmps) {
  1068.     # handle two-element case explicitly for a tiny speedup
  1069.     if ((start - end) == 1) {
  1070.     if ((tmps = Arr[start]) > (tmpe = Arr[end])) {
  1071.         Arr[start] = tmpe
  1072.         Arr[end] = tmps
  1073.     }
  1074.     return
  1075.     }
  1076.     left = start+0
  1077.     right = end+0
  1078.     sepval = Arr[int((left + right) / 2)]
  1079.     while (left < right) {
  1080.     while (Arr[left] < sepval)
  1081.         left++
  1082.     while (Arr[right] > sepval)
  1083.         right--
  1084.     if (left <= right) {
  1085.         tmp = Arr[left]
  1086.         Arr[left++] = Arr[right]
  1087.         Arr[right--] = tmp
  1088.     }
  1089.     }
  1090.     if (start < right)
  1091.     qsortNumIndByValue(Arr,start,right)
  1092.     if (left < end)
  1093.     qsortNumIndByValue(Arr,left,end)
  1094. }
  1095.  
  1096. ### End qsort routines
  1097.