blob: b26e2477907e351e1ef99ea97efb7d1101bd9e34 [file] [log] [blame]
Gaurav Shah322536d2010-01-28 15:01:23 -08001/* Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
2 * Use of this source code is governed by a BSD-style license that can be
3 * found in the LICENSE file.
4 */
5
6/* Helper functions/wrappers for memory allocations, manipulation and
7 * comparison.
8 */
9
10#ifndef VBOOT_REFERENCE_UTILITY_H_
11#define VBOOT_REFERENCE_UTILITY_H_
12
Gaurav Shahd0677122010-02-04 19:35:03 -080013#include <inttypes.h>
Gaurav Shah322536d2010-01-28 15:01:23 -080014#include <string.h>
15
16/* Allocate [size] bytes and return a pointer to the allocated memory. Abort
17 * on error.
18 */
19void* Malloc(size_t size);
20
21/* Free memory pointed by [ptr] previously allocated by Malloc(). */
22void Free(void* ptr);
23
24/* Copy [n] bytes from [src] to [dest]. */
25void* Memcpy(void* dest, const void* src, size_t n);
26
Gaurav Shahd0677122010-02-04 19:35:03 -080027/* Set [n] bytes starting at [s] to [c]. */
28void* Memset(void *dest, const uint8_t c, size_t n);
29
Gaurav Shah08df9b82010-02-23 16:16:23 -080030/* Compare [n] bytes starting at [s1] with [s2] and return 0 if they match,
31 * 1 if they don't. Time taken to perform the comparison is only dependent on
Gaurav Shah322536d2010-01-28 15:01:23 -080032 * [n] and not on the relationship of the match between [s1] and [s2].
33 */
34int SafeMemcmp(const void* s1, const void* s2, size_t n);
35
Gaurav Shahd0677122010-02-04 19:35:03 -080036/* Track remaining data to be read in a buffer. */
37typedef struct MemcpyState {
38 void* remaining_buf;
39 int remaining_len;
40} MemcpyState;
41
42/* Copy [len] bytes into [dst] only if there's enough data to read according
43 * to [state].
Gaurav Shahf5564fa2010-03-02 15:40:01 -080044 * On success, return [dst] and update [state].
Gaurav Shahd0677122010-02-04 19:35:03 -080045 * On failure, return NULL, set remaining len in state to -1.
46 *
47 * Useful for iterating through a binary blob to populate a struct. After the
48 * first failure (buffer overrun), successive calls will always fail.
49 */
50void* StatefulMemcpy(MemcpyState* state, void* dst, int len);
51
Gaurav Shahf5564fa2010-03-02 15:40:01 -080052/* Like StatefulMemcpy() but copies in the opposite direction, populating
53 * data from [src] into the buffer encapsulated in state [state].
54 * On success, return [src] and update [state].
55 * On failure, return NULL, set remaining_len in state to -1.
56 *
57 * Useful for iterating through a structure to populate a binary blob. After the
58 * first failure (buffer overrun), successive calls will always fail.
59 */
60const void* StatefulMemcpy_r(MemcpyState* state, const void* src, int len);
Gaurav Shahd0677122010-02-04 19:35:03 -080061
Gaurav Shah322536d2010-01-28 15:01:23 -080062#endif /* VBOOT_REFERENCE_UTILITY_H_ */