xref: /titanic_50/usr/src/cmd/mdb/common/libstand/getopt.c (revision 1c5bc425cc346c6844d58e1fdd8794e9553dd289)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <sys/salib.h>
30 
31 #define	EOF	(-1)
32 
33 int opterr = 1, optind = 1, optopt = 0;
34 char *optarg = NULL;
35 int _sp = 1;
36 
37 extern void warn(const char *, ...);
38 
39 void
40 getopt_reset(void)
41 {
42 	opterr = 1;
43 	optind = 1;
44 	optopt = 0;
45 	optarg = NULL;
46 	_sp = 1;
47 }
48 
49 int
50 getopt(int argc, char *const *argv, const char *opts)
51 {
52 	char c;
53 	char *cp;
54 
55 	if (_sp == 1) {
56 		if (optind >= argc || argv[optind][0] != '-' ||
57 		    argv[optind] == NULL || argv[optind][1] == '\0')
58 			return (EOF);
59 		else if (strcmp(argv[optind], "--") == NULL) {
60 			optind++;
61 			return (EOF);
62 		}
63 	}
64 	optopt = c = (unsigned char)argv[optind][_sp];
65 	if (c == ':' || (cp = strchr(opts, c)) == NULL) {
66 		if (opts[0] != ':')
67 			warn("%s: illegal option -- %c\n", argv[0], c);
68 		if (argv[optind][++_sp] == '\0') {
69 			optind++;
70 			_sp = 1;
71 		}
72 		return ('?');
73 	}
74 
75 	if (*(cp + 1) == ':') {
76 		if (argv[optind][_sp+1] != '\0')
77 			optarg = &argv[optind++][_sp+1];
78 		else if (++optind >= argc) {
79 			if (opts[0] != ':') {
80 				warn("%s: option requires an argument"
81 				    " -- %c\n", argv[0], c);
82 			}
83 			_sp = 1;
84 			optarg = NULL;
85 			return (opts[0] == ':' ? ':' : '?');
86 		} else
87 			optarg = argv[optind++];
88 		_sp = 1;
89 	} else {
90 		if (argv[optind][++_sp] == '\0') {
91 			_sp = 1;
92 			optind++;
93 		}
94 		optarg = NULL;
95 	}
96 	return (c);
97 }
98