util.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  1. /*
  2. * Copyright 2013-2015 Luke Dashjr
  3. * Copyright 2012-2014 Con Kolivas
  4. * Copyright 2011 Andrew Smith
  5. * Copyright 2011 Jeff Garzik
  6. *
  7. * This program is free software; you can redistribute it and/or modify it
  8. * under the terms of the GNU General Public License as published by the Free
  9. * Software Foundation; either version 3 of the License, or (at your option)
  10. * any later version. See COPYING for more details.
  11. */
  12. #ifndef BFG_UTIL_H
  13. #define BFG_UTIL_H
  14. #include <stdbool.h>
  15. #include <stdint.h>
  16. #include <string.h>
  17. #include <sys/time.h>
  18. #include <curl/curl.h>
  19. #include <jansson.h>
  20. #include "compat.h"
  21. #define INVALID_TIMESTAMP ((time_t)-1)
  22. #if defined(unix) || defined(__APPLE__)
  23. #include <errno.h>
  24. #include <sys/types.h>
  25. #include <sys/socket.h>
  26. #include <netinet/in.h>
  27. #include <arpa/inet.h>
  28. #define SOCKETTYPE int
  29. #define SOCKETFAIL(a) ((a) < 0)
  30. #define INVSOCK -1
  31. #define INVINETADDR -1
  32. #define CLOSESOCKET close
  33. #define SOCKERR (errno)
  34. #define SOCKERRMSG bfg_strerror(errno, BST_SOCKET)
  35. static inline bool sock_blocks(void)
  36. {
  37. return (errno == EAGAIN || errno == EWOULDBLOCK);
  38. }
  39. static inline bool interrupted(void)
  40. {
  41. return (errno == EINTR);
  42. }
  43. #elif defined WIN32
  44. #include <ws2tcpip.h>
  45. #include <winsock2.h>
  46. #define SOCKETTYPE SOCKET
  47. #define SOCKETFAIL(a) ((int)(a) == SOCKET_ERROR)
  48. #define INVSOCK INVALID_SOCKET
  49. #define INVINETADDR INADDR_NONE
  50. #define CLOSESOCKET closesocket
  51. #define SOCKERR (WSAGetLastError())
  52. #define SOCKERRMSG bfg_strerror(WSAGetLastError(), BST_SOCKET)
  53. /* Check for windows variants of the errors as well as when ming
  54. * decides to wrap the error into the errno equivalent. */
  55. static inline bool sock_blocks(void)
  56. {
  57. return (WSAGetLastError() == WSAEWOULDBLOCK || errno == EAGAIN);
  58. }
  59. static inline bool interrupted(void)
  60. {
  61. return (WSAGetLastError() == WSAEINTR || errno == EINTR);
  62. }
  63. #ifndef SHUT_RDWR
  64. #define SHUT_RDWR SD_BOTH
  65. #endif
  66. #ifndef in_addr_t
  67. #define in_addr_t uint32_t
  68. #endif
  69. #endif
  70. #define IGNORE_RETURN_VALUE(expr) {if(expr);}(void)0
  71. enum bfg_tristate {
  72. BTS_FALSE = (int)false,
  73. BTS_TRUE = (int)true,
  74. BTS_UNKNOWN,
  75. };
  76. #if JANSSON_MAJOR_VERSION >= 2
  77. #define JSON_LOADS(str, err_ptr) json_loads((str), 0, (err_ptr))
  78. #else
  79. #define JSON_LOADS(str, err_ptr) json_loads((str), (err_ptr))
  80. #endif
  81. extern char *json_dumps_ANY(json_t *, size_t flags);
  82. static inline
  83. const char *bfg_json_obj_string(json_t *json, const char *key, const char *fail)
  84. {
  85. json = json_object_get(json, key);
  86. if (!json)
  87. return fail;
  88. return json_string_value(json) ?: fail;
  89. }
  90. extern const char *__json_array_string(json_t *, unsigned int entry);
  91. #define MAX_STR_UINT(type) ((sizeof(type) * CHAR_BIT + 2) / 3)
  92. #ifndef min
  93. # define min(a, b) ((a) < (b) ? (a) : (b))
  94. #endif
  95. extern void *my_memrchr(const void *, int, size_t);
  96. extern bool isCalpha(int);
  97. static inline
  98. bool isCspace(int c)
  99. {
  100. switch (c)
  101. {
  102. case ' ': case '\f': case '\n': case '\r': case '\t': case '\v':
  103. return true;
  104. default:
  105. return false;
  106. }
  107. }
  108. extern bool match_strtok(const char *optlist, const char *delim, const char *needle);
  109. typedef bool (*appdata_file_callback_t)(const char *, void *);
  110. extern bool appdata_file_call(const char *appname, const char *filename, appdata_file_callback_t, void *userp);
  111. extern char *appdata_file_find_first(const char *appname, const char *filename);
  112. extern const char *get_registered_domain(size_t *out_len, const char *, size_t len);
  113. extern const char *extract_domain(size_t *out_len, const char *uri, size_t urilen);
  114. extern bool match_domains(const char *a, size_t alen, const char *b, size_t blen);
  115. extern void test_domain_funcs();
  116. extern bool bfg_strtobool(const char *, char **endptr, int opts);
  117. extern enum bfg_tristate uri_get_param_bool2(const char *ri, const char *param);
  118. extern bool uri_get_param_bool(const char *uri, const char *param, bool defval);
  119. extern void test_uri_get_param();
  120. enum bfg_gpio_value {
  121. BGV_LOW = 0,
  122. BGV_HIGH = 1,
  123. BGV_ERROR = -1,
  124. };
  125. typedef struct timeval cgtimer_t;
  126. struct thr_info;
  127. struct pool;
  128. enum dev_reason;
  129. struct cgpu_info;
  130. extern void set_cloexec_socket(SOCKETTYPE, bool cloexec);
  131. static inline
  132. SOCKETTYPE bfg_socket(const int domain, const int type, const int protocol)
  133. {
  134. const bool cloexec = true;
  135. SOCKETTYPE sock;
  136. #ifdef WIN32
  137. # ifndef WSA_FLAG_NO_HANDLE_INHERIT
  138. # define WSA_FLAG_NO_HANDLE_INHERIT 0x80
  139. # endif
  140. sock = WSASocket(domain, type, protocol, NULL, 0, WSA_FLAG_OVERLAPPED | ((cloexec) ? WSA_FLAG_NO_HANDLE_INHERIT : 0));
  141. if (sock == INVSOCK)
  142. #endif
  143. sock = socket(domain, type, protocol);
  144. if (sock == INVSOCK)
  145. return INVSOCK;
  146. set_cloexec_socket(sock, cloexec);
  147. return sock;
  148. }
  149. extern void json_rpc_call_async(CURL *, const char *url, const char *userpass, const char *rpc_req, bool longpoll, struct pool *pool, bool share, void *priv);
  150. extern json_t *json_rpc_call_completed(CURL *, int rc, bool probe, int *rolltime, void *out_priv);
  151. extern char *absolute_uri(char *uri, const char *ref); // ref must be a root URI
  152. extern size_t ucs2_to_utf8(char *out, const uint16_t *in, size_t sz);
  153. extern char *ucs2_to_utf8_dup(uint16_t *in, size_t sz);
  154. #define BFGINIT(var, val) do{ \
  155. if (!(var)) \
  156. (var) = val; \
  157. }while(0)
  158. extern void gen_hash(unsigned char *data, unsigned char *hash, int len);
  159. extern void real_block_target(unsigned char *target, const unsigned char *data);
  160. extern bool hash_target_check(const unsigned char *hash, const unsigned char *target);
  161. extern bool hash_target_check_v(const unsigned char *hash, const unsigned char *target);
  162. int thr_info_create(struct thr_info *thr, pthread_attr_t *attr, void *(*start) (void *), void *arg);
  163. void thr_info_freeze(struct thr_info *thr);
  164. void thr_info_cancel(struct thr_info *thr);
  165. void subtime(struct timeval *a, struct timeval *b);
  166. void addtime(struct timeval *a, struct timeval *b);
  167. bool time_more(struct timeval *a, struct timeval *b);
  168. bool time_less(struct timeval *a, struct timeval *b);
  169. void copy_time(struct timeval *dest, const struct timeval *src);
  170. void timespec_to_val(struct timeval *val, const struct timespec *spec);
  171. void timeval_to_spec(struct timespec *spec, const struct timeval *val);
  172. void us_to_timeval(struct timeval *val, int64_t us);
  173. void us_to_timespec(struct timespec *spec, int64_t us);
  174. void ms_to_timespec(struct timespec *spec, int64_t ms);
  175. void timeraddspec(struct timespec *a, const struct timespec *b);
  176. void cgsleep_ms(int ms);
  177. void cgsleep_us(int64_t us);
  178. #define cgtimer_time(ts_start) timer_set_now(ts_start)
  179. #define cgsleep_prepare_r(ts_start) cgtimer_time(ts_start)
  180. void cgsleep_ms_r(cgtimer_t *ts_start, int ms);
  181. extern void (*cgsleep_us_r)(cgtimer_t *ts_start, int64_t us);
  182. static inline
  183. int cgtimer_to_ms(cgtimer_t *cgt)
  184. {
  185. return (cgt->tv_sec * 1000) + (cgt->tv_usec / 1000);
  186. }
  187. extern int bfg_cond_timedwait(pthread_cond_t * restrict, pthread_mutex_t * restrict, const struct timeval *);
  188. extern pthread_condattr_t *bfg_condattr_();
  189. #define bfg_condattr (bfg_condattr_())
  190. #define cgtimer_sub(a, b, res) timersub(a, b, res)
  191. double us_tdiff(struct timeval *end, struct timeval *start);
  192. double tdiff(struct timeval *end, struct timeval *start);
  193. bool _stratum_send(struct pool *pool, char *s, ssize_t len, bool force);
  194. #define stratum_send(pool, s, len) _stratum_send(pool, s, len, false)
  195. bool sock_full(struct pool *pool);
  196. char *recv_line(struct pool *pool);
  197. bool parse_method(struct pool *pool, char *s);
  198. bool extract_sockaddr(char *url, char **sockaddr_url, char **sockaddr_port);
  199. bool auth_stratum(struct pool *pool);
  200. bool initiate_stratum(struct pool *pool);
  201. bool restart_stratum(struct pool *pool);
  202. void suspend_stratum(struct pool *pool);
  203. extern void dev_error_update(struct cgpu_info *, enum dev_reason);
  204. void dev_error(struct cgpu_info *dev, enum dev_reason reason);
  205. void *realloc_strcat(char *ptr, char *s);
  206. extern char *sanestr(char *o, char *s);
  207. void RenameThread(const char* name);
  208. enum bfg_strerror_type {
  209. BST_ERRNO,
  210. BST_SOCKET,
  211. BST_LIBUSB,
  212. BST_SYSTEM,
  213. };
  214. extern const char *bfg_strerror(int, enum bfg_strerror_type);
  215. extern void *bfg_slurp_file(void *buf, size_t bufsz, const char *filename);
  216. typedef SOCKETTYPE notifier_t[2];
  217. extern void notifier_init(notifier_t);
  218. extern void notifier_wake(notifier_t);
  219. extern void notifier_read(notifier_t);
  220. extern bool notifier_wait(notifier_t, const struct timeval *);
  221. extern bool notifier_wait_us(notifier_t, unsigned long long usecs);
  222. extern void notifier_reset(notifier_t);
  223. extern void notifier_init_invalid(notifier_t);
  224. extern void notifier_destroy(notifier_t);
  225. /* Align a size_t to 4 byte boundaries for fussy arches */
  226. static inline void align_len(size_t *len)
  227. {
  228. if (*len % 4)
  229. *len += 4 - (*len % 4);
  230. }
  231. static inline
  232. uint8_t bitflip8(uint8_t p)
  233. {
  234. p = ((p & 0xaa) >> 1) | ((p & 0x55) << 1);
  235. p = ((p & 0xcc) >> 2) | ((p & 0x33) << 2);
  236. p = ((p & 0xf0) >> 4) | ((p & 0x0f) << 4);
  237. return p;
  238. }
  239. static inline
  240. uint8_t upk_u8(const void * const bufp, const int offset)
  241. {
  242. const uint8_t * const buf = bufp;
  243. return buf[offset];
  244. }
  245. #define upk_u8be(buf, offset) upk_u8(buf, offset)
  246. static inline
  247. uint16_t upk_u16be(const void * const bufp, const int offset)
  248. {
  249. const uint8_t * const buf = bufp;
  250. return (((uint16_t)buf[offset+0]) << 8)
  251. | (((uint16_t)buf[offset+1]) << 0);
  252. }
  253. static inline
  254. uint32_t upk_u32be(const void * const bufp, const int offset)
  255. {
  256. const uint8_t * const buf = bufp;
  257. return (((uint32_t)buf[offset+0]) << 0x18)
  258. | (((uint32_t)buf[offset+1]) << 0x10)
  259. | (((uint32_t)buf[offset+2]) << 8)
  260. | (((uint32_t)buf[offset+3]) << 0);
  261. }
  262. static inline
  263. uint64_t upk_u64be(const void * const bufp, const int offset)
  264. {
  265. const uint8_t * const buf = bufp;
  266. return (((uint64_t)buf[offset+0]) << 0x38)
  267. | (((uint64_t)buf[offset+1]) << 0x30)
  268. | (((uint64_t)buf[offset+2]) << 0x28)
  269. | (((uint64_t)buf[offset+3]) << 0x20)
  270. | (((uint64_t)buf[offset+4]) << 0x18)
  271. | (((uint64_t)buf[offset+5]) << 0x10)
  272. | (((uint64_t)buf[offset+6]) << 8)
  273. | (((uint64_t)buf[offset+7]) << 0);
  274. }
  275. #define upk_u8le(buf, offset) upk_u8(buf, offset)
  276. static inline
  277. uint16_t upk_u16le(const void * const bufp, const int offset)
  278. {
  279. const uint8_t * const buf = bufp;
  280. return (((uint16_t)buf[offset+0]) << 0)
  281. | (((uint16_t)buf[offset+1]) << 8);
  282. }
  283. static inline
  284. uint32_t upk_u32le(const void * const bufp, const int offset)
  285. {
  286. const uint8_t * const buf = bufp;
  287. return (((uint32_t)buf[offset+0]) << 0)
  288. | (((uint32_t)buf[offset+1]) << 8)
  289. | (((uint32_t)buf[offset+2]) << 0x10)
  290. | (((uint32_t)buf[offset+3]) << 0x18);
  291. }
  292. static inline
  293. uint64_t upk_u64le(const void * const bufp, const int offset)
  294. {
  295. const uint8_t * const buf = bufp;
  296. return (((uint64_t)buf[offset+0]) << 0)
  297. | (((uint64_t)buf[offset+1]) << 8)
  298. | (((uint64_t)buf[offset+2]) << 0x10)
  299. | (((uint64_t)buf[offset+3]) << 0x18)
  300. | (((uint64_t)buf[offset+4]) << 0x20)
  301. | (((uint64_t)buf[offset+5]) << 0x28)
  302. | (((uint64_t)buf[offset+6]) << 0x30)
  303. | (((uint64_t)buf[offset+7]) << 0x38);
  304. }
  305. static inline
  306. void pk_u8(void * const bufp, const int offset, const uint8_t nv)
  307. {
  308. uint8_t * const buf = bufp;
  309. buf[offset] = nv;
  310. }
  311. #define pk_u8be(buf, offset, nv) pk_u8(buf, offset, nv)
  312. static inline
  313. void pk_u16be(void * const bufp, const int offset, const uint16_t nv)
  314. {
  315. uint8_t * const buf = bufp;
  316. buf[offset+0] = (nv >> 8) & 0xff;
  317. buf[offset+1] = (nv >> 0) & 0xff;
  318. }
  319. static inline
  320. void pk_u32be(void * const bufp, const int offset, const uint32_t nv)
  321. {
  322. uint8_t * const buf = bufp;
  323. buf[offset+0] = (nv >> 0x18) & 0xff;
  324. buf[offset+1] = (nv >> 0x10) & 0xff;
  325. buf[offset+2] = (nv >> 8) & 0xff;
  326. buf[offset+3] = (nv >> 0) & 0xff;
  327. }
  328. static inline
  329. void pk_u64be(void * const bufp, const int offset, const uint64_t nv)
  330. {
  331. uint8_t * const buf = bufp;
  332. buf[offset+0] = (nv >> 0x38) & 0xff;
  333. buf[offset+1] = (nv >> 0x30) & 0xff;
  334. buf[offset+2] = (nv >> 0x28) & 0xff;
  335. buf[offset+3] = (nv >> 0x20) & 0xff;
  336. buf[offset+4] = (nv >> 0x18) & 0xff;
  337. buf[offset+5] = (nv >> 0x10) & 0xff;
  338. buf[offset+6] = (nv >> 8) & 0xff;
  339. buf[offset+7] = (nv >> 0) & 0xff;
  340. }
  341. #define pk_u8le(buf, offset, nv) pk_u8(buf, offset, nv)
  342. static inline
  343. void pk_u16le(void * const bufp, const int offset, const uint16_t nv)
  344. {
  345. uint8_t * const buf = bufp;
  346. buf[offset+0] = (nv >> 0) & 0xff;
  347. buf[offset+1] = (nv >> 8) & 0xff;
  348. }
  349. static inline
  350. void pk_u32le(void * const bufp, const int offset, const uint32_t nv)
  351. {
  352. uint8_t * const buf = bufp;
  353. buf[offset+0] = (nv >> 0) & 0xff;
  354. buf[offset+1] = (nv >> 8) & 0xff;
  355. buf[offset+2] = (nv >> 0x10) & 0xff;
  356. buf[offset+3] = (nv >> 0x18) & 0xff;
  357. }
  358. static inline
  359. void pk_u64le(void * const bufp, const int offset, const uint64_t nv)
  360. {
  361. uint8_t * const buf = bufp;
  362. buf[offset+0] = (nv >> 0) & 0xff;
  363. buf[offset+1] = (nv >> 8) & 0xff;
  364. buf[offset+2] = (nv >> 0x10) & 0xff;
  365. buf[offset+3] = (nv >> 0x18) & 0xff;
  366. buf[offset+4] = (nv >> 0x20) & 0xff;
  367. buf[offset+5] = (nv >> 0x28) & 0xff;
  368. buf[offset+6] = (nv >> 0x30) & 0xff;
  369. buf[offset+7] = (nv >> 0x38) & 0xff;
  370. }
  371. #define _pk_uNle(bitwidth, newvalue) do{ \
  372. uint ## bitwidth ## _t _mask = 1; \
  373. _mask <<= _bitlen; \
  374. --_mask; \
  375. uint ## bitwidth ## _t _filt = _mask; \
  376. _filt <<= _bitoff; \
  377. _filt = ~_filt; \
  378. uint ## bitwidth ## _t _u = upk_u ## bitwidth ## le(_buf, 0); \
  379. _u = (_u & _filt) | (((newvalue) & _mask) << _bitoff); \
  380. pk_u ## bitwidth ## le(_buf, 0, _u); \
  381. }while(0)
  382. #define pk_uNle(bufp, offset, bitoffset, bitlength, newvalue) do{ \
  383. uint8_t * const _buf = &((uint8_t *)(bufp))[offset]; \
  384. const int _bitoff = (bitoffset), _bitlen = bitlength; \
  385. const int _bittot = bitoffset + bitlength; \
  386. _Static_assert((bitoffset + bitlength) <= 0x40, "Too many bits addressed in pk_uNle (bitoffset + bitlength must be <= 64)"); \
  387. if (_bittot <= 8) \
  388. _pk_uNle( 8, newvalue); \
  389. else \
  390. if (_bittot <= 0x10) \
  391. _pk_uNle(16, newvalue); \
  392. else \
  393. if (_bittot <= 0x20) \
  394. _pk_uNle(32, newvalue); \
  395. else \
  396. _pk_uNle(64, newvalue); \
  397. }while(0)
  398. #define is_power_of_two(n) \
  399. (0 == ((n) & ((n) - 1)))
  400. static inline
  401. uint32_t upper_power_of_two_u32(uint32_t n)
  402. {
  403. --n;
  404. for (int i = 1; i <= 0x10; i *= 2)
  405. n |= n >> i;
  406. ++n;
  407. return n;
  408. }
  409. typedef struct bytes_t {
  410. uint8_t *buf;
  411. size_t sz;
  412. size_t allocsz;
  413. } bytes_t;
  414. #define BYTES_INIT {.buf=NULL,}
  415. static inline
  416. void bytes_init(bytes_t *b)
  417. {
  418. *b = (bytes_t)BYTES_INIT;
  419. }
  420. // This can't be inline without ugly const/non-const issues
  421. #define bytes_buf(b) ((b)->buf)
  422. static inline
  423. size_t bytes_len(const bytes_t *b)
  424. {
  425. return b->sz;
  426. }
  427. static inline
  428. ssize_t bytes_find(const bytes_t * const b, const uint8_t needle)
  429. {
  430. const size_t blen = bytes_len(b);
  431. const uint8_t * const buf = bytes_buf(b);
  432. for (int i = 0; i < blen; ++i)
  433. if (buf[i] == needle)
  434. return i;
  435. return -1;
  436. }
  437. static inline
  438. bool bytes_eq(const bytes_t * const a, const bytes_t * const b)
  439. {
  440. if (a->sz != b->sz)
  441. return false;
  442. return !memcmp(a->buf, b->buf, a->sz);
  443. }
  444. extern void _bytes_alloc_failure(size_t);
  445. static inline
  446. void bytes_extend_buf(bytes_t * const b, const size_t newsz)
  447. {
  448. if (newsz <= b->allocsz)
  449. return;
  450. if (!b->allocsz)
  451. b->allocsz = 0x10;
  452. do {
  453. b->allocsz *= 2;
  454. } while (newsz > b->allocsz);
  455. b->buf = realloc(b->buf, b->allocsz);
  456. if (!b->buf)
  457. _bytes_alloc_failure(b->allocsz);
  458. }
  459. static inline
  460. void bytes_resize(bytes_t * const b, const size_t newsz)
  461. {
  462. bytes_extend_buf(b, newsz);
  463. b->sz = newsz;
  464. }
  465. static inline
  466. void *bytes_preappend(bytes_t * const b, const size_t addsz)
  467. {
  468. size_t origsz = bytes_len(b);
  469. bytes_extend_buf(b, origsz + addsz);
  470. return &bytes_buf(b)[origsz];
  471. }
  472. static inline
  473. void bytes_postappend(bytes_t * const b, const size_t addsz)
  474. {
  475. size_t origsz = bytes_len(b);
  476. bytes_resize(b, origsz + addsz);
  477. }
  478. static inline
  479. void bytes_append(bytes_t * const b, const void * const add, const size_t addsz)
  480. {
  481. void * const appendbuf = bytes_preappend(b, addsz);
  482. memcpy(appendbuf, add, addsz);
  483. bytes_postappend(b, addsz);
  484. }
  485. static inline
  486. void bytes_cat(bytes_t *b, const bytes_t *cat)
  487. {
  488. bytes_append(b, bytes_buf(cat), bytes_len(cat));
  489. }
  490. static inline
  491. void bytes_cpy(bytes_t *dst, const bytes_t *src)
  492. {
  493. dst->sz = src->sz;
  494. if (!dst->sz) {
  495. dst->allocsz = 0;
  496. dst->buf = NULL;
  497. return;
  498. }
  499. dst->allocsz = src->allocsz;
  500. size_t half;
  501. while (dst->sz <= (half = dst->allocsz / 2))
  502. dst->allocsz = half;
  503. dst->buf = malloc(dst->allocsz);
  504. memcpy(dst->buf, src->buf, dst->sz);
  505. }
  506. // Efficiently moves the data from src to dst, emptying src in the process
  507. static inline
  508. void bytes_assimilate(bytes_t * const dst, bytes_t * const src)
  509. {
  510. void * const buf = dst->buf;
  511. const size_t allocsz = dst->allocsz;
  512. *dst = *src;
  513. *src = (bytes_t){
  514. .buf = buf,
  515. .allocsz = allocsz,
  516. };
  517. }
  518. static inline
  519. void bytes_assimilate_raw(bytes_t * const b, void * const buf, const size_t bufsz, const size_t buflen)
  520. {
  521. free(b->buf);
  522. b->buf = buf;
  523. b->allocsz = bufsz;
  524. b->sz = buflen;
  525. }
  526. static inline
  527. void bytes_shift(bytes_t *b, size_t shift)
  528. {
  529. if (shift >= b->sz)
  530. {
  531. b->sz = 0;
  532. return;
  533. }
  534. b->sz -= shift;
  535. memmove(bytes_buf(b), &bytes_buf(b)[shift], bytes_len(b));
  536. }
  537. static inline
  538. void bytes_reset(bytes_t *b)
  539. {
  540. b->sz = 0;
  541. }
  542. static inline
  543. void bytes_nullterminate(bytes_t *b)
  544. {
  545. bytes_append(b, "", 1);
  546. --b->sz;
  547. }
  548. static inline
  549. void bytes_free(bytes_t *b)
  550. {
  551. free(b->buf);
  552. bytes_init(b);
  553. }
  554. static inline
  555. void set_maxfd(int *p_maxfd, int fd)
  556. {
  557. if (fd > *p_maxfd)
  558. *p_maxfd = fd;
  559. }
  560. static inline
  561. void timer_unset(struct timeval *tvp)
  562. {
  563. tvp->tv_sec = -1;
  564. }
  565. static inline
  566. bool timer_isset(const struct timeval *tvp)
  567. {
  568. return tvp->tv_sec != -1;
  569. }
  570. extern void (*timer_set_now)(struct timeval *);
  571. #define cgtime(tvp) timer_set_now(tvp)
  572. #define TIMEVAL_USECS(usecs) ( \
  573. (struct timeval){ \
  574. .tv_sec = (usecs) / 1000000, \
  575. .tv_usec = (usecs) % 1000000, \
  576. } \
  577. )
  578. static inline
  579. long timeval_to_us(const struct timeval *tvp)
  580. {
  581. return ((long)tvp->tv_sec * 1000000) + tvp->tv_usec;
  582. }
  583. #define timer_set_delay(tvp_timer, tvp_now, usecs) do { \
  584. struct timeval tv_add = TIMEVAL_USECS(usecs); \
  585. timeradd(&tv_add, tvp_now, tvp_timer); \
  586. } while(0)
  587. #define timer_set_delay_from_now(tvp_timer, usecs) do { \
  588. struct timeval tv_now; \
  589. timer_set_now(&tv_now); \
  590. timer_set_delay(tvp_timer, &tv_now, usecs); \
  591. } while(0)
  592. static inline
  593. const struct timeval *_bfg_nullisnow(const struct timeval *tvp, struct timeval *tvp_buf)
  594. {
  595. if (tvp)
  596. return tvp;
  597. cgtime(tvp_buf);
  598. return tvp_buf;
  599. }
  600. static inline
  601. long timer_elapsed_us(const struct timeval *tvp_timer, const struct timeval *tvp_now)
  602. {
  603. struct timeval tv;
  604. const struct timeval *_tvp_now = _bfg_nullisnow(tvp_now, &tv);
  605. timersub(_tvp_now, tvp_timer, &tv);
  606. return timeval_to_us(&tv);
  607. }
  608. #define ms_tdiff(end, start) (timer_elapsed_us(start, end) / 1000)
  609. static inline
  610. int timer_elapsed(const struct timeval *tvp_timer, const struct timeval *tvp_now)
  611. {
  612. struct timeval tv;
  613. const struct timeval *_tvp_now = _bfg_nullisnow(tvp_now, &tv);
  614. timersub(_tvp_now, tvp_timer, &tv);
  615. return tv.tv_sec;
  616. }
  617. static inline
  618. long timer_remaining_us(const struct timeval *tvp_timer, const struct timeval *tvp_now)
  619. {
  620. struct timeval tv;
  621. const struct timeval *_tvp_now = _bfg_nullisnow(tvp_now, &tv);
  622. timersub(tvp_timer, _tvp_now, &tv);
  623. return timeval_to_us(&tv);
  624. }
  625. static inline
  626. bool timer_passed(const struct timeval *tvp_timer, const struct timeval *tvp_now)
  627. {
  628. if (!timer_isset(tvp_timer))
  629. return false;
  630. struct timeval tv;
  631. const struct timeval *_tvp_now = _bfg_nullisnow(tvp_now, &tv);
  632. return timercmp(tvp_timer, _tvp_now, <);
  633. }
  634. #if defined(WIN32) && !defined(HAVE_POOR_GETTIMEOFDAY)
  635. #define HAVE_POOR_GETTIMEOFDAY
  636. #endif
  637. #ifdef HAVE_POOR_GETTIMEOFDAY
  638. extern void bfg_gettimeofday(struct timeval *);
  639. #else
  640. #define bfg_gettimeofday(out) gettimeofday(out, NULL)
  641. #endif
  642. static inline
  643. void reduce_timeout_to(struct timeval *tvp_timeout, struct timeval *tvp_time)
  644. {
  645. if (!timer_isset(tvp_time))
  646. return;
  647. if ((!timer_isset(tvp_timeout)) || timercmp(tvp_time, tvp_timeout, <))
  648. *tvp_timeout = *tvp_time;
  649. }
  650. static inline
  651. struct timeval *select_timeout(struct timeval *tvp_timeout, struct timeval *tvp_now)
  652. {
  653. if (!timer_isset(tvp_timeout))
  654. return NULL;
  655. if (timercmp(tvp_timeout, tvp_now, <))
  656. timerclear(tvp_timeout);
  657. else
  658. timersub(tvp_timeout, tvp_now, tvp_timeout);
  659. return tvp_timeout;
  660. }
  661. #define _SNP2(fn, ...) do{ \
  662. int __n42 = fn(s, sz, __VA_ARGS__); \
  663. s += __n42; \
  664. sz = (sz <= __n42) ? 0 : (sz - __n42); \
  665. rv += __n42; \
  666. }while(0)
  667. #define _SNP(...) _SNP2(snprintf, __VA_ARGS__)
  668. extern int double_find_precision(double, double base);
  669. #define REPLACEMENT_CHAR (0xFFFD)
  670. #define U8_DEGREE "\xc2\xb0"
  671. #define U8_MICRO "\xc2\xb5"
  672. #define U8_HLINE "\xe2\x94\x80"
  673. #define U8_BTEE "\xe2\x94\xb4"
  674. extern int utf8_len(uint8_t);
  675. extern int32_t utf8_decode(const void *, int *out_len);
  676. extern size_t utf8_strlen(const void *);
  677. extern void utf8_test();
  678. #define RUNONCE(rv) do { \
  679. static bool _runonce = false; \
  680. if (_runonce) \
  681. return rv; \
  682. _runonce = true; \
  683. } while(0)
  684. static inline
  685. char *maybe_strdup(const char *s)
  686. {
  687. return s ? strdup(s) : NULL;
  688. }
  689. static inline
  690. void maybe_strdup_if_null(const char **p, const char *s)
  691. {
  692. if (!*p)
  693. *p = maybe_strdup(s);
  694. }
  695. extern char *trimmed_strdup(const char *);
  696. extern void run_cmd(const char *cmd);
  697. extern bool bm1382_freq_to_reg_data(uint8_t *out_reg_data, float mhz);
  698. extern uint8_t crc5usb(unsigned char *ptr, uint8_t len);
  699. extern void bfg_init_checksums(void);
  700. extern uint8_t crc8ccitt(const void *, size_t);
  701. extern uint16_t crc16(const void *, size_t, uint16_t init);
  702. #define crc16ffff( DATA, SZ) crc16(DATA, SZ, 0xffff)
  703. #define crc16xmodem(DATA, SZ) crc16(DATA, SZ, 0)
  704. #endif /* __UTIL_H__ */