blob: 03f6b8dd9f06f9171e111f42f3684e0ecfa15699 [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
11//Generates a random section of the given byte size, saving the result to the given location.
12//Returns the length of the section as passed in.
Lawrence Tange407b4c2022-07-21 13:54:01 +010013size_t generate_random_section(void **location, size_t size)
Lawrence Tang02c801a2022-07-18 14:43:52 +010014{
Lawrence Tange407b4c2022-07-21 13:54:01 +010015 *location = generate_random_bytes(size);
16 return size;
Lawrence Tang02c801a2022-07-18 14:43:52 +010017}
18
19//Generates a random byte allocation of the given size.
Lawrence Tange407b4c2022-07-21 13:54:01 +010020UINT8 *generate_random_bytes(size_t size)
Lawrence Tang02c801a2022-07-18 14:43:52 +010021{
Lawrence Tange407b4c2022-07-21 13:54:01 +010022 UINT8 *bytes = malloc(size);
John Chungf8fc7052024-05-03 20:05:29 +080023 for (size_t i = 0; i < size; i++) {
Lawrence Tange407b4c2022-07-21 13:54:01 +010024 bytes[i] = rand();
John Chungf8fc7052024-05-03 20:05:29 +080025 }
Lawrence Tange407b4c2022-07-21 13:54:01 +010026 return bytes;
Lawrence Tang02c801a2022-07-18 14:43:52 +010027}
28
Lawrence Tangde9707f2022-07-19 10:54:31 +010029//Creates a valid common CPER error section, given the start of the error section.
30//Clears reserved bits.
Lawrence Tange407b4c2022-07-21 13:54:01 +010031void create_valid_error_section(UINT8 *start)
Lawrence Tangde9707f2022-07-19 10:54:31 +010032{
Lawrence Tange407b4c2022-07-21 13:54:01 +010033 //Fix reserved bits.
34 UINT64 *error_section = (UINT64 *)start;
John Chungf8fc7052024-05-03 20:05:29 +080035 *error_section &= ~0xFF; //Reserved bits 0-7.
Lawrence Tange407b4c2022-07-21 13:54:01 +010036 *error_section &= 0x7FFFFF; //Reserved bits 23-63
Lawrence Tangde9707f2022-07-19 10:54:31 +010037
Lawrence Tange407b4c2022-07-21 13:54:01 +010038 //Ensure error type has a valid value.
39 *(start + 1) =
40 CPER_ERROR_TYPES_KEYS[rand() % (sizeof(CPER_ERROR_TYPES_KEYS) /
41 sizeof(int))];
Lawrence Tangde9707f2022-07-19 10:54:31 +010042}
43
Lawrence Tang02c801a2022-07-18 14:43:52 +010044//Initializes the random seed for rand() using the current time.
45void init_random()
46{
Lawrence Tange407b4c2022-07-21 13:54:01 +010047 srand((unsigned int)time(NULL));
John Chungf8fc7052024-05-03 20:05:29 +080048}