zstd_cwksp.h 27 KB

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