Index: head/usr.bin/iscsictl/iscsictl.c =================================================================== --- head/usr.bin/iscsictl/iscsictl.c (revision 298878) +++ head/usr.bin/iscsictl/iscsictl.c (revision 298879) @@ -1,980 +1,980 @@ /*- * Copyright (c) 2012 The FreeBSD Foundation * All rights reserved. * * This software was developed by Edward Tomasz Napierala under sponsorship * from the FreeBSD Foundation. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "iscsictl.h" struct conf * conf_new(void) { struct conf *conf; conf = calloc(1, sizeof(*conf)); if (conf == NULL) xo_err(1, "calloc"); TAILQ_INIT(&conf->conf_targets); return (conf); } struct target * target_find(struct conf *conf, const char *nickname) { struct target *targ; TAILQ_FOREACH(targ, &conf->conf_targets, t_next) { if (targ->t_nickname != NULL && strcasecmp(targ->t_nickname, nickname) == 0) return (targ); } return (NULL); } struct target * target_new(struct conf *conf) { struct target *targ; targ = calloc(1, sizeof(*targ)); if (targ == NULL) xo_err(1, "calloc"); targ->t_conf = conf; TAILQ_INSERT_TAIL(&conf->conf_targets, targ, t_next); return (targ); } void target_delete(struct target *targ) { TAILQ_REMOVE(&targ->t_conf->conf_targets, targ, t_next); free(targ); } static char * default_initiator_name(void) { char *name; size_t namelen; int error; namelen = _POSIX_HOST_NAME_MAX + strlen(DEFAULT_IQN); name = calloc(1, namelen + 1); if (name == NULL) xo_err(1, "calloc"); strcpy(name, DEFAULT_IQN); error = gethostname(name + strlen(DEFAULT_IQN), namelen - strlen(DEFAULT_IQN)); if (error != 0) xo_err(1, "gethostname"); return (name); } static bool valid_hex(const char ch) { switch (ch) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case 'a': case 'A': case 'b': case 'B': case 'c': case 'C': case 'd': case 'D': case 'e': case 'E': case 'f': case 'F': return (true); default: return (false); } } bool valid_iscsi_name(const char *name) { int i; if (strlen(name) >= MAX_NAME_LEN) { xo_warnx("overlong name for \"%s\"; max length allowed " "by iSCSI specification is %d characters", name, MAX_NAME_LEN); return (false); } /* * In the cases below, we don't return an error, just in case the admin * was right, and we're wrong. */ if (strncasecmp(name, "iqn.", strlen("iqn.")) == 0) { for (i = strlen("iqn."); name[i] != '\0'; i++) { /* * XXX: We should verify UTF-8 normalisation, as defined * by 3.2.6.2: iSCSI Name Encoding. */ if (isalnum(name[i])) continue; if (name[i] == '-' || name[i] == '.' || name[i] == ':') continue; xo_warnx("invalid character \"%c\" in iSCSI name " "\"%s\"; allowed characters are letters, digits, " "'-', '.', and ':'", name[i], name); break; } /* * XXX: Check more stuff: valid date and a valid reversed domain. */ } else if (strncasecmp(name, "eui.", strlen("eui.")) == 0) { if (strlen(name) != strlen("eui.") + 16) xo_warnx("invalid iSCSI name \"%s\"; the \"eui.\" " "should be followed by exactly 16 hexadecimal " "digits", name); for (i = strlen("eui."); name[i] != '\0'; i++) { if (!valid_hex(name[i])) { xo_warnx("invalid character \"%c\" in iSCSI " "name \"%s\"; allowed characters are 1-9 " "and A-F", name[i], name); break; } } } else if (strncasecmp(name, "naa.", strlen("naa.")) == 0) { if (strlen(name) > strlen("naa.") + 32) xo_warnx("invalid iSCSI name \"%s\"; the \"naa.\" " "should be followed by at most 32 hexadecimal " "digits", name); for (i = strlen("naa."); name[i] != '\0'; i++) { if (!valid_hex(name[i])) { xo_warnx("invalid character \"%c\" in ISCSI " "name \"%s\"; allowed characters are 1-9 " "and A-F", name[i], name); break; } } } else { xo_warnx("invalid iSCSI name \"%s\"; should start with " "either \".iqn\", \"eui.\", or \"naa.\"", name); } return (true); } void conf_verify(struct conf *conf) { struct target *targ; TAILQ_FOREACH(targ, &conf->conf_targets, t_next) { assert(targ->t_nickname != NULL); if (targ->t_session_type == SESSION_TYPE_UNSPECIFIED) targ->t_session_type = SESSION_TYPE_NORMAL; if (targ->t_session_type == SESSION_TYPE_NORMAL && targ->t_name == NULL) xo_errx(1, "missing TargetName for target \"%s\"", targ->t_nickname); if (targ->t_session_type == SESSION_TYPE_DISCOVERY && targ->t_name != NULL) xo_errx(1, "cannot specify TargetName for discovery " "sessions for target \"%s\"", targ->t_nickname); if (targ->t_name != NULL) { if (valid_iscsi_name(targ->t_name) == false) xo_errx(1, "invalid target name \"%s\"", targ->t_name); } if (targ->t_protocol == PROTOCOL_UNSPECIFIED) targ->t_protocol = PROTOCOL_ISCSI; if (targ->t_address == NULL) xo_errx(1, "missing TargetAddress for target \"%s\"", targ->t_nickname); if (targ->t_initiator_name == NULL) targ->t_initiator_name = default_initiator_name(); if (valid_iscsi_name(targ->t_initiator_name) == false) xo_errx(1, "invalid initiator name \"%s\"", targ->t_initiator_name); if (targ->t_header_digest == DIGEST_UNSPECIFIED) targ->t_header_digest = DIGEST_NONE; if (targ->t_data_digest == DIGEST_UNSPECIFIED) targ->t_data_digest = DIGEST_NONE; if (targ->t_auth_method == AUTH_METHOD_UNSPECIFIED) { if (targ->t_user != NULL || targ->t_secret != NULL || targ->t_mutual_user != NULL || targ->t_mutual_secret != NULL) targ->t_auth_method = AUTH_METHOD_CHAP; else targ->t_auth_method = AUTH_METHOD_NONE; } if (targ->t_auth_method == AUTH_METHOD_CHAP) { if (targ->t_user == NULL) { xo_errx(1, "missing chapIName for target \"%s\"", targ->t_nickname); } if (targ->t_secret == NULL) xo_errx(1, "missing chapSecret for target \"%s\"", targ->t_nickname); if (targ->t_mutual_user != NULL || targ->t_mutual_secret != NULL) { if (targ->t_mutual_user == NULL) xo_errx(1, "missing tgtChapName for " "target \"%s\"", targ->t_nickname); if (targ->t_mutual_secret == NULL) xo_errx(1, "missing tgtChapSecret for " "target \"%s\"", targ->t_nickname); } } } } static void conf_from_target(struct iscsi_session_conf *conf, const struct target *targ) { memset(conf, 0, sizeof(*conf)); /* * XXX: Check bounds and return error instead of silently truncating. */ if (targ->t_initiator_name != NULL) strlcpy(conf->isc_initiator, targ->t_initiator_name, sizeof(conf->isc_initiator)); if (targ->t_initiator_address != NULL) strlcpy(conf->isc_initiator_addr, targ->t_initiator_address, sizeof(conf->isc_initiator_addr)); if (targ->t_initiator_alias != NULL) strlcpy(conf->isc_initiator_alias, targ->t_initiator_alias, sizeof(conf->isc_initiator_alias)); if (targ->t_name != NULL) strlcpy(conf->isc_target, targ->t_name, sizeof(conf->isc_target)); if (targ->t_address != NULL) strlcpy(conf->isc_target_addr, targ->t_address, sizeof(conf->isc_target_addr)); if (targ->t_user != NULL) strlcpy(conf->isc_user, targ->t_user, sizeof(conf->isc_user)); if (targ->t_secret != NULL) strlcpy(conf->isc_secret, targ->t_secret, sizeof(conf->isc_secret)); if (targ->t_mutual_user != NULL) strlcpy(conf->isc_mutual_user, targ->t_mutual_user, sizeof(conf->isc_mutual_user)); if (targ->t_mutual_secret != NULL) strlcpy(conf->isc_mutual_secret, targ->t_mutual_secret, sizeof(conf->isc_mutual_secret)); if (targ->t_session_type == SESSION_TYPE_DISCOVERY) conf->isc_discovery = 1; if (targ->t_protocol == PROTOCOL_ISER) conf->isc_iser = 1; if (targ->t_offload != NULL) strlcpy(conf->isc_offload, targ->t_offload, sizeof(conf->isc_offload)); if (targ->t_header_digest == DIGEST_CRC32C) conf->isc_header_digest = ISCSI_DIGEST_CRC32C; else conf->isc_header_digest = ISCSI_DIGEST_NONE; if (targ->t_data_digest == DIGEST_CRC32C) conf->isc_data_digest = ISCSI_DIGEST_CRC32C; else conf->isc_data_digest = ISCSI_DIGEST_NONE; } static int kernel_add(int iscsi_fd, const struct target *targ) { struct iscsi_session_add isa; int error; memset(&isa, 0, sizeof(isa)); conf_from_target(&isa.isa_conf, targ); error = ioctl(iscsi_fd, ISCSISADD, &isa); if (error != 0) xo_warn("ISCSISADD"); return (error); } static int kernel_modify(int iscsi_fd, unsigned int session_id, const struct target *targ) { struct iscsi_session_modify ism; int error; memset(&ism, 0, sizeof(ism)); ism.ism_session_id = session_id; conf_from_target(&ism.ism_conf, targ); error = ioctl(iscsi_fd, ISCSISMODIFY, &ism); if (error != 0) xo_warn("ISCSISMODIFY"); return (error); } static void kernel_modify_some(int iscsi_fd, unsigned int session_id, const char *target, const char *target_addr, const char *user, const char *secret) { struct iscsi_session_state *states = NULL; struct iscsi_session_state *state; struct iscsi_session_conf *conf; struct iscsi_session_list isl; struct iscsi_session_modify ism; unsigned int i, nentries = 1; int error; for (;;) { states = realloc(states, nentries * sizeof(struct iscsi_session_state)); if (states == NULL) xo_err(1, "realloc"); memset(&isl, 0, sizeof(isl)); isl.isl_nentries = nentries; isl.isl_pstates = states; error = ioctl(iscsi_fd, ISCSISLIST, &isl); if (error != 0 && errno == EMSGSIZE) { nentries *= 4; continue; } break; } if (error != 0) xo_errx(1, "ISCSISLIST"); for (i = 0; i < isl.isl_nentries; i++) { state = &states[i]; if (state->iss_id == session_id) break; } if (i == isl.isl_nentries) xo_errx(1, "session-id %u not found", session_id); conf = &state->iss_conf; if (target != NULL) strlcpy(conf->isc_target, target, sizeof(conf->isc_target)); if (target_addr != NULL) strlcpy(conf->isc_target_addr, target_addr, sizeof(conf->isc_target_addr)); if (user != NULL) strlcpy(conf->isc_user, user, sizeof(conf->isc_user)); if (secret != NULL) strlcpy(conf->isc_secret, secret, sizeof(conf->isc_secret)); memset(&ism, 0, sizeof(ism)); ism.ism_session_id = session_id; memcpy(&ism.ism_conf, conf, sizeof(ism.ism_conf)); error = ioctl(iscsi_fd, ISCSISMODIFY, &ism); if (error != 0) xo_warn("ISCSISMODIFY"); } static int kernel_remove(int iscsi_fd, const struct target *targ) { struct iscsi_session_remove isr; int error; memset(&isr, 0, sizeof(isr)); conf_from_target(&isr.isr_conf, targ); error = ioctl(iscsi_fd, ISCSISREMOVE, &isr); if (error != 0) xo_warn("ISCSISREMOVE"); return (error); } /* * XXX: Add filtering. */ static int kernel_list(int iscsi_fd, const struct target *targ __unused, int verbose) { struct iscsi_session_state *states = NULL; const struct iscsi_session_state *state; const struct iscsi_session_conf *conf; struct iscsi_session_list isl; unsigned int i, nentries = 1; int error; for (;;) { states = realloc(states, nentries * sizeof(struct iscsi_session_state)); if (states == NULL) xo_err(1, "realloc"); memset(&isl, 0, sizeof(isl)); isl.isl_nentries = nentries; isl.isl_pstates = states; error = ioctl(iscsi_fd, ISCSISLIST, &isl); if (error != 0 && errno == EMSGSIZE) { nentries *= 4; continue; } break; } if (error != 0) { xo_warn("ISCSISLIST"); return (error); } if (verbose != 0) { xo_open_list("session"); for (i = 0; i < isl.isl_nentries; i++) { state = &states[i]; conf = &state->iss_conf; xo_open_instance("session"); /* * Display-only modifier as this information * is also present within the 'session' container */ xo_emit("{L:/%-18s}{V:sessionId/%u}\n", "Session ID:", state->iss_id); xo_open_container("initiator"); xo_emit("{L:/%-18s}{V:name/%s}\n", "Initiator name:", conf->isc_initiator); xo_emit("{L:/%-18s}{V:portal/%s}\n", "Initiator portal:", conf->isc_initiator_addr); xo_emit("{L:/%-18s}{V:alias/%s}\n", "Initiator alias:", conf->isc_initiator_alias); xo_close_container("initiator"); xo_open_container("target"); xo_emit("{L:/%-18s}{V:name/%s}\n", "Target name:", conf->isc_target); xo_emit("{L:/%-18s}{V:portal/%s}\n", "Target portal:", conf->isc_target_addr); xo_emit("{L:/%-18s}{V:alias/%s}\n", "Target alias:", state->iss_target_alias); xo_close_container("target"); xo_open_container("auth"); xo_emit("{L:/%-18s}{V:user/%s}\n", "User:", conf->isc_user); xo_emit("{L:/%-18s}{V:secret/%s}\n", "Secret:", conf->isc_secret); xo_emit("{L:/%-18s}{V:mutualUser/%s}\n", "Mutual user:", conf->isc_mutual_user); xo_emit("{L:/%-18s}{V:mutualSecret/%s}\n", "Mutual secret:", conf->isc_mutual_secret); xo_close_container("auth"); xo_emit("{L:/%-18s}{V:type/%s}\n", "Session type:", conf->isc_discovery ? "Discovery" : "Normal"); xo_emit("{L:/%-18s}{V:state/%s}\n", "Session state:", state->iss_connected ? "Connected" : "Disconnected"); xo_emit("{L:/%-18s}{V:failureReason/%s}\n", "Failure reason:", state->iss_reason); xo_emit("{L:/%-18s}{V:headerDigest/%s}\n", "Header digest:", state->iss_header_digest == ISCSI_DIGEST_CRC32C ? "CRC32C" : "None"); xo_emit("{L:/%-18s}{V:dataDigest/%s}\n", "Data digest:", state->iss_data_digest == ISCSI_DIGEST_CRC32C ? "CRC32C" : "None"); xo_emit("{L:/%-18s}{V:dataSegmentLen/%d}\n", "DataSegmentLen:", state->iss_max_data_segment_length); xo_emit("{L:/%-18s}{V:immediateData/%s}\n", "ImmediateData:", state->iss_immediate_data ? "Yes" : "No"); xo_emit("{L:/%-18s}{V:iSER/%s}\n", "iSER (RDMA):", conf->isc_iser ? "Yes" : "No"); xo_emit("{L:/%-18s}{V:offloadDriver/%s}\n", "Offload driver:", state->iss_offload); xo_emit("{L:/%-18s}", "Device nodes:"); print_periphs(state->iss_id); xo_emit("\n\n"); xo_close_instance("session"); } xo_close_list("session"); } else { xo_emit("{T:/%-36s} {T:/%-16s} {T:/%s}\n", "Target name", "Target portal", "State"); if (isl.isl_nentries != 0) xo_open_list("session"); for (i = 0; i < isl.isl_nentries; i++) { state = &states[i]; conf = &state->iss_conf; xo_open_instance("session"); xo_emit("{V:name/%-36s/%s} {V:portal/%-16s/%s} ", conf->isc_target, conf->isc_target_addr); if (state->iss_reason[0] != '\0') { xo_emit("{V:state/%s}\n", state->iss_reason); } else { if (conf->isc_discovery) { xo_emit("{V:state}\n", "Discovery"); } else if (state->iss_connected) { xo_emit("{V:state}: ", "Connected"); print_periphs(state->iss_id); xo_emit("\n"); } else { xo_emit("{V:state}\n", "Disconnected"); } } xo_close_instance("session"); } if (isl.isl_nentries != 0) xo_close_list("session"); } return (0); } static int kernel_wait(int iscsi_fd, int timeout) { struct iscsi_session_state *states = NULL; const struct iscsi_session_state *state; struct iscsi_session_list isl; unsigned int i, nentries = 1; bool all_connected; int error; for (;;) { for (;;) { states = realloc(states, nentries * sizeof(struct iscsi_session_state)); if (states == NULL) xo_err(1, "realloc"); memset(&isl, 0, sizeof(isl)); isl.isl_nentries = nentries; isl.isl_pstates = states; error = ioctl(iscsi_fd, ISCSISLIST, &isl); if (error != 0 && errno == EMSGSIZE) { nentries *= 4; continue; } break; } if (error != 0) { xo_warn("ISCSISLIST"); return (error); } all_connected = true; for (i = 0; i < isl.isl_nentries; i++) { state = &states[i]; if (!state->iss_connected) { all_connected = false; break; } } if (all_connected) return (0); sleep(1); if (timeout > 0) { timeout--; if (timeout == 0) return (1); } } } static void usage(void) { fprintf(stderr, "usage: iscsictl -A -p portal -t target " "[-u user -s secret] [-w timeout]\n"); fprintf(stderr, " iscsictl -A -d discovery-host " "[-u user -s secret]\n"); fprintf(stderr, " iscsictl -A -a [-c path]\n"); fprintf(stderr, " iscsictl -A -n nickname [-c path]\n"); fprintf(stderr, " iscsictl -M -i session-id [-p portal] " "[-t target] [-u user] [-s secret]\n"); fprintf(stderr, " iscsictl -M -i session-id -n nickname " "[-c path]\n"); fprintf(stderr, " iscsictl -R [-p portal] [-t target]\n"); fprintf(stderr, " iscsictl -R -a\n"); fprintf(stderr, " iscsictl -R -n nickname [-c path]\n"); fprintf(stderr, " iscsictl -L [-v] [-w timeout]\n"); exit(1); } char * checked_strdup(const char *s) { char *c; c = strdup(s); if (c == NULL) xo_err(1, "strdup"); return (c); } int main(int argc, char **argv) { int Aflag = 0, Mflag = 0, Rflag = 0, Lflag = 0, aflag = 0, vflag = 0; const char *conf_path = DEFAULT_CONFIG_PATH; char *nickname = NULL, *discovery_host = NULL, *portal = NULL, *target = NULL, *user = NULL, *secret = NULL; int timeout = -1; long long session_id = -1; char *end; int ch, error, iscsi_fd, retval, saved_errno; int failed = 0; struct conf *conf; struct target *targ; argc = xo_parse_args(argc, argv); xo_open_container("iscsictl"); while ((ch = getopt(argc, argv, "AMRLac:d:i:n:p:t:u:s:vw:")) != -1) { switch (ch) { case 'A': Aflag = 1; break; case 'M': Mflag = 1; break; case 'R': Rflag = 1; break; case 'L': Lflag = 1; break; case 'a': aflag = 1; break; case 'c': conf_path = optarg; break; case 'd': discovery_host = optarg; break; case 'i': session_id = strtol(optarg, &end, 10); if ((size_t)(end - optarg) != strlen(optarg)) xo_errx(1, "trailing characters after session-id"); if (session_id < 0) xo_errx(1, "session-id cannot be negative"); if (session_id > UINT_MAX) xo_errx(1, "session-id cannot be greater than %u", UINT_MAX); break; case 'n': nickname = optarg; break; case 'p': portal = optarg; break; case 't': target = optarg; break; case 'u': user = optarg; break; case 's': secret = optarg; break; case 'v': vflag = 1; break; case 'w': timeout = strtol(optarg, &end, 10); if ((size_t)(end - optarg) != strlen(optarg)) xo_errx(1, "trailing characters after timeout"); if (timeout < 0) xo_errx(1, "timeout cannot be negative"); break; case '?': default: usage(); } } argc -= optind; if (argc != 0) usage(); if (Aflag + Mflag + Rflag + Lflag == 0) Lflag = 1; if (Aflag + Mflag + Rflag + Lflag > 1) xo_errx(1, "at most one of -A, -M, -R, or -L may be specified"); /* - * Note that we ignore unneccessary/inapplicable "-c" flag; so that + * Note that we ignore unnecessary/inapplicable "-c" flag; so that * people can do something like "alias ISCSICTL="iscsictl -c path" * in shell scripts. */ if (Aflag != 0) { if (aflag != 0) { if (portal != NULL) xo_errx(1, "-a and -p and mutually exclusive"); if (target != NULL) xo_errx(1, "-a and -t and mutually exclusive"); if (user != NULL) xo_errx(1, "-a and -u and mutually exclusive"); if (secret != NULL) xo_errx(1, "-a and -s and mutually exclusive"); if (nickname != NULL) xo_errx(1, "-a and -n and mutually exclusive"); if (discovery_host != NULL) xo_errx(1, "-a and -d and mutually exclusive"); } else if (nickname != NULL) { if (portal != NULL) xo_errx(1, "-n and -p and mutually exclusive"); if (target != NULL) xo_errx(1, "-n and -t and mutually exclusive"); if (user != NULL) xo_errx(1, "-n and -u and mutually exclusive"); if (secret != NULL) xo_errx(1, "-n and -s and mutually exclusive"); if (discovery_host != NULL) xo_errx(1, "-n and -d and mutually exclusive"); } else if (discovery_host != NULL) { if (portal != NULL) xo_errx(1, "-d and -p and mutually exclusive"); if (target != NULL) xo_errx(1, "-d and -t and mutually exclusive"); } else { if (target == NULL && portal == NULL) xo_errx(1, "must specify -a, -n or -t/-p"); if (target != NULL && portal == NULL) xo_errx(1, "-t must always be used with -p"); if (portal != NULL && target == NULL) xo_errx(1, "-p must always be used with -t"); } if (user != NULL && secret == NULL) xo_errx(1, "-u must always be used with -s"); if (secret != NULL && user == NULL) xo_errx(1, "-s must always be used with -u"); if (session_id != -1) xo_errx(1, "-i cannot be used with -A"); if (vflag != 0) xo_errx(1, "-v cannot be used with -A"); } else if (Mflag != 0) { if (session_id == -1) xo_errx(1, "-M requires -i"); if (discovery_host != NULL) xo_errx(1, "-M and -d are mutually exclusive"); if (aflag != 0) xo_errx(1, "-M and -a are mutually exclusive"); if (nickname != NULL) { if (portal != NULL) xo_errx(1, "-n and -p and mutually exclusive"); if (target != NULL) xo_errx(1, "-n and -t and mutually exclusive"); if (user != NULL) xo_errx(1, "-n and -u and mutually exclusive"); if (secret != NULL) xo_errx(1, "-n and -s and mutually exclusive"); } if (vflag != 0) xo_errx(1, "-v cannot be used with -M"); if (timeout != -1) xo_errx(1, "-w cannot be used with -M"); } else if (Rflag != 0) { if (user != NULL) xo_errx(1, "-R and -u are mutually exclusive"); if (secret != NULL) xo_errx(1, "-R and -s are mutually exclusive"); if (discovery_host != NULL) xo_errx(1, "-R and -d are mutually exclusive"); if (aflag != 0) { if (portal != NULL) xo_errx(1, "-a and -p and mutually exclusive"); if (target != NULL) xo_errx(1, "-a and -t and mutually exclusive"); if (nickname != NULL) xo_errx(1, "-a and -n and mutually exclusive"); } else if (nickname != NULL) { if (portal != NULL) xo_errx(1, "-n and -p and mutually exclusive"); if (target != NULL) xo_errx(1, "-n and -t and mutually exclusive"); } else if (target == NULL && portal == NULL) { xo_errx(1, "must specify either -a, -n, -t, or -p"); } if (session_id != -1) xo_errx(1, "-i cannot be used with -R"); if (vflag != 0) xo_errx(1, "-v cannot be used with -R"); if (timeout != -1) xo_errx(1, "-w cannot be used with -R"); } else { assert(Lflag != 0); if (portal != NULL) xo_errx(1, "-L and -p and mutually exclusive"); if (target != NULL) xo_errx(1, "-L and -t and mutually exclusive"); if (user != NULL) xo_errx(1, "-L and -u and mutually exclusive"); if (secret != NULL) xo_errx(1, "-L and -s and mutually exclusive"); if (nickname != NULL) xo_errx(1, "-L and -n and mutually exclusive"); if (discovery_host != NULL) xo_errx(1, "-L and -d and mutually exclusive"); if (session_id != -1) xo_errx(1, "-i cannot be used with -L"); } iscsi_fd = open(ISCSI_PATH, O_RDWR); if (iscsi_fd < 0 && errno == ENOENT) { saved_errno = errno; retval = kldload("iscsi"); if (retval != -1) iscsi_fd = open(ISCSI_PATH, O_RDWR); else errno = saved_errno; } if (iscsi_fd < 0) xo_err(1, "failed to open %s", ISCSI_PATH); if (Aflag != 0 && aflag != 0) { conf = conf_new_from_file(conf_path); TAILQ_FOREACH(targ, &conf->conf_targets, t_next) failed += kernel_add(iscsi_fd, targ); } else if (nickname != NULL) { conf = conf_new_from_file(conf_path); targ = target_find(conf, nickname); if (targ == NULL) xo_errx(1, "target %s not found in %s", nickname, conf_path); if (Aflag != 0) failed += kernel_add(iscsi_fd, targ); else if (Mflag != 0) failed += kernel_modify(iscsi_fd, session_id, targ); else if (Rflag != 0) failed += kernel_remove(iscsi_fd, targ); else failed += kernel_list(iscsi_fd, targ, vflag); } else if (Mflag != 0) { kernel_modify_some(iscsi_fd, session_id, target, portal, user, secret); } else { if (Aflag != 0 && target != NULL) { if (valid_iscsi_name(target) == false) xo_errx(1, "invalid target name \"%s\"", target); } conf = conf_new(); targ = target_new(conf); targ->t_initiator_name = default_initiator_name(); targ->t_header_digest = DIGEST_NONE; targ->t_data_digest = DIGEST_NONE; targ->t_name = target; if (discovery_host != NULL) { targ->t_session_type = SESSION_TYPE_DISCOVERY; targ->t_address = discovery_host; } else { targ->t_session_type = SESSION_TYPE_NORMAL; targ->t_address = portal; } targ->t_user = user; targ->t_secret = secret; if (Aflag != 0) failed += kernel_add(iscsi_fd, targ); else if (Rflag != 0) failed += kernel_remove(iscsi_fd, targ); else failed += kernel_list(iscsi_fd, targ, vflag); } if (timeout != -1) failed += kernel_wait(iscsi_fd, timeout); error = close(iscsi_fd); if (error != 0) xo_err(1, "close"); if (failed > 0) return (1); xo_close_container("iscsictl"); xo_finish(); return (0); } Index: head/usr.bin/m4/eval.c =================================================================== --- head/usr.bin/m4/eval.c (revision 298878) +++ head/usr.bin/m4/eval.c (revision 298879) @@ -1,1014 +1,1014 @@ /* $OpenBSD: eval.c,v 1.74 2015/02/05 12:59:57 millert Exp $ */ /* $NetBSD: eval.c,v 1.7 1996/11/10 21:21:29 pk Exp $ */ /* * Copyright (c) 1989, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Ozan Yigit at York University. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); /* * eval.c * Facility: m4 macro processor * by: oz */ #include #include #include #include #include #include #include #include #include #include #include #include "mdef.h" #include "stdd.h" #include "extern.h" #include "pathnames.h" static void dodefn(const char *); static void dopushdef(const char *, const char *); static void dodump(const char *[], int); static void dotrace(const char *[], int, int); static void doifelse(const char *[], int); static int doincl(const char *); static int dopaste(const char *); static void dochq(const char *[], int); static void dochc(const char *[], int); static void dom4wrap(const char *); static void dodiv(int); static void doundiv(const char *[], int); static void dosub(const char *[], int); static void map(char *, const char *, const char *, const char *); static const char *handledash(char *, char *, const char *); static void expand_builtin(const char *[], int, int); static void expand_macro(const char *[], int); static void dump_one_def(const char *, struct macro_definition *); unsigned long expansion_id; /* * eval - eval all macros and builtins calls * argc - number of elements in argv. * argv - element vector : * argv[0] = definition of a user * macro or NULL if built-in. * argv[1] = name of the macro or * built-in. * argv[2] = parameters to user-defined * . macro or built-in. * . * * A call in the form of macro-or-builtin() will result in: * argv[0] = nullstr * argv[1] = macro-or-builtin * argv[2] = nullstr * * argc is 3 for macro-or-builtin() and 2 for macro-or-builtin */ void eval(const char *argv[], int argc, int td, int is_traced) { size_t mark = SIZE_MAX; expansion_id++; if (td & RECDEF) m4errx(1, "expanding recursive definition for %s.", argv[1]); if (is_traced) mark = trace(argv, argc, infile+ilevel); if (td == MACRTYPE) expand_macro(argv, argc); else expand_builtin(argv, argc, td); if (mark != SIZE_MAX) finish_trace(mark); } /* * expand_builtin - evaluate built-in macros. */ void expand_builtin(const char *argv[], int argc, int td) { int c, n; int ac; static int sysval = 0; #ifdef DEBUG printf("argc = %d\n", argc); for (n = 0; n < argc; n++) printf("argv[%d] = %s\n", n, argv[n]); fflush(stdout); #endif /* * if argc == 3 and argv[2] is null, then we * have macro-or-builtin() type call. We adjust * argc to avoid further checking.. */ /* we keep the initial value for those built-ins that differentiate * between builtin() and builtin. */ ac = argc; if (argc == 3 && !*(argv[2]) && !mimic_gnu) argc--; switch (td & TYPEMASK) { case DEFITYPE: if (argc > 2) dodefine(argv[2], (argc > 3) ? argv[3] : null); break; case PUSDTYPE: if (argc > 2) dopushdef(argv[2], (argc > 3) ? argv[3] : null); break; case DUMPTYPE: dodump(argv, argc); break; case TRACEONTYPE: dotrace(argv, argc, 1); break; case TRACEOFFTYPE: dotrace(argv, argc, 0); break; case EXPRTYPE: /* * doexpr - evaluate arithmetic * expression */ { int base = 10; int maxdigits = 0; const char *errstr; if (argc > 3) { base = strtonum(argv[3], 2, 36, &errstr); if (errstr) { m4errx(1, "expr: base %s invalid.", argv[3]); } } if (argc > 4) { maxdigits = strtonum(argv[4], 0, INT_MAX, &errstr); if (errstr) { m4errx(1, "expr: maxdigits %s invalid.", argv[4]); } } if (argc > 2) pbnumbase(expr(argv[2]), base, maxdigits); break; } case IFELTYPE: if (argc > 4) doifelse(argv, argc); break; case IFDFTYPE: /* * doifdef - select one of two * alternatives based on the existence of * another definition */ if (argc > 3) { if (lookup_macro_definition(argv[2]) != NULL) pbstr(argv[3]); else if (argc > 4) pbstr(argv[4]); } break; case LENGTYPE: /* * dolen - find the length of the * argument */ pbnum((argc > 2) ? strlen(argv[2]) : 0); break; case INCRTYPE: /* * doincr - increment the value of the * argument */ if (argc > 2) pbnum(atoi(argv[2]) + 1); break; case DECRTYPE: /* * dodecr - decrement the value of the * argument */ if (argc > 2) pbnum(atoi(argv[2]) - 1); break; case SYSCTYPE: /* * dosys - execute system command */ if (argc > 2) { fflush(stdout); sysval = system(argv[2]); } break; case SYSVTYPE: /* * dosysval - return value of the last * system call. * */ pbnum(sysval); break; case ESYSCMDTYPE: if (argc > 2) doesyscmd(argv[2]); break; case INCLTYPE: if (argc > 2) { if (!doincl(argv[2])) { if (mimic_gnu) { warn("%s at line %lu: include(%s)", CURRENT_NAME, CURRENT_LINE, argv[2]); exit_code = 1; } else err(1, "%s at line %lu: include(%s)", CURRENT_NAME, CURRENT_LINE, argv[2]); } } break; case SINCTYPE: if (argc > 2) (void) doincl(argv[2]); break; #ifdef EXTENDED case PASTTYPE: if (argc > 2) if (!dopaste(argv[2])) err(1, "%s at line %lu: paste(%s)", CURRENT_NAME, CURRENT_LINE, argv[2]); break; case SPASTYPE: if (argc > 2) (void) dopaste(argv[2]); break; case FORMATTYPE: doformat(argv, argc); break; #endif case CHNQTYPE: dochq(argv, ac); break; case CHNCTYPE: dochc(argv, argc); break; case SUBSTYPE: /* * dosub - select substring * */ if (argc > 3) dosub(argv, argc); break; case SHIFTYPE: /* * doshift - push back all arguments * except the first one (i.e. skip * argv[2]) */ if (argc > 3) { for (n = argc - 1; n > 3; n--) { pbstr(rquote); pbstr(argv[n]); pbstr(lquote); pushback(COMMA); } pbstr(rquote); pbstr(argv[3]); pbstr(lquote); } break; case DIVRTYPE: if (argc > 2 && (n = atoi(argv[2])) != 0) dodiv(n); else { active = stdout; oindex = 0; } break; case UNDVTYPE: doundiv(argv, argc); break; case DIVNTYPE: /* * dodivnum - return the number of * current output diversion */ pbnum(oindex); break; case UNDFTYPE: /* * doundefine - undefine a previously * defined macro(s) or m4 keyword(s). */ if (argc > 2) for (n = 2; n < argc; n++) macro_undefine(argv[n]); break; case POPDTYPE: /* * dopopdef - remove the topmost * definitions of macro(s) or m4 * keyword(s). */ if (argc > 2) for (n = 2; n < argc; n++) macro_popdef(argv[n]); break; case MKTMTYPE: /* * dotemp - create a temporary file */ if (argc > 2) { int fd; char *temp; temp = xstrdup(argv[2]); fd = mkstemp(temp); if (fd == -1) err(1, "%s at line %lu: couldn't make temp file %s", CURRENT_NAME, CURRENT_LINE, argv[2]); close(fd); pbstr(temp); free(temp); } break; case TRNLTYPE: /* * dotranslit - replace all characters in * the source string that appears in the * "from" string with the corresponding * characters in the "to" string. */ if (argc > 3) { char *temp; temp = xalloc(strlen(argv[2])+1, NULL); if (argc > 4) map(temp, argv[2], argv[3], argv[4]); else map(temp, argv[2], argv[3], null); pbstr(temp); free(temp); } else if (argc > 2) pbstr(argv[2]); break; case INDXTYPE: /* * doindex - find the index of the second * argument string in the first argument * string. -1 if not present. */ pbnum((argc > 3) ? indx(argv[2], argv[3]) : -1); break; case ERRPTYPE: /* * doerrp - print the arguments to stderr * file */ if (argc > 2) { for (n = 2; n < argc; n++) fprintf(stderr, "%s ", argv[n]); fprintf(stderr, "\n"); } break; case DNLNTYPE: /* * dodnl - eat-up-to and including * newline */ while ((c = gpbc()) != '\n' && c != EOF) ; break; case M4WRTYPE: /* * dom4wrap - set up for * wrap-up/wind-down activity */ if (argc > 2) dom4wrap(argv[2]); break; case EXITTYPE: /* * doexit - immediate exit from m4. */ killdiv(); exit((argc > 2) ? atoi(argv[2]) : 0); break; case DEFNTYPE: if (argc > 2) for (n = 2; n < argc; n++) dodefn(argv[n]); break; case INDIRTYPE: /* Indirect call */ if (argc > 2) doindir(argv, argc); break; case BUILTINTYPE: /* Builtins only */ if (argc > 2) dobuiltin(argv, argc); break; case PATSTYPE: if (argc > 2) dopatsubst(argv, argc); break; case REGEXPTYPE: if (argc > 2) doregexp(argv, argc); break; case LINETYPE: doprintlineno(infile+ilevel); break; case FILENAMETYPE: doprintfilename(infile+ilevel); break; case SELFTYPE: pbstr(rquote); pbstr(argv[1]); pbstr(lquote); break; default: m4errx(1, "eval: major botch."); break; } } /* * expand_macro - user-defined macro expansion */ void expand_macro(const char *argv[], int argc) { const char *t; const char *p; int n; int argno; t = argv[0]; /* defn string as a whole */ p = t; while (*p) p++; p--; /* last character of defn */ while (p > t) { if (*(p - 1) != ARGFLAG) PUSHBACK(*p); else { switch (*p) { case '#': pbnum(argc - 2); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if ((argno = *p - '0') < argc - 1) pbstr(argv[argno + 1]); break; case '*': if (argc > 2) { for (n = argc - 1; n > 2; n--) { pbstr(argv[n]); pushback(COMMA); } pbstr(argv[2]); } break; case '@': if (argc > 2) { for (n = argc - 1; n > 2; n--) { pbstr(rquote); pbstr(argv[n]); pbstr(lquote); pushback(COMMA); } pbstr(rquote); pbstr(argv[2]); pbstr(lquote); } break; default: PUSHBACK(*p); PUSHBACK('$'); break; } p--; } p--; } if (p == t) /* do last character */ PUSHBACK(*p); } /* * dodefine - install definition in the table */ void dodefine(const char *name, const char *defn) { if (!*name && !mimic_gnu) m4errx(1, "null definition."); else macro_define(name, defn); } /* * dodefn - push back a quoted definition of * the given name. */ static void dodefn(const char *name) { struct macro_definition *p; if ((p = lookup_macro_definition(name)) != NULL) { if ((p->type & TYPEMASK) == MACRTYPE) { pbstr(rquote); pbstr(p->defn); pbstr(lquote); } else { pbstr(p->defn); pbstr(BUILTIN_MARKER); } } } /* * dopushdef - install a definition in the hash table * without removing a previous definition. Since * each new entry is entered in *front* of the * hash bucket, it hides a previous definition from * lookup. */ static void dopushdef(const char *name, const char *defn) { if (!*name && !mimic_gnu) m4errx(1, "null definition."); else macro_pushdef(name, defn); } /* * dump_one_def - dump the specified definition. */ static void dump_one_def(const char *name, struct macro_definition *p) { if (!traceout) traceout = stderr; if (mimic_gnu) { if ((p->type & TYPEMASK) == MACRTYPE) fprintf(traceout, "%s:\t%s\n", name, p->defn); else { fprintf(traceout, "%s:\t<%s>\n", name, p->defn); } } else fprintf(traceout, "`%s'\t`%s'\n", name, p->defn); } /* * dodumpdef - dump the specified definitions in the hash * table to stderr. If nothing is specified, the entire * hash table is dumped. */ static void dodump(const char *argv[], int argc) { int n; struct macro_definition *p; if (argc > 2) { for (n = 2; n < argc; n++) if ((p = lookup_macro_definition(argv[n])) != NULL) dump_one_def(argv[n], p); } else macro_for_all(dump_one_def); } /* * dotrace - mark some macros as traced/untraced depending upon on. */ static void dotrace(const char *argv[], int argc, int on) { int n; if (argc > 2) { for (n = 2; n < argc; n++) mark_traced(argv[n], on); } else mark_traced(NULL, on); } /* * doifelse - select one of two alternatives - loop. */ static void doifelse(const char *argv[], int argc) { cycle { if (STREQ(argv[2], argv[3])) pbstr(argv[4]); else if (argc == 6) pbstr(argv[5]); else if (argc > 6) { argv += 3; argc -= 3; continue; } break; } } /* * doinclude - include a given file. */ static int doincl(const char *ifile) { if (ilevel + 1 == MAXINP) m4errx(1, "too many include files."); if (fopen_trypath(infile+ilevel+1, ifile) != NULL) { ilevel++; bbase[ilevel] = bufbase = bp; return (1); } else return (0); } #ifdef EXTENDED /* * dopaste - include a given file without any * macro processing. */ static int dopaste(const char *pfile) { FILE *pf; int c; if ((pf = fopen(pfile, "r")) != NULL) { if (synch_lines) fprintf(active, "#line 1 \"%s\"\n", pfile); while ((c = getc(pf)) != EOF) putc(c, active); (void) fclose(pf); emit_synchline(); return (1); } else return (0); } #endif /* * dochq - change quote characters */ static void dochq(const char *argv[], int ac) { if (ac == 2) { lquote[0] = LQUOTE; lquote[1] = EOS; rquote[0] = RQUOTE; rquote[1] = EOS; } else { strlcpy(lquote, argv[2], sizeof(lquote)); if (ac > 3) { strlcpy(rquote, argv[3], sizeof(rquote)); } else { rquote[0] = ECOMMT; rquote[1] = EOS; } } } /* * dochc - change comment characters */ static void dochc(const char *argv[], int argc) { /* XXX Note that there is no difference between no argument and a single * empty argument. */ if (argc == 2) { scommt[0] = EOS; ecommt[0] = EOS; } else { strlcpy(scommt, argv[2], sizeof(scommt)); if (argc == 3) { ecommt[0] = ECOMMT; ecommt[1] = EOS; } else { strlcpy(ecommt, argv[3], sizeof(ecommt)); } } } /* * dom4wrap - expand text at EOF */ static void dom4wrap(const char *text) { if (wrapindex >= maxwraps) { if (maxwraps == 0) maxwraps = 16; else maxwraps *= 2; m4wraps = xreallocarray(m4wraps, maxwraps, sizeof(*m4wraps), "too many m4wraps"); } m4wraps[wrapindex++] = xstrdup(text); } /* * dodivert - divert the output to a temporary file */ static void dodiv(int n) { int fd; oindex = n; if (n >= maxout) { if (mimic_gnu) resizedivs(n + 10); else n = 0; /* bitbucket */ } if (n < 0) n = 0; /* bitbucket */ if (outfile[n] == NULL) { char fname[] = _PATH_DIVNAME; if ((fd = mkstemp(fname)) < 0 || unlink(fname) == -1 || (outfile[n] = fdopen(fd, "w+")) == NULL) err(1, "%s: cannot divert", fname); } active = outfile[n]; } /* * doundivert - undivert a specified output, or all * other outputs, in numerical order. */ static void doundiv(const char *argv[], int argc) { int ind; int n; if (argc > 2) { for (ind = 2; ind < argc; ind++) { const char *errstr; n = strtonum(argv[ind], 1, INT_MAX, &errstr); if (errstr) { if (errno == EINVAL && mimic_gnu) getdivfile(argv[ind]); } else { if (n < maxout && outfile[n] != NULL) getdiv(n); } } } else for (n = 1; n < maxout; n++) if (outfile[n] != NULL) getdiv(n); } /* * dosub - select substring */ static void dosub(const char *argv[], int argc) { const char *ap, *fc, *k; int nc; ap = argv[2]; /* target string */ #ifdef EXPR fc = ap + expr(argv[3]); /* first char */ #else fc = ap + atoi(argv[3]); /* first char */ #endif nc = strlen(fc); if (argc >= 5) #ifdef EXPR nc = min(nc, expr(argv[4])); #else nc = min(nc, atoi(argv[4])); #endif if (fc >= ap && fc < ap + strlen(ap)) for (k = fc + nc - 1; k >= fc; k--) pushback(*k); } /* * map: * map every character of s1 that is specified in from * into s3 and replace in s. (source s1 remains untouched) * * This is derived from the a standard implementation of map(s,from,to) * function of ICON language. Within mapvec, we replace every character * of "from" with the corresponding character in "to". * If "to" is shorter than "from", than the corresponding entries are null, - * which means that those characters dissapear altogether. + * which means that those characters disappear altogether. */ static void map(char *dest, const char *src, const char *from, const char *to) { const char *tmp; unsigned char sch, dch; static char frombis[257]; static char tobis[257]; int i; char seen[256]; static unsigned char mapvec[256] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255 }; if (*src) { if (mimic_gnu) { /* * expand character ranges on the fly */ from = handledash(frombis, frombis + 256, from); to = handledash(tobis, tobis + 256, to); } tmp = from; /* * create a mapping between "from" and * "to" */ for (i = 0; i < 256; i++) seen[i] = 0; while (*from) { if (!seen[(unsigned char)(*from)]) { mapvec[(unsigned char)(*from)] = (unsigned char)(*to); seen[(unsigned char)(*from)] = 1; } from++; if (*to) to++; } while (*src) { sch = (unsigned char)(*src++); dch = mapvec[sch]; if ((*dest = (char)dch)) dest++; } /* * restore all the changed characters */ while (*tmp) { mapvec[(unsigned char)(*tmp)] = (unsigned char)(*tmp); tmp++; } } *dest = '\0'; } /* * handledash: * use buffer to copy the src string, expanding character ranges * on the way. */ static const char * handledash(char *buffer, char *end, const char *src) { char *p; p = buffer; while(*src) { if (src[1] == '-' && src[2]) { unsigned char i; if ((unsigned char)src[0] <= (unsigned char)src[2]) { for (i = (unsigned char)src[0]; i <= (unsigned char)src[2]; i++) { *p++ = i; if (p == end) { *p = '\0'; return buffer; } } } else { for (i = (unsigned char)src[0]; i >= (unsigned char)src[2]; i--) { *p++ = i; if (p == end) { *p = '\0'; return buffer; } } } src += 3; } else *p++ = *src++; if (p == end) break; } *p = '\0'; return buffer; } Index: head/usr.bin/timeout/tests/timeout.sh =================================================================== --- head/usr.bin/timeout/tests/timeout.sh (revision 298878) +++ head/usr.bin/timeout/tests/timeout.sh (revision 298879) @@ -1,215 +1,215 @@ # $FreeBSD$ atf_test_case nominal nominal_head() { atf_set "descr" "Basic tests on timeout(1) utility" } nominal_body() { atf_check \ -o empty \ -e empty \ -s exit:0 \ -x timeout 5 true } atf_test_case time_unit time_unit_head() { atf_set "descr" "Test parsing the default time unit" } time_unit_body() { atf_check \ -o empty \ -e empty \ -s exit:0 \ -x timeout 1d true atf_check \ -o empty \ -e empty \ -s exit:0 \ -x timeout 1h true atf_check \ -o empty \ -e empty \ -s exit:0 \ -x timeout 1m true atf_check \ -o empty \ -e empty \ -s exit:0 \ -x timeout 1s true } atf_test_case no_timeout no_timeout_head() { atf_set "descr" "Test disabled timeout" } no_timeout_body() { atf_check \ -o empty \ -e empty \ -s exit:0 \ -x timeout 0 true } atf_test_case exit_numbers exit_numbers_head() { atf_set "descr" "Test exit numbers" } exit_numbers_body() { atf_check \ -o empty \ -e empty \ -s exit:2 \ -x timeout 5 sh -c \'exit 2\' atf_check \ -o empty \ -e empty \ -s exit:124 \ -x timeout .1 sleep 1 - # With preserv status exit shoudl be 128 + TERM aka 143 + # With preserv status exit should be 128 + TERM aka 143 atf_check \ -o empty \ -e empty \ -s exit:143 \ -x timeout --preserve-status .1 sleep 10 atf_check \ -o empty \ -e empty \ -s exit:124 \ -x timeout -s1 -k1 .1 sleep 10 atf_check \ -o empty \ -e empty \ -s exit:0 \ -x sh -c 'trap "" CHLD; exec timeout 10 true' } atf_test_case with_a_child with_a_child_head() { atf_set "descr" "When starting with a child (coreutils bug#9098)" } with_a_child_body() { out=$(sleep .1 & exec timeout .5 sh -c 'sleep 2; echo foo') status=$? test "$out" = "" && test $status = 124 || atf_fail } atf_test_case invalid_timeout invalid_timeout_head() { atf_set "descr" "Invalid timeout" } invalid_timeout_body() { atf_check \ -o empty \ -e inline:"timeout: invalid duration\n" \ -s exit:125 \ -x timeout invalid sleep 0 atf_check \ -o empty \ -e inline:"timeout: invalid duration\n" \ -s exit:125 \ -x timeout --kill-after=invalid 1 sleep 0 atf_check \ -o empty \ -e inline:"timeout: invalid duration\n" \ -s exit:125 \ -x timeout 42D sleep 0 atf_check \ -o empty \ -e inline:"timeout: invalid duration\n" \ -s exit:125 \ -x timeout 999999999999999999999999999999999999999999999999999999999999d sleep 0 atf_check \ -o empty \ -e inline:"timeout: invalid duration\n" \ -s exit:125 \ -x timeout 2.34e+5d sleep 0 } atf_test_case invalid_signal invalid_signal_head() { atf_set "descr" "Invalid signal" } invalid_signal_body() { atf_check \ -o empty \ -e inline:"timeout: invalid signal\n" \ -s exit:125 \ -x timeout --signal=invalid 1 sleep 0 } atf_test_case invalid_command invalid_command_head() { atf_set "descr" "Invalid command" } invalid_command_body() { atf_check \ -o empty \ -e inline:"timeout: exec(.): Permission denied\n" \ -s exit:126 \ -x timeout 10 . } atf_test_case no_such_command no_such_command_head() { atf_set "descr" "No such command" } no_such_command_body() { atf_check \ -o empty \ -e inline:"timeout: exec(enoexists): No such file or directory\n" \ -s exit:127 \ -x timeout 10 enoexists } atf_init_test_cases() { atf_add_test_case nominal atf_add_test_case time_unit atf_add_test_case no_timeout atf_add_test_case exit_numbers atf_add_test_case with_a_child atf_add_test_case invalid_timeout atf_add_test_case invalid_signal atf_add_test_case invalid_command atf_add_test_case no_such_command } Index: head/usr.bin/timeout/timeout.c =================================================================== --- head/usr.bin/timeout/timeout.c (revision 298878) +++ head/usr.bin/timeout/timeout.c (revision 298879) @@ -1,362 +1,362 @@ /*- * Copyright (c) 2014 Baptiste Daroussin * Copyright (c) 2014 Vsevolod Stakhov * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer * in this position and unchanged. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #define EXIT_TIMEOUT 124 static sig_atomic_t sig_chld = 0; static sig_atomic_t sig_term = 0; static sig_atomic_t sig_alrm = 0; static sig_atomic_t sig_ign = 0; static void usage(void) { fprintf(stderr, "Usage: %s [--signal sig | -s sig] [--preserve-status]" " [--kill-after time | -k time] [--foreground] " " \n", getprogname()); exit(EX_USAGE); } static double parse_duration(const char *duration) { double ret; char *end; ret = strtod(duration, &end); if (ret == 0 && end == duration) errx(125, "invalid duration"); if (end == NULL || *end == '\0') return (ret); if (end != NULL && *(end + 1) != '\0') errx(EX_USAGE, "invalid duration"); switch (*end) { case 's': break; case 'm': ret *= 60; break; case 'h': ret *= 60 * 60; break; case 'd': ret *= 60 * 60 * 24; break; default: errx(125, "invalid duration"); } if (ret < 0 || ret >= 100000000UL) errx(125, "invalid duration"); return (ret); } static int parse_signal(const char *str) { int sig, i; const char *errstr; sig = strtonum(str, 1, sys_nsig - 1, &errstr); if (errstr == NULL) return (sig); if (strncasecmp(str, "SIG", 3) == 0) str += 3; for (i = 1; i < sys_nsig; i++) { if (strcasecmp(str, sys_signame[i]) == 0) return (i); } errx(125, "invalid signal"); } static void sig_handler(int signo) { if (sig_ign != 0 && signo == sig_ign) { sig_ign = 0; return; } switch(signo) { case 0: case SIGINT: case SIGHUP: case SIGQUIT: case SIGTERM: sig_term = signo; break; case SIGCHLD: sig_chld = 1; break; case SIGALRM: sig_alrm = 1; break; } } static void set_interval(double iv) { struct itimerval tim; memset(&tim, 0, sizeof(tim)); tim.it_value.tv_sec = (time_t)iv; iv -= (time_t)iv; tim.it_value.tv_usec = (suseconds_t)(iv * 1000000UL); if (setitimer(ITIMER_REAL, &tim, NULL) == -1) err(EX_OSERR, "setitimer()"); } int main(int argc, char **argv) { int ch; unsigned long i; int foreground, preserve; int error, pstat, status; int killsig = SIGTERM; pid_t pid, cpid; double first_kill; double second_kill; bool timedout = false; bool do_second_kill = false; bool child_done = false; struct sigaction signals; struct procctl_reaper_status info; struct procctl_reaper_kill killemall; int signums[] = { -1, SIGTERM, SIGINT, SIGHUP, SIGCHLD, SIGALRM, SIGQUIT, }; foreground = preserve = 0; second_kill = 0; const struct option longopts[] = { { "preserve-status", no_argument, &preserve, 1 }, { "foreground", no_argument, &foreground, 1 }, { "kill-after", required_argument, NULL, 'k'}, { "signal", required_argument, NULL, 's'}, { "help", no_argument, NULL, 'h'}, { NULL, 0, NULL, 0 } }; while ((ch = getopt_long(argc, argv, "+k:s:h", longopts, NULL)) != -1) { switch (ch) { case 'k': do_second_kill = true; second_kill = parse_duration(optarg); break; case 's': killsig = parse_signal(optarg); break; case 0: break; case 'h': default: usage(); break; } } argc -= optind; argv += optind; if (argc < 2) usage(); first_kill = parse_duration(argv[0]); argc--; argv++; if (!foreground) { - /* Aquire a reaper */ + /* Acquire a reaper */ if (procctl(P_PID, getpid(), PROC_REAP_ACQUIRE, NULL) == -1) err(EX_OSERR, "Fail to acquire the reaper"); } memset(&signals, 0, sizeof(signals)); sigemptyset(&signals.sa_mask); if (killsig != SIGKILL && killsig != SIGSTOP) signums[0] = killsig; for (i = 0; i < sizeof(signums) / sizeof(signums[0]); i ++) sigaddset(&signals.sa_mask, signums[i]); signals.sa_handler = sig_handler; signals.sa_flags = SA_RESTART; for (i = 0; i < sizeof(signums) / sizeof(signums[0]); i ++) if (signums[i] != -1 && signums[i] != 0 && sigaction(signums[i], &signals, NULL) == -1) err(EX_OSERR, "sigaction()"); signal(SIGTTIN, SIG_IGN); signal(SIGTTOU, SIG_IGN); pid = fork(); if (pid == -1) err(EX_OSERR, "fork()"); else if (pid == 0) { /* child process */ signal(SIGTTIN, SIG_DFL); signal(SIGTTOU, SIG_DFL); error = execvp(argv[0], argv); if (error == -1) { if (errno == ENOENT) err(127, "exec(%s)", argv[0]); else err(126, "exec(%s)", argv[0]); } } if (sigprocmask(SIG_BLOCK, &signals.sa_mask, NULL) == -1) err(EX_OSERR, "sigprocmask()"); /* parent continues here */ set_interval(first_kill); for (;;) { sigemptyset(&signals.sa_mask); sigsuspend(&signals.sa_mask); if (sig_chld) { sig_chld = 0; while ((cpid = waitpid(-1, &status, WNOHANG)) != 0) { if (cpid < 0) { if (errno == EINTR) continue; else break; } else if (cpid == pid) { pstat = status; child_done = true; } } if (child_done) { if (foreground) { break; } else { procctl(P_PID, getpid(), PROC_REAP_STATUS, &info); if (info.rs_children == 0) break; } } } else if (sig_alrm) { sig_alrm = 0; timedout = true; if (!foreground) { killemall.rk_sig = killsig; killemall.rk_flags = 0; procctl(P_PID, getpid(), PROC_REAP_KILL, &killemall); } else kill(pid, killsig); if (do_second_kill) { set_interval(second_kill); second_kill = 0; sig_ign = killsig; killsig = SIGKILL; } else break; } else if (sig_term) { if (!foreground) { killemall.rk_sig = sig_term; killemall.rk_flags = 0; procctl(P_PID, getpid(), PROC_REAP_KILL, &killemall); } else kill(pid, sig_term); if (do_second_kill) { set_interval(second_kill); second_kill = 0; sig_ign = killsig; killsig = SIGKILL; } else break; } } while (!child_done && wait(&pstat) == -1) { if (errno != EINTR) err(EX_OSERR, "waitpid()"); } if (!foreground) procctl(P_PID, getpid(), PROC_REAP_RELEASE, NULL); if (WEXITSTATUS(pstat)) pstat = WEXITSTATUS(pstat); else if(WIFSIGNALED(pstat)) pstat = 128 + WTERMSIG(pstat); if (timedout && !preserve) pstat = EXIT_TIMEOUT; return (pstat); } Index: head/usr.bin/whereis/whereis.c =================================================================== --- head/usr.bin/whereis/whereis.c (revision 298878) +++ head/usr.bin/whereis/whereis.c (revision 298879) @@ -1,691 +1,691 @@ /* * Copyright © 2002, Jörg Wunsch * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* * 4.3BSD UI-compatible whereis(1) utility. Rewritten from scratch * since the original 4.3BSD version suffers legal problems that * prevent it from being redistributed, and since the 4.4BSD version * was pretty inferior in functionality. */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include "pathnames.h" #define NO_BIN_FOUND 1 #define NO_MAN_FOUND 2 #define NO_SRC_FOUND 4 typedef const char *ccharp; static int opt_a, opt_b, opt_m, opt_q, opt_s, opt_u, opt_x; static ccharp *bindirs, *mandirs, *sourcedirs; static char **query; static const char *sourcepath = PATH_SOURCES; static char *colonify(ccharp *); static int contains(ccharp *, const char *); static void decolonify(char *, ccharp **, int *); static void defaults(void); static void scanopts(int, char **); static void usage(void); /* * Throughout this program, a number of strings are dynamically * allocated but never freed. Their memory is written to when * splitting the strings into string lists which will later be * processed. Since it's important that those string lists remain * valid even after the functions allocating the memory returned, * those functions cannot free them. They could be freed only at end * of main(), which is pretty pointless anyway. * * The overall amount of memory to be allocated for processing the * strings is not expected to exceed a few kilobytes. For that * reason, allocation can usually always be assumed to succeed (within * a virtual memory environment), thus we simply bail out using * abort(3) in case of an allocation failure. */ static void usage(void) { (void)fprintf(stderr, "usage: whereis [-abmqsux] [-BMS dir ... -f] program ...\n"); exit(EX_USAGE); } /* * Scan options passed to program. * * Note that the -B/-M/-S options expect a list of directory * names that must be terminated with -f. */ static void scanopts(int argc, char **argv) { int c, i; ccharp **dirlist; while ((c = getopt(argc, argv, "BMSabfmqsux")) != -1) switch (c) { case 'B': dirlist = &bindirs; goto dolist; case 'M': dirlist = &mandirs; goto dolist; case 'S': dirlist = &sourcedirs; dolist: i = 0; *dirlist = realloc(*dirlist, (i + 1) * sizeof(char *)); (*dirlist)[i] = NULL; while (optind < argc && strcmp(argv[optind], "-f") != 0 && strcmp(argv[optind], "-B") != 0 && strcmp(argv[optind], "-M") != 0 && strcmp(argv[optind], "-S") != 0) { decolonify(argv[optind], dirlist, &i); optind++; } break; case 'a': opt_a = 1; break; case 'b': opt_b = 1; break; case 'f': goto breakout; case 'm': opt_m = 1; break; case 'q': opt_q = 1; break; case 's': opt_s = 1; break; case 'u': opt_u = 1; break; case 'x': opt_x = 1; break; default: usage(); } breakout: if (optind == argc) usage(); query = argv + optind; } /* * Find out whether string `s' is contained in list `cpp'. */ static int contains(ccharp *cpp, const char *s) { ccharp cp; if (cpp == NULL) return (0); while ((cp = *cpp) != NULL) { if (strcmp(cp, s) == 0) return (1); cpp++; } return (0); } /* * Split string `s' at colons, and pass it to the string list pointed * to by `cppp' (which has `*ip' elements). Note that the original * string is modified by replacing the colon with a NUL byte. The * partial string is only added if it has a length greater than 0, and * if it's not already contained in the string list. */ static void decolonify(char *s, ccharp **cppp, int *ip) { char *cp; while ((cp = strchr(s, ':')), *s != '\0') { if (cp) *cp = '\0'; if (strlen(s) && !contains(*cppp, s)) { *cppp = realloc(*cppp, (*ip + 2) * sizeof(char *)); if (*cppp == NULL) abort(); (*cppp)[*ip] = s; (*cppp)[*ip + 1] = NULL; (*ip)++; } if (cp) s = cp + 1; else break; } } /* * Join string list `cpp' into a colon-separated string. */ static char * colonify(ccharp *cpp) { size_t s; char *cp; int i; if (cpp == NULL) return (0); for (s = 0, i = 0; cpp[i] != NULL; i++) s += strlen(cpp[i]) + 1; if ((cp = malloc(s + 1)) == NULL) abort(); for (i = 0, *cp = '\0'; cpp[i] != NULL; i++) { strcat(cp, cpp[i]); strcat(cp, ":"); } cp[s - 1] = '\0'; /* eliminate last colon */ return (cp); } /* * Provide defaults for all options and directory lists. */ static void defaults(void) { size_t s; char *b, buf[BUFSIZ], *cp; int nele; FILE *p; DIR *dir; struct stat sb; struct dirent *dirp; /* default to -bms if none has been specified */ if (!opt_b && !opt_m && !opt_s) opt_b = opt_m = opt_s = 1; /* -b defaults to default path + /usr/libexec + * user's path */ if (!bindirs) { if (sysctlbyname("user.cs_path", (void *)NULL, &s, (void *)NULL, 0) == -1) err(EX_OSERR, "sysctlbyname(\"user.cs_path\")"); if ((b = malloc(s + 1)) == NULL) abort(); if (sysctlbyname("user.cs_path", b, &s, (void *)NULL, 0) == -1) err(EX_OSERR, "sysctlbyname(\"user.cs_path\")"); nele = 0; decolonify(b, &bindirs, &nele); bindirs = realloc(bindirs, (nele + 2) * sizeof(char *)); if (bindirs == NULL) abort(); bindirs[nele++] = PATH_LIBEXEC; bindirs[nele] = NULL; if ((cp = getenv("PATH")) != NULL) { /* don't destroy the original environment... */ if ((b = malloc(strlen(cp) + 1)) == NULL) abort(); strcpy(b, cp); decolonify(b, &bindirs, &nele); } } /* -m defaults to $(manpath) */ if (!mandirs) { if ((p = popen(MANPATHCMD, "r")) == NULL) err(EX_OSERR, "cannot execute manpath command"); if (fgets(buf, BUFSIZ - 1, p) == NULL || pclose(p)) err(EX_OSERR, "error processing manpath results"); if ((b = strchr(buf, '\n')) != NULL) *b = '\0'; if ((b = malloc(strlen(buf) + 1)) == NULL) abort(); strcpy(b, buf); nele = 0; decolonify(b, &mandirs, &nele); } /* -s defaults to precompiled list, plus subdirs of /usr/ports */ if (!sourcedirs) { if ((b = malloc(strlen(sourcepath) + 1)) == NULL) abort(); strcpy(b, sourcepath); nele = 0; decolonify(b, &sourcedirs, &nele); if (stat(PATH_PORTS, &sb) == -1) { if (errno == ENOENT) /* no /usr/ports, we are done */ return; err(EX_OSERR, "stat(" PATH_PORTS ")"); } if ((sb.st_mode & S_IFMT) != S_IFDIR) /* /usr/ports is not a directory, ignore */ return; if (access(PATH_PORTS, R_OK | X_OK) != 0) return; if ((dir = opendir(PATH_PORTS)) == NULL) err(EX_OSERR, "opendir" PATH_PORTS ")"); while ((dirp = readdir(dir)) != NULL) { /* * Not everything below PATH_PORTS is of * interest. First, all dot files and * directories (e. g. .snap) can be ignored. * Also, all subdirectories starting with a * capital letter are not going to be * examined, as they are used for internal * purposes (Mk, Tools, ...). This also * matches a possible CVS subdirectory. * Finally, the distfiles subdirectory is also * special, and should not be considered to * avoid false matches. */ if (dirp->d_name[0] == '.' || /* * isupper() not used on purpose: the * check is supposed to default to the C * locale instead of the current user's * locale. */ (dirp->d_name[0] >= 'A' && dirp->d_name[0] <= 'Z') || strcmp(dirp->d_name, "distfiles") == 0) continue; if ((b = malloc(sizeof PATH_PORTS + 1 + dirp->d_namlen)) == NULL) abort(); strcpy(b, PATH_PORTS); strcat(b, "/"); strcat(b, dirp->d_name); if (stat(b, &sb) == -1 || (sb.st_mode & S_IFMT) != S_IFDIR || access(b, R_OK | X_OK) != 0) { free(b); continue; } sourcedirs = realloc(sourcedirs, (nele + 2) * sizeof(char *)); if (sourcedirs == NULL) abort(); sourcedirs[nele++] = b; sourcedirs[nele] = NULL; } closedir(dir); } } int main(int argc, char **argv) { int unusual, i, printed; char *bin, buf[BUFSIZ], *cp, *cp2, *man, *name, *src; ccharp *dp; size_t nlen, olen, s; struct stat sb; regex_t re, re2; regmatch_t matches[2]; regoff_t rlen; FILE *p; setlocale(LC_ALL, ""); scanopts(argc, argv); defaults(); if (mandirs == NULL) opt_m = 0; if (bindirs == NULL) opt_b = 0; if (sourcedirs == NULL) opt_s = 0; if (opt_m + opt_b + opt_s == 0) errx(EX_DATAERR, "no directories to search"); if (opt_m) { setenv("MANPATH", colonify(mandirs), 1); if ((i = regcomp(&re, MANWHEREISMATCH, REG_EXTENDED)) != 0) { regerror(i, &re, buf, BUFSIZ - 1); errx(EX_UNAVAILABLE, "regcomp(%s) failed: %s", MANWHEREISMATCH, buf); } } for (; (name = *query) != NULL; query++) { /* strip leading path name component */ if ((cp = strrchr(name, '/')) != NULL) name = cp + 1; /* strip SCCS or RCS suffix/prefix */ if (strlen(name) > 2 && strncmp(name, "s.", 2) == 0) name += 2; if ((s = strlen(name)) > 2 && strcmp(name + s - 2, ",v") == 0) name[s - 2] = '\0'; /* compression suffix */ s = strlen(name); if (s > 2 && (strcmp(name + s - 2, ".z") == 0 || strcmp(name + s - 2, ".Z") == 0)) name[s - 2] = '\0'; else if (s > 3 && strcmp(name + s - 3, ".gz") == 0) name[s - 3] = '\0'; else if (s > 4 && strcmp(name + s - 4, ".bz2") == 0) name[s - 4] = '\0'; unusual = 0; bin = man = src = NULL; s = strlen(name); if (opt_b) { /* * Binaries have to match exactly, and must be regular * executable files. */ unusual = unusual | NO_BIN_FOUND; for (dp = bindirs; *dp != NULL; dp++) { cp = malloc(strlen(*dp) + 1 + s + 1); if (cp == NULL) abort(); strcpy(cp, *dp); strcat(cp, "/"); strcat(cp, name); if (stat(cp, &sb) == 0 && (sb.st_mode & S_IFMT) == S_IFREG && (sb.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)) != 0) { unusual = unusual & ~NO_BIN_FOUND; if (bin == NULL) { bin = strdup(cp); } else { olen = strlen(bin); nlen = strlen(cp); bin = realloc(bin, olen + nlen + 2); if (bin == NULL) abort(); strcat(bin, " "); strcat(bin, cp); } if (!opt_a) { free(cp); break; } } free(cp); } } if (opt_m) { /* * Ask the man command to perform the search for us. */ unusual = unusual | NO_MAN_FOUND; if (opt_a) cp = malloc(sizeof MANWHEREISALLCMD - 2 + s); else cp = malloc(sizeof MANWHEREISCMD - 2 + s); if (cp == NULL) abort(); if (opt_a) sprintf(cp, MANWHEREISALLCMD, name); else sprintf(cp, MANWHEREISCMD, name); if ((p = popen(cp, "r")) != NULL) { while (fgets(buf, BUFSIZ - 1, p) != NULL) { unusual = unusual & ~NO_MAN_FOUND; if ((cp2 = strchr(buf, '\n')) != NULL) *cp2 = '\0'; if (regexec(&re, buf, 2, matches, 0) == 0 && (rlen = matches[1].rm_eo - matches[1].rm_so) > 0) { /* - * man -w found formated + * man -w found formatted * page, need to pick up * source page name. */ cp2 = malloc(rlen + 1); if (cp2 == NULL) abort(); memcpy(cp2, buf + matches[1].rm_so, rlen); cp2[rlen] = '\0'; } else { /* * man -w found plain source * page, use it. */ s = strlen(buf); cp2 = malloc(s + 1); if (cp2 == NULL) abort(); strcpy(cp2, buf); } if (man == NULL) { man = strdup(cp2); } else { olen = strlen(man); nlen = strlen(cp2); man = realloc(man, olen + nlen + 2); if (man == NULL) abort(); strcat(man, " "); strcat(man, cp2); } free(cp2); if (!opt_a) break; } pclose(p); free(cp); } } if (opt_s) { /* * Sources match if a subdir with the exact * name is found. */ unusual = unusual | NO_SRC_FOUND; for (dp = sourcedirs; *dp != NULL; dp++) { cp = malloc(strlen(*dp) + 1 + s + 1); if (cp == NULL) abort(); strcpy(cp, *dp); strcat(cp, "/"); strcat(cp, name); if (stat(cp, &sb) == 0 && (sb.st_mode & S_IFMT) == S_IFDIR) { unusual = unusual & ~NO_SRC_FOUND; if (src == NULL) { src = strdup(cp); } else { olen = strlen(src); nlen = strlen(cp); src = realloc(src, olen + nlen + 2); if (src == NULL) abort(); strcat(src, " "); strcat(src, cp); } if (!opt_a) { free(cp); break; } } free(cp); } /* * If still not found, ask locate to search it * for us. This will find sources for things * like lpr that are well hidden in the * /usr/src tree, but takes a lot longer. * Thus, option -x (`expensive') prevents this * search. * * Do only match locate output that starts * with one of our source directories, and at * least one further level of subdirectories. */ if (opt_x || (src && !opt_a)) goto done_sources; cp = malloc(sizeof LOCATECMD - 2 + s); if (cp == NULL) abort(); sprintf(cp, LOCATECMD, name); if ((p = popen(cp, "r")) == NULL) goto done_sources; while ((src == NULL || opt_a) && (fgets(buf, BUFSIZ - 1, p)) != NULL) { if ((cp2 = strchr(buf, '\n')) != NULL) *cp2 = '\0'; for (dp = sourcedirs; (src == NULL || opt_a) && *dp != NULL; dp++) { cp2 = malloc(strlen(*dp) + 9); if (cp2 == NULL) abort(); strcpy(cp2, "^"); strcat(cp2, *dp); strcat(cp2, "/[^/]+/"); if ((i = regcomp(&re2, cp2, REG_EXTENDED|REG_NOSUB)) != 0) { regerror(i, &re, buf, BUFSIZ - 1); errx(EX_UNAVAILABLE, "regcomp(%s) failed: %s", cp2, buf); } free(cp2); if (regexec(&re2, buf, 0, (regmatch_t *)NULL, 0) == 0) { unusual = unusual & ~NO_SRC_FOUND; if (src == NULL) { src = strdup(buf); } else { olen = strlen(src); nlen = strlen(buf); src = realloc(src, olen + nlen + 2); if (src == NULL) abort(); strcat(src, " "); strcat(src, buf); } } regfree(&re2); } } pclose(p); free(cp); } done_sources: if (opt_u && !unusual) continue; printed = 0; if (!opt_q) { printf("%s:", name); printed++; } if (bin) { if (printed++) putchar(' '); fputs(bin, stdout); } if (man) { if (printed++) putchar(' '); fputs(man, stdout); } if (src) { if (printed++) putchar(' '); fputs(src, stdout); } if (printed) putchar('\n'); } if (opt_m) regfree(&re); return (0); } Index: head/usr.bin/xlint/lint2/chk.c =================================================================== --- head/usr.bin/xlint/lint2/chk.c (revision 298878) +++ head/usr.bin/xlint/lint2/chk.c (revision 298879) @@ -1,1350 +1,1350 @@ /* $NetBSD: chk.c,v 1.15 2002/01/21 19:49:52 tv Exp $ */ /* * Copyright (c) 1996 Christopher G. Demetriou. All Rights Reserved. * Copyright (c) 1994, 1995 Jochen Pohl * All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by Jochen Pohl for * The NetBSD Project. * 4. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #if defined(__RCSID) && !defined(lint) __RCSID("$NetBSD: chk.c,v 1.15 2002/01/21 19:49:52 tv Exp $"); #endif __FBSDID("$FreeBSD$"); #include #include #include #include #include "lint2.h" static void chkund(hte_t *); static void chkdnu(hte_t *); static void chkdnud(hte_t *); static void chkmd(hte_t *); static void chkvtui(hte_t *, sym_t *, sym_t *); static void chkvtdi(hte_t *, sym_t *, sym_t *); static void chkfaui(hte_t *, sym_t *, sym_t *); static void chkau(hte_t *, int, sym_t *, sym_t *, pos_t *, fcall_t *, fcall_t *, type_t *, type_t *); static void chkrvu(hte_t *, sym_t *); static void chkadecl(hte_t *, sym_t *, sym_t *); static void printflike(hte_t *,fcall_t *, int, const char *, type_t **); static void scanflike(hte_t *, fcall_t *, int, const char *, type_t **); static void badfmt(hte_t *, fcall_t *); static void inconarg(hte_t *, fcall_t *, int); static void tofewarg(hte_t *, fcall_t *); static void tomanyarg(hte_t *, fcall_t *); static int eqtype(type_t *, type_t *, int, int, int, int *); static int eqargs(type_t *, type_t *, int *); static int mnoarg(type_t *, int *); /* * If there is a symbol named "main", mark it as used. */ void mainused(void) { hte_t *hte; if ((hte = hsearch("main", 0)) != NULL) hte->h_used = 1; } /* * Performs all tests for a single name */ void chkname(hte_t *hte) { sym_t *sym, *def, *pdecl, *decl; if (uflag) { chkund(hte); chkdnu(hte); if (xflag) chkdnud(hte); } chkmd(hte); /* Get definition, prototype declaration and declaration */ def = pdecl = decl = NULL; for (sym = hte->h_syms; sym != NULL; sym = sym->s_nxt) { if (def == NULL && (sym->s_def == DEF || sym->s_def == TDEF)) def = sym; if (pdecl == NULL && sym->s_def == DECL && TP(sym->s_type)->t_tspec == FUNC && TP(sym->s_type)->t_proto) { pdecl = sym; } if (decl == NULL && sym->s_def == DECL) decl = sym; } /* A prototype is better than an old style declaration. */ if (pdecl != NULL) decl = pdecl; chkvtui(hte, def, decl); chkvtdi(hte, def, decl); chkfaui(hte, def, decl); chkrvu(hte, def); chkadecl(hte, def, decl); } /* * Print a warning if the name has been used, but not defined. */ static void chkund(hte_t *hte) { fcall_t *fcall; usym_t *usym; if (!hte->h_used || hte->h_def) return; if ((fcall = hte->h_calls) != NULL) { /* %s used( %s ), but not defined */ msg(0, hte->h_name, mkpos(&fcall->f_pos)); } else if ((usym = hte->h_usyms) != NULL) { /* %s used( %s ), but not defined */ msg(0, hte->h_name, mkpos(&usym->u_pos)); } } /* * Print a warning if the name has been defined, but never used. */ static void chkdnu(hte_t *hte) { sym_t *sym; if (!hte->h_def || hte->h_used) return; for (sym = hte->h_syms; sym != NULL; sym = sym->s_nxt) { if (sym->s_def == DEF || sym->s_def == TDEF) { /* %s defined( %s ), but never used */ msg(1, hte->h_name, mkpos(&sym->s_pos)); break; } } } /* * Print a warning if the variable has been declared, but is not used * or defined. */ static void chkdnud(hte_t *hte) { sym_t *sym; if (hte->h_syms == NULL || hte->h_used || hte->h_def) return; sym = hte->h_syms; if (TP(sym->s_type)->t_tspec == FUNC) return; if (sym->s_def != DECL) errx(1, "internal error: chkdnud() 1"); /* %s declared( %s ), but never used or defined */ msg(2, hte->h_name, mkpos(&sym->s_pos)); } /* * Print a warning if there is more than one definition for * this name. */ static void chkmd(hte_t *hte) { sym_t *sym, *def1; char *pos1; if (!hte->h_def) return; def1 = NULL; for (sym = hte->h_syms; sym != NULL; sym = sym->s_nxt) { /* * ANSI C allows tentative definitions of the same name in * only one compilation unit. */ if (sym->s_def != DEF && (!sflag || sym->s_def != TDEF)) continue; if (def1 == NULL) { def1 = sym; continue; } pos1 = xstrdup(mkpos(&def1->s_pos)); /* %s multiply defined\t%s :: %s */ msg(3, hte->h_name, pos1, mkpos(&sym->s_pos)); free(pos1); } } /* * Print a warning if the return value assumed for a function call * differs from the return value of the function definition or * function declaration. * * If no definition/declaration can be found, the assumed return values * are always int. So there is no need to compare with another function * call as it's done for function arguments. */ static void chkvtui(hte_t *hte, sym_t *def, sym_t *decl) { fcall_t *call; char *pos1; type_t *tp1, *tp2; /* LINTED (automatic hides external declaration: warn) */ int warn, eq; tspec_t t1; if (hte->h_calls == NULL) return; if (def == NULL) def = decl; if (def == NULL) return; t1 = (tp1 = TP(def->s_type)->t_subt)->t_tspec; for (call = hte->h_calls; call != NULL; call = call->f_nxt) { tp2 = TP(call->f_type)->t_subt; eq = eqtype(tp1, tp2, 1, 0, 0, (warn = 0, &warn)); if (!call->f_rused) { /* no return value used */ if ((t1 == STRUCT || t1 == UNION) && !eq) { /* * If a function returns a struct or union it * must be declared to return a struct or * union, also if the return value is ignored. * This is necessary because the caller must * allocate stack space for the return value. * If it does not, the return value would over- * write other data. * XXX Following massage may be confusing * because it appears also if the return value * was declared inconsistently. But this * behaviour matches pcc based lint, so it is * accepted for now. */ pos1 = xstrdup(mkpos(&def->s_pos)); /* %s value must be decl. before use %s :: %s */ msg(17, hte->h_name, pos1, mkpos(&call->f_pos)); free(pos1); } continue; } if (!eq || (sflag && warn)) { pos1 = xstrdup(mkpos(&def->s_pos)); /* %s value used inconsistenty\t%s :: %s */ msg(4, hte->h_name, pos1, mkpos(&call->f_pos)); free(pos1); } } } /* * Print a warning if a definition/declaration does not match another * definition/declaration of the same name. For functions, only the * types of return values are tested. */ static void chkvtdi(hte_t *hte, sym_t *def, sym_t *decl) { sym_t *sym; type_t *tp1, *tp2; /* LINTED (automatic hides external declaration: warn) */ int eq, warn; char *pos1; if (def == NULL) def = decl; if (def == NULL) return; tp1 = TP(def->s_type); for (sym = hte->h_syms; sym != NULL; sym = sym->s_nxt) { if (sym == def) continue; tp2 = TP(sym->s_type); warn = 0; if (tp1->t_tspec == FUNC && tp2->t_tspec == FUNC) { eq = eqtype(tp1->t_subt, tp2->t_subt, 1, 0, 0, &warn); } else { eq = eqtype(tp1, tp2, 0, 0, 0, &warn); } if (!eq || (sflag && warn)) { pos1 = xstrdup(mkpos(&def->s_pos)); /* %s value declared inconsistently\t%s :: %s */ msg(5, hte->h_name, pos1, mkpos(&sym->s_pos)); free(pos1); } } } /* * Print a warning if a function is called with arguments which does * not match the function definition, declaration or another call * of the same function. */ static void chkfaui(hte_t *hte, sym_t *def, sym_t *decl) { type_t *tp1, *tp2, **ap1, **ap2; pos_t *pos1p = NULL; fcall_t *calls, *call, *call1; int n, as; char *pos1; arginf_t *ai; if ((calls = hte->h_calls) == NULL) return; /* * If we find a function definition, we use this for comparison, * otherwise the first prototype we can find. If there is no * definition or prototype declaration, the first function call * is used. */ tp1 = NULL; call1 = NULL; if (def != NULL) { if ((tp1 = TP(def->s_type))->t_tspec != FUNC) return; pos1p = &def->s_pos; } else if (decl != NULL && TP(decl->s_type)->t_proto) { if ((tp1 = TP(decl->s_type))->t_tspec != FUNC) return; pos1p = &decl->s_pos; } if (tp1 == NULL) { call1 = calls; calls = calls->f_nxt; if ((tp1 = TP(call1->f_type))->t_tspec != FUNC) return; pos1p = &call1->f_pos; } n = 1; for (call = calls; call != NULL; call = call->f_nxt) { if ((tp2 = TP(call->f_type))->t_tspec != FUNC) continue; ap1 = tp1->t_args; ap2 = tp2->t_args; n = 0; while (*ap1 != NULL && *ap2 != NULL) { if (def != NULL && def->s_va && n >= def->s_nva) break; n++; chkau(hte, n, def, decl, pos1p, call1, call, *ap1, *ap2); ap1++; ap2++; } if (*ap1 == *ap2) { /* equal # of arguments */ } else if (def != NULL && def->s_va && n >= def->s_nva) { /* * function definition with VARARGS; The # of * arguments of the call must be at least as large * as the parameter of VARARGS. */ } else if (*ap2 != NULL && tp1->t_proto && tp1->t_vararg) { /* * prototype with ... and function call with * at least the same # of arguments as declared * in the prototype. */ } else { pos1 = xstrdup(mkpos(pos1p)); /* %s: variable # of args\t%s :: %s */ msg(7, hte->h_name, pos1, mkpos(&call->f_pos)); free(pos1); continue; } /* perform SCANFLIKE/PRINTFLIKE tests */ if (def == NULL || (!def->s_prfl && !def->s_scfl)) continue; as = def->s_prfl ? def->s_nprfl : def->s_nscfl; for (ai = call->f_args; ai != NULL; ai = ai->a_nxt) { if (ai->a_num == as) break; } if (ai == NULL || !ai->a_fmt) continue; if (def->s_prfl) { printflike(hte, call, n, ai->a_fstrg, ap2); } else { scanflike(hte, call, n, ai->a_fstrg, ap2); } } } /* * Check a single argument in a function call. * * hte a pointer to the hash table entry of the function * n the number of the argument (1..) * def the function definition or NULL * decl prototype declaration, old style declaration or NULL * pos1p position of definition, declaration of first call * call1 first call, if both def and decl are old style def/decl * call checked call * arg1 currently checked argument of def/decl/call1 * arg2 currently checked argument of call * */ static void chkau(hte_t *hte, int n, sym_t *def, sym_t *decl, pos_t *pos1p, fcall_t *call1, fcall_t *call, type_t *arg1, type_t *arg2) { /* LINTED (automatic hides external declaration: warn) */ int promote, asgn, warn; tspec_t t1, t2; arginf_t *ai, *ai1; char *pos1; /* * If a function definition is available (def != NULL), we compare the * function call (call) with the definition. Otherwise, if a function * definition is available and it is not an old style definition * (decl != NULL && TP(decl->s_type)->t_proto), we compare the call * with this declaration. Otherwise we compare it with the first * call we have found (call1). */ /* arg1 must be promoted if it stems from an old style definition */ promote = def != NULL && def->s_osdef; /* - * If we compair with a definition or declaration, we must perform + * If we compare with a definition or declaration, we must perform * the same checks for qualifiers in indirected types as in * assignments. */ asgn = def != NULL || (decl != NULL && TP(decl->s_type)->t_proto); warn = 0; if (eqtype(arg1, arg2, 1, promote, asgn, &warn) && (!sflag || !warn)) return; /* * Other lint implementations print warnings as soon as the type * of an argument does not match exactly the expected type. The * result are lots of warnings which are really not necessary. * We print a warning only if * (0) at least one type is not an integer type and types differ * (1) hflag is set and types differ * (2) types differ, except in signedness * If the argument is an integer constant whose msb is not set, * signedness is ignored (e.g. 0 matches both signed and unsigned * int). This is with and without hflag. * If the argument is an integer constant with value 0 and the * expected argument is of type pointer and the width of the * integer constant is the same as the width of the pointer, * no warning is printed. */ t1 = arg1->t_tspec; t2 = arg2->t_tspec; if (isityp(t1) && isityp(t2) && !arg1->t_isenum && !arg2->t_isenum) { if (promote) { /* * XXX Here is a problem: Although it is possible to * pass an int where a char/short it expected, there * may be loss in significant digits. We should first * check for const arguments if they can be converted * into the original parameter type. */ if (t1 == FLOAT) { t1 = DOUBLE; } else if (t1 == CHAR || t1 == SCHAR) { t1 = INT; } else if (t1 == UCHAR) { t1 = tflag ? UINT : INT; } else if (t1 == SHORT) { t1 = INT; } else if (t1 == USHORT) { /* CONSTCOND */ t1 = INT_MAX < USHRT_MAX || tflag ? UINT : INT; } } if (styp(t1) == styp(t2)) { /* * types differ only in signedness; get information * about arguments */ /* * treat a definition like a call with variable * arguments */ ai1 = call1 != NULL ? call1->f_args : NULL; /* * if two calls are compared, ai1 is set to the * information for the n-th argument, if this was * a constant, otherwise to NULL */ for ( ; ai1 != NULL; ai1 = ai1->a_nxt) { if (ai1->a_num == n) break; } /* * ai is set to the information of the n-th arg * of the (second) call, if this was a constant, * otherwise to NULL */ for (ai = call->f_args; ai != NULL; ai = ai->a_nxt) { if (ai->a_num == n) break; } if (ai1 == NULL && ai == NULL) { /* no constant at all */ if (!hflag) return; } else if (ai1 == NULL || ai == NULL) { /* one constant */ if (ai == NULL) ai = ai1; if (ai->a_zero || ai->a_pcon) /* same value in signed and unsigned */ return; /* value (not representation) differently */ } else { /* * two constants, one signed, one unsigned; * if the msb of one of the constants is set, * the argument is used inconsistently. */ if (!ai1->a_ncon && !ai->a_ncon) return; } } } else if (t1 == PTR && isityp(t2)) { for (ai = call->f_args; ai != NULL; ai = ai->a_nxt) { if (ai->a_num == n) break; } /* * Vendor implementations of lint (e.g. HP-UX, Digital UNIX) * don't care about the size of the integer argument, * only whether or not it is zero. We do the same. */ if (ai != NULL && ai->a_zero) return; } pos1 = xstrdup(mkpos(pos1p)); /* %s, arg %d used inconsistently\t%s :: %s */ msg(6, hte->h_name, n, pos1, mkpos(&call->f_pos)); free(pos1); } /* * Compare the types in the NULL-terminated array ap with the format * string fmt. */ static void printflike(hte_t *hte, fcall_t *call, int n, const char *fmt, type_t **ap) { const char *fp; int fc; int fwidth, prec, left, sign, space, alt, zero; tspec_t sz, t1, t2 = NOTSPEC; type_t *tp; fp = fmt; fc = *fp++; for ( ; ; ) { if (fc == '\0') { if (*ap != NULL) tomanyarg(hte, call); break; } if (fc != '%') { badfmt(hte, call); break; } fc = *fp++; fwidth = prec = left = sign = space = alt = zero = 0; sz = NOTSPEC; /* Flags */ for ( ; ; ) { if (fc == '-') { if (left) break; left = 1; } else if (fc == '+') { if (sign) break; sign = 1; } else if (fc == ' ') { if (space) break; space = 1; } else if (fc == '#') { if (alt) break; alt = 1; } else if (fc == '0') { if (zero) break; zero = 1; } else { break; } fc = *fp++; } /* field width */ if (isdigit(fc)) { fwidth = 1; do { fc = *fp++; } while (isdigit(fc)) ; } else if (fc == '*') { fwidth = 1; fc = *fp++; if ((tp = *ap++) == NULL) { tofewarg(hte, call); break; } n++; if ((t1 = tp->t_tspec) != INT && (hflag || t1 != UINT)) inconarg(hte, call, n); } /* precision */ if (fc == '.') { fc = *fp++; prec = 1; if (isdigit(fc)) { do { fc = *fp++; } while (isdigit(fc)); } else if (fc == '*') { fc = *fp++; if ((tp = *ap++) == NULL) { tofewarg(hte, call); break; } n++; if (tp->t_tspec != INT) inconarg(hte, call, n); } else { badfmt(hte, call); break; } } if (fc == 'h') { sz = SHORT; } else if (fc == 'l') { sz = LONG; } else if (fc == 'q') { sz = QUAD; } else if (fc == 'L') { sz = LDOUBLE; } if (sz != NOTSPEC) fc = *fp++; if (fc == '%') { if (sz != NOTSPEC || left || sign || space || alt || zero || prec || fwidth) { badfmt(hte, call); } fc = *fp++; continue; } if (fc == '\0') { badfmt(hte, call); break; } if ((tp = *ap++) == NULL) { tofewarg(hte, call); break; } n++; if ((t1 = tp->t_tspec) == PTR) t2 = tp->t_subt->t_tspec; if (fc == 'd' || fc == 'i') { if (alt || sz == LDOUBLE) { badfmt(hte, call); break; } int_conv: if (sz == LONG) { if (t1 != LONG && (hflag || t1 != ULONG)) inconarg(hte, call, n); } else if (sz == QUAD) { if (t1 != QUAD && (hflag || t1 != UQUAD)) inconarg(hte, call, n); } else { /* * SHORT is always promoted to INT, USHORT * to INT or UINT. */ if (t1 != INT && (hflag || t1 != UINT)) inconarg(hte, call, n); } } else if (fc == 'o' || fc == 'u' || fc == 'x' || fc == 'X') { if ((alt && fc == 'u') || sz == LDOUBLE) badfmt(hte, call); uint_conv: if (sz == LONG) { if (t1 != ULONG && (hflag || t1 != LONG)) inconarg(hte, call, n); } else if (sz == QUAD) { if (t1 != UQUAD && (hflag || t1 != QUAD)) inconarg(hte, call, n); } else if (sz == SHORT) { /* USHORT was promoted to INT or UINT */ if (t1 != UINT && t1 != INT) inconarg(hte, call, n); } else { if (t1 != UINT && (hflag || t1 != INT)) inconarg(hte, call, n); } } else if (fc == 'D' || fc == 'O' || fc == 'U') { if ((alt && fc != 'O') || sz != NOTSPEC || !tflag) badfmt(hte, call); sz = LONG; if (fc == 'D') { goto int_conv; } else { goto uint_conv; } } else if (fc == 'f' || fc == 'e' || fc == 'E' || fc == 'g' || fc == 'G') { if (sz == NOTSPEC) sz = DOUBLE; if (sz != DOUBLE && sz != LDOUBLE) badfmt(hte, call); if (t1 != sz) inconarg(hte, call, n); } else if (fc == 'c') { if (sz != NOTSPEC || alt || zero) badfmt(hte, call); if (t1 != INT) inconarg(hte, call, n); } else if (fc == 's') { if (sz != NOTSPEC || alt || zero) badfmt(hte, call); if (t1 != PTR || (t2 != CHAR && t2 != UCHAR && t2 != SCHAR)) { inconarg(hte, call, n); } } else if (fc == 'p') { if (fwidth || prec || sz != NOTSPEC || alt || zero) badfmt(hte, call); if (t1 != PTR || (hflag && t2 != VOID)) inconarg(hte, call, n); } else if (fc == 'n') { if (fwidth || prec || alt || zero || sz == LDOUBLE) badfmt(hte, call); if (t1 != PTR) { inconarg(hte, call, n); } else if (sz == LONG) { if (t2 != LONG && t2 != ULONG) inconarg(hte, call, n); } else if (sz == SHORT) { if (t2 != SHORT && t2 != USHORT) inconarg(hte, call, n); } else { if (t2 != INT && t2 != UINT) inconarg(hte, call, n); } } else { badfmt(hte, call); break; } fc = *fp++; } } /* * Compare the types in the NULL-terminated array ap with the format * string fmt. */ static void scanflike(hte_t *hte, fcall_t *call, int n, const char *fmt, type_t **ap) { const char *fp; int fc; int noasgn, fwidth; tspec_t sz, t1 = NOTSPEC, t2 = NOTSPEC; type_t *tp = NULL; fp = fmt; fc = *fp++; for ( ; ; ) { if (fc == '\0') { if (*ap != NULL) tomanyarg(hte, call); break; } if (fc != '%') { badfmt(hte, call); break; } fc = *fp++; noasgn = fwidth = 0; sz = NOTSPEC; if (fc == '*') { noasgn = 1; fc = *fp++; } if (isdigit(fc)) { fwidth = 1; do { fc = *fp++; } while (isdigit(fc)); } if (fc == 'h') { sz = SHORT; } else if (fc == 'l') { sz = LONG; } else if (fc == 'q') { sz = QUAD; } else if (fc == 'L') { sz = LDOUBLE; } if (sz != NOTSPEC) fc = *fp++; if (fc == '%') { if (sz != NOTSPEC || noasgn || fwidth) badfmt(hte, call); fc = *fp++; continue; } if (!noasgn) { if ((tp = *ap++) == NULL) { tofewarg(hte, call); break; } n++; if ((t1 = tp->t_tspec) == PTR) t2 = tp->t_subt->t_tspec; } if (fc == 'd' || fc == 'i' || fc == 'n') { if (sz == LDOUBLE) badfmt(hte, call); if (sz != SHORT && sz != LONG && sz != QUAD) sz = INT; conv: if (!noasgn) { if (t1 != PTR) { inconarg(hte, call, n); } else if (t2 != styp(sz)) { inconarg(hte, call, n); } else if (hflag && t2 != sz) { inconarg(hte, call, n); } else if (tp->t_subt->t_const) { inconarg(hte, call, n); } } } else if (fc == 'o' || fc == 'u' || fc == 'x') { if (sz == LDOUBLE) badfmt(hte, call); if (sz == SHORT) { sz = USHORT; } else if (sz == LONG) { sz = ULONG; } else if (sz == QUAD) { sz = UQUAD; } else { sz = UINT; } goto conv; } else if (fc == 'D') { if (sz != NOTSPEC || !tflag) badfmt(hte, call); sz = LONG; goto conv; } else if (fc == 'O') { if (sz != NOTSPEC || !tflag) badfmt(hte, call); sz = ULONG; goto conv; } else if (fc == 'X') { /* * XXX valid in ANSI C, but in NetBSD's libc imple- * mented as "lx". Thats why it should be avoided. */ if (sz != NOTSPEC || !tflag) badfmt(hte, call); sz = ULONG; goto conv; } else if (fc == 'E') { /* * XXX valid in ANSI C, but in NetBSD's libc imple- * mented as "lf". Thats why it should be avoided. */ if (sz != NOTSPEC || !tflag) badfmt(hte, call); sz = DOUBLE; goto conv; } else if (fc == 'F') { /* XXX only for backward compatibility */ if (sz != NOTSPEC || !tflag) badfmt(hte, call); sz = DOUBLE; goto conv; } else if (fc == 'G') { /* * XXX valid in ANSI C, but in NetBSD's libc not * implemented */ if (sz != NOTSPEC && sz != LONG && sz != LDOUBLE) badfmt(hte, call); goto fconv; } else if (fc == 'e' || fc == 'f' || fc == 'g') { fconv: if (sz == NOTSPEC) { sz = FLOAT; } else if (sz == LONG) { sz = DOUBLE; } else if (sz != LDOUBLE) { badfmt(hte, call); sz = FLOAT; } goto conv; } else if (fc == 's' || fc == '[' || fc == 'c') { if (sz != NOTSPEC) badfmt(hte, call); if (fc == '[') { if ((fc = *fp++) == '-') { badfmt(hte, call); fc = *fp++; } if (fc != ']') { badfmt(hte, call); if (fc == '\0') break; } } if (!noasgn) { if (t1 != PTR) { inconarg(hte, call, n); } else if (t2 != CHAR && t2 != UCHAR && t2 != SCHAR) { inconarg(hte, call, n); } } } else if (fc == 'p') { if (sz != NOTSPEC) badfmt(hte, call); if (!noasgn) { if (t1 != PTR || t2 != PTR) { inconarg(hte, call, n); } else if (tp->t_subt->t_subt->t_tspec!=VOID) { if (hflag) inconarg(hte, call, n); } } } else { badfmt(hte, call); break; } fc = *fp++; } } static void badfmt(hte_t *hte, fcall_t *call) { /* %s: malformed format string\t%s */ msg(13, hte->h_name, mkpos(&call->f_pos)); } static void inconarg(hte_t *hte, fcall_t *call, int n) { /* %s, arg %d inconsistent with format\t%s(%d) */ msg(14, hte->h_name, n, mkpos(&call->f_pos)); } static void tofewarg(hte_t *hte, fcall_t *call) { /* %s: too few args for format \t%s */ msg(15, hte->h_name, mkpos(&call->f_pos)); } static void tomanyarg(hte_t *hte, fcall_t *call) { /* %s: too many args for format \t%s */ msg(16, hte->h_name, mkpos(&call->f_pos)); } /* * Print warnings for return values which are used, but not returned, * or return values which are always or sometimes ignored. */ static void chkrvu(hte_t *hte, sym_t *def) { fcall_t *call; int used, ignored; if (def == NULL) /* don't know wheter or not the functions returns a value */ return; if (hte->h_calls == NULL) return; if (def->s_rval) { /* function has return value */ used = ignored = 0; for (call = hte->h_calls; call != NULL; call = call->f_nxt) { used |= call->f_rused || call->f_rdisc; ignored |= !call->f_rused && !call->f_rdisc; } /* * XXX as soon as we are able to disable single warnings * the following dependencies from hflag should be removed. * but for now I do'nt want to be botherd by this warnings * which are almost always useless. */ if (!used && ignored) { if (hflag) /* %s returns value which is always ignored */ msg(8, hte->h_name); } else if (used && ignored) { if (hflag) /* %s returns value which is sometimes ign. */ msg(9, hte->h_name); } } else { /* function has no return value */ for (call = hte->h_calls; call != NULL; call = call->f_nxt) { if (call->f_rused) /* %s value is used( %s ), but none ret. */ msg(10, hte->h_name, mkpos(&call->f_pos)); } } } /* * Print warnings for inconsistent argument declarations. */ static void chkadecl(hte_t *hte, sym_t *def, sym_t *decl) { /* LINTED (automatic hides external declaration: warn) */ int osdef, eq, warn, n; sym_t *sym1, *sym; type_t **ap1, **ap2, *tp1, *tp2; char *pos1; const char *pos2; osdef = 0; if (def != NULL) { osdef = def->s_osdef; sym1 = def; } else if (decl != NULL && TP(decl->s_type)->t_proto) { sym1 = decl; } else { return; } if (TP(sym1->s_type)->t_tspec != FUNC) return; /* * XXX Prototypes should also be compared with old style function * declarations. */ for (sym = hte->h_syms; sym != NULL; sym = sym->s_nxt) { if (sym == sym1 || !TP(sym->s_type)->t_proto) continue; ap1 = TP(sym1->s_type)->t_args; ap2 = TP(sym->s_type)->t_args; n = 0; while (*ap1 != NULL && *ap2 != NULL) { warn = 0; eq = eqtype(*ap1, *ap2, 1, osdef, 0, &warn); if (!eq || warn) { pos1 = xstrdup(mkpos(&sym1->s_pos)); pos2 = mkpos(&sym->s_pos); /* %s, arg %d declared inconsistently ... */ msg(11, hte->h_name, n + 1, pos1, pos2); free(pos1); } n++; ap1++; ap2++; } if (*ap1 == *ap2) { tp1 = TP(sym1->s_type); tp2 = TP(sym->s_type); if (tp1->t_vararg == tp2->t_vararg) continue; if (tp2->t_vararg && sym1->s_va && sym1->s_nva == n && !sflag) { continue; } } /* %s: variable # of args declared\t%s :: %s */ pos1 = xstrdup(mkpos(&sym1->s_pos)); msg(12, hte->h_name, pos1, mkpos(&sym->s_pos)); free(pos1); } } /* * Check compatibility of two types. Returns 1 if types are compatible, * otherwise 0. * * ignqual if set, ignore qualifiers of outhermost type; used for * function arguments * promote if set, promote left type before comparison; used for * comparisons of arguments with parameters of old style * definitions * asgn left indirected type must have at least the same qualifiers * like right indirected type (for assignments and function * arguments) * *warn set to 1 if an old style declaration was compared with * an incompatible prototype declaration */ static int eqtype(type_t *tp1, type_t *tp2, int ignqual, int promot, int asgn, int *warn) { tspec_t t, to; int indir; to = NOTSPEC; indir = 0; while (tp1 != NULL && tp2 != NULL) { t = tp1->t_tspec; if (promot) { if (t == FLOAT) { t = DOUBLE; } else if (t == CHAR || t == SCHAR) { t = INT; } else if (t == UCHAR) { t = tflag ? UINT : INT; } else if (t == SHORT) { t = INT; } else if (t == USHORT) { /* CONSTCOND */ t = INT_MAX < USHRT_MAX || tflag ? UINT : INT; } } if (asgn && to == PTR) { if (indir == 1 && (t == VOID || tp2->t_tspec == VOID)) return (1); } if (t != tp2->t_tspec) { /* * Give pointer to types which differ only in * signedness a chance if not sflag and not hflag. */ if (sflag || hflag || to != PTR) return (0); if (styp(t) != styp(tp2->t_tspec)) return (0); } if (tp1->t_isenum && tp2->t_isenum) { if (tp1->t_istag && tp2->t_istag) { return (tp1->t_tag == tp2->t_tag); } else if (tp1->t_istynam && tp2->t_istynam) { return (tp1->t_tynam == tp2->t_tynam); } else if (tp1->t_isuniqpos && tp2->t_isuniqpos) { return (tp1->t_uniqpos.p_line == tp2->t_uniqpos.p_line && tp1->t_uniqpos.p_file == tp2->t_uniqpos.p_file && tp1->t_uniqpos.p_uniq == tp2->t_uniqpos.p_uniq); } else { return (0); } } /* * XXX Handle combinations of enum and int if eflag is set. * But note: enum and 0 should be allowed. */ if (asgn && indir == 1) { if (!tp1->t_const && tp2->t_const) return (0); if (!tp1->t_volatile && tp2->t_volatile) return (0); } else if (!ignqual && !tflag) { if (tp1->t_const != tp2->t_const) return (0); if (tp1->t_const != tp2->t_const) return (0); } if (t == STRUCT || t == UNION) { if (tp1->t_istag && tp2->t_istag) { return (tp1->t_tag == tp2->t_tag); } else if (tp1->t_istynam && tp2->t_istynam) { return (tp1->t_tynam == tp2->t_tynam); } else if (tp1->t_isuniqpos && tp2->t_isuniqpos) { return (tp1->t_uniqpos.p_line == tp2->t_uniqpos.p_line && tp1->t_uniqpos.p_file == tp2->t_uniqpos.p_file && tp1->t_uniqpos.p_uniq == tp2->t_uniqpos.p_uniq); } else { return (0); } } if (t == ARRAY && tp1->t_dim != tp2->t_dim) { if (tp1->t_dim != 0 && tp2->t_dim != 0) return (0); } if (t == FUNC) { if (tp1->t_proto && tp2->t_proto) { if (!eqargs(tp1, tp2, warn)) return (0); } else if (tp1->t_proto) { if (!mnoarg(tp1, warn)) return (0); } else if (tp2->t_proto) { if (!mnoarg(tp2, warn)) return (0); } } tp1 = tp1->t_subt; tp2 = tp2->t_subt; ignqual = promot = 0; to = t; indir++; } return (tp1 == tp2); } /* * Compares arguments of two prototypes */ static int eqargs(type_t *tp1, type_t *tp2, int *warn) { type_t **a1, **a2; if (tp1->t_vararg != tp2->t_vararg) return (0); a1 = tp1->t_args; a2 = tp2->t_args; while (*a1 != NULL && *a2 != NULL) { if (eqtype(*a1, *a2, 1, 0, 0, warn) == 0) return (0); a1++; a2++; } return (*a1 == *a2); } /* * mnoarg() (matches functions with no argument type information) * returns 1 if all parameters of a prototype are compatible with * and old style function declaration. * This is the case if following conditions are met: * 1. the prototype must have a fixed number of parameters * 2. no parameter is of type float * 3. no parameter is converted to another type if integer promotion * is applied on it */ static int mnoarg(type_t *tp, int *warn) { type_t **arg; tspec_t t; if (tp->t_vararg && warn != NULL) *warn = 1; for (arg = tp->t_args; *arg != NULL; arg++) { if ((t = (*arg)->t_tspec) == FLOAT) return (0); if (t == CHAR || t == SCHAR || t == UCHAR) return (0); if (t == SHORT || t == USHORT) return (0); } return (1); }