dmake: do not set MAKEFLAGS=k
[unleashed/tickless.git] / usr / src / cmd / sgs / elfedit / common / elfedit.c
blob9cd9aae37bddbbd3bc0fbce1ad13850363d83079
1 /*
2 * CDDL HEADER START
4 * The contents of this file are subject to the terms of the
5 * Common Development and Distribution License (the "License").
6 * You may not use this file except in compliance with the License.
8 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9 * or http://www.opensolaris.org/os/licensing.
10 * See the License for the specific language governing permissions
11 * and limitations under the License.
13 * When distributing Covered Code, include this CDDL HEADER in each
14 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15 * If applicable, add the following below this CDDL HEADER, with the
16 * fields enclosed by brackets "[]" replaced with your own identifying
17 * information: Portions Copyright [yyyy] [name of copyright owner]
19 * CDDL HEADER END
23 * Copyright 2010 Sun Microsystems, Inc. All rights reserved.
24 * Use is subject to license terms.
27 #include <sys/types.h>
28 #include <sys/stat.h>
29 #include <sys/wait.h>
30 #include <stdarg.h>
31 #include <fcntl.h>
32 #include <stdlib.h>
33 #include <stdio.h>
34 #include <signal.h>
35 #include <dirent.h>
36 #include <libelf.h>
37 #include <gelf.h>
38 #include <conv.h>
39 #include <dlfcn.h>
40 #include <link.h>
41 #include <stdarg.h>
42 #include <libgen.h>
43 #include <libintl.h>
44 #include <locale.h>
45 #include <unistd.h>
46 #include <errno.h>
47 #include <ctype.h>
48 #include <limits.h>
49 #include <strings.h>
50 #include <sgs.h>
51 #include "msg.h"
52 #include "_elfedit.h"
53 #include <debug.h> /* liblddb */
58 * Column at which elfedit_format_command_usage() will wrap the
59 * generated usage string if the wrap argument is True (1).
61 #define USAGE_WRAP_COL 55
67 * Type used to represent a string buffer that can grow as needed
68 * to hold strings of arbitrary length. The user should declare
69 * variables of this type sa static. The strbuf_ensure_size() function
70 * is used to ensure that it has a minimum desired size.
72 typedef struct {
73 char *buf; /* String buffer */
74 size_t n; /* Size of buffer */
75 } STRBUF;
81 * Types used by tokenize_user_cmd() to represent the result of
82 * spliting a user command into individual tokens.
84 typedef struct {
85 char *tok_str; /* Token string */
86 size_t tok_len; /* strlen(str) */
87 size_t tok_line_off; /* Token offset in original string */
88 } TOK_ELT;
89 typedef struct {
90 size_t tokst_cmd_len; /* Length of original user command, without */
91 /* newline or NULL termination chars */
92 size_t tokst_str_size; /* Space needed to hold all the resulting */
93 /* tokens, including terminating NULL */
94 TOK_ELT *tokst_buf; /* The array of tokens */
95 size_t tokst_cnt; /* # of tokens in array */
96 size_t tokst_bufsize; /* capacity of array */
97 } TOK_STATE;
102 /* State block used by gettok_init() and gettok() */
103 typedef struct {
104 const char *gtok_buf; /* Addr of buffer containing string */
105 char *gtok_cur_buf; /* Addr withing buffer for next token */
106 int gtok_inc_null_final; /* True if final NULL token used */
107 int gtok_null_seen; /* True when NULL byte seen */
108 TOK_ELT gtok_last_token; /* Last token parsed */
110 } GETTOK_STATE;
116 * The elfedit_cpl_*() functions are used for command line completion.
117 * Currently this uses the tecla library, but to allow for changing the
118 * library used, we hide all tecla interfaces from our modules. Instead,
119 * cmd_match_fcn() builds an ELFEDIT_CPL_STATE struct, and we pass the
120 * address of that struct as an opaque handle to the modules. Since the
121 * pointer is opaque, the contents of ELFEDIT_CPL_STATE are free to change
122 * as necessary.
124 typedef struct {
125 WordCompletion *ecpl_cpl; /* tecla handle */
126 const char *ecpl_line; /* raw input line */
127 int ecpl_word_start; /* start offset within line */
128 int ecpl_word_end; /* offset just past token */
130 * ecpl_add_mod_colon is a secret handshake between
131 * elfedit_cpl_command() and elfedit_cpl_add_match(). It adds
132 * ':' to end of matched modules.
134 int ecpl_add_mod_colon;
135 const char *ecpl_token_str; /* token being completed */
136 size_t ecpl_token_len; /* strlen(ecpl_token_str) */
137 } ELFEDIT_CPL_STATE;
142 /* This structure maintains elfedit global state */
143 STATE_T state;
148 * Define a pair of static global variables that contain the
149 * ISA strings that correspond to %i and %I tokens in module search
150 * paths.
152 * isa_i_str - The ISA string for the currently running program
153 * isa_I_str - For 64-bit programs, the same as isa_i_str. For
154 * 32-bit programs, an empty string.
157 #ifdef __i386
158 static const char *isa_i_str = MSG_ORIG(MSG_ISA_X86_32);
159 static const char *isa_I_str = MSG_ORIG(MSG_STR_EMPTY);
160 #endif
161 #ifdef __amd64
162 static const char *isa_i_str = MSG_ORIG(MSG_ISA_X86_64);
163 static const char *isa_I_str = MSG_ORIG(MSG_ISA_X86_64);
164 #endif
168 /* Forward declarations */
169 static void free_user_cmds(void);
170 static void elfedit_pager_cleanup(void);
175 * We supply this function for the msg module
177 const char *
178 _elfedit_msg(Msg mid)
180 return (gettext(MSG_ORIG(mid)));
185 * Copy at most min(cpsize, dstsize-1) bytes from src into dst,
186 * truncating src if necessary. The result is always null-terminated.
188 * entry:
189 * dst - Destination buffer
190 * src - Source string
191 * dstsize - sizeof(dst)
193 * note:
194 * This is similar to strncpy(), but with two modifications:
195 * 1) You specify the number of characters to copy, not just
196 * the size of the destination. Hence, you can copy non-NULL
197 * terminated strings.
198 * 2) The destination is guaranteed to be NULL terminated. strncpy()
199 * does not terminate a completely full buffer.
201 static void
202 elfedit_strnbcpy(char *dst, const char *src, size_t cpsize, size_t dstsize)
204 if (cpsize >= dstsize)
205 cpsize = dstsize - 1;
206 if (cpsize > 0)
207 (void) strncpy(dst, src, cpsize + 1);
208 dst[cpsize] = '\0';
213 * Calls exit() on behalf of elfedit.
215 void
216 elfedit_exit(int status)
218 if (state.file.present) {
219 /* Exiting with unflushed changes pending? Issue debug notice */
220 if (state.file.dirty)
221 elfedit_msg(ELFEDIT_MSG_DEBUG,
222 MSG_INTL(MSG_DEBUG_DIRTYEXIT));
225 * If the edit file is marked for unlink on exit, then
226 * take care of it here.
228 if (state.file.unlink_on_exit) {
229 elfedit_msg(ELFEDIT_MSG_DEBUG,
230 MSG_INTL(MSG_DEBUG_UNLINKFILE),
231 state.file.outfile);
232 (void) unlink(state.file.outfile);
236 exit(status);
241 * Standard message function for elfedit. All user visible
242 * output, for error or informational reasons, should go through
243 * this function.
245 * entry:
246 * type - Type of message. One of the ELFEDIT_MSG_* values.
247 * format, ... - As per the printf() family
249 * exit:
250 * The desired message has been output. For informational
251 * messages, control returns to the caller. For errors,
252 * this routine will terminate execution or strip the execution
253 * stack and return control directly to the outer control loop.
254 * In either case, the caller will not receive control.
256 /*PRINTFLIKE2*/
257 void
258 elfedit_msg(elfedit_msg_t type, const char *format, ...)
260 typedef enum { /* What to do after finished */
261 DISP_RET = 0, /* Return to caller */
262 DISP_JMP = 1, /* if (interactive) longjmp else exit */
263 DISP_EXIT = 2 /* exit under all circumstances */
264 } DISP;
266 va_list args;
267 FILE *stream = stderr;
268 DISP disp = DISP_RET;
269 int do_output = 1;
270 int need_prefix = 1;
272 va_start(args, format);
274 switch (type) {
275 case ELFEDIT_MSG_ERR:
276 case ELFEDIT_MSG_CMDUSAGE:
277 disp = DISP_JMP;
278 break;
279 case ELFEDIT_MSG_FATAL:
280 disp = DISP_EXIT;
281 break;
282 case ELFEDIT_MSG_USAGE:
283 need_prefix = 0;
284 break;
285 case ELFEDIT_MSG_DEBUG:
286 if (!(state.flags & ELFEDIT_F_DEBUG))
287 return;
288 stream = stdout;
289 break;
290 case ELFEDIT_MSG_QUIET:
291 do_output = 0;
292 disp = DISP_JMP;
293 break;
298 * If there is a pager process running, we are returning to the
299 * caller, and the output is going to stdout, then let the
300 * pager handle it instead of writing it directly from this process.
301 * That way, the output gets paged along with everything else.
303 * If there is a pager process running, and we are not returning
304 * to the caller, then end the pager process now, before we generate
305 * any new output. This allows for any text buffered in the pager
306 * pipe to be output before the new stuff.
308 if (state.pager.fptr != NULL) {
309 if (disp == DISP_RET) {
310 if (stream == stdout)
311 stream = state.pager.fptr;
312 } else {
313 elfedit_pager_cleanup();
318 * If this message is coming from within the libtecla command
319 * completion code, call gl_normal_io() to give the library notice.
320 * That function sets the tty back to cooked mode and advances
321 * the cursor to the beginning of the next line so that our output
322 * will appear properly. When we return to the command completion code,
323 * tecla will re-enter raw mode and redraw the current command line.
325 if (state.input.in_tecla)
326 (void) gl_normal_io(state.input.gl);
328 if (do_output) {
329 if (need_prefix)
330 (void) fprintf(stream, MSG_ORIG(MSG_STR_ELFEDIT));
331 (void) vfprintf(stream, format, args);
332 (void) fflush(stream);
334 va_end(args);
337 * If this is an error, then we do not return to the caller.
338 * The action taken depends on whether the outer loop has registered
339 * a jump buffer for us or not.
341 if (disp != DISP_RET) {
342 if (state.msg_jbuf.active && (disp == DISP_JMP)) {
343 /* Free the user command list */
344 free_user_cmds();
346 /* Clean up to reflect effect of non-local goto */
347 state.input.in_tecla = FALSE;
349 /* Jump to the outer loop to resume */
350 siglongjmp(state.msg_jbuf.env, 1);
351 } else {
352 elfedit_exit(1);
359 * Wrapper on elfedit_msg() that issues an error that results from
360 * a call to libelf.
362 * entry:
363 * file - Name of ELF object
364 * libelf_rtn_name - Name of routine that was called
366 * exit:
367 * An error has been issued that shows the routine called
368 * and the libelf error string for it from elf_errmsg().
369 * This routine does not return to the caller.
371 void
372 elfedit_elferr(const char *file, const char *libelf_rtn_name)
374 const char *errstr = elf_errmsg(elf_errno());
376 elfedit_msg(ELFEDIT_MSG_ERR, MSG_INTL(MSG_ERR_LIBELF), file,
377 libelf_rtn_name, errstr ? errstr : MSG_INTL(MSG_FMT_UNKNOWN));
382 * Start an output pager process for elfedit_printf()/elfedit_write() to use.
384 * note:
385 * If this elfedit session is not interactive, then no pager is
386 * started. Paging is only intended for interactive use. The caller
387 * is not supposed to worry about this point, but simply to use
388 * this function to flag situations in which paging might be needed.
390 void
391 elfedit_pager_init(void)
393 const char *errstr;
394 const char *cmd;
395 int err;
398 * If there is no pager process running, start one.
399 * Only do this for interactive sessions --- elfedit_pager()
400 * won't use a pager in batch mode.
402 if (state.msg_jbuf.active && state.input.full_tty &&
403 (state.pager.fptr == NULL)) {
405 * If the user has the PAGER environment variable set,
406 * then we will use that program. Otherwise we default
407 * to /bin/more.
409 cmd = getenv(MSG_ORIG(MSG_STR_PAGER));
410 if ((cmd == NULL) || (*cmd == '\0'))
411 cmd = MSG_ORIG(MSG_STR_BINMORE);
414 * The popen() manpage says that on failure, it "may set errno",
415 * which is somewhat ambiguous. We explicitly zero it here, and
416 * assume that any change is due to popen() failing.
418 errno = 0;
419 state.pager.fptr = popen(cmd, MSG_ORIG(MSG_STR_W));
420 if (state.pager.fptr == NULL) {
421 err = errno;
422 errstr = (err == 0) ? MSG_INTL(MSG_ERR_UNKNOWNSYSERR) :
423 strerror(err);
424 elfedit_msg(ELFEDIT_MSG_ERR, MSG_INTL(MSG_ERR_CNTEXEC),
425 MSG_ORIG(MSG_STR_ELFEDIT), cmd, errstr);
432 * If there is a pager process present, close it out.
434 * note:
435 * This function is called from within elfedit_msg(), and as
436 * such, must not use elfedit_msg() to report errors. Furthermore,
437 * any such errors are not a sufficient reason to terminate the process
438 * or to longjmp(). This is a rare case where errors are written
439 * directly to stderr.
441 static void
442 elfedit_pager_cleanup(void)
444 if (state.pager.fptr != NULL) {
445 if (pclose(state.pager.fptr) == -1)
446 (void) fprintf(stderr, MSG_INTL(MSG_ERR_PAGERFINI));
448 state.pager.fptr = NULL;
454 * Print general formtted text for the user, using printf()-style
455 * formatting. Uses the pager process if one has been started, or
456 * stdout otherwise.
458 void
459 elfedit_printf(const char *format, ...)
461 va_list args;
462 int err;
463 FILE *fptr;
464 int pager;
465 int broken_pipe = 0;
468 * If there is a pager process, then use it. Otherwise write
469 * directly to stdout.
471 pager = (state.pager.fptr != NULL);
472 fptr = pager ? state.pager.fptr : stdout;
474 va_start(args, format);
475 errno = 0;
476 err = vfprintf(fptr, format, args);
478 /* Did we fail because a child pager process has exited? */
479 broken_pipe = pager && (err < 0) && (errno == EPIPE);
481 va_end(args);
484 * On error, we simply issue the error without cleaning up
485 * the pager process. The message code handles that as a standard
486 * part of error processing.
488 * We handle failure due to an exited pager process differently
489 * than a normal error, because it is usually due to the user
490 * intentionally telling it to.
492 if (err < 0) {
493 if (broken_pipe)
494 elfedit_msg(ELFEDIT_MSG_QUIET, MSG_ORIG(MSG_STR_NULL));
495 else
496 elfedit_msg(ELFEDIT_MSG_ERR, MSG_INTL(MSG_ERR_PRINTF));
502 * Some our modules use liblddb routines to format ELF output.
503 * In order to ensure that such output is sent to the pager pipe
504 * when there is one, and stdout otherwise, we redefine the dbg_print()
505 * function here.
507 * This item should be defined NODIRECT.
509 /* PRINTFLIKE2 */
510 void
511 dbg_print(Lm_list *lml, const char *format, ...)
513 va_list ap;
514 int err;
515 FILE *fptr;
516 int pager;
517 int broken_pipe = 0;
521 * If there is a pager process, then use it. Otherwise write
522 * directly to stdout.
524 pager = (state.pager.fptr != NULL);
525 fptr = pager ? state.pager.fptr : stdout;
527 va_start(ap, format);
528 errno = 0;
529 err = vfprintf(fptr, format, ap);
530 if (err >= 0)
531 err = fprintf(fptr, MSG_ORIG(MSG_STR_NL));
533 /* Did we fail because a child pager process has exited? */
534 broken_pipe = (err < 0) && pager && (errno == EPIPE);
536 va_end(ap);
539 * On error, we simply issue the error without cleaning up
540 * the pager process. The message code handles that as a standard
541 * part of error processing.
543 * We handle failure due to an exited pager process differently
544 * than a normal error, because it is usually due to the user
545 * intentionally telling it to.
547 if (err < 0) {
548 if (broken_pipe)
549 elfedit_msg(ELFEDIT_MSG_QUIET, MSG_ORIG(MSG_STR_NULL));
550 else
551 elfedit_msg(ELFEDIT_MSG_ERR, MSG_INTL(MSG_ERR_PRINTF));
557 * Write raw bytes of text in a manner similar to fwrite().
558 * Uses the pager process if one has been started, or
559 * stdout otherwise.
561 void
562 elfedit_write(const void *ptr, size_t size)
564 FILE *fptr;
565 int err;
568 * If there is a pager process, then use it. Otherwise write
569 * directly to stdout.
571 fptr = (state.pager.fptr == NULL) ? stdout : state.pager.fptr;
573 if (fwrite(ptr, 1, size, fptr) != size) {
574 err = errno;
575 elfedit_msg(ELFEDIT_MSG_ERR, MSG_INTL(MSG_ERR_FWRITE),
576 strerror(err));
582 * Convert the NULL terminated string to the form used by the C
583 * language to represent literal strings. See conv_str_to_c_literal()
584 * for details.
586 * This routine differs from conv_str_to_c_literal() in two ways:
587 * 1) String is NULL terminated instead of counted
588 * 2) Signature of outfunc
590 * entry:
591 * str - String to be processed
592 * outfunc - Function to be called to move output characters. Note
593 * that this function has the same signature as elfedit_write(),
594 * and that function can be used to write the characters to
595 * the output.
597 * exit:
598 * The string has been processed, with the resulting data passed
599 * to outfunc for processing.
601 static void
602 elfedit_str_to_c_literal_cb(const void *ptr, size_t size, void *uvalue)
604 elfedit_write_func_t *outfunc = (elfedit_write_func_t *)uvalue;
606 (* outfunc)(ptr, size);
609 void
610 elfedit_str_to_c_literal(const char *str, elfedit_write_func_t *outfunc)
612 conv_str_to_c_literal(str, strlen(str),
613 elfedit_str_to_c_literal_cb, (void *) outfunc);
618 * Wrappers on malloc() and realloc() that check the result for success
619 * and issue an error if not. The caller can use the result of these
620 * functions without checking for a NULL pointer, as we do not return to
621 * the caller in the failure case.
623 void *
624 elfedit_malloc(const char *item_name, size_t size)
626 void *m;
628 m = malloc(size);
629 if (m == NULL) {
630 int err = errno;
631 elfedit_msg(ELFEDIT_MSG_ERR, MSG_INTL(MSG_ERR_MALLOC),
632 item_name, strerror(err));
635 return (m);
638 void *
639 elfedit_realloc(const char *item_name, void *ptr, size_t size)
641 void *m;
643 m = realloc(ptr, size);
644 if (m == NULL) {
645 int err = errno;
646 elfedit_msg(ELFEDIT_MSG_ERR, MSG_INTL(MSG_ERR_MALLOC),
647 item_name, strerror(err));
650 return (m);
655 * Ensure that the given buffer has room for n bytes of data.
657 static void
658 strbuf_ensure_size(STRBUF *str, size_t size)
660 #define INITIAL_STR_ALLOC 128
662 size_t n;
664 n = (str->n == 0) ? INITIAL_STR_ALLOC : str->n;
665 while (size > n) /* Double buffer until string fits */
666 n *= 2;
667 if (n != str->n) { /* Alloc new string buffer if needed */
668 str->buf = elfedit_realloc(MSG_INTL(MSG_ALLOC_UCMDSTR),
669 str->buf, n);
670 str->n = n;
673 #undef INITIAL_STR_ALLOC
678 * Extract the argument/option information for the next item referenced
679 * by optarg, and advance the pointer to the next item.
681 * entry:
682 * optarg - Address of pointer to argument or option array
683 * item - Struct to be filled in.
685 * exit:
686 * The item block has been filled in with the information for
687 * the next item in the optarg array. *optarg has been advanced
688 * to the next item.
690 void
691 elfedit_next_optarg(elfedit_cmd_optarg_t **optarg, elfedit_optarg_item_t *item)
694 * Array of inheritable options/arguments. Indexed by one less
695 * than the corresponding ELFEDIT_STDOA_ value.
697 static const elfedit_optarg_item_t stdoa[] = {
698 /* ELFEDIT_STDOA_O */
699 { MSG_ORIG(MSG_STR_MINUS_O), MSG_ORIG(MSG_STR_OUTSTYLE),
700 /* MSG_INTL(MSG_STDOA_OPTDESC_O) */
701 (elfedit_i18nhdl_t)MSG_STDOA_OPTDESC_O,
702 ELFEDIT_CMDOA_F_VALUE },
704 /* ELFEDIT_STDOA_AND */
705 { MSG_ORIG(MSG_STR_MINUS_AND), NULL,
706 /* MSG_INTL(MSG_STDOA_OPTDESC_AND) */
707 (elfedit_i18nhdl_t)MSG_STDOA_OPTDESC_AND, 0 },
709 /* ELFEDIT_STDOA_CMP */
710 { MSG_ORIG(MSG_STR_MINUS_CMP), NULL,
711 /* MSG_INTL(MSG_STDOA_OPTDESC_CMP) */
712 (elfedit_i18nhdl_t)MSG_STDOA_OPTDESC_CMP, 0 },
714 /* ELFEDIT_STDOA_OR */
715 { MSG_ORIG(MSG_STR_MINUS_OR), NULL,
716 /* MSG_INTL(MSG_STDOA_OPTDESC_OR) */
717 (elfedit_i18nhdl_t)MSG_STDOA_OPTDESC_OR, 0 },
720 elfedit_cmd_optarg_t *oa;
723 /* Grab first item, advance the callers pointer over it */
724 oa = (*optarg)++;
726 if (oa->oa_flags & ELFEDIT_CMDOA_F_INHERIT) {
727 /* Values are pre-chewed in the stdoa array above */
728 *item = stdoa[((uintptr_t)oa->oa_name) - 1];
731 * Set the inherited flag so that elfedit_optarg_helpstr()
732 * can tell who is responsible for translating the help string.
734 item->oai_flags |= ELFEDIT_CMDOA_F_INHERIT;
735 } else { /* Non-inherited item */
736 item->oai_name = oa->oa_name;
737 if ((oa->oa_flags & ELFEDIT_CMDOA_F_VALUE) != 0) {
738 item->oai_vname = oa[1].oa_name;
740 /* Advance users pointer past value element */
741 (*optarg)++;
742 } else {
743 item->oai_vname = NULL;
745 item->oai_help = oa->oa_help;
746 item->oai_flags = oa->oa_flags;
750 * The module determines the idmask and excmask fields whether
751 * or not inheritance is in play.
753 item->oai_idmask = oa->oa_idmask;
754 item->oai_excmask = oa->oa_excmask;
760 * Return the help string for an option/argument item, as returned
761 * by elfedit_next_optarg(). This routine handles the details of
762 * knowing whether the string is provided by elfedit itself (inherited),
763 * or needs to be translated by the module.
765 const char *
766 elfedit_optarg_helpstr(elfeditGC_module_t *mod, elfedit_optarg_item_t *item)
769 * The help string from an inherited item comes right out
770 * of the main elfedit string table.
772 if (item->oai_flags & ELFEDIT_CMDOA_F_INHERIT)
773 return (MSG_INTL((Msg) item->oai_help));
776 * If the string is defined by the module, then we need to
777 * have the module translate it for us.
779 return ((* mod->mod_i18nhdl_to_str)(item->oai_help));
785 * Used by usage_optarg() to insert a character into the output buffer,
786 * advancing the buffer pointer and current column, and reducing the
787 * amount of remaining space.
789 static void
790 usage_optarg_insert_ch(int ch, char **cur, size_t *n, size_t *cur_col)
793 *(*cur)++ = ch;
794 **cur = '\0';
795 (*n)--;
796 (*cur_col)++;
800 * Used by usage_optarg() to insert a string into the output
801 * buffer, advancing the buffer pointer and current column, and reducing
802 * the amount of remaining space.
804 static void
805 usage_optarg_insert_str(char **cur, size_t *n, size_t *cur_col,
806 const char *format, ...)
808 size_t len;
809 va_list args;
811 va_start(args, format);
812 len = vsnprintf(*cur, *n, format, args);
813 va_end(args);
815 *cur += len;
816 *n -= len;
817 *cur_col += len;
820 * Used by usage_optarg() to insert an optarg item string into the output
821 * buffer, advancing the buffer pointer and current column, and reducing
822 * the amount of remaining space.
824 static void
825 usage_optarg_insert_item(elfedit_optarg_item_t *item, char **cur,
826 size_t *n, size_t *cur_col)
828 size_t len;
830 if (item->oai_flags & ELFEDIT_CMDOA_F_VALUE) {
831 len = snprintf(*cur, *n, MSG_ORIG(MSG_STR_HLPOPTARG2),
832 item->oai_name, item->oai_vname);
833 } else {
834 len = snprintf(*cur, *n, MSG_ORIG(MSG_STR_HLPOPTARG),
835 item->oai_name);
837 *cur += len;
838 *n -= len;
839 *cur_col += len;
845 * Write the options/arguments to the usage string.
847 * entry:
848 * main_buf_n - Size of main buffer from which buf and buf_n are
849 * allocated.
850 * buf - Address of pointer to where next item is to be placed.
851 * buf_n - Address of count of remaining bytes in buffer
852 * buf_cur_col - Address of current output column for current line
853 * of generated string.
854 * optarg - Options list
855 * isopt - True if these are options, false for arguments.
856 * wrap_str - String to indent wrapped lines. If NULL, lines
857 * are not wrapped
859 static void
860 usage_optarg(size_t main_buf_n, char **buf, size_t *buf_n, size_t *buf_cur_col,
861 elfedit_cmd_optarg_t *optarg, int isopt, const char *wrap_str)
864 * An option can be combined into a simple format if it lacks
865 * these flags and is only one character in length.
867 static const elfedit_cmd_oa_flag_t exflags =
868 (ELFEDIT_CMDOA_F_VALUE | ELFEDIT_CMDOA_F_MULT);
871 * A static buffer, which is grown as needed to accomodate
872 * the maximum usage string seen.
874 static STRBUF simple_str;
876 char *cur = *buf;
877 size_t n = *buf_n;
878 size_t cur_col = *buf_cur_col;
879 int len;
880 int use_simple = 0;
881 elfedit_optarg_item_t item;
882 elfedit_cmd_oa_mask_t optmask = 0;
883 int use_bkt;
886 * If processing options, pull the 1-character ones that don't have
887 * an associated value and don't have any mutual exclusion issues into
888 * a single combination string to go at the beginning of the usage.
890 if (isopt) {
891 elfedit_cmd_optarg_t *tmp_optarg = optarg;
892 char *s;
895 * The simple string is guaranteed to fit in the same
896 * amount of space reserved for the main buffer.
898 strbuf_ensure_size(&simple_str, main_buf_n);
899 s = simple_str.buf;
900 *s++ = ' ';
901 *s++ = '[';
902 *s++ = '-';
903 while (tmp_optarg->oa_name != NULL) {
904 elfedit_next_optarg(&tmp_optarg, &item);
905 if (((item.oai_flags & exflags) == 0) &&
906 (item.oai_name[2] == '\0') &&
907 (item.oai_excmask == 0)) {
908 optmask |= item.oai_idmask;
909 *s++ = item.oai_name[1];
914 * If we found more than one, then finish the string and
915 * add it. Don't do this for a single option, because
916 * it looks better in that case if the option shows up
917 * in alphabetical order rather than being hoisted.
919 use_simple = (s > (simple_str.buf + 4));
920 if (use_simple) {
921 *s++ = ']';
922 *s++ = '\0';
923 usage_optarg_insert_str(&cur, &n, &cur_col,
924 MSG_ORIG(MSG_STR_HLPOPTARG), simple_str.buf);
925 } else {
926 /* Not using it, so reset the cumulative options mask */
927 optmask = 0;
931 while (optarg->oa_name != NULL) {
932 elfedit_next_optarg(&optarg, &item);
934 if (isopt) {
936 * If this is an option that was pulled into the
937 * combination string above, then skip over it.
939 if (use_simple && ((item.oai_flags & exflags) == 0) &&
940 (item.oai_name[2] == '\0') &&
941 (item.oai_excmask == 0))
942 continue;
945 * If this is a mutual exclusion option that was
946 * picked up out of order by a previous iteration
947 * of this loop, then skip over it.
949 if ((optmask & item.oai_idmask) != 0)
950 continue;
952 /* Add this item to the accumulating options mask */
953 optmask |= item.oai_idmask;
956 /* Wrap line, or insert blank separator */
957 if ((wrap_str != NULL) && (cur_col > USAGE_WRAP_COL)) {
958 len = snprintf(cur, n, MSG_ORIG(MSG_FMT_WRAPUSAGE),
959 wrap_str);
960 cur += len;
961 n -= len;
962 cur_col = len - 1; /* Don't count the newline */
963 } else {
964 usage_optarg_insert_ch(' ', &cur, &n, &cur_col);
967 use_bkt = (item.oai_flags & ELFEDIT_CMDOA_F_OPT) || isopt;
968 if (use_bkt)
969 usage_optarg_insert_ch('[', &cur, &n, &cur_col);
971 /* Add the item to the buffer */
972 usage_optarg_insert_item(&item, &cur, &n, &cur_col);
975 * If this item has a non-zero mutual exclusion mask,
976 * then look for the other items and display them all
977 * together with alternation (|). Note that plain arguments
978 * cannot have a non-0 exclusion mask, so this is
979 * effectively options-only (isopt != 0).
981 if (item.oai_excmask != 0) {
982 elfedit_cmd_optarg_t *tmp_optarg = optarg;
983 elfedit_optarg_item_t tmp_item;
986 * When showing alternation, elipses for multiple
987 * copies need to appear inside the [] brackets.
989 if (item.oai_flags & ELFEDIT_CMDOA_F_MULT)
990 usage_optarg_insert_str(&cur, &n, &cur_col,
991 MSG_ORIG(MSG_STR_ELIPSES));
994 while (tmp_optarg->oa_name != NULL) {
995 elfedit_next_optarg(&tmp_optarg, &tmp_item);
996 if ((item.oai_excmask & tmp_item.oai_idmask) ==
998 continue;
999 usage_optarg_insert_str(&cur, &n, &cur_col,
1000 MSG_ORIG(MSG_STR_SP_BAR_SP));
1001 usage_optarg_insert_item(&tmp_item,
1002 &cur, &n, &cur_col);
1005 * Add it to the mask of seen options.
1006 * This will keep us from showing it twice.
1008 optmask |= tmp_item.oai_idmask;
1011 if (use_bkt)
1012 usage_optarg_insert_ch(']', &cur, &n, &cur_col);
1015 * If alternation was not shown above (non-zero exclusion mask)
1016 * then the elipses for multiple copies are shown outside
1017 * any [] brackets.
1019 if ((item.oai_excmask == 0) &&
1020 (item.oai_flags & ELFEDIT_CMDOA_F_MULT))
1021 usage_optarg_insert_str(&cur, &n, &cur_col,
1022 MSG_ORIG(MSG_STR_ELIPSES));
1026 *buf = cur;
1027 *buf_n = n;
1028 *buf_cur_col = cur_col;
1034 * Format the usage string for a command into a static buffer and
1035 * return the pointer to the user. The resultant string is valid
1036 * until the next call to this routine, and which point it
1037 * will be overwritten or the memory is freed.
1039 * entry:
1040 * mod, cmd - Module and command definitions for command to be described
1041 * wrap_str - NULL, or string to be used to indent when
1042 * lines are wrapped. If NULL, no wrapping is done, and
1043 * all output is on a single line.
1044 * cur_col - Starting column at which the string will be displayed.
1045 * Ignored if wrap_str is NULL.
1047 const char *
1048 elfedit_format_command_usage(elfeditGC_module_t *mod, elfeditGC_cmd_t *cmd,
1049 const char *wrap_str, size_t cur_col)
1053 * A static buffer, which is grown as needed to accomodate
1054 * the maximum usage string seen.
1056 static STRBUF str;
1058 elfedit_cmd_optarg_t *optarg;
1059 size_t len, n, elipses_len;
1060 char *cur;
1061 elfedit_optarg_item_t item;
1064 * Estimate a worst case size for the usage string:
1065 * - module name
1066 * - lengths of the strings
1067 * - every option or argument is enclosed in brackets
1068 * - space in between each item, with an alternation (" | ")
1069 * - elipses will be displayed with each option and argument
1071 n = strlen(mod->mod_name) + strlen(cmd->cmd_name[0]) + 6;
1072 elipses_len = strlen(MSG_ORIG(MSG_STR_ELIPSES));
1073 if ((optarg = cmd->cmd_opt) != NULL)
1074 while (optarg->oa_name != NULL) {
1075 elfedit_next_optarg(&optarg, &item);
1076 n += strlen(item.oai_name) + 5 + elipses_len;
1078 if ((optarg = cmd->cmd_args) != NULL)
1079 while (optarg->oa_name != NULL) {
1080 elfedit_next_optarg(&optarg, &item);
1081 n += strlen(item.oai_name) + 5 + elipses_len;
1083 n++; /* Null termination */
1086 * If wrapping lines, we insert a newline and then wrap_str
1087 * every USAGE_WRAP_COL characters.
1089 if (wrap_str != NULL)
1090 n += ((n + USAGE_WRAP_COL) / USAGE_WRAP_COL) *
1091 (strlen(wrap_str) + 1);
1093 strbuf_ensure_size(&str, n);
1095 /* Command name */
1096 cur = str.buf;
1097 n = str.n;
1098 if (strcmp(mod->mod_name, MSG_ORIG(MSG_MOD_SYS)) == 0)
1099 len = snprintf(cur, n, MSG_ORIG(MSG_FMT_SYSCMD),
1100 cmd->cmd_name[0]);
1101 else
1102 len = snprintf(cur, n, MSG_ORIG(MSG_FMT_MODCMD),
1103 mod->mod_name, cmd->cmd_name[0]);
1104 cur += len;
1105 n -= len;
1106 cur_col += len;
1108 if (cmd->cmd_opt != NULL)
1109 usage_optarg(str.n, &cur, &n, &cur_col, cmd->cmd_opt,
1110 1, wrap_str);
1111 if (cmd->cmd_args != NULL)
1112 usage_optarg(str.n, &cur, &n, &cur_col, cmd->cmd_args,
1113 0, wrap_str);
1115 return (str.buf);
1119 * Wrapper on elfedit_msg() that issues an ELFEDIT_MSG_USAGE
1120 * error giving usage information for the command currently
1121 * referenced by state.cur_cmd.
1123 void
1124 elfedit_command_usage(void)
1126 elfedit_msg(ELFEDIT_MSG_CMDUSAGE, MSG_INTL(MSG_USAGE_CMD),
1127 elfedit_format_command_usage(state.cur_cmd->ucmd_mod,
1128 state.cur_cmd->ucmd_cmd, NULL, 0));
1133 * This function allows the loadable modules to get the command line
1134 * flags.
1136 elfedit_flag_t
1137 elfedit_flags(void)
1139 return (state.flags);
1143 * This function is used to register a per-command invocation output style
1144 * that will momentarily override the global output style for the duration
1145 * of the current command. This function must only be called by an
1146 * active command.
1148 * entry:
1149 * str - One of the valid strings for the output style
1151 void
1152 elfedit_set_cmd_outstyle(const char *str)
1154 if ((state.cur_cmd != NULL) && (str != NULL)) {
1155 if (elfedit_atooutstyle(str, &state.cur_cmd->ucmd_ostyle) == 0)
1156 elfedit_msg(ELFEDIT_MSG_ERR,
1157 MSG_INTL(MSG_ERR_BADOSTYLE), str);
1158 state.cur_cmd->ucmd_ostyle_set = 1;
1163 * This function allows the loadable modules to get the output style.
1165 elfedit_outstyle_t
1166 elfedit_outstyle(void)
1169 * If there is an active per-command output style,
1170 * return it.
1172 if ((state.cur_cmd != NULL) && (state.cur_cmd->ucmd_ostyle_set))
1173 return (state.cur_cmd->ucmd_ostyle);
1176 return (state.outstyle);
1180 * Return the command descriptor of the currently executing command.
1181 * For use only by the modules or code called by the modules.
1183 elfeditGC_cmd_t *
1184 elfedit_curcmd(void)
1186 return (state.cur_cmd->ucmd_cmd);
1190 * Build a dynamically allocated elfedit_obj_state_t struct that
1191 * contains a cache of the ELF file contents. This pre-chewed form
1192 * is fed to each command, reducing the amount of ELF boilerplate
1193 * code each command needs to contain.
1195 * entry:
1196 * file - Name of file to process
1198 * exit:
1199 * Fills state.elf with the necessary information for the open file.
1201 * note: The resulting elfedit_obj_state_t is allocated from a single
1202 * piece of memory, such that a single call to free() suffices
1203 * to release it as well as any memory it references.
1205 static void
1206 init_obj_state(const char *file)
1208 int fd;
1209 Elf *elf;
1210 int open_flag;
1213 * In readonly mode, we open the file readonly so that it is
1214 * impossible to modify the file by accident. This also allows
1215 * us to access readonly files, perhaps in a case where we don't
1216 * intend to change it.
1218 * We always use ELF_C_RDWR with elf_begin(), even in a readonly
1219 * session. This allows us to modify the in-memory image, which
1220 * can be useful when examining a file, even though we don't intend
1221 * to modify the on-disk data. The file is not writable in
1222 * this case, and we don't call elf_update(), so it is safe to do so.
1224 open_flag = ((state.flags & ELFEDIT_F_READONLY) ? O_RDONLY : O_RDWR);
1225 if ((fd = open(file, open_flag)) == -1) {
1226 int err = errno;
1227 elfedit_msg(ELFEDIT_MSG_ERR, MSG_INTL(MSG_ERR_CNTOPNFILE),
1228 file, strerror(err));
1230 (void) elf_version(EV_CURRENT);
1231 elf = elf_begin(fd, ELF_C_RDWR, NULL);
1232 if (elf == NULL) {
1233 (void) close(fd);
1234 elfedit_elferr(file, MSG_ORIG(MSG_ELF_BEGIN));
1235 /*NOTREACHED*/
1238 /* We only handle standalone ELF files */
1239 switch (elf_kind(elf)) {
1240 case ELF_K_AR:
1241 (void) close(fd);
1242 elfedit_msg(ELFEDIT_MSG_ERR, MSG_INTL(MSG_ERR_NOAR), file);
1243 break;
1244 case ELF_K_ELF:
1245 break;
1246 default:
1247 (void) close(fd);
1248 elfedit_msg(ELFEDIT_MSG_ERR, MSG_INTL(MSG_ERR_UNRECELFFILE),
1249 file);
1250 break;
1254 * Tell libelf that we take responsibility for object layout.
1255 * Otherwise, it will compute "proper" values for layout and
1256 * alignment fields, and these values can overwrite the values
1257 * set in the elfedit session. We are modifying existing
1258 * objects --- the layout concerns have already been dealt
1259 * with when the object was built.
1261 (void) elf_flagelf(elf, ELF_C_SET, ELF_F_LAYOUT);
1263 /* Fill in state.elf.obj_state */
1264 state.elf.elfclass = gelf_getclass(elf);
1265 switch (state.elf.elfclass) {
1266 case ELFCLASS32:
1267 elfedit32_init_obj_state(file, fd, elf);
1268 break;
1269 case ELFCLASS64:
1270 elfedit64_init_obj_state(file, fd, elf);
1271 break;
1272 default:
1273 (void) close(fd);
1274 elfedit_msg(ELFEDIT_MSG_ERR, MSG_INTL(MSG_ERR_BADELFCLASS),
1275 file);
1276 break;
1281 #ifdef DEBUG_MODULE_LIST
1283 * Debug routine. Dump the module list to stdout.
1285 static void
1286 dbg_module_list(char *title)
1288 MODLIST_T *m;
1290 printf("<MODULE LIST: %s>\n", title);
1291 for (m = state.modlist; m != NULL; m = m->next) {
1292 printf("Module: >%s<\n", m->mod->mod_name);
1293 printf(" hdl: %llx\n", m->dl_hdl);
1294 printf(" path: >%s<\n", m->path ? m->path : "<builtin>");
1296 printf("<END OF MODULE LIST>\n");
1298 #endif
1302 * Search the module list for the named module.
1304 * entry:
1305 * name - Name of module to find
1306 * insdef - Address of variable to receive address of predecessor
1307 * node to the desired one.
1309 * exit:
1310 * If the module is it is found, this routine returns the pointer to
1311 * its MODLIST_T structure. *insdef references the predecessor node, or
1312 * is NULL if the found item is at the head of the list.
1314 * If the module is not found, NULL is returned. *insdef references
1315 * the predecessor node of the position where an entry for this module
1316 * would be placed, or NULL if it would go at the beginning.
1318 static MODLIST_T *
1319 module_loaded(const char *name, MODLIST_T **insdef)
1321 MODLIST_T *moddef;
1322 int cmp;
1324 *insdef = NULL;
1325 moddef = state.modlist;
1326 if (moddef != NULL) {
1327 cmp = strcasecmp(name, moddef->ml_mod->mod_name);
1328 if (cmp == 0) { /* Desired module is first in list */
1329 return (moddef);
1330 } else if (cmp > 0) { /* cmp > 0: Insert in middle/end */
1331 *insdef = moddef;
1332 moddef = moddef->ml_next;
1333 cmp = -1;
1334 while (moddef && (cmp < 0)) {
1335 cmp = strcasecmp(moddef->ml_mod->mod_name,
1336 name);
1337 if (cmp == 0)
1338 return (moddef);
1339 if (cmp < 0) {
1340 *insdef = moddef;
1341 moddef = (*insdef)->ml_next;
1347 return (NULL);
1352 * Determine if a file is a sharable object based on its file path.
1353 * If path ends in a .so, followed optionally by a period and 1 or more
1354 * digits, we say that it is and return a pointer to the first character
1355 * of the suffix. Otherwise NULL is returned.
1357 static const char *
1358 path_is_so(const char *path)
1360 int dotso_len;
1361 const char *tail;
1362 size_t len;
1364 len = strlen(path);
1365 if (len == 0)
1366 return (NULL);
1367 tail = path + len;
1368 if (isdigit(*(tail - 1))) {
1369 while ((tail > path) && isdigit(*(tail - 1)))
1370 tail--;
1371 if ((tail <= path) || (*tail != '.'))
1372 return (NULL);
1374 dotso_len = strlen(MSG_ORIG(MSG_STR_DOTSO));
1375 if ((tail - path) < dotso_len)
1376 return (NULL);
1377 tail -= dotso_len;
1378 if (strncmp(tail, MSG_ORIG(MSG_STR_DOTSO), dotso_len) == 0)
1379 return (tail);
1381 return (NULL);
1386 * Locate the start of the unsuffixed file name within path. Returns pointer
1387 * to first character of that name in path.
1389 * entry:
1390 * path - Path to be examined.
1391 * tail - NULL, or pointer to position at tail of path from which
1392 * the search for '/' characters should start. If NULL,
1393 * strlen() is used to locate the end of the string.
1394 * buf - NULL, or buffer to receive a copy of the characters that
1395 * lie between the start of the filename and tail.
1396 * bufsize - sizeof(buf)
1398 * exit:
1399 * The pointer to the first character of the unsuffixed file name
1400 * within path is returned. If buf is non-NULL, the characters
1401 * lying between that point and tail (or the end of path if tail
1402 * is NULL) are copied into buf.
1404 static const char *
1405 elfedit_basename(const char *path, const char *tail, char *buf, size_t bufsiz)
1407 const char *s;
1409 if (tail == NULL)
1410 tail = path + strlen(path);
1411 s = tail;
1412 while ((s > path) && (*(s - 1) != '/'))
1413 s--;
1414 if (buf != NULL)
1415 elfedit_strnbcpy(buf, s, tail - s, bufsiz);
1416 return (s);
1421 * Issue an error on behalf of load_module(), taking care to release
1422 * resources that routine may have aquired:
1424 * entry:
1425 * moddef - NULL, or a module definition to be released via free()
1426 * dl_hdl - NULL, or a handle to a sharable object to release via
1427 * dlclose().
1428 * dl_path - If dl_hdl is non-NULL, the path to the sharable object
1429 * file that was loaded.
1430 * format - A format string to pass to elfedit_msg(), containing
1431 * no more than (3) %s format codes, and no other format codes.
1432 * [s1-s4] - Strings to pass to elfedit_msg() to satisfy the four
1433 * allowed %s codes in format. Should be set to NULL if the
1434 * format string does not need them.
1436 * note:
1437 * This routine makes a copy of the s1-s4 strings before freeing any
1438 * memory or unmapping the sharable library. It is therefore safe to
1439 * use strings from moddef, or from the sharable library (which will
1440 * be unmapped) to satisfy the other arguments s1-s4.
1442 static void
1443 load_module_err(MODLIST_T *moddef, void *dl_hdl, const char *dl_path,
1444 const char *format, const char *s1, const char *s2, const char *s3,
1445 const char *s4)
1447 #define SCRBUFSIZE (PATH_MAX + 256) /* A path, plus some extra */
1449 char s1_buf[SCRBUFSIZE];
1450 char s2_buf[SCRBUFSIZE];
1451 char s3_buf[SCRBUFSIZE];
1452 char s4_buf[SCRBUFSIZE];
1455 * The caller may provide strings for s1-s3 that are from
1456 * moddef. If we free moddef, the printf() will die on access
1457 * to free memory. We could push back on the user and force
1458 * each call to carefully make copies of such data. However, this
1459 * is an easy case to miss. Furthermore, this is an error case,
1460 * and machine efficiency is not the main issue. We therefore make
1461 * copies of the s1-s3 strings here into auto variables, and then
1462 * use those copies. The user is freed from worrying about it.
1464 * We use oversized stack based buffers instead of malloc() to
1465 * reduce the number of ways that things can go wrong while
1466 * reporting the error.
1468 if (s1 != NULL)
1469 (void) strlcpy(s1_buf, s1, sizeof (s1_buf));
1470 if (s2 != NULL)
1471 (void) strlcpy(s2_buf, s2, sizeof (s2_buf));
1472 if (s3 != NULL)
1473 (void) strlcpy(s3_buf, s3, sizeof (s3_buf));
1474 if (s4 != NULL)
1475 (void) strlcpy(s4_buf, s4, sizeof (s4_buf));
1478 free(moddef);
1480 if ((dl_hdl != NULL) && (dlclose(dl_hdl) != 0))
1481 elfedit_msg(ELFEDIT_MSG_ERR, MSG_INTL(MSG_ERR_CNTDLCLOSE),
1482 dl_path, dlerror());
1484 elfedit_msg(ELFEDIT_MSG_ERR, format, s1_buf, s2_buf, s3_buf, s4_buf);
1485 #undef SCRBUFSIZE
1490 * Load a module sharable object for load_module().
1492 * entry:
1493 * path - Path of file to open
1494 * moddef - If this function issues a non-returning error, it will
1495 * first return the memory referenced by moddef. This argument
1496 * is not used otherwise.
1497 * must_exist - If True, we consider it to be an error if the file given
1498 * by path does not exist. If False, no error is issued
1499 * and a NULL value is quietly returned.
1501 * exit:
1502 * Returns a handle to the loaded object on success, or NULL if no
1503 * file was loaded.
1505 static void *
1506 load_module_dlopen(const char *path, MODLIST_T *moddef, int must_exist)
1508 int fd;
1509 void *hdl;
1512 * If the file is not required to exist, and it doesn't, then
1513 * we want to quietly return without an error.
1515 if (!must_exist) {
1516 fd = open(path, O_RDONLY);
1517 if (fd >= 0) {
1518 (void) close(fd);
1519 } else if (errno == ENOENT) {
1520 return (NULL);
1524 if ((hdl = dlopen(path, RTLD_LAZY|RTLD_FIRST)) == NULL)
1525 load_module_err(moddef, NULL, NULL,
1526 MSG_INTL(MSG_ERR_CNTDLOPEN), path, dlerror(), NULL, NULL);
1528 return (hdl);
1533 * Sanity check option arguments to prevent common errors. The rest of
1534 * elfedit assumes these tests have been done, and does not check
1535 * again.
1537 static void
1538 validate_optarg(elfedit_cmd_optarg_t *optarg, int isopt, MODLIST_T *moddef,
1539 const char *mod_name, const char *cmd_name,
1540 void *dl_hdl, const char *dl_path)
1542 #define FAIL(_msg) errmsg = _msg; goto fail
1544 Msg errmsg;
1545 elfedit_cmd_oa_mask_t optmask = 0;
1547 for (; optarg->oa_name != NULL; optarg++) {
1549 * If ELFEDIT_CMDOA_F_INHERIT is set:
1550 * - oa_name must be a value in the range of
1551 * known ELFEDIT_STDOA_ values.
1552 * - oa_help must be NULL
1553 * - ELFEDIT_CMDOA_F_INHERIT must be the only flag set
1555 if (optarg->oa_flags & ELFEDIT_CMDOA_F_INHERIT) {
1556 if ((((uintptr_t)optarg->oa_name) >
1557 ELFEDIT_NUM_STDOA) ||
1558 (optarg->oa_help != 0) ||
1559 (optarg->oa_flags != ELFEDIT_CMDOA_F_INHERIT))
1561 * Can't use FAIL --- oa_name is not a valid
1562 * string, and load_module_err() looks at args.
1564 load_module_err(moddef, dl_hdl, dl_path,
1565 MSG_INTL(MSG_ERR_BADSTDOA), dl_path,
1566 mod_name, cmd_name, NULL);
1567 continue;
1570 if (isopt) {
1572 * Option name must start with a '-', and must
1573 * have at one following character.
1575 if (optarg->oa_name[0] != '-') {
1576 /* MSG_INTL(MSG_ERR_OPT_MODPRE) */
1577 FAIL(MSG_ERR_OPT_MODPRE);
1579 if (optarg->oa_name[1] == '\0') {
1580 /* MSG_INTL(MSG_ERR_OPT_MODLEN) */
1581 FAIL(MSG_ERR_OPT_MODLEN);
1585 * oa_idmask must be 0, or it must have a single
1586 * bit set (a power of 2).oa_excmask must be 0
1587 * if oa_idmask is 0
1589 if (optarg->oa_idmask == 0) {
1590 if (optarg->oa_excmask != 0) {
1591 /* MSG_INTL(MSG_ERR_OPT_EXCMASKN0) */
1592 FAIL(MSG_ERR_OPT_EXCMASKN0);
1594 } else {
1595 if (elfedit_bits_set(optarg->oa_idmask,
1596 sizeof (optarg->oa_idmask)) != 1) {
1597 /* MSG_INTL(MSG_ERR_OPT_IDMASKPOW2) */
1598 FAIL(MSG_ERR_OPT_IDMASKPOW2);
1601 /* Non-zero idmask must be unique */
1602 if ((optarg->oa_idmask & optmask) != 0) {
1603 /* MSG_INTL(MSG_ERR_OPT_IDMASKUNIQ) */
1604 FAIL(MSG_ERR_OPT_IDMASKUNIQ);
1607 /* Add this one to the overall mask */
1608 optmask |= optarg->oa_idmask;
1610 } else {
1612 * Argument name cannot start with a'-', and must
1613 * not be a null string.
1615 if (optarg->oa_name[0] == '-') {
1616 /* MSG_INTL(MSG_ERR_ARG_MODPRE) */
1617 FAIL(MSG_ERR_ARG_MODPRE);
1619 if (optarg->oa_name[1] == '\0') {
1620 /* MSG_INTL(MSG_ERR_ARG_MODLEN) */
1621 FAIL(MSG_ERR_ARG_MODLEN);
1625 /* oa_idmask and oa_excmask must both be 0 */
1626 if ((optarg->oa_idmask != 0) ||
1627 (optarg->oa_excmask != 0)) {
1628 /* MSG_INTL(MSG_ERR_ARG_MASKNOT0) */
1629 FAIL(MSG_ERR_ARG_MASKNOT0);
1635 * If it takes a value, make sure that we are
1636 * processing options, because CMDOA_F_VALUE is not
1637 * allowed for plain arguments. Then check the following
1638 * item in the list:
1639 * - There must be a following item.
1640 * - oa_name must be non-NULL. This is the only field
1641 * that is used by elfedit.
1642 * - oa_help, oa_flags, oa_idmask, and oa_excmask
1643 * must be 0.
1645 if (optarg->oa_flags & ELFEDIT_CMDOA_F_VALUE) {
1646 elfedit_cmd_optarg_t *oa1 = optarg + 1;
1648 if (!isopt) {
1649 /* MSG_INTL(MSG_ERR_ARG_CMDOA_VAL) */
1650 FAIL(MSG_ERR_ARG_CMDOA_VAL);
1653 if ((optarg + 1)->oa_name == NULL) {
1654 /* MSG_INTL(MSG_ERR_BADMODOPTVAL) */
1655 FAIL(MSG_ERR_BADMODOPTVAL);
1658 if (oa1->oa_name == NULL) {
1659 /* MSG_INTL(MSG_ERR_CMDOA_VALNAM) */
1660 FAIL(MSG_ERR_CMDOA_VALNAM);
1662 if ((oa1->oa_help != (elfedit_i18nhdl_t)NULL) ||
1663 (oa1->oa_flags != 0) ||
1664 (oa1->oa_idmask != 0) || (oa1->oa_excmask != 0)) {
1665 /* MSG_INTL(MSG_ERR_CMDOA_VALNOT0) */
1666 FAIL(MSG_ERR_CMDOA_VALNOT0);
1668 optarg++;
1673 return;
1675 fail:
1676 load_module_err(moddef, dl_hdl, dl_path, MSG_INTL(errmsg),
1677 dl_path, mod_name, cmd_name, optarg->oa_name);
1681 * Look up the specified module, loading the module if necessary,
1682 * and return its definition, or NULL on failure.
1684 * entry:
1685 * name - Name of module to load. If name contains a '/' character or has
1686 * a ".so" suffix, then it is taken to be an absolute file path,
1687 * and is used directly as is. If name does not contain a '/'
1688 * character, then we look for it against the locations in
1689 * the module path, addint the '.so' suffix, and taking the first
1690 * one we find.
1691 * must_exist - If True, we consider it to be an error if we are unable
1692 * to locate a file to load and the module does not already exist.
1693 * If False, NULL is returned quietly in this case.
1694 * allow_abs - True if absolute paths are allowed. False to disallow
1695 * them.
1697 * note:
1698 * If the path is absolute, then we load the file and take the module
1699 * name from the data returned by its elfedit_init() function. If a
1700 * module of that name is already loaded, it is unloaded and replaced
1701 * with the new one.
1703 * If the path is non absolute, then we check to see if the module has
1704 * already been loaded, and if so, we return that module definition.
1705 * In this case, nothing new is loaded. If the module has not been loaded,
1706 * we search the path for it and load it. If the module name provided
1707 * by the elfedit_init() function does not match the name of the file,
1708 * an error results.
1710 elfeditGC_module_t *
1711 elfedit_load_module(const char *name, int must_exist, int allow_abs)
1713 elfedit_init_func_t *init_func;
1714 elfeditGC_module_t *mod;
1715 MODLIST_T *moddef, *insdef;
1716 const char *path;
1717 char path_buf[PATH_MAX + 1];
1718 void *hdl;
1719 size_t i;
1720 int is_abs_path;
1721 elfeditGC_cmd_t *cmd;
1724 * If the name includes a .so suffix, or has any '/' characters,
1725 * then it is an absolute path that we use as is to load the named
1726 * file. Otherwise, we iterate over the path, adding the .so suffix
1727 * and load the first file that matches.
1729 is_abs_path = (path_is_so(name) != NULL) ||
1730 (name != elfedit_basename(name, NULL, NULL, 0));
1732 if (is_abs_path && !allow_abs)
1733 load_module_err(NULL, NULL, NULL,
1734 MSG_INTL(MSG_ERR_UNRECMOD), name, NULL, NULL, NULL);
1737 * If this is a non-absolute path, search for the module already
1738 * having been loaded, and return it if so.
1740 if (!is_abs_path) {
1741 moddef = module_loaded(name, &insdef);
1742 if (moddef != NULL)
1743 return (moddef->ml_mod);
1745 * As a result of module_loaded(), insdef now contains the
1746 * immediate predecessor node for the new one, or NULL if
1747 * it goes at the front. In the absolute-path case, we take
1748 * care of this below, after the sharable object is loaded.
1753 * malloc() a module definition block before trying to dlopen().
1754 * Doing things in the other order can cause the dlopen()'d object
1755 * to leak: If elfedit_malloc() fails, it can cause a jump to the
1756 * outer command loop without returning to the caller. Hence,
1757 * there will be no opportunity to clean up. Allocaing the module
1758 * first allows us to free it if necessary.
1760 moddef = elfedit_malloc(MSG_INTL(MSG_ALLOC_MODDEF),
1761 sizeof (*moddef) + PATH_MAX + 1);
1762 moddef->ml_path = ((char *)moddef) + sizeof (*moddef);
1764 if (is_abs_path) {
1765 path = name;
1766 hdl = load_module_dlopen(name, moddef, must_exist);
1767 } else {
1768 hdl = NULL;
1769 path = path_buf;
1770 for (i = 0; i < state.modpath.n; i++) {
1771 if (snprintf(path_buf, sizeof (path_buf),
1772 MSG_ORIG(MSG_FMT_BLDSOPATH), state.modpath.seg[i],
1773 name) > sizeof (path_buf))
1774 load_module_err(moddef, NULL, NULL,
1775 MSG_INTL(MSG_ERR_PATHTOOLONG),
1776 state.modpath.seg[i], name, NULL, NULL);
1777 hdl = load_module_dlopen(path, moddef, 0);
1779 if (must_exist && (hdl == NULL))
1780 load_module_err(moddef, NULL, NULL,
1781 MSG_INTL(MSG_ERR_UNRECMOD), name, NULL, NULL, NULL);
1784 if (hdl == NULL) {
1785 free(moddef);
1786 return (NULL);
1789 if (state.elf.elfclass == ELFCLASS32) {
1790 init_func = (elfedit_init_func_t *)
1791 dlsym(hdl, MSG_ORIG(MSG_STR_ELFEDITINIT32));
1792 } else {
1793 init_func = (elfedit_init_func_t *)
1794 dlsym(hdl, MSG_ORIG(MSG_STR_ELFEDITINIT64));
1796 if (init_func == NULL)
1797 load_module_err(moddef, hdl, path,
1798 MSG_INTL(MSG_ERR_SONOTMOD), path, NULL, NULL, NULL);
1801 * Note that the init function will be passing us an
1802 * elfedit[32|64]_module_t pointer, which we cast to the
1803 * generic module pointer type in order to be able to manage
1804 * either type with one set of code.
1806 if (!(mod = (elfeditGC_module_t *)(* init_func)(ELFEDIT_VER_CURRENT)))
1807 load_module_err(moddef, hdl, path,
1808 MSG_INTL(MSG_ERR_BADMODLOAD), path, NULL, NULL, NULL);
1811 * Enforce some rules, to help module developers:
1812 * - The primary name of a command must not be
1813 * the empty string ("").
1814 * - Options must start with a '-' followed by at least
1815 * one character.
1816 * - Arguments and options must be well formed.
1818 for (cmd = mod->mod_cmds; cmd->cmd_func != NULL; cmd++) {
1819 if (**cmd->cmd_name == '\0')
1820 load_module_err(moddef, hdl, path,
1821 MSG_INTL(MSG_ERR_NULLPRICMDNAM), mod->mod_name,
1822 NULL, NULL, NULL);
1824 if (cmd->cmd_args != NULL)
1825 validate_optarg(cmd->cmd_args, 0, moddef, mod->mod_name,
1826 cmd->cmd_name[0], hdl, path);
1827 if (cmd->cmd_opt != NULL)
1828 validate_optarg(cmd->cmd_opt, 1, moddef, mod->mod_name,
1829 cmd->cmd_name[0], hdl, path);
1833 * Check the name the module provides. How we handle this depends
1834 * on whether the path is absolute or the result of a path search.
1836 if (is_abs_path) {
1837 MODLIST_T *old_moddef = module_loaded(mod->mod_name, &insdef);
1839 if (old_moddef != NULL) { /* Replace existing */
1840 free(moddef); /* Rare case: Don't need it */
1842 * Be sure we don't unload builtin modules!
1843 * These have a NULL dl_hdl field.
1845 if (old_moddef->ml_dl_hdl == NULL)
1846 load_module_err(NULL, hdl, path,
1847 MSG_INTL(MSG_ERR_CNTULSMOD),
1848 old_moddef->ml_mod->mod_name, NULL,
1849 NULL, NULL);
1851 /* Unload existing */
1852 if (dlclose(old_moddef->ml_dl_hdl) != 0)
1853 elfedit_msg(ELFEDIT_MSG_ERR,
1854 MSG_INTL(MSG_ERR_CNTDLCLOSE),
1855 old_moddef->ml_path, dlerror());
1856 elfedit_msg(ELFEDIT_MSG_DEBUG,
1857 MSG_INTL(MSG_DEBUG_MODUNLOAD),
1858 old_moddef->ml_mod->mod_name, old_moddef->ml_path);
1859 old_moddef->ml_mod = mod;
1860 old_moddef->ml_dl_hdl = hdl;
1861 (void) strlcpy((char *)old_moddef->ml_path, path,
1862 PATH_MAX + 1);
1863 elfedit_msg(ELFEDIT_MSG_DEBUG,
1864 MSG_INTL(MSG_DEBUG_MODLOAD),
1865 old_moddef->ml_mod->mod_name, path);
1866 return (old_moddef->ml_mod);
1869 * insdef now contains the insertion point for the absolute
1870 * path case.
1872 } else {
1873 /* If the names don't match, then error */
1874 if (strcasecmp(name, mod->mod_name) != 0)
1875 load_module_err(moddef, hdl, path,
1876 MSG_INTL(MSG_ERR_BADMODNAME),
1877 mod->mod_name, name, path, NULL);
1881 * Link module into the module list. If insdef is NULL,
1882 * it goes at the head. If insdef is non-NULL, it goes immediately
1883 * after
1885 if (insdef == NULL) {
1886 moddef->ml_next = state.modlist;
1887 state.modlist = moddef;
1888 } else {
1889 moddef->ml_next = insdef->ml_next;
1890 insdef->ml_next = moddef;
1892 moddef->ml_mod = mod;
1893 moddef->ml_dl_hdl = hdl;
1894 (void) strlcpy((char *)moddef->ml_path, path, PATH_MAX + 1);
1896 elfedit_msg(ELFEDIT_MSG_DEBUG, MSG_INTL(MSG_DEBUG_MODLOAD),
1897 moddef->ml_mod->mod_name, path);
1899 return (moddef->ml_mod);
1904 * Unload the specified module
1906 void
1907 elfedit_unload_module(const char *name)
1909 MODLIST_T *moddef, *insdef;
1911 moddef = module_loaded(name, &insdef);
1912 if (moddef == NULL)
1913 return;
1915 /* Built in modules cannot be unloaded. They have a NULL dl_hdl field */
1916 if (moddef->ml_dl_hdl == NULL)
1917 elfedit_msg(ELFEDIT_MSG_ERR, MSG_INTL(MSG_ERR_CNTULSMOD),
1918 moddef->ml_mod->mod_name);
1921 * When we unload it, the name string goes with it. So
1922 * announce it while we still can without having to make a copy.
1924 elfedit_msg(ELFEDIT_MSG_DEBUG, MSG_INTL(MSG_DEBUG_MODUNLOAD),
1925 moddef->ml_mod->mod_name, moddef->ml_path);
1928 * Close it before going further. On failure, we'll jump, and the
1929 * record will remain in the module list. On success,
1930 * we'll retain control, and can safely remove it.
1932 if (dlclose(moddef->ml_dl_hdl) != 0)
1933 elfedit_msg(ELFEDIT_MSG_ERR, MSG_INTL(MSG_ERR_CNTDLCLOSE),
1934 moddef->ml_path, dlerror());
1936 /* Unlink the record from the module list */
1937 if (insdef == NULL)
1938 state.modlist = moddef->ml_next;
1939 else
1940 insdef->ml_next = moddef->ml_next;
1942 /* Release the memory */
1943 free(moddef);
1948 * Load all sharable objects found in the specified directory.
1950 * entry:
1951 * dirpath - Path of directory to process.
1952 * must_exist - If True, it is an error if diropen() fails to open
1953 * the given directory. Of False, we quietly ignore it and return.
1954 * abs_path - If True, files are loaded using their literal paths.
1955 * If False, their module name is extracted from the dirpath
1956 * and a path based search is used to locate it.
1958 void
1959 elfedit_load_moddir(const char *dirpath, int must_exist, int abs_path)
1961 char path[PATH_MAX + 1];
1962 DIR *dir;
1963 struct dirent *dp;
1964 const char *tail;
1966 dir = opendir(dirpath);
1967 if (dir == NULL) {
1968 int err = errno;
1970 if (!must_exist && (err == ENOENT))
1971 return;
1972 elfedit_msg(ELFEDIT_MSG_ERR, MSG_INTL(MSG_ERR_CNTOPNDIR),
1973 dirpath, strerror(err));
1974 /*NOTREACHED*/
1977 while (dp = readdir(dir)) {
1978 if ((tail = path_is_so(dp->d_name)) != NULL) {
1979 if (abs_path) {
1980 (void) snprintf(path, sizeof (path),
1981 MSG_ORIG(MSG_FMT_BLDPATH), dirpath,
1982 dp->d_name);
1983 } else {
1984 (void) elfedit_basename(dp->d_name, tail,
1985 path, sizeof (path));
1987 (void) elfedit_load_module(path, must_exist, 1);
1990 (void) closedir(dir);
1995 * Follow the module load path, and load the first module found for each
1996 * given name.
1998 void
1999 elfedit_load_modpath(void)
2001 size_t i;
2003 for (i = 0; i < state.modpath.n; i++)
2004 elfedit_load_moddir(state.modpath.seg[i], 0, 0);
2008 * Given a module definition, look for the specified command.
2009 * Returns the command if found, and NULL otherwise.
2011 static elfeditGC_cmd_t *
2012 find_cmd(elfeditGC_module_t *mod, const char *name)
2014 elfeditGC_cmd_t *cmd;
2015 const char **cmd_name;
2017 for (cmd = mod->mod_cmds; cmd->cmd_func != NULL; cmd++)
2018 for (cmd_name = cmd->cmd_name; *cmd_name; cmd_name++)
2019 if (strcasecmp(name, *cmd_name) == 0) {
2020 if (cmd_name != cmd->cmd_name)
2021 elfedit_msg(ELFEDIT_MSG_DEBUG,
2022 MSG_INTL(MSG_DEBUG_CMDALIAS),
2023 mod->mod_name, *cmd_name,
2024 mod->mod_name, *cmd->cmd_name);
2025 return (cmd);
2028 return (NULL);
2033 * Given a command name, return its command definition.
2035 * entry:
2036 * name - Command to be looked up
2037 * must_exist - If True, we consider it to be an error if the command
2038 * does not exist. If False, NULL is returned quietly in
2039 * this case.
2040 * mod_ret - NULL, or address of a variable to receive the
2041 * module definition block of the module containing
2042 * the command.
2044 * exit:
2045 * On success, returns a pointer to the command definition, and
2046 * if mod_ret is non-NULL, *mod_ret receives a pointer to the
2047 * module definition. On failure, must_exist determines the
2048 * action taken: If must_exist is True, an error is issued and
2049 * control does not return to the caller. If must_exist is False,
2050 * NULL is quietly returned.
2052 * note:
2053 * A ':' in name is used to delimit the module and command names.
2054 * If it is omitted, or if it is the first non-whitespace character
2055 * in the name, then the built in sys: module is implied.
2057 elfeditGC_cmd_t *
2058 elfedit_find_command(const char *name, int must_exist,
2059 elfeditGC_module_t **mod_ret)
2061 elfeditGC_module_t *mod;
2062 const char *mod_str;
2063 const char *cmd_str;
2064 char mod_buf[ELFEDIT_MAXMODNAM + 1];
2065 size_t n;
2066 elfeditGC_cmd_t *cmd;
2069 cmd_str = strstr(name, MSG_ORIG(MSG_STR_COLON));
2070 if (cmd_str == NULL) { /* No module name -> sys: */
2071 mod_str = MSG_ORIG(MSG_MOD_SYS);
2072 cmd_str = name;
2073 } else if (cmd_str == name) { /* Empty module name -> sys: */
2074 mod_str = MSG_ORIG(MSG_MOD_SYS);
2075 cmd_str++; /* Skip the colon */
2076 } else { /* Have both module and command */
2077 n = cmd_str - name;
2078 if (n >= sizeof (mod_buf)) {
2079 if (must_exist)
2080 elfedit_msg(ELFEDIT_MSG_ERR,
2081 MSG_INTL(MSG_ERR_MODNAMTOOLONG), name);
2082 return (NULL);
2084 (void) strlcpy(mod_buf, name, n + 1);
2085 mod_str = mod_buf;
2086 cmd_str++;
2089 /* Lookup/load module. Won't return on error */
2090 mod = elfedit_load_module(mod_str, must_exist, 0);
2091 if (mod == NULL)
2092 return (NULL);
2094 /* Locate the command */
2095 cmd = find_cmd(mod, cmd_str);
2096 if (cmd == NULL) {
2097 if (must_exist) {
2099 * Catch empty command in order to provide
2100 * a better error message.
2102 if (*cmd_str == '\0') {
2103 elfedit_msg(ELFEDIT_MSG_ERR,
2104 MSG_INTL(MSG_ERR_MODNOCMD), mod_str);
2105 } else {
2106 elfedit_msg(ELFEDIT_MSG_ERR,
2107 MSG_INTL(MSG_ERR_UNRECCMD),
2108 mod_str, cmd_str);
2111 } else {
2112 if (mod_ret != NULL)
2113 *mod_ret = mod;
2115 return (cmd);
2120 * Release all user command blocks found on state.ucmd
2122 static void
2123 free_user_cmds(void)
2125 USER_CMD_T *next;
2127 while (state.ucmd.list) {
2128 next = state.ucmd.list->ucmd_next;
2129 free(state.ucmd.list);
2130 state.ucmd.list = next;
2132 state.ucmd.tail = NULL;
2133 state.ucmd.n = 0;
2134 state.cur_cmd = NULL;
2139 * Process all user command blocks found on state.ucmd, and then
2140 * remove them from the list.
2142 static void
2143 dispatch_user_cmds()
2145 USER_CMD_T *ucmd;
2146 elfedit_cmdret_t cmd_ret;
2148 ucmd = state.ucmd.list;
2149 if (ucmd) {
2150 /* Do them, in order */
2151 for (; ucmd; ucmd = ucmd->ucmd_next) {
2152 state.cur_cmd = ucmd;
2153 if (!state.msg_jbuf.active)
2154 elfedit_msg(ELFEDIT_MSG_DEBUG,
2155 MSG_INTL(MSG_DEBUG_EXECCMD),
2156 ucmd->ucmd_orig_str);
2158 * The cmd_func field is the generic definition.
2159 * We need to cast it to the type that matches
2160 * the proper ELFCLASS before calling it.
2162 if (state.elf.elfclass == ELFCLASS32) {
2163 elfedit32_cmd_func_t *cmd_func =
2164 (elfedit32_cmd_func_t *)
2165 ucmd->ucmd_cmd->cmd_func;
2167 cmd_ret = (* cmd_func)(state.elf.obj_state.s32,
2168 ucmd->ucmd_argc, ucmd->ucmd_argv);
2169 } else {
2170 elfedit64_cmd_func_t *cmd_func =
2171 (elfedit64_cmd_func_t *)
2172 ucmd->ucmd_cmd->cmd_func;
2174 cmd_ret = (* cmd_func)(state.elf.obj_state.s64,
2175 ucmd->ucmd_argc, ucmd->ucmd_argv);
2177 state.cur_cmd = NULL;
2178 /* If a pager was started, wrap it up */
2179 elfedit_pager_cleanup();
2181 switch (cmd_ret) {
2182 case ELFEDIT_CMDRET_MOD_OS_MACH:
2184 * Inform the elfconst module that the machine
2185 * or osabi has has changed. It may be necessary
2186 * to fetch new strings from libconv.
2188 state.elf.elfconst_ehdr_change = 1;
2189 /*FALLTHROUGH*/
2190 case ELFEDIT_CMDRET_MOD:
2192 * Command modified the output ELF image,
2193 * mark the file as needing a flush to disk.
2195 state.file.dirty = 1;
2196 break;
2197 case ELFEDIT_CMDRET_FLUSH:
2199 * Command flushed the output file,
2200 * clear the dirty bit.
2202 state.file.dirty = 0;
2205 free_user_cmds();
2211 * Prepare a GETTOK_STATE struct for gettok().
2213 * entry:
2214 * gettok_state - gettok state block to use
2215 * str - Writable buffer to tokenize. Note that gettok()
2216 * is allowed to change the contents of this buffer.
2217 * inc_null_final - If the line ends in whitespace instead of
2218 * immediately hitting a NULL, and inc_null_final is TRUE,
2219 * then a null final token is generated. Otherwise trailing
2220 * whitespace is ignored.
2222 static void
2223 gettok_init(GETTOK_STATE *gettok_state, char *buf, int inc_null_final)
2225 gettok_state->gtok_buf = gettok_state->gtok_cur_buf = buf;
2226 gettok_state->gtok_inc_null_final = inc_null_final;
2227 gettok_state->gtok_null_seen = 0;
2232 * Locate the next token from the buffer.
2234 * entry:
2235 * gettok_state - State of gettok() operation. Initialized
2236 * by gettok_init(), and passed to gettok().
2238 * exit:
2239 * If a token is found, gettok_state->gtok_last_token is filled in
2240 * with the details and True (1) is returned. If no token is found,
2241 * False (1) is returned, and the contents of
2242 * gettok_state->gtok_last_token are undefined.
2244 * note:
2245 * - The token returned references the memory in gettok_state->gtok_buf.
2246 * The caller should not modify the buffer until all such
2247 * pointers have been discarded.
2248 * - This routine will modify the contents of gettok_state->gtok_buf
2249 * as necessary to remove quotes and eliminate escape
2250 * (\)characters.
2252 static int
2253 gettok(GETTOK_STATE *gettok_state)
2255 char *str = gettok_state->gtok_cur_buf;
2256 char *look;
2257 int quote_ch = '\0';
2259 /* Skip leading whitespace */
2260 while (isspace(*str))
2261 str++;
2263 if (*str == '\0') {
2265 * If user requested it, and there was whitespace at the
2266 * end, then generate one last null token.
2268 if (gettok_state->gtok_inc_null_final &&
2269 !gettok_state->gtok_null_seen) {
2270 gettok_state->gtok_inc_null_final = 0;
2271 gettok_state->gtok_null_seen = 1;
2272 gettok_state->gtok_last_token.tok_str = str;
2273 gettok_state->gtok_last_token.tok_len = 0;
2274 gettok_state->gtok_last_token.tok_line_off =
2275 str - gettok_state->gtok_buf;
2276 return (1);
2278 gettok_state->gtok_null_seen = 1;
2279 return (0);
2283 * Read token: The standard delimiter is whitespace, but
2284 * we honor either single or double quotes. Also, we honor
2285 * backslash escapes.
2287 gettok_state->gtok_last_token.tok_str = look = str;
2288 gettok_state->gtok_last_token.tok_line_off =
2289 look - gettok_state->gtok_buf;
2290 for (; *look; look++) {
2291 if (*look == quote_ch) { /* Terminates active quote */
2292 quote_ch = '\0';
2293 continue;
2296 if (quote_ch == '\0') { /* No quote currently active */
2297 if ((*look == '\'') || (*look == '"')) {
2298 quote_ch = *look; /* New active quote */
2299 continue;
2301 if (isspace(*look))
2302 break;
2306 * The semantics of the backslash character depends on
2307 * the quote style in use:
2308 * - Within single quotes, backslash is not
2309 * an escape character, and is taken literally.
2310 * - If outside of quotes, the backslash is an escape
2311 * character. The backslash is ignored and the
2312 * following character is taken literally, losing
2313 * any special properties it normally has.
2314 * - Within double quotes, backslash works like a
2315 * backslash escape within a C literal. Certain
2316 * escapes are recognized and replaced with their
2317 * special character. Any others are an error.
2319 if (*look == '\\') {
2320 if (quote_ch == '\'') {
2321 *str++ = *look;
2322 continue;
2325 look++;
2326 if (*look == '\0') { /* Esc applied to NULL term? */
2327 elfedit_msg(ELFEDIT_MSG_ERR,
2328 MSG_INTL(MSG_ERR_ESCEOL));
2329 /*NOTREACHED*/
2332 if (quote_ch == '"') {
2333 int ch = conv_translate_c_esc(&look);
2335 if (ch == -1)
2336 elfedit_msg(ELFEDIT_MSG_ERR,
2337 MSG_INTL(MSG_ERR_BADCESC), *look);
2338 *str++ = ch;
2339 look--; /* for() will advance by 1 */
2340 continue;
2344 if (look != str)
2345 *str = *look;
2346 str++;
2349 /* Don't allow unterminated quoted tokens */
2350 if (quote_ch != '\0')
2351 elfedit_msg(ELFEDIT_MSG_ERR, MSG_INTL(MSG_ERR_UNTERMQUOTE),
2352 quote_ch);
2354 gettok_state->gtok_last_token.tok_len = str -
2355 gettok_state->gtok_last_token.tok_str;
2356 gettok_state->gtok_null_seen = *look == '\0';
2357 if (!gettok_state->gtok_null_seen)
2358 look++;
2359 *str = '\0';
2360 gettok_state->gtok_cur_buf = look;
2362 #ifdef DEBUG_GETTOK
2363 printf("GETTOK >");
2364 elfedit_str_to_c_literal(gettok_state->gtok_last_token.tok_str,
2365 elfedit_write);
2366 printf("< \tlen(%d) offset(%d)\n",
2367 gettok_state->gtok_last_token.tok_len,
2368 gettok_state->gtok_last_token.tok_line_off);
2369 #endif
2371 return (1);
2376 * Tokenize the user command string, and return a pointer to the
2377 * TOK_STATE buffer maintained by this function. That buffer contains
2378 * the tokenized strings.
2380 * entry:
2381 * user_cmd_str - String to tokenize
2382 * len - # of characters in user_cmd_str to examine. If
2383 * (len < 0), then the complete string is processed
2384 * stopping with the NULL termination. Otherwise,
2385 * processing stops after len characters, and any
2386 * remaining characters are ignored.
2387 * inc_null_final - If True, and if user_cmd_str has whitespace
2388 * at the end following the last non-null token, then
2389 * a final null token will be included. If False, null
2390 * tokens are ignored.
2392 * note:
2393 * This routine returns pointers to internally allocated memory.
2394 * The caller must not alter anything contained in the TOK_STATE
2395 * buffer returned. Furthermore, the the contents of TOK_STATE
2396 * are only valid until the next call to tokenize_user_cmd().
2398 static TOK_STATE *
2399 tokenize_user_cmd(const char *user_cmd_str, size_t len, int inc_null_final)
2401 #define INITIAL_TOK_ALLOC 5
2404 * As we parse the user command, we need temporary space to
2405 * hold the tokens. We do this by dynamically allocating a string
2406 * buffer and a token array, and doubling them as necessary. This
2407 * is a single threaded application, so static variables suffice.
2409 static STRBUF str;
2410 static TOK_STATE tokst;
2412 GETTOK_STATE gettok_state;
2413 size_t n;
2416 * Make a copy we can modify. If (len == 0), take the entire
2417 * string. Otherwise limit it to the specified length.
2419 tokst.tokst_cmd_len = strlen(user_cmd_str);
2420 if ((len > 0) && (len < tokst.tokst_cmd_len))
2421 tokst.tokst_cmd_len = len;
2422 tokst.tokst_cmd_len++; /* Room for NULL termination */
2423 strbuf_ensure_size(&str, tokst.tokst_cmd_len);
2424 (void) strlcpy(str.buf, user_cmd_str, tokst.tokst_cmd_len);
2426 /* Trim off any newline character that might be present */
2427 if ((tokst.tokst_cmd_len > 1) &&
2428 (str.buf[tokst.tokst_cmd_len - 2] == '\n')) {
2429 tokst.tokst_cmd_len--;
2430 str.buf[tokst.tokst_cmd_len - 1] = '\0';
2433 /* Tokenize the user command string into tok struct */
2434 gettok_init(&gettok_state, str.buf, inc_null_final);
2435 tokst.tokst_str_size = 0; /* Space needed for token strings */
2436 for (tokst.tokst_cnt = 0; gettok(&gettok_state) != 0;
2437 tokst.tokst_cnt++) {
2438 /* If we need more room, expand the token buffer */
2439 if (tokst.tokst_cnt >= tokst.tokst_bufsize) {
2440 n = (tokst.tokst_bufsize == 0) ?
2441 INITIAL_TOK_ALLOC : (tokst.tokst_bufsize * 2);
2442 tokst.tokst_buf = elfedit_realloc(
2443 MSG_INTL(MSG_ALLOC_TOKBUF), tokst.tokst_buf,
2444 n * sizeof (*tokst.tokst_buf));
2445 tokst.tokst_bufsize = n;
2447 tokst.tokst_str_size +=
2448 gettok_state.gtok_last_token.tok_len + 1;
2449 tokst.tokst_buf[tokst.tokst_cnt] = gettok_state.gtok_last_token;
2451 /* fold the command token to lowercase */
2452 if (tokst.tokst_cnt > 0) {
2453 char *s;
2455 for (s = tokst.tokst_buf[0].tok_str; *s; s++)
2456 if (isupper(*s))
2457 *s = tolower(*s);
2460 return (&tokst);
2462 #undef INITIAL_TOK_ALLOC
2467 * Parse the user command string, and put an entry for it at the end
2468 * of state.ucmd.
2470 static void
2471 parse_user_cmd(const char *user_cmd_str)
2473 TOK_STATE *tokst;
2474 char *s;
2475 size_t n;
2476 size_t len;
2477 USER_CMD_T *ucmd;
2478 elfeditGC_module_t *mod;
2479 elfeditGC_cmd_t *cmd;
2482 * Break it into tokens. If there are none, then it is
2483 * an empty command and is ignored.
2485 tokst = tokenize_user_cmd(user_cmd_str, -1, 0);
2486 if (tokst->tokst_cnt == 0)
2487 return;
2489 /* Find the command. Won't return on error */
2490 cmd = elfedit_find_command(tokst->tokst_buf[0].tok_str, 1, &mod);
2493 * If there is no ELF file being edited, then only commands
2494 * from the sys: module are allowed.
2496 if ((state.file.present == 0) &&
2497 (strcmp(mod->mod_name, MSG_ORIG(MSG_MOD_SYS)) != 0))
2498 elfedit_msg(ELFEDIT_MSG_ERR, MSG_INTL(MSG_ERR_NOFILSYSONLY),
2499 mod->mod_name, cmd->cmd_name[0]);
2502 /* Allocate, fill in, and insert a USER_CMD_T block */
2503 n = S_DROUND(sizeof (USER_CMD_T));
2504 ucmd = elfedit_malloc(MSG_INTL(MSG_ALLOC_UCMD),
2505 n + (sizeof (char *) * (tokst->tokst_cnt - 1)) +
2506 tokst->tokst_cmd_len + tokst->tokst_str_size);
2507 ucmd->ucmd_next = NULL;
2508 ucmd->ucmd_argc = tokst->tokst_cnt - 1;
2509 /*LINTED E_BAD_PTR_CAST_ALIGN*/
2510 ucmd->ucmd_argv = (const char **)(n + (char *)ucmd);
2511 ucmd->ucmd_orig_str = (char *)(ucmd->ucmd_argv + ucmd->ucmd_argc);
2512 (void) strncpy(ucmd->ucmd_orig_str, user_cmd_str, tokst->tokst_cmd_len);
2513 ucmd->ucmd_mod = mod;
2514 ucmd->ucmd_cmd = cmd;
2515 ucmd->ucmd_ostyle_set = 0;
2516 s = ucmd->ucmd_orig_str + tokst->tokst_cmd_len;
2517 for (n = 1; n < tokst->tokst_cnt; n++) {
2518 len = tokst->tokst_buf[n].tok_len + 1;
2519 ucmd->ucmd_argv[n - 1] = s;
2520 (void) strncpy(s, tokst->tokst_buf[n].tok_str, len);
2521 s += len;
2523 if (state.ucmd.list == NULL) {
2524 state.ucmd.list = state.ucmd.tail = ucmd;
2525 } else {
2526 state.ucmd.tail->ucmd_next = ucmd;
2527 state.ucmd.tail = ucmd;
2529 state.ucmd.n++;
2534 * Copy infile to a new file with the name given by outfile.
2536 static void
2537 create_outfile(const char *infile, const char *outfile)
2539 pid_t pid;
2540 int statloc;
2541 struct stat statbuf;
2544 pid = fork();
2545 switch (pid) {
2546 case -1: /* Unable to create process */
2548 int err = errno;
2549 elfedit_msg(ELFEDIT_MSG_ERR, MSG_INTL(MSG_ERR_CNTFORK),
2550 strerror(err));
2552 /*NOTREACHED*/
2553 return;
2555 case 0:
2556 (void) execl(MSG_ORIG(MSG_STR_BINCP),
2557 MSG_ORIG(MSG_STR_BINCP), infile, outfile, NULL);
2559 * exec() only returns on error. This is the child process,
2560 * so we want to stay away from the usual error mechanism
2561 * and handle things directly.
2564 int err = errno;
2565 (void) fprintf(stderr, MSG_INTL(MSG_ERR_CNTEXEC),
2566 MSG_ORIG(MSG_STR_ELFEDIT),
2567 MSG_ORIG(MSG_STR_BINCP), strerror(err));
2569 exit(1);
2570 /*NOTREACHED*/
2573 /* This is the parent: Wait for the child to terminate */
2574 if (waitpid(pid, &statloc, 0) != pid) {
2575 int err = errno;
2576 elfedit_msg(ELFEDIT_MSG_ERR, MSG_INTL(MSG_ERR_CNTWAIT),
2577 strerror(err));
2580 * If the child failed, then terminate the process. There is no
2581 * need for an error message, because the child will have taken
2582 * care of that.
2584 if (!WIFEXITED(statloc) || (WEXITSTATUS(statloc) != 0))
2585 exit(1);
2587 /* Make sure the copy allows user write access */
2588 if (stat(outfile, &statbuf) == -1) {
2589 int err = errno;
2590 (void) unlink(outfile);
2591 elfedit_msg(ELFEDIT_MSG_ERR, MSG_INTL(MSG_ERR_CNTSTAT),
2592 outfile, strerror(err));
2594 if ((statbuf.st_mode & S_IWUSR) == 0) {
2595 /* Only keep permission bits, and add user write */
2596 statbuf.st_mode |= S_IWUSR;
2597 statbuf.st_mode &= 07777; /* Only keep the permission bits */
2598 if (chmod(outfile, statbuf.st_mode) == -1) {
2599 int err = errno;
2600 (void) unlink(outfile);
2601 elfedit_msg(ELFEDIT_MSG_ERR, MSG_INTL(MSG_ERR_CNTCHMOD),
2602 outfile, strerror(err));
2608 * Given a module path string, determine how long the resulting path will
2609 * be when all % tokens have been expanded.
2611 * entry:
2612 * path - Path for which expanded length is desired
2613 * origin_root - Root of $ORIGIN tree containing running elfedit program
2615 * exit:
2616 * Returns the value strlen() will give for the expanded path.
2618 static size_t
2619 modpath_strlen(const char *path, const char *origin_root)
2621 size_t len = 0;
2622 const char *s;
2624 s = path;
2625 len = 0;
2626 for (s = path; *s != '\0'; s++) {
2627 if (*s == '%') {
2628 s++;
2629 switch (*s) {
2630 case 'i': /* ISA of running elfedit */
2631 len += strlen(isa_i_str);
2632 break;
2633 case 'I': /* "" for 32-bit, same as %i for 64 */
2634 len += strlen(isa_I_str);
2635 break;
2636 case 'o': /* Insert default path */
2637 len +=
2638 modpath_strlen(MSG_ORIG(MSG_STR_MODPATH),
2639 origin_root);
2640 break;
2641 case 'r': /* root of tree with running elfedit */
2642 len += strlen(origin_root);
2643 break;
2645 case '%': /* %% is reduced to just '%' */
2646 len++;
2647 break;
2648 default: /* All other % codes are reserved */
2649 elfedit_msg(ELFEDIT_MSG_ERR,
2650 MSG_INTL(MSG_ERR_BADPATHCODE), *s);
2651 /*NOTREACHED*/
2652 break;
2654 } else { /* Non-% character passes straight through */
2655 len++;
2659 return (len);
2664 * Given a module path string, and a buffer large enough to hold the results,
2665 * fill the buffer with the expanded path.
2667 * entry:
2668 * path - Path for which expanded length is desired
2669 * origin_root - Root of tree containing running elfedit program
2670 * buf - Buffer to receive the result. buf must as large or larger
2671 * than the value given by modpath_strlen().
2673 * exit:
2674 * Returns pointer to location following the last character
2675 * written to buf. A NULL byte is written to that address.
2677 static char *
2678 modpath_expand(const char *path, const char *origin_root, char *buf)
2680 size_t len;
2681 const char *cp_str;
2683 for (; *path != '\0'; path++) {
2684 if (*path == '%') {
2685 path++;
2686 cp_str = NULL;
2687 switch (*path) {
2688 case 'i': /* ISA of running elfedit */
2689 cp_str = isa_i_str;
2690 break;
2691 case 'I': /* "" for 32-bit, same as %i for 64 */
2692 cp_str = isa_I_str;
2693 break;
2694 case 'o': /* Insert default path */
2695 buf = modpath_expand(MSG_ORIG(MSG_STR_MODPATH),
2696 origin_root, buf);
2697 break;
2698 case 'r':
2699 cp_str = origin_root;
2700 break;
2701 case '%': /* %% is reduced to just '%' */
2702 *buf++ = *path;
2703 break;
2704 default: /* All other % codes are reserved */
2705 elfedit_msg(ELFEDIT_MSG_ERR,
2706 MSG_INTL(MSG_ERR_BADPATHCODE), *path);
2707 /*NOTREACHED*/
2708 break;
2710 if ((cp_str != NULL) && ((len = strlen(cp_str)) > 0)) {
2711 bcopy(cp_str, buf, len);
2712 buf += len;
2714 } else { /* Non-% character passes straight through */
2715 *buf++ = *path;
2719 *buf = '\0';
2720 return (buf);
2725 * Establish the module search path: state.modpath
2727 * The path used comes from the following sources, taking the first
2728 * one that has a value, and ignoring any others:
2730 * - ELFEDIT_PATH environment variable
2731 * - -L command line argument
2732 * - Default value
2734 * entry:
2735 * path - NULL, or the value of the -L command line argument
2737 * exit:
2738 * state.modpath has been filled in
2740 static void
2741 establish_modpath(const char *cmdline_path)
2743 char origin_root[PATH_MAX + 1]; /* Where elfedit binary is */
2744 const char *path; /* Initial path */
2745 char *expath; /* Expanded path */
2746 size_t len;
2747 char *src, *dst;
2749 path = getenv(MSG_ORIG(MSG_STR_ENVVAR));
2750 if (path == NULL)
2751 path = cmdline_path;
2752 if (path == NULL)
2753 path = MSG_ORIG(MSG_STR_MODPATH);
2757 * Root of tree containing running for running program. 32-bit elfedit
2758 * is installed in /usr/bin, and 64-bit elfedit is one level lower
2759 * in an ISA-specific subdirectory. So, we find the root by
2760 * getting the $ORGIN of the current running program, and trimming
2761 * off the last 2 (32-bit) or 3 (64-bit) directories.
2763 * On a standard system, this will simply yield '/'. However,
2764 * doing it this way allows us to run elfedit from a proto area,
2765 * and pick up modules from the same proto area instead of those
2766 * installed on the system.
2768 if (dlinfo(RTLD_SELF, RTLD_DI_ORIGIN, &origin_root) == -1)
2769 elfedit_msg(ELFEDIT_MSG_ERR, MSG_INTL(MSG_ERR_CNTGETORIGIN));
2770 len = (sizeof (char *) == 8) ? 3 : 2;
2771 src = origin_root + strlen(origin_root);
2772 while ((src > origin_root) && (len > 0)) {
2773 if (*(src - 1) == '/')
2774 len--;
2775 src--;
2777 *src = '\0';
2781 * Calculate space needed to hold expanded path. Note that
2782 * this assumes that MSG_STR_MODPATH will never contain a '%o'
2783 * code, and so, the expansion is not recursive. The codes allowed
2784 * are:
2785 * %i - ISA of running elfedit (sparc, sparcv9, etc)
2786 * %I - 64-bit ISA: Same as %i for 64-bit versions of elfedit,
2787 * but yields empty string for 32-bit ISAs.
2788 * %o - The original (default) path.
2789 * %r - Root of tree holding elfedit program.
2790 * %% - A single %
2792 * A % followed by anything else is an error. This allows us to
2793 * add new codes in the future without backward compatability issues.
2795 len = modpath_strlen(path, origin_root);
2797 expath = elfedit_malloc(MSG_INTL(MSG_ALLOC_EXPATH), len + 1);
2798 (void) modpath_expand(path, origin_root, expath);
2801 * Count path segments, eliminate extra '/', and replace ':'
2802 * with NULL.
2804 state.modpath.n = 1;
2805 for (src = dst = expath; *src; src++) {
2806 if (*src == '/') {
2807 switch (*(src + 1)) {
2808 case '/':
2809 case ':':
2810 case '\0':
2811 continue;
2814 if (*src == ':') {
2815 state.modpath.n++;
2816 *dst = '\0';
2817 } else if (src != dst) {
2818 *dst = *src;
2820 dst++;
2822 if (src != dst)
2823 *dst = '\0';
2825 state.modpath.seg = elfedit_malloc(MSG_INTL(MSG_ALLOC_PATHARR),
2826 sizeof (state.modpath.seg[0]) * state.modpath.n);
2828 src = expath;
2829 for (len = 0; len < state.modpath.n; len++) {
2830 if (*src == '\0') {
2831 state.modpath.seg[len] = MSG_ORIG(MSG_STR_DOT);
2832 src++;
2833 } else {
2834 state.modpath.seg[len] = src;
2835 src += strlen(src) + 1;
2841 * When interactive (reading commands from a tty), we catch
2842 * SIGINT in order to restart the outer command loop.
2844 /*ARGSUSED*/
2845 static void
2846 sigint_handler(int sig, siginfo_t *sip, void *ucp)
2848 /* Jump to the outer loop to resume */
2849 if (state.msg_jbuf.active) {
2850 state.msg_jbuf.active = 0;
2851 siglongjmp(state.msg_jbuf.env, 1);
2856 static void
2857 usage(int full)
2859 elfedit_msg(ELFEDIT_MSG_USAGE, MSG_INTL(MSG_USAGE_BRIEF));
2860 if (full) {
2861 elfedit_msg(ELFEDIT_MSG_USAGE, MSG_INTL(MSG_USAGE_DETAIL1));
2862 elfedit_msg(ELFEDIT_MSG_USAGE, MSG_INTL(MSG_USAGE_DETAIL2));
2863 elfedit_msg(ELFEDIT_MSG_USAGE, MSG_INTL(MSG_USAGE_DETAIL3));
2864 elfedit_msg(ELFEDIT_MSG_USAGE, MSG_INTL(MSG_USAGE_DETAIL4));
2865 elfedit_msg(ELFEDIT_MSG_USAGE, MSG_INTL(MSG_USAGE_DETAIL5));
2866 elfedit_msg(ELFEDIT_MSG_USAGE, MSG_INTL(MSG_USAGE_DETAIL6));
2867 elfedit_msg(ELFEDIT_MSG_USAGE, MSG_INTL(MSG_USAGE_DETAIL_LAST));
2869 elfedit_exit(2);
2874 * In order to complete commands, we need to know about them,
2875 * which means that we need to force all the modules to be
2876 * loaded. This is a relatively expensive operation, so we use
2877 * this function, which avoids doing it more than once in a session.
2879 static void
2880 elfedit_cpl_load_modules(void)
2882 static int loaded;
2884 if (!loaded) {
2885 elfedit_load_modpath();
2886 loaded = 1; /* Don't do it again */
2891 * Compare the token to the given string, and if they share a common
2892 * initial sequence, add the tail of string to the tecla command completion
2893 * buffer:
2895 * entry:
2896 * cpldata - Current completion state
2897 * str - String to match against token
2898 * casefold - True to allow case insensitive completion, False
2899 * if case must match exactly.
2901 void
2902 elfedit_cpl_match(void *cpldata, const char *str, int casefold)
2904 ELFEDIT_CPL_STATE *cstate = (ELFEDIT_CPL_STATE *) cpldata;
2905 const char *cont_suffix;
2906 const char *type_suffix;
2909 * Reasons to return immediately:
2910 * - NULL strings have no completion value
2911 * - The string is shorter than the existing item being completed
2913 if ((str == NULL) || (*str == '\0') ||
2914 ((cstate->ecpl_token_len != 0) &&
2915 ((strlen(str) < cstate->ecpl_token_len))))
2916 return;
2918 /* If the string does not share the existing prefix, don't use it */
2919 if (casefold) {
2920 if (strncasecmp(cstate->ecpl_token_str, str,
2921 cstate->ecpl_token_len) != 0)
2922 return;
2923 } else {
2924 if (strncmp(cstate->ecpl_token_str, str,
2925 cstate->ecpl_token_len) != 0)
2926 return;
2929 if (cstate->ecpl_add_mod_colon) {
2930 cont_suffix = type_suffix = MSG_ORIG(MSG_STR_COLON);
2931 } else {
2932 cont_suffix = MSG_ORIG(MSG_STR_SPACE);
2933 type_suffix = NULL;
2935 (void) cpl_add_completion(cstate->ecpl_cpl, cstate->ecpl_line,
2936 cstate->ecpl_word_start, cstate->ecpl_word_end,
2937 str + cstate->ecpl_token_len, type_suffix, cont_suffix);
2943 * Convenience wrapper on elfedit_cpl_match(): Format an unsigned
2944 * 32-bit integer as a string and enter the result for command completion.
2946 void
2947 elfedit_cpl_ndx(void *cpldata, uint_t ndx)
2949 Conv_inv_buf_t buf;
2951 (void) snprintf(buf.buf, sizeof (buf.buf),
2952 MSG_ORIG(MSG_FMT_WORDVAL), ndx);
2953 elfedit_cpl_match(cpldata, buf.buf, 0);
2958 * Compare the token to the names of the commands from the given module,
2959 * and if they share a common initial sequence, add the tail of string
2960 * to the tecla command completion buffer:
2962 * entry:
2963 * tok_buf - Token user has entered
2964 * tok_len - strlen(tok_buf)
2965 * mod - Module definition from which commands should be matched
2966 * cpl, line, word_start, word_end, cont_suffix - As documented
2967 * for gl_get_line() and cpl_add_completion.
2969 static void
2970 match_module_cmds(ELFEDIT_CPL_STATE *cstate, elfeditGC_module_t *mod)
2972 elfeditGC_cmd_t *cmd;
2973 const char **cmd_name;
2975 for (cmd = mod->mod_cmds; cmd->cmd_func != NULL; cmd++)
2976 for (cmd_name = cmd->cmd_name; *cmd_name; cmd_name++)
2977 elfedit_cpl_match(cstate, *cmd_name, 1);
2982 * Compare the token to the known module names, and add those that
2983 * match to the list of alternatives via elfedit_cpl_match().
2985 * entry:
2986 * load_all_modules - If True, causes all modules to be loaded
2987 * before processing is done. If False, only the modules
2988 * currently seen will be used.
2990 void
2991 elfedit_cpl_module(void *cpldata, int load_all_modules)
2993 ELFEDIT_CPL_STATE *cstate = (ELFEDIT_CPL_STATE *) cpldata;
2994 MODLIST_T *modlist;
2996 if (load_all_modules)
2997 elfedit_cpl_load_modules();
2999 for (modlist = state.modlist; modlist != NULL;
3000 modlist = modlist->ml_next) {
3001 elfedit_cpl_match(cstate, modlist->ml_mod->mod_name, 1);
3007 * Compare the token to all the known commands, and add those that
3008 * match to the list of alternatives.
3010 * note:
3011 * This routine will force modules to be loaded as necessary to
3012 * obtain the names it needs to match.
3014 void
3015 elfedit_cpl_command(void *cpldata)
3017 ELFEDIT_CPL_STATE *cstate = (ELFEDIT_CPL_STATE *) cpldata;
3018 ELFEDIT_CPL_STATE colon_state;
3019 const char *colon_pos;
3020 MODLIST_T *modlist;
3021 MODLIST_T *insdef;
3022 char buf[128];
3025 * Is there a colon in the command? If so, locate its offset within
3026 * the raw input line.
3028 for (colon_pos = cstate->ecpl_token_str;
3029 *colon_pos && (*colon_pos != ':'); colon_pos++)
3033 * If no colon was seen, then we are completing a module name,
3034 * or one of the commands from 'sys:'
3036 if (*colon_pos == '\0') {
3038 * Setting cstate->add_mod_colon tells elfedit_cpl_match()
3039 * to add an implicit ':' to the names it matches. We use it
3040 * here so the user doesn't have to enter the ':' manually.
3041 * Hiding this in the opaque state instead of making it
3042 * an argument to that function gives us the ability to
3043 * change it later without breaking the published interface.
3045 cstate->ecpl_add_mod_colon = 1;
3046 elfedit_cpl_module(cpldata, 1);
3047 cstate->ecpl_add_mod_colon = 0;
3049 /* Add bare (no sys: prefix) commands from the sys: module */
3050 match_module_cmds(cstate,
3051 elfedit_load_module(MSG_ORIG(MSG_MOD_SYS), 1, 0));
3053 return;
3057 * A colon was seen, so we have a module name. Extract the name,
3058 * substituting 'sys' for the case where the given name is empty.
3060 if (colon_pos == 0)
3061 (void) strlcpy(buf, MSG_ORIG(MSG_MOD_SYS), sizeof (buf));
3062 else
3063 elfedit_strnbcpy(buf, cstate->ecpl_token_str,
3064 colon_pos - cstate->ecpl_token_str, sizeof (buf));
3067 * Locate the module. If it isn't already loaded, make an explicit
3068 * attempt to load it and try again. If a module definition is
3069 * obtained, process the commands it supplies.
3071 modlist = module_loaded(buf, &insdef);
3072 if (modlist == NULL) {
3073 (void) elfedit_load_module(buf, 0, 0);
3074 modlist = module_loaded(buf, &insdef);
3076 if (modlist != NULL) {
3078 * Make a copy of the cstate, and adjust the line and
3079 * token so that the new one starts just past the colon
3080 * character. We know that the colon exists because
3081 * of the preceeding test that found it. Therefore, we do
3082 * not need to test against running off the end of the
3083 * string here.
3085 colon_state = *cstate;
3086 while (colon_state.ecpl_line[colon_state.ecpl_word_start] !=
3087 ':')
3088 colon_state.ecpl_word_start++;
3089 while (*colon_state.ecpl_token_str != ':') {
3090 colon_state.ecpl_token_str++;
3091 colon_state.ecpl_token_len--;
3093 /* Skip past the ':' character */
3094 colon_state.ecpl_word_start++;
3095 colon_state.ecpl_token_str++;
3096 colon_state.ecpl_token_len--;
3098 match_module_cmds(&colon_state, modlist->ml_mod);
3104 * Command completion function for use with libtacla.
3106 /*ARGSUSED1*/
3107 static int
3108 cmd_match_fcn(WordCompletion *cpl, void *data, const char *line, int word_end)
3110 const char *argv[ELFEDIT_MAXCPLARGS];
3111 ELFEDIT_CPL_STATE cstate;
3112 TOK_STATE *tokst;
3113 int ndx;
3114 int i;
3115 elfeditGC_module_t *mod;
3116 elfeditGC_cmd_t *cmd;
3117 int num_opt;
3118 int opt_term_seen;
3119 int skip_one;
3120 elfedit_cmd_optarg_t *optarg;
3121 elfedit_optarg_item_t item;
3122 int ostyle_ndx = -1;
3125 * For debugging, enable the following block. It tells the tecla
3126 * library that the program using is going to write to stdout.
3127 * It will put the tty back into normal mode, and it will cause
3128 * tecla to redraw the current input line when it gets control back.
3130 #ifdef DEBUG_CMD_MATCH
3131 gl_normal_io(state.input.gl);
3132 #endif
3135 * Tokenize the line up through word_end. The last token in
3136 * the list is the one requiring completion.
3138 tokst = tokenize_user_cmd(line, word_end, 1);
3139 if (tokst->tokst_cnt == 0)
3140 return (0);
3142 /* Set up the cstate block, containing the completion state */
3143 ndx = tokst->tokst_cnt - 1; /* Index of token to complete */
3144 cstate.ecpl_cpl = cpl;
3145 cstate.ecpl_line = line;
3146 cstate.ecpl_word_start = tokst->tokst_buf[ndx].tok_line_off;
3147 cstate.ecpl_word_end = word_end;
3148 cstate.ecpl_add_mod_colon = 0;
3149 cstate.ecpl_token_str = tokst->tokst_buf[ndx].tok_str;
3150 cstate.ecpl_token_len = tokst->tokst_buf[ndx].tok_len;
3153 * If there is only one token, then we are completing the
3154 * command itself.
3156 if (ndx == 0) {
3157 elfedit_cpl_command(&cstate);
3158 return (0);
3162 * There is more than one token. Use the first one to
3163 * locate the definition for the command. If we don't have
3164 * a definition for the command, then there's nothing more
3165 * we can do.
3167 cmd = elfedit_find_command(tokst->tokst_buf[0].tok_str, 0, &mod);
3168 if (cmd == NULL)
3169 return (0);
3172 * Since we know the command, give them a quick usage message.
3173 * It may be that they just need a quick reminder about the form
3174 * of the command and the options.
3176 (void) gl_normal_io(state.input.gl);
3177 elfedit_printf(MSG_INTL(MSG_USAGE_CMD),
3178 elfedit_format_command_usage(mod, cmd, NULL, 0));
3182 * We have a generous setting for ELFEDIT_MAXCPLARGS, so there
3183 * should always be plenty of room. If there's not room, we
3184 * can't proceed.
3186 if (ndx >= ELFEDIT_MAXCPLARGS)
3187 return (0);
3190 * Put pointers to the tokens into argv, and determine how
3191 * many of the tokens are optional arguments.
3193 * We consider the final optional argument to be the rightmost
3194 * argument that starts with a '-'. If a '--' is seen, then
3195 * we stop there, and any argument that follows is a plain argument
3196 * (even if it starts with '-').
3198 * We look for an inherited '-o' option, because we are willing
3199 * to supply command completion for these values.
3201 num_opt = 0;
3202 opt_term_seen = 0;
3203 skip_one = 0;
3204 for (i = 0; i < ndx; i++) {
3205 argv[i] = tokst->tokst_buf[i + 1].tok_str;
3206 if (opt_term_seen || skip_one) {
3207 skip_one = 0;
3208 continue;
3210 skip_one = 0;
3211 ostyle_ndx = -1;
3212 if ((strcmp(argv[i], MSG_ORIG(MSG_STR_MINUS_MINUS)) == 0) ||
3213 (*argv[i] != '-')) {
3214 opt_term_seen = 1;
3215 continue;
3217 num_opt = i + 1;
3219 * If it is a recognised ELFEDIT_CMDOA_F_VALUE option,
3220 * then the item following it is the associated value.
3221 * Check for this and skip the value.
3223 * At the same time, look for STDOA_OPT_O inherited
3224 * options. We want to identify the index of any such
3225 * item. Although the option is simply "-o", we are willing
3226 * to treat any option that starts with "-o" as a potential
3227 * STDOA_OPT_O. This lets us to command completion for things
3228 * like "-onum", and is otherwise harmless, the only cost
3229 * being a few additional strcmps by the cpl code.
3231 if ((optarg = cmd->cmd_opt) == NULL)
3232 continue;
3233 while (optarg->oa_name != NULL) {
3234 int is_ostyle_optarg =
3235 (optarg->oa_flags & ELFEDIT_CMDOA_F_INHERIT) &&
3236 (optarg->oa_name == ELFEDIT_STDOA_OPT_O);
3238 elfedit_next_optarg(&optarg, &item);
3239 if (item.oai_flags & ELFEDIT_CMDOA_F_VALUE) {
3240 if (is_ostyle_optarg && (strncmp(argv[i],
3241 MSG_ORIG(MSG_STR_MINUS_O), 2) == 0))
3242 ostyle_ndx = i + 1;
3244 if (strcmp(item.oai_name, argv[i]) == 0) {
3245 num_opt = i + 2;
3246 skip_one = 1;
3247 break;
3250 * If it didn't match "-o" exactly, but it is
3251 * ostyle_ndx, then it is a potential combined
3252 * STDOA_OPT_O, as discussed above. It counts
3253 * as a single argument.
3255 if (ostyle_ndx == ndx)
3256 break;
3261 #ifdef DEBUG_CMD_MATCH
3262 (void) printf("NDX(%d) NUM_OPT(%d) ostyle_ndx(%d)\n", ndx, num_opt,
3263 ostyle_ndx);
3264 #endif
3266 if (ostyle_ndx != -1) {
3268 * If ostyle_ndx is one less than ndx, and ndx is
3269 * the same as num_opt, then we have a definitive
3270 * STDOA_OPT_O inherited outstyle option. We supply
3271 * the value strings, and are done.
3273 if ((ostyle_ndx == (ndx - 1)) && (ndx == num_opt)) {
3274 elfedit_cpl_atoconst(&cstate, ELFEDIT_CONST_OUTSTYLE);
3275 return (0);
3279 * If ostyle is the same as ndx, then we have an option
3280 * staring with "-o" that may end up being a STDOA_OPT_O,
3281 * and we are still inside that token. In this case, we
3282 * supply completion strings that include the leading
3283 * "-o" followed by the values, without a space
3284 * (i.e. "-onum"). We then fall through, allowing any
3285 * other options starting with "-o" to be added
3286 * below. elfedit_cpl_match() will throw out the incorrect
3287 * options, so it is harmless to add these extra items in
3288 * the worst case, and useful otherwise.
3290 if (ostyle_ndx == ndx)
3291 elfedit_cpl_atoconst(&cstate,
3292 ELFEDIT_CONST_OUTSTYLE_MO);
3296 * If (ndx <= num_opt), then the token needing completion
3297 * is an option. If the leading '-' is there, then we should fill
3298 * in all of the option alternatives. If anything follows the '-'
3299 * though, we assume that the user has already figured out what
3300 * option to use, and we leave well enough alone.
3302 * Note that we are intentionally ignoring a related case
3303 * where supplying option strings would be legal: In the case
3304 * where we are one past the last option (ndx == (num_opt + 1)),
3305 * and the current option is an empty string, the argument can
3306 * be either a plain argument or an option --- the user needs to
3307 * enter the next character before we can tell. It would be
3308 * OK to enter the option strings in this case. However, consider
3309 * what happens when the first plain argument to the command does
3310 * not provide any command completion (e.g. it is a plain integer).
3311 * In this case, tecla will see that all the alternatives start
3312 * with '-', and will insert a '-' into the input. If the user
3313 * intends the next argument to be plain, they will have to delete
3314 * this '-', which is annoying. Worse than that, they may be confused
3315 * by it, and think that the plain argument is not allowed there.
3316 * The best solution is to not supply option strings unless the
3317 * user first enters the '-'.
3319 if ((ndx <= num_opt) && (argv[ndx - 1][0] == '-')) {
3320 if ((optarg = cmd->cmd_opt) != NULL) {
3321 while (optarg->oa_name != NULL) {
3322 elfedit_next_optarg(&optarg, &item);
3323 elfedit_cpl_match(&cstate, item.oai_name, 1);
3326 return (0);
3330 * At this point we know that ndx and num_opt are not equal.
3331 * If num_opt is larger than ndx, then we have an ELFEDIT_CMDOA_F_VALUE
3332 * argument at the end, and the following value has not been entered.
3334 * If ndx is greater than num_opt, it means that we are looking
3335 * at a plain argument (or in the case where (ndx == (num_opt + 1)),
3336 * a *potential* plain argument.
3338 * If the command has a completion function registered, then we
3339 * hand off the remaining work to it. The cmd_cplfunc field is
3340 * the generic definition. We need to cast it to the type that matches
3341 * the proper ELFCLASS before calling it.
3343 if (state.elf.elfclass == ELFCLASS32) {
3344 elfedit32_cmdcpl_func_t *cmdcpl_func =
3345 (elfedit32_cmdcpl_func_t *)cmd->cmd_cplfunc;
3347 if (cmdcpl_func != NULL)
3348 (* cmdcpl_func)(state.elf.obj_state.s32,
3349 &cstate, ndx, argv, num_opt);
3350 } else {
3351 elfedit64_cmdcpl_func_t *cmdcpl_func =
3352 (elfedit64_cmdcpl_func_t *)cmd->cmd_cplfunc;
3354 if (cmdcpl_func != NULL)
3355 (* cmdcpl_func)(state.elf.obj_state.s64,
3356 &cstate, ndx, argv, num_opt);
3359 return (0);
3364 * Read a line of input from stdin, and return pointer to it.
3366 * This routine uses a private buffer, so the contents of the returned
3367 * string are only good until the next call.
3369 static const char *
3370 read_cmd(void)
3372 char *s;
3374 if (state.input.full_tty) {
3375 state.input.in_tecla = TRUE;
3376 s = gl_get_line(state.input.gl,
3377 MSG_ORIG(MSG_STR_PROMPT), NULL, -1);
3378 state.input.in_tecla = FALSE;
3380 * gl_get_line() returns NULL for EOF or for error. EOF is fine,
3381 * but we need to catch and report anything else. Since
3382 * reading from stdin is critical to our operation, an
3383 * error implies that we cannot recover and must exit.
3385 if ((s == NULL) &&
3386 (gl_return_status(state.input.gl) == GLR_ERROR)) {
3387 elfedit_msg(ELFEDIT_MSG_FATAL, MSG_INTL(MSG_ERR_GLREAD),
3388 gl_error_message(state.input.gl, NULL, 0));
3390 } else {
3392 * This should be a dynamically sized buffer, but for now,
3393 * I'm going to take a simpler path.
3395 static char cmd_buf[ELFEDIT_MAXCMD + 1];
3397 s = fgets(cmd_buf, sizeof (cmd_buf), stdin);
3400 /* Return user string, or 'quit' on EOF */
3401 return (s ? s : MSG_ORIG(MSG_SYS_CMD_QUIT));
3405 main(int argc, char **argv, char **envp)
3408 * Note: This function can use setjmp()/longjmp() which does
3409 * not preserve the values of auto/register variables. Hence,
3410 * variables that need their values preserved across a jump must
3411 * be marked volatile, or must not be auto/register.
3413 * Volatile can be messy, because it requires explictly casting
3414 * away the attribute when passing it to functions, or declaring
3415 * those functions with the attribute as well. In a single threaded
3416 * program like this one, an easier approach is to make things
3417 * static. That can be done here, or by putting things in the
3418 * 'state' structure.
3421 int c, i;
3422 int num_batch = 0;
3423 char **batch_list = NULL;
3424 const char *modpath = NULL;
3427 * Always have liblddb display unclipped section names.
3428 * This global is exported by liblddb, and declared in debug.h.
3430 dbg_desc->d_extra |= DBG_E_LONG;
3432 opterr = 0;
3433 while ((c = getopt(argc, argv, MSG_ORIG(MSG_STR_OPTIONS))) != EOF) {
3434 switch (c) {
3435 case 'a':
3436 state.flags |= ELFEDIT_F_AUTOPRINT;
3437 break;
3439 case 'd':
3440 state.flags |= ELFEDIT_F_DEBUG;
3441 break;
3443 case 'e':
3445 * Delay parsing the -e options until after the call to
3446 * conv_check_native() so that we won't bother loading
3447 * modules of the wrong class.
3449 if (batch_list == NULL)
3450 batch_list = elfedit_malloc(
3451 MSG_INTL(MSG_ALLOC_BATCHLST),
3452 sizeof (*batch_list) * (argc - 1));
3453 batch_list[num_batch++] = optarg;
3454 break;
3456 case 'L':
3457 modpath = optarg;
3458 break;
3460 case 'o':
3461 if (elfedit_atooutstyle(optarg, &state.outstyle) == 0)
3462 usage(1);
3463 break;
3465 case 'r':
3466 state.flags |= ELFEDIT_F_READONLY;
3467 break;
3469 case '?':
3470 usage(1);
3475 * We allow 0, 1, or 2 files:
3477 * The no-file case is an extremely limited mode, in which the
3478 * only commands allowed to execute come from the sys: module.
3479 * This mode exists primarily to allow easy access to the help
3480 * facility.
3482 * To get full access to elfedit's capablities, there must
3483 * be an input file. If this is not a readonly
3484 * session, then an optional second output file is allowed.
3486 * In the case where two files are given and the session is
3487 * readonly, use a full usage message, because the simple
3488 * one isn't enough for the user to understand their error.
3489 * Otherwise, the simple usage message suffices.
3491 argc = argc - optind;
3492 if ((argc == 2) && (state.flags & ELFEDIT_F_READONLY))
3493 usage(1);
3494 if (argc > 2)
3495 usage(0);
3497 state.file.present = (argc != 0);
3500 * If we have a file to edit, and unless told otherwise by the
3501 * caller, we try to run the 64-bit version of this program
3502 * when the system is capable of it. If that fails, then we
3503 * continue on with the currently running version.
3505 * To force 32-bit execution on a 64-bit host, set the
3506 * LD_NOEXEC_64 environment variable to a non-empty value.
3508 * There is no reason to bother with this if in "no file" mode.
3510 if (state.file.present != 0)
3511 (void) conv_check_native(argv, envp);
3513 elfedit_msg(ELFEDIT_MSG_DEBUG, MSG_INTL(MSG_DEBUG_VERSION),
3514 (sizeof (char *) == 8) ? 64 : 32);
3517 * Put a module definition for the builtin system module on the
3518 * module list. We know it starts out empty, so we do not have
3519 * to go through a more general insertion process than this.
3521 state.modlist = elfedit_sys_init(ELFEDIT_VER_CURRENT);
3523 /* Establish the search path for loadable modules */
3524 establish_modpath(modpath);
3527 * Now that we are running the final version of this program,
3528 * deal with the input/output file(s).
3530 if (state.file.present == 0) {
3532 * This is arbitrary --- we simply need to be able to
3533 * load modules so that we can access their help strings
3534 * and command completion functions. Without a file, we
3535 * will refuse to call commands from any module other
3536 * than sys. Those commands have been written to be aware
3537 * of the case where there is no input file, and are
3538 * therefore safe to run.
3540 state.elf.elfclass = ELFCLASS32;
3541 elfedit_msg(ELFEDIT_MSG_DEBUG, MSG_INTL(MSG_DEBUG_NOFILE));
3543 } else {
3544 state.file.infile = argv[optind];
3545 if (argc == 1) {
3546 state.file.outfile = state.file.infile;
3547 if (state.flags & ELFEDIT_F_READONLY)
3548 elfedit_msg(ELFEDIT_MSG_DEBUG,
3549 MSG_INTL(MSG_DEBUG_READONLY));
3550 else
3551 elfedit_msg(ELFEDIT_MSG_DEBUG,
3552 MSG_INTL(MSG_DEBUG_INPLACEWARN),
3553 state.file.infile);
3554 } else {
3555 state.file.outfile = argv[optind + 1];
3556 create_outfile(state.file.infile, state.file.outfile);
3557 elfedit_msg(ELFEDIT_MSG_DEBUG,
3558 MSG_INTL(MSG_DEBUG_CPFILE),
3559 state.file.infile, state.file.outfile);
3561 * We are editing a copy of the original file that we
3562 * just created. If we should exit before the edits are
3563 * updated, then we want to unlink this copy so that we
3564 * don't leave junk lying around. Once an update
3565 * succeeds however, we'll leave it in place even
3566 * if an error occurs afterwards.
3568 state.file.unlink_on_exit = 1;
3569 optind++; /* Edit copy instead of the original */
3572 init_obj_state(state.file.outfile);
3577 * Process commands.
3579 * If any -e options were used, then do them and
3580 * immediately exit. On error, exit immediately without
3581 * updating the target ELF file. On success, the 'write'
3582 * and 'quit' commands are implicit in this mode.
3584 * If no -e options are used, read commands from stdin.
3585 * quit must be explicitly used. Exit is implicit on EOF.
3586 * If stdin is a tty, then errors do not cause the editor
3587 * to terminate. Rather, the error message is printed, and the
3588 * user prompted to continue.
3590 if (batch_list != NULL) { /* -e was used */
3591 /* Compile the commands */
3592 for (i = 0; i < num_batch; i++)
3593 parse_user_cmd(batch_list[i]);
3594 free(batch_list);
3597 * 'write' and 'quit' are implicit in this mode.
3598 * Add them as well.
3600 if ((state.flags & ELFEDIT_F_READONLY) == 0)
3601 parse_user_cmd(MSG_ORIG(MSG_SYS_CMD_WRITE));
3602 parse_user_cmd(MSG_ORIG(MSG_SYS_CMD_QUIT));
3604 /* And run them. This won't return, thanks to the 'quit' */
3605 dispatch_user_cmds();
3606 } else {
3607 state.input.is_tty = isatty(fileno(stdin));
3608 state.input.full_tty = state.input.is_tty &&
3609 isatty(fileno(stdout));
3611 if (state.input.full_tty) {
3612 struct sigaction act;
3614 act.sa_sigaction = sigint_handler;
3615 (void) sigemptyset(&act.sa_mask);
3616 act.sa_flags = 0;
3617 if (sigaction(SIGINT, &act, NULL) == -1) {
3618 int err = errno;
3619 elfedit_msg(ELFEDIT_MSG_ERR,
3620 MSG_INTL(MSG_ERR_SIGACTION), strerror(err));
3623 * If pager process exits before we are done
3624 * writing, we can see SIGPIPE. Prevent it
3625 * from killing the process.
3627 (void) sigignore(SIGPIPE);
3629 /* Open tecla handle for command line editing */
3630 state.input.gl = new_GetLine(ELFEDIT_MAXCMD,
3631 ELFEDIT_MAXHIST);
3632 /* Register our command completion function */
3633 (void) gl_customize_completion(state.input.gl,
3634 NULL, cmd_match_fcn);
3637 * Make autoprint the default for interactive
3638 * sessions.
3640 state.flags |= ELFEDIT_F_AUTOPRINT;
3642 for (;;) {
3644 * If this is an interactive session, then use
3645 * sigsetjmp()/siglongjmp() to recover from bad
3646 * commands and keep going. A non-0 return from
3647 * sigsetjmp() means that an error just occurred.
3648 * In that case, we simply restart this loop.
3650 if (state.input.is_tty) {
3651 if (sigsetjmp(state.msg_jbuf.env, 1) != 0) {
3652 if (state.input.full_tty)
3653 gl_abandon_line(state.input.gl);
3654 continue;
3656 state.msg_jbuf.active = TRUE;
3660 * Force all output out before each command.
3661 * This is a no-OP when a tty is in use, but
3662 * in a pipeline, it ensures that the block
3663 * mode buffering doesn't delay output past
3664 * the completion of each command.
3666 * If we didn't do this, the output would eventually
3667 * arrive at its destination, but the lag can be
3668 * annoying when you pipe the output into a tool
3669 * that displays the results in real time.
3671 (void) fflush(stdout);
3672 (void) fflush(stderr);
3674 parse_user_cmd(read_cmd());
3675 dispatch_user_cmds();
3676 state.msg_jbuf.active = FALSE;
3681 /*NOTREACHED*/
3682 return (0);