1 /**
2 * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
3 * All rights reserved.
4 *
5 * This source code is licensed under the BSD-style license found in the
6 * LICENSE file in the root directory of https://github.com/facebook/zstd.
7 * An additional grant of patent rights can be found in the PATENTS file in the
8 * same directory.
9 *
10 * This program is free software; you can redistribute it and/or modify it under
11 * the terms of the GNU General Public License version 2 as published by the
12 * Free Software Foundation. This program is dual-licensed; you may select
13 * either version 2 of the GNU General Public License ("GPL") or BSD license
14 * ("BSD").
15 */
16
17 /*-*************************************
18 * Dependencies
19 ***************************************/
20 #include "error_private.h"
21 #include "zstd_internal.h" /* declaration of ZSTD_isError, ZSTD_getErrorName, ZSTD_getErrorCode, ZSTD_getErrorString, ZSTD_versionNumber */
22
23 /*=**************************************************************
24 * Custom allocator
25 ****************************************************************/
26
27 #define stack_push(stack, size) \
28 ({ \
29 void *const ptr = ZSTD_PTR_ALIGN((stack)->ptr); \
30 (stack)->ptr = (char *)ptr + (size); \
31 (stack)->ptr <= (stack)->end ? ptr : NULL; \
32 })
33
ZSTD_initStack(void * workspace,size_t workspaceSize)34 ZSTD_customMem __init ZSTD_initStack(void *workspace, size_t workspaceSize)
35 {
36 ZSTD_customMem stackMem = {ZSTD_stackAlloc, ZSTD_stackFree, workspace};
37 ZSTD_stack *stack = (ZSTD_stack *)workspace;
38 /* Verify preconditions */
39 if (!workspace || workspaceSize < sizeof(ZSTD_stack) || workspace != ZSTD_PTR_ALIGN(workspace)) {
40 ZSTD_customMem error = {NULL, NULL, NULL};
41 return error;
42 }
43 /* Initialize the stack */
44 stack->ptr = workspace;
45 stack->end = (char *)workspace + workspaceSize;
46 stack_push(stack, sizeof(ZSTD_stack));
47 return stackMem;
48 }
49
ZSTD_stackAllocAll(void * opaque,size_t * size)50 void *__init ZSTD_stackAllocAll(void *opaque, size_t *size)
51 {
52 ZSTD_stack *stack = (ZSTD_stack *)opaque;
53 *size = (BYTE const *)stack->end - (BYTE *)ZSTD_PTR_ALIGN(stack->ptr);
54 return stack_push(stack, *size);
55 }
56
ZSTD_stackAlloc(void * opaque,size_t size)57 void *__init cf_check ZSTD_stackAlloc(void *opaque, size_t size)
58 {
59 ZSTD_stack *stack = (ZSTD_stack *)opaque;
60 return stack_push(stack, size);
61 }
ZSTD_stackFree(void * opaque,void * address)62 void __init cf_check ZSTD_stackFree(void *opaque, void *address)
63 {
64 (void)opaque;
65 (void)address;
66 }
67
ZSTD_malloc(size_t size,ZSTD_customMem customMem)68 void *__init ZSTD_malloc(size_t size, ZSTD_customMem customMem) { return customMem.customAlloc(customMem.opaque, size); }
69
ZSTD_free(void * ptr,ZSTD_customMem customMem)70 void __init ZSTD_free(void *ptr, ZSTD_customMem customMem)
71 {
72 if (ptr != NULL)
73 customMem.customFree(customMem.opaque, ptr);
74 }
75