zstd_cwksp.h 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. /*
  2. * Copyright (c) Meta Platforms, Inc. and affiliates.
  3. * All rights reserved.
  4. *
  5. * This source code is licensed under both the BSD-style license (found in the
  6. * LICENSE file in the root directory of this source tree) and the GPLv2 (found
  7. * in the COPYING file in the root directory of this source tree).
  8. * You may select, at your option, one of the above-listed licenses.
  9. */
  10. #ifndef ZSTD_CWKSP_H
  11. #define ZSTD_CWKSP_H
  12. /*-*************************************
  13. * Dependencies
  14. ***************************************/
  15. #include "../common/allocations.h" /* ZSTD_customMalloc, ZSTD_customFree */
  16. #include "../common/zstd_internal.h"
  17. #include "../common/portability_macros.h"
  18. #include "../common/compiler.h" /* ZS2_isPower2 */
  19. /*-*************************************
  20. * Constants
  21. ***************************************/
  22. /* Since the workspace is effectively its own little malloc implementation /
  23. * arena, when we run under ASAN, we should similarly insert redzones between
  24. * each internal element of the workspace, so ASAN will catch overruns that
  25. * reach outside an object but that stay inside the workspace.
  26. *
  27. * This defines the size of that redzone.
  28. */
  29. #ifndef ZSTD_CWKSP_ASAN_REDZONE_SIZE
  30. #define ZSTD_CWKSP_ASAN_REDZONE_SIZE 128
  31. #endif
  32. /* Set our tables and aligneds to align by 64 bytes */
  33. #define ZSTD_CWKSP_ALIGNMENT_BYTES 64
  34. /*-*************************************
  35. * Structures
  36. ***************************************/
  37. typedef enum {
  38. ZSTD_cwksp_alloc_objects,
  39. ZSTD_cwksp_alloc_aligned_init_once,
  40. ZSTD_cwksp_alloc_aligned,
  41. ZSTD_cwksp_alloc_buffers
  42. } ZSTD_cwksp_alloc_phase_e;
  43. /**
  44. * Used to describe whether the workspace is statically allocated (and will not
  45. * necessarily ever be freed), or if it's dynamically allocated and we can
  46. * expect a well-formed caller to free this.
  47. */
  48. typedef enum {
  49. ZSTD_cwksp_dynamic_alloc,
  50. ZSTD_cwksp_static_alloc
  51. } ZSTD_cwksp_static_alloc_e;
  52. /**
  53. * Zstd fits all its internal datastructures into a single continuous buffer,
  54. * so that it only needs to perform a single OS allocation (or so that a buffer
  55. * can be provided to it and it can perform no allocations at all). This buffer
  56. * is called the workspace.
  57. *
  58. * Several optimizations complicate that process of allocating memory ranges
  59. * from this workspace for each internal datastructure:
  60. *
  61. * - These different internal datastructures have different setup requirements:
  62. *
  63. * - The static objects need to be cleared once and can then be trivially
  64. * reused for each compression.
  65. *
  66. * - Various buffers don't need to be initialized at all--they are always
  67. * written into before they're read.
  68. *
  69. * - The matchstate tables have a unique requirement that they don't need
  70. * their memory to be totally cleared, but they do need the memory to have
  71. * some bound, i.e., a guarantee that all values in the memory they've been
  72. * allocated is less than some maximum value (which is the starting value
  73. * for the indices that they will then use for compression). When this
  74. * guarantee is provided to them, they can use the memory without any setup
  75. * work. When it can't, they have to clear the area.
  76. *
  77. * - These buffers also have different alignment requirements.
  78. *
  79. * - We would like to reuse the objects in the workspace for multiple
  80. * compressions without having to perform any expensive reallocation or
  81. * reinitialization work.
  82. *
  83. * - We would like to be able to efficiently reuse the workspace across
  84. * multiple compressions **even when the compression parameters change** and
  85. * we need to resize some of the objects (where possible).
  86. *
  87. * To attempt to manage this buffer, given these constraints, the ZSTD_cwksp
  88. * abstraction was created. It works as follows:
  89. *
  90. * Workspace Layout:
  91. *
  92. * [ ... workspace ... ]
  93. * [objects][tables ->] free space [<- buffers][<- aligned][<- init once]
  94. *
  95. * The various objects that live in the workspace are divided into the
  96. * following categories, and are allocated separately:
  97. *
  98. * - Static objects: this is optionally the enclosing ZSTD_CCtx or ZSTD_CDict,
  99. * so that literally everything fits in a single buffer. Note: if present,
  100. * this must be the first object in the workspace, since ZSTD_customFree{CCtx,
  101. * CDict}() rely on a pointer comparison to see whether one or two frees are
  102. * required.
  103. *
  104. * - Fixed size objects: these are fixed-size, fixed-count objects that are
  105. * nonetheless "dynamically" allocated in the workspace so that we can
  106. * control how they're initialized separately from the broader ZSTD_CCtx.
  107. * Examples:
  108. * - Entropy Workspace
  109. * - 2 x ZSTD_compressedBlockState_t
  110. * - CDict dictionary contents
  111. *
  112. * - Tables: these are any of several different datastructures (hash tables,
  113. * chain tables, binary trees) that all respect a common format: they are
  114. * uint32_t arrays, all of whose values are between 0 and (nextSrc - base).
  115. * Their sizes depend on the cparams. These tables are 64-byte aligned.
  116. *
  117. * - Init once: these buffers require to be initialized at least once before
  118. * use. They should be used when we want to skip memory initialization
  119. * while not triggering memory checkers (like Valgrind) when reading from
  120. * from this memory without writing to it first.
  121. * These buffers should be used carefully as they might contain data
  122. * from previous compressions.
  123. * Buffers are aligned to 64 bytes.
  124. *
  125. * - Aligned: these buffers don't require any initialization before they're
  126. * used. The user of the buffer should make sure they write into a buffer
  127. * location before reading from it.
  128. * Buffers are aligned to 64 bytes.
  129. *
  130. * - Buffers: these buffers are used for various purposes that don't require
  131. * any alignment or initialization before they're used. This means they can
  132. * be moved around at no cost for a new compression.
  133. *
  134. * Allocating Memory:
  135. *
  136. * The various types of objects must be allocated in order, so they can be
  137. * correctly packed into the workspace buffer. That order is:
  138. *
  139. * 1. Objects
  140. * 2. Init once / Tables
  141. * 3. Aligned / Tables
  142. * 4. Buffers / Tables
  143. *
  144. * Attempts to reserve objects of different types out of order will fail.
  145. */
  146. typedef struct {
  147. void* workspace;
  148. void* workspaceEnd;
  149. void* objectEnd;
  150. void* tableEnd;
  151. void* tableValidEnd;
  152. void* allocStart;
  153. void* initOnceStart;
  154. BYTE allocFailed;
  155. int workspaceOversizedDuration;
  156. ZSTD_cwksp_alloc_phase_e phase;
  157. ZSTD_cwksp_static_alloc_e isStatic;
  158. } ZSTD_cwksp;
  159. /*-*************************************
  160. * Functions
  161. ***************************************/
  162. MEM_STATIC size_t ZSTD_cwksp_available_space(ZSTD_cwksp* ws);
  163. MEM_STATIC void* ZSTD_cwksp_initialAllocStart(ZSTD_cwksp* ws);
  164. MEM_STATIC void ZSTD_cwksp_assert_internal_consistency(ZSTD_cwksp* ws) {
  165. (void)ws;
  166. assert(ws->workspace <= ws->objectEnd);
  167. assert(ws->objectEnd <= ws->tableEnd);
  168. assert(ws->objectEnd <= ws->tableValidEnd);
  169. assert(ws->tableEnd <= ws->allocStart);
  170. assert(ws->tableValidEnd <= ws->allocStart);
  171. assert(ws->allocStart <= ws->workspaceEnd);
  172. assert(ws->initOnceStart <= ZSTD_cwksp_initialAllocStart(ws));
  173. assert(ws->workspace <= ws->initOnceStart);
  174. #if ZSTD_MEMORY_SANITIZER
  175. {
  176. intptr_t const offset = __msan_test_shadow(ws->initOnceStart,
  177. (U8*)ZSTD_cwksp_initialAllocStart(ws) - (U8*)ws->initOnceStart);
  178. (void)offset;
  179. #if defined(ZSTD_MSAN_PRINT)
  180. if(offset!=-1) {
  181. __msan_print_shadow((U8*)ws->initOnceStart + offset - 8, 32);
  182. }
  183. #endif
  184. assert(offset==-1);
  185. };
  186. #endif
  187. }
  188. /**
  189. * Align must be a power of 2.
  190. */
  191. MEM_STATIC size_t ZSTD_cwksp_align(size_t size, size_t align) {
  192. size_t const mask = align - 1;
  193. assert(ZSTD_isPower2(align));
  194. return (size + mask) & ~mask;
  195. }
  196. /**
  197. * Use this to determine how much space in the workspace we will consume to
  198. * allocate this object. (Normally it should be exactly the size of the object,
  199. * but under special conditions, like ASAN, where we pad each object, it might
  200. * be larger.)
  201. *
  202. * Since tables aren't currently redzoned, you don't need to call through this
  203. * to figure out how much space you need for the matchState tables. Everything
  204. * else is though.
  205. *
  206. * Do not use for sizing aligned buffers. Instead, use ZSTD_cwksp_aligned64_alloc_size().
  207. */
  208. MEM_STATIC size_t ZSTD_cwksp_alloc_size(size_t size) {
  209. if (size == 0)
  210. return 0;
  211. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  212. return size + 2 * ZSTD_CWKSP_ASAN_REDZONE_SIZE;
  213. #else
  214. return size;
  215. #endif
  216. }
  217. MEM_STATIC size_t ZSTD_cwksp_aligned_alloc_size(size_t size, size_t alignment) {
  218. return ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(size, alignment));
  219. }
  220. /**
  221. * Returns an adjusted alloc size that is the nearest larger multiple of 64 bytes.
  222. * Used to determine the number of bytes required for a given "aligned".
  223. */
  224. MEM_STATIC size_t ZSTD_cwksp_aligned64_alloc_size(size_t size) {
  225. return ZSTD_cwksp_aligned_alloc_size(size, ZSTD_CWKSP_ALIGNMENT_BYTES);
  226. }
  227. /**
  228. * Returns the amount of additional space the cwksp must allocate
  229. * for internal purposes (currently only alignment).
  230. */
  231. MEM_STATIC size_t ZSTD_cwksp_slack_space_required(void) {
  232. /* For alignment, the wksp will always allocate an additional 2*ZSTD_CWKSP_ALIGNMENT_BYTES
  233. * bytes to align the beginning of tables section and end of buffers;
  234. */
  235. size_t const slackSpace = ZSTD_CWKSP_ALIGNMENT_BYTES * 2;
  236. return slackSpace;
  237. }
  238. /**
  239. * Return the number of additional bytes required to align a pointer to the given number of bytes.
  240. * alignBytes must be a power of two.
  241. */
  242. MEM_STATIC size_t ZSTD_cwksp_bytes_to_align_ptr(void* ptr, const size_t alignBytes) {
  243. size_t const alignBytesMask = alignBytes - 1;
  244. size_t const bytes = (alignBytes - ((size_t)ptr & (alignBytesMask))) & alignBytesMask;
  245. assert(ZSTD_isPower2(alignBytes));
  246. assert(bytes < alignBytes);
  247. return bytes;
  248. }
  249. /**
  250. * Returns the initial value for allocStart which is used to determine the position from
  251. * which we can allocate from the end of the workspace.
  252. */
  253. MEM_STATIC void* ZSTD_cwksp_initialAllocStart(ZSTD_cwksp* ws)
  254. {
  255. char* endPtr = (char*)ws->workspaceEnd;
  256. assert(ZSTD_isPower2(ZSTD_CWKSP_ALIGNMENT_BYTES));
  257. endPtr = endPtr - ((size_t)endPtr % ZSTD_CWKSP_ALIGNMENT_BYTES);
  258. return (void*)endPtr;
  259. }
  260. /**
  261. * Internal function. Do not use directly.
  262. * Reserves the given number of bytes within the aligned/buffer segment of the wksp,
  263. * which counts from the end of the wksp (as opposed to the object/table segment).
  264. *
  265. * Returns a pointer to the beginning of that space.
  266. */
  267. MEM_STATIC void*
  268. ZSTD_cwksp_reserve_internal_buffer_space(ZSTD_cwksp* ws, size_t const bytes)
  269. {
  270. void* const alloc = (BYTE*)ws->allocStart - bytes;
  271. void* const bottom = ws->tableEnd;
  272. DEBUGLOG(5, "cwksp: reserving [0x%p]:%zd bytes; %zd bytes remaining",
  273. alloc, bytes, ZSTD_cwksp_available_space(ws) - bytes);
  274. ZSTD_cwksp_assert_internal_consistency(ws);
  275. assert(alloc >= bottom);
  276. if (alloc < bottom) {
  277. DEBUGLOG(4, "cwksp: alloc failed!");
  278. ws->allocFailed = 1;
  279. return NULL;
  280. }
  281. /* the area is reserved from the end of wksp.
  282. * If it overlaps with tableValidEnd, it voids guarantees on values' range */
  283. if (alloc < ws->tableValidEnd) {
  284. ws->tableValidEnd = alloc;
  285. }
  286. ws->allocStart = alloc;
  287. return alloc;
  288. }
  289. /**
  290. * Moves the cwksp to the next phase, and does any necessary allocations.
  291. * cwksp initialization must necessarily go through each phase in order.
  292. * Returns a 0 on success, or zstd error
  293. */
  294. MEM_STATIC size_t
  295. ZSTD_cwksp_internal_advance_phase(ZSTD_cwksp* ws, ZSTD_cwksp_alloc_phase_e phase)
  296. {
  297. assert(phase >= ws->phase);
  298. if (phase > ws->phase) {
  299. /* Going from allocating objects to allocating initOnce / tables */
  300. if (ws->phase < ZSTD_cwksp_alloc_aligned_init_once &&
  301. phase >= ZSTD_cwksp_alloc_aligned_init_once) {
  302. ws->tableValidEnd = ws->objectEnd;
  303. ws->initOnceStart = ZSTD_cwksp_initialAllocStart(ws);
  304. { /* Align the start of the tables to 64 bytes. Use [0, 63] bytes */
  305. void *const alloc = ws->objectEnd;
  306. size_t const bytesToAlign = ZSTD_cwksp_bytes_to_align_ptr(alloc, ZSTD_CWKSP_ALIGNMENT_BYTES);
  307. void *const objectEnd = (BYTE *) alloc + bytesToAlign;
  308. DEBUGLOG(5, "reserving table alignment addtl space: %zu", bytesToAlign);
  309. RETURN_ERROR_IF(objectEnd > ws->workspaceEnd, memory_allocation,
  310. "table phase - alignment initial allocation failed!");
  311. ws->objectEnd = objectEnd;
  312. ws->tableEnd = objectEnd; /* table area starts being empty */
  313. if (ws->tableValidEnd < ws->tableEnd) {
  314. ws->tableValidEnd = ws->tableEnd;
  315. }
  316. }
  317. }
  318. ws->phase = phase;
  319. ZSTD_cwksp_assert_internal_consistency(ws);
  320. }
  321. return 0;
  322. }
  323. /**
  324. * Returns whether this object/buffer/etc was allocated in this workspace.
  325. */
  326. MEM_STATIC int ZSTD_cwksp_owns_buffer(const ZSTD_cwksp* ws, const void* ptr)
  327. {
  328. return (ptr != NULL) && (ws->workspace <= ptr) && (ptr < ws->workspaceEnd);
  329. }
  330. /**
  331. * Internal function. Do not use directly.
  332. */
  333. MEM_STATIC void*
  334. ZSTD_cwksp_reserve_internal(ZSTD_cwksp* ws, size_t bytes, ZSTD_cwksp_alloc_phase_e phase)
  335. {
  336. void* alloc;
  337. if (ZSTD_isError(ZSTD_cwksp_internal_advance_phase(ws, phase)) || bytes == 0) {
  338. return NULL;
  339. }
  340. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  341. /* over-reserve space */
  342. bytes += 2 * ZSTD_CWKSP_ASAN_REDZONE_SIZE;
  343. #endif
  344. alloc = ZSTD_cwksp_reserve_internal_buffer_space(ws, bytes);
  345. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  346. /* Move alloc so there's ZSTD_CWKSP_ASAN_REDZONE_SIZE unused space on
  347. * either size. */
  348. if (alloc) {
  349. alloc = (BYTE *)alloc + ZSTD_CWKSP_ASAN_REDZONE_SIZE;
  350. if (ws->isStatic == ZSTD_cwksp_dynamic_alloc) {
  351. /* We need to keep the redzone poisoned while unpoisoning the bytes that
  352. * are actually allocated. */
  353. __asan_unpoison_memory_region(alloc, bytes - 2 * ZSTD_CWKSP_ASAN_REDZONE_SIZE);
  354. }
  355. }
  356. #endif
  357. return alloc;
  358. }
  359. /**
  360. * Reserves and returns unaligned memory.
  361. */
  362. MEM_STATIC BYTE* ZSTD_cwksp_reserve_buffer(ZSTD_cwksp* ws, size_t bytes)
  363. {
  364. return (BYTE*)ZSTD_cwksp_reserve_internal(ws, bytes, ZSTD_cwksp_alloc_buffers);
  365. }
  366. /**
  367. * Reserves and returns memory sized on and aligned on ZSTD_CWKSP_ALIGNMENT_BYTES (64 bytes).
  368. * This memory has been initialized at least once in the past.
  369. * This doesn't mean it has been initialized this time, and it might contain data from previous
  370. * operations.
  371. * The main usage is for algorithms that might need read access into uninitialized memory.
  372. * The algorithm must maintain safety under these conditions and must make sure it doesn't
  373. * leak any of the past data (directly or in side channels).
  374. */
  375. MEM_STATIC void* ZSTD_cwksp_reserve_aligned_init_once(ZSTD_cwksp* ws, size_t bytes)
  376. {
  377. size_t const alignedBytes = ZSTD_cwksp_align(bytes, ZSTD_CWKSP_ALIGNMENT_BYTES);
  378. void* ptr = ZSTD_cwksp_reserve_internal(ws, alignedBytes, ZSTD_cwksp_alloc_aligned_init_once);
  379. assert(((size_t)ptr & (ZSTD_CWKSP_ALIGNMENT_BYTES-1)) == 0);
  380. if(ptr && ptr < ws->initOnceStart) {
  381. /* We assume the memory following the current allocation is either:
  382. * 1. Not usable as initOnce memory (end of workspace)
  383. * 2. Another initOnce buffer that has been allocated before (and so was previously memset)
  384. * 3. An ASAN redzone, in which case we don't want to write on it
  385. * For these reasons it should be fine to not explicitly zero every byte up to ws->initOnceStart.
  386. * Note that we assume here that MSAN and ASAN cannot run in the same time. */
  387. ZSTD_memset(ptr, 0, MIN((size_t)((U8*)ws->initOnceStart - (U8*)ptr), alignedBytes));
  388. ws->initOnceStart = ptr;
  389. }
  390. #if ZSTD_MEMORY_SANITIZER
  391. assert(__msan_test_shadow(ptr, bytes) == -1);
  392. #endif
  393. return ptr;
  394. }
  395. /**
  396. * Reserves and returns memory sized on and aligned on ZSTD_CWKSP_ALIGNMENT_BYTES (64 bytes).
  397. */
  398. MEM_STATIC void* ZSTD_cwksp_reserve_aligned64(ZSTD_cwksp* ws, size_t bytes)
  399. {
  400. void* const ptr = ZSTD_cwksp_reserve_internal(ws,
  401. ZSTD_cwksp_align(bytes, ZSTD_CWKSP_ALIGNMENT_BYTES),
  402. ZSTD_cwksp_alloc_aligned);
  403. assert(((size_t)ptr & (ZSTD_CWKSP_ALIGNMENT_BYTES-1)) == 0);
  404. return ptr;
  405. }
  406. /**
  407. * Aligned on 64 bytes. These buffers have the special property that
  408. * their values remain constrained, allowing us to reuse them without
  409. * memset()-ing them.
  410. */
  411. MEM_STATIC void* ZSTD_cwksp_reserve_table(ZSTD_cwksp* ws, size_t bytes)
  412. {
  413. const ZSTD_cwksp_alloc_phase_e phase = ZSTD_cwksp_alloc_aligned_init_once;
  414. void* alloc;
  415. void* end;
  416. void* top;
  417. /* We can only start allocating tables after we are done reserving space for objects at the
  418. * start of the workspace */
  419. if(ws->phase < phase) {
  420. if (ZSTD_isError(ZSTD_cwksp_internal_advance_phase(ws, phase))) {
  421. return NULL;
  422. }
  423. }
  424. alloc = ws->tableEnd;
  425. end = (BYTE *)alloc + bytes;
  426. top = ws->allocStart;
  427. DEBUGLOG(5, "cwksp: reserving %p table %zd bytes, %zd bytes remaining",
  428. alloc, bytes, ZSTD_cwksp_available_space(ws) - bytes);
  429. assert((bytes & (sizeof(U32)-1)) == 0);
  430. ZSTD_cwksp_assert_internal_consistency(ws);
  431. assert(end <= top);
  432. if (end > top) {
  433. DEBUGLOG(4, "cwksp: table alloc failed!");
  434. ws->allocFailed = 1;
  435. return NULL;
  436. }
  437. ws->tableEnd = end;
  438. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  439. if (ws->isStatic == ZSTD_cwksp_dynamic_alloc) {
  440. __asan_unpoison_memory_region(alloc, bytes);
  441. }
  442. #endif
  443. assert((bytes & (ZSTD_CWKSP_ALIGNMENT_BYTES-1)) == 0);
  444. assert(((size_t)alloc & (ZSTD_CWKSP_ALIGNMENT_BYTES-1)) == 0);
  445. return alloc;
  446. }
  447. /**
  448. * Aligned on sizeof(void*).
  449. * Note : should happen only once, at workspace first initialization
  450. */
  451. MEM_STATIC void* ZSTD_cwksp_reserve_object(ZSTD_cwksp* ws, size_t bytes)
  452. {
  453. size_t const roundedBytes = ZSTD_cwksp_align(bytes, sizeof(void*));
  454. void* alloc = ws->objectEnd;
  455. void* end = (BYTE*)alloc + roundedBytes;
  456. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  457. /* over-reserve space */
  458. end = (BYTE *)end + 2 * ZSTD_CWKSP_ASAN_REDZONE_SIZE;
  459. #endif
  460. DEBUGLOG(4,
  461. "cwksp: reserving %p object %zd bytes (rounded to %zd), %zd bytes remaining",
  462. alloc, bytes, roundedBytes, ZSTD_cwksp_available_space(ws) - roundedBytes);
  463. assert((size_t)alloc % ZSTD_ALIGNOF(void*) == 0);
  464. assert(bytes % ZSTD_ALIGNOF(void*) == 0);
  465. ZSTD_cwksp_assert_internal_consistency(ws);
  466. /* we must be in the first phase, no advance is possible */
  467. if (ws->phase != ZSTD_cwksp_alloc_objects || end > ws->workspaceEnd) {
  468. DEBUGLOG(3, "cwksp: object alloc failed!");
  469. ws->allocFailed = 1;
  470. return NULL;
  471. }
  472. ws->objectEnd = end;
  473. ws->tableEnd = end;
  474. ws->tableValidEnd = end;
  475. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  476. /* Move alloc so there's ZSTD_CWKSP_ASAN_REDZONE_SIZE unused space on
  477. * either size. */
  478. alloc = (BYTE*)alloc + ZSTD_CWKSP_ASAN_REDZONE_SIZE;
  479. if (ws->isStatic == ZSTD_cwksp_dynamic_alloc) {
  480. __asan_unpoison_memory_region(alloc, bytes);
  481. }
  482. #endif
  483. return alloc;
  484. }
  485. /**
  486. * with alignment control
  487. * Note : should happen only once, at workspace first initialization
  488. */
  489. MEM_STATIC void* ZSTD_cwksp_reserve_object_aligned(ZSTD_cwksp* ws, size_t byteSize, size_t alignment)
  490. {
  491. size_t const mask = alignment - 1;
  492. size_t const surplus = (alignment > sizeof(void*)) ? alignment - sizeof(void*) : 0;
  493. void* const start = ZSTD_cwksp_reserve_object(ws, byteSize + surplus);
  494. if (start == NULL) return NULL;
  495. if (surplus == 0) return start;
  496. assert(ZSTD_isPower2(alignment));
  497. return (void*)(((size_t)start + surplus) & ~mask);
  498. }
  499. MEM_STATIC void ZSTD_cwksp_mark_tables_dirty(ZSTD_cwksp* ws)
  500. {
  501. DEBUGLOG(4, "cwksp: ZSTD_cwksp_mark_tables_dirty");
  502. #if ZSTD_MEMORY_SANITIZER && !defined (ZSTD_MSAN_DONT_POISON_WORKSPACE)
  503. /* To validate that the table reuse logic is sound, and that we don't
  504. * access table space that we haven't cleaned, we re-"poison" the table
  505. * space every time we mark it dirty.
  506. * Since tableValidEnd space and initOnce space may overlap we don't poison
  507. * the initOnce portion as it break its promise. This means that this poisoning
  508. * check isn't always applied fully. */
  509. {
  510. size_t size = (BYTE*)ws->tableValidEnd - (BYTE*)ws->objectEnd;
  511. assert(__msan_test_shadow(ws->objectEnd, size) == -1);
  512. if((BYTE*)ws->tableValidEnd < (BYTE*)ws->initOnceStart) {
  513. __msan_poison(ws->objectEnd, size);
  514. } else {
  515. assert(ws->initOnceStart >= ws->objectEnd);
  516. __msan_poison(ws->objectEnd, (BYTE*)ws->initOnceStart - (BYTE*)ws->objectEnd);
  517. }
  518. }
  519. #endif
  520. assert(ws->tableValidEnd >= ws->objectEnd);
  521. assert(ws->tableValidEnd <= ws->allocStart);
  522. ws->tableValidEnd = ws->objectEnd;
  523. ZSTD_cwksp_assert_internal_consistency(ws);
  524. }
  525. MEM_STATIC void ZSTD_cwksp_mark_tables_clean(ZSTD_cwksp* ws) {
  526. DEBUGLOG(4, "cwksp: ZSTD_cwksp_mark_tables_clean");
  527. assert(ws->tableValidEnd >= ws->objectEnd);
  528. assert(ws->tableValidEnd <= ws->allocStart);
  529. if (ws->tableValidEnd < ws->tableEnd) {
  530. ws->tableValidEnd = ws->tableEnd;
  531. }
  532. ZSTD_cwksp_assert_internal_consistency(ws);
  533. }
  534. /**
  535. * Zero the part of the allocated tables not already marked clean.
  536. */
  537. MEM_STATIC void ZSTD_cwksp_clean_tables(ZSTD_cwksp* ws) {
  538. DEBUGLOG(4, "cwksp: ZSTD_cwksp_clean_tables");
  539. assert(ws->tableValidEnd >= ws->objectEnd);
  540. assert(ws->tableValidEnd <= ws->allocStart);
  541. if (ws->tableValidEnd < ws->tableEnd) {
  542. ZSTD_memset(ws->tableValidEnd, 0, (size_t)((BYTE*)ws->tableEnd - (BYTE*)ws->tableValidEnd));
  543. }
  544. ZSTD_cwksp_mark_tables_clean(ws);
  545. }
  546. /**
  547. * Invalidates table allocations.
  548. * All other allocations remain valid.
  549. */
  550. MEM_STATIC void ZSTD_cwksp_clear_tables(ZSTD_cwksp* ws)
  551. {
  552. DEBUGLOG(4, "cwksp: clearing tables!");
  553. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  554. /* We don't do this when the workspace is statically allocated, because
  555. * when that is the case, we have no capability to hook into the end of the
  556. * workspace's lifecycle to unpoison the memory.
  557. */
  558. if (ws->isStatic == ZSTD_cwksp_dynamic_alloc) {
  559. size_t size = (BYTE*)ws->tableValidEnd - (BYTE*)ws->objectEnd;
  560. __asan_poison_memory_region(ws->objectEnd, size);
  561. }
  562. #endif
  563. ws->tableEnd = ws->objectEnd;
  564. ZSTD_cwksp_assert_internal_consistency(ws);
  565. }
  566. /**
  567. * Invalidates all buffer, aligned, and table allocations.
  568. * Object allocations remain valid.
  569. */
  570. MEM_STATIC void ZSTD_cwksp_clear(ZSTD_cwksp* ws) {
  571. DEBUGLOG(4, "cwksp: clearing!");
  572. #if ZSTD_MEMORY_SANITIZER && !defined (ZSTD_MSAN_DONT_POISON_WORKSPACE)
  573. /* To validate that the context reuse logic is sound, and that we don't
  574. * access stuff that this compression hasn't initialized, we re-"poison"
  575. * the workspace except for the areas in which we expect memory reuse
  576. * without initialization (objects, valid tables area and init once
  577. * memory). */
  578. {
  579. if((BYTE*)ws->tableValidEnd < (BYTE*)ws->initOnceStart) {
  580. size_t size = (BYTE*)ws->initOnceStart - (BYTE*)ws->tableValidEnd;
  581. __msan_poison(ws->tableValidEnd, size);
  582. }
  583. }
  584. #endif
  585. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  586. /* We don't do this when the workspace is statically allocated, because
  587. * when that is the case, we have no capability to hook into the end of the
  588. * workspace's lifecycle to unpoison the memory.
  589. */
  590. if (ws->isStatic == ZSTD_cwksp_dynamic_alloc) {
  591. size_t size = (BYTE*)ws->workspaceEnd - (BYTE*)ws->objectEnd;
  592. __asan_poison_memory_region(ws->objectEnd, size);
  593. }
  594. #endif
  595. ws->tableEnd = ws->objectEnd;
  596. ws->allocStart = ZSTD_cwksp_initialAllocStart(ws);
  597. ws->allocFailed = 0;
  598. if (ws->phase > ZSTD_cwksp_alloc_aligned_init_once) {
  599. ws->phase = ZSTD_cwksp_alloc_aligned_init_once;
  600. }
  601. ZSTD_cwksp_assert_internal_consistency(ws);
  602. }
  603. MEM_STATIC size_t ZSTD_cwksp_sizeof(const ZSTD_cwksp* ws) {
  604. return (size_t)((BYTE*)ws->workspaceEnd - (BYTE*)ws->workspace);
  605. }
  606. MEM_STATIC size_t ZSTD_cwksp_used(const ZSTD_cwksp* ws) {
  607. return (size_t)((BYTE*)ws->tableEnd - (BYTE*)ws->workspace)
  608. + (size_t)((BYTE*)ws->workspaceEnd - (BYTE*)ws->allocStart);
  609. }
  610. /**
  611. * The provided workspace takes ownership of the buffer [start, start+size).
  612. * Any existing values in the workspace are ignored (the previously managed
  613. * buffer, if present, must be separately freed).
  614. */
  615. MEM_STATIC void ZSTD_cwksp_init(ZSTD_cwksp* ws, void* start, size_t size, ZSTD_cwksp_static_alloc_e isStatic) {
  616. DEBUGLOG(4, "cwksp: init'ing workspace with %zd bytes", size);
  617. assert(((size_t)start & (sizeof(void*)-1)) == 0); /* ensure correct alignment */
  618. ws->workspace = start;
  619. ws->workspaceEnd = (BYTE*)start + size;
  620. ws->objectEnd = ws->workspace;
  621. ws->tableValidEnd = ws->objectEnd;
  622. ws->initOnceStart = ZSTD_cwksp_initialAllocStart(ws);
  623. ws->phase = ZSTD_cwksp_alloc_objects;
  624. ws->isStatic = isStatic;
  625. ZSTD_cwksp_clear(ws);
  626. ws->workspaceOversizedDuration = 0;
  627. ZSTD_cwksp_assert_internal_consistency(ws);
  628. }
  629. MEM_STATIC size_t ZSTD_cwksp_create(ZSTD_cwksp* ws, size_t size, ZSTD_customMem customMem) {
  630. void* workspace = ZSTD_customMalloc(size, customMem);
  631. DEBUGLOG(4, "cwksp: creating new workspace with %zd bytes", size);
  632. RETURN_ERROR_IF(workspace == NULL, memory_allocation, "NULL pointer!");
  633. ZSTD_cwksp_init(ws, workspace, size, ZSTD_cwksp_dynamic_alloc);
  634. return 0;
  635. }
  636. MEM_STATIC void ZSTD_cwksp_free(ZSTD_cwksp* ws, ZSTD_customMem customMem) {
  637. void *ptr = ws->workspace;
  638. DEBUGLOG(4, "cwksp: freeing workspace");
  639. #if ZSTD_MEMORY_SANITIZER && !defined(ZSTD_MSAN_DONT_POISON_WORKSPACE)
  640. if (ptr != NULL && customMem.customFree != NULL) {
  641. __msan_unpoison(ptr, ZSTD_cwksp_sizeof(ws));
  642. }
  643. #endif
  644. ZSTD_memset(ws, 0, sizeof(ZSTD_cwksp));
  645. ZSTD_customFree(ptr, customMem);
  646. }
  647. /**
  648. * Moves the management of a workspace from one cwksp to another. The src cwksp
  649. * is left in an invalid state (src must be re-init()'ed before it's used again).
  650. */
  651. MEM_STATIC void ZSTD_cwksp_move(ZSTD_cwksp* dst, ZSTD_cwksp* src) {
  652. *dst = *src;
  653. ZSTD_memset(src, 0, sizeof(ZSTD_cwksp));
  654. }
  655. MEM_STATIC int ZSTD_cwksp_reserve_failed(const ZSTD_cwksp* ws) {
  656. return ws->allocFailed;
  657. }
  658. /*-*************************************
  659. * Functions Checking Free Space
  660. ***************************************/
  661. /* ZSTD_alignmentSpaceWithinBounds() :
  662. * Returns if the estimated space needed for a wksp is within an acceptable limit of the
  663. * actual amount of space used.
  664. */
  665. MEM_STATIC int ZSTD_cwksp_estimated_space_within_bounds(const ZSTD_cwksp *const ws, size_t const estimatedSpace) {
  666. /* We have an alignment space between objects and tables between tables and buffers, so we can have up to twice
  667. * the alignment bytes difference between estimation and actual usage */
  668. return (estimatedSpace - ZSTD_cwksp_slack_space_required()) <= ZSTD_cwksp_used(ws) &&
  669. ZSTD_cwksp_used(ws) <= estimatedSpace;
  670. }
  671. MEM_STATIC size_t ZSTD_cwksp_available_space(ZSTD_cwksp* ws) {
  672. return (size_t)((BYTE*)ws->allocStart - (BYTE*)ws->tableEnd);
  673. }
  674. MEM_STATIC int ZSTD_cwksp_check_available(ZSTD_cwksp* ws, size_t additionalNeededSpace) {
  675. return ZSTD_cwksp_available_space(ws) >= additionalNeededSpace;
  676. }
  677. MEM_STATIC int ZSTD_cwksp_check_too_large(ZSTD_cwksp* ws, size_t additionalNeededSpace) {
  678. return ZSTD_cwksp_check_available(
  679. ws, additionalNeededSpace * ZSTD_WORKSPACETOOLARGE_FACTOR);
  680. }
  681. MEM_STATIC int ZSTD_cwksp_check_wasteful(ZSTD_cwksp* ws, size_t additionalNeededSpace) {
  682. return ZSTD_cwksp_check_too_large(ws, additionalNeededSpace)
  683. && ws->workspaceOversizedDuration > ZSTD_WORKSPACETOOLARGE_MAXDURATION;
  684. }
  685. MEM_STATIC void ZSTD_cwksp_bump_oversized_duration(
  686. ZSTD_cwksp* ws, size_t additionalNeededSpace) {
  687. if (ZSTD_cwksp_check_too_large(ws, additionalNeededSpace)) {
  688. ws->workspaceOversizedDuration++;
  689. } else {
  690. ws->workspaceOversizedDuration = 0;
  691. }
  692. }
  693. #endif /* ZSTD_CWKSP_H */