Repository: jsecurity101/JonMon Branch: main Commit: ce5de1c7c647 Files: 87 Total size: 1.4 MB Directory structure: gitextract_k5_9flv0/ ├── .github/ │ └── ISSUE_TEMPLATE/ │ ├── bug_report.md │ └── feature_request.md ├── .gitignore ├── Extensions/ │ └── Extension1/ │ └── JonMon-Ext1/ │ ├── JonMon-Ext1.vcxproj │ ├── dllmain.cpp │ ├── dllmain.h │ ├── framework.h │ ├── pch.cpp │ └── pch.h ├── JonMon/ │ ├── JonMon.sln │ ├── JonMon.vcxproj │ ├── callbacks.cpp │ ├── callbacks.h │ ├── driver.cpp │ ├── driver.h │ ├── jtime.h │ ├── minifilter.cpp │ ├── minifilter.h │ ├── process.cpp │ ├── process.h │ ├── registry.cpp │ ├── registry.h │ └── shared.h ├── JonMon-Service/ │ ├── JonMon-Service.vcxproj │ ├── JonMonService.cpp │ ├── config.cpp │ ├── config.h │ ├── context.cpp │ ├── context.h │ ├── etwMain.cpp │ ├── etwMain.h │ ├── global.h │ ├── service.cpp │ └── service.h ├── JonMonConfig.json ├── JonMonProvider/ │ ├── jonmon.h │ ├── jonmon.man │ ├── jonmon.rc │ └── jonmon.res ├── LICENSE ├── Libs/ │ └── nlohmann/ │ ├── adl_serializer.hpp │ ├── byte_container_with_subtype.hpp │ ├── detail/ │ │ ├── abi_macros.hpp │ │ ├── conversions/ │ │ │ ├── from_json.hpp │ │ │ ├── to_chars.hpp │ │ │ └── to_json.hpp │ │ ├── exceptions.hpp │ │ ├── hash.hpp │ │ ├── input/ │ │ │ ├── binary_reader.hpp │ │ │ ├── input_adapters.hpp │ │ │ ├── json_sax.hpp │ │ │ ├── lexer.hpp │ │ │ ├── parser.hpp │ │ │ └── position_t.hpp │ │ ├── iterators/ │ │ │ ├── internal_iterator.hpp │ │ │ ├── iter_impl.hpp │ │ │ ├── iteration_proxy.hpp │ │ │ ├── iterator_traits.hpp │ │ │ ├── json_reverse_iterator.hpp │ │ │ └── primitive_iterator.hpp │ │ ├── json_custom_base_class.hpp │ │ ├── json_pointer.hpp │ │ ├── json_ref.hpp │ │ ├── macro_scope.hpp │ │ ├── macro_unscope.hpp │ │ ├── meta/ │ │ │ ├── call_std/ │ │ │ │ ├── begin.hpp │ │ │ │ └── end.hpp │ │ │ ├── cpp_future.hpp │ │ │ ├── detected.hpp │ │ │ ├── identity_tag.hpp │ │ │ ├── is_sax.hpp │ │ │ ├── std_fs.hpp │ │ │ ├── type_traits.hpp │ │ │ └── void_t.hpp │ │ ├── output/ │ │ │ ├── binary_writer.hpp │ │ │ ├── output_adapters.hpp │ │ │ └── serializer.hpp │ │ ├── string_concat.hpp │ │ ├── string_escape.hpp │ │ └── value_t.hpp │ ├── json.hpp │ ├── json_fwd.hpp │ ├── ordered_map.hpp │ └── thirdparty/ │ └── hedley/ │ ├── hedley.hpp │ └── hedley_undef.hpp ├── README.md └── deployment/ └── Azure/ └── README.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.md ================================================ --- name: Bug report about: Report to introduce issues within the JonMon code title: '' labels: bug assignees: jsecurity101 --- **Describe the bug** A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior: 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error **Expected behavior** A clear and concise description of what you expected to happen. **Screenshots** If applicable, add screenshots to help explain your problem. **Desktop (please complete the following information):** - OS Build [e.g. 22621.2283] **Additional context** Add any other context about the problem here. ## Please include dump file if applicable ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.md ================================================ --- name: Feature request about: Suggest an idea for this project title: '' labels: enhancement assignees: jsecurity101 --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here. ================================================ FILE: .gitignore ================================================ # Created by https://www.toptal.com/developers/gitignore/api/visualstudio # Edit at https://www.toptal.com/developers/gitignore?templates=visualstudio ### VisualStudio ### ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. ## ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore # User-specific files *.rsuser *.suo *.user *.userosscache *.sln.docstates # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs # Mono auto generated files mono_crash.* # Build results [Dd]ebug/ [Dd]ebugPublic/ [Rr]elease/ [Rr]eleases/ x64/ x86/ [Ww][Ii][Nn]32/ [Aa][Rr][Mm]/ [Aa][Rr][Mm]64/ bld/ [Bb]in/ [Oo]bj/ [Ll]og/ [Ll]ogs/ # Visual Studio 2015/2017 cache/options directory .vs/ # Uncomment if you have tasks that create the project's static files in wwwroot #wwwroot/ # Visual Studio 2017 auto generated files Generated\ Files/ # MSTest test Results [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* # NUnit *.VisualState.xml TestResult.xml nunit-*.xml # Build Results of an ATL Project [Dd]ebugPS/ [Rr]eleasePS/ dlldata.c # Benchmark Results BenchmarkDotNet.Artifacts/ # .NET Core project.lock.json project.fragment.lock.json artifacts/ # ASP.NET Scaffolding ScaffoldingReadMe.txt # StyleCop StyleCopReport.xml # Files built by Visual Studio *_i.c *_p.c *_h.h *.ilk *.meta *.obj *.iobj *.pch *.pdb *.ipdb *.pgc *.pgd *.rsp *.sbr *.tlb *.tli *.tlh *.tmp *.tmp_proj *_wpftmp.csproj *.log *.tlog *.vspscc *.vssscc .builds *.pidb *.svclog *.scc # Chutzpah Test files _Chutzpah* # Visual C++ cache files ipch/ *.aps *.ncb *.opendb *.opensdf *.sdf *.cachefile *.VC.db *.VC.VC.opendb # Visual Studio profiler *.psess *.vsp *.vspx *.sap # Visual Studio Trace Files *.e2e # TFS 2012 Local Workspace $tf/ # Guidance Automation Toolkit *.gpState # ReSharper is a .NET coding add-in _ReSharper*/ *.[Rr]e[Ss]harper *.DotSettings.user # TeamCity is a build add-in _TeamCity* # DotCover is a Code Coverage Tool *.dotCover # AxoCover is a Code Coverage Tool .axoCover/* !.axoCover/settings.json # Coverlet is a free, cross platform Code Coverage Tool coverage*.json coverage*.xml coverage*.info # Visual Studio code coverage results *.coverage *.coveragexml # NCrunch _NCrunch_* .*crunch*.local.xml nCrunchTemp_* # MightyMoose *.mm.* AutoTest.Net/ # Web workbench (sass) .sass-cache/ # Installshield output folder [Ee]xpress/ # DocProject is a documentation generator add-in DocProject/buildhelp/ DocProject/Help/*.HxT DocProject/Help/*.HxC DocProject/Help/*.hhc DocProject/Help/*.hhk DocProject/Help/*.hhp DocProject/Help/Html2 DocProject/Help/html # Click-Once directory publish/ # Publish Web Output *.[Pp]ublish.xml *.azurePubxml # Note: Comment the next line if you want to checkin your web deploy settings, # but database connection strings (with potential passwords) will be unencrypted *.pubxml *.publishproj # Microsoft Azure Web App publish settings. Comment the next line if you want to # checkin your Azure Web App publish settings, but sensitive information contained # in these scripts will be unencrypted PublishScripts/ # NuGet Packages *.nupkg # NuGet Symbol Packages *.snupkg # The packages folder can be ignored because of Package Restore **/[Pp]ackages/* # except build/, which is used as an MSBuild target. !**/[Pp]ackages/build/ # Uncomment if necessary however generally it will be regenerated when needed #!**/[Pp]ackages/repositories.config # NuGet v3's project.json files produces more ignorable files *.nuget.props *.nuget.targets # Microsoft Azure Build Output csx/ *.build.csdef # Microsoft Azure Emulator ecf/ rcf/ # Windows Store app package directories and files AppPackages/ BundleArtifacts/ Package.StoreAssociation.xml _pkginfo.txt *.appx *.appxbundle *.appxupload # Visual Studio cache files # files ending in .cache can be ignored *.[Cc]ache # but keep track of directories ending in .cache !?*.[Cc]ache/ # Others ClientBin/ ~$* *~ *.dbmdl *.dbproj.schemaview *.jfm *.pfx *.publishsettings orleans.codegen.cs # Including strong name files can present a security risk # (https://github.com/github/gitignore/pull/2483#issue-259490424) #*.snk # Since there are multiple workflows, uncomment next line to ignore bower_components # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) #bower_components/ # RIA/Silverlight projects Generated_Code/ # Backup & report files from converting an old project file # to a newer Visual Studio version. Backup files are not needed, # because we have git ;-) _UpgradeReport_Files/ Backup*/ UpgradeLog*.XML UpgradeLog*.htm ServiceFabricBackup/ *.rptproj.bak # SQL Server files *.mdf *.ldf *.ndf # Business Intelligence projects *.rdl.data *.bim.layout *.bim_*.settings *.rptproj.rsuser *- [Bb]ackup.rdl *- [Bb]ackup ([0-9]).rdl *- [Bb]ackup ([0-9][0-9]).rdl # Microsoft Fakes FakesAssemblies/ # GhostDoc plugin setting file *.GhostDoc.xml # Node.js Tools for Visual Studio .ntvs_analysis.dat node_modules/ # Visual Studio 6 build log *.plg # Visual Studio 6 workspace options file *.opt # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) *.vbw # Visual Studio 6 auto-generated project file (contains which files were open etc.) *.vbp # Visual Studio 6 workspace and project file (working project files containing files to include in project) *.dsw *.dsp # Visual Studio 6 technical files # Visual Studio LightSwitch build output **/*.HTMLClient/GeneratedArtifacts **/*.DesktopClient/GeneratedArtifacts **/*.DesktopClient/ModelManifest.xml **/*.Server/GeneratedArtifacts **/*.Server/ModelManifest.xml _Pvt_Extensions # Paket dependency manager .paket/paket.exe paket-files/ # FAKE - F# Make .fake/ # CodeRush personal settings .cr/personal # Python Tools for Visual Studio (PTVS) __pycache__/ *.pyc # Cake - Uncomment if you are using it # tools/** # !tools/packages.config # Tabs Studio *.tss # Telerik's JustMock configuration file *.jmconfig # BizTalk build output *.btp.cs *.btm.cs *.odx.cs *.xsd.cs # OpenCover UI analysis results OpenCover/ # Azure Stream Analytics local run output ASALocalRun/ # MSBuild Binary and Structured Log *.binlog # NVidia Nsight GPU debugger configuration file *.nvuser # MFractors (Xamarin productivity tool) working folder .mfractor/ # Local History for Visual Studio .localhistory/ # Visual Studio History (VSHistory) files .vshistory/ # BeatPulse healthcheck temp database healthchecksdb # Backup folder for Package Reference Convert tool in Visual Studio 2017 MigrationBackup/ # Ionide (cross platform F# VS Code tools) working folder .ionide/ # Fody - auto-generated XML schema FodyWeavers.xsd # VS Code files for those working on multiple tools .vscode/* !.vscode/settings.json !.vscode/tasks.json !.vscode/launch.json !.vscode/extensions.json *.code-workspace # Local History for Visual Studio Code .history/ # Windows Installer files from build outputs *.cab *.msi *.msix *.msm *.msp # JetBrains Rider *.sln.iml ### VisualStudio Patch ### # Additional files built by Visual Studio *.vcxproj.* # End of https://www.toptal.com/developers/gitignore/api/visualstudio ================================================ FILE: Extensions/Extension1/JonMon-Ext1/JonMon-Ext1.vcxproj ================================================ Debug ARM Debug Win32 Release ARM Release Win32 Debug x64 Release x64 16.0 Win32Proj {bd72f0c3-dbd8-4ba2-8ff9-7f357f9232b1} JonMonExt1 10.0 DynamicLibrary true v143 Unicode DynamicLibrary false v143 true Unicode DynamicLibrary true v143 Unicode DynamicLibrary true v143 Unicode DynamicLibrary false v143 true Unicode DynamicLibrary false v143 true Unicode Level3 true WIN32;_DEBUG;JONMONEXT1_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) true Use pch.h Windows true false Level3 true true true WIN32;NDEBUG;JONMONEXT1_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) true Use pch.h Windows true true true false Level3 true _DEBUG;JONMONEXT1_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) true Use pch.h Windows true false Level3 true _DEBUG;JONMONEXT1_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) true Use pch.h Windows true false Level3 true true true NDEBUG;JONMONEXT1_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) true Use pch.h Windows true true true false Level3 true true true NDEBUG;JONMONEXT1_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) true Use pch.h Windows true true true false Create Create Create Create Create Create ================================================ FILE: Extensions/Extension1/JonMon-Ext1/dllmain.cpp ================================================ // // Author: Jonathan Johnson (@jsecurity101) // JonMon-Ext1.dll. This is the DLL that will be loaded by JonMon-Service.dll and will query threads to see if they are impersonating a token. // #include "pch.h" #include #include #include #include "tlhelp32.h" #include "sddl.h" #include "dllmain.h" #include "../../../JonMonProvider/jonmon.h" // // JonMon TraceLogging Provider Information // TRACELOGGING_DECLARE_PROVIDER(g_hJonMon); TRACELOGGING_DEFINE_PROVIDER(g_hJonMon, "JonMon", (0xdd82bf6f, 0x5295, 0x4541, 0x96, 0x8d, 0x8c, 0xac, 0x58, 0xe5, 0x72, 0xe4)); BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; } DWORD IntegritySID(HANDLE hToken, PDWORD *IntegrityLevel) { PSID pIntegritySid = NULL; PTOKEN_MANDATORY_LABEL pIntegrityLabel = NULL; DWORD retValue = 0; // // pull thread tokens integrity level // DWORD dwTokenInfoSize = 0; GetTokenInformation(hToken, TokenIntegrityLevel, NULL, 0, &dwTokenInfoSize); if (dwTokenInfoSize == 0) { printf("GetTokenInformation failed (%d)\n", GetLastError()); retValue = 1; goto Exit; } // // Allocate memory for the TOKEN_MANDATORY_LABEL structure // pIntegrityLabel = (PTOKEN_MANDATORY_LABEL)LocalAlloc(0, dwTokenInfoSize); if (!pIntegrityLabel) { printf("Memory allocation failed\n"); retValue = 1; goto Exit; } // // Get the TOKEN_MANDATORY_LABEL structure // if (!GetTokenInformation(hToken, TokenIntegrityLevel, pIntegrityLabel, dwTokenInfoSize, &dwTokenInfoSize)) { printf("GetTokenInformation failed (%d)\n", GetLastError()); retValue = 1; goto Exit; } // // Extract the integrity level SID from the TOKEN_MANDATORY_LABEL structure // pIntegritySid = pIntegrityLabel->Label.Sid; // Convert the integrity level SID to a human-readable string *IntegrityLevel = GetSidSubAuthority(pIntegritySid, (DWORD)(UCHAR)(*GetSidSubAuthorityCount(pIntegritySid) - 1)); Exit: // // Free resources // if (pIntegrityLabel != nullptr) { LocalFree(pIntegrityLabel); } return retValue; } DWORD TokenUserName(HANDLE hToken, LPWSTR* pStringSid) { DWORD retValue = 0; PTOKEN_USER processTokenUser = NULL; DWORD dwTokenInfoSize = 0; LPWSTR lpName = NULL; LPWSTR lpDomain = NULL; DWORD dwNameSize = 0; DWORD dwDomainSize = 0; SID_NAME_USE eSidType; PSID pUserSid = NULL; DWORD dwSize = 0; GetTokenInformation(hToken, TokenUser, NULL, 0, &dwTokenInfoSize); if (dwTokenInfoSize == 0) { printf("GetTokenInformation failed (%d)\n", GetLastError()); retValue = 1; goto Exit; } // Allocate memory for the TOKEN_USER structure processTokenUser = (PTOKEN_USER)LocalAlloc(LPTR, dwTokenInfoSize); if (processTokenUser == NULL) { printf("Memory allocation failed\n"); retValue = 1; goto Exit; } // Get the TOKEN_USER structure if (!GetTokenInformation(hToken, TokenUser, processTokenUser, dwTokenInfoSize, &dwTokenInfoSize)) { printf("GetTokenInformation failed (%d)\n", GetLastError()); retValue = 1; goto Exit; } // Extract the user SID from the TOKEN_USER structure pUserSid = processTokenUser->User.Sid; // First call to LookupAccountSid to get the buffer sizes LookupAccountSidW(NULL, pUserSid, NULL, &dwNameSize, NULL, &dwDomainSize, &eSidType); if (dwNameSize == 0 || dwDomainSize == 0) { printf("LookupAccountSidW failed (%d)\n", GetLastError()); retValue = 1; goto Exit; } // Allocate memory for name and domain lpName = (LPWSTR)LocalAlloc(0, dwNameSize * sizeof(WCHAR)); lpDomain = (LPWSTR)LocalAlloc(0, dwDomainSize * sizeof(WCHAR)); if (!lpName || !lpDomain) { printf("Memory allocation failed\n"); retValue = 1; goto Exit; } // Second call to LookupAccountSid to get the account name if (!LookupAccountSidW(NULL, pUserSid, lpName, &dwNameSize, lpDomain, &dwDomainSize, &eSidType)) { printf("LookupAccountSidW failed (%d)\n", GetLastError()); retValue = 1; goto Exit; } // // put together the username and domain into a string // dwSize = wcslen(lpName) + wcslen(lpDomain) + 2; // // Allocate memory for the string // *pStringSid = (LPWSTR)LocalAlloc(0, dwSize * sizeof(WCHAR)); // // put together the username and domain into a string // wsprintf(*pStringSid, L"%s\\%s", lpDomain, lpName); Exit: if (processTokenUser != NULL) { LocalFree(processTokenUser); } if (lpName != NULL) { LocalFree(lpName); } if (lpDomain != NULL) { LocalFree(lpDomain); } return retValue; } extern "C" void TokenImpersonationCheck() { TraceLoggingRegister(g_hJonMon); // // Loop every 60s to use message box // while (true) { // // Get snapshot of all threads // HANDLE hThreadSnap = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if (hThreadSnap == INVALID_HANDLE_VALUE) { printf("CreateToolhelp32Snapshot failed (%d)\n", GetLastError()); return; } // // for each thread attempt to get access token and print handle // THREADENTRY32 te32; te32.dwSize = sizeof(THREADENTRY32); if (!Thread32First(hThreadSnap, &te32)) { printf("Thread32First failed (%d)\n", GetLastError()); CloseHandle(hThreadSnap); return; } do { // // OpenThread with THREAD_QUERY_INFORMATION access right // HANDLE hThread = NULL; HANDLE hToken = NULL; HANDLE processToken = NULL; HANDLE pHandle = NULL; DWORD retValue = 0; TOKEN_STATISTICS tokenStats; DWORD dwReturnLength; LPWSTR threadTokenUser = NULL; LPWSTR processTokenUser = NULL; PDWORD threadIntegrityLevel = 0; PDWORD processIntegrityLevel = 0; SYSTEMTIME st; BOOL result; REGHANDLE RegistrationHandle = NULL; hThread = OpenThread(THREAD_QUERY_INFORMATION, FALSE, te32.th32ThreadID); if (hThread == NULL) { goto Exit; } // // Get thread access token // if (!OpenThreadToken(hThread, TOKEN_QUERY, FALSE, &hToken)) { goto Exit; } retValue = IntegritySID(hToken, &threadIntegrityLevel); if (retValue != 0) { goto Exit; } if (!GetTokenInformation(hToken, TokenStatistics, &tokenStats, sizeof(TOKEN_STATISTICS), &dwReturnLength)) { printf("GetTokenInformation failed (%d)\n", GetLastError()); goto Exit; } retValue = TokenUserName(hToken, &threadTokenUser); if (retValue != 0 || threadTokenUser == NULL) { goto Exit; } // // Print token handle and impersonation level // if (tokenStats.ImpersonationLevel != SecurityImpersonation && tokenStats.ImpersonationLevel != SecurityDelegation) { goto Exit; } pHandle = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, te32.th32OwnerProcessID); if (pHandle == NULL) { printf("OpenProcess failed (%d), ProcessID: %d\n", GetLastError(), te32.th32OwnerProcessID); goto Exit; } result = OpenProcessToken(pHandle, TOKEN_QUERY, &processToken); if (processToken == NULL) { printf("OpenProcessToken failed (%d) ProcessId: %d\n", GetLastError(), te32.th32OwnerProcessID); goto Exit; } retValue = IntegritySID(processToken, &processIntegrityLevel); if (retValue != 0) { printf("IntegritySID failed (%d)\n", GetLastError()); goto Exit; } retValue = TokenUserName(processToken, &processTokenUser); if (retValue != 0 || processTokenUser == NULL) { goto Exit; } if ((*processIntegrityLevel != 16384) && (wcscmp(processTokenUser, threadTokenUser) != 0)) { GetSystemTime(&st); TraceLoggingWrite( g_hJonMon, "16", TraceLoggingInt32(16, "EventID"), TraceLoggingUInt32(te32.th32ThreadID, "ThreadID"), TraceLoggingUInt32(te32.th32OwnerProcessID, "ProcessID"), TraceLoggingUInt32(*threadIntegrityLevel, "ThreadIntegrityLevel"), TraceLoggingSystemTime(st, "EventTime"), TraceLoggingWideString(threadTokenUser, "ImpersonatedUser") ); } Exit: if (threadTokenUser != NULL) { LocalFree(threadTokenUser); threadTokenUser = NULL; } if (processTokenUser != NULL) { LocalFree(processTokenUser); processTokenUser = NULL; } if (hThread != NULL) { CloseHandle(hThread); hThread = NULL; } if (hToken != NULL) { CloseHandle(hToken); hToken = NULL; } if (pHandle != NULL) { CloseHandle(pHandle); pHandle = NULL; } if (processToken != NULL) { CloseHandle(processToken); processToken = NULL; } } while (Thread32Next(hThreadSnap, &te32)); CloseHandle(hThreadSnap); Sleep(5000); } } ================================================ FILE: Extensions/Extension1/JonMon-Ext1/dllmain.h ================================================ #ifdef JONMON_EXPORTS #define JONMON_EXPORTS __declspec(dllexport) #else #define JONMON_EXPORTS __declspec(dllimport) #endif #include "Windows.h" #include "evntprov.h" #include "stdio.h" #include // // Export function that will query process tokens // extern "C" JONMON_EXPORTS void TokenImpersonationCheck(); ================================================ FILE: Extensions/Extension1/JonMon-Ext1/framework.h ================================================ #pragma once #define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers // Windows Header Files #include ================================================ FILE: Extensions/Extension1/JonMon-Ext1/pch.cpp ================================================ // pch.cpp: source file corresponding to the pre-compiled header #include "pch.h" // When you are using pre-compiled headers, this source file is necessary for compilation to succeed. ================================================ FILE: Extensions/Extension1/JonMon-Ext1/pch.h ================================================ // pch.h: This is a precompiled header file. // Files listed below are compiled only once, improving build performance for future builds. // This also affects IntelliSense performance, including code completion and many code browsing features. // However, files listed here are ALL re-compiled if any one of them is updated between builds. // Do not add files here that you will be updating frequently as this negates the performance advantage. #ifndef PCH_H #define PCH_H // add headers that you want to pre-compile here #include "framework.h" #endif //PCH_H ================================================ FILE: JonMon/JonMon.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.4.33205.214 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "JonMon", "JonMon.vcxproj", "{27DCE7FD-EC60-49F7-9245-A39DE05E7056}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "JonMon-Service", "..\JonMon-Service\JonMon-Service.vcxproj", "{BF810292-3774-41A4-B51E-CEF92E26894A}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "JonMon-Ext1", "..\Extensions\Extension1\JonMon-Ext1\JonMon-Ext1.vcxproj", "{BD72F0C3-DBD8-4BA2-8FF9-7F357F9232B1}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|ARM64 = Debug|ARM64 Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|ARM64 = Release|ARM64 Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {27DCE7FD-EC60-49F7-9245-A39DE05E7056}.Debug|ARM64.ActiveCfg = Debug|ARM64 {27DCE7FD-EC60-49F7-9245-A39DE05E7056}.Debug|ARM64.Build.0 = Debug|ARM64 {27DCE7FD-EC60-49F7-9245-A39DE05E7056}.Debug|ARM64.Deploy.0 = Debug|ARM64 {27DCE7FD-EC60-49F7-9245-A39DE05E7056}.Debug|x64.ActiveCfg = Debug|x64 {27DCE7FD-EC60-49F7-9245-A39DE05E7056}.Debug|x64.Build.0 = Debug|x64 {27DCE7FD-EC60-49F7-9245-A39DE05E7056}.Debug|x64.Deploy.0 = Debug|x64 {27DCE7FD-EC60-49F7-9245-A39DE05E7056}.Debug|x86.ActiveCfg = Debug|x64 {27DCE7FD-EC60-49F7-9245-A39DE05E7056}.Debug|x86.Build.0 = Debug|x64 {27DCE7FD-EC60-49F7-9245-A39DE05E7056}.Debug|x86.Deploy.0 = Debug|x64 {27DCE7FD-EC60-49F7-9245-A39DE05E7056}.Release|ARM64.ActiveCfg = Release|ARM64 {27DCE7FD-EC60-49F7-9245-A39DE05E7056}.Release|ARM64.Build.0 = Release|ARM64 {27DCE7FD-EC60-49F7-9245-A39DE05E7056}.Release|x64.ActiveCfg = Release|x64 {27DCE7FD-EC60-49F7-9245-A39DE05E7056}.Release|x64.Build.0 = Release|x64 {27DCE7FD-EC60-49F7-9245-A39DE05E7056}.Release|x64.Deploy.0 = Release|x64 {27DCE7FD-EC60-49F7-9245-A39DE05E7056}.Release|x86.ActiveCfg = Release|x64 {27DCE7FD-EC60-49F7-9245-A39DE05E7056}.Release|x86.Build.0 = Release|x64 {27DCE7FD-EC60-49F7-9245-A39DE05E7056}.Release|x86.Deploy.0 = Release|x64 {BF810292-3774-41A4-B51E-CEF92E26894A}.Debug|ARM64.ActiveCfg = Debug|x64 {BF810292-3774-41A4-B51E-CEF92E26894A}.Debug|ARM64.Build.0 = Debug|x64 {BF810292-3774-41A4-B51E-CEF92E26894A}.Debug|x64.ActiveCfg = Debug|x64 {BF810292-3774-41A4-B51E-CEF92E26894A}.Debug|x64.Build.0 = Debug|x64 {BF810292-3774-41A4-B51E-CEF92E26894A}.Debug|x86.ActiveCfg = Debug|Win32 {BF810292-3774-41A4-B51E-CEF92E26894A}.Debug|x86.Build.0 = Debug|Win32 {BF810292-3774-41A4-B51E-CEF92E26894A}.Release|ARM64.ActiveCfg = Release|x64 {BF810292-3774-41A4-B51E-CEF92E26894A}.Release|ARM64.Build.0 = Release|x64 {BF810292-3774-41A4-B51E-CEF92E26894A}.Release|x64.ActiveCfg = Release|x64 {BF810292-3774-41A4-B51E-CEF92E26894A}.Release|x64.Build.0 = Release|x64 {BF810292-3774-41A4-B51E-CEF92E26894A}.Release|x86.ActiveCfg = Release|Win32 {BF810292-3774-41A4-B51E-CEF92E26894A}.Release|x86.Build.0 = Release|Win32 {BD72F0C3-DBD8-4BA2-8FF9-7F357F9232B1}.Debug|ARM64.ActiveCfg = Debug|x64 {BD72F0C3-DBD8-4BA2-8FF9-7F357F9232B1}.Debug|ARM64.Build.0 = Debug|x64 {BD72F0C3-DBD8-4BA2-8FF9-7F357F9232B1}.Debug|x64.ActiveCfg = Debug|x64 {BD72F0C3-DBD8-4BA2-8FF9-7F357F9232B1}.Debug|x64.Build.0 = Debug|x64 {BD72F0C3-DBD8-4BA2-8FF9-7F357F9232B1}.Debug|x86.ActiveCfg = Debug|Win32 {BD72F0C3-DBD8-4BA2-8FF9-7F357F9232B1}.Debug|x86.Build.0 = Debug|Win32 {BD72F0C3-DBD8-4BA2-8FF9-7F357F9232B1}.Release|ARM64.ActiveCfg = Release|x64 {BD72F0C3-DBD8-4BA2-8FF9-7F357F9232B1}.Release|ARM64.Build.0 = Release|x64 {BD72F0C3-DBD8-4BA2-8FF9-7F357F9232B1}.Release|x64.ActiveCfg = Release|x64 {BD72F0C3-DBD8-4BA2-8FF9-7F357F9232B1}.Release|x64.Build.0 = Release|x64 {BD72F0C3-DBD8-4BA2-8FF9-7F357F9232B1}.Release|x86.ActiveCfg = Release|Win32 {BD72F0C3-DBD8-4BA2-8FF9-7F357F9232B1}.Release|x86.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {EA991FDB-4D7B-4F75-B564-463A826AC12F} EndGlobalSection EndGlobal ================================================ FILE: JonMon/JonMon.vcxproj ================================================  Debug ARM Debug x64 Release ARM Release x64 Debug ARM64 Release ARM64 {27DCE7FD-EC60-49F7-9245-A39DE05E7056} {dd38f7fc-d7bd-488b-9242-7d8754cde80d} v4.5 12.0 Debug x64 JonMon 10.0.26100.0 Windows10 true WindowsKernelModeDriver10.0 Driver WDM false Windows10 false WindowsKernelModeDriver10.0 Driver WDM false Windows10 true WindowsKernelModeDriver10.0 Driver WDM Windows10 false WindowsKernelModeDriver10.0 Driver WDM DbgengKernelDebugger DbgengKernelDebugger false DbgengKernelDebugger DbgengKernelDebugger DbgengKernelDebugger DbgengKernelDebugger sha256 Ksecdd.lib;FltMgr.lib;Setupapi.lib;%(AdditionalDependencies) /INTEGRITYCHECK %(AdditionalOptions) sha256 Ksecdd.lib;FltMgr.lib;%(AdditionalDependencies) /INTEGRITYCHECK %(AdditionalOptions) FltMgr.lib;%(AdditionalDependencies) FltMgr.lib;%(AdditionalDependencies) /INTEGRITYCHECK %(AdditionalOptions) ================================================ FILE: JonMon/callbacks.cpp ================================================ #include "callbacks.h" #include "process.h" #include "registry.h" #include "minifilter.h" PAGED_FILE(); #define MAX_PATH_LENGTH 100 PVOID ProcessRegistrationHandle = NULL; PVOID ThreadRegistrationHandle = NULL; LARGE_INTEGER Cookie; ULONG g_ServicePID = 0; PDRIVER_OBJECT g_DriverObject = NULL; EventSchema g_EventSchema = { FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, 0, 0 }; _IRQL_requires_max_(PASSIVE_LEVEL) NTSTATUS RegisterCallbacks( ) { PAGED_CODE(); NTSTATUS status = STATUS_SUCCESS; UNICODE_STRING Altitude; RtlInitUnicodeString(&Altitude, L"385202"); // // Checks global g_EventSchema to see if ConfigSet is set to false, if it is will sleep and recheck // while (g_EventSchema.ConfigSet == FALSE) { LARGE_INTEGER interval; interval.QuadPart = -10000000; // 1 second KeDelayExecutionThread(KernelMode, FALSE, &interval); } if(g_EventSchema.ProcessCreation == TRUE) { status = PsSetCreateProcessNotifyRoutineEx(CreateProcessNotifyRoutineEx, FALSE); if (!NT_SUCCESS(status)) { DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "Failed to load PsSetCreateProcessNotifyRoutineEx : 0x%X\n", status); return status; } DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "PsSetCreateProcessNotifyRoutineEx Loaded\n"); } if(g_EventSchema.ProcessTermination == TRUE) { status = PsSetCreateProcessNotifyRoutine(TerminateProcessNotifyRoutine, FALSE); if (!NT_SUCCESS(status)) { DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "Failed to load PsSetCreateProcessNotifyRoutine : 0x%X\n", status); return status; } DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "PsSetCreateProcessNotifyRoutine Loaded\n"); } if(g_EventSchema.RemoteThreadCreation == TRUE) { status = PsSetCreateThreadNotifyRoutine(PsCreateThreadNotifyRoutine); if (!NT_SUCCESS(status)) { DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "Failed to load PsSetCreateThreadNotifyRoutine : 0x%X\n", status); return status; } DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "PsSetCreateThreadNotifyRoutine Loaded\n"); } if(g_EventSchema.ImageLoad == TRUE) { status = PsSetLoadImageNotifyRoutine(LoadImageRoutine); if (!NT_SUCCESS(status)) { DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "Failed to load PsSetLoadImageNotifyRoutine : 0x%X\n", status); return status; } DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "PsSetLoadImageNotifyRoutine Loaded\n"); } if(g_EventSchema.ProcessHandleCreation == TRUE || g_EventSchema.ProcessHandleDuplication == TRUE) { // //Setting up callback for PsProcessType // OB_CALLBACK_REGISTRATION CallbackRegistration; OB_OPERATION_REGISTRATION OperationRegistration; OperationRegistration.ObjectType = PsProcessType; if(g_EventSchema.ProcessHandleDuplication == TRUE && g_EventSchema.ProcessHandleCreation == TRUE) { OperationRegistration.Operations = OB_OPERATION_HANDLE_CREATE | OB_OPERATION_HANDLE_DUPLICATE; } else if(g_EventSchema.ProcessHandleCreation == TRUE && g_EventSchema.ProcessHandleDuplication == FALSE) { OperationRegistration.Operations = OB_OPERATION_HANDLE_CREATE; } else if(g_EventSchema.ProcessHandleDuplication == TRUE && g_EventSchema.ProcessHandleCreation == FALSE) { OperationRegistration.Operations = OB_OPERATION_HANDLE_DUPLICATE; } OperationRegistration.PreOperation = NULL; OperationRegistration.PostOperation = PostProcessHandleCallback; // // Setting members // CallbackRegistration.Version = OB_FLT_REGISTRATION_VERSION; CallbackRegistration.OperationRegistrationCount = 1; CallbackRegistration.Altitude = Altitude; CallbackRegistration.RegistrationContext = NULL; CallbackRegistration.OperationRegistration = &OperationRegistration; status = ObRegisterCallbacks(&CallbackRegistration, &ProcessRegistrationHandle); if (!NT_SUCCESS(status)) { DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "Failed to load ObRegisterCallbacks : 0x%X\n", status); return status; } DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "ObRegisterCallbacks Loaded\n"); } if(g_EventSchema.File == TRUE) { status = FltCallbackStart(g_DriverObject); if (!NT_SUCCESS(status)) { DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "Failed to load FltCallbackStart : 0x%X\n", status); return status; } DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "FltCallbackStart Loaded\n"); } if (g_EventSchema.Registry == TRUE) { status = CmRegisterCallbackEx(RegistryCallback, &Altitude, g_DriverObject, NULL, &Cookie, NULL); if (!NT_SUCCESS(status)) { DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "Failed to load CmRegisterCallbackEx : 0x%X\n", status); return status; } DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "CmRegisterCallbackEx Loaded\n"); } PsTerminateSystemThread(STATUS_SUCCESS); return status; } _IRQL_requires_max_(PASSIVE_LEVEL) VOID LoadImageRoutine( _In_ PUNICODE_STRING FullImageName, _In_ HANDLE ProcessId, _In_ PIMAGE_INFO ImageInfo ) { FILETIME fileTime; KeQuerySystemTime(&fileTime); PAGED_CODE(); ULONGLONG ProcessStartKey = PsGetProcessStartKey(PsGetCurrentProcess()); TraceLoggingWrite( g_hJonMon, "ImageLoad", TraceLoggingInt32(4, "EventID"), TraceLoggingValue(ProcessId, "ProcessId"), TraceLoggingValue(ProcessStartKey, "ProcessStartKey"), TraceLoggingValue(PsGetCurrentThreadId(), "ThreadId"), TraceLoggingValue(ImageInfo->SystemModeImage, "SystemModeImage"), TraceLoggingWideString(FullImageName->Buffer, "ImagePath"), TraceLoggingFileTime(fileTime, "FileTime") ); } BOOLEAN ContainsSubstring(PCWSTR keyPath, PCWSTR substring) { size_t keyPathLen = wcslen(keyPath); size_t substringLen = wcslen(substring); if (keyPathLen < substringLen) { return FALSE; } for (PCWSTR p = keyPath; *p != L'\0'; p++) { if (wcsncmp(p, substring, substringLen) == 0) { return TRUE; } } return FALSE; } _IRQL_requires_max_(PASSIVE_LEVEL) NTSTATUS RegistryCallback( _In_ PVOID CallbackContext, _In_ PVOID RegNotifyClass, _In_ PVOID RegObject ) { // //IRQL less == Passive, if not exit // if (KeGetCurrentIrql() > PASSIVE_LEVEL) { return STATUS_UNSUCCESSFUL; } PCWSTR keyPath = NULL; FILETIME fileTime; REG_NOTIFY_CLASS notifyClass = (REG_NOTIFY_CLASS)(ULONG_PTR)RegNotifyClass; NTSTATUS status = STATUS_SUCCESS; PAGED_CODE(); UNREFERENCED_PARAMETER(CallbackContext); if (RegObject == NULL) { DbgPrint("Callback RegObject is NULL. \n"); status = STATUS_UNSUCCESSFUL; goto Exit; } KeQuerySystemTime(&fileTime); ULONGLONG sourceProcessId = HandleToULong(PsGetCurrentProcessId()); ULONGLONG sourceThreadId = HandleToULong(PsGetCurrentThreadId()); switch (notifyClass) { case RegNtPostCreateKeyEx: { PREG_POST_OPERATION_INFORMATION object = (PREG_POST_OPERATION_INFORMATION)RegObject; if (object->Status != STATUS_SUCCESS) { DbgPrint("[RegNtPostCreateKeyEx] - Status is not success. Status 0x%x\n", object->Status); goto Exit; } PREG_CREATE_KEY_INFORMATION_V1 info = (PREG_CREATE_KEY_INFORMATION_V1)object->PreInformation; if (*info->Disposition != REG_CREATED_NEW_KEY ) { DbgPrint("[RegNtPostCreateKeyEx] - Disposition is not REG_CREATED_NEW_KEY. Disposition 0x%x\n", *info->Disposition); goto Exit; } status = GetRegistryKeyPath(object->Object, REGISTRY_TAG, &keyPath); if (status != STATUS_SUCCESS || keyPath == NULL) { DbgPrint("[RegNtPostCreateKeyEx] - GetRegistryKeyPath failed. Status 0x%x\n", status); goto Exit; } TraceLoggingWrite( g_hJonMon, "RegCreateKey", TraceLoggingInt32(9, "EventID"), TraceLoggingValue(sourceThreadId, "SourceThreadId"), TraceLoggingValue(sourceProcessId, "SourceProcessId"), TraceLoggingValue(PsGetProcessStartKey(PsGetCurrentProcess()), "SourceProcessStartKey"), TraceLoggingWideString(keyPath, "KeyPath"), TraceLoggingValue(info->DesiredAccess, "DesiredAccess"), TraceLoggingFileTime(fileTime, "FileTime") ); break; } case RegNtPostSaveKey: { PREG_POST_OPERATION_INFORMATION object = (PREG_POST_OPERATION_INFORMATION)RegObject; if (object->Status == STATUS_SUCCESS) { status = GetRegistryKeyPath(object->Object, REGISTRY_TAG, &keyPath); if (keyPath == NULL) { goto Exit; } TraceLoggingWrite( g_hJonMon, "RegSaveKey", TraceLoggingInt32(6, "EventID"), TraceLoggingValue(sourceThreadId, "SourceThreadId"), TraceLoggingValue(sourceProcessId, "SourceProcessId"), TraceLoggingValue(PsGetProcessStartKey(PsGetCurrentProcess()), "SourceProcessStartKey"), TraceLoggingWideString(keyPath, "KeyPath"), TraceLoggingFileTime(fileTime, "FileTime") ); } break; } case RegNtPreDeleteKey: { PREG_DELETE_KEY_INFORMATION object = (PREG_DELETE_KEY_INFORMATION)RegObject; if (object->Object == NULL) { goto Exit; } status = GetRegistryKeyPath(object->Object, REGISTRY_TAG, &keyPath); if (keyPath == NULL) { goto Exit; } TraceLoggingWrite( g_hJonMon, "RegDeleteKey", TraceLoggingInt32(7, "EventID"), TraceLoggingValue(sourceThreadId, "SourceThreadId"), TraceLoggingValue(sourceProcessId, "SourceProcessId"), TraceLoggingValue(PsGetProcessStartKey(PsGetCurrentProcess()), "SourceProcessStartKey"), TraceLoggingWideString(keyPath, "KeyPath"), TraceLoggingFileTime(fileTime, "FileTime") ); break; } case RegNtPostSetValueKey: { UNICODE_STRING valueData; PREG_POST_OPERATION_INFORMATION postObject = (PREG_POST_OPERATION_INFORMATION)RegObject; if (postObject->Status != STATUS_SUCCESS) { goto Exit; } PREG_SET_VALUE_KEY_INFORMATION info = (PREG_SET_VALUE_KEY_INFORMATION)postObject->PreInformation; if (info->ValueName == NULL || info->ValueName->Length == 0) { goto Exit; } status = GetRegistryKeyPath(info->Object, REGISTRY_TAG, &keyPath); if (status != STATUS_SUCCESS || keyPath == NULL) { DbgPrint("[RegNtPostSetValueKey] - GetRegistryKeyPath failed. Status 0x%x", status); goto Exit; } if (info->DataSize <= 0) { goto Exit; } if(info->Data == NULL) { goto Exit; } // // Reducing noise // if (ContainsSubstring(keyPath, L"DeliveryOptimization\\Usage")) { goto Exit; } if (ContainsSubstring(keyPath, L"\\DeliveryOptimization\\Config")) { goto Exit; } if (ContainsSubstring(keyPath, L"\\Microsoft\\Input\\TypingInsights")) { goto Exit; } if (ContainsSubstring(keyPath, L"\\REGISTRY\\MACHINE\\SYSTEM\\ControlSet001\\Services\\W32Time")) { goto Exit; } if (ContainsSubstring(keyPath, L"\\REGISTRY\\A\\")) { goto Exit; } // // Fixing valueName buffer // UNICODE_STRING valueName; valueName.Length = info->ValueName->Length; valueName.MaximumLength = info->ValueName->Length + sizeof(UNICODE_NULL); valueName.Buffer = (PWSTR)ExAllocatePool2(POOL_FLAG_PAGED, valueName.MaximumLength, SYSTEM_THREAD_TAG); // Use valueName.Length here. if (valueName.Buffer == NULL || valueName.Length == 0) { goto Exit; } RtlZeroMemory(valueName.Buffer, valueName.MaximumLength); RtlCopyMemory(valueName.Buffer, info->ValueName->Buffer, info->ValueName->Length); // // adding null terminator // valueName.Buffer[valueName.Length / sizeof(WCHAR)] = UNICODE_NULL; // // Creating a UNICODE_STRING to hold the data information // valueData.Length = (USHORT)info->DataSize; valueData.MaximumLength = valueData.Length + sizeof(WCHAR); // Account for null terminator valueData.Buffer = (PWSTR)ExAllocatePool2(POOL_FLAG_PAGED, valueData.MaximumLength, SYSTEM_THREAD_TAG); if (valueData.Buffer == NULL || valueData.MaximumLength == 0) { goto Exit; } RtlZeroMemory(valueData.Buffer, valueData.MaximumLength); // // To do: Update REG_MULTI_SZ and REG_BINARY // switch (info->Type) { case REG_SZ: { RtlCopyMemory(valueData.Buffer, info->Data, valueData.Length); valueData.Buffer[valueData.Length / sizeof(WCHAR)] = UNICODE_NULL; // Set null terminator break; } case REG_EXPAND_SZ: { RtlCopyMemory(valueData.Buffer, info->Data, valueData.Length); valueData.Buffer[valueData.Length / sizeof(WCHAR)] = UNICODE_NULL; // Set null terminator break; } case REG_MULTI_SZ: { RtlCopyMemory(valueData.Buffer, info->Data, valueData.Length); // Ensure the data is properly double-null terminated if (valueData.Length >= sizeof(WCHAR) && valueData.Buffer[(valueData.Length / sizeof(WCHAR)) - 1] != UNICODE_NULL) { // Add an additional null terminator if the last character isn't already a null terminator valueData.Buffer[valueData.Length / sizeof(WCHAR)] = UNICODE_NULL; // First null terminator valueData.Buffer[(valueData.Length / sizeof(WCHAR)) + 1] = UNICODE_NULL; // Second null terminator } else { // If the data already ends with a null, just add another valueData.Buffer[valueData.Length / sizeof(WCHAR)] = UNICODE_NULL; } break; } case REG_DWORD: { RtlStringCchPrintfW(valueData.Buffer, valueData.MaximumLength / sizeof(WCHAR), L"%d", *(DWORD*)info->Data); break; } case REG_QWORD: { RtlStringCchPrintfW(valueData.Buffer, valueData.MaximumLength / sizeof(WCHAR), L"%lld", *(ULONGLONG*)info->Data); break; } case REG_BINARY: { RtlStringCchPrintfW(valueData.Buffer, valueData.MaximumLength / sizeof(WCHAR), L"%d", *(DWORD*)info->Data); break; } default: { break; } } // // check each field below to see if it is null lol // if (keyPath == NULL) { DbgPrint("keyPath is NULL\n"); } if (valueName.Buffer == NULL) { DbgPrint("valueName.Buffer is NULL\n"); } if (valueData.Buffer == NULL) { DbgPrint("valueData.Buffer is NULL\n"); } if(info->Type == NULL) { DbgPrint("info->Type is NULL\n"); } if(info->DataSize == NULL) { DbgPrint("info->DataSize is NULL\n"); } TraceLoggingWrite( g_hJonMon, "RegSetValueKey", TraceLoggingInt32(8, "EventID"), TraceLoggingValue(sourceThreadId, "SourceThreadId"), TraceLoggingValue(sourceProcessId, "SourceProcessId"), TraceLoggingValue(PsGetProcessStartKey(PsGetCurrentProcess()), "SourceProcessStartKey"), TraceLoggingWideString(keyPath, "KeyPath"), TraceLoggingWideString(valueName.Buffer, "ValueName"), TraceLoggingValue(valueData.Buffer, "Data"), TraceLoggingValue(info->Type, "Type"), TraceLoggingValue(info->DataSize, "DataSize"), TraceLoggingFileTime(fileTime, "FileTime") ); if(valueName.Buffer != NULL) { ExFreePoolWithTag(valueName.Buffer, SYSTEM_THREAD_TAG); } if(valueData.Buffer != NULL) { ExFreePoolWithTag(valueData.Buffer, SYSTEM_THREAD_TAG); } break; } default: { break; } } Exit: if (keyPath != NULL) { ExFreePoolWithTag((PVOID)keyPath, REGISTRY_TAG); } return status; } _IRQL_requires_max_(PASSIVE_LEVEL) void PsCreateThreadNotifyRoutine( _In_ HANDLE ProcessId, _In_ HANDLE ThreadId, _In_ BOOLEAN Create ) { NTSTATUS status; PEPROCESS sourceProcess; PEPROCESS targetProcess; FILETIME filetime; KeQuerySystemTime(&filetime); PAGED_CODE(); // // Check if the thread is being created or deleted // if (Create != TRUE) { goto Exit; } HANDLE CurrentPID = PsGetCurrentProcessId(); if (CurrentPID == ProcessId) { goto Exit; } if (CurrentPID == (HANDLE)0x4) { goto Exit; } if (ProcessId == (HANDLE)0x4) { goto Exit; } HANDLE sourceThreadId = PsGetCurrentThreadId(); status = PsLookupProcessByProcessId(ProcessId, &targetProcess); if (status != STATUS_SUCCESS) { DbgPrint("Failed to get target process, status: %d", status); goto Exit; } status = PsLookupProcessByProcessId(CurrentPID, &sourceProcess); if (status != STATUS_SUCCESS) { DbgPrint("Failed to get source process, status: %d", status); goto Exit; } ULONGLONG sourceProcStartKey = PsGetProcessStartKey(sourceProcess); ULONGLONG targetProcStartKey = PsGetProcessStartKey(targetProcess); TraceLoggingWrite( g_hJonMon, "RemoteThreadCreation", TraceLoggingInt32(3, "EventID"), TraceLoggingValue(sourceThreadId, "SourceThreadId"), TraceLoggingValue(CurrentPID, "SourceProcessId"), TraceLoggingValue(sourceProcStartKey, "SourceProcessStartKey"), TraceLoggingValue(ThreadId, "NewThreadId"), TraceLoggingValue(ProcessId, "TargetProcessId"), TraceLoggingValue(targetProcStartKey, "TargetProcessStartKey"), TraceLoggingFileTime(filetime, "FileTime") ); Exit: return; } _IRQL_requires_max_(PASSIVE_LEVEL) void CreateProcessNotifyRoutineEx( _In_ PEPROCESS Process, _In_ HANDLE ProcessId, _In_ PPS_CREATE_NOTIFY_INFO CreateInfo ) { FILETIME fileTime; UNICODE_STRING commandLine{ 0 }; PAGED_CODE(); if (CreateInfo == NULL) { goto Exit; } KeQuerySystemTime(&fileTime); ULONGLONG ProcessStartKey = PsGetProcessStartKey(Process); ULONGLONG parentProcessStartKey = PsGetProcessStartKey(PsGetCurrentProcess()); // //Checking to see if CommandLine is NULL and if it isn't, creating a buffer // if (CreateInfo->CommandLine != NULL) { // //create buffer // commandLine.Buffer = (PWSTR)ExAllocatePool2(POOL_FLAG_PAGED, CreateInfo->CommandLine->Length + sizeof(UNICODE_NULL), SYSTEM_THREAD_TAG); if (commandLine.Buffer == NULL) { goto Exit; } // //Zero out the buffer // RtlZeroMemory(commandLine.Buffer, CreateInfo->CommandLine->Length + sizeof(UNICODE_NULL)); // //Copy the CommandLine into the buffer // RtlCopyMemory(commandLine.Buffer, CreateInfo->CommandLine->Buffer, CreateInfo->CommandLine->Length); // //Null terminate the buffer // commandLine.Buffer[CreateInfo->CommandLine->Length / sizeof(UNICODE_NULL)] = UNICODE_NULL; } else { commandLine.Buffer = L"NULL"; commandLine.Length = sizeof(L"NULL"); commandLine.MaximumLength = sizeof(L"NULL") + sizeof(UNICODE_NULL); } // // TraceLogging Event // TraceLoggingWrite( g_hJonMon, "ProcessCreation", TraceLoggingInt32(1, "EventID"), TraceLoggingValue(ProcessId, "ProcessId"), TraceLoggingValue(ProcessStartKey, "ProcessStartKey"), TraceLoggingValue(CreateInfo->ParentProcessId, "ParentProcessId"), TraceLoggingValue(parentProcessStartKey, "ParentProcessStartKey"), TraceLoggingValue(CreateInfo->CreatingThreadId.UniqueProcess, "CreatorProcessId"), TraceLoggingValue(CreateInfo->CreatingThreadId.UniqueThread, "CreatorThreadId"), TraceLoggingWideString(commandLine.Buffer, "CommandLine"), TraceLoggingFileTime(fileTime, "FileTime") ); Exit: if (commandLine.Buffer != NULL) { ExFreePoolWithTag(commandLine.Buffer, SYSTEM_THREAD_TAG); } } _IRQL_requires_max_(PASSIVE_LEVEL) void PostProcessHandleCallback( _In_ PVOID RegistrationContext, _In_ POB_POST_OPERATION_INFORMATION OperationInformation ) { UNREFERENCED_PARAMETER(RegistrationContext); FILETIME filetime; DWORD OperationType; ACCESS_MASK DesiredAccess; PAGED_CODE(); KeQuerySystemTime(&filetime); PEPROCESS targetProcess = (PEPROCESS)OperationInformation->Object; HANDLE TargetProcessId = PsGetProcessId(targetProcess); HANDLE SourceProcessId = PsGetCurrentProcessId(); DesiredAccess = OperationInformation->Parameters->CreateHandleInformation.GrantedAccess; if ((HANDLE)g_ServicePID == SourceProcessId) { goto Exit; } if (DesiredAccess == 0x0) { goto Exit; } if (SourceProcessId == TargetProcessId) { goto Exit; } if (SourceProcessId == (HANDLE)0x4 || TargetProcessId == (HANDLE)0x4) { goto Exit; } switch (OperationInformation->Operation) { case OB_OPERATION_HANDLE_CREATE: { OperationType = 1; break; } case OB_OPERATION_HANDLE_DUPLICATE: { if ((DesiredAccess & 0x40) != 0x40) { goto Exit; } DesiredAccess = OperationInformation->Parameters->DuplicateHandleInformation.GrantedAccess; OperationType = 2; break; } } TraceLoggingWrite( g_hJonMon, "ProcessHandle", TraceLoggingInt32(5, "EventID"), TraceLoggingValue(PsGetCurrentThreadId(), "SourceThreadId"), TraceLoggingValue(SourceProcessId, "SourceProcessId"), TraceLoggingValue(PsGetProcessStartKey(PsGetCurrentProcess()), "SourceProcessStartKey"), TraceLoggingValue(TargetProcessId, "TargetProcessId"), TraceLoggingValue(PsGetProcessStartKey(targetProcess), "TargetProcessStartKey"), TraceLoggingValue(OperationType, "OperationType"), TraceLoggingValue(DesiredAccess, "DesiredAccess"), TraceLoggingFileTime(filetime, "FileTime") ); Exit: return; } _IRQL_requires_max_(PASSIVE_LEVEL) void TerminateProcessNotifyRoutine( _In_ HANDLE ParentProcessId, _In_ HANDLE ProcessId, _In_ BOOLEAN Create ) { FILETIME fileTime; PAGED_CODE(); if (!Create) { KeQuerySystemTime(&fileTime); ULONGLONG sourceProcessStartKey = PsGetProcessStartKey(PsGetCurrentProcess()); ULONGLONG targetProcessStartKey = PsGetProcessStartKey(PsGetCurrentProcess()); TraceLoggingWrite( g_hJonMon, "ProcessTermination", TraceLoggingInt32(2, "EventID"), TraceLoggingValue(ProcessId, "ProcessId"), TraceLoggingValue(targetProcessStartKey, "ProcessStartKey"), TraceLoggingValue(ParentProcessId, "ParentProcessId"), TraceLoggingValue(sourceProcessStartKey, "ParentProcessStartKey"), TraceLoggingFileTime(fileTime, "FileTime") ); goto Exit; } Exit: return; } ================================================ FILE: JonMon/callbacks.h ================================================ #ifndef _CALLBACK_ #define _CALLBACK_ #include "shared.h" extern ULONG g_ServicePID; extern PVOID ProcessRegistrationHandle; extern PVOID ThreadRegistrationHandle; extern PDRIVER_OBJECT g_DriverObject; typedef struct _EventSchema { BOOLEAN ConfigSet; BOOLEAN ProcessCreation; BOOLEAN ProcessTermination; BOOLEAN ProcessHandleCreation; BOOLEAN ProcessHandleDuplication; BOOLEAN RemoteThreadCreation; BOOLEAN ImageLoad; BOOLEAN File; BOOLEAN Registry; INT ConfigVersion; INT JonMonVersion; } EventSchema, * PEventSchema; typedef struct _HANDLE_CREATION_CALLBACK_INFO { ULONGLONG SourceProcessStartKey; HANDLE SourceProcessId; HANDLE SourceThreadId; HANDLE TargetProcessId; PETHREAD SourceThread; ULONGLONG TargetProcessStartKey; ACCESS_MASK DesiredAccess; FILETIME FileTime; DWORD OperationType; } HANDLE_CREATION_CALLBACK_INFO, * PHANDLE_CREATION_CALLBACK_INFO; typedef struct _LOAD_IMAGE_CALLBACK_INFO { HANDLE SourceProcessId; HANDLE SourceThread; PETHREAD SourceEThread; FILETIME FileTime; UNICODE_STRING ModuleName; ULONG SystemModeImage; } LOAD_IMAGE_CALLBACK_INFO, * PLOAD_IMAGE_CALLBACK_INFO; typedef struct _PROCESS_CREATE_CALLBACK_INFO { PEPROCESS Process; HANDLE ProcessId; FILETIME FileTime; HANDLE ParentProcessId; CLIENT_ID CreatorId; UNICODE_STRING CommandLine; } PROCESS_CREATE_CALLBACK_INFO, * PPROCESS_CREATE_CALLBACK_INFO; typedef struct _THREAD_CREATE_CALLBACK_INFO { HANDLE SourceProcessId; HANDLE TargetProcessId; HANDLE TargetThreadId; FILETIME FileTime; } THREAD_CREATE_CALLBACK_INFO, * PTHREAD_CREATE_CALLBACK_INFO; typedef struct _PROCESS_TERMINATE_CALLBACK_INFO { FILETIME FileTime; HANDLE SourceProcessId; HANDLE TargetProcessId; } PROCESS_TERMINATE_CALLBACK_INFO, * PPROCESS_TERMINATE_CALLBACK_INFO; // // global variable to store the schema // extern EventSchema g_EventSchema; _IRQL_requires_max_(PASSIVE_LEVEL) NTSTATUS RegisterCallbacks( ); _IRQL_requires_max_(PASSIVE_LEVEL) VOID CreateProcessNotifyRoutineEx( _In_ PEPROCESS Process, _In_ HANDLE ProcessId, _In_ PPS_CREATE_NOTIFY_INFO CreateInfo ); _IRQL_requires_max_(PASSIVE_LEVEL) VOID PsCreateThreadNotifyRoutine( _In_ HANDLE ProcessId, _In_ HANDLE ThreadId, _In_ BOOLEAN Create ); _IRQL_requires_max_(PASSIVE_LEVEL) VOID TerminateProcessNotifyRoutine( _In_ HANDLE ParentProcessId, _In_ HANDLE ProcessId, _In_ BOOLEAN Create ); _IRQL_requires_max_(PASSIVE_LEVEL) VOID LoadImageWorkerThread( _In_ PVOID StartContext ); _IRQL_requires_max_(PASSIVE_LEVEL) VOID LoadImageRoutine( _In_ PUNICODE_STRING FullImageName, _In_ HANDLE ProcessId, _In_ PIMAGE_INFO ImageInfo ); _IRQL_requires_max_(PASSIVE_LEVEL) void PostProcessHandleCallback( _In_ PVOID RegistrationContext, _In_ POB_POST_OPERATION_INFORMATION OperationInformation ); _IRQL_requires_max_(PASSIVE_LEVEL) NTSTATUS RegistryCallback( _In_ PVOID CallbackContext, _In_ PVOID RegNotifyClass, _In_ PVOID RegObject ); #endif // !_CALLBACK_ ================================================ FILE: JonMon/driver.cpp ================================================ #include "driver.h" #include "callbacks.h" #include "process.h" TRACELOGGING_DEFINE_PROVIDER(g_hJonMon, "JonMon", (0xdd82bf6f, 0x5295, 0x4541, 0x96, 0x8d, 0x8c, 0xac, 0x58, 0xe5, 0x72, 0xe4)); extern "C" NTSTATUS DriverEntry( _In_ PDRIVER_OBJECT DriverObject, _In_ PUNICODE_STRING RegistryPath ) { TraceLoggingRegister(g_hJonMon); TraceLoggingWrite( g_hJonMon, "100", TraceLoggingInt32(100, "EventID"), TraceLoggingBool(TRUE, "TraceLogging Provider Registered") ); g_RegPath.Buffer = (PWSTR)ExAllocatePool2(POOL_FLAG_PAGED, RegistryPath->Length, DRIVER_TAG); if (g_RegPath.Buffer == NULL) { DbgPrint("Failed allocation\n"); return STATUS_INSUFFICIENT_RESOURCES; } // //Copy DriverObject to global variable // g_DriverObject = DriverObject; g_RegPath.Length = g_RegPath.MaximumLength = RegistryPath->Length; memcpy(g_RegPath.Buffer, RegistryPath->Buffer, g_RegPath.Length); DriverObject->DriverUnload = JonMonUnload; DriverObject->MajorFunction[IRP_MJ_CREATE] = JonMonCreateClose; DriverObject->MajorFunction[IRP_MJ_CLOSE] = JonMonCreateClose; DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = JonMonDeviceControl; UNICODE_STRING name; RtlInitUnicodeString(&name, L"\\Device\\JonMon"); PDEVICE_OBJECT DeviceObject; NTSTATUS status = IoCreateDevice(DriverObject, 0, &name, FILE_DEVICE_UNKNOWN, 0, FALSE, &DeviceObject); if (!NT_SUCCESS(status)) { DbgPrint("Error creating device: 0x%X\n", status); ExFreePool(g_RegPath.Buffer); return status; } DriverObject->DeviceObject = DeviceObject; DeviceObject->Flags |= DO_DIRECT_IO; UNICODE_STRING symlink; RtlInitUnicodeString(&symlink, L"\\??\\JonMon"); status = IoCreateSymbolicLink(&symlink, &name); if (!NT_SUCCESS(status)) { DbgPrint("Error creating device: 0x%X\n", status); ExFreePool(g_RegPath.Buffer); IoDeleteDevice(DeviceObject); return status; } ExFreePool(g_RegPath.Buffer); return status; } NTSTATUS JonMonDeviceControl( _In_ PDEVICE_OBJECT, _In_ PIRP Irp ) { auto irpSp = IoGetCurrentIrpStackLocation(Irp); auto status = STATUS_INVALID_DEVICE_REQUEST; auto& dic = irpSp->Parameters.DeviceIoControl; auto len = 0; switch (dic.IoControlCode) { case IOCTL_CHANGE_PROTECTION_LEVEL_PROCESS: { ChangePPL(); } case IOCTL_EVENT_CONFIGURATION: { if (dic.InputBufferLength < sizeof(EventSchema)) { status = STATUS_BUFFER_TOO_SMALL; break; } auto schema = (EventSchema*)Irp->AssociatedIrp.SystemBuffer; if (schema == nullptr) { status = STATUS_INVALID_PARAMETER; break; } g_EventSchema.ConfigSet = true; g_EventSchema.ConfigVersion = schema->ConfigVersion; g_EventSchema.JonMonVersion = schema->JonMonVersion; g_EventSchema.ProcessCreation = schema->ProcessCreation; g_EventSchema.ProcessTermination = schema->ProcessTermination; g_EventSchema.Registry = schema->Registry; g_EventSchema.ProcessHandleCreation = schema->ProcessHandleCreation; g_EventSchema.ProcessHandleDuplication = schema->ProcessHandleDuplication; g_EventSchema.RemoteThreadCreation = schema->RemoteThreadCreation; g_EventSchema.ImageLoad = schema->ImageLoad; g_EventSchema.File = schema->File; // // TraceLogging Event // TraceLoggingWrite( g_hJonMon, "101", TraceLoggingInt32(101, "EventID"), TraceLoggingBool(schema->ProcessCreation, "ProcessCreation"), TraceLoggingBool(schema->ProcessTermination, "ProcessTermination"), TraceLoggingBool(schema->Registry, "RegistryEvents"), TraceLoggingBool(schema->ProcessHandleCreation, "ProcessHandleCreation"), TraceLoggingBool(schema->ProcessHandleDuplication, "ProcessHandleDuplication"), TraceLoggingBool(schema->RemoteThreadCreation, "RemoteThreadCreation"), TraceLoggingBool(schema->ImageLoad, "ImageLoad"), TraceLoggingBool(schema->File, "FileEvents") ); HANDLE hRegisterCallbackThread = NULL; OBJECT_ATTRIBUTES objectAttributes; InitializeObjectAttributes(&objectAttributes, NULL, OBJ_KERNEL_HANDLE, NULL, NULL); status = PsCreateSystemThread(&hRegisterCallbackThread, THREAD_ALL_ACCESS, &objectAttributes, NULL, NULL, (PKSTART_ROUTINE)RegisterCallbacks, NULL); if (!NT_SUCCESS(status)) { DbgPrint("PsCreateSystemThread - RegisterCallback failed: %x\n", status); } if (hRegisterCallbackThread != NULL) { ZwClose(hRegisterCallbackThread); } status = STATUS_SUCCESS; break; } default: break; } return CompleteRequest(Irp, status, len); } VOID AlterPPL( _In_ ULONG PID, _In_ ULONG value ) { ULONG offset = 0x0; RTL_OSVERSIONINFOEXW osInfo = { 0 }; osInfo.dwOSVersionInfoSize = sizeof(osInfo); RtlGetVersion((POSVERSIONINFOW)&osInfo); #ifdef _M_ARM64 if (osInfo.dwBuildNumber < 19045 || osInfo.dwBuildNumber > 26100) { DbgPrint("OS Version is not supported\n"); return; } if (osInfo.dwBuildNumber >= 19045 && osInfo.dwBuildNumber <= 22631) { offset = 0x939; } if (osInfo.dwBuildNumber == 26100) { offset = 0x6b8; } #endif #ifdef _M_X64 if (osInfo.dwBuildNumber < 19045 || osInfo.dwBuildNumber > 26100) { DbgPrint("OS Version is not supported\n"); return; } if (osInfo.dwBuildNumber >= 19045 && osInfo.dwBuildNumber <= 22631) { offset = 0x878; } if (osInfo.dwBuildNumber == 26100) { offset = 0x5f8; } #endif PEPROCESS pProcess = NULL; PPROCESS_SIGNATURE_PROTECTION pSignatureProtect = NULL; ULONG pid = PID; NTSTATUS status = PsLookupProcessByProcessId((HANDLE)pid, &pProcess); if (NT_SUCCESS(status)) { DbgPrint("Changing PPL value for target PROCESS ID: %d\n", PID); pSignatureProtect = (PPROCESS_SIGNATURE_PROTECTION)(((ULONG_PTR)pProcess) + offset); if (value == 1) { pSignatureProtect->SignatureLevel = 0x11; pSignatureProtect->SectionSignatureLevel = 0x11; pSignatureProtect->Protection = { 1,0,3 }; } if (value == 0) { pSignatureProtect->SignatureLevel = 0x0; pSignatureProtect->SectionSignatureLevel = 0x0; pSignatureProtect->Protection = { 0,0,0 }; } DbgPrint("Process ID %d 's protection level has changed\n", PID); ObDereferenceObject(pProcess); } } VOID ChangePPL() { UNICODE_STRING functionName; RtlInitUnicodeString(&functionName, L"ZwQuerySystemInformation"); ZwQuerySystemInformation = (ZWQUERYSYSTEMINFORMATION)MmGetSystemRoutineAddress(&functionName); NTSTATUS status; ULONG bufferSize = 0; UNICODE_STRING processName, processPath; RtlInitUnicodeString(&processName, L"JonMon-Service.exe"); RtlInitUnicodeString(&processPath, L"\\Windows\\JonMon-Service.exe"); status = ZwQuerySystemInformation(SystemProcessInformation, NULL, 0, &bufferSize); if (status != STATUS_INFO_LENGTH_MISMATCH) { return; } if (bufferSize) { PVOID info = ExAllocatePool2(POOL_FLAG_PAGED, bufferSize, DRIVER_TAG); if (info) { status = ZwQuerySystemInformation(SystemProcessInformation, info, bufferSize, &bufferSize); if (NT_SUCCESS(status)) { PSYSTEM_PROCESSES processInfo = (PSYSTEM_PROCESSES)info; UNICODE_STRING imagePath; imagePath.MaximumLength = 1024; imagePath.Buffer = (PWSTR)ExAllocatePool2(POOL_FLAG_PAGED, 1024, DRIVER_TAG); if (imagePath.Buffer == NULL) { DbgPrint("Failed allocation\n"); return; } int count = 0; do { do { if (RtlEqualUnicodeString(&processName, &processInfo->ProcessName, TRUE)) { status = GetProcessImageName((HANDLE)processInfo->ProcessId, &imagePath); if (wcsstr(imagePath.Buffer, processPath.Buffer) != NULL) { g_ServicePID = (ULONG)processInfo->ProcessId; AlterPPL(g_ServicePID, 1); count++; DbgPrint("Found JonMon-Service.exe\n"); } } processInfo = (PSYSTEM_PROCESSES)((unsigned char*)processInfo + processInfo->NextEntryDelta); } while (processInfo->NextEntryDelta); } while (count != 1); ExFreePoolWithTag(imagePath.Buffer, DRIVER_TAG); } ExFreePoolWithTag(info, DRIVER_TAG); } } } // //Function unloads the driver // VOID JonMonUnload( _In_ PDRIVER_OBJECT DriverObject ) { PAGED_CODE(); TraceLoggingWrite( g_hJonMon, "100", TraceLoggingUInt32(100, "EventID"), TraceLoggingValue(FALSE, "TraceLogging Provider Registered") ); TraceLoggingUnregister(g_hJonMon); AlterPPL(g_ServicePID, 0); if (g_EventSchema.Registry == TRUE) { CmUnRegisterCallback(Cookie); DbgPrint((DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "CmUnRegisterCallback Unloaded\n")); } if(g_EventSchema.ProcessCreation == TRUE) { PsSetCreateProcessNotifyRoutineEx(CreateProcessNotifyRoutineEx, TRUE); DbgPrint((DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "PsSetCreateProcessNotifyRoutineEx Unloaded\n")); } if (g_EventSchema.ProcessHandleCreation == TRUE || g_EventSchema.ProcessHandleDuplication == TRUE) { ObUnRegisterCallbacks(ProcessRegistrationHandle); DbgPrint((DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "ObUnRegisterCallbacks Unloaded\n")); } if (g_EventSchema.ImageLoad == TRUE) { PsRemoveLoadImageNotifyRoutine(LoadImageRoutine); DbgPrint((DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "PsSetLoadImageNotifyRoutine Unloaded\n")); } if (g_EventSchema.RemoteThreadCreation == TRUE) { PsRemoveCreateThreadNotifyRoutine(PsCreateThreadNotifyRoutine); DbgPrint((DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "PsSetCreateThreadNotifyRoutine Unloaded\n")); } if (g_EventSchema.ProcessTermination == TRUE) { PsSetCreateProcessNotifyRoutine(TerminateProcessNotifyRoutine, TRUE); DbgPrint((DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "PsSetCreateProcessNotifyRoutine Unloaded\n")); } //sleep for 5 seconds to allow worker threads to finish LARGE_INTEGER interval; interval.QuadPart = -(3 * 10000000); KeDelayExecutionThread(KernelMode, FALSE, &interval); UNICODE_STRING symlink; RtlInitUnicodeString(&symlink, L"\\??\\JonMon"); IoDeleteSymbolicLink(&symlink); IoDeleteDevice(DriverObject->DeviceObject); DbgPrint("JonMon Driver Unloaded\n"); } //Function completes the driver requests NTSTATUS CompleteRequest( PIRP Irp, NTSTATUS status, ULONG_PTR info ) { PAGED_CODE(); Irp->IoStatus.Status = status; Irp->IoStatus.Information = info; IoCompleteRequest(Irp, IO_NO_INCREMENT); return status; } //Function handles the create and close requests. Function just points to CompleteRequest. NTSTATUS JonMonCreateClose( _In_ PDEVICE_OBJECT, _In_ PIRP Irp ) { PAGED_CODE(); return CompleteRequest(Irp); } ================================================ FILE: JonMon/driver.h ================================================ #ifndef _DRIVER_ #define _DRIVER_ #include "shared.h" /* * Global variable to store the registry path */ #define JonMon_DEVICE 0x8010 #define IOCTL_CHANGE_PROTECTION_LEVEL_PROCESS CTL_CODE(JonMon_DEVICE, 0x800, METHOD_BUFFERED, FILE_ANY_ACCESS) #define IOCTL_EVENT_CONFIGURATION CTL_CODE(JonMon_DEVICE, 0x801, METHOD_BUFFERED, FILE_ANY_ACCESS) UNICODE_STRING g_RegPath; typedef struct _SYSTEM_THREADS { LARGE_INTEGER KernelTime; LARGE_INTEGER UserTime; LARGE_INTEGER CreateTime; ULONG WaitTime; PVOID StartAddress; CLIENT_ID ClientId; KPRIORITY Priority; KPRIORITY BasePriority; ULONG ContextSwitchCount; LONG State; LONG WaitReason; } SYSTEM_THREADS, * PSYSTEM_THREADS; typedef struct _SYSTEM_PROCESSES { ULONG NextEntryDelta; ULONG ThreadCount; ULONG Reserved1[6]; LARGE_INTEGER CreateTime; LARGE_INTEGER UserTime; LARGE_INTEGER KernelTime; UNICODE_STRING ProcessName; KPRIORITY BasePriority; SIZE_T ProcessId; SIZE_T InheritedFromProcessId; ULONG HandleCount; ULONG Reserved2[2]; VM_COUNTERS VmCounters; IO_COUNTERS IoCounters; SYSTEM_THREADS Threads[1]; } SYSTEM_PROCESSES, * PSYSTEM_PROCESSES; typedef struct _PS_PROTECTION { UCHAR Type : 3; UCHAR Audit : 1; UCHAR Signer : 4; } PS_PROTECTION, * PPS_PROTECTION; typedef struct _PROCESS_SIGNATURE_PROTECTION { UCHAR SignatureLevel; UCHAR SectionSignatureLevel; PS_PROTECTION Protection; } PROCESS_SIGNATURE_PROTECTION, * PPROCESS_SIGNATURE_PROTECTION; typedef NTSTATUS(NTAPI* ZWQUERYSYSTEMINFORMATION)( IN SYSTEM_INFORMATION_CLASS SystemInformationClass, OUT PVOID SystemInformation, IN ULONG SystemInformationLength, OUT PULONG ReturnLength ); ZWQUERYSYSTEMINFORMATION ZwQuerySystemInformation; /* * Driver Function Protoypes */ NTSTATUS JonMonCreateClose( _In_ PDEVICE_OBJECT DeviceObject, _In_ PIRP Irp ); NTSTATUS CompleteRequest( PIRP Irp, NTSTATUS status = STATUS_SUCCESS, ULONG_PTR info = 0 ); NTSTATUS JonMonDeviceControl( _In_ PDEVICE_OBJECT, _In_ PIRP Irp ); VOID JonMonUnload( _In_ PDRIVER_OBJECT DriverObject ); VOID AlterPPL( _In_ ULONG PID, _In_ ULONG value ); VOID ChangePPL(); #endif // !_DRIVER_ ================================================ FILE: JonMon/jtime.h ================================================ #ifndef _JTIME_ #define _JTIME_ typedef unsigned short WORD; typedef unsigned long DWORD; typedef struct _SYSTEMTIME { WORD wYear; WORD wMonth; WORD wDayOfWeek; WORD wDay; WORD wHour; WORD wMinute; WORD wSecond; WORD wMilliseconds; } SYSTEMTIME, * PSYSTEMTIME, * LPSYSTEMTIME; typedef struct _FILETIME { DWORD dwLowDateTime; DWORD dwHighDateTime; } FILETIME, * PFILETIME, * LPFILETIME; #endif // !_TIME_ ================================================ FILE: JonMon/minifilter.cpp ================================================ #include "minifilter.h" #include "process.h" PAGED_FILE(); PFLT_FILTER gFilterHandle; NTSTATUS JonMonFilterUnload ( _In_ FLT_FILTER_UNLOAD_FLAGS Flags ) { PAGED_CODE(); NTSTATUS status; DbgPrint("In JonMonFilterUnload\n"); if (Flags == FLTFL_FILTER_UNLOAD_MANDATORY) { FltUnregisterFilter(gFilterHandle); status = STATUS_SUCCESS; } else { status = STATUS_FLT_DO_NOT_DETACH; } return status; } _IRQL_requires_max_(PASSIVE_LEVEL) FLT_POSTOP_CALLBACK_STATUS FLTAPI FilterPostCallback ( _In_ PFLT_CALLBACK_DATA Data, _In_ PCFLT_RELATED_OBJECTS FltObjects, _In_ PVOID CompletionContext, _In_ FLT_POST_OPERATION_FLAGS Flags ) { UNREFERENCED_PARAMETER(Flags); UNREFERENCED_PARAMETER(FltObjects); UNREFERENCED_PARAMETER(CompletionContext); HANDLE sourceThreadId = PsGetThreadId(Data->Thread); ULONG currentProcessId = FltGetRequestorProcessId(Data); ULONGLONG sourceProcStartKey = PsGetProcessStartKey(PsGetCurrentProcess()); FILETIME filetime; NTSTATUS status; PFLT_FILE_NAME_INFORMATION fileNameInfo = NULL; if (Data->RequestorMode != UserMode) { goto Exit; } if (currentProcessId == 4) { goto Exit; } // //go to exit if filename is null // if (Data->Iopb->TargetFileObject->FileName.Length == 0) { goto Exit; } KeQuerySystemTime(&filetime); switch (Data->Iopb->MajorFunction) { case IRP_MJ_CREATE: { switch (Data->IoStatus.Information) { case FILE_CREATED: { status = FltGetFileNameInformation(Data, FLT_FILE_NAME_NORMALIZED | FLT_FILE_NAME_QUERY_ALWAYS_ALLOW_CACHE_LOOKUP, &fileNameInfo); if (!NT_SUCCESS(status)) { goto Exit; } TraceLoggingWrite( g_hJonMon, "FileCreate", TraceLoggingInt32(10, "EventID"), TraceLoggingValue(sourceThreadId, "SourceThreadId"), TraceLoggingValue(currentProcessId, "SourceProcessId"), TraceLoggingValue(sourceProcStartKey, "SourceProcStartKey"), TraceLoggingWideString(fileNameInfo->Name.Buffer, "FileName"), TraceLoggingFileTime(filetime, "EventTime") ); break; } case FILE_OPENED: { if (FltObjects->FileObject->Flags & FO_MAILSLOT) { DWORD RequestedRights = Data->Iopb->Parameters.Create.SecurityContext->DesiredAccess; status = FltGetFileNameInformation(Data, FLT_FILE_NAME_NORMALIZED | FLT_FILE_NAME_QUERY_ALWAYS_ALLOW_CACHE_LOOKUP, &fileNameInfo); if (!NT_SUCCESS(status)) { goto Exit; } TraceLoggingWrite( g_hJonMon, "MailslotOpen", TraceLoggingInt32(14, "EventID"), TraceLoggingValue(sourceThreadId, "SourceThreadId"), TraceLoggingValue(currentProcessId, "SourceProcessId"), TraceLoggingValue(sourceProcStartKey, "SourceProcStartKey"), TraceLoggingWideString(fileNameInfo->Name.Buffer, "FileName"), TraceLoggingValue(RequestedRights, "RequestedRights"), TraceLoggingFileTime(filetime, "EventTime") ); break; } if (FltObjects->FileObject->Flags & FO_NAMED_PIPE) { DWORD RequestedRights = Data->Iopb->Parameters.Create.SecurityContext->DesiredAccess; status = FltGetFileNameInformation(Data, FLT_FILE_NAME_NORMALIZED | FLT_FILE_NAME_QUERY_ALWAYS_ALLOW_CACHE_LOOKUP, &fileNameInfo); if (!NT_SUCCESS(status)) { goto Exit; } TraceLoggingWrite( g_hJonMon, "NamedPipeConnection", TraceLoggingInt32(12, "EventID"), TraceLoggingValue(sourceThreadId, "SourceThreadId"), TraceLoggingValue(currentProcessId, "SourceProcessId"), TraceLoggingValue(sourceProcStartKey, "SourceProcStartKey"), TraceLoggingWideString(fileNameInfo->Name.Buffer, "FileName"), TraceLoggingValue(RequestedRights, "RequestedRights"), TraceLoggingFileTime(filetime, "EventTime") ); break; } break; } case FILE_SUPERSEDED: { if (Data->Iopb->TargetFileObject->FileName.Length == 0) { break; } status = FltGetFileNameInformation(Data, FLT_FILE_NAME_NORMALIZED | FLT_FILE_NAME_QUERY_ALWAYS_ALLOW_CACHE_LOOKUP, &fileNameInfo); if (!NT_SUCCESS(status)) { DbgPrint("[IRP_MJ_CREATE_NAMED_PIPE] Failed to get file info\n"); goto Exit; } // // check to see if FileName is valid before proceeding // if (Data->Iopb->Parameters.Create.Options & FO_REMOTE_ORIGIN) { // // only print if fileNameInfo->Name.Buffer contains pipe // if (wcsstr(fileNameInfo->Name.Buffer, L"\\pipe\\") != NULL) { TraceLoggingWrite( g_hJonMon, "RemoteNamedPipeConnection", TraceLoggingInt32(15, "EventID"), TraceLoggingFileTime(filetime, "EventTime"), TraceLoggingWideString(fileNameInfo->Name.Buffer, "FileName"), TraceLoggingValue(currentProcessId, "SourceProcessId"), TraceLoggingValue(sourceProcStartKey, "SourceProcStartKey"), TraceLoggingValue(sourceThreadId, "SourceThreadId") ); break; } } if (Data->Iopb->Parameters.Create.Options == (FO_REMOTE_ORIGIN | FO_SEQUENTIAL_ONLY | FO_CACHE_SUPPORTED)) { // // only print if fileNameInfo->Name.Buffer contains mailslot // if (wcsstr(fileNameInfo->Name.Buffer, L"mailslot") != NULL) { TraceLoggingWrite( g_hJonMon, "RemoteMailslotConnection", TraceLoggingInt32(15, "EventID"), TraceLoggingFileTime(filetime, "EventTime"), TraceLoggingWideString(Data->Iopb->TargetFileObject->FileName.Buffer, "FileName"), TraceLoggingValue(currentProcessId, "SourceProcessId"), TraceLoggingValue(sourceProcStartKey, "SourceProcStartKey"), TraceLoggingValue(sourceThreadId, "SourceThreadId") ); break; } } break; } default: { break; } } break; } case IRP_MJ_CREATE_NAMED_PIPE: { DWORD RequestedRights = Data->Iopb->Parameters.CreatePipe.SecurityContext->DesiredAccess; DWORD GrantedRights = Data->Iopb->Parameters.CreatePipe.SecurityContext->AccessState->PreviouslyGrantedAccess; if (Data->IoStatus.Information == FILE_CREATED || Data->IoStatus.Information == FILE_OPENED) { status = FltGetFileNameInformation(Data, FLT_FILE_NAME_NORMALIZED | FLT_FILE_NAME_QUERY_ALWAYS_ALLOW_CACHE_LOOKUP, &fileNameInfo); if (!NT_SUCCESS(status)) { DbgPrint("[IRP_MJ_CREATE_NAMED_PIPE] Failed to get file info\n"); goto Exit; } switch (Data->IoStatus.Information) { case FILE_CREATED: { bool RemoteCreation = FALSE; if (FltObjects->FileObject->Flags & FO_REMOTE_ORIGIN) { DbgPrint(" Creation request came from remote machine\n"); RemoteCreation = TRUE; } TraceLoggingWrite( g_hJonMon, "NamedPipeCreate", TraceLoggingInt32(11, "EventID"), TraceLoggingValue(sourceThreadId, "SourceThreadId"), TraceLoggingValue(currentProcessId, "SourceProcessId"), TraceLoggingValue(sourceProcStartKey, "SourceProcStartKey"), TraceLoggingWideString(fileNameInfo->Name.Buffer, "FileName"), TraceLoggingValue(RequestedRights, "RequestedRights"), TraceLoggingValue(GrantedRights, "GrantedRights"), TraceLoggingFileTime(filetime, "EventTime") ); break; } default: { break; } } } break; } case IRP_MJ_CREATE_MAILSLOT: { if (Data->IoStatus.Information == FILE_CREATED || Data->IoStatus.Information == FILE_OPENED) { DWORD RequestedRights = Data->Iopb->Parameters.CreateMailslot.SecurityContext->DesiredAccess; status = FltGetFileNameInformation(Data, FLT_FILE_NAME_NORMALIZED | FLT_FILE_NAME_QUERY_ALWAYS_ALLOW_CACHE_LOOKUP, &fileNameInfo); if (!NT_SUCCESS(status)) { DbgPrint("[IRP_MJ_CREATE_MAILSLOT] Failed to get file info\n"); goto Exit; } switch (Data->IoStatus.Information) { case FILE_CREATED: { TraceLoggingWrite( g_hJonMon, "MailslotCreate", TraceLoggingInt32(13, "EventID"), TraceLoggingValue(sourceThreadId, "SourceThreadId"), TraceLoggingValue(currentProcessId, "SourceProcessId"), TraceLoggingValue(sourceProcStartKey, "SourceProcStartKey"), TraceLoggingWideString(fileNameInfo->Name.Buffer, "FileName"), TraceLoggingValue(RequestedRights, "RequestedRights"), TraceLoggingFileTime(filetime, "EventTime") ); break; } default: { break; } } } break; } default: { break; } } Exit: if(fileNameInfo != NULL) { FltReleaseFileNameInformation(fileNameInfo); } return FLT_POSTOP_FINISHED_PROCESSING; }; // // FilterPreCallback placeholder // _IRQL_requires_max_(APC_LEVEL) FLT_PREOP_CALLBACK_STATUS FLTAPI FilterPreCallback ( _In_ PFLT_CALLBACK_DATA Data, _In_ PCFLT_RELATED_OBJECTS FltObjects, _In_ PVOID* CompletionContext ) { UNREFERENCED_PARAMETER(Data); UNREFERENCED_PARAMETER(FltObjects); UNREFERENCED_PARAMETER(CompletionContext); PAGED_CODE(); return FLT_PREOP_SUCCESS_WITH_CALLBACK; } NTSTATUS FltCallbackStart ( _In_ PDRIVER_OBJECT DriverObject ) { PAGED_CODE(); NTSTATUS status; CONST FLT_OPERATION_REGISTRATION FileSystemOperationCallbacks[] = { { IRP_MJ_CREATE, 0, NULL, FilterPostCallback }, { IRP_MJ_CREATE_NAMED_PIPE, 0, NULL, FilterPostCallback }, { IRP_MJ_CREATE_MAILSLOT, 0, NULL, FilterPostCallback }, { IRP_MJ_OPERATION_END } }; CONST FLT_REGISTRATION FilterRegistration = { sizeof(FLT_REGISTRATION), FLT_REGISTRATION_VERSION, FLTFL_REGISTRATION_SUPPORT_NPFS_MSFS, NULL, FileSystemOperationCallbacks, JonMonFilterUnload, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, }; status = FltRegisterFilter( DriverObject, &FilterRegistration, &gFilterHandle ); if (!NT_SUCCESS(status)) { DbgPrint("Failed FltRegisterFilter\n"); return status; } status = FltStartFiltering(gFilterHandle); if (!NT_SUCCESS(status)) { DbgPrint("Failed FltStartFiltering\n"); FltUnregisterFilter(gFilterHandle); gFilterHandle = nullptr; } return status; } ================================================ FILE: JonMon/minifilter.h ================================================ #ifndef _MINIFILTER_ #define _MINIFILTER_ #include "shared.h" extern PFLT_FILTER gFilterHandle; NTSTATUS JonMonFilterUnload ( _In_ FLT_FILTER_UNLOAD_FLAGS Flags ); _IRQL_requires_max_(PASSIVE_LEVEL) FLT_POSTOP_CALLBACK_STATUS FLTAPI FilterPostCallback ( _In_ PFLT_CALLBACK_DATA Data, _In_ PCFLT_RELATED_OBJECTS FltObjects, _In_ PVOID CompletionContext, _In_ FLT_POST_OPERATION_FLAGS Flags ); _IRQL_requires_max_(APC_LEVEL) FLT_PREOP_CALLBACK_STATUS FLTAPI FilterPreCallback ( _In_ PFLT_CALLBACK_DATA Data, _In_ PCFLT_RELATED_OBJECTS FltObjects, _In_ PVOID* CompletionContext ); NTSTATUS FltCallbackStart ( _In_ PDRIVER_OBJECT DriverObject ); #endif // !_MINIFILTER_ ================================================ FILE: JonMon/process.cpp ================================================ #include "process.h" PAGED_FILE(); ZWQUERYINFORMATIONPROCESS ZwQueryInformationProcess; NTSTATUS GetProcessImageName(HANDLE processId, PUNICODE_STRING ProcessImageName) { PAGED_CODE(); NTSTATUS status; ULONG returnedLength; ULONG bufferLength; HANDLE hProcess = NULL; PVOID buffer{}; PEPROCESS eProcess; UNICODE_STRING routineName; status = PsLookupProcessByProcessId(processId, &eProcess); if (!NT_SUCCESS(status)) { goto Exit; } status = ObOpenObjectByPointer( eProcess, OBJ_KERNEL_HANDLE, NULL, 0, 0, KernelMode, &hProcess); if (!NT_SUCCESS(status)) { goto Exit; } ObDereferenceObject(eProcess); if (!ZwQueryInformationProcess) { RtlInitUnicodeString(&routineName, L"ZwQueryInformationProcess"); ZwQueryInformationProcess = (ZWQUERYINFORMATIONPROCESS)MmGetSystemRoutineAddress(&routineName); if (ZwQueryInformationProcess == NULL) { DbgPrint("Cannot resolve ZwQueryInformationProcess\n"); return STATUS_NOT_FOUND; } } status = ZwQueryInformationProcess(hProcess, ProcessImageFileName, NULL, 0, &returnedLength); if (status != STATUS_INFO_LENGTH_MISMATCH) { goto Exit; } bufferLength = returnedLength; if (ProcessImageName->MaximumLength < bufferLength) { ProcessImageName->MaximumLength = (USHORT)bufferLength; return STATUS_BUFFER_OVERFLOW; } buffer = ExAllocatePool2(POOL_FLAG_PAGED, bufferLength, PROCESS_TAG); if (buffer == NULL) { return STATUS_INSUFFICIENT_RESOURCES; } status = ZwQueryInformationProcess(hProcess, ProcessImageFileName, buffer, bufferLength, &bufferLength); if (!NT_SUCCESS(status)) { goto Exit; } RtlCopyUnicodeString(ProcessImageName, (PUNICODE_STRING)buffer); //Adding null terminator ProcessImageName->Buffer[ProcessImageName->Length / sizeof(UNICODE_NULL)] = UNICODE_NULL; Exit: if(hProcess != NULL) { ZwClose(hProcess); } if (buffer != NULL) { ExFreePoolWithTag(buffer, PROCESS_TAG); } return status; } ================================================ FILE: JonMon/process.h ================================================ #ifndef _PROCESS_ #define _PROCESS_ #include "shared.h" typedef NTSTATUS(*ZWQUERYINFORMATIONPROCESS) ( __in HANDLE ProcessHandle, __in PROCESSINFOCLASS ProcessInformationClass, __out_bcount(ProcessInformationLength) PVOID ProcessInformation, __in ULONG ProcessInformationLength, __out_opt PULONG ReturnLength ); NTSTATUS GetProcessImageName(HANDLE processId, PUNICODE_STRING ProcessImageName); NTSTATUS GetProcessToken(HANDLE processId, PHANDLE hToken); #endif // !_PROCESS_ ================================================ FILE: JonMon/registry.cpp ================================================ #include "registry.h" #include "shared.h" #include "process.h" #include PAGED_FILE(); NTSTATUS GetRegistryKeyPath( _In_ PVOID object, _In_ ULONG tag, _In_ PCWSTR* keyPath ) { PCUNICODE_STRING registryPath = NULL; NTSTATUS status; PWCHAR buffer = NULL; ULONG bufferSize; PAGED_CODE(); status = CmCallbackGetKeyObjectIDEx(&Cookie, object, NULL, ®istryPath, 0); if (!NT_SUCCESS(status) || registryPath == NULL) { DbgPrint("CmCallbackGetKeyObjectIDEx failed. Status 0x%x", status); goto Exit; } // Allocate a buffer for the registry path bufferSize = (registryPath->Length / sizeof(WCHAR)) + 1; buffer = (PWCHAR)ExAllocatePool2(POOL_FLAG_PAGED, bufferSize * sizeof(WCHAR), tag); if (buffer == NULL) { DbgPrint("GetRegistryKeyPath - ExAllocatePool2 failed. Status 0x%x", status); goto Exit; } // Zero the buffer before copying the registry path and adding a null terminator RtlZeroMemory(buffer, bufferSize + sizeof(UNICODE_NULL)); RtlCopyMemory(buffer, registryPath->Buffer, registryPath->Length); buffer[bufferSize - 1] = UNICODE_NULL; *keyPath = buffer; status = STATUS_SUCCESS; Exit: if (registryPath != NULL) { CmCallbackReleaseKeyObjectIDEx(registryPath); } return status; } ================================================ FILE: JonMon/registry.h ================================================ #ifndef _REGISTRY_ #define _REGISTRY_ #include // // Structure to hold registry callback info // typedef struct _REG_SET_VALUE_CALLBACK_INFO { PEPROCESS SourceProcess; HANDLE SourceProcessId; HANDLE SourceThreadId; PETHREAD SourceThread; ULONG Type; PCWSTR KeyPath; PVOID Data; ULONG DataSize; UNICODE_STRING ValueName; } REG_SET_VALUE_CALLBACK_INFO, * PREG_SET_VALUE_CALLBACK_INFO; typedef struct _REG_CREATE_KEY_CALLBACK_INFO { HANDLE SourceProcessId; ULONGLONG ProcStartKey; PETHREAD SourceThread; HANDLE SourceThreadId; ACCESS_MASK DesiredAccess; UNICODE_STRING KeyPath; } REG_CREATE_KEY_CALLBACK_INFO, * PREG_CREATE_KEY_CALLBACK_INFO; typedef struct _REG_DELETE_KEY_CALLBACK_INFO { PEPROCESS SourceProcess; HANDLE SourceProcessId; HANDLE SourceThreadId; PCWSTR KeyPath; } REG_DELETE_KEY_CALLBACK_INFO, * PREG_DELETE_KEY_CALLBACK_INFO; NTSTATUS GetRegistryKeyPath( _In_ PVOID object, _In_ ULONG tag, _In_ PCWSTR* keyPath ); VOID SendSetValueRegistryInfo( _In_ PVOID StartContext ); VOID DeleteKey( _In_ PVOID context, _In_ PREG_DELETE_KEY_INFORMATION info ); VOID CreateKey( _In_ PVOID StartContext ); VOID SaveKey( _In_ PVOID context, _In_ PREG_SAVE_KEY_INFORMATION info ); #endif // !_REGISTRY_ ================================================ FILE: JonMon/shared.h ================================================ #ifndef _SHARED_ #define _SHARED_ #include #include #include #include #include #include #include #include #include #define INVALID_HANDLE_VALUE ((HANDLE)(LONG_PTR)-1) TRACELOGGING_DECLARE_PROVIDER(g_hJonMon); /* TraceLogging Event Schema: ---- Security Events ---- EID 1 - Process Creation EID 2 - Process Termination EID 3 - Remote Thread Creation EID 4 - Load Image EID 5 - ProcessHandle (OpenProcess/DuplicateHandle) EID 6 - RegistrySaveKey EID 7 - RegistryDeleteKey EID 8 - RegistrySetValue EID 9 - RegistryCreateKey EID 10 - FileOperation (CreateFile) EID 11 - NamedPipeCreation EID 12 - NamedPipeConnection EID 13 - MailslotCreation EID 14 - MailslotConnection EID 15 - RemoteFileConnection (Named Pipes/Mailslots) ---- Debug/Informational Events ---- EID 100 - TraceLogging Provider Registered (True or False) EID 101 - Event Schema Configuration EID 102 - Protection Level Changed */ // // https://github.com/winsiderss/systeminformer/blob/0e3d514e23cf4813ba5895c74b6d596c8966e1b3/KSystemInformer/include/kph.h#L31 // #define PAGED_PASSIVE()\ PAGED_CODE()\ NT_ASSERT(KeGetCurrentIrql() == PASSIVE_LEVEL) // // https://github.com/winsiderss/systeminformer/blob/0e3d514e23cf4813ba5895c74b6d596c8966e1b3/KSystemInformer/include/kph.h#L31 // #define PAGED_FILE() \ __pragma(bss_seg("PAGEBBS"))\ __pragma(code_seg("PAGE"))\ __pragma(data_seg("PAGEDATA"))\ __pragma(const_seg("PAGERO")) /* * Creating tags to be used with in different scenerios of memory allocation */ #define DRIVER_TAG 'monj' #define REGISTRY_TAG 'regj' #define PROCESS_TAG 'prcj' #define THREAD_TAG 'thrj' #define TOKEN_TAG 'tknj' #define FILE_TAG 'flj' #define CALBACK_TAG 'clkj' #define SYSTEM_THREAD_TAG 'rhsj' #define MAX_ALLOC 260 extern LARGE_INTEGER Cookie; typedef struct _SYSTEM_PROCESS_INFORMATION { ULONG NextEntryOffset; ULONG NumberOfThreads; LARGE_INTEGER Reserved[3]; LARGE_INTEGER CreateTime; LARGE_INTEGER UserTime; LARGE_INTEGER KernelTime; UNICODE_STRING ImageName; KPRIORITY BasePriority; HANDLE ProcessId; HANDLE InheritedFromProcessId; } SYSTEM_PROCESS_INFORMATION, * PSYSTEM_PROCESS_INFORMATION; typedef enum _SYSTEM_INFORMATION_CLASS { SystemProcessInformation = 5, } SYSTEM_INFORMATION_CLASS; typedef struct _LIST_ENTRY* PLIST_ENTRY; typedef struct _THREAD_LIST_ENTRY* PTHREAD_LIST_ENTRY; typedef struct _THREAD_LIST_ENTRY { PLIST_ENTRY PrevThread; PLIST_ENTRY NextThread; PETHREAD Thread; } THREAD_LIST_ENTRY, * PTHREAD_LIST_ENTRY; #endif // !_SHARED_ ================================================ FILE: JonMon-Service/JonMon-Service.vcxproj ================================================ Debug ARM Debug Win32 Release ARM Release Win32 Debug x64 Release x64 16.0 Win32Proj {bf810292-3774-41a4-b51e-cef92e26894a} JonMonService 10.0 Application true v143 Unicode Application false v143 true Unicode Application true v143 Unicode Application true v143 Unicode Application false v143 true Unicode Level3 true WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true Level3 true true true WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true true true Level3 true _DEBUG;_CONSOLE;%(PreprocessorDefinitions) true ..\Libs;%(AdditionalIncludeDirectories) MultiThreadedDebug Console true Level3 true true true NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true MultiThreaded ..\Libs;%(AdditionalIncludeDirectories) Console true true true %(AdditionalDependencies) UseLinkTimeCodeGeneration ================================================ FILE: JonMon-Service/JonMonService.cpp ================================================ #include #include #include #include "etwMain.h" #include "service.h" #include "config.h" #pragma comment(lib, "setupapi.lib") int wmain(int argc, wchar_t* argv[]) { std::wstring VariantString(argv[1]); std::wstring ConfigPath = L"JonMonConfig.json"; EventSchema_Full eventSchema = { 0 }; if (argc == 3) { ConfigPath = argv[2]; } BOOL FileCopy = CopyFileW(ConfigPath.c_str(), L"C:\\Windows\\JonMonConfig.json", FALSE); if (FileCopy != TRUE) { printf("[-] JonMonConfig.json did not copy to C:\\Windows\\JonMonConfig.json\n"); } int result = ConfigFile(L"C:\\Windows\\JonMonConfig.json", &eventSchema); if (VariantString == L"-etw") { //Copying resource file to C:\Windows and installing manifest BOOL FileCopy = CopyFileW(L"JonMon.dll", L"C:\\Windows\\JonMon.dll", FALSE); if (FileCopy != TRUE) { printf("[-] JonMon.dll did not copy to C:\\Windows\\JonMon.dll\n"); } else { printf("[*] JonMon.dll copied\n"); } DWORD status = InstallManifest(); TraceEvent(L"JonMonDebug", JonMonDebugGuid, &eventSchema); } if (VariantString == L"-c") { std::wcout << L"JonMon EventSchema: " << std::endl; std::wcout << L"ProcessCreationEvents: " << (eventSchema.ProcessCreation_Events ? L"True" : L"False") << std::endl; std::wcout << L"FileEvents: " << (eventSchema.File_Events ? L"True" : L"False") << std::endl; std::wcout << L"ProcessTerminationEvents: " << (eventSchema.ProcessTermination_Events ? L"True" : L"False") << std::endl; std::wcout << L"RegistryEvents: " << (eventSchema.Registry_Events ? L"True" : L"False") << std::endl; std::wcout << L"ProcessHandleCreationEvents: " << (eventSchema.ProcessHandleCreation_Events ? L"True" : L"False") << std::endl; std::wcout << L"ProcessHandleDuplicationEvents: " << (eventSchema.ProcessHandleDuplication_Events ? L"True" : L"False") << std::endl; std::wcout << L"RemoteThreadCreationEvents: " << (eventSchema.RemoteThreadCreation_Events ? L"True" : L"False") << std::endl; std::wcout << L"ImageLoadEvents: " << (eventSchema.ImageLoad_Events ? L"True" : L"False") << std::endl; std::wcout << L"RPCEvents: " << (eventSchema.RPC_Events ? L"True" : L"False") << std::endl; std::wcout << L"NetworkEvents: " << (eventSchema.Network_Events ? L"True" : L"False") << std::endl; std::wcout << L"DotNetLoadEvents: " << (eventSchema.DotNetLoad_Events ? L"True" : L"False") << std::endl; std::wcout << L"AMSIEvents: " << (eventSchema.AMSI_Events ? L"True" : L"False") << std::endl; std::wcout << L"SchedTaskEvents: " << (eventSchema.SchedTask_Events ? L"True" : L"False") << std::endl; std::wcout << L"WMIEventSubscriptionEvents: " << (eventSchema.WMIEventSubscription_Events ? L"True" : L"False") << std::endl; std::wcout << L"CryptUnprotectEvents: " << (eventSchema.CryptUnprotect_Events ? L"True" : L"False") << std::endl; std::wcout << L"ThreatIntelligenceEvents: " << (eventSchema.ThreatIntelligence_Events ? L"True" : L"False") << std::endl; std::wcout << L"ThreatIntelligenceEvents RemoteReadProcessMemory: " << (eventSchema.ThreatIntelligence_Events_RemoteReadProcessMemory ? L"True" : L"False") << std::endl; std::wcout << L"ThreatIntelligenceEvents RemoteWriteProcessMemory: " << (eventSchema.ThreatIntelligence_Events_RemoteWriteProcessMemory ? L"True" : L"False") << std::endl; std::wcout << L"ThreatIntelligenceEvents RemoteVirtualAllocation: " << (eventSchema.ThreatIntelligence_Events_RemoteVirtualAllocation ? L"True" : L"False") << std::endl; std::wcout << L"ThreatIntelligenceEvents RemoteQueueUserAPC: " << (eventSchema.ThreatIntelligence_Events_RemoteQueueUserAPC ? L"True" : L"False") << std::endl; std::wcout << L"TokenImpersonationEvents: " << (eventSchema.TokenImpersonation_Events ? L"True" : L"False") << std::endl; std::wcout << L"ConfigVersion: " << eventSchema.ConfigVersion << std::endl; std::wcout << L"JonMonVersion: " << eventSchema.JonMonVersion << std::endl; EventSchema_KM eventSchemaKM = { 0 }; eventSchemaKM.ConfigSet = eventSchema.ConfigSet; eventSchemaKM.ProcessCreation = eventSchema.ProcessCreation_Events; eventSchemaKM.ProcessTermination = eventSchema.ProcessTermination_Events; eventSchemaKM.ProcessHandleCreation = eventSchema.ProcessHandleCreation_Events; eventSchemaKM.ProcessHandleDuplication = eventSchema.ProcessHandleDuplication_Events; eventSchemaKM.RemoteThreadCreation = eventSchema.RemoteThreadCreation_Events; eventSchemaKM.ImageLoad = eventSchema.ImageLoad_Events; eventSchemaKM.File = eventSchema.File_Events; eventSchemaKM.Registry = eventSchema.Registry_Events; eventSchemaKM.ConfigVersion = eventSchema.ConfigVersion; eventSchemaKM.JonMonVersion = eventSchema.JonMonVersion; } if (VariantString == L"-i") { //Copying resource file to C:\Windows and installing manifest printf("[*] Starting JonMon Installation Process....\n"); FileCopy = CopyFileW(L"JonMon.dll", L"C:\\Windows\\JonMon.dll", FALSE); if (FileCopy != TRUE) { printf("[-] JonMon.dll did not copy to C:\\Windows\\JonMon.dll\n"); } DWORD status = InstallManifest(); if (status != 0) { printf("[-] InstallManifest Failed\n"); } LPWSTR CurrentDirectory = new WCHAR[MAX_PATH]; FileCopy = CopyFileW(L"JonMon.sys", L"C:\\Windows\\JonMon.sys", FALSE); if (FileCopy != TRUE) { printf("[-] JonMon.sys did not copy to C:\\Windows\\JonMon.sys\n"); } FileCopy = CopyFileW(L"JonMon-Service.exe", L"C:\\Windows\\JonMon-Service.exe", FALSE); if (FileCopy != TRUE) { printf("[-] JonMon-Service.exe did not copy to C:\\Windows\\JonMon-Service.exe\n"); } FileCopy = CopyFileW(L".\\Extensions\\JonMon-Ext1.dll", L"C:\\Windows\\JonMon-Ext1.dll", FALSE); if (FileCopy != TRUE) { printf("[-] JonMon-Ext1.dlll did not copy to C:\\Windows\\JonMon-Ext1.dlll\n"); } else { printf("[*] JonMon-Ext1.dll copied\n"); } printf("[*] Installing JonMonDrv Service....\n"); status = CreateCustomService(L"JonMonDrv", L"C:\\Windows\\JonMon.sys", SERVICE_KERNEL_DRIVER); printf("[*] JonMonDrv Service Installed\n"); // // --- Start Minifilter Settings --- // printf("[*] Adding Minifilter registry values....\n"); HKEY hKey; status = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Services\\JonMonDrv", 0, KEY_SET_VALUE, &hKey); if (hKey == NULL || status != 0) { printf("[-] Failed to open registry key to JonMonDrv\n"); } DWORD value = 3; status = RegSetKeyValueW(hKey, NULL, L"SupportedFeatures", REG_DWORD, &value, sizeof(value)); if (status != ERROR_SUCCESS) { printf("[-] Failed to set registry value for SupportedFeatures\n"); } RegCloseKey(hKey); hKey = NULL; LONG lRes = RegCreateKeyExW(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Services\\JonMonDrv\\Instances", 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, NULL); if (lRes != ERROR_SUCCESS) { printf("[-] Failed to create registry key for Instances\n"); } lRes = RegSetValueExW(hKey, L"DefaultInstance", 0, REG_SZ, (const BYTE*)L"JonMon Instance", sizeof(L"JonMon Instance")); if (lRes != ERROR_SUCCESS) { printf("[-] Failed to set registry value for DefaultInstance\n"); } RegCloseKey(hKey); hKey = NULL; lRes = RegCreateKeyExW(HKEY_LOCAL_MACHINE, L"SYSTEM\\CurrentControlSet\\Services\\JonMonDrv\\Instances\\JonMon Instance", 0, NULL, REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, NULL, &hKey, NULL); if (lRes != ERROR_SUCCESS) { printf("[-] Failed to create registry key for JonMon Instance\n"); } lRes = RegSetValueExW(hKey, L"Altitude", 0, REG_SZ, (const BYTE*)L"385202", sizeof(L"385202")); if (lRes != ERROR_SUCCESS) { printf("[-] Failed to set registry value for Altitude\n"); } value = 0; status = RegSetKeyValueW(hKey,NULL,L"Flags",REG_DWORD,&value,sizeof(value)); if (status != ERROR_SUCCESS) { printf("[-] Failed to set registry value for Flags\n"); } RegCloseKey(hKey); printf("[*] Minifilter registry values added\n"); // // --- Stop Minifilter Settings --- // status = CreateCustomService(L"JonMon", L"C:\\Windows\\JonMon-Service.exe -s", SERVICE_WIN32_OWN_PROCESS); if (status != 0) { printf("[-] InstallService Failed\n"); } status = StartCustomService(L"JonMon"); if (status != 0) { printf("[-] Failed to start JonMon\n"); } EventSchema_KM eventSchemaKM = { 0 }; eventSchemaKM.ConfigSet = eventSchema.ConfigSet; eventSchemaKM.ProcessCreation = eventSchema.ProcessCreation_Events; eventSchemaKM.ProcessTermination = eventSchema.ProcessTermination_Events; eventSchemaKM.ProcessHandleCreation = eventSchema.ProcessHandleCreation_Events; eventSchemaKM.ProcessHandleDuplication = eventSchema.ProcessHandleDuplication_Events; eventSchemaKM.RemoteThreadCreation = eventSchema.RemoteThreadCreation_Events; eventSchemaKM.ImageLoad = eventSchema.ImageLoad_Events; eventSchemaKM.File = eventSchema.File_Events; eventSchemaKM.Registry = eventSchema.Registry_Events; eventSchemaKM.ConfigVersion = eventSchema.ConfigVersion; eventSchemaKM.JonMonVersion = eventSchema.JonMonVersion; HANDLE hDevice = CreateFile(L"\\\\.\\JonMon", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (hDevice == INVALID_HANDLE_VALUE) { printf("Error %u\n", GetLastError()); goto Exit; } DeviceIoControl(hDevice, IOCTL_EVENT_CONFIGURATION, &eventSchemaKM, sizeof(eventSchemaKM), NULL, 0, NULL, NULL); CloseHandle(hDevice); } if (VariantString == L"-s") { DWORD status = StartCustomService(L"JonMonDrv"); if (status != 0) { printf("[-] Failed to start JonMonDrv\n"); } //Starting service for JonMon-Service.exe SERVICE_TABLE_ENTRYW serviceTable[] = { { const_cast (L""), (LPSERVICE_MAIN_FUNCTIONW)ServiceMain } }; if (!StartServiceCtrlDispatcherW(serviceTable)) { // Failed to start service control dispatcher return GetLastError(); } } if (VariantString == L"-u") { printf("[*] Starting JonMon Uninstallation Process....\n"); DWORD status = StopCustomService(L"JonMonDrv"); if (status != 0) { printf("[-] Failed to stop JonMonDrv\n"); } status = DeleteCustomService(L"JonMonDrv"); if (status != 0) { printf("[-] Failed to delete JonMonDrv\n"); } status = StopCustomService(L"JonMon"); if (status != 0) { printf("[-] Failed to stop JonMon\n"); } status = DeleteCustomService(L"JonMon"); if (status != 0) { printf("[-] Failed to delete JonMon\n"); } printf("[*] Deregestering JonMon Provider\n"); status = StopETWTrace(); printf("[*] Removing Files....\n"); DeleteFileW(L"C:\\Windows\\JonMon.sys"); DeleteFileW(L"C:\\Windows\\JonMon-Service.exe"); DeleteFileW(L"C:\\Windows\\JonMon-Ext1.dll"); DeleteFileW(L"C:\\Windows\\JonMon.dll"); DeleteFileW(L"C:\\Windows\\JonMonConfig.json"); printf("[*] JonMon Uninstallation Complete\n"); } if (VariantString == L"-h") { printf("Usage: 'JonMon-Service.exe -etw' will start an ETW trace called JonMon to collect events from various providers\n"); printf("Usage: 'JonMon-Service.exe -i' will install the JonMon Services and Driver\n"); printf("Usage: 'JonMon-Service.exe -s' will start the JonMon Services and Driver\n"); printf("Usage: 'JonMon-Service.exe -u' will stop/uninstall all the JonMon Services\n"); printf("Usage: 'JonMon-Service.exe -c' will read the configuration file\n"); } Exit: return 0; } ================================================ FILE: JonMon-Service/config.cpp ================================================ #include "config.h" #include #include #include "nlohmann/json.hpp" using json = nlohmann::json; int ConfigFile( _In_ std::wstring ConfigFile, _Out_ EventSchema_Full* EventSchemaStruct ) { // // Initialize the EventSchema structure // EventSchemaStruct->ConfigSet = true; EventSchemaStruct->ProcessCreation_Events = false; EventSchemaStruct->ProcessTermination_Events = false; EventSchemaStruct->File_Events = false; EventSchemaStruct->Registry_Events = false; EventSchemaStruct->ProcessHandleCreation_Events = false; EventSchemaStruct->ProcessHandleDuplication_Events = false; EventSchemaStruct->RemoteThreadCreation_Events = false; EventSchemaStruct->ImageLoad_Events = false; EventSchemaStruct->RPC_Events = false; EventSchemaStruct->Network_Events = false; EventSchemaStruct->DotNetLoad_Events = false; EventSchemaStruct->AMSI_Events = false; EventSchemaStruct->SchedTask_Events = false; EventSchemaStruct->WMIEventSubscription_Events = false; EventSchemaStruct->CryptUnprotect_Events = false; EventSchemaStruct->ThreatIntelligence_Events = false; EventSchemaStruct->ThreatIntelligence_Events_RemoteReadProcessMemory = false; EventSchemaStruct->ThreatIntelligence_Events_RemoteWriteProcessMemory = false; EventSchemaStruct->ThreatIntelligence_Events_RemoteVirtualAllocation = false; EventSchemaStruct->ThreatIntelligence_Events_RemoteQueueUserAPC = false; EventSchemaStruct->TokenImpersonation_Events = false; EventSchemaStruct->ConfigVersion = 0; EventSchemaStruct->JonMonVersion = 0; // // Open the JSON configuration file // std::ifstream jsonFile(ConfigFile); if (!jsonFile.is_open()) { std::wcerr << "Failed to open file: " << ConfigFile << std::endl; return 1; } json jsonData; jsonFile >> jsonData; if (jsonData.contains("ConfigVersion")) { std::string ConfigVersion = jsonData["ConfigVersion"]; EventSchemaStruct->ConfigVersion = std::stoi(ConfigVersion); } if (jsonData.contains("JonMonVersion")) { std::string JonMonVersion = jsonData["JonMonVersion"]; EventSchemaStruct->JonMonVersion = std::stoi(JonMonVersion); } if (jsonData.contains("ProcessCreation_Events")) { EventSchemaStruct->ProcessCreation_Events = jsonData["ProcessCreation_Events"]; } if (jsonData.contains("File_Events")) { EventSchemaStruct->File_Events = jsonData["File_Events"]; } if (jsonData.contains("Registry_Events")) { EventSchemaStruct->Registry_Events = jsonData["Registry_Events"]; } if (jsonData.contains("ProcessTermination_Events")) { EventSchemaStruct->ProcessTermination_Events = jsonData["ProcessTermination_Events"]; } if (jsonData.contains("ProcessHandleCreation_Events")) { EventSchemaStruct->ProcessHandleCreation_Events = jsonData["ProcessHandleCreation_Events"]; } if (jsonData.contains("ProcessHandleDuplication_Events")) { EventSchemaStruct->ProcessHandleDuplication_Events = jsonData["ProcessHandleDuplication_Events"]; } if (jsonData.contains("RemoteThreadCreation_Events")) { EventSchemaStruct->RemoteThreadCreation_Events = jsonData["RemoteThreadCreation_Events"]; } if (jsonData.contains("ImageLoad_Events")) { EventSchemaStruct->ImageLoad_Events = jsonData["ImageLoad_Events"]; } if(jsonData.contains("RPC_Events")) { EventSchemaStruct->RPC_Events = jsonData["RPC_Events"]; } if(jsonData.contains("Network_Events")) { EventSchemaStruct->Network_Events = jsonData["Network_Events"]; } if(jsonData.contains("DotNetLoad_Events")) { EventSchemaStruct->DotNetLoad_Events = jsonData["DotNetLoad_Events"]; } if(jsonData.contains("AMSI_Events")) { EventSchemaStruct->AMSI_Events = jsonData["AMSI_Events"]; } if(jsonData.contains("SchedTask_Events")) { EventSchemaStruct->SchedTask_Events = jsonData["SchedTask_Events"]; } if (jsonData.contains("WMIEventSubscription_Events")) { EventSchemaStruct->WMIEventSubscription_Events = jsonData["WMIEventSubscription_Events"]; } if (jsonData.contains("CryptUnprotect_Events")) { EventSchemaStruct->CryptUnprotect_Events = jsonData["CryptUnprotect_Events"]; } if (jsonData.contains("ThreatIntelligence_Events")) { EventSchemaStruct->ThreatIntelligence_Events_RemoteReadProcessMemory = jsonData["ThreatIntelligence_Events"]["RemoteReadProcessMemory"]; EventSchemaStruct->ThreatIntelligence_Events_RemoteWriteProcessMemory = jsonData["ThreatIntelligence_Events"]["RemoteWriteProcessMemory"]; EventSchemaStruct->ThreatIntelligence_Events_RemoteVirtualAllocation = jsonData["ThreatIntelligence_Events"]["RemoteVirtualAllocation"]; EventSchemaStruct->ThreatIntelligence_Events_RemoteQueueUserAPC = jsonData["ThreatIntelligence_Events"]["RemoteQueueUserAPC"]; if (EventSchemaStruct->ThreatIntelligence_Events_RemoteReadProcessMemory || EventSchemaStruct->ThreatIntelligence_Events_RemoteWriteProcessMemory || EventSchemaStruct->ThreatIntelligence_Events_RemoteVirtualAllocation || EventSchemaStruct->ThreatIntelligence_Events_RemoteQueueUserAPC) { EventSchemaStruct->ThreatIntelligence_Events = true; } } if (jsonData.contains("TokenImpersonation_Events")) { EventSchemaStruct->TokenImpersonation_Events = jsonData["TokenImpersonation_Events"]; } return 0; } ================================================ FILE: JonMon-Service/config.h ================================================ #pragma once #include struct EventSchema_KM { bool ConfigSet; bool ProcessCreation; bool ProcessTermination; bool ProcessHandleCreation; bool ProcessHandleDuplication; bool RemoteThreadCreation; bool ImageLoad; bool File; bool Registry; int ConfigVersion; int JonMonVersion; }; struct EventSchema_Full { bool ConfigSet; bool ProcessCreation_Events; // KM Event bool ProcessTermination_Events; // KM Event bool ProcessHandleCreation_Events; // KM Event bool ProcessHandleDuplication_Events; // KM Event bool RemoteThreadCreation_Events; // KM Event bool ImageLoad_Events; // KM Event bool File_Events; // KM Event bool Registry_Events; // KM Event bool RPC_Events; // UM Event bool Network_Events; // UM Event bool DotNetLoad_Events; // UM Event bool AMSI_Events; // UM Event bool SchedTask_Events; // UM Event bool WMIEventSubscription_Events; // UM Event bool CryptUnprotect_Events; // UM Event bool ThreatIntelligence_Events; // UM Event bool ThreatIntelligence_Events_RemoteReadProcessMemory; // UM Event bool ThreatIntelligence_Events_RemoteWriteProcessMemory; // UM Event bool ThreatIntelligence_Events_RemoteVirtualAllocation; // UM Event bool ThreatIntelligence_Events_RemoteQueueUserAPC; // UM Event bool TokenImpersonation_Events; // UM Event int ConfigVersion; int JonMonVersion; }; int ConfigFile( _In_ std::wstring ConfigFile, _Out_ EventSchema_Full* EventSchemaStruct ); ================================================ FILE: JonMon-Service/context.cpp ================================================ #include #include #include "context.h" #include #include #include #include std::vector processList; std::vector initialProcessList; // // Mutexes to protect access to the process lists // std::mutex processListMutex; // Mutex to protect access to processList std::mutex initialProcessListMutex; // Mutex to protect access to initialProcessList // // Function to enumerate initial processes running on the system and store them in the initialProcessList // void InitialProcesses() { PTokenInformation tokenInformation = NULL; PProcessInformation processInformation = NULL; HANDLE hProcessSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hProcessSnapshot == INVALID_HANDLE_VALUE) { return; } PROCESSENTRY32 pe32; pe32.dwSize = sizeof(PROCESSENTRY32); // Retrieve information about the first process if (!Process32First(hProcessSnapshot, &pe32)) { goto Exit; } // Loop through the processes in the snapshot do { // Get the process ID DWORD processID = pe32.th32ProcessID; // // if PID 4 is found, skip it // if (processID == 4) { continue; } WCHAR processName[MAX_PATH] = L""; // Open the process to get its full path HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processID); if (hProcess != NULL) { // // Get token information // PTokenInformation tokenInformation = new TokenInformation(); if (tokenInformation == NULL) { std::wcout << L"Error allocating memory for token information\n"; continue; } DWORD status = GetUserInformation(processID, tokenInformation); if (status != 0) { std::wcout << L"GetUserInformation failed: " << status << std::endl; continue; } PProcessInformation processInformation = new ProcessInformation(); if (processInformation == NULL) { std::wcout << L"Error allocating memory for process information\n"; continue; } processInformation->processId = processID; processInformation->authenticationId = tokenInformation->authenticationId; processInformation->integrityLevel = tokenInformation->integrityLevel; processInformation->sessionId = tokenInformation->sessionId; processInformation->tokenType = tokenInformation->tokenType; processInformation->userName = tokenInformation->userName; processInformation->linkedAuthenticationId = tokenInformation->linkedAuthenticationId; // Get the full process image file name DWORD size = MAX_PATH; // This should be set to the size of the buffer // Get the full process image file name if (QueryFullProcessImageName(hProcess, PROCESS_NAME_NATIVE, processName, &size)) { processInformation->processName = processName; std::lock_guard lock(initialProcessListMutex); initialProcessList.push_back(*processInformation); } CloseHandle(hProcess); // Close handle to process } } while (Process32Next(hProcessSnapshot, &pe32)); // Continue with the next process // Clean up the snapshot object Exit: if (hProcessSnapshot != NULL) { CloseHandle(hProcessSnapshot); } if (tokenInformation != NULL) { delete(tokenInformation); } if (processInformation != NULL) { delete(processInformation); } return; } DWORD GetUserInformation( _In_ DWORD processId, _In_ PTokenInformation tokenInformation ) { DWORD status = 0; HANDLE hToken = NULL; HANDLE hProcess = NULL; DWORD dwLengthNeeded; PTOKEN_LINKED_TOKEN pTokenLinkedToken = NULL; hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processId); if (hProcess == NULL) { std::wcout << L"OpenProcess failed: " << GetLastError() << std::endl; return 1; } if (!OpenProcessToken(hProcess, TOKEN_QUERY, &hToken)) { std::wcout << L"OpenProcessToken failed: " << GetLastError() << std::endl; CloseHandle(hProcess); return 1; } status = GetTokenUserInfo(hToken, tokenInformation->userName); if (status != 0) { std::wcout << L"GetTokenUserInfo failed: " << status << std::endl; goto Exit; } // Get Token Type dwLengthNeeded = 0; if (!GetTokenInformation(hToken, TokenType, &tokenInformation->tokenType, sizeof(DWORD), &dwLengthNeeded)) { status = GetLastError(); std::wcout << L"GetTokenInformation (TokenType) failed: " << status << std::endl; goto Exit; } // Get Authentication ID status = GetAuthenticationId(hToken, &tokenInformation->authenticationId); if (status != 0) { std::wcout << L"GetAuthenticationId failed: " << status << std::endl; goto Exit; } // Get Session ID dwLengthNeeded = 0; if (!GetTokenInformation(hToken, TokenSessionId, &tokenInformation->sessionId, sizeof(DWORD), &dwLengthNeeded)) { status = GetLastError(); std::wcout << L"GetTokenInformation (SessionId) failed: " << status << std::endl; goto Exit; } // Get Linked Authentication ID pTokenLinkedToken = (PTOKEN_LINKED_TOKEN)LocalAlloc(LPTR, sizeof(TOKEN_LINKED_TOKEN)); if (pTokenLinkedToken == NULL) { status = GetLastError(); std::wcout << L"LocalAlloc for pTokenLinkedToken failed: " << status << std::endl; goto Exit; } if (!GetTokenInformation(hToken, TokenLinkedToken, pTokenLinkedToken, sizeof(TOKEN_LINKED_TOKEN), &dwLengthNeeded)) { status = GetLastError(); if (status == ERROR_NO_SUCH_LOGON_SESSION) { tokenInformation->linkedAuthenticationId.LowPart = 0; tokenInformation->linkedAuthenticationId.HighPart = 0; } else { std::wcout << L"GetTokenInformation (LinkedToken) failed: " << status << std::endl; goto Exit; } } else if (pTokenLinkedToken->LinkedToken != NULL) { status = GetAuthenticationId(pTokenLinkedToken->LinkedToken, &tokenInformation->linkedAuthenticationId); if (status != 0) { std::wcout << L"GetAuthenticationId (LinkedToken) failed: " << status << std::endl; goto Exit; } } else { tokenInformation->linkedAuthenticationId.LowPart = 0; tokenInformation->linkedAuthenticationId.HighPart = 0; } // Get Integrity Level status = GetMandatoryLabel(hToken, tokenInformation->integrityLevel); if (status != 0) { std::wcout << L"GetMandatoryLabel failed: " << status << std::endl; goto Exit; } Exit: if (pTokenLinkedToken != NULL) { if (pTokenLinkedToken->LinkedToken != NULL) { CloseHandle(pTokenLinkedToken->LinkedToken); } LocalFree(pTokenLinkedToken); } if (hToken != NULL) { CloseHandle(hToken); } if (hProcess != NULL) { CloseHandle(hProcess); } return status; } // // Query the process list to get the process name of a given process id // PProcessInformation GetProcessName( _In_ DWORD processId) { { std::lock_guard lock(initialProcessListMutex); for (auto& process : initialProcessList) { if (process.processId == processId) { return &process; } } } { std::lock_guard lock(processListMutex); for (auto& process : processList) { if (process.processId == processId) { return &process; } } } return nullptr; } void ClearProcessList() { // // lock the process list using a mutex // std::lock_guard lock(processListMutex); // Locks the mutex // // Clear the existing processList3 to avoid duplication // processList.clear(); } void GetProcessList() { // Take a snapshot of all processes in the system PTokenInformation tokenInformation = NULL; PProcessInformation processInformation = NULL; HANDLE hProcessSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hProcessSnapshot == INVALID_HANDLE_VALUE) { return; } PROCESSENTRY32 pe32; pe32.dwSize = sizeof(PROCESSENTRY32); // Retrieve information about the first process if (!Process32First(hProcessSnapshot, &pe32)) { goto Exit; } // Loop through the processes in the snapshot do { DWORD processID = pe32.th32ProcessID; if (processID == 4) // Skip PID 4 continue; // Check if process already exists in initialProcessList or processList bool exists = false; for (const auto& process : initialProcessList) { if (process.processId == processID) { exists = true; break; } } if (exists) { continue; } for (const auto& process : processList) { if (process.processId == processID) { exists = true; break; } } if (exists) { continue; } WCHAR processName[MAX_PATH] = L""; HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processID); if (hProcess != NULL) { // Allocate token information tokenInformation = new TokenInformation(); if (tokenInformation == NULL) { std::wcout << L"Error allocating memory for token information\n"; CloseHandle(hProcess); continue; } DWORD status = GetUserInformation(processID, tokenInformation); if (status != 0) { std::wcout << L"GetUserInformation failed: " << status << std::endl; delete tokenInformation; tokenInformation = nullptr; CloseHandle(hProcess); continue; } // Allocate process information processInformation = new ProcessInformation(); if (processInformation == NULL) { std::wcout << L"Error allocating memory for process information\n"; delete tokenInformation; tokenInformation = nullptr; CloseHandle(hProcess); continue; } // Populate processInformation processInformation->processId = processID; processInformation->authenticationId = tokenInformation->authenticationId; processInformation->integrityLevel = tokenInformation->integrityLevel; processInformation->sessionId = tokenInformation->sessionId; processInformation->tokenType = tokenInformation->tokenType; processInformation->userName = tokenInformation->userName; processInformation->linkedAuthenticationId = tokenInformation->linkedAuthenticationId; // Get the process name DWORD size = MAX_PATH; if (QueryFullProcessImageName(hProcess, PROCESS_NAME_NATIVE, processName, &size)) { processInformation->processName = processName; std::lock_guard lock(processListMutex); processList.push_back(*processInformation); } // Free allocated memory for this iteration delete tokenInformation; delete processInformation; tokenInformation = nullptr; processInformation = nullptr; CloseHandle(hProcess); // Close handle to process } } while (Process32Next(hProcessSnapshot, &pe32)); // Continue with the next process // Clean up and exit Exit: if (hProcessSnapshot != NULL) { CloseHandle(hProcessSnapshot); } } // // Function to periodically update the process list every second // void UpdateProcessListPeriodically() { while (true) { GetProcessList(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); // trying to be fast because of sacraficial processes } } void ClearListPeriodically() { while (true) { ClearProcessList(); // // Pause for 5 seconds to allow the process list to be updated // std::this_thread::sleep_for(std::chrono::seconds(5)); } } DWORD GetTokenUserInfo( _In_ HANDLE hToken, _In_ std::wstring& fullUserName ) { PTOKEN_USER pTokenUser = NULL; DWORD status = 0; DWORD dwLengthNeeded = 0; DWORD dwSizeName; DWORD dwSizeDomain; WCHAR szName[256]; WCHAR szDomain[256]; WCHAR userName[514]; SID_NAME_USE eUse; if (!GetTokenInformation(hToken, TokenUser, NULL, 0, &dwLengthNeeded)) { if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) { std::wcout << L"GetTokenInformation failed: " << GetLastError() << std::endl; status = GetLastError(); goto Exit; } } pTokenUser = (PTOKEN_USER)LocalAlloc(LPTR, dwLengthNeeded); if (pTokenUser == NULL) { std::wcout << L"LocalAlloc failed: " << GetLastError() << std::endl; status = GetLastError(); goto Exit; } if (!GetTokenInformation(hToken, TokenUser, pTokenUser, dwLengthNeeded, &dwLengthNeeded)) { std::wcout << L"GetTokenInformation failed: " << GetLastError() << std::endl; status = GetLastError(); goto Exit; } dwSizeName = 256; dwSizeDomain = 256; if (!LookupAccountSid(NULL, pTokenUser->User.Sid, szName, &dwSizeName, szDomain, &dwSizeDomain, &eUse)) { std::wcout << L"LookupAccountSid failed: " << GetLastError() << std::endl; status = GetLastError(); goto Exit; } // // Combine the domain and user name // wcscpy_s(userName, szDomain); wcscat_s(userName, L"\\"); wcscat_s(userName, szName); userName[513] = L'\0'; fullUserName.assign(userName); Exit: if (pTokenUser != NULL) { LocalFree(pTokenUser); } return status; } DWORD GetAuthenticationId( _In_ HANDLE hToken, _In_ PLUID authId ) { DWORD status = 0; DWORD dwLengthNeeded = 0; PTOKEN_STATISTICS pTokenStatistics = NULL; *authId = { 0 }; if (!GetTokenInformation(hToken, TokenStatistics, NULL, 0, &dwLengthNeeded)) { if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) { std::wcout << L"GetTokenInformation failed: " << GetLastError() << std::endl; status = GetLastError(); goto Exit; } } pTokenStatistics = (PTOKEN_STATISTICS)LocalAlloc(LPTR, dwLengthNeeded); if (pTokenStatistics == NULL) { std::wcout << L"LocalAlloc failed: " << GetLastError() << std::endl; status = GetLastError(); goto Exit; } if (!GetTokenInformation(hToken, TokenStatistics, pTokenStatistics, dwLengthNeeded, &dwLengthNeeded)) { status = GetLastError(); if (status != ERROR_NO_SUCH_LOGON_SESSION) { std::wcout << L"GetTokenInformation failed: " << status << std::endl; } goto Exit; } // Successfully retrieved token statistics; assign AuthenticationId *authId = pTokenStatistics->AuthenticationId; Exit: if (pTokenStatistics != NULL) { LocalFree(pTokenStatistics); } return status; } DWORD GetMandatoryLabel( _In_ HANDLE hToken, _In_ std::wstring& integrityLevel ) { DWORD status = 0; DWORD dwLengthNeeded = 0; PTOKEN_MANDATORY_LABEL pTokenMandatoryLabel = NULL; DWORD dwIntegrityLevel = 0; WCHAR szIntegrityLevel[1024] = L"Unknown"; // Default value for unknown levels if (!GetTokenInformation(hToken, TokenIntegrityLevel, NULL, 0, &dwLengthNeeded)) { if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) { std::wcout << L"GetTokenInformation failed: " << GetLastError() << std::endl; status = GetLastError(); goto Exit; } } pTokenMandatoryLabel = (PTOKEN_MANDATORY_LABEL)LocalAlloc(LPTR, dwLengthNeeded); if (pTokenMandatoryLabel == NULL) { std::wcout << L"LocalAlloc failed: " << GetLastError() << std::endl; status = GetLastError(); goto Exit; } if (!GetTokenInformation(hToken, TokenIntegrityLevel, pTokenMandatoryLabel, dwLengthNeeded, &dwLengthNeeded)) { std::wcout << L"GetTokenInformation failed: " << GetLastError() << std::endl; status = GetLastError(); goto Exit; } // Get integrity level RID from SID dwIntegrityLevel = *GetSidSubAuthority(pTokenMandatoryLabel->Label.Sid, 0); // Determine integrity level description if (dwIntegrityLevel == SECURITY_MANDATORY_LOW_RID) { wcscpy_s(szIntegrityLevel, L"Low"); } else if (dwIntegrityLevel == SECURITY_MANDATORY_MEDIUM_RID) { wcscpy_s(szIntegrityLevel, L"Medium"); } else if (dwIntegrityLevel == SECURITY_MANDATORY_HIGH_RID) { wcscpy_s(szIntegrityLevel, L"High"); } else if (dwIntegrityLevel == SECURITY_MANDATORY_SYSTEM_RID) { wcscpy_s(szIntegrityLevel, L"System"); } // Assign the integrity level to the output parameter integrityLevel.assign(szIntegrityLevel); Exit: if (pTokenMandatoryLabel != NULL) { LocalFree(pTokenMandatoryLabel); } return status; } ================================================ FILE: JonMon-Service/context.h ================================================ #pragma once #include #include "tlhelp32.h" #include #include #pragma comment(lib, "tdh.lib") typedef struct _TokenInformation { std::wstring userName; DWORD tokenType; LUID authenticationId; LUID linkedAuthenticationId; std::wstring integrityLevel; DWORD sessionId; } TokenInformation, * PTokenInformation; typedef struct _ProcessInformation { DWORD processId; std::wstring processName; std::wstring userName; DWORD tokenType; LUID authenticationId; LUID linkedAuthenticationId; std::wstring integrityLevel; DWORD sessionId; } ProcessInformation, * PProcessInformation; // // global variables that hold process ids and process names of every process currently running // extern std::vector processList; extern std::vector initialProcessList; DWORD GetUserInformation( _In_ DWORD processId, _In_ PTokenInformation tokenInformation ); DWORD GetMandatoryLabel( _In_ HANDLE hToken, _In_ std::wstring& integrityLevel ); DWORD GetAuthenticationId( _In_ HANDLE hToken, _In_ PLUID authId ); DWORD GetTokenUserInfo( _In_ HANDLE hToken, _In_ std::wstring& fullUserName ); void UpdateProcessListPeriodically(); void ClearListPeriodically(); PProcessInformation GetProcessName( _In_ DWORD processId ); void InitialProcesses(); ================================================ FILE: JonMon-Service/etwMain.cpp ================================================ #include #include #include #include #include #include #include #include #include #include #include "global.h" #include "context.h" #include "etwMain.h" #include "service.h" #pragma comment(lib, "Ws2_32.lib") #pragma comment(lib, "dbghelp.lib") DWORD lsassPID = 0; SYSTEMTIME lastEventTime; DWORD StopETWTrace() { TRACEHANDLE traceHandle = 0; ULONG status, bufferSize; wchar_t traceName[] = L"JonMon"; EVENT_TRACE_PROPERTIES* traceProp; bufferSize = sizeof(EVENT_TRACE_PROPERTIES) + sizeof(traceName) + sizeof(WCHAR); traceProp = (EVENT_TRACE_PROPERTIES*)LocalAlloc(LPTR, bufferSize); traceProp->Wnode.BufferSize = bufferSize; traceProp->Wnode.Guid = JonMonGuid; traceProp->LogFileNameOffset = 0; traceProp->LoggerNameOffset = sizeof(EVENT_TRACE_PROPERTIES); status = StopTrace(traceHandle, traceName, traceProp); if (status != ERROR_SUCCESS) { OutputDebugStringW(L"StopTrace Failed"); return status; } else { OutputDebugStringW(L"StopTrace Success"); return status; } return 0; } DWORD CheckLSASSPID() { // // Enumerate initialProcessList to find the LSASS PID // Sleep(2000); for (auto& process : initialProcessList) { // // print out each process id and process name // std::wstring lsassSubstring = L"lsass.exe"; if (process.processName.find(lsassSubstring) != std::wstring::npos) { return process.processId; } } } DWORD TraceEvent( _In_ LPCWSTR Name, _In_ GUID TraceGuid, _In_ EventSchema_Full* EventSchemaStruct ) { std::thread initialProcesses(InitialProcesses); std::thread updateThread(UpdateProcessListPeriodically); std::thread clearThread(ClearListPeriodically); // // Detach threads // initialProcesses.detach(); updateThread.detach(); clearThread.detach(); printf("[+] Starting ETW Trace\n"); TRACEHANDLE hTrace = 0; ULONG result, bufferSize; EVENT_TRACE_LOGFILEW trace; EVENT_TRACE_PROPERTIES* traceProp = nullptr; lsassPID = CheckLSASSPID(); memset(&trace, 0, sizeof(EVENT_TRACE_LOGFILEW)); trace.ProcessTraceMode = PROCESS_TRACE_MODE_REAL_TIME | PROCESS_TRACE_MODE_EVENT_RECORD; trace.LoggerName = (LPWSTR)Name; trace.EventRecordCallback = (PEVENT_RECORD_CALLBACK)ProcessEvent; // // Calculate buffer size // ULONG nameLength = (ULONG)(wcslen(Name) + 1); bufferSize = sizeof(EVENT_TRACE_PROPERTIES) + nameLength * sizeof(WCHAR); // // Allocate memory for EVENT_TRACE_PROPERTIES and logger name // traceProp = (EVENT_TRACE_PROPERTIES*)LocalAlloc(LPTR, bufferSize); if (traceProp == nullptr) { printf("Failed to allocate memory for trace properties\n"); return ERROR_OUTOFMEMORY; } // // Initialize EVENT_TRACE_PROPERTIES // traceProp->Wnode.BufferSize = bufferSize; traceProp->Wnode.ClientContext = 2; traceProp->Wnode.Guid = TraceGuid; traceProp->Wnode.Flags = WNODE_FLAG_TRACED_GUID; traceProp->LogFileMode = EVENT_TRACE_REAL_TIME_MODE | EVENT_TRACE_SYSTEM_LOGGER_MODE; traceProp->LogFileNameOffset = 0; traceProp->LoggerNameOffset = sizeof(EVENT_TRACE_PROPERTIES); // // Set logger name // LPWSTR loggerNamePtr = (LPWSTR)((BYTE*)traceProp + traceProp->LoggerNameOffset); wcscpy(loggerNamePtr, Name); // // Start the trace // if ((result = StartTraceW(&hTrace, Name, traceProp)) != ERROR_SUCCESS) { OutputDebugStringW(L"Error starting trace\n"); LocalFree(traceProp); return result; } // // Set up and enable trace parameters // ENABLE_TRACE_PARAMETERS enableTraceParameters; ZeroMemory(&enableTraceParameters, sizeof(ENABLE_TRACE_PARAMETERS)); enableTraceParameters.Version = ENABLE_TRACE_PARAMETERS_VERSION_2; enableTraceParameters.EnableProperty = EVENT_ENABLE_PROPERTY_STACK_TRACE; printf("[+] JonMon Trace started\n"); if ((result = EnableTraceEx2( hTrace, &JonMonTraceLogging, EVENT_CONTROL_CODE_ENABLE_PROVIDER, TRACE_LEVEL_VERBOSE, 0, 0, 0, 0 )) != ERROR_SUCCESS) { OutputDebugStringW(L"Error enabling trace\n"); printf("Error: %lu\n", result); LocalFree(traceProp); // Ensure traceProp is freed CloseTrace(hTrace); // Ensure hTrace is closed return result; } // //DotNet Events // if (EventSchemaStruct->DotNetLoad_Events) { if ((result = EnableTraceEx2( hTrace, &DotNet_Provider, EVENT_CONTROL_CODE_ENABLE_PROVIDER, TRACE_LEVEL_INFORMATION, 0x8, 0, 0, NULL )) != ERROR_SUCCESS) { OutputDebugString(L"[!] Error EnableTraceEx - DotNet\n"); } } // // WMI Events // if (EventSchemaStruct->WMIEventSubscription_Events) { if ((result = EnableTraceEx2( hTrace, &WMIActivty_Provider, EVENT_CONTROL_CODE_ENABLE_PROVIDER, TRACE_LEVEL_INFORMATION, 0, 0, 0, &enableTraceParameters )) != ERROR_SUCCESS) { OutputDebugString(L"[!] Error EnableTraceEx - WMI\n"); } } // // RPC Events // if (EventSchemaStruct->RPC_Events) { if ((result = EnableTraceEx2( hTrace, &RPC_Provider, EVENT_CONTROL_CODE_ENABLE_PROVIDER, TRACE_LEVEL_INFORMATION, 0, 0, 0, &enableTraceParameters )) != ERROR_SUCCESS) { OutputDebugString(L"[!] Error EnableTraceEx - RPC\n"); } } // // AMSI // if (EventSchemaStruct->AMSI_Events) { if ((result = EnableTraceEx2( hTrace, &AMSI_Provider, EVENT_CONTROL_CODE_ENABLE_PROVIDER, TRACE_LEVEL_INFORMATION, 0, 0, 0, &enableTraceParameters )) != ERROR_SUCCESS) { OutputDebugString(L"[!] Error EnableTraceEx - RPC\n"); } } // // Network Events // if (EventSchemaStruct->Network_Events) { if ((result = EnableTraceEx2( hTrace, &Network_Provider, EVENT_CONTROL_CODE_ENABLE_PROVIDER, TRACE_LEVEL_INFORMATION, 0, 0x10, 0, &enableTraceParameters )) != ERROR_SUCCESS) { OutputDebugString(L"[!] Error EnableTraceEx - RPC\n"); } } // // Threat Intellgiene Events // if (EventSchemaStruct->ThreatIntelligence_Events) { OutputDebugStringW(L"Threat Intelligence Events Enabled\n"); ULONGLONG matchAnyKeyword = 0x0; if (EventSchemaStruct->ThreatIntelligence_Events_RemoteReadProcessMemory) { OutputDebugStringW(L"RemoteReadProcessMemory Enabled\n"); matchAnyKeyword |= 0x20000; } if (EventSchemaStruct->ThreatIntelligence_Events_RemoteWriteProcessMemory) { OutputDebugStringW(L"RemoteWriteProcessMemory Enabled\n"); matchAnyKeyword |= 0x80000; } if (EventSchemaStruct->ThreatIntelligence_Events_RemoteVirtualAllocation) { OutputDebugStringW(L"RemoteVirtualAllocation Enabled\n"); matchAnyKeyword |= (0x4 | 0x8); } if (EventSchemaStruct->ThreatIntelligence_Events_RemoteQueueUserAPC) { OutputDebugStringW(L"RemoteQueueUserAPC Enabled\n"); matchAnyKeyword |= (0x1000 | 0x2000); } if ((result = EnableTraceEx2( hTrace, &ThreatIntel_Provider, EVENT_CONTROL_CODE_ENABLE_PROVIDER, TRACE_LEVEL_INFORMATION, matchAnyKeyword, 0, 0, &enableTraceParameters )) != ERROR_SUCCESS) { OutputDebugString(L"[!] Error EnableTraceEx - ThreatIntelligence\n"); } } // // Free traceProp after trace is successfully started // LocalFree(traceProp); hTrace = OpenTraceW(&trace); if (hTrace == INVALID_PROCESSTRACE_HANDLE) { OutputDebugString(L"[!] Error OpenTrace\n"); return 1; } // // Process the trace // result = ProcessTrace(&hTrace, 1, NULL, NULL); if (result != ERROR_SUCCESS) { printf("[!] Error ProcessTrace\n"); CloseTrace(hTrace); // Ensure hTrace is closed return result; } // // Close trace handle after processing is complete // CloseTrace(hTrace); return 0; } void ProcessEvent( _In_ PEVENT_RECORD EventRecord ) { PEVENT_HEADER eventHeader = &EventRecord->EventHeader; PEVENT_DESCRIPTOR eventDescriptor = &eventHeader->EventDescriptor; NTSTATUS status; if (eventHeader->ProviderId == JonMonTraceLogging) { status = WriteJonMonTraceLoggingEvents(EventRecord, eventHeader); if (status != ERROR_SUCCESS) { OutputDebugString(L"Error writing JonMon Trace Logging Events\n"); } } if (eventHeader->ProviderId == DotNet_Provider) { switch (eventDescriptor->Id) { case 154: { status = WriteDotNetEvents(EventRecord, eventHeader); if (status != ERROR_SUCCESS) { OutputDebugString(L"Error writing DotNet Events\n"); } break; } default: { break; } } } if (eventHeader->ProviderId == Network_Provider) { status = WriteNetworkEvents(EventRecord, eventHeader); if (status != ERROR_SUCCESS) { OutputDebugString(L"Error writing Network Events\n"); } } if (eventHeader->ProviderId == DPAPI_Provider) { switch (eventDescriptor->Id) { case 16385: { status = WriteDpapiEvents(EventRecord, eventHeader); if (status != ERROR_SUCCESS) { OutputDebugString(L"Error writing DPAPI Events\n"); } break; } default: { break; } } } if (eventHeader->ProviderId == WMIActivty_Provider) { switch (eventDescriptor->Id) { case 5861: { status = WriteWMIEvents(EventRecord, eventHeader); if (status != ERROR_SUCCESS) { OutputDebugString(L"Error writing WMI Events\n"); } break; } default: { break; } } } if (eventHeader->ProviderId == RPC_Provider) { switch (eventDescriptor->Id) { case 5: { status = WriteRpcEvents(EventRecord, eventHeader, 0); // 0 == CLIENT if (status != ERROR_SUCCESS) { OutputDebugString(L"Error writing RPC Events\n"); } break; } case 6: { status = WriteRpcEvents(EventRecord, eventHeader, 1); // 1 == SERVER if (status != ERROR_SUCCESS) { OutputDebugString(L"Error writing RPC Events\n"); } break; } default: { break; } } } if (eventHeader->ProviderId == AMSI_Provider) { switch (eventDescriptor->Id) { case 1101: { status = WriteAMSIEvents(EventRecord, eventHeader); if (status != ERROR_SUCCESS) { OutputDebugString(L"Error writing AMSI Events\n"); } break; } default: { break; } } } if (eventHeader->ProviderId == ThreatIntel_Provider) { status = WriteThreatIntelEvents(EventRecord, eventHeader); if (status != ERROR_SUCCESS) { OutputDebugString(L"Error writing Threat Intelligence Events\n"); } } } NTSTATUS WriteJonMonTraceLoggingEvents( _In_ PEVENT_RECORD EventRecord, _In_ PEVENT_HEADER EventHeader ) { NTSTATUS status = ERROR_SUCCESS; DWORD bufferSize = 0; PTRACE_EVENT_INFO pInfo = nullptr; BYTE** propertyDataVector = nullptr; int vectorCapacity = 10; int vectorSize = 0; SYSTEMTIME systemTime; // Fetch initial event information size status = TdhGetEventInformation(EventRecord, 0, NULL, NULL, &bufferSize); if (status == ERROR_INSUFFICIENT_BUFFER) { pInfo = (PTRACE_EVENT_INFO)malloc(bufferSize); if (!pInfo) { OutputDebugString(L"Error allocating memory for event info\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } status = TdhGetEventInformation(EventRecord, 0, NULL, pInfo, &bufferSize); } if (status != ERROR_SUCCESS) { OutputDebugString(L"Error fetching event info\n"); goto Exit; } // Allocate memory for property data vector propertyDataVector = (BYTE**)malloc(vectorCapacity * sizeof(BYTE*)); if (!propertyDataVector) { OutputDebugString(L"Error allocating memory for propertyDataVector\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } // Process each property in the event for (ULONG i = 0; i < pInfo->TopLevelPropertyCount; i++) { PROPERTY_DATA_DESCRIPTOR dataDescriptor; DWORD propertySize = 0; WCHAR* propertyName = (WCHAR*)((BYTE*)pInfo + pInfo->EventPropertyInfoArray[i].NameOffset); dataDescriptor.PropertyName = (ULONGLONG)propertyName; dataDescriptor.ArrayIndex = ULONG_MAX; // Determine the size of the property status = TdhGetPropertySize(EventRecord, 0, NULL, 1, &dataDescriptor, &propertySize); if (status != ERROR_SUCCESS) { wprintf(L"Error getting size for property %ls\n", propertyName); goto Exit; } BYTE* propertyData = (BYTE*)malloc(propertySize); if (!propertyData) { wprintf(L"Error allocating memory for property %ls\n", propertyName); goto Exit; } // Get the actual property data status = TdhGetProperty(EventRecord, 0, NULL, 1, &dataDescriptor, propertySize, propertyData); if (status != ERROR_SUCCESS) { wprintf(L"Error getting data for property %ls\n", propertyName); goto Exit; } // Check if we need to resize the vector if (vectorSize == vectorCapacity) { BYTE** resizedVector = (BYTE**)realloc(propertyDataVector, 2 * vectorCapacity * sizeof(BYTE*)); if (!resizedVector) { OutputDebugString(L"Error resizing propertyDataVector\n"); free(propertyData); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } propertyDataVector = resizedVector; vectorCapacity *= 2; } // Add the data to the vector propertyDataVector[vectorSize++] = propertyData; } switch (*(INT32*)propertyDataVector[0]) { case 1: { BOOL ProcessReParented = FALSE; printf("Process Creation Event\n"); PProcessCreationEvent processCreationEvent = (PProcessCreationEvent)malloc(sizeof(ProcessCreationEvent)); if (processCreationEvent == nullptr) { OutputDebugString(L"Error allocating memory for processCreationEvent\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } processCreationEvent->EventId = *(INT32*)propertyDataVector[0]; processCreationEvent->ProcessId = *(INT64*)propertyDataVector[1]; processCreationEvent->ProcessStartKey = *(UINT64*)propertyDataVector[2]; processCreationEvent->ParentProcessId = *(INT64*)propertyDataVector[3]; processCreationEvent->ParentProcessStartKey = *(UINT64*)propertyDataVector[4]; processCreationEvent->CreatorProcessId = *(INT64*)propertyDataVector[5]; processCreationEvent->CreatorThreadId = *(INT64*)propertyDataVector[6]; processCreationEvent->CommandLine = (WCHAR*)propertyDataVector[7]; processCreationEvent->EventTime = *(FILETIME*)propertyDataVector[8]; if (processCreationEvent->ParentProcessId != processCreationEvent->CreatorProcessId) { ProcessReParented = TRUE; } PProcessInformation processInformation = GetProcessName(processCreationEvent->ProcessId); // Check if processInformation is not nullptr before dereferencing it if (processInformation == nullptr) { printf("Process not found\n"); break; } PProcessInformation parentProcessInformation; parentProcessInformation = GetProcessName(processCreationEvent->ParentProcessId); // Check if processInformation is not nullptr before dereferencing it if (parentProcessInformation == nullptr) { printf("Parent Process not found\n"); break; } FileTimeToSystemTime(&processCreationEvent->EventTime, &systemTime); EventWriteProcessCreation( &systemTime, processCreationEvent->CreatorThreadId, processCreationEvent->CreatorProcessId, processCreationEvent->ParentProcessId, processCreationEvent->ParentProcessStartKey, parentProcessInformation->processName.c_str(), parentProcessInformation->userName.c_str(), parentProcessInformation->authenticationId.LowPart, parentProcessInformation->integrityLevel.c_str(), parentProcessInformation->sessionId, parentProcessInformation->tokenType, processInformation->processName.c_str(), processCreationEvent->CommandLine, processCreationEvent->ProcessId, processCreationEvent->ProcessStartKey, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->linkedAuthenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, processInformation->tokenType, ProcessReParented ); free(processCreationEvent); break; } case 2: { printf("Process Termination Event\n"); PProcessTerminationEvent processTerminationEvent = (PProcessTerminationEvent)malloc(sizeof(ProcessTerminationEvent)); if (processTerminationEvent == nullptr) { OutputDebugString(L"Error allocating memory for processTerminationEvent\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } processTerminationEvent->EventId = *(INT32*)propertyDataVector[0]; processTerminationEvent->ProcessId = *(INT64*)propertyDataVector[1]; processTerminationEvent->ProcessStartKey = *(UINT64*)propertyDataVector[2]; processTerminationEvent->ParentProcessId = *(INT64*)propertyDataVector[3]; processTerminationEvent->ParentProcessStartKey = *(UINT64*)propertyDataVector[4]; processTerminationEvent->EventTime = *(FILETIME*)propertyDataVector[5]; PProcessInformation processInformation = GetProcessName(processTerminationEvent->ProcessId); // Check if processInformation is not nullptr before dereferencing it if (processInformation == nullptr) { printf("Process not found\n"); break; } FileTimeToSystemTime(&processTerminationEvent->EventTime, &systemTime); EventWriteProcessTerminate( &systemTime, processTerminationEvent->ParentProcessId, processTerminationEvent->ParentProcessStartKey, processInformation->processName.c_str(), processTerminationEvent->ProcessId ); free(processTerminationEvent); break; } case 3: { printf("Remote Thread Creation Event\n"); PRemoteThreadCreationEvent remoteThreadCreationEvent = (PRemoteThreadCreationEvent)malloc(sizeof(RemoteThreadCreationEvent)); if (remoteThreadCreationEvent == nullptr) { OutputDebugString(L"Error allocating memory for remoteThreadCreationEvent\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } remoteThreadCreationEvent->EventId = *(INT32*)propertyDataVector[0]; remoteThreadCreationEvent->SourceThreadId = *(INT64*)propertyDataVector[1]; remoteThreadCreationEvent->SourceProcessId = *(INT64*)propertyDataVector[2]; remoteThreadCreationEvent->SourceProcessStartKey = *(UINT64*)propertyDataVector[3]; remoteThreadCreationEvent->NewThreadId = *(INT64*)propertyDataVector[4]; remoteThreadCreationEvent->TargetProcessId = *(INT64*)propertyDataVector[5]; remoteThreadCreationEvent->TargetProcessStartKey = *(UINT64*)propertyDataVector[6]; remoteThreadCreationEvent->EventTime = *(FILETIME*)propertyDataVector[7]; PProcessInformation processInformation = GetProcessName(remoteThreadCreationEvent->TargetProcessId); // Check if processInformation is not nullptr before dereferencing it if (processInformation == nullptr) { printf("Process not found\n"); break; } PProcessInformation sourceProcessInformation; sourceProcessInformation = GetProcessName(remoteThreadCreationEvent->SourceProcessId); // Check if processInformation is not nullptr before dereferencing it if (sourceProcessInformation == nullptr) { printf("Source Process not found\n"); break; } FileTimeToSystemTime(&remoteThreadCreationEvent->EventTime, &systemTime); EventWriteRemoteThreadCreation( &systemTime, remoteThreadCreationEvent->SourceProcessId, remoteThreadCreationEvent->SourceProcessStartKey, remoteThreadCreationEvent->SourceThreadId, sourceProcessInformation->processName.c_str(), sourceProcessInformation->userName.c_str(), sourceProcessInformation->authenticationId.LowPart, sourceProcessInformation->integrityLevel.c_str(), sourceProcessInformation->sessionId, sourceProcessInformation->tokenType, processInformation->processName.c_str(), remoteThreadCreationEvent->TargetProcessId, remoteThreadCreationEvent->TargetProcessStartKey, remoteThreadCreationEvent->NewThreadId, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->linkedAuthenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId ); // // Free the memory allocated for the event data // free(remoteThreadCreationEvent); break; } case 4: { printf("Load Image Event\n"); PLoadImageEvent loadImageEvent = (PLoadImageEvent)malloc(sizeof(LoadImageEvent)); if (loadImageEvent == nullptr) { OutputDebugString(L"Error allocating memory for loadImageEvent\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } loadImageEvent->EventId = *(INT32*)propertyDataVector[0]; loadImageEvent->ProcessId = *(INT64*)propertyDataVector[1]; loadImageEvent->ProcessStartKey = *(UINT64*)propertyDataVector[2]; loadImageEvent->ThreadId = *(INT64*)propertyDataVector[3]; loadImageEvent->SystemModeImage = *(ULONG*)propertyDataVector[4]; loadImageEvent->ImageName = (WCHAR*)propertyDataVector[5]; loadImageEvent->EventTime = *(FILETIME*)propertyDataVector[6]; FileTimeToSystemTime(&loadImageEvent->EventTime, &systemTime); if (loadImageEvent->SystemModeImage == 1) { printf("System Mode Image\n"); EventWriteImageLoaded( &systemTime, NULL, loadImageEvent->ProcessId, loadImageEvent->ThreadId, loadImageEvent->ProcessStartKey, NULL, 0, 0, NULL, 0, 0, loadImageEvent->ImageName, loadImageEvent->SystemModeImage, ); free(loadImageEvent); break; } PProcessInformation processInformation; processInformation = GetProcessName(loadImageEvent->ProcessId); // Check if processInformation is not nullptr before dereferencing it if (processInformation == nullptr) { printf("Process not found\n"); break; } EventWriteImageLoaded( &systemTime, processInformation->processName.c_str(), loadImageEvent->ProcessId, loadImageEvent->ThreadId, loadImageEvent->ProcessStartKey, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->linkedAuthenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, processInformation->tokenType, loadImageEvent->ImageName, loadImageEvent->SystemModeImage, ); // // Free the memory allocated for the event data // free(loadImageEvent); break; } case 5: { printf("Process Handle Event\n"); PProcessHandleEvent processHandleEvent = (PProcessHandleEvent)malloc(sizeof(ProcessHandleEvent)); if (processHandleEvent == nullptr) { OutputDebugString(L"Error allocating memory for processHandleEvent\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } processHandleEvent->EventId = *(INT32*)propertyDataVector[0]; processHandleEvent->SourceThreadId = *(INT64*)propertyDataVector[1]; processHandleEvent->SourceProcessId = *(INT64*)propertyDataVector[2]; processHandleEvent->SourceProcessStartKey = *(UINT64*)propertyDataVector[3]; processHandleEvent->TargetProcessId = *(INT64*)propertyDataVector[4]; processHandleEvent->TargetProcessStartKey = *(UINT64*)propertyDataVector[5]; processHandleEvent->OperationType = *(INT32*)propertyDataVector[6]; processHandleEvent->DesiredAccess = *(INT32*)propertyDataVector[7]; processHandleEvent->EventTime = *(FILETIME*)propertyDataVector[8]; FileTimeToSystemTime(&processHandleEvent->EventTime, &systemTime); PProcessInformation sourceProcessInformation; sourceProcessInformation = GetProcessName(processHandleEvent->SourceProcessId); // Check if processInformation is not nullptr before dereferencing it if (sourceProcessInformation == nullptr) { printf("Source Process not found\n"); break; } // // Check to see if source process contains JonMon-Service.exe // if (sourceProcessInformation->processName.find(L"Windows\\JonMon-Service.exe") != std::string::npos) { printf("Exiting because JonMon-Service is the source process\n"); break; } PProcessInformation targetProcessInformation; targetProcessInformation = GetProcessName(processHandleEvent->TargetProcessId); // Check if processInformation is not nullptr before dereferencing it if (targetProcessInformation == nullptr) { printf("Target Process not found\n"); break; } EventWriteProcessAccess( &systemTime, processHandleEvent->SourceProcessId, processHandleEvent->SourceThreadId, processHandleEvent->SourceProcessStartKey, sourceProcessInformation->processName.c_str(), sourceProcessInformation->userName.c_str(), sourceProcessInformation->authenticationId.LowPart, sourceProcessInformation->integrityLevel.c_str(), sourceProcessInformation->sessionId, sourceProcessInformation->tokenType, processHandleEvent->TargetProcessId, processHandleEvent->TargetProcessStartKey, targetProcessInformation->processName.c_str(), targetProcessInformation->userName.c_str(), targetProcessInformation->authenticationId.LowPart, targetProcessInformation->linkedAuthenticationId.LowPart, targetProcessInformation->integrityLevel.c_str(), targetProcessInformation->sessionId, targetProcessInformation->tokenType, processHandleEvent->DesiredAccess, processHandleEvent->OperationType ); // // Free the memory allocated for the event data // free(processHandleEvent); break; } case 6: { printf("Registry Save Key Event\n"); PRegistrySaveKeyEvent registrySaveKeyEvent = (PRegistrySaveKeyEvent)malloc(sizeof(RegistrySaveKeyEvent)); if (registrySaveKeyEvent == nullptr) { OutputDebugString(L"Error allocating memory for registrySaveKeyEvent\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } registrySaveKeyEvent->EventId = *(INT32*)propertyDataVector[0]; registrySaveKeyEvent->SourceThreadId = *(INT64*)propertyDataVector[1]; registrySaveKeyEvent->SourceProcessId = *(INT64*)propertyDataVector[2]; registrySaveKeyEvent->SourceProcessStartKey = *(UINT64*)propertyDataVector[3]; registrySaveKeyEvent->KeyPath = (WCHAR*)propertyDataVector[4]; registrySaveKeyEvent->EventTime = *(FILETIME*)propertyDataVector[5]; FileTimeToSystemTime(®istrySaveKeyEvent->EventTime, &systemTime); PProcessInformation processInformation; processInformation = GetProcessName(registrySaveKeyEvent->SourceProcessId); // Check if processInformation is not nullptr before dereferencing it if (processInformation == nullptr) { printf("Process not found\n"); break; } EventWriteRegistrySaveKey( &systemTime, processInformation->processName.c_str(), registrySaveKeyEvent->SourceProcessId, registrySaveKeyEvent->SourceThreadId, registrySaveKeyEvent->SourceProcessStartKey, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, registrySaveKeyEvent->KeyPath ); // // Free the memory allocated for the event data // free(registrySaveKeyEvent); break; } case 8: { printf("Registry Set Value Key Event\n"); PRegistrySetValueKeyEvent registrySetValueKeyEvent = (PRegistrySetValueKeyEvent)malloc(sizeof(RegistrySetValueKeyEvent)); if (registrySetValueKeyEvent == nullptr) { OutputDebugString(L"Error allocating memory for registrySetValueKeyEvent\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } registrySetValueKeyEvent->EventId = *(INT32*)propertyDataVector[0]; registrySetValueKeyEvent->SourceThreadId = *(INT64*)propertyDataVector[1]; registrySetValueKeyEvent->SourceProcessId = *(INT64*)propertyDataVector[2]; registrySetValueKeyEvent->SourceProcessStartKey = *(UINT64*)propertyDataVector[3]; registrySetValueKeyEvent->KeyPath = (WCHAR*)propertyDataVector[4]; registrySetValueKeyEvent->ValueName = (WCHAR*)propertyDataVector[5]; registrySetValueKeyEvent->Data = (WCHAR*)propertyDataVector[6]; registrySetValueKeyEvent->Type = *(INT32*)propertyDataVector[7]; registrySetValueKeyEvent->DataSize = *(INT32*)propertyDataVector[8]; registrySetValueKeyEvent->EventTime = *(FILETIME*)propertyDataVector[9]; FileTimeToSystemTime(®istrySetValueKeyEvent->EventTime, &systemTime); PProcessInformation processInformation; processInformation = GetProcessName(registrySetValueKeyEvent->SourceProcessId); // Check if processInformation is not nullptr before dereferencing it if (processInformation == nullptr) { printf("Process not found\n"); break; } EventWriteRegistrySetValueKey( &systemTime, processInformation->processName.c_str(), registrySetValueKeyEvent->SourceProcessId, registrySetValueKeyEvent->SourceThreadId, registrySetValueKeyEvent->SourceProcessStartKey, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, registrySetValueKeyEvent->KeyPath, registrySetValueKeyEvent->Type, registrySetValueKeyEvent->Data, registrySetValueKeyEvent->ValueName ); // // Free the memory allocated for the event data // free(registrySetValueKeyEvent); break; } case 9: { printf("Registry Create Key Event\n"); PRegistryCreateKeyEvent registryCreateKeyEvent = (PRegistryCreateKeyEvent)malloc(sizeof(RegistryCreateKeyEvent)); if (registryCreateKeyEvent == nullptr) { OutputDebugString(L"Error allocating memory for registryCreateKeyEvent\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } registryCreateKeyEvent->EventId = *(INT32*)propertyDataVector[0]; registryCreateKeyEvent->SourceThreadId = *(INT64*)propertyDataVector[1]; registryCreateKeyEvent->SourceProcessId = *(INT64*)propertyDataVector[2]; registryCreateKeyEvent->SourceProcessStartKey = *(UINT64*)propertyDataVector[3]; registryCreateKeyEvent->KeyPath = (WCHAR*)propertyDataVector[4]; registryCreateKeyEvent->DesiredAccess = *(INT32*)propertyDataVector[5]; registryCreateKeyEvent->EventTime = *(FILETIME*)propertyDataVector[6]; FileTimeToSystemTime(®istryCreateKeyEvent->EventTime, &systemTime); PProcessInformation processInformation; processInformation = GetProcessName(registryCreateKeyEvent->SourceProcessId); // Check if processInformation is not nullptr before dereferencing it if (processInformation == nullptr) { printf("Process not found\n"); break; } EventWriteRegistryCreateKey( &systemTime, processInformation->processName.c_str(), registryCreateKeyEvent->SourceProcessId, registryCreateKeyEvent->SourceThreadId, registryCreateKeyEvent->SourceProcessStartKey, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, registryCreateKeyEvent->KeyPath ); // // Free the memory allocated for the event data // free(registryCreateKeyEvent); break; } case 10: { printf("File Operation Event\n"); PFileCreationEvent fileCreationEvent = (PFileCreationEvent)malloc(sizeof(FileCreationEvent)); if (fileCreationEvent == nullptr) { OutputDebugString(L"Error allocating memory for fileCreationEvent\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } fileCreationEvent->EventId = *(INT32*)propertyDataVector[0]; fileCreationEvent->SourceThreadId = *(INT64*)propertyDataVector[1]; fileCreationEvent->SourceProcessId = *(INT64*)propertyDataVector[2]; fileCreationEvent->SourceProcessStartKey = *(UINT64*)propertyDataVector[3]; fileCreationEvent->FileName = (WCHAR*)propertyDataVector[4]; fileCreationEvent->EventTime = *(FILETIME*)propertyDataVector[5]; FileTimeToSystemTime(&fileCreationEvent->EventTime, &systemTime); // // Filter: Check to see if ending of the file is .exe, .sys, .dll, .js, .vbs, .ps1, .bat, .cmd, .hta, .msi. Set all fileNames to lowercase before checking // std::wstring fileName = fileCreationEvent->FileName; std::transform(fileName.begin(), fileName.end(), fileName.begin(), ::tolower); std::wregex validExtensions(LR"((\.exe|\.sys|\.dll|\.js|\.vbs|\.ps1|\.bat|\.cmd|\.hta|\.msi)$)"); bool hasValidExtension = std::regex_search(fileName, validExtensions); if (!hasValidExtension) { free(fileCreationEvent); break; } PProcessInformation processInformation; processInformation = GetProcessName(fileCreationEvent->SourceProcessId); // Check if processInformation is not nullptr before dereferencing it if (processInformation == nullptr) { printf("Process not found\n"); break; } EventWriteFileCreation( &systemTime, processInformation->processName.c_str(), fileCreationEvent->SourceProcessId, fileCreationEvent->SourceThreadId, fileCreationEvent->SourceProcessStartKey, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, fileCreationEvent->FileName ); // // Free the memory allocated for the event data // free(fileCreationEvent); break; } case 11: { printf("Named Pipe Creation Event\n"); PNamedPipeCreateEvent namedPipeCreationEvent = (PNamedPipeCreateEvent)malloc(sizeof(NamedPipeCreateEvent)); if (namedPipeCreationEvent == nullptr) { OutputDebugString(L"Error allocating memory for namedPipeCreationEvent\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } namedPipeCreationEvent->EventId = *(INT32*)propertyDataVector[0]; namedPipeCreationEvent->SourceThreadId = *(INT64*)propertyDataVector[1]; namedPipeCreationEvent->SourceProcessId = *(INT64*)propertyDataVector[2]; namedPipeCreationEvent->SourceProcessStartKey = *(UINT64*)propertyDataVector[3]; namedPipeCreationEvent->FileName = (WCHAR*)propertyDataVector[4]; namedPipeCreationEvent->RequestedRights = *(INT32*)propertyDataVector[5]; namedPipeCreationEvent->GrantedRights = *(INT32*)propertyDataVector[6]; namedPipeCreationEvent->EventTime = *(FILETIME*)propertyDataVector[7]; FileTimeToSystemTime(&namedPipeCreationEvent->EventTime, &systemTime); PProcessInformation processInformation; processInformation = GetProcessName(namedPipeCreationEvent->SourceProcessId); // Check if processInformation is not nullptr before dereferencing it if (processInformation == nullptr) { printf("Process not found\n"); break; } EventWriteNamedPipeCreation( &systemTime, processInformation->processName.c_str(), namedPipeCreationEvent->SourceProcessId, namedPipeCreationEvent->SourceThreadId, namedPipeCreationEvent->SourceProcessStartKey, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, namedPipeCreationEvent->FileName, namedPipeCreationEvent->RequestedRights ); // // Free the memory allocated for the event data // free(namedPipeCreationEvent); break; } case 12: { printf("Named Pipe Connection Event\n"); PNamedPipeConnectionEvent namedPipeConnectionEvent = (PNamedPipeConnectionEvent)malloc(sizeof(NamedPipeConnectionEvent)); if (namedPipeConnectionEvent == nullptr) { OutputDebugString(L"Error allocating memory for namedPipeConnectionEvent\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } namedPipeConnectionEvent->EventId = *(INT32*)propertyDataVector[0]; namedPipeConnectionEvent->SourceThreadId = *(INT64*)propertyDataVector[1]; namedPipeConnectionEvent->SourceProcessId = *(INT64*)propertyDataVector[2]; namedPipeConnectionEvent->SourceProcessStartKey = *(UINT64*)propertyDataVector[3]; namedPipeConnectionEvent->FileName = (WCHAR*)propertyDataVector[4]; namedPipeConnectionEvent->RequestedRights = *(INT32*)propertyDataVector[5]; namedPipeConnectionEvent->EventTime = *(FILETIME*)propertyDataVector[6]; FileTimeToSystemTime(&namedPipeConnectionEvent->EventTime, &systemTime); PProcessInformation processInformation; processInformation = GetProcessName(namedPipeConnectionEvent->SourceProcessId); // Check if processInformation is not nullptr before dereferencing it if (processInformation == nullptr) { printf("Process not found\n"); break; } EventWriteNamedPipeConnection( &systemTime, processInformation->processName.c_str(), namedPipeConnectionEvent->SourceProcessId, namedPipeConnectionEvent->SourceThreadId, namedPipeConnectionEvent->SourceProcessStartKey, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, namedPipeConnectionEvent->FileName, namedPipeConnectionEvent->RequestedRights ); // // Free the memory allocated for the event data // free(namedPipeConnectionEvent); break; } case 13: { printf("Mailslot Creation Event\n"); PMailslotCreateEvent mailslotCreationEvent = (PMailslotCreateEvent)malloc(sizeof(MailslotCreateEvent)); if (mailslotCreationEvent == nullptr) { OutputDebugString(L"Error allocating memory for mailslotCreationEvent\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } mailslotCreationEvent->EventId = *(INT32*)propertyDataVector[0]; mailslotCreationEvent->SourceThreadId = *(INT64*)propertyDataVector[1]; mailslotCreationEvent->SourceProcessId = *(INT64*)propertyDataVector[2]; mailslotCreationEvent->SourceProcessStartKey = *(UINT64*)propertyDataVector[3]; mailslotCreationEvent->FileName = (WCHAR*)propertyDataVector[4]; mailslotCreationEvent->RequestedRights = *(INT32*)propertyDataVector[5]; mailslotCreationEvent->EventTime = *(FILETIME*)propertyDataVector[6]; FileTimeToSystemTime(&mailslotCreationEvent->EventTime, &systemTime); PProcessInformation processInformation; processInformation = GetProcessName(mailslotCreationEvent->SourceProcessId); // Check if processInformation is not nullptr before dereferencing it if (processInformation == nullptr) { printf("Process not found\n"); break; } EventWriteMailslotCreation( &systemTime, processInformation->processName.c_str(), mailslotCreationEvent->SourceProcessId, mailslotCreationEvent->SourceThreadId, mailslotCreationEvent->SourceProcessStartKey, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, mailslotCreationEvent->FileName, mailslotCreationEvent->RequestedRights ); // // Free the memory allocated for the event data // free(mailslotCreationEvent); } case 14: { printf("Mailslot Connection Event\n"); PMailslotConnectionEvent mailslotConnectionEvent = (PMailslotConnectionEvent)malloc(sizeof(MailslotConnectionEvent)); if (mailslotConnectionEvent == nullptr) { OutputDebugString(L"Error allocating memory for mailslotConnectionEvent\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } mailslotConnectionEvent->EventId = *(INT32*)propertyDataVector[0]; mailslotConnectionEvent->SourceThreadId = *(INT64*)propertyDataVector[1]; mailslotConnectionEvent->SourceProcessId = *(INT64*)propertyDataVector[2]; mailslotConnectionEvent->SourceProcessStartKey = *(UINT64*)propertyDataVector[3]; mailslotConnectionEvent->FileName = (WCHAR*)propertyDataVector[4]; mailslotConnectionEvent->RequestedRights = *(INT32*)propertyDataVector[5]; mailslotConnectionEvent->EventTime = *(FILETIME*)propertyDataVector[6]; FileTimeToSystemTime(&mailslotConnectionEvent->EventTime, &systemTime); PProcessInformation processInformation; processInformation = GetProcessName(mailslotConnectionEvent->SourceProcessId); // Check if processInformation is not nullptr before dereferencing it if (processInformation == nullptr) { printf("Process not found\n"); break; } EventWriteMailslotConnection( &systemTime, processInformation->processName.c_str(), mailslotConnectionEvent->SourceProcessId, mailslotConnectionEvent->SourceThreadId, mailslotConnectionEvent->SourceProcessStartKey, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, mailslotConnectionEvent->FileName, mailslotConnectionEvent->RequestedRights ); // // Free the memory allocated for the event data // free(mailslotConnectionEvent); break; } case 15: { printf("Remote File Connection Event\n"); PRemoteFileConnectionEvent remoteFileConnectionEvent = (PRemoteFileConnectionEvent)malloc(sizeof(RemoteFileConnectionEvent)); remoteFileConnectionEvent->EventId = *(INT32*)propertyDataVector[0]; remoteFileConnectionEvent->SourceThreadId = *(INT64*)propertyDataVector[1]; remoteFileConnectionEvent->SourceProcessId = *(INT64*)propertyDataVector[2]; remoteFileConnectionEvent->SourceProcessStartKey = *(UINT64*)propertyDataVector[3]; remoteFileConnectionEvent->FileName = (WCHAR*)propertyDataVector[4]; remoteFileConnectionEvent->EventTime = *(FILETIME*)propertyDataVector[5]; FileTimeToSystemTime(&remoteFileConnectionEvent->EventTime, &systemTime); PProcessInformation processInformation; processInformation = GetProcessName(remoteFileConnectionEvent->SourceProcessId); // Check if processInformation is not nullptr before dereferencing it if (processInformation == nullptr) { printf("Process not found\n"); break; } EventWriteRemoteFileConnection( &systemTime, processInformation->processName.c_str(), remoteFileConnectionEvent->SourceProcessId, remoteFileConnectionEvent->SourceThreadId, remoteFileConnectionEvent->SourceProcessStartKey, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, remoteFileConnectionEvent->FileName ); // // Free the memory allocated for the event data // free(remoteFileConnectionEvent); break; } case 16: { std::wstring integirtyLevelString; OutputDebugStringW(L"Query - Thread Token Impersonation Event\n"); PThreadImpersonationEvent threadImpersonationEvent = (PThreadImpersonationEvent)malloc(sizeof(ThreadImpersonationEvent)); if (threadImpersonationEvent == nullptr) { OutputDebugString(L"Error allocating memory for threadImpersonationEvent\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } threadImpersonationEvent->EventId = *(INT32*)propertyDataVector[0]; threadImpersonationEvent->ThreadId = *(UINT32*)propertyDataVector[1]; threadImpersonationEvent->ProcessId = *(UINT32*)propertyDataVector[2]; threadImpersonationEvent->threadIntegrityLevel = *(UINT32*)propertyDataVector[3]; threadImpersonationEvent->EventTime = *(SYSTEMTIME*)propertyDataVector[4]; threadImpersonationEvent->ImpersonatedUser = (WCHAR*)propertyDataVector[5]; switch(threadImpersonationEvent->threadIntegrityLevel) { case 12288: integirtyLevelString = L"High"; break; case 16384: integirtyLevelString = L"System"; break; default: free(threadImpersonationEvent); goto Exit; } PProcessInformation processInformation; processInformation = GetProcessName(threadImpersonationEvent->ProcessId); // Check if processInformation is not nullptr before dereferencing it if (processInformation == nullptr) { OutputDebugStringW(L"Query - Thread Token Impersonation Event Process Information Not Found\n"); break; } EventWriteQueryTokenImpersonation( &threadImpersonationEvent->EventTime, processInformation->processName.c_str(), threadImpersonationEvent->ProcessId, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), threadImpersonationEvent->ThreadId, integirtyLevelString.c_str(), threadImpersonationEvent->ImpersonatedUser ); // // Free the memory allocated for the event data // free(threadImpersonationEvent); break; } case 100: { printf("TraceLogging Provider Registered Event\n"); PTraceLoggingProviderRegistered traceLoggingProviderRegistered = (PTraceLoggingProviderRegistered)malloc(sizeof(TraceLoggingProviderRegistered)); traceLoggingProviderRegistered->EventId = *(INT32*)propertyDataVector[0]; traceLoggingProviderRegistered->IsRegistered = *(BOOL*)propertyDataVector[1]; printf(" EventId %d\n", traceLoggingProviderRegistered->EventId); printf(" IsRegistered: %s\n", traceLoggingProviderRegistered->IsRegistered ? "true" : "false"); printf("\n"); // // Free the memory allocated for the event data // free(traceLoggingProviderRegistered); break; } case 101: { printf("Event Schema Configuration Event\n"); PEventSchemaConfiguration eventSchemaConfiguration = (PEventSchemaConfiguration)malloc(sizeof(EventSchemaConfiguration)); eventSchemaConfiguration->EventId = *(INT32*)propertyDataVector[0]; eventSchemaConfiguration->ProcessCreation = *(BOOL*)propertyDataVector[1]; eventSchemaConfiguration->ProcessTermination = *(BOOL*)propertyDataVector[2]; eventSchemaConfiguration->RegistryEvents = *(BOOL*)propertyDataVector[3]; eventSchemaConfiguration->ProcessHandleCreation = *(BOOL*)propertyDataVector[4]; eventSchemaConfiguration->ProcessHandleDuplication = *(BOOL*)propertyDataVector[5]; eventSchemaConfiguration->RemoteThreadCreation = *(BOOL*)propertyDataVector[6]; eventSchemaConfiguration->ImageLoad = *(BOOL*)propertyDataVector[7]; eventSchemaConfiguration->ThreadImpersonationEvents_KM = *(BOOL*)propertyDataVector[8]; eventSchemaConfiguration->FileEvents = *(BOOL*)propertyDataVector[9]; printf(" EventId %d\n", eventSchemaConfiguration->EventId); printf(" ProcessCreation %s\n", eventSchemaConfiguration->ProcessCreation ? "true" : "false"); printf(" ProcessTermination %s\n", eventSchemaConfiguration->ProcessTermination ? "true" : "false"); printf(" RegistryEvents %s\n", eventSchemaConfiguration->RegistryEvents ? "true" : "false"); printf(" ProcessHandleCreation %s\n", eventSchemaConfiguration->ProcessHandleCreation ? "true" : "false"); printf(" ProcessHandleDuplication %s\n", eventSchemaConfiguration->ProcessHandleDuplication ? "true" : "false"); printf(" RemoteThreadCreation %s\n", eventSchemaConfiguration->RemoteThreadCreation ? "true" : "false"); printf(" ImageLoad %s\n", eventSchemaConfiguration->ImageLoad ? "true" : "false"); printf(" ThreadImpersonationEvents_KM %s\n", eventSchemaConfiguration->ThreadImpersonationEvents_KM ? "true" : "false"); printf(" FileEvents %s\n", eventSchemaConfiguration->FileEvents ? "true" : "false"); printf("\n"); // // Free the memory allocated for the event data // free(eventSchemaConfiguration); break; } case 102: { PDebugLog debugLog = (PDebugLog)malloc(sizeof(DebugLog)); debugLog->EventId = *(INT32*)propertyDataVector[0]; debugLog->ProcessProtection = *(BOOL*)propertyDataVector[1]; OutputDebugString(L"Debug Log Event\n"); OutputDebugString(L" EventId: "); OutputDebugString(std::to_wstring(debugLog->EventId).c_str()); OutputDebugString(L"\n"); OutputDebugString(L" ProcessProtection: "); OutputDebugString(debugLog->ProcessProtection ? L"true" : L"false"); EventWriteDebugLog102( debugLog->EventId, debugLog->ProcessProtection ); free(debugLog); break; } default: { break; } } Exit: if (pInfo != nullptr) { free(pInfo); } // Free each element in propertyDataVector and the vector itself if (propertyDataVector != nullptr) { for (int i = 0; i < vectorSize; i++) { if (propertyDataVector[i] != nullptr) { free(propertyDataVector[i]); } } free(propertyDataVector); } return status; } NTSTATUS WriteThreatIntelEvents( _In_ PEVENT_RECORD EventRecord, _In_ PEVENT_HEADER EventHeader ) { NTSTATUS status = ERROR_SUCCESS; DWORD bufferSize = 0; PTRACE_EVENT_INFO pInfo = NULL; SYSTEMTIME systemTime; BYTE** propertyDataVector = NULL; PProcessInformation callingProcessInformation; PProcessInformation targetProcessInformation; GetSystemTime(&systemTime); switch (EventHeader->EventDescriptor.Id) { case 1: { UINT32 CallingProcessId, CallingThreadId, TargetProcessId, OriginalProcessId, AllocationType, ProtectionMask; UINT64 CallingProcessStartKey, TargetProcessStartKey, OriginalProcessStartKey, BaseAddress, RegionSize; FILETIME CallingProcessCreationTime, CallingThreadCreationTime, TargetProcessCreateTime, OriginalProcessCreateTime; UINT8 CallingProcessSignatureLevel, CallingProcessSectionSignatureLevel, CallingProcessProtection, TargetProcessSignatureLevel, TargetProcessSectionSignatureLevel, TargetProcessProtection, OriginalProcessSignatureLevel, OriginalProcessProtection, OriginalProcessSectionSignatureLevel; status = TdhGetEventInformation(EventRecord, 0, NULL, NULL, &bufferSize); if (status == ERROR_INSUFFICIENT_BUFFER) { pInfo = (PTRACE_EVENT_INFO)malloc(bufferSize); if (!pInfo) { OutputDebugString(L"Error allocating memory for event info\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } status = TdhGetEventInformation(EventRecord, 0, NULL, pInfo, &bufferSize); } if (status != ERROR_SUCCESS || pInfo == NULL) { OutputDebugString(L"Error fetching event info\n"); return status; } // // Allocate memory for property data vector // propertyDataVector = (BYTE**)malloc(sizeof(BYTE*) * pInfo->TopLevelPropertyCount); if (!propertyDataVector) { OutputDebugString(L"Error allocating memory for propertyDataVector\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } status = ProcessEtwEvent(EventRecord, pInfo, propertyDataVector); if (status != ERROR_SUCCESS) { OutputDebugString(L"Error processing ETW event\n"); goto Exit; } CallingProcessId = *(UINT32*)propertyDataVector[0]; CallingProcessCreationTime = *(FILETIME*)propertyDataVector[1]; CallingProcessStartKey = *(UINT64*)propertyDataVector[2]; CallingProcessSignatureLevel = *(UINT8*)propertyDataVector[3]; CallingProcessSectionSignatureLevel = *(UINT8*)propertyDataVector[4]; CallingProcessProtection = *(UINT8*)propertyDataVector[5]; CallingThreadId = *(UINT32*)propertyDataVector[6]; CallingThreadCreationTime = *(FILETIME*)propertyDataVector[7]; TargetProcessId = *(UINT32*)propertyDataVector[8]; TargetProcessCreateTime = *(FILETIME*)propertyDataVector[9]; TargetProcessStartKey = *(UINT64*)propertyDataVector[10]; TargetProcessSignatureLevel = *(UINT8*)propertyDataVector[11]; TargetProcessSectionSignatureLevel = *(UINT8*)propertyDataVector[12]; TargetProcessProtection = *(UINT8*)propertyDataVector[13]; OriginalProcessId = *(UINT32*)propertyDataVector[14]; OriginalProcessCreateTime = *(FILETIME*)propertyDataVector[15]; OriginalProcessStartKey = *(UINT64*)propertyDataVector[16]; OriginalProcessSignatureLevel = *(UINT8*)propertyDataVector[17]; OriginalProcessSectionSignatureLevel = *(UINT8*)propertyDataVector[18]; OriginalProcessProtection = *(UINT8*)propertyDataVector[19]; BaseAddress = *(UINT64*)propertyDataVector[20]; RegionSize = *(UINT64*)propertyDataVector[21]; AllocationType = *(UINT32*)propertyDataVector[22]; ProtectionMask = *(UINT32*)propertyDataVector[23]; if (CallingProcessId == TargetProcessId) { goto Exit; } callingProcessInformation = GetProcessName(CallingProcessId); if (callingProcessInformation == nullptr) { OutputDebugString(L"ThreatIntel ETW - Error getting process name\n"); goto Exit; } targetProcessInformation = GetProcessName(TargetProcessId); if (targetProcessInformation == nullptr) { OutputDebugString(L"ThreatIntel ETW - Error getting process name\n"); goto Exit; } EventWriteRemoteVirtualAllocation( &systemTime, callingProcessInformation->processName.c_str(), callingProcessInformation->processId, callingProcessInformation->userName.c_str(), callingProcessInformation->authenticationId.LowPart, callingProcessInformation->integrityLevel.c_str(), callingProcessInformation->sessionId, CallingThreadId, targetProcessInformation->processName.c_str(), targetProcessInformation->processId, targetProcessInformation->userName.c_str(), targetProcessInformation->authenticationId.LowPart, targetProcessInformation->integrityLevel.c_str(), targetProcessInformation->sessionId, CallingProcessStartKey, TargetProcessStartKey, BaseAddress ); goto Exit; } case 4: { UINT32 CallingProcessId, CallingThreadId, TargetProcessId, OriginalProcessId, TargetThreadId; UINT64 CallingProcessStartKey, TargetProcessStartKey, OriginalProcessStartKey, ApcRoutine, ApcArgument1, ApcArgument2, ApcArgument3; FILETIME CallingProcessCreationTime, CallingThreadCreationTime, TargetProcessCreateTime, OriginalProcessCreateTime, RealEventTime, TargetThreadCreateTime; UINT8 CallingProcessSignatureLevel, CallingProcessSectionSignatureLevel, CallingProcessProtection, TargetProcessSignatureLevel, TargetProcessSectionSignatureLevel, TargetProcessProtection, OriginalProcessSignatureLevel, OriginalProcessProtection, OriginalProcessSectionSignatureLevel, TargetThreadAlertable; status = TdhGetEventInformation(EventRecord, 0, NULL, NULL, &bufferSize); if (status == ERROR_INSUFFICIENT_BUFFER) { pInfo = (PTRACE_EVENT_INFO)malloc(bufferSize); if (!pInfo) { OutputDebugString(L"Error allocating memory for event info\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } status = TdhGetEventInformation(EventRecord, 0, NULL, pInfo, &bufferSize); } if (status != ERROR_SUCCESS) { OutputDebugString(L"Error fetching event info\n"); return status; } // // Allocate memory for property data vector // propertyDataVector = (BYTE**)malloc(sizeof(BYTE*) * pInfo->TopLevelPropertyCount); if (!propertyDataVector) { OutputDebugString(L"Error allocating memory for propertyDataVector\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } status = ProcessEtwEvent(EventRecord, pInfo, propertyDataVector); if (status != ERROR_SUCCESS) { OutputDebugString(L"Error processing ETW event\n"); goto Exit; } CallingProcessId = *(UINT32*)propertyDataVector[0]; CallingProcessCreationTime = *(FILETIME*)propertyDataVector[1]; CallingProcessStartKey = *(UINT64*)propertyDataVector[2]; CallingProcessSignatureLevel = *(UINT8*)propertyDataVector[3]; CallingProcessSectionSignatureLevel = *(UINT8*)propertyDataVector[4]; CallingProcessProtection = *(UINT8*)propertyDataVector[5]; CallingThreadId = *(UINT32*)propertyDataVector[6]; CallingThreadCreationTime = *(FILETIME*)propertyDataVector[7]; TargetProcessId = *(UINT32*)propertyDataVector[8]; TargetProcessCreateTime = *(FILETIME*)propertyDataVector[9]; TargetProcessStartKey = *(UINT64*)propertyDataVector[10]; TargetProcessSignatureLevel = *(UINT8*)propertyDataVector[11]; TargetProcessSectionSignatureLevel = *(UINT8*)propertyDataVector[12]; TargetProcessProtection = *(UINT8*)propertyDataVector[13]; TargetThreadId = *(UINT32*)propertyDataVector[14]; TargetThreadCreateTime = *(FILETIME*)propertyDataVector[15]; OriginalProcessId = *(UINT32*)propertyDataVector[16]; OriginalProcessCreateTime = *(FILETIME*)propertyDataVector[17]; OriginalProcessStartKey = *(UINT64*)propertyDataVector[18]; OriginalProcessSignatureLevel = *(UINT8*)propertyDataVector[19]; OriginalProcessSectionSignatureLevel = *(UINT8*)propertyDataVector[20]; OriginalProcessProtection = *(UINT8*)propertyDataVector[21]; TargetThreadAlertable = *(UINT8*)propertyDataVector[22]; ApcRoutine = *(UINT64*)propertyDataVector[23]; ApcArgument1 = *(UINT64*)propertyDataVector[24]; ApcArgument2 = *(UINT64*)propertyDataVector[25]; ApcArgument3 = *(UINT64*)propertyDataVector[26]; RealEventTime = *(FILETIME*)propertyDataVector[27]; callingProcessInformation = GetProcessName(CallingProcessId); if (callingProcessInformation == nullptr) { OutputDebugString(L"ThreatIntel ETW - Error getting process name\n"); goto Exit; } targetProcessInformation = GetProcessName(TargetProcessId); if (targetProcessInformation == nullptr) { OutputDebugString(L"ThreatIntel ETW - Error getting process name\n"); goto Exit; } EventWriteRemoteQueueUserAPC( &systemTime, callingProcessInformation->processName.c_str(), callingProcessInformation->processId, callingProcessInformation->userName.c_str(), callingProcessInformation->authenticationId.LowPart, callingProcessInformation->integrityLevel.c_str(), callingProcessInformation->sessionId, CallingThreadId, targetProcessInformation->processName.c_str(), targetProcessInformation->processId, targetProcessInformation->userName.c_str(), targetProcessInformation->authenticationId.LowPart, targetProcessInformation->integrityLevel.c_str(), targetProcessInformation->sessionId, CallingProcessStartKey, TargetProcessStartKey, ApcRoutine, ApcArgument1, ApcArgument2, ApcArgument3 ); goto Exit; } case 13: { // // check to see if there is a second between lastEventTime and systemTime // if (systemTime.wSecond - lastEventTime.wSecond < 1) { goto Exit; } lastEventTime = systemTime; UINT32 OperationStatus, CallingProcessId, CallingThreadId, TargetProcessId; FILETIME CallingProcessCreateTime, CallingThreadCreateTime, TargetProcessCreateTime; UINT64 CallingProcessStartKey, TargetProcessStartKey, BaseAddress, BytesCopied; UINT8 CallingProcessSignatureLevel, CallingProcessSectionSignatureLevel, CallingProcessProtection, TargetProcessSignatureLevel, TargetProcessSectionSignatureLevel, TargetProcessProtection; status = TdhGetEventInformation(EventRecord, 0, NULL, NULL, &bufferSize); if (status == ERROR_INSUFFICIENT_BUFFER) { pInfo = (PTRACE_EVENT_INFO)malloc(bufferSize); if (!pInfo) { OutputDebugString(L"Error allocating memory for event info\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } status = TdhGetEventInformation(EventRecord, 0, NULL, pInfo, &bufferSize); } if (status != ERROR_SUCCESS) { OutputDebugString(L"Error fetching event info\n"); return status; } // // Allocate memory for property data vector // propertyDataVector = (BYTE**)malloc(sizeof(BYTE*) * pInfo->TopLevelPropertyCount); if (!propertyDataVector) { OutputDebugString(L"Error allocating memory for propertyDataVector\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } status = ProcessEtwEvent(EventRecord, pInfo, propertyDataVector); if (status != ERROR_SUCCESS) { OutputDebugString(L"Error processing ETW event\n"); goto Exit; } OperationStatus = *(UINT32*)propertyDataVector[0]; CallingProcessId = *(UINT32*)propertyDataVector[1]; CallingProcessCreateTime = *(FILETIME*)propertyDataVector[2]; CallingProcessStartKey = *(UINT64*)propertyDataVector[3]; CallingProcessSignatureLevel = *(UINT8*)propertyDataVector[4]; CallingProcessSectionSignatureLevel = *(UINT8*)propertyDataVector[5]; CallingProcessProtection = *(UINT8*)propertyDataVector[6]; CallingThreadId = *(UINT32*)propertyDataVector[7]; CallingThreadCreateTime = *(FILETIME*)propertyDataVector[8]; TargetProcessId = *(UINT32*)propertyDataVector[9]; TargetProcessCreateTime = *(FILETIME*)propertyDataVector[10]; TargetProcessStartKey = *(UINT64*)propertyDataVector[11]; TargetProcessSignatureLevel = *(UINT8*)propertyDataVector[12]; TargetProcessSectionSignatureLevel = *(UINT8*)propertyDataVector[13]; TargetProcessProtection = *(UINT8*)propertyDataVector[14]; BaseAddress = *(UINT64*)propertyDataVector[15]; BytesCopied = *(UINT64*)propertyDataVector[16]; if (TargetProcessId != lsassPID) { goto Exit; } callingProcessInformation = GetProcessName(CallingProcessId); if (callingProcessInformation == nullptr) { OutputDebugString(L"ThreatIntel ETW - Error getting process name\n"); goto Exit; } targetProcessInformation = GetProcessName(TargetProcessId); if (targetProcessInformation == nullptr) { OutputDebugString(L"ThreatIntel ETW - Error getting process name\n"); goto Exit; } EventWriteRemoteReadProcessMemory( &systemTime, callingProcessInformation->processName.c_str(), callingProcessInformation->processId, callingProcessInformation->userName.c_str(), callingProcessInformation->authenticationId.LowPart, callingProcessInformation->integrityLevel.c_str(), callingProcessInformation->sessionId, CallingThreadId, targetProcessInformation->processName.c_str(), targetProcessInformation->processId, targetProcessInformation->userName.c_str(), targetProcessInformation->authenticationId.LowPart, targetProcessInformation->integrityLevel.c_str(), targetProcessInformation->sessionId, CallingProcessStartKey, TargetProcessStartKey ); goto Exit; } case 14: { UINT32 OperationStatus, CallingProcessId, CallingThreadId, TargetProcessId; FILETIME CallingProcessCreateTime, CallingThreadCreateTime, TargetProcessCreateTime; UINT64 CallingProcessStartKey, TargetProcessStartKey, BaseAddress, BytesCopied; UINT8 CallingProcessSignatureLevel, CallingProcessSectionSignatureLevel, CallingProcessProtection, TargetProcessSignatureLevel, TargetProcessSectionSignatureLevel, TargetProcessProtection; status = TdhGetEventInformation(EventRecord, 0, NULL, NULL, &bufferSize); if (status == ERROR_INSUFFICIENT_BUFFER) { pInfo = (PTRACE_EVENT_INFO)malloc(bufferSize); if (!pInfo) { OutputDebugString(L"Error allocating memory for event info\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } status = TdhGetEventInformation(EventRecord, 0, NULL, pInfo, &bufferSize); } if (status != ERROR_SUCCESS) { OutputDebugString(L"Error fetching event info\n"); return status; } // // Allocate memory for property data vector // propertyDataVector = (BYTE**)malloc(sizeof(BYTE*) * pInfo->TopLevelPropertyCount); if (!propertyDataVector) { OutputDebugString(L"Error allocating memory for propertyDataVector\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } status = ProcessEtwEvent(EventRecord, pInfo, propertyDataVector); if (status != ERROR_SUCCESS) { OutputDebugString(L"Error processing ETW event\n"); goto Exit; } OperationStatus = *(UINT32*)propertyDataVector[0]; CallingProcessId = *(UINT32*)propertyDataVector[1]; CallingProcessCreateTime = *(FILETIME*)propertyDataVector[2]; CallingProcessStartKey = *(UINT64*)propertyDataVector[3]; CallingProcessSignatureLevel = *(UINT8*)propertyDataVector[4]; CallingProcessSectionSignatureLevel = *(UINT8*)propertyDataVector[5]; CallingProcessProtection = *(UINT8*)propertyDataVector[6]; CallingThreadId = *(UINT32*)propertyDataVector[7]; CallingThreadCreateTime = *(FILETIME*)propertyDataVector[8]; TargetProcessId = *(UINT32*)propertyDataVector[9]; TargetProcessCreateTime = *(FILETIME*)propertyDataVector[10]; TargetProcessStartKey = *(UINT64*)propertyDataVector[11]; TargetProcessSignatureLevel = *(UINT8*)propertyDataVector[12]; TargetProcessSectionSignatureLevel = *(UINT8*)propertyDataVector[13]; TargetProcessProtection = *(UINT8*)propertyDataVector[14]; BaseAddress = *(UINT64*)propertyDataVector[15]; BytesCopied = *(UINT64*)propertyDataVector[16]; callingProcessInformation = GetProcessName(CallingProcessId); if (callingProcessInformation == nullptr) { OutputDebugString(L"ThreatIntel ETW - Error getting process name\n"); goto Exit; } targetProcessInformation = GetProcessName(TargetProcessId); if (targetProcessInformation == nullptr) { OutputDebugString(L"ThreatIntel ETW - Error getting process name\n"); goto Exit; } EventWriteRemoteWriteProcessMemory( &systemTime, callingProcessInformation->processName.c_str(), callingProcessInformation->processId, callingProcessInformation->userName.c_str(), callingProcessInformation->authenticationId.LowPart, callingProcessInformation->integrityLevel.c_str(), callingProcessInformation->sessionId, CallingThreadId, targetProcessInformation->processName.c_str(), targetProcessInformation->processId, targetProcessInformation->userName.c_str(), targetProcessInformation->authenticationId.LowPart, targetProcessInformation->integrityLevel.c_str(), targetProcessInformation->sessionId, CallingProcessStartKey, TargetProcessStartKey ); goto Exit; } case 21: { UINT32 CallingProcessId, CallingThreadId, TargetProcessId, OriginalProcessId, AllocationType, ProtectionMask; UINT64 CallingProcessStartKey, TargetProcessStartKey, OriginalProcessStartKey, BaseAddress, RegionSize; FILETIME CallingProcessCreationTime, CallingThreadCreationTime, TargetProcessCreateTime, OriginalProcessCreateTime; UINT8 CallingProcessSignatureLevel, CallingProcessSectionSignatureLevel, CallingProcessProtection, TargetProcessSignatureLevel, TargetProcessSectionSignatureLevel, TargetProcessProtection, OriginalProcessSignatureLevel, OriginalProcessProtection, OriginalProcessSectionSignatureLevel; status = TdhGetEventInformation(EventRecord, 0, NULL, NULL, &bufferSize); if (status == ERROR_INSUFFICIENT_BUFFER) { pInfo = (PTRACE_EVENT_INFO)malloc(bufferSize); if (!pInfo) { OutputDebugString(L"Error allocating memory for event info\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } status = TdhGetEventInformation(EventRecord, 0, NULL, pInfo, &bufferSize); } if (status != ERROR_SUCCESS) { OutputDebugString(L"Error fetching event info\n"); return status; } // // Allocate memory for property data vector // propertyDataVector = (BYTE**)malloc(sizeof(BYTE*) * pInfo->TopLevelPropertyCount); if (!propertyDataVector) { OutputDebugString(L"Error allocating memory for propertyDataVector\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } status = ProcessEtwEvent(EventRecord, pInfo, propertyDataVector); if (status != ERROR_SUCCESS) { OutputDebugString(L"Error processing ETW event\n"); goto Exit; } CallingProcessId = *(UINT32*)propertyDataVector[0]; CallingProcessCreationTime = *(FILETIME*)propertyDataVector[1]; CallingProcessStartKey = *(UINT64*)propertyDataVector[2]; CallingProcessSignatureLevel = *(UINT8*)propertyDataVector[3]; CallingProcessSectionSignatureLevel = *(UINT8*)propertyDataVector[4]; CallingProcessProtection = *(UINT8*)propertyDataVector[5]; CallingThreadId = *(UINT32*)propertyDataVector[6]; CallingThreadCreationTime = *(FILETIME*)propertyDataVector[7]; TargetProcessId = *(UINT32*)propertyDataVector[8]; TargetProcessCreateTime = *(FILETIME*)propertyDataVector[9]; TargetProcessStartKey = *(UINT64*)propertyDataVector[10]; TargetProcessSignatureLevel = *(UINT8*)propertyDataVector[11]; TargetProcessSectionSignatureLevel = *(UINT8*)propertyDataVector[12]; TargetProcessProtection = *(UINT8*)propertyDataVector[13]; OriginalProcessId = *(UINT32*)propertyDataVector[14]; OriginalProcessCreateTime = *(FILETIME*)propertyDataVector[15]; OriginalProcessStartKey = *(UINT64*)propertyDataVector[16]; OriginalProcessSignatureLevel = *(UINT8*)propertyDataVector[17]; OriginalProcessSectionSignatureLevel = *(UINT8*)propertyDataVector[18]; OriginalProcessProtection = *(UINT8*)propertyDataVector[19]; BaseAddress = *(UINT64*)propertyDataVector[20]; RegionSize = *(UINT64*)propertyDataVector[21]; AllocationType = *(UINT32*)propertyDataVector[22]; ProtectionMask = *(UINT32*)propertyDataVector[23]; if (CallingProcessId == TargetProcessId) { goto Exit; } callingProcessInformation = GetProcessName(CallingProcessId); if (callingProcessInformation == nullptr) { OutputDebugString(L"ThreatIntel ETW - Error getting process name\n"); goto Exit; } targetProcessInformation = GetProcessName(TargetProcessId); if (targetProcessInformation == nullptr) { OutputDebugString(L"ThreatIntel ETW - Error getting process name\n"); goto Exit; } EventWriteRemoteReadProcessMemory( &systemTime, callingProcessInformation->processName.c_str(), callingProcessInformation->processId, callingProcessInformation->userName.c_str(), callingProcessInformation->authenticationId.LowPart, callingProcessInformation->integrityLevel.c_str(), callingProcessInformation->sessionId, CallingThreadId, targetProcessInformation->processName.c_str(), targetProcessInformation->processId, targetProcessInformation->userName.c_str(), targetProcessInformation->authenticationId.LowPart, targetProcessInformation->integrityLevel.c_str(), targetProcessInformation->sessionId, CallingProcessStartKey, TargetProcessStartKey ); goto Exit; } case 24: { UINT32 CallingProcessId, CallingThreadId, TargetProcessId, OriginalProcessId, TargetThreadId; UINT64 CallingProcessStartKey, TargetProcessStartKey, OriginalProcessStartKey, ApcRoutine, ApcArgument1, ApcArgument2, ApcArgument3; FILETIME CallingProcessCreationTime, CallingThreadCreationTime, TargetProcessCreateTime, OriginalProcessCreateTime, RealEventTime, TargetThreadCreateTime; UINT8 CallingProcessSignatureLevel, CallingProcessSectionSignatureLevel, CallingProcessProtection, TargetProcessSignatureLevel, TargetProcessSectionSignatureLevel, TargetProcessProtection, OriginalProcessSignatureLevel, OriginalProcessProtection, OriginalProcessSectionSignatureLevel, TargetThreadAlertable; status = TdhGetEventInformation(EventRecord, 0, NULL, NULL, &bufferSize); if (status == ERROR_INSUFFICIENT_BUFFER) { pInfo = (PTRACE_EVENT_INFO)malloc(bufferSize); if (!pInfo) { OutputDebugString(L"Error allocating memory for event info\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } status = TdhGetEventInformation(EventRecord, 0, NULL, pInfo, &bufferSize); } if (status != ERROR_SUCCESS) { OutputDebugString(L"Error fetching event info\n"); return status; } // // Allocate memory for property data vector // propertyDataVector = (BYTE**)malloc(sizeof(BYTE*) * pInfo->TopLevelPropertyCount); if (!propertyDataVector) { OutputDebugString(L"Error allocating memory for propertyDataVector\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } status = ProcessEtwEvent(EventRecord, pInfo, propertyDataVector); if (status != ERROR_SUCCESS) { OutputDebugString(L"Error processing ETW event\n"); goto Exit; } CallingProcessId = *(UINT32*)propertyDataVector[0]; CallingProcessCreationTime = *(FILETIME*)propertyDataVector[1]; CallingProcessStartKey = *(UINT64*)propertyDataVector[2]; CallingProcessSignatureLevel = *(UINT8*)propertyDataVector[3]; CallingProcessSectionSignatureLevel = *(UINT8*)propertyDataVector[4]; CallingProcessProtection = *(UINT8*)propertyDataVector[5]; CallingThreadId = *(UINT32*)propertyDataVector[6]; CallingThreadCreationTime = *(FILETIME*)propertyDataVector[7]; TargetProcessId = *(UINT32*)propertyDataVector[8]; TargetProcessCreateTime = *(FILETIME*)propertyDataVector[9]; TargetProcessStartKey = *(UINT64*)propertyDataVector[10]; TargetProcessSignatureLevel = *(UINT8*)propertyDataVector[11]; TargetProcessSectionSignatureLevel = *(UINT8*)propertyDataVector[12]; TargetProcessProtection = *(UINT8*)propertyDataVector[13]; TargetThreadId = *(UINT32*)propertyDataVector[14]; TargetThreadCreateTime = *(FILETIME*)propertyDataVector[15]; OriginalProcessId = *(UINT32*)propertyDataVector[16]; OriginalProcessCreateTime = *(FILETIME*)propertyDataVector[17]; OriginalProcessStartKey = *(UINT64*)propertyDataVector[18]; OriginalProcessSignatureLevel = *(UINT8*)propertyDataVector[19]; OriginalProcessSectionSignatureLevel = *(UINT8*)propertyDataVector[20]; OriginalProcessProtection = *(UINT8*)propertyDataVector[21]; TargetThreadAlertable = *(UINT8*)propertyDataVector[22]; ApcRoutine = *(UINT64*)propertyDataVector[23]; ApcArgument1 = *(UINT64*)propertyDataVector[24]; ApcArgument2 = *(UINT64*)propertyDataVector[25]; ApcArgument3 = *(UINT64*)propertyDataVector[26]; RealEventTime = *(FILETIME*)propertyDataVector[27]; callingProcessInformation = GetProcessName(CallingProcessId); if (callingProcessInformation == nullptr) { OutputDebugString(L"ThreatIntel ETW - Error getting process name\n"); goto Exit; } targetProcessInformation = GetProcessName(TargetProcessId); if (targetProcessInformation == nullptr) { OutputDebugString(L"ThreatIntel ETW - Error getting process name\n"); goto Exit; } EventWriteRemoteQueueUserAPC( &systemTime, callingProcessInformation->processName.c_str(), callingProcessInformation->processId, callingProcessInformation->userName.c_str(), callingProcessInformation->authenticationId.LowPart, callingProcessInformation->integrityLevel.c_str(), callingProcessInformation->sessionId, CallingThreadId, targetProcessInformation->processName.c_str(), targetProcessInformation->processId, targetProcessInformation->userName.c_str(), targetProcessInformation->authenticationId.LowPart, targetProcessInformation->integrityLevel.c_str(), targetProcessInformation->sessionId, CallingProcessStartKey, TargetProcessStartKey, ApcRoutine, ApcArgument1, ApcArgument2, ApcArgument3 ); goto Exit; } default: { goto Exit; } } Exit: // Free each element in propertyDataVector and the vector itself if (propertyDataVector != nullptr) { for (int i = 0; i < pInfo->TopLevelPropertyCount; i++) { if (propertyDataVector[i] != nullptr) { free(propertyDataVector[i]); } } free(propertyDataVector); } if (pInfo != nullptr) { free(pInfo); } return 0; } BOOL WriteNetworkEvents( _In_ PEVENT_RECORD EventRecord, _In_ PEVENT_HEADER EventHeader ) { NTSTATUS status = ERROR_SUCCESS; DWORD bufferSize = 0; PTRACE_EVENT_INFO pInfo = nullptr; BYTE** propertyDataVector = nullptr; int vectorCapacity = 10; int vectorSize = 0; SYSTEMTIME systemTime; UINT32 processId, size, sourceAddress, destinationAddress; UINT16 sourcePort, destinationPort; PProcessInformation processInformation; WCHAR wide_deststring_ip[INET_ADDRSTRLEN]; WCHAR wide_sourcestring_ip[INET_ADDRSTRLEN]; struct in_addr srceaddr = {}; struct in_addr destaddr = {}; BOOL isInitiated = false; switch (EventHeader->EventDescriptor.Id) { case 10: { isInitiated = true; // // Get System Time // GetSystemTime(&systemTime); // Fetch initial event information size status = TdhGetEventInformation(EventRecord, 0, NULL, NULL, &bufferSize); if (status == ERROR_INSUFFICIENT_BUFFER) { pInfo = (PTRACE_EVENT_INFO)malloc(bufferSize); if (!pInfo) { OutputDebugString(L"Error allocating memory for event info\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } status = TdhGetEventInformation(EventRecord, 0, NULL, pInfo, &bufferSize); } if (status != ERROR_SUCCESS) { OutputDebugString(L"Error fetching event info\n"); return status; } // Allocate memory for property data vector propertyDataVector = (BYTE**)malloc(vectorCapacity * sizeof(BYTE*)); if (!propertyDataVector) { OutputDebugString(L"Error allocating memory for propertyDataVector\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } // Process each property in the event for (ULONG i = 0; i < pInfo->TopLevelPropertyCount; i++) { PROPERTY_DATA_DESCRIPTOR dataDescriptor; DWORD propertySize = 0; WCHAR* propertyName = (WCHAR*)((BYTE*)pInfo + pInfo->EventPropertyInfoArray[i].NameOffset); dataDescriptor.PropertyName = (ULONGLONG)propertyName; dataDescriptor.ArrayIndex = ULONG_MAX; // Determine the size of the property status = TdhGetPropertySize(EventRecord, 0, NULL, 1, &dataDescriptor, &propertySize); if (status != ERROR_SUCCESS) { wprintf(L"Error getting size for property %ls\n", propertyName); goto Exit; } BYTE* propertyData = (BYTE*)malloc(propertySize); if (!propertyData) { wprintf(L"Error allocating memory for property %ls\n", propertyName); goto Exit; } // Get the actual property data status = TdhGetProperty(EventRecord, 0, NULL, 1, &dataDescriptor, propertySize, propertyData); if (status != ERROR_SUCCESS) { wprintf(L"Error getting data for property %ls\n", propertyName); goto Exit; } // Check if we need to resize the vector if (vectorSize == vectorCapacity) { BYTE** resizedVector = (BYTE**)realloc(propertyDataVector, 2 * vectorCapacity * sizeof(BYTE*)); if (!resizedVector) { OutputDebugString(L"Error resizing propertyDataVector\n"); goto Exit; } propertyDataVector = resizedVector; vectorCapacity *= 2; } // Add the data to the vector propertyDataVector[vectorSize++] = propertyData; } processId = *(UINT32*)propertyDataVector[0]; if (processId == 4) { goto Exit; } size = *(UINT32*)propertyDataVector[1]; destinationAddress = *(UINT32*)propertyDataVector[2]; sourceAddress = *(UINT32*)propertyDataVector[3]; sourcePort = *(UINT16*)propertyDataVector[4]; destinationPort = *(UINT16*)propertyDataVector[5]; destaddr.s_addr = destinationAddress; srceaddr.s_addr = sourceAddress; InetNtop(AF_INET, &srceaddr, wide_sourcestring_ip, INET_ADDRSTRLEN); InetNtop(AF_INET, &destaddr, wide_deststring_ip, INET_ADDRSTRLEN); processInformation = GetProcessName(processId); if (processInformation == nullptr) { OutputDebugString(L"DotNet ETW - Error getting process name\n"); goto Exit; } if (processInformation->integrityLevel == L"Low") { goto Exit; } EventWriteNetworkConnection( &systemTime, processId, processInformation->processName.c_str(), wide_sourcestring_ip, wide_deststring_ip, sourcePort, destinationPort, isInitiated, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId ); break; } case 11: { // // Get System Time // GetSystemTime(&systemTime); // Fetch initial event information size status = TdhGetEventInformation(EventRecord, 0, NULL, NULL, &bufferSize); if (status == ERROR_INSUFFICIENT_BUFFER) { pInfo = (PTRACE_EVENT_INFO)malloc(bufferSize); if (!pInfo) { OutputDebugString(L"Error allocating memory for event info\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } status = TdhGetEventInformation(EventRecord, 0, NULL, pInfo, &bufferSize); } if (status != ERROR_SUCCESS) { OutputDebugString(L"Error fetching event info\n"); return status; } // Allocate memory for property data vector propertyDataVector = (BYTE**)malloc(vectorCapacity * sizeof(BYTE*)); if (!propertyDataVector) { OutputDebugString(L"Error allocating memory for propertyDataVector\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } // Process each property in the event for (ULONG i = 0; i < pInfo->TopLevelPropertyCount; i++) { PROPERTY_DATA_DESCRIPTOR dataDescriptor; DWORD propertySize = 0; WCHAR* propertyName = (WCHAR*)((BYTE*)pInfo + pInfo->EventPropertyInfoArray[i].NameOffset); dataDescriptor.PropertyName = (ULONGLONG)propertyName; dataDescriptor.ArrayIndex = ULONG_MAX; // Determine the size of the property status = TdhGetPropertySize(EventRecord, 0, NULL, 1, &dataDescriptor, &propertySize); if (status != ERROR_SUCCESS) { wprintf(L"Error getting size for property %ls\n", propertyName); goto Exit; } BYTE* propertyData = (BYTE*)malloc(propertySize); if (!propertyData) { wprintf(L"Error allocating memory for property %ls\n", propertyName); goto Exit; } // Get the actual property data status = TdhGetProperty(EventRecord, 0, NULL, 1, &dataDescriptor, propertySize, propertyData); if (status != ERROR_SUCCESS) { wprintf(L"Error getting data for property %ls\n", propertyName); goto Exit; } // Check if we need to resize the vector if (vectorSize == vectorCapacity) { BYTE** resizedVector = (BYTE**)realloc(propertyDataVector, 2 * vectorCapacity * sizeof(BYTE*)); if (!resizedVector) { OutputDebugString(L"Error resizing propertyDataVector\n"); goto Exit; } propertyDataVector = resizedVector; vectorCapacity *= 2; } // Add the data to the vector propertyDataVector[vectorSize++] = propertyData; } processId = *(UINT32*)propertyDataVector[0]; if (processId == 4) { goto Exit; } size = *(UINT32*)propertyDataVector[1]; destinationAddress = *(UINT32*)propertyDataVector[2]; sourceAddress = *(UINT32*)propertyDataVector[3]; sourcePort = *(UINT16*)propertyDataVector[4]; destinationPort = *(UINT16*)propertyDataVector[5]; destaddr.s_addr = sourceAddress; srceaddr.s_addr = destinationAddress; InetNtop(AF_INET, &srceaddr, wide_sourcestring_ip, INET_ADDRSTRLEN); InetNtop(AF_INET, &destaddr, wide_deststring_ip, INET_ADDRSTRLEN); processInformation = GetProcessName(processId); if (processInformation == nullptr) { OutputDebugString(L"DotNet ETW - Error getting process name\n"); goto Exit; } if (processInformation->integrityLevel == L"Low") { goto Exit; } EventWriteNetworkConnection( &systemTime, processId, processInformation->processName.c_str(), wide_sourcestring_ip, wide_deststring_ip, sourcePort, destinationPort, isInitiated, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId ); break; } default: { break; } } Exit: if (pInfo != nullptr) { free(pInfo); } // Free each element in propertyDataVector and the vector itself if (propertyDataVector != nullptr) { for (int i = 0; i < vectorSize; i++) { if (propertyDataVector[i] != nullptr) { free(propertyDataVector[i]); } } free(propertyDataVector); } return status; } NTSTATUS ProcessEtwEvent( _In_ PEVENT_RECORD EventRecord, _In_ PTRACE_EVENT_INFO PropertyInfo, _In_ BYTE** EventData ) { NTSTATUS status = ERROR_SUCCESS; int vectorSize = 0; // Process each property in the event for (ULONG i = 0; i < PropertyInfo->TopLevelPropertyCount; i++) { PROPERTY_DATA_DESCRIPTOR dataDescriptor; DWORD propertySize = 0; WCHAR* propertyName = (WCHAR*)((BYTE*)PropertyInfo + PropertyInfo->EventPropertyInfoArray[i].NameOffset); dataDescriptor.PropertyName = (ULONGLONG)propertyName; dataDescriptor.ArrayIndex = ULONG_MAX; // Determine the size of the property status = TdhGetPropertySize(EventRecord, 0, NULL, 1, &dataDescriptor, &propertySize); if (status != ERROR_SUCCESS) { OutputDebugString(L"Error getting size for property\n"); goto Exit; } BYTE* propertyData = (BYTE*)malloc(propertySize); if (!propertyData) { OutputDebugString(L" Error allocating memory for propertyData\n"); goto Exit; } // Get the actual property data status = TdhGetProperty(EventRecord, 0, NULL, 1, &dataDescriptor, propertySize, propertyData); if (status != ERROR_SUCCESS) { OutputDebugString(L"Error getting data for property\n"); goto Exit; } // // Add the data to the vector // EventData[vectorSize++] = propertyData; if (vectorSize > PropertyInfo->TopLevelPropertyCount) { OutputDebugString(L"Error: vectorSize exceeded allocated EventData size\n"); status = ERROR_BUFFER_OVERFLOW; goto Exit; } } Exit: if (status != ERROR_SUCCESS) { for (int i = 0; i < vectorSize; i++) { if (EventData[i] != nullptr) { free(EventData[i]); } } free(EventData); } return status; } BOOL WriteAMSIEvents( _In_ PEVENT_RECORD EventRecord, _In_ PEVENT_HEADER EventHeader ) { ULONG64 Session; UINT8 ScanStatus; UINT32 ScanResult, ContentSize, OriginalSize; std::wstring AppName, ContentName, decodedString; BYTE* Content; NTSTATUS status = ERROR_SUCCESS; DWORD bufferSize = 0; PTRACE_EVENT_INFO pInfo = NULL; SYSTEMTIME systemTime; BYTE** propertyDataVector = NULL; PProcessInformation processInformation; GetSystemTime(&systemTime); // // Fetch initial event information size // status = TdhGetEventInformation(EventRecord, 0, NULL, NULL, &bufferSize); if (status == ERROR_INSUFFICIENT_BUFFER) { pInfo = (PTRACE_EVENT_INFO)malloc(bufferSize); if (!pInfo) { OutputDebugString(L"Error allocating memory for event info\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } status = TdhGetEventInformation(EventRecord, 0, NULL, pInfo, &bufferSize); } if (status != ERROR_SUCCESS) { OutputDebugString(L"Error fetching event info\n"); return status; } // // Allocate memory for property data vector // propertyDataVector = (BYTE**)malloc(sizeof(BYTE*) * pInfo->TopLevelPropertyCount); if (!propertyDataVector) { OutputDebugString(L"Error allocating memory for propertyDataVector\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } status = ProcessEtwEvent(EventRecord, pInfo, propertyDataVector); if (status != ERROR_SUCCESS) { OutputDebugString(L"Error processing ETW event\n"); goto Exit; } Session = *(ULONG64*)propertyDataVector[0]; ScanStatus = *(UINT8*)propertyDataVector[1]; ScanResult = *(UINT32*)propertyDataVector[2]; AppName = (WCHAR*)propertyDataVector[3]; if (AppName != L"VBScript" && AppName != L"JScript" && AppName != L"OFFICE_VBA" && AppName != L"Excel" && AppName != L"Excel.exe") { goto Exit; } ContentName = (WCHAR*)propertyDataVector[4]; ContentSize = *(UINT32*)propertyDataVector[5]; OriginalSize = *(UINT32*)propertyDataVector[6]; Content = (BYTE*)propertyDataVector[7]; if (ScanResult != (UINT32)1 && ScanResult != (UINT32)32768) { goto Exit; } processInformation = GetProcessName(EventHeader->ProcessId); if (processInformation == nullptr) { OutputDebugString(L"AMSI - Error getting process name\n"); goto Exit; } decodedString = std::wstring(reinterpret_cast(Content), ContentSize / sizeof(wchar_t)); EventWriteAMSI( &systemTime, processInformation->processName.c_str(), processInformation->processId, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, AppName.c_str(), ContentName.c_str(), ScanStatus, ScanResult, ContentSize, Content, decodedString.c_str() ); Exit: // Free each element in propertyDataVector and the vector itself if (propertyDataVector != nullptr) { for (int i = 0; i < pInfo->TopLevelPropertyCount; i++) { if (propertyDataVector[i] != nullptr) { free(propertyDataVector[i]); } } free(propertyDataVector); } if (pInfo != nullptr) { free(pInfo); } return TRUE; } NTSTATUS WriteDotNetEvents( _In_ PEVENT_RECORD EventRecord, _In_ PEVENT_HEADER EventHeader ) { UINT64 AssemblyID, AppDomainID, BindingID; UINT32 AssemblyFlags; UINT16 ClrInstanceID; std::wstring FQAN; NTSTATUS status = ERROR_SUCCESS; DWORD bufferSize = 0; PTRACE_EVENT_INFO pInfo = NULL; SYSTEMTIME systemTime; BYTE** propertyDataVector = NULL; PProcessInformation processInformation; GetSystemTime(&systemTime); // // Fetch initial event information size // status = TdhGetEventInformation(EventRecord, 0, NULL, NULL, &bufferSize); if (status == ERROR_INSUFFICIENT_BUFFER) { pInfo = (PTRACE_EVENT_INFO)malloc(bufferSize); if (!pInfo) { OutputDebugString(L"Error allocating memory for event info\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } status = TdhGetEventInformation(EventRecord, 0, NULL, pInfo, &bufferSize); } if (status != ERROR_SUCCESS) { OutputDebugString(L"Error fetching event info\n"); return status; } // // Allocate memory for property data vector // propertyDataVector = (BYTE**)malloc(sizeof(BYTE*) * pInfo->TopLevelPropertyCount); if (!propertyDataVector) { OutputDebugString(L"Error allocating memory for propertyDataVector\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } status = ProcessEtwEvent(EventRecord, pInfo, propertyDataVector); if (status != ERROR_SUCCESS) { OutputDebugString(L"Error processing ETW event\n"); goto Exit; } AssemblyID = *(UINT64*)propertyDataVector[0]; AppDomainID = *(UINT64*)propertyDataVector[1]; BindingID = *(UINT64*)propertyDataVector[2]; AssemblyFlags = *(UINT32*)propertyDataVector[3]; FQAN = (WCHAR*)propertyDataVector[4]; ClrInstanceID = *(UINT16*)propertyDataVector[5]; processInformation = GetProcessName(EventHeader->ProcessId); if (processInformation == nullptr) { OutputDebugString(L"DotNet ETW - Error getting process name\n"); goto Exit; } EventWriteDotNetLoad( &systemTime, processInformation->processName.c_str(), processInformation->processId, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, FQAN.c_str(), ClrInstanceID ); Exit: // Free each element in propertyDataVector and the vector itself if (propertyDataVector != nullptr) { for (int i = 0; i < pInfo->TopLevelPropertyCount; i++) { if (propertyDataVector[i] != nullptr) { free(propertyDataVector[i]); } } free(propertyDataVector); } if (pInfo != nullptr) { free(pInfo); } return status; } NTSTATUS WriteWMIEvents( _In_ PEVENT_RECORD EventRecord, _In_ PEVENT_HEADER EventHeader ) { std::wstring Namespace, ESS, Consumer, PossibleCause; NTSTATUS status = ERROR_SUCCESS; DWORD bufferSize = 0; PTRACE_EVENT_INFO pInfo = NULL; SYSTEMTIME systemTime; BYTE** propertyDataVector = NULL; PProcessInformation processInformation; GetSystemTime(&systemTime); // // Fetch initial event information size // status = TdhGetEventInformation(EventRecord, 0, NULL, NULL, &bufferSize); if (status == ERROR_INSUFFICIENT_BUFFER) { pInfo = (PTRACE_EVENT_INFO)malloc(bufferSize); if (!pInfo) { OutputDebugString(L"Error allocating memory for event info\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } status = TdhGetEventInformation(EventRecord, 0, NULL, pInfo, &bufferSize); } if (status != ERROR_SUCCESS) { OutputDebugString(L"Error fetching event info\n"); return status; } // // Allocate memory for property data vector // propertyDataVector = (BYTE**)malloc(sizeof(BYTE*) * pInfo->TopLevelPropertyCount); if (!propertyDataVector) { OutputDebugString(L"Error allocating memory for propertyDataVector\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } status = ProcessEtwEvent(EventRecord, pInfo, propertyDataVector); if (status != ERROR_SUCCESS) { OutputDebugString(L"Error processing ETW event\n"); goto Exit; } processInformation = GetProcessName(EventHeader->ProcessId); if (processInformation == nullptr) { OutputDebugString(L"DotNet ETW - Error getting process name\n"); goto Exit; } Namespace = (WCHAR*)propertyDataVector[0]; ESS = (WCHAR*)propertyDataVector[1]; Consumer = (WCHAR*)propertyDataVector[2]; PossibleCause = (WCHAR*)propertyDataVector[3]; EventWriteWMIEventFilter( &systemTime, processInformation->processName.c_str(), processInformation->processId, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, Namespace.c_str(), ESS.c_str(), Consumer.c_str(), PossibleCause.c_str() ); Exit: // Free each element in propertyDataVector and the vector itself if (propertyDataVector != nullptr) { for (int i = 0; i < pInfo->TopLevelPropertyCount; i++) { if (propertyDataVector[i] != nullptr) { free(propertyDataVector[i]); } } free(propertyDataVector); } if (pInfo != nullptr) { free(pInfo); } return status; } wchar_t* GetCallStack( _In_ PEVENT_RECORD EventRecord, _In_ PEVENT_HEADER_EXTENDED_DATA_ITEM extendedData, _In_ HANDLE hProcess ) { const int MAX_SYM_NAME_LEN = 1024; std::wstring wtext; BOOL symInitialized = FALSE; const char* szSymSearchPath = "srv*http://msdl.microsoft.com/download/symbols"; SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS | SYMOPT_INCLUDE_32BIT_MODULES | SYMOPT_CASE_INSENSITIVE | SYMOPT_ALLOW_ZERO_ADDRESS | SYMOPT_ALLOW_ABSOLUTE_SYMBOLS); symInitialized = SymInitialize(hProcess, szSymSearchPath, TRUE); if (!symInitialized) { printf("[!] SymInitialize failed: %d\n", GetLastError()); return nullptr; } if (EventRecord->ExtendedDataCount == 0) { SymCleanup(hProcess); return nullptr; } for (USHORT i = 0; i < EventRecord->ExtendedDataCount; i++) { if (extendedData[i].ExtType == EVENT_HEADER_EXT_TYPE_STACK_TRACE64) { auto stacktrace = reinterpret_cast(extendedData[i].DataPtr); int stack_length = extendedData[i].DataSize / sizeof(ULONG64); for (int j = 0; j < stack_length; j++) { DWORD64 dwDisplacement = 0; DWORD64 dwAddress = stacktrace->Address[j]; char buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME_LEN * sizeof(TCHAR)]; PSYMBOL_INFOW pSymbol = (PSYMBOL_INFOW)buffer; pSymbol->SizeOfStruct = sizeof(SYMBOL_INFOW); pSymbol->MaxNameLen = MAX_SYM_NAME_LEN; if (SymFromAddrW(hProcess, dwAddress, &dwDisplacement, pSymbol)) { wtext += pSymbol->Name; } else { wtext += L""; } wtext += L" "; } } } SymCleanup(hProcess); if (!wtext.empty()) { wtext.pop_back(); // Remove trailing space size_t wtext_len = wtext.length() + 1; wchar_t* result = new wchar_t[wtext_len]; wcscpy_s(result, wtext_len, wtext.c_str()); return result; } return nullptr; } NTSTATUS WriteRpcEvents( _In_ PEVENT_RECORD EventRecord, _In_ PEVENT_HEADER EventHeader, _In_ INT32 EventType ) { PEVENT_HEADER_EXTENDED_DATA_ITEM extendedData = EventRecord->ExtendedData; wchar_t szInterfaceUUID[64] = { 0 }; GUID interfaceUUID; UINT32 procNum, protocol, authenticationLevel, authenticationService, impersonationLevel; std::wstring networkAddress, endpoint, options, methodString, interfaceString; HANDLE hProcess = GetCurrentProcess(); wchar_t* CallStack; int result; NTSTATUS status = ERROR_SUCCESS; DWORD bufferSize = 0; PTRACE_EVENT_INFO pInfo = NULL; SYSTEMTIME systemTime; BYTE** propertyDataVector = NULL; PProcessInformation processInformation; GetSystemTime(&systemTime); // // Fetch initial event information size // status = TdhGetEventInformation(EventRecord, 0, NULL, NULL, &bufferSize); if (status == ERROR_INSUFFICIENT_BUFFER) { pInfo = (PTRACE_EVENT_INFO)malloc(bufferSize); if (!pInfo) { OutputDebugString(L"Error allocating memory for event info\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } status = TdhGetEventInformation(EventRecord, 0, NULL, pInfo, &bufferSize); } if (status != ERROR_SUCCESS) { OutputDebugString(L"Error fetching event info\n"); return status; } // // Allocate memory for property data vector // propertyDataVector = (BYTE**)malloc(sizeof(BYTE*) * pInfo->TopLevelPropertyCount); if (!propertyDataVector) { OutputDebugString(L"Error allocating memory for propertyDataVector\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } status = ProcessEtwEvent(EventRecord, pInfo, propertyDataVector); if (status != ERROR_SUCCESS) { OutputDebugString(L"Error processing ETW event\n"); goto Exit; } interfaceUUID = *(GUID*)propertyDataVector[0]; procNum = *(UINT32*)propertyDataVector[1]; protocol = *(UINT32*)propertyDataVector[2]; networkAddress = (WCHAR*)propertyDataVector[3]; endpoint = (WCHAR*)propertyDataVector[4]; options = (WCHAR*)propertyDataVector[5]; authenticationLevel = *(UINT32*)propertyDataVector[6]; authenticationService = *(UINT32*)propertyDataVector[7]; impersonationLevel = *(UINT32*)propertyDataVector[8]; // // convert GUID to string // result = StringFromGUID2(interfaceUUID, szInterfaceUUID, 64); if (result == 0) { OutputDebugString(L"Error converting GUID to string\n"); goto Exit; } //MS-SCMR {367ABB81-9844-35F1-AD32-98F038001003} if (wcscmp(szInterfaceUUID, L"{367ABB81-9844-35F1-AD32-98F038001003}") == 0) { interfaceString = L"MS-SCMR"; switch (procNum) { case 12: { methodString = L"RCreateServiceW"; processInformation = GetProcessName(EventHeader->ProcessId); if (processInformation == nullptr) { OutputDebugString(L"RPC ETW - Error getting process name\n"); goto Exit; } CallStack = GetCallStack(EventRecord, extendedData, hProcess); switch (EventType) { case 0: { EventWriteRPCClient( &systemTime, processInformation->processName.c_str(), processInformation->processId, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, szInterfaceUUID, procNum, protocol, networkAddress.c_str(), endpoint.c_str(), interfaceString.c_str(), methodString.c_str(), CallStack ); break; } case 1: { EventWriteRPCServer( &systemTime, processInformation->processName.c_str(), processInformation->processId, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, szInterfaceUUID, procNum, protocol, networkAddress.c_str(), endpoint.c_str(), interfaceString.c_str(), methodString.c_str(), CallStack ); break; } } if (CallStack != nullptr) { delete[] CallStack; } goto Exit; } default: { goto Exit; } } goto Exit; } //MS-DRSR {E3514235-4B06-11D1-AB04-00C04FC2DCD2} if (wcscmp(szInterfaceUUID, L"{E3514235-4B06-11D1-AB04-00C04FC2DCD2}") == 0) { interfaceString = L"MS-DRSR"; switch (procNum) { case 3: { methodString = L"GetNCChanges"; processInformation = GetProcessName(EventHeader->ProcessId); if (processInformation == nullptr) { OutputDebugString(L"RPC ETW - Error getting process name\n"); goto Exit; } CallStack = GetCallStack(EventRecord, extendedData, hProcess); switch (EventType) { case 0: { EventWriteRPCClient( &systemTime, processInformation->processName.c_str(), processInformation->processId, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, szInterfaceUUID, procNum, protocol, networkAddress.c_str(), endpoint.c_str(), interfaceString.c_str(), methodString.c_str(), CallStack ); break; } case 1: { EventWriteRPCServer( &systemTime, processInformation->processName.c_str(), processInformation->processId, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, szInterfaceUUID, procNum, protocol, networkAddress.c_str(), endpoint.c_str(), interfaceString.c_str(), methodString.c_str(), CallStack ); break; } } if (CallStack != nullptr) { delete[] CallStack; } goto Exit; } default: { goto Exit; } } goto Exit; } //MS-RRP {338CD001-2244-31F1-AAAA-900038001003} if (wcscmp(szInterfaceUUID, L"{338CD001-2244-31F1-AAAA-900038001003}") == 0) { interfaceString = L"MS-RRP"; switch (procNum) { case 6: { methodString = L"BaseRegCreateKey"; processInformation = GetProcessName(EventHeader->ProcessId); if (processInformation == nullptr) { OutputDebugString(L"RPC ETW - Error getting process name\n"); goto Exit; } CallStack = GetCallStack(EventRecord, extendedData, hProcess); switch (EventType) { case 0: { EventWriteRPCClient( &systemTime, processInformation->processName.c_str(), processInformation->processId, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, szInterfaceUUID, procNum, protocol, networkAddress.c_str(), endpoint.c_str(), interfaceString.c_str(), methodString.c_str(), CallStack ); break; } case 1: { EventWriteRPCServer( &systemTime, processInformation->processName.c_str(), processInformation->processId, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, szInterfaceUUID, procNum, protocol, networkAddress.c_str(), endpoint.c_str(), interfaceString.c_str(), methodString.c_str(), CallStack ); break; } } if (CallStack != nullptr) { delete[] CallStack; } goto Exit; } case 22: { methodString = L"BaseRegSetValue"; processInformation = GetProcessName(EventHeader->ProcessId); if (processInformation == nullptr) { OutputDebugString(L"RPC ETW - Error getting process name\n"); goto Exit; } CallStack = GetCallStack(EventRecord, extendedData, hProcess); switch (EventType) { case 0: { EventWriteRPCClient( &systemTime, processInformation->processName.c_str(), processInformation->processId, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, szInterfaceUUID, procNum, protocol, networkAddress.c_str(), endpoint.c_str(), interfaceString.c_str(), methodString.c_str(), CallStack ); break; } case 1: { EventWriteRPCServer( &systemTime, processInformation->processName.c_str(), processInformation->processId, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, szInterfaceUUID, procNum, protocol, networkAddress.c_str(), endpoint.c_str(), interfaceString.c_str(), methodString.c_str(), CallStack ); break; } } if (CallStack != nullptr) { delete[] CallStack; } goto Exit; } default: { goto Exit; } } goto Exit; } //MS-SRVS {4B324FC8-1670-01D3-1278-5A47BF6EE188} if (wcscmp(szInterfaceUUID, L"{4B324FC8-1670-01D3-1278-5A47BF6EE188}") == 0) { interfaceString = L"MS-SRVS"; switch (procNum) { case 12: { methodString = L"NetrSessionEnum"; processInformation = GetProcessName(EventHeader->ProcessId); if (processInformation == nullptr) { OutputDebugString(L"RPC ETW - Error getting process name\n"); goto Exit; } CallStack = GetCallStack(EventRecord, extendedData, hProcess); switch (EventType) { case 0: { EventWriteRPCClient( &systemTime, processInformation->processName.c_str(), processInformation->processId, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, szInterfaceUUID, procNum, protocol, networkAddress.c_str(), endpoint.c_str(), interfaceString.c_str(), methodString.c_str(), CallStack ); break; } case 1: { EventWriteRPCServer( &systemTime, processInformation->processName.c_str(), processInformation->processId, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, szInterfaceUUID, procNum, protocol, networkAddress.c_str(), endpoint.c_str(), interfaceString.c_str(), methodString.c_str(), CallStack ); break; } } if (CallStack != nullptr) { delete[] CallStack; } goto Exit; } default: { goto Exit; } } goto Exit; } //MS-RPRN {12345678-1234-ABCD-EF00-0123456789AB} if (wcscmp(szInterfaceUUID, L"{12345678-1234-ABCD-EF00-0123456789AB}") == 0) { interfaceString = L"MS-RPRN"; switch (procNum) { case 89: { methodString = L"RpcAddPrinterDriverEx"; processInformation = GetProcessName(EventHeader->ProcessId); if (processInformation == nullptr) { OutputDebugString(L"RPC ETW - Error getting process name\n"); goto Exit; } CallStack = GetCallStack(EventRecord, extendedData, hProcess); switch (EventType) { case 0: { EventWriteRPCClient( &systemTime, processInformation->processName.c_str(), processInformation->processId, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, szInterfaceUUID, procNum, protocol, networkAddress.c_str(), endpoint.c_str(), interfaceString.c_str(), methodString.c_str(), CallStack ); break; } case 1: { EventWriteRPCServer( &systemTime, processInformation->processName.c_str(), processInformation->processId, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, szInterfaceUUID, procNum, protocol, networkAddress.c_str(), endpoint.c_str(), interfaceString.c_str(), methodString.c_str(), CallStack ); break; } } if (CallStack != nullptr) { delete[] CallStack; } goto Exit; } default: { goto Exit; } } goto Exit; } //MS-PAR 76F03F96-CDFD-44FC-A22C-64950A001209 if (wcscmp(szInterfaceUUID, L"{76F03F96-CDFD-44FC-A22C-64950A001209}") == 0) { interfaceString = L"MS-PAR"; switch (procNum) { case 39: { methodString = L"RpcAsyncAddPrinterDriver"; processInformation = GetProcessName(EventHeader->ProcessId); if (processInformation == nullptr) { OutputDebugString(L"RPC ETW - Error getting process name\n"); goto Exit; } CallStack = GetCallStack(EventRecord, extendedData, hProcess); switch (EventType) { case 0: { EventWriteRPCClient( &systemTime, processInformation->processName.c_str(), processInformation->processId, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, szInterfaceUUID, procNum, protocol, networkAddress.c_str(), endpoint.c_str(), interfaceString.c_str(), methodString.c_str(), CallStack ); break; } case 1: { EventWriteRPCServer( &systemTime, processInformation->processName.c_str(), processInformation->processId, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, szInterfaceUUID, procNum, protocol, networkAddress.c_str(), endpoint.c_str(), interfaceString.c_str(), methodString.c_str(), CallStack ); break; } } if (CallStack != nullptr) { delete[] CallStack; } goto Exit; } default: { goto Exit; } } goto Exit; } // MS-EFSR {D9A0A0C0-150F-11D1-8C7A-00C04FC297EB} || {C681D488-D850-11D0-8C52-00C04FD90F7E}" if ((wcscmp(szInterfaceUUID, L"{C681D488-D850-11D0-8C52-00C04FD90F7E}") == 0) || (wcscmp(szInterfaceUUID, L"{DF1941C5-FE89-4E79-BF10-463657ACF44D}") == 0)) { interfaceString = L"MS-EFSR"; switch (procNum) { case 0: { methodString = L"EfsRpcOpenFileRaw"; processInformation = GetProcessName(EventHeader->ProcessId); if (processInformation == nullptr) { OutputDebugString(L"RPC ETW - Error getting process name\n"); goto Exit; } CallStack = GetCallStack(EventRecord, extendedData, hProcess); switch (EventType) { case 0: { EventWriteRPCClient( &systemTime, processInformation->processName.c_str(), processInformation->processId, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, szInterfaceUUID, procNum, protocol, networkAddress.c_str(), endpoint.c_str(), interfaceString.c_str(), methodString.c_str(), CallStack ); break; } case 1: { EventWriteRPCServer( &systemTime, processInformation->processName.c_str(), processInformation->processId, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, szInterfaceUUID, procNum, protocol, networkAddress.c_str(), endpoint.c_str(), interfaceString.c_str(), methodString.c_str(), CallStack ); break; } } if (CallStack != nullptr) { delete[] CallStack; } goto Exit; } case 4: { methodString = L"EfsRpcEncryptFileSrv"; processInformation = GetProcessName(EventHeader->ProcessId); if (processInformation == nullptr) { OutputDebugString(L"RPC ETW - Error getting process name\n"); goto Exit; } CallStack = GetCallStack(EventRecord, extendedData, hProcess); switch (EventType) { case 0: { EventWriteRPCClient( &systemTime, processInformation->processName.c_str(), processInformation->processId, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, szInterfaceUUID, procNum, protocol, networkAddress.c_str(), endpoint.c_str(), interfaceString.c_str(), methodString.c_str(), CallStack ); break; } case 1: { EventWriteRPCServer( &systemTime, processInformation->processName.c_str(), processInformation->processId, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, szInterfaceUUID, procNum, protocol, networkAddress.c_str(), endpoint.c_str(), interfaceString.c_str(), methodString.c_str(), CallStack ); break; } } if (CallStack != nullptr) { delete[] CallStack; } goto Exit; } case 5: { methodString = L"EfsRpcDecryptFileSrv"; processInformation = GetProcessName(EventHeader->ProcessId); if (processInformation == nullptr) { OutputDebugString(L"RPC ETW - Error getting process name\n"); goto Exit; } CallStack = GetCallStack(EventRecord, extendedData, hProcess); switch (EventType) { case 0: { EventWriteRPCClient( &systemTime, processInformation->processName.c_str(), processInformation->processId, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, szInterfaceUUID, procNum, protocol, networkAddress.c_str(), endpoint.c_str(), interfaceString.c_str(), methodString.c_str(), CallStack ); break; } case 1: { EventWriteRPCServer( &systemTime, processInformation->processName.c_str(), processInformation->processId, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, szInterfaceUUID, procNum, protocol, networkAddress.c_str(), endpoint.c_str(), interfaceString.c_str(), methodString.c_str(), CallStack ); break; } } if (CallStack != nullptr) { delete[] CallStack; } goto Exit; } default: { goto Exit; } } goto Exit; } Exit: // Free each element in propertyDataVector and the vector itself if (propertyDataVector != nullptr) { for (int i = 0; i < pInfo->TopLevelPropertyCount; i++) { if (propertyDataVector[i] != nullptr) { free(propertyDataVector[i]); } } free(propertyDataVector); } if (pInfo != nullptr) { free(pInfo); } return status; } NTSTATUS WriteDpapiEvents( _In_ PEVENT_RECORD EventRecord, _In_ PEVENT_HEADER EventHeader ) { UINT32 Flags, ProtectionFlags, ReturnValue, CallerProcessID, PlainTextDataSize; std::wstring OperationType, DataDescription; GUID MasterKeyGUID; UINT64 CallerProcessStartKey, CallerProcessCreationTime; NTSTATUS status = ERROR_SUCCESS; DWORD bufferSize = 0; PTRACE_EVENT_INFO pInfo = NULL; SYSTEMTIME systemTime; BYTE** propertyDataVector = NULL; PProcessInformation processInformation; GetSystemTime(&systemTime); // // Fetch initial event information size // status = TdhGetEventInformation(EventRecord, 0, NULL, NULL, &bufferSize); if (status == ERROR_INSUFFICIENT_BUFFER) { pInfo = (PTRACE_EVENT_INFO)malloc(bufferSize); if (!pInfo) { OutputDebugString(L"Error allocating memory for event info\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } status = TdhGetEventInformation(EventRecord, 0, NULL, pInfo, &bufferSize); } if (status != ERROR_SUCCESS) { OutputDebugString(L"Error fetching event info\n"); return status; } // // Allocate memory for property data vector // propertyDataVector = (BYTE**)malloc(sizeof(BYTE*) * pInfo->TopLevelPropertyCount); if (!propertyDataVector) { OutputDebugString(L"Error allocating memory for propertyDataVector\n"); status = ERROR_NOT_ENOUGH_MEMORY; goto Exit; } status = ProcessEtwEvent(EventRecord, pInfo, propertyDataVector); if (status != ERROR_SUCCESS) { OutputDebugString(L"Error processing ETW event\n"); goto Exit; } OperationType = (WCHAR*)propertyDataVector[0]; DataDescription = (WCHAR*)propertyDataVector[1]; MasterKeyGUID = *(GUID*)propertyDataVector[2]; Flags = *(UINT32*)propertyDataVector[3]; ProtectionFlags = *(UINT32*)propertyDataVector[4]; ReturnValue = *(UINT32*)propertyDataVector[5]; CallerProcessStartKey = *(UINT64*)propertyDataVector[6]; CallerProcessID = *(UINT32*)propertyDataVector[7]; CallerProcessCreationTime = *(UINT64*)propertyDataVector[8]; PlainTextDataSize = *(UINT32*)propertyDataVector[9]; // //Seeing if OperationType == SPCryptUnprotect // if (OperationType == L"SPCryptUnprotect") { processInformation = GetProcessName(CallerProcessID); if (processInformation == nullptr) { OutputDebugString(L"DotNet ETW - Error getting process name\n"); goto Exit; } EventWriteDPAPIUnprotect( &systemTime, processInformation->processName.c_str(), CallerProcessID, processInformation->userName.c_str(), processInformation->authenticationId.LowPart, processInformation->integrityLevel.c_str(), processInformation->sessionId, OperationType.c_str(), DataDescription.c_str(), Flags, ProtectionFlags ); } Exit: // Free each element in propertyDataVector and the vector itself if (propertyDataVector != nullptr) { for (int i = 0; i < pInfo->TopLevelPropertyCount; i++) { if (propertyDataVector[i] != nullptr) { free(propertyDataVector[i]); } } free(propertyDataVector); } if (pInfo != nullptr) { free(pInfo); } return status; } ================================================ FILE: JonMon-Service/etwMain.h ================================================ #pragma once #include #include #include #include #include "../JonMonProvider/jonmon.h" #include "config.h" static GUID JonMonGuid = { 0xd8909c24, 0x5be9, 0x4502, { 0x98, 0xca, 0xab, 0x7b, 0xdc, 0x24, 0x89, 0x9d } }; static GUID JonMonDebugGuid = { 0xc5d8e634, 0x9614, 0x45ac, { 0x93, 0x0c, 0xda, 0x88, 0xcd, 0x77, 0xbb, 0x39 } }; struct ProcessData { ULONG ProcessId; ULONG ValueOption; }; NTSTATUS ProcessEtwEvent( _In_ PEVENT_RECORD EventRecord, _In_ PTRACE_EVENT_INFO PropertyInfo, _In_ BYTE** EventData ); void NTAPI ProcessEvent( _In_ PEVENT_RECORD EventRecord ); DWORD StopETWTrace(); DWORD TraceEvent( _In_ LPCWSTR Name, _In_ GUID TraceGuid, _In_ EventSchema_Full* EventSchemaStruct ); NTSTATUS WriteJonMonTraceLoggingEvents( _In_ PEVENT_RECORD EventRecord, _In_ PEVENT_HEADER EventHeader ); NTSTATUS WriteDotNetEvents( _In_ PEVENT_RECORD EventRecord, _In_ PEVENT_HEADER EventHeader ); BOOL WriteAMSIEvents( _In_ PEVENT_RECORD EventRecord, _In_ PEVENT_HEADER EventHeader ); NTSTATUS WriteWMIEvents( _In_ PEVENT_RECORD EventRecord, _In_ PEVENT_HEADER EventHeader ); BOOL WriteNetworkEvents( _In_ PEVENT_RECORD EventRecord, _In_ PEVENT_HEADER EventHeader ); NTSTATUS WriteThreatIntelEvents( _In_ PEVENT_RECORD EventRecord, _In_ PEVENT_HEADER EventHeader ); #pragma warning(disable: 4996) wchar_t* GetCallStack( _In_ PEVENT_RECORD EventRecord, _In_ PEVENT_HEADER_EXTENDED_DATA_ITEM extendedData, _In_ HANDLE hProcess ); NTSTATUS WriteRpcEvents( _In_ PEVENT_RECORD EventRecord, _In_ PEVENT_HEADER EventHeader, _In_ INT32 EventType ); NTSTATUS WriteDpapiEvents( _In_ PEVENT_RECORD EventRecord, _In_ PEVENT_HEADER EventHeader ); // // Event ID 100 // typedef struct _TraceLoggingProviderRegistered { INT32 EventId; BOOL IsRegistered; } TraceLoggingProviderRegistered, * PTraceLoggingProviderRegistered; // // Event ID 101 // typedef struct _EventSchemaConfiguration { INT32 EventId; BOOL ProcessCreation; BOOL ProcessTermination; BOOL RegistryEvents; BOOL ProcessHandleCreation; BOOL ProcessHandleDuplication; BOOL RemoteThreadCreation; BOOL ImageLoad; BOOL ThreadImpersonationEvents_KM; BOOL FileEvents; } EventSchemaConfiguration, * PEventSchemaConfiguration; // // Event ID 102 // typedef struct _DebugLog { INT32 EventId; BOOL ProcessProtection; } DebugLog, * PDebugLog; // //Event ID 1 - Process Creation // typedef struct _ProcessCreationEvent { INT32 EventId; INT64 ProcessId; UINT64 ProcessStartKey; INT64 ParentProcessId; UINT64 ParentProcessStartKey; INT64 CreatorProcessId; INT64 CreatorThreadId; WCHAR* CommandLine; FILETIME EventTime; } ProcessCreationEvent, * PProcessCreationEvent; // // Event ID 2 - Process Termination // typedef struct _ProcessTerminationEvent { INT32 EventId; INT64 ProcessId; UINT64 ProcessStartKey; INT64 ParentProcessId; UINT64 ParentProcessStartKey; FILETIME EventTime; } ProcessTerminationEvent, * PProcessTerminationEvent; // // Event ID 3 - Remote Thread Creation // typedef struct _RemoteThreadCreationEvent { INT32 EventId; INT64 SourceThreadId; INT64 SourceProcessId; UINT64 SourceProcessStartKey; INT64 NewThreadId; INT64 TargetProcessId; UINT64 TargetProcessStartKey; FILETIME EventTime; } RemoteThreadCreationEvent, * PRemoteThreadCreationEvent; // // Event ID 4 - Load Image // typedef struct _LoadImageEvent { INT32 EventId; INT64 ProcessId; UINT64 ProcessStartKey; INT64 ThreadId; ULONG SystemModeImage; WCHAR* ImageName; FILETIME EventTime; } LoadImageEvent, * PLoadImageEvent; // // Event ID 5 - ProcessHandle (OpenProcess/DuplicateHandle) // typedef struct _ProcessHandleEvent { INT32 EventId; INT64 SourceThreadId; INT64 SourceProcessId; UINT64 SourceProcessStartKey; INT64 TargetProcessId; UINT64 TargetProcessStartKey; INT32 OperationType; INT32 DesiredAccess; FILETIME EventTime; } ProcessHandleEvent, * PProcessHandleEvent; // // Event ID 6 - RegistrySaveKey // typedef struct _RegistrySaveKeyEvent { INT32 EventId; INT64 SourceThreadId; INT64 SourceProcessId; UINT64 SourceProcessStartKey; WCHAR* KeyPath; FILETIME EventTime; } RegistrySaveKeyEvent, * PRegistrySaveKeyEvent; // // Event ID 7 - RegistryDeleteKey // typedef struct _RegistryDeleteKeyEvent { INT32 EventId; INT64 SourceThreadId; INT64 SourceProcessId; UINT64 SourceProcessStartKey; WCHAR* KeyPath; FILETIME EventTime; } RegistryDeleteKeyEvent, * PRegistryDeleteKeyEvent; // // Event ID 8 - RegistrySetValue // typedef struct _RegistrySetValueKeyEvent { INT32 EventId; INT64 SourceThreadId; INT64 SourceProcessId; UINT64 SourceProcessStartKey; WCHAR* KeyPath; WCHAR* ValueName; WCHAR* Data; ULONG Type; ULONG DataSize; FILETIME EventTime; } RegistrySetValueKeyEvent, * PRegistrySetValueKeyEvent; // // Event ID 9 - RegistryCreateKey // typedef struct _RegistryCreateKeyEvent { INT32 EventId; INT64 SourceThreadId; INT64 SourceProcessId; UINT64 SourceProcessStartKey; WCHAR* KeyPath; INT32 DesiredAccess; FILETIME EventTime; } RegistryCreateKeyEvent, * PRegistryCreateKeyEvent; // // Event ID 10 - File Creation // typedef struct _FileCreationEvent { INT32 EventId; INT64 SourceThreadId; INT64 SourceProcessId; UINT64 SourceProcessStartKey; WCHAR* FileName; FILETIME EventTime; } FileCreationEvent, * PFileCreationEvent; // // Event ID 11 - NamedPipeCreation // typedef struct _NamedPipeCreateEvent { INT32 EventId; INT64 SourceThreadId; INT64 SourceProcessId; UINT64 SourceProcessStartKey; WCHAR* FileName; ULONG RequestedRights; ULONG GrantedRights; FILETIME EventTime; } NamedPipeCreateEvent, * PNamedPipeCreateEvent; // // Event ID 12 - NamedPipeConnection // typedef struct _NamedPipeConnectionEvent { INT32 EventId; INT64 SourceThreadId; INT64 SourceProcessId; UINT64 SourceProcessStartKey; WCHAR* FileName; ULONG RequestedRights; FILETIME EventTime; } NamedPipeConnectionEvent, * PNamedPipeConnectionEvent; // // Event ID 13 - MailslotCreation // typedef struct _MailslotCreateEvent { INT32 EventId; INT64 SourceThreadId; INT64 SourceProcessId; UINT64 SourceProcessStartKey; WCHAR* FileName; ULONG RequestedRights; FILETIME EventTime; } MailslotCreateEvent, * PMailslotCreateEvent; // // Event ID 14 - MailslotConnection // typedef struct _MailslotConnectionEvent { INT32 EventId; INT64 SourceThreadId; INT64 SourceProcessId; UINT64 SourceProcessStartKey; WCHAR* FileName; ULONG RequestedRights; FILETIME EventTime; } MailslotConnectionEvent, * PMailslotConnectionEvent; // // Event ID 15 - RemoteFileConnection (Named Pipes/Mailslots) // typedef struct _RemoteFileConnectionEvent { INT32 EventId; INT64 SourceThreadId; INT64 SourceProcessId; UINT64 SourceProcessStartKey; WCHAR* FileName; FILETIME EventTime; } RemoteFileConnectionEvent, * PRemoteFileConnectionEvent; // // Event ID 16 - ThreadImpersonation // typedef struct _ThreadImpersonationEvent { INT32 EventId; UINT32 ThreadId; UINT32 ProcessId; UINT32 threadIntegrityLevel; SYSTEMTIME EventTime; WCHAR* ImpersonatedUser; } ThreadImpersonationEvent, * PThreadImpersonationEvent; ================================================ FILE: JonMon-Service/global.h ================================================ #pragma once #include // //ETW GUIDS // static GUID RPC_Provider = { 0x6ad52b32, 0xd609, 0x4be9, { 0xae, 0x07, 0xce, 0x8d, 0xae, 0x93, 0x7e, 0x39 } }; static GUID Network_Provider = { 0x7DD42A49,0x5329,0x4832,{0x8D, 0xFD, 0x43, 0xD9, 0x79, 0x15, 0x3A, 0x88} }; static GUID DotNet_Provider = { 0xe13c0d23, 0xccbc, 0x4e12, { 0x93, 0x1b, 0xd9, 0xcc, 0x2e, 0xee, 0x27, 0xe4 } }; static GUID AMSI_Provider = { 0x2a576b87, 0x09a7, 0x520e, { 0xc2, 0x1a, 0x49, 0x42, 0xf0, 0x27, 0x1d, 0x67 } }; static GUID WMIActivty_Provider = { 0x1418ef04, 0xb0b4, 0x4623, { 0xbf, 0x7e, 0xd7, 0x4a, 0xb4, 0x7b, 0xbd, 0xaa } }; static GUID ThreatIntel_Provider = { 0xf4e1897c, 0xbb5d, 0x5668, { 0xf1, 0xd8, 0x04, 0x0f, 0x4d, 0x8d, 0xd3, 0x44 } }; static GUID DPAPI_Provider = { 0x89fe8f40, 0xcdce, 0x464e, { 0x82, 0x17, 0x15, 0xef, 0x97, 0xd4, 0xc7, 0xc3 } }; static GUID JonMonTraceLogging = { 0xdd82bf6f, 0x5295, 0x4541, { 0x96, 0x8d, 0x8c, 0xac, 0x58, 0xe5, 0x72, 0xe4 } }; // // EVENT DESCRIPTORS // const EVENT_DESCRIPTOR AMSIEvents = { 0x10, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000 }; const EVENT_DESCRIPTOR DPAPIEvent = { 0x1c, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000 }; ================================================ FILE: JonMon-Service/service.cpp ================================================ #include #include #include "service.h" #include "config.h" #include "etwMain.h" SERVICE_STATUS_HANDLE g_hServiceStatus = NULL; SERVICE_STATUS g_ServiceStatus = { 0 }; // // JonMon TraceLogging Provider Information // TRACELOGGING_DECLARE_PROVIDER(g_hJonMon); TRACELOGGING_DEFINE_PROVIDER(g_hJonMon, "JonMon", (0xdd82bf6f, 0x5295, 0x4541, 0x96, 0x8d, 0x8c, 0xac, 0x58, 0xe5, 0x72, 0xe4)); VOID WINAPI ServiceCtrlHandler( _In_ DWORD dwCtrl ) { switch (dwCtrl) { case SERVICE_CONTROL_STOP: // Update the service status g_ServiceStatus.dwControlsAccepted = 0; g_ServiceStatus.dwCurrentState = SERVICE_STOP_PENDING; g_ServiceStatus.dwWin32ExitCode = 0; g_ServiceStatus.dwCheckPoint = 0; g_ServiceStatus.dwWaitHint = 0; SetServiceStatus(g_hServiceStatus, &g_ServiceStatus); // Perform service-specific cleanup here // Update the service status g_ServiceStatus.dwCurrentState = SERVICE_STOPPED; g_ServiceStatus.dwWin32ExitCode = 0; g_ServiceStatus.dwCheckPoint = 0; g_ServiceStatus.dwWaitHint = 0; SetServiceStatus(g_hServiceStatus, &g_ServiceStatus); EventUnregisterJonMon(); break; case SERVICE_CONTROL_PAUSE: // Update the service status g_ServiceStatus.dwCurrentState = SERVICE_PAUSE_PENDING; g_ServiceStatus.dwWin32ExitCode = 0; g_ServiceStatus.dwCheckPoint = 0; g_ServiceStatus.dwWaitHint = 0; SetServiceStatus(g_hServiceStatus, &g_ServiceStatus); // Perform service-specific pause here // Update the service status g_ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP; g_ServiceStatus.dwCurrentState = SERVICE_PAUSED; g_ServiceStatus.dwWin32ExitCode = 0; g_ServiceStatus.dwCheckPoint = 0; g_ServiceStatus.dwWaitHint = 0; SetServiceStatus(g_hServiceStatus, &g_ServiceStatus); break; case SERVICE_CONTROL_CONTINUE: // Update the service status g_ServiceStatus.dwCurrentState = SERVICE_CONTINUE_PENDING; g_ServiceStatus.dwWin32ExitCode = 0; g_ServiceStatus.dwCheckPoint = 0; g_ServiceStatus.dwWaitHint = 0; SetServiceStatus(g_hServiceStatus, &g_ServiceStatus); // Perform service-specific continue here // Update the service status g_ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP; g_ServiceStatus.dwCurrentState = SERVICE_RUNNING; g_ServiceStatus.dwWin32ExitCode = 0; g_ServiceStatus.dwCheckPoint = 0; g_ServiceStatus.dwWaitHint = 0; SetServiceStatus(g_hServiceStatus, &g_ServiceStatus); break; case SERVICE_CONTROL_SHUTDOWN: // Perform service-specific shutdown here g_ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_SHUTDOWN; g_ServiceStatus.dwCurrentState = SERVICE_STOP_PENDING; g_ServiceStatus.dwWin32ExitCode = 0; g_ServiceStatus.dwCheckPoint = 0; g_ServiceStatus.dwWaitHint = 0; SetServiceStatus(g_hServiceStatus, &g_ServiceStatus); break; default: // Update the service status g_ServiceStatus.dwWin32ExitCode = ERROR_CALL_NOT_IMPLEMENTED; g_ServiceStatus.dwCheckPoint = 0; g_ServiceStatus.dwWaitHint = 0; SetServiceStatus(g_hServiceStatus, &g_ServiceStatus); break; } } VOID WINAPI ServiceMain( _In_ DWORD argc, _In_ LPTSTR* argv ) { DWORD protectionLevel = 0; g_hServiceStatus = RegisterServiceCtrlHandlerExA("JonMon", (LPHANDLER_FUNCTION_EX)ServiceCtrlHandler, NULL); if (g_hServiceStatus == NULL) { return; } g_ServiceStatus.dwCurrentState = SERVICE_RUNNING; g_ServiceStatus.dwCheckPoint = 0; g_ServiceStatus.dwWaitHint = 0; g_ServiceStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS; g_ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN; g_ServiceStatus.dwWin32ExitCode = 0; g_ServiceStatus.dwServiceSpecificExitCode = 0; if (!SetServiceStatus(g_hServiceStatus, &g_ServiceStatus)) { return; } // // Register JonMon Providers // EventRegisterJonMon(); TraceLoggingRegister(g_hJonMon); EventSchema_Full eventSchema = { 0 }; int result = ConfigFile(argv[1], &eventSchema); if (result != 0) { printf("Failed to read configuration file\n"); return; } if (eventSchema.TokenImpersonation_Events) { LoadExtensions(); } protectionLevel = ProtectionCheck(); if (protectionLevel != 31) { ChangePPL(); } std::thread protectionCheck(ProtectionCheck); protectionCheck.detach(); TraceEvent(L"JonMon", JonMonGuid, &eventSchema); } DWORD ProtectionCheck() { Sleep(5000); DWORD protectionLevel = 0; do { PROCESS_PROTECTION_LEVEL_INFORMATION protectionInfo = { 0 }; if (GetProcessInformation(GetCurrentProcess(), ProcessProtectionLevelInfo, &protectionInfo, sizeof(protectionInfo))) { if (protectionInfo.ProtectionLevel != 5) { protectionLevel = 1; TraceLoggingWrite( g_hJonMon, "102", TraceLoggingInt32(102, "EventID"), TraceLoggingBool(TRUE, "JonMon Protection Level Changed") ); } } else { printf("Failed to retrieve PPL. Error code: %lu\n", GetLastError()); TraceLoggingWrite( g_hJonMon, "102", TraceLoggingInt32(102, "EventID"), TraceLoggingBool(FALSE, "JonMon Protection Level Changed") ); return 1; } } while (protectionLevel == 0); return 0; } VOID ChangePPL() { HANDLE hDevice = CreateFile(L"\\\\.\\JonMon", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (hDevice == INVALID_HANDLE_VALUE) { printf("Error %u\n", GetLastError()); return; } DWORD bytes; HANDLE hProcess; if (DeviceIoControl(hDevice, IOCTL_CHANGE_PROTECTION_LEVEL_PROCESS, NULL, NULL, NULL, NULL, NULL, NULL)) { OutputDebugStringW(L"Protection Level Changed\n"); } else { printf("Error: %u\n", GetLastError()); } CloseHandle(hDevice); } VOID LoadExtensions() { // // Loading JonMon-Ext1.dll to capture token impersonation events // typedef VOID(__stdcall* TokenImpersonationCheck)(); HMODULE hModule = LoadLibrary(L"JonMon-Ext1.dll"); if (hModule == NULL) { OutputDebugString(L"Failed to load JonMon-Ext1.dll"); return; } // // Execute the TokenImpersonationCheck function // TokenImpersonationCheck TokenImpersonationCheckFunc = (TokenImpersonationCheck)GetProcAddress(hModule, "TokenImpersonationCheck"); if (TokenImpersonationCheckFunc == NULL) { OutputDebugString(L"Failed to get TokenImpersonationCheck function address"); return; } // // Call the TokenImpersonationCheck function and give it a thread // std::thread tokenImpersonationCheckThread(TokenImpersonationCheckFunc); tokenImpersonationCheckThread.detach(); } DWORD CreateCustomService( _In_ LPCWSTR ServiceName, _In_ LPCWSTR ImagePath, _In_ DWORD dwServiceType ) { SC_HANDLE hSCManager = nullptr; SC_HANDLE hService = nullptr; DWORD dwError = 0; printf("[*] Creating Service %ws....\n", ServiceName); hSCManager = OpenSCManager(nullptr, nullptr, SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE); if (hSCManager == nullptr) { printf("[-] Service creation failed on OpenSCManager\n"); dwError = GetLastError(); goto Exit; } hService = CreateService(hSCManager, ServiceName, ServiceName, SC_MANAGER_CREATE_SERVICE, dwServiceType, SERVICE_DEMAND_START, SERVICE_ERROR_IGNORE, ImagePath, nullptr, nullptr, nullptr, nullptr, nullptr); if (hService == nullptr) { printf("[-] Service creation failed on CreateService\n"); dwError = GetLastError(); goto Exit; } printf("[*] Service %ws created successfully\n", ServiceName); Exit: if(hSCManager != nullptr) { CloseServiceHandle(hSCManager); } if(hService != nullptr) { CloseServiceHandle(hService); } return 0; } DWORD StartCustomService( _In_ LPCWSTR ServiceName ) { SC_HANDLE hSCManager = nullptr; SC_HANDLE hService = nullptr; DWORD dwError = 0; printf("[*] Starting Service %ws....\n", ServiceName); hSCManager = OpenSCManager(nullptr, nullptr, SERVICE_START); if (hSCManager == nullptr) { printf("[-] Start service failed on OpenSCManager\n"); dwError = GetLastError(); goto Exit; } hService = OpenService(hSCManager, ServiceName, SERVICE_START); if (hService == nullptr) { printf("[-] Start service failed on OpenService\n"); dwError = GetLastError(); goto Exit; } if (ServiceName == L"JonMon") { LPCWSTR serviceArgs[] = { L"C:\\Windows\\JonMonConfig.json"}; if (!StartService(hService, 1, serviceArgs)) { printf("[-] Start service failed on %ws\n", ServiceName); dwError = GetLastError(); goto Exit; } printf("[*] Service %ws started successfully\n", ServiceName); } else if (ServiceName == L"JonMonDrv") { if (!StartService(hService, 0, nullptr)) { printf("[-] Start service failed on %ws\n", ServiceName); dwError = GetLastError(); goto Exit; } printf("[*] Service %ws started successfully\n", ServiceName); } Exit: if (hSCManager != nullptr) { CloseServiceHandle(hSCManager); } if (hService != nullptr) { CloseServiceHandle(hService); } return 0; } DWORD StopCustomService( _In_ LPCWSTR ServiceName ) { printf("[*] Stopping Service %ws....\n", ServiceName); SC_HANDLE hSCManager = nullptr; hSCManager = OpenSCManager(nullptr, nullptr, SERVICE_STOP); if (hSCManager == nullptr) { printf("[-] OpenSCManager Failed"); return GetLastError(); } SC_HANDLE hService = OpenService(hSCManager, ServiceName, SERVICE_STOP); if (hService == nullptr) { printf("[-] OpenService Failed\n"); CloseServiceHandle(hSCManager); return GetLastError(); } SERVICE_STATUS status; if (!ControlService(hService, SERVICE_CONTROL_STOP, &status)) { printf("[-] ControlService Failed\n"); CloseServiceHandle(hSCManager); CloseServiceHandle(hService); return GetLastError(); } CloseServiceHandle(hSCManager); CloseServiceHandle(hService); if (g_hJonMon != NULL) { TraceLoggingUnregister(g_hJonMon); } printf("[*] Service %ws stopped successfully\n", ServiceName); return 0; } DWORD DeleteCustomService( _In_ LPCWSTR ServiceName ) { printf("[*] Deleting Service %ws....\n", ServiceName); SC_HANDLE hSCManager = nullptr; hSCManager = OpenSCManager(nullptr, nullptr, SC_MANAGER_CONNECT | SC_MANAGER_CREATE_SERVICE); if (hSCManager == nullptr) { printf("[-] OpenSCManager Failed\n"); return GetLastError(); } SC_HANDLE hService = OpenService(hSCManager, ServiceName, DELETE); if (hService == nullptr) { printf("[-] OpenService Failed\n"); CloseServiceHandle(hSCManager); return GetLastError(); } if (!DeleteService(hService)) { printf("[-] DeleteService Failed\n"); CloseServiceHandle(hSCManager); CloseServiceHandle(hService); return GetLastError(); } CloseServiceHandle(hSCManager); CloseServiceHandle(hService); printf("[*] Service %ws deleted successfully\n", ServiceName); return 0; } DWORD UninstallManifest() { printf("[*] Uninstalling Manifest....\n"); STARTUPINFOW si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); ZeroMemory(&pi, sizeof(pi)); wchar_t cmdLine[] = L"C:\\Windows\\System32\\wevtutil.exe um JonMon.man"; if (!CreateProcessW(NULL, cmdLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) { printf("CreateProcess Failed"); return GetLastError(); } WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); printf("[*] Manifest Uninstalled....\n"); return 0; } DWORD InstallManifest() { printf("[*] Installing Manifest....\n"); DWORD dwRet = UninstallManifest(); STARTUPINFOW si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); ZeroMemory(&pi, sizeof(pi)); wchar_t cmdLine[] = L"C:\\Windows\\System32\\wevtutil.exe im JonMon.man"; if (!CreateProcessW(NULL, cmdLine, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) { printf("[-] CreateProcess Failed"); return GetLastError(); } WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(pi.hProcess); CloseHandle(pi.hThread); printf("[*] Manifest Installed....\n"); return 0; } ================================================ FILE: JonMon-Service/service.h ================================================ #pragma once #include #define JonMon_DEVICE 0x8010 #define IOCTL_CHANGE_PROTECTION_LEVEL_PROCESS CTL_CODE(JonMon_DEVICE, 0x800, METHOD_BUFFERED, FILE_ANY_ACCESS) #define IOCTL_EVENT_CONFIGURATION CTL_CODE(JonMon_DEVICE, 0x801, METHOD_BUFFERED, FILE_ANY_ACCESS) VOID WINAPI ServiceCtrlHandler( _In_ DWORD dwCtrl ); VOID WINAPI ServiceMain( _In_ DWORD argc, _In_ LPTSTR* argv ); DWORD CreateCustomService( _In_ LPCWSTR ServiceName, _In_ LPCWSTR ImagePath, _In_ DWORD dwServiceType ); DWORD StartCustomService( _In_ LPCWSTR ServiceName ); DWORD StopCustomService( _In_ LPCWSTR ServiceName ); DWORD DeleteCustomService( _In_ LPCWSTR ServiceName ); DWORD UninstallManifest(); DWORD InstallManifest(); VOID ChangePPL(); DWORD ProtectionCheck(); VOID LoadExtensions(); ================================================ FILE: JonMonConfig.json ================================================ { "ConfigVersion": "1.0", "JonMonVersion": "2.0", "ProcessCreation_Events": false, "File_Events": false, "ProcessHandleCreation_Events": false, "ProcessHandleDuplication_Events": false, "Registry_Events": false, "RemoteThreadCreation_Events": false, "ImageLoad_Events": false, "ProcessTermination_Events": false, "RPC_Events": false, "Network_Events": false, "DotNetLoad_Events": false, "AMSI_Events": false, "SchedTask_Events": false, "WMIEventSubscription_Events": false, "CryptUnprotect_Events": false, "ThreatIntelligence_Events": { "RemoteReadProcessMemory": false, "RemoteWriteProcessMemory": false, "RemoteVirtualAllocation": false, "RemoteQueueUserAPC": false }, "TokenImpersonation_Events": false } ================================================ FILE: JonMonProvider/jonmon.h ================================================ //**********************************************************************` //* This is an include file generated by Message Compiler. *` //* *` //* Copyright (c) Microsoft Corporation. All Rights Reserved. *` //**********************************************************************` #pragma once //***************************************************************************** // // Notes on the ETW event code generated by MC: // // - Structures and arrays of structures are treated as an opaque binary blob. // The caller is responsible for packing the data for the structure into a // single region of memory, with no padding between values. The macro will // have an extra parameter for the length of the blob. // - Arrays of nul-terminated strings must be packed by the caller into a // single binary blob containing the correct number of strings, with a nul // after each string. The size of the blob is specified in characters, and // includes the final nul. // - Arrays of SID are treated as a single binary blob. The caller is // responsible for packing the SID values into a single region of memory with // no padding. // - The length attribute on the data element in the manifest is significant // for values with intype win:UnicodeString, win:AnsiString, or win:Binary. // The length attribute must be specified for win:Binary, and is optional for // win:UnicodeString and win:AnsiString (if no length is given, the strings // are assumed to be nul-terminated). For win:UnicodeString, the length is // measured in characters, not bytes. // - For an array of win:UnicodeString, win:AnsiString, or win:Binary, the // length attribute applies to every value in the array, so every value in // the array must have the same length. The values in the array are provided // to the macro via a single pointer -- the caller is responsible for packing // all of the values into a single region of memory with no padding between // values. // - Values of type win:CountedUnicodeString, win:CountedAnsiString, and // win:CountedBinary can be generated and collected on Vista or later. // However, they may not decode properly without the Windows 10 2018 Fall // Update. // - Arrays of type win:CountedUnicodeString, win:CountedAnsiString, and // win:CountedBinary must be packed by the caller into a single region of // memory. The format for each item is a UINT16 byte-count followed by that // many bytes of data. When providing the array to the generated macro, you // must provide the total size of the packed array data, including the UINT16 // sizes for each item. In the case of win:CountedUnicodeString, the data // size is specified in WCHAR (16-bit) units. In the case of // win:CountedAnsiString and win:CountedBinary, the data size is specified in // bytes. // //***************************************************************************** #include #include #include #ifndef ETW_INLINE #ifdef _ETW_KM_ // In kernel mode, save stack space by never inlining templates. #define ETW_INLINE DECLSPEC_NOINLINE __inline #else // In user mode, save code size by inlining templates as appropriate. #define ETW_INLINE __inline #endif #endif // ETW_INLINE #if defined(__cplusplus) extern "C" { #endif // // MCGEN_DISABLE_PROVIDER_CODE_GENERATION macro: // Define this macro to have the compiler skip the generated functions in this // header. // #ifndef MCGEN_DISABLE_PROVIDER_CODE_GENERATION // // MCGEN_USE_KERNEL_MODE_APIS macro: // Controls whether the generated code uses kernel-mode or user-mode APIs. // - Set to 0 to use Windows user-mode APIs such as EventRegister. // - Set to 1 to use Windows kernel-mode APIs such as EtwRegister. // Default is based on whether the _ETW_KM_ macro is defined (i.e. by wdm.h). // Note that the APIs can also be overridden directly, e.g. by setting the // MCGEN_EVENTWRITETRANSFER or MCGEN_EVENTREGISTER macros. // #ifndef MCGEN_USE_KERNEL_MODE_APIS #ifdef _ETW_KM_ #define MCGEN_USE_KERNEL_MODE_APIS 1 #else #define MCGEN_USE_KERNEL_MODE_APIS 0 #endif #endif // MCGEN_USE_KERNEL_MODE_APIS // // MCGEN_HAVE_EVENTSETINFORMATION macro: // Controls how McGenEventSetInformation uses the EventSetInformation API. // - Set to 0 to disable the use of EventSetInformation // (McGenEventSetInformation will always return an error). // - Set to 1 to directly invoke MCGEN_EVENTSETINFORMATION. // - Set to 2 to to locate EventSetInformation at runtime via GetProcAddress // (user-mode) or MmGetSystemRoutineAddress (kernel-mode). // Default is determined as follows: // - If MCGEN_EVENTSETINFORMATION has been customized, set to 1 // (i.e. use MCGEN_EVENTSETINFORMATION). // - Else if the target OS version has EventSetInformation, set to 1 // (i.e. use MCGEN_EVENTSETINFORMATION). // - Else set to 2 (i.e. try to dynamically locate EventSetInformation). // Note that an McGenEventSetInformation function will only be generated if one // or more provider in a manifest has provider traits. // #ifndef MCGEN_HAVE_EVENTSETINFORMATION #ifdef MCGEN_EVENTSETINFORMATION // if MCGEN_EVENTSETINFORMATION has been customized, #define MCGEN_HAVE_EVENTSETINFORMATION 1 // directly invoke MCGEN_EVENTSETINFORMATION(...). #elif MCGEN_USE_KERNEL_MODE_APIS // else if using kernel-mode APIs, #if NTDDI_VERSION >= 0x06040000 // if target OS is Windows 10 or later, #define MCGEN_HAVE_EVENTSETINFORMATION 1 // directly invoke MCGEN_EVENTSETINFORMATION(...). #else // else #define MCGEN_HAVE_EVENTSETINFORMATION 2 // find "EtwSetInformation" via MmGetSystemRoutineAddress. #endif // else (using user-mode APIs) #else // if target OS and SDK is Windows 8 or later, #if WINVER >= 0x0602 && defined(EVENT_FILTER_TYPE_SCHEMATIZED) #define MCGEN_HAVE_EVENTSETINFORMATION 1 // directly invoke MCGEN_EVENTSETINFORMATION(...). #else // else #define MCGEN_HAVE_EVENTSETINFORMATION 2 // find "EventSetInformation" via GetModuleHandleExW/GetProcAddress. #endif #endif #endif // MCGEN_HAVE_EVENTSETINFORMATION // // MCGEN Override Macros // // The following override macros may be defined before including this header // to control the APIs used by this header: // // - MCGEN_EVENTREGISTER // - MCGEN_EVENTUNREGISTER // - MCGEN_EVENTSETINFORMATION // - MCGEN_EVENTWRITETRANSFER // // If the the macro is undefined, the MC implementation will default to the // corresponding ETW APIs. For example, if the MCGEN_EVENTREGISTER macro is // undefined, the EventRegister[MyProviderName] macro will use EventRegister // in user mode and will use EtwRegister in kernel mode. // // To prevent issues from conflicting definitions of these macros, the value // of the override macro will be used as a suffix in certain internal function // names. Because of this, the override macros must follow certain rules: // // - The macro must be defined before any MC-generated header is included and // must not be undefined or redefined after any MC-generated header is // included. Different translation units (i.e. different .c or .cpp files) // may set the macros to different values, but within a translation unit // (within a single .c or .cpp file), the macro must be set once and not // changed. // - The override must be an object-like macro, not a function-like macro // (i.e. the override macro must not have a parameter list). // - The override macro's value must be a simple identifier, i.e. must be // something that starts with a letter or '_' and contains only letters, // numbers, and '_' characters. // - If the override macro's value is the name of a second object-like macro, // the second object-like macro must follow the same rules. (The override // macro's value can also be the name of a function-like macro, in which // case the function-like macro does not need to follow the same rules.) // // For example, the following will cause compile errors: // // #define MCGEN_EVENTWRITETRANSFER MyNamespace::MyClass::MyFunction // Value has non-identifier characters (colon). // #define MCGEN_EVENTWRITETRANSFER GetEventWriteFunctionPointer(7) // Value has non-identifier characters (parentheses). // #define MCGEN_EVENTWRITETRANSFER(h,e,a,r,c,d) EventWrite(h,e,c,d) // Override is defined as a function-like macro. // #define MY_OBJECT_LIKE_MACRO MyNamespace::MyClass::MyEventWriteFunction // #define MCGEN_EVENTWRITETRANSFER MY_OBJECT_LIKE_MACRO // Evaluates to something with non-identifier characters (colon). // // The following would be ok: // // #define MCGEN_EVENTWRITETRANSFER MyEventWriteFunction1 // OK, suffix will be "MyEventWriteFunction1". // #define MY_OBJECT_LIKE_MACRO MyEventWriteFunction2 // #define MCGEN_EVENTWRITETRANSFER MY_OBJECT_LIKE_MACRO // OK, suffix will be "MyEventWriteFunction2". // #define MY_FUNCTION_LIKE_MACRO(h,e,a,r,c,d) MyNamespace::MyClass::MyEventWriteFunction3(h,e,c,d) // #define MCGEN_EVENTWRITETRANSFER MY_FUNCTION_LIKE_MACRO // OK, suffix will be "MY_FUNCTION_LIKE_MACRO". // #ifndef MCGEN_EVENTREGISTER #if MCGEN_USE_KERNEL_MODE_APIS #define MCGEN_EVENTREGISTER EtwRegister #else #define MCGEN_EVENTREGISTER EventRegister #endif #endif // MCGEN_EVENTREGISTER #ifndef MCGEN_EVENTUNREGISTER #if MCGEN_USE_KERNEL_MODE_APIS #define MCGEN_EVENTUNREGISTER EtwUnregister #else #define MCGEN_EVENTUNREGISTER EventUnregister #endif #endif // MCGEN_EVENTUNREGISTER #ifndef MCGEN_EVENTSETINFORMATION #if MCGEN_USE_KERNEL_MODE_APIS #define MCGEN_EVENTSETINFORMATION EtwSetInformation #else #define MCGEN_EVENTSETINFORMATION EventSetInformation #endif #endif // MCGEN_EVENTSETINFORMATION #ifndef MCGEN_EVENTWRITETRANSFER #if MCGEN_USE_KERNEL_MODE_APIS #define MCGEN_EVENTWRITETRANSFER EtwWriteTransfer #else #define MCGEN_EVENTWRITETRANSFER EventWriteTransfer #endif #endif // MCGEN_EVENTWRITETRANSFER // // MCGEN_EVENT_ENABLED macro: // Override to control how the EventWrite[EventName] macros determine whether // an event is enabled. The default behavior is for EventWrite[EventName] to // use the EventEnabled[EventName] macros. // #ifndef MCGEN_EVENT_ENABLED #define MCGEN_EVENT_ENABLED(EventName) EventEnabled##EventName() #endif // // MCGEN_EVENT_ENABLED_FORCONTEXT macro: // Override to control how the EventWrite[EventName]_ForContext macros // determine whether an event is enabled. The default behavior is for // EventWrite[EventName]_ForContext to use the // EventEnabled[EventName]_ForContext macros. // #ifndef MCGEN_EVENT_ENABLED_FORCONTEXT #define MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, EventName) EventEnabled##EventName##_ForContext(pContext) #endif // // MCGEN_ENABLE_CHECK macro: // Determines whether the specified event would be considered as enabled // based on the state of the specified context. Slightly faster than calling // McGenEventEnabled directly. // #ifndef MCGEN_ENABLE_CHECK #define MCGEN_ENABLE_CHECK(Context, Descriptor) (Context.IsEnabled && McGenEventEnabled(&Context, &Descriptor)) #endif #if !defined(MCGEN_TRACE_CONTEXT_DEF) #define MCGEN_TRACE_CONTEXT_DEF // This structure is for use by MC-generated code and should not be used directly. typedef struct _MCGEN_TRACE_CONTEXT { TRACEHANDLE RegistrationHandle; TRACEHANDLE Logger; // Used as pointer to provider traits. ULONGLONG MatchAnyKeyword; ULONGLONG MatchAllKeyword; ULONG Flags; ULONG IsEnabled; UCHAR Level; UCHAR Reserve; USHORT EnableBitsCount; PULONG EnableBitMask; const ULONGLONG* EnableKeyWords; const UCHAR* EnableLevel; } MCGEN_TRACE_CONTEXT, *PMCGEN_TRACE_CONTEXT; #endif // MCGEN_TRACE_CONTEXT_DEF #if !defined(MCGEN_LEVEL_KEYWORD_ENABLED_DEF) #define MCGEN_LEVEL_KEYWORD_ENABLED_DEF // // Determines whether an event with a given Level and Keyword would be // considered as enabled based on the state of the specified context. // Note that you may want to use MCGEN_ENABLE_CHECK instead of calling this // function directly. // FORCEINLINE BOOLEAN McGenLevelKeywordEnabled( _In_ PMCGEN_TRACE_CONTEXT EnableInfo, _In_ UCHAR Level, _In_ ULONGLONG Keyword ) { // // Check if the event Level is lower than the level at which // the channel is enabled. // If the event Level is 0 or the channel is enabled at level 0, // all levels are enabled. // if ((Level <= EnableInfo->Level) || // This also covers the case of Level == 0. (EnableInfo->Level == 0)) { // // Check if Keyword is enabled // if ((Keyword == (ULONGLONG)0) || ((Keyword & EnableInfo->MatchAnyKeyword) && ((Keyword & EnableInfo->MatchAllKeyword) == EnableInfo->MatchAllKeyword))) { return TRUE; } } return FALSE; } #endif // MCGEN_LEVEL_KEYWORD_ENABLED_DEF #if !defined(MCGEN_EVENT_ENABLED_DEF) #define MCGEN_EVENT_ENABLED_DEF // // Determines whether the specified event would be considered as enabled based // on the state of the specified context. Note that you may want to use // MCGEN_ENABLE_CHECK instead of calling this function directly. // FORCEINLINE BOOLEAN McGenEventEnabled( _In_ PMCGEN_TRACE_CONTEXT EnableInfo, _In_ PCEVENT_DESCRIPTOR EventDescriptor ) { return McGenLevelKeywordEnabled(EnableInfo, EventDescriptor->Level, EventDescriptor->Keyword); } #endif // MCGEN_EVENT_ENABLED_DEF #if !defined(MCGEN_CONTROL_CALLBACK) #define MCGEN_CONTROL_CALLBACK // This function is for use by MC-generated code and should not be used directly. DECLSPEC_NOINLINE __inline VOID __stdcall McGenControlCallbackV2( _In_ LPCGUID SourceId, _In_ ULONG ControlCode, _In_ UCHAR Level, _In_ ULONGLONG MatchAnyKeyword, _In_ ULONGLONG MatchAllKeyword, _In_opt_ PEVENT_FILTER_DESCRIPTOR FilterData, _Inout_opt_ PVOID CallbackContext ) /*++ Routine Description: This is the notification callback for Windows Vista and later. Arguments: SourceId - The GUID that identifies the session that enabled the provider. ControlCode - The parameter indicates whether the provider is being enabled or disabled. Level - The level at which the event is enabled. MatchAnyKeyword - The bitmask of keywords that the provider uses to determine the category of events that it writes. MatchAllKeyword - This bitmask additionally restricts the category of events that the provider writes. FilterData - The provider-defined data. CallbackContext - The context of the callback that is defined when the provider called EtwRegister to register itself. Remarks: ETW calls this function to notify provider of enable/disable --*/ { PMCGEN_TRACE_CONTEXT Ctx = (PMCGEN_TRACE_CONTEXT)CallbackContext; ULONG Ix; #ifndef MCGEN_PRIVATE_ENABLE_CALLBACK_V2 UNREFERENCED_PARAMETER(SourceId); UNREFERENCED_PARAMETER(FilterData); #endif if (Ctx == NULL) { return; } switch (ControlCode) { case EVENT_CONTROL_CODE_ENABLE_PROVIDER: Ctx->Level = Level; Ctx->MatchAnyKeyword = MatchAnyKeyword; Ctx->MatchAllKeyword = MatchAllKeyword; Ctx->IsEnabled = EVENT_CONTROL_CODE_ENABLE_PROVIDER; for (Ix = 0; Ix < Ctx->EnableBitsCount; Ix += 1) { if (McGenLevelKeywordEnabled(Ctx, Ctx->EnableLevel[Ix], Ctx->EnableKeyWords[Ix]) != FALSE) { Ctx->EnableBitMask[Ix >> 5] |= (1 << (Ix % 32)); } else { Ctx->EnableBitMask[Ix >> 5] &= ~(1 << (Ix % 32)); } } break; case EVENT_CONTROL_CODE_DISABLE_PROVIDER: Ctx->IsEnabled = EVENT_CONTROL_CODE_DISABLE_PROVIDER; Ctx->Level = 0; Ctx->MatchAnyKeyword = 0; Ctx->MatchAllKeyword = 0; if (Ctx->EnableBitsCount > 0) { #pragma warning(suppress: 26451) // Arithmetic overflow cannot occur, no matter the value of EnableBitCount RtlZeroMemory(Ctx->EnableBitMask, (((Ctx->EnableBitsCount - 1) / 32) + 1) * sizeof(ULONG)); } break; default: break; } #ifdef MCGEN_PRIVATE_ENABLE_CALLBACK_V2 // // Call user defined callback // MCGEN_PRIVATE_ENABLE_CALLBACK_V2( SourceId, ControlCode, Level, MatchAnyKeyword, MatchAllKeyword, FilterData, CallbackContext ); #endif // MCGEN_PRIVATE_ENABLE_CALLBACK_V2 return; } #endif // MCGEN_CONTROL_CALLBACK #ifndef _mcgen_PENABLECALLBACK #if MCGEN_USE_KERNEL_MODE_APIS #define _mcgen_PENABLECALLBACK PETWENABLECALLBACK #else #define _mcgen_PENABLECALLBACK PENABLECALLBACK #endif #endif // _mcgen_PENABLECALLBACK #if !defined(_mcgen_PASTE2) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_PASTE2(a, b) _mcgen_PASTE2_imp(a, b) #define _mcgen_PASTE2_imp(a, b) a##b #endif // _mcgen_PASTE2 #if !defined(_mcgen_PASTE3) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_PASTE3(a, b, c) _mcgen_PASTE3_imp(a, b, c) #define _mcgen_PASTE3_imp(a, b, c) a##b##_##c #endif // _mcgen_PASTE3 // // Macro validation // // Validate MCGEN_EVENTREGISTER: // Trigger an error if MCGEN_EVENTREGISTER is not an unqualified (simple) identifier: struct _mcgen_PASTE2(MCGEN_EVENTREGISTER_definition_must_be_an_unqualified_identifier_, MCGEN_EVENTREGISTER); // Trigger an error if MCGEN_EVENTREGISTER is redefined: typedef struct _mcgen_PASTE2(MCGEN_EVENTREGISTER_definition_must_be_an_unqualified_identifier_, MCGEN_EVENTREGISTER) MCGEN_EVENTREGISTER_must_not_be_redefined_between_headers; // Trigger an error if MCGEN_EVENTREGISTER is defined as a function-like macro: typedef void MCGEN_EVENTREGISTER_must_not_be_a_functionLike_macro_MCGEN_EVENTREGISTER; typedef int _mcgen_PASTE2(MCGEN_EVENTREGISTER_must_not_be_a_functionLike_macro_, MCGEN_EVENTREGISTER); // Validate MCGEN_EVENTUNREGISTER: // Trigger an error if MCGEN_EVENTUNREGISTER is not an unqualified (simple) identifier: struct _mcgen_PASTE2(MCGEN_EVENTUNREGISTER_definition_must_be_an_unqualified_identifier_, MCGEN_EVENTUNREGISTER); // Trigger an error if MCGEN_EVENTUNREGISTER is redefined: typedef struct _mcgen_PASTE2(MCGEN_EVENTUNREGISTER_definition_must_be_an_unqualified_identifier_, MCGEN_EVENTUNREGISTER) MCGEN_EVENTUNREGISTER_must_not_be_redefined_between_headers; // Trigger an error if MCGEN_EVENTUNREGISTER is defined as a function-like macro: typedef void MCGEN_EVENTUNREGISTER_must_not_be_a_functionLike_macro_MCGEN_EVENTUNREGISTER; typedef int _mcgen_PASTE2(MCGEN_EVENTUNREGISTER_must_not_be_a_functionLike_macro_, MCGEN_EVENTUNREGISTER); // Validate MCGEN_EVENTSETINFORMATION: // Trigger an error if MCGEN_EVENTSETINFORMATION is not an unqualified (simple) identifier: struct _mcgen_PASTE2(MCGEN_EVENTSETINFORMATION_definition_must_be_an_unqualified_identifier_, MCGEN_EVENTSETINFORMATION); // Trigger an error if MCGEN_EVENTSETINFORMATION is redefined: typedef struct _mcgen_PASTE2(MCGEN_EVENTSETINFORMATION_definition_must_be_an_unqualified_identifier_, MCGEN_EVENTSETINFORMATION) MCGEN_EVENTSETINFORMATION_must_not_be_redefined_between_headers; // Trigger an error if MCGEN_EVENTSETINFORMATION is defined as a function-like macro: typedef void MCGEN_EVENTSETINFORMATION_must_not_be_a_functionLike_macro_MCGEN_EVENTSETINFORMATION; typedef int _mcgen_PASTE2(MCGEN_EVENTSETINFORMATION_must_not_be_a_functionLike_macro_, MCGEN_EVENTSETINFORMATION); // Validate MCGEN_EVENTWRITETRANSFER: // Trigger an error if MCGEN_EVENTWRITETRANSFER is not an unqualified (simple) identifier: struct _mcgen_PASTE2(MCGEN_EVENTWRITETRANSFER_definition_must_be_an_unqualified_identifier_, MCGEN_EVENTWRITETRANSFER); // Trigger an error if MCGEN_EVENTWRITETRANSFER is redefined: typedef struct _mcgen_PASTE2(MCGEN_EVENTWRITETRANSFER_definition_must_be_an_unqualified_identifier_, MCGEN_EVENTWRITETRANSFER) MCGEN_EVENTWRITETRANSFER_must_not_be_redefined_between_headers;; // Trigger an error if MCGEN_EVENTWRITETRANSFER is defined as a function-like macro: typedef void MCGEN_EVENTWRITETRANSFER_must_not_be_a_functionLike_macro_MCGEN_EVENTWRITETRANSFER; typedef int _mcgen_PASTE2(MCGEN_EVENTWRITETRANSFER_must_not_be_a_functionLike_macro_, MCGEN_EVENTWRITETRANSFER); #ifndef McGenEventWrite_def #define McGenEventWrite_def // This macro is for use by MC-generated code and should not be used directly. #define McGenEventWrite _mcgen_PASTE2(McGenEventWrite_, MCGEN_EVENTWRITETRANSFER) // This function is for use by MC-generated code and should not be used directly. DECLSPEC_NOINLINE __inline ULONG __stdcall McGenEventWrite( _In_ PMCGEN_TRACE_CONTEXT Context, _In_ PCEVENT_DESCRIPTOR Descriptor, _In_opt_ LPCGUID ActivityId, _In_range_(1, 128) ULONG EventDataCount, _Pre_cap_(EventDataCount) EVENT_DATA_DESCRIPTOR* EventData ) { const USHORT UNALIGNED* Traits; // Some customized MCGEN_EVENTWRITETRANSFER macros might ignore ActivityId. UNREFERENCED_PARAMETER(ActivityId); Traits = (const USHORT UNALIGNED*)(UINT_PTR)Context->Logger; if (Traits == NULL) { EventData[0].Ptr = 0; EventData[0].Size = 0; EventData[0].Reserved = 0; } else { EventData[0].Ptr = (ULONG_PTR)Traits; EventData[0].Size = *Traits; EventData[0].Reserved = 2; // EVENT_DATA_DESCRIPTOR_TYPE_PROVIDER_METADATA } return MCGEN_EVENTWRITETRANSFER( Context->RegistrationHandle, Descriptor, ActivityId, NULL, EventDataCount, EventData); } #endif // McGenEventWrite_def #if !defined(McGenEventRegisterUnregister) #define McGenEventRegisterUnregister // This macro is for use by MC-generated code and should not be used directly. #define McGenEventRegister _mcgen_PASTE2(McGenEventRegister_, MCGEN_EVENTREGISTER) #pragma warning(push) #pragma warning(disable:6103) // This function is for use by MC-generated code and should not be used directly. DECLSPEC_NOINLINE __inline ULONG __stdcall McGenEventRegister( _In_ LPCGUID ProviderId, _In_opt_ _mcgen_PENABLECALLBACK EnableCallback, _In_opt_ PVOID CallbackContext, _Inout_ PREGHANDLE RegHandle ) /*++ Routine Description: This function registers the provider with ETW. Arguments: ProviderId - Provider ID to register with ETW. EnableCallback - Callback to be used. CallbackContext - Context for the callback. RegHandle - Pointer to registration handle. Remarks: Should not be called if the provider is already registered (i.e. should not be called if *RegHandle != 0). Repeatedly registering a provider is a bug and may indicate a race condition. However, for compatibility with previous behavior, this function will return SUCCESS in this case. --*/ { ULONG Error; if (*RegHandle != 0) { Error = 0; // ERROR_SUCCESS } else { Error = MCGEN_EVENTREGISTER(ProviderId, EnableCallback, CallbackContext, RegHandle); } return Error; } #pragma warning(pop) // This macro is for use by MC-generated code and should not be used directly. #define McGenEventUnregister _mcgen_PASTE2(McGenEventUnregister_, MCGEN_EVENTUNREGISTER) // This function is for use by MC-generated code and should not be used directly. DECLSPEC_NOINLINE __inline ULONG __stdcall McGenEventUnregister(_Inout_ PREGHANDLE RegHandle) /*++ Routine Description: Unregister from ETW and set *RegHandle = 0. Arguments: RegHandle - the pointer to the provider registration handle Remarks: If provider has not been registered (i.e. if *RegHandle == 0), return SUCCESS. It is safe to call McGenEventUnregister even if the call to McGenEventRegister returned an error. --*/ { ULONG Error; if(*RegHandle == 0) { Error = 0; // ERROR_SUCCESS } else { Error = MCGEN_EVENTUNREGISTER(*RegHandle); *RegHandle = (REGHANDLE)0; } return Error; } #endif // McGenEventRegisterUnregister #ifndef _mcgen_EVENT_BIT_SET #if defined(_M_IX86) || defined(_M_X64) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_EVENT_BIT_SET(EnableBits, BitPosition) ((((const unsigned char*)EnableBits)[BitPosition >> 3] & (1u << (BitPosition & 7))) != 0) #else // CPU type // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_EVENT_BIT_SET(EnableBits, BitPosition) ((EnableBits[BitPosition >> 5] & (1u << (BitPosition & 31))) != 0) #endif // CPU type #endif // _mcgen_EVENT_BIT_SET #endif // MCGEN_DISABLE_PROVIDER_CODE_GENERATION //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Provider "JonMon" event count 27 //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Provider GUID = d8909c24-5be9-4502-98ca-ab7bdc24899d EXTERN_C __declspec(selectany) const GUID JonMonProvider = {0xd8909c24, 0x5be9, 0x4502, {0x98, 0xca, 0xab, 0x7b, 0xdc, 0x24, 0x89, 0x9d}}; #ifndef JonMonProvider_Traits #define JonMonProvider_Traits NULL #endif // JonMonProvider_Traits // // Channel // #define JonMonProvider_CHANNEL_JonMon 0x10 #define JonMonProvider_CHANNEL_JonMon_KEYWORD 0x8000000000000000 // // Event Descriptors // EXTERN_C __declspec(selectany) const EVENT_DESCRIPTOR ProcessCreation = {0x1, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000}; #define ProcessCreation_value 0x1 EXTERN_C __declspec(selectany) const EVENT_DESCRIPTOR ProcessTerminate = {0x2, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000}; #define ProcessTerminate_value 0x2 EXTERN_C __declspec(selectany) const EVENT_DESCRIPTOR RemoteThreadCreation = {0x3, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000}; #define RemoteThreadCreation_value 0x3 EXTERN_C __declspec(selectany) const EVENT_DESCRIPTOR ImageLoaded = {0x4, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000}; #define ImageLoaded_value 0x4 EXTERN_C __declspec(selectany) const EVENT_DESCRIPTOR ProcessAccess = {0x5, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000}; #define ProcessAccess_value 0x5 EXTERN_C __declspec(selectany) const EVENT_DESCRIPTOR RegistrySaveKey = {0x6, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000}; #define RegistrySaveKey_value 0x6 EXTERN_C __declspec(selectany) const EVENT_DESCRIPTOR RegistrySetValueKey = {0x8, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000}; #define RegistrySetValueKey_value 0x8 EXTERN_C __declspec(selectany) const EVENT_DESCRIPTOR RegistryCreateKey = {0x9, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000}; #define RegistryCreateKey_value 0x9 EXTERN_C __declspec(selectany) const EVENT_DESCRIPTOR FileCreation = {0xa, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000}; #define FileCreation_value 0xa EXTERN_C __declspec(selectany) const EVENT_DESCRIPTOR NamedPipeCreation = {0xb, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000}; #define NamedPipeCreation_value 0xb EXTERN_C __declspec(selectany) const EVENT_DESCRIPTOR NamedPipeConnection = {0xc, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000}; #define NamedPipeConnection_value 0xc EXTERN_C __declspec(selectany) const EVENT_DESCRIPTOR MailslotCreation = {0xd, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000}; #define MailslotCreation_value 0xd EXTERN_C __declspec(selectany) const EVENT_DESCRIPTOR MailslotConnection = {0xe, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000}; #define MailslotConnection_value 0xe EXTERN_C __declspec(selectany) const EVENT_DESCRIPTOR RemoteFileConnection = {0xf, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000}; #define RemoteFileConnection_value 0xf EXTERN_C __declspec(selectany) const EVENT_DESCRIPTOR DotNetLoad = {0x10, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000}; #define DotNetLoad_value 0x10 EXTERN_C __declspec(selectany) const EVENT_DESCRIPTOR WMIEventFilter = {0x11, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000}; #define WMIEventFilter_value 0x11 EXTERN_C __declspec(selectany) const EVENT_DESCRIPTOR RPCClient = {0x12, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000}; #define RPCClient_value 0x12 EXTERN_C __declspec(selectany) const EVENT_DESCRIPTOR RPCServer = {0x13, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000}; #define RPCServer_value 0x13 EXTERN_C __declspec(selectany) const EVENT_DESCRIPTOR DPAPIUnprotect = {0x14, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000}; #define DPAPIUnprotect_value 0x14 EXTERN_C __declspec(selectany) const EVENT_DESCRIPTOR NetworkConnection = {0x15, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000}; #define NetworkConnection_value 0x15 EXTERN_C __declspec(selectany) const EVENT_DESCRIPTOR AMSI = {0x16, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000}; #define AMSI_value 0x16 EXTERN_C __declspec(selectany) const EVENT_DESCRIPTOR RemoteReadProcessMemory = {0x17, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000}; #define RemoteReadProcessMemory_value 0x17 EXTERN_C __declspec(selectany) const EVENT_DESCRIPTOR RemoteWriteProcessMemory = {0x18, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000}; #define RemoteWriteProcessMemory_value 0x18 EXTERN_C __declspec(selectany) const EVENT_DESCRIPTOR RemoteVirtualAllocation = {0x19, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000}; #define RemoteVirtualAllocation_value 0x19 EXTERN_C __declspec(selectany) const EVENT_DESCRIPTOR RemoteQueueUserAPC = {0x1a, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000}; #define RemoteQueueUserAPC_value 0x1a EXTERN_C __declspec(selectany) const EVENT_DESCRIPTOR QueryTokenImpersonation = {0x1b, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000}; #define QueryTokenImpersonation_value 0x1b EXTERN_C __declspec(selectany) const EVENT_DESCRIPTOR DebugLog102 = {0x66, 0x0, 0x10, 0x4, 0x0, 0x0, 0x8000000000000000}; #define DebugLog102_value 0x66 // // MCGEN_DISABLE_PROVIDER_CODE_GENERATION macro: // Define this macro to have the compiler skip the generated functions in this // header. // #ifndef MCGEN_DISABLE_PROVIDER_CODE_GENERATION // // Event Enablement Bits // These variables are for use by MC-generated code and should not be used directly. // EXTERN_C __declspec(selectany) DECLSPEC_CACHEALIGN ULONG JonMonEnableBits[1]; EXTERN_C __declspec(selectany) const ULONGLONG JonMonKeywords[1] = {0x8000000000000000}; EXTERN_C __declspec(selectany) const unsigned char JonMonLevels[1] = {4}; // // Provider context // EXTERN_C __declspec(selectany) MCGEN_TRACE_CONTEXT JonMonProvider_Context = {0, (ULONG_PTR)JonMonProvider_Traits, 0, 0, 0, 0, 0, 0, 1, JonMonEnableBits, JonMonKeywords, JonMonLevels}; // // Provider REGHANDLE // #define JonMonHandle (JonMonProvider_Context.RegistrationHandle) // // This macro is set to 0, indicating that the EventWrite[Name] macros do not // have an Activity parameter. This is controlled by the -km and -um options. // #define JonMonProvider_EventWriteActivity 0 // // Register with ETW using the control GUID specified in the manifest. // Invoke this macro during module initialization (i.e. program startup, // DLL process attach, or driver load) to initialize the provider. // Note that if this function returns an error, the error means that // will not work, but no action needs to be taken -- even if EventRegister // returns an error, it is generally safe to use EventWrite and // EventUnregister macros (they will be no-ops if EventRegister failed). // #ifndef EventRegisterJonMon #define EventRegisterJonMon() McGenEventRegister(&JonMonProvider, McGenControlCallbackV2, &JonMonProvider_Context, &JonMonHandle) #endif // // Register with ETW using a specific control GUID (i.e. a GUID other than what // is specified in the manifest). Advanced scenarios only. // #ifndef EventRegisterByGuidJonMon #define EventRegisterByGuidJonMon(Guid) McGenEventRegister(&(Guid), McGenControlCallbackV2, &JonMonProvider_Context, &JonMonHandle) #endif // // Unregister with ETW and close the provider. // Invoke this macro during module shutdown (i.e. program exit, DLL process // detach, or driver unload) to unregister the provider. // Note that you MUST call EventUnregister before DLL or driver unload // (not optional): failure to unregister a provider before DLL or driver unload // will result in crashes. // #ifndef EventUnregisterJonMon #define EventUnregisterJonMon() McGenEventUnregister(&JonMonHandle) #endif // // MCGEN_ENABLE_FORCONTEXT_CODE_GENERATION macro: // Define this macro to enable support for caller-allocated provider context. // #ifdef MCGEN_ENABLE_FORCONTEXT_CODE_GENERATION // // Advanced scenarios: Caller-allocated provider context. // Use when multiple differently-configured provider handles are needed, // e.g. for container-aware drivers, one context per container. // // Usage: // // - Caller enables the feature before including this header, e.g. // #define MCGEN_ENABLE_FORCONTEXT_CODE_GENERATION 1 // - Caller allocates memory, e.g. pContext = malloc(sizeof(McGenContext_JonMon)); // - Caller registers the provider, e.g. EventRegisterJonMon_ForContext(pContext); // - Caller writes events, e.g. EventWriteMyEvent_ForContext(pContext, ...); // - Caller unregisters, e.g. EventUnregisterJonMon_ForContext(pContext); // - Caller frees memory, e.g. free(pContext); // typedef struct tagMcGenContext_JonMon { // The fields of this structure are subject to change and should // not be accessed directly. To access the provider's REGHANDLE, // use JonMonHandle_ForContext(pContext). MCGEN_TRACE_CONTEXT Context; ULONG EnableBits[1]; } McGenContext_JonMon; #define EventRegisterJonMon_ForContext(pContext) _mcgen_PASTE2(_mcgen_RegisterForContext_JonMon_, MCGEN_EVENTREGISTER)(&JonMonProvider, pContext) #define EventRegisterByGuidJonMon_ForContext(Guid, pContext) _mcgen_PASTE2(_mcgen_RegisterForContext_JonMon_, MCGEN_EVENTREGISTER)(&(Guid), pContext) #define EventUnregisterJonMon_ForContext(pContext) McGenEventUnregister(&(pContext)->Context.RegistrationHandle) // // Provider REGHANDLE for caller-allocated context. // #define JonMonHandle_ForContext(pContext) ((pContext)->Context.RegistrationHandle) // This function is for use by MC-generated code and should not be used directly. // Initialize and register the caller-allocated context. __inline ULONG __stdcall _mcgen_PASTE2(_mcgen_RegisterForContext_JonMon_, MCGEN_EVENTREGISTER)( _In_ LPCGUID pProviderId, _Out_ McGenContext_JonMon* pContext) { RtlZeroMemory(pContext, sizeof(*pContext)); pContext->Context.Logger = (ULONG_PTR)JonMonProvider_Traits; pContext->Context.EnableBitsCount = 1; pContext->Context.EnableBitMask = pContext->EnableBits; pContext->Context.EnableKeyWords = JonMonKeywords; pContext->Context.EnableLevel = JonMonLevels; return McGenEventRegister( pProviderId, McGenControlCallbackV2, &pContext->Context, &pContext->Context.RegistrationHandle); } // This function is for use by MC-generated code and should not be used directly. // Trigger a compile error if called with the wrong parameter type. FORCEINLINE _Ret_ McGenContext_JonMon* _mcgen_CheckContextType_JonMon(_In_ McGenContext_JonMon* pContext) { return pContext; } #endif // MCGEN_ENABLE_FORCONTEXT_CODE_GENERATION // // Enablement check macro for event "ProcessCreation" // #define EventEnabledProcessCreation() _mcgen_EVENT_BIT_SET(JonMonEnableBits, 0) #define EventEnabledProcessCreation_ForContext(pContext) _mcgen_EVENT_BIT_SET(_mcgen_CheckContextType_JonMon(pContext)->EnableBits, 0) // // Event write macros for event "ProcessCreation" // #define EventWriteProcessCreation(EventTime, CreatorThreadId, CreatorProcessId, ParentProcessId, ParentProcessStartKey, ParentProcessFilePath, ParentProcessUser, ParentProcessUserLogonId, ParentProcessIntegrityLevel, ParentProcessSessionId, ParentProcessTokenType, ProcessFilePath, ProcessCommandLine, ProcessId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessUserLinkedLogonId, ProcessIntegrityLevel, ProcessSessionId, ProcessTokenType, ProcessReparented) \ MCGEN_EVENT_ENABLED(ProcessCreation) \ ? _mcgen_TEMPLATE_FOR_ProcessCreation(&JonMonProvider_Context, &ProcessCreation, EventTime, CreatorThreadId, CreatorProcessId, ParentProcessId, ParentProcessStartKey, ParentProcessFilePath, ParentProcessUser, ParentProcessUserLogonId, ParentProcessIntegrityLevel, ParentProcessSessionId, ParentProcessTokenType, ProcessFilePath, ProcessCommandLine, ProcessId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessUserLinkedLogonId, ProcessIntegrityLevel, ProcessSessionId, ProcessTokenType, ProcessReparented) : 0 #define EventWriteProcessCreation_AssumeEnabled(EventTime, CreatorThreadId, CreatorProcessId, ParentProcessId, ParentProcessStartKey, ParentProcessFilePath, ParentProcessUser, ParentProcessUserLogonId, ParentProcessIntegrityLevel, ParentProcessSessionId, ParentProcessTokenType, ProcessFilePath, ProcessCommandLine, ProcessId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessUserLinkedLogonId, ProcessIntegrityLevel, ProcessSessionId, ProcessTokenType, ProcessReparented) \ _mcgen_TEMPLATE_FOR_ProcessCreation(&JonMonProvider_Context, &ProcessCreation, EventTime, CreatorThreadId, CreatorProcessId, ParentProcessId, ParentProcessStartKey, ParentProcessFilePath, ParentProcessUser, ParentProcessUserLogonId, ParentProcessIntegrityLevel, ParentProcessSessionId, ParentProcessTokenType, ProcessFilePath, ProcessCommandLine, ProcessId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessUserLinkedLogonId, ProcessIntegrityLevel, ProcessSessionId, ProcessTokenType, ProcessReparented) #define EventWriteProcessCreation_ForContext(pContext, EventTime, CreatorThreadId, CreatorProcessId, ParentProcessId, ParentProcessStartKey, ParentProcessFilePath, ParentProcessUser, ParentProcessUserLogonId, ParentProcessIntegrityLevel, ParentProcessSessionId, ParentProcessTokenType, ProcessFilePath, ProcessCommandLine, ProcessId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessUserLinkedLogonId, ProcessIntegrityLevel, ProcessSessionId, ProcessTokenType, ProcessReparented) \ MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, ProcessCreation) \ ? _mcgen_TEMPLATE_FOR_ProcessCreation(&(pContext)->Context, &ProcessCreation, EventTime, CreatorThreadId, CreatorProcessId, ParentProcessId, ParentProcessStartKey, ParentProcessFilePath, ParentProcessUser, ParentProcessUserLogonId, ParentProcessIntegrityLevel, ParentProcessSessionId, ParentProcessTokenType, ProcessFilePath, ProcessCommandLine, ProcessId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessUserLinkedLogonId, ProcessIntegrityLevel, ProcessSessionId, ProcessTokenType, ProcessReparented) : 0 #define EventWriteProcessCreation_ForContextAssumeEnabled(pContext, EventTime, CreatorThreadId, CreatorProcessId, ParentProcessId, ParentProcessStartKey, ParentProcessFilePath, ParentProcessUser, ParentProcessUserLogonId, ParentProcessIntegrityLevel, ParentProcessSessionId, ParentProcessTokenType, ProcessFilePath, ProcessCommandLine, ProcessId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessUserLinkedLogonId, ProcessIntegrityLevel, ProcessSessionId, ProcessTokenType, ProcessReparented) \ _mcgen_TEMPLATE_FOR_ProcessCreation(&_mcgen_CheckContextType_JonMon(pContext)->Context, &ProcessCreation, EventTime, CreatorThreadId, CreatorProcessId, ParentProcessId, ParentProcessStartKey, ParentProcessFilePath, ParentProcessUser, ParentProcessUserLogonId, ParentProcessIntegrityLevel, ParentProcessSessionId, ParentProcessTokenType, ProcessFilePath, ProcessCommandLine, ProcessId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessUserLinkedLogonId, ProcessIntegrityLevel, ProcessSessionId, ProcessTokenType, ProcessReparented) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_TEMPLATE_FOR_ProcessCreation _mcgen_PASTE2(McTemplateU0yiiiizzqzqqzziizqqzqqt_, MCGEN_EVENTWRITETRANSFER) // // Enablement check macro for event "ProcessTerminate" // #define EventEnabledProcessTerminate() _mcgen_EVENT_BIT_SET(JonMonEnableBits, 0) #define EventEnabledProcessTerminate_ForContext(pContext) _mcgen_EVENT_BIT_SET(_mcgen_CheckContextType_JonMon(pContext)->EnableBits, 0) // // Event write macros for event "ProcessTerminate" // #define EventWriteProcessTerminate(EventTime, SourceProcessId, SourceProcessStartKey, TargetProcessFilePath, TargetProcessId) \ MCGEN_EVENT_ENABLED(ProcessTerminate) \ ? _mcgen_TEMPLATE_FOR_ProcessTerminate(&JonMonProvider_Context, &ProcessTerminate, EventTime, SourceProcessId, SourceProcessStartKey, TargetProcessFilePath, TargetProcessId) : 0 #define EventWriteProcessTerminate_AssumeEnabled(EventTime, SourceProcessId, SourceProcessStartKey, TargetProcessFilePath, TargetProcessId) \ _mcgen_TEMPLATE_FOR_ProcessTerminate(&JonMonProvider_Context, &ProcessTerminate, EventTime, SourceProcessId, SourceProcessStartKey, TargetProcessFilePath, TargetProcessId) #define EventWriteProcessTerminate_ForContext(pContext, EventTime, SourceProcessId, SourceProcessStartKey, TargetProcessFilePath, TargetProcessId) \ MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, ProcessTerminate) \ ? _mcgen_TEMPLATE_FOR_ProcessTerminate(&(pContext)->Context, &ProcessTerminate, EventTime, SourceProcessId, SourceProcessStartKey, TargetProcessFilePath, TargetProcessId) : 0 #define EventWriteProcessTerminate_ForContextAssumeEnabled(pContext, EventTime, SourceProcessId, SourceProcessStartKey, TargetProcessFilePath, TargetProcessId) \ _mcgen_TEMPLATE_FOR_ProcessTerminate(&_mcgen_CheckContextType_JonMon(pContext)->Context, &ProcessTerminate, EventTime, SourceProcessId, SourceProcessStartKey, TargetProcessFilePath, TargetProcessId) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_TEMPLATE_FOR_ProcessTerminate _mcgen_PASTE2(McTemplateU0yiizi_, MCGEN_EVENTWRITETRANSFER) // // Enablement check macro for event "RemoteThreadCreation" // #define EventEnabledRemoteThreadCreation() _mcgen_EVENT_BIT_SET(JonMonEnableBits, 0) #define EventEnabledRemoteThreadCreation_ForContext(pContext) _mcgen_EVENT_BIT_SET(_mcgen_CheckContextType_JonMon(pContext)->EnableBits, 0) // // Event write macros for event "RemoteThreadCreation" // #define EventWriteRemoteThreadCreation(EventTime, SourceProcessId, SourceProcessStartKey, SourceThreadId, SourceProcessFilePath, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceProcessTokenType, TargetProcessFilePath, TargetProcessId, TargetProcessStartKey, TargetThreadId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessUserLinkedLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId) \ MCGEN_EVENT_ENABLED(RemoteThreadCreation) \ ? _mcgen_TEMPLATE_FOR_RemoteThreadCreation(&JonMonProvider_Context, &RemoteThreadCreation, EventTime, SourceProcessId, SourceProcessStartKey, SourceThreadId, SourceProcessFilePath, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceProcessTokenType, TargetProcessFilePath, TargetProcessId, TargetProcessStartKey, TargetThreadId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessUserLinkedLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId) : 0 #define EventWriteRemoteThreadCreation_AssumeEnabled(EventTime, SourceProcessId, SourceProcessStartKey, SourceThreadId, SourceProcessFilePath, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceProcessTokenType, TargetProcessFilePath, TargetProcessId, TargetProcessStartKey, TargetThreadId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessUserLinkedLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId) \ _mcgen_TEMPLATE_FOR_RemoteThreadCreation(&JonMonProvider_Context, &RemoteThreadCreation, EventTime, SourceProcessId, SourceProcessStartKey, SourceThreadId, SourceProcessFilePath, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceProcessTokenType, TargetProcessFilePath, TargetProcessId, TargetProcessStartKey, TargetThreadId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessUserLinkedLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId) #define EventWriteRemoteThreadCreation_ForContext(pContext, EventTime, SourceProcessId, SourceProcessStartKey, SourceThreadId, SourceProcessFilePath, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceProcessTokenType, TargetProcessFilePath, TargetProcessId, TargetProcessStartKey, TargetThreadId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessUserLinkedLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId) \ MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, RemoteThreadCreation) \ ? _mcgen_TEMPLATE_FOR_RemoteThreadCreation(&(pContext)->Context, &RemoteThreadCreation, EventTime, SourceProcessId, SourceProcessStartKey, SourceThreadId, SourceProcessFilePath, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceProcessTokenType, TargetProcessFilePath, TargetProcessId, TargetProcessStartKey, TargetThreadId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessUserLinkedLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId) : 0 #define EventWriteRemoteThreadCreation_ForContextAssumeEnabled(pContext, EventTime, SourceProcessId, SourceProcessStartKey, SourceThreadId, SourceProcessFilePath, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceProcessTokenType, TargetProcessFilePath, TargetProcessId, TargetProcessStartKey, TargetThreadId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessUserLinkedLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId) \ _mcgen_TEMPLATE_FOR_RemoteThreadCreation(&_mcgen_CheckContextType_JonMon(pContext)->Context, &RemoteThreadCreation, EventTime, SourceProcessId, SourceProcessStartKey, SourceThreadId, SourceProcessFilePath, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceProcessTokenType, TargetProcessFilePath, TargetProcessId, TargetProcessStartKey, TargetThreadId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessUserLinkedLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_TEMPLATE_FOR_RemoteThreadCreation _mcgen_PASTE2(McTemplateU0yiiizzqzqqziiizqqzq_, MCGEN_EVENTWRITETRANSFER) // // Enablement check macro for event "ImageLoaded" // #define EventEnabledImageLoaded() _mcgen_EVENT_BIT_SET(JonMonEnableBits, 0) #define EventEnabledImageLoaded_ForContext(pContext) _mcgen_EVENT_BIT_SET(_mcgen_CheckContextType_JonMon(pContext)->EnableBits, 0) // // Event write macros for event "ImageLoaded" // #define EventWriteImageLoaded(EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessUserLinkedLogonId, ProcessIntegrityLevel, ProcessSessionId, ProcessTokenType, ModulePath, SystemModeImage) \ MCGEN_EVENT_ENABLED(ImageLoaded) \ ? _mcgen_TEMPLATE_FOR_ImageLoaded(&JonMonProvider_Context, &ImageLoaded, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessUserLinkedLogonId, ProcessIntegrityLevel, ProcessSessionId, ProcessTokenType, ModulePath, SystemModeImage) : 0 #define EventWriteImageLoaded_AssumeEnabled(EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessUserLinkedLogonId, ProcessIntegrityLevel, ProcessSessionId, ProcessTokenType, ModulePath, SystemModeImage) \ _mcgen_TEMPLATE_FOR_ImageLoaded(&JonMonProvider_Context, &ImageLoaded, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessUserLinkedLogonId, ProcessIntegrityLevel, ProcessSessionId, ProcessTokenType, ModulePath, SystemModeImage) #define EventWriteImageLoaded_ForContext(pContext, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessUserLinkedLogonId, ProcessIntegrityLevel, ProcessSessionId, ProcessTokenType, ModulePath, SystemModeImage) \ MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, ImageLoaded) \ ? _mcgen_TEMPLATE_FOR_ImageLoaded(&(pContext)->Context, &ImageLoaded, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessUserLinkedLogonId, ProcessIntegrityLevel, ProcessSessionId, ProcessTokenType, ModulePath, SystemModeImage) : 0 #define EventWriteImageLoaded_ForContextAssumeEnabled(pContext, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessUserLinkedLogonId, ProcessIntegrityLevel, ProcessSessionId, ProcessTokenType, ModulePath, SystemModeImage) \ _mcgen_TEMPLATE_FOR_ImageLoaded(&_mcgen_CheckContextType_JonMon(pContext)->Context, &ImageLoaded, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessUserLinkedLogonId, ProcessIntegrityLevel, ProcessSessionId, ProcessTokenType, ModulePath, SystemModeImage) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_TEMPLATE_FOR_ImageLoaded _mcgen_PASTE2(McTemplateU0yziiizqqzqqzi_, MCGEN_EVENTWRITETRANSFER) // // Enablement check macro for event "ProcessAccess" // #define EventEnabledProcessAccess() _mcgen_EVENT_BIT_SET(JonMonEnableBits, 0) #define EventEnabledProcessAccess_ForContext(pContext) _mcgen_EVENT_BIT_SET(_mcgen_CheckContextType_JonMon(pContext)->EnableBits, 0) // // Event write macros for event "ProcessAccess" // #define EventWriteProcessAccess(EventTime, SourceProcessId, SourceThreadId, SourceProcessStartKey, SourceProcessFilePath, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceProcessTokenType, ProcessId, ProcessStartKey, ProcessFilePath, ProcessUser, ProcessUserLogonId, ProcessUserLinkedLogonId, ProcessIntegrityLevel, ProcessSessionId, ProcessTokenType, DesiredAccess, OperationType) \ MCGEN_EVENT_ENABLED(ProcessAccess) \ ? _mcgen_TEMPLATE_FOR_ProcessAccess(&JonMonProvider_Context, &ProcessAccess, EventTime, SourceProcessId, SourceThreadId, SourceProcessStartKey, SourceProcessFilePath, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceProcessTokenType, ProcessId, ProcessStartKey, ProcessFilePath, ProcessUser, ProcessUserLogonId, ProcessUserLinkedLogonId, ProcessIntegrityLevel, ProcessSessionId, ProcessTokenType, DesiredAccess, OperationType) : 0 #define EventWriteProcessAccess_AssumeEnabled(EventTime, SourceProcessId, SourceThreadId, SourceProcessStartKey, SourceProcessFilePath, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceProcessTokenType, ProcessId, ProcessStartKey, ProcessFilePath, ProcessUser, ProcessUserLogonId, ProcessUserLinkedLogonId, ProcessIntegrityLevel, ProcessSessionId, ProcessTokenType, DesiredAccess, OperationType) \ _mcgen_TEMPLATE_FOR_ProcessAccess(&JonMonProvider_Context, &ProcessAccess, EventTime, SourceProcessId, SourceThreadId, SourceProcessStartKey, SourceProcessFilePath, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceProcessTokenType, ProcessId, ProcessStartKey, ProcessFilePath, ProcessUser, ProcessUserLogonId, ProcessUserLinkedLogonId, ProcessIntegrityLevel, ProcessSessionId, ProcessTokenType, DesiredAccess, OperationType) #define EventWriteProcessAccess_ForContext(pContext, EventTime, SourceProcessId, SourceThreadId, SourceProcessStartKey, SourceProcessFilePath, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceProcessTokenType, ProcessId, ProcessStartKey, ProcessFilePath, ProcessUser, ProcessUserLogonId, ProcessUserLinkedLogonId, ProcessIntegrityLevel, ProcessSessionId, ProcessTokenType, DesiredAccess, OperationType) \ MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, ProcessAccess) \ ? _mcgen_TEMPLATE_FOR_ProcessAccess(&(pContext)->Context, &ProcessAccess, EventTime, SourceProcessId, SourceThreadId, SourceProcessStartKey, SourceProcessFilePath, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceProcessTokenType, ProcessId, ProcessStartKey, ProcessFilePath, ProcessUser, ProcessUserLogonId, ProcessUserLinkedLogonId, ProcessIntegrityLevel, ProcessSessionId, ProcessTokenType, DesiredAccess, OperationType) : 0 #define EventWriteProcessAccess_ForContextAssumeEnabled(pContext, EventTime, SourceProcessId, SourceThreadId, SourceProcessStartKey, SourceProcessFilePath, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceProcessTokenType, ProcessId, ProcessStartKey, ProcessFilePath, ProcessUser, ProcessUserLogonId, ProcessUserLinkedLogonId, ProcessIntegrityLevel, ProcessSessionId, ProcessTokenType, DesiredAccess, OperationType) \ _mcgen_TEMPLATE_FOR_ProcessAccess(&_mcgen_CheckContextType_JonMon(pContext)->Context, &ProcessAccess, EventTime, SourceProcessId, SourceThreadId, SourceProcessStartKey, SourceProcessFilePath, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceProcessTokenType, ProcessId, ProcessStartKey, ProcessFilePath, ProcessUser, ProcessUserLogonId, ProcessUserLinkedLogonId, ProcessIntegrityLevel, ProcessSessionId, ProcessTokenType, DesiredAccess, OperationType) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_TEMPLATE_FOR_ProcessAccess _mcgen_PASTE2(McTemplateU0yiiizzqzqqiizzqqzqqdd_, MCGEN_EVENTWRITETRANSFER) // // Enablement check macro for event "RegistrySaveKey" // #define EventEnabledRegistrySaveKey() _mcgen_EVENT_BIT_SET(JonMonEnableBits, 0) #define EventEnabledRegistrySaveKey_ForContext(pContext) _mcgen_EVENT_BIT_SET(_mcgen_CheckContextType_JonMon(pContext)->EnableBits, 0) // // Event write macros for event "RegistrySaveKey" // #define EventWriteRegistrySaveKey(EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, RegKeyPath) \ MCGEN_EVENT_ENABLED(RegistrySaveKey) \ ? _mcgen_TEMPLATE_FOR_RegistrySaveKey(&JonMonProvider_Context, &RegistrySaveKey, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, RegKeyPath) : 0 #define EventWriteRegistrySaveKey_AssumeEnabled(EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, RegKeyPath) \ _mcgen_TEMPLATE_FOR_RegistrySaveKey(&JonMonProvider_Context, &RegistrySaveKey, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, RegKeyPath) #define EventWriteRegistrySaveKey_ForContext(pContext, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, RegKeyPath) \ MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, RegistrySaveKey) \ ? _mcgen_TEMPLATE_FOR_RegistrySaveKey(&(pContext)->Context, &RegistrySaveKey, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, RegKeyPath) : 0 #define EventWriteRegistrySaveKey_ForContextAssumeEnabled(pContext, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, RegKeyPath) \ _mcgen_TEMPLATE_FOR_RegistrySaveKey(&_mcgen_CheckContextType_JonMon(pContext)->Context, &RegistrySaveKey, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, RegKeyPath) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_TEMPLATE_FOR_RegistrySaveKey _mcgen_PASTE2(McTemplateU0yziiizqzqz_, MCGEN_EVENTWRITETRANSFER) // // Enablement check macro for event "RegistrySetValueKey" // #define EventEnabledRegistrySetValueKey() _mcgen_EVENT_BIT_SET(JonMonEnableBits, 0) #define EventEnabledRegistrySetValueKey_ForContext(pContext) _mcgen_EVENT_BIT_SET(_mcgen_CheckContextType_JonMon(pContext)->EnableBits, 0) // // Event write macros for event "RegistrySetValueKey" // #define EventWriteRegistrySetValueKey(EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, RegKeyPath, DataType, Data, ValueName) \ MCGEN_EVENT_ENABLED(RegistrySetValueKey) \ ? _mcgen_TEMPLATE_FOR_RegistrySetValueKey(&JonMonProvider_Context, &RegistrySetValueKey, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, RegKeyPath, DataType, Data, ValueName) : 0 #define EventWriteRegistrySetValueKey_AssumeEnabled(EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, RegKeyPath, DataType, Data, ValueName) \ _mcgen_TEMPLATE_FOR_RegistrySetValueKey(&JonMonProvider_Context, &RegistrySetValueKey, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, RegKeyPath, DataType, Data, ValueName) #define EventWriteRegistrySetValueKey_ForContext(pContext, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, RegKeyPath, DataType, Data, ValueName) \ MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, RegistrySetValueKey) \ ? _mcgen_TEMPLATE_FOR_RegistrySetValueKey(&(pContext)->Context, &RegistrySetValueKey, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, RegKeyPath, DataType, Data, ValueName) : 0 #define EventWriteRegistrySetValueKey_ForContextAssumeEnabled(pContext, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, RegKeyPath, DataType, Data, ValueName) \ _mcgen_TEMPLATE_FOR_RegistrySetValueKey(&_mcgen_CheckContextType_JonMon(pContext)->Context, &RegistrySetValueKey, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, RegKeyPath, DataType, Data, ValueName) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_TEMPLATE_FOR_RegistrySetValueKey _mcgen_PASTE2(McTemplateU0yziiizqzqzdzz_, MCGEN_EVENTWRITETRANSFER) // // Enablement check macro for event "RegistryCreateKey" // #define EventEnabledRegistryCreateKey() _mcgen_EVENT_BIT_SET(JonMonEnableBits, 0) #define EventEnabledRegistryCreateKey_ForContext(pContext) _mcgen_EVENT_BIT_SET(_mcgen_CheckContextType_JonMon(pContext)->EnableBits, 0) // // Event write macros for event "RegistryCreateKey" // #define EventWriteRegistryCreateKey(EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, RegKeyPath) \ MCGEN_EVENT_ENABLED(RegistryCreateKey) \ ? _mcgen_TEMPLATE_FOR_RegistryCreateKey(&JonMonProvider_Context, &RegistryCreateKey, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, RegKeyPath) : 0 #define EventWriteRegistryCreateKey_AssumeEnabled(EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, RegKeyPath) \ _mcgen_TEMPLATE_FOR_RegistryCreateKey(&JonMonProvider_Context, &RegistryCreateKey, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, RegKeyPath) #define EventWriteRegistryCreateKey_ForContext(pContext, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, RegKeyPath) \ MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, RegistryCreateKey) \ ? _mcgen_TEMPLATE_FOR_RegistryCreateKey(&(pContext)->Context, &RegistryCreateKey, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, RegKeyPath) : 0 #define EventWriteRegistryCreateKey_ForContextAssumeEnabled(pContext, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, RegKeyPath) \ _mcgen_TEMPLATE_FOR_RegistryCreateKey(&_mcgen_CheckContextType_JonMon(pContext)->Context, &RegistryCreateKey, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, RegKeyPath) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_TEMPLATE_FOR_RegistryCreateKey _mcgen_PASTE2(McTemplateU0yziiizqzqz_, MCGEN_EVENTWRITETRANSFER) // // Enablement check macro for event "FileCreation" // #define EventEnabledFileCreation() _mcgen_EVENT_BIT_SET(JonMonEnableBits, 0) #define EventEnabledFileCreation_ForContext(pContext) _mcgen_EVENT_BIT_SET(_mcgen_CheckContextType_JonMon(pContext)->EnableBits, 0) // // Event write macros for event "FileCreation" // #define EventWriteFileCreation(EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName) \ MCGEN_EVENT_ENABLED(FileCreation) \ ? _mcgen_TEMPLATE_FOR_FileCreation(&JonMonProvider_Context, &FileCreation, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName) : 0 #define EventWriteFileCreation_AssumeEnabled(EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName) \ _mcgen_TEMPLATE_FOR_FileCreation(&JonMonProvider_Context, &FileCreation, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName) #define EventWriteFileCreation_ForContext(pContext, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName) \ MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, FileCreation) \ ? _mcgen_TEMPLATE_FOR_FileCreation(&(pContext)->Context, &FileCreation, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName) : 0 #define EventWriteFileCreation_ForContextAssumeEnabled(pContext, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName) \ _mcgen_TEMPLATE_FOR_FileCreation(&_mcgen_CheckContextType_JonMon(pContext)->Context, &FileCreation, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_TEMPLATE_FOR_FileCreation _mcgen_PASTE2(McTemplateU0yziiizqzqz_, MCGEN_EVENTWRITETRANSFER) // // Enablement check macro for event "NamedPipeCreation" // #define EventEnabledNamedPipeCreation() _mcgen_EVENT_BIT_SET(JonMonEnableBits, 0) #define EventEnabledNamedPipeCreation_ForContext(pContext) _mcgen_EVENT_BIT_SET(_mcgen_CheckContextType_JonMon(pContext)->EnableBits, 0) // // Event write macros for event "NamedPipeCreation" // #define EventWriteNamedPipeCreation(EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) \ MCGEN_EVENT_ENABLED(NamedPipeCreation) \ ? _mcgen_TEMPLATE_FOR_NamedPipeCreation(&JonMonProvider_Context, &NamedPipeCreation, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) : 0 #define EventWriteNamedPipeCreation_AssumeEnabled(EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) \ _mcgen_TEMPLATE_FOR_NamedPipeCreation(&JonMonProvider_Context, &NamedPipeCreation, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) #define EventWriteNamedPipeCreation_ForContext(pContext, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) \ MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, NamedPipeCreation) \ ? _mcgen_TEMPLATE_FOR_NamedPipeCreation(&(pContext)->Context, &NamedPipeCreation, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) : 0 #define EventWriteNamedPipeCreation_ForContextAssumeEnabled(pContext, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) \ _mcgen_TEMPLATE_FOR_NamedPipeCreation(&_mcgen_CheckContextType_JonMon(pContext)->Context, &NamedPipeCreation, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_TEMPLATE_FOR_NamedPipeCreation _mcgen_PASTE2(McTemplateU0yziiizqzqzd_, MCGEN_EVENTWRITETRANSFER) // // Enablement check macro for event "NamedPipeConnection" // #define EventEnabledNamedPipeConnection() _mcgen_EVENT_BIT_SET(JonMonEnableBits, 0) #define EventEnabledNamedPipeConnection_ForContext(pContext) _mcgen_EVENT_BIT_SET(_mcgen_CheckContextType_JonMon(pContext)->EnableBits, 0) // // Event write macros for event "NamedPipeConnection" // #define EventWriteNamedPipeConnection(EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) \ MCGEN_EVENT_ENABLED(NamedPipeConnection) \ ? _mcgen_TEMPLATE_FOR_NamedPipeConnection(&JonMonProvider_Context, &NamedPipeConnection, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) : 0 #define EventWriteNamedPipeConnection_AssumeEnabled(EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) \ _mcgen_TEMPLATE_FOR_NamedPipeConnection(&JonMonProvider_Context, &NamedPipeConnection, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) #define EventWriteNamedPipeConnection_ForContext(pContext, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) \ MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, NamedPipeConnection) \ ? _mcgen_TEMPLATE_FOR_NamedPipeConnection(&(pContext)->Context, &NamedPipeConnection, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) : 0 #define EventWriteNamedPipeConnection_ForContextAssumeEnabled(pContext, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) \ _mcgen_TEMPLATE_FOR_NamedPipeConnection(&_mcgen_CheckContextType_JonMon(pContext)->Context, &NamedPipeConnection, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_TEMPLATE_FOR_NamedPipeConnection _mcgen_PASTE2(McTemplateU0yziiizqzqzd_, MCGEN_EVENTWRITETRANSFER) // // Enablement check macro for event "MailslotCreation" // #define EventEnabledMailslotCreation() _mcgen_EVENT_BIT_SET(JonMonEnableBits, 0) #define EventEnabledMailslotCreation_ForContext(pContext) _mcgen_EVENT_BIT_SET(_mcgen_CheckContextType_JonMon(pContext)->EnableBits, 0) // // Event write macros for event "MailslotCreation" // #define EventWriteMailslotCreation(EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) \ MCGEN_EVENT_ENABLED(MailslotCreation) \ ? _mcgen_TEMPLATE_FOR_MailslotCreation(&JonMonProvider_Context, &MailslotCreation, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) : 0 #define EventWriteMailslotCreation_AssumeEnabled(EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) \ _mcgen_TEMPLATE_FOR_MailslotCreation(&JonMonProvider_Context, &MailslotCreation, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) #define EventWriteMailslotCreation_ForContext(pContext, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) \ MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, MailslotCreation) \ ? _mcgen_TEMPLATE_FOR_MailslotCreation(&(pContext)->Context, &MailslotCreation, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) : 0 #define EventWriteMailslotCreation_ForContextAssumeEnabled(pContext, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) \ _mcgen_TEMPLATE_FOR_MailslotCreation(&_mcgen_CheckContextType_JonMon(pContext)->Context, &MailslotCreation, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_TEMPLATE_FOR_MailslotCreation _mcgen_PASTE2(McTemplateU0yziiizqzqzd_, MCGEN_EVENTWRITETRANSFER) // // Enablement check macro for event "MailslotConnection" // #define EventEnabledMailslotConnection() _mcgen_EVENT_BIT_SET(JonMonEnableBits, 0) #define EventEnabledMailslotConnection_ForContext(pContext) _mcgen_EVENT_BIT_SET(_mcgen_CheckContextType_JonMon(pContext)->EnableBits, 0) // // Event write macros for event "MailslotConnection" // #define EventWriteMailslotConnection(EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) \ MCGEN_EVENT_ENABLED(MailslotConnection) \ ? _mcgen_TEMPLATE_FOR_MailslotConnection(&JonMonProvider_Context, &MailslotConnection, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) : 0 #define EventWriteMailslotConnection_AssumeEnabled(EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) \ _mcgen_TEMPLATE_FOR_MailslotConnection(&JonMonProvider_Context, &MailslotConnection, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) #define EventWriteMailslotConnection_ForContext(pContext, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) \ MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, MailslotConnection) \ ? _mcgen_TEMPLATE_FOR_MailslotConnection(&(pContext)->Context, &MailslotConnection, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) : 0 #define EventWriteMailslotConnection_ForContextAssumeEnabled(pContext, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) \ _mcgen_TEMPLATE_FOR_MailslotConnection(&_mcgen_CheckContextType_JonMon(pContext)->Context, &MailslotConnection, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName, RequestedRights) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_TEMPLATE_FOR_MailslotConnection _mcgen_PASTE2(McTemplateU0yziiizqzqzd_, MCGEN_EVENTWRITETRANSFER) // // Enablement check macro for event "RemoteFileConnection" // #define EventEnabledRemoteFileConnection() _mcgen_EVENT_BIT_SET(JonMonEnableBits, 0) #define EventEnabledRemoteFileConnection_ForContext(pContext) _mcgen_EVENT_BIT_SET(_mcgen_CheckContextType_JonMon(pContext)->EnableBits, 0) // // Event write macros for event "RemoteFileConnection" // #define EventWriteRemoteFileConnection(EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName) \ MCGEN_EVENT_ENABLED(RemoteFileConnection) \ ? _mcgen_TEMPLATE_FOR_RemoteFileConnection(&JonMonProvider_Context, &RemoteFileConnection, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName) : 0 #define EventWriteRemoteFileConnection_AssumeEnabled(EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName) \ _mcgen_TEMPLATE_FOR_RemoteFileConnection(&JonMonProvider_Context, &RemoteFileConnection, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName) #define EventWriteRemoteFileConnection_ForContext(pContext, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName) \ MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, RemoteFileConnection) \ ? _mcgen_TEMPLATE_FOR_RemoteFileConnection(&(pContext)->Context, &RemoteFileConnection, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName) : 0 #define EventWriteRemoteFileConnection_ForContextAssumeEnabled(pContext, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName) \ _mcgen_TEMPLATE_FOR_RemoteFileConnection(&_mcgen_CheckContextType_JonMon(pContext)->Context, &RemoteFileConnection, EventTime, ProcessFilePath, ProcessId, ProcessThreadId, ProcessStartKey, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, FileName) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_TEMPLATE_FOR_RemoteFileConnection _mcgen_PASTE2(McTemplateU0yziiizqzqz_, MCGEN_EVENTWRITETRANSFER) // // Enablement check macro for event "DotNetLoad" // #define EventEnabledDotNetLoad() _mcgen_EVENT_BIT_SET(JonMonEnableBits, 0) #define EventEnabledDotNetLoad_ForContext(pContext) _mcgen_EVENT_BIT_SET(_mcgen_CheckContextType_JonMon(pContext)->EnableBits, 0) // // Event write macros for event "DotNetLoad" // #define EventWriteDotNetLoad(EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, AssemblyName, ClrInstanceID) \ MCGEN_EVENT_ENABLED(DotNetLoad) \ ? _mcgen_TEMPLATE_FOR_DotNetLoad(&JonMonProvider_Context, &DotNetLoad, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, AssemblyName, ClrInstanceID) : 0 #define EventWriteDotNetLoad_AssumeEnabled(EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, AssemblyName, ClrInstanceID) \ _mcgen_TEMPLATE_FOR_DotNetLoad(&JonMonProvider_Context, &DotNetLoad, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, AssemblyName, ClrInstanceID) #define EventWriteDotNetLoad_ForContext(pContext, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, AssemblyName, ClrInstanceID) \ MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, DotNetLoad) \ ? _mcgen_TEMPLATE_FOR_DotNetLoad(&(pContext)->Context, &DotNetLoad, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, AssemblyName, ClrInstanceID) : 0 #define EventWriteDotNetLoad_ForContextAssumeEnabled(pContext, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, AssemblyName, ClrInstanceID) \ _mcgen_TEMPLATE_FOR_DotNetLoad(&_mcgen_CheckContextType_JonMon(pContext)->Context, &DotNetLoad, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, AssemblyName, ClrInstanceID) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_TEMPLATE_FOR_DotNetLoad _mcgen_PASTE2(McTemplateU0yzizqzqzh_, MCGEN_EVENTWRITETRANSFER) // // Enablement check macro for event "WMIEventFilter" // #define EventEnabledWMIEventFilter() _mcgen_EVENT_BIT_SET(JonMonEnableBits, 0) #define EventEnabledWMIEventFilter_ForContext(pContext) _mcgen_EVENT_BIT_SET(_mcgen_CheckContextType_JonMon(pContext)->EnableBits, 0) // // Event write macros for event "WMIEventFilter" // #define EventWriteWMIEventFilter(EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, Namespace, ESS, Consumer, PossibleCause) \ MCGEN_EVENT_ENABLED(WMIEventFilter) \ ? _mcgen_TEMPLATE_FOR_WMIEventFilter(&JonMonProvider_Context, &WMIEventFilter, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, Namespace, ESS, Consumer, PossibleCause) : 0 #define EventWriteWMIEventFilter_AssumeEnabled(EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, Namespace, ESS, Consumer, PossibleCause) \ _mcgen_TEMPLATE_FOR_WMIEventFilter(&JonMonProvider_Context, &WMIEventFilter, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, Namespace, ESS, Consumer, PossibleCause) #define EventWriteWMIEventFilter_ForContext(pContext, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, Namespace, ESS, Consumer, PossibleCause) \ MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, WMIEventFilter) \ ? _mcgen_TEMPLATE_FOR_WMIEventFilter(&(pContext)->Context, &WMIEventFilter, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, Namespace, ESS, Consumer, PossibleCause) : 0 #define EventWriteWMIEventFilter_ForContextAssumeEnabled(pContext, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, Namespace, ESS, Consumer, PossibleCause) \ _mcgen_TEMPLATE_FOR_WMIEventFilter(&_mcgen_CheckContextType_JonMon(pContext)->Context, &WMIEventFilter, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, Namespace, ESS, Consumer, PossibleCause) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_TEMPLATE_FOR_WMIEventFilter _mcgen_PASTE2(McTemplateU0yzizqzqzzzz_, MCGEN_EVENTWRITETRANSFER) // // Enablement check macro for event "RPCClient" // #define EventEnabledRPCClient() _mcgen_EVENT_BIT_SET(JonMonEnableBits, 0) #define EventEnabledRPCClient_ForContext(pContext) _mcgen_EVENT_BIT_SET(_mcgen_CheckContextType_JonMon(pContext)->EnableBits, 0) // // Event write macros for event "RPCClient" // #define EventWriteRPCClient(EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, InterfaceUUID, ProcNum, Protocol, NetworkAddress, Endpoint, InterfaceString, MethodString, CallStack) \ MCGEN_EVENT_ENABLED(RPCClient) \ ? _mcgen_TEMPLATE_FOR_RPCClient(&JonMonProvider_Context, &RPCClient, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, InterfaceUUID, ProcNum, Protocol, NetworkAddress, Endpoint, InterfaceString, MethodString, CallStack) : 0 #define EventWriteRPCClient_AssumeEnabled(EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, InterfaceUUID, ProcNum, Protocol, NetworkAddress, Endpoint, InterfaceString, MethodString, CallStack) \ _mcgen_TEMPLATE_FOR_RPCClient(&JonMonProvider_Context, &RPCClient, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, InterfaceUUID, ProcNum, Protocol, NetworkAddress, Endpoint, InterfaceString, MethodString, CallStack) #define EventWriteRPCClient_ForContext(pContext, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, InterfaceUUID, ProcNum, Protocol, NetworkAddress, Endpoint, InterfaceString, MethodString, CallStack) \ MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, RPCClient) \ ? _mcgen_TEMPLATE_FOR_RPCClient(&(pContext)->Context, &RPCClient, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, InterfaceUUID, ProcNum, Protocol, NetworkAddress, Endpoint, InterfaceString, MethodString, CallStack) : 0 #define EventWriteRPCClient_ForContextAssumeEnabled(pContext, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, InterfaceUUID, ProcNum, Protocol, NetworkAddress, Endpoint, InterfaceString, MethodString, CallStack) \ _mcgen_TEMPLATE_FOR_RPCClient(&_mcgen_CheckContextType_JonMon(pContext)->Context, &RPCClient, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, InterfaceUUID, ProcNum, Protocol, NetworkAddress, Endpoint, InterfaceString, MethodString, CallStack) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_TEMPLATE_FOR_RPCClient _mcgen_PASTE2(McTemplateU0yzizqzqzqqzzzzz_, MCGEN_EVENTWRITETRANSFER) // // Enablement check macro for event "RPCServer" // #define EventEnabledRPCServer() _mcgen_EVENT_BIT_SET(JonMonEnableBits, 0) #define EventEnabledRPCServer_ForContext(pContext) _mcgen_EVENT_BIT_SET(_mcgen_CheckContextType_JonMon(pContext)->EnableBits, 0) // // Event write macros for event "RPCServer" // #define EventWriteRPCServer(EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, InterfaceUUID, ProcNum, Protocol, NetworkAddress, Endpoint, InterfaceString, MethodString, CallStack) \ MCGEN_EVENT_ENABLED(RPCServer) \ ? _mcgen_TEMPLATE_FOR_RPCServer(&JonMonProvider_Context, &RPCServer, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, InterfaceUUID, ProcNum, Protocol, NetworkAddress, Endpoint, InterfaceString, MethodString, CallStack) : 0 #define EventWriteRPCServer_AssumeEnabled(EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, InterfaceUUID, ProcNum, Protocol, NetworkAddress, Endpoint, InterfaceString, MethodString, CallStack) \ _mcgen_TEMPLATE_FOR_RPCServer(&JonMonProvider_Context, &RPCServer, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, InterfaceUUID, ProcNum, Protocol, NetworkAddress, Endpoint, InterfaceString, MethodString, CallStack) #define EventWriteRPCServer_ForContext(pContext, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, InterfaceUUID, ProcNum, Protocol, NetworkAddress, Endpoint, InterfaceString, MethodString, CallStack) \ MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, RPCServer) \ ? _mcgen_TEMPLATE_FOR_RPCServer(&(pContext)->Context, &RPCServer, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, InterfaceUUID, ProcNum, Protocol, NetworkAddress, Endpoint, InterfaceString, MethodString, CallStack) : 0 #define EventWriteRPCServer_ForContextAssumeEnabled(pContext, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, InterfaceUUID, ProcNum, Protocol, NetworkAddress, Endpoint, InterfaceString, MethodString, CallStack) \ _mcgen_TEMPLATE_FOR_RPCServer(&_mcgen_CheckContextType_JonMon(pContext)->Context, &RPCServer, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, InterfaceUUID, ProcNum, Protocol, NetworkAddress, Endpoint, InterfaceString, MethodString, CallStack) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_TEMPLATE_FOR_RPCServer _mcgen_PASTE2(McTemplateU0yzizqzqzqqzzzzz_, MCGEN_EVENTWRITETRANSFER) // // Enablement check macro for event "DPAPIUnprotect" // #define EventEnabledDPAPIUnprotect() _mcgen_EVENT_BIT_SET(JonMonEnableBits, 0) #define EventEnabledDPAPIUnprotect_ForContext(pContext) _mcgen_EVENT_BIT_SET(_mcgen_CheckContextType_JonMon(pContext)->EnableBits, 0) // // Event write macros for event "DPAPIUnprotect" // #define EventWriteDPAPIUnprotect(EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, OperationType, DataDescription, Flags, ProtectionFlags) \ MCGEN_EVENT_ENABLED(DPAPIUnprotect) \ ? _mcgen_TEMPLATE_FOR_DPAPIUnprotect(&JonMonProvider_Context, &DPAPIUnprotect, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, OperationType, DataDescription, Flags, ProtectionFlags) : 0 #define EventWriteDPAPIUnprotect_AssumeEnabled(EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, OperationType, DataDescription, Flags, ProtectionFlags) \ _mcgen_TEMPLATE_FOR_DPAPIUnprotect(&JonMonProvider_Context, &DPAPIUnprotect, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, OperationType, DataDescription, Flags, ProtectionFlags) #define EventWriteDPAPIUnprotect_ForContext(pContext, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, OperationType, DataDescription, Flags, ProtectionFlags) \ MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, DPAPIUnprotect) \ ? _mcgen_TEMPLATE_FOR_DPAPIUnprotect(&(pContext)->Context, &DPAPIUnprotect, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, OperationType, DataDescription, Flags, ProtectionFlags) : 0 #define EventWriteDPAPIUnprotect_ForContextAssumeEnabled(pContext, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, OperationType, DataDescription, Flags, ProtectionFlags) \ _mcgen_TEMPLATE_FOR_DPAPIUnprotect(&_mcgen_CheckContextType_JonMon(pContext)->Context, &DPAPIUnprotect, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, OperationType, DataDescription, Flags, ProtectionFlags) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_TEMPLATE_FOR_DPAPIUnprotect _mcgen_PASTE2(McTemplateU0yzizqzqzzqq_, MCGEN_EVENTWRITETRANSFER) // // Enablement check macro for event "NetworkConnection" // #define EventEnabledNetworkConnection() _mcgen_EVENT_BIT_SET(JonMonEnableBits, 0) #define EventEnabledNetworkConnection_ForContext(pContext) _mcgen_EVENT_BIT_SET(_mcgen_CheckContextType_JonMon(pContext)->EnableBits, 0) // // Event write macros for event "NetworkConnection" // #define EventWriteNetworkConnection(EventTime, ProcessId, ProcessFilePath, SrcIpAddressIpv4, DestIpAddressIpv4, SrcPort, DestPort, Initiated, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId) \ MCGEN_EVENT_ENABLED(NetworkConnection) \ ? _mcgen_TEMPLATE_FOR_NetworkConnection(&JonMonProvider_Context, &NetworkConnection, EventTime, ProcessId, ProcessFilePath, SrcIpAddressIpv4, DestIpAddressIpv4, SrcPort, DestPort, Initiated, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId) : 0 #define EventWriteNetworkConnection_AssumeEnabled(EventTime, ProcessId, ProcessFilePath, SrcIpAddressIpv4, DestIpAddressIpv4, SrcPort, DestPort, Initiated, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId) \ _mcgen_TEMPLATE_FOR_NetworkConnection(&JonMonProvider_Context, &NetworkConnection, EventTime, ProcessId, ProcessFilePath, SrcIpAddressIpv4, DestIpAddressIpv4, SrcPort, DestPort, Initiated, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId) #define EventWriteNetworkConnection_ForContext(pContext, EventTime, ProcessId, ProcessFilePath, SrcIpAddressIpv4, DestIpAddressIpv4, SrcPort, DestPort, Initiated, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId) \ MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, NetworkConnection) \ ? _mcgen_TEMPLATE_FOR_NetworkConnection(&(pContext)->Context, &NetworkConnection, EventTime, ProcessId, ProcessFilePath, SrcIpAddressIpv4, DestIpAddressIpv4, SrcPort, DestPort, Initiated, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId) : 0 #define EventWriteNetworkConnection_ForContextAssumeEnabled(pContext, EventTime, ProcessId, ProcessFilePath, SrcIpAddressIpv4, DestIpAddressIpv4, SrcPort, DestPort, Initiated, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId) \ _mcgen_TEMPLATE_FOR_NetworkConnection(&_mcgen_CheckContextType_JonMon(pContext)->Context, &NetworkConnection, EventTime, ProcessId, ProcessFilePath, SrcIpAddressIpv4, DestIpAddressIpv4, SrcPort, DestPort, Initiated, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_TEMPLATE_FOR_NetworkConnection _mcgen_PASTE2(McTemplateU0yqzzzhhtzqzq_, MCGEN_EVENTWRITETRANSFER) // // Enablement check macro for event "AMSI" // #define EventEnabledAMSI() _mcgen_EVENT_BIT_SET(JonMonEnableBits, 0) #define EventEnabledAMSI_ForContext(pContext) _mcgen_EVENT_BIT_SET(_mcgen_CheckContextType_JonMon(pContext)->EnableBits, 0) // // Event write macros for event "AMSI" // #define EventWriteAMSI(EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, AppName, ContentName, ScanStatus, ScanResult, ContentSize, Content, DecodedContent) \ MCGEN_EVENT_ENABLED(AMSI) \ ? _mcgen_TEMPLATE_FOR_AMSI(&JonMonProvider_Context, &AMSI, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, AppName, ContentName, ScanStatus, ScanResult, ContentSize, Content, DecodedContent) : 0 #define EventWriteAMSI_AssumeEnabled(EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, AppName, ContentName, ScanStatus, ScanResult, ContentSize, Content, DecodedContent) \ _mcgen_TEMPLATE_FOR_AMSI(&JonMonProvider_Context, &AMSI, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, AppName, ContentName, ScanStatus, ScanResult, ContentSize, Content, DecodedContent) #define EventWriteAMSI_ForContext(pContext, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, AppName, ContentName, ScanStatus, ScanResult, ContentSize, Content, DecodedContent) \ MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, AMSI) \ ? _mcgen_TEMPLATE_FOR_AMSI(&(pContext)->Context, &AMSI, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, AppName, ContentName, ScanStatus, ScanResult, ContentSize, Content, DecodedContent) : 0 #define EventWriteAMSI_ForContextAssumeEnabled(pContext, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, AppName, ContentName, ScanStatus, ScanResult, ContentSize, Content, DecodedContent) \ _mcgen_TEMPLATE_FOR_AMSI(&_mcgen_CheckContextType_JonMon(pContext)->Context, &AMSI, EventTime, ProcessFilePath, ProcessId, ProcessUser, ProcessUserLogonId, ProcessIntegrityLevel, ProcessSessionId, AppName, ContentName, ScanStatus, ScanResult, ContentSize, Content, DecodedContent) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_TEMPLATE_FOR_AMSI _mcgen_PASTE2(McTemplateU0yzizqzqzzuqqbr11z_, MCGEN_EVENTWRITETRANSFER) // // Enablement check macro for event "RemoteReadProcessMemory" // #define EventEnabledRemoteReadProcessMemory() _mcgen_EVENT_BIT_SET(JonMonEnableBits, 0) #define EventEnabledRemoteReadProcessMemory_ForContext(pContext) _mcgen_EVENT_BIT_SET(_mcgen_CheckContextType_JonMon(pContext)->EnableBits, 0) // // Event write macros for event "RemoteReadProcessMemory" // #define EventWriteRemoteReadProcessMemory(EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey) \ MCGEN_EVENT_ENABLED(RemoteReadProcessMemory) \ ? _mcgen_TEMPLATE_FOR_RemoteReadProcessMemory(&JonMonProvider_Context, &RemoteReadProcessMemory, EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey) : 0 #define EventWriteRemoteReadProcessMemory_AssumeEnabled(EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey) \ _mcgen_TEMPLATE_FOR_RemoteReadProcessMemory(&JonMonProvider_Context, &RemoteReadProcessMemory, EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey) #define EventWriteRemoteReadProcessMemory_ForContext(pContext, EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey) \ MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, RemoteReadProcessMemory) \ ? _mcgen_TEMPLATE_FOR_RemoteReadProcessMemory(&(pContext)->Context, &RemoteReadProcessMemory, EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey) : 0 #define EventWriteRemoteReadProcessMemory_ForContextAssumeEnabled(pContext, EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey) \ _mcgen_TEMPLATE_FOR_RemoteReadProcessMemory(&_mcgen_CheckContextType_JonMon(pContext)->Context, &RemoteReadProcessMemory, EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_TEMPLATE_FOR_RemoteReadProcessMemory _mcgen_PASTE2(McTemplateU0yzizqzqqzizqzqxx_, MCGEN_EVENTWRITETRANSFER) // // Enablement check macro for event "RemoteWriteProcessMemory" // #define EventEnabledRemoteWriteProcessMemory() _mcgen_EVENT_BIT_SET(JonMonEnableBits, 0) #define EventEnabledRemoteWriteProcessMemory_ForContext(pContext) _mcgen_EVENT_BIT_SET(_mcgen_CheckContextType_JonMon(pContext)->EnableBits, 0) // // Event write macros for event "RemoteWriteProcessMemory" // #define EventWriteRemoteWriteProcessMemory(EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey) \ MCGEN_EVENT_ENABLED(RemoteWriteProcessMemory) \ ? _mcgen_TEMPLATE_FOR_RemoteWriteProcessMemory(&JonMonProvider_Context, &RemoteWriteProcessMemory, EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey) : 0 #define EventWriteRemoteWriteProcessMemory_AssumeEnabled(EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey) \ _mcgen_TEMPLATE_FOR_RemoteWriteProcessMemory(&JonMonProvider_Context, &RemoteWriteProcessMemory, EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey) #define EventWriteRemoteWriteProcessMemory_ForContext(pContext, EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey) \ MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, RemoteWriteProcessMemory) \ ? _mcgen_TEMPLATE_FOR_RemoteWriteProcessMemory(&(pContext)->Context, &RemoteWriteProcessMemory, EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey) : 0 #define EventWriteRemoteWriteProcessMemory_ForContextAssumeEnabled(pContext, EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey) \ _mcgen_TEMPLATE_FOR_RemoteWriteProcessMemory(&_mcgen_CheckContextType_JonMon(pContext)->Context, &RemoteWriteProcessMemory, EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_TEMPLATE_FOR_RemoteWriteProcessMemory _mcgen_PASTE2(McTemplateU0yzizqzqqzizqzqxx_, MCGEN_EVENTWRITETRANSFER) // // Enablement check macro for event "RemoteVirtualAllocation" // #define EventEnabledRemoteVirtualAllocation() _mcgen_EVENT_BIT_SET(JonMonEnableBits, 0) #define EventEnabledRemoteVirtualAllocation_ForContext(pContext) _mcgen_EVENT_BIT_SET(_mcgen_CheckContextType_JonMon(pContext)->EnableBits, 0) // // Event write macros for event "RemoteVirtualAllocation" // #define EventWriteRemoteVirtualAllocation(EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey, BaseAddress) \ MCGEN_EVENT_ENABLED(RemoteVirtualAllocation) \ ? _mcgen_TEMPLATE_FOR_RemoteVirtualAllocation(&JonMonProvider_Context, &RemoteVirtualAllocation, EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey, BaseAddress) : 0 #define EventWriteRemoteVirtualAllocation_AssumeEnabled(EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey, BaseAddress) \ _mcgen_TEMPLATE_FOR_RemoteVirtualAllocation(&JonMonProvider_Context, &RemoteVirtualAllocation, EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey, BaseAddress) #define EventWriteRemoteVirtualAllocation_ForContext(pContext, EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey, BaseAddress) \ MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, RemoteVirtualAllocation) \ ? _mcgen_TEMPLATE_FOR_RemoteVirtualAllocation(&(pContext)->Context, &RemoteVirtualAllocation, EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey, BaseAddress) : 0 #define EventWriteRemoteVirtualAllocation_ForContextAssumeEnabled(pContext, EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey, BaseAddress) \ _mcgen_TEMPLATE_FOR_RemoteVirtualAllocation(&_mcgen_CheckContextType_JonMon(pContext)->Context, &RemoteVirtualAllocation, EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey, BaseAddress) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_TEMPLATE_FOR_RemoteVirtualAllocation _mcgen_PASTE2(McTemplateU0yzizqzqqzizqzqxxx_, MCGEN_EVENTWRITETRANSFER) // // Enablement check macro for event "RemoteQueueUserAPC" // #define EventEnabledRemoteQueueUserAPC() _mcgen_EVENT_BIT_SET(JonMonEnableBits, 0) #define EventEnabledRemoteQueueUserAPC_ForContext(pContext) _mcgen_EVENT_BIT_SET(_mcgen_CheckContextType_JonMon(pContext)->EnableBits, 0) // // Event write macros for event "RemoteQueueUserAPC" // #define EventWriteRemoteQueueUserAPC(EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey, ApcRoutine, ApcArgument1, ApcArgument2, ApcArgument3) \ MCGEN_EVENT_ENABLED(RemoteQueueUserAPC) \ ? _mcgen_TEMPLATE_FOR_RemoteQueueUserAPC(&JonMonProvider_Context, &RemoteQueueUserAPC, EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey, ApcRoutine, ApcArgument1, ApcArgument2, ApcArgument3) : 0 #define EventWriteRemoteQueueUserAPC_AssumeEnabled(EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey, ApcRoutine, ApcArgument1, ApcArgument2, ApcArgument3) \ _mcgen_TEMPLATE_FOR_RemoteQueueUserAPC(&JonMonProvider_Context, &RemoteQueueUserAPC, EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey, ApcRoutine, ApcArgument1, ApcArgument2, ApcArgument3) #define EventWriteRemoteQueueUserAPC_ForContext(pContext, EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey, ApcRoutine, ApcArgument1, ApcArgument2, ApcArgument3) \ MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, RemoteQueueUserAPC) \ ? _mcgen_TEMPLATE_FOR_RemoteQueueUserAPC(&(pContext)->Context, &RemoteQueueUserAPC, EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey, ApcRoutine, ApcArgument1, ApcArgument2, ApcArgument3) : 0 #define EventWriteRemoteQueueUserAPC_ForContextAssumeEnabled(pContext, EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey, ApcRoutine, ApcArgument1, ApcArgument2, ApcArgument3) \ _mcgen_TEMPLATE_FOR_RemoteQueueUserAPC(&_mcgen_CheckContextType_JonMon(pContext)->Context, &RemoteQueueUserAPC, EventTime_, SourceProcessFilePath, SourceProcessId, SourceProcessUser, SourceProcessUserLogonId, SourceProcessIntegrityLevel, SourceProcessSessionId, SourceThreadId, TargetProcessFilePath, TargetProcessId, TargetProcessUser, TargetProcessUserLogonId, TargetProcessIntegrityLevel, TargetProcessSessionId, SourceProcessStartKey, TargetProcessStartKey, ApcRoutine, ApcArgument1, ApcArgument2, ApcArgument3) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_TEMPLATE_FOR_RemoteQueueUserAPC _mcgen_PASTE2(McTemplateU0yzizqzqqzizqzqxxxxxx_, MCGEN_EVENTWRITETRANSFER) // // Enablement check macro for event "QueryTokenImpersonation" // #define EventEnabledQueryTokenImpersonation() _mcgen_EVENT_BIT_SET(JonMonEnableBits, 0) #define EventEnabledQueryTokenImpersonation_ForContext(pContext) _mcgen_EVENT_BIT_SET(_mcgen_CheckContextType_JonMon(pContext)->EnableBits, 0) // // Event write macros for event "QueryTokenImpersonation" // #define EventWriteQueryTokenImpersonation(EventTime_, ProcessFilePath, ProcessId, ProcessUserName, ProcessUserLogonId, ProcessIntegrityLevel, TargetThreadId, TargetThreadIntegrityLevel, TargetThreadUserName) \ MCGEN_EVENT_ENABLED(QueryTokenImpersonation) \ ? _mcgen_TEMPLATE_FOR_QueryTokenImpersonation(&JonMonProvider_Context, &QueryTokenImpersonation, EventTime_, ProcessFilePath, ProcessId, ProcessUserName, ProcessUserLogonId, ProcessIntegrityLevel, TargetThreadId, TargetThreadIntegrityLevel, TargetThreadUserName) : 0 #define EventWriteQueryTokenImpersonation_AssumeEnabled(EventTime_, ProcessFilePath, ProcessId, ProcessUserName, ProcessUserLogonId, ProcessIntegrityLevel, TargetThreadId, TargetThreadIntegrityLevel, TargetThreadUserName) \ _mcgen_TEMPLATE_FOR_QueryTokenImpersonation(&JonMonProvider_Context, &QueryTokenImpersonation, EventTime_, ProcessFilePath, ProcessId, ProcessUserName, ProcessUserLogonId, ProcessIntegrityLevel, TargetThreadId, TargetThreadIntegrityLevel, TargetThreadUserName) #define EventWriteQueryTokenImpersonation_ForContext(pContext, EventTime_, ProcessFilePath, ProcessId, ProcessUserName, ProcessUserLogonId, ProcessIntegrityLevel, TargetThreadId, TargetThreadIntegrityLevel, TargetThreadUserName) \ MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, QueryTokenImpersonation) \ ? _mcgen_TEMPLATE_FOR_QueryTokenImpersonation(&(pContext)->Context, &QueryTokenImpersonation, EventTime_, ProcessFilePath, ProcessId, ProcessUserName, ProcessUserLogonId, ProcessIntegrityLevel, TargetThreadId, TargetThreadIntegrityLevel, TargetThreadUserName) : 0 #define EventWriteQueryTokenImpersonation_ForContextAssumeEnabled(pContext, EventTime_, ProcessFilePath, ProcessId, ProcessUserName, ProcessUserLogonId, ProcessIntegrityLevel, TargetThreadId, TargetThreadIntegrityLevel, TargetThreadUserName) \ _mcgen_TEMPLATE_FOR_QueryTokenImpersonation(&_mcgen_CheckContextType_JonMon(pContext)->Context, &QueryTokenImpersonation, EventTime_, ProcessFilePath, ProcessId, ProcessUserName, ProcessUserLogonId, ProcessIntegrityLevel, TargetThreadId, TargetThreadIntegrityLevel, TargetThreadUserName) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_TEMPLATE_FOR_QueryTokenImpersonation _mcgen_PASTE2(McTemplateU0yzqzqzqzz_, MCGEN_EVENTWRITETRANSFER) // // Enablement check macro for event "DebugLog102" // #define EventEnabledDebugLog102() _mcgen_EVENT_BIT_SET(JonMonEnableBits, 0) #define EventEnabledDebugLog102_ForContext(pContext) _mcgen_EVENT_BIT_SET(_mcgen_CheckContextType_JonMon(pContext)->EnableBits, 0) // // Event write macros for event "DebugLog102" // #define EventWriteDebugLog102(EventId, ProtectionLevel) \ MCGEN_EVENT_ENABLED(DebugLog102) \ ? _mcgen_TEMPLATE_FOR_DebugLog102(&JonMonProvider_Context, &DebugLog102, EventId, ProtectionLevel) : 0 #define EventWriteDebugLog102_AssumeEnabled(EventId, ProtectionLevel) \ _mcgen_TEMPLATE_FOR_DebugLog102(&JonMonProvider_Context, &DebugLog102, EventId, ProtectionLevel) #define EventWriteDebugLog102_ForContext(pContext, EventId, ProtectionLevel) \ MCGEN_EVENT_ENABLED_FORCONTEXT(pContext, DebugLog102) \ ? _mcgen_TEMPLATE_FOR_DebugLog102(&(pContext)->Context, &DebugLog102, EventId, ProtectionLevel) : 0 #define EventWriteDebugLog102_ForContextAssumeEnabled(pContext, EventId, ProtectionLevel) \ _mcgen_TEMPLATE_FOR_DebugLog102(&_mcgen_CheckContextType_JonMon(pContext)->Context, &DebugLog102, EventId, ProtectionLevel) // This macro is for use by MC-generated code and should not be used directly. #define _mcgen_TEMPLATE_FOR_DebugLog102 _mcgen_PASTE2(McTemplateU0dt_, MCGEN_EVENTWRITETRANSFER) #endif // MCGEN_DISABLE_PROVIDER_CODE_GENERATION // // MCGEN_DISABLE_PROVIDER_CODE_GENERATION macro: // Define this macro to have the compiler skip the generated functions in this // header. // #ifndef MCGEN_DISABLE_PROVIDER_CODE_GENERATION // // Template Functions // // // Function for template "EID102" (and possibly others). // This function is for use by MC-generated code and should not be used directly. // #ifndef McTemplateU0dt_def #define McTemplateU0dt_def ETW_INLINE ULONG _mcgen_PASTE2(McTemplateU0dt_, MCGEN_EVENTWRITETRANSFER)( _In_ PMCGEN_TRACE_CONTEXT Context, _In_ PCEVENT_DESCRIPTOR Descriptor, _In_ const signed int _Arg0, _In_ const signed int _Arg1 ) { #define McTemplateU0dt_ARGCOUNT 2 EVENT_DATA_DESCRIPTOR EventData[McTemplateU0dt_ARGCOUNT + 1]; EventDataDescCreate(&EventData[1],&_Arg0, sizeof(const signed int) ); EventDataDescCreate(&EventData[2],&_Arg1, sizeof(const signed int) ); return McGenEventWrite(Context, Descriptor, NULL, McTemplateU0dt_ARGCOUNT + 1, EventData); } #endif // McTemplateU0dt_def // // Function for template "EID1" (and possibly others). // This function is for use by MC-generated code and should not be used directly. // #ifndef McTemplateU0yiiiizzqzqqzziizqqzqqt_def #define McTemplateU0yiiiizzqzqqzziizqqzqqt_def ETW_INLINE ULONG _mcgen_PASTE2(McTemplateU0yiiiizzqzqqzziizqqzqqt_, MCGEN_EVENTWRITETRANSFER)( _In_ PMCGEN_TRACE_CONTEXT Context, _In_ PCEVENT_DESCRIPTOR Descriptor, _In_ const SYSTEMTIME* _Arg0, _In_ const signed __int64 _Arg1, _In_ const signed __int64 _Arg2, _In_ const signed __int64 _Arg3, _In_ const signed __int64 _Arg4, _In_opt_ PCWSTR _Arg5, _In_opt_ PCWSTR _Arg6, _In_ const unsigned int _Arg7, _In_opt_ PCWSTR _Arg8, _In_ const unsigned int _Arg9, _In_ const unsigned int _Arg10, _In_opt_ PCWSTR _Arg11, _In_opt_ PCWSTR _Arg12, _In_ const signed __int64 _Arg13, _In_ const signed __int64 _Arg14, _In_opt_ PCWSTR _Arg15, _In_ const unsigned int _Arg16, _In_ const unsigned int _Arg17, _In_opt_ PCWSTR _Arg18, _In_ const unsigned int _Arg19, _In_ const unsigned int _Arg20, _In_ const signed int _Arg21 ) { #define McTemplateU0yiiiizzqzqqzziizqqzqqt_ARGCOUNT 22 EVENT_DATA_DESCRIPTOR EventData[McTemplateU0yiiiizzqzqqzziizqqzqqt_ARGCOUNT + 1]; EventDataDescCreate(&EventData[1],_Arg0, sizeof(SYSTEMTIME) ); EventDataDescCreate(&EventData[2],&_Arg1, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[3],&_Arg2, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[4],&_Arg3, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[5],&_Arg4, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[6], (_Arg5 != NULL) ? _Arg5 : L"NULL", (_Arg5 != NULL) ? (ULONG)((wcslen(_Arg5) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[7], (_Arg6 != NULL) ? _Arg6 : L"NULL", (_Arg6 != NULL) ? (ULONG)((wcslen(_Arg6) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[8],&_Arg7, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[9], (_Arg8 != NULL) ? _Arg8 : L"NULL", (_Arg8 != NULL) ? (ULONG)((wcslen(_Arg8) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[10],&_Arg9, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[11],&_Arg10, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[12], (_Arg11 != NULL) ? _Arg11 : L"NULL", (_Arg11 != NULL) ? (ULONG)((wcslen(_Arg11) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[13], (_Arg12 != NULL) ? _Arg12 : L"NULL", (_Arg12 != NULL) ? (ULONG)((wcslen(_Arg12) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[14],&_Arg13, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[15],&_Arg14, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[16], (_Arg15 != NULL) ? _Arg15 : L"NULL", (_Arg15 != NULL) ? (ULONG)((wcslen(_Arg15) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[17],&_Arg16, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[18],&_Arg17, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[19], (_Arg18 != NULL) ? _Arg18 : L"NULL", (_Arg18 != NULL) ? (ULONG)((wcslen(_Arg18) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[20],&_Arg19, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[21],&_Arg20, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[22],&_Arg21, sizeof(const signed int) ); return McGenEventWrite(Context, Descriptor, NULL, McTemplateU0yiiiizzqzqqzziizqqzqqt_ARGCOUNT + 1, EventData); } #endif // McTemplateU0yiiiizzqzqqzziizqqzqqt_def // // Function for template "EID5" (and possibly others). // This function is for use by MC-generated code and should not be used directly. // #ifndef McTemplateU0yiiizzqzqqiizzqqzqqdd_def #define McTemplateU0yiiizzqzqqiizzqqzqqdd_def ETW_INLINE ULONG _mcgen_PASTE2(McTemplateU0yiiizzqzqqiizzqqzqqdd_, MCGEN_EVENTWRITETRANSFER)( _In_ PMCGEN_TRACE_CONTEXT Context, _In_ PCEVENT_DESCRIPTOR Descriptor, _In_ const SYSTEMTIME* _Arg0, _In_ const signed __int64 _Arg1, _In_ const signed __int64 _Arg2, _In_ const signed __int64 _Arg3, _In_opt_ PCWSTR _Arg4, _In_opt_ PCWSTR _Arg5, _In_ const unsigned int _Arg6, _In_opt_ PCWSTR _Arg7, _In_ const unsigned int _Arg8, _In_ const unsigned int _Arg9, _In_ const signed __int64 _Arg10, _In_ const signed __int64 _Arg11, _In_opt_ PCWSTR _Arg12, _In_opt_ PCWSTR _Arg13, _In_ const unsigned int _Arg14, _In_ const unsigned int _Arg15, _In_opt_ PCWSTR _Arg16, _In_ const unsigned int _Arg17, _In_ const unsigned int _Arg18, _In_ const signed int _Arg19, _In_ const signed int _Arg20 ) { #define McTemplateU0yiiizzqzqqiizzqqzqqdd_ARGCOUNT 21 EVENT_DATA_DESCRIPTOR EventData[McTemplateU0yiiizzqzqqiizzqqzqqdd_ARGCOUNT + 1]; EventDataDescCreate(&EventData[1],_Arg0, sizeof(SYSTEMTIME) ); EventDataDescCreate(&EventData[2],&_Arg1, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[3],&_Arg2, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[4],&_Arg3, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[5], (_Arg4 != NULL) ? _Arg4 : L"NULL", (_Arg4 != NULL) ? (ULONG)((wcslen(_Arg4) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[6], (_Arg5 != NULL) ? _Arg5 : L"NULL", (_Arg5 != NULL) ? (ULONG)((wcslen(_Arg5) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[7],&_Arg6, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[8], (_Arg7 != NULL) ? _Arg7 : L"NULL", (_Arg7 != NULL) ? (ULONG)((wcslen(_Arg7) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[9],&_Arg8, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[10],&_Arg9, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[11],&_Arg10, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[12],&_Arg11, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[13], (_Arg12 != NULL) ? _Arg12 : L"NULL", (_Arg12 != NULL) ? (ULONG)((wcslen(_Arg12) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[14], (_Arg13 != NULL) ? _Arg13 : L"NULL", (_Arg13 != NULL) ? (ULONG)((wcslen(_Arg13) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[15],&_Arg14, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[16],&_Arg15, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[17], (_Arg16 != NULL) ? _Arg16 : L"NULL", (_Arg16 != NULL) ? (ULONG)((wcslen(_Arg16) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[18],&_Arg17, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[19],&_Arg18, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[20],&_Arg19, sizeof(const signed int) ); EventDataDescCreate(&EventData[21],&_Arg20, sizeof(const signed int) ); return McGenEventWrite(Context, Descriptor, NULL, McTemplateU0yiiizzqzqqiizzqqzqqdd_ARGCOUNT + 1, EventData); } #endif // McTemplateU0yiiizzqzqqiizzqqzqqdd_def // // Function for template "EID3" (and possibly others). // This function is for use by MC-generated code and should not be used directly. // #ifndef McTemplateU0yiiizzqzqqziiizqqzq_def #define McTemplateU0yiiizzqzqqziiizqqzq_def ETW_INLINE ULONG _mcgen_PASTE2(McTemplateU0yiiizzqzqqziiizqqzq_, MCGEN_EVENTWRITETRANSFER)( _In_ PMCGEN_TRACE_CONTEXT Context, _In_ PCEVENT_DESCRIPTOR Descriptor, _In_ const SYSTEMTIME* _Arg0, _In_ const signed __int64 _Arg1, _In_ const signed __int64 _Arg2, _In_ const signed __int64 _Arg3, _In_opt_ PCWSTR _Arg4, _In_opt_ PCWSTR _Arg5, _In_ const unsigned int _Arg6, _In_opt_ PCWSTR _Arg7, _In_ const unsigned int _Arg8, _In_ const unsigned int _Arg9, _In_opt_ PCWSTR _Arg10, _In_ const signed __int64 _Arg11, _In_ const signed __int64 _Arg12, _In_ const signed __int64 _Arg13, _In_opt_ PCWSTR _Arg14, _In_ const unsigned int _Arg15, _In_ const unsigned int _Arg16, _In_opt_ PCWSTR _Arg17, _In_ const unsigned int _Arg18 ) { #define McTemplateU0yiiizzqzqqziiizqqzq_ARGCOUNT 19 EVENT_DATA_DESCRIPTOR EventData[McTemplateU0yiiizzqzqqziiizqqzq_ARGCOUNT + 1]; EventDataDescCreate(&EventData[1],_Arg0, sizeof(SYSTEMTIME) ); EventDataDescCreate(&EventData[2],&_Arg1, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[3],&_Arg2, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[4],&_Arg3, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[5], (_Arg4 != NULL) ? _Arg4 : L"NULL", (_Arg4 != NULL) ? (ULONG)((wcslen(_Arg4) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[6], (_Arg5 != NULL) ? _Arg5 : L"NULL", (_Arg5 != NULL) ? (ULONG)((wcslen(_Arg5) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[7],&_Arg6, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[8], (_Arg7 != NULL) ? _Arg7 : L"NULL", (_Arg7 != NULL) ? (ULONG)((wcslen(_Arg7) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[9],&_Arg8, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[10],&_Arg9, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[11], (_Arg10 != NULL) ? _Arg10 : L"NULL", (_Arg10 != NULL) ? (ULONG)((wcslen(_Arg10) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[12],&_Arg11, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[13],&_Arg12, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[14],&_Arg13, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[15], (_Arg14 != NULL) ? _Arg14 : L"NULL", (_Arg14 != NULL) ? (ULONG)((wcslen(_Arg14) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[16],&_Arg15, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[17],&_Arg16, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[18], (_Arg17 != NULL) ? _Arg17 : L"NULL", (_Arg17 != NULL) ? (ULONG)((wcslen(_Arg17) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[19],&_Arg18, sizeof(const unsigned int) ); return McGenEventWrite(Context, Descriptor, NULL, McTemplateU0yiiizzqzqqziiizqqzq_ARGCOUNT + 1, EventData); } #endif // McTemplateU0yiiizzqzqqziiizqqzq_def // // Function for template "EID2" (and possibly others). // This function is for use by MC-generated code and should not be used directly. // #ifndef McTemplateU0yiizi_def #define McTemplateU0yiizi_def ETW_INLINE ULONG _mcgen_PASTE2(McTemplateU0yiizi_, MCGEN_EVENTWRITETRANSFER)( _In_ PMCGEN_TRACE_CONTEXT Context, _In_ PCEVENT_DESCRIPTOR Descriptor, _In_ const SYSTEMTIME* _Arg0, _In_ const signed __int64 _Arg1, _In_ const signed __int64 _Arg2, _In_opt_ PCWSTR _Arg3, _In_ const signed __int64 _Arg4 ) { #define McTemplateU0yiizi_ARGCOUNT 5 EVENT_DATA_DESCRIPTOR EventData[McTemplateU0yiizi_ARGCOUNT + 1]; EventDataDescCreate(&EventData[1],_Arg0, sizeof(SYSTEMTIME) ); EventDataDescCreate(&EventData[2],&_Arg1, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[3],&_Arg2, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[4], (_Arg3 != NULL) ? _Arg3 : L"NULL", (_Arg3 != NULL) ? (ULONG)((wcslen(_Arg3) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[5],&_Arg4, sizeof(const signed __int64) ); return McGenEventWrite(Context, Descriptor, NULL, McTemplateU0yiizi_ARGCOUNT + 1, EventData); } #endif // McTemplateU0yiizi_def // // Function for template "EID21" (and possibly others). // This function is for use by MC-generated code and should not be used directly. // #ifndef McTemplateU0yqzzzhhtzqzq_def #define McTemplateU0yqzzzhhtzqzq_def ETW_INLINE ULONG _mcgen_PASTE2(McTemplateU0yqzzzhhtzqzq_, MCGEN_EVENTWRITETRANSFER)( _In_ PMCGEN_TRACE_CONTEXT Context, _In_ PCEVENT_DESCRIPTOR Descriptor, _In_ const SYSTEMTIME* _Arg0, _In_ const unsigned int _Arg1, _In_opt_ PCWSTR _Arg2, _In_opt_ PCWSTR _Arg3, _In_opt_ PCWSTR _Arg4, _In_ const unsigned short _Arg5, _In_ const unsigned short _Arg6, _In_ const signed int _Arg7, _In_opt_ PCWSTR _Arg8, _In_ const unsigned int _Arg9, _In_opt_ PCWSTR _Arg10, _In_ const unsigned int _Arg11 ) { #define McTemplateU0yqzzzhhtzqzq_ARGCOUNT 12 EVENT_DATA_DESCRIPTOR EventData[McTemplateU0yqzzzhhtzqzq_ARGCOUNT + 1]; EventDataDescCreate(&EventData[1],_Arg0, sizeof(SYSTEMTIME) ); EventDataDescCreate(&EventData[2],&_Arg1, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[3], (_Arg2 != NULL) ? _Arg2 : L"NULL", (_Arg2 != NULL) ? (ULONG)((wcslen(_Arg2) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[4], (_Arg3 != NULL) ? _Arg3 : L"NULL", (_Arg3 != NULL) ? (ULONG)((wcslen(_Arg3) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[5], (_Arg4 != NULL) ? _Arg4 : L"NULL", (_Arg4 != NULL) ? (ULONG)((wcslen(_Arg4) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[6],&_Arg5, sizeof(const unsigned short) ); EventDataDescCreate(&EventData[7],&_Arg6, sizeof(const unsigned short) ); EventDataDescCreate(&EventData[8],&_Arg7, sizeof(const signed int) ); EventDataDescCreate(&EventData[9], (_Arg8 != NULL) ? _Arg8 : L"NULL", (_Arg8 != NULL) ? (ULONG)((wcslen(_Arg8) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[10],&_Arg9, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[11], (_Arg10 != NULL) ? _Arg10 : L"NULL", (_Arg10 != NULL) ? (ULONG)((wcslen(_Arg10) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[12],&_Arg11, sizeof(const unsigned int) ); return McGenEventWrite(Context, Descriptor, NULL, McTemplateU0yqzzzhhtzqzq_ARGCOUNT + 1, EventData); } #endif // McTemplateU0yqzzzhhtzqzq_def // // Function for template "EID4" (and possibly others). // This function is for use by MC-generated code and should not be used directly. // #ifndef McTemplateU0yziiizqqzqqzi_def #define McTemplateU0yziiizqqzqqzi_def ETW_INLINE ULONG _mcgen_PASTE2(McTemplateU0yziiizqqzqqzi_, MCGEN_EVENTWRITETRANSFER)( _In_ PMCGEN_TRACE_CONTEXT Context, _In_ PCEVENT_DESCRIPTOR Descriptor, _In_ const SYSTEMTIME* _Arg0, _In_opt_ PCWSTR _Arg1, _In_ const signed __int64 _Arg2, _In_ const signed __int64 _Arg3, _In_ const signed __int64 _Arg4, _In_opt_ PCWSTR _Arg5, _In_ const unsigned int _Arg6, _In_ const unsigned int _Arg7, _In_opt_ PCWSTR _Arg8, _In_ const unsigned int _Arg9, _In_ const unsigned int _Arg10, _In_opt_ PCWSTR _Arg11, _In_ const signed __int64 _Arg12 ) { #define McTemplateU0yziiizqqzqqzi_ARGCOUNT 13 EVENT_DATA_DESCRIPTOR EventData[McTemplateU0yziiizqqzqqzi_ARGCOUNT + 1]; EventDataDescCreate(&EventData[1],_Arg0, sizeof(SYSTEMTIME) ); EventDataDescCreate(&EventData[2], (_Arg1 != NULL) ? _Arg1 : L"NULL", (_Arg1 != NULL) ? (ULONG)((wcslen(_Arg1) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[3],&_Arg2, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[4],&_Arg3, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[5],&_Arg4, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[6], (_Arg5 != NULL) ? _Arg5 : L"NULL", (_Arg5 != NULL) ? (ULONG)((wcslen(_Arg5) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[7],&_Arg6, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[8],&_Arg7, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[9], (_Arg8 != NULL) ? _Arg8 : L"NULL", (_Arg8 != NULL) ? (ULONG)((wcslen(_Arg8) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[10],&_Arg9, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[11],&_Arg10, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[12], (_Arg11 != NULL) ? _Arg11 : L"NULL", (_Arg11 != NULL) ? (ULONG)((wcslen(_Arg11) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[13],&_Arg12, sizeof(const signed __int64) ); return McGenEventWrite(Context, Descriptor, NULL, McTemplateU0yziiizqqzqqzi_ARGCOUNT + 1, EventData); } #endif // McTemplateU0yziiizqqzqqzi_def // // Function for template "EID6" (and possibly others). // This function is for use by MC-generated code and should not be used directly. // #ifndef McTemplateU0yziiizqzqz_def #define McTemplateU0yziiizqzqz_def ETW_INLINE ULONG _mcgen_PASTE2(McTemplateU0yziiizqzqz_, MCGEN_EVENTWRITETRANSFER)( _In_ PMCGEN_TRACE_CONTEXT Context, _In_ PCEVENT_DESCRIPTOR Descriptor, _In_ const SYSTEMTIME* _Arg0, _In_opt_ PCWSTR _Arg1, _In_ const signed __int64 _Arg2, _In_ const signed __int64 _Arg3, _In_ const signed __int64 _Arg4, _In_opt_ PCWSTR _Arg5, _In_ const unsigned int _Arg6, _In_opt_ PCWSTR _Arg7, _In_ const unsigned int _Arg8, _In_opt_ PCWSTR _Arg9 ) { #define McTemplateU0yziiizqzqz_ARGCOUNT 10 EVENT_DATA_DESCRIPTOR EventData[McTemplateU0yziiizqzqz_ARGCOUNT + 1]; EventDataDescCreate(&EventData[1],_Arg0, sizeof(SYSTEMTIME) ); EventDataDescCreate(&EventData[2], (_Arg1 != NULL) ? _Arg1 : L"NULL", (_Arg1 != NULL) ? (ULONG)((wcslen(_Arg1) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[3],&_Arg2, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[4],&_Arg3, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[5],&_Arg4, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[6], (_Arg5 != NULL) ? _Arg5 : L"NULL", (_Arg5 != NULL) ? (ULONG)((wcslen(_Arg5) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[7],&_Arg6, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[8], (_Arg7 != NULL) ? _Arg7 : L"NULL", (_Arg7 != NULL) ? (ULONG)((wcslen(_Arg7) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[9],&_Arg8, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[10], (_Arg9 != NULL) ? _Arg9 : L"NULL", (_Arg9 != NULL) ? (ULONG)((wcslen(_Arg9) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); return McGenEventWrite(Context, Descriptor, NULL, McTemplateU0yziiizqzqz_ARGCOUNT + 1, EventData); } #endif // McTemplateU0yziiizqzqz_def // // Function for template "EID11" (and possibly others). // This function is for use by MC-generated code and should not be used directly. // #ifndef McTemplateU0yziiizqzqzd_def #define McTemplateU0yziiizqzqzd_def ETW_INLINE ULONG _mcgen_PASTE2(McTemplateU0yziiizqzqzd_, MCGEN_EVENTWRITETRANSFER)( _In_ PMCGEN_TRACE_CONTEXT Context, _In_ PCEVENT_DESCRIPTOR Descriptor, _In_ const SYSTEMTIME* _Arg0, _In_opt_ PCWSTR _Arg1, _In_ const signed __int64 _Arg2, _In_ const signed __int64 _Arg3, _In_ const signed __int64 _Arg4, _In_opt_ PCWSTR _Arg5, _In_ const unsigned int _Arg6, _In_opt_ PCWSTR _Arg7, _In_ const unsigned int _Arg8, _In_opt_ PCWSTR _Arg9, _In_ const signed int _Arg10 ) { #define McTemplateU0yziiizqzqzd_ARGCOUNT 11 EVENT_DATA_DESCRIPTOR EventData[McTemplateU0yziiizqzqzd_ARGCOUNT + 1]; EventDataDescCreate(&EventData[1],_Arg0, sizeof(SYSTEMTIME) ); EventDataDescCreate(&EventData[2], (_Arg1 != NULL) ? _Arg1 : L"NULL", (_Arg1 != NULL) ? (ULONG)((wcslen(_Arg1) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[3],&_Arg2, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[4],&_Arg3, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[5],&_Arg4, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[6], (_Arg5 != NULL) ? _Arg5 : L"NULL", (_Arg5 != NULL) ? (ULONG)((wcslen(_Arg5) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[7],&_Arg6, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[8], (_Arg7 != NULL) ? _Arg7 : L"NULL", (_Arg7 != NULL) ? (ULONG)((wcslen(_Arg7) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[9],&_Arg8, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[10], (_Arg9 != NULL) ? _Arg9 : L"NULL", (_Arg9 != NULL) ? (ULONG)((wcslen(_Arg9) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[11],&_Arg10, sizeof(const signed int) ); return McGenEventWrite(Context, Descriptor, NULL, McTemplateU0yziiizqzqzd_ARGCOUNT + 1, EventData); } #endif // McTemplateU0yziiizqzqzd_def // // Function for template "EID8" (and possibly others). // This function is for use by MC-generated code and should not be used directly. // #ifndef McTemplateU0yziiizqzqzdzz_def #define McTemplateU0yziiizqzqzdzz_def ETW_INLINE ULONG _mcgen_PASTE2(McTemplateU0yziiizqzqzdzz_, MCGEN_EVENTWRITETRANSFER)( _In_ PMCGEN_TRACE_CONTEXT Context, _In_ PCEVENT_DESCRIPTOR Descriptor, _In_ const SYSTEMTIME* _Arg0, _In_opt_ PCWSTR _Arg1, _In_ const signed __int64 _Arg2, _In_ const signed __int64 _Arg3, _In_ const signed __int64 _Arg4, _In_opt_ PCWSTR _Arg5, _In_ const unsigned int _Arg6, _In_opt_ PCWSTR _Arg7, _In_ const unsigned int _Arg8, _In_opt_ PCWSTR _Arg9, _In_ const signed int _Arg10, _In_opt_ PCWSTR _Arg11, _In_opt_ PCWSTR _Arg12 ) { #define McTemplateU0yziiizqzqzdzz_ARGCOUNT 13 EVENT_DATA_DESCRIPTOR EventData[McTemplateU0yziiizqzqzdzz_ARGCOUNT + 1]; EventDataDescCreate(&EventData[1],_Arg0, sizeof(SYSTEMTIME) ); EventDataDescCreate(&EventData[2], (_Arg1 != NULL) ? _Arg1 : L"NULL", (_Arg1 != NULL) ? (ULONG)((wcslen(_Arg1) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[3],&_Arg2, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[4],&_Arg3, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[5],&_Arg4, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[6], (_Arg5 != NULL) ? _Arg5 : L"NULL", (_Arg5 != NULL) ? (ULONG)((wcslen(_Arg5) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[7],&_Arg6, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[8], (_Arg7 != NULL) ? _Arg7 : L"NULL", (_Arg7 != NULL) ? (ULONG)((wcslen(_Arg7) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[9],&_Arg8, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[10], (_Arg9 != NULL) ? _Arg9 : L"NULL", (_Arg9 != NULL) ? (ULONG)((wcslen(_Arg9) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[11],&_Arg10, sizeof(const signed int) ); EventDataDescCreate(&EventData[12], (_Arg11 != NULL) ? _Arg11 : L"NULL", (_Arg11 != NULL) ? (ULONG)((wcslen(_Arg11) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[13], (_Arg12 != NULL) ? _Arg12 : L"NULL", (_Arg12 != NULL) ? (ULONG)((wcslen(_Arg12) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); return McGenEventWrite(Context, Descriptor, NULL, McTemplateU0yziiizqzqzdzz_ARGCOUNT + 1, EventData); } #endif // McTemplateU0yziiizqzqzdzz_def // // Function for template "EID23" (and possibly others). // This function is for use by MC-generated code and should not be used directly. // #ifndef McTemplateU0yzizqzqqzizqzqxx_def #define McTemplateU0yzizqzqqzizqzqxx_def ETW_INLINE ULONG _mcgen_PASTE2(McTemplateU0yzizqzqqzizqzqxx_, MCGEN_EVENTWRITETRANSFER)( _In_ PMCGEN_TRACE_CONTEXT Context, _In_ PCEVENT_DESCRIPTOR Descriptor, _In_ const SYSTEMTIME* _Arg0, _In_opt_ PCWSTR _Arg1, _In_ const signed __int64 _Arg2, _In_opt_ PCWSTR _Arg3, _In_ const unsigned int _Arg4, _In_opt_ PCWSTR _Arg5, _In_ const unsigned int _Arg6, _In_ const unsigned int _Arg7, _In_opt_ PCWSTR _Arg8, _In_ const signed __int64 _Arg9, _In_opt_ PCWSTR _Arg10, _In_ const unsigned int _Arg11, _In_opt_ PCWSTR _Arg12, _In_ const unsigned int _Arg13, _In_ const unsigned __int64 _Arg14, _In_ const unsigned __int64 _Arg15 ) { #define McTemplateU0yzizqzqqzizqzqxx_ARGCOUNT 16 EVENT_DATA_DESCRIPTOR EventData[McTemplateU0yzizqzqqzizqzqxx_ARGCOUNT + 1]; EventDataDescCreate(&EventData[1],_Arg0, sizeof(SYSTEMTIME) ); EventDataDescCreate(&EventData[2], (_Arg1 != NULL) ? _Arg1 : L"NULL", (_Arg1 != NULL) ? (ULONG)((wcslen(_Arg1) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[3],&_Arg2, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[4], (_Arg3 != NULL) ? _Arg3 : L"NULL", (_Arg3 != NULL) ? (ULONG)((wcslen(_Arg3) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[5],&_Arg4, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[6], (_Arg5 != NULL) ? _Arg5 : L"NULL", (_Arg5 != NULL) ? (ULONG)((wcslen(_Arg5) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[7],&_Arg6, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[8],&_Arg7, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[9], (_Arg8 != NULL) ? _Arg8 : L"NULL", (_Arg8 != NULL) ? (ULONG)((wcslen(_Arg8) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[10],&_Arg9, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[11], (_Arg10 != NULL) ? _Arg10 : L"NULL", (_Arg10 != NULL) ? (ULONG)((wcslen(_Arg10) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[12],&_Arg11, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[13], (_Arg12 != NULL) ? _Arg12 : L"NULL", (_Arg12 != NULL) ? (ULONG)((wcslen(_Arg12) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[14],&_Arg13, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[15],&_Arg14, sizeof(const unsigned __int64) ); EventDataDescCreate(&EventData[16],&_Arg15, sizeof(const unsigned __int64) ); return McGenEventWrite(Context, Descriptor, NULL, McTemplateU0yzizqzqqzizqzqxx_ARGCOUNT + 1, EventData); } #endif // McTemplateU0yzizqzqqzizqzqxx_def // // Function for template "EID25" (and possibly others). // This function is for use by MC-generated code and should not be used directly. // #ifndef McTemplateU0yzizqzqqzizqzqxxx_def #define McTemplateU0yzizqzqqzizqzqxxx_def ETW_INLINE ULONG _mcgen_PASTE2(McTemplateU0yzizqzqqzizqzqxxx_, MCGEN_EVENTWRITETRANSFER)( _In_ PMCGEN_TRACE_CONTEXT Context, _In_ PCEVENT_DESCRIPTOR Descriptor, _In_ const SYSTEMTIME* _Arg0, _In_opt_ PCWSTR _Arg1, _In_ const signed __int64 _Arg2, _In_opt_ PCWSTR _Arg3, _In_ const unsigned int _Arg4, _In_opt_ PCWSTR _Arg5, _In_ const unsigned int _Arg6, _In_ const unsigned int _Arg7, _In_opt_ PCWSTR _Arg8, _In_ const signed __int64 _Arg9, _In_opt_ PCWSTR _Arg10, _In_ const unsigned int _Arg11, _In_opt_ PCWSTR _Arg12, _In_ const unsigned int _Arg13, _In_ const unsigned __int64 _Arg14, _In_ const unsigned __int64 _Arg15, _In_ const unsigned __int64 _Arg16 ) { #define McTemplateU0yzizqzqqzizqzqxxx_ARGCOUNT 17 EVENT_DATA_DESCRIPTOR EventData[McTemplateU0yzizqzqqzizqzqxxx_ARGCOUNT + 1]; EventDataDescCreate(&EventData[1],_Arg0, sizeof(SYSTEMTIME) ); EventDataDescCreate(&EventData[2], (_Arg1 != NULL) ? _Arg1 : L"NULL", (_Arg1 != NULL) ? (ULONG)((wcslen(_Arg1) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[3],&_Arg2, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[4], (_Arg3 != NULL) ? _Arg3 : L"NULL", (_Arg3 != NULL) ? (ULONG)((wcslen(_Arg3) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[5],&_Arg4, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[6], (_Arg5 != NULL) ? _Arg5 : L"NULL", (_Arg5 != NULL) ? (ULONG)((wcslen(_Arg5) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[7],&_Arg6, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[8],&_Arg7, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[9], (_Arg8 != NULL) ? _Arg8 : L"NULL", (_Arg8 != NULL) ? (ULONG)((wcslen(_Arg8) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[10],&_Arg9, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[11], (_Arg10 != NULL) ? _Arg10 : L"NULL", (_Arg10 != NULL) ? (ULONG)((wcslen(_Arg10) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[12],&_Arg11, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[13], (_Arg12 != NULL) ? _Arg12 : L"NULL", (_Arg12 != NULL) ? (ULONG)((wcslen(_Arg12) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[14],&_Arg13, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[15],&_Arg14, sizeof(const unsigned __int64) ); EventDataDescCreate(&EventData[16],&_Arg15, sizeof(const unsigned __int64) ); EventDataDescCreate(&EventData[17],&_Arg16, sizeof(const unsigned __int64) ); return McGenEventWrite(Context, Descriptor, NULL, McTemplateU0yzizqzqqzizqzqxxx_ARGCOUNT + 1, EventData); } #endif // McTemplateU0yzizqzqqzizqzqxxx_def // // Function for template "EID26" (and possibly others). // This function is for use by MC-generated code and should not be used directly. // #ifndef McTemplateU0yzizqzqqzizqzqxxxxxx_def #define McTemplateU0yzizqzqqzizqzqxxxxxx_def ETW_INLINE ULONG _mcgen_PASTE2(McTemplateU0yzizqzqqzizqzqxxxxxx_, MCGEN_EVENTWRITETRANSFER)( _In_ PMCGEN_TRACE_CONTEXT Context, _In_ PCEVENT_DESCRIPTOR Descriptor, _In_ const SYSTEMTIME* _Arg0, _In_opt_ PCWSTR _Arg1, _In_ const signed __int64 _Arg2, _In_opt_ PCWSTR _Arg3, _In_ const unsigned int _Arg4, _In_opt_ PCWSTR _Arg5, _In_ const unsigned int _Arg6, _In_ const unsigned int _Arg7, _In_opt_ PCWSTR _Arg8, _In_ const signed __int64 _Arg9, _In_opt_ PCWSTR _Arg10, _In_ const unsigned int _Arg11, _In_opt_ PCWSTR _Arg12, _In_ const unsigned int _Arg13, _In_ const unsigned __int64 _Arg14, _In_ const unsigned __int64 _Arg15, _In_ const unsigned __int64 _Arg16, _In_ const unsigned __int64 _Arg17, _In_ const unsigned __int64 _Arg18, _In_ const unsigned __int64 _Arg19 ) { #define McTemplateU0yzizqzqqzizqzqxxxxxx_ARGCOUNT 20 EVENT_DATA_DESCRIPTOR EventData[McTemplateU0yzizqzqqzizqzqxxxxxx_ARGCOUNT + 1]; EventDataDescCreate(&EventData[1],_Arg0, sizeof(SYSTEMTIME) ); EventDataDescCreate(&EventData[2], (_Arg1 != NULL) ? _Arg1 : L"NULL", (_Arg1 != NULL) ? (ULONG)((wcslen(_Arg1) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[3],&_Arg2, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[4], (_Arg3 != NULL) ? _Arg3 : L"NULL", (_Arg3 != NULL) ? (ULONG)((wcslen(_Arg3) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[5],&_Arg4, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[6], (_Arg5 != NULL) ? _Arg5 : L"NULL", (_Arg5 != NULL) ? (ULONG)((wcslen(_Arg5) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[7],&_Arg6, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[8],&_Arg7, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[9], (_Arg8 != NULL) ? _Arg8 : L"NULL", (_Arg8 != NULL) ? (ULONG)((wcslen(_Arg8) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[10],&_Arg9, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[11], (_Arg10 != NULL) ? _Arg10 : L"NULL", (_Arg10 != NULL) ? (ULONG)((wcslen(_Arg10) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[12],&_Arg11, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[13], (_Arg12 != NULL) ? _Arg12 : L"NULL", (_Arg12 != NULL) ? (ULONG)((wcslen(_Arg12) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[14],&_Arg13, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[15],&_Arg14, sizeof(const unsigned __int64) ); EventDataDescCreate(&EventData[16],&_Arg15, sizeof(const unsigned __int64) ); EventDataDescCreate(&EventData[17],&_Arg16, sizeof(const unsigned __int64) ); EventDataDescCreate(&EventData[18],&_Arg17, sizeof(const unsigned __int64) ); EventDataDescCreate(&EventData[19],&_Arg18, sizeof(const unsigned __int64) ); EventDataDescCreate(&EventData[20],&_Arg19, sizeof(const unsigned __int64) ); return McGenEventWrite(Context, Descriptor, NULL, McTemplateU0yzizqzqqzizqzqxxxxxx_ARGCOUNT + 1, EventData); } #endif // McTemplateU0yzizqzqqzizqzqxxxxxx_def // // Function for template "EID16" (and possibly others). // This function is for use by MC-generated code and should not be used directly. // #ifndef McTemplateU0yzizqzqzh_def #define McTemplateU0yzizqzqzh_def ETW_INLINE ULONG _mcgen_PASTE2(McTemplateU0yzizqzqzh_, MCGEN_EVENTWRITETRANSFER)( _In_ PMCGEN_TRACE_CONTEXT Context, _In_ PCEVENT_DESCRIPTOR Descriptor, _In_ const SYSTEMTIME* _Arg0, _In_opt_ PCWSTR _Arg1, _In_ const signed __int64 _Arg2, _In_opt_ PCWSTR _Arg3, _In_ const unsigned int _Arg4, _In_opt_ PCWSTR _Arg5, _In_ const unsigned int _Arg6, _In_opt_ PCWSTR _Arg7, _In_ const unsigned short _Arg8 ) { #define McTemplateU0yzizqzqzh_ARGCOUNT 9 EVENT_DATA_DESCRIPTOR EventData[McTemplateU0yzizqzqzh_ARGCOUNT + 1]; EventDataDescCreate(&EventData[1],_Arg0, sizeof(SYSTEMTIME) ); EventDataDescCreate(&EventData[2], (_Arg1 != NULL) ? _Arg1 : L"NULL", (_Arg1 != NULL) ? (ULONG)((wcslen(_Arg1) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[3],&_Arg2, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[4], (_Arg3 != NULL) ? _Arg3 : L"NULL", (_Arg3 != NULL) ? (ULONG)((wcslen(_Arg3) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[5],&_Arg4, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[6], (_Arg5 != NULL) ? _Arg5 : L"NULL", (_Arg5 != NULL) ? (ULONG)((wcslen(_Arg5) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[7],&_Arg6, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[8], (_Arg7 != NULL) ? _Arg7 : L"NULL", (_Arg7 != NULL) ? (ULONG)((wcslen(_Arg7) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[9],&_Arg8, sizeof(const unsigned short) ); return McGenEventWrite(Context, Descriptor, NULL, McTemplateU0yzizqzqzh_ARGCOUNT + 1, EventData); } #endif // McTemplateU0yzizqzqzh_def // // Function for template "EID18" (and possibly others). // This function is for use by MC-generated code and should not be used directly. // #ifndef McTemplateU0yzizqzqzqqzzzzz_def #define McTemplateU0yzizqzqzqqzzzzz_def ETW_INLINE ULONG _mcgen_PASTE2(McTemplateU0yzizqzqzqqzzzzz_, MCGEN_EVENTWRITETRANSFER)( _In_ PMCGEN_TRACE_CONTEXT Context, _In_ PCEVENT_DESCRIPTOR Descriptor, _In_ const SYSTEMTIME* _Arg0, _In_opt_ PCWSTR _Arg1, _In_ const signed __int64 _Arg2, _In_opt_ PCWSTR _Arg3, _In_ const unsigned int _Arg4, _In_opt_ PCWSTR _Arg5, _In_ const unsigned int _Arg6, _In_opt_ PCWSTR _Arg7, _In_ const unsigned int _Arg8, _In_ const unsigned int _Arg9, _In_opt_ PCWSTR _Arg10, _In_opt_ PCWSTR _Arg11, _In_opt_ PCWSTR _Arg12, _In_opt_ PCWSTR _Arg13, _In_opt_ PCWSTR _Arg14 ) { #define McTemplateU0yzizqzqzqqzzzzz_ARGCOUNT 15 EVENT_DATA_DESCRIPTOR EventData[McTemplateU0yzizqzqzqqzzzzz_ARGCOUNT + 1]; EventDataDescCreate(&EventData[1],_Arg0, sizeof(SYSTEMTIME) ); EventDataDescCreate(&EventData[2], (_Arg1 != NULL) ? _Arg1 : L"NULL", (_Arg1 != NULL) ? (ULONG)((wcslen(_Arg1) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[3],&_Arg2, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[4], (_Arg3 != NULL) ? _Arg3 : L"NULL", (_Arg3 != NULL) ? (ULONG)((wcslen(_Arg3) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[5],&_Arg4, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[6], (_Arg5 != NULL) ? _Arg5 : L"NULL", (_Arg5 != NULL) ? (ULONG)((wcslen(_Arg5) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[7],&_Arg6, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[8], (_Arg7 != NULL) ? _Arg7 : L"NULL", (_Arg7 != NULL) ? (ULONG)((wcslen(_Arg7) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[9],&_Arg8, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[10],&_Arg9, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[11], (_Arg10 != NULL) ? _Arg10 : L"NULL", (_Arg10 != NULL) ? (ULONG)((wcslen(_Arg10) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[12], (_Arg11 != NULL) ? _Arg11 : L"NULL", (_Arg11 != NULL) ? (ULONG)((wcslen(_Arg11) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[13], (_Arg12 != NULL) ? _Arg12 : L"NULL", (_Arg12 != NULL) ? (ULONG)((wcslen(_Arg12) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[14], (_Arg13 != NULL) ? _Arg13 : L"NULL", (_Arg13 != NULL) ? (ULONG)((wcslen(_Arg13) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[15], (_Arg14 != NULL) ? _Arg14 : L"NULL", (_Arg14 != NULL) ? (ULONG)((wcslen(_Arg14) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); return McGenEventWrite(Context, Descriptor, NULL, McTemplateU0yzizqzqzqqzzzzz_ARGCOUNT + 1, EventData); } #endif // McTemplateU0yzizqzqzqqzzzzz_def // // Function for template "EID20" (and possibly others). // This function is for use by MC-generated code and should not be used directly. // #ifndef McTemplateU0yzizqzqzzqq_def #define McTemplateU0yzizqzqzzqq_def ETW_INLINE ULONG _mcgen_PASTE2(McTemplateU0yzizqzqzzqq_, MCGEN_EVENTWRITETRANSFER)( _In_ PMCGEN_TRACE_CONTEXT Context, _In_ PCEVENT_DESCRIPTOR Descriptor, _In_ const SYSTEMTIME* _Arg0, _In_opt_ PCWSTR _Arg1, _In_ const signed __int64 _Arg2, _In_opt_ PCWSTR _Arg3, _In_ const unsigned int _Arg4, _In_opt_ PCWSTR _Arg5, _In_ const unsigned int _Arg6, _In_opt_ PCWSTR _Arg7, _In_opt_ PCWSTR _Arg8, _In_ const unsigned int _Arg9, _In_ const unsigned int _Arg10 ) { #define McTemplateU0yzizqzqzzqq_ARGCOUNT 11 EVENT_DATA_DESCRIPTOR EventData[McTemplateU0yzizqzqzzqq_ARGCOUNT + 1]; EventDataDescCreate(&EventData[1],_Arg0, sizeof(SYSTEMTIME) ); EventDataDescCreate(&EventData[2], (_Arg1 != NULL) ? _Arg1 : L"NULL", (_Arg1 != NULL) ? (ULONG)((wcslen(_Arg1) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[3],&_Arg2, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[4], (_Arg3 != NULL) ? _Arg3 : L"NULL", (_Arg3 != NULL) ? (ULONG)((wcslen(_Arg3) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[5],&_Arg4, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[6], (_Arg5 != NULL) ? _Arg5 : L"NULL", (_Arg5 != NULL) ? (ULONG)((wcslen(_Arg5) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[7],&_Arg6, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[8], (_Arg7 != NULL) ? _Arg7 : L"NULL", (_Arg7 != NULL) ? (ULONG)((wcslen(_Arg7) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[9], (_Arg8 != NULL) ? _Arg8 : L"NULL", (_Arg8 != NULL) ? (ULONG)((wcslen(_Arg8) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[10],&_Arg9, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[11],&_Arg10, sizeof(const unsigned int) ); return McGenEventWrite(Context, Descriptor, NULL, McTemplateU0yzizqzqzzqq_ARGCOUNT + 1, EventData); } #endif // McTemplateU0yzizqzqzzqq_def // // Function for template "EID22" (and possibly others). // This function is for use by MC-generated code and should not be used directly. // #ifndef McTemplateU0yzizqzqzzuqqbr11z_def #define McTemplateU0yzizqzqzzuqqbr11z_def ETW_INLINE ULONG _mcgen_PASTE2(McTemplateU0yzizqzqzzuqqbr11z_, MCGEN_EVENTWRITETRANSFER)( _In_ PMCGEN_TRACE_CONTEXT Context, _In_ PCEVENT_DESCRIPTOR Descriptor, _In_ const SYSTEMTIME* _Arg0, _In_opt_ PCWSTR _Arg1, _In_ const signed __int64 _Arg2, _In_opt_ PCWSTR _Arg3, _In_ const unsigned int _Arg4, _In_opt_ PCWSTR _Arg5, _In_ const unsigned int _Arg6, _In_opt_ PCWSTR _Arg7, _In_opt_ PCWSTR _Arg8, _In_ const unsigned char _Arg9, _In_ const unsigned int _Arg10, _In_ const unsigned int _Arg11, _In_reads_(_Arg11) const unsigned char* _Arg12, _In_opt_ PCWSTR _Arg13 ) { #define McTemplateU0yzizqzqzzuqqbr11z_ARGCOUNT 14 EVENT_DATA_DESCRIPTOR EventData[McTemplateU0yzizqzqzzuqqbr11z_ARGCOUNT + 1]; EventDataDescCreate(&EventData[1],_Arg0, sizeof(SYSTEMTIME) ); EventDataDescCreate(&EventData[2], (_Arg1 != NULL) ? _Arg1 : L"NULL", (_Arg1 != NULL) ? (ULONG)((wcslen(_Arg1) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[3],&_Arg2, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[4], (_Arg3 != NULL) ? _Arg3 : L"NULL", (_Arg3 != NULL) ? (ULONG)((wcslen(_Arg3) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[5],&_Arg4, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[6], (_Arg5 != NULL) ? _Arg5 : L"NULL", (_Arg5 != NULL) ? (ULONG)((wcslen(_Arg5) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[7],&_Arg6, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[8], (_Arg7 != NULL) ? _Arg7 : L"NULL", (_Arg7 != NULL) ? (ULONG)((wcslen(_Arg7) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[9], (_Arg8 != NULL) ? _Arg8 : L"NULL", (_Arg8 != NULL) ? (ULONG)((wcslen(_Arg8) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[10],&_Arg9, sizeof(const unsigned char) ); EventDataDescCreate(&EventData[11],&_Arg10, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[12],&_Arg11, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[13],_Arg12, (ULONG)sizeof(char)*_Arg11); EventDataDescCreate(&EventData[14], (_Arg13 != NULL) ? _Arg13 : L"NULL", (_Arg13 != NULL) ? (ULONG)((wcslen(_Arg13) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); return McGenEventWrite(Context, Descriptor, NULL, McTemplateU0yzizqzqzzuqqbr11z_ARGCOUNT + 1, EventData); } #endif // McTemplateU0yzizqzqzzuqqbr11z_def // // Function for template "EID17" (and possibly others). // This function is for use by MC-generated code and should not be used directly. // #ifndef McTemplateU0yzizqzqzzzz_def #define McTemplateU0yzizqzqzzzz_def ETW_INLINE ULONG _mcgen_PASTE2(McTemplateU0yzizqzqzzzz_, MCGEN_EVENTWRITETRANSFER)( _In_ PMCGEN_TRACE_CONTEXT Context, _In_ PCEVENT_DESCRIPTOR Descriptor, _In_ const SYSTEMTIME* _Arg0, _In_opt_ PCWSTR _Arg1, _In_ const signed __int64 _Arg2, _In_opt_ PCWSTR _Arg3, _In_ const unsigned int _Arg4, _In_opt_ PCWSTR _Arg5, _In_ const unsigned int _Arg6, _In_opt_ PCWSTR _Arg7, _In_opt_ PCWSTR _Arg8, _In_opt_ PCWSTR _Arg9, _In_opt_ PCWSTR _Arg10 ) { #define McTemplateU0yzizqzqzzzz_ARGCOUNT 11 EVENT_DATA_DESCRIPTOR EventData[McTemplateU0yzizqzqzzzz_ARGCOUNT + 1]; EventDataDescCreate(&EventData[1],_Arg0, sizeof(SYSTEMTIME) ); EventDataDescCreate(&EventData[2], (_Arg1 != NULL) ? _Arg1 : L"NULL", (_Arg1 != NULL) ? (ULONG)((wcslen(_Arg1) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[3],&_Arg2, sizeof(const signed __int64) ); EventDataDescCreate(&EventData[4], (_Arg3 != NULL) ? _Arg3 : L"NULL", (_Arg3 != NULL) ? (ULONG)((wcslen(_Arg3) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[5],&_Arg4, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[6], (_Arg5 != NULL) ? _Arg5 : L"NULL", (_Arg5 != NULL) ? (ULONG)((wcslen(_Arg5) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[7],&_Arg6, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[8], (_Arg7 != NULL) ? _Arg7 : L"NULL", (_Arg7 != NULL) ? (ULONG)((wcslen(_Arg7) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[9], (_Arg8 != NULL) ? _Arg8 : L"NULL", (_Arg8 != NULL) ? (ULONG)((wcslen(_Arg8) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[10], (_Arg9 != NULL) ? _Arg9 : L"NULL", (_Arg9 != NULL) ? (ULONG)((wcslen(_Arg9) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[11], (_Arg10 != NULL) ? _Arg10 : L"NULL", (_Arg10 != NULL) ? (ULONG)((wcslen(_Arg10) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); return McGenEventWrite(Context, Descriptor, NULL, McTemplateU0yzizqzqzzzz_ARGCOUNT + 1, EventData); } #endif // McTemplateU0yzizqzqzzzz_def // // Function for template "EID27" (and possibly others). // This function is for use by MC-generated code and should not be used directly. // #ifndef McTemplateU0yzqzqzqzz_def #define McTemplateU0yzqzqzqzz_def ETW_INLINE ULONG _mcgen_PASTE2(McTemplateU0yzqzqzqzz_, MCGEN_EVENTWRITETRANSFER)( _In_ PMCGEN_TRACE_CONTEXT Context, _In_ PCEVENT_DESCRIPTOR Descriptor, _In_ const SYSTEMTIME* _Arg0, _In_opt_ PCWSTR _Arg1, _In_ const unsigned int _Arg2, _In_opt_ PCWSTR _Arg3, _In_ const unsigned int _Arg4, _In_opt_ PCWSTR _Arg5, _In_ const unsigned int _Arg6, _In_opt_ PCWSTR _Arg7, _In_opt_ PCWSTR _Arg8 ) { #define McTemplateU0yzqzqzqzz_ARGCOUNT 9 EVENT_DATA_DESCRIPTOR EventData[McTemplateU0yzqzqzqzz_ARGCOUNT + 1]; EventDataDescCreate(&EventData[1],_Arg0, sizeof(SYSTEMTIME) ); EventDataDescCreate(&EventData[2], (_Arg1 != NULL) ? _Arg1 : L"NULL", (_Arg1 != NULL) ? (ULONG)((wcslen(_Arg1) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[3],&_Arg2, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[4], (_Arg3 != NULL) ? _Arg3 : L"NULL", (_Arg3 != NULL) ? (ULONG)((wcslen(_Arg3) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[5],&_Arg4, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[6], (_Arg5 != NULL) ? _Arg5 : L"NULL", (_Arg5 != NULL) ? (ULONG)((wcslen(_Arg5) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[7],&_Arg6, sizeof(const unsigned int) ); EventDataDescCreate(&EventData[8], (_Arg7 != NULL) ? _Arg7 : L"NULL", (_Arg7 != NULL) ? (ULONG)((wcslen(_Arg7) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); EventDataDescCreate(&EventData[9], (_Arg8 != NULL) ? _Arg8 : L"NULL", (_Arg8 != NULL) ? (ULONG)((wcslen(_Arg8) + 1) * sizeof(WCHAR)) : (ULONG)sizeof(L"NULL")); return McGenEventWrite(Context, Descriptor, NULL, McTemplateU0yzqzqzqzz_ARGCOUNT + 1, EventData); } #endif // McTemplateU0yzqzqzqzz_def #endif // MCGEN_DISABLE_PROVIDER_CODE_GENERATION #if defined(__cplusplus) } #endif #define MSG_ProcessCreation_EventMessage 0xB0000001L #define MSG_ProcessTerminate_EventMessage 0xB0000002L #define MSG_RemoteThreadCreation_EventMessage 0xB0000003L #define MSG_ImageLoaded_EventMessage 0xB0000004L #define MSG_ProcessAccess_EventMessage 0xB0000005L #define MSG_RegistrySaveKey_EventMessage 0xB0000006L #define MSG_RegistrySetValueKey_EventMessage 0xB0000008L #define MSG_RegistryCreateKey_EventMessage 0xB0000009L #define MSG_FileCreation_EventMessage 0xB000000AL #define MSG_NamedPipeCreation_EventMessage 0xB000000BL #define MSG_NamedPipeConnection_EventMessage 0xB000000CL #define MSG_MailslotCreation_EventMessage 0xB000000DL #define MSG_MailslotConnection_EventMessage 0xB000000EL #define MSG_RemoteFileConnection_EventMessage 0xB000000FL #define MSG_DotNetLoad_EventMessage 0xB0000010L #define MSG_WMIEventFilter_EventMessage 0xB0000011L #define MSG_RPCClient_EventMessage 0xB0000012L #define MSG_RPCServer_EventMessage 0xB0000013L #define MSG_DPAPIUnprotect_EventMessage 0xB0000014L #define MSG_NetworkConnection_EventMessage 0xB0000015L #define MSG_AMSI_EventMessage 0xB0000016L #define MSG_RemoteReadProcessMemory_EventMessage 0xB0000017L #define MSG_RemoteWriteProcessMemory_EventMessage 0xB0000018L #define MSG_RemoteVirtualAllocation_EventMessage 0xB0000019L #define MSG_RemoteQueueUserAPC_EventMessage 0xB000001AL #define MSG_QueryTokenImpersonation_EventMessage 0xB000001BL #define MSG_DebugLog102_EventMessage 0xB0000066L ================================================ FILE: JonMonProvider/jonmon.man ================================================ 67112660 ================================================ FILE: JonMonProvider/jonmon.rc ================================================ LANGUAGE 0x9,0x1 1 11 "MSG00001.bin" 1 WEVT_TEMPLATE "jonmonTEMP.BIN" ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2023 Jonathan Johnson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: Libs/nlohmann/adl_serializer.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include #include #include #include #include NLOHMANN_JSON_NAMESPACE_BEGIN /// @sa https://json.nlohmann.me/api/adl_serializer/ template struct adl_serializer { /// @brief convert a JSON value to any value type /// @sa https://json.nlohmann.me/api/adl_serializer/from_json/ template static auto from_json(BasicJsonType && j, TargetType& val) noexcept( noexcept(::nlohmann::from_json(std::forward(j), val))) -> decltype(::nlohmann::from_json(std::forward(j), val), void()) { ::nlohmann::from_json(std::forward(j), val); } /// @brief convert a JSON value to any value type /// @sa https://json.nlohmann.me/api/adl_serializer/from_json/ template static auto from_json(BasicJsonType && j) noexcept( noexcept(::nlohmann::from_json(std::forward(j), detail::identity_tag {}))) -> decltype(::nlohmann::from_json(std::forward(j), detail::identity_tag {})) { return ::nlohmann::from_json(std::forward(j), detail::identity_tag {}); } /// @brief convert any value type to a JSON value /// @sa https://json.nlohmann.me/api/adl_serializer/to_json/ template static auto to_json(BasicJsonType& j, TargetType && val) noexcept( noexcept(::nlohmann::to_json(j, std::forward(val)))) -> decltype(::nlohmann::to_json(j, std::forward(val)), void()) { ::nlohmann::to_json(j, std::forward(val)); } }; NLOHMANN_JSON_NAMESPACE_END ================================================ FILE: Libs/nlohmann/byte_container_with_subtype.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include // uint8_t, uint64_t #include // tie #include // move #include NLOHMANN_JSON_NAMESPACE_BEGIN /// @brief an internal type for a backed binary type /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/ template class byte_container_with_subtype : public BinaryType { public: using container_type = BinaryType; using subtype_type = std::uint64_t; /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ byte_container_with_subtype() noexcept(noexcept(container_type())) : container_type() {} /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ byte_container_with_subtype(const container_type& b) noexcept(noexcept(container_type(b))) : container_type(b) {} /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ byte_container_with_subtype(container_type&& b) noexcept(noexcept(container_type(std::move(b)))) : container_type(std::move(b)) {} /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ byte_container_with_subtype(const container_type& b, subtype_type subtype_) noexcept(noexcept(container_type(b))) : container_type(b) , m_subtype(subtype_) , m_has_subtype(true) {} /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/byte_container_with_subtype/ byte_container_with_subtype(container_type&& b, subtype_type subtype_) noexcept(noexcept(container_type(std::move(b)))) : container_type(std::move(b)) , m_subtype(subtype_) , m_has_subtype(true) {} bool operator==(const byte_container_with_subtype& rhs) const { return std::tie(static_cast(*this), m_subtype, m_has_subtype) == std::tie(static_cast(rhs), rhs.m_subtype, rhs.m_has_subtype); } bool operator!=(const byte_container_with_subtype& rhs) const { return !(rhs == *this); } /// @brief sets the binary subtype /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/set_subtype/ void set_subtype(subtype_type subtype_) noexcept { m_subtype = subtype_; m_has_subtype = true; } /// @brief return the binary subtype /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/subtype/ constexpr subtype_type subtype() const noexcept { return m_has_subtype ? m_subtype : static_cast(-1); } /// @brief return whether the value has a subtype /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/has_subtype/ constexpr bool has_subtype() const noexcept { return m_has_subtype; } /// @brief clears the binary subtype /// @sa https://json.nlohmann.me/api/byte_container_with_subtype/clear_subtype/ void clear_subtype() noexcept { m_subtype = 0; m_has_subtype = false; } private: subtype_type m_subtype = 0; bool m_has_subtype = false; }; NLOHMANN_JSON_NAMESPACE_END ================================================ FILE: Libs/nlohmann/detail/abi_macros.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once // This file contains all macro definitions affecting or depending on the ABI #ifndef JSON_SKIP_LIBRARY_VERSION_CHECK #if defined(NLOHMANN_JSON_VERSION_MAJOR) && defined(NLOHMANN_JSON_VERSION_MINOR) && defined(NLOHMANN_JSON_VERSION_PATCH) #if NLOHMANN_JSON_VERSION_MAJOR != 3 || NLOHMANN_JSON_VERSION_MINOR != 11 || NLOHMANN_JSON_VERSION_PATCH != 3 #warning "Already included a different version of the library!" #endif #endif #endif #define NLOHMANN_JSON_VERSION_MAJOR 3 // NOLINT(modernize-macro-to-enum) #define NLOHMANN_JSON_VERSION_MINOR 11 // NOLINT(modernize-macro-to-enum) #define NLOHMANN_JSON_VERSION_PATCH 3 // NOLINT(modernize-macro-to-enum) #ifndef JSON_DIAGNOSTICS #define JSON_DIAGNOSTICS 0 #endif #ifndef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0 #endif #if JSON_DIAGNOSTICS #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS _diag #else #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS #endif #if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON _ldvcmp #else #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON #endif #ifndef NLOHMANN_JSON_NAMESPACE_NO_VERSION #define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0 #endif // Construct the namespace ABI tags component #define NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b) json_abi ## a ## b #define NLOHMANN_JSON_ABI_TAGS_CONCAT(a, b) \ NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b) #define NLOHMANN_JSON_ABI_TAGS \ NLOHMANN_JSON_ABI_TAGS_CONCAT( \ NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS, \ NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON) // Construct the namespace version component #define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) \ _v ## major ## _ ## minor ## _ ## patch #define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(major, minor, patch) \ NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) #if NLOHMANN_JSON_NAMESPACE_NO_VERSION #define NLOHMANN_JSON_NAMESPACE_VERSION #else #define NLOHMANN_JSON_NAMESPACE_VERSION \ NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(NLOHMANN_JSON_VERSION_MAJOR, \ NLOHMANN_JSON_VERSION_MINOR, \ NLOHMANN_JSON_VERSION_PATCH) #endif // Combine namespace components #define NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) a ## b #define NLOHMANN_JSON_NAMESPACE_CONCAT(a, b) \ NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) #ifndef NLOHMANN_JSON_NAMESPACE #define NLOHMANN_JSON_NAMESPACE \ nlohmann::NLOHMANN_JSON_NAMESPACE_CONCAT( \ NLOHMANN_JSON_ABI_TAGS, \ NLOHMANN_JSON_NAMESPACE_VERSION) #endif #ifndef NLOHMANN_JSON_NAMESPACE_BEGIN #define NLOHMANN_JSON_NAMESPACE_BEGIN \ namespace nlohmann \ { \ inline namespace NLOHMANN_JSON_NAMESPACE_CONCAT( \ NLOHMANN_JSON_ABI_TAGS, \ NLOHMANN_JSON_NAMESPACE_VERSION) \ { #endif #ifndef NLOHMANN_JSON_NAMESPACE_END #define NLOHMANN_JSON_NAMESPACE_END \ } /* namespace (inline namespace) NOLINT(readability/namespace) */ \ } // namespace nlohmann #endif ================================================ FILE: Libs/nlohmann/detail/conversions/from_json.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include // transform #include // array #include // forward_list #include // inserter, front_inserter, end #include // map #include // string #include // tuple, make_tuple #include // is_arithmetic, is_same, is_enum, underlying_type, is_convertible #include // unordered_map #include // pair, declval #include // valarray #include #include #include #include #include #include #include #include NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { template inline void from_json(const BasicJsonType& j, typename std::nullptr_t& n) { if (JSON_HEDLEY_UNLIKELY(!j.is_null())) { JSON_THROW(type_error::create(302, concat("type must be null, but is ", j.type_name()), &j)); } n = nullptr; } // overloads for basic_json template parameters template < typename BasicJsonType, typename ArithmeticType, enable_if_t < std::is_arithmetic::value&& !std::is_same::value, int > = 0 > void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val) { switch (static_cast(j)) { case value_t::number_unsigned: { val = static_cast(*j.template get_ptr()); break; } case value_t::number_integer: { val = static_cast(*j.template get_ptr()); break; } case value_t::number_float: { val = static_cast(*j.template get_ptr()); break; } case value_t::null: case value_t::object: case value_t::array: case value_t::string: case value_t::boolean: case value_t::binary: case value_t::discarded: default: JSON_THROW(type_error::create(302, concat("type must be number, but is ", j.type_name()), &j)); } } template inline void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b) { if (JSON_HEDLEY_UNLIKELY(!j.is_boolean())) { JSON_THROW(type_error::create(302, concat("type must be boolean, but is ", j.type_name()), &j)); } b = *j.template get_ptr(); } template inline void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s) { if (JSON_HEDLEY_UNLIKELY(!j.is_string())) { JSON_THROW(type_error::create(302, concat("type must be string, but is ", j.type_name()), &j)); } s = *j.template get_ptr(); } template < typename BasicJsonType, typename StringType, enable_if_t < std::is_assignable::value && is_detected_exact::value && !std::is_same::value && !is_json_ref::value, int > = 0 > inline void from_json(const BasicJsonType& j, StringType& s) { if (JSON_HEDLEY_UNLIKELY(!j.is_string())) { JSON_THROW(type_error::create(302, concat("type must be string, but is ", j.type_name()), &j)); } s = *j.template get_ptr(); } template inline void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val) { get_arithmetic_value(j, val); } template inline void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val) { get_arithmetic_value(j, val); } template inline void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val) { get_arithmetic_value(j, val); } #if !JSON_DISABLE_ENUM_SERIALIZATION template::value, int> = 0> inline void from_json(const BasicJsonType& j, EnumType& e) { typename std::underlying_type::type val; get_arithmetic_value(j, val); e = static_cast(val); } #endif // JSON_DISABLE_ENUM_SERIALIZATION // forward_list doesn't have an insert method template::value, int> = 0> inline void from_json(const BasicJsonType& j, std::forward_list& l) { if (JSON_HEDLEY_UNLIKELY(!j.is_array())) { JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j)); } l.clear(); std::transform(j.rbegin(), j.rend(), std::front_inserter(l), [](const BasicJsonType & i) { return i.template get(); }); } // valarray doesn't have an insert method template::value, int> = 0> inline void from_json(const BasicJsonType& j, std::valarray& l) { if (JSON_HEDLEY_UNLIKELY(!j.is_array())) { JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j)); } l.resize(j.size()); std::transform(j.begin(), j.end(), std::begin(l), [](const BasicJsonType & elem) { return elem.template get(); }); } template auto from_json(const BasicJsonType& j, T (&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) -> decltype(j.template get(), void()) { for (std::size_t i = 0; i < N; ++i) { arr[i] = j.at(i).template get(); } } template inline void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/) { arr = *j.template get_ptr(); } template auto from_json_array_impl(const BasicJsonType& j, std::array& arr, priority_tag<2> /*unused*/) -> decltype(j.template get(), void()) { for (std::size_t i = 0; i < N; ++i) { arr[i] = j.at(i).template get(); } } template::value, int> = 0> auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/) -> decltype( arr.reserve(std::declval()), j.template get(), void()) { using std::end; ConstructibleArrayType ret; ret.reserve(j.size()); std::transform(j.begin(), j.end(), std::inserter(ret, end(ret)), [](const BasicJsonType & i) { // get() returns *this, this won't call a from_json // method when value_type is BasicJsonType return i.template get(); }); arr = std::move(ret); } template::value, int> = 0> inline void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<0> /*unused*/) { using std::end; ConstructibleArrayType ret; std::transform( j.begin(), j.end(), std::inserter(ret, end(ret)), [](const BasicJsonType & i) { // get() returns *this, this won't call a from_json // method when value_type is BasicJsonType return i.template get(); }); arr = std::move(ret); } template < typename BasicJsonType, typename ConstructibleArrayType, enable_if_t < is_constructible_array_type::value&& !is_constructible_object_type::value&& !is_constructible_string_type::value&& !std::is_same::value&& !is_basic_json::value, int > = 0 > auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr) -> decltype(from_json_array_impl(j, arr, priority_tag<3> {}), j.template get(), void()) { if (JSON_HEDLEY_UNLIKELY(!j.is_array())) { JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j)); } from_json_array_impl(j, arr, priority_tag<3> {}); } template < typename BasicJsonType, typename T, std::size_t... Idx > std::array from_json_inplace_array_impl(BasicJsonType&& j, identity_tag> /*unused*/, index_sequence /*unused*/) { return { { std::forward(j).at(Idx).template get()... } }; } template < typename BasicJsonType, typename T, std::size_t N > auto from_json(BasicJsonType&& j, identity_tag> tag) -> decltype(from_json_inplace_array_impl(std::forward(j), tag, make_index_sequence {})) { if (JSON_HEDLEY_UNLIKELY(!j.is_array())) { JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j)); } return from_json_inplace_array_impl(std::forward(j), tag, make_index_sequence {}); } template inline void from_json(const BasicJsonType& j, typename BasicJsonType::binary_t& bin) { if (JSON_HEDLEY_UNLIKELY(!j.is_binary())) { JSON_THROW(type_error::create(302, concat("type must be binary, but is ", j.type_name()), &j)); } bin = *j.template get_ptr(); } template::value, int> = 0> inline void from_json(const BasicJsonType& j, ConstructibleObjectType& obj) { if (JSON_HEDLEY_UNLIKELY(!j.is_object())) { JSON_THROW(type_error::create(302, concat("type must be object, but is ", j.type_name()), &j)); } ConstructibleObjectType ret; const auto* inner_object = j.template get_ptr(); using value_type = typename ConstructibleObjectType::value_type; std::transform( inner_object->begin(), inner_object->end(), std::inserter(ret, ret.begin()), [](typename BasicJsonType::object_t::value_type const & p) { return value_type(p.first, p.second.template get()); }); obj = std::move(ret); } // overload for arithmetic types, not chosen for basic_json template arguments // (BooleanType, etc..); note: Is it really necessary to provide explicit // overloads for boolean_t etc. in case of a custom BooleanType which is not // an arithmetic type? template < typename BasicJsonType, typename ArithmeticType, enable_if_t < std::is_arithmetic::value&& !std::is_same::value&& !std::is_same::value&& !std::is_same::value&& !std::is_same::value, int > = 0 > inline void from_json(const BasicJsonType& j, ArithmeticType& val) { switch (static_cast(j)) { case value_t::number_unsigned: { val = static_cast(*j.template get_ptr()); break; } case value_t::number_integer: { val = static_cast(*j.template get_ptr()); break; } case value_t::number_float: { val = static_cast(*j.template get_ptr()); break; } case value_t::boolean: { val = static_cast(*j.template get_ptr()); break; } case value_t::null: case value_t::object: case value_t::array: case value_t::string: case value_t::binary: case value_t::discarded: default: JSON_THROW(type_error::create(302, concat("type must be number, but is ", j.type_name()), &j)); } } template std::tuple from_json_tuple_impl_base(BasicJsonType&& j, index_sequence /*unused*/) { return std::make_tuple(std::forward(j).at(Idx).template get()...); } template < typename BasicJsonType, class A1, class A2 > std::pair from_json_tuple_impl(BasicJsonType&& j, identity_tag> /*unused*/, priority_tag<0> /*unused*/) { return {std::forward(j).at(0).template get(), std::forward(j).at(1).template get()}; } template inline void from_json_tuple_impl(BasicJsonType&& j, std::pair& p, priority_tag<1> /*unused*/) { p = from_json_tuple_impl(std::forward(j), identity_tag> {}, priority_tag<0> {}); } template std::tuple from_json_tuple_impl(BasicJsonType&& j, identity_tag> /*unused*/, priority_tag<2> /*unused*/) { return from_json_tuple_impl_base(std::forward(j), index_sequence_for {}); } template inline void from_json_tuple_impl(BasicJsonType&& j, std::tuple& t, priority_tag<3> /*unused*/) { t = from_json_tuple_impl_base(std::forward(j), index_sequence_for {}); } template auto from_json(BasicJsonType&& j, TupleRelated&& t) -> decltype(from_json_tuple_impl(std::forward(j), std::forward(t), priority_tag<3> {})) { if (JSON_HEDLEY_UNLIKELY(!j.is_array())) { JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j)); } return from_json_tuple_impl(std::forward(j), std::forward(t), priority_tag<3> {}); } template < typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator, typename = enable_if_t < !std::is_constructible < typename BasicJsonType::string_t, Key >::value >> inline void from_json(const BasicJsonType& j, std::map& m) { if (JSON_HEDLEY_UNLIKELY(!j.is_array())) { JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j)); } m.clear(); for (const auto& p : j) { if (JSON_HEDLEY_UNLIKELY(!p.is_array())) { JSON_THROW(type_error::create(302, concat("type must be array, but is ", p.type_name()), &j)); } m.emplace(p.at(0).template get(), p.at(1).template get()); } } template < typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator, typename = enable_if_t < !std::is_constructible < typename BasicJsonType::string_t, Key >::value >> inline void from_json(const BasicJsonType& j, std::unordered_map& m) { if (JSON_HEDLEY_UNLIKELY(!j.is_array())) { JSON_THROW(type_error::create(302, concat("type must be array, but is ", j.type_name()), &j)); } m.clear(); for (const auto& p : j) { if (JSON_HEDLEY_UNLIKELY(!p.is_array())) { JSON_THROW(type_error::create(302, concat("type must be array, but is ", p.type_name()), &j)); } m.emplace(p.at(0).template get(), p.at(1).template get()); } } #if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM template inline void from_json(const BasicJsonType& j, std_fs::path& p) { if (JSON_HEDLEY_UNLIKELY(!j.is_string())) { JSON_THROW(type_error::create(302, concat("type must be string, but is ", j.type_name()), &j)); } p = *j.template get_ptr(); } #endif struct from_json_fn { template auto operator()(const BasicJsonType& j, T&& val) const noexcept(noexcept(from_json(j, std::forward(val)))) -> decltype(from_json(j, std::forward(val))) { return from_json(j, std::forward(val)); } }; } // namespace detail #ifndef JSON_HAS_CPP_17 /// namespace to hold default `from_json` function /// to see why this is required: /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces) { #endif JSON_INLINE_VARIABLE constexpr const auto& from_json = // NOLINT(misc-definitions-in-headers) detail::static_const::value; #ifndef JSON_HAS_CPP_17 } // namespace #endif NLOHMANN_JSON_NAMESPACE_END ================================================ FILE: Libs/nlohmann/detail/conversions/to_chars.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2009 Florian Loitsch // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include // array #include // signbit, isfinite #include // intN_t, uintN_t #include // memcpy, memmove #include // numeric_limits #include // conditional #include NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { /*! @brief implements the Grisu2 algorithm for binary to decimal floating-point conversion. This implementation is a slightly modified version of the reference implementation which may be obtained from http://florian.loitsch.com/publications (bench.tar.gz). The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch. For a detailed description of the algorithm see: [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming Language Design and Implementation, PLDI 2010 [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately", Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language Design and Implementation, PLDI 1996 */ namespace dtoa_impl { template Target reinterpret_bits(const Source source) { static_assert(sizeof(Target) == sizeof(Source), "size mismatch"); Target target; std::memcpy(&target, &source, sizeof(Source)); return target; } struct diyfp // f * 2^e { static constexpr int kPrecision = 64; // = q std::uint64_t f = 0; int e = 0; constexpr diyfp(std::uint64_t f_, int e_) noexcept : f(f_), e(e_) {} /*! @brief returns x - y @pre x.e == y.e and x.f >= y.f */ static diyfp sub(const diyfp& x, const diyfp& y) noexcept { JSON_ASSERT(x.e == y.e); JSON_ASSERT(x.f >= y.f); return {x.f - y.f, x.e}; } /*! @brief returns x * y @note The result is rounded. (Only the upper q bits are returned.) */ static diyfp mul(const diyfp& x, const diyfp& y) noexcept { static_assert(kPrecision == 64, "internal error"); // Computes: // f = round((x.f * y.f) / 2^q) // e = x.e + y.e + q // Emulate the 64-bit * 64-bit multiplication: // // p = u * v // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi) // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi ) // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 ) // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 ) // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3) // = (p0_lo ) + 2^32 (Q ) + 2^64 (H ) // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H ) // // (Since Q might be larger than 2^32 - 1) // // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H) // // (Q_hi + H does not overflow a 64-bit int) // // = p_lo + 2^64 p_hi const std::uint64_t u_lo = x.f & 0xFFFFFFFFu; const std::uint64_t u_hi = x.f >> 32u; const std::uint64_t v_lo = y.f & 0xFFFFFFFFu; const std::uint64_t v_hi = y.f >> 32u; const std::uint64_t p0 = u_lo * v_lo; const std::uint64_t p1 = u_lo * v_hi; const std::uint64_t p2 = u_hi * v_lo; const std::uint64_t p3 = u_hi * v_hi; const std::uint64_t p0_hi = p0 >> 32u; const std::uint64_t p1_lo = p1 & 0xFFFFFFFFu; const std::uint64_t p1_hi = p1 >> 32u; const std::uint64_t p2_lo = p2 & 0xFFFFFFFFu; const std::uint64_t p2_hi = p2 >> 32u; std::uint64_t Q = p0_hi + p1_lo + p2_lo; // The full product might now be computed as // // p_hi = p3 + p2_hi + p1_hi + (Q >> 32) // p_lo = p0_lo + (Q << 32) // // But in this particular case here, the full p_lo is not required. // Effectively we only need to add the highest bit in p_lo to p_hi (and // Q_hi + 1 does not overflow). Q += std::uint64_t{1} << (64u - 32u - 1u); // round, ties up const std::uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32u); return {h, x.e + y.e + 64}; } /*! @brief normalize x such that the significand is >= 2^(q-1) @pre x.f != 0 */ static diyfp normalize(diyfp x) noexcept { JSON_ASSERT(x.f != 0); while ((x.f >> 63u) == 0) { x.f <<= 1u; x.e--; } return x; } /*! @brief normalize x such that the result has the exponent E @pre e >= x.e and the upper e - x.e bits of x.f must be zero. */ static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept { const int delta = x.e - target_exponent; JSON_ASSERT(delta >= 0); JSON_ASSERT(((x.f << delta) >> delta) == x.f); return {x.f << delta, target_exponent}; } }; struct boundaries { diyfp w; diyfp minus; diyfp plus; }; /*! Compute the (normalized) diyfp representing the input number 'value' and its boundaries. @pre value must be finite and positive */ template boundaries compute_boundaries(FloatType value) { JSON_ASSERT(std::isfinite(value)); JSON_ASSERT(value > 0); // Convert the IEEE representation into a diyfp. // // If v is denormal: // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1)) // If v is normalized: // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1)) static_assert(std::numeric_limits::is_iec559, "internal error: dtoa_short requires an IEEE-754 floating-point implementation"); constexpr int kPrecision = std::numeric_limits::digits; // = p (includes the hidden bit) constexpr int kBias = std::numeric_limits::max_exponent - 1 + (kPrecision - 1); constexpr int kMinExp = 1 - kBias; constexpr std::uint64_t kHiddenBit = std::uint64_t{1} << (kPrecision - 1); // = 2^(p-1) using bits_type = typename std::conditional::type; const auto bits = static_cast(reinterpret_bits(value)); const std::uint64_t E = bits >> (kPrecision - 1); const std::uint64_t F = bits & (kHiddenBit - 1); const bool is_denormal = E == 0; const diyfp v = is_denormal ? diyfp(F, kMinExp) : diyfp(F + kHiddenBit, static_cast(E) - kBias); // Compute the boundaries m- and m+ of the floating-point value // v = f * 2^e. // // Determine v- and v+, the floating-point predecessor and successor if v, // respectively. // // v- = v - 2^e if f != 2^(p-1) or e == e_min (A) // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B) // // v+ = v + 2^e // // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_ // between m- and m+ round to v, regardless of how the input rounding // algorithm breaks ties. // // ---+-------------+-------------+-------------+-------------+--- (A) // v- m- v m+ v+ // // -----------------+------+------+-------------+-------------+--- (B) // v- m- v m+ v+ const bool lower_boundary_is_closer = F == 0 && E > 1; const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1); const diyfp m_minus = lower_boundary_is_closer ? diyfp(4 * v.f - 1, v.e - 2) // (B) : diyfp(2 * v.f - 1, v.e - 1); // (A) // Determine the normalized w+ = m+. const diyfp w_plus = diyfp::normalize(m_plus); // Determine w- = m- such that e_(w-) = e_(w+). const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e); return {diyfp::normalize(v), w_minus, w_plus}; } // Given normalized diyfp w, Grisu needs to find a (normalized) cached // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies // within a certain range [alpha, gamma] (Definition 3.2 from [1]) // // alpha <= e = e_c + e_w + q <= gamma // // or // // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q // <= f_c * f_w * 2^gamma // // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies // // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma // // or // // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma) // // The choice of (alpha,gamma) determines the size of the table and the form of // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well // in practice: // // The idea is to cut the number c * w = f * 2^e into two parts, which can be // processed independently: An integral part p1, and a fractional part p2: // // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e // = (f div 2^-e) + (f mod 2^-e) * 2^e // = p1 + p2 * 2^e // // The conversion of p1 into decimal form requires a series of divisions and // modulos by (a power of) 10. These operations are faster for 32-bit than for // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be // achieved by choosing // // -e >= 32 or e <= -32 := gamma // // In order to convert the fractional part // // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ... // // into decimal form, the fraction is repeatedly multiplied by 10 and the digits // d[-i] are extracted in order: // // (10 * p2) div 2^-e = d[-1] // (10 * p2) mod 2^-e = d[-2] / 10^1 + ... // // The multiplication by 10 must not overflow. It is sufficient to choose // // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64. // // Since p2 = f mod 2^-e < 2^-e, // // -e <= 60 or e >= -60 := alpha constexpr int kAlpha = -60; constexpr int kGamma = -32; struct cached_power // c = f * 2^e ~= 10^k { std::uint64_t f; int e; int k; }; /*! For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c satisfies (Definition 3.2 from [1]) alpha <= e_c + e + q <= gamma. */ inline cached_power get_cached_power_for_binary_exponent(int e) { // Now // // alpha <= e_c + e + q <= gamma (1) // ==> f_c * 2^alpha <= c * 2^e * 2^q // // and since the c's are normalized, 2^(q-1) <= f_c, // // ==> 2^(q - 1 + alpha) <= c * 2^(e + q) // ==> 2^(alpha - e - 1) <= c // // If c were an exact power of ten, i.e. c = 10^k, one may determine k as // // k = ceil( log_10( 2^(alpha - e - 1) ) ) // = ceil( (alpha - e - 1) * log_10(2) ) // // From the paper: // "In theory the result of the procedure could be wrong since c is rounded, // and the computation itself is approximated [...]. In practice, however, // this simple function is sufficient." // // For IEEE double precision floating-point numbers converted into // normalized diyfp's w = f * 2^e, with q = 64, // // e >= -1022 (min IEEE exponent) // -52 (p - 1) // -52 (p - 1, possibly normalize denormal IEEE numbers) // -11 (normalize the diyfp) // = -1137 // // and // // e <= +1023 (max IEEE exponent) // -52 (p - 1) // -11 (normalize the diyfp) // = 960 // // This binary exponent range [-1137,960] results in a decimal exponent // range [-307,324]. One does not need to store a cached power for each // k in this range. For each such k it suffices to find a cached power // such that the exponent of the product lies in [alpha,gamma]. // This implies that the difference of the decimal exponents of adjacent // table entries must be less than or equal to // // floor( (gamma - alpha) * log_10(2) ) = 8. // // (A smaller distance gamma-alpha would require a larger table.) // NB: // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34. constexpr int kCachedPowersMinDecExp = -300; constexpr int kCachedPowersDecStep = 8; static constexpr std::array kCachedPowers = { { { 0xAB70FE17C79AC6CA, -1060, -300 }, { 0xFF77B1FCBEBCDC4F, -1034, -292 }, { 0xBE5691EF416BD60C, -1007, -284 }, { 0x8DD01FAD907FFC3C, -980, -276 }, { 0xD3515C2831559A83, -954, -268 }, { 0x9D71AC8FADA6C9B5, -927, -260 }, { 0xEA9C227723EE8BCB, -901, -252 }, { 0xAECC49914078536D, -874, -244 }, { 0x823C12795DB6CE57, -847, -236 }, { 0xC21094364DFB5637, -821, -228 }, { 0x9096EA6F3848984F, -794, -220 }, { 0xD77485CB25823AC7, -768, -212 }, { 0xA086CFCD97BF97F4, -741, -204 }, { 0xEF340A98172AACE5, -715, -196 }, { 0xB23867FB2A35B28E, -688, -188 }, { 0x84C8D4DFD2C63F3B, -661, -180 }, { 0xC5DD44271AD3CDBA, -635, -172 }, { 0x936B9FCEBB25C996, -608, -164 }, { 0xDBAC6C247D62A584, -582, -156 }, { 0xA3AB66580D5FDAF6, -555, -148 }, { 0xF3E2F893DEC3F126, -529, -140 }, { 0xB5B5ADA8AAFF80B8, -502, -132 }, { 0x87625F056C7C4A8B, -475, -124 }, { 0xC9BCFF6034C13053, -449, -116 }, { 0x964E858C91BA2655, -422, -108 }, { 0xDFF9772470297EBD, -396, -100 }, { 0xA6DFBD9FB8E5B88F, -369, -92 }, { 0xF8A95FCF88747D94, -343, -84 }, { 0xB94470938FA89BCF, -316, -76 }, { 0x8A08F0F8BF0F156B, -289, -68 }, { 0xCDB02555653131B6, -263, -60 }, { 0x993FE2C6D07B7FAC, -236, -52 }, { 0xE45C10C42A2B3B06, -210, -44 }, { 0xAA242499697392D3, -183, -36 }, { 0xFD87B5F28300CA0E, -157, -28 }, { 0xBCE5086492111AEB, -130, -20 }, { 0x8CBCCC096F5088CC, -103, -12 }, { 0xD1B71758E219652C, -77, -4 }, { 0x9C40000000000000, -50, 4 }, { 0xE8D4A51000000000, -24, 12 }, { 0xAD78EBC5AC620000, 3, 20 }, { 0x813F3978F8940984, 30, 28 }, { 0xC097CE7BC90715B3, 56, 36 }, { 0x8F7E32CE7BEA5C70, 83, 44 }, { 0xD5D238A4ABE98068, 109, 52 }, { 0x9F4F2726179A2245, 136, 60 }, { 0xED63A231D4C4FB27, 162, 68 }, { 0xB0DE65388CC8ADA8, 189, 76 }, { 0x83C7088E1AAB65DB, 216, 84 }, { 0xC45D1DF942711D9A, 242, 92 }, { 0x924D692CA61BE758, 269, 100 }, { 0xDA01EE641A708DEA, 295, 108 }, { 0xA26DA3999AEF774A, 322, 116 }, { 0xF209787BB47D6B85, 348, 124 }, { 0xB454E4A179DD1877, 375, 132 }, { 0x865B86925B9BC5C2, 402, 140 }, { 0xC83553C5C8965D3D, 428, 148 }, { 0x952AB45CFA97A0B3, 455, 156 }, { 0xDE469FBD99A05FE3, 481, 164 }, { 0xA59BC234DB398C25, 508, 172 }, { 0xF6C69A72A3989F5C, 534, 180 }, { 0xB7DCBF5354E9BECE, 561, 188 }, { 0x88FCF317F22241E2, 588, 196 }, { 0xCC20CE9BD35C78A5, 614, 204 }, { 0x98165AF37B2153DF, 641, 212 }, { 0xE2A0B5DC971F303A, 667, 220 }, { 0xA8D9D1535CE3B396, 694, 228 }, { 0xFB9B7CD9A4A7443C, 720, 236 }, { 0xBB764C4CA7A44410, 747, 244 }, { 0x8BAB8EEFB6409C1A, 774, 252 }, { 0xD01FEF10A657842C, 800, 260 }, { 0x9B10A4E5E9913129, 827, 268 }, { 0xE7109BFBA19C0C9D, 853, 276 }, { 0xAC2820D9623BF429, 880, 284 }, { 0x80444B5E7AA7CF85, 907, 292 }, { 0xBF21E44003ACDD2D, 933, 300 }, { 0x8E679C2F5E44FF8F, 960, 308 }, { 0xD433179D9C8CB841, 986, 316 }, { 0x9E19DB92B4E31BA9, 1013, 324 }, } }; // This computation gives exactly the same results for k as // k = ceil((kAlpha - e - 1) * 0.30102999566398114) // for |e| <= 1500, but doesn't require floating-point operations. // NB: log_10(2) ~= 78913 / 2^18 JSON_ASSERT(e >= -1500); JSON_ASSERT(e <= 1500); const int f = kAlpha - e - 1; const int k = (f * 78913) / (1 << 18) + static_cast(f > 0); const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep; JSON_ASSERT(index >= 0); JSON_ASSERT(static_cast(index) < kCachedPowers.size()); const cached_power cached = kCachedPowers[static_cast(index)]; JSON_ASSERT(kAlpha <= cached.e + e + 64); JSON_ASSERT(kGamma >= cached.e + e + 64); return cached; } /*! For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k. For n == 0, returns 1 and sets pow10 := 1. */ inline int find_largest_pow10(const std::uint32_t n, std::uint32_t& pow10) { // LCOV_EXCL_START if (n >= 1000000000) { pow10 = 1000000000; return 10; } // LCOV_EXCL_STOP if (n >= 100000000) { pow10 = 100000000; return 9; } if (n >= 10000000) { pow10 = 10000000; return 8; } if (n >= 1000000) { pow10 = 1000000; return 7; } if (n >= 100000) { pow10 = 100000; return 6; } if (n >= 10000) { pow10 = 10000; return 5; } if (n >= 1000) { pow10 = 1000; return 4; } if (n >= 100) { pow10 = 100; return 3; } if (n >= 10) { pow10 = 10; return 2; } pow10 = 1; return 1; } inline void grisu2_round(char* buf, int len, std::uint64_t dist, std::uint64_t delta, std::uint64_t rest, std::uint64_t ten_k) { JSON_ASSERT(len >= 1); JSON_ASSERT(dist <= delta); JSON_ASSERT(rest <= delta); JSON_ASSERT(ten_k > 0); // <--------------------------- delta ----> // <---- dist ---------> // --------------[------------------+-------------------]-------------- // M- w M+ // // ten_k // <------> // <---- rest ----> // --------------[------------------+----+--------------]-------------- // w V // = buf * 10^k // // ten_k represents a unit-in-the-last-place in the decimal representation // stored in buf. // Decrement buf by ten_k while this takes buf closer to w. // The tests are written in this order to avoid overflow in unsigned // integer arithmetic. while (rest < dist && delta - rest >= ten_k && (rest + ten_k < dist || dist - rest > rest + ten_k - dist)) { JSON_ASSERT(buf[len - 1] != '0'); buf[len - 1]--; rest += ten_k; } } /*! Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+. M- and M+ must be normalized and share the same exponent -60 <= e <= -32. */ inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent, diyfp M_minus, diyfp w, diyfp M_plus) { static_assert(kAlpha >= -60, "internal error"); static_assert(kGamma <= -32, "internal error"); // Generates the digits (and the exponent) of a decimal floating-point // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma. // // <--------------------------- delta ----> // <---- dist ---------> // --------------[------------------+-------------------]-------------- // M- w M+ // // Grisu2 generates the digits of M+ from left to right and stops as soon as // V is in [M-,M+]. JSON_ASSERT(M_plus.e >= kAlpha); JSON_ASSERT(M_plus.e <= kGamma); std::uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e) std::uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e) // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0): // // M+ = f * 2^e // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e // = ((p1 ) * 2^-e + (p2 )) * 2^e // = p1 + p2 * 2^e const diyfp one(std::uint64_t{1} << -M_plus.e, M_plus.e); auto p1 = static_cast(M_plus.f >> -one.e); // p1 = f div 2^-e (Since -e >= 32, p1 fits into a 32-bit int.) std::uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e // 1) // // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0] JSON_ASSERT(p1 > 0); std::uint32_t pow10{}; const int k = find_largest_pow10(p1, pow10); // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1) // // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1)) // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1)) // // M+ = p1 + p2 * 2^e // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e // = d[k-1] * 10^(k-1) + ( rest) * 2^e // // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0) // // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0] // // but stop as soon as // // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e int n = k; while (n > 0) { // Invariants: // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k) // pow10 = 10^(n-1) <= p1 < 10^n // const std::uint32_t d = p1 / pow10; // d = p1 div 10^(n-1) const std::uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1) // // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e) // JSON_ASSERT(d <= 9); buffer[length++] = static_cast('0' + d); // buffer := buffer * 10 + d // // M+ = buffer * 10^(n-1) + (r + p2 * 2^e) // p1 = r; n--; // // M+ = buffer * 10^n + (p1 + p2 * 2^e) // pow10 = 10^n // // Now check if enough digits have been generated. // Compute // // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e // // Note: // Since rest and delta share the same exponent e, it suffices to // compare the significands. const std::uint64_t rest = (std::uint64_t{p1} << -one.e) + p2; if (rest <= delta) { // V = buffer * 10^n, with M- <= V <= M+. decimal_exponent += n; // We may now just stop. But instead look if the buffer could be // decremented to bring V closer to w. // // pow10 = 10^n is now 1 ulp in the decimal representation V. // The rounding procedure works with diyfp's with an implicit // exponent of e. // // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e // const std::uint64_t ten_n = std::uint64_t{pow10} << -one.e; grisu2_round(buffer, length, dist, delta, rest, ten_n); return; } pow10 /= 10; // // pow10 = 10^(n-1) <= p1 < 10^n // Invariants restored. } // 2) // // The digits of the integral part have been generated: // // M+ = d[k-1]...d[1]d[0] + p2 * 2^e // = buffer + p2 * 2^e // // Now generate the digits of the fractional part p2 * 2^e. // // Note: // No decimal point is generated: the exponent is adjusted instead. // // p2 actually represents the fraction // // p2 * 2^e // = p2 / 2^-e // = d[-1] / 10^1 + d[-2] / 10^2 + ... // // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...) // // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...) // // using // // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e) // = ( d) * 2^-e + ( r) // // or // 10^m * p2 * 2^e = d + r * 2^e // // i.e. // // M+ = buffer + p2 * 2^e // = buffer + 10^-m * (d + r * 2^e) // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e // // and stop as soon as 10^-m * r * 2^e <= delta * 2^e JSON_ASSERT(p2 > delta); int m = 0; for (;;) { // Invariant: // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e // = buffer * 10^-m + 10^-m * (p2 ) * 2^e // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e // JSON_ASSERT(p2 <= (std::numeric_limits::max)() / 10); p2 *= 10; const std::uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e const std::uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e // // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e)) // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e // JSON_ASSERT(d <= 9); buffer[length++] = static_cast('0' + d); // buffer := buffer * 10 + d // // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e // p2 = r; m++; // // M+ = buffer * 10^-m + 10^-m * p2 * 2^e // Invariant restored. // Check if enough digits have been generated. // // 10^-m * p2 * 2^e <= delta * 2^e // p2 * 2^e <= 10^m * delta * 2^e // p2 <= 10^m * delta delta *= 10; dist *= 10; if (p2 <= delta) { break; } } // V = buffer * 10^-m, with M- <= V <= M+. decimal_exponent -= m; // 1 ulp in the decimal representation is now 10^-m. // Since delta and dist are now scaled by 10^m, we need to do the // same with ulp in order to keep the units in sync. // // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e // const std::uint64_t ten_m = one.f; grisu2_round(buffer, length, dist, delta, p2, ten_m); // By construction this algorithm generates the shortest possible decimal // number (Loitsch, Theorem 6.2) which rounds back to w. // For an input number of precision p, at least // // N = 1 + ceil(p * log_10(2)) // // decimal digits are sufficient to identify all binary floating-point // numbers (Matula, "In-and-Out conversions"). // This implies that the algorithm does not produce more than N decimal // digits. // // N = 17 for p = 53 (IEEE double precision) // N = 9 for p = 24 (IEEE single precision) } /*! v = buf * 10^decimal_exponent len is the length of the buffer (number of decimal digits) The buffer must be large enough, i.e. >= max_digits10. */ JSON_HEDLEY_NON_NULL(1) inline void grisu2(char* buf, int& len, int& decimal_exponent, diyfp m_minus, diyfp v, diyfp m_plus) { JSON_ASSERT(m_plus.e == m_minus.e); JSON_ASSERT(m_plus.e == v.e); // --------(-----------------------+-----------------------)-------- (A) // m- v m+ // // --------------------(-----------+-----------------------)-------- (B) // m- v m+ // // First scale v (and m- and m+) such that the exponent is in the range // [alpha, gamma]. const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e); const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma] const diyfp w = diyfp::mul(v, c_minus_k); const diyfp w_minus = diyfp::mul(m_minus, c_minus_k); const diyfp w_plus = diyfp::mul(m_plus, c_minus_k); // ----(---+---)---------------(---+---)---------------(---+---)---- // w- w w+ // = c*m- = c*v = c*m+ // // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and // w+ are now off by a small amount. // In fact: // // w - v * 10^k < 1 ulp // // To account for this inaccuracy, add resp. subtract 1 ulp. // // --------+---[---------------(---+---)---------------]---+-------- // w- M- w M+ w+ // // Now any number in [M-, M+] (bounds included) will round to w when input, // regardless of how the input rounding algorithm breaks ties. // // And digit_gen generates the shortest possible such number in [M-, M+]. // Note that this does not mean that Grisu2 always generates the shortest // possible number in the interval (m-, m+). const diyfp M_minus(w_minus.f + 1, w_minus.e); const diyfp M_plus (w_plus.f - 1, w_plus.e ); decimal_exponent = -cached.k; // = -(-k) = k grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus); } /*! v = buf * 10^decimal_exponent len is the length of the buffer (number of decimal digits) The buffer must be large enough, i.e. >= max_digits10. */ template JSON_HEDLEY_NON_NULL(1) void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value) { static_assert(diyfp::kPrecision >= std::numeric_limits::digits + 3, "internal error: not enough precision"); JSON_ASSERT(std::isfinite(value)); JSON_ASSERT(value > 0); // If the neighbors (and boundaries) of 'value' are always computed for double-precision // numbers, all float's can be recovered using strtod (and strtof). However, the resulting // decimal representations are not exactly "short". // // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars) // says "value is converted to a string as if by std::sprintf in the default ("C") locale" // and since sprintf promotes floats to doubles, I think this is exactly what 'std::to_chars' // does. // On the other hand, the documentation for 'std::to_chars' requires that "parsing the // representation using the corresponding std::from_chars function recovers value exactly". That // indicates that single precision floating-point numbers should be recovered using // 'std::strtof'. // // NB: If the neighbors are computed for single-precision numbers, there is a single float // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision // value is off by 1 ulp. #if 0 // NOLINT(readability-avoid-unconditional-preprocessor-if) const boundaries w = compute_boundaries(static_cast(value)); #else const boundaries w = compute_boundaries(value); #endif grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus); } /*! @brief appends a decimal representation of e to buf @return a pointer to the element following the exponent. @pre -1000 < e < 1000 */ JSON_HEDLEY_NON_NULL(1) JSON_HEDLEY_RETURNS_NON_NULL inline char* append_exponent(char* buf, int e) { JSON_ASSERT(e > -1000); JSON_ASSERT(e < 1000); if (e < 0) { e = -e; *buf++ = '-'; } else { *buf++ = '+'; } auto k = static_cast(e); if (k < 10) { // Always print at least two digits in the exponent. // This is for compatibility with printf("%g"). *buf++ = '0'; *buf++ = static_cast('0' + k); } else if (k < 100) { *buf++ = static_cast('0' + k / 10); k %= 10; *buf++ = static_cast('0' + k); } else { *buf++ = static_cast('0' + k / 100); k %= 100; *buf++ = static_cast('0' + k / 10); k %= 10; *buf++ = static_cast('0' + k); } return buf; } /*! @brief prettify v = buf * 10^decimal_exponent If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point notation. Otherwise it will be printed in exponential notation. @pre min_exp < 0 @pre max_exp > 0 */ JSON_HEDLEY_NON_NULL(1) JSON_HEDLEY_RETURNS_NON_NULL inline char* format_buffer(char* buf, int len, int decimal_exponent, int min_exp, int max_exp) { JSON_ASSERT(min_exp < 0); JSON_ASSERT(max_exp > 0); const int k = len; const int n = len + decimal_exponent; // v = buf * 10^(n-k) // k is the length of the buffer (number of decimal digits) // n is the position of the decimal point relative to the start of the buffer. if (k <= n && n <= max_exp) { // digits[000] // len <= max_exp + 2 std::memset(buf + k, '0', static_cast(n) - static_cast(k)); // Make it look like a floating-point number (#362, #378) buf[n + 0] = '.'; buf[n + 1] = '0'; return buf + (static_cast(n) + 2); } if (0 < n && n <= max_exp) { // dig.its // len <= max_digits10 + 1 JSON_ASSERT(k > n); std::memmove(buf + (static_cast(n) + 1), buf + n, static_cast(k) - static_cast(n)); buf[n] = '.'; return buf + (static_cast(k) + 1U); } if (min_exp < n && n <= 0) { // 0.[000]digits // len <= 2 + (-min_exp - 1) + max_digits10 std::memmove(buf + (2 + static_cast(-n)), buf, static_cast(k)); buf[0] = '0'; buf[1] = '.'; std::memset(buf + 2, '0', static_cast(-n)); return buf + (2U + static_cast(-n) + static_cast(k)); } if (k == 1) { // dE+123 // len <= 1 + 5 buf += 1; } else { // d.igitsE+123 // len <= max_digits10 + 1 + 5 std::memmove(buf + 2, buf + 1, static_cast(k) - 1); buf[1] = '.'; buf += 1 + static_cast(k); } *buf++ = 'e'; return append_exponent(buf, n - 1); } } // namespace dtoa_impl /*! @brief generates a decimal representation of the floating-point number value in [first, last). The format of the resulting decimal representation is similar to printf's %g format. Returns an iterator pointing past-the-end of the decimal representation. @note The input number must be finite, i.e. NaN's and Inf's are not supported. @note The buffer must be large enough. @note The result is NOT null-terminated. */ template JSON_HEDLEY_NON_NULL(1, 2) JSON_HEDLEY_RETURNS_NON_NULL char* to_chars(char* first, const char* last, FloatType value) { static_cast(last); // maybe unused - fix warning JSON_ASSERT(std::isfinite(value)); // Use signbit(value) instead of (value < 0) since signbit works for -0. if (std::signbit(value)) { value = -value; *first++ = '-'; } #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wfloat-equal" #endif if (value == 0) // +-0 { *first++ = '0'; // Make it look like a floating-point number (#362, #378) *first++ = '.'; *first++ = '0'; return first; } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif JSON_ASSERT(last - first >= std::numeric_limits::max_digits10); // Compute v = buffer * 10^decimal_exponent. // The decimal digits are stored in the buffer, which needs to be interpreted // as an unsigned decimal integer. // len is the length of the buffer, i.e. the number of decimal digits. int len = 0; int decimal_exponent = 0; dtoa_impl::grisu2(first, len, decimal_exponent, value); JSON_ASSERT(len <= std::numeric_limits::max_digits10); // Format the buffer like printf("%.*g", prec, value) constexpr int kMinExp = -4; // Use digits10 here to increase compatibility with version 2. constexpr int kMaxExp = std::numeric_limits::digits10; JSON_ASSERT(last - first >= kMaxExp + 2); JSON_ASSERT(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits::max_digits10); JSON_ASSERT(last - first >= std::numeric_limits::max_digits10 + 6); return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp); } } // namespace detail NLOHMANN_JSON_NAMESPACE_END ================================================ FILE: Libs/nlohmann/detail/conversions/to_json.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include // copy #include // begin, end #include // string #include // tuple, get #include // is_same, is_constructible, is_floating_point, is_enum, underlying_type #include // move, forward, declval, pair #include // valarray #include // vector #include #include #include #include #include #include NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { ////////////////// // constructors // ////////////////// /* * Note all external_constructor<>::construct functions need to call * j.m_data.m_value.destroy(j.m_data.m_type) to avoid a memory leak in case j contains an * allocated value (e.g., a string). See bug issue * https://github.com/nlohmann/json/issues/2865 for more information. */ template struct external_constructor; template<> struct external_constructor { template static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept { j.m_data.m_value.destroy(j.m_data.m_type); j.m_data.m_type = value_t::boolean; j.m_data.m_value = b; j.assert_invariant(); } }; template<> struct external_constructor { template static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s) { j.m_data.m_value.destroy(j.m_data.m_type); j.m_data.m_type = value_t::string; j.m_data.m_value = s; j.assert_invariant(); } template static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s) { j.m_data.m_value.destroy(j.m_data.m_type); j.m_data.m_type = value_t::string; j.m_data.m_value = std::move(s); j.assert_invariant(); } template < typename BasicJsonType, typename CompatibleStringType, enable_if_t < !std::is_same::value, int > = 0 > static void construct(BasicJsonType& j, const CompatibleStringType& str) { j.m_data.m_value.destroy(j.m_data.m_type); j.m_data.m_type = value_t::string; j.m_data.m_value.string = j.template create(str); j.assert_invariant(); } }; template<> struct external_constructor { template static void construct(BasicJsonType& j, const typename BasicJsonType::binary_t& b) { j.m_data.m_value.destroy(j.m_data.m_type); j.m_data.m_type = value_t::binary; j.m_data.m_value = typename BasicJsonType::binary_t(b); j.assert_invariant(); } template static void construct(BasicJsonType& j, typename BasicJsonType::binary_t&& b) { j.m_data.m_value.destroy(j.m_data.m_type); j.m_data.m_type = value_t::binary; j.m_data.m_value = typename BasicJsonType::binary_t(std::move(b)); j.assert_invariant(); } }; template<> struct external_constructor { template static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept { j.m_data.m_value.destroy(j.m_data.m_type); j.m_data.m_type = value_t::number_float; j.m_data.m_value = val; j.assert_invariant(); } }; template<> struct external_constructor { template static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept { j.m_data.m_value.destroy(j.m_data.m_type); j.m_data.m_type = value_t::number_unsigned; j.m_data.m_value = val; j.assert_invariant(); } }; template<> struct external_constructor { template static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept { j.m_data.m_value.destroy(j.m_data.m_type); j.m_data.m_type = value_t::number_integer; j.m_data.m_value = val; j.assert_invariant(); } }; template<> struct external_constructor { template static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr) { j.m_data.m_value.destroy(j.m_data.m_type); j.m_data.m_type = value_t::array; j.m_data.m_value = arr; j.set_parents(); j.assert_invariant(); } template static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr) { j.m_data.m_value.destroy(j.m_data.m_type); j.m_data.m_type = value_t::array; j.m_data.m_value = std::move(arr); j.set_parents(); j.assert_invariant(); } template < typename BasicJsonType, typename CompatibleArrayType, enable_if_t < !std::is_same::value, int > = 0 > static void construct(BasicJsonType& j, const CompatibleArrayType& arr) { using std::begin; using std::end; j.m_data.m_value.destroy(j.m_data.m_type); j.m_data.m_type = value_t::array; j.m_data.m_value.array = j.template create(begin(arr), end(arr)); j.set_parents(); j.assert_invariant(); } template static void construct(BasicJsonType& j, const std::vector& arr) { j.m_data.m_value.destroy(j.m_data.m_type); j.m_data.m_type = value_t::array; j.m_data.m_value = value_t::array; j.m_data.m_value.array->reserve(arr.size()); for (const bool x : arr) { j.m_data.m_value.array->push_back(x); j.set_parent(j.m_data.m_value.array->back()); } j.assert_invariant(); } template::value, int> = 0> static void construct(BasicJsonType& j, const std::valarray& arr) { j.m_data.m_value.destroy(j.m_data.m_type); j.m_data.m_type = value_t::array; j.m_data.m_value = value_t::array; j.m_data.m_value.array->resize(arr.size()); if (arr.size() > 0) { std::copy(std::begin(arr), std::end(arr), j.m_data.m_value.array->begin()); } j.set_parents(); j.assert_invariant(); } }; template<> struct external_constructor { template static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj) { j.m_data.m_value.destroy(j.m_data.m_type); j.m_data.m_type = value_t::object; j.m_data.m_value = obj; j.set_parents(); j.assert_invariant(); } template static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj) { j.m_data.m_value.destroy(j.m_data.m_type); j.m_data.m_type = value_t::object; j.m_data.m_value = std::move(obj); j.set_parents(); j.assert_invariant(); } template < typename BasicJsonType, typename CompatibleObjectType, enable_if_t < !std::is_same::value, int > = 0 > static void construct(BasicJsonType& j, const CompatibleObjectType& obj) { using std::begin; using std::end; j.m_data.m_value.destroy(j.m_data.m_type); j.m_data.m_type = value_t::object; j.m_data.m_value.object = j.template create(begin(obj), end(obj)); j.set_parents(); j.assert_invariant(); } }; ///////////// // to_json // ///////////// template::value, int> = 0> inline void to_json(BasicJsonType& j, T b) noexcept { external_constructor::construct(j, b); } template < typename BasicJsonType, typename BoolRef, enable_if_t < ((std::is_same::reference, BoolRef>::value && !std::is_same ::reference, typename BasicJsonType::boolean_t&>::value) || (std::is_same::const_reference, BoolRef>::value && !std::is_same ::const_reference>, typename BasicJsonType::boolean_t >::value)) && std::is_convertible::value, int > = 0 > inline void to_json(BasicJsonType& j, const BoolRef& b) noexcept { external_constructor::construct(j, static_cast(b)); } template::value, int> = 0> inline void to_json(BasicJsonType& j, const CompatibleString& s) { external_constructor::construct(j, s); } template inline void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s) { external_constructor::construct(j, std::move(s)); } template::value, int> = 0> inline void to_json(BasicJsonType& j, FloatType val) noexcept { external_constructor::construct(j, static_cast(val)); } template::value, int> = 0> inline void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept { external_constructor::construct(j, static_cast(val)); } template::value, int> = 0> inline void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept { external_constructor::construct(j, static_cast(val)); } #if !JSON_DISABLE_ENUM_SERIALIZATION template::value, int> = 0> inline void to_json(BasicJsonType& j, EnumType e) noexcept { using underlying_type = typename std::underlying_type::type; static constexpr value_t integral_value_t = std::is_unsigned::value ? value_t::number_unsigned : value_t::number_integer; external_constructor::construct(j, static_cast(e)); } #endif // JSON_DISABLE_ENUM_SERIALIZATION template inline void to_json(BasicJsonType& j, const std::vector& e) { external_constructor::construct(j, e); } template < typename BasicJsonType, typename CompatibleArrayType, enable_if_t < is_compatible_array_type::value&& !is_compatible_object_type::value&& !is_compatible_string_type::value&& !std::is_same::value&& !is_basic_json::value, int > = 0 > inline void to_json(BasicJsonType& j, const CompatibleArrayType& arr) { external_constructor::construct(j, arr); } template inline void to_json(BasicJsonType& j, const typename BasicJsonType::binary_t& bin) { external_constructor::construct(j, bin); } template::value, int> = 0> inline void to_json(BasicJsonType& j, const std::valarray& arr) { external_constructor::construct(j, std::move(arr)); } template inline void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr) { external_constructor::construct(j, std::move(arr)); } template < typename BasicJsonType, typename CompatibleObjectType, enable_if_t < is_compatible_object_type::value&& !is_basic_json::value, int > = 0 > inline void to_json(BasicJsonType& j, const CompatibleObjectType& obj) { external_constructor::construct(j, obj); } template inline void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj) { external_constructor::construct(j, std::move(obj)); } template < typename BasicJsonType, typename T, std::size_t N, enable_if_t < !std::is_constructible::value, // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) int > = 0 > inline void to_json(BasicJsonType& j, const T(&arr)[N]) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) { external_constructor::construct(j, arr); } template < typename BasicJsonType, typename T1, typename T2, enable_if_t < std::is_constructible::value&& std::is_constructible::value, int > = 0 > inline void to_json(BasicJsonType& j, const std::pair& p) { j = { p.first, p.second }; } // for https://github.com/nlohmann/json/pull/1134 template>::value, int> = 0> inline void to_json(BasicJsonType& j, const T& b) { j = { {b.key(), b.value()} }; } template inline void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence /*unused*/) { j = { std::get(t)... }; } template::value, int > = 0> inline void to_json(BasicJsonType& j, const T& t) { to_json_tuple_impl(j, t, make_index_sequence::value> {}); } #if JSON_HAS_FILESYSTEM || JSON_HAS_EXPERIMENTAL_FILESYSTEM template inline void to_json(BasicJsonType& j, const std_fs::path& p) { j = p.string(); } #endif struct to_json_fn { template auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward(val)))) -> decltype(to_json(j, std::forward(val)), void()) { return to_json(j, std::forward(val)); } }; } // namespace detail #ifndef JSON_HAS_CPP_17 /// namespace to hold default `to_json` function /// to see why this is required: /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html namespace // NOLINT(cert-dcl59-cpp,fuchsia-header-anon-namespaces,google-build-namespaces) { #endif JSON_INLINE_VARIABLE constexpr const auto& to_json = // NOLINT(misc-definitions-in-headers) detail::static_const::value; #ifndef JSON_HAS_CPP_17 } // namespace #endif NLOHMANN_JSON_NAMESPACE_END ================================================ FILE: Libs/nlohmann/detail/exceptions.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include // nullptr_t #include // exception #if JSON_DIAGNOSTICS #include // accumulate #endif #include // runtime_error #include // to_string #include // vector #include #include #include #include #include #include #include NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { //////////////// // exceptions // //////////////// /// @brief general exception of the @ref basic_json class /// @sa https://json.nlohmann.me/api/basic_json/exception/ class exception : public std::exception { public: /// returns the explanatory string const char* what() const noexcept override { return m.what(); } /// the id of the exception const int id; // NOLINT(cppcoreguidelines-non-private-member-variables-in-classes) protected: JSON_HEDLEY_NON_NULL(3) exception(int id_, const char* what_arg) : id(id_), m(what_arg) {} // NOLINT(bugprone-throw-keyword-missing) static std::string name(const std::string& ename, int id_) { return concat("[json.exception.", ename, '.', std::to_string(id_), "] "); } static std::string diagnostics(std::nullptr_t /*leaf_element*/) { return ""; } template static std::string diagnostics(const BasicJsonType* leaf_element) { #if JSON_DIAGNOSTICS std::vector tokens; for (const auto* current = leaf_element; current != nullptr && current->m_parent != nullptr; current = current->m_parent) { switch (current->m_parent->type()) { case value_t::array: { for (std::size_t i = 0; i < current->m_parent->m_data.m_value.array->size(); ++i) { if (¤t->m_parent->m_data.m_value.array->operator[](i) == current) { tokens.emplace_back(std::to_string(i)); break; } } break; } case value_t::object: { for (const auto& element : *current->m_parent->m_data.m_value.object) { if (&element.second == current) { tokens.emplace_back(element.first.c_str()); break; } } break; } case value_t::null: // LCOV_EXCL_LINE case value_t::string: // LCOV_EXCL_LINE case value_t::boolean: // LCOV_EXCL_LINE case value_t::number_integer: // LCOV_EXCL_LINE case value_t::number_unsigned: // LCOV_EXCL_LINE case value_t::number_float: // LCOV_EXCL_LINE case value_t::binary: // LCOV_EXCL_LINE case value_t::discarded: // LCOV_EXCL_LINE default: // LCOV_EXCL_LINE break; // LCOV_EXCL_LINE } } if (tokens.empty()) { return ""; } auto str = std::accumulate(tokens.rbegin(), tokens.rend(), std::string{}, [](const std::string & a, const std::string & b) { return concat(a, '/', detail::escape(b)); }); return concat('(', str, ") "); #else static_cast(leaf_element); return ""; #endif } private: /// an exception object as storage for error messages std::runtime_error m; }; /// @brief exception indicating a parse error /// @sa https://json.nlohmann.me/api/basic_json/parse_error/ class parse_error : public exception { public: /*! @brief create a parse error exception @param[in] id_ the id of the exception @param[in] pos the position where the error occurred (or with chars_read_total=0 if the position cannot be determined) @param[in] what_arg the explanatory string @return parse_error object */ template::value, int> = 0> static parse_error create(int id_, const position_t& pos, const std::string& what_arg, BasicJsonContext context) { const std::string w = concat(exception::name("parse_error", id_), "parse error", position_string(pos), ": ", exception::diagnostics(context), what_arg); return {id_, pos.chars_read_total, w.c_str()}; } template::value, int> = 0> static parse_error create(int id_, std::size_t byte_, const std::string& what_arg, BasicJsonContext context) { const std::string w = concat(exception::name("parse_error", id_), "parse error", (byte_ != 0 ? (concat(" at byte ", std::to_string(byte_))) : ""), ": ", exception::diagnostics(context), what_arg); return {id_, byte_, w.c_str()}; } /*! @brief byte index of the parse error The byte index of the last read character in the input file. @note For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector (CBOR or MessagePack). */ const std::size_t byte; private: parse_error(int id_, std::size_t byte_, const char* what_arg) : exception(id_, what_arg), byte(byte_) {} static std::string position_string(const position_t& pos) { return concat(" at line ", std::to_string(pos.lines_read + 1), ", column ", std::to_string(pos.chars_read_current_line)); } }; /// @brief exception indicating errors with iterators /// @sa https://json.nlohmann.me/api/basic_json/invalid_iterator/ class invalid_iterator : public exception { public: template::value, int> = 0> static invalid_iterator create(int id_, const std::string& what_arg, BasicJsonContext context) { const std::string w = concat(exception::name("invalid_iterator", id_), exception::diagnostics(context), what_arg); return {id_, w.c_str()}; } private: JSON_HEDLEY_NON_NULL(3) invalid_iterator(int id_, const char* what_arg) : exception(id_, what_arg) {} }; /// @brief exception indicating executing a member function with a wrong type /// @sa https://json.nlohmann.me/api/basic_json/type_error/ class type_error : public exception { public: template::value, int> = 0> static type_error create(int id_, const std::string& what_arg, BasicJsonContext context) { const std::string w = concat(exception::name("type_error", id_), exception::diagnostics(context), what_arg); return {id_, w.c_str()}; } private: JSON_HEDLEY_NON_NULL(3) type_error(int id_, const char* what_arg) : exception(id_, what_arg) {} }; /// @brief exception indicating access out of the defined range /// @sa https://json.nlohmann.me/api/basic_json/out_of_range/ class out_of_range : public exception { public: template::value, int> = 0> static out_of_range create(int id_, const std::string& what_arg, BasicJsonContext context) { const std::string w = concat(exception::name("out_of_range", id_), exception::diagnostics(context), what_arg); return {id_, w.c_str()}; } private: JSON_HEDLEY_NON_NULL(3) out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {} }; /// @brief exception indicating other library errors /// @sa https://json.nlohmann.me/api/basic_json/other_error/ class other_error : public exception { public: template::value, int> = 0> static other_error create(int id_, const std::string& what_arg, BasicJsonContext context) { const std::string w = concat(exception::name("other_error", id_), exception::diagnostics(context), what_arg); return {id_, w.c_str()}; } private: JSON_HEDLEY_NON_NULL(3) other_error(int id_, const char* what_arg) : exception(id_, what_arg) {} }; } // namespace detail NLOHMANN_JSON_NAMESPACE_END ================================================ FILE: Libs/nlohmann/detail/hash.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include // uint8_t #include // size_t #include // hash #include #include NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { // boost::hash_combine inline std::size_t combine(std::size_t seed, std::size_t h) noexcept { seed ^= h + 0x9e3779b9 + (seed << 6U) + (seed >> 2U); return seed; } /*! @brief hash a JSON value The hash function tries to rely on std::hash where possible. Furthermore, the type of the JSON value is taken into account to have different hash values for null, 0, 0U, and false, etc. @tparam BasicJsonType basic_json specialization @param j JSON value to hash @return hash value of j */ template std::size_t hash(const BasicJsonType& j) { using string_t = typename BasicJsonType::string_t; using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; const auto type = static_cast(j.type()); switch (j.type()) { case BasicJsonType::value_t::null: case BasicJsonType::value_t::discarded: { return combine(type, 0); } case BasicJsonType::value_t::object: { auto seed = combine(type, j.size()); for (const auto& element : j.items()) { const auto h = std::hash {}(element.key()); seed = combine(seed, h); seed = combine(seed, hash(element.value())); } return seed; } case BasicJsonType::value_t::array: { auto seed = combine(type, j.size()); for (const auto& element : j) { seed = combine(seed, hash(element)); } return seed; } case BasicJsonType::value_t::string: { const auto h = std::hash {}(j.template get_ref()); return combine(type, h); } case BasicJsonType::value_t::boolean: { const auto h = std::hash {}(j.template get()); return combine(type, h); } case BasicJsonType::value_t::number_integer: { const auto h = std::hash {}(j.template get()); return combine(type, h); } case BasicJsonType::value_t::number_unsigned: { const auto h = std::hash {}(j.template get()); return combine(type, h); } case BasicJsonType::value_t::number_float: { const auto h = std::hash {}(j.template get()); return combine(type, h); } case BasicJsonType::value_t::binary: { auto seed = combine(type, j.get_binary().size()); const auto h = std::hash {}(j.get_binary().has_subtype()); seed = combine(seed, h); seed = combine(seed, static_cast(j.get_binary().subtype())); for (const auto byte : j.get_binary()) { seed = combine(seed, std::hash {}(byte)); } return seed; } default: // LCOV_EXCL_LINE JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE return 0; // LCOV_EXCL_LINE } } } // namespace detail NLOHMANN_JSON_NAMESPACE_END ================================================ FILE: Libs/nlohmann/detail/input/binary_reader.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include // generate_n #include // array #include // ldexp #include // size_t #include // uint8_t, uint16_t, uint32_t, uint64_t #include // snprintf #include // memcpy #include // back_inserter #include // numeric_limits #include // char_traits, string #include // make_pair, move #include // vector #include #include #include #include #include #include #include #include #include NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { /// how to treat CBOR tags enum class cbor_tag_handler_t { error, ///< throw a parse_error exception in case of a tag ignore, ///< ignore tags store ///< store tags as binary type }; /*! @brief determine system byte order @return true if and only if system's byte order is little endian @note from https://stackoverflow.com/a/1001328/266378 */ static inline bool little_endianness(int num = 1) noexcept { return *reinterpret_cast(&num) == 1; } /////////////////// // binary reader // /////////////////// /*! @brief deserialization of CBOR, MessagePack, and UBJSON values */ template> class binary_reader { using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; using json_sax_t = SAX; using char_type = typename InputAdapterType::char_type; using char_int_type = typename char_traits::int_type; public: /*! @brief create a binary reader @param[in] adapter input adapter to read from */ explicit binary_reader(InputAdapterType&& adapter, const input_format_t format = input_format_t::json) noexcept : ia(std::move(adapter)), input_format(format) { (void)detail::is_sax_static_asserts {}; } // make class move-only binary_reader(const binary_reader&) = delete; binary_reader(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) binary_reader& operator=(const binary_reader&) = delete; binary_reader& operator=(binary_reader&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) ~binary_reader() = default; /*! @param[in] format the binary format to parse @param[in] sax_ a SAX event processor @param[in] strict whether to expect the input to be consumed completed @param[in] tag_handler how to treat CBOR tags @return whether parsing was successful */ JSON_HEDLEY_NON_NULL(3) bool sax_parse(const input_format_t format, json_sax_t* sax_, const bool strict = true, const cbor_tag_handler_t tag_handler = cbor_tag_handler_t::error) { sax = sax_; bool result = false; switch (format) { case input_format_t::bson: result = parse_bson_internal(); break; case input_format_t::cbor: result = parse_cbor_internal(true, tag_handler); break; case input_format_t::msgpack: result = parse_msgpack_internal(); break; case input_format_t::ubjson: case input_format_t::bjdata: result = parse_ubjson_internal(); break; case input_format_t::json: // LCOV_EXCL_LINE default: // LCOV_EXCL_LINE JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE } // strict mode: next byte must be EOF if (result && strict) { if (input_format == input_format_t::ubjson || input_format == input_format_t::bjdata) { get_ignore_noop(); } else { get(); } if (JSON_HEDLEY_UNLIKELY(current != char_traits::eof())) { return sax->parse_error(chars_read, get_token_string(), parse_error::create(110, chars_read, exception_message(input_format, concat("expected end of input; last byte: 0x", get_token_string()), "value"), nullptr)); } } return result; } private: ////////// // BSON // ////////// /*! @brief Reads in a BSON-object and passes it to the SAX-parser. @return whether a valid BSON-value was passed to the SAX parser */ bool parse_bson_internal() { std::int32_t document_size{}; get_number(input_format_t::bson, document_size); if (JSON_HEDLEY_UNLIKELY(!sax->start_object(static_cast(-1)))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/false))) { return false; } return sax->end_object(); } /*! @brief Parses a C-style string from the BSON input. @param[in,out] result A reference to the string variable where the read string is to be stored. @return `true` if the \x00-byte indicating the end of the string was encountered before the EOF; false` indicates an unexpected EOF. */ bool get_bson_cstr(string_t& result) { auto out = std::back_inserter(result); while (true) { get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "cstring"))) { return false; } if (current == 0x00) { return true; } *out++ = static_cast(current); } } /*! @brief Parses a zero-terminated string of length @a len from the BSON input. @param[in] len The length (including the zero-byte at the end) of the string to be read. @param[in,out] result A reference to the string variable where the read string is to be stored. @tparam NumberType The type of the length @a len @pre len >= 1 @return `true` if the string was successfully parsed */ template bool get_bson_string(const NumberType len, string_t& result) { if (JSON_HEDLEY_UNLIKELY(len < 1)) { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, concat("string length must be at least 1, is ", std::to_string(len)), "string"), nullptr)); } return get_string(input_format_t::bson, len - static_cast(1), result) && get() != char_traits::eof(); } /*! @brief Parses a byte array input of length @a len from the BSON input. @param[in] len The length of the byte array to be read. @param[in,out] result A reference to the binary variable where the read array is to be stored. @tparam NumberType The type of the length @a len @pre len >= 0 @return `true` if the byte array was successfully parsed */ template bool get_bson_binary(const NumberType len, binary_t& result) { if (JSON_HEDLEY_UNLIKELY(len < 0)) { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, concat("byte array length cannot be negative, is ", std::to_string(len)), "binary"), nullptr)); } // All BSON binary values have a subtype std::uint8_t subtype{}; get_number(input_format_t::bson, subtype); result.set_subtype(subtype); return get_binary(input_format_t::bson, len, result); } /*! @brief Read a BSON document element of the given @a element_type. @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html @param[in] element_type_parse_position The position in the input stream, where the `element_type` was read. @warning Not all BSON element types are supported yet. An unsupported @a element_type will give rise to a parse_error.114: Unsupported BSON record type 0x... @return whether a valid BSON-object/array was passed to the SAX parser */ bool parse_bson_element_internal(const char_int_type element_type, const std::size_t element_type_parse_position) { switch (element_type) { case 0x01: // double { double number{}; return get_number(input_format_t::bson, number) && sax->number_float(static_cast(number), ""); } case 0x02: // string { std::int32_t len{}; string_t value; return get_number(input_format_t::bson, len) && get_bson_string(len, value) && sax->string(value); } case 0x03: // object { return parse_bson_internal(); } case 0x04: // array { return parse_bson_array(); } case 0x05: // binary { std::int32_t len{}; binary_t value; return get_number(input_format_t::bson, len) && get_bson_binary(len, value) && sax->binary(value); } case 0x08: // boolean { return sax->boolean(get() != 0); } case 0x0A: // null { return sax->null(); } case 0x10: // int32 { std::int32_t value{}; return get_number(input_format_t::bson, value) && sax->number_integer(value); } case 0x12: // int64 { std::int64_t value{}; return get_number(input_format_t::bson, value) && sax->number_integer(value); } default: // anything else not supported (yet) { std::array cr{{}}; static_cast((std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast(element_type))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) const std::string cr_str{cr.data()}; return sax->parse_error(element_type_parse_position, cr_str, parse_error::create(114, element_type_parse_position, concat("Unsupported BSON record type 0x", cr_str), nullptr)); } } } /*! @brief Read a BSON element list (as specified in the BSON-spec) The same binary layout is used for objects and arrays, hence it must be indicated with the argument @a is_array which one is expected (true --> array, false --> object). @param[in] is_array Determines if the element list being read is to be treated as an object (@a is_array == false), or as an array (@a is_array == true). @return whether a valid BSON-object/array was passed to the SAX parser */ bool parse_bson_element_list(const bool is_array) { string_t key; while (auto element_type = get()) { if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::bson, "element list"))) { return false; } const std::size_t element_type_parse_position = chars_read; if (JSON_HEDLEY_UNLIKELY(!get_bson_cstr(key))) { return false; } if (!is_array && !sax->key(key)) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_internal(element_type, element_type_parse_position))) { return false; } // get_bson_cstr only appends key.clear(); } return true; } /*! @brief Reads an array from the BSON input and passes it to the SAX-parser. @return whether a valid BSON-array was passed to the SAX parser */ bool parse_bson_array() { std::int32_t document_size{}; get_number(input_format_t::bson, document_size); if (JSON_HEDLEY_UNLIKELY(!sax->start_array(static_cast(-1)))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_bson_element_list(/*is_array*/true))) { return false; } return sax->end_array(); } ////////// // CBOR // ////////// /*! @param[in] get_char whether a new character should be retrieved from the input (true) or whether the last read character should be considered instead (false) @param[in] tag_handler how CBOR tags should be treated @return whether a valid CBOR value was passed to the SAX parser */ bool parse_cbor_internal(const bool get_char, const cbor_tag_handler_t tag_handler) { switch (get_char ? get() : current) { // EOF case char_traits::eof(): return unexpect_eof(input_format_t::cbor, "value"); // Integer 0x00..0x17 (0..23) case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case 0x09: case 0x0A: case 0x0B: case 0x0C: case 0x0D: case 0x0E: case 0x0F: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: return sax->number_unsigned(static_cast(current)); case 0x18: // Unsigned integer (one-byte uint8_t follows) { std::uint8_t number{}; return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); } case 0x19: // Unsigned integer (two-byte uint16_t follows) { std::uint16_t number{}; return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); } case 0x1A: // Unsigned integer (four-byte uint32_t follows) { std::uint32_t number{}; return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); } case 0x1B: // Unsigned integer (eight-byte uint64_t follows) { std::uint64_t number{}; return get_number(input_format_t::cbor, number) && sax->number_unsigned(number); } // Negative integer -1-0x00..-1-0x17 (-1..-24) case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27: case 0x28: case 0x29: case 0x2A: case 0x2B: case 0x2C: case 0x2D: case 0x2E: case 0x2F: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37: return sax->number_integer(static_cast(0x20 - 1 - current)); case 0x38: // Negative integer (one-byte uint8_t follows) { std::uint8_t number{}; return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - number); } case 0x39: // Negative integer -1-n (two-byte uint16_t follows) { std::uint16_t number{}; return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - number); } case 0x3A: // Negative integer -1-n (four-byte uint32_t follows) { std::uint32_t number{}; return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - number); } case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows) { std::uint64_t number{}; return get_number(input_format_t::cbor, number) && sax->number_integer(static_cast(-1) - static_cast(number)); } // Binary data (0x00..0x17 bytes follow) case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4A: case 0x4B: case 0x4C: case 0x4D: case 0x4E: case 0x4F: case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: case 0x58: // Binary data (one-byte uint8_t for n follows) case 0x59: // Binary data (two-byte uint16_t for n follow) case 0x5A: // Binary data (four-byte uint32_t for n follow) case 0x5B: // Binary data (eight-byte uint64_t for n follow) case 0x5F: // Binary data (indefinite length) { binary_t b; return get_cbor_binary(b) && sax->binary(b); } // UTF-8 string (0x00..0x17 bytes follow) case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6A: case 0x6B: case 0x6C: case 0x6D: case 0x6E: case 0x6F: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: case 0x78: // UTF-8 string (one-byte uint8_t for n follows) case 0x79: // UTF-8 string (two-byte uint16_t for n follow) case 0x7A: // UTF-8 string (four-byte uint32_t for n follow) case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow) case 0x7F: // UTF-8 string (indefinite length) { string_t s; return get_cbor_string(s) && sax->string(s); } // array (0x00..0x17 data items follow) case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: return get_cbor_array( conditional_static_cast(static_cast(current) & 0x1Fu), tag_handler); case 0x98: // array (one-byte uint8_t for n follows) { std::uint8_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); } case 0x99: // array (two-byte uint16_t for n follow) { std::uint16_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_array(static_cast(len), tag_handler); } case 0x9A: // array (four-byte uint32_t for n follow) { std::uint32_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_array(conditional_static_cast(len), tag_handler); } case 0x9B: // array (eight-byte uint64_t for n follow) { std::uint64_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_array(conditional_static_cast(len), tag_handler); } case 0x9F: // array (indefinite length) return get_cbor_array(static_cast(-1), tag_handler); // map (0x00..0x17 pairs of data items follow) case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: return get_cbor_object(conditional_static_cast(static_cast(current) & 0x1Fu), tag_handler); case 0xB8: // map (one-byte uint8_t for n follows) { std::uint8_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); } case 0xB9: // map (two-byte uint16_t for n follow) { std::uint16_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_object(static_cast(len), tag_handler); } case 0xBA: // map (four-byte uint32_t for n follow) { std::uint32_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_object(conditional_static_cast(len), tag_handler); } case 0xBB: // map (eight-byte uint64_t for n follow) { std::uint64_t len{}; return get_number(input_format_t::cbor, len) && get_cbor_object(conditional_static_cast(len), tag_handler); } case 0xBF: // map (indefinite length) return get_cbor_object(static_cast(-1), tag_handler); case 0xC6: // tagged item case 0xC7: case 0xC8: case 0xC9: case 0xCA: case 0xCB: case 0xCC: case 0xCD: case 0xCE: case 0xCF: case 0xD0: case 0xD1: case 0xD2: case 0xD3: case 0xD4: case 0xD8: // tagged item (1 bytes follow) case 0xD9: // tagged item (2 bytes follow) case 0xDA: // tagged item (4 bytes follow) case 0xDB: // tagged item (8 bytes follow) { switch (tag_handler) { case cbor_tag_handler_t::error: { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, concat("invalid byte: 0x", last_token), "value"), nullptr)); } case cbor_tag_handler_t::ignore: { // ignore binary subtype switch (current) { case 0xD8: { std::uint8_t subtype_to_ignore{}; get_number(input_format_t::cbor, subtype_to_ignore); break; } case 0xD9: { std::uint16_t subtype_to_ignore{}; get_number(input_format_t::cbor, subtype_to_ignore); break; } case 0xDA: { std::uint32_t subtype_to_ignore{}; get_number(input_format_t::cbor, subtype_to_ignore); break; } case 0xDB: { std::uint64_t subtype_to_ignore{}; get_number(input_format_t::cbor, subtype_to_ignore); break; } default: break; } return parse_cbor_internal(true, tag_handler); } case cbor_tag_handler_t::store: { binary_t b; // use binary subtype and store in binary container switch (current) { case 0xD8: { std::uint8_t subtype{}; get_number(input_format_t::cbor, subtype); b.set_subtype(detail::conditional_static_cast(subtype)); break; } case 0xD9: { std::uint16_t subtype{}; get_number(input_format_t::cbor, subtype); b.set_subtype(detail::conditional_static_cast(subtype)); break; } case 0xDA: { std::uint32_t subtype{}; get_number(input_format_t::cbor, subtype); b.set_subtype(detail::conditional_static_cast(subtype)); break; } case 0xDB: { std::uint64_t subtype{}; get_number(input_format_t::cbor, subtype); b.set_subtype(detail::conditional_static_cast(subtype)); break; } default: return parse_cbor_internal(true, tag_handler); } get(); return get_cbor_binary(b) && sax->binary(b); } default: // LCOV_EXCL_LINE JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE return false; // LCOV_EXCL_LINE } } case 0xF4: // false return sax->boolean(false); case 0xF5: // true return sax->boolean(true); case 0xF6: // null return sax->null(); case 0xF9: // Half-Precision Float (two-byte IEEE 754) { const auto byte1_raw = get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number"))) { return false; } const auto byte2_raw = get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "number"))) { return false; } const auto byte1 = static_cast(byte1_raw); const auto byte2 = static_cast(byte2_raw); // code from RFC 7049, Appendix D, Figure 3: // As half-precision floating-point numbers were only added // to IEEE 754 in 2008, today's programming platforms often // still only have limited support for them. It is very // easy to include at least decoding support for them even // without such support. An example of a small decoder for // half-precision floating-point numbers in the C language // is shown in Fig. 3. const auto half = static_cast((byte1 << 8u) + byte2); const double val = [&half] { const int exp = (half >> 10u) & 0x1Fu; const unsigned int mant = half & 0x3FFu; JSON_ASSERT(0 <= exp&& exp <= 32); JSON_ASSERT(mant <= 1024); switch (exp) { case 0: return std::ldexp(mant, -24); case 31: return (mant == 0) ? std::numeric_limits::infinity() : std::numeric_limits::quiet_NaN(); default: return std::ldexp(mant + 1024, exp - 25); } }(); return sax->number_float((half & 0x8000u) != 0 ? static_cast(-val) : static_cast(val), ""); } case 0xFA: // Single-Precision Float (four-byte IEEE 754) { float number{}; return get_number(input_format_t::cbor, number) && sax->number_float(static_cast(number), ""); } case 0xFB: // Double-Precision Float (eight-byte IEEE 754) { double number{}; return get_number(input_format_t::cbor, number) && sax->number_float(static_cast(number), ""); } default: // anything else (0xFF is handled inside the other types) { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, concat("invalid byte: 0x", last_token), "value"), nullptr)); } } } /*! @brief reads a CBOR string This function first reads starting bytes to determine the expected string length and then copies this number of bytes into a string. Additionally, CBOR's strings with indefinite lengths are supported. @param[out] result created string @return whether string creation completed */ bool get_cbor_string(string_t& result) { if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "string"))) { return false; } switch (current) { // UTF-8 string (0x00..0x17 bytes follow) case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6A: case 0x6B: case 0x6C: case 0x6D: case 0x6E: case 0x6F: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: { return get_string(input_format_t::cbor, static_cast(current) & 0x1Fu, result); } case 0x78: // UTF-8 string (one-byte uint8_t for n follows) { std::uint8_t len{}; return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); } case 0x79: // UTF-8 string (two-byte uint16_t for n follow) { std::uint16_t len{}; return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); } case 0x7A: // UTF-8 string (four-byte uint32_t for n follow) { std::uint32_t len{}; return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); } case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow) { std::uint64_t len{}; return get_number(input_format_t::cbor, len) && get_string(input_format_t::cbor, len, result); } case 0x7F: // UTF-8 string (indefinite length) { while (get() != 0xFF) { string_t chunk; if (!get_cbor_string(chunk)) { return false; } result.append(chunk); } return true; } default: { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, concat("expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0x", last_token), "string"), nullptr)); } } } /*! @brief reads a CBOR byte array This function first reads starting bytes to determine the expected byte array length and then copies this number of bytes into the byte array. Additionally, CBOR's byte arrays with indefinite lengths are supported. @param[out] result created byte array @return whether byte array creation completed */ bool get_cbor_binary(binary_t& result) { if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::cbor, "binary"))) { return false; } switch (current) { // Binary data (0x00..0x17 bytes follow) case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4A: case 0x4B: case 0x4C: case 0x4D: case 0x4E: case 0x4F: case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: { return get_binary(input_format_t::cbor, static_cast(current) & 0x1Fu, result); } case 0x58: // Binary data (one-byte uint8_t for n follows) { std::uint8_t len{}; return get_number(input_format_t::cbor, len) && get_binary(input_format_t::cbor, len, result); } case 0x59: // Binary data (two-byte uint16_t for n follow) { std::uint16_t len{}; return get_number(input_format_t::cbor, len) && get_binary(input_format_t::cbor, len, result); } case 0x5A: // Binary data (four-byte uint32_t for n follow) { std::uint32_t len{}; return get_number(input_format_t::cbor, len) && get_binary(input_format_t::cbor, len, result); } case 0x5B: // Binary data (eight-byte uint64_t for n follow) { std::uint64_t len{}; return get_number(input_format_t::cbor, len) && get_binary(input_format_t::cbor, len, result); } case 0x5F: // Binary data (indefinite length) { while (get() != 0xFF) { binary_t chunk; if (!get_cbor_binary(chunk)) { return false; } result.insert(result.end(), chunk.begin(), chunk.end()); } return true; } default: { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, concat("expected length specification (0x40-0x5B) or indefinite binary array type (0x5F); last byte: 0x", last_token), "binary"), nullptr)); } } } /*! @param[in] len the length of the array or static_cast(-1) for an array of indefinite size @param[in] tag_handler how CBOR tags should be treated @return whether array creation completed */ bool get_cbor_array(const std::size_t len, const cbor_tag_handler_t tag_handler) { if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len))) { return false; } if (len != static_cast(-1)) { for (std::size_t i = 0; i < len; ++i) { if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) { return false; } } } else { while (get() != 0xFF) { if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(false, tag_handler))) { return false; } } } return sax->end_array(); } /*! @param[in] len the length of the object or static_cast(-1) for an object of indefinite size @param[in] tag_handler how CBOR tags should be treated @return whether object creation completed */ bool get_cbor_object(const std::size_t len, const cbor_tag_handler_t tag_handler) { if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len))) { return false; } if (len != 0) { string_t key; if (len != static_cast(-1)) { for (std::size_t i = 0; i < len; ++i) { get(); if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) { return false; } key.clear(); } } else { while (get() != 0xFF) { if (JSON_HEDLEY_UNLIKELY(!get_cbor_string(key) || !sax->key(key))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_cbor_internal(true, tag_handler))) { return false; } key.clear(); } } } return sax->end_object(); } ///////////// // MsgPack // ///////////// /*! @return whether a valid MessagePack value was passed to the SAX parser */ bool parse_msgpack_internal() { switch (get()) { // EOF case char_traits::eof(): return unexpect_eof(input_format_t::msgpack, "value"); // positive fixint case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case 0x09: case 0x0A: case 0x0B: case 0x0C: case 0x0D: case 0x0E: case 0x0F: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1A: case 0x1B: case 0x1C: case 0x1D: case 0x1E: case 0x1F: case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27: case 0x28: case 0x29: case 0x2A: case 0x2B: case 0x2C: case 0x2D: case 0x2E: case 0x2F: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: case 0x3A: case 0x3B: case 0x3C: case 0x3D: case 0x3E: case 0x3F: case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4A: case 0x4B: case 0x4C: case 0x4D: case 0x4E: case 0x4F: case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: case 0x58: case 0x59: case 0x5A: case 0x5B: case 0x5C: case 0x5D: case 0x5E: case 0x5F: case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6A: case 0x6B: case 0x6C: case 0x6D: case 0x6E: case 0x6F: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: case 0x78: case 0x79: case 0x7A: case 0x7B: case 0x7C: case 0x7D: case 0x7E: case 0x7F: return sax->number_unsigned(static_cast(current)); // fixmap case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: return get_msgpack_object(conditional_static_cast(static_cast(current) & 0x0Fu)); // fixarray case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: case 0x98: case 0x99: case 0x9A: case 0x9B: case 0x9C: case 0x9D: case 0x9E: case 0x9F: return get_msgpack_array(conditional_static_cast(static_cast(current) & 0x0Fu)); // fixstr case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: case 0xB8: case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: case 0xD9: // str 8 case 0xDA: // str 16 case 0xDB: // str 32 { string_t s; return get_msgpack_string(s) && sax->string(s); } case 0xC0: // nil return sax->null(); case 0xC2: // false return sax->boolean(false); case 0xC3: // true return sax->boolean(true); case 0xC4: // bin 8 case 0xC5: // bin 16 case 0xC6: // bin 32 case 0xC7: // ext 8 case 0xC8: // ext 16 case 0xC9: // ext 32 case 0xD4: // fixext 1 case 0xD5: // fixext 2 case 0xD6: // fixext 4 case 0xD7: // fixext 8 case 0xD8: // fixext 16 { binary_t b; return get_msgpack_binary(b) && sax->binary(b); } case 0xCA: // float 32 { float number{}; return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast(number), ""); } case 0xCB: // float 64 { double number{}; return get_number(input_format_t::msgpack, number) && sax->number_float(static_cast(number), ""); } case 0xCC: // uint 8 { std::uint8_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); } case 0xCD: // uint 16 { std::uint16_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); } case 0xCE: // uint 32 { std::uint32_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); } case 0xCF: // uint 64 { std::uint64_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_unsigned(number); } case 0xD0: // int 8 { std::int8_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_integer(number); } case 0xD1: // int 16 { std::int16_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_integer(number); } case 0xD2: // int 32 { std::int32_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_integer(number); } case 0xD3: // int 64 { std::int64_t number{}; return get_number(input_format_t::msgpack, number) && sax->number_integer(number); } case 0xDC: // array 16 { std::uint16_t len{}; return get_number(input_format_t::msgpack, len) && get_msgpack_array(static_cast(len)); } case 0xDD: // array 32 { std::uint32_t len{}; return get_number(input_format_t::msgpack, len) && get_msgpack_array(conditional_static_cast(len)); } case 0xDE: // map 16 { std::uint16_t len{}; return get_number(input_format_t::msgpack, len) && get_msgpack_object(static_cast(len)); } case 0xDF: // map 32 { std::uint32_t len{}; return get_number(input_format_t::msgpack, len) && get_msgpack_object(conditional_static_cast(len)); } // negative fixint case 0xE0: case 0xE1: case 0xE2: case 0xE3: case 0xE4: case 0xE5: case 0xE6: case 0xE7: case 0xE8: case 0xE9: case 0xEA: case 0xEB: case 0xEC: case 0xED: case 0xEE: case 0xEF: case 0xF0: case 0xF1: case 0xF2: case 0xF3: case 0xF4: case 0xF5: case 0xF6: case 0xF7: case 0xF8: case 0xF9: case 0xFA: case 0xFB: case 0xFC: case 0xFD: case 0xFE: case 0xFF: return sax->number_integer(static_cast(current)); default: // anything else { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::msgpack, concat("invalid byte: 0x", last_token), "value"), nullptr)); } } } /*! @brief reads a MessagePack string This function first reads starting bytes to determine the expected string length and then copies this number of bytes into a string. @param[out] result created string @return whether string creation completed */ bool get_msgpack_string(string_t& result) { if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format_t::msgpack, "string"))) { return false; } switch (current) { // fixstr case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: case 0xB8: case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: { return get_string(input_format_t::msgpack, static_cast(current) & 0x1Fu, result); } case 0xD9: // str 8 { std::uint8_t len{}; return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); } case 0xDA: // str 16 { std::uint16_t len{}; return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); } case 0xDB: // str 32 { std::uint32_t len{}; return get_number(input_format_t::msgpack, len) && get_string(input_format_t::msgpack, len, result); } default: { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::msgpack, concat("expected length specification (0xA0-0xBF, 0xD9-0xDB); last byte: 0x", last_token), "string"), nullptr)); } } } /*! @brief reads a MessagePack byte array This function first reads starting bytes to determine the expected byte array length and then copies this number of bytes into a byte array. @param[out] result created byte array @return whether byte array creation completed */ bool get_msgpack_binary(binary_t& result) { // helper function to set the subtype auto assign_and_return_true = [&result](std::int8_t subtype) { result.set_subtype(static_cast(subtype)); return true; }; switch (current) { case 0xC4: // bin 8 { std::uint8_t len{}; return get_number(input_format_t::msgpack, len) && get_binary(input_format_t::msgpack, len, result); } case 0xC5: // bin 16 { std::uint16_t len{}; return get_number(input_format_t::msgpack, len) && get_binary(input_format_t::msgpack, len, result); } case 0xC6: // bin 32 { std::uint32_t len{}; return get_number(input_format_t::msgpack, len) && get_binary(input_format_t::msgpack, len, result); } case 0xC7: // ext 8 { std::uint8_t len{}; std::int8_t subtype{}; return get_number(input_format_t::msgpack, len) && get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, len, result) && assign_and_return_true(subtype); } case 0xC8: // ext 16 { std::uint16_t len{}; std::int8_t subtype{}; return get_number(input_format_t::msgpack, len) && get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, len, result) && assign_and_return_true(subtype); } case 0xC9: // ext 32 { std::uint32_t len{}; std::int8_t subtype{}; return get_number(input_format_t::msgpack, len) && get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, len, result) && assign_and_return_true(subtype); } case 0xD4: // fixext 1 { std::int8_t subtype{}; return get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, 1, result) && assign_and_return_true(subtype); } case 0xD5: // fixext 2 { std::int8_t subtype{}; return get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, 2, result) && assign_and_return_true(subtype); } case 0xD6: // fixext 4 { std::int8_t subtype{}; return get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, 4, result) && assign_and_return_true(subtype); } case 0xD7: // fixext 8 { std::int8_t subtype{}; return get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, 8, result) && assign_and_return_true(subtype); } case 0xD8: // fixext 16 { std::int8_t subtype{}; return get_number(input_format_t::msgpack, subtype) && get_binary(input_format_t::msgpack, 16, result) && assign_and_return_true(subtype); } default: // LCOV_EXCL_LINE return false; // LCOV_EXCL_LINE } } /*! @param[in] len the length of the array @return whether array creation completed */ bool get_msgpack_array(const std::size_t len) { if (JSON_HEDLEY_UNLIKELY(!sax->start_array(len))) { return false; } for (std::size_t i = 0; i < len; ++i) { if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal())) { return false; } } return sax->end_array(); } /*! @param[in] len the length of the object @return whether object creation completed */ bool get_msgpack_object(const std::size_t len) { if (JSON_HEDLEY_UNLIKELY(!sax->start_object(len))) { return false; } string_t key; for (std::size_t i = 0; i < len; ++i) { get(); if (JSON_HEDLEY_UNLIKELY(!get_msgpack_string(key) || !sax->key(key))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_msgpack_internal())) { return false; } key.clear(); } return sax->end_object(); } //////////// // UBJSON // //////////// /*! @param[in] get_char whether a new character should be retrieved from the input (true, default) or whether the last read character should be considered instead @return whether a valid UBJSON value was passed to the SAX parser */ bool parse_ubjson_internal(const bool get_char = true) { return get_ubjson_value(get_char ? get_ignore_noop() : current); } /*! @brief reads a UBJSON string This function is either called after reading the 'S' byte explicitly indicating a string, or in case of an object key where the 'S' byte can be left out. @param[out] result created string @param[in] get_char whether a new character should be retrieved from the input (true, default) or whether the last read character should be considered instead @return whether string creation completed */ bool get_ubjson_string(string_t& result, const bool get_char = true) { if (get_char) { get(); // TODO(niels): may we ignore N here? } if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format, "value"))) { return false; } switch (current) { case 'U': { std::uint8_t len{}; return get_number(input_format, len) && get_string(input_format, len, result); } case 'i': { std::int8_t len{}; return get_number(input_format, len) && get_string(input_format, len, result); } case 'I': { std::int16_t len{}; return get_number(input_format, len) && get_string(input_format, len, result); } case 'l': { std::int32_t len{}; return get_number(input_format, len) && get_string(input_format, len, result); } case 'L': { std::int64_t len{}; return get_number(input_format, len) && get_string(input_format, len, result); } case 'u': { if (input_format != input_format_t::bjdata) { break; } std::uint16_t len{}; return get_number(input_format, len) && get_string(input_format, len, result); } case 'm': { if (input_format != input_format_t::bjdata) { break; } std::uint32_t len{}; return get_number(input_format, len) && get_string(input_format, len, result); } case 'M': { if (input_format != input_format_t::bjdata) { break; } std::uint64_t len{}; return get_number(input_format, len) && get_string(input_format, len, result); } default: break; } auto last_token = get_token_string(); std::string message; if (input_format != input_format_t::bjdata) { message = "expected length type specification (U, i, I, l, L); last byte: 0x" + last_token; } else { message = "expected length type specification (U, i, u, I, m, l, M, L); last byte: 0x" + last_token; } return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format, message, "string"), nullptr)); } /*! @param[out] dim an integer vector storing the ND array dimensions @return whether reading ND array size vector is successful */ bool get_ubjson_ndarray_size(std::vector& dim) { std::pair size_and_type; size_t dimlen = 0; bool no_ndarray = true; if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type, no_ndarray))) { return false; } if (size_and_type.first != npos) { if (size_and_type.second != 0) { if (size_and_type.second != 'N') { for (std::size_t i = 0; i < size_and_type.first; ++i) { if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_value(dimlen, no_ndarray, size_and_type.second))) { return false; } dim.push_back(dimlen); } } } else { for (std::size_t i = 0; i < size_and_type.first; ++i) { if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_value(dimlen, no_ndarray))) { return false; } dim.push_back(dimlen); } } } else { while (current != ']') { if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_value(dimlen, no_ndarray, current))) { return false; } dim.push_back(dimlen); get_ignore_noop(); } } return true; } /*! @param[out] result determined size @param[in,out] is_ndarray for input, `true` means already inside an ndarray vector or ndarray dimension is not allowed; `false` means ndarray is allowed; for output, `true` means an ndarray is found; is_ndarray can only return `true` when its initial value is `false` @param[in] prefix type marker if already read, otherwise set to 0 @return whether size determination completed */ bool get_ubjson_size_value(std::size_t& result, bool& is_ndarray, char_int_type prefix = 0) { if (prefix == 0) { prefix = get_ignore_noop(); } switch (prefix) { case 'U': { std::uint8_t number{}; if (JSON_HEDLEY_UNLIKELY(!get_number(input_format, number))) { return false; } result = static_cast(number); return true; } case 'i': { std::int8_t number{}; if (JSON_HEDLEY_UNLIKELY(!get_number(input_format, number))) { return false; } if (number < 0) { return sax->parse_error(chars_read, get_token_string(), parse_error::create(113, chars_read, exception_message(input_format, "count in an optimized container must be positive", "size"), nullptr)); } result = static_cast(number); // NOLINT(bugprone-signed-char-misuse,cert-str34-c): number is not a char return true; } case 'I': { std::int16_t number{}; if (JSON_HEDLEY_UNLIKELY(!get_number(input_format, number))) { return false; } if (number < 0) { return sax->parse_error(chars_read, get_token_string(), parse_error::create(113, chars_read, exception_message(input_format, "count in an optimized container must be positive", "size"), nullptr)); } result = static_cast(number); return true; } case 'l': { std::int32_t number{}; if (JSON_HEDLEY_UNLIKELY(!get_number(input_format, number))) { return false; } if (number < 0) { return sax->parse_error(chars_read, get_token_string(), parse_error::create(113, chars_read, exception_message(input_format, "count in an optimized container must be positive", "size"), nullptr)); } result = static_cast(number); return true; } case 'L': { std::int64_t number{}; if (JSON_HEDLEY_UNLIKELY(!get_number(input_format, number))) { return false; } if (number < 0) { return sax->parse_error(chars_read, get_token_string(), parse_error::create(113, chars_read, exception_message(input_format, "count in an optimized container must be positive", "size"), nullptr)); } if (!value_in_range_of(number)) { return sax->parse_error(chars_read, get_token_string(), out_of_range::create(408, exception_message(input_format, "integer value overflow", "size"), nullptr)); } result = static_cast(number); return true; } case 'u': { if (input_format != input_format_t::bjdata) { break; } std::uint16_t number{}; if (JSON_HEDLEY_UNLIKELY(!get_number(input_format, number))) { return false; } result = static_cast(number); return true; } case 'm': { if (input_format != input_format_t::bjdata) { break; } std::uint32_t number{}; if (JSON_HEDLEY_UNLIKELY(!get_number(input_format, number))) { return false; } result = conditional_static_cast(number); return true; } case 'M': { if (input_format != input_format_t::bjdata) { break; } std::uint64_t number{}; if (JSON_HEDLEY_UNLIKELY(!get_number(input_format, number))) { return false; } if (!value_in_range_of(number)) { return sax->parse_error(chars_read, get_token_string(), out_of_range::create(408, exception_message(input_format, "integer value overflow", "size"), nullptr)); } result = detail::conditional_static_cast(number); return true; } case '[': { if (input_format != input_format_t::bjdata) { break; } if (is_ndarray) // ndarray dimensional vector can only contain integers, and can not embed another array { return sax->parse_error(chars_read, get_token_string(), parse_error::create(113, chars_read, exception_message(input_format, "ndarray dimensional vector is not allowed", "size"), nullptr)); } std::vector dim; if (JSON_HEDLEY_UNLIKELY(!get_ubjson_ndarray_size(dim))) { return false; } if (dim.size() == 1 || (dim.size() == 2 && dim.at(0) == 1)) // return normal array size if 1D row vector { result = dim.at(dim.size() - 1); return true; } if (!dim.empty()) // if ndarray, convert to an object in JData annotated array format { for (auto i : dim) // test if any dimension in an ndarray is 0, if so, return a 1D empty container { if ( i == 0 ) { result = 0; return true; } } string_t key = "_ArraySize_"; if (JSON_HEDLEY_UNLIKELY(!sax->start_object(3) || !sax->key(key) || !sax->start_array(dim.size()))) { return false; } result = 1; for (auto i : dim) { result *= i; if (result == 0 || result == npos) // because dim elements shall not have zeros, result = 0 means overflow happened; it also can't be npos as it is used to initialize size in get_ubjson_size_type() { return sax->parse_error(chars_read, get_token_string(), out_of_range::create(408, exception_message(input_format, "excessive ndarray size caused overflow", "size"), nullptr)); } if (JSON_HEDLEY_UNLIKELY(!sax->number_unsigned(static_cast(i)))) { return false; } } is_ndarray = true; return sax->end_array(); } result = 0; return true; } default: break; } auto last_token = get_token_string(); std::string message; if (input_format != input_format_t::bjdata) { message = "expected length type specification (U, i, I, l, L) after '#'; last byte: 0x" + last_token; } else { message = "expected length type specification (U, i, u, I, m, l, M, L) after '#'; last byte: 0x" + last_token; } return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format, message, "size"), nullptr)); } /*! @brief determine the type and size for a container In the optimized UBJSON format, a type and a size can be provided to allow for a more compact representation. @param[out] result pair of the size and the type @param[in] inside_ndarray whether the parser is parsing an ND array dimensional vector @return whether pair creation completed */ bool get_ubjson_size_type(std::pair& result, bool inside_ndarray = false) { result.first = npos; // size result.second = 0; // type bool is_ndarray = false; get_ignore_noop(); if (current == '$') { result.second = get(); // must not ignore 'N', because 'N' maybe the type if (input_format == input_format_t::bjdata && JSON_HEDLEY_UNLIKELY(std::binary_search(bjd_optimized_type_markers.begin(), bjd_optimized_type_markers.end(), result.second))) { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format, concat("marker 0x", last_token, " is not a permitted optimized array type"), "type"), nullptr)); } if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format, "type"))) { return false; } get_ignore_noop(); if (JSON_HEDLEY_UNLIKELY(current != '#')) { if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format, "value"))) { return false; } auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format, concat("expected '#' after type information; last byte: 0x", last_token), "size"), nullptr)); } const bool is_error = get_ubjson_size_value(result.first, is_ndarray); if (input_format == input_format_t::bjdata && is_ndarray) { if (inside_ndarray) { return sax->parse_error(chars_read, get_token_string(), parse_error::create(112, chars_read, exception_message(input_format, "ndarray can not be recursive", "size"), nullptr)); } result.second |= (1 << 8); // use bit 8 to indicate ndarray, all UBJSON and BJData markers should be ASCII letters } return is_error; } if (current == '#') { const bool is_error = get_ubjson_size_value(result.first, is_ndarray); if (input_format == input_format_t::bjdata && is_ndarray) { return sax->parse_error(chars_read, get_token_string(), parse_error::create(112, chars_read, exception_message(input_format, "ndarray requires both type and size", "size"), nullptr)); } return is_error; } return true; } /*! @param prefix the previously read or set type prefix @return whether value creation completed */ bool get_ubjson_value(const char_int_type prefix) { switch (prefix) { case char_traits::eof(): // EOF return unexpect_eof(input_format, "value"); case 'T': // true return sax->boolean(true); case 'F': // false return sax->boolean(false); case 'Z': // null return sax->null(); case 'U': { std::uint8_t number{}; return get_number(input_format, number) && sax->number_unsigned(number); } case 'i': { std::int8_t number{}; return get_number(input_format, number) && sax->number_integer(number); } case 'I': { std::int16_t number{}; return get_number(input_format, number) && sax->number_integer(number); } case 'l': { std::int32_t number{}; return get_number(input_format, number) && sax->number_integer(number); } case 'L': { std::int64_t number{}; return get_number(input_format, number) && sax->number_integer(number); } case 'u': { if (input_format != input_format_t::bjdata) { break; } std::uint16_t number{}; return get_number(input_format, number) && sax->number_unsigned(number); } case 'm': { if (input_format != input_format_t::bjdata) { break; } std::uint32_t number{}; return get_number(input_format, number) && sax->number_unsigned(number); } case 'M': { if (input_format != input_format_t::bjdata) { break; } std::uint64_t number{}; return get_number(input_format, number) && sax->number_unsigned(number); } case 'h': { if (input_format != input_format_t::bjdata) { break; } const auto byte1_raw = get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format, "number"))) { return false; } const auto byte2_raw = get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format, "number"))) { return false; } const auto byte1 = static_cast(byte1_raw); const auto byte2 = static_cast(byte2_raw); // code from RFC 7049, Appendix D, Figure 3: // As half-precision floating-point numbers were only added // to IEEE 754 in 2008, today's programming platforms often // still only have limited support for them. It is very // easy to include at least decoding support for them even // without such support. An example of a small decoder for // half-precision floating-point numbers in the C language // is shown in Fig. 3. const auto half = static_cast((byte2 << 8u) + byte1); const double val = [&half] { const int exp = (half >> 10u) & 0x1Fu; const unsigned int mant = half & 0x3FFu; JSON_ASSERT(0 <= exp&& exp <= 32); JSON_ASSERT(mant <= 1024); switch (exp) { case 0: return std::ldexp(mant, -24); case 31: return (mant == 0) ? std::numeric_limits::infinity() : std::numeric_limits::quiet_NaN(); default: return std::ldexp(mant + 1024, exp - 25); } }(); return sax->number_float((half & 0x8000u) != 0 ? static_cast(-val) : static_cast(val), ""); } case 'd': { float number{}; return get_number(input_format, number) && sax->number_float(static_cast(number), ""); } case 'D': { double number{}; return get_number(input_format, number) && sax->number_float(static_cast(number), ""); } case 'H': { return get_ubjson_high_precision_number(); } case 'C': // char { get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format, "char"))) { return false; } if (JSON_HEDLEY_UNLIKELY(current > 127)) { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format, concat("byte after 'C' must be in range 0x00..0x7F; last byte: 0x", last_token), "char"), nullptr)); } string_t s(1, static_cast(current)); return sax->string(s); } case 'S': // string { string_t s; return get_ubjson_string(s) && sax->string(s); } case '[': // array return get_ubjson_array(); case '{': // object return get_ubjson_object(); default: // anything else break; } auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format, "invalid byte: 0x" + last_token, "value"), nullptr)); } /*! @return whether array creation completed */ bool get_ubjson_array() { std::pair size_and_type; if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type))) { return false; } // if bit-8 of size_and_type.second is set to 1, encode bjdata ndarray as an object in JData annotated array format (https://github.com/NeuroJSON/jdata): // {"_ArrayType_" : "typeid", "_ArraySize_" : [n1, n2, ...], "_ArrayData_" : [v1, v2, ...]} if (input_format == input_format_t::bjdata && size_and_type.first != npos && (size_and_type.second & (1 << 8)) != 0) { size_and_type.second &= ~(static_cast(1) << 8); // use bit 8 to indicate ndarray, here we remove the bit to restore the type marker auto it = std::lower_bound(bjd_types_map.begin(), bjd_types_map.end(), size_and_type.second, [](const bjd_type & p, char_int_type t) { return p.first < t; }); string_t key = "_ArrayType_"; if (JSON_HEDLEY_UNLIKELY(it == bjd_types_map.end() || it->first != size_and_type.second)) { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format, "invalid byte: 0x" + last_token, "type"), nullptr)); } string_t type = it->second; // sax->string() takes a reference if (JSON_HEDLEY_UNLIKELY(!sax->key(key) || !sax->string(type))) { return false; } if (size_and_type.second == 'C') { size_and_type.second = 'U'; } key = "_ArrayData_"; if (JSON_HEDLEY_UNLIKELY(!sax->key(key) || !sax->start_array(size_and_type.first) )) { return false; } for (std::size_t i = 0; i < size_and_type.first; ++i) { if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second))) { return false; } } return (sax->end_array() && sax->end_object()); } if (size_and_type.first != npos) { if (JSON_HEDLEY_UNLIKELY(!sax->start_array(size_and_type.first))) { return false; } if (size_and_type.second != 0) { if (size_and_type.second != 'N') { for (std::size_t i = 0; i < size_and_type.first; ++i) { if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second))) { return false; } } } } else { for (std::size_t i = 0; i < size_and_type.first; ++i) { if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) { return false; } } } } else { if (JSON_HEDLEY_UNLIKELY(!sax->start_array(static_cast(-1)))) { return false; } while (current != ']') { if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal(false))) { return false; } get_ignore_noop(); } } return sax->end_array(); } /*! @return whether object creation completed */ bool get_ubjson_object() { std::pair size_and_type; if (JSON_HEDLEY_UNLIKELY(!get_ubjson_size_type(size_and_type))) { return false; } // do not accept ND-array size in objects in BJData if (input_format == input_format_t::bjdata && size_and_type.first != npos && (size_and_type.second & (1 << 8)) != 0) { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format, "BJData object does not support ND-array size in optimized format", "object"), nullptr)); } string_t key; if (size_and_type.first != npos) { if (JSON_HEDLEY_UNLIKELY(!sax->start_object(size_and_type.first))) { return false; } if (size_and_type.second != 0) { for (std::size_t i = 0; i < size_and_type.first; ++i) { if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key))) { return false; } if (JSON_HEDLEY_UNLIKELY(!get_ubjson_value(size_and_type.second))) { return false; } key.clear(); } } else { for (std::size_t i = 0; i < size_and_type.first; ++i) { if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key) || !sax->key(key))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) { return false; } key.clear(); } } } else { if (JSON_HEDLEY_UNLIKELY(!sax->start_object(static_cast(-1)))) { return false; } while (current != '}') { if (JSON_HEDLEY_UNLIKELY(!get_ubjson_string(key, false) || !sax->key(key))) { return false; } if (JSON_HEDLEY_UNLIKELY(!parse_ubjson_internal())) { return false; } get_ignore_noop(); key.clear(); } } return sax->end_object(); } // Note, no reader for UBJSON binary types is implemented because they do // not exist bool get_ubjson_high_precision_number() { // get size of following number string std::size_t size{}; bool no_ndarray = true; auto res = get_ubjson_size_value(size, no_ndarray); if (JSON_HEDLEY_UNLIKELY(!res)) { return res; } // get number string std::vector number_vector; for (std::size_t i = 0; i < size; ++i) { get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(input_format, "number"))) { return false; } number_vector.push_back(static_cast(current)); } // parse number string using ia_type = decltype(detail::input_adapter(number_vector)); auto number_lexer = detail::lexer(detail::input_adapter(number_vector), false); const auto result_number = number_lexer.scan(); const auto number_string = number_lexer.get_token_string(); const auto result_remainder = number_lexer.scan(); using token_type = typename detail::lexer_base::token_type; if (JSON_HEDLEY_UNLIKELY(result_remainder != token_type::end_of_input)) { return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read, exception_message(input_format, concat("invalid number text: ", number_lexer.get_token_string()), "high-precision number"), nullptr)); } switch (result_number) { case token_type::value_integer: return sax->number_integer(number_lexer.get_number_integer()); case token_type::value_unsigned: return sax->number_unsigned(number_lexer.get_number_unsigned()); case token_type::value_float: return sax->number_float(number_lexer.get_number_float(), std::move(number_string)); case token_type::uninitialized: case token_type::literal_true: case token_type::literal_false: case token_type::literal_null: case token_type::value_string: case token_type::begin_array: case token_type::begin_object: case token_type::end_array: case token_type::end_object: case token_type::name_separator: case token_type::value_separator: case token_type::parse_error: case token_type::end_of_input: case token_type::literal_or_value: default: return sax->parse_error(chars_read, number_string, parse_error::create(115, chars_read, exception_message(input_format, concat("invalid number text: ", number_lexer.get_token_string()), "high-precision number"), nullptr)); } } /////////////////////// // Utility functions // /////////////////////// /*! @brief get next character from the input This function provides the interface to the used input adapter. It does not throw in case the input reached EOF, but returns a -'ve valued `char_traits::eof()` in that case. @return character read from the input */ char_int_type get() { ++chars_read; return current = ia.get_character(); } /*! @return character read from the input after ignoring all 'N' entries */ char_int_type get_ignore_noop() { do { get(); } while (current == 'N'); return current; } /* @brief read a number from the input @tparam NumberType the type of the number @param[in] format the current format (for diagnostics) @param[out] result number of type @a NumberType @return whether conversion completed @note This function needs to respect the system's endianness, because bytes in CBOR, MessagePack, and UBJSON are stored in network order (big endian) and therefore need reordering on little endian systems. On the other hand, BSON and BJData use little endian and should reorder on big endian systems. */ template bool get_number(const input_format_t format, NumberType& result) { // step 1: read input into array with system's byte order std::array vec{}; for (std::size_t i = 0; i < sizeof(NumberType); ++i) { get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "number"))) { return false; } // reverse byte order prior to conversion if necessary if (is_little_endian != (InputIsLittleEndian || format == input_format_t::bjdata)) { vec[sizeof(NumberType) - i - 1] = static_cast(current); } else { vec[i] = static_cast(current); // LCOV_EXCL_LINE } } // step 2: convert array into number of type T and return std::memcpy(&result, vec.data(), sizeof(NumberType)); return true; } /*! @brief create a string by reading characters from the input @tparam NumberType the type of the number @param[in] format the current format (for diagnostics) @param[in] len number of characters to read @param[out] result string created by reading @a len bytes @return whether string creation completed @note We can not reserve @a len bytes for the result, because @a len may be too large. Usually, @ref unexpect_eof() detects the end of the input before we run out of string memory. */ template bool get_string(const input_format_t format, const NumberType len, string_t& result) { bool success = true; for (NumberType i = 0; i < len; i++) { get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "string"))) { success = false; break; } result.push_back(static_cast(current)); } return success; } /*! @brief create a byte array by reading bytes from the input @tparam NumberType the type of the number @param[in] format the current format (for diagnostics) @param[in] len number of bytes to read @param[out] result byte array created by reading @a len bytes @return whether byte array creation completed @note We can not reserve @a len bytes for the result, because @a len may be too large. Usually, @ref unexpect_eof() detects the end of the input before we run out of memory. */ template bool get_binary(const input_format_t format, const NumberType len, binary_t& result) { bool success = true; for (NumberType i = 0; i < len; i++) { get(); if (JSON_HEDLEY_UNLIKELY(!unexpect_eof(format, "binary"))) { success = false; break; } result.push_back(static_cast(current)); } return success; } /*! @param[in] format the current format (for diagnostics) @param[in] context further context information (for diagnostics) @return whether the last read character is not EOF */ JSON_HEDLEY_NON_NULL(3) bool unexpect_eof(const input_format_t format, const char* context) const { if (JSON_HEDLEY_UNLIKELY(current == char_traits::eof())) { return sax->parse_error(chars_read, "", parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context), nullptr)); } return true; } /*! @return a string representation of the last read byte */ std::string get_token_string() const { std::array cr{{}}; static_cast((std::snprintf)(cr.data(), cr.size(), "%.2hhX", static_cast(current))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) return std::string{cr.data()}; } /*! @param[in] format the current format @param[in] detail a detailed error message @param[in] context further context information @return a message string to use in the parse_error exceptions */ std::string exception_message(const input_format_t format, const std::string& detail, const std::string& context) const { std::string error_msg = "syntax error while parsing "; switch (format) { case input_format_t::cbor: error_msg += "CBOR"; break; case input_format_t::msgpack: error_msg += "MessagePack"; break; case input_format_t::ubjson: error_msg += "UBJSON"; break; case input_format_t::bson: error_msg += "BSON"; break; case input_format_t::bjdata: error_msg += "BJData"; break; case input_format_t::json: // LCOV_EXCL_LINE default: // LCOV_EXCL_LINE JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE } return concat(error_msg, ' ', context, ": ", detail); } private: static JSON_INLINE_VARIABLE constexpr std::size_t npos = static_cast(-1); /// input adapter InputAdapterType ia; /// the current character char_int_type current = char_traits::eof(); /// the number of characters read std::size_t chars_read = 0; /// whether we can assume little endianness const bool is_little_endian = little_endianness(); /// input format const input_format_t input_format = input_format_t::json; /// the SAX parser json_sax_t* sax = nullptr; // excluded markers in bjdata optimized type #define JSON_BINARY_READER_MAKE_BJD_OPTIMIZED_TYPE_MARKERS_ \ make_array('F', 'H', 'N', 'S', 'T', 'Z', '[', '{') #define JSON_BINARY_READER_MAKE_BJD_TYPES_MAP_ \ make_array( \ bjd_type{'C', "char"}, \ bjd_type{'D', "double"}, \ bjd_type{'I', "int16"}, \ bjd_type{'L', "int64"}, \ bjd_type{'M', "uint64"}, \ bjd_type{'U', "uint8"}, \ bjd_type{'d', "single"}, \ bjd_type{'i', "int8"}, \ bjd_type{'l', "int32"}, \ bjd_type{'m', "uint32"}, \ bjd_type{'u', "uint16"}) JSON_PRIVATE_UNLESS_TESTED: // lookup tables // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) const decltype(JSON_BINARY_READER_MAKE_BJD_OPTIMIZED_TYPE_MARKERS_) bjd_optimized_type_markers = JSON_BINARY_READER_MAKE_BJD_OPTIMIZED_TYPE_MARKERS_; using bjd_type = std::pair; // NOLINTNEXTLINE(cppcoreguidelines-non-private-member-variables-in-classes) const decltype(JSON_BINARY_READER_MAKE_BJD_TYPES_MAP_) bjd_types_map = JSON_BINARY_READER_MAKE_BJD_TYPES_MAP_; #undef JSON_BINARY_READER_MAKE_BJD_OPTIMIZED_TYPE_MARKERS_ #undef JSON_BINARY_READER_MAKE_BJD_TYPES_MAP_ }; #ifndef JSON_HAS_CPP_17 template constexpr std::size_t binary_reader::npos; #endif } // namespace detail NLOHMANN_JSON_NAMESPACE_END ================================================ FILE: Libs/nlohmann/detail/input/input_adapters.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include // array #include // size_t #include // strlen #include // begin, end, iterator_traits, random_access_iterator_tag, distance, next #include // shared_ptr, make_shared, addressof #include // accumulate #include // string, char_traits #include // enable_if, is_base_of, is_pointer, is_integral, remove_pointer #include // pair, declval #ifndef JSON_NO_IO #include // FILE * #include // istream #endif // JSON_NO_IO #include #include #include NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { /// the supported input formats enum class input_format_t { json, cbor, msgpack, ubjson, bson, bjdata }; //////////////////// // input adapters // //////////////////// #ifndef JSON_NO_IO /*! Input adapter for stdio file access. This adapter read only 1 byte and do not use any buffer. This adapter is a very low level adapter. */ class file_input_adapter { public: using char_type = char; JSON_HEDLEY_NON_NULL(2) explicit file_input_adapter(std::FILE* f) noexcept : m_file(f) { JSON_ASSERT(m_file != nullptr); } // make class move-only file_input_adapter(const file_input_adapter&) = delete; file_input_adapter(file_input_adapter&&) noexcept = default; file_input_adapter& operator=(const file_input_adapter&) = delete; file_input_adapter& operator=(file_input_adapter&&) = delete; ~file_input_adapter() = default; std::char_traits::int_type get_character() noexcept { return std::fgetc(m_file); } private: /// the file pointer to read from std::FILE* m_file; }; /*! Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at beginning of input. Does not support changing the underlying std::streambuf in mid-input. Maintains underlying std::istream and std::streambuf to support subsequent use of standard std::istream operations to process any input characters following those used in parsing the JSON input. Clears the std::istream flags; any input errors (e.g., EOF) will be detected by the first subsequent call for input from the std::istream. */ class input_stream_adapter { public: using char_type = char; ~input_stream_adapter() { // clear stream flags; we use underlying streambuf I/O, do not // maintain ifstream flags, except eof if (is != nullptr) { is->clear(is->rdstate() & std::ios::eofbit); } } explicit input_stream_adapter(std::istream& i) : is(&i), sb(i.rdbuf()) {} // delete because of pointer members input_stream_adapter(const input_stream_adapter&) = delete; input_stream_adapter& operator=(input_stream_adapter&) = delete; input_stream_adapter& operator=(input_stream_adapter&&) = delete; input_stream_adapter(input_stream_adapter&& rhs) noexcept : is(rhs.is), sb(rhs.sb) { rhs.is = nullptr; rhs.sb = nullptr; } // std::istream/std::streambuf use std::char_traits::to_int_type, to // ensure that std::char_traits::eof() and the character 0xFF do not // end up as the same value, e.g. 0xFFFFFFFF. std::char_traits::int_type get_character() { auto res = sb->sbumpc(); // set eof manually, as we don't use the istream interface. if (JSON_HEDLEY_UNLIKELY(res == std::char_traits::eof())) { is->clear(is->rdstate() | std::ios::eofbit); } return res; } private: /// the associated input stream std::istream* is = nullptr; std::streambuf* sb = nullptr; }; #endif // JSON_NO_IO // General-purpose iterator-based adapter. It might not be as fast as // theoretically possible for some containers, but it is extremely versatile. template class iterator_input_adapter { public: using char_type = typename std::iterator_traits::value_type; iterator_input_adapter(IteratorType first, IteratorType last) : current(std::move(first)), end(std::move(last)) {} typename char_traits::int_type get_character() { if (JSON_HEDLEY_LIKELY(current != end)) { auto result = char_traits::to_int_type(*current); std::advance(current, 1); return result; } return char_traits::eof(); } private: IteratorType current; IteratorType end; template friend struct wide_string_input_helper; bool empty() const { return current == end; } }; template struct wide_string_input_helper; template struct wide_string_input_helper { // UTF-32 static void fill_buffer(BaseInputAdapter& input, std::array::int_type, 4>& utf8_bytes, size_t& utf8_bytes_index, size_t& utf8_bytes_filled) { utf8_bytes_index = 0; if (JSON_HEDLEY_UNLIKELY(input.empty())) { utf8_bytes[0] = std::char_traits::eof(); utf8_bytes_filled = 1; } else { // get the current character const auto wc = input.get_character(); // UTF-32 to UTF-8 encoding if (wc < 0x80) { utf8_bytes[0] = static_cast::int_type>(wc); utf8_bytes_filled = 1; } else if (wc <= 0x7FF) { utf8_bytes[0] = static_cast::int_type>(0xC0u | ((static_cast(wc) >> 6u) & 0x1Fu)); utf8_bytes[1] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); utf8_bytes_filled = 2; } else if (wc <= 0xFFFF) { utf8_bytes[0] = static_cast::int_type>(0xE0u | ((static_cast(wc) >> 12u) & 0x0Fu)); utf8_bytes[1] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 6u) & 0x3Fu)); utf8_bytes[2] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); utf8_bytes_filled = 3; } else if (wc <= 0x10FFFF) { utf8_bytes[0] = static_cast::int_type>(0xF0u | ((static_cast(wc) >> 18u) & 0x07u)); utf8_bytes[1] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 12u) & 0x3Fu)); utf8_bytes[2] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 6u) & 0x3Fu)); utf8_bytes[3] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); utf8_bytes_filled = 4; } else { // unknown character utf8_bytes[0] = static_cast::int_type>(wc); utf8_bytes_filled = 1; } } } }; template struct wide_string_input_helper { // UTF-16 static void fill_buffer(BaseInputAdapter& input, std::array::int_type, 4>& utf8_bytes, size_t& utf8_bytes_index, size_t& utf8_bytes_filled) { utf8_bytes_index = 0; if (JSON_HEDLEY_UNLIKELY(input.empty())) { utf8_bytes[0] = std::char_traits::eof(); utf8_bytes_filled = 1; } else { // get the current character const auto wc = input.get_character(); // UTF-16 to UTF-8 encoding if (wc < 0x80) { utf8_bytes[0] = static_cast::int_type>(wc); utf8_bytes_filled = 1; } else if (wc <= 0x7FF) { utf8_bytes[0] = static_cast::int_type>(0xC0u | ((static_cast(wc) >> 6u))); utf8_bytes[1] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); utf8_bytes_filled = 2; } else if (0xD800 > wc || wc >= 0xE000) { utf8_bytes[0] = static_cast::int_type>(0xE0u | ((static_cast(wc) >> 12u))); utf8_bytes[1] = static_cast::int_type>(0x80u | ((static_cast(wc) >> 6u) & 0x3Fu)); utf8_bytes[2] = static_cast::int_type>(0x80u | (static_cast(wc) & 0x3Fu)); utf8_bytes_filled = 3; } else { if (JSON_HEDLEY_UNLIKELY(!input.empty())) { const auto wc2 = static_cast(input.get_character()); const auto charcode = 0x10000u + (((static_cast(wc) & 0x3FFu) << 10u) | (wc2 & 0x3FFu)); utf8_bytes[0] = static_cast::int_type>(0xF0u | (charcode >> 18u)); utf8_bytes[1] = static_cast::int_type>(0x80u | ((charcode >> 12u) & 0x3Fu)); utf8_bytes[2] = static_cast::int_type>(0x80u | ((charcode >> 6u) & 0x3Fu)); utf8_bytes[3] = static_cast::int_type>(0x80u | (charcode & 0x3Fu)); utf8_bytes_filled = 4; } else { utf8_bytes[0] = static_cast::int_type>(wc); utf8_bytes_filled = 1; } } } } }; // Wraps another input adapter to convert wide character types into individual bytes. template class wide_string_input_adapter { public: using char_type = char; wide_string_input_adapter(BaseInputAdapter base) : base_adapter(base) {} typename std::char_traits::int_type get_character() noexcept { // check if buffer needs to be filled if (utf8_bytes_index == utf8_bytes_filled) { fill_buffer(); JSON_ASSERT(utf8_bytes_filled > 0); JSON_ASSERT(utf8_bytes_index == 0); } // use buffer JSON_ASSERT(utf8_bytes_filled > 0); JSON_ASSERT(utf8_bytes_index < utf8_bytes_filled); return utf8_bytes[utf8_bytes_index++]; } private: BaseInputAdapter base_adapter; template void fill_buffer() { wide_string_input_helper::fill_buffer(base_adapter, utf8_bytes, utf8_bytes_index, utf8_bytes_filled); } /// a buffer for UTF-8 bytes std::array::int_type, 4> utf8_bytes = {{0, 0, 0, 0}}; /// index to the utf8_codes array for the next valid byte std::size_t utf8_bytes_index = 0; /// number of valid bytes in the utf8_codes array std::size_t utf8_bytes_filled = 0; }; template struct iterator_input_adapter_factory { using iterator_type = IteratorType; using char_type = typename std::iterator_traits::value_type; using adapter_type = iterator_input_adapter; static adapter_type create(IteratorType first, IteratorType last) { return adapter_type(std::move(first), std::move(last)); } }; template struct is_iterator_of_multibyte { using value_type = typename std::iterator_traits::value_type; enum { value = sizeof(value_type) > 1 }; }; template struct iterator_input_adapter_factory::value>> { using iterator_type = IteratorType; using char_type = typename std::iterator_traits::value_type; using base_adapter_type = iterator_input_adapter; using adapter_type = wide_string_input_adapter; static adapter_type create(IteratorType first, IteratorType last) { return adapter_type(base_adapter_type(std::move(first), std::move(last))); } }; // General purpose iterator-based input template typename iterator_input_adapter_factory::adapter_type input_adapter(IteratorType first, IteratorType last) { using factory_type = iterator_input_adapter_factory; return factory_type::create(first, last); } // Convenience shorthand from container to iterator // Enables ADL on begin(container) and end(container) // Encloses the using declarations in namespace for not to leak them to outside scope namespace container_input_adapter_factory_impl { using std::begin; using std::end; template struct container_input_adapter_factory {}; template struct container_input_adapter_factory< ContainerType, void_t()), end(std::declval()))>> { using adapter_type = decltype(input_adapter(begin(std::declval()), end(std::declval()))); static adapter_type create(const ContainerType& container) { return input_adapter(begin(container), end(container)); } }; } // namespace container_input_adapter_factory_impl template typename container_input_adapter_factory_impl::container_input_adapter_factory::adapter_type input_adapter(const ContainerType& container) { return container_input_adapter_factory_impl::container_input_adapter_factory::create(container); } #ifndef JSON_NO_IO // Special cases with fast paths inline file_input_adapter input_adapter(std::FILE* file) { return file_input_adapter(file); } inline input_stream_adapter input_adapter(std::istream& stream) { return input_stream_adapter(stream); } inline input_stream_adapter input_adapter(std::istream&& stream) { return input_stream_adapter(stream); } #endif // JSON_NO_IO using contiguous_bytes_input_adapter = decltype(input_adapter(std::declval(), std::declval())); // Null-delimited strings, and the like. template < typename CharT, typename std::enable_if < std::is_pointer::value&& !std::is_array::value&& std::is_integral::type>::value&& sizeof(typename std::remove_pointer::type) == 1, int >::type = 0 > contiguous_bytes_input_adapter input_adapter(CharT b) { auto length = std::strlen(reinterpret_cast(b)); const auto* ptr = reinterpret_cast(b); return input_adapter(ptr, ptr + length); } template auto input_adapter(T (&array)[N]) -> decltype(input_adapter(array, array + N)) // NOLINT(cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays) { return input_adapter(array, array + N); } // This class only handles inputs of input_buffer_adapter type. // It's required so that expressions like {ptr, len} can be implicitly cast // to the correct adapter. class span_input_adapter { public: template < typename CharT, typename std::enable_if < std::is_pointer::value&& std::is_integral::type>::value&& sizeof(typename std::remove_pointer::type) == 1, int >::type = 0 > span_input_adapter(CharT b, std::size_t l) : ia(reinterpret_cast(b), reinterpret_cast(b) + l) {} template::iterator_category, std::random_access_iterator_tag>::value, int>::type = 0> span_input_adapter(IteratorType first, IteratorType last) : ia(input_adapter(first, last)) {} contiguous_bytes_input_adapter&& get() { return std::move(ia); // NOLINT(hicpp-move-const-arg,performance-move-const-arg) } private: contiguous_bytes_input_adapter ia; }; } // namespace detail NLOHMANN_JSON_NAMESPACE_END ================================================ FILE: Libs/nlohmann/detail/input/json_sax.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include #include // string #include // move #include // vector #include #include #include NLOHMANN_JSON_NAMESPACE_BEGIN /*! @brief SAX interface This class describes the SAX interface used by @ref nlohmann::json::sax_parse. Each function is called in different situations while the input is parsed. The boolean return value informs the parser whether to continue processing the input. */ template struct json_sax { using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; /*! @brief a null value was read @return whether parsing should proceed */ virtual bool null() = 0; /*! @brief a boolean value was read @param[in] val boolean value @return whether parsing should proceed */ virtual bool boolean(bool val) = 0; /*! @brief an integer number was read @param[in] val integer value @return whether parsing should proceed */ virtual bool number_integer(number_integer_t val) = 0; /*! @brief an unsigned integer number was read @param[in] val unsigned integer value @return whether parsing should proceed */ virtual bool number_unsigned(number_unsigned_t val) = 0; /*! @brief a floating-point number was read @param[in] val floating-point value @param[in] s raw token value @return whether parsing should proceed */ virtual bool number_float(number_float_t val, const string_t& s) = 0; /*! @brief a string value was read @param[in] val string value @return whether parsing should proceed @note It is safe to move the passed string value. */ virtual bool string(string_t& val) = 0; /*! @brief a binary value was read @param[in] val binary value @return whether parsing should proceed @note It is safe to move the passed binary value. */ virtual bool binary(binary_t& val) = 0; /*! @brief the beginning of an object was read @param[in] elements number of object elements or -1 if unknown @return whether parsing should proceed @note binary formats may report the number of elements */ virtual bool start_object(std::size_t elements) = 0; /*! @brief an object key was read @param[in] val object key @return whether parsing should proceed @note It is safe to move the passed string. */ virtual bool key(string_t& val) = 0; /*! @brief the end of an object was read @return whether parsing should proceed */ virtual bool end_object() = 0; /*! @brief the beginning of an array was read @param[in] elements number of array elements or -1 if unknown @return whether parsing should proceed @note binary formats may report the number of elements */ virtual bool start_array(std::size_t elements) = 0; /*! @brief the end of an array was read @return whether parsing should proceed */ virtual bool end_array() = 0; /*! @brief a parse error occurred @param[in] position the position in the input where the error occurs @param[in] last_token the last read token @param[in] ex an exception object describing the error @return whether parsing should proceed (must return false) */ virtual bool parse_error(std::size_t position, const std::string& last_token, const detail::exception& ex) = 0; json_sax() = default; json_sax(const json_sax&) = default; json_sax(json_sax&&) noexcept = default; json_sax& operator=(const json_sax&) = default; json_sax& operator=(json_sax&&) noexcept = default; virtual ~json_sax() = default; }; namespace detail { /*! @brief SAX implementation to create a JSON value from SAX events This class implements the @ref json_sax interface and processes the SAX events to create a JSON value which makes it basically a DOM parser. The structure or hierarchy of the JSON value is managed by the stack `ref_stack` which contains a pointer to the respective array or object for each recursion depth. After successful parsing, the value that is passed by reference to the constructor contains the parsed value. @tparam BasicJsonType the JSON type */ template class json_sax_dom_parser { public: using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; /*! @param[in,out] r reference to a JSON value that is manipulated while parsing @param[in] allow_exceptions_ whether parse errors yield exceptions */ explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true) : root(r), allow_exceptions(allow_exceptions_) {} // make class move-only json_sax_dom_parser(const json_sax_dom_parser&) = delete; json_sax_dom_parser(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) json_sax_dom_parser& operator=(const json_sax_dom_parser&) = delete; json_sax_dom_parser& operator=(json_sax_dom_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) ~json_sax_dom_parser() = default; bool null() { handle_value(nullptr); return true; } bool boolean(bool val) { handle_value(val); return true; } bool number_integer(number_integer_t val) { handle_value(val); return true; } bool number_unsigned(number_unsigned_t val) { handle_value(val); return true; } bool number_float(number_float_t val, const string_t& /*unused*/) { handle_value(val); return true; } bool string(string_t& val) { handle_value(val); return true; } bool binary(binary_t& val) { handle_value(std::move(val)); return true; } bool start_object(std::size_t len) { ref_stack.push_back(handle_value(BasicJsonType::value_t::object)); if (JSON_HEDLEY_UNLIKELY(len != static_cast(-1) && len > ref_stack.back()->max_size())) { JSON_THROW(out_of_range::create(408, concat("excessive object size: ", std::to_string(len)), ref_stack.back())); } return true; } bool key(string_t& val) { JSON_ASSERT(!ref_stack.empty()); JSON_ASSERT(ref_stack.back()->is_object()); // add null at given key and store the reference for later object_element = &(ref_stack.back()->m_data.m_value.object->operator[](val)); return true; } bool end_object() { JSON_ASSERT(!ref_stack.empty()); JSON_ASSERT(ref_stack.back()->is_object()); ref_stack.back()->set_parents(); ref_stack.pop_back(); return true; } bool start_array(std::size_t len) { ref_stack.push_back(handle_value(BasicJsonType::value_t::array)); if (JSON_HEDLEY_UNLIKELY(len != static_cast(-1) && len > ref_stack.back()->max_size())) { JSON_THROW(out_of_range::create(408, concat("excessive array size: ", std::to_string(len)), ref_stack.back())); } return true; } bool end_array() { JSON_ASSERT(!ref_stack.empty()); JSON_ASSERT(ref_stack.back()->is_array()); ref_stack.back()->set_parents(); ref_stack.pop_back(); return true; } template bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const Exception& ex) { errored = true; static_cast(ex); if (allow_exceptions) { JSON_THROW(ex); } return false; } constexpr bool is_errored() const { return errored; } private: /*! @invariant If the ref stack is empty, then the passed value will be the new root. @invariant If the ref stack contains a value, then it is an array or an object to which we can add elements */ template JSON_HEDLEY_RETURNS_NON_NULL BasicJsonType* handle_value(Value&& v) { if (ref_stack.empty()) { root = BasicJsonType(std::forward(v)); return &root; } JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object()); if (ref_stack.back()->is_array()) { ref_stack.back()->m_data.m_value.array->emplace_back(std::forward(v)); return &(ref_stack.back()->m_data.m_value.array->back()); } JSON_ASSERT(ref_stack.back()->is_object()); JSON_ASSERT(object_element); *object_element = BasicJsonType(std::forward(v)); return object_element; } /// the parsed JSON value BasicJsonType& root; /// stack to model hierarchy of values std::vector ref_stack {}; /// helper to hold the reference for the next object element BasicJsonType* object_element = nullptr; /// whether a syntax error occurred bool errored = false; /// whether to throw exceptions in case of errors const bool allow_exceptions = true; }; template class json_sax_dom_callback_parser { public: using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; using parser_callback_t = typename BasicJsonType::parser_callback_t; using parse_event_t = typename BasicJsonType::parse_event_t; json_sax_dom_callback_parser(BasicJsonType& r, const parser_callback_t cb, const bool allow_exceptions_ = true) : root(r), callback(cb), allow_exceptions(allow_exceptions_) { keep_stack.push_back(true); } // make class move-only json_sax_dom_callback_parser(const json_sax_dom_callback_parser&) = delete; json_sax_dom_callback_parser(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) json_sax_dom_callback_parser& operator=(const json_sax_dom_callback_parser&) = delete; json_sax_dom_callback_parser& operator=(json_sax_dom_callback_parser&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) ~json_sax_dom_callback_parser() = default; bool null() { handle_value(nullptr); return true; } bool boolean(bool val) { handle_value(val); return true; } bool number_integer(number_integer_t val) { handle_value(val); return true; } bool number_unsigned(number_unsigned_t val) { handle_value(val); return true; } bool number_float(number_float_t val, const string_t& /*unused*/) { handle_value(val); return true; } bool string(string_t& val) { handle_value(val); return true; } bool binary(binary_t& val) { handle_value(std::move(val)); return true; } bool start_object(std::size_t len) { // check callback for object start const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::object_start, discarded); keep_stack.push_back(keep); auto val = handle_value(BasicJsonType::value_t::object, true); ref_stack.push_back(val.second); // check object limit if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != static_cast(-1) && len > ref_stack.back()->max_size())) { JSON_THROW(out_of_range::create(408, concat("excessive object size: ", std::to_string(len)), ref_stack.back())); } return true; } bool key(string_t& val) { BasicJsonType k = BasicJsonType(val); // check callback for key const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::key, k); key_keep_stack.push_back(keep); // add discarded value at given key and store the reference for later if (keep && ref_stack.back()) { object_element = &(ref_stack.back()->m_data.m_value.object->operator[](val) = discarded); } return true; } bool end_object() { if (ref_stack.back()) { if (!callback(static_cast(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back())) { // discard object *ref_stack.back() = discarded; } else { ref_stack.back()->set_parents(); } } JSON_ASSERT(!ref_stack.empty()); JSON_ASSERT(!keep_stack.empty()); ref_stack.pop_back(); keep_stack.pop_back(); if (!ref_stack.empty() && ref_stack.back() && ref_stack.back()->is_structured()) { // remove discarded value for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it) { if (it->is_discarded()) { ref_stack.back()->erase(it); break; } } } return true; } bool start_array(std::size_t len) { const bool keep = callback(static_cast(ref_stack.size()), parse_event_t::array_start, discarded); keep_stack.push_back(keep); auto val = handle_value(BasicJsonType::value_t::array, true); ref_stack.push_back(val.second); // check array limit if (ref_stack.back() && JSON_HEDLEY_UNLIKELY(len != static_cast(-1) && len > ref_stack.back()->max_size())) { JSON_THROW(out_of_range::create(408, concat("excessive array size: ", std::to_string(len)), ref_stack.back())); } return true; } bool end_array() { bool keep = true; if (ref_stack.back()) { keep = callback(static_cast(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back()); if (keep) { ref_stack.back()->set_parents(); } else { // discard array *ref_stack.back() = discarded; } } JSON_ASSERT(!ref_stack.empty()); JSON_ASSERT(!keep_stack.empty()); ref_stack.pop_back(); keep_stack.pop_back(); // remove discarded value if (!keep && !ref_stack.empty() && ref_stack.back()->is_array()) { ref_stack.back()->m_data.m_value.array->pop_back(); } return true; } template bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const Exception& ex) { errored = true; static_cast(ex); if (allow_exceptions) { JSON_THROW(ex); } return false; } constexpr bool is_errored() const { return errored; } private: /*! @param[in] v value to add to the JSON value we build during parsing @param[in] skip_callback whether we should skip calling the callback function; this is required after start_array() and start_object() SAX events, because otherwise we would call the callback function with an empty array or object, respectively. @invariant If the ref stack is empty, then the passed value will be the new root. @invariant If the ref stack contains a value, then it is an array or an object to which we can add elements @return pair of boolean (whether value should be kept) and pointer (to the passed value in the ref_stack hierarchy; nullptr if not kept) */ template std::pair handle_value(Value&& v, const bool skip_callback = false) { JSON_ASSERT(!keep_stack.empty()); // do not handle this value if we know it would be added to a discarded // container if (!keep_stack.back()) { return {false, nullptr}; } // create value auto value = BasicJsonType(std::forward(v)); // check callback const bool keep = skip_callback || callback(static_cast(ref_stack.size()), parse_event_t::value, value); // do not handle this value if we just learnt it shall be discarded if (!keep) { return {false, nullptr}; } if (ref_stack.empty()) { root = std::move(value); return {true, & root}; } // skip this value if we already decided to skip the parent // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360) if (!ref_stack.back()) { return {false, nullptr}; } // we now only expect arrays and objects JSON_ASSERT(ref_stack.back()->is_array() || ref_stack.back()->is_object()); // array if (ref_stack.back()->is_array()) { ref_stack.back()->m_data.m_value.array->emplace_back(std::move(value)); return {true, & (ref_stack.back()->m_data.m_value.array->back())}; } // object JSON_ASSERT(ref_stack.back()->is_object()); // check if we should store an element for the current key JSON_ASSERT(!key_keep_stack.empty()); const bool store_element = key_keep_stack.back(); key_keep_stack.pop_back(); if (!store_element) { return {false, nullptr}; } JSON_ASSERT(object_element); *object_element = std::move(value); return {true, object_element}; } /// the parsed JSON value BasicJsonType& root; /// stack to model hierarchy of values std::vector ref_stack {}; /// stack to manage which values to keep std::vector keep_stack {}; // NOLINT(readability-redundant-member-init) /// stack to manage which object keys to keep std::vector key_keep_stack {}; // NOLINT(readability-redundant-member-init) /// helper to hold the reference for the next object element BasicJsonType* object_element = nullptr; /// whether a syntax error occurred bool errored = false; /// callback function const parser_callback_t callback = nullptr; /// whether to throw exceptions in case of errors const bool allow_exceptions = true; /// a discarded value for the callback BasicJsonType discarded = BasicJsonType::value_t::discarded; }; template class json_sax_acceptor { public: using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; bool null() { return true; } bool boolean(bool /*unused*/) { return true; } bool number_integer(number_integer_t /*unused*/) { return true; } bool number_unsigned(number_unsigned_t /*unused*/) { return true; } bool number_float(number_float_t /*unused*/, const string_t& /*unused*/) { return true; } bool string(string_t& /*unused*/) { return true; } bool binary(binary_t& /*unused*/) { return true; } bool start_object(std::size_t /*unused*/ = static_cast(-1)) { return true; } bool key(string_t& /*unused*/) { return true; } bool end_object() { return true; } bool start_array(std::size_t /*unused*/ = static_cast(-1)) { return true; } bool end_array() { return true; } bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/) { return false; } }; } // namespace detail NLOHMANN_JSON_NAMESPACE_END ================================================ FILE: Libs/nlohmann/detail/input/lexer.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include // array #include // localeconv #include // size_t #include // snprintf #include // strtof, strtod, strtold, strtoll, strtoull #include // initializer_list #include // char_traits, string #include // move #include // vector #include #include #include #include NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { /////////// // lexer // /////////// template class lexer_base { public: /// token types for the parser enum class token_type { uninitialized, ///< indicating the scanner is uninitialized literal_true, ///< the `true` literal literal_false, ///< the `false` literal literal_null, ///< the `null` literal value_string, ///< a string -- use get_string() for actual value value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value value_integer, ///< a signed integer -- use get_number_integer() for actual value value_float, ///< an floating point number -- use get_number_float() for actual value begin_array, ///< the character for array begin `[` begin_object, ///< the character for object begin `{` end_array, ///< the character for array end `]` end_object, ///< the character for object end `}` name_separator, ///< the name separator `:` value_separator, ///< the value separator `,` parse_error, ///< indicating a parse error end_of_input, ///< indicating the end of the input buffer literal_or_value ///< a literal or the begin of a value (only for diagnostics) }; /// return name of values of type token_type (only used for errors) JSON_HEDLEY_RETURNS_NON_NULL JSON_HEDLEY_CONST static const char* token_type_name(const token_type t) noexcept { switch (t) { case token_type::uninitialized: return ""; case token_type::literal_true: return "true literal"; case token_type::literal_false: return "false literal"; case token_type::literal_null: return "null literal"; case token_type::value_string: return "string literal"; case token_type::value_unsigned: case token_type::value_integer: case token_type::value_float: return "number literal"; case token_type::begin_array: return "'['"; case token_type::begin_object: return "'{'"; case token_type::end_array: return "']'"; case token_type::end_object: return "'}'"; case token_type::name_separator: return "':'"; case token_type::value_separator: return "','"; case token_type::parse_error: return ""; case token_type::end_of_input: return "end of input"; case token_type::literal_or_value: return "'[', '{', or a literal"; // LCOV_EXCL_START default: // catch non-enum values return "unknown token"; // LCOV_EXCL_STOP } } }; /*! @brief lexical analysis This class organizes the lexical analysis during JSON deserialization. */ template class lexer : public lexer_base { using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using char_type = typename InputAdapterType::char_type; using char_int_type = typename char_traits::int_type; public: using token_type = typename lexer_base::token_type; explicit lexer(InputAdapterType&& adapter, bool ignore_comments_ = false) noexcept : ia(std::move(adapter)) , ignore_comments(ignore_comments_) , decimal_point_char(static_cast(get_decimal_point())) {} // delete because of pointer members lexer(const lexer&) = delete; lexer(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) lexer& operator=(lexer&) = delete; lexer& operator=(lexer&&) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor) ~lexer() = default; private: ///////////////////// // locales ///////////////////// /// return the locale-dependent decimal point JSON_HEDLEY_PURE static char get_decimal_point() noexcept { const auto* loc = localeconv(); JSON_ASSERT(loc != nullptr); return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point); } ///////////////////// // scan functions ///////////////////// /*! @brief get codepoint from 4 hex characters following `\u` For input "\u c1 c2 c3 c4" the codepoint is: (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4 = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0) Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f' must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The conversion is done by subtracting the offset (0x30, 0x37, and 0x57) between the ASCII value of the character and the desired integer value. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or non-hex character) */ int get_codepoint() { // this function only makes sense after reading `\u` JSON_ASSERT(current == 'u'); int codepoint = 0; const auto factors = { 12u, 8u, 4u, 0u }; for (const auto factor : factors) { get(); if (current >= '0' && current <= '9') { codepoint += static_cast((static_cast(current) - 0x30u) << factor); } else if (current >= 'A' && current <= 'F') { codepoint += static_cast((static_cast(current) - 0x37u) << factor); } else if (current >= 'a' && current <= 'f') { codepoint += static_cast((static_cast(current) - 0x57u) << factor); } else { return -1; } } JSON_ASSERT(0x0000 <= codepoint && codepoint <= 0xFFFF); return codepoint; } /*! @brief check if the next byte(s) are inside a given range Adds the current byte and, for each passed range, reads a new byte and checks if it is inside the range. If a violation was detected, set up an error message and return false. Otherwise, return true. @param[in] ranges list of integers; interpreted as list of pairs of inclusive lower and upper bound, respectively @pre The passed list @a ranges must have 2, 4, or 6 elements; that is, 1, 2, or 3 pairs. This precondition is enforced by an assertion. @return true if and only if no range violation was detected */ bool next_byte_in_range(std::initializer_list ranges) { JSON_ASSERT(ranges.size() == 2 || ranges.size() == 4 || ranges.size() == 6); add(current); for (auto range = ranges.begin(); range != ranges.end(); ++range) { get(); if (JSON_HEDLEY_LIKELY(*range <= current && current <= *(++range))) // NOLINT(bugprone-inc-dec-in-conditions) { add(current); } else { error_message = "invalid string: ill-formed UTF-8 byte"; return false; } } return true; } /*! @brief scan a string literal This function scans a string according to Sect. 7 of RFC 8259. While scanning, bytes are escaped and copied into buffer token_buffer. Then the function returns successfully, token_buffer is *not* null-terminated (as it may contain \0 bytes), and token_buffer.size() is the number of bytes in the string. @return token_type::value_string if string could be successfully scanned, token_type::parse_error otherwise @note In case of errors, variable error_message contains a textual description. */ token_type scan_string() { // reset token_buffer (ignore opening quote) reset(); // we entered the function by reading an open quote JSON_ASSERT(current == '\"'); while (true) { // get next character switch (get()) { // end of file while parsing string case char_traits::eof(): { error_message = "invalid string: missing closing quote"; return token_type::parse_error; } // closing quote case '\"': { return token_type::value_string; } // escapes case '\\': { switch (get()) { // quotation mark case '\"': add('\"'); break; // reverse solidus case '\\': add('\\'); break; // solidus case '/': add('/'); break; // backspace case 'b': add('\b'); break; // form feed case 'f': add('\f'); break; // line feed case 'n': add('\n'); break; // carriage return case 'r': add('\r'); break; // tab case 't': add('\t'); break; // unicode escapes case 'u': { const int codepoint1 = get_codepoint(); int codepoint = codepoint1; // start with codepoint1 if (JSON_HEDLEY_UNLIKELY(codepoint1 == -1)) { error_message = "invalid string: '\\u' must be followed by 4 hex digits"; return token_type::parse_error; } // check if code point is a high surrogate if (0xD800 <= codepoint1 && codepoint1 <= 0xDBFF) { // expect next \uxxxx entry if (JSON_HEDLEY_LIKELY(get() == '\\' && get() == 'u')) { const int codepoint2 = get_codepoint(); if (JSON_HEDLEY_UNLIKELY(codepoint2 == -1)) { error_message = "invalid string: '\\u' must be followed by 4 hex digits"; return token_type::parse_error; } // check if codepoint2 is a low surrogate if (JSON_HEDLEY_LIKELY(0xDC00 <= codepoint2 && codepoint2 <= 0xDFFF)) { // overwrite codepoint codepoint = static_cast( // high surrogate occupies the most significant 22 bits (static_cast(codepoint1) << 10u) // low surrogate occupies the least significant 15 bits + static_cast(codepoint2) // there is still the 0xD800, 0xDC00 and 0x10000 noise // in the result, so we have to subtract with: // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00 - 0x35FDC00u); } else { error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF"; return token_type::parse_error; } } else { error_message = "invalid string: surrogate U+D800..U+DBFF must be followed by U+DC00..U+DFFF"; return token_type::parse_error; } } else { if (JSON_HEDLEY_UNLIKELY(0xDC00 <= codepoint1 && codepoint1 <= 0xDFFF)) { error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF"; return token_type::parse_error; } } // result of the above calculation yields a proper codepoint JSON_ASSERT(0x00 <= codepoint && codepoint <= 0x10FFFF); // translate codepoint into bytes if (codepoint < 0x80) { // 1-byte characters: 0xxxxxxx (ASCII) add(static_cast(codepoint)); } else if (codepoint <= 0x7FF) { // 2-byte characters: 110xxxxx 10xxxxxx add(static_cast(0xC0u | (static_cast(codepoint) >> 6u))); add(static_cast(0x80u | (static_cast(codepoint) & 0x3Fu))); } else if (codepoint <= 0xFFFF) { // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx add(static_cast(0xE0u | (static_cast(codepoint) >> 12u))); add(static_cast(0x80u | ((static_cast(codepoint) >> 6u) & 0x3Fu))); add(static_cast(0x80u | (static_cast(codepoint) & 0x3Fu))); } else { // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx add(static_cast(0xF0u | (static_cast(codepoint) >> 18u))); add(static_cast(0x80u | ((static_cast(codepoint) >> 12u) & 0x3Fu))); add(static_cast(0x80u | ((static_cast(codepoint) >> 6u) & 0x3Fu))); add(static_cast(0x80u | (static_cast(codepoint) & 0x3Fu))); } break; } // other characters after escape default: error_message = "invalid string: forbidden character after backslash"; return token_type::parse_error; } break; } // invalid control characters case 0x00: { error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000"; return token_type::parse_error; } case 0x01: { error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001"; return token_type::parse_error; } case 0x02: { error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002"; return token_type::parse_error; } case 0x03: { error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003"; return token_type::parse_error; } case 0x04: { error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004"; return token_type::parse_error; } case 0x05: { error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005"; return token_type::parse_error; } case 0x06: { error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006"; return token_type::parse_error; } case 0x07: { error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007"; return token_type::parse_error; } case 0x08: { error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b"; return token_type::parse_error; } case 0x09: { error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t"; return token_type::parse_error; } case 0x0A: { error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n"; return token_type::parse_error; } case 0x0B: { error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B"; return token_type::parse_error; } case 0x0C: { error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f"; return token_type::parse_error; } case 0x0D: { error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r"; return token_type::parse_error; } case 0x0E: { error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E"; return token_type::parse_error; } case 0x0F: { error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F"; return token_type::parse_error; } case 0x10: { error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010"; return token_type::parse_error; } case 0x11: { error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011"; return token_type::parse_error; } case 0x12: { error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012"; return token_type::parse_error; } case 0x13: { error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013"; return token_type::parse_error; } case 0x14: { error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014"; return token_type::parse_error; } case 0x15: { error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015"; return token_type::parse_error; } case 0x16: { error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016"; return token_type::parse_error; } case 0x17: { error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017"; return token_type::parse_error; } case 0x18: { error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018"; return token_type::parse_error; } case 0x19: { error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019"; return token_type::parse_error; } case 0x1A: { error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A"; return token_type::parse_error; } case 0x1B: { error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B"; return token_type::parse_error; } case 0x1C: { error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C"; return token_type::parse_error; } case 0x1D: { error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D"; return token_type::parse_error; } case 0x1E: { error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E"; return token_type::parse_error; } case 0x1F: { error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F"; return token_type::parse_error; } // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace)) case 0x20: case 0x21: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27: case 0x28: case 0x29: case 0x2A: case 0x2B: case 0x2C: case 0x2D: case 0x2E: case 0x2F: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: case 0x3A: case 0x3B: case 0x3C: case 0x3D: case 0x3E: case 0x3F: case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4A: case 0x4B: case 0x4C: case 0x4D: case 0x4E: case 0x4F: case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: case 0x58: case 0x59: case 0x5A: case 0x5B: case 0x5D: case 0x5E: case 0x5F: case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6A: case 0x6B: case 0x6C: case 0x6D: case 0x6E: case 0x6F: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: case 0x78: case 0x79: case 0x7A: case 0x7B: case 0x7C: case 0x7D: case 0x7E: case 0x7F: { add(current); break; } // U+0080..U+07FF: bytes C2..DF 80..BF case 0xC2: case 0xC3: case 0xC4: case 0xC5: case 0xC6: case 0xC7: case 0xC8: case 0xC9: case 0xCA: case 0xCB: case 0xCC: case 0xCD: case 0xCE: case 0xCF: case 0xD0: case 0xD1: case 0xD2: case 0xD3: case 0xD4: case 0xD5: case 0xD6: case 0xD7: case 0xD8: case 0xD9: case 0xDA: case 0xDB: case 0xDC: case 0xDD: case 0xDE: case 0xDF: { if (JSON_HEDLEY_UNLIKELY(!next_byte_in_range({0x80, 0xBF}))) { return token_type::parse_error; } break; } // U+0800..U+0FFF: bytes E0 A0..BF 80..BF case 0xE0: { if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF case 0xE1: case 0xE2: case 0xE3: case 0xE4: case 0xE5: case 0xE6: case 0xE7: case 0xE8: case 0xE9: case 0xEA: case 0xEB: case 0xEC: case 0xEE: case 0xEF: { if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+D000..U+D7FF: bytes ED 80..9F 80..BF case 0xED: { if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x9F, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF case 0xF0: { if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF case 0xF1: case 0xF2: case 0xF3: { if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF case 0xF4: { if (JSON_HEDLEY_UNLIKELY(!(next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // remaining bytes (80..C1 and F5..FF) are ill-formed default: { error_message = "invalid string: ill-formed UTF-8 byte"; return token_type::parse_error; } } } } /*! * @brief scan a comment * @return whether comment could be scanned successfully */ bool scan_comment() { switch (get()) { // single-line comments skip input until a newline or EOF is read case '/': { while (true) { switch (get()) { case '\n': case '\r': case char_traits::eof(): case '\0': return true; default: break; } } } // multi-line comments skip input until */ is read case '*': { while (true) { switch (get()) { case char_traits::eof(): case '\0': { error_message = "invalid comment; missing closing '*/'"; return false; } case '*': { switch (get()) { case '/': return true; default: { unget(); continue; } } } default: continue; } } } // unexpected character after reading '/' default: { error_message = "invalid comment; expecting '/' or '*' after '/'"; return false; } } } JSON_HEDLEY_NON_NULL(2) static void strtof(float& f, const char* str, char** endptr) noexcept { f = std::strtof(str, endptr); } JSON_HEDLEY_NON_NULL(2) static void strtof(double& f, const char* str, char** endptr) noexcept { f = std::strtod(str, endptr); } JSON_HEDLEY_NON_NULL(2) static void strtof(long double& f, const char* str, char** endptr) noexcept { f = std::strtold(str, endptr); } /*! @brief scan a number literal This function scans a string according to Sect. 6 of RFC 8259. The function is realized with a deterministic finite state machine derived from the grammar described in RFC 8259. Starting in state "init", the input is read and used to determined the next state. Only state "done" accepts the number. State "error" is a trap state to model errors. In the table below, "anything" means any character but the ones listed before. state | 0 | 1-9 | e E | + | - | . | anything ---------|----------|----------|----------|---------|---------|----------|----------- init | zero | any1 | [error] | [error] | minus | [error] | [error] minus | zero | any1 | [error] | [error] | [error] | [error] | [error] zero | done | done | exponent | done | done | decimal1 | done any1 | any1 | any1 | exponent | done | done | decimal1 | done decimal1 | decimal2 | decimal2 | [error] | [error] | [error] | [error] | [error] decimal2 | decimal2 | decimal2 | exponent | done | done | done | done exponent | any2 | any2 | [error] | sign | sign | [error] | [error] sign | any2 | any2 | [error] | [error] | [error] | [error] | [error] any2 | any2 | any2 | done | done | done | done | done The state machine is realized with one label per state (prefixed with "scan_number_") and `goto` statements between them. The state machine contains cycles, but any cycle can be left when EOF is read. Therefore, the function is guaranteed to terminate. During scanning, the read bytes are stored in token_buffer. This string is then converted to a signed integer, an unsigned integer, or a floating-point number. @return token_type::value_unsigned, token_type::value_integer, or token_type::value_float if number could be successfully scanned, token_type::parse_error otherwise @note The scanner is independent of the current locale. Internally, the locale's decimal point is used instead of `.` to work with the locale-dependent converters. */ token_type scan_number() // lgtm [cpp/use-of-goto] { // reset token_buffer to store the number's bytes reset(); // the type of the parsed number; initially set to unsigned; will be // changed if minus sign, decimal point or exponent is read token_type number_type = token_type::value_unsigned; // state (init): we just found out we need to scan a number switch (current) { case '-': { add(current); goto scan_number_minus; } case '0': { add(current); goto scan_number_zero; } case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any1; } // all other characters are rejected outside scan_number() default: // LCOV_EXCL_LINE JSON_ASSERT(false); // NOLINT(cert-dcl03-c,hicpp-static-assert,misc-static-assert) LCOV_EXCL_LINE } scan_number_minus: // state: we just parsed a leading minus sign number_type = token_type::value_integer; switch (get()) { case '0': { add(current); goto scan_number_zero; } case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any1; } default: { error_message = "invalid number; expected digit after '-'"; return token_type::parse_error; } } scan_number_zero: // state: we just parse a zero (maybe with a leading minus sign) switch (get()) { case '.': { add(decimal_point_char); goto scan_number_decimal1; } case 'e': case 'E': { add(current); goto scan_number_exponent; } default: goto scan_number_done; } scan_number_any1: // state: we just parsed a number 0-9 (maybe with a leading minus sign) switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any1; } case '.': { add(decimal_point_char); goto scan_number_decimal1; } case 'e': case 'E': { add(current); goto scan_number_exponent; } default: goto scan_number_done; } scan_number_decimal1: // state: we just parsed a decimal point number_type = token_type::value_float; switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_decimal2; } default: { error_message = "invalid number; expected digit after '.'"; return token_type::parse_error; } } scan_number_decimal2: // we just parsed at least one number after a decimal point switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_decimal2; } case 'e': case 'E': { add(current); goto scan_number_exponent; } default: goto scan_number_done; } scan_number_exponent: // we just parsed an exponent number_type = token_type::value_float; switch (get()) { case '+': case '-': { add(current); goto scan_number_sign; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any2; } default: { error_message = "invalid number; expected '+', '-', or digit after exponent"; return token_type::parse_error; } } scan_number_sign: // we just parsed an exponent sign switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any2; } default: { error_message = "invalid number; expected digit after exponent sign"; return token_type::parse_error; } } scan_number_any2: // we just parsed a number after the exponent or exponent sign switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any2; } default: goto scan_number_done; } scan_number_done: // unget the character after the number (we only read it to know that // we are done scanning a number) unget(); char* endptr = nullptr; // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) errno = 0; // try to parse integers first and fall back to floats if (number_type == token_type::value_unsigned) { const auto x = std::strtoull(token_buffer.data(), &endptr, 10); // we checked the number format before JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); if (errno == 0) { value_unsigned = static_cast(x); if (value_unsigned == x) { return token_type::value_unsigned; } } } else if (number_type == token_type::value_integer) { const auto x = std::strtoll(token_buffer.data(), &endptr, 10); // we checked the number format before JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); if (errno == 0) { value_integer = static_cast(x); if (value_integer == x) { return token_type::value_integer; } } } // this code is reached if we parse a floating-point number or if an // integer conversion above failed strtof(value_float, token_buffer.data(), &endptr); // we checked the number format before JSON_ASSERT(endptr == token_buffer.data() + token_buffer.size()); return token_type::value_float; } /*! @param[in] literal_text the literal text to expect @param[in] length the length of the passed literal text @param[in] return_type the token type to return on success */ JSON_HEDLEY_NON_NULL(2) token_type scan_literal(const char_type* literal_text, const std::size_t length, token_type return_type) { JSON_ASSERT(char_traits::to_char_type(current) == literal_text[0]); for (std::size_t i = 1; i < length; ++i) { if (JSON_HEDLEY_UNLIKELY(char_traits::to_char_type(get()) != literal_text[i])) { error_message = "invalid literal"; return token_type::parse_error; } } return return_type; } ///////////////////// // input management ///////////////////// /// reset token_buffer; current character is beginning of token void reset() noexcept { token_buffer.clear(); token_string.clear(); token_string.push_back(char_traits::to_char_type(current)); } /* @brief get next character from the input This function provides the interface to the used input adapter. It does not throw in case the input reached EOF, but returns a `char_traits::eof()` in that case. Stores the scanned characters for use in error messages. @return character read from the input */ char_int_type get() { ++position.chars_read_total; ++position.chars_read_current_line; if (next_unget) { // just reset the next_unget variable and work with current next_unget = false; } else { current = ia.get_character(); } if (JSON_HEDLEY_LIKELY(current != char_traits::eof())) { token_string.push_back(char_traits::to_char_type(current)); } if (current == '\n') { ++position.lines_read; position.chars_read_current_line = 0; } return current; } /*! @brief unget current character (read it again on next get) We implement unget by setting variable next_unget to true. The input is not changed - we just simulate ungetting by modifying chars_read_total, chars_read_current_line, and token_string. The next call to get() will behave as if the unget character is read again. */ void unget() { next_unget = true; --position.chars_read_total; // in case we "unget" a newline, we have to also decrement the lines_read if (position.chars_read_current_line == 0) { if (position.lines_read > 0) { --position.lines_read; } } else { --position.chars_read_current_line; } if (JSON_HEDLEY_LIKELY(current != char_traits::eof())) { JSON_ASSERT(!token_string.empty()); token_string.pop_back(); } } /// add a character to token_buffer void add(char_int_type c) { token_buffer.push_back(static_cast(c)); } public: ///////////////////// // value getters ///////////////////// /// return integer value constexpr number_integer_t get_number_integer() const noexcept { return value_integer; } /// return unsigned integer value constexpr number_unsigned_t get_number_unsigned() const noexcept { return value_unsigned; } /// return floating-point value constexpr number_float_t get_number_float() const noexcept { return value_float; } /// return current string value (implicitly resets the token; useful only once) string_t& get_string() { return token_buffer; } ///////////////////// // diagnostics ///////////////////// /// return position of last read token constexpr position_t get_position() const noexcept { return position; } /// return the last read token (for errors only). Will never contain EOF /// (an arbitrary value that is not a valid char value, often -1), because /// 255 may legitimately occur. May contain NUL, which should be escaped. std::string get_token_string() const { // escape control characters std::string result; for (const auto c : token_string) { if (static_cast(c) <= '\x1F') { // escape control characters std::array cs{{}}; static_cast((std::snprintf)(cs.data(), cs.size(), "", static_cast(c))); // NOLINT(cppcoreguidelines-pro-type-vararg,hicpp-vararg) result += cs.data(); } else { // add character as is result.push_back(static_cast(c)); } } return result; } /// return syntax error message JSON_HEDLEY_RETURNS_NON_NULL constexpr const char* get_error_message() const noexcept { return error_message; } ///////////////////// // actual scanner ///////////////////// /*! @brief skip the UTF-8 byte order mark @return true iff there is no BOM or the correct BOM has been skipped */ bool skip_bom() { if (get() == 0xEF) { // check if we completely parse the BOM return get() == 0xBB && get() == 0xBF; } // the first character is not the beginning of the BOM; unget it to // process is later unget(); return true; } void skip_whitespace() { do { get(); } while (current == ' ' || current == '\t' || current == '\n' || current == '\r'); } token_type scan() { // initially, skip the BOM if (position.chars_read_total == 0 && !skip_bom()) { error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given"; return token_type::parse_error; } // read next character and ignore whitespace skip_whitespace(); // ignore comments while (ignore_comments && current == '/') { if (!scan_comment()) { return token_type::parse_error; } // skip following whitespace skip_whitespace(); } switch (current) { // structural characters case '[': return token_type::begin_array; case ']': return token_type::end_array; case '{': return token_type::begin_object; case '}': return token_type::end_object; case ':': return token_type::name_separator; case ',': return token_type::value_separator; // literals case 't': { std::array true_literal = {{static_cast('t'), static_cast('r'), static_cast('u'), static_cast('e')}}; return scan_literal(true_literal.data(), true_literal.size(), token_type::literal_true); } case 'f': { std::array false_literal = {{static_cast('f'), static_cast('a'), static_cast('l'), static_cast('s'), static_cast('e')}}; return scan_literal(false_literal.data(), false_literal.size(), token_type::literal_false); } case 'n': { std::array null_literal = {{static_cast('n'), static_cast('u'), static_cast('l'), static_cast('l')}}; return scan_literal(null_literal.data(), null_literal.size(), token_type::literal_null); } // string case '\"': return scan_string(); // number case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return scan_number(); // end of input (the null byte is needed when parsing from // string literals) case '\0': case char_traits::eof(): return token_type::end_of_input; // error default: error_message = "invalid literal"; return token_type::parse_error; } } private: /// input adapter InputAdapterType ia; /// whether comments should be ignored (true) or signaled as errors (false) const bool ignore_comments = false; /// the current character char_int_type current = char_traits::eof(); /// whether the next get() call should just return current bool next_unget = false; /// the start position of the current token position_t position {}; /// raw input token string (for error messages) std::vector token_string {}; /// buffer for variable-length tokens (numbers, strings) string_t token_buffer {}; /// a description of occurred lexer errors const char* error_message = ""; // number values number_integer_t value_integer = 0; number_unsigned_t value_unsigned = 0; number_float_t value_float = 0; /// the decimal point const char_int_type decimal_point_char = '.'; }; } // namespace detail NLOHMANN_JSON_NAMESPACE_END ================================================ FILE: Libs/nlohmann/detail/input/parser.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include // isfinite #include // uint8_t #include // function #include // string #include // move #include // vector #include #include #include #include #include #include #include #include NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { //////////// // parser // //////////// enum class parse_event_t : std::uint8_t { /// the parser read `{` and started to process a JSON object object_start, /// the parser read `}` and finished processing a JSON object object_end, /// the parser read `[` and started to process a JSON array array_start, /// the parser read `]` and finished processing a JSON array array_end, /// the parser read a key of a value in an object key, /// the parser finished reading a JSON value value }; template using parser_callback_t = std::function; /*! @brief syntax analysis This class implements a recursive descent parser. */ template class parser { using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using lexer_t = lexer; using token_type = typename lexer_t::token_type; public: /// a parser reading from an input adapter explicit parser(InputAdapterType&& adapter, const parser_callback_t cb = nullptr, const bool allow_exceptions_ = true, const bool skip_comments = false) : callback(cb) , m_lexer(std::move(adapter), skip_comments) , allow_exceptions(allow_exceptions_) { // read first token get_token(); } /*! @brief public parser interface @param[in] strict whether to expect the last token to be EOF @param[in,out] result parsed JSON value @throw parse_error.101 in case of an unexpected token @throw parse_error.102 if to_unicode fails or surrogate error @throw parse_error.103 if to_unicode fails */ void parse(const bool strict, BasicJsonType& result) { if (callback) { json_sax_dom_callback_parser sdp(result, callback, allow_exceptions); sax_parse_internal(&sdp); // in strict mode, input must be completely read if (strict && (get_token() != token_type::end_of_input)) { sdp.parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), nullptr)); } // in case of an error, return discarded value if (sdp.is_errored()) { result = value_t::discarded; return; } // set top-level value to null if it was discarded by the callback // function if (result.is_discarded()) { result = nullptr; } } else { json_sax_dom_parser sdp(result, allow_exceptions); sax_parse_internal(&sdp); // in strict mode, input must be completely read if (strict && (get_token() != token_type::end_of_input)) { sdp.parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), nullptr)); } // in case of an error, return discarded value if (sdp.is_errored()) { result = value_t::discarded; return; } } result.assert_invariant(); } /*! @brief public accept interface @param[in] strict whether to expect the last token to be EOF @return whether the input is a proper JSON text */ bool accept(const bool strict = true) { json_sax_acceptor sax_acceptor; return sax_parse(&sax_acceptor, strict); } template JSON_HEDLEY_NON_NULL(2) bool sax_parse(SAX* sax, const bool strict = true) { (void)detail::is_sax_static_asserts {}; const bool result = sax_parse_internal(sax); // strict mode: next byte must be EOF if (result && strict && (get_token() != token_type::end_of_input)) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"), nullptr)); } return result; } private: template JSON_HEDLEY_NON_NULL(2) bool sax_parse_internal(SAX* sax) { // stack to remember the hierarchy of structured values we are parsing // true = array; false = object std::vector states; // value to avoid a goto (see comment where set to true) bool skip_to_state_evaluation = false; while (true) { if (!skip_to_state_evaluation) { // invariant: get_token() was called before each iteration switch (last_token) { case token_type::begin_object: { if (JSON_HEDLEY_UNLIKELY(!sax->start_object(static_cast(-1)))) { return false; } // closing } -> we are done if (get_token() == token_type::end_object) { if (JSON_HEDLEY_UNLIKELY(!sax->end_object())) { return false; } break; } // parse key if (JSON_HEDLEY_UNLIKELY(last_token != token_type::value_string)) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"), nullptr)); } if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string()))) { return false; } // parse separator (:) if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator)) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"), nullptr)); } // remember we are now inside an object states.push_back(false); // parse values get_token(); continue; } case token_type::begin_array: { if (JSON_HEDLEY_UNLIKELY(!sax->start_array(static_cast(-1)))) { return false; } // closing ] -> we are done if (get_token() == token_type::end_array) { if (JSON_HEDLEY_UNLIKELY(!sax->end_array())) { return false; } break; } // remember we are now inside an array states.push_back(true); // parse values (no need to call get_token) continue; } case token_type::value_float: { const auto res = m_lexer.get_number_float(); if (JSON_HEDLEY_UNLIKELY(!std::isfinite(res))) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), out_of_range::create(406, concat("number overflow parsing '", m_lexer.get_token_string(), '\''), nullptr)); } if (JSON_HEDLEY_UNLIKELY(!sax->number_float(res, m_lexer.get_string()))) { return false; } break; } case token_type::literal_false: { if (JSON_HEDLEY_UNLIKELY(!sax->boolean(false))) { return false; } break; } case token_type::literal_null: { if (JSON_HEDLEY_UNLIKELY(!sax->null())) { return false; } break; } case token_type::literal_true: { if (JSON_HEDLEY_UNLIKELY(!sax->boolean(true))) { return false; } break; } case token_type::value_integer: { if (JSON_HEDLEY_UNLIKELY(!sax->number_integer(m_lexer.get_number_integer()))) { return false; } break; } case token_type::value_string: { if (JSON_HEDLEY_UNLIKELY(!sax->string(m_lexer.get_string()))) { return false; } break; } case token_type::value_unsigned: { if (JSON_HEDLEY_UNLIKELY(!sax->number_unsigned(m_lexer.get_number_unsigned()))) { return false; } break; } case token_type::parse_error: { // using "uninitialized" to avoid "expected" message return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::uninitialized, "value"), nullptr)); } case token_type::end_of_input: { if (JSON_HEDLEY_UNLIKELY(m_lexer.get_position().chars_read_total == 1)) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), "attempting to parse an empty input; check that your input string or stream contains the expected JSON", nullptr)); } return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::literal_or_value, "value"), nullptr)); } case token_type::uninitialized: case token_type::end_array: case token_type::end_object: case token_type::name_separator: case token_type::value_separator: case token_type::literal_or_value: default: // the last token was unexpected { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::literal_or_value, "value"), nullptr)); } } } else { skip_to_state_evaluation = false; } // we reached this line after we successfully parsed a value if (states.empty()) { // empty stack: we reached the end of the hierarchy: done return true; } if (states.back()) // array { // comma -> next value if (get_token() == token_type::value_separator) { // parse a new value get_token(); continue; } // closing ] if (JSON_HEDLEY_LIKELY(last_token == token_type::end_array)) { if (JSON_HEDLEY_UNLIKELY(!sax->end_array())) { return false; } // We are done with this array. Before we can parse a // new value, we need to evaluate the new state first. // By setting skip_to_state_evaluation to false, we // are effectively jumping to the beginning of this if. JSON_ASSERT(!states.empty()); states.pop_back(); skip_to_state_evaluation = true; continue; } return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_array, "array"), nullptr)); } // states.back() is false -> object // comma -> next value if (get_token() == token_type::value_separator) { // parse key if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::value_string)) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"), nullptr)); } if (JSON_HEDLEY_UNLIKELY(!sax->key(m_lexer.get_string()))) { return false; } // parse separator (:) if (JSON_HEDLEY_UNLIKELY(get_token() != token_type::name_separator)) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"), nullptr)); } // parse values get_token(); continue; } // closing } if (JSON_HEDLEY_LIKELY(last_token == token_type::end_object)) { if (JSON_HEDLEY_UNLIKELY(!sax->end_object())) { return false; } // We are done with this object. Before we can parse a // new value, we need to evaluate the new state first. // By setting skip_to_state_evaluation to false, we // are effectively jumping to the beginning of this if. JSON_ASSERT(!states.empty()); states.pop_back(); skip_to_state_evaluation = true; continue; } return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_object, "object"), nullptr)); } } /// get next token from lexer token_type get_token() { return last_token = m_lexer.scan(); } std::string exception_message(const token_type expected, const std::string& context) { std::string error_msg = "syntax error "; if (!context.empty()) { error_msg += concat("while parsing ", context, ' '); } error_msg += "- "; if (last_token == token_type::parse_error) { error_msg += concat(m_lexer.get_error_message(), "; last read: '", m_lexer.get_token_string(), '\''); } else { error_msg += concat("unexpected ", lexer_t::token_type_name(last_token)); } if (expected != token_type::uninitialized) { error_msg += concat("; expected ", lexer_t::token_type_name(expected)); } return error_msg; } private: /// callback function const parser_callback_t callback = nullptr; /// the type of the last read token token_type last_token = token_type::uninitialized; /// the lexer lexer_t m_lexer; /// whether to throw exceptions in case of errors const bool allow_exceptions = true; }; } // namespace detail NLOHMANN_JSON_NAMESPACE_END ================================================ FILE: Libs/nlohmann/detail/input/position_t.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include // size_t #include NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { /// struct to capture the start position of the current token struct position_t { /// the total number of characters read std::size_t chars_read_total = 0; /// the number of characters read in the current line std::size_t chars_read_current_line = 0; /// the number of lines read std::size_t lines_read = 0; /// conversion to size_t to preserve SAX interface constexpr operator size_t() const { return chars_read_total; } }; } // namespace detail NLOHMANN_JSON_NAMESPACE_END ================================================ FILE: Libs/nlohmann/detail/iterators/internal_iterator.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include #include NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { /*! @brief an iterator value @note This structure could easily be a union, but MSVC currently does not allow unions members with complex constructors, see https://github.com/nlohmann/json/pull/105. */ template struct internal_iterator { /// iterator for JSON objects typename BasicJsonType::object_t::iterator object_iterator {}; /// iterator for JSON arrays typename BasicJsonType::array_t::iterator array_iterator {}; /// generic iterator for all other types primitive_iterator_t primitive_iterator {}; }; } // namespace detail NLOHMANN_JSON_NAMESPACE_END ================================================ FILE: Libs/nlohmann/detail/iterators/iter_impl.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next #include // conditional, is_const, remove_const #include #include #include #include #include #include #include NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { // forward declare, to be able to friend it later on template class iteration_proxy; template class iteration_proxy_value; /*! @brief a template for a bidirectional iterator for the @ref basic_json class This class implements a both iterators (iterator and const_iterator) for the @ref basic_json class. @note An iterator is called *initialized* when a pointer to a JSON value has been set (e.g., by a constructor or a copy assignment). If the iterator is default-constructed, it is *uninitialized* and most methods are undefined. **The library uses assertions to detect calls on uninitialized iterators.** @requirement The class satisfies the following concept requirements: - [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator): The iterator that can be moved can be moved in both directions (i.e. incremented and decremented). @since version 1.0.0, simplified in version 2.0.9, change to bidirectional iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593) */ template class iter_impl // NOLINT(cppcoreguidelines-special-member-functions,hicpp-special-member-functions) { /// the iterator with BasicJsonType of different const-ness using other_iter_impl = iter_impl::value, typename std::remove_const::type, const BasicJsonType>::type>; /// allow basic_json to access private members friend other_iter_impl; friend BasicJsonType; friend iteration_proxy; friend iteration_proxy_value; using object_t = typename BasicJsonType::object_t; using array_t = typename BasicJsonType::array_t; // make sure BasicJsonType is basic_json or const basic_json static_assert(is_basic_json::type>::value, "iter_impl only accepts (const) basic_json"); // superficial check for the LegacyBidirectionalIterator named requirement static_assert(std::is_base_of::value && std::is_base_of::iterator_category>::value, "basic_json iterator assumes array and object type iterators satisfy the LegacyBidirectionalIterator named requirement."); public: /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17. /// The C++ Standard has never required user-defined iterators to derive from std::iterator. /// A user-defined iterator should provide publicly accessible typedefs named /// iterator_category, value_type, difference_type, pointer, and reference. /// Note that value_type is required to be non-const, even for constant iterators. using iterator_category = std::bidirectional_iterator_tag; /// the type of the values when the iterator is dereferenced using value_type = typename BasicJsonType::value_type; /// a type to represent differences between iterators using difference_type = typename BasicJsonType::difference_type; /// defines a pointer to the type iterated over (value_type) using pointer = typename std::conditional::value, typename BasicJsonType::const_pointer, typename BasicJsonType::pointer>::type; /// defines a reference to the type iterated over (value_type) using reference = typename std::conditional::value, typename BasicJsonType::const_reference, typename BasicJsonType::reference>::type; iter_impl() = default; ~iter_impl() = default; iter_impl(iter_impl&&) noexcept = default; iter_impl& operator=(iter_impl&&) noexcept = default; /*! @brief constructor for a given JSON instance @param[in] object pointer to a JSON object for this iterator @pre object != nullptr @post The iterator is initialized; i.e. `m_object != nullptr`. */ explicit iter_impl(pointer object) noexcept : m_object(object) { JSON_ASSERT(m_object != nullptr); switch (m_object->m_data.m_type) { case value_t::object: { m_it.object_iterator = typename object_t::iterator(); break; } case value_t::array: { m_it.array_iterator = typename array_t::iterator(); break; } case value_t::null: case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: { m_it.primitive_iterator = primitive_iterator_t(); break; } } } /*! @note The conventional copy constructor and copy assignment are implicitly defined. Combined with the following converting constructor and assignment, they support: (1) copy from iterator to iterator, (2) copy from const iterator to const iterator, and (3) conversion from iterator to const iterator. However conversion from const iterator to iterator is not defined. */ /*! @brief const copy constructor @param[in] other const iterator to copy from @note This copy constructor had to be defined explicitly to circumvent a bug occurring on msvc v19.0 compiler (VS 2015) debug build. For more information refer to: https://github.com/nlohmann/json/issues/1608 */ iter_impl(const iter_impl& other) noexcept : m_object(other.m_object), m_it(other.m_it) {} /*! @brief converting assignment @param[in] other const iterator to copy from @return const/non-const iterator @note It is not checked whether @a other is initialized. */ iter_impl& operator=(const iter_impl& other) noexcept { if (&other != this) { m_object = other.m_object; m_it = other.m_it; } return *this; } /*! @brief converting constructor @param[in] other non-const iterator to copy from @note It is not checked whether @a other is initialized. */ iter_impl(const iter_impl::type>& other) noexcept : m_object(other.m_object), m_it(other.m_it) {} /*! @brief converting assignment @param[in] other non-const iterator to copy from @return const/non-const iterator @note It is not checked whether @a other is initialized. */ iter_impl& operator=(const iter_impl::type>& other) noexcept // NOLINT(cert-oop54-cpp) { m_object = other.m_object; m_it = other.m_it; return *this; } JSON_PRIVATE_UNLESS_TESTED: /*! @brief set the iterator to the first value @pre The iterator is initialized; i.e. `m_object != nullptr`. */ void set_begin() noexcept { JSON_ASSERT(m_object != nullptr); switch (m_object->m_data.m_type) { case value_t::object: { m_it.object_iterator = m_object->m_data.m_value.object->begin(); break; } case value_t::array: { m_it.array_iterator = m_object->m_data.m_value.array->begin(); break; } case value_t::null: { // set to end so begin()==end() is true: null is empty m_it.primitive_iterator.set_end(); break; } case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: { m_it.primitive_iterator.set_begin(); break; } } } /*! @brief set the iterator past the last value @pre The iterator is initialized; i.e. `m_object != nullptr`. */ void set_end() noexcept { JSON_ASSERT(m_object != nullptr); switch (m_object->m_data.m_type) { case value_t::object: { m_it.object_iterator = m_object->m_data.m_value.object->end(); break; } case value_t::array: { m_it.array_iterator = m_object->m_data.m_value.array->end(); break; } case value_t::null: case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: { m_it.primitive_iterator.set_end(); break; } } } public: /*! @brief return a reference to the value pointed to by the iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ reference operator*() const { JSON_ASSERT(m_object != nullptr); switch (m_object->m_data.m_type) { case value_t::object: { JSON_ASSERT(m_it.object_iterator != m_object->m_data.m_value.object->end()); return m_it.object_iterator->second; } case value_t::array: { JSON_ASSERT(m_it.array_iterator != m_object->m_data.m_value.array->end()); return *m_it.array_iterator; } case value_t::null: JSON_THROW(invalid_iterator::create(214, "cannot get value", m_object)); case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: { if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin())) { return *m_object; } JSON_THROW(invalid_iterator::create(214, "cannot get value", m_object)); } } } /*! @brief dereference the iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ pointer operator->() const { JSON_ASSERT(m_object != nullptr); switch (m_object->m_data.m_type) { case value_t::object: { JSON_ASSERT(m_it.object_iterator != m_object->m_data.m_value.object->end()); return &(m_it.object_iterator->second); } case value_t::array: { JSON_ASSERT(m_it.array_iterator != m_object->m_data.m_value.array->end()); return &*m_it.array_iterator; } case value_t::null: case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: { if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.is_begin())) { return m_object; } JSON_THROW(invalid_iterator::create(214, "cannot get value", m_object)); } } } /*! @brief post-increment (it++) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl operator++(int)& // NOLINT(cert-dcl21-cpp) { auto result = *this; ++(*this); return result; } /*! @brief pre-increment (++it) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator++() { JSON_ASSERT(m_object != nullptr); switch (m_object->m_data.m_type) { case value_t::object: { std::advance(m_it.object_iterator, 1); break; } case value_t::array: { std::advance(m_it.array_iterator, 1); break; } case value_t::null: case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: { ++m_it.primitive_iterator; break; } } return *this; } /*! @brief post-decrement (it--) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl operator--(int)& // NOLINT(cert-dcl21-cpp) { auto result = *this; --(*this); return result; } /*! @brief pre-decrement (--it) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator--() { JSON_ASSERT(m_object != nullptr); switch (m_object->m_data.m_type) { case value_t::object: { std::advance(m_it.object_iterator, -1); break; } case value_t::array: { std::advance(m_it.array_iterator, -1); break; } case value_t::null: case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: { --m_it.primitive_iterator; break; } } return *this; } /*! @brief comparison: equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ template < typename IterImpl, detail::enable_if_t < (std::is_same::value || std::is_same::value), std::nullptr_t > = nullptr > bool operator==(const IterImpl& other) const { // if objects are not the same, the comparison is undefined if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object)) { JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", m_object)); } JSON_ASSERT(m_object != nullptr); switch (m_object->m_data.m_type) { case value_t::object: return (m_it.object_iterator == other.m_it.object_iterator); case value_t::array: return (m_it.array_iterator == other.m_it.array_iterator); case value_t::null: case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: return (m_it.primitive_iterator == other.m_it.primitive_iterator); } } /*! @brief comparison: not equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ template < typename IterImpl, detail::enable_if_t < (std::is_same::value || std::is_same::value), std::nullptr_t > = nullptr > bool operator!=(const IterImpl& other) const { return !operator==(other); } /*! @brief comparison: smaller @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator<(const iter_impl& other) const { // if objects are not the same, the comparison is undefined if (JSON_HEDLEY_UNLIKELY(m_object != other.m_object)) { JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers", m_object)); } JSON_ASSERT(m_object != nullptr); switch (m_object->m_data.m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators", m_object)); case value_t::array: return (m_it.array_iterator < other.m_it.array_iterator); case value_t::null: case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: return (m_it.primitive_iterator < other.m_it.primitive_iterator); } } /*! @brief comparison: less than or equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator<=(const iter_impl& other) const { return !other.operator < (*this); } /*! @brief comparison: greater than @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator>(const iter_impl& other) const { return !operator<=(other); } /*! @brief comparison: greater than or equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator>=(const iter_impl& other) const { return !operator<(other); } /*! @brief add to iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator+=(difference_type i) { JSON_ASSERT(m_object != nullptr); switch (m_object->m_data.m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", m_object)); case value_t::array: { std::advance(m_it.array_iterator, i); break; } case value_t::null: case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: { m_it.primitive_iterator += i; break; } } return *this; } /*! @brief subtract from iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator-=(difference_type i) { return operator+=(-i); } /*! @brief add to iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl operator+(difference_type i) const { auto result = *this; result += i; return result; } /*! @brief addition of distance and iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ friend iter_impl operator+(difference_type i, const iter_impl& it) { auto result = it; result += i; return result; } /*! @brief subtract from iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl operator-(difference_type i) const { auto result = *this; result -= i; return result; } /*! @brief return difference @pre The iterator is initialized; i.e. `m_object != nullptr`. */ difference_type operator-(const iter_impl& other) const { JSON_ASSERT(m_object != nullptr); switch (m_object->m_data.m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators", m_object)); case value_t::array: return m_it.array_iterator - other.m_it.array_iterator; case value_t::null: case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: return m_it.primitive_iterator - other.m_it.primitive_iterator; } } /*! @brief access to successor @pre The iterator is initialized; i.e. `m_object != nullptr`. */ reference operator[](difference_type n) const { JSON_ASSERT(m_object != nullptr); switch (m_object->m_data.m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators", m_object)); case value_t::array: return *std::next(m_it.array_iterator, n); case value_t::null: JSON_THROW(invalid_iterator::create(214, "cannot get value", m_object)); case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: { if (JSON_HEDLEY_LIKELY(m_it.primitive_iterator.get_value() == -n)) { return *m_object; } JSON_THROW(invalid_iterator::create(214, "cannot get value", m_object)); } } } /*! @brief return the key of an object iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ const typename object_t::key_type& key() const { JSON_ASSERT(m_object != nullptr); if (JSON_HEDLEY_LIKELY(m_object->is_object())) { return m_it.object_iterator->first; } JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators", m_object)); } /*! @brief return the value of an iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ reference value() const { return operator*(); } JSON_PRIVATE_UNLESS_TESTED: /// associated JSON instance pointer m_object = nullptr; /// the actual iterator of the associated instance internal_iterator::type> m_it {}; }; } // namespace detail NLOHMANN_JSON_NAMESPACE_END ================================================ FILE: Libs/nlohmann/detail/iterators/iteration_proxy.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include // size_t #include // input_iterator_tag #include // string, to_string #include // tuple_size, get, tuple_element #include // move #if JSON_HAS_RANGES #include // enable_borrowed_range #endif #include #include #include NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { template void int_to_string( string_type& target, std::size_t value ) { // For ADL using std::to_string; target = to_string(value); } template class iteration_proxy_value { public: using difference_type = std::ptrdiff_t; using value_type = iteration_proxy_value; using pointer = value_type *; using reference = value_type &; using iterator_category = std::input_iterator_tag; using string_type = typename std::remove_cv< typename std::remove_reference().key() ) >::type >::type; private: /// the iterator IteratorType anchor{}; /// an index for arrays (used to create key names) std::size_t array_index = 0; /// last stringified array index mutable std::size_t array_index_last = 0; /// a string representation of the array index mutable string_type array_index_str = "0"; /// an empty string (to return a reference for primitive values) string_type empty_str{}; public: explicit iteration_proxy_value() = default; explicit iteration_proxy_value(IteratorType it, std::size_t array_index_ = 0) noexcept(std::is_nothrow_move_constructible::value && std::is_nothrow_default_constructible::value) : anchor(std::move(it)) , array_index(array_index_) {} iteration_proxy_value(iteration_proxy_value const&) = default; iteration_proxy_value& operator=(iteration_proxy_value const&) = default; // older GCCs are a bit fussy and require explicit noexcept specifiers on defaulted functions iteration_proxy_value(iteration_proxy_value&&) noexcept(std::is_nothrow_move_constructible::value && std::is_nothrow_move_constructible::value) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor,cppcoreguidelines-noexcept-move-operations) iteration_proxy_value& operator=(iteration_proxy_value&&) noexcept(std::is_nothrow_move_assignable::value && std::is_nothrow_move_assignable::value) = default; // NOLINT(hicpp-noexcept-move,performance-noexcept-move-constructor,cppcoreguidelines-noexcept-move-operations) ~iteration_proxy_value() = default; /// dereference operator (needed for range-based for) const iteration_proxy_value& operator*() const { return *this; } /// increment operator (needed for range-based for) iteration_proxy_value& operator++() { ++anchor; ++array_index; return *this; } iteration_proxy_value operator++(int)& // NOLINT(cert-dcl21-cpp) { auto tmp = iteration_proxy_value(anchor, array_index); ++anchor; ++array_index; return tmp; } /// equality operator (needed for InputIterator) bool operator==(const iteration_proxy_value& o) const { return anchor == o.anchor; } /// inequality operator (needed for range-based for) bool operator!=(const iteration_proxy_value& o) const { return anchor != o.anchor; } /// return key of the iterator const string_type& key() const { JSON_ASSERT(anchor.m_object != nullptr); switch (anchor.m_object->type()) { // use integer array index as key case value_t::array: { if (array_index != array_index_last) { int_to_string( array_index_str, array_index ); array_index_last = array_index; } return array_index_str; } // use key from the object case value_t::object: return anchor.key(); // use an empty key for all primitive types case value_t::null: case value_t::string: case value_t::boolean: case value_t::number_integer: case value_t::number_unsigned: case value_t::number_float: case value_t::binary: case value_t::discarded: default: return empty_str; } } /// return value of the iterator typename IteratorType::reference value() const { return anchor.value(); } }; /// proxy class for the items() function template class iteration_proxy { private: /// the container to iterate typename IteratorType::pointer container = nullptr; public: explicit iteration_proxy() = default; /// construct iteration proxy from a container explicit iteration_proxy(typename IteratorType::reference cont) noexcept : container(&cont) {} iteration_proxy(iteration_proxy const&) = default; iteration_proxy& operator=(iteration_proxy const&) = default; iteration_proxy(iteration_proxy&&) noexcept = default; iteration_proxy& operator=(iteration_proxy&&) noexcept = default; ~iteration_proxy() = default; /// return iterator begin (needed for range-based for) iteration_proxy_value begin() const noexcept { return iteration_proxy_value(container->begin()); } /// return iterator end (needed for range-based for) iteration_proxy_value end() const noexcept { return iteration_proxy_value(container->end()); } }; // Structured Bindings Support // For further reference see https://blog.tartanllama.xyz/structured-bindings/ // And see https://github.com/nlohmann/json/pull/1391 template = 0> auto get(const nlohmann::detail::iteration_proxy_value& i) -> decltype(i.key()) { return i.key(); } // Structured Bindings Support // For further reference see https://blog.tartanllama.xyz/structured-bindings/ // And see https://github.com/nlohmann/json/pull/1391 template = 0> auto get(const nlohmann::detail::iteration_proxy_value& i) -> decltype(i.value()) { return i.value(); } } // namespace detail NLOHMANN_JSON_NAMESPACE_END // The Addition to the STD Namespace is required to add // Structured Bindings Support to the iteration_proxy_value class // For further reference see https://blog.tartanllama.xyz/structured-bindings/ // And see https://github.com/nlohmann/json/pull/1391 namespace std { #if defined(__clang__) // Fix: https://github.com/nlohmann/json/issues/1401 #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wmismatched-tags" #endif template class tuple_size<::nlohmann::detail::iteration_proxy_value> // NOLINT(cert-dcl58-cpp) : public std::integral_constant {}; template class tuple_element> // NOLINT(cert-dcl58-cpp) { public: using type = decltype( get(std::declval < ::nlohmann::detail::iteration_proxy_value> ())); }; #if defined(__clang__) #pragma clang diagnostic pop #endif } // namespace std #if JSON_HAS_RANGES template inline constexpr bool ::std::ranges::enable_borrowed_range<::nlohmann::detail::iteration_proxy> = true; #endif ================================================ FILE: Libs/nlohmann/detail/iterators/iterator_traits.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include // random_access_iterator_tag #include #include #include NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { template struct iterator_types {}; template struct iterator_types < It, void_t> { using difference_type = typename It::difference_type; using value_type = typename It::value_type; using pointer = typename It::pointer; using reference = typename It::reference; using iterator_category = typename It::iterator_category; }; // This is required as some compilers implement std::iterator_traits in a way that // doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. template struct iterator_traits { }; template struct iterator_traits < T, enable_if_t < !std::is_pointer::value >> : iterator_types { }; template struct iterator_traits::value>> { using iterator_category = std::random_access_iterator_tag; using value_type = T; using difference_type = ptrdiff_t; using pointer = T*; using reference = T&; }; } // namespace detail NLOHMANN_JSON_NAMESPACE_END ================================================ FILE: Libs/nlohmann/detail/iterators/json_reverse_iterator.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include // ptrdiff_t #include // reverse_iterator #include // declval #include NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { ////////////////////// // reverse_iterator // ////////////////////// /*! @brief a template for a reverse iterator class @tparam Base the base iterator type to reverse. Valid types are @ref iterator (to create @ref reverse_iterator) and @ref const_iterator (to create @ref const_reverse_iterator). @requirement The class satisfies the following concept requirements: - [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator): The iterator that can be moved can be moved in both directions (i.e. incremented and decremented). - [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator): It is possible to write to the pointed-to element (only if @a Base is @ref iterator). @since version 1.0.0 */ template class json_reverse_iterator : public std::reverse_iterator { public: using difference_type = std::ptrdiff_t; /// shortcut to the reverse iterator adapter using base_iterator = std::reverse_iterator; /// the reference type for the pointed-to element using reference = typename Base::reference; /// create reverse iterator from iterator explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept : base_iterator(it) {} /// create reverse iterator from base class explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {} /// post-increment (it++) json_reverse_iterator operator++(int)& // NOLINT(cert-dcl21-cpp) { return static_cast(base_iterator::operator++(1)); } /// pre-increment (++it) json_reverse_iterator& operator++() { return static_cast(base_iterator::operator++()); } /// post-decrement (it--) json_reverse_iterator operator--(int)& // NOLINT(cert-dcl21-cpp) { return static_cast(base_iterator::operator--(1)); } /// pre-decrement (--it) json_reverse_iterator& operator--() { return static_cast(base_iterator::operator--()); } /// add to iterator json_reverse_iterator& operator+=(difference_type i) { return static_cast(base_iterator::operator+=(i)); } /// add to iterator json_reverse_iterator operator+(difference_type i) const { return static_cast(base_iterator::operator+(i)); } /// subtract from iterator json_reverse_iterator operator-(difference_type i) const { return static_cast(base_iterator::operator-(i)); } /// return difference difference_type operator-(const json_reverse_iterator& other) const { return base_iterator(*this) - base_iterator(other); } /// access to successor reference operator[](difference_type n) const { return *(this->operator+(n)); } /// return the key of an object iterator auto key() const -> decltype(std::declval().key()) { auto it = --this->base(); return it.key(); } /// return the value of an iterator reference value() const { auto it = --this->base(); return it.operator * (); } }; } // namespace detail NLOHMANN_JSON_NAMESPACE_END ================================================ FILE: Libs/nlohmann/detail/iterators/primitive_iterator.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include // ptrdiff_t #include // numeric_limits #include NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { /* @brief an iterator for primitive JSON types This class models an iterator for primitive JSON types (boolean, number, string). It's only purpose is to allow the iterator/const_iterator classes to "iterate" over primitive values. Internally, the iterator is modeled by a `difference_type` variable. Value begin_value (`0`) models the begin, end_value (`1`) models past the end. */ class primitive_iterator_t { private: using difference_type = std::ptrdiff_t; static constexpr difference_type begin_value = 0; static constexpr difference_type end_value = begin_value + 1; JSON_PRIVATE_UNLESS_TESTED: /// iterator as signed integer type difference_type m_it = (std::numeric_limits::min)(); public: constexpr difference_type get_value() const noexcept { return m_it; } /// set iterator to a defined beginning void set_begin() noexcept { m_it = begin_value; } /// set iterator to a defined past the end void set_end() noexcept { m_it = end_value; } /// return whether the iterator can be dereferenced constexpr bool is_begin() const noexcept { return m_it == begin_value; } /// return whether the iterator is at end constexpr bool is_end() const noexcept { return m_it == end_value; } friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return lhs.m_it == rhs.m_it; } friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return lhs.m_it < rhs.m_it; } primitive_iterator_t operator+(difference_type n) noexcept { auto result = *this; result += n; return result; } friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return lhs.m_it - rhs.m_it; } primitive_iterator_t& operator++() noexcept { ++m_it; return *this; } primitive_iterator_t operator++(int)& noexcept // NOLINT(cert-dcl21-cpp) { auto result = *this; ++m_it; return result; } primitive_iterator_t& operator--() noexcept { --m_it; return *this; } primitive_iterator_t operator--(int)& noexcept // NOLINT(cert-dcl21-cpp) { auto result = *this; --m_it; return result; } primitive_iterator_t& operator+=(difference_type n) noexcept { m_it += n; return *this; } primitive_iterator_t& operator-=(difference_type n) noexcept { m_it -= n; return *this; } }; } // namespace detail NLOHMANN_JSON_NAMESPACE_END ================================================ FILE: Libs/nlohmann/detail/json_custom_base_class.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include // conditional, is_same #include NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { /*! @brief Default base class of the @ref basic_json class. So that the correct implementations of the copy / move ctors / assign operators of @ref basic_json do not require complex case distinctions (no base class / custom base class used as customization point), @ref basic_json always has a base class. By default, this class is used because it is empty and thus has no effect on the behavior of @ref basic_json. */ struct json_default_base {}; template using json_base_class = typename std::conditional < std::is_same::value, json_default_base, T >::type; } // namespace detail NLOHMANN_JSON_NAMESPACE_END ================================================ FILE: Libs/nlohmann/detail/json_pointer.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include // all_of #include // isdigit #include // errno, ERANGE #include // strtoull #ifndef JSON_NO_IO #include // ostream #endif // JSON_NO_IO #include // max #include // accumulate #include // string #include // move #include // vector #include #include #include #include #include NLOHMANN_JSON_NAMESPACE_BEGIN /// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document /// @sa https://json.nlohmann.me/api/json_pointer/ template class json_pointer { // allow basic_json to access private members NLOHMANN_BASIC_JSON_TPL_DECLARATION friend class basic_json; template friend class json_pointer; template struct string_t_helper { using type = T; }; NLOHMANN_BASIC_JSON_TPL_DECLARATION struct string_t_helper { using type = StringType; }; public: // for backwards compatibility accept BasicJsonType using string_t = typename string_t_helper::type; /// @brief create JSON pointer /// @sa https://json.nlohmann.me/api/json_pointer/json_pointer/ explicit json_pointer(const string_t& s = "") : reference_tokens(split(s)) {} /// @brief return a string representation of the JSON pointer /// @sa https://json.nlohmann.me/api/json_pointer/to_string/ string_t to_string() const { return std::accumulate(reference_tokens.begin(), reference_tokens.end(), string_t{}, [](const string_t& a, const string_t& b) { return detail::concat(a, '/', detail::escape(b)); }); } /// @brief return a string representation of the JSON pointer /// @sa https://json.nlohmann.me/api/json_pointer/operator_string/ JSON_HEDLEY_DEPRECATED_FOR(3.11.0, to_string()) operator string_t() const { return to_string(); } #ifndef JSON_NO_IO /// @brief write string representation of the JSON pointer to stream /// @sa https://json.nlohmann.me/api/basic_json/operator_ltlt/ friend std::ostream& operator<<(std::ostream& o, const json_pointer& ptr) { o << ptr.to_string(); return o; } #endif /// @brief append another JSON pointer at the end of this JSON pointer /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/ json_pointer& operator/=(const json_pointer& ptr) { reference_tokens.insert(reference_tokens.end(), ptr.reference_tokens.begin(), ptr.reference_tokens.end()); return *this; } /// @brief append an unescaped reference token at the end of this JSON pointer /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/ json_pointer& operator/=(string_t token) { push_back(std::move(token)); return *this; } /// @brief append an array index at the end of this JSON pointer /// @sa https://json.nlohmann.me/api/json_pointer/operator_slasheq/ json_pointer& operator/=(std::size_t array_idx) { return *this /= std::to_string(array_idx); } /// @brief create a new JSON pointer by appending the right JSON pointer at the end of the left JSON pointer /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/ friend json_pointer operator/(const json_pointer& lhs, const json_pointer& rhs) { return json_pointer(lhs) /= rhs; } /// @brief create a new JSON pointer by appending the unescaped token at the end of the JSON pointer /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/ friend json_pointer operator/(const json_pointer& lhs, string_t token) // NOLINT(performance-unnecessary-value-param) { return json_pointer(lhs) /= std::move(token); } /// @brief create a new JSON pointer by appending the array-index-token at the end of the JSON pointer /// @sa https://json.nlohmann.me/api/json_pointer/operator_slash/ friend json_pointer operator/(const json_pointer& lhs, std::size_t array_idx) { return json_pointer(lhs) /= array_idx; } /// @brief returns the parent of this JSON pointer /// @sa https://json.nlohmann.me/api/json_pointer/parent_pointer/ json_pointer parent_pointer() const { if (empty()) { return *this; } json_pointer res = *this; res.pop_back(); return res; } /// @brief remove last reference token /// @sa https://json.nlohmann.me/api/json_pointer/pop_back/ void pop_back() { if (JSON_HEDLEY_UNLIKELY(empty())) { JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", nullptr)); } reference_tokens.pop_back(); } /// @brief return last reference token /// @sa https://json.nlohmann.me/api/json_pointer/back/ const string_t& back() const { if (JSON_HEDLEY_UNLIKELY(empty())) { JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", nullptr)); } return reference_tokens.back(); } /// @brief append an unescaped token at the end of the reference pointer /// @sa https://json.nlohmann.me/api/json_pointer/push_back/ void push_back(const string_t& token) { reference_tokens.push_back(token); } /// @brief append an unescaped token at the end of the reference pointer /// @sa https://json.nlohmann.me/api/json_pointer/push_back/ void push_back(string_t&& token) { reference_tokens.push_back(std::move(token)); } /// @brief return whether pointer points to the root document /// @sa https://json.nlohmann.me/api/json_pointer/empty/ bool empty() const noexcept { return reference_tokens.empty(); } private: /*! @param[in] s reference token to be converted into an array index @return integer representation of @a s @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index begins not with a digit @throw out_of_range.404 if string @a s could not be converted to an integer @throw out_of_range.410 if an array index exceeds size_type */ template static typename BasicJsonType::size_type array_index(const string_t& s) { using size_type = typename BasicJsonType::size_type; // error condition (cf. RFC 6901, Sect. 4) if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && s[0] == '0')) { JSON_THROW(detail::parse_error::create(106, 0, detail::concat("array index '", s, "' must not begin with '0'"), nullptr)); } // error condition (cf. RFC 6901, Sect. 4) if (JSON_HEDLEY_UNLIKELY(s.size() > 1 && !(s[0] >= '1' && s[0] <= '9'))) { JSON_THROW(detail::parse_error::create(109, 0, detail::concat("array index '", s, "' is not a number"), nullptr)); } const char* p = s.c_str(); char* p_end = nullptr; errno = 0; // strtoull doesn't reset errno const unsigned long long res = std::strtoull(p, &p_end, 10); // NOLINT(runtime/int) if (p == p_end // invalid input or empty string || errno == ERANGE // out of range || JSON_HEDLEY_UNLIKELY(static_cast(p_end - p) != s.size())) // incomplete read { JSON_THROW(detail::out_of_range::create(404, detail::concat("unresolved reference token '", s, "'"), nullptr)); } // only triggered on special platforms (like 32bit), see also // https://github.com/nlohmann/json/pull/2203 if (res >= static_cast((std::numeric_limits::max)())) // NOLINT(runtime/int) { JSON_THROW(detail::out_of_range::create(410, detail::concat("array index ", s, " exceeds size_type"), nullptr)); // LCOV_EXCL_LINE } return static_cast(res); } JSON_PRIVATE_UNLESS_TESTED: json_pointer top() const { if (JSON_HEDLEY_UNLIKELY(empty())) { JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent", nullptr)); } json_pointer result = *this; result.reference_tokens = {reference_tokens[0]}; return result; } private: /*! @brief create and return a reference to the pointed to value @complexity Linear in the number of reference tokens. @throw parse_error.109 if array index is not a number @throw type_error.313 if value cannot be unflattened */ template BasicJsonType& get_and_create(BasicJsonType& j) const { auto* result = &j; // in case no reference tokens exist, return a reference to the JSON value // j which will be overwritten by a primitive value for (const auto& reference_token : reference_tokens) { switch (result->type()) { case detail::value_t::null: { if (reference_token == "0") { // start a new array if reference token is 0 result = &result->operator[](0); } else { // start a new object otherwise result = &result->operator[](reference_token); } break; } case detail::value_t::object: { // create an entry in the object result = &result->operator[](reference_token); break; } case detail::value_t::array: { // create an entry in the array result = &result->operator[](array_index(reference_token)); break; } /* The following code is only reached if there exists a reference token _and_ the current value is primitive. In this case, we have an error situation, because primitive values may only occur as single value; that is, with an empty list of reference tokens. */ case detail::value_t::string: case detail::value_t::boolean: case detail::value_t::number_integer: case detail::value_t::number_unsigned: case detail::value_t::number_float: case detail::value_t::binary: case detail::value_t::discarded: default: JSON_THROW(detail::type_error::create(313, "invalid value to unflatten", &j)); } } return *result; } /*! @brief return a reference to the pointed to value @note This version does not throw if a value is not present, but tries to create nested values instead. For instance, calling this function with pointer `"/this/that"` on a null value is equivalent to calling `operator[]("this").operator[]("that")` on that value, effectively changing the null value to an object. @param[in] ptr a JSON value @return reference to the JSON value pointed to by the JSON pointer @complexity Linear in the length of the JSON pointer. @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.404 if the JSON pointer can not be resolved */ template BasicJsonType& get_unchecked(BasicJsonType* ptr) const { for (const auto& reference_token : reference_tokens) { // convert null values to arrays or objects before continuing if (ptr->is_null()) { // check if reference token is a number const bool nums = std::all_of(reference_token.begin(), reference_token.end(), [](const unsigned char x) { return std::isdigit(x); }); // change value to array for numbers or "-" or to object otherwise *ptr = (nums || reference_token == "-") ? detail::value_t::array : detail::value_t::object; } switch (ptr->type()) { case detail::value_t::object: { // use unchecked object access ptr = &ptr->operator[](reference_token); break; } case detail::value_t::array: { if (reference_token == "-") { // explicitly treat "-" as index beyond the end ptr = &ptr->operator[](ptr->m_data.m_value.array->size()); } else { // convert array index to number; unchecked access ptr = &ptr->operator[](array_index(reference_token)); } break; } case detail::value_t::null: case detail::value_t::string: case detail::value_t::boolean: case detail::value_t::number_integer: case detail::value_t::number_unsigned: case detail::value_t::number_float: case detail::value_t::binary: case detail::value_t::discarded: default: JSON_THROW(detail::out_of_range::create(404, detail::concat("unresolved reference token '", reference_token, "'"), ptr)); } } return *ptr; } /*! @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.402 if the array index '-' is used @throw out_of_range.404 if the JSON pointer can not be resolved */ template BasicJsonType& get_checked(BasicJsonType* ptr) const { for (const auto& reference_token : reference_tokens) { switch (ptr->type()) { case detail::value_t::object: { // note: at performs range check ptr = &ptr->at(reference_token); break; } case detail::value_t::array: { if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) { // "-" always fails the range check JSON_THROW(detail::out_of_range::create(402, detail::concat( "array index '-' (", std::to_string(ptr->m_data.m_value.array->size()), ") is out of range"), ptr)); } // note: at performs range check ptr = &ptr->at(array_index(reference_token)); break; } case detail::value_t::null: case detail::value_t::string: case detail::value_t::boolean: case detail::value_t::number_integer: case detail::value_t::number_unsigned: case detail::value_t::number_float: case detail::value_t::binary: case detail::value_t::discarded: default: JSON_THROW(detail::out_of_range::create(404, detail::concat("unresolved reference token '", reference_token, "'"), ptr)); } } return *ptr; } /*! @brief return a const reference to the pointed to value @param[in] ptr a JSON value @return const reference to the JSON value pointed to by the JSON pointer @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.402 if the array index '-' is used @throw out_of_range.404 if the JSON pointer can not be resolved */ template const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const { for (const auto& reference_token : reference_tokens) { switch (ptr->type()) { case detail::value_t::object: { // use unchecked object access ptr = &ptr->operator[](reference_token); break; } case detail::value_t::array: { if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) { // "-" cannot be used for const access JSON_THROW(detail::out_of_range::create(402, detail::concat("array index '-' (", std::to_string(ptr->m_data.m_value.array->size()), ") is out of range"), ptr)); } // use unchecked array access ptr = &ptr->operator[](array_index(reference_token)); break; } case detail::value_t::null: case detail::value_t::string: case detail::value_t::boolean: case detail::value_t::number_integer: case detail::value_t::number_unsigned: case detail::value_t::number_float: case detail::value_t::binary: case detail::value_t::discarded: default: JSON_THROW(detail::out_of_range::create(404, detail::concat("unresolved reference token '", reference_token, "'"), ptr)); } } return *ptr; } /*! @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.402 if the array index '-' is used @throw out_of_range.404 if the JSON pointer can not be resolved */ template const BasicJsonType& get_checked(const BasicJsonType* ptr) const { for (const auto& reference_token : reference_tokens) { switch (ptr->type()) { case detail::value_t::object: { // note: at performs range check ptr = &ptr->at(reference_token); break; } case detail::value_t::array: { if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) { // "-" always fails the range check JSON_THROW(detail::out_of_range::create(402, detail::concat( "array index '-' (", std::to_string(ptr->m_data.m_value.array->size()), ") is out of range"), ptr)); } // note: at performs range check ptr = &ptr->at(array_index(reference_token)); break; } case detail::value_t::null: case detail::value_t::string: case detail::value_t::boolean: case detail::value_t::number_integer: case detail::value_t::number_unsigned: case detail::value_t::number_float: case detail::value_t::binary: case detail::value_t::discarded: default: JSON_THROW(detail::out_of_range::create(404, detail::concat("unresolved reference token '", reference_token, "'"), ptr)); } } return *ptr; } /*! @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number */ template bool contains(const BasicJsonType* ptr) const { for (const auto& reference_token : reference_tokens) { switch (ptr->type()) { case detail::value_t::object: { if (!ptr->contains(reference_token)) { // we did not find the key in the object return false; } ptr = &ptr->operator[](reference_token); break; } case detail::value_t::array: { if (JSON_HEDLEY_UNLIKELY(reference_token == "-")) { // "-" always fails the range check return false; } if (JSON_HEDLEY_UNLIKELY(reference_token.size() == 1 && !("0" <= reference_token && reference_token <= "9"))) { // invalid char return false; } if (JSON_HEDLEY_UNLIKELY(reference_token.size() > 1)) { if (JSON_HEDLEY_UNLIKELY(!('1' <= reference_token[0] && reference_token[0] <= '9'))) { // first char should be between '1' and '9' return false; } for (std::size_t i = 1; i < reference_token.size(); i++) { if (JSON_HEDLEY_UNLIKELY(!('0' <= reference_token[i] && reference_token[i] <= '9'))) { // other char should be between '0' and '9' return false; } } } const auto idx = array_index(reference_token); if (idx >= ptr->size()) { // index out of range return false; } ptr = &ptr->operator[](idx); break; } case detail::value_t::null: case detail::value_t::string: case detail::value_t::boolean: case detail::value_t::number_integer: case detail::value_t::number_unsigned: case detail::value_t::number_float: case detail::value_t::binary: case detail::value_t::discarded: default: { // we do not expect primitive values if there is still a // reference token to process return false; } } } // no reference token left means we found a primitive value return true; } /*! @brief split the string input to reference tokens @note This function is only called by the json_pointer constructor. All exceptions below are documented there. @throw parse_error.107 if the pointer is not empty or begins with '/' @throw parse_error.108 if character '~' is not followed by '0' or '1' */ static std::vector split(const string_t& reference_string) { std::vector result; // special case: empty reference string -> no reference tokens if (reference_string.empty()) { return result; } // check if nonempty reference string begins with slash if (JSON_HEDLEY_UNLIKELY(reference_string[0] != '/')) { JSON_THROW(detail::parse_error::create(107, 1, detail::concat("JSON pointer must be empty or begin with '/' - was: '", reference_string, "'"), nullptr)); } // extract the reference tokens: // - slash: position of the last read slash (or end of string) // - start: position after the previous slash for ( // search for the first slash after the first character std::size_t slash = reference_string.find_first_of('/', 1), // set the beginning of the first reference token start = 1; // we can stop if start == 0 (if slash == string_t::npos) start != 0; // set the beginning of the next reference token // (will eventually be 0 if slash == string_t::npos) start = (slash == string_t::npos) ? 0 : slash + 1, // find next slash slash = reference_string.find_first_of('/', start)) { // use the text between the beginning of the reference token // (start) and the last slash (slash). auto reference_token = reference_string.substr(start, slash - start); // check reference tokens are properly escaped for (std::size_t pos = reference_token.find_first_of('~'); pos != string_t::npos; pos = reference_token.find_first_of('~', pos + 1)) { JSON_ASSERT(reference_token[pos] == '~'); // ~ must be followed by 0 or 1 if (JSON_HEDLEY_UNLIKELY(pos == reference_token.size() - 1 || (reference_token[pos + 1] != '0' && reference_token[pos + 1] != '1'))) { JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'", nullptr)); } } // finally, store the reference token detail::unescape(reference_token); result.push_back(reference_token); } return result; } private: /*! @param[in] reference_string the reference string to the current value @param[in] value the value to consider @param[in,out] result the result object to insert values to @note Empty objects or arrays are flattened to `null`. */ template static void flatten(const string_t& reference_string, const BasicJsonType& value, BasicJsonType& result) { switch (value.type()) { case detail::value_t::array: { if (value.m_data.m_value.array->empty()) { // flatten empty array as null result[reference_string] = nullptr; } else { // iterate array and use index as reference string for (std::size_t i = 0; i < value.m_data.m_value.array->size(); ++i) { flatten(detail::concat(reference_string, '/', std::to_string(i)), value.m_data.m_value.array->operator[](i), result); } } break; } case detail::value_t::object: { if (value.m_data.m_value.object->empty()) { // flatten empty object as null result[reference_string] = nullptr; } else { // iterate object and use keys as reference string for (const auto& element : *value.m_data.m_value.object) { flatten(detail::concat(reference_string, '/', detail::escape(element.first)), element.second, result); } } break; } case detail::value_t::null: case detail::value_t::string: case detail::value_t::boolean: case detail::value_t::number_integer: case detail::value_t::number_unsigned: case detail::value_t::number_float: case detail::value_t::binary: case detail::value_t::discarded: default: { // add primitive value with its reference string result[reference_string] = value; break; } } } /*! @param[in] value flattened JSON @return unflattened JSON @throw parse_error.109 if array index is not a number @throw type_error.314 if value is not an object @throw type_error.315 if object values are not primitive @throw type_error.313 if value cannot be unflattened */ template static BasicJsonType unflatten(const BasicJsonType& value) { if (JSON_HEDLEY_UNLIKELY(!value.is_object())) { JSON_THROW(detail::type_error::create(314, "only objects can be unflattened", &value)); } BasicJsonType result; // iterate the JSON object values for (const auto& element : *value.m_data.m_value.object) { if (JSON_HEDLEY_UNLIKELY(!element.second.is_primitive())) { JSON_THROW(detail::type_error::create(315, "values in object must be primitive", &element.second)); } // assign value to reference pointed to by JSON pointer; Note that if // the JSON pointer is "" (i.e., points to the whole value), function // get_and_create returns a reference to result itself. An assignment // will then create a primitive value. json_pointer(element.first).get_and_create(result) = element.second; } return result; } // can't use conversion operator because of ambiguity json_pointer convert() const& { json_pointer result; result.reference_tokens = reference_tokens; return result; } json_pointer convert()&& { json_pointer result; result.reference_tokens = std::move(reference_tokens); return result; } public: #if JSON_HAS_THREE_WAY_COMPARISON /// @brief compares two JSON pointers for equality /// @sa https://json.nlohmann.me/api/json_pointer/operator_eq/ template bool operator==(const json_pointer& rhs) const noexcept { return reference_tokens == rhs.reference_tokens; } /// @brief compares JSON pointer and string for equality /// @sa https://json.nlohmann.me/api/json_pointer/operator_eq/ JSON_HEDLEY_DEPRECATED_FOR(3.11.2, operator==(json_pointer)) bool operator==(const string_t& rhs) const { return *this == json_pointer(rhs); } /// @brief 3-way compares two JSON pointers template std::strong_ordering operator<=>(const json_pointer& rhs) const noexcept // *NOPAD* { return reference_tokens <=> rhs.reference_tokens; // *NOPAD* } #else /// @brief compares two JSON pointers for equality /// @sa https://json.nlohmann.me/api/json_pointer/operator_eq/ template // NOLINTNEXTLINE(readability-redundant-declaration) friend bool operator==(const json_pointer& lhs, const json_pointer& rhs) noexcept; /// @brief compares JSON pointer and string for equality /// @sa https://json.nlohmann.me/api/json_pointer/operator_eq/ template // NOLINTNEXTLINE(readability-redundant-declaration) friend bool operator==(const json_pointer& lhs, const StringType& rhs); /// @brief compares string and JSON pointer for equality /// @sa https://json.nlohmann.me/api/json_pointer/operator_eq/ template // NOLINTNEXTLINE(readability-redundant-declaration) friend bool operator==(const StringType& lhs, const json_pointer& rhs); /// @brief compares two JSON pointers for inequality /// @sa https://json.nlohmann.me/api/json_pointer/operator_ne/ template // NOLINTNEXTLINE(readability-redundant-declaration) friend bool operator!=(const json_pointer& lhs, const json_pointer& rhs) noexcept; /// @brief compares JSON pointer and string for inequality /// @sa https://json.nlohmann.me/api/json_pointer/operator_ne/ template // NOLINTNEXTLINE(readability-redundant-declaration) friend bool operator!=(const json_pointer& lhs, const StringType& rhs); /// @brief compares string and JSON pointer for inequality /// @sa https://json.nlohmann.me/api/json_pointer/operator_ne/ template // NOLINTNEXTLINE(readability-redundant-declaration) friend bool operator!=(const StringType& lhs, const json_pointer& rhs); /// @brief compares two JSON pointer for less-than template // NOLINTNEXTLINE(readability-redundant-declaration) friend bool operator<(const json_pointer& lhs, const json_pointer& rhs) noexcept; #endif private: /// the reference tokens std::vector reference_tokens; }; #if !JSON_HAS_THREE_WAY_COMPARISON // functions cannot be defined inside class due to ODR violations template inline bool operator==(const json_pointer& lhs, const json_pointer& rhs) noexcept { return lhs.reference_tokens == rhs.reference_tokens; } template::string_t> JSON_HEDLEY_DEPRECATED_FOR(3.11.2, operator==(json_pointer, json_pointer)) inline bool operator==(const json_pointer& lhs, const StringType& rhs) { return lhs == json_pointer(rhs); } template::string_t> JSON_HEDLEY_DEPRECATED_FOR(3.11.2, operator==(json_pointer, json_pointer)) inline bool operator==(const StringType& lhs, const json_pointer& rhs) { return json_pointer(lhs) == rhs; } template inline bool operator!=(const json_pointer& lhs, const json_pointer& rhs) noexcept { return !(lhs == rhs); } template::string_t> JSON_HEDLEY_DEPRECATED_FOR(3.11.2, operator!=(json_pointer, json_pointer)) inline bool operator!=(const json_pointer& lhs, const StringType& rhs) { return !(lhs == rhs); } template::string_t> JSON_HEDLEY_DEPRECATED_FOR(3.11.2, operator!=(json_pointer, json_pointer)) inline bool operator!=(const StringType& lhs, const json_pointer& rhs) { return !(lhs == rhs); } template inline bool operator<(const json_pointer& lhs, const json_pointer& rhs) noexcept { return lhs.reference_tokens < rhs.reference_tokens; } #endif NLOHMANN_JSON_NAMESPACE_END ================================================ FILE: Libs/nlohmann/detail/json_ref.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include #include #include #include NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { template class json_ref { public: using value_type = BasicJsonType; json_ref(value_type&& value) : owned_value(std::move(value)) {} json_ref(const value_type& value) : value_ref(&value) {} json_ref(std::initializer_list init) : owned_value(init) {} template < class... Args, enable_if_t::value, int> = 0 > json_ref(Args && ... args) : owned_value(std::forward(args)...) {} // class should be movable only json_ref(json_ref&&) noexcept = default; json_ref(const json_ref&) = delete; json_ref& operator=(const json_ref&) = delete; json_ref& operator=(json_ref&&) = delete; ~json_ref() = default; value_type moved_or_copied() const { if (value_ref == nullptr) { return std::move(owned_value); } return *value_ref; } value_type const& operator*() const { return value_ref ? *value_ref : owned_value; } value_type const* operator->() const { return &** this; } private: mutable value_type owned_value = nullptr; value_type const* value_ref = nullptr; }; } // namespace detail NLOHMANN_JSON_NAMESPACE_END ================================================ FILE: Libs/nlohmann/detail/macro_scope.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include // declval, pair #include #include // This file contains all internal macro definitions (except those affecting ABI) // You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them #include // exclude unsupported compilers #if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) #if defined(__clang__) #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" #endif #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" #endif #endif #endif // C++ language standard detection // if the user manually specified the used c++ version this is skipped #if !defined(JSON_HAS_CPP_20) && !defined(JSON_HAS_CPP_17) && !defined(JSON_HAS_CPP_14) && !defined(JSON_HAS_CPP_11) #if (defined(__cplusplus) && __cplusplus >= 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 202002L) #define JSON_HAS_CPP_20 #define JSON_HAS_CPP_17 #define JSON_HAS_CPP_14 #elif (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 #define JSON_HAS_CPP_17 #define JSON_HAS_CPP_14 #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) #define JSON_HAS_CPP_14 #endif // the cpp 11 flag is always specified because it is the minimal required version #define JSON_HAS_CPP_11 #endif #ifdef __has_include #if __has_include() #include #endif #endif #if !defined(JSON_HAS_FILESYSTEM) && !defined(JSON_HAS_EXPERIMENTAL_FILESYSTEM) #ifdef JSON_HAS_CPP_17 #if defined(__cpp_lib_filesystem) #define JSON_HAS_FILESYSTEM 1 #elif defined(__cpp_lib_experimental_filesystem) #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 #elif !defined(__has_include) #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 #elif __has_include() #define JSON_HAS_FILESYSTEM 1 #elif __has_include() #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 #endif // std::filesystem does not work on MinGW GCC 8: https://sourceforge.net/p/mingw-w64/bugs/737/ #if defined(__MINGW32__) && defined(__GNUC__) && __GNUC__ == 8 #undef JSON_HAS_FILESYSTEM #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM #endif // no filesystem support before GCC 8: https://en.cppreference.com/w/cpp/compiler_support #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 8 #undef JSON_HAS_FILESYSTEM #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM #endif // no filesystem support before Clang 7: https://en.cppreference.com/w/cpp/compiler_support #if defined(__clang_major__) && __clang_major__ < 7 #undef JSON_HAS_FILESYSTEM #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM #endif // no filesystem support before MSVC 19.14: https://en.cppreference.com/w/cpp/compiler_support #if defined(_MSC_VER) && _MSC_VER < 1914 #undef JSON_HAS_FILESYSTEM #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM #endif // no filesystem support before iOS 13 #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED < 130000 #undef JSON_HAS_FILESYSTEM #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM #endif // no filesystem support before macOS Catalina #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500 #undef JSON_HAS_FILESYSTEM #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM #endif #endif #endif #ifndef JSON_HAS_EXPERIMENTAL_FILESYSTEM #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 0 #endif #ifndef JSON_HAS_FILESYSTEM #define JSON_HAS_FILESYSTEM 0 #endif #ifndef JSON_HAS_THREE_WAY_COMPARISON #if defined(__cpp_impl_three_way_comparison) && __cpp_impl_three_way_comparison >= 201907L \ && defined(__cpp_lib_three_way_comparison) && __cpp_lib_three_way_comparison >= 201907L #define JSON_HAS_THREE_WAY_COMPARISON 1 #else #define JSON_HAS_THREE_WAY_COMPARISON 0 #endif #endif #ifndef JSON_HAS_RANGES // ranges header shipping in GCC 11.1.0 (released 2021-04-27) has syntax error #if defined(__GLIBCXX__) && __GLIBCXX__ == 20210427 #define JSON_HAS_RANGES 0 #elif defined(__cpp_lib_ranges) #define JSON_HAS_RANGES 1 #else #define JSON_HAS_RANGES 0 #endif #endif #ifndef JSON_HAS_STATIC_RTTI #if !defined(_HAS_STATIC_RTTI) || _HAS_STATIC_RTTI != 0 #define JSON_HAS_STATIC_RTTI 1 #else #define JSON_HAS_STATIC_RTTI 0 #endif #endif #ifdef JSON_HAS_CPP_17 #define JSON_INLINE_VARIABLE inline #else #define JSON_INLINE_VARIABLE #endif #if JSON_HEDLEY_HAS_ATTRIBUTE(no_unique_address) #define JSON_NO_UNIQUE_ADDRESS [[no_unique_address]] #else #define JSON_NO_UNIQUE_ADDRESS #endif // disable documentation warnings on clang #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdocumentation" #pragma clang diagnostic ignored "-Wdocumentation-unknown-command" #endif // allow disabling exceptions #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) #define JSON_THROW(exception) throw exception #define JSON_TRY try #define JSON_CATCH(exception) catch(exception) #define JSON_INTERNAL_CATCH(exception) catch(exception) #else #include #define JSON_THROW(exception) std::abort() #define JSON_TRY if(true) #define JSON_CATCH(exception) if(false) #define JSON_INTERNAL_CATCH(exception) if(false) #endif // override exception macros #if defined(JSON_THROW_USER) #undef JSON_THROW #define JSON_THROW JSON_THROW_USER #endif #if defined(JSON_TRY_USER) #undef JSON_TRY #define JSON_TRY JSON_TRY_USER #endif #if defined(JSON_CATCH_USER) #undef JSON_CATCH #define JSON_CATCH JSON_CATCH_USER #undef JSON_INTERNAL_CATCH #define JSON_INTERNAL_CATCH JSON_CATCH_USER #endif #if defined(JSON_INTERNAL_CATCH_USER) #undef JSON_INTERNAL_CATCH #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER #endif // allow overriding assert #if !defined(JSON_ASSERT) #include // assert #define JSON_ASSERT(x) assert(x) #endif // allow to access some private functions (needed by the test suite) #if defined(JSON_TESTS_PRIVATE) #define JSON_PRIVATE_UNLESS_TESTED public #else #define JSON_PRIVATE_UNLESS_TESTED private #endif /*! @brief macro to briefly define a mapping between an enum and JSON @def NLOHMANN_JSON_SERIALIZE_ENUM @since version 3.4.0 */ #define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ template \ inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ { \ static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ static const std::pair m[] = __VA_ARGS__; \ auto it = std::find_if(std::begin(m), std::end(m), \ [e](const std::pair& ej_pair) -> bool \ { \ return ej_pair.first == e; \ }); \ j = ((it != std::end(m)) ? it : std::begin(m))->second; \ } \ template \ inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ { \ static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ static const std::pair m[] = __VA_ARGS__; \ auto it = std::find_if(std::begin(m), std::end(m), \ [&j](const std::pair& ej_pair) -> bool \ { \ return ej_pair.second == j; \ }); \ e = ((it != std::end(m)) ? it : std::begin(m))->first; \ } // Ugly macros to avoid uglier copy-paste when specializing basic_json. They // may be removed in the future once the class is split. #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ template class ObjectType, \ template class ArrayType, \ class StringType, class BooleanType, class NumberIntegerType, \ class NumberUnsignedType, class NumberFloatType, \ template class AllocatorType, \ template class JSONSerializer, \ class BinaryType, \ class CustomBaseClass> #define NLOHMANN_BASIC_JSON_TPL \ basic_json // Macros to simplify conversion from/to types #define NLOHMANN_JSON_EXPAND( x ) x #define NLOHMANN_JSON_GET_MACRO(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, NAME,...) NAME #define NLOHMANN_JSON_PASTE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \ NLOHMANN_JSON_PASTE64, \ NLOHMANN_JSON_PASTE63, \ NLOHMANN_JSON_PASTE62, \ NLOHMANN_JSON_PASTE61, \ NLOHMANN_JSON_PASTE60, \ NLOHMANN_JSON_PASTE59, \ NLOHMANN_JSON_PASTE58, \ NLOHMANN_JSON_PASTE57, \ NLOHMANN_JSON_PASTE56, \ NLOHMANN_JSON_PASTE55, \ NLOHMANN_JSON_PASTE54, \ NLOHMANN_JSON_PASTE53, \ NLOHMANN_JSON_PASTE52, \ NLOHMANN_JSON_PASTE51, \ NLOHMANN_JSON_PASTE50, \ NLOHMANN_JSON_PASTE49, \ NLOHMANN_JSON_PASTE48, \ NLOHMANN_JSON_PASTE47, \ NLOHMANN_JSON_PASTE46, \ NLOHMANN_JSON_PASTE45, \ NLOHMANN_JSON_PASTE44, \ NLOHMANN_JSON_PASTE43, \ NLOHMANN_JSON_PASTE42, \ NLOHMANN_JSON_PASTE41, \ NLOHMANN_JSON_PASTE40, \ NLOHMANN_JSON_PASTE39, \ NLOHMANN_JSON_PASTE38, \ NLOHMANN_JSON_PASTE37, \ NLOHMANN_JSON_PASTE36, \ NLOHMANN_JSON_PASTE35, \ NLOHMANN_JSON_PASTE34, \ NLOHMANN_JSON_PASTE33, \ NLOHMANN_JSON_PASTE32, \ NLOHMANN_JSON_PASTE31, \ NLOHMANN_JSON_PASTE30, \ NLOHMANN_JSON_PASTE29, \ NLOHMANN_JSON_PASTE28, \ NLOHMANN_JSON_PASTE27, \ NLOHMANN_JSON_PASTE26, \ NLOHMANN_JSON_PASTE25, \ NLOHMANN_JSON_PASTE24, \ NLOHMANN_JSON_PASTE23, \ NLOHMANN_JSON_PASTE22, \ NLOHMANN_JSON_PASTE21, \ NLOHMANN_JSON_PASTE20, \ NLOHMANN_JSON_PASTE19, \ NLOHMANN_JSON_PASTE18, \ NLOHMANN_JSON_PASTE17, \ NLOHMANN_JSON_PASTE16, \ NLOHMANN_JSON_PASTE15, \ NLOHMANN_JSON_PASTE14, \ NLOHMANN_JSON_PASTE13, \ NLOHMANN_JSON_PASTE12, \ NLOHMANN_JSON_PASTE11, \ NLOHMANN_JSON_PASTE10, \ NLOHMANN_JSON_PASTE9, \ NLOHMANN_JSON_PASTE8, \ NLOHMANN_JSON_PASTE7, \ NLOHMANN_JSON_PASTE6, \ NLOHMANN_JSON_PASTE5, \ NLOHMANN_JSON_PASTE4, \ NLOHMANN_JSON_PASTE3, \ NLOHMANN_JSON_PASTE2, \ NLOHMANN_JSON_PASTE1)(__VA_ARGS__)) #define NLOHMANN_JSON_PASTE2(func, v1) func(v1) #define NLOHMANN_JSON_PASTE3(func, v1, v2) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE2(func, v2) #define NLOHMANN_JSON_PASTE4(func, v1, v2, v3) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE3(func, v2, v3) #define NLOHMANN_JSON_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE4(func, v2, v3, v4) #define NLOHMANN_JSON_PASTE6(func, v1, v2, v3, v4, v5) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE5(func, v2, v3, v4, v5) #define NLOHMANN_JSON_PASTE7(func, v1, v2, v3, v4, v5, v6) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE6(func, v2, v3, v4, v5, v6) #define NLOHMANN_JSON_PASTE8(func, v1, v2, v3, v4, v5, v6, v7) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE7(func, v2, v3, v4, v5, v6, v7) #define NLOHMANN_JSON_PASTE9(func, v1, v2, v3, v4, v5, v6, v7, v8) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE8(func, v2, v3, v4, v5, v6, v7, v8) #define NLOHMANN_JSON_PASTE10(func, v1, v2, v3, v4, v5, v6, v7, v8, v9) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE9(func, v2, v3, v4, v5, v6, v7, v8, v9) #define NLOHMANN_JSON_PASTE11(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE10(func, v2, v3, v4, v5, v6, v7, v8, v9, v10) #define NLOHMANN_JSON_PASTE12(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE11(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) #define NLOHMANN_JSON_PASTE13(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE12(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) #define NLOHMANN_JSON_PASTE14(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE13(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) #define NLOHMANN_JSON_PASTE15(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE14(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) #define NLOHMANN_JSON_PASTE16(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE15(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) #define NLOHMANN_JSON_PASTE17(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE16(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) #define NLOHMANN_JSON_PASTE18(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE17(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) #define NLOHMANN_JSON_PASTE19(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE18(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) #define NLOHMANN_JSON_PASTE20(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE19(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) #define NLOHMANN_JSON_PASTE21(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE20(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) #define NLOHMANN_JSON_PASTE22(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE21(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) #define NLOHMANN_JSON_PASTE23(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE22(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) #define NLOHMANN_JSON_PASTE24(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE23(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) #define NLOHMANN_JSON_PASTE25(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE24(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) #define NLOHMANN_JSON_PASTE26(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE25(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) #define NLOHMANN_JSON_PASTE27(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE26(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) #define NLOHMANN_JSON_PASTE28(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE27(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) #define NLOHMANN_JSON_PASTE29(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE28(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) #define NLOHMANN_JSON_PASTE30(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE29(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) #define NLOHMANN_JSON_PASTE31(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE30(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) #define NLOHMANN_JSON_PASTE32(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE31(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) #define NLOHMANN_JSON_PASTE33(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE32(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) #define NLOHMANN_JSON_PASTE34(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE33(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) #define NLOHMANN_JSON_PASTE35(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE34(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) #define NLOHMANN_JSON_PASTE36(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE35(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) #define NLOHMANN_JSON_PASTE37(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE36(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) #define NLOHMANN_JSON_PASTE38(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE37(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) #define NLOHMANN_JSON_PASTE39(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE38(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) #define NLOHMANN_JSON_PASTE40(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE39(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) #define NLOHMANN_JSON_PASTE41(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE40(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) #define NLOHMANN_JSON_PASTE42(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE41(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) #define NLOHMANN_JSON_PASTE43(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE42(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) #define NLOHMANN_JSON_PASTE44(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE43(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) #define NLOHMANN_JSON_PASTE45(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE44(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) #define NLOHMANN_JSON_PASTE46(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE45(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) #define NLOHMANN_JSON_PASTE47(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE46(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) #define NLOHMANN_JSON_PASTE48(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE47(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) #define NLOHMANN_JSON_PASTE49(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE48(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) #define NLOHMANN_JSON_PASTE50(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE49(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) #define NLOHMANN_JSON_PASTE51(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE50(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) #define NLOHMANN_JSON_PASTE52(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE51(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) #define NLOHMANN_JSON_PASTE53(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE52(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) #define NLOHMANN_JSON_PASTE54(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE53(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) #define NLOHMANN_JSON_PASTE55(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE54(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) #define NLOHMANN_JSON_PASTE56(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE55(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) #define NLOHMANN_JSON_PASTE57(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE56(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) #define NLOHMANN_JSON_PASTE58(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE57(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) #define NLOHMANN_JSON_PASTE59(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE58(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) #define NLOHMANN_JSON_PASTE60(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE59(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) #define NLOHMANN_JSON_PASTE61(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE60(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) #define NLOHMANN_JSON_PASTE62(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE61(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) #define NLOHMANN_JSON_PASTE63(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE62(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) #define NLOHMANN_JSON_PASTE64(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE63(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) #define NLOHMANN_JSON_TO(v1) nlohmann_json_j[#v1] = nlohmann_json_t.v1; #define NLOHMANN_JSON_FROM(v1) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1); #define NLOHMANN_JSON_FROM_WITH_DEFAULT(v1) nlohmann_json_t.v1 = nlohmann_json_j.value(#v1, nlohmann_json_default_obj.v1); /*! @brief macro @def NLOHMANN_DEFINE_TYPE_INTRUSIVE @since version 3.9.0 */ #define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, ...) \ friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ friend void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } #define NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(Type, ...) \ friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ friend void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } #define NLOHMANN_DEFINE_TYPE_INTRUSIVE_ONLY_SERIALIZE(Type, ...) \ friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } /*! @brief macro @def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE @since version 3.9.0 */ #define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Type, ...) \ inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ inline void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } #define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_ONLY_SERIALIZE(Type, ...) \ inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } #define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(Type, ...) \ inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ inline void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { const Type nlohmann_json_default_obj{}; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } // inspired from https://stackoverflow.com/a/26745591 // allows to call any std function as if (e.g. with begin): // using std::begin; begin(x); // // it allows using the detected idiom to retrieve the return type // of such an expression #define NLOHMANN_CAN_CALL_STD_FUNC_IMPL(std_name) \ namespace detail { \ using std::std_name; \ \ template \ using result_of_##std_name = decltype(std_name(std::declval()...)); \ } \ \ namespace detail2 { \ struct std_name##_tag \ { \ }; \ \ template \ std_name##_tag std_name(T&&...); \ \ template \ using result_of_##std_name = decltype(std_name(std::declval()...)); \ \ template \ struct would_call_std_##std_name \ { \ static constexpr auto const value = ::nlohmann::detail:: \ is_detected_exact::value; \ }; \ } /* namespace detail2 */ \ \ template \ struct would_call_std_##std_name : detail2::would_call_std_##std_name \ { \ } #ifndef JSON_USE_IMPLICIT_CONVERSIONS #define JSON_USE_IMPLICIT_CONVERSIONS 1 #endif #if JSON_USE_IMPLICIT_CONVERSIONS #define JSON_EXPLICIT #else #define JSON_EXPLICIT explicit #endif #ifndef JSON_DISABLE_ENUM_SERIALIZATION #define JSON_DISABLE_ENUM_SERIALIZATION 0 #endif #ifndef JSON_USE_GLOBAL_UDLS #define JSON_USE_GLOBAL_UDLS 1 #endif ================================================ FILE: Libs/nlohmann/detail/macro_unscope.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once // restore clang diagnostic settings #if defined(__clang__) #pragma clang diagnostic pop #endif // clean up #undef JSON_ASSERT #undef JSON_INTERNAL_CATCH #undef JSON_THROW #undef JSON_PRIVATE_UNLESS_TESTED #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION #undef NLOHMANN_BASIC_JSON_TPL #undef JSON_EXPLICIT #undef NLOHMANN_CAN_CALL_STD_FUNC_IMPL #undef JSON_INLINE_VARIABLE #undef JSON_NO_UNIQUE_ADDRESS #undef JSON_DISABLE_ENUM_SERIALIZATION #undef JSON_USE_GLOBAL_UDLS #ifndef JSON_TEST_KEEP_MACROS #undef JSON_CATCH #undef JSON_TRY #undef JSON_HAS_CPP_11 #undef JSON_HAS_CPP_14 #undef JSON_HAS_CPP_17 #undef JSON_HAS_CPP_20 #undef JSON_HAS_FILESYSTEM #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM #undef JSON_HAS_THREE_WAY_COMPARISON #undef JSON_HAS_RANGES #undef JSON_HAS_STATIC_RTTI #undef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON #endif #include ================================================ FILE: Libs/nlohmann/detail/meta/call_std/begin.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include NLOHMANN_JSON_NAMESPACE_BEGIN NLOHMANN_CAN_CALL_STD_FUNC_IMPL(begin); NLOHMANN_JSON_NAMESPACE_END ================================================ FILE: Libs/nlohmann/detail/meta/call_std/end.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include NLOHMANN_JSON_NAMESPACE_BEGIN NLOHMANN_CAN_CALL_STD_FUNC_IMPL(end); NLOHMANN_JSON_NAMESPACE_END ================================================ FILE: Libs/nlohmann/detail/meta/cpp_future.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-FileCopyrightText: 2018 The Abseil Authors // SPDX-License-Identifier: MIT #pragma once #include // array #include // size_t #include // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type #include // index_sequence, make_index_sequence, index_sequence_for #include NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { template using uncvref_t = typename std::remove_cv::type>::type; #ifdef JSON_HAS_CPP_14 // the following utilities are natively available in C++14 using std::enable_if_t; using std::index_sequence; using std::make_index_sequence; using std::index_sequence_for; #else // alias templates to reduce boilerplate template using enable_if_t = typename std::enable_if::type; // The following code is taken from https://github.com/abseil/abseil-cpp/blob/10cb35e459f5ecca5b2ff107635da0bfa41011b4/absl/utility/utility.h // which is part of Google Abseil (https://github.com/abseil/abseil-cpp), licensed under the Apache License 2.0. //// START OF CODE FROM GOOGLE ABSEIL // integer_sequence // // Class template representing a compile-time integer sequence. An instantiation // of `integer_sequence` has a sequence of integers encoded in its // type through its template arguments (which is a common need when // working with C++11 variadic templates). `absl::integer_sequence` is designed // to be a drop-in replacement for C++14's `std::integer_sequence`. // // Example: // // template< class T, T... Ints > // void user_function(integer_sequence); // // int main() // { // // user_function's `T` will be deduced to `int` and `Ints...` // // will be deduced to `0, 1, 2, 3, 4`. // user_function(make_integer_sequence()); // } template struct integer_sequence { using value_type = T; static constexpr std::size_t size() noexcept { return sizeof...(Ints); } }; // index_sequence // // A helper template for an `integer_sequence` of `size_t`, // `absl::index_sequence` is designed to be a drop-in replacement for C++14's // `std::index_sequence`. template using index_sequence = integer_sequence; namespace utility_internal { template struct Extend; // Note that SeqSize == sizeof...(Ints). It's passed explicitly for efficiency. template struct Extend, SeqSize, 0> { using type = integer_sequence < T, Ints..., (Ints + SeqSize)... >; }; template struct Extend, SeqSize, 1> { using type = integer_sequence < T, Ints..., (Ints + SeqSize)..., 2 * SeqSize >; }; // Recursion helper for 'make_integer_sequence'. // 'Gen::type' is an alias for 'integer_sequence'. template struct Gen { using type = typename Extend < typename Gen < T, N / 2 >::type, N / 2, N % 2 >::type; }; template struct Gen { using type = integer_sequence; }; } // namespace utility_internal // Compile-time sequences of integers // make_integer_sequence // // This template alias is equivalent to // `integer_sequence`, and is designed to be a drop-in // replacement for C++14's `std::make_integer_sequence`. template using make_integer_sequence = typename utility_internal::Gen::type; // make_index_sequence // // This template alias is equivalent to `index_sequence<0, 1, ..., N-1>`, // and is designed to be a drop-in replacement for C++14's // `std::make_index_sequence`. template using make_index_sequence = make_integer_sequence; // index_sequence_for // // Converts a typename pack into an index sequence of the same length, and // is designed to be a drop-in replacement for C++14's // `std::index_sequence_for()` template using index_sequence_for = make_index_sequence; //// END OF CODE FROM GOOGLE ABSEIL #endif // dispatch utility (taken from ranges-v3) template struct priority_tag : priority_tag < N - 1 > {}; template<> struct priority_tag<0> {}; // taken from ranges-v3 template struct static_const { static JSON_INLINE_VARIABLE constexpr T value{}; }; #ifndef JSON_HAS_CPP_17 template constexpr T static_const::value; #endif template inline constexpr std::array make_array(Args&& ... args) { return std::array {{static_cast(std::forward(args))...}}; } } // namespace detail NLOHMANN_JSON_NAMESPACE_END ================================================ FILE: Libs/nlohmann/detail/meta/detected.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include #include NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { // https://en.cppreference.com/w/cpp/experimental/is_detected struct nonesuch { nonesuch() = delete; ~nonesuch() = delete; nonesuch(nonesuch const&) = delete; nonesuch(nonesuch const&&) = delete; void operator=(nonesuch const&) = delete; void operator=(nonesuch&&) = delete; }; template class Op, class... Args> struct detector { using value_t = std::false_type; using type = Default; }; template class Op, class... Args> struct detector>, Op, Args...> { using value_t = std::true_type; using type = Op; }; template class Op, class... Args> using is_detected = typename detector::value_t; template class Op, class... Args> struct is_detected_lazy : is_detected { }; template class Op, class... Args> using detected_t = typename detector::type; template class Op, class... Args> using detected_or = detector; template class Op, class... Args> using detected_or_t = typename detected_or::type; template class Op, class... Args> using is_detected_exact = std::is_same>; template class Op, class... Args> using is_detected_convertible = std::is_convertible, To>; } // namespace detail NLOHMANN_JSON_NAMESPACE_END ================================================ FILE: Libs/nlohmann/detail/meta/identity_tag.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { // dispatching helper struct template struct identity_tag {}; } // namespace detail NLOHMANN_JSON_NAMESPACE_END ================================================ FILE: Libs/nlohmann/detail/meta/is_sax.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include // size_t #include // declval #include // string #include #include #include NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { template using null_function_t = decltype(std::declval().null()); template using boolean_function_t = decltype(std::declval().boolean(std::declval())); template using number_integer_function_t = decltype(std::declval().number_integer(std::declval())); template using number_unsigned_function_t = decltype(std::declval().number_unsigned(std::declval())); template using number_float_function_t = decltype(std::declval().number_float( std::declval(), std::declval())); template using string_function_t = decltype(std::declval().string(std::declval())); template using binary_function_t = decltype(std::declval().binary(std::declval())); template using start_object_function_t = decltype(std::declval().start_object(std::declval())); template using key_function_t = decltype(std::declval().key(std::declval())); template using end_object_function_t = decltype(std::declval().end_object()); template using start_array_function_t = decltype(std::declval().start_array(std::declval())); template using end_array_function_t = decltype(std::declval().end_array()); template using parse_error_function_t = decltype(std::declval().parse_error( std::declval(), std::declval(), std::declval())); template struct is_sax { private: static_assert(is_basic_json::value, "BasicJsonType must be of type basic_json<...>"); using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; using exception_t = typename BasicJsonType::exception; public: static constexpr bool value = is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value && is_detected_exact::value; }; template struct is_sax_static_asserts { private: static_assert(is_basic_json::value, "BasicJsonType must be of type basic_json<...>"); using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using binary_t = typename BasicJsonType::binary_t; using exception_t = typename BasicJsonType::exception; public: static_assert(is_detected_exact::value, "Missing/invalid function: bool null()"); static_assert(is_detected_exact::value, "Missing/invalid function: bool boolean(bool)"); static_assert(is_detected_exact::value, "Missing/invalid function: bool boolean(bool)"); static_assert( is_detected_exact::value, "Missing/invalid function: bool number_integer(number_integer_t)"); static_assert( is_detected_exact::value, "Missing/invalid function: bool number_unsigned(number_unsigned_t)"); static_assert(is_detected_exact::value, "Missing/invalid function: bool number_float(number_float_t, const string_t&)"); static_assert( is_detected_exact::value, "Missing/invalid function: bool string(string_t&)"); static_assert( is_detected_exact::value, "Missing/invalid function: bool binary(binary_t&)"); static_assert(is_detected_exact::value, "Missing/invalid function: bool start_object(std::size_t)"); static_assert(is_detected_exact::value, "Missing/invalid function: bool key(string_t&)"); static_assert(is_detected_exact::value, "Missing/invalid function: bool end_object()"); static_assert(is_detected_exact::value, "Missing/invalid function: bool start_array(std::size_t)"); static_assert(is_detected_exact::value, "Missing/invalid function: bool end_array()"); static_assert( is_detected_exact::value, "Missing/invalid function: bool parse_error(std::size_t, const " "std::string&, const exception&)"); }; } // namespace detail NLOHMANN_JSON_NAMESPACE_END ================================================ FILE: Libs/nlohmann/detail/meta/std_fs.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include #if JSON_HAS_EXPERIMENTAL_FILESYSTEM #include NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { namespace std_fs = std::experimental::filesystem; } // namespace detail NLOHMANN_JSON_NAMESPACE_END #elif JSON_HAS_FILESYSTEM #include NLOHMANN_JSON_NAMESPACE_BEGIN namespace detail { namespace std_fs = std::filesystem; } // namespace detail NLOHMANN_JSON_NAMESPACE_END #endif ================================================ FILE: Libs/nlohmann/detail/meta/type_traits.hpp ================================================ // __ _____ _____ _____ // __| | __| | | | JSON for Modern C++ // | | |__ | | | | | | version 3.11.3 // |_____|_____|_____|_|___| https://github.com/nlohmann/json // // SPDX-FileCopyrightText: 2013-2023 Niels Lohmann // SPDX-License-Identifier: MIT #pragma once #include // numeric_limits #include // false_type, is_constructible, is_integral, is_same, true_type #include // declval #include // tuple #include // char_traits #include #include #include #include #include #include #include NLOHMANN_JSON_NAMESPACE_BEGIN /*! @brief detail namespace with internal helper functions This namespace collects functions that should not be exposed, implementations of some @ref basic_json methods, and meta-programming helpers. @since version 2.1.0 */ namespace detail { ///////////// // helpers // ///////////// // Note to maintainers: // // Every trait in this file expects a non CV-qualified type. // The only exceptions are in the 'aliases for detected' section // (i.e. those of the form: decltype(T::member_function(std::declval()))) // // In this case, T has to be properly CV-qualified to constraint the function arguments // (e.g. to_json(BasicJsonType&, const T&)) template struct is_basic_json : std::false_type {}; NLOHMANN_BASIC_JSON_TPL_DECLARATION struct is_basic_json : std::true_type {}; // used by exceptions create() member functions // true_type for pointer to possibly cv-qualified basic_json or std::nullptr_t // false_type otherwise template struct is_basic_json_context : std::integral_constant < bool, is_basic_json::type>::type>::value || std::is_same::value > {}; ////////////////////// // json_ref helpers // ////////////////////// template class json_ref; template struct is_json_ref : std::false_type {}; template struct is_json_ref> : std::true_type {}; ////////////////////////// // aliases for detected // ////////////////////////// template using mapped_type_t = typename T::mapped_type; template using key_type_t = typename T::key_type; template using value_type_t = typename T::value_type; template using difference_type_t = typename T::difference_type; template using pointer_t = typename T::pointer; template using reference_t = typename T::reference; template using iterator_category_t = typename T::iterator_category; template using to_json_function = decltype(T::to_json(std::declval()...)); template using from_json_function = decltype(T::from_json(std::declval()...)); template using get_template_function = decltype(std::declval().template get()); // trait checking if JSONSerializer::from_json(json const&, udt&) exists template struct has_from_json : std::false_type {}; // trait checking if j.get is valid // use this trait instead of std::is_constructible or std::is_convertible, // both rely on, or make use of implicit conversions, and thus fail when T // has several constructors/operator= (see https://github.com/nlohmann/json/issues/958) template struct is_getable { static constexpr bool value = is_detected::value; }; template struct has_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> { using serializer = typename BasicJsonType::template json_serializer; static constexpr bool value = is_detected_exact::value; }; // This trait checks if JSONSerializer::from_json(json const&) exists // this overload is used for non-default-constructible user-defined-types template struct has_non_default_from_json : std::false_type {}; template struct has_non_default_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> { using serializer = typename BasicJsonType::template json_serializer; static constexpr bool value = is_detected_exact::value; }; // This trait checks if BasicJsonType::json_serializer::to_json exists // Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion. template struct has_to_json : std::false_type {}; template struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> { using serializer = typename BasicJsonType::template json_serializer; static constexpr bool value = is_detected_exact::value; }; template using detect_key_compare = typename T::key_compare; template struct has_key_compare : std::integral_constant::value> {}; // obtains the actual object key comparator template struct actual_object_comparator { using object_t = typename BasicJsonType::object_t; using object_comparator_t = typename BasicJsonType::default_object_comparator_t; using type = typename std::conditional < has_key_compare::value, typename object_t::key_compare, object_comparator_t>::type; }; template using actual_object_comparator_t = typename actual_object_comparator::type; ///////////////// // char_traits // ///////////////// // Primary template of char_traits calls std char_traits template struct char_traits : std::char_traits {}; // Explicitly define char traits for unsigned char since it is not standard template<> struct char_traits : std::char_traits { using char_type = unsigned char; using int_type = uint64_t; // Redefine to_int_type function static int_type to_int_type(char_type c) noexcept { return static_cast(c); } static char_type to_char_type(int_type i) noexcept { return static_cast(i); } static constexpr int_type eof() noexcept { return static_cast(EOF); } }; // Explicitly define char traits for signed char since it is not standard template<> struct char_traits : std::char_traits { using char_type = signed char; using int_type = uint64_t; // Redefine to_int_type function static int_type to_int_type(char_type c) noexcept { return static_cast(c); } static char_type to_char_type(int_type i) noexcept { return static_cast(i); } static constexpr int_type eof() noexcept { return static_cast(EOF); } }; /////////////////// // is_ functions // /////////////////// // https://en.cppreference.com/w/cpp/types/conjunction template struct conjunction : std::true_type { }; template struct conjunction : B { }; template struct conjunction : std::conditional(B::value), conjunction, B>::type {}; // https://en.cppreference.com/w/cpp/types/negation template struct negation : std::integral_constant < bool, !B::value > { }; // Reimplementation of is_constructible and is_default_constructible, due to them being broken for // std::pair and std::tuple until LWG 2367 fix (see https://cplusplus.github.io/LWG/lwg-defects.html#2367). // This causes compile errors in e.g. clang 3.5 or gcc 4.9. template struct is_default_constructible : std::is_default_constructible {}; template struct is_default_constructible> : conjunction, is_default_constructible> {}; template struct is_default_constructible> : conjunction, is_default_constructible> {}; template struct is_default_constructible> : conjunction...> {}; template struct is_default_constructible> : conjunction...> {}; template struct is_constructible : std::is_constructible {}; template struct is_constructible> : is_default_constructible> {}; template struct is_constructible> : is_default_constructible> {}; template struct is_constructible> : is_default_constructible> {}; template struct is_constructible> : is_default_constructible> {}; template struct is_iterator_traits : std::false_type {}; template struct is_iterator_traits> { private: using traits = iterator_traits; public: static constexpr auto value = is_detected::value && is_detected::value && is_detected::value && is_detected::value && is_detected::value; }; template struct is_range { private: using t_ref = typename std::add_lvalue_reference::type; using iterator = detected_t; using sentinel = detected_t; // to be 100% correct, it should use https://en.cppreference.com/w/cpp/iterator/input_or_output_iterator // and https://en.cppreference.com/w/cpp/iterator/sentinel_for // but reimplementing these would be too much work, as a lot of other concepts are used underneath static constexpr auto is_iterator_begin = is_iterator_traits>::value; public: static constexpr bool value = !std::is_same::value && !std::is_same::value && is_iterator_begin; }; template using iterator_t = enable_if_t::value, result_of_begin())>>; template using range_value_t = value_type_t>>; // The following implementation of is_complete_type is taken from // https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/ // and is written by Xiang Fan who agreed to using it in this library. template struct is_complete_type : std::false_type {}; template struct is_complete_type : std::true_type {}; template struct is_compatible_object_type_impl : std::false_type {}; template struct is_compatible_object_type_impl < BasicJsonType, CompatibleObjectType, enable_if_t < is_detected::value&& is_detected::value >> { using object_t = typename BasicJsonType::object_t; // macOS's is_constructible does not play well with nonesuch... static constexpr bool value = is_constructible::value && is_constructible::value; }; template struct is_compatible_object_type : is_compatible_object_type_impl {}; template struct is_constructible_object_type_impl : std::false_type {}; template struct is_constructible_object_type_impl < BasicJsonType, ConstructibleObjectType, enable_if_t < is_detected::value&& is_detected::value >> { using object_t = typename BasicJsonType::object_t; static constexpr bool value = (is_default_constructible::value && (std::is_move_assignable::value || std::is_copy_assignable::value) && (is_constructible::value && std::is_same < typename object_t::mapped_type, typename ConstructibleObjectType::mapped_type >::value)) || (has_from_json::value || has_non_default_from_json < BasicJsonType, typename ConstructibleObjectType::mapped_type >::value); }; template struct is_constructible_object_type : is_constructible_object_type_impl {}; template struct is_compatible_string_type { static constexpr auto value = is_constructible::value; }; template struct is_constructible_string_type { // launder type through decltype() to fix compilation failure on ICPC #ifdef __INTEL_COMPILER using laundered_type = decltype(std::declval()); #else using laundered_type = ConstructibleStringType; #endif static constexpr auto value = conjunction < is_constructible, is_detected_exact>::value; }; template struct is_compatible_array_type_impl : std::false_type {}; template struct is_compatible_array_type_impl < BasicJsonType, CompatibleArrayType, enable_if_t < is_detected::value&& is_iterator_traits>>::value&& // special case for types like std::filesystem::path whose iterator's value_type are themselves // c.f. https://github.com/nlohmann/json/pull/3073 !std::is_same>::value >> { static constexpr bool value = is_constructible>::value; }; template struct is_compatible_array_type : is_compatible_array_type_impl {}; template struct is_constructible_array_type_impl : std::false_type {}; template struct is_constructible_array_type_impl < BasicJsonType, ConstructibleArrayType, enable_if_t::value >> : std::true_type {}; template struct is_constructible_array_type_impl < BasicJsonType, ConstructibleArrayType, enable_if_t < !std::is_same::value&& !is_compatible_string_type::value&& is_default_constructible::value&& (std::is_move_assignable::value || std::is_copy_assignable::value)&& is_detected::value&& is_iterator_traits>>::value&& is_detected::value&& // special case for types like std::filesystem::path whose iterator's value_type are themselves // c.f. https://github.com/nlohmann/json/pull/3073 !std::is_same>::value&& is_complete_type < detected_t>::value >> { using value_type = range_value_t; static constexpr bool value = std::is_same::value || has_from_json::value || has_non_default_from_json < BasicJsonType, value_type >::value; }; template struct is_constructible_array_type : is_constructible_array_type_impl {}; template struct is_compatible_integer_type_impl : std::false_type {}; template struct is_compatible_integer_type_impl < RealIntegerType, CompatibleNumberIntegerType, enable_if_t < std::is_integral::value&& std::is_integral::value&& !std::is_same::value >> { // is there an assert somewhere on overflows? using RealLimits = std::numeric_limits; using CompatibleLimits = std::numeric_limits; static constexpr auto value = is_constructible::value && CompatibleLimits::is_integer && RealLimits::is_signed == CompatibleLimits::is_signed; }; template struct is_compatible_integer_type : is_compatible_integer_type_impl {}; template struct is_compatible_type_impl: std::false_type {}; template struct is_compatible_type_impl < BasicJsonType, CompatibleType, enable_if_t::value >> { static constexpr bool value = has_to_json::value; }; template struct is_compatible_type : is_compatible_type_impl {}; template struct is_constructible_tuple : std::false_type {}; template struct is_constructible_tuple> : conjunction...> {}; template struct is_json_iterator_of : std::false_type {}; template struct is_json_iterator_of : std::true_type {}; template struct is_json_iterator_of : std::true_type {}; // checks if a given type T is a template specialization of Primary template