1 // SPDX-License-Identifier: (GPL-2.0 or BSD-3-Clause-Clear)
2 /**
3  * Copyright (c) 2016-present, Yann Collet, Facebook, Inc.
4  * All rights reserved.
5  */
6 
7 /*-*************************************
8 *  Dependencies
9 ***************************************/
10 #include "error_private.h"
11 #include "zstd_internal.h" /* declaration of ZSTD_isError, ZSTD_getErrorName, ZSTD_getErrorCode, ZSTD_getErrorString, ZSTD_versionNumber */
12 #include <malloc.h>
13 #include <linux/kernel.h>
14 
15 /*=**************************************************************
16 *  Custom allocator
17 ****************************************************************/
18 
19 #define stack_push(stack, size)                                 \
20 	({                                                      \
21 		void *const ptr = ZSTD_PTR_ALIGN((stack)->ptr); \
22 		(stack)->ptr = (char *)ptr + (size);            \
23 		(stack)->ptr <= (stack)->end ? ptr : NULL;      \
24 	})
25 
ZSTD_initStack(void * workspace,size_t workspaceSize)26 ZSTD_customMem ZSTD_initStack(void *workspace, size_t workspaceSize)
27 {
28 	ZSTD_customMem stackMem = {ZSTD_stackAlloc, ZSTD_stackFree, workspace};
29 	ZSTD_stack *stack = (ZSTD_stack *)workspace;
30 	/* Verify preconditions */
31 	if (!workspace || workspaceSize < sizeof(ZSTD_stack) || workspace != ZSTD_PTR_ALIGN(workspace)) {
32 		ZSTD_customMem error = {NULL, NULL, NULL};
33 		return error;
34 	}
35 	/* Initialize the stack */
36 	stack->ptr = workspace;
37 	stack->end = (char *)workspace + workspaceSize;
38 	stack_push(stack, sizeof(ZSTD_stack));
39 	return stackMem;
40 }
41 
ZSTD_stackAllocAll(void * opaque,size_t * size)42 void *ZSTD_stackAllocAll(void *opaque, size_t *size)
43 {
44 	ZSTD_stack *stack = (ZSTD_stack *)opaque;
45 	*size = (BYTE const *)stack->end - (BYTE *)ZSTD_PTR_ALIGN(stack->ptr);
46 	return stack_push(stack, *size);
47 }
48 
ZSTD_stackAlloc(void * opaque,size_t size)49 void *ZSTD_stackAlloc(void *opaque, size_t size)
50 {
51 	ZSTD_stack *stack = (ZSTD_stack *)opaque;
52 	return stack_push(stack, size);
53 }
ZSTD_stackFree(void * opaque,void * address)54 void ZSTD_stackFree(void *opaque, void *address)
55 {
56 	(void)opaque;
57 	(void)address;
58 }
59 
ZSTD_malloc(size_t size,ZSTD_customMem customMem)60 void *ZSTD_malloc(size_t size, ZSTD_customMem customMem) { return customMem.customAlloc(customMem.opaque, size); }
61 
ZSTD_free(void * ptr,ZSTD_customMem customMem)62 void ZSTD_free(void *ptr, ZSTD_customMem customMem)
63 {
64 	if (ptr != NULL)
65 		customMem.customFree(customMem.opaque, ptr);
66 }
67