diff --git a/contrib/mandoc/config.h b/contrib/mandoc/config.h index 91957717b3fc..ea6d70042670 100644 --- a/contrib/mandoc/config.h +++ b/contrib/mandoc/config.h @@ -1,57 +1,57 @@ #ifdef __cplusplus #error "Do not use C++. See the INSTALL file." #endif #include #define MAN_CONF_FILE "/etc/man.conf" #define MANPATH_BASE "/usr/share/man" #define MANPATH_DEFAULT "/usr/share/man:/usr/local/man" #define OSENUM MANDOC_OS_OTHER #define UTF8_LOCALE "en_US.UTF-8" #define HAVE_DIRENT_NAMLEN 1 #define HAVE_ENDIAN 0 #define HAVE_ERR 1 #define HAVE_FTS 1 -#if defined(__GLIBC__) || defined(__APPLE__) +#if defined(__linux__) || defined(__APPLE__) #define HAVE_FTS_COMPARE_CONST 0 #else #define HAVE_FTS_COMPARE_CONST 1 #endif #define HAVE_GETLINE 1 #define HAVE_GETSUBOPT 1 #define HAVE_ISBLANK 1 #define HAVE_LESS_T 1 #define HAVE_MKDTEMP 1 #define HAVE_MKSTEMPS 1 #define HAVE_NTOHL 1 #define HAVE_PLEDGE 0 #define HAVE_PROGNAME 1 #define HAVE_REALLOCARRAY 1 #define HAVE_RECALLOCARRAY 0 #define HAVE_REWB_BSD 1 #define HAVE_REWB_SYSV 1 #define HAVE_SANDBOX_INIT 0 #define HAVE_STRCASESTR 1 #define HAVE_STRINGLIST 1 #define HAVE_STRLCAT 1 #define HAVE_STRLCPY 1 #define HAVE_STRNDUP 1 #define HAVE_STRPTIME 1 #define HAVE_STRSEP 1 #define HAVE_STRTONUM 1 #define HAVE_SYS_ENDIAN 1 #define HAVE_VASPRINTF 1 #define HAVE_WCHAR 1 #define HAVE_OHASH 1 #define NEED_XPG4_2 0 #define BINM_APROPOS "apropos" #define BINM_CATMAN "catman" #define BINM_MAKEWHATIS "makewhatis" #define BINM_MAN "man" #define BINM_SOELIM "soelim" #define BINM_WHATIS "whatis" #define BINM_PAGER "less" extern void *recallocarray(void *, size_t, size_t, size_t); diff --git a/lib/libpmc/pmu-events/jevents.c b/lib/libpmc/pmu-events/jevents.c index 7059b31da2ba..628ed26c6f9d 100644 --- a/lib/libpmc/pmu-events/jevents.c +++ b/lib/libpmc/pmu-events/jevents.c @@ -1,1444 +1,1444 @@ /* Parse event JSON files */ /* * Copyright (c) 2014, Intel Corporation * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 * COPYRIGHT HOLDER 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 #include /* getrlimit */ #include #include /* getrlimit */ #include #include #include #include #include #include #include #include #include #include #include #include #include "list.h" #include "jsmn.h" #include "json.h" #include "pmu-events.h" static int nftw_ordered(const char *path, int (*fn)(const char *, const struct stat *, int, struct FTW *), int nfds, int ftwflags); #define nftw nftw_ordered _Noreturn void _Exit(int); char *get_cpu_str(void); int verbose; static char *prog; struct json_event { char *name; char *compat; char *event; char *desc; char *long_desc; char *pmu; char *unit; char *perpkg; char *aggr_mode; char *metric_expr; char *metric_name; char *metric_group; char *deprecated; char *metric_constraint; }; static enum aggr_mode_class convert(const char *aggr_mode) { if (!strcmp(aggr_mode, "PerCore")) return PerCore; else if (!strcmp(aggr_mode, "PerChip")) return PerChip; pr_err("%s: Wrong AggregationMode value '%s'\n", prog, aggr_mode); return -1; } static LIST_HEAD(sys_event_tables); struct sys_event_table { struct list_head list; char *soc_id; }; static void free_sys_event_tables(void) { struct sys_event_table *et, *next; list_for_each_entry_safe(et, next, &sys_event_tables, list) { free(et->soc_id); free(et); } } int eprintf(int level, int var, const char *fmt, ...) { int ret; va_list args; if (var < level) return 0; va_start(args, fmt); ret = vfprintf(stderr, fmt, args); va_end(args); return ret; } static void addfield(char *map, char **dst, const char *sep, const char *a, jsmntok_t *bt) { unsigned int len = strlen(a) + 1 + strlen(sep); int olen = *dst ? strlen(*dst) : 0; int blen = bt ? json_len(bt) : 0; char *out; out = realloc(*dst, len + olen + blen); if (!out) { /* Don't add field in this case */ return; } *dst = out; if (!olen) *(*dst) = 0; else strcat(*dst, sep); strcat(*dst, a); if (bt) strncat(*dst, map + bt->start, blen); } static void fixname(char *s) { for (; *s; s++) *s = tolower(*s); } static void fixdesc(char *s) { char *e = s + strlen(s); /* Remove trailing dots that look ugly in perf list */ --e; while (e >= s && isspace(*e)) --e; if (e >= s && *e == '.') *e = 0; } /* Add escapes for '\' so they are proper C strings. */ static char *fixregex(char *s) { int len = 0; int esc_count = 0; char *fixed = NULL; char *p, *q; /* Count the number of '\' in string */ for (p = s; *p; p++) { ++len; if (*p == '\\') ++esc_count; } if (esc_count == 0) return s; /* allocate space for a new string */ fixed = (char *) malloc(len + esc_count + 1); if (!fixed) return NULL; /* copy over the characters */ q = fixed; for (p = s; *p; p++) { if (*p == '\\') { *q = '\\'; ++q; } *q = *p; ++q; } *q = '\0'; return fixed; } static struct msrmap { const char *num; const char *pname; } msrmap[] = { { "0x3F6", "ldlat=" }, { "0x1A6", "offcore_rsp=" }, { "0x1A7", "offcore_rsp=" }, { "0x3F7", "frontend=" }, { NULL, NULL } }; static void cut_comma(char *map, jsmntok_t *newval) { int i; /* Cut off everything after comma */ for (i = newval->start; i < newval->end; i++) { if (map[i] == ',') newval->end = i; } } static struct msrmap *lookup_msr(char *map, jsmntok_t *val) { jsmntok_t newval = *val; static bool warned; int i; cut_comma(map, &newval); for (i = 0; msrmap[i].num; i++) if (json_streq(map, &newval, msrmap[i].num)) return &msrmap[i]; if (!warned) { warned = true; pr_err("%s: Unknown MSR in event file %.*s\n", prog, json_len(val), map + val->start); } return NULL; } static struct map { const char *json; const char *perf; } unit_to_pmu[] = { { "CBO", "uncore_cbox" }, { "QPI LL", "uncore_qpi" }, { "SBO", "uncore_sbox" }, { "iMPH-U", "uncore_arb" }, { "CPU-M-CF", "cpum_cf" }, { "CPU-M-SF", "cpum_sf" }, { "UPI LL", "uncore_upi" }, { "hisi_sicl,cpa", "hisi_sicl,cpa"}, { "hisi_sccl,ddrc", "hisi_sccl,ddrc" }, { "hisi_sccl,hha", "hisi_sccl,hha" }, { "hisi_sccl,l3c", "hisi_sccl,l3c" }, /* it's not realistic to keep adding these, we need something more scalable ... */ { "imx8_ddr", "imx8_ddr" }, { "L3PMC", "amd_l3" }, { "DFPMC", "amd_df" }, { "cpu_core", "cpu_core" }, { "cpu_atom", "cpu_atom" }, {} }; static const char *field_to_perf(struct map *table, char *map, jsmntok_t *val) { int i; for (i = 0; table[i].json; i++) { if (json_streq(map, val, table[i].json)) return table[i].perf; } return NULL; } #define EXPECT(e, t, m) do { if (!(e)) { \ jsmntok_t *loc = (t); \ if (!(t)->start && (t) > tokens) \ loc = (t) - 1; \ pr_err("%s:%d: " m ", got %s\n", fn, \ json_line(map, loc), \ json_name(t)); \ err = -EIO; \ goto out_free; \ } } while (0) static char *topic; static char *get_topic(void) { char *tp; int i; /* tp is free'd in process_one_file() */ i = asprintf(&tp, "%s", topic); if (i < 0) { pr_info("%s: asprintf() error %s\n", prog); return NULL; } for (i = 0; i < (int) strlen(tp); i++) { char c = tp[i]; if (c == '-') tp[i] = ' '; else if (c == '.') { tp[i] = '\0'; break; } } return tp; } static int add_topic(char *bname) { free(topic); topic = strdup(bname); if (!topic) { pr_info("%s: strdup() error %s for file %s\n", prog, strerror(errno), bname); return -ENOMEM; } return 0; } struct perf_entry_data { FILE *outfp; char *topic; }; static int close_table; static void print_events_table_prefix(FILE *fp, const char *tblname) { fprintf(fp, "static const struct pmu_event %s[] = {\n", tblname); close_table = 1; } static int print_events_table_entry(void *data, struct json_event *je) { struct perf_entry_data *pd = data; FILE *outfp = pd->outfp; char *topic_local = pd->topic; /* * TODO: Remove formatting chars after debugging to reduce * string lengths. */ fprintf(outfp, "{\n"); if (je->name) fprintf(outfp, "\t.name = \"%s\",\n", je->name); if (je->event) fprintf(outfp, "\t.event = \"%s\",\n", je->event); fprintf(outfp, "\t.desc = \"%s\",\n", je->desc); if (je->compat) fprintf(outfp, "\t.compat = \"%s\",\n", je->compat); fprintf(outfp, "\t.topic = \"%s\",\n", topic_local); if (je->long_desc && je->long_desc[0]) fprintf(outfp, "\t.long_desc = \"%s\",\n", je->long_desc); if (je->pmu) fprintf(outfp, "\t.pmu = \"%s\",\n", je->pmu); if (je->unit) fprintf(outfp, "\t.unit = \"%s\",\n", je->unit); if (je->perpkg) fprintf(outfp, "\t.perpkg = \"%s\",\n", je->perpkg); if (je->aggr_mode) fprintf(outfp, "\t.aggr_mode = \"%d\",\n", convert(je->aggr_mode)); if (je->metric_expr) fprintf(outfp, "\t.metric_expr = \"%s\",\n", je->metric_expr); if (je->metric_name) fprintf(outfp, "\t.metric_name = \"%s\",\n", je->metric_name); if (je->metric_group) fprintf(outfp, "\t.metric_group = \"%s\",\n", je->metric_group); if (je->deprecated) fprintf(outfp, "\t.deprecated = \"%s\",\n", je->deprecated); if (je->metric_constraint) fprintf(outfp, "\t.metric_constraint = \"%s\",\n", je->metric_constraint); fprintf(outfp, "},\n"); return 0; } struct event_struct { struct list_head list; char *name; char *event; char *compat; char *desc; char *long_desc; char *pmu; char *unit; char *perpkg; char *aggr_mode; char *metric_expr; char *metric_name; char *metric_group; char *deprecated; char *metric_constraint; }; #define ADD_EVENT_FIELD(field) do { if (je->field) { \ es->field = strdup(je->field); \ if (!es->field) \ goto out_free; \ } } while (0) #define FREE_EVENT_FIELD(field) free(es->field) #define TRY_FIXUP_FIELD(field) do { if (es->field && !je->field) {\ je->field = strdup(es->field); \ if (!je->field) \ return -ENOMEM; \ } } while (0) #define FOR_ALL_EVENT_STRUCT_FIELDS(op) do { \ op(name); \ op(event); \ op(desc); \ op(long_desc); \ op(pmu); \ op(unit); \ op(perpkg); \ op(aggr_mode); \ op(metric_expr); \ op(metric_name); \ op(metric_group); \ op(deprecated); \ } while (0) static LIST_HEAD(arch_std_events); static void free_arch_std_events(void) { struct event_struct *es, *next; list_for_each_entry_safe(es, next, &arch_std_events, list) { FOR_ALL_EVENT_STRUCT_FIELDS(FREE_EVENT_FIELD); list_del_init(&es->list); free(es); } } static int save_arch_std_events(void *data __unused, struct json_event *je) { struct event_struct *es; es = malloc(sizeof(*es)); if (!es) return -ENOMEM; memset(es, 0, sizeof(*es)); FOR_ALL_EVENT_STRUCT_FIELDS(ADD_EVENT_FIELD); list_add_tail(&es->list, &arch_std_events); return 0; out_free: FOR_ALL_EVENT_STRUCT_FIELDS(FREE_EVENT_FIELD); free(es); return -ENOMEM; } static void print_events_table_suffix(FILE *outfp) { fprintf(outfp, "{\n"); fprintf(outfp, "\t.name = 0,\n"); fprintf(outfp, "\t.event = 0,\n"); fprintf(outfp, "\t.desc = 0,\n"); fprintf(outfp, "},\n"); fprintf(outfp, "};\n"); close_table = 0; } static struct fixed { const char *name; const char *event; } fixed[] = { #if 0 { "inst_retired.any", "event=0xc0,period=2000003" }, { "inst_retired.any_p", "event=0xc0,period=2000003" }, { "cpu_clk_unhalted.ref", "event=0x0,umask=0x03,period=2000003" }, { "cpu_clk_unhalted.thread", "event=0x3c,period=2000003" }, { "cpu_clk_unhalted.core", "event=0x3c,period=2000003" }, { "cpu_clk_unhalted.thread_any", "event=0x3c,any=1,period=2000003" }, #endif { NULL, NULL}, }; /* * Handle different fixed counter encodings between JSON and perf. */ static char *real_event(const char *name, char *event) { int i; if (!name) return NULL; for (i = 0; fixed[i].name; i++) if (!strcasecmp(name, fixed[i].name)) return (char *)fixed[i].event; return event; } static int try_fixup(const char *fn, char *arch_std, struct json_event *je, char **event) { /* try to find matching event from arch standard values */ struct event_struct *es; list_for_each_entry(es, &arch_std_events, list) { if (!strcmp(arch_std, es->name)) { FOR_ALL_EVENT_STRUCT_FIELDS(TRY_FIXUP_FIELD); *event = je->event; return 0; } } pr_err("%s: could not find matching %s for %s\n", prog, arch_std, fn); return -1; } /* Call func with each event in the json file */ static int json_events(const char *fn, int (*func)(void *data, struct json_event *je), void *data) { int err; size_t size; jsmntok_t *tokens, *tok; int i, j, len; char *map; char buf[128]; if (!fn) return -ENOENT; tokens = parse_json(fn, &map, &size, &len); if (!tokens) return -EIO; EXPECT(tokens->type == JSMN_ARRAY, tokens, "expected top level array"); tok = tokens + 1; for (i = 0; i < tokens->size; i++) { char *event = NULL; char *extra_desc = NULL; char *filter = NULL; struct json_event je = {}; char *arch_std = NULL; unsigned long long eventcode = 0; unsigned long long configcode = 0; struct msrmap *msr = NULL; jsmntok_t *msrval = NULL; jsmntok_t *precise = NULL; jsmntok_t *obj = tok++; bool configcode_present = false; char *umask = NULL; char *cmask = NULL; char *inv = NULL; char *any = NULL; char *edge = NULL; char *period = NULL; char *fc_mask = NULL; char *ch_mask = NULL; EXPECT(obj->type == JSMN_OBJECT, obj, "expected object"); for (j = 0; j < obj->size; j += 2) { jsmntok_t *field, *val; int nz; char *s; field = tok + j; EXPECT(field->type == JSMN_STRING, tok + j, "Expected field name"); val = tok + j + 1; EXPECT(val->type == JSMN_STRING, tok + j + 1, "Expected string value"); nz = !json_streq(map, val, "0"); /* match_field */ if (json_streq(map, field, "UMask") && nz) { addfield(map, &umask, "", "umask=", val); } else if (json_streq(map, field, "CounterMask") && nz) { addfield(map, &cmask, "", "cmask=", val); } else if (json_streq(map, field, "Invert") && nz) { addfield(map, &inv, "", "inv=", val); } else if (json_streq(map, field, "AnyThread") && nz) { addfield(map, &any, "", "any=", val); } else if (json_streq(map, field, "EdgeDetect") && nz) { addfield(map, &edge, "", "edge=", val); } else if (json_streq(map, field, "SampleAfterValue") && nz) { addfield(map, &period, "", "period=", val); } else if (json_streq(map, field, "FCMask") && nz) { addfield(map, &fc_mask, "", "fc_mask=", val); } else if (json_streq(map, field, "PortMask") && nz) { addfield(map, &ch_mask, "", "ch_mask=", val); } else if (json_streq(map, field, "EventCode")) { char *code = NULL; addfield(map, &code, "", "", val); eventcode |= strtoul(code, NULL, 0); free(code); } else if (json_streq(map, field, "ConfigCode")) { char *code = NULL; addfield(map, &code, "", "", val); configcode |= strtoul(code, NULL, 0); free(code); configcode_present = true; } else if (json_streq(map, field, "ExtSel")) { char *code = NULL; addfield(map, &code, "", "", val); eventcode |= strtoul(code, NULL, 0) << 8; free(code); } else if (json_streq(map, field, "EventName")) { addfield(map, &je.name, "", "", val); } else if (json_streq(map, field, "Compat")) { addfield(map, &je.compat, "", "", val); } else if (json_streq(map, field, "BriefDescription")) { addfield(map, &je.desc, "", "", val); fixdesc(je.desc); } else if (json_streq(map, field, "PublicDescription")) { addfield(map, &je.long_desc, "", "", val); fixdesc(je.long_desc); } else if (json_streq(map, field, "PEBS") && nz) { precise = val; } else if (json_streq(map, field, "MSRIndex") && nz) { msr = lookup_msr(map, val); } else if (json_streq(map, field, "MSRValue")) { msrval = val; } else if (json_streq(map, field, "Errata") && !json_streq(map, val, "null")) { addfield(map, &extra_desc, ". ", " Spec update: ", val); } else if (json_streq(map, field, "Data_LA") && nz) { addfield(map, &extra_desc, ". ", " Supports address when precise", NULL); } else if (json_streq(map, field, "Unit")) { const char *ppmu; ppmu = field_to_perf(unit_to_pmu, map, val); if (ppmu) { je.pmu = strdup(ppmu); } else { if (!je.pmu) je.pmu = strdup("uncore_"); addfield(map, &je.pmu, "", "", val); for (s = je.pmu; *s; s++) *s = tolower(*s); } } else if (json_streq(map, field, "Filter")) { addfield(map, &filter, "", "", val); } else if (json_streq(map, field, "ScaleUnit")) { addfield(map, &je.unit, "", "", val); } else if (json_streq(map, field, "PerPkg")) { addfield(map, &je.perpkg, "", "", val); } else if (json_streq(map, field, "AggregationMode")) { addfield(map, &je.aggr_mode, "", "", val); } else if (json_streq(map, field, "Deprecated")) { addfield(map, &je.deprecated, "", "", val); } else if (json_streq(map, field, "MetricName")) { addfield(map, &je.metric_name, "", "", val); } else if (json_streq(map, field, "MetricGroup")) { addfield(map, &je.metric_group, "", "", val); } else if (json_streq(map, field, "MetricConstraint")) { addfield(map, &je.metric_constraint, "", "", val); } else if (json_streq(map, field, "MetricExpr")) { addfield(map, &je.metric_expr, "", "", val); } else if (json_streq(map, field, "ArchStdEvent")) { addfield(map, &arch_std, "", "", val); for (s = arch_std; *s; s++) *s = tolower(*s); } /* ignore unknown fields */ } if (precise && je.desc && !strstr(je.desc, "(Precise Event)")) { if (json_streq(map, precise, "2")) addfield(map, &extra_desc, " ", "(Must be precise)", NULL); else addfield(map, &extra_desc, " ", "(Precise event)", NULL); } if (configcode_present) snprintf(buf, sizeof buf, "config=%#llx", configcode); else snprintf(buf, sizeof buf, "event=%#llx", eventcode); addfield(map, &event, ",", buf, NULL); if (any) addfield(map, &event, ",", any, NULL); if (ch_mask) addfield(map, &event, ",", ch_mask, NULL); if (cmask) addfield(map, &event, ",", cmask, NULL); if (edge) addfield(map, &event, ",", edge, NULL); if (fc_mask) addfield(map, &event, ",", fc_mask, NULL); if (inv) addfield(map, &event, ",", inv, NULL); if (period) addfield(map, &event, ",", period, NULL); if (umask) addfield(map, &event, ",", umask, NULL); if (je.desc && extra_desc) addfield(map, &je.desc, " ", extra_desc, NULL); if (je.long_desc && extra_desc) addfield(map, &je.long_desc, " ", extra_desc, NULL); if (je.pmu) { addfield(map, &je.desc, ". ", "Unit: ", NULL); addfield(map, &je.desc, "", je.pmu, NULL); addfield(map, &je.desc, "", " ", NULL); } if (filter) addfield(map, &event, ",", filter, NULL); if (msr != NULL) addfield(map, &event, ",", msr->pname, msrval); if (je.name) fixname(je.name); if (arch_std) { /* * An arch standard event is referenced, so try to * fixup any unassigned values. */ err = try_fixup(fn, arch_std, &je, &event); if (err) goto free_strings; } je.event = real_event(je.name, event); err = func(data, &je); free_strings: free(umask); free(cmask); free(inv); free(any); free(edge); free(period); free(fc_mask); free(ch_mask); free(event); free(je.desc); free(je.name); free(je.compat); free(je.long_desc); free(extra_desc); free(je.pmu); free(filter); free(je.perpkg); free(je.aggr_mode); free(je.deprecated); free(je.unit); free(je.metric_expr); free(je.metric_name); free(je.metric_group); free(je.metric_constraint); free(arch_std); if (err) break; tok += j; } EXPECT(tok - tokens == len, tok, "unexpected objects at end"); err = 0; out_free: free_json(map, size, tokens); return err; } static char *file_name_to_table_name(char *fname) { unsigned int i; int n; int c; char *tblname; /* * Ensure tablename starts with alphabetic character. * Derive rest of table name from basename of the JSON file, * replacing hyphens and stripping out .json suffix. */ n = asprintf(&tblname, "pme_%s", fname); if (n < 0) { pr_info("%s: asprintf() error %s for file %s\n", prog, strerror(errno), fname); return NULL; } for (i = 0; i < strlen(tblname); i++) { c = tblname[i]; if (c == '-' || c == '/') tblname[i] = '_'; else if (c == '.') { tblname[i] = '\0'; break; } else if (!isalnum(c) && c != '_') { pr_err("%s: Invalid character '%c' in file name '%s'\n", prog, c, fname); free(tblname); tblname = NULL; break; } } return tblname; } static bool is_sys_dir(char *fname) { size_t len = strlen(fname), len2 = strlen("/sys"); if (len2 > len) return false; return !strcmp(fname+len-len2, "/sys"); } static void print_mapping_table_prefix(FILE *outfp) { fprintf(outfp, "const struct pmu_events_map pmu_events_map[] = {\n"); } static void print_mapping_table_suffix(FILE *outfp) { /* * Print the terminating, NULL entry. */ fprintf(outfp, "{\n"); fprintf(outfp, "\t.cpuid = 0,\n"); fprintf(outfp, "\t.version = 0,\n"); fprintf(outfp, "\t.type = 0,\n"); fprintf(outfp, "\t.table = 0,\n"); fprintf(outfp, "},\n"); /* and finally, the closing curly bracket for the struct */ fprintf(outfp, "};\n"); } static void print_mapping_test_table(FILE *outfp) { /* * Print the terminating, NULL entry. */ fprintf(outfp, "{\n"); fprintf(outfp, "\t.cpuid = \"testcpu\",\n"); fprintf(outfp, "\t.version = \"v1\",\n"); fprintf(outfp, "\t.type = \"core\",\n"); fprintf(outfp, "\t.table = pme_test_soc_cpu,\n"); fprintf(outfp, "},\n"); } static void print_system_event_mapping_table_prefix(FILE *outfp) { fprintf(outfp, "\nconst struct pmu_sys_events pmu_sys_event_tables[] = {"); } static void print_system_event_mapping_table_suffix(FILE *outfp) { fprintf(outfp, "\n\t{\n\t\t.table = 0\n\t},"); fprintf(outfp, "\n};\n"); } static int process_system_event_tables(FILE *outfp) { struct sys_event_table *sys_event_table; print_system_event_mapping_table_prefix(outfp); list_for_each_entry(sys_event_table, &sys_event_tables, list) { fprintf(outfp, "\n\t{\n\t\t.table = %s,\n\t\t.name = \"%s\",\n\t},", sys_event_table->soc_id, sys_event_table->soc_id); } print_system_event_mapping_table_suffix(outfp); return 0; } static int process_mapfile(FILE *outfp, char *fpath) { int n = 16384; FILE *mapfp; char *save = NULL; char *line, *p; int line_num; char *tblname; int ret = 0; pr_info("%s: Processing mapfile %s\n", prog, fpath); line = malloc(n); if (!line) return -1; mapfp = fopen(fpath, "r"); if (!mapfp) { pr_info("%s: Error %s opening %s\n", prog, strerror(errno), fpath); free(line); return -1; } print_mapping_table_prefix(outfp); /* Skip first line (header) */ p = fgets(line, n, mapfp); if (!p) goto out; line_num = 1; while (1) { char *cpuid, *version, *type, *fname; line_num++; p = fgets(line, n, mapfp); if (!p) break; if (line[0] == '#' || line[0] == '\n') continue; if (line[strlen(line)-1] != '\n') { /* TODO Deal with lines longer than 16K */ pr_info("%s: Mapfile %s: line %d too long, aborting\n", prog, fpath, line_num); ret = -1; goto out; } line[strlen(line)-1] = '\0'; cpuid = fixregex(strtok_r(p, ",", &save)); version = strtok_r(NULL, ",", &save); fname = strtok_r(NULL, ",", &save); type = strtok_r(NULL, ",", &save); tblname = file_name_to_table_name(fname); fprintf(outfp, "{\n"); fprintf(outfp, "\t.cpuid = \"%s\",\n", cpuid); fprintf(outfp, "\t.version = \"%s\",\n", version); fprintf(outfp, "\t.type = \"%s\",\n", type); /* * CHECK: We can't use the type (eg "core") field in the * table name. For us to do that, we need to somehow tweak * the other caller of file_name_to_table(), process_json() * to determine the type. process_json() file has no way * of knowing these are "core" events unless file name has * core in it. If filename has core in it, we can safely * ignore the type field here also. */ fprintf(outfp, "\t.table = %s\n", tblname); fprintf(outfp, "},\n"); } out: print_mapping_test_table(outfp); print_mapping_table_suffix(outfp); fclose(mapfp); free(line); return ret; } /* * If we fail to locate/process JSON and map files, create a NULL mapping * table. This would at least allow perf to build even if we can't find/use * the aliases. */ static void create_empty_mapping(const char *output_file) { FILE *outfp; pr_info("%s: Creating empty pmu_events_map[] table\n", prog); /* Truncate file to clear any partial writes to it */ outfp = fopen(output_file, "w"); if (!outfp) { perror("fopen()"); _Exit(1); } fprintf(outfp, "#include \"pmu-events/pmu-events.h\"\n"); print_mapping_table_prefix(outfp); print_mapping_table_suffix(outfp); print_system_event_mapping_table_prefix(outfp); print_system_event_mapping_table_suffix(outfp); fclose(outfp); } static int get_maxfds(void) { struct rlimit rlim; if (getrlimit(RLIMIT_NOFILE, &rlim) == 0) { if (rlim.rlim_max == RLIM_INFINITY) return 512; return MIN(rlim.rlim_max / 2, 512); } return 512; } /* * nftw() doesn't let us pass an argument to the processing function, * so use a global variables. */ static FILE *eventsfp; static char *mapfile; static int is_leaf_dir(const char *fpath) { DIR *d; struct dirent *dir; int res = 1; d = opendir(fpath); if (!d) return 0; while ((dir = readdir(d)) != NULL) { if (!strcmp(dir->d_name, ".") || !strcmp(dir->d_name, "..")) continue; if (dir->d_type == DT_DIR) { res = 0; break; } else if (dir->d_type == DT_UNKNOWN) { char path[PATH_MAX]; struct stat st; snprintf(path, sizeof(path), "%s/%s", fpath, dir->d_name); if (stat(path, &st)) break; if (S_ISDIR(st.st_mode)) { res = 0; break; } } } closedir(d); return res; } static int is_json_file(const char *name) { const char *suffix; if (strlen(name) < 5) return 0; suffix = name + strlen(name) - 5; if (strncmp(suffix, ".json", 5) == 0) return 1; return 0; } static int preprocess_arch_std_files(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) { int level = ftwbuf->level; int is_file = typeflag == FTW_F; if (level == 1 && is_file && is_json_file(fpath)) return json_events(fpath, save_arch_std_events, (void *)(uintptr_t)sb); return 0; } static int process_one_file(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf) { char *tblname, *bname; int is_dir = typeflag == FTW_D; int is_file = typeflag == FTW_F; int level = ftwbuf->level; int err = 0; if (level >= 2 && is_dir) { int count = 0; /* * For level 2 directory, bname will include parent name, * like vendor/platform. So search back from platform dir * to find this. * Something similar for level 3 directory, but we're a PMU * category folder, like vendor/platform/cpu. */ bname = (char *) fpath + ftwbuf->base - 2; for (;;) { if (*bname == '/') count++; if (count == level - 1) break; bname--; } bname++; } else bname = (char *) fpath + ftwbuf->base; pr_debug("%s %d %7jd %-20s %s\n", is_file ? "f" : is_dir ? "d" : "x", level, sb->st_size, bname, fpath); /* base dir or too deep */ if (level == 0 || level > 4) return 0; /* model directory, reset topic */ if ((level == 1 && is_dir && is_leaf_dir(fpath)) || (level >= 2 && is_dir && is_leaf_dir(fpath))) { if (close_table) print_events_table_suffix(eventsfp); /* * Drop file name suffix. Replace hyphens with underscores. * Fail if file name contains any alphanum characters besides * underscores. */ tblname = file_name_to_table_name(bname); if (!tblname) { pr_info("%s: Error determining table name for %s\n", prog, bname); return -1; } if (is_sys_dir(bname)) { struct sys_event_table *sys_event_table; sys_event_table = malloc(sizeof(*sys_event_table)); if (!sys_event_table) return -1; sys_event_table->soc_id = strdup(tblname); if (!sys_event_table->soc_id) { free(sys_event_table); return -1; } list_add_tail(&sys_event_table->list, &sys_event_tables); } print_events_table_prefix(eventsfp, tblname); return 0; } /* * Save the mapfile name for now. We will process mapfile * after processing all JSON files (so we can write out the * mapping table after all PMU events tables). * */ if (level == 1 && is_file) { if (!strcmp(bname, "mapfile.csv")) { mapfile = strdup(fpath); return 0; } if (is_json_file(bname)) pr_debug("%s: ArchStd json is preprocessed %s\n", prog, fpath); else pr_info("%s: Ignoring file %s\n", prog, fpath); return 0; } /* * If the file name does not have a .json extension, * ignore it. It could be a readme.txt for instance. */ if (is_file) { if (!is_json_file(bname)) { pr_info("%s: Ignoring file without .json suffix %s\n", prog, fpath); return 0; } } if (level > 1 && add_topic(bname)) return -ENOMEM; /* * Assume all other files are JSON files. * * If mapfile refers to 'power7_core.json', we create a table * named 'power7_core'. Any inconsistencies between the mapfile * and directory tree could result in build failure due to table * names not being found. * * At least for now, be strict with processing JSON file names. * i.e. if JSON file name cannot be mapped to C-style table name, * fail. */ if (is_file) { struct perf_entry_data data = { .topic = get_topic(), .outfp = eventsfp, }; err = json_events(fpath, print_events_table_entry, &data); free(data.topic); } return err; } #ifndef PATH_MAX #define PATH_MAX 4096 #endif /* * Starting in directory 'start_dirname', find the "mapfile.csv" and * the set of JSON files for the architecture 'arch'. * * From each JSON file, create a C-style "PMU events table" from the * JSON file (see struct pmu_event). * * From the mapfile, create a mapping between the CPU revisions and * PMU event tables (see struct pmu_events_map). * * Write out the PMU events tables and the mapping table to pmu-event.c. */ int main(int argc, char *argv[]) { int rc, ret = 0, empty_map = 0; int maxfds; char ldirname[PATH_MAX]; const char *arch; const char *output_file; const char *start_dirname; const char *err_string_ext = ""; struct stat stbuf; prog = basename(argv[0]); if (argc < 4) { pr_err("Usage: %s \n", prog); return 1; } arch = argv[1]; start_dirname = argv[2]; output_file = argv[3]; if (argc > 4) verbose = atoi(argv[4]); eventsfp = fopen(output_file, "w"); if (!eventsfp) { pr_err("%s Unable to create required file %s (%s)\n", prog, output_file, strerror(errno)); return 2; } snprintf(ldirname, sizeof(ldirname), "%s/%s", start_dirname, arch); /* If architecture does not have any event lists, bail out */ if (stat(ldirname, &stbuf) < 0) { pr_info("%s: Arch %s has no PMU event lists\n", prog, arch); empty_map = 1; goto err_close_eventsfp; } /* Include pmu-events.h first */ fprintf(eventsfp, "#include \"pmu-events/pmu-events.h\"\n"); /* * The mapfile allows multiple CPUids to point to the same JSON file, * so, not sure if there is a need for symlinks within the pmu-events * directory. * * For now, treat symlinks of JSON files as regular files and create * separate tables for each symlink (presumably, each symlink refers * to specific version of the CPU). */ maxfds = get_maxfds(); rc = nftw(ldirname, preprocess_arch_std_files, maxfds, 0); if (rc) goto err_processing_std_arch_event_dir; rc = nftw(ldirname, process_one_file, maxfds, 0); if (rc) goto err_processing_dir; sprintf(ldirname, "%s/test", start_dirname); rc = nftw(ldirname, preprocess_arch_std_files, maxfds, 0); if (rc) goto err_processing_std_arch_event_dir; rc = nftw(ldirname, process_one_file, maxfds, 0); if (rc) goto err_processing_dir; if (close_table) print_events_table_suffix(eventsfp); if (!mapfile) { pr_info("%s: No CPU->JSON mapping?\n", prog); empty_map = 1; goto err_close_eventsfp; } rc = process_mapfile(eventsfp, mapfile); if (rc) { pr_info("%s: Error processing mapfile %s\n", prog, mapfile); /* Make build fail */ ret = 1; goto err_close_eventsfp; } rc = process_system_event_tables(eventsfp); fclose(eventsfp); if (rc) { ret = 1; goto err_out; } free_arch_std_events(); free_sys_event_tables(); free(mapfile); return 0; err_processing_std_arch_event_dir: err_string_ext = " for std arch event"; err_processing_dir: if (verbose) { pr_info("%s: Error walking file tree %s%s\n", prog, ldirname, err_string_ext); empty_map = 1; } else if (rc < 0) { ret = 1; } else { empty_map = 1; } err_close_eventsfp: fclose(eventsfp); if (empty_map) create_empty_mapping(output_file); err_out: free_arch_std_events(); free_sys_event_tables(); free(mapfile); return ret; } #include static int -#if defined(__GLIBC__) || defined(__APPLE__) +#if defined(__linux__) || defined(__APPLE__) fts_compare(const FTSENT **a, const FTSENT **b) #else fts_compare(const FTSENT * const *a, const FTSENT * const *b) #endif { return (strcmp((*a)->fts_name, (*b)->fts_name)); } static int nftw_ordered(const char *path, int (*fn)(const char *, const struct stat *, int, struct FTW *), int nfds, int ftwflags) { char * const paths[2] = { (char *)path, NULL }; struct FTW ftw; FTSENT *cur; FTS *ftsp; int error = 0, ftsflags, fnflag, postorder, sverrno; /* XXX - nfds is currently unused */ if (nfds < 1) { errno = EINVAL; return (-1); } ftsflags = FTS_COMFOLLOW; if (!(ftwflags & FTW_CHDIR)) ftsflags |= FTS_NOCHDIR; if (ftwflags & FTW_MOUNT) ftsflags |= FTS_XDEV; if (ftwflags & FTW_PHYS) ftsflags |= FTS_PHYSICAL; else ftsflags |= FTS_LOGICAL; postorder = (ftwflags & FTW_DEPTH) != 0; ftsp = fts_open(paths, ftsflags, fts_compare); if (ftsp == NULL) return (-1); while ((cur = fts_read(ftsp)) != NULL) { switch (cur->fts_info) { case FTS_D: if (postorder) continue; fnflag = FTW_D; break; case FTS_DC: continue; case FTS_DNR: fnflag = FTW_DNR; break; case FTS_DP: if (!postorder) continue; fnflag = FTW_DP; break; case FTS_F: case FTS_DEFAULT: fnflag = FTW_F; break; case FTS_NS: case FTS_NSOK: fnflag = FTW_NS; break; case FTS_SL: fnflag = FTW_SL; break; case FTS_SLNONE: fnflag = FTW_SLN; break; default: error = -1; goto done; } ftw.base = cur->fts_pathlen - cur->fts_namelen; ftw.level = cur->fts_level; error = fn(cur->fts_path, cur->fts_statp, fnflag, &ftw); if (error != 0) break; } done: sverrno = errno; if (fts_close(ftsp) != 0 && error == 0) error = -1; else errno = sverrno; return (error); } diff --git a/tools/build/mk/Makefile.boot b/tools/build/mk/Makefile.boot index 9f63a7499592..b8a5c7780948 100644 --- a/tools/build/mk/Makefile.boot +++ b/tools/build/mk/Makefile.boot @@ -1,100 +1,104 @@ CFLAGS+= -I${WORLDTMP}/legacy/usr/include DPADD+= ${WORLDTMP}/legacy/usr/lib/libegacy.a LDADD+= -legacy LDFLAGS+= -L${WORLDTMP}/legacy/usr/lib .if ${.MAKE.OS} != "FreeBSD" # On MacOS using a non-mac ar will fail the build, similarly on Linux using # nm may not work as expected if the nm for the target architecture comes in # $PATH before a nm that supports the host architecture. # To ensure that host binary compile as expected we use the tools from /usr/bin. AR:= /usr/bin/ar RANLIB:= /usr/bin/ranlib NM:= /usr/bin/nm # Avoid stale dependecy warnings: LIBC:= LIBM:= LIBUTIL:= LIBCPLUSPLUS:= LIBARCHIVE:= LIBPTHREAD:= LIBMD:=${WORLDTMP}/legacy/usr/lib/libmd.a LIBNV:=${WORLDTMP}/legacy/usr/lib/libnv.a LIBSBUF:=${WORLDTMP}/legacy/usr/lib/libsbuf.a LIBY:=${WORLDTMP}/legacy/usr/lib/liby.a LIBL:=${WORLDTMP}/legacy/usr/lib/libl.a LIBROKEN:=${WORLDTMP}/legacy/usr/lib/libroken.a LIBDWARF:=${WORLDTMP}/legacy/usr/lib/libdwarf.a LIBELF:=${WORLDTMP}/legacy/usr/lib/libelf.a LIBZ:=${WORLDTMP}/legacy/usr/lib/libz.a # Add various -Werror flags to catch missing function declarations CFLAGS+= -Werror=implicit-function-declaration -Werror=implicit-int \ -Werror=return-type -Wundef CFLAGS+= -DHAVE_NBTOOL_CONFIG_H=1 # This is needed for code that compiles for pre-C11 C standards CWARNFLAGS.clang+=-Wno-typedef-redefinition # bsd.sys.mk explicitly turns on -Wsystem-headers, but that's extremely # noisy when building on Linux. CWARNFLAGS+= -Wno-system-headers CWARNFLAGS.clang+=-Werror=incompatible-pointer-types-discards-qualifiers # b64_pton and b64_ntop is in libresolv on MacOS and Linux: # TODO: only needed for uuencode and uudecode LDADD+=-lresolv .if ${.MAKE.OS} == "Linux" CFLAGS+= -I${SRCTOP}/tools/build/cross-build/include/linux CFLAGS+= -D_GNU_SOURCE=1 # Needed for sem_init, etc. on Linux (used by usr.bin/sort) LDADD+= -pthread +.if exists(/usr/lib/libfts.so) || exists(/usr/lib/libfts.a) || exists(/lib/libfts.so) || exists(/lib/libfts.a) +# Needed for fts_open, etc. on musl (used by usr.bin/grep) +LDADD+= -lfts +.endif .elif ${.MAKE.OS} == "Darwin" CFLAGS+= -D_DARWIN_C_SOURCE=1 CFLAGS+= -I${SRCTOP}/tools/build/cross-build/include/mac # The macOS ar and ranlib don't understand all the flags supported by the # FreeBSD and Linux ar/ranlib ARFLAGS:= -crs RANLIBFLAGS:= # to get libarchive (needed for elftoolchain) # MacOS ships /usr/lib/libarchive.dylib but doesn't provide the headers CFLAGS+= -idirafter ${SRCTOP}/contrib/libarchive/libarchive .else .error Unsupported build OS: ${.MAKE.OS} .endif .endif # ${.MAKE.OS} != "FreeBSD" .if ${.MAKE.OS} != "FreeBSD" # Add the common compatibility headers after the OS-specific ones. CFLAGS+= -I${SRCTOP}/tools/build/cross-build/include/common .endif # we do not want to capture dependencies referring to the above UPDATE_DEPENDFILE= no # When building host tools we should never pull in headers from the source sys # directory to avoid any ABI issues that might cause the built binary to crash. # The only exceptions to this are sys/cddl/compat for dtrace bootstrap tools and # sys/crypto for libmd bootstrap. # We have to skip this check during make obj since bsd.crunchgen.mk will run # make obj on every directory during the build-tools phase. .if !make(obj) .if !empty(CFLAGS:M*${SRCTOP}/sys) .error Do not include $${SRCTOP}/sys when building bootstrap tools. \ Copy the header to $${WORLDTMP}/legacy in tools/build/Makefile instead. \ Error was caused by Makefile in ${.CURDIR} .endif # ${SRCTOP}/include should also never be used to avoid ABI issues .if !empty(CFLAGS:M*${SRCTOP}/include*) .error Do not include $${SRCTOP}/include when building bootstrap tools. \ Copy the header to $${WORLDTMP}/legacy in tools/build/Makefile instead. \ Error was caused by Makefile in ${.CURDIR} .endif .endif # GCC doesn't allow silencing warn_unused_result calls with (void) casts. CFLAGS.gcc+=-Wno-unused-result diff --git a/usr.sbin/kldxref/kldxref.c b/usr.sbin/kldxref/kldxref.c index c88769ce1824..122551940ac7 100644 --- a/usr.sbin/kldxref/kldxref.c +++ b/usr.sbin/kldxref/kldxref.c @@ -1,852 +1,852 @@ /*- * SPDX-License-Identifier: BSD-4-Clause * * Copyright (c) 2000, Boris Popov * 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 Boris Popov. * 4. Neither the name of the author nor the names of any co-contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * 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 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "ef.h" #define MAXRECSIZE (64 << 10) /* 64k */ #define check(val) if ((error = (val)) != 0) break static bool dflag; /* do not create a hint file, only write on stdout */ static int verbose; static FILE *fxref; /* current hints file */ static int byte_order; static GElf_Ehdr ehdr; static char *ehdr_filename; static const char *xref_file = "linker.hints"; /* * A record is stored in the static buffer recbuf before going to disk. */ static char recbuf[MAXRECSIZE]; static int recpos; /* current write position */ static int reccnt; /* total record written to this file so far */ static void intalign(void) { recpos = roundup2(recpos, sizeof(int)); } static void write_int(int val) { char buf[4]; assert(byte_order != ELFDATANONE); if (byte_order == ELFDATA2LSB) le32enc(buf, val); else be32enc(buf, val); fwrite(buf, sizeof(buf), 1, fxref); } static void record_start(void) { recpos = 0; memset(recbuf, 0, MAXRECSIZE); } static int record_end(void) { if (recpos == 0) { /* * Pretend to have written a record in debug mode so * the architecture check works. */ if (dflag) reccnt++; return (0); } if (reccnt == 0) { /* File version record. */ write_int(1); } reccnt++; intalign(); write_int(recpos); return (fwrite(recbuf, recpos, 1, fxref) != 1 ? errno : 0); } static int record_buf(const void *buf, size_t size) { if (MAXRECSIZE - recpos < size) errx(1, "record buffer overflow"); memcpy(recbuf + recpos, buf, size); recpos += size; return (0); } /* * An int is stored in target byte order and aligned */ static int record_int(int val) { char buf[4]; assert(byte_order != ELFDATANONE); if (byte_order == ELFDATA2LSB) le32enc(buf, val); else be32enc(buf, val); intalign(); return (record_buf(buf, sizeof(buf))); } /* * A string is stored as 1-byte length plus data, no padding */ static int record_string(const char *str) { int error; size_t len; u_char val; if (dflag) return (0); val = len = strlen(str); if (len > 255) errx(1, "string %s too long", str); error = record_buf(&val, sizeof(val)); if (error != 0) return (error); return (record_buf(str, len)); } /* From sys/isa/pnp.c */ static char * pnp_eisaformat(uint32_t id) { uint8_t *data; static char idbuf[8]; const char hextoascii[] = "0123456789abcdef"; id = htole32(id); data = (uint8_t *)&id; idbuf[0] = '@' + ((data[0] & 0x7c) >> 2); idbuf[1] = '@' + (((data[0] & 0x3) << 3) + ((data[1] & 0xe0) >> 5)); idbuf[2] = '@' + (data[1] & 0x1f); idbuf[3] = hextoascii[(data[2] >> 4)]; idbuf[4] = hextoascii[(data[2] & 0xf)]; idbuf[5] = hextoascii[(data[3] >> 4)]; idbuf[6] = hextoascii[(data[3] & 0xf)]; idbuf[7] = 0; return (idbuf); } struct pnp_elt { int pe_kind; /* What kind of entry */ #define TYPE_SZ_MASK 0x0f #define TYPE_FLAGGED 0x10 /* all f's is a wildcard */ #define TYPE_INT 0x20 /* Is a number */ #define TYPE_PAIRED 0x40 #define TYPE_LE 0x80 /* Matches <= this value */ #define TYPE_GE 0x100 /* Matches >= this value */ #define TYPE_MASK 0x200 /* Specifies a mask to follow */ #define TYPE_U8 (1 | TYPE_INT) #define TYPE_V8 (1 | TYPE_INT | TYPE_FLAGGED) #define TYPE_G16 (2 | TYPE_INT | TYPE_GE) #define TYPE_L16 (2 | TYPE_INT | TYPE_LE) #define TYPE_M16 (2 | TYPE_INT | TYPE_MASK) #define TYPE_U16 (2 | TYPE_INT) #define TYPE_V16 (2 | TYPE_INT | TYPE_FLAGGED) #define TYPE_U32 (4 | TYPE_INT) #define TYPE_V32 (4 | TYPE_INT | TYPE_FLAGGED) #define TYPE_W32 (4 | TYPE_INT | TYPE_PAIRED) #define TYPE_D 7 #define TYPE_Z 8 #define TYPE_P 9 #define TYPE_E 10 #define TYPE_T 11 int pe_offset; /* Offset within the element */ char * pe_key; /* pnp key name */ TAILQ_ENTRY(pnp_elt) next; /* Link */ }; typedef TAILQ_HEAD(pnp_head, pnp_elt) pnp_list; /* * this function finds the data from the pnp table, as described by the * description and creates a new output (new_desc). This output table * is a form that's easier for the agent that's automatically loading the * modules. * * The format output is the simplified string from this routine in the * same basic format as the pnp string, as documented in sys/module.h. * First a string describing the format is output, the a count of the * number of records, then each record. The format string also describes * the length of each entry (though it isn't a fixed length when strings * are present). * * type Output Meaning * I uint32_t Integer equality comparison * J uint32_t Pair of uint16_t fields converted to native * byte order. The two fields both must match. * G uint32_t Greater than or equal to * L uint32_t Less than or equal to * M uint32_t Mask of which fields to test. Fields that * take up space increment the count. This * field must be first, and resets the count. * D string Description of the device this pnp info is for * Z string pnp string must match this * T nothing T fields set pnp values that must be true for * the entire table. * Values are packed the same way that other values are packed in this file. * Strings and int32_t's start on a 32-bit boundary and are padded with 0 * bytes. Objects that are smaller than uint32_t are converted, without * sign extension to uint32_t to simplify parsing downstream. */ static int parse_pnp_list(struct elf_file *ef, const char *desc, char **new_desc, pnp_list *list) { const char *walker, *ep; const char *colon, *semi; struct pnp_elt *elt; char type[8], key[32]; int off; size_t new_desc_size; FILE *fp; TAILQ_INIT(list); walker = desc; ep = desc + strlen(desc); off = 0; fp = open_memstream(new_desc, &new_desc_size); if (fp == NULL) err(1, "Could not open new memory stream"); if (verbose > 1) printf("Converting %s into a list\n", desc); while (walker < ep) { colon = strchr(walker, ':'); semi = strchr(walker, ';'); if (semi != NULL && semi < colon) goto err; if (colon - walker > sizeof(type)) goto err; strncpy(type, walker, colon - walker); type[colon - walker] = '\0'; if (semi != NULL) { if (semi - colon >= sizeof(key)) goto err; strncpy(key, colon + 1, semi - colon - 1); key[semi - colon - 1] = '\0'; walker = semi + 1; /* Fail safe if we have spaces after ; */ while (walker < ep && isspace(*walker)) walker++; } else { if (strlen(colon + 1) >= sizeof(key)) goto err; strcpy(key, colon + 1); walker = ep; } if (verbose > 1) printf("Found type %s for name %s\n", type, key); /* Skip pointer place holders */ if (strcmp(type, "P") == 0) { off += elf_pointer_size(ef); continue; } /* * Add a node of the appropriate type */ elt = malloc(sizeof(struct pnp_elt) + strlen(key) + 1); TAILQ_INSERT_TAIL(list, elt, next); elt->pe_key = (char *)(elt + 1); elt->pe_offset = off; if (strcmp(type, "U8") == 0) elt->pe_kind = TYPE_U8; else if (strcmp(type, "V8") == 0) elt->pe_kind = TYPE_V8; else if (strcmp(type, "G16") == 0) elt->pe_kind = TYPE_G16; else if (strcmp(type, "L16") == 0) elt->pe_kind = TYPE_L16; else if (strcmp(type, "M16") == 0) elt->pe_kind = TYPE_M16; else if (strcmp(type, "U16") == 0) elt->pe_kind = TYPE_U16; else if (strcmp(type, "V16") == 0) elt->pe_kind = TYPE_V16; else if (strcmp(type, "U32") == 0) elt->pe_kind = TYPE_U32; else if (strcmp(type, "V32") == 0) elt->pe_kind = TYPE_V32; else if (strcmp(type, "W32") == 0) elt->pe_kind = TYPE_W32; else if (strcmp(type, "D") == 0) /* description char * */ elt->pe_kind = TYPE_D; else if (strcmp(type, "Z") == 0) /* char * to match */ elt->pe_kind = TYPE_Z; else if (strcmp(type, "P") == 0) /* Pointer -- ignored */ elt->pe_kind = TYPE_P; else if (strcmp(type, "E") == 0) /* EISA PNP ID, as uint32_t */ elt->pe_kind = TYPE_E; else if (strcmp(type, "T") == 0) elt->pe_kind = TYPE_T; else goto err; /* * Maybe the rounding here needs to be more nuanced and/or somehow * architecture specific. Fortunately, most tables in the system * have sane ordering of types. */ if (elt->pe_kind & TYPE_INT) { elt->pe_offset = roundup2(elt->pe_offset, elt->pe_kind & TYPE_SZ_MASK); off = elt->pe_offset + (elt->pe_kind & TYPE_SZ_MASK); } else if (elt->pe_kind == TYPE_E) { /* Type E stored as Int, displays as string */ elt->pe_offset = roundup2(elt->pe_offset, sizeof(uint32_t)); off = elt->pe_offset + sizeof(uint32_t); } else if (elt->pe_kind == TYPE_T) { /* doesn't actually consume space in the table */ off = elt->pe_offset; } else { elt->pe_offset = roundup2(elt->pe_offset, elf_pointer_size(ef)); off = elt->pe_offset + elf_pointer_size(ef); } if (elt->pe_kind & TYPE_PAIRED) { char *word, *ctx, newtype; for (word = strtok_r(key, "/", &ctx); word; word = strtok_r(NULL, "/", &ctx)) { newtype = elt->pe_kind & TYPE_FLAGGED ? 'J' : 'I'; fprintf(fp, "%c:%s;", newtype, word); } } else { char newtype; if (elt->pe_kind & TYPE_FLAGGED) newtype = 'J'; else if (elt->pe_kind & TYPE_GE) newtype = 'G'; else if (elt->pe_kind & TYPE_LE) newtype = 'L'; else if (elt->pe_kind & TYPE_MASK) newtype = 'M'; else if (elt->pe_kind & TYPE_INT) newtype = 'I'; else if (elt->pe_kind == TYPE_D) newtype = 'D'; else if (elt->pe_kind == TYPE_Z || elt->pe_kind == TYPE_E) newtype = 'Z'; else if (elt->pe_kind == TYPE_T) newtype = 'T'; else errx(1, "Impossible type %x\n", elt->pe_kind); fprintf(fp, "%c:%s;", newtype, key); } } if (ferror(fp) != 0) { fclose(fp); errx(1, "Exhausted space converting description %s", desc); } if (fclose(fp) != 0) errx(1, "Failed to close memory stream"); return (0); err: errx(1, "Parse error of description string %s", desc); } static void free_pnp_list(char *new_desc, pnp_list *list) { struct pnp_elt *elt, *elt_tmp; TAILQ_FOREACH_SAFE(elt, list, next, elt_tmp) { TAILQ_REMOVE(list, elt, next); free(elt); } free(new_desc); } static uint16_t parse_16(const void *p) { if (byte_order == ELFDATA2LSB) return (le16dec(p)); else return (be16dec(p)); } static uint32_t parse_32(const void *p) { if (byte_order == ELFDATA2LSB) return (le32dec(p)); else return (be32dec(p)); } static void parse_pnp_entry(struct elf_file *ef, struct pnp_elt *elt, const char *walker) { uint8_t v1; uint16_t v2; uint32_t v4; int value; char buffer[1024]; if (elt->pe_kind == TYPE_W32) { v4 = parse_32(walker + elt->pe_offset); value = v4 & 0xffff; record_int(value); if (verbose > 1) printf("W32:%#x", value); value = (v4 >> 16) & 0xffff; record_int(value); if (verbose > 1) printf(":%#x;", value); } else if (elt->pe_kind & TYPE_INT) { switch (elt->pe_kind & TYPE_SZ_MASK) { case 1: memcpy(&v1, walker + elt->pe_offset, sizeof(v1)); if ((elt->pe_kind & TYPE_FLAGGED) && v1 == 0xff) value = -1; else value = v1; break; case 2: v2 = parse_16(walker + elt->pe_offset); if ((elt->pe_kind & TYPE_FLAGGED) && v2 == 0xffff) value = -1; else value = v2; break; case 4: v4 = parse_32(walker + elt->pe_offset); if ((elt->pe_kind & TYPE_FLAGGED) && v4 == 0xffffffff) value = -1; else value = v4; break; default: errx(1, "Invalid size somehow %#x", elt->pe_kind); } if (verbose > 1) printf("I:%#x;", value); record_int(value); } else if (elt->pe_kind == TYPE_T) { /* Do nothing */ } else { /* E, Z or D -- P already filtered */ if (elt->pe_kind == TYPE_E) { v4 = parse_32(walker + elt->pe_offset); strcpy(buffer, pnp_eisaformat(v4)); } else { GElf_Addr address; address = elf_address_from_pointer(ef, walker + elt->pe_offset); buffer[0] = '\0'; if (address != 0) { elf_read_string(ef, address, buffer, sizeof(buffer)); buffer[sizeof(buffer) - 1] = '\0'; } } if (verbose > 1) printf("%c:%s;", elt->pe_kind == TYPE_E ? 'E' : (elt->pe_kind == TYPE_Z ? 'Z' : 'D'), buffer); record_string(buffer); } } static void record_pnp_info(struct elf_file *ef, const char *cval, struct Gmod_pnp_match_info *pnp, const char *descr) { pnp_list list; struct pnp_elt *elt; char *new_descr, *walker; void *table; size_t len; int error, i; if (verbose > 1) printf(" pnp info for bus %s format %s %d entries of %d bytes\n", cval, descr, pnp->num_entry, pnp->entry_len); /* * Parse descr to weed out the chaff and to create a list * of offsets to output. */ parse_pnp_list(ef, descr, &new_descr, &list); record_int(MDT_PNP_INFO); record_string(cval); record_string(new_descr); record_int(pnp->num_entry); len = pnp->num_entry * pnp->entry_len; error = elf_read_relocated_data(ef, pnp->table, len, &table); if (error != 0) { free_pnp_list(new_descr, &list); return; } /* * Walk the list and output things. We've collapsed all the * variant forms of the table down to just ints and strings. */ walker = table; for (i = 0; i < pnp->num_entry; i++) { TAILQ_FOREACH(elt, &list, next) { parse_pnp_entry(ef, elt, walker); } if (verbose > 1) printf("\n"); walker += pnp->entry_len; } /* Now free it */ free_pnp_list(new_descr, &list); free(table); } static int parse_entry(struct Gmod_metadata *md, const char *cval, struct elf_file *ef, const char *kldname) { struct Gmod_depend mdp; struct Gmod_version mdv; struct Gmod_pnp_match_info pnp; char descr[1024]; GElf_Addr data; int error; data = md->md_data; error = 0; record_start(); switch (md->md_type) { case MDT_DEPEND: if (!dflag) break; check(elf_read_mod_depend(ef, data, &mdp)); printf(" depends on %s.%d (%d,%d)\n", cval, mdp.md_ver_preferred, mdp.md_ver_minimum, mdp.md_ver_maximum); break; case MDT_VERSION: check(elf_read_mod_version(ef, data, &mdv)); if (dflag) { printf(" interface %s.%d\n", cval, mdv.mv_version); } else { record_int(MDT_VERSION); record_string(cval); record_int(mdv.mv_version); record_string(kldname); } break; case MDT_MODULE: if (dflag) { printf(" module %s\n", cval); } else { record_int(MDT_MODULE); record_string(cval); record_string(kldname); } break; case MDT_PNP_INFO: check(elf_read_mod_pnp_match_info(ef, data, &pnp)); check(elf_read_string(ef, pnp.descr, descr, sizeof(descr))); if (dflag) { printf(" pnp info for bus %s format %s %d entries of %d bytes\n", cval, descr, pnp.num_entry, pnp.entry_len); } else { record_pnp_info(ef, cval, &pnp, descr); } break; default: warnx("unknown metadata record %d in file %s", md->md_type, kldname); } if (!error) record_end(); return (error); } static int read_kld(char *filename, char *kldname) { struct Gmod_metadata md; struct elf_file ef; GElf_Addr *p; int error; long entries, i; char cval[MAXMODNAME + 1]; if (verbose || dflag) printf("%s\n", filename); error = elf_open_file(&ef, filename, verbose); if (error != 0) return (error); if (reccnt == 0) { ehdr = ef.ef_hdr; byte_order = elf_encoding(&ef); free(ehdr_filename); ehdr_filename = strdup(filename); } else if (!elf_compatible(&ef, &ehdr)) { warnx("%s does not match architecture of %s", filename, ehdr_filename); elf_close_file(&ef); return (EINVAL); } do { check(elf_read_linker_set(&ef, MDT_SETNAME, &p, &entries)); /* * Do a first pass to find MDT_MODULE. It is required to be * ordered first in the output linker.hints stream because it * serves as an implicit record boundary between distinct klds * in the stream. Other MDTs only make sense in the context of * a specific MDT_MODULE. * * Some compilers (e.g., GCC 6.4.0 xtoolchain) or binutils * (e.g., GNU binutils 2.32 objcopy/ld.bfd) can reorder * MODULE_METADATA set entries relative to the source ordering. * This is permitted by the C standard; memory layout of * file-scope objects is left implementation-defined. There is * no requirement that source code ordering is retained. * * Handle that here by taking two passes to ensure MDT_MODULE * records are emitted to linker.hints before other MDT records * in the same kld. */ for (i = 0; i < entries; i++) { check(elf_read_mod_metadata(&ef, p[i], &md)); check(elf_read_string(&ef, md.md_cval, cval, sizeof(cval))); if (md.md_type == MDT_MODULE) { parse_entry(&md, cval, &ef, kldname); break; } } if (error != 0) { free(p); warnc(error, "error while reading %s", filename); break; } /* * Second pass for all !MDT_MODULE entries. */ for (i = 0; i < entries; i++) { check(elf_read_mod_metadata(&ef, p[i], &md)); check(elf_read_string(&ef, md.md_cval, cval, sizeof(cval))); if (md.md_type != MDT_MODULE) parse_entry(&md, cval, &ef, kldname); } if (error != 0) warnc(error, "error while reading %s", filename); free(p); } while(0); elf_close_file(&ef); return (error); } /* * Create a temp file in directory root, make sure we don't * overflow the buffer for the destination name */ static FILE * maketempfile(char *dest, const char *root) { int fd; if (snprintf(dest, MAXPATHLEN, "%s/lhint.XXXXXX", root) >= MAXPATHLEN) { errno = ENAMETOOLONG; return (NULL); } fd = mkstemp(dest); if (fd < 0) return (NULL); fchmod(fd, 0644); /* nothing secret in the file */ return (fdopen(fd, "w+")); } static char xrefname[MAXPATHLEN], tempname[MAXPATHLEN]; static void usage(void) { fprintf(stderr, "%s\n", "usage: kldxref [-Rdv] [-f hintsfile] path ..." ); exit(1); } static int -#if defined(__GLIBC__) || defined(__APPLE__) +#if defined(__linux__) || defined(__APPLE__) compare(const FTSENT **a, const FTSENT **b) #else compare(const FTSENT *const *a, const FTSENT *const *b) #endif { if ((*a)->fts_info == FTS_D && (*b)->fts_info != FTS_D) return (1); if ((*a)->fts_info != FTS_D && (*b)->fts_info == FTS_D) return (-1); return (strcmp((*a)->fts_name, (*b)->fts_name)); } int main(int argc, char *argv[]) { FTS *ftsp; FTSENT *p; char *dot = NULL; int opt, fts_options; struct stat sb; fts_options = FTS_PHYSICAL; while ((opt = getopt(argc, argv, "Rdf:v")) != -1) { switch (opt) { case 'd': /* no hint file, only print on stdout */ dflag = true; break; case 'f': /* use this name instead of linker.hints */ xref_file = optarg; break; case 'v': verbose++; break; case 'R': /* recurse on directories */ fts_options |= FTS_COMFOLLOW; break; default: usage(); /* NOTREACHED */ } } if (argc - optind < 1) usage(); argc -= optind; argv += optind; if (stat(argv[0], &sb) != 0) err(1, "%s", argv[0]); if ((sb.st_mode & S_IFDIR) == 0 && !dflag) { errno = ENOTDIR; err(1, "%s", argv[0]); } if (elf_version(EV_CURRENT) == EV_NONE) errx(1, "unsupported libelf"); ftsp = fts_open(argv, fts_options, compare); if (ftsp == NULL) exit(1); for (;;) { p = fts_read(ftsp); if ((p == NULL || p->fts_info == FTS_D) && fxref) { /* close and rename the current hint file */ fclose(fxref); fxref = NULL; if (reccnt != 0) { rename(tempname, xrefname); } else { /* didn't find any entry, ignore this file */ unlink(tempname); unlink(xrefname); } } if (p == NULL) break; if (p->fts_info == FTS_D && !dflag) { /* visiting a new directory, create a new hint file */ snprintf(xrefname, sizeof(xrefname), "%s/%s", ftsp->fts_path, xref_file); fxref = maketempfile(tempname, ftsp->fts_path); if (fxref == NULL) err(1, "can't create %s", tempname); byte_order = ELFDATANONE; reccnt = 0; } /* skip non-files.. */ if (p->fts_info != FTS_F) continue; /* * Skip files that generate errors like .debug, .symbol and .pkgsave * by generally skipping all files not ending with ".ko" or that have * no dots in the name (like kernel). */ dot = strrchr(p->fts_name, '.'); if (dot != NULL && strcmp(dot, ".ko") != 0) continue; read_kld(p->fts_path, p->fts_name); } fts_close(ftsp); return (0); }