zstd_cwksp.h 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  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. (void)offset;
  181. #if defined(ZSTD_MSAN_PRINT)
  182. if(offset!=-1) {
  183. __msan_print_shadow((U8*)ws->initOnceStart + offset - 8, 32);
  184. }
  185. #endif
  186. assert(offset==-1);
  187. };
  188. #endif
  189. }
  190. /**
  191. * Align must be a power of 2.
  192. */
  193. MEM_STATIC size_t ZSTD_cwksp_align(size_t size, size_t const align) {
  194. size_t const mask = align - 1;
  195. assert((align & mask) == 0);
  196. return (size + mask) & ~mask;
  197. }
  198. /**
  199. * Use this to determine how much space in the workspace we will consume to
  200. * allocate this object. (Normally it should be exactly the size of the object,
  201. * but under special conditions, like ASAN, where we pad each object, it might
  202. * be larger.)
  203. *
  204. * Since tables aren't currently redzoned, you don't need to call through this
  205. * to figure out how much space you need for the matchState tables. Everything
  206. * else is though.
  207. *
  208. * Do not use for sizing aligned buffers. Instead, use ZSTD_cwksp_aligned_alloc_size().
  209. */
  210. MEM_STATIC size_t ZSTD_cwksp_alloc_size(size_t size) {
  211. if (size == 0)
  212. return 0;
  213. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  214. return size + 2 * ZSTD_CWKSP_ASAN_REDZONE_SIZE;
  215. #else
  216. return size;
  217. #endif
  218. }
  219. /**
  220. * Returns an adjusted alloc size that is the nearest larger multiple of 64 bytes.
  221. * Used to determine the number of bytes required for a given "aligned".
  222. */
  223. MEM_STATIC size_t ZSTD_cwksp_aligned_alloc_size(size_t size) {
  224. return ZSTD_cwksp_alloc_size(ZSTD_cwksp_align(size, ZSTD_CWKSP_ALIGNMENT_BYTES));
  225. }
  226. /**
  227. * Returns the amount of additional space the cwksp must allocate
  228. * for internal purposes (currently only alignment).
  229. */
  230. MEM_STATIC size_t ZSTD_cwksp_slack_space_required(void) {
  231. /* For alignment, the wksp will always allocate an additional 2*ZSTD_CWKSP_ALIGNMENT_BYTES
  232. * bytes to align the beginning of tables section and end of buffers;
  233. */
  234. size_t const slackSpace = ZSTD_CWKSP_ALIGNMENT_BYTES * 2;
  235. return slackSpace;
  236. }
  237. /**
  238. * Return the number of additional bytes required to align a pointer to the given number of bytes.
  239. * alignBytes must be a power of two.
  240. */
  241. MEM_STATIC size_t ZSTD_cwksp_bytes_to_align_ptr(void* ptr, const size_t alignBytes) {
  242. size_t const alignBytesMask = alignBytes - 1;
  243. size_t const bytes = (alignBytes - ((size_t)ptr & (alignBytesMask))) & alignBytesMask;
  244. assert((alignBytes & alignBytesMask) == 0);
  245. assert(bytes < alignBytes);
  246. return bytes;
  247. }
  248. /**
  249. * Returns the initial value for allocStart which is used to determine the position from
  250. * which we can allocate from the end of the workspace.
  251. */
  252. MEM_STATIC void* ZSTD_cwksp_initialAllocStart(ZSTD_cwksp* ws) {
  253. return (void*)((size_t)ws->workspaceEnd & ~(ZSTD_CWKSP_ALIGNMENT_BYTES-1));
  254. }
  255. /**
  256. * Internal function. Do not use directly.
  257. * Reserves the given number of bytes within the aligned/buffer segment of the wksp,
  258. * which counts from the end of the wksp (as opposed to the object/table segment).
  259. *
  260. * Returns a pointer to the beginning of that space.
  261. */
  262. MEM_STATIC void*
  263. ZSTD_cwksp_reserve_internal_buffer_space(ZSTD_cwksp* ws, size_t const bytes)
  264. {
  265. void* const alloc = (BYTE*)ws->allocStart - bytes;
  266. void* const bottom = ws->tableEnd;
  267. DEBUGLOG(5, "cwksp: reserving %p %zd bytes, %zd bytes remaining",
  268. alloc, bytes, ZSTD_cwksp_available_space(ws) - bytes);
  269. ZSTD_cwksp_assert_internal_consistency(ws);
  270. assert(alloc >= bottom);
  271. if (alloc < bottom) {
  272. DEBUGLOG(4, "cwksp: alloc failed!");
  273. ws->allocFailed = 1;
  274. return NULL;
  275. }
  276. /* the area is reserved from the end of wksp.
  277. * If it overlaps with tableValidEnd, it voids guarantees on values' range */
  278. if (alloc < ws->tableValidEnd) {
  279. ws->tableValidEnd = alloc;
  280. }
  281. ws->allocStart = alloc;
  282. return alloc;
  283. }
  284. /**
  285. * Moves the cwksp to the next phase, and does any necessary allocations.
  286. * cwksp initialization must necessarily go through each phase in order.
  287. * Returns a 0 on success, or zstd error
  288. */
  289. MEM_STATIC size_t
  290. ZSTD_cwksp_internal_advance_phase(ZSTD_cwksp* ws, ZSTD_cwksp_alloc_phase_e phase)
  291. {
  292. assert(phase >= ws->phase);
  293. if (phase > ws->phase) {
  294. /* Going from allocating objects to allocating initOnce / tables */
  295. if (ws->phase < ZSTD_cwksp_alloc_aligned_init_once &&
  296. phase >= ZSTD_cwksp_alloc_aligned_init_once) {
  297. ws->tableValidEnd = ws->objectEnd;
  298. ws->initOnceStart = ZSTD_cwksp_initialAllocStart(ws);
  299. { /* Align the start of the tables to 64 bytes. Use [0, 63] bytes */
  300. void *const alloc = ws->objectEnd;
  301. size_t const bytesToAlign = ZSTD_cwksp_bytes_to_align_ptr(alloc, ZSTD_CWKSP_ALIGNMENT_BYTES);
  302. void *const objectEnd = (BYTE *) alloc + bytesToAlign;
  303. DEBUGLOG(5, "reserving table alignment addtl space: %zu", bytesToAlign);
  304. RETURN_ERROR_IF(objectEnd > ws->workspaceEnd, memory_allocation,
  305. "table phase - alignment initial allocation failed!");
  306. ws->objectEnd = objectEnd;
  307. ws->tableEnd = objectEnd; /* table area starts being empty */
  308. if (ws->tableValidEnd < ws->tableEnd) {
  309. ws->tableValidEnd = ws->tableEnd;
  310. }
  311. }
  312. }
  313. ws->phase = phase;
  314. ZSTD_cwksp_assert_internal_consistency(ws);
  315. }
  316. return 0;
  317. }
  318. /**
  319. * Returns whether this object/buffer/etc was allocated in this workspace.
  320. */
  321. MEM_STATIC int ZSTD_cwksp_owns_buffer(const ZSTD_cwksp* ws, const void* ptr)
  322. {
  323. return (ptr != NULL) && (ws->workspace <= ptr) && (ptr < ws->workspaceEnd);
  324. }
  325. /**
  326. * Internal function. Do not use directly.
  327. */
  328. MEM_STATIC void*
  329. ZSTD_cwksp_reserve_internal(ZSTD_cwksp* ws, size_t bytes, ZSTD_cwksp_alloc_phase_e phase)
  330. {
  331. void* alloc;
  332. if (ZSTD_isError(ZSTD_cwksp_internal_advance_phase(ws, phase)) || bytes == 0) {
  333. return NULL;
  334. }
  335. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  336. /* over-reserve space */
  337. bytes += 2 * ZSTD_CWKSP_ASAN_REDZONE_SIZE;
  338. #endif
  339. alloc = ZSTD_cwksp_reserve_internal_buffer_space(ws, bytes);
  340. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  341. /* Move alloc so there's ZSTD_CWKSP_ASAN_REDZONE_SIZE unused space on
  342. * either size. */
  343. if (alloc) {
  344. alloc = (BYTE *)alloc + ZSTD_CWKSP_ASAN_REDZONE_SIZE;
  345. if (ws->isStatic == ZSTD_cwksp_dynamic_alloc) {
  346. /* We need to keep the redzone poisoned while unpoisoning the bytes that
  347. * are actually allocated. */
  348. __asan_unpoison_memory_region(alloc, bytes - 2 * ZSTD_CWKSP_ASAN_REDZONE_SIZE);
  349. }
  350. }
  351. #endif
  352. return alloc;
  353. }
  354. /**
  355. * Reserves and returns unaligned memory.
  356. */
  357. MEM_STATIC BYTE* ZSTD_cwksp_reserve_buffer(ZSTD_cwksp* ws, size_t bytes)
  358. {
  359. return (BYTE*)ZSTD_cwksp_reserve_internal(ws, bytes, ZSTD_cwksp_alloc_buffers);
  360. }
  361. /**
  362. * Reserves and returns memory sized on and aligned on ZSTD_CWKSP_ALIGNMENT_BYTES (64 bytes).
  363. * This memory has been initialized at least once in the past.
  364. * This doesn't mean it has been initialized this time, and it might contain data from previous
  365. * operations.
  366. * The main usage is for algorithms that might need read access into uninitialized memory.
  367. * The algorithm must maintain safety under these conditions and must make sure it doesn't
  368. * leak any of the past data (directly or in side channels).
  369. */
  370. MEM_STATIC void* ZSTD_cwksp_reserve_aligned_init_once(ZSTD_cwksp* ws, size_t bytes)
  371. {
  372. size_t const alignedBytes = ZSTD_cwksp_align(bytes, ZSTD_CWKSP_ALIGNMENT_BYTES);
  373. void* ptr = ZSTD_cwksp_reserve_internal(ws, alignedBytes, ZSTD_cwksp_alloc_aligned_init_once);
  374. assert(((size_t)ptr & (ZSTD_CWKSP_ALIGNMENT_BYTES-1))== 0);
  375. if(ptr && ptr < ws->initOnceStart) {
  376. /* We assume the memory following the current allocation is either:
  377. * 1. Not usable as initOnce memory (end of workspace)
  378. * 2. Another initOnce buffer that has been allocated before (and so was previously memset)
  379. * 3. An ASAN redzone, in which case we don't want to write on it
  380. * For these reasons it should be fine to not explicitly zero every byte up to ws->initOnceStart.
  381. * Note that we assume here that MSAN and ASAN cannot run in the same time. */
  382. ZSTD_memset(ptr, 0, MIN((size_t)((U8*)ws->initOnceStart - (U8*)ptr), alignedBytes));
  383. ws->initOnceStart = ptr;
  384. }
  385. #if ZSTD_MEMORY_SANITIZER
  386. assert(__msan_test_shadow(ptr, bytes) == -1);
  387. #endif
  388. return ptr;
  389. }
  390. /**
  391. * Reserves and returns memory sized on and aligned on ZSTD_CWKSP_ALIGNMENT_BYTES (64 bytes).
  392. */
  393. MEM_STATIC void* ZSTD_cwksp_reserve_aligned(ZSTD_cwksp* ws, size_t bytes)
  394. {
  395. void* ptr = ZSTD_cwksp_reserve_internal(ws, ZSTD_cwksp_align(bytes, ZSTD_CWKSP_ALIGNMENT_BYTES),
  396. ZSTD_cwksp_alloc_aligned);
  397. assert(((size_t)ptr & (ZSTD_CWKSP_ALIGNMENT_BYTES-1))== 0);
  398. return ptr;
  399. }
  400. /**
  401. * Aligned on 64 bytes. These buffers have the special property that
  402. * their values remain constrained, allowing us to reuse them without
  403. * memset()-ing them.
  404. */
  405. MEM_STATIC void* ZSTD_cwksp_reserve_table(ZSTD_cwksp* ws, size_t bytes)
  406. {
  407. const ZSTD_cwksp_alloc_phase_e phase = ZSTD_cwksp_alloc_aligned_init_once;
  408. void* alloc;
  409. void* end;
  410. void* top;
  411. /* We can only start allocating tables after we are done reserving space for objects at the
  412. * start of the workspace */
  413. if(ws->phase < phase) {
  414. if (ZSTD_isError(ZSTD_cwksp_internal_advance_phase(ws, phase))) {
  415. return NULL;
  416. }
  417. }
  418. alloc = ws->tableEnd;
  419. end = (BYTE *)alloc + bytes;
  420. top = ws->allocStart;
  421. DEBUGLOG(5, "cwksp: reserving %p table %zd bytes, %zd bytes remaining",
  422. alloc, bytes, ZSTD_cwksp_available_space(ws) - bytes);
  423. assert((bytes & (sizeof(U32)-1)) == 0);
  424. ZSTD_cwksp_assert_internal_consistency(ws);
  425. assert(end <= top);
  426. if (end > top) {
  427. DEBUGLOG(4, "cwksp: table alloc failed!");
  428. ws->allocFailed = 1;
  429. return NULL;
  430. }
  431. ws->tableEnd = end;
  432. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  433. if (ws->isStatic == ZSTD_cwksp_dynamic_alloc) {
  434. __asan_unpoison_memory_region(alloc, bytes);
  435. }
  436. #endif
  437. assert((bytes & (ZSTD_CWKSP_ALIGNMENT_BYTES-1)) == 0);
  438. assert(((size_t)alloc & (ZSTD_CWKSP_ALIGNMENT_BYTES-1))== 0);
  439. return alloc;
  440. }
  441. /**
  442. * Aligned on sizeof(void*).
  443. * Note : should happen only once, at workspace first initialization
  444. */
  445. MEM_STATIC void* ZSTD_cwksp_reserve_object(ZSTD_cwksp* ws, size_t bytes)
  446. {
  447. size_t const roundedBytes = ZSTD_cwksp_align(bytes, sizeof(void*));
  448. void* alloc = ws->objectEnd;
  449. void* end = (BYTE*)alloc + roundedBytes;
  450. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  451. /* over-reserve space */
  452. end = (BYTE *)end + 2 * ZSTD_CWKSP_ASAN_REDZONE_SIZE;
  453. #endif
  454. DEBUGLOG(4,
  455. "cwksp: reserving %p object %zd bytes (rounded to %zd), %zd bytes remaining",
  456. alloc, bytes, roundedBytes, ZSTD_cwksp_available_space(ws) - roundedBytes);
  457. assert((size_t)alloc % ZSTD_ALIGNOF(void*) == 0);
  458. assert(bytes % ZSTD_ALIGNOF(void*) == 0);
  459. ZSTD_cwksp_assert_internal_consistency(ws);
  460. /* we must be in the first phase, no advance is possible */
  461. if (ws->phase != ZSTD_cwksp_alloc_objects || end > ws->workspaceEnd) {
  462. DEBUGLOG(3, "cwksp: object alloc failed!");
  463. ws->allocFailed = 1;
  464. return NULL;
  465. }
  466. ws->objectEnd = end;
  467. ws->tableEnd = end;
  468. ws->tableValidEnd = end;
  469. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  470. /* Move alloc so there's ZSTD_CWKSP_ASAN_REDZONE_SIZE unused space on
  471. * either size. */
  472. alloc = (BYTE*)alloc + ZSTD_CWKSP_ASAN_REDZONE_SIZE;
  473. if (ws->isStatic == ZSTD_cwksp_dynamic_alloc) {
  474. __asan_unpoison_memory_region(alloc, bytes);
  475. }
  476. #endif
  477. return alloc;
  478. }
  479. MEM_STATIC void ZSTD_cwksp_mark_tables_dirty(ZSTD_cwksp* ws)
  480. {
  481. DEBUGLOG(4, "cwksp: ZSTD_cwksp_mark_tables_dirty");
  482. #if ZSTD_MEMORY_SANITIZER && !defined (ZSTD_MSAN_DONT_POISON_WORKSPACE)
  483. /* To validate that the table reuse logic is sound, and that we don't
  484. * access table space that we haven't cleaned, we re-"poison" the table
  485. * space every time we mark it dirty.
  486. * Since tableValidEnd space and initOnce space may overlap we don't poison
  487. * the initOnce portion as it break its promise. This means that this poisoning
  488. * check isn't always applied fully. */
  489. {
  490. size_t size = (BYTE*)ws->tableValidEnd - (BYTE*)ws->objectEnd;
  491. assert(__msan_test_shadow(ws->objectEnd, size) == -1);
  492. if((BYTE*)ws->tableValidEnd < (BYTE*)ws->initOnceStart) {
  493. __msan_poison(ws->objectEnd, size);
  494. } else {
  495. assert(ws->initOnceStart >= ws->objectEnd);
  496. __msan_poison(ws->objectEnd, (BYTE*)ws->initOnceStart - (BYTE*)ws->objectEnd);
  497. }
  498. }
  499. #endif
  500. assert(ws->tableValidEnd >= ws->objectEnd);
  501. assert(ws->tableValidEnd <= ws->allocStart);
  502. ws->tableValidEnd = ws->objectEnd;
  503. ZSTD_cwksp_assert_internal_consistency(ws);
  504. }
  505. MEM_STATIC void ZSTD_cwksp_mark_tables_clean(ZSTD_cwksp* ws) {
  506. DEBUGLOG(4, "cwksp: ZSTD_cwksp_mark_tables_clean");
  507. assert(ws->tableValidEnd >= ws->objectEnd);
  508. assert(ws->tableValidEnd <= ws->allocStart);
  509. if (ws->tableValidEnd < ws->tableEnd) {
  510. ws->tableValidEnd = ws->tableEnd;
  511. }
  512. ZSTD_cwksp_assert_internal_consistency(ws);
  513. }
  514. /**
  515. * Zero the part of the allocated tables not already marked clean.
  516. */
  517. MEM_STATIC void ZSTD_cwksp_clean_tables(ZSTD_cwksp* ws) {
  518. DEBUGLOG(4, "cwksp: ZSTD_cwksp_clean_tables");
  519. assert(ws->tableValidEnd >= ws->objectEnd);
  520. assert(ws->tableValidEnd <= ws->allocStart);
  521. if (ws->tableValidEnd < ws->tableEnd) {
  522. ZSTD_memset(ws->tableValidEnd, 0, (size_t)((BYTE*)ws->tableEnd - (BYTE*)ws->tableValidEnd));
  523. }
  524. ZSTD_cwksp_mark_tables_clean(ws);
  525. }
  526. /**
  527. * Invalidates table allocations.
  528. * All other allocations remain valid.
  529. */
  530. MEM_STATIC void ZSTD_cwksp_clear_tables(ZSTD_cwksp* ws) {
  531. DEBUGLOG(4, "cwksp: clearing tables!");
  532. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  533. /* We don't do this when the workspace is statically allocated, because
  534. * when that is the case, we have no capability to hook into the end of the
  535. * workspace's lifecycle to unpoison the memory.
  536. */
  537. if (ws->isStatic == ZSTD_cwksp_dynamic_alloc) {
  538. size_t size = (BYTE*)ws->tableValidEnd - (BYTE*)ws->objectEnd;
  539. __asan_poison_memory_region(ws->objectEnd, size);
  540. }
  541. #endif
  542. ws->tableEnd = ws->objectEnd;
  543. ZSTD_cwksp_assert_internal_consistency(ws);
  544. }
  545. /**
  546. * Invalidates all buffer, aligned, and table allocations.
  547. * Object allocations remain valid.
  548. */
  549. MEM_STATIC void ZSTD_cwksp_clear(ZSTD_cwksp* ws) {
  550. DEBUGLOG(4, "cwksp: clearing!");
  551. #if ZSTD_MEMORY_SANITIZER && !defined (ZSTD_MSAN_DONT_POISON_WORKSPACE)
  552. /* To validate that the context reuse logic is sound, and that we don't
  553. * access stuff that this compression hasn't initialized, we re-"poison"
  554. * the workspace except for the areas in which we expect memory reuse
  555. * without initialization (objects, valid tables area and init once
  556. * memory). */
  557. {
  558. if((BYTE*)ws->tableValidEnd < (BYTE*)ws->initOnceStart) {
  559. size_t size = (BYTE*)ws->initOnceStart - (BYTE*)ws->tableValidEnd;
  560. __msan_poison(ws->tableValidEnd, size);
  561. }
  562. }
  563. #endif
  564. #if ZSTD_ADDRESS_SANITIZER && !defined (ZSTD_ASAN_DONT_POISON_WORKSPACE)
  565. /* We don't do this when the workspace is statically allocated, because
  566. * when that is the case, we have no capability to hook into the end of the
  567. * workspace's lifecycle to unpoison the memory.
  568. */
  569. if (ws->isStatic == ZSTD_cwksp_dynamic_alloc) {
  570. size_t size = (BYTE*)ws->workspaceEnd - (BYTE*)ws->objectEnd;
  571. __asan_poison_memory_region(ws->objectEnd, size);
  572. }
  573. #endif
  574. ws->tableEnd = ws->objectEnd;
  575. ws->allocStart = ZSTD_cwksp_initialAllocStart(ws);
  576. ws->allocFailed = 0;
  577. if (ws->phase > ZSTD_cwksp_alloc_aligned_init_once) {
  578. ws->phase = ZSTD_cwksp_alloc_aligned_init_once;
  579. }
  580. ZSTD_cwksp_assert_internal_consistency(ws);
  581. }
  582. MEM_STATIC size_t ZSTD_cwksp_sizeof(const ZSTD_cwksp* ws) {
  583. return (size_t)((BYTE*)ws->workspaceEnd - (BYTE*)ws->workspace);
  584. }
  585. MEM_STATIC size_t ZSTD_cwksp_used(const ZSTD_cwksp* ws) {
  586. return (size_t)((BYTE*)ws->tableEnd - (BYTE*)ws->workspace)
  587. + (size_t)((BYTE*)ws->workspaceEnd - (BYTE*)ws->allocStart);
  588. }
  589. /**
  590. * The provided workspace takes ownership of the buffer [start, start+size).
  591. * Any existing values in the workspace are ignored (the previously managed
  592. * buffer, if present, must be separately freed).
  593. */
  594. MEM_STATIC void ZSTD_cwksp_init(ZSTD_cwksp* ws, void* start, size_t size, ZSTD_cwksp_static_alloc_e isStatic) {
  595. DEBUGLOG(4, "cwksp: init'ing workspace with %zd bytes", size);
  596. assert(((size_t)start & (sizeof(void*)-1)) == 0); /* ensure correct alignment */
  597. ws->workspace = start;
  598. ws->workspaceEnd = (BYTE*)start + size;
  599. ws->objectEnd = ws->workspace;
  600. ws->tableValidEnd = ws->objectEnd;
  601. ws->initOnceStart = ZSTD_cwksp_initialAllocStart(ws);
  602. ws->phase = ZSTD_cwksp_alloc_objects;
  603. ws->isStatic = isStatic;
  604. ZSTD_cwksp_clear(ws);
  605. ws->workspaceOversizedDuration = 0;
  606. ZSTD_cwksp_assert_internal_consistency(ws);
  607. }
  608. MEM_STATIC size_t ZSTD_cwksp_create(ZSTD_cwksp* ws, size_t size, ZSTD_customMem customMem) {
  609. void* workspace = ZSTD_customMalloc(size, customMem);
  610. DEBUGLOG(4, "cwksp: creating new workspace with %zd bytes", size);
  611. RETURN_ERROR_IF(workspace == NULL, memory_allocation, "NULL pointer!");
  612. ZSTD_cwksp_init(ws, workspace, size, ZSTD_cwksp_dynamic_alloc);
  613. return 0;
  614. }
  615. MEM_STATIC void ZSTD_cwksp_free(ZSTD_cwksp* ws, ZSTD_customMem customMem) {
  616. void *ptr = ws->workspace;
  617. DEBUGLOG(4, "cwksp: freeing workspace");
  618. #if ZSTD_MEMORY_SANITIZER && !defined(ZSTD_MSAN_DONT_POISON_WORKSPACE)
  619. if (ptr != NULL && customMem.customFree != NULL) {
  620. __msan_unpoison(ptr, ZSTD_cwksp_sizeof(ws));
  621. }
  622. #endif
  623. ZSTD_memset(ws, 0, sizeof(ZSTD_cwksp));
  624. ZSTD_customFree(ptr, customMem);
  625. }
  626. /**
  627. * Moves the management of a workspace from one cwksp to another. The src cwksp
  628. * is left in an invalid state (src must be re-init()'ed before it's used again).
  629. */
  630. MEM_STATIC void ZSTD_cwksp_move(ZSTD_cwksp* dst, ZSTD_cwksp* src) {
  631. *dst = *src;
  632. ZSTD_memset(src, 0, sizeof(ZSTD_cwksp));
  633. }
  634. MEM_STATIC int ZSTD_cwksp_reserve_failed(const ZSTD_cwksp* ws) {
  635. return ws->allocFailed;
  636. }
  637. /*-*************************************
  638. * Functions Checking Free Space
  639. ***************************************/
  640. /* ZSTD_alignmentSpaceWithinBounds() :
  641. * Returns if the estimated space needed for a wksp is within an acceptable limit of the
  642. * actual amount of space used.
  643. */
  644. MEM_STATIC int ZSTD_cwksp_estimated_space_within_bounds(const ZSTD_cwksp *const ws, size_t const estimatedSpace) {
  645. /* We have an alignment space between objects and tables between tables and buffers, so we can have up to twice
  646. * the alignment bytes difference between estimation and actual usage */
  647. return (estimatedSpace - ZSTD_cwksp_slack_space_required()) <= ZSTD_cwksp_used(ws) &&
  648. ZSTD_cwksp_used(ws) <= estimatedSpace;
  649. }
  650. MEM_STATIC size_t ZSTD_cwksp_available_space(ZSTD_cwksp* ws) {
  651. return (size_t)((BYTE*)ws->allocStart - (BYTE*)ws->tableEnd);
  652. }
  653. MEM_STATIC int ZSTD_cwksp_check_available(ZSTD_cwksp* ws, size_t additionalNeededSpace) {
  654. return ZSTD_cwksp_available_space(ws) >= additionalNeededSpace;
  655. }
  656. MEM_STATIC int ZSTD_cwksp_check_too_large(ZSTD_cwksp* ws, size_t additionalNeededSpace) {
  657. return ZSTD_cwksp_check_available(
  658. ws, additionalNeededSpace * ZSTD_WORKSPACETOOLARGE_FACTOR);
  659. }
  660. MEM_STATIC int ZSTD_cwksp_check_wasteful(ZSTD_cwksp* ws, size_t additionalNeededSpace) {
  661. return ZSTD_cwksp_check_too_large(ws, additionalNeededSpace)
  662. && ws->workspaceOversizedDuration > ZSTD_WORKSPACETOOLARGE_MAXDURATION;
  663. }
  664. MEM_STATIC void ZSTD_cwksp_bump_oversized_duration(
  665. ZSTD_cwksp* ws, size_t additionalNeededSpace) {
  666. if (ZSTD_cwksp_check_too_large(ws, additionalNeededSpace)) {
  667. ws->workspaceOversizedDuration++;
  668. } else {
  669. ws->workspaceOversizedDuration = 0;
  670. }
  671. }
  672. #if defined (__cplusplus)
  673. }
  674. #endif
  675. #endif /* ZSTD_CWKSP_H */