cutils.c 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130
  1. /*
  2. * Simple C functions to supplement the C library
  3. *
  4. * Copyright (c) 2006 Fabrice Bellard
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  19. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. * THE SOFTWARE.
  23. */
  24. #include "qemu/osdep.h"
  25. #include "qemu/host-utils.h"
  26. #include <math.h>
  27. #ifdef __FreeBSD__
  28. #include <sys/sysctl.h>
  29. #include <sys/user.h>
  30. #endif
  31. #ifdef __NetBSD__
  32. #include <sys/sysctl.h>
  33. #endif
  34. #ifdef __HAIKU__
  35. #include <kernel/image.h>
  36. #endif
  37. #ifdef __APPLE__
  38. #include <mach-o/dyld.h>
  39. #endif
  40. #ifdef G_OS_WIN32
  41. #include <pathcch.h>
  42. #include <wchar.h>
  43. #endif
  44. #include "qemu/ctype.h"
  45. #include "qemu/cutils.h"
  46. #include "qemu/error-report.h"
  47. void strpadcpy(char *buf, int buf_size, const char *str, char pad)
  48. {
  49. int len = qemu_strnlen(str, buf_size);
  50. memcpy(buf, str, len);
  51. memset(buf + len, pad, buf_size - len);
  52. }
  53. void pstrcpy(char *buf, int buf_size, const char *str)
  54. {
  55. int c;
  56. char *q = buf;
  57. if (buf_size <= 0)
  58. return;
  59. for(;;) {
  60. c = *str++;
  61. if (c == 0 || q >= buf + buf_size - 1)
  62. break;
  63. *q++ = c;
  64. }
  65. *q = '\0';
  66. }
  67. /* strcat and truncate. */
  68. char *pstrcat(char *buf, int buf_size, const char *s)
  69. {
  70. int len;
  71. len = strlen(buf);
  72. if (len < buf_size)
  73. pstrcpy(buf + len, buf_size - len, s);
  74. return buf;
  75. }
  76. int strstart(const char *str, const char *val, const char **ptr)
  77. {
  78. const char *p, *q;
  79. p = str;
  80. q = val;
  81. while (*q != '\0') {
  82. if (*p != *q)
  83. return 0;
  84. p++;
  85. q++;
  86. }
  87. if (ptr)
  88. *ptr = p;
  89. return 1;
  90. }
  91. int stristart(const char *str, const char *val, const char **ptr)
  92. {
  93. const char *p, *q;
  94. p = str;
  95. q = val;
  96. while (*q != '\0') {
  97. if (qemu_toupper(*p) != qemu_toupper(*q))
  98. return 0;
  99. p++;
  100. q++;
  101. }
  102. if (ptr)
  103. *ptr = p;
  104. return 1;
  105. }
  106. /* XXX: use host strnlen if available ? */
  107. int qemu_strnlen(const char *s, int max_len)
  108. {
  109. int i;
  110. for(i = 0; i < max_len; i++) {
  111. if (s[i] == '\0') {
  112. break;
  113. }
  114. }
  115. return i;
  116. }
  117. char *qemu_strsep(char **input, const char *delim)
  118. {
  119. char *result = *input;
  120. if (result != NULL) {
  121. char *p;
  122. for (p = result; *p != '\0'; p++) {
  123. if (strchr(delim, *p)) {
  124. break;
  125. }
  126. }
  127. if (*p == '\0') {
  128. *input = NULL;
  129. } else {
  130. *p = '\0';
  131. *input = p + 1;
  132. }
  133. }
  134. return result;
  135. }
  136. time_t mktimegm(struct tm *tm)
  137. {
  138. time_t t;
  139. int y = tm->tm_year + 1900, m = tm->tm_mon + 1, d = tm->tm_mday;
  140. if (m < 3) {
  141. m += 12;
  142. y--;
  143. }
  144. t = 86400ULL * (d + (153 * m - 457) / 5 + 365 * y + y / 4 - y / 100 +
  145. y / 400 - 719469);
  146. t += 3600 * tm->tm_hour + 60 * tm->tm_min + tm->tm_sec;
  147. return t;
  148. }
  149. static int64_t suffix_mul(char suffix, int64_t unit)
  150. {
  151. switch (qemu_toupper(suffix)) {
  152. case 'B':
  153. return 1;
  154. case 'K':
  155. return unit;
  156. case 'M':
  157. return unit * unit;
  158. case 'G':
  159. return unit * unit * unit;
  160. case 'T':
  161. return unit * unit * unit * unit;
  162. case 'P':
  163. return unit * unit * unit * unit * unit;
  164. case 'E':
  165. return unit * unit * unit * unit * unit * unit;
  166. }
  167. return -1;
  168. }
  169. /*
  170. * Convert size string to bytes.
  171. *
  172. * The size parsing supports the following syntaxes
  173. * - 12345 - decimal, scale determined by @default_suffix and @unit
  174. * - 12345{bBkKmMgGtTpPeE} - decimal, scale determined by suffix and @unit
  175. * - 12345.678{kKmMgGtTpPeE} - decimal, scale determined by suffix, and
  176. * fractional portion is truncated to byte
  177. * - 0x7fEE - hexadecimal, unit determined by @default_suffix
  178. *
  179. * The following are intentionally not supported
  180. * - hex with scaling suffix, such as 0x20M
  181. * - octal, such as 08
  182. * - fractional hex, such as 0x1.8
  183. * - floating point exponents, such as 1e3
  184. *
  185. * The end pointer will be returned in *end, if not NULL. If there is
  186. * no fraction, the input can be decimal or hexadecimal; if there is a
  187. * fraction, then the input must be decimal and there must be a suffix
  188. * (possibly by @default_suffix) larger than Byte, and the fractional
  189. * portion may suffer from precision loss or rounding. The input must
  190. * be positive.
  191. *
  192. * Return -ERANGE on overflow (with *@end advanced), and -EINVAL on
  193. * other error (with *@end left unchanged).
  194. */
  195. static int do_strtosz(const char *nptr, const char **end,
  196. const char default_suffix, int64_t unit,
  197. uint64_t *result)
  198. {
  199. int retval;
  200. const char *endptr, *f;
  201. unsigned char c;
  202. uint64_t val, valf = 0;
  203. int64_t mul;
  204. /* Parse integral portion as decimal. */
  205. retval = qemu_strtou64(nptr, &endptr, 10, &val);
  206. if (retval) {
  207. goto out;
  208. }
  209. if (memchr(nptr, '-', endptr - nptr) != NULL) {
  210. endptr = nptr;
  211. retval = -EINVAL;
  212. goto out;
  213. }
  214. if (val == 0 && (*endptr == 'x' || *endptr == 'X')) {
  215. /* Input looks like hex; reparse, and insist on no fraction or suffix. */
  216. retval = qemu_strtou64(nptr, &endptr, 16, &val);
  217. if (retval) {
  218. goto out;
  219. }
  220. if (*endptr == '.' || suffix_mul(*endptr, unit) > 0) {
  221. endptr = nptr;
  222. retval = -EINVAL;
  223. goto out;
  224. }
  225. } else if (*endptr == '.') {
  226. /*
  227. * Input looks like a fraction. Make sure even 1.k works
  228. * without fractional digits. If we see an exponent, treat
  229. * the entire input as invalid instead.
  230. */
  231. double fraction;
  232. f = endptr;
  233. retval = qemu_strtod_finite(f, &endptr, &fraction);
  234. if (retval) {
  235. endptr++;
  236. } else if (memchr(f, 'e', endptr - f) || memchr(f, 'E', endptr - f)) {
  237. endptr = nptr;
  238. retval = -EINVAL;
  239. goto out;
  240. } else {
  241. /* Extract into a 64-bit fixed-point fraction. */
  242. valf = (uint64_t)(fraction * 0x1p64);
  243. }
  244. }
  245. c = *endptr;
  246. mul = suffix_mul(c, unit);
  247. if (mul > 0) {
  248. endptr++;
  249. } else {
  250. mul = suffix_mul(default_suffix, unit);
  251. assert(mul > 0);
  252. }
  253. if (mul == 1) {
  254. /* When a fraction is present, a scale is required. */
  255. if (valf != 0) {
  256. endptr = nptr;
  257. retval = -EINVAL;
  258. goto out;
  259. }
  260. } else {
  261. uint64_t valh, tmp;
  262. /* Compute exact result: 64.64 x 64.0 -> 128.64 fixed point */
  263. mulu64(&val, &valh, val, mul);
  264. mulu64(&valf, &tmp, valf, mul);
  265. val += tmp;
  266. valh += val < tmp;
  267. /* Round 0.5 upward. */
  268. tmp = valf >> 63;
  269. val += tmp;
  270. valh += val < tmp;
  271. /* Report overflow. */
  272. if (valh != 0) {
  273. retval = -ERANGE;
  274. goto out;
  275. }
  276. }
  277. retval = 0;
  278. out:
  279. if (end) {
  280. *end = endptr;
  281. } else if (*endptr) {
  282. retval = -EINVAL;
  283. }
  284. if (retval == 0) {
  285. *result = val;
  286. }
  287. return retval;
  288. }
  289. int qemu_strtosz(const char *nptr, const char **end, uint64_t *result)
  290. {
  291. return do_strtosz(nptr, end, 'B', 1024, result);
  292. }
  293. int qemu_strtosz_MiB(const char *nptr, const char **end, uint64_t *result)
  294. {
  295. return do_strtosz(nptr, end, 'M', 1024, result);
  296. }
  297. int qemu_strtosz_metric(const char *nptr, const char **end, uint64_t *result)
  298. {
  299. return do_strtosz(nptr, end, 'B', 1000, result);
  300. }
  301. /**
  302. * Helper function for error checking after strtol() and the like
  303. */
  304. static int check_strtox_error(const char *nptr, char *ep,
  305. const char **endptr, bool check_zero,
  306. int libc_errno)
  307. {
  308. assert(ep >= nptr);
  309. /* Windows has a bug in that it fails to parse 0 from "0x" in base 16 */
  310. if (check_zero && ep == nptr && libc_errno == 0) {
  311. char *tmp;
  312. errno = 0;
  313. if (strtol(nptr, &tmp, 10) == 0 && errno == 0 &&
  314. (*tmp == 'x' || *tmp == 'X')) {
  315. ep = tmp;
  316. }
  317. }
  318. if (endptr) {
  319. *endptr = ep;
  320. }
  321. /* Turn "no conversion" into an error */
  322. if (libc_errno == 0 && ep == nptr) {
  323. return -EINVAL;
  324. }
  325. /* Fail when we're expected to consume the string, but didn't */
  326. if (!endptr && *ep) {
  327. return -EINVAL;
  328. }
  329. return -libc_errno;
  330. }
  331. /**
  332. * Convert string @nptr to an integer, and store it in @result.
  333. *
  334. * This is a wrapper around strtol() that is harder to misuse.
  335. * Semantics of @nptr, @endptr, @base match strtol() with differences
  336. * noted below.
  337. *
  338. * @nptr may be null, and no conversion is performed then.
  339. *
  340. * If no conversion is performed, store @nptr in *@endptr and return
  341. * -EINVAL.
  342. *
  343. * If @endptr is null, and the string isn't fully converted, return
  344. * -EINVAL. This is the case when the pointer that would be stored in
  345. * a non-null @endptr points to a character other than '\0'.
  346. *
  347. * If the conversion overflows @result, store INT_MAX in @result,
  348. * and return -ERANGE.
  349. *
  350. * If the conversion underflows @result, store INT_MIN in @result,
  351. * and return -ERANGE.
  352. *
  353. * Else store the converted value in @result, and return zero.
  354. */
  355. int qemu_strtoi(const char *nptr, const char **endptr, int base,
  356. int *result)
  357. {
  358. char *ep;
  359. long long lresult;
  360. assert((unsigned) base <= 36 && base != 1);
  361. if (!nptr) {
  362. if (endptr) {
  363. *endptr = nptr;
  364. }
  365. return -EINVAL;
  366. }
  367. errno = 0;
  368. lresult = strtoll(nptr, &ep, base);
  369. if (lresult < INT_MIN) {
  370. *result = INT_MIN;
  371. errno = ERANGE;
  372. } else if (lresult > INT_MAX) {
  373. *result = INT_MAX;
  374. errno = ERANGE;
  375. } else {
  376. *result = lresult;
  377. }
  378. return check_strtox_error(nptr, ep, endptr, lresult == 0, errno);
  379. }
  380. /**
  381. * Convert string @nptr to an unsigned integer, and store it in @result.
  382. *
  383. * This is a wrapper around strtoul() that is harder to misuse.
  384. * Semantics of @nptr, @endptr, @base match strtoul() with differences
  385. * noted below.
  386. *
  387. * @nptr may be null, and no conversion is performed then.
  388. *
  389. * If no conversion is performed, store @nptr in *@endptr and return
  390. * -EINVAL.
  391. *
  392. * If @endptr is null, and the string isn't fully converted, return
  393. * -EINVAL. This is the case when the pointer that would be stored in
  394. * a non-null @endptr points to a character other than '\0'.
  395. *
  396. * If the conversion overflows @result, store UINT_MAX in @result,
  397. * and return -ERANGE.
  398. *
  399. * Else store the converted value in @result, and return zero.
  400. *
  401. * Note that a number with a leading minus sign gets converted without
  402. * the minus sign, checked for overflow (see above), then negated (in
  403. * @result's type). This is exactly how strtoul() works.
  404. */
  405. int qemu_strtoui(const char *nptr, const char **endptr, int base,
  406. unsigned int *result)
  407. {
  408. char *ep;
  409. long long lresult;
  410. assert((unsigned) base <= 36 && base != 1);
  411. if (!nptr) {
  412. if (endptr) {
  413. *endptr = nptr;
  414. }
  415. return -EINVAL;
  416. }
  417. errno = 0;
  418. lresult = strtoull(nptr, &ep, base);
  419. /* Windows returns 1 for negative out-of-range values. */
  420. if (errno == ERANGE) {
  421. *result = -1;
  422. } else {
  423. if (lresult > UINT_MAX) {
  424. *result = UINT_MAX;
  425. errno = ERANGE;
  426. } else if (lresult < INT_MIN) {
  427. *result = UINT_MAX;
  428. errno = ERANGE;
  429. } else {
  430. *result = lresult;
  431. }
  432. }
  433. return check_strtox_error(nptr, ep, endptr, lresult == 0, errno);
  434. }
  435. /**
  436. * Convert string @nptr to a long integer, and store it in @result.
  437. *
  438. * This is a wrapper around strtol() that is harder to misuse.
  439. * Semantics of @nptr, @endptr, @base match strtol() with differences
  440. * noted below.
  441. *
  442. * @nptr may be null, and no conversion is performed then.
  443. *
  444. * If no conversion is performed, store @nptr in *@endptr and return
  445. * -EINVAL.
  446. *
  447. * If @endptr is null, and the string isn't fully converted, return
  448. * -EINVAL. This is the case when the pointer that would be stored in
  449. * a non-null @endptr points to a character other than '\0'.
  450. *
  451. * If the conversion overflows @result, store LONG_MAX in @result,
  452. * and return -ERANGE.
  453. *
  454. * If the conversion underflows @result, store LONG_MIN in @result,
  455. * and return -ERANGE.
  456. *
  457. * Else store the converted value in @result, and return zero.
  458. */
  459. int qemu_strtol(const char *nptr, const char **endptr, int base,
  460. long *result)
  461. {
  462. char *ep;
  463. assert((unsigned) base <= 36 && base != 1);
  464. if (!nptr) {
  465. if (endptr) {
  466. *endptr = nptr;
  467. }
  468. return -EINVAL;
  469. }
  470. errno = 0;
  471. *result = strtol(nptr, &ep, base);
  472. return check_strtox_error(nptr, ep, endptr, *result == 0, errno);
  473. }
  474. /**
  475. * Convert string @nptr to an unsigned long, and store it in @result.
  476. *
  477. * This is a wrapper around strtoul() that is harder to misuse.
  478. * Semantics of @nptr, @endptr, @base match strtoul() with differences
  479. * noted below.
  480. *
  481. * @nptr may be null, and no conversion is performed then.
  482. *
  483. * If no conversion is performed, store @nptr in *@endptr and return
  484. * -EINVAL.
  485. *
  486. * If @endptr is null, and the string isn't fully converted, return
  487. * -EINVAL. This is the case when the pointer that would be stored in
  488. * a non-null @endptr points to a character other than '\0'.
  489. *
  490. * If the conversion overflows @result, store ULONG_MAX in @result,
  491. * and return -ERANGE.
  492. *
  493. * Else store the converted value in @result, and return zero.
  494. *
  495. * Note that a number with a leading minus sign gets converted without
  496. * the minus sign, checked for overflow (see above), then negated (in
  497. * @result's type). This is exactly how strtoul() works.
  498. */
  499. int qemu_strtoul(const char *nptr, const char **endptr, int base,
  500. unsigned long *result)
  501. {
  502. char *ep;
  503. assert((unsigned) base <= 36 && base != 1);
  504. if (!nptr) {
  505. if (endptr) {
  506. *endptr = nptr;
  507. }
  508. return -EINVAL;
  509. }
  510. errno = 0;
  511. *result = strtoul(nptr, &ep, base);
  512. /* Windows returns 1 for negative out-of-range values. */
  513. if (errno == ERANGE) {
  514. *result = -1;
  515. }
  516. return check_strtox_error(nptr, ep, endptr, *result == 0, errno);
  517. }
  518. /**
  519. * Convert string @nptr to an int64_t.
  520. *
  521. * Works like qemu_strtol(), except it stores INT64_MAX on overflow,
  522. * and INT64_MIN on underflow.
  523. */
  524. int qemu_strtoi64(const char *nptr, const char **endptr, int base,
  525. int64_t *result)
  526. {
  527. char *ep;
  528. assert((unsigned) base <= 36 && base != 1);
  529. if (!nptr) {
  530. if (endptr) {
  531. *endptr = nptr;
  532. }
  533. return -EINVAL;
  534. }
  535. /* This assumes int64_t is long long TODO relax */
  536. QEMU_BUILD_BUG_ON(sizeof(int64_t) != sizeof(long long));
  537. errno = 0;
  538. *result = strtoll(nptr, &ep, base);
  539. return check_strtox_error(nptr, ep, endptr, *result == 0, errno);
  540. }
  541. /**
  542. * Convert string @nptr to an uint64_t.
  543. *
  544. * Works like qemu_strtoul(), except it stores UINT64_MAX on overflow.
  545. */
  546. int qemu_strtou64(const char *nptr, const char **endptr, int base,
  547. uint64_t *result)
  548. {
  549. char *ep;
  550. assert((unsigned) base <= 36 && base != 1);
  551. if (!nptr) {
  552. if (endptr) {
  553. *endptr = nptr;
  554. }
  555. return -EINVAL;
  556. }
  557. /* This assumes uint64_t is unsigned long long TODO relax */
  558. QEMU_BUILD_BUG_ON(sizeof(uint64_t) != sizeof(unsigned long long));
  559. errno = 0;
  560. *result = strtoull(nptr, &ep, base);
  561. /* Windows returns 1 for negative out-of-range values. */
  562. if (errno == ERANGE) {
  563. *result = -1;
  564. }
  565. return check_strtox_error(nptr, ep, endptr, *result == 0, errno);
  566. }
  567. /**
  568. * Convert string @nptr to a double.
  569. *
  570. * This is a wrapper around strtod() that is harder to misuse.
  571. * Semantics of @nptr and @endptr match strtod() with differences
  572. * noted below.
  573. *
  574. * @nptr may be null, and no conversion is performed then.
  575. *
  576. * If no conversion is performed, store @nptr in *@endptr and return
  577. * -EINVAL.
  578. *
  579. * If @endptr is null, and the string isn't fully converted, return
  580. * -EINVAL. This is the case when the pointer that would be stored in
  581. * a non-null @endptr points to a character other than '\0'.
  582. *
  583. * If the conversion overflows, store +/-HUGE_VAL in @result, depending
  584. * on the sign, and return -ERANGE.
  585. *
  586. * If the conversion underflows, store +/-0.0 in @result, depending on the
  587. * sign, and return -ERANGE.
  588. *
  589. * Else store the converted value in @result, and return zero.
  590. */
  591. int qemu_strtod(const char *nptr, const char **endptr, double *result)
  592. {
  593. char *ep;
  594. if (!nptr) {
  595. if (endptr) {
  596. *endptr = nptr;
  597. }
  598. return -EINVAL;
  599. }
  600. errno = 0;
  601. *result = strtod(nptr, &ep);
  602. return check_strtox_error(nptr, ep, endptr, false, errno);
  603. }
  604. /**
  605. * Convert string @nptr to a finite double.
  606. *
  607. * Works like qemu_strtod(), except that "NaN" and "inf" are rejected
  608. * with -EINVAL and no conversion is performed.
  609. */
  610. int qemu_strtod_finite(const char *nptr, const char **endptr, double *result)
  611. {
  612. double tmp;
  613. int ret;
  614. ret = qemu_strtod(nptr, endptr, &tmp);
  615. if (!ret && !isfinite(tmp)) {
  616. if (endptr) {
  617. *endptr = nptr;
  618. }
  619. ret = -EINVAL;
  620. }
  621. if (ret != -EINVAL) {
  622. *result = tmp;
  623. }
  624. return ret;
  625. }
  626. /**
  627. * Searches for the first occurrence of 'c' in 's', and returns a pointer
  628. * to the trailing null byte if none was found.
  629. */
  630. #ifndef HAVE_STRCHRNUL
  631. const char *qemu_strchrnul(const char *s, int c)
  632. {
  633. const char *e = strchr(s, c);
  634. if (!e) {
  635. e = s + strlen(s);
  636. }
  637. return e;
  638. }
  639. #endif
  640. /**
  641. * parse_uint:
  642. *
  643. * @s: String to parse
  644. * @value: Destination for parsed integer value
  645. * @endptr: Destination for pointer to first character not consumed
  646. * @base: integer base, between 2 and 36 inclusive, or 0
  647. *
  648. * Parse unsigned integer
  649. *
  650. * Parsed syntax is like strtoull()'s: arbitrary whitespace, a single optional
  651. * '+' or '-', an optional "0x" if @base is 0 or 16, one or more digits.
  652. *
  653. * If @s is null, or @base is invalid, or @s doesn't start with an
  654. * integer in the syntax above, set *@value to 0, *@endptr to @s, and
  655. * return -EINVAL.
  656. *
  657. * Set *@endptr to point right beyond the parsed integer (even if the integer
  658. * overflows or is negative, all digits will be parsed and *@endptr will
  659. * point right beyond them).
  660. *
  661. * If the integer is negative, set *@value to 0, and return -ERANGE.
  662. *
  663. * If the integer overflows unsigned long long, set *@value to
  664. * ULLONG_MAX, and return -ERANGE.
  665. *
  666. * Else, set *@value to the parsed integer, and return 0.
  667. */
  668. int parse_uint(const char *s, unsigned long long *value, char **endptr,
  669. int base)
  670. {
  671. int r = 0;
  672. char *endp = (char *)s;
  673. unsigned long long val = 0;
  674. assert((unsigned) base <= 36 && base != 1);
  675. if (!s) {
  676. r = -EINVAL;
  677. goto out;
  678. }
  679. errno = 0;
  680. val = strtoull(s, &endp, base);
  681. if (errno) {
  682. r = -errno;
  683. goto out;
  684. }
  685. if (endp == s) {
  686. r = -EINVAL;
  687. goto out;
  688. }
  689. /* make sure we reject negative numbers: */
  690. while (qemu_isspace(*s)) {
  691. s++;
  692. }
  693. if (*s == '-') {
  694. val = 0;
  695. r = -ERANGE;
  696. goto out;
  697. }
  698. out:
  699. *value = val;
  700. *endptr = endp;
  701. return r;
  702. }
  703. /**
  704. * parse_uint_full:
  705. *
  706. * @s: String to parse
  707. * @value: Destination for parsed integer value
  708. * @base: integer base, between 2 and 36 inclusive, or 0
  709. *
  710. * Parse unsigned integer from entire string
  711. *
  712. * Have the same behavior of parse_uint(), but with an additional check
  713. * for additional data after the parsed number. If extra characters are present
  714. * after the parsed number, the function will return -EINVAL, and *@v will
  715. * be set to 0.
  716. */
  717. int parse_uint_full(const char *s, unsigned long long *value, int base)
  718. {
  719. char *endp;
  720. int r;
  721. r = parse_uint(s, value, &endp, base);
  722. if (r < 0) {
  723. return r;
  724. }
  725. if (*endp) {
  726. *value = 0;
  727. return -EINVAL;
  728. }
  729. return 0;
  730. }
  731. int qemu_parse_fd(const char *param)
  732. {
  733. long fd;
  734. char *endptr;
  735. errno = 0;
  736. fd = strtol(param, &endptr, 10);
  737. if (param == endptr /* no conversion performed */ ||
  738. errno != 0 /* not representable as long; possibly others */ ||
  739. *endptr != '\0' /* final string not empty */ ||
  740. fd < 0 /* invalid as file descriptor */ ||
  741. fd > INT_MAX /* not representable as int */) {
  742. return -1;
  743. }
  744. return fd;
  745. }
  746. /*
  747. * Implementation of ULEB128 (http://en.wikipedia.org/wiki/LEB128)
  748. * Input is limited to 14-bit numbers
  749. */
  750. int uleb128_encode_small(uint8_t *out, uint32_t n)
  751. {
  752. g_assert(n <= 0x3fff);
  753. if (n < 0x80) {
  754. *out = n;
  755. return 1;
  756. } else {
  757. *out++ = (n & 0x7f) | 0x80;
  758. *out = n >> 7;
  759. return 2;
  760. }
  761. }
  762. int uleb128_decode_small(const uint8_t *in, uint32_t *n)
  763. {
  764. if (!(*in & 0x80)) {
  765. *n = *in;
  766. return 1;
  767. } else {
  768. *n = *in++ & 0x7f;
  769. /* we exceed 14 bit number */
  770. if (*in & 0x80) {
  771. return -1;
  772. }
  773. *n |= *in << 7;
  774. return 2;
  775. }
  776. }
  777. /*
  778. * helper to parse debug environment variables
  779. */
  780. int parse_debug_env(const char *name, int max, int initial)
  781. {
  782. char *debug_env = getenv(name);
  783. char *inv = NULL;
  784. long debug;
  785. if (!debug_env) {
  786. return initial;
  787. }
  788. errno = 0;
  789. debug = strtol(debug_env, &inv, 10);
  790. if (inv == debug_env) {
  791. return initial;
  792. }
  793. if (debug < 0 || debug > max || errno != 0) {
  794. warn_report("%s not in [0, %d]", name, max);
  795. return initial;
  796. }
  797. return debug;
  798. }
  799. const char *si_prefix(unsigned int exp10)
  800. {
  801. static const char *prefixes[] = {
  802. "a", "f", "p", "n", "u", "m", "", "K", "M", "G", "T", "P", "E"
  803. };
  804. exp10 += 18;
  805. assert(exp10 % 3 == 0 && exp10 / 3 < ARRAY_SIZE(prefixes));
  806. return prefixes[exp10 / 3];
  807. }
  808. const char *iec_binary_prefix(unsigned int exp2)
  809. {
  810. static const char *prefixes[] = { "", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei" };
  811. assert(exp2 % 10 == 0 && exp2 / 10 < ARRAY_SIZE(prefixes));
  812. return prefixes[exp2 / 10];
  813. }
  814. /*
  815. * Return human readable string for size @val.
  816. * @val can be anything that uint64_t allows (no more than "16 EiB").
  817. * Use IEC binary units like KiB, MiB, and so forth.
  818. * Caller is responsible for passing it to g_free().
  819. */
  820. char *size_to_str(uint64_t val)
  821. {
  822. uint64_t div;
  823. int i;
  824. /*
  825. * The exponent (returned in i) minus one gives us
  826. * floor(log2(val * 1024 / 1000). The correction makes us
  827. * switch to the higher power when the integer part is >= 1000.
  828. * (see e41b509d68afb1f for more info)
  829. */
  830. frexp(val / (1000.0 / 1024.0), &i);
  831. i = (i - 1) / 10 * 10;
  832. div = 1ULL << i;
  833. return g_strdup_printf("%0.3g %sB", (double)val / div, iec_binary_prefix(i));
  834. }
  835. char *freq_to_str(uint64_t freq_hz)
  836. {
  837. double freq = freq_hz;
  838. size_t exp10 = 0;
  839. while (freq >= 1000.0) {
  840. freq /= 1000.0;
  841. exp10 += 3;
  842. }
  843. return g_strdup_printf("%0.3g %sHz", freq, si_prefix(exp10));
  844. }
  845. int qemu_pstrcmp0(const char **str1, const char **str2)
  846. {
  847. return g_strcmp0(*str1, *str2);
  848. }
  849. static inline bool starts_with_prefix(const char *dir)
  850. {
  851. size_t prefix_len = strlen(CONFIG_PREFIX);
  852. return !memcmp(dir, CONFIG_PREFIX, prefix_len) &&
  853. (!dir[prefix_len] || G_IS_DIR_SEPARATOR(dir[prefix_len]));
  854. }
  855. /* Return the next path component in dir, and store its length in *p_len. */
  856. static inline const char *next_component(const char *dir, int *p_len)
  857. {
  858. int len;
  859. while ((*dir && G_IS_DIR_SEPARATOR(*dir)) ||
  860. (*dir == '.' && (G_IS_DIR_SEPARATOR(dir[1]) || dir[1] == '\0'))) {
  861. dir++;
  862. }
  863. len = 0;
  864. while (dir[len] && !G_IS_DIR_SEPARATOR(dir[len])) {
  865. len++;
  866. }
  867. *p_len = len;
  868. return dir;
  869. }
  870. static const char *exec_dir;
  871. void qemu_init_exec_dir(const char *argv0)
  872. {
  873. #ifdef G_OS_WIN32
  874. char *p;
  875. char buf[MAX_PATH];
  876. DWORD len;
  877. if (exec_dir) {
  878. return;
  879. }
  880. len = GetModuleFileName(NULL, buf, sizeof(buf) - 1);
  881. if (len == 0) {
  882. return;
  883. }
  884. buf[len] = 0;
  885. p = buf + len - 1;
  886. while (p != buf && *p != '\\') {
  887. p--;
  888. }
  889. *p = 0;
  890. if (access(buf, R_OK) == 0) {
  891. exec_dir = g_strdup(buf);
  892. } else {
  893. exec_dir = CONFIG_BINDIR;
  894. }
  895. #else
  896. char *p = NULL;
  897. char buf[PATH_MAX];
  898. if (exec_dir) {
  899. return;
  900. }
  901. #if defined(__linux__)
  902. {
  903. int len;
  904. len = readlink("/proc/self/exe", buf, sizeof(buf) - 1);
  905. if (len > 0) {
  906. buf[len] = 0;
  907. p = buf;
  908. }
  909. }
  910. #elif defined(__FreeBSD__) \
  911. || (defined(__NetBSD__) && defined(KERN_PROC_PATHNAME))
  912. {
  913. #if defined(__FreeBSD__)
  914. static int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1};
  915. #else
  916. static int mib[4] = {CTL_KERN, KERN_PROC_ARGS, -1, KERN_PROC_PATHNAME};
  917. #endif
  918. size_t len = sizeof(buf) - 1;
  919. *buf = '\0';
  920. if (!sysctl(mib, ARRAY_SIZE(mib), buf, &len, NULL, 0) &&
  921. *buf) {
  922. buf[sizeof(buf) - 1] = '\0';
  923. p = buf;
  924. }
  925. }
  926. #elif defined(__APPLE__)
  927. {
  928. char fpath[PATH_MAX];
  929. uint32_t len = sizeof(fpath);
  930. if (_NSGetExecutablePath(fpath, &len) == 0) {
  931. p = realpath(fpath, buf);
  932. if (!p) {
  933. return;
  934. }
  935. }
  936. }
  937. #elif defined(__HAIKU__)
  938. {
  939. image_info ii;
  940. int32_t c = 0;
  941. *buf = '\0';
  942. while (get_next_image_info(0, &c, &ii) == B_OK) {
  943. if (ii.type == B_APP_IMAGE) {
  944. strncpy(buf, ii.name, sizeof(buf));
  945. buf[sizeof(buf) - 1] = 0;
  946. p = buf;
  947. break;
  948. }
  949. }
  950. }
  951. #endif
  952. /* If we don't have any way of figuring out the actual executable
  953. location then try argv[0]. */
  954. if (!p && argv0) {
  955. p = realpath(argv0, buf);
  956. }
  957. if (p) {
  958. exec_dir = g_path_get_dirname(p);
  959. } else {
  960. exec_dir = CONFIG_BINDIR;
  961. }
  962. #endif
  963. }
  964. const char *qemu_get_exec_dir(void)
  965. {
  966. return exec_dir;
  967. }
  968. char *get_relocated_path(const char *dir)
  969. {
  970. size_t prefix_len = strlen(CONFIG_PREFIX);
  971. const char *bindir = CONFIG_BINDIR;
  972. const char *exec_dir = qemu_get_exec_dir();
  973. GString *result;
  974. int len_dir, len_bindir;
  975. /* Fail if qemu_init_exec_dir was not called. */
  976. assert(exec_dir[0]);
  977. result = g_string_new(exec_dir);
  978. g_string_append(result, "/qemu-bundle");
  979. if (access(result->str, R_OK) == 0) {
  980. #ifdef G_OS_WIN32
  981. size_t size = mbsrtowcs(NULL, &dir, 0, &(mbstate_t){0}) + 1;
  982. PWSTR wdir = g_new(WCHAR, size);
  983. mbsrtowcs(wdir, &dir, size, &(mbstate_t){0});
  984. PCWSTR wdir_skipped_root;
  985. PathCchSkipRoot(wdir, &wdir_skipped_root);
  986. size = wcsrtombs(NULL, &wdir_skipped_root, 0, &(mbstate_t){0});
  987. char *cursor = result->str + result->len;
  988. g_string_set_size(result, result->len + size);
  989. wcsrtombs(cursor, &wdir_skipped_root, size + 1, &(mbstate_t){0});
  990. g_free(wdir);
  991. #else
  992. g_string_append(result, dir);
  993. #endif
  994. } else if (!starts_with_prefix(dir) || !starts_with_prefix(bindir)) {
  995. g_string_assign(result, dir);
  996. } else {
  997. g_string_assign(result, exec_dir);
  998. /* Advance over common components. */
  999. len_dir = len_bindir = prefix_len;
  1000. do {
  1001. dir += len_dir;
  1002. bindir += len_bindir;
  1003. dir = next_component(dir, &len_dir);
  1004. bindir = next_component(bindir, &len_bindir);
  1005. } while (len_dir && len_dir == len_bindir && !memcmp(dir, bindir, len_dir));
  1006. /* Ascend from bindir to the common prefix with dir. */
  1007. while (len_bindir) {
  1008. bindir += len_bindir;
  1009. g_string_append(result, "/..");
  1010. bindir = next_component(bindir, &len_bindir);
  1011. }
  1012. if (*dir) {
  1013. assert(G_IS_DIR_SEPARATOR(dir[-1]));
  1014. g_string_append(result, dir - 1);
  1015. }
  1016. }
  1017. return g_string_free(result, false);
  1018. }