From 24e337bec5a5b3bc6e7eba6cda818ef5a8b7c625 Mon Sep 17 00:00:00 2001 From: Ryan Moeller Date: Tue, 28 Jul 2020 02:56:26 +0000 Subject: [PATCH] libpmc: Use known pmc_cpuid buffer size Use the existing PMC_CPUID_LEN to size pmc_cpuid in the kernel and various buffers for reading it in libpmc. This avoids some extra syscalls and malloc/frees. While in here, use strlcpy to copy a user-provided cpuid string instead of memcpy, to make sure we terminate the buffer. Reviewed by: mav MFC after: 1 week Sponsored by: iXsystems, Inc. Differential Revision: https://reviews.freebsd.org/D25679 --- lib/libpmc/libpmc_pmu_util.c | 24 +++++++----------------- sys/dev/hwpmc/hwpmc_mod.c | 2 +- 2 files changed, 8 insertions(+), 18 deletions(-) diff --git a/lib/libpmc/libpmc_pmu_util.c b/lib/libpmc/libpmc_pmu_util.c index 11949a3ad3cd..d652573a883f 100644 --- a/lib/libpmc/libpmc_pmu_util.c +++ b/lib/libpmc/libpmc_pmu_util.c @@ -30,6 +30,7 @@ #include #include +#include #include #include #include @@ -89,20 +90,13 @@ static struct pmu_alias pmu_amd_alias_table[] = { static pmu_mfr_t pmu_events_mfr(void) { - char *buf; - size_t s; + char buf[PMC_CPUID_LEN]; + size_t s = sizeof(buf); pmu_mfr_t mfr; - if (sysctlbyname("kern.hwpmc.cpuid", (void *)NULL, &s, + if (sysctlbyname("kern.hwpmc.cpuid", buf, &s, (void *)NULL, 0) == -1) return (PMU_INVALID); - if ((buf = malloc(s + 1)) == NULL) - return (PMU_INVALID); - if (sysctlbyname("kern.hwpmc.cpuid", buf, &s, - (void *)NULL, 0) == -1) { - free(buf); - return (PMU_INVALID); - } if (strcasestr(buf, "AuthenticAMD") != NULL || strcasestr(buf, "HygonGenuine") != NULL) mfr = PMU_AMD; @@ -110,7 +104,6 @@ pmu_events_mfr(void) mfr = PMU_INTEL; else mfr = PMU_INVALID; - free(buf); return (mfr); } @@ -169,17 +162,14 @@ pmu_events_map_get(const char *cpuid) { regex_t re; regmatch_t pmatch[1]; - size_t s; - char buf[64]; + char buf[PMC_CPUID_LEN]; + size_t s = sizeof(buf); int match; const struct pmu_events_map *pme; if (cpuid != NULL) { - memcpy(buf, cpuid, 64); + strlcpy(buf, cpuid, s); } else { - if (sysctlbyname("kern.hwpmc.cpuid", (void *)NULL, &s, - (void *)NULL, 0) == -1) - return (NULL); if (sysctlbyname("kern.hwpmc.cpuid", buf, &s, (void *)NULL, 0) == -1) return (NULL); diff --git a/sys/dev/hwpmc/hwpmc_mod.c b/sys/dev/hwpmc/hwpmc_mod.c index df7400f73528..d343bdced22d 100644 --- a/sys/dev/hwpmc/hwpmc_mod.c +++ b/sys/dev/hwpmc/hwpmc_mod.c @@ -305,7 +305,7 @@ static int pmc_callchaindepth = PMC_CALLCHAIN_DEPTH; SYSCTL_INT(_kern_hwpmc, OID_AUTO, callchaindepth, CTLFLAG_RDTUN, &pmc_callchaindepth, 0, "depth of call chain records"); -char pmc_cpuid[64]; +char pmc_cpuid[PMC_CPUID_LEN]; SYSCTL_STRING(_kern_hwpmc, OID_AUTO, cpuid, CTLFLAG_RD, pmc_cpuid, 0, "cpu version string"); #ifdef HWPMC_DEBUG