blob: b299f7b58412e8ac7e4c6f4fa5b834dbc4907a93 [file] [log] [blame]
Lawrence Tang02c801a2022-07-18 14:43:52 +01001/**
Ed Tanousfedd4572024-07-12 13:56:00 -07002 * Utility functions to assist in generating pseudo-random CPER sections.
3 *
Lawrence Tang02c801a2022-07-18 14:43:52 +01004 * Author: Lawrence.Tang@arm.com
5 **/
6#include <stdlib.h>
7#include <time.h>
Thu Nguyene42fb482024-10-15 14:43:11 +00008#include <libcper/BaseTypes.h>
9#include <libcper/generator/gen-utils.h>
Lawrence Tang02c801a2022-07-18 14:43:52 +010010
Ed Tanous2d4d3b62025-03-11 10:34:29 -070011UINT32 lfsr = 0xACE1u;
12
13void cper_rand_seed(UINT32 seed)
14{
15 lfsr = seed;
16}
17
18UINT32 cper_rand()
19{
20 lfsr |= lfsr == 0; // if x == 0, set x = 1 instead
21 lfsr ^= (lfsr & 0x0007ffff) << 13;
22 lfsr ^= lfsr >> 17;
23 lfsr ^= (lfsr & 0x07ffffff) << 5;
24 return lfsr;
25}
26
Lawrence Tang02c801a2022-07-18 14:43:52 +010027//Generates a random section of the given byte size, saving the result to the given location.
28//Returns the length of the section as passed in.
Lawrence Tange407b4c2022-07-21 13:54:01 +010029size_t generate_random_section(void **location, size_t size)
Lawrence Tang02c801a2022-07-18 14:43:52 +010030{
Lawrence Tange407b4c2022-07-21 13:54:01 +010031 *location = generate_random_bytes(size);
32 return size;
Lawrence Tang02c801a2022-07-18 14:43:52 +010033}
34
35//Generates a random byte allocation of the given size.
Lawrence Tange407b4c2022-07-21 13:54:01 +010036UINT8 *generate_random_bytes(size_t size)
Lawrence Tang02c801a2022-07-18 14:43:52 +010037{
Lawrence Tange407b4c2022-07-21 13:54:01 +010038 UINT8 *bytes = malloc(size);
John Chungf8fc7052024-05-03 20:05:29 +080039 for (size_t i = 0; i < size; i++) {
Ed Tanous2d4d3b62025-03-11 10:34:29 -070040 bytes[i] = cper_rand();
John Chungf8fc7052024-05-03 20:05:29 +080041 }
Lawrence Tange407b4c2022-07-21 13:54:01 +010042 return bytes;
Lawrence Tang02c801a2022-07-18 14:43:52 +010043}
44
Lawrence Tangde9707f2022-07-19 10:54:31 +010045//Creates a valid common CPER error section, given the start of the error section.
46//Clears reserved bits.
Lawrence Tange407b4c2022-07-21 13:54:01 +010047void create_valid_error_section(UINT8 *start)
Lawrence Tangde9707f2022-07-19 10:54:31 +010048{
Lawrence Tange407b4c2022-07-21 13:54:01 +010049 //Fix reserved bits.
50 UINT64 *error_section = (UINT64 *)start;
John Chungf8fc7052024-05-03 20:05:29 +080051 *error_section &= ~0xFF; //Reserved bits 0-7.
Lawrence Tange407b4c2022-07-21 13:54:01 +010052 *error_section &= 0x7FFFFF; //Reserved bits 23-63
Lawrence Tangde9707f2022-07-19 10:54:31 +010053
Lawrence Tange407b4c2022-07-21 13:54:01 +010054 //Ensure error type has a valid value.
Ed Tanous2d4d3b62025-03-11 10:34:29 -070055 *(start + 1) = CPER_ERROR_TYPES_KEYS[cper_rand() %
56 (sizeof(CPER_ERROR_TYPES_KEYS) /
57 sizeof(int))];
John Chungf8fc7052024-05-03 20:05:29 +080058}