From 786f250c5767172e0528affde2d489ddd45daa31 Mon Sep 17 00:00:00 2001 From: Nodir Temirkhodjaev Date: Fri, 3 Jan 2020 14:11:37 +0500 Subject: [PATCH] Driver: Prepare add/del apps. --- src/3rdparty/tlsf/tlsf.c | 1268 +++++++++++++++++++++++++++ src/3rdparty/tlsf/tlsf.h | 96 ++ src/3rdparty/tommyds/tommyhashdyn.c | 4 +- src/3rdparty/tommyds/tommyhashdyn.h | 3 +- src/3rdparty/tommyds/tommylist.h | 35 +- src/common/common.h | 2 + src/common/fortconf.c | 24 +- src/common/fortconf.h | 6 +- src/driver/fortcnf.c | 238 ++++- src/driver/fortdrv.c | 53 +- src/driver/forttlsf.c | 6 + src/ui/form/prog/programswindow.cpp | 2 +- src/ui/fortcommon.cpp | 4 +- src/ui/log/model/applistmodel.cpp | 6 +- src/ui/task/tasklistmodel.cpp | 3 +- src/ui/util/conf/confutil.cpp | 2 +- 16 files changed, 1676 insertions(+), 76 deletions(-) create mode 100644 src/3rdparty/tlsf/tlsf.c create mode 100644 src/3rdparty/tlsf/tlsf.h create mode 100644 src/driver/forttlsf.c diff --git a/src/3rdparty/tlsf/tlsf.c b/src/3rdparty/tlsf/tlsf.c new file mode 100644 index 00000000..790e3a39 --- /dev/null +++ b/src/3rdparty/tlsf/tlsf.c @@ -0,0 +1,1268 @@ +#include +#include +#include +#include +#include +#include + +#include "tlsf.h" + +#if defined(__cplusplus) +#define tlsf_decl inline +#else +#define tlsf_decl static +#endif + +#if !defined(tlsf_printf) +#define tlsf_printf printf +#endif + +/* +** Architecture-specific bit manipulation routines. +** +** TLSF achieves O(1) cost for malloc and free operations by limiting +** the search for a free block to a free list of guaranteed size +** adequate to fulfill the request, combined with efficient free list +** queries using bitmasks and architecture-specific bit-manipulation +** routines. +** +** Most modern processors provide instructions to count leading zeroes +** in a word, find the lowest and highest set bit, etc. These +** specific implementations will be used when available, falling back +** to a reasonably efficient generic implementation. +** +** NOTE: TLSF spec relies on ffs/fls returning value 0..31. +** ffs/fls return 1-32 by default, returning 0 for error. +*/ + +/* +** 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__) +#define TLSF_64BIT +#endif + +/* +** gcc 3.4 and above have builtin support, specialized for architecture. +** Some compilers masquerade as gcc; patchlevel test filters them out. +*/ +#if defined (__GNUC__) && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) \ + && defined (__GNUC_PATCHLEVEL__) + +#if defined (__SNC__) +/* SNC for Playstation 3. */ + +tlsf_decl int tlsf_ffs(unsigned int word) +{ + const unsigned int reverse = word & (~word + 1); + const int bit = 32 - __builtin_clz(reverse); + return bit - 1; +} + +#else + +tlsf_decl int tlsf_ffs(unsigned int word) +{ + return __builtin_ffs(word) - 1; +} + +#endif + +tlsf_decl int tlsf_fls(unsigned int word) +{ + const int bit = word ? 32 - __builtin_clz(word) : 0; + return bit - 1; +} + +#elif defined (_MSC_VER) && (_MSC_VER >= 1400) && (defined (_M_IX86) || defined (_M_X64)) +/* Microsoft Visual C++ support on x86/X64 architectures. */ + +#include + +#pragma intrinsic(_BitScanReverse) +#pragma intrinsic(_BitScanForward) + +tlsf_decl int tlsf_fls(unsigned int word) +{ + unsigned long index; + return _BitScanReverse(&index, word) ? index : -1; +} + +tlsf_decl int tlsf_ffs(unsigned int word) +{ + unsigned long index; + return _BitScanForward(&index, word) ? index : -1; +} + +#elif defined (_MSC_VER) && defined (_M_PPC) +/* Microsoft Visual C++ support on PowerPC architectures. */ + +#include + +tlsf_decl int tlsf_fls(unsigned int word) +{ + const int bit = 32 - _CountLeadingZeros(word); + return bit - 1; +} + +tlsf_decl int tlsf_ffs(unsigned int word) +{ + const unsigned int reverse = word & (~word + 1); + const int bit = 32 - _CountLeadingZeros(reverse); + return bit - 1; +} + +#elif defined (__ARMCC_VERSION) +/* RealView Compilation Tools for ARM */ + +tlsf_decl int tlsf_ffs(unsigned int word) +{ + const unsigned int reverse = word & (~word + 1); + const int bit = 32 - __clz(reverse); + return bit - 1; +} + +tlsf_decl int tlsf_fls(unsigned int word) +{ + const int bit = word ? 32 - __clz(word) : 0; + return bit - 1; +} + +#elif defined (__ghs__) +/* Green Hills support for PowerPC */ + +#include + +tlsf_decl int tlsf_ffs(unsigned int word) +{ + const unsigned int reverse = word & (~word + 1); + const int bit = 32 - __CLZ32(reverse); + return bit - 1; +} + +tlsf_decl int tlsf_fls(unsigned int word) +{ + const int bit = word ? 32 - __CLZ32(word) : 0; + return bit - 1; +} + +#else +/* Fall back to generic implementation. */ + +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; } + + return bit; +} + +/* Implement ffs in terms of fls. */ +tlsf_decl int tlsf_ffs(unsigned int word) +{ + return tlsf_fls_generic(word & (~word + 1)) - 1; +} + +tlsf_decl int tlsf_fls(unsigned int word) +{ + return tlsf_fls_generic(word) - 1; +} + +#endif + +/* Possibly 64-bit version of tlsf_fls. */ +#if defined (TLSF_64BIT) +tlsf_decl int tlsf_fls_sizet(size_t size) +{ + int high = (int)(size >> 32); + int bits = 0; + if (high) + { + bits = 32 + tlsf_fls(high); + } + else + { + bits = tlsf_fls((int)size & 0xffffffff); + + } + return bits; +} +#else +#define tlsf_fls_sizet tlsf_fls +#endif + +#undef tlsf_decl + +/* +** Constants. +*/ + +/* Public constants: may be modified. */ +enum tlsf_public +{ + /* log2 of number of linear subdivisions of block sizes. Larger + ** values require more memory in the control structure. Values of + ** 4 or 5 are typical. + */ + SL_INDEX_COUNT_LOG2 = 5, +}; + +/* Private constants: do not modify. */ +enum tlsf_private +{ +#if defined (TLSF_64BIT) + /* All allocation sizes and addresses are aligned to 8 bytes. */ + ALIGN_SIZE_LOG2 = 3, +#else + /* All allocation sizes and addresses are aligned to 4 bytes. */ + ALIGN_SIZE_LOG2 = 2, +#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 + ** create first-level lists for sizes smaller than SL_INDEX_COUNT * 4, + ** or (1 << (SL_INDEX_COUNT_LOG2 + 2)) bytes, as there we will be + ** trying to split size ranges into more slots than we have available. + ** Instead, we calculate the minimum threshold size, and place all + ** blocks below that size into the 0th first-level list. + */ + +#if defined (TLSF_64BIT) + /* + ** TODO: We can increase this to support larger sizes, at the expense + ** of more overhead in the TLSF structure. + */ + FL_INDEX_MAX = 32, +#else + FL_INDEX_MAX = 30, +#endif + SL_INDEX_COUNT = (1 << SL_INDEX_COUNT_LOG2), + FL_INDEX_SHIFT = (SL_INDEX_COUNT_LOG2 + ALIGN_SIZE_LOG2), + FL_INDEX_COUNT = (FL_INDEX_MAX - FL_INDEX_SHIFT + 1), + + SMALL_BLOCK_SIZE = (1 << FL_INDEX_SHIFT), +}; + +/* +** 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)) + +/* +** Set assert macro, if it has not been provided by the user. +*/ +#if !defined (tlsf_assert) +#define tlsf_assert assert +#endif + +/* +** Static assertion mechanism. +*/ + +#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] + +/* This code has been tested on 32- and 64-bit (LP/LLP) architectures. */ +tlsf_static_assert(sizeof(int) * CHAR_BIT == 32); +tlsf_static_assert(sizeof(size_t) * CHAR_BIT >= 32); +tlsf_static_assert(sizeof(size_t) * CHAR_BIT <= 64); + +/* SL_INDEX_COUNT must be <= number of bits in sl_bitmap's storage type. */ +tlsf_static_assert(sizeof(unsigned int) * CHAR_BIT >= SL_INDEX_COUNT); + +/* Ensure we've properly tuned our sizes. */ +tlsf_static_assert(ALIGN_SIZE == SMALL_BLOCK_SIZE / SL_INDEX_COUNT); + +/* +** Data structures and associated constants. +*/ + +/* +** Block header structure. +** +** There are several implementation subtleties involved: +** - The prev_phys_block field is only valid if the previous block is free. +** - The prev_phys_block field is actually stored at the end of the +** previous block. It appears at the beginning of this structure only to +** simplify the implementation. +** - The next_free / prev_free fields are only valid if the block is free. +*/ +typedef struct block_header_t +{ + /* Points to the previous physical block. */ + struct block_header_t* prev_phys_block; + + /* The size of this block, excluding the block header. */ + size_t size; + + /* Next and previous free blocks. */ + struct block_header_t* next_free; + struct block_header_t* prev_free; +} block_header_t; + +/* +** Since block sizes are always at least a multiple of 4, the two least +** significant bits of the size field are used to store the block status: +** - bit 0: whether block is busy or free +** - bit 1: whether previous block is busy or free +*/ +static const size_t block_header_free_bit = 1 << 0; +static const size_t block_header_prev_free_bit = 1 << 1; + +/* +** The size of the block header exposed to used blocks is the size field. +** The prev_phys_block field is stored *inside* the previous free block. +*/ +static const size_t block_header_overhead = sizeof(size_t); + +/* 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); + +/* +** A free block must be large enough to store its header minus the size of +** the prev_phys_block field, and no larger than the number of addressable +** bits for FL_INDEX. +*/ +static const size_t block_size_min = + sizeof(block_header_t) - sizeof(block_header_t*); +static const size_t block_size_max = tlsf_cast(size_t, 1) << FL_INDEX_MAX; + + +/* The TLSF control structure. */ +typedef struct control_t +{ + /* Empty lists point at this block to indicate they are free. */ + block_header_t block_null; + + /* Bitmaps for free lists. */ + unsigned int fl_bitmap; + unsigned int sl_bitmap[FL_INDEX_COUNT]; + + /* Head of free lists. */ + block_header_t* blocks[FL_INDEX_COUNT][SL_INDEX_COUNT]; +} control_t; + +/* A type used for casting when doing pointer arithmetic. */ +typedef ptrdiff_t tlsfptr_t; + +/* +** block_header_t member functions. +*/ + +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) +{ + const size_t oldsize = block->size; + block->size = size | (oldsize & (block_header_free_bit | block_header_prev_free_bit)); +} + +static int block_is_last(const block_header_t* block) +{ + return block_size(block) == 0; +} + +static int block_is_free(const block_header_t* block) +{ + return tlsf_cast(int, block->size & block_header_free_bit); +} + +static void block_set_free(block_header_t* block) +{ + block->size |= block_header_free_bit; +} + +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) +{ + return tlsf_cast(int, block->size & block_header_prev_free_bit); +} + +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) +{ + block->size &= ~block_header_prev_free_bit; +} + +static block_header_t* block_from_ptr(const void* ptr) +{ + return tlsf_cast(block_header_t*, + tlsf_cast(unsigned char*, ptr) - block_start_offset); +} + +static void* block_to_ptr(const block_header_t* block) +{ + 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) +{ + 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) +{ + tlsf_assert(block_is_prev_free(block) && "previous block must be free"); + return block->prev_phys_block; +} + +/* Return location of next existing 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) - block_header_overhead); + 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) +{ + block_header_t* next = block_next(block); + next->prev_phys_block = block; + return next; +} + +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_set_prev_free(next); + block_set_free(block); +} + +static void block_mark_as_used(block_header_t* block) +{ + block_header_t* next = block_next(block); + block_set_prev_used(next); + block_set_used(block); +} + +static size_t align_up(size_t x, size_t align) +{ + tlsf_assert(0 == (align & (align - 1)) && "must align to a power of two"); + return (x + (align - 1)) & ~(align - 1); +} + +static size_t align_down(size_t x, size_t align) +{ + tlsf_assert(0 == (align & (align - 1)) && "must align to a power of two"); + return x - (x & (align - 1)); +} + +static void* align_ptr(const void* ptr, size_t align) +{ + const tlsfptr_t aligned = + (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); +} + +/* +** Adjust an allocation size to be aligned to word size, and no smaller +** than internal minimum. +*/ +static size_t adjust_request_size(size_t size, size_t align) +{ + size_t adjust = 0; + if (size) + { + const size_t aligned = align_up(size, align); + + /* aligned sized must not exceed block_size_max or we'll go out of bounds on sl_bitmap */ + if (aligned < block_size_max) + { + adjust = tlsf_max(aligned, block_size_min); + } + } + return adjust; +} + +/* +** TLSF utility functions. In most cases, these are direct translations of +** the documentation found in the white paper. +*/ + +static void mapping_insert(size_t size, int* fli, int* sli) +{ + int fl, sl; + 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 + { + fl = tlsf_fls_sizet(size); + sl = tlsf_cast(int, size >> (fl - SL_INDEX_COUNT_LOG2)) ^ (1 << SL_INDEX_COUNT_LOG2); + fl -= (FL_INDEX_SHIFT - 1); + } + *fli = fl; + *sli = sl; +} + +/* This version rounds up to the next block size (for allocations) */ +static void mapping_search(size_t size, int* fli, int* sli) +{ + if (size >= SMALL_BLOCK_SIZE) + { + 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) +{ + int fl = *fli; + int sl = *sli; + + /* + ** First, search for a block in the list associated with the given + ** fl/sl index. + */ + unsigned int sl_map = control->sl_bitmap[fl] & (~0U << sl); + if (!sl_map) + { + /* No block exists. Search in the next largest first-level list. */ + const unsigned int fl_map = control->fl_bitmap & (~0U << (fl + 1)); + if (!fl_map) + { + /* No free blocks available, memory has been exhausted. */ + return 0; + } + + fl = tlsf_ffs(fl_map); + *fli = fl; + sl_map = control->sl_bitmap[fl]; + } + tlsf_assert(sl_map && "internal error - second level bitmap is null"); + sl = tlsf_ffs(sl_map); + *sli = sl; + + /* Return the first block in the free list. */ + return control->blocks[fl][sl]; +} + +/* Remove a free block from the free list.*/ +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; + 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) + { + control->blocks[fl][sl] = next; + + /* If the new head is null, clear the bitmap. */ + 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]) + { + control->fl_bitmap &= ~(1 << 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) +{ + 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"); + /* + ** Insert the new block at the head of the list, and mark the first- + ** and second-level bitmaps appropriately. + */ + control->blocks[fl][sl] = block; + control->fl_bitmap |= (1 << fl); + control->sl_bitmap[fl] |= (1 << sl); +} + +/* Remove a given block from the free list. */ +static void block_remove(control_t* control, block_header_t* block) +{ + int fl, sl; + mapping_insert(block_size(block), &fl, &sl); + remove_free_block(control, block, fl, sl); +} + +/* Insert a given block into the free list. */ +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) +{ + 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) +{ + /* Calculate the amount of space left in the remaining block. */ + block_header_t* remaining = + offset_to_block(block_to_ptr(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_size(block) == remain_size + size + block_header_overhead); + block_set_size(remaining, remain_size); + tlsf_assert(block_size(remaining) >= block_size_min && "block split with invalid size"); + + block_set_size(block, size); + block_mark_as_free(remaining); + + return remaining; +} + +/* 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) +{ + tlsf_assert(!block_is_last(prev) && "previous block can't be last"); + /* Note: Leaves flags untouched. */ + prev->size += block_size(block) + block_header_overhead; + block_link_next(prev); + return prev; +} + +/* 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) +{ + 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"); + block_remove(control, prev); + block = block_absorb(prev, block); + } + + return block; +} + +/* Merge a just-freed block with an adjacent free block. */ +static block_header_t* block_merge_next(control_t* control, block_header_t* block) +{ + block_header_t* next = block_next(block); + tlsf_assert(next && "next physical block can't be null"); + + 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); + } + + return block; +} + +/* 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) +{ + 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); + block_link_next(block); + block_set_prev_free(remaining_block); + block_insert(control, remaining_block); + } +} + +/* 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) +{ + tlsf_assert(!block_is_free(block) && "block must be used"); + 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_set_prev_used(remaining_block); + + remaining_block = block_merge_next(control, remaining_block); + block_insert(control, remaining_block); + } +} + +static block_header_t* block_trim_free_leading(control_t* control, block_header_t* block, size_t size) +{ + block_header_t* remaining_block = block; + if (block_can_split(block, size)) + { + /* We want the 2nd block. */ + remaining_block = block_split(block, size - block_header_overhead); + block_set_prev_free(remaining_block); + + block_link_next(block); + block_insert(control, block); + } + + return remaining_block; +} + +static block_header_t* block_locate_free(control_t* control, size_t size) +{ + int fl = 0, sl = 0; + block_header_t* block = 0; + + if (size) + { + mapping_search(size, &fl, &sl); + + /* + ** mapping_search can futz with the size, so for excessively large sizes it can sometimes wind up + ** with indices that are off the end of the block array. + ** So, we protect against that here, since this is the only callsite of mapping_search. + ** Note that we don't need to check sl, since it comes from a modulo operation that guarantees it's always in range. + */ + if (fl < FL_INDEX_COUNT) + { + block = search_suitable_block(control, &fl, &sl); + } + } + + if (block) + { + tlsf_assert(block_size(block) >= size); + remove_free_block(control, block, fl, sl); + } + + return block; +} + +static void* block_prepare_used(control_t* control, block_header_t* block, size_t size) +{ + void* p = 0; + if (block) + { + tlsf_assert(size && "size must be non-zero"); + block_trim_free(control, block, size); + block_mark_as_used(block); + p = block_to_ptr(block); + } + return p; +} + +/* Clear structure and point all empty lists at the null block. */ +static void control_construct(control_t* control) +{ + int i, j; + + control->block_null.next_free = &control->block_null; + control->block_null.prev_free = &control->block_null; + + control->fl_bitmap = 0; + for (i = 0; i < FL_INDEX_COUNT; ++i) + { + control->sl_bitmap[i] = 0; + for (j = 0; j < SL_INDEX_COUNT; ++j) + { + control->blocks[i][j] = &control->block_null; + } + } +} + +/* +** Debugging utilities. +*/ + +typedef struct integrity_t +{ + int prev_status; + int status; +} integrity_t; + +#define tlsf_insist(x) { tlsf_assert(x); if (!(x)) { status--; } } + +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); + 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; + (void)used; + 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; + integ->status += status; +} + +TLSF_API int tlsf_check(tlsf_t tlsf) +{ + int i, j; + + 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) + { + 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]; + + /* Check that first- and second-level lists agree. */ + 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"); + 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"); + + 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"); + + mapping_insert(block_size(block), &fli, &sli); + tlsf_insist(fli == i && sli == j && "block size indexed in wrong list"); + block = block->next_free; + } + } + } + + return status; +} + +#undef tlsf_insist + +static void default_walker(void* ptr, size_t size, int used, void* user) +{ + (void)user; + tlsf_printf("\t%p %s size: %x (%p)\n", ptr, used ? "used" : "free", (unsigned int)size, block_from_ptr(ptr)); +} + +TLSF_API void tlsf_walk_pool(pool_t pool, tlsf_walker walker, void* user) +{ + tlsf_walker pool_walker = walker ? walker : default_walker; + block_header_t* block = + offset_to_block(pool, -(int)block_header_overhead); + + while (block && !block_is_last(block)) + { + pool_walker( + block_to_ptr(block), + block_size(block), + !block_is_free(block), + user); + block = block_next(block); + } +} + +TLSF_API size_t tlsf_block_size(void* ptr) +{ + size_t size = 0; + if (ptr) + { + const block_header_t* block = block_from_ptr(ptr); + size = block_size(block); + } + return size; +} + +TLSF_API int tlsf_check_pool(pool_t pool) +{ + /* Check that the blocks are physically correct. */ + integrity_t integ = { 0, 0 }; + tlsf_walk_pool(pool, integrity_walker, &integ); + + return integ.status; +} + +/* +** Size of the TLSF structures in a given memory block passed to +** tlsf_create, equal to the size of a control_t +*/ +TLSF_API size_t tlsf_size(void) +{ + return sizeof(control_t); +} + +TLSF_API size_t tlsf_align_size(void) +{ + return ALIGN_SIZE; +} + +TLSF_API size_t tlsf_block_size_min(void) +{ + return block_size_min; +} + +TLSF_API size_t tlsf_block_size_max(void) +{ + return block_size_max; +} + +/* +** Overhead of the TLSF structures in a given memory block passed to +** tlsf_add_pool, equal to the overhead of a free block and the +** sentinel block. +*/ +TLSF_API size_t tlsf_pool_overhead(void) +{ + return 2 * block_header_overhead; +} + +TLSF_API size_t tlsf_alloc_overhead(void) +{ + return block_header_overhead; +} + +TLSF_API pool_t tlsf_add_pool(tlsf_t tlsf, void* mem, size_t bytes) +{ + 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) + { + tlsf_printf("tlsf_add_pool: Memory must be aligned by %u bytes.\n", + (unsigned int)ALIGN_SIZE); + return 0; + } + + if (pool_bytes < block_size_min || pool_bytes > block_size_max) + { +#if defined (TLSF_64BIT) + tlsf_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 + tlsf_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)); +#endif + return 0; + } + + /* + ** Create the main free block. Offset the start of the block slightly + ** so that the prev_phys_block field falls outside of the pool - + ** it will never be used. + */ + block = 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); + + /* Split the block to create a zero-size sentinel block. */ + next = block_link_next(block); + block_set_size(next, 0); + block_set_used(next); + block_set_prev_free(next); + + return mem; +} + +TLSF_API 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); + + 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"); + + mapping_insert(block_size(block), &fl, &sl); + remove_free_block(control, block, fl, sl); +} + +/* +** TLSF main interface. +*/ + +#if _DEBUG +static int test_ffs_fls() +{ + /* Verify ffs/fls work properly. */ + int rv = 0; + rv += (tlsf_ffs(0) == -1) ? 0 : 0x1; + rv += (tlsf_fls(0) == -1) ? 0 : 0x2; + rv += (tlsf_ffs(1) == 0) ? 0 : 0x4; + rv += (tlsf_fls(1) == 0) ? 0 : 0x8; + rv += (tlsf_ffs(0x80000000) == 31) ? 0 : 0x10; + rv += (tlsf_ffs(0x80008000) == 15) ? 0 : 0x20; + rv += (tlsf_fls(0x80000008) == 31) ? 0 : 0x40; + rv += (tlsf_fls(0x7FFFFFFF) == 30) ? 0 : 0x80; + +#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) + { + tlsf_printf("test_ffs_fls: %x ffs/fls tests failed.\n", rv); + } + return rv; +} +#endif + +TLSF_API tlsf_t tlsf_create(void* mem) +{ +#if _DEBUG + if (test_ffs_fls()) + { + return 0; + } +#endif + + if (((tlsfptr_t)mem % ALIGN_SIZE) != 0) + { + tlsf_printf("tlsf_create: Memory must be aligned to %u bytes.\n", + (unsigned int)ALIGN_SIZE); + return 0; + } + + control_construct(tlsf_cast(control_t*, mem)); + + return tlsf_cast(tlsf_t, mem); +} + +TLSF_API tlsf_t tlsf_create_with_pool(void* mem, size_t bytes) +{ + tlsf_t tlsf = tlsf_create(mem); + tlsf_add_pool(tlsf, (char*)mem + tlsf_size(), bytes - tlsf_size()); + return tlsf; +} + +TLSF_API void tlsf_destroy(tlsf_t tlsf) +{ + /* Nothing to do. */ + (void)tlsf; +} + +TLSF_API pool_t tlsf_get_pool(tlsf_t tlsf) +{ + return tlsf_cast(pool_t, (char*)tlsf + tlsf_size()); +} + +TLSF_API void* tlsf_malloc(tlsf_t tlsf, size_t size) +{ + control_t* control = tlsf_cast(control_t*, tlsf); + const size_t adjust = adjust_request_size(size, ALIGN_SIZE); + block_header_t* block = block_locate_free(control, adjust); + return block_prepare_used(control, block, adjust); +} + +TLSF_API void* tlsf_memalign(tlsf_t tlsf, size_t align, size_t size) +{ + control_t* control = tlsf_cast(control_t*, tlsf); + const size_t adjust = adjust_request_size(size, ALIGN_SIZE); + + /* + ** We must allocate an additional minimum block size bytes so that if + ** our free block will leave an alignment gap which is smaller, we can + ** trim a leading free block and release it back to the pool. We must + ** do this because the previous physical block is in use, therefore + ** the prev_phys_block field is not valid, and we can't simply adjust + ** the size of that block. + */ + const size_t gap_minimum = sizeof(block_header_t); + const size_t size_with_gap = adjust_request_size(adjust + align + gap_minimum, align); + + /* + ** If alignment is less than or equals base alignment, we're done. + ** If we requested 0 bytes, return null, as tlsf_malloc(0) does. + */ + const size_t aligned_size = (adjust && align > ALIGN_SIZE) ? size_with_gap : adjust; + + block_header_t* block = block_locate_free(control, aligned_size); + + /* This can't be a static assert. */ + tlsf_assert(sizeof(block_header_t) == block_size_min + block_header_overhead); + + if (block) + { + void* ptr = block_to_ptr(block); + void* aligned = align_ptr(ptr, align); + size_t gap = tlsf_cast(size_t, + tlsf_cast(tlsfptr_t, aligned) - tlsf_cast(tlsfptr_t, ptr)); + + /* If gap size is too small, offset to next aligned boundary. */ + if (gap && gap < gap_minimum) + { + const size_t gap_remain = gap_minimum - gap; + const size_t offset = tlsf_max(gap_remain, align); + const void* next_aligned = tlsf_cast(void*, + tlsf_cast(tlsfptr_t, aligned) + offset); + + aligned = align_ptr(next_aligned, align); + gap = tlsf_cast(size_t, + tlsf_cast(tlsfptr_t, aligned) - tlsf_cast(tlsfptr_t, ptr)); + } + + if (gap) + { + tlsf_assert(gap >= gap_minimum && "gap size too small"); + block = block_trim_free_leading(control, block, gap); + } + } + + return block_prepare_used(control, block, adjust); +} + +TLSF_API void tlsf_free(tlsf_t tlsf, void* ptr) +{ + /* 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); + tlsf_assert(!block_is_free(block) && "block already marked as free"); + block_mark_as_free(block); + block = block_merge_prev(control, block); + block = block_merge_next(control, block); + block_insert(control, block); + } +} + +/* +** The TLSF block information provides us with enough information to +** provide a reasonably intelligent implementation of realloc, growing or +** shrinking the currently allocated block as required. +** +** This routine handles the somewhat esoteric edge cases of realloc: +** - a non-zero size with a null pointer will behave like malloc +** - a zero size with a non-null pointer will behave like free +** - a request that cannot be satisfied will leave the original buffer +** untouched +** - an extended buffer size will leave the newly-allocated area with +** contents undefined +*/ +TLSF_API void* tlsf_realloc(tlsf_t tlsf, void* ptr, size_t size) +{ + control_t* control = tlsf_cast(control_t*, tlsf); + void* p = 0; + + /* Zero-size requests are treated as free. */ + if (ptr && size == 0) + { + tlsf_free(tlsf, ptr); + } + /* Requests with NULL pointers are treated as malloc. */ + else if (!ptr) + { + p = tlsf_malloc(tlsf, size); + } + 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 adjust = adjust_request_size(size, ALIGN_SIZE); + + tlsf_assert(!block_is_free(block) && "block already marked as free"); + + /* + ** 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)) + { + p = tlsf_malloc(tlsf, size); + if (p) + { + const size_t minsize = tlsf_min(cursize, size); + memcpy(p, ptr, minsize); + tlsf_free(tlsf, ptr); + } + } + else + { + /* Do we need to expand to the next block? */ + if (adjust > cursize) + { + block_merge_next(control, block); + block_mark_as_used(block); + } + + /* Trim the resulting block and return the original pointer. */ + block_trim_used(control, block, adjust); + p = ptr; + } + } + + return p; +} diff --git a/src/3rdparty/tlsf/tlsf.h b/src/3rdparty/tlsf/tlsf.h new file mode 100644 index 00000000..61702bf3 --- /dev/null +++ b/src/3rdparty/tlsf/tlsf.h @@ -0,0 +1,96 @@ +#ifndef INCLUDED_tlsf +#define INCLUDED_tlsf + +/* +** Two Level Segregated Fit memory allocator, version 3.1. +** Written by Matthew Conte +** http://tlsf.baisoku.org +** +** Based on the original documentation by Miguel Masmano: +** http://www.gii.upv.es/tlsf/main/docs +** +** This implementation was written to the specification +** of the document, therefore no GPL restrictions apply. +** +** Copyright (c) 2006-2016, Matthew Conte +** All rights reserved. +** +** Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * 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. +** * Neither the name of the copyright holder nor the +** names of its contributors may be used to endorse or promote products +** derived from this software without specific prior written permission. +** +** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 EVENT SHALL MATTHEW CONTE BE LIABLE FOR ANY +** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include + +/* Definition of the TLSF_API. */ +/* Provide the ability to override linkage features of the interface. */ +#if !defined(TLSF_API) +#define TLSF_API +#endif + +#if defined(__cplusplus) +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; + +/* Create/destroy a memory pool. */ +TLSF_API tlsf_t tlsf_create(void* mem); +TLSF_API tlsf_t tlsf_create_with_pool(void* mem, size_t bytes); +TLSF_API void tlsf_destroy(tlsf_t tlsf); +TLSF_API pool_t tlsf_get_pool(tlsf_t tlsf); + +/* Add/remove memory pools. */ +TLSF_API pool_t tlsf_add_pool(tlsf_t tlsf, void* mem, size_t bytes); +TLSF_API void tlsf_remove_pool(tlsf_t tlsf, pool_t pool); + +/* malloc/memalign/realloc/free replacements. */ +TLSF_API void* tlsf_malloc(tlsf_t tlsf, size_t bytes); +TLSF_API void* tlsf_memalign(tlsf_t tlsf, size_t align, size_t bytes); +TLSF_API void* tlsf_realloc(tlsf_t tlsf, void* ptr, size_t size); +TLSF_API void tlsf_free(tlsf_t tlsf, void* ptr); + +/* Returns internal block size, not original request size */ +TLSF_API size_t tlsf_block_size(void* ptr); + +/* Overheads/limits of internal structures. */ +TLSF_API size_t tlsf_size(void); +TLSF_API size_t tlsf_align_size(void); +TLSF_API size_t tlsf_block_size_min(void); +TLSF_API size_t tlsf_block_size_max(void); +TLSF_API size_t tlsf_pool_overhead(void); +TLSF_API size_t tlsf_alloc_overhead(void); + +/* Debugging. */ +typedef void (*tlsf_walker)(void* ptr, size_t size, int used, void* user); +TLSF_API void tlsf_walk_pool(pool_t pool, tlsf_walker walker, void* user); +/* Returns nonzero if any internal consistency check fails. */ +TLSF_API int tlsf_check(tlsf_t tlsf); +TLSF_API int tlsf_check_pool(pool_t pool); + +#if defined(__cplusplus) +}; +#endif + +#endif diff --git a/src/3rdparty/tommyds/tommyhashdyn.c b/src/3rdparty/tommyds/tommyhashdyn.c index 40abee0e..6a8f2a9d 100644 --- a/src/3rdparty/tommyds/tommyhashdyn.c +++ b/src/3rdparty/tommyds/tommyhashdyn.c @@ -147,7 +147,7 @@ TOMMY_API void tommy_hashdyn_insert(tommy_hashdyn* hashdyn, tommy_hashdyn_node* hashdyn_grow_step(hashdyn); } -TOMMY_API void* tommy_hashdyn_remove_existing(tommy_hashdyn* hashdyn, tommy_hashdyn_node* node) +TOMMY_API void tommy_hashdyn_remove_existing(tommy_hashdyn* hashdyn, tommy_hashdyn_node* node) { tommy_size_t pos = node->index & hashdyn->bucket_mask; @@ -156,8 +156,6 @@ TOMMY_API void* tommy_hashdyn_remove_existing(tommy_hashdyn* hashdyn, tommy_hash --hashdyn->count; hashdyn_shrink_step(hashdyn); - - return node->data; } TOMMY_API void* tommy_hashdyn_remove(tommy_hashdyn* hashdyn, tommy_search_func* cmp, const void* cmp_arg, tommy_hash_t hash) diff --git a/src/3rdparty/tommyds/tommyhashdyn.h b/src/3rdparty/tommyds/tommyhashdyn.h index 7aa554da..3e947325 100644 --- a/src/3rdparty/tommyds/tommyhashdyn.h +++ b/src/3rdparty/tommyds/tommyhashdyn.h @@ -236,9 +236,8 @@ tommy_inline void* tommy_hashdyn_search(tommy_hashdyn* hashdyn, tommy_search_fun /** * Removes an element from the hashtable. * You must already have the address of the element to remove. - * \return The tommy_node::data field of the node removed. */ -TOMMY_API void* tommy_hashdyn_remove_existing(tommy_hashdyn* hashdyn, tommy_hashdyn_node* node); +TOMMY_API void tommy_hashdyn_remove_existing(tommy_hashdyn* hashdyn, tommy_hashdyn_node* node); /** * Calls the specified function for each element in the hashtable. diff --git a/src/3rdparty/tommyds/tommylist.h b/src/3rdparty/tommyds/tommylist.h index 32f1b192..13835e97 100644 --- a/src/3rdparty/tommyds/tommylist.h +++ b/src/3rdparty/tommyds/tommylist.h @@ -195,9 +195,8 @@ tommy_inline void tommy_list_insert_tail_not_empty(tommy_node* head, tommy_node* /** * Inserts an element at the head of a list. * \param node The node to insert. - * \param data The object containing the node. It's used to set the tommy_node::data field of the node. */ -tommy_inline void tommy_list_insert_head(tommy_list* list, tommy_node* node, void* data) +tommy_inline void tommy_list_insert_head_check(tommy_list* list, tommy_node* node) { tommy_node* head = tommy_list_head(list); @@ -205,16 +204,13 @@ tommy_inline void tommy_list_insert_head(tommy_list* list, tommy_node* node, voi tommy_list_insert_head_not_empty(list, node); else tommy_list_insert_first(list, node); - - node->data = data; } /** * Inserts an element at the tail of a list. * \param node The node to insert. - * \param data The object containing the node. It's used to set the tommy_node::data field of the node. */ -tommy_inline void tommy_list_insert_tail(tommy_list* list, tommy_node* node, void* data) +tommy_inline void tommy_list_insert_tail_check(tommy_list* list, tommy_node* node) { tommy_node* head = tommy_list_head(list); @@ -222,6 +218,28 @@ tommy_inline void tommy_list_insert_tail(tommy_list* list, tommy_node* node, voi tommy_list_insert_tail_not_empty(head, node); else tommy_list_insert_first(list, node); +} + +/** + * Inserts an element at the head of a list and sets the data. + * \param node The node to insert. + * \param data The object containing the node. It's used to set the tommy_node::data field of the node. + */ +tommy_inline void tommy_list_insert_head(tommy_list* list, tommy_node* node, void* data) +{ + tommy_list_insert_head_check(list, node); + + node->data = data; +} + +/** + * Inserts an element at the tail of a list and sets the data. + * \param node The node to insert. + * \param data The object containing the node. It's used to set the tommy_node::data field of the node. + */ +tommy_inline void tommy_list_insert_tail(tommy_list* list, tommy_node* node, void* data) +{ + tommy_list_insert_tail_check(list, node); node->data = data; } @@ -232,9 +250,8 @@ tommy_inline void tommy_list_insert_tail(tommy_list* list, tommy_node* node, voi * \note The node content is left unchanged, including the tommy_node::next * and tommy_node::prev fields that still contain pointers at the list. * \param node The node to remove. The node must be in the list. - * \return The tommy_node::data field of the node removed. */ -tommy_inline void* tommy_list_remove_existing(tommy_list* list, tommy_node* node) +tommy_inline void tommy_list_remove_existing(tommy_list* list, tommy_node* node) { tommy_node* head = tommy_list_head(list); @@ -249,8 +266,6 @@ tommy_inline void* tommy_list_remove_existing(tommy_list* list, tommy_node* node *list = node->next; /* the new head, in case 0 */ else node->prev->next = node->next; - - return node->data; } /** diff --git a/src/common/common.h b/src/common/common.h index 6d51f913..22acbdb8 100644 --- a/src/common/common.h +++ b/src/common/common.h @@ -83,6 +83,8 @@ DEFINE_GUID(FORT_GUID_FILTER_REAUTH_OUT, #define FORT_IOCTL_SETCONF FORT_CTL_CODE(1, FILE_WRITE_DATA) #define FORT_IOCTL_SETFLAGS FORT_CTL_CODE(2, FILE_WRITE_DATA) #define FORT_IOCTL_GETLOG FORT_CTL_CODE(3, FILE_READ_DATA) +#define FORT_IOCTL_ADDAPP FORT_CTL_CODE(4, FILE_WRITE_DATA) +#define FORT_IOCTL_DELAPP FORT_CTL_CODE(5, FILE_WRITE_DATA) #ifndef NT_SUCCESS diff --git a/src/common/fortconf.c b/src/common/fortconf.c index 6a8e2544..b5107ad4 100644 --- a/src/common/fortconf.c +++ b/src/common/fortconf.c @@ -100,8 +100,8 @@ fort_conf_ip_included (const PFORT_CONF conf, UINT32 remote_ip, fort_conf_ip_included((conf), (remote_ip), 1) static BOOL -fort_conf_app_exe_equal (UINT32 path_len, const char *path, - PFORT_APP_ENTRY app_entry) +fort_conf_app_exe_equal (PFORT_APP_ENTRY app_entry, + const char *path, UINT32 path_len) { const char *app_path = (const char *) (app_entry + 1); const UINT32 app_path_len = app_entry->path_len; @@ -114,7 +114,7 @@ fort_conf_app_exe_equal (UINT32 path_len, const char *path, static FORT_APP_FLAGS fort_conf_app_exe_find (const PFORT_CONF conf, - UINT32 path_len, const char *path) + const char *path, UINT32 path_len) { FORT_APP_FLAGS app_flags; const char *data; @@ -130,7 +130,7 @@ fort_conf_app_exe_find (const PFORT_CONF conf, do { const PFORT_APP_ENTRY app_entry = (const PFORT_APP_ENTRY) app_entries; - if (fort_conf_app_exe_equal(path_len, path, app_entry)) { + if (fort_conf_app_exe_equal(app_entry, path, path_len)) { app_flags = app_entry->flags; goto end; } @@ -146,8 +146,8 @@ fort_conf_app_exe_find (const PFORT_CONF conf, } static int -fort_conf_app_prefix_cmp (UINT32 path_len, const char *path, - PFORT_APP_ENTRY app_entry) +fort_conf_app_prefix_cmp (PFORT_APP_ENTRY app_entry, + const char *path, UINT32 path_len) { const char *app_path = (const char *) (app_entry + 1); const UINT32 app_path_len = app_entry->path_len; @@ -160,7 +160,7 @@ fort_conf_app_prefix_cmp (UINT32 path_len, const char *path, static FORT_APP_FLAGS fort_conf_app_prefix_find (const PFORT_CONF conf, - UINT32 path_len, const char *path) + const char *path, UINT32 path_len) { FORT_APP_FLAGS app_flags; const char *data; @@ -182,7 +182,7 @@ fort_conf_app_prefix_find (const PFORT_CONF conf, const int mid = (low + high) / 2; const UINT32 app_off = app_offsets[mid]; const PFORT_APP_ENTRY app_entry = (PFORT_APP_ENTRY) (app_entries + app_off); - const int res = fort_conf_app_prefix_cmp(path_len, path, app_entry); + const int res = fort_conf_app_prefix_cmp(app_entry, path, path_len); if (res < 0) high = mid - 1; @@ -237,16 +237,16 @@ fort_conf_app_wild_find (const PFORT_CONF conf, const char *path) static FORT_APP_FLAGS fort_conf_app_find (const PFORT_CONF conf, - UINT32 path_len, const char *path, + const char *path, UINT32 path_len, fort_conf_app_exe_find_func *exe_find_func) { FORT_APP_FLAGS app_flags; - app_flags = exe_find_func(conf, path_len, path); + app_flags = exe_find_func(conf, path, path_len); if (app_flags.v != 0) goto end; - app_flags = fort_conf_app_prefix_find(conf, path_len, path); + app_flags = fort_conf_app_prefix_find(conf, path, path_len); if (app_flags.v != 0) goto end; @@ -259,7 +259,7 @@ fort_conf_app_find (const PFORT_CONF conf, static BOOL fort_conf_app_blocked (const PFORT_CONF conf, FORT_APP_FLAGS app_flags) { - const BOOL app_found = app_flags.found; + const BOOL app_found = (app_flags.v != 0); if (app_found && !app_flags.use_group_perm) { return app_flags.blocked; diff --git a/src/common/fortconf.h b/src/common/fortconf.h index 548dddd9..7a4b0238 100644 --- a/src/common/fortconf.h +++ b/src/common/fortconf.h @@ -76,7 +76,9 @@ typedef struct fort_app_flags { UCHAR group_index; UCHAR use_group_perm : 1; UCHAR blocked : 1; - UCHAR found : 1; + UCHAR alerted : 1; + UCHAR in_conf : 1; + UCHAR in_pool : 1; }; }; } FORT_APP_FLAGS, *PFORT_APP_FLAGS; @@ -141,6 +143,6 @@ typedef struct fort_conf_io { #define FORT_CONF_ADDR_DATA_OFF offsetof(FORT_CONF_ADDR_GROUP, ip) typedef FORT_APP_FLAGS fort_conf_app_exe_find_func( - const PFORT_CONF conf, UINT32 path_len, const char *path); + const PFORT_CONF conf, const char *path, UINT32 path_len); #endif FORTCONF_H diff --git a/src/driver/fortcnf.c b/src/driver/fortcnf.c index 9ee7a688..33931ad1 100644 --- a/src/driver/fortcnf.c +++ b/src/driver/fortcnf.c @@ -1,14 +1,15 @@ /* Fort Firewall Configuration */ -#define FORT_CONF_BLOCK_SIZE (8 * 1024) +#define FORT_CONF_POOL_SIZE (8 * 1024) +#define FORT_CONF_POOL_DATA_OFF offsetof(FORT_CONF_POOL, data) /* Synchronize with tommy_node! */ -typedef struct fort_conf_block { - struct fort_conf_block *next; - struct fort_conf_block *prev; +typedef struct fort_conf_pool { + struct fort_conf_pool *next; + struct fort_conf_pool *prev; - UINT16 top; -} FORT_CONF_BLOCK, *PFORT_CONF_BLOCK; + char data[4]; +} FORT_CONF_POOL, *PFORT_CONF_POOL; /* Synchronize with tommy_hashdyn_node! */ typedef struct fort_conf_exe_node { @@ -23,7 +24,9 @@ typedef struct fort_conf_exe_node { typedef struct fort_conf_ref { UINT32 volatile refcount; - tommy_list exe_blocks; + tlsf_t tlsf; + tommy_list pools; + tommy_list free_nodes; tommy_arrayof exe_nodes; tommy_hashdyn exe_map; @@ -71,32 +74,92 @@ fort_device_flag (PFORT_DEVICE_CONF device_conf, UCHAR flag) return fort_device_flags(device_conf) & flag; } -static FORT_APP_FLAGS -fort_conf_ref_exe_find (const PFORT_CONF conf, - UINT32 path_len, const char *path) +static void +fort_conf_pool_done (PFORT_CONF_REF conf_ref) { - PFORT_CONF_REF conf_ref = (PFORT_CONF_REF) ((char *) conf - offsetof(FORT_CONF_REF, conf)); - const tommy_key_t path_hash = (tommy_key_t) tommy_hash_u64( - 0, path, path_len); + tommy_node *pool = tommy_list_head(&conf_ref->pools); + while (pool != NULL) { + tommy_node *next = pool->next; + tommy_free(pool); + pool = next; + } +} +static void * +fort_conf_pool_malloc (PFORT_CONF_REF conf_ref, UINT32 size) +{ + tommy_node *pool = tommy_list_tail(&conf_ref->pools); + void *p; + + if (pool == NULL) { + const UINT32 pool_size = (size >= FORT_CONF_POOL_SIZE) + ? size * 2 : FORT_CONF_POOL_SIZE; + + pool = tommy_malloc(pool_size); + if (pool == NULL) + return NULL; + + tommy_list_insert_first(&conf_ref->pools, pool); + + conf_ref->tlsf = tlsf_create_with_pool( + (char *) pool + FORT_CONF_POOL_DATA_OFF, + pool_size - FORT_CONF_POOL_DATA_OFF); + } + + p = tlsf_malloc(conf_ref->tlsf, size); + if (p == NULL) { + const UINT32 pool_size = (size >= FORT_CONF_POOL_SIZE) + ? size * 2 : FORT_CONF_POOL_SIZE; + + pool = tommy_malloc(pool_size); + if (pool == NULL) + return NULL; + + tommy_list_insert_head_not_empty(&conf_ref->pools, pool); + + tlsf_add_pool(conf_ref->tlsf, + (char *) pool + FORT_CONF_POOL_DATA_OFF, + pool_size - FORT_CONF_POOL_DATA_OFF); + + p = tlsf_malloc(conf_ref->tlsf, size); + } + + return p; +} + +static PFORT_CONF_EXE_NODE +fort_conf_ref_exe_find_node (PFORT_CONF_REF conf_ref, + const char *path, UINT32 path_len, + tommy_key_t path_hash) +{ PFORT_CONF_EXE_NODE node = (PFORT_CONF_EXE_NODE) tommy_hashdyn_bucket( &conf_ref->exe_map, path_hash); - FORT_APP_FLAGS app_flags; - app_flags.v = 0; - while (node != NULL) { - PFORT_APP_ENTRY entry = node->app_entry; - if (node->path_hash == path_hash - && fort_conf_app_exe_equal(path_len, path, entry)) { - app_flags = entry->flags; - break; + && fort_conf_app_exe_equal(node->app_entry, path, path_len)) { + return node; } node = node->next; } + return NULL; +} + +static FORT_APP_FLAGS +fort_conf_exe_find (const PFORT_CONF conf, + const char *path, UINT32 path_len) +{ + PFORT_CONF_REF conf_ref = (PFORT_CONF_REF) ((char *) conf - offsetof(FORT_CONF_REF, conf)); + const tommy_key_t path_hash = (tommy_key_t) tommy_hash_u64(0, path, path_len); + + const PFORT_CONF_EXE_NODE node = fort_conf_ref_exe_find_node( + conf_ref, path, path_len, path_hash); + + FORT_APP_FLAGS app_flags; + app_flags.v = node ? node->app_entry->flags.v : 0; + return app_flags; } @@ -117,7 +180,7 @@ fort_conf_ref_exe_fill (PFORT_CONF_REF conf_ref) for (i = 0; i < count; ++i) { const PFORT_APP_ENTRY entry = (const PFORT_APP_ENTRY) app_entries; const char *path = (const char *) (entry + 1); - const UINT16 path_len = entry->path_len; + const UINT32 path_len = entry->path_len; const tommy_key_t path_hash = (tommy_key_t) tommy_hash_u64(0, path, path_len); tommy_hashdyn_node *node = tommy_arrayof_ref(exe_nodes, i); @@ -128,12 +191,133 @@ fort_conf_ref_exe_fill (PFORT_CONF_REF conf_ref) } } +static BOOL +fort_conf_ref_exe_add_path (PFORT_CONF_REF conf_ref, + const char *path, UINT32 path_len, + FORT_APP_FLAGS flags) +{ + const tommy_key_t path_hash = (tommy_key_t) tommy_hash_u64(0, path, path_len); + + const PFORT_CONF_EXE_NODE node = fort_conf_ref_exe_find_node( + conf_ref, path, path_len, path_hash); + + if (node == NULL) { + const UINT16 entry_size = FORT_CONF_APP_ENTRY_SIZE(path_len); + PFORT_APP_ENTRY entry = fort_conf_pool_malloc(conf_ref, entry_size); + + if (entry == NULL) + return FALSE; + + flags.in_pool = 1; + entry->flags = flags; + + entry->path_len = (UINT16) path_len; + + // Copy path + { + char *new_path = (char *) (entry + 1); + RtlCopyMemory(new_path, path, path_len); + } + + // Add exe node + { + PFORT_CONF conf = &conf_ref->conf; + + tommy_arrayof *exe_nodes = &conf_ref->exe_nodes; + tommy_hashdyn *exe_map = &conf_ref->exe_map; + + tommy_hashdyn_node *node = tommy_list_tail(&conf_ref->free_nodes); + + if (node != NULL) { + tommy_list_remove_existing(&conf_ref->free_nodes, node); + } else { + const UINT16 index = conf->exe_apps_n; + + tommy_arrayof_grow(exe_nodes, index + 1); + + node = tommy_arrayof_ref(exe_nodes, index); + } + + tommy_hashdyn_insert(exe_map, node, entry, path_hash); + + ++conf->exe_apps_n; + } + + return TRUE; + } + + if (flags.alerted) + return FALSE; + + // Replace flags + { + PFORT_APP_ENTRY entry = node->app_entry; + + flags.in_pool = entry->flags.in_pool; + entry->flags = flags; + + return TRUE; + } +} + +static BOOL +fort_conf_ref_exe_add_entry (PFORT_CONF_REF conf_ref, const PFORT_APP_ENTRY entry) +{ + const char *path = (const char *) (entry + 1); + const UINT32 path_len = entry->path_len; + const FORT_APP_FLAGS flags = entry->flags; + + return fort_conf_ref_exe_add_path(conf_ref, path, path_len, flags); +} + +static void +fort_conf_ref_exe_del_path (PFORT_CONF_REF conf_ref, + const char *path, UINT32 path_len) +{ + const tommy_key_t path_hash = (tommy_key_t) tommy_hash_u64(0, path, path_len); + + PFORT_CONF_EXE_NODE node = fort_conf_ref_exe_find_node( + conf_ref, path, path_len, path_hash); + + if (node == NULL) + return; + + // Delete from conf + { + PFORT_CONF conf = &conf_ref->conf; + --conf->exe_apps_n; + } + + // Delete from pool + { + PFORT_APP_ENTRY entry = node->app_entry; + if (entry->flags.in_pool) { + tlsf_free(conf_ref->tlsf, entry); + } + } + + // Delete from exe map + tommy_hashdyn_remove_existing(&conf_ref->exe_map, (tommy_hashdyn_node *) node); + + tommy_list_insert_tail_check(&conf_ref->free_nodes, (tommy_node *) node); +} + +static void +fort_conf_ref_exe_del_entry (PFORT_CONF_REF conf_ref, const PFORT_APP_ENTRY entry) +{ + const char *path = (const char *) (entry + 1); + const UINT32 path_len = entry->path_len; + + fort_conf_ref_exe_del_path(conf_ref, path, path_len); +} + static void fort_conf_ref_init (PFORT_CONF_REF conf_ref) { conf_ref->refcount = 0; - tommy_list_init(&conf_ref->exe_blocks); + tommy_list_init(&conf_ref->pools); + tommy_list_init(&conf_ref->free_nodes); tommy_arrayof_init(&conf_ref->exe_nodes, sizeof(FORT_CONF_EXE_NODE)); tommy_hashdyn_init(&conf_ref->exe_map); @@ -158,13 +342,7 @@ fort_conf_ref_new (const PFORT_CONF conf, ULONG len) static void fort_conf_ref_del (PFORT_CONF_REF conf_ref) { - /* Delete exe blocks */ - tommy_node *exe_block = tommy_list_head(&conf_ref->exe_blocks); - while (exe_block) { - tommy_node *next = exe_block->next; - tommy_free(exe_block); - exe_block = next; - } + fort_conf_pool_done(conf_ref); tommy_hashdyn_done(&conf_ref->exe_map); tommy_arrayof_done(&conf_ref->exe_nodes); diff --git a/src/driver/fortdrv.c b/src/driver/fortdrv.c index 97b2b374..62cd0f4b 100644 --- a/src/driver/fortdrv.c +++ b/src/driver/fortdrv.c @@ -20,6 +20,7 @@ #include "../common/fortconf.c" #include "../common/fortlog.c" #include "../common/fortprov.c" +#include "forttlsf.c" #include "forttds.c" #include "fortcnf.c" #include "fortbuf.c" @@ -143,7 +144,7 @@ fort_callout_classify_v4 (const FWPS_INCOMING_VALUES0 *inFixedValues, if (fort_conf_ip_inet_included(&conf_ref->conf, remote_ip)) { const FORT_APP_FLAGS app_flags = fort_conf_app_find( - &conf_ref->conf, path_len, path, fort_conf_ref_exe_find); + &conf_ref->conf, path, path_len, fort_conf_exe_find); if (!fort_conf_app_blocked(&conf_ref->conf, app_flags)) { if (conf_flags.log_stat) { @@ -179,14 +180,21 @@ fort_callout_classify_v4 (const FWPS_INCOMING_VALUES0 *inFixedValues, } if (conf_flags.log_blocked) { - const UINT16 remote_port = inFixedValues->incomingValue[ - remotePortField].value.uint16; - const IPPROTO ip_proto = (IPPROTO) inFixedValues->incomingValue[ - ipProtoField].value.uint8; + FORT_APP_FLAGS flags; + flags.v = 0; + flags.blocked = 1; + flags.alerted = 1; - fort_buffer_blocked_write(&g_device->buffer, - remote_ip, remote_port, ip_proto, - process_id, path_len, path, &irp, &info); + if (fort_conf_ref_exe_add_path(conf_ref, path, path_len, flags)) { + const UINT16 remote_port = inFixedValues->incomingValue[ + remotePortField].value.uint16; + const IPPROTO ip_proto = (IPPROTO) inFixedValues->incomingValue[ + ipProtoField].value.uint8; + + fort_buffer_blocked_write(&g_device->buffer, + remote_ip, remote_port, ip_proto, + process_id, path_len, path, &irp, &info); + } } block: @@ -968,11 +976,13 @@ fort_device_control (PDEVICE_OBJECT device, PIRP irp) { PIO_STACK_LOCATION irp_stack; ULONG_PTR info = 0; + ULONG control_code; NTSTATUS status = STATUS_INVALID_PARAMETER; irp_stack = IoGetCurrentIrpStackLocation(irp); + control_code = irp_stack->Parameters.DeviceIoControl.IoControlCode; - switch (irp_stack->Parameters.DeviceIoControl.IoControlCode) { + switch (control_code) { case FORT_IOCTL_VALIDATE: { const PFORT_CONF_VERSION conf_ver = irp->AssociatedIrp.SystemBuffer; const ULONG len = irp_stack->Parameters.DeviceIoControl.InputBufferLength; @@ -1049,6 +1059,31 @@ fort_device_control (PDEVICE_OBJECT device, PIRP irp) } break; } + case FORT_IOCTL_ADDAPP: + case FORT_IOCTL_DELAPP: { + const PFORT_APP_ENTRY app_entry = irp->AssociatedIrp.SystemBuffer; + const ULONG len = irp_stack->Parameters.DeviceIoControl.InputBufferLength; + + if (len > sizeof(FORT_APP_ENTRY) + && len >= (sizeof(FORT_APP_ENTRY) + app_entry->path_len)) { + PFORT_CONF_REF conf_ref = fort_conf_ref_take(&g_device->conf); + + if (conf_ref == NULL) { + status = STATUS_INSUFFICIENT_RESOURCES; + } else { + if (control_code == FORT_IOCTL_ADDAPP) { + status = fort_conf_ref_exe_add_entry(conf_ref, app_entry) + ? STATUS_SUCCESS : STATUS_UNSUCCESSFUL; + } else { + fort_conf_ref_exe_del_entry(conf_ref, app_entry); + status = STATUS_SUCCESS; + } + + fort_conf_ref_put(&g_device->conf, conf_ref); + } + } + break; + } default: break; } diff --git a/src/driver/forttlsf.c b/src/driver/forttlsf.c new file mode 100644 index 00000000..b5b49097 --- /dev/null +++ b/src/driver/forttlsf.c @@ -0,0 +1,6 @@ +/* Fort Firewall TLSF */ + +#define TLSF_API static +#define tlsf_printf + +#include "..\3rdparty\tlsf\tlsf.c" diff --git a/src/ui/form/prog/programswindow.cpp b/src/ui/form/prog/programswindow.cpp index bba659ce..8c5cd11d 100644 --- a/src/ui/form/prog/programswindow.cpp +++ b/src/ui/form/prog/programswindow.cpp @@ -72,7 +72,7 @@ void ProgramsWindow::onRestoreWindowState() void ProgramsWindow::onRetranslateUi() { - m_cbLogBlocked->setText(tr("Show Blocked Programs")); + m_cbLogBlocked->setText(tr("Alert Blocked Programs")); appListModel()->refresh(); } diff --git a/src/ui/fortcommon.cpp b/src/ui/fortcommon.cpp index bc191332..2d73e45e 100644 --- a/src/ui/fortcommon.cpp +++ b/src/ui/fortcommon.cpp @@ -165,11 +165,11 @@ quint16 FortCommon::confAppFind(const void *drvConf, { const PFORT_CONF conf = (const PFORT_CONF) drvConf; const QString kernelPathLower = kernelPath.toLower(); - const int len = kernelPathLower.size() * int(sizeof(wchar_t)); + const quint32 len = quint32(kernelPathLower.size()) * sizeof(wchar_t); const wchar_t *p = (const wchar_t *) kernelPathLower.utf16(); const FORT_APP_FLAGS app_flags = - fort_conf_app_find(conf, len, (const char *) p, + fort_conf_app_find(conf, (const char *) p, len, fort_conf_app_exe_find); return app_flags.v; diff --git a/src/ui/log/model/applistmodel.cpp b/src/ui/log/model/applistmodel.cpp index a1aba6a2..2cc15b50 100644 --- a/src/ui/log/model/applistmodel.cpp +++ b/src/ui/log/model/applistmodel.cpp @@ -32,9 +32,9 @@ void AppListModel::addLogEntry(const LogEntryBlocked &logEntry) + ':' + QString::number(logEntry.port()); #endif - beginResetModel(); - confManager()->addApp(appPath, QDateTime(), 0, true, true); - endResetModel(); + if (confManager()->addApp(appPath, QDateTime(), 0, true, true)) { + reset(); + } } int AppListModel::rowCount(const QModelIndex &parent) const diff --git a/src/ui/task/tasklistmodel.cpp b/src/ui/task/tasklistmodel.cpp index 0ea211e2..af403888 100644 --- a/src/ui/task/tasklistmodel.cpp +++ b/src/ui/task/tasklistmodel.cpp @@ -69,8 +69,9 @@ QVariant TaskListModel::data(const QModelIndex &index, int role) const case 2: return formatDateTime(taskInfo->lastRun()); case 3: return formatDateTime(taskInfo->lastSuccess()); } - } + break; + } case Qt::CheckStateRole: case RoleEnabled: diff --git a/src/ui/util/conf/confutil.cpp b/src/ui/util/conf/confutil.cpp index eac4a3dd..e156b462 100644 --- a/src/ui/util/conf/confutil.cpp +++ b/src/ui/util/conf/confutil.cpp @@ -294,7 +294,7 @@ bool ConfUtil::parseApps(int groupOffset, bool blocked, const QString &text, appEntry.flags.group_index = quint8(groupOffset); appEntry.flags.use_group_perm = 1; appEntry.flags.blocked = blocked; - appEntry.flags.found = 1; + appEntry.flags.in_conf = 1; appsMap.insert(appPath, appEntry.v); }