175 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
304 lines
19 KiB
C++
304 lines
19 KiB
C++
// SPDX-License-Identifier: GPL-2.0-or-later
|
|
// Linux worker configures ONLY our owned PE module. No engine calls on this
|
|
// thread, and no ELF/C++ callback runs on the Windows UI thread.
|
|
#include "engine_bridge.hpp"
|
|
#include "session.h"
|
|
#include <boost/property_tree/json_parser.hpp>
|
|
#include <boost/property_tree/ptree.hpp>
|
|
#include <array>
|
|
#include <chrono>
|
|
#include <cstring>
|
|
#include <fstream>
|
|
#include <mutex>
|
|
#include <sstream>
|
|
#include <thread>
|
|
#include <atomic>
|
|
#include <vector>
|
|
#include <sys/mman.h>
|
|
#include <fcntl.h>
|
|
#include <unistd.h>
|
|
namespace gateway::engine {
|
|
namespace {
|
|
constexpr uintptr_t base=0x140000000,login_table=0x14575a130;
|
|
struct Bridge {
|
|
uint32_t abi,size;
|
|
volatile uint32_t stage,result_count,balanced,input_count;
|
|
uint64_t original_callback;
|
|
uint32_t report_length,reserved;
|
|
char report[16384];
|
|
};
|
|
static_assert(sizeof(Bridge)==16424 && offsetof(Bridge,report)==40);
|
|
std::mutex report_mutex;
|
|
std::string public_report;
|
|
bool read_at(int fd,uintptr_t address,void* out,size_t size){return pread(fd,out,size,off_t(address))==ssize_t(size);}
|
|
std::string hex(uintptr_t v){std::ostringstream s;s<<"0x"<<std::hex<<v;return s.str();}
|
|
uintptr_t owned_module(const std::filesystem::path& path){
|
|
std::ifstream maps("/proc/self/maps");std::string line;
|
|
while(std::getline(maps,line)){
|
|
std::istringstream row(line);std::string interval,permissions,offset,device,inode,name;
|
|
row>>interval>>permissions>>offset>>device>>inode;std::getline(row,name);
|
|
auto start=name.find_first_not_of(' ');if(start==std::string::npos)continue;
|
|
if(name.substr(start)==path.string() && offset=="00000000")return std::stoull(interval,nullptr,16);
|
|
}
|
|
return 0;
|
|
}
|
|
bool owned_writable(uintptr_t address,size_t length){
|
|
if(length>UINTPTR_MAX-address)return false;
|
|
auto cursor=address,end=address+length;
|
|
std::ifstream maps("/proc/self/maps");std::string line;
|
|
while(std::getline(maps,line)){
|
|
std::istringstream row(line);std::string interval,permissions;row>>interval>>permissions;
|
|
auto split=interval.find('-');if(split==std::string::npos)continue;
|
|
auto low=std::stoull(interval.substr(0,split),nullptr,16),high=std::stoull(interval.substr(split+1),nullptr,16);
|
|
if(low>cursor)return false;
|
|
if(low<=cursor && cursor<high && permissions.starts_with("rw")){
|
|
cursor=std::min<uintptr_t>(high,end);if(cursor==end)return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
bool install_callback_adapters(uintptr_t ready,uintptr_t getter,uintptr_t snapshot=0,uintptr_t request=0){
|
|
constexpr uintptr_t page=0x144597000;
|
|
// The additional two tails are certified by the loaded258868 page and
|
|
// pinned original pdata intervals. Existing Ready/GetState sites remain.
|
|
const std::array<std::pair<uintptr_t,uintptr_t>,4> adapters{{
|
|
{0x144597493,getter},{0x1445979a4,ready},
|
|
{0x144597f22,snapshot},{0x144597fe2,request}}};
|
|
if(!ready || !getter || bool(snapshot)!=bool(request))return false;
|
|
const unsigned count=snapshot?4:2;
|
|
// This exact page is shared RX in Wine. PTRACE_POKEDATA cannot force a
|
|
// shared read-only write. Perform the bounded, process-local patch here,
|
|
// while the diagnostic parent holds the UI at its genuine registration.
|
|
std::ifstream maps("/proc/self/maps");std::string line;bool executable=false;
|
|
while(std::getline(maps,line)){
|
|
std::istringstream row(line);std::string interval,permissions;row>>interval>>permissions;
|
|
auto split=interval.find('-');if(split==std::string::npos)continue;
|
|
auto low=std::stoull(interval.substr(0,split),nullptr,16),high=std::stoull(interval.substr(split+1),nullptr,16);
|
|
if(low<=page && page+4096<=high && permissions.starts_with("r-x"))executable=true;
|
|
}
|
|
if(!executable)return false;
|
|
for(unsigned at=0;at<count;++at)for(unsigned i=0;i<12;++i)if(*reinterpret_cast<volatile uint8_t*>(adapters[at].first+i)!=0xcc)return false;
|
|
if(mprotect(reinterpret_cast<void*>(page),4096,PROT_READ|PROT_WRITE|PROT_EXEC))return false;
|
|
for(unsigned at=0;at<count;++at){
|
|
auto [address,target]=adapters[at];
|
|
std::array<uint8_t,12> code{0x48,0xb8};std::memcpy(code.data()+2,&target,8);code[10]=0xff;code[11]=0xe0;
|
|
std::memcpy(reinterpret_cast<void*>(address),code.data(),code.size());
|
|
}
|
|
std::atomic_thread_fence(std::memory_order_seq_cst);
|
|
__builtin___clear_cache(reinterpret_cast<char*>(page),reinterpret_cast<char*>(page+4096));
|
|
if(!mprotect(reinterpret_cast<void*>(page),4096,PROT_READ|PROT_EXEC))return true;
|
|
// Retain no half-install if protection restoration fails.
|
|
for(unsigned at=0;at<count;++at)std::memset(reinterpret_cast<void*>(adapters[at].first),0xcc,12);
|
|
(void)mprotect(reinterpret_cast<void*>(page),4096,PROT_READ|PROT_EXEC);
|
|
return false;
|
|
}
|
|
}
|
|
void backend_report(std::string report){std::lock_guard lock(report_mutex);public_report=std::move(report);}
|
|
PacketDelivery publish_roster(const std::filesystem::path& workspace,gw_native_session* session,uint32_t realm_wire_id){
|
|
PacketDelivery result;
|
|
struct PacketHost {
|
|
uint32_t abi,size,ready,ack,proof_valid,payload_bytes,submitted,received;
|
|
uint32_t last_opcode,observed_state,error,reserved;
|
|
uint64_t original_receive;
|
|
uint8_t payload[16384];
|
|
};
|
|
static_assert(sizeof(PacketHost)==16440 && offsetof(PacketHost,payload)==56);
|
|
uint32_t required=0;
|
|
result.encode_result=gw_native_encode_roster(session,realm_wire_id,0,0,nullptr,0,&required);
|
|
if(result.encode_result!=-3 || required>16380)return result;
|
|
std::vector<uint8_t> wire(required+4);wire[0]=0x18;wire[1]=0;wire[2]=0x47;wire[3]=0;
|
|
result.encode_result=gw_native_encode_roster(session,realm_wire_id,0,0,wire.data()+4,required,&required);
|
|
if(result.encode_result)return result;
|
|
result.bytes=uint32_t(wire.size());
|
|
int fd=-1;
|
|
try{
|
|
boost::property_tree::ptree metadata;boost::property_tree::read_json((workspace/"runtime/native-engine-pe.json").string(),metadata);
|
|
auto packet_rva=metadata.get<uintptr_t>("exports.gw_packet_host_data");
|
|
auto poll_rva=metadata.get<uintptr_t>("exports.gw_poll_host_data");
|
|
auto path=workspace/"runtime/native-wine-prefix/drive_c/windows/system32/GWNativeBridge.dll";
|
|
fd=open("/proc/self/mem",O_RDONLY|O_CLOEXEC);if(fd<0)return result;
|
|
auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(60);
|
|
while(std::chrono::steady_clock::now()<deadline){
|
|
auto dll=owned_module(path);std::array<uint32_t,3> poll{};
|
|
if(dll && read_at(fd,dll+poll_rva,poll.data(),sizeof(poll)) && poll[0]==1 && poll[1]==1080 && poll[2]==3 && owned_writable(dll+packet_rva,sizeof(PacketHost))){
|
|
auto shared=reinterpret_cast<PacketHost*>(dll+packet_rva);
|
|
if(shared->abi!=1 || shared->size!=sizeof(PacketHost) || !shared->original_receive || shared->ready || shared->ack)break;
|
|
// Only a genuine authenticated native session reaches this point.
|
|
// No keys/authentication input cross into the Windows module.
|
|
std::memcpy(shared->payload,wire.data(),wire.size());shared->payload_bytes=uint32_t(wire.size());shared->proof_valid=1;
|
|
std::atomic_ref<uint32_t>(shared->ready).store(1,std::memory_order_release);result.published=true;
|
|
auto until=std::chrono::steady_clock::now()+std::chrono::seconds(5);
|
|
while(std::chrono::steady_clock::now()<until){
|
|
if(std::atomic_ref<uint32_t>(shared->ack).load(std::memory_order_acquire) && std::atomic_ref<uint32_t>(shared->received).load(std::memory_order_acquire))break;
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(10));
|
|
}
|
|
result.submitted=std::atomic_ref<uint32_t>(shared->submitted).load(std::memory_order_acquire);
|
|
result.received=std::atomic_ref<uint32_t>(shared->received).load(std::memory_order_acquire);
|
|
if(result.received){result.opcode=shared->last_opcode;result.state=shared->observed_state;}
|
|
result.error=std::atomic_ref<uint32_t>(shared->error).load(std::memory_order_acquire);break;
|
|
}
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(20));
|
|
}
|
|
close(fd);fd=-1;
|
|
}catch(...){if(fd>=0)close(fd);}
|
|
return result;
|
|
}
|
|
SessionRetention retain_session(const std::filesystem::path& workspace,gw_native_session* session,uint32_t seconds,
|
|
const std::function<void(const SessionRetention&)>& report){
|
|
SessionRetention result;
|
|
if(!session || seconds<1 || seconds>600){result.reason="invalid-retention-bound";return result;}
|
|
const auto start=std::chrono::steady_clock::now(),end=start+std::chrono::seconds(seconds);
|
|
try{
|
|
boost::property_tree::ptree metadata;
|
|
boost::property_tree::read_json((workspace/"runtime/native-engine-pe.json").string(),metadata);
|
|
auto rva=metadata.get<uintptr_t>("exports.gw_poll_host_data");
|
|
if(rva>=0x10000){result.reason="invalid-owned-host";return result;}
|
|
auto module=owned_module(workspace/"runtime/native-wine-prefix/drive_c/windows/system32/GWNativeBridge.dll");
|
|
if(!module || !owned_writable(module+rva,24)){result.reason="owned-host-unavailable";return result;}
|
|
auto* host=reinterpret_cast<uint32_t*>(module+rva);
|
|
auto next_ping=start,ping_deadline=end;
|
|
result.active=true;result.reason="awaiting-engine-session-adoption";report(result);
|
|
while(std::chrono::steady_clock::now()<end){
|
|
// Atomic access to our own status only. Restore sets stage4. Never
|
|
// keep a backend alive after its owned frame binding is removed.
|
|
auto stage=std::atomic_ref<uint32_t>(host[2]).load(std::memory_order_acquire);
|
|
if(host[0]!=1 || host[1]!=1080 || stage!=3 || host[5]){result.reason="frame-host-restored-or-failed";break;}
|
|
auto now=std::chrono::steady_clock::now();
|
|
if(now>=next_ping){
|
|
result.error=gw_native_ping(session,result.pings+1,0);
|
|
if(result.error){result.reason="heartbeat-send-failed";break;}
|
|
++result.pings;next_ping=now+std::chrono::seconds(30);ping_deadline=now+std::chrono::seconds(5);
|
|
}
|
|
auto serviced=gw_native_service(session,100);
|
|
if(serviced<0){result.error=serviced;result.reason="backend-stream-failed";break;}
|
|
if(serviced==2){result.reason="non-control-packet-awaits-engine-consumer";break;}
|
|
if(serviced==1){
|
|
++result.pongs;ping_deadline=end;
|
|
result.elapsed_ms=uint32_t(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now()-start).count());
|
|
report(result);
|
|
}
|
|
if(result.pings!=result.pongs && std::chrono::steady_clock::now()>=ping_deadline){
|
|
result.error=-2;result.reason="heartbeat-timeout";break;
|
|
}
|
|
}
|
|
if(result.reason=="awaiting-engine-session-adoption")result.reason="bounded-retention-expired";
|
|
}catch(...){result.error=-2;result.reason="retention-host-unavailable";}
|
|
result.active=false;
|
|
result.elapsed_ms=uint32_t(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now()-start).count());
|
|
return result;
|
|
}
|
|
void watch_registration(const std::filesystem::path& workspace){
|
|
// Read only owned, fixed public diagnostic fields. This worker never
|
|
// installs hooks or calls the engine; Windows initializes itself.
|
|
struct Registration {
|
|
uint32_t abi,size,stage,error,namespaces_seen,callbacks_seen;
|
|
uint32_t windows_thread,original_count,registered_count,reserved;
|
|
uint64_t lua_state,helper_return;
|
|
};
|
|
static_assert(sizeof(Registration)==56);
|
|
try{
|
|
boost::property_tree::ptree metadata;
|
|
boost::property_tree::read_json((workspace/"runtime/native-engine-pe.json").string(),metadata);
|
|
auto rva=metadata.get<uintptr_t>("exports.gw_registration_data");
|
|
auto bridge_rva=metadata.get<uintptr_t>("exports.gw_bridge_data");
|
|
auto path=workspace/"runtime/native-wine-prefix/drive_c/windows/system32/GWNativeBridge.dll";
|
|
if(rva>=0x10000 || bridge_rva>=0x10000)return;
|
|
int fd=open("/proc/self/mem",O_RDONLY|O_CLOEXEC);if(fd<0)return;
|
|
auto until=std::chrono::steady_clock::now()+std::chrono::seconds(180);
|
|
uint32_t previous_stage=~0U,previous_calls=~0U,previous_ready=~0U;
|
|
while(std::chrono::steady_clock::now()<until){
|
|
auto dll=owned_module(path);Registration d{};Bridge b{};
|
|
if(dll && owned_writable(dll+rva,sizeof(d)) && read_at(fd,dll+rva,&d,sizeof(d)) && d.abi==1 && d.size==sizeof(d) && read_at(fd,dll+bridge_rva,&b,sizeof(b))){
|
|
if(d.stage==1){
|
|
auto shared=reinterpret_cast<volatile Registration*>(dll+rva);
|
|
bool okay=false;
|
|
if(d.registered_count==30 || d.registered_count==32){
|
|
const bool realm=d.registered_count==32;
|
|
okay=install_callback_adapters(dll+metadata.get<uintptr_t>("exports.gw_bridge_callback"),dll+metadata.get<uintptr_t>("exports.gw_registration_get_state"),
|
|
realm?dll+metadata.get<uintptr_t>("exports.gw_registration_get_realm_snapshot"):0,
|
|
realm?dll+metadata.get<uintptr_t>("exports.gw_registration_request_realm"):0);
|
|
}
|
|
shared->error=okay?0:1;shared->stage=okay?2:101;
|
|
d.error=shared->error;d.stage=shared->stage;
|
|
}
|
|
if(d.stage!=previous_stage || d.callbacks_seen!=previous_calls || b.stage!=previous_ready){
|
|
std::ofstream out(workspace/"runtime/native-engine-registration.json");
|
|
out<<"{\"pid\":"<<getpid()<<",\"stage\":"<<d.stage<<",\"error\":"<<d.error
|
|
<<",\"namespaces_seen\":"<<d.namespaces_seen<<",\"windows_thread\":"<<d.windows_thread
|
|
<<",\"original_count\":"<<d.original_count<<",\"registered_count\":"<<d.registered_count
|
|
<<",\"registered_callback_calls\":"<<d.callbacks_seen<<",\"lua_state\":\""<<hex(d.lua_state)
|
|
<<"\",\"helper_return\":\""<<hex(d.helper_return)<<"\",\"original_ready_stage\":"<<b.stage
|
|
<<",\"original_ready_result_count\":"<<b.result_count<<",\"original_ready_stack_balanced\":"<<(b.balanced?"true":"false")
|
|
<<",\"native_helper_returned\":"<<(d.stage==3?"true":"false")
|
|
<<",\"initialization_debugger_used\":true,\"engine_world_entry\":false}\n";
|
|
previous_stage=d.stage;previous_calls=d.callbacks_seen;previous_ready=b.stage;
|
|
}
|
|
}
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(20));
|
|
}
|
|
close(fd);
|
|
}catch(...){}
|
|
}
|
|
void prepare_probe(const std::filesystem::path& workspace){
|
|
try{
|
|
boost::property_tree::ptree metadata;
|
|
boost::property_tree::read_json((workspace/"runtime/native-engine-pe.json").string(),metadata);
|
|
auto callback_rva=metadata.get<uintptr_t>("exports.gw_bridge_callback");
|
|
auto data_rva=metadata.get<uintptr_t>("exports.gw_bridge_data");
|
|
if(callback_rva>=0x10000 || data_rva>=0x10000)return;
|
|
auto output=workspace/"runtime/native-engine-plan.json";
|
|
auto module_path=workspace/"runtime/native-client/_classic_beta_/GWNativeBridge.dll";
|
|
if(metadata.get<std::string>("host","")=="private_prefix_d3d11")
|
|
module_path=workspace/"runtime/native-wine-prefix/drive_c/windows/system32/GWNativeBridge.dll";
|
|
int fd=open("/proc/self/mem",O_RDONLY|O_CLOEXEC);if(fd<0)return;
|
|
auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(60);
|
|
Bridge* shared=nullptr;
|
|
while(std::chrono::steady_clock::now()<deadline){
|
|
auto dll=owned_module(module_path);
|
|
if(dll && owned_writable(dll+data_rva,sizeof(Bridge))){
|
|
auto candidate=reinterpret_cast<Bridge*>(dll+data_rva);
|
|
if(candidate->abi==1 && candidate->size==sizeof(Bridge)){
|
|
// GetState is generated elsewhere, absent from this29-entry
|
|
// handwritten registration. Match actual IsLoginReady only.
|
|
for(unsigned i=0;i<29;++i){
|
|
std::array<uintptr_t,2> row{};std::array<char,13> name{};
|
|
if(!read_at(fd,login_table+i*16,row.data(),sizeof(row)))continue;
|
|
if(row[0]<base || row[0]>=base+0x8000000 || row[1]!=0x14242fd80)continue;
|
|
if(!read_at(fd,row[0],name.data(),name.size()) || std::memcmp(name.data(),"IsLoginReady",name.size()))continue;
|
|
std::string report;{std::lock_guard lock(report_mutex);report=public_report;}
|
|
if(report.empty() || report.size()>=sizeof(candidate->report))continue;
|
|
candidate->original_callback=row[1];
|
|
std::memcpy(candidate->report,report.data(),report.size());candidate->report_length=uint32_t(report.size());
|
|
std::ofstream out(output);
|
|
out<<"{\"pid\":"<<getpid()<<",\"login_callback\":\""<<hex(row[1])
|
|
<<"\",\"callback_name\":\"C_Login.IsLoginReady\",\"bridge_callback\":\""<<hex(dll+callback_rva)
|
|
<<"\",\"registration_entry\":\""<<hex(login_table+i*16)
|
|
<<"\",\"mode\":\"one_main_thread_PE_callback\",\"engine_world_entry\":false}\n";
|
|
shared=candidate;break;
|
|
}
|
|
}
|
|
}
|
|
if(shared)break;
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(20));
|
|
}
|
|
close(fd);if(!shared)return;
|
|
deadline=std::chrono::steady_clock::now()+std::chrono::seconds(300);uint32_t previous=~0U;
|
|
while(std::chrono::steady_clock::now()<deadline){
|
|
auto stage=shared->stage;
|
|
if(stage!=previous){
|
|
std::ofstream out(workspace/"runtime/native-engine-lua-bound.json");
|
|
out<<"{\"pid\":"<<getpid()<<",\"stage\":"<<stage<<",\"windows_PE_callback\":true"
|
|
<<",\"original_login_callback_called\":"<<(stage>=2?"true":"false")
|
|
<<",\"original_result_count\":"<<shared->result_count
|
|
<<",\"lua_stack_balanced\":"<<(shared->balanced?"true":"false")
|
|
<<",\"lua_input_count\":"<<shared->input_count
|
|
<<",\"namespace_registered\":false"<<",\"engine_world_entry\":false}\n";
|
|
previous=stage;
|
|
}
|
|
if(stage>=8)break;
|
|
std::this_thread::sleep_for(std::chrono::milliseconds(20));
|
|
}
|
|
}catch(...){} // Never let diagnostics terminate the engine or alter auth.
|
|
}
|
|
}
|