1 /* Copyright (c) 2013 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 /* 7 * Helper functions/wrappers for memory allocations, manipulation and 8 * comparison. 9 */ 10 11 #ifndef VBOOT_FIRMWARE_LIB_STATEFUL_UTIL_H_ 12 #define VBOOT_FIRMWARE_LIB_STATEFUL_UTIL_H_ 13 14 #include "sysincludes.h" 15 16 /* Track remaining data to be read in a buffer. */ 17 typedef struct MemcpyState { 18 uint8_t *remaining_buf; 19 uint64_t remaining_len; /* Remaining length of the buffer. */ 20 uint8_t overrun; /* Flag set to 1 when an overrun occurs. */ 21 } MemcpyState; 22 23 /** 24 * Initialize a stateful buffer struct to point to the buffer, with the 25 * specified remaining length in bytes. 26 */ 27 void StatefulInit(MemcpyState *state, void *buf, uint64_t len); 28 29 /** 30 * Skip [len] bytes only if there's enough data to skip according to [state]. 31 * 32 * On success, return a meaningless but non-NULL pointer and updates [state]. 33 * On failure, return NULL, set state->overrun to 1. 34 * 35 * Useful for iterating through a binary blob to populate a struct. After the 36 * first failure (buffer overrun), successive calls will always fail. 37 */ 38 void *StatefulSkip(MemcpyState *state, uint64_t len); 39 40 /** 41 * Copy [len] bytes into [dst] only if there's enough data to read according 42 * to [state]. 43 * 44 * On success, return [dst] and update [state]. 45 * On failure, return NULL, set state->overrun 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 */ 50 void *StatefulMemcpy(MemcpyState *state, void *dst, uint64_t len); 51 52 /** 53 * Like StatefulMemcpy() but copies in the opposite direction, populating 54 * data from [src] into the buffer encapsulated in state [state]. 55 * 56 * On success, return [src] and update [state]. 57 * On failure, return NULL, set state->overrun to 1. 58 * 59 * Useful for iterating through a structure to populate a binary blob. After the 60 * first failure (buffer overrun), successive calls will always fail. 61 */ 62 const void *StatefulMemcpy_r(MemcpyState *state, const void *src, uint64_t len); 63 64 /** 65 * Like StatefulMemcpy_r() but fills a portion of the encapsulated buffer with 66 * a constant value. 67 * 68 * On success, return a meaningless but non-NULL pointer and updates [state]. 69 * On failure, return NULL, set state->overrun to 1. 70 * 71 * After the first failure (buffer overrun), successive calls will always fail. 72 */ 73 const void *StatefulMemset_r(MemcpyState *state, const uint8_t val, 74 uint64_t len); 75 76 #endif 77