2017-1-15-libubox analysis
utils.h
提供了一些简单的实用工具函数。比如大小端转换,位图操作,编译器属性的封装,连续内存申请函数calloc_a,静态计算数组大小的宏,断言/调试的实用工具,苹果兼容的时钟获取时间的封装,base64编解码。
- /*
- *
- * calloc_a(size_t len, [void **addr, size_t len,...], NULL)
- * 申请一个足够大内存块来保存多个对齐的对象。
- * 返回一个指针,指针指向全部对象(以第一个块开始)注意:释放这个指针将释放所有全部对象的内存
- * 所有其它指针被保存在额外的addr参数指向的位置。
- * 最后一个参数必须是NULL指针
- */
-
- #define calloc_a(len, ...) __calloc_a(len, ##__VA_ARGS__, NULL)
- void *__calloc_a(size_t len, ...);
-
calloc_a示例:
- #include <string.h>
- #include <libubox/utils.h>
-
- struct sleeper {
- int aa;
- int bb;
- };
-
- #define NAME_LEN 32
- int main(int argc, char **argv)
- {
- struct sleeper *s;
- char *name;
- int *a1;
- s = (struct sleeper *)calloc_a(sizeof(*s), &name, NAME_LEN, &a1, sizeof(*a1));
- s->aa = 0x10101010;
- s->bb = 0x20202020;
- strncpy(name, "SSSSSSSSSSSSSSSSSSSSSSSS", NAME_LEN-1);
- name[NAME_LEN-1] = ‘\0‘;
- *a1 = 0xaaaaaaaa;
- free(s);
- return 0;
- }
-
- (gdb) x/20x s
- 0x602010: 0x10101010 0x20202020 0x53535353 0x53535353
- 0x602020: 0x53535353 0x53535353 0x53535353 0x53535353
- 0x602030: 0x00000000 0x00000000 0xaaaaaaaa 0x00000000
-
-
-
- #ifndef ARRAY_SIZE
- #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
- #endif
- /*
- * BUILD_BUG_ON基于一个GCC不支持负数数组,在编译时报错
- * 但是4.4后GCC支持变长数组,不会引起编译器报错。
- * 加入GCC优化选项后,编译时不会错,但是链接时会有找不到符号__BUILD_BUG_ON_CONDITION_FAILED的错误
- */
- #define __BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
-
- #ifdef __OPTIMIZE__
- extern int __BUILD_BUG_ON_CONDITION_FAILED;
- #define BUILD_BUG_ON(condition) \
- do { \
- __BUILD_BUG_ON(condition); \
- if (condition) \
- __BUILD_BUG_ON_CONDITION_FAILED = 1; \
- } while(0)
- #else
- #define BUILD_BUG_ON __BUILD_BUG_ON
- #endif
FIXUP:
- /* Force a compilation error if condition is true */
- -#define BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)]))
- +#define BUILD_BUG_ON(condition) ((void)BUILD_BUG_ON_ZERO(condition))
- +
- +/* Force a compilation error if condition is constant and true */
- +#define MAYBE_BUILD_BUG_ON(cond) ((void)sizeof(char[1 - 2 * !!(cond)]))
-
- /* Force a compilation error if condition is true, but also produce a
- result (of value 0 and type size_t), so the expression can be used
- e.g. in a structure initializer (or where-ever else comma expressions
- aren‘t permitted). */
- -#define BUILD_BUG_ON_ZERO(e) (sizeof(char[1 - 2 * !!(e)]) - 1)
- +#define BUILD_BUG_ON_ZERO(e) (sizeof(struct { int:-!!(e); }))
- +#define BUILD_BUG_ON_NULL(e) ((void *)sizeof(struct { int:-!!(e); }))
- /*
- */
- #ifdef __APPLE__
-
- #define CLOCK_REALTIME 0
- #define CLOCK_MONOTONIC 1
-
- void clock_gettime(int type, struct timespec *tv);
-
- #endif
Leilei Wang