From 95513201e195147a1363b21b0fd99d35071e0de4 Mon Sep 17 00:00:00 2001 From: Victor Seva Date: Thu, 18 May 2023 15:15:36 +0200 Subject: [PATCH 01/14] pre-commit: tool to keep thing tidy --- .pre-commit-config.yaml | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 .pre-commit-config.yaml diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 00000000000..de87c76fda6 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,11 @@ +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v2.3.0 + hooks: + - id: check-yaml + - id: end-of-file-fixer + - id: trailing-whitespace + - repo: https://github.com/pre-commit/mirrors-clang-format + rev: v15.0.7 + hooks: + - id: clang-format From 9e67b77829c69208a656eecf8805bd21251cb7a3 Mon Sep 17 00:00:00 2001 From: Victor Seva Date: Thu, 18 May 2023 15:17:32 +0200 Subject: [PATCH 02/14] core: [atomic] clang-format for coherent indentation and coding style --- src/core/atomic/atomic_alpha.h | 381 +++++++++++++++--------------- src/core/atomic/atomic_arm.h | 335 +++++++++++++------------- src/core/atomic/atomic_common.h | 29 +-- src/core/atomic/atomic_mips2.h | 388 +++++++++++++++--------------- src/core/atomic/atomic_native.h | 10 +- src/core/atomic/atomic_ppc.h | 308 ++++++++++++------------ src/core/atomic/atomic_sparc.h | 61 ++--- src/core/atomic/atomic_sparc64.h | 336 +++++++++++++------------- src/core/atomic/atomic_unknown.h | 273 +++++++++++----------- src/core/atomic/atomic_x86.h | 390 +++++++++++++++++-------------- 10 files changed, 1277 insertions(+), 1234 deletions(-) diff --git a/src/core/atomic/atomic_alpha.h b/src/core/atomic/atomic_alpha.h index 49f329a53d4..77fb790c7f4 100644 --- a/src/core/atomic/atomic_alpha.h +++ b/src/core/atomic/atomic_alpha.h @@ -1,4 +1,4 @@ -/* +/* * Copyright (C) 2006 iptelorg GmbH * * Permission to use, copy, modify, and distribute this software for any @@ -14,16 +14,16 @@ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ -/** +/** * @file * @brief Atomic operations and memory barriers (alpha specific) * * Atomic operations and memory barriers (alpha specific) * \warning atomic ops do not include memory barriers, see atomic_ops.h * for more details. - * + * * Config defines: - * - NOSMP + * - NOSMP * - __CPU_alpha * @ingroup atomic */ @@ -39,32 +39,38 @@ sr-dev@lists.kamailio.org #ifdef NOSMP -#define membar() asm volatile ("" : : : "memory") /* gcc do not cache barrier*/ -#define membar_read() membar() +#define membar() asm volatile("" : : : "memory") /* gcc do not cache barrier*/ +#define membar_read() membar() #define membar_write() membar() -#define membar_depends() do {} while(0) /* really empty, not even a cc bar. */ +#define membar_depends() \ + do { \ + } while(0) /* really empty, not even a cc bar. */ /* lock barriers: empty, not needed for NOSMP; the lock/unlock should already * contain gcc barriers*/ -#define membar_enter_lock() do {} while(0) -#define membar_leave_lock() do {} while(0) +#define membar_enter_lock() \ + do { \ + } while(0) +#define membar_leave_lock() \ + do { \ + } while(0) /* membars after or before atomic_ops or atomic_setget -> use these or * mb_() if you need a memory barrier in one of these * situations (on some archs where the atomic operations imply memory * barriers is better to use atomic_op_x(); membar_atomic_op() then * atomic_op_x(); membar()) */ -#define membar_atomic_op() membar() -#define membar_atomic_setget() membar() -#define membar_write_atomic_op() membar_write() -#define membar_write_atomic_setget() membar_write() -#define membar_read_atomic_op() membar_read() -#define membar_read_atomic_setget() membar_read() +#define membar_atomic_op() membar() +#define membar_atomic_setget() membar() +#define membar_write_atomic_op() membar_write() +#define membar_write_atomic_setget() membar_write() +#define membar_read_atomic_op() membar_read() +#define membar_read_atomic_setget() membar_read() #else -#define membar() asm volatile (" mb \n\t" : : : "memory" ) -#define membar_read() membar() -#define membar_write() asm volatile (" wmb \n\t" : : : "memory" ) -#define membar_depends() asm volatile ("mb \n\t" : : : "memory" ) +#define membar() asm volatile(" mb \n\t" : : : "memory") +#define membar_read() membar() +#define membar_write() asm volatile(" wmb \n\t" : : : "memory") +#define membar_depends() asm volatile("mb \n\t" : : : "memory") #define membar_enter_lock() asm volatile("mb \n\t" : : : "memory") #define membar_leave_lock() asm volatile("mb \n\t" : : : "memory") @@ -73,189 +79,180 @@ * situations (on some archs where the atomic operations imply memory * barriers is better to use atomic_op_x(); membar_atomic_op() then * atomic_op_x(); membar()) */ -#define membar_atomic_op() membar() -#define membar_atomic_setget() membar() -#define membar_write_atomic_op() membar_write() -#define membar_write_atomic_setget() membar_write() -#define membar_read_atomic_op() membar_read() -#define membar_read_atomic_setget() membar_read() +#define membar_atomic_op() membar() +#define membar_atomic_setget() membar() +#define membar_write_atomic_op() membar_write() +#define membar_write_atomic_setget() membar_write() +#define membar_read_atomic_op() membar_read() +#define membar_read_atomic_setget() membar_read() #endif /* NOSMP */ - -/* main asm block +/* main asm block * if store fails, jump _forward_ (optimization, because back jumps are * always predicted to happen on alpha )*/ #define ATOMIC_ASM_OP00_int(op) \ - "1: ldl_l %0, %2 \n\t" \ - " " op "\n\t" \ - " stl_c %0, %2 \n\t" \ - " beq %0, 2f \n\t" \ - ".subsection 2 \n\t" \ - "2: br 1b \n\t" \ - ".previous \n\t" + "1: ldl_l %0, %2 \n\t" \ + " " op "\n\t" \ + " stl_c %0, %2 \n\t" \ + " beq %0, 2f \n\t" \ + ".subsection 2 \n\t" \ + "2: br 1b \n\t" \ + ".previous \n\t" /* as above, but output in %1 instead of %0 (%0 is not clobbered) */ #define ATOMIC_ASM_OP01_int(op) \ - "1: ldl_l %0, %3 \n\t" \ - " " op "\n\t" \ - " stl_c %1, %3 \n\t" \ - " beq %1, 2f \n\t" \ - ".subsection 2 \n\t" \ - "2: br 1b \n\t" \ - ".previous \n\t" + "1: ldl_l %0, %3 \n\t" \ + " " op "\n\t" \ + " stl_c %1, %3 \n\t" \ + " beq %1, 2f \n\t" \ + ".subsection 2 \n\t" \ + "2: br 1b \n\t" \ + ".previous \n\t" #define ATOMIC_ASM_OP00_long(op) \ - "1: ldq_l %0, %2 \n\t" \ - " " op "\n\t" \ - " stq_c %0, %2 \n\t" \ - " beq %0, 2f \n\t" \ - ".subsection 2 \n\t" \ - "2: br 1b \n\t" \ - ".previous \n\t" + "1: ldq_l %0, %2 \n\t" \ + " " op "\n\t" \ + " stq_c %0, %2 \n\t" \ + " beq %0, 2f \n\t" \ + ".subsection 2 \n\t" \ + "2: br 1b \n\t" \ + ".previous \n\t" /* as above, but output in %1 instead of %0 (%0 is not clobbered) */ #define ATOMIC_ASM_OP01_long(op) \ - "1: ldq_l %0, %3 \n\t" \ - " " op "\n\t" \ - " stq_c %1, %3 \n\t" \ - " beq %1, 2f \n\t" \ - ".subsection 2 \n\t" \ - "2: br 1b \n\t" \ - ".previous \n\t" - + "1: ldq_l %0, %3 \n\t" \ + " " op "\n\t" \ + " stq_c %1, %3 \n\t" \ + " beq %1, 2f \n\t" \ + ".subsection 2 \n\t" \ + "2: br 1b \n\t" \ + ".previous \n\t" /* input in %0, output in %0 */ -#define ATOMIC_FUNC_DECL0_0(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ - inline static RET_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var) \ - { \ - P_TYPE ret; \ - asm volatile( \ - ATOMIC_ASM_OP00_##P_TYPE(OP) : "=&r"(ret), "=m"(*var) : "m"(*var) \ - ); \ - return RET_EXPR; \ +#define ATOMIC_FUNC_DECL0_0(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ + inline static RET_TYPE atomic_##NAME##_##P_TYPE(volatile P_TYPE *var) \ + { \ + P_TYPE ret; \ + asm volatile(ATOMIC_ASM_OP00_##P_TYPE(OP) \ + : "=&r"(ret), "=m"(*var) \ + : "m"(*var)); \ + return RET_EXPR; \ } -#if defined __GNUC__ && __GNUC__ < 3 && __GNUC_MINOR__ < 9 +#if defined __GNUC__ && __GNUC__ < 3 && __GNUC_MINOR__ < 9 #define ATOMIC_FUNC_DECL01_1(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ - inline static RET_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var, \ - P_TYPE v ) \ - { \ - P_TYPE ret; \ - asm volatile( \ - ATOMIC_ASM_OP01_##P_TYPE(OP) \ - : "=&r"(ret), "=r"(v), "=m"(*var) : "m"(*var), "1"(v) \ - ); \ - return RET_EXPR; \ + inline static RET_TYPE atomic_##NAME##_##P_TYPE( \ + volatile P_TYPE *var, P_TYPE v) \ + { \ + P_TYPE ret; \ + asm volatile(ATOMIC_ASM_OP01_##P_TYPE(OP) \ + : "=&r"(ret), "=r"(v), "=m"(*var) \ + : "m"(*var), "1"(v)); \ + return RET_EXPR; \ } #else /* input in %0, and %1 (param), output in %1, %0 goes in ret */ #define ATOMIC_FUNC_DECL01_1(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ - inline static RET_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var, \ - P_TYPE v ) \ - { \ - P_TYPE ret; \ - asm volatile( \ - ATOMIC_ASM_OP01_##P_TYPE(OP) \ - : "=&r"(ret), "+r"(v), "=m"(*var) : "m"(*var) \ - ); \ - return RET_EXPR; \ + inline static RET_TYPE atomic_##NAME##_##P_TYPE( \ + volatile P_TYPE *var, P_TYPE v) \ + { \ + P_TYPE ret; \ + asm volatile(ATOMIC_ASM_OP01_##P_TYPE(OP) \ + : "=&r"(ret), "+r"(v), "=m"(*var) \ + : "m"(*var)); \ + return RET_EXPR; \ } #endif /* gcc && gcc version < 2.9 */ /* input in %0, output in %1, %0 goes in ret */ -#define ATOMIC_FUNC_DECL0_1(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ - inline static RET_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var) \ - { \ - P_TYPE ret, tmp; \ - asm volatile( \ - ATOMIC_ASM_OP01_##P_TYPE(OP) \ - : "=&r"(ret), "=&r"(tmp), "=m"(*var) : "m"(*var) \ - ); \ - return RET_EXPR; \ +#define ATOMIC_FUNC_DECL0_1(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ + inline static RET_TYPE atomic_##NAME##_##P_TYPE(volatile P_TYPE *var) \ + { \ + P_TYPE ret, tmp; \ + asm volatile(ATOMIC_ASM_OP01_##P_TYPE(OP) \ + : "=&r"(ret), "=&r"(tmp), "=m"(*var) \ + : "m"(*var)); \ + return RET_EXPR; \ } /* input in %0 and %3 (param), output in %0 */ #define ATOMIC_FUNC_DECL03_0(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ - inline static RET_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var, \ - P_TYPE v) \ - { \ - P_TYPE ret; \ - asm volatile( \ - ATOMIC_ASM_OP00_##P_TYPE(OP) \ - : "=&r"(ret), "=m"(*var) : "m"(*var), "r"(v) \ - ); \ - return RET_EXPR; \ + inline static RET_TYPE atomic_##NAME##_##P_TYPE( \ + volatile P_TYPE *var, P_TYPE v) \ + { \ + P_TYPE ret; \ + asm volatile(ATOMIC_ASM_OP00_##P_TYPE(OP) \ + : "=&r"(ret), "=m"(*var) \ + : "m"(*var), "r"(v)); \ + return RET_EXPR; \ } /* input in %0 and %3 (param), output in %0 */ /* cmpxchg var in %1, old in %0, new_v in % * makes the xchg if old==*var * returns initial *var (so if ret==old => new_v was written into var)*/ -#define ATOMIC_CMPXCHG_DECL(NAME, P_TYPE) \ - inline static P_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var, \ - P_TYPE old, \ - P_TYPE new_v) \ - { \ - P_TYPE ret; \ - P_TYPE tmp; \ - asm volatile( \ - ATOMIC_ASM_OP01_##P_TYPE("subq %0, %5, %2 \n\t bne %2, 3f")\ - "3: \n\t" \ - : "=&r"(ret), "=&r"(new_v), "=r"(tmp), "=m"(*var) :\ - "m"(*var), "r"(old), "1"(new_v) :"cc" \ - ); \ - return ret; \ +#define ATOMIC_CMPXCHG_DECL(NAME, P_TYPE) \ + inline static P_TYPE atomic_##NAME##_##P_TYPE( \ + volatile P_TYPE *var, P_TYPE old, P_TYPE new_v) \ + { \ + P_TYPE ret; \ + P_TYPE tmp; \ + asm volatile(ATOMIC_ASM_OP01_##P_TYPE( \ + "subq %0, %5, %2 \n\t bne %2, 3f") "3: \n\t" \ + : "=&r"(ret), "=&r"(new_v), "=r"(tmp), "=m"(*var) \ + : "m"(*var), "r"(old), "1"(new_v) \ + : "cc"); \ + return ret; \ } -ATOMIC_FUNC_DECL0_0(inc, "addl %0, 1, %0", int, void, /* no return */ ) -ATOMIC_FUNC_DECL0_0(dec, "subl %0, 1, %0", int, void, /* no return */ ) -ATOMIC_FUNC_DECL03_0(and, "and %0, %3, %0", int, void, /* no return */ ) -ATOMIC_FUNC_DECL03_0(or, "bis %0, %3, %0", int, void, /* no return */ ) -ATOMIC_FUNC_DECL0_1(inc_and_test, "addl %0, 1, %1", int, int, (ret+1)==0 ) -ATOMIC_FUNC_DECL0_1(dec_and_test, "subl %0, 1, %1", int, int, (ret-1)==0 ) -ATOMIC_FUNC_DECL01_1(get_and_set, "" /* nothing needed */, int, int, ret ) -ATOMIC_CMPXCHG_DECL(cmpxchg, int ) -ATOMIC_FUNC_DECL01_1(add, "addl %1, %0, %1", int, int, ret+v) +ATOMIC_FUNC_DECL0_0(inc, "addl %0, 1, %0", int, void, /* no return */) +ATOMIC_FUNC_DECL0_0(dec, "subl %0, 1, %0", int, void, /* no return */) +ATOMIC_FUNC_DECL03_0(and, "and %0, %3, %0", int, void, /* no return */) +ATOMIC_FUNC_DECL03_0(or, "bis %0, %3, %0", int, void, /* no return */) +ATOMIC_FUNC_DECL0_1(inc_and_test, "addl %0, 1, %1", int, int, (ret + 1) == 0) +ATOMIC_FUNC_DECL0_1(dec_and_test, "subl %0, 1, %1", int, int, (ret - 1) == 0) +ATOMIC_FUNC_DECL01_1(get_and_set, "" /* nothing needed */, int, int, ret) +ATOMIC_CMPXCHG_DECL(cmpxchg, int) +ATOMIC_FUNC_DECL01_1(add, "addl %1, %0, %1", int, int, ret + v) -ATOMIC_FUNC_DECL0_0(inc, "addq %0, 1, %0", long, void, /* no return */ ) -ATOMIC_FUNC_DECL0_0(dec, "subq %0, 1, %0", long, void, /* no return */ ) -ATOMIC_FUNC_DECL03_0(and, "and %0, %3, %0", long, void, /* no return */ ) -ATOMIC_FUNC_DECL03_0(or, "bis %0, %3, %0", long, void, /* no return */ ) -ATOMIC_FUNC_DECL0_1(inc_and_test, "addq %0, 1, %1", long, long, (ret+1)==0 ) -ATOMIC_FUNC_DECL0_1(dec_and_test, "subq %0, 1, %1", long, long, (ret-1)==0 ) -ATOMIC_FUNC_DECL01_1(get_and_set, "" /* nothing needed */, long, long, ret ) -ATOMIC_CMPXCHG_DECL(cmpxchg, long ) -ATOMIC_FUNC_DECL01_1(add, "addq %1, %0, %1", long, long, ret+v) +ATOMIC_FUNC_DECL0_0(inc, "addq %0, 1, %0", long, void, /* no return */) +ATOMIC_FUNC_DECL0_0(dec, "subq %0, 1, %0", long, void, /* no return */) +ATOMIC_FUNC_DECL03_0(and, "and %0, %3, %0", long, void, /* no return */) +ATOMIC_FUNC_DECL03_0(or, "bis %0, %3, %0", long, void, /* no return */) +ATOMIC_FUNC_DECL0_1(inc_and_test, "addq %0, 1, %1", long, long, (ret + 1) == 0) +ATOMIC_FUNC_DECL0_1(dec_and_test, "subq %0, 1, %1", long, long, (ret - 1) == 0) +ATOMIC_FUNC_DECL01_1(get_and_set, "" /* nothing needed */, long, long, ret) +ATOMIC_CMPXCHG_DECL(cmpxchg, long) +ATOMIC_FUNC_DECL01_1(add, "addq %1, %0, %1", long, long, ret + v) #define atomic_inc(var) atomic_inc_int(&(var)->val) #define atomic_dec(var) atomic_dec_int(&(var)->val) #define atomic_and(var, mask) atomic_and_int(&(var)->val, (mask)) -#define atomic_or(var, mask) atomic_or_int(&(var)->val, (mask)) +#define atomic_or(var, mask) atomic_or_int(&(var)->val, (mask)) #define atomic_dec_and_test(var) atomic_dec_and_test_int(&(var)->val) #define atomic_inc_and_test(var) atomic_inc_and_test_int(&(var)->val) #define atomic_get_and_set(var, i) atomic_get_and_set_int(&(var)->val, i) #define atomic_cmpxchg(var, old, new_v) \ - atomic_cmpxchg_int(&(var)->val, old, new_v) + atomic_cmpxchg_int(&(var)->val, old, new_v) #define atomic_add(var, v) atomic_add_int(&(var)->val, (v)) /* with integrated membar */ #define mb_atomic_set_int(v, i) \ - do{ \ - membar(); \ - atomic_set_int(v, i); \ - }while(0) + do { \ + membar(); \ + atomic_set_int(v, i); \ + } while(0) - -inline static int mb_atomic_get_int(volatile int* v) +inline static int mb_atomic_get_int(volatile int *v) { membar(); return atomic_get_int(v); @@ -263,71 +260,69 @@ inline static int mb_atomic_get_int(volatile int* v) #define mb_atomic_inc_int(v) \ - do{ \ - membar(); \ - atomic_inc_int(v); \ - }while(0) + do { \ + membar(); \ + atomic_inc_int(v); \ + } while(0) #define mb_atomic_dec_int(v) \ - do{ \ - membar(); \ - atomic_dec_int(v); \ - }while(0) + do { \ + membar(); \ + atomic_dec_int(v); \ + } while(0) #define mb_atomic_or_int(v, m) \ - do{ \ - membar(); \ - atomic_or_int(v, m); \ - }while(0) + do { \ + membar(); \ + atomic_or_int(v, m); \ + } while(0) #define mb_atomic_and_int(v, m) \ - do{ \ - membar(); \ - atomic_and_int(v, m); \ - }while(0) + do { \ + membar(); \ + atomic_and_int(v, m); \ + } while(0) -inline static int mb_atomic_inc_and_test_int(volatile int* v) +inline static int mb_atomic_inc_and_test_int(volatile int *v) { membar(); return atomic_inc_and_test_int(v); } -inline static int mb_atomic_dec_and_test_int(volatile int* v) +inline static int mb_atomic_dec_and_test_int(volatile int *v) { membar(); return atomic_dec_and_test_int(v); } -inline static int mb_atomic_get_and_set_int(volatile int* v, int i) +inline static int mb_atomic_get_and_set_int(volatile int *v, int i) { membar(); return atomic_get_and_set_int(v, i); } -inline static int mb_atomic_cmpxchg_int(volatile int* v, int o, int n) +inline static int mb_atomic_cmpxchg_int(volatile int *v, int o, int n) { membar(); return atomic_cmpxchg_int(v, o, n); } -inline static int mb_atomic_add_int(volatile int* v, int i) +inline static int mb_atomic_add_int(volatile int *v, int i) { membar(); return atomic_add_int(v, i); } - #define mb_atomic_set_long(v, i) \ - do{ \ - membar(); \ - atomic_set_long(v, i); \ - }while(0) - + do { \ + membar(); \ + atomic_set_long(v, i); \ + } while(0) -inline static long mb_atomic_get_long(volatile long* v) +inline static long mb_atomic_get_long(volatile long *v) { membar(); return atomic_get_long(v); @@ -335,57 +330,57 @@ inline static long mb_atomic_get_long(volatile long* v) #define mb_atomic_inc_long(v) \ - do{ \ - membar(); \ - atomic_inc_long(v); \ - }while(0) + do { \ + membar(); \ + atomic_inc_long(v); \ + } while(0) #define mb_atomic_dec_long(v) \ - do{ \ - membar(); \ - atomic_dec_long(v); \ - }while(0) + do { \ + membar(); \ + atomic_dec_long(v); \ + } while(0) #define mb_atomic_or_long(v, m) \ - do{ \ - membar(); \ - atomic_or_long(v, m); \ - }while(0) + do { \ + membar(); \ + atomic_or_long(v, m); \ + } while(0) #define mb_atomic_and_long(v, m) \ - do{ \ - membar(); \ - atomic_and_long(v, m); \ - }while(0) + do { \ + membar(); \ + atomic_and_long(v, m); \ + } while(0) -inline static long mb_atomic_inc_and_test_long(volatile long* v) +inline static long mb_atomic_inc_and_test_long(volatile long *v) { membar(); return atomic_inc_and_test_long(v); } -inline static long mb_atomic_dec_and_test_long(volatile long* v) +inline static long mb_atomic_dec_and_test_long(volatile long *v) { membar(); return atomic_dec_and_test_long(v); } -inline static long mb_atomic_get_and_set_long(volatile long* v, long l) +inline static long mb_atomic_get_and_set_long(volatile long *v, long l) { membar(); return atomic_get_and_set_long(v, l); } -inline static long mb_atomic_cmpxchg_long(volatile long* v, long o, long n) +inline static long mb_atomic_cmpxchg_long(volatile long *v, long o, long n) { membar(); return atomic_cmpxchg_long(v, o, n); } -inline static long mb_atomic_add_long(volatile long* v, long i) +inline static long mb_atomic_add_long(volatile long *v, long i) { membar(); return atomic_add_long(v, i); @@ -395,11 +390,11 @@ inline static long mb_atomic_add_long(volatile long* v, long i) #define mb_atomic_inc(var) mb_atomic_inc_int(&(var)->val) #define mb_atomic_dec(var) mb_atomic_dec_int(&(var)->val) #define mb_atomic_and(var, mask) mb_atomic_and_int(&(var)->val, (mask)) -#define mb_atomic_or(var, mask) mb_atomic_or_int(&(var)->val, (mask)) +#define mb_atomic_or(var, mask) mb_atomic_or_int(&(var)->val, (mask)) #define mb_atomic_dec_and_test(var) mb_atomic_dec_and_test_int(&(var)->val) #define mb_atomic_inc_and_test(var) mb_atomic_inc_and_test_int(&(var)->val) -#define mb_atomic_get(var) mb_atomic_get_int(&(var)->val) -#define mb_atomic_set(var, i) mb_atomic_set_int(&(var)->val, i) +#define mb_atomic_get(var) mb_atomic_get_int(&(var)->val) +#define mb_atomic_set(var, i) mb_atomic_set_int(&(var)->val, i) #define mb_atomic_get_and_set(var, i) mb_atomic_get_and_set_int(&(var)->val, i) #define mb_atomic_cmpxchg(var, o, n) mb_atomic_cmpxchg_int(&(var)->val, o, n) #define mb_atomic_add(var, i) mb_atomic_add_int(&(var)->val, i) diff --git a/src/core/atomic/atomic_arm.h b/src/core/atomic/atomic_arm.h index 23b41914b5b..4202d6146d2 100644 --- a/src/core/atomic/atomic_arm.h +++ b/src/core/atomic/atomic_arm.h @@ -1,4 +1,4 @@ -/* +/* * Copyright (C) 2006 iptelorg GmbH * * Permission to use, copy, modify, and distribute this software for any @@ -17,15 +17,15 @@ /** * @file * @brief Atomic ops and memory barriers for ARM (>= v3) - * + * * Atomic ops and memory barriers for ARM architecture (starting from version 3) * see atomic_ops.h for more info. - * + * * Config defines: * - NOSMP * - __CPU_arm * - __CPU_arm6 - armv6 support (supports atomic ops via ldrex/strex) - * - __CPU_arm7 - armv7 support + * - __CPU_arm7 - armv7 support * @ingroup atomic */ @@ -33,25 +33,23 @@ #define _atomic_arm_h - - #ifdef NOSMP #define HAVE_ASM_INLINE_MEMBAR -#define membar() asm volatile ("" : : : "memory") /* gcc do not cache barrier*/ +#define membar() asm volatile("" : : : "memory") /* gcc do not cache barrier*/ #else /* SMP */ #ifdef __CPU_arm7 #define HAVE_ASM_INLINE_MEMBAR -#define membar() asm volatile ("dmb" : : : "memory") +#define membar() asm volatile("dmb" : : : "memory") #elif defined __CPU_arm6 #define HAVE_ASM_INLINE_MEMBAR /* arm6 implements memory barriers using CP15 */ -#define membar() asm volatile ("mcr p15, 0, %0, c7, c10, 5" \ - : : "r"(0) : "memory") +#define membar() \ + asm volatile("mcr p15, 0, %0, c7, c10, 5" : : "r"(0) : "memory") #else #warning SMP not supported for arm atomic ops, try compiling with -DNOSMP @@ -65,23 +63,25 @@ irrespective of the SMP or NOSMP mode */ #ifdef HAVE_ASM_INLINE_MEMBAR -#define membar_read() membar() +#define membar_read() membar() #define membar_write() membar() -#define membar_depends() do {} while(0) /* really empty, not even a cc bar.*/ +#define membar_depends() \ + do { \ + } while(0) /* really empty, not even a cc bar.*/ /* lock barriers */ -#define membar_enter_lock() membar() -#define membar_leave_lock() membar() +#define membar_enter_lock() membar() +#define membar_leave_lock() membar() /* membars after or before atomic_ops or atomic_setget -> use these or * mb_() if you need a memory barrier in one of these * situations (on some archs where the atomic operations imply memory * barriers is better to use atomic_op_x(); membar_atomic_op() then * atomic_op_x(); membar()) */ -#define membar_atomic_op() membar() -#define membar_atomic_setget() membar() -#define membar_write_atomic_op() membar_write() -#define membar_write_atomic_setget() membar_write() -#define membar_read_atomic_op() membar_read() -#define membar_read_atomic_setget() membar_read() +#define membar_atomic_op() membar() +#define membar_atomic_setget() membar() +#define membar_write_atomic_op() membar_write() +#define membar_write_atomic_setget() membar_write() +#define membar_read_atomic_op() membar_read() +#define membar_read_atomic_setget() membar_read() #endif /* HAVE_ASM_INLINE_MEMBAR */ @@ -96,73 +96,73 @@ #include "atomic_unknown.h" #endif -/* main asm block +/* main asm block * use %0 as input and write the output in %1*/ -#define ATOMIC_ASM_OP(op) \ - "1: ldrex %0, [%3] \n\t" \ - " " op "\n\t" \ - " strex %0, %1, [%3] \n\t" \ - " cmp %0, #0 \n\t" \ - " bne 1b \n\t" - -/* same as above but writes %4 instead of %1, and %0 will contain +#define ATOMIC_ASM_OP(op) \ + "1: ldrex %0, [%3] \n\t" \ + " " op "\n\t" \ + " strex %0, %1, [%3] \n\t" \ + " cmp %0, #0 \n\t" \ + " bne 1b \n\t" + +/* same as above but writes %4 instead of %1, and %0 will contain * the prev. val*/ -#define ATOMIC_ASM_OP2(op) \ - "1: ldrex %0, [%3] \n\t" \ - " " op "\n\t" \ - " strex %1, %4, [%3] \n\t" \ - " cmp %1, #0 \n\t" \ - " bne 1b \n\t" +#define ATOMIC_ASM_OP2(op) \ + "1: ldrex %0, [%3] \n\t" \ + " " op "\n\t" \ + " strex %1, %4, [%3] \n\t" \ + " cmp %1, #0 \n\t" \ + " bne 1b \n\t" /* no extra param, %0 contains *var, %1 should contain the result */ -#define ATOMIC_FUNC_DECL(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ - inline static RET_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var) \ - { \ - P_TYPE ret, tmp; \ - asm volatile( \ - ATOMIC_ASM_OP(OP) \ - : "=&r"(tmp), "=&r"(ret), "=m"(*var) : "r"(var) : "cc" \ - ); \ - return RET_EXPR; \ +#define ATOMIC_FUNC_DECL(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ + inline static RET_TYPE atomic_##NAME##_##P_TYPE(volatile P_TYPE *var) \ + { \ + P_TYPE ret, tmp; \ + asm volatile(ATOMIC_ASM_OP(OP) \ + : "=&r"(tmp), "=&r"(ret), "=m"(*var) \ + : "r"(var) \ + : "cc"); \ + return RET_EXPR; \ } /* one extra param in %4 */ #define ATOMIC_FUNC_DECL1(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ - inline static RET_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var, \ - P_TYPE v) \ - { \ - P_TYPE ret, tmp; \ - asm volatile( \ - ATOMIC_ASM_OP(OP) \ - : "=&r"(tmp), "=&r"(ret), "=m"(*var) : "r"(var), "r"(v) : "cc" \ - ); \ - return RET_EXPR; \ + inline static RET_TYPE atomic_##NAME##_##P_TYPE( \ + volatile P_TYPE *var, P_TYPE v) \ + { \ + P_TYPE ret, tmp; \ + asm volatile(ATOMIC_ASM_OP(OP) \ + : "=&r"(tmp), "=&r"(ret), "=m"(*var) \ + : "r"(var), "r"(v) \ + : "cc"); \ + return RET_EXPR; \ } /* as above, but %4 should contain the result, and %0 is returned*/ #define ATOMIC_FUNC_DECL2(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ - inline static RET_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var, \ - P_TYPE v) \ - { \ - P_TYPE ret, tmp; \ - asm volatile( \ - ATOMIC_ASM_OP2(OP) \ - : "=&r"(ret), "=&r"(tmp), "=m"(*var) : "r"(var), "r"(v) : "cc" \ - ); \ - return RET_EXPR; \ + inline static RET_TYPE atomic_##NAME##_##P_TYPE( \ + volatile P_TYPE *var, P_TYPE v) \ + { \ + P_TYPE ret, tmp; \ + asm volatile(ATOMIC_ASM_OP2(OP) \ + : "=&r"(ret), "=&r"(tmp), "=m"(*var) \ + : "r"(var), "r"(v) \ + : "cc"); \ + return RET_EXPR; \ } -#define ATOMIC_XCHG_DECL(NAME, P_TYPE) \ - inline static P_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var, \ - P_TYPE v ) \ - { \ - P_TYPE ret; \ - asm volatile( \ - ATOMIC_ASM_OP2() \ - : "=&r"(ret), "=&r"(tmp), "=m"(*var) : "r"(var), "r"(v) : "cc" \ - ); \ - return ret; \ +#define ATOMIC_XCHG_DECL(NAME, P_TYPE) \ + inline static P_TYPE atomic_##NAME##_##P_TYPE( \ + volatile P_TYPE *var, P_TYPE v) \ + { \ + P_TYPE ret; \ + asm volatile(ATOMIC_ASM_OP2() \ + : "=&r"(ret), "=&r"(tmp), "=m"(*var) \ + : "r"(var), "r"(v) \ + : "cc"); \ + return ret; \ } /* old swp based version (doesn't work on arm7) @@ -183,57 +183,54 @@ /* cmpxchg: %5=old, %4=new_v, %3=var * if (*var==old) *var=new_v - * returns the original *var (can be used to check if it succeeded: + * returns the original *var (can be used to check if it succeeded: * if old==cmpxchg(var, old, new_v) -> success */ -#define ATOMIC_CMPXCHG_DECL(NAME, P_TYPE) \ - inline static P_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var, \ - P_TYPE old, \ - P_TYPE new_v) \ - { \ - P_TYPE ret, tmp; \ - asm volatile( \ - "1: ldrex %0, [%3] \n\t" \ - " cmp %0, %5 \n\t" \ - " strexeq %1, %4, [%3] \n\t" \ - " cmp %1, #0 \n\t" \ - " bne 1b \n\t" \ - /* strexeq is exec. only if cmp was successful \ +#define ATOMIC_CMPXCHG_DECL(NAME, P_TYPE) \ + inline static P_TYPE atomic_##NAME##_##P_TYPE( \ + volatile P_TYPE *var, P_TYPE old, P_TYPE new_v) \ + { \ + P_TYPE ret, tmp; \ + asm volatile( \ + "1: ldrex %0, [%3] \n\t" \ + " cmp %0, %5 \n\t" \ + " strexeq %1, %4, [%3] \n\t" \ + " cmp %1, #0 \n\t" \ + " bne 1b \n\t" /* strexeq is exec. only if cmp was successful \ * => if not successful %1 is not changed and remains 0 */ \ - : "=&r"(ret), "=&r"(tmp), "=m"(*var) :\ - "r"(var), "r"(new_v), "r"(old), "1"(0) : "cc" \ - ); \ - return ret; \ + : "=&r"(ret), "=&r"(tmp), "=m"(*var) \ + : "r"(var), "r"(new_v), "r"(old), "1"(0) \ + : "cc"); \ + return ret; \ } - -ATOMIC_FUNC_DECL(inc, "add %1, %0, #1", int, void, /* no return */ ) -ATOMIC_FUNC_DECL(dec, "sub %1, %0, #1", int, void, /* no return */ ) -ATOMIC_FUNC_DECL1(and, "and %1, %0, %4", int, void, /* no return */ ) -ATOMIC_FUNC_DECL1(or, "orr %1, %0, %4", int, void, /* no return */ ) -ATOMIC_FUNC_DECL(inc_and_test, "add %1, %0, #1", int, int, ret==0 ) -ATOMIC_FUNC_DECL(dec_and_test, "sub %1, %0, #1", int, int, ret==0 ) -ATOMIC_FUNC_DECL2(get_and_set, "" /* no extra op needed */ , int, int, ret) +ATOMIC_FUNC_DECL(inc, "add %1, %0, #1", int, void, /* no return */) +ATOMIC_FUNC_DECL(dec, "sub %1, %0, #1", int, void, /* no return */) +ATOMIC_FUNC_DECL1(and, "and %1, %0, %4", int, void, /* no return */) +ATOMIC_FUNC_DECL1(or, "orr %1, %0, %4", int, void, /* no return */) +ATOMIC_FUNC_DECL(inc_and_test, "add %1, %0, #1", int, int, ret == 0) +ATOMIC_FUNC_DECL(dec_and_test, "sub %1, %0, #1", int, int, ret == 0) +ATOMIC_FUNC_DECL2(get_and_set, "" /* no extra op needed */, int, int, ret) //ATOMIC_XCHG_DECL(get_and_set, int) ATOMIC_CMPXCHG_DECL(cmpxchg, int) -ATOMIC_FUNC_DECL1(add, "add %1, %0, %4", int, int, ret ) - -ATOMIC_FUNC_DECL(inc, "add %1, %0, #1", long, void, /* no return */ ) -ATOMIC_FUNC_DECL(dec, "sub %1, %0, #1", long, void, /* no return */ ) -ATOMIC_FUNC_DECL1(and, "and %1, %0, %4", long, void, /* no return */ ) -ATOMIC_FUNC_DECL1(or, "orr %1, %0, %4", long, void, /* no return */ ) -ATOMIC_FUNC_DECL(inc_and_test, "add %1, %0, #1", long, long, ret==0 ) -ATOMIC_FUNC_DECL(dec_and_test, "sub %1, %0, #1", long, long, ret==0 ) -ATOMIC_FUNC_DECL2(get_and_set, "" /* no extra op needed */ , long, long, ret) +ATOMIC_FUNC_DECL1(add, "add %1, %0, %4", int, int, ret) + +ATOMIC_FUNC_DECL(inc, "add %1, %0, #1", long, void, /* no return */) +ATOMIC_FUNC_DECL(dec, "sub %1, %0, #1", long, void, /* no return */) +ATOMIC_FUNC_DECL1(and, "and %1, %0, %4", long, void, /* no return */) +ATOMIC_FUNC_DECL1(or, "orr %1, %0, %4", long, void, /* no return */) +ATOMIC_FUNC_DECL(inc_and_test, "add %1, %0, #1", long, long, ret == 0) +ATOMIC_FUNC_DECL(dec_and_test, "sub %1, %0, #1", long, long, ret == 0) +ATOMIC_FUNC_DECL2(get_and_set, "" /* no extra op needed */, long, long, ret) //ATOMIC_XCHG_DECL(get_and_set, long) ATOMIC_CMPXCHG_DECL(cmpxchg, long) -ATOMIC_FUNC_DECL1(add, "add %1, %0, %4", long, long, ret ) +ATOMIC_FUNC_DECL1(add, "add %1, %0, %4", long, long, ret) #define atomic_inc(var) atomic_inc_int(&(var)->val) #define atomic_dec(var) atomic_dec_int(&(var)->val) #define atomic_and(var, mask) atomic_and_int(&(var)->val, (mask)) -#define atomic_or(var, mask) atomic_or_int(&(var)->val, (mask)) +#define atomic_or(var, mask) atomic_or_int(&(var)->val, (mask)) #define atomic_dec_and_test(var) atomic_dec_and_test_int(&(var)->val) #define atomic_inc_and_test(var) atomic_inc_and_test_int(&(var)->val) #define atomic_get_and_set(var, i) atomic_get_and_set_int(&(var)->val, i) @@ -245,14 +242,13 @@ ATOMIC_FUNC_DECL1(add, "add %1, %0, %4", long, long, ret ) /* with integrated membar */ #define mb_atomic_set_int(v, i) \ - do{ \ - membar(); \ - atomic_set_int(v, i); \ - }while(0) - + do { \ + membar(); \ + atomic_set_int(v, i); \ + } while(0) -inline static int mb_atomic_get_int(volatile int* v) +inline static int mb_atomic_get_int(volatile int *v) { membar(); return atomic_get_int(v); @@ -260,71 +256,69 @@ inline static int mb_atomic_get_int(volatile int* v) #define mb_atomic_inc_int(v) \ - do{ \ - membar(); \ - atomic_inc_int(v); \ - }while(0) + do { \ + membar(); \ + atomic_inc_int(v); \ + } while(0) #define mb_atomic_dec_int(v) \ - do{ \ - membar(); \ - atomic_dec_int(v); \ - }while(0) + do { \ + membar(); \ + atomic_dec_int(v); \ + } while(0) #define mb_atomic_or_int(v, m) \ - do{ \ - membar(); \ - atomic_or_int(v, m); \ - }while(0) + do { \ + membar(); \ + atomic_or_int(v, m); \ + } while(0) #define mb_atomic_and_int(v, m) \ - do{ \ - membar(); \ - atomic_and_int(v, m); \ - }while(0) + do { \ + membar(); \ + atomic_and_int(v, m); \ + } while(0) -inline static int mb_atomic_inc_and_test_int(volatile int* v) +inline static int mb_atomic_inc_and_test_int(volatile int *v) { membar(); return atomic_inc_and_test_int(v); } -inline static int mb_atomic_dec_and_test_int(volatile int* v) +inline static int mb_atomic_dec_and_test_int(volatile int *v) { membar(); return atomic_dec_and_test_int(v); } -inline static int mb_atomic_get_and_set_int(volatile int* v, int i) +inline static int mb_atomic_get_and_set_int(volatile int *v, int i) { membar(); return atomic_get_and_set_int(v, i); } -inline static int mb_atomic_cmpxchg_int(volatile int* v, int o, int n) +inline static int mb_atomic_cmpxchg_int(volatile int *v, int o, int n) { membar(); return atomic_cmpxchg_int(v, o, n); } -inline static int mb_atomic_add_int(volatile int* v, int i) +inline static int mb_atomic_add_int(volatile int *v, int i) { membar(); return atomic_add_int(v, i); } - #define mb_atomic_set_long(v, i) \ - do{ \ - membar(); \ - atomic_set_long(v, i); \ - }while(0) - + do { \ + membar(); \ + atomic_set_long(v, i); \ + } while(0) -inline static long mb_atomic_get_long(volatile long* v) +inline static long mb_atomic_get_long(volatile long *v) { membar(); return atomic_get_long(v); @@ -332,56 +326,56 @@ inline static long mb_atomic_get_long(volatile long* v) #define mb_atomic_inc_long(v) \ - do{ \ - membar(); \ - atomic_inc_long(v); \ - }while(0) + do { \ + membar(); \ + atomic_inc_long(v); \ + } while(0) #define mb_atomic_dec_long(v) \ - do{ \ - membar(); \ - atomic_dec_long(v); \ - }while(0) + do { \ + membar(); \ + atomic_dec_long(v); \ + } while(0) #define mb_atomic_or_long(v, m) \ - do{ \ - membar(); \ - atomic_or_long(v, m); \ - }while(0) + do { \ + membar(); \ + atomic_or_long(v, m); \ + } while(0) #define mb_atomic_and_long(v, m) \ - do{ \ - membar(); \ - atomic_and_long(v, m); \ - }while(0) + do { \ + membar(); \ + atomic_and_long(v, m); \ + } while(0) -inline static long mb_atomic_inc_and_test_long(volatile long* v) +inline static long mb_atomic_inc_and_test_long(volatile long *v) { membar(); return atomic_inc_and_test_long(v); } -inline static long mb_atomic_dec_and_test_long(volatile long* v) +inline static long mb_atomic_dec_and_test_long(volatile long *v) { membar(); return atomic_dec_and_test_long(v); } -inline static long mb_atomic_get_and_set_long(volatile long* v, long l) +inline static long mb_atomic_get_and_set_long(volatile long *v, long l) { membar(); return atomic_get_and_set_long(v, l); } -inline static long mb_atomic_cmpxchg_long(volatile long* v, long o, long n) +inline static long mb_atomic_cmpxchg_long(volatile long *v, long o, long n) { membar(); return atomic_cmpxchg_long(v, o, n); } -inline static long mb_atomic_add_long(volatile long* v, long i) +inline static long mb_atomic_add_long(volatile long *v, long i) { membar(); return atomic_add_long(v, i); @@ -390,17 +384,16 @@ inline static long mb_atomic_add_long(volatile long* v, long i) #define mb_atomic_inc(var) mb_atomic_inc_int(&(var)->val) #define mb_atomic_dec(var) mb_atomic_dec_int(&(var)->val) #define mb_atomic_and(var, mask) mb_atomic_and_int(&(var)->val, (mask)) -#define mb_atomic_or(var, mask) mb_atomic_or_int(&(var)->val, (mask)) +#define mb_atomic_or(var, mask) mb_atomic_or_int(&(var)->val, (mask)) #define mb_atomic_dec_and_test(var) mb_atomic_dec_and_test_int(&(var)->val) #define mb_atomic_inc_and_test(var) mb_atomic_inc_and_test_int(&(var)->val) -#define mb_atomic_get(var) mb_atomic_get_int(&(var)->val) -#define mb_atomic_set(var, i) mb_atomic_set_int(&(var)->val, i) +#define mb_atomic_get(var) mb_atomic_get_int(&(var)->val) +#define mb_atomic_set(var, i) mb_atomic_set_int(&(var)->val, i) #define mb_atomic_get_and_set(var, i) mb_atomic_get_and_set_int(&(var)->val, i) #define mb_atomic_cmpxchg(var, o, n) mb_atomic_cmpxchg_int(&(var)->val, o, n) #define mb_atomic_add(var, i) mb_atomic_add_int(&(var)->val, i) - #else /* ! __CPU_arm6 => __CPU_arm */ /* no atomic ops for v <6 , only SWP supported @@ -408,14 +401,14 @@ inline static long mb_atomic_add_long(volatile long* v, long i) * a spinlock, e.g: * mov %r0, #0x1 * 1: swp %r1, %r0, [&atomic_val] - * if (%r1 & 0x1) goto 1 # wait if first bit is 1 + * if (%r1 & 0x1) goto 1 # wait if first bit is 1 * %r1>>=1 # restore the value (only 31 bits can be used ) - * %r1=op (%r1, ...) + * %r1=op (%r1, ...) * %r1<<=1 # shift back the value, such that the first bit is 0 * str %r1, [&atomic_val] # write the value * * However only 31 bits could be used (=> atomic_*_int and atomic_*_long - * would still have to be lock based, since in these cases we guarantee all + * would still have to be lock based, since in these cases we guarantee all * the bits) and I'm not sure there would be a significant performance * benefit when compared with the fallback lock based version: * lock(atomic_lock); diff --git a/src/core/atomic/atomic_common.h b/src/core/atomic/atomic_common.h index e44c8c7d4e9..b51ab57dd55 100644 --- a/src/core/atomic/atomic_common.h +++ b/src/core/atomic/atomic_common.h @@ -1,4 +1,4 @@ -/* +/* * Copyright (C) 2006 iptelorg GmbH * * Permission to use, copy, modify, and distribute this software for any @@ -17,7 +17,7 @@ /** * @defgroup atomic Kamailio atomic operations * @brief Kamailio atomic operations and memory barriers support - * + * * Kamailio atomic operations and memory barriers support for different CPU * architectures implemented in assembler. It also provides some generic * fallback code for architectures not currently supported. @@ -26,7 +26,7 @@ /** * @file * @brief Common part for all the atomic operations - * + * * Common part for all the atomic operations (atomic_t and common operations) * see atomic_ops.h for more info. * @ingroup atomic @@ -37,29 +37,32 @@ /** * @brief atomic_t defined as a struct to easily catch non atomic operations on it. - * + * * atomic_t defined as a struct to easily catch non atomic operations on it, * e.g. atomic_t foo; foo++ will generate a compile error. */ -typedef struct{ volatile int val; } atomic_t; +typedef struct +{ + volatile int val; +} atomic_t; -/** +/** * @name Atomic load and store operations * Atomic store and load operations are atomic on all cpus, note however that they - * don't include memory barriers so if you want to use atomic_{get,set} + * don't include memory barriers so if you want to use atomic_{get,set} * to implement mutexes you must use the mb_* versions or explicitely use - * the barriers + * the barriers */ /*@{ */ -#define atomic_set_int(pvar, i) (*(int*)(pvar)=i) -#define atomic_set_long(pvar, i) (*(long*)(pvar)=i) -#define atomic_get_int(pvar) (*(int*)(pvar)) -#define atomic_get_long(pvar) (*(long*)(pvar)) +#define atomic_set_int(pvar, i) (*(int *)(pvar) = i) +#define atomic_set_long(pvar, i) (*(long *)(pvar) = i) +#define atomic_get_int(pvar) (*(int *)(pvar)) +#define atomic_get_long(pvar) (*(long *)(pvar)) -#define atomic_set(at_var, value) (atomic_set_int(&((at_var)->val), (value))) +#define atomic_set(at_var, value) (atomic_set_int(&((at_var)->val), (value))) inline static int atomic_get(atomic_t *v) { diff --git a/src/core/atomic/atomic_mips2.h b/src/core/atomic/atomic_mips2.h index 3407a608048..bc1fdd3f6d3 100644 --- a/src/core/atomic/atomic_mips2.h +++ b/src/core/atomic/atomic_mips2.h @@ -1,4 +1,4 @@ -/* +/* * Copyright (C) 2006 iptelorg GmbH * * Permission to use, copy, modify, and distribute this software for any @@ -14,10 +14,10 @@ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ -/** - * @file +/** + * @file * @brief Atomic operations and memory barriers (MIPS isa 2 and MIPS64 specific) - * + * * Atomic operations and memory barriers (MIPS isa 2 and MIPS64 specific) * \warning atomic ops do not include memory barriers, see atomic_ops.h for * more details. @@ -43,41 +43,49 @@ #endif #ifdef NOSMP -#define membar() asm volatile ("" : : : "memory") /* gcc do not cache barrier*/ -#define membar_read() membar() +#define membar() asm volatile("" : : : "memory") /* gcc do not cache barrier*/ +#define membar_read() membar() #define membar_write() membar() -#define membar_depends() do {} while(0) /* really empty, not even a cc bar. */ +#define membar_depends() \ + do { \ + } while(0) /* really empty, not even a cc bar. */ /* lock barriers: empty, not needed for NOSMP; the lock/unlock should already * contain gcc barriers*/ -#define membar_enter_lock() do {} while(0) -#define membar_leave_lock() do {} while(0) +#define membar_enter_lock() \ + do { \ + } while(0) +#define membar_leave_lock() \ + do { \ + } while(0) /* membars after or before atomic_ops or atomic_setget -> use these or * mb_() if you need a memory barrier in one of these * situations (on some archs where the atomic operations imply memory * barriers is better to use atomic_op_x(); membar_atomic_op() then * atomic_op_x(); membar()) */ -#define membar_atomic_op() membar() -#define membar_atomic_setget() membar() -#define membar_write_atomic_op() membar_write() -#define membar_write_atomic_setget() membar_write() -#define membar_read_atomic_op() membar_read() -#define membar_read_atomic_setget() membar_read() +#define membar_atomic_op() membar() +#define membar_atomic_setget() membar() +#define membar_write_atomic_op() membar_write() +#define membar_write_atomic_setget() membar_write() +#define membar_read_atomic_op() membar_read() +#define membar_read_atomic_setget() membar_read() #else -#define membar() \ - asm volatile( \ - ".set push \n\t" \ - ".set noreorder \n\t" \ - ".set mips2 \n\t" \ - " sync\n\t" \ - ".set pop \n\t" \ - : : : "memory" \ - ) - -#define membar_read() membar() +#define membar() \ + asm volatile(".set push \n\t" \ + ".set noreorder \n\t" \ + ".set mips2 \n\t" \ + " sync\n\t" \ + ".set pop \n\t" \ + : \ + : \ + : "memory") + +#define membar_read() membar() #define membar_write() membar() -#define membar_depends() do {} while(0) /* really empty, not even a cc bar. */ +#define membar_depends() \ + do { \ + } while(0) /* really empty, not even a cc bar. */ #define membar_enter_lock() membar() #define membar_leave_lock() membar() /* membars after or before atomic_ops or atomic_setget -> use these or @@ -85,182 +93,177 @@ * situations (on some archs where the atomic operations imply memory * barriers is better to use atomic_op_x(); membar_atomic_op() then * atomic_op_x(); membar()) */ -#define membar_atomic_op() membar() -#define membar_atomic_setget() membar() -#define membar_write_atomic_op() membar_write() -#define membar_write_atomic_setget() membar_write() -#define membar_read_atomic_op() membar_read() -#define membar_read_atomic_setget() membar_read() +#define membar_atomic_op() membar() +#define membar_atomic_setget() membar() +#define membar_write_atomic_op() membar_write() +#define membar_write_atomic_setget() membar_write() +#define membar_read_atomic_op() membar_read() +#define membar_read_atomic_setget() membar_read() #endif /* NOSMP */ - /* main asm block */ -#define ATOMIC_ASM_OP_int(op) \ - ".set push \n\t" \ - ".set noreorder \n\t" \ - ".set mips2 \n\t" \ - "1: ll %1, %0 \n\t" \ - " " op "\n\t" \ - " sc %2, %0 \n\t" \ - " beqz %2, 1b \n\t" \ - " nop \n\t" /* delay slot */ \ - ".set pop \n\t" +#define ATOMIC_ASM_OP_int(op) \ + ".set push \n\t" \ + ".set noreorder \n\t" \ + ".set mips2 \n\t" \ + "1: ll %1, %0 \n\t" \ + " " op "\n\t" \ + " sc %2, %0 \n\t" \ + " beqz %2, 1b \n\t" \ + " nop \n\t" /* delay slot */ \ + ".set pop \n\t" #ifdef __CPU_mips64 -#define ATOMIC_ASM_OP_long(op) \ - ".set push \n\t" \ - ".set noreorder \n\t" \ - "1: lld %1, %0 \n\t" \ - " " op "\n\t" \ - " scd %2, %0 \n\t" \ - " beqz %2, 1b \n\t" \ - " nop \n\t" /* delay slot */ \ - ".set pop \n\t" +#define ATOMIC_ASM_OP_long(op) \ + ".set push \n\t" \ + ".set noreorder \n\t" \ + "1: lld %1, %0 \n\t" \ + " " op "\n\t" \ + " scd %2, %0 \n\t" \ + " beqz %2, 1b \n\t" \ + " nop \n\t" /* delay slot */ \ + ".set pop \n\t" #else /* ! __CPU_mips64 => __CPU_mips2 or __CPU_mips & MIPS_HAS_LLSC */ #define ATOMIC_ASM_OP_long(op) ATOMIC_ASM_OP_int(op) #endif -#define ATOMIC_FUNC_DECL(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ - inline static RET_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var) \ - { \ - P_TYPE ret, tmp; \ - asm volatile( \ - ATOMIC_ASM_OP_##P_TYPE(OP) \ - : "=m"(*var), "=&r"(ret), "=&r"(tmp) \ - : "m"(*var) \ - \ - ); \ - return RET_EXPR; \ +#define ATOMIC_FUNC_DECL(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ + inline static RET_TYPE atomic_##NAME##_##P_TYPE(volatile P_TYPE *var) \ + { \ + P_TYPE ret, tmp; \ + asm volatile(ATOMIC_ASM_OP_##P_TYPE(OP) \ + : "=m"(*var), "=&r"(ret), "=&r"(tmp) \ + : "m"(*var) \ + \ + ); \ + return RET_EXPR; \ } /* same as above, but with CT in %3 */ -#define ATOMIC_FUNC_DECL_CT(NAME, OP, CT, P_TYPE, RET_TYPE, RET_EXPR) \ - inline static RET_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var) \ - { \ - P_TYPE ret, tmp; \ - asm volatile( \ - ATOMIC_ASM_OP_##P_TYPE(OP) \ - : "=m"(*var), "=&r"(ret), "=&r"(tmp) \ - : "r"((CT)), "m"(*var) \ - \ - ); \ - return RET_EXPR; \ +#define ATOMIC_FUNC_DECL_CT(NAME, OP, CT, P_TYPE, RET_TYPE, RET_EXPR) \ + inline static RET_TYPE atomic_##NAME##_##P_TYPE(volatile P_TYPE *var) \ + { \ + P_TYPE ret, tmp; \ + asm volatile(ATOMIC_ASM_OP_##P_TYPE(OP) \ + : "=m"(*var), "=&r"(ret), "=&r"(tmp) \ + : "r"((CT)), "m"(*var) \ + \ + ); \ + return RET_EXPR; \ } /* takes an extra param, i which goes in %3 */ #define ATOMIC_FUNC_DECL1(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ - inline static RET_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var, \ - P_TYPE i) \ - { \ - P_TYPE ret, tmp; \ - asm volatile( \ - ATOMIC_ASM_OP_##P_TYPE(OP) \ - : "=m"(*var), "=&r"(ret), "=&r"(tmp) \ - : "r"((i)), "m"(*var) \ - \ - ); \ - return RET_EXPR; \ + inline static RET_TYPE atomic_##NAME##_##P_TYPE( \ + volatile P_TYPE *var, P_TYPE i) \ + { \ + P_TYPE ret, tmp; \ + asm volatile(ATOMIC_ASM_OP_##P_TYPE(OP) \ + : "=m"(*var), "=&r"(ret), "=&r"(tmp) \ + : "r"((i)), "m"(*var) \ + \ + ); \ + return RET_EXPR; \ } /* takes an extra param, like above, but i goes in %2 */ #define ATOMIC_FUNC_DECL2(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ - inline static RET_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var, \ - P_TYPE i) \ - { \ - P_TYPE ret; \ - asm volatile( \ - ATOMIC_ASM_OP_##P_TYPE(OP) \ - : "=m"(*var), "=&r"(ret), "+&r"(i) \ - : "m"(*var) \ - \ - ); \ - return RET_EXPR; \ + inline static RET_TYPE atomic_##NAME##_##P_TYPE( \ + volatile P_TYPE *var, P_TYPE i) \ + { \ + P_TYPE ret; \ + asm volatile(ATOMIC_ASM_OP_##P_TYPE(OP) \ + : "=m"(*var), "=&r"(ret), "+&r"(i) \ + : "m"(*var) \ + \ + ); \ + return RET_EXPR; \ } /* %0=var, %1=*var, %2=new, %3=old : * ret=*var; if *var==old then *var=new; return ret * => if successful (changed var to new) ret==old */ -#define ATOMIC_CMPXCHG_DECL(NAME, P_TYPE) \ - inline static P_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var, \ - P_TYPE old, \ - P_TYPE new_v) \ - { \ - asm volatile( \ - ATOMIC_ASM_OP_##P_TYPE("bne %1, %3, 2f \n\t nop") \ - "2: \n\t" \ - : "=m"(*var), "=&r"(old), "=r"(new_v) \ - : "r"(old), "m"(*var), "2"(new_v) \ - \ - ); \ - return old; \ +#define ATOMIC_CMPXCHG_DECL(NAME, P_TYPE) \ + inline static P_TYPE atomic_##NAME##_##P_TYPE( \ + volatile P_TYPE *var, P_TYPE old, P_TYPE new_v) \ + { \ + asm volatile( \ + ATOMIC_ASM_OP_##P_TYPE("bne %1, %3, 2f \n\t nop") "2: \n\t" \ + : "=m"(*var), "=&r"(old), "=r"(new_v) \ + : "r"(old), "m"(*var), "2"(new_v) \ + \ + ); \ + return old; \ } -ATOMIC_FUNC_DECL(inc, "addiu %2, %1, 1", int, void, /* no return */ ) -ATOMIC_FUNC_DECL_CT(dec, "subu %2, %1, %3", 1, int, void, /* no return */ ) -ATOMIC_FUNC_DECL1(and, "and %2, %1, %3", int, void, /* no return */ ) -ATOMIC_FUNC_DECL1(or, "or %2, %1, %3", int, void, /* no return */ ) -ATOMIC_FUNC_DECL(inc_and_test, "addiu %2, %1, 1", int, int, (ret+1)==0 ) -ATOMIC_FUNC_DECL_CT(dec_and_test, "subu %2, %1, %3", 1, int, int, (ret-1)==0 ) -ATOMIC_FUNC_DECL2(get_and_set, "" /* nothing needed */, int, int, ret ) +ATOMIC_FUNC_DECL(inc, "addiu %2, %1, 1", int, void, /* no return */) +ATOMIC_FUNC_DECL_CT(dec, "subu %2, %1, %3", 1, int, void, /* no return */) +ATOMIC_FUNC_DECL1(and, "and %2, %1, %3", int, void, /* no return */) +ATOMIC_FUNC_DECL1(or, "or %2, %1, %3", int, void, /* no return */) +ATOMIC_FUNC_DECL(inc_and_test, "addiu %2, %1, 1", int, int, (ret + 1) == 0) +ATOMIC_FUNC_DECL_CT( + dec_and_test, "subu %2, %1, %3", 1, int, int, (ret - 1) == 0) +ATOMIC_FUNC_DECL2(get_and_set, "" /* nothing needed */, int, int, ret) ATOMIC_CMPXCHG_DECL(cmpxchg, int) -ATOMIC_FUNC_DECL1(add, "addu %2, %1, %3 \n\t move %1, %2", int, int, ret ) +ATOMIC_FUNC_DECL1(add, "addu %2, %1, %3 \n\t move %1, %2", int, int, ret) #ifdef __CPU_mips64 -ATOMIC_FUNC_DECL(inc, "daddiu %2, %1, 1", long, void, /* no return */ ) -ATOMIC_FUNC_DECL_CT(dec, "dsubu %2, %1, %3", 1, long, void, /* no return */ ) -ATOMIC_FUNC_DECL1(and, "and %2, %1, %3", long, void, /* no return */ ) -ATOMIC_FUNC_DECL1(or, "or %2, %1, %3", long, void, /* no return */ ) -ATOMIC_FUNC_DECL(inc_and_test, "daddiu %2, %1, 1", long, long, (ret+1)==0 ) -ATOMIC_FUNC_DECL_CT(dec_and_test, "dsubu %2, %1, %3", 1,long, long, (ret-1)==0 ) -ATOMIC_FUNC_DECL2(get_and_set, "" /* nothing needed */, long, long, ret ) +ATOMIC_FUNC_DECL(inc, "daddiu %2, %1, 1", long, void, /* no return */) +ATOMIC_FUNC_DECL_CT(dec, "dsubu %2, %1, %3", 1, long, void, /* no return */) +ATOMIC_FUNC_DECL1(and, "and %2, %1, %3", long, void, /* no return */) +ATOMIC_FUNC_DECL1(or, "or %2, %1, %3", long, void, /* no return */) +ATOMIC_FUNC_DECL(inc_and_test, "daddiu %2, %1, 1", long, long, (ret + 1) == 0) +ATOMIC_FUNC_DECL_CT( + dec_and_test, "dsubu %2, %1, %3", 1, long, long, (ret - 1) == 0) +ATOMIC_FUNC_DECL2(get_and_set, "" /* nothing needed */, long, long, ret) ATOMIC_CMPXCHG_DECL(cmpxchg, long) -ATOMIC_FUNC_DECL1(add, "daddu %2, %1, %3 \n\t move %1, %2", long, long, ret ) +ATOMIC_FUNC_DECL1(add, "daddu %2, %1, %3 \n\t move %1, %2", long, long, ret) #else /* ! __CPU_mips64 => __CPU_mips2 or __CPU_mips */ -ATOMIC_FUNC_DECL(inc, "addiu %2, %1, 1", long, void, /* no return */ ) -ATOMIC_FUNC_DECL_CT(dec, "subu %2, %1, %3", 1, long, void, /* no return */ ) -ATOMIC_FUNC_DECL1(and, "and %2, %1, %3", long, void, /* no return */ ) -ATOMIC_FUNC_DECL1(or, "or %2, %1, %3", long, void, /* no return */ ) -ATOMIC_FUNC_DECL(inc_and_test, "addiu %2, %1, 1", long, long, (ret+1)==0 ) -ATOMIC_FUNC_DECL_CT(dec_and_test, "subu %2, %1, %3", 1,long, long, (ret-1)==0 ) -ATOMIC_FUNC_DECL2(get_and_set, "" /* nothing needed */, long, long, ret ) +ATOMIC_FUNC_DECL(inc, "addiu %2, %1, 1", long, void, /* no return */) +ATOMIC_FUNC_DECL_CT(dec, "subu %2, %1, %3", 1, long, void, /* no return */) +ATOMIC_FUNC_DECL1(and, "and %2, %1, %3", long, void, /* no return */) +ATOMIC_FUNC_DECL1(or, "or %2, %1, %3", long, void, /* no return */) +ATOMIC_FUNC_DECL(inc_and_test, "addiu %2, %1, 1", long, long, (ret + 1) == 0) +ATOMIC_FUNC_DECL_CT( + dec_and_test, "subu %2, %1, %3", 1, long, long, (ret - 1) == 0) +ATOMIC_FUNC_DECL2(get_and_set, "" /* nothing needed */, long, long, ret) ATOMIC_CMPXCHG_DECL(cmpxchg, long) -ATOMIC_FUNC_DECL1(add, "addu %2, %1, %3 \n\t move %1, %2", long, long, ret ) +ATOMIC_FUNC_DECL1(add, "addu %2, %1, %3 \n\t move %1, %2", long, long, ret) #endif /* __CPU_mips64 */ #define atomic_inc(var) atomic_inc_int(&(var)->val) #define atomic_dec(var) atomic_dec_int(&(var)->val) #define atomic_and(var, mask) atomic_and_int(&(var)->val, (mask)) -#define atomic_or(var, mask) atomic_or_int(&(var)->val, (mask)) +#define atomic_or(var, mask) atomic_or_int(&(var)->val, (mask)) #define atomic_dec_and_test(var) atomic_dec_and_test_int(&(var)->val) #define atomic_inc_and_test(var) atomic_inc_and_test_int(&(var)->val) #define atomic_get_and_set(var, i) atomic_get_and_set_int(&(var)->val, i) #define atomic_add(var, i) atomic_add_int(&(var)->val, i) -#define atomic_cmpxchg(var, old, new_v) \ +#define atomic_cmpxchg(var, old, new_v) \ atomic_cmpxchg_int(&(var)->val, old, new_v) /* with integrated membar */ #define mb_atomic_set_int(v, i) \ - do{ \ - membar(); \ - atomic_set_int(v, i); \ - }while(0) + do { \ + membar(); \ + atomic_set_int(v, i); \ + } while(0) - -inline static int mb_atomic_get_int(volatile int* v) +inline static int mb_atomic_get_int(volatile int *v) { membar(); return atomic_get_int(v); @@ -268,55 +271,55 @@ inline static int mb_atomic_get_int(volatile int* v) #define mb_atomic_inc_int(v) \ - do{ \ - membar(); \ - atomic_inc_int(v); \ - }while(0) + do { \ + membar(); \ + atomic_inc_int(v); \ + } while(0) #define mb_atomic_dec_int(v) \ - do{ \ - membar(); \ - atomic_dec_int(v); \ - }while(0) + do { \ + membar(); \ + atomic_dec_int(v); \ + } while(0) #define mb_atomic_or_int(v, m) \ - do{ \ - membar(); \ - atomic_or_int(v, m); \ - }while(0) + do { \ + membar(); \ + atomic_or_int(v, m); \ + } while(0) #define mb_atomic_and_int(v, m) \ - do{ \ - membar(); \ - atomic_and_int(v, m); \ - }while(0) + do { \ + membar(); \ + atomic_and_int(v, m); \ + } while(0) -inline static int mb_atomic_inc_and_test_int(volatile int* v) +inline static int mb_atomic_inc_and_test_int(volatile int *v) { membar(); return atomic_inc_and_test_int(v); } -inline static int mb_atomic_dec_and_test_int(volatile int* v) +inline static int mb_atomic_dec_and_test_int(volatile int *v) { membar(); return atomic_dec_and_test_int(v); } -inline static int mb_atomic_get_and_set_int(volatile int* v, int i) +inline static int mb_atomic_get_and_set_int(volatile int *v, int i) { membar(); return atomic_get_and_set_int(v, i); } -inline static int mb_atomic_cmpxchg_int(volatile int* v, int o, int n) +inline static int mb_atomic_cmpxchg_int(volatile int *v, int o, int n) { membar(); return atomic_cmpxchg_int(v, o, n); } -inline static int mb_atomic_add_int(volatile int* v, int i) +inline static int mb_atomic_add_int(volatile int *v, int i) { membar(); return atomic_add_int(v, i); @@ -324,14 +327,13 @@ inline static int mb_atomic_add_int(volatile int* v, int i) #define mb_atomic_set_long(v, i) \ - do{ \ - membar(); \ - atomic_set_long(v, i); \ - }while(0) - + do { \ + membar(); \ + atomic_set_long(v, i); \ + } while(0) -inline static long mb_atomic_get_long(volatile long* v) +inline static long mb_atomic_get_long(volatile long *v) { membar(); return atomic_get_long(v); @@ -339,56 +341,56 @@ inline static long mb_atomic_get_long(volatile long* v) #define mb_atomic_inc_long(v) \ - do{ \ - membar(); \ - atomic_inc_long(v); \ - }while(0) + do { \ + membar(); \ + atomic_inc_long(v); \ + } while(0) #define mb_atomic_dec_long(v) \ - do{ \ - membar(); \ - atomic_dec_long(v); \ - }while(0) + do { \ + membar(); \ + atomic_dec_long(v); \ + } while(0) #define mb_atomic_or_long(v, m) \ - do{ \ - membar(); \ - atomic_or_long(v, m); \ - }while(0) + do { \ + membar(); \ + atomic_or_long(v, m); \ + } while(0) #define mb_atomic_and_long(v, m) \ - do{ \ - membar(); \ - atomic_and_long(v, m); \ - }while(0) + do { \ + membar(); \ + atomic_and_long(v, m); \ + } while(0) -inline static long mb_atomic_inc_and_test_long(volatile long* v) +inline static long mb_atomic_inc_and_test_long(volatile long *v) { membar(); return atomic_inc_and_test_long(v); } -inline static long mb_atomic_dec_and_test_long(volatile long* v) +inline static long mb_atomic_dec_and_test_long(volatile long *v) { membar(); return atomic_dec_and_test_long(v); } -inline static long mb_atomic_get_and_set_long(volatile long* v, long l) +inline static long mb_atomic_get_and_set_long(volatile long *v, long l) { membar(); return atomic_get_and_set_long(v, l); } -inline static long mb_atomic_cmpxchg_long(volatile long* v, long o, long n) +inline static long mb_atomic_cmpxchg_long(volatile long *v, long o, long n) { membar(); return atomic_cmpxchg_long(v, o, n); } -inline static long mb_atomic_add_long(volatile long* v, long i) +inline static long mb_atomic_add_long(volatile long *v, long i) { membar(); return atomic_add_long(v, i); @@ -398,11 +400,11 @@ inline static long mb_atomic_add_long(volatile long* v, long i) #define mb_atomic_inc(var) mb_atomic_inc_int(&(var)->val) #define mb_atomic_dec(var) mb_atomic_dec_int(&(var)->val) #define mb_atomic_and(var, mask) mb_atomic_and_int(&(var)->val, (mask)) -#define mb_atomic_or(var, mask) mb_atomic_or_int(&(var)->val, (mask)) +#define mb_atomic_or(var, mask) mb_atomic_or_int(&(var)->val, (mask)) #define mb_atomic_dec_and_test(var) mb_atomic_dec_and_test_int(&(var)->val) #define mb_atomic_inc_and_test(var) mb_atomic_inc_and_test_int(&(var)->val) -#define mb_atomic_get(var) mb_atomic_get_int(&(var)->val) -#define mb_atomic_set(var, i) mb_atomic_set_int(&(var)->val, i) +#define mb_atomic_get(var) mb_atomic_get_int(&(var)->val) +#define mb_atomic_set(var, i) mb_atomic_set_int(&(var)->val, i) #define mb_atomic_get_and_set(var, i) mb_atomic_get_and_set_int(&(var)->val, i) #define mb_atomic_cmpxchg(var, o, n) mb_atomic_cmpxchg_int(&(var)->val, o, n) #define mb_atomic_add(var, i) mb_atomic_add_int(&(var)->val, i) diff --git a/src/core/atomic/atomic_native.h b/src/core/atomic/atomic_native.h index 5e83a642ea4..f18420a0045 100644 --- a/src/core/atomic/atomic_native.h +++ b/src/core/atomic/atomic_native.h @@ -1,4 +1,4 @@ -/* +/* * Copyright (C) 2006 iptelorg GmbH * * Permission to use, copy, modify, and distribute this software for any @@ -17,12 +17,12 @@ /** * @file * @brief Native (asm) atomic operations and memory barriers - * + * * Native (assembler) atomic operations and memory barriers. * \warning atomic ops do not include memory barriers, see atomic_ops.h for * more info. Expects atomic_t to be defined (#include "atomic_common.h") * - * Config defines: + * Config defines: * - CC_GCC_LIKE_ASM - the compiler support gcc style inline asm * - NOSMP - the code will be a little faster, but not SMP safe * - __CPU_i386, __CPU_x86_64, X86_OOSTORE - see atomic_x86.h @@ -44,8 +44,8 @@ #include "atomic_x86.h" -#elif defined __CPU_mips2 || defined __CPU_mips64 || \ - ( defined __CPU_mips && defined MIPS_HAS_LLSC ) +#elif defined __CPU_mips2 || defined __CPU_mips64 \ + || (defined __CPU_mips && defined MIPS_HAS_LLSC) #include "atomic_mips2.h" diff --git a/src/core/atomic/atomic_ppc.h b/src/core/atomic/atomic_ppc.h index 1d1e7889659..97682a08a63 100644 --- a/src/core/atomic/atomic_ppc.h +++ b/src/core/atomic/atomic_ppc.h @@ -1,4 +1,4 @@ -/* +/* * Copyright (C) 2006 iptelorg GmbH * * Permission to use, copy, modify, and distribute this software for any @@ -17,10 +17,10 @@ /** * @file * @brief Atomic operations and memory barriers (PowerPC and PowerPC64 versions) - * + * * Atomic operations and memory barriers (PowerPC and PowerPC64 versions) * \warning atomic ops do not include memory barriers see atomic_ops.h for - * more details. + * more details. * \warning not tested on ppc64 * * Config defines: @@ -43,33 +43,41 @@ #ifdef NOSMP -#define membar() asm volatile ("" : : : "memory") /* gcc do not cache barrier*/ -#define membar_read() membar() +#define membar() asm volatile("" : : : "memory") /* gcc do not cache barrier*/ +#define membar_read() membar() #define membar_write() membar() -#define membar_depends() do {} while(0) /* really empty, not even a cc bar. */ +#define membar_depends() \ + do { \ + } while(0) /* really empty, not even a cc bar. */ /* lock barriers: empty, not needed for NOSMP; the lock/unlock should already * contain gcc barriers*/ -#define membar_enter_lock() do {} while(0) -#define membar_leave_lock() do {} while(0) +#define membar_enter_lock() \ + do { \ + } while(0) +#define membar_leave_lock() \ + do { \ + } while(0) /* membars after or before atomic_ops or atomic_setget -> use these or * mb_() if you need a memory barrier in one of these * situations (on some archs where the atomic operations imply memory * barriers is better to use atomic_op_x(); membar_atomic_op() then * atomic_op_x(); membar()) */ -#define membar_atomic_op() membar() -#define membar_atomic_setget() membar() -#define membar_write_atomic_op() membar_write() -#define membar_write_atomic_setget() membar_write() -#define membar_read_atomic_op() membar_read() -#define membar_read_atomic_setget() membar_read() +#define membar_atomic_op() membar() +#define membar_atomic_setget() membar() +#define membar_write_atomic_op() membar_write() +#define membar_write_atomic_setget() membar_write() +#define membar_read_atomic_op() membar_read() +#define membar_read_atomic_setget() membar_read() #else -#define membar() asm volatile ("sync \n\t" : : : "memory") +#define membar() asm volatile("sync \n\t" : : : "memory") /* lwsync orders LoadLoad, LoadStore and StoreStore */ -#define membar_read() asm volatile ("lwsync \n\t" : : : "memory") +#define membar_read() asm volatile("lwsync \n\t" : : : "memory") /* on "normal" cached mem. eieio orders StoreStore */ -#define membar_write() asm volatile ("eieio \n\t" : : : "memory") -#define membar_depends() do {} while(0) /* really empty, not even a cc bar. */ +#define membar_write() asm volatile("eieio \n\t" : : : "memory") +#define membar_depends() \ + do { \ + } while(0) /* really empty, not even a cc bar. */ #define membar_enter_lock() asm volatile("lwsync \n\t" : : : "memory") /* for unlock lwsync will work too and is faster than sync * [IBM Prgramming Environments Manual, D.4.2.2] */ @@ -79,40 +87,40 @@ * situations (on some archs where the atomic operations imply memory * barriers is better to use atomic_op_x(); membar_atomic_op() then * atomic_op_x(); membar()) */ -#define membar_atomic_op() membar() -#define membar_atomic_setget() membar() -#define membar_write_atomic_op() membar_write() -#define membar_write_atomic_setget() membar_write() -#define membar_read_atomic_op() membar_read() -#define membar_read_atomic_setget() membar_read() +#define membar_atomic_op() membar() +#define membar_atomic_setget() membar() +#define membar_write_atomic_op() membar_write() +#define membar_write_atomic_setget() membar_write() +#define membar_read_atomic_op() membar_read() +#define membar_read_atomic_setget() membar_read() #endif /* NOSMP */ #define ATOMIC_ASM_OP0_int(op) \ "1: lwarx %0, 0, %2 \n\t" \ - " " op " \n\t" \ + " " op " \n\t" \ " stwcx. %0, 0, %2 \n\t" \ " bne- 1b \n\t" #define ATOMIC_ASM_OP3_int(op) \ "1: lwarx %0, 0, %2 \n\t" \ - " " op " \n\t" \ + " " op " \n\t" \ " stwcx. %3, 0, %2 \n\t" \ - " bne- 1b \n\t" \ + " bne- 1b \n\t" \ "2: \n\t" #ifdef __CPU_ppc64 #define ATOMIC_ASM_OP0_long(op) \ - "1: ldarx %0, 0, %2 \n\t" \ - " " op " \n\t" \ - " stdcx. %0, 0, %2 \n\t" \ + "1: ldarx %0, 0, %2 \n\t" \ + " " op " \n\t" \ + " stdcx. %0, 0, %2 \n\t" \ " bne- 1b \n\t" #define ATOMIC_ASM_OP3_long(op) \ - "1: ldarx %0, 0, %2 \n\t" \ - " " op " \n\t" \ - " stdcx. %3, 0, %2 \n\t" \ - " bne- 1b \n\t" \ + "1: ldarx %0, 0, %2 \n\t" \ + " " op " \n\t" \ + " stdcx. %3, 0, %2 \n\t" \ + " bne- 1b \n\t" \ "2: \n\t" #else /* __CPU_ppc */ @@ -121,87 +129,82 @@ #endif -#define ATOMIC_FUNC_DECL(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ - inline static RET_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var) \ - { \ - P_TYPE ret; \ - asm volatile( \ - ATOMIC_ASM_OP0_##P_TYPE(OP) \ - : "=&r"(ret), "=m"(*var) : "r"(var) : "cc" \ - ); \ - return RET_EXPR; \ +#define ATOMIC_FUNC_DECL(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ + inline static RET_TYPE atomic_##NAME##_##P_TYPE(volatile P_TYPE *var) \ + { \ + P_TYPE ret; \ + asm volatile(ATOMIC_ASM_OP0_##P_TYPE(OP) \ + : "=&r"(ret), "=m"(*var) \ + : "r"(var) \ + : "cc"); \ + return RET_EXPR; \ } /* same as above, but takes an extra param, v, which goes in %3 */ #define ATOMIC_FUNC_DECL1(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ - inline static RET_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var, \ - P_TYPE v) \ - { \ - P_TYPE ret; \ - asm volatile( \ - ATOMIC_ASM_OP0_##P_TYPE(OP) \ - : "=&r"(ret), "=m"(*var) : "r"(var), "r"(v) : "cc" \ - ); \ - return RET_EXPR; \ + inline static RET_TYPE atomic_##NAME##_##P_TYPE( \ + volatile P_TYPE *var, P_TYPE v) \ + { \ + P_TYPE ret; \ + asm volatile(ATOMIC_ASM_OP0_##P_TYPE(OP) \ + : "=&r"(ret), "=m"(*var) \ + : "r"(var), "r"(v) \ + : "cc"); \ + return RET_EXPR; \ } /* same as above, but uses ATOMIC_ASM_OP3, v in %3 and %3 not changed */ #define ATOMIC_FUNC_DECL3(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ - inline static RET_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var, \ - P_TYPE v) \ - { \ - P_TYPE ret; \ - asm volatile( \ - ATOMIC_ASM_OP3_##P_TYPE(OP) \ - : "=&r"(ret), "=m"(*var) : "r"(var), "r"(v) : "cc" \ - ); \ - return RET_EXPR; \ + inline static RET_TYPE atomic_##NAME##_##P_TYPE( \ + volatile P_TYPE *var, P_TYPE v) \ + { \ + P_TYPE ret; \ + asm volatile(ATOMIC_ASM_OP3_##P_TYPE(OP) \ + : "=&r"(ret), "=m"(*var) \ + : "r"(var), "r"(v) \ + : "cc"); \ + return RET_EXPR; \ } /* cmpxchg, %3=var, %0=*var, %4=old, %3=new */ -#define ATOMIC_CMPXCHG_DECL(NAME, P_TYPE) \ - inline static P_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var, \ - P_TYPE old, \ - P_TYPE new_v) \ - { \ - P_TYPE ret; \ - asm volatile( \ - ATOMIC_ASM_OP3_##P_TYPE("cmpw %0, %4 \n\t bne- 2f") \ - : "=&r"(ret), "=m"(*var) : "r"(var), "r"(new_v), "r"(old) \ - : "cc" \ - ); \ - return ret; \ +#define ATOMIC_CMPXCHG_DECL(NAME, P_TYPE) \ + inline static P_TYPE atomic_##NAME##_##P_TYPE( \ + volatile P_TYPE *var, P_TYPE old, P_TYPE new_v) \ + { \ + P_TYPE ret; \ + asm volatile(ATOMIC_ASM_OP3_##P_TYPE("cmpw %0, %4 \n\t bne- 2f") \ + : "=&r"(ret), "=m"(*var) \ + : "r"(var), "r"(new_v), "r"(old) \ + : "cc"); \ + return ret; \ } - - - -ATOMIC_FUNC_DECL(inc, "addic %0, %0, 1", int, void, /* no return */ ) -ATOMIC_FUNC_DECL(dec, "addic %0, %0, -1", int, void, /* no return */ ) -ATOMIC_FUNC_DECL1(and, "and %0, %0, %3", int, void, /* no return */ ) -ATOMIC_FUNC_DECL1(or, "or %0, %0, %3", int, void, /* no return */ ) -ATOMIC_FUNC_DECL(inc_and_test, "addic %0, %0, 1", int, int, (ret==0) ) -ATOMIC_FUNC_DECL(dec_and_test, "addic %0, %0, -1", int, int, (ret==0) ) -ATOMIC_FUNC_DECL3(get_and_set, /* no extra op needed */ , int, int, ret) +ATOMIC_FUNC_DECL(inc, "addic %0, %0, 1", int, void, /* no return */) +ATOMIC_FUNC_DECL(dec, "addic %0, %0, -1", int, void, /* no return */) +ATOMIC_FUNC_DECL1(and, "and %0, %0, %3", int, void, /* no return */) +ATOMIC_FUNC_DECL1(or, "or %0, %0, %3", int, void, /* no return */) +ATOMIC_FUNC_DECL(inc_and_test, "addic %0, %0, 1", int, int, (ret == 0)) +ATOMIC_FUNC_DECL(dec_and_test, "addic %0, %0, -1", int, int, (ret == 0)) +ATOMIC_FUNC_DECL3(get_and_set, /* no extra op needed */, int, int, ret) ATOMIC_CMPXCHG_DECL(cmpxchg, int) -ATOMIC_FUNC_DECL1(add, "add %0, %0, %3" , int, int, ret) - -ATOMIC_FUNC_DECL(inc, "addic %0, %0, 1", long, void, /* no return */ ) -ATOMIC_FUNC_DECL(dec, "addic %0, %0, -1", long, void, /* no return */ ) -ATOMIC_FUNC_DECL1(and, "and %0, %0, %3",long, void, /* no return */ ) -ATOMIC_FUNC_DECL1(or, "or %0, %0, %3", long, void, /* no return */ ) -ATOMIC_FUNC_DECL(inc_and_test, "addic %0, %0, 1", long, long, (ret==0) ) -ATOMIC_FUNC_DECL(dec_and_test, "addic %0, %0, -1", long, long, (ret==0) ) -ATOMIC_FUNC_DECL3(get_and_set, /* no extra op needed */ , long, long, ret) +ATOMIC_FUNC_DECL1(add, "add %0, %0, %3", int, int, ret) + +ATOMIC_FUNC_DECL(inc, "addic %0, %0, 1", long, void, /* no return */) +ATOMIC_FUNC_DECL(dec, "addic %0, %0, -1", long, void, /* no return */) +ATOMIC_FUNC_DECL1(and, "and %0, %0, %3", long, void, /* no return */) +ATOMIC_FUNC_DECL1(or, "or %0, %0, %3", long, void, /* no return */) +ATOMIC_FUNC_DECL(inc_and_test, "addic %0, %0, 1", long, long, (ret == 0)) +ATOMIC_FUNC_DECL(dec_and_test, "addic %0, %0, -1", long, long, (ret == 0)) +ATOMIC_FUNC_DECL3(get_and_set, /* no extra op needed */, long, long, ret) ATOMIC_CMPXCHG_DECL(cmpxchg, long) -ATOMIC_FUNC_DECL1(add, "add %0, %0, %3" , long, long, ret) +ATOMIC_FUNC_DECL1(add, "add %0, %0, %3", long, long, ret) #define atomic_inc(var) atomic_inc_int(&(var)->val) #define atomic_dec(var) atomic_dec_int(&(var)->val) #define atomic_and(var, mask) atomic_and_int(&(var)->val, (mask)) -#define atomic_or(var, mask) atomic_or_int(&(var)->val, (mask)) +#define atomic_or(var, mask) atomic_or_int(&(var)->val, (mask)) #define atomic_dec_and_test(var) atomic_dec_and_test_int(&(var)->val) #define atomic_inc_and_test(var) atomic_inc_and_test_int(&(var)->val) #define atomic_get_and_set(var, i) atomic_get_and_set_int(&(var)->val, i) @@ -212,14 +215,13 @@ ATOMIC_FUNC_DECL1(add, "add %0, %0, %3" , long, long, ret) /* with integrated membar */ #define mb_atomic_set_int(v, i) \ - do{ \ - membar(); \ - atomic_set_int(v, i); \ - }while(0) + do { \ + membar(); \ + atomic_set_int(v, i); \ + } while(0) - -inline static int mb_atomic_get_int(volatile int* v) +inline static int mb_atomic_get_int(volatile int *v) { membar(); return atomic_get_int(v); @@ -227,55 +229,55 @@ inline static int mb_atomic_get_int(volatile int* v) #define mb_atomic_inc_int(v) \ - do{ \ - membar(); \ - atomic_inc_int(v); \ - }while(0) + do { \ + membar(); \ + atomic_inc_int(v); \ + } while(0) #define mb_atomic_dec_int(v) \ - do{ \ - membar(); \ - atomic_dec_int(v); \ - }while(0) + do { \ + membar(); \ + atomic_dec_int(v); \ + } while(0) #define mb_atomic_or_int(v, m) \ - do{ \ - membar(); \ - atomic_or_int(v, m); \ - }while(0) + do { \ + membar(); \ + atomic_or_int(v, m); \ + } while(0) #define mb_atomic_and_int(v, m) \ - do{ \ - membar(); \ - atomic_and_int(v, m); \ - }while(0) + do { \ + membar(); \ + atomic_and_int(v, m); \ + } while(0) -inline static int mb_atomic_inc_and_test_int(volatile int* v) +inline static int mb_atomic_inc_and_test_int(volatile int *v) { membar(); return atomic_inc_and_test_int(v); } -inline static int mb_atomic_dec_and_test_int(volatile int* v) +inline static int mb_atomic_dec_and_test_int(volatile int *v) { membar(); return atomic_dec_and_test_int(v); } -inline static int mb_atomic_get_and_set_int(volatile int* v, int i) +inline static int mb_atomic_get_and_set_int(volatile int *v, int i) { membar(); return atomic_get_and_set_int(v, i); } -inline static int mb_atomic_cmpxchg_int(volatile int* v, int o, int n) +inline static int mb_atomic_cmpxchg_int(volatile int *v, int o, int n) { membar(); return atomic_cmpxchg_int(v, o, n); } -inline static int mb_atomic_add_int(volatile int* v, int i) +inline static int mb_atomic_add_int(volatile int *v, int i) { membar(); return atomic_add_int(v, i); @@ -283,14 +285,13 @@ inline static int mb_atomic_add_int(volatile int* v, int i) #define mb_atomic_set_long(v, i) \ - do{ \ - membar(); \ - atomic_set_long(v, i); \ - }while(0) - + do { \ + membar(); \ + atomic_set_long(v, i); \ + } while(0) -inline static long mb_atomic_get_long(volatile long* v) +inline static long mb_atomic_get_long(volatile long *v) { membar(); return atomic_get_long(v); @@ -298,74 +299,73 @@ inline static long mb_atomic_get_long(volatile long* v) #define mb_atomic_inc_long(v) \ - do{ \ - membar(); \ - atomic_inc_long(v); \ - }while(0) + do { \ + membar(); \ + atomic_inc_long(v); \ + } while(0) #define mb_atomic_dec_long(v) \ - do{ \ - membar(); \ - atomic_dec_long(v); \ - }while(0) + do { \ + membar(); \ + atomic_dec_long(v); \ + } while(0) #define mb_atomic_or_long(v, m) \ - do{ \ - membar(); \ - atomic_or_long(v, m); \ - }while(0) + do { \ + membar(); \ + atomic_or_long(v, m); \ + } while(0) #define mb_atomic_and_long(v, m) \ - do{ \ - membar(); \ - atomic_and_long(v, m); \ - }while(0) + do { \ + membar(); \ + atomic_and_long(v, m); \ + } while(0) -inline static long mb_atomic_inc_and_test_long(volatile long* v) +inline static long mb_atomic_inc_and_test_long(volatile long *v) { membar(); return atomic_inc_and_test_long(v); } -inline static long mb_atomic_dec_and_test_long(volatile long* v) +inline static long mb_atomic_dec_and_test_long(volatile long *v) { membar(); return atomic_dec_and_test_long(v); } -inline static long mb_atomic_get_and_set_long(volatile long* v, long l) +inline static long mb_atomic_get_and_set_long(volatile long *v, long l) { membar(); return atomic_get_and_set_long(v, l); } -inline static long mb_atomic_cmpxchg_long(volatile long* v, long o, long n) +inline static long mb_atomic_cmpxchg_long(volatile long *v, long o, long n) { membar(); return atomic_cmpxchg_long(v, o, n); } -inline static long mb_atomic_add_long(volatile long* v, long i) +inline static long mb_atomic_add_long(volatile long *v, long i) { membar(); return atomic_add_long(v, i); } - #define mb_atomic_inc(var) mb_atomic_inc_int(&(var)->val) #define mb_atomic_dec(var) mb_atomic_dec_int(&(var)->val) #define mb_atomic_and(var, mask) mb_atomic_and_int(&(var)->val, (mask)) -#define mb_atomic_or(var, mask) mb_atomic_or_int(&(var)->val, (mask)) +#define mb_atomic_or(var, mask) mb_atomic_or_int(&(var)->val, (mask)) #define mb_atomic_dec_and_test(var) mb_atomic_dec_and_test_int(&(var)->val) #define mb_atomic_inc_and_test(var) mb_atomic_inc_and_test_int(&(var)->val) -#define mb_atomic_get(var) mb_atomic_get_int(&(var)->val) -#define mb_atomic_set(var, i) mb_atomic_set_int(&(var)->val, i) +#define mb_atomic_get(var) mb_atomic_get_int(&(var)->val) +#define mb_atomic_set(var, i) mb_atomic_set_int(&(var)->val, i) #define mb_atomic_get_and_set(var, i) mb_atomic_get_and_set_int(&(var)->val, i) -#define mb_atomic_cmpxchg(v, o, n) atomic_cmpxchg_int(&(v)->val, o, n) -#define mb_atomic_add(v, a) atomic_add_int(&(v)->val, a) +#define mb_atomic_cmpxchg(v, o, n) atomic_cmpxchg_int(&(v)->val, o, n) +#define mb_atomic_add(v, a) atomic_add_int(&(v)->val, a) #endif diff --git a/src/core/atomic/atomic_sparc.h b/src/core/atomic/atomic_sparc.h index fce9714b282..6a1db75a18f 100644 --- a/src/core/atomic/atomic_sparc.h +++ b/src/core/atomic/atomic_sparc.h @@ -1,4 +1,4 @@ -/* +/* * Copyright (C) 2006 iptelorg GmbH * * Permission to use, copy, modify, and distribute this software for any @@ -17,11 +17,11 @@ /** * @file * @brief Memory barriers for SPARC32 ( version < v 9)) - * + * * Memory barriers for SPARC32 ( version < v 9)), see atomic_ops.h for more * details. * - * Config defines: + * Config defines: * - NOSMP * @ingroup atomic */ @@ -36,46 +36,55 @@ #warning "sparc32 atomic operations support not tested" #ifdef NOSMP -#define membar() asm volatile ("" : : : "memory") /* gcc do not cache barrier*/ -#define membar_read() membar() +#define membar() asm volatile("" : : : "memory") /* gcc do not cache barrier*/ +#define membar_read() membar() #define membar_write() membar() -#define membar_depends() do {} while(0) /* really empty, not even a cc bar. */ +#define membar_depends() \ + do { \ + } while(0) /* really empty, not even a cc bar. */ /* lock barrriers: empty, not needed for NOSMP; the lock/unlock should already * contain gcc barriers*/ -#define membar_enter_lock() do {} while(0) -#define membar_leave_lock() do {} while(0) +#define membar_enter_lock() \ + do { \ + } while(0) +#define membar_leave_lock() \ + do { \ + } while(0) /* membars after or before atomic_ops or atomic_setget -> use these or * mb_() if you need a memory barrier in one of these * situations (on some archs where the atomic operations imply memory * barriers is better to use atomic_op_x(); membar_atomic_op() then * atomic_op_x(); membar()) */ -#define membar_atomic_op() membar() -#define membar_atomic_setget() membar() -#define membar_write_atomic_op() membar_write() -#define membar_write_atomic_setget() membar_write() -#define membar_read_atomic_op() membar_read() -#define membar_read_atomic_setget() membar_read() +#define membar_atomic_op() membar() +#define membar_atomic_setget() membar() +#define membar_write_atomic_op() membar_write() +#define membar_write_atomic_setget() membar_write() +#define membar_read_atomic_op() membar_read() +#define membar_read_atomic_setget() membar_read() #else /* SMP */ -#define membar_write() asm volatile ("stbar \n\t" : : : "memory") +#define membar_write() asm volatile("stbar \n\t" : : : "memory") #define membar() membar_write() -#define membar_read() asm volatile ("" : : : "memory") -#define membar_depends() do {} while(0) /* really empty, not even a cc bar. */ -#define membar_enter_lock() do {} while(0) -#define membar_leave_lock() asm volatile ("stbar \n\t" : : : "memory") +#define membar_read() asm volatile("" : : : "memory") +#define membar_depends() \ + do { \ + } while(0) /* really empty, not even a cc bar. */ +#define membar_enter_lock() \ + do { \ + } while(0) +#define membar_leave_lock() asm volatile("stbar \n\t" : : : "memory") /* membars after or before atomic_ops or atomic_setget -> use these or * mb_() if you need a memory barrier in one of these * situations (on some archs where the atomic operations imply memory * barriers is better to use atomic_op_x(); membar_atomic_op() then * atomic_op_x(); membar()) */ -#define membar_atomic_op() membar() -#define membar_atomic_setget() membar() -#define membar_write_atomic_op() membar_write() -#define membar_write_atomic_setget() membar_write() -#define membar_read_atomic_op() membar_read() -#define membar_read_atomic_setget() membar_read() +#define membar_atomic_op() membar() +#define membar_atomic_setget() membar() +#define membar_write_atomic_op() membar_write() +#define membar_write_atomic_setget() membar_write() +#define membar_read_atomic_op() membar_read() +#define membar_read_atomic_setget() membar_read() #endif /* NOSMP */ - #endif diff --git a/src/core/atomic/atomic_sparc64.h b/src/core/atomic/atomic_sparc64.h index 98e1fb6e202..ca777770ed7 100644 --- a/src/core/atomic/atomic_sparc64.h +++ b/src/core/atomic/atomic_sparc64.h @@ -1,4 +1,4 @@ -/* +/* * Copyright (C) 2006 iptelorg GmbH * * Permission to use, copy, modify, and distribute this software for any @@ -17,7 +17,7 @@ /** * @file * @brief Atomic operations and memory barriers (SPARC64 version, 32 and 64 bit modes) - * + * * Atomic operations and memory barriers (SPARC64 version, 32 and 64 bit modes) * \warning atomic ops do not include memory barriers see atomic_ops.h for * more details. @@ -38,21 +38,23 @@ #ifdef __SUNPRO_C -#pragma error_messages (off,E_ASM_UNUSED_PARAM) +#pragma error_messages(off, E_ASM_UNUSED_PARAM) #endif /* try to guess if in SPARC64_MODE */ -#if ! defined SPARC64_MODE && \ - (defined __LP64__ || defined _LP64 || defined __arch64__) +#if !defined SPARC64_MODE \ + && (defined __LP64__ || defined _LP64 || defined __arch64__) #define SPARC64_MODE #endif #ifdef NOSMP -#define membar() asm volatile ("" : : : "memory") /* gcc do not cache barrier*/ -#define membar_read() membar() +#define membar() asm volatile("" : : : "memory") /* gcc do not cache barrier*/ +#define membar_read() membar() #define membar_write() membar() -#define membar_depends() do {} while(0) /* really empty, not even a cc bar. */ +#define membar_depends() \ + do { \ + } while(0) /* really empty, not even a cc bar. */ /* memory barriers for lock & unlock where lock & unlock are inline asm * functions that use atomic ops (and both of them use at least a store to * the lock). membar_enter_lock() is at most a StoreStore|StoreLoad barrier @@ -60,164 +62,170 @@ * (if the atomic ops on the specific architecture imply these barriers * => these macros will be empty) * Warning: these barriers don't force LoadLoad ordering between code - * before the lock/membar_enter_lock() and code + * before the lock/membar_enter_lock() and code * after membar_leave_lock()/unlock() * * Usage: lock(); membar_enter_lock(); .... ; membar_leave_lock(); unlock() */ -#define membar_enter_lock() do {} while(0) -#define membar_leave_lock() do {} while(0) +#define membar_enter_lock() \ + do { \ + } while(0) +#define membar_leave_lock() \ + do { \ + } while(0) /* membars after or before atomic_ops or atomic_setget -> use these or * mb_() if you need a memory barrier in one of these * situations (on some archs where the atomic operations imply memory * barriers is better to use atomic_op_x(); membar_atomic_op() then * atomic_op_x(); membar()) */ -#define membar_atomic_op() membar() -#define membar_atomic_setget() membar() -#define membar_write_atomic_op() membar_write() -#define membar_write_atomic_setget() membar_write() -#define membar_read_atomic_op() membar_read() -#define membar_read_atomic_setget() membar_read() +#define membar_atomic_op() membar() +#define membar_atomic_setget() membar() +#define membar_write_atomic_op() membar_write() +#define membar_write_atomic_setget() membar_write() +#define membar_read_atomic_op() membar_read() +#define membar_read_atomic_setget() membar_read() #else /* SMP */ -#define membar() \ - asm volatile ( \ +#define membar() \ + asm volatile( \ "membar #LoadLoad | #LoadStore | #StoreStore | #StoreLoad \n\t" \ - : : : "memory") - -#define membar_read() asm volatile ("membar #LoadLoad \n\t" : : : "memory") -#define membar_write() asm volatile ("membar #StoreStore \n\t" : : : "memory") -#define membar_depends() do {} while(0) /* really empty, not even a cc bar. */ + : \ + : \ + : "memory") + +#define membar_read() asm volatile("membar #LoadLoad \n\t" : : : "memory") +#define membar_write() asm volatile("membar #StoreStore \n\t" : : : "memory") +#define membar_depends() \ + do { \ + } while(0) /* really empty, not even a cc bar. */ #define membar_enter_lock() \ - asm volatile ("membar #StoreStore | #StoreLoad \n\t" : : : "memory"); + asm volatile("membar #StoreStore | #StoreLoad \n\t" : : : "memory"); #define membar_leave_lock() \ - asm volatile ("membar #LoadStore | #StoreStore \n\t" : : : "memory"); + asm volatile("membar #LoadStore | #StoreStore \n\t" : : : "memory"); /* membars after or before atomic_ops or atomic_setget -> use these or * mb_() if you need a memory barrier in one of these * situations (on some archs where the atomic operations imply memory * barriers is better to use atomic_op_x(); membar_atomic_op() then * atomic_op_x(); membar()) */ -#define membar_atomic_op() membar() -#define membar_atomic_setget() membar() -#define membar_write_atomic_op() membar_write() -#define membar_write_atomic_setget() membar_write() -#define membar_read_atomic_op() membar_read() -#define membar_read_atomic_setget() membar_read() +#define membar_atomic_op() membar() +#define membar_atomic_setget() membar() +#define membar_write_atomic_op() membar_write() +#define membar_write_atomic_setget() membar_write() +#define membar_read_atomic_op() membar_read() +#define membar_read_atomic_setget() membar_read() #endif /* NOSMP */ - /* 32 bit version, op should store the result in %1, and use %0 as input, * both %0 and %1 are modified */ -#define ATOMIC_ASM_OP_int(op)\ - " ldsw [%3], %0 \n\t" /* signed or lduw? */ \ - "1: " op " \n\t" \ - " cas [%3], %0, %1 \n\t" \ - " cmp %0, %1 \n\t" \ - " bne,a,pn %%icc, 1b \n\t" /* predict not taken, annul */ \ - " mov %1, %0\n\t" /* delay slot */ +#define ATOMIC_ASM_OP_int(op) \ + " ldsw [%3], %0 \n\t" /* signed or lduw? */ \ + "1: " op " \n\t" \ + " cas [%3], %0, %1 \n\t" \ + " cmp %0, %1 \n\t" \ + " bne,a,pn %%icc, 1b \n\t" /* predict not taken, annul */ \ + " mov %1, %0\n\t" /* delay slot */ #ifdef SPARC64_MODE /* 64 bit version, same as above */ -#define ATOMIC_ASM_OP_long(op)\ - " ldx [%3], %0 \n\t" \ - "1: " op " \n\t" \ - " casx [%3], %0, %1 \n\t" \ - " cmp %0, %1 \n\t" \ - " bne,a,pn %%xcc, 1b \n\t" /* predict not taken, annul */ \ - " mov %1, %0\n\t" /* delay slot */ - +#define ATOMIC_ASM_OP_long(op) \ + " ldx [%3], %0 \n\t" \ + "1: " op " \n\t" \ + " casx [%3], %0, %1 \n\t" \ + " cmp %0, %1 \n\t" \ + " bne,a,pn %%xcc, 1b \n\t" /* predict not taken, annul */ \ + " mov %1, %0\n\t" /* delay slot */ + #else /* no SPARC64_MODE => 32bit mode on a sparc64*/ #define ATOMIC_ASM_OP_long(op) ATOMIC_ASM_OP_int(op) #endif -#define ATOMIC_FUNC_DECL(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ - inline static RET_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var) \ - { \ - P_TYPE ret, tmp; \ - asm volatile( \ - ATOMIC_ASM_OP_##P_TYPE(OP) \ - : "=&r"(ret), "=&r"(tmp), "=m"(*var) : "r"(var) : "cc" \ - ); \ - return RET_EXPR; \ +#define ATOMIC_FUNC_DECL(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ + inline static RET_TYPE atomic_##NAME##_##P_TYPE(volatile P_TYPE *var) \ + { \ + P_TYPE ret, tmp; \ + asm volatile(ATOMIC_ASM_OP_##P_TYPE(OP) \ + : "=&r"(ret), "=&r"(tmp), "=m"(*var) \ + : "r"(var) \ + : "cc"); \ + return RET_EXPR; \ } /* same as above, but takes an extra param, v, which goes in %4 */ #define ATOMIC_FUNC_DECL1(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ - inline static RET_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var, \ - P_TYPE v) \ - { \ - P_TYPE ret, tmp; \ - asm volatile( \ - ATOMIC_ASM_OP_##P_TYPE(OP) \ - : "=&r"(ret), "=&r"(tmp), "=m"(*var) : "r"(var), "r"(v) : "cc" \ - ); \ - return RET_EXPR; \ + inline static RET_TYPE atomic_##NAME##_##P_TYPE( \ + volatile P_TYPE *var, P_TYPE v) \ + { \ + P_TYPE ret, tmp; \ + asm volatile(ATOMIC_ASM_OP_##P_TYPE(OP) \ + : "=&r"(ret), "=&r"(tmp), "=m"(*var) \ + : "r"(var), "r"(v) \ + : "cc"); \ + return RET_EXPR; \ } -/* same as above, but uses a short 1 op sequence +/* same as above, but uses a short 1 op sequence * %2 (or %1) is var, %0 is v and return (ret)*/ #define ATOMIC_FUNC_DECL1_RAW(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ - inline static RET_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var, \ - P_TYPE v) \ - { \ - P_TYPE ret; \ - asm volatile( \ - OP "\n\t" \ - : "=&r"(ret), "=m"(*var) : "r"(var), "0"(v) : "cc" \ - ); \ - return RET_EXPR; \ + inline static RET_TYPE atomic_##NAME##_##P_TYPE( \ + volatile P_TYPE *var, P_TYPE v) \ + { \ + P_TYPE ret; \ + asm volatile(OP "\n\t" \ + : "=&r"(ret), "=m"(*var) \ + : "r"(var), "0"(v) \ + : "cc"); \ + return RET_EXPR; \ } /* same as above, but takes two extra params, v, which goes in %4 * and uses a short 1 op sequence: * %2 (or %1) is var, %3 is v1 and %0 is v2 & result (ret) */ #define ATOMIC_FUNC_DECL2_CAS(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ - inline static RET_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var, \ - P_TYPE v1, P_TYPE v2) \ - { \ - P_TYPE ret; \ - asm volatile( \ - OP "\n\t" \ - : "=&r"(ret), "=m"(*var) : "r"(var), "r"(v1), "0"(v2) : "cc" \ - ); \ - return RET_EXPR; \ + inline static RET_TYPE atomic_##NAME##_##P_TYPE( \ + volatile P_TYPE *var, P_TYPE v1, P_TYPE v2) \ + { \ + P_TYPE ret; \ + asm volatile(OP "\n\t" \ + : "=&r"(ret), "=m"(*var) \ + : "r"(var), "r"(v1), "0"(v2) \ + : "cc"); \ + return RET_EXPR; \ } - -ATOMIC_FUNC_DECL(inc, "add %0, 1, %1", int, void, /* no return */ ) -ATOMIC_FUNC_DECL(dec, "sub %0, 1, %1", int, void, /* no return */ ) -ATOMIC_FUNC_DECL1(and, "and %0, %4, %1", int, void, /* no return */ ) -ATOMIC_FUNC_DECL1(or, "or %0, %4, %1", int, void, /* no return */ ) -ATOMIC_FUNC_DECL(inc_and_test, "add %0, 1, %1", int, int, ((ret+1)==0) ) -ATOMIC_FUNC_DECL(dec_and_test, "sub %0, 1, %1", int, int, ((ret-1)==0) ) +ATOMIC_FUNC_DECL(inc, "add %0, 1, %1", int, void, /* no return */) +ATOMIC_FUNC_DECL(dec, "sub %0, 1, %1", int, void, /* no return */) +ATOMIC_FUNC_DECL1(and, "and %0, %4, %1", int, void, /* no return */) +ATOMIC_FUNC_DECL1(or, "or %0, %4, %1", int, void, /* no return */) +ATOMIC_FUNC_DECL(inc_and_test, "add %0, 1, %1", int, int, ((ret + 1) == 0)) +ATOMIC_FUNC_DECL(dec_and_test, "sub %0, 1, %1", int, int, ((ret - 1) == 0)) /* deprecated but probably better than CAS for futexes */ ATOMIC_FUNC_DECL1_RAW(get_and_set, "swap [%2], %0", int, int, ret) /*ATOMIC_FUNC_DECL1(get_and_set, "mov %4, %1" , int, int, ret)*/ -ATOMIC_FUNC_DECL1(add, "add %0, %4, %1", int, int, ret+v) -ATOMIC_FUNC_DECL2_CAS(cmpxchg, "cas [%2], %3, %0", int, int, ret) - - -ATOMIC_FUNC_DECL(inc, "add %0, 1, %1", long, void, /* no return */ ) -ATOMIC_FUNC_DECL(dec, "sub %0, 1, %1", long, void, /* no return */ ) -ATOMIC_FUNC_DECL1(and, "and %0, %4, %1", long, void, /* no return */ ) -ATOMIC_FUNC_DECL1(or, "or %0, %4, %1", long, void, /* no return */ ) -ATOMIC_FUNC_DECL(inc_and_test, "add %0, 1, %1", long, long, ((ret+1)==0) ) -ATOMIC_FUNC_DECL(dec_and_test, "sub %0, 1, %1", long, long, ((ret-1)==0) ) -ATOMIC_FUNC_DECL1(get_and_set, "mov %4, %1" , long, long, ret) -ATOMIC_FUNC_DECL1(add, "add %0, %4, %1", long, long, ret+v) +ATOMIC_FUNC_DECL1(add, "add %0, %4, %1", int, int, ret + v) +ATOMIC_FUNC_DECL2_CAS(cmpxchg, "cas [%2], %3, %0", int, int, ret) + + +ATOMIC_FUNC_DECL(inc, "add %0, 1, %1", long, void, /* no return */) +ATOMIC_FUNC_DECL(dec, "sub %0, 1, %1", long, void, /* no return */) +ATOMIC_FUNC_DECL1(and, "and %0, %4, %1", long, void, /* no return */) +ATOMIC_FUNC_DECL1(or, "or %0, %4, %1", long, void, /* no return */) +ATOMIC_FUNC_DECL(inc_and_test, "add %0, 1, %1", long, long, ((ret + 1) == 0)) +ATOMIC_FUNC_DECL(dec_and_test, "sub %0, 1, %1", long, long, ((ret - 1) == 0)) +ATOMIC_FUNC_DECL1(get_and_set, "mov %4, %1", long, long, ret) +ATOMIC_FUNC_DECL1(add, "add %0, %4, %1", long, long, ret + v) #ifdef SPARC64_MODE -ATOMIC_FUNC_DECL2_CAS(cmpxchg, "casx [%2], %3, %0", long, long, ret) +ATOMIC_FUNC_DECL2_CAS(cmpxchg, "casx [%2], %3, %0", long, long, ret) #else -ATOMIC_FUNC_DECL2_CAS(cmpxchg, "cas [%2], %3, %0", long, long, ret) +ATOMIC_FUNC_DECL2_CAS(cmpxchg, "cas [%2], %3, %0", long, long, ret) #endif #define atomic_inc(var) atomic_inc_int(&(var)->val) #define atomic_dec(var) atomic_dec_int(&(var)->val) #define atomic_and(var, mask) atomic_and_int(&(var)->val, (mask)) -#define atomic_or(var, mask) atomic_or_int(&(var)->val, (mask)) +#define atomic_or(var, mask) atomic_or_int(&(var)->val, (mask)) #define atomic_dec_and_test(var) atomic_dec_and_test_int(&(var)->val) #define atomic_inc_and_test(var) atomic_inc_and_test_int(&(var)->val) #define atomic_get_and_set(var, i) atomic_get_and_set_int(&(var)->val, i) @@ -226,18 +234,16 @@ ATOMIC_FUNC_DECL2_CAS(cmpxchg, "cas [%2], %3, %0", long, long, ret) atomic_cmpxchg_int(&(var)->val, old, new_v) - /* with integrated membar */ #define mb_atomic_set_int(v, i) \ - do{ \ - membar(); \ - atomic_set_int(v, i); \ - }while(0) - + do { \ + membar(); \ + atomic_set_int(v, i); \ + } while(0) -inline static int mb_atomic_get_int(volatile int* v) +inline static int mb_atomic_get_int(volatile int *v) { membar(); return atomic_get_int(v); @@ -245,71 +251,69 @@ inline static int mb_atomic_get_int(volatile int* v) #define mb_atomic_inc_int(v) \ - do{ \ - membar(); \ - atomic_inc_int(v); \ - }while(0) + do { \ + membar(); \ + atomic_inc_int(v); \ + } while(0) #define mb_atomic_dec_int(v) \ - do{ \ - membar(); \ - atomic_dec_int(v); \ - }while(0) + do { \ + membar(); \ + atomic_dec_int(v); \ + } while(0) #define mb_atomic_or_int(v, m) \ - do{ \ - membar(); \ - atomic_or_int(v, m); \ - }while(0) + do { \ + membar(); \ + atomic_or_int(v, m); \ + } while(0) #define mb_atomic_and_int(v, m) \ - do{ \ - membar(); \ - atomic_and_int(v, m); \ - }while(0) + do { \ + membar(); \ + atomic_and_int(v, m); \ + } while(0) -inline static int mb_atomic_inc_and_test_int(volatile int* v) +inline static int mb_atomic_inc_and_test_int(volatile int *v) { membar(); return atomic_inc_and_test_int(v); } -inline static int mb_atomic_dec_and_test_int(volatile int* v) +inline static int mb_atomic_dec_and_test_int(volatile int *v) { membar(); return atomic_dec_and_test_int(v); } -inline static int mb_atomic_get_and_set_int(volatile int* v, int i) +inline static int mb_atomic_get_and_set_int(volatile int *v, int i) { membar(); return atomic_get_and_set_int(v, i); } -inline static int mb_atomic_cmpxchg_int(volatile int* v, int o, int n) +inline static int mb_atomic_cmpxchg_int(volatile int *v, int o, int n) { membar(); return atomic_cmpxchg_int(v, o, n); } -inline static int mb_atomic_add_int(volatile int* v, int i) +inline static int mb_atomic_add_int(volatile int *v, int i) { membar(); return atomic_add_int(v, i); } - #define mb_atomic_set_long(v, i) \ - do{ \ - membar(); \ - atomic_set_long(v, i); \ - }while(0) - + do { \ + membar(); \ + atomic_set_long(v, i); \ + } while(0) -inline static long mb_atomic_get_long(volatile long* v) +inline static long mb_atomic_get_long(volatile long *v) { membar(); return atomic_get_long(v); @@ -317,56 +321,56 @@ inline static long mb_atomic_get_long(volatile long* v) #define mb_atomic_inc_long(v) \ - do{ \ - membar(); \ - atomic_inc_long(v); \ - }while(0) + do { \ + membar(); \ + atomic_inc_long(v); \ + } while(0) #define mb_atomic_dec_long(v) \ - do{ \ - membar(); \ - atomic_dec_long(v); \ - }while(0) + do { \ + membar(); \ + atomic_dec_long(v); \ + } while(0) #define mb_atomic_or_long(v, m) \ - do{ \ - membar(); \ - atomic_or_long(v, m); \ - }while(0) + do { \ + membar(); \ + atomic_or_long(v, m); \ + } while(0) #define mb_atomic_and_long(v, m) \ - do{ \ - membar(); \ - atomic_and_long(v, m); \ - }while(0) + do { \ + membar(); \ + atomic_and_long(v, m); \ + } while(0) -inline static long mb_atomic_inc_and_test_long(volatile long* v) +inline static long mb_atomic_inc_and_test_long(volatile long *v) { membar(); return atomic_inc_and_test_long(v); } -inline static long mb_atomic_dec_and_test_long(volatile long* v) +inline static long mb_atomic_dec_and_test_long(volatile long *v) { membar(); return atomic_dec_and_test_long(v); } -inline static long mb_atomic_get_and_set_long(volatile long* v, long l) +inline static long mb_atomic_get_and_set_long(volatile long *v, long l) { membar(); return atomic_get_and_set_long(v, l); } -inline static long mb_atomic_cmpxchg_long(volatile long* v, long o, long n) +inline static long mb_atomic_cmpxchg_long(volatile long *v, long o, long n) { membar(); return atomic_cmpxchg_long(v, o, n); } -inline static long mb_atomic_add_long(volatile long* v, long i) +inline static long mb_atomic_add_long(volatile long *v, long i) { membar(); return atomic_add_long(v, i); @@ -376,11 +380,11 @@ inline static long mb_atomic_add_long(volatile long* v, long i) #define mb_atomic_inc(var) mb_atomic_inc_int(&(var)->val) #define mb_atomic_dec(var) mb_atomic_dec_int(&(var)->val) #define mb_atomic_and(var, mask) mb_atomic_and_int(&(var)->val, (mask)) -#define mb_atomic_or(var, mask) mb_atomic_or_int(&(var)->val, (mask)) +#define mb_atomic_or(var, mask) mb_atomic_or_int(&(var)->val, (mask)) #define mb_atomic_dec_and_test(var) mb_atomic_dec_and_test_int(&(var)->val) #define mb_atomic_inc_and_test(var) mb_atomic_inc_and_test_int(&(var)->val) -#define mb_atomic_get(var) mb_atomic_get_int(&(var)->val) -#define mb_atomic_set(var, i) mb_atomic_set_int(&(var)->val, i) +#define mb_atomic_get(var) mb_atomic_get_int(&(var)->val) +#define mb_atomic_set(var, i) mb_atomic_set_int(&(var)->val, i) #define mb_atomic_get_and_set(var, i) mb_atomic_get_and_set_int(&(var)->val, i) #define mb_atomic_cmpxchg(var, o, n) mb_atomic_cmpxchg_int(&(var)->val, o, n) #define mb_atomic_add(var, i) mb_atomic_add_int(&(var)->val, i) diff --git a/src/core/atomic/atomic_unknown.h b/src/core/atomic/atomic_unknown.h index d4610719a2e..323aacf9fff 100644 --- a/src/core/atomic/atomic_unknown.h +++ b/src/core/atomic/atomic_unknown.h @@ -1,4 +1,4 @@ -/* +/* * Copyright (C) 2006 iptelorg GmbH * * Permission to use, copy, modify, and distribute this software for any @@ -22,7 +22,7 @@ * (for architectures not yet supported via inline assembler). * * \warning atomic ops do not include memory barriers, see atomic_ops.h - * for more details + * for more details * * Config defines: * - NOSMP (membars are null in this case) @@ -38,15 +38,16 @@ #include "../lock_ops.h" - #ifndef HAVE_ASM_INLINE_MEMBAR #ifdef NOSMP -#define membar() do {} while(0) +#define membar() \ + do { \ + } while(0) #else /* SMP */ #if defined __CPU_arm64 && defined __OS_darwin - /* fallback to locking-variant of atomic ops for OSes used for development +/* fallback to locking-variant of atomic ops for OSes used for development * - MacOS with Apple silicon */ #else #warning no native memory barrier implementations, falling back to slow lock \ @@ -55,12 +56,12 @@ #define MEMBAR_USES_LOCK -extern gen_lock_t* __membar_lock; /* init in atomic_ops.c */ -#define _membar_lock lock_get(__membar_lock) -#define _membar_unlock lock_release(__membar_lock) +extern gen_lock_t *__membar_lock; /* init in atomic_ops.c */ +#define _membar_lock lock_get(__membar_lock) +#define _membar_unlock lock_release(__membar_lock) -/* memory barriers - * not a known cpu -> fall back unlock/lock: safe but costly (it should +/* memory barriers + * not a known cpu -> fall back unlock/lock: safe but costly (it should * include a memory barrier effect) * lock/unlock does not imply a full memory barrier effect (it allows mixing * operations from before the lock with operations after the lock _inside_ @@ -70,40 +71,46 @@ extern gen_lock_t* __membar_lock; /* init in atomic_ops.c */ * with a full memory barrier * => to be safe we must use either unlock; lock or lock; unlock; lock; unlock * --andrei*/ -#define membar() \ - do{\ +#define membar() \ + do { \ _membar_unlock; \ - _membar_lock; \ + _membar_lock; \ } while(0) #endif /* NOSMP */ #define membar_write() membar() -#define membar_read() membar() +#define membar_read() membar() #ifndef __CPU_alpha -#define membar_depends() do {} while(0) /* really empty, not even a cc bar. */ +#define membar_depends() \ + do { \ + } while(0) /* really empty, not even a cc bar. */ #else /* really slow */ -#define membar_depends() membar_read() +#define membar_depends() membar_read() #endif -#define membar_enter_lock() do {} while(0) -#define membar_leave_lock() do {} while(0) +#define membar_enter_lock() \ + do { \ + } while(0) +#define membar_leave_lock() \ + do { \ + } while(0) /* membars after or before atomic_ops or atomic_setget -> use these or * mb_() if you need a memory barrier in one of these * situations (on some archs where the atomic operations imply memory * barriers is better to use atomic_op_x(); membar_atomic_op() then * atomic_op_x(); membar()) */ -#define membar_atomic_op() membar() -#define membar_atomic_setget() membar() -#define membar_write_atomic_op() membar_write() -#define membar_write_atomic_setget() membar_write() -#define membar_read_atomic_op() membar_read() -#define membar_read_atomic_setget() membar_read() +#define membar_atomic_op() membar() +#define membar_atomic_setget() membar() +#define membar_write_atomic_op() membar_write() +#define membar_write_atomic_setget() membar_write() +#define membar_read_atomic_op() membar_read() +#define membar_read_atomic_setget() membar_read() #endif /* HAVE_ASM_INLINE_MEMBAR */ @@ -120,21 +127,21 @@ extern gen_lock_t* __membar_lock; /* init in atomic_ops.c */ #endif #endif /* GEN_LOCK_SET_T_UNLIMITED */ -#ifdef ATOMIC_OPS_USE_LOCK_SET -#define _ATOMIC_LS_SIZE 256 +#ifdef ATOMIC_OPS_USE_LOCK_SET +#define _ATOMIC_LS_SIZE 256 /* hash after the variable address: ignore first 4 bits since * vars are generally alloc'ed at at least 16 bytes multiples */ -#define _atomic_ls_hash(v) ((((unsigned long)(v))>>4)&(_ATOMIC_LS_SIZE-1)) -extern gen_lock_set_t* _atomic_lock_set; +#define _atomic_ls_hash(v) ((((unsigned long)(v)) >> 4) & (_ATOMIC_LS_SIZE - 1)) +extern gen_lock_set_t *_atomic_lock_set; -#define atomic_lock(v) lock_set_get(_atomic_lock_set, _atomic_ls_hash(v)) +#define atomic_lock(v) lock_set_get(_atomic_lock_set, _atomic_ls_hash(v)) #define atomic_unlock(v) lock_set_release(_atomic_lock_set, _atomic_ls_hash(v)) #else -extern gen_lock_t* _atomic_lock; /* declared and init in ../atomic_ops.c */ +extern gen_lock_t *_atomic_lock; /* declared and init in ../atomic_ops.c */ -#define atomic_lock(v) lock_get(_atomic_lock) -#define atomic_unlock(v) lock_release(_atomic_lock) +#define atomic_lock(v) lock_get(_atomic_lock) +#define atomic_unlock(v) lock_release(_atomic_lock) #endif /* ATOMIC_OPS_USE_LOCK_SET */ @@ -142,94 +149,94 @@ extern gen_lock_t* _atomic_lock; /* declared and init in ../atomic_ops.c */ /* OP can include var (function param), no other var. is declared */ -#define ATOMIC_FUNC_DECL(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ - inline static RET_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var) \ - { \ - atomic_lock(var); \ - OP ; \ - atomic_unlock(var); \ - return RET_EXPR; \ +#define ATOMIC_FUNC_DECL(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ + inline static RET_TYPE atomic_##NAME##_##P_TYPE(volatile P_TYPE *var) \ + { \ + atomic_lock(var); \ + OP; \ + atomic_unlock(var); \ + return RET_EXPR; \ } /* like above, but takes an extra param: v => * OP can use var and v (function params) */ #define ATOMIC_FUNC_DECL1(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ - inline static RET_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var, \ - P_TYPE v) \ - { \ - atomic_lock(var); \ - OP ; \ - atomic_unlock(var); \ - return RET_EXPR; \ + inline static RET_TYPE atomic_##NAME##_##P_TYPE( \ + volatile P_TYPE *var, P_TYPE v) \ + { \ + atomic_lock(var); \ + OP; \ + atomic_unlock(var); \ + return RET_EXPR; \ } /* OP can include var (function param), and ret (return) * ( like ATOMIC_FUNC_DECL, but includes ret) */ -#define ATOMIC_FUNC_DECL_RET(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ - inline static RET_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var) \ - { \ - P_TYPE ret; \ - atomic_lock(var); \ - OP ; \ - atomic_unlock(var); \ - return RET_EXPR; \ +#define ATOMIC_FUNC_DECL_RET(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ + inline static RET_TYPE atomic_##NAME##_##P_TYPE(volatile P_TYPE *var) \ + { \ + P_TYPE ret; \ + atomic_lock(var); \ + OP; \ + atomic_unlock(var); \ + return RET_EXPR; \ } /* like ATOMIC_FUNC_DECL1, but declares an extra variable: P_TYPE ret */ #define ATOMIC_FUNC_DECL1_RET(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ - inline static RET_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var, \ - P_TYPE v) \ - { \ - P_TYPE ret; \ - atomic_lock(var); \ - OP ; \ - atomic_unlock(var); \ - return RET_EXPR; \ + inline static RET_TYPE atomic_##NAME##_##P_TYPE( \ + volatile P_TYPE *var, P_TYPE v) \ + { \ + P_TYPE ret; \ + atomic_lock(var); \ + OP; \ + atomic_unlock(var); \ + return RET_EXPR; \ } /* like ATOMIC_FUNC_DECL1_RET, but takes an extra param */ #define ATOMIC_FUNC_DECL2_RET(NAME, OP, P_TYPE, RET_TYPE, RET_EXPR) \ - inline static RET_TYPE atomic_##NAME##_##P_TYPE (volatile P_TYPE *var, \ - P_TYPE v1, P_TYPE v2)\ - { \ - P_TYPE ret; \ - atomic_lock(var); \ - OP ; \ - atomic_unlock(var); \ - return RET_EXPR; \ + inline static RET_TYPE atomic_##NAME##_##P_TYPE( \ + volatile P_TYPE *var, P_TYPE v1, P_TYPE v2) \ + { \ + P_TYPE ret; \ + atomic_lock(var); \ + OP; \ + atomic_unlock(var); \ + return RET_EXPR; \ } -ATOMIC_FUNC_DECL(inc, (*var)++, int, void, /* no return */ ) -ATOMIC_FUNC_DECL(dec, (*var)--, int, void, /* no return */ ) -ATOMIC_FUNC_DECL1(and, *var&=v, int, void, /* no return */ ) -ATOMIC_FUNC_DECL1(or, *var|=v, int, void, /* no return */ ) -ATOMIC_FUNC_DECL_RET(inc_and_test, ret=++(*var), int, int, (ret==0) ) -ATOMIC_FUNC_DECL_RET(dec_and_test, ret=--(*var), int, int, (ret==0) ) -ATOMIC_FUNC_DECL1_RET(get_and_set, ret=*var;*var=v , int, int, ret) -ATOMIC_FUNC_DECL2_RET(cmpxchg, ret=*var;\ - *var=(((ret!=v1)-1)&v2)+(~((ret!=v1)-1)&ret),\ - int, int, ret) -ATOMIC_FUNC_DECL1_RET(add, *var+=v;ret=*var, int, int, ret ) - -ATOMIC_FUNC_DECL(inc, (*var)++, long, void, /* no return */ ) -ATOMIC_FUNC_DECL(dec, (*var)--, long, void, /* no return */ ) -ATOMIC_FUNC_DECL1(and, *var&=v, long, void, /* no return */ ) -ATOMIC_FUNC_DECL1(or, *var|=v, long, void, /* no return */ ) -ATOMIC_FUNC_DECL_RET(inc_and_test, ret=++(*var), long, long, (ret==0) ) -ATOMIC_FUNC_DECL_RET(dec_and_test, ret=--(*var), long, long, (ret==0) ) -ATOMIC_FUNC_DECL1_RET(get_and_set, ret=*var;*var=v , long, long, ret) -ATOMIC_FUNC_DECL2_RET(cmpxchg, ret=*var;\ - *var=(((ret!=v1)-1)&v2)+(~((ret!=v1)-1)&ret),\ - long, long, ret) -ATOMIC_FUNC_DECL1_RET(add, *var+=v;ret=*var, long, long, ret ) +ATOMIC_FUNC_DECL(inc, (*var)++, int, void, /* no return */) +ATOMIC_FUNC_DECL(dec, (*var)--, int, void, /* no return */) +ATOMIC_FUNC_DECL1(and, *var &= v, int, void, /* no return */) +ATOMIC_FUNC_DECL1(or, *var |= v, int, void, /* no return */) +ATOMIC_FUNC_DECL_RET(inc_and_test, ret = ++(*var), int, int, (ret == 0)) +ATOMIC_FUNC_DECL_RET(dec_and_test, ret = --(*var), int, int, (ret == 0)) +ATOMIC_FUNC_DECL1_RET(get_and_set, ret = *var; *var = v, int, int, ret) +ATOMIC_FUNC_DECL2_RET(cmpxchg, ret = *var; *var = (((ret != v1) - 1) & v2) + + (~((ret != v1) - 1) & ret), + int, int, ret) +ATOMIC_FUNC_DECL1_RET(add, *var += v; ret = *var, int, int, ret) + +ATOMIC_FUNC_DECL(inc, (*var)++, long, void, /* no return */) +ATOMIC_FUNC_DECL(dec, (*var)--, long, void, /* no return */) +ATOMIC_FUNC_DECL1(and, *var &= v, long, void, /* no return */) +ATOMIC_FUNC_DECL1(or, *var |= v, long, void, /* no return */) +ATOMIC_FUNC_DECL_RET(inc_and_test, ret = ++(*var), long, long, (ret == 0)) +ATOMIC_FUNC_DECL_RET(dec_and_test, ret = --(*var), long, long, (ret == 0)) +ATOMIC_FUNC_DECL1_RET(get_and_set, ret = *var; *var = v, long, long, ret) +ATOMIC_FUNC_DECL2_RET(cmpxchg, ret = *var; *var = (((ret != v1) - 1) & v2) + + (~((ret != v1) - 1) & ret), + long, long, ret) +ATOMIC_FUNC_DECL1_RET(add, *var += v; ret = *var, long, long, ret) #define atomic_inc(var) atomic_inc_int(&(var)->val) #define atomic_dec(var) atomic_dec_int(&(var)->val) #define atomic_and(var, mask) atomic_and_int(&(var)->val, (mask)) -#define atomic_or(var, mask) atomic_or_int(&(var)->val, (mask)) +#define atomic_or(var, mask) atomic_or_int(&(var)->val, (mask)) #define atomic_dec_and_test(var) atomic_dec_and_test_int(&(var)->val) #define atomic_inc_and_test(var) atomic_inc_and_test_int(&(var)->val) #define atomic_get_and_set(var, i) atomic_get_and_set_int(&(var)->val, i) @@ -239,71 +246,71 @@ ATOMIC_FUNC_DECL1_RET(add, *var+=v;ret=*var, long, long, ret ) /* memory barrier versions, the same as "normal" versions (since the - * locks act as membars), * except fot * the set/get + * locks act as membars), * except fot * the set/get */ /* mb_atomic_{set,get} use membar() : if we're lucky we have membars * for the arch. (e.g. sparc32) => membar() might be cheaper than lock/unlock */ #define mb_atomic_set_int(v, i) \ - do{ \ - membar(); \ - atomic_set_int(v, i); \ - }while(0) + do { \ + membar(); \ + atomic_set_int(v, i); \ + } while(0) -inline static int mb_atomic_get_int(volatile int* v) +inline static int mb_atomic_get_int(volatile int *v) { - membar(); - return atomic_get_int(v); + membar(); + return atomic_get_int(v); } #define mb_atomic_set_long(v, i) \ - do{ \ - membar(); \ - atomic_set_long(v, i); \ - }while(0) + do { \ + membar(); \ + atomic_set_long(v, i); \ + } while(0) -inline static long mb_atomic_get_long(volatile long* v) +inline static long mb_atomic_get_long(volatile long *v) { - membar(); - return atomic_get_long(v); + membar(); + return atomic_get_long(v); } /* the rest are the same as the non membar version (the locks have a membar * effect) */ -#define mb_atomic_inc_int(v) atomic_inc_int(v) -#define mb_atomic_dec_int(v) atomic_dec_int(v) -#define mb_atomic_or_int(v, m) atomic_or_int(v, m) -#define mb_atomic_and_int(v, m) atomic_and_int(v, m) -#define mb_atomic_inc_and_test_int(v) atomic_inc_and_test_int(v) -#define mb_atomic_dec_and_test_int(v) atomic_dec_and_test_int(v) -#define mb_atomic_get_and_set_int(v, i) atomic_get_and_set_int(v, i) -#define mb_atomic_cmpxchg_int(v, o, n) atomic_cmpxchg_int(v, o, n) -#define mb_atomic_add_int(v, i) atomic_add_int(v, i) - -#define mb_atomic_inc_long(v) atomic_inc_long(v) -#define mb_atomic_dec_long(v) atomic_dec_long(v) -#define mb_atomic_or_long(v, m) atomic_or_long(v, m) -#define mb_atomic_and_long(v, m) atomic_and_long(v, m) -#define mb_atomic_inc_and_test_long(v) atomic_inc_and_test_long(v) -#define mb_atomic_dec_and_test_long(v) atomic_dec_and_test_long(v) -#define mb_atomic_get_and_set_long(v, i) atomic_get_and_set_long(v, i) -#define mb_atomic_cmpxchg_long(v, o, n) atomic_cmpxchg_long(v, o, n) -#define mb_atomic_add_long(v, i) atomic_add_long(v, i) +#define mb_atomic_inc_int(v) atomic_inc_int(v) +#define mb_atomic_dec_int(v) atomic_dec_int(v) +#define mb_atomic_or_int(v, m) atomic_or_int(v, m) +#define mb_atomic_and_int(v, m) atomic_and_int(v, m) +#define mb_atomic_inc_and_test_int(v) atomic_inc_and_test_int(v) +#define mb_atomic_dec_and_test_int(v) atomic_dec_and_test_int(v) +#define mb_atomic_get_and_set_int(v, i) atomic_get_and_set_int(v, i) +#define mb_atomic_cmpxchg_int(v, o, n) atomic_cmpxchg_int(v, o, n) +#define mb_atomic_add_int(v, i) atomic_add_int(v, i) + +#define mb_atomic_inc_long(v) atomic_inc_long(v) +#define mb_atomic_dec_long(v) atomic_dec_long(v) +#define mb_atomic_or_long(v, m) atomic_or_long(v, m) +#define mb_atomic_and_long(v, m) atomic_and_long(v, m) +#define mb_atomic_inc_and_test_long(v) atomic_inc_and_test_long(v) +#define mb_atomic_dec_and_test_long(v) atomic_dec_and_test_long(v) +#define mb_atomic_get_and_set_long(v, i) atomic_get_and_set_long(v, i) +#define mb_atomic_cmpxchg_long(v, o, n) atomic_cmpxchg_long(v, o, n) +#define mb_atomic_add_long(v, i) atomic_add_long(v, i) #define mb_atomic_inc(var) mb_atomic_inc_int(&(var)->val) #define mb_atomic_dec(var) mb_atomic_dec_int(&(var)->val) #define mb_atomic_and(var, mask) mb_atomic_and_int(&(var)->val, (mask)) -#define mb_atomic_or(var, mask) mb_atomic_or_int(&(var)->val, (mask)) +#define mb_atomic_or(var, mask) mb_atomic_or_int(&(var)->val, (mask)) #define mb_atomic_dec_and_test(var) mb_atomic_dec_and_test_int(&(var)->val) #define mb_atomic_inc_and_test(var) mb_atomic_inc_and_test_int(&(var)->val) #define mb_atomic_get_and_set(var, i) mb_atomic_get_and_set_int(&(var)->val, i) -#define mb_atomic_cmpxchg(v, o, n) atomic_cmpxchg_int(&(v)->val, o, n) -#define mb_atomic_add(v, i) atomic_add_int(&(v)->val, i) +#define mb_atomic_cmpxchg(v, o, n) atomic_cmpxchg_int(&(v)->val, o, n) +#define mb_atomic_add(v, i) atomic_add_int(&(v)->val, i) -#define mb_atomic_get(var) mb_atomic_get_int(&(var)->val) -#define mb_atomic_set(var, i) mb_atomic_set_int(&(var)->val, i) +#define mb_atomic_get(var) mb_atomic_get_int(&(var)->val) +#define mb_atomic_set(var, i) mb_atomic_set_int(&(var)->val, i) #endif /* if HAVE_ASM_INLINE_ATOMIC_OPS */ diff --git a/src/core/atomic/atomic_x86.h b/src/core/atomic/atomic_x86.h index 536d1b21057..03a6c2bb9f2 100644 --- a/src/core/atomic/atomic_x86.h +++ b/src/core/atomic/atomic_x86.h @@ -1,4 +1,4 @@ -/* +/* * Copyright (C) 2006 iptelorg GmbH * * Permission to use, copy, modify, and distribute this software for any @@ -17,7 +17,7 @@ /** * @file * @brief Atomic operations and memory barriers (x86 and x86_64/amd64 specific) - * + * * Atomic operations and memory barriers (x86 and x86_64/amd64 specific) * \warning atomic ops do not include memory barriers, see atomic_ops.h for more * details. @@ -39,7 +39,7 @@ #define HAVE_ASM_INLINE_MEMBAR #ifdef NOSMP -#define __LOCK_PREF +#define __LOCK_PREF #else #define __LOCK_PREF "lock ;" #endif @@ -49,31 +49,43 @@ #ifdef NOSMP -#define membar() asm volatile ("" : : : "memory") -#define membar_read() membar() -#define membar_write() membar() -#define membar_depends() do {} while(0) /* really empty, not even a cc bar. */ +#define membar() asm volatile("" : : : "memory") +#define membar_read() membar() +#define membar_write() membar() +#define membar_depends() \ + do { \ + } while(0) /* really empty, not even a cc bar. */ /* lock barrriers: empty, not needed for NOSMP; the lock/unlock should already * contain gcc barriers*/ -#define membar_enter_lock() do {} while(0) -#define membar_leave_lock() do {} while(0) +#define membar_enter_lock() \ + do { \ + } while(0) +#define membar_leave_lock() \ + do { \ + } while(0) /* membars after or before atomic_ops or atomic_setget -> use these or * mb_() if you need a memory barrier in one of these * situations (on some archs where the atomic operations imply memory * barriers is better to use atomic_op_x(); membar_atomic_op() then * atomic_op_x(); membar()) */ -#define membar_atomic_op() do {} while(0) -#define membar_atomic_setget() membar() -#define membar_write_atomic_op() do {} while(0) -#define membar_write_atomic_setget() membar_write() -#define membar_read_atomic_op() do {} while(0) -#define membar_read_atomic_setget() membar_read() +#define membar_atomic_op() \ + do { \ + } while(0) +#define membar_atomic_setget() membar() +#define membar_write_atomic_op() \ + do { \ + } while(0) +#define membar_write_atomic_setget() membar_write() +#define membar_read_atomic_op() \ + do { \ + } while(0) +#define membar_read_atomic_setget() membar_read() #else /* although most x86 do stores in order, we're playing it safe and use * oostore ready write barriers */ -#define X86_OOSTORE +#define X86_OOSTORE #ifdef __CPU_x86_64 /* @@ -81,224 +93,237 @@ asm volatile( \ " lock; addq $0, 0(%%rsp) \n\t " \ : : : "memory" \ - ) + ) */ -#define membar() asm volatile( " mfence \n\t " : : : "memory" ) -#define membar_read() asm volatile( " lfence \n\t " : : : "memory" ) +#define membar() asm volatile(" mfence \n\t " : : : "memory") +#define membar_read() asm volatile(" lfence \n\t " : : : "memory") #ifdef X86_64_OOSTORE -#define membar_write() asm volatile( " sfence \n\t " : : : "memory" ) +#define membar_write() asm volatile(" sfence \n\t " : : : "memory") #else -#define membar_write() asm volatile ("" : : : "memory") /* gcc don't cache*/ -#endif /* X86_OOSTORE */ +#define membar_write() asm volatile("" : : : "memory") /* gcc don't cache*/ +#endif /* X86_OOSTORE */ #else /* ! __CPU_x86_64 => __CPU_i386*/ /* membar: lfence, mfence, sfence available only on newer cpus, so for now * stick to lock addl */ -#define membar() asm volatile(" lock; addl $0, 0(%%esp) \n\t " : : : "memory" ) -#define membar_read() membar() +#define membar() asm volatile(" lock; addl $0, 0(%%esp) \n\t " : : : "memory") +#define membar_read() membar() #ifdef X86_OOSTORE /* out of order store version */ -#define membar_write() membar() +#define membar_write() membar() #else /* no oostore, most x86 cpus => do nothing, just a gcc do_not_cache barrier*/ -#define membar_write() asm volatile ("" : : : "memory") +#define membar_write() asm volatile("" : : : "memory") #endif /* X86_OOSTORE */ #endif /* __CPU_x86_64 */ -#define membar_depends() do {} while(0) /* really empty, not even a cc bar. */ +#define membar_depends() \ + do { \ + } while(0) /* really empty, not even a cc bar. */ /* lock barrriers: empty, not needed on x86 or x86_64 (atomic ops already - * force the barriers if needed); the lock/unlock should already contain the + * force the barriers if needed); the lock/unlock should already contain the * gcc do_not_cache barriers*/ -#define membar_enter_lock() do {} while(0) -#define membar_leave_lock() do {} while(0) +#define membar_enter_lock() \ + do { \ + } while(0) +#define membar_leave_lock() \ + do { \ + } while(0) /* membars after or before atomic_ops or atomic_setget -> use these or * mb_() if you need a memory barrier in one of these * situations (on some archs where the atomic operations imply memory * barriers is better to use atomic_op_x(); membar_atomic_op() then * atomic_op_x(); membar()) */ -#define membar_atomic_op() do {} while(0) -#define membar_atomic_setget() membar() -#define membar_write_atomic_op() do {} while(0) -#define membar_write_atomic_setget() membar_write() -#define membar_read_atomic_op() do {} while(0) -#define membar_read_atomic_setget() membar_read() +#define membar_atomic_op() \ + do { \ + } while(0) +#define membar_atomic_setget() membar() +#define membar_write_atomic_op() \ + do { \ + } while(0) +#define membar_write_atomic_setget() membar_write() +#define membar_read_atomic_op() \ + do { \ + } while(0) +#define membar_read_atomic_setget() membar_read() #endif /* NOSMP */ /* 1 param atomic f */ -#define ATOMIC_FUNC_DECL1(NAME, OP, P_TYPE) \ - inline static void atomic_##NAME##_##P_TYPE (volatile P_TYPE* var) \ - { \ - asm volatile( \ - __LOCK_PREF " " OP " \n\t" \ - : "=m"(*var) : "m"(*var) : "cc", "memory" \ - ); \ +#define ATOMIC_FUNC_DECL1(NAME, OP, P_TYPE) \ + inline static void atomic_##NAME##_##P_TYPE(volatile P_TYPE *var) \ + { \ + asm volatile(__LOCK_PREF " " OP " \n\t" \ + : "=m"(*var) \ + : "m"(*var) \ + : "cc", "memory"); \ } /* 2 params atomic f */ -#define ATOMIC_FUNC_DECL2(NAME, OP, P_TYPE) \ - inline static void atomic_##NAME##_##P_TYPE (volatile P_TYPE* var, \ - P_TYPE v) \ - { \ - asm volatile( \ - __LOCK_PREF " " OP " \n\t" \ - : "=m"(*var) : "ri" (v), "m"(*var) : "cc", "memory" \ - ); \ +#define ATOMIC_FUNC_DECL2(NAME, OP, P_TYPE) \ + inline static void atomic_##NAME##_##P_TYPE( \ + volatile P_TYPE *var, P_TYPE v) \ + { \ + asm volatile(__LOCK_PREF " " OP " \n\t" \ + : "=m"(*var) \ + : "ri"(v), "m"(*var) \ + : "cc", "memory"); \ } -#if defined __GNUC__ && __GNUC__ < 3 && __GNUC_MINOR__ < 9 +#if defined __GNUC__ && __GNUC__ < 3 && __GNUC_MINOR__ < 9 /* gcc version < 2.9 */ -#define ATOMIC_FUNC_XCHG(NAME, OP, TYPE) \ - inline static TYPE atomic_##NAME##_##TYPE(volatile TYPE* var, TYPE v) \ -{ \ - asm volatile( \ - OP " \n\t" \ - : "=q"(v), "=m"(*var) :"m"(*var), "0"(v) : "memory" \ - ); \ - return v; \ -} +#define ATOMIC_FUNC_XCHG(NAME, OP, TYPE) \ + inline static TYPE atomic_##NAME##_##TYPE(volatile TYPE *var, TYPE v) \ + { \ + asm volatile(OP " \n\t" \ + : "=q"(v), "=m"(*var) \ + : "m"(*var), "0"(v) \ + : "memory"); \ + return v; \ + } #else -#define ATOMIC_FUNC_XCHG(NAME, OP, TYPE) \ - inline static TYPE atomic_##NAME##_##TYPE(volatile TYPE* var, TYPE v) \ -{ \ - asm volatile( \ - OP " \n\t" \ - : "+q"(v), "=m"(*var) : "m"(*var) : "memory" \ - ); \ - return v; \ -} +#define ATOMIC_FUNC_XCHG(NAME, OP, TYPE) \ + inline static TYPE atomic_##NAME##_##TYPE(volatile TYPE *var, TYPE v) \ + { \ + asm volatile(OP " \n\t" : "+q"(v), "=m"(*var) : "m"(*var) : "memory"); \ + return v; \ + } #endif /* gcc & gcc version < 2.9 */ /* returns a value, 1 param */ -#define ATOMIC_FUNC_TEST(NAME, OP, P_TYPE, RET_TYPE) \ - inline static RET_TYPE atomic_##NAME##_##P_TYPE(volatile P_TYPE* var) \ - { \ - char ret; \ - asm volatile( \ - __LOCK_PREF " " OP "\n\t" \ - "setz %1 \n\t" \ - : "=m" (*var), "=qm"(ret) : "m"(*var) : "cc", "memory" \ - ); \ - return ret; \ +#define ATOMIC_FUNC_TEST(NAME, OP, P_TYPE, RET_TYPE) \ + inline static RET_TYPE atomic_##NAME##_##P_TYPE(volatile P_TYPE *var) \ + { \ + char ret; \ + asm volatile(__LOCK_PREF " " OP "\n\t" \ + "setz %1 \n\t" \ + : "=m"(*var), "=qm"(ret) \ + : "m"(*var) \ + : "cc", "memory"); \ + return ret; \ } /* returns a value, 3 params (var, old, new) * The returned value is the value before the xchg: * if ret!=old => cmpxchg failed and ret is var's value * else => success and new_v is var's new value */ -#define ATOMIC_FUNC_CMPXCHG(NAME, OP, P_TYPE, RET_TYPE) \ - inline static RET_TYPE atomic_##NAME##_##P_TYPE(volatile P_TYPE* var, \ - P_TYPE old, P_TYPE new_v)\ - { \ - P_TYPE ret; \ - asm volatile( \ - __LOCK_PREF " " OP "\n\t" \ - : "=a"(ret), "=m" (*var) :\ - "r"(new_v), "m"(*var), "0"(old):\ - "cc", "memory" \ - ); \ - return ret; \ +#define ATOMIC_FUNC_CMPXCHG(NAME, OP, P_TYPE, RET_TYPE) \ + inline static RET_TYPE atomic_##NAME##_##P_TYPE( \ + volatile P_TYPE *var, P_TYPE old, P_TYPE new_v) \ + { \ + P_TYPE ret; \ + asm volatile(__LOCK_PREF " " OP "\n\t" \ + : "=a"(ret), "=m"(*var) \ + : "r"(new_v), "m"(*var), "0"(old) \ + : "cc", "memory"); \ + return ret; \ } /* similar w/ XCHG but with LOCK prefix, relaxed constraints & diff. return */ -#define ATOMIC_FUNC_XADD(NAME, OP, TYPE) \ - inline static TYPE atomic_##NAME##_##TYPE(volatile TYPE* var, TYPE v) \ -{ \ - TYPE ret; \ - asm volatile( \ - __LOCK_PREF " " OP " \n\t" \ - : "=r"(ret), "=m"(*var) :"m"(*var), "0"(v) : "cc", "memory" \ - ); \ - return ret+v; \ -} +#define ATOMIC_FUNC_XADD(NAME, OP, TYPE) \ + inline static TYPE atomic_##NAME##_##TYPE(volatile TYPE *var, TYPE v) \ + { \ + TYPE ret; \ + asm volatile(__LOCK_PREF " " OP " \n\t" \ + : "=r"(ret), "=m"(*var) \ + : "m"(*var), "0"(v) \ + : "cc", "memory"); \ + return ret + v; \ + } ATOMIC_FUNC_DECL1(inc, "incl %0", int) ATOMIC_FUNC_DECL1(dec, "decl %0", int) ATOMIC_FUNC_DECL2(and, "andl %1, %0", int) -ATOMIC_FUNC_DECL2(or, "orl %1, %0", int) +ATOMIC_FUNC_DECL2(or, "orl %1, %0", int) ATOMIC_FUNC_TEST(inc_and_test, "incl %0", int, int) ATOMIC_FUNC_TEST(dec_and_test, "decl %0", int, int) -ATOMIC_FUNC_XCHG(get_and_set, "xchgl %1, %0", int) -ATOMIC_FUNC_CMPXCHG(cmpxchg, "cmpxchgl %2, %1", int , int) -ATOMIC_FUNC_XADD(add, "xaddl %0, %1", int) +ATOMIC_FUNC_XCHG(get_and_set, "xchgl %1, %0", int) +ATOMIC_FUNC_CMPXCHG(cmpxchg, "cmpxchgl %2, %1", int, int) +ATOMIC_FUNC_XADD(add, "xaddl %0, %1", int) #ifdef __CPU_x86_64 ATOMIC_FUNC_DECL1(inc, "incq %0", long) ATOMIC_FUNC_DECL1(dec, "decq %0", long) ATOMIC_FUNC_DECL2(and, "andq %1, %0", long) -ATOMIC_FUNC_DECL2(or, "orq %1, %0", long) +ATOMIC_FUNC_DECL2(or, "orq %1, %0", long) ATOMIC_FUNC_TEST(inc_and_test, "incq %0", long, int) ATOMIC_FUNC_TEST(dec_and_test, "decq %0", long, int) -ATOMIC_FUNC_XCHG(get_and_set, "xchgq %1, %0", long) -ATOMIC_FUNC_CMPXCHG(cmpxchg, "cmpxchgq %2, %1", long , long) -ATOMIC_FUNC_XADD(add, "xaddq %0, %1",long) +ATOMIC_FUNC_XCHG(get_and_set, "xchgq %1, %0", long) +ATOMIC_FUNC_CMPXCHG(cmpxchg, "cmpxchgq %2, %1", long, long) +ATOMIC_FUNC_XADD(add, "xaddq %0, %1", long) #else ATOMIC_FUNC_DECL1(inc, "incl %0", long) ATOMIC_FUNC_DECL1(dec, "decl %0", long) ATOMIC_FUNC_DECL2(and, "andl %1, %0", long) -ATOMIC_FUNC_DECL2(or, "orl %1, %0", long) +ATOMIC_FUNC_DECL2(or, "orl %1, %0", long) ATOMIC_FUNC_TEST(inc_and_test, "incl %0", long, int) ATOMIC_FUNC_TEST(dec_and_test, "decl %0", long, int) -ATOMIC_FUNC_XCHG(get_and_set, "xchgl %1, %0", long) -ATOMIC_FUNC_CMPXCHG(cmpxchg, "cmpxchgl %2, %1", long , long) -ATOMIC_FUNC_XADD(add, "xaddl %0, %1",long) +ATOMIC_FUNC_XCHG(get_and_set, "xchgl %1, %0", long) +ATOMIC_FUNC_CMPXCHG(cmpxchg, "cmpxchgl %2, %1", long, long) +ATOMIC_FUNC_XADD(add, "xaddl %0, %1", long) #endif #define atomic_inc(var) atomic_inc_int(&(var)->val) #define atomic_dec(var) atomic_dec_int(&(var)->val) #define atomic_and(var, mask) atomic_and_int(&(var)->val, (mask)) -#define atomic_or(var, mask) atomic_or_int(&(var)->val, (mask)) +#define atomic_or(var, mask) atomic_or_int(&(var)->val, (mask)) #define atomic_dec_and_test(var) atomic_dec_and_test_int(&(var)->val) #define atomic_inc_and_test(var) atomic_inc_and_test_int(&(var)->val) #define atomic_get_and_set(var, i) atomic_get_and_set_int(&(var)->val, i) #define atomic_cmpxchg(var, old, newv) \ - atomic_cmpxchg_int(&(var)->val, old, newv) + atomic_cmpxchg_int(&(var)->val, old, newv) #define atomic_add(var, v) atomic_add_int(&(var)->val, v) #ifdef NOSMP #define mb_atomic_set_int(v, i) \ - do{ \ - membar(); atomic_set_int(v, i); \ - }while(0) + do { \ + membar(); \ + atomic_set_int(v, i); \ + } while(0) #define mb_atomic_set_long(v, i) \ - do{ \ - membar(); atomic_set_long(v, i); \ - }while(0) - + do { \ + membar(); \ + atomic_set_long(v, i); \ + } while(0) -inline static int mb_atomic_get_int(volatile int* v) +inline static int mb_atomic_get_int(volatile int *v) { - membar(); return atomic_get_int(v); + membar(); + return atomic_get_int(v); } -inline static long mb_atomic_get_long(volatile long* v) +inline static long mb_atomic_get_long(volatile long *v) { - membar(); return atomic_get_long(v); + membar(); + return atomic_get_long(v); } #else /* NOSMP */ -inline static void mb_atomic_set_int(volatile int* v, int i) +inline static void mb_atomic_set_int(volatile int *v, int i) { - asm volatile( - "xchgl %1, %0 \n\t" -#if defined __GNUC__ && __GNUC__ < 3 && __GNUC_MINOR__ < 9 - : "=q"(i), "=m"(*v) : "m"(*v), "0"(i) : "memory" + asm volatile("xchgl %1, %0 \n\t" +#if defined __GNUC__ && __GNUC__ < 3 && __GNUC_MINOR__ < 9 + : "=q"(i), "=m"(*v) + : "m"(*v), "0"(i) + : "memory" #else - : "+q"(i), "=m"(*v) : "m"(*v) : "memory" + : "+q"(i), "=m"(*v) + : "m"(*v) + : "memory" #endif - ); + ); } -inline static void mb_atomic_set_long(volatile long* v, long l) +inline static void mb_atomic_set_long(volatile long *v, long l) { asm volatile( #ifdef __CPU_x86_64 @@ -306,38 +331,43 @@ inline static void mb_atomic_set_long(volatile long* v, long l) #else "xchgl %1, %0 \n\t" #endif -#if defined __GNUC__ && __GNUC__ < 3 && __GNUC_MINOR__ < 9 - : "=q"(l), "=m"(*v) : "m"(*v), "0"(l) : "memory" +#if defined __GNUC__ && __GNUC__ < 3 && __GNUC_MINOR__ < 9 + : "=q"(l), "=m"(*v) + : "m"(*v), "0"(l) + : "memory" #else - : "+q"(l), "=m"(*v) : "m"(*v) : "memory" + : "+q"(l), "=m"(*v) + : "m"(*v) + : "memory" #endif - ); + ); } -inline static int mb_atomic_get_int(volatile int* var) +inline static int mb_atomic_get_int(volatile int *var) { int ret; - - asm volatile( - __LOCK_PREF " cmpxchgl %0, %1 \n\t" - : "=a"(ret) : "m"(*var) : "cc", "memory" - ); + + asm volatile(__LOCK_PREF " cmpxchgl %0, %1 \n\t" + : "=a"(ret) + : "m"(*var) + : "cc", "memory"); return ret; } -inline static long mb_atomic_get_long(volatile long* var) +inline static long mb_atomic_get_long(volatile long *var) { long ret; - + asm volatile( #ifdef __CPU_x86_64 __LOCK_PREF " cmpxchgq %0, %1 \n\t" #else __LOCK_PREF " cmpxchgl %0, %1 \n\t" #endif - : "=a"(ret) : "m"(*var) : "cc", "memory" - ); + : "=a"(ret) + : "m"(*var) + : "cc", "memory"); return ret; } @@ -345,37 +375,37 @@ inline static long mb_atomic_get_long(volatile long* var) /* on x86 atomic intructions act also as barriers */ -#define mb_atomic_inc_int(v) atomic_inc_int(v) -#define mb_atomic_dec_int(v) atomic_dec_int(v) -#define mb_atomic_or_int(v, m) atomic_or_int(v, m) -#define mb_atomic_and_int(v, m) atomic_and_int(v, m) -#define mb_atomic_inc_and_test_int(v) atomic_inc_and_test_int(v) -#define mb_atomic_dec_and_test_int(v) atomic_dec_and_test_int(v) -#define mb_atomic_get_and_set_int(v, i) atomic_get_and_set_int(v, i) -#define mb_atomic_cmpxchg_int(v, o, n) atomic_cmpxchg_int(v, o, n) -#define mb_atomic_add_int(v, a) atomic_add_int(v, a) - -#define mb_atomic_inc_long(v) atomic_inc_long(v) -#define mb_atomic_dec_long(v) atomic_dec_long(v) -#define mb_atomic_or_long(v, m) atomic_or_long(v, m) -#define mb_atomic_and_long(v, m) atomic_and_long(v, m) -#define mb_atomic_inc_and_test_long(v) atomic_inc_and_test_long(v) -#define mb_atomic_dec_and_test_long(v) atomic_dec_and_test_long(v) -#define mb_atomic_get_and_set_long(v, i) atomic_get_and_set_long(v, i) -#define mb_atomic_cmpxchg_long(v, o, n) atomic_cmpxchg_long(v, o, n) -#define mb_atomic_add_long(v, a) atomic_add_long(v, a) - -#define mb_atomic_inc(v) atomic_inc(v) -#define mb_atomic_dec(v) atomic_dec(v) -#define mb_atomic_or(v, m) atomic_or(v, m) -#define mb_atomic_and(v, m) atomic_and(v, m) -#define mb_atomic_inc_and_test(v) atomic_inc_and_test(v) -#define mb_atomic_dec_and_test(v) atomic_dec_and_test(v) -#define mb_atomic_get(v) mb_atomic_get_int( &(v)->val) -#define mb_atomic_set(v, i) mb_atomic_set_int(&(v)->val, i) -#define mb_atomic_get_and_set(v, i) atomic_get_and_set_int(&(v)->val, i) -#define mb_atomic_cmpxchg(v, o, n) atomic_cmpxchg_int(&(v)->val, o, n) -#define mb_atomic_add(v, a) atomic_add_int(&(v)->val, a) +#define mb_atomic_inc_int(v) atomic_inc_int(v) +#define mb_atomic_dec_int(v) atomic_dec_int(v) +#define mb_atomic_or_int(v, m) atomic_or_int(v, m) +#define mb_atomic_and_int(v, m) atomic_and_int(v, m) +#define mb_atomic_inc_and_test_int(v) atomic_inc_and_test_int(v) +#define mb_atomic_dec_and_test_int(v) atomic_dec_and_test_int(v) +#define mb_atomic_get_and_set_int(v, i) atomic_get_and_set_int(v, i) +#define mb_atomic_cmpxchg_int(v, o, n) atomic_cmpxchg_int(v, o, n) +#define mb_atomic_add_int(v, a) atomic_add_int(v, a) + +#define mb_atomic_inc_long(v) atomic_inc_long(v) +#define mb_atomic_dec_long(v) atomic_dec_long(v) +#define mb_atomic_or_long(v, m) atomic_or_long(v, m) +#define mb_atomic_and_long(v, m) atomic_and_long(v, m) +#define mb_atomic_inc_and_test_long(v) atomic_inc_and_test_long(v) +#define mb_atomic_dec_and_test_long(v) atomic_dec_and_test_long(v) +#define mb_atomic_get_and_set_long(v, i) atomic_get_and_set_long(v, i) +#define mb_atomic_cmpxchg_long(v, o, n) atomic_cmpxchg_long(v, o, n) +#define mb_atomic_add_long(v, a) atomic_add_long(v, a) + +#define mb_atomic_inc(v) atomic_inc(v) +#define mb_atomic_dec(v) atomic_dec(v) +#define mb_atomic_or(v, m) atomic_or(v, m) +#define mb_atomic_and(v, m) atomic_and(v, m) +#define mb_atomic_inc_and_test(v) atomic_inc_and_test(v) +#define mb_atomic_dec_and_test(v) atomic_dec_and_test(v) +#define mb_atomic_get(v) mb_atomic_get_int(&(v)->val) +#define mb_atomic_set(v, i) mb_atomic_set_int(&(v)->val, i) +#define mb_atomic_get_and_set(v, i) atomic_get_and_set_int(&(v)->val, i) +#define mb_atomic_cmpxchg(v, o, n) atomic_cmpxchg_int(&(v)->val, o, n) +#define mb_atomic_add(v, a) atomic_add_int(&(v)->val, a) #endif From 7aede62f97073b5fb066fdda8d9106fb4d876e6f Mon Sep 17 00:00:00 2001 From: Victor Seva Date: Thu, 18 May 2023 15:18:48 +0200 Subject: [PATCH 03/14] core: [cfg] clang-format for coherent indentation and coding style --- src/core/cfg/cfg.c | 197 +++---- src/core/cfg/cfg.h | 74 +-- src/core/cfg/cfg_ctx.c | 1116 +++++++++++++++++-------------------- src/core/cfg/cfg_ctx.h | 112 ++-- src/core/cfg/cfg_script.c | 288 +++++----- src/core/cfg/cfg_script.h | 32 +- src/core/cfg/cfg_select.c | 202 +++---- src/core/cfg/cfg_select.h | 10 +- src/core/cfg/cfg_struct.c | 674 +++++++++++----------- src/core/cfg/cfg_struct.h | 318 ++++++----- 10 files changed, 1492 insertions(+), 1531 deletions(-) diff --git a/src/core/cfg/cfg.c b/src/core/cfg/cfg.c index c223e8c3732..0b1e56ac121 100644 --- a/src/core/cfg/cfg.c +++ b/src/core/cfg/cfg.c @@ -34,93 +34,94 @@ * \return value is -1 on error */ int cfg_declare(char *group_name, cfg_def_t *def, void *values, int def_size, - void **handle) + void **handle) { - int i, num, size, group_name_len; - cfg_mapping_t *mapping = NULL; - cfg_group_t *group; + int i, num, size, group_name_len; + cfg_mapping_t *mapping = NULL; + cfg_group_t *group; int types; - if(def==NULL || def[0].name==NULL) + if(def == NULL || def[0].name == NULL) return -1; /* check the number of the variables */ - for (num=0; def[num].name; num++); + for(num = 0; def[num].name; num++) + ; - mapping = (cfg_mapping_t *)pkg_malloc(sizeof(cfg_mapping_t)*num); - if (!mapping) { + mapping = (cfg_mapping_t *)pkg_malloc(sizeof(cfg_mapping_t) * num); + if(!mapping) { PKG_MEM_ERROR; goto error; } - memset(mapping, 0, sizeof(cfg_mapping_t)*num); - types=0; + memset(mapping, 0, sizeof(cfg_mapping_t) * num); + types = 0; /* calculate the size of the memory block that has to be allocated for the cfg variables, and set the content of the cfg_mapping array the same time */ - for (i=0, size=0; i CFG_INPUT_STR) { - LM_ERR("%s.%s: unsupported input type\n", - group_name, def[i].name); + if(CFG_INPUT_MASK(def[i].type) > CFG_INPUT_STR) { + LM_ERR("%s.%s: unsupported input type\n", group_name, def[i].name); goto error; } - if (def[i].type & CFG_ATOMIC) { - if (CFG_VAR_MASK(def[i].type) != CFG_VAR_INT) { + if(def[i].type & CFG_ATOMIC) { + if(CFG_VAR_MASK(def[i].type) != CFG_VAR_INT) { LM_ERR("%s.%s: atomic change is allowed " - "only for integer types\n", + "only for integer types\n", group_name, def[i].name); goto error; } - if (def[i].on_set_child_cb) { + if(def[i].on_set_child_cb) { LM_ERR("%s.%s: per-child process callback " - "does not work together with atomic change\n", + "does not work together with atomic change\n", group_name, def[i].name); goto error; } @@ -129,13 +130,17 @@ int cfg_declare(char *group_name, cfg_def_t *def, void *values, int def_size, /* fix the computed size (char*, str or pointer members will force structure padding to multiple of sizeof(pointer)) */ - if (types & ((1<dynamic != CFG_GROUP_UNKNOWN) { + if((group = cfg_lookup_group(group_name, group_name_len))) { + if(group->dynamic != CFG_GROUP_UNKNOWN) { /* conflict with another module/core group, or with a dynamic group */ LM_ERR("configuration group has been already declared: %s\n", - group_name); + group_name); goto error; } /* An empty group is found which does not have any variable yet */ @@ -162,7 +167,8 @@ int cfg_declare(char *group_name, cfg_def_t *def, void *values, int def_size, /* create a new group I will allocate memory in shm mem for the variables later in a single block, when we know the size of all the registered groups. */ - if (!(group = cfg_new_group(group_name, group_name_len, num, mapping, values, size, handle))) + if(!(group = cfg_new_group(group_name, group_name_len, num, mapping, + values, size, handle))) goto error; } group->dynamic = CFG_GROUP_STATIC; @@ -171,25 +177,26 @@ int cfg_declare(char *group_name, cfg_def_t *def, void *values, int def_size, cfg_notify_drivers(group_name, group_name_len, def); LM_DBG("new config group has been registered: '%s' (num=%d, size=%d)\n", - group_name, num, size); + group_name, num, size); return 0; error: - if (mapping) pkg_free(mapping); - LM_ERR("failed to register the config group: %s\n", - group_name); + if(mapping) + pkg_free(mapping); + LM_ERR("failed to register the config group: %s\n", group_name); return -1; } /* declares a single variable with integer type */ -int cfg_declare_int(char *group_name, char *var_name, - int val, int min, int max, char *descr) +int cfg_declare_int(char *group_name, char *var_name, int val, int min, int max, + char *descr) { - cfg_script_var_t *var; + cfg_script_var_t *var; - if ((var = new_cfg_script_var(group_name, var_name, CFG_VAR_INT, descr)) == NULL) + if((var = new_cfg_script_var(group_name, var_name, CFG_VAR_INT, descr)) + == NULL) return -1; var->val.i = val; @@ -202,16 +209,17 @@ int cfg_declare_int(char *group_name, char *var_name, /* declares a single variable with str type */ int cfg_declare_str(char *group_name, char *var_name, char *val, char *descr) { - cfg_script_var_t *var; - int len; + cfg_script_var_t *var; + int len; - if ((var = new_cfg_script_var(group_name, var_name, CFG_VAR_STR, descr)) == NULL) + if((var = new_cfg_script_var(group_name, var_name, CFG_VAR_STR, descr)) + == NULL) return -1; - if (val) { + if(val) { len = strlen(val); var->val.s.s = (char *)pkg_malloc(sizeof(char) * (len + 1)); - if (!var->val.s.s) { + if(!var->val.s.s) { PKG_MEM_ERROR; return -1; } @@ -229,36 +237,35 @@ int cfg_declare_str(char *group_name, char *var_name, char *val, char *descr) * The group instance is created if it does not exist. * wrapper function for new_add_var() */ -int cfg_ginst_var_int(char *group_name, unsigned int group_id, char *var_name, - int val) +int cfg_ginst_var_int( + char *group_name, unsigned int group_id, char *var_name, int val) { - str gname, vname; + str gname, vname; gname.s = group_name; gname.len = strlen(group_name); vname.s = var_name; vname.len = strlen(var_name); - return new_add_var(&gname, group_id, &vname, - (void *)(long)val, CFG_VAR_INT); + return new_add_var( + &gname, group_id, &vname, (void *)(long)val, CFG_VAR_INT); } /* Add a variable to a group instance with string type. * The group instance is created if it does not exist. * wrapper function for new_add_var() */ -int cfg_ginst_var_string(char *group_name, unsigned int group_id, char *var_name, - char *val) +int cfg_ginst_var_string( + char *group_name, unsigned int group_id, char *var_name, char *val) { - str gname, vname; + str gname, vname; gname.s = group_name; gname.len = strlen(group_name); vname.s = var_name; vname.len = strlen(var_name); - return new_add_var(&gname, group_id, &vname, - (void *)val, CFG_VAR_STRING); + return new_add_var(&gname, group_id, &vname, (void *)val, CFG_VAR_STRING); } /* Create a new group instance. @@ -266,22 +273,23 @@ int cfg_ginst_var_string(char *group_name, unsigned int group_id, char *var_name */ int cfg_new_ginst(char *group_name, unsigned int group_id) { - str gname; + str gname; gname.s = group_name; gname.len = strlen(group_name); - return new_add_var(&gname, group_id, NULL /* var */, - NULL /* val */, 0 /* type */); + return new_add_var( + &gname, group_id, NULL /* var */, NULL /* val */, 0 /* type */); } /* returns the handle of a cfg group */ void **cfg_get_handle(char *gname) { - cfg_group_t *group; + cfg_group_t *group; group = cfg_lookup_group(gname, strlen(gname)); - if (!group || (group->dynamic != CFG_GROUP_STATIC)) return NULL; + if(!group || (group->dynamic != CFG_GROUP_STATIC)) + return NULL; return group->handle; } @@ -294,30 +302,29 @@ void **cfg_get_handle(char *gname) */ int cfg_get_group_id(str *group, unsigned int **group_id) { - static unsigned int id; - str s; + static unsigned int id; + str s; - if (!group->s || (group->s[group->len-1] != ']')) { + if(!group->s || (group->s[group->len - 1] != ']')) { *group_id = NULL; return 0; } s.s = group->s + group->len - 2; s.len = 0; - while ((s.s > group->s) && (*s.s != '[')) { + while((s.s > group->s) && (*s.s != '[')) { s.s--; s.len++; } - if (s.s == group->s) /* '[' not found */ + if(s.s == group->s) /* '[' not found */ return -1; group->len = s.s - group->s; s.s++; - if (!group->len || !s.len) + if(!group->len || !s.len) return -1; - if (str2int(&s, &id)) + if(str2int(&s, &id)) return -1; *group_id = &id; return 0; } - diff --git a/src/core/cfg/cfg.h b/src/core/cfg/cfg.h index 19cb824055c..f76e1115e78 100644 --- a/src/core/cfg/cfg.h +++ b/src/core/cfg/cfg.h @@ -25,39 +25,45 @@ #include "../str.h" /* variable type */ -#define CFG_VAR_UNSET 0U -#define CFG_VAR_INT 1U -#define CFG_VAR_STRING 2U -#define CFG_VAR_STR 3U -#define CFG_VAR_POINTER 4U +#define CFG_VAR_UNSET 0U +#define CFG_VAR_INT 1U +#define CFG_VAR_STRING 2U +#define CFG_VAR_STR 3U +#define CFG_VAR_POINTER 4U /*! \brief number of bits required for the variable type */ -#define CFG_INPUT_SHIFT 3 +#define CFG_INPUT_SHIFT 3 /*! \brief input types */ -#define CFG_INPUT_INT (CFG_VAR_INT << CFG_INPUT_SHIFT) -#define CFG_INPUT_STRING (CFG_VAR_STRING << CFG_INPUT_SHIFT) -#define CFG_INPUT_STR (CFG_VAR_STR << CFG_INPUT_SHIFT) - -#define CFG_VAR_MASK(x) ((x)&((1U<var +#define cfg_get(gname, handle, var) ((struct cfg_group_##gname *)handle)->var /*! \brief declares a single variable with integer type */ -int cfg_declare_int(char *group_name, char *var_name, - int val, int min, int max, char *descr); +int cfg_declare_int(char *group_name, char *var_name, int val, int min, int max, + char *descr); /*! \brief declares a single variable with str type */ int cfg_declare_str(char *group_name, char *var_name, char *val, char *descr); @@ -84,15 +88,15 @@ int cfg_declare_str(char *group_name, char *var_name, char *val, char *descr); * The group instance is created if it does not exist. * wrapper function for new_add_var() */ -int cfg_ginst_var_int(char *group_name, unsigned int group_id, char *var_name, - int val); +int cfg_ginst_var_int( + char *group_name, unsigned int group_id, char *var_name, int val); /*! \brief Add a variable to a group instance with string type. * The group instance is created if it does not exist. * wrapper function for new_add_var() */ -int cfg_ginst_var_string(char *group_name, unsigned int group_id, char *var_name, - char *val); +int cfg_ginst_var_string( + char *group_name, unsigned int group_id, char *var_name, char *val); /*! \brief Create a new group instance. * wrapper function for new_add_var() diff --git a/src/core/cfg/cfg_ctx.c b/src/core/cfg/cfg_ctx.c index 2faf8cb8edc..cbb3511c539 100644 --- a/src/core/cfg/cfg_ctx.c +++ b/src/core/cfg/cfg_ctx.c @@ -30,27 +30,27 @@ /* linked list of all the registered cfg contexts */ -static cfg_ctx_t *cfg_ctx_list = NULL; +static cfg_ctx_t *cfg_ctx_list = NULL; /* creates a new config context that is an interface to the * cfg variables with write permission */ int cfg_register_ctx(cfg_ctx_t **handle, cfg_on_declare on_declare_cb) { - cfg_ctx_t *ctx; - cfg_group_t *group; - str gname; + cfg_ctx_t *ctx; + cfg_group_t *group; + str gname; /* allocate memory for the new context * Better to use shm mem, because 'changed' and 'lock' * must be in shm mem anyway */ ctx = (cfg_ctx_t *)shm_malloc(sizeof(cfg_ctx_t)); - if (!ctx) { + if(!ctx) { SHM_MEM_ERROR; return -1; } memset(ctx, 0, sizeof(cfg_ctx_t)); - if (lock_init(&ctx->lock) == 0) { + if(lock_init(&ctx->lock) == 0) { LM_ERR("failed to init lock\n"); shm_free(ctx); return -1; @@ -64,16 +64,14 @@ int cfg_register_ctx(cfg_ctx_t **handle, cfg_on_declare on_declare_cb) * The handle of the context must be set before calling the * on_declare callbacks. */ *handle = ctx; - if (on_declare_cb) { + if(on_declare_cb) { ctx->on_declare_cb = on_declare_cb; - for (group = cfg_group; - group; - group = group->next - ) { + for(group = cfg_group; group; group = group->next) { /* dynamic groups are not ready, the callback * will be called later when the group is fixed-up */ - if (group->dynamic != CFG_GROUP_STATIC) continue; + if(group->dynamic != CFG_GROUP_STATIC) + continue; gname.s = group->name; gname.len = group->name_len; @@ -87,12 +85,9 @@ int cfg_register_ctx(cfg_ctx_t **handle, cfg_on_declare on_declare_cb) /* free the memory allocated for the contexts */ void cfg_ctx_destroy(void) { - cfg_ctx_t *ctx, *ctx2; + cfg_ctx_t *ctx, *ctx2; - for (ctx = cfg_ctx_list; - ctx; - ctx = ctx2 - ) { + for(ctx = cfg_ctx_list; ctx; ctx = ctx2) { ctx2 = ctx->next; shm_free(ctx); } @@ -102,58 +97,55 @@ void cfg_ctx_destroy(void) /* notify the drivers about the new config definition */ void cfg_notify_drivers(char *group_name, int group_name_len, cfg_def_t *def) { - cfg_ctx_t *ctx; - str gname; + cfg_ctx_t *ctx; + str gname; gname.s = group_name; gname.len = group_name_len; - for (ctx = cfg_ctx_list; - ctx; - ctx = ctx->next - ) - if (ctx->on_declare_cb) + for(ctx = cfg_ctx_list; ctx; ctx = ctx->next) + if(ctx->on_declare_cb) ctx->on_declare_cb(&gname, def); } /* placeholder for a temporary string */ -static char *temp_string = NULL; +static char *temp_string = NULL; /* convert the value to the requested type */ -int convert_val(unsigned int val_type, void *val, - unsigned int var_type, void **new_val) +int convert_val( + unsigned int val_type, void *val, unsigned int var_type, void **new_val) { - static str s; - char *end; - int i; - static char buf[INT2STR_MAX_LEN]; + static str s; + char *end; + int i; + static char buf[INT2STR_MAX_LEN]; /* we have to convert from val_type to var_type */ - switch (CFG_INPUT_MASK(var_type)) { + switch(CFG_INPUT_MASK(var_type)) { case CFG_INPUT_INT: - if (val_type == CFG_VAR_INT) { + if(val_type == CFG_VAR_INT) { *new_val = val; break; - } else if (val_type == CFG_VAR_STRING) { - if (!val || (((char *)val)[0] == '\0')) { + } else if(val_type == CFG_VAR_STRING) { + if(!val || (((char *)val)[0] == '\0')) { LM_ERR("cannot convert NULL string value to integer\n"); return -1; } *new_val = (void *)(long)strtol((char *)val, &end, 10); - if (*end != '\0') { + if(*end != '\0') { LM_ERR("cannot convert string to integer '%s'\n", (char *)val); return -1; } break; - } else if (val_type == CFG_VAR_STR) { - if (!((str *)val)->len || !((str *)val)->s) { + } else if(val_type == CFG_VAR_STR) { + if(!((str *)val)->len || !((str *)val)->s) { LM_ERR("cannot convert NULL str value to integer\n"); return -1; } - if (str2sint((str *)val, &i)) { + if(str2sint((str *)val, &i)) { LM_ERR("cannot convert string to integer '%.*s'\n", ((str *)val)->len, ((str *)val)->s); return -1; @@ -164,25 +156,27 @@ int convert_val(unsigned int val_type, void *val, goto error; case CFG_INPUT_STRING: - if (val_type == CFG_VAR_INT) { - buf[snprintf(buf, sizeof(buf)-1, "%ld", (long)val)] = '\0'; + if(val_type == CFG_VAR_INT) { + buf[snprintf(buf, sizeof(buf) - 1, "%ld", (long)val)] = '\0'; *new_val = buf; break; - } else if (val_type == CFG_VAR_STRING) { + } else if(val_type == CFG_VAR_STRING) { *new_val = val; break; - } else if (val_type == CFG_VAR_STR) { - if (!((str *)val)->s) { + } else if(val_type == CFG_VAR_STR) { + if(!((str *)val)->s) { *new_val = NULL; break; } /* the value may not be zero-terminated, thus, * a new variable has to be allocated with larger memory space */ - if (temp_string) pkg_free(temp_string); - temp_string = (char *)pkg_malloc(sizeof(char) * (((str *)val)->len + 1)); - if (!temp_string) { + if(temp_string) + pkg_free(temp_string); + temp_string = (char *)pkg_malloc( + sizeof(char) * (((str *)val)->len + 1)); + if(!temp_string) { PKG_MEM_ERROR; return -1; } @@ -190,25 +184,24 @@ int convert_val(unsigned int val_type, void *val, temp_string[((str *)val)->len] = '\0'; *new_val = (void *)temp_string; break; - } goto error; case CFG_INPUT_STR: - if (val_type == CFG_VAR_INT) { - s.len = snprintf(buf, sizeof(buf)-1, "%ld", (long)val); + if(val_type == CFG_VAR_INT) { + s.len = snprintf(buf, sizeof(buf) - 1, "%ld", (long)val); buf[s.len] = '\0'; s.s = buf; *new_val = (void *)&s; break; - } else if (val_type == CFG_VAR_STRING) { + } else if(val_type == CFG_VAR_STRING) { s.s = (char *)val; s.len = (s.s) ? strlen(s.s) : 0; *new_val = (void *)&s; break; - } else if (val_type == CFG_VAR_STR) { + } else if(val_type == CFG_VAR_STR) { *new_val = val; break; } @@ -218,14 +211,14 @@ int convert_val(unsigned int val_type, void *val, return 0; error: - LM_ERR("got a value with type %u, but expected %u\n", - val_type, CFG_INPUT_MASK(var_type)); + LM_ERR("got a value with type %u, but expected %u\n", val_type, + CFG_INPUT_MASK(var_type)); return -1; } void convert_val_cleanup(void) { - if (temp_string) { + if(temp_string) { pkg_free(temp_string); temp_string = NULL; } @@ -234,7 +227,7 @@ void convert_val_cleanup(void) /* returns the size of the variable */ static int cfg_var_size(cfg_mapping_t *var) { - switch (CFG_VAR_TYPE(var)) { + switch(CFG_VAR_TYPE(var)) { case CFG_VAR_INT: return sizeof(int); @@ -258,28 +251,28 @@ static int cfg_var_size(cfg_mapping_t *var) * with the new default value. * The array is cloned before a change if clone is set to 1. */ -static int cfg_update_defaults(cfg_group_meta_t *meta, - cfg_group_t *group, cfg_mapping_t *var, char *new_val, - int clone) +static int cfg_update_defaults(cfg_group_meta_t *meta, cfg_group_t *group, + cfg_mapping_t *var, char *new_val, int clone) { - int i, clone_done=0; + int i, clone_done = 0; cfg_group_inst_t *array, *ginst; - if (!(array = meta->array)) + if(!(array = meta->array)) return 0; - for (i = 0; i < meta->num; i++) { + for(i = 0; i < meta->num; i++) { ginst = (cfg_group_inst_t *)((char *)array - + (sizeof(cfg_group_inst_t) + group->size - 1) * i); + + (sizeof(cfg_group_inst_t) + group->size + - 1) + * i); - if (!CFG_VAR_TEST(ginst, var)) { + if(!CFG_VAR_TEST(ginst, var)) { /* The variable uses the default value, it needs to be rewritten. */ - if (clone && !clone_done) { + if(clone && !clone_done) { /* The array needs to be cloned before the modification */ - if (!(array = cfg_clone_array(meta, group))) + if(!(array = cfg_clone_array(meta, group))) return -1; - ginst = (cfg_group_inst_t *)translate_pointer((char *)array, - (char *)meta->array, - (char *)ginst); + ginst = (cfg_group_inst_t *)translate_pointer( + (char *)array, (char *)meta->array, (char *)ginst); /* re-link the array to the meta-data */ meta->array = array; clone_done = 1; @@ -301,49 +294,48 @@ static int cfg_update_defaults(cfg_group_meta_t *meta, * -1: error * 1: variable has not been found */ -int cfg_set_now(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *var_name, - void *val, unsigned int val_type) +int cfg_set_now(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, + str *var_name, void *val, unsigned int val_type) { - int i; - cfg_group_t *group; - cfg_mapping_t *var; - void *p, *v; - cfg_block_t *block = NULL; - str s, s2; - char *old_string = NULL; - void **replaced = NULL; - cfg_child_cb_t *child_cb = NULL; - cfg_group_inst_t *group_inst = NULL, *new_array = NULL; - unsigned char *var_block; + int i; + cfg_group_t *group; + cfg_mapping_t *var; + void *p, *v; + cfg_block_t *block = NULL; + str s, s2; + char *old_string = NULL; + void **replaced = NULL; + cfg_child_cb_t *child_cb = NULL; + cfg_group_inst_t *group_inst = NULL, *new_array = NULL; + unsigned char *var_block; /* verify the context even if we do not need it now * to make sure that a cfg driver has called the function * (very very weak security) */ - if (!ctx) { + if(!ctx) { LM_ERR("context is undefined\n"); return -1; } - if ((val_type == CFG_VAR_UNSET) && !group_id) { + if((val_type == CFG_VAR_UNSET) && !group_id) { LM_ERR("Only group instance values can be deleted\n"); return -1; } - if (group_id && !cfg_shmized) { + if(group_id && !cfg_shmized) { /* The config group has not been shmized yet, but * an additional instance of a variable needs to be added to the group. * Add this instance to the linked list of variables, they * will be fixed later. */ - return new_add_var(group_name, *group_id, var_name, - val, val_type); + return new_add_var(group_name, *group_id, var_name, val, val_type); } /* look-up the group and the variable */ - if (cfg_lookup_var(group_name, var_name, &group, &var)) { - if (!cfg_shmized) { + if(cfg_lookup_var(group_name, var_name, &group, &var)) { + if(!cfg_shmized) { /* The group may be dynamic which is not yet ready * before forking */ - if ((group = cfg_lookup_group(group_name->s, group_name->len)) + if((group = cfg_lookup_group(group_name->s, group_name->len)) && (group->dynamic == CFG_GROUP_DYNAMIC)) return cfg_set_script_var(group, var_name, val, val_type); } @@ -351,7 +343,7 @@ int cfg_set_now(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *va } /* check whether the variable is read-only */ - if (var->def->type & CFG_READONLY) { + if(var->def->type & CFG_READONLY) { LM_ERR("variable is read-only\n"); goto error0; } @@ -361,45 +353,40 @@ int cfg_set_now(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *va * The reason is that such variables typically set global parameters * as opposed to per-process variables. Hence, it is not possible to set * the group handle temporary to another block, and then reset it back later. */ - if (group_id - && var->def->on_set_child_cb - && var->def->type & CFG_CB_ONLY_ONCE ) { + if(group_id && var->def->on_set_child_cb + && var->def->type & CFG_CB_ONLY_ONCE) { LM_ERR("This variable does not support multiple values.\n"); goto error0; } /* check whether we have to convert the type */ - if ((val_type != CFG_VAR_UNSET) + if((val_type != CFG_VAR_UNSET) && convert_val(val_type, val, CFG_INPUT_TYPE(var), &v)) goto error0; - if ((val_type != CFG_VAR_UNSET) - && (CFG_INPUT_TYPE(var) == CFG_INPUT_INT) + if((val_type != CFG_VAR_UNSET) && (CFG_INPUT_TYPE(var) == CFG_INPUT_INT) && (var->def->min || var->def->max)) { /* perform a simple min-max check for integers */ - if (((int)(long)v < var->def->min) - || ((int)(long)v > var->def->max)) { + if(((int)(long)v < var->def->min) || ((int)(long)v > var->def->max)) { LM_ERR("integer value is out of range\n"); goto error0; } } - if ((val_type != CFG_VAR_UNSET) - && var->def->on_change_cb) { + if((val_type != CFG_VAR_UNSET) && var->def->on_change_cb) { /* Call the fixup function. * There is no need to set a temporary cfg handle, * because a single variable is changed */ - if (!group_id) { + if(!group_id) { var_block = *(group->handle); } else { - if (!cfg_local) { + if(!cfg_local) { LM_ERR("Local configuration is missing\n"); goto error0; } - group_inst = cfg_find_group(CFG_GROUP_META(cfg_local, group), - group->size, - *group_id); - if (!group_inst) { + group_inst = cfg_find_group( + CFG_GROUP_META(cfg_local, group), group->size, *group_id); + if(!group_inst) { LM_ERR("local group instance %.*s[%u] is not found\n", group_name->len, group_name->s, *group_id); goto error0; @@ -407,50 +394,44 @@ int cfg_set_now(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *va var_block = group_inst->vars; } - if (var->def->on_change_cb(var_block, - group_name, - var_name, - &v) < 0) { + if(var->def->on_change_cb(var_block, group_name, var_name, &v) < 0) { LM_ERR("fixup failed\n"); goto error0; } - } /* Set the per-child process callback only if the default value is changed. * The callback of other instances will be called when the config is * switched to that instance. */ - if (!group_id && var->def->on_set_child_cb) { + if(!group_id && var->def->on_set_child_cb) { /* get the name of the variable from the internal struct, * because var_name may be freed before the callback needs it */ s.s = group->name; s.len = group->name_len; s2.s = var->def->name; s2.len = var->name_len; - child_cb = cfg_child_cb_new(&s, &s2, - var->def->on_set_child_cb, - var->def->type); - if (!child_cb) { + child_cb = cfg_child_cb_new( + &s, &s2, var->def->on_set_child_cb, var->def->type); + if(!child_cb) { SHM_MEM_ERROR; goto error0; } } - if (cfg_shmized) { + if(cfg_shmized) { /* make sure that nobody else replaces the global config * while the new one is prepared */ CFG_WRITER_LOCK(); - if (group_id) { - group_inst = cfg_find_group(CFG_GROUP_META(*cfg_global, group), - group->size, - *group_id); - if (!group_inst) { + if(group_id) { + group_inst = cfg_find_group( + CFG_GROUP_META(*cfg_global, group), group->size, *group_id); + if(!group_inst) { LM_ERR("global group instance %.*s[%u] is not found\n", group_name->len, group_name->s, *group_id); goto error; } - if ((val_type == CFG_VAR_UNSET) && !CFG_VAR_TEST(group_inst, var)) { + if((val_type == CFG_VAR_UNSET) && !CFG_VAR_TEST(group_inst, var)) { /* nothing to do, the variable is not set in the group instance */ CFG_WRITER_UNLOCK(); LM_DBG("The variable is not set\n"); @@ -462,22 +443,25 @@ int cfg_set_now(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *va var_block = CFG_GROUP_DATA(*cfg_global, group); } - if (var->def->type & CFG_ATOMIC) { + if(var->def->type & CFG_ATOMIC) { /* atomic change is allowed, we can rewrite the value * directly in the global config */ p = var_block + var->offset; } else { /* clone the memory block, and prepare the modification */ - if (!(block = cfg_clone_global())) goto error; + if(!(block = cfg_clone_global())) + goto error; - if (group_inst) { + if(group_inst) { /* The additional array of the group needs to be also cloned. * When any of the variables within this array is changed, then * the complete config block and this array is replaced. */ - if (!(new_array = cfg_clone_array(CFG_GROUP_META(*cfg_global, group), group))) + if(!(new_array = cfg_clone_array( + CFG_GROUP_META(*cfg_global, group), group))) goto error; - group_inst = (cfg_group_inst_t *)translate_pointer((char *)new_array, + group_inst = (cfg_group_inst_t *)translate_pointer( + (char *)new_array, (char *)CFG_GROUP_META(*cfg_global, group)->array, (char *)group_inst); var_block = group_inst->vars; @@ -500,9 +484,9 @@ int cfg_set_now(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *va p = *(group->handle) + var->offset; } - if (val_type != CFG_VAR_UNSET) { + if(val_type != CFG_VAR_UNSET) { /* set the new value */ - switch (CFG_VAR_TYPE(var)) { + switch(CFG_VAR_TYPE(var)) { case CFG_VAR_INT: *(int *)p = (int)(long)v; break; @@ -511,7 +495,8 @@ int cfg_set_now(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *va /* clone the string to shm mem */ s.s = v; s.len = (s.s) ? strlen(s.s) : 0; - if (cfg_clone_str(&s, &s)) goto error; + if(cfg_clone_str(&s, &s)) + goto error; old_string = *(char **)p; *(char **)p = s.s; break; @@ -519,7 +504,8 @@ int cfg_set_now(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *va case CFG_VAR_STR: /* clone the string to shm mem */ s = *(str *)v; - if (cfg_clone_str(&s, &s)) goto error; + if(cfg_clone_str(&s, &s)) + goto error; old_string = *(char **)p; memcpy(p, &s, sizeof(str)); break; @@ -527,61 +513,65 @@ int cfg_set_now(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *va case CFG_VAR_POINTER: *(void **)p = v; break; - } - if (group_inst && !CFG_VAR_TEST_AND_SET(group_inst, var)) + if(group_inst && !CFG_VAR_TEST_AND_SET(group_inst, var)) old_string = NULL; /* the string is the same as the default one, * it cannot be freed */ } else { /* copy the default value to the group instance */ - if ((CFG_VAR_TYPE(var) == CFG_VAR_STRING) + if((CFG_VAR_TYPE(var) == CFG_VAR_STRING) || (CFG_VAR_TYPE(var) == CFG_VAR_STR)) old_string = *(char **)p; - memcpy(p, CFG_GROUP_DATA(*cfg_global, group) + var->offset, cfg_var_size(var)); + memcpy(p, CFG_GROUP_DATA(*cfg_global, group) + var->offset, + cfg_var_size(var)); CFG_VAR_TEST_AND_RESET(group_inst, var); } - if (cfg_shmized) { - if (!group_inst) { + if(cfg_shmized) { + if(!group_inst) { /* the default value is changed, the copies of this value * need to be also updated */ - if (cfg_update_defaults(CFG_GROUP_META(block ? block : *cfg_global, group), - group, var, p, - block ? 1 : 0) /* clone if needed */ - ) + if(cfg_update_defaults( + CFG_GROUP_META(block ? block : *cfg_global, group), + group, var, p, block ? 1 : 0) /* clone if needed */ + ) goto error; - if (block && (CFG_GROUP_META(block, group)->array != CFG_GROUP_META(*cfg_global, group)->array)) + if(block + && (CFG_GROUP_META(block, group)->array + != CFG_GROUP_META(*cfg_global, group)->array)) new_array = CFG_GROUP_META(block, group)->array; } - if (old_string || new_array) { + if(old_string || new_array) { /* prepare the array of the replaced strings, * and replaced group instances, * they will be freed when the old block is freed */ - replaced = (void **)shm_malloc(sizeof(void *) - * ((old_string?1:0) + (new_array?1:0) + 1)); - if (!replaced) { + replaced = (void **)shm_malloc( + sizeof(void *) + * ((old_string ? 1 : 0) + (new_array ? 1 : 0) + 1)); + if(!replaced) { SHM_MEM_ERROR; goto error; } i = 0; - if (old_string) { + if(old_string) { replaced[i] = old_string; i++; } - if (new_array) { + if(new_array) { replaced[i] = CFG_GROUP_META(*cfg_global, group)->array; i++; } replaced[i] = NULL; } /* replace the global config with the new one */ - if (block) cfg_install_global(block, replaced, child_cb, child_cb); + if(block) + cfg_install_global(block, replaced, child_cb, child_cb); CFG_WRITER_UNLOCK(); } else { /* cfg_set() may be called more than once before forking */ - if (old_string && (var->flag & cfg_var_shmized)) + if(old_string && (var->flag & cfg_var_shmized)) shm_free(old_string); /* flag the variable because there is no need @@ -591,55 +581,52 @@ int cfg_set_now(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *va /* the global config does not have to be replaced, * but the child callback has to be installed, otherwise the * child processes will miss the change */ - if (child_cb) + if(child_cb) cfg_install_child_cb(child_cb, child_cb); } - if (val_type == CFG_VAR_INT) - LM_INFO("%.*s.%.*s has been changed to %d\n", - group_name->len, group_name->s, - var_name->len, var_name->s, - (int)(long)val); + if(val_type == CFG_VAR_INT) + LM_INFO("%.*s.%.*s has been changed to %d\n", group_name->len, + group_name->s, var_name->len, var_name->s, (int)(long)val); - else if (val_type == CFG_VAR_STRING) - LM_INFO("%.*s.%.*s has been changed to \"%s\"\n", - group_name->len, group_name->s, - var_name->len, var_name->s, - (char *)val); + else if(val_type == CFG_VAR_STRING) + LM_INFO("%.*s.%.*s has been changed to \"%s\"\n", group_name->len, + group_name->s, var_name->len, var_name->s, (char *)val); - else if (val_type == CFG_VAR_STR) - LM_INFO("%.*s.%.*s has been changed to \"%.*s\"\n", - group_name->len, group_name->s, - var_name->len, var_name->s, - ((str *)val)->len, ((str *)val)->s); + else if(val_type == CFG_VAR_STR) + LM_INFO("%.*s.%.*s has been changed to \"%.*s\"\n", group_name->len, + group_name->s, var_name->len, var_name->s, ((str *)val)->len, + ((str *)val)->s); - else if (val_type == CFG_VAR_UNSET) - LM_INFO("%.*s.%.*s has been deleted\n", - group_name->len, group_name->s, + else if(val_type == CFG_VAR_UNSET) + LM_INFO("%.*s.%.*s has been deleted\n", group_name->len, group_name->s, var_name->len, var_name->s); else - LM_INFO("%.*s.%.*s has been changed\n", - group_name->len, group_name->s, + LM_INFO("%.*s.%.*s has been changed\n", group_name->len, group_name->s, var_name->len, var_name->s); - if (group_id) + if(group_id) LM_INFO("group id = %u\n", *group_id); convert_val_cleanup(); return 0; error: - if (cfg_shmized) CFG_WRITER_UNLOCK(); - if (block) cfg_block_free(block); - if (new_array) shm_free(new_array); - if (child_cb) cfg_child_cb_free_list(child_cb); - if (replaced) shm_free(replaced); + if(cfg_shmized) + CFG_WRITER_UNLOCK(); + if(block) + cfg_block_free(block); + if(new_array) + shm_free(new_array); + if(child_cb) + cfg_child_cb_free_list(child_cb); + if(replaced) + shm_free(replaced); error0: - LM_ERR("failed to set the variable: %.*s.%.*s\n", - group_name->len, group_name->s, - var_name->len, var_name->s); + LM_ERR("failed to set the variable: %.*s.%.*s\n", group_name->len, + group_name->s, var_name->len, var_name->s); convert_val_cleanup(); @@ -650,33 +637,33 @@ int cfg_set_now(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *va int cfg_set_now_int(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *var_name, int val) { - return cfg_set_now(ctx, group_name, group_id, var_name, - (void *)(long)val, CFG_VAR_INT); + return cfg_set_now(ctx, group_name, group_id, var_name, (void *)(long)val, + CFG_VAR_INT); } /* wrapper function for cfg_set_now */ int cfg_set_now_string(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *var_name, char *val) { - return cfg_set_now(ctx, group_name, group_id, var_name, - (void *)val, CFG_VAR_STRING); + return cfg_set_now( + ctx, group_name, group_id, var_name, (void *)val, CFG_VAR_STRING); } /* wrapper function for cfg_set_now */ int cfg_set_now_str(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *var_name, str *val) { - return cfg_set_now(ctx, group_name, group_id, var_name, - (void *)val, CFG_VAR_STR); + return cfg_set_now( + ctx, group_name, group_id, var_name, (void *)val, CFG_VAR_STR); } /* Delete a variable from the group instance. * wrapper function for cfg_set_now */ -int cfg_del_now(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, - str *var_name) +int cfg_del_now( + cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *var_name) { - return cfg_set_now(ctx, group_name, group_id, var_name, - NULL, CFG_VAR_UNSET); + return cfg_set_now( + ctx, group_name, group_id, var_name, NULL, CFG_VAR_UNSET); } /* sets the value of a variable but does not commit the change @@ -689,39 +676,38 @@ int cfg_del_now(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, int cfg_set_delayed(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *var_name, void *val, unsigned int val_type) { - cfg_group_t *group; - cfg_mapping_t *var; - void *v; - unsigned char *temp_handle; - int temp_handle_created; - cfg_changed_var_t *changed = NULL, **changed_p; - int size; - str s; - cfg_group_inst_t *group_inst = NULL; - unsigned char *var_block; - - if (!cfg_shmized) + cfg_group_t *group; + cfg_mapping_t *var; + void *v; + unsigned char *temp_handle; + int temp_handle_created; + cfg_changed_var_t *changed = NULL, **changed_p; + int size; + str s; + cfg_group_inst_t *group_inst = NULL; + unsigned char *var_block; + + if(!cfg_shmized) /* the cfg has not been shmized yet, there is no * point in registering the change and committing it later */ - return cfg_set_now(ctx, group_name, group_id, var_name, - val, val_type); + return cfg_set_now(ctx, group_name, group_id, var_name, val, val_type); - if (!ctx) { + if(!ctx) { LM_ERR("context is undefined\n"); return -1; } - if ((val_type == CFG_VAR_UNSET) && !group_id) { + if((val_type == CFG_VAR_UNSET) && !group_id) { LM_ERR("Only group instance values can be deleted\n"); return -1; } /* look-up the group and the variable */ - if (cfg_lookup_var(group_name, var_name, &group, &var)) + if(cfg_lookup_var(group_name, var_name, &group, &var)) return 1; /* check whether the variable is read-only */ - if (var->def->type & CFG_READONLY) { + if(var->def->type & CFG_READONLY) { LM_ERR("variable is read-only\n"); goto error0; } @@ -731,24 +717,21 @@ int cfg_set_delayed(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, * The reason is that such variables typically set global parameters * as opposed to per-process variables. Hence, it is not possible to set * the group handle temporary to another block, and then reset it back later. */ - if (group_id - && var->def->on_set_child_cb + if(group_id && var->def->on_set_child_cb && var->def->type & CFG_CB_ONLY_ONCE) { LM_ERR("This variable does not support multiple values.\n"); goto error0; } /* check whether we have to convert the type */ - if ((val_type != CFG_VAR_UNSET) + if((val_type != CFG_VAR_UNSET) && convert_val(val_type, val, CFG_INPUT_TYPE(var), &v)) goto error0; - if ((val_type != CFG_VAR_UNSET) - && (CFG_INPUT_TYPE(var) == CFG_INPUT_INT) + if((val_type != CFG_VAR_UNSET) && (CFG_INPUT_TYPE(var) == CFG_INPUT_INT) && (var->def->min || var->def->max)) { /* perform a simple min-max check for integers */ - if (((int)(long)v < var->def->min) - || ((int)(long)v > var->def->max)) { + if(((int)(long)v < var->def->min) || ((int)(long)v > var->def->max)) { LM_ERR("integer value is out of range\n"); goto error0; } @@ -758,24 +741,23 @@ int cfg_set_delayed(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, * the list of changed variables */ CFG_CTX_LOCK(ctx); - if ((val_type != CFG_VAR_UNSET) && var->def->on_change_cb) { + if((val_type != CFG_VAR_UNSET) && var->def->on_change_cb) { /* The fixup function must see also the * not yet committed values, so a temporary handle * must be prepared that points to the new config. * Only the values within the group are applied, * other modifications are not visible to the callback. * The local config is the base. */ - if (!group_id) { + if(!group_id) { var_block = *(group->handle); } else { - if (!cfg_local) { + if(!cfg_local) { LM_ERR("Local configuration is missing\n"); goto error; } - group_inst = cfg_find_group(CFG_GROUP_META(cfg_local, group), - group->size, - *group_id); - if (!group_inst) { + group_inst = cfg_find_group( + CFG_GROUP_META(cfg_local, group), group->size, *group_id); + if(!group_inst) { LM_ERR("local group instance %.*s[%u] is not found\n", group_name->len, group_name->s, *group_id); goto error; @@ -783,9 +765,9 @@ int cfg_set_delayed(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, var_block = group_inst->vars; } - if (ctx->changed_first) { + if(ctx->changed_first) { temp_handle = (unsigned char *)pkg_malloc(group->size); - if (!temp_handle) { + if(!temp_handle) { PKG_MEM_ERROR; goto error; } @@ -793,23 +775,20 @@ int cfg_set_delayed(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, memcpy(temp_handle, var_block, group->size); /* apply the changes */ - for ( changed = ctx->changed_first; - changed; - changed = changed->next - ) { - if (changed->group != group) + for(changed = ctx->changed_first; changed; + changed = changed->next) { + if(changed->group != group) continue; - if ((!group_id && !changed->group_id_set) /* default values */ + if((!group_id && !changed->group_id_set) /* default values */ || (group_id && !changed->group_id_set - && !CFG_VAR_TEST(group_inst, changed->var)) + && !CFG_VAR_TEST(group_inst, changed->var)) /* default value is changed which affects the group_instance */ || (group_id && changed->group_id_set - && (*group_id == changed->group_id)) + && (*group_id == changed->group_id)) /* change within the group instance */ - ) - memcpy( temp_handle + changed->var->offset, - changed->new_val.vraw, - cfg_var_size(changed->var)); + ) + memcpy(temp_handle + changed->var->offset, + changed->new_val.vraw, cfg_var_size(changed->var)); } } else { /* there is not any change */ @@ -817,37 +796,34 @@ int cfg_set_delayed(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, temp_handle_created = 0; } - if (var->def->on_change_cb(temp_handle, - group_name, - var_name, - &v) < 0) { + if(var->def->on_change_cb(temp_handle, group_name, var_name, &v) < 0) { LM_ERR("fixup failed\n"); - if (temp_handle_created) pkg_free(temp_handle); + if(temp_handle_created) + pkg_free(temp_handle); goto error; } - if (temp_handle_created) pkg_free(temp_handle); - + if(temp_handle_created) + pkg_free(temp_handle); } /* everything went ok, we can add the new value to the list */ - size = sizeof(cfg_changed_var_t) - - sizeof(((cfg_changed_var_t*)0)->new_val) - + ((val_type != CFG_VAR_UNSET) ? cfg_var_size(var) : 0); + size = sizeof(cfg_changed_var_t) - sizeof(((cfg_changed_var_t *)0)->new_val) + + ((val_type != CFG_VAR_UNSET) ? cfg_var_size(var) : 0); changed = (cfg_changed_var_t *)shm_malloc(size); - if (!changed) { + if(!changed) { SHM_MEM_ERROR; goto error; } memset(changed, 0, size); changed->group = group; changed->var = var; - if (group_id) { + if(group_id) { changed->group_id = *group_id; changed->group_id_set = 1; } - if (val_type != CFG_VAR_UNSET) { - switch (CFG_VAR_TYPE(var)) { + if(val_type != CFG_VAR_UNSET) { + switch(CFG_VAR_TYPE(var)) { case CFG_VAR_INT: changed->new_val.vint = (int)(long)v; @@ -857,21 +833,22 @@ int cfg_set_delayed(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, /* clone the string to shm mem */ s.s = v; s.len = (s.s) ? strlen(s.s) : 0; - if (cfg_clone_str(&s, &s)) goto error; + if(cfg_clone_str(&s, &s)) + goto error; changed->new_val.vp = s.s; break; case CFG_VAR_STR: /* clone the string to shm mem */ s = *(str *)v; - if (cfg_clone_str(&s, &s)) goto error; - changed->new_val.vstr=s; + if(cfg_clone_str(&s, &s)) + goto error; + changed->new_val.vstr = s; break; case CFG_VAR_POINTER: - changed->new_val.vp=v; + changed->new_val.vp = v; break; - } } else { changed->del_value = 1; @@ -883,77 +860,67 @@ int cfg_set_delayed(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, * do not have to be looked-up for each and every variable. */ /* Check whether there is any variable in the list which * belongs to the same group */ - for ( changed_p = &ctx->changed_first; + for(changed_p = &ctx->changed_first; *changed_p && ((*changed_p)->group != changed->group); - changed_p = &(*changed_p)->next); + changed_p = &(*changed_p)->next) + ; /* try to find the group instance, and move changed_p to the end of * the instance. */ - for ( ; - *changed_p - && ((*changed_p)->group == changed->group) + for(; *changed_p && ((*changed_p)->group == changed->group) && (!(*changed_p)->group_id_set - || ((*changed_p)->group_id_set && changed->group_id_set - && ((*changed_p)->group_id <= changed->group_id))); - changed_p = &(*changed_p)->next); + || ((*changed_p)->group_id_set && changed->group_id_set + && ((*changed_p)->group_id <= changed->group_id))); + changed_p = &(*changed_p)->next) + ; /* Add the new variable before *changed_p */ changed->next = *changed_p; *changed_p = changed; CFG_CTX_UNLOCK(ctx); - if (val_type == CFG_VAR_INT) + if(val_type == CFG_VAR_INT) LM_INFO("%.*s.%.*s is going to be changed to %d " "[context=%p]\n", - group_name->len, group_name->s, - var_name->len, var_name->s, - (int)(long)val, - ctx); + group_name->len, group_name->s, var_name->len, var_name->s, + (int)(long)val, ctx); - else if (val_type == CFG_VAR_STRING) + else if(val_type == CFG_VAR_STRING) LM_INFO("%.*s.%.*s is going to be changed to \"%s\" " "[context=%p]\n", - group_name->len, group_name->s, - var_name->len, var_name->s, - (char *)val, - ctx); + group_name->len, group_name->s, var_name->len, var_name->s, + (char *)val, ctx); - else if (val_type == CFG_VAR_STR) + else if(val_type == CFG_VAR_STR) LM_INFO("%.*s.%.*s is going to be changed to \"%.*s\" " "[context=%p]\n", - group_name->len, group_name->s, - var_name->len, var_name->s, - ((str *)val)->len, ((str *)val)->s, - ctx); + group_name->len, group_name->s, var_name->len, var_name->s, + ((str *)val)->len, ((str *)val)->s, ctx); - else if (val_type == CFG_VAR_UNSET) + else if(val_type == CFG_VAR_UNSET) LM_INFO("%.*s.%.*s is going to be deleted " "[context=%p]\n", - group_name->len, group_name->s, - var_name->len, var_name->s, + group_name->len, group_name->s, var_name->len, var_name->s, ctx); else LM_INFO("%.*s.%.*s is going to be changed " "[context=%p]\n", - group_name->len, group_name->s, - var_name->len, var_name->s, + group_name->len, group_name->s, var_name->len, var_name->s, ctx); - if (group_id) - LM_INFO("group id = %u [context=%p]\n", - *group_id, - ctx); + if(group_id) + LM_INFO("group id = %u [context=%p]\n", *group_id, ctx); convert_val_cleanup(); return 0; error: CFG_CTX_UNLOCK(ctx); - if (changed) shm_free(changed); + if(changed) + shm_free(changed); error0: - LM_ERR("failed to set the variable: %.*s.%.*s\n", - group_name->len, group_name->s, - var_name->len, var_name->s); + LM_ERR("failed to set the variable: %.*s.%.*s\n", group_name->len, + group_name->s, var_name->len, var_name->s); convert_val_cleanup(); return -1; @@ -971,56 +938,58 @@ int cfg_set_delayed_int(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, int cfg_set_delayed_string(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *var_name, char *val) { - return cfg_set_delayed(ctx, group_name, group_id, var_name, - (void *)val, CFG_VAR_STRING); + return cfg_set_delayed( + ctx, group_name, group_id, var_name, (void *)val, CFG_VAR_STRING); } /* wrapper function for cfg_set_delayed */ -int cfg_set_delayed_str(cfg_ctx_t *ctx, str *group_name, - unsigned int *group_id, str *var_name, str *val) +int cfg_set_delayed_str(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, + str *var_name, str *val) { - return cfg_set_delayed(ctx, group_name, group_id, var_name, - (void *)val, CFG_VAR_STR); + return cfg_set_delayed( + ctx, group_name, group_id, var_name, (void *)val, CFG_VAR_STR); } /* Delete a variable from the group instance. * wrapper function for cfg_set_delayed */ -int cfg_del_delayed(cfg_ctx_t *ctx, str *group_name, - unsigned int *group_id, str *var_name) +int cfg_del_delayed( + cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *var_name) { - return cfg_set_delayed(ctx, group_name, group_id, var_name, - NULL, CFG_VAR_UNSET); + return cfg_set_delayed( + ctx, group_name, group_id, var_name, NULL, CFG_VAR_UNSET); } /* commits the previously prepared changes within the context */ int cfg_commit(cfg_ctx_t *ctx) { - int replaced_num = 0; - cfg_changed_var_t *changed, *changed2; - cfg_block_t *block = NULL; - void **replaced = NULL; - cfg_child_cb_t *child_cb; - cfg_child_cb_t *child_cb_first = NULL; - cfg_child_cb_t *child_cb_last = NULL; - int size; - void *p; - str s, s2; - cfg_group_t *group; - cfg_group_inst_t *group_inst = NULL; - - if (!ctx) { + int replaced_num = 0; + cfg_changed_var_t *changed, *changed2; + cfg_block_t *block = NULL; + void **replaced = NULL; + cfg_child_cb_t *child_cb; + cfg_child_cb_t *child_cb_first = NULL; + cfg_child_cb_t *child_cb_last = NULL; + int size; + void *p; + str s, s2; + cfg_group_t *group; + cfg_group_inst_t *group_inst = NULL; + + if(!ctx) { LM_ERR("context is undefined\n"); return -1; } - if (!cfg_shmized) return 0; /* nothing to do */ + if(!cfg_shmized) + return 0; /* nothing to do */ /* the ctx must be locked while reading and writing * the list of changed variables */ CFG_CTX_LOCK(ctx); /* is there any change? */ - if (!ctx->changed_first) goto done; + if(!ctx->changed_first) + goto done; /* Count the number of replaced strings, * and replaced group arrays. @@ -1038,12 +1007,12 @@ int cfg_commit(cfg_ctx_t *ctx) replaced_num++; /* See the above comments for strings */ - if (group != changed->group) { + if(group != changed->group) { replaced_num++; group = changed->group; } - if (changed->group && !changed->group_id_set + if(changed->group && !changed->group_id_set && changed->var->def->on_set_child_cb) { s.s = changed->group->name; s.len = changed->group->name_len; @@ -1052,9 +1021,10 @@ int cfg_commit(cfg_ctx_t *ctx) child_cb = cfg_child_cb_new(&s, &s2, changed->var->def->on_set_child_cb, changed->var->def->type); - if (!child_cb) goto error0; + if(!child_cb) + goto error0; - if (child_cb_last) + if(child_cb_last) child_cb_last->next = child_cb; else child_cb_first = child_cb; @@ -1062,15 +1032,15 @@ int cfg_commit(cfg_ctx_t *ctx) } } - if (replaced_num) { + if(replaced_num) { /* allocate memory for the replaced string array */ - size = sizeof(void *)*(replaced_num + 1); + size = sizeof(void *) * (replaced_num + 1); replaced = (void **)shm_malloc(size); - if (!replaced) { + if(!replaced) { SHM_MEM_ERROR; goto error0; } - memset(replaced, 0 , size); + memset(replaced, 0, size); } else { /* no replacement */ LM_INFO("commit operation executed without having changes\n"); @@ -1082,7 +1052,7 @@ int cfg_commit(cfg_ctx_t *ctx) CFG_WRITER_LOCK(); /* clone the memory block, and prepare the modification */ - if (!(block = cfg_clone_global())) + if(!(block = cfg_clone_global())) goto error; /* Apply the modifications to the buffer. @@ -1093,87 +1063,85 @@ int cfg_commit(cfg_ctx_t *ctx) * last group array that * has been cloned */ changed; changed = changed->next) { - if (!changed->group_id_set) { - p = CFG_GROUP_DATA(block, changed->group) - + changed->var->offset; + if(!changed->group_id_set) { + p = CFG_GROUP_DATA(block, changed->group) + changed->var->offset; group_inst = NULL; /* force the look-up of the next group_inst */ } else { - if (group != changed->group) { + if(group != changed->group) { /* The group array has not been cloned yet. */ group = changed->group; - if (!(CFG_GROUP_META(block, group)->array = - cfg_clone_array(CFG_GROUP_META(*cfg_global, group), group)) - ) { + if(!(CFG_GROUP_META(block, group)->array = cfg_clone_array( + CFG_GROUP_META(*cfg_global, group), group))) { LM_ERR("group array cannot be cloned for %.*s[%u]\n", group->name_len, group->name, changed->group_id); goto error; } - replaced[replaced_num] = CFG_GROUP_META(*cfg_global, group)->array; + replaced[replaced_num] = + CFG_GROUP_META(*cfg_global, group)->array; replaced_num++; group_inst = NULL; /* fore the look-up of group_inst */ } - if (group && (!group_inst || (group_inst->id != changed->group_id))) { + if(group + && (!group_inst || (group_inst->id != changed->group_id))) { group_inst = cfg_find_group(CFG_GROUP_META(block, group), - group->size, - changed->group_id); + group->size, changed->group_id); } - if (group && !group_inst) { + if(group && !group_inst) { LM_ERR("global group instance %.*s[%u] is not found\n", group->name_len, group->name, changed->group_id); goto error; } p = group_inst->vars + changed->var->offset; } - if(p==NULL) { + if(p == NULL) { LM_ERR("failed to resolve valid variable offset\n"); goto error; } - if (((changed->group_id_set && !changed->del_value - && CFG_VAR_TEST_AND_SET(group_inst, changed->var)) - || (changed->group_id_set && changed->del_value - && CFG_VAR_TEST_AND_RESET(group_inst, changed->var)) - || !changed->group_id_set) + if(((changed->group_id_set && !changed->del_value + && CFG_VAR_TEST_AND_SET(group_inst, changed->var)) + || (changed->group_id_set && changed->del_value + && CFG_VAR_TEST_AND_RESET(group_inst, changed->var)) + || !changed->group_id_set) && ((CFG_VAR_TYPE(changed->var) == CFG_VAR_STRING) - || (CFG_VAR_TYPE(changed->var) == CFG_VAR_STR)) - ) { + || (CFG_VAR_TYPE(changed->var) == CFG_VAR_STR))) { replaced[replaced_num] = *(char **)p; - if (replaced[replaced_num]) + if(replaced[replaced_num]) replaced_num++; /* else do not increase replaced_num, because * the cfg_block_free() will stop at the first * NULL value */ } - if (!changed->del_value) - memcpy( p, - changed->new_val.vraw, - cfg_var_size(changed->var)); + if(!changed->del_value) + memcpy(p, changed->new_val.vraw, cfg_var_size(changed->var)); else - memcpy( p, - CFG_GROUP_DATA(block, changed->group) + changed->var->offset, + memcpy(p, + CFG_GROUP_DATA(block, changed->group) + + changed->var->offset, cfg_var_size(changed->var)); - if (!changed->group_id_set) { + if(!changed->group_id_set) { /* the default value is changed, the copies of this value * need to be also updated */ - if (cfg_update_defaults(CFG_GROUP_META(block, changed->group), - changed->group, changed->var, p, - (group != changed->group)) /* clone if the array + if(cfg_update_defaults(CFG_GROUP_META(block, changed->group), + changed->group, changed->var, p, + (group != changed->group)) /* clone if the array * has not been cloned yet */ - ) + ) goto error; - if ((group != changed->group) + if((group != changed->group) && (CFG_GROUP_META(block, changed->group)->array - != CFG_GROUP_META(*cfg_global, changed->group)->array) - ) { + != CFG_GROUP_META(*cfg_global, changed->group) + ->array)) { /* The array has been cloned */ group = changed->group; - replaced[replaced_num] = CFG_GROUP_META(*cfg_global, group)->array; + replaced[replaced_num] = + CFG_GROUP_META(*cfg_global, group)->array; replaced_num++; } } @@ -1184,45 +1152,39 @@ int cfg_commit(cfg_ctx_t *ctx) CFG_WRITER_UNLOCK(); /* free the changed list */ - for ( changed = ctx->changed_first; - changed; - changed = changed2 - ) { + for(changed = ctx->changed_first; changed; changed = changed2) { changed2 = changed->next; shm_free(changed); } ctx->changed_first = NULL; done: - LM_INFO("config changes have been applied [context=%p]\n", - ctx); + LM_INFO("config changes have been applied [context=%p]\n", ctx); CFG_CTX_UNLOCK(ctx); return 0; error: - if (block) { + if(block) { /* clean the new block from the cloned arrays */ - for (group = cfg_group; - group; - group = group->next - ) - if (CFG_GROUP_META(block, group)->array + for(group = cfg_group; group; group = group->next) + if(CFG_GROUP_META(block, group)->array && (CFG_GROUP_META(block, group)->array - != CFG_GROUP_META(*cfg_global, group)->array) - ) + != CFG_GROUP_META(*cfg_global, group)->array)) shm_free(CFG_GROUP_META(block, group)->array); /* the block can be freed outside of the writer lock */ } CFG_WRITER_UNLOCK(); - if (block) + if(block) shm_free(block); error0: CFG_CTX_UNLOCK(ctx); - if (child_cb_first) cfg_child_cb_free_list(child_cb_first); - if (replaced) shm_free(replaced); + if(child_cb_first) + cfg_child_cb_free_list(child_cb_first); + if(replaced) + shm_free(replaced); return -1; } @@ -1230,33 +1192,29 @@ int cfg_commit(cfg_ctx_t *ctx) /* drops the not yet committed changes within the context */ int cfg_rollback(cfg_ctx_t *ctx) { - cfg_changed_var_t *changed, *changed2; + cfg_changed_var_t *changed, *changed2; - if (!ctx) { + if(!ctx) { LM_ERR("context is undefined\n"); return -1; } - if (!cfg_shmized) return 0; /* nothing to do */ + if(!cfg_shmized) + return 0; /* nothing to do */ - LM_INFO("deleting the config changes [context=%p]\n", - ctx); + LM_INFO("deleting the config changes [context=%p]\n", ctx); /* the ctx must be locked while reading and writing * the list of changed variables */ CFG_CTX_LOCK(ctx); - for (changed = ctx->changed_first; - changed; - changed = changed2 - ) { + for(changed = ctx->changed_first; changed; changed = changed2) { changed2 = changed->next; - if (!changed->del_value + if(!changed->del_value && ((CFG_VAR_TYPE(changed->var) == CFG_VAR_STRING) - || (CFG_VAR_TYPE(changed->var) == CFG_VAR_STR)) - ) { - if (changed->new_val.vp) + || (CFG_VAR_TYPE(changed->var) == CFG_VAR_STR))) { + if(changed->new_val.vp) shm_free(changed->new_val.vp); } shm_free(changed); @@ -1277,41 +1235,40 @@ int cfg_rollback(cfg_ctx_t *ctx) int cfg_get_by_name(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *var_name, void **val, unsigned int *val_type) { - cfg_group_t *group; - cfg_mapping_t *var; - void *p; - static str s; /* we need the value even + cfg_group_t *group; + cfg_mapping_t *var; + void *p; + static str s; /* we need the value even * after the function returns */ - cfg_group_inst_t *group_inst; + cfg_group_inst_t *group_inst; /* verify the context even if we do not need it now * to make sure that a cfg driver has called the function * (very very weak security) */ - if (!ctx) { + if(!ctx) { LM_ERR("context is undefined\n"); return -1; } /* look-up the group and the variable */ - if (cfg_lookup_var(group_name, var_name, &group, &var)) + if(cfg_lookup_var(group_name, var_name, &group, &var)) return -1; - if (var->def->on_change_cb) { + if(var->def->on_change_cb) { /* The variable cannot be retrieved, because the fixup * function may have changed it, and it is better to return * an error than an incorrect value */ return 1; } - if (group_id) { - if (!cfg_local) { + if(group_id) { + if(!cfg_local) { LM_ERR("Local configuration is missing\n"); return -1; } - group_inst = cfg_find_group(CFG_GROUP_META(cfg_local, group), - group->size, - *group_id); - if (!group_inst) { + group_inst = cfg_find_group( + CFG_GROUP_META(cfg_local, group), group->size, *group_id); + if(!group_inst) { LM_ERR("local group instance %.*s[%u] is not found\n", group_name->len, group_name->s, *group_id); return -1; @@ -1325,7 +1282,7 @@ int cfg_get_by_name(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, p = *(group->handle) + var->offset; } - switch (CFG_VAR_TYPE(var)) { + switch(CFG_VAR_TYPE(var)) { case CFG_VAR_INT: *val = (void *)(long)*(int *)p; break; @@ -1342,7 +1299,6 @@ int cfg_get_by_name(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, case CFG_VAR_POINTER: *val = *(void **)p; break; - } *val_type = CFG_VAR_TYPE(var); @@ -1359,22 +1315,22 @@ int cfg_get_default_value_by_name(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *var_name, void **val, unsigned int *val_type) { - cfg_group_t *group; - cfg_mapping_t *var; - void *p; - static str s; /* we need the value even + cfg_group_t *group; + cfg_mapping_t *var; + void *p; + static str s; /* we need the value even * after the function returns */ /* verify the context even if we do not need it now * to make sure that a cfg driver has called the function * (very very weak security) */ - if (!ctx) { + if(!ctx) { LM_ERR("context is undefined\n"); return -1; } /* look-up the group and the variable */ - if (cfg_lookup_var(group_name, var_name, &group, &var)) { + if(cfg_lookup_var(group_name, var_name, &group, &var)) { return -1; } else { /* if variables exist then prevents resetting the read-only ones */ @@ -1382,7 +1338,7 @@ int cfg_get_default_value_by_name(cfg_ctx_t *ctx, str *group_name, return -1; } - if (var->def->on_change_cb) { + if(var->def->on_change_cb) { /* The variable cannot be retrieved, because the fixup * function may have changed it, and it is better to return * an error than an incorrect value */ @@ -1393,7 +1349,7 @@ int cfg_get_default_value_by_name(cfg_ctx_t *ctx, str *group_name, * the variable for any group*/ p = (group->orig_handle) + var->offset; - switch (CFG_VAR_TYPE(var)) { + switch(CFG_VAR_TYPE(var)) { case CFG_VAR_INT: *val = (void *)(long)*(int *)p; break; @@ -1410,7 +1366,6 @@ int cfg_get_default_value_by_name(cfg_ctx_t *ctx, str *group_name, case CFG_VAR_POINTER: *val = *(void **)p; break; - } *val_type = CFG_VAR_TYPE(var); @@ -1419,25 +1374,25 @@ int cfg_get_default_value_by_name(cfg_ctx_t *ctx, str *group_name, /* returns the description of a variable */ -int cfg_help(cfg_ctx_t *ctx, str *group_name, str *var_name, - char **ch, unsigned int *input_type) +int cfg_help(cfg_ctx_t *ctx, str *group_name, str *var_name, char **ch, + unsigned int *input_type) { - cfg_mapping_t *var; + cfg_mapping_t *var; /* verify the context even if we do not need it now * to make sure that a cfg driver has called the function * (very very weak security) */ - if (!ctx) { + if(!ctx) { LM_ERR("context is undefined\n"); return -1; } /* look-up the group and the variable */ - if (cfg_lookup_var(group_name, var_name, NULL, &var)) + if(cfg_lookup_var(group_name, var_name, NULL, &var)) return -1; *ch = var->def->descr; - if (input_type) + if(input_type) *input_type = CFG_INPUT_TYPE(var); return 0; } @@ -1448,13 +1403,13 @@ int cfg_help(cfg_ctx_t *ctx, str *group_name, str *var_name, * 0: no more group * 1: group exists */ -int cfg_get_group_next(void **h, - str *gname, cfg_def_t **def) +int cfg_get_group_next(void **h, str *gname, cfg_def_t **def) { - cfg_group_t *group; + cfg_group_t *group; group = (cfg_group_t *)(*h); - if (group == NULL) return 0; + if(group == NULL) + return 0; gname->s = group->name; gname->len = group->name_len; @@ -1465,10 +1420,9 @@ int cfg_get_group_next(void **h, } /* Initialize the handle for cfg_diff_next() */ -int cfg_diff_init(cfg_ctx_t *ctx, - void **h) +int cfg_diff_init(cfg_ctx_t *ctx, void **h) { - if (!ctx) { + if(!ctx) { LM_ERR("context is undefined\n"); return -1; } @@ -1486,19 +1440,18 @@ int cfg_diff_init(cfg_ctx_t *ctx, * 0: no more changed value found * -1: error occurred */ -int cfg_diff_next(void **h, - str *gname, unsigned int **gid, str *vname, - void **old_val, void **new_val, - unsigned int *val_type) +int cfg_diff_next(void **h, str *gname, unsigned int **gid, str *vname, + void **old_val, void **new_val, unsigned int *val_type) { - cfg_changed_var_t *changed; - cfg_group_inst_t *group_inst; - union cfg_var_value *pval_old, *pval_new; - static str old_s, new_s; /* we need the value even + cfg_changed_var_t *changed; + cfg_group_inst_t *group_inst; + union cfg_var_value *pval_old, *pval_new; + static str old_s, new_s; /* we need the value even * after the function returns */ changed = (cfg_changed_var_t *)(*h); - if (changed == NULL) return 0; + if(changed == NULL) + return 0; gname->s = changed->group->name; gname->len = changed->group->name_len; @@ -1509,33 +1462,32 @@ int cfg_diff_next(void **h, /* use the module's handle to access the variable * It means that the variable is read from the local config * after forking */ - if (!changed->group_id_set) { - pval_old = (union cfg_var_value*) - (*(changed->group->handle) + changed->var->offset); + if(!changed->group_id_set) { + pval_old = (union cfg_var_value *)(*(changed->group->handle) + + changed->var->offset); } else { - if (!cfg_local) { + if(!cfg_local) { LM_ERR("Local configuration is missing\n"); return -1; } group_inst = cfg_find_group(CFG_GROUP_META(cfg_local, changed->group), - changed->group->size, - changed->group_id); - if (!group_inst) { + changed->group->size, changed->group_id); + if(!group_inst) { LM_ERR("local group instance %.*s[%u] is not found\n", changed->group->name_len, changed->group->name, changed->group_id); return -1; } - pval_old = (union cfg_var_value*) - (group_inst->vars + changed->var->offset); + pval_old = (union cfg_var_value *)(group_inst->vars + + changed->var->offset); } - if (!changed->del_value) + if(!changed->del_value) pval_new = &changed->new_val; else - pval_new = (union cfg_var_value*) - (*(changed->group->handle) + changed->var->offset); + pval_new = (union cfg_var_value *)(*(changed->group->handle) + + changed->var->offset); - switch (CFG_VAR_TYPE(changed->var)) { + switch(CFG_VAR_TYPE(changed->var)) { case CFG_VAR_INT: *old_val = (void *)(long)pval_old->vint; *new_val = (void *)(long)pval_new->vint; @@ -1547,9 +1499,9 @@ int cfg_diff_next(void **h, break; case CFG_VAR_STR: - old_s=pval_old->vstr; + old_s = pval_old->vstr; *old_val = (void *)&old_s; - new_s=pval_new->vstr; + new_s = pval_new->vstr; *new_val = (void *)&new_s; break; @@ -1557,7 +1509,6 @@ int cfg_diff_next(void **h, *old_val = pval_old->vp; *new_val = pval_new->vp; break; - } *val_type = CFG_VAR_TYPE(changed->var); @@ -1568,7 +1519,7 @@ int cfg_diff_next(void **h, /* release the handle of cfg_diff_next() */ void cfg_diff_release(cfg_ctx_t *ctx) { - if (!ctx) { + if(!ctx) { LM_ERR("context is undefined\n"); return; } @@ -1579,28 +1530,28 @@ void cfg_diff_release(cfg_ctx_t *ctx) /* Add a new instance to an existing group */ int cfg_add_group_inst(cfg_ctx_t *ctx, str *group_name, unsigned int group_id) { - cfg_group_t *group; - cfg_block_t *block = NULL; - void **replaced = NULL; - cfg_group_inst_t *new_array = NULL, *new_inst; + cfg_group_t *group; + cfg_block_t *block = NULL; + void **replaced = NULL; + cfg_group_inst_t *new_array = NULL, *new_inst; /* verify the context even if we do not need it now * to make sure that a cfg driver has called the function * (very very weak security) */ - if (!ctx) { + if(!ctx) { LM_ERR("context is undefined\n"); return -1; } - if (!cfg_shmized) { + if(!cfg_shmized) { /* Add a new variable without any value to * the linked list of additional values. This variable * will force a new group instance to be created. */ - return new_add_var(group_name, group_id, NULL /* var_name */, + return new_add_var(group_name, group_id, NULL /* var_name */, NULL /* val */, 0 /* type */); } - if (!(group = cfg_lookup_group(group_name->s, group_name->len))) { + if(!(group = cfg_lookup_group(group_name->s, group_name->len))) { LM_ERR("group not found\n"); return -1; } @@ -1608,10 +1559,8 @@ int cfg_add_group_inst(cfg_ctx_t *ctx, str *group_name, unsigned int group_id) /* make sure that nobody else replaces the global config * while the new one is prepared */ CFG_WRITER_LOCK(); - if (cfg_find_group(CFG_GROUP_META(*cfg_global, group), - group->size, - group_id) - ) { + if(cfg_find_group( + CFG_GROUP_META(*cfg_global, group), group->size, group_id)) { LM_DBG("the group instance already exists\n"); CFG_WRITER_UNLOCK(); return 0; /* not an error */ @@ -1619,30 +1568,26 @@ int cfg_add_group_inst(cfg_ctx_t *ctx, str *group_name, unsigned int group_id) /* clone the global memory block because the additional array can be * replaced only together with the block. */ - if (!(block = cfg_clone_global())) + if(!(block = cfg_clone_global())) goto error; /* Extend the array with a new group instance */ - if (!(new_array = cfg_extend_array(CFG_GROUP_META(*cfg_global, group), group, - group_id, - &new_inst)) - ) + if(!(new_array = cfg_extend_array(CFG_GROUP_META(*cfg_global, group), group, + group_id, &new_inst))) goto error; /* fill in the new group instance with the default data */ - memcpy( new_inst->vars, - CFG_GROUP_DATA(*cfg_global, group), - group->size); + memcpy(new_inst->vars, CFG_GROUP_DATA(*cfg_global, group), group->size); CFG_GROUP_META(block, group)->array = new_array; CFG_GROUP_META(block, group)->num++; - if (CFG_GROUP_META(*cfg_global, group)->array) { + if(CFG_GROUP_META(*cfg_global, group)->array) { /* prepare the array of the replaced strings, * and replaced group instances, * they will be freed when the old block is freed */ replaced = (void **)shm_malloc(sizeof(void *) * 2); - if (!replaced) { + if(!replaced) { SHM_MEM_ERROR; goto error; } @@ -1653,9 +1598,8 @@ int cfg_add_group_inst(cfg_ctx_t *ctx, str *group_name, unsigned int group_id) cfg_install_global(block, replaced, NULL, NULL); CFG_WRITER_UNLOCK(); - LM_INFO("group instance is added: %.*s[%u]\n", - group_name->len, group_name->s, - group_id); + LM_INFO("group instance is added: %.*s[%u]\n", group_name->len, + group_name->s, group_id); /* Make sure that cfg_set_*() sees the change when * the function is immediately called after the group @@ -1665,13 +1609,15 @@ int cfg_add_group_inst(cfg_ctx_t *ctx, str *group_name, unsigned int group_id) return 0; error: CFG_WRITER_UNLOCK(); - if (block) cfg_block_free(block); - if (new_array) shm_free(new_array); - if (replaced) shm_free(replaced); + if(block) + cfg_block_free(block); + if(new_array) + shm_free(new_array); + if(replaced) + shm_free(replaced); - LM_ERR("Failed to add the group instance: %.*s[%u]\n", - group_name->len, group_name->s, - group_id); + LM_ERR("Failed to add the group instance: %.*s[%u]\n", group_name->len, + group_name->s, group_id); return -1; } @@ -1679,28 +1625,28 @@ int cfg_add_group_inst(cfg_ctx_t *ctx, str *group_name, unsigned int group_id) /* Delete an instance of a group */ int cfg_del_group_inst(cfg_ctx_t *ctx, str *group_name, unsigned int group_id) { - cfg_group_t *group; - cfg_block_t *block = NULL; - void **replaced = NULL; - cfg_group_inst_t *new_array = NULL, *group_inst; - cfg_mapping_t *var; - int i, num; + cfg_group_t *group; + cfg_block_t *block = NULL; + void **replaced = NULL; + cfg_group_inst_t *new_array = NULL, *group_inst; + cfg_mapping_t *var; + int i, num; /* verify the context even if we do not need it now * to make sure that a cfg driver has called the function * (very very weak security) */ - if (!ctx) { + if(!ctx) { LM_ERR("context is undefined\n"); return -1; } - if (!cfg_shmized) { + if(!cfg_shmized) { /* It makes no sense to delete a group instance that has not * been created yet */ return -1; } - if (!(group = cfg_lookup_group(group_name->s, group_name->len))) { + if(!(group = cfg_lookup_group(group_name->s, group_name->len))) { LM_ERR("group not found\n"); return -1; } @@ -1708,60 +1654,57 @@ int cfg_del_group_inst(cfg_ctx_t *ctx, str *group_name, unsigned int group_id) /* make sure that nobody else replaces the global config * while the new one is prepared */ CFG_WRITER_LOCK(); - if (!(group_inst = cfg_find_group(CFG_GROUP_META(*cfg_global, group), - group->size, - group_id)) - ) { + if(!(group_inst = cfg_find_group( + CFG_GROUP_META(*cfg_global, group), group->size, group_id))) { LM_DBG("the group instance does not exist\n"); goto error; } /* clone the global memory block because the additional array can be * replaced only together with the block. */ - if (!(block = cfg_clone_global())) + if(!(block = cfg_clone_global())) goto error; /* Remove the group instance from the array. */ - if (cfg_collapse_array(CFG_GROUP_META(*cfg_global, group), group, - group_inst, - &new_array)) + if(cfg_collapse_array(CFG_GROUP_META(*cfg_global, group), group, group_inst, + &new_array)) goto error; CFG_GROUP_META(block, group)->array = new_array; CFG_GROUP_META(block, group)->num--; - if (CFG_GROUP_META(*cfg_global, group)->array) { + if(CFG_GROUP_META(*cfg_global, group)->array) { /* prepare the array of the replaced strings, * and replaced group instances, * they will be freed when the old block is freed */ /* count the number of strings that has to be freed */ num = 0; - for (i = 0; i < group->num; i++) { + for(i = 0; i < group->num; i++) { var = &group->mapping[i]; - if (CFG_VAR_TEST(group_inst, var) + if(CFG_VAR_TEST(group_inst, var) && ((CFG_VAR_TYPE(var) == CFG_VAR_STRING) - || (CFG_VAR_TYPE(var) == CFG_VAR_STR)) + || (CFG_VAR_TYPE(var) == CFG_VAR_STR)) && (*(char **)(group_inst->vars + var->offset) != NULL)) num++; } replaced = (void **)shm_malloc(sizeof(void *) * (num + 2)); - if (!replaced) { + if(!replaced) { SHM_MEM_ERROR; goto error; } - if (num) { + if(num) { /* There was at least one string to free, go though the list again */ num = 0; - for (i = 0; i < group->num; i++) { + for(i = 0; i < group->num; i++) { var = &group->mapping[i]; - if (CFG_VAR_TEST(group_inst, var) + if(CFG_VAR_TEST(group_inst, var) && ((CFG_VAR_TYPE(var) == CFG_VAR_STRING) - || (CFG_VAR_TYPE(var) == CFG_VAR_STR)) - && (*(char **)(group_inst->vars + var->offset) != NULL) - ) { + || (CFG_VAR_TYPE(var) == CFG_VAR_STR)) + && (*(char **)(group_inst->vars + var->offset) + != NULL)) { replaced[num] = *(char **)(group_inst->vars + var->offset); num++; } @@ -1769,15 +1712,14 @@ int cfg_del_group_inst(cfg_ctx_t *ctx, str *group_name, unsigned int group_id) } replaced[num] = CFG_GROUP_META(*cfg_global, group)->array; - replaced[num+1] = NULL; + replaced[num + 1] = NULL; } /* replace the global config with the new one */ cfg_install_global(block, replaced, NULL, NULL); CFG_WRITER_UNLOCK(); - LM_INFO("group instance is deleted: %.*s[%u]\n", - group_name->len, group_name->s, - group_id); + LM_INFO("group instance is deleted: %.*s[%u]\n", group_name->len, + group_name->s, group_id); /* Make sure that cfg_set_*() sees the change when * the function is immediately called after the group @@ -1787,13 +1729,15 @@ int cfg_del_group_inst(cfg_ctx_t *ctx, str *group_name, unsigned int group_id) return 0; error: CFG_WRITER_UNLOCK(); - if (block) cfg_block_free(block); - if (new_array) shm_free(new_array); - if (replaced) shm_free(replaced); + if(block) + cfg_block_free(block); + if(new_array) + shm_free(new_array); + if(replaced) + shm_free(replaced); - LM_ERR("Failed to delete the group instance: %.*s[%u]\n", - group_name->len, group_name->s, - group_id); + LM_ERR("Failed to delete the group instance: %.*s[%u]\n", group_name->len, + group_name->s, group_id); return -1; } @@ -1803,34 +1747,32 @@ int cfg_del_group_inst(cfg_ctx_t *ctx, str *group_name, unsigned int group_id) * 1: exists * 0: does not exist */ -int cfg_group_inst_exists(cfg_ctx_t *ctx, str *group_name, unsigned int group_id) +int cfg_group_inst_exists( + cfg_ctx_t *ctx, str *group_name, unsigned int group_id) { - cfg_group_t *group; - cfg_add_var_t *add_var; - int found; + cfg_group_t *group; + cfg_add_var_t *add_var; + int found; /* verify the context even if we do not need it now * to make sure that a cfg driver has called the function * (very very weak security) */ - if (!ctx) { + if(!ctx) { LM_ERR("context is undefined\n"); return 0; } - if (!(group = cfg_lookup_group(group_name->s, group_name->len))) { + if(!(group = cfg_lookup_group(group_name->s, group_name->len))) { LM_ERR("group not found\n"); return 0; } - if (!cfg_shmized) { + if(!cfg_shmized) { /* group instances are stored in the additional variable list * before forking */ found = 0; - for (add_var = group->add_var; - add_var; - add_var = add_var->next - ) - if (add_var->group_id == group_id) { + for(add_var = group->add_var; add_var; add_var = add_var->next) + if(add_var->group_id == group_id) { found = 1; break; } @@ -1838,10 +1780,9 @@ int cfg_group_inst_exists(cfg_ctx_t *ctx, str *group_name, unsigned int group_id } else { /* make sure that nobody else replaces the global config meantime */ CFG_WRITER_LOCK(); - found = (cfg_find_group(CFG_GROUP_META(*cfg_global, group), - group->size, - group_id) - != NULL); + found = (cfg_find_group(CFG_GROUP_META(*cfg_global, group), group->size, + group_id) + != NULL); CFG_WRITER_UNLOCK(); } @@ -1857,33 +1798,32 @@ int cfg_group_inst_exists(cfg_ctx_t *ctx, str *group_name, unsigned int group_id int cfg_apply_list(cfg_group_inst_t *ginst, cfg_group_t *group, unsigned int group_id, cfg_add_var_t **add_var_p) { - cfg_add_var_t *add_var; - cfg_mapping_t *var; - void *val, *v, *p; - str group_name, var_name, s; - char *old_string; + cfg_add_var_t *add_var; + cfg_mapping_t *var; + void *val, *v, *p; + str group_name, var_name, s; + char *old_string; group_name.s = group->name; group_name.len = group->name_len; - while (*add_var_p && ((*add_var_p)->group_id == group_id)) { + while(*add_var_p && ((*add_var_p)->group_id == group_id)) { add_var = *add_var_p; - if (add_var->type == 0) + if(add_var->type == 0) goto done; /* Nothing needs to be changed, * this additional variable only forces a new * group instance to be created. */ var_name.s = add_var->name; var_name.len = add_var->name_len; - if (!(var = cfg_lookup_var2(group, add_var->name, add_var->name_len))) { - LM_ERR("Variable is not found: %.*s.%.*s\n", - group->name_len, group->name, - add_var->name_len, add_var->name); + if(!(var = cfg_lookup_var2(group, add_var->name, add_var->name_len))) { + LM_ERR("Variable is not found: %.*s.%.*s\n", group->name_len, + group->name, add_var->name_len, add_var->name); goto error; } /* check whether the variable is read-only */ - if (var->def->type & CFG_READONLY) { + if(var->def->type & CFG_READONLY) { LM_ERR("variable is read-only\n"); goto error; } @@ -1893,9 +1833,7 @@ int cfg_apply_list(cfg_group_inst_t *ginst, cfg_group_t *group, * The reason is that such variables typically set global parameters * as opposed to per-process variables. Hence, it is not possible to set * the group handle temporary to another block, and then reset it back later. */ - if (var->def->on_set_child_cb - && var->def->type & CFG_CB_ONLY_ONCE - ) { + if(var->def->on_set_child_cb && var->def->type & CFG_CB_ONLY_ONCE) { LM_ERR("This variable does not support multiple values.\n"); goto error; } @@ -1911,31 +1849,28 @@ int cfg_apply_list(cfg_group_inst_t *ginst, cfg_group_t *group, val = (char *)add_var->val.ch; break; default: - LM_ERR("unsupported variable type: %d\n", - add_var->type); + LM_ERR("unsupported variable type: %d\n", add_var->type); goto error; } /* check whether we have to convert the type */ - if (convert_val(add_var->type, val, CFG_INPUT_TYPE(var), &v)) + if(convert_val(add_var->type, val, CFG_INPUT_TYPE(var), &v)) goto error; - if ((CFG_INPUT_TYPE(var) == CFG_INPUT_INT) + if((CFG_INPUT_TYPE(var) == CFG_INPUT_INT) && (var->def->min || var->def->max)) { /* perform a simple min-max check for integers */ - if (((int)(long)v < var->def->min) + if(((int)(long)v < var->def->min) || ((int)(long)v > var->def->max)) { LM_ERR("integer value is out of range\n"); goto error; } } - if (var->def->on_change_cb) { + if(var->def->on_change_cb) { /* Call the fixup function. * The handle can point to the variables of the group instance. */ - if (var->def->on_change_cb(ginst->vars, - &group_name, - &var_name, - &v) < 0) { + if(var->def->on_change_cb(ginst->vars, &group_name, &var_name, &v) + < 0) { LM_ERR("fixup failed\n"); goto error; } @@ -1944,7 +1879,7 @@ int cfg_apply_list(cfg_group_inst_t *ginst, cfg_group_t *group, p = ginst->vars + var->offset; old_string = NULL; /* set the new value */ - switch (CFG_VAR_TYPE(var)) { + switch(CFG_VAR_TYPE(var)) { case CFG_VAR_INT: *(int *)p = (int)(long)v; break; @@ -1953,7 +1888,8 @@ int cfg_apply_list(cfg_group_inst_t *ginst, cfg_group_t *group, /* clone the string to shm mem */ s.s = v; s.len = (s.s) ? strlen(s.s) : 0; - if (cfg_clone_str(&s, &s)) goto error; + if(cfg_clone_str(&s, &s)) + goto error; old_string = *(char **)p; *(char **)p = s.s; break; @@ -1961,7 +1897,8 @@ int cfg_apply_list(cfg_group_inst_t *ginst, cfg_group_t *group, case CFG_VAR_STR: /* clone the string to shm mem */ s = *(str *)v; - if (cfg_clone_str(&s, &s)) goto error; + if(cfg_clone_str(&s, &s)) + goto error; old_string = *(char **)p; memcpy(p, &s, sizeof(str)); break; @@ -1969,53 +1906,44 @@ int cfg_apply_list(cfg_group_inst_t *ginst, cfg_group_t *group, case CFG_VAR_POINTER: *(void **)p = v; break; - } - if (CFG_VAR_TEST_AND_SET(ginst, var) && old_string) + if(CFG_VAR_TEST_AND_SET(ginst, var) && old_string) shm_free(old_string); /* the string was already in shm memory, * it needs to be freed. * This can happen when the same variable is set * multiple times before forking. */ - if (add_var->type == CFG_VAR_INT) - LM_INFO("%.*s[%u].%.*s has been set to %d\n", - group_name.len, group_name.s, - group_id, - var_name.len, var_name.s, + if(add_var->type == CFG_VAR_INT) + LM_INFO("%.*s[%u].%.*s has been set to %d\n", group_name.len, + group_name.s, group_id, var_name.len, var_name.s, (int)(long)val); - else if (add_var->type == CFG_VAR_STRING) - LM_INFO("%.*s[%u].%.*s has been set to \"%s\"\n", - group_name.len, group_name.s, - group_id, - var_name.len, var_name.s, + else if(add_var->type == CFG_VAR_STRING) + LM_INFO("%.*s[%u].%.*s has been set to \"%s\"\n", group_name.len, + group_name.s, group_id, var_name.len, var_name.s, (char *)val); else /* str type */ - LM_INFO("%.*s[%u].%.*s has been set to \"%.*s\"\n", - group_name.len, group_name.s, - group_id, - var_name.len, var_name.s, + LM_INFO("%.*s[%u].%.*s has been set to \"%.*s\"\n", group_name.len, + group_name.s, group_id, var_name.len, var_name.s, ((str *)val)->len, ((str *)val)->s); convert_val_cleanup(); -done: + done: *add_var_p = add_var->next; - if ((add_var->type == CFG_VAR_STR) && add_var->val.s.s) + if((add_var->type == CFG_VAR_STR) && add_var->val.s.s) pkg_free(add_var->val.s.s); - else if ((add_var->type == CFG_VAR_STRING) && add_var->val.ch) + else if((add_var->type == CFG_VAR_STRING) && add_var->val.ch) pkg_free(add_var->val.ch); pkg_free(add_var); } return 0; error: - LM_ERR("Failed to set the value for: %.*s[%u].%.*s\n", - group->name_len, group->name, - group_id, - add_var->name_len, add_var->name); + LM_ERR("Failed to set the value for: %.*s[%u].%.*s\n", group->name_len, + group->name, group_id, add_var->name_len, add_var->name); convert_val_cleanup(); return -1; } diff --git a/src/core/cfg/cfg_ctx.h b/src/core/cfg/cfg_ctx.h index 0c270e65878..1bf93038583 100644 --- a/src/core/cfg/cfg_ctx.h +++ b/src/core/cfg/cfg_ctx.h @@ -29,24 +29,26 @@ /* variable values */ -union cfg_var_value{ - void* vp; +union cfg_var_value +{ + void *vp; long vlong; int vint; str vstr; - unsigned char vraw[1]; /* variable length */ + unsigned char vraw[1]; /* variable length */ }; /** linked list of variables with their new values. */ -typedef struct _cfg_changed_var { - cfg_group_t *group; - cfg_mapping_t *var; - struct _cfg_changed_var *next; +typedef struct _cfg_changed_var +{ + cfg_group_t *group; + cfg_mapping_t *var; + struct _cfg_changed_var *next; - unsigned int group_id; /* valid only if group_id_set==1 */ - unsigned char group_id_set; - unsigned char del_value; /* delete the value instead of setting it */ + unsigned int group_id; /* valid only if group_id_set==1 */ + unsigned char group_id_set; + unsigned char del_value; /* delete the value instead of setting it */ /* blob that contains the new value */ union cfg_var_value new_val; /* variable size */ @@ -56,23 +58,24 @@ typedef struct _cfg_changed_var { typedef void (*cfg_on_declare)(str *, cfg_def_t *); /*! \brief linked list of registered contexts */ -typedef struct _cfg_ctx { +typedef struct _cfg_ctx +{ /* variables that are already changed but have not been committed yet */ - cfg_changed_var_t *changed_first; + cfg_changed_var_t *changed_first; /* lock protecting the linked-list of changed variables */ - gen_lock_t lock; + gen_lock_t lock; /* callback that is called when a new group is registered */ - cfg_on_declare on_declare_cb; + cfg_on_declare on_declare_cb; - struct _cfg_ctx *next; + struct _cfg_ctx *next; } cfg_ctx_t; -#define CFG_CTX_LOCK(ctx) lock_get(&(ctx)->lock) -#define CFG_CTX_UNLOCK(ctx) lock_release(&(ctx)->lock) +#define CFG_CTX_LOCK(ctx) lock_get(&(ctx)->lock) +#define CFG_CTX_UNLOCK(ctx) lock_release(&(ctx)->lock) /*! \brief creates a new config context that is an interface to the * cfg variables with write permission */ @@ -82,32 +85,34 @@ int cfg_register_ctx(cfg_ctx_t **handle, cfg_on_declare on_declare_cb); void cfg_ctx_destroy(void); /*! \brief set the value of a variable without the need of explicit commit */ -int cfg_set_now(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *var_name, - void *val, unsigned int val_type); -int cfg_set_now_int(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *var_name, - int val); -int cfg_set_now_string(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *var_name, - char *val); -int cfg_set_now_str(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *var_name, - str *val); +int cfg_set_now(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, + str *var_name, void *val, unsigned int val_type); +int cfg_set_now_int(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, + str *var_name, int val); +int cfg_set_now_string(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, + str *var_name, char *val); +int cfg_set_now_str(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, + str *var_name, str *val); /*! \brief Delete a variable from the group instance. * wrapper function for cfg_set_now */ -int cfg_del_now(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *var_name); +int cfg_del_now( + cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *var_name); /* sets the value of a variable but does not commit the change */ -int cfg_set_delayed(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *var_name, - void *val, unsigned int val_type); -int cfg_set_delayed_int(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *var_name, - int val); -int cfg_set_delayed_string(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *var_name, - char *val); -int cfg_set_delayed_str(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *var_name, - str *val); +int cfg_set_delayed(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, + str *var_name, void *val, unsigned int val_type); +int cfg_set_delayed_int(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, + str *var_name, int val); +int cfg_set_delayed_string(cfg_ctx_t *ctx, str *group_name, + unsigned int *group_id, str *var_name, char *val); +int cfg_set_delayed_str(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, + str *var_name, str *val); /*! \brief Delete a variable from the group instance. * wrapper function for cfg_set_delayed */ -int cfg_del_delayed(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *var_name); +int cfg_del_delayed( + cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *var_name); /*! \brief commits the previously prepared changes within the context */ int cfg_commit(cfg_ctx_t *ctx); @@ -116,30 +121,30 @@ int cfg_commit(cfg_ctx_t *ctx); int cfg_rollback(cfg_ctx_t *ctx); /*! \brief returns the value of a variable */ -int cfg_get_by_name(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *var_name, - void **val, unsigned int *val_type); +int cfg_get_by_name(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, + str *var_name, void **val, unsigned int *val_type); -int cfg_get_default_value_by_name(cfg_ctx_t *ctx, str *group_name, unsigned int *group_id, str *var_name, - void **val, unsigned int *val_type); +int cfg_get_default_value_by_name(cfg_ctx_t *ctx, str *group_name, + unsigned int *group_id, str *var_name, void **val, + unsigned int *val_type); /*! \brief returns the description of a variable */ -int cfg_help(cfg_ctx_t *ctx, str *group_name, str *var_name, - char **ch, unsigned int *input_type); +int cfg_help(cfg_ctx_t *ctx, str *group_name, str *var_name, char **ch, + unsigned int *input_type); /*! \brief notify the drivers about the new config definition */ void cfg_notify_drivers(char *group_name, int group_name_len, cfg_def_t *def); /*! \brief convert the value to the requested type. * Do not forget the call convert_val_cleaup afterwards. */ -int convert_val(unsigned int val_type, void *val, - unsigned int var_type, void **new_val); +int convert_val(unsigned int val_type, void *val, unsigned int var_type, + void **new_val); /*! \brief cleanup function for convert_val() */ void convert_val_cleanup(void); /*! \brief initialize the handle for cfg_get_group_next() */ -#define cfg_get_group_init(handle) \ - (*(handle)) = (void *)cfg_group +#define cfg_get_group_init(handle) (*(handle)) = (void *)cfg_group /*! \brief returns the group name and the cfg structure definition, * and moves the handle to the next group @@ -156,15 +161,13 @@ void convert_val_cleanup(void); * ... * } */ -int cfg_get_group_next(void **h, - str *gname, cfg_def_t **def); +int cfg_get_group_next(void **h, str *gname, cfg_def_t **def); /*! \brief Initialize the handle for cfg_diff_next() * WARNING: keeps the context lock held, do not forget * to release it with cfg_diff_release() */ -int cfg_diff_init(cfg_ctx_t *ctx, - void **h); +int cfg_diff_init(cfg_ctx_t *ctx, void **h); /*! \brief return the pending changes that have not been * committed yet @@ -191,10 +194,8 @@ int cfg_diff_init(cfg_ctx_t *ctx, * ... * } */ -int cfg_diff_next(void **h, - str *gname, unsigned int **gid, str *vname, - void **old_val, void **new_val, - unsigned int *val_type); +int cfg_diff_next(void **h, str *gname, unsigned int **gid, str *vname, + void **old_val, void **new_val, unsigned int *val_type); /*! \brief destroy the handle of cfg_diff_next() */ void cfg_diff_release(cfg_ctx_t *ctx); @@ -210,13 +211,14 @@ int cfg_del_group_inst(cfg_ctx_t *ctx, str *group_name, unsigned int group_id); * 1: exists * 0: does not exist */ -int cfg_group_inst_exists(cfg_ctx_t *ctx, str *group_name, unsigned int group_id); +int cfg_group_inst_exists( + cfg_ctx_t *ctx, str *group_name, unsigned int group_id); /* Apply the changes to a group instance as long as the additional variable * belongs to the specified group_id. *add_var_p is moved to the next additional * variable, and all the consumed variables are freed. */ int cfg_apply_list(cfg_group_inst_t *ginst, cfg_group_t *group, - unsigned int group_id, cfg_add_var_t **add_var_p); + unsigned int group_id, cfg_add_var_t **add_var_p); #endif /* _CFG_CTX_H */ diff --git a/src/core/cfg/cfg_script.c b/src/core/cfg/cfg_script.c index 80257a4d6a1..ebd3f33a7a1 100644 --- a/src/core/cfg/cfg_script.c +++ b/src/core/cfg/cfg_script.c @@ -31,18 +31,18 @@ /* allocates memory for a new config script variable * The value of the variable is not set! */ -cfg_script_var_t *new_cfg_script_var(char *gname, char *vname, unsigned int type, - char *descr) +cfg_script_var_t *new_cfg_script_var( + char *gname, char *vname, unsigned int type, char *descr) { - cfg_group_t *group; - cfg_script_var_t *var, **last_var; - int gname_len, vname_len, descr_len; + cfg_group_t *group; + cfg_script_var_t *var, **last_var; + int gname_len, vname_len, descr_len; LM_DBG("declaring %s.%s\n", gname, vname); - if (cfg_shmized) { + if(cfg_shmized) { LM_ERR("too late variable declaration, " - "the config has been already shmized\n"); + "the config has been already shmized\n"); return NULL; } @@ -50,65 +50,63 @@ cfg_script_var_t *new_cfg_script_var(char *gname, char *vname, unsigned int type vname_len = strlen(vname); /* the group may have been already declared */ group = cfg_lookup_group(gname, gname_len); - if (group) { - if (group->dynamic == CFG_GROUP_STATIC) { + if(group) { + if(group->dynamic == CFG_GROUP_STATIC) { /* the group has been already declared by a module or by the core */ LM_ERR("configuration group has been already declared: %s\n", - gname); + gname); return NULL; } /* the dynamic or empty group is found */ /* verify that the variable does not exist */ - for ( var = (cfg_script_var_t *)group->vars; - var; - var = var->next - ) { - if ((var->name_len == vname_len) && - (memcmp(var->name, vname, vname_len) == 0)) { + for(var = (cfg_script_var_t *)group->vars; var; var = var->next) { + if((var->name_len == vname_len) + && (memcmp(var->name, vname, vname_len) == 0)) { LM_ERR("variable already exists: %s.%s\n", gname, vname); return NULL; } } - if (group->dynamic == CFG_GROUP_UNKNOWN) + if(group->dynamic == CFG_GROUP_UNKNOWN) group->dynamic = CFG_GROUP_DYNAMIC; } else { /* create a new group with NULL values, we will fix it later, when all the variables are known */ - group = cfg_new_group(gname, gname_len, - 0 /* num */, NULL /* mapping */, - NULL /* vars */, 0 /* size */, NULL /* handle */); - if (!group) goto error; + group = cfg_new_group(gname, gname_len, 0 /* num */, NULL /* mapping */, + NULL /* vars */, 0 /* size */, NULL /* handle */); + if(!group) + goto error; group->dynamic = CFG_GROUP_DYNAMIC; } - switch (type) { - case CFG_VAR_INT: - group->size = ROUND_INT(group->size); - group->size += sizeof(int); - break; + switch(type) { + case CFG_VAR_INT: + group->size = ROUND_INT(group->size); + group->size += sizeof(int); + break; - case CFG_VAR_STR: - group->size = ROUND_POINTER(group->size); - group->size += sizeof(str); - break; + case CFG_VAR_STR: + group->size = ROUND_POINTER(group->size); + group->size += sizeof(str); + break; - default: - LM_ERR("unsupported variable type\n"); - return NULL; + default: + LM_ERR("unsupported variable type\n"); + return NULL; } group->num++; - if (group->num > CFG_MAX_VAR_NUM) { + if(group->num > CFG_MAX_VAR_NUM) { LM_ERR("too many variables (%d) within a single group," - " the limit is %d. Increase CFG_MAX_VAR_NUM, or split the group" - " into multiple definitions.\n", - group->num, CFG_MAX_VAR_NUM); + " the limit is %d. Increase CFG_MAX_VAR_NUM, or split the group" + " into multiple definitions.\n", + group->num, CFG_MAX_VAR_NUM); return NULL; } var = (cfg_script_var_t *)pkg_malloc(sizeof(cfg_script_var_t)); - if (!var) goto error; + if(!var) + goto error; memset(var, 0, sizeof(cfg_script_var_t)); var->type = type; @@ -117,22 +115,24 @@ cfg_script_var_t *new_cfg_script_var(char *gname, char *vname, unsigned int type * The list will be travelled later again, which must be done in * the same order. */ last_var = (cfg_script_var_t **)(void **)&group->vars; - while ((*last_var)) + while((*last_var)) last_var = &((*last_var)->next); *last_var = var; var->next = NULL; /* clone the name of the variable */ var->name = (char *)pkg_malloc(sizeof(char) * (vname_len + 1)); - if (!var->name) goto error; + if(!var->name) + goto error; memcpy(var->name, vname, vname_len + 1); var->name_len = vname_len; - if (descr) { + if(descr) { /* save the description */ descr_len = strlen(descr); var->descr = (char *)pkg_malloc(sizeof(char) * (descr_len + 1)); - if (!var->descr) goto error; + if(!var->descr) + goto error; memcpy(var->descr, descr, descr_len + 1); } @@ -149,62 +149,58 @@ cfg_script_var_t *new_cfg_script_var(char *gname, char *vname, unsigned int type * -1: error * 1: variable not found */ -int cfg_set_script_var(cfg_group_t *group, str *var_name, - void *val, unsigned int val_type) +int cfg_set_script_var( + cfg_group_t *group, str *var_name, void *val, unsigned int val_type) { - cfg_script_var_t *var; - void *v; - str s; + cfg_script_var_t *var; + void *v; + str s; - if (cfg_shmized || (group->dynamic != CFG_GROUP_DYNAMIC)) { + if(cfg_shmized || (group->dynamic != CFG_GROUP_DYNAMIC)) { LM_ERR("not a dynamic group before forking\n"); return -1; } - for ( var = (cfg_script_var_t *)(void *)group->vars; - var; - var = var->next - ) { - if ((var->name_len == var_name->len) - && (memcmp(var->name, var_name->s, var_name->len) == 0) - ) { - switch (var->type) { - case CFG_VAR_INT: - if (convert_val(val_type, val, CFG_INPUT_INT, &v)) - goto error; - if ((var->min || var->max) - && ((var->min > (int)(long)v) || (var->max < (int)(long)v)) - ) { - LM_ERR("integer value is out of range\n"); - goto error; - } - var->val.i = (int)(long)v; - break; + for(var = (cfg_script_var_t *)(void *)group->vars; var; var = var->next) { + if((var->name_len == var_name->len) + && (memcmp(var->name, var_name->s, var_name->len) == 0)) { + switch(var->type) { + case CFG_VAR_INT: + if(convert_val(val_type, val, CFG_INPUT_INT, &v)) + goto error; + if((var->min || var->max) + && ((var->min > (int)(long)v) + || (var->max < (int)(long)v))) { + LM_ERR("integer value is out of range\n"); + goto error; + } + var->val.i = (int)(long)v; + break; - case CFG_VAR_STR: - if (convert_val(val_type, val, CFG_INPUT_STR, &v)) - goto error; - if (((str *)v)->s) { - s.len = ((str *)v)->len; - s.s = pkg_malloc(sizeof(char) * (s.len + 1)); - if (!s.s) { - PKG_MEM_ERROR; + case CFG_VAR_STR: + if(convert_val(val_type, val, CFG_INPUT_STR, &v)) goto error; + if(((str *)v)->s) { + s.len = ((str *)v)->len; + s.s = pkg_malloc(sizeof(char) * (s.len + 1)); + if(!s.s) { + PKG_MEM_ERROR; + goto error; + } + memcpy(s.s, ((str *)v)->s, s.len); + s.s[s.len] = '\0'; + } else { + s.s = NULL; + s.len = 0; } - memcpy(s.s, ((str *)v)->s, s.len); - s.s[s.len] = '\0'; - } else { - s.s = NULL; - s.len = 0; - } - if (var->val.s.s) - pkg_free(var->val.s.s); - var->val.s = s; - break; + if(var->val.s.s) + pkg_free(var->val.s.s); + var->val.s = s; + break; - default: - LM_ERR("unsupported variable type\n"); - goto error; + default: + LM_ERR("unsupported variable type\n"); + goto error; } convert_val_cleanup(); @@ -215,9 +211,8 @@ int cfg_set_script_var(cfg_group_t *group, str *var_name, return 1; error: - LM_ERR("failed to set the script variable: %.*s.%.*s\n", - group->name_len, group->name, - var_name->len, var_name->s); + LM_ERR("failed to set the script variable: %.*s.%.*s\n", group->name_len, + group->name, var_name->len, var_name->s); return -1; } @@ -227,33 +222,33 @@ int cfg_set_script_var(cfg_group_t *group, str *var_name, */ int cfg_script_fixup(cfg_group_t *group, unsigned char *block) { - cfg_mapping_t *mapping = NULL; - cfg_def_t *def = NULL; - void **handle = NULL; - int i, offset; - cfg_script_var_t *script_var, *script_var2; - str s; - - if(group==NULL || group->vars==NULL) { + cfg_mapping_t *mapping = NULL; + cfg_def_t *def = NULL; + void **handle = NULL; + int i, offset; + cfg_script_var_t *script_var, *script_var2; + str s; + + if(group == NULL || group->vars == NULL) { LM_ERR("invalid group parameter: %p\n", group); return -1; } - mapping = (cfg_mapping_t *)pkg_malloc(sizeof(cfg_mapping_t)*group->num); - if (!mapping) goto error; - memset(mapping, 0, sizeof(cfg_mapping_t)*group->num); + mapping = (cfg_mapping_t *)pkg_malloc(sizeof(cfg_mapping_t) * group->num); + if(!mapping) + goto error; + memset(mapping, 0, sizeof(cfg_mapping_t) * group->num); /* The variable definition array must look like as if it was declared * in C code, thus, add an additional slot at the end with NULL values */ - def = (cfg_def_t *)pkg_malloc(sizeof(cfg_def_t)*(group->num + 1)); - if (!def) goto error; - memset(def, 0, sizeof(cfg_def_t)*(group->num + 1)); + def = (cfg_def_t *)pkg_malloc(sizeof(cfg_def_t) * (group->num + 1)); + if(!def) + goto error; + memset(def, 0, sizeof(cfg_def_t) * (group->num + 1)); /* fill the definition and the mapping arrays */ offset = 0; - for ( i = 0, script_var = (cfg_script_var_t *)group->vars; - script_var; - i++, script_var = script_var->next - ) { + for(i = 0, script_var = (cfg_script_var_t *)group->vars; script_var; + i++, script_var = script_var->next) { /* there has been already memory allocated for the name */ def[i].name = script_var->name; def[i].type = script_var->type | (script_var->type << CFG_INPUT_SHIFT); @@ -265,34 +260,37 @@ int cfg_script_fixup(cfg_group_t *group, unsigned char *block) mapping[i].name_len = script_var->name_len; mapping[i].pos = i; - switch (script_var->type) { - case CFG_VAR_INT: - offset = ROUND_INT(offset); - mapping[i].offset = offset; + switch(script_var->type) { + case CFG_VAR_INT: + offset = ROUND_INT(offset); + mapping[i].offset = offset; - *(int *)(block + offset) = script_var->val.i; + *(int *)(block + offset) = script_var->val.i; - offset += sizeof(int); - break; + offset += sizeof(int); + break; - case CFG_VAR_STR: - offset = ROUND_POINTER(offset); - mapping[i].offset = offset; + case CFG_VAR_STR: + offset = ROUND_POINTER(offset); + mapping[i].offset = offset; - if (cfg_clone_str(&(script_var->val.s), &s)) goto error; - memcpy(block + offset, &s, sizeof(str)); - mapping[i].flag |= cfg_var_shmized; + if(cfg_clone_str(&(script_var->val.s), &s)) + goto error; + memcpy(block + offset, &s, sizeof(str)); + mapping[i].flag |= cfg_var_shmized; - offset += sizeof(str); - break; + offset += sizeof(str); + break; } } /* Sanity check for the group size, make sure that the * newly calculated size equals the already calculated * group size. */ - if (offset != group->size) { - LM_ERR("BUG: incorrect group size: %d; previously calculated value: %d \n", offset, group->size); + if(offset != group->size) { + LM_ERR("BUG: incorrect group size: %d; previously calculated value: %d " + "\n", + offset, group->size); goto error; } @@ -301,7 +299,8 @@ int cfg_script_fixup(cfg_group_t *group, unsigned char *block) cfg_get_* functions access the memory block via the handle to make sure that it is always safe, thus, it must be created */ handle = (void **)pkg_malloc(sizeof(void *)); - if (!handle) goto error; + if(!handle) + goto error; *handle = NULL; group->handle = handle; @@ -310,9 +309,9 @@ int cfg_script_fixup(cfg_group_t *group, unsigned char *block) /* everything went fine, we can free the temporary list */ script_var = (cfg_script_var_t *)group->vars; group->vars = NULL; - while (script_var) { + while(script_var) { script_var2 = script_var->next; - if ((script_var->type == CFG_VAR_STR) && script_var->val.s.s) + if((script_var->type == CFG_VAR_STR) && script_var->val.s.s) pkg_free(script_var->val.s.s); pkg_free(script_var); script_var = script_var2; @@ -321,9 +320,12 @@ int cfg_script_fixup(cfg_group_t *group, unsigned char *block) return 0; error: - if (mapping) pkg_free(mapping); - if (def) pkg_free(def); - if (handle) pkg_free(handle); + if(mapping) + pkg_free(mapping); + if(def) + pkg_free(def); + if(handle) + pkg_free(handle); PKG_MEM_ERROR; return -1; @@ -332,27 +334,29 @@ int cfg_script_fixup(cfg_group_t *group, unsigned char *block) /* destory a dynamically allocated group definition */ void cfg_script_destroy(cfg_group_t *group) { - int i; - cfg_script_var_t *script_var, *script_var2; + int i; + cfg_script_var_t *script_var, *script_var2; - if (group->mapping && group->mapping->def) { - for (i=0; inum; i++) { - if (group->mapping->def[i].name) + if(group->mapping && group->mapping->def) { + for(i = 0; i < group->num; i++) { + if(group->mapping->def[i].name) pkg_free(group->mapping->def[i].name); - if (group->mapping->def[i].descr) + if(group->mapping->def[i].descr) pkg_free(group->mapping->def[i].descr); } pkg_free(group->mapping->def); } - if (group->mapping) pkg_free(group->mapping); - if (group->handle) pkg_free(group->handle); + if(group->mapping) + pkg_free(group->mapping); + if(group->handle) + pkg_free(group->handle); /* it may happen that the temporary var list still exists because the fixup failed and did not complete */ script_var = (cfg_script_var_t *)group->vars; - while (script_var) { + while(script_var) { script_var2 = script_var->next; - if ((script_var->type == CFG_VAR_STR) && script_var->val.s.s) + if((script_var->type == CFG_VAR_STR) && script_var->val.s.s) pkg_free(script_var->val.s.s); pkg_free(script_var); script_var = script_var2; diff --git a/src/core/cfg/cfg_script.h b/src/core/cfg/cfg_script.h index 7a4ac018211..e242538e652 100644 --- a/src/core/cfg/cfg_script.h +++ b/src/core/cfg/cfg_script.h @@ -27,25 +27,27 @@ /* structure used for temporary storing the variables * which are declared in the script */ -typedef struct _cfg_script_var { - unsigned int type; - union { - str s; - int i; +typedef struct _cfg_script_var +{ + unsigned int type; + union + { + str s; + int i; } val; - int min; - int max; - struct _cfg_script_var *next; - int name_len; - char *name; - char *descr; + int min; + int max; + struct _cfg_script_var *next; + int name_len; + char *name; + char *descr; } cfg_script_var_t; /* allocates memory for a new config script variable * The value of the variable is not set! */ -cfg_script_var_t *new_cfg_script_var(char *gname, char *vname, unsigned int type, - char *descr); +cfg_script_var_t *new_cfg_script_var( + char *gname, char *vname, unsigned int type, char *descr); /* Rewrite the value of an already declared script variable before forking. * Return value: @@ -53,8 +55,8 @@ cfg_script_var_t *new_cfg_script_var(char *gname, char *vname, unsigned int type * -1: error * 1: variable not found */ -int cfg_set_script_var(cfg_group_t *group, str *var_name, - void *val, unsigned int val_type); +int cfg_set_script_var( + cfg_group_t *group, str *var_name, void *val, unsigned int val_type); /* fix-up the dynamically declared group */ int cfg_script_fixup(cfg_group_t *group, unsigned char *block); diff --git a/src/core/cfg/cfg_select.c b/src/core/cfg/cfg_select.c index 30b99cf4e3c..f948dd4ab4c 100644 --- a/src/core/cfg/cfg_select.c +++ b/src/core/cfg/cfg_select.c @@ -31,35 +31,39 @@ * allocated for the dynamic groups yet. So we have to keep track of all the * selects that we failed to fix-up, and retry the fixup once more just * before forking */ -typedef struct _cfg_selects { - str gname; - str vname; - void **group_p; - void **var_p; - struct _cfg_selects *next; +typedef struct _cfg_selects +{ + str gname; + str vname; + void **group_p; + void **var_p; + struct _cfg_selects *next; } cfg_selects_t; /* linked list of non-fixed selects */ -static cfg_selects_t *cfg_non_fixed_selects = NULL; +static cfg_selects_t *cfg_non_fixed_selects = NULL; /* add a new select item to the linked list */ static int cfg_new_select(str *gname, str *vname, void **group_p, void **var_p) { - cfg_selects_t *sel; + cfg_selects_t *sel; sel = (cfg_selects_t *)pkg_malloc(sizeof(cfg_selects_t)); - if (!sel) goto error; + if(!sel) + goto error; memset(sel, 0, sizeof(cfg_selects_t)); - sel->gname.s = (char *)pkg_malloc(sizeof(char)*gname->len); - if (!sel->gname.s) goto error; + sel->gname.s = (char *)pkg_malloc(sizeof(char) * gname->len); + if(!sel->gname.s) + goto error; memcpy(sel->gname.s, gname->s, gname->len); sel->gname.len = gname->len; sel->group_p = group_p; - if (vname) { - sel->vname.s = (char *)pkg_malloc(sizeof(char)*vname->len); - if (!sel->vname.s) goto error; + if(vname) { + sel->vname.s = (char *)pkg_malloc(sizeof(char) * vname->len); + if(!sel->vname.s) + goto error; memcpy(sel->vname.s, vname->s, vname->len); sel->vname.len = vname->len; @@ -74,9 +78,11 @@ static int cfg_new_select(str *gname, str *vname, void **group_p, void **var_p) error: PKG_MEM_ERROR; - if (sel) { - if (sel->gname.s) pkg_free(sel->gname.s); - if (sel->vname.s) pkg_free(sel->vname.s); + if(sel) { + if(sel->gname.s) + pkg_free(sel->gname.s); + if(sel->vname.s) + pkg_free(sel->vname.s); pkg_free(sel); } return -1; @@ -85,14 +91,16 @@ static int cfg_new_select(str *gname, str *vname, void **group_p, void **var_p) /* free the list of not yet fixed selects */ void cfg_free_selects() { - cfg_selects_t *sel, *next_sel; + cfg_selects_t *sel, *next_sel; sel = cfg_non_fixed_selects; - while (sel) { + while(sel) { next_sel = sel->next; - if (sel->gname.s) pkg_free(sel->gname.s); - if (sel->vname.s) pkg_free(sel->vname.s); + if(sel->gname.s) + pkg_free(sel->gname.s); + if(sel->vname.s) + pkg_free(sel->vname.s); pkg_free(sel); sel = next_sel; @@ -103,25 +111,24 @@ void cfg_free_selects() /* fix-up the select calls */ int cfg_fixup_selects() { - cfg_selects_t *sel; - cfg_group_t *group; - cfg_mapping_t *var; + cfg_selects_t *sel; + cfg_group_t *group; + cfg_mapping_t *var; - for (sel=cfg_non_fixed_selects; sel; sel=sel->next) { + for(sel = cfg_non_fixed_selects; sel; sel = sel->next) { - if (sel->var_p) { - if (cfg_lookup_var(&sel->gname, &sel->vname, &group, &var)) { - LM_ERR("unknown variable: %.*s.%.*s\n", - sel->gname.len, sel->gname.s, - sel->vname.len, sel->vname.s); + if(sel->var_p) { + if(cfg_lookup_var(&sel->gname, &sel->vname, &group, &var)) { + LM_ERR("unknown variable: %.*s.%.*s\n", sel->gname.len, + sel->gname.s, sel->vname.len, sel->vname.s); return -1; } *(sel->group_p) = (void *)group; *(sel->var_p) = (void *)var; } else { - if (!(group = cfg_lookup_group(sel->gname.s, sel->gname.len))) { - LM_ERR("unknown configuration group: %.*s\n", - sel->gname.len, sel->gname.s); + if(!(group = cfg_lookup_group(sel->gname.s, sel->gname.len))) { + LM_ERR("unknown configuration group: %.*s\n", sel->gname.len, + sel->gname.s); return -1; } *(sel->group_p) = (void *)group; @@ -134,39 +141,39 @@ int cfg_fixup_selects() int select_cfg_var(str *res, select_t *s, struct sip_msg *msg) { - cfg_group_t *group; - cfg_mapping_t *var; - void *p; - int i; - static char buf[INT2STR_MAX_LEN]; + cfg_group_t *group; + cfg_mapping_t *var; + void *p; + int i; + static char buf[INT2STR_MAX_LEN]; - if (msg == NULL) { + if(msg == NULL) { /* fixup call */ /* two parameters are mandatory, group name and variable name */ - if (s->n < 3) { + if(s->n < 3) { LM_ERR("At least two parameters are expected\n"); return -1; } - if ((s->params[1].type != SEL_PARAM_STR) + if((s->params[1].type != SEL_PARAM_STR) || (s->params[2].type != SEL_PARAM_STR)) { LM_ERR("string parameters are expected\n"); return -1; } /* look-up the group and the variable */ - if (cfg_lookup_var(&s->params[1].v.s, &s->params[2].v.s, &group, &var)) { - if (cfg_shmized) { - LM_ERR("unknown variable: %.*s.%.*s\n", - s->params[1].v.s.len, s->params[1].v.s.s, - s->params[2].v.s.len, s->params[2].v.s.s); + if(cfg_lookup_var(&s->params[1].v.s, &s->params[2].v.s, &group, &var)) { + if(cfg_shmized) { + LM_ERR("unknown variable: %.*s.%.*s\n", s->params[1].v.s.len, + s->params[1].v.s.s, s->params[2].v.s.len, + s->params[2].v.s.s); return -1; } /* The variable was not found, add it to the non-fixed select list. * So we act as if the fixup was successful, and we retry it later */ - if (cfg_new_select(&s->params[1].v.s, &s->params[2].v.s, - &s->params[1].v.p, &s->params[2].v.p)) + if(cfg_new_select(&s->params[1].v.s, &s->params[2].v.s, + &s->params[1].v.p, &s->params[2].v.p)) return -1; LM_DBG("select fixup is postponed: %.*s.%.*s\n", @@ -182,7 +189,7 @@ int select_cfg_var(str *res, select_t *s, struct sip_msg *msg) return 0; } - if (var->def->on_change_cb) { + if(var->def->on_change_cb) { /* fixup function is defined -- safer to return an error * than an incorrect value */ LM_ERR("variable cannot be retrieved\n"); @@ -200,16 +207,17 @@ int select_cfg_var(str *res, select_t *s, struct sip_msg *msg) group = (cfg_group_t *)s->params[1].v.p; var = (cfg_mapping_t *)s->params[2].v.p; - if (!group || !var) return -1; + if(!group || !var) + return -1; /* use the module's handle to access the variable, so the variables * are read from the local config */ p = *(group->handle) + var->offset; - switch (CFG_VAR_TYPE(var)) { + switch(CFG_VAR_TYPE(var)) { case CFG_VAR_INT: i = *(int *)p; - res->len = snprintf(buf, sizeof(buf)-1, "%d", i); + res->len = snprintf(buf, sizeof(buf) - 1, "%d", i); buf[res->len] = '\0'; res->s = buf; break; @@ -229,8 +237,7 @@ int select_cfg_var(str *res, select_t *s, struct sip_msg *msg) break; default: - LM_DBG("unsupported variable type: %d\n", - CFG_VAR_TYPE(var)); + LM_DBG("unsupported variable type: %d\n", CFG_VAR_TYPE(var)); return -1; } return 0; @@ -239,7 +246,7 @@ int select_cfg_var(str *res, select_t *s, struct sip_msg *msg) /* fake function to eat the first parameter of @cfg_get */ ABSTRACT_F(select_cfg_var1) - /* fix-up function for read_cfg_var() +/* fix-up function for read_cfg_var() * * return value: * >0 - success @@ -247,13 +254,14 @@ ABSTRACT_F(select_cfg_var1) * fixed-up later. * <0 - error */ -int read_cfg_var_fixup(char *gname, char *vname, struct cfg_read_handle *read_handle) +int read_cfg_var_fixup( + char *gname, char *vname, struct cfg_read_handle *read_handle) { - cfg_group_t *group; - cfg_mapping_t *var; - str group_name, var_name; + cfg_group_t *group; + cfg_mapping_t *var; + str group_name, var_name; - if (!gname || !vname || !read_handle) + if(!gname || !vname || !read_handle) return -1; group_name.s = gname; @@ -262,22 +270,20 @@ int read_cfg_var_fixup(char *gname, char *vname, struct cfg_read_handle *read_ha var_name.len = strlen(vname); /* look-up the group and the variable */ - if (cfg_lookup_var(&group_name, &var_name, &group, &var)) { - if (cfg_shmized) { - LM_ERR("unknown variable: %.*s.%.*s\n", - group_name.len, group_name.s, - var_name.len, var_name.s); + if(cfg_lookup_var(&group_name, &var_name, &group, &var)) { + if(cfg_shmized) { + LM_ERR("unknown variable: %.*s.%.*s\n", group_name.len, + group_name.s, var_name.len, var_name.s); return -1; } /* The variable was not found, add it to the non-fixed select list. * So we act as if the fixup was successful, and we retry it later */ - if (cfg_new_select(&group_name, &var_name, - &read_handle->group, &read_handle->var)) + if(cfg_new_select(&group_name, &var_name, &read_handle->group, + &read_handle->var)) return -1; - LM_DBG("cfg read fixup is postponed: %.*s.%.*s\n", - group_name.len, group_name.s, - var_name.len, var_name.s); + LM_DBG("cfg read fixup is postponed: %.*s.%.*s\n", group_name.len, + group_name.s, var_name.len, var_name.s); read_handle->group = NULL; read_handle->var = NULL; @@ -294,12 +300,12 @@ int read_cfg_var_fixup(char *gname, char *vname, struct cfg_read_handle *read_ha */ unsigned int read_cfg_var(struct cfg_read_handle *read_handle, void **val) { - cfg_group_t *group; - cfg_mapping_t *var; - void *p; - static str s; + cfg_group_t *group; + cfg_mapping_t *var; + void *p; + static str s; - if (!val || !read_handle || !read_handle->group || !read_handle->var) + if(!val || !read_handle || !read_handle->group || !read_handle->var) return 0; group = (cfg_group_t *)(read_handle->group); @@ -310,7 +316,7 @@ unsigned int read_cfg_var(struct cfg_read_handle *read_handle, void **val) * are read from the local config */ p = *(group->handle) + var->offset; - switch (CFG_VAR_TYPE(var)) { + switch(CFG_VAR_TYPE(var)) { case CFG_VAR_INT: *val = (void *)(long)*(int *)p; break; @@ -327,7 +333,6 @@ unsigned int read_cfg_var(struct cfg_read_handle *read_handle, void **val) case CFG_VAR_POINTER: *val = *(void **)p; break; - } return CFG_VAR_TYPE(var); } @@ -337,13 +342,13 @@ unsigned int read_cfg_var(struct cfg_read_handle *read_handle, void **val) */ int read_cfg_var_int(struct cfg_read_handle *read_handle, int *val) { - unsigned int type; - void *v1=NULL, *v2=NULL; + unsigned int type; + void *v1 = NULL, *v2 = NULL; - if ((type = read_cfg_var(read_handle, &v1)) == 0) + if((type = read_cfg_var(read_handle, &v1)) == 0) return -1; - if (convert_val(type, v1, CFG_INPUT_INT, &v2)) + if(convert_val(type, v1, CFG_INPUT_INT, &v2)) return -1; *val = (int)(long)(v2); @@ -355,13 +360,13 @@ int read_cfg_var_int(struct cfg_read_handle *read_handle, int *val) */ int read_cfg_var_str(struct cfg_read_handle *read_handle, str *val) { - unsigned int type; - void *v1=NULL, *v2=NULL; + unsigned int type; + void *v1 = NULL, *v2 = NULL; - if ((type = read_cfg_var(read_handle, &v1)) == 0) + if((type = read_cfg_var(read_handle, &v1)) == 0) return -1; - if (convert_val(type, v1, CFG_INPUT_STR, &v2)) + if(convert_val(type, v1, CFG_INPUT_STR, &v2)) return -1; *val = *(str *)(v2); @@ -371,38 +376,38 @@ int read_cfg_var_str(struct cfg_read_handle *read_handle, str *val) /* return the selected group instance */ int cfg_selected_inst(str *res, select_t *s, struct sip_msg *msg) { - cfg_group_t *group; - cfg_group_inst_t *inst; + cfg_group_t *group; + cfg_group_inst_t *inst; - if (msg == NULL) { + if(msg == NULL) { /* fixup call */ /* one parameter is mandatory: group name */ - if (s->n != 2) { + if(s->n != 2) { LM_ERR("One parameter is expected\n"); return -1; } - if (s->params[1].type != SEL_PARAM_STR) { + if(s->params[1].type != SEL_PARAM_STR) { LM_ERR("string parameter is expected\n"); return -1; } /* look-up the group and the variable */ - if (!(group = cfg_lookup_group(s->params[1].v.s.s, s->params[1].v.s.len))) { - if (cfg_shmized) { + if(!(group = cfg_lookup_group( + s->params[1].v.s.s, s->params[1].v.s.len))) { + if(cfg_shmized) { LM_ERR("unknown configuration group: %.*s\n", s->params[1].v.s.len, s->params[1].v.s.s); return -1; } /* The group was not found, add it to the non-fixed select list. * So we act as if the fixup was successful, and we retry it later */ - if (cfg_new_select(&s->params[1].v.s, NULL, - &s->params[1].v.p, NULL)) + if(cfg_new_select(&s->params[1].v.s, NULL, &s->params[1].v.p, NULL)) return -1; - LM_DBG("select fixup is postponed: %.*s\n", - s->params[1].v.s.len, s->params[1].v.s.s); + LM_DBG("select fixup is postponed: %.*s\n", s->params[1].v.s.len, + s->params[1].v.s.s); s->params[1].type = SEL_PARAM_PTR; s->params[1].v.p = NULL; @@ -417,12 +422,13 @@ int cfg_selected_inst(str *res, select_t *s, struct sip_msg *msg) } group = (cfg_group_t *)s->params[1].v.p; - if (!group) return -1; + if(!group) + return -1; /* Get the current group instance from the group handle. */ inst = CFG_HANDLE_TO_GINST(*(group->handle)); - if (inst) { + if(inst) { res->s = int2str(inst->id, &res->len); } else { res->s = ""; diff --git a/src/core/cfg/cfg_select.h b/src/core/cfg/cfg_select.h index 585bc666330..3f044ece942 100644 --- a/src/core/cfg/cfg_select.h +++ b/src/core/cfg/cfg_select.h @@ -24,9 +24,10 @@ #include "../select.h" -struct cfg_read_handle { - void *group; - void *var; +struct cfg_read_handle +{ + void *group; + void *var; }; /* free the list of not yet fixed selects */ @@ -45,7 +46,8 @@ int select_cfg_var(str *res, select_t *s, struct sip_msg *msg); * fixed-up later. * <0 - error */ -int read_cfg_var_fixup(char *gname, char *vname, struct cfg_read_handle *read_handle); +int read_cfg_var_fixup( + char *gname, char *vname, struct cfg_read_handle *read_handle); /* read the value of a variable via a group and variable name previously fixed up * Returns the type of the variable diff --git a/src/core/cfg/cfg_struct.c b/src/core/cfg/cfg_struct.c index 936580eb093..c5942af471f 100644 --- a/src/core/cfg/cfg_struct.c +++ b/src/core/cfg/cfg_struct.c @@ -31,25 +31,29 @@ #include "cfg_select.h" #include "cfg_struct.h" -cfg_group_t *cfg_group = NULL; /* linked list of registered cfg groups */ -cfg_block_t **cfg_global = NULL; /* pointer to the active cfg block */ -cfg_block_t *cfg_local = NULL; /* per-process pointer to the active cfg block. +cfg_group_t *cfg_group = NULL; /* linked list of registered cfg groups */ +cfg_block_t **cfg_global = NULL; /* pointer to the active cfg block */ +cfg_block_t *cfg_local = NULL; /* per-process pointer to the active cfg block. * Updated only when the child process * finishes working on the SIP message */ -int cfg_block_size = 0; /* size of the cfg block including the meta-data (constant) */ -gen_lock_t *cfg_global_lock = 0; /* protects *cfg_global */ -gen_lock_t *cfg_writer_lock = 0; /* This lock makes sure that two processes do not +int cfg_block_size = + 0; /* size of the cfg block including the meta-data (constant) */ +gen_lock_t *cfg_global_lock = 0; /* protects *cfg_global */ +gen_lock_t *cfg_writer_lock = + 0; /* This lock makes sure that two processes do not * try to clone *cfg_global at the same time. * Never try to get cfg_writer_lock when * cfg_global_lock is held */ -int cfg_shmized = 0; /* indicates whether the cfg block has been +int cfg_shmized = 0; /* indicates whether the cfg block has been * already shmized */ -cfg_child_cb_t **cfg_child_cb_first = NULL; /* first item of the per-child process +cfg_child_cb_t **cfg_child_cb_first = + NULL; /* first item of the per-child process * callback list */ -cfg_child_cb_t **cfg_child_cb_last = NULL; /* last item of the above list */ -cfg_child_cb_t *cfg_child_cb = NULL; /* pointer to the previously executed cb */ -int cfg_ginst_count = 0; /* number of group instances set within the child process */ +cfg_child_cb_t **cfg_child_cb_last = NULL; /* last item of the above list */ +cfg_child_cb_t *cfg_child_cb = NULL; /* pointer to the previously executed cb */ +int cfg_ginst_count = + 0; /* number of group instances set within the child process */ /* forward declarations */ @@ -57,38 +61,37 @@ static void del_add_var_list(cfg_group_t *group); static int apply_add_var_list(cfg_block_t *block, cfg_group_t *group); /* creates a new cfg group, and adds it to the linked list */ -cfg_group_t *cfg_new_group(char *name, int name_len, - int num, cfg_mapping_t *mapping, - char *vars, int size, void **handle) +cfg_group_t *cfg_new_group(char *name, int name_len, int num, + cfg_mapping_t *mapping, char *vars, int size, void **handle) { - cfg_group_t *group; + cfg_group_t *group; - if (cfg_shmized) { + if(cfg_shmized) { LM_ERR("too late config declaration\n"); return NULL; } - if (num > CFG_MAX_VAR_NUM) { + if(num > CFG_MAX_VAR_NUM) { LM_ERR("too many variables (%d) within a single group," - " the limit is %d. Increase CFG_MAX_VAR_NUM, or split the group" - " into multiple definitions.\n", + " the limit is %d. Increase CFG_MAX_VAR_NUM, or split the group" + " into multiple definitions.\n", num, CFG_MAX_VAR_NUM); return NULL; } - group = (cfg_group_t *)pkg_malloc(sizeof(cfg_group_t)+name_len-1); - if (!group) { + group = (cfg_group_t *)pkg_malloc(sizeof(cfg_group_t) + name_len - 1); + if(!group) { PKG_MEM_ERROR; return NULL; } - memset(group, 0, sizeof(cfg_group_t)+name_len-1); + memset(group, 0, sizeof(cfg_group_t) + name_len - 1); group->num = num; group->mapping = mapping; group->vars = vars; group->size = size; group->handle = handle; - if (handle) + if(handle) group->orig_handle = *handle; group->name_len = name_len; memcpy(&group->name, name, name_len); @@ -101,8 +104,7 @@ cfg_group_t *cfg_new_group(char *name, int name_len, } /* Set the values of an existing cfg group. */ -void cfg_set_group(cfg_group_t *group, - int num, cfg_mapping_t *mapping, +void cfg_set_group(cfg_group_t *group, int num, cfg_mapping_t *mapping, char *vars, int size, void **handle) { group->num = num; @@ -110,7 +112,7 @@ void cfg_set_group(cfg_group_t *group, group->vars = vars; group->size = size; group->handle = handle; - if (handle) + if(handle) group->orig_handle = *handle; } @@ -119,16 +121,16 @@ void cfg_set_group(cfg_group_t *group, */ int cfg_clone_str(str *src, str *dst) { - char *c; + char *c; - if (!src->s) { + if(!src->s) { dst->s = NULL; dst->len = 0; return 0; } - c = (char *)shm_malloc(sizeof(char)*(src->len+1)); - if (!c) { + c = (char *)shm_malloc(sizeof(char) * (src->len + 1)); + if(!c) { SHM_MEM_ERROR; return -1; } @@ -144,31 +146,35 @@ int cfg_clone_str(str *src, str *dst) /* copies the strings to shared memory */ static int cfg_shmize_strings(cfg_group_t *group) { - cfg_mapping_t *mapping; - int i; - str s; + cfg_mapping_t *mapping; + int i; + str s; /* We do not know in advance whether the variable will be changed or not, * and it can happen that we try to free the shm memory area when * the variable is changed, hence, it must be already in shm mem */ mapping = group->mapping; - for (i=0; inum; i++) { + for(i = 0; i < group->num; i++) { /* the cfg driver module may have already shmized the variable */ - if (mapping[i].flag & cfg_var_shmized) continue; + if(mapping[i].flag & cfg_var_shmized) + continue; - if (CFG_VAR_TYPE(&mapping[i]) == CFG_VAR_STRING) { + if(CFG_VAR_TYPE(&mapping[i]) == CFG_VAR_STRING) { s.s = *(char **)(group->vars + mapping[i].offset); - if (!s.s) continue; + if(!s.s) + continue; s.len = strlen(s.s); - } else if (CFG_VAR_TYPE(&mapping[i]) == CFG_VAR_STR) { + } else if(CFG_VAR_TYPE(&mapping[i]) == CFG_VAR_STR) { memcpy(&s, group->vars + mapping[i].offset, sizeof(str)); - if (!s.s) continue; + if(!s.s) + continue; } else { continue; } - if (cfg_clone_str(&s, &s)) return -1; + if(cfg_clone_str(&s, &s)) + return -1; *(char **)(group->vars + mapping[i].offset) = s.s; mapping[i].flag |= cfg_var_shmized; } @@ -179,11 +185,12 @@ static int cfg_shmize_strings(cfg_group_t *group) /* copy the variables to shm mem */ int cfg_shmize(void) { - cfg_group_t *group; - cfg_block_t *block = NULL; - int size; + cfg_group_t *group; + cfg_block_t *block = NULL; + int size; - if (!cfg_group) return 0; + if(!cfg_group) + return 0; /* Let us allocate one memory block that * will contain all the variables + meta-data @@ -201,10 +208,7 @@ int cfg_shmize(void) * The additional array for the multiple values * of the same variable is linked to the meta-data. */ - for (size=0, group = cfg_group; - group; - group=group->next - ) { + for(size = 0, group = cfg_group; group; group = group->next) { size = ROUND_POINTER(size); group->meta_offset = size; size += sizeof(cfg_group_meta_t); @@ -214,54 +218,55 @@ int cfg_shmize(void) size += group->size; } - block = (cfg_block_t*)shm_malloc(sizeof(cfg_block_t)+size-1); - if (!block) { + block = (cfg_block_t *)shm_malloc(sizeof(cfg_block_t) + size - 1); + if(!block) { SHM_MEM_ERROR; goto error; } - memset(block, 0, sizeof(cfg_block_t)+size-1); + memset(block, 0, sizeof(cfg_block_t) + size - 1); cfg_block_size = size; /* copy the memory fragments to the single block */ - for ( group = cfg_group; - group; - group=group->next - ) { - if (group->dynamic == CFG_GROUP_STATIC) { + for(group = cfg_group; group; group = group->next) { + if(group->dynamic == CFG_GROUP_STATIC) { /* clone the strings to shm mem */ - if (cfg_shmize_strings(group)) goto error; + if(cfg_shmize_strings(group)) + goto error; /* copy the values to the new block */ memcpy(CFG_GROUP_DATA(block, group), group->vars, group->size); - } else if (group->dynamic == CFG_GROUP_DYNAMIC) { + } else if(group->dynamic == CFG_GROUP_DYNAMIC) { /* The group was declared with NULL values, * we have to fix it up. * The fixup function takes care about the values, * it fills up the block */ - if (cfg_script_fixup(group, CFG_GROUP_DATA(block, group))) goto error; + if(cfg_script_fixup(group, CFG_GROUP_DATA(block, group))) + goto error; /* Notify the drivers about the new config definition. * Temporary set the group handle so that the drivers have a chance to * overwrite the default values. The handle must be reset after this * because the main process does not have a local configuration. */ *(group->handle) = CFG_GROUP_DATA(block, group); - cfg_notify_drivers(group->name, group->name_len, - group->mapping->def); + cfg_notify_drivers( + group->name, group->name_len, group->mapping->def); *(group->handle) = NULL; } else { - LM_ERR("configuration group is declared without any variable: %.*s\n", + LM_ERR("configuration group is declared without any variable: " + "%.*s\n", group->name_len, group->name); goto error; } /* Create the additional group instances with applying * the temporary list. */ - if (apply_add_var_list(block, group)) + if(apply_add_var_list(block, group)) goto error; } /* try to fixup the selects that failed to be fixed-up previously */ - if (cfg_fixup_selects()) goto error; + if(cfg_fixup_selects()) + goto error; /* install the new config */ cfg_install_global(block, NULL, NULL, NULL); @@ -270,18 +275,19 @@ int cfg_shmize(void) return 0; error: - if (block) shm_free(block); + if(block) + shm_free(block); return -1; } /* deallocate the list of groups, and the shmized strings */ static void cfg_destory_groups(unsigned char *block) { - cfg_group_t *group, *group2; - cfg_mapping_t *mapping; - cfg_def_t *def; - void *old_string; - int i; + cfg_group_t *group, *group2; + cfg_mapping_t *mapping; + cfg_def_t *def; + void *old_string; + int i; group = cfg_group; while(group) { @@ -289,23 +295,26 @@ static void cfg_destory_groups(unsigned char *block) def = mapping ? mapping->def : NULL; /* destory the shmized strings in the block */ - if (block && def) - for (i=0; inum; i++) - if (((CFG_VAR_TYPE(&mapping[i]) == CFG_VAR_STRING) || - (CFG_VAR_TYPE(&mapping[i]) == CFG_VAR_STR)) && - mapping[i].flag & cfg_var_shmized) { - - old_string = *(char **)(block + group->var_offset + mapping[i].offset); - if (old_string) shm_free(old_string); + if(block && def) + for(i = 0; i < group->num; i++) + if(((CFG_VAR_TYPE(&mapping[i]) == CFG_VAR_STRING) + || (CFG_VAR_TYPE(&mapping[i]) == CFG_VAR_STR)) + && mapping[i].flag & cfg_var_shmized) { + + old_string = *(char **)(block + group->var_offset + + mapping[i].offset); + if(old_string) + shm_free(old_string); } - if (group->dynamic == CFG_GROUP_DYNAMIC) { + if(group->dynamic == CFG_GROUP_DYNAMIC) { /* the group was dynamically allocated */ cfg_script_destroy(group); } else { /* only the mapping was allocated, all the other * pointers are just set to static variables */ - if (mapping) pkg_free(mapping); + if(mapping) + pkg_free(mapping); } /* Delete the additional variable list */ del_add_var_list(group); @@ -321,11 +330,11 @@ int sr_cfg_init(void) { /* lock_alloc() is a define for shm_malloc */ cfg_global_lock = lock_alloc(); - if (!cfg_global_lock) { + if(!cfg_global_lock) { SHM_MEM_ERROR; goto error; } - if (lock_init(cfg_global_lock) == 0) { + if(lock_init(cfg_global_lock) == 0) { LM_ERR("failed to init lock\n"); lock_dealloc(cfg_global_lock); cfg_global_lock = 0; @@ -333,11 +342,11 @@ int sr_cfg_init(void) } cfg_writer_lock = lock_alloc(); - if (!cfg_writer_lock) { + if(!cfg_writer_lock) { SHM_MEM_ERROR; goto error; } - if (lock_init(cfg_writer_lock) == 0) { + if(lock_init(cfg_writer_lock) == 0) { LM_ERR("failed to init lock\n"); lock_dealloc(cfg_writer_lock); cfg_writer_lock = 0; @@ -345,21 +354,22 @@ int sr_cfg_init(void) } cfg_global = (cfg_block_t **)shm_malloc(sizeof(cfg_block_t *)); - if (!cfg_global) { + if(!cfg_global) { SHM_MEM_ERROR; goto error; } *cfg_global = NULL; - cfg_child_cb_first = (cfg_child_cb_t **)shm_malloc(sizeof(cfg_child_cb_t *)); - if (!cfg_child_cb_first) { + cfg_child_cb_first = + (cfg_child_cb_t **)shm_malloc(sizeof(cfg_child_cb_t *)); + if(!cfg_child_cb_first) { SHM_MEM_ERROR; goto error; } *cfg_child_cb_first = NULL; cfg_child_cb_last = (cfg_child_cb_t **)shm_malloc(sizeof(cfg_child_cb_t *)); - if (!cfg_child_cb_last) { + if(!cfg_child_cb_last) { SHM_MEM_ERROR; goto error; } @@ -369,9 +379,10 @@ int sr_cfg_init(void) * This stucture will be the entry point for the child processes, and * will be freed later, when none of the processes refers to it */ *cfg_child_cb_first = *cfg_child_cb_last = - cfg_child_cb_new(NULL, NULL, NULL, 0); + cfg_child_cb_new(NULL, NULL, NULL, 0); - if (!*cfg_child_cb_first) goto error; + if(!*cfg_child_cb_first) + goto error; return 0; @@ -388,33 +399,36 @@ void cfg_destroy(void) cfg_ctx_destroy(); /* free the list of groups */ - cfg_destory_groups((cfg_global && (*cfg_global)) ? (*cfg_global)->vars : NULL); + cfg_destory_groups( + (cfg_global && (*cfg_global)) ? (*cfg_global)->vars : NULL); /* free the select list */ cfg_free_selects(); - if (cfg_child_cb_first) { - if (*cfg_child_cb_first) cfg_child_cb_free_list(*cfg_child_cb_first); + if(cfg_child_cb_first) { + if(*cfg_child_cb_first) + cfg_child_cb_free_list(*cfg_child_cb_first); shm_free(cfg_child_cb_first); cfg_child_cb_first = NULL; } - if (cfg_child_cb_last) { + if(cfg_child_cb_last) { shm_free(cfg_child_cb_last); cfg_child_cb_last = NULL; } - if (cfg_global) { - if (*cfg_global) cfg_block_free(*cfg_global); + if(cfg_global) { + if(*cfg_global) + cfg_block_free(*cfg_global); shm_free(cfg_global); cfg_global = NULL; } - if (cfg_global_lock) { + if(cfg_global_lock) { lock_destroy(cfg_global_lock); lock_dealloc(cfg_global_lock); cfg_global_lock = 0; } - if (cfg_writer_lock) { + if(cfg_writer_lock) { lock_destroy(cfg_writer_lock); lock_dealloc(cfg_writer_lock); cfg_writer_lock = 0; @@ -494,15 +508,16 @@ int cfg_child_no_cb_init(void) */ void cfg_child_destroy(void) { - cfg_child_cb_t *prev_cb; + cfg_child_cb_t *prev_cb; /* unref the local config */ - if (cfg_local) { + if(cfg_local) { CFG_UNREF(cfg_local); cfg_local = NULL; } - if (!cfg_child_cb || cfg_child_cb==CFG_NO_CHILD_CBS) return; + if(!cfg_child_cb || cfg_child_cb == CFG_NO_CHILD_CBS) + return; /* The lock must be held to make sure that the global config * is not replaced meantime, and the other child processes do not @@ -514,16 +529,16 @@ void cfg_child_destroy(void) /* go through the list and check whether there is any item that * has to be freed (similar to cfg_update_local(), but without executing * the callback functions) */ - while (cfg_child_cb != *cfg_child_cb_last) { + while(cfg_child_cb != *cfg_child_cb_last) { prev_cb = cfg_child_cb; cfg_child_cb = cfg_child_cb->next; atomic_inc(&cfg_child_cb->refcnt); - if (atomic_dec_and_test(&prev_cb->refcnt)) { + if(atomic_dec_and_test(&prev_cb->refcnt)) { /* No more pocess refers to this callback. * Did this process block the deletion, * or is there any other process that has not * reached prev_cb yet? */ - if (*cfg_child_cb_first == prev_cb) { + if(*cfg_child_cb_first == prev_cb) { /* yes, this process was blocking the deletion */ *cfg_child_cb_first = cfg_child_cb; cfg_child_cb_free_item(prev_cb); @@ -544,75 +559,66 @@ void cfg_child_destroy(void) /* searches a group by name */ cfg_group_t *cfg_lookup_group(char *name, int len) { - cfg_group_t *g; - - for ( g = cfg_group; - g; - g = g->next - ) - if ((g->name_len == len) - && (memcmp(g->name, name, len)==0)) + cfg_group_t *g; + + for(g = cfg_group; g; g = g->next) + if((g->name_len == len) && (memcmp(g->name, name, len) == 0)) return g; return NULL; } /* searches a variable definition by group and variable name */ -int cfg_lookup_var(str *gname, str *vname, - cfg_group_t **group, cfg_mapping_t **var) +int cfg_lookup_var( + str *gname, str *vname, cfg_group_t **group, cfg_mapping_t **var) { - cfg_group_t *g; - int i; - - for (g = cfg_group; - g; - g = g->next - ) - if ((g->name_len == gname->len) - && (memcmp(g->name, gname->s, gname->len)==0)) { - - if (!g->mapping) return -1; /* dynamic group is not ready */ - - for ( i = 0; - i < g->num; - i++ - ) { - if ((g->mapping[i].name_len == vname->len) - && (memcmp(g->mapping[i].def->name, vname->s, vname->len)==0)) { - if (group) *group = g; - if (var) *var = &(g->mapping[i]); + cfg_group_t *g; + int i; + + for(g = cfg_group; g; g = g->next) + if((g->name_len == gname->len) + && (memcmp(g->name, gname->s, gname->len) == 0)) { + + if(!g->mapping) + return -1; /* dynamic group is not ready */ + + for(i = 0; i < g->num; i++) { + if((g->mapping[i].name_len == vname->len) + && (memcmp(g->mapping[i].def->name, vname->s, + vname->len) + == 0)) { + if(group) + *group = g; + if(var) + *var = &(g->mapping[i]); return 0; } } break; } - LM_DBG("variable not found: %.*s.%.*s\n", - gname->len, gname->s, - vname->len, vname->s); + LM_DBG("variable not found: %.*s.%.*s\n", gname->len, gname->s, vname->len, + vname->s); return -1; } /* searches a variable definition within a group by its name */ cfg_mapping_t *cfg_lookup_var2(cfg_group_t *group, char *name, int len) { - int i; + int i; - if (!group->mapping) return NULL; /* dynamic group is not ready */ + if(!group->mapping) + return NULL; /* dynamic group is not ready */ - for ( i = 0; - i < group->num; - i++ - ) { - if ((group->mapping[i].name_len == len) - && (memcmp(group->mapping[i].def->name, name, len)==0)) { + for(i = 0; i < group->num; i++) { + if((group->mapping[i].name_len == len) + && (memcmp(group->mapping[i].def->name, name, len) == 0)) { return &(group->mapping[i]); } } - LM_DBG("variable not found: %.*s.%.*s\n", - group->name_len, group->name, - len, name); + LM_DBG("variable not found: %.*s.%.*s\n", group->name_len, group->name, len, + name); return NULL; } @@ -621,14 +627,14 @@ cfg_mapping_t *cfg_lookup_var2(cfg_group_t *group, char *name, int len) */ cfg_block_t *cfg_clone_global(void) { - cfg_block_t *block; + cfg_block_t *block; - block = (cfg_block_t*)shm_malloc(sizeof(cfg_block_t)+cfg_block_size-1); - if (!block) { + block = (cfg_block_t *)shm_malloc(sizeof(cfg_block_t) + cfg_block_size - 1); + if(!block) { SHM_MEM_ERROR; return NULL; } - memcpy(block, *cfg_global, sizeof(cfg_block_t)+cfg_block_size-1); + memcpy(block, *cfg_global, sizeof(cfg_block_t) + cfg_block_size - 1); /* reset the reference counter */ atomic_set(&block->refcnt, 0); @@ -639,15 +645,15 @@ cfg_block_t *cfg_clone_global(void) /* Clone an array of configuration group instances. */ cfg_group_inst_t *cfg_clone_array(cfg_group_meta_t *meta, cfg_group_t *group) { - cfg_group_inst_t *new_array; - int size; + cfg_group_inst_t *new_array; + int size; - if (!meta->array || !meta->num) + if(!meta->array || !meta->num) return NULL; size = (sizeof(cfg_group_inst_t) + group->size - 1) * meta->num; new_array = (cfg_group_inst_t *)shm_malloc(size); - if (!new_array) { + if(!new_array) { SHM_MEM_ERROR; return NULL; } @@ -659,40 +665,37 @@ cfg_group_inst_t *cfg_clone_array(cfg_group_meta_t *meta, cfg_group_t *group) /* Extend the array of configuration group instances with one more instance. * Only the ID of the new group is set, nothing else. */ cfg_group_inst_t *cfg_extend_array(cfg_group_meta_t *meta, cfg_group_t *group, - unsigned int group_id, - cfg_group_inst_t **new_group) + unsigned int group_id, cfg_group_inst_t **new_group) { - int i; - cfg_group_inst_t *new_array, *old_array; - int inst_size; + int i; + cfg_group_inst_t *new_array, *old_array; + int inst_size; inst_size = sizeof(cfg_group_inst_t) + group->size - 1; new_array = (cfg_group_inst_t *)shm_malloc(inst_size * (meta->num + 1)); - if (!new_array) { + if(!new_array) { SHM_MEM_ERROR; return NULL; } /* Find the position of the new group in the array. The array is ordered * by the group IDs. */ old_array = meta->array; - for ( i = 0; - (i < meta->num) - && (((cfg_group_inst_t *)((char *)old_array + inst_size * i))->id < group_id); - i++ - ); - if (i > 0) - memcpy( new_array, - old_array, - (size_t) inst_size * i); - - memset((char*)new_array + inst_size * i, 0, inst_size); - *new_group = (cfg_group_inst_t *)((char*)new_array + inst_size * i); + for(i = 0; (i < meta->num) + && (((cfg_group_inst_t *)((char *)old_array + inst_size * i))->id + < group_id); + i++) + ; + if(i > 0) + memcpy(new_array, old_array, (size_t)inst_size * i); + + memset((char *)new_array + inst_size * i, 0, inst_size); + *new_group = (cfg_group_inst_t *)((char *)new_array + inst_size * i); (*new_group)->id = group_id; - if (i < meta->num) - memcpy( (char*)new_array + inst_size * (i + 1), - (char*)old_array + inst_size * i, - (size_t) inst_size * (meta->num - i)); + if(i < meta->num) + memcpy((char *)new_array + inst_size * (i + 1), + (char *)old_array + inst_size * i, + (size_t)inst_size * (meta->num - i)); return new_array; } @@ -701,36 +704,33 @@ cfg_group_inst_t *cfg_extend_array(cfg_group_meta_t *meta, cfg_group_t *group, * inst must point to an instance within meta->array. * *_new_array is set to the newly allocated array. */ int cfg_collapse_array(cfg_group_meta_t *meta, cfg_group_t *group, - cfg_group_inst_t *inst, - cfg_group_inst_t **_new_array) + cfg_group_inst_t *inst, cfg_group_inst_t **_new_array) { - cfg_group_inst_t *new_array, *old_array; - int inst_size, offset; + cfg_group_inst_t *new_array, *old_array; + int inst_size, offset; - if (!meta->num) + if(!meta->num) return -1; - if (meta->num == 1) { + if(meta->num == 1) { *_new_array = NULL; return 0; } inst_size = sizeof(cfg_group_inst_t) + group->size - 1; new_array = (cfg_group_inst_t *)shm_malloc(inst_size * (meta->num - 1)); - if (!new_array) { + if(!new_array) { SHM_MEM_ERROR; return -1; } old_array = meta->array; offset = (char *)inst - (char *)old_array; - if (offset) - memcpy( new_array, - old_array, - offset); + if(offset) + memcpy(new_array, old_array, offset); - if (meta->num * inst_size > offset + inst_size) - memcpy( (char *)new_array + offset, + if(meta->num * inst_size > offset + inst_size) + memcpy((char *)new_array + offset, (char *)old_array + offset + inst_size, (meta->num - 1) * inst_size - offset); @@ -739,21 +739,24 @@ int cfg_collapse_array(cfg_group_meta_t *meta, cfg_group_t *group, } /* Find the group instance within the meta-data based on the group_id */ -cfg_group_inst_t *cfg_find_group(cfg_group_meta_t *meta, int group_size, unsigned int group_id) +cfg_group_inst_t *cfg_find_group( + cfg_group_meta_t *meta, int group_size, unsigned int group_id) { - int i; + int i; cfg_group_inst_t *ginst; - if (!meta) + if(!meta) return NULL; /* For now, search lineary. TODO: improve */ - for (i = 0; i < meta->num; i++) { + for(i = 0; i < meta->num; i++) { ginst = (cfg_group_inst_t *)((char *)meta->array - + (sizeof(cfg_group_inst_t) + group_size - 1) * i); - if (ginst->id == group_id) + + (sizeof(cfg_group_inst_t) + group_size + - 1) + * i); + if(ginst->id == group_id) return ginst; - else if (ginst->id > group_id) + else if(ginst->id > group_id) break; /* needless to continue, the array is ordered */ } return NULL; @@ -781,19 +784,20 @@ void cfg_install_child_cb(cfg_child_cb_t *cb_first, cfg_child_cb_t *cb_last) void cfg_install_global(cfg_block_t *block, void **replaced, cfg_child_cb_t *cb_first, cfg_child_cb_t *cb_last) { - cfg_block_t* old_cfg; + cfg_block_t *old_cfg; CFG_REF(block); - if (replaced) { + if(replaced) { /* The replaced array is specified, it has to be linked to the child cb structure. * The last child process processing this structure will free the old strings and the array. */ - if (cb_first) { + if(cb_first) { cb_first->replaced = replaced; } else { /* At least one child cb structure is needed. */ - cb_first = cfg_child_cb_new(NULL, NULL, NULL, 0 /* gname, name, cb, type */); - if (cb_first) { + cb_first = cfg_child_cb_new( + NULL, NULL, NULL, 0 /* gname, name, cb, type */); + if(cb_first) { cb_last = cb_first; cb_first->replaced = replaced; } else { @@ -810,40 +814,39 @@ void cfg_install_global(cfg_block_t *block, void **replaced, old_cfg = *cfg_global; *cfg_global = block; - if (cb_first) + if(cb_first) cfg_install_child_cb(cb_first, cb_last); CFG_UNLOCK(); - if (old_cfg) + if(old_cfg) CFG_UNREF(old_cfg); } /* creates a structure for a per-child process callback */ -cfg_child_cb_t *cfg_child_cb_new(str *gname, str *name, - cfg_on_set_child cb, - unsigned int type) +cfg_child_cb_t *cfg_child_cb_new( + str *gname, str *name, cfg_on_set_child cb, unsigned int type) { - cfg_child_cb_t *cb_struct; + cfg_child_cb_t *cb_struct; cb_struct = (cfg_child_cb_t *)shm_malloc(sizeof(cfg_child_cb_t)); - if (!cb_struct) { + if(!cb_struct) { SHM_MEM_ERROR; return NULL; } memset(cb_struct, 0, sizeof(cfg_child_cb_t)); - if (gname) { + if(gname) { cb_struct->gname.s = gname->s; cb_struct->gname.len = gname->len; } - if (name) { + if(name) { cb_struct->name.s = name->s; cb_struct->name.len = name->len; } cb_struct->cb = cb; atomic_set(&cb_struct->refcnt, 0); - if (type & CFG_CB_ONLY_ONCE) { + if(type & CFG_CB_ONLY_ONCE) { /* The callback needs to be executed only once. * Set the cb_count value to 1, so the first child * process that executes the callback will decrement @@ -856,7 +859,7 @@ cfg_child_cb_t *cfg_child_cb_new(str *gname, str *name, * so all the child processes will execute the callback, * the counter will never reach 0. */ - atomic_set(&cb_struct->cb_count, (1U<<(sizeof(int)*8-1))-1); + atomic_set(&cb_struct->cb_count, (1U << (sizeof(int) * 8 - 1)) - 1); } return cb_struct; @@ -865,12 +868,9 @@ cfg_child_cb_t *cfg_child_cb_new(str *gname, str *name, /* free the memory allocated for a child cb list */ void cfg_child_cb_free_list(cfg_child_cb_t *child_cb_first) { - cfg_child_cb_t *cb, *cb_next; + cfg_child_cb_t *cb, *cb_next; - for(cb = child_cb_first; - cb; - cb = cb_next - ) { + for(cb = child_cb_first; cb; cb = cb_next) { cb_next = cb->next; cfg_child_cb_free_item(cb); } @@ -885,66 +885,64 @@ void cfg_child_cb_free_list(cfg_child_cb_t *child_cb_first) int new_add_var(str *group_name, unsigned int group_id, str *var_name, void *val, unsigned int type) { - cfg_group_t *group; - cfg_add_var_t *add_var = NULL, **add_var_p; - int len; + cfg_group_t *group; + cfg_add_var_t *add_var = NULL, **add_var_p; + int len; - if (type && !var_name) { + if(type && !var_name) { LM_ERR("Missing variable specification\n"); goto error; } - if (type) + if(type) LM_DBG("declaring a new variable instance %.*s[%u].%.*s\n", - group_name->len, group_name->s, - group_id, - var_name->len, var_name->s); + group_name->len, group_name->s, group_id, var_name->len, + var_name->s); else - LM_DBG("declaring a new group instance %.*s[%u]\n", - group_name->len, group_name->s, - group_id); + LM_DBG("declaring a new group instance %.*s[%u]\n", group_name->len, + group_name->s, group_id); - if (cfg_shmized) { + if(cfg_shmized) { LM_ERR("too late, the configuration has already been shmized\n"); goto error; } group = cfg_lookup_group(group_name->s, group_name->len); - if (!group) { + if(!group) { /* create a new group with NULL values, it will be filled in later */ - group = cfg_new_group(group_name->s, group_name->len, - 0 /* num */, NULL /* mapping */, - NULL /* vars */, 0 /* size */, NULL /* handle */); + group = cfg_new_group(group_name->s, group_name->len, 0 /* num */, + NULL /* mapping */, NULL /* vars */, 0 /* size */, + NULL /* handle */); - if (!group) + if(!group) goto error; /* It is not yet known whether the group will be static or dynamic */ group->dynamic = CFG_GROUP_UNKNOWN; } - add_var = (cfg_add_var_t *)pkg_malloc(sizeof(cfg_add_var_t) + - (type ? (var_name->len - 1) : 0)); - if (!add_var) { + add_var = (cfg_add_var_t *)pkg_malloc( + sizeof(cfg_add_var_t) + (type ? (var_name->len - 1) : 0)); + if(!add_var) { PKG_MEM_ERROR; goto error; } - memset(add_var, 0, sizeof(cfg_add_var_t) + - (type ? (var_name->len - 1) : 0)); + memset(add_var, 0, + sizeof(cfg_add_var_t) + (type ? (var_name->len - 1) : 0)); add_var->group_id = group_id; - if (type) { + if(type) { add_var->name_len = var_name->len; memcpy(add_var->name, var_name->s, var_name->len); - switch (type) { + switch(type) { case CFG_VAR_INT: add_var->val.i = (int)(long)val; break; case CFG_VAR_STR: len = ((str *)val)->len; - if (len) { + if(len) { add_var->val.s.s = (char *)pkg_malloc(sizeof(char) * len); - if (!add_var->val.s.s) { + if(!add_var->val.s.s) { PKG_MEM_ERROR; goto error; } @@ -956,10 +954,11 @@ int new_add_var(str *group_name, unsigned int group_id, str *var_name, break; case CFG_VAR_STRING: - if (val) { + if(val) { len = strlen((char *)val); - add_var->val.ch = (char *)pkg_malloc(sizeof(char) * (len + 1)); - if (!add_var->val.ch) { + add_var->val.ch = + (char *)pkg_malloc(sizeof(char) * (len + 1)); + if(!add_var->val.ch) { PKG_MEM_ERROR; goto error; } @@ -979,9 +978,10 @@ int new_add_var(str *group_name, unsigned int group_id, str *var_name, /* order the list by group_id, it will be easier * to count the group instances */ - for( add_var_p = &group->add_var; + for(add_var_p = &group->add_var; *add_var_p && ((*add_var_p)->group_id <= group_id); - add_var_p = &((*add_var_p)->next)); + add_var_p = &((*add_var_p)->next)) + ; add_var->next = *add_var_p; *add_var_p = add_var; @@ -989,16 +989,17 @@ int new_add_var(str *group_name, unsigned int group_id, str *var_name, return 0; error: - if (!type) + if(!type) LM_ERR("failed to add the additional group instance: %.*s[%u]\n", group_name->len, group_name->s, group_id); else - LM_ERR("failed to add the additional variable instance: %.*s[%u].%.*s\n", + LM_ERR("failed to add the additional variable instance: " + "%.*s[%u].%.*s\n", group_name->len, group_name->s, group_id, - (var_name)?var_name->len:0, - (var_name&&var_name->s)?var_name->s:""); + (var_name) ? var_name->len : 0, + (var_name && var_name->s) ? var_name->s : ""); - if (add_var) + if(add_var) pkg_free(add_var); return -1; } @@ -1006,14 +1007,14 @@ int new_add_var(str *group_name, unsigned int group_id, str *var_name, /* delete the additional variable list */ static void del_add_var_list(cfg_group_t *group) { - cfg_add_var_t *add_var, *add_var2; + cfg_add_var_t *add_var, *add_var2; add_var = group->add_var; - while (add_var) { + while(add_var) { add_var2 = add_var->next; - if ((add_var->type == CFG_VAR_STR) && add_var->val.s.s) + if((add_var->type == CFG_VAR_STR) && add_var->val.s.s) pkg_free(add_var->val.s.s); - else if ((add_var->type == CFG_VAR_STRING) && add_var->val.ch) + else if((add_var->type == CFG_VAR_STRING) && add_var->val.ch) pkg_free(add_var->val.ch); pkg_free(add_var); add_var = add_var2; @@ -1024,60 +1025,58 @@ static void del_add_var_list(cfg_group_t *group) /* create the array of additional group instances from the linked list */ static int apply_add_var_list(cfg_block_t *block, cfg_group_t *group) { - int i, num, size; - unsigned int group_id; - cfg_add_var_t *add_var; - cfg_group_inst_t *new_array, *ginst; + int i, num, size; + unsigned int group_id; + cfg_add_var_t *add_var; + cfg_group_inst_t *new_array, *ginst; cfg_group_meta_t *gm; /* count the number of group instances */ - for ( add_var = group->add_var, num = 0, group_id = 0; - add_var; - add_var = add_var->next - ) { - if (!num || (group_id != add_var->group_id)) { + for(add_var = group->add_var, num = 0, group_id = 0; add_var; + add_var = add_var->next) { + if(!num || (group_id != add_var->group_id)) { num++; group_id = add_var->group_id; } } - if (!num) /* nothing to do */ + if(!num) /* nothing to do */ return 0; LM_DBG("creating the group instance array " - "for '%.*s' with %d slots\n", + "for '%.*s' with %d slots\n", group->name_len, group->name, num); size = (sizeof(cfg_group_inst_t) + group->size - 1) * num; new_array = (cfg_group_inst_t *)shm_malloc(size); - if (!new_array) { + if(!new_array) { SHM_MEM_ERROR; return -1; } memset(new_array, 0, size); - for (i = 0; i < num; i++) { + for(i = 0; i < num; i++) { /* Go though each group instance, set the default values, * and apply the changes */ - if (!group->add_var) { + if(!group->add_var) { LM_ERR("BUG: no more additional variable left\n"); goto error; } - ginst = (cfg_group_inst_t *)((char*)new_array - + (sizeof(cfg_group_inst_t) + group->size - 1) * i); + ginst = (cfg_group_inst_t *)((char *)new_array + + (sizeof(cfg_group_inst_t) + group->size + - 1) + * i); ginst->id = group->add_var->group_id; /* fill in the new group instance with the default data */ - memcpy( ginst->vars, - CFG_GROUP_DATA(block, group), - group->size); + memcpy(ginst->vars, CFG_GROUP_DATA(block, group), group->size); /* cfg_apply_list() moves the group->add_var pointer to * the beginning of the new group instance. */ - if (cfg_apply_list(ginst, group, ginst->id, &group->add_var)) + if(cfg_apply_list(ginst, group, ginst->id, &group->add_var)) goto error; } #ifdef EXTRA_DEBUG - if (group->add_var) { + if(group->add_var) { LM_ERR("not all the additional variables have been consumed\n"); goto error; } @@ -1101,23 +1100,23 @@ static int apply_add_var_list(cfg_block_t *block, cfg_group_t *group) * The function executes all the per-child process callbacks which are different * in the two instances. */ -void cfg_move_handle(cfg_group_t *group, cfg_group_inst_t *src_ginst, cfg_group_inst_t *dst_ginst) +void cfg_move_handle(cfg_group_t *group, cfg_group_inst_t *src_ginst, + cfg_group_inst_t *dst_ginst) { - cfg_mapping_t *var; - unsigned int bitmap; - int i, pos; - str gname, vname; + cfg_mapping_t *var; + unsigned int bitmap; + int i, pos; + str gname, vname; - if (src_ginst == dst_ginst) - return; /* nothing to do */ + if(src_ginst == dst_ginst) + return; /* nothing to do */ /* move the handle to the variables of the dst group instance, * or to the local config if no dst group instance is specified */ - *(group->handle) = dst_ginst ? - dst_ginst->vars - : CFG_GROUP_DATA(cfg_local, group); + *(group->handle) = + dst_ginst ? dst_ginst->vars : CFG_GROUP_DATA(cfg_local, group); - if (cfg_child_cb != CFG_NO_CHILD_CBS) { + if(cfg_child_cb != CFG_NO_CHILD_CBS) { /* call the per child process callback of those variables * that have different value in the two group instances */ /* TODO: performance optimization: this entire loop can be @@ -1126,13 +1125,13 @@ void cfg_move_handle(cfg_group_t *group, cfg_group_inst_t *src_ginst, cfg_group_ * structure for this purpose. */ gname.s = group->name; gname.len = group->name_len; - for (i = 0; i < CFG_MAX_VAR_NUM/(sizeof(int)*8); i++) { + for(i = 0; i < CFG_MAX_VAR_NUM / (sizeof(int) * 8); i++) { bitmap = ((src_ginst) ? src_ginst->set[i] : 0U) - | ((dst_ginst) ? dst_ginst->set[i] : 0U); - while (bitmap) { + | ((dst_ginst) ? dst_ginst->set[i] : 0U); + while(bitmap) { pos = bit_scan_forward32(bitmap); - var = &group->mapping[pos + i*sizeof(int)*8]; - if (var->def->on_set_child_cb) { + var = &group->mapping[pos + i * sizeof(int) * 8]; + if(var->def->on_set_child_cb) { vname.s = var->def->name; vname.len = var->name_len; var->def->on_set_child_cb(&gname, &vname); @@ -1142,12 +1141,12 @@ void cfg_move_handle(cfg_group_t *group, cfg_group_inst_t *src_ginst, cfg_group_ } } /* keep track of how many group instances are set in the child process */ - if (!src_ginst && dst_ginst) + if(!src_ginst && dst_ginst) cfg_ginst_count++; - else if (!dst_ginst) + else if(!dst_ginst) cfg_ginst_count--; #ifdef EXTRA_DEBUG - if (cfg_ginst_count < 0) + if(cfg_ginst_count < 0) LM_ERR("BUG: cfg_ginst_count is negative: %d. group=%.*s\n", cfg_ginst_count, group->name_len, group->name); #endif @@ -1157,45 +1156,45 @@ void cfg_move_handle(cfg_group_t *group, cfg_group_inst_t *src_ginst, cfg_group_ /* Move the group handle to the specified group instance. */ int cfg_select(cfg_group_t *group, unsigned int id) { - cfg_group_inst_t *ginst; + cfg_group_inst_t *ginst; - if (!cfg_local) { + if(!cfg_local) { LM_ERR("The child process has no local configuration\n"); return -1; } - if (!(ginst = cfg_find_group(CFG_GROUP_META(cfg_local, group), - group->size, - id)) - ) { - LM_ERR("group instance '%.*s[%u]' does not exist\n", - group->name_len, group->name, id); + if(!(ginst = cfg_find_group( + CFG_GROUP_META(cfg_local, group), group->size, id))) { + LM_ERR("group instance '%.*s[%u]' does not exist\n", group->name_len, + group->name, id); return -1; } cfg_move_handle(group, - CFG_HANDLE_TO_GINST(*(group->handle)), /* the active group instance */ + CFG_HANDLE_TO_GINST( + *(group->handle)), /* the active group instance */ ginst); - LM_DBG("group instance '%.*s[%u]' has been selected\n", - group->name_len, group->name, id); + LM_DBG("group instance '%.*s[%u]' has been selected\n", group->name_len, + group->name, id); return 0; } /* Reset the group handle to the default, local configuration */ int cfg_reset(cfg_group_t *group) { - if (!cfg_local) { + if(!cfg_local) { LM_ERR("The child process has no local configuration\n"); return -1; } cfg_move_handle(group, - CFG_HANDLE_TO_GINST(*(group->handle)), /* the active group instance */ + CFG_HANDLE_TO_GINST( + *(group->handle)), /* the active group instance */ NULL); - LM_DBG("default group '%.*s' has been selected\n", - group->name_len, group->name); + LM_DBG("default group '%.*s' has been selected\n", group->name_len, + group->name); return 0; } @@ -1209,25 +1208,26 @@ int cfg_reset(cfg_group_t *group) */ int cfg_select_first(cfg_group_t *group) { - cfg_group_meta_t *meta; - cfg_group_inst_t *ginst; + cfg_group_meta_t *meta; + cfg_group_inst_t *ginst; - if (!cfg_local) { + if(!cfg_local) { LM_ERR("The child process has no local configuration\n"); return -1; } meta = CFG_GROUP_META(cfg_local, group); - if (!meta || (meta->num == 0)) + if(!meta || (meta->num == 0)) return -1; ginst = (cfg_group_inst_t *)meta->array; cfg_move_handle(group, - CFG_HANDLE_TO_GINST(*(group->handle)), /* the active group instance */ + CFG_HANDLE_TO_GINST( + *(group->handle)), /* the active group instance */ ginst); - LM_DBG("group instance '%.*s[%u]' has been selected\n", - group->name_len, group->name, ginst->id); + LM_DBG("group instance '%.*s[%u]' has been selected\n", group->name_len, + group->name, ginst->id); return 0; } @@ -1242,35 +1242,34 @@ int cfg_select_first(cfg_group_t *group) */ int cfg_select_next(cfg_group_t *group) { - cfg_group_meta_t *meta; - cfg_group_inst_t *old_ginst, *new_ginst; - int size; + cfg_group_meta_t *meta; + cfg_group_inst_t *old_ginst, *new_ginst; + int size; - if (!cfg_local) { + if(!cfg_local) { LM_ERR("The child process has no local configuration\n"); return -1; } meta = CFG_GROUP_META(cfg_local, group); - if (!(old_ginst = CFG_HANDLE_TO_GINST(*(group->handle)) - /* the active group instance */)) { + if(!(old_ginst = CFG_HANDLE_TO_GINST(*(group->handle)) + /* the active group instance */)) { LM_ERR("No group instance is set currently." - "Forgot to call cfg_select_first()?\n"); + "Forgot to call cfg_select_first()?\n"); return -1; } size = sizeof(cfg_group_inst_t) + group->size - 1; - if (((char *)old_ginst - (char *)meta->array)/size + 1 >= meta->num) + if(((char *)old_ginst - (char *)meta->array) / size + 1 >= meta->num) return -1; /* this is the last group instance */ new_ginst = (cfg_group_inst_t *)((char *)old_ginst + size); - cfg_move_handle(group, - old_ginst, /* the active group instance */ + cfg_move_handle(group, old_ginst, /* the active group instance */ new_ginst); - LM_DBG("group instance '%.*s[%u]' has been selected\n", - group->name_len, group->name, new_ginst->id); + LM_DBG("group instance '%.*s[%u]' has been selected\n", group->name_len, + group->name, new_ginst->id); return 0; } @@ -1292,19 +1291,16 @@ void cfg_main_set_local(void) */ void cfg_main_reset_local(void) { - cfg_group_t *group; + cfg_group_t *group; /* Unref the local config, and set it back to NULL. * Each child will set its own local configuration. */ - if (cfg_local) { + if(cfg_local) { CFG_UNREF(cfg_local); cfg_local = NULL; /* restore the original value of the module handles */ - for ( group = cfg_group; - group; - group = group->next - ) + for(group = cfg_group; group; group = group->next) *(group->handle) = group->orig_handle; /* The handle might have pointed to a group instance, * reset the instance counter. */ diff --git a/src/core/cfg/cfg_struct.h b/src/core/cfg/cfg_struct.h index 9f92261122f..a735c7169e4 100644 --- a/src/core/cfg/cfg_struct.h +++ b/src/core/cfg/cfg_struct.h @@ -31,93 +31,103 @@ #include "cfg.h" /*! \brief Maximum number of variables within a configuration group. */ -#define CFG_MAX_VAR_NUM 256 +#define CFG_MAX_VAR_NUM 256 /*! \brief indicates that the variable has been already shmized */ -#define cfg_var_shmized 1U +#define cfg_var_shmized 1U /*! \brief Structure for storing additional values of a variable. * When the config is shmzied, these variables are combined in * an array. */ #pragma pack(push, 1) -typedef struct _cfg_add_var { - struct _cfg_add_var *next; - unsigned int type; /*!< type == 0 is also valid, it indicates that the group +typedef struct _cfg_add_var +{ + struct _cfg_add_var *next; + unsigned int type; /*!< type == 0 is also valid, it indicates that the group must be created with the default values */ - unsigned int group_id; /*!< Id of the group instance */ - union { - char *ch; - str s; - int i; + unsigned int group_id; /*!< Id of the group instance */ + union + { + char *ch; + str s; + int i; } val; - int name_len; /*!< Name of the variable. The variable may not be known, + int name_len; /*!< Name of the variable. The variable may not be known, for example the additional group value is set in the script before the cfg group is declared. Hence, the pointer cannot be stored here. */ - char name[1]; + char name[1]; } cfg_add_var_t; #pragma pack(pop) /*! \brief structure used for variable - pointer mapping */ -typedef struct _cfg_mapping { - cfg_def_t *def; /*!< one item of the cfg structure definition */ - int name_len; /*!< length of def->name */ +typedef struct _cfg_mapping +{ + cfg_def_t *def; /*!< one item of the cfg structure definition */ + int name_len; /*!< length of def->name */ /* additional information about the cfg variable */ - int pos; /*!< position of the variable within the group starting from 0 */ - int offset; /*!< offest within the memory block */ - unsigned int flag; /*!< flag indicating the state of the variable */ + int pos; /*!< position of the variable within the group starting from 0 */ + int offset; /*!< offest within the memory block */ + unsigned int flag; /*!< flag indicating the state of the variable */ } cfg_mapping_t; /*! \brief type of the group */ -enum { CFG_GROUP_UNKNOWN = 0, CFG_GROUP_DYNAMIC, CFG_GROUP_STATIC }; +enum +{ + CFG_GROUP_UNKNOWN = 0, + CFG_GROUP_DYNAMIC, + CFG_GROUP_STATIC +}; /*! \brief linked list of registered groups */ #pragma pack(push, 1) -typedef struct _cfg_group { - cfg_mapping_t *mapping; /*!< describes the mapping betweeen +typedef struct _cfg_group +{ + cfg_mapping_t *mapping; /*!< describes the mapping betweeen the cfg variable definition and the memory block */ - char *vars; /*!< pointer to the memory block where the values + char *vars; /*!< pointer to the memory block where the values are stored -- used only before the config is shmized. */ - cfg_add_var_t *add_var; /*!< Additional instances of the variables. + cfg_add_var_t *add_var; /*!< Additional instances of the variables. This linked list is used only before the config is shmized. */ - int num; /*!< number of variables within the group */ - int size; /*!< size of the memory block that has to be + int num; /*!< number of variables within the group */ + int size; /*!< size of the memory block that has to be allocated to store the values */ - int meta_offset; /*!< offset of the group within the + int meta_offset; /*!< offset of the group within the shmized memory block for the meta_data */ - int var_offset; /*!< offset of the group within the + int var_offset; /*!< offset of the group within the shmized memory block for the variables */ - void **handle; /*!< per-process handle that can be used + void **handle; /*!< per-process handle that can be used by the modules to access the variables. It is registered when the group is created, and updated every time the block is replaced */ - void *orig_handle; /*!< Original value that the handle points to + void *orig_handle; /*!< Original value that the handle points to when the config group is registered. This is needed to temporary set the handle in the main process and restore it later to its original value. */ - struct _cfg_group *next; - unsigned int dynamic; /*!< indicates whether the variables within the group + struct _cfg_group *next; + unsigned int dynamic; /*!< indicates whether the variables within the group are dynamically allocated or not */ - int name_len; - char name[1]; + int name_len; + char name[1]; } cfg_group_t; #pragma pack(pop) /*! \brief One instance of the cfg group variables which stores * the additional values. These values can overwrite the default values. */ #pragma pack(push, 1) -typedef struct _cfg_group_inst { - unsigned int id; /*!< identifier of the group instance */ - unsigned int set[CFG_MAX_VAR_NUM/(sizeof(int)*8)]; - /*!< Bitmap indicating whether or not a value is explicitely set +typedef struct _cfg_group_inst +{ + unsigned int id; /*!< identifier of the group instance */ + unsigned int set[CFG_MAX_VAR_NUM / (sizeof(int) * 8)]; + /*!< Bitmap indicating whether or not a value is explicitely set within this instance. If the value is not set, then the default value is used, and copied into this instance. */ - unsigned char vars[1]; /*!< block for the values */ + unsigned char vars[1]; /*!< block for the values */ } cfg_group_inst_t; #pragma pack(pop) @@ -125,19 +135,22 @@ typedef struct _cfg_group_inst { * within the blob. This structure is used to handle the multivalue * instances of the variables, i.e. manages the array for the * additional values. */ -typedef struct _cfg_group_meta { - int num; /*!< Number of items in the array */ - cfg_group_inst_t *array; /*!< Array of cfg groups with num number of items */ +typedef struct _cfg_group_meta +{ + int num; /*!< Number of items in the array */ + cfg_group_inst_t + *array; /*!< Array of cfg groups with num number of items */ } cfg_group_meta_t; /*! \brief single memory block that contains all the cfg values */ #pragma pack(push, 1) -typedef struct _cfg_block { - atomic_t refcnt; /*!< reference counter, +typedef struct _cfg_block +{ + atomic_t refcnt; /*!< reference counter, the block is automatically deleted when it reaches 0 */ - int _pad; /*!< force 8 byte alignment */ - unsigned char vars[1]; /*!< blob that contains the values */ + int _pad; /*!< force 8 byte alignment */ + unsigned char vars[1]; /*!< blob that contains the values */ } cfg_block_t; #pragma pack(pop) @@ -147,45 +160,46 @@ typedef struct _cfg_block { * Items from the begginning of the list are deleted when the starter * pointer is moved, and no more child process uses them. */ -typedef struct _cfg_child_cb { - atomic_t refcnt; /*!< number of child processes +typedef struct _cfg_child_cb +{ + atomic_t refcnt; /*!< number of child processes referring to the element */ - atomic_t cb_count; /*!< This counter is used to track + atomic_t cb_count; /*!< This counter is used to track * how many times the callback needs * to be executed. * >0 the cb needs to be executed * <=0 the cb no longer needs to be executed */ - str gname, name; /*!< name of the variable that has changed */ - cfg_on_set_child cb; /*!< callback function that has to be called */ - void **replaced; /*!< set of strings and other memory segments + str gname, name; /*!< name of the variable that has changed */ + cfg_on_set_child cb; /*!< callback function that has to be called */ + void **replaced; /*!< set of strings and other memory segments that must be freed together with this structure. The content depends on the new config block. This makes sure that the replaced strings are freed after all the child processes release the old configuration. */ - struct _cfg_child_cb *next; + struct _cfg_child_cb *next; } cfg_child_cb_t; -extern cfg_group_t *cfg_group; -extern cfg_block_t **cfg_global; -extern cfg_block_t *cfg_local; -extern int cfg_block_size; -extern gen_lock_t *cfg_global_lock; -extern gen_lock_t *cfg_writer_lock; -extern int cfg_shmized; -extern cfg_child_cb_t **cfg_child_cb_first; -extern cfg_child_cb_t **cfg_child_cb_last; -extern cfg_child_cb_t *cfg_child_cb; -extern int cfg_ginst_count; +extern cfg_group_t *cfg_group; +extern cfg_block_t **cfg_global; +extern cfg_block_t *cfg_local; +extern int cfg_block_size; +extern gen_lock_t *cfg_global_lock; +extern gen_lock_t *cfg_writer_lock; +extern int cfg_shmized; +extern cfg_child_cb_t **cfg_child_cb_first; +extern cfg_child_cb_t **cfg_child_cb_last; +extern cfg_child_cb_t *cfg_child_cb; +extern int cfg_ginst_count; /* magic value for cfg_child_cb for processes that do not want to execute per-child callbacks */ -#define CFG_NO_CHILD_CBS ((void*)(long)(-1)) +#define CFG_NO_CHILD_CBS ((void *)(long)(-1)) /* macros for easier variable access */ -#define CFG_VAR_TYPE(var) CFG_VAR_MASK((var)->def->type) -#define CFG_INPUT_TYPE(var) CFG_INPUT_MASK((var)->def->type) +#define CFG_VAR_TYPE(var) CFG_VAR_MASK((var)->def->type) +#define CFG_INPUT_TYPE(var) CFG_INPUT_MASK((var)->def->type) /* get the meta-data of a group from the block */ #define CFG_GROUP_META(block, group) \ @@ -197,27 +211,32 @@ extern int cfg_ginst_count; /* Test whether a variable is explicitely set in the group instance, * or it uses the default value */ -#define CFG_VAR_TEST(group_inst, var) \ - bit_test((var)->pos % (sizeof(int)*8), (group_inst)->set + (var)->pos/(sizeof(int)*8)) +#define CFG_VAR_TEST(group_inst, var) \ + bit_test((var)->pos % (sizeof(int) * 8), \ + (group_inst)->set + (var)->pos / (sizeof(int) * 8)) /* Test whether a variable is explicitely set in the group instance, * or it uses the default value, and set the flag. */ -#define CFG_VAR_TEST_AND_SET(group_inst, var) \ - bit_test_and_set((var)->pos % (sizeof(int)*8), (group_inst)->set + (var)->pos/(sizeof(int)*8)) +#define CFG_VAR_TEST_AND_SET(group_inst, var) \ + bit_test_and_set((var)->pos % (sizeof(int) * 8), \ + (group_inst)->set + (var)->pos / (sizeof(int) * 8)) /* Test whether a variable is explicitely set in the group instance, * or it uses the default value, and reset the flag. */ -#define CFG_VAR_TEST_AND_RESET(group_inst, var) \ - bit_test_and_reset((var)->pos % (sizeof(int)*8), (group_inst)->set + (var)->pos/(sizeof(int)*8)) +#define CFG_VAR_TEST_AND_RESET(group_inst, var) \ + bit_test_and_reset((var)->pos % (sizeof(int) * 8), \ + (group_inst)->set + (var)->pos / (sizeof(int) * 8)) /* Return the group instance pointer from a handle, * or NULL if the handle points to the default configuration block */ -#define CFG_HANDLE_TO_GINST(h) \ - ( (((unsigned char*)(h) < cfg_local->vars) \ - || ((unsigned char*)(h) > cfg_local->vars + cfg_block_size) \ - ) ? \ - (cfg_group_inst_t*)((char*)(h) - (unsigned long)&((cfg_group_inst_t *)0)->vars) \ - : NULL ) +#define CFG_HANDLE_TO_GINST(h) \ + ((((unsigned char *)(h) < cfg_local->vars) \ + || ((unsigned char *)(h) > cfg_local->vars + cfg_block_size)) \ + ? (cfg_group_inst_t *)((char *)(h) \ + - (unsigned long)&( \ + (cfg_group_inst_t *)0) \ + ->vars) \ + : NULL) /* initiate the cfg framework */ int sr_cfg_init(void); @@ -265,13 +284,11 @@ int cfg_child_no_cb_init(void); void cfg_child_destroy(void); /* creates a new cfg group, and adds it to the linked list */ -cfg_group_t *cfg_new_group(char *name, int name_len, - int num, cfg_mapping_t *mapping, - char *vars, int size, void **handle); +cfg_group_t *cfg_new_group(char *name, int name_len, int num, + cfg_mapping_t *mapping, char *vars, int size, void **handle); /* Set the values of an existing cfg group. */ -void cfg_set_group(cfg_group_t *group, - int num, cfg_mapping_t *mapping, +void cfg_set_group(cfg_group_t *group, int num, cfg_mapping_t *mapping, char *vars, int size, void **handle); /* copy the variables to shm mem */ @@ -280,49 +297,48 @@ int cfg_shmize(void); /* free the memory of a child cb structure */ static inline void cfg_child_cb_free_item(cfg_child_cb_t *cb) { - int i; + int i; /* free the changed variables */ - if (cb->replaced) { - for (i=0; cb->replaced[i]; i++) + if(cb->replaced) { + for(i = 0; cb->replaced[i]; i++) shm_free(cb->replaced[i]); shm_free(cb->replaced); } shm_free(cb); } -#define cfg_block_free(block) \ - shm_free(block) +#define cfg_block_free(block) shm_free(block) /* Move the group handle to the specified group instance pointed by dst_ginst. * src_ginst shall point to the active group instance. - * Both parameters can be NULL meaning that the src/dst config is the default, + * Both parameters can be NULL meaning that the src/dst config is the default, * not an additional group instance. * The function executes all the per-child process callbacks which are different * in the two instances. */ -void cfg_move_handle(cfg_group_t *group, cfg_group_inst_t *src_ginst, cfg_group_inst_t *dst_ginst); +void cfg_move_handle(cfg_group_t *group, cfg_group_inst_t *src_ginst, + cfg_group_inst_t *dst_ginst); /* lock and unlock the global cfg block -- used only at the * very last step when the block is replaced */ -#define CFG_LOCK() lock_get(cfg_global_lock); -#define CFG_UNLOCK() lock_release(cfg_global_lock); +#define CFG_LOCK() lock_get(cfg_global_lock); +#define CFG_UNLOCK() lock_release(cfg_global_lock); /* lock and unlock used by the cfg drivers to make sure that * only one driver process is considering replacing the global * cfg block */ -#define CFG_WRITER_LOCK() lock_get(cfg_writer_lock); -#define CFG_WRITER_UNLOCK() lock_release(cfg_writer_lock); +#define CFG_WRITER_LOCK() lock_get(cfg_writer_lock); +#define CFG_WRITER_UNLOCK() lock_release(cfg_writer_lock); /* increase and decrease the reference counter of a block */ -#define CFG_REF(block) \ - atomic_inc(&(block)->refcnt) +#define CFG_REF(block) atomic_inc(&(block)->refcnt) -#define CFG_UNREF(block) \ - do { \ - if (atomic_dec_and_test(&(block)->refcnt)) \ - cfg_block_free(block); \ +#define CFG_UNREF(block) \ + do { \ + if(atomic_dec_and_test(&(block)->refcnt)) \ + cfg_block_free(block); \ } while(0) /* updates all the module handles and calls the @@ -333,11 +349,12 @@ void cfg_move_handle(cfg_group_t *group, cfg_group_inst_t *src_ginst, cfg_group_ */ static inline void cfg_update_local(int no_cbs) { - cfg_group_t *group; - cfg_child_cb_t *last_cb; - cfg_child_cb_t *prev_cb; + cfg_group_t *group; + cfg_child_cb_t *last_cb; + cfg_child_cb_t *prev_cb; - if (cfg_local) CFG_UNREF(cfg_local); + if(cfg_local) + CFG_UNREF(cfg_local); CFG_LOCK(); CFG_REF(*cfg_global); cfg_local = *cfg_global; @@ -352,26 +369,23 @@ static inline void cfg_update_local(int no_cbs) CFG_UNLOCK(); /* update the handles */ - for ( group = cfg_group; - group; - group = group->next - ) + for(group = cfg_group; group; group = group->next) *(group->handle) = CFG_GROUP_DATA(cfg_local, group); - if (unlikely(cfg_child_cb==CFG_NO_CHILD_CBS || no_cbs)) + if(unlikely(cfg_child_cb == CFG_NO_CHILD_CBS || no_cbs)) return; /* call the per-process callbacks */ - while (cfg_child_cb != last_cb) { + while(cfg_child_cb != last_cb) { prev_cb = cfg_child_cb; cfg_child_cb = cfg_child_cb->next; atomic_inc(&cfg_child_cb->refcnt); - if (atomic_dec_and_test(&prev_cb->refcnt)) { + if(atomic_dec_and_test(&prev_cb->refcnt)) { /* No more pocess refers to this callback. Did this process block the deletion, or is there any other process that has not reached prev_cb yet? */ CFG_LOCK(); - if (*cfg_child_cb_first == prev_cb) { + if(*cfg_child_cb_first == prev_cb) { /* yes, this process was blocking the deletion */ *cfg_child_cb_first = cfg_child_cb; CFG_UNLOCK(); @@ -380,8 +394,9 @@ static inline void cfg_update_local(int no_cbs) CFG_UNLOCK(); } } - if (cfg_child_cb->cb - && (atomic_add(&cfg_child_cb->cb_count, -1) >= 0) /* the new value is returned + if(cfg_child_cb->cb + && (atomic_add(&cfg_child_cb->cb_count, -1) + >= 0) /* the new value is returned by atomic_add() */ ) /* execute the callback */ @@ -393,67 +408,64 @@ static inline void cfg_update_local(int no_cbs) /* Reset all the group handles to the default, local configuration */ static inline void cfg_reset_handles(void) { - cfg_group_t *group; + cfg_group_t *group; - if (!cfg_local) + if(!cfg_local) return; - for ( group = cfg_group; - group && cfg_ginst_count; /* cfg_ginst_count is decreased every time + for(group = cfg_group; + group && cfg_ginst_count; /* cfg_ginst_count is decreased every time a group handle is reset. When it reaches 0, needless to continue the loop */ - group = group->next - ) { - if (((unsigned char*)*(group->handle) < cfg_local->vars) - || ((unsigned char*)*(group->handle) > cfg_local->vars + cfg_block_size) - ) - cfg_move_handle(group, - CFG_HANDLE_TO_GINST(*(group->handle)), - NULL); + group = group->next) { + if(((unsigned char *)*(group->handle) < cfg_local->vars) + || ((unsigned char *)*(group->handle) + > cfg_local->vars + cfg_block_size)) + cfg_move_handle(group, CFG_HANDLE_TO_GINST(*(group->handle)), NULL); } } /* sets the local cfg block to the active block - * + * * If your module forks a new process that implements * an infinite loop, put cfg_update() to the beginning of * the cycle to make sure, that subsequent function calls see the * up-to-date config set. */ -#define cfg_update() \ - do { \ - if (unlikely(cfg_ginst_count)) \ - cfg_reset_handles(); \ - if (unlikely(cfg_local != *cfg_global)) \ - cfg_update_local(0); \ +#define cfg_update() \ + do { \ + if(unlikely(cfg_ginst_count)) \ + cfg_reset_handles(); \ + if(unlikely(cfg_local != *cfg_global)) \ + cfg_update_local(0); \ } while(0) /* like cfg_update(), but does not execute callbacks * (it should be used sparingly only in special cases, since it * breaks an important cfg framework feature) */ -#define cfg_update_no_cbs() \ - do { \ - if (unlikely(cfg_local != *cfg_global)) \ - cfg_update_local(1); \ +#define cfg_update_no_cbs() \ + do { \ + if(unlikely(cfg_local != *cfg_global)) \ + cfg_update_local(1); \ } while(0) /* Reset all the group handles in the child process, * i.e. move them back to the default local configuration. */ -#define cfg_reset_all() \ - do { \ - if (unlikely(cfg_ginst_count)) \ - cfg_reset_handles(); \ +#define cfg_reset_all() \ + do { \ + if(unlikely(cfg_ginst_count)) \ + cfg_reset_handles(); \ } while(0) /* searches a group by name */ cfg_group_t *cfg_lookup_group(char *name, int len); - + /* searches a variable definition by group and variable name */ -int cfg_lookup_var(str *gname, str *vname, - cfg_group_t **group, cfg_mapping_t **var); +int cfg_lookup_var( + str *gname, str *vname, cfg_group_t **group, cfg_mapping_t **var); /* searches a variable definition within a group by its name */ cfg_mapping_t *cfg_lookup_var2(cfg_group_t *group, char *name, int len); @@ -469,21 +481,20 @@ cfg_group_inst_t *cfg_clone_array(cfg_group_meta_t *meta, cfg_group_t *group); /* Extend the array of configuration group instances with one more instance. * Only the ID of the new group is set, nothing else. */ cfg_group_inst_t *cfg_extend_array(cfg_group_meta_t *meta, cfg_group_t *group, - unsigned int group_id, - cfg_group_inst_t **new_group); + unsigned int group_id, cfg_group_inst_t **new_group); /* Remove an instance from a group array. * inst must point to an instance within meta->array. * *_new_array is set to the newly allocated array. */ int cfg_collapse_array(cfg_group_meta_t *meta, cfg_group_t *group, - cfg_group_inst_t *inst, - cfg_group_inst_t **_new_array); + cfg_group_inst_t *inst, cfg_group_inst_t **_new_array); /* clones a string to shared memory */ int cfg_clone_str(str *src, str *dst); /* Find the group instance within the meta-data based on the group_id */ -cfg_group_inst_t *cfg_find_group(cfg_group_meta_t *meta, int group_size, unsigned int group_id); +cfg_group_inst_t *cfg_find_group( + cfg_group_meta_t *meta, int group_size, unsigned int group_id); /* append new callbacks to the end of the child callback list * @@ -500,12 +511,11 @@ void cfg_install_child_cb(cfg_child_cb_t *cb_first, cfg_child_cb_t *cb_last); * callbacks. This list is added to the global linked list. */ void cfg_install_global(cfg_block_t *block, void **replaced, - cfg_child_cb_t *cb_first, cfg_child_cb_t *cb_last); + cfg_child_cb_t *cb_first, cfg_child_cb_t *cb_last); /* creates a structure for a per-child process callback */ -cfg_child_cb_t *cfg_child_cb_new(str *gname, str *name, - cfg_on_set_child cb, - unsigned int type); +cfg_child_cb_t *cfg_child_cb_new( + str *gname, str *name, cfg_on_set_child cb, unsigned int type); /* free the memory allocated for a child cb list */ void cfg_child_cb_free_list(cfg_child_cb_t *child_cb_first); @@ -517,7 +527,7 @@ void cfg_child_cb_free_list(cfg_child_cb_t *child_cb_first); * Note: this function is usable only before the configuration is shmized. */ int new_add_var(str *group_name, unsigned int group_id, str *var_name, - void *val, unsigned int type); + void *val, unsigned int type); /* Move the group handle to the specified group instance. */ int cfg_select(cfg_group_t *group, unsigned int id); From d1794f1d78bf6231c638152b28588d33565ceb70 Mon Sep 17 00:00:00 2001 From: Victor Seva Date: Thu, 18 May 2023 15:19:53 +0200 Subject: [PATCH 04/14] core: [crypto] clang-format for coherent indentation and coding style --- src/core/crypto/md5.c | 184 +++++----- src/core/crypto/md5.h | 37 +- src/core/crypto/md5utils.c | 33 +- src/core/crypto/md5utils.h | 12 +- src/core/crypto/rijndael.c | 467 ++++++++++++------------ src/core/crypto/rijndael.h | 42 ++- src/core/crypto/sha256.c | 724 ++++++++++++++++++------------------- src/core/crypto/sha256.h | 108 +++--- src/core/crypto/shautils.c | 6 +- 9 files changed, 797 insertions(+), 816 deletions(-) diff --git a/src/core/crypto/md5.c b/src/core/crypto/md5.c index 0c80a6a3eda..4ff542e700b 100644 --- a/src/core/crypto/md5.c +++ b/src/core/crypto/md5.c @@ -25,34 +25,36 @@ #ifndef __OS_solaris -#define PUT_64BIT_LE(cp, value) do { \ - (cp)[7] = (value) >> 56; \ - (cp)[6] = (value) >> 48; \ - (cp)[5] = (value) >> 40; \ - (cp)[4] = (value) >> 32; \ - (cp)[3] = (value) >> 24; \ - (cp)[2] = (value) >> 16; \ - (cp)[1] = (value) >> 8; \ - (cp)[0] = (value); } while (0) - -#define PUT_32BIT_LE(cp, value) do { \ - (cp)[3] = (value) >> 24; \ - (cp)[2] = (value) >> 16; \ - (cp)[1] = (value) >> 8; \ - (cp)[0] = (value); } while (0) - -static u_int8_t PADDING[MD5_BLOCK_LENGTH] = { - 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -}; +#define PUT_64BIT_LE(cp, value) \ + do { \ + (cp)[7] = (value) >> 56; \ + (cp)[6] = (value) >> 48; \ + (cp)[5] = (value) >> 40; \ + (cp)[4] = (value) >> 32; \ + (cp)[3] = (value) >> 24; \ + (cp)[2] = (value) >> 16; \ + (cp)[1] = (value) >> 8; \ + (cp)[0] = (value); \ + } while(0) + +#define PUT_32BIT_LE(cp, value) \ + do { \ + (cp)[3] = (value) >> 24; \ + (cp)[2] = (value) >> 16; \ + (cp)[1] = (value) >> 8; \ + (cp)[0] = (value); \ + } while(0) + +static u_int8_t PADDING[MD5_BLOCK_LENGTH] = {0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0}; /* * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious * initialization constants. */ -void -MD5Init(MD5_CTX *ctx) +void MD5Init(MD5_CTX *ctx) { ctx->count = 0; ctx->state[0] = 0x67452301; @@ -65,8 +67,7 @@ MD5Init(MD5_CTX *ctx) * Update context to reflect the concatenation of another buffer full * of bytes. */ -void -U_MD5Update(MD5_CTX *ctx, const unsigned char *input, size_t len) +void U_MD5Update(MD5_CTX *ctx, const unsigned char *input, size_t len) { size_t have, need; @@ -77,8 +78,8 @@ U_MD5Update(MD5_CTX *ctx, const unsigned char *input, size_t len) /* Update bitcount */ ctx->count += (u_int64_t)len << 3; - if (len >= need) { - if (have != 0) { + if(len >= need) { + if(have != 0) { memcpy(ctx->buffer + have, input, need); MD5Transform(ctx->state, ctx->buffer); input += need; @@ -87,7 +88,7 @@ U_MD5Update(MD5_CTX *ctx, const unsigned char *input, size_t len) } /* Process data in MD5_BLOCK_LENGTH-byte chunks. */ - while (len >= MD5_BLOCK_LENGTH) { + while(len >= MD5_BLOCK_LENGTH) { MD5Transform(ctx->state, input); input += MD5_BLOCK_LENGTH; len -= MD5_BLOCK_LENGTH; @@ -95,7 +96,7 @@ U_MD5Update(MD5_CTX *ctx, const unsigned char *input, size_t len) } /* Handle any remaining bytes of data. */ - if (len != 0) + if(len != 0) memcpy(ctx->buffer + have, input, len); } @@ -103,8 +104,7 @@ U_MD5Update(MD5_CTX *ctx, const unsigned char *input, size_t len) * Pad pad to 64-byte boundary with the bit pattern * 1 0* (64-bit count of bits processed, MSB-first) */ -void -MD5Pad(MD5_CTX *ctx) +void MD5Pad(MD5_CTX *ctx) { u_int8_t count[8]; size_t padlen; @@ -113,25 +113,23 @@ MD5Pad(MD5_CTX *ctx) PUT_64BIT_LE(count, ctx->count); /* Pad out to 56 mod 64. */ - padlen = MD5_BLOCK_LENGTH - - ((ctx->count >> 3) & (MD5_BLOCK_LENGTH - 1)); - if (padlen < 1 + 8) + padlen = MD5_BLOCK_LENGTH - ((ctx->count >> 3) & (MD5_BLOCK_LENGTH - 1)); + if(padlen < 1 + 8) padlen += MD5_BLOCK_LENGTH; - U_MD5Update(ctx, PADDING, padlen - 8); /* padlen - 8 <= 64 */ + U_MD5Update(ctx, PADDING, padlen - 8); /* padlen - 8 <= 64 */ U_MD5Update(ctx, count, 8); } /* * Final wrapup--call MD5Pad, fill in digest and zero out ctx. */ -void -U_MD5Final(unsigned char digest[MD5_DIGEST_LENGTH], MD5_CTX *ctx) +void U_MD5Final(unsigned char digest[MD5_DIGEST_LENGTH], MD5_CTX *ctx) { int i; MD5Pad(ctx); - if (digest != NULL) { - for (i = 0; i < 4; i++) + if(digest != NULL) { + for(i = 0; i < 4; i++) PUT_32BIT_LE(digest + i * 4, ctx->state[i]); memset(ctx, 0, sizeof(*ctx)); } @@ -148,27 +146,25 @@ U_MD5Final(unsigned char digest[MD5_DIGEST_LENGTH], MD5_CTX *ctx) /* This is the central step in the MD5 algorithm. */ #define MD5STEP(f, w, x, y, z, data, s) \ - ( w += f(x, y, z) + data, w = w<>(32-s), w += x ) + (w += f(x, y, z) + data, w = w << s | w >> (32 - s), w += x) /* * The core of the MD5 algorithm, this alters an existing MD5 hash to * reflect the addition of 16 longwords of new data. MD5Update blocks * the data and converts bytes into longwords for this routine. */ -void -MD5Transform(u_int32_t state[4], const u_int8_t block[MD5_BLOCK_LENGTH]) +void MD5Transform(u_int32_t state[4], const u_int8_t block[MD5_BLOCK_LENGTH]) { u_int32_t a, b, c, d, in[MD5_BLOCK_LENGTH / 4]; #ifndef __IS_BIG_ENDIAN memcpy(in, block, sizeof(in)); #else - for (a = 0; a < MD5_BLOCK_LENGTH / 4; a++) { - in[a] = (u_int32_t)( - (u_int32_t)(block[a * 4 + 0]) | - (u_int32_t)(block[a * 4 + 1]) << 8 | - (u_int32_t)(block[a * 4 + 2]) << 16 | - (u_int32_t)(block[a * 4 + 3]) << 24); + for(a = 0; a < MD5_BLOCK_LENGTH / 4; a++) { + in[a] = (u_int32_t)((u_int32_t)(block[a * 4 + 0]) + | (u_int32_t)(block[a * 4 + 1]) << 8 + | (u_int32_t)(block[a * 4 + 2]) << 16 + | (u_int32_t)(block[a * 4 + 3]) << 24); } #endif @@ -177,73 +173,73 @@ MD5Transform(u_int32_t state[4], const u_int8_t block[MD5_BLOCK_LENGTH]) c = state[2]; d = state[3]; - MD5STEP(F1, a, b, c, d, in[ 0] + 0xd76aa478, 7); - MD5STEP(F1, d, a, b, c, in[ 1] + 0xe8c7b756, 12); - MD5STEP(F1, c, d, a, b, in[ 2] + 0x242070db, 17); - MD5STEP(F1, b, c, d, a, in[ 3] + 0xc1bdceee, 22); - MD5STEP(F1, a, b, c, d, in[ 4] + 0xf57c0faf, 7); - MD5STEP(F1, d, a, b, c, in[ 5] + 0x4787c62a, 12); - MD5STEP(F1, c, d, a, b, in[ 6] + 0xa8304613, 17); - MD5STEP(F1, b, c, d, a, in[ 7] + 0xfd469501, 22); - MD5STEP(F1, a, b, c, d, in[ 8] + 0x698098d8, 7); - MD5STEP(F1, d, a, b, c, in[ 9] + 0x8b44f7af, 12); + MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7); + MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12); + MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17); + MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22); + MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7); + MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12); + MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17); + MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22); + MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7); + MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12); MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17); MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22); - MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); + MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7); MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12); MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17); MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22); - MD5STEP(F2, a, b, c, d, in[ 1] + 0xf61e2562, 5); - MD5STEP(F2, d, a, b, c, in[ 6] + 0xc040b340, 9); + MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5); + MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9); MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14); - MD5STEP(F2, b, c, d, a, in[ 0] + 0xe9b6c7aa, 20); - MD5STEP(F2, a, b, c, d, in[ 5] + 0xd62f105d, 5); - MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); + MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20); + MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5); + MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9); MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14); - MD5STEP(F2, b, c, d, a, in[ 4] + 0xe7d3fbc8, 20); - MD5STEP(F2, a, b, c, d, in[ 9] + 0x21e1cde6, 5); - MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); - MD5STEP(F2, c, d, a, b, in[ 3] + 0xf4d50d87, 14); - MD5STEP(F2, b, c, d, a, in[ 8] + 0x455a14ed, 20); - MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); - MD5STEP(F2, d, a, b, c, in[ 2] + 0xfcefa3f8, 9); - MD5STEP(F2, c, d, a, b, in[ 7] + 0x676f02d9, 14); + MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20); + MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5); + MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9); + MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14); + MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20); + MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5); + MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9); + MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14); MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20); - MD5STEP(F3, a, b, c, d, in[ 5] + 0xfffa3942, 4); - MD5STEP(F3, d, a, b, c, in[ 8] + 0x8771f681, 11); + MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4); + MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11); MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16); MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23); - MD5STEP(F3, a, b, c, d, in[ 1] + 0xa4beea44, 4); - MD5STEP(F3, d, a, b, c, in[ 4] + 0x4bdecfa9, 11); - MD5STEP(F3, c, d, a, b, in[ 7] + 0xf6bb4b60, 16); + MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4); + MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11); + MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16); MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23); - MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); - MD5STEP(F3, d, a, b, c, in[ 0] + 0xeaa127fa, 11); - MD5STEP(F3, c, d, a, b, in[ 3] + 0xd4ef3085, 16); - MD5STEP(F3, b, c, d, a, in[ 6] + 0x04881d05, 23); - MD5STEP(F3, a, b, c, d, in[ 9] + 0xd9d4d039, 4); + MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4); + MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11); + MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16); + MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23); + MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4); MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11); MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16); - MD5STEP(F3, b, c, d, a, in[2 ] + 0xc4ac5665, 23); + MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23); - MD5STEP(F4, a, b, c, d, in[ 0] + 0xf4292244, 6); - MD5STEP(F4, d, a, b, c, in[7 ] + 0x432aff97, 10); + MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6); + MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10); MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15); - MD5STEP(F4, b, c, d, a, in[5 ] + 0xfc93a039, 21); - MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); - MD5STEP(F4, d, a, b, c, in[3 ] + 0x8f0ccc92, 10); + MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21); + MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6); + MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10); MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15); - MD5STEP(F4, b, c, d, a, in[1 ] + 0x85845dd1, 21); - MD5STEP(F4, a, b, c, d, in[8 ] + 0x6fa87e4f, 6); + MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21); + MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6); MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10); - MD5STEP(F4, c, d, a, b, in[6 ] + 0xa3014314, 15); + MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15); MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21); - MD5STEP(F4, a, b, c, d, in[4 ] + 0xf7537e82, 6); + MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6); MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10); - MD5STEP(F4, c, d, a, b, in[2 ] + 0x2ad7d2bb, 15); - MD5STEP(F4, b, c, d, a, in[9 ] + 0xeb86d391, 21); + MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15); + MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21); state[0] += a; state[1] += b; diff --git a/src/core/crypto/md5.h b/src/core/crypto/md5.h index 02715b82fab..41f9b921d7d 100644 --- a/src/core/crypto/md5.h +++ b/src/core/crypto/md5.h @@ -17,40 +17,41 @@ #ifndef __OS_solaris -#define MD5_BLOCK_LENGTH 64 -#define MD5_DIGEST_LENGTH 16 -#define MD5_DIGEST_STRING_LENGTH (MD5_DIGEST_LENGTH * 2 + 1) +#define MD5_BLOCK_LENGTH 64 +#define MD5_DIGEST_LENGTH 16 +#define MD5_DIGEST_STRING_LENGTH (MD5_DIGEST_LENGTH * 2 + 1) /* Probably not the proper place, but will do for Debian: */ #include -typedef struct MD5Context { - u_int32_t state[4]; /* state */ - u_int64_t count; /* number of bits, mod 2^64 */ - unsigned char buffer[MD5_BLOCK_LENGTH]; /* input buffer */ +typedef struct MD5Context +{ + u_int32_t state[4]; /* state */ + u_int64_t count; /* number of bits, mod 2^64 */ + unsigned char buffer[MD5_BLOCK_LENGTH]; /* input buffer */ } MD5_CTX; -void MD5Init(MD5_CTX *); -void U_MD5Update(MD5_CTX *, const unsigned char *, size_t); -void MD5Pad(MD5_CTX *); -void U_MD5Final(unsigned char [MD5_DIGEST_LENGTH], MD5_CTX *); -void MD5Transform(u_int32_t [4], const unsigned char [MD5_BLOCK_LENGTH]); +void MD5Init(MD5_CTX *); +void U_MD5Update(MD5_CTX *, const unsigned char *, size_t); +void MD5Pad(MD5_CTX *); +void U_MD5Final(unsigned char[MD5_DIGEST_LENGTH], MD5_CTX *); +void MD5Transform(u_int32_t[4], const unsigned char[MD5_BLOCK_LENGTH]); -static inline void MD5Update(MD5_CTX *ctx, const char *str, size_t len) { +static inline void MD5Update(MD5_CTX *ctx, const char *str, size_t len) +{ U_MD5Update(ctx, (const unsigned char *)str, len); } -static inline void MD5Final(char buf[MD5_DIGEST_LENGTH], MD5_CTX *ctx) { +static inline void MD5Final(char buf[MD5_DIGEST_LENGTH], MD5_CTX *ctx) +{ U_MD5Final((unsigned char *)buf, ctx); } #else /* __OS_solaris */ #include -#define U_MD5Update(ctx, input, len) \ - MD5Update(ctx, input, len) -#define U_MD5Final(digest, ctx) \ - MD5Final(digest, ctx) +#define U_MD5Update(ctx, input, len) MD5Update(ctx, input, len) +#define U_MD5Final(digest, ctx) MD5Final(digest, ctx) #endif /* __OS_solaris */ diff --git a/src/core/crypto/md5utils.c b/src/core/crypto/md5utils.c index b80c4a4e5bb..093f742f29f 100644 --- a/src/core/crypto/md5utils.c +++ b/src/core/crypto/md5utils.c @@ -1,22 +1,22 @@ /* * Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All * rights reserved. - * + * * License to copy and use this software is granted provided that it * is identified as the "RSA Data Security, Inc. MD5 Message-Digest * Algorithm" in all material mentioning or referencing this software * or this function. - * + * * License is also granted to make and use derivative works provided * that such works are identified as "derived from the RSA Data * Security, Inc. MD5 Message-Digest Algorithm" in all material * mentioning or referencing the derived work. - * + * * RSA Data Security, Inc. makes no representations concerning either * the merchantability of this software or the suitability of this * software for any particular purpose. It is provided "as is" * without express or implied warranty of any kind. - * + * * These notices must be retained in any copies of any part of this * documentation and/or software. */ @@ -39,7 +39,7 @@ /*! * \brief Calculate a MD5 digests over a string array - * + * * Calculate a MD5 digests over a string array and stores the result in the * destination char array. This function assumes 32 bytes in the destination * buffer. @@ -47,23 +47,22 @@ * \param src string input array * \param size elements in the input array */ -void MD5StringArray (char *dst, str src[], int size) +void MD5StringArray(char *dst, str src[], int size) { MD5_CTX context; unsigned char digest[16]; - int i; + int i; int len; char *s; - MD5Init (&context); - for (i=0; i 0) - MD5Update (&context, s, len); - } - U_MD5Final (digest, &context); - - string2hex(digest, 16, dst ); - LM_DBG("MD5 calculated: %.*s\n", MD5_LEN, dst ); + MD5Init(&context); + for(i = 0; i < size; i++) { + trim_len(len, s, src[i]); + if(len > 0) + MD5Update(&context, s, len); + } + U_MD5Final(digest, &context); + string2hex(digest, 16, dst); + LM_DBG("MD5 calculated: %.*s\n", MD5_LEN, dst); } diff --git a/src/core/crypto/md5utils.h b/src/core/crypto/md5utils.h index 2448a49eb5c..02ecfafe647 100644 --- a/src/core/crypto/md5utils.h +++ b/src/core/crypto/md5utils.h @@ -1,4 +1,4 @@ -/* +/* * Copyright (C) 2001-2003 FhG Fokus * * This file is part of Kamailio, a free SIP server. @@ -13,8 +13,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ @@ -30,11 +30,11 @@ #include "../str.h" -#define MD5_LEN 32 +#define MD5_LEN 32 /*! * \brief Calculate a MD5 digests over a string array - * + * * Calculate a MD5 digests over a string array and stores the result in the * destination char array. This function assumes 32 bytes in the destination * buffer. @@ -42,6 +42,6 @@ * \param src string input array * \param size elements in the input array */ -void MD5StringArray (char *dst, str src[], int size); +void MD5StringArray(char *dst, str src[], int size); #endif /* _MD5UTILS_H */ diff --git a/src/core/crypto/rijndael.c b/src/core/crypto/rijndael.c index 16b2493887b..e5aa57000bf 100644 --- a/src/core/crypto/rijndael.c +++ b/src/core/crypto/rijndael.c @@ -54,21 +54,21 @@ static void gen_tabs(void); /* Circular rotate of 32 bit values */ -#define rotr(x,n) (((x) >> ((int)(n))) | ((x) << (32 - (int)(n)))) -#define rotl(x,n) (((x) << ((int)(n))) | ((x) >> (32 - (int)(n)))) +#define rotr(x, n) (((x) >> ((int)(n))) | ((x) << (32 - (int)(n)))) +#define rotl(x, n) (((x) << ((int)(n))) | ((x) >> (32 - (int)(n)))) /* Invert byte order in a 32 bit variable */ -#define bswap(x) ((rotl((x), 8) & 0x00ff00ff) | (rotr((x), 8) & 0xff00ff00)) +#define bswap(x) ((rotl((x), 8) & 0x00ff00ff) | (rotr((x), 8) & 0xff00ff00)) /* Extract byte from a 32 bit quantity (little endian notation) */ -#define byte(x,n) ((u1byte)((x) >> (8 * (n)))) +#define byte(x, n) ((u1byte)((x) >> (8 * (n)))) #ifdef WORDS_BIGENDIAN -#define io_swap(x) bswap(x) +#define io_swap(x) bswap(x) #else -#define io_swap(x) (x) +#define io_swap(x) (x) #endif #ifdef PRINT_TABS @@ -78,8 +78,8 @@ static void gen_tabs(void); #ifdef PRE_CALC_TABLES #include "rijndael.tbl" -#define tab_gen 1 -#else /* !PRE_CALC_TABLES */ +#define tab_gen 1 +#else /* !PRE_CALC_TABLES */ static u1byte pow_tab[256]; static u1byte log_tab[256]; @@ -89,85 +89,81 @@ static u4byte rco_tab[10]; static u4byte ft_tab[4][256]; static u4byte it_tab[4][256]; -#ifdef LARGE_TABLES +#ifdef LARGE_TABLES static u4byte fl_tab[4][256]; static u4byte il_tab[4][256]; #endif static u4byte tab_gen = 0; -#endif /* !PRE_CALC_TABLES */ +#endif /* !PRE_CALC_TABLES */ -#define ff_mult(a,b) ((a) && (b) ? pow_tab[(log_tab[a] + log_tab[b]) % 255] : 0) +#define ff_mult(a, b) \ + ((a) && (b) ? pow_tab[(log_tab[a] + log_tab[b]) % 255] : 0) -#define f_rn(bo, bi, n, k) \ - (bo)[n] = ft_tab[0][byte((bi)[n],0)] ^ \ - ft_tab[1][byte((bi)[((n) + 1) & 3],1)] ^ \ - ft_tab[2][byte((bi)[((n) + 2) & 3],2)] ^ \ - ft_tab[3][byte((bi)[((n) + 3) & 3],3)] ^ *((k) + (n)) +#define f_rn(bo, bi, n, k) \ + (bo)[n] = ft_tab[0][byte((bi)[n], 0)] \ + ^ ft_tab[1][byte((bi)[((n) + 1) & 3], 1)] \ + ^ ft_tab[2][byte((bi)[((n) + 2) & 3], 2)] \ + ^ ft_tab[3][byte((bi)[((n) + 3) & 3], 3)] ^ *((k) + (n)) -#define i_rn(bo, bi, n, k) \ - (bo)[n] = it_tab[0][byte((bi)[n],0)] ^ \ - it_tab[1][byte((bi)[((n) + 3) & 3],1)] ^ \ - it_tab[2][byte((bi)[((n) + 2) & 3],2)] ^ \ - it_tab[3][byte((bi)[((n) + 1) & 3],3)] ^ *((k) + (n)) +#define i_rn(bo, bi, n, k) \ + (bo)[n] = it_tab[0][byte((bi)[n], 0)] \ + ^ it_tab[1][byte((bi)[((n) + 3) & 3], 1)] \ + ^ it_tab[2][byte((bi)[((n) + 2) & 3], 2)] \ + ^ it_tab[3][byte((bi)[((n) + 1) & 3], 3)] ^ *((k) + (n)) #ifdef LARGE_TABLES -#define ls_box(x) \ - ( fl_tab[0][byte(x, 0)] ^ \ - fl_tab[1][byte(x, 1)] ^ \ - fl_tab[2][byte(x, 2)] ^ \ - fl_tab[3][byte(x, 3)] ) - -#define f_rl(bo, bi, n, k) \ - (bo)[n] = fl_tab[0][byte((bi)[n],0)] ^ \ - fl_tab[1][byte((bi)[((n) + 1) & 3],1)] ^ \ - fl_tab[2][byte((bi)[((n) + 2) & 3],2)] ^ \ - fl_tab[3][byte((bi)[((n) + 3) & 3],3)] ^ *((k) + (n)) - -#define i_rl(bo, bi, n, k) \ - (bo)[n] = il_tab[0][byte((bi)[n],0)] ^ \ - il_tab[1][byte((bi)[((n) + 3) & 3],1)] ^ \ - il_tab[2][byte((bi)[((n) + 2) & 3],2)] ^ \ - il_tab[3][byte((bi)[((n) + 1) & 3],3)] ^ *((k) + (n)) +#define ls_box(x) \ + (fl_tab[0][byte(x, 0)] ^ fl_tab[1][byte(x, 1)] ^ fl_tab[2][byte(x, 2)] \ + ^ fl_tab[3][byte(x, 3)]) + +#define f_rl(bo, bi, n, k) \ + (bo)[n] = fl_tab[0][byte((bi)[n], 0)] \ + ^ fl_tab[1][byte((bi)[((n) + 1) & 3], 1)] \ + ^ fl_tab[2][byte((bi)[((n) + 2) & 3], 2)] \ + ^ fl_tab[3][byte((bi)[((n) + 3) & 3], 3)] ^ *((k) + (n)) + +#define i_rl(bo, bi, n, k) \ + (bo)[n] = il_tab[0][byte((bi)[n], 0)] \ + ^ il_tab[1][byte((bi)[((n) + 3) & 3], 1)] \ + ^ il_tab[2][byte((bi)[((n) + 2) & 3], 2)] \ + ^ il_tab[3][byte((bi)[((n) + 1) & 3], 3)] ^ *((k) + (n)) #else -#define ls_box(x) \ - ((u4byte)sbx_tab[byte(x, 0)] << 0) ^ \ - ((u4byte)sbx_tab[byte(x, 1)] << 8) ^ \ - ((u4byte)sbx_tab[byte(x, 2)] << 16) ^ \ - ((u4byte)sbx_tab[byte(x, 3)] << 24) - -#define f_rl(bo, bi, n, k) \ - (bo)[n] = (u4byte)sbx_tab[byte((bi)[n],0)] ^ \ - rotl(((u4byte)sbx_tab[byte((bi)[((n) + 1) & 3],1)]), 8) ^ \ - rotl(((u4byte)sbx_tab[byte((bi)[((n) + 2) & 3],2)]), 16) ^ \ - rotl(((u4byte)sbx_tab[byte((bi)[((n) + 3) & 3],3)]), 24) ^ *((k) + (n)) - -#define i_rl(bo, bi, n, k) \ - (bo)[n] = (u4byte)isb_tab[byte((bi)[n],0)] ^ \ - rotl(((u4byte)isb_tab[byte((bi)[((n) + 3) & 3],1)]), 8) ^ \ - rotl(((u4byte)isb_tab[byte((bi)[((n) + 2) & 3],2)]), 16) ^ \ - rotl(((u4byte)isb_tab[byte((bi)[((n) + 1) & 3],3)]), 24) ^ *((k) + (n)) +#define ls_box(x) \ + ((u4byte)sbx_tab[byte(x, 0)] << 0) ^ ((u4byte)sbx_tab[byte(x, 1)] << 8) \ + ^ ((u4byte)sbx_tab[byte(x, 2)] << 16) \ + ^ ((u4byte)sbx_tab[byte(x, 3)] << 24) + +#define f_rl(bo, bi, n, k) \ + (bo)[n] = (u4byte)sbx_tab[byte((bi)[n], 0)] \ + ^ rotl(((u4byte)sbx_tab[byte((bi)[((n) + 1) & 3], 1)]), 8) \ + ^ rotl(((u4byte)sbx_tab[byte((bi)[((n) + 2) & 3], 2)]), 16) \ + ^ rotl(((u4byte)sbx_tab[byte((bi)[((n) + 3) & 3], 3)]), 24) \ + ^ *((k) + (n)) + +#define i_rl(bo, bi, n, k) \ + (bo)[n] = (u4byte)isb_tab[byte((bi)[n], 0)] \ + ^ rotl(((u4byte)isb_tab[byte((bi)[((n) + 3) & 3], 1)]), 8) \ + ^ rotl(((u4byte)isb_tab[byte((bi)[((n) + 2) & 3], 2)]), 16) \ + ^ rotl(((u4byte)isb_tab[byte((bi)[((n) + 1) & 3], 3)]), 24) \ + ^ *((k) + (n)) #endif -static void -gen_tabs(void) +static void gen_tabs(void) { #ifndef PRE_CALC_TABLES - u4byte i, - t; - u1byte p, - q; + u4byte i, t; + u1byte p, q; /* log and power tables for GF(2**8) finite field with */ /* 0x11b as modular polynomial - the simplest primitive */ /* root is 0x11, used here to generate the tables */ - for (i = 0, p = 1; i < 256; ++i) - { - pow_tab[i] = (u1byte) p; - log_tab[p] = (u1byte) i; + for(i = 0, p = 1; i < 256; ++i) { + pow_tab[i] = (u1byte)p; + log_tab[p] = (u1byte)i; p = p ^ (p << 1) ^ (p & 0x80 ? 0x01b : 0); } @@ -175,8 +171,7 @@ gen_tabs(void) log_tab[1] = 0; p = 1; - for (i = 0; i < 10; ++i) - { + for(i = 0; i < 10; ++i) { rco_tab[i] = p; p = (p << 1) ^ (p & 0x80 ? 0x1b : 0); @@ -188,8 +183,7 @@ gen_tabs(void) /* of the specification the bits are numbered from the */ /* least significant end of a byte. */ - for (i = 0; i < 256; ++i) - { + for(i = 0; i < 256; ++i) { p = (i ? pow_tab[255 - log_tab[i]] : 0); q = p; q = (q >> 7) | (q << 1); @@ -200,15 +194,14 @@ gen_tabs(void) p ^= q; q = (q >> 7) | (q << 1); p ^= q ^ 0x63; - sbx_tab[i] = (u1byte) p; - isb_tab[p] = (u1byte) i; + sbx_tab[i] = (u1byte)p; + isb_tab[p] = (u1byte)i; } - for (i = 0; i < 256; ++i) - { + for(i = 0; i < 256; ++i) { p = sbx_tab[i]; -#ifdef LARGE_TABLES +#ifdef LARGE_TABLES t = p; fl_tab[0][i] = t; @@ -216,10 +209,8 @@ gen_tabs(void) fl_tab[2][i] = rotl(t, 16); fl_tab[3][i] = rotl(t, 24); #endif - t = ((u4byte) ff_mult(2, p)) | - ((u4byte) p << 8) | - ((u4byte) p << 16) | - ((u4byte) ff_mult(3, p) << 24); + t = ((u4byte)ff_mult(2, p)) | ((u4byte)p << 8) | ((u4byte)p << 16) + | ((u4byte)ff_mult(3, p) << 24); ft_tab[0][i] = t; ft_tab[1][i] = rotl(t, 8); @@ -228,7 +219,7 @@ gen_tabs(void) p = isb_tab[i]; -#ifdef LARGE_TABLES +#ifdef LARGE_TABLES t = p; il_tab[0][i] = t; @@ -236,10 +227,8 @@ gen_tabs(void) il_tab[2][i] = rotl(t, 16); il_tab[3][i] = rotl(t, 24); #endif - t = ((u4byte) ff_mult(14, p)) | - ((u4byte) ff_mult(9, p) << 8) | - ((u4byte) ff_mult(13, p) << 16) | - ((u4byte) ff_mult(11, p) << 24); + t = ((u4byte)ff_mult(14, p)) | ((u4byte)ff_mult(9, p) << 8) + | ((u4byte)ff_mult(13, p) << 16) | ((u4byte)ff_mult(11, p) << 24); it_tab[0][i] = t; it_tab[1][i] = rotl(t, 8); @@ -248,72 +237,85 @@ gen_tabs(void) } tab_gen = 1; -#endif /* !PRE_CALC_TABLES */ +#endif /* !PRE_CALC_TABLES */ } -#define star_x(x) (((x) & 0x7f7f7f7f) << 1) ^ ((((x) & 0x80808080) >> 7) * 0x1b) +#define star_x(x) (((x)&0x7f7f7f7f) << 1) ^ ((((x)&0x80808080) >> 7) * 0x1b) -#define imix_col(y,x) \ -do { \ - u = star_x(x); \ - v = star_x(u); \ - w = star_x(v); \ - t = w ^ (x); \ - (y) = u ^ v ^ w; \ - (y) ^= rotr(u ^ t, 8) ^ \ - rotr(v ^ t, 16) ^ \ - rotr(t,24); \ -} while (0) +#define imix_col(y, x) \ + do { \ + u = star_x(x); \ + v = star_x(u); \ + w = star_x(v); \ + t = w ^ (x); \ + (y) = u ^ v ^ w; \ + (y) ^= rotr(u ^ t, 8) ^ rotr(v ^ t, 16) ^ rotr(t, 24); \ + } while(0) /* initialise the key schedule from the user supplied key */ -#define loop4(i) \ -do { t = ls_box(rotr(t, 8)) ^ rco_tab[i]; \ - t ^= e_key[4 * i]; e_key[4 * i + 4] = t; \ - t ^= e_key[4 * i + 1]; e_key[4 * i + 5] = t; \ - t ^= e_key[4 * i + 2]; e_key[4 * i + 6] = t; \ - t ^= e_key[4 * i + 3]; e_key[4 * i + 7] = t; \ -} while (0) - -#define loop6(i) \ -do { t = ls_box(rotr(t, 8)) ^ rco_tab[i]; \ - t ^= e_key[6 * (i)]; e_key[6 * (i) + 6] = t; \ - t ^= e_key[6 * (i) + 1]; e_key[6 * (i) + 7] = t; \ - t ^= e_key[6 * (i) + 2]; e_key[6 * (i) + 8] = t; \ - t ^= e_key[6 * (i) + 3]; e_key[6 * (i) + 9] = t; \ - t ^= e_key[6 * (i) + 4]; e_key[6 * (i) + 10] = t; \ - t ^= e_key[6 * (i) + 5]; e_key[6 * (i) + 11] = t; \ -} while (0) - -#define loop8(i) \ -do { t = ls_box(rotr(t, 8)) ^ rco_tab[i]; \ - t ^= e_key[8 * (i)]; e_key[8 * (i) + 8] = t; \ - t ^= e_key[8 * (i) + 1]; e_key[8 * (i) + 9] = t; \ - t ^= e_key[8 * (i) + 2]; e_key[8 * (i) + 10] = t; \ - t ^= e_key[8 * (i) + 3]; e_key[8 * (i) + 11] = t; \ - t = e_key[8 * (i) + 4] ^ ls_box(t); \ - e_key[8 * (i) + 12] = t; \ - t ^= e_key[8 * (i) + 5]; e_key[8 * (i) + 13] = t; \ - t ^= e_key[8 * (i) + 6]; e_key[8 * (i) + 14] = t; \ - t ^= e_key[8 * (i) + 7]; e_key[8 * (i) + 15] = t; \ -} while (0) - -rijndael_ctx * -rijndael_set_key(rijndael_ctx *ctx, const u4byte *in_key, const u4byte key_len, - int encrypt) +#define loop4(i) \ + do { \ + t = ls_box(rotr(t, 8)) ^ rco_tab[i]; \ + t ^= e_key[4 * i]; \ + e_key[4 * i + 4] = t; \ + t ^= e_key[4 * i + 1]; \ + e_key[4 * i + 5] = t; \ + t ^= e_key[4 * i + 2]; \ + e_key[4 * i + 6] = t; \ + t ^= e_key[4 * i + 3]; \ + e_key[4 * i + 7] = t; \ + } while(0) + +#define loop6(i) \ + do { \ + t = ls_box(rotr(t, 8)) ^ rco_tab[i]; \ + t ^= e_key[6 * (i)]; \ + e_key[6 * (i) + 6] = t; \ + t ^= e_key[6 * (i) + 1]; \ + e_key[6 * (i) + 7] = t; \ + t ^= e_key[6 * (i) + 2]; \ + e_key[6 * (i) + 8] = t; \ + t ^= e_key[6 * (i) + 3]; \ + e_key[6 * (i) + 9] = t; \ + t ^= e_key[6 * (i) + 4]; \ + e_key[6 * (i) + 10] = t; \ + t ^= e_key[6 * (i) + 5]; \ + e_key[6 * (i) + 11] = t; \ + } while(0) + +#define loop8(i) \ + do { \ + t = ls_box(rotr(t, 8)) ^ rco_tab[i]; \ + t ^= e_key[8 * (i)]; \ + e_key[8 * (i) + 8] = t; \ + t ^= e_key[8 * (i) + 1]; \ + e_key[8 * (i) + 9] = t; \ + t ^= e_key[8 * (i) + 2]; \ + e_key[8 * (i) + 10] = t; \ + t ^= e_key[8 * (i) + 3]; \ + e_key[8 * (i) + 11] = t; \ + t = e_key[8 * (i) + 4] ^ ls_box(t); \ + e_key[8 * (i) + 12] = t; \ + t ^= e_key[8 * (i) + 5]; \ + e_key[8 * (i) + 13] = t; \ + t ^= e_key[8 * (i) + 6]; \ + e_key[8 * (i) + 14] = t; \ + t ^= e_key[8 * (i) + 7]; \ + e_key[8 * (i) + 15] = t; \ + } while(0) + +rijndael_ctx *rijndael_set_key(rijndael_ctx *ctx, const u4byte *in_key, + const u4byte key_len, int encrypt) { - u4byte i, - t, - u, - v, - w; - u4byte *e_key = ctx->e_key; - u4byte *d_key = ctx->d_key; + u4byte i, t, u, v, w; + u4byte *e_key = ctx->e_key; + u4byte *d_key = ctx->d_key; ctx->decrypt = !encrypt; - if (!tab_gen) + if(!tab_gen) gen_tabs(); ctx->k_len = (key_len + 31) / 32; @@ -323,18 +325,17 @@ rijndael_set_key(rijndael_ctx *ctx, const u4byte *in_key, const u4byte key_len, e_key[2] = io_swap(in_key[2]); e_key[3] = io_swap(in_key[3]); - switch (ctx->k_len) - { + switch(ctx->k_len) { case 4: t = e_key[3]; - for (i = 0; i < 10; ++i) + for(i = 0; i < 10; ++i) loop4(i); break; case 6: e_key[4] = io_swap(in_key[4]); t = e_key[5] = io_swap(in_key[5]); - for (i = 0; i < 8; ++i) + for(i = 0; i < 8; ++i) loop6(i); break; @@ -343,19 +344,18 @@ rijndael_set_key(rijndael_ctx *ctx, const u4byte *in_key, const u4byte key_len, e_key[5] = io_swap(in_key[5]); e_key[6] = io_swap(in_key[6]); t = e_key[7] = io_swap(in_key[7]); - for (i = 0; i < 7; ++i) + for(i = 0; i < 7; ++i) loop8(i); break; } - if (!encrypt) - { + if(!encrypt) { d_key[0] = e_key[0]; d_key[1] = e_key[1]; d_key[2] = e_key[2]; d_key[3] = e_key[3]; - for (i = 4; i < 4 * ctx->k_len + 24; ++i) + for(i = 4; i < 4 * ctx->k_len + 24; ++i) imix_col(d_key[i], e_key[i]); } @@ -365,30 +365,27 @@ rijndael_set_key(rijndael_ctx *ctx, const u4byte *in_key, const u4byte key_len, /* encrypt a block of text */ #define f_nround(bo, bi, k) \ -do { \ - f_rn(bo, bi, 0, k); \ - f_rn(bo, bi, 1, k); \ - f_rn(bo, bi, 2, k); \ - f_rn(bo, bi, 3, k); \ - k += 4; \ -} while (0) + do { \ + f_rn(bo, bi, 0, k); \ + f_rn(bo, bi, 1, k); \ + f_rn(bo, bi, 2, k); \ + f_rn(bo, bi, 3, k); \ + k += 4; \ + } while(0) #define f_lround(bo, bi, k) \ -do { \ - f_rl(bo, bi, 0, k); \ - f_rl(bo, bi, 1, k); \ - f_rl(bo, bi, 2, k); \ - f_rl(bo, bi, 3, k); \ -} while (0) - -void -rijndael_encrypt(rijndael_ctx *ctx, const u4byte *in_blk, u4byte *out_blk) + do { \ + f_rl(bo, bi, 0, k); \ + f_rl(bo, bi, 1, k); \ + f_rl(bo, bi, 2, k); \ + f_rl(bo, bi, 3, k); \ + } while(0) + +void rijndael_encrypt(rijndael_ctx *ctx, const u4byte *in_blk, u4byte *out_blk) { - u4byte k_len = ctx->k_len; - u4byte *e_key = ctx->e_key; - u4byte b0[4], - b1[4], - *kp; + u4byte k_len = ctx->k_len; + u4byte *e_key = ctx->e_key; + u4byte b0[4], b1[4], *kp; b0[0] = io_swap(in_blk[0]) ^ e_key[0]; b0[1] = io_swap(in_blk[1]) ^ e_key[1]; @@ -397,14 +394,12 @@ rijndael_encrypt(rijndael_ctx *ctx, const u4byte *in_blk, u4byte *out_blk) kp = e_key + 4; - if (k_len > 6) - { + if(k_len > 6) { f_nround(b1, b0, kp); f_nround(b0, b1, kp); } - if (k_len > 4) - { + if(k_len > 4) { f_nround(b1, b0, kp); f_nround(b0, b1, kp); } @@ -429,31 +424,28 @@ rijndael_encrypt(rijndael_ctx *ctx, const u4byte *in_blk, u4byte *out_blk) /* decrypt a block of text */ #define i_nround(bo, bi, k) \ -do { \ - i_rn(bo, bi, 0, k); \ - i_rn(bo, bi, 1, k); \ - i_rn(bo, bi, 2, k); \ - i_rn(bo, bi, 3, k); \ - k -= 4; \ -} while (0) + do { \ + i_rn(bo, bi, 0, k); \ + i_rn(bo, bi, 1, k); \ + i_rn(bo, bi, 2, k); \ + i_rn(bo, bi, 3, k); \ + k -= 4; \ + } while(0) #define i_lround(bo, bi, k) \ -do { \ - i_rl(bo, bi, 0, k); \ - i_rl(bo, bi, 1, k); \ - i_rl(bo, bi, 2, k); \ - i_rl(bo, bi, 3, k); \ -} while (0) - -void -rijndael_decrypt(rijndael_ctx *ctx, const u4byte *in_blk, u4byte *out_blk) + do { \ + i_rl(bo, bi, 0, k); \ + i_rl(bo, bi, 1, k); \ + i_rl(bo, bi, 2, k); \ + i_rl(bo, bi, 3, k); \ + } while(0) + +void rijndael_decrypt(rijndael_ctx *ctx, const u4byte *in_blk, u4byte *out_blk) { - u4byte b0[4], - b1[4], - *kp; - u4byte k_len = ctx->k_len; - u4byte *e_key = ctx->e_key; - u4byte *d_key = ctx->d_key; + u4byte b0[4], b1[4], *kp; + u4byte k_len = ctx->k_len; + u4byte *e_key = ctx->e_key; + u4byte *d_key = ctx->d_key; b0[0] = io_swap(in_blk[0]) ^ e_key[4 * k_len + 24]; b0[1] = io_swap(in_blk[1]) ^ e_key[4 * k_len + 25]; @@ -462,14 +454,12 @@ rijndael_decrypt(rijndael_ctx *ctx, const u4byte *in_blk, u4byte *out_blk) kp = d_key + 4 * (k_len + 5); - if (k_len > 6) - { + if(k_len > 6) { i_nround(b1, b0, kp); i_nround(b0, b1, kp); } - if (k_len > 4) - { + if(k_len > 4) { i_nround(b1, b0, kp); i_nround(b0, b1, kp); } @@ -498,24 +488,22 @@ rijndael_decrypt(rijndael_ctx *ctx, const u4byte *in_blk, u4byte *out_blk) * should be true for PX. -marko */ -void -aes_set_key(rijndael_ctx *ctx, const u_int8_t *key, unsigned keybits, int enc) +void aes_set_key( + rijndael_ctx *ctx, const u_int8_t *key, unsigned keybits, int enc) { - u_int32_t *k; + u_int32_t *k; - k = (u_int32_t *) key; + k = (u_int32_t *)key; rijndael_set_key(ctx, k, keybits, enc); } -void -aes_ecb_encrypt(rijndael_ctx *ctx, u_int8_t *data, unsigned len) +void aes_ecb_encrypt(rijndael_ctx *ctx, u_int8_t *data, unsigned len) { - unsigned bs = 16; - u_int32_t *d; + unsigned bs = 16; + u_int32_t *d; - while (len >= bs) - { - d = (u_int32_t *) data; + while(len >= bs) { + d = (u_int32_t *)data; rijndael_encrypt(ctx, d, d); len -= bs; @@ -523,15 +511,13 @@ aes_ecb_encrypt(rijndael_ctx *ctx, u_int8_t *data, unsigned len) } } -void -aes_ecb_decrypt(rijndael_ctx *ctx, u_int8_t *data, unsigned len) +void aes_ecb_decrypt(rijndael_ctx *ctx, u_int8_t *data, unsigned len) { - unsigned bs = 16; - u_int32_t *d; + unsigned bs = 16; + u_int32_t *d; - while (len >= bs) - { - d = (u_int32_t *) data; + while(len >= bs) { + d = (u_int32_t *)data; rijndael_decrypt(ctx, d, d); len -= bs; @@ -539,15 +525,14 @@ aes_ecb_decrypt(rijndael_ctx *ctx, u_int8_t *data, unsigned len) } } -void -aes_cbc_encrypt(rijndael_ctx *ctx, u_int8_t *iva, u_int8_t *data, unsigned len) +void aes_cbc_encrypt( + rijndael_ctx *ctx, u_int8_t *iva, u_int8_t *data, unsigned len) { - u_int32_t *iv = (u_int32_t *) iva; - u_int32_t *d = (u_int32_t *) data; - unsigned bs = 16; + u_int32_t *iv = (u_int32_t *)iva; + u_int32_t *d = (u_int32_t *)data; + unsigned bs = 16; - while (len >= bs) - { + while(len >= bs) { d[0] ^= iv[0]; d[1] ^= iv[1]; d[2] ^= iv[2]; @@ -561,17 +546,15 @@ aes_cbc_encrypt(rijndael_ctx *ctx, u_int8_t *iva, u_int8_t *data, unsigned len) } } -void -aes_cbc_decrypt(rijndael_ctx *ctx, u_int8_t *iva, u_int8_t *data, unsigned len) +void aes_cbc_decrypt( + rijndael_ctx *ctx, u_int8_t *iva, u_int8_t *data, unsigned len) { - u_int32_t *d = (u_int32_t *) data; - unsigned bs = 16; - u_int32_t buf[4], - iv[4]; + u_int32_t *d = (u_int32_t *)data; + unsigned bs = 16; + u_int32_t buf[4], iv[4]; memcpy(iv, iva, bs); - while (len >= bs) - { + while(len >= bs) { buf[0] = d[0]; buf[1] = d[1]; buf[2] = d[2]; @@ -602,36 +585,30 @@ aes_cbc_decrypt(rijndael_ctx *ctx, u_int8_t *iva, u_int8_t *data, unsigned len) */ #ifdef PRINT_TABS -static void -show256u8(char *name, u_int8_t *data) +static void show256u8(char *name, u_int8_t *data) { - int i; + int i; printf("static const u1byte %s[256] = {\n ", name); - for (i = 0; i < 256;) - { + for(i = 0; i < 256;) { printf("%u", pow_tab[i++]); - if (i < 256) + if(i < 256) printf(i % 16 ? ", " : ",\n "); } printf("\n};\n\n"); } -static void -show4x256u32(char *name, u_int32_t data[4][256]) +static void show4x256u32(char *name, u_int32_t data[4][256]) { - int i, - j; + int i, j; printf("static const u4byte %s[4][256] = {\n{\n ", name); - for (i = 0; i < 4; i++) - { - for (j = 0; j < 256;) - { + for(i = 0; i < 4; i++) { + for(j = 0; j < 256;) { printf("0x%08x", data[i][j]); j++; - if (j < 256) + if(j < 256) printf(j % 4 ? ", " : ",\n "); } printf(i < 3 ? "\n}, {\n " : "\n}\n"); diff --git a/src/core/crypto/rijndael.h b/src/core/crypto/rijndael.h index 5c22f4d4089..d1a27cecfad 100644 --- a/src/core/crypto/rijndael.h +++ b/src/core/crypto/rijndael.h @@ -24,20 +24,20 @@ /* 1. Standard types for AES cryptography source code */ -typedef u_int8_t u1byte; /* an 8 bit u_int8_tacter type */ -typedef u_int16_t u2byte; /* a 16 bit unsigned integer type */ -typedef u_int32_t u4byte; /* a 32 bit unsigned integer type */ +typedef u_int8_t u1byte; /* an 8 bit u_int8_tacter type */ +typedef u_int16_t u2byte; /* a 16 bit unsigned integer type */ +typedef u_int32_t u4byte; /* a 32 bit unsigned integer type */ -typedef int8_t s1byte; /* an 8 bit signed character type */ -typedef int16_t s2byte; /* a 16 bit signed integer type */ -typedef int32_t s4byte; /* a 32 bit signed integer type */ +typedef int8_t s1byte; /* an 8 bit signed character type */ +typedef int16_t s2byte; /* a 16 bit signed integer type */ +typedef int32_t s4byte; /* a 32 bit signed integer type */ typedef struct _rijndael_ctx { - u4byte k_len; - int decrypt; - u4byte e_key[64]; - u4byte d_key[64]; + u4byte k_len; + int decrypt; + u4byte e_key[64]; + u4byte d_key[64]; } rijndael_ctx; @@ -46,16 +46,20 @@ typedef struct _rijndael_ctx /* These are all based on 32 bit unsigned values and will therefore */ /* require endian conversions for big-endian architectures */ -rijndael_ctx *rijndael_set_key(rijndael_ctx *, const u4byte *, const u4byte, int); -void rijndael_encrypt(rijndael_ctx *, const u4byte *, u4byte *); -void rijndael_decrypt(rijndael_ctx *, const u4byte *, u4byte *); +rijndael_ctx *rijndael_set_key( + rijndael_ctx *, const u4byte *, const u4byte, int); +void rijndael_encrypt(rijndael_ctx *, const u4byte *, u4byte *); +void rijndael_decrypt(rijndael_ctx *, const u4byte *, u4byte *); /* conventional interface */ -void aes_set_key(rijndael_ctx *ctx, const u_int8_t *key, unsigned keybits, int enc); -void aes_ecb_encrypt(rijndael_ctx *ctx, u_int8_t *data, unsigned len); -void aes_ecb_decrypt(rijndael_ctx *ctx, u_int8_t *data, unsigned len); -void aes_cbc_encrypt(rijndael_ctx *ctx, u_int8_t *iva, u_int8_t *data, unsigned len); -void aes_cbc_decrypt(rijndael_ctx *ctx, u_int8_t *iva, u_int8_t *data, unsigned len); +void aes_set_key( + rijndael_ctx *ctx, const u_int8_t *key, unsigned keybits, int enc); +void aes_ecb_encrypt(rijndael_ctx *ctx, u_int8_t *data, unsigned len); +void aes_ecb_decrypt(rijndael_ctx *ctx, u_int8_t *data, unsigned len); +void aes_cbc_encrypt( + rijndael_ctx *ctx, u_int8_t *iva, u_int8_t *data, unsigned len); +void aes_cbc_decrypt( + rijndael_ctx *ctx, u_int8_t *iva, u_int8_t *data, unsigned len); -#endif /* _RIJNDAEL_H_ */ +#endif /* _RIJNDAEL_H_ */ diff --git a/src/core/crypto/sha256.c b/src/core/crypto/sha256.c index ba5562755d6..4753a5952fb 100644 --- a/src/core/crypto/sha256.c +++ b/src/core/crypto/sha256.c @@ -31,14 +31,14 @@ * */ -#include /* memcpy()/memset() or bcopy()/bzero() */ -#include /* assert() */ +#include /* memcpy()/memset() or bcopy()/bzero() */ +#include /* assert() */ #include "sha256.h" /* discover byte order on solaris */ #if defined(__SVR4) || defined(__sun) - #include - #define BYTE_ORDER _BYTE_ORDER +#include +#define BYTE_ORDER _BYTE_ORDER #endif /* @@ -90,32 +90,35 @@ * where the appropriate definitions are actually * made). */ -#if !defined(BYTE_ORDER) || (BYTE_ORDER != LITTLE_ENDIAN && BYTE_ORDER != BIG_ENDIAN) +#if !defined(BYTE_ORDER) \ + || (BYTE_ORDER != LITTLE_ENDIAN && BYTE_ORDER != BIG_ENDIAN) #error Define BYTE_ORDER to be equal to either LITTLE_ENDIAN or BIG_ENDIAN #endif /*** SHA-256/384/512 Various Length Definitions ***********************/ /* NOTE: Most of these are in sha2.h */ -#define SHA256_SHORT_BLOCK_LENGTH (SHA256_BLOCK_LENGTH - 8) -#define SHA384_SHORT_BLOCK_LENGTH (SHA384_BLOCK_LENGTH - 16) -#define SHA512_SHORT_BLOCK_LENGTH (SHA512_BLOCK_LENGTH - 16) +#define SHA256_SHORT_BLOCK_LENGTH (SHA256_BLOCK_LENGTH - 8) +#define SHA384_SHORT_BLOCK_LENGTH (SHA384_BLOCK_LENGTH - 16) +#define SHA512_SHORT_BLOCK_LENGTH (SHA512_BLOCK_LENGTH - 16) /*** ENDIAN REVERSAL MACROS *******************************************/ #if BYTE_ORDER == LITTLE_ENDIAN -#define REVERSE32(w,x) { \ - sha2_word32 tmp = (w); \ - tmp = (tmp >> 16) | (tmp << 16); \ - (x) = ((tmp & 0xff00ff00UL) >> 8) | ((tmp & 0x00ff00ffUL) << 8); \ -} -#define REVERSE64(w,x) { \ - sha2_word64 tmp = (w); \ - tmp = (tmp >> 32) | (tmp << 32); \ - tmp = ((tmp & 0xff00ff00ff00ff00ULL) >> 8) | \ - ((tmp & 0x00ff00ff00ff00ffULL) << 8); \ - (x) = ((tmp & 0xffff0000ffff0000ULL) >> 16) | \ - ((tmp & 0x0000ffff0000ffffULL) << 16); \ -} +#define REVERSE32(w, x) \ + { \ + sha2_word32 tmp = (w); \ + tmp = (tmp >> 16) | (tmp << 16); \ + (x) = ((tmp & 0xff00ff00UL) >> 8) | ((tmp & 0x00ff00ffUL) << 8); \ + } +#define REVERSE64(w, x) \ + { \ + sha2_word64 tmp = (w); \ + tmp = (tmp >> 32) | (tmp << 32); \ + tmp = ((tmp & 0xff00ff00ff00ff00ULL) >> 8) \ + | ((tmp & 0x00ff00ff00ff00ffULL) << 8); \ + (x) = ((tmp & 0xffff0000ffff0000ULL) >> 16) \ + | ((tmp & 0x0000ffff0000ffffULL) << 16); \ + } #endif /* BYTE_ORDER == LITTLE_ENDIAN */ /* @@ -123,12 +126,13 @@ * unsigned 128-bit integer (represented using a two-element array of * 64-bit words): */ -#define ADDINC128(w,n) { \ - (w)[0] += (sha2_word64)(n); \ - if ((w)[0] < (n)) { \ - (w)[1]++; \ - } \ -} +#define ADDINC128(w, n) \ + { \ + (w)[0] += (sha2_word64)(n); \ + if((w)[0] < (n)) { \ + (w)[1]++; \ + } \ + } /* * Macros for copying blocks of memory and for zeroing out ranges @@ -141,7 +145,7 @@ */ #if !defined(SHA2_USE_MEMSET_MEMCPY) && !defined(SHA2_USE_BZERO_BCOPY) /* Default to memset()/memcpy() if no option is specified */ -#define SHA2_USE_MEMSET_MEMCPY 1 +#define SHA2_USE_MEMSET_MEMCPY 1 #endif #if defined(SHA2_USE_MEMSET_MEMCPY) && defined(SHA2_USE_BZERO_BCOPY) /* Abort with an error if BOTH options are defined */ @@ -149,12 +153,12 @@ #endif #ifdef SHA2_USE_MEMSET_MEMCPY -#define MEMSET_BZERO(p,l) memset((p), 0, (l)) -#define MEMCPY_BCOPY(d,s,l) memcpy((d), (s), (l)) +#define MEMSET_BZERO(p, l) memset((p), 0, (l)) +#define MEMCPY_BCOPY(d, s, l) memcpy((d), (s), (l)) #endif #ifdef SHA2_USE_BZERO_BCOPY -#define MEMSET_BZERO(p,l) bzero((p), (l)) -#define MEMCPY_BCOPY(d,s,l) bcopy((s), (d), (l)) +#define MEMSET_BZERO(p, l) bzero((p), (l)) +#define MEMCPY_BCOPY(d, s, l) bcopy((s), (d), (l)) #endif @@ -168,150 +172,107 @@ * same "backwards" definition. */ /* Shift-right (used in SHA-256, SHA-384, and SHA-512): */ -#define R(b,x) ((x) >> (b)) +#define R(b, x) ((x) >> (b)) /* 32-bit Rotate-right (used in SHA-256): */ -#define S32(b,x) (((x) >> (b)) | ((x) << (32 - (b)))) +#define S32(b, x) (((x) >> (b)) | ((x) << (32 - (b)))) /* 64-bit Rotate-right (used in SHA-384 and SHA-512): */ -#define S64(b,x) (((x) >> (b)) | ((x) << (64 - (b)))) +#define S64(b, x) (((x) >> (b)) | ((x) << (64 - (b)))) /* Two of six logical functions used in SHA-256, SHA-384, and SHA-512: */ -#define Ch(x,y,z) (((x) & (y)) ^ ((~(x)) & (z))) -#define Maj(x,y,z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) +#define Ch(x, y, z) (((x) & (y)) ^ ((~(x)) & (z))) +#define Maj(x, y, z) (((x) & (y)) ^ ((x) & (z)) ^ ((y) & (z))) /* Four of six logical functions used in SHA-256: */ -#define Sigma0_256(x) (S32(2, (x)) ^ S32(13, (x)) ^ S32(22, (x))) -#define Sigma1_256(x) (S32(6, (x)) ^ S32(11, (x)) ^ S32(25, (x))) -#define sigma0_256(x) (S32(7, (x)) ^ S32(18, (x)) ^ R(3 , (x))) -#define sigma1_256(x) (S32(17, (x)) ^ S32(19, (x)) ^ R(10, (x))) +#define Sigma0_256(x) (S32(2, (x)) ^ S32(13, (x)) ^ S32(22, (x))) +#define Sigma1_256(x) (S32(6, (x)) ^ S32(11, (x)) ^ S32(25, (x))) +#define sigma0_256(x) (S32(7, (x)) ^ S32(18, (x)) ^ R(3, (x))) +#define sigma1_256(x) (S32(17, (x)) ^ S32(19, (x)) ^ R(10, (x))) /* Four of six logical functions used in SHA-384 and SHA-512: */ -#define Sigma0_512(x) (S64(28, (x)) ^ S64(34, (x)) ^ S64(39, (x))) -#define Sigma1_512(x) (S64(14, (x)) ^ S64(18, (x)) ^ S64(41, (x))) -#define sigma0_512(x) (S64( 1, (x)) ^ S64( 8, (x)) ^ R( 7, (x))) -#define sigma1_512(x) (S64(19, (x)) ^ S64(61, (x)) ^ R( 6, (x))) +#define Sigma0_512(x) (S64(28, (x)) ^ S64(34, (x)) ^ S64(39, (x))) +#define Sigma1_512(x) (S64(14, (x)) ^ S64(18, (x)) ^ S64(41, (x))) +#define sigma0_512(x) (S64(1, (x)) ^ S64(8, (x)) ^ R(7, (x))) +#define sigma1_512(x) (S64(19, (x)) ^ S64(61, (x)) ^ R(6, (x))) /*** INTERNAL FUNCTION PROTOTYPES *************************************/ /* NOTE: These should not be accessed directly from outside this * library -- they are intended for private internal visibility/use * only. */ -void SHA512_Last(SHA512_CTX*); -void SHA256_Transform(SHA256_CTX*, const sha2_word32*); -void SHA512_Transform(SHA512_CTX*, const sha2_word64*); +void SHA512_Last(SHA512_CTX *); +void SHA256_Transform(SHA256_CTX *, const sha2_word32 *); +void SHA512_Transform(SHA512_CTX *, const sha2_word64 *); /*** SHA-XYZ INITIAL HASH VALUES AND CONSTANTS ************************/ /* Hash constant words K for SHA-256: */ -const static sha2_word32 K256[64] = { - 0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, 0xe9b5dba5UL, - 0x3956c25bUL, 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, - 0xd807aa98UL, 0x12835b01UL, 0x243185beUL, 0x550c7dc3UL, - 0x72be5d74UL, 0x80deb1feUL, 0x9bdc06a7UL, 0xc19bf174UL, - 0xe49b69c1UL, 0xefbe4786UL, 0x0fc19dc6UL, 0x240ca1ccUL, - 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, 0x76f988daUL, - 0x983e5152UL, 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, - 0xc6e00bf3UL, 0xd5a79147UL, 0x06ca6351UL, 0x14292967UL, - 0x27b70a85UL, 0x2e1b2138UL, 0x4d2c6dfcUL, 0x53380d13UL, - 0x650a7354UL, 0x766a0abbUL, 0x81c2c92eUL, 0x92722c85UL, - 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, 0xc76c51a3UL, - 0xd192e819UL, 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, - 0x19a4c116UL, 0x1e376c08UL, 0x2748774cUL, 0x34b0bcb5UL, - 0x391c0cb3UL, 0x4ed8aa4aUL, 0x5b9cca4fUL, 0x682e6ff3UL, - 0x748f82eeUL, 0x78a5636fUL, 0x84c87814UL, 0x8cc70208UL, - 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, 0xc67178f2UL -}; +const static sha2_word32 K256[64] = {0x428a2f98UL, 0x71374491UL, 0xb5c0fbcfUL, + 0xe9b5dba5UL, 0x3956c25bUL, 0x59f111f1UL, 0x923f82a4UL, 0xab1c5ed5UL, + 0xd807aa98UL, 0x12835b01UL, 0x243185beUL, 0x550c7dc3UL, 0x72be5d74UL, + 0x80deb1feUL, 0x9bdc06a7UL, 0xc19bf174UL, 0xe49b69c1UL, 0xefbe4786UL, + 0x0fc19dc6UL, 0x240ca1ccUL, 0x2de92c6fUL, 0x4a7484aaUL, 0x5cb0a9dcUL, + 0x76f988daUL, 0x983e5152UL, 0xa831c66dUL, 0xb00327c8UL, 0xbf597fc7UL, + 0xc6e00bf3UL, 0xd5a79147UL, 0x06ca6351UL, 0x14292967UL, 0x27b70a85UL, + 0x2e1b2138UL, 0x4d2c6dfcUL, 0x53380d13UL, 0x650a7354UL, 0x766a0abbUL, + 0x81c2c92eUL, 0x92722c85UL, 0xa2bfe8a1UL, 0xa81a664bUL, 0xc24b8b70UL, + 0xc76c51a3UL, 0xd192e819UL, 0xd6990624UL, 0xf40e3585UL, 0x106aa070UL, + 0x19a4c116UL, 0x1e376c08UL, 0x2748774cUL, 0x34b0bcb5UL, 0x391c0cb3UL, + 0x4ed8aa4aUL, 0x5b9cca4fUL, 0x682e6ff3UL, 0x748f82eeUL, 0x78a5636fUL, + 0x84c87814UL, 0x8cc70208UL, 0x90befffaUL, 0xa4506cebUL, 0xbef9a3f7UL, + 0xc67178f2UL}; /* Initial hash value H for SHA-256: */ -const static sha2_word32 sha256_initial_hash_value[8] = { - 0x6a09e667UL, - 0xbb67ae85UL, - 0x3c6ef372UL, - 0xa54ff53aUL, - 0x510e527fUL, - 0x9b05688cUL, - 0x1f83d9abUL, - 0x5be0cd19UL -}; +const static sha2_word32 sha256_initial_hash_value[8] = {0x6a09e667UL, + 0xbb67ae85UL, 0x3c6ef372UL, 0xa54ff53aUL, 0x510e527fUL, 0x9b05688cUL, + 0x1f83d9abUL, 0x5be0cd19UL}; /* Hash constant words K for SHA-384 and SHA-512: */ -const static sha2_word64 K512[80] = { - 0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL, - 0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL, - 0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL, - 0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL, - 0xd807aa98a3030242ULL, 0x12835b0145706fbeULL, - 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL, - 0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL, - 0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL, - 0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL, - 0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL, - 0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL, - 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL, - 0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL, - 0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL, - 0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL, - 0x06ca6351e003826fULL, 0x142929670a0e6e70ULL, - 0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL, - 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL, - 0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL, - 0x81c2c92e47edaee6ULL, 0x92722c851482353bULL, - 0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL, - 0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL, - 0xd192e819d6ef5218ULL, 0xd69906245565a910ULL, - 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL, - 0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL, - 0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL, - 0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL, - 0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL, - 0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL, - 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL, - 0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL, - 0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL, - 0xca273eceea26619cULL, 0xd186b8c721c0c207ULL, - 0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL, - 0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL, - 0x113f9804bef90daeULL, 0x1b710b35131c471bULL, - 0x28db77f523047d84ULL, 0x32caab7b40c72493ULL, - 0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL, - 0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL, - 0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL -}; +const static sha2_word64 K512[80] = {0x428a2f98d728ae22ULL, + 0x7137449123ef65cdULL, 0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL, + 0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL, 0x923f82a4af194f9bULL, + 0xab1c5ed5da6d8118ULL, 0xd807aa98a3030242ULL, 0x12835b0145706fbeULL, + 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL, 0x72be5d74f27b896fULL, + 0x80deb1fe3b1696b1ULL, 0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL, + 0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL, 0x0fc19dc68b8cd5b5ULL, + 0x240ca1cc77ac9c65ULL, 0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL, + 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL, 0x983e5152ee66dfabULL, + 0xa831c66d2db43210ULL, 0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL, + 0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL, 0x06ca6351e003826fULL, + 0x142929670a0e6e70ULL, 0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL, + 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL, 0x650a73548baf63deULL, + 0x766a0abb3c77b2a8ULL, 0x81c2c92e47edaee6ULL, 0x92722c851482353bULL, + 0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL, 0xc24b8b70d0f89791ULL, + 0xc76c51a30654be30ULL, 0xd192e819d6ef5218ULL, 0xd69906245565a910ULL, + 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL, 0x19a4c116b8d2d0c8ULL, + 0x1e376c085141ab53ULL, 0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL, + 0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL, 0x5b9cca4f7763e373ULL, + 0x682e6ff3d6b2b8a3ULL, 0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL, + 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL, 0x90befffa23631e28ULL, + 0xa4506cebde82bde9ULL, 0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL, + 0xca273eceea26619cULL, 0xd186b8c721c0c207ULL, 0xeada7dd6cde0eb1eULL, + 0xf57d4f7fee6ed178ULL, 0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL, + 0x113f9804bef90daeULL, 0x1b710b35131c471bULL, 0x28db77f523047d84ULL, + 0x32caab7b40c72493ULL, 0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL, + 0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL, 0x5fcb6fab3ad6faecULL, + 0x6c44198c4a475817ULL}; /* Initial hash value H for SHA-384 */ -const static sha2_word64 sha384_initial_hash_value[8] = { - 0xcbbb9d5dc1059ed8ULL, - 0x629a292a367cd507ULL, - 0x9159015a3070dd17ULL, - 0x152fecd8f70e5939ULL, - 0x67332667ffc00b31ULL, - 0x8eb44a8768581511ULL, - 0xdb0c2e0d64f98fa7ULL, - 0x47b5481dbefa4fa4ULL -}; +const static sha2_word64 sha384_initial_hash_value[8] = {0xcbbb9d5dc1059ed8ULL, + 0x629a292a367cd507ULL, 0x9159015a3070dd17ULL, 0x152fecd8f70e5939ULL, + 0x67332667ffc00b31ULL, 0x8eb44a8768581511ULL, 0xdb0c2e0d64f98fa7ULL, + 0x47b5481dbefa4fa4ULL}; /* Initial hash value H for SHA-512 */ -const static sha2_word64 sha512_initial_hash_value[8] = { - 0x6a09e667f3bcc908ULL, - 0xbb67ae8584caa73bULL, - 0x3c6ef372fe94f82bULL, - 0xa54ff53a5f1d36f1ULL, - 0x510e527fade682d1ULL, - 0x9b05688c2b3e6c1fULL, - 0x1f83d9abfb41bd6bULL, - 0x5be0cd19137e2179ULL -}; +const static sha2_word64 sha512_initial_hash_value[8] = {0x6a09e667f3bcc908ULL, + 0xbb67ae8584caa73bULL, 0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL, + 0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL, 0x1f83d9abfb41bd6bULL, + 0x5be0cd19137e2179ULL}; /* Initial hash value H for SHA-512/256 */ const static sha2_word64 sha512_256_initial_hash_value[8] = { - 0x22312194FC2BF72CULL, - 0x9F555FA3C84C64C2ULL, - 0x2393B86B6F53B151ULL, - 0x963877195940EABDULL, - 0x96283EE2A88EFFE3ULL, - 0xBE5E1E2553863992ULL, - 0x2B0199FC2C85B8AAULL, - 0x0EB72DDC81C52CA2ULL -}; + 0x22312194FC2BF72CULL, 0x9F555FA3C84C64C2ULL, 0x2393B86B6F53B151ULL, + 0x963877195940EABDULL, 0x96283EE2A88EFFE3ULL, 0xBE5E1E2553863992ULL, + 0x2B0199FC2C85B8AAULL, 0x0EB72DDC81C52CA2ULL}; /* * Constant used by SHA256/384/512_End() functions for converting the @@ -321,11 +282,13 @@ static const char *sha2_hex_digits = "0123456789abcdef"; /*** SHA-256: *********************************************************/ -void sr_SHA256_Init(SHA256_CTX* context) { - if (context == (SHA256_CTX*)0) { +void sr_SHA256_Init(SHA256_CTX *context) +{ + if(context == (SHA256_CTX *)0) { return; } - MEMCPY_BCOPY(context->state, sha256_initial_hash_value, SHA256_DIGEST_LENGTH); + MEMCPY_BCOPY( + context->state, sha256_initial_hash_value, SHA256_DIGEST_LENGTH); MEMSET_BZERO(context->buffer, SHA256_BLOCK_LENGTH); context->bitcount = 0; } @@ -336,43 +299,43 @@ void sr_SHA256_Init(SHA256_CTX* context) { #if BYTE_ORDER == LITTLE_ENDIAN -#define ROUND256_0_TO_15(a,b,c,d,e,f,g,h) \ - REVERSE32(*data++, W256[j]); \ - T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \ - K256[j] + W256[j]; \ - (d) += T1; \ - (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \ +#define ROUND256_0_TO_15(a, b, c, d, e, f, g, h) \ + REVERSE32(*data++, W256[j]); \ + T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + K256[j] + W256[j]; \ + (d) += T1; \ + (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \ j++ #else /* BYTE_ORDER == LITTLE_ENDIAN */ -#define ROUND256_0_TO_15(a,b,c,d,e,f,g,h) \ - T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + \ - K256[j] + (W256[j] = *data++); \ - (d) += T1; \ - (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \ +#define ROUND256_0_TO_15(a, b, c, d, e, f, g, h) \ + T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + K256[j] \ + + (W256[j] = *data++); \ + (d) += T1; \ + (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \ j++ #endif /* BYTE_ORDER == LITTLE_ENDIAN */ -#define ROUND256(a,b,c,d,e,f,g,h) \ - s0 = W256[(j+1)&0x0f]; \ - s0 = sigma0_256(s0); \ - s1 = W256[(j+14)&0x0f]; \ - s1 = sigma1_256(s1); \ - T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + K256[j] + \ - (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0); \ - (d) += T1; \ - (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \ +#define ROUND256(a, b, c, d, e, f, g, h) \ + s0 = W256[(j + 1) & 0x0f]; \ + s0 = sigma0_256(s0); \ + s1 = W256[(j + 14) & 0x0f]; \ + s1 = sigma1_256(s1); \ + T1 = (h) + Sigma1_256(e) + Ch((e), (f), (g)) + K256[j] \ + + (W256[j & 0x0f] += s1 + W256[(j + 9) & 0x0f] + s0); \ + (d) += T1; \ + (h) = T1 + Sigma0_256(a) + Maj((a), (b), (c)); \ j++ -void SHA256_Transform(SHA256_CTX* context, const sha2_word32* data) { - sha2_word32 a, b, c, d, e, f, g, h, s0, s1; - sha2_word32 T1, *W256; - int j; +void SHA256_Transform(SHA256_CTX *context, const sha2_word32 *data) +{ + sha2_word32 a, b, c, d, e, f, g, h, s0, s1; + sha2_word32 T1, *W256; + int j; - W256 = (sha2_word32*)context->buffer; + W256 = (sha2_word32 *)context->buffer; /* Initialize registers with the prev. intermediate value */ a = context->state[0]; @@ -387,27 +350,27 @@ void SHA256_Transform(SHA256_CTX* context, const sha2_word32* data) { j = 0; do { /* Rounds 0 to 15 (unrolled): */ - ROUND256_0_TO_15(a,b,c,d,e,f,g,h); - ROUND256_0_TO_15(h,a,b,c,d,e,f,g); - ROUND256_0_TO_15(g,h,a,b,c,d,e,f); - ROUND256_0_TO_15(f,g,h,a,b,c,d,e); - ROUND256_0_TO_15(e,f,g,h,a,b,c,d); - ROUND256_0_TO_15(d,e,f,g,h,a,b,c); - ROUND256_0_TO_15(c,d,e,f,g,h,a,b); - ROUND256_0_TO_15(b,c,d,e,f,g,h,a); - } while (j < 16); + ROUND256_0_TO_15(a, b, c, d, e, f, g, h); + ROUND256_0_TO_15(h, a, b, c, d, e, f, g); + ROUND256_0_TO_15(g, h, a, b, c, d, e, f); + ROUND256_0_TO_15(f, g, h, a, b, c, d, e); + ROUND256_0_TO_15(e, f, g, h, a, b, c, d); + ROUND256_0_TO_15(d, e, f, g, h, a, b, c); + ROUND256_0_TO_15(c, d, e, f, g, h, a, b); + ROUND256_0_TO_15(b, c, d, e, f, g, h, a); + } while(j < 16); /* Now for the remaining rounds to 64: */ do { - ROUND256(a,b,c,d,e,f,g,h); - ROUND256(h,a,b,c,d,e,f,g); - ROUND256(g,h,a,b,c,d,e,f); - ROUND256(f,g,h,a,b,c,d,e); - ROUND256(e,f,g,h,a,b,c,d); - ROUND256(d,e,f,g,h,a,b,c); - ROUND256(c,d,e,f,g,h,a,b); - ROUND256(b,c,d,e,f,g,h,a); - } while (j < 64); + ROUND256(a, b, c, d, e, f, g, h); + ROUND256(h, a, b, c, d, e, f, g); + ROUND256(g, h, a, b, c, d, e, f); + ROUND256(f, g, h, a, b, c, d, e); + ROUND256(e, f, g, h, a, b, c, d); + ROUND256(d, e, f, g, h, a, b, c); + ROUND256(c, d, e, f, g, h, a, b); + ROUND256(b, c, d, e, f, g, h, a); + } while(j < 64); /* Compute the current intermediate hash value */ context->state[0] += a; @@ -425,12 +388,13 @@ void SHA256_Transform(SHA256_CTX* context, const sha2_word32* data) { #else /* SHA2_UNROLL_TRANSFORM */ -void SHA256_Transform(SHA256_CTX* context, const sha2_word32* data) { - sha2_word32 a, b, c, d, e, f, g, h, s0, s1; - sha2_word32 T1, T2, *W256; - int j; +void SHA256_Transform(SHA256_CTX *context, const sha2_word32 *data) +{ + sha2_word32 a, b, c, d, e, f, g, h, s0, s1; + sha2_word32 T1, T2, *W256; + int j; - W256 = (sha2_word32*)context->buffer; + W256 = (sha2_word32 *)context->buffer; /* Initialize registers with the prev. intermediate value */ a = context->state[0]; @@ -446,10 +410,10 @@ void SHA256_Transform(SHA256_CTX* context, const sha2_word32* data) { do { #if BYTE_ORDER == LITTLE_ENDIAN /* Copy data while converting to host byte order */ - REVERSE32(*data++,W256[j]); + REVERSE32(*data++, W256[j]); /* Apply the SHA-256 compression function to update a..h */ T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + W256[j]; -#else /* BYTE_ORDER == LITTLE_ENDIAN */ +#else /* BYTE_ORDER == LITTLE_ENDIAN */ /* Apply the SHA-256 compression function to update a..h with copy */ T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + (W256[j] = *data++); #endif /* BYTE_ORDER == LITTLE_ENDIAN */ @@ -464,18 +428,18 @@ void SHA256_Transform(SHA256_CTX* context, const sha2_word32* data) { a = T1 + T2; j++; - } while (j < 16); + } while(j < 16); do { /* Part of the message block expansion: */ - s0 = W256[(j+1)&0x0f]; + s0 = W256[(j + 1) & 0x0f]; s0 = sigma0_256(s0); - s1 = W256[(j+14)&0x0f]; + s1 = W256[(j + 14) & 0x0f]; s1 = sigma1_256(s1); /* Apply the SHA-256 compression function to update a..h */ - T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + - (W256[j&0x0f] += s1 + W256[(j+9)&0x0f] + s0); + T1 = h + Sigma1_256(e) + Ch(e, f, g) + K256[j] + + (W256[j & 0x0f] += s1 + W256[(j + 9) & 0x0f] + s0); T2 = Sigma0_256(a) + Maj(a, b, c); h = g; g = f; @@ -487,7 +451,7 @@ void SHA256_Transform(SHA256_CTX* context, const sha2_word32* data) { a = T1 + T2; j++; - } while (j < 64); + } while(j < 64); /* Compute the current intermediate hash value */ context->state[0] += a; @@ -505,29 +469,30 @@ void SHA256_Transform(SHA256_CTX* context, const sha2_word32* data) { #endif /* SHA2_UNROLL_TRANSFORM */ -void sr_SHA256_Update(SHA256_CTX* context, const sha2_byte *data, size_t len) { - unsigned int freespace, usedspace; +void sr_SHA256_Update(SHA256_CTX *context, const sha2_byte *data, size_t len) +{ + unsigned int freespace, usedspace; - if (len == 0) { + if(len == 0) { /* Calling with no data is valid - we do nothing */ return; } /* Sanity check: */ - assert(context != (SHA256_CTX*)0 && data != (sha2_byte*)0); + assert(context != (SHA256_CTX *)0 && data != (sha2_byte *)0); usedspace = (context->bitcount >> 3) % SHA256_BLOCK_LENGTH; - if (usedspace > 0) { + if(usedspace > 0) { /* Calculate how much free space is available in the buffer */ freespace = SHA256_BLOCK_LENGTH - usedspace; - if (len >= freespace) { + if(len >= freespace) { /* Fill the buffer completely and process it */ MEMCPY_BCOPY(&context->buffer[usedspace], data, freespace); context->bitcount += freespace << 3; len -= freespace; data += freespace; - SHA256_Transform(context, (sha2_word32*)context->buffer); + SHA256_Transform(context, (sha2_word32 *)context->buffer); } else { /* The buffer is not yet full */ MEMCPY_BCOPY(&context->buffer[usedspace], data, len); @@ -537,14 +502,14 @@ void sr_SHA256_Update(SHA256_CTX* context, const sha2_byte *data, size_t len) { return; } } - while (len >= SHA256_BLOCK_LENGTH) { + while(len >= SHA256_BLOCK_LENGTH) { /* Process as many complete blocks as we can */ - SHA256_Transform(context, (sha2_word32*)data); + SHA256_Transform(context, (sha2_word32 *)data); context->bitcount += SHA256_BLOCK_LENGTH << 3; len -= SHA256_BLOCK_LENGTH; data += SHA256_BLOCK_LENGTH; } - if (len > 0) { + if(len > 0) { /* There's left-overs, so save 'em */ MEMCPY_BCOPY(context->buffer, data, len); context->bitcount += len << 3; @@ -553,33 +518,37 @@ void sr_SHA256_Update(SHA256_CTX* context, const sha2_byte *data, size_t len) { usedspace = freespace = 0; } -void sr_SHA256_Final(sha2_byte digest[SHA256_DIGEST_LENGTH], SHA256_CTX* context) { - sha2_word32 *d = (sha2_word32*)digest; - unsigned int usedspace; +void sr_SHA256_Final( + sha2_byte digest[SHA256_DIGEST_LENGTH], SHA256_CTX *context) +{ + sha2_word32 *d = (sha2_word32 *)digest; + unsigned int usedspace; /* Sanity check: */ - assert(context != (SHA256_CTX*)0); + assert(context != (SHA256_CTX *)0); /* If no digest buffer is passed, we don't bother doing this: */ - if (digest != (sha2_byte*)0) { + if(digest != (sha2_byte *)0) { usedspace = (context->bitcount >> 3) % SHA256_BLOCK_LENGTH; #if BYTE_ORDER == LITTLE_ENDIAN /* Convert FROM host byte order */ - REVERSE64(context->bitcount,context->bitcount); + REVERSE64(context->bitcount, context->bitcount); #endif - if (usedspace > 0) { + if(usedspace > 0) { /* Begin padding with a 1 bit: */ context->buffer[usedspace++] = 0x80; - if (usedspace <= SHA256_SHORT_BLOCK_LENGTH) { + if(usedspace <= SHA256_SHORT_BLOCK_LENGTH) { /* Set-up for the last transform: */ - MEMSET_BZERO(&context->buffer[usedspace], SHA256_SHORT_BLOCK_LENGTH - usedspace); + MEMSET_BZERO(&context->buffer[usedspace], + SHA256_SHORT_BLOCK_LENGTH - usedspace); } else { - if (usedspace < SHA256_BLOCK_LENGTH) { - MEMSET_BZERO(&context->buffer[usedspace], SHA256_BLOCK_LENGTH - usedspace); + if(usedspace < SHA256_BLOCK_LENGTH) { + MEMSET_BZERO(&context->buffer[usedspace], + SHA256_BLOCK_LENGTH - usedspace); } /* Do second-to-last transform: */ - SHA256_Transform(context, (sha2_word32*)context->buffer); + SHA256_Transform(context, (sha2_word32 *)context->buffer); /* And set-up for the last transform: */ MEMSET_BZERO(context->buffer, SHA256_SHORT_BLOCK_LENGTH); @@ -592,17 +561,18 @@ void sr_SHA256_Final(sha2_byte digest[SHA256_DIGEST_LENGTH], SHA256_CTX* context *context->buffer = 0x80; } /* Set the bit count: */ - MEMCPY_BCOPY(&(context->buffer[SHA256_SHORT_BLOCK_LENGTH]), &(context->bitcount), sizeof(sha2_word64)); + MEMCPY_BCOPY(&(context->buffer[SHA256_SHORT_BLOCK_LENGTH]), + &(context->bitcount), sizeof(sha2_word64)); /* Final transform: */ - SHA256_Transform(context, (sha2_word32*)context->buffer); + SHA256_Transform(context, (sha2_word32 *)context->buffer); #if BYTE_ORDER == LITTLE_ENDIAN { /* Convert TO host byte order */ - int j; - for (j = 0; j < 8; j++) { - REVERSE32(context->state[j],context->state[j]); + int j; + for(j = 0; j < 8; j++) { + REVERSE32(context->state[j], context->state[j]); *d++ = context->state[j]; } } @@ -616,17 +586,19 @@ void sr_SHA256_Final(sha2_byte digest[SHA256_DIGEST_LENGTH], SHA256_CTX* context usedspace = 0; } -char *sr_SHA256_End(SHA256_CTX* context, char buffer[SHA256_DIGEST_STRING_LENGTH]) { - sha2_byte digest[SHA256_DIGEST_LENGTH], *d = digest; - int i; +char *sr_SHA256_End( + SHA256_CTX *context, char buffer[SHA256_DIGEST_STRING_LENGTH]) +{ + sha2_byte digest[SHA256_DIGEST_LENGTH], *d = digest; + int i; /* Sanity check: */ - assert(context != (SHA256_CTX*)0); + assert(context != (SHA256_CTX *)0); - if (buffer != (char*)0) { + if(buffer != (char *)0) { sr_SHA256_Final(digest, context); - for (i = 0; i < SHA256_DIGEST_LENGTH; i++) { + for(i = 0; i < SHA256_DIGEST_LENGTH; i++) { *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4]; *buffer++ = sha2_hex_digits[*d & 0x0f]; d++; @@ -639,8 +611,10 @@ char *sr_SHA256_End(SHA256_CTX* context, char buffer[SHA256_DIGEST_STRING_LENGTH return buffer; } -char* sr_SHA256_Data(const sha2_byte* data, size_t len, char digest[SHA256_DIGEST_STRING_LENGTH]) { - SHA256_CTX context; +char *sr_SHA256_Data(const sha2_byte *data, size_t len, + char digest[SHA256_DIGEST_STRING_LENGTH]) +{ + SHA256_CTX context; sr_SHA256_Init(&context); sr_SHA256_Update(&context, data, len); @@ -649,22 +623,26 @@ char* sr_SHA256_Data(const sha2_byte* data, size_t len, char digest[SHA256_DIGES /*** SHA-512 SHA-512/256: *********************************************************/ -void sr_SHA512_Init(SHA512_CTX* context) { - if (context == (SHA512_CTX*)0) { +void sr_SHA512_Init(SHA512_CTX *context) +{ + if(context == (SHA512_CTX *)0) { return; } - MEMCPY_BCOPY(context->state, sha512_initial_hash_value, SHA512_DIGEST_LENGTH); + MEMCPY_BCOPY( + context->state, sha512_initial_hash_value, SHA512_DIGEST_LENGTH); MEMSET_BZERO(context->buffer, SHA512_BLOCK_LENGTH); - context->bitcount[0] = context->bitcount[1] = 0; + context->bitcount[0] = context->bitcount[1] = 0; } -void sr_SHA512_256_Init(SHA512_CTX* context) { - if (context == (SHA512_CTX*)0) { +void sr_SHA512_256_Init(SHA512_CTX *context) +{ + if(context == (SHA512_CTX *)0) { return; } - MEMCPY_BCOPY(context->state, sha512_256_initial_hash_value, SHA512_DIGEST_LENGTH); + MEMCPY_BCOPY(context->state, sha512_256_initial_hash_value, + SHA512_DIGEST_LENGTH); MEMSET_BZERO(context->buffer, SHA512_BLOCK_LENGTH); - context->bitcount[0] = context->bitcount[1] = 0; + context->bitcount[0] = context->bitcount[1] = 0; } #ifdef SHA2_UNROLL_TRANSFORM @@ -672,41 +650,39 @@ void sr_SHA512_256_Init(SHA512_CTX* context) { /* Unrolled SHA-512 round macros: */ #if BYTE_ORDER == LITTLE_ENDIAN -#define ROUND512_0_TO_15(a,b,c,d,e,f,g,h) \ - REVERSE64(*data++, W512[j]); \ - T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + \ - K512[j] + W512[j]; \ - (d) += T1, \ - (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)), \ - j++ +#define ROUND512_0_TO_15(a, b, c, d, e, f, g, h) \ + REVERSE64(*data++, W512[j]); \ + T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + K512[j] + W512[j]; \ + (d) += T1, (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)), j++ #else /* BYTE_ORDER == LITTLE_ENDIAN */ -#define ROUND512_0_TO_15(a,b,c,d,e,f,g,h) \ - T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + \ - K512[j] + (W512[j] = *data++); \ - (d) += T1; \ - (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \ +#define ROUND512_0_TO_15(a, b, c, d, e, f, g, h) \ + T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + K512[j] \ + + (W512[j] = *data++); \ + (d) += T1; \ + (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \ j++ #endif /* BYTE_ORDER == LITTLE_ENDIAN */ -#define ROUND512(a,b,c,d,e,f,g,h) \ - s0 = W512[(j+1)&0x0f]; \ - s0 = sigma0_512(s0); \ - s1 = W512[(j+14)&0x0f]; \ - s1 = sigma1_512(s1); \ - T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + K512[j] + \ - (W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0); \ - (d) += T1; \ - (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \ +#define ROUND512(a, b, c, d, e, f, g, h) \ + s0 = W512[(j + 1) & 0x0f]; \ + s0 = sigma0_512(s0); \ + s1 = W512[(j + 14) & 0x0f]; \ + s1 = sigma1_512(s1); \ + T1 = (h) + Sigma1_512(e) + Ch((e), (f), (g)) + K512[j] \ + + (W512[j & 0x0f] += s1 + W512[(j + 9) & 0x0f] + s0); \ + (d) += T1; \ + (h) = T1 + Sigma0_512(a) + Maj((a), (b), (c)); \ j++ -void SHA512_Transform(SHA512_CTX* context, const sha2_word64* data) { - sha2_word64 a, b, c, d, e, f, g, h, s0, s1; - sha2_word64 T1, *W512 = (sha2_word64*)context->buffer; - int j; +void SHA512_Transform(SHA512_CTX *context, const sha2_word64 *data) +{ + sha2_word64 a, b, c, d, e, f, g, h, s0, s1; + sha2_word64 T1, *W512 = (sha2_word64 *)context->buffer; + int j; /* Initialize registers with the prev. intermediate value */ a = context->state[0]; @@ -720,27 +696,27 @@ void SHA512_Transform(SHA512_CTX* context, const sha2_word64* data) { j = 0; do { - ROUND512_0_TO_15(a,b,c,d,e,f,g,h); - ROUND512_0_TO_15(h,a,b,c,d,e,f,g); - ROUND512_0_TO_15(g,h,a,b,c,d,e,f); - ROUND512_0_TO_15(f,g,h,a,b,c,d,e); - ROUND512_0_TO_15(e,f,g,h,a,b,c,d); - ROUND512_0_TO_15(d,e,f,g,h,a,b,c); - ROUND512_0_TO_15(c,d,e,f,g,h,a,b); - ROUND512_0_TO_15(b,c,d,e,f,g,h,a); - } while (j < 16); + ROUND512_0_TO_15(a, b, c, d, e, f, g, h); + ROUND512_0_TO_15(h, a, b, c, d, e, f, g); + ROUND512_0_TO_15(g, h, a, b, c, d, e, f); + ROUND512_0_TO_15(f, g, h, a, b, c, d, e); + ROUND512_0_TO_15(e, f, g, h, a, b, c, d); + ROUND512_0_TO_15(d, e, f, g, h, a, b, c); + ROUND512_0_TO_15(c, d, e, f, g, h, a, b); + ROUND512_0_TO_15(b, c, d, e, f, g, h, a); + } while(j < 16); /* Now for the remaining rounds up to 79: */ do { - ROUND512(a,b,c,d,e,f,g,h); - ROUND512(h,a,b,c,d,e,f,g); - ROUND512(g,h,a,b,c,d,e,f); - ROUND512(f,g,h,a,b,c,d,e); - ROUND512(e,f,g,h,a,b,c,d); - ROUND512(d,e,f,g,h,a,b,c); - ROUND512(c,d,e,f,g,h,a,b); - ROUND512(b,c,d,e,f,g,h,a); - } while (j < 80); + ROUND512(a, b, c, d, e, f, g, h); + ROUND512(h, a, b, c, d, e, f, g); + ROUND512(g, h, a, b, c, d, e, f); + ROUND512(f, g, h, a, b, c, d, e); + ROUND512(e, f, g, h, a, b, c, d); + ROUND512(d, e, f, g, h, a, b, c); + ROUND512(c, d, e, f, g, h, a, b); + ROUND512(b, c, d, e, f, g, h, a); + } while(j < 80); /* Compute the current intermediate hash value */ context->state[0] += a; @@ -758,10 +734,11 @@ void SHA512_Transform(SHA512_CTX* context, const sha2_word64* data) { #else /* SHA2_UNROLL_TRANSFORM */ -void SHA512_Transform(SHA512_CTX* context, const sha2_word64* data) { - sha2_word64 a, b, c, d, e, f, g, h, s0, s1; - sha2_word64 T1, T2, *W512 = (sha2_word64*)context->buffer; - int j; +void SHA512_Transform(SHA512_CTX *context, const sha2_word64 *data) +{ + sha2_word64 a, b, c, d, e, f, g, h, s0, s1; + sha2_word64 T1, T2, *W512 = (sha2_word64 *)context->buffer; + int j; /* Initialize registers with the prev. intermediate value */ a = context->state[0]; @@ -780,7 +757,7 @@ void SHA512_Transform(SHA512_CTX* context, const sha2_word64* data) { REVERSE64(*data++, W512[j]); /* Apply the SHA-512 compression function to update a..h */ T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + W512[j]; -#else /* BYTE_ORDER == LITTLE_ENDIAN */ +#else /* BYTE_ORDER == LITTLE_ENDIAN */ /* Apply the SHA-512 compression function to update a..h with copy */ T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + (W512[j] = *data++); #endif /* BYTE_ORDER == LITTLE_ENDIAN */ @@ -795,18 +772,18 @@ void SHA512_Transform(SHA512_CTX* context, const sha2_word64* data) { a = T1 + T2; j++; - } while (j < 16); + } while(j < 16); do { /* Part of the message block expansion: */ - s0 = W512[(j+1)&0x0f]; + s0 = W512[(j + 1) & 0x0f]; s0 = sigma0_512(s0); - s1 = W512[(j+14)&0x0f]; - s1 = sigma1_512(s1); + s1 = W512[(j + 14) & 0x0f]; + s1 = sigma1_512(s1); /* Apply the SHA-512 compression function to update a..h */ - T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + - (W512[j&0x0f] += s1 + W512[(j+9)&0x0f] + s0); + T1 = h + Sigma1_512(e) + Ch(e, f, g) + K512[j] + + (W512[j & 0x0f] += s1 + W512[(j + 9) & 0x0f] + s0); T2 = Sigma0_512(a) + Maj(a, b, c); h = g; g = f; @@ -818,7 +795,7 @@ void SHA512_Transform(SHA512_CTX* context, const sha2_word64* data) { a = T1 + T2; j++; - } while (j < 80); + } while(j < 80); /* Compute the current intermediate hash value */ context->state[0] += a; @@ -836,29 +813,30 @@ void SHA512_Transform(SHA512_CTX* context, const sha2_word64* data) { #endif /* SHA2_UNROLL_TRANSFORM */ -void sr_SHA512_Update(SHA512_CTX* context, const sha2_byte *data, size_t len) { - unsigned int freespace, usedspace; +void sr_SHA512_Update(SHA512_CTX *context, const sha2_byte *data, size_t len) +{ + unsigned int freespace, usedspace; - if (len == 0) { + if(len == 0) { /* Calling with no data is valid - we do nothing */ return; } /* Sanity check: */ - assert(context != (SHA512_CTX*)0 && data != (sha2_byte*)0); + assert(context != (SHA512_CTX *)0 && data != (sha2_byte *)0); usedspace = (context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH; - if (usedspace > 0) { + if(usedspace > 0) { /* Calculate how much free space is available in the buffer */ freespace = SHA512_BLOCK_LENGTH - usedspace; - if (len >= freespace) { + if(len >= freespace) { /* Fill the buffer completely and process it */ MEMCPY_BCOPY(&context->buffer[usedspace], data, freespace); ADDINC128(context->bitcount, freespace << 3); len -= freespace; data += freespace; - SHA512_Transform(context, (sha2_word64*)context->buffer); + SHA512_Transform(context, (sha2_word64 *)context->buffer); } else { /* The buffer is not yet full */ MEMCPY_BCOPY(&context->buffer[usedspace], data, len); @@ -868,14 +846,14 @@ void sr_SHA512_Update(SHA512_CTX* context, const sha2_byte *data, size_t len) { return; } } - while (len >= SHA512_BLOCK_LENGTH) { + while(len >= SHA512_BLOCK_LENGTH) { /* Process as many complete blocks as we can */ - SHA512_Transform(context, (sha2_word64*)data); + SHA512_Transform(context, (sha2_word64 *)data); ADDINC128(context->bitcount, SHA512_BLOCK_LENGTH << 3); len -= SHA512_BLOCK_LENGTH; data += SHA512_BLOCK_LENGTH; } - if (len > 0) { + if(len > 0) { /* There's left-overs, so save 'em */ MEMCPY_BCOPY(context->buffer, data, len); ADDINC128(context->bitcount, len << 3); @@ -884,28 +862,31 @@ void sr_SHA512_Update(SHA512_CTX* context, const sha2_byte *data, size_t len) { usedspace = freespace = 0; } -void SHA512_Last(SHA512_CTX* context) { - unsigned int usedspace; +void SHA512_Last(SHA512_CTX *context) +{ + unsigned int usedspace; usedspace = (context->bitcount[0] >> 3) % SHA512_BLOCK_LENGTH; #if BYTE_ORDER == LITTLE_ENDIAN /* Convert FROM host byte order */ - REVERSE64(context->bitcount[0],context->bitcount[0]); - REVERSE64(context->bitcount[1],context->bitcount[1]); + REVERSE64(context->bitcount[0], context->bitcount[0]); + REVERSE64(context->bitcount[1], context->bitcount[1]); #endif - if (usedspace > 0) { + if(usedspace > 0) { /* Begin padding with a 1 bit: */ context->buffer[usedspace++] = 0x80; - if (usedspace <= SHA512_SHORT_BLOCK_LENGTH) { + if(usedspace <= SHA512_SHORT_BLOCK_LENGTH) { /* Set-up for the last transform: */ - MEMSET_BZERO(&context->buffer[usedspace], SHA512_SHORT_BLOCK_LENGTH - usedspace); + MEMSET_BZERO(&context->buffer[usedspace], + SHA512_SHORT_BLOCK_LENGTH - usedspace); } else { - if (usedspace < SHA512_BLOCK_LENGTH) { - MEMSET_BZERO(&context->buffer[usedspace], SHA512_BLOCK_LENGTH - usedspace); + if(usedspace < SHA512_BLOCK_LENGTH) { + MEMSET_BZERO(&context->buffer[usedspace], + SHA512_BLOCK_LENGTH - usedspace); } /* Do second-to-last transform: */ - SHA512_Transform(context, (sha2_word64*)context->buffer); + SHA512_Transform(context, (sha2_word64 *)context->buffer); /* And set-up for the last transform: */ MEMSET_BZERO(context->buffer, SHA512_BLOCK_LENGTH - 2); @@ -918,30 +899,34 @@ void SHA512_Last(SHA512_CTX* context) { *context->buffer = 0x80; } /* Store the length of input data (in bits): */ - MEMCPY_BCOPY(&(context->buffer[SHA512_SHORT_BLOCK_LENGTH+0]), &(context->bitcount[1]), sizeof(sha2_word64)); - MEMCPY_BCOPY(&(context->buffer[SHA512_SHORT_BLOCK_LENGTH+8]), &(context->bitcount[0]), sizeof(sha2_word64)); + MEMCPY_BCOPY(&(context->buffer[SHA512_SHORT_BLOCK_LENGTH + 0]), + &(context->bitcount[1]), sizeof(sha2_word64)); + MEMCPY_BCOPY(&(context->buffer[SHA512_SHORT_BLOCK_LENGTH + 8]), + &(context->bitcount[0]), sizeof(sha2_word64)); /* Final transform: */ - SHA512_Transform(context, (sha2_word64*)context->buffer); + SHA512_Transform(context, (sha2_word64 *)context->buffer); } -void sr_SHA512_Final(sha2_byte digest[SHA512_DIGEST_LENGTH], SHA512_CTX* context) { - sha2_word64 *d = (sha2_word64*)digest; +void sr_SHA512_Final( + sha2_byte digest[SHA512_DIGEST_LENGTH], SHA512_CTX *context) +{ + sha2_word64 *d = (sha2_word64 *)digest; /* Sanity check: */ - assert(context != (SHA512_CTX*)0); + assert(context != (SHA512_CTX *)0); /* If no digest buffer is passed, we don't bother doing this: */ - if (digest != (sha2_byte*)0) { + if(digest != (sha2_byte *)0) { SHA512_Last(context); /* Save the hash data for output: */ #if BYTE_ORDER == LITTLE_ENDIAN { /* Convert TO host byte order */ - int j; - for (j = 0; j < 8; j++) { - REVERSE64(context->state[j],context->state[j]); + int j; + for(j = 0; j < 8; j++) { + REVERSE64(context->state[j], context->state[j]); *d++ = context->state[j]; } } @@ -954,17 +939,19 @@ void sr_SHA512_Final(sha2_byte digest[SHA512_DIGEST_LENGTH], SHA512_CTX* context MEMSET_BZERO(context, sizeof(*context)); } -char *sr_SHA512_End(SHA512_CTX* context, char buffer[SHA512_DIGEST_STRING_LENGTH]) { - sha2_byte digest[SHA512_DIGEST_LENGTH], *d = digest; - int i; +char *sr_SHA512_End( + SHA512_CTX *context, char buffer[SHA512_DIGEST_STRING_LENGTH]) +{ + sha2_byte digest[SHA512_DIGEST_LENGTH], *d = digest; + int i; /* Sanity check: */ - assert(context != (SHA512_CTX*)0); + assert(context != (SHA512_CTX *)0); - if (buffer != (char*)0) { + if(buffer != (char *)0) { sr_SHA512_Final(digest, context); - for (i = 0; i < SHA512_DIGEST_LENGTH; i++) { + for(i = 0; i < SHA512_DIGEST_LENGTH; i++) { *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4]; *buffer++ = sha2_hex_digits[*d & 0x0f]; d++; @@ -977,8 +964,10 @@ char *sr_SHA512_End(SHA512_CTX* context, char buffer[SHA512_DIGEST_STRING_LENGTH return buffer; } -char* sr_SHA512_Data(const sha2_byte* data, size_t len, char digest[SHA512_DIGEST_STRING_LENGTH]) { - SHA512_CTX context; +char *sr_SHA512_Data(const sha2_byte *data, size_t len, + char digest[SHA512_DIGEST_STRING_LENGTH]) +{ + SHA512_CTX context; sr_SHA512_Init(&context); sr_SHA512_Update(&context, data, len); @@ -987,36 +976,41 @@ char* sr_SHA512_Data(const sha2_byte* data, size_t len, char digest[SHA512_DIGES /*** SHA-384: *********************************************************/ -void sr_SHA384_Init(SHA384_CTX* context) { - if (context == (SHA384_CTX*)0) { +void sr_SHA384_Init(SHA384_CTX *context) +{ + if(context == (SHA384_CTX *)0) { return; } - MEMCPY_BCOPY(context->state, sha384_initial_hash_value, SHA512_DIGEST_LENGTH); + MEMCPY_BCOPY( + context->state, sha384_initial_hash_value, SHA512_DIGEST_LENGTH); MEMSET_BZERO(context->buffer, SHA384_BLOCK_LENGTH); context->bitcount[0] = context->bitcount[1] = 0; } -void sr_SHA384_Update(SHA384_CTX* context, const sha2_byte* data, size_t len) { - sr_SHA512_Update((SHA512_CTX*)context, data, len); +void sr_SHA384_Update(SHA384_CTX *context, const sha2_byte *data, size_t len) +{ + sr_SHA512_Update((SHA512_CTX *)context, data, len); } -void sr_SHA384_Final(sha2_byte digest[SHA384_DIGEST_LENGTH], SHA384_CTX* context) { - sha2_word64 *d = (sha2_word64*)digest; +void sr_SHA384_Final( + sha2_byte digest[SHA384_DIGEST_LENGTH], SHA384_CTX *context) +{ + sha2_word64 *d = (sha2_word64 *)digest; /* Sanity check: */ - assert(context != (SHA384_CTX*)0); + assert(context != (SHA384_CTX *)0); /* If no digest buffer is passed, we don't bother doing this: */ - if (digest != (sha2_byte*)0) { - SHA512_Last((SHA512_CTX*)context); + if(digest != (sha2_byte *)0) { + SHA512_Last((SHA512_CTX *)context); /* Save the hash data for output: */ #if BYTE_ORDER == LITTLE_ENDIAN { /* Convert TO host byte order */ - int j; - for (j = 0; j < 6; j++) { - REVERSE64(context->state[j],context->state[j]); + int j; + for(j = 0; j < 6; j++) { + REVERSE64(context->state[j], context->state[j]); *d++ = context->state[j]; } } @@ -1029,17 +1023,19 @@ void sr_SHA384_Final(sha2_byte digest[SHA384_DIGEST_LENGTH], SHA384_CTX* context MEMSET_BZERO(context, sizeof(*context)); } -char *sr_SHA384_End(SHA384_CTX* context, char buffer[SHA384_DIGEST_STRING_LENGTH]) { - sha2_byte digest[SHA384_DIGEST_LENGTH], *d = digest; - int i; +char *sr_SHA384_End( + SHA384_CTX *context, char buffer[SHA384_DIGEST_STRING_LENGTH]) +{ + sha2_byte digest[SHA384_DIGEST_LENGTH], *d = digest; + int i; /* Sanity check: */ - assert(context != (SHA384_CTX*)0); + assert(context != (SHA384_CTX *)0); - if (buffer != (char*)0) { + if(buffer != (char *)0) { sr_SHA384_Final(digest, context); - for (i = 0; i < SHA384_DIGEST_LENGTH; i++) { + for(i = 0; i < SHA384_DIGEST_LENGTH; i++) { *buffer++ = sha2_hex_digits[(*d & 0xf0) >> 4]; *buffer++ = sha2_hex_digits[*d & 0x0f]; d++; @@ -1052,8 +1048,10 @@ char *sr_SHA384_End(SHA384_CTX* context, char buffer[SHA384_DIGEST_STRING_LENGTH return buffer; } -char* sr_SHA384_Data(const sha2_byte* data, size_t len, char digest[SHA384_DIGEST_STRING_LENGTH]) { - SHA384_CTX context; +char *sr_SHA384_Data(const sha2_byte *data, size_t len, + char digest[SHA384_DIGEST_STRING_LENGTH]) +{ + SHA384_CTX context; sr_SHA384_Init(&context); sr_SHA384_Update(&context, data, len); diff --git a/src/core/crypto/sha256.h b/src/core/crypto/sha256.h index 5710ed81a96..1bb78f21fb6 100644 --- a/src/core/crypto/sha256.h +++ b/src/core/crypto/sha256.h @@ -35,22 +35,23 @@ #define __SHA2_H__ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif #include #include /*** SHA-256/384/512 Various Length Definitions ***********************/ -#define SHA256_BLOCK_LENGTH 64 -#define SHA256_DIGEST_LENGTH 32 -#define SHA256_DIGEST_STRING_LENGTH (SHA256_DIGEST_LENGTH * 2 + 1) -#define SHA384_BLOCK_LENGTH 128 -#define SHA384_DIGEST_LENGTH 48 -#define SHA384_DIGEST_STRING_LENGTH (SHA384_DIGEST_LENGTH * 2 + 1) -#define SHA512_BLOCK_LENGTH 128 -#define SHA512_DIGEST_LENGTH 64 -#define SHA512_DIGEST_STRING_LENGTH (SHA512_DIGEST_LENGTH * 2 + 1) +#define SHA256_BLOCK_LENGTH 64 +#define SHA256_DIGEST_LENGTH 32 +#define SHA256_DIGEST_STRING_LENGTH (SHA256_DIGEST_LENGTH * 2 + 1) +#define SHA384_BLOCK_LENGTH 128 +#define SHA384_DIGEST_LENGTH 48 +#define SHA384_DIGEST_STRING_LENGTH (SHA384_DIGEST_LENGTH * 2 + 1) +#define SHA512_BLOCK_LENGTH 128 +#define SHA512_DIGEST_LENGTH 64 +#define SHA512_DIGEST_STRING_LENGTH (SHA512_DIGEST_LENGTH * 2 + 1) /*** SHA-256/384/512 Context Structures *******************************/ @@ -64,69 +65,74 @@ typedef unsigned int u_int32_t; /* 4-bytes (32-bits) */ typedef unsigned long long u_int64_t; /* 8-bytes (64-bits) */ #endif -typedef struct _SHA256_CTX { - uint32_t state[8]; - uint64_t bitcount; - uint8_t buffer[SHA256_BLOCK_LENGTH]; -} SHA256_CTX; -typedef struct _SHA512_CTX { - uint64_t state[8]; - uint64_t bitcount[2]; - uint8_t buffer[SHA512_BLOCK_LENGTH]; -} SHA512_CTX; - -typedef SHA512_CTX SHA384_CTX; - -typedef uint8_t sha2_byte; /* Exactly 1 byte */ -typedef uint32_t sha2_word32; /* Exactly 4 bytes */ -typedef uint64_t sha2_word64; /* Exactly 8 bytes */ + typedef struct _SHA256_CTX + { + uint32_t state[8]; + uint64_t bitcount; + uint8_t buffer[SHA256_BLOCK_LENGTH]; + } SHA256_CTX; + typedef struct _SHA512_CTX + { + uint64_t state[8]; + uint64_t bitcount[2]; + uint8_t buffer[SHA512_BLOCK_LENGTH]; + } SHA512_CTX; + + typedef SHA512_CTX SHA384_CTX; + + typedef uint8_t sha2_byte; /* Exactly 1 byte */ + typedef uint32_t sha2_word32; /* Exactly 4 bytes */ + typedef uint64_t sha2_word64; /* Exactly 8 bytes */ /*** SHA-256/384/512 Function Prototypes ******************************/ #ifndef NOPROTO -void sr_SHA256_Init(SHA256_CTX *); -void sr_SHA256_Update(SHA256_CTX*, const uint8_t*, size_t); -void sr_SHA256_Final(sha2_byte[SHA256_DIGEST_LENGTH], SHA256_CTX*); -char* sr_SHA256_End(SHA256_CTX*, char[SHA256_DIGEST_STRING_LENGTH]); -char* sr_SHA256_Data(const uint8_t*, size_t, char[SHA256_DIGEST_STRING_LENGTH]); - -void sr_SHA384_Init(SHA384_CTX*); -void sr_SHA384_Update(SHA384_CTX*, const uint8_t*, size_t); -void sr_SHA384_Final(sha2_byte[SHA384_DIGEST_LENGTH], SHA384_CTX*); -char* sr_SHA384_End(SHA384_CTX*, char[SHA384_DIGEST_STRING_LENGTH]); -char* sr_SHA384_Data(const uint8_t*, size_t, char[SHA384_DIGEST_STRING_LENGTH]); - -void sr_SHA512_Init(SHA512_CTX*); -void sr_SHA512_256_Init(SHA512_CTX*); -void sr_SHA512_Update(SHA512_CTX*, const uint8_t*, size_t); -void sr_SHA512_Final(sha2_byte[SHA512_DIGEST_LENGTH], SHA512_CTX*); -char* sr_SHA512_End(SHA512_CTX*, char[SHA512_DIGEST_STRING_LENGTH]); -char* sr_SHA512_Data(const uint8_t*, size_t, char[SHA512_DIGEST_STRING_LENGTH]); + void sr_SHA256_Init(SHA256_CTX *); + void sr_SHA256_Update(SHA256_CTX *, const uint8_t *, size_t); + void sr_SHA256_Final(sha2_byte[SHA256_DIGEST_LENGTH], SHA256_CTX *); + char *sr_SHA256_End(SHA256_CTX *, char[SHA256_DIGEST_STRING_LENGTH]); + char *sr_SHA256_Data( + const uint8_t *, size_t, char[SHA256_DIGEST_STRING_LENGTH]); + + void sr_SHA384_Init(SHA384_CTX *); + void sr_SHA384_Update(SHA384_CTX *, const uint8_t *, size_t); + void sr_SHA384_Final(sha2_byte[SHA384_DIGEST_LENGTH], SHA384_CTX *); + char *sr_SHA384_End(SHA384_CTX *, char[SHA384_DIGEST_STRING_LENGTH]); + char *sr_SHA384_Data( + const uint8_t *, size_t, char[SHA384_DIGEST_STRING_LENGTH]); + + void sr_SHA512_Init(SHA512_CTX *); + void sr_SHA512_256_Init(SHA512_CTX *); + void sr_SHA512_Update(SHA512_CTX *, const uint8_t *, size_t); + void sr_SHA512_Final(sha2_byte[SHA512_DIGEST_LENGTH], SHA512_CTX *); + char *sr_SHA512_End(SHA512_CTX *, char[SHA512_DIGEST_STRING_LENGTH]); + char *sr_SHA512_Data( + const uint8_t *, size_t, char[SHA512_DIGEST_STRING_LENGTH]); #else /* NOPROTO */ void sr_SHA256_Init(); void sr_SHA256_Update(); void sr_SHA256_Final(); -char* sr_SHA256_End(); -char* sr_SHA256_Data(); +char *sr_SHA256_End(); +char *sr_SHA256_Data(); void sr_SHA384_Init(); void sr_SHA384_Update(); void sr_SHA384_Final(); -char* sr_SHA384_End(); -char* sr_SHA384_Data(); +char *sr_SHA384_End(); +char *sr_SHA384_Data(); void sr_SHA512_Init(); void sr_SHA512_256_Init(); void sr_SHA512_Update(); void sr_SHA512_Final(); -char* sr_SHA512_End(); -char* sr_SHA512_Data(); +char *sr_SHA512_End(); +char *sr_SHA512_Data(); #endif /* NOPROTO */ -#ifdef __cplusplus +#ifdef __cplusplus } #endif /* __cplusplus */ diff --git a/src/core/crypto/shautils.c b/src/core/crypto/shautils.c index 582b54e1b15..ca0ff5aa790 100644 --- a/src/core/crypto/shautils.c +++ b/src/core/crypto/shautils.c @@ -39,9 +39,9 @@ void compute_md5(char *dst, char *src, int src_len) { MD5_CTX context; unsigned char digest[16]; - MD5Init (&context); - MD5Update (&context, src, src_len); - U_MD5Final (digest, &context); + MD5Init(&context); + MD5Update(&context, src, src_len); + U_MD5Final(digest, &context); string2hex(digest, 16, dst); } From cbc6a0fe229435f0345828dbb6c8e78ae0c5ca94 Mon Sep 17 00:00:00 2001 From: Victor Seva Date: Thu, 18 May 2023 15:22:08 +0200 Subject: [PATCH 05/14] core: [mem] clang-format for coherent indentation and coding style --- src/core/mem/dl_malloc.c | 5288 ++++++++++++++++--------------- src/core/mem/dl_malloc.h | 210 +- src/core/mem/f_malloc.c | 888 +++--- src/core/mem/f_malloc.h | 101 +- src/core/mem/ll_malloc.c | 1001 +++--- src/core/mem/ll_malloc.h | 99 +- src/core/mem/mem.h | 1 - src/core/mem/memapi.h | 104 +- src/core/mem/memdbg.h | 21 +- src/core/mem/meminfo.h | 50 +- src/core/mem/memtest.c | 26 +- src/core/mem/pkg.c | 47 +- src/core/mem/pkg.h | 233 +- src/core/mem/q_malloc.c | 1156 +++---- src/core/mem/q_malloc.h | 104 +- src/core/mem/sf_malloc.c | 83 +- src/core/mem/sf_malloc.h | 105 +- src/core/mem/shm.c | 110 +- src/core/mem/shm.h | 95 +- src/core/mem/shm_mem.h | 1 - src/core/mem/src_loc.h | 40 +- src/core/mem/tlsf_malloc.c | 855 ++--- src/core/mem/tlsf_malloc.h | 105 +- src/core/mem/tlsf_malloc_bits.h | 51 +- 24 files changed, 5528 insertions(+), 5246 deletions(-) diff --git a/src/core/mem/dl_malloc.c b/src/core/mem/dl_malloc.c index f4c5da82b54..d67a02f2019 100644 --- a/src/core/mem/dl_malloc.c +++ b/src/core/mem/dl_malloc.c @@ -363,9 +363,9 @@ MALLINFO_FIELD_TYPE default: size_t size_t. The value is used only if HAVE_USR_INCLUDE_MALLOC_H is not set REALLOC_ZERO_BYTES_FREES default: not defined - This should be set if a call to realloc with zero bytes should - be the same as a call to free. Some people think it should. Otherwise, - since this malloc returns a unique pointer for malloc(0), so does + This should be set if a call to realloc with zero bytes should + be the same as a call to free. Some people think it should. Otherwise, + since this malloc returns a unique pointer for malloc(0), so does realloc(p, 0). LACKS_UNISTD_H, LACKS_FCNTL_H, LACKS_SYS_PARAM_H, LACKS_SYS_MMAN_H @@ -445,8 +445,8 @@ DEFAULT_MMAP_THRESHOLD default: 256K #ifndef WIN32 #ifdef _WIN32 #define WIN32 1 -#endif /* _WIN32 */ -#endif /* WIN32 */ +#endif /* _WIN32 */ +#endif /* WIN32 */ #ifdef WIN32 #define WIN32_LEAN_AND_MEAN #include @@ -461,120 +461,120 @@ DEFAULT_MMAP_THRESHOLD default: 256K #define LACKS_ERRNO_H #define MALLOC_FAILURE_ACTION #define MMAP_CLEARS 0 /* WINCE and some others apparently don't clear */ -#endif /* WIN32 */ +#endif /* WIN32 */ #if defined(DARWIN) || defined(_DARWIN) /* Mac OSX docs advise not to use sbrk; it seems better to use mmap */ #ifndef HAVE_MORECORE #define HAVE_MORECORE 0 #define HAVE_MMAP 1 -#endif /* HAVE_MORECORE */ -#endif /* DARWIN */ +#endif /* HAVE_MORECORE */ +#endif /* DARWIN */ #ifndef LACKS_SYS_TYPES_H -#include /* For size_t */ -#endif /* LACKS_SYS_TYPES_H */ +#include /* For size_t */ +#endif /* LACKS_SYS_TYPES_H */ /* The maximum possible size_t value has all bits set */ -#define MAX_SIZE_T (~(size_t)0) +#define MAX_SIZE_T (~(size_t)0) #ifndef ONLY_MSPACES #define ONLY_MSPACES 0 -#endif /* ONLY_MSPACES */ +#endif /* ONLY_MSPACES */ #ifndef MSPACES #if ONLY_MSPACES #define MSPACES 1 -#else /* ONLY_MSPACES */ +#else /* ONLY_MSPACES */ #define MSPACES 0 -#endif /* ONLY_MSPACES */ -#endif /* MSPACES */ +#endif /* ONLY_MSPACES */ +#endif /* MSPACES */ #ifndef MALLOC_ALIGNMENT #define MALLOC_ALIGNMENT ((size_t)8U) -#endif /* MALLOC_ALIGNMENT */ +#endif /* MALLOC_ALIGNMENT */ #ifndef FOOTERS #define FOOTERS 0 -#endif /* FOOTERS */ +#endif /* FOOTERS */ #ifndef ABORT -#define ABORT abort() -#endif /* ABORT */ +#define ABORT abort() +#endif /* ABORT */ #ifndef ABORT_ON_ASSERT_FAILURE #define ABORT_ON_ASSERT_FAILURE 1 -#endif /* ABORT_ON_ASSERT_FAILURE */ +#endif /* ABORT_ON_ASSERT_FAILURE */ #ifndef PROCEED_ON_ERROR #define PROCEED_ON_ERROR 0 -#endif /* PROCEED_ON_ERROR */ +#endif /* PROCEED_ON_ERROR */ #ifndef USE_LOCKS #define USE_LOCKS 0 -#endif /* USE_LOCKS */ +#endif /* USE_LOCKS */ #ifndef INSECURE #define INSECURE 0 -#endif /* INSECURE */ +#endif /* INSECURE */ #ifndef HAVE_MMAP #define HAVE_MMAP 1 -#endif /* HAVE_MMAP */ +#endif /* HAVE_MMAP */ #ifndef MMAP_CLEARS #define MMAP_CLEARS 1 -#endif /* MMAP_CLEARS */ +#endif /* MMAP_CLEARS */ #ifndef HAVE_MREMAP #ifdef linux #define HAVE_MREMAP 1 -#else /* linux */ +#else /* linux */ #define HAVE_MREMAP 0 -#endif /* linux */ -#endif /* HAVE_MREMAP */ +#endif /* linux */ +#endif /* HAVE_MREMAP */ #ifndef MALLOC_FAILURE_ACTION -#define MALLOC_FAILURE_ACTION errno = ENOMEM; -#endif /* MALLOC_FAILURE_ACTION */ +#define MALLOC_FAILURE_ACTION errno = ENOMEM; +#endif /* MALLOC_FAILURE_ACTION */ #ifndef HAVE_MORECORE #if ONLY_MSPACES #define HAVE_MORECORE 0 -#else /* ONLY_MSPACES */ +#else /* ONLY_MSPACES */ #define HAVE_MORECORE 1 -#endif /* ONLY_MSPACES */ -#endif /* HAVE_MORECORE */ +#endif /* ONLY_MSPACES */ +#endif /* HAVE_MORECORE */ #if !HAVE_MORECORE #define MORECORE_CONTIGUOUS 0 -#else /* !HAVE_MORECORE */ +#else /* !HAVE_MORECORE */ #ifndef MORECORE #define MORECORE sbrk -#endif /* MORECORE */ +#endif /* MORECORE */ #ifndef MORECORE_CONTIGUOUS #define MORECORE_CONTIGUOUS 1 -#endif /* MORECORE_CONTIGUOUS */ -#endif /* HAVE_MORECORE */ +#endif /* MORECORE_CONTIGUOUS */ +#endif /* HAVE_MORECORE */ #ifndef DEFAULT_GRANULARITY #if MORECORE_CONTIGUOUS -#define DEFAULT_GRANULARITY (0) /* 0 means to compute in init_mparams */ -#else /* MORECORE_CONTIGUOUS */ +#define DEFAULT_GRANULARITY (0) /* 0 means to compute in init_mparams */ +#else /* MORECORE_CONTIGUOUS */ #define DEFAULT_GRANULARITY ((size_t)64U * (size_t)1024U) -#endif /* MORECORE_CONTIGUOUS */ -#endif /* DEFAULT_GRANULARITY */ +#endif /* MORECORE_CONTIGUOUS */ +#endif /* DEFAULT_GRANULARITY */ #ifndef DEFAULT_TRIM_THRESHOLD #ifndef MORECORE_CANNOT_TRIM #define DEFAULT_TRIM_THRESHOLD ((size_t)2U * (size_t)1024U * (size_t)1024U) -#else /* MORECORE_CANNOT_TRIM */ +#else /* MORECORE_CANNOT_TRIM */ #define DEFAULT_TRIM_THRESHOLD MAX_SIZE_T -#endif /* MORECORE_CANNOT_TRIM */ -#endif /* DEFAULT_TRIM_THRESHOLD */ +#endif /* MORECORE_CANNOT_TRIM */ +#endif /* DEFAULT_TRIM_THRESHOLD */ #ifndef DEFAULT_MMAP_THRESHOLD #if HAVE_MMAP #define DEFAULT_MMAP_THRESHOLD ((size_t)256U * (size_t)1024U) -#else /* HAVE_MMAP */ +#else /* HAVE_MMAP */ #define DEFAULT_MMAP_THRESHOLD MAX_SIZE_T -#endif /* HAVE_MMAP */ -#endif /* DEFAULT_MMAP_THRESHOLD */ +#endif /* HAVE_MMAP */ +#endif /* DEFAULT_MMAP_THRESHOLD */ #ifndef USE_BUILTIN_FFS #define USE_BUILTIN_FFS 0 -#endif /* USE_BUILTIN_FFS */ +#endif /* USE_BUILTIN_FFS */ #ifndef USE_DEV_RANDOM #define USE_DEV_RANDOM 0 -#endif /* USE_DEV_RANDOM */ +#endif /* USE_DEV_RANDOM */ #ifndef NO_MALLINFO #define NO_MALLINFO 0 -#endif /* NO_MALLINFO */ +#endif /* NO_MALLINFO */ #ifndef MALLINFO_FIELD_TYPE #define MALLINFO_FIELD_TYPE size_t -#endif /* MALLINFO_FIELD_TYPE */ +#endif /* MALLINFO_FIELD_TYPE */ /* mallopt tuning options. SVID/XPG defines four standard parameter @@ -583,9 +583,9 @@ DEFAULT_MMAP_THRESHOLD default: 256K malloc does support the following options. */ -#define M_TRIM_THRESHOLD (-1) -#define M_GRANULARITY (-2) -#define M_MMAP_THRESHOLD (-3) +#define M_TRIM_THRESHOLD (-1) +#define M_GRANULARITY (-2) +#define M_MMAP_THRESHOLD (-3) /* ------------------------ Mallinfo declarations ------------------------ */ @@ -618,51 +618,53 @@ DEFAULT_MMAP_THRESHOLD default: 256K #include "/usr/include/malloc.h" #else /* HAVE_USR_INCLUDE_MALLOC_H */ -struct mallinfo { - MALLINFO_FIELD_TYPE arena; /* non-mmapped space allocated from system */ - MALLINFO_FIELD_TYPE ordblks; /* number of free chunks */ - MALLINFO_FIELD_TYPE smblks; /* always 0 */ - MALLINFO_FIELD_TYPE hblks; /* always 0 */ - MALLINFO_FIELD_TYPE hblkhd; /* space in mmapped regions */ - MALLINFO_FIELD_TYPE usmblks; /* maximum total allocated space */ - MALLINFO_FIELD_TYPE fsmblks; /* always 0 */ - MALLINFO_FIELD_TYPE uordblks; /* total allocated space */ - MALLINFO_FIELD_TYPE fordblks; /* total free space */ - MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */ +struct mallinfo +{ + MALLINFO_FIELD_TYPE arena; /* non-mmapped space allocated from system */ + MALLINFO_FIELD_TYPE ordblks; /* number of free chunks */ + MALLINFO_FIELD_TYPE smblks; /* always 0 */ + MALLINFO_FIELD_TYPE hblks; /* always 0 */ + MALLINFO_FIELD_TYPE hblkhd; /* space in mmapped regions */ + MALLINFO_FIELD_TYPE usmblks; /* maximum total allocated space */ + MALLINFO_FIELD_TYPE fsmblks; /* always 0 */ + MALLINFO_FIELD_TYPE uordblks; /* total allocated space */ + MALLINFO_FIELD_TYPE fordblks; /* total free space */ + MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */ }; #endif /* HAVE_USR_INCLUDE_MALLOC_H */ #endif /* NO_MALLINFO */ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif /* __cplusplus */ #if !ONLY_MSPACES -/* ------------------- Declarations of public routines ------------------- */ + /* ------------------- Declarations of public routines ------------------- */ #ifndef USE_DL_PREFIX -#define dlcalloc calloc -#define dlfree free -#define dlmalloc malloc -#define dlmemalign memalign -#define dlrealloc realloc -#define dlvalloc valloc -#define dlpvalloc pvalloc -#define dlmallinfo mallinfo -#define dlmallopt mallopt -#define dlmalloc_trim malloc_trim -#define dlmalloc_stats malloc_stats -#define dlmalloc_usable_size malloc_usable_size -#define dlmalloc_footprint malloc_footprint +#define dlcalloc calloc +#define dlfree free +#define dlmalloc malloc +#define dlmemalign memalign +#define dlrealloc realloc +#define dlvalloc valloc +#define dlpvalloc pvalloc +#define dlmallinfo mallinfo +#define dlmallopt mallopt +#define dlmalloc_trim malloc_trim +#define dlmalloc_stats malloc_stats +#define dlmalloc_usable_size malloc_usable_size +#define dlmalloc_footprint malloc_footprint #define dlmalloc_max_footprint malloc_max_footprint -#define dlindependent_calloc independent_calloc +#define dlindependent_calloc independent_calloc #define dlindependent_comalloc independent_comalloc #endif /* USE_DL_PREFIX */ -/* + /* malloc(size_t n) Returns a pointer to a newly allocated chunk of at least n bytes, or null if no space is available, in which case errno is set to ENOMEM @@ -676,25 +678,25 @@ extern "C" { maximum supported value of n differs across systems, but is in all cases less than the maximum representable value of a size_t. */ -void* dlmalloc(size_t); + void *dlmalloc(size_t); -/* + /* free(void* p) Releases the chunk of memory pointed to by p, that had been previously allocated using malloc or a related routine such as realloc. It has no effect if p is null. If p was not malloced or already freed, free(p) will by default cause the current program to abort. */ -void dlfree(void*); + void dlfree(void *); -/* + /* calloc(size_t n_elements, size_t element_size); Returns a pointer to n_elements * element_size bytes, with all locations set to zero. */ -void* dlcalloc(size_t, size_t); + void *dlcalloc(size_t, size_t); -/* + /* realloc(void* p, size_t n) Returns a pointer to a chunk of size n that contains the same data as does chunk p up to the minimum of (n, p's size) bytes, or null @@ -717,9 +719,9 @@ void* dlcalloc(size_t, size_t); to be used as an argument to realloc is not supported. */ -void* dlrealloc(void*, size_t); + void *dlrealloc(void *, size_t); -/* + /* memalign(size_t alignment, size_t n); Returns a pointer to a newly allocated chunk of n bytes, aligned in accord with the alignment argument. @@ -731,16 +733,16 @@ void* dlrealloc(void*, size_t); Overreliance on memalign is a sure way to fragment space. */ -void* dlmemalign(size_t, size_t); + void *dlmemalign(size_t, size_t); -/* + /* valloc(size_t n); Equivalent to memalign(pagesize, n), where pagesize is the page size of the system. If the pagesize is unknown, 4096 is used. */ -void* dlvalloc(size_t); + void *dlvalloc(size_t); -/* + /* mallopt(int parameter_number, int parameter_value) Sets tunable parameters The format is to provide a (parameter-number, parameter-value) pair. mallopt then sets the @@ -758,9 +760,9 @@ void* dlvalloc(size_t); M_GRANULARITY -2 page size any power of 2 >= page size M_MMAP_THRESHOLD -3 256*1024 any (or 0 if no MMAP support) */ -int dlmallopt(int, int); + int dlmallopt(int, int); -/* + /* malloc_footprint(); Returns the number of bytes obtained from the system. The total number of bytes allocated by malloc, realloc etc., is less than this @@ -769,9 +771,9 @@ int dlmallopt(int, int); Even if locks are otherwise defined, this function does not use them, so results might not be up to date. */ -size_t dlmalloc_footprint(void); + size_t dlmalloc_footprint(void); -/* + /* malloc_max_footprint(); Returns the maximum number of bytes obtained from the system. This value will be greater than current footprint if deallocated space @@ -782,10 +784,10 @@ size_t dlmalloc_footprint(void); otherwise defined, this function does not use them, so results might not be up to date. */ -size_t dlmalloc_max_footprint(void); + size_t dlmalloc_max_footprint(void); #if !NO_MALLINFO -/* + /* mallinfo() Returns (by copy) a struct containing various summary statistics: @@ -807,10 +809,10 @@ size_t dlmalloc_max_footprint(void); be kept as longs, the reported values may wrap around zero and thus be inaccurate. */ -struct mallinfo dlmallinfo(void); + struct mallinfo dlmallinfo(void); #endif /* NO_MALLINFO */ -/* + /* independent_calloc(size_t n_elements, size_t element_size, void* chunks[]); independent_calloc is similar to calloc, but instead of returning a @@ -862,9 +864,9 @@ struct mallinfo dlmallinfo(void); return first; } */ -void** dlindependent_calloc(size_t, size_t, void**); + void **dlindependent_calloc(size_t, size_t, void **); -/* + /* independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]); independent_comalloc allocates, all at once, a set of n_elements @@ -923,17 +925,17 @@ void** dlindependent_calloc(size_t, size_t, void**); since it cannot reuse existing noncontiguous small chunks that might be available for some of the elements. */ -void** dlindependent_comalloc(size_t, size_t*, void**); + void **dlindependent_comalloc(size_t, size_t *, void **); -/* + /* pvalloc(size_t n); Equivalent to valloc(minimum-page-that-holds(n)), that is, round up n to nearest pagesize. */ -void* dlpvalloc(size_t); + void *dlpvalloc(size_t); -/* + /* malloc_trim(size_t pad); If possible, gives memory back to the system (via negative arguments @@ -954,9 +956,9 @@ void* dlpvalloc(size_t); Malloc_trim returns 1 if it actually released any memory, else 0. */ -int dlmalloc_trim(size_t); + int dlmalloc_trim(size_t); -/* + /* malloc_usable_size(void* p); Returns the number of bytes you can actually use in @@ -970,9 +972,9 @@ int dlmalloc_trim(size_t); p = malloc(n); assert(malloc_usable_size(p) >= 256); */ -size_t dlmalloc_usable_size(void*); + size_t dlmalloc_usable_size(void *); -/* + /* malloc_stats(); Prints on stderr the amount of space obtained from the system (both via sbrk and mmap), the maximum amount (which may be more than @@ -991,19 +993,19 @@ size_t dlmalloc_usable_size(void*); malloc_stats prints only the most commonly interesting statistics. More information can be obtained by calling mallinfo. */ -void dlmalloc_stats(void); + void dlmalloc_stats(void); #endif /* ONLY_MSPACES */ #if MSPACES -/* + /* mspace is an opaque type representing an independent region of space that supports mspace_malloc, etc. */ -typedef void* mspace; + typedef void *mspace; -/* + /* create_mspace creates and returns a new independent space with the given initial capacity, or, if 0, the default granularity size. It returns null if there is no system memory available to create the @@ -1014,17 +1016,17 @@ typedef void* mspace; compiling with a different DEFAULT_GRANULARITY or dynamically setting with mallopt(M_GRANULARITY, value). */ -mspace create_mspace(size_t capacity, int locked); + mspace create_mspace(size_t capacity, int locked); -/* + /* destroy_mspace destroys the given space, and attempts to return all of its memory back to the system, returning the total number of bytes freed. After destruction, the results of access to all memory used by the space become undefined. */ -size_t destroy_mspace(mspace msp); + size_t destroy_mspace(mspace msp); -/* + /* create_mspace_with_base uses the memory supplied as the initial base of a new mspace. Part (less than 128*sizeof(size_t) bytes) of this space is used for bookkeeping, so the capacity must be at least this @@ -1033,15 +1035,15 @@ size_t destroy_mspace(mspace msp); Destroying this space will deallocate all additionally allocated space (if possible) but not the initial base. */ -mspace create_mspace_with_base(void* base, size_t capacity, int locked); + mspace create_mspace_with_base(void *base, size_t capacity, int locked); -/* + /* mspace_malloc behaves as malloc, but operates within the given space. */ -void* mspace_malloc(mspace msp, size_t bytes); + void *mspace_malloc(mspace msp, size_t bytes); -/* + /* mspace_free behaves as free, but operates within the given space. @@ -1049,9 +1051,9 @@ void* mspace_malloc(mspace msp, size_t bytes); free may be called instead of mspace_free because freed chunks from any space are handled by their originating spaces. */ -void mspace_free(mspace msp, void* mem); + void mspace_free(mspace msp, void *mem); -/* + /* mspace_realloc behaves as realloc, but operates within the given space. @@ -1060,79 +1062,79 @@ void mspace_free(mspace msp, void* mem); realloced chunks from any space are handled by their originating spaces. */ -void* mspace_realloc(mspace msp, void* mem, size_t newsize); + void *mspace_realloc(mspace msp, void *mem, size_t newsize); -/* + /* mspace_calloc behaves as calloc, but operates within the given space. */ -void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size); + void *mspace_calloc(mspace msp, size_t n_elements, size_t elem_size); -/* + /* mspace_memalign behaves as memalign, but operates within the given space. */ -void* mspace_memalign(mspace msp, size_t alignment, size_t bytes); + void *mspace_memalign(mspace msp, size_t alignment, size_t bytes); -/* + /* mspace_independent_calloc behaves as independent_calloc, but operates within the given space. */ -void** mspace_independent_calloc(mspace msp, size_t n_elements, - size_t elem_size, void* chunks[]); + void **mspace_independent_calloc( + mspace msp, size_t n_elements, size_t elem_size, void *chunks[]); -/* + /* mspace_independent_comalloc behaves as independent_comalloc, but operates within the given space. */ -void** mspace_independent_comalloc(mspace msp, size_t n_elements, - size_t sizes[], void* chunks[]); + void **mspace_independent_comalloc( + mspace msp, size_t n_elements, size_t sizes[], void *chunks[]); -/* + /* mspace_footprint() returns the number of bytes obtained from the system for this space. */ -size_t mspace_footprint(mspace msp); + size_t mspace_footprint(mspace msp); -/* + /* mspace_max_footprint() returns the peak number of bytes obtained from the system for this space. */ -size_t mspace_max_footprint(mspace msp); + size_t mspace_max_footprint(mspace msp); #if !NO_MALLINFO -/* + /* mspace_mallinfo behaves as mallinfo, but reports properties of the given space. */ -struct mallinfo mspace_mallinfo(mspace msp); + struct mallinfo mspace_mallinfo(mspace msp); #endif /* NO_MALLINFO */ -/* + /* mspace_malloc_stats behaves as malloc_stats, but reports properties of the given space. */ -void mspace_malloc_stats(mspace msp); + void mspace_malloc_stats(mspace msp); -/* + /* mspace_trim behaves as malloc_trim, but operates within the given space. */ -int mspace_trim(mspace msp, size_t pad); + int mspace_trim(mspace msp, size_t pad); -/* + /* An alias for mallopt. */ -int mspace_mallopt(int, int); + int mspace_mallopt(int, int); #endif /* MSPACES */ #ifdef __cplusplus -}; /* end of extern "C" */ +}; /* end of extern "C" */ #endif /* __cplusplus */ -/* + /* ======================================================================== To make a fully customizable malloc.h header file, cut everything above this line, put into file malloc.h, edit to suit, and #include it @@ -1140,28 +1142,30 @@ int mspace_mallopt(int, int); ======================================================================== */ -/* #include "malloc.h" */ + /* #include "malloc.h" */ -/*------------------------------ internal #includes ---------------------- */ + /*------------------------------ internal #includes ---------------------- */ #ifdef WIN32 -#pragma warning( disable : 4146 ) /* no "unsigned" warnings */ -#endif /* WIN32 */ +#pragma warning(disable : 4146) /* no "unsigned" warnings */ +#endif /* WIN32 */ -#include /* for printing in malloc_stats */ +#include /* for printing in malloc_stats */ #ifndef LACKS_ERRNO_H -#include /* for MALLOC_FAILURE_ACTION */ -#endif /* LACKS_ERRNO_H */ +#include /* for MALLOC_FAILURE_ACTION */ +#endif /* LACKS_ERRNO_H */ #if FOOTERS -#include /* for magic initialization */ -#endif /* FOOTERS */ +#include /* for magic initialization */ +#endif /* FOOTERS */ #ifndef LACKS_STDLIB_H -#include /* for abort() */ -#endif /* LACKS_STDLIB_H */ +#include /* for abort() */ +#endif /* LACKS_STDLIB_H */ #ifdef DEBUG #if ABORT_ON_ASSERT_FAILURE -#define assert(x) if(!(x)) ABORT +#define assert(x) \ + if(!(x)) \ + ABORT #else /* ABORT_ON_ASSERT_FAILURE */ #include #endif /* ABORT_ON_ASSERT_FAILURE */ @@ -1169,104 +1173,106 @@ int mspace_mallopt(int, int); #define assert(x) #endif /* DEBUG */ #ifndef LACKS_STRING_H -#include /* for memset etc */ -#endif /* LACKS_STRING_H */ +#include /* for memset etc */ +#endif /* LACKS_STRING_H */ #if USE_BUILTIN_FFS #ifndef LACKS_STRINGS_H -#include /* for ffs */ -#endif /* LACKS_STRINGS_H */ -#endif /* USE_BUILTIN_FFS */ +#include /* for ffs */ +#endif /* LACKS_STRINGS_H */ +#endif /* USE_BUILTIN_FFS */ #if HAVE_MMAP #ifndef LACKS_SYS_MMAN_H -#include /* for mmap */ -#endif /* LACKS_SYS_MMAN_H */ +#include /* for mmap */ +#endif /* LACKS_SYS_MMAN_H */ #ifndef LACKS_FCNTL_H #include #endif /* LACKS_FCNTL_H */ #endif /* HAVE_MMAP */ #if HAVE_MORECORE #ifndef LACKS_UNISTD_H -#include /* for sbrk */ -#else /* LACKS_UNISTD_H */ +#include /* for sbrk */ +#else /* LACKS_UNISTD_H */ #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__) -extern void* sbrk(ptrdiff_t); +extern void *sbrk(ptrdiff_t); #endif /* FreeBSD etc */ #endif /* LACKS_UNISTD_H */ #endif /* HAVE_MORECORE */ #ifndef WIN32 #ifndef malloc_getpagesize -# ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */ -# ifndef _SC_PAGE_SIZE -# define _SC_PAGE_SIZE _SC_PAGESIZE -# endif -# endif -# ifdef _SC_PAGE_SIZE -# define malloc_getpagesize sysconf(_SC_PAGE_SIZE) -# else -# if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE) - extern size_t getpagesize(); -# define malloc_getpagesize getpagesize() -# else -# ifdef WIN32 /* use supplied emulation of getpagesize */ -# define malloc_getpagesize getpagesize() -# else -# ifndef LACKS_SYS_PARAM_H -# include -# endif -# ifdef EXEC_PAGESIZE -# define malloc_getpagesize EXEC_PAGESIZE -# else -# ifdef NBPG -# ifndef CLSIZE -# define malloc_getpagesize NBPG -# else -# define malloc_getpagesize (NBPG * CLSIZE) -# endif -# else -# ifdef NBPC -# define malloc_getpagesize NBPC -# else -# ifdef PAGESIZE -# define malloc_getpagesize PAGESIZE -# else /* just guess */ -# define malloc_getpagesize ((size_t)4096U) -# endif -# endif -# endif -# endif -# endif -# endif -# endif +#ifdef _SC_PAGESIZE /* some SVR4 systems omit an underscore */ +#ifndef _SC_PAGE_SIZE +#define _SC_PAGE_SIZE _SC_PAGESIZE +#endif +#endif +#ifdef _SC_PAGE_SIZE +#define malloc_getpagesize sysconf(_SC_PAGE_SIZE) +#else +#if defined(BSD) || defined(DGUX) || defined(HAVE_GETPAGESIZE) +extern size_t getpagesize(); +#define malloc_getpagesize getpagesize() +#else +#ifdef WIN32 /* use supplied emulation of getpagesize */ +#define malloc_getpagesize getpagesize() +#else +#ifndef LACKS_SYS_PARAM_H +#include +#endif +#ifdef EXEC_PAGESIZE +#define malloc_getpagesize EXEC_PAGESIZE +#else +#ifdef NBPG +#ifndef CLSIZE +#define malloc_getpagesize NBPG +#else +#define malloc_getpagesize (NBPG * CLSIZE) +#endif +#else +#ifdef NBPC +#define malloc_getpagesize NBPC +#else +#ifdef PAGESIZE +#define malloc_getpagesize PAGESIZE +#else /* just guess */ +#define malloc_getpagesize ((size_t)4096U) +#endif +#endif +#endif +#endif +#endif +#endif +#endif #endif #endif /* ------------------- size_t and alignment properties -------------------- */ /* The byte and bit size of a size_t */ -#define SIZE_T_SIZE (sizeof(size_t)) -#define SIZE_T_BITSIZE (sizeof(size_t) << 3) +#define SIZE_T_SIZE (sizeof(size_t)) +#define SIZE_T_BITSIZE (sizeof(size_t) << 3) /* Some constants coerced to size_t */ /* Annoying but necessary to avoid errors on some plaftorms */ -#define SIZE_T_ZERO ((size_t)0) -#define SIZE_T_ONE ((size_t)1) -#define SIZE_T_TWO ((size_t)2) -#define TWO_SIZE_T_SIZES (SIZE_T_SIZE<<1) -#define FOUR_SIZE_T_SIZES (SIZE_T_SIZE<<2) -#define SIX_SIZE_T_SIZES (FOUR_SIZE_T_SIZES+TWO_SIZE_T_SIZES) -#define HALF_MAX_SIZE_T (MAX_SIZE_T / 2U) +#define SIZE_T_ZERO ((size_t)0) +#define SIZE_T_ONE ((size_t)1) +#define SIZE_T_TWO ((size_t)2) +#define TWO_SIZE_T_SIZES (SIZE_T_SIZE << 1) +#define FOUR_SIZE_T_SIZES (SIZE_T_SIZE << 2) +#define SIX_SIZE_T_SIZES (FOUR_SIZE_T_SIZES + TWO_SIZE_T_SIZES) +#define HALF_MAX_SIZE_T (MAX_SIZE_T / 2U) /* The bit mask value corresponding to MALLOC_ALIGNMENT */ -#define CHUNK_ALIGN_MASK (MALLOC_ALIGNMENT - SIZE_T_ONE) +#define CHUNK_ALIGN_MASK (MALLOC_ALIGNMENT - SIZE_T_ONE) /* True if address A has acceptable alignment */ -#define is_aligned(A) (((size_t)((A)) & (CHUNK_ALIGN_MASK)) == 0) +#define is_aligned(A) (((size_t)((A)) & (CHUNK_ALIGN_MASK)) == 0) /* the number of bytes to offset an address to align it */ -#define align_offset(A)\ - ((((size_t)(A) & CHUNK_ALIGN_MASK) == 0)? 0 :\ - ((MALLOC_ALIGNMENT - ((size_t)(A) & CHUNK_ALIGN_MASK)) & CHUNK_ALIGN_MASK)) +#define align_offset(A) \ + ((((size_t)(A)&CHUNK_ALIGN_MASK) == 0) \ + ? 0 \ + : ((MALLOC_ALIGNMENT - ((size_t)(A)&CHUNK_ALIGN_MASK)) \ + & CHUNK_ALIGN_MASK)) /* -------------------------- MMAP preliminaries ------------------------- */ @@ -1278,106 +1284,109 @@ extern void* sbrk(ptrdiff_t); /* MORECORE and MMAP must return MFAIL on failure */ -#define MFAIL ((void*)(MAX_SIZE_T)) -#define CMFAIL ((char*)(MFAIL)) /* defined for convenience */ +#define MFAIL ((void *)(MAX_SIZE_T)) +#define CMFAIL ((char *)(MFAIL)) /* defined for convenience */ #if !HAVE_MMAP -#define IS_MMAPPED_BIT (SIZE_T_ZERO) -#define USE_MMAP_BIT (SIZE_T_ZERO) -#define CALL_MMAP(s) MFAIL -#define CALL_MUNMAP(a, s) (-1) -#define DIRECT_MMAP(s) MFAIL +#define IS_MMAPPED_BIT (SIZE_T_ZERO) +#define USE_MMAP_BIT (SIZE_T_ZERO) +#define CALL_MMAP(s) MFAIL +#define CALL_MUNMAP(a, s) (-1) +#define DIRECT_MMAP(s) MFAIL #else /* HAVE_MMAP */ -#define IS_MMAPPED_BIT (SIZE_T_ONE) -#define USE_MMAP_BIT (SIZE_T_ONE) +#define IS_MMAPPED_BIT (SIZE_T_ONE) +#define USE_MMAP_BIT (SIZE_T_ONE) #ifndef WIN32 -#define CALL_MUNMAP(a, s) munmap((a), (s)) -#define MMAP_PROT (PROT_READ|PROT_WRITE) +#define CALL_MUNMAP(a, s) munmap((a), (s)) +#define MMAP_PROT (PROT_READ | PROT_WRITE) #if !defined(MAP_ANONYMOUS) && defined(MAP_ANON) -#define MAP_ANONYMOUS MAP_ANON +#define MAP_ANONYMOUS MAP_ANON #endif /* MAP_ANON */ #ifdef MAP_ANONYMOUS -#define MMAP_FLAGS (MAP_PRIVATE|MAP_ANONYMOUS) -#define CALL_MMAP(s) mmap(0, (s), MMAP_PROT, MMAP_FLAGS, -1, 0) +#define MMAP_FLAGS (MAP_PRIVATE | MAP_ANONYMOUS) +#define CALL_MMAP(s) mmap(0, (s), MMAP_PROT, MMAP_FLAGS, -1, 0) #else /* MAP_ANONYMOUS */ /* Nearly all versions of mmap support MAP_ANONYMOUS, so the following is unlikely to be needed, but is supplied just in case. */ -#define MMAP_FLAGS (MAP_PRIVATE) +#define MMAP_FLAGS (MAP_PRIVATE) static int dev_zero_fd = -1; /* Cached file descriptor for /dev/zero. */ -#define CALL_MMAP(s) ((dev_zero_fd < 0) ? \ - (dev_zero_fd = open("/dev/zero", O_RDWR), \ - mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) : \ - mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) +#define CALL_MMAP(s) \ + ((dev_zero_fd < 0) ? (dev_zero_fd = open("/dev/zero", O_RDWR), \ + mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) \ + : mmap(0, (s), MMAP_PROT, MMAP_FLAGS, dev_zero_fd, 0)) #endif /* MAP_ANONYMOUS */ -#define DIRECT_MMAP(s) CALL_MMAP(s) +#define DIRECT_MMAP(s) CALL_MMAP(s) #else /* WIN32 */ /* Win32 MMAP via VirtualAlloc */ -static void* win32mmap(size_t size) { - void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT, PAGE_READWRITE); - return (ptr != 0)? ptr: MFAIL; +static void *win32mmap(size_t size) +{ + void *ptr = VirtualAlloc(0, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + return (ptr != 0) ? ptr : MFAIL; } /* For direct MMAP, use MEM_TOP_DOWN to minimize interference */ -static void* win32direct_mmap(size_t size) { - void* ptr = VirtualAlloc(0, size, MEM_RESERVE|MEM_COMMIT|MEM_TOP_DOWN, - PAGE_READWRITE); - return (ptr != 0)? ptr: MFAIL; +static void *win32direct_mmap(size_t size) +{ + void *ptr = VirtualAlloc( + 0, size, MEM_RESERVE | MEM_COMMIT | MEM_TOP_DOWN, PAGE_READWRITE); + return (ptr != 0) ? ptr : MFAIL; } /* This function supports releasing coalesed segments */ -static int win32munmap(void* ptr, size_t size) { - MEMORY_BASIC_INFORMATION minfo; - char* cptr = ptr; - while (size) { - if (VirtualQuery(cptr, &minfo, sizeof(minfo)) == 0) - return -1; - if (minfo.BaseAddress != cptr || minfo.AllocationBase != cptr || - minfo.State != MEM_COMMIT || minfo.RegionSize > size) - return -1; - if (VirtualFree(cptr, 0, MEM_RELEASE) == 0) - return -1; - cptr += minfo.RegionSize; - size -= minfo.RegionSize; - } - return 0; +static int win32munmap(void *ptr, size_t size) +{ + MEMORY_BASIC_INFORMATION minfo; + char *cptr = ptr; + while(size) { + if(VirtualQuery(cptr, &minfo, sizeof(minfo)) == 0) + return -1; + if(minfo.BaseAddress != cptr || minfo.AllocationBase != cptr + || minfo.State != MEM_COMMIT || minfo.RegionSize > size) + return -1; + if(VirtualFree(cptr, 0, MEM_RELEASE) == 0) + return -1; + cptr += minfo.RegionSize; + size -= minfo.RegionSize; + } + return 0; } -#define CALL_MMAP(s) win32mmap(s) -#define CALL_MUNMAP(a, s) win32munmap((a), (s)) -#define DIRECT_MMAP(s) win32direct_mmap(s) +#define CALL_MMAP(s) win32mmap(s) +#define CALL_MUNMAP(a, s) win32munmap((a), (s)) +#define DIRECT_MMAP(s) win32direct_mmap(s) #endif /* WIN32 */ #endif /* HAVE_MMAP */ #if HAVE_MMAP && HAVE_MREMAP #define CALL_MREMAP(addr, osz, nsz, mv) mremap((addr), (osz), (nsz), (mv)) -#else /* HAVE_MMAP && HAVE_MREMAP */ +#else /* HAVE_MMAP && HAVE_MREMAP */ #define CALL_MREMAP(addr, osz, nsz, mv) MFAIL #endif /* HAVE_MMAP && HAVE_MREMAP */ #if HAVE_MORECORE -#define CALL_MORECORE(S) MORECORE(S) -#else /* HAVE_MORECORE */ -#define CALL_MORECORE(S) MFAIL +#define CALL_MORECORE(S) MORECORE(S) +#else /* HAVE_MORECORE */ +#define CALL_MORECORE(S) MFAIL #endif /* HAVE_MORECORE */ /* mstate bit set if contiguous morecore disabled or failed */ #define USE_NONCONTIGUOUS_BIT (4U) /* segment bit set in create_mspace_with_base */ -#define EXTERN_BIT (8U) +#define EXTERN_BIT (8U) -/* --------------------------- Lock preliminaries ------------------------ */ + /* --------------------------- Lock preliminaries ------------------------ */ #if USE_LOCKS -/* + /* When locks are defined, there are up to two global locks: * If HAVE_MORECORE, morecore_mutex protects sequences of calls to @@ -1395,9 +1404,9 @@ static int win32munmap(void* ptr, size_t size) { /* By default use posix locks */ #include #define MLOCK_T pthread_mutex_t -#define INITIAL_LOCK(l) pthread_mutex_init(l, NULL) -#define ACQUIRE_LOCK(l) pthread_mutex_lock(l) -#define RELEASE_LOCK(l) pthread_mutex_unlock(l) +#define INITIAL_LOCK(l) pthread_mutex_init(l, NULL) +#define ACQUIRE_LOCK(l) pthread_mutex_lock(l) +#define RELEASE_LOCK(l) pthread_mutex_unlock(l) #if HAVE_MORECORE static MLOCK_T morecore_mutex = PTHREAD_MUTEX_INITIALIZER; @@ -1412,50 +1421,52 @@ static MLOCK_T magic_init_mutex = PTHREAD_MUTEX_INITIALIZER; */ #define MLOCK_T long -static int win32_acquire_lock (MLOCK_T *sl) { - for (;;) { +static int win32_acquire_lock(MLOCK_T *sl) +{ + for(;;) { #ifdef InterlockedCompareExchangePointer - if (!InterlockedCompareExchange(sl, 1, 0)) - return 0; + if(!InterlockedCompareExchange(sl, 1, 0)) + return 0; #else /* Use older void* version */ - if (!InterlockedCompareExchange((void**)sl, (void*)1, (void*)0)) - return 0; + if(!InterlockedCompareExchange((void **)sl, (void *)1, (void *)0)) + return 0; #endif /* InterlockedCompareExchangePointer */ - Sleep (0); - } + Sleep(0); + } } -static void win32_release_lock (MLOCK_T *sl) { - InterlockedExchange (sl, 0); +static void win32_release_lock(MLOCK_T *sl) +{ + InterlockedExchange(sl, 0); } -#define INITIAL_LOCK(l) *(l)=0 -#define ACQUIRE_LOCK(l) win32_acquire_lock(l) -#define RELEASE_LOCK(l) win32_release_lock(l) +#define INITIAL_LOCK(l) *(l) = 0 +#define ACQUIRE_LOCK(l) win32_acquire_lock(l) +#define RELEASE_LOCK(l) win32_release_lock(l) #if HAVE_MORECORE static MLOCK_T morecore_mutex; #endif /* HAVE_MORECORE */ static MLOCK_T magic_init_mutex; #endif /* WIN32 */ -#define USE_LOCK_BIT (2U) -#else /* USE_LOCKS */ -#define USE_LOCK_BIT (0U) +#define USE_LOCK_BIT (2U) +#else /* USE_LOCKS */ +#define USE_LOCK_BIT (0U) #define INITIAL_LOCK(l) #endif /* USE_LOCKS */ #if USE_LOCKS && HAVE_MORECORE -#define ACQUIRE_MORECORE_LOCK() ACQUIRE_LOCK(&morecore_mutex); -#define RELEASE_MORECORE_LOCK() RELEASE_LOCK(&morecore_mutex); +#define ACQUIRE_MORECORE_LOCK() ACQUIRE_LOCK(&morecore_mutex); +#define RELEASE_MORECORE_LOCK() RELEASE_LOCK(&morecore_mutex); #else /* USE_LOCKS && HAVE_MORECORE */ #define ACQUIRE_MORECORE_LOCK() #define RELEASE_MORECORE_LOCK() #endif /* USE_LOCKS && HAVE_MORECORE */ #if USE_LOCKS -#define ACQUIRE_MAGIC_INIT_LOCK() ACQUIRE_LOCK(&magic_init_mutex); -#define RELEASE_MAGIC_INIT_LOCK() RELEASE_LOCK(&magic_init_mutex); -#else /* USE_LOCKS */ +#define ACQUIRE_MAGIC_INIT_LOCK() ACQUIRE_LOCK(&magic_init_mutex); +#define RELEASE_MAGIC_INIT_LOCK() RELEASE_LOCK(&magic_init_mutex); +#else /* USE_LOCKS */ #define ACQUIRE_MAGIC_INIT_LOCK() #define RELEASE_MAGIC_INIT_LOCK() #endif /* USE_LOCKS */ @@ -1598,56 +1609,56 @@ static MLOCK_T magic_init_mutex; */ -struct malloc_chunk { - size_t prev_foot; /* Size of previous chunk (if free). */ - size_t head; /* Size and inuse bits. */ - struct malloc_chunk* fd; /* double links -- used only if free. */ - struct malloc_chunk* bk; +struct malloc_chunk +{ + size_t prev_foot; /* Size of previous chunk (if free). */ + size_t head; /* Size and inuse bits. */ + struct malloc_chunk *fd; /* double links -- used only if free. */ + struct malloc_chunk *bk; }; -typedef struct malloc_chunk mchunk; -typedef struct malloc_chunk* mchunkptr; -typedef struct malloc_chunk* sbinptr; /* The type of bins of chunks */ -typedef unsigned int bindex_t; /* Described below */ -typedef unsigned int binmap_t; /* Described below */ -typedef unsigned int flag_t; /* The type of various bit flag sets */ +typedef struct malloc_chunk mchunk; +typedef struct malloc_chunk *mchunkptr; +typedef struct malloc_chunk *sbinptr; /* The type of bins of chunks */ +typedef unsigned int bindex_t; /* Described below */ +typedef unsigned int binmap_t; /* Described below */ +typedef unsigned int flag_t; /* The type of various bit flag sets */ /* ------------------- Chunks sizes and alignments ----------------------- */ -#define MCHUNK_SIZE (sizeof(mchunk)) +#define MCHUNK_SIZE (sizeof(mchunk)) #if FOOTERS -#define CHUNK_OVERHEAD (TWO_SIZE_T_SIZES) +#define CHUNK_OVERHEAD (TWO_SIZE_T_SIZES) #else /* FOOTERS */ -#define CHUNK_OVERHEAD (SIZE_T_SIZE) +#define CHUNK_OVERHEAD (SIZE_T_SIZE) #endif /* FOOTERS */ /* MMapped chunks need a second word of overhead ... */ #define MMAP_CHUNK_OVERHEAD (TWO_SIZE_T_SIZES) /* ... and additional padding for fake next-chunk at foot */ -#define MMAP_FOOT_PAD (FOUR_SIZE_T_SIZES) +#define MMAP_FOOT_PAD (FOUR_SIZE_T_SIZES) /* The smallest size we can malloc is an aligned minimal chunk */ -#define MIN_CHUNK_SIZE\ - ((MCHUNK_SIZE + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK) +#define MIN_CHUNK_SIZE ((MCHUNK_SIZE + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK) /* conversion from malloc headers to user pointers, and back */ -#define chunk2mem(p) ((void*)((char*)(p) + TWO_SIZE_T_SIZES)) -#define mem2chunk(mem) ((mchunkptr)((char*)(mem) - TWO_SIZE_T_SIZES)) +#define chunk2mem(p) ((void *)((char *)(p) + TWO_SIZE_T_SIZES)) +#define mem2chunk(mem) ((mchunkptr)((char *)(mem)-TWO_SIZE_T_SIZES)) /* chunk associated with aligned address A */ -#define align_as_chunk(A) (mchunkptr)((A) + align_offset(chunk2mem(A))) +#define align_as_chunk(A) (mchunkptr)((A) + align_offset(chunk2mem(A))) /* Bounds on request (not chunk) sizes. */ -#define MAX_REQUEST ((-MIN_CHUNK_SIZE) << 2) -#define MIN_REQUEST (MIN_CHUNK_SIZE - CHUNK_OVERHEAD - SIZE_T_ONE) +#define MAX_REQUEST ((-MIN_CHUNK_SIZE) << 2) +#define MIN_REQUEST (MIN_CHUNK_SIZE - CHUNK_OVERHEAD - SIZE_T_ONE) /* pad request bytes into a usable size */ #define pad_request(req) \ - (((req) + CHUNK_OVERHEAD + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK) + (((req) + CHUNK_OVERHEAD + CHUNK_ALIGN_MASK) & ~CHUNK_ALIGN_MASK) /* pad request, checking for minimum (but not maximum) */ #define request2size(req) \ - (((req) < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(req)) + (((req) < MIN_REQUEST) ? MIN_CHUNK_SIZE : pad_request(req)) /* ------------------ Operations on head and foot fields ----------------- */ @@ -1660,50 +1671,49 @@ typedef unsigned int flag_t; /* The type of various bit flag sets */ mmapped region to the base of the chunk. */ -#define PINUSE_BIT (SIZE_T_ONE) -#define CINUSE_BIT (SIZE_T_TWO) -#define INUSE_BITS (PINUSE_BIT|CINUSE_BIT) +#define PINUSE_BIT (SIZE_T_ONE) +#define CINUSE_BIT (SIZE_T_TWO) +#define INUSE_BITS (PINUSE_BIT | CINUSE_BIT) /* Head value for fenceposts */ -#define FENCEPOST_HEAD (INUSE_BITS|SIZE_T_SIZE) +#define FENCEPOST_HEAD (INUSE_BITS | SIZE_T_SIZE) /* extraction of fields from head words */ -#define cinuse(p) ((p)->head & CINUSE_BIT) -#define pinuse(p) ((p)->head & PINUSE_BIT) -#define chunksize(p) ((p)->head & ~(INUSE_BITS)) +#define cinuse(p) ((p)->head & CINUSE_BIT) +#define pinuse(p) ((p)->head & PINUSE_BIT) +#define chunksize(p) ((p)->head & ~(INUSE_BITS)) -#define clear_pinuse(p) ((p)->head &= ~PINUSE_BIT) -#define clear_cinuse(p) ((p)->head &= ~CINUSE_BIT) +#define clear_pinuse(p) ((p)->head &= ~PINUSE_BIT) +#define clear_cinuse(p) ((p)->head &= ~CINUSE_BIT) /* Treat space at ptr +/- offset as a chunk */ -#define chunk_plus_offset(p, s) ((mchunkptr)(((char*)(p)) + (s))) -#define chunk_minus_offset(p, s) ((mchunkptr)(((char*)(p)) - (s))) +#define chunk_plus_offset(p, s) ((mchunkptr)(((char *)(p)) + (s))) +#define chunk_minus_offset(p, s) ((mchunkptr)(((char *)(p)) - (s))) /* Ptr to next or previous physical malloc_chunk. */ -#define next_chunk(p) ((mchunkptr)( ((char*)(p)) + ((p)->head & ~INUSE_BITS))) -#define prev_chunk(p) ((mchunkptr)( ((char*)(p)) - ((p)->prev_foot) )) +#define next_chunk(p) ((mchunkptr)(((char *)(p)) + ((p)->head & ~INUSE_BITS))) +#define prev_chunk(p) ((mchunkptr)(((char *)(p)) - ((p)->prev_foot))) /* extract next chunk's pinuse bit */ -#define next_pinuse(p) ((next_chunk(p)->head) & PINUSE_BIT) +#define next_pinuse(p) ((next_chunk(p)->head) & PINUSE_BIT) /* Get/set size at footer */ -#define get_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot) -#define set_foot(p, s) (((mchunkptr)((char*)(p) + (s)))->prev_foot = (s)) +#define get_foot(p, s) (((mchunkptr)((char *)(p) + (s)))->prev_foot) +#define set_foot(p, s) (((mchunkptr)((char *)(p) + (s)))->prev_foot = (s)) /* Set size, pinuse bit, and foot */ -#define set_size_and_pinuse_of_free_chunk(p, s)\ - ((p)->head = (s|PINUSE_BIT), set_foot(p, s)) +#define set_size_and_pinuse_of_free_chunk(p, s) \ + ((p)->head = (s | PINUSE_BIT), set_foot(p, s)) /* Set size, pinuse bit, foot, and clear next pinuse */ -#define set_free_with_pinuse(p, s, n)\ - (clear_pinuse(n), set_size_and_pinuse_of_free_chunk(p, s)) +#define set_free_with_pinuse(p, s, n) \ + (clear_pinuse(n), set_size_and_pinuse_of_free_chunk(p, s)) -#define is_mmapped(p)\ - (!((p)->head & PINUSE_BIT) && ((p)->prev_foot & IS_MMAPPED_BIT)) +#define is_mmapped(p) \ + (!((p)->head & PINUSE_BIT) && ((p)->prev_foot & IS_MMAPPED_BIT)) /* Get the internal overhead associated with chunk p */ -#define overhead_for(p)\ - (is_mmapped(p)? MMAP_CHUNK_OVERHEAD : CHUNK_OVERHEAD) +#define overhead_for(p) (is_mmapped(p) ? MMAP_CHUNK_OVERHEAD : CHUNK_OVERHEAD) /* Return true if malloced space is not necessarily cleared */ #if MMAP_CLEARS @@ -1803,24 +1813,25 @@ nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ is of course much better. */ -struct malloc_tree_chunk { - /* The first four fields must be compatible with malloc_chunk */ - size_t prev_foot; - size_t head; - struct malloc_tree_chunk* fd; - struct malloc_tree_chunk* bk; - - struct malloc_tree_chunk* child[2]; - struct malloc_tree_chunk* parent; - bindex_t index; +struct malloc_tree_chunk +{ + /* The first four fields must be compatible with malloc_chunk */ + size_t prev_foot; + size_t head; + struct malloc_tree_chunk *fd; + struct malloc_tree_chunk *bk; + + struct malloc_tree_chunk *child[2]; + struct malloc_tree_chunk *parent; + bindex_t index; }; -typedef struct malloc_tree_chunk tchunk; -typedef struct malloc_tree_chunk* tchunkptr; -typedef struct malloc_tree_chunk* tbinptr; /* The type of bins of trees */ +typedef struct malloc_tree_chunk tchunk; +typedef struct malloc_tree_chunk *tchunkptr; +typedef struct malloc_tree_chunk *tbinptr; /* The type of bins of trees */ /* A little helper macro for trees */ -#define leftmost_child(t) ((t)->child[0] != 0? (t)->child[0] : (t)->child[1]) +#define leftmost_child(t) ((t)->child[0] != 0 ? (t)->child[0] : (t)->child[1]) /* ----------------------------- Segments -------------------------------- */ @@ -1879,18 +1890,19 @@ typedef struct malloc_tree_chunk* tbinptr; /* The type of bins of trees */ and deallocated/trimmed using MORECORE with negative arguments. */ -struct malloc_segment { - char* base; /* base address */ - size_t size; /* allocated size */ - struct malloc_segment* next; /* ptr to next segment */ - flag_t sflags; /* mmap and extern flag */ +struct malloc_segment +{ + char *base; /* base address */ + size_t size; /* allocated size */ + struct malloc_segment *next; /* ptr to next segment */ + flag_t sflags; /* mmap and extern flag */ }; -#define is_mmapped_segment(S) ((S)->sflags & IS_MMAPPED_BIT) -#define is_extern_segment(S) ((S)->sflags & EXTERN_BIT) +#define is_mmapped_segment(S) ((S)->sflags & IS_MMAPPED_BIT) +#define is_extern_segment(S) ((S)->sflags & EXTERN_BIT) -typedef struct malloc_segment msegment; -typedef struct malloc_segment* msegmentptr; +typedef struct malloc_segment msegment; +typedef struct malloc_segment *msegmentptr; /* ---------------------------- malloc_state ----------------------------- */ @@ -1968,37 +1980,38 @@ typedef struct malloc_segment* msegmentptr; */ /* Bin types, widths and sizes */ -#define NSMALLBINS (32U) -#define NTREEBINS (32U) -#define SMALLBIN_SHIFT (3U) -#define SMALLBIN_WIDTH (SIZE_T_ONE << SMALLBIN_SHIFT) -#define TREEBIN_SHIFT (8U) -#define MIN_LARGE_SIZE (SIZE_T_ONE << TREEBIN_SHIFT) -#define MAX_SMALL_SIZE (MIN_LARGE_SIZE - SIZE_T_ONE) +#define NSMALLBINS (32U) +#define NTREEBINS (32U) +#define SMALLBIN_SHIFT (3U) +#define SMALLBIN_WIDTH (SIZE_T_ONE << SMALLBIN_SHIFT) +#define TREEBIN_SHIFT (8U) +#define MIN_LARGE_SIZE (SIZE_T_ONE << TREEBIN_SHIFT) +#define MAX_SMALL_SIZE (MIN_LARGE_SIZE - SIZE_T_ONE) #define MAX_SMALL_REQUEST (MAX_SMALL_SIZE - CHUNK_ALIGN_MASK - CHUNK_OVERHEAD) -struct malloc_state { - binmap_t smallmap; - binmap_t treemap; - size_t dvsize; - size_t topsize; - char* least_addr; - mchunkptr dv; - mchunkptr top; - size_t trim_check; - size_t magic; - mchunkptr smallbins[(NSMALLBINS+1)*2]; - tbinptr treebins[NTREEBINS]; - size_t footprint; - size_t max_footprint; - flag_t mflags; +struct malloc_state +{ + binmap_t smallmap; + binmap_t treemap; + size_t dvsize; + size_t topsize; + char *least_addr; + mchunkptr dv; + mchunkptr top; + size_t trim_check; + size_t magic; + mchunkptr smallbins[(NSMALLBINS + 1) * 2]; + tbinptr treebins[NTREEBINS]; + size_t footprint; + size_t max_footprint; + flag_t mflags; #if USE_LOCKS - MLOCK_T mutex; /* locate lock among fields that rarely change */ -#endif /* USE_LOCKS */ - msegment seg; + MLOCK_T mutex; /* locate lock among fields that rarely change */ +#endif /* USE_LOCKS */ + msegment seg; }; -typedef struct malloc_state* mstate; +typedef struct malloc_state *mstate; /* ------------- Global malloc_state and malloc_params ------------------- */ @@ -2008,86 +2021,88 @@ typedef struct malloc_state* mstate; initialized in init_mparams. */ -struct malloc_params { - size_t magic; - size_t page_size; - size_t granularity; - size_t mmap_threshold; - size_t trim_threshold; - flag_t default_mflags; +struct malloc_params +{ + size_t magic; + size_t page_size; + size_t granularity; + size_t mmap_threshold; + size_t trim_threshold; + flag_t default_mflags; }; static struct malloc_params mparams; /* The global malloc_state used for all non-"mspace" calls */ static struct malloc_state _gm_; -#define gm (&_gm_) -#define is_global(M) ((M) == &_gm_) -#define is_initialized(M) ((M)->top != 0) +#define gm (&_gm_) +#define is_global(M) ((M) == &_gm_) +#define is_initialized(M) ((M)->top != 0) /* -------------------------- system alloc setup ------------------------- */ /* Operations on mflags */ -#define use_lock(M) ((M)->mflags & USE_LOCK_BIT) -#define enable_lock(M) ((M)->mflags |= USE_LOCK_BIT) -#define disable_lock(M) ((M)->mflags &= ~USE_LOCK_BIT) +#define use_lock(M) ((M)->mflags & USE_LOCK_BIT) +#define enable_lock(M) ((M)->mflags |= USE_LOCK_BIT) +#define disable_lock(M) ((M)->mflags &= ~USE_LOCK_BIT) -#define use_mmap(M) ((M)->mflags & USE_MMAP_BIT) -#define enable_mmap(M) ((M)->mflags |= USE_MMAP_BIT) -#define disable_mmap(M) ((M)->mflags &= ~USE_MMAP_BIT) +#define use_mmap(M) ((M)->mflags & USE_MMAP_BIT) +#define enable_mmap(M) ((M)->mflags |= USE_MMAP_BIT) +#define disable_mmap(M) ((M)->mflags &= ~USE_MMAP_BIT) -#define use_noncontiguous(M) ((M)->mflags & USE_NONCONTIGUOUS_BIT) -#define disable_contiguous(M) ((M)->mflags |= USE_NONCONTIGUOUS_BIT) +#define use_noncontiguous(M) ((M)->mflags & USE_NONCONTIGUOUS_BIT) +#define disable_contiguous(M) ((M)->mflags |= USE_NONCONTIGUOUS_BIT) -#define set_lock(M,L)\ - ((M)->mflags = (L)?\ - ((M)->mflags | USE_LOCK_BIT) :\ - ((M)->mflags & ~USE_LOCK_BIT)) +#define set_lock(M, L) \ + ((M)->mflags = (L) ? ((M)->mflags | USE_LOCK_BIT) \ + : ((M)->mflags & ~USE_LOCK_BIT)) /* page-align a size */ -#define page_align(S)\ - (((S) + (mparams.page_size)) & ~(mparams.page_size - SIZE_T_ONE)) +#define page_align(S) \ + (((S) + (mparams.page_size)) & ~(mparams.page_size - SIZE_T_ONE)) /* granularity-align a size */ -#define granularity_align(S)\ - (((S) + (mparams.granularity)) & ~(mparams.granularity - SIZE_T_ONE)) +#define granularity_align(S) \ + (((S) + (mparams.granularity)) & ~(mparams.granularity - SIZE_T_ONE)) -#define is_page_aligned(S)\ - (((size_t)(S) & (mparams.page_size - SIZE_T_ONE)) == 0) -#define is_granularity_aligned(S)\ - (((size_t)(S) & (mparams.granularity - SIZE_T_ONE)) == 0) +#define is_page_aligned(S) \ + (((size_t)(S) & (mparams.page_size - SIZE_T_ONE)) == 0) +#define is_granularity_aligned(S) \ + (((size_t)(S) & (mparams.granularity - SIZE_T_ONE)) == 0) /* True if segment S holds address A */ -#define segment_holds(S, A)\ - ((char*)(A) >= S->base && (char*)(A) < S->base + S->size) +#define segment_holds(S, A) \ + ((char *)(A) >= S->base && (char *)(A) < S->base + S->size) /* Return segment holding given address */ -static msegmentptr segment_holding(mstate m, char* addr) { - msegmentptr sp = &m->seg; - for (;;) { - if (addr >= sp->base && addr < sp->base + sp->size) - return sp; - if ((sp = sp->next) == 0) - return 0; - } +static msegmentptr segment_holding(mstate m, char *addr) +{ + msegmentptr sp = &m->seg; + for(;;) { + if(addr >= sp->base && addr < sp->base + sp->size) + return sp; + if((sp = sp->next) == 0) + return 0; + } } /* Return true if segment contains a segment link */ -static int has_segment_link(mstate m, msegmentptr ss) { - msegmentptr sp = &m->seg; - for (;;) { - if ((char*)sp >= ss->base && (char*)sp < ss->base + ss->size) - return 1; - if ((sp = sp->next) == 0) - return 0; - } +static int has_segment_link(mstate m, msegmentptr ss) +{ + msegmentptr sp = &m->seg; + for(;;) { + if((char *)sp >= ss->base && (char *)sp < ss->base + ss->size) + return 1; + if((sp = sp->next) == 0) + return 0; + } } #ifndef MORECORE_CANNOT_TRIM -#define should_trim(M,s) ((s) > (M)->trim_check) -#else /* MORECORE_CANNOT_TRIM */ -#define should_trim(M,s) (0) +#define should_trim(M, s) ((s) > (M)->trim_check) +#else /* MORECORE_CANNOT_TRIM */ +#define should_trim(M, s) (0) #endif /* MORECORE_CANNOT_TRIM */ /* @@ -2095,8 +2110,9 @@ static int has_segment_link(mstate m, msegmentptr ss) { that may be needed to place segment records and fenceposts when new noncontiguous segments are added. */ -#define TOP_FOOT_SIZE\ - (align_offset(chunk2mem(0))+pad_request(sizeof(struct malloc_segment))+MIN_CHUNK_SIZE) +#define TOP_FOOT_SIZE \ + (align_offset(chunk2mem(0)) + pad_request(sizeof(struct malloc_segment)) \ + + MIN_CHUNK_SIZE) /* ------------------------------- Hooks -------------------------------- */ @@ -2112,17 +2128,22 @@ static int has_segment_link(mstate m, msegmentptr ss) { /* Ensure locks are initialized */ #define GLOBALLY_INITIALIZE() (mparams.page_size == 0 && init_mparams()) -#define PREACTION(M) ((GLOBALLY_INITIALIZE() || use_lock(M))? ACQUIRE_LOCK(&(M)->mutex) : 0) -#define POSTACTION(M) { if (use_lock(M)) RELEASE_LOCK(&(M)->mutex); } +#define PREACTION(M) \ + ((GLOBALLY_INITIALIZE() || use_lock(M)) ? ACQUIRE_LOCK(&(M)->mutex) : 0) +#define POSTACTION(M) \ + { \ + if(use_lock(M)) \ + RELEASE_LOCK(&(M)->mutex); \ + } #else /* USE_LOCKS */ #ifndef PREACTION #define PREACTION(M) (0) -#endif /* PREACTION */ +#endif /* PREACTION */ #ifndef POSTACTION #define POSTACTION(M) -#endif /* POSTACTION */ +#endif /* POSTACTION */ #endif /* USE_LOCKS */ @@ -2142,7 +2163,7 @@ int malloc_corruption_error_count; /* default corruption action */ static void reset_on_error(mstate m); -#define CORRUPTION_ERROR_ACTION(m) reset_on_error(m) +#define CORRUPTION_ERROR_ACTION(m) reset_on_error(m) #define USAGE_ERROR_ACTION(m, p) #else /* PROCEED_ON_ERROR */ @@ -2152,153 +2173,161 @@ static void reset_on_error(mstate m); #endif /* CORRUPTION_ERROR_ACTION */ #ifndef USAGE_ERROR_ACTION -#define USAGE_ERROR_ACTION(m,p) ABORT +#define USAGE_ERROR_ACTION(m, p) ABORT #endif /* USAGE_ERROR_ACTION */ #endif /* PROCEED_ON_ERROR */ /* -------------------------- Debugging setup ---------------------------- */ -#if ! DEBUG +#if !DEBUG -#define check_free_chunk(M,P) -#define check_inuse_chunk(M,P) -#define check_malloced_chunk(M,P,N) -#define check_mmapped_chunk(M,P) +#define check_free_chunk(M, P) +#define check_inuse_chunk(M, P) +#define check_malloced_chunk(M, P, N) +#define check_mmapped_chunk(M, P) #define check_malloc_state(M) -#define check_top_chunk(M,P) +#define check_top_chunk(M, P) #else /* DEBUG */ -#define check_free_chunk(M,P) do_check_free_chunk(M,P) -#define check_inuse_chunk(M,P) do_check_inuse_chunk(M,P) -#define check_top_chunk(M,P) do_check_top_chunk(M,P) -#define check_malloced_chunk(M,P,N) do_check_malloced_chunk(M,P,N) -#define check_mmapped_chunk(M,P) do_check_mmapped_chunk(M,P) -#define check_malloc_state(M) do_check_malloc_state(M) - -static void do_check_any_chunk(mstate m, mchunkptr p); -static void do_check_top_chunk(mstate m, mchunkptr p); -static void do_check_mmapped_chunk(mstate m, mchunkptr p); -static void do_check_inuse_chunk(mstate m, mchunkptr p); -static void do_check_free_chunk(mstate m, mchunkptr p); -static void do_check_malloced_chunk(mstate m, void* mem, size_t s); -static void do_check_tree(mstate m, tchunkptr t); -static void do_check_treebin(mstate m, bindex_t i); -static void do_check_smallbin(mstate m, bindex_t i); -static void do_check_malloc_state(mstate m); -static int bin_find(mstate m, mchunkptr x); +#define check_free_chunk(M, P) do_check_free_chunk(M, P) +#define check_inuse_chunk(M, P) do_check_inuse_chunk(M, P) +#define check_top_chunk(M, P) do_check_top_chunk(M, P) +#define check_malloced_chunk(M, P, N) do_check_malloced_chunk(M, P, N) +#define check_mmapped_chunk(M, P) do_check_mmapped_chunk(M, P) +#define check_malloc_state(M) do_check_malloc_state(M) + +static void do_check_any_chunk(mstate m, mchunkptr p); +static void do_check_top_chunk(mstate m, mchunkptr p); +static void do_check_mmapped_chunk(mstate m, mchunkptr p); +static void do_check_inuse_chunk(mstate m, mchunkptr p); +static void do_check_free_chunk(mstate m, mchunkptr p); +static void do_check_malloced_chunk(mstate m, void *mem, size_t s); +static void do_check_tree(mstate m, tchunkptr t); +static void do_check_treebin(mstate m, bindex_t i); +static void do_check_smallbin(mstate m, bindex_t i); +static void do_check_malloc_state(mstate m); +static int bin_find(mstate m, mchunkptr x); static size_t traverse_and_check(mstate m); #endif /* DEBUG */ /* ---------------------------- Indexing Bins ---------------------------- */ -#define is_small(s) (((s) >> SMALLBIN_SHIFT) < NSMALLBINS) -#define small_index(s) ((s) >> SMALLBIN_SHIFT) -#define small_index2size(i) ((i) << SMALLBIN_SHIFT) -#define MIN_SMALL_INDEX (small_index(MIN_CHUNK_SIZE)) +#define is_small(s) (((s) >> SMALLBIN_SHIFT) < NSMALLBINS) +#define small_index(s) ((s) >> SMALLBIN_SHIFT) +#define small_index2size(i) ((i) << SMALLBIN_SHIFT) +#define MIN_SMALL_INDEX (small_index(MIN_CHUNK_SIZE)) /* addressing by index. See above about smallbin repositioning */ -#define smallbin_at(M, i) ((sbinptr)((char*)&((M)->smallbins[(i)<<1]))) -#define treebin_at(M,i) (&((M)->treebins[i])) +#define smallbin_at(M, i) ((sbinptr)((char *)&((M)->smallbins[(i) << 1]))) +#define treebin_at(M, i) (&((M)->treebins[i])) /* assign tree index for size S to variable I */ #if defined(__GNUC__) && defined(i386) -#define compute_tree_index(S, I)\ -{\ - size_t X = S >> TREEBIN_SHIFT;\ - if (X == 0)\ - I = 0;\ - else if (X > 0xFFFF)\ - I = NTREEBINS-1;\ - else {\ - unsigned int K;\ - __asm__("bsrl %1,%0\n\t" : "=r" (K) : "rm" (X));\ - I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1)));\ - }\ -} +#define compute_tree_index(S, I) \ + { \ + size_t X = S >> TREEBIN_SHIFT; \ + if(X == 0) \ + I = 0; \ + else if(X > 0xFFFF) \ + I = NTREEBINS - 1; \ + else { \ + unsigned int K; \ + __asm__("bsrl %1,%0\n\t" : "=r"(K) : "rm"(X)); \ + I = (bindex_t)((K << 1) + ((S >> (K + (TREEBIN_SHIFT - 1)) & 1))); \ + } \ + } #else /* GNUC */ -#define compute_tree_index(S, I)\ -{\ - size_t X = S >> TREEBIN_SHIFT;\ - if (X == 0)\ - I = 0;\ - else if (X > 0xFFFF)\ - I = NTREEBINS-1;\ - else {\ - unsigned int Y = (unsigned int)X;\ - unsigned int N = ((Y - 0x100) >> 16) & 8;\ - unsigned int K = (((Y <<= N) - 0x1000) >> 16) & 4;\ - N += K;\ - N += K = (((Y <<= K) - 0x4000) >> 16) & 2;\ - K = 14 - N + ((Y <<= K) >> 15);\ - I = (K << 1) + ((S >> (K + (TREEBIN_SHIFT-1)) & 1));\ - }\ -} +#define compute_tree_index(S, I) \ + { \ + size_t X = S >> TREEBIN_SHIFT; \ + if(X == 0) \ + I = 0; \ + else if(X > 0xFFFF) \ + I = NTREEBINS - 1; \ + else { \ + unsigned int Y = (unsigned int)X; \ + unsigned int N = ((Y - 0x100) >> 16) & 8; \ + unsigned int K = (((Y <<= N) - 0x1000) >> 16) & 4; \ + N += K; \ + N += K = (((Y <<= K) - 0x4000) >> 16) & 2; \ + K = 14 - N + ((Y <<= K) >> 15); \ + I = (K << 1) + ((S >> (K + (TREEBIN_SHIFT - 1)) & 1)); \ + } \ + } #endif /* GNUC */ /* Bit representing maximum resolved size in a treebin at i */ -#define bit_for_tree_index(i) \ - (i == NTREEBINS-1)? (SIZE_T_BITSIZE-1) : (((i) >> 1) + TREEBIN_SHIFT - 2) +#define bit_for_tree_index(i) \ + (i == NTREEBINS - 1) ? (SIZE_T_BITSIZE - 1) \ + : (((i) >> 1) + TREEBIN_SHIFT - 2) /* Shift placing maximum resolved bit in a treebin at i as sign bit */ -#define leftshift_for_tree_index(i) \ - ((i == NTREEBINS-1)? 0 : \ - ((SIZE_T_BITSIZE-SIZE_T_ONE) - (((i) >> 1) + TREEBIN_SHIFT - 2))) +#define leftshift_for_tree_index(i) \ + ((i == NTREEBINS - 1) ? 0 \ + : ((SIZE_T_BITSIZE - SIZE_T_ONE) \ + - (((i) >> 1) + TREEBIN_SHIFT - 2))) /* The size of the smallest chunk held in bin with index i */ -#define minsize_for_tree_index(i) \ - ((SIZE_T_ONE << (((i) >> 1) + TREEBIN_SHIFT)) | \ - (((size_t)((i) & SIZE_T_ONE)) << (((i) >> 1) + TREEBIN_SHIFT - 1))) +#define minsize_for_tree_index(i) \ + ((SIZE_T_ONE << (((i) >> 1) + TREEBIN_SHIFT)) \ + | (((size_t)((i)&SIZE_T_ONE)) \ + << (((i) >> 1) + TREEBIN_SHIFT - 1))) /* ------------------------ Operations on bin maps ----------------------- */ /* bit corresponding to given index */ -#define idx2bit(i) ((binmap_t)(1) << (i)) +#define idx2bit(i) ((binmap_t)(1) << (i)) /* Mark/Clear bits with given index */ -#define mark_smallmap(M,i) ((M)->smallmap |= idx2bit(i)) -#define clear_smallmap(M,i) ((M)->smallmap &= ~idx2bit(i)) -#define smallmap_is_marked(M,i) ((M)->smallmap & idx2bit(i)) +#define mark_smallmap(M, i) ((M)->smallmap |= idx2bit(i)) +#define clear_smallmap(M, i) ((M)->smallmap &= ~idx2bit(i)) +#define smallmap_is_marked(M, i) ((M)->smallmap & idx2bit(i)) -#define mark_treemap(M,i) ((M)->treemap |= idx2bit(i)) -#define clear_treemap(M,i) ((M)->treemap &= ~idx2bit(i)) -#define treemap_is_marked(M,i) ((M)->treemap & idx2bit(i)) +#define mark_treemap(M, i) ((M)->treemap |= idx2bit(i)) +#define clear_treemap(M, i) ((M)->treemap &= ~idx2bit(i)) +#define treemap_is_marked(M, i) ((M)->treemap & idx2bit(i)) /* index corresponding to given bit */ #if defined(__GNUC__) && defined(i386) -#define compute_bit2idx(X, I)\ -{\ - unsigned int J;\ - __asm__("bsfl %1,%0\n\t" : "=r" (J) : "rm" (X));\ - I = (bindex_t)J;\ -} +#define compute_bit2idx(X, I) \ + { \ + unsigned int J; \ + __asm__("bsfl %1,%0\n\t" : "=r"(J) : "rm"(X)); \ + I = (bindex_t)J; \ + } #else /* GNUC */ -#if USE_BUILTIN_FFS -#define compute_bit2idx(X, I) I = ffs(X)-1 +#if USE_BUILTIN_FFS +#define compute_bit2idx(X, I) I = ffs(X) - 1 #else /* USE_BUILTIN_FFS */ -#define compute_bit2idx(X, I)\ -{\ - unsigned int Y = X - 1;\ - unsigned int K = Y >> (16-4) & 16;\ - unsigned int N = K; Y >>= K;\ - N += K = Y >> (8-3) & 8; Y >>= K;\ - N += K = Y >> (4-2) & 4; Y >>= K;\ - N += K = Y >> (2-1) & 2; Y >>= K;\ - N += K = Y >> (1-0) & 1; Y >>= K;\ - I = (bindex_t)(N + Y);\ -} +#define compute_bit2idx(X, I) \ + { \ + unsigned int Y = X - 1; \ + unsigned int K = Y >> (16 - 4) & 16; \ + unsigned int N = K; \ + Y >>= K; \ + N += K = Y >> (8 - 3) & 8; \ + Y >>= K; \ + N += K = Y >> (4 - 2) & 4; \ + Y >>= K; \ + N += K = Y >> (2 - 1) & 2; \ + Y >>= K; \ + N += K = Y >> (1 - 0) & 1; \ + Y >>= K; \ + I = (bindex_t)(N + Y); \ + } #endif /* USE_BUILTIN_FFS */ #endif /* GNUC */ /* isolate the least set bit of a bitmap */ -#define least_bit(x) ((x) & -(x)) +#define least_bit(x) ((x) & -(x)) /* mask with all bits to left of least bit of x on */ -#define left_bits(x) ((x<<1) | -(x<<1)) +#define left_bits(x) ((x << 1) | -(x << 1)) /* mask with all bits to left of or equal to least bit of x on */ #define same_or_left_bits(x) ((x) | -(x)) @@ -2334,527 +2363,538 @@ static size_t traverse_and_check(mstate m); #if !INSECURE /* Check if address a is at least as high as any from MORECORE or MMAP */ -#define ok_address(M, a) ((char*)(a) >= (M)->least_addr) +#define ok_address(M, a) ((char *)(a) >= (M)->least_addr) /* Check if address of next chunk n is higher than base chunk p */ -#define ok_next(p, n) ((char*)(p) < (char*)(n)) +#define ok_next(p, n) ((char *)(p) < (char *)(n)) /* Check if p has its cinuse bit on */ -#define ok_cinuse(p) cinuse(p) +#define ok_cinuse(p) cinuse(p) /* Check if p has its pinuse bit on */ -#define ok_pinuse(p) pinuse(p) +#define ok_pinuse(p) pinuse(p) #else /* !INSECURE */ #define ok_address(M, a) (1) -#define ok_next(b, n) (1) -#define ok_cinuse(p) (1) -#define ok_pinuse(p) (1) +#define ok_next(b, n) (1) +#define ok_cinuse(p) (1) +#define ok_pinuse(p) (1) #endif /* !INSECURE */ -#if (FOOTERS && !INSECURE) +#if(FOOTERS && !INSECURE) /* Check if (alleged) mstate m has expected magic field */ -#define ok_magic(M) ((M)->magic == mparams.magic) -#else /* (FOOTERS && !INSECURE) */ -#define ok_magic(M) (1) +#define ok_magic(M) ((M)->magic == mparams.magic) +#else /* (FOOTERS && !INSECURE) */ +#define ok_magic(M) (1) #endif /* (FOOTERS && !INSECURE) */ /* In gcc, use __builtin_expect to minimize impact of checks */ #if !INSECURE #if defined(__GNUC__) && __GNUC__ >= 3 -#define RTCHECK(e) __builtin_expect(e, 1) +#define RTCHECK(e) __builtin_expect(e, 1) #else /* GNUC */ -#define RTCHECK(e) (e) +#define RTCHECK(e) (e) #endif /* GNUC */ -#else /* !INSECURE */ -#define RTCHECK(e) (1) +#else /* !INSECURE */ +#define RTCHECK(e) (1) #endif /* !INSECURE */ /* macros to set up inuse chunks with or without footers */ #if !FOOTERS -#define mark_inuse_foot(M,p,s) +#define mark_inuse_foot(M, p, s) /* Set cinuse bit and pinuse bit of next chunk */ -#define set_inuse(M,p,s)\ - ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\ - ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT) +#define set_inuse(M, p, s) \ + ((p)->head = (((p)->head & PINUSE_BIT) | s | CINUSE_BIT), \ + ((mchunkptr)(((char *)(p)) + (s)))->head |= PINUSE_BIT) /* Set cinuse and pinuse of this chunk and pinuse of next chunk */ -#define set_inuse_and_pinuse(M,p,s)\ - ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\ - ((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT) +#define set_inuse_and_pinuse(M, p, s) \ + ((p)->head = (s | PINUSE_BIT | CINUSE_BIT), \ + ((mchunkptr)(((char *)(p)) + (s)))->head |= PINUSE_BIT) /* Set size, cinuse and pinuse bit of this chunk */ -#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\ - ((p)->head = (s|PINUSE_BIT|CINUSE_BIT)) +#define set_size_and_pinuse_of_inuse_chunk(M, p, s) \ + ((p)->head = (s | PINUSE_BIT | CINUSE_BIT)) #else /* FOOTERS */ /* Set foot of inuse chunk to be xor of mstate and seed */ -#define mark_inuse_foot(M,p,s)\ - (((mchunkptr)((char*)(p) + (s)))->prev_foot = ((size_t)(M) ^ mparams.magic)) +#define mark_inuse_foot(M, p, s) \ + (((mchunkptr)((char *)(p) + (s)))->prev_foot = \ + ((size_t)(M) ^ mparams.magic)) -#define get_mstate_for(p)\ - ((mstate)(((mchunkptr)((char*)(p) +\ - (chunksize(p))))->prev_foot ^ mparams.magic)) +#define get_mstate_for(p) \ + ((mstate)(((mchunkptr)((char *)(p) + (chunksize(p))))->prev_foot \ + ^ mparams.magic)) -#define set_inuse(M,p,s)\ - ((p)->head = (((p)->head & PINUSE_BIT)|s|CINUSE_BIT),\ - (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT), \ - mark_inuse_foot(M,p,s)) +#define set_inuse(M, p, s) \ + ((p)->head = (((p)->head & PINUSE_BIT) | s | CINUSE_BIT), \ + (((mchunkptr)(((char *)(p)) + (s)))->head |= PINUSE_BIT), \ + mark_inuse_foot(M, p, s)) -#define set_inuse_and_pinuse(M,p,s)\ - ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\ - (((mchunkptr)(((char*)(p)) + (s)))->head |= PINUSE_BIT),\ - mark_inuse_foot(M,p,s)) +#define set_inuse_and_pinuse(M, p, s) \ + ((p)->head = (s | PINUSE_BIT | CINUSE_BIT), \ + (((mchunkptr)(((char *)(p)) + (s)))->head |= PINUSE_BIT), \ + mark_inuse_foot(M, p, s)) -#define set_size_and_pinuse_of_inuse_chunk(M, p, s)\ - ((p)->head = (s|PINUSE_BIT|CINUSE_BIT),\ - mark_inuse_foot(M, p, s)) +#define set_size_and_pinuse_of_inuse_chunk(M, p, s) \ + ((p)->head = (s | PINUSE_BIT | CINUSE_BIT), mark_inuse_foot(M, p, s)) #endif /* !FOOTERS */ /* ---------------------------- setting mparams -------------------------- */ /* Initialize mparams */ -static int init_mparams(void) { - if (mparams.page_size == 0) { - size_t s; +static int init_mparams(void) +{ + if(mparams.page_size == 0) { + size_t s; - mparams.mmap_threshold = DEFAULT_MMAP_THRESHOLD; - mparams.trim_threshold = DEFAULT_TRIM_THRESHOLD; + mparams.mmap_threshold = DEFAULT_MMAP_THRESHOLD; + mparams.trim_threshold = DEFAULT_TRIM_THRESHOLD; #if MORECORE_CONTIGUOUS - mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT; + mparams.default_mflags = USE_LOCK_BIT | USE_MMAP_BIT; #else /* MORECORE_CONTIGUOUS */ - mparams.default_mflags = USE_LOCK_BIT|USE_MMAP_BIT|USE_NONCONTIGUOUS_BIT; + mparams.default_mflags = + USE_LOCK_BIT | USE_MMAP_BIT | USE_NONCONTIGUOUS_BIT; #endif /* MORECORE_CONTIGUOUS */ -#if (FOOTERS && !INSECURE) - { +#if(FOOTERS && !INSECURE) + { #if USE_DEV_RANDOM - int fd; - unsigned char buf[sizeof(size_t)]; - /* Try to use /dev/urandom, else fall back on using time */ - if ((fd = open("/dev/urandom", O_RDONLY)) >= 0 && - read(fd, buf, sizeof(buf)) == sizeof(buf)) { - s = *((size_t *) buf); - close(fd); - } - else + int fd; + unsigned char buf[sizeof(size_t)]; + /* Try to use /dev/urandom, else fall back on using time */ + if((fd = open("/dev/urandom", O_RDONLY)) >= 0 + && read(fd, buf, sizeof(buf)) == sizeof(buf)) { + s = *((size_t *)buf); + close(fd); + } else #endif /* USE_DEV_RANDOM */ - s = (size_t)(time(0) ^ (size_t)0x55555555U); + s = (size_t)(time(0) ^ (size_t)0x55555555U); - s |= (size_t)8U; /* ensure nonzero */ - s &= ~(size_t)7U; /* improve chances of fault for bad values */ - - } -#else /* (FOOTERS && !INSECURE) */ - s = (size_t)0x58585858U; + s |= (size_t)8U; /* ensure nonzero */ + s &= ~(size_t)7U; /* improve chances of fault for bad values */ + } +#else /* (FOOTERS && !INSECURE) */ + s = (size_t)0x58585858U; #endif /* (FOOTERS && !INSECURE) */ - ACQUIRE_MAGIC_INIT_LOCK(); - if (mparams.magic == 0) { - mparams.magic = s; - /* Set up lock for main malloc area */ - INITIAL_LOCK(&gm->mutex); - gm->mflags = mparams.default_mflags; - } - RELEASE_MAGIC_INIT_LOCK(); + ACQUIRE_MAGIC_INIT_LOCK(); + if(mparams.magic == 0) { + mparams.magic = s; + /* Set up lock for main malloc area */ + INITIAL_LOCK(&gm->mutex); + gm->mflags = mparams.default_mflags; + } + RELEASE_MAGIC_INIT_LOCK(); #ifndef WIN32 - mparams.page_size = malloc_getpagesize; - mparams.granularity = ((DEFAULT_GRANULARITY != 0)? - DEFAULT_GRANULARITY : mparams.page_size); -#else /* WIN32 */ - { - SYSTEM_INFO system_info; - GetSystemInfo(&system_info); - mparams.page_size = system_info.dwPageSize; - mparams.granularity = system_info.dwAllocationGranularity; - } + mparams.page_size = malloc_getpagesize; + mparams.granularity = ((DEFAULT_GRANULARITY != 0) ? DEFAULT_GRANULARITY + : mparams.page_size); +#else /* WIN32 */ + { + SYSTEM_INFO system_info; + GetSystemInfo(&system_info); + mparams.page_size = system_info.dwPageSize; + mparams.granularity = system_info.dwAllocationGranularity; + } #endif /* WIN32 */ - /* Sanity-check configuration: + /* Sanity-check configuration: size_t must be unsigned and as wide as pointer type. ints must be at least 4 bytes. alignment must be at least 8. Alignment, min chunk size, and page size must all be powers of 2. */ - if ((sizeof(size_t) != sizeof(char*)) || - (MAX_SIZE_T < MIN_CHUNK_SIZE) || - (sizeof(int) < 4) || - (MALLOC_ALIGNMENT < (size_t)8U) || - ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT-SIZE_T_ONE)) != 0) || - ((MCHUNK_SIZE & (MCHUNK_SIZE-SIZE_T_ONE)) != 0) || - ((mparams.granularity & (mparams.granularity-SIZE_T_ONE)) != 0) || - ((mparams.page_size & (mparams.page_size-SIZE_T_ONE)) != 0)) - ABORT; - } - return 0; + if((sizeof(size_t) != sizeof(char *)) || (MAX_SIZE_T < MIN_CHUNK_SIZE) + || (sizeof(int) < 4) || (MALLOC_ALIGNMENT < (size_t)8U) + || ((MALLOC_ALIGNMENT & (MALLOC_ALIGNMENT - SIZE_T_ONE)) != 0) + || ((MCHUNK_SIZE & (MCHUNK_SIZE - SIZE_T_ONE)) != 0) + || ((mparams.granularity & (mparams.granularity - SIZE_T_ONE)) + != 0) + || ((mparams.page_size & (mparams.page_size - SIZE_T_ONE)) + != 0)) + ABORT; + } + return 0; } /* support for mallopt */ -static int change_mparam(int param_number, int value) { - size_t val = (size_t)value; - init_mparams(); - switch(param_number) { - case M_TRIM_THRESHOLD: - mparams.trim_threshold = val; - return 1; - case M_GRANULARITY: - if (val >= mparams.page_size && ((val & (val-1)) == 0)) { - mparams.granularity = val; - return 1; - } - else - return 0; - case M_MMAP_THRESHOLD: - mparams.mmap_threshold = val; - return 1; - default: - return 0; - } +static int change_mparam(int param_number, int value) +{ + size_t val = (size_t)value; + init_mparams(); + switch(param_number) { + case M_TRIM_THRESHOLD: + mparams.trim_threshold = val; + return 1; + case M_GRANULARITY: + if(val >= mparams.page_size && ((val & (val - 1)) == 0)) { + mparams.granularity = val; + return 1; + } else + return 0; + case M_MMAP_THRESHOLD: + mparams.mmap_threshold = val; + return 1; + default: + return 0; + } } #if DEBUG /* ------------------------- Debugging Support --------------------------- */ /* Check properties of any chunk, whether free, inuse, mmapped etc */ -static void do_check_any_chunk(mstate m, mchunkptr p) { - assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); - assert(ok_address(m, p)); +static void do_check_any_chunk(mstate m, mchunkptr p) +{ + assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); + assert(ok_address(m, p)); } /* Check properties of top chunk */ -static void do_check_top_chunk(mstate m, mchunkptr p) { - msegmentptr sp = segment_holding(m, (char*)p); - size_t sz = chunksize(p); - assert(sp != 0); - assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); - assert(ok_address(m, p)); - assert(sz == m->topsize); - assert(sz > 0); - assert(sz == ((sp->base + sp->size) - (char*)p) - TOP_FOOT_SIZE); - assert(pinuse(p)); - assert(!next_pinuse(p)); +static void do_check_top_chunk(mstate m, mchunkptr p) +{ + msegmentptr sp = segment_holding(m, (char *)p); + size_t sz = chunksize(p); + assert(sp != 0); + assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); + assert(ok_address(m, p)); + assert(sz == m->topsize); + assert(sz > 0); + assert(sz == ((sp->base + sp->size) - (char *)p) - TOP_FOOT_SIZE); + assert(pinuse(p)); + assert(!next_pinuse(p)); } /* Check properties of (inuse) mmapped chunks */ -static void do_check_mmapped_chunk(mstate m, mchunkptr p) { - size_t sz = chunksize(p); - size_t len = (sz + (p->prev_foot & ~IS_MMAPPED_BIT) + MMAP_FOOT_PAD); - assert(is_mmapped(p)); - assert(use_mmap(m)); - assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); - assert(ok_address(m, p)); - assert(!is_small(sz)); - assert((len & (mparams.page_size-SIZE_T_ONE)) == 0); - assert(chunk_plus_offset(p, sz)->head == FENCEPOST_HEAD); - assert(chunk_plus_offset(p, sz+SIZE_T_SIZE)->head == 0); +static void do_check_mmapped_chunk(mstate m, mchunkptr p) +{ + size_t sz = chunksize(p); + size_t len = (sz + (p->prev_foot & ~IS_MMAPPED_BIT) + MMAP_FOOT_PAD); + assert(is_mmapped(p)); + assert(use_mmap(m)); + assert((is_aligned(chunk2mem(p))) || (p->head == FENCEPOST_HEAD)); + assert(ok_address(m, p)); + assert(!is_small(sz)); + assert((len & (mparams.page_size - SIZE_T_ONE)) == 0); + assert(chunk_plus_offset(p, sz)->head == FENCEPOST_HEAD); + assert(chunk_plus_offset(p, sz + SIZE_T_SIZE)->head == 0); } /* Check properties of inuse chunks */ -static void do_check_inuse_chunk(mstate m, mchunkptr p) { - do_check_any_chunk(m, p); - assert(cinuse(p)); - assert(next_pinuse(p)); - /* If not pinuse and not mmapped, previous chunk has OK offset */ - assert(is_mmapped(p) || pinuse(p) || next_chunk(prev_chunk(p)) == p); - if (is_mmapped(p)) - do_check_mmapped_chunk(m, p); +static void do_check_inuse_chunk(mstate m, mchunkptr p) +{ + do_check_any_chunk(m, p); + assert(cinuse(p)); + assert(next_pinuse(p)); + /* If not pinuse and not mmapped, previous chunk has OK offset */ + assert(is_mmapped(p) || pinuse(p) || next_chunk(prev_chunk(p)) == p); + if(is_mmapped(p)) + do_check_mmapped_chunk(m, p); } /* Check properties of free chunks */ -static void do_check_free_chunk(mstate m, mchunkptr p) { - size_t sz = p->head & ~(PINUSE_BIT|CINUSE_BIT); - mchunkptr next = chunk_plus_offset(p, sz); - do_check_any_chunk(m, p); - assert(!cinuse(p)); - assert(!next_pinuse(p)); - assert (!is_mmapped(p)); - if (p != m->dv && p != m->top) { - if (sz >= MIN_CHUNK_SIZE) { - assert((sz & CHUNK_ALIGN_MASK) == 0); - assert(is_aligned(chunk2mem(p))); - assert(next->prev_foot == sz); - assert(pinuse(p)); - assert (next == m->top || cinuse(next)); - assert(p->fd->bk == p); - assert(p->bk->fd == p); - } - else /* markers are always of size SIZE_T_SIZE */ - assert(sz == SIZE_T_SIZE); - } +static void do_check_free_chunk(mstate m, mchunkptr p) +{ + size_t sz = p->head & ~(PINUSE_BIT | CINUSE_BIT); + mchunkptr next = chunk_plus_offset(p, sz); + do_check_any_chunk(m, p); + assert(!cinuse(p)); + assert(!next_pinuse(p)); + assert(!is_mmapped(p)); + if(p != m->dv && p != m->top) { + if(sz >= MIN_CHUNK_SIZE) { + assert((sz & CHUNK_ALIGN_MASK) == 0); + assert(is_aligned(chunk2mem(p))); + assert(next->prev_foot == sz); + assert(pinuse(p)); + assert(next == m->top || cinuse(next)); + assert(p->fd->bk == p); + assert(p->bk->fd == p); + } else /* markers are always of size SIZE_T_SIZE */ + assert(sz == SIZE_T_SIZE); + } } /* Check properties of malloced chunks at the point they are malloced */ -static void do_check_malloced_chunk(mstate m, void* mem, size_t s) { - if (mem != 0) { - mchunkptr p = mem2chunk(mem); - size_t sz = p->head & ~(PINUSE_BIT|CINUSE_BIT); - do_check_inuse_chunk(m, p); - assert((sz & CHUNK_ALIGN_MASK) == 0); - assert(sz >= MIN_CHUNK_SIZE); - assert(sz >= s); - /* unless mmapped, size is less than MIN_CHUNK_SIZE more than request */ - assert(is_mmapped(p) || sz < (s + MIN_CHUNK_SIZE)); - } +static void do_check_malloced_chunk(mstate m, void *mem, size_t s) +{ + if(mem != 0) { + mchunkptr p = mem2chunk(mem); + size_t sz = p->head & ~(PINUSE_BIT | CINUSE_BIT); + do_check_inuse_chunk(m, p); + assert((sz & CHUNK_ALIGN_MASK) == 0); + assert(sz >= MIN_CHUNK_SIZE); + assert(sz >= s); + /* unless mmapped, size is less than MIN_CHUNK_SIZE more than request */ + assert(is_mmapped(p) || sz < (s + MIN_CHUNK_SIZE)); + } } /* Check a tree and its subtrees. */ -static void do_check_tree(mstate m, tchunkptr t) { - tchunkptr head = 0; - tchunkptr u = t; - bindex_t tindex = t->index; - size_t tsize = chunksize(t); - bindex_t idx; - compute_tree_index(tsize, idx); - assert(tindex == idx); - assert(tsize >= MIN_LARGE_SIZE); - assert(tsize >= minsize_for_tree_index(idx)); - assert((idx == NTREEBINS-1) || (tsize < minsize_for_tree_index((idx+1)))); - - do { /* traverse through chain of same-sized nodes */ - do_check_any_chunk(m, ((mchunkptr)u)); - assert(u->index == tindex); - assert(chunksize(u) == tsize); - assert(!cinuse(u)); - assert(!next_pinuse(u)); - assert(u->fd->bk == u); - assert(u->bk->fd == u); - if (u->parent == 0) { - assert(u->child[0] == 0); - assert(u->child[1] == 0); - } - else { - assert(head == 0); /* only one node on chain has parent */ - head = u; - assert(u->parent != u); - assert (u->parent->child[0] == u || - u->parent->child[1] == u || - *((tbinptr*)(u->parent)) == u); - if (u->child[0] != 0) { - assert(u->child[0]->parent == u); - assert(u->child[0] != u); - do_check_tree(m, u->child[0]); - } - if (u->child[1] != 0) { - assert(u->child[1]->parent == u); - assert(u->child[1] != u); - do_check_tree(m, u->child[1]); - } - if (u->child[0] != 0 && u->child[1] != 0) { - assert(chunksize(u->child[0]) < chunksize(u->child[1])); - } - } - u = u->fd; - } while (u != t); - assert(head != 0); +static void do_check_tree(mstate m, tchunkptr t) +{ + tchunkptr head = 0; + tchunkptr u = t; + bindex_t tindex = t->index; + size_t tsize = chunksize(t); + bindex_t idx; + compute_tree_index(tsize, idx); + assert(tindex == idx); + assert(tsize >= MIN_LARGE_SIZE); + assert(tsize >= minsize_for_tree_index(idx)); + assert((idx == NTREEBINS - 1) + || (tsize < minsize_for_tree_index((idx + 1)))); + + do { /* traverse through chain of same-sized nodes */ + do_check_any_chunk(m, ((mchunkptr)u)); + assert(u->index == tindex); + assert(chunksize(u) == tsize); + assert(!cinuse(u)); + assert(!next_pinuse(u)); + assert(u->fd->bk == u); + assert(u->bk->fd == u); + if(u->parent == 0) { + assert(u->child[0] == 0); + assert(u->child[1] == 0); + } else { + assert(head == 0); /* only one node on chain has parent */ + head = u; + assert(u->parent != u); + assert(u->parent->child[0] == u || u->parent->child[1] == u + || *((tbinptr *)(u->parent)) == u); + if(u->child[0] != 0) { + assert(u->child[0]->parent == u); + assert(u->child[0] != u); + do_check_tree(m, u->child[0]); + } + if(u->child[1] != 0) { + assert(u->child[1]->parent == u); + assert(u->child[1] != u); + do_check_tree(m, u->child[1]); + } + if(u->child[0] != 0 && u->child[1] != 0) { + assert(chunksize(u->child[0]) < chunksize(u->child[1])); + } + } + u = u->fd; + } while(u != t); + assert(head != 0); } /* Check all the chunks in a treebin. */ -static void do_check_treebin(mstate m, bindex_t i) { - tbinptr* tb = treebin_at(m, i); - tchunkptr t = *tb; - int empty = (m->treemap & (1U << i)) == 0; - if (t == 0) - assert(empty); - if (!empty) - do_check_tree(m, t); +static void do_check_treebin(mstate m, bindex_t i) +{ + tbinptr *tb = treebin_at(m, i); + tchunkptr t = *tb; + int empty = (m->treemap & (1U << i)) == 0; + if(t == 0) + assert(empty); + if(!empty) + do_check_tree(m, t); } /* Check all the chunks in a smallbin. */ -static void do_check_smallbin(mstate m, bindex_t i) { - sbinptr b = smallbin_at(m, i); - mchunkptr p = b->bk; - unsigned int empty = (m->smallmap & (1U << i)) == 0; - if (p == b) - assert(empty); - if (!empty) { - for (; p != b; p = p->bk) { - size_t size = chunksize(p); - mchunkptr q; - /* each chunk claims to be free */ - do_check_free_chunk(m, p); - /* chunk belongs in bin */ - assert(small_index(size) == i); - assert(p->bk == b || chunksize(p->bk) == chunksize(p)); - /* chunk is followed by an inuse chunk */ - q = next_chunk(p); - if (q->head != FENCEPOST_HEAD) - do_check_inuse_chunk(m, q); - } - } +static void do_check_smallbin(mstate m, bindex_t i) +{ + sbinptr b = smallbin_at(m, i); + mchunkptr p = b->bk; + unsigned int empty = (m->smallmap & (1U << i)) == 0; + if(p == b) + assert(empty); + if(!empty) { + for(; p != b; p = p->bk) { + size_t size = chunksize(p); + mchunkptr q; + /* each chunk claims to be free */ + do_check_free_chunk(m, p); + /* chunk belongs in bin */ + assert(small_index(size) == i); + assert(p->bk == b || chunksize(p->bk) == chunksize(p)); + /* chunk is followed by an inuse chunk */ + q = next_chunk(p); + if(q->head != FENCEPOST_HEAD) + do_check_inuse_chunk(m, q); + } + } } /* Find x in a bin. Used in other check functions. */ -static int bin_find(mstate m, mchunkptr x) { - size_t size = chunksize(x); - if (is_small(size)) { - bindex_t sidx = small_index(size); - sbinptr b = smallbin_at(m, sidx); - if (smallmap_is_marked(m, sidx)) { - mchunkptr p = b; - do { - if (p == x) - return 1; - } while ((p = p->fd) != b); - } - } - else { - bindex_t tidx; - compute_tree_index(size, tidx); - if (treemap_is_marked(m, tidx)) { - tchunkptr t = *treebin_at(m, tidx); - size_t sizebits = size << leftshift_for_tree_index(tidx); - while (t != 0 && chunksize(t) != size) { - t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]; - sizebits <<= 1; - } - if (t != 0) { - tchunkptr u = t; - do { - if (u == (tchunkptr)x) - return 1; - } while ((u = u->fd) != t); - } - } - } - return 0; +static int bin_find(mstate m, mchunkptr x) +{ + size_t size = chunksize(x); + if(is_small(size)) { + bindex_t sidx = small_index(size); + sbinptr b = smallbin_at(m, sidx); + if(smallmap_is_marked(m, sidx)) { + mchunkptr p = b; + do { + if(p == x) + return 1; + } while((p = p->fd) != b); + } + } else { + bindex_t tidx; + compute_tree_index(size, tidx); + if(treemap_is_marked(m, tidx)) { + tchunkptr t = *treebin_at(m, tidx); + size_t sizebits = size << leftshift_for_tree_index(tidx); + while(t != 0 && chunksize(t) != size) { + t = t->child[(sizebits >> (SIZE_T_BITSIZE - SIZE_T_ONE)) & 1]; + sizebits <<= 1; + } + if(t != 0) { + tchunkptr u = t; + do { + if(u == (tchunkptr)x) + return 1; + } while((u = u->fd) != t); + } + } + } + return 0; } /* Traverse each chunk and check it; return total */ -static size_t traverse_and_check(mstate m) { - size_t sum = 0; - if (is_initialized(m)) { - msegmentptr s = &m->seg; - sum += m->topsize + TOP_FOOT_SIZE; - while (s != 0) { - mchunkptr q = align_as_chunk(s->base); - mchunkptr lastq = 0; - assert(pinuse(q)); - while (segment_holds(s, q) && - q != m->top && q->head != FENCEPOST_HEAD) { - sum += chunksize(q); - if (cinuse(q)) { - assert(!bin_find(m, q)); - do_check_inuse_chunk(m, q); - } - else { - assert(q == m->dv || bin_find(m, q)); - assert(lastq == 0 || cinuse(lastq)); /* Not 2 consecutive free */ - do_check_free_chunk(m, q); - } - lastq = q; - q = next_chunk(q); - } - s = s->next; - } - } - return sum; +static size_t traverse_and_check(mstate m) +{ + size_t sum = 0; + if(is_initialized(m)) { + msegmentptr s = &m->seg; + sum += m->topsize + TOP_FOOT_SIZE; + while(s != 0) { + mchunkptr q = align_as_chunk(s->base); + mchunkptr lastq = 0; + assert(pinuse(q)); + while(segment_holds(s, q) && q != m->top + && q->head != FENCEPOST_HEAD) { + sum += chunksize(q); + if(cinuse(q)) { + assert(!bin_find(m, q)); + do_check_inuse_chunk(m, q); + } else { + assert(q == m->dv || bin_find(m, q)); + assert(lastq == 0 + || cinuse(lastq)); /* Not 2 consecutive free */ + do_check_free_chunk(m, q); + } + lastq = q; + q = next_chunk(q); + } + s = s->next; + } + } + return sum; } /* Check all properties of malloc_state. */ -static void do_check_malloc_state(mstate m) { - bindex_t i; - size_t total; - /* check bins */ - for (i = 0; i < NSMALLBINS; ++i) - do_check_smallbin(m, i); - for (i = 0; i < NTREEBINS; ++i) - do_check_treebin(m, i); - - if (m->dvsize != 0) { /* check dv chunk */ - do_check_any_chunk(m, m->dv); - assert(m->dvsize == chunksize(m->dv)); - assert(m->dvsize >= MIN_CHUNK_SIZE); - assert(bin_find(m, m->dv) == 0); - } - - if (m->top != 0) { /* check top chunk */ - do_check_top_chunk(m, m->top); - assert(m->topsize == chunksize(m->top)); - assert(m->topsize > 0); - assert(bin_find(m, m->top) == 0); - } - - total = traverse_and_check(m); - assert(total <= m->footprint); - assert(m->footprint <= m->max_footprint); +static void do_check_malloc_state(mstate m) +{ + bindex_t i; + size_t total; + /* check bins */ + for(i = 0; i < NSMALLBINS; ++i) + do_check_smallbin(m, i); + for(i = 0; i < NTREEBINS; ++i) + do_check_treebin(m, i); + + if(m->dvsize != 0) { /* check dv chunk */ + do_check_any_chunk(m, m->dv); + assert(m->dvsize == chunksize(m->dv)); + assert(m->dvsize >= MIN_CHUNK_SIZE); + assert(bin_find(m, m->dv) == 0); + } + + if(m->top != 0) { /* check top chunk */ + do_check_top_chunk(m, m->top); + assert(m->topsize == chunksize(m->top)); + assert(m->topsize > 0); + assert(bin_find(m, m->top) == 0); + } + + total = traverse_and_check(m); + assert(total <= m->footprint); + assert(m->footprint <= m->max_footprint); } #endif /* DEBUG */ /* ----------------------------- statistics ------------------------------ */ #if !NO_MALLINFO -static struct mallinfo internal_mallinfo(mstate m) { - struct mallinfo nm = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - if (!PREACTION(m)) { - check_malloc_state(m); - if (is_initialized(m)) { - size_t nfree = SIZE_T_ONE; /* top always free */ - size_t mfree = m->topsize + TOP_FOOT_SIZE; - size_t sum = mfree; - msegmentptr s = &m->seg; - while (s != 0) { - mchunkptr q = align_as_chunk(s->base); - while (segment_holds(s, q) && - q != m->top && q->head != FENCEPOST_HEAD) { - size_t sz = chunksize(q); - sum += sz; - if (!cinuse(q)) { - mfree += sz; - ++nfree; - } - q = next_chunk(q); - } - s = s->next; - } - - nm.arena = sum; - nm.ordblks = nfree; - nm.hblkhd = m->footprint - sum; - nm.usmblks = m->max_footprint; - nm.uordblks = m->footprint - mfree; - nm.fordblks = mfree; - nm.keepcost = m->topsize; - } - - POSTACTION(m); - } - return nm; +static struct mallinfo internal_mallinfo(mstate m) +{ + struct mallinfo nm = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + if(!PREACTION(m)) { + check_malloc_state(m); + if(is_initialized(m)) { + size_t nfree = SIZE_T_ONE; /* top always free */ + size_t mfree = m->topsize + TOP_FOOT_SIZE; + size_t sum = mfree; + msegmentptr s = &m->seg; + while(s != 0) { + mchunkptr q = align_as_chunk(s->base); + while(segment_holds(s, q) && q != m->top + && q->head != FENCEPOST_HEAD) { + size_t sz = chunksize(q); + sum += sz; + if(!cinuse(q)) { + mfree += sz; + ++nfree; + } + q = next_chunk(q); + } + s = s->next; + } + + nm.arena = sum; + nm.ordblks = nfree; + nm.hblkhd = m->footprint - sum; + nm.usmblks = m->max_footprint; + nm.uordblks = m->footprint - mfree; + nm.fordblks = mfree; + nm.keepcost = m->topsize; + } + + POSTACTION(m); + } + return nm; } #endif /* !NO_MALLINFO */ -static void internal_malloc_stats(mstate m) { - if (!PREACTION(m)) { - size_t maxfp = 0; - size_t fp = 0; - size_t used = 0; - check_malloc_state(m); - if (is_initialized(m)) { - msegmentptr s = &m->seg; - maxfp = m->max_footprint; - fp = m->footprint; - used = fp - (m->topsize + TOP_FOOT_SIZE); - - while (s != 0) { - mchunkptr q = align_as_chunk(s->base); - while (segment_holds(s, q) && - q != m->top && q->head != FENCEPOST_HEAD) { - if (!cinuse(q)) - used -= chunksize(q); - q = next_chunk(q); - } - s = s->next; - } - } - - fprintf(stderr, "max system bytes = %10lu\n", (unsigned long)(maxfp)); - fprintf(stderr, "system bytes = %10lu\n", (unsigned long)(fp)); - fprintf(stderr, "in use bytes = %10lu\n", (unsigned long)(used)); - - POSTACTION(m); - } +static void internal_malloc_stats(mstate m) +{ + if(!PREACTION(m)) { + size_t maxfp = 0; + size_t fp = 0; + size_t used = 0; + check_malloc_state(m); + if(is_initialized(m)) { + msegmentptr s = &m->seg; + maxfp = m->max_footprint; + fp = m->footprint; + used = fp - (m->topsize + TOP_FOOT_SIZE); + + while(s != 0) { + mchunkptr q = align_as_chunk(s->base); + while(segment_holds(s, q) && q != m->top + && q->head != FENCEPOST_HEAD) { + if(!cinuse(q)) + used -= chunksize(q); + q = next_chunk(q); + } + s = s->next; + } + } + + fprintf(stderr, "max system bytes = %10lu\n", (unsigned long)(maxfp)); + fprintf(stderr, "system bytes = %10lu\n", (unsigned long)(fp)); + fprintf(stderr, "in use bytes = %10lu\n", (unsigned long)(used)); + + POSTACTION(m); + } } /* ----------------------- Operations on smallbins ----------------------- */ @@ -2867,127 +2907,128 @@ static void internal_malloc_stats(mstate m) { */ /* Link a free chunk into a smallbin */ -#define insert_small_chunk(M, P, S) {\ - bindex_t I = small_index(S);\ - mchunkptr B = smallbin_at(M, I);\ - mchunkptr F = B;\ - assert(S >= MIN_CHUNK_SIZE);\ - if (!smallmap_is_marked(M, I))\ - mark_smallmap(M, I);\ - else if (RTCHECK(ok_address(M, B->fd)))\ - F = B->fd;\ - else {\ - CORRUPTION_ERROR_ACTION(M);\ - }\ - B->fd = P;\ - F->bk = P;\ - P->fd = F;\ - P->bk = B;\ -} +#define insert_small_chunk(M, P, S) \ + { \ + bindex_t I = small_index(S); \ + mchunkptr B = smallbin_at(M, I); \ + mchunkptr F = B; \ + assert(S >= MIN_CHUNK_SIZE); \ + if(!smallmap_is_marked(M, I)) \ + mark_smallmap(M, I); \ + else if(RTCHECK(ok_address(M, B->fd))) \ + F = B->fd; \ + else { \ + CORRUPTION_ERROR_ACTION(M); \ + } \ + B->fd = P; \ + F->bk = P; \ + P->fd = F; \ + P->bk = B; \ + } /* Unlink a chunk from a smallbin */ -#define unlink_small_chunk(M, P, S) {\ - mchunkptr F = P->fd;\ - mchunkptr B = P->bk;\ - bindex_t I = small_index(S);\ - assert(P != B);\ - assert(P != F);\ - assert(chunksize(P) == small_index2size(I));\ - if (F == B)\ - clear_smallmap(M, I);\ - else if (RTCHECK((F == smallbin_at(M,I) || ok_address(M, F)) &&\ - (B == smallbin_at(M,I) || ok_address(M, B)))) {\ - F->bk = B;\ - B->fd = F;\ - }\ - else {\ - CORRUPTION_ERROR_ACTION(M);\ - }\ -} +#define unlink_small_chunk(M, P, S) \ + { \ + mchunkptr F = P->fd; \ + mchunkptr B = P->bk; \ + bindex_t I = small_index(S); \ + assert(P != B); \ + assert(P != F); \ + assert(chunksize(P) == small_index2size(I)); \ + if(F == B) \ + clear_smallmap(M, I); \ + else if(RTCHECK((F == smallbin_at(M, I) || ok_address(M, F)) \ + && (B == smallbin_at(M, I) || ok_address(M, B)))) { \ + F->bk = B; \ + B->fd = F; \ + } else { \ + CORRUPTION_ERROR_ACTION(M); \ + } \ + } /* Unlink the first chunk from a smallbin */ -#define unlink_first_small_chunk(M, B, P, I) {\ - mchunkptr F = P->fd;\ - assert(P != B);\ - assert(P != F);\ - assert(chunksize(P) == small_index2size(I));\ - if (B == F)\ - clear_smallmap(M, I);\ - else if (RTCHECK(ok_address(M, F))) {\ - B->fd = F;\ - F->bk = B;\ - }\ - else {\ - CORRUPTION_ERROR_ACTION(M);\ - }\ -} +#define unlink_first_small_chunk(M, B, P, I) \ + { \ + mchunkptr F = P->fd; \ + assert(P != B); \ + assert(P != F); \ + assert(chunksize(P) == small_index2size(I)); \ + if(B == F) \ + clear_smallmap(M, I); \ + else if(RTCHECK(ok_address(M, F))) { \ + B->fd = F; \ + F->bk = B; \ + } else { \ + CORRUPTION_ERROR_ACTION(M); \ + } \ + } /* Replace dv node, binning the old one */ /* Used only when dvsize known to be small */ -#define replace_dv(M, P, S) {\ - size_t DVS = M->dvsize;\ - if (DVS != 0) {\ - mchunkptr DV = M->dv;\ - assert(is_small(DVS));\ - insert_small_chunk(M, DV, DVS);\ - }\ - M->dvsize = S;\ - M->dv = P;\ -} +#define replace_dv(M, P, S) \ + { \ + size_t DVS = M->dvsize; \ + if(DVS != 0) { \ + mchunkptr DV = M->dv; \ + assert(is_small(DVS)); \ + insert_small_chunk(M, DV, DVS); \ + } \ + M->dvsize = S; \ + M->dv = P; \ + } /* ------------------------- Operations on trees ------------------------- */ /* Insert chunk into tree */ -#define insert_large_chunk(M, X, S) {\ - tbinptr* H;\ - bindex_t I;\ - compute_tree_index(S, I);\ - H = treebin_at(M, I);\ - X->index = I;\ - X->child[0] = X->child[1] = 0;\ - if (!treemap_is_marked(M, I)) {\ - mark_treemap(M, I);\ - *H = X;\ - X->parent = (tchunkptr)H;\ - X->fd = X->bk = X;\ - }\ - else {\ - tchunkptr T = *H;\ - size_t K = S << leftshift_for_tree_index(I);\ - for (;;) {\ - if (chunksize(T) != S) {\ - tchunkptr* C = &(T->child[(K >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]);\ - K <<= 1;\ - if (*C != 0)\ - T = *C;\ - else if (RTCHECK(ok_address(M, C))) {\ - *C = X;\ - X->parent = T;\ - X->fd = X->bk = X;\ - break;\ - }\ - else {\ - CORRUPTION_ERROR_ACTION(M);\ - break;\ - }\ - }\ - else {\ - tchunkptr F = T->fd;\ - if (RTCHECK(ok_address(M, T) && ok_address(M, F))) {\ - T->fd = F->bk = X;\ - X->fd = F;\ - X->bk = T;\ - X->parent = 0;\ - break;\ - }\ - else {\ - CORRUPTION_ERROR_ACTION(M);\ - break;\ - }\ - }\ - }\ - }\ -} +#define insert_large_chunk(M, X, S) \ + { \ + tbinptr *H; \ + bindex_t I; \ + compute_tree_index(S, I); \ + H = treebin_at(M, I); \ + X->index = I; \ + X->child[0] = X->child[1] = 0; \ + if(!treemap_is_marked(M, I)) { \ + mark_treemap(M, I); \ + *H = X; \ + X->parent = (tchunkptr)H; \ + X->fd = X->bk = X; \ + } else { \ + tchunkptr T = *H; \ + size_t K = S << leftshift_for_tree_index(I); \ + for(;;) { \ + if(chunksize(T) != S) { \ + tchunkptr *C = \ + &(T->child[(K >> (SIZE_T_BITSIZE - SIZE_T_ONE)) \ + & 1]); \ + K <<= 1; \ + if(*C != 0) \ + T = *C; \ + else if(RTCHECK(ok_address(M, C))) { \ + *C = X; \ + X->parent = T; \ + X->fd = X->bk = X; \ + break; \ + } else { \ + CORRUPTION_ERROR_ACTION(M); \ + break; \ + } \ + } else { \ + tchunkptr F = T->fd; \ + if(RTCHECK(ok_address(M, T) && ok_address(M, F))) { \ + T->fd = F->bk = X; \ + X->fd = F; \ + X->bk = T; \ + X->parent = 0; \ + break; \ + } else { \ + CORRUPTION_ERROR_ACTION(M); \ + break; \ + } \ + } \ + } \ + } \ + } /* Unlink steps: @@ -3006,99 +3047,103 @@ static void internal_malloc_stats(mstate m) { x's parent and children to x's replacement (or null if none). */ -#define unlink_large_chunk(M, X) {\ - tchunkptr XP = X->parent;\ - tchunkptr R;\ - if (X->bk != X) {\ - tchunkptr F = X->fd;\ - R = X->bk;\ - if (RTCHECK(ok_address(M, F))) {\ - F->bk = R;\ - R->fd = F;\ - }\ - else {\ - CORRUPTION_ERROR_ACTION(M);\ - }\ - }\ - else {\ - tchunkptr* RP;\ - if (((R = *(RP = &(X->child[1]))) != 0) ||\ - ((R = *(RP = &(X->child[0]))) != 0)) {\ - tchunkptr* CP;\ - while ((*(CP = &(R->child[1])) != 0) ||\ - (*(CP = &(R->child[0])) != 0)) {\ - R = *(RP = CP);\ - }\ - if (RTCHECK(ok_address(M, RP)))\ - *RP = 0;\ - else {\ - CORRUPTION_ERROR_ACTION(M);\ - }\ - }\ - }\ - if (XP != 0) {\ - tbinptr* H = treebin_at(M, X->index);\ - if (X == *H) {\ - if ((*H = R) == 0) \ - clear_treemap(M, X->index);\ - }\ - else if (RTCHECK(ok_address(M, XP))) {\ - if (XP->child[0] == X) \ - XP->child[0] = R;\ - else \ - XP->child[1] = R;\ - }\ - else\ - CORRUPTION_ERROR_ACTION(M);\ - if (R != 0) {\ - if (RTCHECK(ok_address(M, R))) {\ - tchunkptr C0, C1;\ - R->parent = XP;\ - if ((C0 = X->child[0]) != 0) {\ - if (RTCHECK(ok_address(M, C0))) {\ - R->child[0] = C0;\ - C0->parent = R;\ - }\ - else\ - CORRUPTION_ERROR_ACTION(M);\ - }\ - if ((C1 = X->child[1]) != 0) {\ - if (RTCHECK(ok_address(M, C1))) {\ - R->child[1] = C1;\ - C1->parent = R;\ - }\ - else\ - CORRUPTION_ERROR_ACTION(M);\ - }\ - }\ - else\ - CORRUPTION_ERROR_ACTION(M);\ - }\ - }\ -} +#define unlink_large_chunk(M, X) \ + { \ + tchunkptr XP = X->parent; \ + tchunkptr R; \ + if(X->bk != X) { \ + tchunkptr F = X->fd; \ + R = X->bk; \ + if(RTCHECK(ok_address(M, F))) { \ + F->bk = R; \ + R->fd = F; \ + } else { \ + CORRUPTION_ERROR_ACTION(M); \ + } \ + } else { \ + tchunkptr *RP; \ + if(((R = *(RP = &(X->child[1]))) != 0) \ + || ((R = *(RP = &(X->child[0]))) != 0)) { \ + tchunkptr *CP; \ + while((*(CP = &(R->child[1])) != 0) \ + || (*(CP = &(R->child[0])) != 0)) { \ + R = *(RP = CP); \ + } \ + if(RTCHECK(ok_address(M, RP))) \ + *RP = 0; \ + else { \ + CORRUPTION_ERROR_ACTION(M); \ + } \ + } \ + } \ + if(XP != 0) { \ + tbinptr *H = treebin_at(M, X->index); \ + if(X == *H) { \ + if((*H = R) == 0) \ + clear_treemap(M, X->index); \ + } else if(RTCHECK(ok_address(M, XP))) { \ + if(XP->child[0] == X) \ + XP->child[0] = R; \ + else \ + XP->child[1] = R; \ + } else \ + CORRUPTION_ERROR_ACTION(M); \ + if(R != 0) { \ + if(RTCHECK(ok_address(M, R))) { \ + tchunkptr C0, C1; \ + R->parent = XP; \ + if((C0 = X->child[0]) != 0) { \ + if(RTCHECK(ok_address(M, C0))) { \ + R->child[0] = C0; \ + C0->parent = R; \ + } else \ + CORRUPTION_ERROR_ACTION(M); \ + } \ + if((C1 = X->child[1]) != 0) { \ + if(RTCHECK(ok_address(M, C1))) { \ + R->child[1] = C1; \ + C1->parent = R; \ + } else \ + CORRUPTION_ERROR_ACTION(M); \ + } \ + } else \ + CORRUPTION_ERROR_ACTION(M); \ + } \ + } \ + } /* Relays to large vs small bin operations */ -#define insert_chunk(M, P, S)\ - if (is_small(S)) insert_small_chunk(M, P, S)\ - else { tchunkptr TP = (tchunkptr)(P); insert_large_chunk(M, TP, S); } +#define insert_chunk(M, P, S) \ + if(is_small(S)) \ + insert_small_chunk(M, P, S) else \ + { \ + tchunkptr TP = (tchunkptr)(P); \ + insert_large_chunk(M, TP, S); \ + } -#define unlink_chunk(M, P, S)\ - if (is_small(S)) unlink_small_chunk(M, P, S)\ - else { tchunkptr TP = (tchunkptr)(P); unlink_large_chunk(M, TP); } +#define unlink_chunk(M, P, S) \ + if(is_small(S)) \ + unlink_small_chunk(M, P, S) else \ + { \ + tchunkptr TP = (tchunkptr)(P); \ + unlink_large_chunk(M, TP); \ + } /* Relays to internal calls to malloc/free from realloc, memalign etc */ #if ONLY_MSPACES #define internal_malloc(m, b) mspace_malloc(m, b) -#define internal_free(m, mem) mspace_free(m,mem); +#define internal_free(m, mem) mspace_free(m, mem); #else /* ONLY_MSPACES */ #if MSPACES -#define internal_malloc(m, b)\ - (m == gm)? dlmalloc(b) : mspace_malloc(m, b) -#define internal_free(m, mem)\ - if (m == gm) dlfree(mem); else mspace_free(m,mem); +#define internal_malloc(m, b) (m == gm) ? dlmalloc(b) : mspace_malloc(m, b) +#define internal_free(m, mem) \ + if(m == gm) \ + dlfree(mem); \ + else \ + mspace_free(m, mem); #else /* MSPACES */ #define internal_malloc(m, b) dlmalloc(b) #define internal_free(m, mem) dlfree(mem) @@ -3118,227 +3163,232 @@ static void internal_malloc_stats(mstate m) { */ /* Malloc using mmap */ -static void* mmap_alloc(mstate m, size_t nb) { - size_t mmsize = granularity_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK); - if (mmsize > nb) { /* Check for wrap around 0 */ - char* mm = (char*)(DIRECT_MMAP(mmsize)); - if (mm != CMFAIL) { - size_t offset = align_offset(chunk2mem(mm)); - size_t psize = mmsize - offset - MMAP_FOOT_PAD; - mchunkptr p = (mchunkptr)(mm + offset); - p->prev_foot = offset | IS_MMAPPED_BIT; - (p)->head = (psize|CINUSE_BIT); - mark_inuse_foot(m, p, psize); - chunk_plus_offset(p, psize)->head = FENCEPOST_HEAD; - chunk_plus_offset(p, psize+SIZE_T_SIZE)->head = 0; - - if (mm < m->least_addr) - m->least_addr = mm; - if ((m->footprint += mmsize) > m->max_footprint) - m->max_footprint = m->footprint; - assert(is_aligned(chunk2mem(p))); - check_mmapped_chunk(m, p); - return chunk2mem(p); - } - } - return 0; +static void *mmap_alloc(mstate m, size_t nb) +{ + size_t mmsize = granularity_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK); + if(mmsize > nb) { /* Check for wrap around 0 */ + char *mm = (char *)(DIRECT_MMAP(mmsize)); + if(mm != CMFAIL) { + size_t offset = align_offset(chunk2mem(mm)); + size_t psize = mmsize - offset - MMAP_FOOT_PAD; + mchunkptr p = (mchunkptr)(mm + offset); + p->prev_foot = offset | IS_MMAPPED_BIT; + (p)->head = (psize | CINUSE_BIT); + mark_inuse_foot(m, p, psize); + chunk_plus_offset(p, psize)->head = FENCEPOST_HEAD; + chunk_plus_offset(p, psize + SIZE_T_SIZE)->head = 0; + + if(mm < m->least_addr) + m->least_addr = mm; + if((m->footprint += mmsize) > m->max_footprint) + m->max_footprint = m->footprint; + assert(is_aligned(chunk2mem(p))); + check_mmapped_chunk(m, p); + return chunk2mem(p); + } + } + return 0; } /* Realloc using mmap */ -static mchunkptr mmap_resize(mstate m, mchunkptr oldp, size_t nb) { - size_t oldsize = chunksize(oldp); - if (is_small(nb)) /* Can't shrink mmap regions below small size */ - return 0; - /* Keep old chunk if big enough but not too big */ - if (oldsize >= nb + SIZE_T_SIZE && - (oldsize - nb) <= (mparams.granularity << 1)) - return oldp; - else { - size_t offset = oldp->prev_foot & ~IS_MMAPPED_BIT; - size_t oldmmsize = oldsize + offset + MMAP_FOOT_PAD; - size_t newmmsize = granularity_align(nb + SIX_SIZE_T_SIZES + - CHUNK_ALIGN_MASK); - char* cp = (char*)CALL_MREMAP((char*)oldp - offset, - oldmmsize, newmmsize, 1); - if (cp != CMFAIL) { - mchunkptr newp = (mchunkptr)(cp + offset); - size_t psize = newmmsize - offset - MMAP_FOOT_PAD; - newp->head = (psize|CINUSE_BIT); - mark_inuse_foot(m, newp, psize); - chunk_plus_offset(newp, psize)->head = FENCEPOST_HEAD; - chunk_plus_offset(newp, psize+SIZE_T_SIZE)->head = 0; - - if (cp < m->least_addr) - m->least_addr = cp; - if ((m->footprint += newmmsize - oldmmsize) > m->max_footprint) - m->max_footprint = m->footprint; - check_mmapped_chunk(m, newp); - return newp; - } - } - return 0; +static mchunkptr mmap_resize(mstate m, mchunkptr oldp, size_t nb) +{ + size_t oldsize = chunksize(oldp); + if(is_small(nb)) /* Can't shrink mmap regions below small size */ + return 0; + /* Keep old chunk if big enough but not too big */ + if(oldsize >= nb + SIZE_T_SIZE + && (oldsize - nb) <= (mparams.granularity << 1)) + return oldp; + else { + size_t offset = oldp->prev_foot & ~IS_MMAPPED_BIT; + size_t oldmmsize = oldsize + offset + MMAP_FOOT_PAD; + size_t newmmsize = + granularity_align(nb + SIX_SIZE_T_SIZES + CHUNK_ALIGN_MASK); + char *cp = (char *)CALL_MREMAP( + (char *)oldp - offset, oldmmsize, newmmsize, 1); + if(cp != CMFAIL) { + mchunkptr newp = (mchunkptr)(cp + offset); + size_t psize = newmmsize - offset - MMAP_FOOT_PAD; + newp->head = (psize | CINUSE_BIT); + mark_inuse_foot(m, newp, psize); + chunk_plus_offset(newp, psize)->head = FENCEPOST_HEAD; + chunk_plus_offset(newp, psize + SIZE_T_SIZE)->head = 0; + + if(cp < m->least_addr) + m->least_addr = cp; + if((m->footprint += newmmsize - oldmmsize) > m->max_footprint) + m->max_footprint = m->footprint; + check_mmapped_chunk(m, newp); + return newp; + } + } + return 0; } /* -------------------------- mspace management -------------------------- */ /* Initialize top chunk and its size */ -static void init_top(mstate m, mchunkptr p, size_t psize) { - /* Ensure alignment */ - size_t offset = align_offset(chunk2mem(p)); - p = (mchunkptr)((char*)p + offset); - psize -= offset; - - m->top = p; - m->topsize = psize; - p->head = psize | PINUSE_BIT; - /* set size of fake trailing chunk holding overhead space only once */ - chunk_plus_offset(p, psize)->head = TOP_FOOT_SIZE; - m->trim_check = mparams.trim_threshold; /* reset on each update */ +static void init_top(mstate m, mchunkptr p, size_t psize) +{ + /* Ensure alignment */ + size_t offset = align_offset(chunk2mem(p)); + p = (mchunkptr)((char *)p + offset); + psize -= offset; + + m->top = p; + m->topsize = psize; + p->head = psize | PINUSE_BIT; + /* set size of fake trailing chunk holding overhead space only once */ + chunk_plus_offset(p, psize)->head = TOP_FOOT_SIZE; + m->trim_check = mparams.trim_threshold; /* reset on each update */ } /* Initialize bins for a new mstate that is otherwise zeroed out */ -static void init_bins(mstate m) { - /* Establish circular links for smallbins */ - bindex_t i; - for (i = 0; i < NSMALLBINS; ++i) { - sbinptr bin = smallbin_at(m,i); - bin->fd = bin->bk = bin; - } +static void init_bins(mstate m) +{ + /* Establish circular links for smallbins */ + bindex_t i; + for(i = 0; i < NSMALLBINS; ++i) { + sbinptr bin = smallbin_at(m, i); + bin->fd = bin->bk = bin; + } } #if PROCEED_ON_ERROR /* default corruption action */ -static void reset_on_error(mstate m) { - int i; - ++malloc_corruption_error_count; - /* Reinitialize fields to forget about all memory */ - m->smallbins = m->treebins = 0; - m->dvsize = m->topsize = 0; - m->seg.base = 0; - m->seg.size = 0; - m->seg.next = 0; - m->top = m->dv = 0; - for (i = 0; i < NTREEBINS; ++i) - *treebin_at(m, i) = 0; - init_bins(m); +static void reset_on_error(mstate m) +{ + int i; + ++malloc_corruption_error_count; + /* Reinitialize fields to forget about all memory */ + m->smallbins = m->treebins = 0; + m->dvsize = m->topsize = 0; + m->seg.base = 0; + m->seg.size = 0; + m->seg.next = 0; + m->top = m->dv = 0; + for(i = 0; i < NTREEBINS; ++i) + *treebin_at(m, i) = 0; + init_bins(m); } #endif /* PROCEED_ON_ERROR */ /* Allocate chunk and prepend remainder with chunk in successor base. */ -static void* prepend_alloc(mstate m, char* newbase, char* oldbase, - size_t nb) { - mchunkptr p = align_as_chunk(newbase); - mchunkptr oldfirst = align_as_chunk(oldbase); - size_t psize = (char*)oldfirst - (char*)p; - mchunkptr q = chunk_plus_offset(p, nb); - size_t qsize = psize - nb; - set_size_and_pinuse_of_inuse_chunk(m, p, nb); - - assert((char*)oldfirst > (char*)q); - assert(pinuse(oldfirst)); - assert(qsize >= MIN_CHUNK_SIZE); - - /* consolidate remainder with first chunk of old base */ - if (oldfirst == m->top) { - size_t tsize = m->topsize += qsize; - m->top = q; - q->head = tsize | PINUSE_BIT; - check_top_chunk(m, q); - } - else if (oldfirst == m->dv) { - size_t dsize = m->dvsize += qsize; - m->dv = q; - set_size_and_pinuse_of_free_chunk(q, dsize); - } - else { - if (!cinuse(oldfirst)) { - size_t nsize = chunksize(oldfirst); - unlink_chunk(m, oldfirst, nsize); - oldfirst = chunk_plus_offset(oldfirst, nsize); - qsize += nsize; - } - set_free_with_pinuse(q, qsize, oldfirst); - insert_chunk(m, q, qsize); - check_free_chunk(m, q); - } - - check_malloced_chunk(m, chunk2mem(p), nb); - return chunk2mem(p); +static void *prepend_alloc(mstate m, char *newbase, char *oldbase, size_t nb) +{ + mchunkptr p = align_as_chunk(newbase); + mchunkptr oldfirst = align_as_chunk(oldbase); + size_t psize = (char *)oldfirst - (char *)p; + mchunkptr q = chunk_plus_offset(p, nb); + size_t qsize = psize - nb; + set_size_and_pinuse_of_inuse_chunk(m, p, nb); + + assert((char *)oldfirst > (char *)q); + assert(pinuse(oldfirst)); + assert(qsize >= MIN_CHUNK_SIZE); + + /* consolidate remainder with first chunk of old base */ + if(oldfirst == m->top) { + size_t tsize = m->topsize += qsize; + m->top = q; + q->head = tsize | PINUSE_BIT; + check_top_chunk(m, q); + } else if(oldfirst == m->dv) { + size_t dsize = m->dvsize += qsize; + m->dv = q; + set_size_and_pinuse_of_free_chunk(q, dsize); + } else { + if(!cinuse(oldfirst)) { + size_t nsize = chunksize(oldfirst); + unlink_chunk(m, oldfirst, nsize); + oldfirst = chunk_plus_offset(oldfirst, nsize); + qsize += nsize; + } + set_free_with_pinuse(q, qsize, oldfirst); + insert_chunk(m, q, qsize); + check_free_chunk(m, q); + } + + check_malloced_chunk(m, chunk2mem(p), nb); + return chunk2mem(p); } /* Add a segment to hold a new noncontiguous region */ -static void add_segment(mstate m, char* tbase, size_t tsize, flag_t mmapped) { - /* Determine locations and sizes of segment, fenceposts, old top */ - char* old_top = (char*)m->top; - msegmentptr oldsp = segment_holding(m, old_top); - char* old_end = oldsp->base + oldsp->size; - size_t ssize = pad_request(sizeof(struct malloc_segment)); - char* rawsp = old_end - (ssize + FOUR_SIZE_T_SIZES + CHUNK_ALIGN_MASK); - size_t offset = align_offset(chunk2mem(rawsp)); - char* asp = rawsp + offset; - char* csp = (asp < (old_top + MIN_CHUNK_SIZE))? old_top : asp; - mchunkptr sp = (mchunkptr)csp; - msegmentptr ss = (msegmentptr)(chunk2mem(sp)); - mchunkptr tnext = chunk_plus_offset(sp, ssize); - mchunkptr p = tnext; - int nfences = 0; - - /* reset top to new space */ - init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE); - - /* Set up segment record */ - assert(is_aligned(ss)); - set_size_and_pinuse_of_inuse_chunk(m, sp, ssize); - *ss = m->seg; /* Push current record */ - m->seg.base = tbase; - m->seg.size = tsize; - m->seg.sflags = mmapped; - m->seg.next = ss; - - /* Insert trailing fenceposts */ - for (;;) { - mchunkptr nextp = chunk_plus_offset(p, SIZE_T_SIZE); - p->head = FENCEPOST_HEAD; - ++nfences; - if ((char*)(&(nextp->head)) < old_end) - p = nextp; - else - break; - } - assert(nfences >= 2); - - /* Insert the rest of old top into a bin as an ordinary free chunk */ - if (csp != old_top) { - mchunkptr q = (mchunkptr)old_top; - size_t psize = csp - old_top; - mchunkptr tn = chunk_plus_offset(q, psize); - set_free_with_pinuse(q, psize, tn); - insert_chunk(m, q, psize); - } - - check_top_chunk(m, m->top); +static void add_segment(mstate m, char *tbase, size_t tsize, flag_t mmapped) +{ + /* Determine locations and sizes of segment, fenceposts, old top */ + char *old_top = (char *)m->top; + msegmentptr oldsp = segment_holding(m, old_top); + char *old_end = oldsp->base + oldsp->size; + size_t ssize = pad_request(sizeof(struct malloc_segment)); + char *rawsp = old_end - (ssize + FOUR_SIZE_T_SIZES + CHUNK_ALIGN_MASK); + size_t offset = align_offset(chunk2mem(rawsp)); + char *asp = rawsp + offset; + char *csp = (asp < (old_top + MIN_CHUNK_SIZE)) ? old_top : asp; + mchunkptr sp = (mchunkptr)csp; + msegmentptr ss = (msegmentptr)(chunk2mem(sp)); + mchunkptr tnext = chunk_plus_offset(sp, ssize); + mchunkptr p = tnext; + int nfences = 0; + + /* reset top to new space */ + init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE); + + /* Set up segment record */ + assert(is_aligned(ss)); + set_size_and_pinuse_of_inuse_chunk(m, sp, ssize); + *ss = m->seg; /* Push current record */ + m->seg.base = tbase; + m->seg.size = tsize; + m->seg.sflags = mmapped; + m->seg.next = ss; + + /* Insert trailing fenceposts */ + for(;;) { + mchunkptr nextp = chunk_plus_offset(p, SIZE_T_SIZE); + p->head = FENCEPOST_HEAD; + ++nfences; + if((char *)(&(nextp->head)) < old_end) + p = nextp; + else + break; + } + assert(nfences >= 2); + + /* Insert the rest of old top into a bin as an ordinary free chunk */ + if(csp != old_top) { + mchunkptr q = (mchunkptr)old_top; + size_t psize = csp - old_top; + mchunkptr tn = chunk_plus_offset(q, psize); + set_free_with_pinuse(q, psize, tn); + insert_chunk(m, q, psize); + } + + check_top_chunk(m, m->top); } /* -------------------------- System allocation -------------------------- */ /* Get memory from system using MORECORE or MMAP */ -static void* sys_alloc(mstate m, size_t nb) { - char* tbase = CMFAIL; - size_t tsize = 0; - flag_t mmap_flag = 0; - - init_mparams(); - - /* Directly map large chunks */ - if (use_mmap(m) && nb >= mparams.mmap_threshold) { - void* mem = mmap_alloc(m, nb); - if (mem != 0) - return mem; - } +static void *sys_alloc(mstate m, size_t nb) +{ + char *tbase = CMFAIL; + size_t tsize = 0; + flag_t mmap_flag = 0; - /* + init_mparams(); + + /* Directly map large chunks */ + if(use_mmap(m) && nb >= mparams.mmap_threshold) { + void *mem = mmap_alloc(m, nb); + if(mem != 0) + return mem; + } + + /* Try getting memory in any of three ways (in most-preferred to least-preferred order): 1. A call to MORECORE that can normally contiguously extend memory. @@ -3355,485 +3405,488 @@ static void* sys_alloc(mstate m, size_t nb) { (disabled if not HAVE_MORECORE) */ - if (MORECORE_CONTIGUOUS && !use_noncontiguous(m)) { - char* br = CMFAIL; - msegmentptr ss = (m->top == 0)? 0 : segment_holding(m, (char*)m->top); - size_t asize = 0; - ACQUIRE_MORECORE_LOCK(); - - if (ss == 0) { /* First time through or recovery */ - char* base = (char*)CALL_MORECORE(0); - if (base != CMFAIL) { - asize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE); - /* Adjust to end on a page boundary */ - if (!is_page_aligned(base)) - asize += (page_align((size_t)base) - (size_t)base); - /* Can't call MORECORE if size is negative when treated as signed */ - if (asize < HALF_MAX_SIZE_T && - (br = (char*)(CALL_MORECORE(asize))) == base) { - tbase = base; - tsize = asize; - } - } - } - else { - /* Subtract out existing available top space from MORECORE request. */ - asize = granularity_align(nb - m->topsize + TOP_FOOT_SIZE + SIZE_T_ONE); - /* Use mem here only if it did continuously extend old space */ - if (asize < HALF_MAX_SIZE_T && - (br = (char*)(CALL_MORECORE(asize))) == ss->base+ss->size) { - tbase = br; - tsize = asize; - } - } - - if (tbase == CMFAIL) { /* Cope with partial failure */ - if (br != CMFAIL) { /* Try to use/extend the space we did get */ - if (asize < HALF_MAX_SIZE_T && - asize < nb + TOP_FOOT_SIZE + SIZE_T_ONE) { - size_t esize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE - asize); - if (esize < HALF_MAX_SIZE_T) { - char* end = (char*)CALL_MORECORE(esize); - if (end != CMFAIL) - asize += esize; - else { /* Can't use; try to release */ - CALL_MORECORE(-asize); - br = CMFAIL; - } - } - } - } - if (br != CMFAIL) { /* Use the space we did get */ - tbase = br; - tsize = asize; - } - else - disable_contiguous(m); /* Don't try contiguous path in the future */ - } - - RELEASE_MORECORE_LOCK(); - } - - if (HAVE_MMAP && tbase == CMFAIL) { /* Try MMAP */ - size_t req = nb + TOP_FOOT_SIZE + SIZE_T_ONE; - size_t rsize = granularity_align(req); - if (rsize > nb) { /* Fail if wraps around zero */ - char* mp = (char*)(CALL_MMAP(rsize)); - if (mp != CMFAIL) { - tbase = mp; - tsize = rsize; - mmap_flag = IS_MMAPPED_BIT; - } - } - } - - if (HAVE_MORECORE && tbase == CMFAIL) { /* Try noncontiguous MORECORE */ - size_t asize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE); - if (asize < HALF_MAX_SIZE_T) { - char* br = CMFAIL; - char* end = CMFAIL; - ACQUIRE_MORECORE_LOCK(); - br = (char*)(CALL_MORECORE(asize)); - end = (char*)(CALL_MORECORE(0)); - RELEASE_MORECORE_LOCK(); - if (br != CMFAIL && end != CMFAIL && br < end) { - size_t ssize = end - br; - if (ssize > nb + TOP_FOOT_SIZE) { - tbase = br; - tsize = ssize; - } - } - } - } - - if (tbase != CMFAIL) { - - if ((m->footprint += tsize) > m->max_footprint) - m->max_footprint = m->footprint; - - if (!is_initialized(m)) { /* first-time initialization */ - m->seg.base = m->least_addr = tbase; - m->seg.size = tsize; - m->seg.sflags = mmap_flag; - m->magic = mparams.magic; - init_bins(m); - if (is_global(m)) - init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE); - else { - /* Offset top by embedded malloc_state */ - mchunkptr mn = next_chunk(mem2chunk(m)); - init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) -TOP_FOOT_SIZE); - } - } - - else { - /* Try to merge with an existing segment */ - msegmentptr sp = &m->seg; - while (sp != 0 && tbase != sp->base + sp->size) - sp = sp->next; - if (sp != 0 && - !is_extern_segment(sp) && - (sp->sflags & IS_MMAPPED_BIT) == mmap_flag && - segment_holds(sp, m->top)) { /* append */ - sp->size += tsize; - init_top(m, m->top, m->topsize + tsize); - } - else { - if (tbase < m->least_addr) - m->least_addr = tbase; - sp = &m->seg; - while (sp != 0 && sp->base != tbase + tsize) - sp = sp->next; - if (sp != 0 && - !is_extern_segment(sp) && - (sp->sflags & IS_MMAPPED_BIT) == mmap_flag) { - char* oldbase = sp->base; - sp->base = tbase; - sp->size += tsize; - return prepend_alloc(m, tbase, oldbase, nb); - } - else - add_segment(m, tbase, tsize, mmap_flag); - } - } - - if (nb < m->topsize) { /* Allocate from new or extended top space */ - size_t rsize = m->topsize -= nb; - mchunkptr p = m->top; - mchunkptr r = m->top = chunk_plus_offset(p, nb); - r->head = rsize | PINUSE_BIT; - set_size_and_pinuse_of_inuse_chunk(m, p, nb); - check_top_chunk(m, m->top); - check_malloced_chunk(m, chunk2mem(p), nb); - return chunk2mem(p); - } - } - - MALLOC_FAILURE_ACTION; - return 0; + if(MORECORE_CONTIGUOUS && !use_noncontiguous(m)) { + char *br = CMFAIL; + msegmentptr ss = (m->top == 0) ? 0 : segment_holding(m, (char *)m->top); + size_t asize = 0; + ACQUIRE_MORECORE_LOCK(); + + if(ss == 0) { /* First time through or recovery */ + char *base = (char *)CALL_MORECORE(0); + if(base != CMFAIL) { + asize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE); + /* Adjust to end on a page boundary */ + if(!is_page_aligned(base)) + asize += (page_align((size_t)base) - (size_t)base); + /* Can't call MORECORE if size is negative when treated as signed */ + if(asize < HALF_MAX_SIZE_T + && (br = (char *)(CALL_MORECORE(asize))) == base) { + tbase = base; + tsize = asize; + } + } + } else { + /* Subtract out existing available top space from MORECORE request. */ + asize = granularity_align( + nb - m->topsize + TOP_FOOT_SIZE + SIZE_T_ONE); + /* Use mem here only if it did continuously extend old space */ + if(asize < HALF_MAX_SIZE_T + && (br = (char *)(CALL_MORECORE(asize))) + == ss->base + ss->size) { + tbase = br; + tsize = asize; + } + } + + if(tbase == CMFAIL) { /* Cope with partial failure */ + if(br != CMFAIL) { /* Try to use/extend the space we did get */ + if(asize < HALF_MAX_SIZE_T + && asize < nb + TOP_FOOT_SIZE + SIZE_T_ONE) { + size_t esize = granularity_align( + nb + TOP_FOOT_SIZE + SIZE_T_ONE - asize); + if(esize < HALF_MAX_SIZE_T) { + char *end = (char *)CALL_MORECORE(esize); + if(end != CMFAIL) + asize += esize; + else { /* Can't use; try to release */ + CALL_MORECORE(-asize); + br = CMFAIL; + } + } + } + } + if(br != CMFAIL) { /* Use the space we did get */ + tbase = br; + tsize = asize; + } else + disable_contiguous( + m); /* Don't try contiguous path in the future */ + } + + RELEASE_MORECORE_LOCK(); + } + + if(HAVE_MMAP && tbase == CMFAIL) { /* Try MMAP */ + size_t req = nb + TOP_FOOT_SIZE + SIZE_T_ONE; + size_t rsize = granularity_align(req); + if(rsize > nb) { /* Fail if wraps around zero */ + char *mp = (char *)(CALL_MMAP(rsize)); + if(mp != CMFAIL) { + tbase = mp; + tsize = rsize; + mmap_flag = IS_MMAPPED_BIT; + } + } + } + + if(HAVE_MORECORE && tbase == CMFAIL) { /* Try noncontiguous MORECORE */ + size_t asize = granularity_align(nb + TOP_FOOT_SIZE + SIZE_T_ONE); + if(asize < HALF_MAX_SIZE_T) { + char *br = CMFAIL; + char *end = CMFAIL; + ACQUIRE_MORECORE_LOCK(); + br = (char *)(CALL_MORECORE(asize)); + end = (char *)(CALL_MORECORE(0)); + RELEASE_MORECORE_LOCK(); + if(br != CMFAIL && end != CMFAIL && br < end) { + size_t ssize = end - br; + if(ssize > nb + TOP_FOOT_SIZE) { + tbase = br; + tsize = ssize; + } + } + } + } + + if(tbase != CMFAIL) { + + if((m->footprint += tsize) > m->max_footprint) + m->max_footprint = m->footprint; + + if(!is_initialized(m)) { /* first-time initialization */ + m->seg.base = m->least_addr = tbase; + m->seg.size = tsize; + m->seg.sflags = mmap_flag; + m->magic = mparams.magic; + init_bins(m); + if(is_global(m)) + init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE); + else { + /* Offset top by embedded malloc_state */ + mchunkptr mn = next_chunk(mem2chunk(m)); + init_top(m, mn, + (size_t)((tbase + tsize) - (char *)mn) - TOP_FOOT_SIZE); + } + } + + else { + /* Try to merge with an existing segment */ + msegmentptr sp = &m->seg; + while(sp != 0 && tbase != sp->base + sp->size) + sp = sp->next; + if(sp != 0 && !is_extern_segment(sp) + && (sp->sflags & IS_MMAPPED_BIT) == mmap_flag + && segment_holds(sp, m->top)) { /* append */ + sp->size += tsize; + init_top(m, m->top, m->topsize + tsize); + } else { + if(tbase < m->least_addr) + m->least_addr = tbase; + sp = &m->seg; + while(sp != 0 && sp->base != tbase + tsize) + sp = sp->next; + if(sp != 0 && !is_extern_segment(sp) + && (sp->sflags & IS_MMAPPED_BIT) == mmap_flag) { + char *oldbase = sp->base; + sp->base = tbase; + sp->size += tsize; + return prepend_alloc(m, tbase, oldbase, nb); + } else + add_segment(m, tbase, tsize, mmap_flag); + } + } + + if(nb < m->topsize) { /* Allocate from new or extended top space */ + size_t rsize = m->topsize -= nb; + mchunkptr p = m->top; + mchunkptr r = m->top = chunk_plus_offset(p, nb); + r->head = rsize | PINUSE_BIT; + set_size_and_pinuse_of_inuse_chunk(m, p, nb); + check_top_chunk(m, m->top); + check_malloced_chunk(m, chunk2mem(p), nb); + return chunk2mem(p); + } + } + + MALLOC_FAILURE_ACTION; + return 0; } /* ----------------------- system deallocation -------------------------- */ /* Unmap and unlink any mmapped segments that don't contain used chunks */ -static size_t release_unused_segments(mstate m) { - size_t released = 0; - msegmentptr pred = &m->seg; - msegmentptr sp = pred->next; - while (sp != 0) { - char* base = sp->base; - size_t size = sp->size; - msegmentptr next = sp->next; - if (is_mmapped_segment(sp) && !is_extern_segment(sp)) { - mchunkptr p = align_as_chunk(base); - size_t psize = chunksize(p); - /* Can unmap if first chunk holds entire segment and not pinned */ - if (!cinuse(p) && (char*)p + psize >= base + size - TOP_FOOT_SIZE) { - tchunkptr tp = (tchunkptr)p; - assert(segment_holds(sp, (char*)sp)); - if (p == m->dv) { - m->dv = 0; - m->dvsize = 0; - } - else { - unlink_large_chunk(m, tp); - } - if (CALL_MUNMAP(base, size) == 0) { - released += size; - m->footprint -= size; - /* unlink obsoleted record */ - sp = pred; - sp->next = next; - } - else { /* back out if cannot unmap */ - insert_large_chunk(m, tp, psize); - } - } - } - pred = sp; - sp = next; - } - return released; +static size_t release_unused_segments(mstate m) +{ + size_t released = 0; + msegmentptr pred = &m->seg; + msegmentptr sp = pred->next; + while(sp != 0) { + char *base = sp->base; + size_t size = sp->size; + msegmentptr next = sp->next; + if(is_mmapped_segment(sp) && !is_extern_segment(sp)) { + mchunkptr p = align_as_chunk(base); + size_t psize = chunksize(p); + /* Can unmap if first chunk holds entire segment and not pinned */ + if(!cinuse(p) && (char *)p + psize >= base + size - TOP_FOOT_SIZE) { + tchunkptr tp = (tchunkptr)p; + assert(segment_holds(sp, (char *)sp)); + if(p == m->dv) { + m->dv = 0; + m->dvsize = 0; + } else { + unlink_large_chunk(m, tp); + } + if(CALL_MUNMAP(base, size) == 0) { + released += size; + m->footprint -= size; + /* unlink obsoleted record */ + sp = pred; + sp->next = next; + } else { /* back out if cannot unmap */ + insert_large_chunk(m, tp, psize); + } + } + } + pred = sp; + sp = next; + } + return released; } -static int sys_trim(mstate m, size_t pad) { - size_t released = 0; - if (pad < MAX_REQUEST && is_initialized(m)) { - pad += TOP_FOOT_SIZE; /* ensure enough room for segment overhead */ - - if (m->topsize > pad) { - /* Shrink top space in granularity-size units, keeping at least one */ - size_t unit = mparams.granularity; - size_t extra = ((m->topsize - pad + (unit - SIZE_T_ONE)) / unit - - SIZE_T_ONE) * unit; - msegmentptr sp = segment_holding(m, (char*)m->top); - - if (!is_extern_segment(sp)) { - if (is_mmapped_segment(sp)) { - if (HAVE_MMAP && - sp->size >= extra && - !has_segment_link(m, sp)) { /* can't shrink if pinned */ - size_t newsize = sp->size - extra; - /* Prefer mremap, fall back to munmap */ - if ((CALL_MREMAP(sp->base, sp->size, newsize, 0) != MFAIL) || - (CALL_MUNMAP(sp->base + newsize, extra) == 0)) { - released = extra; - } - } - } - else if (HAVE_MORECORE) { - if (extra >= HALF_MAX_SIZE_T) /* Avoid wrapping negative */ - extra = (HALF_MAX_SIZE_T) + SIZE_T_ONE - unit; - ACQUIRE_MORECORE_LOCK(); - { - /* Make sure end of memory is where we last set it. */ - char* old_br = (char*)(CALL_MORECORE(0)); - if (old_br == sp->base + sp->size) { - char* rel_br = (char*)(CALL_MORECORE(-extra)); - char* new_br = (char*)(CALL_MORECORE(0)); - if (rel_br != CMFAIL && new_br < old_br) - released = old_br - new_br; - } - } - RELEASE_MORECORE_LOCK(); - } - } - - if (released != 0) { - sp->size -= released; - m->footprint -= released; - init_top(m, m->top, m->topsize - released); - check_top_chunk(m, m->top); - } - } - - /* Unmap any unused mmapped segments */ - if (HAVE_MMAP) - released += release_unused_segments(m); - - /* On failure, disable autotrim to avoid repeated failed future calls */ - if (released == 0) - m->trim_check = MAX_SIZE_T; - } - - return (released != 0)? 1 : 0; +static int sys_trim(mstate m, size_t pad) +{ + size_t released = 0; + if(pad < MAX_REQUEST && is_initialized(m)) { + pad += TOP_FOOT_SIZE; /* ensure enough room for segment overhead */ + + if(m->topsize > pad) { + /* Shrink top space in granularity-size units, keeping at least one */ + size_t unit = mparams.granularity; + size_t extra = ((m->topsize - pad + (unit - SIZE_T_ONE)) / unit + - SIZE_T_ONE) + * unit; + msegmentptr sp = segment_holding(m, (char *)m->top); + + if(!is_extern_segment(sp)) { + if(is_mmapped_segment(sp)) { + if(HAVE_MMAP && sp->size >= extra + && !has_segment_link( + m, sp)) { /* can't shrink if pinned */ + size_t newsize = sp->size - extra; + /* Prefer mremap, fall back to munmap */ + if((CALL_MREMAP(sp->base, sp->size, newsize, 0) + != MFAIL) + || (CALL_MUNMAP(sp->base + newsize, extra) + == 0)) { + released = extra; + } + } + } else if(HAVE_MORECORE) { + if(extra >= HALF_MAX_SIZE_T) /* Avoid wrapping negative */ + extra = (HALF_MAX_SIZE_T) + SIZE_T_ONE - unit; + ACQUIRE_MORECORE_LOCK(); + { + /* Make sure end of memory is where we last set it. */ + char *old_br = (char *)(CALL_MORECORE(0)); + if(old_br == sp->base + sp->size) { + char *rel_br = (char *)(CALL_MORECORE(-extra)); + char *new_br = (char *)(CALL_MORECORE(0)); + if(rel_br != CMFAIL && new_br < old_br) + released = old_br - new_br; + } + } + RELEASE_MORECORE_LOCK(); + } + } + + if(released != 0) { + sp->size -= released; + m->footprint -= released; + init_top(m, m->top, m->topsize - released); + check_top_chunk(m, m->top); + } + } + + /* Unmap any unused mmapped segments */ + if(HAVE_MMAP) + released += release_unused_segments(m); + + /* On failure, disable autotrim to avoid repeated failed future calls */ + if(released == 0) + m->trim_check = MAX_SIZE_T; + } + + return (released != 0) ? 1 : 0; } /* ---------------------------- malloc support --------------------------- */ /* allocate a large request from the best fitting chunk in a treebin */ -static void* tmalloc_large(mstate m, size_t nb) { - tchunkptr v = 0; - size_t rsize = -nb; /* Unsigned negation */ - tchunkptr t; - bindex_t idx; - compute_tree_index(nb, idx); - - if ((t = *treebin_at(m, idx)) != 0) { - /* Traverse tree for this bin looking for node with size == nb */ - size_t sizebits = nb << leftshift_for_tree_index(idx); - tchunkptr rst = 0; /* The deepest untaken right subtree */ - for (;;) { - tchunkptr rt; - size_t trem = chunksize(t) - nb; - if (trem < rsize) { - v = t; - if ((rsize = trem) == 0) - break; - } - rt = t->child[1]; - t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]; - if (rt != 0 && rt != t) - rst = rt; - if (t == 0) { - t = rst; /* set t to least subtree holding sizes > nb */ - break; - } - sizebits <<= 1; - } - } - - if (t == 0 && v == 0) { /* set t to root of next non-empty treebin */ - binmap_t leftbits = left_bits(idx2bit(idx)) & m->treemap; - if (leftbits != 0) { - bindex_t i; - binmap_t leastbit = least_bit(leftbits); - compute_bit2idx(leastbit, i); - t = *treebin_at(m, i); - } - } - - while (t != 0) { /* find smallest of tree or subtree */ - size_t trem = chunksize(t) - nb; - if (trem < rsize) { - rsize = trem; - v = t; - } - t = leftmost_child(t); - } - - /* If dv is a better fit, return 0 so malloc will use it */ - if (v != 0 && rsize < (size_t)(m->dvsize - nb)) { - if (RTCHECK(ok_address(m, v))) { /* split */ - mchunkptr r = chunk_plus_offset(v, nb); - assert(chunksize(v) == rsize + nb); - if (RTCHECK(ok_next(v, r))) { - unlink_large_chunk(m, v); - if (rsize < MIN_CHUNK_SIZE) - set_inuse_and_pinuse(m, v, (rsize + nb)); - else { - set_size_and_pinuse_of_inuse_chunk(m, v, nb); - set_size_and_pinuse_of_free_chunk(r, rsize); - insert_chunk(m, r, rsize); - } - return chunk2mem(v); - } - } - CORRUPTION_ERROR_ACTION(m); - } - return 0; +static void *tmalloc_large(mstate m, size_t nb) +{ + tchunkptr v = 0; + size_t rsize = -nb; /* Unsigned negation */ + tchunkptr t; + bindex_t idx; + compute_tree_index(nb, idx); + + if((t = *treebin_at(m, idx)) != 0) { + /* Traverse tree for this bin looking for node with size == nb */ + size_t sizebits = nb << leftshift_for_tree_index(idx); + tchunkptr rst = 0; /* The deepest untaken right subtree */ + for(;;) { + tchunkptr rt; + size_t trem = chunksize(t) - nb; + if(trem < rsize) { + v = t; + if((rsize = trem) == 0) + break; + } + rt = t->child[1]; + t = t->child[(sizebits >> (SIZE_T_BITSIZE - SIZE_T_ONE)) & 1]; + if(rt != 0 && rt != t) + rst = rt; + if(t == 0) { + t = rst; /* set t to least subtree holding sizes > nb */ + break; + } + sizebits <<= 1; + } + } + + if(t == 0 && v == 0) { /* set t to root of next non-empty treebin */ + binmap_t leftbits = left_bits(idx2bit(idx)) & m->treemap; + if(leftbits != 0) { + bindex_t i; + binmap_t leastbit = least_bit(leftbits); + compute_bit2idx(leastbit, i); + t = *treebin_at(m, i); + } + } + + while(t != 0) { /* find smallest of tree or subtree */ + size_t trem = chunksize(t) - nb; + if(trem < rsize) { + rsize = trem; + v = t; + } + t = leftmost_child(t); + } + + /* If dv is a better fit, return 0 so malloc will use it */ + if(v != 0 && rsize < (size_t)(m->dvsize - nb)) { + if(RTCHECK(ok_address(m, v))) { /* split */ + mchunkptr r = chunk_plus_offset(v, nb); + assert(chunksize(v) == rsize + nb); + if(RTCHECK(ok_next(v, r))) { + unlink_large_chunk(m, v); + if(rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(m, v, (rsize + nb)); + else { + set_size_and_pinuse_of_inuse_chunk(m, v, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + insert_chunk(m, r, rsize); + } + return chunk2mem(v); + } + } + CORRUPTION_ERROR_ACTION(m); + } + return 0; } /* allocate a small request from the best fitting chunk in a treebin */ -static void* tmalloc_small(mstate m, size_t nb) { - tchunkptr t, v; - size_t rsize; - bindex_t i; - binmap_t leastbit = least_bit(m->treemap); - compute_bit2idx(leastbit, i); - - v = t = *treebin_at(m, i); - rsize = chunksize(t) - nb; - - while ((t = leftmost_child(t)) != 0) { - size_t trem = chunksize(t) - nb; - if (trem < rsize) { - rsize = trem; - v = t; - } - } - - if (RTCHECK(ok_address(m, v))) { - mchunkptr r = chunk_plus_offset(v, nb); - assert(chunksize(v) == rsize + nb); - if (RTCHECK(ok_next(v, r))) { - unlink_large_chunk(m, v); - if (rsize < MIN_CHUNK_SIZE) - set_inuse_and_pinuse(m, v, (rsize + nb)); - else { - set_size_and_pinuse_of_inuse_chunk(m, v, nb); - set_size_and_pinuse_of_free_chunk(r, rsize); - replace_dv(m, r, rsize); - } - return chunk2mem(v); - } - } - - CORRUPTION_ERROR_ACTION(m); - return 0; +static void *tmalloc_small(mstate m, size_t nb) +{ + tchunkptr t, v; + size_t rsize; + bindex_t i; + binmap_t leastbit = least_bit(m->treemap); + compute_bit2idx(leastbit, i); + + v = t = *treebin_at(m, i); + rsize = chunksize(t) - nb; + + while((t = leftmost_child(t)) != 0) { + size_t trem = chunksize(t) - nb; + if(trem < rsize) { + rsize = trem; + v = t; + } + } + + if(RTCHECK(ok_address(m, v))) { + mchunkptr r = chunk_plus_offset(v, nb); + assert(chunksize(v) == rsize + nb); + if(RTCHECK(ok_next(v, r))) { + unlink_large_chunk(m, v); + if(rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(m, v, (rsize + nb)); + else { + set_size_and_pinuse_of_inuse_chunk(m, v, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + replace_dv(m, r, rsize); + } + return chunk2mem(v); + } + } + + CORRUPTION_ERROR_ACTION(m); + return 0; } /* --------------------------- realloc support --------------------------- */ -static void* internal_realloc(mstate m, void* oldmem, size_t bytes) { - if (bytes >= MAX_REQUEST) { - MALLOC_FAILURE_ACTION; - return 0; - } - if (!PREACTION(m)) { - mchunkptr oldp = mem2chunk(oldmem); - size_t oldsize = chunksize(oldp); - mchunkptr next = chunk_plus_offset(oldp, oldsize); - mchunkptr newp = 0; - void* extra = 0; - - /* Try to either shrink or extend into top. Else malloc-copy-free */ - - if (RTCHECK(ok_address(m, oldp) && ok_cinuse(oldp) && - ok_next(oldp, next) && ok_pinuse(next))) { - size_t nb = request2size(bytes); - if (is_mmapped(oldp)) - newp = mmap_resize(m, oldp, nb); - else if (oldsize >= nb) { /* already big enough */ - size_t rsize = oldsize - nb; - newp = oldp; - if (rsize >= MIN_CHUNK_SIZE) { - mchunkptr remainder = chunk_plus_offset(newp, nb); - set_inuse(m, newp, nb); - set_inuse(m, remainder, rsize); - extra = chunk2mem(remainder); - } - } - else if (next == m->top && oldsize + m->topsize > nb) { - /* Expand into top */ - size_t newsize = oldsize + m->topsize; - size_t newtopsize = newsize - nb; - mchunkptr newtop = chunk_plus_offset(oldp, nb); - set_inuse(m, oldp, nb); - newtop->head = newtopsize |PINUSE_BIT; - m->top = newtop; - m->topsize = newtopsize; - newp = oldp; - } - } - else { - USAGE_ERROR_ACTION(m, oldmem); - POSTACTION(m); - return 0; - } - - POSTACTION(m); - - if (newp != 0) { - if (extra != 0) { - internal_free(m, extra); - } - check_inuse_chunk(m, newp); - return chunk2mem(newp); - } - else { - void* newmem = internal_malloc(m, bytes); - if (newmem != 0) { - size_t oc = oldsize - overhead_for(oldp); - memcpy(newmem, oldmem, (oc < bytes)? oc : bytes); - internal_free(m, oldmem); - } - return newmem; - } - } - return 0; +static void *internal_realloc(mstate m, void *oldmem, size_t bytes) +{ + if(bytes >= MAX_REQUEST) { + MALLOC_FAILURE_ACTION; + return 0; + } + if(!PREACTION(m)) { + mchunkptr oldp = mem2chunk(oldmem); + size_t oldsize = chunksize(oldp); + mchunkptr next = chunk_plus_offset(oldp, oldsize); + mchunkptr newp = 0; + void *extra = 0; + + /* Try to either shrink or extend into top. Else malloc-copy-free */ + + if(RTCHECK(ok_address(m, oldp) && ok_cinuse(oldp) && ok_next(oldp, next) + && ok_pinuse(next))) { + size_t nb = request2size(bytes); + if(is_mmapped(oldp)) + newp = mmap_resize(m, oldp, nb); + else if(oldsize >= nb) { /* already big enough */ + size_t rsize = oldsize - nb; + newp = oldp; + if(rsize >= MIN_CHUNK_SIZE) { + mchunkptr remainder = chunk_plus_offset(newp, nb); + set_inuse(m, newp, nb); + set_inuse(m, remainder, rsize); + extra = chunk2mem(remainder); + } + } else if(next == m->top && oldsize + m->topsize > nb) { + /* Expand into top */ + size_t newsize = oldsize + m->topsize; + size_t newtopsize = newsize - nb; + mchunkptr newtop = chunk_plus_offset(oldp, nb); + set_inuse(m, oldp, nb); + newtop->head = newtopsize | PINUSE_BIT; + m->top = newtop; + m->topsize = newtopsize; + newp = oldp; + } + } else { + USAGE_ERROR_ACTION(m, oldmem); + POSTACTION(m); + return 0; + } + + POSTACTION(m); + + if(newp != 0) { + if(extra != 0) { + internal_free(m, extra); + } + check_inuse_chunk(m, newp); + return chunk2mem(newp); + } else { + void *newmem = internal_malloc(m, bytes); + if(newmem != 0) { + size_t oc = oldsize - overhead_for(oldp); + memcpy(newmem, oldmem, (oc < bytes) ? oc : bytes); + internal_free(m, oldmem); + } + return newmem; + } + } + return 0; } /* --------------------------- memalign support -------------------------- */ -static void* internal_memalign(mstate m, size_t alignment, size_t bytes) { - if (alignment <= MALLOC_ALIGNMENT) /* Can just use malloc */ - return internal_malloc(m, bytes); - if (alignment < MIN_CHUNK_SIZE) /* must be at least a minimum chunk size */ - alignment = MIN_CHUNK_SIZE; - if ((alignment & (alignment-SIZE_T_ONE)) != 0) {/* Ensure a power of 2 */ - size_t a = MALLOC_ALIGNMENT << 1; - while (a < alignment) a <<= 1; - alignment = a; - } - - if (bytes >= MAX_REQUEST - alignment) { - if (m != 0) { /* Test isn't needed but avoids compiler warning */ - MALLOC_FAILURE_ACTION; - } - } - else { - size_t nb = request2size(bytes); - size_t req = nb + alignment + MIN_CHUNK_SIZE - CHUNK_OVERHEAD; - char* mem = (char*)internal_malloc(m, req); - if (mem != 0) { - void* leader = 0; - void* trailer = 0; - mchunkptr p = mem2chunk(mem); - - if (PREACTION(m)) return 0; - if ((((size_t)(mem)) % alignment) != 0) { /* misaligned */ - /* +static void *internal_memalign(mstate m, size_t alignment, size_t bytes) +{ + if(alignment <= MALLOC_ALIGNMENT) /* Can just use malloc */ + return internal_malloc(m, bytes); + if(alignment < MIN_CHUNK_SIZE) /* must be at least a minimum chunk size */ + alignment = MIN_CHUNK_SIZE; + if((alignment & (alignment - SIZE_T_ONE)) != 0) { /* Ensure a power of 2 */ + size_t a = MALLOC_ALIGNMENT << 1; + while(a < alignment) + a <<= 1; + alignment = a; + } + + if(bytes >= MAX_REQUEST - alignment) { + if(m != 0) { /* Test isn't needed but avoids compiler warning */ + MALLOC_FAILURE_ACTION; + } + } else { + size_t nb = request2size(bytes); + size_t req = nb + alignment + MIN_CHUNK_SIZE - CHUNK_OVERHEAD; + char *mem = (char *)internal_malloc(m, req); + if(mem != 0) { + void *leader = 0; + void *trailer = 0; + mchunkptr p = mem2chunk(mem); + + if(PREACTION(m)) + return 0; + if((((size_t)(mem)) % alignment) != 0) { /* misaligned */ + /* Find an aligned spot inside chunk. Since we need to give back leading space in a chunk of at least MIN_CHUNK_SIZE, if the first calculation places us at a spot with less than @@ -3841,64 +3894,61 @@ static void* internal_memalign(mstate m, size_t alignment, size_t bytes) { We've allocated enough total room so that this is always possible. */ - char* br = (char*)mem2chunk((size_t)(((size_t)(mem + - alignment - - SIZE_T_ONE)) & - -alignment)); - char* pos = ((size_t)(br - (char*)(p)) >= MIN_CHUNK_SIZE)? - br : br+alignment; - mchunkptr newp = (mchunkptr)pos; - size_t leadsize = pos - (char*)(p); - size_t newsize = chunksize(p) - leadsize; - - if (is_mmapped(p)) { /* For mmapped chunks, just adjust offset */ - newp->prev_foot = p->prev_foot + leadsize; - newp->head = (newsize|CINUSE_BIT); - } - else { /* Otherwise, give back leader, use the rest */ - set_inuse(m, newp, newsize); - set_inuse(m, p, leadsize); - leader = chunk2mem(p); - } - p = newp; - } - - /* Give back spare room at the end */ - if (!is_mmapped(p)) { - size_t size = chunksize(p); - if (size > nb + MIN_CHUNK_SIZE) { - size_t remainder_size = size - nb; - mchunkptr remainder = chunk_plus_offset(p, nb); - set_inuse(m, p, nb); - set_inuse(m, remainder, remainder_size); - trailer = chunk2mem(remainder); - } - } - - assert (chunksize(p) >= nb); - assert((((size_t)(chunk2mem(p))) % alignment) == 0); - check_inuse_chunk(m, p); - POSTACTION(m); - if (leader != 0) { - internal_free(m, leader); - } - if (trailer != 0) { - internal_free(m, trailer); - } - return chunk2mem(p); - } - } - return 0; + char *br = (char *)mem2chunk( + (size_t)(((size_t)(mem + alignment - SIZE_T_ONE)) + & -alignment)); + char *pos = ((size_t)(br - (char *)(p)) >= MIN_CHUNK_SIZE) + ? br + : br + alignment; + mchunkptr newp = (mchunkptr)pos; + size_t leadsize = pos - (char *)(p); + size_t newsize = chunksize(p) - leadsize; + + if(is_mmapped(p)) { /* For mmapped chunks, just adjust offset */ + newp->prev_foot = p->prev_foot + leadsize; + newp->head = (newsize | CINUSE_BIT); + } else { /* Otherwise, give back leader, use the rest */ + set_inuse(m, newp, newsize); + set_inuse(m, p, leadsize); + leader = chunk2mem(p); + } + p = newp; + } + + /* Give back spare room at the end */ + if(!is_mmapped(p)) { + size_t size = chunksize(p); + if(size > nb + MIN_CHUNK_SIZE) { + size_t remainder_size = size - nb; + mchunkptr remainder = chunk_plus_offset(p, nb); + set_inuse(m, p, nb); + set_inuse(m, remainder, remainder_size); + trailer = chunk2mem(remainder); + } + } + + assert(chunksize(p) >= nb); + assert((((size_t)(chunk2mem(p))) % alignment) == 0); + check_inuse_chunk(m, p); + POSTACTION(m); + if(leader != 0) { + internal_free(m, leader); + } + if(trailer != 0) { + internal_free(m, trailer); + } + return chunk2mem(p); + } + } + return 0; } /* ------------------------ comalloc/coalloc support --------------------- */ -static void** ialloc(mstate m, - size_t n_elements, - size_t* sizes, - int opts, - void* chunks[]) { - /* +static void **ialloc( + mstate m, size_t n_elements, size_t *sizes, int opts, void *chunks[]) +{ + /* This provides common support for independent_X routines, handling all of the combinations that can result. @@ -3907,116 +3957,113 @@ static void** ialloc(mstate m, bit 1 set if elements should be zeroed */ - size_t element_size; /* chunksize of each element, if all same */ - size_t contents_size; /* total size of elements */ - size_t array_size; /* request size of pointer array */ - void* mem; /* malloced aggregate space */ - mchunkptr p; /* corresponding chunk */ - size_t remainder_size; /* remaining bytes while splitting */ - void** marray; /* either "chunks" or malloced ptr array */ - mchunkptr array_chunk; /* chunk for malloced ptr array */ - flag_t was_enabled; /* to disable mmap */ - size_t size; - size_t i; - - /* compute array length, if needed */ - if (chunks != 0) { - if (n_elements == 0) - return chunks; /* nothing to do */ - marray = chunks; - array_size = 0; - } - else { - /* if empty req, must still return chunk representing empty array */ - if (n_elements == 0) - return (void**)internal_malloc(m, 0); - marray = 0; - array_size = request2size(n_elements * (sizeof(void*))); - } - - /* compute total element size */ - if (opts & 0x1) { /* all-same-size */ - element_size = request2size(*sizes); - contents_size = n_elements * element_size; - } - else { /* add up all the sizes */ - element_size = 0; - contents_size = 0; - for (i = 0; i != n_elements; ++i) - contents_size += request2size(sizes[i]); - } - - size = contents_size + array_size; - - /* + size_t element_size; /* chunksize of each element, if all same */ + size_t contents_size; /* total size of elements */ + size_t array_size; /* request size of pointer array */ + void *mem; /* malloced aggregate space */ + mchunkptr p; /* corresponding chunk */ + size_t remainder_size; /* remaining bytes while splitting */ + void **marray; /* either "chunks" or malloced ptr array */ + mchunkptr array_chunk; /* chunk for malloced ptr array */ + flag_t was_enabled; /* to disable mmap */ + size_t size; + size_t i; + + /* compute array length, if needed */ + if(chunks != 0) { + if(n_elements == 0) + return chunks; /* nothing to do */ + marray = chunks; + array_size = 0; + } else { + /* if empty req, must still return chunk representing empty array */ + if(n_elements == 0) + return (void **)internal_malloc(m, 0); + marray = 0; + array_size = request2size(n_elements * (sizeof(void *))); + } + + /* compute total element size */ + if(opts & 0x1) { /* all-same-size */ + element_size = request2size(*sizes); + contents_size = n_elements * element_size; + } else { /* add up all the sizes */ + element_size = 0; + contents_size = 0; + for(i = 0; i != n_elements; ++i) + contents_size += request2size(sizes[i]); + } + + size = contents_size + array_size; + + /* Allocate the aggregate chunk. First disable direct-mmapping so malloc won't use it, since we would not be able to later free/realloc space internal to a segregated mmap region. */ - was_enabled = use_mmap(m); - disable_mmap(m); - mem = internal_malloc(m, size - CHUNK_OVERHEAD); - if (was_enabled) - enable_mmap(m); - if (mem == 0) - return 0; - - if (PREACTION(m)) return 0; - p = mem2chunk(mem); - remainder_size = chunksize(p); - - assert(!is_mmapped(p)); - - if (opts & 0x2) { /* optionally clear the elements */ - memset((size_t*)mem, 0, remainder_size - SIZE_T_SIZE - array_size); - } - - /* If not provided, allocate the pointer array as final part of chunk */ - if (marray == 0) { - size_t array_chunk_size; - array_chunk = chunk_plus_offset(p, contents_size); - array_chunk_size = remainder_size - contents_size; - marray = (void**) (chunk2mem(array_chunk)); - set_size_and_pinuse_of_inuse_chunk(m, array_chunk, array_chunk_size); - remainder_size = contents_size; - } - - /* split out elements */ - for (i = 0; ; ++i) { - marray[i] = chunk2mem(p); - if (i != n_elements-1) { - if (element_size != 0) - size = element_size; - else - size = request2size(sizes[i]); - remainder_size -= size; - set_size_and_pinuse_of_inuse_chunk(m, p, size); - p = chunk_plus_offset(p, size); - } - else { /* the final element absorbs any overallocation slop */ - set_size_and_pinuse_of_inuse_chunk(m, p, remainder_size); - break; - } - } + was_enabled = use_mmap(m); + disable_mmap(m); + mem = internal_malloc(m, size - CHUNK_OVERHEAD); + if(was_enabled) + enable_mmap(m); + if(mem == 0) + return 0; + + if(PREACTION(m)) + return 0; + p = mem2chunk(mem); + remainder_size = chunksize(p); + + assert(!is_mmapped(p)); + + if(opts & 0x2) { /* optionally clear the elements */ + memset((size_t *)mem, 0, remainder_size - SIZE_T_SIZE - array_size); + } + + /* If not provided, allocate the pointer array as final part of chunk */ + if(marray == 0) { + size_t array_chunk_size; + array_chunk = chunk_plus_offset(p, contents_size); + array_chunk_size = remainder_size - contents_size; + marray = (void **)(chunk2mem(array_chunk)); + set_size_and_pinuse_of_inuse_chunk(m, array_chunk, array_chunk_size); + remainder_size = contents_size; + } + + /* split out elements */ + for(i = 0;; ++i) { + marray[i] = chunk2mem(p); + if(i != n_elements - 1) { + if(element_size != 0) + size = element_size; + else + size = request2size(sizes[i]); + remainder_size -= size; + set_size_and_pinuse_of_inuse_chunk(m, p, size); + p = chunk_plus_offset(p, size); + } else { /* the final element absorbs any overallocation slop */ + set_size_and_pinuse_of_inuse_chunk(m, p, remainder_size); + break; + } + } #if DEBUG - if (marray != chunks) { - /* final element must have exactly exhausted chunk */ - if (element_size != 0) { - assert(remainder_size == element_size); - } - else { - assert(remainder_size == request2size(sizes[i])); - } - check_inuse_chunk(m, mem2chunk(marray)); - } - for (i = 0; i != n_elements; ++i) - check_inuse_chunk(m, mem2chunk(marray[i])); + if(marray != chunks) { + /* final element must have exactly exhausted chunk */ + if(element_size != 0) { + assert(remainder_size == element_size); + } else { + assert(remainder_size == request2size(sizes[i])); + } + check_inuse_chunk(m, mem2chunk(marray)); + } + for(i = 0; i != n_elements; ++i) + check_inuse_chunk(m, mem2chunk(marray[i])); #endif /* DEBUG */ - POSTACTION(m); - return marray; + POSTACTION(m); + return marray; } @@ -4024,8 +4071,9 @@ static void** ialloc(mstate m, #if !ONLY_MSPACES -void* dlmalloc(size_t bytes) { - /* +void *dlmalloc(size_t bytes) +{ + /* Basic algorithm: If a small request (< 256 bytes minus per-chunk overhead): 1. If one exists, use a remainderless chunk in associated smallbin. @@ -4048,319 +4096,328 @@ void* dlmalloc(size_t bytes) { The ugly goto's here ensure that postaction occurs along all paths. */ - if (!PREACTION(gm)) { - void* mem; - size_t nb; - if (bytes <= MAX_SMALL_REQUEST) { - bindex_t idx; - binmap_t smallbits; - nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes); - idx = small_index(nb); - smallbits = gm->smallmap >> idx; - - if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */ - mchunkptr b, p; - idx += ~smallbits & 1; /* Uses next bin if idx empty */ - b = smallbin_at(gm, idx); - p = b->fd; - assert(chunksize(p) == small_index2size(idx)); - unlink_first_small_chunk(gm, b, p, idx); - set_inuse_and_pinuse(gm, p, small_index2size(idx)); - mem = chunk2mem(p); - check_malloced_chunk(gm, mem, nb); - goto postaction; - } - - else if (nb > gm->dvsize) { - if (smallbits != 0) { /* Use chunk in next nonempty smallbin */ - mchunkptr b, p, r; - size_t rsize; - bindex_t i; - binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx)); - binmap_t leastbit = least_bit(leftbits); - compute_bit2idx(leastbit, i); - b = smallbin_at(gm, i); - p = b->fd; - assert(chunksize(p) == small_index2size(i)); - unlink_first_small_chunk(gm, b, p, i); - rsize = small_index2size(i) - nb; - /* Fit here cannot be remainderless if 4byte sizes */ - if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE) - set_inuse_and_pinuse(gm, p, small_index2size(i)); - else { - set_size_and_pinuse_of_inuse_chunk(gm, p, nb); - r = chunk_plus_offset(p, nb); - set_size_and_pinuse_of_free_chunk(r, rsize); - replace_dv(gm, r, rsize); - } - mem = chunk2mem(p); - check_malloced_chunk(gm, mem, nb); - goto postaction; - } - - else if (gm->treemap != 0 && (mem = tmalloc_small(gm, nb)) != 0) { - check_malloced_chunk(gm, mem, nb); - goto postaction; - } - } - } - else if (bytes >= MAX_REQUEST) - nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */ - else { - nb = pad_request(bytes); - if (gm->treemap != 0 && (mem = tmalloc_large(gm, nb)) != 0) { - check_malloced_chunk(gm, mem, nb); - goto postaction; - } - } - - if (nb <= gm->dvsize) { - size_t rsize = gm->dvsize - nb; - mchunkptr p = gm->dv; - if (rsize >= MIN_CHUNK_SIZE) { /* split dv */ - mchunkptr r = gm->dv = chunk_plus_offset(p, nb); - gm->dvsize = rsize; - set_size_and_pinuse_of_free_chunk(r, rsize); - set_size_and_pinuse_of_inuse_chunk(gm, p, nb); - } - else { /* exhaust dv */ - size_t dvs = gm->dvsize; - gm->dvsize = 0; - gm->dv = 0; - set_inuse_and_pinuse(gm, p, dvs); - } - mem = chunk2mem(p); - check_malloced_chunk(gm, mem, nb); - goto postaction; - } - - else if (nb < gm->topsize) { /* Split top */ - size_t rsize = gm->topsize -= nb; - mchunkptr p = gm->top; - mchunkptr r = gm->top = chunk_plus_offset(p, nb); - r->head = rsize | PINUSE_BIT; - set_size_and_pinuse_of_inuse_chunk(gm, p, nb); - mem = chunk2mem(p); - check_top_chunk(gm, gm->top); - check_malloced_chunk(gm, mem, nb); - goto postaction; - } - - mem = sys_alloc(gm, nb); - - postaction: - POSTACTION(gm); - return mem; - } - - return 0; + if(!PREACTION(gm)) { + void *mem; + size_t nb; + if(bytes <= MAX_SMALL_REQUEST) { + bindex_t idx; + binmap_t smallbits; + nb = (bytes < MIN_REQUEST) ? MIN_CHUNK_SIZE : pad_request(bytes); + idx = small_index(nb); + smallbits = gm->smallmap >> idx; + + if((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */ + mchunkptr b, p; + idx += ~smallbits & 1; /* Uses next bin if idx empty */ + b = smallbin_at(gm, idx); + p = b->fd; + assert(chunksize(p) == small_index2size(idx)); + unlink_first_small_chunk(gm, b, p, idx); + set_inuse_and_pinuse(gm, p, small_index2size(idx)); + mem = chunk2mem(p); + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + + else if(nb > gm->dvsize) { + if(smallbits != 0) { /* Use chunk in next nonempty smallbin */ + mchunkptr b, p, r; + size_t rsize; + bindex_t i; + binmap_t leftbits = + (smallbits << idx) & left_bits(idx2bit(idx)); + binmap_t leastbit = least_bit(leftbits); + compute_bit2idx(leastbit, i); + b = smallbin_at(gm, i); + p = b->fd; + assert(chunksize(p) == small_index2size(i)); + unlink_first_small_chunk(gm, b, p, i); + rsize = small_index2size(i) - nb; + /* Fit here cannot be remainderless if 4byte sizes */ + if(SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(gm, p, small_index2size(i)); + else { + set_size_and_pinuse_of_inuse_chunk(gm, p, nb); + r = chunk_plus_offset(p, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + replace_dv(gm, r, rsize); + } + mem = chunk2mem(p); + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + + else if(gm->treemap != 0 + && (mem = tmalloc_small(gm, nb)) != 0) { + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + } + } else if(bytes >= MAX_REQUEST) + nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */ + else { + nb = pad_request(bytes); + if(gm->treemap != 0 && (mem = tmalloc_large(gm, nb)) != 0) { + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + } + + if(nb <= gm->dvsize) { + size_t rsize = gm->dvsize - nb; + mchunkptr p = gm->dv; + if(rsize >= MIN_CHUNK_SIZE) { /* split dv */ + mchunkptr r = gm->dv = chunk_plus_offset(p, nb); + gm->dvsize = rsize; + set_size_and_pinuse_of_free_chunk(r, rsize); + set_size_and_pinuse_of_inuse_chunk(gm, p, nb); + } else { /* exhaust dv */ + size_t dvs = gm->dvsize; + gm->dvsize = 0; + gm->dv = 0; + set_inuse_and_pinuse(gm, p, dvs); + } + mem = chunk2mem(p); + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + + else if(nb < gm->topsize) { /* Split top */ + size_t rsize = gm->topsize -= nb; + mchunkptr p = gm->top; + mchunkptr r = gm->top = chunk_plus_offset(p, nb); + r->head = rsize | PINUSE_BIT; + set_size_and_pinuse_of_inuse_chunk(gm, p, nb); + mem = chunk2mem(p); + check_top_chunk(gm, gm->top); + check_malloced_chunk(gm, mem, nb); + goto postaction; + } + + mem = sys_alloc(gm, nb); + + postaction: + POSTACTION(gm); + return mem; + } + + return 0; } -void dlfree(void* mem) { - /* +void dlfree(void *mem) +{ + /* Consolidate freed chunks with preceding or succeeding bordering free chunks, if they exist, and then place in a bin. Intermixed with special cases for top, dv, mmapped chunks, and usage errors. */ - if (mem != 0) { - mchunkptr p = mem2chunk(mem); + if(mem != 0) { + mchunkptr p = mem2chunk(mem); #if FOOTERS - mstate fm = get_mstate_for(p); - if (!ok_magic(fm)) { - USAGE_ERROR_ACTION(fm, p); - return; - } + mstate fm = get_mstate_for(p); + if(!ok_magic(fm)) { + USAGE_ERROR_ACTION(fm, p); + return; + } #else /* FOOTERS */ #define fm gm #endif /* FOOTERS */ - if (!PREACTION(fm)) { - check_inuse_chunk(fm, p); - if (RTCHECK(ok_address(fm, p) && ok_cinuse(p))) { - size_t psize = chunksize(p); - mchunkptr next = chunk_plus_offset(p, psize); - if (!pinuse(p)) { - size_t prevsize = p->prev_foot; - if ((prevsize & IS_MMAPPED_BIT) != 0) { - prevsize &= ~IS_MMAPPED_BIT; - psize += prevsize + MMAP_FOOT_PAD; - if (CALL_MUNMAP((char*)p - prevsize, psize) == 0) - fm->footprint -= psize; - goto postaction; - } - else { - mchunkptr prev = chunk_minus_offset(p, prevsize); - psize += prevsize; - p = prev; - if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */ - if (p != fm->dv) { - unlink_chunk(fm, p, prevsize); - } - else if ((next->head & INUSE_BITS) == INUSE_BITS) { - fm->dvsize = psize; - set_free_with_pinuse(p, psize, next); - goto postaction; - } - } - else - goto erroraction; - } - } - - if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) { - if (!cinuse(next)) { /* consolidate forward */ - if (next == fm->top) { - size_t tsize = fm->topsize += psize; - fm->top = p; - p->head = tsize | PINUSE_BIT; - if (p == fm->dv) { - fm->dv = 0; - fm->dvsize = 0; - } - if (should_trim(fm, tsize)) - sys_trim(fm, 0); - goto postaction; - } - else if (next == fm->dv) { - size_t dsize = fm->dvsize += psize; - fm->dv = p; - set_size_and_pinuse_of_free_chunk(p, dsize); - goto postaction; - } - else { - size_t nsize = chunksize(next); - psize += nsize; - unlink_chunk(fm, next, nsize); - set_size_and_pinuse_of_free_chunk(p, psize); - if (p == fm->dv) { - fm->dvsize = psize; - goto postaction; - } - } - } - else - set_free_with_pinuse(p, psize, next); - insert_chunk(fm, p, psize); - check_free_chunk(fm, p); - goto postaction; - } - } - erroraction: - USAGE_ERROR_ACTION(fm, p); - postaction: - POSTACTION(fm); - } - } + if(!PREACTION(fm)) { + check_inuse_chunk(fm, p); + if(RTCHECK(ok_address(fm, p) && ok_cinuse(p))) { + size_t psize = chunksize(p); + mchunkptr next = chunk_plus_offset(p, psize); + if(!pinuse(p)) { + size_t prevsize = p->prev_foot; + if((prevsize & IS_MMAPPED_BIT) != 0) { + prevsize &= ~IS_MMAPPED_BIT; + psize += prevsize + MMAP_FOOT_PAD; + if(CALL_MUNMAP((char *)p - prevsize, psize) == 0) + fm->footprint -= psize; + goto postaction; + } else { + mchunkptr prev = chunk_minus_offset(p, prevsize); + psize += prevsize; + p = prev; + if(RTCHECK(ok_address( + fm, prev))) { /* consolidate backward */ + if(p != fm->dv) { + unlink_chunk(fm, p, prevsize); + } else if((next->head & INUSE_BITS) == INUSE_BITS) { + fm->dvsize = psize; + set_free_with_pinuse(p, psize, next); + goto postaction; + } + } else + goto erroraction; + } + } + + if(RTCHECK(ok_next(p, next) && ok_pinuse(next))) { + if(!cinuse(next)) { /* consolidate forward */ + if(next == fm->top) { + size_t tsize = fm->topsize += psize; + fm->top = p; + p->head = tsize | PINUSE_BIT; + if(p == fm->dv) { + fm->dv = 0; + fm->dvsize = 0; + } + if(should_trim(fm, tsize)) + sys_trim(fm, 0); + goto postaction; + } else if(next == fm->dv) { + size_t dsize = fm->dvsize += psize; + fm->dv = p; + set_size_and_pinuse_of_free_chunk(p, dsize); + goto postaction; + } else { + size_t nsize = chunksize(next); + psize += nsize; + unlink_chunk(fm, next, nsize); + set_size_and_pinuse_of_free_chunk(p, psize); + if(p == fm->dv) { + fm->dvsize = psize; + goto postaction; + } + } + } else + set_free_with_pinuse(p, psize, next); + insert_chunk(fm, p, psize); + check_free_chunk(fm, p); + goto postaction; + } + } + erroraction: + USAGE_ERROR_ACTION(fm, p); + postaction: + POSTACTION(fm); + } + } #if !FOOTERS #undef fm #endif /* FOOTERS */ } -void* dlcalloc(size_t n_elements, size_t elem_size) { - void* mem; - size_t req = 0; - if (n_elements != 0) { - req = n_elements * elem_size; - if (((n_elements | elem_size) & ~(size_t)0xffff) && - (req / n_elements != elem_size)) - req = MAX_SIZE_T; /* force downstream failure on overflow */ - } - mem = dlmalloc(req); - if (mem != 0 && calloc_must_clear(mem2chunk(mem))) - memset(mem, 0, req); - return mem; +void *dlcalloc(size_t n_elements, size_t elem_size) +{ + void *mem; + size_t req = 0; + if(n_elements != 0) { + req = n_elements * elem_size; + if(((n_elements | elem_size) & ~(size_t)0xffff) + && (req / n_elements != elem_size)) + req = MAX_SIZE_T; /* force downstream failure on overflow */ + } + mem = dlmalloc(req); + if(mem != 0 && calloc_must_clear(mem2chunk(mem))) + memset(mem, 0, req); + return mem; } -void* dlrealloc(void* oldmem, size_t bytes) { - if (oldmem == 0) - return dlmalloc(bytes); +void *dlrealloc(void *oldmem, size_t bytes) +{ + if(oldmem == 0) + return dlmalloc(bytes); #ifdef REALLOC_ZERO_BYTES_FREES - if (bytes == 0) { - dlfree(oldmem); - return 0; - } + if(bytes == 0) { + dlfree(oldmem); + return 0; + } #endif /* REALLOC_ZERO_BYTES_FREES */ - else { -#if ! FOOTERS - mstate m = gm; -#else /* FOOTERS */ - mstate m = get_mstate_for(mem2chunk(oldmem)); - if (!ok_magic(m)) { - USAGE_ERROR_ACTION(m, oldmem); - return 0; - } + else { +#if !FOOTERS + mstate m = gm; +#else /* FOOTERS */ + mstate m = get_mstate_for(mem2chunk(oldmem)); + if(!ok_magic(m)) { + USAGE_ERROR_ACTION(m, oldmem); + return 0; + } #endif /* FOOTERS */ - return internal_realloc(m, oldmem, bytes); - } + return internal_realloc(m, oldmem, bytes); + } } -void* dlmemalign(size_t alignment, size_t bytes) { - return internal_memalign(gm, alignment, bytes); +void *dlmemalign(size_t alignment, size_t bytes) +{ + return internal_memalign(gm, alignment, bytes); } -void** dlindependent_calloc(size_t n_elements, size_t elem_size, - void* chunks[]) { - size_t sz = elem_size; /* serves as 1-element array */ - return ialloc(gm, n_elements, &sz, 3, chunks); +void **dlindependent_calloc(size_t n_elements, size_t elem_size, void *chunks[]) +{ + size_t sz = elem_size; /* serves as 1-element array */ + return ialloc(gm, n_elements, &sz, 3, chunks); } -void** dlindependent_comalloc(size_t n_elements, size_t sizes[], - void* chunks[]) { - return ialloc(gm, n_elements, sizes, 0, chunks); +void **dlindependent_comalloc(size_t n_elements, size_t sizes[], void *chunks[]) +{ + return ialloc(gm, n_elements, sizes, 0, chunks); } -void* dlvalloc(size_t bytes) { - size_t pagesz; - init_mparams(); - pagesz = mparams.page_size; - return dlmemalign(pagesz, bytes); +void *dlvalloc(size_t bytes) +{ + size_t pagesz; + init_mparams(); + pagesz = mparams.page_size; + return dlmemalign(pagesz, bytes); } -void* dlpvalloc(size_t bytes) { - size_t pagesz; - init_mparams(); - pagesz = mparams.page_size; - return dlmemalign(pagesz, (bytes + pagesz - SIZE_T_ONE) & ~(pagesz - SIZE_T_ONE)); +void *dlpvalloc(size_t bytes) +{ + size_t pagesz; + init_mparams(); + pagesz = mparams.page_size; + return dlmemalign( + pagesz, (bytes + pagesz - SIZE_T_ONE) & ~(pagesz - SIZE_T_ONE)); } -int dlmalloc_trim(size_t pad) { - int result = 0; - if (!PREACTION(gm)) { - result = sys_trim(gm, pad); - POSTACTION(gm); - } - return result; +int dlmalloc_trim(size_t pad) +{ + int result = 0; + if(!PREACTION(gm)) { + result = sys_trim(gm, pad); + POSTACTION(gm); + } + return result; } -size_t dlmalloc_footprint(void) { - return gm->footprint; +size_t dlmalloc_footprint(void) +{ + return gm->footprint; } -size_t dlmalloc_max_footprint(void) { - return gm->max_footprint; +size_t dlmalloc_max_footprint(void) +{ + return gm->max_footprint; } #if !NO_MALLINFO -struct mallinfo dlmallinfo(void) { - return internal_mallinfo(gm); +struct mallinfo dlmallinfo(void) +{ + return internal_mallinfo(gm); } #endif /* NO_MALLINFO */ -void dlmalloc_stats() { - internal_malloc_stats(gm); +void dlmalloc_stats() +{ + internal_malloc_stats(gm); } -size_t dlmalloc_usable_size(void* mem) { - if (mem != 0) { - mchunkptr p = mem2chunk(mem); - if (cinuse(p)) - return chunksize(p) - overhead_for(p); - } - return 0; +size_t dlmalloc_usable_size(void *mem) +{ + if(mem != 0) { + mchunkptr p = mem2chunk(mem); + if(cinuse(p)) + return chunksize(p) - overhead_for(p); + } + return 0; } -int dlmallopt(int param_number, int value) { - return change_mparam(param_number, value); +int dlmallopt(int param_number, int value) +{ + return change_mparam(param_number, value); } #endif /* !ONLY_MSPACES */ @@ -4369,78 +4426,83 @@ int dlmallopt(int param_number, int value) { #if MSPACES -static mstate init_user_mstate(char* tbase, size_t tsize) { - size_t msize = pad_request(sizeof(struct malloc_state)); - mchunkptr mn; - mchunkptr msp = align_as_chunk(tbase); - mstate m = (mstate)(chunk2mem(msp)); - memset(m, 0, msize); - INITIAL_LOCK(&m->mutex); - msp->head = (msize|PINUSE_BIT|CINUSE_BIT); - m->seg.base = m->least_addr = tbase; - m->seg.size = m->footprint = m->max_footprint = tsize; - m->magic = mparams.magic; - m->mflags = mparams.default_mflags; - disable_contiguous(m); - init_bins(m); - mn = next_chunk(mem2chunk(m)); - init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) - TOP_FOOT_SIZE); - check_top_chunk(m, m->top); - return m; +static mstate init_user_mstate(char *tbase, size_t tsize) +{ + size_t msize = pad_request(sizeof(struct malloc_state)); + mchunkptr mn; + mchunkptr msp = align_as_chunk(tbase); + mstate m = (mstate)(chunk2mem(msp)); + memset(m, 0, msize); + INITIAL_LOCK(&m->mutex); + msp->head = (msize | PINUSE_BIT | CINUSE_BIT); + m->seg.base = m->least_addr = tbase; + m->seg.size = m->footprint = m->max_footprint = tsize; + m->magic = mparams.magic; + m->mflags = mparams.default_mflags; + disable_contiguous(m); + init_bins(m); + mn = next_chunk(mem2chunk(m)); + init_top(m, mn, (size_t)((tbase + tsize) - (char *)mn) - TOP_FOOT_SIZE); + check_top_chunk(m, m->top); + return m; } -mspace create_mspace(size_t capacity, int locked) { - mstate m = 0; - size_t msize = pad_request(sizeof(struct malloc_state)); - init_mparams(); /* Ensure pagesize etc initialized */ - - if (capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) { - size_t rs = ((capacity == 0)? mparams.granularity : - (capacity + TOP_FOOT_SIZE + msize)); - size_t tsize = granularity_align(rs); - char* tbase = (char*)(CALL_MMAP(tsize)); - if (tbase != CMFAIL) { - m = init_user_mstate(tbase, tsize); - m->seg.sflags = IS_MMAPPED_BIT; - set_lock(m, locked); - } - } - return (mspace)m; +mspace create_mspace(size_t capacity, int locked) +{ + mstate m = 0; + size_t msize = pad_request(sizeof(struct malloc_state)); + init_mparams(); /* Ensure pagesize etc initialized */ + + if(capacity < (size_t) - (msize + TOP_FOOT_SIZE + mparams.page_size)) { + size_t rs = ((capacity == 0) ? mparams.granularity + : (capacity + TOP_FOOT_SIZE + msize)); + size_t tsize = granularity_align(rs); + char *tbase = (char *)(CALL_MMAP(tsize)); + if(tbase != CMFAIL) { + m = init_user_mstate(tbase, tsize); + m->seg.sflags = IS_MMAPPED_BIT; + set_lock(m, locked); + } + } + return (mspace)m; } -mspace create_mspace_with_base(void* base, size_t capacity, int locked) { - mstate m = 0; - size_t msize = pad_request(sizeof(struct malloc_state)); - init_mparams(); /* Ensure pagesize etc initialized */ - - if (capacity > msize + TOP_FOOT_SIZE && - capacity < (size_t) -(msize + TOP_FOOT_SIZE + mparams.page_size)) { - m = init_user_mstate((char*)base, capacity); - m->seg.sflags = EXTERN_BIT; - set_lock(m, locked); - } - return (mspace)m; +mspace create_mspace_with_base(void *base, size_t capacity, int locked) +{ + mstate m = 0; + size_t msize = pad_request(sizeof(struct malloc_state)); + init_mparams(); /* Ensure pagesize etc initialized */ + + if(capacity > msize + TOP_FOOT_SIZE + && capacity < (size_t) + - (msize + TOP_FOOT_SIZE + + mparams.page_size)) { + m = init_user_mstate((char *)base, capacity); + m->seg.sflags = EXTERN_BIT; + set_lock(m, locked); + } + return (mspace)m; } -size_t destroy_mspace(mspace msp) { - size_t freed = 0; - mstate ms = (mstate)msp; - if (ok_magic(ms)) { - msegmentptr sp = &ms->seg; - while (sp != 0) { - char* base = sp->base; - size_t size = sp->size; - flag_t flag = sp->sflags; - sp = sp->next; - if ((flag & IS_MMAPPED_BIT) && !(flag & EXTERN_BIT) && - CALL_MUNMAP(base, size) == 0) - freed += size; - } - } - else { - USAGE_ERROR_ACTION(ms,ms); - } - return freed; +size_t destroy_mspace(mspace msp) +{ + size_t freed = 0; + mstate ms = (mstate)msp; + if(ok_magic(ms)) { + msegmentptr sp = &ms->seg; + while(sp != 0) { + char *base = sp->base; + size_t size = sp->size; + flag_t flag = sp->sflags; + sp = sp->next; + if((flag & IS_MMAPPED_BIT) && !(flag & EXTERN_BIT) + && CALL_MUNMAP(base, size) == 0) + freed += size; + } + } else { + USAGE_ERROR_ACTION(ms, ms); + } + return freed; } /* @@ -4449,345 +4511,351 @@ size_t destroy_mspace(mspace msp) { */ -void* mspace_malloc(mspace msp, size_t bytes) { - mstate ms = (mstate)msp; - if (!ok_magic(ms)) { - USAGE_ERROR_ACTION(ms,ms); - return 0; - } - if (!PREACTION(ms)) { - void* mem; - size_t nb; - if (bytes <= MAX_SMALL_REQUEST) { - bindex_t idx; - binmap_t smallbits; - nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes); - idx = small_index(nb); - smallbits = ms->smallmap >> idx; - - if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */ - mchunkptr b, p; - idx += ~smallbits & 1; /* Uses next bin if idx empty */ - b = smallbin_at(ms, idx); - p = b->fd; - assert(chunksize(p) == small_index2size(idx)); - unlink_first_small_chunk(ms, b, p, idx); - set_inuse_and_pinuse(ms, p, small_index2size(idx)); - mem = chunk2mem(p); - check_malloced_chunk(ms, mem, nb); - goto postaction; - } - - else if (nb > ms->dvsize) { - if (smallbits != 0) { /* Use chunk in next nonempty smallbin */ - mchunkptr b, p, r; - size_t rsize; - bindex_t i; - binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx)); - binmap_t leastbit = least_bit(leftbits); - compute_bit2idx(leastbit, i); - b = smallbin_at(ms, i); - p = b->fd; - assert(chunksize(p) == small_index2size(i)); - unlink_first_small_chunk(ms, b, p, i); - rsize = small_index2size(i) - nb; - /* Fit here cannot be remainderless if 4byte sizes */ - if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE) - set_inuse_and_pinuse(ms, p, small_index2size(i)); - else { - set_size_and_pinuse_of_inuse_chunk(ms, p, nb); - r = chunk_plus_offset(p, nb); - set_size_and_pinuse_of_free_chunk(r, rsize); - replace_dv(ms, r, rsize); - } - mem = chunk2mem(p); - check_malloced_chunk(ms, mem, nb); - goto postaction; - } - - else if (ms->treemap != 0 && (mem = tmalloc_small(ms, nb)) != 0) { - check_malloced_chunk(ms, mem, nb); - goto postaction; - } - } - } - else if (bytes >= MAX_REQUEST) - nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */ - else { - nb = pad_request(bytes); - if (ms->treemap != 0 && (mem = tmalloc_large(ms, nb)) != 0) { - check_malloced_chunk(ms, mem, nb); - goto postaction; - } - } - - if (nb <= ms->dvsize) { - size_t rsize = ms->dvsize - nb; - mchunkptr p = ms->dv; - if (rsize >= MIN_CHUNK_SIZE) { /* split dv */ - mchunkptr r = ms->dv = chunk_plus_offset(p, nb); - ms->dvsize = rsize; - set_size_and_pinuse_of_free_chunk(r, rsize); - set_size_and_pinuse_of_inuse_chunk(ms, p, nb); - } - else { /* exhaust dv */ - size_t dvs = ms->dvsize; - ms->dvsize = 0; - ms->dv = 0; - set_inuse_and_pinuse(ms, p, dvs); - } - mem = chunk2mem(p); - check_malloced_chunk(ms, mem, nb); - goto postaction; - } - - else if (nb < ms->topsize) { /* Split top */ - size_t rsize = ms->topsize -= nb; - mchunkptr p = ms->top; - mchunkptr r = ms->top = chunk_plus_offset(p, nb); - r->head = rsize | PINUSE_BIT; - set_size_and_pinuse_of_inuse_chunk(ms, p, nb); - mem = chunk2mem(p); - check_top_chunk(ms, ms->top); - check_malloced_chunk(ms, mem, nb); - goto postaction; - } - - /* mem = sys_alloc(ms, nb); */ - mem = 0; - - postaction: - POSTACTION(ms); - return mem; - } - - return 0; +void *mspace_malloc(mspace msp, size_t bytes) +{ + mstate ms = (mstate)msp; + if(!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms, ms); + return 0; + } + if(!PREACTION(ms)) { + void *mem; + size_t nb; + if(bytes <= MAX_SMALL_REQUEST) { + bindex_t idx; + binmap_t smallbits; + nb = (bytes < MIN_REQUEST) ? MIN_CHUNK_SIZE : pad_request(bytes); + idx = small_index(nb); + smallbits = ms->smallmap >> idx; + + if((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */ + mchunkptr b, p; + idx += ~smallbits & 1; /* Uses next bin if idx empty */ + b = smallbin_at(ms, idx); + p = b->fd; + assert(chunksize(p) == small_index2size(idx)); + unlink_first_small_chunk(ms, b, p, idx); + set_inuse_and_pinuse(ms, p, small_index2size(idx)); + mem = chunk2mem(p); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + else if(nb > ms->dvsize) { + if(smallbits != 0) { /* Use chunk in next nonempty smallbin */ + mchunkptr b, p, r; + size_t rsize; + bindex_t i; + binmap_t leftbits = + (smallbits << idx) & left_bits(idx2bit(idx)); + binmap_t leastbit = least_bit(leftbits); + compute_bit2idx(leastbit, i); + b = smallbin_at(ms, i); + p = b->fd; + assert(chunksize(p) == small_index2size(i)); + unlink_first_small_chunk(ms, b, p, i); + rsize = small_index2size(i) - nb; + /* Fit here cannot be remainderless if 4byte sizes */ + if(SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE) + set_inuse_and_pinuse(ms, p, small_index2size(i)); + else { + set_size_and_pinuse_of_inuse_chunk(ms, p, nb); + r = chunk_plus_offset(p, nb); + set_size_and_pinuse_of_free_chunk(r, rsize); + replace_dv(ms, r, rsize); + } + mem = chunk2mem(p); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + else if(ms->treemap != 0 + && (mem = tmalloc_small(ms, nb)) != 0) { + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + } + } else if(bytes >= MAX_REQUEST) + nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */ + else { + nb = pad_request(bytes); + if(ms->treemap != 0 && (mem = tmalloc_large(ms, nb)) != 0) { + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + } + + if(nb <= ms->dvsize) { + size_t rsize = ms->dvsize - nb; + mchunkptr p = ms->dv; + if(rsize >= MIN_CHUNK_SIZE) { /* split dv */ + mchunkptr r = ms->dv = chunk_plus_offset(p, nb); + ms->dvsize = rsize; + set_size_and_pinuse_of_free_chunk(r, rsize); + set_size_and_pinuse_of_inuse_chunk(ms, p, nb); + } else { /* exhaust dv */ + size_t dvs = ms->dvsize; + ms->dvsize = 0; + ms->dv = 0; + set_inuse_and_pinuse(ms, p, dvs); + } + mem = chunk2mem(p); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + else if(nb < ms->topsize) { /* Split top */ + size_t rsize = ms->topsize -= nb; + mchunkptr p = ms->top; + mchunkptr r = ms->top = chunk_plus_offset(p, nb); + r->head = rsize | PINUSE_BIT; + set_size_and_pinuse_of_inuse_chunk(ms, p, nb); + mem = chunk2mem(p); + check_top_chunk(ms, ms->top); + check_malloced_chunk(ms, mem, nb); + goto postaction; + } + + /* mem = sys_alloc(ms, nb); */ + mem = 0; + + postaction: + POSTACTION(ms); + return mem; + } + + return 0; } -void mspace_free(mspace msp, void* mem) { - if (mem != 0) { - mchunkptr p = mem2chunk(mem); +void mspace_free(mspace msp, void *mem) +{ + if(mem != 0) { + mchunkptr p = mem2chunk(mem); #if FOOTERS - mstate fm = get_mstate_for(p); -#else /* FOOTERS */ - mstate fm = (mstate)msp; + mstate fm = get_mstate_for(p); +#else /* FOOTERS */ + mstate fm = (mstate)msp; #endif /* FOOTERS */ - if (!ok_magic(fm)) { - USAGE_ERROR_ACTION(fm, p); - return; - } - if (!PREACTION(fm)) { - check_inuse_chunk(fm, p); - if (RTCHECK(ok_address(fm, p) && ok_cinuse(p))) { - size_t psize = chunksize(p); - mchunkptr next = chunk_plus_offset(p, psize); - if (!pinuse(p)) { - size_t prevsize = p->prev_foot; - if ((prevsize & IS_MMAPPED_BIT) != 0) { - prevsize &= ~IS_MMAPPED_BIT; - psize += prevsize + MMAP_FOOT_PAD; - if (CALL_MUNMAP((char*)p - prevsize, psize) == 0) - fm->footprint -= psize; - goto postaction; - } - else { - mchunkptr prev = chunk_minus_offset(p, prevsize); - psize += prevsize; - p = prev; - if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */ - if (p != fm->dv) { - unlink_chunk(fm, p, prevsize); - } - else if ((next->head & INUSE_BITS) == INUSE_BITS) { - fm->dvsize = psize; - set_free_with_pinuse(p, psize, next); - goto postaction; - } - } - else - goto erroraction; - } - } - - if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) { - if (!cinuse(next)) { /* consolidate forward */ - if (next == fm->top) { - size_t tsize = fm->topsize += psize; - fm->top = p; - p->head = tsize | PINUSE_BIT; - if (p == fm->dv) { - fm->dv = 0; - fm->dvsize = 0; - } - if (should_trim(fm, tsize)) - sys_trim(fm, 0); - goto postaction; - } - else if (next == fm->dv) { - size_t dsize = fm->dvsize += psize; - fm->dv = p; - set_size_and_pinuse_of_free_chunk(p, dsize); - goto postaction; - } - else { - size_t nsize = chunksize(next); - psize += nsize; - unlink_chunk(fm, next, nsize); - set_size_and_pinuse_of_free_chunk(p, psize); - if (p == fm->dv) { - fm->dvsize = psize; - goto postaction; - } - } - } - else - set_free_with_pinuse(p, psize, next); - insert_chunk(fm, p, psize); - check_free_chunk(fm, p); - goto postaction; - } - } - erroraction: - USAGE_ERROR_ACTION(fm, p); - postaction: - POSTACTION(fm); - } - } + if(!ok_magic(fm)) { + USAGE_ERROR_ACTION(fm, p); + return; + } + if(!PREACTION(fm)) { + check_inuse_chunk(fm, p); + if(RTCHECK(ok_address(fm, p) && ok_cinuse(p))) { + size_t psize = chunksize(p); + mchunkptr next = chunk_plus_offset(p, psize); + if(!pinuse(p)) { + size_t prevsize = p->prev_foot; + if((prevsize & IS_MMAPPED_BIT) != 0) { + prevsize &= ~IS_MMAPPED_BIT; + psize += prevsize + MMAP_FOOT_PAD; + if(CALL_MUNMAP((char *)p - prevsize, psize) == 0) + fm->footprint -= psize; + goto postaction; + } else { + mchunkptr prev = chunk_minus_offset(p, prevsize); + psize += prevsize; + p = prev; + if(RTCHECK(ok_address( + fm, prev))) { /* consolidate backward */ + if(p != fm->dv) { + unlink_chunk(fm, p, prevsize); + } else if((next->head & INUSE_BITS) == INUSE_BITS) { + fm->dvsize = psize; + set_free_with_pinuse(p, psize, next); + goto postaction; + } + } else + goto erroraction; + } + } + + if(RTCHECK(ok_next(p, next) && ok_pinuse(next))) { + if(!cinuse(next)) { /* consolidate forward */ + if(next == fm->top) { + size_t tsize = fm->topsize += psize; + fm->top = p; + p->head = tsize | PINUSE_BIT; + if(p == fm->dv) { + fm->dv = 0; + fm->dvsize = 0; + } + if(should_trim(fm, tsize)) + sys_trim(fm, 0); + goto postaction; + } else if(next == fm->dv) { + size_t dsize = fm->dvsize += psize; + fm->dv = p; + set_size_and_pinuse_of_free_chunk(p, dsize); + goto postaction; + } else { + size_t nsize = chunksize(next); + psize += nsize; + unlink_chunk(fm, next, nsize); + set_size_and_pinuse_of_free_chunk(p, psize); + if(p == fm->dv) { + fm->dvsize = psize; + goto postaction; + } + } + } else + set_free_with_pinuse(p, psize, next); + insert_chunk(fm, p, psize); + check_free_chunk(fm, p); + goto postaction; + } + } + erroraction: + USAGE_ERROR_ACTION(fm, p); + postaction: + POSTACTION(fm); + } + } } -void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size) { - void* mem; - size_t req = 0; - mstate ms = (mstate)msp; - if (!ok_magic(ms)) { - USAGE_ERROR_ACTION(ms,ms); - return 0; - } - if (n_elements != 0) { - req = n_elements * elem_size; - if (((n_elements | elem_size) & ~(size_t)0xffff) && - (req / n_elements != elem_size)) - req = MAX_SIZE_T; /* force downstream failure on overflow */ - } - mem = internal_malloc(ms, req); - if (mem != 0 && calloc_must_clear(mem2chunk(mem))) - memset(mem, 0, req); - return mem; +void *mspace_calloc(mspace msp, size_t n_elements, size_t elem_size) +{ + void *mem; + size_t req = 0; + mstate ms = (mstate)msp; + if(!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms, ms); + return 0; + } + if(n_elements != 0) { + req = n_elements * elem_size; + if(((n_elements | elem_size) & ~(size_t)0xffff) + && (req / n_elements != elem_size)) + req = MAX_SIZE_T; /* force downstream failure on overflow */ + } + mem = internal_malloc(ms, req); + if(mem != 0 && calloc_must_clear(mem2chunk(mem))) + memset(mem, 0, req); + return mem; } -void* mspace_realloc(mspace msp, void* oldmem, size_t bytes) { - if (oldmem == 0) - return mspace_malloc(msp, bytes); +void *mspace_realloc(mspace msp, void *oldmem, size_t bytes) +{ + if(oldmem == 0) + return mspace_malloc(msp, bytes); #ifdef REALLOC_ZERO_BYTES_FREES - if (bytes == 0) { - mspace_free(msp, oldmem); - return 0; - } + if(bytes == 0) { + mspace_free(msp, oldmem); + return 0; + } #endif /* REALLOC_ZERO_BYTES_FREES */ - else { + else { #if FOOTERS - mchunkptr p = mem2chunk(oldmem); - mstate ms = get_mstate_for(p); -#else /* FOOTERS */ - mstate ms = (mstate)msp; + mchunkptr p = mem2chunk(oldmem); + mstate ms = get_mstate_for(p); +#else /* FOOTERS */ + mstate ms = (mstate)msp; #endif /* FOOTERS */ - if (!ok_magic(ms)) { - USAGE_ERROR_ACTION(ms,ms); - return 0; - } - return internal_realloc(ms, oldmem, bytes); - } + if(!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms, ms); + return 0; + } + return internal_realloc(ms, oldmem, bytes); + } } -void* mspace_memalign(mspace msp, size_t alignment, size_t bytes) { - mstate ms = (mstate)msp; - if (!ok_magic(ms)) { - USAGE_ERROR_ACTION(ms,ms); - return 0; - } - return internal_memalign(ms, alignment, bytes); +void *mspace_memalign(mspace msp, size_t alignment, size_t bytes) +{ + mstate ms = (mstate)msp; + if(!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms, ms); + return 0; + } + return internal_memalign(ms, alignment, bytes); } -void** mspace_independent_calloc(mspace msp, size_t n_elements, - size_t elem_size, void* chunks[]) { - size_t sz = elem_size; /* serves as 1-element array */ - mstate ms = (mstate)msp; - if (!ok_magic(ms)) { - USAGE_ERROR_ACTION(ms,ms); - return 0; - } - return ialloc(ms, n_elements, &sz, 3, chunks); +void **mspace_independent_calloc( + mspace msp, size_t n_elements, size_t elem_size, void *chunks[]) +{ + size_t sz = elem_size; /* serves as 1-element array */ + mstate ms = (mstate)msp; + if(!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms, ms); + return 0; + } + return ialloc(ms, n_elements, &sz, 3, chunks); } -void** mspace_independent_comalloc(mspace msp, size_t n_elements, - size_t sizes[], void* chunks[]) { - mstate ms = (mstate)msp; - if (!ok_magic(ms)) { - USAGE_ERROR_ACTION(ms,ms); - return 0; - } - return ialloc(ms, n_elements, sizes, 0, chunks); +void **mspace_independent_comalloc( + mspace msp, size_t n_elements, size_t sizes[], void *chunks[]) +{ + mstate ms = (mstate)msp; + if(!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms, ms); + return 0; + } + return ialloc(ms, n_elements, sizes, 0, chunks); } -int mspace_trim(mspace msp, size_t pad) { - int result = 0; - mstate ms = (mstate)msp; - if (ok_magic(ms)) { - if (!PREACTION(ms)) { - result = sys_trim(ms, pad); - POSTACTION(ms); - } - } - else { - USAGE_ERROR_ACTION(ms,ms); - } - return result; +int mspace_trim(mspace msp, size_t pad) +{ + int result = 0; + mstate ms = (mstate)msp; + if(ok_magic(ms)) { + if(!PREACTION(ms)) { + result = sys_trim(ms, pad); + POSTACTION(ms); + } + } else { + USAGE_ERROR_ACTION(ms, ms); + } + return result; } -void mspace_malloc_stats(mspace msp) { - mstate ms = (mstate)msp; - if (ok_magic(ms)) { - internal_malloc_stats(ms); - } - else { - USAGE_ERROR_ACTION(ms,ms); - } +void mspace_malloc_stats(mspace msp) +{ + mstate ms = (mstate)msp; + if(ok_magic(ms)) { + internal_malloc_stats(ms); + } else { + USAGE_ERROR_ACTION(ms, ms); + } } -size_t mspace_footprint(mspace msp) { - size_t result; - mstate ms = (mstate)msp; - if (ok_magic(ms)) { - result = ms->footprint; - } - USAGE_ERROR_ACTION(ms,ms); - return result; +size_t mspace_footprint(mspace msp) +{ + size_t result; + mstate ms = (mstate)msp; + if(ok_magic(ms)) { + result = ms->footprint; + } + USAGE_ERROR_ACTION(ms, ms); + return result; } -size_t mspace_max_footprint(mspace msp) { - size_t result; - mstate ms = (mstate)msp; - if (ok_magic(ms)) { - result = ms->max_footprint; - } - USAGE_ERROR_ACTION(ms,ms); - return result; +size_t mspace_max_footprint(mspace msp) +{ + size_t result; + mstate ms = (mstate)msp; + if(ok_magic(ms)) { + result = ms->max_footprint; + } + USAGE_ERROR_ACTION(ms, ms); + return result; } #if !NO_MALLINFO -struct mallinfo mspace_mallinfo(mspace msp) { - mstate ms = (mstate)msp; - if (!ok_magic(ms)) { - USAGE_ERROR_ACTION(ms,ms); - } - return internal_mallinfo(ms); +struct mallinfo mspace_mallinfo(mspace msp) +{ + mstate ms = (mstate)msp; + if(!ok_magic(ms)) { + USAGE_ERROR_ACTION(ms, ms); + } + return internal_mallinfo(ms); } #endif /* NO_MALLINFO */ -int mspace_mallopt(int param_number, int value) { - return change_mparam(param_number, value); +int mspace_mallopt(int param_number, int value) +{ + return change_mparam(param_number, value); } #endif /* MSPACES */ @@ -5062,22 +5130,22 @@ int mspace_mallopt(int param_number, int value) { Trial version Fri Aug 28 13:14:29 1992 Doug Lea (dl at g.oswego.edu) * Based loosely on libg++-1.2X malloc. (It retains some of the overall structure of old version, but most details differ.) - + */ -void mspace_info(mspace ms, struct mem_info* info) +void mspace_info(mspace ms, struct mem_info *info) { struct mallinfo mi; - - mi = mspace_mallinfo (ms); - memset(info,0, sizeof(*info)); - info->total_size=mi.uordblks+mi.fordblks; - info->min_frag=0; - info->free=mi.fordblks; - info->used=mi.uordblks; - info->real_used=mi.uordblks; - info->max_used=0; - info->total_frags=0; + + mi = mspace_mallinfo(ms); + memset(info, 0, sizeof(*info)); + info->total_size = mi.uordblks + mi.fordblks; + info->min_frag = 0; + info->free = mi.fordblks; + info->used = mi.uordblks; + info->real_used = mi.uordblks; + info->max_used = 0; + info->total_frags = 0; } diff --git a/src/core/mem/dl_malloc.h b/src/core/mem/dl_malloc.h index f889aff47e6..f9ff86931df 100644 --- a/src/core/mem/dl_malloc.h +++ b/src/core/mem/dl_malloc.h @@ -1,14 +1,14 @@ /* Default header file for malloc-2.8.x, written by Doug Lea and released to the public domain, as explained at - http://creativecommons.org/licenses/publicdomain. - + http://creativecommons.org/licenses/publicdomain. + last update: Mon Aug 15 08:55:52 2005 Doug Lea (dl at gee) This header is for ANSI C/C++ only. You can set any of the following #defines before including: - * If USE_DL_PREFIX is defined, it is assumed that malloc.c + * If USE_DL_PREFIX is defined, it is assumed that malloc.c was also compiled with this option, so all routines have names starting with "dl". @@ -29,33 +29,34 @@ #include "meminfo.h" #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif -#include /* for size_t */ +#include /* for size_t */ #if !ONLY_MSPACES #ifndef USE_DL_PREFIX -#define dlcalloc calloc -#define dlfree free -#define dlmalloc malloc -#define dlmemalign memalign -#define dlrealloc realloc -#define dlvalloc valloc -#define dlpvalloc pvalloc -#define dlmallinfo mallinfo -#define dlmallopt mallopt -#define dlmalloc_trim malloc_trim -#define dlmalloc_stats malloc_stats -#define dlmalloc_usable_size malloc_usable_size -#define dlmalloc_footprint malloc_footprint -#define dlindependent_calloc independent_calloc +#define dlcalloc calloc +#define dlfree free +#define dlmalloc malloc +#define dlmemalign memalign +#define dlrealloc realloc +#define dlvalloc valloc +#define dlpvalloc pvalloc +#define dlmallinfo mallinfo +#define dlmallopt mallopt +#define dlmalloc_trim malloc_trim +#define dlmalloc_stats malloc_stats +#define dlmalloc_usable_size malloc_usable_size +#define dlmalloc_footprint malloc_footprint +#define dlindependent_calloc independent_calloc #define dlindependent_comalloc independent_comalloc #endif /* USE_DL_PREFIX */ -/* + /* malloc(size_t n) Returns a pointer to a newly allocated chunk of at least n bytes, or null if no space is available, in which case errno is set to ENOMEM @@ -69,25 +70,25 @@ extern "C" { maximum supported value of n differs across systems, but is in all cases less than the maximum representable value of a size_t. */ -void* dlmalloc(size_t); + void *dlmalloc(size_t); -/* + /* free(void* p) Releases the chunk of memory pointed to by p, that had been previously allocated using malloc or a related routine such as realloc. It has no effect if p is null. If p was not malloced or already freed, free(p) will by default cuase the current program to abort. */ -void dlfree(void*); + void dlfree(void *); -/* + /* calloc(size_t n_elements, size_t element_size); Returns a pointer to n_elements * element_size bytes, with all locations set to zero. */ -void* dlcalloc(size_t, size_t); + void *dlcalloc(size_t, size_t); -/* + /* realloc(void* p, size_t n) Returns a pointer to a chunk of size n that contains the same data as does chunk p up to the minimum of (n, p's size) bytes, or null @@ -110,9 +111,9 @@ void* dlcalloc(size_t, size_t); to be used as an argument to realloc is not supported. */ -void* dlrealloc(void*, size_t); + void *dlrealloc(void *, size_t); -/* + /* memalign(size_t alignment, size_t n); Returns a pointer to a newly allocated chunk of n bytes, aligned in accord with the alignment argument. @@ -124,16 +125,16 @@ void* dlrealloc(void*, size_t); Overreliance on memalign is a sure way to fragment space. */ -void* dlmemalign(size_t, size_t); + void *dlmemalign(size_t, size_t); -/* + /* valloc(size_t n); Equivalent to memalign(pagesize, n), where pagesize is the page size of the system. If the pagesize is unknown, 4096 is used. */ -void* dlvalloc(size_t); + void *dlvalloc(size_t); -/* + /* mallopt(int parameter_number, int parameter_value) Sets tunable parameters The format is to provide a (parameter-number, parameter-value) pair. mallopt then sets the @@ -149,14 +150,14 @@ void* dlvalloc(size_t); M_GRANULARITY -2 page size any power of 2 >= page size M_MMAP_THRESHOLD -3 256*1024 any (or 0 if no MMAP support) */ -int dlmallopt(int, int); + int dlmallopt(int, int); -#define M_TRIM_THRESHOLD (-1) -#define M_GRANULARITY (-2) -#define M_MMAP_THRESHOLD (-3) +#define M_TRIM_THRESHOLD (-1) +#define M_GRANULARITY (-2) +#define M_MMAP_THRESHOLD (-3) -/* + /* malloc_footprint(); Returns the number of bytes obtained from the system. The total number of bytes allocated by malloc, realloc etc., is less than this @@ -165,7 +166,7 @@ int dlmallopt(int, int); Even if locks are otherwise defined, this function does not use them, so results might not be up to date. */ -size_t dlmalloc_footprint(); + size_t dlmalloc_footprint(); #if !NO_MALLINFO /* @@ -195,25 +196,26 @@ size_t dlmalloc_footprint(); #ifndef MALLINFO_FIELD_TYPE #define MALLINFO_FIELD_TYPE size_t #endif /* MALLINFO_FIELD_TYPE */ -struct mallinfo { - MALLINFO_FIELD_TYPE arena; /* non-mmapped space allocated from system */ - MALLINFO_FIELD_TYPE ordblks; /* number of free chunks */ - MALLINFO_FIELD_TYPE smblks; /* always 0 */ - MALLINFO_FIELD_TYPE hblks; /* always 0 */ - MALLINFO_FIELD_TYPE hblkhd; /* space in mmapped regions */ - MALLINFO_FIELD_TYPE usmblks; /* maximum total allocated space */ - MALLINFO_FIELD_TYPE fsmblks; /* always 0 */ - MALLINFO_FIELD_TYPE uordblks; /* total allocated space */ - MALLINFO_FIELD_TYPE fordblks; /* total free space */ - MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */ -}; -#endif /* _MALLOC_H */ -#endif /* HAVE_USR_INCLUDE_MALLOC_H */ - -struct mallinfo dlmallinfo(void); -#endif /* NO_MALLINFO */ + struct mallinfo + { + MALLINFO_FIELD_TYPE arena; /* non-mmapped space allocated from system */ + MALLINFO_FIELD_TYPE ordblks; /* number of free chunks */ + MALLINFO_FIELD_TYPE smblks; /* always 0 */ + MALLINFO_FIELD_TYPE hblks; /* always 0 */ + MALLINFO_FIELD_TYPE hblkhd; /* space in mmapped regions */ + MALLINFO_FIELD_TYPE usmblks; /* maximum total allocated space */ + MALLINFO_FIELD_TYPE fsmblks; /* always 0 */ + MALLINFO_FIELD_TYPE uordblks; /* total allocated space */ + MALLINFO_FIELD_TYPE fordblks; /* total free space */ + MALLINFO_FIELD_TYPE keepcost; /* releasable (via malloc_trim) space */ + }; +#endif /* _MALLOC_H */ +#endif /* HAVE_USR_INCLUDE_MALLOC_H */ + + struct mallinfo dlmallinfo(void); +#endif /* NO_MALLINFO */ -/* + /* independent_calloc(size_t n_elements, size_t element_size, void* chunks[]); independent_calloc is similar to calloc, but instead of returning a @@ -265,9 +267,9 @@ struct mallinfo dlmallinfo(void); return first; } */ -void** dlindependent_calloc(size_t, size_t, void**); + void **dlindependent_calloc(size_t, size_t, void **); -/* + /* independent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]); independent_comalloc allocates, all at once, a set of n_elements @@ -326,17 +328,17 @@ void** dlindependent_calloc(size_t, size_t, void**); since it cannot reuse existing noncontiguous small chunks that might be available for some of the elements. */ -void** dlindependent_comalloc(size_t, size_t*, void**); + void **dlindependent_comalloc(size_t, size_t *, void **); -/* + /* pvalloc(size_t n); Equivalent to valloc(minimum-page-that-holds(n)), that is, round up n to nearest pagesize. */ -void* dlpvalloc(size_t); + void *dlpvalloc(size_t); -/* + /* malloc_trim(size_t pad); If possible, gives memory back to the system (via negative arguments @@ -357,9 +359,9 @@ void* dlpvalloc(size_t); Malloc_trim returns 1 if it actually released any memory, else 0. */ -int dlmalloc_trim(size_t); + int dlmalloc_trim(size_t); -/* + /* malloc_usable_size(void* p); Returns the number of bytes you can actually use in @@ -373,9 +375,9 @@ int dlmalloc_trim(size_t); p = malloc(n); assert(malloc_usable_size(p) >= 256); */ -size_t dlmalloc_usable_size(void*); + size_t dlmalloc_usable_size(void *); -/* + /* malloc_stats(); Prints on stderr the amount of space obtained from the system (both via sbrk and mmap), the maximum amount (which may be more than @@ -394,19 +396,19 @@ size_t dlmalloc_usable_size(void*); malloc_stats prints only the most commonly interesting statistics. More information can be obtained by calling mallinfo. */ -void dlmalloc_stats(); + void dlmalloc_stats(); #endif /* !ONLY_MSPACES */ #if MSPACES -/* + /* mspace is an opaque type representing an independent region of space that supports mspace_malloc, etc. */ -typedef void* mspace; + typedef void *mspace; -/* + /* create_mspace creates and returns a new independent space with the given initial capacity, or, if 0, the default granularity size. It returns null if there is no system memory available to create the @@ -417,17 +419,17 @@ typedef void* mspace; compiling with a different DEFAULT_GRANULARITY or dynamically setting with mallopt(M_GRANULARITY, value). */ -mspace create_mspace(size_t capacity, int locked); + mspace create_mspace(size_t capacity, int locked); -/* + /* destroy_mspace destroys the given space, and attempts to return all of its memory back to the system, returning the total number of bytes freed. After destruction, the results of access to all memory used by the space become undefined. */ -size_t destroy_mspace(mspace msp); + size_t destroy_mspace(mspace msp); -/* + /* create_mspace_with_base uses the memory supplied as the initial base of a new mspace. Part (less than 128*sizeof(size_t) bytes) of this space is used for bookkeeping, so the capacity must be at least this @@ -436,15 +438,15 @@ size_t destroy_mspace(mspace msp); Destroying this space will deallocate all additionally allocated space (if possible) but not the initial base. */ -mspace create_mspace_with_base(void* base, size_t capacity, int locked); + mspace create_mspace_with_base(void *base, size_t capacity, int locked); -/* + /* mspace_malloc behaves as malloc, but operates within the given space. */ -void* mspace_malloc(mspace msp, size_t bytes); + void *mspace_malloc(mspace msp, size_t bytes); -/* + /* mspace_free behaves as free, but operates within the given space. @@ -452,9 +454,9 @@ void* mspace_malloc(mspace msp, size_t bytes); free may be called instead of mspace_free because freed chunks from any space are handled by their originating spaces. */ -void mspace_free(mspace msp, void* mem); + void mspace_free(mspace msp, void *mem); -/* + /* mspace_realloc behaves as realloc, but operates within the given space. @@ -463,72 +465,72 @@ void mspace_free(mspace msp, void* mem); realloced chunks from any space are handled by their originating spaces. */ -void* mspace_realloc(mspace msp, void* mem, size_t newsize); + void *mspace_realloc(mspace msp, void *mem, size_t newsize); -/* + /* mspace_calloc behaves as calloc, but operates within the given space. */ -void* mspace_calloc(mspace msp, size_t n_elements, size_t elem_size); + void *mspace_calloc(mspace msp, size_t n_elements, size_t elem_size); -/* + /* mspace_memalign behaves as memalign, but operates within the given space. */ -void* mspace_memalign(mspace msp, size_t alignment, size_t bytes); + void *mspace_memalign(mspace msp, size_t alignment, size_t bytes); -/* + /* mspace_independent_calloc behaves as independent_calloc, but operates within the given space. */ -void** mspace_independent_calloc(mspace msp, size_t n_elements, - size_t elem_size, void* chunks[]); + void **mspace_independent_calloc( + mspace msp, size_t n_elements, size_t elem_size, void *chunks[]); -/* + /* mspace_independent_comalloc behaves as independent_comalloc, but operates within the given space. */ -void** mspace_independent_comalloc(mspace msp, size_t n_elements, - size_t sizes[], void* chunks[]); + void **mspace_independent_comalloc( + mspace msp, size_t n_elements, size_t sizes[], void *chunks[]); -/* + /* mspace_footprint() returns the number of bytes obtained from the system for this space. */ -size_t mspace_footprint(mspace msp); + size_t mspace_footprint(mspace msp); #if !NO_MALLINFO -/* + /* mspace_mallinfo behaves as mallinfo, but reports properties of the given space. */ -struct mallinfo mspace_mallinfo(mspace msp); + struct mallinfo mspace_mallinfo(mspace msp); #endif /* NO_MALLINFO */ -/* + /* mspace_malloc_stats behaves as malloc_stats, but reports properties of the given space. */ -void mspace_malloc_stats(mspace msp); + void mspace_malloc_stats(mspace msp); -/* + /* mspace_trim behaves as malloc_trim, but operates within the given space. */ -int mspace_trim(mspace msp, size_t pad); + int mspace_trim(mspace msp, size_t pad); -/* + /* An alias for mallopt. */ -int mspace_mallopt(int, int); + int mspace_mallopt(int, int); -void mspace_info(mspace ms, struct mem_info* info); + void mspace_info(mspace ms, struct mem_info *info); -#endif /* MSPACES */ +#endif /* MSPACES */ #ifdef __cplusplus -}; /* end of extern "C" */ +}; /* end of extern "C" */ #endif #endif /* MALLOC_280_H */ diff --git a/src/core/mem/f_malloc.c b/src/core/mem/f_malloc.c index 6cb98addc13..6bc60bba0a3 100644 --- a/src/core/mem/f_malloc.c +++ b/src/core/mem/f_malloc.c @@ -44,51 +44,51 @@ /* useful macros */ #define FRAG_NEXT(f) \ - ((struct fm_frag*)((char*)(f)+sizeof(struct fm_frag)+(f)->size )) - -#define FRAG_OVERHEAD (sizeof(struct fm_frag)) -#define INIT_OVERHEAD \ - (ROUNDUP(sizeof(struct fm_block))+2*sizeof(struct fm_frag)) + ((struct fm_frag *)((char *)(f) + sizeof(struct fm_frag) + (f)->size)) +#define FRAG_OVERHEAD (sizeof(struct fm_frag)) +#define INIT_OVERHEAD \ + (ROUNDUP(sizeof(struct fm_block)) + 2 * sizeof(struct fm_frag)) /** ROUNDTO= 2^k so the following works */ -#define ROUNDTO_MASK (~((unsigned long)ROUNDTO-1)) -#define ROUNDUP(s) (((s)+(ROUNDTO-1))&ROUNDTO_MASK) -#define ROUNDDOWN(s) ((s)&ROUNDTO_MASK) - +#define ROUNDTO_MASK (~((unsigned long)ROUNDTO - 1)) +#define ROUNDUP(s) (((s) + (ROUNDTO - 1)) & ROUNDTO_MASK) +#define ROUNDDOWN(s) ((s)&ROUNDTO_MASK) /** finds the hash value for s, s=ROUNDTO multiple */ -#define GET_HASH(s) ( ((unsigned long)(s)<=F_MALLOC_OPTIMIZE)?\ - (unsigned long)(s)/ROUNDTO: \ - F_MALLOC_OPTIMIZE/ROUNDTO+big_hash_idx((s))- \ - F_MALLOC_OPTIMIZE_FACTOR+1 ) +#define GET_HASH(s) \ + (((unsigned long)(s) <= F_MALLOC_OPTIMIZE) \ + ? (unsigned long)(s) / ROUNDTO \ + : F_MALLOC_OPTIMIZE / ROUNDTO + big_hash_idx((s)) \ + - F_MALLOC_OPTIMIZE_FACTOR + 1) -#define UN_HASH(h) ( ((unsigned long)(h)<=(F_MALLOC_OPTIMIZE/ROUNDTO))?\ - (unsigned long)(h)*ROUNDTO: \ - 1UL<<((unsigned long)(h)-F_MALLOC_OPTIMIZE/ROUNDTO+\ - F_MALLOC_OPTIMIZE_FACTOR-1)\ - ) +#define UN_HASH(h) \ + (((unsigned long)(h) <= (F_MALLOC_OPTIMIZE / ROUNDTO)) \ + ? (unsigned long)(h)*ROUNDTO \ + : 1UL << ((unsigned long)(h)-F_MALLOC_OPTIMIZE / ROUNDTO \ + + F_MALLOC_OPTIMIZE_FACTOR - 1)) #ifdef F_MALLOC_HASH_BITMAP -#define fm_bmp_set(qm, b) \ - do{ \ - (qm)->free_bitmap[(b)/FM_HASH_BMP_BITS] |= \ - 1UL<<((b)%FM_HASH_BMP_BITS); \ - }while(0) +#define fm_bmp_set(qm, b) \ + do { \ + (qm)->free_bitmap[(b) / FM_HASH_BMP_BITS] |= \ + 1UL << ((b) % FM_HASH_BMP_BITS); \ + } while(0) -#define fm_bmp_reset(qm, b) \ - do{ \ - (qm)->free_bitmap[(b)/FM_HASH_BMP_BITS] &= \ - ~(1UL<<((b)%FM_HASH_BMP_BITS)); \ - }while(0) +#define fm_bmp_reset(qm, b) \ + do { \ + (qm)->free_bitmap[(b) / FM_HASH_BMP_BITS] &= \ + ~(1UL << ((b) % FM_HASH_BMP_BITS)); \ + } while(0) /** returns 0 if not set, !=0 if set */ -#define fm_bmp_is_set(qm, b) \ - ((qm)->free_bitmap[(b)/FM_HASH_BMP_BITS] & (1UL<<((b)%FM_HASH_BMP_BITS))) +#define fm_bmp_is_set(qm, b) \ + ((qm)->free_bitmap[(b) / FM_HASH_BMP_BITS] \ + & (1UL << ((b) % FM_HASH_BMP_BITS))) #define fm_is_free(f) ((f)->is_free) @@ -101,7 +101,7 @@ * \param start start value * \return index for free fragment */ -inline static int fm_bmp_first_set(struct fm_block* qm, int start) +inline static int fm_bmp_first_set(struct fm_block *qm, int start) { int bmp_idx; int bit; @@ -109,12 +109,12 @@ inline static int fm_bmp_first_set(struct fm_block* qm, int start) fm_hash_bitmap_t test_val; fm_hash_bitmap_t v; - bmp_idx=start/FM_HASH_BMP_BITS; - bit=start%FM_HASH_BMP_BITS; - test_val=1UL <<((unsigned long)bit); - if (qm->free_bitmap[bmp_idx] & test_val) + bmp_idx = start / FM_HASH_BMP_BITS; + bit = start % FM_HASH_BMP_BITS; + test_val = 1UL << ((unsigned long)bit); + if(qm->free_bitmap[bmp_idx] & test_val) return start; - else if (qm->free_bitmap[bmp_idx] & ~(test_val-1)){ + else if(qm->free_bitmap[bmp_idx] & ~(test_val - 1)) { #if 0 test_val<<=1; for (r=bit+1; rfree_bitmap[bmp_idx]>>(bit+1); - else v = 0; - return start+1+bit_scan_forward((unsigned long)v); + if((bit + 1) < 8 * sizeof(v)) + v = qm->free_bitmap[bmp_idx] >> (bit + 1); + else + v = 0; + return start + 1 + bit_scan_forward((unsigned long)v); } - for (r=bmp_idx+1;rfree_bitmap[r]){ + for(r = bmp_idx + 1; r < FM_HASH_BMP_SIZE; r++) { + if(qm->free_bitmap[r]) { /* find first set bit */ - return r*FM_HASH_BMP_BITS+ - bit_scan_forward((unsigned long)qm->free_bitmap[r]); + return r * FM_HASH_BMP_BITS + + bit_scan_forward((unsigned long)qm->free_bitmap[r]); } } /* not found, nothing free */ @@ -139,11 +141,10 @@ inline static int fm_bmp_first_set(struct fm_block* qm, int start) #endif /* F_MALLOC_HASH_BITMAP */ - /* mark/test used/unused frags */ #define FRAG_MARK_USED(f) #define FRAG_CLEAR_USED(f) -#define FRAG_WAS_USED(f) (1) +#define FRAG_WAS_USED(f) (1) /* other frag related defines: * MEM_COALESCE_FRAGS @@ -160,7 +161,7 @@ inline static int fm_bmp_first_set(struct fm_block* qm, int start) * \name Memory manager boundary check pattern */ /*@{ */ -#define ST_CHECK_PATTERN 0xf0f0f0f0 /** inserted at the beginning */ +#define ST_CHECK_PATTERN 0xf0f0f0f0 /** inserted at the beginning */ #define END_CHECK_PATTERN1 0xc0c0c0c0 /** inserted at the end */ #define END_CHECK_PATTERN2 0xabcdefed /** inserted at the end */ /*@} */ @@ -171,7 +172,7 @@ inline static int fm_bmp_first_set(struct fm_block* qm, int start) * \param qm memory block * \param frag memory fragment */ -static inline void fm_extract_free(struct fm_block* qm, struct fm_frag* frag) +static inline void fm_extract_free(struct fm_block *qm, struct fm_frag *frag) { int hash; @@ -193,12 +194,12 @@ static inline void fm_extract_free(struct fm_block* qm, struct fm_frag* frag) qm->ffrags--; qm->free_hash[hash].no--; #ifdef F_MALLOC_HASH_BITMAP - if (qm->free_hash[hash].no==0) + if(qm->free_hash[hash].no == 0) fm_bmp_reset(qm, hash); #endif /* F_MALLOC_HASH_BITMAP */ - qm->real_used+=frag->size; - qm->used+=frag->size; + qm->real_used += frag->size; + qm->used += frag->size; } /** @@ -206,21 +207,22 @@ static inline void fm_extract_free(struct fm_block* qm, struct fm_frag* frag) * \param qm memory block * \param frag memory fragment */ -static inline void fm_insert_free(struct fm_block* qm, struct fm_frag* frag) +static inline void fm_insert_free(struct fm_block *qm, struct fm_frag *frag) { - struct fm_frag* f; - struct fm_frag* p; + struct fm_frag *f; + struct fm_frag *p; int hash; - hash=GET_HASH(frag->size); - f=qm->free_hash[hash].first; - p=NULL; - if (frag->size > F_MALLOC_OPTIMIZE){ /* because of '<=' in GET_HASH, + hash = GET_HASH(frag->size); + f = qm->free_hash[hash].first; + p = NULL; + if(frag->size > F_MALLOC_OPTIMIZE) { /* because of '<=' in GET_HASH, (different from 0.8.1[24] on purpose --andrei ) */ /* large fragments list -- add at a position ordered by size */ - for(; f; f=f->next_free){ - if (frag->size <= f->size) break; + for(; f; f = f->next_free) { + if(frag->size <= f->size) + break; p = f; } @@ -249,8 +251,8 @@ static inline void fm_insert_free(struct fm_block* qm, struct fm_frag* frag) #ifdef F_MALLOC_HASH_BITMAP fm_bmp_set(qm, hash); #endif /* F_MALLOC_HASH_BITMAP */ - qm->used-=frag->size; - qm->real_used-=frag->size; + qm->used -= frag->size; + qm->real_used -= frag->size; } @@ -264,42 +266,43 @@ static inline void fm_insert_free(struct fm_block* qm, struct fm_frag* frag) */ static inline #ifdef DBG_F_MALLOC -void fm_split_frag(struct fm_block* qm, struct fm_frag* frag, - size_t size, - const char* file, const char* func, unsigned int line, - const char* mname) + void + fm_split_frag(struct fm_block *qm, struct fm_frag *frag, size_t size, + const char *file, const char *func, unsigned int line, + const char *mname) #else -void fm_split_frag(struct fm_block* qm, struct fm_frag* frag, - size_t size) + void + fm_split_frag(struct fm_block *qm, struct fm_frag *frag, size_t size) #endif { size_t rest; - struct fm_frag* n; + struct fm_frag *n; - rest=frag->size-size; + rest = frag->size - size; #ifdef MEM_FRAG_AVOIDANCE - if ((rest> (FRAG_OVERHEAD+F_MALLOC_OPTIMIZE))|| - (rest>=(FRAG_OVERHEAD+size))){ /* the residue fragm. is big enough*/ + if((rest > (FRAG_OVERHEAD + F_MALLOC_OPTIMIZE)) + || (rest >= (FRAG_OVERHEAD + + size))) { /* the residue fragm. is big enough*/ #else - if (rest>(FRAG_OVERHEAD+MIN_FRAG_SIZE)){ + if(rest > (FRAG_OVERHEAD + MIN_FRAG_SIZE)) { #endif - frag->size=size; + frag->size = size; /*split the fragment*/ - n=FRAG_NEXT(frag); - n->size=rest-FRAG_OVERHEAD; + n = FRAG_NEXT(frag); + n->size = rest - FRAG_OVERHEAD; FRAG_CLEAR_USED(n); /* never used */ #ifdef DBG_F_MALLOC /* frag created by malloc, mark it*/ - n->file=file; - n->func="frag. from fm_split_frag"; - n->line=line; - n->mname=mname; + n->file = file; + n->func = "frag. from fm_split_frag"; + n->line = line; + n->mname = mname; #endif - n->check=ST_CHECK_PATTERN; + n->check = ST_CHECK_PATTERN; /* reinsert n in free list*/ - qm->used-=FRAG_OVERHEAD; + qm->used -= FRAG_OVERHEAD; fm_insert_free(qm, n); - }else{ + } else { /* we cannot split this fragment any more => alloc all of it*/ } } @@ -311,61 +314,63 @@ void fm_split_frag(struct fm_block* qm, struct fm_frag* frag, * \param size Size of allocation * \return return the fm_block */ -struct fm_block* fm_malloc_init(char* address, unsigned long size, int type) +struct fm_block *fm_malloc_init(char *address, unsigned long size, int type) { - char* start; - char* end; - struct fm_block* qm; + char *start; + char *end; + struct fm_block *qm; unsigned long init_overhead; /* make address and size multiple of 8*/ - start=(char*)ROUNDUP((unsigned long) address); - LM_DBG("F_OPTIMIZE=%lu, /ROUNDTO=%lu\n", - F_MALLOC_OPTIMIZE, F_MALLOC_OPTIMIZE/ROUNDTO); - LM_DBG("F_HASH_SIZE=%lu, fm_block size=%lu\n", - F_HASH_SIZE, (unsigned long)sizeof(struct fm_block)); + start = (char *)ROUNDUP((unsigned long)address); + LM_DBG("F_OPTIMIZE=%lu, /ROUNDTO=%lu\n", F_MALLOC_OPTIMIZE, + F_MALLOC_OPTIMIZE / ROUNDTO); + LM_DBG("F_HASH_SIZE=%lu, fm_block size=%lu\n", F_HASH_SIZE, + (unsigned long)sizeof(struct fm_block)); LM_DBG("fm_malloc_init(%p, %lu), start=%p\n", address, (unsigned long)size, start); - if (sizesize=size; + qm->size = size; qm->used = size - init_overhead; - qm->real_used=size; - qm->max_real_used=init_overhead; + qm->real_used = size; + qm->max_real_used = init_overhead; qm->type = type; - size-=init_overhead; + size -= init_overhead; - qm->first_frag=(struct fm_frag*)(start+ROUNDUP(sizeof(struct fm_block))); - qm->last_frag=(struct fm_frag*)(end-sizeof(struct fm_frag)); + qm->first_frag = + (struct fm_frag *)(start + ROUNDUP(sizeof(struct fm_block))); + qm->last_frag = (struct fm_frag *)(end - sizeof(struct fm_frag)); /* init first fragment*/ - qm->first_frag->size=size; - qm->first_frag->prev_free=0; - qm->first_frag->next_free=0; - qm->first_frag->is_free=0; + qm->first_frag->size = size; + qm->first_frag->prev_free = 0; + qm->first_frag->next_free = 0; + qm->first_frag->is_free = 0; /* init last fragment*/ - qm->last_frag->size=0; - qm->last_frag->prev_free=0; - qm->last_frag->next_free=0; - qm->last_frag->is_free=0; + qm->last_frag->size = 0; + qm->last_frag->prev_free = 0; + qm->last_frag->next_free = 0; + qm->last_frag->is_free = 0; - qm->first_frag->check=ST_CHECK_PATTERN; - qm->last_frag->check=END_CHECK_PATTERN1; + qm->first_frag->check = ST_CHECK_PATTERN; + qm->last_frag->check = END_CHECK_PATTERN1; /* link initial fragment into the free list*/ @@ -380,16 +385,16 @@ struct fm_block* fm_malloc_init(char* address, unsigned long size, int type) * \param size memory allocation size * \return address of allocated memory */ -struct fm_frag* fm_search_defrag(struct fm_block* qm, size_t size) +struct fm_frag *fm_search_defrag(struct fm_block *qm, size_t size) { - struct fm_frag* frag; - struct fm_frag* nxt; + struct fm_frag *frag; + struct fm_frag *nxt; frag = qm->first_frag; - while((char*)frag < (char*)qm->last_frag) { + while((char *)frag < (char *)qm->last_frag) { nxt = FRAG_NEXT(frag); - if ( ((char*)nxt < (char*)qm->last_frag) && fm_is_free(frag) + if(((char *)nxt < (char *)qm->last_frag) && fm_is_free(frag) && fm_is_free(nxt)) { /* join frag with all next consecutive free frags */ fm_extract_free(qm, frag); @@ -401,11 +406,11 @@ struct fm_frag* fm_search_defrag(struct fm_block* qm, size_t size) * (real_used already has it - f and n were extracted */ qm->used += FRAG_OVERHEAD; - if( frag->size >size ) + if(frag->size > size) return frag; nxt = FRAG_NEXT(frag); - } while (((char*)nxt < (char*)qm->last_frag) && fm_is_free(nxt)); + } while(((char *)nxt < (char *)qm->last_frag) && fm_is_free(nxt)); fm_insert_free(qm, frag); } @@ -427,42 +432,45 @@ struct fm_frag* fm_search_defrag(struct fm_block* qm, size_t size) * \return address of allocated memory */ #ifdef DBG_F_MALLOC -void* fm_malloc(void* qmp, size_t size, const char* file, - const char* func, unsigned int line, const char* mname) +void *fm_malloc(void *qmp, size_t size, const char *file, const char *func, + unsigned int line, const char *mname) #else -void* fm_malloc(void* qmp, size_t size) +void *fm_malloc(void *qmp, size_t size) #endif { - struct fm_block* qm; - struct fm_frag* f; - struct fm_frag* frag; + struct fm_block *qm; + struct fm_frag *f; + struct fm_frag *frag; int hash; - qm = (struct fm_block*)qmp; + qm = (struct fm_block *)qmp; #ifdef DBG_F_MALLOC - MDBG("fm_malloc(%p, %lu) called from %s: %s(%d)\n", qm, - (unsigned long)size, file, func, line); + MDBG("fm_malloc(%p, %lu) called from %s: %s(%d)\n", qm, (unsigned long)size, + file, func, line); #endif /*malloc(0) should return a valid pointer according to specs*/ - if(unlikely(size==0)) size=4; + if(unlikely(size == 0)) + size = 4; /*size must be a multiple of 8*/ - size=ROUNDUP(size); + size = ROUNDUP(size); /*search for a suitable free frag*/ #ifdef F_MALLOC_HASH_BITMAP - hash=fm_bmp_first_set(qm, GET_HASH(size)); - if (likely(hash>=0)){ - if (likely(hash<=F_MALLOC_OPTIMIZE/ROUNDTO)) { /* return first match */ - f=qm->free_hash[hash].first; - if(likely(f)) goto found; + hash = fm_bmp_first_set(qm, GET_HASH(size)); + if(likely(hash >= 0)) { + if(likely(hash + <= F_MALLOC_OPTIMIZE / ROUNDTO)) { /* return first match */ + f = qm->free_hash[hash].first; + if(likely(f)) + goto found; #ifdef DBG_F_MALLOC - MDBG(" block %p hash %d empty but no. is %lu\n", qm, - hash, qm->free_hash[hash].no); + MDBG(" block %p hash %d empty but no. is %lu\n", qm, hash, + qm->free_hash[hash].no); #endif /* reset slot and try next hash */ - qm->free_hash[hash].no=0; + qm->free_hash[hash].no = 0; fm_bmp_reset(qm, hash); hash++; } @@ -474,17 +482,19 @@ void* fm_malloc(void* qmp, size_t size) * hash buckets. */ do { - for(f=qm->free_hash[hash].first; f; f=f->next_free) - if (f->size>=size) goto found; + for(f = qm->free_hash[hash].first; f; f = f->next_free) + if(f->size >= size) + goto found; hash++; /* try in next hash cell */ - }while((hash < F_HASH_SIZE) && - ((hash=fm_bmp_first_set(qm, hash)) >= 0)); + } while((hash < F_HASH_SIZE) + && ((hash = fm_bmp_first_set(qm, hash)) >= 0)); } -#else /* F_MALLOC_HASH_BITMAP */ - for(hash=GET_HASH(size);hashfree_hash[hash].first; - for(; f; f=f->u.nxt_free) - if (f->size>=size) goto found; +#else /* F_MALLOC_HASH_BITMAP */ + for(hash = GET_HASH(size); hash < F_HASH_SIZE; hash++) { + f = qm->free_hash[hash].first; + for(; f; f = f->u.nxt_free) + if(f->size >= size) + goto found; /* try in a bigger bucket */ } #endif /* F_MALLOC_HASH_BITMAP */ @@ -492,15 +502,16 @@ void* fm_malloc(void* qmp, size_t size) frag = fm_search_defrag(qm, size); - if(frag) goto finish; + if(frag) + goto finish; #ifdef DBG_F_MALLOC LM_ERR("fm_malloc(%p, %lu) called from %s: %s(%d)," - " module: %s; Free fragment not found!\n", - qm, (unsigned long)size, file, func, line, mname); + " module: %s; Free fragment not found!\n", + qm, (unsigned long)size, file, func, line, mname); #else - LM_ERR("fm_malloc(%p, %lu); Free fragment not found!\n", - qm, (unsigned long)size); + LM_ERR("fm_malloc(%p, %lu); Free fragment not found!\n", qm, + (unsigned long)size); #endif return 0; @@ -508,7 +519,7 @@ void* fm_malloc(void* qmp, size_t size) found: /* we found it!*/ /* detach it from the free list*/ - frag=f; + frag = f; fm_extract_free(qm, frag); /*see if use full frag or split it in two*/ @@ -521,22 +532,22 @@ void* fm_malloc(void* qmp, size_t size) finish: #ifdef DBG_F_MALLOC - frag->file=file; - frag->func=func; - frag->mname=mname; - frag->line=line; + frag->file = file; + frag->func = func; + frag->mname = mname; + frag->line = line; MDBG("fm_malloc(%p, %lu) returns address %p \n", qm, (unsigned long)size, - (char*)frag+sizeof(struct fm_frag)); + (char *)frag + sizeof(struct fm_frag)); #endif - frag->check=ST_CHECK_PATTERN; + frag->check = ST_CHECK_PATTERN; - if (qm->max_real_usedreal_used) - qm->max_real_used=qm->real_used; + if(qm->max_real_used < qm->real_used) + qm->max_real_used = qm->real_used; FRAG_MARK_USED(frag); /* mark it as used */ - if(qm->type==MEM_TYPE_PKG) { + if(qm->type == MEM_TYPE_PKG) { sr_event_exec(SREV_PKG_UPDATE_STATS, 0); } - return (char*)frag+sizeof(struct fm_frag); + return (char *)frag + sizeof(struct fm_frag); } /** @@ -549,10 +560,10 @@ void* fm_malloc(void* qmp, size_t size) * \return address of allocated memory */ #ifdef DBG_F_MALLOC -void* fm_mallocxz(void* qmp, size_t size, const char* file, - const char* func, unsigned int line, const char* mname) +void *fm_mallocxz(void *qmp, size_t size, const char *file, const char *func, + unsigned int line, const char *mname) #else -void* fm_mallocxz(void* qmp, size_t size) +void *fm_mallocxz(void *qmp, size_t size) #endif { void *p; @@ -563,7 +574,8 @@ void* fm_mallocxz(void* qmp, size_t size) p = fm_malloc(qmp, size); #endif - if(p) memset(p, 0, size); + if(p) + memset(p, 0, size); return p; } @@ -572,26 +584,25 @@ void* fm_mallocxz(void* qmp, size_t size) /** * join fragment free frag f with next one (if it is free) */ -static void fm_join_frag(struct fm_block* qm, struct fm_frag* f) +static void fm_join_frag(struct fm_block *qm, struct fm_frag *f) { struct fm_frag *n; - n=FRAG_NEXT(f); + n = FRAG_NEXT(f); /* check if n is valid and if in free list */ - if (((char*)n >= (char*)qm->last_frag) || !fm_is_free(n)) + if(((char *)n >= (char *)qm->last_frag) || !fm_is_free(n)) return; /* detach n from the free list */ fm_extract_free(qm, n); /* join - f extended with size of n plus its overhead */ - f->size+=n->size+FRAG_OVERHEAD; + f->size += n->size + FRAG_OVERHEAD; /* after join - one frag less, add its overhead to used * (real_used already has it - f and n were extracted */ qm->used += FRAG_OVERHEAD; - } #endif /*MEM_JOIN_FREE*/ @@ -603,60 +614,59 @@ static void fm_join_frag(struct fm_block* qm, struct fm_frag* f) * \param p freed memory */ #ifdef DBG_F_MALLOC -void fm_free(void* qmp, void* p, const char* file, const char* func, - unsigned int line, const char* mname) +void fm_free(void *qmp, void *p, const char *file, const char *func, + unsigned int line, const char *mname) #else -void fm_free(void* qmp, void* p) +void fm_free(void *qmp, void *p) #endif { - struct fm_block* qm; - struct fm_frag* f; + struct fm_block *qm; + struct fm_frag *f; - qm = (struct fm_block*)qmp; + qm = (struct fm_block *)qmp; #ifdef DBG_F_MALLOC MDBG("fm_free(%p, %p), called from %s: %s(%d)\n", qm, p, file, func, line); #endif - if (p==0) { + if(p == 0) { MDBG("WARNING:fm_free: free(0) called\n"); return; } #ifdef DBG_F_MALLOC - if (p>(void*)qm->last_frag || p<(void*)qm->first_frag){ - if(likely(cfg_get(core, core_cfg, mem_safety)==0)) { + if(p > (void *)qm->last_frag || p < (void *)qm->first_frag) { + if(likely(cfg_get(core, core_cfg, mem_safety) == 0)) { LM_CRIT("BUG: bad pointer %p (out of memory block (%p)!)," - " called from %s: %s(%d) - aborting\n", p, qm, - file, func, line); + " called from %s: %s(%d) - aborting\n", + p, qm, file, func, line); abort(); } else { LM_CRIT("BUG: bad pointer %p (out of memory block (%p)!)," - " called from %s: %s(%d) - ignoring\n", p, qm, - file, func, line); + " called from %s: %s(%d) - ignoring\n", + p, qm, file, func, line); return; } } #endif - f=(struct fm_frag*) ((char*)p-sizeof(struct fm_frag)); + f = (struct fm_frag *)((char *)p - sizeof(struct fm_frag)); #ifdef DBG_F_MALLOC - MDBG("fm_free: freeing block alloc'ed from %s: %s(%ld)\n", - f->file, f->func, f->line); + MDBG("fm_free: freeing block alloc'ed from %s: %s(%ld)\n", f->file, f->func, + f->line); #endif if(unlikely(fm_is_free(f))) { - LM_INFO("freeing a free fragment (%p/%p) - ignore\n", - f, p); + LM_INFO("freeing a free fragment (%p/%p) - ignore\n", f, p); return; } - if(qm->type==MEM_TYPE_PKG) { + if(qm->type == MEM_TYPE_PKG) { sr_event_exec(SREV_PKG_UPDATE_STATS, 0); } #ifdef DBG_F_MALLOC - f->file=file; - f->func=func; - f->line=line; - f->mname=mname; + f->file = file; + f->func = func; + f->line = line; + f->mname = mname; #endif #ifdef MEM_JOIN_FREE - if(likely(cfg_get(core, core_cfg, mem_join)!=0)) + if(likely(cfg_get(core, core_cfg, mem_join) != 0)) fm_join_frag(qm, f); #endif /*MEM_JOIN_FREE*/ fm_insert_free(qm, f); @@ -673,33 +683,33 @@ void fm_free(void* qmp, void* p) * \return reallocated memory block */ #ifdef DBG_F_MALLOC -void* fm_realloc(void* qmp, void* p, size_t size, - const char* file, const char* func, unsigned int line, - const char *mname) +void *fm_realloc(void *qmp, void *p, size_t size, const char *file, + const char *func, unsigned int line, const char *mname) #else -void* fm_realloc(void* qmp, void* p, size_t size) +void *fm_realloc(void *qmp, void *p, size_t size) #endif { - struct fm_block* qm; + struct fm_block *qm; struct fm_frag *f; size_t diff; size_t orig_size; struct fm_frag *n; void *ptr; - qm = (struct fm_block*)qmp; + qm = (struct fm_block *)qmp; #ifdef DBG_F_MALLOC MDBG("fm_realloc(%p, %p, %lu) called from %s: %s(%d)\n", qm, p, (unsigned long)size, file, func, line); - if ((p)&&(p>(void*)qm->last_frag || p<(void*)qm->first_frag)){ + if((p) && (p > (void *)qm->last_frag || p < (void *)qm->first_frag)) { LM_CRIT("BUG: bad pointer %p (out of memory block (%p)!) - " - "aborting\n", p, qm); + "aborting\n", + p, qm); abort(); } #endif - if (size==0) { - if (p) + if(size == 0) { + if(p) #ifdef DBG_F_MALLOC fm_free(qm, p, file, func, line, mname); #else @@ -707,93 +717,91 @@ void* fm_realloc(void* qmp, void* p, size_t size) #endif return 0; } - if (p==0) + if(p == 0) #ifdef DBG_F_MALLOC return fm_malloc(qm, size, file, func, line, mname); #else return fm_malloc(qm, size); #endif - f=(struct fm_frag*) ((char*)p-sizeof(struct fm_frag)); + f = (struct fm_frag *)((char *)p - sizeof(struct fm_frag)); #ifdef DBG_F_MALLOC - MDBG("realloc'ing frag %p alloc'ed from %s: %s(%ld)\n", - f, f->file, f->func, f->line); + MDBG("realloc'ing frag %p alloc'ed from %s: %s(%ld)\n", f, f->file, f->func, + f->line); #endif - size=ROUNDUP(size); - orig_size=f->size; - if (f->size > size){ + size = ROUNDUP(size); + orig_size = f->size; + if(f->size > size) { /* shrink */ #ifdef DBG_F_MALLOC - MDBG("shrinking from %lu to %lu\n", f->size, - (unsigned long)size); + MDBG("shrinking from %lu to %lu\n", f->size, (unsigned long)size); fm_split_frag(qm, f, size, file, "frag. from fm_realloc", line, mname); #else fm_split_frag(qm, f, size); #endif - }else if (f->sizesize < size) { /* grow */ #ifdef DBG_F_MALLOC - MDBG("growing from %lu to %lu\n", f->size, - (unsigned long)size); + MDBG("growing from %lu to %lu\n", f->size, (unsigned long)size); #endif - diff=size-f->size; - n=FRAG_NEXT(f); + diff = size - f->size; + n = FRAG_NEXT(f); /*if next frag is free, check if a join has enough size*/ - if (((char*)n < (char*)qm->last_frag) && - fm_is_free(n) && ((n->size+FRAG_OVERHEAD)>=diff)){ + if(((char *)n < (char *)qm->last_frag) && fm_is_free(n) + && ((n->size + FRAG_OVERHEAD) >= diff)) { /* detach n from the free list */ fm_extract_free(qm, n); /* join */ - f->size+=n->size+FRAG_OVERHEAD; - qm->used+=FRAG_OVERHEAD; + f->size += n->size + FRAG_OVERHEAD; + qm->used += FRAG_OVERHEAD; /* split it if necessary */ - if (f->size > size){ - #ifdef DBG_F_MALLOC - fm_split_frag(qm, f, size, file, "fragm. from fm_realloc", - line, mname); - #else + if(f->size > size) { +#ifdef DBG_F_MALLOC + fm_split_frag(qm, f, size, file, "fragm. from fm_realloc", line, + mname); +#else fm_split_frag(qm, f, size); - #endif +#endif } - }else{ + } else { /* could not join => realloc */ - #ifdef DBG_F_MALLOC - ptr=fm_malloc(qm, size, file, func, line, mname); - #else - ptr=fm_malloc(qm, size); - #endif - if (ptr){ +#ifdef DBG_F_MALLOC + ptr = fm_malloc(qm, size, file, func, line, mname); +#else + ptr = fm_malloc(qm, size); +#endif + if(ptr) { /* copy old content */ memcpy(ptr, p, orig_size); /* free old buffer */ - #ifdef DBG_F_MALLOC +#ifdef DBG_F_MALLOC fm_free(qm, p, file, func, line, mname); - #else +#else fm_free(qm, p); - #endif +#endif } else { #ifdef DBG_F_MALLOC LM_ERR("fm_realloc(%p, %lu) called from %s: %s(%d)," - " module: %s; fm_malloc() failed!\n", + " module: %s; fm_malloc() failed!\n", qm, (unsigned long)size, file, func, line, mname); #else - LM_ERR("fm_realloc(%p, %lu); fm_malloc() failed!\n", - qm, (unsigned long)size); + LM_ERR("fm_realloc(%p, %lu); fm_malloc() failed!\n", qm, + (unsigned long)size); #endif } - p=ptr; + p = ptr; } - }else{ + } else { /* do nothing */ #ifdef DBG_F_MALLOC - MDBG("doing nothing, same size: %lu - %lu\n", - f->size, (unsigned long)size); + MDBG("doing nothing, same size: %lu - %lu\n", f->size, + (unsigned long)size); #endif } #ifdef DBG_F_MALLOC MDBG("returning pointer value %p\n", p); #endif - if(qm->type==MEM_TYPE_PKG) { + if(qm->type == MEM_TYPE_PKG) { sr_event_exec(SREV_PKG_UPDATE_STATS, 0); } return p; @@ -810,11 +818,10 @@ void* fm_realloc(void* qmp, void* p, size_t size) * \return reallocated memory block */ #ifdef DBG_F_MALLOC -void* fm_reallocxf(void* qmp, void* p, size_t size, - const char* file, const char* func, unsigned int line, - const char *mname) +void *fm_reallocxf(void *qmp, void *p, size_t size, const char *file, + const char *func, unsigned int line, const char *mname) #else -void* fm_reallocxf(void* qmp, void* p, size_t size) +void *fm_reallocxf(void *qmp, void *p, size_t size) #endif { void *r; @@ -826,12 +833,11 @@ void* fm_reallocxf(void* qmp, void* p, size_t size) #endif if(!r && p) { - #ifdef DBG_F_MALLOC +#ifdef DBG_F_MALLOC fm_free(qmp, p, file, func, line, mname); - #else +#else fm_free(qmp, p); - #endif - +#endif } return r; @@ -842,35 +848,37 @@ void* fm_reallocxf(void* qmp, void* p, size_t size) * \brief Report internal memory manager status * \param qm memory block */ -void fm_status(void* qmp) +void fm_status(void *qmp) { - struct fm_block* qm; - struct fm_frag* f; - int i,j; + struct fm_block *qm; + struct fm_frag *f; + int i, j; int h; int unused; unsigned long size; int memlog; int mem_summary; - qm = (struct fm_block*)qmp; + qm = (struct fm_block *)qmp; - memlog=cfg_get(core, core_cfg, memlog); - mem_summary=cfg_get(core, core_cfg, mem_summary); + memlog = cfg_get(core, core_cfg, memlog); + mem_summary = cfg_get(core, core_cfg, mem_summary); LOG_FP(DEFAULT_FACILITY, memlog, "fm_status: ", "fm_status (%p):\n", qm); - if (!qm) return; + if(!qm) + return; LOG_FP(DEFAULT_FACILITY, memlog, "fm_status: ", " heap size= %ld\n", qm->size); #if defined(DBG_F_MALLOC) || defined(MALLOC_STATS) - LOG_FP(DEFAULT_FACILITY, memlog, "fm_status: ", - " used= %lu, used+overhead=%lu, free=%lu\n", - qm->used, qm->real_used, qm->size-qm->real_used); - LOG_FP(DEFAULT_FACILITY, memlog, "fm_status: ", - " max used (+overhead)= %lu\n", qm->max_real_used); + LOG_FP(DEFAULT_FACILITY, memlog, + "fm_status: ", " used= %lu, used+overhead=%lu, free=%lu\n", + qm->used, qm->real_used, qm->size - qm->real_used); + LOG_FP(DEFAULT_FACILITY, memlog, + "fm_status: ", " max used (+overhead)= %lu\n", qm->max_real_used); #endif - if (mem_summary & 16) return; + if(mem_summary & 16) + return; /* LOG_FP(DEFAULT_FACILITY, memlog, "fm_status: ", "dumping all fragments:\n"); @@ -888,31 +896,32 @@ void fm_status(void* qmp) } */ LOG_FP(DEFAULT_FACILITY, memlog, "fm_status: ", "dumping free list:\n"); - for(h=0,i=0,size=0;hfree_hash[h].first,j=0; f; - size+=f->size,f=f->next_free,i++,j++){ - if (!FRAG_WAS_USED(f)){ + for(h = 0, i = 0, size = 0; h < F_HASH_SIZE; h++) { + unused = 0; + for(f = qm->free_hash[h].first, j = 0; f; + size += f->size, f = f->next_free, i++, j++) { + if(!FRAG_WAS_USED(f)) { unused++; #ifdef DBG_F_MALLOC LOG_FP(DEFAULT_FACILITY, memlog, "fm_status: ", - "unused fragm.: hash = %3d, fragment %p," - " address %p size %lu, created from %s: %s(%ld)\n", - h, f, (char*)f+sizeof(struct fm_frag), f->size, - f->file, f->func, f->line); + "unused fragm.: hash = %3d, fragment %p," + " address %p size %lu, created from %s: %s(%ld)\n", + h, f, (char *)f + sizeof(struct fm_frag), f->size, + f->file, f->func, f->line); #endif }; } - if (j) LOG_FP(DEFAULT_FACILITY, memlog, "fm_status: ", - "hash = %3d fragments no.: %5d, unused: %5d\n\t\t" - " bucket size: %9lu - %9lu (first %9lu)\n", - h, j, unused, UN_HASH(h), - ((h<=F_MALLOC_OPTIMIZE/ROUNDTO)?1:2)* UN_HASH(h), - qm->free_hash[h].first->size - ); - if (j!=qm->free_hash[h].no){ + if(j) + LOG_FP(DEFAULT_FACILITY, memlog, "fm_status: ", + "hash = %3d fragments no.: %5d, unused: %5d\n\t\t" + " bucket size: %9lu - %9lu (first %9lu)\n", + h, j, unused, UN_HASH(h), + ((h <= F_MALLOC_OPTIMIZE / ROUNDTO) ? 1 : 2) * UN_HASH(h), + qm->free_hash[h].first->size); + if(j != qm->free_hash[h].no) { LM_CRIT("BUG: fm_status - different free frag. count: %d!=%ld" - " for hash %3d\n", j, qm->free_hash[h].no, h); + " for hash %3d\n", + j, qm->free_hash[h].no, h); } /* { @@ -928,10 +937,11 @@ void fm_status(void* qmp) } */ } - LOG_FP(DEFAULT_FACILITY, memlog, "fm_status: ", - "TOTAL: %6d free fragments = %6lu free bytes\n", i, size); - LOG_FP(DEFAULT_FACILITY, memlog, "fm_status: ", - "-----------------------------\n"); + LOG_FP(DEFAULT_FACILITY, memlog, + "fm_status: ", "TOTAL: %6d free fragments = %6lu free bytes\n", i, + size); + LOG_FP(DEFAULT_FACILITY, memlog, + "fm_status: ", "-----------------------------\n"); } @@ -943,19 +953,19 @@ void fm_status(void* qmp) * \param qm memory block * \param info memory information */ -void fm_info(void* qmp, struct mem_info* info) +void fm_info(void *qmp, struct mem_info *info) { - struct fm_block* qm; - - qm = (struct fm_block*)qmp; - memset(info,0, sizeof(*info)); - info->total_size=qm->size; - info->min_frag=MIN_FRAG_SIZE; - info->free_size=qm->size-qm->real_used; - info->used_size=qm->used; - info->real_used=qm->real_used; - info->max_used=qm->max_real_used; - info->total_frags=qm->ffrags; + struct fm_block *qm; + + qm = (struct fm_block *)qmp; + memset(info, 0, sizeof(*info)); + info->total_size = qm->size; + info->min_frag = MIN_FRAG_SIZE; + info->free_size = qm->size - qm->real_used; + info->used_size = qm->used; + info->real_used = qm->real_used; + info->max_used = qm->max_real_used; + info->total_frags = qm->ffrags; } @@ -965,24 +975,25 @@ void fm_info(void* qmp, struct mem_info* info) * \return Returns how much free memory is available, on error (not compiled * with bookkeeping code) returns (unsigned long)(-1) */ -unsigned long fm_available(void* qmp) +unsigned long fm_available(void *qmp) { - struct fm_block* qm; + struct fm_block *qm; - qm = (struct fm_block*)qmp; - return qm->size-qm->real_used; + qm = (struct fm_block *)qmp; + return qm->size - qm->real_used; } #ifdef DBG_F_MALLOC -static mem_counter* get_mem_counter(mem_counter **root,struct fm_frag* f) +static mem_counter *get_mem_counter(mem_counter **root, struct fm_frag *f) { mem_counter *x; - if (!*root) goto make_new; - for(x=*root;x;x=x->next) - if (x->file == f->file && x->func == f->func && x->line == f->line) + if(!*root) + goto make_new; + for(x = *root; x; x = x->next) + if(x->file == f->file && x->func == f->func && x->line == f->line) return x; make_new: x = malloc(sizeof(mem_counter)); @@ -1002,71 +1013,70 @@ static mem_counter* get_mem_counter(mem_counter **root,struct fm_frag* f) * \brief Debugging helper, summary and logs all allocated memory blocks * \param qm memory block */ -void fm_sums(void* qmp) +void fm_sums(void *qmp) { - struct fm_block* qm; + struct fm_block *qm; - qm = (struct fm_block*)qmp; - struct fm_frag* f; + qm = (struct fm_block *)qmp; + struct fm_frag *f; int i; int memlog; - mem_counter *root,*x; + mem_counter *root, *x; - root=0; - if (!qm) return; + root = 0; + if(!qm) + return; - memlog=cfg_get(core, core_cfg, memlog); - LOG_FP(DEFAULT_FACILITY, memlog, "fm_status: ", - "summarizing all alloc'ed. fragments:\n"); + memlog = cfg_get(core, core_cfg, memlog); + LOG_FP(DEFAULT_FACILITY, memlog, + "fm_status: ", "summarizing all alloc'ed. fragments:\n"); - for (f=qm->first_frag, i=0; (char*)f<(char*)qm->last_frag; - f=FRAG_NEXT(f), i++){ - if (!fm_is_free(f)){ - x = get_mem_counter(&root,f); + for(f = qm->first_frag, i = 0; (char *)f < (char *)qm->last_frag; + f = FRAG_NEXT(f), i++) { + if(!fm_is_free(f)) { + x = get_mem_counter(&root, f); x->count++; - x->size+=f->size; + x->size += f->size; } } x = root; - while(x){ - LOG_FP(DEFAULT_FACILITY, memlog, "fm_status: ", - " count=%6d size=%10lu bytes from %s: %s(%ld)\n", - x->count,x->size, - x->file, x->func, x->line - ); + while(x) { + LOG_FP(DEFAULT_FACILITY, memlog, + "fm_status: ", " count=%6d size=%10lu bytes from %s: %s(%ld)\n", + x->count, x->size, x->file, x->func, x->line); root = x->next; free(x); x = root; } - LOG_FP(DEFAULT_FACILITY, memlog, "fm_status: ", - "-----------------------------\n"); - + LOG_FP(DEFAULT_FACILITY, memlog, + "fm_status: ", "-----------------------------\n"); } void fm_mod_get_stats(void *qmp, void **fm_rootp) { - if (!fm_rootp) { + if(!fm_rootp) { return; } LM_DBG("get fm memory statistics\n"); - struct fm_block *qm = (struct fm_block *) qmp; - mem_counter **fm_root = (mem_counter **) fm_rootp; - struct fm_frag* f; + struct fm_block *qm = (struct fm_block *)qmp; + mem_counter **fm_root = (mem_counter **)fm_rootp; + struct fm_frag *f; int i; mem_counter *x; - if (!qm) return; + if(!qm) + return; /* update fragment detail list */ - for (f=qm->first_frag, i=0; (char*)f<(char*)qm->last_frag; - f=FRAG_NEXT(f), i++){ - if (f->is_free==0){ - x = get_mem_counter(fm_root,f); + for(f = qm->first_frag, i = 0; (char *)f < (char *)qm->last_frag; + f = FRAG_NEXT(f), i++) { + if(f->is_free == 0) { + x = get_mem_counter(fm_root, f); x->count++; - x->size+=f->size; + x->size += f->size; } } @@ -1075,18 +1085,18 @@ void fm_mod_get_stats(void *qmp, void **fm_rootp) void fm_mod_free_stats(void *fm_rootp) { - if (!fm_rootp) { - return ; + if(!fm_rootp) { + return; } LM_DBG("free fm memory statistics\n"); - mem_counter *root = (mem_counter *) fm_rootp; + mem_counter *root = (mem_counter *)fm_rootp; mem_counter *new, *old; new = root; old = root; - while (new) { + while(new) { old = new; new = new->next; free(old); @@ -1095,11 +1105,11 @@ void fm_mod_free_stats(void *fm_rootp) #else void fm_sums(void *qmp) { - struct fm_block* qm; + struct fm_block *qm; int memlog; - qm = (struct fm_block*)qmp; - memlog=cfg_get(core, core_cfg, memlog); + qm = (struct fm_block *)qmp; + memlog = cfg_get(core, core_cfg, memlog); LOG_FP(DEFAULT_FACILITY, memlog, "fm_sums: ", "not available (%p)\n", qm); return; } @@ -1107,13 +1117,13 @@ void fm_sums(void *qmp) void fm_mod_get_stats(void *qmp, void **fm_rootp) { LM_WARN("Enable DBG_F_MALLOC for getting statistics\n"); - return ; + return; } void fm_mod_free_stats(void *fm_rootp) { LM_WARN("Enable DBG_F_MALLOC for freeing statistics\n"); - return ; + return; } #endif /* DBG_F_MALLOC */ @@ -1130,7 +1140,7 @@ static struct fm_block *_fm_pkg_block = 0; */ void fm_malloc_destroy_pkg_manager(void) { - if (_fm_pkg_pool) { + if(_fm_pkg_pool) { free(_fm_pkg_pool); _fm_pkg_pool = 0; } @@ -1144,30 +1154,31 @@ int fm_malloc_init_pkg_manager(void) { sr_pkg_api_t ma; _fm_pkg_pool = malloc(pkg_mem_size); - if (_fm_pkg_pool) - _fm_pkg_block=fm_malloc_init(_fm_pkg_pool, pkg_mem_size, MEM_TYPE_PKG); - if (_fm_pkg_block==0){ + if(_fm_pkg_pool) + _fm_pkg_block = + fm_malloc_init(_fm_pkg_pool, pkg_mem_size, MEM_TYPE_PKG); + if(_fm_pkg_block == 0) { LM_CRIT("could not initialize fm pkg memory pool\n"); fprintf(stderr, "Too much fm pkg memory demanded: %ld bytes\n", - pkg_mem_size); + pkg_mem_size); return -1; } memset(&ma, 0, sizeof(sr_pkg_api_t)); - ma.mname = _fm_mem_name; - ma.mem_pool = _fm_pkg_pool; - ma.mem_block = _fm_pkg_block; - ma.xmalloc = fm_malloc; - ma.xmallocxz = fm_mallocxz; - ma.xfree = fm_free; - ma.xrealloc = fm_realloc; + ma.mname = _fm_mem_name; + ma.mem_pool = _fm_pkg_pool; + ma.mem_block = _fm_pkg_block; + ma.xmalloc = fm_malloc; + ma.xmallocxz = fm_mallocxz; + ma.xfree = fm_free; + ma.xrealloc = fm_realloc; ma.xreallocxf = fm_reallocxf; - ma.xstatus = fm_status; - ma.xinfo = fm_info; + ma.xstatus = fm_status; + ma.xinfo = fm_info; ma.xavailable = fm_available; - ma.xsums = fm_sums; - ma.xdestroy = fm_malloc_destroy_pkg_manager; - ma.xmodstats = fm_mod_get_stats; + ma.xsums = fm_sums; + ma.xdestroy = fm_malloc_destroy_pkg_manager; + ma.xmodstats = fm_mod_get_stats; ma.xfmodstats = fm_mod_free_stats; return pkg_init_api(&ma); @@ -1177,15 +1188,15 @@ int fm_malloc_init_pkg_manager(void) /* SHM - shared memory API*/ static void *_fm_shm_pool = 0; static struct fm_block *_fm_shm_block = 0; -static gen_lock_t* _fm_shm_lock = 0; +static gen_lock_t *_fm_shm_lock = 0; -#define fm_shm_lock() lock_get(_fm_shm_lock) -#define fm_shm_unlock() lock_release(_fm_shm_lock) +#define fm_shm_lock() lock_get(_fm_shm_lock) +#define fm_shm_unlock() lock_release(_fm_shm_lock) /** * */ -void fm_shm_glock(void* qmp) +void fm_shm_glock(void *qmp) { lock_get(_fm_shm_lock); } @@ -1193,7 +1204,7 @@ void fm_shm_glock(void* qmp) /** * */ -void fm_shm_gunlock(void* qmp) +void fm_shm_gunlock(void *qmp) { lock_release(_fm_shm_lock); } @@ -1203,7 +1214,7 @@ void fm_shm_gunlock(void* qmp) */ void fm_shm_lock_destroy(void) { - if (_fm_shm_lock){ + if(_fm_shm_lock) { DBG("destroying the shared memory lock\n"); lock_destroy(_fm_shm_lock); /* we don't need to dealloc it*/ } @@ -1214,23 +1225,23 @@ void fm_shm_lock_destroy(void) */ int fm_shm_lock_init(void) { - if (_fm_shm_lock) { + if(_fm_shm_lock) { LM_DBG("shared memory lock initialized\n"); return 0; } #ifdef DBG_F_MALLOC - _fm_shm_lock = fm_malloc(_fm_shm_block, sizeof(gen_lock_t), - _SRC_LOC_, _SRC_FUNCTION_, _SRC_LINE_, _SRC_MODULE_); + _fm_shm_lock = fm_malloc(_fm_shm_block, sizeof(gen_lock_t), _SRC_LOC_, + _SRC_FUNCTION_, _SRC_LINE_, _SRC_MODULE_); #else _fm_shm_lock = fm_malloc(_fm_shm_block, sizeof(gen_lock_t)); #endif - if (_fm_shm_lock==0){ + if(_fm_shm_lock == 0) { LOG(L_CRIT, "could not allocate lock\n"); return -1; } - if (lock_init(_fm_shm_lock)==0){ + if(lock_init(_fm_shm_lock) == 0) { LOG(L_CRIT, "could not initialize lock\n"); return -1; } @@ -1239,8 +1250,8 @@ int fm_shm_lock_init(void) /*SHM wrappers to sync the access to memory block*/ #ifdef DBG_F_MALLOC -void* fm_shm_malloc(void* qmp, size_t size, - const char* file, const char* func, unsigned int line, const char* mname) +void *fm_shm_malloc(void *qmp, size_t size, const char *file, const char *func, + unsigned int line, const char *mname) { void *r; fm_shm_lock(); @@ -1248,8 +1259,8 @@ void* fm_shm_malloc(void* qmp, size_t size, fm_shm_unlock(); return r; } -void* fm_shm_mallocxz(void* qmp, size_t size, - const char* file, const char* func, unsigned int line, const char* mname) +void *fm_shm_mallocxz(void *qmp, size_t size, const char *file, + const char *func, unsigned int line, const char *mname) { void *r; fm_shm_lock(); @@ -1257,8 +1268,8 @@ void* fm_shm_mallocxz(void* qmp, size_t size, fm_shm_unlock(); return r; } -void* fm_shm_realloc(void* qmp, void* p, size_t size, - const char* file, const char* func, unsigned int line, const char* mname) +void *fm_shm_realloc(void *qmp, void *p, size_t size, const char *file, + const char *func, unsigned int line, const char *mname) { void *r; fm_shm_lock(); @@ -1266,8 +1277,8 @@ void* fm_shm_realloc(void* qmp, void* p, size_t size, fm_shm_unlock(); return r; } -void* fm_shm_reallocxf(void* qmp, void* p, size_t size, - const char* file, const char* func, unsigned int line, const char* mname) +void *fm_shm_reallocxf(void *qmp, void *p, size_t size, const char *file, + const char *func, unsigned int line, const char *mname) { void *r; fm_shm_lock(); @@ -1275,25 +1286,26 @@ void* fm_shm_reallocxf(void* qmp, void* p, size_t size, fm_shm_unlock(); return r; } -void* fm_shm_resize(void* qmp, void* p, size_t size, - const char* file, const char* func, unsigned int line, const char* mname) +void *fm_shm_resize(void *qmp, void *p, size_t size, const char *file, + const char *func, unsigned int line, const char *mname) { void *r; fm_shm_lock(); - if(p) fm_free(qmp, p, file, func, line, mname); + if(p) + fm_free(qmp, p, file, func, line, mname); r = fm_malloc(qmp, size, file, func, line, mname); fm_shm_unlock(); return r; } -void fm_shm_free(void* qmp, void* p, const char* file, const char* func, - unsigned int line, const char* mname) +void fm_shm_free(void *qmp, void *p, const char *file, const char *func, + unsigned int line, const char *mname) { fm_shm_lock(); fm_free(qmp, p, file, func, line, mname); fm_shm_unlock(); } #else -void* fm_shm_malloc(void* qmp, size_t size) +void *fm_shm_malloc(void *qmp, size_t size) { void *r; fm_shm_lock(); @@ -1301,7 +1313,7 @@ void* fm_shm_malloc(void* qmp, size_t size) fm_shm_unlock(); return r; } -void* fm_shm_mallocxz(void* qmp, size_t size) +void *fm_shm_mallocxz(void *qmp, size_t size) { void *r; fm_shm_lock(); @@ -1309,7 +1321,7 @@ void* fm_shm_mallocxz(void* qmp, size_t size) fm_shm_unlock(); return r; } -void* fm_shm_realloc(void* qmp, void* p, size_t size) +void *fm_shm_realloc(void *qmp, void *p, size_t size) { void *r; fm_shm_lock(); @@ -1317,7 +1329,7 @@ void* fm_shm_realloc(void* qmp, void* p, size_t size) fm_shm_unlock(); return r; } -void* fm_shm_reallocxf(void* qmp, void* p, size_t size) +void *fm_shm_reallocxf(void *qmp, void *p, size_t size) { void *r; fm_shm_lock(); @@ -1325,35 +1337,36 @@ void* fm_shm_reallocxf(void* qmp, void* p, size_t size) fm_shm_unlock(); return r; } -void* fm_shm_resize(void* qmp, void* p, size_t size) +void *fm_shm_resize(void *qmp, void *p, size_t size) { void *r; fm_shm_lock(); - if(p) fm_free(qmp, p); + if(p) + fm_free(qmp, p); r = fm_malloc(qmp, size); fm_shm_unlock(); return r; } -void fm_shm_free(void* qmp, void* p) +void fm_shm_free(void *qmp, void *p) { fm_shm_lock(); fm_free(qmp, p); fm_shm_unlock(); } #endif -void fm_shm_status(void* qmp) +void fm_shm_status(void *qmp) { fm_shm_lock(); fm_status(qmp); fm_shm_unlock(); } -void fm_shm_info(void* qmp, struct mem_info* info) +void fm_shm_info(void *qmp, struct mem_info *info) { fm_shm_lock(); fm_info(qmp, info); fm_shm_unlock(); } -unsigned long fm_shm_available(void* qmp) +unsigned long fm_shm_available(void *qmp) { unsigned long r; fm_shm_lock(); @@ -1361,7 +1374,7 @@ unsigned long fm_shm_available(void* qmp) fm_shm_unlock(); return r; } -void fm_shm_sums(void* qmp) +void fm_shm_sums(void *qmp) { fm_shm_lock(); fm_sums(qmp); @@ -1397,42 +1410,43 @@ int fm_malloc_init_shm_manager(void) { sr_shm_api_t ma; _fm_shm_pool = shm_core_get_pool(); - if (_fm_shm_pool) - _fm_shm_block=fm_malloc_init(_fm_shm_pool, shm_mem_size, MEM_TYPE_SHM); - if (_fm_shm_block==0){ + if(_fm_shm_pool) + _fm_shm_block = + fm_malloc_init(_fm_shm_pool, shm_mem_size, MEM_TYPE_SHM); + if(_fm_shm_block == 0) { LM_CRIT("could not initialize fm shm memory pool\n"); fprintf(stderr, "Too much fm shm memory demanded: %ld bytes\n", - shm_mem_size); + shm_mem_size); return -1; } memset(&ma, 0, sizeof(sr_shm_api_t)); - ma.mname = _fm_mem_name; - ma.mem_pool = _fm_shm_pool; - ma.mem_block = _fm_shm_block; - ma.xmalloc = fm_shm_malloc; - ma.xmallocxz = fm_shm_mallocxz; + ma.mname = _fm_mem_name; + ma.mem_pool = _fm_shm_pool; + ma.mem_block = _fm_shm_block; + ma.xmalloc = fm_shm_malloc; + ma.xmallocxz = fm_shm_mallocxz; ma.xmalloc_unsafe = fm_malloc; - ma.xfree = fm_shm_free; - ma.xfree_unsafe = fm_free; - ma.xrealloc = fm_shm_realloc; - ma.xreallocxf = fm_shm_reallocxf; - ma.xresize = fm_shm_resize; - ma.xstatus = fm_shm_status; - ma.xinfo = fm_shm_info; - ma.xavailable = fm_shm_available; - ma.xsums = fm_shm_sums; - ma.xdestroy = fm_malloc_destroy_shm_manager; - ma.xmodstats = fm_shm_mod_get_stats; - ma.xfmodstats = fm_shm_mod_free_stats; - ma.xglock = fm_shm_glock; - ma.xgunlock = fm_shm_gunlock; - - if(shm_init_api(&ma)<0) { + ma.xfree = fm_shm_free; + ma.xfree_unsafe = fm_free; + ma.xrealloc = fm_shm_realloc; + ma.xreallocxf = fm_shm_reallocxf; + ma.xresize = fm_shm_resize; + ma.xstatus = fm_shm_status; + ma.xinfo = fm_shm_info; + ma.xavailable = fm_shm_available; + ma.xsums = fm_shm_sums; + ma.xdestroy = fm_malloc_destroy_shm_manager; + ma.xmodstats = fm_shm_mod_get_stats; + ma.xfmodstats = fm_shm_mod_free_stats; + ma.xglock = fm_shm_glock; + ma.xgunlock = fm_shm_gunlock; + + if(shm_init_api(&ma) < 0) { LM_ERR("cannot initialize the core shm api\n"); return -1; } - if(fm_shm_lock_init()<0) { + if(fm_shm_lock_init() < 0) { LM_ERR("cannot initialize the core shm lock\n"); return -1; } diff --git a/src/core/mem/f_malloc.h b/src/core/mem/f_malloc.h index 2bed0b8e537..fda311188d4 100644 --- a/src/core/mem/f_malloc.h +++ b/src/core/mem/f_malloc.h @@ -45,31 +45,32 @@ /* tricky, on sun in 32 bits mode long long must be 64 bits aligned * but long can be 32 bits aligned => malloc should return long long * aligned memory */ - #define ROUNDTO sizeof(long long) +#define ROUNDTO sizeof(long long) #else - #define ROUNDTO sizeof(void*) /* size we round to, must be = 2^n, and +#define ROUNDTO \ + sizeof(void *) /* size we round to, must be = 2^n, and * sizeof(fm_frag) must be multiple of ROUNDTO !*/ #endif #else /* DBG_F_MALLOC */ - #define ROUNDTO 8UL +#define ROUNDTO 8UL #endif -#define MIN_FRAG_SIZE ROUNDTO - +#define MIN_FRAG_SIZE ROUNDTO #define F_MALLOC_OPTIMIZE_FACTOR 14UL /* used below */ /** Size to optimize for, (most allocs <= this size), must be 2^k */ -#define F_MALLOC_OPTIMIZE (1UL<size )) + ((struct sfm_frag *)((char *)(f) + sizeof(struct sfm_frag) + (f)->size)) /* SF_ROUNDTO= 2^k so the following works */ -#define ROUNDTO_MASK (~((unsigned long)SF_ROUNDTO-1)) -#define ROUNDUP(s) (((s)+(SF_ROUNDTO-1))&ROUNDTO_MASK) -#define ROUNDDOWN(s) ((s)&ROUNDTO_MASK) - -#define FRAG_OVERHEAD (sizeof(struct sfm_frag)) -#define INIT_OVERHEAD \ - (ROUNDUP(sizeof(struct sfm_block))+sizeof(struct sfm_frag)) +#define ROUNDTO_MASK (~((unsigned long)SF_ROUNDTO - 1)) +#define ROUNDUP(s) (((s) + (SF_ROUNDTO - 1)) & ROUNDTO_MASK) +#define ROUNDDOWN(s) ((s)&ROUNDTO_MASK) +#define FRAG_OVERHEAD (sizeof(struct sfm_frag)) +#define INIT_OVERHEAD \ + (ROUNDUP(sizeof(struct sfm_block)) + sizeof(struct sfm_frag)) /* finds hash if s <=SF_MALLOC_OPTIMIZE */ -#define GET_SMALL_HASH(s) (unsigned long)(s)/SF_ROUNDTO +#define GET_SMALL_HASH(s) (unsigned long)(s) / SF_ROUNDTO /* finds hash if s > SF_MALLOC_OPTIMIZE */ -#define GET_BIG_HASH(s) \ - (SF_MALLOC_OPTIMIZE/SF_ROUNDTO+big_hash_idx((s))-SF_MALLOC_OPTIMIZE_FACTOR+1) +#define GET_BIG_HASH(s) \ + (SF_MALLOC_OPTIMIZE / SF_ROUNDTO + big_hash_idx((s)) \ + - SF_MALLOC_OPTIMIZE_FACTOR + 1) /* finds the hash value for s, s=SF_ROUNDTO multiple*/ -#define GET_HASH(s) ( ((unsigned long)(s)<=SF_MALLOC_OPTIMIZE)?\ - GET_SMALL_HASH(s): GET_BIG_HASH(s) ) +#define GET_HASH(s) \ + (((unsigned long)(s) <= SF_MALLOC_OPTIMIZE) ? GET_SMALL_HASH(s) \ + : GET_BIG_HASH(s)) #define UN_HASH_SMALL(h) ((unsigned long)(h)*SF_ROUNDTO) -#define UN_HASH_BIG(h) (1UL<<((unsigned long)(h)-SF_MALLOC_OPTIMIZE/SF_ROUNDTO+\ - SF_MALLOC_OPTIMIZE_FACTOR-1)) +#define UN_HASH_BIG(h) \ + (1UL << ((unsigned long)(h)-SF_MALLOC_OPTIMIZE / SF_ROUNDTO \ + + SF_MALLOC_OPTIMIZE_FACTOR - 1)) -#define UN_HASH(h) ( ((unsigned long)(h)<=(SF_MALLOC_OPTIMIZE/SF_ROUNDTO))?\ - UN_HASH_SMALL(h): UN_HASH_BIG(h) ) +#define UN_HASH(h) \ + (((unsigned long)(h) <= (SF_MALLOC_OPTIMIZE / SF_ROUNDTO)) \ + ? UN_HASH_SMALL(h) \ + : UN_HASH_BIG(h)) -#define BITMAP_BITS (sizeof(((struct sfm_block*)0)->bitmap)*8) -#define BITMAP_BLOCK_SIZE ((SF_MALLOC_OPTIMIZE/SF_ROUNDTO)/ BITMAP_BITS) +#define BITMAP_BITS (sizeof(((struct sfm_block *)0)->bitmap) * 8) +#define BITMAP_BLOCK_SIZE ((SF_MALLOC_OPTIMIZE / SF_ROUNDTO) / BITMAP_BITS) /* only for "small" hashes (up to HASH(SF_MALLOC_OPTIMIZE) */ -#define HASH_BIT_POS(h) (((unsigned long)(h))/BITMAP_BLOCK_SIZE) -#define HASH_TO_BITMAP(h) (1UL< s = k*2^n (SF_ROUNDTO=2^n) + /* s is rounded => s = k*2^n (SF_ROUNDTO=2^n) * index= i such that 2^i > s >= 2^(i-1) * * => index = number of the first non null bit in s*/ - idx=sizeof(long)*8-1; - for (; !(s&(1UL<<(sizeof(long)*8-1))) ; s<<=1, idx--); + idx = sizeof(long) * 8 - 1; + for(; !(s & (1UL << (sizeof(long) * 8 - 1))); s <<= 1, idx--) + ; return idx; } #ifdef DBG_F_MALLOC -#define ST_CHECK_PATTERN 0xf0f0f0f0 +#define ST_CHECK_PATTERN 0xf0f0f0f0 #define END_CHECK_PATTERN1 0xc0c0c0c0 #define END_CHECK_PATTERN2 0xabcdefed #endif @@ -123,9 +127,8 @@ inline static unsigned long big_hash_idx(unsigned long s) #elif defined SFM_LOCK_PER_BUCKET -#define SFM_MAIN_HASH_LOCK(qm, hash) \ - lock_get(&(qm)->free_hash[(hash)].lock) -#define SFM_MAIN_HASH_UNLOCK(qm, hash) \ +#define SFM_MAIN_HASH_LOCK(qm, hash) lock_get(&(qm)->free_hash[(hash)].lock) +#define SFM_MAIN_HASH_UNLOCK(qm, hash) \ lock_release(&(qm)->free_hash[(hash)].lock) #define SFM_POOL_LOCK(p, hash) lock_get(&(p)->pool_hash[(hash)].lock) #define SFM_POOL_UNLOCK(p, hash) lock_release(&(p)->pool_hash[(hash)].lock) @@ -133,484 +136,486 @@ inline static unsigned long big_hash_idx(unsigned long s) #error no locks defined #endif /* SFM_ONE_LOCK/SFM_LOCK_PER_BUCKET */ -#define SFM_BIG_GET_AND_SPLIT_LOCK(qm) lock_get(&(qm)->get_and_split) +#define SFM_BIG_GET_AND_SPLIT_LOCK(qm) lock_get(&(qm)->get_and_split) #define SFM_BIG_GET_AND_SPLIT_UNLOCK(qm) lock_release(&(qm)->get_and_split) -static unsigned long sfm_max_hash=0; /* maximum hash value (no point in +static unsigned long sfm_max_hash = 0; /* maximum hash value (no point in searching further) */ -static unsigned long pool_id=(unsigned long)-1; +static unsigned long pool_id = (unsigned long)-1; /* call for each child */ int sfm_pool_reset() { - pool_id=(unsigned long)-1; + pool_id = (unsigned long)-1; return 0; } -#define sfm_fix_pool_id(qm) \ - do{ \ - if (unlikely(pool_id>=SFM_POOLS_NO)) \ - pool_id=((unsigned)atomic_add(&(qm)->crt_id, 1))%SFM_POOLS_NO; \ - }while(0) +#define sfm_fix_pool_id(qm) \ + do { \ + if(unlikely(pool_id >= SFM_POOLS_NO)) \ + pool_id = ((unsigned)atomic_add(&(qm)->crt_id, 1)) % SFM_POOLS_NO; \ + } while(0) - -static inline void frag_push(struct sfm_frag** head, struct sfm_frag* frag) +static inline void frag_push(struct sfm_frag **head, struct sfm_frag *frag) { - register struct sfm_frag* old; - register struct sfm_frag* crt; - - crt=(void*)atomic_get_long(head); - do{ - frag->u.nxt_free=crt; - old=crt; + register struct sfm_frag *old; + register struct sfm_frag *crt; + + crt = (void *)atomic_get_long(head); + do { + frag->u.nxt_free = crt; + old = crt; membar_write_atomic_op(); - crt=(void*)atomic_cmpxchg_long((void*)head, (long)old, (long)frag); - }while(crt!=old); + crt = (void *)atomic_cmpxchg_long((void *)head, (long)old, (long)frag); + } while(crt != old); } -static inline struct sfm_frag* frag_pop(struct sfm_frag** head) +static inline struct sfm_frag *frag_pop(struct sfm_frag **head) { - register struct sfm_frag* old; - register struct sfm_frag* crt; - register struct sfm_frag* nxt; - - crt=(void*)atomic_get_long(head); - do{ + register struct sfm_frag *old; + register struct sfm_frag *crt; + register struct sfm_frag *nxt; + + crt = (void *)atomic_get_long(head); + do { /* if circular list, test not needed */ - nxt=crt?crt->u.nxt_free:0; - old=crt; + nxt = crt ? crt->u.nxt_free : 0; + old = crt; membar_read_atomic_op(); - crt=(void*)atomic_cmpxchg_long((void*)head, (long)old, (long)nxt); - }while(crt!=old); + crt = (void *)atomic_cmpxchg_long((void *)head, (long)old, (long)nxt); + } while(crt != old); return crt; } -static inline void sfm_pool_insert (struct sfm_pool* pool, int hash, - struct sfm_frag* frag) +static inline void sfm_pool_insert( + struct sfm_pool *pool, int hash, struct sfm_frag *frag) { unsigned long hash_bit; frag_push(&pool->pool_hash[hash].first, frag); - atomic_inc_long((long*)&pool->pool_hash[hash].no); + atomic_inc_long((long *)&pool->pool_hash[hash].no); /* set it only if not already set (avoids an expensive * cache trashing atomic write op) */ - hash_bit=HASH_TO_BITMAP(hash); - if (!(atomic_get_long((long*)&pool->bitmap) & hash_bit)) - atomic_or_long((long*)&pool->bitmap, hash_bit); + hash_bit = HASH_TO_BITMAP(hash); + if(!(atomic_get_long((long *)&pool->bitmap) & hash_bit)) + atomic_or_long((long *)&pool->bitmap, hash_bit); } - /* returns 1 if it's ok to add a fragm. to pool p_id @ hash, 0 otherwise */ -static inline int sfm_check_pool(struct sfm_block* qm, unsigned long p_id, - int hash, int split) +static inline int sfm_check_pool( + struct sfm_block *qm, unsigned long p_id, int hash, int split) { /* TODO: come up with something better * if fragment is some split/rest from an allocation, that is * >= requested size, accept it, else * look at misses and current fragments and decide based on them */ - return (p_idpool[p_id].pool_hash[hash].no < MIN_POOL_FRAGS) || - ((qm->pool[p_id].pool_hash[hash].misses > - qm->pool[p_id].pool_hash[hash].no) && - (qm->pool[p_id].pool_hash[hash].nopool[p_id].pool_hash[hash].no < MIN_POOL_FRAGS) + || ((qm->pool[p_id].pool_hash[hash].misses + > qm->pool[p_id].pool_hash[hash].no) + && (qm->pool[p_id].pool_hash[hash].no + < MAX_POOL_FRAGS)))); } /* choose on which pool to add a free'd packet * return - pool idx or -1 if it should be added to main*/ -static inline unsigned long sfm_choose_pool(struct sfm_block* qm, - struct sfm_frag* frag, - int hash, int split) +static inline unsigned long sfm_choose_pool( + struct sfm_block *qm, struct sfm_frag *frag, int hash, int split) { /* check original pool first */ - if (sfm_check_pool(qm, frag->id, hash, split)) + if(sfm_check_pool(qm, frag->id, hash, split)) return frag->id; - else{ + else { /* check if our pool is properly set */ sfm_fix_pool_id(qm); /* check if my pool needs some frags */ - if ((pool_id!=frag->id) && (sfm_check_pool(qm, pool_id, hash, 0))){ - frag->id=pool_id; + if((pool_id != frag->id) && (sfm_check_pool(qm, pool_id, hash, 0))) { + frag->id = pool_id; return pool_id; } } /* else add it back to main */ - frag->id=(unsigned long)(-1); + frag->id = (unsigned long)(-1); return frag->id; } -static inline void sfm_insert_free(struct sfm_block* qm, struct sfm_frag* frag, - int split) +static inline void sfm_insert_free( + struct sfm_block *qm, struct sfm_frag *frag, int split) { - struct sfm_frag** f; + struct sfm_frag **f; unsigned long p_id; int hash; unsigned long hash_bit; - - if (likely(frag->size<=SF_POOL_MAX_SIZE)){ - hash=GET_SMALL_HASH(frag->size); - if (unlikely((p_id=sfm_choose_pool(qm, frag, hash, split))== - (unsigned long)-1)){ + + if(likely(frag->size <= SF_POOL_MAX_SIZE)) { + hash = GET_SMALL_HASH(frag->size); + if(unlikely((p_id = sfm_choose_pool(qm, frag, hash, split)) + == (unsigned long)-1)) { /* add it back to the "main" hash */ - frag->id=(unsigned long)(-1); /* main hash marker */ - /*insert it here*/ - frag_push(&(qm->free_hash[hash].first), frag); - atomic_inc_long((long*)&qm->free_hash[hash].no); - /* set it only if not already set (avoids an expensive + frag->id = (unsigned long)(-1); /* main hash marker */ + /*insert it here*/ + frag_push(&(qm->free_hash[hash].first), frag); + atomic_inc_long((long *)&qm->free_hash[hash].no); + /* set it only if not already set (avoids an expensive * cache trashing atomic write op) */ - hash_bit=HASH_TO_BITMAP(hash); - if (!(atomic_get_long((long*)&qm->bitmap) & hash_bit)) - atomic_or_long((long*)&qm->bitmap, hash_bit); - }else{ + hash_bit = HASH_TO_BITMAP(hash); + if(!(atomic_get_long((long *)&qm->bitmap) & hash_bit)) + atomic_or_long((long *)&qm->bitmap, hash_bit); + } else { /* add it to one of the pools pool */ sfm_pool_insert(&qm->pool[p_id], hash, frag); } - }else{ - hash=GET_BIG_HASH(frag->size); + } else { + hash = GET_BIG_HASH(frag->size); SFM_MAIN_HASH_LOCK(qm, hash); - f=&(qm->free_hash[hash].first); - for(; *f; f=&((*f)->u.nxt_free)) - if (frag->size <= (*f)->size) break; - frag->id=(unsigned long)(-1); /* main hash marker */ - /*insert it here*/ - frag->u.nxt_free=*f; - *f=frag; - qm->free_hash[hash].no++; - /* inc. big hash free size ? */ + f = &(qm->free_hash[hash].first); + for(; *f; f = &((*f)->u.nxt_free)) + if(frag->size <= (*f)->size) + break; + frag->id = (unsigned long)(-1); /* main hash marker */ + /*insert it here*/ + frag->u.nxt_free = *f; + *f = frag; + qm->free_hash[hash].no++; + /* inc. big hash free size ? */ SFM_MAIN_HASH_UNLOCK(qm, hash); } - } - - /* size should be already rounded-up */ +/* size should be already rounded-up */ static inline -#ifdef DBG_F_MALLOC -void sfm_split_frag(struct sfm_block* qm, struct sfm_frag* frag, - unsigned long size, - const char* file, const char* func, unsigned int line) +#ifdef DBG_F_MALLOC + void + sfm_split_frag(struct sfm_block *qm, struct sfm_frag *frag, + unsigned long size, const char *file, const char *func, + unsigned int line) #else -void sfm_split_frag(struct sfm_block* qm, struct sfm_frag* frag, - unsigned long size) + void + sfm_split_frag( + struct sfm_block *qm, struct sfm_frag *frag, unsigned long size) #endif { unsigned long rest; - struct sfm_frag* n; + struct sfm_frag *n; int bigger_rest; - - rest=frag->size-size; + + rest = frag->size - size; #ifdef MEM_FRAG_AVOIDANCE - if ((rest> (FRAG_OVERHEAD+SF_MALLOC_OPTIMIZE))|| - (rest>=(FRAG_OVERHEAD+size))){ /* the residue fragm. is big enough*/ - bigger_rest=1; + if((rest > (FRAG_OVERHEAD + SF_MALLOC_OPTIMIZE)) + || (rest >= (FRAG_OVERHEAD + + size))) { /* the residue fragm. is big enough*/ + bigger_rest = 1; #else - if (rest>(FRAG_OVERHEAD+SF_MIN_FRAG_SIZE)){ - bigger_rest=rest>=(size+FRAG_OVERHEAD); + if(rest > (FRAG_OVERHEAD + SF_MIN_FRAG_SIZE)) { + bigger_rest = rest >= (size + FRAG_OVERHEAD); #endif - frag->size=size; + frag->size = size; /*split the fragment*/ - n=FRAG_NEXT(frag); - n->size=rest-FRAG_OVERHEAD; - n->id=pool_id; + n = FRAG_NEXT(frag); + n->size = rest - FRAG_OVERHEAD; + n->id = pool_id; FRAG_CLEAR_USED(n); /* never used */ #ifdef DBG_F_MALLOC /* frag created by malloc, mark it*/ - n->file=file; - n->func="frag. from sfm_malloc"; - n->line=line; - n->check=ST_CHECK_PATTERN; + n->file = file; + n->func = "frag. from sfm_malloc"; + n->line = line; + n->check = ST_CHECK_PATTERN; #endif /* reinsert n in free list*/ sfm_insert_free(qm, n, bigger_rest); - }else{ + } else { /* we cannot split this fragment any more => alloc all of it*/ } } - /* init malloc and return a sfm_block*/ -struct sfm_block* sfm_malloc_init(char* address, unsigned long size, int type) +struct sfm_block *sfm_malloc_init(char *address, unsigned long size, int type) { - char* start; - char* end; - struct sfm_block* qm; + char *start; + char *end; + struct sfm_block *qm; unsigned long init_overhead; int r; #ifdef SFM_LOCK_PER_BUCKET int i; #endif - + /* make address and size multiple of 8*/ - start=(char*)ROUNDUP((unsigned long) address); + start = (char *)ROUNDUP((unsigned long)address); DBG("sfm_malloc_init: SF_OPTIMIZE=%lu, /SF_ROUNDTO=%lu\n", - SF_MALLOC_OPTIMIZE, SF_MALLOC_OPTIMIZE/SF_ROUNDTO); - DBG("sfm_malloc_init: SF_HASH_SIZE=%lu, sfm_block size=%lu\n", - SF_HASH_SIZE, (long)sizeof(struct sfm_block)); + SF_MALLOC_OPTIMIZE, SF_MALLOC_OPTIMIZE / SF_ROUNDTO); + DBG("sfm_malloc_init: SF_HASH_SIZE=%lu, sfm_block size=%lu\n", SF_HASH_SIZE, + (long)sizeof(struct sfm_block)); DBG("sfm_malloc_init(%p, %lu), start=%p\n", address, size, start); - if (sizesize=size; + qm->size = size; qm->type = type; - size-=init_overhead; - - qm->first_frag=(struct sfm_frag*)(start+ROUNDUP(sizeof(struct sfm_block))); - qm->last_frag=(struct sfm_frag*)(end-sizeof(struct sfm_frag)); + size -= init_overhead; + + qm->first_frag = + (struct sfm_frag *)(start + ROUNDUP(sizeof(struct sfm_block))); + qm->last_frag = (struct sfm_frag *)(end - sizeof(struct sfm_frag)); /* init initial fragment*/ - qm->first_frag->size=size; - qm->first_frag->id=(unsigned long)-1; /* not in a pool */ - qm->last_frag->size=0; - + qm->first_frag->size = size; + qm->first_frag->id = (unsigned long)-1; /* not in a pool */ + qm->last_frag->size = 0; + #ifdef DBG_F_MALLOC - qm->first_frag->check=ST_CHECK_PATTERN; - qm->last_frag->check=END_CHECK_PATTERN1; + qm->first_frag->check = ST_CHECK_PATTERN; + qm->last_frag->check = END_CHECK_PATTERN1; #endif - + /* link initial fragment into the free list*/ - + sfm_insert_free(qm, qm->first_frag, 0); - sfm_max_hash=GET_HASH(size); - + sfm_max_hash = GET_HASH(size); + /* init locks */ - if (lock_init(&qm->get_and_split)==0) + if(lock_init(&qm->get_and_split) == 0) goto error; #ifdef SFM_ONE_LOCK - if (lock_init(&qm->lock)==0){ + if(lock_init(&qm->lock) == 0) { lock_destroy(&qm->get_and_split); goto error; } - for (r=0; rpool[r].lock)==0){ - for (;r>0; r--) lock_destroy(&qm->pool[r-1].lock); + for(r = 0; r < SFM_POOLS_NO; r++) { + if(lock_init(&qm->pool[r].lock) == 0) { + for(; r > 0; r--) + lock_destroy(&qm->pool[r - 1].lock); lock_destroy(&qm->lock); lock_destroy(&qm->get_and_split); goto error; } } #elif defined(SFM_LOCK_PER_BUCKET) - for (r=0; rfree_hash[r].lock)==0){ - for(;r>0; r--) lock_destroy(&qm->free_hash[r-1].lock); + for(r = 0; r < SF_HASH_SIZE; r++) + if(lock_init(&qm->free_hash[r].lock) == 0) { + for(; r > 0; r--) + lock_destroy(&qm->free_hash[r - 1].lock); lock_destroy(&qm->get_and_split); goto error; } - for (i=0; ipool[i].pool_hash[r].lock)==0){ - for(;r>0; r--) lock_destroy(&qm->pool[i].poo_hash[r].lock); - for(; i>0; i--){ - for (r=0; rpool[i].pool_hash[r].lock) == 0) { + for(; r > 0; r--) + lock_destroy(&qm->pool[i].poo_hash[r].lock); + for(; i > 0; i--) { + for(r = 0; r < SF_HASH_POOL_SIZE; r++) lock_destroy(&qm->pool[i].pool_hash[r].lock); } - for (r=0; rfree_hash[r].lock); lock_destroy(&qm->get_and_split); goto error; } } #endif - qm->is_init=1; + qm->is_init = 1; return qm; error: return 0; } - /* cleanup */ -void sfm_malloc_destroy(struct sfm_block* qm) +void sfm_malloc_destroy(struct sfm_block *qm) { int r, i; /* destroy all the locks */ - if (!qm || !qm->is_init) + if(!qm || !qm->is_init) return; /* nothing to do */ lock_destroy(&qm->get_and_split); #ifdef SFM_ONE_LOCK lock_destroy(&qm->lock); - for (r=0; rpool[r].lock); } #elif defined(SFM_LOCK_PER_BUCKET) - for (r=0; rfree_hash[r].lock); - for (i=0; ipool[i].pool_hash[r].lock); } #endif - qm->is_init=0; - + qm->is_init = 0; } /* returns next set bit in bitmap, starts at b * if b is set, returns b * if not found returns BITMAP_BITS */ -static inline unsigned long _next_set_bit(unsigned long b, - unsigned long* bitmap) +static inline unsigned long _next_set_bit( + unsigned long b, unsigned long *bitmap) { - for (; !((1UL<=BITMAP_BITS))){ - s=BIT_TO_HASH(BITMAP_BITS); - *end=SF_HASH_POOL_SIZE; /* last, possible rest block */ - }else{ - s=BIT_TO_HASH(b); - *end=s+BITMAP_BLOCK_SIZE; + + if((unlikely(b >= BITMAP_BITS))) { + s = BIT_TO_HASH(BITMAP_BITS); + *end = SF_HASH_POOL_SIZE; /* last, possible rest block */ + } else { + s = BIT_TO_HASH(b); + *end = s + BITMAP_BLOCK_SIZE; } return s; } #ifdef DBG_F_MALLOC -static inline struct sfm_frag* pool_get_frag(struct sfm_block* qm, - struct sfm_pool* pool, int hash, unisgned long size, - const char* file, const char* func, unsigned int line) +static inline struct sfm_frag *pool_get_frag(struct sfm_block *qm, + struct sfm_pool *pool, int hash, unisgned long size, const char *file, + const char *func, unsigned int line) #else -static inline struct sfm_frag* pool_get_frag(struct sfm_block* qm, - struct sfm_pool* pool, - int hash, unsigned long size) +static inline struct sfm_frag *pool_get_frag(struct sfm_block *qm, + struct sfm_pool *pool, int hash, unsigned long size) #endif { int r; int next_block; - struct sfm_frag* volatile* f; - struct sfm_frag* frag; + struct sfm_frag *volatile *f; + struct sfm_frag *frag; unsigned long b; unsigned long eob; /* special case for r=hash */ - r=hash; - f=&pool->pool_hash[r].first; + r = hash; + f = &pool->pool_hash[r].first; /* detach it from the free list */ - if ((frag=frag_pop((struct sfm_frag**)f))==0) + if((frag = frag_pop((struct sfm_frag **)f)) == 0) goto not_found; found: - atomic_dec_long((long*)&pool->pool_hash[r].no); - frag->u.nxt_free=0; /* mark it as 'taken' */ - frag->id=pool_id; + atomic_dec_long((long *)&pool->pool_hash[r].no); + frag->u.nxt_free = 0; /* mark it as 'taken' */ + frag->id = pool_id; #ifdef DBG_F_MALLOC sfm_split_frag(qm, frag, size, file, func, line); #else sfm_split_frag(qm, frag, size); #endif - if (&qm->pool[pool_id]==pool) - atomic_inc_long((long*)&pool->hits); + if(&qm->pool[pool_id] == pool) + atomic_inc_long((long *)&pool->hits); return frag; - + not_found: - atomic_inc_long((long*)&pool->pool_hash[r].misses); + atomic_inc_long((long *)&pool->pool_hash[r].misses); r++; - b=HASH_BIT_POS(r); - - while(rbitmap); - next_block=_hash_range(b, &eob); - r=(rpool_hash[r].first; - if ((frag=frag_pop((struct sfm_frag**)f))!=0) + b = HASH_BIT_POS(r); + + while(r < SF_HASH_POOL_SIZE) { + b = _next_set_bit(b, &pool->bitmap); + next_block = _hash_range(b, &eob); + r = (r < next_block) ? next_block : r; + for(; r < eob; r++) { + f = &pool->pool_hash[r].first; + if((frag = frag_pop((struct sfm_frag **)f)) != 0) goto found; - atomic_inc_long((long*)&pool->pool_hash[r].misses); + atomic_inc_long((long *)&pool->pool_hash[r].misses); } b++; } - atomic_inc_long((long*)&pool->missed); + atomic_inc_long((long *)&pool->missed); return 0; } - #ifdef DBG_F_MALLOC -static inline struct sfm_frag* main_get_frag(struct sfm_block* qm, int hash, - unsigned long size, - const char* file, const char* func, unsigned int line) +static inline struct sfm_frag *main_get_frag(struct sfm_block *qm, int hash, + unsigned long size, const char *file, const char *func, + unsigned int line) #else -static inline struct sfm_frag* main_get_frag(struct sfm_block* qm, int hash, - unsigned long size) +static inline struct sfm_frag *main_get_frag( + struct sfm_block *qm, int hash, unsigned long size) #endif { int r; int next_block; - struct sfm_frag* volatile* f; - struct sfm_frag* frag; + struct sfm_frag *volatile *f; + struct sfm_frag *frag; unsigned long b; unsigned long eob; - r=hash; - b=HASH_BIT_POS(r); - while(r<=SF_MALLOC_OPTIMIZE/SF_ROUNDTO){ - b=_next_set_bit(b, &qm->bitmap); - next_block=_hash_range(b, &eob); - r=(rfree_hash[r].first; - if ((frag=frag_pop((struct sfm_frag**)f))!=0){ - atomic_dec_long((long*)&qm->free_hash[r].no); - frag->u.nxt_free=0; /* mark it as 'taken' */ - frag->id=pool_id; + r = hash; + b = HASH_BIT_POS(r); + while(r <= SF_MALLOC_OPTIMIZE / SF_ROUNDTO) { + b = _next_set_bit(b, &qm->bitmap); + next_block = _hash_range(b, &eob); + r = (r < next_block) ? next_block : r; + for(; r < eob; r++) { + f = &qm->free_hash[r].first; + if((frag = frag_pop((struct sfm_frag **)f)) != 0) { + atomic_dec_long((long *)&qm->free_hash[r].no); + frag->u.nxt_free = 0; /* mark it as 'taken' */ + frag->id = pool_id; #ifdef DBG_F_MALLOC - sfm_split_frag(qm, frag, size, file, func, line); + sfm_split_frag(qm, frag, size, file, func, line); #else - sfm_split_frag(qm, frag, size); + sfm_split_frag(qm, frag, size); #endif - return frag; - } + return frag; } - b++; + } + b++; } /* big fragments */ SFM_BIG_GET_AND_SPLIT_LOCK(qm); - for (; r<= sfm_max_hash ; r++){ - f=&qm->free_hash[r].first; - if (*f){ + for(; r <= sfm_max_hash; r++) { + f = &qm->free_hash[r].first; + if(*f) { SFM_MAIN_HASH_LOCK(qm, r); - if (unlikely((*f)==0)){ + if(unlikely((*f) == 0)) { /* not found */ SFM_MAIN_HASH_UNLOCK(qm, r); - continue; + continue; } - for(;(*f); f=&((*f)->u.nxt_free)) - if ((*f)->size>=size){ + for(; (*f); f = &((*f)->u.nxt_free)) + if((*f)->size >= size) { /* found, detach it from the free list*/ - frag=*f; - *f=frag->u.nxt_free; - frag->u.nxt_free=0; /* mark it as 'taken' */ + frag = *f; + *f = frag->u.nxt_free; + frag->u.nxt_free = 0; /* mark it as 'taken' */ qm->free_hash[r].no--; SFM_MAIN_HASH_UNLOCK(qm, r); - frag->id=pool_id; + frag->id = pool_id; #ifdef DBG_F_MALLOC sfm_split_frag(qm, frag, size, file, func, line); #else @@ -628,69 +633,72 @@ static inline struct sfm_frag* main_get_frag(struct sfm_block* qm, int hash, } - #ifdef DBG_F_MALLOC -void* sfm_malloc(struct sfm_block* qm, unsigned long size, - const char* file, const char* func, unsigned int line) +void *sfm_malloc(struct sfm_block *qm, unsigned long size, const char *file, + const char *func, unsigned int line) #else -void* sfm_malloc(struct sfm_block* qm, unsigned long size) +void *sfm_malloc(struct sfm_block *qm, unsigned long size) #endif { - struct sfm_frag* frag; + struct sfm_frag *frag; int hash; unsigned int i; - + #ifdef DBG_F_MALLOC MDBG("sfm_malloc(%p, %lu) called from %s: %s(%d)\n", qm, size, file, func, line); #endif /*size must be a multiple of 8*/ - size=ROUNDUP(size); -/* if (size>(qm->size-qm->real_used)) return 0; */ + size = ROUNDUP(size); + /* if (size>(qm->size-qm->real_used)) return 0; */ /* check if our pool id is set */ sfm_fix_pool_id(qm); - + /*search for a suitable free frag*/ - if (likely(size<=SF_POOL_MAX_SIZE)){ - hash=GET_SMALL_HASH(size); + if(likely(size <= SF_POOL_MAX_SIZE)) { + hash = GET_SMALL_HASH(size); /* try first in our pool */ #ifdef DBG_F_MALLOC - if (likely((frag=pool_get_frag(qm, &qm->pool[pool_id], hash, size, - file, func, line))!=0)) + if(likely((frag = pool_get_frag(qm, &qm->pool[pool_id], hash, size, + file, func, line)) + != 0)) goto found; /* try in the "main" free hash, go through all the hash */ - if (likely((frag=main_get_frag(qm, hash, size, file, func, line))!=0)) + if(likely((frag = main_get_frag(qm, hash, size, file, func, line)) + != 0)) goto found; /* really low mem , try in other pools */ - for (i=(pool_id+1); i< (pool_id+SFM_POOLS_NO); i++){ - if ((frag=pool_get_frag(qm, &qm->pool[i%SFM_POOLS_NO], hash, size, - file, func, line))!=0) + for(i = (pool_id + 1); i < (pool_id + SFM_POOLS_NO); i++) { + if((frag = pool_get_frag(qm, &qm->pool[i % SFM_POOLS_NO], hash, + size, file, func, line)) + != 0) goto found; } #else - if (likely((frag=pool_get_frag(qm, &qm->pool[pool_id], hash, size)) - !=0 )) + if(likely((frag = pool_get_frag(qm, &qm->pool[pool_id], hash, size)) + != 0)) goto found; /* try in the "main" free hash, go through all the hash */ - if (likely((frag=main_get_frag(qm, hash, size))!=0)) + if(likely((frag = main_get_frag(qm, hash, size)) != 0)) goto found; /* really low mem , try in other pools */ - for (i=(pool_id+1); i< (pool_id+SFM_POOLS_NO); i++){ - if ((frag=pool_get_frag(qm, &qm->pool[i%SFM_POOLS_NO], hash, size)) - !=0 ) + for(i = (pool_id + 1); i < (pool_id + SFM_POOLS_NO); i++) { + if((frag = pool_get_frag( + qm, &qm->pool[i % SFM_POOLS_NO], hash, size)) + != 0) goto found; } #endif /* not found, bad! */ return 0; - }else{ - hash=GET_BIG_HASH(size); + } else { + hash = GET_BIG_HASH(size); #ifdef DBG_F_MALLOC - if ((frag=main_get_frag(qm, hash, size, file, func, line))==0) + if((frag = main_get_frag(qm, hash, size, file, func, line)) == 0) return 0; /* not found, bad! */ #else - if ((frag=main_get_frag(qm, hash, size))==0) + if((frag = main_get_frag(qm, hash, size)) == 0) return 0; /* not found, bad! */ #endif } @@ -698,60 +706,60 @@ void* sfm_malloc(struct sfm_block* qm, unsigned long size) found: /* we found it!*/ #ifdef DBG_F_MALLOC - frag->file=file; - frag->func=func; - frag->line=line; - frag->check=ST_CHECK_PATTERN; + frag->file = file; + frag->func = func; + frag->line = line; + frag->check = ST_CHECK_PATTERN; MDBG("sfm_malloc(%p, %lu) returns address %p \n", qm, size, - (char*)frag+sizeof(struct sfm_frag)); + (char *)frag + sizeof(struct sfm_frag)); #endif FRAG_MARK_USED(frag); /* mark it as used */ - return (char*)frag+sizeof(struct sfm_frag); + return (char *)frag + sizeof(struct sfm_frag); } - #ifdef DBG_F_MALLOC -void sfm_free(struct sfm_block* qm, void* p, const char* file, - const char* func, unsigned int line) +void sfm_free(struct sfm_block *qm, void *p, const char *file, const char *func, + unsigned int line) #else -void sfm_free(struct sfm_block* qm, void* p) +void sfm_free(struct sfm_block *qm, void *p) #endif { - struct sfm_frag* f; + struct sfm_frag *f; #ifdef DBG_F_MALLOC - MDBG("sfm_free(%p, %p), called from %s: %s(%d)\n", qm, p, file, func, - line); - if (p>(void*)qm->last_frag || p<(void*)qm->first_frag){ - LOG(L_CRIT, "BUG: sfm_free: bad pointer %p (out of memory block!) - " - "aborting\n", p); + MDBG("sfm_free(%p, %p), called from %s: %s(%d)\n", qm, p, file, func, line); + if(p > (void *)qm->last_frag || p < (void *)qm->first_frag) { + LOG(L_CRIT, + "BUG: sfm_free: bad pointer %p (out of memory block!) - " + "aborting\n", + p); abort(); } #endif - if (unlikely(p==0)) { + if(unlikely(p == 0)) { LOG(L_WARN, "WARNING: sfm_free: free(0) called\n"); return; } - f=(struct sfm_frag*) ((char*)p-sizeof(struct sfm_frag)); + f = (struct sfm_frag *)((char *)p - sizeof(struct sfm_frag)); #ifdef DBG_F_MALLOC - MDBG("sfm_free: freeing block alloc'ed from %s: %s(%ld)\n", - f->file, f->func, f->line); + MDBG("sfm_free: freeing block alloc'ed from %s: %s(%ld)\n", f->file, + f->func, f->line); #endif #ifdef DBG_F_MALLOC - f->file=file; - f->func=func; - f->line=line; + f->file = file; + f->func = func; + f->line = line; #endif sfm_insert_free(qm, f, 0); } #ifdef DBG_F_MALLOC -void* sfm_realloc(struct sfm_block* qm, void* p, unsigned long size, - const char* file, const char* func, unsigned int line) +void *sfm_realloc(struct sfm_block *qm, void *p, unsigned long size, + const char *file, const char *func, unsigned int line) #else -void* sfm_realloc(struct sfm_block* qm, void* p, unsigned long size) +void *sfm_realloc(struct sfm_block *qm, void *p, unsigned long size) #endif { struct sfm_frag *f; @@ -764,20 +772,22 @@ void* sfm_realloc(struct sfm_block* qm, void* p, unsigned long size) unsigned long p_id; int hash; unsigned long n_size; - struct sfm_pool * pool; + struct sfm_pool *pool; #endif - + #ifdef DBG_F_MALLOC - MDBG("sfm_realloc(%p, %p, %lu) called from %s: %s(%d)\n", qm, p, size, - file, func, line); - if ((p)&&(p>(void*)qm->last_frag || p<(void*)qm->first_frag)){ - LOG(L_CRIT, "BUG: sfm_free: bad pointer %p (out of memory block!) - " - "aborting\n", p); + MDBG("sfm_realloc(%p, %p, %lu) called from %s: %s(%d)\n", qm, p, size, file, + func, line); + if((p) && (p > (void *)qm->last_frag || p < (void *)qm->first_frag)) { + LOG(L_CRIT, + "BUG: sfm_free: bad pointer %p (out of memory block!) - " + "aborting\n", + p); abort(); } #endif - if (size==0) { - if (p) + if(size == 0) { + if(p) #ifdef DBG_F_MALLOC sfm_free(qm, p, file, func, line); #else @@ -785,20 +795,20 @@ void* sfm_realloc(struct sfm_block* qm, void* p, unsigned long size) #endif return 0; } - if (p==0) + if(p == 0) #ifdef DBG_F_MALLOC return sfm_malloc(qm, size, file, func, line); #else return sfm_malloc(qm, size); #endif - f=(struct sfm_frag*) ((char*)p-sizeof(struct sfm_frag)); + f = (struct sfm_frag *)((char *)p - sizeof(struct sfm_frag)); #ifdef DBG_F_MALLOC - MDBG("sfm_realloc: realloc'ing frag %p alloc'ed from %s: %s(%ld)\n", - f, f->file, f->func, f->line); + MDBG("sfm_realloc: realloc'ing frag %p alloc'ed from %s: %s(%ld)\n", f, + f->file, f->func, f->line); #endif - size=ROUNDUP(size); - orig_size=f->size; - if (f->size > size){ + size = ROUNDUP(size); + orig_size = f->size; + if(f->size > size) { /* shrink */ #ifdef DBG_F_MALLOC MDBG("sfm_realloc: shrinking from %lu to %lu\n", f->size, size); @@ -806,7 +816,7 @@ void* sfm_realloc(struct sfm_block* qm, void* p, unsigned long size) #else sfm_split_frag(qm, f, size); #endif - }else if (f->sizesize < size) { /* grow */ #ifdef DBG_F_MALLOC MDBG("sfm_realloc: growing from %lu to %lu\n", f->size, size); @@ -815,126 +825,138 @@ void* sfm_realloc(struct sfm_block* qm, void* p, unsigned long size) /* should set a magic value in list head and in push/pop if magic value => * lock and wait */ #error LL_MALLOC realloc not finished yet - diff=size-f->size; - n=FRAG_NEXT(f); - if (((char*)n < (char*)qm->last_frag) && - (n->u.nxt_free)&&((n->size+FRAG_OVERHEAD)>=diff)){ + diff = size - f->size; + n = FRAG_NEXT(f); + if(((char *)n < (char *)qm->last_frag) && (n->u.nxt_free) + && ((n->size + FRAG_OVERHEAD) >= diff)) { /* join */ /* detach n from the free list */ -try_again: - p_id=n->id; - n_size=n->size; - if ((unlikely(p_id >=SFM_POOLS_NO))){ - hash=GET_HASH(n_size); + try_again: + p_id = n->id; + n_size = n->size; + if((unlikely(p_id >= SFM_POOLS_NO))) { + hash = GET_HASH(n_size); SFM_MAIN_HASH_LOCK(qm, hash); - if (unlikely((n->u.nxt_free==0) || - ((n->size+FRAG_OVERHEAD)u.nxt_free == 0) + || ((n->size + FRAG_OVERHEAD) < diff))) { SFM_MAIN_HASH_UNLOCK(qm, hash); goto not_found; } - if (unlikely((n->id!=p_id) || (n->size!=n_size))){ - /* fragment still free, but changed, either + if(unlikely((n->id != p_id) || (n->size != n_size))) { + /* fragment still free, but changed, either * moved to another pool or has a diff. size */ SFM_MAIN_HASH_UNLOCK(qm, hash); goto try_again; } - pf=&(qm->free_hash[hash].first); + pf = &(qm->free_hash[hash].first); /* find it */ - for(;(*pf)&&(*pf!=n); pf=&((*pf)->u.nxt_free));/*FIXME slow */ - if (*pf==0){ + for(; (*pf) && (*pf != n); pf = &((*pf)->u.nxt_free)) + ; /*FIXME slow */ + if(*pf == 0) { SFM_MAIN_HASH_UNLOCK(qm, hash); /* not found, bad! */ - LOG(L_WARN, "WARNING: sfm_realloc: could not find %p in " - "free " "list (hash=%d)\n", n, hash); + LOG(L_WARN, + "WARNING: sfm_realloc: could not find %p in " + "free " + "list (hash=%d)\n", + n, hash); /* somebody is in the process of changing it ? */ goto not_found; } /* detach */ - *pf=n->u.nxt_free; - n->u.nxt_free=0; /* mark it immediately as detached */ + *pf = n->u.nxt_free; + n->u.nxt_free = 0; /* mark it immediately as detached */ qm->free_hash[hash].no--; SFM_MAIN_HASH_UNLOCK(qm, hash); /* join */ - f->size+=n->size+FRAG_OVERHEAD; + f->size += n->size + FRAG_OVERHEAD; /* split it if necessary */ - if (f->size > size){ - #ifdef DBG_F_MALLOC - sfm_split_frag(qm, f, size, file, "fragm. from " - "sfm_realloc", line); - #else + if(f->size > size) { +#ifdef DBG_F_MALLOC + sfm_split_frag(qm, f, size, file, + "fragm. from " + "sfm_realloc", + line); +#else sfm_split_frag(qm, f, size); - #endif +#endif } - }else{ /* p_id < SFM_POOLS_NO (=> in a pool )*/ - hash=GET_SMALL_HASH(n_size); - pool=&qm->pool[p_id]; + } else { /* p_id < SFM_POOLS_NO (=> in a pool )*/ + hash = GET_SMALL_HASH(n_size); + pool = &qm->pool[p_id]; SFM_POOL_LOCK(pool, hash); - if (unlikely((n->u.nxt_free==0) || - ((n->size+FRAG_OVERHEAD)u.nxt_free == 0) + || ((n->size + FRAG_OVERHEAD) < diff))) { SFM_POOL_UNLOCK(pool, hash); goto not_found; } - if (unlikely((n->id!=p_id) || (n->size!=n_size))){ - /* fragment still free, but changed, either + if(unlikely((n->id != p_id) || (n->size != n_size))) { + /* fragment still free, but changed, either * moved to another pool or has a diff. size */ SFM_POOL_UNLOCK(pool, hash); goto try_again; } - pf=&(pool->pool_hash[hash].first); + pf = &(pool->pool_hash[hash].first); /* find it */ - for(;(*pf)&&(*pf!=n); pf=&((*pf)->u.nxt_free));/*FIXME slow */ - if (*pf==0){ + for(; (*pf) && (*pf != n); pf = &((*pf)->u.nxt_free)) + ; /*FIXME slow */ + if(*pf == 0) { SFM_POOL_UNLOCK(pool, hash); /* not found, bad! */ - LOG(L_WARN, "WARNING: sfm_realloc: could not find %p in " - "free " "list (hash=%d)\n", n, hash); + LOG(L_WARN, + "WARNING: sfm_realloc: could not find %p in " + "free " + "list (hash=%d)\n", + n, hash); /* somebody is in the process of changing it ? */ goto not_found; } /* detach */ - *pf=n->u.nxt_free; - n->u.nxt_free=0; /* mark it immediately as detached */ + *pf = n->u.nxt_free; + n->u.nxt_free = 0; /* mark it immediately as detached */ pool->pool_hash[hash].no--; SFM_POOL_UNLOCK(pool, hash); /* join */ - f->size+=n->size+FRAG_OVERHEAD; + f->size += n->size + FRAG_OVERHEAD; /* split it if necessary */ - if (f->size > size){ - #ifdef DBG_F_MALLOC - sfm_split_frag(qm, f, size, file, "fragm. from " - "sfm_realloc", line); - #else + if(f->size > size) { +#ifdef DBG_F_MALLOC + sfm_split_frag(qm, f, size, file, + "fragm. from " + "sfm_realloc", + line); +#else sfm_split_frag(qm, f, size); - #endif +#endif } } - }else{ -not_found: + } else { + not_found: /* could not join => realloc */ -#else/* SFM_REALLOC_REMALLOC */ +#else /* SFM_REALLOC_REMALLOC */ { #endif /* SFM_REALLOC_REMALLOC */ - #ifdef DBG_F_MALLOC - ptr=sfm_malloc(qm, size, file, func, line); - #else - ptr=sfm_malloc(qm, size); - #endif - if (ptr){ +#ifdef DBG_F_MALLOC + ptr = sfm_malloc(qm, size, file, func, line); +#else + ptr = sfm_malloc(qm, size); +#endif + if(ptr) { /* copy, need by libssl */ memcpy(ptr, p, orig_size); - #ifdef DBG_F_MALLOC +#ifdef DBG_F_MALLOC sfm_free(qm, p, file, func, line); - #else +#else sfm_free(qm, p); - #endif +#endif } - p=ptr; + p = ptr; } - }else{ + } else { /* do nothing */ #ifdef DBG_F_MALLOC - MDBG("sfm_realloc: doing nothing, same size: %lu - %lu\n", - f->size, size); + MDBG("sfm_realloc: doing nothing, same size: %lu - %lu\n", f->size, + size); #endif } #ifdef DBG_F_MALLOC @@ -944,11 +966,10 @@ void* sfm_realloc(struct sfm_block* qm, void* p, unsigned long size) } - -void sfm_status(struct sfm_block* qm) +void sfm_status(struct sfm_block *qm) { - struct sfm_frag* f; - int i,j; + struct sfm_frag *f; + int i, j; int h; int unused; unsigned long size; @@ -958,72 +979,82 @@ void sfm_status(struct sfm_block* qm) #warning "ll_status doesn't work (might crash if used)" - memlog=cfg_get(core, core_cfg, memlog); - mem_summary=cfg_get(core, core_cfg, mem_summary); + memlog = cfg_get(core, core_cfg, memlog); + mem_summary = cfg_get(core, core_cfg, mem_summary); LOG(memlog, "sfm_status (%p):\n", qm); - if (!qm) return; + if(!qm) + return; LOG(memlog, " heap size= %ld\n", qm->size); - if (mem_summary & 16) return; + if(mem_summary & 16) + return; LOG(memlog, "dumping free list:\n"); - for(h=0,i=0,size=0;h<=sfm_max_hash;h++){ + for(h = 0, i = 0, size = 0; h <= sfm_max_hash; h++) { SFM_MAIN_HASH_LOCK(qm, h); - unused=0; - for (f=qm->free_hash[h].first,j=0; f; - size+=f->size,f=f->u.nxt_free,i++,j++){ - if (!FRAG_WAS_USED(f)){ + unused = 0; + for(f = qm->free_hash[h].first, j = 0; f; + size += f->size, f = f->u.nxt_free, i++, j++) { + if(!FRAG_WAS_USED(f)) { unused++; #ifdef DBG_F_MALLOC - LOG(memlog, "unused fragm.: hash = %3d, fragment %p," - " address %p size %lu, created from %s: %s(%ld)\n", - h, f, (char*)f+sizeof(struct sfm_frag), f->size, - f->file, f->func, f->line); + LOG(memlog, + "unused fragm.: hash = %3d, fragment %p," + " address %p size %lu, created from %s: %s(%ld)\n", + h, f, (char *)f + sizeof(struct sfm_frag), f->size, + f->file, f->func, f->line); #endif }; } - if (j) LOG(memlog, "hash = %3d fragments no.: %5d, unused: %5d\n\t\t" - " bucket size: %9lu - %9lu (first %9lu)\n", - h, j, unused, UN_HASH(h), - ((h<=SF_MALLOC_OPTIMIZE/SF_ROUNDTO)?1:2)* UN_HASH(h), - qm->free_hash[h].first->size - ); - if (j!=qm->free_hash[h].no){ - LOG(L_CRIT, "BUG: sfm_status: different free frag. count: %d!=%ld" - " for hash %3d\n", j, qm->free_hash[h].no, h); + if(j) + LOG(memlog, + "hash = %3d fragments no.: %5d, unused: %5d\n\t\t" + " bucket size: %9lu - %9lu (first %9lu)\n", + h, j, unused, UN_HASH(h), + ((h <= SF_MALLOC_OPTIMIZE / SF_ROUNDTO) ? 1 : 2) + * UN_HASH(h), + qm->free_hash[h].first->size); + if(j != qm->free_hash[h].no) { + LOG(L_CRIT, + "BUG: sfm_status: different free frag. count: %d!=%ld" + " for hash %3d\n", + j, qm->free_hash[h].no, h); } SFM_MAIN_HASH_UNLOCK(qm, h); } - for (k=0; kpool[k], h); - unused=0; - for (f=qm->pool[k].pool_hash[h].first,j=0; f; - size+=f->size,f=f->u.nxt_free,i++,j++){ - if (!FRAG_WAS_USED(f)){ + unused = 0; + for(f = qm->pool[k].pool_hash[h].first, j = 0; f; + size += f->size, f = f->u.nxt_free, i++, j++) { + if(!FRAG_WAS_USED(f)) { unused++; #ifdef DBG_F_MALLOC - LOG(memlog, "[%2d] unused fragm.: hash = %3d, fragment %p," - " address %p size %lu, created from %s: " - "%s(%ld)\n", k - h, f, (char*)f+sizeof(struct sfm_frag), - f->size, f->file, f->func, f->line); + LOG(memlog, + "[%2d] unused fragm.: hash = %3d, fragment %p," + " address %p size %lu, created from %s: " + "%s(%ld)\n", + k h, f, (char *)f + sizeof(struct sfm_frag), + f->size, f->file, f->func, f->line); #endif }; } - if (j) LOG(memlog, "[%2d] hash = %3d fragments no.: %5d, unused: " - "%5d\n\t\t bucket size: %9lu - %9lu " - "(first %9lu)\n", - k, h, j, unused, UN_HASH(h), - ((h<=SF_MALLOC_OPTIMIZE/SF_ROUNDTO)?1:2) * - UN_HASH(h), - qm->pool[k].pool_hash[h].first->size - ); - if (j!=qm->pool[k].pool_hash[h].no){ - LOG(L_CRIT, "BUG: sfm_status: [%d] different free frag." - " count: %d!=%ld for hash %3d\n", - k, j, qm->pool[k].pool_hash[h].no, h); + if(j) + LOG(memlog, + "[%2d] hash = %3d fragments no.: %5d, unused: " + "%5d\n\t\t bucket size: %9lu - %9lu " + "(first %9lu)\n", + k, h, j, unused, UN_HASH(h), + ((h <= SF_MALLOC_OPTIMIZE / SF_ROUNDTO) ? 1 : 2) + * UN_HASH(h), + qm->pool[k].pool_hash[h].first->size); + if(j != qm->pool[k].pool_hash[h].no) { + LOG(L_CRIT, + "BUG: sfm_status: [%d] different free frag." + " count: %d!=%ld for hash %3d\n", + k, j, qm->pool[k].pool_hash[h].no, h); } SFM_POOL_UNLOCK(&qm->pool[k], h); } @@ -1033,50 +1064,48 @@ void sfm_status(struct sfm_block* qm) } - /* fills a malloc info structure with info about the block * if a parameter is not supported, it will be filled with 0 */ -void sfm_info(struct sfm_block* qm, struct mem_info* info) +void sfm_info(struct sfm_block *qm, struct mem_info *info) { int r, k; unsigned long total_frags; - struct sfm_frag* f; - - memset(info,0, sizeof(*info)); - total_frags=0; - info->total_size=qm->size; - info->min_frag=SF_MIN_FRAG_SIZE; + struct sfm_frag *f; + + memset(info, 0, sizeof(*info)); + total_frags = 0; + info->total_size = qm->size; + info->min_frag = SF_MIN_FRAG_SIZE; /* we'll have to compute it all */ - for (r=0; r<=SF_MALLOC_OPTIMIZE/SF_ROUNDTO; r++){ - info->free+=qm->free_hash[r].no*UN_HASH(r); - total_frags+=qm->free_hash[r].no; + for(r = 0; r <= SF_MALLOC_OPTIMIZE / SF_ROUNDTO; r++) { + info->free += qm->free_hash[r].no * UN_HASH(r); + total_frags += qm->free_hash[r].no; } - for(;r<=sfm_max_hash; r++){ - total_frags+=qm->free_hash[r].no; + for(; r <= sfm_max_hash; r++) { + total_frags += qm->free_hash[r].no; SFM_MAIN_HASH_LOCK(qm, r); - for(f=qm->free_hash[r].first;f;f=f->u.nxt_free){ - info->free+=f->size; + for(f = qm->free_hash[r].first; f; f = f->u.nxt_free) { + info->free += f->size; } SFM_MAIN_HASH_UNLOCK(qm, r); } - for (k=0; kfree+=qm->pool[k].pool_hash[r].no*UN_HASH(r); - total_frags+=qm->pool[k].pool_hash[r].no; + for(k = 0; k < SFM_POOLS_NO; k++) { + for(r = 0; r < SF_HASH_POOL_SIZE; r++) { + info->free += qm->pool[k].pool_hash[r].no * UN_HASH(r); + total_frags += qm->pool[k].pool_hash[r].no; } } - info->real_used=info->total_size-info->free; - info->used=info->real_used-total_frags*FRAG_OVERHEAD-INIT_OVERHEAD - -FRAG_OVERHEAD; - info->max_used=0; /* we don't really know */ - info->total_frags=total_frags; + info->real_used = info->total_size - info->free; + info->used = info->real_used - total_frags * FRAG_OVERHEAD - INIT_OVERHEAD + - FRAG_OVERHEAD; + info->max_used = 0; /* we don't really know */ + info->total_frags = total_frags; } - /* returns how much free memory is available * on error (not compiled with bookkeeping code) returns (unsigned long)(-1) */ -unsigned long sfm_available(struct sfm_block* qm) +unsigned long sfm_available(struct sfm_block *qm) { /* we don't know how much free memory we have and it's too expensive * to compute it */ diff --git a/src/core/mem/ll_malloc.h b/src/core/mem/ll_malloc.h index ad366cd11bc..e58020f3e8e 100644 --- a/src/core/mem/ll_malloc.h +++ b/src/core/mem/ll_malloc.h @@ -1,5 +1,5 @@ /* - * shared memory, multi-process safe, pool based, mostly lockless version of + * shared memory, multi-process safe, pool based, mostly lockless version of * f_malloc * * This file is part of Kamailio, a free SIP server. @@ -19,7 +19,7 @@ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ -#if !defined(ll_malloc_h) +#if !defined(ll_malloc_h) #define ll_malloc_h @@ -42,63 +42,71 @@ /* tricky, on sun in 32 bits mode long long must be 64 bits aligned * but long can be 32 bits aligned => malloc should return long long * aligned memory */ - #define SF_ROUNDTO sizeof(long long) +#define SF_ROUNDTO sizeof(long long) #else - #define SF_ROUNDTO sizeof(void*) /* size we round to, must be = 2^n, and +#define SF_ROUNDTO \ + sizeof(void *) /* size we round to, must be = 2^n, and sizeof(sfm_frag) must be multiple of SF_ROUNDTO !*/ #endif #else /* DBG_SF_MALLOC */ - #define SF_ROUNDTO 8UL +#define SF_ROUNDTO 8UL #endif -#define SF_MIN_FRAG_SIZE SF_ROUNDTO +#define SF_MIN_FRAG_SIZE SF_ROUNDTO -#define SFM_POOLS_NO 4U /* the more the better, but higher initial +#define SFM_POOLS_NO \ + 4U /* the more the better, but higher initial mem. consumption */ #define SF_MALLOC_OPTIMIZE_FACTOR 14UL /*used below */ -#define SF_MALLOC_OPTIMIZE (1UL<mname; - _pkg_root.mem_pool = ap->mem_pool; - _pkg_root.mem_block = ap->mem_block; - _pkg_root.xmalloc = ap->xmalloc; - _pkg_root.xmallocxz = ap->xmallocxz; - _pkg_root.xfree = ap->xfree; - _pkg_root.xrealloc = ap->xrealloc; + _pkg_root.mname = ap->mname; + _pkg_root.mem_pool = ap->mem_pool; + _pkg_root.mem_block = ap->mem_block; + _pkg_root.xmalloc = ap->xmalloc; + _pkg_root.xmallocxz = ap->xmallocxz; + _pkg_root.xfree = ap->xfree; + _pkg_root.xrealloc = ap->xrealloc; _pkg_root.xreallocxf = ap->xreallocxf; - _pkg_root.xstatus = ap->xstatus; - _pkg_root.xinfo = ap->xinfo; - _pkg_root.xreport = ap->xreport; + _pkg_root.xstatus = ap->xstatus; + _pkg_root.xinfo = ap->xinfo; + _pkg_root.xreport = ap->xreport; _pkg_root.xavailable = ap->xavailable; - _pkg_root.xsums = ap->xsums; - _pkg_root.xdestroy = ap->xdestroy; - _pkg_root.xmodstats = ap->xmodstats; + _pkg_root.xsums = ap->xsums; + _pkg_root.xdestroy = ap->xdestroy; + _pkg_root.xmodstats = ap->xmodstats; _pkg_root.xfmodstats = ap->xfmodstats; return 0; } @@ -66,21 +66,18 @@ int pkg_init_api(sr_pkg_api_t *ap) */ int pkg_init_manager(char *name) { - if(strcmp(name, "fm")==0 - || strcmp(name, "f_malloc")==0 - || strcmp(name, "fmalloc")==0) { + if(strcmp(name, "fm") == 0 || strcmp(name, "f_malloc") == 0 + || strcmp(name, "fmalloc") == 0) { /*fast malloc*/ return fm_malloc_init_pkg_manager(); - } else if(strcmp(name, "qm")==0 - || strcmp(name, "q_malloc")==0 - || strcmp(name, "qmalloc")==0) { + } else if(strcmp(name, "qm") == 0 || strcmp(name, "q_malloc") == 0 + || strcmp(name, "qmalloc") == 0) { /*quick malloc*/ return qm_malloc_init_pkg_manager(); - } else if(strcmp(name, "tlsf")==0 - || strcmp(name, "tlsf_malloc")==0) { + } else if(strcmp(name, "tlsf") == 0 || strcmp(name, "tlsf_malloc") == 0) { /*tlsf malloc*/ return tlsf_malloc_init_pkg_manager(); - } else if(strcmp(name, "sm")==0) { + } else if(strcmp(name, "sm") == 0) { /*system malloc*/ } else { /*custom malloc - module*/ @@ -96,7 +93,7 @@ void pkg_destroy_manager(void) { if(_pkg_root.xdestroy) { LM_DBG("destroying memory manager: %s\n", - (_pkg_root.mname)?_pkg_root.mname:"unknown"); + (_pkg_root.mname) ? _pkg_root.mname : "unknown"); _pkg_root.xdestroy(); } } @@ -107,5 +104,5 @@ void pkg_destroy_manager(void) void pkg_print_manager(void) { LM_DBG("pkg - using memory manager: %s\n", - (_pkg_root.mname)?_pkg_root.mname:"unknown"); + (_pkg_root.mname) ? _pkg_root.mname : "unknown"); } diff --git a/src/core/mem/pkg.h b/src/core/mem/pkg.h index ed6b8bc73ed..9b0e5087d1d 100644 --- a/src/core/mem/pkg.h +++ b/src/core/mem/pkg.h @@ -19,7 +19,7 @@ /** * \file * \brief Main definitions for memory manager - * + * * Main definitions for PKG memory manager, like malloc, free and realloc * \ingroup mem */ @@ -41,106 +41,171 @@ void pkg_print_manager(void); #ifdef PKG_MALLOC #ifdef DBG_SR_MEMORY -# define pkg_malloc(s) _pkg_root.xmalloc(_pkg_root.mem_block, (s), \ - _SRC_LOC_, _SRC_FUNCTION_, _SRC_LINE_, _SRC_MODULE_) -# define pkg_mallocxz(s) _pkg_root.xmallocxz(_pkg_root.mem_block, (s), \ - _SRC_LOC_, _SRC_FUNCTION_, _SRC_LINE_, _SRC_MODULE_) -# define pkg_free(p) _pkg_root.xfree(_pkg_root.mem_block, (p), \ - _SRC_LOC_, _SRC_FUNCTION_, _SRC_LINE_, _SRC_MODULE_) -# define pkg_realloc(p, s) _pkg_root.xrealloc(_pkg_root.mem_block, (p), (s), \ - _SRC_LOC_, _SRC_FUNCTION_, _SRC_LINE_, _SRC_MODULE_) -# define pkg_reallocxf(p, s) _pkg_root.xreallocxf(_pkg_root.mem_block, (p), (s), \ - _SRC_LOC_, _SRC_FUNCTION_, _SRC_LINE_, _SRC_MODULE_) +#define pkg_malloc(s) \ + _pkg_root.xmalloc(_pkg_root.mem_block, (s), _SRC_LOC_, _SRC_FUNCTION_, \ + _SRC_LINE_, _SRC_MODULE_) +#define pkg_mallocxz(s) \ + _pkg_root.xmallocxz(_pkg_root.mem_block, (s), _SRC_LOC_, _SRC_FUNCTION_, \ + _SRC_LINE_, _SRC_MODULE_) +#define pkg_free(p) \ + _pkg_root.xfree(_pkg_root.mem_block, (p), _SRC_LOC_, _SRC_FUNCTION_, \ + _SRC_LINE_, _SRC_MODULE_) +#define pkg_realloc(p, s) \ + _pkg_root.xrealloc(_pkg_root.mem_block, (p), (s), _SRC_LOC_, \ + _SRC_FUNCTION_, _SRC_LINE_, _SRC_MODULE_) +#define pkg_reallocxf(p, s) \ + _pkg_root.xreallocxf(_pkg_root.mem_block, (p), (s), _SRC_LOC_, \ + _SRC_FUNCTION_, _SRC_LINE_, _SRC_MODULE_) #else -# define pkg_malloc(s) _pkg_root.xmalloc(_pkg_root.mem_block, (s)) -# define pkg_mallocxz(s) _pkg_root.xmallocxz(_pkg_root.mem_block, (s)) -# define pkg_free(p) _pkg_root.xfree(_pkg_root.mem_block, (p)) -# define pkg_realloc(p, s) _pkg_root.xrealloc(_pkg_root.mem_block, (p), (s)) -# define pkg_reallocxf(p, s) _pkg_root.xreallocxf(_pkg_root.mem_block, (p), (s)) +#define pkg_malloc(s) _pkg_root.xmalloc(_pkg_root.mem_block, (s)) +#define pkg_mallocxz(s) _pkg_root.xmallocxz(_pkg_root.mem_block, (s)) +#define pkg_free(p) _pkg_root.xfree(_pkg_root.mem_block, (p)) +#define pkg_realloc(p, s) _pkg_root.xrealloc(_pkg_root.mem_block, (p), (s)) +#define pkg_reallocxf(p, s) _pkg_root.xreallocxf(_pkg_root.mem_block, (p), (s)) #endif -# define pkg_status() _pkg_root.xstatus(_pkg_root.mem_block) -# define pkg_info(mi) _pkg_root.xinfo(_pkg_root.mem_block, mi) -# define pkg_report(mr) _pkg_root.xreport(_pkg_root.mem_block, mr) -# define pkg_available() _pkg_root.xavailable(_pkg_root.mem_block) -# define pkg_sums() _pkg_root.xsums(_pkg_root.mem_block) -# define pkg_mod_get_stats(x) _pkg_root.xmodstats(_pkg_root.mem_block, x) -# define pkg_mod_free_stats(x) _pkg_root.xfmodstats(x) +#define pkg_status() _pkg_root.xstatus(_pkg_root.mem_block) +#define pkg_info(mi) _pkg_root.xinfo(_pkg_root.mem_block, mi) +#define pkg_report(mr) _pkg_root.xreport(_pkg_root.mem_block, mr) +#define pkg_available() _pkg_root.xavailable(_pkg_root.mem_block) +#define pkg_sums() _pkg_root.xsums(_pkg_root.mem_block) +#define pkg_mod_get_stats(x) _pkg_root.xmodstats(_pkg_root.mem_block, x) +#define pkg_mod_free_stats(x) _pkg_root.xfmodstats(x) #else /*PKG_MALLOC*/ /* use system allocator */ -# define SYS_MALLOC -# include -# include "memdbg.h" -# ifdef DBG_SYS_MEMORY -# define pkg_malloc(s) \ - ( { void *____v123; ____v123=malloc((s)); \ - MDBG("malloc %p size %lu end %p (%s:%d)\n", ____v123, (unsigned long)(s), (char*)____v123+(s), __FILE__, __LINE__);\ - ____v123; } ) -# define pkg_mallocxz(s) \ - ( { void *____v123; ____v123=malloc((s)); \ - MDBG("malloc %p size %lu end %p (%s:%d)\n", ____v123, (unsigned long)(s), (char*)____v123+(s), __FILE__, __LINE__);\ - if(____v123) memset(____v123, 0, (s)); \ - ____v123; } ) -# define pkg_free(p) do{ MDBG("free %p (%s:%d)\n", (p), __FILE__, __LINE__); free((p)); }while(0) -# define pkg_realloc(p, s) \ - ( { void *____v123; ____v123=realloc(p, s); \ - MDBG("realloc %p size %lu end %p (%s:%d)\n", ____v123, (unsigned long)(s), (char*)____v123+(s), __FILE__, __LINE__);\ - ____v123; } ) -# define pkg_reallocxf(p, s) \ - ( { void *____v123; ____v123=realloc(p, s); \ - MDBG("realloc %p size %lu end %p (%s:%d)\n", ____v123, (unsigned long)(s), (char*)____v123+(s), __FILE__, __LINE__);\ - if(!____v123) free(p); \ - ____v123; } ) -# else -# define pkg_malloc(s) malloc((s)) -# define pkg_mallocxz(s) \ - ( { void *____v123; ____v123=malloc((s)); \ - if(____v123) memset(____v123, 0, (s)); \ - ____v123; } ) -# define pkg_free(p) free((p)) -# define pkg_realloc(p, s) realloc((p), (s)) -# define pkg_reallocxf(p, s) \ - ( { void *____v123; ____v123=realloc((p), (s)); \ - if(!____v123 && (p)) free(p); \ - ____v123; } ) -# endif -# define pkg_status() do{}while(0) -# define pkg_info(mi) do{ memset((mi),0, sizeof(*(mi))); } while(0) -# define pkg_report(mr) do{ memset((mr),0, sizeof(*(mr))); } while(0) -# define pkg_available() 0 -# define pkg_sums() do{}while(0) -# define pkg_mod_get_stats(x) do{}while(0) -# define pkg_mod_free_stats(x) do{}while(0) +#define SYS_MALLOC +#include +#include "memdbg.h" +#ifdef DBG_SYS_MEMORY +#define pkg_malloc(s) \ + ({ \ + void *____v123; \ + ____v123 = malloc((s)); \ + MDBG("malloc %p size %lu end %p (%s:%d)\n", ____v123, \ + (unsigned long)(s), (char *)____v123 + (s), __FILE__, \ + __LINE__); \ + ____v123; \ + }) +#define pkg_mallocxz(s) \ + ({ \ + void *____v123; \ + ____v123 = malloc((s)); \ + MDBG("malloc %p size %lu end %p (%s:%d)\n", ____v123, \ + (unsigned long)(s), (char *)____v123 + (s), __FILE__, \ + __LINE__); \ + if(____v123) \ + memset(____v123, 0, (s)); \ + ____v123; \ + }) +#define pkg_free(p) \ + do { \ + MDBG("free %p (%s:%d)\n", (p), __FILE__, __LINE__); \ + free((p)); \ + } while(0) +#define pkg_realloc(p, s) \ + ({ \ + void *____v123; \ + ____v123 = realloc(p, s); \ + MDBG("realloc %p size %lu end %p (%s:%d)\n", ____v123, \ + (unsigned long)(s), (char *)____v123 + (s), __FILE__, \ + __LINE__); \ + ____v123; \ + }) +#define pkg_reallocxf(p, s) \ + ({ \ + void *____v123; \ + ____v123 = realloc(p, s); \ + MDBG("realloc %p size %lu end %p (%s:%d)\n", ____v123, \ + (unsigned long)(s), (char *)____v123 + (s), __FILE__, \ + __LINE__); \ + if(!____v123) \ + free(p); \ + ____v123; \ + }) +#else +#define pkg_malloc(s) malloc((s)) +#define pkg_mallocxz(s) \ + ({ \ + void *____v123; \ + ____v123 = malloc((s)); \ + if(____v123) \ + memset(____v123, 0, (s)); \ + ____v123; \ + }) +#define pkg_free(p) free((p)) +#define pkg_realloc(p, s) realloc((p), (s)) +#define pkg_reallocxf(p, s) \ + ({ \ + void *____v123; \ + ____v123 = realloc((p), (s)); \ + if(!____v123 && (p)) \ + free(p); \ + ____v123; \ + }) +#endif +#define pkg_status() \ + do { \ + } while(0) +#define pkg_info(mi) \ + do { \ + memset((mi), 0, sizeof(*(mi))); \ + } while(0) +#define pkg_report(mr) \ + do { \ + memset((mr), 0, sizeof(*(mr))); \ + } while(0) +#define pkg_available() 0 +#define pkg_sums() \ + do { \ + } while(0) +#define pkg_mod_get_stats(x) \ + do { \ + } while(0) +#define pkg_mod_free_stats(x) \ + do { \ + } while(0) #endif /*PKG_MALLOC*/ /* generic logging helper for allocation errors in private system memory */ #ifdef SYS_MALLOC -#define PKG_MEM_ERROR LM_ERR("could not allocate private memory from sys pool\n") -#define PKG_MEM_CRITICAL LM_CRIT("could not allocate private memory from sys pool\n") +#define PKG_MEM_ERROR \ + LM_ERR("could not allocate private memory from sys pool\n") +#define PKG_MEM_CRITICAL \ + LM_CRIT("could not allocate private memory from sys pool\n") #ifdef __SUNPRO_C -#define PKG_MEM_ERROR_FMT(...) LM_ERR("could not allocate private memory from sys pool" __VA_ARGS__) -#define PKG_MEM_CRITICAL_FMT(...) LM_CRIT("could not allocate private memory from sys pool" __VA_ARGS__) +#define PKG_MEM_ERROR_FMT(...) \ + LM_ERR("could not allocate private memory from sys pool" __VA_ARGS__) +#define PKG_MEM_CRITICAL_FMT(...) \ + LM_CRIT("could not allocate private memory from sys pool" __VA_ARGS__) #else -#define PKG_MEM_ERROR_FMT(fmt, args...) LM_ERR("could not allocate private memory from sys pool - " fmt , ## args) -#define PKG_MEM_CRITICAL_FMT(fmt, args...) LM_CRIT("could not allocate private memory from sys pool - " fmt , ## args) +#define PKG_MEM_ERROR_FMT(fmt, args...) \ + LM_ERR("could not allocate private memory from sys pool - " fmt, ##args) +#define PKG_MEM_CRITICAL_FMT(fmt, args...) \ + LM_CRIT("could not allocate private memory from sys pool - " fmt, ##args) #endif /* generic logging helper for allocation errors in private memory pool */ #else -#define PKG_MEM_ERROR LM_ERR("could not allocate private memory from pkg pool\n") -#define PKG_MEM_CRITICAL LM_CRIT("could not allocate private memory from pkg pool\n") +#define PKG_MEM_ERROR \ + LM_ERR("could not allocate private memory from pkg pool\n") +#define PKG_MEM_CRITICAL \ + LM_CRIT("could not allocate private memory from pkg pool\n") #ifdef __SUNPRO_C -#define PKG_MEM_ERROR_FMT(...) LM_ERR("could not allocate private memory from pkg pool" __VA_ARGS__) -#define PKG_MEM_CRITICAL_FMT(...) LM_CRIT("could not allocate private memory from pkg pool" __VA_ARGS__) +#define PKG_MEM_ERROR_FMT(...) \ + LM_ERR("could not allocate private memory from pkg pool" __VA_ARGS__) +#define PKG_MEM_CRITICAL_FMT(...) \ + LM_CRIT("could not allocate private memory from pkg pool" __VA_ARGS__) #else -#define PKG_MEM_ERROR_FMT(fmt, args...) LM_ERR("could not allocate private memory from pkg pool - " fmt , ## args) -#define PKG_MEM_CRITICAL_FMT(fmt, args...) LM_CRIT("could not allocate private memory from pkg pool - " fmt , ## args) +#define PKG_MEM_ERROR_FMT(fmt, args...) \ + LM_ERR("could not allocate private memory from pkg pool - " fmt, ##args) +#define PKG_MEM_CRITICAL_FMT(fmt, args...) \ + LM_CRIT("could not allocate private memory from pkg pool - " fmt, ##args) #endif #endif /* SYS_MALLOC */ @@ -151,11 +216,15 @@ void pkg_print_manager(void); #define SYS_MEM_CRITICAL LM_CRIT("could not allocate memory from system\n") #ifdef __SUNPRO_C -#define SYS_MEM_ERROR_FMT(...) LM_ERR("could not allocate memory from system" __VA_ARGS__) -#define SYS_MEM_CRITICAL_FMT(...) LM_CRIT("could not allocate memory from system" __VA_ARGS__) +#define SYS_MEM_ERROR_FMT(...) \ + LM_ERR("could not allocate memory from system" __VA_ARGS__) +#define SYS_MEM_CRITICAL_FMT(...) \ + LM_CRIT("could not allocate memory from system" __VA_ARGS__) #else -#define SYS_MEM_ERROR_FMT(fmt, args...) LM_ERR("could not allocate memory from system - " fmt , ## args) -#define SYS_MEM_CRITICAL_FMT(fmt, args...) LM_CRIT("could not allocate memory from system - " fmt , ## args) +#define SYS_MEM_ERROR_FMT(fmt, args...) \ + LM_ERR("could not allocate memory from system - " fmt, ##args) +#define SYS_MEM_CRITICAL_FMT(fmt, args...) \ + LM_CRIT("could not allocate memory from system - " fmt, ##args) #endif #endif /* _sr_pkg_h_ */ diff --git a/src/core/mem/q_malloc.c b/src/core/mem/q_malloc.c index ba64f008547..a3b9161ca3b 100644 --- a/src/core/mem/q_malloc.c +++ b/src/core/mem/q_malloc.c @@ -40,49 +40,51 @@ #include "pkg.h" /*useful macros*/ -#define FRAG_END(f) \ - ((struct qm_frag_end*)((char*)(f)+sizeof(struct qm_frag)+ \ - (f)->size)) +#define FRAG_END(f) \ + ((struct qm_frag_end *)((char *)(f) + sizeof(struct qm_frag) + (f)->size)) -#define FRAG_NEXT(f) \ - ((struct qm_frag*)((char*)(f)+sizeof(struct qm_frag)+(f)->size+ \ - sizeof(struct qm_frag_end))) +#define FRAG_NEXT(f) \ + ((struct qm_frag *)((char *)(f) + sizeof(struct qm_frag) + (f)->size \ + + sizeof(struct qm_frag_end))) -#define FRAG_PREV(f) \ - ( (struct qm_frag*) ( ((char*)(f)-sizeof(struct qm_frag_end))- \ - ((struct qm_frag_end*)((char*)(f)-sizeof(struct qm_frag_end)))->size- \ - sizeof(struct qm_frag) ) ) +#define FRAG_PREV(f) \ + ((struct qm_frag *)(((char *)(f) - sizeof(struct qm_frag_end)) \ + - ((struct qm_frag_end \ + *)((char *)(f) \ + - sizeof(struct qm_frag_end))) \ + ->size \ + - sizeof(struct qm_frag))) #define PREV_FRAG_END(f) \ - ((struct qm_frag_end*)((char*)(f)-sizeof(struct qm_frag_end))) + ((struct qm_frag_end *)((char *)(f) - sizeof(struct qm_frag_end))) -#define FRAG_OVERHEAD (sizeof(struct qm_frag)+sizeof(struct qm_frag_end)) +#define FRAG_OVERHEAD (sizeof(struct qm_frag) + sizeof(struct qm_frag_end)) -#define ROUNDTO_MASK (~((unsigned long)ROUNDTO-1)) -#define ROUNDUP(s) (((s)+(ROUNDTO-1))&ROUNDTO_MASK) -#define ROUNDDOWN(s) ((s)&ROUNDTO_MASK) +#define ROUNDTO_MASK (~((unsigned long)ROUNDTO - 1)) +#define ROUNDUP(s) (((s) + (ROUNDTO - 1)) & ROUNDTO_MASK) +#define ROUNDDOWN(s) ((s)&ROUNDTO_MASK) +/* finds the hash value for s, s=ROUNDTO multiple*/ +#define GET_HASH(s) \ + (((unsigned long)(s) <= QM_MALLOC_OPTIMIZE) \ + ? (unsigned long)(s) / ROUNDTO \ + : QM_MALLOC_OPTIMIZE / ROUNDTO + big_hash_idx((s)) \ + - QM_MALLOC_OPTIMIZE_FACTOR + 1) - /* finds the hash value for s, s=ROUNDTO multiple*/ -#define GET_HASH(s) ( ((unsigned long)(s)<=QM_MALLOC_OPTIMIZE)?\ - (unsigned long)(s)/ROUNDTO: \ - QM_MALLOC_OPTIMIZE/ROUNDTO+big_hash_idx((s))- \ - QM_MALLOC_OPTIMIZE_FACTOR+1 ) - -#define UN_HASH(h) ( ((unsigned long)(h)<=(QM_MALLOC_OPTIMIZE/ROUNDTO))?\ - (unsigned long)(h)*ROUNDTO: \ - 1UL<<((h)-QM_MALLOC_OPTIMIZE/ROUNDTO+\ - QM_MALLOC_OPTIMIZE_FACTOR-1)\ - ) +#define UN_HASH(h) \ + (((unsigned long)(h) <= (QM_MALLOC_OPTIMIZE / ROUNDTO)) \ + ? (unsigned long)(h)*ROUNDTO \ + : 1UL << ((h)-QM_MALLOC_OPTIMIZE / ROUNDTO \ + + QM_MALLOC_OPTIMIZE_FACTOR - 1)) /* mark/test used/unused frags */ #define FRAG_MARK_USED(f) #define FRAG_CLEAR_USED(f) -#define FRAG_WAS_USED(f) (1) +#define FRAG_WAS_USED(f) (1) /* other frag related defines: * MEM_COALESCE_FRAGS @@ -100,59 +102,60 @@ inline static unsigned long big_hash_idx(unsigned long s) * index= i such that 2^i > s >= 2^(i-1) * * => index = number of the first non null bit in s*/ - idx=sizeof(long)*8-1; - for (; !(s&(1UL<<(sizeof(long)*8-1))) ; s<<=1, idx--); + idx = sizeof(long) * 8 - 1; + for(; !(s & (1UL << (sizeof(long) * 8 - 1))); s <<= 1, idx--) + ; return idx; } #ifdef DBG_QM_MALLOC -#define ST_CHECK_PATTERN 0xf0f0f0f0 +#define ST_CHECK_PATTERN 0xf0f0f0f0 #define END_CHECK_PATTERN1 0xc0c0c0c0 #define END_CHECK_PATTERN2 0xabcdefed -#define qm_debug_frag(qm, f, file, line) \ - qm_debug_check_frag((qm), (f), (file), (line), __FILE__, __LINE__) -static void qm_debug_check_frag(struct qm_block* qm, struct qm_frag* f, - const char* file, unsigned int line, - const char* efile, unsigned int eline) +#define qm_debug_frag(qm, f, file, line) \ + qm_debug_check_frag((qm), (f), (file), (line), __FILE__, __LINE__) +static void qm_debug_check_frag(struct qm_block *qm, struct qm_frag *f, + const char *file, unsigned int line, const char *efile, + unsigned int eline) { struct qm_frag *p; - if (f->check!=ST_CHECK_PATTERN){ + if(f->check != ST_CHECK_PATTERN) { LM_CRIT("BUG: qm: fragm. %p (address %p) " "beginning overwritten (%lx)! Memory allocator was called " "from %s:%u. Fragment marked by %s:%lu. Exec from %s:%u.\n", - f, (char*)f+sizeof(struct qm_frag), - f->check, file, line, f->file, f->line, efile, eline); + f, (char *)f + sizeof(struct qm_frag), f->check, file, line, + f->file, f->line, efile, eline); qm_status(qm); abort(); }; - if ((FRAG_END(f)->check1!=END_CHECK_PATTERN1)|| - (FRAG_END(f)->check2!=END_CHECK_PATTERN2)){ + if((FRAG_END(f)->check1 != END_CHECK_PATTERN1) + || (FRAG_END(f)->check2 != END_CHECK_PATTERN2)) { LM_CRIT("BUG: qm: fragm. %p (address %p) " "end overwritten (%lx, %lx)! Memory allocator was called " "from %s:%u. Fragment marked by %s:%lu. Exec from %s:%u.\n", - f, (char*)f+sizeof(struct qm_frag), - FRAG_END(f)->check1, FRAG_END(f)->check2, - file, line, f->file, f->line, efile, eline); + f, (char *)f + sizeof(struct qm_frag), FRAG_END(f)->check1, + FRAG_END(f)->check2, file, line, f->file, f->line, efile, + eline); qm_status(qm); abort(); } - if ((f>qm->first_frag)&& - ((PREV_FRAG_END(f)->check1!=END_CHECK_PATTERN1) || - (PREV_FRAG_END(f)->check2!=END_CHECK_PATTERN2) ) ){ + if((f > qm->first_frag) + && ((PREV_FRAG_END(f)->check1 != END_CHECK_PATTERN1) + || (PREV_FRAG_END(f)->check2 != END_CHECK_PATTERN2))) { LM_CRIT("BUG: qm: prev. fragm. tail overwritten(%lx, %lx)[%p:%p]! " "Memory allocator was called from %s:%u. Fragment marked by " "%s:%lu. Exec from %s:%u.\n", PREV_FRAG_END(f)->check1, PREV_FRAG_END(f)->check2, f, - (char*)f+sizeof(struct qm_frag), file, line, f->file, f->line, - efile, eline); - if(PREV_FRAG_END(f)->check2==END_CHECK_PATTERN2) { + (char *)f + sizeof(struct qm_frag), file, line, f->file, + f->line, efile, eline); + if(PREV_FRAG_END(f)->check2 == END_CHECK_PATTERN2) { p = FRAG_PREV(f); LM_CRIT("BUG: qm: prev. fragm. tail overwritten [%p:%p]" - " - fragment marked by %s:%lu\n", p, - (char*)p+sizeof(struct qm_frag), p->file, p->line); + " - fragment marked by %s:%lu\n", + p, (char *)p + sizeof(struct qm_frag), p->file, p->line); } qm_status(qm); abort(); @@ -161,90 +164,93 @@ static void qm_debug_check_frag(struct qm_block* qm, struct qm_frag* f, #endif - -static inline void qm_insert_free(struct qm_block* qm, struct qm_frag* frag) +static inline void qm_insert_free(struct qm_block *qm, struct qm_frag *frag) { - struct qm_frag* f; - struct qm_frag* prev; + struct qm_frag *f; + struct qm_frag *prev; int hash; - hash=GET_HASH(frag->size); - for(f=qm->free_hash[hash].head.u.nxt_free; f!=&(qm->free_hash[hash].head); - f=f->u.nxt_free){ - if (frag->size <= f->size) break; + hash = GET_HASH(frag->size); + for(f = qm->free_hash[hash].head.u.nxt_free; + f != &(qm->free_hash[hash].head); f = f->u.nxt_free) { + if(frag->size <= f->size) + break; } /*insert it here*/ - prev=FRAG_END(f)->prev_free; - prev->u.nxt_free=frag; - FRAG_END(frag)->prev_free=prev; - frag->u.nxt_free=f; - FRAG_END(f)->prev_free=frag; + prev = FRAG_END(f)->prev_free; + prev->u.nxt_free = frag; + FRAG_END(frag)->prev_free = prev; + frag->u.nxt_free = f; + FRAG_END(f)->prev_free = frag; qm->free_hash[hash].no++; qm->ffrags++; } - /* init malloc and return a qm_block*/ -struct qm_block* qm_malloc_init(char* address, unsigned long size, int type) +struct qm_block *qm_malloc_init(char *address, unsigned long size, int type) { - char* start; - char* end; - struct qm_block* qm; + char *start; + char *end; + struct qm_block *qm; unsigned long init_overhead; int h; /* make address and size multiple of 8*/ - start=(char*)ROUNDUP((unsigned long) address); - LM_DBG("QM_OPTIMIZE=%lu, /ROUNDTO=%lu\n", - QM_MALLOC_OPTIMIZE, QM_MALLOC_OPTIMIZE/ROUNDTO); - LM_DBG("QM_HASH_SIZE=%lu, qm_block size=%lu\n", - QM_HASH_SIZE, (unsigned long)sizeof(struct qm_block)); - LM_DBG("qm_malloc_init(%p, %lu), start=%p\n", address, - (unsigned long)size, start); - if (sizesize=size; - qm->real_used=init_overhead; - qm->max_real_used=qm->real_used; - qm->type=type; - size-=init_overhead; - - qm->first_frag=(struct qm_frag*)(start+ROUNDUP(sizeof(struct qm_block))); - qm->last_frag_end=(struct qm_frag_end*)(end-sizeof(struct qm_frag_end)); + qm->size = size; + qm->real_used = init_overhead; + qm->max_real_used = qm->real_used; + qm->type = type; + size -= init_overhead; + + qm->first_frag = + (struct qm_frag *)(start + ROUNDUP(sizeof(struct qm_block))); + qm->last_frag_end = + (struct qm_frag_end *)(end - sizeof(struct qm_frag_end)); /* init initial fragment*/ - qm->first_frag->size=size; - qm->last_frag_end->size=size; + qm->first_frag->size = size; + qm->last_frag_end->size = size; #ifdef DBG_QM_MALLOC - qm->first_frag->check=ST_CHECK_PATTERN; - qm->last_frag_end->check1=END_CHECK_PATTERN1; - qm->last_frag_end->check2=END_CHECK_PATTERN2; + qm->first_frag->check = ST_CHECK_PATTERN; + qm->last_frag_end->check1 = END_CHECK_PATTERN1; + qm->last_frag_end->check2 = END_CHECK_PATTERN2; #endif /* init free_hash* */ - for (h=0; hfree_hash[h].head.u.nxt_free=&(qm->free_hash[h].head); - qm->free_hash[h].tail.prev_free=&(qm->free_hash[h].head); - qm->free_hash[h].head.size=0; - qm->free_hash[h].tail.size=0; + for(h = 0; h < QM_HASH_SIZE; h++) { + qm->free_hash[h].head.u.nxt_free = &(qm->free_hash[h].head); + qm->free_hash[h].tail.prev_free = &(qm->free_hash[h].head); + qm->free_hash[h].head.size = 0; + qm->free_hash[h].tail.size = 0; } /* link initial fragment into the free list*/ @@ -260,42 +266,45 @@ struct qm_block* qm_malloc_init(char* address, unsigned long size, int type) } -static inline void qm_detach_free(struct qm_block* qm, struct qm_frag* frag) +static inline void qm_detach_free(struct qm_block *qm, struct qm_frag *frag) { struct qm_frag *prev; struct qm_frag *next; - prev=FRAG_END(frag)->prev_free; - next=frag->u.nxt_free; - prev->u.nxt_free=next; - FRAG_END(next)->prev_free=prev; + prev = FRAG_END(frag)->prev_free; + next = frag->u.nxt_free; + prev->u.nxt_free = next; + FRAG_END(next)->prev_free = prev; } #ifdef DBG_QM_MALLOC -static inline struct qm_frag* qm_find_free(struct qm_block* qm, - size_t size, int *h, unsigned int *count) +static inline struct qm_frag *qm_find_free( + struct qm_block *qm, size_t size, int *h, unsigned int *count) #else -static inline struct qm_frag* qm_find_free(struct qm_block* qm, - size_t size, int* h) +static inline struct qm_frag *qm_find_free( + struct qm_block *qm, size_t size, int *h) #endif { int hash; - struct qm_frag* f; + struct qm_frag *f; - for (hash=GET_HASH(size); hashfree_hash[hash].head.u.nxt_free; - f!=&(qm->free_hash[hash].head); f=f->u.nxt_free){ + for(hash = GET_HASH(size); hash < QM_HASH_SIZE; hash++) { + for(f = qm->free_hash[hash].head.u.nxt_free; + f != &(qm->free_hash[hash].head); f = f->u.nxt_free) { #ifdef DBG_QM_MALLOC - *count+=1; /* *count++ generates a warning with gcc 2.9* -Wall */ + *count += 1; /* *count++ generates a warning with gcc 2.9* -Wall */ #endif - if (f->size>=size){ *h=hash; return f; } + if(f->size >= size) { + *h = hash; + return f; + } } - /*try in a bigger bucket*/ + /*try in a bigger bucket*/ } /* not found */ - LM_ERR("qm_find_free(%p, %lu); Free fragment not found!\n", - qm, (unsigned long)size); + LM_ERR("qm_find_free(%p, %lu); Free fragment not found!\n", qm, + (unsigned long)size); return 0; } @@ -304,95 +313,99 @@ static inline struct qm_frag* qm_find_free(struct qm_block* qm, * new_size < size & rounded-up already!*/ static inline #ifdef DBG_QM_MALLOC -int split_frag(struct qm_block* qm, struct qm_frag* f, size_t new_size, - const char* file, const char* func, unsigned int line, const char *mname) + int + split_frag(struct qm_block *qm, struct qm_frag *f, size_t new_size, + const char *file, const char *func, unsigned int line, + const char *mname) #else -int split_frag(struct qm_block* qm, struct qm_frag* f, size_t new_size) + int + split_frag(struct qm_block *qm, struct qm_frag *f, size_t new_size) #endif { size_t rest; - struct qm_frag* n; - struct qm_frag_end* end; + struct qm_frag *n; + struct qm_frag_end *end; - rest=f->size-new_size; + rest = f->size - new_size; #ifdef MEM_FRAG_AVOIDANCE - if ((rest> (FRAG_OVERHEAD+QM_MALLOC_OPTIMIZE))|| - (rest>=(FRAG_OVERHEAD+new_size))){/* the residue fragm. is big enough*/ + if((rest > (FRAG_OVERHEAD + QM_MALLOC_OPTIMIZE)) + || (rest >= (FRAG_OVERHEAD + + new_size))) { /* the residue fragm. is big enough*/ #else - if (rest>(FRAG_OVERHEAD+MIN_FRAG_SIZE)){ + if(rest > (FRAG_OVERHEAD + MIN_FRAG_SIZE)) { #endif - f->size=new_size; + f->size = new_size; /*split the fragment*/ - end=FRAG_END(f); - end->size=new_size; - n=(struct qm_frag*)((char*)end+sizeof(struct qm_frag_end)); - n->size=rest-FRAG_OVERHEAD; - FRAG_END(n)->size=n->size; + end = FRAG_END(f); + end->size = new_size; + n = (struct qm_frag *)((char *)end + sizeof(struct qm_frag_end)); + n->size = rest - FRAG_OVERHEAD; + FRAG_END(n)->size = n->size; FRAG_CLEAR_USED(n); /* never used */ - qm->real_used+=FRAG_OVERHEAD; + qm->real_used += FRAG_OVERHEAD; #ifdef DBG_QM_MALLOC - end->check1=END_CHECK_PATTERN1; - end->check2=END_CHECK_PATTERN2; + end->check1 = END_CHECK_PATTERN1; + end->check2 = END_CHECK_PATTERN2; /* frag created by malloc, mark it*/ - n->file=file; - n->func=func; - n->line=line; - n->mname=mname; - n->check=ST_CHECK_PATTERN; + n->file = file; + n->func = func; + n->line = line; + n->mname = mname; + n->check = ST_CHECK_PATTERN; #endif /* reinsert n in free list*/ qm_insert_free(qm, n); return 0; - }else{ - /* we cannot split this fragment any more */ + } else { + /* we cannot split this fragment any more */ return -1; } } - #ifdef DBG_QM_MALLOC -void* qm_malloc(void* qmp, size_t size, - const char* file, const char* func, unsigned int line, - const char *mname) +void *qm_malloc(void *qmp, size_t size, const char *file, const char *func, + unsigned int line, const char *mname) #else -void* qm_malloc(void* qmp, size_t size) +void *qm_malloc(void *qmp, size_t size) #endif { - struct qm_block* qm; - struct qm_frag* f; + struct qm_block *qm; + struct qm_frag *f; int hash; #ifdef DBG_QM_MALLOC unsigned int list_cntr; #endif - qm = (struct qm_block*)qmp; + qm = (struct qm_block *)qmp; #ifdef DBG_QM_MALLOC list_cntr = 0; - MDBG("qm_malloc(%p, %lu) called from %s: %s(%d)\n", - qm, (unsigned long)size, file, func, line); + MDBG("qm_malloc(%p, %lu) called from %s: %s(%d)\n", qm, (unsigned long)size, + file, func, line); #endif /*malloc(0) should return a valid pointer according to specs*/ - if(unlikely(size==0)) size=4; + if(unlikely(size == 0)) + size = 4; /*size must be a multiple of 8*/ - size=ROUNDUP(size); - if (size>(qm->size-qm->real_used)) return 0; + size = ROUNDUP(size); + if(size > (qm->size - qm->real_used)) + return 0; - /*search for a suitable free frag*/ + /*search for a suitable free frag*/ #ifdef DBG_QM_MALLOC - if ((f=qm_find_free(qm, size, &hash, &list_cntr))!=0){ + if((f = qm_find_free(qm, size, &hash, &list_cntr)) != 0) { #else - if ((f=qm_find_free(qm, size, &hash))!=0){ + if((f = qm_find_free(qm, size, &hash)) != 0) { #endif /* we found it!*/ /*detach it from the free list*/ #ifdef DBG_QM_MALLOC - qm_debug_frag(qm, f, file, line); + qm_debug_frag(qm, f, file, line); #endif qm_detach_free(qm, f); /*mark it as "busy"*/ - f->u.is_free=0; + f->u.is_free = 0; qm->free_hash[hash].no--; qm->ffrags--; /* we ignore split return */ @@ -401,38 +414,38 @@ void* qm_malloc(void* qmp, size_t size) #else split_frag(qm, f, size); #endif - qm->real_used+=f->size; - qm->used+=f->size; - if (qm->max_real_usedreal_used) - qm->max_real_used=qm->real_used; + qm->real_used += f->size; + qm->used += f->size; + if(qm->max_real_used < qm->real_used) + qm->max_real_used = qm->real_used; #ifdef DBG_QM_MALLOC - f->file=file; - f->func=func; - f->mname=mname; - f->line=line; - f->check=ST_CHECK_PATTERN; + f->file = file; + f->func = func; + f->mname = mname; + f->line = line; + f->check = ST_CHECK_PATTERN; /* FRAG_END(f)->check1=END_CHECK_PATTERN1; FRAG_END(f)->check2=END_CHECK_PATTERN2;*/ MDBG("qm_malloc(%p, %lu) returns address %p frag. %p (size=%lu) on %d" - " -th hit\n", - qm, (unsigned long)size, (char*)f+sizeof(struct qm_frag), f, + " -th hit\n", + qm, (unsigned long)size, (char *)f + sizeof(struct qm_frag), f, f->size, list_cntr); #endif #ifdef MALLOC_STATS - if(qm->type==MEM_TYPE_PKG) { + if(qm->type == MEM_TYPE_PKG) { sr_event_exec(SREV_PKG_UPDATE_STATS, 0); } #endif - return (char*)f+sizeof(struct qm_frag); + return (char *)f + sizeof(struct qm_frag); } #ifdef DBG_QM_MALLOC LM_ERR("qm_malloc(%p, %lu) called from %s: %s(%d), module: %s;" - " Free fragment not found!\n", + " Free fragment not found!\n", qm, (unsigned long)size, file, func, line, mname); #else - LM_ERR("qm_malloc(%p, %lu); Free fragment not found!\n", - qm, (unsigned long)size); + LM_ERR("qm_malloc(%p, %lu); Free fragment not found!\n", qm, + (unsigned long)size); #endif return 0; @@ -440,11 +453,10 @@ void* qm_malloc(void* qmp, size_t size) #ifdef DBG_QM_MALLOC -void* qm_mallocxz(void* qmp, size_t size, - const char* file, const char* func, unsigned int line, - const char *mname) +void *qm_mallocxz(void *qmp, size_t size, const char *file, const char *func, + unsigned int line, const char *mname) #else -void* qm_mallocxz(void* qmp, size_t size) +void *qm_mallocxz(void *qmp, size_t size) #endif { void *p; @@ -455,34 +467,35 @@ void* qm_mallocxz(void* qmp, size_t size) p = qm_malloc(qmp, size); #endif - if(p) memset(p, 0, size); + if(p) + memset(p, 0, size); return p; } #ifdef DBG_QM_MALLOC -void qm_free(void* qmp, void* p, const char* file, const char* func, - unsigned int line, const char *mname) +void qm_free(void *qmp, void *p, const char *file, const char *func, + unsigned int line, const char *mname) #else -void qm_free(void* qmp, void* p) +void qm_free(void *qmp, void *p) #endif { - struct qm_block* qm; - struct qm_frag* f; + struct qm_block *qm; + struct qm_frag *f; size_t size; #ifdef MEM_JOIN_FREE - struct qm_frag* next; - struct qm_frag* prev; + struct qm_frag *next; + struct qm_frag *prev; #endif /* MEM_JOIN_FREE*/ - qm = (struct qm_block*)qmp; + qm = (struct qm_block *)qmp; #ifdef DBG_QM_MALLOC MDBG("qm_free(%p, %p), called from %s: %s(%d)\n", qm, p, file, func, line); #endif - if (p==0) { + if(p == 0) { #ifdef DBG_QM_MALLOC LM_WARN("WARNING: free(0) called from %s: %s(%d)\n", file, func, line); #else @@ -492,138 +505,139 @@ void qm_free(void* qmp, void* p) } #ifdef DBG_QM_MALLOC - if (p>(void*)qm->last_frag_end || p<(void*)qm->first_frag){ - if(likely(cfg_get(core, core_cfg, mem_safety)==0)) { + if(p > (void *)qm->last_frag_end || p < (void *)qm->first_frag) { + if(likely(cfg_get(core, core_cfg, mem_safety) == 0)) { LM_CRIT("BUG: bad pointer %p (out of memory block!)" - " called from %s: %s(%d) - aborting\n", p, file, func, line); + " called from %s: %s(%d) - aborting\n", + p, file, func, line); abort(); } else { LM_CRIT("BUG: bad pointer %p (out of memory block!)" - " called from %s: %s(%d) - ignoring\n", p, file, func, line); + " called from %s: %s(%d) - ignoring\n", + p, file, func, line); return; } } #endif - f=(struct qm_frag*) ((char*)p-sizeof(struct qm_frag)); + f = (struct qm_frag *)((char *)p - sizeof(struct qm_frag)); #ifdef DBG_QM_MALLOC qm_debug_frag(qm, f, file, line); - if (unlikely(f->u.is_free)){ - if(likely(cfg_get(core, core_cfg, mem_safety)==0)) { + if(unlikely(f->u.is_free)) { + if(likely(cfg_get(core, core_cfg, mem_safety) == 0)) { LM_CRIT("BUG: freeing already freed pointer (%p)," - " called from %s: %s(%d), first free %s: %s(%ld) - aborting\n", - p, file, func, line, f->file, f->func, f->line); + " called from %s: %s(%d), first free %s: %s(%ld) - " + "aborting\n", + p, file, func, line, f->file, f->func, f->line); abort(); } else { LM_CRIT("BUG: freeing already freed pointer (%p)," - " called from %s: %s(%d), first free %s: %s(%ld) - ignoring\n", - p, file, func, line, f->file, f->func, f->line); + " called from %s: %s(%d), first free %s: %s(%ld) - " + "ignoring\n", + p, file, func, line, f->file, f->func, f->line); return; } } - MDBG("freeing frag. %p alloc'ed from %s: %s(%ld)\n", - f, f->file, f->func, f->line); + MDBG("freeing frag. %p alloc'ed from %s: %s(%ld)\n", f, f->file, f->func, + f->line); #else - if (unlikely(f->u.is_free)){ - LM_INFO("freeing a free fragment (%p/%p) - ignore\n", - f, p); + if(unlikely(f->u.is_free)) { + LM_INFO("freeing a free fragment (%p/%p) - ignore\n", f, p); return; } #endif - size=f->size; - qm->used-=size; - qm->real_used-=size; + size = f->size; + qm->used -= size; + qm->real_used -= size; #ifdef MEM_JOIN_FREE - if(likely(cfg_get(core, core_cfg, mem_join)!=0)) { - next=prev=0; + if(likely(cfg_get(core, core_cfg, mem_join) != 0)) { + next = prev = 0; /* mark this fragment as used (might fall into the middle of joined frags) * to give us an extra chance of detecting a double free call (if the joined * fragment has not yet been reused) */ - f->u.nxt_free=(void*)0x1L; /* bogus value, just to mark it as free */ + f->u.nxt_free = (void *)0x1L; /* bogus value, just to mark it as free */ /* join packets if possible*/ - next=FRAG_NEXT(f); - if (((char*)next < (char*)qm->last_frag_end) && (next->u.is_free)){ + next = FRAG_NEXT(f); + if(((char *)next < (char *)qm->last_frag_end) && (next->u.is_free)) { /* join next packet */ #ifdef DBG_QM_MALLOC qm_debug_frag(qm, next, file, line); #endif qm_detach_free(qm, next); - size+=next->size+FRAG_OVERHEAD; - qm->real_used-=FRAG_OVERHEAD; + size += next->size + FRAG_OVERHEAD; + qm->real_used -= FRAG_OVERHEAD; qm->free_hash[GET_HASH(next->size)].no--; /* FIXME slow */ qm->ffrags--; } - if (f > qm->first_frag){ - prev=FRAG_PREV(f); + if(f > qm->first_frag) { + prev = FRAG_PREV(f); /* (struct qm_frag*)((char*)f - (struct qm_frag_end*)((char*)f- sizeof(struct qm_frag_end))->size);*/ - if (prev->u.is_free){ + if(prev->u.is_free) { /* join prev packet */ #ifdef DBG_QM_MALLOC qm_debug_frag(qm, prev, file, line); #endif qm_detach_free(qm, prev); - size+=prev->size+FRAG_OVERHEAD; - qm->real_used-=FRAG_OVERHEAD; + size += prev->size + FRAG_OVERHEAD; + qm->real_used -= FRAG_OVERHEAD; qm->free_hash[GET_HASH(prev->size)].no--; /* FIXME slow */ qm->ffrags--; - f=prev; + f = prev; } } - f->size=size; - FRAG_END(f)->size=f->size; - } /* if cfg_core->mem_join */ + f->size = size; + FRAG_END(f)->size = f->size; + } /* if cfg_core->mem_join */ #endif /* MEM_JOIN_FREE*/ #ifdef DBG_QM_MALLOC - f->file=file; - f->func=func; - f->mname=mname; - f->line=line; + f->file = file; + f->func = func; + f->mname = mname; + f->line = line; #endif qm_insert_free(qm, f); #ifdef MALLOC_STATS - if(qm->type==MEM_TYPE_PKG) { + if(qm->type == MEM_TYPE_PKG) { sr_event_exec(SREV_PKG_UPDATE_STATS, 0); } #endif } - #ifdef DBG_QM_MALLOC -void* qm_realloc(void* qmp, void* p, size_t size, - const char* file, const char* func, unsigned int line, - const char *mname) +void *qm_realloc(void *qmp, void *p, size_t size, const char *file, + const char *func, unsigned int line, const char *mname) #else -void* qm_realloc(void* qmp, void* p, size_t size) +void *qm_realloc(void *qmp, void *p, size_t size) #endif { - struct qm_block* qm; - struct qm_frag* f; + struct qm_block *qm; + struct qm_frag *f; size_t diff; size_t orig_size; - struct qm_frag* n; - void* ptr; + struct qm_frag *n; + void *ptr; - qm = (struct qm_block*)qmp; + qm = (struct qm_block *)qmp; #ifdef DBG_QM_MALLOC - MDBG("qm_realloc(%p, %p, %lu) called from %s: %s(%d)\n", - qm, p, (unsigned long)size, - file, func, line); - if ((p)&&(p>(void*)qm->last_frag_end || p<(void*)qm->first_frag)) { + MDBG("qm_realloc(%p, %p, %lu) called from %s: %s(%d)\n", qm, p, + (unsigned long)size, file, func, line); + if((p) && (p > (void *)qm->last_frag_end || p < (void *)qm->first_frag)) { LM_CRIT("BUG: bad pointer %p (out of memory block!) - " - "aborting\n", p); + "aborting\n", + p); abort(); } #endif - if (size==0) { - if (p) { + if(size == 0) { + if(p) { #ifdef DBG_QM_MALLOC qm_free(qm, p, file, func, line, mname); #else @@ -632,114 +646,114 @@ void* qm_realloc(void* qmp, void* p, size_t size) } return 0; } - if (p==0) + if(p == 0) #ifdef DBG_QM_MALLOC return qm_malloc(qm, size, file, func, line, mname); #else return qm_malloc(qm, size); #endif - f=(struct qm_frag*) ((char*)p-sizeof(struct qm_frag)); + f = (struct qm_frag *)((char *)p - sizeof(struct qm_frag)); #ifdef DBG_QM_MALLOC qm_debug_frag(qm, f, file, line); - MDBG("realloc'ing frag %p alloc'ed from %s: %s(%ld)\n", - f, f->file, f->func, f->line); - if (f->u.is_free){ + MDBG("realloc'ing frag %p alloc'ed from %s: %s(%ld)\n", f, f->file, f->func, + f->line); + if(f->u.is_free) { LM_CRIT("BUG: trying to realloc an already freed " - "pointer %p , fragment %p -- aborting\n", p, f); + "pointer %p , fragment %p -- aborting\n", + p, f); abort(); } #endif /* find first acceptable size */ - size=ROUNDUP(size); - if (f->size > size){ - orig_size=f->size; + size = ROUNDUP(size); + if(f->size > size) { + orig_size = f->size; /* shrink */ #ifdef DBG_QM_MALLOC - MDBG("shrinking from %lu to %lu\n", - f->size, (unsigned long)size); - if(split_frag(qm, f, size, file, "fragm. from qm_realloc", line, mname)!=0){ - MDBG("shrinked successful\n"); + MDBG("shrinking from %lu to %lu\n", f->size, (unsigned long)size); + if(split_frag(qm, f, size, file, "fragm. from qm_realloc", line, mname) + != 0) { + MDBG("shrinked successful\n"); #else - if(split_frag(qm, f, size)!=0){ + if(split_frag(qm, f, size) != 0) { #endif /* update used sizes: freed the splited frag */ /* split frag already adds FRAG_OVERHEAD for the newly created * free frag, so here we only need orig_size-f->size for real used */ - qm->real_used-=(orig_size-f->size); - qm->used-=(orig_size-f->size); + qm->real_used -= (orig_size - f->size); + qm->used -= (orig_size - f->size); } - }else if (f->size < size){ + } else if(f->size < size) { /* grow */ #ifdef DBG_QM_MALLOC - MDBG("growing from %lu to %lu\n", - f->size, (unsigned long)size); + MDBG("growing from %lu to %lu\n", f->size, (unsigned long)size); #endif - orig_size=f->size; - diff=size-f->size; - n=FRAG_NEXT(f); - if (((char*)n < (char*)qm->last_frag_end) && - (n->u.is_free)&&((n->size+FRAG_OVERHEAD)>=diff)){ - /* join */ - qm_detach_free(qm, n); - qm->free_hash[GET_HASH(n->size)].no--; /*FIXME: slow*/ - qm->ffrags--; - f->size+=n->size+FRAG_OVERHEAD; - qm->real_used-=FRAG_OVERHEAD; - FRAG_END(f)->size=f->size; - /* end checks should be ok */ - /* split it if necessary */ - if (f->size > size ){ - #ifdef DBG_QM_MALLOC - split_frag(qm, f, size, file, "fragm. from qm_realloc", - line, mname); - #else - split_frag(qm, f, size); - #endif - } - qm->real_used+=(f->size-orig_size); - qm->used+=(f->size-orig_size); - }else{ - /* could not join => realloc */ - #ifdef DBG_QM_MALLOC - ptr=qm_malloc(qm, size, file, func, line, mname); - #else - ptr=qm_malloc(qm, size); - #endif - if (ptr){ - /* copy old content */ - memcpy(ptr, p, orig_size); - /* free old pointer */ - #ifdef DBG_QM_MALLOC - qm_free(qm, p, file, func, line, mname); - #else - qm_free(qm, p); - #endif - } else { + orig_size = f->size; + diff = size - f->size; + n = FRAG_NEXT(f); + if(((char *)n < (char *)qm->last_frag_end) && (n->u.is_free) + && ((n->size + FRAG_OVERHEAD) >= diff)) { + /* join */ + qm_detach_free(qm, n); + qm->free_hash[GET_HASH(n->size)].no--; /*FIXME: slow*/ + qm->ffrags--; + f->size += n->size + FRAG_OVERHEAD; + qm->real_used -= FRAG_OVERHEAD; + FRAG_END(f)->size = f->size; + /* end checks should be ok */ + /* split it if necessary */ + if(f->size > size) { #ifdef DBG_QM_MALLOC - LM_ERR("qm_realloc(%p, %lu) called from %s: %s(%d)," - " module: %s; qm_malloc() failed!\n", - qm, (unsigned long)size, file, func, line, mname); + split_frag(qm, f, size, file, "fragm. from qm_realloc", line, + mname); #else - LM_ERR("qm_realloc(%p, %lu); qm_malloc() failed!\n", - qm, (unsigned long)size); + split_frag(qm, f, size); +#endif + } + qm->real_used += (f->size - orig_size); + qm->used += (f->size - orig_size); + } else { + /* could not join => realloc */ +#ifdef DBG_QM_MALLOC + ptr = qm_malloc(qm, size, file, func, line, mname); +#else + ptr = qm_malloc(qm, size); +#endif + if(ptr) { + /* copy old content */ + memcpy(ptr, p, orig_size); + /* free old pointer */ +#ifdef DBG_QM_MALLOC + qm_free(qm, p, file, func, line, mname); +#else + qm_free(qm, p); +#endif + } else { +#ifdef DBG_QM_MALLOC + LM_ERR("qm_realloc(%p, %lu) called from %s: %s(%d)," + " module: %s; qm_malloc() failed!\n", + qm, (unsigned long)size, file, func, line, mname); +#else + LM_ERR("qm_realloc(%p, %lu); qm_malloc() failed!\n", qm, + (unsigned long)size); #endif - } - p=ptr; } - }else{ + p = ptr; + } + } else { /* do nothing */ #ifdef DBG_QM_MALLOC - MDBG("doing nothing, same size: %lu - %lu\n", - f->size, (unsigned long)size); + MDBG("doing nothing, same size: %lu - %lu\n", f->size, + (unsigned long)size); #endif } #ifdef DBG_QM_MALLOC MDBG("returning pointer address: %p\n", p); #endif #ifdef MALLOC_STATS - if(qm->type==MEM_TYPE_PKG) { + if(qm->type == MEM_TYPE_PKG) { sr_event_exec(SREV_PKG_UPDATE_STATS, 0); } #endif @@ -748,11 +762,10 @@ void* qm_realloc(void* qmp, void* p, size_t size) #ifdef DBG_QM_MALLOC -void* qm_reallocxf(void* qmp, void* p, size_t size, - const char* file, const char* func, unsigned int line, - const char *mname) +void *qm_reallocxf(void *qmp, void *p, size_t size, const char *file, + const char *func, unsigned int line, const char *mname) #else -void* qm_reallocxf(void* qmp, void* p, size_t size) +void *qm_reallocxf(void *qmp, void *p, size_t size) #endif { void *r; @@ -764,68 +777,67 @@ void* qm_reallocxf(void* qmp, void* p, size_t size) #endif if(!r && p) { - #ifdef DBG_QM_MALLOC +#ifdef DBG_QM_MALLOC qm_free(qmp, p, file, func, line, mname); - #else +#else qm_free(qmp, p); - #endif - +#endif } return r; } -void qm_check(struct qm_block* qm) +void qm_check(struct qm_block *qm) { - struct qm_frag* f; + struct qm_frag *f; long fcount = 0; int memlog; - memlog=cfg_get(core, core_cfg, memlog); + memlog = cfg_get(core, core_cfg, memlog); LOG(memlog, "executing qm_check()\n"); f = qm->first_frag; - while ((char*)f < (char*)qm->last_frag_end) { + while((char *)f < (char *)qm->last_frag_end) { fcount++; /* check struct qm_frag */ #ifdef DBG_QM_MALLOC - if (f->check!=ST_CHECK_PATTERN){ + if(f->check != ST_CHECK_PATTERN) { LM_CRIT("BUG: qm: fragm. %p (address %p) " "beginning overwritten(%lx)!\n", - f, (char*)f + sizeof(struct qm_frag), - f->check); + f, (char *)f + sizeof(struct qm_frag), f->check); qm_status(qm); abort(); }; #endif - if ((char*)f + sizeof(struct qm_frag) + f->size - + sizeof(struct qm_frag_end) > (char*)qm->first_frag + qm->size) { + if((char *)f + sizeof(struct qm_frag) + f->size + + sizeof(struct qm_frag_end) + > (char *)qm->first_frag + qm->size) { LM_CRIT("BUG: qm: fragm. %p (address %p) " - "bad size: %lu (frag end: %p > end of block: %p)\n", - f, (char*)f + sizeof(struct qm_frag), f->size, - (char*)f + sizeof(struct qm_frag) + f->size - + sizeof(struct qm_frag_end), - (char*)qm->first_frag + qm->size); + "bad size: %lu (frag end: %p > end of block: %p)\n", + f, (char *)f + sizeof(struct qm_frag), f->size, + (char *)f + sizeof(struct qm_frag) + f->size + + sizeof(struct qm_frag_end), + (char *)qm->first_frag + qm->size); qm_status(qm); abort(); } /* check struct qm_frag_end */ - if (FRAG_END(f)->size != f->size) { + if(FRAG_END(f)->size != f->size) { LM_CRIT("BUG: qm: fragm. %p (address %p) " "size in qm_frag and qm_frag_end does not match:" " frag->size=%lu, frag_end->size=%lu)\n", - f, (char*)f + sizeof(struct qm_frag), - f->size, FRAG_END(f)->size); + f, (char *)f + sizeof(struct qm_frag), f->size, + FRAG_END(f)->size); qm_status(qm); abort(); } #ifdef DBG_QM_MALLOC - if ((FRAG_END(f)->check1 != END_CHECK_PATTERN1) || - (FRAG_END(f)->check2 != END_CHECK_PATTERN2)) { + if((FRAG_END(f)->check1 != END_CHECK_PATTERN1) + || (FRAG_END(f)->check2 != END_CHECK_PATTERN2)) { LM_CRIT("BUG: qm: fragm. %p (address %p)" - " end overwritten(%lx, %lx)!\n", - f, (char*)f + sizeof(struct qm_frag), - FRAG_END(f)->check1, FRAG_END(f)->check2); + " end overwritten(%lx, %lx)!\n", + f, (char *)f + sizeof(struct qm_frag), FRAG_END(f)->check1, + FRAG_END(f)->check2); qm_status(qm); abort(); } @@ -836,56 +848,58 @@ void qm_check(struct qm_block* qm) LOG(memlog, "summary of qm_check: %lu fragments OK\n", fcount); } -void qm_status(void* qmp) +void qm_status(void *qmp) { - struct qm_block* qm; - struct qm_frag* f; - int i,j; + struct qm_block *qm; + struct qm_frag *f; + int i, j; int h; int unused; int memlog; int mem_summary; - qm = (struct qm_block*)qmp; + qm = (struct qm_block *)qmp; - memlog=cfg_get(core, core_cfg, memlog); - mem_summary=cfg_get(core, core_cfg, mem_summary); + memlog = cfg_get(core, core_cfg, memlog); + mem_summary = cfg_get(core, core_cfg, mem_summary); LOG_FP(DEFAULT_FACILITY, memlog, "qm_status: ", "(%p):\n", qm); - if (!qm) return; + if(!qm) + return; LOG_FP(DEFAULT_FACILITY, memlog, "qm_status: ", "heap size= %lu\n", qm->size); - LOG_FP(DEFAULT_FACILITY, memlog, "qm_status: ", - "used= %lu, used+overhead=%lu, free=%lu\n", - qm->used, qm->real_used, qm->size-qm->real_used); - LOG_FP(DEFAULT_FACILITY, memlog, "qm_status: ", - "max used (+overhead)= %lu\n", qm->max_real_used); - - if (mem_summary & 16) return; - - LOG_FP(DEFAULT_FACILITY, memlog, "qm_status: ", - "dumping all alloc'ed. fragments:\n"); - for (f=qm->first_frag, i=0;(char*)f<(char*)qm->last_frag_end;f=FRAG_NEXT(f) - ,i++){ - if ((! f->u.is_free) || (cfg_get(core, core_cfg, mem_status_mode)!=0)){ + LOG_FP(DEFAULT_FACILITY, memlog, + "qm_status: ", "used= %lu, used+overhead=%lu, free=%lu\n", qm->used, + qm->real_used, qm->size - qm->real_used); + LOG_FP(DEFAULT_FACILITY, memlog, + "qm_status: ", "max used (+overhead)= %lu\n", qm->max_real_used); + + if(mem_summary & 16) + return; + + LOG_FP(DEFAULT_FACILITY, memlog, + "qm_status: ", "dumping all alloc'ed. fragments:\n"); + for(f = qm->first_frag, i = 0; (char *)f < (char *)qm->last_frag_end; + f = FRAG_NEXT(f), i++) { + if((!f->u.is_free) || (cfg_get(core, core_cfg, mem_status_mode) != 0)) { LOG_FP(DEFAULT_FACILITY, memlog, "qm_status: ", - " %3d. %c address=%p frag=%p size=%lu used=%d\n", - i, - (f->u.is_free)?'A':'N', - (char*)f+sizeof(struct qm_frag), f, f->size, FRAG_WAS_USED(f)); + " %3d. %c address=%p frag=%p size=%lu used=%d\n", i, + (f->u.is_free) ? 'A' : 'N', + (char *)f + sizeof(struct qm_frag), f, f->size, + FRAG_WAS_USED(f)); #ifdef DBG_QM_MALLOC + LOG_FP(DEFAULT_FACILITY, memlog, + "qm_status: ", " %s from %s: %s(%ld)\n", + (f->u.is_free) ? "freed" : "alloc'd", f->file, f->func, + f->line); LOG_FP(DEFAULT_FACILITY, memlog, "qm_status: ", - " %s from %s: %s(%ld)\n", - (f->u.is_free)?"freed":"alloc'd", f->file, f->func, f->line); - LOG_FP(DEFAULT_FACILITY, memlog, "qm_status: ", - " start check=%lx, end check= %lx, %lx\n", - f->check, FRAG_END(f)->check1, FRAG_END(f)->check2); - if (f->check!=ST_CHECK_PATTERN){ + " start check=%lx, end check= %lx, %lx\n", f->check, + FRAG_END(f)->check1, FRAG_END(f)->check2); + if(f->check != ST_CHECK_PATTERN) { LOG_FP(DEFAULT_FACILITY, memlog, "qm_status: ", - " * beginning overwritten(%lx)!\n", - f->check); + " * beginning overwritten(%lx)!\n", f->check); } - if ((FRAG_END(f)->check1 != END_CHECK_PATTERN1) + if((FRAG_END(f)->check1 != END_CHECK_PATTERN1) || (FRAG_END(f)->check2 != END_CHECK_PATTERN2)) { LOG_FP(DEFAULT_FACILITY, memlog, "qm_status: ", " * end overwritten(%lx, %lx)!\n", @@ -895,89 +909,90 @@ void qm_status(void* qmp) #endif } } - LOG_FP(DEFAULT_FACILITY, memlog, "qm_status: ", - "dumping free list stats :\n"); - for(h=0,i=0;hfree_hash[h].head.u.nxt_free,j=0; - f!=&(qm->free_hash[h].head); f=f->u.nxt_free, i++, j++){ - if (!FRAG_WAS_USED(f)){ - unused++; + LOG_FP(DEFAULT_FACILITY, memlog, + "qm_status: ", "dumping free list stats :\n"); + for(h = 0, i = 0; h < QM_HASH_SIZE; h++) { + unused = 0; + for(f = qm->free_hash[h].head.u.nxt_free, j = 0; + f != &(qm->free_hash[h].head); f = f->u.nxt_free, i++, j++) { + if(!FRAG_WAS_USED(f)) { + unused++; #ifdef DBG_QM_MALLOC - LOG_FP(DEFAULT_FACILITY, memlog, "qm_status: ", + LOG_FP(DEFAULT_FACILITY, memlog, "qm_status: ", "unused fragm.: hash = %3d, fragment %p," " address %p size %lu, created from %s: %s(%lu)\n", - h, f, (char*)f+sizeof(struct qm_frag), f->size, + h, f, (char *)f + sizeof(struct qm_frag), f->size, f->file, f->func, f->line); #endif - } + } } - if (j) LOG_FP(DEFAULT_FACILITY, memlog, "qm_status: ", - "hash= %3d. fragments no.: %5d, unused: %5d\n" + if(j) + LOG_FP(DEFAULT_FACILITY, memlog, "qm_status: ", + "hash= %3d. fragments no.: %5d, unused: %5d\n" "\t\t bucket size: %9lu - %9ld (first %9lu)\n", h, j, unused, UN_HASH(h), - ((h<=QM_MALLOC_OPTIMIZE/ROUNDTO)?1:2)*UN_HASH(h), - qm->free_hash[h].head.u.nxt_free->size - ); - if (j!=qm->free_hash[h].no){ - LOG(L_CRIT, "BUG: qm_status: different free frag. count: %d!=%lu" - " for hash %3d\n", j, qm->free_hash[h].no, h); + ((h <= QM_MALLOC_OPTIMIZE / ROUNDTO) ? 1 : 2) * UN_HASH(h), + qm->free_hash[h].head.u.nxt_free->size); + if(j != qm->free_hash[h].no) { + LOG(L_CRIT, + "BUG: qm_status: different free frag. count: %d!=%lu" + " for hash %3d\n", + j, qm->free_hash[h].no, h); } - } - LOG_FP(DEFAULT_FACILITY, memlog, "qm_status: ", - "-----------------------------\n"); + LOG_FP(DEFAULT_FACILITY, memlog, + "qm_status: ", "-----------------------------\n"); } /* fills a malloc info structure with info about the block * if a parameter is not supported, it will be filled with 0 */ -void qm_info(void* qmp, struct mem_info* info) +void qm_info(void *qmp, struct mem_info *info) { - struct qm_block* qm; - - qm = (struct qm_block*)qmp; - - memset(info,0, sizeof(*info)); - info->total_size=qm->size; - info->min_frag=MIN_FRAG_SIZE; - info->free_size=qm->size-qm->real_used; - info->used_size=qm->used; - info->real_used=qm->real_used; - info->max_used=qm->max_real_used; - info->total_frags=qm->ffrags; + struct qm_block *qm; + + qm = (struct qm_block *)qmp; + + memset(info, 0, sizeof(*info)); + info->total_size = qm->size; + info->min_frag = MIN_FRAG_SIZE; + info->free_size = qm->size - qm->real_used; + info->used_size = qm->used; + info->real_used = qm->real_used; + info->max_used = qm->max_real_used; + info->total_frags = qm->ffrags; } /* returns how much free memory is available * it never returns an error (unlike fm_available) */ -unsigned long qm_available(void* qmp) +unsigned long qm_available(void *qmp) { - struct qm_block* qm; + struct qm_block *qm; - qm = (struct qm_block*)qmp; + qm = (struct qm_block *)qmp; - return qm->size-qm->real_used; + return qm->size - qm->real_used; } - #ifdef DBG_QM_MALLOC -static mem_counter* get_mem_counter(mem_counter **root, struct qm_frag* f) +static mem_counter *get_mem_counter(mem_counter **root, struct qm_frag *f) { mem_counter *x; - if (!*root) goto make_new; - for(x=*root;x;x=x->next) - if (x->file == f->file && x->func == f->func && x->line == f->line) + if(!*root) + goto make_new; + for(x = *root; x; x = x->next) + if(x->file == f->file && x->func == f->func && x->line == f->line) return x; make_new: x = malloc(sizeof(mem_counter)); x->file = f->file; x->func = f->func; - x->mname= f->mname; + x->mname = f->mname; x->line = f->line; x->count = 0; x->size = 0; @@ -987,84 +1002,85 @@ static mem_counter* get_mem_counter(mem_counter **root, struct qm_frag* f) } - -void qm_sums(void* qmp) +void qm_sums(void *qmp) { - struct qm_block* qm; - struct qm_frag* f; + struct qm_block *qm; + struct qm_frag *f; int i; mem_counter *root, *x; int memlog; - qm = (struct qm_block*)qmp; + qm = (struct qm_block *)qmp; - root=0; - if (!qm) return; + root = 0; + if(!qm) + return; - memlog=cfg_get(core, core_cfg, memlog); - LOG_FP(DEFAULT_FACILITY, memlog, "qm_sums: ", - "summarizing all alloc'ed. fragments:\n"); + memlog = cfg_get(core, core_cfg, memlog); + LOG_FP(DEFAULT_FACILITY, memlog, + "qm_sums: ", "summarizing all alloc'ed. fragments:\n"); - for (f=qm->first_frag, i=0;(char*)f<(char*)qm->last_frag_end; - f=FRAG_NEXT(f),i++){ - if (! f->u.is_free){ - x = get_mem_counter(&root,f); + for(f = qm->first_frag, i = 0; (char *)f < (char *)qm->last_frag_end; + f = FRAG_NEXT(f), i++) { + if(!f->u.is_free) { + x = get_mem_counter(&root, f); x->count++; - x->size+=f->size; + x->size += f->size; } } x = root; - while(x){ - LOG_FP(DEFAULT_FACILITY, memlog, "qm_sums: ", - " count=%6d size=%10lu bytes from %s: %s(%ld)\n", - x->count,x->size, - x->file, x->func, x->line - ); + while(x) { + LOG_FP(DEFAULT_FACILITY, memlog, + "qm_sums: ", " count=%6d size=%10lu bytes from %s: %s(%ld)\n", + x->count, x->size, x->file, x->func, x->line); root = x->next; free(x); x = root; } - LOG_FP(DEFAULT_FACILITY, memlog, "qm_sums: ", - "-----------------------------\n"); + LOG_FP(DEFAULT_FACILITY, memlog, + "qm_sums: ", "-----------------------------\n"); } -#define QM_REPORT_SET(MREP, FRAG, FIELD) do { \ - MREP->FIELD ## _size = FRAG->size; \ - MREP->FIELD ## _file = FRAG->file; \ - MREP->FIELD ## _func = FRAG->func; \ - MREP->FIELD ## _mname = FRAG->mname; \ - MREP->FIELD ## _line = FRAG->line; \ +#define QM_REPORT_SET(MREP, FRAG, FIELD) \ + do { \ + MREP->FIELD##_size = FRAG->size; \ + MREP->FIELD##_file = FRAG->file; \ + MREP->FIELD##_func = FRAG->func; \ + MREP->FIELD##_mname = FRAG->mname; \ + MREP->FIELD##_line = FRAG->line; \ } while(0) -void qm_report(void* qmp, mem_report_t *mrep) +void qm_report(void *qmp, mem_report_t *mrep) { - struct qm_block* qm; - struct qm_frag* f; + struct qm_block *qm; + struct qm_frag *f; - qm = (struct qm_block*)qmp; + qm = (struct qm_block *)qmp; memset(mrep, 0, sizeof(mem_report_t)); - if (!qm) return; + if(!qm) + return; - mrep->total_size=qm->size; - mrep->free_size_s=qm->size - qm->real_used; - mrep->used_size_s=qm->used; - mrep->real_used_s=qm->real_used; - mrep->max_used_s=qm->max_real_used; + mrep->total_size = qm->size; + mrep->free_size_s = qm->size - qm->real_used; + mrep->used_size_s = qm->used; + mrep->real_used_s = qm->real_used; + mrep->max_used_s = qm->max_real_used; - for (f=qm->first_frag; (char*)f<(char*)qm->last_frag_end; f=FRAG_NEXT(f)) { + for(f = qm->first_frag; (char *)f < (char *)qm->last_frag_end; + f = FRAG_NEXT(f)) { mrep->total_frags++; - if (f->u.is_free) { + if(f->u.is_free) { mrep->free_frags++; mrep->free_size_m += f->size; - if(mrep->max_free_frag_size==0) { + if(mrep->max_free_frag_size == 0) { QM_REPORT_SET(mrep, f, max_free_frag); } else { if(f->size > mrep->max_free_frag_size) { QM_REPORT_SET(mrep, f, max_free_frag); } } - if(mrep->min_free_frag_size==0) { + if(mrep->min_free_frag_size == 0) { QM_REPORT_SET(mrep, f, min_free_frag); } else { if(f->size < mrep->min_free_frag_size) { @@ -1074,14 +1090,14 @@ void qm_report(void* qmp, mem_report_t *mrep) } else { mrep->used_frags++; mrep->used_size_m += f->size; - if(mrep->max_used_frag_size==0) { + if(mrep->max_used_frag_size == 0) { QM_REPORT_SET(mrep, f, max_used_frag); } else { if(f->size > mrep->max_used_frag_size) { QM_REPORT_SET(mrep, f, max_used_frag); } } - if(mrep->min_used_frag_size==0) { + if(mrep->min_used_frag_size == 0) { QM_REPORT_SET(mrep, f, min_used_frag); } else { if(f->size < mrep->min_used_frag_size) { @@ -1095,47 +1111,48 @@ void qm_report(void* qmp, mem_report_t *mrep) void qm_mod_get_stats(void *qmp, void **qm_rootp) { - if (!qm_rootp) { + if(!qm_rootp) { return; } LM_DBG("get qm memory statistics\n"); - struct qm_block *qm = (struct qm_block *) qmp; - mem_counter **qm_root = (mem_counter **) qm_rootp; - struct qm_frag* f; + struct qm_block *qm = (struct qm_block *)qmp; + mem_counter **qm_root = (mem_counter **)qm_rootp; + struct qm_frag *f; int i; mem_counter *x; - if (!qm) return ; + if(!qm) + return; /* update fragment detail list */ - for (f=qm->first_frag, i=0; (char*)f<(char*)qm->last_frag_end; - f=FRAG_NEXT(f), i++){ - if (! f->u.is_free){ - x = get_mem_counter(qm_root,f); + for(f = qm->first_frag, i = 0; (char *)f < (char *)qm->last_frag_end; + f = FRAG_NEXT(f), i++) { + if(!f->u.is_free) { + x = get_mem_counter(qm_root, f); x->count++; - x->size+=f->size; + x->size += f->size; } } - return ; + return; } void qm_mod_free_stats(void *qm_rootp) { - if (!qm_rootp) { + if(!qm_rootp) { return; } LM_DBG("free qm memory statistics\n"); - mem_counter *root = (mem_counter *) qm_rootp; + mem_counter *root = (mem_counter *)qm_rootp; mem_counter *new, *old; new = root; old = root; - while (new) { + while(new) { old = new; new = new->next; free(old); @@ -1149,7 +1166,7 @@ void qm_sums(void *qmp) return; } -void qm_report(void* qmp, mem_report_t *mrep) +void qm_report(void *qmp, mem_report_t *mrep) { LM_WARN("Enable DBG_QM_MALLOC for getting the report\n"); memset(mrep, 0, sizeof(mem_report_t)); @@ -1182,7 +1199,7 @@ static struct qm_block *_qm_pkg_block = 0; */ void qm_malloc_destroy_pkg_manager(void) { - if (_qm_pkg_pool) { + if(_qm_pkg_pool) { free(_qm_pkg_pool); _qm_pkg_pool = 0; } @@ -1196,12 +1213,13 @@ int qm_malloc_init_pkg_manager(void) { sr_pkg_api_t ma; _qm_pkg_pool = malloc(pkg_mem_size); - if (_qm_pkg_pool) - _qm_pkg_block=qm_malloc_init(_qm_pkg_pool, pkg_mem_size, MEM_TYPE_PKG); - if (_qm_pkg_block==0){ + if(_qm_pkg_pool) + _qm_pkg_block = + qm_malloc_init(_qm_pkg_pool, pkg_mem_size, MEM_TYPE_PKG); + if(_qm_pkg_block == 0) { LM_CRIT("could not initialize qm memory pool\n"); fprintf(stderr, "Too much qm pkg memory demanded: %ld bytes\n", - pkg_mem_size); + pkg_mem_size); return -1; } @@ -1230,15 +1248,15 @@ int qm_malloc_init_pkg_manager(void) /* SHM - shared memory API*/ static void *_qm_shm_pool = 0; static struct qm_block *_qm_shm_block = 0; -static gen_lock_t* _qm_shm_lock = 0; +static gen_lock_t *_qm_shm_lock = 0; -#define qm_shm_lock() lock_get(_qm_shm_lock) -#define qm_shm_unlock() lock_release(_qm_shm_lock) +#define qm_shm_lock() lock_get(_qm_shm_lock) +#define qm_shm_unlock() lock_release(_qm_shm_lock) /** * */ -void qm_shm_glock(void* qmp) +void qm_shm_glock(void *qmp) { lock_get(_qm_shm_lock); } @@ -1246,7 +1264,7 @@ void qm_shm_glock(void* qmp) /** * */ -void qm_shm_gunlock(void* qmp) +void qm_shm_gunlock(void *qmp) { lock_release(_qm_shm_lock); } @@ -1256,7 +1274,7 @@ void qm_shm_gunlock(void* qmp) */ void qm_shm_lock_destroy(void) { - if (_qm_shm_lock){ + if(_qm_shm_lock) { DBG("destroying the shared memory lock\n"); lock_destroy(_qm_shm_lock); /* we don't need to dealloc it*/ } @@ -1267,23 +1285,23 @@ void qm_shm_lock_destroy(void) */ int qm_shm_lock_init(void) { - if (_qm_shm_lock) { + if(_qm_shm_lock) { LM_DBG("shared memory lock initialized\n"); return 0; } #ifdef DBG_QM_MALLOC - _qm_shm_lock = qm_malloc(_qm_shm_block, sizeof(gen_lock_t), - _SRC_LOC_, _SRC_FUNCTION_, _SRC_LINE_, _SRC_MODULE_); + _qm_shm_lock = qm_malloc(_qm_shm_block, sizeof(gen_lock_t), _SRC_LOC_, + _SRC_FUNCTION_, _SRC_LINE_, _SRC_MODULE_); #else _qm_shm_lock = qm_malloc(_qm_shm_block, sizeof(gen_lock_t)); #endif - if (_qm_shm_lock==0){ + if(_qm_shm_lock == 0) { LOG(L_CRIT, "could not allocate lock\n"); return -1; } - if (lock_init(_qm_shm_lock)==0){ + if(lock_init(_qm_shm_lock) == 0) { LOG(L_CRIT, "could not initialize lock\n"); return -1; } @@ -1292,9 +1310,8 @@ int qm_shm_lock_init(void) /*SHM wrappers to sync the access to memory block*/ #ifdef DBG_QM_MALLOC -void* qm_shm_malloc(void* qmp, size_t size, - const char* file, const char* func, unsigned int line, - const char* mname) +void *qm_shm_malloc(void *qmp, size_t size, const char *file, const char *func, + unsigned int line, const char *mname) { void *r; qm_shm_lock(); @@ -1302,9 +1319,8 @@ void* qm_shm_malloc(void* qmp, size_t size, qm_shm_unlock(); return r; } -void* qm_shm_mallocxz(void* qmp, size_t size, - const char* file, const char* func, unsigned int line, - const char* mname) +void *qm_shm_mallocxz(void *qmp, size_t size, const char *file, + const char *func, unsigned int line, const char *mname) { void *r; qm_shm_lock(); @@ -1312,9 +1328,8 @@ void* qm_shm_mallocxz(void* qmp, size_t size, qm_shm_unlock(); return r; } -void* qm_shm_realloc(void* qmp, void* p, size_t size, - const char* file, const char* func, unsigned int line, - const char* mname) +void *qm_shm_realloc(void *qmp, void *p, size_t size, const char *file, + const char *func, unsigned int line, const char *mname) { void *r; qm_shm_lock(); @@ -1322,9 +1337,8 @@ void* qm_shm_realloc(void* qmp, void* p, size_t size, qm_shm_unlock(); return r; } -void* qm_shm_reallocxf(void* qmp, void* p, size_t size, - const char* file, const char* func, unsigned int line, - const char* mname) +void *qm_shm_reallocxf(void *qmp, void *p, size_t size, const char *file, + const char *func, unsigned int line, const char *mname) { void *r; qm_shm_lock(); @@ -1332,26 +1346,26 @@ void* qm_shm_reallocxf(void* qmp, void* p, size_t size, qm_shm_unlock(); return r; } -void* qm_shm_resize(void* qmp, void* p, size_t size, - const char* file, const char* func, unsigned int line, - const char* mname) +void *qm_shm_resize(void *qmp, void *p, size_t size, const char *file, + const char *func, unsigned int line, const char *mname) { void *r; qm_shm_lock(); - if(p) qm_free(qmp, p, file, func, line, mname); + if(p) + qm_free(qmp, p, file, func, line, mname); r = qm_malloc(qmp, size, file, func, line, mname); qm_shm_unlock(); return r; } -void qm_shm_free(void* qmp, void* p, const char* file, const char* func, - unsigned int line, const char* mname) +void qm_shm_free(void *qmp, void *p, const char *file, const char *func, + unsigned int line, const char *mname) { qm_shm_lock(); qm_free(qmp, p, file, func, line, mname); qm_shm_unlock(); } #else -void* qm_shm_malloc(void* qmp, size_t size) +void *qm_shm_malloc(void *qmp, size_t size) { void *r; qm_shm_lock(); @@ -1359,7 +1373,7 @@ void* qm_shm_malloc(void* qmp, size_t size) qm_shm_unlock(); return r; } -void* qm_shm_mallocxz(void* qmp, size_t size) +void *qm_shm_mallocxz(void *qmp, size_t size) { void *r; qm_shm_lock(); @@ -1367,7 +1381,7 @@ void* qm_shm_mallocxz(void* qmp, size_t size) qm_shm_unlock(); return r; } -void* qm_shm_realloc(void* qmp, void* p, size_t size) +void *qm_shm_realloc(void *qmp, void *p, size_t size) { void *r; qm_shm_lock(); @@ -1375,7 +1389,7 @@ void* qm_shm_realloc(void* qmp, void* p, size_t size) qm_shm_unlock(); return r; } -void* qm_shm_reallocxf(void* qmp, void* p, size_t size) +void *qm_shm_reallocxf(void *qmp, void *p, size_t size) { void *r; qm_shm_lock(); @@ -1383,41 +1397,42 @@ void* qm_shm_reallocxf(void* qmp, void* p, size_t size) qm_shm_unlock(); return r; } -void* qm_shm_resize(void* qmp, void* p, size_t size) +void *qm_shm_resize(void *qmp, void *p, size_t size) { void *r; qm_shm_lock(); - if(p) qm_free(qmp, p); + if(p) + qm_free(qmp, p); r = qm_malloc(qmp, size); qm_shm_unlock(); return r; } -void qm_shm_free(void* qmp, void* p) +void qm_shm_free(void *qmp, void *p) { qm_shm_lock(); qm_free(qmp, p); qm_shm_unlock(); } #endif -void qm_shm_status(void* qmp) +void qm_shm_status(void *qmp) { qm_shm_lock(); qm_status(qmp); qm_shm_unlock(); } -void qm_shm_info(void* qmp, struct mem_info* info) +void qm_shm_info(void *qmp, struct mem_info *info) { qm_shm_lock(); qm_info(qmp, info); qm_shm_unlock(); } -void qm_shm_report(void* qmp, mem_report_t* mrep) +void qm_shm_report(void *qmp, mem_report_t *mrep) { qm_shm_lock(); qm_report(qmp, mrep); qm_shm_unlock(); } -unsigned long qm_shm_available(void* qmp) +unsigned long qm_shm_available(void *qmp) { unsigned long r; qm_shm_lock(); @@ -1425,7 +1440,7 @@ unsigned long qm_shm_available(void* qmp) qm_shm_unlock(); return r; } -void qm_shm_sums(void* qmp) +void qm_shm_sums(void *qmp) { qm_shm_lock(); qm_sums(qmp); @@ -1460,43 +1475,44 @@ int qm_malloc_init_shm_manager(void) { sr_shm_api_t ma; _qm_shm_pool = shm_core_get_pool(); - if (_qm_shm_pool) - _qm_shm_block=qm_malloc_init(_qm_shm_pool, shm_mem_size, MEM_TYPE_SHM); - if (_qm_shm_block==0){ + if(_qm_shm_pool) + _qm_shm_block = + qm_malloc_init(_qm_shm_pool, shm_mem_size, MEM_TYPE_SHM); + if(_qm_shm_block == 0) { LM_CRIT("could not initialize qm shm memory pool\n"); fprintf(stderr, "Too much qm shm memory demanded: %ld bytes\n", - shm_mem_size); + shm_mem_size); return -1; } memset(&ma, 0, sizeof(sr_shm_api_t)); - ma.mname = _qm_mem_name; - ma.mem_pool = _qm_shm_pool; - ma.mem_block = _qm_shm_block; - ma.xmalloc = qm_shm_malloc; - ma.xmallocxz = qm_shm_mallocxz; + ma.mname = _qm_mem_name; + ma.mem_pool = _qm_shm_pool; + ma.mem_block = _qm_shm_block; + ma.xmalloc = qm_shm_malloc; + ma.xmallocxz = qm_shm_mallocxz; ma.xmalloc_unsafe = qm_malloc; - ma.xfree = qm_shm_free; - ma.xfree_unsafe = qm_free; - ma.xrealloc = qm_shm_realloc; - ma.xreallocxf = qm_shm_reallocxf; - ma.xresize = qm_shm_resize; - ma.xstatus = qm_shm_status; - ma.xinfo = qm_shm_info; - ma.xreport = qm_shm_report; - ma.xavailable = qm_shm_available; - ma.xsums = qm_shm_sums; - ma.xdestroy = qm_malloc_destroy_shm_manager; - ma.xmodstats = qm_shm_mod_get_stats; - ma.xfmodstats = qm_shm_mod_free_stats; - ma.xglock = qm_shm_glock; - ma.xgunlock = qm_shm_gunlock; - - if(shm_init_api(&ma)<0) { + ma.xfree = qm_shm_free; + ma.xfree_unsafe = qm_free; + ma.xrealloc = qm_shm_realloc; + ma.xreallocxf = qm_shm_reallocxf; + ma.xresize = qm_shm_resize; + ma.xstatus = qm_shm_status; + ma.xinfo = qm_shm_info; + ma.xreport = qm_shm_report; + ma.xavailable = qm_shm_available; + ma.xsums = qm_shm_sums; + ma.xdestroy = qm_malloc_destroy_shm_manager; + ma.xmodstats = qm_shm_mod_get_stats; + ma.xfmodstats = qm_shm_mod_free_stats; + ma.xglock = qm_shm_glock; + ma.xgunlock = qm_shm_gunlock; + + if(shm_init_api(&ma) < 0) { LM_ERR("cannot initialize the core shm api\n"); return -1; } - if(qm_shm_lock_init()<0) { + if(qm_shm_lock_init() < 0) { LM_ERR("cannot initialize the core shm lock\n"); return -1; } diff --git a/src/core/mem/q_malloc.h b/src/core/mem/q_malloc.h index cfcb43ecedd..71ca3f77d57 100644 --- a/src/core/mem/q_malloc.h +++ b/src/core/mem/q_malloc.h @@ -39,51 +39,56 @@ /* tricky, on sun in 32 bits mode long long must be 64 bits aligned * but long can be 32 bits aligned => malloc should return long long * aligned memory */ - #define ROUNDTO sizeof(long long) +#define ROUNDTO sizeof(long long) #else - #define ROUNDTO sizeof(void*) /* minimum possible ROUNDTO +#define ROUNDTO \ + sizeof(void *) /* minimum possible ROUNDTO * ->heavy debugging*/ #endif #else /* DBG_QM_MALLOC */ - #define ROUNDTO 16UL /* size we round to, must be = 2^n and also +#define ROUNDTO \ + 16UL /* size we round to, must be = 2^n and also * sizeof(qm_frag)+sizeof(qm_frag_end) * must be multiple of ROUNDTO! */ #endif -#define MIN_FRAG_SIZE ROUNDTO - +#define MIN_FRAG_SIZE ROUNDTO #define QM_MALLOC_OPTIMIZE_FACTOR 14UL /*used below */ -#define QM_MALLOC_OPTIMIZE ((unsigned long)(1UL<= requested size, accept it, else * look at misses and current fragments and decide based on them */ return (p_id < SFM_POOLS_NO) - && (split || ((qm->pool[p_id].pool_hash[hash].no < MIN_POOL_FRAGS) - || ((qm->pool[p_id].pool_hash[hash].misses - > qm->pool[p_id].pool_hash[hash].no) - && (qm->pool[p_id].pool_hash[hash].no - < MAX_POOL_FRAGS)))); + && (split + || ((qm->pool[p_id].pool_hash[hash].no < MIN_POOL_FRAGS) + || ((qm->pool[p_id].pool_hash[hash].misses + > qm->pool[p_id].pool_hash[hash].no) + && (qm->pool[p_id].pool_hash[hash].no + < MAX_POOL_FRAGS)))); } @@ -279,11 +280,13 @@ static inline void sfm_insert_free( /* size should be already rounded-up */ static inline #ifdef DBG_SF_MALLOC -void sfm_split_frag(struct sfm_block *qm, struct sfm_frag *frag, + void + sfm_split_frag(struct sfm_block *qm, struct sfm_frag *frag, unsigned long size, const char *file, const char *func, unsigned int line) #else -void sfm_split_frag( + void + sfm_split_frag( struct sfm_block *qm, struct sfm_frag *frag, unsigned long size) #endif { @@ -295,7 +298,7 @@ void sfm_split_frag( #ifdef MEM_FRAG_AVOIDANCE if((rest > (FRAG_OVERHEAD + SF_MALLOC_OPTIMIZE)) || (rest >= (FRAG_OVERHEAD - + size))) { /* the residue fragm. is big enough*/ + + size))) { /* the residue fragm. is big enough*/ bigger_rest = 1; #else if(rest > (FRAG_OVERHEAD + SF_MIN_FRAG_SIZE)) { @@ -336,8 +339,8 @@ struct sfm_block *sfm_malloc_init(char *address, unsigned long size, int type) /* make address and size multiple of 8*/ start = (char *)ROUNDUP((unsigned long)address); - LM_DBG("SF_OPTIMIZE=%lu, /SF_ROUNDTO=%lu\n", - SF_MALLOC_OPTIMIZE, SF_MALLOC_OPTIMIZE / SF_ROUNDTO); + LM_DBG("SF_OPTIMIZE=%lu, /SF_ROUNDTO=%lu\n", SF_MALLOC_OPTIMIZE, + SF_MALLOC_OPTIMIZE / SF_ROUNDTO); LM_DBG("SF_HASH_SIZE=%lu, sfm_block size=%lu\n", SF_HASH_SIZE, (long)sizeof(struct sfm_block)); LM_DBG("sfm_malloc_init(%p, %lu), start=%p\n", address, size, start); @@ -752,7 +755,7 @@ void sfm_free(struct sfm_block *qm, void *p) MDBG("sfm_free(%p, %p), called from %s: %s(%d)\n", qm, p, file, func, line); if(p > (void *)qm->last_frag || p < (void *)qm->first_frag) { LM_CRIT("BUG: bad pointer %p (out of memory block!) - " - "aborting\n", + "aborting\n", p); abort(); } @@ -800,7 +803,7 @@ void *sfm_realloc(struct sfm_block *qm, void *p, unsigned long size) func, line); if((p) && (p > (void *)qm->last_frag || p < (void *)qm->first_frag)) { LM_CRIT("BUG: bad pointer %p (out of memory block!) - " - "aborting\n", + "aborting\n", p); abort(); } @@ -871,8 +874,8 @@ void *sfm_realloc(struct sfm_block *qm, void *p, unsigned long size) if(*pf == 0) { SFM_MAIN_HASH_UNLOCK(qm, hash); /* not found, bad! */ - LM_WARN("could not find %p in free list (hash=%d)\n", - n, hash); + LM_WARN("could not find %p in free list (hash=%d)\n", n, + hash); /* somebody is in the process of changing it ? */ goto not_found; } @@ -886,8 +889,9 @@ void *sfm_realloc(struct sfm_block *qm, void *p, unsigned long size) /* split it if necessary */ if(f->size > size) { #ifdef DBG_SF_MALLOC - sfm_split_frag(qm, f, size, file, "fragm. from " - "sfm_realloc", + sfm_split_frag(qm, f, size, file, + "fragm. from " + "sfm_realloc", line); #else sfm_split_frag(qm, f, size); @@ -915,8 +919,8 @@ void *sfm_realloc(struct sfm_block *qm, void *p, unsigned long size) if(*pf == 0) { SFM_POOL_UNLOCK(pool, hash); /* not found, bad! */ - LM_WARN("could not find %p in free list (hash=%d)\n", - n, hash); + LM_WARN("could not find %p in free list (hash=%d)\n", n, + hash); /* somebody is in the process of changing it ? */ goto not_found; } @@ -930,8 +934,9 @@ void *sfm_realloc(struct sfm_block *qm, void *p, unsigned long size) /* split it if necessary */ if(f->size > size) { #ifdef DBG_SF_MALLOC - sfm_split_frag(qm, f, size, file, "fragm. from " - "sfm_realloc", + sfm_split_frag(qm, f, size, file, + "fragm. from " + "sfm_realloc", line); #else sfm_split_frag(qm, f, size); @@ -963,8 +968,7 @@ void *sfm_realloc(struct sfm_block *qm, void *p, unsigned long size) } else { /* do nothing */ #ifdef DBG_SF_MALLOC - MDBG("doing nothing, same size: %lu - %lu\n", f->size, - size); + MDBG("doing nothing, same size: %lu - %lu\n", f->size, size); #endif } #ifdef DBG_SF_MALLOC @@ -999,23 +1003,25 @@ void sfm_status(struct sfm_block *qm) if(!FRAG_WAS_USED(f)) { unused++; #ifdef DBG_SF_MALLOC - LOG(memlog, "unused fragm.: hash = %3d, fragment %p," - " address %p size %lu, created from %s: %s(%ld)\n", + LOG(memlog, + "unused fragm.: hash = %3d, fragment %p," + " address %p size %lu, created from %s: %s(%ld)\n", h, f, (char *)f + sizeof(struct sfm_frag), f->size, f->file, f->func, f->line); #endif }; } if(j) - LOG(memlog, "hash = %3d fragments no.: %5d, unused: %5d\n\t\t" - " bucket size: %9lu - %9lu (first %9lu)\n", + LOG(memlog, + "hash = %3d fragments no.: %5d, unused: %5d\n\t\t" + " bucket size: %9lu - %9lu (first %9lu)\n", h, j, unused, UN_HASH(h), ((h <= SF_MALLOC_OPTIMIZE / SF_ROUNDTO) ? 1 : 2) * UN_HASH(h), qm->free_hash[h].first->size); if(j != qm->free_hash[h].no) { LM_CRIT("BUG: different free frag. count: %d!=%ld" - " for hash %3d\n", + " for hash %3d\n", j, qm->free_hash[h].no, h); } SFM_MAIN_HASH_UNLOCK(qm, h); @@ -1029,25 +1035,28 @@ void sfm_status(struct sfm_block *qm) if(!FRAG_WAS_USED(f)) { unused++; #ifdef DBG_SF_MALLOC - LOG(memlog, "[%2d] unused fragm.: hash = %3d, fragment %p," - " address %p size %lu, created from %s: " - "%s(%ld)\n", + LOG(memlog, + "[%2d] unused fragm.: hash = %3d, fragment %p," + " address %p size %lu, created from %s: " + "%s(%ld)\n", k, h, f, (char *)f + sizeof(struct sfm_frag), f->size, f->file, f->func, f->line); #endif }; } if(j) - LOG(memlog, "[%2d] hash = %3d fragments no.: %5d, unused: " - "%5d\n\t\t bucket size: %9lu - %9lu " - "(first %9lu)\n", + LOG(memlog, + "[%2d] hash = %3d fragments no.: %5d, unused: " + "%5d\n\t\t bucket size: %9lu - %9lu " + "(first %9lu)\n", k, h, j, unused, UN_HASH(h), ((h <= SF_MALLOC_OPTIMIZE / SF_ROUNDTO) ? 1 : 2) * UN_HASH(h), qm->pool[k].pool_hash[h].first->size); if(j != qm->pool[k].pool_hash[h].no) { - LOG(L_CRIT, "BUG: sfm_status: [%d] different free frag." - " count: %d!=%ld for hash %3d\n", + LOG(L_CRIT, + "BUG: sfm_status: [%d] different free frag." + " count: %d!=%ld for hash %3d\n", k, j, qm->pool[k].pool_hash[h].no, h); } SFM_POOL_UNLOCK(&qm->pool[k], h); @@ -1106,4 +1115,4 @@ unsigned long sfm_available(struct sfm_block *qm) return ((unsigned long)-1); } -#endif \ No newline at end of file +#endif diff --git a/src/core/mem/sf_malloc.h b/src/core/mem/sf_malloc.h index 580ecc1fa72..2b444ff2ab9 100644 --- a/src/core/mem/sf_malloc.h +++ b/src/core/mem/sf_malloc.h @@ -45,63 +45,71 @@ /* tricky, on sun in 32 bits mode long long must be 64 bits aligned * but long can be 32 bits aligned => malloc should return long long * aligned memory */ - #define SF_ROUNDTO sizeof(long long) +#define SF_ROUNDTO sizeof(long long) #else - #define SF_ROUNDTO sizeof(void*) /* size we round to, must be = 2^n, +#define SF_ROUNDTO \ + sizeof(void *) /* size we round to, must be = 2^n, * and sizeof(sfm_frag) must be multiple of SF_ROUNDTO !*/ #endif #else /* DBG_SF_MALLOC */ - #define SF_ROUNDTO 8UL +#define SF_ROUNDTO 8UL #endif -#define SF_MIN_FRAG_SIZE SF_ROUNDTO +#define SF_MIN_FRAG_SIZE SF_ROUNDTO -#define SFM_POOLS_NO 4U /* the more the better, but higher initial +#define SFM_POOLS_NO \ + 4U /* the more the better, but higher initial * mem. consumption */ #define SF_MALLOC_OPTIMIZE_FACTOR 14UL /*used below */ -#define SF_MALLOC_OPTIMIZE (1UL< #include @@ -41,21 +41,21 @@ #include "memcore.h" -#define SHM_CORE_POOLS_SIZE 4 +#define SHM_CORE_POOLS_SIZE 4 #define _ROUND2TYPE(s, type) \ - (((s)+(sizeof(type)-1))&(~(sizeof(type)-1))) + (((s) + (sizeof(type) - 1)) & (~(sizeof(type) - 1))) #define _ROUND_LONG(s) _ROUND2TYPE(s, long) void shm_core_destroy(void); #ifndef SHM_MMAP -static int _shm_core_shmid[SHM_CORE_POOLS_SIZE] = { -1 }; /*shared memory id*/ +static int _shm_core_shmid[SHM_CORE_POOLS_SIZE] = {-1}; /*shared memory id*/ #endif -static void* _shm_core_pools_mem[SHM_CORE_POOLS_SIZE] = { (void*)-1 }; -static int _shm_core_pools_num = 1; +static void *_shm_core_pools_mem[SHM_CORE_POOLS_SIZE] = {(void *)-1}; +static int _shm_core_pools_num = 1; sr_shm_api_t _shm_root = {0}; @@ -80,20 +80,21 @@ int shm_core_pools_init(void) #ifdef SHM_MMAP if(_shm_core_pools_mem[i] != (void *)-1) { #else - if((_shm_core_shmid[i] != -1)||(_shm_core_pools_mem[i] != (void *)-1)) { + if((_shm_core_shmid[i] != -1) + || (_shm_core_pools_mem[i] != (void *)-1)) { #endif LM_DBG("shm pool[%d] already initialized\n", i); pinit++; } } - if(pinit!=0) { - if(pinit==_shm_core_pools_num) { + if(pinit != 0) { + if(pinit == _shm_core_pools_num) { LM_DBG("all shm pools initialized\n"); return 0; } else { - LM_CRIT("partial initialization of shm pools (%d / %d)\n", - pinit, _shm_core_pools_num); + LM_CRIT("partial initialization of shm pools (%d / %d)\n", pinit, + _shm_core_pools_num); return -1; } } else { @@ -108,8 +109,8 @@ int shm_core_pools_init(void) #else fd = open("/dev/zero", O_RDWR); if(fd == -1) { - LOG(L_CRIT, "could not open /dev/zero [%d]: %s\n", - i, strerror(errno)); + LOG(L_CRIT, "could not open /dev/zero [%d]: %s\n", i, + strerror(errno)); return -1; } _shm_core_pools_mem[i] = mmap( @@ -121,15 +122,15 @@ int shm_core_pools_init(void) _shm_core_shmid[i] = shmget(IPC_PRIVATE, shm_mem_size, 0700); if(_shm_core_shmid[i] == -1) { - LOG(L_CRIT, "could not allocate shared memory segment[%d]: %s\n", - i, strerror(errno)); + LOG(L_CRIT, "could not allocate shared memory segment[%d]: %s\n", i, + strerror(errno)); return -1; } _shm_core_pools_mem[i] = shmat(_shm_core_shmid[i], 0, 0); #endif if(_shm_core_pools_mem[i] == (void *)-1) { - LOG(L_CRIT, "could not attach shared memory segment[%d]: %s\n", - i, strerror(errno)); + LOG(L_CRIT, "could not attach shared memory segment[%d]: %s\n", i, + strerror(errno)); /* destroy segment*/ shm_core_destroy(); return -1; @@ -141,16 +142,16 @@ int shm_core_pools_init(void) /** * */ -void* shm_core_get_pool(void) +void *shm_core_get_pool(void) { int ret; long sz; - long* p; - long* end; + long *p; + long *end; int i; - ret=shm_core_pools_init(); - if (ret<0) + ret = shm_core_pools_init(); + if(ret < 0) return NULL; for(i = 0; i < _shm_core_pools_num; i++) { @@ -182,8 +183,9 @@ int shm_address_in(void *p) if(_shm_core_pools_mem[i] == (void *)-1) { continue; } - if(((char*)p >= (char*)_shm_core_pools_mem[i]) - && ((char*)p < ((char*)_shm_core_pools_mem[i]) + shm_mem_size)) { + if(((char *)p >= (char *)_shm_core_pools_mem[i]) + && ((char *)p + < ((char *)_shm_core_pools_mem[i]) + shm_mem_size)) { /* address in shm zone */ return 1; } @@ -228,29 +230,28 @@ void shm_core_destroy(void) int shm_init_api(sr_shm_api_t *ap) { memset(&_shm_root, 0, sizeof(sr_shm_api_t)); - _shm_root.mname = ap->mname; - _shm_root.mem_pool = ap->mem_pool; - _shm_root.mem_block = ap->mem_block; - _shm_root.xmalloc = ap->xmalloc; - _shm_root.xmallocxz = ap->xmallocxz; + _shm_root.mname = ap->mname; + _shm_root.mem_pool = ap->mem_pool; + _shm_root.mem_block = ap->mem_block; + _shm_root.xmalloc = ap->xmalloc; + _shm_root.xmallocxz = ap->xmallocxz; _shm_root.xmalloc_unsafe = ap->xmalloc_unsafe; - _shm_root.xfree = ap->xfree; - _shm_root.xfree_unsafe = ap->xfree_unsafe; - _shm_root.xrealloc = ap->xrealloc; - _shm_root.xreallocxf = ap->xreallocxf; - _shm_root.xresize = ap->xresize; - _shm_root.xstatus = ap->xstatus; - _shm_root.xinfo = ap->xinfo; - _shm_root.xreport = ap->xreport; - _shm_root.xavailable = ap->xavailable; - _shm_root.xsums = ap->xsums; - _shm_root.xdestroy = ap->xdestroy; - _shm_root.xmodstats = ap->xmodstats; - _shm_root.xfmodstats = ap->xfmodstats; - _shm_root.xglock = ap->xglock; - _shm_root.xgunlock = ap->xgunlock; + _shm_root.xfree = ap->xfree; + _shm_root.xfree_unsafe = ap->xfree_unsafe; + _shm_root.xrealloc = ap->xrealloc; + _shm_root.xreallocxf = ap->xreallocxf; + _shm_root.xresize = ap->xresize; + _shm_root.xstatus = ap->xstatus; + _shm_root.xinfo = ap->xinfo; + _shm_root.xreport = ap->xreport; + _shm_root.xavailable = ap->xavailable; + _shm_root.xsums = ap->xsums; + _shm_root.xdestroy = ap->xdestroy; + _shm_root.xmodstats = ap->xmodstats; + _shm_root.xfmodstats = ap->xfmodstats; + _shm_root.xglock = ap->xglock; + _shm_root.xgunlock = ap->xgunlock; return 0; - } /** @@ -258,21 +259,18 @@ int shm_init_api(sr_shm_api_t *ap) */ int shm_init_manager(char *name) { - if(strcmp(name, "fm")==0 - || strcmp(name, "f_malloc")==0 - || strcmp(name, "fmalloc")==0) { + if(strcmp(name, "fm") == 0 || strcmp(name, "f_malloc") == 0 + || strcmp(name, "fmalloc") == 0) { /*fast malloc*/ return fm_malloc_init_shm_manager(); - } else if(strcmp(name, "qm")==0 - || strcmp(name, "q_malloc")==0 - || strcmp(name, "qmalloc")==0) { + } else if(strcmp(name, "qm") == 0 || strcmp(name, "q_malloc") == 0 + || strcmp(name, "qmalloc") == 0) { /*quick malloc*/ return qm_malloc_init_shm_manager(); - } else if(strcmp(name, "tlsf")==0 - || strcmp(name, "tlsf_malloc")==0) { + } else if(strcmp(name, "tlsf") == 0 || strcmp(name, "tlsf_malloc") == 0) { /*tlsf malloc*/ return tlsf_malloc_init_shm_manager(); - } else if(strcmp(name, "sm")==0) { + } else if(strcmp(name, "sm") == 0) { /*system malloc*/ } else { /*custom malloc - module*/ @@ -287,7 +285,7 @@ void shm_destroy_manager(void) { if(_shm_root.xdestroy) { LM_DBG("destroying memory manager: %s\n", - (_shm_root.mname)?_shm_root.mname:"unknown"); + (_shm_root.mname) ? _shm_root.mname : "unknown"); _shm_root.xdestroy(); } shm_core_destroy(); @@ -299,5 +297,5 @@ void shm_destroy_manager(void) void shm_print_manager(void) { LM_DBG("shm - using memory manager: %s\n", - (_shm_root.mname)?_shm_root.mname:"unknown"); + (_shm_root.mname) ? _shm_root.mname : "unknown"); } diff --git a/src/core/mem/shm.h b/src/core/mem/shm.h index b7bae024d59..3813d984012 100644 --- a/src/core/mem/shm.h +++ b/src/core/mem/shm.h @@ -47,46 +47,54 @@ extern sr_shm_api_t _shm_root; #ifdef DBG_SR_MEMORY -# define shm_malloc(s) _shm_root.xmalloc(_shm_root.mem_block, (s), _SRC_LOC_, \ - _SRC_FUNCTION_, _SRC_LINE_, _SRC_MODULE_) -# define shm_mallocxz(s) _shm_root.xmallocxz(_shm_root.mem_block, (s), _SRC_LOC_, \ - _SRC_FUNCTION_, _SRC_LINE_, _SRC_MODULE_) -# define shm_malloc_unsafe(s) _shm_root.xmalloc_unsafe(_shm_root.mem_block, (s), _SRC_LOC_, \ - _SRC_FUNCTION_, _SRC_LINE_, _SRC_MODULE_) -# define shm_realloc(p, s) _shm_root.xrealloc(_shm_root.mem_block, (p), (s), \ - _SRC_LOC_, _SRC_FUNCTION_, _SRC_LINE_, _SRC_MODULE_) -# define shm_reallocxf(p, s) _shm_root.xreallocxf(_shm_root.mem_block, (p), (s), \ - _SRC_LOC_, _SRC_FUNCTION_, _SRC_LINE_, _SRC_MODULE_) -# define shm_resize(p, s) _shm_root.xresize(_shm_root.mem_block, (p), (s), \ - _SRC_LOC_, _SRC_FUNCTION_, _SRC_LINE_, _SRC_MODULE_) -# define shm_free(p) _shm_root.xfree(_shm_root.mem_block, (p), _SRC_LOC_, \ - _SRC_FUNCTION_, _SRC_LINE_, _SRC_MODULE_) -# define shm_free_unsafe(p) _shm_root.xfree_unsafe(_shm_root.mem_block, (p), _SRC_LOC_, \ - _SRC_FUNCTION_, _SRC_LINE_, _SRC_MODULE_) +#define shm_malloc(s) \ + _shm_root.xmalloc(_shm_root.mem_block, (s), _SRC_LOC_, _SRC_FUNCTION_, \ + _SRC_LINE_, _SRC_MODULE_) +#define shm_mallocxz(s) \ + _shm_root.xmallocxz(_shm_root.mem_block, (s), _SRC_LOC_, _SRC_FUNCTION_, \ + _SRC_LINE_, _SRC_MODULE_) +#define shm_malloc_unsafe(s) \ + _shm_root.xmalloc_unsafe(_shm_root.mem_block, (s), _SRC_LOC_, \ + _SRC_FUNCTION_, _SRC_LINE_, _SRC_MODULE_) +#define shm_realloc(p, s) \ + _shm_root.xrealloc(_shm_root.mem_block, (p), (s), _SRC_LOC_, \ + _SRC_FUNCTION_, _SRC_LINE_, _SRC_MODULE_) +#define shm_reallocxf(p, s) \ + _shm_root.xreallocxf(_shm_root.mem_block, (p), (s), _SRC_LOC_, \ + _SRC_FUNCTION_, _SRC_LINE_, _SRC_MODULE_) +#define shm_resize(p, s) \ + _shm_root.xresize(_shm_root.mem_block, (p), (s), _SRC_LOC_, \ + _SRC_FUNCTION_, _SRC_LINE_, _SRC_MODULE_) +#define shm_free(p) \ + _shm_root.xfree(_shm_root.mem_block, (p), _SRC_LOC_, _SRC_FUNCTION_, \ + _SRC_LINE_, _SRC_MODULE_) +#define shm_free_unsafe(p) \ + _shm_root.xfree_unsafe(_shm_root.mem_block, (p), _SRC_LOC_, \ + _SRC_FUNCTION_, _SRC_LINE_, _SRC_MODULE_) #else -# define shm_malloc(s) _shm_root.xmalloc(_shm_root.mem_block, (s)) -# define shm_mallocxz(s) _shm_root.xmallocxz(_shm_root.mem_block, (s)) -# define shm_malloc_unsafe(s) _shm_root.xmalloc_unsafe(_shm_root.mem_block, (s)) -# define shm_realloc(p, s) _shm_root.xrealloc(_shm_root.mem_block, (p), (s)) -# define shm_reallocxf(p, s) _shm_root.xreallocxf(_shm_root.mem_block, (p), (s)) -# define shm_resize(p, s) _shm_root.xresize(_shm_root.mem_block, (p), (s)) -# define shm_free(p) _shm_root.xfree(_shm_root.mem_block, (p)) -# define shm_free_unsafe(p) _shm_root.xfree_unsafe(_shm_root.mem_block, (p)) +#define shm_malloc(s) _shm_root.xmalloc(_shm_root.mem_block, (s)) +#define shm_mallocxz(s) _shm_root.xmallocxz(_shm_root.mem_block, (s)) +#define shm_malloc_unsafe(s) _shm_root.xmalloc_unsafe(_shm_root.mem_block, (s)) +#define shm_realloc(p, s) _shm_root.xrealloc(_shm_root.mem_block, (p), (s)) +#define shm_reallocxf(p, s) _shm_root.xreallocxf(_shm_root.mem_block, (p), (s)) +#define shm_resize(p, s) _shm_root.xresize(_shm_root.mem_block, (p), (s)) +#define shm_free(p) _shm_root.xfree(_shm_root.mem_block, (p)) +#define shm_free_unsafe(p) _shm_root.xfree_unsafe(_shm_root.mem_block, (p)) #endif -# define shm_status() _shm_root.xstatus(_shm_root.mem_block) -# define shm_info(mi) _shm_root.xinfo(_shm_root.mem_block, mi) -# define shm_report(mr) _shm_root.xreport(_shm_root.mem_block, mr) -# define shm_available() _shm_root.xavailable(_shm_root.mem_block) -# define shm_sums() _shm_root.xsums(_shm_root.mem_block) -# define shm_mod_get_stats(x) _shm_root.xmodstats(_shm_root.mem_block, x) -# define shm_mod_free_stats(x) _shm_root.xfmodstats(x) +#define shm_status() _shm_root.xstatus(_shm_root.mem_block) +#define shm_info(mi) _shm_root.xinfo(_shm_root.mem_block, mi) +#define shm_report(mr) _shm_root.xreport(_shm_root.mem_block, mr) +#define shm_available() _shm_root.xavailable(_shm_root.mem_block) +#define shm_sums() _shm_root.xsums(_shm_root.mem_block) +#define shm_mod_get_stats(x) _shm_root.xmodstats(_shm_root.mem_block, x) +#define shm_mod_free_stats(x) _shm_root.xfmodstats(x) -# define shm_global_lock() _shm_root.xglock(_shm_root.mem_block) -# define shm_global_unlock() _shm_root.xgunlock(_shm_root.mem_block) +#define shm_global_lock() _shm_root.xglock(_shm_root.mem_block) +#define shm_global_unlock() _shm_root.xgunlock(_shm_root.mem_block) -void* shm_core_get_pool(void); +void *shm_core_get_pool(void); int shm_init_api(sr_shm_api_t *ap); int shm_init_manager(char *name); void shm_destroy_manager(void); @@ -95,18 +103,25 @@ void shm_print_manager(void); int shm_address_in(void *p); #define shm_available_safe() shm_available() -#define shm_malloc_on_fork() do{}while(0) +#define shm_malloc_on_fork() \ + do { \ + } while(0) /* generic logging helper for allocation errors in shared memory pool */ #define SHM_MEM_ERROR LM_ERR("could not allocate shared memory from shm pool\n") -#define SHM_MEM_CRITICAL LM_CRIT("could not allocate shared memory from shm pool\n") +#define SHM_MEM_CRITICAL \ + LM_CRIT("could not allocate shared memory from shm pool\n") #ifdef __SUNPRO_C -#define SHM_MEM_ERROR_FMT(...) LM_ERR("could not allocate shared memory from shm pool" __VA_ARGS__) -#define SHM_MEM_CRITICAL_FMT(...) LM_CRIT("could not allocate shared memory from shm pool" __VA_ARGS__) +#define SHM_MEM_ERROR_FMT(...) \ + LM_ERR("could not allocate shared memory from shm pool" __VA_ARGS__) +#define SHM_MEM_CRITICAL_FMT(...) \ + LM_CRIT("could not allocate shared memory from shm pool" __VA_ARGS__) #else -#define SHM_MEM_ERROR_FMT(fmt, args...) LM_ERR("could not allocate shared memory from shm pool - " fmt , ## args) -#define SHM_MEM_CRITICAL_FMT(fmt, args...) LM_CRIT("could not allocate shared memory from shm pool - " fmt , ## args) +#define SHM_MEM_ERROR_FMT(fmt, args...) \ + LM_ERR("could not allocate shared memory from shm pool - " fmt, ##args) +#define SHM_MEM_CRITICAL_FMT(fmt, args...) \ + LM_CRIT("could not allocate shared memory from shm pool - " fmt, ##args) #endif #endif /* _sr_shm_h_ */ diff --git a/src/core/mem/shm_mem.h b/src/core/mem/shm_mem.h index 67127f4bdbe..d4405b3f389 100644 --- a/src/core/mem/shm_mem.h +++ b/src/core/mem/shm_mem.h @@ -32,4 +32,3 @@ #include "shm.h" #endif /* shm_mem_h */ - diff --git a/src/core/mem/src_loc.h b/src/core/mem/src_loc.h index af004464857..236dd35c85a 100644 --- a/src/core/mem/src_loc.h +++ b/src/core/mem/src_loc.h @@ -1,4 +1,4 @@ -/* +/* * Copyright (C) 2009 iptelorg GmbH * * This file is part of Kamailio, a free SIP server. @@ -19,12 +19,12 @@ /** * \file * \brief Helper definitions for internal memory manager - * + * * Helper definitions for internal memory manager, defines for src location * (function name, module a.s.o.), used for recording a *malloc()/ *free() * caller. Expects MOD_NAME defined for modules (if it's not defined "core" * will be assumed). - * + * * Defines: * - _SRC_FUNCTION_ - current function name * - _SRC_FILENAME_ - current .c filename @@ -42,39 +42,39 @@ /* C >= 99 has __func__, older gcc versions have __FUNCTION__ */ #ifndef _SRC_FUNCTION_ -# if __STDC_VERSION__ < 199901L -# if __GNUC__ >= 2 -# define _SRC_FUNCTION_ __FUNCTION__ -# else -# define _SRC_FUNCTION_ "" -# endif -# else -# define _SRC_FUNCTION_ __func__ -# endif /* __STDC_VERSION_ < 199901L */ +#if __STDC_VERSION__ < 199901L +#if __GNUC__ >= 2 +#define _SRC_FUNCTION_ __FUNCTION__ +#else +#define _SRC_FUNCTION_ "" +#endif +#else +#define _SRC_FUNCTION_ __func__ +#endif /* __STDC_VERSION_ < 199901L */ #endif /* _FUNC_NAME_ */ #ifndef _SRC_FILENAME_ -# define _SRC_FILENAME_ __FILE__ +#define _SRC_FILENAME_ __FILE__ #endif /* _SRC_FILENAME_ */ #ifndef _SRC_LINE_ -# define _SRC_LINE_ __LINE__ +#define _SRC_LINE_ __LINE__ #endif /* _SRC_LINE_ */ #ifndef _SRC_MODULE_ -# ifdef MOD_NAME -# define _SRC_MODULE_ MOD_NAME -# else -# define _SRC_MODULE_ "core" -# endif /* MOD_NAME */ +#ifdef MOD_NAME +#define _SRC_MODULE_ MOD_NAME +#else +#define _SRC_MODULE_ "core" +#endif /* MOD_NAME */ #endif /* _SRC_MODULE_ */ #ifndef _SRC_LOC_ -# define _SRC_LOC_ _SRC_MODULE_ ": " _SRC_FILENAME_ +#define _SRC_LOC_ _SRC_MODULE_ ": " _SRC_FILENAME_ #endif /*_SRC_LOC_ */ diff --git a/src/core/mem/tlsf_malloc.c b/src/core/mem/tlsf_malloc.c index 805ada03cc8..f7cdeab5eec 100644 --- a/src/core/mem/tlsf_malloc.c +++ b/src/core/mem/tlsf_malloc.c @@ -30,7 +30,7 @@ enum tlsf_public /* Private constants: do not modify. */ enum tlsf_private { -#if defined (TLSF_64BIT) +#if defined(TLSF_64BIT) /* All allocation sizes and addresses are aligned to 8 bytes. */ ALIGN_SIZE_LOG2 = 3, #else @@ -39,7 +39,7 @@ enum tlsf_private #endif ALIGN_SIZE = (1 << ALIGN_SIZE_LOG2), - /* +/* ** We support allocations of sizes up to (1 << FL_INDEX_MAX) bits. ** However, because we linearly subdivide the second-level lists, and ** our minimum size granularity is 4 bytes, it doesn't make sense to @@ -50,7 +50,7 @@ enum tlsf_private ** blocks below that size into the 0th first-level list. */ -#if defined (TLSF_64BIT) +#if defined(TLSF_64BIT) /* ** TODO: We can increase this to support larger sizes, at the expense ** of more overhead in the TLSF structure. @@ -70,14 +70,14 @@ enum tlsf_private ** Cast and min/max macros. */ -#define tlsf_cast(t, exp) ((t) (exp)) -#define tlsf_min(a, b) ((a) < (b) ? (a) : (b)) -#define tlsf_max(a, b) ((a) > (b) ? (a) : (b)) +#define tlsf_cast(t, exp) ((t)(exp)) +#define tlsf_min(a, b) ((a) < (b) ? (a) : (b)) +#define tlsf_max(a, b) ((a) > (b) ? (a) : (b)) /* ** Set assert macro, if it has not been provided by the user. */ -#if !defined (tlsf_assert) +#if !defined(tlsf_assert) #define tlsf_assert assert #endif @@ -85,10 +85,10 @@ enum tlsf_private ** Static assertion mechanism. */ -#define _tlsf_glue2(x, y) x ## y +#define _tlsf_glue2(x, y) x##y #define _tlsf_glue(x, y) _tlsf_glue2(x, y) #define tlsf_static_assert(exp) \ - typedef char _tlsf_glue(static_assert, __LINE__) [(exp) ? 1 : -1] + typedef char _tlsf_glue(static_assert, __LINE__)[(exp) ? 1 : -1] /* This code has been tested on 32- and 64-bit (LP/LLP) architectures. */ tlsf_static_assert(sizeof(int) * CHAR_BIT == 32); @@ -105,10 +105,11 @@ tlsf_static_assert(ALIGN_SIZE == SMALL_BLOCK_SIZE / SL_INDEX_COUNT); ** Data structures and associated constants. */ #ifdef DBG_TLSF_MALLOC -typedef struct { - const char* file; - const char* func; - const char* mname; +typedef struct +{ + const char *file; + const char *func; + const char *mname; unsigned int line; } alloc_info_t; #endif @@ -125,7 +126,7 @@ typedef struct { typedef struct block_header_t { /* Points to the previous physical block. */ - struct block_header_t* prev_phys_block; + struct block_header_t *prev_phys_block; #ifdef DBG_TLSF_MALLOC alloc_info_t alloc_info; @@ -135,8 +136,8 @@ typedef struct block_header_t size_t size; /* Next and previous free blocks. */ - struct block_header_t* next_free; - struct block_header_t* prev_free; + struct block_header_t *next_free; + struct block_header_t *prev_free; } block_header_t; /* @@ -153,14 +154,15 @@ static const size_t block_header_prev_free_bit = 1 << 1; ** The prev_phys_block field is stored *inside* the previous free block. */ #ifdef DBG_TLSF_MALLOC -static const size_t block_header_overhead = sizeof(size_t) + sizeof(alloc_info_t); +static const size_t block_header_overhead = + sizeof(size_t) + sizeof(alloc_info_t); #else static const size_t block_header_overhead = sizeof(size_t); #endif /* User data starts directly after the size field in a used block. */ static const size_t block_start_offset = - offsetof(block_header_t, size) + sizeof(size_t); + offsetof(block_header_t, size) + sizeof(size_t); /* ** A free block must be large enough to store its header minus the size of @@ -168,11 +170,20 @@ static const size_t block_start_offset = ** bits for FL_INDEX. */ static const size_t block_size_min = - sizeof(block_header_t) - sizeof(block_header_t*); + sizeof(block_header_t) - sizeof(block_header_t *); static const size_t block_size_max = tlsf_cast(size_t, 1) << FL_INDEX_MAX; -#define TLSF_INCREASE_REAL_USED(control, increment) do {control->real_used += (increment) ; control->max_used = tlsf_max(control->real_used, control->max_used);}while(0) -#define TLSF_INCREASE_FRAGMENTS(control) do {control->fragments++ ; control->max_fragments = tlsf_max(control->fragments, control->max_fragments);}while(0) +#define TLSF_INCREASE_REAL_USED(control, increment) \ + do { \ + control->real_used += (increment); \ + control->max_used = tlsf_max(control->real_used, control->max_used); \ + } while(0) +#define TLSF_INCREASE_FRAGMENTS(control) \ + do { \ + control->fragments++; \ + control->max_fragments = \ + tlsf_max(control->fragments, control->max_fragments); \ + } while(0) /* The TLSF control structure. */ typedef struct control_t @@ -190,7 +201,7 @@ typedef struct control_t unsigned int sl_bitmap[FL_INDEX_COUNT]; /* Head of free lists. */ - block_header_t* blocks[FL_INDEX_COUNT][SL_INDEX_COUNT]; + block_header_t *blocks[FL_INDEX_COUNT][SL_INDEX_COUNT]; } control_t; /* A type used for casting when doing pointer arithmetic. */ @@ -200,104 +211,106 @@ typedef ptrdiff_t tlsfptr_t; ** block_header_t member functions. */ -static size_t block_size(const block_header_t* block) +static size_t block_size(const block_header_t *block) { return block->size & ~(block_header_free_bit | block_header_prev_free_bit); } -static void block_set_size(block_header_t* block, size_t size) +static void block_set_size(block_header_t *block, size_t size) { const size_t oldsize = block->size; - block->size = size | (oldsize & (block_header_free_bit | block_header_prev_free_bit)); + block->size = + size + | (oldsize & (block_header_free_bit | block_header_prev_free_bit)); } -static int block_is_last(const block_header_t* block) +static int block_is_last(const block_header_t *block) { return 0 == block_size(block); } -static int block_is_free(const block_header_t* block) +static int block_is_free(const block_header_t *block) { - return tlsf_cast(int, block->size & block_header_free_bit); + return tlsf_cast(int, block->size &block_header_free_bit); } -static void block_set_free(block_header_t* block) +static void block_set_free(block_header_t *block) { block->size |= block_header_free_bit; } -static void block_set_used(block_header_t* block) +static void block_set_used(block_header_t *block) { block->size &= ~block_header_free_bit; } -static int block_is_prev_free(const block_header_t* block) +static int block_is_prev_free(const block_header_t *block) { - return tlsf_cast(int, block->size & block_header_prev_free_bit); + return tlsf_cast(int, block->size &block_header_prev_free_bit); } -static void block_set_prev_free(block_header_t* block) +static void block_set_prev_free(block_header_t *block) { block->size |= block_header_prev_free_bit; } -static void block_set_prev_used(block_header_t* block) +static void block_set_prev_used(block_header_t *block) { block->size &= ~block_header_prev_free_bit; } -static block_header_t* block_from_ptr(const void* ptr) +static block_header_t *block_from_ptr(const void *ptr) { - return tlsf_cast(block_header_t*, - tlsf_cast(unsigned char*, ptr) - block_start_offset); + return tlsf_cast(block_header_t *, + tlsf_cast(unsigned char *, ptr) - block_start_offset); } -static void* block_to_ptr(const block_header_t* block) +static void *block_to_ptr(const block_header_t *block) { - return tlsf_cast(void*, - tlsf_cast(unsigned char*, block) + block_start_offset); + return tlsf_cast( + void *, tlsf_cast(unsigned char *, block) + block_start_offset); } /* Return location of next block after block of given size. */ -static block_header_t* offset_to_block(const void* ptr, size_t size) +static block_header_t *offset_to_block(const void *ptr, size_t size) { - return tlsf_cast(block_header_t*, tlsf_cast(tlsfptr_t, ptr) + size); + return tlsf_cast(block_header_t *, tlsf_cast(tlsfptr_t, ptr) + size); } /* Return location of previous block. */ -static block_header_t* block_prev(const block_header_t* block) +static block_header_t *block_prev(const block_header_t *block) { return block->prev_phys_block; } /* Return location of next existing block. */ -static block_header_t* block_next(const block_header_t* block) +static block_header_t *block_next(const block_header_t *block) { - block_header_t* next = offset_to_block(block_to_ptr(block), - block_size(block) - sizeof(block_header_t*)); + block_header_t *next = offset_to_block( + block_to_ptr(block), block_size(block) - sizeof(block_header_t *)); tlsf_assert(!block_is_last(block)); return next; } /* Link a new block with its physical neighbor, return the neighbor. */ -static block_header_t* block_link_next(block_header_t* block) +static block_header_t *block_link_next(block_header_t *block) { - block_header_t* next = block_next(block); + block_header_t *next = block_next(block); next->prev_phys_block = block; return next; } -static void block_mark_as_free(block_header_t* block) +static void block_mark_as_free(block_header_t *block) { /* Link the block to the next block, first. */ - block_header_t* next = block_link_next(block); + block_header_t *next = block_link_next(block); block_set_prev_free(next); block_set_free(block); } -static void block_mark_as_used(block_header_t* block) +static void block_mark_as_used(block_header_t *block) { - block_header_t* next = block_next(block); + block_header_t *next = block_next(block); block_set_prev_used(next); block_set_used(block); } @@ -314,12 +327,12 @@ static size_t align_down(size_t x, size_t align) return x - (x & (align - 1)); } -static void* align_ptr(const void* ptr, size_t align) +static void *align_ptr(const void *ptr, size_t align) { const tlsfptr_t aligned = - (tlsf_cast(tlsfptr_t, ptr) + (align - 1)) & ~(align - 1); + (tlsf_cast(tlsfptr_t, ptr) + (align - 1)) & ~(align - 1); tlsf_assert(0 == (align & (align - 1)) && "must align to a power of two"); - return tlsf_cast(void*, aligned); + return tlsf_cast(void *, aligned); } /* @@ -329,8 +342,7 @@ static void* align_ptr(const void* ptr, size_t align) static size_t adjust_request_size(size_t size, size_t align) { size_t adjust = 0; - if (size && size < block_size_max) - { + if(size && size < block_size_max) { const size_t aligned = align_up(size, align); adjust = tlsf_max(aligned, block_size_min); } @@ -342,19 +354,17 @@ static size_t adjust_request_size(size_t size, size_t align) ** the documentation found in the white paper. */ -static void mapping_insert(size_t size, int* fli, int* sli) +static void mapping_insert(size_t size, int *fli, int *sli) { int fl, sl; - if (size < SMALL_BLOCK_SIZE) - { + if(size < SMALL_BLOCK_SIZE) { /* Store small blocks in first list. */ fl = 0; sl = tlsf_cast(int, size) / (SMALL_BLOCK_SIZE / SL_INDEX_COUNT); - } - else - { + } else { fl = tlsf_fls_sizet(size); - sl = tlsf_cast(int, size >> (fl - SL_INDEX_COUNT_LOG2)) ^ (1 << SL_INDEX_COUNT_LOG2); + sl = tlsf_cast(int, size >> (fl - SL_INDEX_COUNT_LOG2)) + ^ (1 << SL_INDEX_COUNT_LOG2); fl -= (FL_INDEX_SHIFT - 1); } *fli = fl; @@ -362,17 +372,18 @@ static void mapping_insert(size_t size, int* fli, int* sli) } /* This version rounds up to the next block size (for allocations) */ -static void mapping_search(size_t size, int* fli, int* sli) +static void mapping_search(size_t size, int *fli, int *sli) { - if (size >= (1 << SL_INDEX_COUNT_LOG2)) - { - const size_t round = (1 << (tlsf_fls_sizet(size) - SL_INDEX_COUNT_LOG2)) - 1; + if(size >= (1 << SL_INDEX_COUNT_LOG2)) { + const size_t round = + (1 << (tlsf_fls_sizet(size) - SL_INDEX_COUNT_LOG2)) - 1; size += round; } mapping_insert(size, fli, sli); } -static block_header_t* search_suitable_block(control_t* control, int* fli, int* sli) +static block_header_t *search_suitable_block( + control_t *control, int *fli, int *sli) { int fl = *fli; int sl = *sli; @@ -382,12 +393,10 @@ static block_header_t* search_suitable_block(control_t* control, int* fli, int* ** fl/sl index. */ unsigned int sl_map = control->sl_bitmap[fl] & (~0 << sl); - if (!sl_map) - { + if(!sl_map) { /* No block exists. Search in the next largest first-level list. */ const unsigned int fl_map = control->fl_bitmap & (~0 << (fl + 1)); - if (!fl_map) - { + if(!fl_map) { /* No free blocks available, memory has been exhausted. */ return 0; } @@ -405,28 +414,26 @@ static block_header_t* search_suitable_block(control_t* control, int* fli, int* } /* Remove a free block from the free list.*/ -static void remove_free_block(control_t* control, block_header_t* block, int fl, int sl) +static void remove_free_block( + control_t *control, block_header_t *block, int fl, int sl) { - block_header_t* prev = block->prev_free; - block_header_t* next = block->next_free; + block_header_t *prev = block->prev_free; + block_header_t *next = block->next_free; tlsf_assert(prev && "prev_free field can not be null"); tlsf_assert(next && "next_free field can not be null"); next->prev_free = prev; prev->next_free = next; /* If this block is the head of the free list, set new head. */ - if (control->blocks[fl][sl] == block) - { + if(control->blocks[fl][sl] == block) { control->blocks[fl][sl] = next; /* If the new head is null, clear the bitmap. */ - if (next == &control->block_null) - { + if(next == &control->block_null) { control->sl_bitmap[fl] &= ~(1 << sl); /* If the second bitmap is now empty, clear the fl bitmap. */ - if (!control->sl_bitmap[fl]) - { + if(!control->sl_bitmap[fl]) { control->fl_bitmap &= ~(1 << fl); } } @@ -435,17 +442,19 @@ static void remove_free_block(control_t* control, block_header_t* block, int fl, } /* Insert a free block into the free block list. */ -static void insert_free_block(control_t* control, block_header_t* block, int fl, int sl) +static void insert_free_block( + control_t *control, block_header_t *block, int fl, int sl) { - block_header_t* current = control->blocks[fl][sl]; + block_header_t *current = control->blocks[fl][sl]; tlsf_assert(current && "free list cannot have a null entry"); tlsf_assert(block && "cannot insert a null entry into the free list"); block->next_free = current; block->prev_free = &control->block_null; current->prev_free = block; - tlsf_assert(block_to_ptr(block) == align_ptr(block_to_ptr(block), ALIGN_SIZE) - && "block not aligned properly"); + tlsf_assert( + block_to_ptr(block) == align_ptr(block_to_ptr(block), ALIGN_SIZE) + && "block not aligned properly"); /* ** Insert the new block at the head of the list, and mark the first- ** and second-level bitmaps appropriately. @@ -457,7 +466,7 @@ static void insert_free_block(control_t* control, block_header_t* block, int fl, } /* Remove a given block from the free list. */ -static void block_remove(control_t* control, block_header_t* block) +static void block_remove(control_t *control, block_header_t *block) { int fl, sl; mapping_insert(block_size(block), &fl, &sl); @@ -465,31 +474,34 @@ static void block_remove(control_t* control, block_header_t* block) } /* Insert a given block into the free list. */ -static void block_insert(control_t* control, block_header_t* block) +static void block_insert(control_t *control, block_header_t *block) { int fl, sl; mapping_insert(block_size(block), &fl, &sl); insert_free_block(control, block, fl, sl); } -static int block_can_split(block_header_t* block, size_t size) +static int block_can_split(block_header_t *block, size_t size) { return block_size(block) >= sizeof(block_header_t) + size; } /* Split a block into two, the second of which is free. */ -static block_header_t* block_split(block_header_t* block, size_t size) +static block_header_t *block_split(block_header_t *block, size_t size) { /* Calculate the amount of space left in the remaining block. */ - block_header_t* remaining = - offset_to_block(block_to_ptr(block), size - sizeof(block_header_t*)); + block_header_t *remaining = offset_to_block( + block_to_ptr(block), size - sizeof(block_header_t *)); - const size_t remain_size = block_size(block) - (size + block_header_overhead); + const size_t remain_size = + block_size(block) - (size + block_header_overhead); - tlsf_assert(block_to_ptr(remaining) == align_ptr(block_to_ptr(remaining), ALIGN_SIZE) - && "remaining block not aligned properly"); + tlsf_assert(block_to_ptr(remaining) + == align_ptr(block_to_ptr(remaining), ALIGN_SIZE) + && "remaining block not aligned properly"); - tlsf_assert(block_size(block) == remain_size + size + block_header_overhead); + tlsf_assert( + block_size(block) == remain_size + size + block_header_overhead); block_set_size(remaining, remain_size); block_set_size(block, size); @@ -499,7 +511,7 @@ static block_header_t* block_split(block_header_t* block, size_t size) } /* Absorb a free block's storage into an adjacent previous free block. */ -static block_header_t* block_absorb(block_header_t* prev, block_header_t* block) +static block_header_t *block_absorb(block_header_t *prev, block_header_t *block) { tlsf_assert(!block_is_last(prev) && "previous block can't be last!"); /* Note: Leaves flags untouched. */ @@ -509,13 +521,14 @@ static block_header_t* block_absorb(block_header_t* prev, block_header_t* block) } /* Merge a just-freed block with an adjacent previous free block. */ -static block_header_t* block_merge_prev(control_t* control, block_header_t* block) +static block_header_t *block_merge_prev( + control_t *control, block_header_t *block) { - if (block_is_prev_free(block)) - { - block_header_t* prev = block_prev(block); + if(block_is_prev_free(block)) { + block_header_t *prev = block_prev(block); tlsf_assert(prev && "prev physical block can't be null"); - tlsf_assert(block_is_free(prev) && "prev block is not free though marked as such"); + tlsf_assert(block_is_free(prev) + && "prev block is not free though marked as such"); block_remove(control, prev); block = block_absorb(prev, block); } @@ -524,13 +537,13 @@ static block_header_t* block_merge_prev(control_t* control, block_header_t* bloc } /* Merge a just-freed block with an adjacent free block. */ -static block_header_t* block_merge_next(control_t* control, block_header_t* block) +static block_header_t *block_merge_next( + control_t *control, block_header_t *block) { - block_header_t* next = block_next(block); + block_header_t *next = block_next(block); tlsf_assert(next && "next physical block can't be null"); - if (block_is_free(next)) - { + if(block_is_free(next)) { tlsf_assert(!block_is_last(block) && "previous block can't be last!"); block_remove(control, next); block = block_absorb(block, next); @@ -540,12 +553,12 @@ static block_header_t* block_merge_next(control_t* control, block_header_t* bloc } /* Trim any trailing block space off the end of a block, return to pool. */ -static void block_trim_free(control_t* control, block_header_t* block, size_t size) +static void block_trim_free( + control_t *control, block_header_t *block, size_t size) { tlsf_assert(block_is_free(block) && "block must be free"); - if (block_can_split(block, size)) - { - block_header_t* remaining_block = block_split(block, size); + if(block_can_split(block, size)) { + block_header_t *remaining_block = block_split(block, size); block_link_next(block); block_set_prev_free(remaining_block); #ifdef DBG_TLSF_MALLOC @@ -558,13 +571,13 @@ static void block_trim_free(control_t* control, block_header_t* block, size_t si } /* Trim any trailing block space off the end of a used block, return to pool. */ -static void block_trim_used(control_t* control, block_header_t* block, size_t size) +static void block_trim_used( + control_t *control, block_header_t *block, size_t size) { tlsf_assert(!block_is_free(block) && "block must be used"); - if (block_can_split(block, size)) - { + if(block_can_split(block, size)) { /* If the next block is free, we must coalesce. */ - block_header_t* remaining_block = block_split(block, size); + block_header_t *remaining_block = block_split(block, size); block_set_prev_used(remaining_block); remaining_block = block_merge_next(control, remaining_block); @@ -577,19 +590,17 @@ static void block_trim_used(control_t* control, block_header_t* block, size_t si } } -static block_header_t* block_locate_free(control_t* control, size_t size) +static block_header_t *block_locate_free(control_t *control, size_t size) { int fl = 0, sl = 0; - block_header_t* block = 0; + block_header_t *block = 0; - if (size) - { + if(size) { mapping_search(size, &fl, &sl); block = search_suitable_block(control, &fl, &sl); } - if (block) - { + if(block) { tlsf_assert(block_size(block) >= size); remove_free_block(control, block, fl, sl); } @@ -597,21 +608,25 @@ static block_header_t* block_locate_free(control_t* control, size_t size) return block; } #ifdef DBG_TLSF_MALLOC -static void* block_prepare_used(control_t* control, block_header_t* block, size_t size, - const char *file, const char *function, unsigned long line, const char *mname) +static void *block_prepare_used(control_t *control, block_header_t *block, + size_t size, const char *file, const char *function, unsigned long line, + const char *mname) #else -static void* block_prepare_used(control_t* control, block_header_t* block, size_t size) +static void *block_prepare_used( + control_t *control, block_header_t *block, size_t size) #endif { - void* p = 0; - if (block) - { + void *p = 0; + if(block) { block_trim_free(control, block, size); block_mark_as_used(block); p = block_to_ptr(block); - TLSF_INCREASE_REAL_USED(control, block_size(block) + (p - (void *)block - /* prev_phys_block is melted in the previous block when the current block is used */ - + sizeof(block->prev_phys_block))); + TLSF_INCREASE_REAL_USED(control, + block_size(block) + + (p + - (void *)block + /* prev_phys_block is melted in the previous block when the current block is used */ + + sizeof(block->prev_phys_block))); control->allocated += block_size(block); #ifdef DBG_TLSF_MALLOC block->alloc_info.file = file; @@ -624,7 +639,7 @@ static void* block_prepare_used(control_t* control, block_header_t* block, size_ } /* Clear structure and point all empty lists at the null block. */ -static void control_construct(control_t* control) +static void control_construct(control_t *control) { int i, j; @@ -632,11 +647,9 @@ static void control_construct(control_t* control) control->block_null.prev_free = &control->block_null; control->fl_bitmap = 0; - for (i = 0; i < FL_INDEX_COUNT; ++i) - { + for(i = 0; i < FL_INDEX_COUNT; ++i) { control->sl_bitmap[i] = 0; - for (j = 0; j < SL_INDEX_COUNT; ++j) - { + for(j = 0; j < SL_INDEX_COUNT; ++j) { control->blocks[i][j] = &control->block_null; } } @@ -652,18 +665,25 @@ typedef struct integrity_t int status; } integrity_t; -#define tlsf_insist(x) { tlsf_assert(x); if (!(x)) { status--; } } +#define tlsf_insist(x) \ + { \ + tlsf_assert(x); \ + if(!(x)) { \ + status--; \ + } \ + } -static void integrity_walker(void* ptr, size_t size, int used, void* user) +static void integrity_walker(void *ptr, size_t size, int used, void *user) { - block_header_t* block = block_from_ptr(ptr); - integrity_t* integ = tlsf_cast(integrity_t*, user); + block_header_t *block = block_from_ptr(ptr); + integrity_t *integ = tlsf_cast(integrity_t *, user); const int this_prev_status = block_is_prev_free(block) ? 1 : 0; const int this_status = block_is_free(block) ? 1 : 0; const size_t this_block_size = block_size(block); int status = 0; - tlsf_insist(integ->prev_status == this_prev_status && "prev status incorrect"); + tlsf_insist( + integ->prev_status == this_prev_status && "prev status incorrect"); tlsf_insist(size == this_block_size && "block size incorrect"); integ->prev_status = this_status; @@ -674,46 +694,48 @@ int tlsf_check(tlsf_t tlsf) { int i, j; - control_t* control = tlsf_cast(control_t*, tlsf); + control_t *control = tlsf_cast(control_t *, tlsf); int status = 0; /* Check that the free lists and bitmaps are accurate. */ - for (i = 0; i < FL_INDEX_COUNT; ++i) - { - for (j = 0; j < SL_INDEX_COUNT; ++j) - { + for(i = 0; i < FL_INDEX_COUNT; ++i) { + for(j = 0; j < SL_INDEX_COUNT; ++j) { const int fl_map = control->fl_bitmap & (1 << i); const int sl_list = control->sl_bitmap[i]; const int sl_map = sl_list & (1 << j); - const block_header_t* block = control->blocks[i][j]; + const block_header_t *block = control->blocks[i][j]; /* Check that first- and second-level lists agree. */ - if (!fl_map) - { + if(!fl_map) { tlsf_insist(!sl_map && "second-level map must be null"); } - if (!sl_map) - { - tlsf_insist(block == &control->block_null && "block list must be null"); + if(!sl_map) { + tlsf_insist(block == &control->block_null + && "block list must be null"); continue; } /* Check that there is at least one free block. */ tlsf_insist(sl_list && "no free blocks in second-level map"); - tlsf_insist(block != &control->block_null && "block should not be null"); + tlsf_insist(block != &control->block_null + && "block should not be null"); - while (block != &control->block_null) - { + while(block != &control->block_null) { int fli, sli; tlsf_insist(block_is_free(block) && "block should be free"); - tlsf_insist(!block_is_prev_free(block) && "blocks should have coalesced"); - tlsf_insist(!block_is_free(block_next(block)) && "blocks should have coalesced"); - tlsf_insist(block_is_prev_free(block_next(block)) && "block should be free"); - tlsf_insist(block_size(block) >= block_size_min && "block not minimum size"); + tlsf_insist(!block_is_prev_free(block) + && "blocks should have coalesced"); + tlsf_insist(!block_is_free(block_next(block)) + && "blocks should have coalesced"); + tlsf_insist(block_is_prev_free(block_next(block)) + && "block should be free"); + tlsf_insist(block_size(block) >= block_size_min + && "block not minimum size"); mapping_insert(block_size(block), &fli, &sli); - tlsf_insist(fli == i && sli == j && "block size indexed in wrong list"); + tlsf_insist(fli == i && sli == j + && "block size indexed in wrong list"); block = block->next_free; } } @@ -724,34 +746,30 @@ int tlsf_check(tlsf_t tlsf) #undef tlsf_insist -static void default_walker(void* ptr, size_t size, int used, void* user) +static void default_walker(void *ptr, size_t size, int used, void *user) { (void)user; - printf("\t%p %s size: %x (%p)\n", ptr, used ? "used" : "free", (unsigned int)size, block_from_ptr(ptr)); + printf("\t%p %s size: %x (%p)\n", ptr, used ? "used" : "free", + (unsigned int)size, block_from_ptr(ptr)); } -void tlsf_walk_pool(pool_t pool, tlsf_walker walker, void* user) +void tlsf_walk_pool(pool_t pool, tlsf_walker walker, void *user) { tlsf_walker pool_walker = walker ? walker : default_walker; - block_header_t* block = pool + tlsf_size() - sizeof(block_header_t*); - - while (block && !block_is_last(block)) - { - pool_walker( - block_to_ptr(block), - block_size(block), - !block_is_free(block), - user); + block_header_t *block = pool + tlsf_size() - sizeof(block_header_t *); + + while(block && !block_is_last(block)) { + pool_walker(block_to_ptr(block), block_size(block), + !block_is_free(block), user); block = block_next(block); } } -size_t tlsf_block_size(void* ptr) +size_t tlsf_block_size(void *ptr) { size_t size = 0; - if (ptr) - { - const block_header_t* block = block_from_ptr(ptr); + if(ptr) { + const block_header_t *block = block_from_ptr(ptr); size = block_size(block); } return size; @@ -760,7 +778,7 @@ size_t tlsf_block_size(void* ptr) int tlsf_check_pool(pool_t pool) { /* Check that the blocks are physically correct. */ - integrity_t integ = { 0, 0 }; + integrity_t integ = {0, 0}; tlsf_walk_pool(pool, integrity_walker, &integ); return integ.status; @@ -805,31 +823,30 @@ size_t tlsf_alloc_overhead() return block_header_overhead; } -pool_t tlsf_add_pool(tlsf_t tlsf, void* mem, size_t bytes) +pool_t tlsf_add_pool(tlsf_t tlsf, void *mem, size_t bytes) { - block_header_t* block; - block_header_t* next; + block_header_t *block; + block_header_t *next; const size_t pool_overhead = tlsf_pool_overhead(); const size_t pool_bytes = align_down(bytes - pool_overhead, ALIGN_SIZE); - if (((ptrdiff_t)mem % ALIGN_SIZE) != 0) - { + if(((ptrdiff_t)mem % ALIGN_SIZE) != 0) { printf("tlsf_add_pool: Memory must be aligned by %u bytes.\n", - (unsigned int)ALIGN_SIZE); + (unsigned int)ALIGN_SIZE); return 0; } - if (pool_bytes < block_size_min || pool_bytes > block_size_max) - { -#if defined (TLSF_64BIT) - printf("tlsf_add_pool: Memory size must be between 0x%x and 0x%x00 bytes.\n", - (unsigned int)(pool_overhead + block_size_min), - (unsigned int)((pool_overhead + block_size_max) / 256)); + if(pool_bytes < block_size_min || pool_bytes > block_size_max) { +#if defined(TLSF_64BIT) + printf("tlsf_add_pool: Memory size must be between 0x%x and 0x%x00 " + "bytes.\n", + (unsigned int)(pool_overhead + block_size_min), + (unsigned int)((pool_overhead + block_size_max) / 256)); #else printf("tlsf_add_pool: Memory size must be between %u and %u bytes.\n", - (unsigned int)(pool_overhead + block_size_min), - (unsigned int)(pool_overhead + block_size_max)); + (unsigned int)(pool_overhead + block_size_min), + (unsigned int)(pool_overhead + block_size_max)); #endif return 0; } @@ -839,12 +856,14 @@ pool_t tlsf_add_pool(tlsf_t tlsf, void* mem, size_t bytes) ** so that the prev_phys_block field falls outside of the pool - ** it will never be used. */ - block = mem - sizeof (size_t);/*offset_to_block(mem, -(tlsfptr_t)block_header_overhead);*/ + block = mem + - sizeof( + size_t); /*offset_to_block(mem, -(tlsfptr_t)block_header_overhead);*/ block_set_size(block, pool_bytes); block_set_free(block); block_set_prev_used(block); - block_insert(tlsf_cast(control_t*, tlsf), block); - tlsf_cast(control_t*, tlsf)->total_size += block_size(block); + block_insert(tlsf_cast(control_t *, tlsf), block); + tlsf_cast(control_t *, tlsf)->total_size += block_size(block); #ifdef DBG_TLSF_MALLOC block->alloc_info.file = _SRC_LOC_; block->alloc_info.func = _SRC_FUNCTION_; @@ -861,18 +880,20 @@ pool_t tlsf_add_pool(tlsf_t tlsf, void* mem, size_t bytes) void tlsf_remove_pool(tlsf_t tlsf, pool_t pool) { - control_t* control = tlsf_cast(control_t*, tlsf); - block_header_t* block = offset_to_block(pool, -(int)block_header_overhead); + control_t *control = tlsf_cast(control_t *, tlsf); + block_header_t *block = offset_to_block(pool, -(int)block_header_overhead); int fl = 0, sl = 0; tlsf_assert(block_is_free(block) && "block should be free"); - tlsf_assert(!block_is_free(block_next(block)) && "next block should not be free"); - tlsf_assert(block_size(block_next(block)) == 0 && "next block size should be zero"); + tlsf_assert(!block_is_free(block_next(block)) + && "next block should not be free"); + tlsf_assert(block_size(block_next(block)) == 0 + && "next block size should be zero"); mapping_insert(block_size(block), &fl, &sl); remove_free_block(control, block, fl, sl); - tlsf_cast(control_t*, tlsf)->total_size -= block_size(block); + tlsf_cast(control_t *, tlsf)->total_size -= block_size(block); } /* @@ -893,52 +914,49 @@ int test_ffs_fls() rv += (tlsf_fls(0x80000008) == 31) ? 0 : 0x40; rv += (tlsf_fls(0x7FFFFFFF) == 30) ? 0 : 0x80; -#if defined (TLSF_64BIT) +#if defined(TLSF_64BIT) rv += (tlsf_fls_sizet(0x80000000) == 31) ? 0 : 0x100; rv += (tlsf_fls_sizet(0x100000000) == 32) ? 0 : 0x200; rv += (tlsf_fls_sizet(0xffffffffffffffff) == 63) ? 0 : 0x400; #endif - if (rv) - { + if(rv) { printf("tlsf_create: %x ffs/fls tests failed!\n", rv); } return rv; } #endif -tlsf_t tlsf_create(void* mem) +tlsf_t tlsf_create(void *mem) { #if _DEBUG - if (test_ffs_fls()) - { + if(test_ffs_fls()) { return 0; } #endif - if (((tlsfptr_t)mem % ALIGN_SIZE) != 0) - { + if(((tlsfptr_t)mem % ALIGN_SIZE) != 0) { printf("tlsf_create: Memory must be aligned to %u bytes.\n", - (unsigned int)ALIGN_SIZE); + (unsigned int)ALIGN_SIZE); return 0; } - control_construct(tlsf_cast(control_t*, mem)); - tlsf_cast(control_t*, mem)->real_used = tlsf_size(); - tlsf_cast(control_t*, mem)->max_used = tlsf_size(); - tlsf_cast(control_t*, mem)->allocated = 0; - tlsf_cast(control_t*, mem)->total_size = tlsf_size(); - tlsf_cast(control_t*, mem)->fragments = 0; - tlsf_cast(control_t*, mem)->max_fragments = 0; + control_construct(tlsf_cast(control_t *, mem)); + tlsf_cast(control_t *, mem)->real_used = tlsf_size(); + tlsf_cast(control_t *, mem)->max_used = tlsf_size(); + tlsf_cast(control_t *, mem)->allocated = 0; + tlsf_cast(control_t *, mem)->total_size = tlsf_size(); + tlsf_cast(control_t *, mem)->fragments = 0; + tlsf_cast(control_t *, mem)->max_fragments = 0; return tlsf_cast(tlsf_t, mem); } -tlsf_t tlsf_create_with_pool(void* mem, size_t bytes) +tlsf_t tlsf_create_with_pool(void *mem, size_t bytes) { tlsf_t tlsf = tlsf_create(mem); if(tlsf) { pool_t p; - p = tlsf_add_pool(tlsf, (char*)mem + tlsf_size(), bytes - tlsf_size()); + p = tlsf_add_pool(tlsf, (char *)mem + tlsf_size(), bytes - tlsf_size()); if(!p) { return NULL; } @@ -954,26 +972,27 @@ void tlsf_destroy(tlsf_t tlsf) pool_t tlsf_get_pool(tlsf_t tlsf) { - return tlsf_cast(pool_t, (char*)tlsf + tlsf_size()); + return tlsf_cast(pool_t, (char *)tlsf + tlsf_size()); } #ifdef DBG_TLSF_MALLOC -void* tlsf_malloc(tlsf_t tlsf, size_t size, - const char *file, const char *function, unsigned int line, const char *mname) +void *tlsf_malloc(tlsf_t tlsf, size_t size, const char *file, + const char *function, unsigned int line, const char *mname) #else -void* tlsf_malloc(tlsf_t tlsf, size_t size) +void *tlsf_malloc(tlsf_t tlsf, size_t size) #endif { - control_t* control = tlsf_cast(control_t*, tlsf); - const size_t adjust = adjust_request_size(size?size:4, ALIGN_SIZE); - block_header_t* block = block_locate_free(control, adjust); + control_t *control = tlsf_cast(control_t *, tlsf); + const size_t adjust = adjust_request_size(size ? size : 4, ALIGN_SIZE); + block_header_t *block = block_locate_free(control, adjust); #ifdef DBG_TLSF_MALLOC void *ptr; - MDBG("tlsf_malloc(%p, %zu) called from %s: %s(%u)\n", tlsf, size, file, function, line); - ptr = block_prepare_used(control, block, adjust, file, function, line, mname); - MDBG("tlsf_malloc(%p, %zu) returns address %p \n", tlsf, size, - ptr); + MDBG("tlsf_malloc(%p, %zu) called from %s: %s(%u)\n", tlsf, size, file, + function, line); + ptr = block_prepare_used( + control, block, adjust, file, function, line, mname); + MDBG("tlsf_malloc(%p, %zu) returns address %p \n", tlsf, size, ptr); return ptr; #else return block_prepare_used(control, block, adjust); @@ -982,10 +1001,10 @@ void* tlsf_malloc(tlsf_t tlsf, size_t size) #ifdef DBG_TLSF_MALLOC -void* tlsf_mallocxz(tlsf_t tlsf, size_t size, - const char *file, const char *function, unsigned int line, const char *mname) +void *tlsf_mallocxz(tlsf_t tlsf, size_t size, const char *file, + const char *function, unsigned int line, const char *mname) #else -void* tlsf_mallocxz(tlsf_t tlsf, size_t size) +void *tlsf_mallocxz(tlsf_t tlsf, size_t size) #endif { void *p; @@ -996,48 +1015,53 @@ void* tlsf_mallocxz(tlsf_t tlsf, size_t size) p = tlsf_malloc(tlsf, size); #endif - if(p) memset(p, 0, size); + if(p) + memset(p, 0, size); return p; } #ifdef DBG_TLSF_MALLOC -void tlsf_free(tlsf_t tlsf, void* ptr, - const char *file, const char *function, unsigned int line, const char *mname) +void tlsf_free(tlsf_t tlsf, void *ptr, const char *file, const char *function, + unsigned int line, const char *mname) #else -void tlsf_free(tlsf_t tlsf, void* ptr) +void tlsf_free(tlsf_t tlsf, void *ptr) #endif { #ifdef DBG_TLSF_MALLOC - MDBG("tlsf_free(%p, %p), called from %s: %s(%u)\n", tlsf, ptr, file, function, line); + MDBG("tlsf_free(%p, %p), called from %s: %s(%u)\n", tlsf, ptr, file, + function, line); #endif /* Don't attempt to free a NULL pointer. */ - if (ptr) - { - control_t* control = tlsf_cast(control_t*, tlsf); - block_header_t* block = block_from_ptr(ptr); - if (block_is_free(block)) { - LOG(L_CRIT, "BUG: tlsf_free: freeing already freed pointer (%p)" + if(ptr) { + control_t *control = tlsf_cast(control_t *, tlsf); + block_header_t *block = block_from_ptr(ptr); + if(block_is_free(block)) { + LOG(L_CRIT, + "BUG: tlsf_free: freeing already freed pointer (%p)" #ifdef DBG_TLSF_MALLOC ", called from %s: %s(%u)" ", first free %s: %s(%u)\n", - ptr, file, function, line, - block->alloc_info.file, block->alloc_info.func, block->alloc_info.line); + ptr, file, function, line, block->alloc_info.file, + block->alloc_info.func, block->alloc_info.line); #else - "\n", ptr); + "\n", + ptr); #endif - if(likely(cfg_get(core, core_cfg, mem_safety)==0)) { + if(likely(cfg_get(core, core_cfg, mem_safety) == 0)) { abort(); } else { return; } - } control->allocated -= block_size(block); - control->real_used -= (block_size(block) + (ptr - (void *)block - /* prev_phys_block is melted in the previous block when the current block is used */ - + sizeof(block->prev_phys_block))); + control->real_used -= + (block_size(block) + + (ptr + - (void *)block + /* prev_phys_block is melted in the previous block when the current block is used */ + + sizeof(block->prev_phys_block))); #ifdef DBG_TLSF_MALLOC block->alloc_info.file = file; block->alloc_info.func = function; @@ -1050,7 +1074,8 @@ void tlsf_free(tlsf_t tlsf, void* ptr) block_insert(control, block); } else { #ifdef DBG_TLSF_MALLOC - LOG(L_WARN, "tlsf_free: free(0) called from %s: %s(%u)\n", file, function, line); + LOG(L_WARN, "tlsf_free: free(0) called from %s: %s(%u)\n", file, + function, line); #else LOG(L_WARN, "tlsf_free: free(0) called\n"); #endif @@ -1071,18 +1096,17 @@ void tlsf_free(tlsf_t tlsf, void* ptr) ** contents undefined */ #ifdef DBG_TLSF_MALLOC -void* tlsf_realloc(tlsf_t tlsf, void* ptr, size_t size, - const char *file, const char *function, unsigned int line, const char *mname) +void *tlsf_realloc(tlsf_t tlsf, void *ptr, size_t size, const char *file, + const char *function, unsigned int line, const char *mname) #else -void* tlsf_realloc(tlsf_t tlsf, void* ptr, size_t size) +void *tlsf_realloc(tlsf_t tlsf, void *ptr, size_t size) #endif { - control_t* control = tlsf_cast(control_t*, tlsf); - void* p = 0; + control_t *control = tlsf_cast(control_t *, tlsf); + void *p = 0; /* Zero-size requests are treated as free. */ - if (ptr && size == 0) - { + if(ptr && size == 0) { #ifdef DBG_TLSF_MALLOC tlsf_free(tlsf, ptr, file, function, line, mname); #else @@ -1090,21 +1114,19 @@ void* tlsf_realloc(tlsf_t tlsf, void* ptr, size_t size) #endif } /* Requests with NULL pointers are treated as malloc. */ - else if (!ptr) - { + else if(!ptr) { #ifdef DBG_TLSF_MALLOC p = tlsf_malloc(tlsf, size, file, function, line, mname); #else p = tlsf_malloc(tlsf, size); #endif - } - else - { - block_header_t* block = block_from_ptr(ptr); - block_header_t* next = block_next(block); + } else { + block_header_t *block = block_from_ptr(ptr); + block_header_t *next = block_next(block); const size_t cursize = block_size(block); - const size_t combined = cursize + block_size(next) + block_header_overhead; + const size_t combined = + cursize + block_size(next) + block_header_overhead; const size_t adjust = adjust_request_size(size, ALIGN_SIZE); tlsf_assert(!block_is_free(block) && "block already marked as free"); @@ -1113,15 +1135,13 @@ void* tlsf_realloc(tlsf_t tlsf, void* ptr, size_t size) ** If the next block is used, or when combined with the current ** block, does not offer enough space, we must reallocate and copy. */ - if (adjust > cursize && (!block_is_free(next) || adjust > combined)) - { + if(adjust > cursize && (!block_is_free(next) || adjust > combined)) { #ifdef DBG_TLSF_MALLOC p = tlsf_malloc(tlsf, size, file, function, line, mname); #else p = tlsf_malloc(tlsf, size); #endif - if (p) - { + if(p) { const size_t minsize = tlsf_min(cursize, size); memcpy(p, ptr, minsize); #ifdef DBG_TLSF_MALLOC @@ -1130,14 +1150,11 @@ void* tlsf_realloc(tlsf_t tlsf, void* ptr, size_t size) tlsf_free(tlsf, ptr); #endif } - } - else - { + } else { control->allocated -= block_size(block); control->real_used -= block_size(block); /* Do we need to expand to the next block? */ - if (adjust > cursize) - { + if(adjust > cursize) { block_merge_next(control, block); block_mark_as_used(block); } @@ -1145,7 +1162,7 @@ void* tlsf_realloc(tlsf_t tlsf, void* ptr, size_t size) /* Trim the resulting block and return the original pointer. */ block_trim_used(control, block, adjust); p = ptr; - control->allocated +=block_size(block); + control->allocated += block_size(block); TLSF_INCREASE_REAL_USED(control, block_size(block)); } } @@ -1154,10 +1171,10 @@ void* tlsf_realloc(tlsf_t tlsf, void* ptr, size_t size) } #ifdef DBG_TLSF_MALLOC -void* tlsf_reallocxf(tlsf_t tlsf, void* ptr, size_t size, - const char *file, const char *function, unsigned int line, const char *mname) +void *tlsf_reallocxf(tlsf_t tlsf, void *ptr, size_t size, const char *file, + const char *function, unsigned int line, const char *mname) #else -void* tlsf_reallocxf(tlsf_t tlsf, void* ptr, size_t size) +void *tlsf_reallocxf(tlsf_t tlsf, void *ptr, size_t size) #endif { void *r; @@ -1169,12 +1186,11 @@ void* tlsf_reallocxf(tlsf_t tlsf, void* ptr, size_t size) #endif if(!r && ptr) { - #ifdef DBG_TLSF_MALLOC +#ifdef DBG_TLSF_MALLOC tlsf_free(tlsf, ptr, file, function, line, mname); - #else +#else tlsf_free(tlsf, ptr); - #endif - +#endif } return r; @@ -1182,7 +1198,7 @@ void* tlsf_reallocxf(tlsf_t tlsf, void* ptr, size_t size) void tlsf_meminfo(tlsf_t pool, struct mem_info *info) { - control_t* control = tlsf_cast(control_t*, pool); + control_t *control = tlsf_cast(control_t *, pool); memset(info, 0, sizeof(*info)); info->free_size = control->total_size - control->real_used; info->max_used = control->max_used; @@ -1194,7 +1210,7 @@ void tlsf_meminfo(tlsf_t pool, struct mem_info *info) unsigned long tlsf_available(tlsf_t pool) { - control_t* control = tlsf_cast(control_t*, pool); + control_t *control = tlsf_cast(control_t *, pool); return (unsigned long)(control->total_size - control->real_used); } @@ -1203,62 +1219,71 @@ void tlsf_status(tlsf_t pool) int memlog, fl, sl; unsigned int len; char summary[FL_INDEX_COUNT]; - control_t* control = tlsf_cast(control_t*, pool); - block_header_t* pb; + control_t *control = tlsf_cast(control_t *, pool); + block_header_t *pb; - memlog=cfg_get(core, core_cfg, memlog); - LOG_FP(DEFAULT_FACILITY, memlog, "tlsf_status: ", "status of pool (%p):\n", pool); + memlog = cfg_get(core, core_cfg, memlog); + LOG_FP(DEFAULT_FACILITY, memlog, "tlsf_status: ", "status of pool (%p):\n", + pool); LOG_FP(DEFAULT_FACILITY, memlog, "tlsf_status: ", "heap size= %zu\n", control->total_size); LOG_FP(DEFAULT_FACILITY, memlog, "tlsf_status: ", "used= %zu, used+overhead=%zu, free=%zu, fragments=%zu\n", - control->allocated, control->real_used, control->total_size - control->real_used, control->fragments); - LOG_FP(DEFAULT_FACILITY, memlog, "tlsf_status: ", - "max used (+overhead)=%zu, max fragments=%zu\n", control->max_used, control->max_fragments); + control->allocated, control->real_used, + control->total_size - control->real_used, control->fragments); + LOG_FP(DEFAULT_FACILITY, memlog, + "tlsf_status: ", "max used (+overhead)=%zu, max fragments=%zu\n", + control->max_used, control->max_fragments); /* print a summary of the 2 levels bucket list */ LOG_FP(DEFAULT_FACILITY, memlog, "tlsf_status: ", - "Free blocks matrix ('.': none, 'X': between 2^X and (2^(X+1)-1) free blocks, X=A..Z, A=0, B=1, ...)\n"); + "Free blocks matrix ('.': none, 'X': between 2^X and (2^(X+1)-1) " + "free blocks, X=A..Z, A=0, B=1, ...)\n"); LOG_FP(DEFAULT_FACILITY, memlog, "tlsf_status: ", - "> first-level: %d block list arrays between 2^fl and 2^(fl+1) bytes (fl=%d..%d)\n", - FL_INDEX_COUNT, FL_INDEX_SHIFT, FL_INDEX_MAX); + "> first-level: %d block list arrays between 2^fl and 2^(fl+1) " + "bytes (fl=%d..%d)\n", + FL_INDEX_COUNT, FL_INDEX_SHIFT, FL_INDEX_MAX); LOG_FP(DEFAULT_FACILITY, memlog, "tlsf_status: ", - "v second-level: %d block lists between 2^fl+sl*2^(fl-%d) and 2^fl+(sl+1)*2^(fl-%d)-1 bytes (sl=0..%d)\n", - SL_INDEX_COUNT, SL_INDEX_COUNT_LOG2, SL_INDEX_COUNT_LOG2, SL_INDEX_COUNT-1); - for (sl = 0 ; sl < SL_INDEX_COUNT ; sl++) { - for (fl = 0 ; fl < FL_INDEX_COUNT ; fl++) { - if (control->blocks[fl][sl] == &control->block_null) { + "v second-level: %d block lists between 2^fl+sl*2^(fl-%d) and " + "2^fl+(sl+1)*2^(fl-%d)-1 bytes (sl=0..%d)\n", + SL_INDEX_COUNT, SL_INDEX_COUNT_LOG2, SL_INDEX_COUNT_LOG2, + SL_INDEX_COUNT - 1); + for(sl = 0; sl < SL_INDEX_COUNT; sl++) { + for(fl = 0; fl < FL_INDEX_COUNT; fl++) { + if(control->blocks[fl][sl] == &control->block_null) { summary[fl] = '.'; } else { /* count free list length */ len = 1; pb = control->blocks[fl][sl]; - while (pb->next_free != &control->block_null) { + while(pb->next_free != &control->block_null) { pb = pb->next_free; len++; } summary[fl] = 'A' + tlsf_fls(len); } } - LOG_FP(DEFAULT_FACILITY, memlog, "tlsf_status: ", - "%2d|%.*s|\n", sl, FL_INDEX_COUNT, summary); + LOG_FP(DEFAULT_FACILITY, memlog, "tlsf_status: ", "%2d|%.*s|\n", sl, + FL_INDEX_COUNT, summary); } } #ifdef DBG_TLSF_MALLOC -static mem_counter* get_mem_counter(mem_counter **root, block_header_t* f) +static mem_counter *get_mem_counter(mem_counter **root, block_header_t *f) { mem_counter *x; - if (!*root) goto make_new; - for(x=*root;x;x=x->next) - if (x->file == f->alloc_info.file && x->func == f->alloc_info.func && x->line == f->alloc_info.line) + if(!*root) + goto make_new; + for(x = *root; x; x = x->next) + if(x->file == f->alloc_info.file && x->func == f->alloc_info.func + && x->line == f->alloc_info.line) return x; make_new: x = malloc(sizeof(mem_counter)); x->file = f->alloc_info.file; x->func = f->alloc_info.func; - x->mname= f->alloc_info.mname; + x->mname = f->alloc_info.mname; x->line = f->alloc_info.line; x->count = 0; x->size = 0; @@ -1271,59 +1296,56 @@ static mem_counter* get_mem_counter(mem_counter **root, block_header_t* f) void tlsf_sums(tlsf_t pool) { int memlog; - block_header_t* block = pool + tlsf_size() - sizeof(block_header_t*); + block_header_t *block = pool + tlsf_size() - sizeof(block_header_t *); mem_counter *root = NULL, *x; - memlog=cfg_get(core, core_cfg, memlog); + memlog = cfg_get(core, core_cfg, memlog); - LOG_FP(DEFAULT_FACILITY, memlog, "tlsf_sums: ", - "pool (%p) summarizing all alloc'ed. fragments:\n", pool); + LOG_FP(DEFAULT_FACILITY, memlog, + "tlsf_sums: ", "pool (%p) summarizing all alloc'ed. fragments:\n", + pool); - while (block && !block_is_last(block)) - { + while(block && !block_is_last(block)) { if(!block_is_free(block)) { x = get_mem_counter(&root, block); x->count++; - x->size+=block_size(block); + x->size += block_size(block); } block = block_next(block); } x = root; - while(x){ - LOG_FP(DEFAULT_FACILITY, memlog, "tlsf_sums: ", - " count=%6d size=%10lu bytes from %s: %s(%ld)\n", - x->count,x->size, - x->file, x->func, x->line - ); + while(x) { + LOG_FP(DEFAULT_FACILITY, memlog, + "tlsf_sums: ", " count=%6d size=%10lu bytes from %s: %s(%ld)\n", + x->count, x->size, x->file, x->func, x->line); root = x->next; free(x); x = root; } - LOG_FP(DEFAULT_FACILITY, memlog, "tlsf_sums: ", - "-----------------------------\n"); + LOG_FP(DEFAULT_FACILITY, memlog, + "tlsf_sums: ", "-----------------------------\n"); } void tlsf_mod_get_stats(tlsf_t pool, void **rootp) { - if (!rootp) { - return ; + if(!rootp) { + return; } LM_DBG("get tlsf memory statistics\n"); - mem_counter **root = (mem_counter **) rootp; - block_header_t* block = pool + tlsf_size() - sizeof(block_header_t*); + mem_counter **root = (mem_counter **)rootp; + block_header_t *block = pool + tlsf_size() - sizeof(block_header_t *); mem_counter *x; - while (block && !block_is_last(block)) - { + while(block && !block_is_last(block)) { if(!block_is_free(block)) { x = get_mem_counter(root, block); x->count++; - x->size+=block_size(block); + x->size += block_size(block); } block = block_next(block); @@ -1332,16 +1354,16 @@ void tlsf_mod_get_stats(tlsf_t pool, void **rootp) void tlsf_mod_free_stats(void *rootp) { - if (!rootp) { - return ; + if(!rootp) { + return; } LM_DBG("free tlsf memory statistics\n"); - mem_counter *root = (mem_counter *) rootp; + mem_counter *root = (mem_counter *)rootp; mem_counter *x; x = root; - while (x) { + while(x) { root = x->next; free(x); x = root; @@ -1350,18 +1372,19 @@ void tlsf_mod_free_stats(void *rootp) #else void tlsf_sums(tlsf_t pool) -{} +{ +} void tlsf_mod_get_stats(tlsf_t pool, void **rootp) { LM_WARN("Enable DBG_TLSF_MALLOC for getting statistics\n"); - return ; + return; } void tlsf_mod_free_stats(void *rootp) { LM_WARN("Enable DBG_TLSF_MALLOC for freeing statistics\n"); - return ; + return; } #endif /* defined DBG_TLSF_MALLOC */ @@ -1377,7 +1400,7 @@ static tlsf_t _tlsf_pkg_block = 0; */ void tlsf_malloc_destroy_pkg_manager(void) { - if (_tlsf_pkg_pool) { + if(_tlsf_pkg_pool) { free(_tlsf_pkg_pool); _tlsf_pkg_pool = 0; } @@ -1391,36 +1414,37 @@ int tlsf_malloc_init_pkg_manager(void) { sr_pkg_api_t ma; _tlsf_pkg_pool = malloc(pkg_mem_size); - if (_tlsf_pkg_pool) { + if(_tlsf_pkg_pool) { _tlsf_pkg_block = tlsf_create_with_pool(_tlsf_pkg_pool, pkg_mem_size); - if(_tlsf_pkg_block==NULL) { + if(_tlsf_pkg_block == NULL) { LM_CRIT("could not create tlsf pkg memory pool\n"); - fprintf(stderr, "could not create tlsf pkg memory pool: %ld bytes\n", - pkg_mem_size); + fprintf(stderr, + "could not create tlsf pkg memory pool: %ld bytes\n", + pkg_mem_size); return -1; } } else { LOG(L_CRIT, "could not initialize tlsf pkg memory pool\n"); fprintf(stderr, "Too much tlsf pkg memory demanded: %ld bytes\n", - pkg_mem_size); + pkg_mem_size); return -1; } memset(&ma, 0, sizeof(sr_pkg_api_t)); - ma.mname = _tlsf_mem_name; - ma.mem_pool = _tlsf_pkg_pool; - ma.mem_block = _tlsf_pkg_block; - ma.xmalloc = tlsf_malloc; - ma.xmallocxz = tlsf_mallocxz; - ma.xfree = tlsf_free; - ma.xrealloc = tlsf_realloc; + ma.mname = _tlsf_mem_name; + ma.mem_pool = _tlsf_pkg_pool; + ma.mem_block = _tlsf_pkg_block; + ma.xmalloc = tlsf_malloc; + ma.xmallocxz = tlsf_mallocxz; + ma.xfree = tlsf_free; + ma.xrealloc = tlsf_realloc; ma.xreallocxf = tlsf_reallocxf; - ma.xstatus = tlsf_status; - ma.xinfo = tlsf_meminfo; + ma.xstatus = tlsf_status; + ma.xinfo = tlsf_meminfo; ma.xavailable = tlsf_available; - ma.xsums = tlsf_sums; - ma.xdestroy = tlsf_malloc_destroy_pkg_manager; - ma.xmodstats = tlsf_mod_get_stats; + ma.xsums = tlsf_sums; + ma.xdestroy = tlsf_malloc_destroy_pkg_manager; + ma.xmodstats = tlsf_mod_get_stats; ma.xfmodstats = tlsf_mod_free_stats; return pkg_init_api(&ma); @@ -1429,15 +1453,15 @@ int tlsf_malloc_init_pkg_manager(void) /* SHM - shared memory API*/ static void *_tlsf_shm_pool = 0; static tlsf_t _tlsf_shm_block = 0; -static gen_lock_t* _tlsf_shm_lock = 0; +static gen_lock_t *_tlsf_shm_lock = 0; -#define tlsf_shm_lock() lock_get(_tlsf_shm_lock) -#define tlsf_shm_unlock() lock_release(_tlsf_shm_lock) +#define tlsf_shm_lock() lock_get(_tlsf_shm_lock) +#define tlsf_shm_unlock() lock_release(_tlsf_shm_lock) /** * */ -void tlsf_shm_glock(void* qmp) +void tlsf_shm_glock(void *qmp) { lock_get(_tlsf_shm_lock); } @@ -1445,7 +1469,7 @@ void tlsf_shm_glock(void* qmp) /** * */ -void tlsf_shm_gunlock(void* qmp) +void tlsf_shm_gunlock(void *qmp) { lock_release(_tlsf_shm_lock); } @@ -1455,7 +1479,7 @@ void tlsf_shm_gunlock(void* qmp) */ void tlsf_shm_lock_destroy(void) { - if (_tlsf_shm_lock){ + if(_tlsf_shm_lock) { DBG("destroying the shared memory lock\n"); lock_destroy(_tlsf_shm_lock); /* we don't need to dealloc it*/ } @@ -1466,23 +1490,23 @@ void tlsf_shm_lock_destroy(void) */ int tlsf_shm_lock_init(void) { - if (_tlsf_shm_lock) { + if(_tlsf_shm_lock) { LM_DBG("shared memory lock initialized\n"); return 0; } #ifdef DBG_TLSF_MALLOC - _tlsf_shm_lock = tlsf_malloc(_tlsf_shm_block, sizeof(gen_lock_t), - _SRC_LOC_, _SRC_FUNCTION_, _SRC_LINE_, _SRC_MODULE_); + _tlsf_shm_lock = tlsf_malloc(_tlsf_shm_block, sizeof(gen_lock_t), _SRC_LOC_, + _SRC_FUNCTION_, _SRC_LINE_, _SRC_MODULE_); #else _tlsf_shm_lock = tlsf_malloc(_tlsf_shm_block, sizeof(gen_lock_t)); #endif - if (_tlsf_shm_lock==0){ + if(_tlsf_shm_lock == 0) { LOG(L_CRIT, "could not allocate lock\n"); return -1; } - if (lock_init(_tlsf_shm_lock)==0){ + if(lock_init(_tlsf_shm_lock) == 0) { LOG(L_CRIT, "could not initialize lock\n"); return -1; } @@ -1491,8 +1515,8 @@ int tlsf_shm_lock_init(void) /*SHM wrappers to sync the access to memory block*/ #ifdef DBG_TLSF_MALLOC -void* tlsf_shm_malloc(void* tlsfmp, size_t size, - const char* file, const char* func, unsigned int line, const char* mname) +void *tlsf_shm_malloc(void *tlsfmp, size_t size, const char *file, + const char *func, unsigned int line, const char *mname) { void *r; tlsf_shm_lock(); @@ -1500,8 +1524,8 @@ void* tlsf_shm_malloc(void* tlsfmp, size_t size, tlsf_shm_unlock(); return r; } -void* tlsf_shm_mallocxz(void* tlsfmp, size_t size, - const char* file, const char* func, unsigned int line, const char* mname) +void *tlsf_shm_mallocxz(void *tlsfmp, size_t size, const char *file, + const char *func, unsigned int line, const char *mname) { void *r; tlsf_shm_lock(); @@ -1509,8 +1533,8 @@ void* tlsf_shm_mallocxz(void* tlsfmp, size_t size, tlsf_shm_unlock(); return r; } -void* tlsf_shm_realloc(void* tlsfmp, void* p, size_t size, - const char* file, const char* func, unsigned int line, const char* mname) +void *tlsf_shm_realloc(void *tlsfmp, void *p, size_t size, const char *file, + const char *func, unsigned int line, const char *mname) { void *r; tlsf_shm_lock(); @@ -1518,8 +1542,8 @@ void* tlsf_shm_realloc(void* tlsfmp, void* p, size_t size, tlsf_shm_unlock(); return r; } -void* tlsf_shm_reallocxf(void* tlsfmp, void* p, size_t size, - const char* file, const char* func, unsigned int line, const char* mname) +void *tlsf_shm_reallocxf(void *tlsfmp, void *p, size_t size, const char *file, + const char *func, unsigned int line, const char *mname) { void *r; tlsf_shm_lock(); @@ -1527,25 +1551,26 @@ void* tlsf_shm_reallocxf(void* tlsfmp, void* p, size_t size, tlsf_shm_unlock(); return r; } -void* tlsf_shm_resize(void* tlsfmp, void* p, size_t size, - const char* file, const char* func, unsigned int line, const char* mname) +void *tlsf_shm_resize(void *tlsfmp, void *p, size_t size, const char *file, + const char *func, unsigned int line, const char *mname) { void *r; tlsf_shm_lock(); - if(p) tlsf_free(tlsfmp, p, file, func, line, mname); + if(p) + tlsf_free(tlsfmp, p, file, func, line, mname); r = tlsf_malloc(tlsfmp, size, file, func, line, mname); tlsf_shm_unlock(); return r; } -void tlsf_shm_free(void* tlsfmp, void* p, const char* file, const char* func, - unsigned int line, const char* mname) +void tlsf_shm_free(void *tlsfmp, void *p, const char *file, const char *func, + unsigned int line, const char *mname) { tlsf_shm_lock(); tlsf_free(tlsfmp, p, file, func, line, mname); tlsf_shm_unlock(); } #else -void* tlsf_shm_malloc(void* tlsfmp, size_t size) +void *tlsf_shm_malloc(void *tlsfmp, size_t size) { void *r; tlsf_shm_lock(); @@ -1553,7 +1578,7 @@ void* tlsf_shm_malloc(void* tlsfmp, size_t size) tlsf_shm_unlock(); return r; } -void* tlsf_shm_mallocxz(void* tlsfmp, size_t size) +void *tlsf_shm_mallocxz(void *tlsfmp, size_t size) { void *r; tlsf_shm_lock(); @@ -1561,7 +1586,7 @@ void* tlsf_shm_mallocxz(void* tlsfmp, size_t size) tlsf_shm_unlock(); return r; } -void* tlsf_shm_realloc(void* tlsfmp, void* p, size_t size) +void *tlsf_shm_realloc(void *tlsfmp, void *p, size_t size) { void *r; tlsf_shm_lock(); @@ -1569,7 +1594,7 @@ void* tlsf_shm_realloc(void* tlsfmp, void* p, size_t size) tlsf_shm_unlock(); return r; } -void* tlsf_shm_reallocxf(void* tlsfmp, void* p, size_t size) +void *tlsf_shm_reallocxf(void *tlsfmp, void *p, size_t size) { void *r; tlsf_shm_lock(); @@ -1577,35 +1602,36 @@ void* tlsf_shm_reallocxf(void* tlsfmp, void* p, size_t size) tlsf_shm_unlock(); return r; } -void* tlsf_shm_resize(void* tlsfmp, void* p, size_t size) +void *tlsf_shm_resize(void *tlsfmp, void *p, size_t size) { void *r; tlsf_shm_lock(); - if(p) tlsf_free(tlsfmp, p); + if(p) + tlsf_free(tlsfmp, p); r = tlsf_malloc(tlsfmp, size); tlsf_shm_unlock(); return r; } -void tlsf_shm_free(void* tlsfmp, void* p) +void tlsf_shm_free(void *tlsfmp, void *p) { tlsf_shm_lock(); tlsf_free(tlsfmp, p); tlsf_shm_unlock(); } #endif -void tlsf_shm_status(void* tlsfmp) +void tlsf_shm_status(void *tlsfmp) { tlsf_shm_lock(); tlsf_status(tlsfmp); tlsf_shm_unlock(); } -void tlsf_shm_info(void* tlsfmp, struct mem_info* info) +void tlsf_shm_info(void *tlsfmp, struct mem_info *info) { tlsf_shm_lock(); tlsf_meminfo(tlsfmp, info); tlsf_shm_unlock(); } -unsigned long tlsf_shm_available(void* tlsfmp) +unsigned long tlsf_shm_available(void *tlsfmp) { unsigned long r; tlsf_shm_lock(); @@ -1613,7 +1639,7 @@ unsigned long tlsf_shm_available(void* tlsfmp) tlsf_shm_unlock(); return r; } -void tlsf_shm_sums(void* tlsfmp) +void tlsf_shm_sums(void *tlsfmp) { tlsf_shm_lock(); tlsf_sums(tlsfmp); @@ -1649,48 +1675,49 @@ int tlsf_malloc_init_shm_manager(void) { sr_shm_api_t ma; _tlsf_shm_pool = shm_core_get_pool(); - if (_tlsf_shm_pool) { + if(_tlsf_shm_pool) { _tlsf_shm_block = tlsf_create_with_pool(_tlsf_shm_pool, shm_mem_size); if(!_tlsf_shm_block) { LM_CRIT("could not create tlsf shm memory pool\n"); - fprintf(stderr, "could not create tlsf shm memory pool: %ld bytes\n", - shm_mem_size); + fprintf(stderr, + "could not create tlsf shm memory pool: %ld bytes\n", + shm_mem_size); return -1; } } else { LOG(L_CRIT, "could not initialize tlsf shm memory pool\n"); fprintf(stderr, "Too much tlsf shm memory demanded: %ld bytes\n", - shm_mem_size); + shm_mem_size); return -1; } memset(&ma, 0, sizeof(sr_shm_api_t)); - ma.mname = _tlsf_mem_name; - ma.mem_pool = _tlsf_shm_pool; - ma.mem_block = _tlsf_shm_block; - ma.xmalloc = tlsf_shm_malloc; - ma.xmallocxz = tlsf_shm_mallocxz; + ma.mname = _tlsf_mem_name; + ma.mem_pool = _tlsf_shm_pool; + ma.mem_block = _tlsf_shm_block; + ma.xmalloc = tlsf_shm_malloc; + ma.xmallocxz = tlsf_shm_mallocxz; ma.xmalloc_unsafe = tlsf_malloc; - ma.xfree = tlsf_shm_free; - ma.xfree_unsafe = tlsf_free; - ma.xrealloc = tlsf_shm_realloc; - ma.xreallocxf = tlsf_shm_reallocxf; - ma.xresize = tlsf_shm_resize; - ma.xstatus = tlsf_shm_status; - ma.xinfo = tlsf_shm_info; - ma.xavailable = tlsf_shm_available; - ma.xsums = tlsf_shm_sums; - ma.xdestroy = tlsf_malloc_destroy_shm_manager; - ma.xmodstats = tlsf_shm_mod_get_stats; - ma.xfmodstats = tlsf_shm_mod_free_stats; - ma.xglock = tlsf_shm_glock; - ma.xgunlock = tlsf_shm_gunlock; - - if(shm_init_api(&ma)<0) { + ma.xfree = tlsf_shm_free; + ma.xfree_unsafe = tlsf_free; + ma.xrealloc = tlsf_shm_realloc; + ma.xreallocxf = tlsf_shm_reallocxf; + ma.xresize = tlsf_shm_resize; + ma.xstatus = tlsf_shm_status; + ma.xinfo = tlsf_shm_info; + ma.xavailable = tlsf_shm_available; + ma.xsums = tlsf_shm_sums; + ma.xdestroy = tlsf_malloc_destroy_shm_manager; + ma.xmodstats = tlsf_shm_mod_get_stats; + ma.xfmodstats = tlsf_shm_mod_free_stats; + ma.xglock = tlsf_shm_glock; + ma.xgunlock = tlsf_shm_gunlock; + + if(shm_init_api(&ma) < 0) { LM_ERR("cannot initialize the core shm api\n"); return -1; } - if(tlsf_shm_lock_init()<0) { + if(tlsf_shm_lock_init() < 0) { LM_ERR("cannot initialize the core shm lock\n"); return -1; } diff --git a/src/core/mem/tlsf_malloc.h b/src/core/mem/tlsf_malloc.h index 4112634b958..11d920c9137 100644 --- a/src/core/mem/tlsf_malloc.h +++ b/src/core/mem/tlsf_malloc.h @@ -26,68 +26,69 @@ #endif #if defined(__cplusplus) -extern "C" { +extern "C" +{ #endif -/* tlsf_t: a TLSF structure. Can contain 1 to N pools. */ -/* pool_t: a block of memory that TLSF can manage. */ -typedef void* tlsf_t; -typedef void* pool_t; + /* tlsf_t: a TLSF structure. Can contain 1 to N pools. */ + /* pool_t: a block of memory that TLSF can manage. */ + typedef void *tlsf_t; + typedef void *pool_t; -/* Create/destroy a memory pool. */ -tlsf_t tlsf_create(void* mem); -tlsf_t tlsf_create_with_pool(void* mem, size_t bytes); -void tlsf_destroy(tlsf_t tlsf); -pool_t tlsf_get_pool(tlsf_t tlsf); + /* Create/destroy a memory pool. */ + tlsf_t tlsf_create(void *mem); + tlsf_t tlsf_create_with_pool(void *mem, size_t bytes); + void tlsf_destroy(tlsf_t tlsf); + pool_t tlsf_get_pool(tlsf_t tlsf); -/* Add/remove memory pools. */ -pool_t tlsf_add_pool(tlsf_t tlsf, void* mem, size_t bytes); -void tlsf_remove_pool(tlsf_t tlsf, pool_t pool); + /* Add/remove memory pools. */ + pool_t tlsf_add_pool(tlsf_t tlsf, void *mem, size_t bytes); + void tlsf_remove_pool(tlsf_t tlsf, pool_t pool); /* malloc/memalign/realloc/free replacements. */ #ifdef DBG_TLSF_MALLOC -void* tlsf_malloc(tlsf_t tlsf, size_t size, - const char *file, const char *function, unsigned int line, const char *mname); -void* tlsf_mallocxz(tlsf_t tlsf, size_t size, - const char *file, const char *function, unsigned int line, const char *mname); -void* tlsf_realloc(tlsf_t tlsf, void* ptr, size_t size, - const char *file, const char *function, unsigned int line, const char *mname); -void* tlsf_reallocxf(tlsf_t tlsf, void* ptr, size_t size, - const char *file, const char *function, unsigned int line, const char *mname); -void tlsf_free(tlsf_t tlsf, void* ptr, - const char *file, const char *function, unsigned int line, const char *mname); + void *tlsf_malloc(tlsf_t tlsf, size_t size, const char *file, + const char *function, unsigned int line, const char *mname); + void *tlsf_mallocxz(tlsf_t tlsf, size_t size, const char *file, + const char *function, unsigned int line, const char *mname); + void *tlsf_realloc(tlsf_t tlsf, void *ptr, size_t size, const char *file, + const char *function, unsigned int line, const char *mname); + void *tlsf_reallocxf(tlsf_t tlsf, void *ptr, size_t size, const char *file, + const char *function, unsigned int line, const char *mname); + void tlsf_free(tlsf_t tlsf, void *ptr, const char *file, + const char *function, unsigned int line, const char *mname); #else -void* tlsf_malloc(tlsf_t tlsf, size_t bytes); -void* tlsf_mallocxz(tlsf_t tlsf, size_t bytes); -void* tlsf_realloc(tlsf_t tlsf, void* ptr, size_t size); -void* tlsf_reallocxf(tlsf_t tlsf, void* ptr, size_t size); -void tlsf_free(tlsf_t tlsf, void* ptr); +void *tlsf_malloc(tlsf_t tlsf, size_t bytes); +void *tlsf_mallocxz(tlsf_t tlsf, size_t bytes); +void *tlsf_realloc(tlsf_t tlsf, void *ptr, size_t size); +void *tlsf_reallocxf(tlsf_t tlsf, void *ptr, size_t size); +void tlsf_free(tlsf_t tlsf, void *ptr); #endif -/* Returns internal block size, not original request size */ -size_t tlsf_block_size(void* ptr); - -/* Overheads/limits of internal structures. */ -size_t tlsf_size(); -size_t tlsf_align_size(); -size_t tlsf_block_size_min(); -size_t tlsf_block_size_max(); -size_t tlsf_pool_overhead(); -size_t tlsf_alloc_overhead(); - -/* Debugging. */ -typedef void (*tlsf_walker)(void* ptr, size_t size, int used, void* user); -void tlsf_walk_pool(pool_t pool, tlsf_walker walker, void* user); -/* Returns nonzero if any internal consistency check fails. */ -int tlsf_check(tlsf_t tlsf); -int tlsf_check_pool(pool_t pool); - -void tlsf_meminfo(tlsf_t pool, struct mem_info *info); -void tlsf_status(tlsf_t pool); -void tlsf_sums(tlsf_t pool); -unsigned long tlsf_available(tlsf_t pool); -void tlsf_mod_get_stats(tlsf_t pool, void **root); -void tlsf_mod_free_stats(void *root); + /* Returns internal block size, not original request size */ + size_t tlsf_block_size(void *ptr); + + /* Overheads/limits of internal structures. */ + size_t tlsf_size(); + size_t tlsf_align_size(); + size_t tlsf_block_size_min(); + size_t tlsf_block_size_max(); + size_t tlsf_pool_overhead(); + size_t tlsf_alloc_overhead(); + + /* Debugging. */ + typedef void (*tlsf_walker)(void *ptr, size_t size, int used, void *user); + void tlsf_walk_pool(pool_t pool, tlsf_walker walker, void *user); + /* Returns nonzero if any internal consistency check fails. */ + int tlsf_check(tlsf_t tlsf); + int tlsf_check_pool(pool_t pool); + + void tlsf_meminfo(tlsf_t pool, struct mem_info *info); + void tlsf_status(tlsf_t pool); + void tlsf_sums(tlsf_t pool); + unsigned long tlsf_available(tlsf_t pool); + void tlsf_mod_get_stats(tlsf_t pool, void **root); + void tlsf_mod_free_stats(void *root); #if defined(__cplusplus) }; diff --git a/src/core/mem/tlsf_malloc_bits.h b/src/core/mem/tlsf_malloc_bits.h index 29c783d4a44..f46dce045ef 100644 --- a/src/core/mem/tlsf_malloc_bits.h +++ b/src/core/mem/tlsf_malloc_bits.h @@ -29,8 +29,8 @@ ** Detect whether or not we are building for a 32- or 64-bit (LP/LLP) ** architecture. There is no reliable portable method at compile-time. */ -#if defined (__alpha__) || defined (__ia64__) || defined (__x86_64__) \ - || defined (_WIN64) || defined (__LP64__) || defined (__LLP64__) +#if defined(__alpha__) || defined(__ia64__) || defined(__x86_64__) \ + || defined(_WIN64) || defined(__LP64__) || defined(__LLP64__) #define TLSF_64BIT #endif @@ -40,8 +40,9 @@ ** ** Note: clang is compatible with GCC builtins and will also define those macros */ -#if defined (__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) \ - && defined (__GNUC_PATCHLEVEL__) +#if defined(__GNUC__) \ + && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) \ + && defined(__GNUC_PATCHLEVEL__) tlsf_decl int tlsf_ffs(unsigned int word) { @@ -54,7 +55,7 @@ tlsf_decl int tlsf_fls(unsigned int word) return bit - 1; } -#if defined (TLSF_64BIT) +#if defined(TLSF_64BIT) tlsf_decl int tlsf_fls_sizet(size_t size) { const int bit = size ? 64 - __builtin_clzl(size) : 0; @@ -68,12 +69,28 @@ tlsf_decl int tlsf_fls_generic(unsigned int word) { int bit = 32; - if (!word) bit -= 1; - if (!(word & 0xffff0000)) { word <<= 16; bit -= 16; } - if (!(word & 0xff000000)) { word <<= 8; bit -= 8; } - if (!(word & 0xf0000000)) { word <<= 4; bit -= 4; } - if (!(word & 0xc0000000)) { word <<= 2; bit -= 2; } - if (!(word & 0x80000000)) { word <<= 1; bit -= 1; } + if(!word) + bit -= 1; + if(!(word & 0xffff0000)) { + word <<= 16; + bit -= 16; + } + if(!(word & 0xff000000)) { + word <<= 8; + bit -= 8; + } + if(!(word & 0xf0000000)) { + word <<= 4; + bit -= 4; + } + if(!(word & 0xc0000000)) { + word <<= 2; + bit -= 2; + } + if(!(word & 0x80000000)) { + word <<= 1; + bit -= 1; + } return bit; } @@ -89,19 +106,15 @@ tlsf_decl int tlsf_fls(unsigned int word) return tlsf_fls_generic(word) - 1; } -#if defined (TLSF_64BIT) +#if defined(TLSF_64BIT) tlsf_decl int tlsf_fls_sizet(size_t size) { int high = (int)(size >> 32); int bits = 0; - if (high) - { + if(high) { bits = 32 + tlsf_fls(high); - } - else - { + } else { bits = tlsf_fls((int)size & 0xffffffff); - } return bits; } @@ -110,7 +123,7 @@ tlsf_decl int tlsf_fls_sizet(size_t size) #endif /* GNUC */ -#if !defined (TLSF_64BIT) +#if !defined(TLSF_64BIT) #define tlsf_fls_sizet tlsf_fls #endif From 7f7ee96a277146380cc425049de5aa855d88a9db Mon Sep 17 00:00:00 2001 From: Victor Seva Date: Thu, 18 May 2023 15:22:55 +0200 Subject: [PATCH 06/14] core: [parser] clang-format for coherent indentation and coding style --- src/core/parser/contact/contact.c | 151 +- src/core/parser/contact/contact.h | 37 +- src/core/parser/contact/parse_contact.c | 93 +- src/core/parser/contact/parse_contact.h | 19 +- src/core/parser/digest/digest.c | 199 ++- src/core/parser/digest/digest.h | 54 +- src/core/parser/digest/digest_keys.h | 24 +- src/core/parser/digest/digest_parser.c | 248 +-- src/core/parser/digest/digest_parser.h | 86 +- src/core/parser/digest/param_parser.c | 287 ++-- src/core/parser/digest/param_parser.h | 25 +- src/core/parser/hf.c | 317 ++-- src/core/parser/hf.h | 277 ++-- src/core/parser/keys.h | 284 ++-- src/core/parser/msg_parser.c | 850 +++++----- src/core/parser/msg_parser.h | 459 +++--- src/core/parser/parse_addr_spec.c | 86 +- src/core/parser/parse_addr_spec.h | 49 +- src/core/parser/parse_allow.c | 41 +- src/core/parser/parse_allow.h | 26 +- src/core/parser/parse_body.c | 356 ++--- src/core/parser/parse_body.h | 18 +- src/core/parser/parse_content.c | 541 +++---- src/core/parser/parse_content.h | 80 +- src/core/parser/parse_cseq.c | 4 +- src/core/parser/parse_cseq.h | 21 +- src/core/parser/parse_date.c | 193 ++- src/core/parser/parse_date.h | 10 +- src/core/parser/parse_def.h | 5 +- src/core/parser/parse_disposition.c | 149 +- src/core/parser/parse_disposition.h | 21 +- src/core/parser/parse_diversion.c | 28 +- src/core/parser/parse_diversion.h | 22 +- src/core/parser/parse_event.c | 90 +- src/core/parser/parse_event.h | 25 +- src/core/parser/parse_expires.c | 37 +- src/core/parser/parse_expires.h | 18 +- src/core/parser/parse_fline.c | 247 +-- src/core/parser/parse_fline.h | 56 +- src/core/parser/parse_from.h | 12 +- src/core/parser/parse_hname2.c | 260 +-- src/core/parser/parse_hname2.h | 14 +- src/core/parser/parse_identity.c | 97 +- src/core/parser/parse_identity.h | 9 +- src/core/parser/parse_identityinfo.c | 4 +- src/core/parser/parse_identityinfo.h | 23 +- src/core/parser/parse_methods.c | 145 +- src/core/parser/parse_methods.h | 10 +- src/core/parser/parse_nameaddr.c | 26 +- src/core/parser/parse_nameaddr.h | 19 +- src/core/parser/parse_option_tags.c | 4 +- src/core/parser/parse_option_tags.h | 117 +- src/core/parser/parse_param.c | 16 +- src/core/parser/parse_param.h | 151 +- src/core/parser/parse_ppi_pai.c | 110 +- src/core/parser/parse_ppi_pai.h | 15 +- src/core/parser/parse_privacy.c | 306 ++-- src/core/parser/parse_privacy.h | 23 +- src/core/parser/parse_refer_to.c | 18 +- src/core/parser/parse_refer_to.h | 18 +- src/core/parser/parse_require.c | 24 +- src/core/parser/parse_require.h | 8 +- src/core/parser/parse_retry_after.c | 41 +- src/core/parser/parse_retry_after.h | 9 +- src/core/parser/parse_rpid.c | 15 +- src/core/parser/parse_rpid.h | 20 +- src/core/parser/parse_rr.c | 224 +-- src/core/parser/parse_rr.h | 192 ++- src/core/parser/parse_sipifmatch.c | 22 +- src/core/parser/parse_sipifmatch.h | 9 +- src/core/parser/parse_subscription_state.c | 80 +- src/core/parser/parse_subscription_state.h | 6 +- src/core/parser/parse_supported.c | 25 +- src/core/parser/parse_supported.h | 9 +- src/core/parser/parse_to.c | 4 +- src/core/parser/parse_to.h | 15 +- src/core/parser/parse_uri.c | 1666 ++++++++++---------- src/core/parser/parse_uri.h | 10 +- src/core/parser/parse_via.c | 72 +- src/core/parser/parse_via.h | 63 +- src/core/parser/parser_f.h | 69 +- src/core/parser/sdp/sdp.c | 1027 ++++++------ src/core/parser/sdp/sdp.h | 116 +- src/core/parser/sdp/sdp_cloner.h | 10 +- src/core/parser/sdp/sdp_helpr_funcs.c | 552 +++---- src/core/parser/sdp/sdp_helpr_funcs.h | 30 +- 86 files changed, 5912 insertions(+), 5336 deletions(-) diff --git a/src/core/parser/contact/contact.c b/src/core/parser/contact/contact.c index 345167022fb..3c66a2082b0 100644 --- a/src/core/parser/contact/contact.c +++ b/src/core/parser/contact/contact.c @@ -26,10 +26,10 @@ * */ -#include /* memset */ +#include /* memset */ #include "../../mem/mem.h" /* pkg_malloc, pkg_free */ #include "../../dprint.h" -#include "../../trim.h" /* trim_leading, trim_trailing */ +#include "../../trim.h" /* trim_leading, trim_trailing */ #include "contact.h" @@ -45,7 +45,7 @@ * Skip URI, stops when , (next contact) * or ; (parameter) is found */ -static inline int skip_uri(str* _s) +static inline int skip_uri(str *_s) { register int st = ST1; @@ -53,28 +53,47 @@ static inline int skip_uri(str* _s) switch(*(_s->s)) { case ',': case ';': - if (st == ST1) return 0; + if(st == ST1) + return 0; break; case '\"': switch(st) { - case ST1: st = ST2; break; - case ST2: st = ST1; break; - case ST3: st = ST4; break; - case ST4: st = ST3; break; - case ST5: st = ST2; break; - case ST6: st = ST4; break; + case ST1: + st = ST2; + break; + case ST2: + st = ST1; + break; + case ST3: + st = ST4; + break; + case ST4: + st = ST3; + break; + case ST5: + st = ST2; + break; + case ST6: + st = ST4; + break; } break; case '<': switch(st) { - case ST1: st = ST3; break; + case ST1: + st = ST3; + break; case ST3: - LM_ERR("second bracket < found\n"); - return -1; - case ST5: st = ST2; break; - case ST6: st = ST4; break; + LM_ERR("second bracket < found\n"); + return -1; + case ST5: + st = ST2; + break; + case ST6: + st = ST4; + break; } break; @@ -84,30 +103,44 @@ static inline int skip_uri(str* _s) LM_ERR("bracket > is first\n"); return -2; - case ST3: st = ST1; break; - case ST5: st = ST2; break; - case ST6: st = ST4; break; + case ST3: + st = ST1; + break; + case ST5: + st = ST2; + break; + case ST6: + st = ST4; + break; } break; case '\\': switch(st) { - case ST2: st = ST5; break; - case ST4: st = ST6; break; - case ST5: st = ST2; break; - case ST6: st = ST4; break; + case ST2: + st = ST5; + break; + case ST4: + st = ST6; + break; + case ST5: + st = ST2; + break; + case ST6: + st = ST4; + break; } break; - default: break; - + default: + break; } _s->s++; _s->len--; } - if (st != ST1) { + if(st != ST1) { LM_ERR("bracket < or \" not closed\n"); return -3; } @@ -122,12 +155,12 @@ static inline int skip_uri(str* _s) * _s will be adjusted to point at the beginning * of URI */ -static inline int skip_name(str* _s) +static inline int skip_name(str *_s) { - char* last_wsp, *p; + char *last_wsp, *p; int i, quoted = 0; - if (!_s) { + if(!_s) { LM_ERR("invalid parameter value\n"); return -1; } @@ -137,35 +170,36 @@ static inline int skip_name(str* _s) last_wsp = 0; for(i = 0; i < _s->len; i++) { - if (!quoted) { - if ((*p == ' ') || (*p == '\t')) { + if(!quoted) { + if((*p == ' ') || (*p == '\t')) { last_wsp = p; } else { - if (*p == '<') { + if(*p == '<') { _s->s = p; _s->len -= i; return 0; } - if (*p == ':' || *p == ';') { - if (last_wsp) { + if(*p == ':' || *p == ';') { + if(last_wsp) { _s->len -= last_wsp - _s->s + 1; _s->s = last_wsp; } return 0; } - if (*p == '\"') { + if(*p == '\"') { quoted = 1; } } } else { - if ((*p == '\"') && (*(p-1) != '\\')) quoted = 0; + if((*p == '\"') && (*(p - 1) != '\\')) + quoted = 0; } p++; } - if (quoted) { + if(quoted) { LM_ERR("closing quote missing in name part of Contact\n"); } else { LM_ERR("error in contact, scheme separator not found\n"); @@ -178,9 +212,9 @@ static inline int skip_name(str* _s) /* * Parse contacts in a Contact HF */ -int parse_contacts(str* _s, contact_t** _c) +int parse_contacts(str *_s, contact_t **_c) { - contact_t* c; + contact_t *c; param_hooks_t hooks; str sv; @@ -188,8 +222,8 @@ int parse_contacts(str* _s, contact_t** _c) while(1) { /* Allocate and clear contact structure */ - c = (contact_t*)pkg_malloc(sizeof(contact_t)); - if (c == 0) { + c = (contact_t *)pkg_malloc(sizeof(contact_t)); + if(c == 0) { PKG_MEM_ERROR; goto error; } @@ -197,7 +231,7 @@ int parse_contacts(str* _s, contact_t** _c) c->name.s = _s->s; - if (skip_name(_s) < 0) { + if(skip_name(_s) < 0) { LM_ERR("error while skipping name part\n"); goto error; } @@ -207,16 +241,16 @@ int parse_contacts(str* _s, contact_t** _c) trim_trailing(&c->name); /* Find the end of the URI */ - if (skip_uri(_s) < 0) { + if(skip_uri(_s) < 0) { LM_ERR("error while skipping URI\n"); goto error; } c->uri.len = _s->s - c->uri.s; /* Calculate URI length */ - trim_trailing(&(c->uri)); /* Remove any trailing spaces from URI */ + trim_trailing(&(c->uri)); /* Remove any trailing spaces from URI */ /* Remove <> if any */ - if ((c->uri.len >= 2) && (c->uri.s[0] == '<') + if((c->uri.len >= 2) && (c->uri.s[0] == '<') && (c->uri.s[c->uri.len - 1] == '>')) { c->uri.s++; c->uri.len -= 2; @@ -228,19 +262,20 @@ int parse_contacts(str* _s, contact_t** _c) goto error; } - if (_s->len == 0) goto ok; + if(_s->len == 0) + goto ok; - if (_s->s[0] == ';') { /* Contact parameter found */ + if(_s->s[0] == ';') { /* Contact parameter found */ _s->s++; _s->len--; trim_leading(_s); - if (_s->len == 0) { + if(_s->len == 0) { LM_ERR("error while parsing params\n"); goto error; } - if (parse_params(_s, CLASS_CONTACT, &hooks, &c->params) < 0) { + if(parse_params(_s, CLASS_CONTACT, &hooks, &c->params) < 0) { LM_ERR("error while parsing parameters\n"); goto error; } @@ -253,7 +288,8 @@ int parse_contacts(str* _s, contact_t** _c) c->reg_id = hooks.contact.reg_id; c->flags = hooks.contact.flags; - if (_s->len == 0) goto ok; + if(_s->len == 0) + goto ok; } /* Next character is comma */ @@ -266,7 +302,7 @@ int parse_contacts(str* _s, contact_t** _c) *_c = c; c = NULL; - if (_s->len == 0) { + if(_s->len == 0) { LM_ERR("text after comma missing\n"); goto error; } @@ -275,7 +311,8 @@ int parse_contacts(str* _s, contact_t** _c) error: LM_ERR("failure parsing '%.*s' (%d) [%p/%p/%d]\n", sv.len, sv.s, sv.len, sv.s, _s->s, (int)(_s->s - sv.s)); - if (c) pkg_free(c); + if(c) + pkg_free(c); free_contacts(_c); /* Free any contacts created so far */ return -1; @@ -291,14 +328,14 @@ int parse_contacts(str* _s, contact_t** _c) * Free list of contacts * _c is head of the list */ -void free_contacts(contact_t** _c) +void free_contacts(contact_t **_c) { - contact_t* ptr; + contact_t *ptr; while(*_c) { ptr = *_c; *_c = (*_c)->next; - if (ptr->params) { + if(ptr->params) { free_params(ptr->params); } pkg_free(ptr); @@ -309,9 +346,9 @@ void free_contacts(contact_t** _c) /* * Print list of contacts, just for debugging */ -void print_contacts(FILE* _o, contact_t* _c) +void print_contacts(FILE *_o, contact_t *_c) { - contact_t* ptr; + contact_t *ptr; ptr = _c; @@ -327,7 +364,7 @@ void print_contacts(FILE* _o, contact_t* _c) fprintf(_o, "reg-id : %p\n", ptr->reg_id); fprintf(_o, "flags : %p\n", ptr->flags); fprintf(_o, "len : %d\n", ptr->len); - if (ptr->params) { + if(ptr->params) { print_params(_o, ptr->params); } fprintf(_o, "---/Contact---\n"); diff --git a/src/core/parser/contact/contact.h b/src/core/parser/contact/contact.h index b72f9e59d9c..b7bcf4d3aa9 100644 --- a/src/core/parser/contact/contact.h +++ b/src/core/parser/contact/contact.h @@ -20,8 +20,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * History: @@ -41,39 +41,40 @@ /* * Structure representing a Contact HF body */ -typedef struct contact { - str name; /* Name part */ - str uri; /* contact uri */ - param_t* q; /* q parameter hook */ - param_t* expires; /* expires parameter hook */ - param_t* methods; /* methods parameter hook */ - param_t* received; /* received parameter hook */ - param_t* instance; /* sip.instance parameter hook */ - param_t* reg_id; /* reg-id parameter hook */ - param_t* flags; /* flags parameter hook */ - param_t* params; /* List of all parameters */ - int len; /* Total length of the element */ - struct contact* next; /* Next contact in the list */ +typedef struct contact +{ + str name; /* Name part */ + str uri; /* contact uri */ + param_t *q; /* q parameter hook */ + param_t *expires; /* expires parameter hook */ + param_t *methods; /* methods parameter hook */ + param_t *received; /* received parameter hook */ + param_t *instance; /* sip.instance parameter hook */ + param_t *reg_id; /* reg-id parameter hook */ + param_t *flags; /* flags parameter hook */ + param_t *params; /* List of all parameters */ + int len; /* Total length of the element */ + struct contact *next; /* Next contact in the list */ } contact_t; /* * Parse contacts in a Contact HF */ -int parse_contacts(str* _s, contact_t** _c); +int parse_contacts(str *_s, contact_t **_c); /* * Free list of contacts * _c is head of the list */ -void free_contacts(contact_t** _c); +void free_contacts(contact_t **_c); /* * Print list of contacts, just for debugging */ -void print_contacts(FILE* _o, contact_t* _c); +void print_contacts(FILE *_o, contact_t *_c); #endif /* CONTACT_H */ diff --git a/src/core/parser/contact/parse_contact.c b/src/core/parser/contact/parse_contact.c index 242c4a07568..c8adeb81235 100644 --- a/src/core/parser/contact/parse_contact.c +++ b/src/core/parser/contact/parse_contact.c @@ -26,16 +26,15 @@ * */ -#include /* memset */ +#include /* memset */ #include "../hf.h" -#include "../../mem/mem.h" /* pkg_malloc, pkg_free */ +#include "../../mem/mem.h" /* pkg_malloc, pkg_free */ #include "../../dprint.h" -#include "../../trim.h" /* trim_leading */ +#include "../../trim.h" /* trim_leading */ #include "parse_contact.h" - -static inline int contact_parser(char* _s, int _l, contact_body_t* _c) +static inline int contact_parser(char *_s, int _l, contact_body_t *_c) { str tmp; @@ -44,15 +43,15 @@ static inline int contact_parser(char* _s, int _l, contact_body_t* _c) trim_leading(&tmp); - if (tmp.len == 0) { + if(tmp.len == 0) { LM_ERR("empty body\n"); return -1; } - if (tmp.s[0] == '*') { + if(tmp.s[0] == '*') { _c->star = 1; } else { - if (parse_contacts(&tmp, &(_c->contacts)) < 0) { + if(parse_contacts(&tmp, &(_c->contacts)) < 0) { LM_ERR("error while parsing contacts\n"); return -2; } @@ -65,29 +64,29 @@ static inline int contact_parser(char* _s, int _l, contact_body_t* _c) /* * Parse contact header field body */ -int parse_contact(struct hdr_field* _h) +int parse_contact(struct hdr_field *_h) { - contact_body_t* b; + contact_body_t *b; - if (_h->parsed != 0) { - return 0; /* Already parsed */ + if(_h->parsed != 0) { + return 0; /* Already parsed */ } - b = (contact_body_t*)pkg_malloc(sizeof(contact_body_t)); - if (b == 0) { + b = (contact_body_t *)pkg_malloc(sizeof(contact_body_t)); + if(b == 0) { PKG_MEM_ERROR; return -1; } memset(b, 0, sizeof(contact_body_t)); - if (contact_parser(_h->body.s, _h->body.len, b) < 0) { + if(contact_parser(_h->body.s, _h->body.len, b) < 0) { LM_ERR("error while parsing\n"); pkg_free(b); return -2; } - _h->parsed = (void*)b; + _h->parsed = (void *)b; return 0; } @@ -95,11 +94,11 @@ int parse_contact(struct hdr_field* _h) /* * Free all memory */ -void free_contact(contact_body_t** _c) +void free_contact(contact_body_t **_c) { - if(*_c==NULL) + if(*_c == NULL) return; - if ((*_c)->contacts) { + if((*_c)->contacts) { free_contacts(&((*_c)->contacts)); } @@ -111,7 +110,7 @@ void free_contact(contact_body_t** _c) /* * Print structure, for debugging only */ -void print_contact(FILE* _o, contact_body_t* _c) +void print_contact(FILE *_o, contact_body_t *_c) { fprintf(_o, "===Contact body===\n"); fprintf(_o, "star: %d\n", _c->star); @@ -124,25 +123,25 @@ void print_contact(FILE* _o, contact_body_t* _c) * Contact header field iterator, returns next contact if any, it doesn't * parse message header if not absolutely necessary */ -int contact_iterator(contact_t** c, struct sip_msg* msg, contact_t* prev) +int contact_iterator(contact_t **c, struct sip_msg *msg, contact_t *prev) { - static struct hdr_field* hdr = 0; - struct hdr_field* last; - contact_body_t* cb; + static struct hdr_field *hdr = 0; + struct hdr_field *last; + contact_body_t *cb; - if (!msg) { + if(!msg) { LM_ERR("invalid parameter value\n"); return -1; } - if (!prev) { + if(!prev) { /* No pointer to previous contact given, find topmost * contact and return pointer to the first contact * inside that header field */ hdr = msg->contact; - if (!hdr) { - if (parse_headers(msg, HDR_CONTACT_F, 0) == -1) { + if(!hdr) { + if(parse_headers(msg, HDR_CONTACT_F, 0) == -1) { LM_ERR("error while parsing headers\n"); return -1; } @@ -150,8 +149,8 @@ int contact_iterator(contact_t** c, struct sip_msg* msg, contact_t* prev) hdr = msg->contact; } - if (hdr) { - if (parse_contact(hdr) < 0) { + if(hdr) { + if(parse_contact(hdr) < 0) { LM_ERR("error while parsing Contact\n"); return -1; } @@ -160,19 +159,19 @@ int contact_iterator(contact_t** c, struct sip_msg* msg, contact_t* prev) return 1; } - cb = (contact_body_t*)hdr->parsed; + cb = (contact_body_t *)hdr->parsed; *c = cb->contacts; return 0; } else { /* Check if there is another contact in the * same header field and if so then return it */ - if (prev->next) { + if(prev->next) { *c = prev->next; return 0; } - if(hdr==NULL) { + if(hdr == NULL) { LM_ERR("contact iterator not initialized\n"); return -1; } @@ -190,11 +189,11 @@ int contact_iterator(contact_t** c, struct sip_msg* msg, contact_t* prev) hdr = hdr->next; } - if (!hdr) { + if(!hdr) { /* Look for another Contact HF in unparsed * part of the message header */ - if (parse_headers(msg, HDR_CONTACT_F, 1) == -1) { + if(parse_headers(msg, HDR_CONTACT_F, 1) == -1) { LM_ERR("error while parsing message header\n"); return -1; } @@ -204,8 +203,8 @@ int contact_iterator(contact_t** c, struct sip_msg* msg, contact_t* prev) * previous Contact HF (that indicates that the previous * one was the last header field in the header) */ - if ((msg->last_header->type == HDR_CONTACT_T) && - (msg->last_header != last)) { + if((msg->last_header->type == HDR_CONTACT_T) + && (msg->last_header != last)) { hdr = msg->last_header; } else { *c = 0; @@ -213,7 +212,7 @@ int contact_iterator(contact_t** c, struct sip_msg* msg, contact_t* prev) } } - if (parse_contact(hdr) < 0) { + if(parse_contact(hdr) < 0) { LM_ERR("error while parsing Contact HF body\n"); return -1; } @@ -221,7 +220,7 @@ int contact_iterator(contact_t** c, struct sip_msg* msg, contact_t* prev) /* And return first contact within that * header field */ - cb = (contact_body_t*)hdr->parsed; + cb = (contact_body_t *)hdr->parsed; *c = cb->contacts; return 0; } @@ -232,18 +231,18 @@ int contact_iterator(contact_t** c, struct sip_msg* msg, contact_t* prev) */ int parse_contact_headers(sip_msg_t *msg) { - hdr_field_t* hdr; + hdr_field_t *hdr; - if (parse_headers(msg, HDR_EOH_F, 0) < 0) { + if(parse_headers(msg, HDR_EOH_F, 0) < 0) { LM_ERR("failed to parse headers\n"); return -1; } - if (msg->contact) { + if(msg->contact) { hdr = msg->contact; while(hdr) { - if (hdr->type == HDR_CONTACT_T) { - if (!hdr->parsed && (parse_contact(hdr) < 0)) { + if(hdr->type == HDR_CONTACT_T) { + if(!hdr->parsed && (parse_contact(hdr) < 0)) { LM_ERR("failed to parse Contact body\n"); return -1; } @@ -260,13 +259,13 @@ int parse_contact_headers(sip_msg_t *msg) */ int parse_contact_header(sip_msg_t *msg) { - if ( !msg->contact && ( parse_headers(msg,HDR_CONTACT_F,0)==-1 - || !msg->contact)) { + if(!msg->contact + && (parse_headers(msg, HDR_CONTACT_F, 0) == -1 || !msg->contact)) { LM_DBG("bad msg or missing CONTACT header\n"); return -1; } - if (msg->contact->parsed) + if(msg->contact->parsed) return 0; return parse_contact(msg->contact); diff --git a/src/core/parser/contact/parse_contact.h b/src/core/parser/contact/parse_contact.h index e6e38b6e9e6..f42ed6cc7f2 100644 --- a/src/core/parser/contact/parse_contact.h +++ b/src/core/parser/contact/parse_contact.h @@ -20,8 +20,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * History: @@ -40,35 +40,36 @@ #include "contact.h" -typedef struct contact_body { - unsigned char star; /* Star contact */ - contact_t* contacts; /* List of contacts */ +typedef struct contact_body +{ + unsigned char star; /* Star contact */ + contact_t *contacts; /* List of contacts */ } contact_body_t; /* * Parse contact header field body */ -int parse_contact(struct hdr_field* _h); +int parse_contact(struct hdr_field *_h); /* * Free all memory */ -void free_contact(contact_body_t** _c); +void free_contact(contact_body_t **_c); /* * Print structure, for debugging only */ -void print_contact(FILE* _o, contact_body_t* _c); +void print_contact(FILE *_o, contact_body_t *_c); /* * Contact header field iterator, returns next contact if any, it doesn't * parse message header if not absolutely necessary */ -int contact_iterator(contact_t** c, struct sip_msg* msg, contact_t* prev); +int contact_iterator(contact_t **c, struct sip_msg *msg, contact_t *prev); /* * parse all Contact headers diff --git a/src/core/parser/digest/digest.c b/src/core/parser/digest/digest.c index 99944217119..5f8ea477c01 100644 --- a/src/core/parser/digest/digest.c +++ b/src/core/parser/digest/digest.c @@ -27,21 +27,21 @@ #include "digest.h" -#include "../../mem/mem.h" /* pkg_malloc */ -#include "../../dprint.h" /* Guess what */ -#include /* printf */ -#include /* strncasecmp */ +#include "../../mem/mem.h" /* pkg_malloc */ +#include "../../dprint.h" /* Guess what */ +#include /* printf */ +#include /* strncasecmp */ /* * Create and initialize a new credentials structure */ -static inline int new_credentials(struct hdr_field* _h) +static inline int new_credentials(struct hdr_field *_h) { - auth_body_t* b; + auth_body_t *b; - b = (auth_body_t*)pkg_malloc(sizeof(auth_body_t)); - if (b == 0) { + b = (auth_body_t *)pkg_malloc(sizeof(auth_body_t)); + if(b == 0) { PKG_MEM_ERROR; return -1; } @@ -50,7 +50,7 @@ static inline int new_credentials(struct hdr_field* _h) b->stale = 0; b->authorized = 0; - _h->parsed = (void*)b; + _h->parsed = (void *)b; return 0; } @@ -63,16 +63,16 @@ static inline int new_credentials(struct hdr_field* _h) * not Bad Request in this case ! * Bad Request should be sent when return value != -1 */ -int parse_credentials(struct hdr_field* _h) +int parse_credentials(struct hdr_field *_h) { int res; - void** ph_parsed; + void **ph_parsed; - if (_h->parsed) { - return 0; /* Already parsed */ + if(_h->parsed) { + return 0; /* Already parsed */ } - if (new_credentials(_h) < 0) { + if(new_credentials(_h) < 0) { LM_ERR("can't create new credentials\n"); return -1; } @@ -81,11 +81,12 @@ int parse_credentials(struct hdr_field* _h) * unable to distinguish if the error was caused by the server or if the * credentials are broken */ - res = parse_digest_cred(&(_h->body), &(((auth_body_t*)(_h->parsed))->digest)); + res = parse_digest_cred( + &(_h->body), &(((auth_body_t *)(_h->parsed))->digest)); - if (res != 0) { - ph_parsed=&_h->parsed; - free_credentials((auth_body_t**)ph_parsed); + if(res != 0) { + ph_parsed = &_h->parsed; + free_credentials((auth_body_t **)ph_parsed); } return res; @@ -95,7 +96,7 @@ int parse_credentials(struct hdr_field* _h) /* * Free all memory */ -void free_credentials(auth_body_t** _b) +void free_credentials(auth_body_t **_b) { pkg_free(*_b); *_b = 0; @@ -110,33 +111,41 @@ void free_credentials(auth_body_t** _b) * The returned value is logical OR of all errors encountered * during the check, see dig_err_t type for more details */ -dig_err_t check_dig_cred(dig_cred_t* _c) +dig_err_t check_dig_cred(dig_cred_t *_c) { dig_err_t res = E_DIG_OK; /* Username must be present */ - if (_c->username.user.s == 0) res |= E_DIG_USERNAME; + if(_c->username.user.s == 0) + res |= E_DIG_USERNAME; /* Realm must be present */ - if (_c->realm.s == 0) res |= E_DIG_REALM; + if(_c->realm.s == 0) + res |= E_DIG_REALM; /* Nonce that was used must be specified */ - if (_c->nonce.s == 0) res |= E_DIG_NONCE; + if(_c->nonce.s == 0) + res |= E_DIG_NONCE; /* URI must be specified */ - if (_c->uri.s == 0) res |= E_DIG_URI; + if(_c->uri.s == 0) + res |= E_DIG_URI; /* We cannot check credentials without response */ - if (_c->response.s == 0) res |= E_DIG_RESPONSE; + if(_c->response.s == 0) + res |= E_DIG_RESPONSE; /* If QOP parameter is present, some additional * requirements must be met */ - if ((_c->qop.qop_parsed == QOP_AUTH) || (_c->qop.qop_parsed == QOP_AUTHINT)) { + if((_c->qop.qop_parsed == QOP_AUTH) + || (_c->qop.qop_parsed == QOP_AUTHINT)) { /* CNONCE must be specified */ - if (_c->cnonce.s == 0) res |= E_DIG_CNONCE; + if(_c->cnonce.s == 0) + res |= E_DIG_CNONCE; /* and also nonce count must be specified */ - if (_c->nc.s == 0) res |= E_DIG_NC; + if(_c->nc.s == 0) + res |= E_DIG_NC; } return res; @@ -147,38 +156,59 @@ dig_err_t check_dig_cred(dig_cred_t* _c) * Print credential structure content to stdout * Just for debugging */ -void print_cred(dig_cred_t* _c) +void print_cred(dig_cred_t *_c) { printf("===Digest credentials===\n"); - if (_c) { + if(_c) { printf("Username\n"); - printf("+--whole = \'%.*s\'\n", _c->username.whole.len, _c->username.whole.s); - printf("+--user = \'%.*s\'\n", _c->username.user.len, _c->username.user.s); - printf("\\--domain = \'%.*s\'\n", _c->username.domain.len, _c->username.domain.s); + printf("+--whole = \'%.*s\'\n", _c->username.whole.len, + _c->username.whole.s); + printf("+--user = \'%.*s\'\n", _c->username.user.len, + _c->username.user.s); + printf("\\--domain = \'%.*s\'\n", _c->username.domain.len, + _c->username.domain.s); printf("Realm = \'%.*s\'\n", _c->realm.len, _c->realm.s); printf("Nonce = \'%.*s\'\n", _c->nonce.len, _c->nonce.s); printf("URI = \'%.*s\'\n", _c->uri.len, _c->uri.s); printf("Response = \'%.*s\'\n", _c->response.len, _c->response.s); - printf("Algorithm = \'%.*s\'\n", _c->alg.alg_str.len, _c->alg.alg_str.s); + printf("Algorithm = \'%.*s\'\n", _c->alg.alg_str.len, + _c->alg.alg_str.s); printf("\\--parsed = "); switch(_c->alg.alg_parsed) { - case ALG_UNSPEC: printf("ALG_UNSPEC\n"); break; - case ALG_MD5: printf("ALG_MD5\n"); break; - case ALG_MD5SESS: printf("ALG_MD5SESS\n"); break; - case ALG_OTHER: printf("ALG_OTHER\n"); break; + case ALG_UNSPEC: + printf("ALG_UNSPEC\n"); + break; + case ALG_MD5: + printf("ALG_MD5\n"); + break; + case ALG_MD5SESS: + printf("ALG_MD5SESS\n"); + break; + case ALG_OTHER: + printf("ALG_OTHER\n"); + break; } printf("Cnonce = \'%.*s\'\n", _c->cnonce.len, _c->cnonce.s); printf("Opaque = \'%.*s\'\n", _c->opaque.len, _c->opaque.s); - printf("QOP = \'%.*s\'\n", _c->qop.qop_str.len, _c->qop.qop_str.s); + printf("QOP = \'%.*s\'\n", _c->qop.qop_str.len, + _c->qop.qop_str.s); printf("\\--parsed = "); switch(_c->qop.qop_parsed) { - case QOP_UNSPEC: printf("QOP_UNSPEC\n"); break; - case QOP_AUTH: printf("QOP_AUTH\n"); break; - case QOP_AUTHINT: printf("QOP_AUTHINT\n"); break; - case QOP_OTHER: printf("QOP_OTHER\n"); break; + case QOP_UNSPEC: + printf("QOP_UNSPEC\n"); + break; + case QOP_AUTH: + printf("QOP_AUTH\n"); + break; + case QOP_AUTHINT: + printf("QOP_AUTHINT\n"); + break; + case QOP_OTHER: + printf("QOP_OTHER\n"); + break; } printf("NC = \'%.*s\'\n", _c->nc.len, _c->nc.s); } @@ -192,26 +222,30 @@ void print_cred(dig_cred_t* _c) * to use if the message contained more than * one */ -int mark_authorized_cred(struct sip_msg* _m, struct hdr_field* _h) +int mark_authorized_cred(struct sip_msg *_m, struct hdr_field *_h) { - struct hdr_field* f; + struct hdr_field *f; switch(_h->type) { - case HDR_AUTHORIZATION_T: f = _m->authorization; break; - case HDR_PROXYAUTH_T: f = _m->proxy_auth; break; - default: - LM_ERR("invalid header field type\n"); - return -1; + case HDR_AUTHORIZATION_T: + f = _m->authorization; + break; + case HDR_PROXYAUTH_T: + f = _m->proxy_auth; + break; + default: + LM_ERR("invalid header field type\n"); + return -1; } - if (!(f->parsed)) { - if (new_credentials(f) < 0) { + if(!(f->parsed)) { + if(new_credentials(f) < 0) { LM_ERR("error in new_credentials\n"); return -1; } } - ((auth_body_t*)(f->parsed))->authorized = _h; + ((auth_body_t *)(f->parsed))->authorized = _h; return 0; } @@ -221,10 +255,10 @@ int mark_authorized_cred(struct sip_msg* _m, struct hdr_field* _h) * Get pointer to authorized credentials, if there are no * authorized credentials, 0 is returned */ -int get_authorized_cred(struct hdr_field* _f, struct hdr_field** _h) +int get_authorized_cred(struct hdr_field *_f, struct hdr_field **_h) { - if (_f && _f->parsed) { - *_h = ((auth_body_t*)(_f->parsed))->authorized; + if(_f && _f->parsed) { + *_h = ((auth_body_t *)(_f->parsed))->authorized; } else { *_h = 0; } @@ -236,13 +270,13 @@ int get_authorized_cred(struct hdr_field* _f, struct hdr_field** _h) /* * Find credentials with given realm in a SIP message header */ -int find_credentials(struct sip_msg* msg, str* realm, - hdr_types_t hftype, struct hdr_field** hdr) +int find_credentials(struct sip_msg *msg, str *realm, hdr_types_t hftype, + struct hdr_field **hdr) { - struct hdr_field** hook, *ptr; + struct hdr_field **hook, *ptr; hdr_flags_t hdr_flags; int res; - str* r; + str *r; /* * Determine if we should use WWW-Authorization or @@ -250,27 +284,28 @@ int find_credentials(struct sip_msg* msg, str* realm, * is set in www_authorize and proxy_authorize */ switch(hftype) { - case HDR_AUTHORIZATION_T: - hook = &(msg->authorization); - hdr_flags=HDR_AUTHORIZATION_F; - break; - case HDR_PROXYAUTH_T: - hook = &(msg->proxy_auth); - hdr_flags=HDR_PROXYAUTH_F; - break; - default: - LM_WARN("unexpected header type %d - using authorization\n", hftype); - hook = &(msg->authorization); - hdr_flags=HDR_AUTHORIZATION_F; - break; + case HDR_AUTHORIZATION_T: + hook = &(msg->authorization); + hdr_flags = HDR_AUTHORIZATION_F; + break; + case HDR_PROXYAUTH_T: + hook = &(msg->proxy_auth); + hdr_flags = HDR_PROXYAUTH_F; + break; + default: + LM_WARN("unexpected header type %d - using authorization\n", + hftype); + hook = &(msg->authorization); + hdr_flags = HDR_AUTHORIZATION_F; + break; } /* * If the credentials haven't been parsed yet, do it now */ - if (*hook == 0) { + if(*hook == 0) { /* No credentials parsed yet */ - if (parse_headers(msg, hdr_flags, 0) == -1) { + if(parse_headers(msg, hdr_flags, 0) == -1) { LM_ERR("error while parsing headers\n"); return -1; } @@ -284,26 +319,26 @@ int find_credentials(struct sip_msg* msg, str* realm, */ while(ptr) { res = parse_credentials(ptr); - if (res < 0) { + if(res < 0) { LM_ERR("error while parsing credentials\n"); return (res == -1) ? -2 : -3; - } else if (res == 0) { - r = &(((auth_body_t*)(ptr->parsed))->digest.realm); + } else if(res == 0) { + r = &(((auth_body_t *)(ptr->parsed))->digest.realm); - if (r->len == realm->len) { - if (!strncasecmp(realm->s, r->s, r->len)) { + if(r->len == realm->len) { + if(!strncasecmp(realm->s, r->s, r->len)) { *hdr = ptr; return 0; } } } - if (parse_headers(msg, hdr_flags, 1) == -1) { + if(parse_headers(msg, hdr_flags, 1) == -1) { LM_ERR("error while parsing headers\n"); return -4; } else { ptr = next_sibling_hdr(ptr); - if (!ptr) + if(!ptr) break; } } diff --git a/src/core/parser/digest/digest.h b/src/core/parser/digest/digest.h index 64f48c980a3..3756c668af0 100644 --- a/src/core/parser/digest/digest.h +++ b/src/core/parser/digest/digest.h @@ -20,8 +20,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ @@ -30,12 +30,13 @@ #define DIGEST_H #include "digest_parser.h" -#include "../hf.h" /* struct hdr_field */ +#include "../hf.h" /* struct hdr_field */ #include "../msg_parser.h" -typedef struct auth_body { - /* This is pointer to header field containing +typedef struct auth_body +{ + /* This is pointer to header field containing * parsed authorized digest credentials. This * pointer is set in sip_msg->{authorization,proxy_auth} * hooks. @@ -43,73 +44,74 @@ typedef struct auth_body { * This is necessary for functions called after * {www,proxy}_authorize, these functions need to know * which credentials are authorized and they will simply - * look into + * look into * sip_msg->{authorization,proxy_auth}->parsed->authorized */ - struct hdr_field* authorized; - dig_cred_t digest; /* Parsed digest credentials */ - unsigned char stale; /* Flag is set if nonce is stale */ + struct hdr_field *authorized; + dig_cred_t digest; /* Parsed digest credentials */ + unsigned char stale; /* Flag is set if nonce is stale */ } auth_body_t; /* * Errors returned by check_dig_cred */ -typedef enum dig_err { - E_DIG_OK = 0, /* Everything is OK */ - E_DIG_USERNAME = 1, /* Username missing */ - E_DIG_REALM = 2, /* Realm missing */ - E_DIG_NONCE = 4, /* Nonce value missing */ - E_DIG_URI = 8, /* URI missing */ +typedef enum dig_err +{ + E_DIG_OK = 0, /* Everything is OK */ + E_DIG_USERNAME = 1, /* Username missing */ + E_DIG_REALM = 2, /* Realm missing */ + E_DIG_NONCE = 4, /* Nonce value missing */ + E_DIG_URI = 8, /* URI missing */ E_DIG_RESPONSE = 16, /* Response missing */ - E_DIG_CNONCE = 32, /* CNONCE missing */ - E_DIG_NC = 64, /* Nonce-count missing */ - E_DIG_DOMAIN = 128 /* Username domain != realm */ + E_DIG_CNONCE = 32, /* CNONCE missing */ + E_DIG_NC = 64, /* Nonce-count missing */ + E_DIG_DOMAIN = 128 /* Username domain != realm */ } dig_err_t; /* * Parse digest credentials */ -int parse_credentials(struct hdr_field* _h); +int parse_credentials(struct hdr_field *_h); /* * Free all memory associated with parsed * structures */ -void free_credentials(auth_body_t** _b); +void free_credentials(auth_body_t **_b); /* * Print dig_cred structure to stdout */ -void print_cred(dig_cred_t* _c); +void print_cred(dig_cred_t *_c); /* * Mark credentials as authorized */ -int mark_authorized_cred(struct sip_msg* _m, struct hdr_field* _h); +int mark_authorized_cred(struct sip_msg *_m, struct hdr_field *_h); /* * Get pointer to authorized credentials */ -int get_authorized_cred(struct hdr_field* _f, struct hdr_field** _h); +int get_authorized_cred(struct hdr_field *_f, struct hdr_field **_h); /* * Check if credentials are correct * (check of semantics) */ -dig_err_t check_dig_cred(dig_cred_t* _c); +dig_err_t check_dig_cred(dig_cred_t *_c); /* * Find credentials with given realm in a SIP message header */ -int find_credentials(struct sip_msg* msg, str* realm, - hdr_types_t hftype, struct hdr_field** hdr); +int find_credentials(struct sip_msg *msg, str *realm, hdr_types_t hftype, + struct hdr_field **hdr); #endif /* DIGEST_H */ diff --git a/src/core/parser/digest/digest_keys.h b/src/core/parser/digest/digest_keys.h index 7ee8686e96a..254a836b95b 100644 --- a/src/core/parser/digest/digest_keys.h +++ b/src/core/parser/digest/digest_keys.h @@ -20,8 +20,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ @@ -29,15 +29,15 @@ #ifndef DIGEST_KEYS_H #define DIGEST_KEYS_H -#define _user_ 0x72657375 /* "user" */ -#define _name_ 0x656d616e /* "name" */ -#define _real_ 0x6c616572 /* "real" */ -#define _nonc_ 0x636e6f6e /* "nonc" */ -#define _resp_ 0x70736572 /* "resp" */ -#define _onse_ 0x65736e6f /* "onse" */ -#define _cnon_ 0x6e6f6e63 /* "cnon" */ -#define _opaq_ 0x7161706f /* "opaq" */ -#define _algo_ 0x6f676c61 /* "algo" */ -#define _rith_ 0x68746972 /* "rith" */ +#define _user_ 0x72657375 /* "user" */ +#define _name_ 0x656d616e /* "name" */ +#define _real_ 0x6c616572 /* "real" */ +#define _nonc_ 0x636e6f6e /* "nonc" */ +#define _resp_ 0x70736572 /* "resp" */ +#define _onse_ 0x65736e6f /* "onse" */ +#define _cnon_ 0x6e6f6e63 /* "cnon" */ +#define _opaq_ 0x7161706f /* "opaq" */ +#define _algo_ 0x6f676c61 /* "algo" */ +#define _rith_ 0x68746972 /* "rith" */ #endif /* DIGEST_KEYS_H */ diff --git a/src/core/parser/digest/digest_parser.c b/src/core/parser/digest/digest_parser.c index 57a5dc1719a..9ce9d184099 100644 --- a/src/core/parser/digest/digest_parser.c +++ b/src/core/parser/digest/digest_parser.c @@ -20,8 +20,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * History: @@ -30,12 +30,11 @@ */ - #include "digest_parser.h" -#include "../../trim.h" /* trim_leading */ -#include /* strncasecmp */ -#include "param_parser.h" /* Digest parameter name parser */ -#include "../../ut.h" /* q_memchr */ +#include "../../trim.h" /* trim_leading */ +#include /* strncasecmp */ +#include "param_parser.h" /* Digest parameter name parser */ +#include "../../ut.h" /* q_memchr */ #define DIGEST_SCHEME "digest" @@ -60,43 +59,43 @@ * parameter and update _s to point behind the * closing quote */ -static inline int parse_quoted(str* _s, str* _r) +static inline int parse_quoted(str *_s, str *_r) { - char* end_quote; + char *end_quote; - /* The string must have at least + /* The string must have at least * surrounding quotes */ - if (_s->len < 2) { + if(_s->len < 2) { return -1; } - /* Skip opening quote */ + /* Skip opening quote */ _s->s++; _s->len--; - /* Find closing quote */ + /* Find closing quote */ end_quote = q_memchr(_s->s, '\"', _s->len); - /* Not found, return error */ - if (!end_quote) { + /* Not found, return error */ + if(!end_quote) { return -2; } - /* Let _r point to the string without + /* Let _r point to the string without * surrounding quotes */ _r->s = _s->s; _r->len = end_quote - _s->s; - /* Update _s parameter to point + /* Update _s parameter to point * behind the closing quote */ _s->len -= (end_quote - _s->s + 1); _s->s = end_quote + 1; - /* Everything went OK */ + /* Everything went OK */ return 0; } @@ -106,52 +105,52 @@ static inline int parse_quoted(str* _s, str* _r) * let _r point to the token and update _s * to point right behind the token */ -static inline int parse_token(str* _s, str* _r) +static inline int parse_token(str *_s, str *_r) { int i; - /* Save the beginning of the + /* Save the beginning of the * token in _r->s */ _r->s = _s->s; - /* Iterate through the + /* Iterate through the * token body */ for(i = 0; i < _s->len; i++) { - /* All these characters + /* All these characters * mark end of the token */ switch(_s->s[i]) { - case ' ': - case '\t': - case '\r': - case '\n': - case ',': - /* So if you find + case ' ': + case '\t': + case '\r': + case '\n': + case ',': + /* So if you find * any of them * stop iterating */ - goto out; + goto out; } } - out: - /* Empty token is error */ - if (i == 0) { - return -2; +out: + /* Empty token is error */ + if(i == 0) { + return -2; } - /* Save length of the token */ - _r->len = i; + /* Save length of the token */ + _r->len = i; - /* Update _s parameter so it points + /* Update _s parameter so it points * right behind the end of the token */ _s->s = _s->s + i; _s->len -= i; - /* Everything went OK */ + /* Everything went OK */ return 0; } @@ -159,58 +158,82 @@ static inline int parse_token(str* _s, str* _r) /* * Parse a digest parameter */ -static inline int parse_digest_param(str* _s, dig_cred_t* _c) +static inline int parse_digest_param(str *_s, dig_cred_t *_c) { dig_par_t t; - str* ptr; + str *ptr; str dummy; - /* Get type of the parameter */ - if (parse_param_name(_s, &t) < 0) { + /* Get type of the parameter */ + if(parse_param_name(_s, &t) < 0) { return -1; } - _s->s++; /* skip = */ + _s->s++; /* skip = */ _s->len--; - /* Find the beginning of body */ + /* Find the beginning of body */ trim_leading(_s); - if (_s->len == 0) { + if(_s->len == 0) { return -2; } - /* Decide in which attribute the + /* Decide in which attribute the * body content will be stored */ switch(t) { - case PAR_USERNAME: ptr = &_c->username.whole; break; - case PAR_REALM: ptr = &_c->realm; break; - case PAR_NONCE: ptr = &_c->nonce; break; - case PAR_URI: ptr = &_c->uri; break; - case PAR_RESPONSE: ptr = &_c->response; break; - case PAR_CNONCE: ptr = &_c->cnonce; break; - case PAR_OPAQUE: ptr = &_c->opaque; break; - case PAR_QOP: ptr = &_c->qop.qop_str; break; - case PAR_NC: ptr = &_c->nc; break; - case PAR_ALGORITHM: ptr = &_c->alg.alg_str; break; - case PAR_OTHER: ptr = &dummy; break; - default: ptr = &dummy; break; + case PAR_USERNAME: + ptr = &_c->username.whole; + break; + case PAR_REALM: + ptr = &_c->realm; + break; + case PAR_NONCE: + ptr = &_c->nonce; + break; + case PAR_URI: + ptr = &_c->uri; + break; + case PAR_RESPONSE: + ptr = &_c->response; + break; + case PAR_CNONCE: + ptr = &_c->cnonce; + break; + case PAR_OPAQUE: + ptr = &_c->opaque; + break; + case PAR_QOP: + ptr = &_c->qop.qop_str; + break; + case PAR_NC: + ptr = &_c->nc; + break; + case PAR_ALGORITHM: + ptr = &_c->alg.alg_str; + break; + case PAR_OTHER: + ptr = &dummy; + break; + default: + ptr = &dummy; + break; } - /* If the first character is quote, it is + /* If the first character is quote, it is * a quoted string, otherwise it is a token */ - if (_s->s[0] == '\"') { - if (parse_quoted(_s, ptr) < 0) { + if(_s->s[0] == '\"') { + if(parse_quoted(_s, ptr) < 0) { return -3; } } else { - if (parse_token(_s, ptr) < 0) { + if(parse_token(_s, ptr) < 0) { return -4; } } - + return 0; } @@ -218,7 +241,7 @@ static inline int parse_digest_param(str* _s, dig_cred_t* _c) /* * Parse qop parameter body */ -void parse_qop(struct qp* _q) +void parse_qop(struct qp *_q) { str s; @@ -227,13 +250,13 @@ void parse_qop(struct qp* _q) trim(&s); - if (s.len == 0) { - _q->qop_parsed = QOP_UNSPEC; - } else if ((s.len == QOP_AUTH_STR_LEN) && - !strncasecmp(s.s, QOP_AUTH_STR, QOP_AUTH_STR_LEN)) { + if(s.len == 0) { + _q->qop_parsed = QOP_UNSPEC; + } else if((s.len == QOP_AUTH_STR_LEN) + && !strncasecmp(s.s, QOP_AUTH_STR, QOP_AUTH_STR_LEN)) { _q->qop_parsed = QOP_AUTH; - } else if ((s.len == QOP_AUTHINT_STR_LEN) && - !strncasecmp(s.s, QOP_AUTHINT_STR, QOP_AUTHINT_STR_LEN)) { + } else if((s.len == QOP_AUTHINT_STR_LEN) + && !strncasecmp(s.s, QOP_AUTHINT_STR, QOP_AUTHINT_STR_LEN)) { _q->qop_parsed = QOP_AUTHINT; } else { _q->qop_parsed = QOP_OTHER; @@ -244,7 +267,7 @@ void parse_qop(struct qp* _q) /* * Parse algorithm parameter body */ -static inline void parse_algorithm(struct algorithm* _a) +static inline void parse_algorithm(struct algorithm *_a) { str s; @@ -253,32 +276,33 @@ static inline void parse_algorithm(struct algorithm* _a) trim(&s); - if ((s.len == ALG_MD5_STR_LEN) && - !strncasecmp(s.s, ALG_MD5_STR, ALG_MD5_STR_LEN)) { + if((s.len == ALG_MD5_STR_LEN) + && !strncasecmp(s.s, ALG_MD5_STR, ALG_MD5_STR_LEN)) { _a->alg_parsed = ALG_MD5; - } else if ((s.len == ALG_MD5SESS_STR_LEN) && - !strncasecmp(s.s, ALG_MD5SESS_STR, ALG_MD5SESS_STR_LEN)) { + } else if((s.len == ALG_MD5SESS_STR_LEN) + && !strncasecmp(s.s, ALG_MD5SESS_STR, ALG_MD5SESS_STR_LEN)) { _a->alg_parsed = ALG_MD5SESS; } else { _a->alg_parsed = ALG_OTHER; - } + } } /* * Parse username for user and domain parts */ -static inline void parse_username(struct username* _u) +static inline void parse_username(struct username *_u) { - char* d; + char *d; _u->user = _u->whole; - if (_u->whole.len <= 2) return; + if(_u->whole.len <= 2) + return; /* get domain - it can be: username@domain */ d = q_memchr(_u->whole.s, '@', _u->whole.len); - if (d) { + if(d) { _u->domain.s = d + 1; _u->domain.len = _u->whole.len - (d - _u->whole.s) - 1; _u->user.len = d - _u->user.s; @@ -286,7 +310,7 @@ static inline void parse_username(struct username* _u) /* get user - it can be: sip:username@domain */ d = q_memchr(_u->user.s, ':', _u->user.len); - if (d) { + if(d) { _u->user.len = _u->user.s + _u->user.len - d - 1; _u->user.s = d + 1; } @@ -296,20 +320,20 @@ static inline void parse_username(struct username* _u) /* * Parse Digest credentials parameter, one by one */ -static inline int parse_digest_params(str* _s, dig_cred_t* _c) +static inline int parse_digest_params(str *_s, dig_cred_t *_c) { - char* comma; + char *comma; do { - /* Parse the first parameter */ - if (parse_digest_param(_s, _c) < 0) { + /* Parse the first parameter */ + if(parse_digest_param(_s, _c) < 0) { return -1; } - - /* Try to find the next parameter */ + + /* Try to find the next parameter */ comma = q_memchr(_s->s, ',', _s->len); - if (comma) { - /* Yes, there is another, + if(comma) { + /* Yes, there is another, * remove any leading white-spaces * and let _s point to the next * parameter name @@ -320,17 +344,17 @@ static inline int parse_digest_params(str* _s, dig_cred_t* _c) } } while(comma); /* Repeat while there are next parameters */ - /* Parse QOP body if the parameter was present */ - if (_c->qop.qop_str.s != 0) { + /* Parse QOP body if the parameter was present */ + if(_c->qop.qop_str.s != 0) { parse_qop(&_c->qop); } - /* Parse algorithm body if the parameter was present */ - if (_c->alg.alg_str.s != 0) { + /* Parse algorithm body if the parameter was present */ + if(_c->alg.alg_str.s != 0) { parse_algorithm(&_c->alg); } - if (_c->username.whole.s != 0) { + if(_c->username.whole.s != 0) { parse_username(&_c->username); } @@ -346,40 +370,39 @@ static inline int parse_digest_params(str* _s, dig_cred_t* _c) * -1 - Error while parsing * 1 - Unknown scheme */ -int parse_digest_cred(str* _s, dig_cred_t* _c) +int parse_digest_cred(str *_s, dig_cred_t *_c) { str tmp; - /* Make a temporary copy, we are - * going to modify it + /* Make a temporary copy, we are + * going to modify it */ tmp.s = _s->s; tmp.len = _s->len; - /* Remove any leading spaces, tabs, \r and \n */ + /* Remove any leading spaces, tabs, \r and \n */ trim_leading(&tmp); - /* Check the string length */ - if (tmp.len < (DIG_LEN + 1)) return 1; /* Too short, unknown scheme */ + /* Check the string length */ + if(tmp.len < (DIG_LEN + 1)) + return 1; /* Too short, unknown scheme */ - /* Now test, if it is digest scheme, since it is the only + /* Now test, if it is digest scheme, since it is the only * scheme we are able to parse here */ - if (!strncasecmp(tmp.s, DIGEST_SCHEME, DIG_LEN) && - ((tmp.s[DIG_LEN] == ' ') || /* Test for one of LWS chars */ - (tmp.s[DIG_LEN] == '\r') || - (tmp.s[DIG_LEN] == '\n') || - (tmp.s[DIG_LEN] == '\t') || - (tmp.s[DIG_LEN] == ','))) { - /* Scheme is Digest */ + if(!strncasecmp(tmp.s, DIGEST_SCHEME, DIG_LEN) + && ((tmp.s[DIG_LEN] == ' ') || /* Test for one of LWS chars */ + (tmp.s[DIG_LEN] == '\r') || (tmp.s[DIG_LEN] == '\n') + || (tmp.s[DIG_LEN] == '\t') || (tmp.s[DIG_LEN] == ','))) { + /* Scheme is Digest */ tmp.s += DIG_LEN + 1; tmp.len -= DIG_LEN + 1; - - /* Again, skip all white-spaces */ + + /* Again, skip all white-spaces */ trim_leading(&tmp); - /* And parse digest parameters */ - if (parse_digest_params(&tmp, _c) < 0) { + /* And parse digest parameters */ + if(parse_digest_params(&tmp, _c) < 0) { return -2; /* We must not return -1 in this function ! */ } else { return 0; @@ -393,8 +416,7 @@ int parse_digest_cred(str* _s, dig_cred_t* _c) /* * Initialize a digest credentials structure */ -void init_dig_cred(dig_cred_t* _c) +void init_dig_cred(dig_cred_t *_c) { memset(_c, 0, sizeof(dig_cred_t)); } - diff --git a/src/core/parser/digest/digest_parser.h b/src/core/parser/digest/digest_parser.h index fd3f9969b48..f52894abfce 100644 --- a/src/core/parser/digest/digest_parser.h +++ b/src/core/parser/digest/digest_parser.h @@ -20,8 +20,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * History: @@ -31,7 +31,6 @@ */ - #ifndef DIGEST_PARSER_H #define DIGEST_PARSER_H @@ -39,59 +38,65 @@ /* Type of algorithm used */ -typedef enum alg { - ALG_UNSPEC = 0, /* Algorithm parameter not specified */ - ALG_MD5 = 1, /* MD5 - default value*/ - ALG_MD5SESS = 2, /* MD5-Session */ - ALG_OTHER = 4 /* Unknown */ +typedef enum alg +{ + ALG_UNSPEC = 0, /* Algorithm parameter not specified */ + ALG_MD5 = 1, /* MD5 - default value*/ + ALG_MD5SESS = 2, /* MD5-Session */ + ALG_OTHER = 4 /* Unknown */ } alg_t; /* Quality Of Protection used */ -typedef enum qop_type { - QOP_UNSPEC = 0, /* QOP parameter not present in response */ - QOP_AUTH = 1, /* Authentication only */ - QOP_AUTHINT = 2, /* Authentication with integrity checks */ - QOP_OTHER = 4 /* Unknown */ +typedef enum qop_type +{ + QOP_UNSPEC = 0, /* QOP parameter not present in response */ + QOP_AUTH = 1, /* Authentication only */ + QOP_AUTHINT = 2, /* Authentication with integrity checks */ + QOP_OTHER = 4 /* Unknown */ } qop_type_t; /* Algorithm structure */ -struct algorithm { - str alg_str; /* The original string representation */ - alg_t alg_parsed; /* Parsed value */ +struct algorithm +{ + str alg_str; /* The original string representation */ + alg_t alg_parsed; /* Parsed value */ }; /* QOP structure */ -struct qp { - str qop_str; /* The original string representation */ +struct qp +{ + str qop_str; /* The original string representation */ qop_type_t qop_parsed; /* Parsed value */ }; /* Username structure */ -struct username { - str whole; /* The whole username parameter value */ - str user; /* username part only */ - str domain; /* Domain part only */ +struct username +{ + str whole; /* The whole username parameter value */ + str user; /* username part only */ + str domain; /* Domain part only */ }; /* * Parsed digest credentials */ -typedef struct dig_cred { - struct username username; /* Username */ - str realm; /* Realm */ - str nonce; /* Nonce value */ - str uri; /* digest-uri, duplicated Request-URI of the Request-Line */ - str response; /* Response string */ - struct algorithm alg; /* Type of algorithm used */ - str cnonce; /* Cnonce value */ - str opaque; /* Opaque data string */ - struct qp qop; /* Quality Of Protection */ - str nc; /* Nonce count parameter */ +typedef struct dig_cred +{ + struct username username; /* Username */ + str realm; /* Realm */ + str nonce; /* Nonce value */ + str uri; /* digest-uri, duplicated Request-URI of the Request-Line */ + str response; /* Response string */ + struct algorithm alg; /* Type of algorithm used */ + str cnonce; /* Cnonce value */ + str opaque; /* Opaque data string */ + struct qp qop; /* Quality Of Protection */ + str nc; /* Nonce count parameter */ } dig_cred_t; @@ -103,17 +108,16 @@ typedef struct dig_cred { * is protected by the response hash) and also to allow subscribers * to specify a different domain part than the one in realm parameter */ -#define GET_REALM(cred) \ - (((cred)->username.domain.len && (cred)->username.domain.s) ? \ - &(cred)->username.domain : \ - &(cred)->realm) - +#define GET_REALM(cred) \ + (((cred)->username.domain.len && (cred)->username.domain.s) \ + ? &(cred)->username.domain \ + : &(cred)->realm) /* * Initialize a digest credentials structure */ -void init_dig_cred(dig_cred_t* _c); +void init_dig_cred(dig_cred_t *_c); /* @@ -124,12 +128,12 @@ void init_dig_cred(dig_cred_t* _c); * -1 - Error while parsing * 1 - Unknown scheme */ -int parse_digest_cred(str* _s, dig_cred_t* _c); +int parse_digest_cred(str *_s, dig_cred_t *_c); /* * Parse qop string */ -void parse_qop(struct qp* _q); +void parse_qop(struct qp *_q); #endif /* DIGEST_PARSER_H */ diff --git a/src/core/parser/digest/param_parser.c b/src/core/parser/digest/param_parser.c index 50e6e5264e3..91411f3222f 100644 --- a/src/core/parser/digest/param_parser.c +++ b/src/core/parser/digest/param_parser.c @@ -20,8 +20,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ @@ -36,35 +36,35 @@ /* * Parse short (less than 4 bytes) parameter names */ -#define PARSE_SHORT \ - switch(LOWER_BYTE(*p)) { \ - case 'u': \ - if (LOWER_BYTE(*(p + 1)) == 'r') { \ - if (LOWER_BYTE(*(p + 2)) == 'i') { \ - *_type = PAR_URI; \ - p += 3; \ - goto end; \ - } \ - } \ - break; \ - \ - case 'q': \ - if (LOWER_BYTE(*(p + 1)) == 'o') { \ - if (LOWER_BYTE(*(p + 2)) == 'p') { \ - *_type = PAR_QOP; \ - p += 3; \ - goto end; \ - } \ - } \ - break; \ - \ - case 'n': \ - if (LOWER_BYTE(*(p + 1)) == 'c') { \ - *_type = PAR_NC; \ - p += 2; \ - goto end; \ - } \ - break; \ +#define PARSE_SHORT \ + switch(LOWER_BYTE(*p)) { \ + case 'u': \ + if(LOWER_BYTE(*(p + 1)) == 'r') { \ + if(LOWER_BYTE(*(p + 2)) == 'i') { \ + *_type = PAR_URI; \ + p += 3; \ + goto end; \ + } \ + } \ + break; \ + \ + case 'q': \ + if(LOWER_BYTE(*(p + 1)) == 'o') { \ + if(LOWER_BYTE(*(p + 2)) == 'p') { \ + *_type = PAR_QOP; \ + p += 3; \ + goto end; \ + } \ + } \ + break; \ + \ + case 'n': \ + if(LOWER_BYTE(*(p + 1)) == 'c') { \ + *_type = PAR_NC; \ + p += 2; \ + goto end; \ + } \ + break; \ } @@ -75,151 +75,156 @@ * (Sparc for example) */ #define READ(val) \ -(*(val + 0) + (*(val + 1) << 8) + (*(val + 2) << 16) + (*(val + 3) << 24)) + (*(val + 0) + (*(val + 1) << 8) + (*(val + 2) << 16) + (*(val + 3) << 24)) -#define name_CASE \ - switch(LOWER_DWORD(val)) { \ - case _name_: \ - *_type = PAR_USERNAME; \ - p += 4; \ - goto end; \ - } +#define name_CASE \ + switch(LOWER_DWORD(val)) { \ + case _name_: \ + *_type = PAR_USERNAME; \ + p += 4; \ + goto end; \ + } -#define user_CASE \ - p += 4; \ - val = READ(p); \ - name_CASE; \ - goto other; +#define user_CASE \ + p += 4; \ + val = READ(p); \ + name_CASE; \ + goto other; -#define real_CASE \ - p += 4; \ - if (LOWER_BYTE(*p) == 'm') { \ - *_type = PAR_REALM; \ - p++; \ - goto end; \ +#define real_CASE \ + p += 4; \ + if(LOWER_BYTE(*p) == 'm') { \ + *_type = PAR_REALM; \ + p++; \ + goto end; \ } -#define nonc_CASE \ - p += 4; \ - if (LOWER_BYTE(*p) == 'e') { \ - *_type = PAR_NONCE; \ - p++; \ - goto end; \ +#define nonc_CASE \ + p += 4; \ + if(LOWER_BYTE(*p) == 'e') { \ + *_type = PAR_NONCE; \ + p++; \ + goto end; \ } -#define onse_CASE \ - switch(LOWER_DWORD(val)) { \ - case _onse_: \ - *_type = PAR_RESPONSE; \ - p += 4; \ - goto end; \ - } - - -#define resp_CASE \ - p += 4; \ - val = READ(p); \ - onse_CASE; \ - goto other; - - -#define cnon_CASE \ - p += 4; \ - if (LOWER_BYTE(*p) == 'c') { \ - p++; \ - if (LOWER_BYTE(*p) == 'e') { \ - *_type = PAR_CNONCE; \ - p++; \ - goto end; \ - } \ - } \ - goto other; - - -#define opaq_CASE \ - p += 4; \ - if (LOWER_BYTE(*p) == 'u') { \ - p++; \ - if (LOWER_BYTE(*p) == 'e') { \ - *_type = PAR_OPAQUE; \ - p++; \ - goto end; \ - } \ - } \ - goto other; - - -#define rith_CASE \ - switch(LOWER_DWORD(val)) { \ - case _rith_: \ - p += 4; \ - if (LOWER_BYTE(*p) == 'm') { \ - *_type = PAR_ALGORITHM; \ - p++; \ - goto end; \ - } \ - goto other; \ +#define onse_CASE \ + switch(LOWER_DWORD(val)) { \ + case _onse_: \ + *_type = PAR_RESPONSE; \ + p += 4; \ + goto end; \ } -#define algo_CASE \ - p += 4; \ - val = READ(p); \ - rith_CASE; \ - goto other +#define resp_CASE \ + p += 4; \ + val = READ(p); \ + onse_CASE; \ + goto other; + + +#define cnon_CASE \ + p += 4; \ + if(LOWER_BYTE(*p) == 'c') { \ + p++; \ + if(LOWER_BYTE(*p) == 'e') { \ + *_type = PAR_CNONCE; \ + p++; \ + goto end; \ + } \ + } \ + goto other; + + +#define opaq_CASE \ + p += 4; \ + if(LOWER_BYTE(*p) == 'u') { \ + p++; \ + if(LOWER_BYTE(*p) == 'e') { \ + *_type = PAR_OPAQUE; \ + p++; \ + goto end; \ + } \ + } \ + goto other; + + +#define rith_CASE \ + switch(LOWER_DWORD(val)) { \ + case _rith_: \ + p += 4; \ + if(LOWER_BYTE(*p) == 'm') { \ + *_type = PAR_ALGORITHM; \ + p++; \ + goto end; \ + } \ + goto other; \ + } -#define FIRST_QUATERNIONS \ - case _user_: user_CASE; \ - case _real_: real_CASE; \ - case _nonc_: nonc_CASE; \ - case _resp_: resp_CASE; \ - case _cnon_: cnon_CASE; \ - case _opaq_: opaq_CASE; \ - case _algo_: algo_CASE; +#define algo_CASE \ + p += 4; \ + val = READ(p); \ + rith_CASE; \ + goto other +#define FIRST_QUATERNIONS \ + case _user_: \ + user_CASE; \ + case _real_: \ + real_CASE; \ + case _nonc_: \ + nonc_CASE; \ + case _resp_: \ + resp_CASE; \ + case _cnon_: \ + cnon_CASE; \ + case _opaq_: \ + opaq_CASE; \ + case _algo_: \ + algo_CASE; -int parse_param_name(str* _s, dig_par_t* _type) +int parse_param_name(str *_s, dig_par_t *_type) { - register char* p; - register int val; - char* end; - + register char *p; + register int val; + char *end; + end = _s->s + _s->len; - + p = _s->s; val = READ(p); - - if (_s->len < 4) { + + if(_s->len < 4) { goto other; } - - switch(LOWER_DWORD(val)) { - FIRST_QUATERNIONS; - default: - PARSE_SHORT; - goto other; - } - end: + switch(LOWER_DWORD(val)) { + FIRST_QUATERNIONS; + default: + PARSE_SHORT; + goto other; + } + +end: _s->len -= p - _s->s; _s->s = p; trim_leading(_s); - if (_s->s[0] == '=') { + if(_s->s[0] == '=') { return 0; } - - other: + +other: p = q_memchr(p, '=', end - p); - if (!p) { + if(!p) { return -1; /* Parse error */ } else { *_type = PAR_OTHER; diff --git a/src/core/parser/digest/param_parser.h b/src/core/parser/digest/param_parser.h index 2952e2a793d..9432a82e8cc 100644 --- a/src/core/parser/digest/param_parser.h +++ b/src/core/parser/digest/param_parser.h @@ -20,8 +20,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ @@ -35,24 +35,25 @@ /* * Digest parameter types */ -typedef enum dig_par { +typedef enum dig_par +{ PAR_USERNAME, /* username parameter */ - PAR_REALM, /* realm parameter */ - PAR_NONCE, /* nonce parameter */ - PAR_URI, /* uri parameter */ + PAR_REALM, /* realm parameter */ + PAR_NONCE, /* nonce parameter */ + PAR_URI, /* uri parameter */ PAR_RESPONSE, /* response parameter */ - PAR_CNONCE, /* cnonce parameter */ - PAR_OPAQUE, /* opaque parameter */ - PAR_QOP, /* qop parameter */ - PAR_NC, /* nonce-count parameter */ + PAR_CNONCE, /* cnonce parameter */ + PAR_OPAQUE, /* opaque parameter */ + PAR_QOP, /* qop parameter */ + PAR_NC, /* nonce-count parameter */ PAR_ALGORITHM, /* algorithm parameter */ - PAR_OTHER /* unknown parameter */ + PAR_OTHER /* unknown parameter */ } dig_par_t; /* * Parse digest parameter name */ -int parse_param_name(str* _s, dig_par_t* _type); +int parse_param_name(str *_s, dig_par_t *_type); #endif /* PARAM_PARSER_H */ diff --git a/src/core/parser/hf.c b/src/core/parser/hf.c index 4ce11346b71..d1ed5c1bb92 100644 --- a/src/core/parser/hf.c +++ b/src/core/parser/hf.c @@ -50,155 +50,155 @@ /** Frees a hdr_field structure. * WARNING: it frees only parsed (and not name.s, body.s) */ -void clean_hdr_field(struct hdr_field* const hf) +void clean_hdr_field(struct hdr_field *const hf) { - void** h_parsed; + void **h_parsed; - if (hf->parsed){ - h_parsed=&hf->parsed; /* strict aliasing warnings workaround */ - switch(hf->type){ - /* headers with pkg alloc for parsed structure (alphabetic order) */ - case HDR_ACCEPT_T: - pkg_free(hf->parsed); - break; - - case HDR_ALLOW_T: - free_allow_header(hf); - break; - - case HDR_AUTHORIZATION_T: - free_credentials((auth_body_t**)h_parsed); - break; - - case HDR_CONTACT_T: - free_contact((contact_body_t**)h_parsed); - break; - - case HDR_CONTENTDISPOSITION_T: - free_disposition( ((struct disposition**)h_parsed)); - break; - - case HDR_CSEQ_T: - free_cseq(hf->parsed); - break; - - case HDR_DATE_T: - free_date(hf->parsed); - break; - - case HDR_DIVERSION_T: - free_to(hf->parsed); - break; - - case HDR_EVENT_T: - free_event((event_t**)h_parsed); - break; - - case HDR_EXPIRES_T: - free_expires((exp_body_t**)h_parsed); - break; - - case HDR_MIN_EXPIRES_T: - free_expires((exp_body_t**)h_parsed); - break; - - case HDR_FROM_T: - free_to(hf->parsed); - break; - - case HDR_IDENTITY_INFO_T: - free_identityinfo(hf->parsed); - break; - - case HDR_IDENTITY_T: - free_identity(hf->parsed); - break; - - case HDR_PAI_T: - free_pai_ppi_body(hf->parsed); - break; - - case HDR_PPI_T: - free_pai_ppi_body(hf->parsed); - break; - - case HDR_PROXYAUTH_T: - free_credentials((auth_body_t**)h_parsed); - break; - - case HDR_RECORDROUTE_T: - free_rr((rr_t**)h_parsed); - break; - - case HDR_REFER_TO_T: - free_to(hf->parsed); - break; - - case HDR_ROUTE_T: - free_rr((rr_t**)h_parsed); - break; - - case HDR_RPID_T: - free_to(hf->parsed); - break; - - case HDR_SESSIONEXPIRES_T: - hdr_free_parsed(h_parsed); - break; - - case HDR_SIPIFMATCH_T: - free_sipifmatch((str **)h_parsed); - break; - - case HDR_SUBSCRIPTION_STATE_T: - free_subscription_state((subscription_state_t**)h_parsed); - break; - - case HDR_REQUIRE_T: - case HDR_SUPPORTED_T: - hdr_free_parsed(h_parsed); - break; - - case HDR_TO_T: - free_to(hf->parsed); - break; - - case HDR_VIA_T: - free_via_list(hf->parsed); - break; - - /* headers with no alloc for parsed structure */ - case HDR_CALLID_T: - case HDR_MAXFORWARDS_T: - case HDR_CONTENTTYPE_T: - case HDR_CONTENTLENGTH_T: - case HDR_RETRY_AFTER_T: - case HDR_PROXYREQUIRE_T: - case HDR_UNSUPPORTED_T: - case HDR_ACCEPTLANGUAGE_T: - case HDR_ORGANIZATION_T: - case HDR_PRIORITY_T: - case HDR_SUBJECT_T: - case HDR_USERAGENT_T: - case HDR_SERVER_T: - case HDR_MIN_SE_T: - case HDR_ACCEPTCONTACT_T: - case HDR_ALLOWEVENTS_T: - case HDR_CONTENTENCODING_T: - case HDR_REFERREDBY_T: - case HDR_REJECTCONTACT_T: - case HDR_REQUESTDISPOSITION_T: - case HDR_WWW_AUTHENTICATE_T: - case HDR_PROXY_AUTHENTICATE_T: - case HDR_PATH_T: - case HDR_PRIVACY_T: - case HDR_REASON_T: - case HDR_CALLINFO_T: - break; - - default: - LM_CRIT("BUG: unknown header type %d\n", hf->type); - break; + if(hf->parsed) { + h_parsed = &hf->parsed; /* strict aliasing warnings workaround */ + switch(hf->type) { + /* headers with pkg alloc for parsed structure (alphabetic order) */ + case HDR_ACCEPT_T: + pkg_free(hf->parsed); + break; + + case HDR_ALLOW_T: + free_allow_header(hf); + break; + + case HDR_AUTHORIZATION_T: + free_credentials((auth_body_t **)h_parsed); + break; + + case HDR_CONTACT_T: + free_contact((contact_body_t **)h_parsed); + break; + + case HDR_CONTENTDISPOSITION_T: + free_disposition(((struct disposition **)h_parsed)); + break; + + case HDR_CSEQ_T: + free_cseq(hf->parsed); + break; + + case HDR_DATE_T: + free_date(hf->parsed); + break; + + case HDR_DIVERSION_T: + free_to(hf->parsed); + break; + + case HDR_EVENT_T: + free_event((event_t **)h_parsed); + break; + + case HDR_EXPIRES_T: + free_expires((exp_body_t **)h_parsed); + break; + + case HDR_MIN_EXPIRES_T: + free_expires((exp_body_t **)h_parsed); + break; + + case HDR_FROM_T: + free_to(hf->parsed); + break; + + case HDR_IDENTITY_INFO_T: + free_identityinfo(hf->parsed); + break; + + case HDR_IDENTITY_T: + free_identity(hf->parsed); + break; + + case HDR_PAI_T: + free_pai_ppi_body(hf->parsed); + break; + + case HDR_PPI_T: + free_pai_ppi_body(hf->parsed); + break; + + case HDR_PROXYAUTH_T: + free_credentials((auth_body_t **)h_parsed); + break; + + case HDR_RECORDROUTE_T: + free_rr((rr_t **)h_parsed); + break; + + case HDR_REFER_TO_T: + free_to(hf->parsed); + break; + + case HDR_ROUTE_T: + free_rr((rr_t **)h_parsed); + break; + + case HDR_RPID_T: + free_to(hf->parsed); + break; + + case HDR_SESSIONEXPIRES_T: + hdr_free_parsed(h_parsed); + break; + + case HDR_SIPIFMATCH_T: + free_sipifmatch((str **)h_parsed); + break; + + case HDR_SUBSCRIPTION_STATE_T: + free_subscription_state((subscription_state_t **)h_parsed); + break; + + case HDR_REQUIRE_T: + case HDR_SUPPORTED_T: + hdr_free_parsed(h_parsed); + break; + + case HDR_TO_T: + free_to(hf->parsed); + break; + + case HDR_VIA_T: + free_via_list(hf->parsed); + break; + + /* headers with no alloc for parsed structure */ + case HDR_CALLID_T: + case HDR_MAXFORWARDS_T: + case HDR_CONTENTTYPE_T: + case HDR_CONTENTLENGTH_T: + case HDR_RETRY_AFTER_T: + case HDR_PROXYREQUIRE_T: + case HDR_UNSUPPORTED_T: + case HDR_ACCEPTLANGUAGE_T: + case HDR_ORGANIZATION_T: + case HDR_PRIORITY_T: + case HDR_SUBJECT_T: + case HDR_USERAGENT_T: + case HDR_SERVER_T: + case HDR_MIN_SE_T: + case HDR_ACCEPTCONTACT_T: + case HDR_ALLOWEVENTS_T: + case HDR_CONTENTENCODING_T: + case HDR_REFERREDBY_T: + case HDR_REJECTCONTACT_T: + case HDR_REQUESTDISPOSITION_T: + case HDR_WWW_AUTHENTICATE_T: + case HDR_PROXY_AUTHENTICATE_T: + case HDR_PATH_T: + case HDR_PRIVACY_T: + case HDR_REASON_T: + case HDR_CALLINFO_T: + break; + + default: + LM_CRIT("BUG: unknown header type %d\n", hf->type); + break; } } } @@ -206,13 +206,13 @@ void clean_hdr_field(struct hdr_field* const hf) /** Frees a hdr_field list. * WARNING: frees only ->parsed and ->next*/ -void free_hdr_field_lst(struct hdr_field* hf) +void free_hdr_field_lst(struct hdr_field *hf) { - struct hdr_field* foo; + struct hdr_field *foo; while(hf) { - foo=hf; - hf=hf->next; + foo = hf; + hf = hf->next; clean_hdr_field(foo); pkg_free(foo); foo = 0; @@ -220,13 +220,12 @@ void free_hdr_field_lst(struct hdr_field* hf) } /* print the content of hdr_field */ -void dump_hdr_field(struct hdr_field const* const hf ) +void dump_hdr_field(struct hdr_field const *const hf) { LM_ERR("DEBUG: type=%d, name=%.*s, " - "body=%.*s, parsed=%p, next=%p\n", - hf->type, hf->name.len, ZSW(hf->name.s), - hf->body.len, ZSW(hf->body.s), - hf->parsed, hf->next ); + "body=%.*s, parsed=%p, next=%p\n", + hf->type, hf->name.len, ZSW(hf->name.s), hf->body.len, + ZSW(hf->body.s), hf->parsed, hf->next); } /** @@ -236,11 +235,11 @@ void dump_hdr_field(struct hdr_field const* const hf ) */ void hdr_free_parsed(void **h_parsed) { - if(h_parsed==NULL || *h_parsed==NULL) + if(h_parsed == NULL || *h_parsed == NULL) return; - if(((hf_parsed_t*)(*h_parsed))->hfree) { - ((hf_parsed_t*)(*h_parsed))->hfree(*h_parsed); + if(((hf_parsed_t *)(*h_parsed))->hfree) { + ((hf_parsed_t *)(*h_parsed))->hfree(*h_parsed); } *h_parsed = 0; } diff --git a/src/core/parser/hf.h b/src/core/parser/hf.h index 04cb22ccb78..3b1558aeb53 100644 --- a/src/core/parser/hf.h +++ b/src/core/parser/hf.h @@ -20,13 +20,12 @@ */ /** Parser :: parse headers. - * @file + * @file * * @ingroup parser */ - #ifndef HF_H #define HF_H @@ -34,9 +33,8 @@ #include "../comp_defs.h" - /** header types enum. - * + * * @note * if you add a new type: * - make sure it's not greater than 63 @@ -47,67 +45,68 @@ * - update get_hdr_field (msg_parser.c) */ -enum _hdr_types_t { - HDR_ERROR_T = -1 /*!< Error while parsing */, - HDR_OTHER_T = 0 /*!< Some other header field */, - HDR_VIA_T = 1 /*!< Via header field */, - HDR_VIA1_T = 1 /*!< First Via header field */, - HDR_VIA2_T = 2 /*!< only used as flag */, - HDR_TO_T = 3 /*!< To header field */, - HDR_FROM_T = 4 /*!< From header field */, - HDR_CSEQ_T = 5 /*!< CSeq header field */, - HDR_CALLID_T = 6 /*!< Call-Id header field */, - HDR_CONTACT_T = 7 /*!< Contact header field */, - HDR_MAXFORWARDS_T = 8 /*!< MaxForwards header field */, - HDR_ROUTE_T = 9 /*!< Route header field */, - HDR_RECORDROUTE_T = 10 /*!< Record-Route header field */, - HDR_CONTENTTYPE_T = 11 /*!< Content-Type header field */, - HDR_CONTENTLENGTH_T = 12 /*!< Content-Length header field */, - HDR_AUTHORIZATION_T = 13 /*!< Authorization header field */, - HDR_EXPIRES_T = 14 /*!< Expires header field */, - HDR_MIN_EXPIRES_T = 15 /*!< Min-Expires header */, - HDR_PROXYAUTH_T = 16 /*!< Proxy-Authorization hdr field */, - HDR_SUPPORTED_T = 17 /*!< Supported header field */, - HDR_REQUIRE_T = 18 /*!< Require header */, - HDR_PROXYREQUIRE_T = 19 /*!< Proxy-Require header field */, - HDR_UNSUPPORTED_T = 20 /*!< Unsupported header field */, - HDR_ALLOW_T = 21 /*!< Allow header field */, - HDR_EVENT_T = 22 /*!< Event header field */, - HDR_ACCEPT_T = 23 /*!< Accept header field */, - HDR_ACCEPTLANGUAGE_T = 24 /*!< Accept-Language header field */, - HDR_ORGANIZATION_T = 25 /*!< Organization header field */, - HDR_PRIORITY_T = 26 /*!< Priority header field */, - HDR_SUBJECT_T = 27 /*!< Subject header field */, - HDR_USERAGENT_T = 28 /*!< User-Agent header field */, - HDR_SERVER_T = 29 /*!< Server header field */, - HDR_CONTENTDISPOSITION_T = 30 /*!< Content-Disposition hdr field */, - HDR_DIVERSION_T = 31 /*!< Diversion header field */, - HDR_RPID_T = 32 /*!< Remote-Party-ID header field */, - HDR_REFER_TO_T = 33 /*!< Refer-To header fields */, - HDR_SIPIFMATCH_T = 34 /*!< SIP-If-Match header field */, - HDR_SESSIONEXPIRES_T = 35 /*!< Session-Expires header */, - HDR_MIN_SE_T = 36 /*!< Min-SE */, - HDR_SUBSCRIPTION_STATE_T = 37 /*!< Subscription-State */, - HDR_ACCEPTCONTACT_T = 38 /*!< Accept-Contact header */, - HDR_ALLOWEVENTS_T = 39 /*!< Allow-Events header */, - HDR_CONTENTENCODING_T = 40 /*!< Content-Encoding header */, - HDR_REFERREDBY_T = 41 /*!< Referred-By header */, - HDR_REJECTCONTACT_T = 42 /*!< Reject-Contact header */, - HDR_REQUESTDISPOSITION_T = 43 /*!< Request-Disposition header */, - HDR_WWW_AUTHENTICATE_T = 44 /*!< WWW-Authenticate header field */, - HDR_PROXY_AUTHENTICATE_T = 45 /*!< Proxy-Authenticate header field */, - HDR_DATE_T = 46 /*!< Date header field */, - HDR_IDENTITY_T = 47 /*!< Identity header field */, - HDR_IDENTITY_INFO_T = 48 /*!< Identity-info header field */, - HDR_RETRY_AFTER_T = 49 /*!< Retry-After header field */, - HDR_PPI_T = 50 /*!< P-Preferred-Identity header field*/, - HDR_PAI_T = 51 /*!< P-Asserted-Identity header field*/, - HDR_PATH_T = 52 /*!< Path header field */, - HDR_PRIVACY_T = 53 /*!< Privacy header field */, - HDR_REASON_T = 54 /**< Reason header field */, - HDR_CALLINFO_T = 55 /*!< Call-Info header field*/, +enum _hdr_types_t +{ + HDR_ERROR_T = -1 /*!< Error while parsing */, + HDR_OTHER_T = 0 /*!< Some other header field */, + HDR_VIA_T = 1 /*!< Via header field */, + HDR_VIA1_T = 1 /*!< First Via header field */, + HDR_VIA2_T = 2 /*!< only used as flag */, + HDR_TO_T = 3 /*!< To header field */, + HDR_FROM_T = 4 /*!< From header field */, + HDR_CSEQ_T = 5 /*!< CSeq header field */, + HDR_CALLID_T = 6 /*!< Call-Id header field */, + HDR_CONTACT_T = 7 /*!< Contact header field */, + HDR_MAXFORWARDS_T = 8 /*!< MaxForwards header field */, + HDR_ROUTE_T = 9 /*!< Route header field */, + HDR_RECORDROUTE_T = 10 /*!< Record-Route header field */, + HDR_CONTENTTYPE_T = 11 /*!< Content-Type header field */, + HDR_CONTENTLENGTH_T = 12 /*!< Content-Length header field */, + HDR_AUTHORIZATION_T = 13 /*!< Authorization header field */, + HDR_EXPIRES_T = 14 /*!< Expires header field */, + HDR_MIN_EXPIRES_T = 15 /*!< Min-Expires header */, + HDR_PROXYAUTH_T = 16 /*!< Proxy-Authorization hdr field */, + HDR_SUPPORTED_T = 17 /*!< Supported header field */, + HDR_REQUIRE_T = 18 /*!< Require header */, + HDR_PROXYREQUIRE_T = 19 /*!< Proxy-Require header field */, + HDR_UNSUPPORTED_T = 20 /*!< Unsupported header field */, + HDR_ALLOW_T = 21 /*!< Allow header field */, + HDR_EVENT_T = 22 /*!< Event header field */, + HDR_ACCEPT_T = 23 /*!< Accept header field */, + HDR_ACCEPTLANGUAGE_T = 24 /*!< Accept-Language header field */, + HDR_ORGANIZATION_T = 25 /*!< Organization header field */, + HDR_PRIORITY_T = 26 /*!< Priority header field */, + HDR_SUBJECT_T = 27 /*!< Subject header field */, + HDR_USERAGENT_T = 28 /*!< User-Agent header field */, + HDR_SERVER_T = 29 /*!< Server header field */, + HDR_CONTENTDISPOSITION_T = 30 /*!< Content-Disposition hdr field */, + HDR_DIVERSION_T = 31 /*!< Diversion header field */, + HDR_RPID_T = 32 /*!< Remote-Party-ID header field */, + HDR_REFER_TO_T = 33 /*!< Refer-To header fields */, + HDR_SIPIFMATCH_T = 34 /*!< SIP-If-Match header field */, + HDR_SESSIONEXPIRES_T = 35 /*!< Session-Expires header */, + HDR_MIN_SE_T = 36 /*!< Min-SE */, + HDR_SUBSCRIPTION_STATE_T = 37 /*!< Subscription-State */, + HDR_ACCEPTCONTACT_T = 38 /*!< Accept-Contact header */, + HDR_ALLOWEVENTS_T = 39 /*!< Allow-Events header */, + HDR_CONTENTENCODING_T = 40 /*!< Content-Encoding header */, + HDR_REFERREDBY_T = 41 /*!< Referred-By header */, + HDR_REJECTCONTACT_T = 42 /*!< Reject-Contact header */, + HDR_REQUESTDISPOSITION_T = 43 /*!< Request-Disposition header */, + HDR_WWW_AUTHENTICATE_T = 44 /*!< WWW-Authenticate header field */, + HDR_PROXY_AUTHENTICATE_T = 45 /*!< Proxy-Authenticate header field */, + HDR_DATE_T = 46 /*!< Date header field */, + HDR_IDENTITY_T = 47 /*!< Identity header field */, + HDR_IDENTITY_INFO_T = 48 /*!< Identity-info header field */, + HDR_RETRY_AFTER_T = 49 /*!< Retry-After header field */, + HDR_PPI_T = 50 /*!< P-Preferred-Identity header field*/, + HDR_PAI_T = 51 /*!< P-Asserted-Identity header field*/, + HDR_PATH_T = 52 /*!< Path header field */, + HDR_PRIVACY_T = 53 /*!< Privacy header field */, + HDR_REASON_T = 54 /**< Reason header field */, + HDR_CALLINFO_T = 55 /*!< Call-Info header field*/, - HDR_EOH_T = 56 /*!< End of message header (lastid + 1) */ + HDR_EOH_T = 56 /*!< End of message header (lastid + 1) */ }; @@ -115,74 +114,74 @@ typedef unsigned long long hdr_flags_t; /** type to flag conversion. * WARNING: HDR_ERROR_T has no corresponding FLAG ! */ -#define HDR_T2F(type) \ - (((type)!=HDR_EOH_T)?((hdr_flags_t)1<<(type)):(~(hdr_flags_t)0)) +#define HDR_T2F(type) \ + (((type) != HDR_EOH_T) ? ((hdr_flags_t)1 << (type)) : (~(hdr_flags_t)0)) /** helper macro for easy defining and keeping in sync the flags enum. */ -#define HDR_F_DEF(name) HDR_T2F(HDR_##name##_T) +#define HDR_F_DEF(name) HDR_T2F(HDR_##name##_T) /** @name flags definitions. * (enum won't work with all the compiler (e.g. icc) due to the 64bit size) */ /*!{ */ -#define HDR_EOH_F HDR_F_DEF(EOH) -#define HDR_VIA_F HDR_F_DEF(VIA) -#define HDR_VIA1_F HDR_F_DEF(VIA1) -#define HDR_VIA2_F HDR_F_DEF(VIA2) -#define HDR_TO_F HDR_F_DEF(TO) -#define HDR_FROM_F HDR_F_DEF(FROM) -#define HDR_CSEQ_F HDR_F_DEF(CSEQ) -#define HDR_CALLID_F HDR_F_DEF(CALLID) -#define HDR_CONTACT_F HDR_F_DEF(CONTACT) -#define HDR_MAXFORWARDS_F HDR_F_DEF(MAXFORWARDS) -#define HDR_ROUTE_F HDR_F_DEF(ROUTE) -#define HDR_RECORDROUTE_F HDR_F_DEF(RECORDROUTE) -#define HDR_CONTENTTYPE_F HDR_F_DEF(CONTENTTYPE) -#define HDR_CONTENTLENGTH_F HDR_F_DEF(CONTENTLENGTH) -#define HDR_AUTHORIZATION_F HDR_F_DEF(AUTHORIZATION) -#define HDR_EXPIRES_F HDR_F_DEF(EXPIRES) -#define HDR_MIN_EXPIRES_F HDR_F_DEF(MIN_EXPIRES) -#define HDR_PROXYAUTH_F HDR_F_DEF(PROXYAUTH) -#define HDR_SUPPORTED_F HDR_F_DEF(SUPPORTED) -#define HDR_REQUIRE_F HDR_F_DEF(REQUIRE) -#define HDR_PROXYREQUIRE_F HDR_F_DEF(PROXYREQUIRE) -#define HDR_UNSUPPORTED_F HDR_F_DEF(UNSUPPORTED) -#define HDR_ALLOW_F HDR_F_DEF(ALLOW) -#define HDR_EVENT_F HDR_F_DEF(EVENT) -#define HDR_ACCEPT_F HDR_F_DEF(ACCEPT) -#define HDR_ACCEPTLANGUAGE_F HDR_F_DEF(ACCEPTLANGUAGE) -#define HDR_ORGANIZATION_F HDR_F_DEF(ORGANIZATION) -#define HDR_PRIORITY_F HDR_F_DEF(PRIORITY) -#define HDR_SUBJECT_F HDR_F_DEF(SUBJECT) -#define HDR_USERAGENT_F HDR_F_DEF(USERAGENT) -#define HDR_SERVER_F HDR_F_DEF(SERVER) -#define HDR_CONTENTDISPOSITION_F HDR_F_DEF(CONTENTDISPOSITION) -#define HDR_DIVERSION_F HDR_F_DEF(DIVERSION) -#define HDR_RPID_F HDR_F_DEF(RPID) -#define HDR_REFER_TO_F HDR_F_DEF(REFER_TO) -#define HDR_SIPIFMATCH_F HDR_F_DEF(SIPIFMATCH) -#define HDR_SESSIONEXPIRES_F HDR_F_DEF(SESSIONEXPIRES) -#define HDR_MIN_SE_F HDR_F_DEF(MIN_SE) -#define HDR_SUBSCRIPTION_STATE_F HDR_F_DEF(SUBSCRIPTION_STATE) -#define HDR_ACCEPTCONTACT_F HDR_F_DEF(ACCEPTCONTACT) -#define HDR_ALLOWEVENTS_F HDR_F_DEF(ALLOWEVENTS) -#define HDR_CONTENTENCODING_F HDR_F_DEF(CONTENTENCODING) -#define HDR_REFERREDBY_F HDR_F_DEF(REFERREDBY) -#define HDR_REJECTCONTACT_F HDR_F_DEF(REJECTCONTACT) -#define HDR_REQUESTDISPOSITION_F HDR_F_DEF(REQUESTDISPOSITION) -#define HDR_WWW_AUTHENTICATE_F HDR_F_DEF(WWW_AUTHENTICATE) -#define HDR_PROXY_AUTHENTICATE_F HDR_F_DEF(PROXY_AUTHENTICATE) -#define HDR_DATE_F HDR_F_DEF(DATE) -#define HDR_IDENTITY_F HDR_F_DEF(IDENTITY) -#define HDR_IDENTITY_INFO_F HDR_F_DEF(IDENTITY_INFO) -#define HDR_RETRY_AFTER_F HDR_F_DEF(RETRY_AFTER) -#define HDR_PPI_F HDR_F_DEF(PPI) -#define HDR_PAI_F HDR_F_DEF(PAI) -#define HDR_PATH_F HDR_F_DEF(PATH) -#define HDR_PRIVACY_F HDR_F_DEF(PRIVACY) -#define HDR_REASON_F HDR_F_DEF(REASON) -#define HDR_CALLINFO_F HDR_F_DEF(CALLINFO) +#define HDR_EOH_F HDR_F_DEF(EOH) +#define HDR_VIA_F HDR_F_DEF(VIA) +#define HDR_VIA1_F HDR_F_DEF(VIA1) +#define HDR_VIA2_F HDR_F_DEF(VIA2) +#define HDR_TO_F HDR_F_DEF(TO) +#define HDR_FROM_F HDR_F_DEF(FROM) +#define HDR_CSEQ_F HDR_F_DEF(CSEQ) +#define HDR_CALLID_F HDR_F_DEF(CALLID) +#define HDR_CONTACT_F HDR_F_DEF(CONTACT) +#define HDR_MAXFORWARDS_F HDR_F_DEF(MAXFORWARDS) +#define HDR_ROUTE_F HDR_F_DEF(ROUTE) +#define HDR_RECORDROUTE_F HDR_F_DEF(RECORDROUTE) +#define HDR_CONTENTTYPE_F HDR_F_DEF(CONTENTTYPE) +#define HDR_CONTENTLENGTH_F HDR_F_DEF(CONTENTLENGTH) +#define HDR_AUTHORIZATION_F HDR_F_DEF(AUTHORIZATION) +#define HDR_EXPIRES_F HDR_F_DEF(EXPIRES) +#define HDR_MIN_EXPIRES_F HDR_F_DEF(MIN_EXPIRES) +#define HDR_PROXYAUTH_F HDR_F_DEF(PROXYAUTH) +#define HDR_SUPPORTED_F HDR_F_DEF(SUPPORTED) +#define HDR_REQUIRE_F HDR_F_DEF(REQUIRE) +#define HDR_PROXYREQUIRE_F HDR_F_DEF(PROXYREQUIRE) +#define HDR_UNSUPPORTED_F HDR_F_DEF(UNSUPPORTED) +#define HDR_ALLOW_F HDR_F_DEF(ALLOW) +#define HDR_EVENT_F HDR_F_DEF(EVENT) +#define HDR_ACCEPT_F HDR_F_DEF(ACCEPT) +#define HDR_ACCEPTLANGUAGE_F HDR_F_DEF(ACCEPTLANGUAGE) +#define HDR_ORGANIZATION_F HDR_F_DEF(ORGANIZATION) +#define HDR_PRIORITY_F HDR_F_DEF(PRIORITY) +#define HDR_SUBJECT_F HDR_F_DEF(SUBJECT) +#define HDR_USERAGENT_F HDR_F_DEF(USERAGENT) +#define HDR_SERVER_F HDR_F_DEF(SERVER) +#define HDR_CONTENTDISPOSITION_F HDR_F_DEF(CONTENTDISPOSITION) +#define HDR_DIVERSION_F HDR_F_DEF(DIVERSION) +#define HDR_RPID_F HDR_F_DEF(RPID) +#define HDR_REFER_TO_F HDR_F_DEF(REFER_TO) +#define HDR_SIPIFMATCH_F HDR_F_DEF(SIPIFMATCH) +#define HDR_SESSIONEXPIRES_F HDR_F_DEF(SESSIONEXPIRES) +#define HDR_MIN_SE_F HDR_F_DEF(MIN_SE) +#define HDR_SUBSCRIPTION_STATE_F HDR_F_DEF(SUBSCRIPTION_STATE) +#define HDR_ACCEPTCONTACT_F HDR_F_DEF(ACCEPTCONTACT) +#define HDR_ALLOWEVENTS_F HDR_F_DEF(ALLOWEVENTS) +#define HDR_CONTENTENCODING_F HDR_F_DEF(CONTENTENCODING) +#define HDR_REFERREDBY_F HDR_F_DEF(REFERREDBY) +#define HDR_REJECTCONTACT_F HDR_F_DEF(REJECTCONTACT) +#define HDR_REQUESTDISPOSITION_F HDR_F_DEF(REQUESTDISPOSITION) +#define HDR_WWW_AUTHENTICATE_F HDR_F_DEF(WWW_AUTHENTICATE) +#define HDR_PROXY_AUTHENTICATE_F HDR_F_DEF(PROXY_AUTHENTICATE) +#define HDR_DATE_F HDR_F_DEF(DATE) +#define HDR_IDENTITY_F HDR_F_DEF(IDENTITY) +#define HDR_IDENTITY_INFO_F HDR_F_DEF(IDENTITY_INFO) +#define HDR_RETRY_AFTER_F HDR_F_DEF(RETRY_AFTER) +#define HDR_PPI_F HDR_F_DEF(PPI) +#define HDR_PAI_F HDR_F_DEF(PAI) +#define HDR_PATH_F HDR_F_DEF(PATH) +#define HDR_PRIVACY_F HDR_F_DEF(PRIVACY) +#define HDR_REASON_F HDR_F_DEF(REASON) +#define HDR_CALLINFO_F HDR_F_DEF(CALLINFO) -#define HDR_OTHER_F HDR_F_DEF(OTHER) +#define HDR_OTHER_F HDR_F_DEF(OTHER) /*!} */ /* Doxygen end marker*/ @@ -190,13 +189,14 @@ typedef enum _hdr_types_t hdr_types_t; /** Format: name':' body. */ -typedef struct hdr_field { - hdr_types_t type; /*!< Header field type */ - str name; /*!< Header field name */ - str body; /*!< Header field body (may not include CRLF) */ - int len; /*!< length from hdr start until EoHF (incl.CRLF) */ - void* parsed; /*!< Parsed data structures */ - struct hdr_field* next; /*!< Next header field in the list */ +typedef struct hdr_field +{ + hdr_types_t type; /*!< Header field type */ + str name; /*!< Header field name */ + str body; /*!< Header field body (may not include CRLF) */ + int len; /*!< length from hdr start until EoHF (incl.CRLF) */ + void *parsed; /*!< Parsed data structures */ + struct hdr_field *next; /*!< Next header field in the list */ } hdr_field_t; @@ -204,14 +204,15 @@ typedef struct hdr_field { typedef void (*hf_parsed_free_f)(void *parsed); /* structure to hold the function to free the parsed header field */ -typedef struct hdr_parsed { +typedef struct hdr_parsed +{ hf_parsed_free_f hfree; } hf_parsed_t; /** returns true if the header links allocated memory on parse field. */ -static inline int hdr_allocs_parse(struct hdr_field* hdr) +static inline int hdr_allocs_parse(struct hdr_field *hdr) { - switch(hdr->type){ + switch(hdr->type) { case HDR_ACCEPT_T: case HDR_ALLOW_T: case HDR_AUTHORIZATION_T: @@ -249,16 +250,16 @@ static inline int hdr_allocs_parse(struct hdr_field* hdr) /** frees a hdr_field structure. * WARNING: it frees only parsed (and not name.s, body.s) */ -void clean_hdr_field(struct hdr_field* const hf); +void clean_hdr_field(struct hdr_field *const hf); /** frees a hdr_field list. * WARNING: frees only ->parsed and ->next */ -void free_hdr_field_lst(struct hdr_field* hf); +void free_hdr_field_lst(struct hdr_field *hf); /* print content of hdr_field */ -void dump_hdr_field( struct hdr_field const* const hf); +void dump_hdr_field(struct hdr_field const *const hf); /** * free hdr parsed structure using inner free function diff --git a/src/core/parser/keys.h b/src/core/parser/keys.h index 322edc67c81..572e57f9bd9 100644 --- a/src/core/parser/keys.h +++ b/src/core/parser/keys.h @@ -49,148 +49,148 @@ /*!{ */ -#define _acce_ 0x65636361 /* "acce" */ -#define _allo_ 0x6f6c6c61 /* "allo" */ -#define _auth_ 0x68747561 /* "auth" */ -#define _oriz_ 0x7a69726f /* "oriz" */ -#define _atio_ 0x6f697461 /* "atio" */ -#define _call_ 0x6c6c6163 /* "call" */ -#define __id2_ 0x2064692d /* "-id " */ -#define __id1_ 0x3a64692d /* "-id:" */ -#define _cont_ 0x746e6f63 /* "cont" */ -#define _act2_ 0x20746361 /* "act " */ -#define _act1_ 0x3a746361 /* "act:" */ -#define _ent__ 0x2d746e65 /* "ent-" */ -#define _leng_ 0x676e656c /* "leng" */ -#define _th12_ 0x203a6874 /* "th: " */ -#define _type_ 0x65707974 /* "type" */ -#define _cseq_ 0x71657363 /* "cseq" */ -#define _expi_ 0x69707865 /* "expi" */ -#define _res2_ 0x20736572 /* "res " */ -#define _res1_ 0x3a736572 /* "res:" */ -#define _from_ 0x6d6f7266 /* "from" */ -#define _max__ 0x2d78616d /* "max-" */ -#define _forw_ 0x77726f66 /* "forw" */ -#define _ards_ 0x73647261 /* "ards" */ -#define _prox_ 0x786f7270 /* "prox" */ -#define _y_au_ 0x75612d79 /* "y-au" */ -#define _thor_ 0x726f6874 /* "thor" */ -#define _izat_ 0x74617a69 /* "izat" */ -#define _ion2_ 0x206e6f69 /* "ion " */ -#define _ion1_ 0x3a6e6f69 /* "ion:" */ -#define _then_ 0x6e656874 /* "then" */ -#define _tica_ 0x61636974 /* "tica" */ -#define _te1_ 0x003a6574 /* "te:" */ -#define _te2_ 0x00206574 /* "te " */ -#define _y_re_ 0x65722d79 /* "y-re" */ -#define _quir_ 0x72697571 /* "quir" */ -#define _reco_ 0x6f636572 /* "reco" */ -#define _rd_r_ 0x722d6472 /* "rd-r" */ -#define _oute_ 0x6574756f /* "oute" */ -#define _requ_ 0x75716572 /* "requ" */ -#define _ire2_ 0x20657269 /* "ire " */ -#define _ire1_ 0x3a657269 /* "ire:" */ -#define _rout_ 0x74756f72 /* "rout" */ -#define _supp_ 0x70707573 /* "supp" */ -#define _orte_ 0x6574726f /* "orte" */ -#define _to12_ 0x203a6f74 /* "to: " */ -#define _unsu_ 0x75736e75 /* "unsu" */ -#define _ppor_ 0x726f7070 /* "ppor" */ -#define _ted2_ 0x20646574 /* "ted " */ -#define _ted1_ 0x3a646574 /* "ted:" */ -#define _via2_ 0x20616976 /* "via " */ -#define _via1_ 0x3a616976 /* "via:" */ -#define _www__ 0x2d777777 /* "www-" */ -#define _enti_ 0x69746e65 /* "enti" */ -#define _cate_ 0x65746163 /* "cate" */ -#define _even_ 0x6e657665 /* "even" */ -#define _sip_ 0x2d706973 /* "sip-" */ -#define _ifm_ 0x6d2d6669 /* "if-m" */ -#define _atch_ 0x68637461 /* "atch" */ -#define _date_ 0x65746164 /* "date" */ -#define _iden_ 0x6e656469 /* "iden" */ -#define _tity_ 0x79746974 /* "tity" */ -#define _info_ 0x6f666e69 /* "info" */ -#define _path_ 0x68746170 /* "path" */ -#define _100r_ 0x72303031 /* "100r" */ -#define _time_ 0x656d6974 /* "time" */ - -#define _pt_l_ 0x6c2d7470 /* "pt-l" */ -#define _angu_ 0x75676e61 /* "angu" */ -#define _age2_ 0x20656761 /* "age " */ -#define _age1_ 0x3a656761 /* "age:" */ -#define _orga_ 0x6167726f /* "orga" */ -#define _niza_ 0x617a696e /* "niza" */ -#define _tion_ 0x6e6f6974 /* "tion" */ -#define _prio_ 0x6f697270 /* "prio" */ -#define _rity_ 0x79746972 /* "rity" */ -#define _subj_ 0x6a627573 /* "subj" */ -#define _subs_ 0x73627573 /* "subs" */ -#define _crip_ 0x70697263 /* "crip" */ -#define __sta_ 0x6174732d /* "-sta" */ -#define _ect2_ 0x20746365 /* "ect " */ -#define _ect1_ 0x3a746365 /* "ect:" */ -#define _user_ 0x72657375 /* "user" */ -#define __age_ 0x6567612d /* "-age" */ -#define _disp_ 0x70736964 /* "disp" */ -#define _osit_ 0x7469736f /* "osit" */ -#define _ion2_ 0x206e6f69 /* "ion " */ -#define _ion1_ 0x3a6e6f69 /* "ion:" */ - -#define _pt_d_ 0x642d7470 /* "pt-d" */ -#define _ispo_ 0x6f707369 /* "ispo" */ -#define _siti_ 0x69746973 /* "siti" */ - -#define _serv_ 0x76726573 /* "serv" */ - -#define _dive_ 0x65766964 /* "dive" */ -#define _rsio_ 0x6f697372 /* "rsio" */ - -#define _remo_ 0x6f6d6572 /* "remo" */ -#define _te_p_ 0x702d6574 /* "te-p" */ -#define _arty_ 0x79747261 /* "arty" */ -#define __id2_ 0x2064692d /* "-id " */ -#define __id1_ 0x3a64692d /* "-id:" */ - -#define _refe_ 0x65666572 /* "refe" */ -#define _r_to_ 0x6f742d72 /* "r-to" */ - -#define _pt_c_ 0x632d7470 /* "pt-c" */ -#define _onta_ 0x61746e6f /* "onta" */ - -#define _sess_ 0x73736573 /* "sess" */ -#define _ion__ 0x2d6e6f69 /* "ion-" */ -#define _res2_ 0x20736572 /* "res " */ -#define _res1_ 0x3a736572 /* "res:" */ - -#define _w_ev_ 0x76652d77 /* "w-ev" */ -#define _ents_ 0x73746e65 /* "ents" */ - -#define _enco_ 0x6f636e65 /* "enco" */ -#define _ding_ 0x676e6964 /* "ding" */ - -#define _rred_ 0x64657272 /* "rred" */ -#define __by2_ 0x2079622d /* "-by " */ -#define __by1_ 0x3a79622d /* "-by:" */ - -#define _reje_ 0x656a6572 /* "reje" */ -#define _ct_c_ 0x632d7463 /* "ct-c" */ - -#define _est__ 0x2d747365 /* "est-" */ - -#define _min__ 0x2d6e696d /* "min-" */ - - -#define _retr_ 0x72746572 /* "retr" */ -#define _y_af_ 0x66612d79 /* "y-af" */ -#define _ter1_ 0x3a726574 /* "ter:" */ -#define _ter2_ 0x20726574 /* "ter " */ - -#define _priv_ 0x76697270 /* "priv" */ -#define _acy2_ 0x20796361 /* "acy " */ -#define _acy1_ 0x3a796361 /* "acy:" */ - -#define _reas_ 0x73616572 /* "reas" */ +#define _acce_ 0x65636361 /* "acce" */ +#define _allo_ 0x6f6c6c61 /* "allo" */ +#define _auth_ 0x68747561 /* "auth" */ +#define _oriz_ 0x7a69726f /* "oriz" */ +#define _atio_ 0x6f697461 /* "atio" */ +#define _call_ 0x6c6c6163 /* "call" */ +#define __id2_ 0x2064692d /* "-id " */ +#define __id1_ 0x3a64692d /* "-id:" */ +#define _cont_ 0x746e6f63 /* "cont" */ +#define _act2_ 0x20746361 /* "act " */ +#define _act1_ 0x3a746361 /* "act:" */ +#define _ent__ 0x2d746e65 /* "ent-" */ +#define _leng_ 0x676e656c /* "leng" */ +#define _th12_ 0x203a6874 /* "th: " */ +#define _type_ 0x65707974 /* "type" */ +#define _cseq_ 0x71657363 /* "cseq" */ +#define _expi_ 0x69707865 /* "expi" */ +#define _res2_ 0x20736572 /* "res " */ +#define _res1_ 0x3a736572 /* "res:" */ +#define _from_ 0x6d6f7266 /* "from" */ +#define _max__ 0x2d78616d /* "max-" */ +#define _forw_ 0x77726f66 /* "forw" */ +#define _ards_ 0x73647261 /* "ards" */ +#define _prox_ 0x786f7270 /* "prox" */ +#define _y_au_ 0x75612d79 /* "y-au" */ +#define _thor_ 0x726f6874 /* "thor" */ +#define _izat_ 0x74617a69 /* "izat" */ +#define _ion2_ 0x206e6f69 /* "ion " */ +#define _ion1_ 0x3a6e6f69 /* "ion:" */ +#define _then_ 0x6e656874 /* "then" */ +#define _tica_ 0x61636974 /* "tica" */ +#define _te1_ 0x003a6574 /* "te:" */ +#define _te2_ 0x00206574 /* "te " */ +#define _y_re_ 0x65722d79 /* "y-re" */ +#define _quir_ 0x72697571 /* "quir" */ +#define _reco_ 0x6f636572 /* "reco" */ +#define _rd_r_ 0x722d6472 /* "rd-r" */ +#define _oute_ 0x6574756f /* "oute" */ +#define _requ_ 0x75716572 /* "requ" */ +#define _ire2_ 0x20657269 /* "ire " */ +#define _ire1_ 0x3a657269 /* "ire:" */ +#define _rout_ 0x74756f72 /* "rout" */ +#define _supp_ 0x70707573 /* "supp" */ +#define _orte_ 0x6574726f /* "orte" */ +#define _to12_ 0x203a6f74 /* "to: " */ +#define _unsu_ 0x75736e75 /* "unsu" */ +#define _ppor_ 0x726f7070 /* "ppor" */ +#define _ted2_ 0x20646574 /* "ted " */ +#define _ted1_ 0x3a646574 /* "ted:" */ +#define _via2_ 0x20616976 /* "via " */ +#define _via1_ 0x3a616976 /* "via:" */ +#define _www__ 0x2d777777 /* "www-" */ +#define _enti_ 0x69746e65 /* "enti" */ +#define _cate_ 0x65746163 /* "cate" */ +#define _even_ 0x6e657665 /* "even" */ +#define _sip_ 0x2d706973 /* "sip-" */ +#define _ifm_ 0x6d2d6669 /* "if-m" */ +#define _atch_ 0x68637461 /* "atch" */ +#define _date_ 0x65746164 /* "date" */ +#define _iden_ 0x6e656469 /* "iden" */ +#define _tity_ 0x79746974 /* "tity" */ +#define _info_ 0x6f666e69 /* "info" */ +#define _path_ 0x68746170 /* "path" */ +#define _100r_ 0x72303031 /* "100r" */ +#define _time_ 0x656d6974 /* "time" */ + +#define _pt_l_ 0x6c2d7470 /* "pt-l" */ +#define _angu_ 0x75676e61 /* "angu" */ +#define _age2_ 0x20656761 /* "age " */ +#define _age1_ 0x3a656761 /* "age:" */ +#define _orga_ 0x6167726f /* "orga" */ +#define _niza_ 0x617a696e /* "niza" */ +#define _tion_ 0x6e6f6974 /* "tion" */ +#define _prio_ 0x6f697270 /* "prio" */ +#define _rity_ 0x79746972 /* "rity" */ +#define _subj_ 0x6a627573 /* "subj" */ +#define _subs_ 0x73627573 /* "subs" */ +#define _crip_ 0x70697263 /* "crip" */ +#define __sta_ 0x6174732d /* "-sta" */ +#define _ect2_ 0x20746365 /* "ect " */ +#define _ect1_ 0x3a746365 /* "ect:" */ +#define _user_ 0x72657375 /* "user" */ +#define __age_ 0x6567612d /* "-age" */ +#define _disp_ 0x70736964 /* "disp" */ +#define _osit_ 0x7469736f /* "osit" */ +#define _ion2_ 0x206e6f69 /* "ion " */ +#define _ion1_ 0x3a6e6f69 /* "ion:" */ + +#define _pt_d_ 0x642d7470 /* "pt-d" */ +#define _ispo_ 0x6f707369 /* "ispo" */ +#define _siti_ 0x69746973 /* "siti" */ + +#define _serv_ 0x76726573 /* "serv" */ + +#define _dive_ 0x65766964 /* "dive" */ +#define _rsio_ 0x6f697372 /* "rsio" */ + +#define _remo_ 0x6f6d6572 /* "remo" */ +#define _te_p_ 0x702d6574 /* "te-p" */ +#define _arty_ 0x79747261 /* "arty" */ +#define __id2_ 0x2064692d /* "-id " */ +#define __id1_ 0x3a64692d /* "-id:" */ + +#define _refe_ 0x65666572 /* "refe" */ +#define _r_to_ 0x6f742d72 /* "r-to" */ + +#define _pt_c_ 0x632d7470 /* "pt-c" */ +#define _onta_ 0x61746e6f /* "onta" */ + +#define _sess_ 0x73736573 /* "sess" */ +#define _ion__ 0x2d6e6f69 /* "ion-" */ +#define _res2_ 0x20736572 /* "res " */ +#define _res1_ 0x3a736572 /* "res:" */ + +#define _w_ev_ 0x76652d77 /* "w-ev" */ +#define _ents_ 0x73746e65 /* "ents" */ + +#define _enco_ 0x6f636e65 /* "enco" */ +#define _ding_ 0x676e6964 /* "ding" */ + +#define _rred_ 0x64657272 /* "rred" */ +#define __by2_ 0x2079622d /* "-by " */ +#define __by1_ 0x3a79622d /* "-by:" */ + +#define _reje_ 0x656a6572 /* "reje" */ +#define _ct_c_ 0x632d7463 /* "ct-c" */ + +#define _est__ 0x2d747365 /* "est-" */ + +#define _min__ 0x2d6e696d /* "min-" */ + + +#define _retr_ 0x72746572 /* "retr" */ +#define _y_af_ 0x66612d79 /* "y-af" */ +#define _ter1_ 0x3a726574 /* "ter:" */ +#define _ter2_ 0x20726574 /* "ter " */ + +#define _priv_ 0x76697270 /* "priv" */ +#define _acy2_ 0x20796361 /* "acy " */ +#define _acy1_ 0x3a796361 /* "acy:" */ + +#define _reas_ 0x73616572 /* "reas" */ #define _on1_ 0x203a6e6f /* "on: " */ #define _on2_ 0x3a206e6f /* "on :" */ #define _on3_ 0x20206e6f /* "on " */ diff --git a/src/core/parser/msg_parser.c b/src/core/parser/msg_parser.c index d28dbd8538e..fdc4a844350 100644 --- a/src/core/parser/msg_parser.c +++ b/src/core/parser/msg_parser.c @@ -58,7 +58,7 @@ #endif -#define parse_hname(_b,_e,_h) parse_hname2((_b),(_e),(_h)) +#define parse_hname(_b, _e, _h) parse_hname2((_b), (_e), (_h)) /* number of via's encountered */ int via_cnt; @@ -69,14 +69,15 @@ int ksr_sip_parser_mode = KSR_SIP_PARSER_MODE_STRICT; /* returns pointer to next header line, and fill hdr_f ; * if at end of header returns pointer to the last crlf (always buf)*/ -char* get_hdr_field(char* const buf, char* const end, struct hdr_field* const hdr) +char *get_hdr_field( + char *const buf, char *const end, struct hdr_field *const hdr) { char *tmp = 0; char *match; struct via_body *vb; - struct cseq_body* cseq_b; - struct to_body* to_b; + struct cseq_body *cseq_b; + struct to_body *to_b; int integer, err; unsigned uval; @@ -85,22 +86,22 @@ char* get_hdr_field(char* const buf, char* const end, struct hdr_field* const hd goto error; } - if ((*buf)=='\n' || (*buf)=='\r'){ + if((*buf) == '\n' || (*buf) == '\r') { /* double crlf or lflf or crcr */ DBG("found end of header\n"); - hdr->type=HDR_EOH_T; + hdr->type = HDR_EOH_T; return buf; } - tmp=parse_hname(buf, end, hdr); - if (hdr->type==HDR_ERROR_T){ + tmp = parse_hname(buf, end, hdr); + if(hdr->type == HDR_ERROR_T) { ERR("bad header\n"); goto error; } /* eliminate leading whitespace */ - tmp=eat_lws_end(tmp, end); - if (tmp>=end) { + tmp = eat_lws_end(tmp, end); + if(tmp >= end) { ERR("HF empty\n"); goto error; } @@ -109,65 +110,65 @@ char* get_hdr_field(char* const buf, char* const end, struct hdr_field* const hd * after leaving the hdr->type switch, tmp should be set to the * next header field */ - switch(hdr->type){ + switch(hdr->type) { case HDR_VIA_T: /* keep number of vias parsed -- we want to report it in replies for diagnostic purposes */ via_cnt++; - vb=pkg_malloc(sizeof(struct via_body)); - if (vb==0){ + vb = pkg_malloc(sizeof(struct via_body)); + if(vb == 0) { PKG_MEM_ERROR; goto error; } - memset(vb,0,sizeof(struct via_body)); - hdr->body.s=tmp; - tmp=parse_via(tmp, end, vb); - if (vb->error==PARSE_ERROR){ + memset(vb, 0, sizeof(struct via_body)); + hdr->body.s = tmp; + tmp = parse_via(tmp, end, vb); + if(vb->error == PARSE_ERROR) { ERR("bad via\n"); free_via_list(vb); goto error; } - hdr->parsed=vb; - vb->hdr.s=hdr->name.s; - vb->hdr.len=hdr->name.len; - hdr->body.len=tmp-hdr->body.s; + hdr->parsed = vb; + vb->hdr.s = hdr->name.s; + vb->hdr.len = hdr->name.len; + hdr->body.len = tmp - hdr->body.s; break; case HDR_CSEQ_T: - cseq_b=pkg_malloc(sizeof(struct cseq_body)); - if (cseq_b==0){ + cseq_b = pkg_malloc(sizeof(struct cseq_body)); + if(cseq_b == 0) { PKG_MEM_ERROR; goto error; } memset(cseq_b, 0, sizeof(struct cseq_body)); - hdr->body.s=tmp; - tmp=parse_cseq(tmp, end, cseq_b); - if (cseq_b->error==PARSE_ERROR){ + hdr->body.s = tmp; + tmp = parse_cseq(tmp, end, cseq_b); + if(cseq_b->error == PARSE_ERROR) { ERR("bad cseq\n"); free_cseq(cseq_b); goto error; } - hdr->parsed=cseq_b; - hdr->body.len=tmp-hdr->body.s; + hdr->parsed = cseq_b; + hdr->body.len = tmp - hdr->body.s; DBG("cseq <%.*s>: <%.*s> <%.*s>\n", hdr->name.len, ZSW(hdr->name.s), - cseq_b->number.len, ZSW(cseq_b->number.s), cseq_b->method.len, - cseq_b->method.s); + cseq_b->number.len, ZSW(cseq_b->number.s), + cseq_b->method.len, cseq_b->method.s); break; case HDR_TO_T: - to_b=pkg_malloc(sizeof(struct to_body)); - if (to_b==0){ + to_b = pkg_malloc(sizeof(struct to_body)); + if(to_b == 0) { PKG_MEM_ERROR; goto error; } memset(to_b, 0, sizeof(struct to_body)); - hdr->body.s=tmp; - tmp=parse_to(tmp, end,to_b); - if (to_b->error==PARSE_ERROR){ + hdr->body.s = tmp; + tmp = parse_to(tmp, end, to_b); + if(to_b->error == PARSE_ERROR) { ERR("bad to header\n"); free_to(to_b); goto error; } - hdr->parsed=to_b; - hdr->body.len=tmp-hdr->body.s; + hdr->parsed = to_b; + hdr->body.len = tmp - hdr->body.s; DBG("<%.*s> [%d]; uri=[%.*s]\n", hdr->name.len, ZSW(hdr->name.s), hdr->body.len, to_b->uri.len, ZSW(to_b->uri.s)); DBG("to body (%d)[%.*s], to tag (%d)[%.*s]\n", to_b->body.len, @@ -175,25 +176,25 @@ char* get_hdr_field(char* const buf, char* const end, struct hdr_field* const hd to_b->tag_value.len, ZSW(to_b->tag_value.s)); break; case HDR_CONTENTLENGTH_T: - hdr->body.s=tmp; - tmp=parse_content_length(tmp,end, &integer); - if (tmp==0){ + hdr->body.s = tmp; + tmp = parse_content_length(tmp, end, &integer); + if(tmp == 0) { ERR("bad content_length header\n"); goto error; } - hdr->parsed=(void*)(long)integer; - hdr->body.len=tmp-hdr->body.s; + hdr->parsed = (void *)(long)integer; + hdr->body.len = tmp - hdr->body.s; DBG("content_length=%d\n", (int)(long)hdr->parsed); break; case HDR_RETRY_AFTER_T: - hdr->body.s=tmp; - tmp=parse_retry_after(tmp,end, &uval, &err); - if (err){ + hdr->body.s = tmp; + tmp = parse_retry_after(tmp, end, &uval, &err); + if(err) { ERR("bad retry_after header\n"); goto error; } - hdr->parsed=(void*)(unsigned long)uval; - hdr->body.len=tmp-hdr->body.s; + hdr->parsed = (void *)(unsigned long)uval; + hdr->body.len = tmp - hdr->body.s; DBG("retry_after=%d\n", (unsigned)(long)hdr->parsed); break; case HDR_IDENTITY_T: @@ -247,45 +248,44 @@ char* get_hdr_field(char* const buf, char* const end, struct hdr_field* const hd case HDR_CALLINFO_T: case HDR_OTHER_T: /* just skip over it */ - hdr->body.s=tmp; + hdr->body.s = tmp; /* find end of header */ /* find lf */ - do{ - match=q_memchr(tmp, '\n', end-tmp); - if (match){ + do { + match = q_memchr(tmp, '\n', end - tmp); + if(match) { match++; } else { ERR("no eol - bad body for <%.*s> (hdr type: %d) [%.*s]\n", - hdr->name.len, hdr->name.s, - hdr->type, ((end-tmp)>128)?128:(int)(end-tmp), tmp); + hdr->name.len, hdr->name.s, hdr->type, + ((end - tmp) > 128) ? 128 : (int)(end - tmp), tmp); /* abort(); */ - tmp=end; + tmp = end; goto error; } - tmp=match; - }while( matchbody.len=match-hdr->body.s; + tmp = match; + } while(match < end && ((*match == ' ') || (*match == '\t'))); + tmp = match; + hdr->body.len = match - hdr->body.s; break; default: BUG("unknown header type %d [%.*s]\n", hdr->type, - ((end-buf)>128)?128:(int)(end-buf), buf); + ((end - buf) > 128) ? 128 : (int)(end - buf), buf); goto error; } /* jku: if \r covered by current length, shrink it */ - trim_r( hdr->body ); - hdr->len=tmp-hdr->name.s; + trim_r(hdr->body); + hdr->len = tmp - hdr->name.s; return tmp; error: DBG("error exit\n"); STATS_BAD_MSG_HDR(); - hdr->type=HDR_ERROR_T; - hdr->len=tmp-hdr->name.s; + hdr->type = HDR_ERROR_T; + hdr->len = tmp - hdr->name.s; return tmp; } - /* parse the headers and adds them to msg->headers and msg->to, from etc. * It stops when all the headers requested in flags were parsed, on error * (bad header) or end of headers @@ -301,46 +301,47 @@ char* get_hdr_field(char* const buf, char* const end, struct hdr_field* const hd give you the first occurrence of a header you are interested in, look at check_transaction_quadruple */ -int parse_headers(struct sip_msg* const msg, const hdr_flags_t flags, const int next) +int parse_headers( + struct sip_msg *const msg, const hdr_flags_t flags, const int next) { - struct hdr_field* hf; - char* tmp; - char* rest; - char* end; + struct hdr_field *hf; + char *tmp; + char *rest; + char *end; hdr_flags_t orig_flag; - end=msg->buf+msg->len; - tmp=msg->unparsed; + end = msg->buf + msg->len; + tmp = msg->unparsed; - if (unlikely(next)) { + if(unlikely(next)) { orig_flag = msg->parsed_flag; msg->parsed_flag &= ~flags; } else { - orig_flag=0; + orig_flag = 0; } #ifdef EXTRA_DEBUG DBG("flags=%llx\n", (unsigned long long)flags); #endif - while(tmpparsed_flag) != flags) { - prefetch_loc_r(tmp+64, 1); - hf=pkg_malloc(sizeof(struct hdr_field)); - if (unlikely(hf==0)){ + while(tmp < end && (flags & msg->parsed_flag) != flags) { + prefetch_loc_r(tmp + 64, 1); + hf = pkg_malloc(sizeof(struct hdr_field)); + if(unlikely(hf == 0)) { PKG_MEM_ERROR; - ser_error=E_OUT_OF_MEM; + ser_error = E_OUT_OF_MEM; goto error; } - memset(hf,0, sizeof(struct hdr_field)); - hf->type=HDR_ERROR_T; - rest=get_hdr_field(tmp, end, hf); - switch (hf->type){ + memset(hf, 0, sizeof(struct hdr_field)); + hf->type = HDR_ERROR_T; + rest = get_hdr_field(tmp, end, hf); + switch(hf->type) { case HDR_ERROR_T: ERR("bad header field [%.*s]\n", - (end-tmp>100)?100:(int)(end-tmp), tmp); - goto error; + (end - tmp > 100) ? 100 : (int)(end - tmp), tmp); + goto error; case HDR_EOH_T: - msg->eoh=tmp; /* or rest?*/ - msg->parsed_flag|=HDR_EOH_F; + msg->eoh = tmp; /* or rest?*/ + msg->parsed_flag |= HDR_EOH_F; pkg_free(hf); goto skip; case HDR_ACCEPTCONTACT_T: @@ -353,277 +354,320 @@ int parse_headers(struct sip_msg* const msg, const hdr_flags_t flags, const int case HDR_PROXY_AUTHENTICATE_T: case HDR_RETRY_AFTER_T: case HDR_OTHER_T: /* mark the type as found/parsed*/ - msg->parsed_flag|=HDR_T2F(hf->type); + msg->parsed_flag |= HDR_T2F(hf->type); break; case HDR_CALLID_T: - if (msg->callid==0) { - msg->callid=hf; + if(msg->callid == 0) { + msg->callid = hf; } else if(ksr_sip_parser_mode & KSR_SIP_PARSER_MODE_STRICT) { if(IS_SIP(msg)) { LOG(cfg_get(core, core_cfg, sip_parser_log), "duplicate Call-ID header field [%.*s]\n", - (end-tmp>100)?100:(int)(end-tmp), tmp); - goto error; + (end - tmp > 100) ? 100 : (int)(end - tmp), + tmp); + goto error; } } - msg->parsed_flag|=HDR_CALLID_F; + msg->parsed_flag |= HDR_CALLID_F; break; case HDR_SIPIFMATCH_T: - if (msg->sipifmatch==0) msg->sipifmatch=hf; - msg->parsed_flag|=HDR_SIPIFMATCH_F; + if(msg->sipifmatch == 0) + msg->sipifmatch = hf; + msg->parsed_flag |= HDR_SIPIFMATCH_F; break; case HDR_TO_T: - if (msg->to==0) { - msg->to=hf; + if(msg->to == 0) { + msg->to = hf; } else if(ksr_sip_parser_mode & KSR_SIP_PARSER_MODE_STRICT) { if(IS_SIP(msg)) { LOG(cfg_get(core, core_cfg, sip_parser_log), "duplicate To header field [%.*s]\n", - (end-tmp>100)?100:(int)(end-tmp), tmp); - goto error; + (end - tmp > 100) ? 100 : (int)(end - tmp), + tmp); + goto error; } } - msg->parsed_flag|=HDR_TO_F; + msg->parsed_flag |= HDR_TO_F; break; case HDR_CSEQ_T: - if (msg->cseq==0) { - msg->cseq=hf; + if(msg->cseq == 0) { + msg->cseq = hf; } else if(ksr_sip_parser_mode & KSR_SIP_PARSER_MODE_STRICT) { if(IS_SIP(msg)) { LOG(cfg_get(core, core_cfg, sip_parser_log), "duplicate CSeq header field [%.*s]\n", - (end-tmp>100)?100:(int)(end-tmp), tmp); - goto error; + (end - tmp > 100) ? 100 : (int)(end - tmp), + tmp); + goto error; } } - msg->parsed_flag|=HDR_CSEQ_F; + msg->parsed_flag |= HDR_CSEQ_F; break; case HDR_FROM_T: - if (msg->from==0) { - msg->from=hf; + if(msg->from == 0) { + msg->from = hf; } else if(ksr_sip_parser_mode & KSR_SIP_PARSER_MODE_STRICT) { if(IS_SIP(msg)) { LOG(cfg_get(core, core_cfg, sip_parser_log), "duplicate From header field [%.*s]\n", - (end-tmp>100)?100:(int)(end-tmp), tmp); - goto error; + (end - tmp > 100) ? 100 : (int)(end - tmp), + tmp); + goto error; } } - msg->parsed_flag|=HDR_FROM_F; + msg->parsed_flag |= HDR_FROM_F; break; case HDR_CONTACT_T: - if (msg->contact==0) msg->contact=hf; - msg->parsed_flag|=HDR_CONTACT_F; + if(msg->contact == 0) + msg->contact = hf; + msg->parsed_flag |= HDR_CONTACT_F; break; case HDR_MAXFORWARDS_T: - if(msg->maxforwards==0) { - msg->maxforwards=hf; + if(msg->maxforwards == 0) { + msg->maxforwards = hf; } else { if(IS_SIP(msg)) { LOG(cfg_get(core, core_cfg, sip_parser_log), "duplicate Max-Forwards header field [%.*s]\n", - (end-tmp>100)?100:(int)(end-tmp), tmp); - goto error; + (end - tmp > 100) ? 100 : (int)(end - tmp), + tmp); + goto error; } } - msg->parsed_flag|=HDR_MAXFORWARDS_F; + msg->parsed_flag |= HDR_MAXFORWARDS_F; break; case HDR_ROUTE_T: - if (msg->route==0) msg->route=hf; - msg->parsed_flag|=HDR_ROUTE_F; + if(msg->route == 0) + msg->route = hf; + msg->parsed_flag |= HDR_ROUTE_F; break; case HDR_RECORDROUTE_T: - if (msg->record_route==0) msg->record_route = hf; - msg->parsed_flag|=HDR_RECORDROUTE_F; + if(msg->record_route == 0) + msg->record_route = hf; + msg->parsed_flag |= HDR_RECORDROUTE_F; break; case HDR_CONTENTTYPE_T: - if (msg->content_type==0) msg->content_type = hf; - msg->parsed_flag|=HDR_CONTENTTYPE_F; + if(msg->content_type == 0) + msg->content_type = hf; + msg->parsed_flag |= HDR_CONTENTTYPE_F; break; case HDR_CONTENTLENGTH_T: - if (msg->content_length==0) { + if(msg->content_length == 0) { msg->content_length = hf; } else if(ksr_sip_parser_mode & KSR_SIP_PARSER_MODE_STRICT) { if(IS_SIP(msg)) { LOG(cfg_get(core, core_cfg, sip_parser_log), - "duplicate Content-Length header field [%.*s]\n", - (end-tmp>100)?100:(int)(end-tmp), tmp); - goto error; + "duplicate Content-Length header field " + "[%.*s]\n", + (end - tmp > 100) ? 100 : (int)(end - tmp), + tmp); + goto error; } } - msg->parsed_flag|=HDR_CONTENTLENGTH_F; + msg->parsed_flag |= HDR_CONTENTLENGTH_F; break; case HDR_AUTHORIZATION_T: - if (msg->authorization==0) msg->authorization = hf; - msg->parsed_flag|=HDR_AUTHORIZATION_F; + if(msg->authorization == 0) + msg->authorization = hf; + msg->parsed_flag |= HDR_AUTHORIZATION_F; break; case HDR_EXPIRES_T: - if (msg->expires==0) msg->expires = hf; - msg->parsed_flag|=HDR_EXPIRES_F; + if(msg->expires == 0) + msg->expires = hf; + msg->parsed_flag |= HDR_EXPIRES_F; break; case HDR_MIN_EXPIRES_T: - if (msg->min_expires==0) msg->min_expires = hf; - msg->parsed_flag|=HDR_MIN_EXPIRES_F; + if(msg->min_expires == 0) + msg->min_expires = hf; + msg->parsed_flag |= HDR_MIN_EXPIRES_F; break; case HDR_PROXYAUTH_T: - if (msg->proxy_auth==0) msg->proxy_auth = hf; - msg->parsed_flag|=HDR_PROXYAUTH_F; + if(msg->proxy_auth == 0) + msg->proxy_auth = hf; + msg->parsed_flag |= HDR_PROXYAUTH_F; break; case HDR_PROXYREQUIRE_T: - if (msg->proxy_require==0) msg->proxy_require = hf; - msg->parsed_flag|=HDR_PROXYREQUIRE_F; + if(msg->proxy_require == 0) + msg->proxy_require = hf; + msg->parsed_flag |= HDR_PROXYREQUIRE_F; break; case HDR_SUPPORTED_T: - if (msg->supported==0) msg->supported=hf; - msg->parsed_flag|=HDR_SUPPORTED_F; + if(msg->supported == 0) + msg->supported = hf; + msg->parsed_flag |= HDR_SUPPORTED_F; break; case HDR_REQUIRE_T: - if (msg->require==0) msg->require=hf; - msg->parsed_flag|=HDR_REQUIRE_F; + if(msg->require == 0) + msg->require = hf; + msg->parsed_flag |= HDR_REQUIRE_F; break; case HDR_UNSUPPORTED_T: - if (msg->unsupported==0) msg->unsupported=hf; - msg->parsed_flag|=HDR_UNSUPPORTED_F; + if(msg->unsupported == 0) + msg->unsupported = hf; + msg->parsed_flag |= HDR_UNSUPPORTED_F; break; case HDR_ALLOW_T: - if (msg->allow==0) msg->allow = hf; - msg->parsed_flag|=HDR_ALLOW_F; + if(msg->allow == 0) + msg->allow = hf; + msg->parsed_flag |= HDR_ALLOW_F; break; case HDR_EVENT_T: - if (msg->event==0) msg->event = hf; - msg->parsed_flag|=HDR_EVENT_F; + if(msg->event == 0) + msg->event = hf; + msg->parsed_flag |= HDR_EVENT_F; break; case HDR_ACCEPT_T: - if (msg->accept==0) msg->accept = hf; - msg->parsed_flag|=HDR_ACCEPT_F; + if(msg->accept == 0) + msg->accept = hf; + msg->parsed_flag |= HDR_ACCEPT_F; break; case HDR_ACCEPTLANGUAGE_T: - if (msg->accept_language==0) msg->accept_language = hf; - msg->parsed_flag|=HDR_ACCEPTLANGUAGE_F; + if(msg->accept_language == 0) + msg->accept_language = hf; + msg->parsed_flag |= HDR_ACCEPTLANGUAGE_F; break; case HDR_ORGANIZATION_T: - if (msg->organization==0) msg->organization = hf; - msg->parsed_flag|=HDR_ORGANIZATION_F; + if(msg->organization == 0) + msg->organization = hf; + msg->parsed_flag |= HDR_ORGANIZATION_F; break; case HDR_PRIORITY_T: - if (msg->priority==0) msg->priority = hf; - msg->parsed_flag|=HDR_PRIORITY_F; + if(msg->priority == 0) + msg->priority = hf; + msg->parsed_flag |= HDR_PRIORITY_F; break; case HDR_SUBJECT_T: - if (msg->subject==0) msg->subject = hf; - msg->parsed_flag|=HDR_SUBJECT_F; + if(msg->subject == 0) + msg->subject = hf; + msg->parsed_flag |= HDR_SUBJECT_F; break; case HDR_USERAGENT_T: - if (msg->user_agent==0) msg->user_agent = hf; - msg->parsed_flag|=HDR_USERAGENT_F; + if(msg->user_agent == 0) + msg->user_agent = hf; + msg->parsed_flag |= HDR_USERAGENT_F; break; case HDR_SERVER_T: - if (msg->server==0) msg->server = hf; - msg->parsed_flag|=HDR_SERVER_F; + if(msg->server == 0) + msg->server = hf; + msg->parsed_flag |= HDR_SERVER_F; break; case HDR_CONTENTDISPOSITION_T: - if (msg->content_disposition==0) msg->content_disposition = hf; - msg->parsed_flag|=HDR_CONTENTDISPOSITION_F; + if(msg->content_disposition == 0) + msg->content_disposition = hf; + msg->parsed_flag |= HDR_CONTENTDISPOSITION_F; break; case HDR_DIVERSION_T: - if (msg->diversion==0) msg->diversion = hf; - msg->parsed_flag|=HDR_DIVERSION_F; + if(msg->diversion == 0) + msg->diversion = hf; + msg->parsed_flag |= HDR_DIVERSION_F; break; case HDR_RPID_T: - if (msg->rpid==0) msg->rpid = hf; - msg->parsed_flag|=HDR_RPID_F; + if(msg->rpid == 0) + msg->rpid = hf; + msg->parsed_flag |= HDR_RPID_F; break; case HDR_REFER_TO_T: - if (msg->refer_to==0) msg->refer_to = hf; - msg->parsed_flag|=HDR_REFER_TO_F; + if(msg->refer_to == 0) + msg->refer_to = hf; + msg->parsed_flag |= HDR_REFER_TO_F; break; case HDR_SESSIONEXPIRES_T: - if (msg->session_expires==0) msg->session_expires = hf; - msg->parsed_flag|=HDR_SESSIONEXPIRES_F; + if(msg->session_expires == 0) + msg->session_expires = hf; + msg->parsed_flag |= HDR_SESSIONEXPIRES_F; break; case HDR_MIN_SE_T: - if (msg->min_se==0) msg->min_se = hf; - msg->parsed_flag|=HDR_MIN_SE_F; + if(msg->min_se == 0) + msg->min_se = hf; + msg->parsed_flag |= HDR_MIN_SE_F; break; case HDR_SUBSCRIPTION_STATE_T: - if (msg->subscription_state==0) msg->subscription_state = hf; - msg->parsed_flag|=HDR_SUBSCRIPTION_STATE_F; + if(msg->subscription_state == 0) + msg->subscription_state = hf; + msg->parsed_flag |= HDR_SUBSCRIPTION_STATE_F; break; case HDR_VIA_T: - msg->parsed_flag|=HDR_VIA_F; + msg->parsed_flag |= HDR_VIA_F; DBG("Via found, flags=%llx\n", (unsigned long long)flags); - if (msg->via1==0) { + if(msg->via1 == 0) { DBG("this is the first via\n"); - msg->h_via1=hf; - msg->via1=hf->parsed; - if (msg->via1->next){ - msg->via2=msg->via1->next; - msg->parsed_flag|=HDR_VIA2_F; + msg->h_via1 = hf; + msg->via1 = hf->parsed; + if(msg->via1->next) { + msg->via2 = msg->via1->next; + msg->parsed_flag |= HDR_VIA2_F; } - }else if (msg->via2==0){ - msg->h_via2=hf; - msg->via2=hf->parsed; - msg->parsed_flag|=HDR_VIA2_F; + } else if(msg->via2 == 0) { + msg->h_via2 = hf; + msg->via2 = hf->parsed; + msg->parsed_flag |= HDR_VIA2_F; DBG("this is the second via\n"); } break; case HDR_DATE_T: - if (msg->date==0) msg->date=hf; - msg->parsed_flag|=HDR_DATE_F; + if(msg->date == 0) + msg->date = hf; + msg->parsed_flag |= HDR_DATE_F; break; case HDR_IDENTITY_T: - if (msg->identity==0) msg->identity=hf; - msg->parsed_flag|=HDR_IDENTITY_F; + if(msg->identity == 0) + msg->identity = hf; + msg->parsed_flag |= HDR_IDENTITY_F; break; case HDR_IDENTITY_INFO_T: - if (msg->identity_info==0) msg->identity_info=hf; - msg->parsed_flag|=HDR_IDENTITY_INFO_F; + if(msg->identity_info == 0) + msg->identity_info = hf; + msg->parsed_flag |= HDR_IDENTITY_INFO_F; break; - case HDR_PATH_T: - if (msg->path==0) msg->path=hf; - msg->parsed_flag|=HDR_PATH_F; + case HDR_PATH_T: + if(msg->path == 0) + msg->path = hf; + msg->parsed_flag |= HDR_PATH_F; break; - case HDR_PRIVACY_T: - if (msg->privacy==0) msg->privacy=hf; - msg->parsed_flag|=HDR_PRIVACY_F; + case HDR_PRIVACY_T: + if(msg->privacy == 0) + msg->privacy = hf; + msg->parsed_flag |= HDR_PRIVACY_F; break; - case HDR_PAI_T: - if (msg->pai==0) msg->pai=hf; - msg->parsed_flag|=HDR_PAI_F; + case HDR_PAI_T: + if(msg->pai == 0) + msg->pai = hf; + msg->parsed_flag |= HDR_PAI_F; break; - case HDR_PPI_T: - if (msg->ppi==0) msg->ppi=hf; - msg->parsed_flag|=HDR_PPI_F; + case HDR_PPI_T: + if(msg->ppi == 0) + msg->ppi = hf; + msg->parsed_flag |= HDR_PPI_F; break; - case HDR_REASON_T: - msg->parsed_flag|=HDR_REASON_F; + case HDR_REASON_T: + msg->parsed_flag |= HDR_REASON_F; break; case HDR_CALLINFO_T: - msg->parsed_flag|=HDR_CALLINFO_F; + msg->parsed_flag |= HDR_CALLINFO_F; break; default: BUG("unknown header type %d\n", hf->type); goto error; } /* add the header to the list*/ - if (msg->last_header==0){ - msg->headers=hf; - msg->last_header=hf; - }else{ - msg->last_header->next=hf; - msg->last_header=hf; + if(msg->last_header == 0) { + msg->headers = hf; + msg->last_header = hf; + } else { + msg->last_header->next = hf; + msg->last_header = hf; } #ifdef EXTRA_DEBUG DBG("header field type %d, name=<%.*s>, body=<%.*s>\n", hf->type, hf->name.len, ZSW(hf->name.s), hf->body.len, ZSW(hf->body.s)); #endif - tmp=rest; + tmp = rest; } skip: - msg->unparsed=tmp; + msg->unparsed = tmp; if(ksr_sip_parser_mode & KSR_SIP_PARSER_MODE_STRICT) { - if(msg->headers==NULL) { + if(msg->headers == NULL) { /* nothing parsed - invalid input sip message */ goto error1; } @@ -633,43 +677,42 @@ int parse_headers(struct sip_msg* const msg, const hdr_flags_t flags, const int return 0; error: - if (hf) { + if(hf) { clean_hdr_field(hf); pkg_free(hf); } error1: - ser_error=E_BAD_REQ; + ser_error = E_BAD_REQ; /* restore original flags */ msg->parsed_flag |= orig_flag; return -1; } - - - /* returns 0 if ok, -1 for errors */ -int parse_msg(char* const buf, const unsigned int len, struct sip_msg* const msg) +int parse_msg( + char *const buf, const unsigned int len, struct sip_msg *const msg) { char *tmp; - char* rest; + char *rest; struct msg_start *fl; int offset; hdr_flags_t flags; /* eat crlf & whitespaces from the beginning */ - for (tmp=buf; (tmp-buf < len) - && (*tmp=='\n' || *tmp=='\r' || *tmp=='\0' - || *tmp=='\t' || *tmp==' '); - tmp++); - offset=tmp-buf; - fl=&(msg->first_line); - rest=parse_first_line(tmp, len-offset, fl); - offset+=rest-tmp; - tmp=rest; - switch(fl->type){ + for(tmp = buf; (tmp - buf < len) + && (*tmp == '\n' || *tmp == '\r' || *tmp == '\0' + || *tmp == '\t' || *tmp == ' '); + tmp++) + ; + offset = tmp - buf; + fl = &(msg->first_line); + rest = parse_first_line(tmp, len - offset, fl); + offset += rest - tmp; + tmp = rest; + switch(fl->type) { case SIP_INVALID: DBG("invalid message\n"); goto error; @@ -682,7 +725,7 @@ int parse_msg(char* const buf, const unsigned int len, struct sip_msg* const msg ZSW(fl->u.request.uri.s)); DBG(" version: <%.*s>\n", fl->u.request.version.len, ZSW(fl->u.request.version.s)); - flags=HDR_VIA_F; + flags = HDR_VIA_F; break; case SIP_REPLY: DBG("SIP Reply (status):\n"); @@ -694,45 +737,44 @@ int parse_msg(char* const buf, const unsigned int len, struct sip_msg* const msg ZSW(fl->u.reply.reason.s)); /* flags=HDR_VIA | HDR_VIA2; */ /* we don't try to parse VIA2 for local messages; -Jiri */ - flags=HDR_VIA_F; + flags = HDR_VIA_F; break; default: DBG("unknown type %d\n", fl->type); goto error; } - msg->unparsed=tmp; + msg->unparsed = tmp; /*find first Via: */ - if (parse_headers(msg, flags, 0)==-1) goto error; + if(parse_headers(msg, flags, 0) == -1) + goto error; #ifdef EXTRA_DEBUG /* dump parsed data */ - if (msg->via1){ - DBG("first via: <%.*s/%.*s/%.*s> <%.*s:%.*s(%d)>", - msg->via1->name.len, ZSW(msg->via1->name.s), - msg->via1->version.len, ZSW(msg->via1->version.s), - msg->via1->transport.len, ZSW(msg->via1->transport.s), - msg->via1->host.len, ZSW(msg->via1->host.s), - msg->via1->port_str.len, ZSW(msg->via1->port_str.s), - msg->via1->port); - if (msg->via1->params.s) + if(msg->via1) { + DBG("first via: <%.*s/%.*s/%.*s> <%.*s:%.*s(%d)>", msg->via1->name.len, + ZSW(msg->via1->name.s), msg->via1->version.len, + ZSW(msg->via1->version.s), msg->via1->transport.len, + ZSW(msg->via1->transport.s), msg->via1->host.len, + ZSW(msg->via1->host.s), msg->via1->port_str.len, + ZSW(msg->via1->port_str.s), msg->via1->port); + if(msg->via1->params.s) DBG(";<%.*s>", msg->via1->params.len, ZSW(msg->via1->params.s)); - if (msg->via1->comment.s) + if(msg->via1->comment.s) DBG(" <%.*s>", msg->via1->comment.len, ZSW(msg->via1->comment.s)); - DBG ("\n"); + DBG("\n"); } - if (msg->via2){ - DBG("second via: <%.*s/%.*s/%.*s> <%.*s:%.*s(%d)>", - msg->via2->name.len, ZSW(msg->via2->name.s), - msg->via2->version.len, ZSW(msg->via2->version.s), - msg->via2->transport.len, ZSW(msg->via2->transport.s), - msg->via2->host.len, ZSW(msg->via2->host.s), - msg->via2->port_str.len, ZSW(msg->via2->port_str.s), - msg->via2->port); - if (msg->via2->params.s) + if(msg->via2) { + DBG("second via: <%.*s/%.*s/%.*s> <%.*s:%.*s(%d)>", msg->via2->name.len, + ZSW(msg->via2->name.s), msg->via2->version.len, + ZSW(msg->via2->version.s), msg->via2->transport.len, + ZSW(msg->via2->transport.s), msg->via2->host.len, + ZSW(msg->via2->host.s), msg->via2->port_str.len, + ZSW(msg->via2->port_str.s), msg->via2->port); + if(msg->via2->params.s) DBG(";<%.*s>", msg->via2->params.len, ZSW(msg->via2->params.s)); - if (msg->via2->comment.s) + if(msg->via2->comment.s) DBG(" <%.*s>", msg->via2->comment.len, ZSW(msg->via2->comment.s)); - DBG ("\n"); + DBG("\n"); } #endif @@ -745,19 +787,18 @@ int parse_msg(char* const buf, const unsigned int len, struct sip_msg* const msg error: /* more debugging, msg->orig is/should be null terminated*/ - LOG(cfg_get(core, core_cfg, sip_parser_log), "ERROR: parse_msg: message=<%.*s>\n", - (int)msg->len, ZSW(ksr_buf_oneline(msg->buf, (int)msg->len))); + LOG(cfg_get(core, core_cfg, sip_parser_log), + "ERROR: parse_msg: message=<%.*s>\n", (int)msg->len, + ZSW(ksr_buf_oneline(msg->buf, (int)msg->len))); return -1; } - -void free_reply_lump( struct lump_rpl *lump) +void free_reply_lump(struct lump_rpl *lump) { struct lump_rpl *foo, *bar; - for(foo=lump;foo;) - { - bar=foo->next; + for(foo = lump; foo;) { + bar = foo->next; free_lump_rpl(foo); foo = bar; } @@ -765,7 +806,7 @@ void free_reply_lump( struct lump_rpl *lump) /*only the content*/ -void free_sip_msg(struct sip_msg* const msg) +void free_sip_msg(struct sip_msg *const msg) { reset_new_uri(msg); reset_dst_uri(msg); @@ -773,11 +814,16 @@ void free_sip_msg(struct sip_msg* const msg) reset_instance(msg); reset_ruid(msg); reset_ua(msg); - if (msg->headers) free_hdr_field_lst(msg->headers); - if (msg->body && msg->body->free) msg->body->free(&msg->body); - if (msg->add_rm) free_lump_list(msg->add_rm); - if (msg->body_lumps) free_lump_list(msg->body_lumps); - if (msg->reply_lump) free_reply_lump(msg->reply_lump); + if(msg->headers) + free_hdr_field_lst(msg->headers); + if(msg->body && msg->body->free) + msg->body->free(&msg->body); + if(msg->add_rm) + free_lump_list(msg->add_rm); + if(msg->body_lumps) + free_lump_list(msg->body_lumps); + if(msg->reply_lump) + free_reply_lump(msg->reply_lump); msg_ldata_reset(msg); /* no free of msg->buf -- a pointer to a static buffer */ } @@ -785,7 +831,7 @@ void free_sip_msg(struct sip_msg* const msg) /** * reset new uri value */ -void reset_new_uri(struct sip_msg* const msg) +void reset_new_uri(struct sip_msg *const msg) { if(msg->new_uri.s != 0) { pkg_free(msg->new_uri.s); @@ -799,29 +845,30 @@ void reset_new_uri(struct sip_msg* const msg) /* * Make a private copy of the string and assign it to dst_uri */ -int set_dst_uri(struct sip_msg* const msg, const str* const uri) +int set_dst_uri(struct sip_msg *const msg, const str *const uri) { - char* ptr; + char *ptr; - if (unlikely(!msg || !uri)) { + if(unlikely(!msg || !uri)) { ERR("Invalid parameter value\n"); return -1; } - if (unlikely(uri->len == 0)) { + if(unlikely(uri->len == 0)) { reset_dst_uri(msg); - }else if (msg->dst_uri.s && (msg->dst_uri.len >= uri->len)) { + } else if(msg->dst_uri.s && (msg->dst_uri.len >= uri->len)) { memcpy(msg->dst_uri.s, uri->s, uri->len); msg->dst_uri.len = uri->len; } else { - ptr = (char*)pkg_malloc(uri->len + 1); - if (!ptr) { + ptr = (char *)pkg_malloc(uri->len + 1); + if(!ptr) { PKG_MEM_ERROR; return -1; } memcpy(ptr, uri->s, uri->len); - if (msg->dst_uri.s) pkg_free(msg->dst_uri.s); + if(msg->dst_uri.s) + pkg_free(msg->dst_uri.s); msg->dst_uri.s = ptr; msg->dst_uri.len = uri->len; msg->dst_uri.s[msg->dst_uri.len] = '\0'; @@ -830,7 +877,7 @@ int set_dst_uri(struct sip_msg* const msg, const str* const uri) } -void reset_dst_uri(struct sip_msg* const msg) +void reset_dst_uri(struct sip_msg *const msg) { if(msg->dst_uri.s != 0) { pkg_free(msg->dst_uri.s); @@ -839,29 +886,30 @@ void reset_dst_uri(struct sip_msg* const msg) msg->dst_uri.len = 0; } -int set_path_vector(struct sip_msg* msg, str* path) +int set_path_vector(struct sip_msg *msg, str *path) { - char* ptr; + char *ptr; - if (unlikely(!msg || !path)) { + if(unlikely(!msg || !path)) { ERR("invalid parameter value\n"); return -1; } - if (unlikely(path->len == 0)) { + if(unlikely(path->len == 0)) { reset_path_vector(msg); - } else if (msg->path_vec.s && (msg->path_vec.len >= path->len)) { + } else if(msg->path_vec.s && (msg->path_vec.len >= path->len)) { memcpy(msg->path_vec.s, path->s, path->len); msg->path_vec.len = path->len; } else { - ptr = (char*)pkg_malloc(path->len); - if (!ptr) { + ptr = (char *)pkg_malloc(path->len); + if(!ptr) { PKG_MEM_ERROR; return -1; } memcpy(ptr, path->s, path->len); - if (msg->path_vec.s) pkg_free(msg->path_vec.s); + if(msg->path_vec.s) + pkg_free(msg->path_vec.s); msg->path_vec.s = ptr; msg->path_vec.len = path->len; } @@ -869,10 +917,10 @@ int set_path_vector(struct sip_msg* msg, str* path) } -void reset_path_vector(struct sip_msg* const msg) +void reset_path_vector(struct sip_msg *const msg) { - if (!shm_address_in(msg->path_vec.s)) { - if (msg->path_vec.s) + if(!shm_address_in(msg->path_vec.s)) { + if(msg->path_vec.s) pkg_free(msg->path_vec.s); msg->path_vec.s = 0; msg->path_vec.len = 0; @@ -882,28 +930,29 @@ void reset_path_vector(struct sip_msg* const msg) } -int set_instance(struct sip_msg* msg, str* instance) +int set_instance(struct sip_msg *msg, str *instance) { - char* ptr; + char *ptr; - if (unlikely(!msg || !instance)) { + if(unlikely(!msg || !instance)) { ERR("invalid instance parameter value\n"); return -1; } - if (unlikely(instance->len == 0)) { + if(unlikely(instance->len == 0)) { reset_instance(msg); - } else if (msg->instance.s && (msg->instance.len >= instance->len)) { + } else if(msg->instance.s && (msg->instance.len >= instance->len)) { memcpy(msg->instance.s, instance->s, instance->len); msg->instance.len = instance->len; } else { - ptr = (char*)pkg_malloc(instance->len); - if (!ptr) { + ptr = (char *)pkg_malloc(instance->len); + if(!ptr) { PKG_MEM_ERROR; return -1; } memcpy(ptr, instance->s, instance->len); - if (msg->instance.s) pkg_free(msg->instance.s); + if(msg->instance.s) + pkg_free(msg->instance.s); msg->instance.s = ptr; msg->instance.len = instance->len; } @@ -911,7 +960,7 @@ int set_instance(struct sip_msg* msg, str* instance) } -void reset_instance(struct sip_msg* const msg) +void reset_instance(struct sip_msg *const msg) { if(msg->instance.s != 0) { pkg_free(msg->instance.s); @@ -921,28 +970,29 @@ void reset_instance(struct sip_msg* const msg) } -int set_ruid(struct sip_msg* msg, str* ruid) +int set_ruid(struct sip_msg *msg, str *ruid) { - char* ptr; + char *ptr; - if (unlikely(!msg || !ruid)) { + if(unlikely(!msg || !ruid)) { ERR("invalid ruid parameter value\n"); return -1; } - if (unlikely(ruid->len == 0)) { + if(unlikely(ruid->len == 0)) { reset_ruid(msg); - } else if (msg->ruid.s && (msg->ruid.len >= ruid->len)) { + } else if(msg->ruid.s && (msg->ruid.len >= ruid->len)) { memcpy(msg->ruid.s, ruid->s, ruid->len); msg->ruid.len = ruid->len; } else { - ptr = (char*)pkg_malloc(ruid->len); - if (!ptr) { + ptr = (char *)pkg_malloc(ruid->len); + if(!ptr) { PKG_MEM_ERROR; return -1; } memcpy(ptr, ruid->s, ruid->len); - if (msg->ruid.s) pkg_free(msg->ruid.s); + if(msg->ruid.s) + pkg_free(msg->ruid.s); msg->ruid.s = ptr; msg->ruid.len = ruid->len; } @@ -950,7 +1000,7 @@ int set_ruid(struct sip_msg* msg, str* ruid) } -void reset_ruid(struct sip_msg* const msg) +void reset_ruid(struct sip_msg *const msg) { if(msg->ruid.s != 0) { pkg_free(msg->ruid.s); @@ -960,28 +1010,30 @@ void reset_ruid(struct sip_msg* const msg) } -int set_ua(struct sip_msg* msg, str* location_ua) +int set_ua(struct sip_msg *msg, str *location_ua) { - char* ptr; + char *ptr; - if (unlikely(!msg || !location_ua)) { + if(unlikely(!msg || !location_ua)) { ERR("invalid location_ua parameter value\n"); return -1; } - if (unlikely(location_ua->len == 0)) { + if(unlikely(location_ua->len == 0)) { reset_ua(msg); - } else if (msg->location_ua.s && (msg->location_ua.len >= location_ua->len)) { + } else if(msg->location_ua.s + && (msg->location_ua.len >= location_ua->len)) { memcpy(msg->location_ua.s, location_ua->s, location_ua->len); msg->location_ua.len = location_ua->len; } else { - ptr = (char*)pkg_malloc(location_ua->len); - if (!ptr) { + ptr = (char *)pkg_malloc(location_ua->len); + if(!ptr) { PKG_MEM_ERROR; return -1; } memcpy(ptr, location_ua->s, location_ua->len); - if (msg->location_ua.s) pkg_free(msg->location_ua.s); + if(msg->location_ua.s) + pkg_free(msg->location_ua.s); msg->location_ua.s = ptr; msg->location_ua.len = location_ua->len; } @@ -989,7 +1041,7 @@ int set_ua(struct sip_msg* msg, str* location_ua) } -void reset_ua(struct sip_msg* const msg) +void reset_ua(struct sip_msg *const msg) { if(msg->location_ua.s != 0) { pkg_free(msg->location_ua.s); @@ -1003,58 +1055,61 @@ void reset_ua(struct sip_msg* const msg) */ void msg_ldata_reset(sip_msg_t *msg) { - if(msg==NULL) + if(msg == NULL) return; memset(&msg->ldv, 0, sizeof(msg_ldata_t)); } -hdr_field_t* get_hdr(const sip_msg_t* const msg, const enum _hdr_types_t ht) +hdr_field_t *get_hdr(const sip_msg_t *const msg, const enum _hdr_types_t ht) { hdr_field_t *hdr; - if (ht == HDR_ERROR_T || ht == HDR_EOH_T) { + if(ht == HDR_ERROR_T || ht == HDR_EOH_T) { return NULL; } - if (msg->parsed_flag & HDR_T2F(ht)) { + if(msg->parsed_flag & HDR_T2F(ht)) { for(hdr = msg->headers; hdr; hdr = hdr->next) { - if(hdr->type == ht) return hdr; + if(hdr->type == ht) + return hdr; } } return NULL; } -hdr_field_t* next_sibling_hdr(const hdr_field_t* const hf) +hdr_field_t *next_sibling_hdr(const hdr_field_t *const hf) { hdr_field_t *hdr; for(hdr = hf->next; hdr; hdr = hdr->next) { - if(hdr->type == hf->type) return hdr; + if(hdr->type == hf->type) + return hdr; } return NULL; } -hdr_field_t* get_hdr_by_name(const sip_msg_t* const msg, const char* const name, const int name_len) +hdr_field_t *get_hdr_by_name( + const sip_msg_t *const msg, const char *const name, const int name_len) { hdr_field_t *hdr; for(hdr = msg->headers; hdr; hdr = hdr->next) { - if(hdr->name.len == name_len && *hdr->name.s==*name - && strncasecmp(hdr->name.s, name, name_len)==0) + if(hdr->name.len == name_len && *hdr->name.s == *name + && strncasecmp(hdr->name.s, name, name_len) == 0) return hdr; } return NULL; } /** not used yet */ -hdr_field_t* next_sibling_hdr_by_name(const hdr_field_t* const hf) +hdr_field_t *next_sibling_hdr_by_name(const hdr_field_t *const hf) { hdr_field_t *hdr; for(hdr = hf->next; hdr; hdr = hdr->next) { - if(hdr->name.len == hf->name.len && *hdr->name.s==*hf->name.s - && strncasecmp(hdr->name.s, hf->name.s, hf->name.len)==0) + if(hdr->name.len == hf->name.len && *hdr->name.s == *hf->name.s + && strncasecmp(hdr->name.s, hf->name.s, hf->name.len) == 0) return hdr; } return NULL; @@ -1064,9 +1119,9 @@ hdr_field_t* next_sibling_hdr_by_name(const hdr_field_t* const hf) * set msg context id * - return: -1 on error; 0 - on set */ -int msg_ctx_id_set(const sip_msg_t* const msg, msg_ctx_id_t* const mid) +int msg_ctx_id_set(const sip_msg_t *const msg, msg_ctx_id_t *const mid) { - if(msg==NULL || mid==NULL) + if(msg == NULL || mid == NULL) return -1; mid->msgid = msg->id; mid->pid = msg->pid; @@ -1077,11 +1132,11 @@ int msg_ctx_id_set(const sip_msg_t* const msg, msg_ctx_id_t* const mid) * check msg context id * - return: -1 on error; 0 - on no match; 1 - on match */ -int msg_ctx_id_match(const sip_msg_t* const msg, const msg_ctx_id_t* const mid) +int msg_ctx_id_match(const sip_msg_t *const msg, const msg_ctx_id_t *const mid) { - if(msg==NULL || mid==NULL) + if(msg == NULL || mid == NULL) return -1; - if(msg->id != mid->msgid || msg->pid!=mid->pid) + if(msg->id != mid->msgid || msg->pid != mid->pid) return 0; return 1; } @@ -1089,11 +1144,11 @@ int msg_ctx_id_match(const sip_msg_t* const msg, const msg_ctx_id_t* const mid) /** * set msg time value */ -int msg_set_time(sip_msg_t* const msg) +int msg_set_time(sip_msg_t *const msg) { - if(unlikely(msg==NULL)) + if(unlikely(msg == NULL)) return -2; - if(msg->tval.tv_sec!=0) + if(msg->tval.tv_sec != 0) return 0; return gettimeofday(&msg->tval, NULL); } @@ -1107,11 +1162,11 @@ char *ksr_buf_oneline(char *inbuf, int inlen) int outlen; int i = 0; - if (cfg_get(core, core_cfg, sip_parser_log_oneline) == 0) { + if(cfg_get(core, core_cfg, sip_parser_log_oneline) == 0) { return inbuf; } - if (inbuf == NULL) { + if(inbuf == NULL) { outbuf[0] = '\0'; return outbuf; } @@ -1120,13 +1175,10 @@ char *ksr_buf_oneline(char *inbuf, int inlen) memcpy(outbuf, inbuf, outlen); outbuf[outlen] = '\0'; - for (i = 0; i < outlen; i++) { - if (outbuf[i] == '\r') - { + for(i = 0; i < outlen; i++) { + if(outbuf[i] == '\r') { outbuf[i] = '.'; - } - else if (outbuf[i] == '\n') - { + } else if(outbuf[i] == '\n') { outbuf[i] = ' '; } } @@ -1141,31 +1193,32 @@ char *ksr_buf_oneline(char *inbuf, int inlen) int get_src_uri(sip_msg_t *m, int tmode, str *uri) { static char buf[MAX_URI_SIZE]; - char* p; + char *p; str ip, port; int len; str proto; - if (!uri || !m) { + if(!uri || !m) { ERR("invalid parameter value\n"); return -1; } - if(tmode==0) { + if(tmode == 0) { switch(m->rcv.proto) { case PROTO_NONE: case PROTO_UDP: - proto.s = 0; /* Do not add transport parameter, UDP is default */ + proto.s = + 0; /* Do not add transport parameter, UDP is default */ proto.len = 0; - break; + break; default: - if(get_valid_proto_string(m->rcv.proto, 1, 0, &proto)<0) { + if(get_valid_proto_string(m->rcv.proto, 1, 0, &proto) < 0) { ERR("unknown transport protocol\n"); return -1; } } } else { - if(get_valid_proto_string(m->rcv.proto, 1, 0, &proto)<0) { + if(get_valid_proto_string(m->rcv.proto, 1, 0, &proto) < 0) { ERR("unknown transport protocol\n"); return -1; } @@ -1176,13 +1229,13 @@ int get_src_uri(sip_msg_t *m, int tmode, str *uri) port.s = int2str(m->rcv.src_port, &port.len); - len = 4 + ip.len + 2*(m->rcv.src_ip.af==AF_INET6)+ 1 + port.len; - if (proto.s) { + len = 4 + ip.len + 2 * (m->rcv.src_ip.af == AF_INET6) + 1 + port.len; + if(proto.s) { len += TRANSPORT_PARAM_LEN; len += proto.len; } - if (len > MAX_URI_SIZE) { + if(len > MAX_URI_SIZE) { ERR("buffer too small\n"); return -1; } @@ -1191,11 +1244,11 @@ int get_src_uri(sip_msg_t *m, int tmode, str *uri) memcpy(p, "sip:", 4); p += 4; - if (m->rcv.src_ip.af==AF_INET6) + if(m->rcv.src_ip.af == AF_INET6) *p++ = '['; memcpy(p, ip.s, ip.len); p += ip.len; - if (m->rcv.src_ip.af==AF_INET6) + if(m->rcv.src_ip.af == AF_INET6) *p++ = ']'; *p++ = ':'; @@ -1203,7 +1256,7 @@ int get_src_uri(sip_msg_t *m, int tmode, str *uri) memcpy(p, port.s, port.len); p += port.len; - if (proto.s) { + if(proto.s) { memcpy(p, TRANSPORT_PARAM, TRANSPORT_PARAM_LEN); p += TRANSPORT_PARAM_LEN; @@ -1223,17 +1276,17 @@ int get_src_uri(sip_msg_t *m, int tmode, str *uri) int get_src_address_socket(sip_msg_t *m, str *ssock) { static char buf[MAX_URI_SIZE]; - char* p; + char *p; str ip, port; int len; str proto; - if (!ssock || !m) { + if(!ssock || !m) { ERR("invalid parameter value\n"); return -1; } - if(get_valid_proto_string(m->rcv.proto, 1, 0, &proto)<0) { + if(get_valid_proto_string(m->rcv.proto, 1, 0, &proto) < 0) { ERR("unknown transport protocol\n"); return -1; } @@ -1243,9 +1296,10 @@ int get_src_address_socket(sip_msg_t *m, str *ssock) port.s = int2str(m->rcv.src_port, &port.len); - len = proto.len + 1 + ip.len + 2*(m->rcv.src_ip.af==AF_INET6)+ 1 + port.len; + len = proto.len + 1 + ip.len + 2 * (m->rcv.src_ip.af == AF_INET6) + 1 + + port.len; - if (len+1 >= MAX_URI_SIZE) { + if(len + 1 >= MAX_URI_SIZE) { ERR("buffer too small\n"); return -1; } @@ -1257,11 +1311,11 @@ int get_src_address_socket(sip_msg_t *m, str *ssock) *p++ = ':'; - if (m->rcv.src_ip.af==AF_INET6) + if(m->rcv.src_ip.af == AF_INET6) *p++ = '['; memcpy(p, ip.s, ip.len); p += ip.len; - if (m->rcv.src_ip.af==AF_INET6) + if(m->rcv.src_ip.af == AF_INET6) *p++ = ']'; *p++ = ':'; @@ -1284,37 +1338,38 @@ int get_src_address_socket(sip_msg_t *m, str *ssock) int get_rcv_socket_uri(sip_msg_t *m, int tmode, str *uri, int atype) { static char buf[MAX_URI_SIZE]; - char* p; + char *p; str ip, port; int len; str proto; - if (!uri || !m || !m->rcv.bind_address) { + if(!uri || !m || !m->rcv.bind_address) { ERR("invalid parameter value\n"); return -1; } - if(tmode==0) { + if(tmode == 0) { switch(m->rcv.proto) { case PROTO_NONE: case PROTO_UDP: - proto.s = 0; /* Do not add transport parameter, UDP is default */ + proto.s = + 0; /* Do not add transport parameter, UDP is default */ proto.len = 0; - break; + break; default: - if(get_valid_proto_string(m->rcv.proto, 1, 0, &proto)<0) { + if(get_valid_proto_string(m->rcv.proto, 1, 0, &proto) < 0) { ERR("unknown transport protocol\n"); return -1; } } } else { - if(get_valid_proto_string(m->rcv.proto, 1, 0, &proto)<0) { + if(get_valid_proto_string(m->rcv.proto, 1, 0, &proto) < 0) { ERR("unknown transport protocol\n"); return -1; } } - if(atype==0 || m->rcv.bind_address->useinfo.address_str.len<=0) { + if(atype == 0 || m->rcv.bind_address->useinfo.address_str.len <= 0) { ip.s = m->rcv.bind_address->address_str.s; ip.len = m->rcv.bind_address->address_str.len; } else { @@ -1322,7 +1377,7 @@ int get_rcv_socket_uri(sip_msg_t *m, int tmode, str *uri, int atype) ip.len = m->rcv.bind_address->useinfo.address_str.len; } - if(atype==0|| m->rcv.bind_address->useinfo.port_no_str.len <= 0) { + if(atype == 0 || m->rcv.bind_address->useinfo.port_no_str.len <= 0) { port.s = m->rcv.bind_address->port_no_str.s; port.len = m->rcv.bind_address->port_no_str.len; } else { @@ -1330,13 +1385,13 @@ int get_rcv_socket_uri(sip_msg_t *m, int tmode, str *uri, int atype) port.len = m->rcv.bind_address->useinfo.port_no_str.len; } - len = 4 + ip.len + 2*(m->rcv.src_ip.af==AF_INET6)+ 1 + port.len; - if (proto.s) { + len = 4 + ip.len + 2 * (m->rcv.src_ip.af == AF_INET6) + 1 + port.len; + if(proto.s) { len += TRANSPORT_PARAM_LEN; len += proto.len; } - if (len > MAX_URI_SIZE) { + if(len > MAX_URI_SIZE) { ERR("buffer too small\n"); return -1; } @@ -1345,11 +1400,11 @@ int get_rcv_socket_uri(sip_msg_t *m, int tmode, str *uri, int atype) memcpy(p, "sip:", 4); p += 4; - if (m->rcv.src_ip.af==AF_INET6) + if(m->rcv.src_ip.af == AF_INET6) *p++ = '['; memcpy(p, ip.s, ip.len); p += ip.len; - if (m->rcv.src_ip.af==AF_INET6) + if(m->rcv.src_ip.af == AF_INET6) *p++ = ']'; *p++ = ':'; @@ -1357,7 +1412,7 @@ int get_rcv_socket_uri(sip_msg_t *m, int tmode, str *uri, int atype) memcpy(p, port.s, port.len); p += port.len; - if (proto.s) { + if(proto.s) { memcpy(p, TRANSPORT_PARAM, TRANSPORT_PARAM_LEN); p += TRANSPORT_PARAM_LEN; @@ -1374,33 +1429,33 @@ int get_rcv_socket_uri(sip_msg_t *m, int tmode, str *uri, int atype) /*! \brief returns a pointer to the beginning of the msg's body */ -char* get_body(sip_msg_t* const msg) +char *get_body(sip_msg_t *const msg) { int offset; unsigned int len; - if ( parse_headers(msg, HDR_EOH_F, 0)==-1 ) { + if(parse_headers(msg, HDR_EOH_F, 0) == -1) { LM_ERR("failed to parse to end of headers\n"); return 0; } - if (msg->unparsed) { - len=(unsigned int)(msg->unparsed-msg->buf); + if(msg->unparsed) { + len = (unsigned int)(msg->unparsed - msg->buf); } else { LM_ERR("unparsed hook for end of headers is not set\n"); return 0; } - if ((len+2<=msg->len) && (strncmp(CRLF,msg->unparsed,CRLF_LEN)==0) ) { + if((len + 2 <= msg->len) && (strncmp(CRLF, msg->unparsed, CRLF_LEN) == 0)) { offset = CRLF_LEN; - } else if ( (len+1<=msg->len) && - (*(msg->unparsed)=='\n' || *(msg->unparsed)=='\r' ) ) { + } else if((len + 1 <= msg->len) + && (*(msg->unparsed) == '\n' || *(msg->unparsed) == '\r')) { offset = 1; } else { LM_ERR("failed to locate end of headers (%p %p - %d %d [%.*s])\n", msg->buf, msg->unparsed, msg->len, len, - (lenlen)?(msg->len-len):0, - (lenlen)?msg->unparsed:""); + (len < msg->len) ? (msg->len - len) : 0, + (len < msg->len) ? msg->unparsed : ""); return 0; } @@ -1410,13 +1465,14 @@ char* get_body(sip_msg_t* const msg) /*! \brief make sure all HFs needed for transaction identification have been * parsed; return 0 if those HFs can't be found */ -int check_transaction_quadruple(sip_msg_t* const msg) +int check_transaction_quadruple(sip_msg_t *const msg) { - if ( parse_headers(msg, HDR_FROM_F|HDR_TO_F|HDR_CALLID_F|HDR_CSEQ_F,0)!=-1 - && msg->from && msg->to && msg->callid && msg->cseq ) { + if(parse_headers(msg, HDR_FROM_F | HDR_TO_F | HDR_CALLID_F | HDR_CSEQ_F, 0) + != -1 + && msg->from && msg->to && msg->callid && msg->cseq) { return 1; } else { - ser_error=E_BAD_TUPEL; + ser_error = E_BAD_TUPEL; return 0; } } diff --git a/src/core/parser/msg_parser.h b/src/core/parser/msg_parser.h index bf0e8c31fa8..b9dc0260f9d 100644 --- a/src/core/parser/msg_parser.h +++ b/src/core/parser/msg_parser.h @@ -50,67 +50,74 @@ #define REQ_LINE(_msg) ((_msg)->first_line.u.request) #define REQ_METHOD first_line.u.request.method_value #define REPLY_STATUS first_line.u.reply.statuscode -#define REPLY_CLASS(_reply) ((_reply)->REPLY_STATUS/100) +#define REPLY_CLASS(_reply) ((_reply)->REPLY_STATUS / 100) /*@} */ /*! \brief start of "actual" sip msg (start of first line) */ -#define SIP_MSG_START(m) ((m)->first_line.u.request.method.s) +#define SIP_MSG_START(m) ((m)->first_line.u.request.method.s) /*! \brief number methods as power of two to allow bitmap matching */ -typedef enum request_method { - METHOD_UNDEF=0, /*!< 0 - --- */ - METHOD_INVITE=1, /*!< 1 - 2^0 */ - METHOD_CANCEL=2, /*!< 2 - 2^1 */ - METHOD_ACK=4, /*!< 4 - 2^2 */ - METHOD_BYE=8, /*!< 8 - 2^3 */ - METHOD_INFO=16, /*!< 16 - 2^4 */ - METHOD_REGISTER=32, /*!< 32 - 2^5 */ - METHOD_SUBSCRIBE=64, /*!< 64 - 2^6 */ - METHOD_NOTIFY=128, /*!< 128 - 2^7 */ - METHOD_MESSAGE=256, /*!< 256 - 2^8 */ - METHOD_OPTIONS=512, /*!< 512 - 2^9 */ - METHOD_PRACK=1024, /*!< 1024 - 2^10 */ - METHOD_UPDATE=2048, /*!< 2048 - 2^11 */ - METHOD_REFER=4096, /*!< 4096 - 2^12 */ - METHOD_PUBLISH=8192, /*!< 8192 - 2^13 */ - METHOD_KDMQ=16384, /*!< 16384 - 2^14 */ - METHOD_GET=32768, /*!< 32768 - 2^15 */ - METHOD_POST=65536, /*!< 65536 - 2^16 */ - METHOD_PUT=131072, /*!< 131072 - 2^17 */ - METHOD_DELETE=262144, /*!< 262144 - 2^18 */ - METHOD_OTHER=524288 /*!< 524288 - 2^19 */ +typedef enum request_method +{ + METHOD_UNDEF = 0, /*!< 0 - --- */ + METHOD_INVITE = 1, /*!< 1 - 2^0 */ + METHOD_CANCEL = 2, /*!< 2 - 2^1 */ + METHOD_ACK = 4, /*!< 4 - 2^2 */ + METHOD_BYE = 8, /*!< 8 - 2^3 */ + METHOD_INFO = 16, /*!< 16 - 2^4 */ + METHOD_REGISTER = 32, /*!< 32 - 2^5 */ + METHOD_SUBSCRIBE = 64, /*!< 64 - 2^6 */ + METHOD_NOTIFY = 128, /*!< 128 - 2^7 */ + METHOD_MESSAGE = 256, /*!< 256 - 2^8 */ + METHOD_OPTIONS = 512, /*!< 512 - 2^9 */ + METHOD_PRACK = 1024, /*!< 1024 - 2^10 */ + METHOD_UPDATE = 2048, /*!< 2048 - 2^11 */ + METHOD_REFER = 4096, /*!< 4096 - 2^12 */ + METHOD_PUBLISH = 8192, /*!< 8192 - 2^13 */ + METHOD_KDMQ = 16384, /*!< 16384 - 2^14 */ + METHOD_GET = 32768, /*!< 32768 - 2^15 */ + METHOD_POST = 65536, /*!< 65536 - 2^16 */ + METHOD_PUT = 131072, /*!< 131072 - 2^17 */ + METHOD_DELETE = 262144, /*!< 262144 - 2^18 */ + METHOD_OTHER = 524288 /*!< 524288 - 2^19 */ } request_method_t; -#define FL_FORCE_RPORT (1 << 0) /*!< force rport */ -#define FL_FORCE_ACTIVE (1 << 1) /*!< force active SDP */ -#define FL_SDP_IP_AFS (1 << 2) /*!< SDP IP rewritten */ -#define FL_SDP_PORT_AFS (1 << 3) /*!< SDP port rewritten */ -#define FL_SHM_CLONE (1 << 4) /*!< msg cloned in SHM as a single chunk */ -#define FL_TIMEOUT (1 << 5) /*!< message belongs to an "expired" branch +#define FL_FORCE_RPORT (1 << 0) /*!< force rport */ +#define FL_FORCE_ACTIVE (1 << 1) /*!< force active SDP */ +#define FL_SDP_IP_AFS (1 << 2) /*!< SDP IP rewritten */ +#define FL_SDP_PORT_AFS (1 << 3) /*!< SDP port rewritten */ +#define FL_SHM_CLONE (1 << 4) /*!< msg cloned in SHM as a single chunk */ +#define FL_TIMEOUT \ + (1 << 5) /*!< message belongs to an "expired" branch (for failure route use) */ -#define FL_REPLIED (1 << 6) /*!< message branch received at least one reply +#define FL_REPLIED \ + (1 << 6) /*!< message branch received at least one reply (for failure route use) */ -#define FL_HASH_INDEX (1 << 7) /*!< msg->hash_index contains a valid value (tm use)*/ - -#define FL_MTU_TCP_FB (1 << 8) -#define FL_MTU_TLS_FB (1 << 9) -#define FL_MTU_SCTP_FB (1 << 10) -#define FL_ADD_LOCAL_RPORT (1 << 11) /*!< add 'rport' to local via hdr */ -#define FL_SDP_BODY (1 << 12) /*!< msg has SDP in body */ -#define FL_USE_UAC_FROM (1<<13) /* take FROM hdr from UAC instead of UAS*/ -#define FL_USE_UAC_TO (1<<14) /* take TO hdr from UAC instead of UAS */ -#define FL_TM_RPL_MATCHED (1<<15) /* tm matched reply already */ -#define FL_RPL_SUSPENDED (1<<16) /* for async reply processing */ -#define FL_BODY_MULTIPART (1<<17) /* body modified is multipart */ -#define FL_RR_ADDED (1<<18) /* Record-Route header was added */ -#define FL_UAC_AUTH (1<<19) /* Proxy UAC-like authentication */ -#define FL_ADD_SRVID (1<<20) /*!< add 'srvid' to local via hdr */ -#define FL_ADD_XAVP_VIA_PARAMS (1<<21) /*!< add xavp fields to local via params */ -#define FL_USE_XAVP_VIA_FIELDS (1<<22) /*!< use xavp fields for local via attrs */ -#define FL_MSG_NOREPLY (1<<23) /*!< do not send sip reply for request */ -#define FL_SIPTRACE (1<<24) /*!< message to be traced in stateless replies */ -#define FL_ROUTE_ADDR (1<<25) /*!< request has Route address for next hop */ -#define FL_USE_OTCPID (1<<26) /*!< request to be routed using outbound tcp con id */ +#define FL_HASH_INDEX \ + (1 << 7) /*!< msg->hash_index contains a valid value (tm use)*/ + +#define FL_MTU_TCP_FB (1 << 8) +#define FL_MTU_TLS_FB (1 << 9) +#define FL_MTU_SCTP_FB (1 << 10) +#define FL_ADD_LOCAL_RPORT (1 << 11) /*!< add 'rport' to local via hdr */ +#define FL_SDP_BODY (1 << 12) /*!< msg has SDP in body */ +#define FL_USE_UAC_FROM (1 << 13) /* take FROM hdr from UAC instead of UAS*/ +#define FL_USE_UAC_TO (1 << 14) /* take TO hdr from UAC instead of UAS */ +#define FL_TM_RPL_MATCHED (1 << 15) /* tm matched reply already */ +#define FL_RPL_SUSPENDED (1 << 16) /* for async reply processing */ +#define FL_BODY_MULTIPART (1 << 17) /* body modified is multipart */ +#define FL_RR_ADDED (1 << 18) /* Record-Route header was added */ +#define FL_UAC_AUTH (1 << 19) /* Proxy UAC-like authentication */ +#define FL_ADD_SRVID (1 << 20) /*!< add 'srvid' to local via hdr */ +#define FL_ADD_XAVP_VIA_PARAMS \ + (1 << 21) /*!< add xavp fields to local via params */ +#define FL_USE_XAVP_VIA_FIELDS \ + (1 << 22) /*!< use xavp fields for local via attrs */ +#define FL_MSG_NOREPLY (1 << 23) /*!< do not send sip reply for request */ +#define FL_SIPTRACE (1 << 24) /*!< message to be traced in stateless replies */ +#define FL_ROUTE_ADDR (1 << 25) /*!< request has Route address for next hop */ +#define FL_USE_OTCPID \ + (1 << 26) /*!< request to be routed using outbound tcp con id */ /* WARNING: Value (1 << 28) is reserved for use in kamailio call_control * module (flag FL_USE_CALL_CONTROL )! */ @@ -124,52 +131,52 @@ typedef enum request_method { /* WARNING: Value (1 << 31) is reserved for use in kamailio * nat_traversal module (flag FL_DO_KEEPALIVE)! */ -#define FL_MTU_FB_MASK (FL_MTU_TCP_FB|FL_MTU_TLS_FB|FL_MTU_SCTP_FB) +#define FL_MTU_FB_MASK (FL_MTU_TCP_FB | FL_MTU_TLS_FB | FL_MTU_SCTP_FB) /* sip parser mode flags (1<type=SIP_REQUEST; \ - fl->u.request.method.len=methodname##_LEN; \ - fl->u.request.method_value=METHOD_##methodname; \ - tmp=buffer+methodname##_LEN; \ -} +#define IFISMETHOD(methodname, firstchar) \ + if((*tmp == (firstchar) || *tmp == ((firstchar) | 32)) \ + && strncasecmp(tmp + 1, &#methodname[1], methodname##_LEN - 1) \ + == 0 \ + && *(tmp + methodname##_LEN) == ' ') { \ + fl->type = SIP_REQUEST; \ + fl->u.request.method.len = methodname##_LEN; \ + fl->u.request.method_value = METHOD_##methodname; \ + tmp = buffer + methodname##_LEN; \ + } /* sip request */ -#define IS_SIP(req) \ - (((req)->first_line.type == SIP_REQUEST) && \ - ((req)->first_line.flags & FLINE_FLAG_PROTO_SIP)) +#define IS_SIP(req) \ + (((req)->first_line.type == SIP_REQUEST) \ + && ((req)->first_line.flags & FLINE_FLAG_PROTO_SIP)) /* sip request */ -#define IS_SIP_REQUEST(req) \ - (((req)->first_line.type == SIP_REQUEST) && \ - ((req)->first_line.flags & FLINE_FLAG_PROTO_SIP)) +#define IS_SIP_REQUEST(req) \ + (((req)->first_line.type == SIP_REQUEST) \ + && ((req)->first_line.flags & FLINE_FLAG_PROTO_SIP)) /* sip reply */ -#define IS_SIP_REPLY(rpl) \ - (((rpl)->first_line.type == SIP_REPLY) && \ - ((rpl)->first_line.flags & FLINE_FLAG_PROTO_SIP)) +#define IS_SIP_REPLY(rpl) \ + (((rpl)->first_line.type == SIP_REPLY) \ + && ((rpl)->first_line.flags & FLINE_FLAG_PROTO_SIP)) /* sip message */ -#define IS_SIP_MSG(req) \ - ((req)->first_line.flags & FLINE_FLAG_PROTO_SIP) +#define IS_SIP_MSG(req) ((req)->first_line.flags & FLINE_FLAG_PROTO_SIP) /* http request */ -#define IS_HTTP(req) \ - (((req)->first_line.type == SIP_REQUEST) && \ - ((req)->first_line.flags & FLINE_FLAG_PROTO_HTTP)) +#define IS_HTTP(req) \ + (((req)->first_line.type == SIP_REQUEST) \ + && ((req)->first_line.flags & FLINE_FLAG_PROTO_HTTP)) /* http reply */ -#define IS_HTTP_REPLY(rpl) \ - (((rpl)->first_line.type == SIP_REPLY) && \ - ((rpl)->first_line.flags & FLINE_FLAG_PROTO_HTTP)) +#define IS_HTTP_REPLY(rpl) \ + (((rpl)->first_line.type == SIP_REPLY) \ + && ((rpl)->first_line.flags & FLINE_FLAG_PROTO_HTTP)) /*! \brief * Return a URI to which the message should be really sent (not what should @@ -178,9 +185,12 @@ if ( (*tmp==(firstchar) || *tmp==((firstchar) | 32)) && \ * 2) new_uri * 3) first_line.u.request.uri */ -#define GET_NEXT_HOP(m) \ -(((m)->dst_uri.s && (m)->dst_uri.len) ? (&(m)->dst_uri) : \ -(((m)->new_uri.s && (m)->new_uri.len) ? (&(m)->new_uri) : (&(m)->first_line.u.request.uri))) +#define GET_NEXT_HOP(m) \ + (((m)->dst_uri.s && (m)->dst_uri.len) \ + ? (&(m)->dst_uri) \ + : (((m)->new_uri.s && (m)->new_uri.len) \ + ? (&(m)->new_uri) \ + : (&(m)->first_line.u.request.uri))) /*! \brief @@ -189,8 +199,9 @@ if ( (*tmp==(firstchar) || *tmp==((firstchar) | 32)) && \ * 1) new_uri * 2) first_line.u.request.uri */ -#define GET_RURI(m) \ -(((m)->new_uri.s && (m)->new_uri.len) ? (&(m)->new_uri) : (&(m)->first_line.u.request.uri)) +#define GET_RURI(m) \ + (((m)->new_uri.s && (m)->new_uri.len) ? (&(m)->new_uri) \ + : (&(m)->first_line.u.request.uri)) /*! \brief @@ -199,24 +210,36 @@ if ( (*tmp==(firstchar) || *tmp==((firstchar) | 32)) && \ * - 5061 for _proto == TLS or WSS * - 5060 for the other _proto */ -#define GET_SIP_PORT(_port, _proto) ((_port==0)?((_proto==PROTO_TLS \ - || _proto==PROTO_WSS)?5061:5060):_port) - -enum _uri_type{ERROR_URI_T=0, SIP_URI_T, SIPS_URI_T, TEL_URI_T, TELS_URI_T, URN_URI_T}; +#define GET_SIP_PORT(_port, _proto) \ + ((_port == 0) ? ( \ + (_proto == PROTO_TLS || _proto == PROTO_WSS) ? 5061 : 5060) \ + : _port) + +enum _uri_type +{ + ERROR_URI_T = 0, + SIP_URI_T, + SIPS_URI_T, + TEL_URI_T, + TELS_URI_T, + URN_URI_T +}; typedef enum _uri_type uri_type; -enum _uri_flags{ - URI_USER_NORMALIZE=1, - URI_SIP_USER_PHONE=2 +enum _uri_flags +{ + URI_USER_NORMALIZE = 1, + URI_SIP_USER_PHONE = 2 }; /* bit fields */ typedef enum _uri_flags uri_flags; /*! \brief The SIP uri object */ -struct sip_uri { - str user; /*!< Username */ - str passwd; /*!< Password */ - str host; /*!< Host name */ - str port; /*!< Port number */ - str params; /*!< Parameters */ +struct sip_uri +{ + str user; /*!< Username */ + str passwd; /*!< Password */ + str host; /*!< Host name */ + str port; /*!< Port number */ + str params; /*!< Parameters */ str sip_params; /*!< Parameters of the sip: URI. * (If a tel: URI is embedded in a sip: URI, then * params points to the parameters of the tel: URI, @@ -225,7 +248,7 @@ struct sip_uri { str headers; unsigned short port_no; unsigned short proto; /*!< from transport */ - uri_type type; /*!< uri scheme */ + uri_type type; /*!< uri scheme */ uri_flags flags; /*!< parameters */ str transport; @@ -236,12 +259,12 @@ struct sip_uri { str lr; str r2; /*!< ser specific rr parameter */ str gr; - str transport_val; /*!< transport value */ - str ttl_val; /*!< TTL value */ + str transport_val; /*!< transport value */ + str ttl_val; /*!< TTL value */ str user_param_val; /*!< User= param value */ - str maddr_val; /*!< Maddr= param value */ - str method_val; /*!< Method value */ - str lr_val; /*!< lr value placeholder for lr=on a.s.o*/ + str maddr_val; /*!< Maddr= param value */ + str method_val; /*!< Method value */ + str lr_val; /*!< lr value placeholder for lr=on a.s.o*/ str r2_val; str gr_val; #ifdef USE_COMP @@ -253,9 +276,10 @@ typedef struct sip_uri sip_uri_t; struct msg_body; -typedef void (*free_msg_body_f)(struct msg_body** ptr); +typedef void (*free_msg_body_f)(struct msg_body **ptr); -typedef enum msg_body_type { +typedef enum msg_body_type +{ MSG_BODY_UNKNOWN = 0, MSG_BODY_SDP } msg_body_type_t; @@ -268,7 +292,8 @@ typedef enum msg_body_type { * retain msg_body_type variable and a pointer to the free function as the * first two variables within the structure. */ -typedef struct msg_body { +typedef struct msg_body +{ msg_body_type_t type; free_msg_body_f free; } msg_body_t; @@ -278,91 +303,94 @@ typedef struct msg_body { struct timeval; /* structure for cached decoded flow for outbound */ -typedef struct ocd_flow { - int decoded; - struct receive_info rcv; +typedef struct ocd_flow +{ + int decoded; + struct receive_info rcv; } ocd_flow_t; /* structure holding fields that don't have to be cloned in shm * - its content is memset'ed to in shm clone * - add to msg_ldata_reset() if a field uses dynamic memory */ -typedef struct msg_ldata { +typedef struct msg_ldata +{ ocd_flow_t flow; void *vdata; } msg_ldata_t; /*! \brief The SIP message */ -typedef struct sip_msg { - unsigned int id; /*!< message id, unique/process*/ - int pid; /*!< process id */ - struct timeval tval; /*!< time value associated to message */ - snd_flags_t fwd_send_flags; /*!< send flags for forwarding */ - snd_flags_t rpl_send_flags; /*!< send flags for replies */ +typedef struct sip_msg +{ + unsigned int id; /*!< message id, unique/process*/ + int pid; /*!< process id */ + struct timeval tval; /*!< time value associated to message */ + snd_flags_t fwd_send_flags; /*!< send flags for forwarding */ + snd_flags_t rpl_send_flags; /*!< send flags for replies */ struct msg_start first_line; /*!< Message first line */ - struct via_body* via1; /*!< The first via */ - struct via_body* via2; /*!< The second via */ - struct hdr_field* headers; /*!< All the parsed headers*/ - struct hdr_field* last_header; /*!< Pointer to the last parsed header*/ - hdr_flags_t parsed_flag; /*!< Already parsed header field types */ + struct via_body *via1; /*!< The first via */ + struct via_body *via2; /*!< The second via */ + struct hdr_field *headers; /*!< All the parsed headers*/ + struct hdr_field *last_header; /*!< Pointer to the last parsed header*/ + hdr_flags_t parsed_flag; /*!< Already parsed header field types */ /* Via, To, CSeq, Call-Id, From, end of header*/ /* pointers to the first occurrences of these headers; * everything is also saved in 'headers' * (WARNING: do not deallocate them twice!)*/ - struct hdr_field* h_via1; - struct hdr_field* h_via2; - struct hdr_field* callid; - struct hdr_field* to; - struct hdr_field* cseq; - struct hdr_field* from; - struct hdr_field* contact; - struct hdr_field* maxforwards; - struct hdr_field* route; - struct hdr_field* record_route; - struct hdr_field* content_type; - struct hdr_field* content_length; - struct hdr_field* authorization; - struct hdr_field* expires; - struct hdr_field* proxy_auth; - struct hdr_field* supported; - struct hdr_field* require; - struct hdr_field* proxy_require; - struct hdr_field* unsupported; - struct hdr_field* allow; - struct hdr_field* event; - struct hdr_field* accept; - struct hdr_field* accept_language; - struct hdr_field* organization; - struct hdr_field* priority; - struct hdr_field* subject; - struct hdr_field* user_agent; - struct hdr_field* server; - struct hdr_field* content_disposition; - struct hdr_field* diversion; - struct hdr_field* rpid; - struct hdr_field* refer_to; - struct hdr_field* session_expires; - struct hdr_field* min_se; - struct hdr_field* sipifmatch; - struct hdr_field* subscription_state; - struct hdr_field* date; - struct hdr_field* identity; - struct hdr_field* identity_info; - struct hdr_field* pai; - struct hdr_field* ppi; - struct hdr_field* path; - struct hdr_field* privacy; - struct hdr_field* min_expires; - - struct msg_body* body; - - char* eoh; /*!< pointer to the end of header (if found) or null */ - char* unparsed; /*!< here we stopped parsing*/ + struct hdr_field *h_via1; + struct hdr_field *h_via2; + struct hdr_field *callid; + struct hdr_field *to; + struct hdr_field *cseq; + struct hdr_field *from; + struct hdr_field *contact; + struct hdr_field *maxforwards; + struct hdr_field *route; + struct hdr_field *record_route; + struct hdr_field *content_type; + struct hdr_field *content_length; + struct hdr_field *authorization; + struct hdr_field *expires; + struct hdr_field *proxy_auth; + struct hdr_field *supported; + struct hdr_field *require; + struct hdr_field *proxy_require; + struct hdr_field *unsupported; + struct hdr_field *allow; + struct hdr_field *event; + struct hdr_field *accept; + struct hdr_field *accept_language; + struct hdr_field *organization; + struct hdr_field *priority; + struct hdr_field *subject; + struct hdr_field *user_agent; + struct hdr_field *server; + struct hdr_field *content_disposition; + struct hdr_field *diversion; + struct hdr_field *rpid; + struct hdr_field *refer_to; + struct hdr_field *session_expires; + struct hdr_field *min_se; + struct hdr_field *sipifmatch; + struct hdr_field *subscription_state; + struct hdr_field *date; + struct hdr_field *identity; + struct hdr_field *identity_info; + struct hdr_field *pai; + struct hdr_field *ppi; + struct hdr_field *path; + struct hdr_field *privacy; + struct hdr_field *min_expires; + + struct msg_body *body; + + char *eoh; /*!< pointer to the end of header (if found) or null */ + char *unparsed; /*!< here we stopped parsing*/ struct receive_info rcv; /*!< source & dest ip, ports, proto a.s.o*/ - char* buf; /*!< scratch pad, holds a modified message, + char *buf; /*!< scratch pad, holds a modified message, * via, etc. point into it */ unsigned int len; /*!< message len (orig) */ @@ -379,10 +407,11 @@ typedef struct sip_msg { struct sip_uri parsed_uri; /*!< speed-up > keep here the parsed uri*/ int parsed_orig_ruri_ok; /*!< 1 if parsed_orig_uri is valid, 0 if not, set if to 0 if you modify the uri (e.g change new_uri)*/ - struct sip_uri parsed_orig_ruri; /*!< speed-up > keep here the parsed orig uri*/ + struct sip_uri + parsed_orig_ruri; /*!< speed-up > keep here the parsed orig uri*/ - struct lump* add_rm; /*!< used for all the forwarded requests/replies */ - struct lump* body_lumps; /*!< Lumps that update Content-Length */ + struct lump *add_rm; /*!< used for all the forwarded requests/replies */ + struct lump *body_lumps; /*!< Lumps that update Content-Length */ struct lump_rpl *reply_lump; /*!< only for locally generated replies !!!*/ /*! \brief str add_to_branch; @@ -390,14 +419,14 @@ typedef struct sip_msg { char add_to_branch_s[MAX_BRANCH_PARAM_LEN]; int add_to_branch_len; - unsigned int hash_index; /*!< index to TM hash table; stored in core + unsigned int hash_index; /*!< index to TM hash table; stored in core to avoid unnecessary calculations */ - unsigned int msg_flags; /*!< internal flags used by core */ - flag_t flags; /*!< config flags */ + unsigned int msg_flags; /*!< internal flags used by core */ + flag_t flags; /*!< config flags */ flag_t xflags[KSR_XFLAGS_SIZE]; /*!< config extended flags */ str set_global_address; str set_global_port; - struct socket_info* force_send_socket; /*!< force sending on this socket */ + struct socket_info *force_send_socket; /*!< force sending on this socket */ str path_vec; str instance; unsigned int reg_id; @@ -420,7 +449,7 @@ typedef struct sip_msg { (when this message is "relayed", it is generated out of the original request) */ -#define FAKED_REPLY ((struct sip_msg *) -1) +#define FAKED_REPLY ((struct sip_msg *)-1) extern int via_cnt; /** global request flags. @@ -431,70 +460,73 @@ extern int via_cnt; extern unsigned int global_req_flags; -int parse_msg(char* const buf, const unsigned int len, struct sip_msg* const msg); +int parse_msg( + char *const buf, const unsigned int len, struct sip_msg *const msg); -int parse_headers(struct sip_msg* const msg, const hdr_flags_t flags, const int next); +int parse_headers( + struct sip_msg *const msg, const hdr_flags_t flags, const int next); -char* get_hdr_field(char* const buf, char* const end, struct hdr_field* const hdr); +char *get_hdr_field( + char *const buf, char *const end, struct hdr_field *const hdr); -void free_sip_msg(struct sip_msg* const msg); +void free_sip_msg(struct sip_msg *const msg); /*! \brief make sure all HFs needed for transaction identification have been parsed; return 0 if those HFs can't be found */ -int check_transaction_quadruple(sip_msg_t* const msg); +int check_transaction_quadruple(sip_msg_t *const msg); /*! \brief returns a pointer to the beginning of the msg's body */ -char* get_body(sip_msg_t* const msg); +char *get_body(sip_msg_t *const msg); /*! \brief If the new_uri is set, then reset it */ -void reset_new_uri(struct sip_msg* const msg); +void reset_new_uri(struct sip_msg *const msg); /*! \brief * Make a private copy of the string and assign it to dst_uri */ -int set_dst_uri(struct sip_msg* const msg, const str* const uri); +int set_dst_uri(struct sip_msg *const msg, const str *const uri); /*! \brief If the dst_uri is set to an URI then reset it */ -void reset_dst_uri(struct sip_msg* const msg); +void reset_dst_uri(struct sip_msg *const msg); -hdr_field_t* get_hdr(const sip_msg_t* const msg, const enum _hdr_types_t ht); -hdr_field_t* next_sibling_hdr(const hdr_field_t* const hf); +hdr_field_t *get_hdr(const sip_msg_t *const msg, const enum _hdr_types_t ht); +hdr_field_t *next_sibling_hdr(const hdr_field_t *const hf); /** not used yet */ -hdr_field_t* get_hdr_by_name(const sip_msg_t* const msg, const char* const name, - const int name_len); -hdr_field_t* next_sibling_hdr_by_name(const hdr_field_t* const hf); +hdr_field_t *get_hdr_by_name( + const sip_msg_t *const msg, const char *const name, const int name_len); +hdr_field_t *next_sibling_hdr_by_name(const hdr_field_t *const hf); -int set_path_vector(struct sip_msg* msg, str* path); +int set_path_vector(struct sip_msg *msg, str *path); -void reset_path_vector(struct sip_msg* const msg); +void reset_path_vector(struct sip_msg *const msg); -int set_instance(struct sip_msg* msg, str* instance); +int set_instance(struct sip_msg *msg, str *instance); -void reset_instance(struct sip_msg* const msg); +void reset_instance(struct sip_msg *const msg); -int set_ruid(struct sip_msg* msg, str* ruid); +int set_ruid(struct sip_msg *msg, str *ruid); -void reset_ruid(struct sip_msg* const msg); +void reset_ruid(struct sip_msg *const msg); -int set_ua(struct sip_msg* msg, str *location_ua); +int set_ua(struct sip_msg *msg, str *location_ua); -void reset_ua(struct sip_msg* const msg); +void reset_ua(struct sip_msg *const msg); /** force a specific send socket for forwarding a request. * @param msg - sip msg. * @param fsocket - forced socket, pointer to struct socket_info, can be 0 (in * which case it's equivalent to reset_force_socket()). */ -#define set_force_socket(msg, fsocket) \ - do { \ - (msg)->force_send_socket=(fsocket); \ - if ((msg)->force_send_socket) \ - (msg)->fwd_send_flags.f |= SND_F_FORCE_SOCKET; \ - else \ +#define set_force_socket(msg, fsocket) \ + do { \ + (msg)->force_send_socket = (fsocket); \ + if((msg)->force_send_socket) \ + (msg)->fwd_send_flags.f |= SND_F_FORCE_SOCKET; \ + else \ (msg)->fwd_send_flags.f &= ~SND_F_FORCE_SOCKET; \ - } while (0) + } while(0) /** reset a previously forced send socket. */ #define reset_force_socket(msg) set_force_socket(msg, 0) @@ -503,7 +535,8 @@ void reset_ua(struct sip_msg* const msg); * struct to identify a msg context * - the pair of message-id and pid (fields in sip_msg_t) */ -typedef struct msg_ctx_id { +typedef struct msg_ctx_id +{ unsigned int msgid; int pid; } msg_ctx_id_t; @@ -512,23 +545,23 @@ typedef struct msg_ctx_id { * set msg context id * - return: -1 on error; 0 - on set */ -int msg_ctx_id_set(const sip_msg_t* const msg, msg_ctx_id_t* const mid); +int msg_ctx_id_set(const sip_msg_t *const msg, msg_ctx_id_t *const mid); /** * check msg context id * - return: -1 on error; 0 - on no match; 1 - on match */ -int msg_ctx_id_match(const sip_msg_t* const msg, const msg_ctx_id_t* const mid); +int msg_ctx_id_match(const sip_msg_t *const msg, const msg_ctx_id_t *const mid); /** * set msg time value */ -int msg_set_time(sip_msg_t* const msg); +int msg_set_time(sip_msg_t *const msg); /** * reset content of msg->ldv (msg_ldata_t structure) */ -void msg_ldata_reset(sip_msg_t*); +void msg_ldata_reset(sip_msg_t *); /** * replace \r\n with . and space diff --git a/src/core/parser/parse_addr_spec.c b/src/core/parser/parse_addr_spec.c index f003e5f31ab..7a4b2dbad86 100644 --- a/src/core/parser/parse_addr_spec.c +++ b/src/core/parser/parse_addr_spec.c @@ -225,10 +225,11 @@ static char *parse_to_param(char *const buffer, const char *const end, case '\\': switch(status) { case PARA_VALUE_QUOTED: - if(tmp+1>=end) { - LM_ERR("unexpected end of data in status %d - start: %p" - " - end: %p - crt: %p\n", - status, buffer, end , tmp); + if(tmp + 1 >= end) { + LM_ERR("unexpected end of data in status %d - " + "start: %p" + " - end: %p - crt: %p\n", + status, buffer, end, tmp); goto error; } switch(*(tmp + 1)) { @@ -247,10 +248,11 @@ static char *parse_to_param(char *const buffer, const char *const end, case '"': switch(status) { case S_PARA_VALUE: - if(tmp+1>=end) { - LM_ERR("unexpected end of data in status %d - start: %p" - " - end: %p - crt: %p\n", - status, buffer, end , tmp); + if(tmp + 1 >= end) { + LM_ERR("unexpected end of data in status %d - " + "start: %p" + " - end: %p - crt: %p\n", + status, buffer, end, tmp); goto error; } param->value.s = tmp + 1; @@ -479,7 +481,7 @@ static char *parse_to_param(char *const buffer, const char *const end, goto endofheader; default: LM_ERR("unexpected char [%c] in status %d: [%.*s] " - ".\n", + ".\n", *tmp, status, (int)(tmp - buffer), ZSW(buffer)); goto error; @@ -526,7 +528,7 @@ static char *parse_to_param(char *const buffer, const char *const end, goto error; } } /*switch*/ - } /*for*/ + } /*for*/ if(!(status == F_CR || status == F_LF || status == F_CRLF)) saved_status = status; @@ -534,8 +536,8 @@ static char *parse_to_param(char *const buffer, const char *const end, endofheader: switch(saved_status) { case TAG3: - param->type = TAG_PARAM; /* tag at the end */ - /* no break */ + param->type = TAG_PARAM; /* tag at the end */ + /* no break */ case PARA_NAME: case TAG1: case TAG2: @@ -650,8 +652,10 @@ char *parse_addr_spec(char *const buffer, const char *const end, status = saved_status; goto endofheader; default: - LM_ERR("unexpected char [%c/%d] in status %d: [%.*s] .\n", - *tmp, *tmp, status, (int)(tmp - buffer), ZSW(buffer)); + LM_ERR("unexpected char [%c/%d] in status %d: [%.*s] " + ".\n", + *tmp, *tmp, status, (int)(tmp - buffer), + ZSW(buffer)); goto error; } break; @@ -678,8 +682,10 @@ char *parse_addr_spec(char *const buffer, const char *const end, status = saved_status; goto endofheader; default: - LM_ERR("unexpected char [%c/%d] in status %d: [%.*s] .\n", - *tmp, *tmp, status, (int)(tmp - buffer), ZSW(buffer)); + LM_ERR("unexpected char [%c/%d] in status %d: [%.*s] " + ".\n", + *tmp, *tmp, status, (int)(tmp - buffer), + ZSW(buffer)); goto error; } break; @@ -692,8 +698,10 @@ char *parse_addr_spec(char *const buffer, const char *const end, saved_status = status = END; goto endofheader; default: - LM_ERR("unexpected char [%c/%d] in status %d: [%.*s] .\n", - *tmp, *tmp, status, (int)(tmp - buffer), ZSW(buffer)); + LM_ERR("unexpected char [%c/%d] in status %d: [%.*s] " + ".\n", + *tmp, *tmp, status, (int)(tmp - buffer), + ZSW(buffer)); goto error; } break; @@ -703,8 +711,10 @@ char *parse_addr_spec(char *const buffer, const char *const end, tmp++; /* jump over next char */ break; default: - LM_ERR("unexpected char [%c/%d] in status %d: [%.*s] .\n", - *tmp, *tmp, status, (int)(tmp - buffer), ZSW(buffer)); + LM_ERR("unexpected char [%c/%d] in status %d: [%.*s] " + ".\n", + *tmp, *tmp, status, (int)(tmp - buffer), + ZSW(buffer)); goto error; } break; @@ -735,8 +745,10 @@ char *parse_addr_spec(char *const buffer, const char *const end, /*previous=crlf and now !=' '*/ goto endofheader; default: - LM_ERR("unexpected char [%c/%d] in status %d: [%.*s] .\n", - *tmp, *tmp, status, (int)(tmp - buffer), ZSW(buffer)); + LM_ERR("unexpected char [%c/%d] in status %d: [%.*s] " + ".\n", + *tmp, *tmp, status, (int)(tmp - buffer), + ZSW(buffer)); goto error; } break; @@ -756,8 +768,10 @@ char *parse_addr_spec(char *const buffer, const char *const end, /*previous=crlf and now !=' '*/ goto endofheader; default: - LM_ERR("unexpected char [%c/%d] in status %d: [%.*s] .\n", - *tmp, *tmp, status, (int)(tmp - buffer), ZSW(buffer)); + LM_ERR("unexpected char [%c/%d] in status %d: [%.*s] " + ".\n", + *tmp, *tmp, status, (int)(tmp - buffer), + ZSW(buffer)); goto error; } break; @@ -778,8 +792,10 @@ char *parse_addr_spec(char *const buffer, const char *const end, /*previous=crlf and now !=' '*/ goto endofheader; default: - LM_ERR("unexpected char [%c/%d] in status %d: [%.*s] .\n", - *tmp, *tmp, status, (int)(tmp - buffer), buffer); + LM_ERR("unexpected char [%c/%d] in status %d: [%.*s] " + ".\n", + *tmp, *tmp, status, (int)(tmp - buffer), + buffer); goto error; } break; @@ -803,8 +819,10 @@ char *parse_addr_spec(char *const buffer, const char *const end, /*previous=crlf and now !=' '*/ goto endofheader; default: - LM_ERR("unexpected char [%c/%d] in status %d: [%.*s] .\n", - *tmp, *tmp, status, (int)(tmp - buffer), buffer); + LM_ERR("unexpected char [%c/%d] in status %d: [%.*s] " + ".\n", + *tmp, *tmp, status, (int)(tmp - buffer), + buffer); goto error; } break; @@ -828,9 +846,11 @@ char *parse_addr_spec(char *const buffer, const char *const end, /*previous=crlf and now !=' '*/ goto endofheader; default: - LM_ERR("unexpected char [%c/%d] in status %d: [%.*s] " - ".\n", - *tmp, *tmp, status, (int)(tmp - buffer), buffer); + LM_ERR("unexpected char [%c/%d] in status %d: " + "[%.*s] " + ".\n", + *tmp, *tmp, status, (int)(tmp - buffer), + buffer); goto error; } break; @@ -866,7 +886,7 @@ char *parse_addr_spec(char *const buffer, const char *const end, goto error; } } /*char switch*/ - } /*for*/ + } /*for*/ /* Reached end of buffer */ switch(status) { @@ -893,7 +913,7 @@ char *parse_addr_spec(char *const buffer, const char *const end, break; default: LM_ERR("invalid body - unexpected " - "end of header in state %d\n", + "end of header in state %d\n", status); goto error; } diff --git a/src/core/parser/parse_addr_spec.h b/src/core/parser/parse_addr_spec.h index 3f6185d4506..7f3663b386a 100644 --- a/src/core/parser/parse_addr_spec.h +++ b/src/core/parser/parse_addr_spec.h @@ -13,8 +13,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ @@ -30,41 +30,46 @@ #include "../str.h" #include "msg_parser.h" -enum { - TAG_PARAM = 400, GENERAL_PARAM +enum +{ + TAG_PARAM = 400, + GENERAL_PARAM }; -typedef struct to_param{ - int type; /*!< Type of parameter */ - str name; /*!< Name of parameter */ - str value; /*!< Parameter value */ - struct to_param* next; /*!< Next parameter in the list */ +typedef struct to_param +{ + int type; /*!< Type of parameter */ + str name; /*!< Name of parameter */ + str value; /*!< Parameter value */ + struct to_param *next; /*!< Next parameter in the list */ } to_param_t; -typedef struct to_body{ - int error; /*!< Error code */ - str body; /*!< The whole header field body */ - str uri; /*!< URI */ - str display; /*!< Display Name */ - str tag_value; /*!< Value of tag */ +typedef struct to_body +{ + int error; /*!< Error code */ + str body; /*!< The whole header field body */ + str uri; /*!< URI */ + str display; /*!< Display Name */ + str tag_value; /*!< Value of tag */ struct sip_uri parsed_uri; - struct to_param *param_lst; /*!< Linked list of parameters */ - struct to_param *last_param; /*!< Last parameter in the list */ + struct to_param *param_lst; /*!< Linked list of parameters */ + struct to_param *last_param; /*!< Last parameter in the list */ } to_body_t; /*! \brief * To header field parser */ -char* parse_addr_spec(char* const buffer, const char* const end, struct to_body* const to_b, int allow_comma_separated); +char *parse_addr_spec(char *const buffer, const char *const end, + struct to_body *const to_b, int allow_comma_separated); -void free_to_params(struct to_body* const tb); +void free_to_params(struct to_body *const tb); -void free_to(struct to_body* const tb); +void free_to(struct to_body *const tb); -int parse_to_header(struct sip_msg* const msg); +int parse_to_header(struct sip_msg *const msg); -sip_uri_t *parse_to_uri(struct sip_msg* const msg); +sip_uri_t *parse_to_uri(struct sip_msg *const msg); #endif diff --git a/src/core/parser/parse_allow.c b/src/core/parser/parse_allow.c index 3b04975e706..e18338ec2ba 100644 --- a/src/core/parser/parse_allow.c +++ b/src/core/parser/parse_allow.c @@ -40,38 +40,39 @@ * \param _hf message header field * \return 0 on success, -1 on failure. */ -int parse_allow_header(struct hdr_field* _hf) +int parse_allow_header(struct hdr_field *_hf) { - struct allow_body* ab = 0; + struct allow_body *ab = 0; - if (!_hf) { + if(!_hf) { LM_ERR("invalid parameter value\n"); return -1; } /* maybe the header is already parsed! */ - if (_hf->parsed) { + if(_hf->parsed) { return 0; } - ab = (struct allow_body*)pkg_malloc(sizeof(struct allow_body)); - if (ab == 0) { + ab = (struct allow_body *)pkg_malloc(sizeof(struct allow_body)); + if(ab == 0) { PKG_MEM_ERROR; return -1; } - memset(ab,'\0', sizeof(struct allow_body)); + memset(ab, '\0', sizeof(struct allow_body)); - if (parse_methods(&(_hf->body), &(ab->allow)) !=0 ) { + if(parse_methods(&(_hf->body), &(ab->allow)) != 0) { LM_ERR("bad allow body header\n"); goto error; } ab->allow_all = 0; - _hf->parsed = (void*)ab; + _hf->parsed = (void *)ab; return 0; error: - if (ab) pkg_free(ab); + if(ab) + pkg_free(ab); return -1; } @@ -83,30 +84,30 @@ int parse_allow_header(struct hdr_field* _hf) int parse_allow(struct sip_msg *msg) { unsigned int allow; - struct hdr_field *hdr; + struct hdr_field *hdr; /* maybe the header is already parsed! */ - if (msg->allow && msg->allow->parsed) { + if(msg->allow && msg->allow->parsed) { return 0; } /* parse to the end in order to get all ALLOW headers */ - if (parse_headers(msg,HDR_EOH_F,0)==-1 || !msg->allow) { + if(parse_headers(msg, HDR_EOH_F, 0) == -1 || !msg->allow) { return -1; } allow = 0; - for(hdr = msg->allow ; hdr ; hdr = next_sibling_hdr(hdr)) { - if (hdr->parsed == 0) { + for(hdr = msg->allow; hdr; hdr = next_sibling_hdr(hdr)) { + if(hdr->parsed == 0) { if(parse_allow_header(hdr) < 0) { return -1; } } - allow |= ((struct allow_body*)hdr->parsed)->allow; + allow |= ((struct allow_body *)hdr->parsed)->allow; } - ((struct allow_body*)msg->allow->parsed)->allow_all = allow; + ((struct allow_body *)msg->allow->parsed)->allow_all = allow; return 0; } @@ -116,14 +117,14 @@ int parse_allow(struct sip_msg *msg) */ void free_allow_body(struct allow_body **ab) { - if (ab && *ab) { + if(ab && *ab) { pkg_free(*ab); *ab = 0; } } -void free_allow_header(struct hdr_field* hf) +void free_allow_header(struct hdr_field *hf) { - free_allow_body((struct allow_body**)(void*)(&(hf->parsed))); + free_allow_body((struct allow_body **)(void *)(&(hf->parsed))); } diff --git a/src/core/parser/parse_allow.h b/src/core/parser/parse_allow.h index 26d60357ce0..25a39cfa491 100644 --- a/src/core/parser/parse_allow.h +++ b/src/core/parser/parse_allow.h @@ -13,8 +13,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ @@ -24,23 +24,24 @@ * \ingroup parser */ - + #ifndef PARSE_ALLOW_H #define PARSE_ALLOW_H - + #include "hf.h" #include "msg_parser.h" - + /*! \brief - * casting macro for accessing Allow body + * casting macro for accessing Allow body */ -#define get_allow_methods(p_msg) \ - (((struct allow_body*)(p_msg)->allow->parsed)->allow_all) +#define get_allow_methods(p_msg) \ + (((struct allow_body *)(p_msg)->allow->parsed)->allow_all) -struct allow_body { - unsigned int allow; /*!< allow mask for the current hdr */ +struct allow_body +{ + unsigned int allow; /*!< allow mask for the current hdr */ unsigned int allow_all; /*!< allow mask for the all allow hdr - it's * set only for the first hdr in sibling * list*/ @@ -59,7 +60,7 @@ int parse_allow(struct sip_msg *msg); * \param _hf message header field * \return 0 on success, -1 on failure. */ -int parse_allow_header(struct hdr_field* _hf); +int parse_allow_header(struct hdr_field *_hf); /*! \brief @@ -67,8 +68,7 @@ int parse_allow_header(struct hdr_field* _hf); */ void free_allow_body(struct allow_body **ab); -void free_allow_header(struct hdr_field* hf); - +void free_allow_header(struct hdr_field *hf); #endif /* PARSE_ALLOW_H */ diff --git a/src/core/parser/parse_body.c b/src/core/parser/parse_body.c index 363588ee25b..c4140342727 100644 --- a/src/core/parser/parse_body.c +++ b/src/core/parser/parse_body.c @@ -13,8 +13,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ @@ -37,55 +37,51 @@ /*! \brief returns the value of boundary parameter from the Content-Type HF */ static inline int get_boundary_param(struct sip_msg *msg, str *boundary) { - str s; - char *c; - param_t *p, *list; - -#define is_boundary(c) \ - (((c)[0] == 'b' || (c)[0] == 'B') && \ - ((c)[1] == 'o' || (c)[1] == 'O') && \ - ((c)[2] == 'u' || (c)[2] == 'U') && \ - ((c)[3] == 'n' || (c)[3] == 'N') && \ - ((c)[4] == 'd' || (c)[4] == 'D') && \ - ((c)[5] == 'a' || (c)[5] == 'A') && \ - ((c)[6] == 'r' || (c)[6] == 'R') && \ - ((c)[7] == 'y' || (c)[7] == 'Y')) - -#define boundary_param_len (sizeof("boundary")-1) + str s; + char *c; + param_t *p, *list; + +#define is_boundary(c) \ + (((c)[0] == 'b' || (c)[0] == 'B') && ((c)[1] == 'o' || (c)[1] == 'O') \ + && ((c)[2] == 'u' || (c)[2] == 'U') \ + && ((c)[3] == 'n' || (c)[3] == 'N') \ + && ((c)[4] == 'd' || (c)[4] == 'D') \ + && ((c)[5] == 'a' || (c)[5] == 'A') \ + && ((c)[6] == 'r' || (c)[6] == 'R') \ + && ((c)[7] == 'y' || (c)[7] == 'Y')) + +#define boundary_param_len (sizeof("boundary") - 1) /* get the pointer to the beginning of the parameter list */ s.s = msg->content_type->body.s; s.len = msg->content_type->body.len; c = find_not_quoted(&s, ';'); - if (!c) + if(!c) return -1; c++; s.len = s.len - (c - s.s); s.s = c; trim_leading(&s); - if (s.len <= 0) + if(s.len <= 0) return -1; /* parse the parameter list, and search for boundary */ - if (parse_params(&s, CLASS_ANY, NULL, &list)<0) + if(parse_params(&s, CLASS_ANY, NULL, &list) < 0) return -1; boundary->s = NULL; - for (p = list; p; p = p->next) - if ((p->name.len == boundary_param_len) && - is_boundary(p->name.s) - ) { + for(p = list; p; p = p->next) + if((p->name.len == boundary_param_len) && is_boundary(p->name.s)) { boundary->s = p->body.s; boundary->len = p->body.len; break; } free_params(list); - if (!boundary->s || !boundary->len) + if(!boundary->s || !boundary->len) return -1; - DBG("boundary is \"%.*s\"\n", - boundary->len, boundary->s); + DBG("boundary is \"%.*s\"\n", boundary->len, boundary->s); return 0; } @@ -95,57 +91,57 @@ static inline char *search_boundary(char *buf, char *buf_end, str *boundary) char *c; c = buf; - while (c + 2 /* -- */ + boundary->len < buf_end) { - if ((*c == '-') && (*(c+1) == '-') && - (memcmp(c+2, boundary->s, boundary->len) == 0) - ) + while(c + 2 /* -- */ + boundary->len < buf_end) { + if((*c == '-') && (*(c + 1) == '-') + && (memcmp(c + 2, boundary->s, boundary->len) == 0)) return c; /* boundary found */ /* go to the next line */ - while ((c < buf_end) && (*c != '\n')) c++; + while((c < buf_end) && (*c != '\n')) + c++; c++; } return NULL; } /*! \brief extract the body of a part from a multipart SIP msg body */ -inline static char *get_multipart_body(char *buf, - char *buf_end, - str *boundary, - int *len) +inline static char *get_multipart_body( + char *buf, char *buf_end, str *boundary, int *len) { char *beg, *end; - if (buf >= buf_end) + if(buf >= buf_end) goto error; beg = buf; - while ((*beg != '\r') && (*beg != '\n')) { - while ((beg < buf_end) && (*beg != '\n')) + while((*beg != '\r') && (*beg != '\n')) { + while((beg < buf_end) && (*beg != '\n')) beg++; beg++; - if (beg >= buf_end) + if(beg >= buf_end) goto error; } /* CRLF delimiter found, the body begins right after it */ - while ((beg < buf_end) && (*beg != '\n')) + while((beg < buf_end) && (*beg != '\n')) beg++; beg++; - if (beg >= buf_end) + if(beg >= buf_end) goto error; - if (!(end = search_boundary(beg, buf_end, boundary))) + if(!(end = search_boundary(beg, buf_end, boundary))) goto error; /* CRLF preceding the boundary belongs to the boundary and not to the body */ - if (*(end-1) == '\n') end--; - if (*(end-1) == '\r') end--; + if(*(end - 1) == '\n') + end--; + if(*(end - 1) == '\r') + end--; - if (end < beg) + if(end < beg) goto error; - *len = end-beg; + *len = end - beg; return beg; error: ERR("failed to extract the body from the multipart mime type\n"); @@ -155,7 +151,7 @@ inline static char *get_multipart_body(char *buf, /*! \brief macros from parse_hname2.c */ #define READ(val) \ -(*(val + 0) + (*(val + 1) << 8) + (*(val + 2) << 16) + (*(val + 3) << 24)) + (*(val + 0) + (*(val + 1) << 8) + (*(val + 2) << 16) + (*(val + 3) << 24)) #define LOWER_DWORD(d) ((d) | 0x20202020) @@ -163,80 +159,74 @@ inline static char *get_multipart_body(char *buf, * and sets the length of the body part. * The result can be the whole msg body, or a part of a multipart body. */ -char *get_body_part( struct sip_msg *msg, - unsigned short type, unsigned short subtype, - int *len) +char *get_body_part(struct sip_msg *msg, unsigned short type, + unsigned short subtype, int *len) { - int mime; - unsigned int umime; - char *c, *c2, *buf_end; - str boundary; + int mime; + unsigned int umime; + char *c, *c2, *buf_end; + str boundary; -#define content_type_len \ - (sizeof("Content-Type") - 1) +#define content_type_len (sizeof("Content-Type") - 1) - if ((mime = parse_content_type_hdr(msg)) <= 0) + if((mime = parse_content_type_hdr(msg)) <= 0) return NULL; - if (mime == ((type<<16)|subtype)) { + if(mime == ((type << 16) | subtype)) { /* content-type is type/subtype */ c = get_body(msg); - if (c) - *len = msg->buf+msg->len - c; + if(c) + *len = msg->buf + msg->len - c; return c; - } else if ((mime>>16) == TYPE_MULTIPART) { + } else if((mime >> 16) == TYPE_MULTIPART) { /* type is multipart/something, search for type/subtype part */ - if (get_boundary_param(msg, &boundary)) { + if(get_boundary_param(msg, &boundary)) { ERR("failed to get boundary parameter\n"); return NULL; } - if (!(c = get_body(msg))) + if(!(c = get_body(msg))) return NULL; - buf_end = msg->buf+msg->len; + buf_end = msg->buf + msg->len; /* check all the body parts delimited by the boundary value, - and search for the Content-Type HF with the given + and search for the Content-Type HF with the given type/subtype */ -next_part: - while ((c = search_boundary(c, buf_end, &boundary))) { + next_part: + while((c = search_boundary(c, buf_end, &boundary))) { /* skip boundary */ c += 2 + boundary.len; - if ((c+2 > buf_end) || - ((*c == '-') && (*(c+1) == '-')) - ) + if((c + 2 > buf_end) || ((*c == '-') && (*(c + 1) == '-'))) /* end boundary, no more body part will follow */ return NULL; /* go to the next line */ - while ((c < buf_end) && (*c != '\n')) c++; + while((c < buf_end) && (*c != '\n')) + c++; c++; - if (c >= buf_end) + if(c >= buf_end) return NULL; /* try to find the content-type header */ - while ((*c != '\r') && (*c != '\n')) { - if (c + content_type_len >= buf_end) + while((*c != '\r') && (*c != '\n')) { + if(c + content_type_len >= buf_end) return NULL; - if ((LOWER_DWORD(READ(c)) == _cont_) && - (LOWER_DWORD(READ(c+4)) == _ent__) && - (LOWER_DWORD(READ(c+8)) == _type_) - ) { + if((LOWER_DWORD(READ(c)) == _cont_) + && (LOWER_DWORD(READ(c + 4)) == _ent__) + && (LOWER_DWORD(READ(c + 8)) == _type_)) { /* Content-Type HF found */ c += content_type_len; - while ((c < buf_end) && - ((*c == ' ') || (*c == '\t')) - ) + while((c < buf_end) && ((*c == ' ') || (*c == '\t'))) c++; - if (c + 1 /* : */ >= buf_end) + if(c + 1 /* : */ >= buf_end) return NULL; - if (*c != ':') + if(*c != ':') /* not really a Content-Type HF */ goto next_hf; c++; @@ -244,17 +234,18 @@ char *get_body_part( struct sip_msg *msg, /* search the end of the header body, decode_mime_type() needs it */ c2 = c; - while (((c2 < buf_end) && (*c2 != '\n')) || - ((c2+1 < buf_end) && (*c2 == '\n') && - ((*(c2+1) == ' ') || (*(c2+1) == '\t'))) - ) + while(((c2 < buf_end) && (*c2 != '\n')) + || ((c2 + 1 < buf_end) && (*c2 == '\n') + && ((*(c2 + 1) == ' ') + || (*(c2 + 1) == '\t')))) c2++; - if (c2 >= buf_end) + if(c2 >= buf_end) return NULL; - if (*(c2-1) == '\r') c2--; + if(*(c2 - 1) == '\r') + c2--; - if (!decode_mime_type(c, c2 , &umime)) { + if(!decode_mime_type(c, c2, &umime)) { ERR("failed to decode the mime type\n"); return NULL; } @@ -262,23 +253,23 @@ char *get_body_part( struct sip_msg *msg, /* c2 points to the CRLF at the end of the line, move the pointer to the beginning of the next line */ c = c2; - if ((c < buf_end) && (*c == '\r')) c++; - if ((c < buf_end) && (*c == '\n')) c++; + if((c < buf_end) && (*c == '\r')) + c++; + if((c < buf_end) && (*c == '\n')) + c++; - if (umime != ((type<<16)|subtype)) { + if(umime != ((type << 16) | subtype)) { /* this is not the part we are looking for */ goto next_part; } /* the requested type/subtype is found! */ - return get_multipart_body(c, - buf_end, - &boundary, - len); + return get_multipart_body(c, buf_end, &boundary, len); } -next_hf: + next_hf: /* go to the next line */ - while ((c < buf_end) && (*c != '\n')) c++; + while((c < buf_end) && (*c != '\n')) + c++; c++; } /* CRLF delimiter reached, @@ -295,14 +286,14 @@ char *get_body_part( struct sip_msg *msg, * trim leading all spaces ' ' and horizontal tabs '\\t' characters. * \param buffer pointer to the beginning of the buffer * \param end_buffer pointer to the end of the buffer - * \return pointer to the first non-match character if success, + * \return pointer to the first non-match character if success, * pointer to NULL if the end_buffer is reached. */ -char *trim_leading_hts (char *buffer, char *end_buffer) +char *trim_leading_hts(char *buffer, char *end_buffer) { char *cpy_buffer = buffer; - while ((cpy_buffer < end_buffer) && - ((*cpy_buffer == ' ') || (*cpy_buffer == '\t'))) { + while((cpy_buffer < end_buffer) + && ((*cpy_buffer == ' ') || (*cpy_buffer == '\t'))) { cpy_buffer++; } @@ -319,10 +310,10 @@ char *trim_leading_hts (char *buffer, char *end_buffer) * \return pointer to the first '\\r' character if success, * pointer to NULL if the end_buffer is reached. */ -char *trim_leading_e_r (char *buffer, char *end_buffer) +char *trim_leading_e_r(char *buffer, char *end_buffer) { char *cpy_buffer = buffer; - while ((cpy_buffer < end_buffer) && (*cpy_buffer != '\r')) { + while((cpy_buffer < end_buffer) && (*cpy_buffer != '\r')) { cpy_buffer++; } return ((cpy_buffer < end_buffer) ? cpy_buffer : NULL); @@ -331,7 +322,7 @@ char *trim_leading_e_r (char *buffer, char *end_buffer) /** * \brief part_multipart_headers_cmp - * + * * trim leading characters until get a '\\r'. * \param buffer pointer to the beginning of the headers in a part of the multipart body * \param end_buffer pointer to the end of the headers in the multipart body @@ -345,12 +336,9 @@ char *trim_leading_e_r (char *buffer, char *end_buffer) * -- Content-Length that matches content_length. (if Content-Length enabled) * - false, if any of them doesn't match. */ -int part_multipart_headers_cmp (char *buffer, - char *end_buffer, - unsigned short content_type, - unsigned short content_subtype, - char *content_id, - char *content_length) +int part_multipart_headers_cmp(char *buffer, char *end_buffer, + unsigned short content_type, unsigned short content_subtype, + char *content_id, char *content_length) { int error = 0; char *error_msg = NULL; @@ -363,48 +351,49 @@ int part_multipart_headers_cmp (char *buffer, unsigned int umime; int found = 0; - int found_content_type = 0; - int found_content_id = 0; + int found_content_type = 0; + int found_content_id = 0; int found_content_length = 0; - if ((buffer == NULL) || (end_buffer == NULL)) { + if((buffer == NULL) || (end_buffer == NULL)) { error = -1; error_msg = "buffer and/or end_buffer are NULL"; } else { cpy_c = buffer; cpy_d = end_buffer; - if ((content_type == 0) && (content_subtype == 0)) { - found_content_type = 1; + if((content_type == 0) && (content_subtype == 0)) { + found_content_type = 1; } - if (content_id == NULL) { + if(content_id == NULL) { found_content_id = 1; } - if (content_length == NULL) { + if(content_length == NULL) { found_content_length = 1; } found = found_content_type * found_content_id * found_content_length; - while ((!found) && (!error) && (cpy_c < cpy_d)) { - if ((cpy_c + 8) < cpy_d) { - if ( (LOWER_DWORD(READ(cpy_c)) == _cont_) - && (LOWER_DWORD(READ(cpy_c + 4)) == _ent__) ) { + while((!found) && (!error) && (cpy_c < cpy_d)) { + if((cpy_c + 8) < cpy_d) { + if((LOWER_DWORD(READ(cpy_c)) == _cont_) + && (LOWER_DWORD(READ(cpy_c + 4)) == _ent__)) { cpy_c += 8; - if ( (!found_content_type) - && ((cpy_c + 5) < cpy_d) + if((!found_content_type) && ((cpy_c + 5) < cpy_d) && ((*(cpy_c + 0) == 't') || (*(cpy_c + 0) == 'T')) && ((*(cpy_c + 1) == 'y') || (*(cpy_c + 1) == 'Y')) && ((*(cpy_c + 2) == 'p') || (*(cpy_c + 2) == 'P')) && ((*(cpy_c + 3) == 'e') || (*(cpy_c + 3) == 'E')) - && (*(cpy_c + 4) == ':') ) { + && (*(cpy_c + 4) == ':')) { cpy_c += 5; /* value_ has the content of the header */ value_ini = trim_leading_hts(cpy_c, cpy_d); value_fin = trim_leading_e_r(cpy_c, cpy_d); - if ((value_ini != NULL) && (value_fin != NULL)) { + if((value_ini != NULL) && (value_fin != NULL)) { cpy_c = value_fin; - if (decode_mime_type(value_ini, value_fin, &umime)) { - if (umime == ((content_type<<16)|content_subtype)) { + if(decode_mime_type(value_ini, value_fin, &umime)) { + if(umime + == ((content_type << 16) + | content_subtype)) { found_content_type = 1; } else { error = -2; @@ -416,19 +405,24 @@ int part_multipart_headers_cmp (char *buffer, } } else { error = -4; - error_msg = "Failed to perform trim_leading_hts || trim_leading_e_r"; + error_msg = "Failed to perform trim_leading_hts || " + "trim_leading_e_r"; } - } else if( (!found_content_id) && ((cpy_c + 3) < cpy_d) - && ((*(cpy_c + 0) == 'i') || (*(cpy_c + 0) == 'I')) - && ((*(cpy_c + 1) == 'd') || (*(cpy_c + 1) == 'D')) - && (*(cpy_c + 2) == ':') ) { + } else if((!found_content_id) && ((cpy_c + 3) < cpy_d) + && ((*(cpy_c + 0) == 'i') + || (*(cpy_c + 0) == 'I')) + && ((*(cpy_c + 1) == 'd') + || (*(cpy_c + 1) == 'D')) + && (*(cpy_c + 2) == ':')) { cpy_c += 3; /* value_ has the content of the header */ value_ini = trim_leading_hts(cpy_c, cpy_d); value_fin = trim_leading_e_r(cpy_c, cpy_d); - if ((value_ini != NULL) && (value_fin != NULL)) { + if((value_ini != NULL) && (value_fin != NULL)) { cpy_c = value_fin; - if (strncmp(content_id, value_ini, value_fin-value_ini) == 0) { + if(strncmp(content_id, value_ini, + value_fin - value_ini) + == 0) { found_content_id = 1; } else { error = -5; @@ -436,23 +430,32 @@ int part_multipart_headers_cmp (char *buffer, } } else { error = -6; - error_msg = "Failed to perform trim_leading_hts || trim_leading_e_r"; + error_msg = "Failed to perform trim_leading_hts || " + "trim_leading_e_r"; } - } else if( (!found_content_length) && ((cpy_c + 7) < cpy_d) - && ((*(cpy_c + 0) == 'l') || (*(cpy_c + 0) == 'L')) - && ((*(cpy_c + 1) == 'e') || (*(cpy_c + 1) == 'E')) - && ((*(cpy_c + 2) == 'n') || (*(cpy_c + 2) == 'N')) - && ((*(cpy_c + 3) == 'g') || (*(cpy_c + 3) == 'G')) - && ((*(cpy_c + 4) == 't') || (*(cpy_c + 4) == 'T')) - && ((*(cpy_c + 5) == 'h') || (*(cpy_c + 5) == 'H')) - && (*(cpy_c + 6) == ':') ) { + } else if((!found_content_length) && ((cpy_c + 7) < cpy_d) + && ((*(cpy_c + 0) == 'l') + || (*(cpy_c + 0) == 'L')) + && ((*(cpy_c + 1) == 'e') + || (*(cpy_c + 1) == 'E')) + && ((*(cpy_c + 2) == 'n') + || (*(cpy_c + 2) == 'N')) + && ((*(cpy_c + 3) == 'g') + || (*(cpy_c + 3) == 'G')) + && ((*(cpy_c + 4) == 't') + || (*(cpy_c + 4) == 'T')) + && ((*(cpy_c + 5) == 'h') + || (*(cpy_c + 5) == 'H')) + && (*(cpy_c + 6) == ':')) { cpy_c += 7; /* value_ has the content of the header */ value_ini = trim_leading_hts(cpy_c, cpy_d); value_fin = trim_leading_e_r(cpy_c, cpy_d); - if ((value_ini != NULL) && (value_fin != NULL)) { + if((value_ini != NULL) && (value_fin != NULL)) { cpy_c = value_fin; - if (strncmp(content_length, value_ini, value_fin-value_ini) == 0) { + if(strncmp(content_length, value_ini, + value_fin - value_ini) + == 0) { found_content_length = 1; } else { error = -7; @@ -460,7 +463,8 @@ int part_multipart_headers_cmp (char *buffer, } } else { error = -8; - error_msg = "Failed to perform trim_leading_hts || trim_leading_e_r"; + error_msg = "Failed to perform trim_leading_hts || " + "trim_leading_e_r"; } } else { /* Next characters don't match "Type:" or "ID:" or "Length:" OR @@ -479,13 +483,14 @@ int part_multipart_headers_cmp (char *buffer, error = -9; error_msg = "Unsuccessfully reached the end of the buffer"; } - found = found_content_type * found_content_id * found_content_length; - if ((!found) && (!error)) { + found = found_content_type * found_content_id + * found_content_length; + if((!found) && (!error)) { value_fin = trim_leading_e_r(cpy_c, cpy_d); - if (value_fin != NULL) { + if(value_fin != NULL) { cpy_c = value_fin; - if ((cpy_c + 1) < cpy_d) { - if ((*cpy_c == '\r') && (*(cpy_c + 1) == '\n')) { + if((cpy_c + 1) < cpy_d) { + if((*cpy_c == '\r') && (*(cpy_c + 1) == '\n')) { cpy_c++; cpy_c++; } else { @@ -504,11 +509,12 @@ int part_multipart_headers_cmp (char *buffer, } /* End main while loop */ } - if (error < 0) { - if ((error == -2) || (error == -9)) { + if(error < 0) { + if((error == -2) || (error == -9)) { LM_DBG("result code: \"%i\" text: \"%s\".\n", error, error_msg); } else { - LM_ERR("error code: \"%i\" error text: \"%s\".\n", error, error_msg); + LM_ERR("error code: \"%i\" error text: \"%s\".\n", error, + error_msg); } return 0; } else { @@ -521,7 +527,7 @@ int part_multipart_headers_cmp (char *buffer, * * Filters the multipart part from a given SIP message which matches the * Content-Type && || Content-ID && || Content-Length - * + * * \param msg SIP message * \param content_type if NULL Content-Type: disabled in the search * \param content_subtype if NULL Content-Subtype: disabled in the search @@ -530,47 +536,45 @@ int part_multipart_headers_cmp (char *buffer, * \param len Length of the multipart message returned * \return pointer to the multipart if success, NULL, if none of the multiparts match */ -char *get_body_part_by_filter(struct sip_msg *msg, - unsigned short content_type, - unsigned short content_subtype, - char *content_id, - char *content_length, - int *len) +char *get_body_part_by_filter(struct sip_msg *msg, unsigned short content_type, + unsigned short content_subtype, char *content_id, char *content_length, + int *len) { int mime; - char*c, *d, *buf_end; + char *c, *d, *buf_end; str boundary; - if ((mime = parse_content_type_hdr(msg)) <= 0) + if((mime = parse_content_type_hdr(msg)) <= 0) return NULL; - if ((mime>>16) == TYPE_MULTIPART) { + if((mime >> 16) == TYPE_MULTIPART) { /* type is multipart/something, search for type/subtype part */ - if (get_boundary_param(msg, &boundary)) { + if(get_boundary_param(msg, &boundary)) { ERR("failed to get boundary parameter\n"); return NULL; } - if (!(c = get_body(msg))) + if(!(c = get_body(msg))) return NULL; - buf_end = msg->buf+msg->len; + buf_end = msg->buf + msg->len; - while ((c = search_boundary(c, buf_end, &boundary))) { + while((c = search_boundary(c, buf_end, &boundary))) { /* skip boundary */ c += 2 + boundary.len; - if ((c+2 > buf_end) || ((*c == '-') && (*(c+1) == '-')) ) + if((c + 2 > buf_end) || ((*c == '-') && (*(c + 1) == '-'))) /* end boundary, no more body part will follow */ return NULL; /* go to the next line */ - while ((c < buf_end) && (*c != '\n')) c++; + while((c < buf_end) && (*c != '\n')) + c++; c++; - if (c >= buf_end) + if(c >= buf_end) return NULL; d = get_multipart_body(c, buf_end, &boundary, len); - if (part_multipart_headers_cmp(c, d, content_type, content_subtype, - content_id, content_length)) { + if(part_multipart_headers_cmp(c, d, content_type, content_subtype, + content_id, content_length)) { return d; } } diff --git a/src/core/parser/parse_body.h b/src/core/parser/parse_body.h index 4b82e3a7c21..f5e28c92f8c 100644 --- a/src/core/parser/parse_body.h +++ b/src/core/parser/parse_body.h @@ -13,8 +13,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ @@ -34,20 +34,16 @@ * and sets the length. * The result can be the whole msg body, or a part of a multipart body. */ -char *get_body_part( struct sip_msg *msg, - unsigned short type, unsigned short subtype, - int *len); +char *get_body_part(struct sip_msg *msg, unsigned short type, + unsigned short subtype, int *len); /*! \brief Returns the pointer within the msg body to the given part matching * type/subtype, content id or content length. It sets the length. * The result can be the whole msg body, or a part of a multipart body. */ -char *get_body_part_by_filter(struct sip_msg *msg, - unsigned short content_type, - unsigned short content_subtype, - char *content_id, - char *content_length, - int *len); +char *get_body_part_by_filter(struct sip_msg *msg, unsigned short content_type, + unsigned short content_subtype, char *content_id, char *content_length, + int *len); #endif /* PARSE_BODY_H */ diff --git a/src/core/parser/parse_content.c b/src/core/parser/parse_content.c index d95d23beccb..e33169d8154 100644 --- a/src/core/parser/parse_content.c +++ b/src/core/parser/parse_content.c @@ -37,242 +37,245 @@ #include "parse_content.h" -#define is_mime_char(_c_) \ - (isalnum((int)_c_) || (_c_)=='-' || (_c_)=='+' || (_c_)=='.' || (_c_)=='_' \ - || (_c_)=='!' || (_c_)=='%' || (_c_)=='*' \ - || (_c_)=='\'' || (_c_)=='`' || (_c_)=='~') -#define is_char_equal(_c_,_cs_) \ - ( (isalpha((int)_c_)?(((_c_)|0x20)==(_cs_)):((_c_)==(_cs_)))==1 ) +#define is_mime_char(_c_) \ + (isalnum((int)_c_) || (_c_) == '-' || (_c_) == '+' || (_c_) == '.' \ + || (_c_) == '_' || (_c_) == '!' || (_c_) == '%' || (_c_) == '*' \ + || (_c_) == '\'' || (_c_) == '`' || (_c_) == '~') +#define is_char_equal(_c_, _cs_) \ + ((isalpha((int)_c_) ? (((_c_) | 0x20) == (_cs_)) : ((_c_) == (_cs_))) == 1) /*! \brief * Node of the type's tree; this tree contains all the known types; */ -typedef struct type_node_s { - char c; /*!< char contained by this node */ - unsigned char final; /*!< says what mime type/subtype was detected +typedef struct type_node_s +{ + char c; /*!< char contained by this node */ + unsigned char final; /*!< says what mime type/subtype was detected *!< if string ends at this node */ - unsigned char nr_sons; /*!< the number of sub-nodes */ - int next; /*!< the next sibling node */ -}type_node_t; + unsigned char nr_sons; /*!< the number of sub-nodes */ + int next; /*!< the next sibling node */ +} type_node_t; static type_node_t type_tree[] = { - {'t',TYPE_UNKNOWN,1,4}, /* 0 */ - {'e',TYPE_UNKNOWN,1,-1}, - {'x',TYPE_UNKNOWN,1,-1}, - {'t',TYPE_TEXT,0,-1}, - {'m',TYPE_UNKNOWN,2,19}, /* 4 */ - {'e',TYPE_UNKNOWN,1,11}, /* 5 */ - {'s',TYPE_UNKNOWN,1,-1}, - {'s',TYPE_UNKNOWN,1,-1}, - {'a',TYPE_UNKNOWN,1,-1}, - {'g',TYPE_UNKNOWN,1,-1}, - {'e',TYPE_MESSAGE,0,-1}, - {'u',TYPE_UNKNOWN,1,-1}, /* 11 */ - {'l',TYPE_UNKNOWN,1,-1}, - {'t',TYPE_UNKNOWN,1,-1}, - {'i',TYPE_UNKNOWN,1,-1}, - {'p',TYPE_UNKNOWN,1,-1}, - {'a',TYPE_UNKNOWN,1,-1}, - {'r',TYPE_UNKNOWN,1,-1}, - {'t',TYPE_MULTIPART,0,-1}, - {'a',TYPE_UNKNOWN,1,-1}, /* 19 */ - {'p',TYPE_UNKNOWN,1,-1}, - {'p',TYPE_UNKNOWN,1,-1}, - {'l',TYPE_UNKNOWN,1,-1}, - {'i',TYPE_UNKNOWN,1,-1}, - {'c',TYPE_UNKNOWN,1,-1}, - {'a',TYPE_UNKNOWN,1,-1}, - {'t',TYPE_UNKNOWN,1,-1}, - {'i',TYPE_UNKNOWN,1,-1}, - {'o',TYPE_UNKNOWN,1,-1}, - {'n',TYPE_APPLICATION,0,-1}, - }; + {'t', TYPE_UNKNOWN, 1, 4}, /* 0 */ + {'e', TYPE_UNKNOWN, 1, -1}, + {'x', TYPE_UNKNOWN, 1, -1}, + {'t', TYPE_TEXT, 0, -1}, + {'m', TYPE_UNKNOWN, 2, 19}, /* 4 */ + {'e', TYPE_UNKNOWN, 1, 11}, /* 5 */ + {'s', TYPE_UNKNOWN, 1, -1}, + {'s', TYPE_UNKNOWN, 1, -1}, + {'a', TYPE_UNKNOWN, 1, -1}, + {'g', TYPE_UNKNOWN, 1, -1}, + {'e', TYPE_MESSAGE, 0, -1}, + {'u', TYPE_UNKNOWN, 1, -1}, /* 11 */ + {'l', TYPE_UNKNOWN, 1, -1}, + {'t', TYPE_UNKNOWN, 1, -1}, + {'i', TYPE_UNKNOWN, 1, -1}, + {'p', TYPE_UNKNOWN, 1, -1}, + {'a', TYPE_UNKNOWN, 1, -1}, + {'r', TYPE_UNKNOWN, 1, -1}, + {'t', TYPE_MULTIPART, 0, -1}, + {'a', TYPE_UNKNOWN, 1, -1}, /* 19 */ + {'p', TYPE_UNKNOWN, 1, -1}, + {'p', TYPE_UNKNOWN, 1, -1}, + {'l', TYPE_UNKNOWN, 1, -1}, + {'i', TYPE_UNKNOWN, 1, -1}, + {'c', TYPE_UNKNOWN, 1, -1}, + {'a', TYPE_UNKNOWN, 1, -1}, + {'t', TYPE_UNKNOWN, 1, -1}, + {'i', TYPE_UNKNOWN, 1, -1}, + {'o', TYPE_UNKNOWN, 1, -1}, + {'n', TYPE_APPLICATION, 0, -1}, +}; static type_node_t subtype_tree[] = { - {'p',SUBTYPE_UNKNOWN,2,13}, - {'l',SUBTYPE_UNKNOWN,1,5}, - {'a',SUBTYPE_UNKNOWN,1,-1}, - {'i',SUBTYPE_UNKNOWN,1,-1}, - {'n',SUBTYPE_PLAIN,0,-1}, - {'i',SUBTYPE_UNKNOWN,1,-1}, /* 5 */ - {'d',SUBTYPE_UNKNOWN,1,-1}, - {'f',SUBTYPE_UNKNOWN,1,-1}, - {'+',TYPE_UNKNOWN,1,-1}, - {'x',TYPE_UNKNOWN,1,-1}, - {'m',TYPE_UNKNOWN,1,-1}, - {'l',SUBTYPE_PIDFXML,0,-1}, - {'l',SUBTYPE_PIDFXML,0,-1}, - {'s',SUBTYPE_UNKNOWN,1,16}, /* 13 */ - {'d',SUBTYPE_UNKNOWN,1,-1}, - {'p',SUBTYPE_SDP,0,-1}, - {'c',SUBTYPE_UNKNOWN,1,34}, /* 16 */ - {'p',SUBTYPE_UNKNOWN,2,-1}, - {'i',SUBTYPE_UNKNOWN,1,29}, - {'m',SUBTYPE_CPIM,1,-1}, - {'-',SUBTYPE_UNKNOWN,1,-1}, - {'p',SUBTYPE_UNKNOWN,1,-1}, - {'i',SUBTYPE_UNKNOWN,1,-1}, - {'d',SUBTYPE_UNKNOWN,1,-1}, - {'f',SUBTYPE_UNKNOWN,1,-1}, - {'+',SUBTYPE_UNKNOWN,1,-1}, - {'x',SUBTYPE_UNKNOWN,1,-1}, - {'m',SUBTYPE_UNKNOWN,1,-1}, - {'l',SUBTYPE_CPIM_PIDFXML,0,-1}, - {'l',SUBTYPE_UNKNOWN,1,-1}, /* 29 */ - {'+',TYPE_UNKNOWN,1,-1}, - {'x',TYPE_UNKNOWN,1,-1}, - {'m',TYPE_UNKNOWN,1,-1}, - {'l',SUBTYPE_CPLXML,0,-1}, - {'r',SUBTYPE_UNKNOWN,2,48}, /* 34 */ - {'l',SUBTYPE_UNKNOWN,1,42},/* 35 */ - {'m',SUBTYPE_UNKNOWN,1,-1}, - {'i',SUBTYPE_UNKNOWN,1,-1}, - {'+',TYPE_UNKNOWN,1,-1}, - {'x',TYPE_UNKNOWN,1,-1}, - {'m',TYPE_UNKNOWN,1,-1}, - {'l',SUBTYPE_RLMIXML,0,-1}, - {'e',SUBTYPE_UNKNOWN,1,-1}, /* 42 */ - {'l',SUBTYPE_UNKNOWN,1,-1}, - {'a',SUBTYPE_UNKNOWN,1,-1}, - {'t',SUBTYPE_UNKNOWN,1,-1}, - {'e',SUBTYPE_UNKNOWN,1,-1}, - {'d',SUBTYPE_RELATED,0,-1}, - {'l',SUBTYPE_UNKNOWN,1,57}, /* 48 */ - {'p',SUBTYPE_UNKNOWN,1,-1}, - {'i',SUBTYPE_UNKNOWN,1,-1}, - {'d',SUBTYPE_UNKNOWN,1,-1}, - {'f',SUBTYPE_UNKNOWN,1,-1}, - {'+',SUBTYPE_UNKNOWN,1,-1}, - {'x',SUBTYPE_UNKNOWN,1,-1}, - {'m',SUBTYPE_UNKNOWN,1,-1}, - {'l',SUBTYPE_LPIDFXML,0,-1}, - {'w',SUBTYPE_UNKNOWN,1,72}, /* 57 */ - {'a',SUBTYPE_UNKNOWN,1,-1}, - {'t',SUBTYPE_UNKNOWN,1,-1}, - {'c',SUBTYPE_UNKNOWN,1,-1}, - {'h',SUBTYPE_UNKNOWN,1,-1}, - {'e',SUBTYPE_UNKNOWN,1,-1}, - {'r',SUBTYPE_UNKNOWN,1,-1}, - {'i',TYPE_UNKNOWN,1,-1}, - {'n',TYPE_UNKNOWN,1,-1}, - {'f',TYPE_UNKNOWN,1,-1}, - {'o',TYPE_UNKNOWN,1,-1}, - {'+',TYPE_UNKNOWN,1,-1}, - {'x',TYPE_UNKNOWN,1,-1}, - {'m',TYPE_UNKNOWN,1,-1}, - {'l',SUBTYPE_WATCHERINFOXML,0,-1}, - {'x',SUBTYPE_UNKNOWN,2,94}, /* 72 */ - {'p',SUBTYPE_UNKNOWN,1,81}, /* 73 */ - {'i',SUBTYPE_UNKNOWN,1,-1}, - {'d',SUBTYPE_UNKNOWN,1,-1}, - {'f',SUBTYPE_UNKNOWN,1,-1}, - {'+',SUBTYPE_UNKNOWN,1,-1}, - {'x',SUBTYPE_UNKNOWN,1,-1}, - {'m',SUBTYPE_UNKNOWN,1,-1}, - {'l',SUBTYPE_XPIDFXML,0,-1}, - {'m',SUBTYPE_UNKNOWN,1,-1}, /* 81 */ - {'l',SUBTYPE_UNKNOWN,1,-1}, - {'+',SUBTYPE_UNKNOWN,1,-1}, - {'m',SUBTYPE_UNKNOWN,1,-1}, - {'s',SUBTYPE_UNKNOWN,1,-1}, - {'r',SUBTYPE_UNKNOWN,1,-1}, - {'t',SUBTYPE_UNKNOWN,1,-1}, - {'c',SUBTYPE_UNKNOWN,1,-1}, - {'.',SUBTYPE_UNKNOWN,1,-1}, - {'p',SUBTYPE_UNKNOWN,1,-1}, - {'i',SUBTYPE_UNKNOWN,1,-1}, - {'d',SUBTYPE_UNKNOWN,1,-1}, - {'f',SUBTYPE_XML_MSRTC_PIDF,0,-1}, - {'e',SUBTYPE_UNKNOWN,1,107}, /* 94 */ - {'x',SUBTYPE_UNKNOWN,1,-1}, - {'t',SUBTYPE_UNKNOWN,1,-1}, - {'e',SUBTYPE_UNKNOWN,1,-1}, - {'r',SUBTYPE_UNKNOWN,1,-1}, - {'n',SUBTYPE_UNKNOWN,1,-1}, - {'a',SUBTYPE_UNKNOWN,1,-1}, - {'l',SUBTYPE_UNKNOWN,1,-1}, - {'-',SUBTYPE_UNKNOWN,1,-1}, - {'b',SUBTYPE_UNKNOWN,1,-1}, - {'o',SUBTYPE_UNKNOWN,1,-1}, - {'d',SUBTYPE_UNKNOWN,1,-1}, - {'y',SUBTYPE_EXTERNAL_BODY,0,-1}, - {'m',SUBTYPE_UNKNOWN,1,112}, /* 107 */ - {'i',SUBTYPE_UNKNOWN,1,-1}, - {'x',SUBTYPE_UNKNOWN,1,-1}, - {'e',SUBTYPE_UNKNOWN,1,-1}, - {'d',SUBTYPE_MIXED,0,-1}, - {'i',SUBTYPE_UNKNOWN,1,-1}, /* 112 */ - {'s',SUBTYPE_UNKNOWN,1,-1}, - {'u',SUBTYPE_UNKNOWN,1,-1}, - {'p',SUBTYPE_ISUP,0,-1}, + {'p', SUBTYPE_UNKNOWN, 2, 13}, + {'l', SUBTYPE_UNKNOWN, 1, 5}, + {'a', SUBTYPE_UNKNOWN, 1, -1}, + {'i', SUBTYPE_UNKNOWN, 1, -1}, + {'n', SUBTYPE_PLAIN, 0, -1}, + {'i', SUBTYPE_UNKNOWN, 1, -1}, /* 5 */ + {'d', SUBTYPE_UNKNOWN, 1, -1}, + {'f', SUBTYPE_UNKNOWN, 1, -1}, + {'+', TYPE_UNKNOWN, 1, -1}, + {'x', TYPE_UNKNOWN, 1, -1}, + {'m', TYPE_UNKNOWN, 1, -1}, + {'l', SUBTYPE_PIDFXML, 0, -1}, + {'l', SUBTYPE_PIDFXML, 0, -1}, + {'s', SUBTYPE_UNKNOWN, 1, 16}, /* 13 */ + {'d', SUBTYPE_UNKNOWN, 1, -1}, + {'p', SUBTYPE_SDP, 0, -1}, + {'c', SUBTYPE_UNKNOWN, 1, 34}, /* 16 */ + {'p', SUBTYPE_UNKNOWN, 2, -1}, + {'i', SUBTYPE_UNKNOWN, 1, 29}, + {'m', SUBTYPE_CPIM, 1, -1}, + {'-', SUBTYPE_UNKNOWN, 1, -1}, + {'p', SUBTYPE_UNKNOWN, 1, -1}, + {'i', SUBTYPE_UNKNOWN, 1, -1}, + {'d', SUBTYPE_UNKNOWN, 1, -1}, + {'f', SUBTYPE_UNKNOWN, 1, -1}, + {'+', SUBTYPE_UNKNOWN, 1, -1}, + {'x', SUBTYPE_UNKNOWN, 1, -1}, + {'m', SUBTYPE_UNKNOWN, 1, -1}, + {'l', SUBTYPE_CPIM_PIDFXML, 0, -1}, + {'l', SUBTYPE_UNKNOWN, 1, -1}, /* 29 */ + {'+', TYPE_UNKNOWN, 1, -1}, + {'x', TYPE_UNKNOWN, 1, -1}, + {'m', TYPE_UNKNOWN, 1, -1}, + {'l', SUBTYPE_CPLXML, 0, -1}, + {'r', SUBTYPE_UNKNOWN, 2, 48}, /* 34 */ + {'l', SUBTYPE_UNKNOWN, 1, 42}, /* 35 */ + {'m', SUBTYPE_UNKNOWN, 1, -1}, + {'i', SUBTYPE_UNKNOWN, 1, -1}, + {'+', TYPE_UNKNOWN, 1, -1}, + {'x', TYPE_UNKNOWN, 1, -1}, + {'m', TYPE_UNKNOWN, 1, -1}, + {'l', SUBTYPE_RLMIXML, 0, -1}, + {'e', SUBTYPE_UNKNOWN, 1, -1}, /* 42 */ + {'l', SUBTYPE_UNKNOWN, 1, -1}, + {'a', SUBTYPE_UNKNOWN, 1, -1}, + {'t', SUBTYPE_UNKNOWN, 1, -1}, + {'e', SUBTYPE_UNKNOWN, 1, -1}, + {'d', SUBTYPE_RELATED, 0, -1}, + {'l', SUBTYPE_UNKNOWN, 1, 57}, /* 48 */ + {'p', SUBTYPE_UNKNOWN, 1, -1}, + {'i', SUBTYPE_UNKNOWN, 1, -1}, + {'d', SUBTYPE_UNKNOWN, 1, -1}, + {'f', SUBTYPE_UNKNOWN, 1, -1}, + {'+', SUBTYPE_UNKNOWN, 1, -1}, + {'x', SUBTYPE_UNKNOWN, 1, -1}, + {'m', SUBTYPE_UNKNOWN, 1, -1}, + {'l', SUBTYPE_LPIDFXML, 0, -1}, + {'w', SUBTYPE_UNKNOWN, 1, 72}, /* 57 */ + {'a', SUBTYPE_UNKNOWN, 1, -1}, + {'t', SUBTYPE_UNKNOWN, 1, -1}, + {'c', SUBTYPE_UNKNOWN, 1, -1}, + {'h', SUBTYPE_UNKNOWN, 1, -1}, + {'e', SUBTYPE_UNKNOWN, 1, -1}, + {'r', SUBTYPE_UNKNOWN, 1, -1}, + {'i', TYPE_UNKNOWN, 1, -1}, + {'n', TYPE_UNKNOWN, 1, -1}, + {'f', TYPE_UNKNOWN, 1, -1}, + {'o', TYPE_UNKNOWN, 1, -1}, + {'+', TYPE_UNKNOWN, 1, -1}, + {'x', TYPE_UNKNOWN, 1, -1}, + {'m', TYPE_UNKNOWN, 1, -1}, + {'l', SUBTYPE_WATCHERINFOXML, 0, -1}, + {'x', SUBTYPE_UNKNOWN, 2, 94}, /* 72 */ + {'p', SUBTYPE_UNKNOWN, 1, 81}, /* 73 */ + {'i', SUBTYPE_UNKNOWN, 1, -1}, + {'d', SUBTYPE_UNKNOWN, 1, -1}, + {'f', SUBTYPE_UNKNOWN, 1, -1}, + {'+', SUBTYPE_UNKNOWN, 1, -1}, + {'x', SUBTYPE_UNKNOWN, 1, -1}, + {'m', SUBTYPE_UNKNOWN, 1, -1}, + {'l', SUBTYPE_XPIDFXML, 0, -1}, + {'m', SUBTYPE_UNKNOWN, 1, -1}, /* 81 */ + {'l', SUBTYPE_UNKNOWN, 1, -1}, + {'+', SUBTYPE_UNKNOWN, 1, -1}, + {'m', SUBTYPE_UNKNOWN, 1, -1}, + {'s', SUBTYPE_UNKNOWN, 1, -1}, + {'r', SUBTYPE_UNKNOWN, 1, -1}, + {'t', SUBTYPE_UNKNOWN, 1, -1}, + {'c', SUBTYPE_UNKNOWN, 1, -1}, + {'.', SUBTYPE_UNKNOWN, 1, -1}, + {'p', SUBTYPE_UNKNOWN, 1, -1}, + {'i', SUBTYPE_UNKNOWN, 1, -1}, + {'d', SUBTYPE_UNKNOWN, 1, -1}, + {'f', SUBTYPE_XML_MSRTC_PIDF, 0, -1}, + {'e', SUBTYPE_UNKNOWN, 1, 107}, /* 94 */ + {'x', SUBTYPE_UNKNOWN, 1, -1}, + {'t', SUBTYPE_UNKNOWN, 1, -1}, + {'e', SUBTYPE_UNKNOWN, 1, -1}, + {'r', SUBTYPE_UNKNOWN, 1, -1}, + {'n', SUBTYPE_UNKNOWN, 1, -1}, + {'a', SUBTYPE_UNKNOWN, 1, -1}, + {'l', SUBTYPE_UNKNOWN, 1, -1}, + {'-', SUBTYPE_UNKNOWN, 1, -1}, + {'b', SUBTYPE_UNKNOWN, 1, -1}, + {'o', SUBTYPE_UNKNOWN, 1, -1}, + {'d', SUBTYPE_UNKNOWN, 1, -1}, + {'y', SUBTYPE_EXTERNAL_BODY, 0, -1}, + {'m', SUBTYPE_UNKNOWN, 1, 112}, /* 107 */ + {'i', SUBTYPE_UNKNOWN, 1, -1}, + {'x', SUBTYPE_UNKNOWN, 1, -1}, + {'e', SUBTYPE_UNKNOWN, 1, -1}, + {'d', SUBTYPE_MIXED, 0, -1}, + {'i', SUBTYPE_UNKNOWN, 1, -1}, /* 112 */ + {'s', SUBTYPE_UNKNOWN, 1, -1}, + {'u', SUBTYPE_UNKNOWN, 1, -1}, + {'p', SUBTYPE_ISUP, 0, -1}, }; - -char* parse_content_length(char* const buffer, const char* const end, - int* const length) +char *parse_content_length( + char *const buffer, const char *const end, int *const length) { int number; char *p; - int size; + int size; p = buffer; - if(buffer>=end) { + if(buffer >= end) { LM_ERR("empty input buffer: %p - %p\n", buffer, end); goto error; } /* search the beginning of the number */ - while ( p='0' && *p<='9') { - if(number >= INT_MAX/10) { + while(p < end && *p >= '0' && *p <= '9') { + if(number >= INT_MAX / 10) { LM_ERR("content length value is too large\n"); goto error; } - number = number*10 + ((*p) - '0'); - size ++; + number = number * 10 + ((*p) - '0'); + size++; p++; } - if (p==end || size==0) + if(p == end || size == 0) goto error; do { /* only spaces till the end-of-header */ - while (p eat everything to * the end or to the first ',' */ - if ( p>16==TYPE_ALL && ((*mime_type)&0x00ff)!=SUBTYPE_ALL) { + if((*mime_type) >> 16 == TYPE_ALL + && ((*mime_type) & 0x00ff) != SUBTYPE_ALL) { LM_ERR("invalid mime format found " - " <*/submime> in [%.*s]!!\n", (int)(end-start), start); + " <*/submime> in [%.*s]!!\n", + (int)(end - start), start); return 0; } return p; error: LM_ERR("parse error near in [%.*s] char" - "[%d][%c] offset=%d\n", (int)(end-start),start,*p,*p,(int)(p-start)); + "[%d][%c] offset=%d\n", + (int)(end - start), start, *p, *p, (int)(p - start)); return 0; } - /*! \brief * \return * - > 0 mime found * - = 0 hdr not found * - =-1 error */ -int parse_content_type_hdr(struct sip_msg* const msg) +int parse_content_type_hdr(struct sip_msg *const msg) { char *end; const char *ret; - unsigned int mime; + unsigned int mime; /* is the header already found? */ - if ( msg->content_type==0 ) { + if(msg->content_type == 0) { /* if not, found it */ - if ( parse_headers(msg, HDR_CONTENTTYPE_F, 0)==-1) + if(parse_headers(msg, HDR_CONTENTTYPE_F, 0) == -1) goto error; - if ( msg->content_type==0 ) { + if(msg->content_type == 0) { LM_DBG("missing Content-Type header\n"); return 0; } } /* maybe the header is already parsed! */ - if ( msg->content_type->parsed!=0) + if(msg->content_type->parsed != 0) return get_content_type(msg); /* it seams we have to parse it! :-( */ end = msg->content_type->body.s + msg->content_type->body.len; - ret = decode_mime_type(msg->content_type->body.s, end , &mime); - if (ret==0) + ret = decode_mime_type(msg->content_type->body.s, end, &mime); + if(ret == 0) goto error; - if (ret!=end) { + if(ret != end) { LM_ERR("Content-Type hdr contains more than one mime type!\n"); goto error; } - if ((mime&0x00ff)==SUBTYPE_ALL || (mime>>16)==TYPE_ALL) { + if((mime & 0x00ff) == SUBTYPE_ALL || (mime >> 16) == TYPE_ALL) { LM_ERR("invalid mime with wildcard '*' in Content-Type hdr!\n"); goto error; } - msg->content_type->parsed = (void*)(unsigned long)mime; + msg->content_type->parsed = (void *)(unsigned long)mime; return mime; error: return -1; } -int parse_accept_body(struct hdr_field* const hdr) +int parse_accept_body(struct hdr_field *const hdr) { static unsigned int mimes[MAX_MIMES_NR]; int nr_mimes; @@ -459,35 +469,37 @@ int parse_accept_body(struct hdr_field* const hdr) char *end; char *ret; - if (!hdr) return -1; + if(!hdr) + return -1; /* maybe the header is already parsed! */ - if (hdr->parsed!=0) return 1; + if(hdr->parsed != 0) + return 1; /* it seams we have to parse it! :-( */ ret = hdr->body.s; end = ret + hdr->body.len; nr_mimes = 0; - while (1){ - ret = decode_mime_type(ret, end , &mime); - if (ret==0) + while(1) { + ret = decode_mime_type(ret, end, &mime); + if(ret == 0) goto error; /* a new mime was found -> put it into array */ - if (nr_mimes==MAX_MIMES_NR) { + if(nr_mimes == MAX_MIMES_NR) { LM_ERR("Accept hdr contains more than %d mime type" - " -> buffer overflow!!\n", MAX_MIMES_NR); + " -> buffer overflow!!\n", + MAX_MIMES_NR); goto error; } mimes[nr_mimes++] = mime; /* is another mime following? */ - if (ret==end ) + if(ret == end) break; /* parse the mime separator ',' */ - if (*ret!=',' || ret+1==end) { + if(*ret != ',' || ret + 1 == end) { LM_ERR("parse error between mimes at " - "char <%x> (offset=%d) in <%.*s>!\n", - *ret, (int)(ret-hdr->body.s), - hdr->body.len, hdr->body.s); + "char <%x> (offset=%d) in <%.*s>!\n", + *ret, (int)(ret - hdr->body.s), hdr->body.len, hdr->body.s); goto error; } /* skip the ',' */ @@ -495,14 +507,14 @@ int parse_accept_body(struct hdr_field* const hdr) } /* copy and link the mime buffer into the message */ - hdr->parsed = (void*)pkg_malloc((nr_mimes+1)*sizeof(int)); - if (hdr->parsed==0) { + hdr->parsed = (void *)pkg_malloc((nr_mimes + 1) * sizeof(int)); + if(hdr->parsed == 0) { PKG_MEM_ERROR; goto error; } - memcpy(hdr->parsed,mimes,nr_mimes*sizeof(int)); + memcpy(hdr->parsed, mimes, nr_mimes * sizeof(int)); /* make the buffer null terminated */ - ((int*)hdr->parsed)[nr_mimes] = 0; + ((int *)hdr->parsed)[nr_mimes] = 0; return 1; error: @@ -513,7 +525,7 @@ int parse_accept_body(struct hdr_field* const hdr) * returns: > 0 ok * = 0 hdr not found * = -1 error */ -int parse_accept_hdr(struct sip_msg* const msg) +int parse_accept_hdr(struct sip_msg *const msg) { static unsigned int mimes[MAX_MIMES_NR]; int nr_mimes; @@ -522,44 +534,45 @@ int parse_accept_hdr(struct sip_msg* const msg) char *ret; /* is the header already found? */ - if ( msg->accept==0 ) { + if(msg->accept == 0) { /* if not, found it */ - if ( parse_headers(msg, HDR_ACCEPT_F, 0)==-1) + if(parse_headers(msg, HDR_ACCEPT_F, 0) == -1) goto error; - if ( msg->accept==0 ) { + if(msg->accept == 0) { LM_DBG("missing Accept header\n"); return 0; } } /* maybe the header is already parsed! */ - if ( msg->accept->parsed!=0) + if(msg->accept->parsed != 0) return 1; /* it seams we have to parse it! :-( */ ret = msg->accept->body.s; end = ret + msg->accept->body.len; nr_mimes = 0; - while (1){ - ret = decode_mime_type(ret, end , &mime); - if (ret==0) + while(1) { + ret = decode_mime_type(ret, end, &mime); + if(ret == 0) goto error; /* a new mime was found -> put it into array */ - if (nr_mimes==MAX_MIMES_NR) { + if(nr_mimes == MAX_MIMES_NR) { LM_ERR("Accept hdr contains more than" - " %d mime type -> buffer overflow!!\n",MAX_MIMES_NR); + " %d mime type -> buffer overflow!!\n", + MAX_MIMES_NR); goto error; } mimes[nr_mimes++] = mime; /* is another mime following? */ - if (ret==end ) + if(ret == end) break; /* parse the mime separator ',' */ - if (*ret!=',' || ret+1==end) { + if(*ret != ',' || ret + 1 == end) { LM_ERR("parse error between mimes at " - "char <%x> (offset=%d) in <%.*s>!\n", - *ret, (int)(ret-msg->accept->body.s), - msg->accept->body.len, msg->accept->body.s); + "char <%x> (offset=%d) in <%.*s>!\n", + *ret, (int)(ret - msg->accept->body.s), + msg->accept->body.len, msg->accept->body.s); goto error; } /* skip the ',' */ @@ -567,14 +580,14 @@ int parse_accept_hdr(struct sip_msg* const msg) } /* copy and link the mime buffer into the message */ - msg->accept->parsed = (void*)pkg_malloc((nr_mimes+1)*sizeof(int)); - if (msg->accept->parsed==0) { + msg->accept->parsed = (void *)pkg_malloc((nr_mimes + 1) * sizeof(int)); + if(msg->accept->parsed == 0) { PKG_MEM_ERROR; goto error; } - memcpy(msg->accept->parsed,mimes,nr_mimes*sizeof(int)); + memcpy(msg->accept->parsed, mimes, nr_mimes * sizeof(int)); /* make the buffer null terminated */ - ((int*)msg->accept->parsed)[nr_mimes] = 0; + ((int *)msg->accept->parsed)[nr_mimes] = 0; return 1; error: diff --git a/src/core/parser/parse_content.h b/src/core/parser/parse_content.h index 35855c0c840..e8563c9651d 100644 --- a/src/core/parser/parse_content.h +++ b/src/core/parser/parse_content.h @@ -13,8 +13,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ @@ -31,70 +31,70 @@ #include "msg_parser.h" -struct mime_type { +struct mime_type +{ unsigned short type; unsigned short subtype; }; - /*! \name MimeTypes * Mimes types/subtypes that are recognized */ /*@{ */ -#define TYPE_TEXT 1 -#define TYPE_MESSAGE 2 -#define TYPE_APPLICATION 3 -#define TYPE_MULTIPART 4 -#define TYPE_ALL 0xfe -#define TYPE_UNKNOWN 0xff - -#define SUBTYPE_PLAIN 1 -#define SUBTYPE_CPIM 2 -#define SUBTYPE_SDP 3 -#define SUBTYPE_CPLXML 4 -#define SUBTYPE_PIDFXML 5 -#define SUBTYPE_RLMIXML 6 -#define SUBTYPE_RELATED 7 -#define SUBTYPE_LPIDFXML 8 -#define SUBTYPE_XPIDFXML 9 -#define SUBTYPE_WATCHERINFOXML 10 -#define SUBTYPE_EXTERNAL_BODY 11 -#define SUBTYPE_XML_MSRTC_PIDF 12 -#define SUBTYPE_CPIM_PIDFXML 13 -#define SUBTYPE_MIXED 14 -#define SUBTYPE_ISUP 15 -#define SUBTYPE_ALL 0xfe -#define SUBTYPE_UNKNOWN 0xff +#define TYPE_TEXT 1 +#define TYPE_MESSAGE 2 +#define TYPE_APPLICATION 3 +#define TYPE_MULTIPART 4 +#define TYPE_ALL 0xfe +#define TYPE_UNKNOWN 0xff + +#define SUBTYPE_PLAIN 1 +#define SUBTYPE_CPIM 2 +#define SUBTYPE_SDP 3 +#define SUBTYPE_CPLXML 4 +#define SUBTYPE_PIDFXML 5 +#define SUBTYPE_RLMIXML 6 +#define SUBTYPE_RELATED 7 +#define SUBTYPE_LPIDFXML 8 +#define SUBTYPE_XPIDFXML 9 +#define SUBTYPE_WATCHERINFOXML 10 +#define SUBTYPE_EXTERNAL_BODY 11 +#define SUBTYPE_XML_MSRTC_PIDF 12 +#define SUBTYPE_CPIM_PIDFXML 13 +#define SUBTYPE_MIXED 14 +#define SUBTYPE_ISUP 15 +#define SUBTYPE_ALL 0xfe +#define SUBTYPE_UNKNOWN 0xff /*@} */ /*! \brief taken from PA module - will be useful here */ -#define MIMETYPE(x_,y_) ((TYPE_##x_ << 16) | (SUBTYPE_##y_)) +#define MIMETYPE(x_, y_) ((TYPE_##x_ << 16) | (SUBTYPE_##y_)) /*! \brief - * Maximum number of mimes allowed in Accept header + * Maximum number of mimes allowed in Accept header */ -#define MAX_MIMES_NR 128 +#define MAX_MIMES_NR 128 /*! \brief * returns the content-length value of a sip_msg as an integer */ -#define get_content_length(_msg_) ((long)((_msg_)->content_length->parsed)) +#define get_content_length(_msg_) ((long)((_msg_)->content_length->parsed)) /*! \brief * returns the content-type value of a sip_msg as an integer */ -#define get_content_type(_msg_) ((int)(long)((_msg_)->content_type->parsed)) +#define get_content_type(_msg_) ((int)(long)((_msg_)->content_type->parsed)) /*! \brief * returns the accept values of a sip_msg as a null-terminated array * of integer */ -#define get_accept(_msg_) ((int*)((_msg_)->accept->parsed)) +#define get_accept(_msg_) ((int *)((_msg_)->accept->parsed)) /*! \brief * parse the body of the Content-Type header. Its value is also converted @@ -103,9 +103,9 @@ struct mime_type { * 0 : hdr not found * -1 : error (parse error ) */ -int parse_content_type_hdr(struct sip_msg* const msg); +int parse_content_type_hdr(struct sip_msg *const msg); -int parse_accept_body(struct hdr_field* const hdr); +int parse_accept_body(struct hdr_field *const hdr); /*! \brief * parse the body of the Accept header. Its values are also converted @@ -114,7 +114,7 @@ int parse_accept_body(struct hdr_field* const hdr); * 0 : hdr not found * -1 : error (parse error) */ -int parse_accept_hdr(struct sip_msg* const msg); +int parse_accept_hdr(struct sip_msg *const msg); /*! \brief @@ -122,11 +122,13 @@ int parse_accept_hdr(struct sip_msg* const msg); * type specified by this header (see the above defines). * Returns the first chr after the end of the header. */ -char* parse_content_length(char* const buffer, const char* const end, int* const length); +char *parse_content_length( + char *const buffer, const char *const end, int *const length); /*! \brief * Sets the mime type from the body of a Content-Type header */ -char* decode_mime_type(char* const start, const char* const end, unsigned int* const mime_type); +char *decode_mime_type(char *const start, const char *const end, + unsigned int *const mime_type); #endif diff --git a/src/core/parser/parse_cseq.c b/src/core/parser/parse_cseq.c index fea21b6ffad..359c4045535 100644 --- a/src/core/parser/parse_cseq.c +++ b/src/core/parser/parse_cseq.c @@ -35,8 +35,8 @@ #include "../mem/mem.h" /* parse cseq header */ -char *parse_cseq(char *const buf, const char *const end, - struct cseq_body *const cb) +char *parse_cseq( + char *const buf, const char *const end, struct cseq_body *const cb) { char *t, *m, *m_end; diff --git a/src/core/parser/parse_cseq.h b/src/core/parser/parse_cseq.h index 766e5c6cd5e..8a4389f001c 100644 --- a/src/core/parser/parse_cseq.h +++ b/src/core/parser/parse_cseq.h @@ -13,8 +13,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ @@ -25,35 +25,36 @@ */ - #ifndef PARSE_CSEQ #define PARSE_CSEQ #include "../str.h" -struct cseq_body{ - int error; /*!< Error code */ - str number; /*!< CSeq number */ - str method; /*!< Associated method */ +struct cseq_body +{ + int error; /*!< Error code */ + str number; /*!< CSeq number */ + str method; /*!< Associated method */ unsigned int method_id; /*!< Associated method ID */ }; /*! \brief casting macro for accessing CSEQ body */ -#define get_cseq(p_msg) ((struct cseq_body*)(p_msg)->cseq->parsed) +#define get_cseq(p_msg) ((struct cseq_body *)(p_msg)->cseq->parsed) /*! \brief * Parse CSeq header field */ -char* parse_cseq(char* const buf, const char* const end, struct cseq_body* const cb); +char *parse_cseq( + char *const buf, const char *const end, struct cseq_body *const cb); /*! \brief * Free all associated memory */ -void free_cseq(struct cseq_body* const cb); +void free_cseq(struct cseq_body *const cb); #endif diff --git a/src/core/parser/parse_date.c b/src/core/parser/parse_date.c index 7fa5b6ed60f..bc2284f42e3 100644 --- a/src/core/parser/parse_date.c +++ b/src/core/parser/parse_date.c @@ -25,11 +25,10 @@ */ - #include #include "parse_date.h" #include "parse_def.h" -#include "parser_f.h" /* eat_space_end and so on */ +#include "parser_f.h" /* eat_space_end and so on */ #include "../mem/mem.h" /* @@ -37,13 +36,13 @@ */ #define READ(val) \ -(*(val + 0) + (*(val + 1) << 8) + (*(val + 2) << 16) + (*(val + 3) << 24)) + (*(val + 0) + (*(val + 1) << 8) + (*(val + 2) << 16) + (*(val + 3) << 24)) -inline static int char2int (char *p, int *t) +inline static int char2int(char *p, int *t) { - if (*p < '0' || *p > '9' || *(p + 1) < '0' || *(p + 1) > '9') + if(*p < '0' || *p > '9' || *(p + 1) < '0' || *(p + 1) > '9') return -1; - *t = (*p - '0')*10 + *(p + 1) - '0'; + *t = (*p - '0') * 10 + *(p + 1) - '0'; return 0; } @@ -51,142 +50,194 @@ inline static int char2int (char *p, int *t) /*! \brief * Converts a RFC 1123 formatted date string to stuct tm */ -static int rfc1123totm (char *stime, struct tm *ttm ) { +static int rfc1123totm(char *stime, struct tm *ttm) +{ char *ptime = stime; unsigned int uval; int ires; uval = READ(ptime); - ptime+=4; - switch (uval) { + ptime += 4; + switch(uval) { /* Sun, */ - case 0x2c6e7553: ttm->tm_wday = 0; break; + case 0x2c6e7553: + ttm->tm_wday = 0; + break; /* Mon, */ - case 0x2c6e6f4d: ttm->tm_wday = 1; break; + case 0x2c6e6f4d: + ttm->tm_wday = 1; + break; /* Tue, */ - case 0x2c657554: ttm->tm_wday = 2; break; + case 0x2c657554: + ttm->tm_wday = 2; + break; /* Wed, */ - case 0x2c646557: ttm->tm_wday = 3; break; + case 0x2c646557: + ttm->tm_wday = 3; + break; /* Thu, */ - case 0x2c756854: ttm->tm_wday = 4; break; + case 0x2c756854: + ttm->tm_wday = 4; + break; /* Fri, */ - case 0x2c697246: ttm->tm_wday = 5; break; + case 0x2c697246: + ttm->tm_wday = 5; + break; /* Sat, */ - case 0x2c746153: ttm->tm_wday = 6; break; - default: return -2; + case 0x2c746153: + ttm->tm_wday = 6; + break; + default: + return -2; } - if (*(ptime++)!=' ') return -3; + if(*(ptime++) != ' ') + return -3; - if (char2int(ptime,&ttm->tm_mday) || ttm->tm_mday > 31) return -4; - ptime+=2; + if(char2int(ptime, &ttm->tm_mday) || ttm->tm_mday > 31) + return -4; + ptime += 2; - if (*(ptime++) != ' ') return -5; + if(*(ptime++) != ' ') + return -5; uval = READ(ptime); - ptime+=4; - switch (uval) { + ptime += 4; + switch(uval) { /* Jan, */ - case 0x206e614a: ttm->tm_mon = 0; break; + case 0x206e614a: + ttm->tm_mon = 0; + break; /* Feb, */ - case 0x20626546: ttm->tm_mon = 1; break; + case 0x20626546: + ttm->tm_mon = 1; + break; /* Mar, */ - case 0x2072614d: ttm->tm_mon = 2; break; + case 0x2072614d: + ttm->tm_mon = 2; + break; /* Apr, */ - case 0x20727041: ttm->tm_mon = 3; break; + case 0x20727041: + ttm->tm_mon = 3; + break; /* May, */ - case 0x2079614d: ttm->tm_mon = 4; break; + case 0x2079614d: + ttm->tm_mon = 4; + break; /* Jun, */ - case 0x206e754a: ttm->tm_mon = 5; break; + case 0x206e754a: + ttm->tm_mon = 5; + break; /* Jul, */ - case 0x206c754a: ttm->tm_mon = 6; break; + case 0x206c754a: + ttm->tm_mon = 6; + break; /* Aug, */ - case 0x20677541: ttm->tm_mon = 7; break; + case 0x20677541: + ttm->tm_mon = 7; + break; /* Sep, */ - case 0x20706553: ttm->tm_mon = 8; break; + case 0x20706553: + ttm->tm_mon = 8; + break; /* Oct, */ - case 0x2074634f: ttm->tm_mon = 9; break; + case 0x2074634f: + ttm->tm_mon = 9; + break; /* Nov, */ - case 0x20766f4e: ttm->tm_mon = 10; break; + case 0x20766f4e: + ttm->tm_mon = 10; + break; /* Dec, */ - case 0x20636544: ttm->tm_mon = 11; break; - default: return -6; + case 0x20636544: + ttm->tm_mon = 11; + break; + default: + return -6; } - if (char2int(ptime,&ires)) return -7; - ptime+=2; - if (char2int(ptime,&ttm->tm_year)) return -8; - ptime+=2; - ttm->tm_year+=(ires-19)*100; - - if (*(ptime++) != ' ') return -9; - - if (char2int(ptime,&ttm->tm_hour) || ttm->tm_hour > 23) return -10; - ptime+=2; - if (*(ptime++) != ':') return -11; - - if (char2int(ptime,&ttm->tm_min) || ttm->tm_min > 59) return -12; - ptime+=2; - if (*(ptime++) != ':') return -13; - - if (char2int(ptime,&ttm->tm_sec) || ttm->tm_sec > 59) return -14; - ptime+=2; + if(char2int(ptime, &ires)) + return -7; + ptime += 2; + if(char2int(ptime, &ttm->tm_year)) + return -8; + ptime += 2; + ttm->tm_year += (ires - 19) * 100; + + if(*(ptime++) != ' ') + return -9; + + if(char2int(ptime, &ttm->tm_hour) || ttm->tm_hour > 23) + return -10; + ptime += 2; + if(*(ptime++) != ':') + return -11; + + if(char2int(ptime, &ttm->tm_min) || ttm->tm_min > 59) + return -12; + ptime += 2; + if(*(ptime++) != ':') + return -13; + + if(char2int(ptime, &ttm->tm_sec) || ttm->tm_sec > 59) + return -14; + ptime += 2; /* " GMT" */ uval = READ(ptime); - if ((uval | 0x20202020) != 0x746d6720) return -15; + if((uval | 0x20202020) != 0x746d6720) + return -15; return 0; } void parse_date(char *buffer, char *end, struct date_body *db) { - db->error=PARSE_ERROR; + db->error = PARSE_ERROR; /* check whether enough characters are available */ - if (end - buffer < RFC1123DATELENGTH) + if(end - buffer < RFC1123DATELENGTH) goto error; - if (rfc1123totm(buffer,&db->date)) + if(rfc1123totm(buffer, &db->date)) goto error; - db->error=PARSE_OK; - return ; + db->error = PARSE_OK; + return; error: LM_ERR("parse error\n"); - return ; + return; } int parse_date_header(struct sip_msg *msg) { - struct date_body* date_b; + struct date_body *date_b; - if ( !msg->date && (parse_headers(msg,HDR_DATE_F,0)==-1 || !msg->date) ) { + if(!msg->date && (parse_headers(msg, HDR_DATE_F, 0) == -1 || !msg->date)) { LM_ERR("bad msg or missing DATE header\n"); goto error; } /* maybe the header is already parsed! */ - if (msg->date->parsed) + if(msg->date->parsed) return 0; - date_b=pkg_malloc(sizeof(*date_b)); - if (date_b==0){ + date_b = pkg_malloc(sizeof(*date_b)); + if(date_b == 0) { PKG_MEM_ERROR; goto error; } memset(date_b, 0, sizeof(*date_b)); - parse_date(msg->date->body.s, - msg->date->body.s + msg->date->body.len+1, - date_b); - if (date_b->error==PARSE_ERROR){ + parse_date(msg->date->body.s, msg->date->body.s + msg->date->body.len + 1, + date_b); + if(date_b->error == PARSE_ERROR) { free_date(date_b); goto error; } - msg->date->parsed=(void*)date_b; + msg->date->parsed = (void *)date_b; return 0; error: diff --git a/src/core/parser/parse_date.h b/src/core/parser/parse_date.h index cc852db494f..bb143746a3d 100644 --- a/src/core/parser/parse_date.h +++ b/src/core/parser/parse_date.h @@ -25,23 +25,23 @@ */ - #ifndef PARSE_DATE #define PARSE_DATE #include #include "msg_parser.h" -#define RFC1123DATELENGTH 29 +#define RFC1123DATELENGTH 29 -struct date_body{ - int error; /* Error code */ +struct date_body +{ + int error; /* Error code */ struct tm date; }; /* casting macro for accessing DATE body */ -#define get_date(p_msg) ((struct date_body*)(p_msg)->date->parsed) +#define get_date(p_msg) ((struct date_body *)(p_msg)->date->parsed) /* diff --git a/src/core/parser/parse_def.h b/src/core/parser/parse_def.h index d250d28c123..11cd95e57af 100644 --- a/src/core/parser/parse_def.h +++ b/src/core/parser/parse_def.h @@ -13,8 +13,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ @@ -25,7 +25,6 @@ */ - #ifndef PARSE_DEF_H #define PARSE_DEF_H diff --git a/src/core/parser/parse_disposition.c b/src/core/parser/parse_disposition.c index 26a68a2755c..c0eaec7ef7d 100644 --- a/src/core/parser/parse_disposition.c +++ b/src/core/parser/parse_disposition.c @@ -13,8 +13,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ @@ -36,23 +36,37 @@ #include "parse_disposition.h" - /*! \brief parse a string that supposed to be a disposition and fills up the structure * Returns: -1 : error * o : success */ -int parse_disposition( str *s, struct disposition *disp) +int parse_disposition(str *s, struct disposition *disp) { - enum { FIND_TYPE, TYPE, END_TYPE, FIND_PARAM, PARAM, END_PARAM, FIND_VAL, - FIND_QUOTED_VAL, QUOTED_VAL, SKIP_QUOTED_VAL, VAL, END_VAL, - F_LF, F_CR, F_CRLF}; + enum + { + FIND_TYPE, + TYPE, + END_TYPE, + FIND_PARAM, + PARAM, + END_PARAM, + FIND_VAL, + FIND_QUOTED_VAL, + QUOTED_VAL, + SKIP_QUOTED_VAL, + VAL, + END_VAL, + F_LF, + F_CR, + F_CRLF + }; struct disposition_param *disp_p; struct disposition_param *new_p; - int state; - int saved_state; + int state; + int saved_state; char *tmp; char *end; - if(s==NULL || s->s==NULL || s->len<=0) { + if(s == NULL || s->s == NULL || s->len <= 0) { LM_ERR("invalid parameters\n"); return -1; } @@ -61,11 +75,11 @@ int parse_disposition( str *s, struct disposition *disp) end = s->s + s->len; disp_p = 0; - for( tmp=s->s; tmps; tmp < end; tmp++) { switch(*tmp) { case ' ': case '\t': - switch (state) { + switch(state) { case FIND_QUOTED_VAL: disp_p->body.s = tmp; state = QUOTED_VAL; @@ -89,12 +103,12 @@ int parse_disposition( str *s, struct disposition *disp) case F_LF: case F_CR: /*previous=crlf and now =' '*/ - state=saved_state; + state = saved_state; break; } break; case '\n': - switch (state) { + switch(state) { case TYPE: disp->type.len = tmp - disp->type.s; saved_state = END_TYPE; @@ -112,20 +126,20 @@ int parse_disposition( str *s, struct disposition *disp) break; case FIND_TYPE: case FIND_PARAM: - saved_state=state; - state=F_LF; + saved_state = state; + state = F_LF; break; case F_CR: - state=F_CRLF; + state = F_CRLF; break; default: LM_ERR("unexpected char [%c] in status %d: <<%.*s>>.\n", - *tmp,state, (int)(tmp-s->s), s->s); + *tmp, state, (int)(tmp - s->s), s->s); goto error; } break; case '\r': - switch (state) { + switch(state) { case TYPE: disp->type.len = tmp - disp->type.s; saved_state = END_TYPE; @@ -143,22 +157,22 @@ int parse_disposition( str *s, struct disposition *disp) break; case FIND_TYPE: case FIND_PARAM: - saved_state=state; - state=F_CR; + saved_state = state; + state = F_CR; break; default: LM_ERR("unexpected char [%c] in status %d: <<%.*s>>.\n", - *tmp,state, (int)(tmp-s->s), ZSW(s->s)); + *tmp, state, (int)(tmp - s->s), ZSW(s->s)); goto error; } break; case 0: - LM_ERR("nexpected char [%c] in status %d: <<%.*s>>.\n", - *tmp,state, (int)(tmp-s->s), ZSW(s->s)); + LM_ERR("nexpected char [%c] in status %d: <<%.*s>>.\n", *tmp, + state, (int)(tmp - s->s), ZSW(s->s)); goto error; break; case ';': - switch (state) { + switch(state) { case FIND_QUOTED_VAL: disp_p->body.s = tmp; state = QUOTED_VAL; @@ -183,12 +197,12 @@ int parse_disposition( str *s, struct disposition *disp) break; default: LM_ERR("unexpected char [%c] in status %d: <<%.*s>>.\n", - *tmp,state, (int)(tmp-s->s), ZSW(s->s)); + *tmp, state, (int)(tmp - s->s), ZSW(s->s)); goto error; } break; case '=': - switch (state) { + switch(state) { case FIND_QUOTED_VAL: disp_p->body.s = tmp; state = QUOTED_VAL; @@ -204,12 +218,12 @@ int parse_disposition( str *s, struct disposition *disp) break; default: LM_ERR("unexpected char [%c] in status %d: <<%.*s>>.\n", - *tmp,state, (int)(tmp-s->s), ZSW(s->s)); + *tmp, state, (int)(tmp - s->s), ZSW(s->s)); goto error; } break; case '\"': - switch (state) { + switch(state) { case SKIP_QUOTED_VAL: state = QUOTED_VAL; break; @@ -223,12 +237,12 @@ int parse_disposition( str *s, struct disposition *disp) break; default: LM_ERR("unexpected char [%c] in status %d: <<%.*s>>.\n", - *tmp,state, (int)(tmp-s->s), ZSW(s->s)); + *tmp, state, (int)(tmp - s->s), ZSW(s->s)); goto error; } break; case '\\': - switch (state) { + switch(state) { case FIND_QUOTED_VAL: disp_p->body.s = tmp; state = SKIP_QUOTED_VAL; @@ -241,7 +255,7 @@ int parse_disposition( str *s, struct disposition *disp) break; default: LM_ERR("unexpected char [%c] in status %d: <<%.*s>>.\n", - *tmp,state, (int)(tmp-s->s), ZSW(s->s)); + *tmp, state, (int)(tmp - s->s), ZSW(s->s)); goto error; } break; @@ -258,7 +272,7 @@ int parse_disposition( str *s, struct disposition *disp) case '?': case '{': case '}': - switch (state) { + switch(state) { case FIND_QUOTED_VAL: disp_p->body.s = tmp; state = QUOTED_VAL; @@ -269,12 +283,12 @@ int parse_disposition( str *s, struct disposition *disp) break; default: LM_ERR("unexpected char [%c] in status %d: <<%.*s>>.\n", - *tmp,state, (int)(tmp-s->s), ZSW(s->s)); + *tmp, state, (int)(tmp - s->s), ZSW(s->s)); goto error; } break; default: - switch (state) { + switch(state) { case SKIP_QUOTED_VAL: state = QUOTED_VAL; case QUOTED_VAL: @@ -284,14 +298,14 @@ int parse_disposition( str *s, struct disposition *disp) state = TYPE; break; case FIND_PARAM: - new_p=(struct disposition_param*)pkg_malloc - (sizeof(struct disposition_param)); - if (new_p==0) { + new_p = (struct disposition_param *)pkg_malloc( + sizeof(struct disposition_param)); + if(new_p == 0) { PKG_MEM_ERROR; goto error; } - memset(new_p,0,sizeof(struct disposition_param)); - if (disp_p==0) + memset(new_p, 0, sizeof(struct disposition_param)); + if(disp_p == 0) disp->params = new_p; else disp_p->next = new_p; @@ -308,11 +322,11 @@ int parse_disposition( str *s, struct disposition *disp) state = QUOTED_VAL; break; } - }/*switch*/ - }/*for*/ + } /*switch*/ + } /*for*/ /* check which was the last parser state */ - switch (state) { + switch(state) { case END_PARAM: case END_TYPE: case END_VAL: @@ -327,8 +341,7 @@ int parse_disposition( str *s, struct disposition *disp) disp_p->body.len = tmp - disp_p->body.s; break; default: - LM_ERR("wrong final state (%d)\n", - state); + LM_ERR("wrong final state (%d)\n", state); goto error; } return 0; @@ -337,24 +350,22 @@ int parse_disposition( str *s, struct disposition *disp) } - /*! \brief Frees the entire disposition structure (params + itself) */ -void free_disposition( struct disposition **disp) +void free_disposition(struct disposition **disp) { struct disposition_param *param; /* free the params */ while((*disp)->params) { param = (*disp)->params->next; - pkg_free( (*disp)->params); + pkg_free((*disp)->params); (*disp)->params = param; } - pkg_free( *disp ); + pkg_free(*disp); *disp = 0; } - /*! \brief looks inside the message, gets the Content-Disposition hdr, parse it, builds * and fills a disposition structure for it what will be attached to hdr as * parsed link. @@ -362,42 +373,42 @@ void free_disposition( struct disposition **disp) * 0 : success * 1 : hdr not found */ -int parse_content_disposition( struct sip_msg *msg ) +int parse_content_disposition(struct sip_msg *msg) { struct disposition *disp; /* look for Content-Disposition header */ - if (msg->content_disposition==0) { - if (parse_headers(msg, HDR_CONTENTDISPOSITION_F, 0)==-1) + if(msg->content_disposition == 0) { + if(parse_headers(msg, HDR_CONTENTDISPOSITION_F, 0) == -1) goto error; - if (msg->content_disposition==0) { + if(msg->content_disposition == 0) { DBG("hdr not found\n"); return 1; } } /* now, we have the header -> look if it isn't already parsed */ - if (msg->content_disposition->parsed!=0) { + if(msg->content_disposition->parsed != 0) { /* already parsed, nothing more to be done */ return 0; } /* parse the body */ - disp = (struct disposition*)pkg_malloc(sizeof(struct disposition)); - if (disp==0) { + disp = (struct disposition *)pkg_malloc(sizeof(struct disposition)); + if(disp == 0) { PKG_MEM_ERROR; goto error; } - memset(disp,0,sizeof(struct disposition)); + memset(disp, 0, sizeof(struct disposition)); - if (parse_disposition( &(msg->content_disposition->body), disp)==-1) { + if(parse_disposition(&(msg->content_disposition->body), disp) == -1) { /* error when parsing the body */ - free_disposition( &disp ); + free_disposition(&disp); goto error; } /* attach the parsed form to the header */ - msg->content_disposition->parsed = (void*)disp; + msg->content_disposition->parsed = (void *)disp; return 0; error: @@ -406,18 +417,16 @@ int parse_content_disposition( struct sip_msg *msg ) /*! \brief Prints recursive a disposition structure */ -void print_disposition( struct disposition *disp) +void print_disposition(struct disposition *disp) { struct disposition_param *param; - DBG("*** Disposition type=<%.*s>[%d]\n", - disp->type.len,disp->type.s,disp->type.len); - for( param=disp->params; param; param=param->next) { + DBG("*** Disposition type=<%.*s>[%d]\n", disp->type.len, disp->type.s, + disp->type.len); + for(param = disp->params; param; param = param->next) { DBG("*** Disposition param: <%.*s>[%d]=<%.*s>[%d] is_quoted=%d\n", - param->name.len,param->name.s, param->name.len, - param->body.len,param->body.s, param->body.len, - param->is_quoted); + param->name.len, param->name.s, param->name.len, + param->body.len, param->body.s, param->body.len, + param->is_quoted); } } - - diff --git a/src/core/parser/parse_disposition.h b/src/core/parser/parse_disposition.h index 8f0f60433b7..a0bd09156ed 100644 --- a/src/core/parser/parse_disposition.h +++ b/src/core/parser/parse_disposition.h @@ -13,8 +13,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ @@ -34,10 +34,11 @@ #define get_content_disposition(_msg_) \ - ((struct disposition*)((_msg_)->content_disposition->parsed)) + ((struct disposition *)((_msg_)->content_disposition->parsed)) -struct disposition_param { +struct disposition_param +{ str name; str body; int is_quoted; @@ -45,7 +46,8 @@ struct disposition_param { }; -struct disposition { +struct disposition +{ str type; struct disposition_param *params; }; @@ -58,20 +60,19 @@ struct disposition { * 0 : success * 1 : hdr not found */ -int parse_content_disposition( struct sip_msg *msg ); +int parse_content_disposition(struct sip_msg *msg); /*! \brief parse a string that supposed to be a disposition and fills up the structure * Returns: -1 : error * o : success */ -int parse_disposition( str *s, struct disposition *disp); +int parse_disposition(str *s, struct disposition *disp); /*! \brief Frees the entire disposition structure (params + itself) */ -void free_disposition( struct disposition **disp); +void free_disposition(struct disposition **disp); /*! \brief Prints recursive a disposition structure */ -void print_disposition( struct disposition *disp); +void print_disposition(struct disposition *disp); #endif - diff --git a/src/core/parser/parse_diversion.c b/src/core/parser/parse_diversion.c index 43a07faf959..804dfdb6b8c 100644 --- a/src/core/parser/parse_diversion.c +++ b/src/core/parser/parse_diversion.c @@ -46,25 +46,25 @@ */ int parse_diversion_header(struct sip_msg *msg) { - struct to_body* diversion_b; + struct to_body *diversion_b; - if (!msg->diversion && (parse_headers(msg, HDR_DIVERSION_F, 0) == -1)) { + if(!msg->diversion && (parse_headers(msg, HDR_DIVERSION_F, 0) == -1)) { goto error; } - if (!msg->diversion) { + if(!msg->diversion) { /* header not found */ return -1; } /* maybe the header is already parsed! */ - if (msg->diversion->parsed) + if(msg->diversion->parsed) return 0; /* bad luck! :-( - we have to parse it */ /* first, get some memory */ diversion_b = pkg_malloc(sizeof(struct to_body)); - if (diversion_b == 0) { + if(diversion_b == 0) { PKG_MEM_ERROR; goto error; } @@ -72,9 +72,9 @@ int parse_diversion_header(struct sip_msg *msg) /* now parse it!! */ memset(diversion_b, 0, sizeof(struct to_body)); parse_addr_spec(msg->diversion->body.s, - msg->diversion->body.s + msg->diversion->body.len + 1, - diversion_b, 1); - if (diversion_b->error == PARSE_ERROR) { + msg->diversion->body.s + msg->diversion->body.len + 1, diversion_b, + 1); + if(diversion_b->error == PARSE_ERROR) { LM_ERR("bad diversion header\n"); free_to(diversion_b); goto error; @@ -90,20 +90,20 @@ int parse_diversion_header(struct sip_msg *msg) /*! \brief * Get the value of a given diversion parameter */ -str *get_diversion_param(struct sip_msg *msg, str* name) +str *get_diversion_param(struct sip_msg *msg, str *name) { struct to_param *params; - if (parse_diversion_header(msg) < 0) { + if(parse_diversion_header(msg) < 0) { LM_ERR("could not get diversion parameter\n"); return 0; } - params = ((struct to_body*)(msg->diversion->parsed))->param_lst; + params = ((struct to_body *)(msg->diversion->parsed))->param_lst; - while (params) { - if ((params->name.len == name->len) && - (strncmp(params->name.s, name->s, name->len) == 0)) { + while(params) { + if((params->name.len == name->len) + && (strncmp(params->name.s, name->s, name->len) == 0)) { return ¶ms->value; } params = params->next; diff --git a/src/core/parser/parse_diversion.h b/src/core/parser/parse_diversion.h index 526006cfc17..271219eba54 100644 --- a/src/core/parser/parse_diversion.h +++ b/src/core/parser/parse_diversion.h @@ -13,36 +13,36 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /*! \file * \brief Parser :: Diversion header - * + * * \ingroup parser */ - + #ifndef PARSE_DIVERSION_H #define PARSE_DIVERSION_H - + #include "msg_parser.h" - + /*! \brief casting macro for accessing Diversion body */ -#define get_diversion(p_msg) ((struct to_body*)(p_msg)->diversion->parsed) - - +#define get_diversion(p_msg) ((struct to_body *)(p_msg)->diversion->parsed) + + /*! \brief * Diversion header field parser */ int parse_diversion_header(struct sip_msg *msg); - + /*! \brief * Get the value of a given diversion parameter */ -str *get_diversion_param(struct sip_msg *msg, str* name); +str *get_diversion_param(struct sip_msg *msg, str *name); #endif /* PARSE_DIVERSION_H */ diff --git a/src/core/parser/parse_event.c b/src/core/parser/parse_event.c index dc482ebbe54..1f3f7d301b4 100644 --- a/src/core/parser/parse_event.c +++ b/src/core/parser/parse_event.c @@ -34,30 +34,29 @@ #include "parse_event.h" -#include "../mem/mem.h" /* pkg_malloc, pkg_free */ +#include "../mem/mem.h" /* pkg_malloc, pkg_free */ #include "../dprint.h" -#include /* memset */ -#include "../trim.h" /* trim_leading */ -#include /* printf */ +#include /* memset */ +#include "../trim.h" /* trim_leading */ +#include /* printf */ #include "../ut.h" -static struct { +static struct +{ str name; int type; -} events[] = { - {STR_STATIC_INIT("presence"), EVENT_PRESENCE}, - {STR_STATIC_INIT("presence.winfo"), EVENT_PRESENCE_WINFO}, - {STR_STATIC_INIT("xcap-change"), EVENT_XCAP_CHANGE}, - {STR_STATIC_INIT("sip-profile"), EVENT_SIP_PROFILE}, - {STR_STATIC_INIT("message-summary"), EVENT_MESSAGE_SUMMARY}, - {STR_STATIC_INIT("dialog"), EVENT_DIALOG}, - {STR_STATIC_INIT("ua-profile"), EVENT_UA_PROFILE}, - /* The following must be the last element in the array */ - {STR_NULL, EVENT_OTHER} -}; - - -static inline char* skip_token(char* _b, int _l) +} events[] = {{STR_STATIC_INIT("presence"), EVENT_PRESENCE}, + {STR_STATIC_INIT("presence.winfo"), EVENT_PRESENCE_WINFO}, + {STR_STATIC_INIT("xcap-change"), EVENT_XCAP_CHANGE}, + {STR_STATIC_INIT("sip-profile"), EVENT_SIP_PROFILE}, + {STR_STATIC_INIT("message-summary"), EVENT_MESSAGE_SUMMARY}, + {STR_STATIC_INIT("dialog"), EVENT_DIALOG}, + {STR_STATIC_INIT("ua-profile"), EVENT_UA_PROFILE}, + /* The following must be the last element in the array */ + {STR_NULL, EVENT_OTHER}}; + + +static inline char *skip_token(char *_b, int _l) { int i = 0; @@ -76,15 +75,15 @@ static inline char* skip_token(char* _b, int _l) } -int event_parser(char* s, int len, event_t* e) +int event_parser(char *s, int len, event_t *e) { int i; str tmp; - char* end; - param_hooks_t* phooks = NULL; + char *end; + param_hooks_t *phooks = NULL; enum pclass pclass = CLASS_ANY; - if (e == NULL) { + if(e == NULL) { LM_ERR("Invalid parameter value\n"); return -1; } @@ -93,7 +92,7 @@ int event_parser(char* s, int len, event_t* e) tmp.len = len; trim_leading(&tmp); - if (tmp.len == 0) { + if(tmp.len == 0) { LM_ERR("Empty body\n"); return -1; } @@ -104,8 +103,8 @@ int event_parser(char* s, int len, event_t* e) e->type = EVENT_OTHER; for(i = 0; events[i].name.len; i++) { - if (e->name.len == events[i].name.len && - !strncasecmp(e->name.s, events[i].name.s, e->name.len)) { + if(e->name.len == events[i].name.len + && !strncasecmp(e->name.s, events[i].name.s, e->name.len)) { e->type = events[i].type; break; } @@ -117,20 +116,22 @@ int event_parser(char* s, int len, event_t* e) e->params.list = NULL; - if (tmp.len && (tmp.s[0] == ';')) { + if(tmp.len && (tmp.s[0] == ';')) { /* Shift the semicolon and skip any leading whitespace, this is needed * for parse_params to work correctly. */ - tmp.s++; tmp.len--; + tmp.s++; + tmp.len--; trim_leading(&tmp); - if (!tmp.len) return 0; + if(!tmp.len) + return 0; /* We have parameters to parse */ - if (e->type == EVENT_DIALOG) { + if(e->type == EVENT_DIALOG) { pclass = CLASS_EVENT_DIALOG; - phooks = (param_hooks_t*)&e->params.hooks; + phooks = (param_hooks_t *)&e->params.hooks; } - if (parse_params(&tmp, pclass, phooks, &e->params.list) < 0) { + if(parse_params(&tmp, pclass, phooks, &e->params.list) < 0) { LM_ERR("Error while parsing parameters parameters\n"); return -1; } @@ -142,29 +143,29 @@ int event_parser(char* s, int len, event_t* e) /*! \brief * Parse Event header field body */ -int parse_event(struct hdr_field* _h) +int parse_event(struct hdr_field *_h) { - event_t* e; + event_t *e; - if (_h->parsed != 0) { + if(_h->parsed != 0) { return 0; } - e = (event_t*)pkg_malloc(sizeof(event_t)); - if (e == 0) { + e = (event_t *)pkg_malloc(sizeof(event_t)); + if(e == 0) { PKG_MEM_ERROR; return -1; } memset(e, 0, sizeof(event_t)); - if (event_parser(_h->body.s, _h->body.len, e) < 0) { + if(event_parser(_h->body.s, _h->body.len, e) < 0) { LM_ERR("Error in event_parser\n"); pkg_free(e); return -2; } - _h->parsed = (void*)e; + _h->parsed = (void *)e; return 0; } @@ -172,10 +173,11 @@ int parse_event(struct hdr_field* _h) /*! \brief * Free all memory */ -void free_event(event_t** _e) +void free_event(event_t **_e) { - if (*_e) { - if ((*_e)->params.list) free_params((*_e)->params.list); + if(*_e) { + if((*_e)->params.list) + free_params((*_e)->params.list); pkg_free(*_e); *_e = NULL; } @@ -185,12 +187,12 @@ void free_event(event_t** _e) /*! \brief * Print structure, for debugging only */ -void print_event(event_t* e) +void print_event(event_t *e) { fprintf(stderr, "===Event===\n"); fprintf(stderr, "name : \'%.*s\'\n", STR_FMT(&e->name)); fprintf(stderr, "type: %d\n", e->type); - if (e->params.list) { + if(e->params.list) { print_params(stderr, e->params.list); } fprintf(stderr, "===/Event===\n"); diff --git a/src/core/parser/parse_event.h b/src/core/parser/parse_event.h index b5069ca4f59..90e4755d2ab 100644 --- a/src/core/parser/parse_event.h +++ b/src/core/parser/parse_event.h @@ -13,8 +13,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ @@ -34,7 +34,8 @@ #include "parse_param.h" /* Recognized event types */ -enum event_type { +enum event_type +{ EVENT_OTHER = 0, EVENT_PRESENCE, EVENT_PRESENCE_WINFO, @@ -46,15 +47,17 @@ enum event_type { }; -struct event_params { +struct event_params +{ param_hooks_t hooks; /* Well known dialog package params */ - param_t* list; /* Linked list of all parsed parameters */ + param_t *list; /* Linked list of all parsed parameters */ }; -typedef struct event { +typedef struct event +{ enum event_type type; /* Parsed variant */ - str name; /* Original string representation */ + str name; /* Original string representation */ struct event_params params; } event_t; @@ -62,21 +65,21 @@ typedef struct event { /* * Parse Event HF body */ -int parse_event(struct hdr_field* hf); +int parse_event(struct hdr_field *hf); /* * Release memory */ -void free_event(event_t** e); +void free_event(event_t **e); /* * Print structure, for debugging only */ -void print_event(event_t* e); +void print_event(event_t *e); -int event_parser(char* s, int l, event_t* e); +int event_parser(char *s, int l, event_t *e); #endif /* PARSE_EVENT_H */ diff --git a/src/core/parser/parse_expires.c b/src/core/parser/parse_expires.c index 587ef350e44..f0ad5d501d3 100644 --- a/src/core/parser/parse_expires.c +++ b/src/core/parser/parse_expires.c @@ -29,17 +29,16 @@ */ - #include "parse_expires.h" -#include /* printf */ -#include "../mem/mem.h" /* pkg_malloc, pkg_free */ +#include /* printf */ +#include "../mem/mem.h" /* pkg_malloc, pkg_free */ #include "../dprint.h" -#include "../trim.h" /* trim_leading */ -#include /* memset */ +#include "../trim.h" /* trim_leading */ +#include /* memset */ #include "../ut.h" -static inline int expires_parser(char* _s, int _l, exp_body_t* _e) +static inline int expires_parser(char *_s, int _l, exp_body_t *_e) { int i; str tmp; @@ -49,7 +48,7 @@ static inline int expires_parser(char* _s, int _l, exp_body_t* _e) trim(&tmp); - if (tmp.len == 0) { + if(tmp.len == 0) { LM_ERR("Empty body\n"); _e->valid = 0; return -1; @@ -59,13 +58,13 @@ static inline int expires_parser(char* _s, int _l, exp_body_t* _e) _e->text.len = tmp.len; /* more than 32bit/maxuint can't be valid */ - if (tmp.len > 10) { + if(tmp.len > 10) { _e->valid = 0; return 0; } for(i = 0; i < tmp.len; i++) { - if ((tmp.s[i] >= '0') && (tmp.s[i] <= '9')) { + if((tmp.s[i] >= '0') && (tmp.s[i] <= '9')) { _e->val *= 10; _e->val += tmp.s[i] - '0'; } else { @@ -100,29 +99,29 @@ static inline int expires_parser(char* _s, int _l, exp_body_t* _e) /*! \brief * Parse expires header field body */ -int parse_expires(struct hdr_field* _h) +int parse_expires(struct hdr_field *_h) { - exp_body_t* e; + exp_body_t *e; - if (_h->parsed) { - return 0; /* Already parsed */ + if(_h->parsed) { + return 0; /* Already parsed */ } - e = (exp_body_t*)pkg_malloc(sizeof(exp_body_t)); - if (e == 0) { + e = (exp_body_t *)pkg_malloc(sizeof(exp_body_t)); + if(e == 0) { PKG_MEM_ERROR; return -1; } memset(e, 0, sizeof(exp_body_t)); - if (expires_parser(_h->body.s, _h->body.len, e) < 0) { + if(expires_parser(_h->body.s, _h->body.len, e) < 0) { LM_ERR("Error while parsing\n"); pkg_free(e); return -2; } - _h->parsed = (void*)e; + _h->parsed = (void *)e; return 0; } @@ -130,7 +129,7 @@ int parse_expires(struct hdr_field* _h) /*! \brief * Free all memory associated with exp_body_t */ -void free_expires(exp_body_t** _e) +void free_expires(exp_body_t **_e) { pkg_free(*_e); *_e = 0; @@ -140,7 +139,7 @@ void free_expires(exp_body_t** _e) /*! \brief * Print exp_body_t content, for debugging only */ -void print_expires(exp_body_t* _e) +void print_expires(exp_body_t *_e) { printf("===Expires===\n"); printf("text: \'%.*s\'\n", _e->text.len, ZSW(_e->text.s)); diff --git a/src/core/parser/parse_expires.h b/src/core/parser/parse_expires.h index 14f4be40de8..6fc9a007a50 100644 --- a/src/core/parser/parse_expires.h +++ b/src/core/parser/parse_expires.h @@ -15,8 +15,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ @@ -27,7 +27,6 @@ */ - #ifndef PARSE_EXPIRES_H #define PARSE_EXPIRES_H @@ -35,29 +34,30 @@ #include "hf.h" -typedef struct exp_body { - str text; /*!< Original text representation */ +typedef struct exp_body +{ + str text; /*!< Original text representation */ unsigned char valid; /*!< Was parsing successful ? */ - unsigned int val; /*!< Parsed value */ + unsigned int val; /*!< Parsed value */ } exp_body_t; /*! \brief * Parse expires header field body */ -int parse_expires(struct hdr_field* _h); +int parse_expires(struct hdr_field *_h); /*! \brief * Free all memory associated with exp_body_t */ -void free_expires(exp_body_t** _e); +void free_expires(exp_body_t **_e); /*! \brief * Print exp_body_t content, for debugging only */ -void print_expires(exp_body_t* _e); +void print_expires(exp_body_t *_e); #endif /* PARSE_EXPIRES_H */ diff --git a/src/core/parser/parse_fline.c b/src/core/parser/parse_fline.c index 43afd723d84..5e640eb2364 100644 --- a/src/core/parser/parse_fline.c +++ b/src/core/parser/parse_fline.c @@ -47,17 +47,17 @@ int http_reply_parse = 0; /* parses the first line, returns pointer to next line & fills fl; * also modifies buffer (to avoid extra copy ops) */ -char* parse_first_line(char* buffer, unsigned int len, struct msg_start* fl) +char *parse_first_line(char *buffer, unsigned int len, struct msg_start *fl) { char *tmp; - char* second; - char* third; - char* nl; + char *second; + char *third; + char *nl; int offset; /* int l; */ - char* end; - char s1,s2,s3; + char *end; + char s1, s2, s3; char *prn; unsigned int t; @@ -69,128 +69,126 @@ char* parse_first_line(char* buffer, unsigned int len, struct msg_start* fl) memset(fl, 0, sizeof(struct msg_start)); offset = 0; - end=buffer+len; + end = buffer + len; /* see if it's a reply (status) */ /* jku -- parse well-known methods */ /* drop messages which are so short they are for sure useless; * utilize knowledge of minimum size in parsing the first token */ - if (len <=16 ) { + if(len <= 16) { LM_INFO("message too short: %d [%.*s]\n", len, len, buffer); goto error1; } - tmp=buffer; + tmp = buffer; /* is it perhaps a reply, ie does it start with "SIP...." ? */ - if ( (*tmp=='S' || *tmp=='s') - && strncasecmp( tmp+1, &SIP_VERSION[1], SIP_VERSION_LEN-1)==0 - && (*(tmp+SIP_VERSION_LEN)==' ')) { - fl->type=SIP_REPLY; - fl->flags|=FLINE_FLAG_PROTO_SIP; - fl->u.reply.version.len=SIP_VERSION_LEN; - tmp=buffer+SIP_VERSION_LEN; - } else if (http_reply_parse != 0 && (*tmp=='H' || *tmp=='h')) { + if((*tmp == 'S' || *tmp == 's') + && strncasecmp(tmp + 1, &SIP_VERSION[1], SIP_VERSION_LEN - 1) == 0 + && (*(tmp + SIP_VERSION_LEN) == ' ')) { + fl->type = SIP_REPLY; + fl->flags |= FLINE_FLAG_PROTO_SIP; + fl->u.reply.version.len = SIP_VERSION_LEN; + tmp = buffer + SIP_VERSION_LEN; + } else if(http_reply_parse != 0 && (*tmp == 'H' || *tmp == 'h')) { /* 'HTTP/1.[0|1]' */ - if (strncasecmp( tmp+1, &HTTP_VERSION[1], HTTP_VERSION_LEN-1)==0 && - ((*(tmp+HTTP_VERSION_LEN)=='0') || (*(tmp+HTTP_VERSION_LEN)=='1')) - && (*(tmp+HTTP_VERSION_LEN+1)==' ') ){ + if(strncasecmp(tmp + 1, &HTTP_VERSION[1], HTTP_VERSION_LEN - 1) == 0 + && ((*(tmp + HTTP_VERSION_LEN) == '0') + || (*(tmp + HTTP_VERSION_LEN) == '1')) + && (*(tmp + HTTP_VERSION_LEN + 1) == ' ')) { /* hack to be able to route http replies * Note: - the http reply must have a via * - the message is marked as SIP_REPLY (ugly) */ - fl->type=SIP_REPLY; - fl->flags|=FLINE_FLAG_PROTO_HTTP; - fl->u.reply.version.len=HTTP_VERSION_LEN+1 /*include last digit*/; - tmp=buffer+HTTP_VERSION_LEN+1 /* last digit */; - /* 'HTTP/2' */ - } else if (strncasecmp( tmp+1, &HTTP2_VERSION[1], HTTP2_VERSION_LEN-1)==0 - && (*(tmp+HTTP2_VERSION_LEN)==' ')) { - fl->type=SIP_REPLY; - fl->flags|=(FLINE_FLAG_PROTO_HTTP | FLINE_FLAG_PROTO_HTTP2); - fl->u.reply.version.len=HTTP2_VERSION_LEN; - tmp=buffer+HTTP2_VERSION_LEN; + fl->type = SIP_REPLY; + fl->flags |= FLINE_FLAG_PROTO_HTTP; + fl->u.reply.version.len = + HTTP_VERSION_LEN + 1 /*include last digit*/; + tmp = buffer + HTTP_VERSION_LEN + 1 /* last digit */; + /* 'HTTP/2' */ + } else if(strncasecmp(tmp + 1, &HTTP2_VERSION[1], HTTP2_VERSION_LEN - 1) + == 0 + && (*(tmp + HTTP2_VERSION_LEN) == ' ')) { + fl->type = SIP_REPLY; + fl->flags |= (FLINE_FLAG_PROTO_HTTP | FLINE_FLAG_PROTO_HTTP2); + fl->u.reply.version.len = HTTP2_VERSION_LEN; + tmp = buffer + HTTP2_VERSION_LEN; } - } else IFISMETHOD( INVITE, 'I' ) - else IFISMETHOD( CANCEL, 'C') - else IFISMETHOD( ACK, 'A' ) - else IFISMETHOD( BYE, 'B' ) - else IFISMETHOD( INFO, 'I' ) - else IFISMETHOD( REGISTER, 'R') - else IFISMETHOD( SUBSCRIBE, 'S') - else IFISMETHOD( NOTIFY, 'N') - else IFISMETHOD( MESSAGE, 'M') - else IFISMETHOD( OPTIONS, 'O') - else IFISMETHOD( PRACK, 'P') - else IFISMETHOD( UPDATE, 'U') - else IFISMETHOD( REFER, 'R') - else IFISMETHOD( PUBLISH, 'P') - else IFISMETHOD( KDMQ, 'K') - else IFISMETHOD( GET, 'G') - else IFISMETHOD( POST, 'P') - else IFISMETHOD( PUT, 'P') - else IFISMETHOD( DELETE, 'D') - /* if you want to add another method XXX, include METHOD_XXX in + } else + IFISMETHOD(INVITE, 'I') + else IFISMETHOD(CANCEL, 'C') else IFISMETHOD(ACK, 'A') else IFISMETHOD( + BYE, 'B') else IFISMETHOD(INFO, 'I') else IFISMETHOD(REGISTER, + 'R') else IFISMETHOD(SUBSCRIBE, 'S') else IFISMETHOD(NOTIFY, + 'N') else IFISMETHOD(MESSAGE, 'M') else IFISMETHOD(OPTIONS, + 'O') else IFISMETHOD(PRACK, 'P') else IFISMETHOD(UPDATE, + 'U') else IFISMETHOD(REFER, 'R') else IFISMETHOD(PUBLISH, + 'P') else IFISMETHOD(KDMQ, 'K') else IFISMETHOD(GET, + 'G') else IFISMETHOD(POST, 'P') else IFISMETHOD(PUT, + 'P') else IFISMETHOD(DELETE, 'D') + /* if you want to add another method XXX, include METHOD_XXX in * H-file (this is the value which you will take later in * processing and define XXX_LEN as length of method name; * then just call IFISMETHOD( XXX, 'X' ) ... 'X' is the first * latter; everything must be capitals */ - else { + else + { /* neither reply, nor any of known method requests, * let's believe it is an unknown method request */ - tmp=eat_token_end(buffer,buffer+len); - if ((tmp==buffer)||(tmp>=end)){ + tmp = eat_token_end(buffer, buffer + len); + if((tmp == buffer) || (tmp >= end)) { LM_INFO("empty or bad first line\n"); goto error1; } - if (*tmp!=' ') { + if(*tmp != ' ') { LM_INFO("method not followed by SP\n"); goto error1; } - fl->type=SIP_REQUEST; - fl->u.request.method_value=METHOD_OTHER; - fl->u.request.method.len=tmp-buffer; + fl->type = SIP_REQUEST; + fl->u.request.method_value = METHOD_OTHER; + fl->u.request.method.len = tmp - buffer; } /* identifying type of message over now; * tmp points at space after; go ahead */ - fl->u.request.method.s=buffer; /* store ptr to first token */ - second=tmp+1; /* jump to second token */ - offset=second-buffer; + fl->u.request.method.s = buffer; /* store ptr to first token */ + second = tmp + 1; /* jump to second token */ + offset = second - buffer; /* EoJku */ /* next element */ - tmp=eat_token_end(second, second+len-offset); - if (tmp>=end){ + tmp = eat_token_end(second, second + len - offset); + if(tmp >= end) { goto error; } - offset+=tmp-second; - third=eat_space_end(tmp, tmp+len-offset); - offset+=third-tmp; - if ((third==tmp)||(tmp>=end)){ + offset += tmp - second; + third = eat_space_end(tmp, tmp + len - offset); + offset += third - tmp; + if((third == tmp) || (tmp >= end)) { goto error; } - fl->u.request.uri.s=second; - fl->u.request.uri.len=tmp-second; + fl->u.request.uri.s = second; + fl->u.request.uri.len = tmp - second; /* jku: parse status code */ - if (fl->type==SIP_REPLY) { - if (fl->u.request.uri.len!=3) { - LM_INFO("len(status code)!=3: %.*s\n", - fl->u.request.uri.len, ZSW(second) ); + if(fl->type == SIP_REPLY) { + if(fl->u.request.uri.len != 3) { + LM_INFO("len(status code)!=3: %.*s\n", fl->u.request.uri.len, + ZSW(second)); goto error; } - s1=*second; s2=*(second+1);s3=*(second+2); - if (s1>='0' && s1<='9' - && s2>='0' && s2<='9' - && s3>='0' && s3<='9' ) { - fl->u.reply.statuscode=(s1-'0')*100+10*(s2-'0')+(s3-'0'); + s1 = *second; + s2 = *(second + 1); + s3 = *(second + 2); + if(s1 >= '0' && s1 <= '9' && s2 >= '0' && s2 <= '9' && s3 >= '0' + && s3 <= '9') { + fl->u.reply.statuscode = + (s1 - '0') * 100 + 10 * (s2 - '0') + (s3 - '0'); } else { - LM_INFO("status code non-numerical: %.*s\n", - fl->u.request.uri.len, ZSW(second) ); + LM_INFO("status code non-numerical: %.*s\n", fl->u.request.uri.len, + ZSW(second)); goto error; } } @@ -199,87 +197,90 @@ char* parse_first_line(char* buffer, unsigned int len, struct msg_start* fl) /* last part: for a request it must be the version, for a reply * it can contain almost anything, including spaces, so we don't care * about it*/ - if (fl->type==SIP_REQUEST){ - tmp=eat_token_end(third,third+len-offset); - offset+=tmp-third; - if ((tmp==third)||(tmp>=end)){ + if(fl->type == SIP_REQUEST) { + tmp = eat_token_end(third, third + len - offset); + offset += tmp - third; + if((tmp == third) || (tmp >= end)) { goto error; } - if (! is_empty_end(tmp, tmp+len-offset)){ + if(!is_empty_end(tmp, tmp + len - offset)) { goto error; } - }else{ + } else { /* find end of line ('\n' or '\r') */ - tmp=eat_token2_end(third,third+len-offset,'\r'); - if (tmp>=end){ /* no crlf in packet => invalid */ + tmp = eat_token2_end(third, third + len - offset, '\r'); + if(tmp >= end) { /* no crlf in packet => invalid */ goto error; } - offset+=tmp-third; + offset += tmp - third; } - nl=eat_line(tmp,len-offset); - if (nl>=end){ /* no crlf in packet or only 1 line > invalid */ + nl = eat_line(tmp, len - offset); + if(nl >= end) { /* no crlf in packet or only 1 line > invalid */ goto error; } - fl->u.request.version.s=third; - fl->u.request.version.len=tmp-third; - fl->len=nl-buffer; + fl->u.request.version.s = third; + fl->u.request.version.len = tmp - third; + fl->len = nl - buffer; - if (fl->type==SIP_REQUEST) { + if(fl->type == SIP_REQUEST) { if(fl->u.request.version.len >= SIP_VERSION_LEN - && (fl->u.request.version.s[0]=='S' - || fl->u.request.version.s[0]=='s') - && !strncasecmp(fl->u.request.version.s+1, - &SIP_VERSION[1], SIP_VERSION_LEN-1)) { - fl->flags|=FLINE_FLAG_PROTO_SIP; + && (fl->u.request.version.s[0] == 'S' + || fl->u.request.version.s[0] == 's') + && !strncasecmp(fl->u.request.version.s + 1, &SIP_VERSION[1], + SIP_VERSION_LEN - 1)) { + fl->flags |= FLINE_FLAG_PROTO_SIP; } else if(fl->u.request.version.len >= 4 - && (fl->u.request.version.s[0]=='H' - || fl->u.request.version.s[0]=='h')) { + && (fl->u.request.version.s[0] == 'H' + || fl->u.request.version.s[0] == 'h')) { if(fl->u.request.version.len >= HTTP_VERSION_LEN - && !strncasecmp(fl->u.request.version.s+1, - &HTTP_VERSION[1], HTTP_VERSION_LEN-1)) { - fl->flags|=FLINE_FLAG_PROTO_HTTP; + && !strncasecmp(fl->u.request.version.s + 1, + &HTTP_VERSION[1], HTTP_VERSION_LEN - 1)) { + fl->flags |= FLINE_FLAG_PROTO_HTTP; } else if(fl->u.request.version.len >= HTTP2_VERSION_LEN - && !strncasecmp(fl->u.request.version.s+1, - &HTTP2_VERSION[1], HTTP2_VERSION_LEN-1)) { - fl->flags|=(FLINE_FLAG_PROTO_HTTP | FLINE_FLAG_PROTO_HTTP2); + && !strncasecmp(fl->u.request.version.s + 1, + &HTTP2_VERSION[1], HTTP2_VERSION_LEN - 1)) { + fl->flags |= (FLINE_FLAG_PROTO_HTTP | FLINE_FLAG_PROTO_HTTP2); } } } LM_DBG("first line type %d (%s) flags %d\n", (int)fl->type, - (fl->type==SIP_REPLY)?"reply(status)":"request", (int)fl->flags); + (fl->type == SIP_REPLY) ? "reply(status)" : "request", + (int)fl->flags); return nl; error: LM_DBG("bad %s first line\n", - (fl->type==SIP_REPLY)?"reply(status)":"request"); + (fl->type == SIP_REPLY) ? "reply(status)" : "request"); - LM_DBG("at line 0 char %d: \n", offset ); - prn=pkg_malloc( offset ); - if (prn) { - for (t=0; ttype=SIP_INVALID; + fl->type = SIP_INVALID; LOG(cfg_get(core, core_cfg, sip_parser_log), "parse_first_line: bad message (offset: %d)\n", offset); /* skip line */ - nl=eat_line(buffer,len); + nl = eat_line(buffer, len); return nl; } -char* parse_fline(char* buffer, char* end, struct msg_start* fl) +char *parse_fline(char *buffer, char *end, struct msg_start *fl) { - if(end<=buffer) { + if(end <= buffer) { /* make it throw error via parse_first_line() for consistency */ return parse_first_line(buffer, 0, fl); } - return parse_first_line(buffer, (unsigned int)(end-buffer), fl); + return parse_first_line(buffer, (unsigned int)(end - buffer), fl); } diff --git a/src/core/parser/parse_fline.h b/src/core/parser/parse_fline.h index d65b04bdbbf..d775d26e35b 100644 --- a/src/core/parser/parse_fline.h +++ b/src/core/parser/parse_fline.h @@ -44,26 +44,26 @@ #define MSG_REQUEST 1 /* Message is reply */ -#define SIP_REPLY 2 -#define MSG_REPLY 2 +#define SIP_REPLY 2 +#define MSG_REPLY 2 /* flags for first line * - stored on a short field (16 flags) */ -#define FLINE_FLAG_PROTO_SIP (1<<0) /* sip 2.0 protocol */ -#define FLINE_FLAG_PROTO_HTTP (1<<1) /* any http protocol */ -#define FLINE_FLAG_PROTO_HTTP2 (1<<2) /* additional for http 2 */ +#define FLINE_FLAG_PROTO_SIP (1 << 0) /* sip 2.0 protocol */ +#define FLINE_FLAG_PROTO_HTTP (1 << 1) /* any http protocol */ +#define FLINE_FLAG_PROTO_HTTP2 (1 << 2) /* additional for http 2 */ #define SIP_VERSION "SIP/2.0" #define SIP_VERSION_LEN 7 #define HTTP_VERSION "HTTP/1." -#define HTTP_VERSION_LEN (sizeof(HTTP_VERSION)-1) +#define HTTP_VERSION_LEN (sizeof(HTTP_VERSION) - 1) #define HTTP2_VERSION "HTTP/2" -#define HTTP2_VERSION_LEN (sizeof(HTTP2_VERSION)-1) +#define HTTP2_VERSION_LEN (sizeof(HTTP2_VERSION) - 1) #define CANCEL "CANCEL" -#define ACK "ACK" +#define ACK "ACK" #define INVITE "INVITE" #define INVITE_LEN 6 @@ -86,28 +86,32 @@ #define PUT_LEN 3 #define DELETE_LEN 6 -typedef struct msg_start { - short type; /*!< Type of the message - request/response */ - short flags; /*!< First line flags */ - int len; /*!< length including delimiter */ - union { - struct { - str method; /*!< Method string */ - str uri; /*!< Request URI */ - str version; /*!< SIP version */ - int method_value; /*!< Method id value */ +typedef struct msg_start +{ + short type; /*!< Type of the message - request/response */ + short flags; /*!< First line flags */ + int len; /*!< length including delimiter */ + union + { + struct + { + str method; /*!< Method string */ + str uri; /*!< Request URI */ + str version; /*!< SIP version */ + int method_value; /*!< Method id value */ } request; - struct { - str version; /*!< SIP version */ - str status; /*!< Reply status */ - str reason; /*!< Reply reason phrase */ - unsigned int statuscode; /*!< Reply status code */ + struct + { + str version; /*!< SIP version */ + str status; /*!< Reply status */ + str reason; /*!< Reply reason phrase */ + unsigned int statuscode; /*!< Reply status code */ } reply; - }u; + } u; } msg_start_t; -char* parse_first_line(char* buffer, unsigned int len, struct msg_start * fl); +char *parse_first_line(char *buffer, unsigned int len, struct msg_start *fl); -char* parse_fline(char* buffer, char* end, struct msg_start* fl); +char *parse_fline(char *buffer, char *end, struct msg_start *fl); #endif /* PARSE_FLINE_H */ diff --git a/src/core/parser/parse_from.h b/src/core/parser/parse_from.h index 5f641ea93eb..284081b2a30 100644 --- a/src/core/parser/parse_from.h +++ b/src/core/parser/parse_from.h @@ -13,8 +13,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ @@ -33,17 +33,17 @@ /* casting macro for accessing From body */ -#define get_from(p_msg) ((struct to_body*)(p_msg)->from->parsed) +#define get_from(p_msg) ((struct to_body *)(p_msg)->from->parsed) -#define free_from(_to_body_) free_to(_to_body_) +#define free_from(_to_body_) free_to(_to_body_) #define GET_FROM_PURI(p_msg) \ - (&((struct to_body*)(p_msg)->from->parsed)->parsed_uri) + (&((struct to_body *)(p_msg)->from->parsed)->parsed_uri) /* * From header field parser */ -int parse_from_header( struct sip_msg *msg); +int parse_from_header(struct sip_msg *msg); sip_uri_t *parse_from_uri(sip_msg_t *msg); diff --git a/src/core/parser/parse_hname2.c b/src/core/parser/parse_hname2.c index 20398a95951..e7d0792e988 100644 --- a/src/core/parser/parse_hname2.c +++ b/src/core/parser/parse_hname2.c @@ -33,7 +33,8 @@ #include "parse_hname2.h" -typedef struct ksr_hdr_map { +typedef struct ksr_hdr_map +{ str hname; hdr_types_t htype; hdr_flags_t hflag; @@ -42,104 +43,112 @@ typedef struct ksr_hdr_map { /* map with SIP header name * - must be groupped by first letter - indexed for faster search */ static ksr_hdr_map_t _ksr_hdr_map[] = { - { str_init("a"), HDR_ACCEPTCONTACT_T, HDR_ACCEPTCONTACT_F }, - { str_init("Accept"), HDR_ACCEPT_T, HDR_ACCEPT_F }, - { str_init("Accept-Contact"), HDR_ACCEPTCONTACT_T, HDR_ACCEPTCONTACT_F }, - { str_init("Accept-Language"), HDR_ACCEPTLANGUAGE_T, HDR_ACCEPTLANGUAGE_F }, - { str_init("Allow"), HDR_ALLOW_T, HDR_ALLOW_F }, - { str_init("Allow-Events"), HDR_ALLOWEVENTS_T, HDR_ALLOWEVENTS_F }, - { str_init("Authorization"), HDR_AUTHORIZATION_T, HDR_AUTHORIZATION_F }, - - { str_init("b"), HDR_REFERREDBY_T, HDR_REFERREDBY_F }, - - { str_init("c"), HDR_CONTENTTYPE_T, HDR_CONTENTTYPE_F }, - { str_init("Call-Id"), HDR_CALLID_T, HDR_CALLID_F }, - { str_init("Call-Info"), HDR_CALLINFO_T, HDR_CALLINFO_F }, - { str_init("Contact"), HDR_CONTACT_T, HDR_CONTACT_F }, - { str_init("Content-Disposition"), HDR_CONTENTDISPOSITION_T, HDR_CONTENTDISPOSITION_F }, - { str_init("Content-Encoding"), HDR_CONTENTENCODING_T, HDR_CONTENTENCODING_F }, - { str_init("Content-Length"), HDR_CONTENTLENGTH_T, HDR_CONTENTLENGTH_F }, - { str_init("Content-Type"), HDR_CONTENTTYPE_T, HDR_CONTENTTYPE_F }, - { str_init("CSeq"), HDR_CSEQ_T, HDR_CSEQ_F }, - - { str_init("d"), HDR_REQUESTDISPOSITION_T, HDR_REQUESTDISPOSITION_F }, - { str_init("Date"), HDR_DATE_T, HDR_DATE_F }, - { str_init("Diversion"), HDR_DIVERSION_T, HDR_DIVERSION_F }, - - { str_init("e"), HDR_CONTENTENCODING_T, HDR_CONTENTENCODING_F }, - { str_init("Event"), HDR_EVENT_T, HDR_EVENT_F }, - { str_init("Expires"), HDR_EXPIRES_T, HDR_EXPIRES_F }, - - { str_init("f"), HDR_FROM_T, HDR_FROM_F }, - { str_init("From"), HDR_FROM_T, HDR_FROM_F }, - - { str_init("i"), HDR_CALLID_T, HDR_CALLID_F }, - { str_init("Identity"), HDR_IDENTITY_T, HDR_IDENTITY_F }, - { str_init("Identity-Info"), HDR_IDENTITY_INFO_T, HDR_IDENTITY_INFO_F }, - - { str_init("j"), HDR_REJECTCONTACT_T, HDR_REJECTCONTACT_F }, - - { str_init("k"), HDR_SUPPORTED_T, HDR_SUPPORTED_F }, - - { str_init("l"), HDR_CONTENTLENGTH_T, HDR_CONTENTLENGTH_F }, - - { str_init("m"), HDR_CONTACT_T, HDR_CONTACT_F }, - { str_init("Max-Forwards"), HDR_MAXFORWARDS_T, HDR_MAXFORWARDS_F }, - { str_init("Min-Expires"), HDR_MIN_EXPIRES_T, HDR_MIN_EXPIRES_F }, - { str_init("Min-SE"), HDR_MIN_SE_T, HDR_MIN_SE_F }, - - { str_init("o"), HDR_EVENT_T, HDR_EVENT_F }, - { str_init("Organization"), HDR_ORGANIZATION_T, HDR_ORGANIZATION_F }, - - { str_init("Path"), HDR_PATH_T, HDR_PATH_F }, - { str_init("Priority"), HDR_PRIORITY_T, HDR_PRIORITY_F }, - { str_init("Privacy"), HDR_PRIVACY_T, HDR_PRIVACY_F }, - { str_init("Proxy-Authenticate"), HDR_PROXY_AUTHENTICATE_T, HDR_PROXY_AUTHENTICATE_F }, - { str_init("Proxy-Authorization"), HDR_PROXYAUTH_T, HDR_PROXYAUTH_F }, - { str_init("Proxy-Require"), HDR_PROXYREQUIRE_T, HDR_PROXYREQUIRE_F }, - { str_init("P-Preferred-Identity"), HDR_PPI_T, HDR_PPI_F }, - { str_init("P-Asserted-Identity"), HDR_PAI_T, HDR_PAI_F }, - - { str_init("r"), HDR_REFER_TO_T, HDR_REFER_TO_F }, - { str_init("Reason"), HDR_REASON_T, HDR_REASON_F }, - { str_init("Record-Route"), HDR_RECORDROUTE_T, HDR_RECORDROUTE_F }, - { str_init("Refer-To"), HDR_REFER_TO_T, HDR_REFER_TO_F }, - { str_init("Referred-By"), HDR_REFERREDBY_T, HDR_REFERREDBY_F }, - { str_init("Reject-Contact"), HDR_REJECTCONTACT_T, HDR_REJECTCONTACT_F }, - { str_init("Remote-Party-ID"), HDR_RPID_T, HDR_RPID_F }, - { str_init("Request-Disposition"), HDR_REQUESTDISPOSITION_T, HDR_REQUESTDISPOSITION_F }, - { str_init("Require"), HDR_REQUIRE_T, HDR_REQUIRE_F }, - { str_init("Retry-After"), HDR_RETRY_AFTER_T, HDR_RETRY_AFTER_F }, - { str_init("Route"), HDR_ROUTE_T, HDR_ROUTE_F }, - - { str_init("s"), HDR_SUBJECT_T, HDR_SUBJECT_F }, - { str_init("Server"), HDR_SERVER_T, HDR_SERVER_F }, - { str_init("Session-Expires"), HDR_SESSIONEXPIRES_T, HDR_SESSIONEXPIRES_F }, - { str_init("SIP-If-Match"), HDR_SIPIFMATCH_T, HDR_SIPIFMATCH_F }, - { str_init("Subject"), HDR_SUBJECT_T, HDR_SUBJECT_F }, - { str_init("Subscription-State"), HDR_SUBSCRIPTION_STATE_T, HDR_SUBSCRIPTION_STATE_F }, - { str_init("Supported"), HDR_SUPPORTED_T, HDR_SUPPORTED_F }, - - { str_init("t"), HDR_TO_T, HDR_TO_F }, - { str_init("To"), HDR_TO_T, HDR_TO_F }, - - { str_init("u"), HDR_ALLOWEVENTS_T, HDR_ALLOWEVENTS_F }, - { str_init("Unsupported"), HDR_UNSUPPORTED_T, HDR_UNSUPPORTED_F }, - { str_init("User-Agent"), HDR_USERAGENT_T, HDR_USERAGENT_F }, - - { str_init("v"), HDR_VIA_T, HDR_VIA_F }, - { str_init("Via"), HDR_VIA_T, HDR_VIA_F }, - - { str_init("x"), HDR_SESSIONEXPIRES_T, HDR_SESSIONEXPIRES_F }, - - { str_init("y"), HDR_IDENTITY_T, HDR_IDENTITY_F }, - - { str_init("WWW-Authenticate"), HDR_WWW_AUTHENTICATE_T, HDR_WWW_AUTHENTICATE_F }, - - { str_init(""), 0, 0 } -}; - -typedef struct ksr_hdr_map_idx { + {str_init("a"), HDR_ACCEPTCONTACT_T, HDR_ACCEPTCONTACT_F}, + {str_init("Accept"), HDR_ACCEPT_T, HDR_ACCEPT_F}, + {str_init("Accept-Contact"), HDR_ACCEPTCONTACT_T, HDR_ACCEPTCONTACT_F}, + {str_init("Accept-Language"), HDR_ACCEPTLANGUAGE_T, + HDR_ACCEPTLANGUAGE_F}, + {str_init("Allow"), HDR_ALLOW_T, HDR_ALLOW_F}, + {str_init("Allow-Events"), HDR_ALLOWEVENTS_T, HDR_ALLOWEVENTS_F}, + {str_init("Authorization"), HDR_AUTHORIZATION_T, HDR_AUTHORIZATION_F}, + + {str_init("b"), HDR_REFERREDBY_T, HDR_REFERREDBY_F}, + + {str_init("c"), HDR_CONTENTTYPE_T, HDR_CONTENTTYPE_F}, + {str_init("Call-Id"), HDR_CALLID_T, HDR_CALLID_F}, + {str_init("Call-Info"), HDR_CALLINFO_T, HDR_CALLINFO_F}, + {str_init("Contact"), HDR_CONTACT_T, HDR_CONTACT_F}, + {str_init("Content-Disposition"), HDR_CONTENTDISPOSITION_T, + HDR_CONTENTDISPOSITION_F}, + {str_init("Content-Encoding"), HDR_CONTENTENCODING_T, + HDR_CONTENTENCODING_F}, + {str_init("Content-Length"), HDR_CONTENTLENGTH_T, HDR_CONTENTLENGTH_F}, + {str_init("Content-Type"), HDR_CONTENTTYPE_T, HDR_CONTENTTYPE_F}, + {str_init("CSeq"), HDR_CSEQ_T, HDR_CSEQ_F}, + + {str_init("d"), HDR_REQUESTDISPOSITION_T, HDR_REQUESTDISPOSITION_F}, + {str_init("Date"), HDR_DATE_T, HDR_DATE_F}, + {str_init("Diversion"), HDR_DIVERSION_T, HDR_DIVERSION_F}, + + {str_init("e"), HDR_CONTENTENCODING_T, HDR_CONTENTENCODING_F}, + {str_init("Event"), HDR_EVENT_T, HDR_EVENT_F}, + {str_init("Expires"), HDR_EXPIRES_T, HDR_EXPIRES_F}, + + {str_init("f"), HDR_FROM_T, HDR_FROM_F}, + {str_init("From"), HDR_FROM_T, HDR_FROM_F}, + + {str_init("i"), HDR_CALLID_T, HDR_CALLID_F}, + {str_init("Identity"), HDR_IDENTITY_T, HDR_IDENTITY_F}, + {str_init("Identity-Info"), HDR_IDENTITY_INFO_T, HDR_IDENTITY_INFO_F}, + + {str_init("j"), HDR_REJECTCONTACT_T, HDR_REJECTCONTACT_F}, + + {str_init("k"), HDR_SUPPORTED_T, HDR_SUPPORTED_F}, + + {str_init("l"), HDR_CONTENTLENGTH_T, HDR_CONTENTLENGTH_F}, + + {str_init("m"), HDR_CONTACT_T, HDR_CONTACT_F}, + {str_init("Max-Forwards"), HDR_MAXFORWARDS_T, HDR_MAXFORWARDS_F}, + {str_init("Min-Expires"), HDR_MIN_EXPIRES_T, HDR_MIN_EXPIRES_F}, + {str_init("Min-SE"), HDR_MIN_SE_T, HDR_MIN_SE_F}, + + {str_init("o"), HDR_EVENT_T, HDR_EVENT_F}, + {str_init("Organization"), HDR_ORGANIZATION_T, HDR_ORGANIZATION_F}, + + {str_init("Path"), HDR_PATH_T, HDR_PATH_F}, + {str_init("Priority"), HDR_PRIORITY_T, HDR_PRIORITY_F}, + {str_init("Privacy"), HDR_PRIVACY_T, HDR_PRIVACY_F}, + {str_init("Proxy-Authenticate"), HDR_PROXY_AUTHENTICATE_T, + HDR_PROXY_AUTHENTICATE_F}, + {str_init("Proxy-Authorization"), HDR_PROXYAUTH_T, HDR_PROXYAUTH_F}, + {str_init("Proxy-Require"), HDR_PROXYREQUIRE_T, HDR_PROXYREQUIRE_F}, + {str_init("P-Preferred-Identity"), HDR_PPI_T, HDR_PPI_F}, + {str_init("P-Asserted-Identity"), HDR_PAI_T, HDR_PAI_F}, + + {str_init("r"), HDR_REFER_TO_T, HDR_REFER_TO_F}, + {str_init("Reason"), HDR_REASON_T, HDR_REASON_F}, + {str_init("Record-Route"), HDR_RECORDROUTE_T, HDR_RECORDROUTE_F}, + {str_init("Refer-To"), HDR_REFER_TO_T, HDR_REFER_TO_F}, + {str_init("Referred-By"), HDR_REFERREDBY_T, HDR_REFERREDBY_F}, + {str_init("Reject-Contact"), HDR_REJECTCONTACT_T, HDR_REJECTCONTACT_F}, + {str_init("Remote-Party-ID"), HDR_RPID_T, HDR_RPID_F}, + {str_init("Request-Disposition"), HDR_REQUESTDISPOSITION_T, + HDR_REQUESTDISPOSITION_F}, + {str_init("Require"), HDR_REQUIRE_T, HDR_REQUIRE_F}, + {str_init("Retry-After"), HDR_RETRY_AFTER_T, HDR_RETRY_AFTER_F}, + {str_init("Route"), HDR_ROUTE_T, HDR_ROUTE_F}, + + {str_init("s"), HDR_SUBJECT_T, HDR_SUBJECT_F}, + {str_init("Server"), HDR_SERVER_T, HDR_SERVER_F}, + {str_init("Session-Expires"), HDR_SESSIONEXPIRES_T, + HDR_SESSIONEXPIRES_F}, + {str_init("SIP-If-Match"), HDR_SIPIFMATCH_T, HDR_SIPIFMATCH_F}, + {str_init("Subject"), HDR_SUBJECT_T, HDR_SUBJECT_F}, + {str_init("Subscription-State"), HDR_SUBSCRIPTION_STATE_T, + HDR_SUBSCRIPTION_STATE_F}, + {str_init("Supported"), HDR_SUPPORTED_T, HDR_SUPPORTED_F}, + + {str_init("t"), HDR_TO_T, HDR_TO_F}, + {str_init("To"), HDR_TO_T, HDR_TO_F}, + + {str_init("u"), HDR_ALLOWEVENTS_T, HDR_ALLOWEVENTS_F}, + {str_init("Unsupported"), HDR_UNSUPPORTED_T, HDR_UNSUPPORTED_F}, + {str_init("User-Agent"), HDR_USERAGENT_T, HDR_USERAGENT_F}, + + {str_init("v"), HDR_VIA_T, HDR_VIA_F}, + {str_init("Via"), HDR_VIA_T, HDR_VIA_F}, + + {str_init("x"), HDR_SESSIONEXPIRES_T, HDR_SESSIONEXPIRES_F}, + + {str_init("y"), HDR_IDENTITY_T, HDR_IDENTITY_F}, + + {str_init("WWW-Authenticate"), HDR_WWW_AUTHENTICATE_T, + HDR_WWW_AUTHENTICATE_F}, + + {str_init(""), 0, 0}}; + +typedef struct ksr_hdr_map_idx +{ int idxs; int idxe; } ksr_hdr_map_idx_t; @@ -154,12 +163,14 @@ static ksr_hdr_map_idx_t _ksr_hdr_map_idx[KSR_HDR_MAP_IDX_SIZE]; /** * valid chars in header names */ -static unsigned char *_ksr_hname_chars_list = (unsigned char*)"0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz-._+~"; +static unsigned char *_ksr_hname_chars_list = + (unsigned char *)"0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuV" + "vWwXxYyZz-._+~"; /** * additional valid chars in header names (core param) */ -unsigned char *_ksr_hname_extra_chars = (unsigned char*)""; +unsigned char *_ksr_hname_extra_chars = (unsigned char *)""; /** * indexed valid chars in 256-array for 1-byte-index access check @@ -175,25 +186,25 @@ int ksr_hname_init_index(void) unsigned char c; int i; - for(i=0; i 0; i++) { + for(i = 0; _ksr_hdr_map[i].hname.len > 0; i++) { c = _ksr_hdr_map[i].hname.s[0]; if(_ksr_hdr_map_idx[c].idxs == -1) { _ksr_hdr_map_idx[tolower(c)].idxs = i; _ksr_hdr_map_idx[toupper(c)].idxs = i; } - if(c != _ksr_hdr_map[i+1].hname.s[0]) { + if(c != _ksr_hdr_map[i + 1].hname.s[0]) { _ksr_hdr_map_idx[tolower(c)].idxe = i; _ksr_hdr_map_idx[toupper(c)].idxe = i; } } - for(i=0; _ksr_hname_chars_list[i] != 0; i++) { + for(i = 0; _ksr_hname_chars_list[i] != 0; i++) { _ksr_hname_chars_idx[_ksr_hname_chars_list[i]] = 1; } @@ -207,7 +218,7 @@ int ksr_hname_init_config(void) { int i; - for(i=0; _ksr_hname_extra_chars[i] != 0; i++) { + for(i = 0; _ksr_hname_extra_chars[i] != 0; i++) { _ksr_hname_chars_idx[_ksr_hname_extra_chars[i]] = 1; } @@ -223,20 +234,20 @@ int ksr_hname_init_config(void) * - returns pointer after : if emode==0 or after header name if emode==1 * in case of parsing error, returns begin and sets hdr->type to HDR_ERROR_T */ -char *parse_sip_header_name(char* const begin, const char* const end, - hdr_field_t* const hdr, int emode, int logmode) +char *parse_sip_header_name(char *const begin, const char *const end, + hdr_field_t *const hdr, int emode, int logmode) { char *p; int i; - if (begin == NULL || end == NULL || end <= begin) { + if(begin == NULL || end == NULL || end <= begin) { hdr->type = HDR_ERROR_T; return begin; } if(_ksr_hname_chars_idx[(unsigned char)(*begin)] == 0) { if(likely(logmode)) { LM_ERR("invalid start of header name for [%.*s]\n", - (int)(end-begin), begin); + (int)(end - begin), begin); } hdr->type = HDR_ERROR_T; return begin; @@ -244,7 +255,7 @@ char *parse_sip_header_name(char* const begin, const char* const end, hdr->type = HDR_OTHER_T; hdr->name.s = begin; - for(p=begin+1; ptype = HDR_ERROR_T; return begin; @@ -279,7 +290,7 @@ char *parse_sip_header_name(char* const begin, const char* const end, /* no : found - emode==0 */ if(likely(logmode)) { LM_ERR("invalid end of header name for [%.*s]\n", - (int)(end-begin), begin); + (int)(end - begin), begin); } hdr->type = HDR_ERROR_T; return begin; @@ -289,22 +300,25 @@ char *parse_sip_header_name(char* const begin, const char* const end, /* lookup header type */ if(_ksr_hdr_map_idx[(unsigned char)(hdr->name.s[0])].idxs >= 0) { for(i = _ksr_hdr_map_idx[(unsigned char)(hdr->name.s[0])].idxs; - i <= _ksr_hdr_map_idx[(unsigned char)(hdr->name.s[0])].idxe; i++) { + i <= _ksr_hdr_map_idx[(unsigned char)(hdr->name.s[0])].idxe; + i++) { if(hdr->name.len == _ksr_hdr_map[i].hname.len && strncasecmp(hdr->name.s, _ksr_hdr_map[i].hname.s, - hdr->name.len) == 0) { + hdr->name.len) + == 0) { hdr->type = _ksr_hdr_map[i].htype; } } } LM_DBG("parsed header name [%.*s] type %d\n", hdr->name.len, hdr->name.s, - hdr->type); + hdr->type); - return (p+1); + return (p + 1); } -char* parse_hname2(char* const begin, const char* const end, struct hdr_field* const hdr) +char *parse_hname2( + char *const begin, const char *const end, struct hdr_field *const hdr) { return parse_sip_header_name(begin, end, hdr, 0, 1); } @@ -313,13 +327,13 @@ char* parse_hname2(char* const begin, const char* const end, struct hdr_field* c * kept for compatibility of code developed in the past * - to be replace with parse_hname2() across the code */ -char* parse_hname2_short(char* const begin, const char* const end, struct hdr_field* const hdr) +char *parse_hname2_short( + char *const begin, const char *const end, struct hdr_field *const hdr) { return parse_sip_header_name(begin, end, hdr, 0, 1); } -char* parse_hname2_str (str* const hbuf, hdr_field_t* const hdr) +char *parse_hname2_str(str *const hbuf, hdr_field_t *const hdr) { return parse_sip_header_name(hbuf->s, hbuf->s + hbuf->len, hdr, 1, 1); } - diff --git a/src/core/parser/parse_hname2.h b/src/core/parser/parse_hname2.h index fc52c1c802e..349a3394c8c 100644 --- a/src/core/parser/parse_hname2.h +++ b/src/core/parser/parse_hname2.h @@ -1,4 +1,4 @@ -/* +/* * Fast 32-bit Header Field Name Parser * * Copyright (C) 2001-2003 FhG Fokus @@ -36,17 +36,19 @@ * @file */ -char *parse_sip_header_name(char* const begin, const char* const end, - hdr_field_t* const hdr, int emode, int logmode); +char *parse_sip_header_name(char *const begin, const char *const end, + hdr_field_t *const hdr, int emode, int logmode); /* macro to find header name without printing errors in failure case */ #define find_hname2_str(hbuf, hdr) \ parse_sip_header_name((hbuf)->s, (hbuf)->s + (hbuf)->len, hdr, 1, 0) -char* parse_hname2(char* const begin, const char* const end, struct hdr_field* const hdr); -char* parse_hname2_short(char* const begin, const char* const end, struct hdr_field* const hdr); -char* parse_hname2_str (str* const hbuf, hdr_field_t* const hdr); +char *parse_hname2( + char *const begin, const char *const end, struct hdr_field *const hdr); +char *parse_hname2_short( + char *const begin, const char *const end, struct hdr_field *const hdr); +char *parse_hname2_str(str *const hbuf, hdr_field_t *const hdr); int ksr_hname_init_index(void); int ksr_hname_init_config(void); diff --git a/src/core/parser/parse_identity.c b/src/core/parser/parse_identity.c index 8408cb4fdb3..e750a3cad2d 100644 --- a/src/core/parser/parse_identity.c +++ b/src/core/parser/parse_identity.c @@ -28,7 +28,7 @@ #include #include "parse_identity.h" #include "parse_def.h" -#include "parser_f.h" /* eat_space_end and so on */ +#include "parser_f.h" /* eat_space_end and so on */ #include "../mem/mem.h" #include "../ut.h" @@ -36,13 +36,13 @@ * Parse Identity header field */ -#define SP(_c) ((_c)=='\t' || (_c)==' ') -inline static int isendofhash (char* p, char* end) +#define SP(_c) ((_c) == '\t' || (_c) == ' ') +inline static int isendofhash(char *p, char *end) { /* new header line */ - if ((phash.s=pkg_malloc(phashend-pstart))) { + if(!(ib->hash.s = pkg_malloc(phashend - pstart))) { PKG_MEM_ERROR; return -2; } - ib->ballocated=1; + ib->ballocated = 1; memcpy(ib->hash.s, pstart, ib->hash.len); @@ -74,51 +73,52 @@ int movetomybuffer (char *pstart, } -void parse_identity(char *buffer, char* end, struct identity_body* ib) +void parse_identity(char *buffer, char *end, struct identity_body *ib) { - char *p=NULL, *pstart=NULL; + char *p = NULL, *pstart = NULL; - if (!buffer || !end || !ib) + if(!buffer || !end || !ib) goto error; - ib->error=PARSE_ERROR; + ib->error = PARSE_ERROR; /* if there is a '"' sign then we'll step over it */ *buffer == '"' ? (pstart = buffer + 1) : (pstart = buffer); - ib->hash.s=pstart; - ib->hash.len=0; + ib->hash.s = pstart; + ib->hash.len = 0; - for (p = pstart; p < end; p++) { + for(p = pstart; p < end; p++) { /* check the BASE64 alphabet */ - if (((*p >= 'a' && *p <='z') - || (*p >= 'A' && *p <='Z') - || (*p >= '0' && *p <='9') - || (*p == '+' || *p == '/' || *p == '='))) { - if (ib->ballocated) - ib->hash.s[ib->hash.len]=*p; + if(((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z') + || (*p >= '0' && *p <= '9') + || (*p == '+' || *p == '/' || *p == '='))) { + if(ib->ballocated) + ib->hash.s[ib->hash.len] = *p; ib->hash.len++; continue; } /* LWS */ - if (*p=='\n' && p+1ballocated && (movetomybuffer(pstart, end, p-1, ib))) + if(!ib->ballocated && (movetomybuffer(pstart, end, p - 1, ib))) goto error; /* p + 1 < end because 'continue' increases p so we'd skip \n we need after this for loop */ - for (p+=1; p + 1 < end && SP(*(p + 1)); p++); + for(p += 1; p + 1 < end && SP(*(p + 1)); p++) + ; continue; } - if (*p=='\r' && p+2ballocated && (movetomybuffer(pstart, end, p-1, ib))) + if(*p == '\r' && p + 2 < end && *(p + 1) == '\n' && SP(*(p + 2))) { + if(!ib->ballocated && (movetomybuffer(pstart, end, p - 1, ib))) goto error; - for (p+=2; p + 1 < end && SP(*(p + 1)); p++); + for(p += 2; p + 1 < end && SP(*(p + 1)); p++) + ; continue; } - if (isendofhash(p, end)) + if(isendofhash(p, end)) break; /* parse error */ @@ -126,47 +126,46 @@ void parse_identity(char *buffer, char* end, struct identity_body* ib) } /* this is the final quotation mark so we step over */ - ib->error=PARSE_OK; - return ; + ib->error = PARSE_OK; + return; parseerror: - LM_ERR("unexpected char [0x%X]: <<%.*s>> .\n", - *p,(int)(p-buffer), ZSW(buffer)); + LM_ERR("unexpected char [0x%X]: <<%.*s>> .\n", *p, (int)(p - buffer), + ZSW(buffer)); error: - return ; + return; } int parse_identity_header(struct sip_msg *msg) { - struct identity_body* identity_b; + struct identity_body *identity_b; - if ( !msg->identity - && (parse_headers(msg,HDR_IDENTITY_F,0)==-1 - || !msg->identity) ) { + if(!msg->identity + && (parse_headers(msg, HDR_IDENTITY_F, 0) == -1 + || !msg->identity)) { LM_ERR("bad msg or missing IDENTITY header\n"); goto error; } /* maybe the header is already parsed! */ - if (msg->identity->parsed) + if(msg->identity->parsed) return 0; - identity_b=pkg_malloc(sizeof(*identity_b)); - if (identity_b==0){ + identity_b = pkg_malloc(sizeof(*identity_b)); + if(identity_b == 0) { PKG_MEM_ERROR; goto error; } memset(identity_b, 0, sizeof(*identity_b)); parse_identity(msg->identity->body.s, - msg->identity->body.s + msg->identity->body.len+1, - identity_b); - if (identity_b->error==PARSE_ERROR){ + msg->identity->body.s + msg->identity->body.len + 1, identity_b); + if(identity_b->error == PARSE_ERROR) { free_identity(identity_b); goto error; } - msg->identity->parsed=(void*)identity_b; + msg->identity->parsed = (void *)identity_b; return 0; error: @@ -175,7 +174,7 @@ int parse_identity_header(struct sip_msg *msg) void free_identity(struct identity_body *ib) { - if (ib->ballocated) + if(ib->ballocated) pkg_free(ib->hash.s); pkg_free(ib); } diff --git a/src/core/parser/parse_identity.h b/src/core/parser/parse_identity.h index 134ce459725..df6afec7619 100644 --- a/src/core/parser/parse_identity.h +++ b/src/core/parser/parse_identity.h @@ -31,15 +31,16 @@ #include "../str.h" #include "msg_parser.h" -struct identity_body{ - int error; /*!< Error code */ - int ballocated; /*!< Does hash point to an allocated area */ +struct identity_body +{ + int error; /*!< Error code */ + int ballocated; /*!< Does hash point to an allocated area */ str hash; }; /*! \brief casting macro for accessing IDENTITY body */ -#define get_identity(p_msg) ((struct identity_body*)(p_msg)->identity->parsed) +#define get_identity(p_msg) ((struct identity_body *)(p_msg)->identity->parsed) /*! \brief diff --git a/src/core/parser/parse_identityinfo.c b/src/core/parser/parse_identityinfo.c index dc0aba5d9ba..fd5c80c6ed7 100644 --- a/src/core/parser/parse_identityinfo.c +++ b/src/core/parser/parse_identityinfo.c @@ -311,8 +311,8 @@ void parse_identityinfo(char *buffer, char *end, struct identityinfo_body *ii_b) parseerror: if(p < end) { - LM_ERR("unexpected char [%c/%d] in status %d - pos %d: [%.*s]\n", *p, *p, - status, (int)(p - buffer), (int)(p - buffer), buffer); + LM_ERR("unexpected char [%c/%d] in status %d - pos %d: [%.*s]\n", *p, + *p, status, (int)(p - buffer), (int)(p - buffer), buffer); } else { LM_ERR("unexpected end of buffer - status %d\n", status); } diff --git a/src/core/parser/parse_identityinfo.h b/src/core/parser/parse_identityinfo.h index 10cbe59e402..69a05220209 100644 --- a/src/core/parser/parse_identityinfo.h +++ b/src/core/parser/parse_identityinfo.h @@ -30,7 +30,8 @@ #include "../str.h" #include "msg_parser.h" -enum { +enum +{ II_START, II_URI_BEGIN, II_URI_DOMAIN, @@ -49,7 +50,8 @@ enum { II_ENDHEADER }; -enum { +enum +{ II_M_START, II_M_URI_BEGIN, II_M_URI_END, @@ -59,22 +61,25 @@ enum { II_M_TOKEN }; -struct identityinfo_body { - int error; /* Error code */ - str uri; /* URI */ - str domain; /* Domain part of the URI */ - str alg; /* Identity-Info header field MUST contain an 'alg' parameter */ +struct identityinfo_body +{ + int error; /* Error code */ + str uri; /* URI */ + str domain; /* Domain part of the URI */ + str alg; /* Identity-Info header field MUST contain an 'alg' parameter */ }; /* casting macro for accessing IDENTITY-INFO body */ -#define get_identityinfo(p_msg) ((struct identityinfo_body*)(p_msg)->identity_info->parsed) +#define get_identityinfo(p_msg) \ + ((struct identityinfo_body *)(p_msg)->identity_info->parsed) /* * Parse Identity-Info header field */ -void parse_identityinfo(char *buffer, char* end, struct identityinfo_body *ii_b); +void parse_identityinfo( + char *buffer, char *end, struct identityinfo_body *ii_b); int parse_identityinfo_header(struct sip_msg *msg); /* diff --git a/src/core/parser/parse_methods.c b/src/core/parser/parse_methods.c index 6242e886670..60d55e6b017 100644 --- a/src/core/parser/parse_methods.c +++ b/src/core/parser/parse_methods.c @@ -35,152 +35,150 @@ */ static int token_char(char _c) { - return (_c >= 65 && _c <= 90) || /* upper alpha */ - (_c >= 97 && _c <= 122) || /* lower aplha */ - (_c >= 48 && _c <= 57) || /* digits */ - (_c == '-') || (_c == '.') || (_c == '!') || (_c == '%') || - (_c == '*') || (_c == '_') || (_c == '+') || (_c == '`') || - (_c == '\'') || (_c == '~'); + return (_c >= 65 && _c <= 90) || /* upper alpha */ + (_c >= 97 && _c <= 122) || /* lower aplha */ + (_c >= 48 && _c <= 57) || /* digits */ + (_c == '-') || (_c == '.') || (_c == '!') || (_c == '%') + || (_c == '*') || (_c == '_') || (_c == '+') || (_c == '`') + || (_c == '\'') || (_c == '~'); } - /*! \brief Parse a string containing a method. * * Parse a method pointed by s & assign its enum bit to method. The string * _must_ contain _only_ the method (without trailing or heading whitespace). * \return 0 on success, -1 on error */ -int parse_method_name(const str* const s, enum request_method* const method) +int parse_method_name(const str *const s, enum request_method *const method) { - if (unlikely(!s || !method)) { + if(unlikely(!s || !method)) { LM_ERR("Invalid parameter value\n"); return -1; } - if (unlikely(!s->len || (s->s==0))) { + if(unlikely(!s->len || (s->s == 0))) { LM_DBG("No input\n"); *method = METHOD_OTHER; return 0; } - switch ((s->s)[0]) { + switch((s->s)[0]) { /* ordered after probability of apparition on a normal proxy */ case 'R': case 'r': - if (likely((s->len == 8) && - !strncasecmp(s->s + 1, "egister", 7))) { + if(likely((s->len == 8) && !strncasecmp(s->s + 1, "egister", 7))) { *method = METHOD_REGISTER; return 0; } - if (likely((s->len==5) && !strncasecmp(s->s + 1, "efer", 4))) { + if(likely((s->len == 5) && !strncasecmp(s->s + 1, "efer", 4))) { *method = METHOD_REFER; return 0; } break; case 'A': case 'a': - if (likely((s->len==3) && !strncasecmp(s->s + 1, "ck", 2))) { + if(likely((s->len == 3) && !strncasecmp(s->s + 1, "ck", 2))) { *method = METHOD_ACK; return 0; } break; case 'I': case 'i': - if (likely((s->len==6) && !strncasecmp(s->s + 1, "nvite", 5))){ + if(likely((s->len == 6) && !strncasecmp(s->s + 1, "nvite", 5))) { *method = METHOD_INVITE; return 0; } - if (likely((s->len==4) && !strncasecmp(s->s + 1, "nfo", 3))) { + if(likely((s->len == 4) && !strncasecmp(s->s + 1, "nfo", 3))) { *method = METHOD_INFO; return 0; } break; case 'P': case 'p': - if (likely((s->len==5) && !strncasecmp(s->s + 1, "rack", 4))) { + if(likely((s->len == 5) && !strncasecmp(s->s + 1, "rack", 4))) { *method = METHOD_PRACK; return 0; } - if (likely((s->len==7) && !strncasecmp(s->s + 1, "ublish", 6))) { + if(likely((s->len == 7) && !strncasecmp(s->s + 1, "ublish", 6))) { *method = METHOD_PUBLISH; return 0; } - if (likely((s->len==4) && !strncasecmp(s->s + 1, "ost", 3))) { + if(likely((s->len == 4) && !strncasecmp(s->s + 1, "ost", 3))) { *method = METHOD_POST; return 0; } - if (likely((s->len==3) && !strncasecmp(s->s + 1, "ut", 2))) { + if(likely((s->len == 3) && !strncasecmp(s->s + 1, "ut", 2))) { *method = METHOD_PUT; return 0; } break; case 'C': case 'c': - if (likely((s->len==6) && !strncasecmp(s->s + 1, "ancel", 5))) { + if(likely((s->len == 6) && !strncasecmp(s->s + 1, "ancel", 5))) { *method = METHOD_CANCEL; return 0; } break; case 'B': case 'b': - if (likely((s->len==3) && !strncasecmp(s->s + 1, "ye", 2))) { + if(likely((s->len == 3) && !strncasecmp(s->s + 1, "ye", 2))) { *method = METHOD_BYE; return 0; } break; case 'M': case 'm': - if (likely((s->len==7) && !strncasecmp(s->s + 1, "essage", 6))) { + if(likely((s->len == 7) && !strncasecmp(s->s + 1, "essage", 6))) { *method = METHOD_MESSAGE; return 0; } break; case 'O': case 'o': - if (likely((s->len==7) && !strncasecmp(s->s + 1, "ptions", 6))) { + if(likely((s->len == 7) && !strncasecmp(s->s + 1, "ptions", 6))) { *method = METHOD_OPTIONS; return 0; } break; case 'S': case 's': - if (likely((s->len==9) && !strncasecmp(s->s + 1, "ubscribe", 8))) { + if(likely((s->len == 9) && !strncasecmp(s->s + 1, "ubscribe", 8))) { *method = METHOD_SUBSCRIBE; return 0; } break; case 'N': case 'n': - if (likely((s->len==6) && !strncasecmp(s->s + 1, "otify", 5))){ + if(likely((s->len == 6) && !strncasecmp(s->s + 1, "otify", 5))) { *method = METHOD_NOTIFY; return 0; } break; case 'U': case 'u': - if (likely((s->len==6) && !strncasecmp(s->s + 1, "pdate", 5))){ + if(likely((s->len == 6) && !strncasecmp(s->s + 1, "pdate", 5))) { *method = METHOD_UPDATE; return 0; } break; case 'D': case 'd': - if (likely((s->len==6) && !strncasecmp(s->s + 1, "elete", 5))){ + if(likely((s->len == 6) && !strncasecmp(s->s + 1, "elete", 5))) { *method = METHOD_DELETE; return 0; } break; case 'G': case 'g': - if (likely((s->len==3) && !strncasecmp(s->s + 1, "et", 2))){ + if(likely((s->len == 3) && !strncasecmp(s->s + 1, "et", 2))) { *method = METHOD_GET; return 0; } break; case 'K': case 'k': - if (likely((s->len==4) && !strncasecmp(s->s + 1, "dmq", 3))){ + if(likely((s->len == 4) && !strncasecmp(s->s + 1, "dmq", 3))) { *method = METHOD_KDMQ; return 0; } @@ -194,31 +192,31 @@ int parse_method_name(const str* const s, enum request_method* const method) } - /*! \brief * Parse a method pointed by _next, assign its enum bit to _method, and update * _next past the method. Returns 1 if parse succeeded and 0 otherwise. */ -static int parse_method_advance(str* const _next, enum request_method* const _method) +static int parse_method_advance( + str *const _next, enum request_method *const _method) { - char* end; + char *end; - if (unlikely(!_next || !_method)) { + if(unlikely(!_next || !_method)) { LM_ERR("Invalid parameter value\n"); return 0; } - if (unlikely(!_next->len || !_next->s)) { + if(unlikely(!_next->len || !_next->s)) { DBG("No input\n"); *_method = METHOD_OTHER; return 1; } - end=_next->s+_next->len; + end = _next->s + _next->len; - switch ((_next->s)[0]) { + switch((_next->s)[0]) { case 'A': case 'a': - if ((_next->len > 2) && !strncasecmp(_next->s + 1, "ck", 2)) { + if((_next->len > 2) && !strncasecmp(_next->s + 1, "ck", 2)) { *_method = METHOD_ACK; _next->len -= 3; _next->s += 3; @@ -229,7 +227,7 @@ static int parse_method_advance(str* const _next, enum request_method* const _me case 'B': case 'b': - if ((_next->len > 2) && !strncasecmp(_next->s + 1, "ye", 2)) { + if((_next->len > 2) && !strncasecmp(_next->s + 1, "ye", 2)) { *_method = METHOD_BYE; _next->len -= 3; _next->s += 3; @@ -240,7 +238,7 @@ static int parse_method_advance(str* const _next, enum request_method* const _me case 'C': case 'c': - if ((_next->len > 5) && !strncasecmp(_next->s + 1, "ancel", 5)) { + if((_next->len > 5) && !strncasecmp(_next->s + 1, "ancel", 5)) { *_method = METHOD_CANCEL; _next->len -= 6; _next->s += 6; @@ -251,16 +249,16 @@ static int parse_method_advance(str* const _next, enum request_method* const _me case 'I': case 'i': - if ((_next->len > 3) && - ((*(_next->s + 1) == 'N') || (*(_next->s + 1) == 'n'))) { - if (!strncasecmp(_next->s + 2, "fo", 2)) { + if((_next->len > 3) + && ((*(_next->s + 1) == 'N') || (*(_next->s + 1) == 'n'))) { + if(!strncasecmp(_next->s + 2, "fo", 2)) { *_method = METHOD_INFO; _next->len -= 4; _next->s += 4; goto found; } - if ((_next->len > 5) && !strncasecmp(_next->s + 2, "vite", 4)) { + if((_next->len > 5) && !strncasecmp(_next->s + 2, "vite", 4)) { *_method = METHOD_INVITE; _next->len -= 6; _next->s += 6; @@ -271,7 +269,7 @@ static int parse_method_advance(str* const _next, enum request_method* const _me case 'M': case 'm': - if ((_next->len > 6) && !strncasecmp(_next->s + 1, "essage", 6)) { + if((_next->len > 6) && !strncasecmp(_next->s + 1, "essage", 6)) { *_method = METHOD_MESSAGE; _next->len -= 7; _next->s += 7; @@ -282,7 +280,7 @@ static int parse_method_advance(str* const _next, enum request_method* const _me case 'N': case 'n': - if ((_next->len > 5) && !strncasecmp(_next->s + 1, "otify", 5)) { + if((_next->len > 5) && !strncasecmp(_next->s + 1, "otify", 5)) { *_method = METHOD_NOTIFY; _next->len -= 6; _next->s += 6; @@ -293,7 +291,7 @@ static int parse_method_advance(str* const _next, enum request_method* const _me case 'O': case 'o': - if ((_next->len > 6) && !strncasecmp(_next->s + 1, "ptions", 6)) { + if((_next->len > 6) && !strncasecmp(_next->s + 1, "ptions", 6)) { *_method = METHOD_OPTIONS; _next->len -= 7; _next->s += 7; @@ -304,25 +302,25 @@ static int parse_method_advance(str* const _next, enum request_method* const _me case 'P': case 'p': - if ((_next->len > 4) && !strncasecmp(_next->s + 1, "rack", 4)) { + if((_next->len > 4) && !strncasecmp(_next->s + 1, "rack", 4)) { *_method = METHOD_PRACK; _next->len -= 5; _next->s += 5; goto found; } - if ((_next->len > 6) && !strncasecmp(_next->s + 1, "ublish", 6)) { + if((_next->len > 6) && !strncasecmp(_next->s + 1, "ublish", 6)) { *_method = METHOD_PUBLISH; _next->len -= 7; _next->s += 7; goto found; } - if ((_next->len > 3) && !strncasecmp(_next->s + 1, "ost", 3)) { + if((_next->len > 3) && !strncasecmp(_next->s + 1, "ost", 3)) { *_method = METHOD_POST; _next->len -= 4; _next->s += 4; goto found; } - if ((_next->len > 2) && !strncasecmp(_next->s + 1, "ut", 2)) { + if((_next->len > 2) && !strncasecmp(_next->s + 1, "ut", 2)) { *_method = METHOD_PUT; _next->len -= 3; _next->s += 3; @@ -332,16 +330,17 @@ static int parse_method_advance(str* const _next, enum request_method* const _me case 'R': case 'r': - if ((_next->len > 4) && - ((*(_next->s + 1) == 'E') || (*(_next->s + 1) == 'e'))) { - if (!strncasecmp(_next->s + 2, "fer", 3)) { + if((_next->len > 4) + && ((*(_next->s + 1) == 'E') || (*(_next->s + 1) == 'e'))) { + if(!strncasecmp(_next->s + 2, "fer", 3)) { *_method = METHOD_REFER; _next->len -= 5; _next->s += 5; goto found; } - if ((_next->len > 7) && !strncasecmp(_next->s + 2, "gister", 6)) { + if((_next->len > 7) + && !strncasecmp(_next->s + 2, "gister", 6)) { *_method = METHOD_REGISTER; _next->len -= 8; _next->s += 8; @@ -352,7 +351,7 @@ static int parse_method_advance(str* const _next, enum request_method* const _me case 'S': case 's': - if ((_next->len > 8) && !strncasecmp(_next->s + 1, "ubscribe", 8)) { + if((_next->len > 8) && !strncasecmp(_next->s + 1, "ubscribe", 8)) { *_method = METHOD_SUBSCRIBE; _next->len -= 9; _next->s += 9; @@ -363,7 +362,7 @@ static int parse_method_advance(str* const _next, enum request_method* const _me case 'U': case 'u': - if ((_next->len > 5) && !strncasecmp(_next->s + 1, "pdate", 5)) { + if((_next->len > 5) && !strncasecmp(_next->s + 1, "pdate", 5)) { *_method = METHOD_UPDATE; _next->len -= 6; _next->s += 6; @@ -373,7 +372,7 @@ static int parse_method_advance(str* const _next, enum request_method* const _me } case 'D': case 'd': - if ((_next->len>5) && !strncasecmp(_next->s + 1, "elete", 5)){ + if((_next->len > 5) && !strncasecmp(_next->s + 1, "elete", 5)) { *_method = METHOD_DELETE; _next->len -= 6; _next->s += 6; @@ -383,7 +382,7 @@ static int parse_method_advance(str* const _next, enum request_method* const _me } case 'G': case 'g': - if ((_next->len>2) && !strncasecmp(_next->s + 1, "et", 2)){ + if((_next->len > 2) && !strncasecmp(_next->s + 1, "et", 2)) { *_method = METHOD_GET; _next->len -= 3; _next->s += 3; @@ -393,7 +392,7 @@ static int parse_method_advance(str* const _next, enum request_method* const _me } case 'K': case 'k': - if ((_next->len>3) && !strncasecmp(_next->s + 1, "dmq", 3)){ + if((_next->len > 3) && !strncasecmp(_next->s + 1, "dmq", 3)) { *_method = METHOD_KDMQ; _next->len -= 4; _next->s += 4; @@ -406,11 +405,11 @@ static int parse_method_advance(str* const _next, enum request_method* const _me } unknown: - if (token_char(*(_next->s))) { + if(token_char(*(_next->s))) { do { _next->s++; _next->len--; - } while (_next->len && token_char(*(_next->s))); + } while(_next->len && token_char(*(_next->s))); *_method = METHOD_OTHER; return 1; } else { @@ -418,7 +417,7 @@ static int parse_method_advance(str* const _next, enum request_method* const _me } found: /* check if the method really ends here (if not return 0) */ - return (_next->s>=end) || (!token_char(*(_next->s))); + return (_next->s >= end) || (!token_char(*(_next->s))); } @@ -426,14 +425,14 @@ static int parse_method_advance(str* const _next, enum request_method* const _me * Parse comma separated list of methods pointed by _body and assign their * enum bits to _methods. Returns 0 on success and -1 on failure. */ -int parse_methods(const str* const _body, unsigned int* const _methods) +int parse_methods(const str *const _body, unsigned int *const _methods) { str next; unsigned int method; - method=0; /* fixes silly gcc 4.x warning */ + method = 0; /* fixes silly gcc 4.x warning */ - if (!_body || !_methods) { + if(!_body || !_methods) { LM_ERR("Invalid parameter value\n"); return -1; } @@ -445,12 +444,12 @@ int parse_methods(const str* const _body, unsigned int* const _methods) *_methods = 0; - if (next.len == 0) { + if(next.len == 0) { return 0; } - while (1) { - if (parse_method_advance(&next, &method)) { + while(1) { + if(parse_method_advance(&next, &method)) { *_methods |= method; } else { LM_ERR("Invalid method\n"); @@ -458,12 +457,12 @@ int parse_methods(const str* const _body, unsigned int* const _methods) } trim_leading(&next); - if (next.len) { - if (next.s[0] == ',') { + if(next.len) { + if(next.s[0] == ',') { next.len--; next.s++; trim_leading(&next); - if (next.len == 0) { + if(next.len == 0) { LM_ERR("Method expected\n"); return 0; } diff --git a/src/core/parser/parse_methods.h b/src/core/parser/parse_methods.h index 75207d395c5..76ce0c7c151 100644 --- a/src/core/parser/parse_methods.h +++ b/src/core/parser/parse_methods.h @@ -13,8 +13,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ @@ -33,13 +33,13 @@ #define ALL_METHODS 0xffffffff -/* +/* * Parse comma separated list of methods pointed by _body and assign their * enum bits to _methods. Returns 1 on success and 0 on failure. */ -int parse_methods(const str* const _body, unsigned int* const _methods); +int parse_methods(const str *const _body, unsigned int *const _methods); -int parse_method_name(const str* const s, enum request_method* const method); +int parse_method_name(const str *const s, enum request_method *const method); #endif /* PARSE_METHODS_H */ diff --git a/src/core/parser/parse_nameaddr.c b/src/core/parser/parse_nameaddr.c index d44c9279e09..dcbc0c48581 100644 --- a/src/core/parser/parse_nameaddr.c +++ b/src/core/parser/parse_nameaddr.c @@ -1,4 +1,4 @@ -/* +/* * Copyright (C) 2001-2003 FhG Fokus * * This file is part of Kamailio, a free SIP server. @@ -13,8 +13,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ @@ -36,33 +36,33 @@ * Parse name-addr part, the given string can be longer, * parsing will stop when closing > is found */ -int parse_nameaddr(str* _s, name_addr_t* _a) +int parse_nameaddr(str *_s, name_addr_t *_a) { - char* uri_end; + char *uri_end; - if (!_s || !_a) { + if(!_s || !_a) { return -1; } _a->name.s = _s->s; - _a->uri.s = find_not_quoted(_s, '<'); - if (_a->uri.s) { + _a->uri.s = find_not_quoted(_s, '<'); + if(_a->uri.s) { _a->name.len = _a->uri.s - _a->name.s; _a->uri.s++; /* We will skip < character */ } else { return -3; } - + _a->uri.len = _s->len - _a->name.len - 1; uri_end = find_not_quoted(&_a->uri, '>'); - - if (!uri_end) { + + if(!uri_end) { return -4; } /* Total length of the field including <> */ _a->len = uri_end - _a->name.s + 1; - + _a->uri.len = uri_end - _a->uri.s; return 0; } @@ -71,7 +71,7 @@ int parse_nameaddr(str* _s, name_addr_t* _a) /*! \brief * Print a name-addr structure, just for debugging */ -void print_nameaddr(FILE* _o, name_addr_t* _a) +void print_nameaddr(FILE *_o, name_addr_t *_a) { fprintf(_o, "---name-addr---\n"); fprintf(_o, "name: '%.*s'\n", _a->name.len, ZSW(_a->name.s)); diff --git a/src/core/parser/parse_nameaddr.h b/src/core/parser/parse_nameaddr.h index 0c566e941f2..34d3749fe23 100644 --- a/src/core/parser/parse_nameaddr.h +++ b/src/core/parser/parse_nameaddr.h @@ -1,4 +1,4 @@ -/* +/* * Copyright (C) 2001-2003 FhG Fokus * * This file is part of Kamailio, a free SIP server. @@ -13,8 +13,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ @@ -34,10 +34,11 @@ /*! \brief * Name-addr structure, see RFC3261 for more details */ -typedef struct name_addr { - str name; /*!< Display name part */ - str uri; /*!< Uri part without surrounding <> */ - int len; /*!< Total length of the field (including all +typedef struct name_addr +{ + str name; /*!< Display name part */ + str uri; /*!< Uri part without surrounding <> */ + int len; /*!< Total length of the field (including all * whitechars present in the parsed message */ } name_addr_t; @@ -46,13 +47,13 @@ typedef struct name_addr { * Parse name-addr part, the given string can be longer, * parsing will stop when closing > is found */ -int parse_nameaddr(str* _s, name_addr_t* _a); +int parse_nameaddr(str *_s, name_addr_t *_a); /*! \brief * Print a name-addr structure, just for debugging */ -void print_nameaddr(FILE* _o, name_addr_t* _a); +void print_nameaddr(FILE *_o, name_addr_t *_a); #endif /* PARSE_NAMEADDR_H */ diff --git a/src/core/parser/parse_option_tags.c b/src/core/parser/parse_option_tags.c index 6fedcefffe8..c47a36a723d 100644 --- a/src/core/parser/parse_option_tags.c +++ b/src/core/parser/parse_option_tags.c @@ -24,7 +24,7 @@ static inline void free_option_tag(struct option_tag_body **otb) { - if (otb && *otb) { + if(otb && *otb) { pkg_free(*otb); *otb = 0; } @@ -33,6 +33,6 @@ static inline void free_option_tag(struct option_tag_body **otb) void hf_free_option_tag(void *parsed) { struct option_tag_body *otb; - otb = (struct option_tag_body *) parsed; + otb = (struct option_tag_body *)parsed; free_option_tag(&otb); } diff --git a/src/core/parser/parse_option_tags.h b/src/core/parser/parse_option_tags.h index 5a19ca62f13..ee2ece3c76b 100644 --- a/src/core/parser/parse_option_tags.h +++ b/src/core/parser/parse_option_tags.h @@ -1,6 +1,6 @@ /* * Copyright (C) 2006 Andreas Granig - * + * * This file is part of Kamailio, a free SIP server. * * Kamailio is free software; you can redistribute it and/or modify @@ -26,47 +26,49 @@ #include "hf.h" #include "keys.h" -#define F_OPTION_TAG_PATH (1 << 0) -#define F_OPTION_TAG_100REL (1 << 1) -#define F_OPTION_TAG_TIMER (1 << 2) -#define F_OPTION_TAG_EVENTLIST (1 << 3) -#define F_OPTION_TAG_GRUU (1 << 4) -#define F_OPTION_TAG_OUTBOUND (1 << 5) +#define F_OPTION_TAG_PATH (1 << 0) +#define F_OPTION_TAG_100REL (1 << 1) +#define F_OPTION_TAG_TIMER (1 << 2) +#define F_OPTION_TAG_EVENTLIST (1 << 3) +#define F_OPTION_TAG_GRUU (1 << 4) +#define F_OPTION_TAG_OUTBOUND (1 << 5) -#define OPTION_TAG_PATH_STR "path" -#define OPTION_TAG_PATH_LEN (sizeof(OPTION_TAG_PATH_STR)-1) +#define OPTION_TAG_PATH_STR "path" +#define OPTION_TAG_PATH_LEN (sizeof(OPTION_TAG_PATH_STR) - 1) /* RFC 3262 (PRACK) */ -#define OPTION_TAG_100REL_STR "100rel" -#define OPTION_TAG_100REL_LEN (sizeof(OPTION_TAG_100REL_STR)-1) +#define OPTION_TAG_100REL_STR "100rel" +#define OPTION_TAG_100REL_LEN (sizeof(OPTION_TAG_100REL_STR) - 1) /* RFC 4028 */ -#define OPTION_TAG_TIMER_STR "timer" -#define OPTION_TAG_TIMER_LEN (sizeof(OPTION_TAG_TIMER_STR)-1) +#define OPTION_TAG_TIMER_STR "timer" +#define OPTION_TAG_TIMER_LEN (sizeof(OPTION_TAG_TIMER_STR) - 1) /* RFC 4662 (RLS) */ -#define OPTION_TAG_EVENTLIST_STR "eventlist" -#define OPTION_TAG_EVENTLIST_LEN (sizeof(OPTION_TAG_EVENTLIST_STR)-1) +#define OPTION_TAG_EVENTLIST_STR "eventlist" +#define OPTION_TAG_EVENTLIST_LEN (sizeof(OPTION_TAG_EVENTLIST_STR) - 1) /* RFC 5627 */ -#define OPTION_TAG_GRUU_STR "gruu" -#define OPTION_TAG_GRUU_LEN (sizeof(OPTION_TAG_GRUU_STR)-1) +#define OPTION_TAG_GRUU_STR "gruu" +#define OPTION_TAG_GRUU_LEN (sizeof(OPTION_TAG_GRUU_STR) - 1) /* RFC 5626 */ -#define OPTION_TAG_OUTBOUND_STR "outbound" -#define OPTION_TAG_OUTBOUND_LEN (sizeof(OPTION_TAG_OUTBOUND_STR)-1) +#define OPTION_TAG_OUTBOUND_STR "outbound" +#define OPTION_TAG_OUTBOUND_LEN (sizeof(OPTION_TAG_OUTBOUND_STR) - 1) -struct option_tag_body { - hf_parsed_free_f hfree; /* function to free the content */ - unsigned int option_tags; /* option-tag mask for the current hdr */ - unsigned int option_tags_all; /* option-tag mask for the all hdr - * - it's set only for the first hdr in +struct option_tag_body +{ + hf_parsed_free_f hfree; /* function to free the content */ + unsigned int option_tags; /* option-tag mask for the current hdr */ + unsigned int option_tags_all; /* option-tag mask for the all hdr + * - it's set only for the first hdr in * sibling list*/ }; -#define IS_DELIM(c) (*(c) == ' ' || *(c) == '\t' || *(c) == '\r' || *(c) == '\n' || *(c) == ',') +#define IS_DELIM(c) \ + (*(c) == ' ' || *(c) == '\t' || *(c) == '\r' || *(c) == '\n' || *(c) == ',') /* from parser/parse_hname2.c: */ #define LOWER_BYTE(b) ((b) | 0x20) @@ -79,7 +81,7 @@ struct option_tag_body { */ static inline int parse_option_tag_body(str *body, unsigned int *tags) { - register char* p; + register char *p; register unsigned int val; int len, pos = 0; int case_found; @@ -89,76 +91,81 @@ static inline int parse_option_tag_body(str *body, unsigned int *tags) p = body->s; len = body->len; - while (pos < len) { + while(pos < len) { /* skip spaces and commas */ - for (; pos < len && IS_DELIM(p); ++pos, ++p); + for(; pos < len && IS_DELIM(p); ++pos, ++p) + ; val = LOWER_DWORD(READ(p)); case_found = 0; - switch (val) { + switch(val) { /* "path" */ case _path_: - if(pos + 4 <= len && IS_DELIM(p+4)) { + if(pos + 4 <= len && IS_DELIM(p + 4)) { *tags |= F_OPTION_TAG_PATH; - pos += 5; p += 5; + pos += 5; + p += 5; case_found = 1; } break; /* "100rel" */ case _100r_: - if ( pos+6 <= len - && LOWER_BYTE(*(p+4))=='e' && LOWER_BYTE(*(p+5))=='l' - && IS_DELIM(p+6)) { + if(pos + 6 <= len && LOWER_BYTE(*(p + 4)) == 'e' + && LOWER_BYTE(*(p + 5)) == 'l' && IS_DELIM(p + 6)) { *tags |= F_OPTION_TAG_100REL; pos += OPTION_TAG_100REL_LEN + 1; - p += OPTION_TAG_100REL_LEN + 1; + p += OPTION_TAG_100REL_LEN + 1; case_found = 1; } break; /* "timer" */ case _time_: - if ( pos+5 <= len && LOWER_BYTE(*(p+4))=='r' - && IS_DELIM(p+5) ) { + if(pos + 5 <= len && LOWER_BYTE(*(p + 4)) == 'r' + && IS_DELIM(p + 5)) { *tags |= F_OPTION_TAG_TIMER; pos += OPTION_TAG_TIMER_LEN + 1; - p += OPTION_TAG_TIMER_LEN + 1; + p += OPTION_TAG_TIMER_LEN + 1; case_found = 1; } break; } - if(case_found==0) { + if(case_found == 0) { /* extra require or unknown */ - if(pos+OPTION_TAG_EVENTLIST_LEN<=len + if(pos + OPTION_TAG_EVENTLIST_LEN <= len && strncasecmp(p, OPTION_TAG_EVENTLIST_STR, - OPTION_TAG_EVENTLIST_LEN)==0 - && IS_DELIM(p+OPTION_TAG_EVENTLIST_LEN) ) { + OPTION_TAG_EVENTLIST_LEN) + == 0 + && IS_DELIM(p + OPTION_TAG_EVENTLIST_LEN)) { *tags |= F_OPTION_TAG_EVENTLIST; pos += OPTION_TAG_EVENTLIST_LEN + 1; - p += OPTION_TAG_EVENTLIST_LEN + 1; - } else if(pos+OPTION_TAG_GRUU_LEN<=len - && strncasecmp(p, OPTION_TAG_GRUU_STR, - OPTION_TAG_GRUU_LEN)==0 - && IS_DELIM(p+OPTION_TAG_GRUU_LEN)) { + p += OPTION_TAG_EVENTLIST_LEN + 1; + } else if(pos + OPTION_TAG_GRUU_LEN <= len + && strncasecmp( + p, OPTION_TAG_GRUU_STR, OPTION_TAG_GRUU_LEN) + == 0 + && IS_DELIM(p + OPTION_TAG_GRUU_LEN)) { *tags |= F_OPTION_TAG_GRUU; pos += OPTION_TAG_GRUU_LEN + 1; - p += OPTION_TAG_GRUU_LEN + 1; - } else if(pos+OPTION_TAG_OUTBOUND_LEN<=len - && strncasecmp(p, OPTION_TAG_OUTBOUND_STR, - OPTION_TAG_OUTBOUND_LEN)==0 - && IS_DELIM(p+OPTION_TAG_OUTBOUND_LEN)) { + p += OPTION_TAG_GRUU_LEN + 1; + } else if(pos + OPTION_TAG_OUTBOUND_LEN <= len + && strncasecmp(p, OPTION_TAG_OUTBOUND_STR, + OPTION_TAG_OUTBOUND_LEN) + == 0 + && IS_DELIM(p + OPTION_TAG_OUTBOUND_LEN)) { *tags |= F_OPTION_TAG_OUTBOUND; pos += OPTION_TAG_OUTBOUND_LEN + 1; - p += OPTION_TAG_OUTBOUND_LEN + 1; + p += OPTION_TAG_OUTBOUND_LEN + 1; } else { /* unknown (not needed) - skip element */ - for (; pos < len && !IS_DELIM(p); ++pos, ++p); + for(; pos < len && !IS_DELIM(p); ++pos, ++p) + ; } } } - + return 0; } diff --git a/src/core/parser/parse_param.c b/src/core/parser/parse_param.c index 8d789fa5687..698c0a9b47d 100644 --- a/src/core/parser/parse_param.c +++ b/src/core/parser/parse_param.c @@ -79,8 +79,8 @@ static inline void parse_event_dialog_class(param_hooks_t *h, param_t *p) case 'i': case 'I': if((p->name.len == 27) - && (!strncasecmp(p->name.s + 1, - "nclude-session-description", 26))) { + && (!strncasecmp( + p->name.s + 1, "nclude-session-description", 26))) { p->type = P_ISD; h->event_dialog.include_session_description = p; } @@ -154,7 +154,7 @@ static inline void parse_contact_class(param_hooks_t *_h, param_t *_p) _p->type = P_RECEIVED; _h->contact.received = _p; } else if((_p->name.len == 6) - && (!strncasecmp(_p->name.s + 1, "eg-id", 5))) { + && (!strncasecmp(_p->name.s + 1, "eg-id", 5))) { _p->type = P_REG_ID; _h->contact.reg_id = _p; } @@ -175,8 +175,8 @@ static inline void parse_contact_class(param_hooks_t *_h, param_t *_p) break; case 'f': case 'F': - if ((_p->name.len == 5) && - (!strncasecmp(_p->name.s + 1, "lags", 4))) { + if((_p->name.len == 5) + && (!strncasecmp(_p->name.s + 1, "lags", 4))) { _p->type = P_FLAGS; _h->contact.flags = _p; } @@ -249,7 +249,7 @@ static inline void parse_uri_class(param_hooks_t *_h, param_t *_p) _p->type = P_DSTIP; _h->uri.dstip = _p; } else if((_p->name.len == 7) - && (!strncasecmp(_p->name.s + 1, "stport", 6))) { + && (!strncasecmp(_p->name.s + 1, "stport", 6))) { _p->type = P_DSTPORT; _h->uri.dstport = _p; } @@ -584,7 +584,7 @@ int parse_params2( memset(_h, 0, sizeof(param_hooks_t)); *_p = 0; - if(!_s->s || _s->len<=0) { /* no parameters at all -- we're done */ + if(!_s->s || _s->len <= 0) { /* no parameters at all -- we're done */ LM_DBG("empty uri params, skipping\n"); return 0; } @@ -779,7 +779,7 @@ static inline int do_duplicate_params(param_t **_n, param_t *_p, int _shm) t = (param_t *)pkg_malloc(sizeof(param_t)); } if(!t) { - if (_shm) { + if(_shm) { SHM_MEM_ERROR; } else { PKG_MEM_ERROR; diff --git a/src/core/parser/parse_param.h b/src/core/parser/parse_param.h index ebb3ac56d6e..f68bfcecc51 100644 --- a/src/core/parser/parse_param.h +++ b/src/core/parser/parse_param.h @@ -1,4 +1,4 @@ -/* +/* * Generic Parameter Parser * * Copyright (C) 2001-2003 FhG Fokus @@ -15,8 +15,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ @@ -38,102 +38,109 @@ /*! \brief * Supported types of parameters */ -typedef enum ptype { +typedef enum ptype +{ P_OTHER = 0, /*!< Unknown parameter */ - P_Q, /*!< Contact: q parameter */ - P_EXPIRES, /*!< Contact: expires parameter */ - P_METHODS, /*!< Contact: methods parameter */ - P_RECEIVED, /*!< Contact: received parameter */ - P_FLAGS, /*!< Contact: flags parameter */ + P_Q, /*!< Contact: q parameter */ + P_EXPIRES, /*!< Contact: expires parameter */ + P_METHODS, /*!< Contact: methods parameter */ + P_RECEIVED, /*!< Contact: received parameter */ + P_FLAGS, /*!< Contact: flags parameter */ P_TRANSPORT, /*!< URI: transport parameter */ - P_LR, /*!< URI: lr parameter */ - P_R2, /*!< URI: r2 parameter (ser specific) */ - P_MADDR, /*!< URI: maddr parameter */ - P_TTL, /*!< URI: ttl parameter */ - P_DSTIP, /*!< URI: dstip parameter */ - P_DSTPORT, /*!< URi: dstport parameter */ - P_INSTANCE, /*!< Contact: sip.instance parameter */ - P_REG_ID, /*!< Contact: reg-id parameter */ - P_FTAG, /*!< URI: ftag parameter */ - P_CALL_ID, /*!< Dialog event package: call-id */ - P_FROM_TAG, /*!< Dialog event package: from-tag */ - P_TO_TAG, /*!< Dialog event package: to-tag */ - P_ISD, /*!< Dialog event package: include-session-description */ - P_SLA, /*!< Dialog event package: sla */ - P_MA, /*!< Dialog event package: ma */ - P_OB /*!< Contact|URI: ob parameter */ + P_LR, /*!< URI: lr parameter */ + P_R2, /*!< URI: r2 parameter (ser specific) */ + P_MADDR, /*!< URI: maddr parameter */ + P_TTL, /*!< URI: ttl parameter */ + P_DSTIP, /*!< URI: dstip parameter */ + P_DSTPORT, /*!< URi: dstport parameter */ + P_INSTANCE, /*!< Contact: sip.instance parameter */ + P_REG_ID, /*!< Contact: reg-id parameter */ + P_FTAG, /*!< URI: ftag parameter */ + P_CALL_ID, /*!< Dialog event package: call-id */ + P_FROM_TAG, /*!< Dialog event package: from-tag */ + P_TO_TAG, /*!< Dialog event package: to-tag */ + P_ISD, /*!< Dialog event package: include-session-description */ + P_SLA, /*!< Dialog event package: sla */ + P_MA, /*!< Dialog event package: ma */ + P_OB /*!< Contact|URI: ob parameter */ } ptype_t; /*! \brief * Class of parameters */ -typedef enum pclass { - CLASS_ANY = 0, /*!< Any parameters, well-known hooks will be not used */ - CLASS_CONTACT, /*!< Contact parameters */ - CLASS_URI, /*!< URI parameters */ - CLASS_EVENT_DIALOG /*!< Event dialog parameters */ +typedef enum pclass +{ + CLASS_ANY = 0, /*!< Any parameters, well-known hooks will be not used */ + CLASS_CONTACT, /*!< Contact parameters */ + CLASS_URI, /*!< URI parameters */ + CLASS_EVENT_DIALOG /*!< Event dialog parameters */ } pclass_t; /*! \brief * Structure representing a parameter */ -typedef struct param { - ptype_t type; /*!< Type of the parameter */ - str name; /*!< Parameter name */ - str body; /*!< Parameter body */ - int len; /*!< Total length of the parameter including = and quotes */ - struct param* next; /*!< Next parameter in the list */ +typedef struct param +{ + ptype_t type; /*!< Type of the parameter */ + str name; /*!< Parameter name */ + str body; /*!< Parameter body */ + int len; /*!< Total length of the parameter including = and quotes */ + struct param *next; /*!< Next parameter in the list */ } param_t; /*! \brief * Hooks to well known parameters for contact class of parameters */ -struct contact_hooks { - struct param* expires; /*!< expires parameter */ - struct param* q; /*!< q parameter */ - struct param* methods; /*!< methods parameter */ - struct param* received; /*!< received parameter */ - struct param* instance; /*!< sip.instance parameter */ - struct param* reg_id; /*!< reg-id parameter */ - struct param* ob; /*!< ob parameter */ - struct param* flags; /*!< flags parameter */ +struct contact_hooks +{ + struct param *expires; /*!< expires parameter */ + struct param *q; /*!< q parameter */ + struct param *methods; /*!< methods parameter */ + struct param *received; /*!< received parameter */ + struct param *instance; /*!< sip.instance parameter */ + struct param *reg_id; /*!< reg-id parameter */ + struct param *ob; /*!< ob parameter */ + struct param *flags; /*!< flags parameter */ }; /*! \brief * Hooks to well known parameter for URI class of parameters */ -struct uri_hooks { - struct param* transport; /*!< transport parameter */ - struct param* lr; /*!< lr parameter */ - struct param* r2; /*!< r2 parameter */ - struct param* maddr; /*!< maddr parameter */ - struct param* ttl; /*!< ttl parameter */ - struct param* dstip; /*!< Destination IP */ - struct param* dstport; /*!< Destination port */ - struct param* ftag; /*!< From tag in the original request */ - struct param* ob; /*!< ob parameter */ +struct uri_hooks +{ + struct param *transport; /*!< transport parameter */ + struct param *lr; /*!< lr parameter */ + struct param *r2; /*!< r2 parameter */ + struct param *maddr; /*!< maddr parameter */ + struct param *ttl; /*!< ttl parameter */ + struct param *dstip; /*!< Destination IP */ + struct param *dstport; /*!< Destination port */ + struct param *ftag; /*!< From tag in the original request */ + struct param *ob; /*!< ob parameter */ }; -struct event_dialog_hooks { - struct param* call_id; - struct param* from_tag; - struct param* to_tag; - struct param* include_session_description; - struct param* sla; - struct param* ma; +struct event_dialog_hooks +{ + struct param *call_id; + struct param *from_tag; + struct param *to_tag; + struct param *include_session_description; + struct param *sla; + struct param *ma; }; /*! \brief * Union of hooks structures for all classes */ -typedef union param_hooks { +typedef union param_hooks +{ struct contact_hooks contact; /*!< Contact hooks */ - struct uri_hooks uri; /*!< URI hooks */ + struct uri_hooks uri; /*!< URI hooks */ struct event_dialog_hooks event_dialog; } param_hooks_t; @@ -157,7 +164,7 @@ extern int parse_param(str *_s, pclass_t _c, param_hooks_t *_h, param_t *t); * \return The function returns 0 on success and negative number * on an error */ -int parse_params(str* _s, pclass_t _c, param_hooks_t* _h, param_t** _p); +int parse_params(str *_s, pclass_t _c, param_hooks_t *_h, param_t **_p); /*! \brief * Parse parameters @@ -169,38 +176,38 @@ int parse_params(str* _s, pclass_t _c, param_hooks_t* _h, param_t** _p); * \return The function returns 0 on success and negative number * on an error */ -int parse_params2(str* _s, pclass_t _c, param_hooks_t* _h, param_t** _p, - char separator); +int parse_params2( + str *_s, pclass_t _c, param_hooks_t *_h, param_t **_p, char separator); /*! \brief * Free linked list of parameters */ -void free_params(param_t* _p); +void free_params(param_t *_p); /*! \brief * Free linked list of parameters from shared memory */ -void shm_free_params(param_t* _p); +void shm_free_params(param_t *_p); /*! \brief * Print linked list of parameters, just for debugging */ -void print_params(FILE* _o, param_t* _p); +void print_params(FILE *_o, param_t *_p); /*! \brief * Duplicate linked list of parameters */ -int duplicate_params(param_t** _n, param_t* _p); +int duplicate_params(param_t **_n, param_t *_p); /*! \brief * Duplicate linked list of parameters */ -int shm_duplicate_params(param_t** _n, param_t* _p); +int shm_duplicate_params(param_t **_n, param_t *_p); #endif /* PARSE_PARAM_H */ diff --git a/src/core/parser/parse_ppi_pai.c b/src/core/parser/parse_ppi_pai.c index c60e33a9fd8..abee7559c7c 100644 --- a/src/core/parser/parse_ppi_pai.c +++ b/src/core/parser/parse_ppi_pai.c @@ -13,8 +13,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ @@ -33,7 +33,7 @@ #include "../ut.h" #include "../mem/mem.h" -/* +/* * A P-Asserted-Identity or P-Preferred-Identity header value is an addr-spec or name-addr * There can be only one of any URI scheme (sip(s), tel etc), which may occur on separate * headers or can be comma separated in a single header. @@ -53,41 +53,42 @@ int parse_pai_ppi_body(char *buf, int len, p_id_body_t **body) int i; memset(uri_b, 0, NUM_PAI_BODIES * sizeof(to_body_t)); - tmp = parse_addr_spec(buf, buf+len, &uri_b[num_uri], 1); - if (uri_b[num_uri].error == PARSE_ERROR) - { + tmp = parse_addr_spec(buf, buf + len, &uri_b[num_uri], 1); + if(uri_b[num_uri].error == PARSE_ERROR) { LM_ERR("Error parsing PAI/PPI body %u '%.*s'\n", num_uri, len, buf); return -1; } /* should be no header params, but in case there are, free them */ free_to_params(&uri_b[num_uri]); num_uri++; - while ((*tmp == ',') && (num_uri < NUM_PAI_BODIES)) - { + while((*tmp == ',') && (num_uri < NUM_PAI_BODIES)) { tmp++; - while(tmp=buf+len) { - LM_ERR("no content after comma when parsing PAI/PPI body %u '%.*s'\n", + while(tmp < buf + len && (*tmp == ' ' || *tmp == '\t')) + tmp++; + if(tmp >= buf + len) { + LM_ERR("no content after comma when parsing PAI/PPI body %u " + "'%.*s'\n", num_uri, len, buf); return -1; } - if((tmp= NUM_PAI_BODIES) - { + if(num_uri >= NUM_PAI_BODIES) { LM_WARN("Too many bodies in PAI/PPI header '%.*s'\n", len, buf); LM_WARN("Ignoring bodies beyond %u\n", NUM_PAI_BODIES); } *body = pkg_malloc(sizeof(p_id_body_t) + num_uri * sizeof(to_body_t)); - if (*body == NULL) - { + if(*body == NULL) { PKG_MEM_ERROR; return -1; } memset(*body, 0, sizeof(p_id_body_t)); - (*body)->id = (to_body_t*)((char*)(*body) + sizeof(p_id_body_t)); + (*body)->id = (to_body_t *)((char *)(*body) + sizeof(p_id_body_t)); (*body)->num_ids = num_uri; - for (i=0; i< num_uri; i++) - { + for(i = 0; i < num_uri; i++) { memcpy(&(*body)->id[i], &uri_b[i], sizeof(to_body_t)); } return 0; @@ -118,8 +116,7 @@ int parse_pai_ppi_body(char *buf, int len, p_id_body_t **body) int free_pai_ppi_body(p_id_body_t *pid_b) { - if (pid_b != NULL) - { + if(pid_b != NULL) { pkg_free(pid_b); } return 0; @@ -130,43 +127,38 @@ int free_pai_ppi_body(p_id_body_t *pid_b) * \param msg The SIP message structure * \return 0 on success, -1 on failure */ -int parse_pai_header(struct sip_msg* const msg) +int parse_pai_header(struct sip_msg *const msg) { p_id_body_t *pai_b; p_id_body_t **prev_pid_b; hdr_field_t *hf; void **vp; - if ( !msg->pai ) - { - if (parse_headers(msg, HDR_PAI_F, 0) < 0) - { + if(!msg->pai) { + if(parse_headers(msg, HDR_PAI_F, 0) < 0) { LM_ERR("Error parsing PAI header\n"); return -1; } - if ( !msg->pai ) + if(!msg->pai) /* No PAI headers */ return -1; } - if ( msg->pai->parsed ) + if(msg->pai->parsed) return 0; vp = &msg->pai->parsed; - prev_pid_b = (p_id_body_t**)vp; + prev_pid_b = (p_id_body_t **)vp; - for (hf = msg->pai; hf != NULL; hf = next_sibling_hdr(hf)) - { - if (parse_pai_ppi_body(hf->body.s, hf->body.len, &pai_b) < 0) - { + for(hf = msg->pai; hf != NULL; hf = next_sibling_hdr(hf)) { + if(parse_pai_ppi_body(hf->body.s, hf->body.len, &pai_b) < 0) { return -1; } - hf->parsed = (void*)pai_b; + hf->parsed = (void *)pai_b; *prev_pid_b = pai_b; prev_pid_b = &pai_b->next; - if (parse_headers(msg, HDR_PAI_F, 1) < 0) - { + if(parse_headers(msg, HDR_PAI_F, 1) < 0) { LM_ERR("Error looking for subsequent PAI header"); return -1; } @@ -179,50 +171,43 @@ int parse_pai_header(struct sip_msg* const msg) * \param msg The SIP message structure * \return 0 on success, -1 on failure */ -int parse_ppi_header(struct sip_msg* const msg) +int parse_ppi_header(struct sip_msg *const msg) { p_id_body_t *ppi_b, *prev_pidb; hdr_field_t *hf; - if ( !msg->ppi ) - { - if (parse_headers(msg, HDR_PPI_F, 0) < 0) - { + if(!msg->ppi) { + if(parse_headers(msg, HDR_PPI_F, 0) < 0) { LM_ERR("Error parsing PPI header\n"); return -1; } - if ( !msg->ppi ) + if(!msg->ppi) /* No PPI headers */ return -1; } - if ( msg->ppi->parsed ) + if(msg->ppi->parsed) return 0; - if (parse_pai_ppi_body(msg->ppi->body.s, msg->ppi->body.len, &ppi_b) < 0) - { + if(parse_pai_ppi_body(msg->ppi->body.s, msg->ppi->body.len, &ppi_b) < 0) { return -1; } - msg->ppi->parsed = (void*)ppi_b; + msg->ppi->parsed = (void *)ppi_b; - if (parse_headers(msg, HDR_PPI_F, 1) < 0) - { + if(parse_headers(msg, HDR_PPI_F, 1) < 0) { LM_ERR("Error looking for subsequent PPI header"); return -1; } prev_pidb = ppi_b; hf = msg->ppi; - if ((hf = next_sibling_hdr(hf)) != NULL) - { - if (parse_pai_ppi_body(hf->body.s, hf->body.len, &ppi_b) < 0) - { + if((hf = next_sibling_hdr(hf)) != NULL) { + if(parse_pai_ppi_body(hf->body.s, hf->body.len, &ppi_b) < 0) { return -1; } - hf->parsed = (void*)ppi_b; + hf->parsed = (void *)ppi_b; - if (parse_headers(msg, HDR_PPI_F, 1) < 0) - { + if(parse_headers(msg, HDR_PPI_F, 1) < 0) { LM_ERR("Error looking for subsequent PPI header"); return -1; } @@ -231,4 +216,3 @@ int parse_ppi_header(struct sip_msg* const msg) } return 0; } - diff --git a/src/core/parser/parse_ppi_pai.h b/src/core/parser/parse_ppi_pai.h index d31dd91d366..57e5102e1b0 100644 --- a/src/core/parser/parse_ppi_pai.h +++ b/src/core/parser/parse_ppi_pai.h @@ -13,8 +13,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ @@ -31,20 +31,21 @@ #include "msg_parser.h" #include "parse_to.h" -typedef struct p_id_body { +typedef struct p_id_body +{ to_body_t *id; int num_ids; struct p_id_body *next; } p_id_body_t; -int parse_pai_header(struct sip_msg* const msg); -int parse_ppi_header(struct sip_msg* const msg); +int parse_pai_header(struct sip_msg *const msg); +int parse_ppi_header(struct sip_msg *const msg); /*! casting macro for accessing P-Asserted-Identity body */ -#define get_pai(p_msg) ((p_id_body_t*)(p_msg)->pai->parsed) +#define get_pai(p_msg) ((p_id_body_t *)(p_msg)->pai->parsed) /*! casting macro for accessing P-Preferred-Identity body */ -#define get_ppi(p_msg) ((p_id_body_t*)(p_msg)->ppi->parsed) +#define get_ppi(p_msg) ((p_id_body_t *)(p_msg)->ppi->parsed) int free_pai_ppi_body(p_id_body_t *pid_b); diff --git a/src/core/parser/parse_privacy.c b/src/core/parser/parse_privacy.c index cfc009a64a6..64431468675 100644 --- a/src/core/parser/parse_privacy.c +++ b/src/core/parser/parse_privacy.c @@ -38,108 +38,109 @@ * Parse a privacy value pointed by start that can be at most max_len long. * \return length of matched privacy value on success or NULL otherwise */ -unsigned int parse_priv_value(char* start, unsigned int max_len, - unsigned int* value) +unsigned int parse_priv_value( + char *start, unsigned int max_len, unsigned int *value) { - unsigned int len; + unsigned int len; - if (!start || !value) { - LM_ERR("invalid parameter value\n"); - return 0; - } - - switch (start[0]) { - - case 'c': - case 'C': - if(max_len < 8) - return 0; - if (strncasecmp(start, "critical", 8) == 0) { - *value = PRIVACY_CRITICAL; - len = 8; - break; - } else { - return 0; + if(!start || !value) { + LM_ERR("invalid parameter value\n"); + return 0; } - case 'h': - case 'H': - if (max_len < 6) - return 0; - if (strncasecmp(start, "header", 6) == 0) { - *value = PRIVACY_HEADER; - len = 6; - break; - } - if (max_len < 7) - return 0; - if (strncasecmp(start, "history", 7) == 0) { - *value = PRIVACY_HISTORY; - len = 7; - break; - } else { - return 0; + switch(start[0]) { + + case 'c': + case 'C': + if(max_len < 8) + return 0; + if(strncasecmp(start, "critical", 8) == 0) { + *value = PRIVACY_CRITICAL; + len = 8; + break; + } else { + return 0; + } + + case 'h': + case 'H': + if(max_len < 6) + return 0; + if(strncasecmp(start, "header", 6) == 0) { + *value = PRIVACY_HEADER; + len = 6; + break; + } + if(max_len < 7) + return 0; + if(strncasecmp(start, "history", 7) == 0) { + *value = PRIVACY_HISTORY; + len = 7; + break; + } else { + return 0; + } + + case 'i': + case 'I': + if(max_len < 2) + return 0; + if(start[1] == 'd' || start[1] == 'D') { + *value = PRIVACY_ID; + len = 2; + break; + } else { + return 0; + } + + case 'n': + case 'N': + if(max_len < 4) + return 0; + if(strncasecmp(start, "none", 4) == 0) { + *value = PRIVACY_NONE; + len = 4; + break; + } else { + return 0; + } + + case 's': + case 'S': + if(max_len < 7) + return 0; + if(strncasecmp(start, "session", 7) == 0) { + *value = PRIVACY_SESSION; + len = 7; + break; + } else { + return 0; + } + + case 'u': + case 'U': + if(max_len < 4) + return 0; + if(strncasecmp(start, "user", 4) == 0) { + *value = PRIVACY_USER; + len = 4; + break; + } else { + return 0; + } + + default: + return 0; } - case 'i': - case 'I': - if(max_len < 2) - return 0; - if (start[1] == 'd' || start[1] == 'D') { - *value = PRIVACY_ID; - len = 2; - break; - } else { - return 0; + if(len < max_len) { + if(start[len] != '\0' && start[len] != ';' && start[len] != ' ' + && start[len] != '\t' && start[len] != '\r' + && start[len] != '\n') + return 0; } - case 'n': - case 'N': - if(max_len < 4) - return 0; - if (strncasecmp(start, "none", 4) == 0) { - *value = PRIVACY_NONE; - len = 4; - break; - } else { - return 0; - } - - case 's': - case 'S': - if(max_len < 7) - return 0; - if (strncasecmp(start, "session", 7) == 0) { - *value = PRIVACY_SESSION; - len = 7; - break; - } else { - return 0; - } - - case 'u': - case 'U': - if(max_len < 4) - return 0; - if (strncasecmp(start, "user", 4) == 0) { - *value = PRIVACY_USER; - len = 4; - break; - } else { - return 0; - } - - default: - return 0; - } - - if(len < max_len) { - if(start[len] != '\0' && start[len] != ';' && start[len] != ' ' - && start[len] != '\t' && start[len] != '\r' && start[len] != '\n') - return 0; - } - - return len; + return len; } @@ -147,76 +148,77 @@ unsigned int parse_priv_value(char* start, unsigned int max_len, * This method is used to parse Privacy HF body, which consist of * comma separated list of priv-values. After parsing, msg->privacy->parsed * contains enum bits of privacy values defined in parse_privacy.h. - * \return 0 on success and -1 on failure. + * \return 0 on success and -1 on failure. */ int parse_privacy(struct sip_msg *msg) { - unsigned int val_len, value, values, len; - str next; - char *p, *beyond; + unsigned int val_len, value, values, len; + str next; + char *p, *beyond; - /* maybe the header is already parsed! */ - if (msg->privacy && msg->privacy->parsed) - return 0; + /* maybe the header is already parsed! */ + if(msg->privacy && msg->privacy->parsed) + return 0; - /* parse Privacy HF (there should be only one) */ - if (!msg->privacy && - (parse_headers(msg, HDR_PRIVACY_F, 0) == -1 || !msg->privacy)) { - return -1; - } - - next.len = msg->privacy->body.len; - next.s = msg->privacy->body.s; - - trim_leading(&next); - - if (next.len == 0) { - LM_ERR("no values\n"); - return -1; - } - - values = 0; - p = next.s; - len = next.len; - beyond = p + len; - - while (p < beyond) { - if((val_len = parse_priv_value(p, len, &value)) != 0) { - values |= value; - p = p + val_len; - len = len - val_len; - } else { - LM_ERR("invalid privacy value\n"); - return -1; + /* parse Privacy HF (there should be only one) */ + if(!msg->privacy + && (parse_headers(msg, HDR_PRIVACY_F, 0) == -1 || !msg->privacy)) { + return -1; } - while(p < beyond && (*p == ' ' || *p == '\t' - || *p == '\r' || *p == '\n')) - p++; + next.len = msg->privacy->body.len; + next.s = msg->privacy->body.s; - if(p >= beyond) break; + trim_leading(&next); - if (*p == ';') { - p++; - while(p < beyond && (*p == ' ' || *p == '\t' - || *p == '\r' || *p == '\n')) - p++; - if(p >= beyond) { - LM_ERR("no privacy value after comma\n"); + if(next.len == 0) { + LM_ERR("no values\n"); return -1; - } - } else { - LM_ERR("semicolon expected\n"); - return -1; } - } - if ((values & PRIVACY_NONE) && (values ^ PRIVACY_NONE)) { - LM_ERR("no other privacy values allowed with 'none'\n"); - return -1; - } + values = 0; + p = next.s; + len = next.len; + beyond = p + len; + + while(p < beyond) { + if((val_len = parse_priv_value(p, len, &value)) != 0) { + values |= value; + p = p + val_len; + len = len - val_len; + } else { + LM_ERR("invalid privacy value\n"); + return -1; + } + + while(p < beyond + && (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n')) + p++; + + if(p >= beyond) + break; + + if(*p == ';') { + p++; + while(p < beyond + && (*p == ' ' || *p == '\t' || *p == '\r' || *p == '\n')) + p++; + if(p >= beyond) { + LM_ERR("no privacy value after comma\n"); + return -1; + } + } else { + LM_ERR("semicolon expected\n"); + return -1; + } + } - msg->privacy->parsed = (void *)(long)values; + if((values & PRIVACY_NONE) && (values ^ PRIVACY_NONE)) { + LM_ERR("no other privacy values allowed with 'none'\n"); + return -1; + } - return 0; + msg->privacy->parsed = (void *)(long)values; + + return 0; } diff --git a/src/core/parser/parse_privacy.h b/src/core/parser/parse_privacy.h index bad560cfc78..241ed968154 100644 --- a/src/core/parser/parse_privacy.h +++ b/src/core/parser/parse_privacy.h @@ -34,14 +34,15 @@ /*! bitmap of Privacy header privacy values * (http://www.iana.org/assignments/sip-priv-values) */ -enum privacy_value { - PRIVACY_USER=1, - PRIVACY_HEADER=2, - PRIVACY_SESSION=4, - PRIVACY_NONE=8, - PRIVACY_CRITICAL=16, - PRIVACY_ID=32, - PRIVACY_HISTORY=64 +enum privacy_value +{ + PRIVACY_USER = 1, + PRIVACY_HEADER = 2, + PRIVACY_SESSION = 4, + PRIVACY_NONE = 8, + PRIVACY_CRITICAL = 16, + PRIVACY_ID = 32, + PRIVACY_HISTORY = 64 }; @@ -56,7 +57,7 @@ enum privacy_value { * This method is used to parse Privacy HF body, which consist of * comma separated list of priv-values. After parsing, msg->privacy->parsed * contains enum bits of privacy values defined in parse_privacy.h. - * \return 0 on success and -1 on failure. + * \return 0 on success and -1 on failure. */ int parse_privacy(struct sip_msg *msg); @@ -65,8 +66,8 @@ int parse_privacy(struct sip_msg *msg); * Parse a privacy value pointed by start that can be at most max_len long. * \return length of matched privacy value on success or NULL otherwise */ -unsigned int parse_priv_value(char* start, unsigned int max_len, - unsigned int* value); +unsigned int parse_priv_value( + char *start, unsigned int max_len, unsigned int *value); #endif /* PARSE_PRIVACY_H */ diff --git a/src/core/parser/parse_refer_to.c b/src/core/parser/parse_refer_to.c index c2deb39b9b1..578be4947c9 100644 --- a/src/core/parser/parse_refer_to.c +++ b/src/core/parser/parse_refer_to.c @@ -41,23 +41,24 @@ * returns 0 on success, * -1 on failure. */ -int parse_refer_to_header( struct sip_msg *msg ) +int parse_refer_to_header(struct sip_msg *msg) { - struct to_body* refer_to_b; + struct to_body *refer_to_b; - if ( !msg->refer_to && - (parse_headers(msg, HDR_REFER_TO_F,0)==-1 || !msg->refer_to)) { + if(!msg->refer_to + && (parse_headers(msg, HDR_REFER_TO_F, 0) == -1 + || !msg->refer_to)) { goto error; } /* maybe the header is already parsed! */ - if (msg->refer_to->parsed) + if(msg->refer_to->parsed) return 0; /* bad luck! :-( - we have to parse it */ /* first, get some memory */ refer_to_b = pkg_malloc(sizeof(struct to_body)); - if (refer_to_b == 0) { + if(refer_to_b == 0) { PKG_MEM_ERROR; goto error; } @@ -65,9 +66,8 @@ int parse_refer_to_header( struct sip_msg *msg ) /* now parse it!! */ memset(refer_to_b, 0, sizeof(struct to_body)); parse_to(msg->refer_to->body.s, - msg->refer_to->body.s + msg->refer_to->body.len+1, - refer_to_b); - if (refer_to_b->error == PARSE_ERROR) { + msg->refer_to->body.s + msg->refer_to->body.len + 1, refer_to_b); + if(refer_to_b->error == PARSE_ERROR) { LM_ERR("bad Refer-To header\n"); free_to(refer_to_b); goto error; diff --git a/src/core/parser/parse_refer_to.h b/src/core/parser/parse_refer_to.h index ad1cd149e74..6f5a93bc7cd 100644 --- a/src/core/parser/parse_refer_to.h +++ b/src/core/parser/parse_refer_to.h @@ -13,8 +13,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ @@ -23,20 +23,20 @@ * * \ingroup parser */ - + #ifndef PARSE_REFER_TO_H #define PARSE_REFER_TO_H - + #include "msg_parser.h" - - + + /*! \brief casting macro for accessing Refer-To body */ -#define get_refer_to(p_msg) ((struct to_body*)(p_msg)->refer_to->parsed) +#define get_refer_to(p_msg) ((struct to_body *)(p_msg)->refer_to->parsed) /* * Refer-To header field parser */ -int parse_refer_to_header( struct sip_msg *msg); - +int parse_refer_to_header(struct sip_msg *msg); + #endif /* PARSE_REFER_TO_H */ diff --git a/src/core/parser/parse_require.c b/src/core/parser/parse_require.c index d7646ca04e7..537e687fc4f 100644 --- a/src/core/parser/parse_require.c +++ b/src/core/parser/parse_require.c @@ -30,30 +30,31 @@ /*! * Parse all Require headers */ -int parse_require( struct sip_msg *msg) +int parse_require(struct sip_msg *msg) { unsigned int require; - struct hdr_field *hdr; + struct hdr_field *hdr; struct option_tag_body *rb; /* maybe the header is already parsed! */ - if (msg->require && msg->require->parsed) + if(msg->require && msg->require->parsed) return 0; /* parse to the end in order to get all SUPPORTED headers */ - if (parse_headers(msg,HDR_EOH_F,0)==-1 || !msg->require) + if(parse_headers(msg, HDR_EOH_F, 0) == -1 || !msg->require) return -1; /* bad luck! :-( - we have to parse them */ require = 0; - for( hdr=msg->require ; hdr ; hdr=next_sibling_hdr(hdr)) { - if (hdr->parsed) { - require |= ((struct option_tag_body*)hdr->parsed)->option_tags; + for(hdr = msg->require; hdr; hdr = next_sibling_hdr(hdr)) { + if(hdr->parsed) { + require |= ((struct option_tag_body *)hdr->parsed)->option_tags; continue; } - rb = (struct option_tag_body*)pkg_malloc(sizeof(struct option_tag_body)); - if (rb == 0) { + rb = (struct option_tag_body *)pkg_malloc( + sizeof(struct option_tag_body)); + if(rb == 0) { PKG_MEM_ERROR; return -1; } @@ -61,11 +62,10 @@ int parse_require( struct sip_msg *msg) parse_option_tag_body(&(hdr->body), &(rb->option_tags)); rb->hfree = hf_free_option_tag; rb->option_tags_all = 0; - hdr->parsed = (void*)rb; + hdr->parsed = (void *)rb; require |= rb->option_tags; } - ((struct option_tag_body*)msg->require->parsed)->option_tags_all = - require; + ((struct option_tag_body *)msg->require->parsed)->option_tags_all = require; return 0; } diff --git a/src/core/parser/parse_require.h b/src/core/parser/parse_require.h index d9bc507c663..3996c0624b8 100644 --- a/src/core/parser/parse_require.h +++ b/src/core/parser/parse_require.h @@ -33,14 +33,16 @@ #include "../mem/mem.h" #include "parse_option_tags.h" -#define get_require(p_msg) \ - ((p_msg)->require ? ((struct option_tag_body*)(p_msg)->require->parsed)->option_tags_all : 0) +#define get_require(p_msg) \ + ((p_msg)->require ? ((struct option_tag_body *)(p_msg)->require->parsed) \ + ->option_tags_all \ + : 0) /*! * Parse all Require headers. */ -int parse_require( struct sip_msg *msg); +int parse_require(struct sip_msg *msg); void free_require(struct option_tag_body **rb); diff --git a/src/core/parser/parse_retry_after.c b/src/core/parser/parse_retry_after.c index ab80e4cb4d7..fd267814583 100644 --- a/src/core/parser/parse_retry_after.c +++ b/src/core/parser/parse_retry_after.c @@ -28,29 +28,30 @@ #include "../comp_defs.h" #include "parse_retry_after.h" -#include "parser_f.h" /* eat_space_end and so on */ +#include "parser_f.h" /* eat_space_end and so on */ #include "parse_def.h" #include "../dprint.h" #include "../mem/mem.h" /*! \brief Parse the Retry-after header field */ -char* parse_retry_after(char* const buf, const char* const end, - unsigned* const after, int* const err) +char *parse_retry_after(char *const buf, const char *const end, + unsigned *const after, int *const err) { char *t; int i; unsigned val; - val=0; - t=buf; + val = 0; + t = buf; - t=eat_lws_end(t, end); - if (t>=end) goto error; - for (i=0; t= '0') && (*t <= '9')){ - val=val*10+(*t-'0'); - }else{ - switch(*t){ + t = eat_lws_end(t, end); + if(t >= end) + goto error; + for(i = 0; t < end; i++, t++) { + if((*t >= '0') && (*t <= '9')) { + val = val * 10 + (*t - '0'); + } else { + switch(*t) { /* for now we don't care about retry-after params or comment*/ case ' ': case '\t': @@ -67,18 +68,18 @@ char* parse_retry_after(char* const buf, const char* const end, } goto error_nocrlf; /* end reached without encountering cr or lf */ found: - if (i>10 || i==0) /* too many or too few digits */ + if(i > 10 || i == 0) /* too many or too few digits */ goto error; - *after=val; + *after = val; /* find the end of header */ - for (; trpid && (parse_headers(msg, HDR_RPID_F, 0)==-1 || !msg->rpid)) { + if(!msg->rpid && (parse_headers(msg, HDR_RPID_F, 0) == -1 || !msg->rpid)) { goto error; } /* maybe the header is already parsed! */ - if (msg->rpid->parsed) + if(msg->rpid->parsed) return 0; /* needs to parse it */ /* first, get some memory */ rpid_b = pkg_malloc(sizeof(struct to_body)); - if (rpid_b == 0) { + if(rpid_b == 0) { PKG_MEM_ERROR; goto error; } /* now parse it!! */ memset(rpid_b, 0, sizeof(struct to_body)); - parse_to(msg->rpid->body.s,msg->rpid->body.s+msg->rpid->body.len+1,rpid_b); - if (rpid_b->error == PARSE_ERROR) { + parse_to(msg->rpid->body.s, msg->rpid->body.s + msg->rpid->body.len + 1, + rpid_b); + if(rpid_b->error == PARSE_ERROR) { LM_ERR("bad rpid header\n"); free_to(rpid_b); goto error; diff --git a/src/core/parser/parse_rpid.h b/src/core/parser/parse_rpid.h index 16d25ee2413..c2c557068e9 100644 --- a/src/core/parser/parse_rpid.h +++ b/src/core/parser/parse_rpid.h @@ -13,30 +13,30 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ - + /*! \file * \brief Parser :: Remote-party-id: header parser * * \ingroup parser */ - + #ifndef PARSE_RPID_H #define PARSE_RPID_H - + #include "msg_parser.h" - - + + /*! \brief casting macro for accessing RPID body */ -#define get_rpid(p_msg) ((struct to_body*)(p_msg)->rpid->parsed) +#define get_rpid(p_msg) ((struct to_body *)(p_msg)->rpid->parsed) /* * RPID header field parser */ -int parse_rpid_header( struct sip_msg *msg); - +int parse_rpid_header(struct sip_msg *msg); + #endif /* PARSE_RPID_H */ diff --git a/src/core/parser/parse_rr.c b/src/core/parser/parse_rr.c index e8854cbd4be..f6fce793faf 100644 --- a/src/core/parser/parse_rr.c +++ b/src/core/parser/parse_rr.c @@ -39,13 +39,12 @@ */ static inline int do_parse_rr_body(char *buf, int len, rr_t **head) { - rr_t* r, *last; + rr_t *r, *last; str s; param_hooks_t hooks; /* Make a temporary copy of the string pointer */ - if(buf==0 || len<=0) - { + if(buf == 0 || len <= 0) { LM_DBG("No body for record-route\n"); *head = 0; return -2; @@ -55,51 +54,51 @@ static inline int do_parse_rr_body(char *buf, int len, rr_t **head) trim_leading(&s); last = 0; - if (*head) { + if(*head) { /* go to last rr in list */ last = *head; - while (last->next) { + while(last->next) { last = last->next; } } while(1) { /* Allocate and clear rr structure */ - r = (rr_t*)pkg_malloc(sizeof(rr_t)); - if (!r) { + r = (rr_t *)pkg_malloc(sizeof(rr_t)); + if(!r) { PKG_MEM_ERROR; goto error; } memset(r, 0, sizeof(rr_t)); /* Parse name-addr part of the header */ - if (parse_nameaddr(&s, &r->nameaddr) < 0) { - LM_ERR("Failed parsing name-addr (%.*s)\n", - s.len, ZSW(s.s)); + if(parse_nameaddr(&s, &r->nameaddr) < 0) { + LM_ERR("Failed parsing name-addr (%.*s)\n", s.len, ZSW(s.s)); goto error; } r->len = r->nameaddr.len; /* Shift just behind the closing > */ - s.s = r->nameaddr.name.s + r->nameaddr.len; /* Point just behind > */ + s.s = r->nameaddr.name.s + r->nameaddr.len; /* Point just behind > */ s.len -= r->nameaddr.len; trim_leading(&s); /* Skip any white-chars */ - if (s.len == 0) goto ok; /* Nothing left, finish */ + if(s.len == 0) + goto ok; /* Nothing left, finish */ - if (s.s[0] == ';') { /* Route parameter found */ + if(s.s[0] == ';') { /* Route parameter found */ s.s++; s.len--; trim_leading(&s); - if (s.len == 0) { + if(s.len == 0) { LM_ERR("Error while parsing params\n"); goto error; } /* Parse all parameters */ - if (parse_params(&s, CLASS_ANY, &hooks, &r->params) < 0) { + if(parse_params(&s, CLASS_ANY, &hooks, &r->params) < 0) { LM_ERR("Error while parsing params\n"); goto error; } @@ -109,10 +108,11 @@ static inline int do_parse_rr_body(char *buf, int len, rr_t **head) /*r->r2 = hooks.rr.r2; */ trim_leading(&s); - if (s.len == 0) goto ok; + if(s.len == 0) + goto ok; } - if (s.s[0] != ',') { + if(s.s[0] != ',') { LM_ERR("Invalid character '%c', comma expected\n", s.s[0]); goto error; } @@ -122,27 +122,32 @@ static inline int do_parse_rr_body(char *buf, int len, rr_t **head) s.len--; trim_leading(&s); - if (s.len == 0) { + if(s.len == 0) { LM_ERR("Text after comma missing\n"); goto error; } /* Append the structure as last parameter of the linked list */ - if (!*head) *head = r; - if (last) last->next = r; + if(!*head) + *head = r; + if(last) + last->next = r; last = r; } error: - if (r) free_rr(&r); + if(r) + free_rr(&r); free_rr(head); /* Free any rr created so far */ *head = NULL; LM_ERR("Failed parsing rr header body [%.*s]\n", len, ZSW(buf)); return -1; ok: - if (!*head) *head = r; - if (last) last->next = r; + if(!*head) + *head = r; + if(last) + last->next = r; return 0; } @@ -157,23 +162,23 @@ int parse_rr_body(char *buf, int len, rr_t **head) /*! \brief * Parse Route and Record-Route header fields */ -int parse_rr(struct hdr_field* _h) +int parse_rr(struct hdr_field *_h) { - rr_t* r = NULL; + rr_t *r = NULL; - if (!_h) { + if(!_h) { LM_ERR("Invalid parameter value\n"); return -1; } - if (_h->parsed) { + if(_h->parsed) { /* Already parsed, return */ return 0; } if(do_parse_rr_body(_h->body.s, _h->body.len, &r) < 0) return -1; - _h->parsed = (void*)r; + _h->parsed = (void *)r; return 0; } @@ -181,19 +186,23 @@ int parse_rr(struct hdr_field* _h) * Free list of rrs * _r is head of the list */ -static inline void do_free_rr(rr_t** _r, int _shm) +static inline void do_free_rr(rr_t **_r, int _shm) { - rr_t* ptr; + rr_t *ptr; while(*_r) { ptr = *_r; *_r = (*_r)->next; - if (ptr->params) { - if (_shm) shm_free_params(ptr->params); - else free_params(ptr->params); + if(ptr->params) { + if(_shm) + shm_free_params(ptr->params); + else + free_params(ptr->params); } - if (_shm) shm_free(ptr); - else pkg_free(ptr); + if(_shm) + shm_free(ptr); + else + pkg_free(ptr); } } @@ -203,7 +212,7 @@ static inline void do_free_rr(rr_t** _r, int _shm) * _r is head of the list */ -void free_rr(rr_t** _r) +void free_rr(rr_t **_r) { do_free_rr(_r, 0); } @@ -214,7 +223,7 @@ void free_rr(rr_t** _r) * _r is head of the list */ -void shm_free_rr(rr_t** _r) +void shm_free_rr(rr_t **_r) { do_free_rr(_r, 1); } @@ -223,9 +232,9 @@ void shm_free_rr(rr_t** _r) /*! \brief * Print list of RRs, just for debugging */ -void print_rr(FILE* _o, rr_t* _r) +void print_rr(FILE *_o, rr_t *_r) { - rr_t* ptr; + rr_t *ptr; ptr = _r; @@ -233,7 +242,7 @@ void print_rr(FILE* _o, rr_t* _r) fprintf(_o, "---RR---\n"); print_nameaddr(_o, &ptr->nameaddr); fprintf(_o, "r2 : %p\n", ptr->r2); - if (ptr->params) { + if(ptr->params) { print_params(_o, ptr->params); } fprintf(_o, "len: %d\n", ptr->len); @@ -247,19 +256,19 @@ void print_rr(FILE* _o, rr_t* _r) * Translate all pointers in the structure and also * in all parameters in the list */ -static inline void xlate_pointers(rr_t* _orig, rr_t* _r) +static inline void xlate_pointers(rr_t *_orig, rr_t *_r) { - param_t* ptr; - _r->nameaddr.uri.s = translate_pointer(_r->nameaddr.name.s, - _orig->nameaddr.name.s, _r->nameaddr.uri.s); + param_t *ptr; + _r->nameaddr.uri.s = translate_pointer( + _r->nameaddr.name.s, _orig->nameaddr.name.s, _r->nameaddr.uri.s); ptr = _r->params; while(ptr) { /* if (ptr->type == P_R2) _r->r2 = ptr; */ - ptr->name.s = translate_pointer(_r->nameaddr.name.s, - _orig->nameaddr.name.s, ptr->name.s); - ptr->body.s = translate_pointer(_r->nameaddr.name.s, - _orig->nameaddr.name.s, ptr->body.s); + ptr->name.s = translate_pointer( + _r->nameaddr.name.s, _orig->nameaddr.name.s, ptr->name.s); + ptr->body.s = translate_pointer( + _r->nameaddr.name.s, _orig->nameaddr.name.s, ptr->body.s); ptr = ptr->next; } } @@ -268,30 +277,31 @@ static inline void xlate_pointers(rr_t* _orig, rr_t* _r) /*! \brief * Duplicate a single rr_t structure using pkg_malloc or shm_malloc */ -static inline int do_duplicate_rr(rr_t** _new, rr_t* _r, int _shm) +static inline int do_duplicate_rr(rr_t **_new, rr_t *_r, int _shm) { int len, ret; - rr_t* res, *prev, *it; + rr_t *res, *prev, *it; - if (!_new || !_r) { + if(!_new || !_r) { LM_ERR("Invalid parameter value\n"); return -1; } - prev = NULL; + prev = NULL; *_new = NULL; - it = _r; - while(it) - { - if (it->params) { + it = _r; + while(it) { + if(it->params) { len = it->params->name.s + it->params->len - it->nameaddr.name.s; } else { len = it->nameaddr.len; } - if (_shm) res = shm_malloc(sizeof(rr_t) + len); - else res = pkg_malloc(sizeof(rr_t) + len); - if (!res) { - if (_shm) { + if(_shm) + res = shm_malloc(sizeof(rr_t) + len); + else + res = pkg_malloc(sizeof(rr_t) + len); + if(!res) { + if(_shm) { SHM_MEM_ERROR; } else { PKG_MEM_ERROR; @@ -301,27 +311,29 @@ static inline int do_duplicate_rr(rr_t** _new, rr_t* _r, int _shm) } memcpy(res, it, sizeof(rr_t)); - res->nameaddr.name.s = (char*)res + sizeof(rr_t); + res->nameaddr.name.s = (char *)res + sizeof(rr_t); memcpy(res->nameaddr.name.s, it->nameaddr.name.s, len); - if (_shm) { + if(_shm) { ret = shm_duplicate_params(&res->params, it->params); } else { ret = duplicate_params(&res->params, it->params); } - if (ret < 0) { + if(ret < 0) { LM_ERR("Error while duplicating parameters\n"); - if (_shm) shm_free(res); - else pkg_free(res); + if(_shm) + shm_free(res); + else + pkg_free(res); ret = -3; goto error; } xlate_pointers(it, res); - res->next=NULL; - if(*_new==NULL) + res->next = NULL; + if(*_new == NULL) *_new = res; if(prev) prev->next = res; @@ -332,7 +344,7 @@ static inline int do_duplicate_rr(rr_t** _new, rr_t* _r, int _shm) error: if(*_new != NULL) { - if (_shm) { + if(_shm) { shm_free_rr(_new); } else { free_rr(_new); @@ -347,7 +359,7 @@ static inline int do_duplicate_rr(rr_t** _new, rr_t* _r, int _shm) /*! \brief * Duplicate a single rr_t structure using pkg_malloc */ -int duplicate_rr(rr_t** _new, rr_t* _r) +int duplicate_rr(rr_t **_new, rr_t *_r) { return do_duplicate_rr(_new, _r, 0); } @@ -356,7 +368,7 @@ int duplicate_rr(rr_t** _new, rr_t* _r) /*! \brief * Duplicate a single rr_t structure using pkg_malloc */ -int shm_duplicate_rr(rr_t** _new, rr_t* _r) +int shm_duplicate_rr(rr_t **_new, rr_t *_r) { return do_duplicate_rr(_new, _r, 1); } @@ -366,41 +378,37 @@ int shm_duplicate_rr(rr_t** _new, rr_t* _r) * - order = 0 normal; order = 1 reverse * - nb_recs - input=skip number of rr; output=number of printed rrs */ -int print_rr_body(struct hdr_field *iroute, str *oroute, int order, - unsigned int * nb_recs) +int print_rr_body( + struct hdr_field *iroute, str *oroute, int order, unsigned int *nb_recs) { rr_t *p; - int n = 0, nr=0; + int n = 0, nr = 0; int i = 0; int route_len; -#define MAX_RR_HDRS 64 +#define MAX_RR_HDRS 64 static str route[MAX_RR_HDRS]; char *cp, *start; - if(iroute==NULL) + if(iroute == NULL) return 0; - route_len= 0; - memset(route, 0, MAX_RR_HDRS*sizeof(str)); + route_len = 0; + memset(route, 0, MAX_RR_HDRS * sizeof(str)); - while (iroute!=NULL) - { - if (parse_rr(iroute) < 0) - { + while(iroute != NULL) { + if(parse_rr(iroute) < 0) { LM_ERR("failed to parse RR\n"); goto error; } - p =(rr_t*)iroute->parsed; - while (p) - { + p = (rr_t *)iroute->parsed; + while(p) { route[n].s = p->nameaddr.name.s; route[n].len = p->len; LM_DBG("current rr is %.*s\n", route[n].len, route[n].s); n++; - if(n==MAX_RR_HDRS) - { + if(n == MAX_RR_HDRS) { LM_ERR("too many RR\n"); goto error; } @@ -410,14 +418,14 @@ int print_rr_body(struct hdr_field *iroute, str *oroute, int order, iroute = next_sibling_hdr(iroute); } - for(i=0;i=*nb_recs)) || (order && (i<=(n-*nb_recs)) )) ) ) - { - route_len+= route[i].len; + for(i = 0; i < n; i++) { + if(!nb_recs + || (nb_recs + && ((!order && (i >= *nb_recs)) + || (order && (i <= (n - *nb_recs)))))) { + route_len += route[i].len; nr++; } - } if(nb_recs) @@ -425,43 +433,39 @@ int print_rr_body(struct hdr_field *iroute, str *oroute, int order, route_len += --nr; /* for commas */ - oroute->s=(char*)pkg_malloc(route_len); + oroute->s = (char *)pkg_malloc(route_len); - if(oroute->s==0) - { + if(oroute->s == 0) { PKG_MEM_ERROR; goto error; } cp = start = oroute->s; - if(order==0) - { - i= (nb_recs == NULL) ? 0:*nb_recs; + if(order == 0) { + i = (nb_recs == NULL) ? 0 : *nb_recs; - while (i=0) - { + while(i >= 0) { memcpy(cp, route[i].s, route[i].len); cp += route[i].len; - if (i-->0) + if(i-- > 0) *(cp++) = ','; } } - oroute->len=cp - start; + oroute->len = cp - start; LM_DBG("out rr [%.*s]\n", oroute->len, oroute->s); - LM_DBG("we have %i records\n", (nb_recs == NULL) ? n : n-*nb_recs); + LM_DBG("we have %i records\n", (nb_recs == NULL) ? n : n - *nb_recs); if(nb_recs != NULL) - *nb_recs = (unsigned int)n-*nb_recs; + *nb_recs = (unsigned int)n - *nb_recs; return 0; @@ -508,7 +512,7 @@ int parse_record_route_headers(sip_msg_t *msg) hf = msg->record_route; while(hf) { - if (parse_rr(hf) < 0) { + if(parse_rr(hf) < 0) { LM_ERR("failed to parse Record-Route\n"); return -1; } @@ -531,7 +535,7 @@ int parse_route_headers(sip_msg_t *msg) hf = msg->route; while(hf) { - if (parse_rr(hf) < 0) { + if(parse_rr(hf) < 0) { LM_ERR("failed to parse Record-Route\n"); return -1; } diff --git a/src/core/parser/parse_rr.h b/src/core/parser/parse_rr.h index 7c38a2d38df..ca00aba6ae8 100644 --- a/src/core/parser/parse_rr.h +++ b/src/core/parser/parse_rr.h @@ -15,8 +15,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ @@ -39,19 +39,20 @@ /*! \brief * Structure representing a Route & Record-Route HF body */ -typedef struct rr { +typedef struct rr +{ name_addr_t nameaddr; /*!< Name-addr part */ - param_t* r2; /*!< Hook to r2 parameter */ - param_t* params; /*!< Linked list of other parameters */ - int len; /*!< Length of the whole route field */ - struct rr* next; /*!< Next RR in the list */ + param_t *r2; /*!< Hook to r2 parameter */ + param_t *params; /*!< Linked list of other parameters */ + int len; /*!< Length of the whole route field */ + struct rr *next; /*!< Next RR in the list */ } rr_t; /* * Parse Route & Record-Route header fields */ -int parse_rr(struct hdr_field* _r); +int parse_rr(struct hdr_field *_r); /* * Parse the body of Route & Record-Route headers @@ -62,112 +63,147 @@ int parse_rr_body(char *buf, int len, rr_t **head); * Free list of rr * _c is head of the list */ -void free_rr(rr_t** _r); +void free_rr(rr_t **_r); /* * Free list of rr * _c is head of the list */ -void shm_free_rr(rr_t** _r); +void shm_free_rr(rr_t **_r); /* * Print list of rrs, just for debugging */ -void print_rr(FILE* _o, rr_t* _r); +void print_rr(FILE *_o, rr_t *_r); /* * Duplicate a single rr_t structure using pkg_malloc */ -int duplicate_rr(rr_t** _new, rr_t* _r); +int duplicate_rr(rr_t **_new, rr_t *_r); /* * Duplicate a single rr_t structure using pkg_malloc */ -int shm_duplicate_rr(rr_t** _new, rr_t* _r); +int shm_duplicate_rr(rr_t **_new, rr_t *_r); /* * Find out if a URI contains r2 parameter which indicates * that we put 2 record routes */ -static inline int is_2rr(str* _params) +static inline int is_2rr(str *_params) { str s; int i, state = 0; - if (_params->len == 0) return 0; + if(_params->len == 0) + return 0; s = *_params; for(i = 0; i < s.len; i++) { switch(state) { - case 0: - switch(s.s[i]) { - case ' ': - case '\r': - case '\n': - case '\t': break; - case 'r': - case 'R': state = 1; break; - default: state = 4; break; - } - break; - - case 1: - switch(s.s[i]) { - case '2': state = 2; break; - default: state = 4; break; - } - break; - - case 2: - switch(s.s[i]) { - case ';': return 1; - case '=': return 1; - case ' ': - case '\r': - case '\n': - case '\t': state = 3; break; - default: state = 4; break; - } - break; - - case 3: - switch(s.s[i]) { - case ';': return 1; - case '=': return 1; - case ' ': - case '\r': - case '\n': - case '\t': break; - default: state = 4; break; - } - break; - - case 4: - switch(s.s[i]) { - case '\"': state = 5; break; - case ';': state = 0; break; - default: break; - } - break; - - case 5: - switch(s.s[i]) { - case '\\': state = 6; break; - case '\"': state = 4; break; - default: break; - } - break; - - case 6: state = 5; break; + case 0: + switch(s.s[i]) { + case ' ': + case '\r': + case '\n': + case '\t': + break; + case 'r': + case 'R': + state = 1; + break; + default: + state = 4; + break; + } + break; + + case 1: + switch(s.s[i]) { + case '2': + state = 2; + break; + default: + state = 4; + break; + } + break; + + case 2: + switch(s.s[i]) { + case ';': + return 1; + case '=': + return 1; + case ' ': + case '\r': + case '\n': + case '\t': + state = 3; + break; + default: + state = 4; + break; + } + break; + + case 3: + switch(s.s[i]) { + case ';': + return 1; + case '=': + return 1; + case ' ': + case '\r': + case '\n': + case '\t': + break; + default: + state = 4; + break; + } + break; + + case 4: + switch(s.s[i]) { + case '\"': + state = 5; + break; + case ';': + state = 0; + break; + default: + break; + } + break; + + case 5: + switch(s.s[i]) { + case '\\': + state = 6; + break; + case '\"': + state = 4; + break; + default: + break; + } + break; + + case 6: + state = 5; + break; } } - if ((state == 2) || (state == 3)) return 1; - else return 0; + if((state == 2) || (state == 3)) + return 1; + else + return 0; } /*! @@ -176,7 +212,7 @@ static inline int is_2rr(str* _params) * - nb_recs - input=skip number of rr; output=number of printed rrs */ int print_rr_body(struct hdr_field *iroute, str *oroute, int order, - unsigned int * nb_recs); + unsigned int *nb_recs); int get_path_dst_uri(str *_p, str *_dst); diff --git a/src/core/parser/parse_sipifmatch.c b/src/core/parser/parse_sipifmatch.c index dd77e668459..c19d615ef09 100644 --- a/src/core/parser/parse_sipifmatch.c +++ b/src/core/parser/parse_sipifmatch.c @@ -32,7 +32,7 @@ #include "../mem/mem.h" #include "../trim.h" -static inline char* skip_token(char* _b, int _l) +static inline char *skip_token(char *_b, int _l) { int i = 0; @@ -53,14 +53,14 @@ static inline char* skip_token(char* _b, int _l) int etag_parser(char *_s, int _l, str *_e) { - char* end; + char *end; _e->s = _s; _e->len = _l; trim_leading(_e); - if (_e->len == 0) { + if(_e->len == 0) { LM_ERR("Empty body\n"); return -1; } @@ -72,38 +72,38 @@ int etag_parser(char *_s, int _l, str *_e) } -int parse_sipifmatch(struct hdr_field* _h) +int parse_sipifmatch(struct hdr_field *_h) { str *e; LM_DBG("parse sip-if-match called\n"); - if (_h->parsed != 0) { + if(_h->parsed != 0) { return 0; } - e = (str*)pkg_malloc(sizeof(str)); - if (e == 0) { + e = (str *)pkg_malloc(sizeof(str)); + if(e == 0) { PKG_MEM_ERROR; return -1; } memset(e, 0, sizeof(str)); - if (etag_parser(_h->body.s, _h->body.len, e) < 0) { + if(etag_parser(_h->body.s, _h->body.len, e) < 0) { LM_ERR("Error in etag parser\n"); pkg_free(e); return -2; } - _h->parsed = (void*)e; + _h->parsed = (void *)e; return 0; } -void free_sipifmatch(str** _e) +void free_sipifmatch(str **_e) { - if (*_e) + if(*_e) pkg_free(*_e); *_e = 0; } diff --git a/src/core/parser/parse_sipifmatch.h b/src/core/parser/parse_sipifmatch.h index dff641682e2..88921eb45b2 100644 --- a/src/core/parser/parse_sipifmatch.h +++ b/src/core/parser/parse_sipifmatch.h @@ -30,21 +30,22 @@ #include "../str.h" #include "hf.h" -typedef struct etag { - str text; /* Original string representation */ +typedef struct etag +{ + str text; /* Original string representation */ } etag_t; /*! \brief * Parse Sipifmatch HF body */ -int parse_sipifmatch(struct hdr_field* _h); +int parse_sipifmatch(struct hdr_field *_h); /*! \brief * Release memory */ -void free_sipifmatch(str** _e); +void free_sipifmatch(str **_e); #endif /* PARSE_SIPIFMATCH_H */ diff --git a/src/core/parser/parse_subscription_state.c b/src/core/parser/parse_subscription_state.c index f7bdc88d569..5d4f20b803b 100644 --- a/src/core/parser/parse_subscription_state.c +++ b/src/core/parser/parse_subscription_state.c @@ -33,10 +33,11 @@ #include "parse_param.h" #include -void free_subscription_state(subscription_state_t**ss) +void free_subscription_state(subscription_state_t **ss) { - if (ss) { - if (*ss) pkg_free(*ss); + if(ss) { + if(*ss) + pkg_free(*ss); *ss = 0; } } @@ -44,11 +45,13 @@ void free_subscription_state(subscription_state_t**ss) static inline int str_cmp(const str *a, const str *b) { int i; - - if (a->len != b->len) return 1; - - for (i = 0; i < a->len; i++) - if (a->s[i] != b->s[i]) return 1; + + if(a->len != b->len) + return 1; + + for(i = 0; i < a->len; i++) + if(a->s[i] != b->s[i]) + return 1; return 0; } @@ -57,69 +60,65 @@ static int ss_parse(str *src, subscription_state_t *ss) static str active = STR_STATIC_INIT("active"); static str pending = STR_STATIC_INIT("pending"); static str terminated = STR_STATIC_INIT("terminated"); - + int res = 0; param_hooks_t ph; param_t *params; str s = *src; str state; char *c; - + /* initialization */ ss->expires_set = 0; ss->expires = 0; - + trim_leading(&s); - + state = s; - + c = find_not_quoted(&s, ';'); - if (c) { + if(c) { /* first parameter starts after c */ state.len = c - state.s; s.len = s.len - (c - s.s) - 1; s.s = c + 1; - } - else { + } else { s.len = 0; } /* set state value */ trim(&state); - if (str_cmp(&state, &active) == 0) { + if(str_cmp(&state, &active) == 0) { ss->value = ss_active; - } - else if (str_cmp(&state, &pending) == 0) { + } else if(str_cmp(&state, &pending) == 0) { ss->value = ss_pending; - } - else if (str_cmp(&state, &terminated) == 0) { + } else if(str_cmp(&state, &terminated) == 0) { ss->value = ss_terminated; - } - else { + } else { /* INFO("unknown subscription-State value :%.*s\n", state.len, state.s); */ ss->value = ss_extension; } /* explore parameters */ - + trim_leading(&s); - if (s.len > 0) { + if(s.len > 0) { params = NULL; - if (parse_params(&s, CLASS_CONTACT, &ph, ¶ms) < 0) { + if(parse_params(&s, CLASS_CONTACT, &ph, ¶ms) < 0) { ERR("can't parse params\n"); res = -1; - } - else { - if (ph.contact.expires) { + } else { + if(ph.contact.expires) { ss->expires_set = 1; res = str2int(&ph.contact.expires->body, &ss->expires); - if (res != 0) - ERR("invalid expires value: \'%.*s\'\n", - ph.contact.expires->body.len, - ph.contact.expires->body.s); + if(res != 0) + ERR("invalid expires value: \'%.*s\'\n", + ph.contact.expires->body.len, + ph.contact.expires->body.s); } - if (params) free_params(params); + if(params) + free_params(params); } } /* @@ -133,23 +132,24 @@ static int ss_parse(str *src, subscription_state_t *ss) int parse_subscription_state(struct hdr_field *h) { subscription_state_t *ss; - if (h->parsed) return 0; + if(h->parsed) + return 0; - ss = (subscription_state_t*)pkg_malloc(sizeof(*ss)); - if (!ss) { + ss = (subscription_state_t *)pkg_malloc(sizeof(*ss)); + if(!ss) { PKG_MEM_ERROR; return -1; } memset(ss, 0, sizeof(*ss)); - if (ss_parse(&h->body, ss) < 0) { + if(ss_parse(&h->body, ss) < 0) { ERR("Can't parse Subscription-State\n"); pkg_free(ss); return -2; } - h->parsed = (void*)ss; - + h->parsed = (void *)ss; + return 0; } diff --git a/src/core/parser/parse_subscription_state.h b/src/core/parser/parse_subscription_state.h index 742d349d5d5..196dc8c9a70 100644 --- a/src/core/parser/parse_subscription_state.h +++ b/src/core/parser/parse_subscription_state.h @@ -29,14 +29,16 @@ #include "hf.h" -typedef enum { +typedef enum +{ ss_active, ss_pending, ss_terminated, ss_extension } substate_value_t; -typedef struct _subscription_state_t { +typedef struct _subscription_state_t +{ substate_value_t value; unsigned int expires; int expires_set; /* expires is valid if nonzero here */ diff --git a/src/core/parser/parse_supported.c b/src/core/parser/parse_supported.c index 4ca108c38f4..a0b1dc01b43 100644 --- a/src/core/parser/parse_supported.c +++ b/src/core/parser/parse_supported.c @@ -30,30 +30,31 @@ /*! * Parse all Supported headers */ -int parse_supported( struct sip_msg *msg) +int parse_supported(struct sip_msg *msg) { unsigned int supported; - struct hdr_field *hdr; + struct hdr_field *hdr; struct option_tag_body *sb; /* maybe the header is already parsed! */ - if (msg->supported && msg->supported->parsed) + if(msg->supported && msg->supported->parsed) return 0; /* parse to the end in order to get all SUPPORTED headers */ - if (parse_headers(msg,HDR_EOH_F,0)==-1 || !msg->supported) + if(parse_headers(msg, HDR_EOH_F, 0) == -1 || !msg->supported) return -1; /* bad luck! :-( - we have to parse them */ supported = 0; - for( hdr=msg->supported ; hdr ; hdr=next_sibling_hdr(hdr)) { - if (hdr->parsed) { - supported |= ((struct option_tag_body*)hdr->parsed)->option_tags; + for(hdr = msg->supported; hdr; hdr = next_sibling_hdr(hdr)) { + if(hdr->parsed) { + supported |= ((struct option_tag_body *)hdr->parsed)->option_tags; continue; } - sb = (struct option_tag_body*)pkg_malloc(sizeof(struct option_tag_body)); - if (sb == 0) { + sb = (struct option_tag_body *)pkg_malloc( + sizeof(struct option_tag_body)); + if(sb == 0) { PKG_MEM_ERROR; return -1; } @@ -61,11 +62,11 @@ int parse_supported( struct sip_msg *msg) parse_option_tag_body(&(hdr->body), &(sb->option_tags)); sb->hfree = hf_free_option_tag; sb->option_tags_all = 0; - hdr->parsed = (void*)sb; + hdr->parsed = (void *)sb; supported |= sb->option_tags; } - ((struct option_tag_body*)msg->supported->parsed)->option_tags_all = - supported; + ((struct option_tag_body *)msg->supported->parsed)->option_tags_all = + supported; return 0; } diff --git a/src/core/parser/parse_supported.h b/src/core/parser/parse_supported.h index 1a55827a3e4..032a129c6ed 100644 --- a/src/core/parser/parse_supported.h +++ b/src/core/parser/parse_supported.h @@ -32,14 +32,17 @@ #include "../mem/mem.h" #include "parse_option_tags.h" -#define get_supported(p_msg) \ - ((p_msg)->supported ? ((struct option_tag_body*)(p_msg)->supported->parsed)->option_tags_all : 0) +#define get_supported(p_msg) \ + ((p_msg)->supported \ + ? ((struct option_tag_body *)(p_msg)->supported->parsed) \ + ->option_tags_all \ + : 0) /*! * Parse all Supported headers. */ -int parse_supported( struct sip_msg *msg); +int parse_supported(struct sip_msg *msg); void free_supported(struct option_tag_body **sb); diff --git a/src/core/parser/parse_to.c b/src/core/parser/parse_to.c index 0832bb84690..c9df1b66d14 100644 --- a/src/core/parser/parse_to.c +++ b/src/core/parser/parse_to.c @@ -35,8 +35,8 @@ #include "../mem/mem.h" -char *parse_to(char *const buffer, const char *const end, - struct to_body *const to_b) +char *parse_to( + char *const buffer, const char *const end, struct to_body *const to_b) { return parse_addr_spec(buffer, end, to_b, 0); } diff --git a/src/core/parser/parse_to.h b/src/core/parser/parse_to.h index 7ffe12d931d..c2bc5004334 100644 --- a/src/core/parser/parse_to.h +++ b/src/core/parser/parse_to.h @@ -13,8 +13,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ @@ -32,18 +32,19 @@ #include "parse_addr_spec.h" /* casting macro for accessing To body */ -#define get_to(p_msg) ((struct to_body*)(p_msg)->to->parsed) +#define get_to(p_msg) ((struct to_body *)(p_msg)->to->parsed) #define GET_TO_PURI(p_msg) \ - (&((struct to_body*)(p_msg)->to->parsed)->parsed_uri) + (&((struct to_body *)(p_msg)->to->parsed)->parsed_uri) /*! \brief * To header field parser */ -char* parse_to(char* const buffer, const char* const end, struct to_body* const to_b); +char *parse_to( + char *const buffer, const char *const end, struct to_body *const to_b); -int parse_to_header(struct sip_msg* const msg); +int parse_to_header(struct sip_msg *const msg); -sip_uri_t *parse_to_uri(struct sip_msg* const msg); +sip_uri_t *parse_to_uri(struct sip_msg *const msg); #endif diff --git a/src/core/parser/parse_uri.c b/src/core/parser/parse_uri.c index 79865751c25..9ccb62ee51e 100644 --- a/src/core/parser/parse_uri.c +++ b/src/core/parser/parse_uri.c @@ -32,12 +32,12 @@ #include "parse_uri.h" #include #include "../dprint.h" -#include "../ut.h" /* q_memchr */ +#include "../ut.h" /* q_memchr */ #include "../error.h" #include "../core_stats.h" static char _sr_uri_empty_buf[2] = {0}; -static str _sr_uri_empty = { _sr_uri_empty_buf, 0 }; +static str _sr_uri_empty = {_sr_uri_empty_buf, 0}; /* extra chars that should be allowed in URI host */ char *_sr_uri_host_extra_chars = ""; @@ -46,11 +46,12 @@ int uri_host_char_allowed(char c) { int i = 0; - if(_sr_uri_host_extra_chars==NULL || _sr_uri_host_extra_chars[0]=='\0') { + if(_sr_uri_host_extra_chars == NULL + || _sr_uri_host_extra_chars[0] == '\0') { return 0; } - while(_sr_uri_host_extra_chars[i]!='\0') { - if(_sr_uri_host_extra_chars[i]==c) { + while(_sr_uri_host_extra_chars[i] != '\0') { + if(_sr_uri_host_extra_chars[i] == c) { return 1; } i++; @@ -62,68 +63,128 @@ int uri_host_char_allowed(char c) * len= len of uri * returns: fills uri & returns <0 on error or 0 if ok */ -int parse_uri(char* buf, int len, struct sip_uri* uri) +int parse_uri(char *buf, int len, struct sip_uri *uri) { - enum states { URI_INIT, URI_USER, URI_PASSWORD, URI_PASSWORD_ALPHA, - URI_HOST, URI_HOST_P, - URI_HOST6_P, URI_HOST6_END, URI_PORT, - URI_PARAM, URI_PARAM_P, URI_VAL_P, URI_HEADERS, - /* param states */ - /* transport */ - PT_T, PT_R, PT_A, PT_N, PT_S, PT_P, PT_O, PT_R2, PT_T2, - PT_eq, - /* ttl */ - PTTL_T2, PTTL_L, PTTL_eq, - /* user */ - PU_U, PU_S, PU_E, PU_R, PU_eq, - /* method */ - PM_M, PM_E, PM_T, PM_H, PM_O, PM_D, PM_eq, - /* maddr */ - PMA_A, PMA_D, PMA_D2, PMA_R, PMA_eq, - /* lr */ - PLR_L, PLR_R_FIN, PLR_eq, - /* r2 */ - PR2_R, PR2_2_FIN, PR2_eq, - /* gr */ - PGR_G, PGR_R_FIN, PGR_eq, + enum states + { + URI_INIT, + URI_USER, + URI_PASSWORD, + URI_PASSWORD_ALPHA, + URI_HOST, + URI_HOST_P, + URI_HOST6_P, + URI_HOST6_END, + URI_PORT, + URI_PARAM, + URI_PARAM_P, + URI_VAL_P, + URI_HEADERS, + /* param states */ + /* transport */ + PT_T, + PT_R, + PT_A, + PT_N, + PT_S, + PT_P, + PT_O, + PT_R2, + PT_T2, + PT_eq, + /* ttl */ + PTTL_T2, + PTTL_L, + PTTL_eq, + /* user */ + PU_U, + PU_S, + PU_E, + PU_R, + PU_eq, + /* method */ + PM_M, + PM_E, + PM_T, + PM_H, + PM_O, + PM_D, + PM_eq, + /* maddr */ + PMA_A, + PMA_D, + PMA_D2, + PMA_R, + PMA_eq, + /* lr */ + PLR_L, + PLR_R_FIN, + PLR_eq, + /* r2 */ + PR2_R, + PR2_2_FIN, + PR2_eq, + /* gr */ + PGR_G, + PGR_R_FIN, + PGR_eq, #ifdef USE_COMP - /* comp */ - PCOMP_C, PCOMP_O, PCOMP_M, PCOMP_P, PCOMP_eq, + /* comp */ + PCOMP_C, + PCOMP_O, + PCOMP_M, + PCOMP_P, + PCOMP_eq, - /* comp values */ - /* sigcomp */ - VCOMP_S, VCOMP_SIGC_I, VCOMP_SIGC_G, - VCOMP_SIGC_C, VCOMP_SIGC_O, VCOMP_SIGC_M, - VCOMP_SIGC_P_FIN, - /* sergz */ - VCOMP_SGZ_E, VCOMP_SGZ_R, VCOMP_SGZ_G, - VCOMP_SGZ_Z_FIN, + /* comp values */ + /* sigcomp */ + VCOMP_S, + VCOMP_SIGC_I, + VCOMP_SIGC_G, + VCOMP_SIGC_C, + VCOMP_SIGC_O, + VCOMP_SIGC_M, + VCOMP_SIGC_P_FIN, + /* sergz */ + VCOMP_SGZ_E, + VCOMP_SGZ_R, + VCOMP_SGZ_G, + VCOMP_SGZ_Z_FIN, #endif - /* transport values */ - /* udp */ - VU_U, VU_D, VU_P_FIN, - /* tcp */ - VT_T, VT_C, VT_P_FIN, - /* tls */ - VTLS_L, VTLS_S_FIN, - /* sctp */ - VS_S, VS_C, VS_T, VS_P_FIN, - /* ws */ - VW_W, VW_S_FIN + /* transport values */ + /* udp */ + VU_U, + VU_D, + VU_P_FIN, + /* tcp */ + VT_T, + VT_C, + VT_P_FIN, + /* tls */ + VTLS_L, + VTLS_S_FIN, + /* sctp */ + VS_S, + VS_C, + VS_T, + VS_P_FIN, + /* ws */ + VW_W, + VW_S_FIN }; register enum states state; - char* s; - char* b; /* param start */ - char *v; /* value start */ - str* param; /* current param */ - str* param_val; /* current param val */ + char *s; + char *b; /* param start */ + char *v; /* value start */ + str *param; /* current param */ + str *param_val; /* current param val */ str user; str password; int port_no; - register char* p; - char* end; - char* pass; + register char *p; + char *end; + char *pass; int found_user; int error_headers; uint32_t scheme; @@ -135,287 +196,294 @@ int parse_uri(char* buf, int len, struct sip_uri* uri) str comp_val; /* not returned for now */ #endif -#define SIP_SCH 0x3a706973 -#define SIPS_SCH 0x73706973 -#define TEL_SCH 0x3a6c6574 -#define URN_SCH 0x3a6e7275 +#define SIP_SCH 0x3a706973 +#define SIPS_SCH 0x73706973 +#define TEL_SCH 0x3a6c6574 +#define URN_SCH 0x3a6e7275 -#define case_port( ch, var) \ - case ch: \ - (var)=(var)*10+ch-'0'; \ - if((var) > MAX_PORT_VAL) { \ - goto error_bad_port; \ - }\ - break +#define case_port(ch, var) \ + case ch: \ + (var) = (var)*10 + ch - '0'; \ + if((var) > MAX_PORT_VAL) { \ + goto error_bad_port; \ + } \ + break -#define still_at_user \ - if (found_user==0){ \ - user.s=uri->host.s; \ - if (pass){\ - user.len=pass-user.s; \ - password.s=pass+1; \ - password.len=p-password.s; \ - }else{ \ - user.len=p-user.s; \ - }\ - /* save the uri type/scheme */ \ - backup_urit=uri->type; \ - backup_urif=uri->flags; \ - /* everything else is 0 */ \ - memset(uri, 0, sizeof(struct sip_uri)); \ - /* restore the scheme & flags, copy user & pass */ \ - uri->type=backup_urit; \ - uri->flags=backup_urif; \ - uri->user=user; \ - if (pass) uri->passwd=password; \ - s=p+1; \ - found_user=1;\ - error_headers=0; \ - state=URI_HOST; \ - }else goto error_bad_char +#define still_at_user \ + if(found_user == 0) { \ + user.s = uri->host.s; \ + if(pass) { \ + user.len = pass - user.s; \ + password.s = pass + 1; \ + password.len = p - password.s; \ + } else { \ + user.len = p - user.s; \ + } \ + /* save the uri type/scheme */ \ + backup_urit = uri->type; \ + backup_urif = uri->flags; \ + /* everything else is 0 */ \ + memset(uri, 0, sizeof(struct sip_uri)); \ + /* restore the scheme & flags, copy user & pass */ \ + uri->type = backup_urit; \ + uri->flags = backup_urif; \ + uri->user = user; \ + if(pass) \ + uri->passwd = password; \ + s = p + 1; \ + found_user = 1; \ + error_headers = 0; \ + state = URI_HOST; \ + } else \ + goto error_bad_char -#define check_host_end \ - case ':': \ - /* found the host */ \ - uri->host.s=s; \ - uri->host.len=p-s; \ - state=URI_PORT; \ - s=p+1; \ - break; \ - case ';': \ - uri->host.s=s; \ - uri->host.len=p-s; \ - state=URI_PARAM; \ - s=p+1; \ - break; \ - case '?': \ - uri->host.s=s; \ - uri->host.len=p-s; \ - state=URI_HEADERS; \ - s=p+1; \ - break; \ - case '&': \ - case '@': \ - goto error_bad_char +#define check_host_end \ + case ':': \ + /* found the host */ \ + uri->host.s = s; \ + uri->host.len = p - s; \ + state = URI_PORT; \ + s = p + 1; \ + break; \ + case ';': \ + uri->host.s = s; \ + uri->host.len = p - s; \ + state = URI_PARAM; \ + s = p + 1; \ + break; \ + case '?': \ + uri->host.s = s; \ + uri->host.len = p - s; \ + state = URI_HEADERS; \ + s = p + 1; \ + break; \ + case '&': \ + case '@': \ + goto error_bad_char #define param_set(t_start, v_start) \ - param->s=(t_start);\ - param->len=(p-(t_start));\ - param_val->s=(v_start); \ - param_val->len=(p-(v_start)) + param->s = (t_start); \ + param->len = (p - (t_start)); \ + param_val->s = (v_start); \ + param_val->len = (p - (v_start)) -#define semicolon_case \ - case';': \ - if (pass){ \ - found_user=1;/* no user, pass cannot contain ';'*/ \ - pass=0; \ - } \ - state=URI_PARAM /* new param */ +#define semicolon_case \ + case ';': \ + if(pass) { \ + found_user = 1; /* no user, pass cannot contain ';'*/ \ + pass = 0; \ + } \ + state = URI_PARAM /* new param */ -#define question_case \ - case '?': \ - uri->params.s=s; \ - uri->params.len=p-s; \ - state=URI_HEADERS; \ - s=p+1; \ - if (pass){ \ - found_user=1;/* no user, pass cannot contain '?'*/ \ - pass=0; \ - } +#define question_case \ + case '?': \ + uri->params.s = s; \ + uri->params.len = p - s; \ + state = URI_HEADERS; \ + s = p + 1; \ + if(pass) { \ + found_user = 1; /* no user, pass cannot contain '?'*/ \ + pass = 0; \ + } -#define colon_case \ - case ':': \ - if (found_user==0){ \ - /*might be pass but only if user not found yet*/ \ - if (pass){ \ - found_user=1; /* no user */ \ - pass=0; \ - }else{ \ - pass=p; \ - } \ - } \ - state=URI_PARAM_P /* generic param */ +#define colon_case \ + case ':': \ + if(found_user == 0) { \ + /*might be pass but only if user not found yet*/ \ + if(pass) { \ + found_user = 1; /* no user */ \ + pass = 0; \ + } else { \ + pass = p; \ + } \ + } \ + state = URI_PARAM_P /* generic param */ -#define param_common_cases \ - case '@': \ - /* ughhh, this is still the user */ \ - still_at_user; \ - break; \ - semicolon_case; \ - break; \ - question_case; \ - break; \ - colon_case; \ - break +#define param_common_cases \ + case '@': \ + /* ughhh, this is still the user */ \ + still_at_user; \ + break; \ + semicolon_case; \ + break; \ + question_case; \ + break; \ + colon_case; \ + break -#define value_common_cases \ - case '@': \ - /* ughhh, this is still the user */ \ - still_at_user; \ - break; \ - semicolon_case; \ - param_set(b, v); \ - break; \ - question_case; \ - param_set(b, v); \ - break; \ - colon_case; \ - state=URI_VAL_P; \ - break +#define value_common_cases \ + case '@': \ + /* ughhh, this is still the user */ \ + still_at_user; \ + break; \ + semicolon_case; \ + param_set(b, v); \ + break; \ + question_case; \ + param_set(b, v); \ + break; \ + colon_case; \ + state = URI_VAL_P; \ + break #define param_switch(old_state, c1, c2, new_state) \ - case old_state: \ - switch(*p){ \ - case c1: \ - case c2: \ - state=(new_state); \ - break; \ - param_common_cases; \ - default: \ - state=URI_PARAM_P; \ - } \ - break + case old_state: \ + switch(*p) { \ + case c1: \ + case c2: \ + state = (new_state); \ + break; \ + param_common_cases; \ + default: \ + state = URI_PARAM_P; \ + } \ + break #define param_switch1(old_state, c1, new_state) \ - case old_state: \ - switch(*p){ \ - case c1: \ - state=(new_state); \ - break; \ - param_common_cases; \ - default: \ - state=URI_PARAM_P; \ - } \ - break + case old_state: \ + switch(*p) { \ + case c1: \ + state = (new_state); \ + break; \ + param_common_cases; \ + default: \ + state = URI_PARAM_P; \ + } \ + break #define param_switch_big(old_state, c1, c2, d1, d2, new_state_c, new_state_d) \ - case old_state : \ - switch(*p){ \ - case c1: \ - case c2: \ - state=(new_state_c); \ - break; \ - case d1: \ - case d2: \ - state=(new_state_d); \ - break; \ - param_common_cases; \ - default: \ - state=URI_PARAM_P; \ - } \ - break + case old_state: \ + switch(*p) { \ + case c1: \ + case c2: \ + state = (new_state_c); \ + break; \ + case d1: \ + case d2: \ + state = (new_state_d); \ + break; \ + param_common_cases; \ + default: \ + state = URI_PARAM_P; \ + } \ + break #define value_switch(old_state, c1, c2, new_state) \ - case old_state: \ - switch(*p){ \ - case c1: \ - case c2: \ - state=(new_state); \ - break; \ - value_common_cases; \ - default: \ - state=URI_VAL_P; \ - } \ - break + case old_state: \ + switch(*p) { \ + case c1: \ + case c2: \ + state = (new_state); \ + break; \ + value_common_cases; \ + default: \ + state = URI_VAL_P; \ + } \ + break #define value_switch_big(old_state, c1, c2, d1, d2, new_state_c, new_state_d) \ - case old_state: \ - switch(*p){ \ - case c1: \ - case c2: \ - state=(new_state_c); \ - break; \ - case d1: \ - case d2: \ - state=(new_state_d); \ - break; \ - value_common_cases; \ - default: \ - state=URI_VAL_P; \ - } \ - break + case old_state: \ + switch(*p) { \ + case c1: \ + case c2: \ + state = (new_state_c); \ + break; \ + case d1: \ + case d2: \ + state = (new_state_d); \ + break; \ + value_common_cases; \ + default: \ + state = URI_VAL_P; \ + } \ + break #define transport_fin(c_state, proto_no) \ - case c_state: \ - switch(*p){ \ - case '@': \ - still_at_user; \ - break; \ - semicolon_case; \ - param_set(b, v); \ - uri->proto=(proto_no); \ - break; \ - question_case; \ - param_set(b, v); \ - uri->proto=(proto_no); \ - break; \ - colon_case; \ - default: \ - state=URI_VAL_P; \ - break; \ - } \ - break + case c_state: \ + switch(*p) { \ + case '@': \ + still_at_user; \ + break; \ + semicolon_case; \ + param_set(b, v); \ + uri->proto = (proto_no); \ + break; \ + question_case; \ + param_set(b, v); \ + uri->proto = (proto_no); \ + break; \ + colon_case; \ + default: \ + state = URI_VAL_P; \ + break; \ + } \ + break #ifdef USE_COMP -#define comp_fin(c_state, comp_no) \ - case c_state: \ - switch(*p){ \ - case '@': \ - still_at_user; \ - break; \ - semicolon_case; \ - /* param_set(b, v); */ \ - uri->comp=(comp_no); \ - break; \ - question_case; \ - /* param_set(b, v) */; \ - uri->comp=(comp_no); \ - break; \ - colon_case; \ - default: \ - state=URI_VAL_P; \ - break; \ - } \ - break +#define comp_fin(c_state, comp_no) \ + case c_state: \ + switch(*p) { \ + case '@': \ + still_at_user; \ + break; \ + semicolon_case; \ + /* param_set(b, v); */ \ + uri->comp = (comp_no); \ + break; \ + question_case; \ + /* param_set(b, v) */; \ + uri->comp = (comp_no); \ + break; \ + colon_case; \ + default: \ + state = URI_VAL_P; \ + break; \ + } \ + break #endif /* init */ - end=buf+len; - p=buf+4; - found_user=0; - error_headers=0; - b=v=0; - param=param_val=0; - pass=0; - password.s=0; /* fixes gcc 4.0 warning */ - password.len=0; - port_no=0; - state=URI_INIT; + end = buf + len; + p = buf + 4; + found_user = 0; + error_headers = 0; + b = v = 0; + param = param_val = 0; + pass = 0; + password.s = 0; /* fixes gcc 4.0 warning */ + password.len = 0; + port_no = 0; + state = URI_INIT; memset(uri, 0, sizeof(struct sip_uri)); /* zero it all, just to be sure*/ /*look for sip:, sips:, tel: or urn:*/ - if (len<5) goto error_too_short; - scheme=((uint32_t)buf[0]) + (((uint32_t)buf[1])<<8) - + (((uint32_t)buf[2])<<16) + (((uint32_t)buf[3])<<24); - scheme|=0x20202020; - if (scheme==SIP_SCH){ - uri->type=SIP_URI_T; - }else if(scheme==SIPS_SCH){ - if(buf[4]==':'){ p++; uri->type=SIPS_URI_T;} - else goto error_bad_uri; - }else if (scheme==TEL_SCH){ - uri->type=TEL_URI_T; - }else if (scheme==URN_SCH){ - uri->type=URN_URI_T; - }else goto error_bad_uri; + if(len < 5) + goto error_too_short; + scheme = ((uint32_t)buf[0]) + (((uint32_t)buf[1]) << 8) + + (((uint32_t)buf[2]) << 16) + (((uint32_t)buf[3]) << 24); + scheme |= 0x20202020; + if(scheme == SIP_SCH) { + uri->type = SIP_URI_T; + } else if(scheme == SIPS_SCH) { + if(buf[4] == ':') { + p++; + uri->type = SIPS_URI_T; + } else + goto error_bad_uri; + } else if(scheme == TEL_SCH) { + uri->type = TEL_URI_T; + } else if(scheme == URN_SCH) { + uri->type = URN_URI_T; + } else + goto error_bad_uri; - s=p; - for(;puser.s=s; - uri->user.len=p-s; - if(uri->user.len<=0) { + uri->user.s = s; + uri->user.len = p - s; + if(uri->user.len <= 0) { /* at '@' and no user part */ goto error_bad_char; } - state=URI_HOST; - found_user=1; - s=p+1; /* skip '@' */ + state = URI_HOST; + found_user = 1; + s = p + 1; /* skip '@' */ break; case ':': /* found the user, or the host? */ - uri->user.s=s; - uri->user.len=p-s; - state=URI_PASSWORD; - s=p+1; /* skip ':' */ + uri->user.s = s; + uri->user.len = p - s; + state = URI_PASSWORD; + s = p + 1; /* skip ':' */ break; case ';': /* this could be still the user or * params?*/ - uri->host.s=s; - uri->host.len=p-s; - state=URI_PARAM; - s=p+1; + uri->host.s = s; + uri->host.len = p - s; + state = URI_PARAM; + s = p + 1; break; case '?': /* still user or headers? */ - uri->host.s=s; - uri->host.len=p-s; - state=URI_HEADERS; - s=p+1; + uri->host.s = s; + uri->host.len = p - s; + state = URI_HEADERS; + s = p + 1; break; /* almost anything permitted in the user part */ case '.': @@ -471,7 +539,7 @@ int parse_uri(char* buf, int len, struct sip_uri* uri) /* tel uri visual separators, set flag meaning, that * user should be normalized before usage */ - uri->flags|=URI_USER_NORMALIZE; + uri->flags |= URI_USER_NORMALIZE; break; case '[': case ']': /* the user part cannot contain "[]" */ @@ -479,73 +547,73 @@ int parse_uri(char* buf, int len, struct sip_uri* uri) } break; case URI_PASSWORD: /* this can also be the port (missing user)*/ - switch(*p){ + switch(*p) { case '@': /* found the password*/ - uri->passwd.s=s; - uri->passwd.len=p-s; - port_no=0; - state=URI_HOST; - found_user=1; - s=p+1; /* skip '@' */ + uri->passwd.s = s; + uri->passwd.len = p - s; + port_no = 0; + state = URI_HOST; + found_user = 1; + s = p + 1; /* skip '@' */ break; case ';': /* upps this is the port */ - uri->port.s=s; - uri->port.len=p-s; - uri->port_no=port_no; + uri->port.s = s; + uri->port.len = p - s; + uri->port_no = port_no; /* user contains in fact the host */ - uri->host.s=uri->user.s; - uri->host.len=uri->user.len; - uri->user.s=0; - uri->user.len=0; - state=URI_PARAM; - found_user=1; /* there is no user part */ - s=p+1; + uri->host.s = uri->user.s; + uri->host.len = uri->user.len; + uri->user.s = 0; + uri->user.len = 0; + state = URI_PARAM; + found_user = 1; /* there is no user part */ + s = p + 1; break; case '?': /* upps this is the port */ - uri->port.s=s; - uri->port.len=p-s; - uri->port_no=port_no; + uri->port.s = s; + uri->port.len = p - s; + uri->port_no = port_no; /* user contains in fact the host */ - uri->host.s=uri->user.s; - uri->host.len=uri->user.len; - uri->user.s=0; - uri->user.len=0; - state=URI_HEADERS; - found_user=1; /* there is no user part */ - s=p+1; + uri->host.s = uri->user.s; + uri->host.len = uri->user.len; + uri->user.s = 0; + uri->user.len = 0; + state = URI_HEADERS; + found_user = 1; /* there is no user part */ + s = p + 1; break; - case_port('0', port_no); - case_port('1', port_no); - case_port('2', port_no); - case_port('3', port_no); - case_port('4', port_no); - case_port('5', port_no); - case_port('6', port_no); - case_port('7', port_no); - case_port('8', port_no); - case_port('9', port_no); + case_port('0', port_no); + case_port('1', port_no); + case_port('2', port_no); + case_port('3', port_no); + case_port('4', port_no); + case_port('5', port_no); + case_port('6', port_no); + case_port('7', port_no); + case_port('8', port_no); + case_port('9', port_no); case '[': case ']': case ':': goto error_bad_char; default: /* it can't be the port, non number found */ - port_no=0; - state=URI_PASSWORD_ALPHA; + port_no = 0; + state = URI_PASSWORD_ALPHA; } break; case URI_PASSWORD_ALPHA: - switch(*p){ + switch(*p) { case '@': /* found the password*/ - uri->passwd.s=s; - uri->passwd.len=p-s; - state=URI_HOST; - found_user=1; - s=p+1; /* skip '@' */ + uri->passwd.s = s; + uri->passwd.len = p - s; + state = URI_HOST; + found_user = 1; + s = p + 1; /* skip '@' */ break; case ';': /* contains non-numbers => cannot be port no*/ case '?': @@ -578,16 +646,16 @@ int parse_uri(char* buf, int len, struct sip_uri* uri) } break; case URI_HOST6_END: - switch(*p){ + switch(*p) { check_host_end; default: /*no chars allowed after [ipv6] */ goto error_bad_host; } break; case URI_HOST6_P: - switch(*p){ + switch(*p) { case ']': - state=URI_HOST6_END; + state = URI_HOST6_END; break; case '[': case '&': @@ -598,31 +666,31 @@ int parse_uri(char* buf, int len, struct sip_uri* uri) } break; case URI_PORT: - switch(*p){ + switch(*p) { case ';': - uri->port.s=s; - uri->port.len=p-s; - uri->port_no=port_no; - state=URI_PARAM; - s=p+1; + uri->port.s = s; + uri->port.len = p - s; + uri->port_no = port_no; + state = URI_PARAM; + s = p + 1; break; case '?': - uri->port.s=s; - uri->port.len=p-s; - uri->port_no=port_no; - state=URI_HEADERS; - s=p+1; + uri->port.s = s; + uri->port.len = p - s; + uri->port_no = port_no; + state = URI_HEADERS; + s = p + 1; break; - case_port('0', port_no); - case_port('1', port_no); - case_port('2', port_no); - case_port('3', port_no); - case_port('4', port_no); - case_port('5', port_no); - case_port('6', port_no); - case_port('7', port_no); - case_port('8', port_no); - case_port('9', port_no); + case_port('0', port_no); + case_port('1', port_no); + case_port('2', port_no); + case_port('3', port_no); + case_port('4', port_no); + case_port('5', port_no); + case_port('6', port_no); + case_port('7', port_no); + case_port('8', port_no); + case_port('9', port_no); case '&': case '@': case ':': @@ -631,366 +699,369 @@ int parse_uri(char* buf, int len, struct sip_uri* uri) } break; case URI_PARAM: /* beginning of a new param */ - switch(*p){ + switch(*p) { param_common_cases; /* recognized params */ case 't': case 'T': - b=p; - state=PT_T; + b = p; + state = PT_T; break; case 'u': case 'U': - b=p; - state=PU_U; + b = p; + state = PU_U; break; case 'm': case 'M': - b=p; - state=PM_M; + b = p; + state = PM_M; break; case 'l': case 'L': - b=p; - state=PLR_L; + b = p; + state = PLR_L; break; case 'r': case 'R': - b=p; - state=PR2_R; + b = p; + state = PR2_R; break; case 'g': case 'G': - b=p; - state=PGR_G; + b = p; + state = PGR_G; break; #ifdef USE_COMP case 'c': case 'C': - b=p; - state=PCOMP_C; + b = p; + state = PCOMP_C; break; #endif default: - state=URI_PARAM_P; + state = URI_PARAM_P; } break; case URI_PARAM_P: /* ignore current param */ /* supported params: * maddr, transport, ttl, lr, user, method, r2 */ - switch(*p){ + switch(*p) { param_common_cases; }; break; - /* ugly but fast param names parsing */ - /*transport */ - param_switch_big(PT_T, 'r', 'R', 't', 'T', PT_R, PTTL_T2); - param_switch(PT_R, 'a', 'A', PT_A); - param_switch(PT_A, 'n', 'N', PT_N); - param_switch(PT_N, 's', 'S', PT_S); - param_switch(PT_S, 'p', 'P', PT_P); - param_switch(PT_P, 'o', 'O', PT_O); - param_switch(PT_O, 'r', 'R', PT_R2); - param_switch(PT_R2, 't', 'T', PT_T2); - param_switch1(PT_T2, '=', PT_eq); + /* ugly but fast param names parsing */ + /*transport */ + param_switch_big(PT_T, 'r', 'R', 't', 'T', PT_R, PTTL_T2); + param_switch(PT_R, 'a', 'A', PT_A); + param_switch(PT_A, 'n', 'N', PT_N); + param_switch(PT_N, 's', 'S', PT_S); + param_switch(PT_S, 'p', 'P', PT_P); + param_switch(PT_P, 'o', 'O', PT_O); + param_switch(PT_O, 'r', 'R', PT_R2); + param_switch(PT_R2, 't', 'T', PT_T2); + param_switch1(PT_T2, '=', PT_eq); /* value parsing */ case PT_eq: - param=&uri->transport; - param_val=&uri->transport_val; - switch (*p){ + param = &uri->transport; + param_val = &uri->transport_val; + switch(*p) { param_common_cases; case 'u': case 'U': - v=p; - state=VU_U; + v = p; + state = VU_U; break; case 't': case 'T': - v=p; - state=VT_T; + v = p; + state = VT_T; break; case 's': case 'S': - v=p; - state=VS_S; + v = p; + state = VS_S; break; case 'w': case 'W': - v=p; - state=VW_W; + v = p; + state = VW_W; break; default: - v=p; - state=URI_VAL_P; + v = p; + state = URI_VAL_P; } break; /* generic value */ case URI_VAL_P: - switch(*p){ + switch(*p) { value_common_cases; } break; - /* udp */ - value_switch(VU_U, 'd', 'D', VU_D); - value_switch(VU_D, 'p', 'P', VU_P_FIN); - transport_fin(VU_P_FIN, PROTO_UDP); - /* tcp */ - value_switch_big(VT_T, 'c', 'C', 'l', 'L', VT_C, VTLS_L); - value_switch(VT_C, 'p', 'P', VT_P_FIN); - transport_fin(VT_P_FIN, PROTO_TCP); - /* tls */ - value_switch(VTLS_L, 's', 'S', VTLS_S_FIN); - transport_fin(VTLS_S_FIN, PROTO_TLS); - /* sctp */ - value_switch(VS_S, 'c', 'C', VS_C); - value_switch(VS_C, 't', 'T', VS_T); - value_switch(VS_T, 'p', 'P', VS_P_FIN); - transport_fin(VS_P_FIN, PROTO_SCTP); - /* ws */ - value_switch(VW_W, 's', 'S', VW_S_FIN); - transport_fin(VW_S_FIN, PROTO_WS); + /* udp */ + value_switch(VU_U, 'd', 'D', VU_D); + value_switch(VU_D, 'p', 'P', VU_P_FIN); + transport_fin(VU_P_FIN, PROTO_UDP); + /* tcp */ + value_switch_big(VT_T, 'c', 'C', 'l', 'L', VT_C, VTLS_L); + value_switch(VT_C, 'p', 'P', VT_P_FIN); + transport_fin(VT_P_FIN, PROTO_TCP); + /* tls */ + value_switch(VTLS_L, 's', 'S', VTLS_S_FIN); + transport_fin(VTLS_S_FIN, PROTO_TLS); + /* sctp */ + value_switch(VS_S, 'c', 'C', VS_C); + value_switch(VS_C, 't', 'T', VS_T); + value_switch(VS_T, 'p', 'P', VS_P_FIN); + transport_fin(VS_P_FIN, PROTO_SCTP); + /* ws */ + value_switch(VW_W, 's', 'S', VW_S_FIN); + transport_fin(VW_S_FIN, PROTO_WS); - /* ttl */ - param_switch(PTTL_T2, 'l', 'L', PTTL_L); - param_switch1(PTTL_L, '=', PTTL_eq); + /* ttl */ + param_switch(PTTL_T2, 'l', 'L', PTTL_L); + param_switch1(PTTL_L, '=', PTTL_eq); case PTTL_eq: - param=&uri->ttl; - param_val=&uri->ttl_val; - switch(*p){ + param = &uri->ttl; + param_val = &uri->ttl_val; + switch(*p) { param_common_cases; default: - v=p; - state=URI_VAL_P; + v = p; + state = URI_VAL_P; } break; - /* user param */ - param_switch(PU_U, 's', 'S', PU_S); - param_switch(PU_S, 'e', 'E', PU_E); - param_switch(PU_E, 'r', 'R', PU_R); - param_switch1(PU_R, '=', PU_eq); + /* user param */ + param_switch(PU_U, 's', 'S', PU_S); + param_switch(PU_S, 'e', 'E', PU_E); + param_switch(PU_E, 'r', 'R', PU_R); + param_switch1(PU_R, '=', PU_eq); case PU_eq: - param=&uri->user_param; - param_val=&uri->user_param_val; - switch(*p){ + param = &uri->user_param; + param_val = &uri->user_param_val; + switch(*p) { param_common_cases; default: - v=p; - state=URI_VAL_P; + v = p; + state = URI_VAL_P; } break; - /* method*/ - param_switch_big(PM_M, 'e', 'E', 'a', 'A', PM_E, PMA_A); - param_switch(PM_E, 't', 'T', PM_T); - param_switch(PM_T, 'h', 'H', PM_H); - param_switch(PM_H, 'o', 'O', PM_O); - param_switch(PM_O, 'd', 'D', PM_D); - param_switch1(PM_D, '=', PM_eq); + /* method*/ + param_switch_big(PM_M, 'e', 'E', 'a', 'A', PM_E, PMA_A); + param_switch(PM_E, 't', 'T', PM_T); + param_switch(PM_T, 'h', 'H', PM_H); + param_switch(PM_H, 'o', 'O', PM_O); + param_switch(PM_O, 'd', 'D', PM_D); + param_switch1(PM_D, '=', PM_eq); case PM_eq: - param=&uri->method; - param_val=&uri->method_val; - switch(*p){ + param = &uri->method; + param_val = &uri->method_val; + switch(*p) { param_common_cases; default: - v=p; - state=URI_VAL_P; + v = p; + state = URI_VAL_P; } break; - /*maddr*/ - param_switch(PMA_A, 'd', 'D', PMA_D); - param_switch(PMA_D, 'd', 'D', PMA_D2); - param_switch(PMA_D2, 'r', 'R', PMA_R); - param_switch1(PMA_R, '=', PMA_eq); + /*maddr*/ + param_switch(PMA_A, 'd', 'D', PMA_D); + param_switch(PMA_D, 'd', 'D', PMA_D2); + param_switch(PMA_D2, 'r', 'R', PMA_R); + param_switch1(PMA_R, '=', PMA_eq); case PMA_eq: - param=&uri->maddr; - param_val=&uri->maddr_val; - switch(*p){ + param = &uri->maddr; + param_val = &uri->maddr_val; + switch(*p) { param_common_cases; default: - v=p; - state=URI_VAL_P; + v = p; + state = URI_VAL_P; } break; - /* lr */ - param_switch(PLR_L, 'r', 'R', PLR_R_FIN); + /* lr */ + param_switch(PLR_L, 'r', 'R', PLR_R_FIN); case PLR_R_FIN: - switch(*p){ + switch(*p) { case '@': still_at_user; break; case '=': - state=PLR_eq; + state = PLR_eq; break; - semicolon_case; - uri->lr.s=b; - uri->lr.len=(p-b); + semicolon_case; + uri->lr.s = b; + uri->lr.len = (p - b); break; - question_case; - uri->lr.s=b; - uri->lr.len=(p-b); + question_case; + uri->lr.s = b; + uri->lr.len = (p - b); break; - colon_case; + colon_case; break; default: - state=URI_PARAM_P; + state = URI_PARAM_P; } break; /* handle lr=something case */ case PLR_eq: - param=&uri->lr; - param_val=&uri->lr_val; - switch(*p){ + param = &uri->lr; + param_val = &uri->lr_val; + switch(*p) { param_common_cases; default: - v=p; - state=URI_VAL_P; + v = p; + state = URI_VAL_P; } break; - /* r2 */ - param_switch1(PR2_R, '2', PR2_2_FIN); + /* r2 */ + param_switch1(PR2_R, '2', PR2_2_FIN); case PR2_2_FIN: - switch(*p){ + switch(*p) { case '@': still_at_user; break; case '=': - state=PR2_eq; + state = PR2_eq; break; - semicolon_case; - uri->r2.s=b; - uri->r2.len=(p-b); + semicolon_case; + uri->r2.s = b; + uri->r2.len = (p - b); break; - question_case; - uri->r2.s=b; - uri->r2.len=(p-b); + question_case; + uri->r2.s = b; + uri->r2.len = (p - b); break; - colon_case; + colon_case; break; default: - state=URI_PARAM_P; + state = URI_PARAM_P; } break; /* handle lr=something case */ case PR2_eq: - param=&uri->r2; - param_val=&uri->r2_val; - switch(*p){ + param = &uri->r2; + param_val = &uri->r2_val; + switch(*p) { param_common_cases; default: - v=p; - state=URI_VAL_P; + v = p; + state = URI_VAL_P; } break; - /* gr */ - param_switch(PGR_G, 'r', 'R', PGR_R_FIN); + /* gr */ + param_switch(PGR_G, 'r', 'R', PGR_R_FIN); case PGR_R_FIN: - switch(*p){ + switch(*p) { case '@': still_at_user; break; case '=': - state=PGR_eq; + state = PGR_eq; break; - semicolon_case; - uri->gr.s=b; - uri->gr.len=(p-b); + semicolon_case; + uri->gr.s = b; + uri->gr.len = (p - b); break; - question_case; - uri->gr.s=b; - uri->gr.len=(p-b); + question_case; + uri->gr.s = b; + uri->gr.len = (p - b); break; - colon_case; + colon_case; break; default: - state=URI_PARAM_P; + state = URI_PARAM_P; } break; /* handle gr=something case */ case PGR_eq: - param=&uri->gr; - param_val=&uri->gr_val; - switch(*p){ + param = &uri->gr; + param_val = &uri->gr_val; + switch(*p) { param_common_cases; default: - v=p; - state=URI_VAL_P; + v = p; + state = URI_VAL_P; } break; #ifdef USE_COMP - param_switch(PCOMP_C, 'o', 'O' , PCOMP_O); - param_switch(PCOMP_O, 'm', 'M' , PCOMP_M); - param_switch(PCOMP_M, 'p', 'P' , PCOMP_P); - param_switch1(PCOMP_P, '=', PCOMP_eq); + param_switch(PCOMP_C, 'o', 'O', PCOMP_O); + param_switch(PCOMP_O, 'm', 'M', PCOMP_M); + param_switch(PCOMP_M, 'p', 'P', PCOMP_P); + param_switch1(PCOMP_P, '=', PCOMP_eq); /* value */ case PCOMP_eq: - param=&comp_str; - param_val=&comp_val; - switch (*p){ + param = &comp_str; + param_val = &comp_val; + switch(*p) { param_common_cases; case 's': case 'S': - v=p; - state=VCOMP_S; + v = p; + state = VCOMP_S; break; default: - v=p; - state=URI_VAL_P; + v = p; + state = URI_VAL_P; } break; - /* sigcomp*/ - value_switch_big(VCOMP_S, 'i', 'I', 'e', 'E', - VCOMP_SIGC_I, VCOMP_SGZ_E); - value_switch(VCOMP_SIGC_I, 'g', 'G', VCOMP_SIGC_G); - value_switch(VCOMP_SIGC_G, 'c', 'C', VCOMP_SIGC_C); - value_switch(VCOMP_SIGC_C, 'o', 'O', VCOMP_SIGC_O); - value_switch(VCOMP_SIGC_O, 'm', 'M', VCOMP_SIGC_M); - value_switch(VCOMP_SIGC_M, 'p', 'P', VCOMP_SIGC_P_FIN); - comp_fin(VCOMP_SIGC_P_FIN, COMP_SIGCOMP); + /* sigcomp*/ + value_switch_big( + VCOMP_S, 'i', 'I', 'e', 'E', VCOMP_SIGC_I, VCOMP_SGZ_E); + value_switch(VCOMP_SIGC_I, 'g', 'G', VCOMP_SIGC_G); + value_switch(VCOMP_SIGC_G, 'c', 'C', VCOMP_SIGC_C); + value_switch(VCOMP_SIGC_C, 'o', 'O', VCOMP_SIGC_O); + value_switch(VCOMP_SIGC_O, 'm', 'M', VCOMP_SIGC_M); + value_switch(VCOMP_SIGC_M, 'p', 'P', VCOMP_SIGC_P_FIN); + comp_fin(VCOMP_SIGC_P_FIN, COMP_SIGCOMP); - /* sergz*/ - value_switch(VCOMP_SGZ_E, 'r', 'R', VCOMP_SGZ_R); - value_switch(VCOMP_SGZ_R, 'g', 'G', VCOMP_SGZ_G); - value_switch(VCOMP_SGZ_G, 'z', 'Z', VCOMP_SGZ_Z_FIN); - comp_fin(VCOMP_SGZ_Z_FIN, COMP_SERGZ); + /* sergz*/ + value_switch(VCOMP_SGZ_E, 'r', 'R', VCOMP_SGZ_R); + value_switch(VCOMP_SGZ_R, 'g', 'G', VCOMP_SGZ_G); + value_switch(VCOMP_SGZ_G, 'z', 'Z', VCOMP_SGZ_Z_FIN); + comp_fin(VCOMP_SGZ_Z_FIN, COMP_SERGZ); #endif case URI_HEADERS: /* for now nobody needs them so we completely ignore the * headers (they are not allowed in request uri) --andrei */ - switch(*p){ + switch(*p) { case '@': /* yak, we are still at user */ still_at_user; break; case ';': /* we might be still parsing user, try it */ - if (found_user) goto error_bad_char; - error_headers=1; /* if this is not the user + if(found_user) + goto error_bad_char; + error_headers = 1; /* if this is not the user we have an error */ /* if pass is set => it cannot be user:pass * => error (';') is illegal in a header */ - if (pass) goto error_headers; + if(pass) + goto error_headers; break; case ':': - if (found_user==0){ + if(found_user == 0) { /*might be pass but only if user not found yet*/ - if (pass){ - found_user=1; /* no user */ - pass=0; - }else{ - pass=p; + if(pass) { + found_user = 1; /* no user */ + pass = 0; + } else { + pass = p; } } break; case '?': - if (pass){ - found_user=1; /* no user, pass cannot contain '?'*/ - pass=0; + if(pass) { + found_user = + 1; /* no user, pass cannot contain '?'*/ + pass = 0; } break; } @@ -1000,48 +1071,51 @@ int parse_uri(char* buf, int len, struct sip_uri* uri) } } /*end of uri */ - switch (state){ + switch(state) { case URI_INIT: /* error empty uri */ goto error_too_short; case URI_USER: /* this is the host, it can't be the user */ - if (found_user) goto error_bad_uri; - uri->host.s=s; - uri->host.len=p-s; - state=URI_HOST; + if(found_user) + goto error_bad_uri; + uri->host.s = s; + uri->host.len = p - s; + state = URI_HOST; break; case URI_PASSWORD: /* this is the port, it can't be the passwd */ - if (found_user) goto error_bad_port; - uri->port.s=s; - uri->port.len=p-s; - uri->port_no=port_no; - uri->host=uri->user; - uri->user.s=0; - uri->user.len=0; + if(found_user) + goto error_bad_port; + uri->port.s = s; + uri->port.len = p - s; + uri->port_no = port_no; + uri->host = uri->user; + uri->user.s = 0; + uri->user.len = 0; break; case URI_PASSWORD_ALPHA: /* it might be an urn, check scheme and set host */ - if (scheme==URN_SCH){ - uri->host.s=s; - uri->host.len=p-s; - LM_DBG("parsed urn scheme with host: %.*s\n", - uri->host.len, uri->host.s); - /* this is the port, it can't be the passwd */ - }else goto error_bad_port; + if(scheme == URN_SCH) { + uri->host.s = s; + uri->host.len = p - s; + LM_DBG("parsed urn scheme with host: %.*s\n", uri->host.len, + uri->host.s); + /* this is the port, it can't be the passwd */ + } else + goto error_bad_port; break; case URI_HOST_P: case URI_HOST6_END: - uri->host.s=s; - uri->host.len=p-s; + uri->host.s = s; + uri->host.len = p - s; break; - case URI_HOST: /* error: null host */ + case URI_HOST: /* error: null host */ case URI_HOST6_P: /* error: unterminated ipv6 reference*/ goto error_bad_host; case URI_PORT: - uri->port.s=s; - uri->port.len=p-s; - uri->port_no=port_no; + uri->port.s = s; + uri->port.len = p - s; + uri->port_no = port_no; break; case URI_PARAM: case URI_PARAM_P: @@ -1055,11 +1129,11 @@ int parse_uri(char* buf, int len, struct sip_uri* uri) case PT_O: case PT_R2: case PT_T2: - case PT_eq: /* ignore empty transport params */ + case PT_eq: /* ignore empty transport params */ case PTTL_T2: /* ttl */ case PTTL_L: case PTTL_eq: - case PU_U: /* user */ + case PU_U: /* user */ case PU_S: case PU_E: case PU_R: @@ -1081,30 +1155,30 @@ int parse_uri(char* buf, int len, struct sip_uri* uri) case PCOMP_P: case PCOMP_eq: #endif - uri->params.s=s; - uri->params.len=p-s; + uri->params.s = s; + uri->params.len = p - s; break; /* fin param states */ case PLR_R_FIN: case PLR_eq: - uri->params.s=s; - uri->params.len=p-s; - uri->lr.s=b; - uri->lr.len=p-b; + uri->params.s = s; + uri->params.len = p - s; + uri->lr.s = b; + uri->lr.len = p - b; break; case PR2_2_FIN: case PR2_eq: - uri->params.s=s; - uri->params.len=p-s; - uri->r2.s=b; - uri->r2.len=p-b; + uri->params.s = s; + uri->params.len = p - s; + uri->r2.s = b; + uri->r2.len = p - b; break; case PGR_R_FIN: case PGR_eq: - uri->params.s=s; - uri->params.len=p-s; - uri->gr.s=b; - uri->gr.len=p-b; + uri->params.s = s; + uri->params.len = p - s; + uri->gr.s = b; + uri->gr.len = p - b; break; case URI_VAL_P: /* intermediate value states */ @@ -1117,8 +1191,8 @@ int parse_uri(char* buf, int len, struct sip_uri* uri) case VS_C: case VS_T: case VW_W: - uri->params.s=s; - uri->params.len=p-s; + uri->params.s = s; + uri->params.len = p - s; param_set(b, v); break; #ifdef USE_COMP @@ -1132,100 +1206,100 @@ int parse_uri(char* buf, int len, struct sip_uri* uri) case VCOMP_SGZ_R: case VCOMP_SGZ_G: /* unrecognized comp method, assume none */ - uri->params.s=s; - uri->params.len=p-s; + uri->params.s = s; + uri->params.len = p - s; /* uri->comp=COMP_NONE ; */ break; #endif /* fin value states */ case VU_P_FIN: - uri->params.s=s; - uri->params.len=p-s; + uri->params.s = s; + uri->params.len = p - s; param_set(b, v); - uri->proto=PROTO_UDP; + uri->proto = PROTO_UDP; break; case VT_P_FIN: - uri->params.s=s; - uri->params.len=p-s; + uri->params.s = s; + uri->params.len = p - s; param_set(b, v); - uri->proto=PROTO_TCP; + uri->proto = PROTO_TCP; break; case VTLS_S_FIN: - uri->params.s=s; - uri->params.len=p-s; + uri->params.s = s; + uri->params.len = p - s; param_set(b, v); - uri->proto=PROTO_TLS; + uri->proto = PROTO_TLS; break; case VS_P_FIN: - uri->params.s=s; - uri->params.len=p-s; + uri->params.s = s; + uri->params.len = p - s; param_set(b, v); - uri->proto=PROTO_SCTP; + uri->proto = PROTO_SCTP; break; case VW_S_FIN: - uri->params.s=s; - uri->params.len=p-s; + uri->params.s = s; + uri->params.len = p - s; param_set(b, v); - uri->proto=PROTO_WS; + uri->proto = PROTO_WS; break; #ifdef USE_COMP case VCOMP_SIGC_P_FIN: - uri->params.s=s; - uri->params.len=p-s; + uri->params.s = s; + uri->params.len = p - s; /* param_set(b, v); */ - uri->comp=COMP_SIGCOMP; + uri->comp = COMP_SIGCOMP; break; case VCOMP_SGZ_Z_FIN: - uri->params.s=s; - uri->params.len=p-s; + uri->params.s = s; + uri->params.len = p - s; /* param_set(b, v); */ - uri->comp=COMP_SERGZ; + uri->comp = COMP_SERGZ; break; #endif /* headers */ case URI_HEADERS: - uri->headers.s=s; - uri->headers.len=p-s; - if (error_headers) goto error_headers; + uri->headers.s = s; + uri->headers.len = p - s; + if(error_headers) + goto error_headers; break; default: goto error_bug; } - switch(uri->type){ + switch(uri->type) { case SIPS_URI_T: case SIP_URI_T: /* save the original sip: URI parameters in sip_params */ - uri->sip_params=uri->params; - if ((phone2tel) && - (uri->user_param_val.len == 5) && - (strncmp(uri->user_param_val.s, "phone", 5) == 0) - ) { + uri->sip_params = uri->params; + if((phone2tel) && (uri->user_param_val.len == 5) + && (strncmp(uri->user_param_val.s, "phone", 5) == 0)) { uri->type = TEL_URI_T; uri->flags |= URI_SIP_USER_PHONE; /* move params from user into uri->params */ - p=q_memchr(uri->user.s, ';', uri->user.len); - if (p){ + p = q_memchr(uri->user.s, ';', uri->user.len); + if(p) { /* NOTE: * specialized uri params (user, maddr, etc.) still hold * the values from the sip-uri envelope * while uri->params point to the params in the embedded tel uri */ - uri->params.s=p+1; - uri->params.len=uri->user.s+uri->user.len-uri->params.s; - uri->user.len=p-uri->user.s; + uri->params.s = p + 1; + uri->params.len = + uri->user.s + uri->user.len - uri->params.s; + uri->user.len = p - uri->user.s; } else { - uri->params.s=0; - uri->params.len=0; + uri->params.s = 0; + uri->params.len = 0; } } else { - uri->flags&=~URI_USER_NORMALIZE; + uri->flags &= ~URI_USER_NORMALIZE; } break; case TEL_URI_T: case TELS_URI_T: /* fix tel uris, move the number in uri and empty the host */ - uri->user=uri->host; - uri->host=_sr_uri_empty; + uri->user = uri->host; + uri->host = _sr_uri_empty; break; /* urn: do nothing */ case URN_URI_T: @@ -1237,12 +1311,12 @@ int parse_uri(char* buf, int len, struct sip_uri* uri) } /* common sanity checks */ - if(uri->port.len>5) { + if(uri->port.len > 5) { /* port value too large */ goto error_invalid_port; } - if(uri->host.len>0 && uri->user.len<=0 &&uri->host.s>buf && (*(uri->host.s-1)=='@' - || *uri->host.s=='@')) { + if(uri->host.len > 0 && uri->user.len <= 0 && uri->host.s > buf + && (*(uri->host.s - 1) == '@' || *uri->host.s == '@')) { /* '@' before host, but no user part */ goto error_bad_uri; } @@ -1251,34 +1325,31 @@ int parse_uri(char* buf, int len, struct sip_uri* uri) /* do stuff */ LM_DBG("state=%d\n", state); LM_DBG("parsed uri:\n type=%d user=<%.*s>(%d)\n passwd=<%.*s>(%d)\n" - " host=<%.*s>(%d)\n port=<%.*s>(%d): %d\n params=<%.*s>(%d)\n" - " headers=<%.*s>(%d)\n", - uri->type, - uri->user.len, ZSW(uri->user.s), uri->user.len, - uri->passwd.len, ZSW(uri->passwd.s), uri->passwd.len, - uri->host.len, ZSW(uri->host.s), uri->host.len, - uri->port.len, ZSW(uri->port.s), uri->port.len, uri->port_no, - uri->params.len, ZSW(uri->params.s), uri->params.len, - uri->headers.len, ZSW(uri->headers.s), uri->headers.len - ); + " host=<%.*s>(%d)\n port=<%.*s>(%d): %d\n params=<%.*s>(%d)\n" + " headers=<%.*s>(%d)\n", + uri->type, uri->user.len, ZSW(uri->user.s), uri->user.len, + uri->passwd.len, ZSW(uri->passwd.s), uri->passwd.len, uri->host.len, + ZSW(uri->host.s), uri->host.len, uri->port.len, ZSW(uri->port.s), + uri->port.len, uri->port_no, uri->params.len, ZSW(uri->params.s), + uri->params.len, uri->headers.len, ZSW(uri->headers.s), + uri->headers.len); LM_DBG(" uri flags : "); - if (uri->flags & URI_USER_NORMALIZE) LM_DBG("user_need_norm "); - if (uri->flags & URI_SIP_USER_PHONE) LM_DBG("sip_user_phone "); - LM_DBG(" value=%d\n",uri->flags); + if(uri->flags & URI_USER_NORMALIZE) + LM_DBG("user_need_norm "); + if(uri->flags & URI_SIP_USER_PHONE) + LM_DBG("sip_user_phone "); + LM_DBG(" value=%d\n", uri->flags); LM_DBG(" uri params:\n transport=<%.*s>, val=<%.*s>, proto=%d\n", uri->transport.len, ZSW(uri->transport.s), uri->transport_val.len, ZSW(uri->transport_val.s), uri->proto); - LM_DBG(" user-param=<%.*s>, val=<%.*s>\n", - uri->user_param.len, ZSW(uri->user_param.s), - uri->user_param_val.len, ZSW(uri->user_param_val.s)); - LM_DBG(" method=<%.*s>, val=<%.*s>\n", - uri->method.len, ZSW(uri->method.s), - uri->method_val.len, ZSW(uri->method_val.s)); - LM_DBG(" ttl=<%.*s>, val=<%.*s>\n", - uri->ttl.len, ZSW(uri->ttl.s), + LM_DBG(" user-param=<%.*s>, val=<%.*s>\n", uri->user_param.len, + ZSW(uri->user_param.s), uri->user_param_val.len, + ZSW(uri->user_param_val.s)); + LM_DBG(" method=<%.*s>, val=<%.*s>\n", uri->method.len, + ZSW(uri->method.s), uri->method_val.len, ZSW(uri->method_val.s)); + LM_DBG(" ttl=<%.*s>, val=<%.*s>\n", uri->ttl.len, ZSW(uri->ttl.s), uri->ttl_val.len, ZSW(uri->ttl_val.s)); - LM_DBG(" maddr=<%.*s>, val=<%.*s>\n", - uri->maddr.len, ZSW(uri->maddr.s), + LM_DBG(" maddr=<%.*s>, val=<%.*s>\n", uri->maddr.len, ZSW(uri->maddr.s), uri->maddr_val.len, ZSW(uri->maddr_val.s)); LM_DBG(" lr=<%.*s>\n", uri->lr.len, ZSW(uri->lr.s)); LM_DBG(" r2=<%.*s>\n", uri->r2.len, ZSW(uri->r2.s)); @@ -1290,171 +1361,172 @@ int parse_uri(char* buf, int len, struct sip_uri* uri) return 0; error_too_short: - LM_DBG("uri too short: <%.*s> (%d)\n", - len, ZSW(buf), len); + LM_DBG("uri too short: <%.*s> (%d)\n", len, ZSW(buf), len); goto error_exit; error_bad_char: LM_DBG("bad char '%c' in state %d" - " parsed: <%.*s> (%d) / <%.*s> (%d)\n", - *p, state, (int)(p-buf), ZSW(buf), (int)(p-buf), - len, ZSW(buf), len); + " parsed: <%.*s> (%d) / <%.*s> (%d)\n", + *p, state, (int)(p - buf), ZSW(buf), (int)(p - buf), len, ZSW(buf), + len); goto error_exit; error_bad_host: LM_DBG("bad host in uri (error at char %c in" - " state %d) parsed: <%.*s>(%d) /<%.*s> (%d)\n", - *p, state, (int)(p-buf), ZSW(buf), (int)(p-buf), - len, ZSW(buf), len); + " state %d) parsed: <%.*s>(%d) /<%.*s> (%d)\n", + *p, state, (int)(p - buf), ZSW(buf), (int)(p - buf), len, ZSW(buf), + len); goto error_exit; error_bad_port: LM_DBG("bad port in uri (error at char %c in" - " state %d) parsed: <%.*s>(%d) /<%.*s> (%d)\n", - *p, state, (int)(p-buf), ZSW(buf), (int)(p-buf), - len, ZSW(buf), len); + " state %d) parsed: <%.*s>(%d) /<%.*s> (%d)\n", + *p, state, (int)(p - buf), ZSW(buf), (int)(p - buf), len, ZSW(buf), + len); goto error_exit; error_invalid_port: - LM_DBG("bad port in uri: [%.*s] in <%.*s>\n", - uri->port.len, uri->port.s, len, ZSW(buf)); + LM_DBG("bad port in uri: [%.*s] in <%.*s>\n", uri->port.len, uri->port.s, + len, ZSW(buf)); goto error_exit; error_bad_uri: - LM_DBG("bad uri, state %d parsed: <%.*s> (%d) / <%.*s> (%d)\n", - state, (int)(p-buf), ZSW(buf), (int)(p-buf), len, - ZSW(buf), len); + LM_DBG("bad uri, state %d parsed: <%.*s> (%d) / <%.*s> (%d)\n", state, + (int)(p - buf), ZSW(buf), (int)(p - buf), len, ZSW(buf), len); goto error_exit; error_headers: - LM_DBG("bad uri headers: <%.*s>(%d) / <%.*s>(%d)\n", - uri->headers.len, ZSW(uri->headers.s), uri->headers.len, - len, ZSW(buf), len); + LM_DBG("bad uri headers: <%.*s>(%d) / <%.*s>(%d)\n", uri->headers.len, + ZSW(uri->headers.s), uri->headers.len, len, ZSW(buf), len); goto error_exit; error_bug: - LM_CRIT("BUG: bad state %d parsed: <%.*s> (%d) / <%.*s> (%d)\n", - state, (int)(p-buf), ZSW(buf), (int)(p-buf), len, ZSW(buf), len); + LM_CRIT("BUG: bad state %d parsed: <%.*s> (%d) / <%.*s> (%d)\n", state, + (int)(p - buf), ZSW(buf), (int)(p - buf), len, ZSW(buf), len); error_exit: - ser_error=E_BAD_URI; - uri->type=ERROR_URI_T; + ser_error = E_BAD_URI; + uri->type = ERROR_URI_T; STATS_BAD_URI(); return E_BAD_URI; } -static inline int _parse_ruri(str *uri, - int *status, struct sip_uri *parsed_uri) +static inline int _parse_ruri(str *uri, int *status, struct sip_uri *parsed_uri) { - if (*status) return 1; + if(*status) + return 1; - if (parse_uri(uri->s, uri->len, parsed_uri)<0) { + if(parse_uri(uri->s, uri->len, parsed_uri) < 0) { LM_ERR("bad uri <%.*s>\n", uri->len, ZSW(uri->s)); - *status=0; + *status = 0; return -1; } - *status=1; + *status = 1; return 1; } -int parse_sip_msg_uri(struct sip_msg* msg) +int parse_sip_msg_uri(struct sip_msg *msg) { - char* tmp; + char *tmp; int tmp_len; - if (msg->parsed_uri_ok) return 1; + if(msg->parsed_uri_ok) + return 1; - if (msg->new_uri.s){ - tmp=msg->new_uri.s; - tmp_len=msg->new_uri.len; - }else{ - tmp=msg->first_line.u.request.uri.s; - tmp_len=msg->first_line.u.request.uri.len; + if(msg->new_uri.s) { + tmp = msg->new_uri.s; + tmp_len = msg->new_uri.len; + } else { + tmp = msg->first_line.u.request.uri.s; + tmp_len = msg->first_line.u.request.uri.len; } - if (parse_uri(tmp, tmp_len, &msg->parsed_uri)<0){ + if(parse_uri(tmp, tmp_len, &msg->parsed_uri) < 0) { LM_DBG("bad uri <%.*s>\n", tmp_len, tmp); - msg->parsed_uri_ok=0; + msg->parsed_uri_ok = 0; return -1; } - msg->parsed_uri_ok=1; + msg->parsed_uri_ok = 1; return 1; } -int parse_orig_ruri(struct sip_msg* msg) +int parse_orig_ruri(struct sip_msg *msg) { int ret; - ret=_parse_ruri(&REQ_LINE(msg).uri, - &msg->parsed_orig_ruri_ok, &msg->parsed_orig_ruri); - if (ret<0) LM_ERR("parse orig ruri failed\n"); + ret = _parse_ruri(&REQ_LINE(msg).uri, &msg->parsed_orig_ruri_ok, + &msg->parsed_orig_ruri); + if(ret < 0) + LM_ERR("parse orig ruri failed\n"); return ret; } -int normalize_tel_user(char* res, str* src) +int normalize_tel_user(char *res, str *src) { int i, l; - l=0; - for (i=0; ilen; i++) { - switch (src->s[i]) { + l = 0; + for(i = 0; i < src->len; i++) { + switch(src->s[i]) { case '-': case '.': case '(': case ')': break; default: - res[l++]=src->s[i]; + res[l++] = src->s[i]; } } return l; } -str s_sip = STR_STATIC_INIT("sip"); -str s_sips = STR_STATIC_INIT("sips"); -str s_tel = STR_STATIC_INIT("tel"); -str s_tels = STR_STATIC_INIT("tels"); -str s_urn = STR_STATIC_INIT("urn"); -static str s_null = STR_STATIC_INIT(""); +str s_sip = STR_STATIC_INIT("sip"); +str s_sips = STR_STATIC_INIT("sips"); +str s_tel = STR_STATIC_INIT("tel"); +str s_tels = STR_STATIC_INIT("tels"); +str s_urn = STR_STATIC_INIT("urn"); +static str s_null = STR_STATIC_INIT(""); -void uri_type_to_str(uri_type type, str *s) { - switch (type) { - case SIP_URI_T: - *s = s_sip; - break; - case SIPS_URI_T: - *s = s_sips; - break; - case TEL_URI_T: - *s = s_tel; - break; - case TELS_URI_T: - *s = s_tels; - break; - case URN_URI_T: - *s = s_urn; - break; - default: - *s = s_null; +void uri_type_to_str(uri_type type, str *s) +{ + switch(type) { + case SIP_URI_T: + *s = s_sip; + break; + case SIPS_URI_T: + *s = s_sips; + break; + case TEL_URI_T: + *s = s_tel; + break; + case TELS_URI_T: + *s = s_tels; + break; + case URN_URI_T: + *s = s_urn; + break; + default: + *s = s_null; } } -static str s_udp = STR_STATIC_INIT("udp"); -static str s_tcp = STR_STATIC_INIT("tcp"); -static str s_tls = STR_STATIC_INIT("tls"); -static str s_sctp = STR_STATIC_INIT("sctp"); -static str s_ws = STR_STATIC_INIT("ws"); +static str s_udp = STR_STATIC_INIT("udp"); +static str s_tcp = STR_STATIC_INIT("tcp"); +static str s_tls = STR_STATIC_INIT("tls"); +static str s_sctp = STR_STATIC_INIT("sctp"); +static str s_ws = STR_STATIC_INIT("ws"); -void proto_type_to_str(unsigned short type, str *s) { - switch (type) { - case PROTO_UDP: - *s = s_udp; - break; - case PROTO_TCP: - *s = s_tcp; - break; - case PROTO_TLS: - *s = s_tls; - break; - case PROTO_SCTP: - *s = s_sctp; - break; - case PROTO_WS: - case PROTO_WSS: - *s = s_ws; - break; - default: - *s = s_null; +void proto_type_to_str(unsigned short type, str *s) +{ + switch(type) { + case PROTO_UDP: + *s = s_udp; + break; + case PROTO_TCP: + *s = s_tcp; + break; + case PROTO_TLS: + *s = s_tls; + break; + case PROTO_SCTP: + *s = s_sctp; + break; + case PROTO_WS: + case PROTO_WSS: + *s = s_ws; + break; + default: + *s = s_null; } } diff --git a/src/core/parser/parse_uri.h b/src/core/parser/parse_uri.h index 02d8aa0d613..47eda21422a 100644 --- a/src/core/parser/parse_uri.h +++ b/src/core/parser/parse_uri.h @@ -35,16 +35,16 @@ #include "../str.h" #include "../parser/msg_parser.h" -extern str s_sip, s_sips, s_tel, s_tels, s_urn; +extern str s_sip, s_sips, s_tel, s_tels, s_urn; /* buf= pointer to beginning of uri (sip:x@foo.bar:5060;a=b?h=i) * len= len of uri * returns: fills uri & returns <0 on error or 0 if ok */ -int parse_uri(char *buf, int len, struct sip_uri* uri); -int parse_sip_msg_uri(struct sip_msg* msg); -int parse_orig_ruri(struct sip_msg* msg); -int normalize_tel_user(char* res, str* src); +int parse_uri(char *buf, int len, struct sip_uri *uri); +int parse_sip_msg_uri(struct sip_msg *msg); +int parse_orig_ruri(struct sip_msg *msg); +int normalize_tel_user(char *res, str *src); void uri_type_to_str(uri_type type, str *s); void proto_type_to_str(unsigned short type, str *s); diff --git a/src/core/parser/parse_via.c b/src/core/parser/parse_via.c index 9d541a00b02..4c6b79241c9 100644 --- a/src/core/parser/parse_via.c +++ b/src/core/parser/parse_via.c @@ -238,7 +238,7 @@ static /*inline*/ char *parse_via_param(char *const p, const char *const end, break; \ default: \ LM_ERR("invalid " \ - "char <%c> in state %d\n", \ + "char <%c> in state %d\n", \ *tmp, state); \ goto error; \ } @@ -502,7 +502,7 @@ static /*inline*/ char *parse_via_param(char *const p, const char *const end, case FIN_COMP: #endif LM_ERR("new via found" - "(',') when '=' expected (state %d=)\n", + "(',') when '=' expected (state %d=)\n", state); goto error; /* or we could ignore this bad param*/ case F_CR: @@ -940,7 +940,7 @@ static /*inline*/ char *parse_via_param(char *const p, const char *const end, find_value: tmp++; - for(; tmphost.s) vb->host.len = tmp - vb->host.s; + if(vb->host.s) + vb->host.len = tmp - vb->host.s; state = L_PORT; break; case L_PORT: /*eat the spaces*/ @@ -2081,7 +2082,8 @@ char *parse_via( break; case P_PORT: /*end of port */ - if(vb->port_str.s) vb->port_str.len = tmp - vb->port_str.s; + if(vb->port_str.s) + vb->port_str.len = tmp - vb->port_str.s; state = L_PARAM; break; case L_PARAM: /* eat the space */ @@ -2131,13 +2133,15 @@ char *parse_via( break; case P_HOST: /*mark end of host*/ - if(vb->host.s) vb->host.len = tmp - vb->host.s; + if(vb->host.s) + vb->host.len = tmp - vb->host.s; saved_state = L_PORT; state = F_LF; break; case P_PORT: /*end of port */ - if(vb->port_str.s) vb->port_str.len = tmp - vb->port_str.s; + if(vb->port_str.s) + vb->port_str.len = tmp - vb->port_str.s; saved_state = L_PARAM; state = F_LF; break; @@ -2176,13 +2180,15 @@ char *parse_via( break; case P_HOST: /*mark end of host*/ - if(vb->host.s) vb->host.len = tmp - vb->host.s; + if(vb->host.s) + vb->host.len = tmp - vb->host.s; saved_state = L_PORT; state = F_CR; break; case P_PORT: /*end of port */ - if(vb->port_str.s) vb->port_str.len = tmp - vb->port_str.s; + if(vb->port_str.s) + vb->port_str.len = tmp - vb->port_str.s; saved_state = L_PARAM; state = F_CR; break; @@ -2212,7 +2218,8 @@ char *parse_via( break; case P_HOST: /*mark end of host*/ - if(vb->host.s) vb->host.len = tmp - vb->host.s; + if(vb->host.s) + vb->host.len = tmp - vb->host.s; state = F_PORT; break; case L_PORT: @@ -2257,13 +2264,15 @@ char *parse_via( LM_ERR("bad ipv6 reference\n"); goto error; case P_HOST: - if(vb->host.s) vb->host.len = tmp - vb->host.s; + if(vb->host.s) + vb->host.len = tmp - vb->host.s; state = F_PARAM; param_start = tmp + 1; break; case P_PORT: /*mark the end*/ - if(vb->port_str.s) vb->port_str.len = tmp - vb->port_str.s; + if(vb->port_str.s) + vb->port_str.len = tmp - vb->port_str.s; case L_PORT: case L_PARAM: state = F_PARAM; @@ -2313,12 +2322,14 @@ char *parse_via( goto error; case P_HOST: /*mark the end*/ - if(vb->host.s) vb->host.len = tmp - vb->host.s; + if(vb->host.s) + vb->host.len = tmp - vb->host.s; state = F_VIA; break; case P_PORT: /*mark the end*/ - if(vb->port_str.s) vb->port_str.len = tmp - vb->port_str.s; + if(vb->port_str.s) + vb->port_str.len = tmp - vb->port_str.s; state = F_VIA; break; case L_PORT: @@ -2363,13 +2374,15 @@ char *parse_via( goto error; case P_HOST: /*mark the end*/ - if(vb->host.s) vb->host.len = tmp - vb->host.s; + if(vb->host.s) + vb->host.len = tmp - vb->host.s; state = F_COMMENT; c_nest++; break; case P_PORT: /*mark the end*/ - if(vb->port_str.s) vb->port_str.len = tmp - vb->port_str.s; + if(vb->port_str.s) + vb->port_str.len = tmp - vb->port_str.s; state = F_COMMENT; c_nest++; break; @@ -2469,7 +2482,9 @@ char *parse_via( switch(state) { case P_IP6HOST: /*mark the end*/ - if(vb->host.s) vb->host.len = (tmp - vb->host.s) + 1; /* include "]" */ + if(vb->host.s) + vb->host.len = + (tmp - vb->host.s) + 1; /* include "]" */ state = L_PORT; break; case F_CRLF: @@ -2527,11 +2542,11 @@ char *parse_via( break; case F_VIA: vb->params.len = param->start + param->size - - vb->params.s; + - vb->params.s; break; case END_OF_HEADER: vb->params.len = param->start + param->size - - vb->params.s; + - vb->params.s; break; case PARAM_ERROR: pkg_free(param); @@ -2539,7 +2554,7 @@ char *parse_via( default: pkg_free(param); LM_ERR("parsing via after parse_via_param:" - " invalid char <%c> on state %d\n", + " invalid char <%c> on state %d\n", *tmp, state); goto error; } @@ -2624,7 +2639,7 @@ char *parse_via( goto endofheader; default: LM_ERR("BUG: parsing via - invalid char <%c>" - " in state %d\n", + " in state %d\n", *tmp, state); goto error; } @@ -2703,7 +2718,8 @@ char *parse_via( error: if(end > buffer) { - LM_ERR("parsing via on: <%.*s>\n", (int)(end - buffer), ZSW(ksr_buf_oneline(buffer, (int)(end - buffer)))); + LM_ERR("parsing via on: <%.*s>\n", (int)(end - buffer), + ZSW(ksr_buf_oneline(buffer, (int)(end - buffer)))); } if((tmp > buffer) && (tmp < end)) { LM_ERR("parse error, parsed so far:<%.*s>\n", (int)(tmp - buffer), @@ -2750,8 +2766,9 @@ int parse_via_header(struct sip_msg *msg, int n, struct via_body **q) switch(n) { case 1: case 2: - if(!msg->h_via1 && (parse_headers(msg, HDR_VIA_F, 0) == -1 - || !msg->h_via1)) { + if(!msg->h_via1 + && (parse_headers(msg, HDR_VIA_F, 0) == -1 + || !msg->h_via1)) { DBG("bad msg or missing VIA1 header \n"); return -1; } @@ -2762,8 +2779,9 @@ int parse_via_header(struct sip_msg *msg, int n, struct via_body **q) if(pp) break; - if(!msg->h_via2 && (parse_headers(msg, HDR_VIA2_F, 0) == -1 - || !msg->h_via2)) { + if(!msg->h_via2 + && (parse_headers(msg, HDR_VIA2_F, 0) == -1 + || !msg->h_via2)) { DBG("bad msg or missing VIA2 header \n"); return -1; } diff --git a/src/core/parser/parse_via.h b/src/core/parser/parse_via.h index ec2b71247fd..4cd17ca3e19 100644 --- a/src/core/parser/parse_via.h +++ b/src/core/parser/parse_via.h @@ -35,35 +35,43 @@ struct sip_msg; * WARNING: keep in sync with parse_via.c FIN_HIDDEN... * and with tm/sip_msg.c via_body_cloner */ -enum { - PARAM_HIDDEN=230, PARAM_TTL, PARAM_BRANCH, - PARAM_MADDR, PARAM_RECEIVED, PARAM_RPORT, PARAM_I, PARAM_ALIAS, +enum +{ + PARAM_HIDDEN = 230, + PARAM_TTL, + PARAM_BRANCH, + PARAM_MADDR, + PARAM_RECEIVED, + PARAM_RPORT, + PARAM_I, + PARAM_ALIAS, #ifdef USE_COMP PARAM_COMP, #endif - GEN_PARAM=253, + GEN_PARAM = 253, PARAM_ERROR }; - -typedef struct via_param { - int type; /* Type of the parameter */ - str name; /* Name of the parameter */ - str value; /* Value of the parameter */ - char* start; /* Pointer to param start, just after ';', +typedef struct via_param +{ + int type; /* Type of the parameter */ + str name; /* Name of the parameter */ + str value; /* Value of the parameter */ + char *start; /* Pointer to param start, just after ';', * (it can be diff. from name.s!) */ - int size; /* total size, including preceding and trailing + int size; /* total size, including preceding and trailing * white space */ - struct via_param* next; /* Next parameter in the list */ + struct via_param *next; /* Next parameter in the list */ } via_param_t; /* Format: name/version/transport host:port;params comment */ /* WARNING: keep in sync with tm/sip_msg.c via_body_cloner */ -typedef struct via_body { +typedef struct via_body +{ int error; - str hdr; /* Contains "Via" or "v" */ + str hdr; /* Contains "Via" or "v" */ str name; str version; str transport; @@ -77,22 +85,22 @@ typedef struct via_body { str port_str; str params; str comment; - char *bstart; /* body content, not including hdr */ - int bsize; /* body size, not including hdr */ - struct via_param* param_lst; /* list of parameters*/ - struct via_param* last_param; /*last via parameter, internal use*/ + char *bstart; /* body content, not including hdr */ + int bsize; /* body size, not including hdr */ + struct via_param *param_lst; /* list of parameters*/ + struct via_param *last_param; /*last via parameter, internal use*/ /* shortcuts to "important" params*/ - struct via_param* branch; + struct via_param *branch; str tid; /* transaction id, part of branch */ - struct via_param* received; - struct via_param* rport; - struct via_param* i; - struct via_param* alias; /* alias see draft-ietf-sip-connect-reuse-00 */ + struct via_param *received; + struct via_param *rport; + struct via_param *i; + struct via_param *alias; /* alias see draft-ietf-sip-connect-reuse-00 */ #ifdef USE_COMP - struct via_param* comp; /* see rfc3486 */ + struct via_param *comp; /* see rfc3486 */ #endif - struct via_body* next; /* pointer to next via body string + struct via_body *next; /* pointer to next via body string if compact via or null */ } via_body_t; @@ -100,7 +108,8 @@ typedef struct via_body { /* * Main Via header field parser */ -char* parse_via(char* buffer, const char* const end, struct via_body* const vbody); +char *parse_via( + char *buffer, const char *const end, struct via_body *const vbody); /* @@ -112,7 +121,7 @@ void free_via_list(struct via_body *vb); /* * Get one Via header */ -int parse_via_header( struct sip_msg *msg, int n, struct via_body** q); +int parse_via_header(struct sip_msg *msg, int n, struct via_body **q); #endif /* PARSE_VIA_H */ diff --git a/src/core/parser/parser_f.h b/src/core/parser/parser_f.h index 043c653d792..fd71154d366 100644 --- a/src/core/parser/parser_f.h +++ b/src/core/parser/parser_f.h @@ -1,4 +1,4 @@ -/* +/* * Copyright (C) 2001-2003 FhG Fokus * * This file is part of Kamailio, a free SIP server. @@ -13,8 +13,8 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ @@ -28,74 +28,81 @@ */ - #ifndef parser_f_h #define parser_f_h #include "../comp_defs.h" #include "../str.h" -char* eat_line(char* buffer, unsigned int len); +char *eat_line(char *buffer, unsigned int len); /* turn the most frequently called functions into inline functions */ -inline static char* eat_space_end(const char* p, const char* pend) +inline static char *eat_space_end(const char *p, const char *pend) { - for(;(plen; i++) { - if (!quoted) { - if (_s->s[i] == '\"') quoted = 1; - else if (_s->s[i] == _c) return _s->s + i; + if(!quoted) { + if(_s->s[i] == '\"') + quoted = 1; + else if(_s->s[i] == _c) + return _s->s + i; } else { - if ((_s->s[i] == '\"') && (_s->s[i - 1] != '\\')) quoted = 0; + if((_s->s[i] == '\"') && (_s->s[i - 1] != '\\')) + quoted = 0; } } return 0; diff --git a/src/core/parser/sdp/sdp.c b/src/core/parser/sdp/sdp.c index 8c08b469acb..52e967a3db9 100644 --- a/src/core/parser/sdp/sdp.c +++ b/src/core/parser/sdp/sdp.c @@ -41,19 +41,19 @@ /** * Creates and initialize a new sdp_info structure */ -static inline int new_sdp(struct sip_msg* _m) +static inline int new_sdp(struct sip_msg *_m) { - sdp_info_t* sdp; + sdp_info_t *sdp; - sdp = (sdp_info_t*)pkg_malloc(sizeof(sdp_info_t)); - if (sdp == NULL) { + sdp = (sdp_info_t *)pkg_malloc(sizeof(sdp_info_t)); + if(sdp == NULL) { PKG_MEM_ERROR; return -1; } - memset( sdp, 0, sizeof(sdp_info_t)); + memset(sdp, 0, sizeof(sdp_info_t)); sdp->type = MSG_BODY_SDP; sdp->free = (free_msg_body_f)free_sdp; - _m->body = (msg_body_t*)sdp; + _m->body = (msg_body_t *)sdp; return 0; } @@ -61,21 +61,22 @@ static inline int new_sdp(struct sip_msg* _m) /** * Allocate a new session cell. */ -static inline sdp_session_cell_t *add_sdp_session(sdp_info_t* _sdp, int session_num, str* cnt_disp) +static inline sdp_session_cell_t *add_sdp_session( + sdp_info_t *_sdp, int session_num, str *cnt_disp) { sdp_session_cell_t *session; int len; len = sizeof(sdp_session_cell_t); - session = (sdp_session_cell_t*)pkg_malloc(len); - if (session == NULL) { + session = (sdp_session_cell_t *)pkg_malloc(len); + if(session == NULL) { PKG_MEM_ERROR; return NULL; } - memset( session, 0, len); + memset(session, 0, len); session->session_num = session_num; - if (cnt_disp != NULL) { + if(cnt_disp != NULL) { session->cnt_disp.s = cnt_disp->s; session->cnt_disp.len = cnt_disp->len; } @@ -91,19 +92,20 @@ static inline sdp_session_cell_t *add_sdp_session(sdp_info_t* _sdp, int session_ /** * Allocate a new stream cell. */ -static inline sdp_stream_cell_t *add_sdp_stream(sdp_session_cell_t* _session, int stream_num, - str* media, str* port, str* transport, str* payloads, int is_rtp, int pf, str* sdp_ip) +static inline sdp_stream_cell_t *add_sdp_stream(sdp_session_cell_t *_session, + int stream_num, str *media, str *port, str *transport, str *payloads, + int is_rtp, int pf, str *sdp_ip) { sdp_stream_cell_t *stream; int len; len = sizeof(sdp_stream_cell_t); - stream = (sdp_stream_cell_t*)pkg_malloc(len); - if (stream == NULL) { + stream = (sdp_stream_cell_t *)pkg_malloc(len); + if(stream == NULL) { PKG_MEM_ERROR; return NULL; } - memset( stream, 0, len); + memset(stream, 0, len); stream->stream_num = stream_num; @@ -133,18 +135,19 @@ static inline sdp_stream_cell_t *add_sdp_stream(sdp_session_cell_t* _session, in /** * Allocate a new payload. */ -static inline sdp_payload_attr_t *add_sdp_payload(sdp_stream_cell_t* _stream, int payload_num, str* payload) +static inline sdp_payload_attr_t *add_sdp_payload( + sdp_stream_cell_t *_stream, int payload_num, str *payload) { sdp_payload_attr_t *payload_attr; int len; len = sizeof(sdp_payload_attr_t); - payload_attr = (sdp_payload_attr_t*)pkg_malloc(len); - if (payload_attr == NULL) { + payload_attr = (sdp_payload_attr_t *)pkg_malloc(len); + if(payload_attr == NULL) { PKG_MEM_ERROR; return NULL; } - memset( payload_attr, 0, len); + memset(payload_attr, 0, len); payload_attr->payload_num = payload_num; payload_attr->rtp_payload.s = payload->s; @@ -162,32 +165,35 @@ static inline sdp_payload_attr_t *add_sdp_payload(sdp_stream_cell_t* _stream, in /** * Initialize fast access pointers. */ -static inline sdp_payload_attr_t** init_p_payload_attr(sdp_stream_cell_t* _stream, int pkg) +static inline sdp_payload_attr_t **init_p_payload_attr( + sdp_stream_cell_t *_stream, int pkg) { int payloads_num, i; sdp_payload_attr_t *payload; - if (_stream == NULL) { + if(_stream == NULL) { LM_ERR("Invalid stream\n"); return NULL; } payloads_num = _stream->payloads_num; - if (payloads_num == 0) { + if(payloads_num == 0) { LM_ERR("Invalid number of payloads\n"); return NULL; } - if (pkg == SDP_USE_PKG_MEM) { - _stream->p_payload_attr = (sdp_payload_attr_t**)pkg_malloc(payloads_num * sizeof(sdp_payload_attr_t*)); - } else if (pkg == SDP_USE_SHM_MEM) { - _stream->p_payload_attr = (sdp_payload_attr_t**)shm_malloc(payloads_num * sizeof(sdp_payload_attr_t*)); + if(pkg == SDP_USE_PKG_MEM) { + _stream->p_payload_attr = (sdp_payload_attr_t **)pkg_malloc( + payloads_num * sizeof(sdp_payload_attr_t *)); + } else if(pkg == SDP_USE_SHM_MEM) { + _stream->p_payload_attr = (sdp_payload_attr_t **)shm_malloc( + payloads_num * sizeof(sdp_payload_attr_t *)); } else { LM_ERR("undefined memory type\n"); return NULL; } - if (_stream->p_payload_attr == NULL) { - if (pkg == SDP_USE_PKG_MEM) { + if(_stream->p_payload_attr == NULL) { + if(pkg == SDP_USE_PKG_MEM) { PKG_MEM_ERROR; - } else if (pkg == SDP_USE_SHM_MEM) { + } else if(pkg == SDP_USE_SHM_MEM) { SHM_MEM_ERROR; } return NULL; @@ -195,8 +201,8 @@ static inline sdp_payload_attr_t** init_p_payload_attr(sdp_stream_cell_t* _strea --payloads_num; payload = _stream->payload_attr; - for (i=0;i<=payloads_num;i++) { - _stream->p_payload_attr[payloads_num-i] = payload; + for(i = 0; i <= payloads_num; i++) { + _stream->p_payload_attr[payloads_num - i] = payload; payload = payload->next; } @@ -207,9 +213,10 @@ static inline sdp_payload_attr_t** init_p_payload_attr(sdp_stream_cell_t* _strea * Setters ... */ -void set_sdp_payload_attr(sdp_payload_attr_t *payload_attr, str *rtp_enc, str *rtp_clock, str *rtp_params) +void set_sdp_payload_attr(sdp_payload_attr_t *payload_attr, str *rtp_enc, + str *rtp_clock, str *rtp_params) { - if (payload_attr == NULL) { + if(payload_attr == NULL) { LM_ERR("Invalid payload location\n"); return; } @@ -223,9 +230,9 @@ void set_sdp_payload_attr(sdp_payload_attr_t *payload_attr, str *rtp_enc, str *r return; } -void set_sdp_payload_fmtp(sdp_payload_attr_t *payload_attr, str *fmtp_string ) +void set_sdp_payload_fmtp(sdp_payload_attr_t *payload_attr, str *fmtp_string) { - if (payload_attr == NULL) { + if(payload_attr == NULL) { LM_ERR("Invalid payload location\n"); return; } @@ -238,55 +245,68 @@ void set_sdp_payload_fmtp(sdp_payload_attr_t *payload_attr, str *fmtp_string ) /* * Getters .... */ -int get_sdp_session_num(struct sip_msg* _m) +int get_sdp_session_num(struct sip_msg *_m) { - if (_m->body == NULL) return 0; - if (_m->body->type != MSG_BODY_SDP) return 0; - return ((sdp_info_t*)_m->body)->sessions_num; + if(_m->body == NULL) + return 0; + if(_m->body->type != MSG_BODY_SDP) + return 0; + return ((sdp_info_t *)_m->body)->sessions_num; } -int get_sdp_stream_num(struct sip_msg* _m) +int get_sdp_stream_num(struct sip_msg *_m) { - if (_m->body == NULL) return 0; - if (_m->body->type != MSG_BODY_SDP) return 0; - return ((sdp_info_t*)_m->body)->streams_num; + if(_m->body == NULL) + return 0; + if(_m->body->type != MSG_BODY_SDP) + return 0; + return ((sdp_info_t *)_m->body)->streams_num; } -sdp_session_cell_t* get_sdp_session_sdp(struct sdp_info* sdp, int session_num) +sdp_session_cell_t *get_sdp_session_sdp(struct sdp_info *sdp, int session_num) { sdp_session_cell_t *session; session = sdp->sessions; - if (session_num >= sdp->sessions_num) return NULL; - while (session) { - if (session->session_num == session_num) return session; + if(session_num >= sdp->sessions_num) + return NULL; + while(session) { + if(session->session_num == session_num) + return session; session = session->next; } return NULL; } -sdp_session_cell_t* get_sdp_session(struct sip_msg* _m, int session_num) +sdp_session_cell_t *get_sdp_session(struct sip_msg *_m, int session_num) { - if (_m->body == NULL) return NULL; - if (_m->body->type != MSG_BODY_SDP) return NULL; - return get_sdp_session_sdp((sdp_info_t*)_m->body, session_num); + if(_m->body == NULL) + return NULL; + if(_m->body->type != MSG_BODY_SDP) + return NULL; + return get_sdp_session_sdp((sdp_info_t *)_m->body, session_num); } -sdp_stream_cell_t* get_sdp_stream_sdp(struct sdp_info* sdp, int session_num, int stream_num) +sdp_stream_cell_t *get_sdp_stream_sdp( + struct sdp_info *sdp, int session_num, int stream_num) { sdp_session_cell_t *session; sdp_stream_cell_t *stream; - if (sdp==NULL) return NULL; - if (session_num >= sdp->sessions_num) return NULL; + if(sdp == NULL) + return NULL; + if(session_num >= sdp->sessions_num) + return NULL; session = sdp->sessions; - while (session) { - if (session->session_num == session_num) { - if (stream_num >= session->streams_num) return NULL; + while(session) { + if(session->session_num == session_num) { + if(stream_num >= session->streams_num) + return NULL; stream = session->streams; - while (stream) { - if (stream->stream_num == stream_num) return stream; + while(stream) { + if(stream->stream_num == stream_num) + return stream; stream = stream->next; } break; @@ -298,32 +318,38 @@ sdp_stream_cell_t* get_sdp_stream_sdp(struct sdp_info* sdp, int session_num, int return NULL; } -sdp_stream_cell_t* get_sdp_stream(struct sip_msg* _m, int session_num, int stream_num) +sdp_stream_cell_t *get_sdp_stream( + struct sip_msg *_m, int session_num, int stream_num) { - if (_m->body == NULL) return NULL; - if (_m->body->type != MSG_BODY_SDP) return NULL; - return get_sdp_stream_sdp((sdp_info_t*)_m->body, session_num, stream_num); + if(_m->body == NULL) + return NULL; + if(_m->body->type != MSG_BODY_SDP) + return NULL; + return get_sdp_stream_sdp((sdp_info_t *)_m->body, session_num, stream_num); } -sdp_payload_attr_t* get_sdp_payload4payload(sdp_stream_cell_t *stream, str *rtp_payload) +sdp_payload_attr_t *get_sdp_payload4payload( + sdp_stream_cell_t *stream, str *rtp_payload) { sdp_payload_attr_t *payload; int i; - if (stream == NULL) { + if(stream == NULL) { LM_ERR("Invalid stream location\n"); return NULL; } - if (stream->p_payload_attr == NULL) { + if(stream->p_payload_attr == NULL) { LM_ERR("Invalid access pointer to payloads\n"); return NULL; } - for (i=0;ipayloads_num;i++) { + for(i = 0; i < stream->payloads_num; i++) { payload = stream->p_payload_attr[i]; - if (rtp_payload->len == payload->rtp_payload.len && - (strncmp(rtp_payload->s, payload->rtp_payload.s, rtp_payload->len)==0)) { + if(rtp_payload->len == payload->rtp_payload.len + && (strncmp(rtp_payload->s, payload->rtp_payload.s, + rtp_payload->len) + == 0)) { return payload; } } @@ -331,17 +357,17 @@ sdp_payload_attr_t* get_sdp_payload4payload(sdp_stream_cell_t *stream, str *rtp_ return NULL; } -sdp_payload_attr_t* get_sdp_payload4index(sdp_stream_cell_t *stream, int index) +sdp_payload_attr_t *get_sdp_payload4index(sdp_stream_cell_t *stream, int index) { - if (stream == NULL) { + if(stream == NULL) { LM_ERR("Invalid stream location\n"); return NULL; } - if (stream->p_payload_attr == NULL) { + if(stream->p_payload_attr == NULL) { LM_ERR("Invalid access pointer to payloads\n"); return NULL; } - if (index >= stream->payloads_num) { + if(index >= stream->payloads_num) { LM_ERR("Out of range index [%d] for payload\n", index); return NULL; } @@ -353,10 +379,11 @@ sdp_payload_attr_t* get_sdp_payload4index(sdp_stream_cell_t *stream, int index) /** * SDP parser method. */ -static int parse_sdp_session(str *sdp_body, int session_num, str *cnt_disp, sdp_info_t* _sdp) +static int parse_sdp_session( + str *sdp_body, int session_num, str *cnt_disp, sdp_info_t *_sdp) { str body = *sdp_body; - str sdp_ip = {NULL,0}; + str sdp_ip = {NULL, 0}; str sdp_media, sdp_port, sdp_transport, sdp_payload; str payload; str rtp_payload, rtp_enc, rtp_clock, rtp_params; @@ -392,30 +419,31 @@ static int parse_sdp_session(str *sdp_body, int session_num, str *cnt_disp, sdp_ */ bodylimit = body.s + body.len; v1p = find_sdp_line(body.s, bodylimit, 'v'); - if (v1p == NULL) { + if(v1p == NULL) { LM_ERR("no sessions in SDP\n"); return -1; } /* get session origin */ o1p = find_sdp_line(v1p, bodylimit, 'o'); - if (o1p == NULL) { + if(o1p == NULL) { LM_ERR("no o= in session\n"); return -1; } /* Have this session media description? */ m1p = find_sdp_line(o1p, bodylimit, 'm'); - if (m1p == NULL) { + if(m1p == NULL) { LM_ERR("no m= in session\n"); return -1; } /* Allocate a session cell */ session = add_sdp_session(_sdp, session_num, cnt_disp); - if (session == NULL) return -1; + if(session == NULL) + return -1; /* Get sess-version */ tmpstr1.s = o1p; - tmpstr1.len = eat_line(o1p,m1p-o1p) - o1p; - if ( extract_sess_version(&tmpstr1, &session->o_sess_version) == -1 ) { + tmpstr1.len = eat_line(o1p, m1p - o1p) - o1p; + if(extract_sess_version(&tmpstr1, &session->o_sess_version) == -1) { LM_ERR("can't extract origin sess-version from the message\n"); return -1; } @@ -423,7 +451,8 @@ static int parse_sdp_session(str *sdp_body, int session_num, str *cnt_disp, sdp_ /* Get origin IP */ tmpstr1.s = o1p; tmpstr1.len = bodylimit - tmpstr1.s; /* limit is session limit text */ - if (extract_mediaip(&tmpstr1, &session->o_ip_addr, &session->o_pf,"o=") == -1) { + if(extract_mediaip(&tmpstr1, &session->o_ip_addr, &session->o_pf, "o=") + == -1) { LM_ERR("can't extract origin media IP from the message\n"); return -1; } @@ -432,11 +461,12 @@ static int parse_sdp_session(str *sdp_body, int session_num, str *cnt_disp, sdp_ * c1p will give common c= for all medias. */ c1p = find_sdp_line(o1p, m1p, 'c'); - if (c1p) { + if(c1p) { /* Extract session address */ tmpstr1.s = c1p; tmpstr1.len = bodylimit - tmpstr1.s; /* limit is session limit text */ - if (extract_mediaip(&tmpstr1, &session->ip_addr, &session->pf,"c=") == -1) { + if(extract_mediaip(&tmpstr1, &session->ip_addr, &session->pf, "c=") + == -1) { LM_ERR("can't extract common media IP from the message\n"); return -1; } @@ -445,7 +475,7 @@ static int parse_sdp_session(str *sdp_body, int session_num, str *cnt_disp, sdp_ /* Find b1p only between session begin and first media. * b1p will give common b= for all medias. */ b1p = find_sdp_line(o1p, m1p, 'b'); - if (b1p) { + if(b1p) { tmpstr1.s = b1p; tmpstr1.len = m1p - b1p; extract_bwidth(&tmpstr1, &session->bw_type, &session->bw_width); @@ -454,10 +484,12 @@ static int parse_sdp_session(str *sdp_body, int session_num, str *cnt_disp, sdp_ /* Find sendrecv_mode between session begin and first media. * parse session attributes to check is_on_hold for a= for all medias. */ a1p = find_first_sdp_line(o1p, m1p, 'a', NULL); - while (a1p) { + while(a1p) { tmpstr1.s = a1p; tmpstr1.len = m1p - a1p; - if (extract_sendrecv_mode(&tmpstr1, &session->sendrecv_mode, &session->is_on_hold) == 0) { + if(extract_sendrecv_mode( + &tmpstr1, &session->sendrecv_mode, &session->is_on_hold) + == 0) { break; } a1p = find_next_sdp_line(a1p, m1p, 'a', NULL); @@ -466,9 +498,9 @@ static int parse_sdp_session(str *sdp_body, int session_num, str *cnt_disp, sdp_ /* Have session. Iterate media descriptions in session */ m2p = m1p; stream_num = 0; - for (;;) { - m1p = m2p; - if (m1p == NULL || m1p >= bodylimit) + for(;;) { + m1p = m2p; + if(m1p == NULL || m1p >= bodylimit) break; m2p = find_next_sdp_line(m1p, bodylimit, 'm', bodylimit); /* c2p will point to per-media "c=" */ @@ -476,16 +508,17 @@ static int parse_sdp_session(str *sdp_body, int session_num, str *cnt_disp, sdp_ sdp_ip.s = NULL; sdp_ip.len = 0; - if (c2p) { + if(c2p) { /* Extract stream address */ tmpstr1.s = c2p; - tmpstr1.len = bodylimit - tmpstr1.s; /* limit is session limit text */ - if (extract_mediaip(&tmpstr1, &sdp_ip, &pf,"c=") == -1) { + tmpstr1.len = + bodylimit - tmpstr1.s; /* limit is session limit text */ + if(extract_mediaip(&tmpstr1, &sdp_ip, &pf, "c=") == -1) { LM_ERR("can't extract media IP from the message\n"); return -1; } } else { - if (!c1p) { + if(!c1p) { /* No "c=" */ LM_ERR("can't find media IP in the message\n"); return -1; @@ -495,25 +528,29 @@ static int parse_sdp_session(str *sdp_body, int session_num, str *cnt_disp, sdp_ /* Extract the port on sdp_port */ tmpstr1.s = m1p; tmpstr1.len = m2p - m1p; - if (extract_media_attr(&tmpstr1, &sdp_media, &sdp_port, &sdp_transport, &sdp_payload, &is_rtp) == -1) { + if(extract_media_attr(&tmpstr1, &sdp_media, &sdp_port, &sdp_transport, + &sdp_payload, &is_rtp) + == -1) { LM_ERR("can't extract media attr from the message\n"); return -1; } /* Allocate a stream cell */ - stream = add_sdp_stream(session, stream_num, &sdp_media, &sdp_port, &sdp_transport, &sdp_payload, is_rtp, pf, &sdp_ip); - if (stream == 0) return -1; + stream = add_sdp_stream(session, stream_num, &sdp_media, &sdp_port, + &sdp_transport, &sdp_payload, is_rtp, pf, &sdp_ip); + if(stream == 0) + return -1; + + /* Store fast access ptr to raw stream */ + stream->raw_stream.s = tmpstr1.s; + stream->raw_stream.len = tmpstr1.len; - /* Store fast access ptr to raw stream */ - stream->raw_stream.s = tmpstr1.s; - stream->raw_stream.len = tmpstr1.len; - /* increment total number of streams */ _sdp->streams_num++; /* b1p will point to per-media "b=" */ b1p = find_sdp_line(m1p, m2p, 'b'); - if (b1p) { + if(b1p) { tmpstr1.s = b1p; tmpstr1.len = m2p - b1p; extract_bwidth(&tmpstr1, &stream->bw_type, &stream->bw_width); @@ -523,25 +560,26 @@ static int parse_sdp_session(str *sdp_body, int session_num, str *cnt_disp, sdp_ tmpstr1.s = sdp_payload.s; tmpstr1.len = sdp_payload.len; payloadnum = 0; - if (tmpstr1.len != 0) { - for (;;) { + if(tmpstr1.len != 0) { + for(;;) { a1p = eat_token_end(tmpstr1.s, tmpstr1.s + tmpstr1.len); payload.s = tmpstr1.s; payload.len = a1p - tmpstr1.s; payload_attr = add_sdp_payload(stream, payloadnum, &payload); - if (payload_attr == NULL) return -1; + if(payload_attr == NULL) + return -1; tmpstr1.len -= payload.len; tmpstr1.s = a1p; a2p = eat_space_end(tmpstr1.s, tmpstr1.s + tmpstr1.len); tmpstr1.len -= a2p - a1p; tmpstr1.s = a2p; - if (a1p >= tmpstr1.s) + if(a1p >= tmpstr1.s) break; payloadnum++; } /* Initialize fast access pointers */ - if (NULL == init_p_payload_attr(stream, SDP_USE_PKG_MEM)) { + if(NULL == init_p_payload_attr(stream, SDP_USE_PKG_MEM)) { return -1; } parse_payload_attr = 1; @@ -553,51 +591,70 @@ static int parse_sdp_session(str *sdp_body, int session_num, str *cnt_disp, sdp_ /* Let's figure out the attributes */ a1p = find_sdp_line(m1p, m2p, 'a'); a2p = a1p; - for (;;) { + for(;;) { a1p = a2p; - if (a1p == NULL || a1p >= m2p) + if(a1p == NULL || a1p >= m2p) break; tmpstr1.s = a2p; tmpstr1.len = m2p - a2p; - if (parse_payload_attr && extract_ptime(&tmpstr1, &stream->ptime) == 0) { + if(parse_payload_attr + && extract_ptime(&tmpstr1, &stream->ptime) == 0) { a1p = stream->ptime.s + stream->ptime.len; - } else if (parse_payload_attr && extract_sendrecv_mode(&tmpstr1, - &stream->sendrecv_mode, &stream->is_on_hold) == 0) { + } else if(parse_payload_attr + && extract_sendrecv_mode(&tmpstr1, &stream->sendrecv_mode, + &stream->is_on_hold) + == 0) { a1p = stream->sendrecv_mode.s + stream->sendrecv_mode.len; - } else if (parse_payload_attr && extract_rtpmap(&tmpstr1, &rtp_payload, &rtp_enc, &rtp_clock, &rtp_params) == 0) { - if (rtp_params.len != 0 && rtp_params.s != NULL) { + } else if(parse_payload_attr + && extract_rtpmap(&tmpstr1, &rtp_payload, &rtp_enc, + &rtp_clock, &rtp_params) + == 0) { + if(rtp_params.len != 0 && rtp_params.s != NULL) { a1p = rtp_params.s + rtp_params.len; } else { a1p = rtp_clock.s + rtp_clock.len; } - payload_attr = (sdp_payload_attr_t*)get_sdp_payload4payload(stream, &rtp_payload); - set_sdp_payload_attr(payload_attr, &rtp_enc, &rtp_clock, &rtp_params); - } else if (extract_rtcp(&tmpstr1, &stream->rtcp_port) == 0) { + payload_attr = (sdp_payload_attr_t *)get_sdp_payload4payload( + stream, &rtp_payload); + set_sdp_payload_attr( + payload_attr, &rtp_enc, &rtp_clock, &rtp_params); + } else if(extract_rtcp(&tmpstr1, &stream->rtcp_port) == 0) { a1p = stream->rtcp_port.s + stream->rtcp_port.len; - } else if (parse_payload_attr && extract_fmtp(&tmpstr1,&rtp_payload,&fmtp_string) == 0){ + } else if(parse_payload_attr + && extract_fmtp(&tmpstr1, &rtp_payload, &fmtp_string) + == 0) { a1p = fmtp_string.s + fmtp_string.len; - payload_attr = (sdp_payload_attr_t*)get_sdp_payload4payload(stream, &rtp_payload); + payload_attr = (sdp_payload_attr_t *)get_sdp_payload4payload( + stream, &rtp_payload); set_sdp_payload_fmtp(payload_attr, &fmtp_string); - } else if (parse_payload_attr && extract_candidate(&tmpstr1, stream) == 0) { + } else if(parse_payload_attr + && extract_candidate(&tmpstr1, stream) == 0) { a1p += 2; - } else if (parse_payload_attr && extract_ice_option(&tmpstr1, stream) == 0) { + } else if(parse_payload_attr + && extract_ice_option(&tmpstr1, stream) == 0) { a1p += 2; - } else if (parse_payload_attr && extract_field(&tmpstr1, &stream->remote_candidates, - remote_candidates) == 0) { + } else if(parse_payload_attr + && extract_field(&tmpstr1, &stream->remote_candidates, + remote_candidates) + == 0) { a1p += 2; - } else if (extract_accept_types(&tmpstr1, &stream->accept_types) == 0) { + } else if(extract_accept_types(&tmpstr1, &stream->accept_types) + == 0) { a1p = stream->accept_types.s + stream->accept_types.len; - } else if (extract_accept_wrapped_types(&tmpstr1, &stream->accept_wrapped_types) == 0) { - a1p = stream->accept_wrapped_types.s + stream->accept_wrapped_types.len; - } else if (extract_max_size(&tmpstr1, &stream->max_size) == 0) { + } else if(extract_accept_wrapped_types( + &tmpstr1, &stream->accept_wrapped_types) + == 0) { + a1p = stream->accept_wrapped_types.s + + stream->accept_wrapped_types.len; + } else if(extract_max_size(&tmpstr1, &stream->max_size) == 0) { a1p = stream->max_size.s + stream->max_size.len; - } else if (extract_path(&tmpstr1, &stream->path) == 0) { + } else if(extract_path(&tmpstr1, &stream->path) == 0) { a1p = stream->path.s + stream->path.len; } else { /* unknown a= line, ignore -- jump over it */ LM_DBG("ignoring unknown type in a= line: `%.*s...'\n", - (tmpstr1.len>20)?20:tmpstr1.len, tmpstr1.s); + (tmpstr1.len > 20) ? 20 : tmpstr1.len, tmpstr1.s); a1p += 2; } @@ -605,14 +662,15 @@ static int parse_sdp_session(str *sdp_body, int session_num, str *cnt_disp, sdp_ } /* Let's detect if the media is on hold by checking * the good old "0.0.0.0" connection address */ - if (!stream->is_on_hold) { + if(!stream->is_on_hold) { /* But, exclude the cases with ICE trickle re-negotiation (RFC8840), * which are not the on hold (RFC2543) case actually */ ice_opt = stream->ice_opt; - while(ice_opt) - { - if (ice_opt->option.len == ICE_OPT_TRICKLE_LEN && - strncmp(ice_opt->option.s, ICE_OPT_TRICKLE_STR, ICE_OPT_TRICKLE_LEN)==0) { + while(ice_opt) { + if(ice_opt->option.len == ICE_OPT_TRICKLE_LEN + && strncmp(ice_opt->option.s, ICE_OPT_TRICKLE_STR, + ICE_OPT_TRICKLE_LEN) + == 0) { ice_trickle = 1; ice_opt = NULL; /* break */ } else { @@ -621,31 +679,39 @@ static int parse_sdp_session(str *sdp_body, int session_num, str *cnt_disp, sdp_ } /* SDP stream level */ - if (stream->ip_addr.s && stream->ip_addr.len) { - if (stream->pf == AF_INET && - stream->ip_addr.len == HOLD_IP_LEN && - strncmp(stream->ip_addr.s, HOLD_IP_STR, HOLD_IP_LEN)==0) { + if(stream->ip_addr.s && stream->ip_addr.len) { + if(stream->pf == AF_INET && stream->ip_addr.len == HOLD_IP_LEN + && strncmp(stream->ip_addr.s, HOLD_IP_STR, HOLD_IP_LEN) + == 0) { /* make sure it's not ICE trickle re-negotiation */ - if (ice_trickle && - stream->port.len==HOLD_PORT_ICE_TRICKLE_LEN && /* port=9 */ - strncmp(stream->port.s,HOLD_PORT_ICE_TRICKLE_STR,HOLD_PORT_ICE_TRICKLE_LEN)==0) - LM_DBG("Not a zeroed on-hold (RFC2543), because is ICE re-negotiaion (RFC8840)\n"); + if(ice_trickle + && stream->port.len == HOLD_PORT_ICE_TRICKLE_LEN + && /* port=9 */ + strncmp(stream->port.s, HOLD_PORT_ICE_TRICKLE_STR, + HOLD_PORT_ICE_TRICKLE_LEN) + == 0) + LM_DBG("Not a zeroed on-hold (RFC2543), because is ICE " + "re-negotiaion (RFC8840)\n"); else stream->is_on_hold = RFC2543_HOLD; } - /* SDP session level */ - } else if (session->ip_addr.s && session->ip_addr.len) { - if (session->pf == AF_INET && - session->ip_addr.len == HOLD_IP_LEN && - strncmp(session->ip_addr.s, HOLD_IP_STR, HOLD_IP_LEN)==0) { + /* SDP session level */ + } else if(session->ip_addr.s && session->ip_addr.len) { + if(session->pf == AF_INET && session->ip_addr.len == HOLD_IP_LEN + && strncmp(session->ip_addr.s, HOLD_IP_STR, HOLD_IP_LEN) + == 0) { /* make sure it's not ICE trickle re-negotiation */ - if (ice_trickle && - stream->port.len==HOLD_PORT_ICE_TRICKLE_LEN && /* port=9 */ - strncmp(stream->port.s,HOLD_PORT_ICE_TRICKLE_STR,HOLD_PORT_ICE_TRICKLE_LEN)==0) - LM_DBG("Not a zeroed on-hold (RFC2543), because is ICE re-negotiaion (RFC8840)\n"); + if(ice_trickle + && stream->port.len == HOLD_PORT_ICE_TRICKLE_LEN + && /* port=9 */ + strncmp(stream->port.s, HOLD_PORT_ICE_TRICKLE_STR, + HOLD_PORT_ICE_TRICKLE_LEN) + == 0) + LM_DBG("Not a zeroed on-hold (RFC2543), because is ICE " + "re-negotiaion (RFC8840)\n"); else stream->is_on_hold = RFC2543_HOLD; } @@ -656,7 +722,7 @@ static int parse_sdp_session(str *sdp_body, int session_num, str *cnt_disp, sdp_ return 0; } -static int parse_mixed_content(str *mixed_body, str delimiter, sdp_info_t* _sdp) +static int parse_mixed_content(str *mixed_body, str delimiter, sdp_info_t *_sdp) { int res, no_eoh_found, start_parsing; char *bodylimit, *rest; @@ -669,7 +735,7 @@ static int parse_mixed_content(str *mixed_body, str delimiter, sdp_info_t* _sdp) bodylimit = mixed_body->s + mixed_body->len; d1p = find_sdp_line_delimiter(mixed_body->s, bodylimit, delimiter); - if (d1p == NULL) { + if(d1p == NULL) { LM_ERR("empty multipart content\n"); return -1; } @@ -678,73 +744,81 @@ static int parse_mixed_content(str *mixed_body, str delimiter, sdp_info_t* _sdp) for(;;) { /* Per-application iteration */ d1p = d2p; - if (d1p == NULL || d1p >= bodylimit) + if(d1p == NULL || d1p >= bodylimit) break; /* No applications left */ if(d1p + delimiter.len + 2 > bodylimit) { LM_ERR("failed parsing [%.*s]\n", mixed_body->len, mixed_body->s); return -1; } - d2p = find_next_sdp_line_delimiter(d1p, bodylimit, delimiter, bodylimit); + d2p = find_next_sdp_line_delimiter( + d1p, bodylimit, delimiter, bodylimit); if(d2p - d1p < delimiter.len + 2) { - LM_ERR("invalid format [%.*s]\n", (int)(d2p-d1p), d1p); + LM_ERR("invalid format [%.*s]\n", (int)(d2p - d1p), d1p); return -1; } /* d2p is text limit for application parsing */ memset(&hf, 0, sizeof(struct hdr_field)); rest = eat_line(d1p + delimiter.len + 2, d2p - d1p - delimiter.len - 2); - if ( rest > d2p ) { - LM_ERR("unparsable [%.*s]\n", (int)(d2p-d1p), d1p); + if(rest > d2p) { + LM_ERR("unparsable [%.*s]\n", (int)(d2p - d1p), d1p); return -1; } no_eoh_found = 1; start_parsing = 0; /*LM_DBG("we need to parse this: <%.*s>\n", d2p-rest, rest); */ - while( rest>16)==TYPE_ALL) { - LM_ERR("invalid mime with wildcard '*' in Content-Type hdr!\n"); + switch(hf.type) { + case HDR_EOH_T: + no_eoh_found = 0; + break; + case HDR_CONTENTTYPE_T: + end = hf.body.s + hf.body.len; + ret = decode_mime_type(hf.body.s, end, &mime); + if(ret == 0) + return -1; + if(ret != end) { + LM_ERR("the header CONTENT_TYPE contains " + "more than one mime type :-(!\n"); + return -1; + } + if((mime & 0x00ff) == SUBTYPE_ALL + || (mime >> 16) == TYPE_ALL) { + LM_ERR("invalid mime with wildcard '*' in Content-Type " + "hdr!\n"); + return -1; + } + //LM_DBG("HDR_CONTENTTYPE_T: %d:%d %p-> <%.*s:%.*s>\n",mime&0x00ff,mime>>16, + // hf.name.s,hf.name.len,hf.name.s,hf.body.len,hf.body.s); + if(((((unsigned int)mime) >> 16) == TYPE_APPLICATION) + && ((mime & 0x00ff) == SUBTYPE_SDP)) { + /*LM_DBG("start_parsing: %d:%d\n",mime&0x00ff,mime>>16); */ + start_parsing = 1; + } + break; + case HDR_CONTENTDISPOSITION_T: + cnt_disp.s = hf.body.s; + cnt_disp.len = hf.body.len; + break; + case HDR_ERROR_T: return -1; - } - //LM_DBG("HDR_CONTENTTYPE_T: %d:%d %p-> <%.*s:%.*s>\n",mime&0x00ff,mime>>16, - // hf.name.s,hf.name.len,hf.name.s,hf.body.len,hf.body.s); - if (((((unsigned int)mime)>>16) == TYPE_APPLICATION) && ((mime&0x00ff) == SUBTYPE_SDP)) { - /*LM_DBG("start_parsing: %d:%d\n",mime&0x00ff,mime>>16); */ - start_parsing = 1; - } - break; - case HDR_CONTENTDISPOSITION_T: - cnt_disp.s = hf.body.s; - cnt_disp.len = hf.body.len; - break; - case HDR_ERROR_T: - return -1; - break; - default: - LM_DBG("unknown header: <%.*s:%.*s>\n",hf.name.len,hf.name.s,hf.body.len,hf.body.s); + break; + default: + LM_DBG("unknown header: <%.*s:%.*s>\n", hf.name.len, + hf.name.s, hf.body.len, hf.body.s); } } /* end of while */ /* and now we need to parse the content */ - if (start_parsing) { - while (('\n' == *rest) || ('\r' == *rest) || ('\t' == *rest)|| (' ' == *rest)) rest++; /* Skip any whitespace */ + if(start_parsing) { + while(('\n' == *rest) || ('\r' == *rest) || ('\t' == *rest) + || (' ' == *rest)) + rest++; /* Skip any whitespace */ _sdp->raw_sdp.s = rest; - _sdp->raw_sdp.len = d2p-rest; + _sdp->raw_sdp.len = d2p - rest; /* LM_DBG("we need to check session %d: <%.*s>\n", session_num, _sdp.raw_sdp.len, _sdp.raw_sdp.s); */ - res = parse_sdp_session(&_sdp->raw_sdp, session_num, &cnt_disp, _sdp); - if (res != 0) { + res = parse_sdp_session( + &_sdp->raw_sdp, session_num, &cnt_disp, _sdp); + if(res != 0) { /* _sdp is freed by the calling function */ return -1; } @@ -760,87 +834,91 @@ static int parse_mixed_content(str *mixed_body, str delimiter, sdp_info_t* _sdp) * @param _m the SIP message structure * @return 0 on success, < 0 on error and 1 if there is no message body */ -int parse_sdp(struct sip_msg* _m) +int parse_sdp(struct sip_msg *_m) { int res; str body, mp_delimiter; int mime; - if (_m->body) { - return 0; /* Already parsed */ + if(_m->body) { + return 0; /* Already parsed */ } body.s = get_body(_m); - if (body.s==NULL) { + if(body.s == NULL) { LM_ERR("failed to get the message body\n"); return -1; } - body.len = _m->len -(int)(body.s - _m->buf); - if (body.len==0) { + body.len = _m->len - (int)(body.s - _m->buf); + if(body.len == 0) { LM_DBG("message body has length zero\n"); return 1; } mime = parse_content_type_hdr(_m); - if (mime <= 0) { + if(mime <= 0) { return -1; } - switch (((unsigned int)mime)>>16) { - case TYPE_APPLICATION: - /* LM_DBG("TYPE_APPLICATION: %d\n",((unsigned int)mime)>>16); */ - switch (mime&0x00ff) { - case SUBTYPE_SDP: - /* LM_DBG("SUBTYPE_SDP: %d\n",mime&0x00ff); */ - if (new_sdp(_m) < 0) { - LM_ERR("Can't create sdp\n"); - return -1; - } - res = parse_sdp_session(&body, 0, NULL, (sdp_info_t*)_m->body); - if (res != 0) { - LM_DBG("failed to parse sdp session - freeing sdp\n"); - free_sdp((sdp_info_t**)(void*)&_m->body); - return res; + switch(((unsigned int)mime) >> 16) { + case TYPE_APPLICATION: + /* LM_DBG("TYPE_APPLICATION: %d\n",((unsigned int)mime)>>16); */ + switch(mime & 0x00ff) { + case SUBTYPE_SDP: + /* LM_DBG("SUBTYPE_SDP: %d\n",mime&0x00ff); */ + if(new_sdp(_m) < 0) { + LM_ERR("Can't create sdp\n"); + return -1; + } + res = parse_sdp_session( + &body, 0, NULL, (sdp_info_t *)_m->body); + if(res != 0) { + LM_DBG("failed to parse sdp session - freeing sdp\n"); + free_sdp((sdp_info_t **)(void *)&_m->body); + return res; + } + /* The whole body is SDP */ + ((sdp_info_t *)_m->body)->raw_sdp.s = body.s; + ((sdp_info_t *)_m->body)->raw_sdp.len = body.len; + return res; + break; + default: + LM_DBG("TYPE_APPLICATION: unknown %d\n", mime & 0x00ff); + return -1; } - /* The whole body is SDP */ - ((sdp_info_t*)_m->body)->raw_sdp.s = body.s; - ((sdp_info_t*)_m->body)->raw_sdp.len = body.len; - return res; break; - default: - LM_DBG("TYPE_APPLICATION: unknown %d\n",mime&0x00ff); - return -1; - } - break; - case TYPE_MULTIPART: - /* LM_DBG("TYPE_MULTIPART: %d\n",((unsigned int)mime)>>16); */ - switch (mime&0x00ff) { - case SUBTYPE_MIXED: - /* LM_DBG("SUBTYPE_MIXED: %d <%.*s>\n",mime&0x00ff,_m->content_type->body.len,_m->content_type->body.s); */ - if(get_mixed_part_delimiter(&(_m->content_type->body),&mp_delimiter) > 0) { - /*LM_DBG("got delimiter: <%.*s>\n",mp_delimiter.len,mp_delimiter.s); */ - if (new_sdp(_m) < 0) { - LM_ERR("Can't create sdp\n"); + case TYPE_MULTIPART: + /* LM_DBG("TYPE_MULTIPART: %d\n",((unsigned int)mime)>>16); */ + switch(mime & 0x00ff) { + case SUBTYPE_MIXED: + /* LM_DBG("SUBTYPE_MIXED: %d <%.*s>\n",mime&0x00ff,_m->content_type->body.len,_m->content_type->body.s); */ + if(get_mixed_part_delimiter( + &(_m->content_type->body), &mp_delimiter) + > 0) { + /*LM_DBG("got delimiter: <%.*s>\n",mp_delimiter.len,mp_delimiter.s); */ + if(new_sdp(_m) < 0) { + LM_ERR("Can't create sdp\n"); + return -1; + } + res = parse_mixed_content( + &body, mp_delimiter, (sdp_info_t *)_m->body); + if(res != 0) { + LM_DBG("free_sdp\n"); + free_sdp((sdp_info_t **)(void *)&_m->body); + } + return res; + } else { + return -1; + } + break; + default: + LM_DBG("TYPE_MULTIPART: unknown %d\n", mime & 0x00ff); return -1; - } - res = parse_mixed_content(&body, mp_delimiter, (sdp_info_t*)_m->body); - if (res != 0) { - LM_DBG("free_sdp\n"); - free_sdp((sdp_info_t**)(void*)&_m->body); - } - return res; - } else { - return -1; } break; default: - LM_DBG("TYPE_MULTIPART: unknown %d\n",mime&0x00ff); + LM_DBG("%d\n", ((unsigned int)mime) >> 16); return -1; - } - break; - default: - LM_DBG("%d\n",((unsigned int)mime)>>16); - return -1; } LM_CRIT("We should not see this!\n"); @@ -851,7 +929,7 @@ int parse_sdp(struct sip_msg* _m) /** * Free all memory. */ -void free_sdp(sdp_info_t** _sdp) +void free_sdp(sdp_info_t **_sdp) { sdp_info_t *sdp = *_sdp; sdp_session_cell_t *session, *l_session; @@ -861,34 +939,35 @@ void free_sdp(sdp_info_t** _sdp) sdp_ice_opt_t *ice_opt, *l_ice_opt; LM_DBG("_sdp = %p\n", _sdp); - if (sdp == NULL) return; + if(sdp == NULL) + return; LM_DBG("sdp = %p\n", sdp); session = sdp->sessions; LM_DBG("session = %p\n", session); - while (session) { + while(session) { l_session = session; session = session->next; stream = l_session->streams; - while (stream) { + while(stream) { l_stream = stream; stream = stream->next; payload = l_stream->payload_attr; - while (payload) { + while(payload) { l_payload = payload; payload = payload->next; pkg_free(l_payload); } - if (l_stream->p_payload_attr) { + if(l_stream->p_payload_attr) { pkg_free(l_stream->p_payload_attr); } ice_attr = l_stream->ice_attr; - while (ice_attr) { + while(ice_attr) { l_ice_attr = ice_attr; ice_attr = ice_attr->next; pkg_free(l_ice_attr); } ice_opt = l_stream->ice_opt; - while (ice_opt) { + while(ice_opt) { l_ice_opt = ice_opt; ice_opt = ice_opt->next; pkg_free(l_ice_opt); @@ -908,49 +987,54 @@ void print_sdp_stream(sdp_stream_cell_t *stream, int log_level) sdp_ice_attr_t *ice_attr; sdp_ice_opt_t *ice_opt; - LOG(log_level , "....stream[%d]:%p=>%p {%p} '%.*s' '%.*s:%.*s:%.*s' '%.*s' [%d] '%.*s' '%.*s:%.*s' (%d)=>%p (%d)=>%p '%.*s' '%.*s' '%.*s' '%.*s' '%.*s' '%.*s' '%.*s'\n", - stream->stream_num, stream, stream->next, - stream->p_payload_attr, - stream->media.len, stream->media.s, - stream->ip_addr.len, stream->ip_addr.s, stream->port.len, stream->port.s, - stream->rtcp_port.len, stream->rtcp_port.s, - stream->transport.len, stream->transport.s, stream->is_rtp, - stream->payloads.len, stream->payloads.s, - stream->bw_type.len, stream->bw_type.s, stream->bw_width.len, stream->bw_width.s, - stream->payloads_num, stream->payload_attr, - stream->ice_attrs_num, stream->ice_attr, - stream->sendrecv_mode.len, stream->sendrecv_mode.s, - stream->ptime.len, stream->ptime.s, - stream->path.len, stream->path.s, - stream->max_size.len, stream->max_size.s, - stream->accept_types.len, stream->accept_types.s, - stream->accept_wrapped_types.len, stream->accept_wrapped_types.s, - stream->remote_candidates.len, stream->remote_candidates.s); + LOG(log_level, + "....stream[%d]:%p=>%p {%p} '%.*s' '%.*s:%.*s:%.*s' '%.*s' [%d] " + "'%.*s' '%.*s:%.*s' (%d)=>%p (%d)=>%p '%.*s' '%.*s' '%.*s' '%.*s' " + "'%.*s' '%.*s' '%.*s'\n", + stream->stream_num, stream, stream->next, stream->p_payload_attr, + stream->media.len, stream->media.s, stream->ip_addr.len, + stream->ip_addr.s, stream->port.len, stream->port.s, + stream->rtcp_port.len, stream->rtcp_port.s, stream->transport.len, + stream->transport.s, stream->is_rtp, stream->payloads.len, + stream->payloads.s, stream->bw_type.len, stream->bw_type.s, + stream->bw_width.len, stream->bw_width.s, stream->payloads_num, + stream->payload_attr, stream->ice_attrs_num, stream->ice_attr, + stream->sendrecv_mode.len, stream->sendrecv_mode.s, + stream->ptime.len, stream->ptime.s, stream->path.len, + stream->path.s, stream->max_size.len, stream->max_size.s, + stream->accept_types.len, stream->accept_types.s, + stream->accept_wrapped_types.len, stream->accept_wrapped_types.s, + stream->remote_candidates.len, stream->remote_candidates.s); payload = stream->payload_attr; - while (payload) { - LOG(log_level, "......payload[%d]:%p=>%p p_payload_attr[%d]:%p '%.*s' '%.*s' '%.*s' '%.*s' '%.*s'\n", - payload->payload_num, payload, payload->next, - payload->payload_num, stream->p_payload_attr[payload->payload_num], - payload->rtp_payload.len, payload->rtp_payload.s, - payload->rtp_enc.len, payload->rtp_enc.s, - payload->rtp_clock.len, payload->rtp_clock.s, - payload->rtp_params.len, payload->rtp_params.s, - payload->fmtp_string.len, payload->fmtp_string.s); - payload=payload->next; + while(payload) { + LOG(log_level, + "......payload[%d]:%p=>%p p_payload_attr[%d]:%p '%.*s' '%.*s' " + "'%.*s' '%.*s' '%.*s'\n", + payload->payload_num, payload, payload->next, + payload->payload_num, + stream->p_payload_attr[payload->payload_num], + payload->rtp_payload.len, payload->rtp_payload.s, + payload->rtp_enc.len, payload->rtp_enc.s, + payload->rtp_clock.len, payload->rtp_clock.s, + payload->rtp_params.len, payload->rtp_params.s, + payload->fmtp_string.len, payload->fmtp_string.s); + payload = payload->next; } ice_attr = stream->ice_attr; - while (ice_attr) { - LOG(log_level, "......ice candidate foundation '%.*s' component id '%u'\n", - ice_attr->foundation.len, ice_attr->foundation.s, - ice_attr->component_id); + while(ice_attr) { + LOG(log_level, + "......ice candidate foundation '%.*s' component id '%u'\n", + ice_attr->foundation.len, ice_attr->foundation.s, + ice_attr->component_id); ice_attr = ice_attr->next; } ice_opt = stream->ice_opt; - while (ice_opt) { - LOG(log_level, "......ice option '%.*s'\n", ice_opt->option.len, ice_opt->option.s); + while(ice_opt) { + LOG(log_level, "......ice option '%.*s'\n", ice_opt->option.len, + ice_opt->option.s); ice_opt = ice_opt->next; } } @@ -959,39 +1043,39 @@ void print_sdp_session(sdp_session_cell_t *session, int log_level) { sdp_stream_cell_t *stream; - if (session==NULL) { + if(session == NULL) { LM_ERR("NULL session\n"); return; } stream = session->streams; - LOG(log_level, "..session[%d]:%p=>%p '%.*s' '%.*s' '%.*s' '%.*s:%.*s' (%d)=>%p\n", - session->session_num, session, session->next, - session->cnt_disp.len, session->cnt_disp.s, - session->ip_addr.len, session->ip_addr.s, - session->o_ip_addr.len, session->o_ip_addr.s, - session->bw_type.len, session->bw_type.s, session->bw_width.len, session->bw_width.s, - session->streams_num, session->streams); - while (stream) { + LOG(log_level, + "..session[%d]:%p=>%p '%.*s' '%.*s' '%.*s' '%.*s:%.*s' (%d)=>%p\n", + session->session_num, session, session->next, session->cnt_disp.len, + session->cnt_disp.s, session->ip_addr.len, session->ip_addr.s, + session->o_ip_addr.len, session->o_ip_addr.s, session->bw_type.len, + session->bw_type.s, session->bw_width.len, session->bw_width.s, + session->streams_num, session->streams); + while(stream) { print_sdp_stream(stream, log_level); - stream=stream->next; + stream = stream->next; } } -void print_sdp(sdp_info_t* sdp, int log_level) +void print_sdp(sdp_info_t *sdp, int log_level) { sdp_session_cell_t *session; - if (!sdp) - { - LOG(log_level, "no sdp body\n"); - return; + if(!sdp) { + LOG(log_level, "no sdp body\n"); + return; } - LOG(log_level, "sdp:%p=>%p (%d:%d)\n", sdp, sdp->sessions, sdp->sessions_num, sdp->streams_num); + LOG(log_level, "sdp:%p=>%p (%d:%d)\n", sdp, sdp->sessions, + sdp->sessions_num, sdp->streams_num); session = sdp->sessions; - while (session) { + while(session) { print_sdp_session(session, log_level); session = session->next; } @@ -1008,26 +1092,26 @@ void free_cloned_sdp_stream(sdp_stream_cell_t *_stream) sdp_ice_opt_t *ice_opt, *l_ice_opt; stream = _stream; - while (stream) { + while(stream) { l_stream = stream; stream = stream->next; payload = l_stream->payload_attr; - while (payload) { + while(payload) { l_payload = payload; payload = payload->next; shm_free(l_payload); } - if (l_stream->p_payload_attr) { + if(l_stream->p_payload_attr) { shm_free(l_stream->p_payload_attr); } ice_attr = l_stream->ice_attr; - while (ice_attr) { + while(ice_attr) { l_ice_attr = ice_attr; ice_attr = ice_attr->next; shm_free(l_ice_attr); } ice_opt = l_stream->ice_opt; - while (ice_opt) { + while(ice_opt) { l_ice_opt = ice_opt; ice_opt = ice_opt->next; shm_free(l_ice_opt); @@ -1044,7 +1128,7 @@ void free_cloned_sdp_session(sdp_session_cell_t *_session) sdp_session_cell_t *session, *l_session; session = _session; - while (session) { + while(session) { l_session = session; session = l_session->next; free_cloned_sdp_stream(l_session->streams); @@ -1052,106 +1136,100 @@ void free_cloned_sdp_session(sdp_session_cell_t *_session) } } -void free_cloned_sdp(sdp_info_t* sdp) +void free_cloned_sdp(sdp_info_t *sdp) { free_cloned_sdp_session(sdp->sessions); shm_free(sdp); } -sdp_payload_attr_t * clone_sdp_payload_attr(sdp_payload_attr_t *attr) +sdp_payload_attr_t *clone_sdp_payload_attr(sdp_payload_attr_t *attr) { - sdp_payload_attr_t * clone_attr; + sdp_payload_attr_t *clone_attr; int len; char *p; - if (attr == NULL) { + if(attr == NULL) { LM_ERR("arg:NULL\n"); return NULL; } - len = sizeof(sdp_payload_attr_t) + - attr->rtp_payload.len + - attr->rtp_enc.len + - attr->rtp_clock.len + - attr->rtp_params.len + - attr->fmtp_string.len; - clone_attr = (sdp_payload_attr_t*)shm_malloc(len); - if (clone_attr == NULL) { + len = sizeof(sdp_payload_attr_t) + attr->rtp_payload.len + attr->rtp_enc.len + + attr->rtp_clock.len + attr->rtp_params.len + attr->fmtp_string.len; + clone_attr = (sdp_payload_attr_t *)shm_malloc(len); + if(clone_attr == NULL) { SHM_MEM_ERROR; return NULL; } - memset( clone_attr, 0, len); - p = (char*)(clone_attr+1); + memset(clone_attr, 0, len); + p = (char *)(clone_attr + 1); clone_attr->payload_num = attr->payload_num; - if (attr->rtp_payload.len) { + if(attr->rtp_payload.len) { clone_attr->rtp_payload.s = p; clone_attr->rtp_payload.len = attr->rtp_payload.len; - memcpy( p, attr->rtp_payload.s, attr->rtp_payload.len); + memcpy(p, attr->rtp_payload.s, attr->rtp_payload.len); p += attr->rtp_payload.len; } - if (attr->rtp_enc.len) { + if(attr->rtp_enc.len) { clone_attr->rtp_enc.s = p; clone_attr->rtp_enc.len = attr->rtp_enc.len; - memcpy( p, attr->rtp_enc.s, attr->rtp_enc.len); + memcpy(p, attr->rtp_enc.s, attr->rtp_enc.len); p += attr->rtp_enc.len; } - if (attr->rtp_clock.len) { + if(attr->rtp_clock.len) { clone_attr->rtp_clock.s = p; clone_attr->rtp_clock.len = attr->rtp_clock.len; - memcpy( p, attr->rtp_clock.s, attr->rtp_clock.len); + memcpy(p, attr->rtp_clock.s, attr->rtp_clock.len); p += attr->rtp_clock.len; } - if (attr->rtp_params.len) { + if(attr->rtp_params.len) { clone_attr->rtp_params.s = p; clone_attr->rtp_params.len = attr->rtp_params.len; - memcpy( p, attr->rtp_params.s, attr->rtp_params.len); + memcpy(p, attr->rtp_params.s, attr->rtp_params.len); p += attr->rtp_params.len; } - if (attr->fmtp_string.len) { + if(attr->fmtp_string.len) { clone_attr->fmtp_string.s = p; clone_attr->fmtp_string.len = attr->fmtp_string.len; - memcpy( p, attr->fmtp_string.s, attr->fmtp_string.len); + memcpy(p, attr->fmtp_string.s, attr->fmtp_string.len); p += attr->fmtp_string.len; } return clone_attr; } -sdp_ice_attr_t * clone_sdp_ice_attr(sdp_ice_attr_t *ice_attr) +sdp_ice_attr_t *clone_sdp_ice_attr(sdp_ice_attr_t *ice_attr) { - sdp_ice_attr_t * clone_ice_attr; + sdp_ice_attr_t *clone_ice_attr; int len; char *p; - if (ice_attr == NULL) return NULL; + if(ice_attr == NULL) + return NULL; - len = sizeof(sdp_ice_attr_t) + - ice_attr->foundation.len + - ice_attr->transport.len + - ice_attr->connection_addr.len + - ice_attr->port.len + - ice_attr->candidate_type.len; + len = sizeof(sdp_ice_attr_t) + ice_attr->foundation.len + + ice_attr->transport.len + ice_attr->connection_addr.len + + ice_attr->port.len + ice_attr->candidate_type.len; - clone_ice_attr = (sdp_ice_attr_t*)shm_malloc(len); - if (clone_ice_attr == NULL) { + clone_ice_attr = (sdp_ice_attr_t *)shm_malloc(len); + if(clone_ice_attr == NULL) { SHM_MEM_ERROR; return NULL; } memset(clone_ice_attr, 0, len); - p = (char*)(clone_ice_attr); /* beginning of the struct */ + p = (char *)(clone_ice_attr); /* beginning of the struct */ /* foundation */ - if (ice_attr->foundation.len) { + if(ice_attr->foundation.len) { clone_ice_attr->foundation.s = p; clone_ice_attr->foundation.len = ice_attr->foundation.len; - memcpy( p, ice_attr->foundation.s, ice_attr->foundation.len); + memcpy(p, ice_attr->foundation.s, ice_attr->foundation.len); p += ice_attr->foundation.len; } @@ -1160,34 +1238,34 @@ sdp_ice_attr_t * clone_sdp_ice_attr(sdp_ice_attr_t *ice_attr) clone_ice_attr->component_id = ice_attr->component_id; /* transport */ - if (ice_attr->transport.len) { + if(ice_attr->transport.len) { clone_ice_attr->transport.s = p; clone_ice_attr->transport.len = ice_attr->transport.len; - memcpy( p, ice_attr->transport.s, ice_attr->transport.len); + memcpy(p, ice_attr->transport.s, ice_attr->transport.len); p += ice_attr->transport.len; } /* connection_addr */ - if (ice_attr->connection_addr.len) { + if(ice_attr->connection_addr.len) { clone_ice_attr->connection_addr.s = p; clone_ice_attr->connection_addr.len = ice_attr->connection_addr.len; - memcpy( p, ice_attr->connection_addr.s, ice_attr->connection_addr.len); + memcpy(p, ice_attr->connection_addr.s, ice_attr->connection_addr.len); p += ice_attr->connection_addr.len; } /* port */ - if (ice_attr->port.len) { + if(ice_attr->port.len) { clone_ice_attr->port.s = p; clone_ice_attr->port.len = ice_attr->port.len; - memcpy( p, ice_attr->port.s, ice_attr->port.len); + memcpy(p, ice_attr->port.s, ice_attr->port.len); p += ice_attr->port.len; } /* candidate_type */ - if (ice_attr->candidate_type.len) { + if(ice_attr->candidate_type.len) { clone_ice_attr->candidate_type.s = p; clone_ice_attr->candidate_type.len = ice_attr->candidate_type.len; - memcpy( p, ice_attr->candidate_type.s, ice_attr->candidate_type.len); + memcpy(p, ice_attr->candidate_type.s, ice_attr->candidate_type.len); p += ice_attr->candidate_type.len; } @@ -1197,34 +1275,35 @@ sdp_ice_attr_t * clone_sdp_ice_attr(sdp_ice_attr_t *ice_attr) return clone_ice_attr; } -sdp_ice_opt_t * clone_sdp_opt_attr(sdp_ice_opt_t *ice_opt) +sdp_ice_opt_t *clone_sdp_opt_attr(sdp_ice_opt_t *ice_opt) { - sdp_ice_opt_t * clone_ice_opt; + sdp_ice_opt_t *clone_ice_opt; int len; char *p; - if (ice_opt == NULL) return NULL; + if(ice_opt == NULL) + return NULL; len = sizeof(sdp_ice_opt_t) + ice_opt->option.len; - clone_ice_opt = (sdp_ice_opt_t*)shm_malloc(len); - if (clone_ice_opt == NULL) { + clone_ice_opt = (sdp_ice_opt_t *)shm_malloc(len); + if(clone_ice_opt == NULL) { SHM_MEM_ERROR; return NULL; } memset(clone_ice_opt, 0, len); - p = (char*)(clone_ice_opt); /* beginning of the struct */ + p = (char *)(clone_ice_opt); /* beginning of the struct */ /* ice option */ - if (ice_opt->option.len) { + if(ice_opt->option.len) { clone_ice_opt->option.s = p; clone_ice_opt->option.len = ice_opt->option.len; - memcpy( p, ice_opt->option.s, ice_opt->option.len); + memcpy(p, ice_opt->option.s, ice_opt->option.len); } return clone_ice_opt; } -sdp_stream_cell_t * clone_sdp_stream_cell(sdp_stream_cell_t *stream) +sdp_stream_cell_t *clone_sdp_stream_cell(sdp_stream_cell_t *stream) { sdp_stream_cell_t *clone_stream; sdp_payload_attr_t *clone_payload_attr, *payload_attr; @@ -1234,38 +1313,30 @@ sdp_stream_cell_t * clone_sdp_stream_cell(sdp_stream_cell_t *stream) int len, i; char *p; - if (stream == NULL) { + if(stream == NULL) { LM_ERR("arg:NULL\n"); return NULL; } /* NOTE: we are not cloning RFC4975 attributes */ - len = sizeof(sdp_stream_cell_t) + - stream->ip_addr.len + - stream->media.len + - stream->port.len + - stream->transport.len + - stream->sendrecv_mode.len + - stream->ptime.len + - stream->payloads.len + - stream->bw_type.len + - stream->bw_width.len + - stream->rtcp_port.len + - stream->raw_stream.len + - stream->remote_candidates.len; - - clone_stream = (sdp_stream_cell_t*)shm_malloc(len); - if (clone_stream == NULL) { + len = sizeof(sdp_stream_cell_t) + stream->ip_addr.len + stream->media.len + + stream->port.len + stream->transport.len + stream->sendrecv_mode.len + + stream->ptime.len + stream->payloads.len + stream->bw_type.len + + stream->bw_width.len + stream->rtcp_port.len + + stream->raw_stream.len + stream->remote_candidates.len; + + clone_stream = (sdp_stream_cell_t *)shm_malloc(len); + if(clone_stream == NULL) { SHM_MEM_ERROR; return NULL; } - memset( clone_stream, 0, len); - p = (char*)(clone_stream+1); + memset(clone_stream, 0, len); + p = (char *)(clone_stream + 1); payload_attr = NULL; - for (i=0;ipayloads_num;i++) { + for(i = 0; i < stream->payloads_num; i++) { clone_payload_attr = clone_sdp_payload_attr(stream->p_payload_attr[i]); - if (clone_payload_attr == NULL) { + if(clone_payload_attr == NULL) { LM_ERR("unable to clone attributes for payload[%d]\n", i); goto error; } @@ -1276,20 +1347,20 @@ sdp_stream_cell_t * clone_sdp_stream_cell(sdp_stream_cell_t *stream) clone_stream->payload_attr = payload_attr; clone_stream->payloads_num = stream->payloads_num; - if (clone_stream->payloads_num) { - if (NULL == init_p_payload_attr(clone_stream, SDP_USE_SHM_MEM)) { + if(clone_stream->payloads_num) { + if(NULL == init_p_payload_attr(clone_stream, SDP_USE_SHM_MEM)) { goto error; } } /* clone ICE candidate attributes */ - if (stream->ice_attrs_num) { + if(stream->ice_attrs_num) { tmp_ice_attr = stream->ice_attr; clone_ice_attr = clone_sdp_ice_attr(tmp_ice_attr); - if (clone_ice_attr == NULL) { + if(clone_ice_attr == NULL) { LM_ERR("unable to clone ice attributes for component[%d]\n", - tmp_ice_attr->component_id); + tmp_ice_attr->component_id); goto error; } clone_stream->ice_attr = clone_ice_attr; @@ -1298,12 +1369,12 @@ sdp_stream_cell_t * clone_sdp_stream_cell(sdp_stream_cell_t *stream) clone_ice_attr->next = NULL; - for (i=1; iice_attrs_num; i++) { + for(i = 1; i < stream->ice_attrs_num; i++) { clone_ice_attr = clone_sdp_ice_attr(tmp_ice_attr); - if (clone_ice_attr == NULL) { + if(clone_ice_attr == NULL) { LM_ERR("unable to clone ice attributes for component[%d]\n", - tmp_ice_attr->component_id); + tmp_ice_attr->component_id); goto error; } prev_ice_attr->next = clone_ice_attr; @@ -1314,11 +1385,11 @@ sdp_stream_cell_t * clone_sdp_stream_cell(sdp_stream_cell_t *stream) clone_stream->ice_attrs_num = stream->ice_attrs_num; /* clone media level ICE options */ - if (stream->ice_opt_num) { + if(stream->ice_opt_num) { tmp_ice_opt = stream->ice_opt; clone_ice_opt = clone_sdp_opt_attr(tmp_ice_opt); - if (clone_ice_opt == NULL) { + if(clone_ice_opt == NULL) { LM_ERR("unable to clone ice option for option[%d]\n", i); goto error; } @@ -1328,10 +1399,10 @@ sdp_stream_cell_t * clone_sdp_stream_cell(sdp_stream_cell_t *stream) clone_ice_opt->next = NULL; - for (i=1; iice_opt_num; i++) { + for(i = 1; i < stream->ice_opt_num; i++) { clone_ice_opt = clone_sdp_opt_attr(tmp_ice_opt); - if (clone_ice_opt == NULL) { + if(clone_ice_opt == NULL) { LM_ERR("unable to clone ice option for option[%d]\n", i); goto error; } @@ -1345,73 +1416,73 @@ sdp_stream_cell_t * clone_sdp_stream_cell(sdp_stream_cell_t *stream) clone_stream->stream_num = stream->stream_num; clone_stream->pf = stream->pf; - if (stream->ip_addr.len) { + if(stream->ip_addr.len) { clone_stream->ip_addr.s = p; clone_stream->ip_addr.len = stream->ip_addr.len; - memcpy( p, stream->ip_addr.s, stream->ip_addr.len); + memcpy(p, stream->ip_addr.s, stream->ip_addr.len); p += stream->ip_addr.len; } clone_stream->is_rtp = stream->is_rtp; - if (stream->media.len) { + if(stream->media.len) { clone_stream->media.s = p; clone_stream->media.len = stream->media.len; - memcpy( p, stream->media.s, stream->media.len); + memcpy(p, stream->media.s, stream->media.len); p += stream->media.len; } - if (stream->port.len) { + if(stream->port.len) { clone_stream->port.s = p; clone_stream->port.len = stream->port.len; - memcpy( p, stream->port.s, stream->port.len); + memcpy(p, stream->port.s, stream->port.len); p += stream->port.len; } - if (stream->transport.len) { + if(stream->transport.len) { clone_stream->transport.s = p; clone_stream->transport.len = stream->transport.len; - memcpy( p, stream->transport.s, stream->transport.len); + memcpy(p, stream->transport.s, stream->transport.len); p += stream->transport.len; } - if (stream->sendrecv_mode.len) { + if(stream->sendrecv_mode.len) { clone_stream->sendrecv_mode.s = p; clone_stream->sendrecv_mode.len = stream->sendrecv_mode.len; - memcpy( p, stream->sendrecv_mode.s, stream->sendrecv_mode.len); + memcpy(p, stream->sendrecv_mode.s, stream->sendrecv_mode.len); p += stream->sendrecv_mode.len; } - if (stream->ptime.len) { + if(stream->ptime.len) { clone_stream->ptime.s = p; clone_stream->ptime.len = stream->ptime.len; - memcpy( p, stream->ptime.s, stream->ptime.len); + memcpy(p, stream->ptime.s, stream->ptime.len); p += stream->ptime.len; } - if (stream->payloads.len) { + if(stream->payloads.len) { clone_stream->payloads.s = p; clone_stream->payloads.len = stream->payloads.len; - memcpy( p, stream->payloads.s, stream->payloads.len); + memcpy(p, stream->payloads.s, stream->payloads.len); p += stream->payloads.len; } - if (stream->bw_type.len) { + if(stream->bw_type.len) { clone_stream->bw_type.s = p; clone_stream->bw_type.len = stream->bw_type.len; p += stream->bw_type.len; } - if (stream->bw_width.len) { + if(stream->bw_width.len) { clone_stream->bw_width.s = p; clone_stream->bw_width.len = stream->bw_width.len; p += stream->bw_width.len; } - if (stream->rtcp_port.len) { + if(stream->rtcp_port.len) { clone_stream->rtcp_port.s = p; clone_stream->rtcp_port.len = stream->rtcp_port.len; - memcpy( p, stream->rtcp_port.s, stream->rtcp_port.len); + memcpy(p, stream->rtcp_port.s, stream->rtcp_port.len); p += stream->rtcp_port.len; } @@ -1428,50 +1499,46 @@ sdp_stream_cell_t * clone_sdp_stream_cell(sdp_stream_cell_t *stream) return NULL; } -sdp_session_cell_t * clone_sdp_session_cell(sdp_session_cell_t *session) +sdp_session_cell_t *clone_sdp_session_cell(sdp_session_cell_t *session) { sdp_session_cell_t *clone_session; sdp_stream_cell_t *clone_stream, *prev_clone_stream, *stream; int len, i; char *p; - if (session == NULL) { + if(session == NULL) { LM_ERR("arg:NULL\n"); return NULL; } - len = sizeof(sdp_session_cell_t) + - session->cnt_disp.len + - session->ip_addr.len + - session->o_ip_addr.len + - session->bw_type.len + - session->bw_width.len + - session->sendrecv_mode.len; + len = sizeof(sdp_session_cell_t) + session->cnt_disp.len + + session->ip_addr.len + session->o_ip_addr.len + session->bw_type.len + + session->bw_width.len + session->sendrecv_mode.len; - clone_session = (sdp_session_cell_t*)shm_malloc(len); - if (clone_session == NULL) { + clone_session = (sdp_session_cell_t *)shm_malloc(len); + if(clone_session == NULL) { SHM_MEM_ERROR; return NULL; } - memset( clone_session, 0, len); - p = (char*)(clone_session+1); + memset(clone_session, 0, len); + p = (char *)(clone_session + 1); - if (session->streams_num) { - stream=session->streams; - clone_stream=clone_sdp_stream_cell(stream); - if (clone_stream==NULL) { + if(session->streams_num) { + stream = session->streams; + clone_stream = clone_sdp_stream_cell(stream); + if(clone_stream == NULL) { goto error; } - clone_session->streams=clone_stream; - prev_clone_stream=clone_stream; - stream=stream->next; - for (i=1;istreams_num;i++) { - clone_stream=clone_sdp_stream_cell(stream); - if (clone_stream==NULL) { + clone_session->streams = clone_stream; + prev_clone_stream = clone_stream; + stream = stream->next; + for(i = 1; i < session->streams_num; i++) { + clone_stream = clone_sdp_stream_cell(stream); + if(clone_stream == NULL) { goto error; } - prev_clone_stream->next=clone_stream; - prev_clone_stream=clone_stream; - stream=stream->next; + prev_clone_stream->next = clone_stream; + prev_clone_stream = clone_stream; + stream = stream->next; } } @@ -1480,38 +1547,38 @@ sdp_session_cell_t * clone_sdp_session_cell(sdp_session_cell_t *session) clone_session->o_pf = session->o_pf; clone_session->streams_num = session->streams_num; - if (session->cnt_disp.len) { + if(session->cnt_disp.len) { clone_session->cnt_disp.s = p; clone_session->cnt_disp.len = session->cnt_disp.len; - memcpy( p, session->cnt_disp.s, session->cnt_disp.len); + memcpy(p, session->cnt_disp.s, session->cnt_disp.len); p += session->cnt_disp.len; } - if (session->ip_addr.len) { + if(session->ip_addr.len) { clone_session->ip_addr.s = p; clone_session->ip_addr.len = session->ip_addr.len; - memcpy( p, session->ip_addr.s, session->ip_addr.len); + memcpy(p, session->ip_addr.s, session->ip_addr.len); p += session->ip_addr.len; } - if (session->o_ip_addr.len) { + if(session->o_ip_addr.len) { clone_session->o_ip_addr.s = p; clone_session->o_ip_addr.len = session->o_ip_addr.len; - memcpy( p, session->o_ip_addr.s, session->o_ip_addr.len); + memcpy(p, session->o_ip_addr.s, session->o_ip_addr.len); p += session->o_ip_addr.len; } - if (session->bw_type.len) { + if(session->bw_type.len) { clone_session->bw_type.s = p; clone_session->bw_type.len = session->bw_type.len; - memcpy( p, session->bw_type.s, session->bw_type.len); + memcpy(p, session->bw_type.s, session->bw_type.len); p += session->bw_type.len; } - if (session->bw_width.len) { + if(session->bw_width.len) { clone_session->bw_width.s = p; clone_session->bw_width.len = session->bw_width.len; - memcpy( p, session->bw_width.s, session->bw_width.len); + memcpy(p, session->bw_width.s, session->bw_width.len); p += session->bw_width.len; } @@ -1521,53 +1588,53 @@ sdp_session_cell_t * clone_sdp_session_cell(sdp_session_cell_t *session) return NULL; } -sdp_info_t * clone_sdp_info(struct sip_msg* _m) +sdp_info_t *clone_sdp_info(struct sip_msg *_m) { - sdp_info_t *clone_sdp_info, *sdp_info=(sdp_info_t*)_m->body; + sdp_info_t *clone_sdp_info, *sdp_info = (sdp_info_t *)_m->body; sdp_session_cell_t *clone_session, *prev_clone_session, *session; int i, len; - if (sdp_info==NULL) { + if(sdp_info == NULL) { LM_ERR("no sdp to clone\n"); return NULL; } - if (sdp_info->type != MSG_BODY_SDP) { + if(sdp_info->type != MSG_BODY_SDP) { LM_ERR("Unsupported body type\n"); return NULL; } - if (sdp_info->sessions_num == 0) { + if(sdp_info->sessions_num == 0) { LM_ERR("no sessions to clone\n"); return NULL; } len = sizeof(sdp_info_t); - clone_sdp_info = (sdp_info_t*)shm_malloc(len); - if (clone_sdp_info == NULL) { + clone_sdp_info = (sdp_info_t *)shm_malloc(len); + if(clone_sdp_info == NULL) { SHM_MEM_ERROR; return NULL; } LM_DBG("clone_sdp_info: %p\n", clone_sdp_info); - memset( clone_sdp_info, 0, len); + memset(clone_sdp_info, 0, len); LM_DBG("we have %d sessions\n", sdp_info->sessions_num); clone_sdp_info->sessions_num = sdp_info->sessions_num; clone_sdp_info->streams_num = sdp_info->streams_num; - session=sdp_info->sessions; - clone_session=clone_sdp_session_cell(session); - if (clone_session==NULL) { + session = sdp_info->sessions; + clone_session = clone_sdp_session_cell(session); + if(clone_session == NULL) { goto error; } - clone_sdp_info->sessions=clone_session; - prev_clone_session=clone_session; - session=session->next; - for (i=1;isessions_num;i++) { - clone_session=clone_sdp_session_cell(session); - if (clone_session==NULL) { + clone_sdp_info->sessions = clone_session; + prev_clone_session = clone_session; + session = session->next; + for(i = 1; i < sdp_info->sessions_num; i++) { + clone_session = clone_sdp_session_cell(session); + if(clone_session == NULL) { goto error; } - prev_clone_session->next=clone_session; - prev_clone_session=clone_session; - session=session->next; + prev_clone_session->next = clone_session; + prev_clone_session = clone_session; + session = session->next; } return clone_sdp_info; diff --git a/src/core/parser/sdp/sdp.h b/src/core/parser/sdp/sdp.h index 417cb2b4c01..52273576323 100644 --- a/src/core/parser/sdp/sdp.h +++ b/src/core/parser/sdp/sdp.h @@ -6,13 +6,13 @@ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE FREEBSD PROJECT ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO @@ -32,7 +32,7 @@ #include "../msg_parser.h" -#define NO_HOLD 0 +#define NO_HOLD 0 #define RFC2543_HOLD 1 #define RFC3264_HOLD 2 @@ -46,7 +46,8 @@ #define ICE_OPT_TRICKLE_STR "trickle" #define ICE_OPT_TRICKLE_LEN 7 -typedef struct sdp_payload_attr { +typedef struct sdp_payload_attr +{ struct sdp_payload_attr *next; int payload_num; /**< payload index inside stream */ str rtp_payload; @@ -56,12 +57,14 @@ typedef struct sdp_payload_attr { str fmtp_string; } sdp_payload_attr_t; -typedef struct sdp_ice_opt { +typedef struct sdp_ice_opt +{ struct sdp_ice_opt *next; str option; /* for e.g. 'trickle', 'rtp+ecn' */ } sdp_ice_opt_t; -typedef struct sdp_ice_attr { +typedef struct sdp_ice_attr +{ struct sdp_ice_attr *next; str foundation; unsigned int component_id; @@ -69,16 +72,17 @@ typedef struct sdp_ice_attr { str connection_addr; str port; str candidate_type; - int candidateType; /* ICE_HOST/ICE_SRFLX/ICE_PRFLX/ICE_RELAY/ICE_UNKNOWN */ + int candidateType; /* ICE_HOST/ICE_SRFLX/ICE_PRFLX/ICE_RELAY/ICE_UNKNOWN */ } sdp_ice_attr_t; -typedef struct sdp_stream_cell { +typedef struct sdp_stream_cell +{ struct sdp_stream_cell *next; /* c=
*/ - int pf; /**< connection address family: AF_INET/AF_INET6 */ - str ip_addr; /**< connection address */ + int pf; /**< connection address family: AF_INET/AF_INET6 */ + str ip_addr; /**< connection address */ int stream_num; /**< stream index inside a session */ - int is_rtp; /**< flag indicating if this is an RTP stream */ + int is_rtp; /**< flag indicating if this is an RTP stream */ int is_on_hold; /**< flag indicating if this stream is on hold */ /* m= */ str media; @@ -87,61 +91,66 @@ typedef struct sdp_stream_cell { str sendrecv_mode; str ptime; str payloads; - int payloads_num; /**< number of payloads inside a stream */ + int payloads_num; /**< number of payloads inside a stream */ /* b=: */ - str bw_type; /**< alphanumeric modifier giving the meaning of the figure: + str bw_type; /**< alphanumeric modifier giving the meaning of the figure: CT - conference total; AS - application specific */ - str bw_width; /**< The is interpreted as kilobits per second by default */ + str bw_width; /**< The is interpreted as kilobits per second by default */ /* RFC3605: Real Time Control Protocol (RTCP) attribute in Session Description Protocol (SDP) */ /* a=rtcp: port [nettype space addrtype space connection-address] CRLF */ - str rtcp_port; /**< RFC3605: rtcp attribute */ - str path; /**< RFC4975: path attribute */ - str max_size; /**< RFC4975: max-size attribute */ - str accept_types; /**< RFC4975: accept-types attribute */ - str accept_wrapped_types; /**< RFC4975: accept-wrapped-types attribute */ - str raw_stream; /**< fast access to raw stream string */ - struct sdp_payload_attr **p_payload_attr; /**< fast access pointers to payloads */ + str rtcp_port; /**< RFC3605: rtcp attribute */ + str path; /**< RFC4975: path attribute */ + str max_size; /**< RFC4975: max-size attribute */ + str accept_types; /**< RFC4975: accept-types attribute */ + str accept_wrapped_types; /**< RFC4975: accept-wrapped-types attribute */ + str raw_stream; /**< fast access to raw stream string */ + struct sdp_payload_attr * + *p_payload_attr; /**< fast access pointers to payloads */ struct sdp_payload_attr *payload_attr; - int ice_attrs_num; /* number of candidate ICE attrs inside a stream */ - sdp_ice_attr_t *ice_attr; /* add fast access pointers to ice candidate attributes */ - int ice_opt_num; /* number of media level ICE options inside the stream */ - sdp_ice_opt_t *ice_opt; /* add fast access pointers to media level ICE options */ - str remote_candidates; /* ICE a:remote-candidates */ + int ice_attrs_num; /* number of candidate ICE attrs inside a stream */ + sdp_ice_attr_t * + ice_attr; /* add fast access pointers to ice candidate attributes */ + int ice_opt_num; /* number of media level ICE options inside the stream */ + sdp_ice_opt_t + *ice_opt; /* add fast access pointers to media level ICE options */ + str remote_candidates; /* ICE a:remote-candidates */ } sdp_stream_cell_t; -typedef struct sdp_session_cell { +typedef struct sdp_session_cell +{ struct sdp_session_cell *next; - int session_num; /**< session index inside sdp */ - str cnt_disp; /**< the Content-Disposition header (for Content-Type:multipart/mixed) */ + int session_num; /**< session index inside sdp */ + str cnt_disp; /**< the Content-Disposition header (for Content-Type:multipart/mixed) */ /* c=
*/ - int pf; /**< connection address family: AF_INET/AF_INET6 */ - str ip_addr; /**< connection address */ + int pf; /**< connection address family: AF_INET/AF_INET6 */ + str ip_addr; /**< connection address */ /* o=
*/ str o_sess_version; /** < origin session version number */ - int o_pf; /**< origin address family: AF_INET/AF_INET6 */ - str o_ip_addr; /**< origin address */ + int o_pf; /**< origin address family: AF_INET/AF_INET6 */ + str o_ip_addr; /**< origin address */ /* b=: */ - str bw_type; /**< alphanumeric modifier giving the meaning of the figure: + str bw_type; /**< alphanumeric modifier giving the meaning of the figure: CT - conference total; AS - application specific */ - str bw_width; /**< The is interpreted as kilobits per second by default */ - int streams_num; /**< number of streams inside a session */ + str bw_width; /**< The is interpreted as kilobits per second by default */ + int streams_num; /**< number of streams inside a session */ str sendrecv_mode; int is_on_hold; /**< flag indicating if this session is on hold */ - struct sdp_stream_cell* streams; + struct sdp_stream_cell *streams; } sdp_session_cell_t; /** * Here we hold the head of the parsed sdp structure */ -typedef struct sdp_info { +typedef struct sdp_info +{ msg_body_type_t type; free_msg_body_f free; - str text; /**< link to start of sdp and its length */ + str text; /**< link to start of sdp and its length */ int sessions_num; /**< number of SDP sessions */ int streams_num; /**< total number of streams for all SDP sessions */ - str raw_sdp; /* Pointer to the Raw SDP (Might be embedded in multipart body) */ + str raw_sdp; /* Pointer to the Raw SDP (Might be embedded in multipart body) */ struct sdp_session_cell *sessions; } sdp_info_t; @@ -149,50 +158,53 @@ typedef struct sdp_info { /* * Parse SDP. */ -int parse_sdp(struct sip_msg* _m); +int parse_sdp(struct sip_msg *_m); /** * Get number of sessions in existing SDP. */ -int get_sdp_session_num(struct sip_msg* _m); +int get_sdp_session_num(struct sip_msg *_m); /** * Get number of streams in existing SDP. */ -int get_sdp_stream_num(struct sip_msg* _m); +int get_sdp_stream_num(struct sip_msg *_m); /** * Get a session for the current sip msg based on position inside SDP. */ -sdp_session_cell_t* get_sdp_session(struct sip_msg* _m, int session_num); +sdp_session_cell_t *get_sdp_session(struct sip_msg *_m, int session_num); /** * Get a session for the given sdp based on position inside SDP. */ -sdp_session_cell_t* get_sdp_session_sdp(struct sdp_info* sdp, int session_num); +sdp_session_cell_t *get_sdp_session_sdp(struct sdp_info *sdp, int session_num); /** * Get a stream for the current sip msg based on positions inside SDP. */ -sdp_stream_cell_t* get_sdp_stream(struct sip_msg* _m, int session_num, int stream_num); +sdp_stream_cell_t *get_sdp_stream( + struct sip_msg *_m, int session_num, int stream_num); /** * Get a stream for the given sdp based on positions inside SDP. */ -sdp_stream_cell_t* get_sdp_stream_sdp(struct sdp_info* sdp, int session_num, int stream_num); +sdp_stream_cell_t *get_sdp_stream_sdp( + struct sdp_info *sdp, int session_num, int stream_num); /** * Get a payload from a stream based on payload. */ -sdp_payload_attr_t* get_sdp_payload4payload(sdp_stream_cell_t *stream, str *rtp_payload); +sdp_payload_attr_t *get_sdp_payload4payload( + sdp_stream_cell_t *stream, str *rtp_payload); /** * Get a payload from a stream based on position. */ -sdp_payload_attr_t* get_sdp_payload4index(sdp_stream_cell_t *stream, int index); +sdp_payload_attr_t *get_sdp_payload4index(sdp_stream_cell_t *stream, int index); /** * Free all memory associated with parsed structure. * * Note: this will free up the parsed sdp structure (form PKG_MEM). */ -void free_sdp(sdp_info_t** _sdp); +void free_sdp(sdp_info_t **_sdp); /** @@ -200,13 +212,13 @@ void free_sdp(sdp_info_t** _sdp); * * Note: only for debug purposes. */ -void print_sdp(sdp_info_t* sdp, int log_level); +void print_sdp(sdp_info_t *sdp, int log_level); /** * Print the content of the given sdp_session structure. * * Note: only for debug purposes. */ -void print_sdp_session(sdp_session_cell_t* sdp_session, int log_level); +void print_sdp_session(sdp_session_cell_t *sdp_session, int log_level); /** * Print the content of the given sdp_stream structure. * diff --git a/src/core/parser/sdp/sdp_cloner.h b/src/core/parser/sdp/sdp_cloner.h index 620d8af4691..47cdca1af1d 100644 --- a/src/core/parser/sdp/sdp_cloner.h +++ b/src/core/parser/sdp/sdp_cloner.h @@ -5,13 +5,13 @@ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE FREEBSD PROJECT ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO @@ -35,7 +35,7 @@ /** * Clone the given sdp_session_cell structure. */ -sdp_session_cell_t * clone_sdp_session_cell(sdp_session_cell_t *session); +sdp_session_cell_t *clone_sdp_session_cell(sdp_session_cell_t *session); /** * Free all memory associated with the cloned sdp_session structure. * @@ -48,12 +48,12 @@ void free_cloned_sdp_session(sdp_session_cell_t *_session); * * Note: all cloned structer will be in SHM_MEM. */ -sdp_info_t* clone_sdp_info(struct sip_msg* _m); +sdp_info_t *clone_sdp_info(struct sip_msg *_m); /** * Free all memory associated with the cloned sdp_info structure. * * Note: this will free up the parsed sdp structure (form SHM_MEM). */ -void free_cloned_sdp(sdp_info_t* sdp); +void free_cloned_sdp(sdp_info_t *sdp); #endif /* SDP_H */ diff --git a/src/core/parser/sdp/sdp_helpr_funcs.c b/src/core/parser/sdp/sdp_helpr_funcs.c index ff19a22c839..b15ddeaa4bd 100644 --- a/src/core/parser/sdp/sdp_helpr_funcs.c +++ b/src/core/parser/sdp/sdp_helpr_funcs.c @@ -6,13 +6,13 @@ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE FREEBSD PROJECT ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO @@ -35,97 +35,94 @@ #include "sdp.h" -static struct { +static struct +{ const char *s; int len; int is_rtp; -} sup_ptypes[] = { - {.s = "rtp/avp", .len = 7, .is_rtp = 1}, - {.s = "udptl", .len = 5, .is_rtp = 0}, - {.s = "rtp/avpf", .len = 8, .is_rtp = 1}, - {.s = "rtp/savp", .len = 8, .is_rtp = 1}, - {.s = "rtp/savpf", .len = 9, .is_rtp = 1}, - {.s = "udp", .len = 3, .is_rtp = 0}, - {.s = "udp/bfcp", .len = 8, .is_rtp = 0}, - {.s = NULL, .len = 0, .is_rtp = 0} -}; - - -#define READ(val) \ - ((unsigned int)(*(val + 0)) \ - + ((unsigned int)(*(val + 1)) << 8) \ - + ((unsigned int)(*(val + 2)) << 16) \ - + ((unsigned int)(*(val + 3)) << 24)) -#define advance(_ptr,_n,_str,_error) \ - do{\ - if ((_ptr)+(_n)>(_str).s+(_str).len)\ - goto _error;\ - (_ptr) = (_ptr) + (_n);\ - }while(0); -#define one_of_16( _x , _t ) \ - (_x==_t[0]||_x==_t[15]||_x==_t[8]||_x==_t[2]||_x==_t[3]||_x==_t[4]\ - ||_x==_t[5]||_x==_t[6]||_x==_t[7]||_x==_t[1]||_x==_t[9]||_x==_t[10]\ - ||_x==_t[11]||_x==_t[12]||_x==_t[13]||_x==_t[14]) -#define one_of_8( _x , _t ) \ - (_x==_t[0]||_x==_t[7]||_x==_t[1]||_x==_t[2]||_x==_t[3]||_x==_t[4]\ - ||_x==_t[5]||_x==_t[6]) - -int get_mixed_part_delimiter(str* body, str *mp_delimiter) +} sup_ptypes[] = {{.s = "rtp/avp", .len = 7, .is_rtp = 1}, + {.s = "udptl", .len = 5, .is_rtp = 0}, + {.s = "rtp/avpf", .len = 8, .is_rtp = 1}, + {.s = "rtp/savp", .len = 8, .is_rtp = 1}, + {.s = "rtp/savpf", .len = 9, .is_rtp = 1}, + {.s = "udp", .len = 3, .is_rtp = 0}, + {.s = "udp/bfcp", .len = 8, .is_rtp = 0}, + {.s = NULL, .len = 0, .is_rtp = 0}}; + + +#define READ(val) \ + ((unsigned int)(*(val + 0)) + ((unsigned int)(*(val + 1)) << 8) \ + + ((unsigned int)(*(val + 2)) << 16) \ + + ((unsigned int)(*(val + 3)) << 24)) +#define advance(_ptr, _n, _str, _error) \ + do { \ + if((_ptr) + (_n) > (_str).s + (_str).len) \ + goto _error; \ + (_ptr) = (_ptr) + (_n); \ + } while(0); +#define one_of_16(_x, _t) \ + (_x == _t[0] || _x == _t[15] || _x == _t[8] || _x == _t[2] || _x == _t[3] \ + || _x == _t[4] || _x == _t[5] || _x == _t[6] || _x == _t[7] \ + || _x == _t[1] || _x == _t[9] || _x == _t[10] || _x == _t[11] \ + || _x == _t[12] || _x == _t[13] || _x == _t[14]) +#define one_of_8(_x, _t) \ + (_x == _t[0] || _x == _t[7] || _x == _t[1] || _x == _t[2] || _x == _t[3] \ + || _x == _t[4] || _x == _t[5] || _x == _t[6]) + +int get_mixed_part_delimiter(str *body, str *mp_delimiter) { - static unsigned int boun[16] = { - 0x6e756f62,0x4e756f62,0x6e556f62,0x4e556f62, - 0x6e754f62,0x4e754f62,0x6e554f62,0x4e554f62, - 0x6e756f42,0x4e756f42,0x6e556f42,0x4e556f42, - 0x6e754f42,0x4e754f42,0x6e554f42,0x4e554f42}; - static unsigned int dary[16] = { - 0x79726164,0x59726164,0x79526164,0x59526164, - 0x79724164,0x59724164,0x79524164,0x59524164, - 0x79726144,0x59726144,0x79526144,0x59526144, - 0x79724144,0x59724144,0x79524144,0x59524144}; + static unsigned int boun[16] = {0x6e756f62, 0x4e756f62, 0x6e556f62, + 0x4e556f62, 0x6e754f62, 0x4e754f62, 0x6e554f62, 0x4e554f62, + 0x6e756f42, 0x4e756f42, 0x6e556f42, 0x4e556f42, 0x6e754f42, + 0x4e754f42, 0x6e554f42, 0x4e554f42}; + static unsigned int dary[16] = {0x79726164, 0x59726164, 0x79526164, + 0x59526164, 0x79724164, 0x59724164, 0x79524164, 0x59524164, + 0x79726144, 0x59726144, 0x79526144, 0x59526144, 0x79724144, + 0x59724144, 0x79524144, 0x59524144}; str str_type; - unsigned int x; - char *p; + unsigned int x; + char *p; /* LM_DBG("<%.*s>\n",body->len,body->s); */ p = str_type.s = body->s; str_type.len = body->len; - while (*p!=';' && p<(body->s+body->len)) - advance(p,1,str_type,error); + while(*p != ';' && p < (body->s + body->len)) + advance(p, 1, str_type, error); p++; str_type.s = p; str_type.len = body->len - (p - body->s); /* LM_DBG("string to parse: <%.*s>\n",str_type.len,str_type.s); */ /* skip spaces and tabs if any */ - while (*p==' ' || *p=='\t') - advance(p,1,str_type,error); - advance(p,4,str_type,error); - x = READ(p-4); - if (!one_of_16(x,boun)) + while(*p == ' ' || *p == '\t') + advance(p, 1, str_type, error); + advance(p, 4, str_type, error); + x = READ(p - 4); + if(!one_of_16(x, boun)) goto other; - advance(p,4,str_type,error); - x = READ(p-4); - if (!one_of_16(x,dary)) + advance(p, 4, str_type, error); + x = READ(p - 4); + if(!one_of_16(x, dary)) goto other; - + /* skip spaces and tabs if any */ - while (*p==' ' || *p=='\t') - advance(p,1,str_type,error); - if (*p!='=') { + while(*p == ' ' || *p == '\t') + advance(p, 1, str_type, error); + if(*p != '=') { LM_ERR("parse error: no = found after boundary field\n"); goto error; } - advance(p,1,str_type,error); - while ((*p==' ' || *p=='\t') && p+1len = str_type.len - (int)(p-str_type.s); + advance(p, 1, str_type, error); + while((*p == ' ' || *p == '\t') && p + 1 < str_type.s + str_type.len) + advance(p, 1, str_type, error); + mp_delimiter->len = str_type.len - (int)(p - str_type.s); mp_delimiter->s = p; /* check if the boundary value is enclosed in quotes */ - if(*p=='"' || *p=='\'') { - if(mp_delimiter->s[mp_delimiter->len-1]==*p) { - mp_delimiter->s = p+1; + if(*p == '"' || *p == '\'') { + if(mp_delimiter->s[mp_delimiter->len - 1] == *p) { + mp_delimiter->s = p + 1; mp_delimiter->len -= 2; - if(mp_delimiter->len<=0) { + if(mp_delimiter->len <= 0) { LM_ERR("invalid boundary field value\n"); goto error; } @@ -136,26 +133,25 @@ int get_mixed_part_delimiter(str* body, str *mp_delimiter) } return 1; -error: +error: return -1; -other: +other: LM_DBG("'boundary' parsing error\n"); return -1; } - /** * rfc4566: * a=rtpmap: / [/] */ -int extract_rtpmap(str *body, - str *rtpmap_payload, str *rtpmap_encoding, str *rtpmap_clockrate, str *rtpmap_parmas) +int extract_rtpmap(str *body, str *rtpmap_payload, str *rtpmap_encoding, + str *rtpmap_clockrate, str *rtpmap_parmas) { char *cp, *cp1; int len; - if (strncasecmp(body->s, "a=rtpmap:", 9) !=0) { + if(strncasecmp(body->s, "a=rtpmap:", 9) != 0) { /*LM_DBG("We are not pointing to an a=rtpmap: attribute =>`%.*s'\n", body->len, body->s); */ return -1; } @@ -163,15 +159,17 @@ int extract_rtpmap(str *body, cp1 = body->s; rtpmap_payload->s = cp1 + 9; /* skip `a=rtpmap:' */ - rtpmap_payload->len = eat_line(rtpmap_payload->s, body->s + body->len - - rtpmap_payload->s) - rtpmap_payload->s; + rtpmap_payload->len = + eat_line(rtpmap_payload->s, body->s + body->len - rtpmap_payload->s) + - rtpmap_payload->s; trim_len(rtpmap_payload->len, rtpmap_payload->s, *rtpmap_payload); len = rtpmap_payload->len; /* */ - cp = eat_token_end(rtpmap_payload->s, rtpmap_payload->s + rtpmap_payload->len); + cp = eat_token_end( + rtpmap_payload->s, rtpmap_payload->s + rtpmap_payload->len); rtpmap_payload->len = cp - rtpmap_payload->s; - if (rtpmap_payload->len <= 0 || cp == rtpmap_payload->s) { + if(rtpmap_payload->len <= 0 || cp == rtpmap_payload->s) { LM_ERR("no encoding in `a=rtpmap'\n"); return -1; } @@ -179,25 +177,25 @@ int extract_rtpmap(str *body, rtpmap_encoding->s = cp; cp = eat_space_end(rtpmap_encoding->s, rtpmap_encoding->s + len); len -= cp - rtpmap_encoding->s; - if (len <= 0 || cp == rtpmap_encoding->s) { + if(len <= 0 || cp == rtpmap_encoding->s) { LM_ERR("no encoding in `a=rtpmap:'\n"); return -1; } rtpmap_encoding->s = cp; - cp1 = (char*)ser_memmem(cp, "/", len, 1); - if(cp1==NULL) { + cp1 = (char *)ser_memmem(cp, "/", len, 1); + if(cp1 == NULL) { LM_ERR("invalid encoding in `a=rtpmap' at [%.*s]\n", len, cp); return -1; } len -= cp1 - cp; rtpmap_encoding->len = cp1 - cp; - cp = cp1+1; /* skip '/' */ + cp = cp1 + 1; /* skip '/' */ len--; rtpmap_clockrate->s = cp; - cp1 = (char*)ser_memmem(cp, "/", len, 1); - if(cp1==NULL) { + cp1 = (char *)ser_memmem(cp, "/", len, 1); + if(cp1 == NULL) { /* no encoding parameters */ rtpmap_clockrate->len = len; rtpmap_parmas->s = NULL; @@ -206,17 +204,17 @@ int extract_rtpmap(str *body, } rtpmap_clockrate->len = cp1 - cp; len -= cp1 - cp; - rtpmap_parmas->s = cp1 + 1; /* skip '/' */ + rtpmap_parmas->s = cp1 + 1; /* skip '/' */ rtpmap_parmas->len = len - 1; return 0; } -int extract_fmtp( str *body, str *fmtp_payload, str *fmtp_string ) +int extract_fmtp(str *body, str *fmtp_payload, str *fmtp_string) { char *cp, *cp1; int len; - if (strncasecmp(body->s, "a=fmtp:", 7) !=0) { + if(strncasecmp(body->s, "a=fmtp:", 7) != 0) { /*LM_DBG("We are not pointing to an a=fmtp: attribute =>`%.*s'\n", body->len, body->s); */ return -1; } @@ -224,15 +222,16 @@ int extract_fmtp( str *body, str *fmtp_payload, str *fmtp_string ) cp1 = body->s; fmtp_payload->s = cp1 + 7; /* skip `a=fmtp:' */ - fmtp_payload->len = eat_line(fmtp_payload->s, body->s + body->len - - fmtp_payload->s) - fmtp_payload->s; + fmtp_payload->len = + eat_line(fmtp_payload->s, body->s + body->len - fmtp_payload->s) + - fmtp_payload->s; trim_len(fmtp_payload->len, fmtp_payload->s, *fmtp_payload); len = fmtp_payload->len; /* */ cp = eat_token_end(fmtp_payload->s, fmtp_payload->s + fmtp_payload->len); fmtp_payload->len = cp - fmtp_payload->s; - if (fmtp_payload->len <= 0 || cp == fmtp_payload->s) { + if(fmtp_payload->len <= 0 || cp == fmtp_payload->s) { LM_ERR("no encoding in `a=fmtp:'\n"); return -1; } @@ -240,15 +239,16 @@ int extract_fmtp( str *body, str *fmtp_payload, str *fmtp_string ) fmtp_string->s = cp; cp = eat_space_end(fmtp_string->s, fmtp_string->s + len); len -= cp - fmtp_string->s; - if (len <= 0 || cp == fmtp_string->s) { + if(len <= 0 || cp == fmtp_string->s) { LM_ERR("no encoding in `a=fmtp:'\n"); return -1; } fmtp_string->s = cp; - fmtp_string->len = eat_line(fmtp_string->s, body->s + body->len - - fmtp_string->s) - fmtp_string->s; + fmtp_string->len = + eat_line(fmtp_string->s, body->s + body->len - fmtp_string->s) + - fmtp_string->s; trim_len(fmtp_string->len, fmtp_string->s, *fmtp_string); return 0; @@ -258,18 +258,18 @@ int extract_fmtp( str *body, str *fmtp_payload, str *fmtp_string ) /** * Allocate a new ice attribute */ -static inline sdp_ice_attr_t *add_sdp_ice(sdp_stream_cell_t* _stream) +static inline sdp_ice_attr_t *add_sdp_ice(sdp_stream_cell_t *_stream) { sdp_ice_attr_t *ice_attr; int len; len = sizeof(sdp_ice_attr_t); ice_attr = (sdp_ice_attr_t *)pkg_malloc(len); - if (ice_attr == NULL) { - PKG_MEM_ERROR; - return NULL; + if(ice_attr == NULL) { + PKG_MEM_ERROR; + return NULL; } - memset( ice_attr, 0, len); + memset(ice_attr, 0, len); /* Insert the new ice attribute */ ice_attr->next = _stream->ice_attr; @@ -279,18 +279,18 @@ static inline sdp_ice_attr_t *add_sdp_ice(sdp_stream_cell_t* _stream) return ice_attr; } -static inline sdp_ice_opt_t *add_sdp_ice_opt(sdp_stream_cell_t* _stream) +static inline sdp_ice_opt_t *add_sdp_ice_opt(sdp_stream_cell_t *_stream) { sdp_ice_opt_t *ice_opt; int len; len = sizeof(sdp_ice_opt_t); ice_opt = (sdp_ice_opt_t *)pkg_malloc(len); - if (ice_opt == NULL) { - PKG_MEM_ERROR; - return NULL; + if(ice_opt == NULL) { + PKG_MEM_ERROR; + return NULL; } - memset( ice_opt, 0, len); + memset(ice_opt, 0, len); /* Insert the new ice option */ ice_opt->next = _stream->ice_opt; @@ -302,47 +302,47 @@ static inline sdp_ice_opt_t *add_sdp_ice_opt(sdp_stream_cell_t* _stream) int extract_candidate(str *body, sdp_stream_cell_t *stream) { - char *space, *start; - int len, fl; - sdp_ice_attr_t *ice_attr; + char *space, *start; + int len, fl; + sdp_ice_attr_t *ice_attr; - if ((body->len < 12) || (strncasecmp(body->s, "a=candidate:", 12) != 0)) { - /*LM_DBG("We are not pointing to an a=candidate: attribute =>`%.*s'\n", body->len, body->s); */ - return -1; - } - - start = body->s + 12; - len = body->len - 12; - - space = memchr(start, 32, len); - if ((space == NULL) || (space - start + 3 > len) || !isdigit(*(space + 1))) { - LM_ERR("no component in `a=candidate'\n"); - return -1; - } - - fl = space - start; - - start = space + 1; - len = len - (space - start + 1); - space = memchr(start, 32, len); - if (space == NULL) { - LM_ERR("no component in `a=candidate'\n"); - return -1; - } + if((body->len < 12) || (strncasecmp(body->s, "a=candidate:", 12) != 0)) { + /*LM_DBG("We are not pointing to an a=candidate: attribute =>`%.*s'\n", body->len, body->s); */ + return -1; + } - ice_attr = add_sdp_ice(stream); - if (ice_attr == NULL) { - LM_ERR("failed to add ice attribute\n"); - return -1; - } + start = body->s + 12; + len = body->len - 12; - /* currently only foundation and component-id are parsed */ - /* if needed, parse more */ - ice_attr->foundation.s = body->s + 12; - ice_attr->foundation.len = fl; - ice_attr->component_id = strtol(start, (char **)NULL, 10); + space = memchr(start, 32, len); + if((space == NULL) || (space - start + 3 > len) || !isdigit(*(space + 1))) { + LM_ERR("no component in `a=candidate'\n"); + return -1; + } - return 0; + fl = space - start; + + start = space + 1; + len = len - (space - start + 1); + space = memchr(start, 32, len); + if(space == NULL) { + LM_ERR("no component in `a=candidate'\n"); + return -1; + } + + ice_attr = add_sdp_ice(stream); + if(ice_attr == NULL) { + LM_ERR("failed to add ice attribute\n"); + return -1; + } + + /* currently only foundation and component-id are parsed */ + /* if needed, parse more */ + ice_attr->foundation.s = body->s + 12; + ice_attr->foundation.len = fl; + ice_attr->component_id = strtol(start, (char **)NULL, 10); + + return 0; } @@ -350,14 +350,14 @@ int extract_candidate(str *body, sdp_stream_cell_t *stream) * field must has format "a=attrname:" */ int extract_field(str *body, str *value, str field) { - if (strncmp(body->s, field.s, field.len < body->len ? field.len : body->len) !=0) { + if(strncmp(body->s, field.s, field.len < body->len ? field.len : body->len) + != 0) { /*LM_DBG("We are not pointing to an %.* attribute =>`%.*s'\n", field.len, field.s, body->len, body->s); */ return -1; } value->s = body->s + field.len; /* skip `a=attrname:' */ - value->len = eat_line(value->s, body->s + body->len - - value->s) - value->s; + value->len = eat_line(value->s, body->s + body->len - value->s) - value->s; trim_len(value->len, value->s, *value); return 0; @@ -367,38 +367,41 @@ int extract_ice_option(str *body, sdp_stream_cell_t *stream) { sdp_ice_opt_t *ice_opt; - char * ptr_src; - int max_options = 10; /* protection - max options can be listed in one line */ - int length = 0; /* each option length */ + char *ptr_src; + int max_options = + 10; /* protection - max options can be listed in one line */ + int length = 0; /* each option length */ /* a=ice-options: */ - if ((body->len < 14) || (strncasecmp(body->s, ICE_OPTIONS, 14) != 0)) + if((body->len < 14) || (strncasecmp(body->s, ICE_OPTIONS, 14) != 0)) return -1; ptr_src = body->s + 14; - if (*ptr_src == 32) ptr_src++; /* if starts with a space, skip it */ + if(*ptr_src == 32) + ptr_src++; /* if starts with a space, skip it */ /* identify all existing ICE options, if they are listed in one row */ - while (*ptr_src && *ptr_src != '\r' && *ptr_src != '\n' && max_options-->0) - { - while (*ptr_src != 32 && *ptr_src && *ptr_src != '\r' && *ptr_src != '\n') - { + while(*ptr_src && *ptr_src != '\r' && *ptr_src != '\n' + && max_options-- > 0) { + while(*ptr_src != 32 && *ptr_src && *ptr_src != '\r' + && *ptr_src != '\n') { length++; ptr_src++; } ice_opt = add_sdp_ice_opt(stream); - if (ice_opt == NULL) { + if(ice_opt == NULL) { LM_ERR("failed to add ice option\n"); return -1; } - ice_opt->option.s = ptr_src-length; + ice_opt->option.s = ptr_src - length; ice_opt->option.len = length; trim_len(ice_opt->option.len, ice_opt->option.s, ice_opt->option); length = 0; - if (*ptr_src == 32) ptr_src++; /* skip space */ + if(*ptr_src == 32) + ptr_src++; /* skip space */ } return 0; @@ -445,10 +448,10 @@ int extract_sendrecv_mode(str *body, str *sendrecv_mode, int *is_on_hold) char *cp1; cp1 = body->s; - if ( !( (strncasecmp(cp1, "a=sendrecv", 10) == 0) || - (strncasecmp(cp1, "a=recvonly", 10) == 0))) { - if ((strncasecmp(cp1, "a=inactive", 10) == 0) || - (strncasecmp(cp1, "a=sendonly", 10) == 0) ) { + if(!((strncasecmp(cp1, "a=sendrecv", 10) == 0) + || (strncasecmp(cp1, "a=recvonly", 10) == 0))) { + if((strncasecmp(cp1, "a=inactive", 10) == 0) + || (strncasecmp(cp1, "a=sendonly", 10) == 0)) { *is_on_hold = RFC3264_HOLD; } else { return -1; @@ -456,7 +459,8 @@ int extract_sendrecv_mode(str *body, str *sendrecv_mode, int *is_on_hold) } sendrecv_mode->s = body->s + 2; /* skip `a=' */ - sendrecv_mode->len = 8; /* we know the length and therefore we don't need to overkill */ + sendrecv_mode->len = + 8; /* we know the length and therefore we don't need to overkill */ /* sendrecv_mode->len = eat_line(sendrecv_mode->s, body->s + body->len - sendrecv_mode->s) - sendrecv_mode->s; @@ -472,24 +476,25 @@ int extract_bwidth(str *body, str *bwtype, str *bwwitdth) int len; cp1 = NULL; - for (cp = body->s; (len = body->s + body->len - cp) > 0;) { - cp1 = (char*)ser_memmem(cp, "b=", len, 2); - if (cp1 == NULL || cp1[-1] == '\n' || cp1[-1] == '\r') + for(cp = body->s; (len = body->s + body->len - cp) > 0;) { + cp1 = (char *)ser_memmem(cp, "b=", len, 2); + if(cp1 == NULL || cp1[-1] == '\n' || cp1[-1] == '\r') break; cp = cp1 + 2; } - if (cp1 == NULL) + if(cp1 == NULL) return -1; bwtype->s = cp1 + 2; - bwtype->len = eat_line(bwtype->s, body->s + body->len - bwtype->s) - bwtype->s; + bwtype->len = + eat_line(bwtype->s, body->s + body->len - bwtype->s) - bwtype->s; trim_len(bwtype->len, bwtype->s, *bwtype); cp = bwtype->s; len = bwtype->len; - cp1 = (char*)ser_memmem(cp, ":", len, 1); + cp1 = (char *)ser_memmem(cp, ":", len, 1); len -= cp1 - cp; - if (len <= 0) { + if(len <= 0) { LM_ERR("invalid encoding in `b=%.*s'\n", bwtype->len, bwtype->s); return -1; } @@ -498,7 +503,7 @@ int extract_bwidth(str *body, str *bwtype, str *bwwitdth) /* skip ':' */ bwwitdth->s = cp1 + 1; bwwitdth->len = len - 1; - + return 0; } @@ -508,46 +513,47 @@ int extract_mediaip(str *body, str *mediaip, int *pf, char *line) int len; cp1 = NULL; - for (cp = body->s; (len = body->s + body->len - cp) > 0;) { - cp1 = (char*)ser_memmem(cp, line, len, 2); - if (cp1 == NULL || cp1[-1] == '\n' || cp1[-1] == '\r') + for(cp = body->s; (len = body->s + body->len - cp) > 0;) { + cp1 = (char *)ser_memmem(cp, line, len, 2); + if(cp1 == NULL || cp1[-1] == '\n' || cp1[-1] == '\r') break; cp = cp1 + 2; } - if (cp1 == NULL) + if(cp1 == NULL) return -1; mediaip->s = cp1 + 2; - mediaip->len = eat_line(mediaip->s, body->s + body->len - mediaip->s) - mediaip->s; + mediaip->len = + eat_line(mediaip->s, body->s + body->len - mediaip->s) - mediaip->s; trim_len(mediaip->len, mediaip->s, *mediaip); - if (mediaip->len == 0) { - LM_ERR("no [%s] line in SDP\n",line); + if(mediaip->len == 0) { + LM_ERR("no [%s] line in SDP\n", line); return -1; } /* search reverse for IP[4|6] in c=/o= line */ - cp = (char*)ser_memrmem(mediaip->s, " IP", mediaip->len, 3); - if (cp == NULL) { - LM_ERR("no `IP[4|6]' in `%s' field\n",line); + cp = (char *)ser_memrmem(mediaip->s, " IP", mediaip->len, 3); + if(cp == NULL) { + LM_ERR("no `IP[4|6]' in `%s' field\n", line); return -1; } /* safety checks: * - for length, at least 6: ' IP[4|6] x...' * - white space after */ - if(cp + 6 > mediaip->s + mediaip->len && cp[4]!=' ') { - LM_ERR("invalid content for `%s' line\n",line); + if(cp + 6 > mediaip->s + mediaip->len && cp[4] != ' ') { + LM_ERR("invalid content for `%s' line\n", line); return -1; } switch(cp[3]) { case '4': *pf = AF_INET; - break; + break; case '6': *pf = AF_INET6; - break; + break; default: - LM_ERR("invalid addrtype IPx for `%s' line\n",line); + LM_ERR("invalid addrtype IPx for `%s' line\n", line); return -1; } cp += 5; @@ -558,35 +564,36 @@ int extract_mediaip(str *body, str *mediaip, int *pf, char *line) mediaip->s = cp; mediaip->len = len; - if (mediaip->len == 0) { - LM_ERR("no `IP[4|6]' address in `%s' field\n",line); + if(mediaip->len == 0) { + LM_ERR("no `IP[4|6]' address in `%s' field\n", line); return -1; } - LM_DBG("located IP address [%.*s] in `%s' field\n", - mediaip->len, mediaip->s, line); + LM_DBG("located IP address [%.*s] in `%s' field\n", mediaip->len, + mediaip->s, line); return 1; } -int extract_media_attr(str *body, str *mediamedia, str *mediaport, str *mediatransport, str *mediapayload, int *is_rtp) +int extract_media_attr(str *body, str *mediamedia, str *mediaport, + str *mediatransport, str *mediapayload, int *is_rtp) { char *cp, *cp1; int len, i; cp1 = NULL; - for (cp = body->s; (len = body->s + body->len - cp) > 0;) { - cp1 = (char*)ser_memmem(cp, "m=", len, 2); - if (cp1 == NULL || cp1[-1] == '\n' || cp1[-1] == '\r') + for(cp = body->s; (len = body->s + body->len - cp) > 0;) { + cp1 = (char *)ser_memmem(cp, "m=", len, 2); + if(cp1 == NULL || cp1[-1] == '\n' || cp1[-1] == '\r') break; cp = cp1 + 2; } - if (cp1 == NULL) { + if(cp1 == NULL) { LM_ERR("no `m=' in SDP\n"); return -1; } mediaport->s = cp1 + 2; /* skip `m=' */ - mediaport->len = eat_line(mediaport->s, body->s + body->len - - mediaport->s) - mediaport->s; + mediaport->len = eat_line(mediaport->s, body->s + body->len - mediaport->s) + - mediaport->s; trim_len(mediaport->len, mediaport->s, *mediaport); mediapayload->len = mediaport->len; @@ -597,7 +604,7 @@ int extract_media_attr(str *body, str *mediamedia, str *mediaport, str *mediatra cp = eat_token_end(mediaport->s, mediaport->s + mediaport->len); mediaport->len -= cp - mediaport->s; mediamedia->len = mediapayload->len - mediaport->len; - if (mediaport->len <= 0 || cp == mediaport->s) { + if(mediaport->len <= 0 || cp == mediaport->s) { LM_ERR("no port in `m='\n"); return -1; } @@ -605,7 +612,7 @@ int extract_media_attr(str *body, str *mediamedia, str *mediaport, str *mediatra cp = eat_space_end(mediaport->s, mediaport->s + mediaport->len); mediaport->len -= cp - mediaport->s; - if (mediaport->len <= 0 || cp == mediaport->s) { + if(mediaport->len <= 0 || cp == mediaport->s) { LM_ERR("no port in `m='\n"); return -1; } @@ -614,7 +621,7 @@ int extract_media_attr(str *body, str *mediamedia, str *mediaport, str *mediatra mediaport->s = cp; cp = eat_token_end(mediaport->s, mediaport->s + mediaport->len); mediatransport->len = mediaport->len - (cp - mediaport->s); - if (mediatransport->len <= 0 || cp == mediaport->s) { + if(mediatransport->len <= 0 || cp == mediaport->s) { LM_ERR("no port in `m='\n"); return -1; } @@ -622,16 +629,18 @@ int extract_media_attr(str *body, str *mediamedia, str *mediaport, str *mediatra mediaport->len = cp - mediaport->s; /* Skip spaces after port */ - cp = eat_space_end(mediatransport->s, mediatransport->s + mediatransport->len); + cp = eat_space_end( + mediatransport->s, mediatransport->s + mediatransport->len); mediatransport->len -= cp - mediatransport->s; - if (mediatransport->len <= 0 || cp == mediatransport->s) { + if(mediatransport->len <= 0 || cp == mediatransport->s) { LM_ERR("no protocol type in `m='\n"); return -1; } /* Extract protocol type */ mediatransport->s = cp; - cp = eat_token_end(mediatransport->s, mediatransport->s + mediatransport->len); - if (cp == mediatransport->s) { + cp = eat_token_end( + mediatransport->s, mediatransport->s + mediatransport->len); + if(cp == mediatransport->s) { LM_ERR("no protocol type in `m='\n"); return -1; } @@ -643,9 +652,11 @@ int extract_media_attr(str *body, str *mediamedia, str *mediaport, str *mediatra mediapayload->len -= cp - mediapayload->s; mediapayload->s = cp; - for (i = 0; sup_ptypes[i].s != NULL; i++) - if (mediatransport->len == sup_ptypes[i].len && - strncasecmp(mediatransport->s, sup_ptypes[i].s, mediatransport->len) == 0) { + for(i = 0; sup_ptypes[i].s != NULL; i++) + if(mediatransport->len == sup_ptypes[i].len + && strncasecmp(mediatransport->s, sup_ptypes[i].s, + mediatransport->len) + == 0) { *is_rtp = sup_ptypes[i].is_rtp; return 0; } @@ -653,13 +664,14 @@ int extract_media_attr(str *body, str *mediamedia, str *mediaport, str *mediatra return 0; } -int extract_sess_version(str* oline, str* sess_version) { +int extract_sess_version(str *oline, str *sess_version) +{ - char* cp0 = NULL; - char* cp = NULL; + char *cp0 = NULL; + char *cp = NULL; int len = 0; char ws = ' '; - int i=0; + int i = 0; /* "o=jdoe 2890844526 2890842807 IN IP4 10.47.16.5" CR LF @@ -667,14 +679,12 @@ int extract_sess_version(str* oline, str* sess_version) { "o=W 1 2 IN IP6 ::1" CR LF -> 20 "o=W 1 2 X Y Z" CR LF -> 15 */ - if ( oline->s == NULL || oline->len < 15 ) - { + if(oline->s == NULL || oline->len < 15) { LM_ERR("invalid o -line\n"); return -1; } - if ( sess_version == NULL ) - { + if(sess_version == NULL) { LM_ERR("invalid result pointer\n"); return -1; } @@ -686,35 +696,34 @@ int extract_sess_version(str* oline, str* sess_version) { len = oline->len - 2; // find whitespace 3 times - do - { - cp0=cp; + do { + cp0 = cp; //LM_DBG("loop %d: >%.*s<\n", len, len, cp0); - cp = (char*)ser_memmem(cp0, &ws, len, 1); - if ( cp == NULL) { break; } + cp = (char *)ser_memmem(cp0, &ws, len, 1); + if(cp == NULL) { + break; + } //LM_DBG("cp0: %p cp: %p (%ld)\n", cp0, cp, cp-cp0); - len-=cp-cp0; + len -= cp - cp0; // step over whitespace - if ( len > 0 ) - { + if(len > 0) { cp++; len--; } i++; - } while ( len < oline->len && i < 3 ); + } while(len < oline->len && i < 3); - len = cp-cp0-1; + len = cp - cp0 - 1; LM_DBG("end %d: >%.*s<\n", len, len, cp0); sess_version->s = cp0; sess_version->len = len; - if (!isdigit(*cp0)) - { + if(!isdigit(*cp0)) { LM_WARN("not digit >%.*s<\n", len, cp0); } @@ -727,31 +736,31 @@ int extract_sess_version(str* oline, str* sess_version) { * Returns pointer to first character of found line, or NULL if no such line. */ -char *find_sdp_line(char* p, char* plimit, char linechar) +char *find_sdp_line(char *p, char *plimit, char linechar) { static char linehead[3] = "x="; char *cp, *cp1; linehead[0] = linechar; /* Iterate through body */ cp = p; - for (;;) { - if (cp >= plimit) + for(;;) { + if(cp >= plimit) return NULL; - cp1 = ser_memmem(cp, linehead, plimit-cp, 2); - if (cp1 == NULL) + cp1 = ser_memmem(cp, linehead, plimit - cp, 2); + if(cp1 == NULL) return NULL; /* * As it is body, we assume it has previous line and we can * lookup previous character. */ - if (cp1[-1] == '\n' || cp1[-1] == '\r') + if(cp1[-1] == '\n' || cp1[-1] == '\r') return cp1; /* * Having such data, but not at line beginning. * Skip them and reiterate. ser_memmem() will find next * occurrence. */ - if (plimit - cp1 < 2) + if(plimit - cp1 < 2) return NULL; cp = cp1 + 2; } @@ -759,10 +768,10 @@ char *find_sdp_line(char* p, char* plimit, char linechar) /* This function assumes p points to a line of requested type. */ -char * find_next_sdp_line(char* p, char* plimit, char linechar, char* defptr) +char *find_next_sdp_line(char *p, char *plimit, char linechar, char *defptr) { char *t; - if (p >= plimit || plimit - p < 3) + if(p >= plimit || plimit - p < 3) return defptr; t = find_sdp_line(p + 2, plimit, linechar); return t ? t : defptr; @@ -770,11 +779,11 @@ char * find_next_sdp_line(char* p, char* plimit, char linechar, char* defptr) /* Find first SDP line starting with linechar. Return defptr if not found */ -char * find_first_sdp_line(char* pstart, char* plimit, char linechar, - char* defptr) +char *find_first_sdp_line( + char *pstart, char *plimit, char linechar, char *defptr) { char *t; - if (pstart >= plimit || plimit - pstart < 3) + if(pstart >= plimit || plimit - pstart < 3) return defptr; t = find_sdp_line(pstart, plimit, linechar); return t ? t : defptr; @@ -783,88 +792,87 @@ char * find_first_sdp_line(char* pstart, char* plimit, char linechar, /* returns pointer to next header line, and fill hdr_f ; * if at end of header returns pointer to the last crlf (always buf)*/ -char* get_sdp_hdr_field(char* buf, char* end, struct hdr_field* hdr) +char *get_sdp_hdr_field(char *buf, char *end, struct hdr_field *hdr) { - char* tmp; + char *tmp; char *match; - if ((*buf)=='\n' || (*buf)=='\r'){ + if((*buf) == '\n' || (*buf) == '\r') { /* double crlf or lflf or crcr */ - hdr->type=HDR_EOH_T; + hdr->type = HDR_EOH_T; return buf; } - tmp=parse_hname2(buf, end, hdr); - if (hdr->type==HDR_ERROR_T){ + tmp = parse_hname2(buf, end, hdr); + if(hdr->type == HDR_ERROR_T) { LM_ERR("bad header\n"); goto error; } /* eliminate leading whitespace */ - tmp=eat_lws_end(tmp, end); - if (tmp>=end) { + tmp = eat_lws_end(tmp, end); + if(tmp >= end) { LM_ERR("hf empty\n"); goto error; } /* just skip over it */ - hdr->body.s=tmp; + hdr->body.s = tmp; /* find end of header */ /* find lf */ - do{ - match=memchr(tmp, '\n', end-tmp); - if (match){ + do { + match = memchr(tmp, '\n', end - tmp); + if(match) { match++; - }else { + } else { LM_ERR("bad body for <%.*s>(%d)\n", hdr->name.len, hdr->name.s, hdr->type); - tmp=end; + tmp = end; goto error; } - tmp=match; - }while( matchbody.len=match-hdr->body.s; + tmp = match; + } while(match < end && ((*match == ' ') || (*match == '\t'))); + tmp = match; + hdr->body.len = match - hdr->body.s; /* jku: if \r covered by current length, shrink it */ - trim_r( hdr->body ); - hdr->len=tmp-hdr->name.s; + trim_r(hdr->body); + hdr->len = tmp - hdr->name.s; return tmp; error: LM_DBG("error exit\n"); - hdr->type=HDR_ERROR_T; - hdr->len=tmp-hdr->name.s; + hdr->type = HDR_ERROR_T; + hdr->len = tmp - hdr->name.s; return tmp; } - -char *find_sdp_line_delimiter(char* p, char* plimit, str delimiter) +char *find_sdp_line_delimiter(char *p, char *plimit, str delimiter) { static char delimiterhead[3] = "--"; char *cp, *cp1; /* Iterate through body */ cp = p; - for (;;) { - if (cp >= plimit) + for(;;) { + if(cp >= plimit) return NULL; for(;;) { - cp1 = ser_memmem(cp, delimiterhead, plimit-cp, 2); - if (cp1 == NULL) + cp1 = ser_memmem(cp, delimiterhead, plimit - cp, 2); + if(cp1 == NULL) return NULL; /* We matched '--', * now let's match the boundary delimiter */ - if(cp1+2+delimiter.len >= plimit) + if(cp1 + 2 + delimiter.len >= plimit) return NULL; - if (strncmp(cp1+2, delimiter.s, delimiter.len) == 0) + if(strncmp(cp1 + 2, delimiter.s, delimiter.len) == 0) break; else cp = cp1 + 2 + delimiter.len; } - if (cp1[-1] == '\n' || cp1[-1] == '\r') + if(cp1[-1] == '\n' || cp1[-1] == '\r') return cp1; - if (plimit - cp1 < 2 + delimiter.len) + if(plimit - cp1 < 2 + delimiter.len) return NULL; cp = cp1 + 2 + delimiter.len; } @@ -874,12 +882,12 @@ char *find_sdp_line_delimiter(char* p, char* plimit, str delimiter) /* * This function assumes p points to a delimiter type line. */ -char *find_next_sdp_line_delimiter(char* p, char* plimit, str delimiter, char* defptr) +char *find_next_sdp_line_delimiter( + char *p, char *plimit, str delimiter, char *defptr) { char *t; - if (p >= plimit || plimit - p < 3) + if(p >= plimit || plimit - p < 3) return defptr; t = find_sdp_line_delimiter(p + 2, plimit, delimiter); return t ? t : defptr; } - diff --git a/src/core/parser/sdp/sdp_helpr_funcs.h b/src/core/parser/sdp/sdp_helpr_funcs.h index 3c4c7d78a26..e8ce6f7e60a 100644 --- a/src/core/parser/sdp/sdp_helpr_funcs.h +++ b/src/core/parser/sdp/sdp_helpr_funcs.h @@ -6,13 +6,13 @@ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * THIS SOFTWARE IS PROVIDED BY THE FREEBSD PROJECT ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO @@ -27,9 +27,8 @@ */ - #ifndef _SDP_HLPR_FUNCS_H -#define _SDP_HLPR_FUNCS_H +#define _SDP_HLPR_FUNCS_H #include "../../str.h" #include "../msg_parser.h" @@ -41,19 +40,21 @@ * Example: "boundary1" * Content-Type: multipart/mixed; boundary="boundary1" */ -int get_mixed_part_delimiter(str * body, str * mp_delimiter); +int get_mixed_part_delimiter(str *body, str *mp_delimiter); -int extract_field(str* body, str* value, str field); -int extract_rtpmap(str *body, str *rtpmap_payload, str *rtpmap_encoding, str *rtpmap_clockrate, str *rtpmap_parmas); -int extract_fmtp( str *body, str *fmtp_payload, str *fmtp_string ); +int extract_field(str *body, str *value, str field); +int extract_rtpmap(str *body, str *rtpmap_payload, str *rtpmap_encoding, + str *rtpmap_clockrate, str *rtpmap_parmas); +int extract_fmtp(str *body, str *fmtp_payload, str *fmtp_string); int extract_ptime(str *body, str *ptime); int extract_sendrecv_mode(str *body, str *sendrecv_mode, int *is_on_hold); int extract_mediaip(str *body, str *mediaip, int *pf, char *line); -int extract_media_attr(str *body, str *mediamedia, str *mediaport, str *mediatransport, str *mediapayload, int *is_rtp); +int extract_media_attr(str *body, str *mediamedia, str *mediaport, + str *mediatransport, str *mediapayload, int *is_rtp); int extract_bwidth(str *body, str *bwtype, str *bwwitdth); int extract_candidate(str *body, sdp_stream_cell_t *stream); int extract_ice_option(str *body, sdp_stream_cell_t *stream); -int extract_sess_version(str* oline, str* sess_version); +int extract_sess_version(str *oline, str *sess_version); /* RFC3605 attributes */ int extract_rtcp(str *body, str *rtcp); @@ -67,10 +68,11 @@ int extract_path(str *body, str *path); char *find_sdp_line(char *p, char *plimit, char linechar); char *find_next_sdp_line(char *p, char *plimit, char linechar, char *defptr); -char* get_sdp_hdr_field(char* , char* , struct hdr_field* ); +char *get_sdp_hdr_field(char *, char *, struct hdr_field *); char *find_sdp_line_delimiter(char *p, char *plimit, str delimiter); -char *find_next_sdp_line_delimiter(char *p, char *plimit, str delimiter, char *defptr); -char * find_first_sdp_line(char* pstart, char* plimit, char linechar, - char* defptr); +char *find_next_sdp_line_delimiter( + char *p, char *plimit, str delimiter, char *defptr); +char *find_first_sdp_line( + char *pstart, char *plimit, char linechar, char *defptr); #endif From 3c225c7447158ccc00a75bc6f3012925bb230502 Mon Sep 17 00:00:00 2001 From: Victor Seva Date: Thu, 18 May 2023 15:23:27 +0200 Subject: [PATCH 07/14] core: [rand] clang-format for coherent indentation and coding style --- src/core/rand/cryptorand.c | 15 +- src/core/rand/fastrand.c | 8 +- src/core/rand/fortuna/fortuna.c | 181 +++++++++++------------- src/core/rand/fortuna/random.c | 33 ++--- src/core/rand/fortuna/random.h | 8 +- src/core/rand/isaac/rand.c | 239 +++++++++++++++++++------------- src/core/rand/isaac/rand.h | 30 ++-- src/core/rand/isaac/standard.h | 54 ++++---- src/core/rand/kam_rand.h | 2 +- 9 files changed, 289 insertions(+), 281 deletions(-) diff --git a/src/core/rand/cryptorand.c b/src/core/rand/cryptorand.c index 469e986b16d..9400c16cb20 100644 --- a/src/core/rand/cryptorand.c +++ b/src/core/rand/cryptorand.c @@ -25,12 +25,13 @@ #include "../dprint.h" /* seed the generator, will also use system randomness */ -void cryptorand_seed(const unsigned int seed) { +void cryptorand_seed(const unsigned int seed) +{ u_int8_t bytes[4]; - + bytes[0] = (seed >> 24) & 0xFF; bytes[1] = (seed >> 16) & 0xFF; - bytes[2] = (seed >> 8) & 0xFF; + bytes[2] = (seed >> 8) & 0xFF; bytes[3] = seed & 0xFF; LM_DBG("seeding cryptorand generator with %u\n", seed); @@ -38,16 +39,16 @@ void cryptorand_seed(const unsigned int seed) { } /* generate a 32 bit random number */ -unsigned int cryptorand(void) { +unsigned int cryptorand(void) +{ u_int8_t bytes[4]; u_int32_t result = 0; - + sr_get_pseudo_random_bytes(bytes, 4); result |= (u_int32_t)bytes[0] << 24; result |= (u_int32_t)bytes[1] << 16; result |= (u_int32_t)bytes[2] << 8; result |= (u_int32_t)bytes[3]; - + return result; } - diff --git a/src/core/rand/fastrand.c b/src/core/rand/fastrand.c index 3af12f32295..73ba6f79ff1 100644 --- a/src/core/rand/fastrand.c +++ b/src/core/rand/fastrand.c @@ -25,7 +25,7 @@ #include #include "isaac/rand.h" -#define FASTRAND_MAX ((unsigned int)(-1)) +#define FASTRAND_MAX ((unsigned int)(-1)) static randctx is_ctx; @@ -36,8 +36,8 @@ void fastrand_seed(unsigned int seed) int i; srandom(seed); - for (i=0; ipool[i]); } @@ -188,16 +182,15 @@ init_state(FState *st) * Endianness does not matter. * It just needs to change without repeating. */ -static void -inc_counter(FState *st) +static void inc_counter(FState *st) { - u_int32_t *val = (u_int32_t *) st->counter; + u_int32_t *val = (u_int32_t *)st->counter; - if (++val[0]) + if(++val[0]) return; - if (++val[1]) + if(++val[1]) return; - if (++val[2]) + if(++val[2]) return; ++val[3]; } @@ -205,8 +198,7 @@ inc_counter(FState *st) /* * This is called 'cipher in counter mode'. */ -static void -encrypt_counter(FState *st, u_int8_t *dst) +static void encrypt_counter(FState *st, u_int8_t *dst) { ciph_encrypt(&st->ciph, st->counter, dst); inc_counter(st); @@ -217,10 +209,9 @@ encrypt_counter(FState *st, u_int8_t *dst) * The time between reseed must be at least RESEED_INTERVAL * microseconds. */ -static int -enough_time_passed(FState *st) +static int enough_time_passed(FState *st) { - int ok; + int ok; struct timeval tv; struct timeval *last = &st->last_reseed_time; @@ -228,18 +219,16 @@ enough_time_passed(FState *st) /* check how much time has passed */ ok = 0; - if (tv.tv_sec > last->tv_sec + 1) + if(tv.tv_sec > last->tv_sec + 1) ok = 1; - else if (tv.tv_sec == last->tv_sec + 1) - { - if (1000000 + tv.tv_usec - last->tv_usec >= RESEED_INTERVAL) + else if(tv.tv_sec == last->tv_sec + 1) { + if(1000000 + tv.tv_usec - last->tv_usec >= RESEED_INTERVAL) ok = 1; - } - else if (tv.tv_usec - last->tv_usec >= RESEED_INTERVAL) + } else if(tv.tv_usec - last->tv_usec >= RESEED_INTERVAL) ok = 1; /* reseed will happen, update last_reseed_time */ - if (ok) + if(ok) memcpy(last, &tv, sizeof(tv)); memset(&tv, 0, sizeof(tv)); @@ -250,13 +239,12 @@ enough_time_passed(FState *st) /* * generate new key from all the pools */ -static void -reseed(FState *st) +static void reseed(FState *st) { - unsigned k; - unsigned n; - MD_CTX key_md; - u_int8_t buf[BLOCK]; + unsigned k; + unsigned n; + MD_CTX key_md; + u_int8_t buf[BLOCK]; /* set pool as empty */ st->pool0_bytes = 0; @@ -270,12 +258,11 @@ reseed(FState *st) * The goal: use k-th pool only 1/(2^k) of the time. */ md_init(&key_md); - for (k = 0; k < NUM_POOLS; k++) - { + for(k = 0; k < NUM_POOLS; k++) { md_result(&st->pool[k], buf); md_update(&key_md, buf, BLOCK); - if (n & 1 || !n) + if(n & 1 || !n) break; n >>= 1; } @@ -296,10 +283,9 @@ reseed(FState *st) /* * Pick a random pool. This uses key bytes as random source. */ -static unsigned -get_rand_pool(FState *st) +static unsigned get_rand_pool(FState *st) { - unsigned rnd; + unsigned rnd; /* * This slightly prefers lower pools - thats OK. @@ -307,7 +293,7 @@ get_rand_pool(FState *st) rnd = st->key[st->rnd_pos] % NUM_POOLS; st->rnd_pos++; - if (st->rnd_pos >= BLOCK) + if(st->rnd_pos >= BLOCK) st->rnd_pos = 0; return rnd; @@ -316,12 +302,11 @@ get_rand_pool(FState *st) /* * update pools */ -static void -add_entropy(FState *st, const u_int8_t *data, unsigned len) +static void add_entropy(FState *st, const u_int8_t *data, unsigned len) { - unsigned pos; - u_int8_t hash[BLOCK]; - MD_CTX md; + unsigned pos; + u_int8_t hash[BLOCK]; + MD_CTX md; /* hash given data */ md_init(&md); @@ -331,13 +316,13 @@ add_entropy(FState *st, const u_int8_t *data, unsigned len) /* * Make sure the pool 0 is initialized, then update randomly. */ - if (st->reseed_count == 0) + if(st->reseed_count == 0) pos = 0; else pos = get_rand_pool(st); md_update(&st->pool[pos], hash, BLOCK); - if (pos == 0) + if(pos == 0) st->pool0_bytes += len; memset(hash, 0, BLOCK); @@ -347,8 +332,7 @@ add_entropy(FState *st, const u_int8_t *data, unsigned len) /* * Just take 2 next blocks as new key */ -static void -rekey(FState *st) +static void rekey(FState *st) { encrypt_counter(st, st->key); encrypt_counter(st, st->key + CIPH_BLOCK); @@ -361,18 +345,16 @@ rekey(FState *st) * This can also be viewed as spreading the startup * entropy over all of the components. */ -static void -startup_tricks(FState *st) +static void startup_tricks(FState *st) { - int i; - u_int8_t buf[BLOCK]; + int i; + u_int8_t buf[BLOCK]; /* Use next block as counter. */ encrypt_counter(st, st->counter); /* Now shuffle pools, excluding #0 */ - for (i = 1; i < NUM_POOLS; i++) - { + for(i = 1; i < NUM_POOLS; i++) { encrypt_counter(st, buf); encrypt_counter(st, buf + CIPH_BLOCK); md_update(&st->pool[i], buf, BLOCK); @@ -386,28 +368,26 @@ startup_tricks(FState *st) st->tricks_done = 1; } -static void -extract_data(FState *st, unsigned count, u_int8_t *dst) +static void extract_data(FState *st, unsigned count, u_int8_t *dst) { - unsigned n; - unsigned block_nr = 0; + unsigned n; + unsigned block_nr = 0; /* Should we reseed? */ - if (st->pool0_bytes >= POOL0_FILL || st->reseed_count == 0) - if (enough_time_passed(st)) + if(st->pool0_bytes >= POOL0_FILL || st->reseed_count == 0) + if(enough_time_passed(st)) reseed(st); /* Do some randomization on first call */ - if (!st->tricks_done) + if(!st->tricks_done) startup_tricks(st); - while (count > 0) - { + while(count > 0) { /* produce bytes */ encrypt_counter(st, st->result); /* copy result */ - if (count > CIPH_BLOCK) + if(count > CIPH_BLOCK) n = CIPH_BLOCK; else n = count; @@ -417,8 +397,7 @@ extract_data(FState *st, unsigned count, u_int8_t *dst) /* must not give out too many bytes with one key */ block_nr++; - if (block_nr > (RESEED_BYTES / CIPH_BLOCK)) - { + if(block_nr > (RESEED_BYTES / CIPH_BLOCK)) { rekey(st); block_nr = 0; } @@ -432,30 +411,26 @@ extract_data(FState *st, unsigned count, u_int8_t *dst) */ FState main_state; -int init_done = 0; +int init_done = 0; -void -fortuna_add_entropy(const u_int8_t *data, unsigned len) +void fortuna_add_entropy(const u_int8_t *data, unsigned len) { - if (!init_done) - { + if(!init_done) { init_state(&main_state); init_done = 1; } - if (!data || !len) + if(!data || !len) return; add_entropy(&main_state, data, len); } -void -fortuna_get_bytes(unsigned len, u_int8_t *dst) +void fortuna_get_bytes(unsigned len, u_int8_t *dst) { - if (!init_done) - { + if(!init_done) { init_state(&main_state); init_done = 1; } - if (!dst || !len) + if(!dst || !len) return; extract_data(&main_state, len, dst); } diff --git a/src/core/rand/fortuna/random.c b/src/core/rand/fortuna/random.c index dfb233b8553..e4635b3186c 100644 --- a/src/core/rand/fortuna/random.c +++ b/src/core/rand/fortuna/random.c @@ -45,7 +45,7 @@ #include "fortuna.h" /* how many bytes to ask from system random provider */ -#define RND_BYTES 32 +#define RND_BYTES 32 /* * Try to read from /dev/urandom or /dev/random on these OS'es. @@ -70,12 +70,10 @@ static int safe_read(int fd, void *buf, size_t count) char *p = buf; int res; - while (count) - { + while(count) { res = read(fd, p, count); - if (res <= 0) - { - if (errno == EINTR) + if(res <= 0) { + if(errno == EINTR) continue; return -10; } @@ -86,21 +84,20 @@ static int safe_read(int fd, void *buf, size_t count) return done; } -static u_int8_t * try_dev_random(u_int8_t *dst) +static u_int8_t *try_dev_random(u_int8_t *dst) { int fd; int res; fd = open("/dev/urandom", O_RDONLY, 0); - if (fd == -1) - { + if(fd == -1) { fd = open("/dev/random", O_RDONLY, 0); - if (fd == -1) + if(fd == -1) return dst; } res = safe_read(fd, dst, RND_BYTES); close(fd); - if (res > 0) + if(res > 0) dst += res; return dst; } @@ -127,15 +124,13 @@ static void system_reseed(void) t = time(NULL); - if (seed_time == 0) + if(seed_time == 0) skip = 0; - else if ((t - seed_time) < SYSTEM_RESEED_MIN) + else if((t - seed_time) < SYSTEM_RESEED_MIN) skip = 1; - else if ((t - seed_time) > SYSTEM_RESEED_MAX) + else if((t - seed_time) > SYSTEM_RESEED_MAX) skip = 0; - else if (check_time == 0 || - (t - check_time) > SYSTEM_RESEED_CHECK_TIME) - { + else if(check_time == 0 || (t - check_time) > SYSTEM_RESEED_CHECK_TIME) { check_time = t; /* roll dice */ @@ -145,11 +140,11 @@ static void system_reseed(void) /* clear 1 byte */ memset(buf, 0, sizeof(buf)); - if (skip) + if(skip) return; n = acquire_system_randomness(buf); - if (n > 0) { + if(n > 0) { fortuna_add_entropy(buf, n); LM_DBG("cryptographic PRNG reseed done with %u bytes\n", n); } diff --git a/src/core/rand/fortuna/random.h b/src/core/rand/fortuna/random.h index 5a87cde392f..45fe056278a 100644 --- a/src/core/rand/fortuna/random.h +++ b/src/core/rand/fortuna/random.h @@ -42,20 +42,20 @@ /* * System reseeds should be separated at least this much. */ -#define SYSTEM_RESEED_MIN (20*60) /* 20 min */ +#define SYSTEM_RESEED_MIN (20 * 60) /* 20 min */ /* * How often to roll dice. */ -#define SYSTEM_RESEED_CHECK_TIME (10*60) /* 10 min */ +#define SYSTEM_RESEED_CHECK_TIME (10 * 60) /* 10 min */ /* * The chance is x/256 that the reseed happens. */ -#define SYSTEM_RESEED_CHANCE (4) /* 256/4 * 10min ~ 10h */ +#define SYSTEM_RESEED_CHANCE (4) /* 256/4 * 10min ~ 10h */ /* * If this much time has passed, force reseed. */ -#define SYSTEM_RESEED_MAX (12*60*60) /* 12h */ +#define SYSTEM_RESEED_MAX (12 * 60 * 60) /* 12h */ int sr_get_pseudo_random_bytes(u_int8_t *dst, unsigned count); diff --git a/src/core/rand/isaac/rand.c b/src/core/rand/isaac/rand.c index 4665b38df98..eb917fdd34f 100644 --- a/src/core/rand/isaac/rand.c +++ b/src/core/rand/isaac/rand.c @@ -16,122 +16,161 @@ rand.c: By Bob Jenkins. My random number generator, ISAAC. Public Domain. #endif -#define ind(mm,x) (*(ub4 *)((ub1 *)(mm) + ((x) & ((RANDSIZ-1)<<2)))) -#define rngstep(mix,a,b,mm,m,m2,r,x) \ -{ \ - x = *m; \ - a = (a^(mix)) + *(m2++); \ - *(m++) = y = ind(mm,x) + a + b; \ - *(r++) = b = ind(mm,y>>RANDSIZL) + x; \ -} +#define ind(mm, x) (*(ub4 *)((ub1 *)(mm) + ((x) & ((RANDSIZ - 1) << 2)))) +#define rngstep(mix, a, b, mm, m, m2, r, x) \ + { \ + x = *m; \ + a = (a ^ (mix)) + *(m2++); \ + *(m++) = y = ind(mm, x) + a + b; \ + *(r++) = b = ind(mm, y >> RANDSIZL) + x; \ + } -void isaac(ctx) -randctx *ctx; +void isaac(ctx) randctx *ctx; { - register ub4 a,b,x,y,*m,*mm,*m2,*r,*mend; - mm=ctx->randmem; r=ctx->randrsl; - a = ctx->randa; b = ctx->randb + (++ctx->randc); - for (m = mm, mend = m2 = m+(RANDSIZ/2); m>6 , a, b, mm, m, m2, r, x); - rngstep( a<<2 , a, b, mm, m, m2, r, x); - rngstep( a>>16, a, b, mm, m, m2, r, x); - } - for (m2 = mm; m2>6 , a, b, mm, m, m2, r, x); - rngstep( a<<2 , a, b, mm, m, m2, r, x); - rngstep( a>>16, a, b, mm, m, m2, r, x); - } - ctx->randb = b; ctx->randa = a; + register ub4 a, b, x, y, *m, *mm, *m2, *r, *mend; + mm = ctx->randmem; + r = ctx->randrsl; + a = ctx->randa; + b = ctx->randb + (++ctx->randc); + for(m = mm, mend = m2 = m + (RANDSIZ / 2); m < mend;) { + rngstep(a << 13, a, b, mm, m, m2, r, x); + rngstep(a >> 6, a, b, mm, m, m2, r, x); + rngstep(a << 2, a, b, mm, m, m2, r, x); + rngstep(a >> 16, a, b, mm, m, m2, r, x); + } + for(m2 = mm; m2 < mend;) { + rngstep(a << 13, a, b, mm, m, m2, r, x); + rngstep(a >> 6, a, b, mm, m, m2, r, x); + rngstep(a << 2, a, b, mm, m, m2, r, x); + rngstep(a >> 16, a, b, mm, m, m2, r, x); + } + ctx->randb = b; + ctx->randa = a; } -#define mix(a,b,c,d,e,f,g,h) \ -{ \ - a^=b<<11; d+=a; b+=c; \ - b^=c>>2; e+=b; c+=d; \ - c^=d<<8; f+=c; d+=e; \ - d^=e>>16; g+=d; e+=f; \ - e^=f<<10; h+=e; f+=g; \ - f^=g>>4; a+=f; g+=h; \ - g^=h<<8; b+=g; h+=a; \ - h^=a>>9; c+=h; a+=b; \ -} +#define mix(a, b, c, d, e, f, g, h) \ + { \ + a ^= b << 11; \ + d += a; \ + b += c; \ + b ^= c >> 2; \ + e += b; \ + c += d; \ + c ^= d << 8; \ + f += c; \ + d += e; \ + d ^= e >> 16; \ + g += d; \ + e += f; \ + e ^= f << 10; \ + h += e; \ + f += g; \ + f ^= g >> 4; \ + a += f; \ + g += h; \ + g ^= h << 8; \ + b += g; \ + h += a; \ + h ^= a >> 9; \ + c += h; \ + a += b; \ + } /* if (flag==TRUE), then use the contents of randrsl[] to initialize mm[]. */ -void randinit(ctx, flag) -randctx *ctx; -word flag; +void randinit(ctx, flag) randctx *ctx; +word flag; { - word i; - ub4 a,b,c,d,e,f,g,h; - ub4 *m,*r; - ctx->randa = ctx->randb = ctx->randc = 0; - m=ctx->randmem; - r=ctx->randrsl; - a=b=c=d=e=f=g=h=0x9e3779b9; /* the golden ratio */ + word i; + ub4 a, b, c, d, e, f, g, h; + ub4 *m, *r; + ctx->randa = ctx->randb = ctx->randc = 0; + m = ctx->randmem; + r = ctx->randrsl; + a = b = c = d = e = f = g = h = 0x9e3779b9; /* the golden ratio */ - for (i=0; i<4; ++i) /* scramble it */ - { - mix(a,b,c,d,e,f,g,h); - } + for(i = 0; i < 4; ++i) /* scramble it */ + { + mix(a, b, c, d, e, f, g, h); + } - if (flag) - { - /* initialize using the contents of r[] as the seed */ - for (i=0; irandcnt=RANDSIZ; /* prepare to use the first set of results */ + isaac(ctx); /* fill in the first set of results */ + ctx->randcnt = RANDSIZ; /* prepare to use the first set of results */ } #ifdef NEVER int main() { - ub4 i,j; - randctx ctx; - ctx.randa=ctx.randb=ctx.randc=(ub4)0; - for (i=0; i<256; ++i) ctx.randrsl[i]=(ub4)0; - randinit(&ctx, TRUE); - for (i=0; i<2; ++i) - { - isaac(&ctx); - for (j=0; j<256; ++j) - { - printf("%.8lx",ctx.randrsl[j]); - if ((j&7)==7) printf("\n"); - } - } + ub4 i, j; + randctx ctx; + ctx.randa = ctx.randb = ctx.randc = (ub4)0; + for(i = 0; i < 256; ++i) + ctx.randrsl[i] = (ub4)0; + randinit(&ctx, TRUE); + for(i = 0; i < 2; ++i) { + isaac(&ctx); + for(j = 0; j < 256; ++j) { + printf("%.8lx", ctx.randrsl[j]); + if((j & 7) == 7) + printf("\n"); + } + } } #endif diff --git a/src/core/rand/isaac/rand.h b/src/core/rand/isaac/rand.h index 018496f676e..e049851ff49 100644 --- a/src/core/rand/isaac/rand.h +++ b/src/core/rand/isaac/rand.h @@ -16,20 +16,20 @@ By Bob Jenkins, 1996, Public Domain #ifndef RAND #define RAND -#define RANDSIZL (8) /* I recommend 8 for crypto, 4 for simulations */ -#define RANDSIZ (1<randcnt-- ? \ - (isaac(r), (r)->randcnt=RANDSIZ-1, (r)->randrsl[(r)->randcnt]) : \ - (r)->randrsl[(r)->randcnt]) - -#endif /* RAND */ - +#define rand(r) \ + (!(r)->randcnt-- ? ( \ + isaac(r), (r)->randcnt = RANDSIZ - 1, (r)->randrsl[(r)->randcnt]) \ + : (r)->randrsl[(r)->randcnt]) +#endif /* RAND */ diff --git a/src/core/rand/isaac/standard.h b/src/core/rand/isaac/standard.h index 0fa188997b6..c7b7c34a8f1 100644 --- a/src/core/rand/isaac/standard.h +++ b/src/core/rand/isaac/standard.h @@ -10,54 +10,54 @@ Standard definitions and types, Bob Jenkins */ #ifndef STANDARD -# define STANDARD -# ifndef STDIO -# include -# define STDIO -# endif -# ifndef STDDEF -# include -# define STDDEF -# endif -typedef unsigned long long ub8; +#define STANDARD +#ifndef STDIO +#include +#define STDIO +#endif +#ifndef STDDEF +#include +#define STDDEF +#endif +typedef unsigned long long ub8; #define UB8MAXVAL 0xffffffffffffffffLL #define UB8BITS 64 -typedef signed long long sb8; +typedef signed long long sb8; #define SB8MAXVAL 0x7fffffffffffffffLL -typedef unsigned int ub4; /* unsigned 4-byte quantities */ +typedef unsigned int ub4; /* unsigned 4-byte quantities */ #define UB4MAXVAL 0xffffffff -typedef signed int sb4; +typedef signed int sb4; #define UB4BITS 32 #define SB4MAXVAL 0x7fffffff -typedef unsigned short int ub2; +typedef unsigned short int ub2; #define UB2MAXVAL 0xffff #define UB2BITS 16 -typedef signed short int sb2; +typedef signed short int sb2; #define SB2MAXVAL 0x7fff -typedef unsigned char ub1; +typedef unsigned char ub1; #define UB1MAXVAL 0xff #define UB1BITS 8 -typedef signed char sb1; /* signed 1-byte quantities */ +typedef signed char sb1; /* signed 1-byte quantities */ #define SB1MAXVAL 0x7f -typedef int word; /* fastest type available */ +typedef int word; /* fastest type available */ -#define bis(target,mask) ((target) |= (mask)) -#define bic(target,mask) ((target) &= ~(mask)) -#define bit(target,mask) ((target) & (mask)) +#define bis(target, mask) ((target) |= (mask)) +#define bic(target, mask) ((target) &= ~(mask)) +#define bit(target, mask) ((target) & (mask)) #ifndef min -# define min(a,b) (((a)<(b)) ? (a) : (b)) +#define min(a, b) (((a) < (b)) ? (a) : (b)) #endif /* min */ #ifndef max -# define max(a,b) (((a)<(b)) ? (b) : (a)) +#define max(a, b) (((a) < (b)) ? (b) : (a)) #endif /* max */ #ifndef align -# define align(a) (((ub4)a+(sizeof(void *)-1))&(~(sizeof(void *)-1))) +#define align(a) (((ub4)a + (sizeof(void *) - 1)) & (~(sizeof(void *) - 1))) #endif /* align */ #ifndef abs -# define abs(a) (((a)>0) ? (a) : -(a)) +#define abs(a) (((a) > 0) ? (a) : -(a)) #endif -#define TRUE 1 +#define TRUE 1 #define FALSE 0 -#define SUCCESS 0 /* 1 on VAX */ +#define SUCCESS 0 /* 1 on VAX */ #endif /* STANDARD */ diff --git a/src/core/rand/kam_rand.h b/src/core/rand/kam_rand.h index 295aed666f9..271f61f220d 100644 --- a/src/core/rand/kam_rand.h +++ b/src/core/rand/kam_rand.h @@ -23,7 +23,7 @@ #include #if RAND_MAX < INT_MAX -#define KAM_RAND_MAX ((int) (0x7FFFFFFF)) /* (1<<31) - 1 */ +#define KAM_RAND_MAX ((int)(0x7FFFFFFF)) /* (1<<31) - 1 */ #define kam_rand(x) ((int)random(x)) #define kam_srand(x) srandom(x) #else From aaa7a592ebc83ff4aaf19b15f22528a1868c6332 Mon Sep 17 00:00:00 2001 From: Victor Seva Date: Thu, 18 May 2023 15:23:49 +0200 Subject: [PATCH 08/14] core: [utils] clang-format for coherent indentation and coding style --- src/core/utils/snexpr.h | 2420 ++++++++++++++++++++------------------- src/core/utils/srjson.c | 807 +++++++------ src/core/utils/srjson.h | 238 ++-- src/core/utils/sruid.c | 95 +- src/core/utils/sruid.h | 14 +- src/core/utils/tmrec.c | 637 +++++------ src/core/utils/tmrec.h | 98 +- 7 files changed, 2216 insertions(+), 2093 deletions(-) diff --git a/src/core/utils/snexpr.h b/src/core/utils/snexpr.h index 0115a52fd8f..559aa7915c9 100644 --- a/src/core/utils/snexpr.h +++ b/src/core/utils/snexpr.h @@ -27,7 +27,8 @@ #define _SNEXPR_H_ #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif #include /* for isspace */ @@ -43,7 +44,8 @@ extern "C" { #define SNEXPR_TNUMBER (1 << 3) #define SNEXPR_TSTRING (1 << 4) #define SNEXPR_TWORD (1 << 5) -#define SNEXPR_TDEFAULT (SNEXPR_TOPEN | SNEXPR_TNUMBER | SNEXPR_TSTRING | SNEXPR_TWORD) +#define SNEXPR_TDEFAULT \ + (SNEXPR_TOPEN | SNEXPR_TNUMBER | SNEXPR_TSTRING | SNEXPR_TWORD) #define SNEXPR_UNARY (1 << 16) #define SNEXPR_COMMA (1 << 17) @@ -52,33 +54,33 @@ extern "C" { #define SNEXPR_VALASSIGN (1 << 20) -/* + /* * Simple expandable vector implementation */ -static int sne_vec_expand(char **buf, int *length, int *cap, int memsz) -{ - if(*length + 1 > *cap) { - void *ptr; - int n = (*cap == 0) ? 1 : *cap << 1; - ptr = realloc(*buf, n * memsz); - if(ptr == NULL) { - return -1; /* allocation failed */ + static int sne_vec_expand(char **buf, int *length, int *cap, int memsz) + { + if(*length + 1 > *cap) { + void *ptr; + int n = (*cap == 0) ? 1 : *cap << 1; + ptr = realloc(*buf, n * memsz); + if(ptr == NULL) { + return -1; /* allocation failed */ + } + *buf = (char *)ptr; + *cap = n; } - *buf = (char *)ptr; - *cap = n; + return 0; } - return 0; -} -#define sne_vec(T) \ - struct \ - { \ - T *buf; \ - int len; \ - int cap; \ +#define sne_vec(T) \ + struct \ + { \ + T *buf; \ + int len; \ + int cap; \ } #define sne_vec_init() \ - { \ - NULL, 0, 0 \ + { \ + NULL, 0, 0 \ } #define sne_vec_len(v) ((v)->len) #define sne_vec_unpack(v) \ @@ -88,141 +90,143 @@ static int sne_vec_expand(char **buf, int *length, int *cap, int memsz) #define sne_vec_nth(v, i) (v)->buf[i] #define sne_vec_peek(v) (v)->buf[(v)->len - 1] #define sne_vec_pop(v) (v)->buf[--(v)->len] -#define sne_vec_free(v) (free((v)->buf), (v)->buf = NULL, (v)->len = (v)->cap = 0) -#define sne_vec_foreach(v, var, iter) \ +#define sne_vec_free(v) \ + (free((v)->buf), (v)->buf = NULL, (v)->len = (v)->cap = 0) +#define sne_vec_foreach(v, var, iter) \ if((v)->len > 0) \ for((iter) = 0; (iter) < (v)->len && (((var) = (v)->buf[(iter)]), 1); \ ++(iter)) -/* + /* * Expression data types */ -struct snexpr; -struct snexpr_func; -struct snexpr_var; - -enum snexpr_type -{ - SNE_OP_UNKNOWN, - SNE_OP_UNARY_MINUS, - SNE_OP_UNARY_LOGICAL_NOT, - SNE_OP_UNARY_BITWISE_NOT, - - SNE_OP_POWER, - SNE_OP_DIVIDE, - SNE_OP_MULTIPLY, - SNE_OP_REMAINDER, - - SNE_OP_PLUS, - SNE_OP_MINUS, - - SNE_OP_SHL, - SNE_OP_SHR, - - SNE_OP_LT, - SNE_OP_LE, - SNE_OP_GT, - SNE_OP_GE, - SNE_OP_EQ, - SNE_OP_NE, - - SNE_OP_BITWISE_AND, - SNE_OP_BITWISE_OR, - SNE_OP_BITWISE_XOR, - - SNE_OP_LOGICAL_AND, - SNE_OP_LOGICAL_OR, - - SNE_OP_ASSIGN, - SNE_OP_COMMA, + struct snexpr; + struct snexpr_func; + struct snexpr_var; - SNE_OP_CONSTNUM, - SNE_OP_CONSTSTZ, - SNE_OP_VAR, - SNE_OP_FUNC, -}; + enum snexpr_type + { + SNE_OP_UNKNOWN, + SNE_OP_UNARY_MINUS, + SNE_OP_UNARY_LOGICAL_NOT, + SNE_OP_UNARY_BITWISE_NOT, + + SNE_OP_POWER, + SNE_OP_DIVIDE, + SNE_OP_MULTIPLY, + SNE_OP_REMAINDER, + + SNE_OP_PLUS, + SNE_OP_MINUS, + + SNE_OP_SHL, + SNE_OP_SHR, + + SNE_OP_LT, + SNE_OP_LE, + SNE_OP_GT, + SNE_OP_GE, + SNE_OP_EQ, + SNE_OP_NE, + + SNE_OP_BITWISE_AND, + SNE_OP_BITWISE_OR, + SNE_OP_BITWISE_XOR, + + SNE_OP_LOGICAL_AND, + SNE_OP_LOGICAL_OR, + + SNE_OP_ASSIGN, + SNE_OP_COMMA, + + SNE_OP_CONSTNUM, + SNE_OP_CONSTSTZ, + SNE_OP_VAR, + SNE_OP_FUNC, + }; -static int prec[] = {0, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 4, 5, 5, 5, 5, 5, 5, 6, 7, - 8, 9, 10, 11, 12, 0, 0, 0, 0}; + static int prec[] = {0, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 4, 5, 5, 5, 5, 5, 5, + 6, 7, 8, 9, 10, 11, 12, 0, 0, 0, 0}; -typedef sne_vec(struct snexpr) sne_vec_expr_t; -typedef void (*snexprfn_cleanup_t)(struct snexpr_func *f, void *context); -typedef struct snexpr* (*snexprfn_t)(struct snexpr_func *f, sne_vec_expr_t *args, void *context); + typedef sne_vec(struct snexpr) sne_vec_expr_t; + typedef void (*snexprfn_cleanup_t)(struct snexpr_func *f, void *context); + typedef struct snexpr *(*snexprfn_t)( + struct snexpr_func *f, sne_vec_expr_t *args, void *context); -typedef struct snexpr* (*snexternval_cbf_t)(char *vname); + typedef struct snexpr *(*snexternval_cbf_t)(char *vname); -static snexternval_cbf_t _snexternval_cbf = NULL; + static snexternval_cbf_t _snexternval_cbf = NULL; -struct snexpr -{ - enum snexpr_type type; - unsigned int eflags; - union + struct snexpr { - struct - { - float nval; - } num; - struct - { - char *sval; - } stz; - struct - { - struct snexpr_var *vref; - } var; - struct + enum snexpr_type type; + unsigned int eflags; + union { - sne_vec_expr_t args; - } op; - struct - { - struct snexpr_func *f; - sne_vec_expr_t args; - void *context; - } func; - } param; -}; - -#define snexpr_init() \ - { \ - .type = (enum snexpr_type)0, \ - .eflags = 0u \ + struct + { + float nval; + } num; + struct + { + char *sval; + } stz; + struct + { + struct snexpr_var *vref; + } var; + struct + { + sne_vec_expr_t args; + } op; + struct + { + struct snexpr_func *f; + sne_vec_expr_t args; + void *context; + } func; + } param; + }; + +#define snexpr_init() \ + { \ + .type = (enum snexpr_type)0, .eflags = 0u \ } -struct snexpr_string -{ - const char *s; - int n; -}; -struct snexpr_arg -{ - int oslen; - int eslen; - sne_vec_expr_t args; -}; + struct snexpr_string + { + const char *s; + int n; + }; + struct snexpr_arg + { + int oslen; + int eslen; + sne_vec_expr_t args; + }; -typedef sne_vec(struct snexpr_string) sne_vec_str_t; -typedef sne_vec(struct snexpr_arg) sne_vec_arg_t; + typedef sne_vec(struct snexpr_string) sne_vec_str_t; + typedef sne_vec(struct snexpr_arg) sne_vec_arg_t; -static int snexpr_is_unary(enum snexpr_type op) -{ - return op == SNE_OP_UNARY_MINUS || op == SNE_OP_UNARY_LOGICAL_NOT - || op == SNE_OP_UNARY_BITWISE_NOT; -} + static int snexpr_is_unary(enum snexpr_type op) + { + return op == SNE_OP_UNARY_MINUS || op == SNE_OP_UNARY_LOGICAL_NOT + || op == SNE_OP_UNARY_BITWISE_NOT; + } -static int snexpr_is_binary(enum snexpr_type op) -{ - return !snexpr_is_unary(op) && op != SNE_OP_CONSTNUM && op != SNE_OP_CONSTSTZ - && op != SNE_OP_VAR && op != SNE_OP_FUNC && op != SNE_OP_UNKNOWN; -} + static int snexpr_is_binary(enum snexpr_type op) + { + return !snexpr_is_unary(op) && op != SNE_OP_CONSTNUM + && op != SNE_OP_CONSTSTZ && op != SNE_OP_VAR && op != SNE_OP_FUNC + && op != SNE_OP_UNKNOWN; + } -static int snexpr_prec(enum snexpr_type a, enum snexpr_type b) -{ - int left = snexpr_is_binary(a) && a != SNE_OP_ASSIGN && a != SNE_OP_POWER - && a != SNE_OP_COMMA; - return (left && prec[a] >= prec[b]) || (prec[a] > prec[b]); -} + static int snexpr_prec(enum snexpr_type a, enum snexpr_type b) + { + int left = snexpr_is_binary(a) && a != SNE_OP_ASSIGN + && a != SNE_OP_POWER && a != SNE_OP_COMMA; + return (left && prec[a] >= prec[b]) || (prec[a] > prec[b]); + } #define isfirstvarchr(c) \ (((unsigned char)c >= '@' && c != '^' && c != '|') || c == '$') @@ -230,1224 +234,1262 @@ static int snexpr_prec(enum snexpr_type a, enum snexpr_type b) (((unsigned char)c >= '@' && c != '^' && c != '|') || c == '$' || c == '#' \ || (c >= '0' && c <= '9')) -static struct -{ - const char *s; - const enum snexpr_type op; -} OPS[] = { - {"-u", SNE_OP_UNARY_MINUS}, - {"!u", SNE_OP_UNARY_LOGICAL_NOT}, - {"^u", SNE_OP_UNARY_BITWISE_NOT}, - {"**", SNE_OP_POWER}, - {"*", SNE_OP_MULTIPLY}, - {"/", SNE_OP_DIVIDE}, - {"%", SNE_OP_REMAINDER}, - {"+", SNE_OP_PLUS}, - {"-", SNE_OP_MINUS}, - {"<<", SNE_OP_SHL}, - {">>", SNE_OP_SHR}, - {"<", SNE_OP_LT}, - {"<=", SNE_OP_LE}, - {">", SNE_OP_GT}, - {">=", SNE_OP_GE}, - {"==", SNE_OP_EQ}, - {"!=", SNE_OP_NE}, - {"&", SNE_OP_BITWISE_AND}, - {"|", SNE_OP_BITWISE_OR}, - {"^", SNE_OP_BITWISE_XOR}, - {"&&", SNE_OP_LOGICAL_AND}, - {"||", SNE_OP_LOGICAL_OR}, - {"=", SNE_OP_ASSIGN}, - {",", SNE_OP_COMMA}, - - /* These are used by lexer and must be ignored by parser, so we put + static struct + { + const char *s; + const enum snexpr_type op; + } OPS[] = { + {"-u", SNE_OP_UNARY_MINUS}, + {"!u", SNE_OP_UNARY_LOGICAL_NOT}, + {"^u", SNE_OP_UNARY_BITWISE_NOT}, + {"**", SNE_OP_POWER}, + {"*", SNE_OP_MULTIPLY}, + {"/", SNE_OP_DIVIDE}, + {"%", SNE_OP_REMAINDER}, + {"+", SNE_OP_PLUS}, + {"-", SNE_OP_MINUS}, + {"<<", SNE_OP_SHL}, + {">>", SNE_OP_SHR}, + {"<", SNE_OP_LT}, + {"<=", SNE_OP_LE}, + {">", SNE_OP_GT}, + {">=", SNE_OP_GE}, + {"==", SNE_OP_EQ}, + {"!=", SNE_OP_NE}, + {"&", SNE_OP_BITWISE_AND}, + {"|", SNE_OP_BITWISE_OR}, + {"^", SNE_OP_BITWISE_XOR}, + {"&&", SNE_OP_LOGICAL_AND}, + {"||", SNE_OP_LOGICAL_OR}, + {"=", SNE_OP_ASSIGN}, + {",", SNE_OP_COMMA}, + + /* These are used by lexer and must be ignored by parser, so we put them at the end */ - {"-", SNE_OP_UNARY_MINUS}, - {"!", SNE_OP_UNARY_LOGICAL_NOT}, - {"^", SNE_OP_UNARY_BITWISE_NOT}, -}; + {"-", SNE_OP_UNARY_MINUS}, + {"!", SNE_OP_UNARY_LOGICAL_NOT}, + {"^", SNE_OP_UNARY_BITWISE_NOT}, + }; -static enum snexpr_type snexpr_op(const char *s, size_t len, int unary) -{ - unsigned int i; - for(i = 0; i < sizeof(OPS) / sizeof(OPS[0]); i++) { - if(strlen(OPS[i].s) == len && strncmp(OPS[i].s, s, len) == 0 - && (unary == -1 || snexpr_is_unary(OPS[i].op) == unary)) { - return OPS[i].op; + static enum snexpr_type snexpr_op(const char *s, size_t len, int unary) + { + unsigned int i; + for(i = 0; i < sizeof(OPS) / sizeof(OPS[0]); i++) { + if(strlen(OPS[i].s) == len && strncmp(OPS[i].s, s, len) == 0 + && (unary == -1 || snexpr_is_unary(OPS[i].op) == unary)) { + return OPS[i].op; + } } + return SNE_OP_UNKNOWN; } - return SNE_OP_UNKNOWN; -} -static float snexpr_parse_number(const char *s, size_t len) -{ - float num = 0; - unsigned int frac = 0; - unsigned int digits = 0; - unsigned int i; - for(i = 0; i < len; i++) { - if(s[i] == '.' && frac == 0) { - frac++; - continue; - } - if(isdigit(s[i])) { - digits++; - if(frac > 0) { + static float snexpr_parse_number(const char *s, size_t len) + { + float num = 0; + unsigned int frac = 0; + unsigned int digits = 0; + unsigned int i; + for(i = 0; i < len; i++) { + if(s[i] == '.' && frac == 0) { frac++; + continue; + } + if(isdigit(s[i])) { + digits++; + if(frac > 0) { + frac++; + } + num = num * 10 + (s[i] - '0'); + } else { + return NAN; } - num = num * 10 + (s[i] - '0'); - } else { - return NAN; } + while(frac > 1) { + num = num / 10; + frac--; + } + return (digits > 0 ? num : NAN); } - while(frac > 1) { - num = num / 10; - frac--; - } - return (digits > 0 ? num : NAN); -} -/* + /* * Functions */ -struct snexpr_func -{ - const char *name; - snexprfn_t f; - snexprfn_cleanup_t cleanup; - size_t ctxsz; -}; - -static struct snexpr_func *snexpr_func_find( - struct snexpr_func *funcs, const char *s, size_t len) -{ - struct snexpr_func *f; - for(f = funcs; f->name; f++) { - if(strlen(f->name) == len && strncmp(f->name, s, len) == 0) { - return f; + struct snexpr_func + { + const char *name; + snexprfn_t f; + snexprfn_cleanup_t cleanup; + size_t ctxsz; + }; + + static struct snexpr_func *snexpr_func_find( + struct snexpr_func *funcs, const char *s, size_t len) + { + struct snexpr_func *f; + for(f = funcs; f->name; f++) { + if(strlen(f->name) == len && strncmp(f->name, s, len) == 0) { + return f; + } } + return NULL; } - return NULL; -} -/* + /* * Variables */ -struct snexpr_var -{ - unsigned int evflags; - char *name; - union + struct snexpr_var { - float nval; - char *sval; - } v; - struct snexpr_var *next; -}; + unsigned int evflags; + char *name; + union + { + float nval; + char *sval; + } v; + struct snexpr_var *next; + }; -struct snexpr_var_list -{ - struct snexpr_var *head; -}; + struct snexpr_var_list + { + struct snexpr_var *head; + }; -static struct snexpr_var *snexpr_var_find( - struct snexpr_var_list *vars, const char *s, size_t len) -{ - struct snexpr_var *v = NULL; - if(len == 0 || !isfirstvarchr(*s)) { - return NULL; - } - for(v = vars->head; v; v = v->next) { - if(strlen(v->name) == len && strncmp(v->name, s, len) == 0) { - return v; + static struct snexpr_var *snexpr_var_find( + struct snexpr_var_list *vars, const char *s, size_t len) + { + struct snexpr_var *v = NULL; + if(len == 0 || !isfirstvarchr(*s)) { + return NULL; } + for(v = vars->head; v; v = v->next) { + if(strlen(v->name) == len && strncmp(v->name, s, len) == 0) { + return v; + } + } + v = (struct snexpr_var *)calloc(1, sizeof(struct snexpr_var) + len + 1); + if(v == NULL) { + return NULL; /* allocation failed */ + } + memset(v, 0, sizeof(struct snexpr_var) + len + 1); + v->next = vars->head; + v->name = (char *)v + sizeof(struct snexpr_var); + strncpy(v->name, s, len); + v->name[len] = '\0'; + vars->head = v; + return v; } - v = (struct snexpr_var *)calloc(1, sizeof(struct snexpr_var) + len + 1); - if(v == NULL) { - return NULL; /* allocation failed */ - } - memset(v, 0, sizeof(struct snexpr_var) + len + 1); - v->next = vars->head; - v->name = (char *)v + sizeof(struct snexpr_var); - strncpy(v->name, s, len); - v->name[len] = '\0'; - vars->head = v; - return v; -} - -static int to_int(float x) -{ - if(isnan(x)) { - return 0; - } else if(isinf(x) != 0) { - return INT_MAX * isinf(x); - } else { - return (int)x; + + static int to_int(float x) + { + if(isnan(x)) { + return 0; + } else if(isinf(x) != 0) { + return INT_MAX * isinf(x); + } else { + return (int)x; + } } -} -static int snexpr_format_num(char **out, float value) -{ - int ret = 0; - *out = (char*)malloc(24*sizeof(char)); - if(*out==NULL) { - return -1; - } - if(value - (long)value != 0) { + static int snexpr_format_num(char **out, float value) + { + int ret = 0; + *out = (char *)malloc(24 * sizeof(char)); + if(*out == NULL) { + return -1; + } + if(value - (long)value != 0) { #ifdef SNEXPR_FLOAT_FULLPREC - ret = snprintf(*out, 24, "%g", value); + ret = snprintf(*out, 24, "%g", value); #else ret = snprintf(*out, 24, "%.4g", value); #endif - } else { - ret = snprintf(*out, 24, "%lld", (long long)value); - } - if((ret < 0) || (ret >= 24)) { - free(*out); - *out = NULL; - return -2; + } else { + ret = snprintf(*out, 24, "%lld", (long long)value); + } + if((ret < 0) || (ret >= 24)) { + free(*out); + *out = NULL; + return -2; + } + return 0; } - return 0; -} -static struct snexpr *snexpr_convert_num(float value, unsigned int ctype) -{ - struct snexpr *e = (struct snexpr *)malloc(sizeof(struct snexpr)); - if(e == NULL) { - return NULL; - } - memset(e, 0, sizeof(struct snexpr)); + static struct snexpr *snexpr_convert_num(float value, unsigned int ctype) + { + struct snexpr *e = (struct snexpr *)malloc(sizeof(struct snexpr)); + if(e == NULL) { + return NULL; + } + memset(e, 0, sizeof(struct snexpr)); - if(ctype == SNE_OP_CONSTSTZ) { - e->eflags |= SNEXPR_EXPALLOC | SNEXPR_VALALLOC; - e->type = SNE_OP_CONSTSTZ; - snexpr_format_num(&e->param.stz.sval, value); + if(ctype == SNE_OP_CONSTSTZ) { + e->eflags |= SNEXPR_EXPALLOC | SNEXPR_VALALLOC; + e->type = SNE_OP_CONSTSTZ; + snexpr_format_num(&e->param.stz.sval, value); + return e; + } + + e->eflags |= SNEXPR_EXPALLOC; + e->type = SNE_OP_CONSTNUM; + e->param.num.nval = value; return e; } - e->eflags |= SNEXPR_EXPALLOC; - e->type = SNE_OP_CONSTNUM; - e->param.num.nval = value; - return e; -} + static struct snexpr *snexpr_convert_stzl( + char *value, size_t len, unsigned int ctype) + { + struct snexpr *e = NULL; + if(value == NULL) { + return NULL; + } + e = (struct snexpr *)malloc(sizeof(struct snexpr)); + if(e == NULL) { + return NULL; + } + memset(e, 0, sizeof(struct snexpr)); -static struct snexpr *snexpr_convert_stzl(char *value, size_t len, unsigned int ctype) -{ - struct snexpr *e = NULL; - if(value==NULL) { - return NULL; - } - e = (struct snexpr *)malloc(sizeof(struct snexpr)); - if(e == NULL) { - return NULL; - } - memset(e, 0, sizeof(struct snexpr)); + if(ctype == SNE_OP_CONSTNUM) { + e->eflags |= SNEXPR_EXPALLOC; + e->type = SNE_OP_CONSTNUM; + e->param.num.nval = snexpr_parse_number(value, len); + return e; + } - if(ctype == SNE_OP_CONSTNUM) { - e->eflags |= SNEXPR_EXPALLOC; - e->type = SNE_OP_CONSTNUM; - e->param.num.nval = snexpr_parse_number(value, len); + e->param.stz.sval = (char *)malloc(len + 1); + if(e->param.stz.sval == NULL) { + free(e); + return NULL; + } + e->eflags |= SNEXPR_EXPALLOC | SNEXPR_VALALLOC; + e->type = SNE_OP_CONSTSTZ; + memcpy(e->param.stz.sval, value, len); + e->param.stz.sval[len] = '\0'; return e; } - e->param.stz.sval = (char *)malloc(len + 1); - if(e->param.stz.sval == NULL) { - free(e); - return NULL; - } - e->eflags |= SNEXPR_EXPALLOC | SNEXPR_VALALLOC; - e->type = SNE_OP_CONSTSTZ; - memcpy(e->param.stz.sval, value, len); - e->param.stz.sval[len] = '\0'; - return e; -} - -static struct snexpr *snexpr_convert_stz(char *value, unsigned int ctype) -{ - if(value==NULL) { - return NULL; + static struct snexpr *snexpr_convert_stz(char *value, unsigned int ctype) + { + if(value == NULL) { + return NULL; + } + + return snexpr_convert_stzl(value, strlen(value), ctype); } - return snexpr_convert_stzl(value, strlen(value), ctype); -} + static struct snexpr *snexpr_concat_strz(char *value0, char *value1) + { + struct snexpr *e = (struct snexpr *)malloc(sizeof(struct snexpr)); + if(e == NULL) { + return NULL; + } + memset(e, 0, sizeof(struct snexpr)); -static struct snexpr *snexpr_concat_strz(char *value0, char *value1) -{ - struct snexpr *e = (struct snexpr *)malloc(sizeof(struct snexpr)); - if(e == NULL) { - return NULL; + e->param.stz.sval = (char *)malloc(strlen(value0) + strlen(value1) + 1); + if(e->param.stz.sval == NULL) { + free(e); + return NULL; + } + e->eflags |= SNEXPR_EXPALLOC | SNEXPR_VALALLOC; + e->type = SNE_OP_CONSTSTZ; + strcpy(e->param.stz.sval, value0); + strcat(e->param.stz.sval, value1); + return e; } - memset(e, 0, sizeof(struct snexpr)); - e->param.stz.sval = (char *)malloc(strlen(value0) + strlen(value1) + 1); - if(e->param.stz.sval == NULL) { + static void snexpr_result_free(struct snexpr *e) + { + if(e == NULL) { + return; + } + if((e->eflags & SNEXPR_VALALLOC) && (e->type == SNE_OP_CONSTSTZ) + && (e->param.stz.sval != NULL)) { + free(e->param.stz.sval); + } + if(!(e->eflags & SNEXPR_EXPALLOC)) { + return; + } free(e); - return NULL; } - e->eflags |= SNEXPR_EXPALLOC | SNEXPR_VALALLOC; - e->type = SNE_OP_CONSTSTZ; - strcpy(e->param.stz.sval, value0); - strcat(e->param.stz.sval, value1); - return e; -} - -static void snexpr_result_free(struct snexpr *e) -{ - if(e == NULL) { - return; - } - if((e->eflags & SNEXPR_VALALLOC) && (e->type == SNE_OP_CONSTSTZ) - && (e->param.stz.sval != NULL)) { - free(e->param.stz.sval); - } - if(!(e->eflags & SNEXPR_EXPALLOC)) { - return; - } - free(e); -} -#define snexpr_eval_check_val(val, vtype) do { \ - if(val==NULL || val->type != vtype) { \ - goto error; \ - } \ +#define snexpr_eval_check_val(val, vtype) \ + do { \ + if(val == NULL || val->type != vtype) { \ + goto error; \ + } \ } while(0) -#define snexpr_eval_check_null(val, vtype) do { \ - if(val==NULL) { \ - goto error; \ - } \ +#define snexpr_eval_check_null(val, vtype) \ + do { \ + if(val == NULL) { \ + goto error; \ + } \ } while(0) -#define snexpr_eval_cmp(_CMPOP_) do { \ - rv0 = snexpr_eval(&e->param.op.args.buf[0]); \ - snexpr_eval_check_null(rv0, SNE_OP_CONSTNUM); \ - rv1 = snexpr_eval(&e->param.op.args.buf[1]); \ - snexpr_eval_check_null(rv1, SNE_OP_CONSTNUM); \ - if(rv0->type == SNE_OP_CONSTSTZ) { \ - /* string comparison */ \ - if(rv1->type == SNE_OP_CONSTNUM) { \ - tv = snexpr_convert_num(rv1->param.num.nval, SNE_OP_CONSTSTZ); \ - snexpr_result_free(rv1); \ - rv1 = tv; \ - snexpr_eval_check_val(rv1, SNE_OP_CONSTSTZ); \ - } \ - if(strcmp(rv0->param.stz.sval, rv1->param.stz.sval) _CMPOP_ 0) { \ - lv = snexpr_convert_num(1, SNE_OP_CONSTNUM); \ - } else { \ - lv = snexpr_convert_num(0, SNE_OP_CONSTNUM); \ - } \ - } else { \ - /* number comparison */ \ - if(rv1->type == SNE_OP_CONSTSTZ) { \ - tv = snexpr_convert_stz(rv1->param.stz.sval, SNE_OP_CONSTNUM); \ - snexpr_result_free(rv1); \ - rv1 = tv; \ - snexpr_eval_check_val(rv1, SNE_OP_CONSTNUM); \ - } \ - lv = snexpr_convert_num( \ - rv0->param.num.nval _CMPOP_ rv1->param.num.nval, SNE_OP_CONSTNUM); \ - } \ +#define snexpr_eval_cmp(_CMPOP_) \ + do { \ + rv0 = snexpr_eval(&e->param.op.args.buf[0]); \ + snexpr_eval_check_null(rv0, SNE_OP_CONSTNUM); \ + rv1 = snexpr_eval(&e->param.op.args.buf[1]); \ + snexpr_eval_check_null(rv1, SNE_OP_CONSTNUM); \ + if(rv0->type == SNE_OP_CONSTSTZ) { \ + /* string comparison */ \ + if(rv1->type == SNE_OP_CONSTNUM) { \ + tv = snexpr_convert_num(rv1->param.num.nval, SNE_OP_CONSTSTZ); \ + snexpr_result_free(rv1); \ + rv1 = tv; \ + snexpr_eval_check_val(rv1, SNE_OP_CONSTSTZ); \ + } \ + if(strcmp(rv0->param.stz.sval, rv1->param.stz.sval) _CMPOP_ 0) { \ + lv = snexpr_convert_num(1, SNE_OP_CONSTNUM); \ + } else { \ + lv = snexpr_convert_num(0, SNE_OP_CONSTNUM); \ + } \ + } else { \ + /* number comparison */ \ + if(rv1->type == SNE_OP_CONSTSTZ) { \ + tv = snexpr_convert_stz(rv1->param.stz.sval, SNE_OP_CONSTNUM); \ + snexpr_result_free(rv1); \ + rv1 = tv; \ + snexpr_eval_check_val(rv1, SNE_OP_CONSTNUM); \ + } \ + lv = snexpr_convert_num( \ + rv0->param.num.nval _CMPOP_ rv1->param.num.nval, \ + SNE_OP_CONSTNUM); \ + } \ } while(0) -static struct snexpr *snexpr_eval(struct snexpr *e) -{ - float n; - struct snexpr *lv = NULL; - struct snexpr *rv0 = NULL; - struct snexpr *rv1 = NULL; - struct snexpr *tv = NULL; - - switch(e->type) { - case SNE_OP_UNARY_MINUS: - rv0 = snexpr_eval(&e->param.op.args.buf[0]); - snexpr_eval_check_val(rv0, SNE_OP_CONSTNUM); - lv = snexpr_convert_num(-(rv0->param.num.nval), SNE_OP_CONSTNUM); - goto done; - case SNE_OP_UNARY_LOGICAL_NOT: - rv0 = snexpr_eval(&e->param.op.args.buf[0]); - snexpr_eval_check_val(rv0, SNE_OP_CONSTNUM); - lv = snexpr_convert_num(!(rv0->param.num.nval), SNE_OP_CONSTNUM); - goto done; - case SNE_OP_UNARY_BITWISE_NOT: - rv0 = snexpr_eval(&e->param.op.args.buf[0]); - snexpr_eval_check_val(rv0, SNE_OP_CONSTNUM); - lv = snexpr_convert_num(~(to_int(rv0->param.num.nval)), SNE_OP_CONSTNUM); - goto done; - case SNE_OP_POWER: - rv0 = snexpr_eval(&e->param.op.args.buf[0]); - snexpr_eval_check_val(rv0, SNE_OP_CONSTNUM); - rv1 = snexpr_eval(&e->param.op.args.buf[1]); - snexpr_eval_check_val(rv1, SNE_OP_CONSTNUM); - lv = snexpr_convert_num( - powf(rv0->param.num.nval, rv1->param.num.nval), - SNE_OP_CONSTNUM); - goto done; - case SNE_OP_MULTIPLY: - rv0 = snexpr_eval(&e->param.op.args.buf[0]); - snexpr_eval_check_val(rv0, SNE_OP_CONSTNUM); - rv1 = snexpr_eval(&e->param.op.args.buf[1]); - snexpr_eval_check_val(rv1, SNE_OP_CONSTNUM); - lv = snexpr_convert_num( - rv0->param.num.nval * rv1->param.num.nval, SNE_OP_CONSTNUM); - goto done; - case SNE_OP_DIVIDE: - rv0 = snexpr_eval(&e->param.op.args.buf[0]); - snexpr_eval_check_val(rv0, SNE_OP_CONSTNUM); - rv1 = snexpr_eval(&e->param.op.args.buf[1]); - snexpr_eval_check_val(rv1, SNE_OP_CONSTNUM); - if(rv1->param.num.nval == 0) { - goto error; - } - lv = snexpr_convert_num( - rv0->param.num.nval / rv1->param.num.nval, SNE_OP_CONSTNUM); - goto done; - case SNE_OP_REMAINDER: - rv0 = snexpr_eval(&e->param.op.args.buf[0]); - snexpr_eval_check_val(rv0, SNE_OP_CONSTNUM); - rv1 = snexpr_eval(&e->param.op.args.buf[1]); - snexpr_eval_check_val(rv1, SNE_OP_CONSTNUM); - lv = snexpr_convert_num( - fmodf(rv0->param.num.nval, rv1->param.num.nval), - SNE_OP_CONSTNUM); - goto done; - case SNE_OP_PLUS: - rv0 = snexpr_eval(&e->param.op.args.buf[0]); - snexpr_eval_check_null(rv0, SNE_OP_CONSTNUM); - rv1 = snexpr_eval(&e->param.op.args.buf[1]); - snexpr_eval_check_null(rv1, SNE_OP_CONSTNUM); - if(rv0->type == SNE_OP_CONSTSTZ) { - /* string concatenation */ - if(rv1->type == SNE_OP_CONSTNUM) { - tv = snexpr_convert_num(rv1->param.num.nval, SNE_OP_CONSTSTZ); - snexpr_result_free(rv1); - rv1 = tv; - snexpr_eval_check_val(rv1, SNE_OP_CONSTSTZ); - } - lv = snexpr_concat_strz(rv0->param.stz.sval, rv1->param.stz.sval); - } else { - /* add */ - if(rv1->type == SNE_OP_CONSTSTZ) { - tv = snexpr_convert_stz(rv1->param.stz.sval, SNE_OP_CONSTNUM); - snexpr_result_free(rv1); - rv1 = tv; - snexpr_eval_check_val(rv1, SNE_OP_CONSTNUM); + static struct snexpr *snexpr_eval(struct snexpr *e) + { + float n; + struct snexpr *lv = NULL; + struct snexpr *rv0 = NULL; + struct snexpr *rv1 = NULL; + struct snexpr *tv = NULL; + + switch(e->type) { + case SNE_OP_UNARY_MINUS: + rv0 = snexpr_eval(&e->param.op.args.buf[0]); + snexpr_eval_check_val(rv0, SNE_OP_CONSTNUM); + lv = snexpr_convert_num( + -(rv0->param.num.nval), SNE_OP_CONSTNUM); + goto done; + case SNE_OP_UNARY_LOGICAL_NOT: + rv0 = snexpr_eval(&e->param.op.args.buf[0]); + snexpr_eval_check_val(rv0, SNE_OP_CONSTNUM); + lv = snexpr_convert_num( + !(rv0->param.num.nval), SNE_OP_CONSTNUM); + goto done; + case SNE_OP_UNARY_BITWISE_NOT: + rv0 = snexpr_eval(&e->param.op.args.buf[0]); + snexpr_eval_check_val(rv0, SNE_OP_CONSTNUM); + lv = snexpr_convert_num( + ~(to_int(rv0->param.num.nval)), SNE_OP_CONSTNUM); + goto done; + case SNE_OP_POWER: + rv0 = snexpr_eval(&e->param.op.args.buf[0]); + snexpr_eval_check_val(rv0, SNE_OP_CONSTNUM); + rv1 = snexpr_eval(&e->param.op.args.buf[1]); + snexpr_eval_check_val(rv1, SNE_OP_CONSTNUM); + lv = snexpr_convert_num( + powf(rv0->param.num.nval, rv1->param.num.nval), + SNE_OP_CONSTNUM); + goto done; + case SNE_OP_MULTIPLY: + rv0 = snexpr_eval(&e->param.op.args.buf[0]); + snexpr_eval_check_val(rv0, SNE_OP_CONSTNUM); + rv1 = snexpr_eval(&e->param.op.args.buf[1]); + snexpr_eval_check_val(rv1, SNE_OP_CONSTNUM); + lv = snexpr_convert_num( + rv0->param.num.nval * rv1->param.num.nval, + SNE_OP_CONSTNUM); + goto done; + case SNE_OP_DIVIDE: + rv0 = snexpr_eval(&e->param.op.args.buf[0]); + snexpr_eval_check_val(rv0, SNE_OP_CONSTNUM); + rv1 = snexpr_eval(&e->param.op.args.buf[1]); + snexpr_eval_check_val(rv1, SNE_OP_CONSTNUM); + if(rv1->param.num.nval == 0) { + goto error; } lv = snexpr_convert_num( - rv0->param.num.nval + rv1->param.num.nval, SNE_OP_CONSTNUM); - } - goto done; - case SNE_OP_MINUS: - rv0 = snexpr_eval(&e->param.op.args.buf[0]); - snexpr_eval_check_val(rv0, SNE_OP_CONSTNUM); - rv1 = snexpr_eval(&e->param.op.args.buf[1]); - snexpr_eval_check_val(rv1, SNE_OP_CONSTNUM); - lv = snexpr_convert_num( - rv0->param.num.nval - rv1->param.num.nval, SNE_OP_CONSTNUM); - goto done; - case SNE_OP_SHL: - rv0 = snexpr_eval(&e->param.op.args.buf[0]); - snexpr_eval_check_val(rv0, SNE_OP_CONSTNUM); - rv1 = snexpr_eval(&e->param.op.args.buf[1]); - snexpr_eval_check_val(rv1, SNE_OP_CONSTNUM); - lv = snexpr_convert_num( - to_int(rv0->param.num.nval) << to_int(rv1->param.num.nval), - SNE_OP_CONSTNUM); - goto done; - case SNE_OP_SHR: - rv0 = snexpr_eval(&e->param.op.args.buf[0]); - snexpr_eval_check_val(rv0, SNE_OP_CONSTNUM); - rv1 = snexpr_eval(&e->param.op.args.buf[1]); - snexpr_eval_check_val(rv1, SNE_OP_CONSTNUM); - lv = snexpr_convert_num( - to_int(rv0->param.num.nval) >> to_int(rv1->param.num.nval), - SNE_OP_CONSTNUM); - goto done; - case SNE_OP_LT: - snexpr_eval_cmp(<); - goto done; - case SNE_OP_LE: - snexpr_eval_cmp(<=); - goto done; - case SNE_OP_GT: - snexpr_eval_cmp(>); - goto done; - case SNE_OP_GE: - snexpr_eval_cmp(>=); - goto done; - case SNE_OP_EQ: - snexpr_eval_cmp(==); - goto done; - case SNE_OP_NE: - snexpr_eval_cmp(!=); - goto done; - case SNE_OP_BITWISE_AND: - rv0 = snexpr_eval(&e->param.op.args.buf[0]); - snexpr_eval_check_val(rv0, SNE_OP_CONSTNUM); - rv1 = snexpr_eval(&e->param.op.args.buf[1]); - snexpr_eval_check_val(rv1, SNE_OP_CONSTNUM); - lv = snexpr_convert_num( - to_int(rv0->param.num.nval) & to_int(rv1->param.num.nval), - SNE_OP_CONSTNUM); - goto done; - case SNE_OP_BITWISE_OR: - rv0 = snexpr_eval(&e->param.op.args.buf[0]); - snexpr_eval_check_val(rv0, SNE_OP_CONSTNUM); - rv1 = snexpr_eval(&e->param.op.args.buf[1]); - snexpr_eval_check_val(rv1, SNE_OP_CONSTNUM); - lv = snexpr_convert_num( - to_int(rv0->param.num.nval) | to_int(rv1->param.num.nval), - SNE_OP_CONSTNUM); - goto done; - case SNE_OP_BITWISE_XOR: - rv0 = snexpr_eval(&e->param.op.args.buf[0]); - snexpr_eval_check_val(rv0, SNE_OP_CONSTNUM); - rv1 = snexpr_eval(&e->param.op.args.buf[1]); - snexpr_eval_check_val(rv1, SNE_OP_CONSTNUM); - lv = snexpr_convert_num( - to_int(rv0->param.num.nval) ^ to_int(rv1->param.num.nval), - SNE_OP_CONSTNUM); - goto done; - case SNE_OP_LOGICAL_AND: - rv0 = snexpr_eval(&e->param.op.args.buf[0]); - n = rv0->param.num.nval; - if(n != 0) { + rv0->param.num.nval / rv1->param.num.nval, + SNE_OP_CONSTNUM); + goto done; + case SNE_OP_REMAINDER: + rv0 = snexpr_eval(&e->param.op.args.buf[0]); + snexpr_eval_check_val(rv0, SNE_OP_CONSTNUM); rv1 = snexpr_eval(&e->param.op.args.buf[1]); - n = rv1->param.num.nval; - if(n != 0) { - lv = snexpr_convert_num(n, SNE_OP_CONSTNUM); - goto done; + snexpr_eval_check_val(rv1, SNE_OP_CONSTNUM); + lv = snexpr_convert_num( + fmodf(rv0->param.num.nval, rv1->param.num.nval), + SNE_OP_CONSTNUM); + goto done; + case SNE_OP_PLUS: + rv0 = snexpr_eval(&e->param.op.args.buf[0]); + snexpr_eval_check_null(rv0, SNE_OP_CONSTNUM); + rv1 = snexpr_eval(&e->param.op.args.buf[1]); + snexpr_eval_check_null(rv1, SNE_OP_CONSTNUM); + if(rv0->type == SNE_OP_CONSTSTZ) { + /* string concatenation */ + if(rv1->type == SNE_OP_CONSTNUM) { + tv = snexpr_convert_num( + rv1->param.num.nval, SNE_OP_CONSTSTZ); + snexpr_result_free(rv1); + rv1 = tv; + snexpr_eval_check_val(rv1, SNE_OP_CONSTSTZ); + } + lv = snexpr_concat_strz( + rv0->param.stz.sval, rv1->param.stz.sval); + } else { + /* add */ + if(rv1->type == SNE_OP_CONSTSTZ) { + tv = snexpr_convert_stz( + rv1->param.stz.sval, SNE_OP_CONSTNUM); + snexpr_result_free(rv1); + rv1 = tv; + snexpr_eval_check_val(rv1, SNE_OP_CONSTNUM); + } + lv = snexpr_convert_num( + rv0->param.num.nval + rv1->param.num.nval, + SNE_OP_CONSTNUM); } - } - lv = snexpr_convert_num(0, SNE_OP_CONSTNUM); - goto done; - case SNE_OP_LOGICAL_OR: - rv0 = snexpr_eval(&e->param.op.args.buf[0]); - n = rv0->param.num.nval; - if(n != 0 && !isnan(n)) { - lv = snexpr_convert_num(n, SNE_OP_CONSTNUM); goto done; - } else { + case SNE_OP_MINUS: + rv0 = snexpr_eval(&e->param.op.args.buf[0]); + snexpr_eval_check_val(rv0, SNE_OP_CONSTNUM); rv1 = snexpr_eval(&e->param.op.args.buf[1]); - n = rv1->param.num.nval; + snexpr_eval_check_val(rv1, SNE_OP_CONSTNUM); + lv = snexpr_convert_num( + rv0->param.num.nval - rv1->param.num.nval, + SNE_OP_CONSTNUM); + goto done; + case SNE_OP_SHL: + rv0 = snexpr_eval(&e->param.op.args.buf[0]); + snexpr_eval_check_val(rv0, SNE_OP_CONSTNUM); + rv1 = snexpr_eval(&e->param.op.args.buf[1]); + snexpr_eval_check_val(rv1, SNE_OP_CONSTNUM); + lv = snexpr_convert_num(to_int(rv0->param.num.nval) + << to_int(rv1->param.num.nval), + SNE_OP_CONSTNUM); + goto done; + case SNE_OP_SHR: + rv0 = snexpr_eval(&e->param.op.args.buf[0]); + snexpr_eval_check_val(rv0, SNE_OP_CONSTNUM); + rv1 = snexpr_eval(&e->param.op.args.buf[1]); + snexpr_eval_check_val(rv1, SNE_OP_CONSTNUM); + lv = snexpr_convert_num(to_int(rv0->param.num.nval) + >> to_int(rv1->param.num.nval), + SNE_OP_CONSTNUM); + goto done; + case SNE_OP_LT: + snexpr_eval_cmp(<); + goto done; + case SNE_OP_LE: + snexpr_eval_cmp(<=); + goto done; + case SNE_OP_GT: + snexpr_eval_cmp(>); + goto done; + case SNE_OP_GE: + snexpr_eval_cmp(>=); + goto done; + case SNE_OP_EQ: + snexpr_eval_cmp(==); + goto done; + case SNE_OP_NE: + snexpr_eval_cmp(!=); + goto done; + case SNE_OP_BITWISE_AND: + rv0 = snexpr_eval(&e->param.op.args.buf[0]); + snexpr_eval_check_val(rv0, SNE_OP_CONSTNUM); + rv1 = snexpr_eval(&e->param.op.args.buf[1]); + snexpr_eval_check_val(rv1, SNE_OP_CONSTNUM); + lv = snexpr_convert_num(to_int(rv0->param.num.nval) + & to_int(rv1->param.num.nval), + SNE_OP_CONSTNUM); + goto done; + case SNE_OP_BITWISE_OR: + rv0 = snexpr_eval(&e->param.op.args.buf[0]); + snexpr_eval_check_val(rv0, SNE_OP_CONSTNUM); + rv1 = snexpr_eval(&e->param.op.args.buf[1]); + snexpr_eval_check_val(rv1, SNE_OP_CONSTNUM); + lv = snexpr_convert_num(to_int(rv0->param.num.nval) + | to_int(rv1->param.num.nval), + SNE_OP_CONSTNUM); + goto done; + case SNE_OP_BITWISE_XOR: + rv0 = snexpr_eval(&e->param.op.args.buf[0]); + snexpr_eval_check_val(rv0, SNE_OP_CONSTNUM); + rv1 = snexpr_eval(&e->param.op.args.buf[1]); + snexpr_eval_check_val(rv1, SNE_OP_CONSTNUM); + lv = snexpr_convert_num(to_int(rv0->param.num.nval) + ^ to_int(rv1->param.num.nval), + SNE_OP_CONSTNUM); + goto done; + case SNE_OP_LOGICAL_AND: + rv0 = snexpr_eval(&e->param.op.args.buf[0]); + n = rv0->param.num.nval; if(n != 0) { + rv1 = snexpr_eval(&e->param.op.args.buf[1]); + n = rv1->param.num.nval; + if(n != 0) { + lv = snexpr_convert_num(n, SNE_OP_CONSTNUM); + goto done; + } + } + lv = snexpr_convert_num(0, SNE_OP_CONSTNUM); + goto done; + case SNE_OP_LOGICAL_OR: + rv0 = snexpr_eval(&e->param.op.args.buf[0]); + n = rv0->param.num.nval; + if(n != 0 && !isnan(n)) { lv = snexpr_convert_num(n, SNE_OP_CONSTNUM); goto done; + } else { + rv1 = snexpr_eval(&e->param.op.args.buf[1]); + n = rv1->param.num.nval; + if(n != 0) { + lv = snexpr_convert_num(n, SNE_OP_CONSTNUM); + goto done; + } } - } - lv = snexpr_convert_num(0, SNE_OP_CONSTNUM); - goto done; - case SNE_OP_ASSIGN: - rv1 = snexpr_eval(&e->param.op.args.buf[1]); - snexpr_eval_check_null(rv1, SNE_OP_CONSTNUM); - if(sne_vec_nth(&e->param.op.args, 0).type == SNE_OP_VAR) { - if(e->param.op.args.buf[0].param.var.vref->evflags & SNEXPR_VALALLOC) { - if(e->param.op.args.buf[0].param.var.vref->v.sval!=NULL) { - free(e->param.op.args.buf[0].param.var.vref->v.sval); - e->param.op.args.buf[0].param.var.vref->v.sval = NULL; + lv = snexpr_convert_num(0, SNE_OP_CONSTNUM); + goto done; + case SNE_OP_ASSIGN: + rv1 = snexpr_eval(&e->param.op.args.buf[1]); + snexpr_eval_check_null(rv1, SNE_OP_CONSTNUM); + if(sne_vec_nth(&e->param.op.args, 0).type == SNE_OP_VAR) { + if(e->param.op.args.buf[0].param.var.vref->evflags + & SNEXPR_VALALLOC) { + if(e->param.op.args.buf[0].param.var.vref->v.sval + != NULL) { + free(e->param.op.args.buf[0] + .param.var.vref->v.sval); + e->param.op.args.buf[0].param.var.vref->v.sval = + NULL; + } + e->param.op.args.buf[0].param.var.vref->evflags &= + ~(SNEXPR_TSTRING | SNEXPR_VALALLOC); + } + if(rv1->type == SNE_OP_CONSTSTZ) { + e->param.op.args.buf[0].param.var.vref->v.sval = + strdup(rv1->param.stz.sval); + e->param.op.args.buf[0].param.var.vref->evflags |= + SNEXPR_VALASSIGN | SNEXPR_TSTRING + | SNEXPR_VALALLOC; + lv = snexpr_convert_stz( + rv1->param.stz.sval, SNE_OP_CONSTSTZ); + } else { + n = rv1->param.num.nval; + e->param.op.args.buf[0].param.var.vref->v.nval = n; + e->param.op.args.buf[0].param.var.vref->evflags |= + SNEXPR_VALASSIGN; + lv = snexpr_convert_num(n, SNE_OP_CONSTNUM); } - e->param.op.args.buf[0].param.var.vref->evflags &= ~(SNEXPR_TSTRING|SNEXPR_VALALLOC); } + goto done; + case SNE_OP_COMMA: + rv0 = snexpr_eval(&e->param.op.args.buf[0]); + rv1 = snexpr_eval(&e->param.op.args.buf[1]); if(rv1->type == SNE_OP_CONSTSTZ) { - e->param.op.args.buf[0].param.var.vref->v.sval = strdup(rv1->param.stz.sval); - e->param.op.args.buf[0].param.var.vref->evflags |= SNEXPR_VALASSIGN|SNEXPR_TSTRING|SNEXPR_VALALLOC; - lv = snexpr_convert_stz(rv1->param.stz.sval, SNE_OP_CONSTSTZ); + lv = snexpr_convert_stz( + rv1->param.stz.sval, SNE_OP_CONSTSTZ); } else { - n = rv1->param.num.nval; - e->param.op.args.buf[0].param.var.vref->v.nval = n; - e->param.op.args.buf[0].param.var.vref->evflags |= SNEXPR_VALASSIGN; - lv = snexpr_convert_num(n, SNE_OP_CONSTNUM); + lv = snexpr_convert_num( + rv1->param.num.nval, SNE_OP_CONSTNUM); } - } - goto done; - case SNE_OP_COMMA: - rv0 = snexpr_eval(&e->param.op.args.buf[0]); - rv1 = snexpr_eval(&e->param.op.args.buf[1]); - if(rv1->type == SNE_OP_CONSTSTZ) { - lv = snexpr_convert_stz(rv1->param.stz.sval, SNE_OP_CONSTSTZ); - } else { - lv = snexpr_convert_num(rv1->param.num.nval, SNE_OP_CONSTNUM); - } - goto done; - case SNE_OP_CONSTNUM: - lv = snexpr_convert_num(e->param.num.nval, SNE_OP_CONSTNUM); - goto done; - case SNE_OP_CONSTSTZ: - lv = snexpr_convert_stz(e->param.stz.sval, SNE_OP_CONSTSTZ); - goto done; - case SNE_OP_VAR: - if((_snexternval_cbf == NULL) - || (e->param.var.vref->evflags & SNEXPR_VALASSIGN)) { - if(e->param.var.vref->evflags & SNEXPR_TSTRING) { - lv = snexpr_convert_stz(e->param.var.vref->v.sval, SNE_OP_CONSTSTZ); + goto done; + case SNE_OP_CONSTNUM: + lv = snexpr_convert_num(e->param.num.nval, SNE_OP_CONSTNUM); + goto done; + case SNE_OP_CONSTSTZ: + lv = snexpr_convert_stz(e->param.stz.sval, SNE_OP_CONSTSTZ); + goto done; + case SNE_OP_VAR: + if((_snexternval_cbf == NULL) + || (e->param.var.vref->evflags & SNEXPR_VALASSIGN)) { + if(e->param.var.vref->evflags & SNEXPR_TSTRING) { + lv = snexpr_convert_stz( + e->param.var.vref->v.sval, SNE_OP_CONSTSTZ); + } else { + lv = snexpr_convert_num( + e->param.var.vref->v.nval, SNE_OP_CONSTNUM); + } } else { - lv = snexpr_convert_num(e->param.var.vref->v.nval, SNE_OP_CONSTNUM); + lv = _snexternval_cbf(e->param.var.vref->name); } - } else { - lv = _snexternval_cbf(e->param.var.vref->name); - } - goto done; - case SNE_OP_FUNC: - rv0 = e->param.func.f->f(e->param.func.f, &e->param.func.args, - e->param.func.context); - if(rv0->type == SNE_OP_CONSTSTZ) { - lv = snexpr_convert_stz(rv0->param.stz.sval, SNE_OP_CONSTSTZ); - } else { - lv = snexpr_convert_num(rv0->param.num.nval, SNE_OP_CONSTNUM); - } - goto done; - default: - lv = snexpr_convert_num(NAN, SNE_OP_CONSTNUM); - goto done; - } - -done: - if(rv0 != NULL) { - snexpr_result_free(rv0); - } - if(rv1 != NULL) { - snexpr_result_free(rv1); - } - return lv; - -error: - if(rv0 != NULL) { - snexpr_result_free(rv0); - } - if(rv1 != NULL) { - snexpr_result_free(rv1); - } - return NULL; - -} - -static int snexpr_next_token(const char *s, size_t len, int *flags) -{ - unsigned int i = 0; - char b; - int bsf = 0; - if(len == 0) { - return 0; - } - char c = s[0]; - if(c == '#') { - for(; i < len && s[i] != '\n'; i++) - ; - return i; - } else if(c == '\n') { - for(; i < len && isspace(s[i]); i++) - ; - if(*flags & SNEXPR_TOP) { - if(i == len || s[i] == ')') { - *flags = *flags & (~SNEXPR_COMMA); - } else { - *flags = SNEXPR_TNUMBER | SNEXPR_TSTRING | SNEXPR_TWORD | SNEXPR_TOPEN - | SNEXPR_COMMA; - } + goto done; + case SNE_OP_FUNC: + rv0 = e->param.func.f->f(e->param.func.f, &e->param.func.args, + e->param.func.context); + if(rv0->type == SNE_OP_CONSTSTZ) { + lv = snexpr_convert_stz( + rv0->param.stz.sval, SNE_OP_CONSTSTZ); + } else { + lv = snexpr_convert_num( + rv0->param.num.nval, SNE_OP_CONSTNUM); + } + goto done; + default: + lv = snexpr_convert_num(NAN, SNE_OP_CONSTNUM); + goto done; } - return i; - } else if(isspace(c)) { - while(i < len && isspace(s[i]) && s[i] != '\n') { - i++; + + done: + if(rv0 != NULL) { + snexpr_result_free(rv0); } - return i; - } else if(isdigit(c)) { - if((*flags & SNEXPR_TNUMBER) == 0) { - return -1; // unexpected number + if(rv1 != NULL) { + snexpr_result_free(rv1); } - *flags = SNEXPR_TOP | SNEXPR_TCLOSE; - while((c == '.' || isdigit(c)) && i < len) { - i++; - c = s[i]; + return lv; + + error: + if(rv0 != NULL) { + snexpr_result_free(rv0); } - return i; - } else if(c == '"' || c == '\'') { - if((*flags & SNEXPR_TSTRING) == 0) { - return -1; // unexpected string + if(rv1 != NULL) { + snexpr_result_free(rv1); } - if(i == len - 1) { - return -1; // invalud start of string + return NULL; + } + + static int snexpr_next_token(const char *s, size_t len, int *flags) + { + unsigned int i = 0; + char b; + int bsf = 0; + if(len == 0) { + return 0; } - *flags = SNEXPR_TOP | SNEXPR_TCLOSE; - b = c; - i++; - c = s[i]; - while(i < len && (bsf==1 || c != b)) { - if(bsf == 0 && c == '\\') { - bsf = 1; - } else { - bsf = 0; + char c = s[0]; + if(c == '#') { + for(; i < len && s[i] != '\n'; i++) + ; + return i; + } else if(c == '\n') { + for(; i < len && isspace(s[i]); i++) + ; + if(*flags & SNEXPR_TOP) { + if(i == len || s[i] == ')') { + *flags = *flags & (~SNEXPR_COMMA); + } else { + *flags = SNEXPR_TNUMBER | SNEXPR_TSTRING | SNEXPR_TWORD + | SNEXPR_TOPEN | SNEXPR_COMMA; + } + } + return i; + } else if(isspace(c)) { + while(i < len && isspace(s[i]) && s[i] != '\n') { + i++; + } + return i; + } else if(isdigit(c)) { + if((*flags & SNEXPR_TNUMBER) == 0) { + return -1; // unexpected number } - i++; - c = s[i]; - } - return i + 1; - } else if(isfirstvarchr(c)) { - if((*flags & SNEXPR_TWORD) == 0) { - return -2; // unexpected word - } - *flags = SNEXPR_TOP | SNEXPR_TOPEN | SNEXPR_TCLOSE; - while((isvarchr(c)) && i < len) { - i++; - c = s[i]; - } - return i; - } else if(c == '(' || c == ')') { - if(c == '(' && (*flags & SNEXPR_TOPEN) != 0) { - *flags = SNEXPR_TNUMBER | SNEXPR_TSTRING | SNEXPR_TWORD | SNEXPR_TOPEN - | SNEXPR_TCLOSE; - } else if(c == ')' && (*flags & SNEXPR_TCLOSE) != 0) { *flags = SNEXPR_TOP | SNEXPR_TCLOSE; - } else { - return -3; // unexpected parenthesis - } - return 1; - } else { - if((*flags & SNEXPR_TOP) == 0) { - if(snexpr_op(&c, 1, 1) == SNE_OP_UNKNOWN) { - return -4; // missing expected operand + while((c == '.' || isdigit(c)) && i < len) { + i++; + c = s[i]; } - *flags = SNEXPR_TNUMBER | SNEXPR_TSTRING | SNEXPR_TWORD | SNEXPR_TOPEN - | SNEXPR_UNARY; - return 1; - } else { - int found = 0; - while(!isvarchr(c) && !isspace(c) && c != '(' && c != ')' - && i < len) { - if(snexpr_op(s, i + 1, 0) != SNE_OP_UNKNOWN) { - found = 1; - } else if(found) { - break; + return i; + } else if(c == '"' || c == '\'') { + if((*flags & SNEXPR_TSTRING) == 0) { + return -1; // unexpected string + } + if(i == len - 1) { + return -1; // invalud start of string + } + *flags = SNEXPR_TOP | SNEXPR_TCLOSE; + b = c; + i++; + c = s[i]; + while(i < len && (bsf == 1 || c != b)) { + if(bsf == 0 && c == '\\') { + bsf = 1; + } else { + bsf = 0; } i++; c = s[i]; } - if(!found) { - return -5; // unknown operator + return i + 1; + } else if(isfirstvarchr(c)) { + if((*flags & SNEXPR_TWORD) == 0) { + return -2; // unexpected word + } + *flags = SNEXPR_TOP | SNEXPR_TOPEN | SNEXPR_TCLOSE; + while((isvarchr(c)) && i < len) { + i++; + c = s[i]; } - *flags = SNEXPR_TNUMBER | SNEXPR_TSTRING | SNEXPR_TWORD | SNEXPR_TOPEN; return i; + } else if(c == '(' || c == ')') { + if(c == '(' && (*flags & SNEXPR_TOPEN) != 0) { + *flags = SNEXPR_TNUMBER | SNEXPR_TSTRING | SNEXPR_TWORD + | SNEXPR_TOPEN | SNEXPR_TCLOSE; + } else if(c == ')' && (*flags & SNEXPR_TCLOSE) != 0) { + *flags = SNEXPR_TOP | SNEXPR_TCLOSE; + } else { + return -3; // unexpected parenthesis + } + return 1; + } else { + if((*flags & SNEXPR_TOP) == 0) { + if(snexpr_op(&c, 1, 1) == SNE_OP_UNKNOWN) { + return -4; // missing expected operand + } + *flags = SNEXPR_TNUMBER | SNEXPR_TSTRING | SNEXPR_TWORD + | SNEXPR_TOPEN | SNEXPR_UNARY; + return 1; + } else { + int found = 0; + while(!isvarchr(c) && !isspace(c) && c != '(' && c != ')' + && i < len) { + if(snexpr_op(s, i + 1, 0) != SNE_OP_UNKNOWN) { + found = 1; + } else if(found) { + break; + } + i++; + c = s[i]; + } + if(!found) { + return -5; // unknown operator + } + *flags = SNEXPR_TNUMBER | SNEXPR_TSTRING | SNEXPR_TWORD + | SNEXPR_TOPEN; + return i; + } } } -} #define SNEXPR_PAREN_ALLOWED 0 #define SNEXPR_PAREN_EXPECTED 1 #define SNEXPR_PAREN_FORBIDDEN 2 -static int snexpr_bind(const char *s, size_t len, sne_vec_expr_t *es) -{ - enum snexpr_type op = snexpr_op(s, len, -1); - if(op == SNE_OP_UNKNOWN) { - return -1; - } - - if(snexpr_is_unary(op)) { - if(sne_vec_len(es) < 1) { - return -1; - } - struct snexpr arg = sne_vec_pop(es); - struct snexpr unary = snexpr_init(); - unary.type = op; - sne_vec_push(&unary.param.op.args, arg); - sne_vec_push(es, unary); - } else { - if(sne_vec_len(es) < 2) { + static int snexpr_bind(const char *s, size_t len, sne_vec_expr_t *es) + { + enum snexpr_type op = snexpr_op(s, len, -1); + if(op == SNE_OP_UNKNOWN) { return -1; } - struct snexpr b = sne_vec_pop(es); - struct snexpr a = sne_vec_pop(es); - struct snexpr binary = snexpr_init(); - binary.type = op; - if(op == SNE_OP_ASSIGN && a.type != SNE_OP_VAR) { - return -1; /* Bad assignment */ + + if(snexpr_is_unary(op)) { + if(sne_vec_len(es) < 1) { + return -1; + } + struct snexpr arg = sne_vec_pop(es); + struct snexpr unary = snexpr_init(); + unary.type = op; + sne_vec_push(&unary.param.op.args, arg); + sne_vec_push(es, unary); + } else { + if(sne_vec_len(es) < 2) { + return -1; + } + struct snexpr b = sne_vec_pop(es); + struct snexpr a = sne_vec_pop(es); + struct snexpr binary = snexpr_init(); + binary.type = op; + if(op == SNE_OP_ASSIGN && a.type != SNE_OP_VAR) { + return -1; /* Bad assignment */ + } + sne_vec_push(&binary.param.op.args, a); + sne_vec_push(&binary.param.op.args, b); + sne_vec_push(es, binary); } - sne_vec_push(&binary.param.op.args, a); - sne_vec_push(&binary.param.op.args, b); - sne_vec_push(es, binary); + return 0; } - return 0; -} - -static struct snexpr snexpr_constnum(float value) -{ - struct snexpr e = snexpr_init(); - e.type = SNE_OP_CONSTNUM; - e.param.num.nval = value; - return e; -} -static struct snexpr snexpr_varref(struct snexpr_var *v) -{ - struct snexpr e = snexpr_init(); - e.type = SNE_OP_VAR; - e.param.var.vref = v; - return e; -} + static struct snexpr snexpr_constnum(float value) + { + struct snexpr e = snexpr_init(); + e.type = SNE_OP_CONSTNUM; + e.param.num.nval = value; + return e; + } -static struct snexpr snexpr_conststr(const char *value, int len) -{ - struct snexpr e = snexpr_init(); - char *p; - int i; - int bsf = 0; - if(len < 2) { - len = 0; - } else { - /* skip the quotes */ - len -= 2; + static struct snexpr snexpr_varref(struct snexpr_var *v) + { + struct snexpr e = snexpr_init(); + e.type = SNE_OP_VAR; + e.param.var.vref = v; + return e; } - e.type = SNE_OP_CONSTSTZ; - e.param.stz.sval = malloc(len + 1); - if(e.param.stz.sval) { - if(len > 0) { - /* do not copy the quotes - start from value[1] */ - p = e.param.stz.sval; - for(i=0; i 0) { + /* do not copy the quotes - start from value[1] */ + p = e.param.stz.sval; + for(i = 0; i < len; i++) { + if(bsf == 0 && value[i + 1] == '\\') { + bsf = 1; + } else if(bsf == 1) { + bsf = 0; + switch(value[i + 1]) { + case 'n': + *p = '\n'; + break; + case 'r': + *p = '\r'; + break; + case 't': + *p = '\t'; + break; + default: + *p = value[i + 1]; + } + p++; + } else { + bsf = 0; + *p = value[i + 1]; + p++; } - p++; - } else { - bsf = 0; - *p = value[i+1]; - p++; } + *p = '\0'; + } else { + e.param.stz.sval[0] = '\0'; } - *p = '\0'; - } else { - e.param.stz.sval[0] = '\0'; } + return e; } - return e; -} -static struct snexpr snexpr_binary( - enum snexpr_type type, struct snexpr a, struct snexpr b) -{ - struct snexpr e = snexpr_init(); - e.type = type; - sne_vec_push(&e.param.op.args, a); - sne_vec_push(&e.param.op.args, b); - return e; -} - -static inline void snexpr_copy(struct snexpr *dst, struct snexpr *src) -{ - int i; - struct snexpr arg; - dst->type = src->type; - if(src->type == SNE_OP_FUNC) { - dst->param.func.f = src->param.func.f; - sne_vec_foreach(&src->param.func.args, arg, i) - { - struct snexpr tmp = snexpr_init(); - snexpr_copy(&tmp, &arg); - sne_vec_push(&dst->param.func.args, tmp); - } - if(src->param.func.f->ctxsz > 0) { - dst->param.func.context = calloc(1, src->param.func.f->ctxsz); - } - } else if(src->type == SNE_OP_CONSTNUM) { - dst->param.num.nval = src->param.num.nval; - } else if(src->type == SNE_OP_VAR) { - dst->param.var.vref = src->param.var.vref; - } else { - sne_vec_foreach(&src->param.op.args, arg, i) - { - struct snexpr tmp = snexpr_init(); - snexpr_copy(&tmp, &arg); - sne_vec_push(&dst->param.op.args, tmp); + static struct snexpr snexpr_binary( + enum snexpr_type type, struct snexpr a, struct snexpr b) + { + struct snexpr e = snexpr_init(); + e.type = type; + sne_vec_push(&e.param.op.args, a); + sne_vec_push(&e.param.op.args, b); + return e; + } + + static inline void snexpr_copy(struct snexpr *dst, struct snexpr *src) + { + int i; + struct snexpr arg; + dst->type = src->type; + if(src->type == SNE_OP_FUNC) { + dst->param.func.f = src->param.func.f; + sne_vec_foreach(&src->param.func.args, arg, i) + { + struct snexpr tmp = snexpr_init(); + snexpr_copy(&tmp, &arg); + sne_vec_push(&dst->param.func.args, tmp); + } + if(src->param.func.f->ctxsz > 0) { + dst->param.func.context = calloc(1, src->param.func.f->ctxsz); + } + } else if(src->type == SNE_OP_CONSTNUM) { + dst->param.num.nval = src->param.num.nval; + } else if(src->type == SNE_OP_VAR) { + dst->param.var.vref = src->param.var.vref; + } else { + sne_vec_foreach(&src->param.op.args, arg, i) + { + struct snexpr tmp = snexpr_init(); + snexpr_copy(&tmp, &arg); + sne_vec_push(&dst->param.op.args, tmp); + } } } -} -static void snexpr_destroy_args(struct snexpr *e); + static void snexpr_destroy_args(struct snexpr *e); -static struct snexpr *snexpr_create(const char *s, size_t len, - struct snexpr_var_list *vars, struct snexpr_func *funcs, - snexternval_cbf_t evcbf) -{ - float num; - struct snexpr_var *v; - const char *id = NULL; - size_t idn = 0; + static struct snexpr *snexpr_create(const char *s, size_t len, + struct snexpr_var_list *vars, struct snexpr_func *funcs, + snexternval_cbf_t evcbf) + { + float num; + struct snexpr_var *v; + const char *id = NULL; + size_t idn = 0; - struct snexpr *result = NULL; + struct snexpr *result = NULL; - _snexternval_cbf = evcbf; + _snexternval_cbf = evcbf; - sne_vec_expr_t es = sne_vec_init(); - sne_vec_str_t os = sne_vec_init(); - sne_vec_arg_t as = sne_vec_init(); + sne_vec_expr_t es = sne_vec_init(); + sne_vec_str_t os = sne_vec_init(); + sne_vec_arg_t as = sne_vec_init(); - struct macro - { - char *name; - sne_vec_expr_t body; - }; - sne_vec(struct macro) macros = sne_vec_init(); - - int flags = SNEXPR_TDEFAULT; - int paren = SNEXPR_PAREN_ALLOWED; - for(;;) { - int n = snexpr_next_token(s, len, &flags); - if(n == 0) { - break; - } else if(n < 0) { - goto cleanup; - } - const char *tok = s; - s = s + n; - len = len - n; - if(*tok == '#') { - continue; - } - if(flags & SNEXPR_UNARY) { - if(n == 1) { - switch(*tok) { - case '-': - tok = "-u"; - break; - case '^': - tok = "^u"; - break; - case '!': - tok = "!u"; - break; - default: - goto cleanup; + struct macro + { + char *name; + sne_vec_expr_t body; + }; + sne_vec(struct macro) macros = sne_vec_init(); + + int flags = SNEXPR_TDEFAULT; + int paren = SNEXPR_PAREN_ALLOWED; + for(;;) { + int n = snexpr_next_token(s, len, &flags); + if(n == 0) { + break; + } else if(n < 0) { + goto cleanup; + } + const char *tok = s; + s = s + n; + len = len - n; + if(*tok == '#') { + continue; + } + if(flags & SNEXPR_UNARY) { + if(n == 1) { + switch(*tok) { + case '-': + tok = "-u"; + break; + case '^': + tok = "^u"; + break; + case '!': + tok = "!u"; + break; + default: + goto cleanup; + } + n = 2; } - n = 2; } - } - if(*tok == '\n' && (flags & SNEXPR_COMMA)) { - flags = flags & (~SNEXPR_COMMA); - n = 1; - tok = ","; - } - if(isspace(*tok)) { - continue; - } - int paren_next = SNEXPR_PAREN_ALLOWED; + if(*tok == '\n' && (flags & SNEXPR_COMMA)) { + flags = flags & (~SNEXPR_COMMA); + n = 1; + tok = ","; + } + if(isspace(*tok)) { + continue; + } + int paren_next = SNEXPR_PAREN_ALLOWED; - if(idn > 0) { - if(n == 1 && *tok == '(') { - int i; - int has_macro = 0; - struct macro m; - sne_vec_foreach(¯os, m, i) - { - if(strlen(m.name) == idn && strncmp(m.name, id, idn) == 0) { - has_macro = 1; - break; + if(idn > 0) { + if(n == 1 && *tok == '(') { + int i; + int has_macro = 0; + struct macro m; + sne_vec_foreach(¯os, m, i) + { + if(strlen(m.name) == idn + && strncmp(m.name, id, idn) == 0) { + has_macro = 1; + break; + } } + if((idn == 1 && id[0] == '$') || has_macro + || snexpr_func_find(funcs, id, idn) != NULL) { + struct snexpr_string str = {id, (int)idn}; + sne_vec_push(&os, str); + paren = SNEXPR_PAREN_EXPECTED; + } else { + goto cleanup; /* invalid function name */ + } + } else if((v = snexpr_var_find(vars, id, idn)) != NULL) { + sne_vec_push(&es, snexpr_varref(v)); + paren = SNEXPR_PAREN_FORBIDDEN; } - if((idn == 1 && id[0] == '$') || has_macro - || snexpr_func_find(funcs, id, idn) != NULL) { - struct snexpr_string str = {id, (int)idn}; + id = NULL; + idn = 0; + } + + if(n == 1 && *tok == '(') { + if(paren == SNEXPR_PAREN_EXPECTED) { + struct snexpr_string str = {"{", 1}; + sne_vec_push(&os, str); + struct snexpr_arg arg = { + sne_vec_len(&os), sne_vec_len(&es), sne_vec_init()}; + sne_vec_push(&as, arg); + } else if(paren == SNEXPR_PAREN_ALLOWED) { + struct snexpr_string str = {"(", 1}; sne_vec_push(&os, str); - paren = SNEXPR_PAREN_EXPECTED; } else { - goto cleanup; /* invalid function name */ + goto cleanup; // Bad call } - } else if((v = snexpr_var_find(vars, id, idn)) != NULL) { - sne_vec_push(&es, snexpr_varref(v)); - paren = SNEXPR_PAREN_FORBIDDEN; - } - id = NULL; - idn = 0; - } - - if(n == 1 && *tok == '(') { - if(paren == SNEXPR_PAREN_EXPECTED) { - struct snexpr_string str = {"{", 1}; - sne_vec_push(&os, str); - struct snexpr_arg arg = {sne_vec_len(&os), sne_vec_len(&es), sne_vec_init()}; - sne_vec_push(&as, arg); - } else if(paren == SNEXPR_PAREN_ALLOWED) { - struct snexpr_string str = {"(", 1}; - sne_vec_push(&os, str); - } else { + } else if(paren == SNEXPR_PAREN_EXPECTED) { goto cleanup; // Bad call - } - } else if(paren == SNEXPR_PAREN_EXPECTED) { - goto cleanup; // Bad call - } else if(n == 1 && *tok == ')') { - int minlen = (sne_vec_len(&as) > 0 ? sne_vec_peek(&as).oslen : 0); - while(sne_vec_len(&os) > minlen && *sne_vec_peek(&os).s != '(' - && *sne_vec_peek(&os).s != '{') { - struct snexpr_string str = sne_vec_pop(&os); - if(snexpr_bind(str.s, str.n, &es) == -1) { - goto cleanup; + } else if(n == 1 && *tok == ')') { + int minlen = + (sne_vec_len(&as) > 0 ? sne_vec_peek(&as).oslen : 0); + while(sne_vec_len(&os) > minlen && *sne_vec_peek(&os).s != '(' + && *sne_vec_peek(&os).s != '{') { + struct snexpr_string str = sne_vec_pop(&os); + if(snexpr_bind(str.s, str.n, &es) == -1) { + goto cleanup; + } } - } - if(sne_vec_len(&os) == 0) { - goto cleanup; // Bad parens - } - struct snexpr_string str = sne_vec_pop(&os); - if(str.n == 1 && *str.s == '{') { - str = sne_vec_pop(&os); - struct snexpr_arg arg = sne_vec_pop(&as); - if(sne_vec_len(&es) > arg.eslen) { - sne_vec_push(&arg.args, sne_vec_pop(&es)); + if(sne_vec_len(&os) == 0) { + goto cleanup; // Bad parens } - if(str.n == 1 && str.s[0] == '$') { - if(sne_vec_len(&arg.args) < 1) { - sne_vec_free(&arg.args); - goto cleanup; /* too few arguments for $() function */ - } - struct snexpr *u = &sne_vec_nth(&arg.args, 0); - if(u->type != SNE_OP_VAR) { - sne_vec_free(&arg.args); - goto cleanup; /* first argument is not a variable */ - } - struct snexpr_var *v; - for(v = vars->head; v; v = v->next) { - if(v == u->param.var.vref) { - struct macro m = {v->name, arg.args}; - sne_vec_push(¯os, m); - break; - } + struct snexpr_string str = sne_vec_pop(&os); + if(str.n == 1 && *str.s == '{') { + str = sne_vec_pop(&os); + struct snexpr_arg arg = sne_vec_pop(&as); + if(sne_vec_len(&es) > arg.eslen) { + sne_vec_push(&arg.args, sne_vec_pop(&es)); } - sne_vec_push(&es, snexpr_constnum(0)); - } else { - int i = 0; - int found = -1; - struct macro m; - sne_vec_foreach(¯os, m, i) - { - if(strlen(m.name) == (size_t)str.n - && strncmp(m.name, str.s, str.n) == 0) { - found = i; + if(str.n == 1 && str.s[0] == '$') { + if(sne_vec_len(&arg.args) < 1) { + sne_vec_free(&arg.args); + goto cleanup; /* too few arguments for $() function */ } - } - if(found != -1) { - m = sne_vec_nth(¯os, found); - struct snexpr root = snexpr_constnum(0); - struct snexpr *p = &root; - int j; - /* Assign macro parameters */ - for(j = 0; j < sne_vec_len(&arg.args); j++) { - char varname[14]; - snprintf(varname, sizeof(varname) - 1, "$%d", - (j + 1)); - struct snexpr_var *v = - snexpr_var_find(vars, varname, strlen(varname)); - struct snexpr ev = snexpr_varref(v); - struct snexpr assign = snexpr_binary( - SNE_OP_ASSIGN, ev, sne_vec_nth(&arg.args, j)); - *p = snexpr_binary( - SNE_OP_COMMA, assign, snexpr_constnum(0)); - p = &sne_vec_nth(&p->param.op.args, 1); + struct snexpr *u = &sne_vec_nth(&arg.args, 0); + if(u->type != SNE_OP_VAR) { + sne_vec_free(&arg.args); + goto cleanup; /* first argument is not a variable */ } - /* Expand macro body */ - for(j = 1; j < sne_vec_len(&m.body); j++) { - if(j < sne_vec_len(&m.body) - 1) { - *p = snexpr_binary(SNE_OP_COMMA, snexpr_constnum(0), - snexpr_constnum(0)); - snexpr_copy(&sne_vec_nth(&p->param.op.args, 0), - &sne_vec_nth(&m.body, j)); - } else { - snexpr_copy(p, &sne_vec_nth(&m.body, j)); + struct snexpr_var *v; + for(v = vars->head; v; v = v->next) { + if(v == u->param.var.vref) { + struct macro m = {v->name, arg.args}; + sne_vec_push(¯os, m); + break; } - p = &sne_vec_nth(&p->param.op.args, 1); } - sne_vec_push(&es, root); - sne_vec_free(&arg.args); + sne_vec_push(&es, snexpr_constnum(0)); } else { - struct snexpr_func *f = snexpr_func_find(funcs, str.s, str.n); - struct snexpr bound_func = snexpr_init(); - bound_func.type = SNE_OP_FUNC; - bound_func.param.func.f = f; - bound_func.param.func.args = arg.args; - if(f->ctxsz > 0) { - void *p = calloc(1, f->ctxsz); - if(p == NULL) { - goto cleanup; /* allocation failed */ + int i = 0; + int found = -1; + struct macro m; + sne_vec_foreach(¯os, m, i) + { + if(strlen(m.name) == (size_t)str.n + && strncmp(m.name, str.s, str.n) == 0) { + found = i; } - bound_func.param.func.context = p; } - sne_vec_push(&es, bound_func); + if(found != -1) { + m = sne_vec_nth(¯os, found); + struct snexpr root = snexpr_constnum(0); + struct snexpr *p = &root; + int j; + /* Assign macro parameters */ + for(j = 0; j < sne_vec_len(&arg.args); j++) { + char varname[14]; + snprintf(varname, sizeof(varname) - 1, "$%d", + (j + 1)); + struct snexpr_var *v = snexpr_var_find( + vars, varname, strlen(varname)); + struct snexpr ev = snexpr_varref(v); + struct snexpr assign = + snexpr_binary(SNE_OP_ASSIGN, ev, + sne_vec_nth(&arg.args, j)); + *p = snexpr_binary(SNE_OP_COMMA, assign, + snexpr_constnum(0)); + p = &sne_vec_nth(&p->param.op.args, 1); + } + /* Expand macro body */ + for(j = 1; j < sne_vec_len(&m.body); j++) { + if(j < sne_vec_len(&m.body) - 1) { + *p = snexpr_binary(SNE_OP_COMMA, + snexpr_constnum(0), + snexpr_constnum(0)); + snexpr_copy( + &sne_vec_nth(&p->param.op.args, 0), + &sne_vec_nth(&m.body, j)); + } else { + snexpr_copy(p, &sne_vec_nth(&m.body, j)); + } + p = &sne_vec_nth(&p->param.op.args, 1); + } + sne_vec_push(&es, root); + sne_vec_free(&arg.args); + } else { + struct snexpr_func *f = + snexpr_func_find(funcs, str.s, str.n); + struct snexpr bound_func = snexpr_init(); + bound_func.type = SNE_OP_FUNC; + bound_func.param.func.f = f; + bound_func.param.func.args = arg.args; + if(f->ctxsz > 0) { + void *p = calloc(1, f->ctxsz); + if(p == NULL) { + goto cleanup; /* allocation failed */ + } + bound_func.param.func.context = p; + } + sne_vec_push(&es, bound_func); + } } } - } - paren_next = SNEXPR_PAREN_FORBIDDEN; - } else if(!isnan(num = snexpr_parse_number(tok, n))) { - sne_vec_push(&es, snexpr_constnum(num)); - paren_next = SNEXPR_PAREN_FORBIDDEN; - } else if(*tok == '"' || *tok == '\'') { - sne_vec_push(&es, snexpr_conststr(tok, n)); - paren_next = SNEXPR_PAREN_FORBIDDEN; - } else if(snexpr_op(tok, n, -1) != SNE_OP_UNKNOWN) { - enum snexpr_type op = snexpr_op(tok, n, -1); - struct snexpr_string o2 = {NULL, 0}; - if(sne_vec_len(&os) > 0) { - o2 = sne_vec_peek(&os); - } - for(;;) { - if(n == 1 && *tok == ',' && sne_vec_len(&os) > 0) { - struct snexpr_string str = sne_vec_peek(&os); - if(str.n == 1 && *str.s == '{') { - struct snexpr e = sne_vec_pop(&es); - sne_vec_push(&sne_vec_peek(&as).args, e); + paren_next = SNEXPR_PAREN_FORBIDDEN; + } else if(!isnan(num = snexpr_parse_number(tok, n))) { + sne_vec_push(&es, snexpr_constnum(num)); + paren_next = SNEXPR_PAREN_FORBIDDEN; + } else if(*tok == '"' || *tok == '\'') { + sne_vec_push(&es, snexpr_conststr(tok, n)); + paren_next = SNEXPR_PAREN_FORBIDDEN; + } else if(snexpr_op(tok, n, -1) != SNE_OP_UNKNOWN) { + enum snexpr_type op = snexpr_op(tok, n, -1); + struct snexpr_string o2 = {NULL, 0}; + if(sne_vec_len(&os) > 0) { + o2 = sne_vec_peek(&os); + } + for(;;) { + if(n == 1 && *tok == ',' && sne_vec_len(&os) > 0) { + struct snexpr_string str = sne_vec_peek(&os); + if(str.n == 1 && *str.s == '{') { + struct snexpr e = sne_vec_pop(&es); + sne_vec_push(&sne_vec_peek(&as).args, e); + break; + } + } + enum snexpr_type type2 = snexpr_op(o2.s, o2.n, -1); + if(!(type2 != SNE_OP_UNKNOWN && snexpr_prec(op, type2))) { + struct snexpr_string str = {tok, n}; + sne_vec_push(&os, str); break; } - } - enum snexpr_type type2 = snexpr_op(o2.s, o2.n, -1); - if(!(type2 != SNE_OP_UNKNOWN && snexpr_prec(op, type2))) { - struct snexpr_string str = {tok, n}; - sne_vec_push(&os, str); - break; - } - if(snexpr_bind(o2.s, o2.n, &es) == -1) { - goto cleanup; + if(snexpr_bind(o2.s, o2.n, &es) == -1) { + goto cleanup; + } + (void)sne_vec_pop(&os); + if(sne_vec_len(&os) > 0) { + o2 = sne_vec_peek(&os); + } else { + o2.n = 0; + } } - (void)sne_vec_pop(&os); - if(sne_vec_len(&os) > 0) { - o2 = sne_vec_peek(&os); + } else { + if(n > 0 && !isdigit(*tok)) { + /* Valid identifier, a variable or a function */ + id = tok; + idn = n; } else { - o2.n = 0; + goto cleanup; // Bad variable name, e.g. '2.3.4' or '4ever' } } - } else { - if(n > 0 && !isdigit(*tok)) { - /* Valid identifier, a variable or a function */ - id = tok; - idn = n; - } else { - goto cleanup; // Bad variable name, e.g. '2.3.4' or '4ever' - } + paren = paren_next; } - paren = paren_next; - } - - if(idn > 0) { - sne_vec_push(&es, snexpr_varref(snexpr_var_find(vars, id, idn))); - } - while(sne_vec_len(&os) > 0) { - struct snexpr_string rest = sne_vec_pop(&os); - if(rest.n == 1 && (*rest.s == '(' || *rest.s == ')')) { - goto cleanup; // Bad paren + if(idn > 0) { + sne_vec_push(&es, snexpr_varref(snexpr_var_find(vars, id, idn))); } - if(snexpr_bind(rest.s, rest.n, &es) == -1) { - goto cleanup; + + while(sne_vec_len(&os) > 0) { + struct snexpr_string rest = sne_vec_pop(&os); + if(rest.n == 1 && (*rest.s == '(' || *rest.s == ')')) { + goto cleanup; // Bad paren + } + if(snexpr_bind(rest.s, rest.n, &es) == -1) { + goto cleanup; + } } - } - result = (struct snexpr *)calloc(1, sizeof(struct snexpr)); - if(result != NULL) { - if(sne_vec_len(&es) == 0) { - result->type = SNE_OP_CONSTNUM; - } else { - *result = sne_vec_pop(&es); + result = (struct snexpr *)calloc(1, sizeof(struct snexpr)); + if(result != NULL) { + if(sne_vec_len(&es) == 0) { + result->type = SNE_OP_CONSTNUM; + } else { + *result = sne_vec_pop(&es); + } } - } - int i, j; - struct macro m; - struct snexpr e; - struct snexpr_arg a; -cleanup: - sne_vec_foreach(¯os, m, i) - { + int i, j; + struct macro m; struct snexpr e; - sne_vec_foreach(&m.body, e, j) + struct snexpr_arg a; + cleanup: + sne_vec_foreach(¯os, m, i) { - snexpr_destroy_args(&e); + struct snexpr e; + sne_vec_foreach(&m.body, e, j) + { + snexpr_destroy_args(&e); + } + sne_vec_free(&m.body); } - sne_vec_free(&m.body); - } - sne_vec_free(¯os); - - sne_vec_foreach(&es, e, i) - { - snexpr_destroy_args(&e); - } - sne_vec_free(&es); + sne_vec_free(¯os); - sne_vec_foreach(&as, a, i) - { - sne_vec_foreach(&a.args, e, j) + sne_vec_foreach(&es, e, i) { snexpr_destroy_args(&e); } - sne_vec_free(&a.args); - } - sne_vec_free(&as); + sne_vec_free(&es); - /*sne_vec_foreach(&os, o, i) {sne_vec_free(&m.body);}*/ - sne_vec_free(&os); - if(result==NULL) { - _snexternval_cbf = NULL; - } - - return result; -} - -static void snexpr_destroy_args(struct snexpr *e) -{ - int i; - struct snexpr arg; - if(e->type == SNE_OP_FUNC) { - sne_vec_foreach(&e->param.func.args, arg, i) + sne_vec_foreach(&as, a, i) { - snexpr_destroy_args(&arg); - } - sne_vec_free(&e->param.func.args); - if(e->param.func.context != NULL) { - if(e->param.func.f->cleanup != NULL) { - e->param.func.f->cleanup( - e->param.func.f, e->param.func.context); + sne_vec_foreach(&a.args, e, j) + { + snexpr_destroy_args(&e); } - free(e->param.func.context); + sne_vec_free(&a.args); } - } else if(e->type != SNE_OP_CONSTNUM && e->type != SNE_OP_CONSTSTZ - && e->type != SNE_OP_VAR) { - sne_vec_foreach(&e->param.op.args, arg, i) - { - snexpr_destroy_args(&arg); + sne_vec_free(&as); + + /*sne_vec_foreach(&os, o, i) {sne_vec_free(&m.body);}*/ + sne_vec_free(&os); + if(result == NULL) { + _snexternval_cbf = NULL; } - sne_vec_free(&e->param.op.args); - } -} -static void snexpr_destroy(struct snexpr *e, struct snexpr_var_list *vars) -{ - struct snexpr_var *v; - _snexternval_cbf = NULL; + return result; + } - if(e != NULL) { - snexpr_destroy_args(e); - free(e); + static void snexpr_destroy_args(struct snexpr *e) + { + int i; + struct snexpr arg; + if(e->type == SNE_OP_FUNC) { + sne_vec_foreach(&e->param.func.args, arg, i) + { + snexpr_destroy_args(&arg); + } + sne_vec_free(&e->param.func.args); + if(e->param.func.context != NULL) { + if(e->param.func.f->cleanup != NULL) { + e->param.func.f->cleanup( + e->param.func.f, e->param.func.context); + } + free(e->param.func.context); + } + } else if(e->type != SNE_OP_CONSTNUM && e->type != SNE_OP_CONSTSTZ + && e->type != SNE_OP_VAR) { + sne_vec_foreach(&e->param.op.args, arg, i) + { + snexpr_destroy_args(&arg); + } + sne_vec_free(&e->param.op.args); + } } - if(vars != NULL) { - for(v = vars->head; v;) { - struct snexpr_var *next = v->next; - if(v->evflags & SNEXPR_VALALLOC) { - free(v->v.sval); + + static void snexpr_destroy(struct snexpr *e, struct snexpr_var_list *vars) + { + struct snexpr_var *v; + _snexternval_cbf = NULL; + + if(e != NULL) { + snexpr_destroy_args(e); + free(e); + } + if(vars != NULL) { + for(v = vars->head; v;) { + struct snexpr_var *next = v->next; + if(v->evflags & SNEXPR_VALALLOC) { + free(v->v.sval); + } + free(v); + v = next; } - free(v); - v = next; } } -} #ifdef __cplusplus } /* extern "C" */ diff --git a/src/core/utils/srjson.c b/src/core/utils/srjson.c index 7752cd52a82..76ef80a1555 100644 --- a/src/core/utils/srjson.c +++ b/src/core/utils/srjson.c @@ -47,31 +47,30 @@ const char *srjson_GetErrorPtr() static int srjson_strcasecmp(const char *s1, const char *s2) { - if (!s1) + if(!s1) return (s1 == s2) ? 0 : 1; - if (!s2) + if(!s2) return 1; - for (; tolower(*s1) == tolower(*s2); ++s1, ++s2) - if (*s1 == 0) + for(; tolower(*s1) == tolower(*s2); ++s1, ++s2) + if(*s1 == 0) return 0; - return tolower(*(const unsigned char *) s1) - tolower(*(const unsigned char *) s2); + return tolower(*(const unsigned char *)s1) + - tolower(*(const unsigned char *)s2); } srjson_doc_t *srjson_NewDoc(srjson_Hooks *hooks) { srjson_doc_t *d; - if(hooks && hooks->malloc_fn) - { - d = (srjson_doc_t*)hooks->malloc_fn(sizeof(srjson_doc_t)); + if(hooks && hooks->malloc_fn) { + d = (srjson_doc_t *)hooks->malloc_fn(sizeof(srjson_doc_t)); } else { - d = (srjson_doc_t*)malloc(sizeof(srjson_doc_t)); + d = (srjson_doc_t *)malloc(sizeof(srjson_doc_t)); } - if(d) - { + if(d) { memset(d, 0, sizeof(srjson_doc_t)); d->malloc_fn = (hooks && hooks->malloc_fn) ? hooks->malloc_fn : malloc; - d->free_fn = (hooks && hooks->free_fn) ? hooks->free_fn : free; + d->free_fn = (hooks && hooks->free_fn) ? hooks->free_fn : free; } return d; } @@ -82,13 +81,13 @@ int srjson_InitDoc(srjson_doc_t *doc, srjson_Hooks *hooks) return -1; memset(doc, 0, sizeof(srjson_doc_t)); doc->malloc_fn = (hooks && hooks->malloc_fn) ? hooks->malloc_fn : malloc; - doc->free_fn = (hooks && hooks->free_fn) ? hooks->free_fn : free; + doc->free_fn = (hooks && hooks->free_fn) ? hooks->free_fn : free; return 0; } void srjson_DeleteDoc(srjson_doc_t *doc) { - void (*f) (void *); + void (*f)(void *); if(!doc) return; @@ -108,10 +107,10 @@ void srjson_DestroyDoc(srjson_doc_t *doc) static char *srjson_strdup(srjson_doc_t *doc, const char *str) { size_t len; - char *copy; + char *copy; len = strlen(str) + 1; - if (!(copy = (char *) doc->malloc_fn(len))) + if(!(copy = (char *)doc->malloc_fn(len))) return 0; memcpy(copy, str, len); return copy; @@ -121,7 +120,7 @@ static char *srjson_strndupz(srjson_doc_t *doc, const char *str, int len) { char *copy; - if (!(copy = (char *) doc->malloc_fn(len+1))) + if(!(copy = (char *)doc->malloc_fn(len + 1))) return 0; memcpy(copy, str, len); copy[len] = '\0'; @@ -132,8 +131,8 @@ static char *srjson_strndupz(srjson_doc_t *doc, const char *str, int len) /* Internal constructor. */ static srjson_t *srjson_New_Item(srjson_doc_t *doc) { - srjson_t *node = (srjson_t*)doc->malloc_fn(sizeof(srjson_t)); - if (node) + srjson_t *node = (srjson_t *)doc->malloc_fn(sizeof(srjson_t)); + if(node) memset(node, 0, sizeof(srjson_t)); return node; } @@ -142,13 +141,13 @@ static srjson_t *srjson_New_Item(srjson_doc_t *doc) void srjson_Delete(srjson_doc_t *doc, srjson_t *c) { srjson_t *next; - while (c) { + while(c) { next = c->next; - if (!(c->type & srjson_IsReference) && c->child) + if(!(c->type & srjson_IsReference) && c->child) srjson_Delete(doc, c->child); - if (!(c->type & srjson_IsReference) && c->valuestring) + if(!(c->type & srjson_IsReference) && c->valuestring) doc->free_fn(c->valuestring); - if (c->string) + if(c->string) doc->free_fn(c->string); doc->free_fn(c); c = next; @@ -159,36 +158,37 @@ void srjson_Delete(srjson_doc_t *doc, srjson_t *c) * Parse the input text to generate a number, and populate the result into * item. */ -static const char *parse_number(srjson_doc_t *doc, srjson_t *item, const char *num) +static const char *parse_number( + srjson_doc_t *doc, srjson_t *item, const char *num) { double n = 0, sign = 1, scale = 0; int subscale = 0, signsubscale = 1; /* Could use sscanf for this? */ - if (*num == '-') - sign = -1, num++; /* Has sign? */ - if (*num == '0') - num++; /* is zero */ - if (*num >= '1' && *num <= '9') + if(*num == '-') + sign = -1, num++; /* Has sign? */ + if(*num == '0') + num++; /* is zero */ + if(*num >= '1' && *num <= '9') do n = (n * 10.0) + (*num++ - '0'); - while (*num >= '0' && *num <= '9'); /* Number? */ - if (*num == '.' && num[1] >= '0' && num[1] <= '9') { + while(*num >= '0' && *num <= '9'); /* Number? */ + if(*num == '.' && num[1] >= '0' && num[1] <= '9') { num++; do n = (n * 10.0) + (*num++ - '0'), scale--; - while (*num >= '0' && *num <= '9'); - } /* Fractional part? */ - if (*num == 'e' || *num == 'E') { /* Exponent? */ + while(*num >= '0' && *num <= '9'); + } /* Fractional part? */ + if(*num == 'e' || *num == 'E') { /* Exponent? */ num++; - if (*num == '+') + if(*num == '+') num++; - else if (*num == '-') - signsubscale = -1, num++; /* With sign? */ - while (*num >= '0' && *num <= '9') - subscale = (subscale * 10) + (*num++ - '0'); /* Number? */ + else if(*num == '-') + signsubscale = -1, num++; /* With sign? */ + while(*num >= '0' && *num <= '9') + subscale = (subscale * 10) + (*num++ - '0'); /* Number? */ } - n = sign * n * pow(10.0, (scale + subscale * signsubscale)); /* number = +/- + n = sign * n * pow(10.0, (scale + subscale * signsubscale)); /* number = +/- * number.fraction * * 10^+/- exponent */ @@ -200,22 +200,22 @@ static const char *parse_number(srjson_doc_t *doc, srjson_t *item, const char *n /* Render the number nicely from the given item into a string. */ static char *print_number(srjson_doc_t *doc, srjson_t *item) { - char *str; - double d = item->valuedouble; - int i = (int)d; - if (fabs(((double) i) - d) <= DBL_EPSILON && d <= INT_MAX && d >= INT_MIN) { - str = (char *) doc->malloc_fn(21); /* 2^64+1 can be + char *str; + double d = item->valuedouble; + int i = (int)d; + if(fabs(((double)i) - d) <= DBL_EPSILON && d <= INT_MAX && d >= INT_MIN) { + str = (char *)doc->malloc_fn(21); /* 2^64+1 can be * represented in 21 * chars. */ - if (str) + if(str) sprintf(str, "%d", i); } else { - str = (char *) doc->malloc_fn(64); /* This is a nice + str = (char *)doc->malloc_fn(64); /* This is a nice * tradeoff. */ - if (str) { - if (fabs(floor(d) - d) <= DBL_EPSILON) + if(str) { + if(fabs(floor(d) - d) <= DBL_EPSILON) sprintf(str, "%.0f", d); - else if (fabs(d) < 1.0e-6 || fabs(d) > 1.0e9) + else if(fabs(d) < 1.0e-6 || fabs(d) > 1.0e9) sprintf(str, "%e", d); else sprintf(str, "%f", d); @@ -225,103 +225,105 @@ static char *print_number(srjson_doc_t *doc, srjson_t *item) } /* Parse the input text into an unescaped cstring, and populate item. */ -static const unsigned char firstByteMark[7] = {0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC}; -static const char *parse_string(srjson_doc_t *doc, srjson_t *item, const char *str) +static const unsigned char firstByteMark[7] = { + 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC}; +static const char *parse_string( + srjson_doc_t *doc, srjson_t *item, const char *str) { - const char *ptr = str + 1; - char *ptr2; - char *out; - int len = 0; - unsigned uc, uc2; - if (*str != '\"') { + const char *ptr = str + 1; + char *ptr2; + char *out; + int len = 0; + unsigned uc, uc2; + if(*str != '\"') { ep = str; return 0; - } /* not a string! */ - while (*ptr != '\"' && *ptr && ++len) - if (*ptr++ == '\\') - ptr++; /* Skip escaped quotes. */ + } /* not a string! */ + while(*ptr != '\"' && *ptr && ++len) + if(*ptr++ == '\\') + ptr++; /* Skip escaped quotes. */ - out = (char *) doc->malloc_fn(len + 1); /* This is how long we need + out = (char *)doc->malloc_fn(len + 1); /* This is how long we need * for the string, roughly. */ - if (!out) + if(!out) return 0; ptr = str + 1; ptr2 = out; - while (*ptr != '\"' && *ptr) { - if (*ptr != '\\') + while(*ptr != '\"' && *ptr) { + if(*ptr != '\\') *ptr2++ = *ptr++; else { ptr++; - switch (*ptr) { - case 'b': - *ptr2++ = '\b'; - break; - case 'f': - *ptr2++ = '\f'; - break; - case 'n': - *ptr2++ = '\n'; - break; - case 'r': - *ptr2++ = '\r'; - break; - case 't': - *ptr2++ = '\t'; - break; - case 'u': /* transcode utf16 to utf8. */ - sscanf(ptr + 1, "%4x", &uc); - ptr += 4; /* get the unicode char. */ - - if ((uc >= 0xDC00 && uc <= 0xDFFF) || uc == 0) + switch(*ptr) { + case 'b': + *ptr2++ = '\b'; break; - //check for invalid - if (uc >= 0xD800 && uc <= 0xDBFF) - //UTF16 surrogate pairs. - { - if (ptr[1] != '\\' || ptr[2] != 'u') - break; - //missing second - half of surrogate. - sscanf(ptr + 3, "%4x", &uc2); - ptr += 6; - if (uc2 < 0xDC00 || uc2 > 0xDFFF) + case 'f': + *ptr2++ = '\f'; + break; + case 'n': + *ptr2++ = '\n'; + break; + case 'r': + *ptr2++ = '\r'; + break; + case 't': + *ptr2++ = '\t'; + break; + case 'u': /* transcode utf16 to utf8. */ + sscanf(ptr + 1, "%4x", &uc); + ptr += 4; /* get the unicode char. */ + + if((uc >= 0xDC00 && uc <= 0xDFFF) || uc == 0) break; - //invalid second - half of surrogate. - uc = 0x10000 | ((uc & 0x3FF) << 10) | (uc2 & 0x3FF); - } - len = 4; - if (uc < 0x80) - len = 1; - else if (uc < 0x800) - len = 2; - else if (uc < 0x10000) - len = 3; - ptr2 += len; - - switch (len) { - case 4: - *--ptr2 = ((uc | 0x80) & 0xBF); - uc >>= 6; - case 3: - *--ptr2 = ((uc | 0x80) & 0xBF); - uc >>= 6; - case 2: - *--ptr2 = ((uc | 0x80) & 0xBF); - uc >>= 6; - case 1: - *--ptr2 = (uc | firstByteMark[len]); - } - ptr2 += len; - break; - default: - *ptr2++ = *ptr; - break; + //check for invalid + if(uc >= 0xD800 && uc <= 0xDBFF) + //UTF16 surrogate pairs. + { + if(ptr[1] != '\\' || ptr[2] != 'u') + break; + //missing second - half of surrogate. + sscanf(ptr + 3, "%4x", &uc2); + ptr += 6; + if(uc2 < 0xDC00 || uc2 > 0xDFFF) + break; + //invalid second - half of surrogate. + uc = 0x10000 | ((uc & 0x3FF) << 10) | (uc2 & 0x3FF); + } + len = 4; + if(uc < 0x80) + len = 1; + else if(uc < 0x800) + len = 2; + else if(uc < 0x10000) + len = 3; + ptr2 += len; + + switch(len) { + case 4: + *--ptr2 = ((uc | 0x80) & 0xBF); + uc >>= 6; + case 3: + *--ptr2 = ((uc | 0x80) & 0xBF); + uc >>= 6; + case 2: + *--ptr2 = ((uc | 0x80) & 0xBF); + uc >>= 6; + case 1: + *--ptr2 = (uc | firstByteMark[len]); + } + ptr2 += len; + break; + default: + *ptr2++ = *ptr; + break; } ptr++; } } *ptr2 = 0; - if (*ptr == '\"') + if(*ptr == '\"') ptr++; item->valuestring = out; item->type = srjson_String; @@ -331,60 +333,60 @@ static const char *parse_string(srjson_doc_t *doc, srjson_t *item, const char *s /* Render the cstring provided to an escaped version that can be printed. */ static char *print_string_ptr(srjson_doc_t *doc, const char *str) { - const char *ptr; - char *ptr2, *out; - int len = 0; - unsigned char token; + const char *ptr; + char *ptr2, *out; + int len = 0; + unsigned char token; - if (!str) + if(!str) return srjson_strdup(doc, ""); ptr = str; - while ((token = *ptr) && ++len) { - if (strchr("\"\\\b\f\n\r\t", token)) + while((token = *ptr) && ++len) { + if(strchr("\"\\\b\f\n\r\t", token)) len++; - else if (token < 32) + else if(token < 32) len += 5; ptr++; } - out = (char *) doc->malloc_fn(len + 3); - if (!out) + out = (char *)doc->malloc_fn(len + 3); + if(!out) return 0; ptr2 = out; ptr = str; *ptr2++ = '\"'; - while (*ptr) { - if ((unsigned char) *ptr > 31 && *ptr != '\"' && *ptr != '\\') + while(*ptr) { + if((unsigned char)*ptr > 31 && *ptr != '\"' && *ptr != '\\') *ptr2++ = *ptr++; else { *ptr2++ = '\\'; - switch (token = *ptr++) { - case '\\': - *ptr2++ = '\\'; - break; - case '\"': - *ptr2++ = '\"'; - break; - case '\b': - *ptr2++ = 'b'; - break; - case '\f': - *ptr2++ = 'f'; - break; - case '\n': - *ptr2++ = 'n'; - break; - case '\r': - *ptr2++ = 'r'; - break; - case '\t': - *ptr2++ = 't'; - break; - default: - sprintf(ptr2, "u%04x", token); - ptr2 += 5; - break; /* escape and print */ + switch(token = *ptr++) { + case '\\': + *ptr2++ = '\\'; + break; + case '\"': + *ptr2++ = '\"'; + break; + case '\b': + *ptr2++ = 'b'; + break; + case '\f': + *ptr2++ = 'f'; + break; + case '\n': + *ptr2++ = 'n'; + break; + case '\r': + *ptr2++ = 'r'; + break; + case '\t': + *ptr2++ = 't'; + break; + default: + sprintf(ptr2, "u%04x", token); + ptr2 += 5; + break; /* escape and print */ } } } @@ -393,22 +395,27 @@ static char *print_string_ptr(srjson_doc_t *doc, const char *str) return out; } /* Invoke print_string_ptr (which is useful) on an item. */ -static char *print_string(srjson_doc_t *doc, srjson_t *item) { +static char *print_string(srjson_doc_t *doc, srjson_t *item) +{ return print_string_ptr(doc, item->valuestring); } /* Predeclare these prototypes. */ -static const char *parse_value(srjson_doc_t *doc, srjson_t *item, const char *value); +static const char *parse_value( + srjson_doc_t *doc, srjson_t *item, const char *value); static char *print_value(srjson_doc_t *doc, srjson_t *item, int depth, int fmt); -static const char *parse_array(srjson_doc_t *doc, srjson_t *item, const char *value); +static const char *parse_array( + srjson_doc_t *doc, srjson_t *item, const char *value); static char *print_array(srjson_doc_t *doc, srjson_t *item, int depth, int fmt); -static const char *parse_object(srjson_doc_t *doc, srjson_t *item, const char *value); -static char *print_object(srjson_doc_t *doc, srjson_t *item, int depth, int fmt); +static const char *parse_object( + srjson_doc_t *doc, srjson_t *item, const char *value); +static char *print_object( + srjson_doc_t *doc, srjson_t *item, int depth, int fmt); /* Utility to jump whitespace and cr/lf */ static const char *skip(const char *in) { - while (in && *in && (unsigned char) *in <= 32) + while(in && *in && (unsigned char)*in <= 32) in++; return in; } @@ -418,10 +425,10 @@ srjson_t *srjson_Parse(srjson_doc_t *doc, const char *value) { srjson_t *c = srjson_New_Item(doc); ep = 0; - if (!c) - return 0; /* memory fail */ + if(!c) + return 0; /* memory fail */ - if (!parse_value(doc, c, skip(value))) { + if(!parse_value(doc, c, skip(value))) { srjson_Delete(doc, c); return 0; } @@ -429,144 +436,148 @@ srjson_t *srjson_Parse(srjson_doc_t *doc, const char *value) } /* Render a srjson item/entity/structure to text. */ -char *srjson_Print(srjson_doc_t *doc, srjson_t *item) { +char *srjson_Print(srjson_doc_t *doc, srjson_t *item) +{ return print_value(doc, item, 0, 1); } -char *srjson_PrintUnformatted(srjson_doc_t *doc, srjson_t *item) { +char *srjson_PrintUnformatted(srjson_doc_t *doc, srjson_t *item) +{ return print_value(doc, item, 0, 0); } /* Parser core - when encountering text, process appropriately. */ -static const char *parse_value(srjson_doc_t *doc, srjson_t *item, const char *value) +static const char *parse_value( + srjson_doc_t *doc, srjson_t *item, const char *value) { - if (!value) - return 0; /* Fail on null. */ - if (!strncmp(value, "null", 4)) { + if(!value) + return 0; /* Fail on null. */ + if(!strncmp(value, "null", 4)) { item->type = srjson_NULL; item->valuedouble = 0; return value + 4; } - if (!strncmp(value, "false", 5)) { + if(!strncmp(value, "false", 5)) { item->type = srjson_False; item->valuedouble = 0; return value + 5; } - if (!strncmp(value, "true", 4)) { + if(!strncmp(value, "true", 4)) { item->type = srjson_True; item->valuedouble = 1; return value + 4; } - if (*value == '\"') { + if(*value == '\"') { return parse_string(doc, item, value); } - if (*value == '-' || (*value >= '0' && *value <= '9')) { + if(*value == '-' || (*value >= '0' && *value <= '9')) { return parse_number(doc, item, value); } - if (*value == '[') { + if(*value == '[') { return parse_array(doc, item, value); } - if (*value == '{') { + if(*value == '{') { return parse_object(doc, item, value); } ep = value; - return 0; /* failure. */ + return 0; /* failure. */ } /* Render a value to text. */ static char *print_value(srjson_doc_t *doc, srjson_t *item, int depth, int fmt) { char *out = 0; - if (!item) + if(!item) return 0; - switch ((item->type) & 255) { - case srjson_NULL: - out = srjson_strdup(doc, "null"); - break; - case srjson_False: - out = srjson_strdup(doc, "false"); - break; - case srjson_True: - out = srjson_strdup(doc, "true"); - break; - case srjson_Number: - out = print_number(doc, item); - break; - case srjson_String: - out = print_string(doc, item); - break; - case srjson_Array: - out = print_array(doc, item, depth, fmt); - break; - case srjson_Object: - out = print_object(doc, item, depth, fmt); - break; + switch((item->type) & 255) { + case srjson_NULL: + out = srjson_strdup(doc, "null"); + break; + case srjson_False: + out = srjson_strdup(doc, "false"); + break; + case srjson_True: + out = srjson_strdup(doc, "true"); + break; + case srjson_Number: + out = print_number(doc, item); + break; + case srjson_String: + out = print_string(doc, item); + break; + case srjson_Array: + out = print_array(doc, item, depth, fmt); + break; + case srjson_Object: + out = print_object(doc, item, depth, fmt); + break; } return out; } /* Build an array from input text. */ -static const char *parse_array(srjson_doc_t *doc, srjson_t *item, const char *value) +static const char *parse_array( + srjson_doc_t *doc, srjson_t *item, const char *value) { srjson_t *child; - if (*value != '[') { + if(*value != '[') { ep = value; return 0; - } /* not an array! */ + } /* not an array! */ item->type = srjson_Array; value = skip(value + 1); - if (*value == ']') - return value + 1; /* empty array. */ + if(*value == ']') + return value + 1; /* empty array. */ item->child = child = srjson_New_Item(doc); - if (!item->child) - return 0; /* memory fail */ - value = skip(parse_value(doc, child, skip(value))); /* skip any spacing, get + if(!item->child) + return 0; /* memory fail */ + value = skip(parse_value(doc, child, skip(value))); /* skip any spacing, get * the value. */ - if (!value) + if(!value) return 0; - while (*value == ',') { + while(*value == ',') { srjson_t *new_item; - if (!(new_item = srjson_New_Item(doc))) - return 0; /* memory fail */ + if(!(new_item = srjson_New_Item(doc))) + return 0; /* memory fail */ child->next = new_item; new_item->prev = child; child = new_item; value = skip(parse_value(doc, child, skip(value + 1))); - if (!value) - return 0; /* memory fail */ + if(!value) + return 0; /* memory fail */ } - if (*value == ']') - return value + 1; /* end of array */ + if(*value == ']') + return value + 1; /* end of array */ ep = value; - return 0; /* malformed. */ + return 0; /* malformed. */ } /* Render an array to text */ static char *print_array(srjson_doc_t *doc, srjson_t *item, int depth, int fmt) { - char **entries; - char *out = 0, *ptr, *ret; - int len = 5; + char **entries; + char *out = 0, *ptr, *ret; + int len = 5; srjson_t *child = item->child; - int numentries = 0, i = 0, fail = 0; + int numentries = 0, i = 0, fail = 0; /* How many entries in the array? */ - while (child) + while(child) numentries++, child = child->next; /* Allocate an array to hold the values for each */ - entries = (char **) doc->malloc_fn(numentries * sizeof(char *)); - if (!entries) + entries = (char **)doc->malloc_fn(numentries * sizeof(char *)); + if(!entries) return 0; memset(entries, 0, numentries * sizeof(char *)); /* Retrieve all the results: */ child = item->child; - while (child && !fail) { + while(child && !fail) { ret = print_value(doc, child, depth + 1, fmt); entries[i++] = ret; - if (ret) + if(ret) len += strlen(ret) + 2 + (fmt ? 1 : 0); else fail = 1; @@ -574,16 +585,16 @@ static char *print_array(srjson_doc_t *doc, srjson_t *item, int depth, int fmt) } /* If we didn't fail, try to malloc the output string */ - if (!fail) - out = (char *) doc->malloc_fn(len); + if(!fail) + out = (char *)doc->malloc_fn(len); /* If that fails, we fail. */ - if (!out) + if(!out) fail = 1; /* Handle failure. */ - if (fail) { - for (i = 0; i < numentries; i++) - if (entries[i]) + if(fail) { + for(i = 0; i < numentries; i++) + if(entries[i]) doc->free_fn(entries[i]); doc->free_fn(entries); return 0; @@ -592,12 +603,12 @@ static char *print_array(srjson_doc_t *doc, srjson_t *item, int depth, int fmt) *out = '['; ptr = out + 1; *ptr = 0; - for (i = 0; i < numentries; i++) { + for(i = 0; i < numentries; i++) { strcpy(ptr, entries[i]); ptr += strlen(entries[i]); - if (i != numentries - 1) { + if(i != numentries - 1) { *ptr++ = ','; - if (fmt) + if(fmt) *ptr++ = ' '; *ptr = 0; } @@ -610,80 +621,83 @@ static char *print_array(srjson_doc_t *doc, srjson_t *item, int depth, int fmt) } /* Build an object from the text. */ -static const char *parse_object(srjson_doc_t *doc, srjson_t *item, const char *value) +static const char *parse_object( + srjson_doc_t *doc, srjson_t *item, const char *value) { srjson_t *child; - if (*value != '{') { + if(*value != '{') { ep = value; return 0; - } /* not an object! */ + } /* not an object! */ item->type = srjson_Object; value = skip(value + 1); - if (*value == '}') - return value + 1; /* empty array. */ + if(*value == '}') + return value + 1; /* empty array. */ item->child = child = srjson_New_Item(doc); - if (!item->child) + if(!item->child) return 0; value = skip(parse_string(doc, child, skip(value))); - if (!value) + if(!value) return 0; child->string = child->valuestring; child->valuestring = 0; - if (*value != ':') { + if(*value != ':') { ep = value; return 0; - } /* fail! */ - value = skip(parse_value(doc, child, skip(value + 1))); /* skip any spacing, get + } /* fail! */ + value = skip( + parse_value(doc, child, skip(value + 1))); /* skip any spacing, get * the value. */ - if (!value) + if(!value) return 0; - while (*value == ',') { + while(*value == ',') { srjson_t *new_item; - if (!(new_item = srjson_New_Item(doc))) - return 0; /* memory fail */ + if(!(new_item = srjson_New_Item(doc))) + return 0; /* memory fail */ child->next = new_item; new_item->prev = child; child = new_item; value = skip(parse_string(doc, child, skip(value + 1))); - if (!value) + if(!value) return 0; child->string = child->valuestring; child->valuestring = 0; - if (*value != ':') { + if(*value != ':') { ep = value; return 0; - } /* fail! */ - value = skip(parse_value(doc, child, skip(value + 1))); /* skip any spacing, get + } /* fail! */ + value = skip(parse_value( + doc, child, skip(value + 1))); /* skip any spacing, get * the value. */ - if (!value) + if(!value) return 0; } - if (*value == '}') - return value + 1; /* end of array */ + if(*value == '}') + return value + 1; /* end of array */ ep = value; - return 0; /* malformed. */ + return 0; /* malformed. */ } /* Render an object to text. */ static char *print_object(srjson_doc_t *doc, srjson_t *item, int depth, int fmt) { - char **entries = 0, **names = 0; - char *out = 0, *ptr, *ret, *str; - int len = 7, i = 0, j; - srjson_t *child = item->child; - int numentries = 0, fail = 0; + char **entries = 0, **names = 0; + char *out = 0, *ptr, *ret, *str; + int len = 7, i = 0, j; + srjson_t *child = item->child; + int numentries = 0, fail = 0; /* Count the number of entries. */ - while (child) + while(child) numentries++, child = child->next; /* Allocate space for the names and the objects */ - entries = (char **) doc->malloc_fn(numentries * sizeof(char *)); - if (!entries) + entries = (char **)doc->malloc_fn(numentries * sizeof(char *)); + if(!entries) return 0; names = (char **)doc->malloc_fn(numentries * sizeof(char *)); - if (!names) { + if(!names) { doc->free_fn(entries); return 0; } @@ -693,12 +707,12 @@ static char *print_object(srjson_doc_t *doc, srjson_t *item, int depth, int fmt) /* Collect all the results into our arrays: */ child = item->child; depth++; - if (fmt) + if(fmt) len += depth; - while (child) { + while(child) { names[i] = str = print_string_ptr(doc, child->string); entries[i++] = ret = print_value(doc, child, depth, fmt); - if (str && ret) + if(str && ret) len += strlen(ret) + strlen(str) + 2 + (fmt ? 2 + depth : 0); else fail = 1; @@ -706,17 +720,17 @@ static char *print_object(srjson_doc_t *doc, srjson_t *item, int depth, int fmt) } /* Try to allocate the output string */ - if (!fail) - out = (char *) doc->malloc_fn(len); - if (!out) + if(!fail) + out = (char *)doc->malloc_fn(len); + if(!out) fail = 1; /* Handle failure */ - if (fail) { - for (i = 0; i < numentries; i++) { - if (names[i]) + if(fail) { + for(i = 0; i < numentries; i++) { + if(names[i]) doc->free_fn(names[i]); - if (entries[i]) + if(entries[i]) doc->free_fn(entries[i]); } doc->free_fn(names); @@ -726,23 +740,23 @@ static char *print_object(srjson_doc_t *doc, srjson_t *item, int depth, int fmt) /* Compose the output: */ *out = '{'; ptr = out + 1; - if (fmt) + if(fmt) *ptr++ = '\n'; *ptr = 0; - for (i = 0; i < numentries; i++) { - if (fmt) - for (j = 0; j < depth; j++) + for(i = 0; i < numentries; i++) { + if(fmt) + for(j = 0; j < depth; j++) *ptr++ = '\t'; strcpy(ptr, names[i]); ptr += strlen(names[i]); *ptr++ = ':'; - if (fmt) + if(fmt) *ptr++ = '\t'; strcpy(ptr, entries[i]); ptr += strlen(entries[i]); - if (i != numentries - 1) + if(i != numentries - 1) *ptr++ = ','; - if (fmt) + if(fmt) *ptr++ = '\n'; *ptr = 0; doc->free_fn(names[i]); @@ -751,8 +765,8 @@ static char *print_object(srjson_doc_t *doc, srjson_t *item, int depth, int fmt) doc->free_fn(names); doc->free_fn(entries); - if (fmt) - for (i = 0; i < depth - 1; i++) + if(fmt) + for(i = 0; i < depth - 1; i++) *ptr++ = '\t'; *ptr++ = '}'; *ptr++ = 0; @@ -764,7 +778,7 @@ int srjson_GetArraySize(srjson_doc_t *doc, srjson_t *array) { srjson_t *c = array->child; int i = 0; - while (c) + while(c) i++, c = c->next; return i; } @@ -772,15 +786,16 @@ int srjson_GetArraySize(srjson_doc_t *doc, srjson_t *array) srjson_t *srjson_GetArrayItem(srjson_doc_t *doc, srjson_t *array, int item) { srjson_t *c = array->child; - while (c && item > 0) + while(c && item > 0) item--, c = c->next; return c; } -srjson_t *srjson_GetObjectItem(srjson_doc_t *doc, srjson_t *object, const char *string) +srjson_t *srjson_GetObjectItem( + srjson_doc_t *doc, srjson_t *object, const char *string) { srjson_t *c = object->child; - while (c && srjson_strcasecmp(c->string, string)) + while(c && srjson_strcasecmp(c->string, string)) c = c->next; return c; } @@ -793,9 +808,10 @@ static void suffix_object(srjson_t *prev, srjson_t *item) } /* Utility for handling references. */ -static srjson_t *create_reference(srjson_doc_t *doc, srjson_t *item) { +static srjson_t *create_reference(srjson_doc_t *doc, srjson_t *item) +{ srjson_t *ref = srjson_New_Item(doc); - if (!ref) + if(!ref) return 0; memcpy(ref, item, sizeof(srjson_t)); ref->string = 0; @@ -805,107 +821,124 @@ static srjson_t *create_reference(srjson_doc_t *doc, srjson_t *item) { } /* Add item to array/object. */ -void srjson_AddItemToArray(srjson_doc_t *doc, srjson_t *array, srjson_t *item) { +void srjson_AddItemToArray(srjson_doc_t *doc, srjson_t *array, srjson_t *item) +{ srjson_t *c = array->child; - if (!item) + if(!item) return; - if (!c) { + if(!c) { array->child = item; } else { - while (c && c->next) + while(c && c->next) c = c->next; suffix_object(c, item); } } -void srjson_AddItemToObject(srjson_doc_t *doc, srjson_t *object, const char *string, srjson_t *item) { - if (!item) +void srjson_AddItemToObject( + srjson_doc_t *doc, srjson_t *object, const char *string, srjson_t *item) +{ + if(!item) return; - if (item->string) + if(item->string) doc->free_fn(item->string); item->string = srjson_strdup(doc, string); srjson_AddItemToArray(doc, object, item); } -void srjson_AddStrItemToObject(srjson_doc_t *doc, srjson_t *object, const char *string, int len, srjson_t *item) { - if (!item) +void srjson_AddStrItemToObject(srjson_doc_t *doc, srjson_t *object, + const char *string, int len, srjson_t *item) +{ + if(!item) return; - if (item->string) + if(item->string) doc->free_fn(item->string); item->string = srjson_strndupz(doc, string, len); srjson_AddItemToArray(doc, object, item); } -void srjson_AddItemReferenceToArray(srjson_doc_t *doc, srjson_t *array, srjson_t *item) { +void srjson_AddItemReferenceToArray( + srjson_doc_t *doc, srjson_t *array, srjson_t *item) +{ srjson_AddItemToArray(doc, array, create_reference(doc, item)); } -void srjson_AddItemReferenceToObject(srjson_doc_t *doc, srjson_t *object, const char *string, srjson_t *item) { +void srjson_AddItemReferenceToObject( + srjson_doc_t *doc, srjson_t *object, const char *string, srjson_t *item) +{ srjson_AddItemToObject(doc, object, string, create_reference(doc, item)); } -srjson_t *srjson_UnlinkItemFromObj(srjson_doc_t *doc, srjson_t *obj, srjson_t *c) +srjson_t *srjson_UnlinkItemFromObj( + srjson_doc_t *doc, srjson_t *obj, srjson_t *c) { - if (!c) + if(!c) return 0; - if (c->prev) + if(c->prev) c->prev->next = c->next; - if (c->next) + if(c->next) c->next->prev = c->prev; - if (c == obj->child) + if(c == obj->child) obj->child = c->next; c->prev = c->next = 0; return c; } -srjson_t *srjson_DetachItemFromArray(srjson_doc_t *doc, srjson_t *array, int which) +srjson_t *srjson_DetachItemFromArray( + srjson_doc_t *doc, srjson_t *array, int which) { srjson_t *c = array->child; - while (c && which > 0) + while(c && which > 0) c = c->next, which--; - if (!c) + if(!c) return 0; - if (c->prev) + if(c->prev) c->prev->next = c->next; - if (c->next) + if(c->next) c->next->prev = c->prev; - if (c == array->child) + if(c == array->child) array->child = c->next; c->prev = c->next = 0; return c; } -void srjson_DeleteItemFromArray(srjson_doc_t *doc, srjson_t *array, int which) { +void srjson_DeleteItemFromArray(srjson_doc_t *doc, srjson_t *array, int which) +{ srjson_Delete(doc, srjson_DetachItemFromArray(doc, array, which)); } -srjson_t *srjson_DetachItemFromObject(srjson_doc_t *doc, srjson_t *object, const char *string) { +srjson_t *srjson_DetachItemFromObject( + srjson_doc_t *doc, srjson_t *object, const char *string) +{ int i = 0; srjson_t *c = object->child; - while (c && srjson_strcasecmp(c->string, string)) + while(c && srjson_strcasecmp(c->string, string)) i++, c = c->next; - if (c) + if(c) return srjson_DetachItemFromArray(doc, object, i); return 0; } -void srjson_DeleteItemFromObject(srjson_doc_t *doc, srjson_t *object, const char *string) { +void srjson_DeleteItemFromObject( + srjson_doc_t *doc, srjson_t *object, const char *string) +{ srjson_Delete(doc, srjson_DetachItemFromObject(doc, object, string)); } /* Replace array/object items with new ones. */ -void srjson_ReplaceItemInArray(srjson_doc_t *doc, srjson_t *array, int which, srjson_t *newitem) +void srjson_ReplaceItemInArray( + srjson_doc_t *doc, srjson_t *array, int which, srjson_t *newitem) { srjson_t *c = array->child; - while (c && which > 0) + while(c && which > 0) c = c->next, which--; - if (!c) + if(!c) return; newitem->next = c->next; newitem->prev = c->prev; - if (newitem->next) + if(newitem->next) newitem->next->prev = newitem; - if (c == array->child) + if(c == array->child) array->child = newitem; else newitem->prev->next = newitem; @@ -913,134 +946,158 @@ void srjson_ReplaceItemInArray(srjson_doc_t *doc, srjson_t *array, int which, sr srjson_Delete(doc, c); } -void srjson_ReplaceItemInObject(srjson_doc_t *doc, srjson_t * object, const char *string, srjson_t *newitem) { +void srjson_ReplaceItemInObject(srjson_doc_t *doc, srjson_t *object, + const char *string, srjson_t *newitem) +{ int i = 0; srjson_t *c = object->child; - while (c && srjson_strcasecmp(c->string, string)) + while(c && srjson_strcasecmp(c->string, string)) i++, c = c->next; - if (c) { + if(c) { newitem->string = srjson_strdup(doc, string); srjson_ReplaceItemInArray(doc, object, i, newitem); } } /* Create basic types: */ -srjson_t *srjson_CreateNull(srjson_doc_t *doc) { +srjson_t *srjson_CreateNull(srjson_doc_t *doc) +{ srjson_t *item = srjson_New_Item(doc); - if (item) + if(item) item->type = srjson_NULL; return item; } -srjson_t *srjson_CreateTrue(srjson_doc_t *doc) { +srjson_t *srjson_CreateTrue(srjson_doc_t *doc) +{ srjson_t *item = srjson_New_Item(doc); - if (item) + if(item) item->type = srjson_True; return item; } -srjson_t *srjson_CreateFalse(srjson_doc_t *doc) { +srjson_t *srjson_CreateFalse(srjson_doc_t *doc) +{ srjson_t *item = srjson_New_Item(doc); - if (item) + if(item) item->type = srjson_False; return item; } -srjson_t *srjson_CreateBool(srjson_doc_t *doc, int b) { +srjson_t *srjson_CreateBool(srjson_doc_t *doc, int b) +{ srjson_t *item = srjson_New_Item(doc); - if (item) + if(item) item->type = b ? srjson_True : srjson_False; return item; } -srjson_t *srjson_CreateNumber(srjson_doc_t *doc, double num) { +srjson_t *srjson_CreateNumber(srjson_doc_t *doc, double num) +{ srjson_t *item = srjson_New_Item(doc); - if (item) { + if(item) { item->type = srjson_Number; item->valuedouble = num; - } return item; + } + return item; } -srjson_t *srjson_CreateString(srjson_doc_t *doc, const char *string) { +srjson_t *srjson_CreateString(srjson_doc_t *doc, const char *string) +{ srjson_t *item = srjson_New_Item(doc); - if (item) { + if(item) { item->type = srjson_String; item->valuestring = srjson_strdup(doc, string); - } return item; + } + return item; } -srjson_t *srjson_CreateStr(srjson_doc_t *doc, const char *string, int len) { +srjson_t *srjson_CreateStr(srjson_doc_t *doc, const char *string, int len) +{ srjson_t *item = srjson_New_Item(doc); - if (item) { + if(item) { item->type = srjson_String; item->valuestring = srjson_strndupz(doc, string, len); - } return item; + } + return item; } -srjson_t *srjson_CreateArray(srjson_doc_t *doc) { +srjson_t *srjson_CreateArray(srjson_doc_t *doc) +{ srjson_t *item = srjson_New_Item(doc); - if (item) + if(item) item->type = srjson_Array; return item; } -srjson_t *srjson_CreateObject(srjson_doc_t *doc) { +srjson_t *srjson_CreateObject(srjson_doc_t *doc) +{ srjson_t *item = srjson_New_Item(doc); - if (item) + if(item) item->type = srjson_Object; return item; } /* Create Arrays: */ -srjson_t *srjson_CreateIntArray(srjson_doc_t *doc, int *numbers, int count) { +srjson_t *srjson_CreateIntArray(srjson_doc_t *doc, int *numbers, int count) +{ int i; srjson_t *n = 0, *p = 0, *a = srjson_CreateArray(doc); - for (i = 0; a && i < count; i++) { + for(i = 0; a && i < count; i++) { n = srjson_CreateNumber(doc, numbers[i]); - if (!i) + if(!i) a->child = n; else suffix_object(p, n); p = n; - } return a; + } + return a; } -srjson_t *srjson_CreateFloatArray(srjson_doc_t *doc, float *numbers, int count) { +srjson_t *srjson_CreateFloatArray(srjson_doc_t *doc, float *numbers, int count) +{ int i; srjson_t *n = 0, *p = 0, *a = srjson_CreateArray(doc); - for (i = 0; a && i < count; i++) { + for(i = 0; a && i < count; i++) { n = srjson_CreateNumber(doc, numbers[i]); - if (!i) + if(!i) a->child = n; else suffix_object(p, n); p = n; - } return a; + } + return a; } -srjson_t *srjson_CreateDoubleArray(srjson_doc_t *doc, double *numbers, int count) { +srjson_t *srjson_CreateDoubleArray( + srjson_doc_t *doc, double *numbers, int count) +{ int i; srjson_t *n = 0, *p = 0, *a = srjson_CreateArray(doc); - for (i = 0; a && i < count; i++) { + for(i = 0; a && i < count; i++) { n = srjson_CreateNumber(doc, numbers[i]); - if (!i) + if(!i) a->child = n; else suffix_object(p, n); p = n; - } return a; + } + return a; } -srjson_t *srjson_CreateStringArray(srjson_doc_t *doc, const char **strings, int count) { +srjson_t *srjson_CreateStringArray( + srjson_doc_t *doc, const char **strings, int count) +{ int i; srjson_t *n = 0, *p = 0, *a = srjson_CreateArray(doc); - for (i = 0; a && i < count; i++) { + for(i = 0; a && i < count; i++) { n = srjson_CreateString(doc, strings[i]); - if (!i) + if(!i) a->child = n; else suffix_object(p, n); p = n; - } return a; + } + return a; } diff --git a/src/core/utils/srjson.h b/src/core/utils/srjson.h index dce2ae92520..fc193940296 100644 --- a/src/core/utils/srjson.h +++ b/src/core/utils/srjson.h @@ -30,165 +30,195 @@ #define _srjson__h_ #ifdef __cplusplus -extern "C" +extern "C" { #endif #include "../../core/str.h" /* srjson Types: */ -#define srjson_False 0 -#define srjson_True 1 -#define srjson_NULL 2 -#define srjson_Number 3 -#define srjson_String 4 -#define srjson_Array 5 -#define srjson_Object 6 +#define srjson_False 0 +#define srjson_True 1 +#define srjson_NULL 2 +#define srjson_Number 3 +#define srjson_String 4 +#define srjson_Array 5 +#define srjson_Object 6 #define srjson_IsReference 256 -/* helper macros */ - -#define SRJSON_GET_INT(sj) ((int)((sj)->valuedouble)) -#define SRJSON_GET_UINT(sj) ((unsigned int)((sj)->valuedouble)) -#define SRJSON_GET_LONG(sj) ((long)((sj)->valuedouble)) -#define SRJSON_GET_ULONG(sj) ((unsigned long)((sj)->valuedouble)) -#define SRJSON_GET_LLONG(sj) ((long long)((sj)->valuedouble)) -#define SRJSON_GET_ULLONG(sj) ((unsigned long long)((sj)->valuedouble)) - -/* The srjson node structure: */ -typedef struct srjson { - struct srjson *parent; - struct srjson *next; - struct srjson *prev; /* next/prev allow you to + /* helper macros */ + +#define SRJSON_GET_INT(sj) ((int)((sj)->valuedouble)) +#define SRJSON_GET_UINT(sj) ((unsigned int)((sj)->valuedouble)) +#define SRJSON_GET_LONG(sj) ((long)((sj)->valuedouble)) +#define SRJSON_GET_ULONG(sj) ((unsigned long)((sj)->valuedouble)) +#define SRJSON_GET_LLONG(sj) ((long long)((sj)->valuedouble)) +#define SRJSON_GET_ULLONG(sj) ((unsigned long long)((sj)->valuedouble)) + + /* The srjson node structure: */ + typedef struct srjson + { + struct srjson *parent; + struct srjson *next; + struct srjson *prev; /* next/prev allow you to * walk array/object chains. * Alternatively, use * GetArraySize/GetArrayItem/G * etObjectItem */ - struct srjson *child; /* An array or object item will have + struct srjson *child; /* An array or object item will have * a child pointer pointing to a * chain of the items in the * array/object. */ - int type; /* The type of the item, as above. */ - char *valuestring; /* The item's string, if + int type; /* The type of the item, as above. */ + char *valuestring; /* The item's string, if * type==srjson_String */ - double valuedouble; /* The item's number, if + double valuedouble; /* The item's number, if * type==srjson_Number */ - char *string; /* The item's name string, if this + char *string; /* The item's name string, if this * item is the child of, or is in the * list of subitems of an object. */ -} srjson_t; + } srjson_t; -typedef struct srjson_doc { - srjson_t *root; - int flags; - str buf; - void *(*malloc_fn) (size_t sz); - void (*free_fn) (void *ptr); -} srjson_doc_t; + typedef struct srjson_doc + { + srjson_t *root; + int flags; + str buf; + void *(*malloc_fn)(size_t sz); + void (*free_fn)(void *ptr); + } srjson_doc_t; -typedef struct srjson_Hooks { - void *(*malloc_fn) (size_t sz); - void (*free_fn) (void *ptr); -} srjson_Hooks; + typedef struct srjson_Hooks + { + void *(*malloc_fn)(size_t sz); + void (*free_fn)(void *ptr); + } srjson_Hooks; -extern srjson_doc_t *srjson_NewDoc(srjson_Hooks *hooks); -extern int srjson_InitDoc(srjson_doc_t *doc, srjson_Hooks *hooks); + extern srjson_doc_t *srjson_NewDoc(srjson_Hooks *hooks); + extern int srjson_InitDoc(srjson_doc_t *doc, srjson_Hooks *hooks); -extern void srjson_DeleteDoc(srjson_doc_t *doc); -extern void srjson_DestroyDoc(srjson_doc_t *doc); + extern void srjson_DeleteDoc(srjson_doc_t *doc); + extern void srjson_DestroyDoc(srjson_doc_t *doc); -/* + /* * Supply a block of JSON, and this returns a srjson object you can * interrogate. Call srjson_Delete when finished. */ -extern srjson_t *srjson_Parse(srjson_doc_t *doc, const char *value); + extern srjson_t *srjson_Parse(srjson_doc_t *doc, const char *value); -/* + /* * Render a srjson entity to text for transfer/storage. Free the char* * when finished. */ -extern char *srjson_Print(srjson_doc_t *doc, srjson_t *item); + extern char *srjson_Print(srjson_doc_t *doc, srjson_t *item); -/* + /* * Render a srjson entity to text for transfer/storage without any * formatting. Free the char* when finished. */ -extern char *srjson_PrintUnformatted(srjson_doc_t *doc, srjson_t *item); + extern char *srjson_PrintUnformatted(srjson_doc_t *doc, srjson_t *item); -/* Delete a srjson entity and all subentities. */ -extern void srjson_Delete(srjson_doc_t *doc, srjson_t *c); + /* Delete a srjson entity and all subentities. */ + extern void srjson_Delete(srjson_doc_t *doc, srjson_t *c); -/* Returns the number of items in an array (or object). */ -extern int srjson_GetArraySize(srjson_doc_t *doc, srjson_t *array); + /* Returns the number of items in an array (or object). */ + extern int srjson_GetArraySize(srjson_doc_t *doc, srjson_t *array); -/* + /* * Retrieve item number "item" from array "array". Returns NULL if * unsuccessful. */ -extern srjson_t *srjson_GetArrayItem(srjson_doc_t *doc, srjson_t *array, int item); + extern srjson_t *srjson_GetArrayItem( + srjson_doc_t *doc, srjson_t *array, int item); -/* Get item "string" from object. Case insensitive. */ -extern srjson_t *srjson_GetObjectItem(srjson_doc_t *doc, srjson_t *object, const char *string); + /* Get item "string" from object. Case insensitive. */ + extern srjson_t *srjson_GetObjectItem( + srjson_doc_t *doc, srjson_t *object, const char *string); -/* + /* * For analysing failed parses. This returns a pointer to the parse * error. You'll probably need to look a few chars back to make sense * of it. Defined when srjson_Parse() returns 0. 0 when srjson_Parse() * succeeds. */ -extern const char *srjson_GetErrorPtr(); - -/* These calls create a srjson item of the appropriate type. */ -extern srjson_t *srjson_CreateNull(srjson_doc_t *doc); -extern srjson_t *srjson_CreateTrue(srjson_doc_t *doc); -extern srjson_t *srjson_CreateFalse(srjson_doc_t *doc); -extern srjson_t *srjson_CreateBool(srjson_doc_t *doc, int b); -extern srjson_t *srjson_CreateNumber(srjson_doc_t *doc, double num); -extern srjson_t *srjson_CreateString(srjson_doc_t *doc, const char *string); -extern srjson_t *srjson_CreateStr(srjson_doc_t *doc, const char *string, int len); -extern srjson_t *srjson_CreateArray(srjson_doc_t *doc); -extern srjson_t *srjson_CreateObject(srjson_doc_t *doc); - -/* These utilities create an Array of count items. */ -extern srjson_t *srjson_CreateIntArray(srjson_doc_t *doc, int *numbers, int count); -extern srjson_t *srjson_CreateFloatArray(srjson_doc_t *doc, float *numbers, int count); -extern srjson_t *srjson_CreateDoubleArray(srjson_doc_t *doc, double *numbers, int count); -extern srjson_t *srjson_CreateStringArray(srjson_doc_t *doc, const char **strings, int count); - -/* Append item to the specified array/object. */ -extern void srjson_AddItemToArray(srjson_doc_t *doc, srjson_t *array, srjson_t *item); -extern void srjson_AddItemToObject(srjson_doc_t *doc, srjson_t *object, const char *string, srjson_t *item); -extern void srjson_AddStrItemToObject(srjson_doc_t *doc, srjson_t *object, const char *string, int len, srjson_t *item); - -/* + extern const char *srjson_GetErrorPtr(); + + /* These calls create a srjson item of the appropriate type. */ + extern srjson_t *srjson_CreateNull(srjson_doc_t *doc); + extern srjson_t *srjson_CreateTrue(srjson_doc_t *doc); + extern srjson_t *srjson_CreateFalse(srjson_doc_t *doc); + extern srjson_t *srjson_CreateBool(srjson_doc_t *doc, int b); + extern srjson_t *srjson_CreateNumber(srjson_doc_t *doc, double num); + extern srjson_t *srjson_CreateString(srjson_doc_t *doc, const char *string); + extern srjson_t *srjson_CreateStr( + srjson_doc_t *doc, const char *string, int len); + extern srjson_t *srjson_CreateArray(srjson_doc_t *doc); + extern srjson_t *srjson_CreateObject(srjson_doc_t *doc); + + /* These utilities create an Array of count items. */ + extern srjson_t *srjson_CreateIntArray( + srjson_doc_t *doc, int *numbers, int count); + extern srjson_t *srjson_CreateFloatArray( + srjson_doc_t *doc, float *numbers, int count); + extern srjson_t *srjson_CreateDoubleArray( + srjson_doc_t *doc, double *numbers, int count); + extern srjson_t *srjson_CreateStringArray( + srjson_doc_t *doc, const char **strings, int count); + + /* Append item to the specified array/object. */ + extern void srjson_AddItemToArray( + srjson_doc_t *doc, srjson_t *array, srjson_t *item); + extern void srjson_AddItemToObject(srjson_doc_t *doc, srjson_t *object, + const char *string, srjson_t *item); + extern void srjson_AddStrItemToObject(srjson_doc_t *doc, srjson_t *object, + const char *string, int len, srjson_t *item); + + /* * Append reference to item to the specified array/object. Use this * when you want to add an existing srjson to a new srjson, but don't * want to corrupt your existing srjson. */ -extern void srjson_AddItemReferenceToArray(srjson_doc_t *doc, srjson_t *array, srjson_t *item); -extern void srjson_AddItemReferenceToObject(srjson_doc_t *doc, srjson_t *object, const char *string, srjson_t *item); - -/* Remove/Detatch items from Arrays/Objects. */ -extern srjson_t *srjson_UnlinkItemFromObj(srjson_doc_t *doc, srjson_t *obj, srjson_t *item); -extern srjson_t *srjson_DetachItemFromArray(srjson_doc_t *doc, srjson_t *array, int which); -extern void srjson_DeleteItemFromArray(srjson_doc_t *doc, srjson_t *array, int which); -extern srjson_t *srjson_DetachItemFromObject(srjson_doc_t *doc, srjson_t *object, const char *string); -extern void srjson_DeleteItemFromObject(srjson_doc_t *doc, srjson_t *object, const char *string); - -/* Update array items. */ -extern void srjson_ReplaceItemInArray(srjson_doc_t *doc, srjson_t *array, int which, srjson_t *newitem); -extern void srjson_ReplaceItemInObject(srjson_doc_t *doc, srjson_t *object, const char *string, srjson_t *newitem); - -#define srjson_AddNullToObject(doc, object,name) srjson_AddItemToObject(doc, object, name, srjson_CreateNull(doc)) -#define srjson_AddTrueToObject(doc, object,name) srjson_AddItemToObject(doc, object, name, srjson_CreateTrue(doc)) -#define srjson_AddFalseToObject(doc, object,name) srjson_AddItemToObject(doc, object, name, srjson_CreateFalse(doc)) -#define srjson_AddNumberToObject(doc, object,name,n) srjson_AddItemToObject(doc, object, name, srjson_CreateNumber(doc,n)) -#define srjson_AddStringToObject(doc, object,name,s) srjson_AddItemToObject(doc, object, name, srjson_CreateString(doc,s)) -#define srjson_AddStrToObject(doc, object,name,s,l) srjson_AddItemToObject(doc, object, name, srjson_CreateStr(doc,s,l)) -#define srjson_AddStrStrToObject(doc, object,name,ln,s,l) srjson_AddStrItemToObject(doc, object, name, ln, srjson_CreateStr(doc,s,l)) + extern void srjson_AddItemReferenceToArray( + srjson_doc_t *doc, srjson_t *array, srjson_t *item); + extern void srjson_AddItemReferenceToObject(srjson_doc_t *doc, + srjson_t *object, const char *string, srjson_t *item); + + /* Remove/Detatch items from Arrays/Objects. */ + extern srjson_t *srjson_UnlinkItemFromObj( + srjson_doc_t *doc, srjson_t *obj, srjson_t *item); + extern srjson_t *srjson_DetachItemFromArray( + srjson_doc_t *doc, srjson_t *array, int which); + extern void srjson_DeleteItemFromArray( + srjson_doc_t *doc, srjson_t *array, int which); + extern srjson_t *srjson_DetachItemFromObject( + srjson_doc_t *doc, srjson_t *object, const char *string); + extern void srjson_DeleteItemFromObject( + srjson_doc_t *doc, srjson_t *object, const char *string); + + /* Update array items. */ + extern void srjson_ReplaceItemInArray( + srjson_doc_t *doc, srjson_t *array, int which, srjson_t *newitem); + extern void srjson_ReplaceItemInObject(srjson_doc_t *doc, srjson_t *object, + const char *string, srjson_t *newitem); + +#define srjson_AddNullToObject(doc, object, name) \ + srjson_AddItemToObject(doc, object, name, srjson_CreateNull(doc)) +#define srjson_AddTrueToObject(doc, object, name) \ + srjson_AddItemToObject(doc, object, name, srjson_CreateTrue(doc)) +#define srjson_AddFalseToObject(doc, object, name) \ + srjson_AddItemToObject(doc, object, name, srjson_CreateFalse(doc)) +#define srjson_AddNumberToObject(doc, object, name, n) \ + srjson_AddItemToObject(doc, object, name, srjson_CreateNumber(doc, n)) +#define srjson_AddStringToObject(doc, object, name, s) \ + srjson_AddItemToObject(doc, object, name, srjson_CreateString(doc, s)) +#define srjson_AddStrToObject(doc, object, name, s, l) \ + srjson_AddItemToObject(doc, object, name, srjson_CreateStr(doc, s, l)) +#define srjson_AddStrStrToObject(doc, object, name, ln, s, l) \ + srjson_AddStrItemToObject( \ + doc, object, name, ln, srjson_CreateStr(doc, s, l)) #ifdef __cplusplus } diff --git a/src/core/utils/sruid.c b/src/core/utils/sruid.c index 5888ffbdcb5..1236fe91855 100644 --- a/src/core/utils/sruid.c +++ b/src/core/utils/sruid.c @@ -58,7 +58,7 @@ static int sruid_shift_lfsr(unsigned int *lfsr, unsigned int mask) feedback = *lfsr & 0x1; *lfsr >>= 1; - if (feedback == 1) { + if(feedback == 1) { *lfsr ^= mask; } @@ -75,9 +75,11 @@ static void sruid_init_lfsr(void) * returns a 32 bit random integer * */ -static int sruid_get_random(){ +static int sruid_get_random() +{ return (sruid_shift_lfsr(&sruid_lfsr32, SRUID_MASK_32) - ^ sruid_shift_lfsr(&sruid_lfsr31, SRUID_MASK_31)) & 0xffffffff; + ^ sruid_shift_lfsr(&sruid_lfsr31, SRUID_MASK_31)) + & 0xffffffff; } /** @@ -87,28 +89,29 @@ int sruid_init(sruid_t *sid, char sep, char *cid, int mode) { int i; - if(sid==NULL) { + if(sid == NULL) { return -1; } memset(sid, 0, sizeof(sruid_t)); memcpy(sid->buf, "srid", 4); - if(cid!=NULL) - { - for(i=0; i<4 && cid[i]!='\0'; i++) + if(cid != NULL) { + for(i = 0; i < 4 && cid[i] != '\0'; i++) sid->buf[i] = cid[i]; } sid->buf[4] = sep; - if(server_id!=0) - i = snprintf(sid->buf+5, SRUID_SIZE - 5 /*so far*/ - 8 /* extra int */, - "%x%c%x%c%x%c", (unsigned int)server_id, sep, - (unsigned int)(uint64_t)time(NULL), sep, (unsigned int)my_pid(), sep); + if(server_id != 0) + i = snprintf(sid->buf + 5, + SRUID_SIZE - 5 /*so far*/ - 8 /* extra int */, "%x%c%x%c%x%c", + (unsigned int)server_id, sep, + (unsigned int)(uint64_t)time(NULL), sep, (unsigned int)my_pid(), + sep); else - i = snprintf(sid->buf+5, SRUID_SIZE - 5 /*so far*/ - 8 /* extra int */, - "%x%c%x%c", - (unsigned int)(uint64_t)time(NULL), sep, (unsigned int)my_pid(), sep); - if(i<=0 || i>SRUID_SIZE-13) - { + i = snprintf(sid->buf + 5, + SRUID_SIZE - 5 /*so far*/ - 8 /* extra int */, "%x%c%x%c", + (unsigned int)(uint64_t)time(NULL), sep, (unsigned int)my_pid(), + sep); + if(i <= 0 || i > SRUID_SIZE - 13) { LM_ERR("could not initialize sruid struct - output len: %d\n", i); return -1; } @@ -119,8 +122,8 @@ int sruid_init(sruid_t *sid, char sep, char *cid, int mode) sruid_init_lfsr(); } sid->pid = my_pid(); - LM_DBG("root for sruid is [%.*s] (%u / %d)\n", i+5, sid->uid.s, - sid->counter, i+5); + LM_DBG("root for sruid is [%.*s] (%u / %d)\n", i + 5, sid->uid.s, + sid->counter, i + 5); return 0; } @@ -132,24 +135,26 @@ int sruid_reinit(sruid_t *sid, int mode) int i; char sep; - if(sid==NULL) { + if(sid == NULL) { return -1; } sep = sid->buf[4]; sid->buf[5] = '\0'; - if(server_id!=0) { - i = snprintf(sid->buf+5, SRUID_SIZE - 5 /*so far*/ - 8 /* extra int */, - "%x%c%x%c%x%c", (unsigned int)server_id, sep, - (unsigned int)(uint64_t)time(NULL), sep, (unsigned int)my_pid(), sep); + if(server_id != 0) { + i = snprintf(sid->buf + 5, + SRUID_SIZE - 5 /*so far*/ - 8 /* extra int */, "%x%c%x%c%x%c", + (unsigned int)server_id, sep, + (unsigned int)(uint64_t)time(NULL), sep, (unsigned int)my_pid(), + sep); } else { - i = snprintf(sid->buf+5, SRUID_SIZE - 5 /*so far*/ - 8 /* extra int */, - "%x%c%x%c", - (unsigned int)(uint64_t)time(NULL), sep, (unsigned int)my_pid(), sep); + i = snprintf(sid->buf + 5, + SRUID_SIZE - 5 /*so far*/ - 8 /* extra int */, "%x%c%x%c", + (unsigned int)(uint64_t)time(NULL), sep, (unsigned int)my_pid(), + sep); } - if(i<=0 || i>SRUID_SIZE-13) - { + if(i <= 0 || i > SRUID_SIZE - 13) { LM_ERR("could not re-initialize sruid struct - output len: %d\n", i); return -1; } @@ -160,8 +165,8 @@ int sruid_reinit(sruid_t *sid, int mode) sruid_init_lfsr(); } sid->pid = my_pid(); - LM_DBG("re-init root for sruid is [%.*s] (%u / %d)\n", i+5, sid->uid.s, - sid->counter, i+5); + LM_DBG("re-init root for sruid is [%.*s] (%u / %d)\n", i + 5, sid->uid.s, + sid->counter, i + 5); return 0; } @@ -174,10 +179,10 @@ int sruid_nextx(sruid_t *sid, str *x) int i; unsigned int val; - if(sid==NULL) { + if(sid == NULL) { return -1; } - if(x!=NULL && x->len>0) { + if(x != NULL && x->len > 0) { if(sid->out - sid->buf + 1 + x->len >= SRUID_SIZE) { LM_ERR("not enough space for x value\n"); return -1; @@ -185,13 +190,13 @@ int sruid_nextx(sruid_t *sid, str *x) } sid->counter++; - if(sid->counter==0) { + if(sid->counter == 0) { if(sid->mode == SRUID_INC) { /* counter overflow - re-init to have new timestamp */ - if(sruid_reinit(sid, SRUID_INC)<0) + if(sruid_reinit(sid, SRUID_INC) < 0) return -1; } - sid->counter=1; + sid->counter = 1; } if(sid->mode == SRUID_LFSR) { @@ -200,12 +205,12 @@ int sruid_nextx(sruid_t *sid, str *x) val = sid->counter; } i = 0; - while(val!=0) { - digit = val & 0x0f; + while(val != 0) { + digit = val & 0x0f; sid->out[i++] = (digit >= 10) ? digit + 'a' - 10 : digit + '0'; val >>= 4; } - if(x!=NULL && x->len>0) { + if(x != NULL && x->len > 0) { sid->out[i++] = sid->buf[4]; /* sep */ memcpy(sid->out + i, x->s, x->len); i += x->len; @@ -226,7 +231,7 @@ int sruid_nexthid(sruid_t *sid, str *sval) str hval = str_init("0"); unsigned int hid = 0; - if(sval==NULL || sval->s==NULL || sval->len<=0) { + if(sval == NULL || sval->s == NULL || sval->len <= 0) { return sruid_nextx(sid, &hval); } hval = *sval; @@ -249,7 +254,8 @@ int sruid_next(sruid_t *sid) */ int sruid_nextx_safe(sruid_t *sid, str *x) { - if(unlikely(sid->pid!=my_pid())) sruid_reinit(sid, sid->mode); + if(unlikely(sid->pid != my_pid())) + sruid_reinit(sid, sid->mode); return sruid_nextx(sid, x); } @@ -258,7 +264,8 @@ int sruid_nextx_safe(sruid_t *sid, str *x) */ int sruid_nexthid_safe(sruid_t *sid, str *sval) { - if(unlikely(sid->pid!=my_pid())) sruid_reinit(sid, sid->mode); + if(unlikely(sid->pid != my_pid())) + sruid_reinit(sid, sid->mode); return sruid_nexthid(sid, sval); } @@ -267,7 +274,8 @@ int sruid_nexthid_safe(sruid_t *sid, str *sval) */ int sruid_next_safe(sruid_t *sid) { - if(unlikely(sid->pid!=my_pid())) sruid_reinit(sid, sid->mode); + if(unlikely(sid->pid != my_pid())) + sruid_reinit(sid, sid->mode); return sruid_nextx(sid, NULL); } @@ -276,7 +284,7 @@ int sruid_next_safe(sruid_t *sid) */ int sruid_uuid_api_set(sruid_uuid_api_t *sapi) { - if(_sruid_uuid_api.fgenerate!=NULL) { + if(_sruid_uuid_api.fgenerate != NULL) { LM_ERR("sruid uuid api already set\n"); return -1; } @@ -320,4 +328,3 @@ int sruid_uuid_generate_random(char *out, int *len) } return _sruid_uuid_api.fgenerate_random(out, len); } - diff --git a/src/core/utils/sruid.h b/src/core/utils/sruid.h index a97675167f8..7b42b6b7af1 100644 --- a/src/core/utils/sruid.h +++ b/src/core/utils/sruid.h @@ -31,11 +31,16 @@ #include "../../core/str.h" -#define SRUID_SIZE 64 +#define SRUID_SIZE 64 -typedef enum {SRUID_INC=0, SRUID_LFSR=1} sruid_mode_t; +typedef enum +{ + SRUID_INC = 0, + SRUID_LFSR = 1 +} sruid_mode_t; -typedef struct sruid { +typedef struct sruid +{ char buf[SRUID_SIZE]; char *out; str uid; @@ -56,7 +61,8 @@ int sruid_nexthid_safe(sruid_t *sid, str *sval); typedef int (*sruid_uuid_generate_f)(char *out, int *len); -typedef struct sruid_uuid_api { +typedef struct sruid_uuid_api +{ sruid_uuid_generate_f fgenerate; sruid_uuid_generate_f fgenerate_time; sruid_uuid_generate_f fgenerate_random; diff --git a/src/core/utils/tmrec.c b/src/core/utils/tmrec.c index 14e92439145..dd413ff392b 100644 --- a/src/core/utils/tmrec.c +++ b/src/core/utils/tmrec.c @@ -50,8 +50,7 @@ static inline int tr_strz_to_int(char *_bp) return 0; _v = 0; _p = _bp; - while(*_p && *_p>='0' && *_p<='9') - { + while(*_p && *_p >= '0' && *_p <= '9') { _v += *_p - '0'; _p++; } @@ -69,26 +68,25 @@ static inline int tr_strz_to_int(char *_bp) #ifndef USE_YWEEK_U #ifndef USE_YWEEK_V #ifndef USE_YWEEK_W -#define USE_YWEEK_W /* Monday system */. +#define USE_YWEEK_W /* Monday system */ . #endif #endif #endif #ifdef USE_YWEEK_U -#define SUN_WEEK(t) (int)(((t)->tm_yday + 7 - \ - ((t)->tm_wday)) / 7) +#define SUN_WEEK(t) (int)(((t)->tm_yday + 7 - ((t)->tm_wday)) / 7) #else -#define MON_WEEK(t) (int)(((t)->tm_yday + 7 - \ - ((t)->tm_wday ? (t)->tm_wday - 1 : 6)) / 7) +#define MON_WEEK(t) \ + (int)(((t)->tm_yday + 7 - ((t)->tm_wday ? (t)->tm_wday - 1 : 6)) / 7) #endif -#define ac_get_wday_yr(t) (int)((t)->tm_yday/7) -#define ac_get_wday_mr(t) (int)(((t)->tm_mday-1)/7) +#define ac_get_wday_yr(t) (int)((t)->tm_yday / 7) +#define ac_get_wday_mr(t) (int)(((t)->tm_mday - 1) / 7) ac_tm_t *ac_tm_new(void) { ac_tm_t *_atp = NULL; - _atp = (ac_tm_t*)pkg_malloc(sizeof(ac_tm_t)); + _atp = (ac_tm_t *)pkg_malloc(sizeof(ac_tm_t)); if(!_atp) return NULL; memset(_atp, 0, sizeof(ac_tm_t)); @@ -96,19 +94,19 @@ ac_tm_t *ac_tm_new(void) return _atp; } -int ac_tm_fill(ac_tm_t *_atp, struct tm* _tm) +int ac_tm_fill(ac_tm_t *_atp, struct tm *_tm) { if(!_atp || !_tm) return -1; - _atp->t.tm_sec = _tm->tm_sec; /* seconds */ - _atp->t.tm_min = _tm->tm_min; /* minutes */ - _atp->t.tm_hour = _tm->tm_hour; /* hours */ - _atp->t.tm_mday = _tm->tm_mday; /* day of the month */ - _atp->t.tm_mon = _tm->tm_mon; /* month */ - _atp->t.tm_year = _tm->tm_year; /* year */ - _atp->t.tm_wday = _tm->tm_wday; /* day of the week */ - _atp->t.tm_yday = _tm->tm_yday; /* day in the year */ - _atp->t.tm_isdst = _tm->tm_isdst; /* daylight saving time */ + _atp->t.tm_sec = _tm->tm_sec; /* seconds */ + _atp->t.tm_min = _tm->tm_min; /* minutes */ + _atp->t.tm_hour = _tm->tm_hour; /* hours */ + _atp->t.tm_mday = _tm->tm_mday; /* day of the month */ + _atp->t.tm_mon = _tm->tm_mon; /* month */ + _atp->t.tm_year = _tm->tm_year; /* year */ + _atp->t.tm_wday = _tm->tm_wday; /* day of the week */ + _atp->t.tm_yday = _tm->tm_yday; /* day in the year */ + _atp->t.tm_isdst = _tm->tm_isdst; /* daylight saving time */ _atp->mweek = ac_get_mweek(_tm); _atp->yweek = ac_get_yweek(_tm); @@ -127,18 +125,20 @@ int ac_tm_set_time(ac_tm_t *_atp, time_t _t) return ac_tm_fill(_atp, &tnow); } -int ac_get_mweek(struct tm* _tm) +int ac_get_mweek(struct tm *_tm) { if(!_tm) return -1; #ifdef USE_YWEEK_U - return ((_tm->tm_mday-1)/7 + (7-_tm->tm_wday+(_tm->tm_mday-1)%7)/7); + return ((_tm->tm_mday - 1) / 7 + + (7 - _tm->tm_wday + (_tm->tm_mday - 1) % 7) / 7); #else - return ((_tm->tm_mday-1)/7 + (7-(6+_tm->tm_wday)%7+(_tm->tm_mday-1)%7)/7); + return ((_tm->tm_mday - 1) / 7 + + (7 - (6 + _tm->tm_wday) % 7 + (_tm->tm_mday - 1) % 7) / 7); #endif } -int ac_get_yweek(struct tm* _tm) +int ac_get_yweek(struct tm *_tm) { int week = -1; #ifdef USE_YWEEK_V @@ -155,13 +155,12 @@ int ac_get_yweek(struct tm* _tm) #endif #ifdef USE_YWEEK_V - days = ((_tm->tm_yday + 7 - (_tm->tm_wday ? _tm->tm_wday-1 : 6)) % 7); + days = ((_tm->tm_yday + 7 - (_tm->tm_wday ? _tm->tm_wday - 1 : 6)) % 7); if(days >= 4) week++; - else - if(week == 0) - week = 53; + else if(week == 0) + week = 53; #endif return week; } @@ -210,25 +209,27 @@ ac_maxval_t *ac_get_maxval(ac_tm_t *_atp) if(!_atp) return NULL; - _amp = (ac_maxval_t*)pkg_malloc(sizeof(ac_maxval_t)); + _amp = (ac_maxval_t *)pkg_malloc(sizeof(ac_maxval_t)); if(!_amp) return NULL; /* the number of the days in the year */ - _amp->yday = 365 + tr_is_leap_year(_atp->t.tm_year+1900); + _amp->yday = 365 + tr_is_leap_year(_atp->t.tm_year + 1900); /* the number of the days in the month */ - switch(_atp->t.tm_mon) - { + switch(_atp->t.tm_mon) { case 1: if(_amp->yday == 366) _amp->mday = 29; else _amp->mday = 28; - break; - case 3: case 5: case 8: case 10: + break; + case 3: + case 5: + case 8: + case 10: _amp->mday = 30; - break; + break; default: _amp->mday = 31; } @@ -244,20 +245,26 @@ ac_maxval_t *ac_get_maxval(ac_tm_t *_atp) _v = _atp->t.tm_wday - _tm.tm_wday + 1; else _v = _tm.tm_wday - _atp->t.tm_wday; - _amp->ywday = (int)((_tm.tm_yday-_v)/7) + 1; + _amp->ywday = (int)((_tm.tm_yday - _v) / 7) + 1; /* maximum number of weeks in the year */ _amp->yweek = ac_get_yweek(&_tm) + 1; /* maximum number of the week day in the month */ - _amp->mwday=(int)((_amp->mday-1-(_amp->mday-_atp->t.tm_mday)%7)/7)+1; + _amp->mwday = + (int)((_amp->mday - 1 - (_amp->mday - _atp->t.tm_mday) % 7) / 7) + + 1; /* maximum number of weeks in the month */ - _v = (_atp->t.tm_wday + (_amp->mday - _atp->t.tm_mday)%7)%7; + _v = (_atp->t.tm_wday + (_amp->mday - _atp->t.tm_mday) % 7) % 7; #ifdef USE_YWEEK_U - _amp->mweek = (int)((_amp->mday-1)/7+(7-_v+(_amp->mday-1)%7)/7)+1; + _amp->mweek = + (int)((_amp->mday - 1) / 7 + (7 - _v + (_amp->mday - 1) % 7) / 7) + + 1; #else - _amp->mweek = (int)((_amp->mday-1)/7+(7-(6+_v)%7+(_amp->mday-1)%7)/7)+1; + _amp->mweek = (int)((_amp->mday - 1) / 7 + + (7 - (6 + _v) % 7 + (_amp->mday - 1) % 7) / 7) + + 1; #endif _atp->mv = _amp; @@ -267,41 +274,39 @@ ac_maxval_t *ac_get_maxval(ac_tm_t *_atp) int ac_print(ac_tm_t *_atp) { static char *_wdays[] = {"SU", "MO", "TU", "WE", "TH", "FR", "SA"}; - if(!_atp) - { + if(!_atp) { printf("\n(null)\n"); return -1; } - printf("\nSys time: %" PRIu64 "\nTime: %02d:%02d:%02d\n", (uint64_t)_atp->time, - _atp->t.tm_hour, _atp->t.tm_min, _atp->t.tm_sec); + printf("\nSys time: %" PRIu64 "\nTime: %02d:%02d:%02d\n", + (uint64_t)_atp->time, _atp->t.tm_hour, _atp->t.tm_min, + _atp->t.tm_sec); printf("Date: %s, %04d-%02d-%02d\n", _wdays[_atp->t.tm_wday], - _atp->t.tm_year+1900, _atp->t.tm_mon+1, _atp->t.tm_mday); + _atp->t.tm_year + 1900, _atp->t.tm_mon + 1, _atp->t.tm_mday); printf("Year day: %d\nYear week-day: %d\nYear week: %d\n", _atp->t.tm_yday, _atp->ywday, _atp->yweek); printf("Month week: %d\nMonth week-day: %d\n", _atp->mweek, _atp->mwday); - if(_atp->mv) - { + if(_atp->mv) { printf("Max ydays: %d\nMax yweeks: %d\nMax yweekday: %d\n", - _atp->mv->yday, _atp->mv->yweek, _atp->mv->ywday);; + _atp->mv->yday, _atp->mv->yweek, _atp->mv->ywday); + ; printf("Max mdays: %d\nMax mweeks: %d\nMax mweekday: %d\n", - _atp->mv->mday, _atp->mv->mweek, _atp->mv->mwday);; + _atp->mv->mday, _atp->mv->mweek, _atp->mv->mwday); + ; } return 0; } - - - /************************ imported from "tmrec.c" ***************************/ -#define _D(c) ((c) -'0') +#define _D(c) ((c) - '0') tr_byxxx_t *tr_byxxx_new(void) { tr_byxxx_t *_bxp = NULL; - _bxp = (tr_byxxx_t*)pkg_malloc(sizeof(tr_byxxx_t)); + _bxp = (tr_byxxx_t *)pkg_malloc(sizeof(tr_byxxx_t)); if(!_bxp) return NULL; memset(_bxp, 0, sizeof(tr_byxxx_t)); @@ -313,19 +318,18 @@ int tr_byxxx_init(tr_byxxx_t *_bxp, int _nr) if(!_bxp) return -1; _bxp->nr = _nr; - _bxp->xxx = (int*)pkg_malloc(_nr*sizeof(int)); + _bxp->xxx = (int *)pkg_malloc(_nr * sizeof(int)); if(!_bxp->xxx) return -1; - _bxp->req = (int*)pkg_malloc(_nr*sizeof(int)); - if(!_bxp->req) - { + _bxp->req = (int *)pkg_malloc(_nr * sizeof(int)); + if(!_bxp->req) { pkg_free(_bxp->xxx); _bxp->xxx = NULL; return -1; } - memset(_bxp->xxx, 0, _nr*sizeof(int)); - memset(_bxp->req, 0, _nr*sizeof(int)); + memset(_bxp->xxx, 0, _nr * sizeof(int)); + memset(_bxp->req, 0, _nr * sizeof(int)); return 0; } @@ -346,11 +350,11 @@ int tr_byxxx_free(tr_byxxx_t *_bxp) tmrec_t *tmrec_new(void) { tmrec_t *_trp = NULL; - _trp = (tmrec_t*)pkg_malloc(sizeof(tmrec_t)); + _trp = (tmrec_t *)pkg_malloc(sizeof(tmrec_t)); if(!_trp) return NULL; memset(_trp, 0, sizeof(tmrec_t)); - localtime_r(&_trp->dtstart,&(_trp->ts)); + localtime_r(&_trp->dtstart, &(_trp->ts)); return _trp; } @@ -388,7 +392,7 @@ int tr_parse_dtstart(tmrec_t *_trp, char *_in) if(!_trp || !_in) return -1; _trp->dtstart = ic_parse_datetime(_in, &(_trp->ts)); - return (_trp->dtstart==0)?-1:0; + return (_trp->dtstart == 0) ? -1 : 0; } int tr_parse_dtend(tmrec_t *_trp, char *_in) @@ -396,8 +400,8 @@ int tr_parse_dtend(tmrec_t *_trp, char *_in) struct tm _tm; if(!_trp || !_in) return -1; - _trp->dtend = ic_parse_datetime(_in,&_tm); - return (_trp->dtend==0)?-1:0; + _trp->dtend = ic_parse_datetime(_in, &_tm); + return (_trp->dtend == 0) ? -1 : 0; } int tr_parse_duration(tmrec_t *_trp, char *_in) @@ -405,7 +409,7 @@ int tr_parse_duration(tmrec_t *_trp, char *_in) if(!_trp || !_in) return -1; _trp->duration = ic_parse_duration(_in); - return (_trp->duration==0)?-1:0; + return (_trp->duration == 0) ? -1 : 0; } int tr_parse_until(tmrec_t *_trp, char *_in) @@ -414,30 +418,26 @@ int tr_parse_until(tmrec_t *_trp, char *_in) if(!_trp || !_in) return -1; _trp->until = ic_parse_datetime(_in, &_tm); - return (_trp->until==0)?-1:0; + return (_trp->until == 0) ? -1 : 0; } int tr_parse_freq(tmrec_t *_trp, char *_in) { if(!_trp || !_in) return -1; - if(!strcasecmp(_in, "daily")) - { + if(!strcasecmp(_in, "daily")) { _trp->freq = FREQ_DAILY; return 0; } - if(!strcasecmp(_in, "weekly")) - { + if(!strcasecmp(_in, "weekly")) { _trp->freq = FREQ_WEEKLY; return 0; } - if(!strcasecmp(_in, "monthly")) - { + if(!strcasecmp(_in, "monthly")) { _trp->freq = FREQ_MONTHLY; return 0; } - if(!strcasecmp(_in, "yearly")) - { + if(!strcasecmp(_in, "yearly")) { _trp->freq = FREQ_YEARLY; return 0; } @@ -507,56 +507,50 @@ int tr_print(tmrec_t *_trp) static char *_wdays[] = {"SU", "MO", "TU", "WE", "TH", "FR", "SA"}; int i; - if(!_trp) - { + if(!_trp) { printf("\n(null)\n"); return -1; } printf("Recurrence definition\n-- start time ---\n"); printf("Sys time: %" PRIu64 "\n", (uint64_t)_trp->dtstart); - printf("Time: %02d:%02d:%02d\n", _trp->ts.tm_hour, - _trp->ts.tm_min, _trp->ts.tm_sec); + printf("Time: %02d:%02d:%02d\n", _trp->ts.tm_hour, _trp->ts.tm_min, + _trp->ts.tm_sec); printf("Date: %s, %04d-%02d-%02d\n", _wdays[_trp->ts.tm_wday], - _trp->ts.tm_year+1900, _trp->ts.tm_mon+1, _trp->ts.tm_mday); + _trp->ts.tm_year + 1900, _trp->ts.tm_mon + 1, _trp->ts.tm_mday); printf("---\n"); printf("End time: %" PRIu64 "\n", (uint64_t)_trp->dtend); printf("Duration: %" PRIu64 "\n", (uint64_t)_trp->duration); printf("Until: %" PRIu64 "\n", (uint64_t)_trp->until); printf("Freq: %d\n", (int)_trp->freq); printf("Interval: %d\n", (int)_trp->interval); - if(_trp->byday) - { + if(_trp->byday) { printf("Byday: "); - for(i=0; i<_trp->byday->nr; i++) + for(i = 0; i < _trp->byday->nr; i++) printf(" %d%s", _trp->byday->req[i], _wdays[_trp->byday->xxx[i]]); printf("\n"); } - if(_trp->bymday) - { + if(_trp->bymday) { printf("Bymday: %d:", _trp->bymday->nr); - for(i=0; i<_trp->bymday->nr; i++) - printf(" %d", _trp->bymday->xxx[i]*_trp->bymday->req[i]); + for(i = 0; i < _trp->bymday->nr; i++) + printf(" %d", _trp->bymday->xxx[i] * _trp->bymday->req[i]); printf("\n"); } - if(_trp->byyday) - { + if(_trp->byyday) { printf("Byyday:"); - for(i=0; i<_trp->byyday->nr; i++) - printf(" %d", _trp->byyday->xxx[i]*_trp->byyday->req[i]); + for(i = 0; i < _trp->byyday->nr; i++) + printf(" %d", _trp->byyday->xxx[i] * _trp->byyday->req[i]); printf("\n"); } - if(_trp->bymonth) - { + if(_trp->bymonth) { printf("Bymonth: %d:", _trp->bymonth->nr); - for(i=0; i< _trp->bymonth->nr; i++) - printf(" %d", _trp->bymonth->xxx[i]*_trp->bymonth->req[i]); + for(i = 0; i < _trp->bymonth->nr; i++) + printf(" %d", _trp->bymonth->xxx[i] * _trp->bymonth->req[i]); printf("\n"); } - if(_trp->byweekno) - { + if(_trp->byweekno) { printf("Byweekno: "); - for(i=0; i<_trp->byweekno->nr; i++) - printf(" %d", _trp->byweekno->xxx[i]*_trp->byweekno->req[i]); + for(i = 0; i < _trp->byweekno->nr; i++) + printf(" %d", _trp->byweekno->xxx[i] * _trp->byweekno->req[i]); printf("\n"); } printf("Weekstart: %d\n", _trp->wkst); @@ -565,17 +559,17 @@ int tr_print(tmrec_t *_trp) time_t ic_parse_datetime(char *_in, struct tm *_tm) { - if(!_in || !_tm || strlen(_in)!=15) + if(!_in || !_tm || strlen(_in) != 15) return 0; memset(_tm, 0, sizeof(struct tm)); - _tm->tm_year = _D(_in[0])*1000 + _D(_in[1])*100 - + _D(_in[2])*10 + _D(_in[3]) - 1900; - _tm->tm_mon = _D(_in[4])*10 + _D(_in[5]) - 1; - _tm->tm_mday = _D(_in[6])*10 + _D(_in[7]); - _tm->tm_hour = _D(_in[9])*10 + _D(_in[10]); - _tm->tm_min = _D(_in[11])*10 + _D(_in[12]); - _tm->tm_sec = _D(_in[13])*10 + _D(_in[14]); + _tm->tm_year = _D(_in[0]) * 1000 + _D(_in[1]) * 100 + _D(_in[2]) * 10 + + _D(_in[3]) - 1900; + _tm->tm_mon = _D(_in[4]) * 10 + _D(_in[5]) - 1; + _tm->tm_mday = _D(_in[6]) * 10 + _D(_in[7]); + _tm->tm_hour = _D(_in[9]) * 10 + _D(_in[10]); + _tm->tm_min = _D(_in[11]) * 10 + _D(_in[12]); + _tm->tm_sec = _D(_in[13]) * 10 + _D(_in[14]); _tm->tm_isdst = -1 /*daylight*/; return mktime(_tm); } @@ -586,73 +580,76 @@ time_t ic_parse_duration(char *_in) char *_p; int _fl; - if(!_in || (*_in!='+' && *_in!='-' && *_in!='P' && *_in!='p')) + if(!_in || (*_in != '+' && *_in != '-' && *_in != 'P' && *_in != 'p')) return 0; - if(*_in == 'P' || *_in=='p') - _p = _in+1; - else - { - if(strlen(_in)<2 || (_in[1]!='P' && _in[1]!='p')) + if(*_in == 'P' || *_in == 'p') + _p = _in + 1; + else { + if(strlen(_in) < 2 || (_in[1] != 'P' && _in[1] != 'p')) return 0; - _p = _in+2; + _p = _in + 2; } _t = _ft = 0; _fl = 1; - while(*_p) - { - switch(*_p) - { - case '0': case '1': case '2': - case '3': case '4': case '5': - case '6': case '7': case '8': + while(*_p) { + switch(*_p) { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': case '9': - _t = _t*10 + *_p - '0'; - break; + _t = _t * 10 + *_p - '0'; + break; case 'w': case 'W': if(!_fl) return 0; - _ft += _t*7*24*3600; + _ft += _t * 7 * 24 * 3600; _t = 0; - break; + break; case 'd': case 'D': if(!_fl) return 0; - _ft += _t*24*3600; + _ft += _t * 24 * 3600; _t = 0; - break; + break; case 'h': case 'H': if(_fl) return 0; - _ft += _t*3600; + _ft += _t * 3600; _t = 0; - break; + break; case 'm': case 'M': if(_fl) return 0; - _ft += _t*60; + _ft += _t * 60; _t = 0; - break; + break; case 's': case 'S': if(_fl) return 0; _ft += _t; _t = 0; - break; + break; case 't': case 'T': if(!_fl) return 0; _fl = 0; - break; + break; default: return 0; } @@ -675,113 +672,113 @@ tr_byxxx_t *ic_parse_byday(char *_in) return NULL; _p = _in; _nr = 1; - while(*_p) - { + while(*_p) { if(*_p == ',') _nr++; _p++; } - if(tr_byxxx_init(_bxp, _nr) < 0) - { + if(tr_byxxx_init(_bxp, _nr) < 0) { tr_byxxx_free(_bxp); return NULL; } _p = _in; _nr = _v = 0; _s = 1; - while(*_p && _nr < _bxp->nr) - { - switch(*_p) - { - case '0': case '1': case '2': - case '3': case '4': case '5': - case '6': case '7': case '8': + while(*_p && _nr < _bxp->nr) { + switch(*_p) { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': case '9': - _v = _v*10 + *_p - '0'; - break; + _v = _v * 10 + *_p - '0'; + break; case 's': case 'S': _p++; - switch(*_p) - { + switch(*_p) { case 'a': case 'A': _bxp->xxx[_nr] = WDAY_SA; - _bxp->req[_nr] = _s*_v; - break; + _bxp->req[_nr] = _s * _v; + break; case 'u': case 'U': _bxp->xxx[_nr] = WDAY_SU; - _bxp->req[_nr] = _s*_v; - break; + _bxp->req[_nr] = _s * _v; + break; default: goto error; } _s = 1; _v = 0; - break; + break; case 'm': case 'M': _p++; - if(*_p!='o' && *_p!='O') + if(*_p != 'o' && *_p != 'O') goto error; _bxp->xxx[_nr] = WDAY_MO; - _bxp->req[_nr] = _s*_v; + _bxp->req[_nr] = _s * _v; _s = 1; _v = 0; - break; + break; case 't': case 'T': _p++; - switch(*_p) - { + switch(*_p) { case 'h': case 'H': _bxp->xxx[_nr] = WDAY_TH; - _bxp->req[_nr] = _s*_v; - break; + _bxp->req[_nr] = _s * _v; + break; case 'u': case 'U': _bxp->xxx[_nr] = WDAY_TU; - _bxp->req[_nr] = _s*_v; - break; + _bxp->req[_nr] = _s * _v; + break; default: goto error; } _s = 1; _v = 0; - break; + break; case 'w': case 'W': _p++; - if(*_p!='e' && *_p!='E') + if(*_p != 'e' && *_p != 'E') goto error; _bxp->xxx[_nr] = WDAY_WE; - _bxp->req[_nr] = _s*_v; + _bxp->req[_nr] = _s * _v; _s = 1; _v = 0; - break; + break; case 'f': case 'F': _p++; - if(*_p!='r' && *_p!='R') + if(*_p != 'r' && *_p != 'R') goto error; _bxp->xxx[_nr] = WDAY_FR; - _bxp->req[_nr] = _s*_v; + _bxp->req[_nr] = _s * _v; _s = 1; _v = 0; - break; + break; case '-': _s = -1; - break; + break; case '+': case ' ': case '\t': - break; + break; case ',': _nr++; - break; + break; default: goto error; } @@ -808,52 +805,53 @@ tr_byxxx_t *ic_parse_byxxx(char *_in) return NULL; _p = _in; _nr = 1; - while(*_p) - { + while(*_p) { if(*_p == ',') _nr++; _p++; } - if(tr_byxxx_init(_bxp, _nr) < 0) - { + if(tr_byxxx_init(_bxp, _nr) < 0) { tr_byxxx_free(_bxp); return NULL; } _p = _in; _nr = _v = 0; _s = 1; - while(*_p && _nr < _bxp->nr) - { - switch(*_p) - { - case '0': case '1': case '2': - case '3': case '4': case '5': - case '6': case '7': case '8': + while(*_p && _nr < _bxp->nr) { + switch(*_p) { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': case '9': - _v = _v*10 + *_p - '0'; - break; + _v = _v * 10 + *_p - '0'; + break; case '-': _s = -1; - break; + break; case '+': case ' ': case '\t': - break; + break; case ',': _bxp->xxx[_nr] = _v; _bxp->req[_nr] = _s; _s = 1; _v = 0; _nr++; - break; + break; default: goto error; } _p++; } - if(_nr < _bxp->nr) - { + if(_nr < _bxp->nr) { _bxp->xxx[_nr] = _v; _bxp->req[_nr] = _s; } @@ -866,15 +864,13 @@ tr_byxxx_t *ic_parse_byxxx(char *_in) int ic_parse_wkst(char *_in) { - if(!_in || strlen(_in)!=2) + if(!_in || strlen(_in) != 2) goto error; - switch(_in[0]) - { + switch(_in[0]) { case 's': case 'S': - switch(_in[1]) - { + switch(_in[1]) { case 'a': case 'A': return WDAY_SA; @@ -886,13 +882,12 @@ int ic_parse_wkst(char *_in) } case 'm': case 'M': - if(_in[1]!='o' && _in[1]!='O') + if(_in[1] != 'o' && _in[1] != 'O') goto error; return WDAY_MO; case 't': case 'T': - switch(_in[1]) - { + switch(_in[1]) { case 'h': case 'H': return WDAY_TH; @@ -904,15 +899,15 @@ int ic_parse_wkst(char *_in) } case 'w': case 'W': - if(_in[1]!='e' && _in[1]!='E') + if(_in[1] != 'e' && _in[1] != 'E') goto error; return WDAY_WE; case 'f': case 'F': - if(_in[1]!='r' && _in[1]!='R') + if(_in[1] != 'r' && _in[1] != 'R') goto error; return WDAY_FR; - break; + break; default: goto error; } @@ -930,17 +925,17 @@ int ic_parse_wkst(char *_in) * =====imported from "checktr.c" */ -#define REC_ERR -1 -#define REC_MATCH 0 +#define REC_ERR -1 +#define REC_MATCH 0 #define REC_NOMATCH 1 -#define _IS_SET(x) (((x)>0)?1:0) +#define _IS_SET(x) (((x) > 0) ? 1 : 0) /*** local headers ***/ -int get_min_interval(tmrec_t*); -int check_min_unit(tmrec_t*, ac_tm_t*, tr_res_t*); +int get_min_interval(tmrec_t *); +int check_min_unit(tmrec_t *, ac_tm_t *, tr_res_t *); int check_freq_interval(tmrec_t *_trp, ac_tm_t *_atp); -int check_byxxx(tmrec_t*, ac_tm_t*); +int check_byxxx(tmrec_t *, ac_tm_t *); /** * @@ -961,19 +956,14 @@ int tr_check_recurrence(tmrec_t *_trp, ac_tm_t *_atp, tr_res_t *_tsw) if(!_IS_SET(_trp->duration)) _trp->duration = _trp->dtend - _trp->dtstart; - if(_atp->time <= _trp->dtstart+_trp->duration) - { - if(_tsw) - { - if(_tsw->flag & TSW_RSET) - { - if(_tsw->rest>_trp->dtstart+_trp->duration-_atp->time) - _tsw->rest = _trp->dtstart+_trp->duration - _atp->time; - } - else - { + if(_atp->time <= _trp->dtstart + _trp->duration) { + if(_tsw) { + if(_tsw->flag & TSW_RSET) { + if(_tsw->rest > _trp->dtstart + _trp->duration - _atp->time) + _tsw->rest = _trp->dtstart + _trp->duration - _atp->time; + } else { _tsw->flag |= TSW_RSET; - _tsw->rest = _trp->dtstart+_trp->duration - _atp->time; + _tsw->rest = _trp->dtstart + _trp->duration - _atp->time; } } return REC_MATCH; @@ -984,13 +974,13 @@ int tr_check_recurrence(tmrec_t *_trp, ac_tm_t *_atp, tr_res_t *_tsw) return REC_NOMATCH; /* check if the instance of recurrence matches the 'interval' */ - if(check_freq_interval(_trp, _atp)!=REC_MATCH) + if(check_freq_interval(_trp, _atp) != REC_MATCH) return REC_NOMATCH; - if(check_min_unit(_trp, _atp, _tsw)!=REC_MATCH) + if(check_min_unit(_trp, _atp, _tsw) != REC_MATCH) return REC_NOMATCH; - if(check_byxxx(_trp, _atp)!=REC_MATCH) + if(check_byxxx(_trp, _atp) != REC_MATCH) return REC_NOMATCH; return REC_MATCH; @@ -1007,11 +997,10 @@ int check_freq_interval(tmrec_t *_trp, ac_tm_t *_atp) if(!_IS_SET(_trp->freq)) return REC_NOMATCH; - if(!_IS_SET(_trp->interval) || _trp->interval==1) + if(!_IS_SET(_trp->interval) || _trp->interval == 1) return REC_MATCH; - switch(_trp->freq) - { + switch(_trp->freq) { case FREQ_DAILY: case FREQ_WEEKLY: memset(&_tm, 0, sizeof(struct tm)); @@ -1025,24 +1014,27 @@ int check_freq_interval(tmrec_t *_trp, ac_tm_t *_atp) _tm.tm_mday = _atp->t.tm_mday; _t1 = (uint64_t)mktime(&_tm); if(_trp->freq == FREQ_DAILY) - return (((_t1-_t0)/(24*3600))%_trp->interval==0)? - REC_MATCH:REC_NOMATCH; + return (((_t1 - _t0) / (24 * 3600)) % _trp->interval == 0) + ? REC_MATCH + : REC_NOMATCH; #ifdef USE_YWEEK_U - _t0 -= _trp->ts.tm_wday*24*3600; - _t1 -= _atp->t.tm_wday*24*3600; + _t0 -= _trp->ts.tm_wday * 24 * 3600; + _t1 -= _atp->t.tm_wday * 24 * 3600; #else - _t0 -= ((_trp->ts.tm_wday+6)%7)*24*3600; - _t1 -= ((_atp->t.tm_wday+6)%7)*24*3600; + _t0 -= ((_trp->ts.tm_wday + 6) % 7) * 24 * 3600; + _t1 -= ((_atp->t.tm_wday + 6) % 7) * 24 * 3600; #endif - return (((_t1-_t0)/(7*24*3600))%_trp->interval==0)? - REC_MATCH:REC_NOMATCH; + return (((_t1 - _t0) / (7 * 24 * 3600)) % _trp->interval == 0) + ? REC_MATCH + : REC_NOMATCH; case FREQ_MONTHLY: - _t0 = (_atp->t.tm_year-_trp->ts.tm_year)*12 - + _atp->t.tm_mon-_trp->ts.tm_mon; - return (_t0%_trp->interval==0)?REC_MATCH:REC_NOMATCH; + _t0 = (_atp->t.tm_year - _trp->ts.tm_year) * 12 + _atp->t.tm_mon + - _trp->ts.tm_mon; + return (_t0 % _trp->interval == 0) ? REC_MATCH : REC_NOMATCH; case FREQ_YEARLY: - return ((_atp->t.tm_year-_trp->ts.tm_year)%_trp->interval==0)? - REC_MATCH:REC_NOMATCH; + return ((_atp->t.tm_year - _trp->ts.tm_year) % _trp->interval == 0) + ? REC_MATCH + : REC_NOMATCH; } return REC_NOMATCH; @@ -1070,39 +1062,33 @@ int check_min_unit(tmrec_t *_trp, ac_tm_t *_atp, tr_res_t *_tsw) int _v0, _v1; if(!_trp || !_atp) return REC_ERR; - switch(get_min_interval(_trp)) - { + switch(get_min_interval(_trp)) { case FREQ_DAILY: - break; + break; case FREQ_WEEKLY: if(_trp->ts.tm_wday != _atp->t.tm_wday) return REC_NOMATCH; - break; + break; case FREQ_MONTHLY: if(_trp->ts.tm_mday != _atp->t.tm_mday) return REC_NOMATCH; - break; + break; case FREQ_YEARLY: if(_trp->ts.tm_mon != _atp->t.tm_mon || _trp->ts.tm_mday != _atp->t.tm_mday) return REC_NOMATCH; - break; + break; default: return REC_NOMATCH; } - _v0 = _trp->ts.tm_hour*3600 + _trp->ts.tm_min*60 + _trp->ts.tm_sec; - _v1 = _atp->t.tm_hour*3600 + _atp->t.tm_min*60 + _atp->t.tm_sec; - if(_v1 >= _v0 && _v1 < _v0 + _trp->duration) - { - if(_tsw) - { - if(_tsw->flag & TSW_RSET) - { - if(_tsw->rest>_v0+_trp->duration-_v1) + _v0 = _trp->ts.tm_hour * 3600 + _trp->ts.tm_min * 60 + _trp->ts.tm_sec; + _v1 = _atp->t.tm_hour * 3600 + _atp->t.tm_min * 60 + _atp->t.tm_sec; + if(_v1 >= _v0 && _v1 < _v0 + _trp->duration) { + if(_tsw) { + if(_tsw->flag & TSW_RSET) { + if(_tsw->rest > _v0 + _trp->duration - _v1) _tsw->rest = _v0 + _trp->duration - _v1; - } - else - { + } else { _tsw->flag |= TSW_RSET; _tsw->rest = _v0 + _trp->duration - _v1; } @@ -1127,93 +1113,91 @@ int check_byxxx(tmrec_t *_trp, ac_tm_t *_atp) if(!_amp) return REC_NOMATCH; - if(_trp->bymonth) - { - for(i=0; i<_trp->bymonth->nr; i++) - { - if(_atp->t.tm_mon == - (_trp->bymonth->xxx[i]*_trp->bymonth->req[i]+12)%12) + if(_trp->bymonth) { + for(i = 0; i < _trp->bymonth->nr; i++) { + if(_atp->t.tm_mon + == (_trp->bymonth->xxx[i] * _trp->bymonth->req[i] + 12) + % 12) break; } - if(i>=_trp->bymonth->nr) + if(i >= _trp->bymonth->nr) return REC_NOMATCH; } - if(_trp->freq==FREQ_YEARLY && _trp->byweekno) - { - for(i=0; i<_trp->byweekno->nr; i++) - { - if(_atp->yweek == (_trp->byweekno->xxx[i]*_trp->byweekno->req[i]+ - _amp->yweek)%_amp->yweek) + if(_trp->freq == FREQ_YEARLY && _trp->byweekno) { + for(i = 0; i < _trp->byweekno->nr; i++) { + if(_atp->yweek + == (_trp->byweekno->xxx[i] * _trp->byweekno->req[i] + + _amp->yweek) + % _amp->yweek) break; } - if(i>=_trp->byweekno->nr) + if(i >= _trp->byweekno->nr) return REC_NOMATCH; } - if(_trp->byyday) - { - for(i=0; i<_trp->byyday->nr; i++) - { - if(_atp->t.tm_yday == (_trp->byyday->xxx[i]*_trp->byyday->req[i]+ - _amp->yday)%_amp->yday) + if(_trp->byyday) { + for(i = 0; i < _trp->byyday->nr; i++) { + if(_atp->t.tm_yday + == (_trp->byyday->xxx[i] * _trp->byyday->req[i] + + _amp->yday) + % _amp->yday) break; } - if(i>=_trp->byyday->nr) + if(i >= _trp->byyday->nr) return REC_NOMATCH; } - if(_trp->bymday) - { - for(i=0; i<_trp->bymday->nr; i++) - { + if(_trp->bymday) { + for(i = 0; i < _trp->bymday->nr; i++) { #ifdef EXTRA_DEBUG DBG("Req:bymday: %d == %d\n", _atp->t.tm_mday, - (_trp->bymday->xxx[i]*_trp->bymday->req[i]+ - _amp->mday)%_amp->mday + ((_trp->bymday->req[i]<0)?1:0)); + (_trp->bymday->xxx[i] * _trp->bymday->req[i] + _amp->mday) + % _amp->mday + + ((_trp->bymday->req[i] < 0) ? 1 : 0)); #endif - if(_atp->t.tm_mday == (_trp->bymday->xxx[i]*_trp->bymday->req[i]+ - _amp->mday)%_amp->mday + (_trp->bymday->req[i]<0)?1:0) + if(_atp->t.tm_mday + == (_trp->bymday->xxx[i] + * _trp->bymday->req[i] + + _amp->mday) + % _amp->mday + + (_trp->bymday->req[i] < 0) + ? 1 + : 0) break; } - if(i>=_trp->bymday->nr) + if(i >= _trp->bymday->nr) return REC_NOMATCH; } - if(_trp->byday) - { - for(i=0; i<_trp->byday->nr; i++) - { - if(_trp->freq==FREQ_YEARLY) - { + if(_trp->byday) { + for(i = 0; i < _trp->byday->nr; i++) { + if(_trp->freq == FREQ_YEARLY) { #ifdef EXTRA_DEBUG DBG("Req:byday:y: %d==%d && %d==%d\n", _atp->t.tm_wday, - _trp->byday->xxx[i], _atp->ywday+1, - (_trp->byday->req[i]+_amp->ywday)%_amp->ywday); + _trp->byday->xxx[i], _atp->ywday + 1, + (_trp->byday->req[i] + _amp->ywday) % _amp->ywday); #endif - if(_atp->t.tm_wday == _trp->byday->xxx[i] && - _atp->ywday+1 == (_trp->byday->req[i]+_amp->ywday)% - _amp->ywday) + if(_atp->t.tm_wday == _trp->byday->xxx[i] + && _atp->ywday + 1 + == (_trp->byday->req[i] + _amp->ywday) + % _amp->ywday) break; - } - else - { - if(_trp->freq==FREQ_MONTHLY) - { + } else { + if(_trp->freq == FREQ_MONTHLY) { #ifdef EXTRA_DEBUG DBG("Req:byday:m: %d==%d && %d==%d\n", _atp->t.tm_wday, - _trp->byday->xxx[i], _atp->mwday+1, - (_trp->byday->req[i]+_amp->mwday)%_amp->mwday); + _trp->byday->xxx[i], _atp->mwday + 1, + (_trp->byday->req[i] + _amp->mwday) % _amp->mwday); #endif - if(_atp->t.tm_wday == _trp->byday->xxx[i] && - _atp->mwday+1==(_trp->byday->req[i]+ - _amp->mwday)%_amp->mwday) + if(_atp->t.tm_wday == _trp->byday->xxx[i] + && _atp->mwday + 1 + == (_trp->byday->req[i] + _amp->mwday) + % _amp->mwday) break; - } - else - { + } else { if(_atp->t.tm_wday == _trp->byday->xxx[i]) break; } } } - if(i>=_trp->byday->nr) + if(i >= _trp->byday->nr) return REC_NOMATCH; } @@ -1231,60 +1215,60 @@ int tr_parse_recurrence_string(tmrec_t *trp, char *rdef, char sep) memset(trp, 0, sizeof(tmrec_t)); - do{ + do { s = strchr(p, (int)sep); - if (s!=NULL) + if(s != NULL) *s = '\0'; /* LM_DBG("----- parsing tr param <%s>\n", p); */ if(s != p) { switch(type) { case 0: - if(tr_parse_dtstart(trp, p)<0) + if(tr_parse_dtstart(trp, p) < 0) goto error; break; case 1: - if(tr_parse_duration(trp, p)<0) + if(tr_parse_duration(trp, p) < 0) goto error; break; case 2: - if(tr_parse_freq(trp, p)<0) + if(tr_parse_freq(trp, p) < 0) goto error; break; case 3: - if(tr_parse_until(trp, p)<0) + if(tr_parse_until(trp, p) < 0) goto error; break; case 4: - if(tr_parse_interval(trp, p)<0) + if(tr_parse_interval(trp, p) < 0) goto error; break; case 5: - if(tr_parse_byday(trp, p)<0) + if(tr_parse_byday(trp, p) < 0) goto error; break; case 6: - if(tr_parse_bymday(trp, p)<0) + if(tr_parse_bymday(trp, p) < 0) goto error; break; case 7: - if(tr_parse_byyday(trp, p)<0) + if(tr_parse_byyday(trp, p) < 0) goto error; break; case 8: - if(tr_parse_byweekno(trp, p)<0) + if(tr_parse_byweekno(trp, p) < 0) goto error; break; case 9: - if(tr_parse_bymonth(trp, p)<0) + if(tr_parse_bymonth(trp, p) < 0) goto error; break; } } type++; - if (s!=NULL) { + if(s != NULL) { *s = sep; p = s + 1; - if(*p==0) + if(*p == 0) goto done; } else { goto done; @@ -1296,8 +1280,7 @@ int tr_parse_recurrence_string(tmrec_t *trp, char *rdef, char sep) error: LM_ERR("failed to parse time recurrence [%s]\n", rdef); - if (s!=NULL) + if(s != NULL) *s = sep; return -1; } - diff --git a/src/core/utils/tmrec.h b/src/core/utils/tmrec.h index be531a83dab..281c3927021 100644 --- a/src/core/utils/tmrec.h +++ b/src/core/utils/tmrec.h @@ -36,14 +36,15 @@ */ #ifndef USE_YWEEK_U -# ifndef USE_YWEEK_V -# ifndef USE_YWEEK_W -# define USE_YWEEK_W -# endif -# endif +#ifndef USE_YWEEK_V +#ifndef USE_YWEEK_W +#define USE_YWEEK_W +#endif +#endif #endif -#define tr_is_leap_year(yyyy) ((((yyyy)%400))?(((yyyy)%100)?(((yyyy)%4)?0:1):0):1) +#define tr_is_leap_year(yyyy) \ + ((((yyyy) % 400)) ? (((yyyy) % 100) ? (((yyyy) % 4) ? 0 : 1) : 0) : 1) typedef struct _ac_maxval @@ -69,20 +70,18 @@ typedef struct _ac_tm ac_tm_t *ac_tm_new(void); -int ac_tm_set_time(ac_tm_t*, time_t); +int ac_tm_set_time(ac_tm_t *, time_t); -int ac_tm_reset(ac_tm_t*); -int ac_tm_free(ac_tm_t*); -int ac_tm_destroy(ac_tm_t*); +int ac_tm_reset(ac_tm_t *); +int ac_tm_free(ac_tm_t *); +int ac_tm_destroy(ac_tm_t *); -int ac_get_mweek(struct tm*); -int ac_get_yweek(struct tm*); -ac_maxval_t *ac_get_maxval(ac_tm_t*); +int ac_get_mweek(struct tm *); +int ac_get_yweek(struct tm *); +ac_maxval_t *ac_get_maxval(ac_tm_t *); int ac_get_wkst(void); -int ac_print(ac_tm_t*); - - +int ac_print(ac_tm_t *); /** @@ -90,11 +89,11 @@ int ac_print(ac_tm_t*); */ -#define FREQ_NOFREQ 0 -#define FREQ_YEARLY 1 +#define FREQ_NOFREQ 0 +#define FREQ_YEARLY 1 #define FREQ_MONTHLY 2 -#define FREQ_WEEKLY 3 -#define FREQ_DAILY 4 +#define FREQ_WEEKLY 3 +#define FREQ_DAILY 4 #define WDAY_SU 0 #define WDAY_MO 1 @@ -105,8 +104,8 @@ int ac_print(ac_tm_t*); #define WDAY_SA 6 #define WDAY_NU 7 -#define TSW_TSET 1 -#define TSW_RSET 2 +#define TSW_TSET 1 +#define TSW_RSET 2 typedef struct _tr_byxxx { @@ -139,37 +138,36 @@ typedef struct _tr_res } tr_res_t; tr_byxxx_t *tr_byxxx_new(void); -int tr_byxxx_init(tr_byxxx_t*, int); -int tr_byxxx_free(tr_byxxx_t*); +int tr_byxxx_init(tr_byxxx_t *, int); +int tr_byxxx_free(tr_byxxx_t *); tmrec_t *tmrec_new(void); -int tmrec_free(tmrec_t*); -int tmrec_destroy(tmrec_t*); - -int tr_parse_dtstart(tmrec_t*, char*); -int tr_parse_dtend(tmrec_t*, char*); -int tr_parse_duration(tmrec_t*, char*); -int tr_parse_until(tmrec_t*, char*); -int tr_parse_freq(tmrec_t*, char*); -int tr_parse_interval(tmrec_t*, char*); -int tr_parse_byday(tmrec_t*, char*); -int tr_parse_bymday(tmrec_t*, char*); -int tr_parse_byyday(tmrec_t*, char*); -int tr_parse_bymonth(tmrec_t*, char*); -int tr_parse_byweekno(tmrec_t*, char*); -int tr_parse_wkst(tmrec_t*, char*); - -int tr_print(tmrec_t*); -time_t ic_parse_datetime(char*,struct tm*); -time_t ic_parse_duration(char*); - -tr_byxxx_t *ic_parse_byday(char*); -tr_byxxx_t *ic_parse_byxxx(char*); -int ic_parse_wkst(char*); - -int tr_check_recurrence(tmrec_t*, ac_tm_t*, tr_res_t*); +int tmrec_free(tmrec_t *); +int tmrec_destroy(tmrec_t *); + +int tr_parse_dtstart(tmrec_t *, char *); +int tr_parse_dtend(tmrec_t *, char *); +int tr_parse_duration(tmrec_t *, char *); +int tr_parse_until(tmrec_t *, char *); +int tr_parse_freq(tmrec_t *, char *); +int tr_parse_interval(tmrec_t *, char *); +int tr_parse_byday(tmrec_t *, char *); +int tr_parse_bymday(tmrec_t *, char *); +int tr_parse_byyday(tmrec_t *, char *); +int tr_parse_bymonth(tmrec_t *, char *); +int tr_parse_byweekno(tmrec_t *, char *); +int tr_parse_wkst(tmrec_t *, char *); + +int tr_print(tmrec_t *); +time_t ic_parse_datetime(char *, struct tm *); +time_t ic_parse_duration(char *); + +tr_byxxx_t *ic_parse_byday(char *); +tr_byxxx_t *ic_parse_byxxx(char *); +int ic_parse_wkst(char *); + +int tr_check_recurrence(tmrec_t *, ac_tm_t *, tr_res_t *); int tr_parse_recurrence_string(tmrec_t *trp, char *rdef, char sep); #endif - From 87e56dbafc6f3652dab52faa5cc473b5d76c7180 Mon Sep 17 00:00:00 2001 From: Victor Seva Date: Thu, 18 May 2023 15:28:11 +0200 Subject: [PATCH 09/14] core: [action] clang-format for coherent indentation and coding style --- src/core/action.c | 1737 +++++++++++++++++++++++---------------------- src/core/action.h | 21 +- 2 files changed, 895 insertions(+), 863 deletions(-) diff --git a/src/core/action.c b/src/core/action.c index 6767c943b2f..4a29a73b06e 100644 --- a/src/core/action.c +++ b/src/core/action.c @@ -28,7 +28,6 @@ */ - #include "comp_defs.h" #include "action.h" @@ -74,7 +73,7 @@ #include #endif -int _last_returned_code = 0; +int _last_returned_code = 0; /* current action executed from config file */ static cfg_action_t *_cfg_crt_action = 0; @@ -96,7 +95,7 @@ cfg_action_t *get_cfg_crt_action(void) /* return line in config for current executed action */ int get_cfg_crt_line(void) { - if(_cfg_crt_action==0) + if(_cfg_crt_action == 0) return 0; return _cfg_crt_action->cline; } @@ -104,7 +103,7 @@ int get_cfg_crt_line(void) /* return name of config for current executed action */ char *get_cfg_crt_file_name(void) { - if(_cfg_crt_action==0) + if(_cfg_crt_action == 0) return 0; return _cfg_crt_action->cfile; } @@ -112,7 +111,7 @@ char *get_cfg_crt_file_name(void) /* return name of routing block for current executed action */ char *get_cfg_crt_route_name(void) { - if(_cfg_crt_action==0) + if(_cfg_crt_action == 0) return 0; return _cfg_crt_action->rname; } @@ -123,37 +122,37 @@ char *get_cfg_crt_route_name(void) * @param ret - module function (v0 or v2) retcode * Side-effects: sets _last_returned_code */ -#define MODF_HANDLE_RETCODE(h, ret) \ - do { \ +#define MODF_HANDLE_RETCODE(h, ret) \ + do { \ /* if (unlikely((ret)==0)) (h)->run_flags|=EXIT_R_F; */ \ - (h)->run_flags |= EXIT_R_F & (((ret) != 0) -1); \ - (h)->last_retcode=(ret); \ - _last_returned_code = (h)->last_retcode; \ + (h)->run_flags |= EXIT_R_F & (((ret) != 0) - 1); \ + (h)->last_retcode = (ret); \ + _last_returned_code = (h)->last_retcode; \ } while(0) - /* frees parameters converted using MODF_RVE_PARAM_CONVERT() from dst. * (used internally in do_action()) * Assumes src is unchanged. * Side-effects: clobbers i (int). */ -#define MODF_RVE_PARAM_FREE(cmd, src, dst) \ - for (i=0; i < (dst)[1].u.number; i++) { \ - if ((src)[i+2].type == RVE_ST && (dst)[i+2].u.data) { \ - if ((dst)[i+2].type == RVE_FREE_FIXUP_ST) {\ - /* call free_fixup (which should restore the original - string) */ \ - (void)call_fixup((cmd)->free_fixup, &(dst)[i+2].u.data, i+1); \ - } else if ((dst)[i+2].type == FPARAM_DYN_ST) {\ - /* completely frees fparam and restore original string */\ - fparam_free_restore(&(dst)[i+2].u.data); \ - } \ - /* free allocated string */ \ - pkg_free((dst)[i+2].u.data); \ - (dst)[i+2].u.data = 0; \ - } \ - } +#define MODF_RVE_PARAM_FREE(cmd, src, dst) \ + for(i = 0; i < (dst)[1].u.number; i++) { \ + if((src)[i + 2].type == RVE_ST && (dst)[i + 2].u.data) { \ + if((dst)[i + 2].type == RVE_FREE_FIXUP_ST) { \ + /* call free_fixup (which should restore the original + string) */ \ + (void)call_fixup( \ + (cmd)->free_fixup, &(dst)[i + 2].u.data, i + 1); \ + } else if((dst)[i + 2].type == FPARAM_DYN_ST) { \ + /* completely frees fparam and restore original string */ \ + fparam_free_restore(&(dst)[i + 2].u.data); \ + } \ + /* free allocated string */ \ + pkg_free((dst)[i + 2].u.data); \ + (dst)[i + 2].u.data = 0; \ + } \ + } /* fills dst from src, converting RVE_ST params to STRING_ST. @@ -163,63 +162,64 @@ char *get_cfg_crt_route_name(void) * WARNING: dst must be cleaned when done, use MODULE_RVE_PARAM_FREE() * Side-effects: clobbers i (int), s (str), rv (rvalue*), might jump to error. */ -#define MODF_RVE_PARAM_CONVERT(h, msg, cmd, src, dst) \ - do { \ - (dst)[1]=(src)[1]; \ - for (i=0; i < (src)[1].u.number; i++) { \ - if ((src)[2+i].type == RVE_ST) { \ - rv=rval_expr_eval((h), (msg), (src)[i+2].u.data); \ - if (unlikely(rv == 0 || \ - rval_get_str((h), (msg), &s, rv, 0) < 0)) { \ - rval_destroy(rv); \ - ERR("failed to convert RVE to string\n"); \ - (dst)[1].u.number = i; \ - MODF_RVE_PARAM_FREE(cmd, src, dst); \ - goto error; \ - } \ - (dst)[i+2].type = STRING_RVE_ST; \ - (dst)[i+2].u.string = s.s; \ - (dst)[i+2].u.str.len = s.len; \ - rval_destroy(rv); \ - if ((cmd)->fixup) {\ - if ((cmd)->free_fixup) {\ - if (likely( call_fixup((cmd)->fixup, \ - &(dst)[i+2].u.data, i+1) >= 0) ) { \ - /* success => mark it for calling free fixup */ \ - if (likely((dst)[i+2].u.data != s.s)) \ - (dst)[i+2].type = RVE_FREE_FIXUP_ST; \ - } else { \ +#define MODF_RVE_PARAM_CONVERT(h, msg, cmd, src, dst) \ + do { \ + (dst)[1] = (src)[1]; \ + for(i = 0; i < (src)[1].u.number; i++) { \ + if((src)[2 + i].type == RVE_ST) { \ + rv = rval_expr_eval((h), (msg), (src)[i + 2].u.data); \ + if(unlikely(rv == 0 \ + || rval_get_str((h), (msg), &s, rv, 0) < 0)) { \ + rval_destroy(rv); \ + ERR("failed to convert RVE to string\n"); \ + (dst)[1].u.number = i; \ + MODF_RVE_PARAM_FREE(cmd, src, dst); \ + goto error; \ + } \ + (dst)[i + 2].type = STRING_RVE_ST; \ + (dst)[i + 2].u.string = s.s; \ + (dst)[i + 2].u.str.len = s.len; \ + rval_destroy(rv); \ + if((cmd)->fixup) { \ + if((cmd)->free_fixup) { \ + if(likely(call_fixup((cmd)->fixup, \ + &(dst)[i + 2].u.data, i + 1) \ + >= 0)) { \ + /* success => mark it for calling free fixup */ \ + if(likely((dst)[i + 2].u.data != s.s)) \ + (dst)[i + 2].type = RVE_FREE_FIXUP_ST; \ + } else { \ /* error calling fixup => mark conv. parameter \ and return error */ \ - (dst)[1].u.number = i; \ - ERR("runtime fixup failed for %s param %d\n", \ - (cmd)->name, i+1); \ - MODF_RVE_PARAM_FREE(cmd, src, dst); \ - goto error; \ - } \ - } else if ((cmd)->fixup_flags & FIXUP_F_FPARAM_RVE) { \ - if (likely( call_fixup((cmd)->fixup, \ - &(dst)[i+2].u.data, i+1) >= 0)) { \ - if ((dst)[i+2].u.data != s.s) \ - (dst)[i+2].type = FPARAM_DYN_ST; \ - } else { \ + (dst)[1].u.number = i; \ + ERR("runtime fixup failed for %s param %d\n", \ + (cmd)->name, i + 1); \ + MODF_RVE_PARAM_FREE(cmd, src, dst); \ + goto error; \ + } \ + } else if((cmd)->fixup_flags & FIXUP_F_FPARAM_RVE) { \ + if(likely(call_fixup((cmd)->fixup, \ + &(dst)[i + 2].u.data, i + 1) \ + >= 0)) { \ + if((dst)[i + 2].u.data != s.s) \ + (dst)[i + 2].type = FPARAM_DYN_ST; \ + } else { \ /* error calling fixup => mark conv. parameter \ and return error */ \ - (dst)[1].u.number = i; \ - ERR("runtime fixup failed for %s param %d\n", \ - (cmd)->name, i+1); \ - MODF_RVE_PARAM_FREE(cmd, src, dst); \ - goto error; \ - }\ - } \ - } \ - } else \ - (dst)[i+2]=(src)[i+2]; \ - } \ + (dst)[1].u.number = i; \ + ERR("runtime fixup failed for %s param %d\n", \ + (cmd)->name, i + 1); \ + MODF_RVE_PARAM_FREE(cmd, src, dst); \ + goto error; \ + } \ + } \ + } \ + } else \ + (dst)[i + 2] = (src)[i + 2]; \ + } \ } while(0) - /* call a module function with normal STRING_ST params. * (used internally in do_action()) * @param f_type - cmd_function type @@ -233,23 +233,22 @@ char *get_cfg_crt_route_name(void) * */ #ifdef __SUNPRO_C -#define MODF_CALL(f_type, h, msg, src, ...) \ - do { \ - cmd=(src)[0].u.data; \ - ret=((f_type)cmd->function)((msg), __VA_ARGS__); \ - MODF_HANDLE_RETCODE(h, ret); \ - } while (0) -#else /* ! __SUNPRO_C (gcc, icc a.s.o) */ -#define MODF_CALL(f_type, h, msg, src, params...) \ - do { \ - cmd=(src)[0].u.data; \ - ret=((f_type)cmd->function)((msg), ## params ); \ - MODF_HANDLE_RETCODE(h, ret); \ - } while (0) +#define MODF_CALL(f_type, h, msg, src, ...) \ + do { \ + cmd = (src)[0].u.data; \ + ret = ((f_type)cmd->function)((msg), __VA_ARGS__); \ + MODF_HANDLE_RETCODE(h, ret); \ + } while(0) +#else /* ! __SUNPRO_C (gcc, icc a.s.o) */ +#define MODF_CALL(f_type, h, msg, src, params...) \ + do { \ + cmd = (src)[0].u.data; \ + ret = ((f_type)cmd->function)((msg), ##params); \ + MODF_HANDLE_RETCODE(h, ret); \ + } while(0) #endif /* __SUNPRO_C */ - /* call a module function with possible RVE params. * (used internally in do_action()) * @param f_type - cmd_function type @@ -266,55 +265,55 @@ char *get_cfg_crt_route_name(void) * */ #ifdef __SUNPRO_C -#define MODF_RVE_CALL(f_type, h, msg, src, dst, ...) \ - do { \ - cmd=(src)[0].u.data; \ - MODF_RVE_PARAM_CONVERT(h, msg, cmd, src, dst); \ - ret=((f_type)cmd->function)((msg), __VA_ARGS__); \ - MODF_HANDLE_RETCODE(h, ret); \ - /* free strings allocated by us or fixups */ \ - MODF_RVE_PARAM_FREE(cmd, src, dst); \ - } while (0) -#else /* ! __SUNPRO_C (gcc, icc a.s.o) */ +#define MODF_RVE_CALL(f_type, h, msg, src, dst, ...) \ + do { \ + cmd = (src)[0].u.data; \ + MODF_RVE_PARAM_CONVERT(h, msg, cmd, src, dst); \ + ret = ((f_type)cmd->function)((msg), __VA_ARGS__); \ + MODF_HANDLE_RETCODE(h, ret); \ + /* free strings allocated by us or fixups */ \ + MODF_RVE_PARAM_FREE(cmd, src, dst); \ + } while(0) +#else /* ! __SUNPRO_C (gcc, icc a.s.o) */ #define MODF_RVE_CALL(f_type, h, msg, src, dst, params...) \ - do { \ - cmd=(src)[0].u.data; \ - MODF_RVE_PARAM_CONVERT(h, msg, cmd, src, dst); \ - ret=((f_type)cmd->function)((msg), ## params ); \ - MODF_HANDLE_RETCODE(h, ret); \ - /* free strings allocated by us or fixups */ \ - MODF_RVE_PARAM_FREE(cmd, src, dst); \ - } while (0) + do { \ + cmd = (src)[0].u.data; \ + MODF_RVE_PARAM_CONVERT(h, msg, cmd, src, dst); \ + ret = ((f_type)cmd->function)((msg), ##params); \ + MODF_HANDLE_RETCODE(h, ret); \ + /* free strings allocated by us or fixups */ \ + MODF_RVE_PARAM_FREE(cmd, src, dst); \ + } while(0) #endif /* __SUNPRO_C */ /* ret= 0! if action -> end of list(e.g DROP), > 0 to continue processing next actions and <0 on error */ -int do_action(struct run_act_ctx* h, struct action* a, struct sip_msg* msg) +int do_action(struct run_act_ctx *h, struct action *a, struct sip_msg *msg) { int ret; long li; long v; struct dest_info dst; - char* tmp; + char *tmp; char *new_uri, *end, *crt; - ksr_cmd_export_t* cmd; + ksr_cmd_export_t *cmd; int len; int user; struct sip_uri uri, next_hop; struct sip_uri *u; unsigned short port; - str* dst_host; + str *dst_host; int i, flags; - avp_t* avp; + avp_t *avp; struct search_state st; - struct switch_cond_table* sct; - struct switch_jmp_table* sjt; - struct rval_expr* rve; - struct match_cond_table* mct; - struct rvalue* rv; - struct rvalue* rv1; + struct switch_cond_table *sct; + struct switch_jmp_table *sjt; + struct rval_expr *rve; + struct match_cond_table *mct; + struct rvalue *rv; + struct rvalue *rv1; struct rval_cache c1; str s; void *srevp[2]; @@ -332,45 +331,43 @@ int do_action(struct run_act_ctx* h, struct action* a, struct sip_msg* msg) functions to return with error (status<0) and not setting it leaving there previous error; cache the previous value though for functions which want to process it */ - prev_ser_error=ser_error; - ser_error=E_UNSPEC; + prev_ser_error = ser_error; + ser_error = E_UNSPEC; /* hook for every executed action (in use by cfg debugger) */ - if(unlikely(sr_event_enabled(SREV_CFG_RUN_ACTION))) - { - srevp[0] = (void*)a; - srevp[1] = (void*)msg; - evp.data = (void*)srevp; + if(unlikely(sr_event_enabled(SREV_CFG_RUN_ACTION))) { + srevp[0] = (void *)a; + srevp[1] = (void *)msg; + evp.data = (void *)srevp; sr_event_exec(SREV_CFG_RUN_ACTION, &evp); } - ret=E_BUG; - switch ((unsigned char)a->type){ + ret = E_BUG; + switch((unsigned char)a->type) { case DROP_T: - switch(a->val[0].type){ - case NUMBER_ST: - ret=(int) a->val[0].u.number; - break; - case RVE_ST: - rve=(struct rval_expr*)a->val[0].u.data; - if(rval_expr_eval_long(h, msg, &li, rve)<0) { - LM_WARN("failed to eval int expression\n"); - } - ret = (int)li; - break; - case RETCODE_ST: - ret=h->last_retcode; - break; - default: - BUG("unexpected subtype %d in DROP_T\n", - a->val[0].type); - ret=0; - goto error; - } - h->run_flags|=(unsigned int)a->val[1].u.number; - if(unlikely((ret==0) && (h->run_flags&RETURN_R_F))) { - h->run_flags |= EXIT_R_F; - } + switch(a->val[0].type) { + case NUMBER_ST: + ret = (int)a->val[0].u.number; + break; + case RVE_ST: + rve = (struct rval_expr *)a->val[0].u.data; + if(rval_expr_eval_long(h, msg, &li, rve) < 0) { + LM_WARN("failed to eval int expression\n"); + } + ret = (int)li; + break; + case RETCODE_ST: + ret = h->last_retcode; + break; + default: + BUG("unexpected subtype %d in DROP_T\n", a->val[0].type); + ret = 0; + goto error; + } + h->run_flags |= (unsigned int)a->val[1].u.number; + if(unlikely((ret == 0) && (h->run_flags & RETURN_R_F))) { + h->run_flags |= EXIT_R_F; + } break; case FORWARD_T: #ifdef USE_TCP @@ -385,59 +382,63 @@ int do_action(struct run_act_ctx* h, struct action* a, struct sip_msg* msg) case FORWARD_UDP_T: /* init dst */ init_dest_info(&dst); - if (a->type==FORWARD_UDP_T) dst.proto=PROTO_UDP; + if(a->type == FORWARD_UDP_T) + dst.proto = PROTO_UDP; #ifdef USE_TCP - else if (a->type==FORWARD_TCP_T) { - dst.proto= PROTO_TCP; + else if(a->type == FORWARD_TCP_T) { + dst.proto = PROTO_TCP; if(msg->msg_flags & FL_USE_OTCPID) { dst.id = msg->otcpid; } } #endif #ifdef USE_TLS - else if (a->type==FORWARD_TLS_T) { - dst.proto= PROTO_TLS; + else if(a->type == FORWARD_TLS_T) { + dst.proto = PROTO_TLS; if(msg->msg_flags & FL_USE_OTCPID) { dst.id = msg->otcpid; } } #endif #ifdef USE_SCTP - else if (a->type==FORWARD_SCTP_T) dst.proto=PROTO_SCTP; + else if(a->type == FORWARD_SCTP_T) + dst.proto = PROTO_SCTP; #endif - else dst.proto=PROTO_NONE; - if (a->val[0].type==URIHOST_ST){ + else + dst.proto = PROTO_NONE; + if(a->val[0].type == URIHOST_ST) { /*parse uri*/ - if (msg->dst_uri.len) { - ret = parse_uri(msg->dst_uri.s, msg->dst_uri.len, - &next_hop); + if(msg->dst_uri.len) { + ret = parse_uri( + msg->dst_uri.s, msg->dst_uri.len, &next_hop); u = &next_hop; } else { ret = parse_sip_msg_uri(msg); u = &msg->parsed_uri; } - if (ret<0) { + if(ret < 0) { LM_ERR("forward: bad_uri dropping packet\n"); goto error; } - switch (a->val[1].type){ + switch(a->val[1].type) { case URIPORT_ST: - port=u->port_no; - break; + port = u->port_no; + break; case NUMBER_ST: - port=a->val[1].u.number; - break; + port = a->val[1].u.number; + break; default: - LM_CRIT("bad forward 2nd param type (%d)\n", a->val[1].type); - ret=E_UNSPEC; - goto error_fwd_uri; + LM_CRIT("bad forward 2nd param type (%d)\n", + a->val[1].type); + ret = E_UNSPEC; + goto error_fwd_uri; } - if (dst.proto == PROTO_NONE){ /* only if proto not set get it + if(dst.proto == PROTO_NONE) { /* only if proto not set get it from the uri */ - switch(u->proto){ + switch(u->proto) { case PROTO_NONE: /*dst.proto=PROTO_UDP; */ /* no proto, try to get it from the dns */ @@ -454,171 +455,171 @@ int do_action(struct run_act_ctx* h, struct action* a, struct sip_msg* msg) #ifdef USE_SCTP case PROTO_SCTP: #endif - dst.proto=u->proto; + dst.proto = u->proto; break; default: LM_ERR("forward: bad uri transport %d\n", u->proto); - ret=E_BAD_PROTO; + ret = E_BAD_PROTO; goto error_fwd_uri; } #ifdef USE_TLS - if (u->type==SIPS_URI_T){ - if (u->proto==PROTO_UDP){ - LM_ERR("forward: secure uri incompatible with transport %d\n", + if(u->type == SIPS_URI_T) { + if(u->proto == PROTO_UDP) { + LM_ERR("forward: secure uri incompatible with " + "transport %d\n", u->proto); - ret=E_BAD_PROTO; + ret = E_BAD_PROTO; goto error_fwd_uri; - } else if (u->proto!=PROTO_WSS) - dst.proto=PROTO_TLS; + } else if(u->proto != PROTO_WSS) + dst.proto = PROTO_TLS; else - dst.proto=PROTO_WSS; + dst.proto = PROTO_WSS; } #endif } #ifdef HONOR_MADDR - if (u->maddr_val.s && u->maddr_val.len) - dst_host=&u->maddr_val; + if(u->maddr_val.s && u->maddr_val.len) + dst_host = &u->maddr_val; else #endif - dst_host=&u->host; + dst_host = &u->host; #ifdef USE_COMP - dst.comp=u->comp; + dst.comp = u->comp; #endif - ret=forward_request(msg, dst_host, port, &dst); - if (ret>=0){ - ret=1; + ret = forward_request(msg, dst_host, port, &dst); + if(ret >= 0) { + ret = 1; } - }else if ((a->val[0].type==PROXY_ST) && (a->val[1].type==NUMBER_ST)){ - if (dst.proto==PROTO_NONE) - dst.proto=msg->rcv.proto; - proxy2su(&dst.to, (struct proxy_l*)a->val[0].u.data); - ret=forward_request(msg, 0, 0, &dst); - if (ret>=0){ - ret=1; - proxy_mark((struct proxy_l*)a->val[0].u.data, ret); - }else if (ser_error!=E_OK){ - proxy_mark((struct proxy_l*)a->val[0].u.data, ret); + } else if((a->val[0].type == PROXY_ST) + && (a->val[1].type == NUMBER_ST)) { + if(dst.proto == PROTO_NONE) + dst.proto = msg->rcv.proto; + proxy2su(&dst.to, (struct proxy_l *)a->val[0].u.data); + ret = forward_request(msg, 0, 0, &dst); + if(ret >= 0) { + ret = 1; + proxy_mark((struct proxy_l *)a->val[0].u.data, ret); + } else if(ser_error != E_OK) { + proxy_mark((struct proxy_l *)a->val[0].u.data, ret); } - }else{ - LM_CRIT("bad forward() types %d, %d\n", - a->val[0].type, a->val[1].type); - ret=E_BUG; + } else { + LM_CRIT("bad forward() types %d, %d\n", a->val[0].type, + a->val[1].type); + ret = E_BUG; goto error; } break; case LOG_T: - if ((a->val[0].type!=NUMBER_ST)|(a->val[1].type!=STRING_ST)){ - LM_CRIT("bad log() types %d, %d\n", - a->val[0].type, a->val[1].type); - ret=E_BUG; + if((a->val[0].type != NUMBER_ST) | (a->val[1].type != STRING_ST)) { + LM_CRIT("bad log() types %d, %d\n", a->val[0].type, + a->val[1].type); + ret = E_BUG; goto error; } LOG_FN(DEFAULT_FACILITY, a->val[0].u.number, "