### Rust Main Function Example Source: https://github.com/werwolv/patternlanguage/blob/master/README.md A simple 'Hello World' example in Rust, demonstrating basic syntax and standard output. ```rust fn main() { std::print("Hello World"); } ``` -------------------------------- ### Install Project Files - CMake Source: https://github.com/werwolv/patternlanguage/blob/master/external/nlohmann_json/CMakeLists.txt Handles the installation of project files, including headers, CMake configuration files, Natvis file (if enabled), and targets, when the JSON_Install option is true. It also exports targets for other CMake projects. ```cmake if(JSON_Install) install( DIRECTORY ${NLOHMANN_JSON_INCLUDE_BUILD_DIR} DESTINATION ${NLOHMANN_JSON_INCLUDE_INSTALL_DIR} ) install( FILES ${NLOHMANN_JSON_CMAKE_PROJECT_CONFIG_FILE} ${NLOHMANN_JSON_CMAKE_VERSION_CONFIG_FILE} DESTINATION ${NLOHMANN_JSON_CONFIG_INSTALL_DIR} ) if (NLOHMANN_ADD_NATVIS) install( FILES ${NLOHMANN_NATVIS_FILE} DESTINATION . ) endif() export( TARGETS ${NLOHMANN_JSON_TARGET_NAME} NAMESPACE ${PROJECT_NAME}:: FILE ${NLOHMANN_JSON_CMAKE_PROJECT_TARGETS_FILE} ) install( TARGETS ${NLOHMANN_JSON_TARGET_NAME} EXPORT ${NLOHMANN_JSON_TARGETS_EXPORT_NAME} INCLUDES DESTINATION ${NLOHMANN_JSON_INCLUDE_INSTALL_DIR} ) install( EXPORT ${NLOHMANN_JSON_TARGETS_EXPORT_NAME} NAMESPACE ${PROJECT_NAME}:: DESTINATION ${NLOHMANN_JSON_CONFIG_INSTALL_DIR} ) install( FILES "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.pc" DESTINATION ${NLOHMANN_JSON_PKGCONFIG_INSTALL_DIR} ) endif() ``` -------------------------------- ### Install pkg-config File - CMake Source: https://github.com/werwolv/patternlanguage/blob/master/external/nlohmann_json/CMakeLists.txt Generates and installs a pkg-config file, enabling other tools to easily find and use the installed library. This is crucial for cross-project dependency management. ```cmake CONFIGURE_FILE( "cmake/pkg-config.pc.in" "${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}.pc" ) ``` -------------------------------- ### Conditional Testing Target Setup Source: https://github.com/werwolv/patternlanguage/blob/master/CMakeLists.txt Sets up a custom target 'unit_tests' if testing is enabled. This ensures that testing infrastructure is only configured when the LIBPL_ENABLE_TESTS option is ON. ```cmake if (LIBPL_ENABLE_TESTS) if(NOT TARGET unit_tests) enable_testing() add_custom_target(unit_tests) endif() endif() ``` -------------------------------- ### macOS Homebrew Clang Linker Flag Setup Source: https://github.com/werwolv/patternlanguage/blob/master/CMakeLists.txt Configures linker flags on macOS to use the libc++ library from Homebrew's LLVM installation if clang++ is being used. This ensures consistent library usage across the build. ```cmake if (APPLE) execute_process(COMMAND brew --prefix llvm OUTPUT_VARIABLE LLVM_PREFIX OUTPUT_STRIP_TRAILING_WHITESPACE) if (NOT LLVM_PREFIX STREQUAL "" AND ${CMAKE_CXX_COMPILER} STREQUAL "${LLVM_PREFIX}/bin/clang++") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -L${LLVM_PREFIX}/lib/c++") set(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -L${LLVM_PREFIX}/lib/c++") set(CMAKE_MODULE_LINKER_FLAGS "${CMAKE_MODULE_LINKER_FLAGS} -L${LLVM_PREFIX}/lib/c++") endif() endif() ``` -------------------------------- ### Set Installation Directories (CMake) Source: https://github.com/werwolv/patternlanguage/blob/master/external/nlohmann_json/CMakeLists.txt Includes the GNUInstallDirs module to set standard installation directory variables and defines various cache variables for configuring installation paths and filenames for CMake configuration files. ```cmake include(GNUInstallDirs) set(NLOHMANN_JSON_TARGET_NAME ${PROJECT_NAME}) set(NLOHMANN_JSON_CONFIG_INSTALL_DIR "${CMAKE_INSTALL_DATADIR}/cmake/${PROJECT_NAME}" CACHE INTERNAL "") set(NLOHMANN_JSON_INCLUDE_INSTALL_DIR "${CMAKE_INSTALL_INCLUDEDIR}") set(NLOHMANN_JSON_TARGETS_EXPORT_NAME "${PROJECT_NAME}Targets") set(NLOHMANN_JSON_CMAKE_CONFIG_TEMPLATE "cmake/config.cmake.in") set(NLOHMANN_JSON_CMAKE_CONFIG_DIR "${CMAKE_CURRENT_BINARY_DIR}") set(NLOHMANN_JSON_CMAKE_VERSION_CONFIG_FILE "${NLOHMANN_JSON_CMAKE_CONFIG_DIR}/${PROJECT_NAME}ConfigVersion.cmake") set(NLOHMANN_JSON_CMAKE_PROJECT_CONFIG_FILE "${NLOHMANN_JSON_CMAKE_CONFIG_DIR}/${PROJECT_NAME}Config.cmake") set(NLOHMANN_JSON_CMAKE_PROJECT_TARGETS_FILE "${NLOHMANN_JSON_CMAKE_CONFIG_DIR}/${PROJECT_NAME}Targets.cmake") set(NLOHMANN_JSON_PKGCONFIG_INSTALL_DIR "${CMAKE_INSTALL_DATADIR}/pkgconfig") ``` -------------------------------- ### Install libpl Library (CMake) Source: https://github.com/werwolv/patternlanguage/blob/master/lib/CMakeLists.txt This CMake snippet defines installation rules for the libpl library. If LIBPL_SHARED_LIBRARY is defined, it installs the library to the 'lib' directory. It also sets the target property for the library's prefix. ```cmake set_target_properties(libpl PROPERTIES PREFIX "") if (LIBPL_SHARED_LIBRARY) install(TARGETS libpl DESTINATION lib) endif () ``` -------------------------------- ### Execute Pattern Language CLI Commands Source: https://context7.com/werwolv/patternlanguage/llms.txt This section provides examples of using the Pattern Language Command Line Interface (CLI) to execute pattern files on binary data and format the output. It covers running patterns, formatting results into JSON and YAML, generating documentation, and retrieving pattern information. ```bash # Run a pattern file on binary data plcli run --input data.bin --pattern structure.hexpat # Format pattern output as JSON plcli format --input data.bin --pattern structure.hexpat --output result.json # Format as YAML plcli format --input data.bin --pattern structure.hexpat --output result.yaml --formatter yaml # Generate documentation for a pattern plcli docs --pattern structure.hexpat --output docs.html # Get pattern information plcli info --pattern structure.hexpat ``` -------------------------------- ### Configure C++ Project Build with CMake Source: https://github.com/werwolv/patternlanguage/blob/master/example/CMakeLists.txt This CMakeLists.txt file sets up the build environment for the pattern language example. It specifies the minimum CMake version, project name, C++ standard, executable target, include directories, and linked libraries. ```cmake cmake_minimum_required(VERSION 3.16) project(pattern_language_example) set(CMAKE_CXX_STANDARD 23) add_executable(pattern_language_example source/main.cpp ) target_include_directories(pattern_language_example PRIVATE include) target_link_libraries(pattern_language_example PRIVATE libpl) ``` -------------------------------- ### fmt Library Dependency Management Source: https://github.com/werwolv/patternlanguage/blob/master/CMakeLists.txt Manages the inclusion of the fmt library. If USE_SYSTEM_FMT is not set, it adds the fmt subdirectory; otherwise, it finds an installed version. Sets the appropriate library target for use. ```cmake if (NOT USE_SYSTEM_FMT) if (NOT TARGET fmt::fmt) add_subdirectory(external/fmt EXCLUDE_FROM_ALL) set(FMT_LIBRARIES fmt::fmt-header-only) endif () else() find_package(fmt 8.0.0 REQUIRED) set(FMT_LIBRARIES fmt::fmt) endif() ``` -------------------------------- ### Add Custom Functions to Pattern Language Runtime - C++ Source: https://context7.com/werwolv/patternlanguage/llms.txt Illustrates how to extend the Pattern Language runtime with custom functions in C++. It shows how to register functions with specific parameter counts (exactly one or at least two) and provides lambda implementations for these functions. The example includes executing pattern language code that utilizes these newly added custom functions. Dependencies include pl.hpp and the fmt library. ```cpp #include #include int main() { pl::PatternLanguage patternLanguage; // Add a normal function with exactly one parameter patternLanguage.addFunction( {"test"}, // namespace "normal_function", // function name pl::api::FunctionParameterCount::exactly(1), [](pl::core::Evaluator *ctx, const std::vector ¶ms) -> std::optional { // Access parameter value auto value = std::get(params[0]); fmt::print("normal_function called with: {}\n", value); return std::nullopt; // No return value } ); // Add function with flexible parameter count patternLanguage.addFunction( {"math"}, "sum", pl::api::FunctionParameterCount::atLeast(2), [](pl::core::Evaluator *ctx, const std::vector ¶ms) -> std::optional { pl::i128 sum = 0; for (const auto ¶m : params) { sum += std::get(param); } return sum; } ); // Execute code using custom functions patternLanguage.executeString(R"( fn main() { test::normal_function(42); s64 result = math::sum(10, 20, 30); std::print(\"Sum: {}\", result); }; )"); return 0; } ``` -------------------------------- ### C++ Struct and Enum Definition Example Source: https://github.com/werwolv/patternlanguage/blob/master/README.md Defines a C++ enum 'Type' and a struct 'MyStruct' with various data types and padding. It also shows how to define a variable at a specific memory address. ```cpp enum Type : u16 { A = 0x50, B, C }; struct MyStruct { Type type; u32 x, y, z; padding[10]; double a; }; MyStruct myStruct @ 0x100; ``` -------------------------------- ### nlohmann_json Library Dependency Management Source: https://github.com/werwolv/patternlanguage/blob/master/CMakeLists.txt Manages the inclusion of the nlohmann_json library. If USE_SYSTEM_NLOHMANN_JSON is not set, it adds the nlohmann_json subdirectory; otherwise, it finds an installed version. Sets the appropriate library target for use. ```cmake if (NOT USE_SYSTEM_NLOHMANN_JSON) if (NOT TARGET nlohmann_json) add_subdirectory(external/nlohmann_json EXCLUDE_FROM_ALL) set(NLOHMANN_JSON_LIBRARIES nlohmann_json) endif () else() find_package(nlohmann_json 3.10.2 REQUIRED) set(NLOHMANN_JSON_LIBRARIES nlohmann_json::nlohmann_json) endif() ``` -------------------------------- ### Subdirectory Inclusion for Project Components Source: https://github.com/werwolv/patternlanguage/blob/master/CMakeLists.txt Includes various subdirectories that contain different parts of the project, such as external libraries, core logic, generators, examples, tests, and CLI tools. Some are excluded from all targets by default. ```cmake add_subdirectory(external/libwolv) add_subdirectory(lib) add_subdirectory(generators EXCLUDE_FROM_ALL) if (LIBPL_ENABLE_EXAMPLE) add_subdirectory(example EXCLUDE_FROM_ALL) endif () if (LIBPL_ENABLE_TESTS) add_subdirectory(tests EXCLUDE_FROM_ALL) endif () if (LIBPL_ENABLE_CLI) add_subdirectory(cli) endif () if (LIBPL_ENABLE_FUZZING) add_subdirectory(fuzz EXCLUDE_FROM_ALL) endif () ``` -------------------------------- ### Generate and Install CMake Config Files - CMake Source: https://github.com/werwolv/patternlanguage/blob/master/external/nlohmann_json/CMakeLists.txt Generates package configuration files (`nlohmann_jsonConfig.cmake` and `nlohmann_jsonConfigVersion.cmake`) for use with `find_package()`. These files facilitate the integration of the library into other CMake projects. ```cmake include(CMakePackageConfigHelpers) # use a custom package version config file instead of # write_basic_package_version_file to ensure that it's architecture-independent # https://github.com/nlohmann/json/issues/1697 configure_file( "cmake/nlohmann_jsonConfigVersion.cmake.in" ${NLOHMANN_JSON_CMAKE_VERSION_CONFIG_FILE} @ONLY ) configure_file( ${NLOHMANN_JSON_CMAKE_CONFIG_TEMPLATE} ${NLOHMANN_JSON_CMAKE_PROJECT_CONFIG_FILE} @ONLY ) ``` -------------------------------- ### Define Build Options (CMake) Source: https://github.com/werwolv/patternlanguage/blob/master/external/nlohmann_json/CMakeLists.txt Defines various build options for the nlohmann/json library, including flags for CI builds, diagnostics, global UDLs, implicit conversions, enum serialization, legacy comparison, installation, multiple headers, and system includes. ```cmake option(JSON_CI "Enable CI build targets." OFF) option(JSON_Diagnostics "Use extended diagnostic messages." OFF) option(JSON_GlobalUDLs "Place use-defined string literals in the global namespace." ON) option(JSON_ImplicitConversions "Enable implicit conversions." ON) option(JSON_DisableEnumSerialization "Disable default integer enum serialization." OFF) option(JSON_LegacyDiscardedValueComparison "Enable legacy discarded value comparison." OFF) option(JSON_Install "Install CMake targets during install step." ${MAIN_PROJECT}) option(JSON_MultipleHeaders "Use non-amalgamated version of the library." ON) option(JSON_SystemInclude "Include as system headers (skip for clang-tidy)." OFF) ``` -------------------------------- ### Set Include Directories (CMake) Source: https://github.com/werwolv/patternlanguage/blob/master/external/nlohmann_json/CMakeLists.txt Configures include directories for the nlohmann_json target. It uses the NLOHMANN_JSON_SYSTEM_INCLUDE variable to potentially mark them as system includes and specifies build and install interfaces. ```cmake target_include_directories( ${NLOHMANN_JSON_TARGET_NAME} ${NLOHMANN_JSON_SYSTEM_INCLUDE} INTERFACE $ $ ) ``` -------------------------------- ### Execute Pattern Language Code with Runtime - C++ Source: https://context7.com/werwolv/patternlanguage/llms.txt Demonstrates how to create and use the PatternLanguage runtime in C++ to execute pattern language code against binary data. It covers setting up the data source, executing a string containing pattern definitions and a main function, and handling potential evaluation errors. Dependencies include the pl.hpp header and standard C++ libraries. ```cpp #include #include #include int main() { // Create an instance of the pattern language runtime pl::PatternLanguage patternLanguage; // Create some sample binary data to analyze constexpr static auto Data = []{ std::array data = { }; for (size_t i = 0; i < data.size(); i++) data[i] = i; return data; }(); // Configure data source with base address, size, and read function patternLanguage.setDataSource(0x00, Data.size(), [](pl::u64 address, pl::u8 *buffer, size_t size){ std::memcpy(buffer, &Data[address], size); } ); // Execute pattern language code int result = patternLanguage.executeString(R"( struct MyStruct { u32 value; u8 flags; padding[3]; }; fn main() { MyStruct data @ 0x00; std::print(\"Value: {}\", data.value); }; )"); // Check execution result if (result != 0) { auto error = patternLanguage.getEvalError(); printf("Error at %d:%d - %s\n", error->line, error->column, error->message.c_str()); return 1; } return 0; } ``` -------------------------------- ### Running Fuzzing Session with AFL++ Source: https://github.com/werwolv/patternlanguage/blob/master/fuzz/README.md Initiate a fuzzing session using the afl-fuzz tool. This command specifies input and output directories, a dictionary for improved fuzzing, and the target binary (plfuzz) to be fuzzed. ```bash afl-fuzz -i inputs -o output -x ./dict/hexpat.dict -- ./plfuzz @@ ``` -------------------------------- ### Rust: Implementing Functions and Control Flow for Binary Parsing Source: https://context7.com/werwolv/patternlanguage/llms.txt Demonstrates defining helper functions like calculateChecksum and validateHeader, and a main function for parsing binary data. It includes conditional logic, loops, and printing output, typical for binary analysis tasks. ```rust // Define helper functions fn calculateChecksum(u32 value) { return (value >> 16) ^ (value & 0xFFFF); }; fn validateHeader(ref auto header) { if (header.magic != "MAGIC") { std::error("Invalid magic number"); return false; } return true; }; // Main entry point fn main() { std::print("Parsing binary data..."); // Read and validate u32 magic @ 0x00; if (!validateChecksum(magic)) { std::error("Checksum failed"); return; } // Loop through data u32 count @ 0x04; u64 offset = 0x08; for (u32 i = 0, i < count, i = i + 1) { u16 value @ offset; std::print("Value {}: {}", i, value); offset = offset + 2; } }; ``` -------------------------------- ### CMakeLists.txt: Post-Build Custom Commands Source: https://github.com/werwolv/patternlanguage/blob/master/tests/CMakeLists.txt Configures custom commands to execute after the 'pattern_language_tests' target is built. These commands copy essential files like test data and export configurations to the binary directory. ```cmake add_custom_command(TARGET pattern_language_tests POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_CURRENT_SOURCE_DIR}/test_data" ${CMAKE_BINARY_DIR}/bin) add_custom_command(TARGET pattern_language_tests POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_CURRENT_SOURCE_DIR}/files/export/json.json" ${CMAKE_BINARY_DIR}/bin/files/export/json.json) add_custom_command(TARGET pattern_language_tests POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy_if_different "${CMAKE_CURRENT_SOURCE_DIR}//files/export/yaml.yml" ${CMAKE_BINARY_DIR}/bin/files/export/yaml.yml) ``` -------------------------------- ### CMake Project Configuration and Options Source: https://github.com/werwolv/patternlanguage/blob/master/CMakeLists.txt Configures the CMake project, sets C++ standards, and defines build options for features like shared libraries, testing, CLI tools, and precompiled headers. These options control which components are built and how. ```cmake cmake_minimum_required(VERSION 3.20) project(PatternLanguage) set(CMAKE_CXX_STANDARD 23) set(CMAKE_CXX_STANDARD_REQUIRED ON) option(LIBPL_SHARED_LIBRARY "Compile the library as a shared library" OFF) option(LIBPL_ENABLE_TESTS "Enable testing" OFF) option(LIBPL_ENABLE_CLI "Enable building the CLI tool" ON) option(LIBPL_BUILD_CLI_AS_EXECUTABLE "Build the CLI tool as an executable" ON) option(LIBPL_ENABLE_EXAMPLE "Enable building the examples" OFF) option(LIBPL_ENABLE_PRECOMPILED_HEADERS "Enable building with precompiled headers" OFF) ``` -------------------------------- ### Minimizing All Crashes with Python Script Source: https://github.com/werwolv/patternlanguage/blob/master/fuzz/README.md Execute a provided Python script to automate the minimization of all crash files found in a specified directory. This script leverages afl-tmin for each crash. ```bash python3 afl-pytmin.py output/crashes output/minimized ./plfuzz ``` -------------------------------- ### Configure Project and Version (CMake) Source: https://github.com/werwolv/patternlanguage/blob/master/external/nlohmann_json/CMakeLists.txt Sets the minimum required CMake version and defines the project name and version. This is crucial for compatibility and identifying the library during the build process. ```cmake cmake_minimum_required(VERSION 3.1...3.14) project(nlohmann_json VERSION 3.11.3 LANGUAGES CXX) ``` -------------------------------- ### CMakeLists.txt: Project and Executable Definition Source: https://github.com/werwolv/patternlanguage/blob/master/tests/CMakeLists.txt Defines the minimum CMake version, project name, and the main executable target 'pattern_language_tests'. It lists the source files and include directories required for the executable. ```cmake cmake_minimum_required(VERSION 3.16) project(pattern_language_tests) # Add new tests here # set(AVAILABLE_TESTS DocComments Strings Placement Structs Unions Enums Literals Padding Matching SucceedingAssert FailingAssert Bitfields ReversedBitfields Math RValues Namespaces Include Import ExtraSemicolon Pointers Arrays NestedStructs Attributes Pragmas PragmasFail Format RValuesAssignmentInStruct TemplateParametersScope TypeNameOf CustomBuiltInType Using ) add_executable(pattern_language_tests source/main.cpp source/tests.cpp include/test_patterns/test_pattern_import.hpp ) # ---- No need to change anything from here downwards unless you know what you're doing ---- # target_include_directories(pattern_language_tests PRIVATE include) target_link_libraries(pattern_language_tests PRIVATE libpl libpl-gen fmt::fmt-header-only) set_target_properties(pattern_language_tests PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) ``` -------------------------------- ### Alias Target for Main Library Source: https://github.com/werwolv/patternlanguage/blob/master/CMakeLists.txt Creates an alias target 'pl::libpl' that refers to the 'libpl' library. This provides a modern CMake interface for referencing the main library. ```cmake add_library(pl::libpl ALIAS libpl) ``` -------------------------------- ### Include CI Configuration (CMake) Source: https://github.com/werwolv/patternlanguage/blob/master/external/nlohmann_json/CMakeLists.txt Includes the 'ci' module if the JSON_CI option is enabled. This is typically used for setting up continuous integration specific build targets and configurations. ```cmake if (JSON_CI) include(ci) endif () ``` -------------------------------- ### Manage Include Directories and Link Libraries for libpl (CMake) Source: https://github.com/werwolv/patternlanguage/blob/master/lib/CMakeLists.txt This CMake snippet configures the include directories and link libraries for the libpl project. It specifies public include directories for the library and its interface, and links against external libraries like FMT and other 'wolv' libraries. ```cmake target_include_directories(libpl PUBLIC include ../external/throwing_ptr/include) target_include_directories(libpl_includes INTERFACE ${CMAKE_CURRENT_SOURCE_DIR}/include ../external/throwing_ptr/include) target_link_libraries(libpl PRIVATE ${FMT_LIBRARIES}) target_link_libraries(libpl PUBLIC wolv::types wolv::io wolv::utils wolv::hash wolv::containers) ``` -------------------------------- ### Minimizing Fuzzer Crashes with afl-tmin Source: https://github.com/werwolv/patternlanguage/blob/master/fuzz/README.md Use the afl-tmin tool to reduce crashing inputs to their minimal reproducible form. This helps in analyzing and fixing bugs more efficiently by providing smaller test cases. ```bash afl-tmin -i output/crashes/ -o output/minimized/ -- ./plfuzz @@ ``` -------------------------------- ### Configure Custom Logging for Runtime Messages Source: https://context7.com/werwolv/patternlanguage/llms.txt This C++ code configures custom logging to capture runtime messages at different severity levels. It defines a mapping for log levels and sets a callback function to print messages with their corresponding severity prefixes. ```cpp #include #include const static std::map LogLevels = { { pl::core::LogConsole::Level::Debug, "DEBUG" }, { pl::core::LogConsole::Level::Info, "INFO" }, { pl::core::LogConsole::Level::Warning, "WARNING" }, { pl::core::LogConsole::Level::Error, "ERROR" } }; int main() { pl::PatternLanguage patternLanguage; // Configure log callback patternLanguage.setLogCallback( [](auto level, const std::string &message) { printf("[%s] %s\n", LogLevels.at(level).c_str(), message.c_str()); } ); patternLanguage.executeString(R"( fn main() { std::print("This is an info message"); std::warning("This is a warning"); std::error("This is an error"); }; )"); return 0; } ``` -------------------------------- ### Operating System Specific Compile Definitions Source: https://github.com/werwolv/patternlanguage/blob/master/CMakeLists.txt Defines preprocessor macros (OS_WEB, OS_WINDOWS, OS_MACOS, OS_LINUX) based on the target operating system. This allows conditional compilation within the C++ source code. ```cmake if (CMAKE_CXX_COMPILER MATCHES "\/em\+\+(-[a-zA-Z0-9.])?$") add_compile_definitions(OS_WEB) elseif (WIN32) add_compile_definitions(OS_WINDOWS) elseif (APPLE) add_compile_definitions(OS_MACOS) elseif (UNIX AND NOT APPLE) add_compile_definitions(OS_LINUX) endif() ``` -------------------------------- ### Retrieve Parsed Patterns from Execution Source: https://context7.com/werwolv/patternlanguage/llms.txt This C++ snippet shows how to access patterns created during execution to inspect parsed binary data structures. It demonstrates setting up a data source, executing a pattern that defines structures, and then retrieving and inspecting these patterns by address. ```cpp #include #include int main() { pl::PatternLanguage patternLanguage; // Setup data source std::vector data = { 0x01, 0x02, 0x03, 0x04, // u32 value 0xFF, // u8 flag 0x00, 0x00, 0x00 // padding }; patternLanguage.setDataSource(0x00, data.size(), [&data](pl::u64 address, pl::u8 *buffer, size_t size){ std::memcpy(buffer, &data[address], size); } ); // Execute pattern that creates data structures patternLanguage.executeString(R"( struct Header { u32 magic; u8 version; padding[3]; }; Header header @ 0x00; )"); // Retrieve all created patterns const auto &patterns = patternLanguage.getPatterns(); printf("Created %zu patterns\n", patterns.size()); // Get patterns at specific address auto patternsAtAddr = patternLanguage.getPatternsAtAddress(0x00); for (auto *pattern : patternsAtAddr) { printf("Pattern at address 0x00: %s\n", pattern->getTypeName().c_str()); } return 0; } ``` -------------------------------- ### Control Dangerous Function Execution with Callbacks Source: https://context7.com/werwolv/patternlanguage/llms.txt This C++ snippet demonstrates how to control the execution of potentially dangerous functions using permission callbacks within the Pattern Language. It shows how to set a handler to intercept calls, decide whether to allow or deny them, and register a custom dangerous function. ```cpp #include int main() { pl::PatternLanguage patternLanguage; // Set handler for dangerous function calls patternLanguage.setDangerousFunctionCallHandler([]() { printf("Warning: Dangerous function called!\n"); // Return true to allow, false to deny return true; }); // Register a dangerous function patternLanguage.addDangerousFunction( {"test"}, "dangerous_function", pl::api::FunctionParameterCount::none(), [](pl::core::Evaluator *ctx, const std::vector ¶ms) -> std::optional { printf("Executing dangerous operation\n"); return 1337; } ); // Execute code that calls dangerous function int result = patternLanguage.executeString(R"( fn main() { s32 x = test::dangerous_function(); std::print("Result: {}", x); }; )"); return result; } ``` -------------------------------- ### Configure libpl-gen CMake Project Source: https://github.com/werwolv/patternlanguage/blob/master/generators/CMakeLists.txt Sets up the CMake build system for the libpl-gen project. It specifies the minimum required CMake version, names the project, sets the C++ standard to 23, defines an INTERFACE library, and configures include directories and target properties. ```cmake cmake_minimum_required(VERSION 3.16) project(libpl-gen) set(CMAKE_CXX_STANDARD 23) add_library(libpl-gen INTERFACE) target_include_directories(libpl-gen INTERFACE include) set_target_properties(libpl-gen PROPERTIES PREFIX "") ``` -------------------------------- ### Display Build Configuration Status Messages (CMake) Source: https://github.com/werwolv/patternlanguage/blob/master/external/nlohmann_json/CMakeLists.txt Prints status messages to the console indicating whether certain features like implicit conversions, enum serialization, legacy discarded value comparison, and diagnostics are enabled or disabled. ```cmake if (NOT JSON_ImplicitConversions) message(STATUS "Implicit conversions are disabled") endif() if (JSON_DisableEnumSerialization) message(STATUS "Enum integer serialization is disabled") endif() if (JSON_LegacyDiscardedValueComparison) message(STATUS "Legacy discarded value comparison enabled") endif() if (JSON_Diagnostics) message(STATUS "Diagnostics enabled") endif() ``` -------------------------------- ### Configure Unit Test Target - CMake Source: https://github.com/werwolv/patternlanguage/blob/master/external/nlohmann_json/CMakeLists.txt Sets up the unit testing framework using CTest and includes the test subdirectory if the JSON_BuildTests option is enabled. This ensures that tests are built and can be run as part of the build process. ```cmake if (JSON_BuildTests) include(CTest) enable_testing() add_subdirectory(tests) endif() ``` -------------------------------- ### Set CMake Policy for Options (CMake) Source: https://github.com/werwolv/patternlanguage/blob/master/external/nlohmann_json/CMakeLists.txt Applies a new policy (CMP0077) for CMake versions 3.13 and above. This policy controls how options are handled when using FetchContent or add_subdirectory, allowing overrides. ```cmake if (POLICY CMP0077) # Allow CMake 3.13+ to override options when using FetchContent / add_subdirectory. cmake_policy(SET CMP0077 NEW) endif () ``` -------------------------------- ### Rust: Utilizing Advanced Type System Features for Complex Binary Structures Source: https://context7.com/werwolv/patternlanguage/llms.txt Showcases advanced type system features in Rust, including generic templates (Optional), bitfields (Flags), unions (Variant), and pointer types (Node) for defining intricate binary formats like ComplexFormat. ```rust // Generic template type struct Optional { u8 hasValue; if (hasValue != 0) { T value; } }; // Bitfield for packed data bitfield Flags { enabled : 1; readonly : 1; reserved : 6; }; // Union for variant data union Variant { u32 intValue; float floatValue; char stringValue[4]; }; // Pointer types struct Node { u32 data; u32 nextPtr; if (nextPtr != 0) { Node *next : u32 @ nextPtr; } }; // Using advanced types struct ComplexFormat { Flags flags; Optional timestamp; Variant data; Node linkedList @ 0x100; }; ComplexFormat format @ 0x00; ``` -------------------------------- ### CMakeLists.txt: Test Definition Loop Source: https://github.com/werwolv/patternlanguage/blob/master/tests/CMakeLists.txt Iterates through the list of available tests defined in 'AVAILABLE_TESTS' and adds each as a separate test case to be run by CTest. Each test is named 'PatternLanguage/' and executed with the test name as an argument. ```cmake foreach (test IN LISTS AVAILABLE_TESTS) add_test(NAME "PatternLanguage/${test}" COMMAND pattern_language_tests "${test}" WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/bin) endforeach () add_dependencies(unit_tests ${PROJECT_NAME}) ``` -------------------------------- ### Building Pattern Language Fuzzer with AFL++ Source: https://github.com/werwolv/patternlanguage/blob/master/fuzz/README.md Configure CMake to use AFL++ compilers and enable fuzzing for the pattern language library. This ensures the fuzzer is built correctly with the necessary instrumentation. ```bash -DCMAKE_C_COMPILER=afl-cc -DCMAKE_CXX_COMPILER=afl-c++ -DLIBPL_ENABLE_FUZZING=ON ``` -------------------------------- ### Debugging Fuzzer Crashes with GDB Source: https://github.com/werwolv/patternlanguage/blob/master/fuzz/README.md Debug a crashing input identified by the fuzzer by running the target binary with the crashing file and attaching the GNU Debugger (GDB). This allows for step-by-step analysis of the crash. ```bash gdb -- ./plfuzz output/crashes/ ``` -------------------------------- ### Define Pattern Language Structures with Rust Source: https://context7.com/werwolv/patternlanguage/llms.txt This Rust code snippet illustrates how to define reusable pattern definitions for binary format parsing using the Pattern Language. It showcases the definition of enumerations, nested structures, dynamic arrays, conditional fields, and how to place structures at specific memory addresses. ```rust // Define enumerations for type safety enum FileType : u16 { TypeA = 0x50, TypeB = 0x51, TypeC = 0x52 }; // Define nested structures struct Header { char magic[4]; u32 version; FileType type; u64 dataOffset; }; struct DataEntry { u32 id; u16 length; char data[length]; }; // Define arrays and conditionals struct FileFormat { Header header; // Conditional field based on header type if (header.type == FileType::TypeA) { u32 extraFlags; } // Dynamic array DataEntry entries[header.version] @ header.dataOffset; }; // Place structure at specific address FileFormat file @ 0x00; ``` -------------------------------- ### Compiler Flags Configuration for C++ Source: https://github.com/werwolv/patternlanguage/blob/master/CMakeLists.txt Applies specific C++ compiler flags based on the detected compiler ID (GNU, MSVC, Clang, AppleClang). This ensures compatibility and enables features like exceptions and RTTI, while disabling specific warnings. ```cmake if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") add_compile_options($<$:-Wno-stringop-overflow>) add_compile_options($<$:-fexceptions>) add_compile_options($<$:-frtti>) elseif (MSVC) elseif (CMAKE_CXX_COMPILER_ID STREQUAL "Clang" OR CMAKE_CXX_COMPILER_ID STREQUAL "AppleClang") add_compile_options($<$:-Wno-deprecated-declarations>) add_compile_options($<$:-fexceptions>) add_compile_options($<$:-frtti>) elseif (NOT (CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")) add_compile_options($<$:-Wno-array-bounds>) endif() ``` -------------------------------- ### Include CMake Modules (CMake) Source: https://github.com/werwolv/patternlanguage/blob/master/external/nlohmann_json/CMakeLists.txt Adds the project's CMake modules directory to the CMake module path and includes the ExternalProject module. This allows for easier management of external dependencies and custom build logic. ```cmake set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake ${CMAKE_MODULE_PATH}) include(ExternalProject) ``` -------------------------------- ### Configure plfuzz Project with CMake Source: https://github.com/werwolv/patternlanguage/blob/master/fuzz/CMakeLists.txt This snippet configures the plfuzz project using CMake. It sets the minimum required version of CMake, defines the project name, specifies the C++ standard to 23, and sets the runtime output directory. It also adds the main executable and links to required libraries. ```cmake cmake_minimum_required(VERSION 3.16) project(plfuzz) set(CMAKE_CXX_STANDARD 23) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) add_executable(plfuzz source/main.cpp) target_link_libraries(plfuzz PRIVATE libpl libpl-gen fmt::fmt-header-only) ``` -------------------------------- ### Configure Build Tests Option (CMake) Source: https://github.com/werwolv/patternlanguage/blob/master/external/nlohmann_json/CMakeLists.txt Configures the JSON_BuildTests option, which controls whether unit tests are built. The default value depends on the CMake version and whether BUILD_TESTING is enabled. ```cmake if (${MAIN_PROJECT} AND (${CMAKE_VERSION} VERSION_EQUAL 3.13 OR ${CMAKE_VERSION} GREATER 3.13)) set(JSON_BuildTests_INIT ON) else() set(JSON_BuildTests_INIT OFF) endif() option(JSON_BuildTests "Build the unit tests when BUILD_TESTING is enabled." ${JSON_BuildTests_INIT}) ``` -------------------------------- ### Set Compiler Options for libpl (CMake) Source: https://github.com/werwolv/patternlanguage/blob/master/lib/CMakeLists.txt This CMake snippet sets compiler-specific options for the libpl library. It includes flags like /EHsc for MSVC and -Wall, -Wextra, -Werror for GCC/Clang, with additional specific warnings for GNU. ```cmake if (CMAKE_CXX_COMPILER_ID MATCHES "MSVC") target_compile_options(libpl PRIVATE /EHsc) elseif (CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") target_compile_options(libpl PRIVATE -Wall -Wextra -Werror -Wpedantic -Wno-unknown-pragmas -Wno-array-bounds) if (CMAKE_CXX_COMPILER_ID MATCHES "GNU") target_compile_options(libpl PRIVATE -Wno-stringop-overflow) endif() endif() if (CMAKE_CXX_COMPILER_ID STREQUAL "GNU") target_compile_options(libpl PRIVATE -Wno-stringop-overread) endif () ``` -------------------------------- ### Configure Precompiled Headers for libpl (CMake) Source: https://github.com/werwolv/patternlanguage/blob/master/lib/CMakeLists.txt This CMake snippet configures precompiled headers for the libpl library if the LIBPL_ENABLE_PRECOMPILED_HEADERS option is enabled. It gathers all header files from the 'include' directory and sets up the necessary precompile_headers target. ```cmake add_library(libpl_includes INTERFACE) if (LIBPL_ENABLE_PRECOMPILED_HEADERS) file(GLOB_RECURSE TARGET_INCLUDES "${CMAKE_CURRENT_SOURCE_DIR}/include/**/*.hpp") set(SYSTEM_INCLUDES ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;") set(INCLUDES "${SYSTEM_INCLUDES};${TARGET_INCLUDES}") string(REPLACE ">" "$" INCLUDES "${INCLUDES}") target_precompile_headers(libpl PUBLIC "$<$:${INCLUDES}>" ) endif () ``` -------------------------------- ### Determine Main Project Status (CMake) Source: https://github.com/werwolv/patternlanguage/blob/master/external/nlohmann_json/CMakeLists.txt Determines if the nlohmann_json library is being built as a subproject (using add_subdirectory) or as the main project. This logic affects certain default configurations. ```cmake set(MAIN_PROJECT OFF) if (CMAKE_CURRENT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR) set(MAIN_PROJECT ON) endif() ``` -------------------------------- ### Set Include Build Directory Based on Headers (CMake) Source: https://github.com/werwolv/patternlanguage/blob/master/external/nlohmann_json/CMakeLists.txt Determines the include directory for building the library based on the JSON_MultipleHeaders option. It sets NLOHMANN_JSON_INCLUDE_BUILD_DIR to either the multi-header or single-header directory and prints a status message. ```cmake if (JSON_MultipleHeaders) set(NLOHMANN_JSON_INCLUDE_BUILD_DIR "${PROJECT_SOURCE_DIR}/include/") message(STATUS "Using the multi-header code from ${NLOHMANN_JSON_INCLUDE_BUILD_DIR}") else() set(NLOHMANN_JSON_INCLUDE_BUILD_DIR "${PROJECT_SOURCE_DIR}/single_include/") message(STATUS "Using the single-header code from ${NLOHMANN_JSON_INCLUDE_BUILD_DIR}") endif() ``` -------------------------------- ### Define Library Target and Compile Features (CMake) Source: https://github.com/werwolv/patternlanguage/blob/master/external/nlohmann_json/CMakeLists.txt Creates an INTERFACE library target for nlohmann_json and an alias. It also sets the required C++ standard (cxx_range_for for CMake < 3.8.0, cxx_std_11 otherwise) using target_compile_features. ```cmake add_library(${NLOHMANN_JSON_TARGET_NAME} INTERFACE) add_library(${PROJECT_NAME}::${NLOHMANN_JSON_TARGET_NAME} ALIAS ${NLOHMANN_JSON_TARGET_NAME}) if (${CMAKE_VERSION} VERSION_LESS "3.8.0") target_compile_features(${NLOHMANN_JSON_TARGET_NAME} INTERFACE cxx_range_for) else() target_compile_features(${NLOHMANN_JSON_TARGET_NAME} INTERFACE cxx_std_11) endif() ``` -------------------------------- ### Configure libpl Library Build (CMake) Source: https://github.com/werwolv/patternlanguage/blob/master/lib/CMakeLists.txt This snippet configures the CMake build for the libpl library. It sets the minimum CMake version, project name, C++ standard, and determines whether to build a SHARED or OBJECT library based on the LIBPL_SHARED_LIBRARY variable. It lists all source files required for the library. ```cmake cmake_minimum_required(VERSION 3.16) project(libpl) set(CMAKE_CXX_STANDARD 23) if (LIBPL_SHARED_LIBRARY) set(LIBRARY_TYPE SHARED) message(STATUS "libpl dynamic library is being created") else () set(LIBRARY_TYPE OBJECT) message(STATUS "libpl static library is being created") endif () add_library(libpl ${LIBRARY_TYPE} source/pl/helpers/utils.cpp source/pl/pattern_language.cpp source/pl/core/ast/ast_node.cpp source/pl/core/ast/ast_node_array_variable_decl.cpp source/pl/core/ast/ast_node_attribute.cpp source/pl/core/ast/ast_node_bitfield.cpp source/pl/core/ast/ast_node_bitfield_array_variable_decl.cpp source/pl/core/ast/ast_node_bitfield_field.cpp source/pl/core/ast/ast_node_builtin_type.cpp source/pl/core/ast/ast_node_cast.cpp source/pl/core/ast/ast_node_compound_statement.cpp source/pl/core/ast/ast_node_conditional_statement.cpp source/pl/core/ast/ast_node_control_flow_statement.cpp source/pl/core/ast/ast_node_enum.cpp source/pl/core/ast/ast_node_function_call.cpp source/pl/core/ast/ast_node_function_definition.cpp source/pl/core/ast/ast_node_imported_type.cpp source/pl/core/ast/ast_node_literal.cpp source/pl/core/ast/ast_node_lvalue_assignment.cpp source/pl/core/ast/ast_node_match_statement.cpp source/pl/core/ast/ast_node_mathematical_expression.cpp source/pl/core/ast/ast_node_multi_variable_decl.cpp source/pl/core/ast/ast_node_parameter_pack.cpp source/pl/core/ast/ast_node_pointer_variable_decl.cpp source/pl/core/ast/ast_node_rvalue.cpp source/pl/core/ast/ast_node_rvalue_assignment.cpp source/pl/core/ast/ast_node_scope_resolution.cpp source/pl/core/ast/ast_node_struct.cpp source/pl/core/ast/ast_node_ternary_expression.cpp source/pl/core/ast/ast_node_try_catch_statement.cpp source/pl/core/ast/ast_node_type_application.cpp source/pl/core/ast/ast_node_type_decl.cpp source/pl/core/ast/ast_node_type_operator.cpp source/pl/core/ast/ast_node_union.cpp source/pl/core/ast/ast_node_variable_decl.cpp source/pl/core/ast/ast_node_while_statement.cpp source/pl/core/token.cpp source/pl/core/evaluator.cpp source/pl/core/lexer.cpp source/pl/core/parser.cpp source/pl/core/preprocessor.cpp source/pl/core/validator.cpp source/pl/core/parser_manager.cpp source/pl/core/resolver.cpp source/pl/core/error.cpp source/pl/lib/std/pragmas.cpp source/pl/lib/std/std.cpp source/pl/lib/std/mem.cpp source/pl/lib/std/math.cpp source/pl/lib/std/string.cpp source/pl/lib/std/file.cpp source/pl/lib/std/time.cpp source/pl/lib/std/core.cpp source/pl/lib/std/hash.cpp source/pl/lib/std/random.cpp source/pl/core/resolvers.cpp ) ``` -------------------------------- ### Set Compile Definitions Based on Options (CMake) Source: https://github.com/werwolv/patternlanguage/blob/master/external/nlohmann_json/CMakeLists.txt Configures compile definitions for the nlohmann_json target based on various build options. This allows enabling or disabling specific features like GLOBAL_UDLS, IMPLICIT_CONVERSIONS, and others at compile time. ```cmake target_compile_definitions( ${NLOHMANN_JSON_TARGET_NAME} INTERFACE $<$>:JSON_USE_GLOBAL_UDLS=0> $<$>:JSON_USE_IMPLICIT_CONVERSIONS=0> $<$:JSON_DISABLE_ENUM_SERIALIZATION=1> $<$:JSON_DIAGNOSTICS=1> $<$:JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON=1> ) ``` -------------------------------- ### Add MSVC Debug View Definition (Natvis) - CMake Source: https://github.com/werwolv/patternlanguage/blob/master/external/nlohmann_json/CMakeLists.txt Conditionally adds a Natvis file for MSVC debugging when the MSVC build option is enabled. This enhances debugging capabilities by providing custom visualizations for data structures. ```cmake if (MSVC) set(NLOHMANN_ADD_NATVIS TRUE) set(NLOHMANN_NATVIS_FILE "nlohmann_natvis") target_sources( ${NLOHMANN_JSON_TARGET_NAME} INTERFACE $ $ ) endif() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.