misc.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. #include "toolkit.h"
  2. #include "core.h"
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #include <net/if.h>
  6. #include <stdint.h>
  7. #include <time.h>
  8. #include "dbgutil.h"
  9. #include <sys/time.h>
  10. #include <sys/resource.h>
  11. #define HAVE_IFADDRS_H 1
  12. # include <ifaddrs.h>
  13. # include <sys/socket.h>
  14. # include <net/ethernet.h>
  15. # include <netpacket/packet.h>
  16. #undef NANOSEC
  17. #define NANOSEC ((uint64_t) 1e9)
  18. extern char** environ;
  19. static int read_models(unsigned int numcpus, toolkit_cpu_info_t* ci);
  20. static int read_times(FILE* statfile_fp,
  21. unsigned int numcpus,
  22. toolkit_cpu_info_t* ci);
  23. static void read_speeds(unsigned int numcpus, toolkit_cpu_info_t* ci);
  24. static uint64_t read_cpufreq(unsigned int cpunum);
  25. int toolkit_translate_sys_error(int sys_errno)
  26. {
  27. return sys_errno <= 0 ? sys_errno : -sys_errno;
  28. }
  29. int toolkit_environ(toolkit_env_item_t** envitems, int* count)
  30. {
  31. int i, j, cnt;
  32. toolkit_env_item_t* envitem;
  33. *envitems = NULL;
  34. *count = 0;
  35. for (i = 0; environ[i] != NULL; i++);
  36. *envitems = ZCALLOC(i, sizeof(**envitems));
  37. if (envitems == NULL)
  38. return TOOLKIT_ENOMEM;
  39. for (j = 0, cnt = 0; j < i; j++) {
  40. char* buf;
  41. char* ptr;
  42. if (environ[j] == NULL)
  43. break;
  44. buf = STRDUP(environ[j]);
  45. if (buf == NULL)
  46. goto fail;
  47. ptr = strchr(buf, '=');
  48. if (ptr == NULL) {
  49. FREE(buf);
  50. continue;
  51. }
  52. *ptr = '\0';
  53. envitem = &(*envitems)[cnt];
  54. envitem->name = buf;
  55. envitem->value = ptr + 1;
  56. cnt++;
  57. }
  58. *count = cnt;
  59. return 0;
  60. fail:
  61. for (i = 0; i < cnt; i++) {
  62. envitem = &(*envitems)[cnt];
  63. FREE(envitem->name);
  64. }
  65. FREE(*envitems);
  66. *envitems = NULL;
  67. *count = 0;
  68. return TOOLKIT_ENOMEM;
  69. }
  70. int toolkit_getenv(const char* name, char* buffer, size_t* size)
  71. {
  72. char* var;
  73. size_t len;
  74. if (name == NULL || buffer == NULL || size == NULL || *size == 0)
  75. return TOOLKIT_EINVAL;
  76. var = getenv(name);
  77. if (var == NULL)
  78. return TOOLKIT_ENOENT;
  79. len = strlen(var);
  80. if (len >= *size) {
  81. *size = len + 1;
  82. return TOOLKIT_ENOBUFS;
  83. }
  84. memcpy(buffer, var, len + 1);
  85. *size = len;
  86. return 0;
  87. }
  88. int toolkit_setenv(const char* name, const char* value)
  89. {
  90. if (name == NULL || value == NULL)
  91. return TOOLKIT_EINVAL;
  92. if (setenv(name, value, 1) != 0)
  93. return TOOLKIT__ERR(errno);
  94. return 0;
  95. }
  96. int toolkit_unsetenv(const char* name) {
  97. if (name == NULL)
  98. return TOOLKIT_EINVAL;
  99. if (unsetenv(name) != 0)
  100. return TOOLKIT__ERR(errno);
  101. return 0;
  102. }
  103. uint64_t toolkit__hrtime()
  104. {
  105. struct timespec ts;
  106. clock_gettime(CLOCK_MONOTONIC, &ts);
  107. return (((uint64_t)ts.tv_sec) * NANOSEC + ts.tv_nsec);
  108. }
  109. uint64_t toolkit_hrtime(void)
  110. {
  111. return toolkit__hrtime();
  112. }
  113. static int toolkit__cpu_num(FILE* statfile_fp, unsigned int* numcpus)
  114. {
  115. unsigned int num;
  116. char buf[1024];
  117. if (!fgets(buf, sizeof(buf), statfile_fp))
  118. return TOOLKIT_EIO;
  119. num = 0;
  120. while (fgets(buf, sizeof(buf), statfile_fp)) {
  121. if (strncmp(buf, "cpu", 3))
  122. break;
  123. num++;
  124. }
  125. if (num == 0)
  126. return TOOLKIT_EIO;
  127. *numcpus = num;
  128. return 0;
  129. }
  130. int toolkit_cpu_info(toolkit_cpu_info_t** cpu_infos, int* count)
  131. {
  132. unsigned int numcpus;
  133. toolkit_cpu_info_t* ci;
  134. int err;
  135. FILE* statfile_fp;
  136. *cpu_infos = NULL;
  137. *count = 0;
  138. statfile_fp = toolkit__open_file("/proc/stat");
  139. if (statfile_fp == NULL)
  140. return TOOLKIT__ERR(errno);
  141. err = toolkit__cpu_num(statfile_fp, &numcpus);
  142. if (err < 0)
  143. goto out;
  144. err = TOOLKIT_ENOMEM;
  145. ci = ZCALLOC(numcpus, sizeof(*ci));
  146. if (ci == NULL)
  147. goto out;
  148. err = read_models(numcpus, ci);
  149. if (err == 0)
  150. err = read_times(statfile_fp, numcpus, ci);
  151. if (err) {
  152. toolkit_free_cpu_info(ci, numcpus);
  153. goto out;
  154. }
  155. /* read_models() on x86 also reads the CPU speed from /proc/cpuinfo.
  156. * We don't check for errors here. Worst case, the field is left zero.
  157. */
  158. if (ci[0].speed == 0)
  159. read_speeds(numcpus, ci);
  160. *cpu_infos = ci;
  161. *count = numcpus;
  162. err = 0;
  163. out:
  164. if (fclose(statfile_fp))
  165. if (errno != EINTR && errno != EINPROGRESS)
  166. abort();
  167. return err;
  168. }
  169. static void read_speeds(unsigned int numcpus, toolkit_cpu_info_t* ci)
  170. {
  171. unsigned int num;
  172. for (num = 0; num < numcpus; num++)
  173. ci[num].speed = read_cpufreq(num) / 1000;
  174. }
  175. /* Also reads the CPU frequency on x86. The other architectures only have
  176. * a BogoMIPS field, which may not be very accurate.
  177. *
  178. * Note: Simply returns on error, toolkit_cpu_info() takes care of the cleanup.
  179. */
  180. static int read_models(unsigned int numcpus, toolkit_cpu_info_t* ci)
  181. {
  182. static const char model_marker[] = "model name\t: ";
  183. static const char speed_marker[] = "cpu MHz\t\t: ";
  184. const char* inferred_model;
  185. unsigned int model_idx;
  186. unsigned int speed_idx;
  187. char buf[1024];
  188. char* model;
  189. FILE* fp;
  190. /* Most are unused on non-ARM, non-MIPS and non-x86 architectures. */
  191. (void)&model_marker;
  192. (void)&speed_marker;
  193. (void)&speed_idx;
  194. (void)&model;
  195. (void)&buf;
  196. (void)&fp;
  197. model_idx = 0;
  198. speed_idx = 0;
  199. #if defined(__arm__) || \
  200. defined(__i386__) || \
  201. defined(__mips__) || \
  202. defined(__x86_64__)
  203. fp = toolkit__open_file("/proc/cpuinfo");
  204. if (fp == NULL)
  205. return TOOLKIT__ERR(errno);
  206. while (fgets(buf, sizeof(buf), fp)) {
  207. if (model_idx < numcpus) {
  208. if (strncmp(buf, model_marker, sizeof(model_marker) - 1) == 0) {
  209. model = buf + sizeof(model_marker) - 1;
  210. model = toolkit_strndup(model, strlen(model) - 1); /* Strip newline. */
  211. if (model == NULL) {
  212. fclose(fp);
  213. return TOOLKIT_ENOMEM;
  214. }
  215. ci[model_idx++].model = model;
  216. continue;
  217. }
  218. }
  219. #if defined(__arm__) || defined(__mips__)
  220. if (model_idx < numcpus) {
  221. #if defined(__arm__)
  222. /* Fallback for pre-3.8 kernels. */
  223. static const char model_marker[] = "Processor\t: ";
  224. #else /* defined(__mips__) */
  225. static const char model_marker[] = "cpu model\t\t: ";
  226. #endif
  227. if (strncmp(buf, model_marker, sizeof(model_marker) - 1) == 0) {
  228. model = buf + sizeof(model_marker) - 1;
  229. model = toolkit_strndup(model, strlen(model) - 1); /* Strip newline. */
  230. if (model == NULL) {
  231. fclose(fp);
  232. return TOOLKIT_ENOMEM;
  233. }
  234. ci[model_idx++].model = model;
  235. continue;
  236. }
  237. }
  238. #else /* !__arm__ && !__mips__ */
  239. if (speed_idx < numcpus) {
  240. if (strncmp(buf, speed_marker, sizeof(speed_marker) - 1) == 0) {
  241. ci[speed_idx++].speed = atoi(buf + sizeof(speed_marker) - 1);
  242. continue;
  243. }
  244. }
  245. #endif /* __arm__ || __mips__ */
  246. }
  247. fclose(fp);
  248. #endif /* __arm__ || __i386__ || __mips__ || __x86_64__ */
  249. /* Now we want to make sure that all the models contain *something* because
  250. * it's not safe to leave them as null. Copy the last entry unless there
  251. * isn't one, in that case we simply put "unknown" into everything.
  252. */
  253. inferred_model = "unknown";
  254. if (model_idx > 0)
  255. inferred_model = ci[model_idx - 1].model;
  256. while (model_idx < numcpus) {
  257. model = toolkit_strndup(inferred_model, strlen(inferred_model));
  258. if (model == NULL)
  259. return TOOLKIT_ENOMEM;
  260. ci[model_idx++].model = model;
  261. }
  262. return 0;
  263. }
  264. static int read_times(FILE* statfile_fp,
  265. unsigned int numcpus,
  266. toolkit_cpu_info_t* ci)
  267. {
  268. struct toolkit_cpu_times_s ts;
  269. uint64_t clock_ticks;
  270. uint64_t user;
  271. uint64_t nice;
  272. uint64_t sys;
  273. uint64_t idle;
  274. uint64_t dummy;
  275. uint64_t irq;
  276. uint64_t num;
  277. uint64_t len;
  278. char buf[1024];
  279. clock_ticks = sysconf(_SC_CLK_TCK);
  280. TOOLKIT_ASSERT(clock_ticks != (uint64_t)-1);
  281. TOOLKIT_ASSERT(clock_ticks != 0);
  282. rewind(statfile_fp);
  283. if (!fgets(buf, sizeof(buf), statfile_fp))
  284. abort();
  285. num = 0;
  286. while (fgets(buf, sizeof(buf), statfile_fp)) {
  287. if (num >= numcpus)
  288. break;
  289. if (strncmp(buf, "cpu", 3))
  290. break;
  291. /* skip "cpu<num> " marker */
  292. {
  293. unsigned int n;
  294. int r = sscanf(buf, "cpu%u ", &n);
  295. TOOLKIT_ASSERT(r == 1);
  296. (void)r; /* silence build warning */
  297. for (len = sizeof("cpu0"); n /= 10; len++);
  298. }
  299. /* Line contains user, nice, system, idle, iowait, irq, softirq, steal,
  300. * guest, guest_nice but we're only interested in the first four + irq.
  301. *
  302. * Don't use %*s to skip fields or %ll to read straight into the uint64_t
  303. * fields, they're not allowed in C89 mode.
  304. */
  305. if (6 != sscanf(buf + len,
  306. "%" PRIu64 " %" PRIu64 " %" PRIu64
  307. "%" PRIu64 " %" PRIu64 " %" PRIu64,
  308. &user,
  309. &nice,
  310. &sys,
  311. &idle,
  312. &dummy,
  313. &irq))
  314. abort();
  315. ts.user = clock_ticks * user;
  316. ts.nice = clock_ticks * nice;
  317. ts.sys = clock_ticks * sys;
  318. ts.idle = clock_ticks * idle;
  319. ts.irq = clock_ticks * irq;
  320. ci[num++].cpu_times = ts;
  321. }
  322. TOOLKIT_ASSERT(num == numcpus);
  323. return 0;
  324. }
  325. static uint64_t read_cpufreq(unsigned int cpunum)
  326. {
  327. uint64_t val;
  328. char buf[1024];
  329. FILE* fp;
  330. snprintf(buf,
  331. sizeof(buf),
  332. "/sys/devices/system/cpu/cpu%u/cpufreq/scaling_cur_freq",
  333. cpunum);
  334. fp = toolkit__open_file(buf);
  335. if (fp == NULL)
  336. return 0;
  337. if (fscanf(fp, "%" PRIu64, &val) != 1)
  338. val = 0;
  339. fclose(fp);
  340. return val;
  341. }
  342. static int toolkit__ifaddr_exclude(struct ifaddrs* ent, int exclude_type)
  343. {
  344. if (!((ent->ifa_flags & IFF_UP) && (ent->ifa_flags & IFF_RUNNING)))
  345. return 1;
  346. if (ent->ifa_addr == NULL)
  347. return 1;
  348. /*
  349. * On Linux getifaddrs returns information related to the raw underlying
  350. * devices. We're not interested in this information yet.
  351. */
  352. if (ent->ifa_addr->sa_family == PF_PACKET)
  353. return exclude_type;
  354. return !exclude_type;
  355. }
  356. int toolkit_interface_addresses(toolkit_interface_address_t** addresses, int* count)
  357. {
  358. #ifndef HAVE_IFADDRS_H
  359. * count = 0;
  360. *addresses = NULL;
  361. return TOOLKIT_ENOSYS;
  362. #else
  363. struct ifaddrs* addrs, * ent;
  364. toolkit_interface_address_t* address;
  365. int i;
  366. struct sockaddr_ll* sll;
  367. *count = 0;
  368. *addresses = NULL;
  369. if (getifaddrs(&addrs))
  370. return TOOLKIT__ERR(errno);
  371. /* Count the number of interfaces */
  372. for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
  373. if (toolkit__ifaddr_exclude(ent, TOOLKIT__EXCLUDE_IFADDR))
  374. continue;
  375. (*count)++;
  376. }
  377. if (*count == 0) {
  378. freeifaddrs(addrs);
  379. return 0;
  380. }
  381. /* Make sure the memory is initiallized to zero using calloc() */
  382. *addresses = toolkit_calloc(*count, sizeof(**addresses));
  383. if (!(*addresses)) {
  384. freeifaddrs(addrs);
  385. return TOOLKIT_ENOMEM;
  386. }
  387. address = *addresses;
  388. for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
  389. if (toolkit__ifaddr_exclude(ent, TOOLKIT__EXCLUDE_IFADDR))
  390. continue;
  391. address->name = toolkit_strdup(ent->ifa_name);
  392. if (ent->ifa_addr->sa_family == AF_INET6) {
  393. address->address.address6 = *((struct sockaddr_in6*)ent->ifa_addr);
  394. } else {
  395. address->address.address4 = *((struct sockaddr_in*)ent->ifa_addr);
  396. }
  397. if (ent->ifa_netmask->sa_family == AF_INET6) {
  398. address->netmask.netmask6 = *((struct sockaddr_in6*)ent->ifa_netmask);
  399. } else {
  400. address->netmask.netmask4 = *((struct sockaddr_in*)ent->ifa_netmask);
  401. }
  402. address->is_internal = !!(ent->ifa_flags & IFF_LOOPBACK);
  403. address++;
  404. }
  405. /* Fill in physical addresses for each interface */
  406. for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
  407. if (toolkit__ifaddr_exclude(ent, TOOLKIT__EXCLUDE_IFPHYS))
  408. continue;
  409. address = *addresses;
  410. for (i = 0; i < (*count); i++) {
  411. size_t namelen = strlen(ent->ifa_name);
  412. /* Alias interface share the same physical address */
  413. if (strncmp(address->name, ent->ifa_name, namelen) == 0 &&
  414. (address->name[namelen] == 0 || address->name[namelen] == ':')) {
  415. sll = (struct sockaddr_ll*)ent->ifa_addr;
  416. memcpy(address->phys_addr, sll->sll_addr, sizeof(address->phys_addr));
  417. }
  418. address++;
  419. }
  420. }
  421. freeifaddrs(addrs);
  422. return 0;
  423. #endif
  424. }
  425. void toolkit_free_interface_addresses(toolkit_interface_address_t* addresses,
  426. int count)
  427. {
  428. int i;
  429. for (i = 0; i < count; i++) {
  430. FREE(addresses[i].name);
  431. }
  432. FREE(addresses);
  433. }
  434. void toolkit_sleep(int msec)
  435. {
  436. int sec;
  437. int usec;
  438. sec = msec / 1000;
  439. usec = (msec % 1000) * 1000;
  440. if (sec > 0)
  441. sleep(sec);
  442. if (usec > 0)
  443. usleep(usec);
  444. }
  445. int toolkit_os_getpriority(toolkit_pid_t pid, int* priority)
  446. {
  447. int r;
  448. if (priority == NULL)
  449. return TOOLKIT_EINVAL;
  450. errno = 0;
  451. r = getpriority(PRIO_PROCESS, (int)pid);
  452. if (r == -1 && errno != 0)
  453. return TOOLKIT__ERR(errno);
  454. *priority = r;
  455. return 0;
  456. }
  457. int toolkit_os_setpriority(toolkit_pid_t pid, int priority)
  458. {
  459. if (priority < TOOLKIT_PRIORITY_HIGHEST || priority > TOOLKIT_PRIORITY_LOW)
  460. return TOOLKIT_EINVAL;
  461. if (setpriority(PRIO_PROCESS, (int)pid, priority) != 0)
  462. return TOOLKIT__ERR(errno);
  463. return 0;
  464. }