blob: ca885fcce86dd30880423ac85ae92fac9108d7de [file] [log] [blame]
Lawrence Tangd34f2b12022-07-19 15:36:31 +01001/**
2 * Defines utility functions for testing CPER-JSON IR output from the cper-parse library.
Ed Tanousfedd4572024-07-12 13:56:00 -07003 *
Lawrence Tangd34f2b12022-07-19 15:36:31 +01004 * Author: Lawrence.Tang@arm.com
5 **/
6
John Chungf8fc7052024-05-03 20:05:29 +08007#include <cstdio>
8#include <cstdlib>
Aushim Nagarkattiae8f6d92025-01-29 17:34:44 -08009#include <fstream>
10#include <filesystem>
Lawrence Tangd34f2b12022-07-19 15:36:31 +010011#include "test-utils.hpp"
Karthik Rajagopalan255bd812024-09-06 14:36:34 -070012
Thu Nguyene42fb482024-10-15 14:43:11 +000013#include <libcper/BaseTypes.h>
14#include <libcper/generator/cper-generate.h>
Lawrence Tangd34f2b12022-07-19 15:36:31 +010015
Aushim Nagarkattiae8f6d92025-01-29 17:34:44 -080016namespace fs = std::filesystem;
17
Ed Tanous2c4d7b62025-03-16 12:22:02 -070018// Objects that have mutually exclusive fields (and thereforce can't have both
19// required at the same time) can be added to this list.
Aushim Nagarkattiae8f6d92025-01-29 17:34:44 -080020// Truly optional properties that shouldn't be added to "required" field for
21// validating the entire schema with validationbits=1
22const static std::map<std::string, std::vector<std::string> >
23 optional_properties_map = {
Aushim Nagarkattiae8f6d92025-01-29 17:34:44 -080024 { "./sections/cper-cxl-protocol.json",
25 { "capabilityStructure", "deviceSerial" } },
Aushim Nagarkattiae8f6d92025-01-29 17:34:44 -080026 { "./sections/cper-cxl-component.json",
27 { "cxlComponentEventLog" } },
Ed Tanousd6b62632025-03-14 15:30:07 -070028 { "./sections/cper-ia32x64-processor.json",
29 { "addressSpace", "errorType", "participationType",
30 "timedOut", "level", "operation", "preciseIP",
31 "restartableIP", "overflow", "uncorrected",
32 "transactionType" } },
Aushim Nagarkattiae8f6d92025-01-29 17:34:44 -080033 };
34
35nlohmann::json loadJson(const char *filePath)
36{
37 std::ifstream file(filePath);
38 if (!file.is_open()) {
39 std::cerr << "Failed to open file: " << filePath << std::endl;
40 }
41 nlohmann::json out = nlohmann::json::parse(file, nullptr, false);
42 return out;
43}
44
Lawrence Tangd34f2b12022-07-19 15:36:31 +010045//Returns a ready-for-use memory stream containing a CPER record with the given sections inside.
Lawrence Tange407b4c2022-07-21 13:54:01 +010046FILE *generate_record_memstream(const char **types, UINT16 num_types,
John Chungf8fc7052024-05-03 20:05:29 +080047 char **buf, size_t *buf_size,
Aushim Nagarkattiae8f6d92025-01-29 17:34:44 -080048 int single_section,
49 GEN_VALID_BITS_TEST_TYPE validBitsType)
Lawrence Tangd34f2b12022-07-19 15:36:31 +010050{
Lawrence Tange407b4c2022-07-21 13:54:01 +010051 //Open a memory stream.
52 FILE *stream = open_memstream(buf, buf_size);
Lawrence Tangd34f2b12022-07-19 15:36:31 +010053
Lawrence Tange407b4c2022-07-21 13:54:01 +010054 //Generate a section to the stream, close & return.
John Chungf8fc7052024-05-03 20:05:29 +080055 if (!single_section) {
56 generate_cper_record(const_cast<char **>(types), num_types,
Aushim Nagarkattiae8f6d92025-01-29 17:34:44 -080057 stream, validBitsType);
John Chungf8fc7052024-05-03 20:05:29 +080058 } else {
59 generate_single_section_record(const_cast<char *>(types[0]),
Aushim Nagarkattiae8f6d92025-01-29 17:34:44 -080060 stream, validBitsType);
John Chungf8fc7052024-05-03 20:05:29 +080061 }
Lawrence Tange407b4c2022-07-21 13:54:01 +010062 fclose(stream);
Lawrence Tangd34f2b12022-07-19 15:36:31 +010063
Lawrence Tange407b4c2022-07-21 13:54:01 +010064 //Return fmemopen() buffer for reading.
65 return fmemopen(*buf, *buf_size, "r");
John Chungf8fc7052024-05-03 20:05:29 +080066}
Aushim Nagarkattiae8f6d92025-01-29 17:34:44 -080067
68void iterate_make_required_props(nlohmann::json &jsonSchema,
69 std::vector<std::string> &optional_props)
70{
71 //id
72 const auto it_id = jsonSchema.find("$id");
73 if (it_id != jsonSchema.end()) {
74 auto id_strptr = it_id->get_ptr<const std::string *>();
75 std::string id_str = *id_strptr;
76 if (id_str.find("header") != std::string::npos ||
77 id_str.find("section-descriptor") != std::string::npos) {
78 return;
79 }
80 }
81 //oneOf
82 const auto it_oneof = jsonSchema.find("oneOf");
83 if (it_oneof != jsonSchema.end()) {
84 //Iterate over oneOf properties
85 for (auto &oneOfProp : *it_oneof) {
86 iterate_make_required_props(oneOfProp, optional_props);
87 }
88 }
89
90 //items
91 const auto it_items = jsonSchema.find("items");
92 if (it_items != jsonSchema.end()) {
93 iterate_make_required_props(*it_items, optional_props);
94 }
95 //required
96 const auto it_req = jsonSchema.find("required");
97 if (it_req == jsonSchema.end()) {
98 return;
99 }
100
101 //properties
102 const auto it_prop = jsonSchema.find("properties");
103 if (it_prop == jsonSchema.end()) {
104 return;
105 }
106 nlohmann::json &propertyFields = *it_prop;
107 nlohmann::json::array_t property_list;
108 if (propertyFields.is_object()) {
109 for (auto &[key, value] : propertyFields.items()) {
110 const auto it_find_opt_prop =
111 std::find(optional_props.begin(),
112 optional_props.end(), key);
113 if (it_find_opt_prop == optional_props.end()) {
114 //Add to list if property is not optional
115 property_list.push_back(key);
116 }
117
118 iterate_make_required_props(value, optional_props);
119 }
120 }
121
122 *it_req = property_list;
123}
124
125// Document loader callback function
Ed Tanousd6b62632025-03-14 15:30:07 -0700126const nlohmann::json *documentLoader(const std::string &uri,
127 AddRequiredProps add_required_props)
Aushim Nagarkattiae8f6d92025-01-29 17:34:44 -0800128{
129 // Load the schema from a file
Ed Tanousd6b62632025-03-14 15:30:07 -0700130 std::unique_ptr<nlohmann::json> ref_schema =
131 std::make_unique<nlohmann::json>();
Aushim Nagarkattiae8f6d92025-01-29 17:34:44 -0800132 *ref_schema = loadJson(uri.c_str());
133 if (ref_schema->is_discarded()) {
134 std::cerr << "Could not open schema file: " << uri << std::endl;
135 }
Ed Tanousd6b62632025-03-14 15:30:07 -0700136 if (add_required_props == AddRequiredProps::YES) {
137 std::vector<std::string> opt = {};
138 const auto it_optional_file = optional_properties_map.find(uri);
139 if (it_optional_file != optional_properties_map.end()) {
140 opt = it_optional_file->second;
141 }
142 iterate_make_required_props(*ref_schema, opt);
Aushim Nagarkattiae8f6d92025-01-29 17:34:44 -0800143 }
Aushim Nagarkattiae8f6d92025-01-29 17:34:44 -0800144
Ed Tanousd6b62632025-03-14 15:30:07 -0700145 return ref_schema.release();
Aushim Nagarkattiae8f6d92025-01-29 17:34:44 -0800146}
147
148// Document release callback function
149void documentRelease(const nlohmann::json *adapter)
150{
151 delete adapter; // Free the adapter memory
152}
153
Ed Tanousd6b62632025-03-14 15:30:07 -0700154std::unique_ptr<valijson::Schema>
155load_schema(AddRequiredProps add_required_props, int single_section)
Aushim Nagarkattiae8f6d92025-01-29 17:34:44 -0800156{
157 // Load the schema
Ed Tanousd6b62632025-03-14 15:30:07 -0700158 fs::path pathObj(LIBCPER_JSON_SPEC);
Aushim Nagarkattiae8f6d92025-01-29 17:34:44 -0800159
Ed Tanousd6b62632025-03-14 15:30:07 -0700160 if (single_section) {
161 pathObj /= "cper-json-section-log.json";
162 } else {
163 pathObj /= "cper-json-full-log.json";
164 }
165 nlohmann::json schema_root = loadJson(pathObj.c_str());
166 fs::path base_path(LIBCPER_JSON_SPEC);
Aushim Nagarkattiae8f6d92025-01-29 17:34:44 -0800167 try {
168 fs::current_path(base_path);
169 // std::cout << "Changed directory to: " << fs::current_path()
170 // << std::endl;
171 } catch (const fs::filesystem_error &e) {
172 std::cerr << "Filesystem error: " << e.what() << std::endl;
173 }
174
175 // Parse the json schema into an internal schema format
Ed Tanousd6b62632025-03-14 15:30:07 -0700176 std::unique_ptr<valijson::Schema> schema =
177 std::make_unique<valijson::Schema>();
Aushim Nagarkattiae8f6d92025-01-29 17:34:44 -0800178 valijson::SchemaParser parser;
179 valijson::adapters::NlohmannJsonAdapter schemaDocumentAdapter(
180 schema_root);
181
182 // Set up callbacks for resolving external references
183 try {
Ed Tanousd6b62632025-03-14 15:30:07 -0700184 parser.populateSchema(
185 schemaDocumentAdapter, *schema,
186 [add_required_props](const std::string &uri) {
187 return documentLoader(uri, add_required_props);
188 },
189 documentRelease);
Aushim Nagarkattiae8f6d92025-01-29 17:34:44 -0800190 } catch (std::exception &e) {
191 std::cerr << "Failed to parse schema: " << e.what()
192 << std::endl;
Aushim Nagarkattiae8f6d92025-01-29 17:34:44 -0800193 }
Ed Tanousd6b62632025-03-14 15:30:07 -0700194 return schema;
195}
Aushim Nagarkattiae8f6d92025-01-29 17:34:44 -0800196
Ed Tanousd6b62632025-03-14 15:30:07 -0700197int schema_validate_from_file(const valijson::Schema &schema,
198 nlohmann::json &jsonData,
199 std::string &error_message)
200{
Aushim Nagarkattiae8f6d92025-01-29 17:34:44 -0800201 // Perform validation
202 valijson::Validator validator(valijson::Validator::kStrongTypes);
203 valijson::ValidationResults results;
204 valijson::adapters::NlohmannJsonAdapter targetDocumentAdapter(jsonData);
205 if (!validator.validate(schema, targetDocumentAdapter, &results)) {
206 std::cerr << "Validation failed." << std::endl;
207 valijson::ValidationResults::Error error;
208 unsigned int errorNum = 1;
209 while (results.popError(error)) {
210 std::string context;
Ed Tanousbadae112025-03-10 13:38:51 -0700211 for (const std::string &str : error.context) {
212 context += str;
Aushim Nagarkattiae8f6d92025-01-29 17:34:44 -0800213 }
214
Ed Tanousbadae112025-03-10 13:38:51 -0700215 std::cout << "Error #" << errorNum << '\n'
216 << " context: " << context << '\n'
217 << " desc: " << error.description << '\n';
Aushim Nagarkattiae8f6d92025-01-29 17:34:44 -0800218 ++errorNum;
219 }
220 return 0;
221 }
222
223 error_message = "Schema validation successful";
224 return 1;
225}