Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add --obfuscate-ids option to driver #660

Merged
merged 4 commits into from
Nov 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions include/slang/driver/Driver.h
Original file line number Diff line number Diff line change
Expand Up @@ -261,10 +261,12 @@ class SLANG_EXPORT Driver {

/// Runs the preprocessor on all loaded buffers and outputs the result to stdout.
/// Any errors encountered will be printed to stderr.
/// @param includeComments If true, comments will be included in the output
/// @param includeComments If true, comments will be included in the output.
/// @param includeDirectives If true, preprocessor directives will be included in the output.
/// @param obfuscateIds If true, identifiers will be randomized.
/// @returns true on success and false if errors were encountered.
[[nodiscard]] bool runPreprocessor(bool includeComments, bool includeDirectives);
[[nodiscard]] bool runPreprocessor(bool includeComments, bool includeDirectives,
bool obfuscateIds);

/// Prints all macros from all loaded buffers to stdout.
void reportMacros();
Expand Down
41 changes: 40 additions & 1 deletion source/driver/Driver.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,12 @@
//------------------------------------------------------------------------------
#include "slang/driver/Driver.h"

#include <array>
#include <cstring>
#include <fmt/color.h>
#include <functional>
#include <random>
#include <unordered_map>

#include "slang/ast/symbols/CompilationUnitSymbols.h"
#include "slang/ast/symbols/InstanceSymbols.h"
Expand Down Expand Up @@ -389,7 +394,29 @@ bool Driver::processOptions() {
return true;
}

bool Driver::runPreprocessor(bool includeComments, bool includeDirectives) {
template<typename T = std::mt19937>
auto randomGenerator() -> T {
auto constexpr seedBytes = sizeof(typename T::result_type) * T::state_size;
auto constexpr seedLen = seedBytes / sizeof(std::seed_seq::result_type);
auto seed = std::array<std::seed_seq::result_type, seedLen>();
auto dev = std::random_device();
std::generate_n(begin(seed), seedLen, std::ref(dev));
auto seedSeq = std::seed_seq(begin(seed), end(seed));
return T{seedSeq};
}

auto generateRandomAlphanumericString(std::size_t len = 16) -> std::string {
static constexpr auto chars = "0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
thread_local auto rng = randomGenerator<>();
auto dist = std::uniform_int_distribution{{}, std::strlen(chars) - 1};
auto result = std::string(len, '\0');
std::generate_n(begin(result), len, [&]() { return chars[dist(rng)]; });
return result;
}

bool Driver::runPreprocessor(bool includeComments, bool includeDirectives, bool obfuscateIds) {
BumpAllocator alloc;
Diagnostics diagnostics;
Preprocessor preprocessor(sourceManager, alloc, diagnostics, createOptionBag());
Expand All @@ -401,8 +428,20 @@ bool Driver::runPreprocessor(bool includeComments, bool includeDirectives) {
output.setIncludeComments(includeComments);
output.setIncludeDirectives(includeDirectives);

std::unordered_map<std::string, std::string> translations;

while (true) {
Token token = preprocessor.next();
if (obfuscateIds && token.kind == TokenKind::Identifier) {
std::string name = std::string(token.valueText());
auto translation = translations.find(name);
if (translation == translations.end()) {
auto new_name = generateRandomAlphanumericString();
auto ret = translations.insert({name, new_name});
Sustrak marked this conversation as resolved.
Show resolved Hide resolved
translation = ret.first;
}
token = token.withRawText(alloc, translation->second);
}
output.print(token);
if (token.kind == TokenKind::EndOfFile)
break;
Expand Down
4 changes: 2 additions & 2 deletions tests/unittests/DriverTests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ TEST_CASE("Driver file preprocess") {
const char* argv[] = {"testfoo", filePath.c_str()};
CHECK(driver.parseCommandLine(2, argv));
CHECK(driver.processOptions());
CHECK(driver.runPreprocessor(true, false));
CHECK(driver.runPreprocessor(true, false, false));

auto output = OS::capturedStdout;
output = std::regex_replace(output, std::regex("\r\n"), "\n");
Expand All @@ -134,7 +134,7 @@ TEST_CASE("Driver file preprocess with error") {
const char* argv[] = {"testfoo", filePath.c_str()};
CHECK(driver.parseCommandLine(2, argv));
CHECK(driver.processOptions());
CHECK(!driver.runPreprocessor(true, false));
CHECK(!driver.runPreprocessor(true, false, false));
CHECK(stderrContains("unknown macro"));
}

Expand Down
6 changes: 5 additions & 1 deletion tools/driver/driver.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,13 @@ int driverMain(int argc, TArgs argv) try {

std::optional<bool> includeComments;
std::optional<bool> includeDirectives;
std::optional<bool> obfuscateIds;
driver.cmdLine.add("--comments", includeComments,
"Include comments in preprocessed output (with -E)");
driver.cmdLine.add("--directives", includeDirectives,
"Include compiler directives in preprocessed output (with -E)");
driver.cmdLine.add("--obfuscate-ids", obfuscateIds,
"Randomize all identifiers in preprocessed output (with -E)");

std::optional<std::string> astJsonFile;
driver.cmdLine.add(
Expand Down Expand Up @@ -127,7 +130,8 @@ int driverMain(int argc, TArgs argv) try {
bool ok = true;
try {
if (onlyPreprocess == true) {
ok = driver.runPreprocessor(includeComments == true, includeDirectives == true);
ok = driver.runPreprocessor(includeComments == true, includeDirectives == true,
obfuscateIds == true);
}
else if (onlyMacros == true) {
driver.reportMacros();
Expand Down