Skip to content
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
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,22 @@ reimplementation of Cheat Engine).

### Fixes

- Tables whose records carry attributes on their tag (`<CheatEntry
NoCheckbox="1">`, `<CheatEntry NoScriptTag="1">`) load completely again
([#15](https://github.com/wleeaf/cheat-engine-linux/issues/15)). Such a
record was skipped and its children moved to the top level: the Dave the
Diver table from that issue lost its "Initialize Mono" script with all 18
hooks under it and loaded 550 of its 1040 records. The attributes are now
kept and written back on save.
- Lua in tables written for Cheat Engine runs further:
- every function answers to both cases of its first letter, as in Cheat
Engine (`OpenProcess`, `ShellExecute`);
- `getProcessIDFromProcessName` and `openProcess` find a Windows game under
Wine or Proton by its `.exe` name;
- `mono_initialize()` and `LaunchMonoDataCollector()` are accepted, so an
"Initialize Mono" script enables (Mono and IL2CPP support is built in, so
they inject nothing);
- `beep()` exists.
- Memory that Wine commits for a hook (see v1.2.0 and
[#9](https://github.com/wleeaf/cheat-engine-linux/issues/9)) now also works
for a game inside a Proton (Steam Runtime) or Flatpak container. The small
Expand Down
34 changes: 25 additions & 9 deletions analysis/mono_dissector.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -100,28 +100,44 @@ MonoDissection parseMonoDump(const std::string& text) {
return out;
}

ManagedKind detectManagedKind(ProcessHandle& proc) {
namespace {
struct RuntimeModules {
std::optional<ModuleInfo> mono, il2cpp;
};

RuntimeModules runtimeModules(ProcessHandle& proc) {
// Mono ships libmono*/mono-2.0; IL2CPP builds put the AOT code in
// GameAssembly.so (Unity/Linux) and carry global-metadata.dat + il2cpp_* code.
bool mono = false, il2cpp = false;
RuntimeModules found;
for (const auto& m : proc.modules()) {
std::string n = m.name;
for (auto& ch : n) ch = static_cast<char>(std::tolower((unsigned char)ch));
// The Mono runtime itself: libmono-2.0 / libmonosgen-2.0 /
// libmonobdwgc-2.0 (Linux), mono-2.0-bdwgc.dll / mono.dll (Unity under
// Proton), or a mono / mono-sgen executable. Not any name containing
// "mono": fonts such as DejaVuSansMono.ttf are mapped by most games.
if (n.starts_with("libmono-2.0") || n.starts_with("libmonosgen") || n.starts_with("libmonobdwgc") ||
n.starts_with("mono-2.0") || n == "mono.dll" || n == "mono" || n.starts_with("mono-sgen"))
mono = true;
if (n.find("gameassembly") != std::string::npos || n.find("il2cpp") != std::string::npos)
il2cpp = true;
if (!found.mono && (n.starts_with("libmono-2.0") || n.starts_with("libmonosgen") || n.starts_with("libmonobdwgc") ||
n.starts_with("mono-2.0") || n == "mono.dll" || n == "mono" || n.starts_with("mono-sgen")))
found.mono = m;
if (!found.il2cpp && (n.find("gameassembly") != std::string::npos || n.find("il2cpp") != std::string::npos))
found.il2cpp = m;
}
if (mono) return ManagedKind::Mono;
if (il2cpp) return ManagedKind::Il2Cpp;
return found;
}
} // namespace

ManagedKind detectManagedKind(ProcessHandle& proc) {
const auto found = runtimeModules(proc);
if (found.mono) return ManagedKind::Mono;
if (found.il2cpp) return ManagedKind::Il2Cpp;
return ManagedKind::None;
}

std::optional<ModuleInfo> managedRuntimeModule(ProcessHandle& proc) {
auto found = runtimeModules(proc);
return found.mono ? found.mono : found.il2cpp;
}

std::string findMonoAgentPath() { return findCompanionLibrary("libcecore_mono_agent.so"); }

std::string findCompanionLibrary(const char* kName) {
Expand Down
3 changes: 3 additions & 0 deletions analysis/mono_dissector.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ std::string findCompanionLibrary(const char* name);
/// rather than injecting an agent that finds no mono_* symbols.
enum class ManagedKind { None, Mono, Il2Cpp };
ManagedKind detectManagedKind(ProcessHandle& proc);
/// The module detectManagedKind decided by: the Mono runtime library, else the
/// IL2CPP binary (GameAssembly). None for a target without either.
std::optional<ModuleInfo> managedRuntimeModule(ProcessHandle& proc);

/// Inject the agent .so into `proc`, wait up to timeoutMs for its dump to
/// complete, and parse it. `agentSoPath` is the path to libcecore_mono_agent.so.
Expand Down
41 changes: 35 additions & 6 deletions core/ct_file.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -930,7 +930,10 @@ bool writeTableXml(const CheatTable& table,std::ostream& f) {
std::function<void(int, int)> writeEntry = [&](int i, int depth) {
if (done[i]) return;
done[i] = 1;
f << " <CheatEntry>\n";
f << " <CheatEntry";
if (!entries[i].entryAttributes.empty() && isAttributeText(entries[i].entryAttributes))
f << " " << entries[i].entryAttributes;
f << ">\n";
writeEntryFields(entries[i]);
if (!children[i].empty() && depth + 1 < kMaxEntryDepth) {
f << " <CheatEntries>\n";
Expand Down Expand Up @@ -1127,19 +1130,36 @@ static std::string unknownRecordElements(const std::string& own) {
// for nested <tag> pairs. npos if unbalanced. Needed because Cheat Engine nests a
// group's children inside its own <CheatEntries>, so a naive find of the first
// close tag matches a child's close instead of the parent's.
// Position of the next start tag of `tag` at or after `from`: "<tag>" or one
// with attributes ("<CheatEntry NoCheckbox=\"1\">", as Cheat Engine writes a
// record without a check box). Not a longer name ("<CheatEntries>") and not a
// self-closing "<tag .../>", which has no close tag to match.
static size_t findStartTag(const std::string& xml, const std::string& tag, size_t from) {
const std::string open = "<" + tag;
for (size_t p = xml.find(open, from); p != std::string::npos; p = xml.find(open, p + 1)) {
const size_t after = p + open.size();
if (after >= xml.size()) break;
if (xml[after] == '>') return p;
if (xml[after] != ' ' && xml[after] != '\t' && xml[after] != '\r' && xml[after] != '\n') continue;
const size_t end = xml.find('>', after);
if (end == std::string::npos) break;
if (xml[end - 1] != '/') return p;
}
return std::string::npos;
}

static size_t findMatchingClose(const std::string& xml, size_t openPos, const std::string& tag) {
std::string open = "<" + tag + ">";
std::string close = "</" + tag + ">";
// Keep the next opening and closing tag and advance only the one taken:
// searching both again on every step rescanned the text up to the next
// close each time, which made a deeply nested table quadratic to load.
size_t nextOpen = xml.find(open, openPos + open.size());
size_t nextClose = xml.find(close, openPos + open.size());
size_t nextOpen = findStartTag(xml, tag, openPos + 1);
size_t nextClose = xml.find(close, openPos + 1);
int depth = 1;
while (nextClose != std::string::npos) {
if (nextOpen != std::string::npos && nextOpen < nextClose) {
++depth;
nextOpen = xml.find(open, nextOpen + open.size());
nextOpen = findStartTag(xml, tag, nextOpen + 1);
} else {
if (--depth == 0) return nextClose;
nextClose = xml.find(close, nextClose + close.size());
Expand Down Expand Up @@ -1172,7 +1192,7 @@ static void parseCheatEntriesBlock(const std::string& xml, size_t begin, size_t
if (depth >= kMaxEntryDepth) { validFormat = false; return; }
size_t pos = begin;
while (true) {
auto entryStart = xml.find("<CheatEntry>", pos);
auto entryStart = findStartTag(xml, "CheatEntry", pos);
if (entryStart == std::string::npos || entryStart >= end) break;
auto entryClose = findMatchingClose(xml, entryStart, "CheatEntry");
if (entryClose == std::string::npos || entryClose + CE_CLOSE.size() > end) break;
Expand Down Expand Up @@ -1205,6 +1225,13 @@ static void parseCheatEntriesBlock(const std::string& xml, size_t begin, size_t

CheatEntry e;
e.parentId = parentId;
// CE marks some records on the tag itself (NoCheckbox="1" for a label,
// NoScriptTag="1"); kept so a save writes them back.
if (const size_t tagEnd = xml.find('>', entryStart); tagEnd != std::string::npos && tagEnd < entryClose) {
const size_t first = entryStart + std::string("<CheatEntry").size();
std::string attributes = trimmedXmlText(xml.substr(first, tagEnd - first));
if (isAttributeText(attributes)) e.entryAttributes = std::move(attributes);
}
auto idStr = getTag(ownXml, "ID");
int parsedId = 0;
const auto [idStop, idError] = std::from_chars(idStr.data(), idStr.data() + idStr.size(), parsedId);
Expand Down Expand Up @@ -1950,6 +1977,7 @@ bool writeTableJson(const CheatTable& table,std::ostream& f) {
}
if (e.asyncScript) f << ",\"async\":true";
if (!e.dropdownAttributes.empty()) f << ",\"dropdownAttributes\":\"" << jsonEscape(e.dropdownAttributes) << "\"";
if (!e.entryAttributes.empty()) f << ",\"entryAttributes\":\"" << jsonEscape(e.entryAttributes) << "\"";
if (!e.extraHotkeysXml.empty()) f << ",\"extraHotkeys\":\"" << jsonEscape(e.extraHotkeysXml) << "\"";
if (!e.extraXml.empty()) f << ",\"extraXml\":\"" << jsonEscape(e.extraXml) << "\"";
if (e.active) f << ",\"active\":true";
Expand Down Expand Up @@ -2105,6 +2133,7 @@ static bool readTableJson(const JsonValue& root,CheatTable& table) {
e.extraHotkeysXml = jsonStringField(item, "extraHotkeys");
e.extraXml = jsonStringField(item, "extraXml");
e.dropdownAttributes = jsonStringField(item, "dropdownAttributes");
e.entryAttributes = jsonStringField(item, "entryAttributes");
e.color = jsonStringField(item, "color");
e.dropdownList = jsonStringField(item, "dropdown");
e.hotkeyKeys = jsonStringField(item, "hotkeys");
Expand Down
1 change: 1 addition & 0 deletions core/ct_file.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ struct CheatEntry {
std::string color; // Display color as RGB hex ("RRGGBB" or "#rrggbb"); .CT files hold CE's BGR
std::string dropdownList; // Choices, one "value:label" per line as CE writes them (older tables: ';')
std::string dropdownAttributes; // Attributes of CE's <DropDownList> (DisplayValueAsItem="1" ...), kept as written
std::string entryAttributes; // Attributes of the record's own <CheatEntry> (NoCheckbox="1", NoScriptTag="1"), kept as written
std::string hotkeyKeys; // Hotkey binding
std::string increaseHotkeyKeys;
std::string decreaseHotkeyKeys;
Expand Down
19 changes: 19 additions & 0 deletions docs/SCRIPTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,25 @@ local layout = getIl2CppClassLayout("Player")
if not layout then print("no IL2CPP here"); return end
```

### Tables written for Cheat Engine

As in Cheat Engine, every function also answers to its name with the other
case of the first letter: `OpenProcess` is `openProcess`, `ShellExecute` is
`shellExecute`. Lua's own functions (`print`, `pairs`) keep their one name.

`getProcessIDFromProcessName("Game.exe")` and `openProcess("Game.exe")` find a
Windows program under Wine or Proton by its `.exe` name, ignoring case, as
Windows does. Wine runs it as `wine64-preloader`, with the program's Windows
path in its first argument.

Cheat Engine's `mono_initialize()` and `LaunchMonoDataCollector()` are accepted,
so a table's "Initialize Mono" script runs. Mono and IL2CPP support is built in,
and nothing is injected: `mono_initialize()` does nothing, and
`LaunchMonoDataCollector()` returns the base address of the target's Mono or
IL2CPP runtime module, or 0 when the target has neither. The collector's
`mono_*` query functions are not provided. Use `monoDissect` and the
`getIl2Cpp*` functions below instead.

---

## Typed memory access
Expand Down
4 changes: 2 additions & 2 deletions gui/addresslist_model.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -539,8 +539,8 @@ bool AddressListModel::fromJson(const QJsonArray& arr, bool preserveExisting) {
e.decreaseHotkeyKeys = obj["decreaseHotkey"].toString();
e.hotkeyStep = obj["hotkeyStep"].toString("1");
e.luaScript = obj["lua"].toString();
for (const char* key : {"customType", "async", "dropdownAttributes", "unparsedAddress", "unparsedOffsets",
"extraHotkeys", "extraXml"})
for (const char* key : {"customType", "async", "dropdownAttributes", "entryAttributes", "unparsedAddress",
"unparsedOffsets", "extraHotkeys", "extraXml"})
if (obj.contains(key)) e.tableFields[key] = obj[key];
e.indent = std::max(0, obj.contains("indent")
? obj["indent"].toInt()
Expand Down
2 changes: 2 additions & 0 deletions gui/mainwindow_table.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ ce::CheatTable MainWindow::buildCheatTable() const {
e.customTypeName = obj["customType"].toString().toStdString();
e.asyncScript = obj["async"].toBool();
e.dropdownAttributes = obj["dropdownAttributes"].toString().toStdString();
e.entryAttributes = obj["entryAttributes"].toString().toStdString();
e.unparsedAddress = obj["unparsedAddress"].toString().toStdString();
for (const auto& text : obj["unparsedOffsets"].toArray())
e.unparsedOffsets.push_back(text.toString().toStdString());
Expand Down Expand Up @@ -349,6 +350,7 @@ QJsonArray cheatEntriesToJson(const ce::CheatTable& table) {
if (!e.customTypeName.empty()) obj["customType"] = QString::fromStdString(e.customTypeName);
if (e.asyncScript) obj["async"] = true;
if (!e.dropdownAttributes.empty()) obj["dropdownAttributes"] = QString::fromStdString(e.dropdownAttributes);
if (!e.entryAttributes.empty()) obj["entryAttributes"] = QString::fromStdString(e.entryAttributes);
if (!e.unparsedOffsets.empty()) {
QJsonArray texts;
for (const auto& text : e.unparsedOffsets) texts.append(QString::fromStdString(text));
Expand Down
3 changes: 3 additions & 0 deletions scripting/lua_bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -638,6 +638,9 @@ static void registerTableToolBindings(lua_State* L) {
lua_register(L, "playSound", l_playSound);
lua_register(L, "getManagedRuntimes", l_getManagedRuntimes);
lua_register(L, "monoDissect", l_monoDissect);
lua_register(L, "mono_initialize", l_monoInitialize);
lua_register(L, "LaunchMonoDataCollector", l_launchMonoDataCollector);
lua_register(L, "beep", l_beep);
lua_register(L, "findMonoFunction", l_findMonoFunction);
lua_register(L, "findMonoInstances", l_findMonoInstances);
lua_register(L, "executeCode", l_executeCode);
Expand Down
3 changes: 3 additions & 0 deletions scripting/lua_bindings_internal.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,9 @@ int l_generateTrainer(lua_State* L);
// lua_bindings_runtimes.cpp
int l_getManagedRuntimes(lua_State* L);
int l_monoDissect(lua_State* L);
int l_monoInitialize(lua_State* L);
int l_launchMonoDataCollector(lua_State* L);
int l_beep(lua_State* L);
int l_createSimpleHook(lua_State* L);
int l_removeSimpleHook(lua_State* L);
int l_findMonoFunction(lua_State* L);
Expand Down
22 changes: 21 additions & 1 deletion scripting/lua_bindings_process.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -109,13 +109,33 @@ static std::string readProcessName(const std::filesystem::path& procDir) {
return name;
}

// A Windows program under Wine or Proton runs as wine64-preloader with a
// truncated comm ("DaveTheDiver.ex"); Wine puts the program's Windows path in
// argv[0] ("Z:\\games\\DaveTheDiver.exe"). Only the program itself has it
// there: Proton's launcher, steam.exe and the runtime's wrappers name the
// .exe later in their arguments. Windows compares the name without case.
static bool windowsProgramMatches(const std::filesystem::path& procDir, std::string_view target) {
auto lower = [](std::string_view text) {
std::string out(text);
for (char& c : out) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
return out;
};
const std::string wanted = lower(target);
if (wanted.size() <= 4 || !wanted.ends_with(".exe")) return false;
std::ifstream cmdline(procDir / "cmdline", std::ios::binary);
std::string argv0;
if (!cmdline || !std::getline(cmdline, argv0, '\0')) return false;
const size_t slash = argv0.find_last_of("/\\");
return lower(slash == std::string::npos ? argv0 : argv0.substr(slash + 1)) == wanted;
}

static bool processNameMatches(const std::filesystem::path& procDir, std::string_view target) {
if (readProcessName(procDir) == target)
return true;

std::error_code ec;
auto exe = std::filesystem::read_symlink(procDir / "exe", ec);
return !ec && exe.filename().string() == target;
return (!ec && exe.filename().string() == target) || windowsProgramMatches(procDir, target);
}

pid_t findProcessIdByName(std::string_view target) {
Expand Down
21 changes: 21 additions & 0 deletions scripting/lua_bindings_runtimes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,27 @@ extern "C" {
#include "scripting/lua_bindings_internal.hpp"
namespace ce::lua_detail {

// Cheat Engine's mono_initialize() sets up its injected Mono data collector
// (menus, process-open hooks). Mono and IL2CPP support is built in here
// (monoDissect, getIl2CppClasses, ...), so there is nothing to set up; tables
// call it before their own scripts.
int l_monoInitialize(lua_State*) { return 0; }

// LaunchMonoDataCollector() -> the base address of the target's Mono or IL2CPP
// runtime module, or 0 without one (Cheat Engine returns the runtime's base
// once its collector runs, and 0 on failure). Nothing is injected: the
// collector's mono_* query functions are not provided, and monoDissect and
// the getIl2Cpp* functions read that information instead.
int l_launchMonoDataCollector(lua_State* L) {
auto* p = getProc(L);
auto runtime = p ? ce::managedRuntimeModule(*p) : std::nullopt;
lua_pushinteger(L, runtime ? static_cast<lua_Integer>(runtime->base) : 0);
return 1;
}

// beep(): the GUI sounds the desktop's bell; without one there is nothing to do.
int l_beep(lua_State*) { return 0; }

int l_getManagedRuntimes(lua_State* L) {
auto* p = getProc(L);
lua_newtable(L);
Expand Down
48 changes: 48 additions & 0 deletions scripting/lua_engine.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
#include "platform/linux/ceserver_client.hpp" // complete type for ownedCeserverClient_

extern "C" {
#include <set>
#include <cctype>
#include <string>
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
Expand Down Expand Up @@ -357,6 +360,51 @@ void LuaEngine::registerBindings() {

// Register extended bindings (readByte, readString, disassemble, autoAssemble, etc.)
registerExtendedBindings(L_);
addCheatEngineCaseAliases(L_);
}

void addCheatEngineCaseAliases(lua_State* L) {
// Lua's own functions keep their one name, as in Cheat Engine.
static const std::set<std::string, std::less<>> baseLibrary = {
"assert", "collectgarbage", "dofile", "error", "getmetatable", "ipairs", "load", "loadfile", "next",
"pairs", "pcall", "print", "rawequal", "rawget", "rawlen", "rawset", "require", "select",
"setmetatable", "tonumber", "tostring", "type", "xpcall"};
static constexpr const char* kAliases = "ce_case_aliases"; // alias name -> the function it was given
if (lua_getfield(L, LUA_REGISTRYINDEX, kAliases) != LUA_TTABLE) {
lua_pop(L, 1);
lua_newtable(L);
lua_pushvalue(L, -1);
lua_setfield(L, LUA_REGISTRYINDEX, kAliases);
}
const int aliases = lua_gettop(L);
lua_pushglobaltable(L);
const int globals = lua_gettop(L);
std::vector<std::string> names;
for (lua_pushnil(L); lua_next(L, globals); lua_pop(L, 1))
if (lua_type(L, -2) == LUA_TSTRING && lua_iscfunction(L, -1)) names.emplace_back(lua_tostring(L, -2));
for (const auto& name : names) {
const unsigned char first = static_cast<unsigned char>(name.front());
if (!std::isalpha(first) || baseLibrary.contains(name)) continue;
// An alias is not a source of further aliases.
if (lua_getfield(L, aliases, name.c_str()) != LUA_TNIL) { lua_pop(L, 1); continue; }
lua_pop(L, 1);
std::string other = name;
other.front() = static_cast<char>(first ^ 0x20);
lua_pushstring(L, other.c_str());
lua_rawget(L, globals); // what the other name holds now
lua_getfield(L, aliases, other.c_str()); // what this gave it before, if anything
const bool free = lua_isnil(L, -2) || (!lua_isnil(L, -1) && lua_rawequal(L, -1, -2));
lua_pop(L, 2);
if (!free) continue;
lua_pushstring(L, name.c_str());
lua_rawget(L, globals);
lua_pushvalue(L, -1);
lua_setfield(L, aliases, other.c_str());
lua_pushstring(L, other.c_str());
lua_insert(L, -2);
lua_rawset(L, globals);
}
lua_pop(L, 2);
}

std::string LuaEngine::execute(const std::string& code) {
Expand Down
Loading
Loading