Remove C# and C++ port trees; update README references

The earlier C# (EasyHook) and C++ (MS Detours) ports were merged into
this repo under csharp/ and cpp/ so their full histories stay reachable
(git log -- csharp/ cpp/). Their trees are removed from HEAD because
their IPC tick epoch (delta against DateTime.UtcNow.Ticks) is
incompatible with the Rust implementation's raw FILETIME contract —
keeping both in the working tree would present two contradictory IPC
designs side by side.

The Java test target remains in the working tree; README links now
point at in-repo paths instead of the retired port repositories.
This commit is contained in:
2026-08-05 20:46:39 +07:00
parent a1db99a432
commit 7d5408d198
35 changed files with 3 additions and 4542 deletions
+3 -3
View File
@@ -2,7 +2,7 @@
A Windows tool that injects fake time into running processes by hooking Win32 time APIs. Written in Rust.
> **Status:** Active development. This is the canonical implementation. Language-specific ports are available in [C# (EasyHook)](https://github.com/tiennm99/time-mocker-csharp) and [C++ (MS Detours)](https://github.com/tiennm99/time-mocker-cpp).
> **Status:** Active development. This is the canonical implementation. Earlier C# (EasyHook) and C++ (MS Detours) ports are preserved in this repo's git history under `csharp/` and `cpp/` (removed from the working tree — their IPC tick epoch is incompatible with this implementation, see below).
## Architecture
@@ -89,5 +89,5 @@ Apache-2.0 — see [LICENSE](LICENSE).
## Related
- [time-mocker-csharp](https://github.com/tiennm99/time-mocker-csharp) — C# / EasyHook implementation
- [time-mocker-cpp](https://github.com/tiennm99/time-mocker-cpp) — C++ / MS Detours implementation
- `csharp/`, `cpp/` — earlier C# (EasyHook) and C++ (MS Detours) ports, preserved in git history only: `git log -- csharp/ cpp/`
- [`target/`](target/) — Java test target that validates injected fake time (also standalone at [time-mocker-target](https://github.com/tiennm99/time-mocker-target))
-15
View File
@@ -1,15 +0,0 @@
.vs/
x64/
x86/
Debug/
Release/
*.user
*.aps
*.suo
*.db
*.opendb
vcpkg/
packages/detours/lib/
packages/detours/include/
build/
out/
-55
View File
@@ -1,55 +0,0 @@
cmake_minimum_required(VERSION 3.20)
project(TimeMocker CXX)
find_package(detours CONFIG REQUIRED)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
if(NOT WIN32)
message(FATAL_ERROR "Windows only.")
endif()
add_compile_definitions(WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE)
set(IMGUI_DIR "${CMAKE_SOURCE_DIR}/TimeMocker.UI/imgui")
# ── TimeMocker.Hook (DLL) ─────────────────────────────────────────────────────
add_library(TimeMocker.Hook SHARED
TimeMocker.Hook/dllmain.cpp
TimeMocker.Hook/exports.cpp
TimeMocker.Hook/TimeMocker.Hook.def
)
target_include_directories(TimeMocker.Hook PRIVATE Shared)
target_link_libraries(TimeMocker.Hook PRIVATE detours::detours)
set_target_properties(TimeMocker.Hook PROPERTIES OUTPUT_NAME "TimeMocker.Hook"
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
# ── ImGui static lib ──────────────────────────────────────────────────────────
add_library(imgui STATIC
${IMGUI_DIR}/imgui.cpp
${IMGUI_DIR}/imgui_draw.cpp
${IMGUI_DIR}/imgui_tables.cpp
${IMGUI_DIR}/imgui_widgets.cpp
${IMGUI_DIR}/imgui_impl_win32.cpp
${IMGUI_DIR}/imgui_impl_dx11.cpp
)
target_include_directories(imgui PUBLIC ${IMGUI_DIR})
# ── TimeMocker.UI (GUI exe) ───────────────────────────────────────────────────
add_executable(TimeMocker.UI WIN32
TimeMocker.UI/main.cpp
TimeMocker.Injector/InjectionManager.cpp
)
target_include_directories(TimeMocker.UI PRIVATE Shared TimeMocker.Injector ${IMGUI_DIR})
target_link_libraries(TimeMocker.UI PRIVATE imgui detours::detours d3d11 dxgi Psapi)
set_target_properties(TimeMocker.UI PROPERTIES OUTPUT_NAME "TimeMocker"
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")
add_custom_command(TARGET TimeMocker.UI POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
$<TARGET_FILE:TimeMocker.Hook>
"${CMAKE_BINARY_DIR}/bin/TimeMocker.Hook.x64.dll"
COMMENT "Copying Hook DLL")
install(TARGETS TimeMocker.UI TimeMocker.Hook RUNTIME DESTINATION bin)
-201
View File
@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-243
View File
@@ -1,243 +0,0 @@
# TimeMocker — C++ / MS Detours Edition
A Windows tool that injects fake time into running processes by hooking Win32 time APIs using **Microsoft Detours**.
Port/rewrite of the original C# / EasyHook version with identical IPC design but in native C++.
---
## Architecture
```
TimeMocker.sln
├── Shared/
│ └── MockTimeInfo.h ─ Named MMF layout (shared between UI and Hook)
├── TimeMocker.Hook/ ─ DLL injected into target processes
│ ├── dllmain.cpp ─ DllMain: opens MMF, installs/removes Detours hooks
│ └── exports.cpp ─ Sentinel export for version check
├── TimeMocker.Injector/ ─ Static library: injection + IPC management
│ ├── InjectionManager.h/.cpp ─ LoadLibrary remote-thread injection + SharedMemoryHandle
│ └── ProcessWatcher.h ─ Background thread: auto-inject via glob/regex rules
└── TimeMocker.UI/
└── main.cpp ─ Interactive console controller
```
---
## Hooked APIs
| API | DLL |
|-----|-----|
| `GetSystemTime` | kernel32 |
| `GetLocalTime` | kernel32 |
| `GetSystemTimeAsFileTime` | kernel32 |
| `GetSystemTimePreciseAsFileTime` | kernel32 |
| `NtQuerySystemTime` | ntdll |
All hooks read `DeltaTicks` from the named MMF on each call and return
`real_utc_filetime_ticks + DeltaTicks`. When `DeltaTicks == 0` the real
time passes through unchanged.
---
## IPC Design
```
Named Memory-Mapped File: TimeMocker_<PID>
Size: 8 bytes
[0..7] DeltaTicks (LONGLONG, 100-ns units, signed)
= fakeUtcTicks - realUtcTicks at the moment the user clicks "Set"
```
- The UI creates the MMF **before** injection so the hook can open it in `DllMain`.
- Updates are written as atomic `InterlockedExchange64` — no locks on the hot path.
- The hook reads with a single volatile 8-byte load (~4 ns, no syscall).
- When the UI closes the MMF (on eject/exit), the hook's next read returns `0`,
silently falling back to real time.
---
## How Detours Works Here
```
Before injection:
kernel32!GetSystemTime → [real implementation]
After injection:
kernel32!GetSystemTime → Hook_GetSystemTime (our function)
→ Real_GetSystemTime (trampoline, via DetourAttach)
```
`DetourAttach` patches the first 514 bytes of the real function with a
`JMP` to our hook, and saves the overwritten bytes + a JMP back in a
trampoline so we can call the original.
---
## Requirements
- **Windows 10/11 x64**
- **Visual Studio 2022** (v143 toolset) or **CMake 3.20+**
- **Microsoft Detours** (installed via `scripts/setup.ps1` → vcpkg)
- Must run as **Administrator** (cross-process injection requires elevated privileges)
---
## Setup & Build
### Option A — Visual Studio 2022
```powershell
# 1. Install Detours via vcpkg (one-time)
powershell -ExecutionPolicy Bypass -File scripts\setup.ps1
# 2. Open solution
start TimeMocker.sln
# 3. Build → Release | x64
```
Output:
```
x64\Release\TimeMocker.exe ← controller
x64\Release\TimeMocker.Hook.x64.dll ← hook DLL (must be next to .exe)
x64\Release\TimeMocker.Hook.x86.dll ← hook DLL for 32-bit targets
```
### Option B — CMake + vcpkg
```powershell
# Install vcpkg + detours
git clone https://github.com/microsoft/vcpkg vcpkg
.\vcpkg\bootstrap-vcpkg.bat -disableMetrics
.\vcpkg\vcpkg install detours:x64-windows detours:x86-windows
# Configure + build
cmake -B build -DCMAKE_TOOLCHAIN_FILE=vcpkg/scripts/buildsystems/vcpkg.cmake -A x64
cmake --build build --config Release
```
---
## Usage (Console Controller)
```
timemocker> help
list [filter] list running processes
inject <pid> inject hook DLL into process
eject <pid> remove hook from process
time YYYY-MM-DD HH:MM:SS set fake time (local)
time now reset to real time
status show injected processes + delta
rule add <pattern> add glob auto-inject rule
rule add -r <pattern> add regex auto-inject rule
rule list list rules
rule del <index> remove rule by index
watch start / stop control auto-inject watcher
quit exit
```
### Examples
```
# List all processes with "notepad" in name/path
timemocker> list notepad
# Inject into Notepad (PID 12345) and set time to Jan 1 2020
timemocker> time 2020-01-01 00:00:00
timemocker> inject 12345
# Change time while injected (takes effect immediately)
timemocker> time 2025-12-31 23:59:00
# Auto-inject any process matching a glob
timemocker> rule add C:\Games\MyGame\*
# Auto-inject chrome.exe by name
timemocker> rule add *chrome*
# Auto-inject using regex
timemocker> rule add -r ^.*\\MyApp\.exe$
# Reset to real time and eject
timemocker> time now
timemocker> eject 12345
```
---
## Project Details
### DLL Injection Method
Uses the classic **LoadLibrary remote thread** technique:
1. `OpenProcess` with `PROCESS_CREATE_THREAD | PROCESS_VM_*` rights
2. `VirtualAllocEx` → write DLL path string into target's memory
3. `CreateRemoteThread(LoadLibraryW, dllPath)` → loads the DLL in-process
4. `WaitForSingleObject` → confirm load completed
5. On `DLL_PROCESS_ATTACH` the hook's `DllMain` opens the MMF and installs Detours
For **new processes** (before they start), `DetourCreateProcessWithDllEx()` can also
be used — it's included in the Detours SDK and injects before the first instruction
runs, before any DRM/anti-cheat initialises.
### 32-bit vs 64-bit
- **64-bit target**: `TimeMocker.Hook.x64.dll` is injected
- **32-bit target** (WOW64): `TimeMocker.Hook.x86.dll` is injected
- Both Hook DLLs are identical source; the platform is selected at build time
- The UI (x64) determines which DLL to use by calling `IsWow64Process`
### Auto-Inject Watcher
`ProcessWatcher` runs a background thread that polls `CreateToolhelp32Snapshot`
every 1.5 seconds. Any process whose full path or `.exe` name matches an enabled
rule is automatically injected with the current fake time delta.
Previously-seen PIDs are tracked in a `HashSet` so they're only matched once,
even if the process restarts with the same PID (very rare on Windows).
### Limitations
| Limitation | Notes |
|-----------|-------|
| **64-bit injector only** | The UI is x64-only; a separate x86 injector would be needed for 32-bit-only scenarios |
| **Anti-cheat / protected processes** | EAC, BattlEye, and system PPL processes block `OpenProcess` |
| **QueryPerformanceCounter** | Not affected — it reads a hardware MSR; EasyHook/Detours cannot intercept kernel MSR reads |
| **GetTickCount / timeGetTime** | Not hooked in this version — easy to add following the same pattern |
| **Hot eject** | DLL stays loaded but hooks are removed on unload (not forcible without `FreeLibrary` in a remote thread) |
---
## Adding a New Hook
1. Declare the real function pointer in `dllmain.cpp`:
```cpp
static DWORD (WINAPI* Real_GetTickCount)() = GetTickCount;
```
2. Write the hook function:
```cpp
static DWORD WINAPI Hook_GetTickCount()
{
// Convert fake UTC ticks to milliseconds since boot (approximate)
return static_cast<DWORD>(GetFakeUtcTicks() / 10000);
}
```
3. Add `DetourAttach` / `DetourDetach` calls in `InstallHooks` / `RemoveHooks`.
---
## License
Apache 2.0 (same as the original C# project).
## Related
- [time-mocker](https://github.com/tiennm99/time-mocker) — Original C# / EasyHook implementation.
-30
View File
@@ -1,30 +0,0 @@
#pragma once
// =============================================================================
// TimeMocker Shared IPC
// Named Memory-Mapped File layout shared between UI and Hook DLL.
// One MMF per injected process, named: TimeMocker_<PID>
// =============================================================================
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
static const wchar_t* MMF_PREFIX = L"TimeMocker_";
static const DWORD MMF_SIZE = sizeof(LONGLONG); // 8 bytes: DeltaTicks (Int64)
// The only field: signed tick offset to add to QueryUnbiasedInterruptTime / FILETIME.
// A tick = 100 nanoseconds (same unit as FILETIME / SYSTEMTIME internals).
// DeltaTicks == 0 → real time (pass-through)
// DeltaTicks > 0 → future (clock is ahead)
// DeltaTicks < 0 → past (clock is behind)
#pragma pack(push, 1)
struct MockTimeInfo
{
LONGLONG DeltaTicks; // Offset to add to the real UTC FILETIME ticks
};
#pragma pack(pop)
// Helper: build the MMF name for a given PID
inline void GetMmfName(DWORD pid, wchar_t* buf, size_t cchBuf)
{
swprintf_s(buf, cchBuf, L"%ls%lu", MMF_PREFIX, pid);
}
-7
View File
@@ -1,7 +0,0 @@
LIBRARY TimeMocker.Hook
EXPORTS
; No public exports required Detours helper process detection uses
; an internal mechanism. We export a sentinel for the injector to
; verify the DLL loaded correctly.
TimeMockerHookVersion @1
-140
View File
@@ -1,140 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{A1111111-1111-1111-1111-111111111111}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>TimeMockerHook</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>DynamicLibrary</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<!-- ── Common compiler settings ── -->
<ItemDefinitionGroup>
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<ConformanceMode>true</ConformanceMode>
<!-- Include Detours via vcpkg or a local copy -->
<AdditionalIncludeDirectories>$(SolutionDir)packages\detours\include;$(SolutionDir)Shared;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32_LEAN_AND_MEAN;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<!-- Link Detours and runtime imports -->
<AdditionalDependencies>detours.lib;%(AdditionalDependencies)</AdditionalDependencies>
<ModuleDefinitionFile>TimeMocker.Hook.def</ModuleDefinitionFile>
</Link>
</ItemDefinitionGroup>
<!-- ── Debug x86 ── -->
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_DEBUG;TIMEMOCKER_HOOK_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
</ClCompile>
<Link>
<AdditionalLibraryDirectories>$(SolutionDir)packages\detours\lib\x86;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<!-- ── Release x86 ── -->
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>NDEBUG;TIMEMOCKER_HOOK_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
</ClCompile>
<Link>
<AdditionalLibraryDirectories>$(SolutionDir)packages\detours\lib\x86;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<!-- ── Debug x64 ── -->
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>_DEBUG;TIMEMOCKER_HOOK_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
</ClCompile>
<Link>
<AdditionalLibraryDirectories>$(SolutionDir)packages\detours\lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<!-- ── Release x64 ── -->
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>NDEBUG;TIMEMOCKER_HOOK_EXPORTS;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
</ClCompile>
<Link>
<AdditionalLibraryDirectories>$(SolutionDir)packages\detours\lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="dllmain.cpp" />
<ClCompile Include="exports.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="..\Shared\MockTimeInfo.h" />
<None Include="TimeMocker.Hook.def" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
</Project>
-311
View File
@@ -1,311 +0,0 @@
// =============================================================================
// TimeMocker.Hook — MS Detours-based time hooking DLL
//
// Injected into a target process by TimeMocker.Injector.
// Opens a named Memory-Mapped File created by the UI:
// Name: TimeMocker_<PID>
// Data: MockTimeInfo { LONGLONG DeltaTicks }
//
// Hooks 5 Win32 time APIs:
// kernel32!GetSystemTime
// kernel32!GetLocalTime
// kernel32!GetSystemTimeAsFileTime
// kernel32!GetSystemTimePreciseAsFileTime
// ntdll!NtQuerySystemTime
//
// The delta (DeltaTicks) is added to the real UTC FILETIME on every call.
// When DeltaTicks == 0 the real time passes through unchanged.
// =============================================================================
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <detours.h>
#include <cstdio>
#include <cstdint>
#include "../Shared/MockTimeInfo.h"
// ---------------------------------------------------------------------------
// Module-level state
// ---------------------------------------------------------------------------
static HANDLE g_hMapFile = nullptr;
static LPVOID g_pView = nullptr;
static wchar_t g_logPath[MAX_PATH];
// ---------------------------------------------------------------------------
// Logging (writes to %TEMP%\TimeMocker.Hook.log)
// ---------------------------------------------------------------------------
static void Log(const char* fmt, ...)
{
FILE* f = nullptr;
if (_wfopen_s(&f, g_logPath, L"a") == 0 && f)
{
SYSTEMTIME st;
GetLocalTime(&st); // NOTE: intentional real time call before hooks install
fprintf(f, "[%02d:%02d:%02d] ", st.wHour, st.wMinute, st.wSecond);
va_list va;
va_start(va, fmt);
vfprintf(f, fmt, va);
va_end(va);
fprintf(f, "\n");
fclose(f);
}
}
// ---------------------------------------------------------------------------
// Read the delta from shared memory (inline, hot path)
// ---------------------------------------------------------------------------
static inline LONGLONG ReadDeltaTicks()
{
if (!g_pView) return 0LL;
// Atomic-friendly: LONGLONG is 8-byte aligned, single read is atomic on x86/x64
return *reinterpret_cast<volatile LONGLONG*>(g_pView);
}
// ---------------------------------------------------------------------------
// FILETIME helpers
// ---------------------------------------------------------------------------
static const LONGLONG FILETIME_EPOCH_BIAS = 116444736000000000LL; // Jan 1, 1601 → Jan 1, 1970
// Convert a FILETIME (100-ns ticks since Jan 1, 1601 UTC) to a SYSTEMTIME UTC
static void FileTimeToSystemTimeLocal(LONGLONG ticks, SYSTEMTIME* pSt, bool localTime)
{
FILETIME ft;
ft.dwLowDateTime = static_cast<DWORD>(ticks & 0xFFFFFFFF);
ft.dwHighDateTime = static_cast<DWORD>(ticks >> 32);
if (localTime)
{
FILETIME localFt;
FileTimeToLocalFileTime(&ft, &localFt);
FileTimeToSystemTime(&localFt, pSt);
}
else
{
FileTimeToSystemTime(&ft, pSt);
}
}
// Get real UTC as 100-ns ticks (FILETIME ticks)
static inline LONGLONG GetRealUtcTicks()
{
FILETIME ft;
// Call the REAL GetSystemTimeAsFileTime (trampoline, set up after DetourAttach)
// We use a raw read of the real function pointer stored in the trampoline.
// To avoid recursion during hook installation we use a flag.
ULARGE_INTEGER ui;
GetSystemTimeAsFileTime(&ft); // will be redirected after hooks are live; see note below
ui.LowPart = ft.dwLowDateTime;
ui.HighPart = ft.dwHighDateTime;
return static_cast<LONGLONG>(ui.QuadPart);
}
// ---------------------------------------------------------------------------
// Original function pointers (Detours trampolines)
// ---------------------------------------------------------------------------
static void (WINAPI* Real_GetSystemTime)(LPSYSTEMTIME) = GetSystemTime;
static void (WINAPI* Real_GetLocalTime)(LPSYSTEMTIME) = GetLocalTime;
static void (WINAPI* Real_GetSystemTimeAsFileTime)(LPFILETIME) = GetSystemTimeAsFileTime;
static void (WINAPI* Real_GetSystemTimePreciseAsFileTime)(LPFILETIME) = GetSystemTimePreciseAsFileTime;
typedef NTSTATUS (NTAPI* NtQuerySystemTimeFn)(PLARGE_INTEGER SystemTime);
static NtQuerySystemTimeFn Real_NtQuerySystemTime = nullptr;
// ---------------------------------------------------------------------------
// Helper: get fake UTC ticks
// ---------------------------------------------------------------------------
static LONGLONG GetFakeUtcTicks()
{
// Get real time via the trampoline (not the hook)
FILETIME ft;
Real_GetSystemTimeAsFileTime(&ft);
ULARGE_INTEGER ui;
ui.LowPart = ft.dwLowDateTime;
ui.HighPart = ft.dwHighDateTime;
return static_cast<LONGLONG>(ui.QuadPart) + ReadDeltaTicks();
}
// ---------------------------------------------------------------------------
// Hook implementations
// ---------------------------------------------------------------------------
static void WINAPI Hook_GetSystemTime(LPSYSTEMTIME lpSystemTime)
{
if (!lpSystemTime) return;
LONGLONG ticks = GetFakeUtcTicks();
FileTimeToSystemTimeLocal(ticks, lpSystemTime, false);
}
static void WINAPI Hook_GetLocalTime(LPSYSTEMTIME lpLocalTime)
{
if (!lpLocalTime) return;
LONGLONG ticks = GetFakeUtcTicks();
FileTimeToSystemTimeLocal(ticks, lpLocalTime, true);
}
static void WINAPI Hook_GetSystemTimeAsFileTime(LPFILETIME lpFileTime)
{
if (!lpFileTime) return;
LONGLONG ticks = GetFakeUtcTicks();
lpFileTime->dwLowDateTime = static_cast<DWORD>(ticks & 0xFFFFFFFF);
lpFileTime->dwHighDateTime = static_cast<DWORD>(ticks >> 32);
}
static void WINAPI Hook_GetSystemTimePreciseAsFileTime(LPFILETIME lpFileTime)
{
// Same as GetSystemTimeAsFileTime — we can't improve precision beyond real time
Hook_GetSystemTimeAsFileTime(lpFileTime);
}
static NTSTATUS NTAPI Hook_NtQuerySystemTime(PLARGE_INTEGER SystemTime)
{
if (!SystemTime) return STATUS_ACCESS_VIOLATION;
SystemTime->QuadPart = GetFakeUtcTicks();
return STATUS_SUCCESS;
}
// ---------------------------------------------------------------------------
// Install / remove hooks
// ---------------------------------------------------------------------------
static bool InstallHooks()
{
// Resolve NtQuerySystemTime from ntdll
HMODULE hNtdll = GetModuleHandleW(L"ntdll.dll");
if (!hNtdll)
{
Log("ERROR: ntdll.dll not found");
return false;
}
Real_NtQuerySystemTime = reinterpret_cast<NtQuerySystemTimeFn>(
GetProcAddress(hNtdll, "NtQuerySystemTime"));
if (!Real_NtQuerySystemTime)
{
Log("ERROR: NtQuerySystemTime not found in ntdll");
return false;
}
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach(reinterpret_cast<PVOID*>(&Real_GetSystemTime),
reinterpret_cast<PVOID>(Hook_GetSystemTime));
DetourAttach(reinterpret_cast<PVOID*>(&Real_GetLocalTime),
reinterpret_cast<PVOID>(Hook_GetLocalTime));
DetourAttach(reinterpret_cast<PVOID*>(&Real_GetSystemTimeAsFileTime),
reinterpret_cast<PVOID>(Hook_GetSystemTimeAsFileTime));
DetourAttach(reinterpret_cast<PVOID*>(&Real_GetSystemTimePreciseAsFileTime),
reinterpret_cast<PVOID>(Hook_GetSystemTimePreciseAsFileTime));
DetourAttach(reinterpret_cast<PVOID*>(&Real_NtQuerySystemTime),
reinterpret_cast<PVOID>(Hook_NtQuerySystemTime));
LONG err = DetourTransactionCommit();
if (err != NO_ERROR)
{
Log("ERROR: DetourTransactionCommit failed: %ld", err);
return false;
}
Log("Hooks installed successfully (delta=%lld ticks)", ReadDeltaTicks());
return true;
}
static void RemoveHooks()
{
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourDetach(reinterpret_cast<PVOID*>(&Real_GetSystemTime),
reinterpret_cast<PVOID>(Hook_GetSystemTime));
DetourDetach(reinterpret_cast<PVOID*>(&Real_GetLocalTime),
reinterpret_cast<PVOID>(Hook_GetLocalTime));
DetourDetach(reinterpret_cast<PVOID*>(&Real_GetSystemTimeAsFileTime),
reinterpret_cast<PVOID>(Hook_GetSystemTimeAsFileTime));
DetourDetach(reinterpret_cast<PVOID*>(&Real_GetSystemTimePreciseAsFileTime),
reinterpret_cast<PVOID>(Hook_GetSystemTimePreciseAsFileTime));
if (Real_NtQuerySystemTime)
DetourDetach(reinterpret_cast<PVOID*>(&Real_NtQuerySystemTime),
reinterpret_cast<PVOID>(Hook_NtQuerySystemTime));
DetourTransactionCommit();
Log("Hooks removed");
}
// ---------------------------------------------------------------------------
// Open the shared memory created by the UI
// ---------------------------------------------------------------------------
static bool OpenSharedMemory(DWORD pid)
{
wchar_t mmfName[64];
GetMmfName(pid, mmfName, _countof(mmfName));
g_hMapFile = OpenFileMappingW(FILE_MAP_READ | FILE_MAP_WRITE, FALSE, mmfName);
if (!g_hMapFile)
{
Log("ERROR: OpenFileMapping('%ls') failed: %lu", mmfName, GetLastError());
return false;
}
g_pView = MapViewOfFile(g_hMapFile, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, MMF_SIZE);
if (!g_pView)
{
Log("ERROR: MapViewOfFile failed: %lu", GetLastError());
CloseHandle(g_hMapFile);
g_hMapFile = nullptr;
return false;
}
Log("Shared memory '%ls' opened (delta=%lld)", mmfName, ReadDeltaTicks());
return true;
}
static void CloseSharedMemory()
{
if (g_pView) { UnmapViewOfFile(g_pView); g_pView = nullptr; }
if (g_hMapFile) { CloseHandle(g_hMapFile); g_hMapFile = nullptr; }
}
// ---------------------------------------------------------------------------
// DllMain
// ---------------------------------------------------------------------------
BOOL WINAPI DllMain(HINSTANCE /*hInst*/, DWORD reason, LPVOID /*reserved*/)
{
if (DetourIsHelperProcess()) return TRUE;
switch (reason)
{
case DLL_PROCESS_ATTACH:
{
// Build log path: %TEMP%\TimeMocker.Hook.log
wchar_t tempDir[MAX_PATH];
GetTempPathW(MAX_PATH, tempDir);
swprintf_s(g_logPath, _countof(g_logPath), L"%lsTimeMocker.Hook.log", tempDir);
DWORD pid = GetCurrentProcessId();
Log("DLL_PROCESS_ATTACH pid=%lu", pid);
if (!OpenSharedMemory(pid))
{
// UI hasn't created the MMF yet — this is fatal for injection
return FALSE;
}
DisableThreadLibraryCalls(/*hInst*/ GetModuleHandleW(nullptr));
if (!InstallHooks())
{
CloseSharedMemory();
return FALSE;
}
break;
}
case DLL_PROCESS_DETACH:
RemoveHooks();
CloseSharedMemory();
Log("DLL_PROCESS_DETACH");
break;
}
return TRUE;
}
-7
View File
@@ -1,7 +0,0 @@
#include <Windows.h>
// Exported sentinel — lets the injector verify the DLL was built correctly
extern "C" __declspec(dllexport) DWORD TimeMockerHookVersion()
{
return 0x0001'0000; // v1.0
}
@@ -1,318 +0,0 @@
// =============================================================================
// TimeMocker.Injector — InjectionManager.cpp
//
// Uses the classic LoadLibrary remote-thread injection technique:
// 1. Open the target process with sufficient rights
// 2. Write the DLL path into the target's address space
// 3. Create a remote thread that calls LoadLibraryW
//
// For new processes, DetourCreateProcessWithDllEx() can alternatively be used
// (see TimeMocker.Injector.CLI for an example).
// =============================================================================
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <TlHelp32.h>
#include <Psapi.h>
#include <detours.h>
#include <cstdio>
#include <cassert>
#include <cwchar>
#include <memory>
#include <sstream>
#include "InjectionManager.h"
#pragma comment(lib, "Psapi.lib")
// ============================================================================
// SharedMemoryHandle
// ============================================================================
SharedMemoryHandle::SharedMemoryHandle(DWORD pid)
{
wchar_t buf[64];
GetMmfName(pid, buf, _countof(buf));
m_name = buf;
m_hMap = CreateFileMappingW(
INVALID_HANDLE_VALUE, nullptr,
PAGE_READWRITE, 0, MMF_SIZE,
m_name.c_str());
if (!m_hMap) return;
m_pView = MapViewOfFile(m_hMap, FILE_MAP_ALL_ACCESS, 0, 0, MMF_SIZE);
if (!m_pView)
{
CloseHandle(m_hMap);
m_hMap = nullptr;
}
else
{
// Zero-initialise (DeltaTicks = 0 → real time)
ZeroMemory(m_pView, MMF_SIZE);
}
}
SharedMemoryHandle::~SharedMemoryHandle()
{
if (m_pView) UnmapViewOfFile(m_pView);
if (m_hMap) CloseHandle(m_hMap);
}
void SharedMemoryHandle::Write(const MockTimeInfo& info)
{
if (!m_pView) return;
// Atomic write on aligned 8-byte address on x64/x86
InterlockedExchange64(reinterpret_cast<LONGLONG*>(m_pView), info.DeltaTicks);
}
// ============================================================================
// TimeUtil
// ============================================================================
LONGLONG TimeUtil::RealUtcTicks()
{
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
ULARGE_INTEGER ui;
ui.LowPart = ft.dwLowDateTime;
ui.HighPart = ft.dwHighDateTime;
return static_cast<LONGLONG>(ui.QuadPart);
}
LONGLONG TimeUtil::LocalSystemTimeToUtcTicks(const SYSTEMTIME& st)
{
FILETIME localFt, utcFt;
SystemTimeToFileTime(&st, &localFt);
LocalFileTimeToFileTime(&localFt, &utcFt);
ULARGE_INTEGER ui;
ui.LowPart = utcFt.dwLowDateTime;
ui.HighPart = utcFt.dwHighDateTime;
return static_cast<LONGLONG>(ui.QuadPart);
}
LONGLONG TimeUtil::ComputeDelta(LONGLONG fakeUtcTicks)
{
return fakeUtcTicks - RealUtcTicks();
}
// ============================================================================
// InjectionManager helpers
// ============================================================================
void InjectionManager::Log(const wchar_t* fmt, ...) const
{
if (!OnLog) return;
wchar_t buf[1024];
va_list va;
va_start(va, fmt);
vswprintf_s(buf, _countof(buf), fmt, va);
va_end(va);
OnLog(buf);
}
std::wstring InjectionManager::ResolveHookDll(bool x64) const
{
// Prefer explicit directory; fall back to the injector's own directory
std::wstring dir = m_hookDllDir;
if (dir.empty())
{
wchar_t exe[MAX_PATH];
GetModuleFileNameW(nullptr, exe, MAX_PATH);
wchar_t* slash = wcsrchr(exe, L'\\');
if (slash) { *(slash + 1) = L'\0'; dir = exe; }
}
return dir + (x64 ? L"TimeMocker.Hook.x64.dll" : L"TimeMocker.Hook.x86.dll");
}
bool InjectionManager::IsProcess64Bit(HANDLE hProcess)
{
BOOL wow64 = FALSE;
IsWow64Process(hProcess, &wow64);
// If we are 64-bit and the target is NOT WOW64, target is 64-bit
#ifdef _WIN64
return !wow64;
#else
return false; // 32-bit injector can only inject x86
#endif
}
// ============================================================================
// InjectionManager
// ============================================================================
InjectionManager::InjectionManager(const std::wstring& hookDllDir)
: m_hookDllDir(hookDllDir)
{
}
InjectionManager::~InjectionManager()
{
std::lock_guard<std::mutex> lk(m_mutex);
for (auto& kv : m_injected)
delete kv.second;
m_injected.clear();
}
bool InjectionManager::Inject(DWORD pid, LONGLONG fakeUtcTicks, std::wstring* pError)
{
std::lock_guard<std::mutex> lk(m_mutex);
if (m_injected.count(pid))
{
// Already injected — just update time
m_injected[pid]->Shm->Write({ TimeUtil::ComputeDelta(fakeUtcTicks) });
return true;
}
// ---- Open target process -----------------------------------------------
HANDLE hProcess = OpenProcess(
PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION |
PROCESS_VM_OPERATION | PROCESS_VM_WRITE | PROCESS_VM_READ,
FALSE, pid);
if (!hProcess)
{
std::wstring err = L"OpenProcess failed: " + std::to_wstring(GetLastError());
Log(L"[Inject] %ls", err.c_str());
if (pError) *pError = err;
return false;
}
bool is64 = IsProcess64Bit(hProcess);
std::wstring dllPath = ResolveHookDll(is64);
// ---- Create shared memory (must exist BEFORE DLL is loaded) -------------
auto* entry = new InjectedProcessInfo();
entry->Pid = pid;
entry->Shm = new SharedMemoryHandle(pid);
if (!entry->Shm->IsValid())
{
delete entry;
CloseHandle(hProcess);
std::wstring err = L"CreateFileMapping failed: " + std::to_wstring(GetLastError());
Log(L"[Inject] %ls", err.c_str());
if (pError) *pError = err;
return false;
}
// Write initial delta
entry->Shm->Write({ TimeUtil::ComputeDelta(fakeUtcTicks) });
// ---- Collect process name / path ----------------------------------------
wchar_t pathBuf[MAX_PATH] = {};
DWORD pathLen = MAX_PATH;
QueryFullProcessImageNameW(hProcess, 0, pathBuf, &pathLen);
entry->ProcessPath = pathBuf;
const wchar_t* slash = wcsrchr(pathBuf, L'\\');
entry->ProcessName = slash ? (slash + 1) : pathBuf;
// ---- Inject the DLL via LoadLibraryW remote thread ----------------------
SIZE_T dllPathBytes = (dllPath.size() + 1) * sizeof(wchar_t);
LPVOID remoteStr = VirtualAllocEx(hProcess, nullptr, dllPathBytes,
MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
if (!remoteStr)
{
delete entry;
CloseHandle(hProcess);
std::wstring err = L"VirtualAllocEx failed: " + std::to_wstring(GetLastError());
Log(L"[Inject] %ls", err.c_str());
if (pError) *pError = err;
return false;
}
WriteProcessMemory(hProcess, remoteStr, dllPath.c_str(), dllPathBytes, nullptr);
HMODULE hKernel = GetModuleHandleW(L"kernel32.dll");
FARPROC pLoadLib = GetProcAddress(hKernel, "LoadLibraryW");
HANDLE hThread = CreateRemoteThread(
hProcess, nullptr, 0,
reinterpret_cast<LPTHREAD_START_ROUTINE>(pLoadLib),
remoteStr, 0, nullptr);
if (!hThread)
{
VirtualFreeEx(hProcess, remoteStr, 0, MEM_RELEASE);
delete entry;
CloseHandle(hProcess);
std::wstring err = L"CreateRemoteThread failed: " + std::to_wstring(GetLastError());
Log(L"[Inject] %ls", err.c_str());
if (pError) *pError = err;
return false;
}
// Wait for LoadLibraryW to return (give it 5 seconds)
WaitForSingleObject(hThread, 5000);
// Check the return value (hModule loaded)
DWORD exitCode = 0;
GetExitCodeThread(hThread, &exitCode);
CloseHandle(hThread);
VirtualFreeEx(hProcess, remoteStr, 0, MEM_RELEASE);
CloseHandle(hProcess);
if (!exitCode)
{
delete entry;
std::wstring err = L"LoadLibraryW in target returned NULL — DLL load failed";
Log(L"[Inject] %ls", err.c_str());
if (pError) *pError = err;
return false;
}
m_injected[pid] = entry;
Log(L"[Inject] pid=%lu '%ls' injected ('%ls')", pid, entry->ProcessName.c_str(), dllPath.c_str());
return true;
}
bool InjectionManager::SetFakeTime(DWORD pid, LONGLONG fakeUtcTicks)
{
std::lock_guard<std::mutex> lk(m_mutex);
auto it = m_injected.find(pid);
if (it == m_injected.end()) return false;
it->second->Shm->Write({ TimeUtil::ComputeDelta(fakeUtcTicks) });
return true;
}
void InjectionManager::SetFakeTimeAll(LONGLONG fakeUtcTicks)
{
std::lock_guard<std::mutex> lk(m_mutex);
LONGLONG delta = TimeUtil::ComputeDelta(fakeUtcTicks);
for (auto& kv : m_injected)
kv.second->Shm->Write({ delta });
}
bool InjectionManager::Eject(DWORD pid)
{
std::lock_guard<std::mutex> lk(m_mutex);
auto it = m_injected.find(pid);
if (it == m_injected.end()) return false;
// Zero out the delta so the hook passes through real time before we unmap
it->second->Shm->Write({ 0LL });
Sleep(50); // let any in-flight hook calls complete
delete it->second;
m_injected.erase(it);
Log(L"[Eject] pid=%lu ejected (shared memory closed)", pid);
return true;
}
bool InjectionManager::IsInjected(DWORD pid) const
{
std::lock_guard<std::mutex> lk(m_mutex);
return m_injected.count(pid) != 0;
}
void InjectionManager::ForEach(std::function<void(const InjectedProcessInfo&)> fn) const
{
std::lock_guard<std::mutex> lk(m_mutex);
for (auto& kv : m_injected)
fn(*kv.second);
}
-110
View File
@@ -1,110 +0,0 @@
#pragma once
// =============================================================================
// TimeMocker.Injector — inject/eject Hook DLL + manage shared memory
//
// Usage:
// InjectionManager mgr;
// mgr.Inject(pid, fakeTimeUtc); // inject and set time
// mgr.SetFakeTime(pid, fakeUtc); // update time while injected
// mgr.Eject(pid); // detach hook
// =============================================================================
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <string>
#include <unordered_map>
#include <functional>
#include <mutex>
#include "../Shared/MockTimeInfo.h"
// ---------------------------------------------------------------------------
// SharedMemoryHandle
// Wraps one named MMF per injected process.
// ---------------------------------------------------------------------------
class SharedMemoryHandle
{
public:
explicit SharedMemoryHandle(DWORD pid);
~SharedMemoryHandle();
SharedMemoryHandle(const SharedMemoryHandle&) = delete;
SharedMemoryHandle& operator=(const SharedMemoryHandle&) = delete;
bool IsValid() const { return m_pView != nullptr; }
void Write(const MockTimeInfo& info);
const std::wstring& Name() const { return m_name; }
private:
std::wstring m_name;
HANDLE m_hMap = nullptr;
LPVOID m_pView = nullptr;
};
// ---------------------------------------------------------------------------
// InjectedProcessInfo
// ---------------------------------------------------------------------------
struct InjectedProcessInfo
{
DWORD Pid = 0;
std::wstring ProcessName;
std::wstring ProcessPath;
SharedMemoryHandle* Shm = nullptr;
};
// ---------------------------------------------------------------------------
// InjectionManager
// ---------------------------------------------------------------------------
class InjectionManager
{
public:
explicit InjectionManager(const std::wstring& hookDllDir = L"");
~InjectionManager();
// Inject hook DLL into process and set initial fake time (UTC FILETIME ticks)
bool Inject(DWORD pid, LONGLONG fakeUtcTicks, std::wstring* pError = nullptr);
// Update fake time for an already-injected process
bool SetFakeTime(DWORD pid, LONGLONG fakeUtcTicks);
// Set fake time for all injected processes
void SetFakeTimeAll(LONGLONG fakeUtcTicks);
// Remove hook from process (best-effort — DLL stays loaded but hooks removed on next call)
bool Eject(DWORD pid);
bool IsInjected(DWORD pid) const;
// Callback for log messages
std::function<void(const std::wstring&)> OnLog;
// Iterate injected processes
void ForEach(std::function<void(const InjectedProcessInfo&)> fn) const;
private:
std::wstring ResolveHookDll(bool x64) const;
static bool IsProcess64Bit(HANDLE hProcess);
static LONGLONG RealUtcTicks();
static LONGLONG ToFiletimeDelta(LONGLONG fakeUtcTicks);
void Log(const wchar_t* fmt, ...) const;
mutable std::mutex m_mutex;
std::unordered_map<DWORD, InjectedProcessInfo*> m_injected;
std::wstring m_hookDllDir; // directory where Hook DLLs live
};
// ---------------------------------------------------------------------------
// Utility: convert a DateTime-style local SYSTEMTIME to UTC FILETIME ticks
// (helper for callers that work with wall-clock time)
// ---------------------------------------------------------------------------
namespace TimeUtil
{
// Get the current real UTC as FILETIME ticks (100-ns units since Jan 1, 1601)
LONGLONG RealUtcTicks();
// Convert a local SYSTEMTIME to UTC FILETIME ticks
LONGLONG LocalSystemTimeToUtcTicks(const SYSTEMTIME& st);
// Build a DeltaTicks value: how many ticks ahead/behind of real time
LONGLONG ComputeDelta(LONGLONG fakeUtcTicks);
}
-188
View File
@@ -1,188 +0,0 @@
#pragma once
// =============================================================================
// ProcessWatcher — polls running processes and auto-injects those matching
// a set of glob/regex patterns.
// =============================================================================
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <TlHelp32.h>
#include <string>
#include <vector>
#include <unordered_set>
#include <functional>
#include <thread>
#include <atomic>
#include <mutex>
#include <regex>
#include <algorithm>
#include "InjectionManager.h"
struct PatternRule
{
std::wstring Pattern;
bool UseRegex = false;
bool Enabled = true;
bool IsMatch(const std::wstring& path) const
{
if (path.empty()) return false;
std::wstring regexStr;
if (UseRegex)
{
regexStr = Pattern;
}
else
{
regexStr = L"^";
for (wchar_t c : Pattern)
{
switch (c)
{
case L'*': regexStr += L".*"; break;
case L'?': regexStr += L'.'; break;
case L'.': regexStr += L"\\."; break;
case L'\\': regexStr += L"\\\\"; break;
default: regexStr += c; break;
}
}
regexStr += L'$';
}
try
{
std::wregex re(regexStr, std::regex_constants::icase);
return std::regex_match(path, re) || std::regex_search(path, re);
}
catch (...) { return false; }
}
};
class ProcessWatcher
{
public:
explicit ProcessWatcher(InjectionManager& mgr)
: m_mgr(mgr)
{
m_fakeUtcTicks = TimeUtil::RealUtcTicks();
}
~ProcessWatcher() { Stop(); }
void AddRule(PatternRule rule)
{
std::lock_guard<std::mutex> lk(m_rulesMutex);
m_rules.push_back(std::move(rule));
}
void RemoveRule(const std::wstring& pattern)
{
std::lock_guard<std::mutex> lk(m_rulesMutex);
m_rules.erase(
std::remove_if(m_rules.begin(), m_rules.end(),
[&](const PatternRule& r){ return r.Pattern == pattern; }),
m_rules.end());
}
void ClearRules()
{
std::lock_guard<std::mutex> lk(m_rulesMutex);
m_rules.clear();
}
void SetFakeUtcTicks(LONGLONG ticks) { m_fakeUtcTicks.store(ticks); }
void Start(DWORD pollIntervalMs = 1500)
{
if (m_running.exchange(true)) return;
m_thread = std::thread([this, pollIntervalMs]()
{
while (m_running.load())
{
Scan();
for (DWORD e = 0; m_running.load() && e < pollIntervalMs; e += 100)
Sleep(100);
}
});
}
void Stop()
{
if (!m_running.exchange(false)) return;
if (m_thread.joinable()) m_thread.join();
}
// Callbacks
std::function<void(DWORD pid, const std::wstring& name, const std::wstring& path)> OnAutoInjected;
std::function<void(const std::wstring&)> OnLog;
private:
void Scan()
{
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snap == INVALID_HANDLE_VALUE) return;
PROCESSENTRY32W pe; pe.dwSize = sizeof(pe);
if (!Process32FirstW(snap, &pe)) { CloseHandle(snap); return; }
std::lock_guard<std::mutex> ruleLk(m_rulesMutex);
do
{
DWORD pid = pe.th32ProcessID;
{ std::lock_guard<std::mutex> lk(m_seenMutex); if (m_seenPids.count(pid)) continue; }
if (m_mgr.IsInjected(pid)) continue;
HANDLE hProc = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
std::wstring fullPath;
if (hProc)
{
wchar_t buf[MAX_PATH] = {}; DWORD len = MAX_PATH;
QueryFullProcessImageNameW(hProc, 0, buf, &len);
fullPath = buf;
CloseHandle(hProc);
}
std::wstring procName = pe.szExeFile;
for (auto& rule : m_rules)
{
if (!rule.Enabled) continue;
if (!rule.IsMatch(fullPath) && !rule.IsMatch(procName)) continue;
{ std::lock_guard<std::mutex> lk(m_seenMutex); m_seenPids.insert(pid); }
std::wstring err;
if (m_mgr.Inject(pid, m_fakeUtcTicks.load(), &err))
{
DoLog(L"[AutoInject] '%ls' → [%lu] %ls", rule.Pattern.c_str(), pid, procName.c_str());
if (OnAutoInjected) OnAutoInjected(pid, procName, fullPath);
}
else
{
DoLog(L"[AutoInject] FAIL [%lu] %ls: %ls", pid, procName.c_str(), err.c_str());
}
break;
}
} while (Process32NextW(snap, &pe));
CloseHandle(snap);
}
void DoLog(const wchar_t* fmt, ...) const
{
if (!OnLog) return;
wchar_t buf[1024]; va_list va; va_start(va, fmt);
vswprintf_s(buf, _countof(buf), fmt, va); va_end(va);
OnLog(buf);
}
InjectionManager& m_mgr;
mutable std::mutex m_rulesMutex;
std::vector<PatternRule> m_rules;
std::mutex m_seenMutex;
std::unordered_set<DWORD> m_seenPids;
std::atomic<LONGLONG> m_fakeUtcTicks{ 0 };
std::atomic<bool> m_running{ false };
std::thread m_thread;
};
@@ -1,71 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32"> <Configuration>Debug</Configuration> <Platform>Win32</Platform> </ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32"><Configuration>Release</Configuration><Platform>Win32</Platform> </ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64"> <Configuration>Debug</Configuration> <Platform>x64</Platform> </ProjectConfiguration>
<ProjectConfiguration Include="Release|x64"> <Configuration>Release</Configuration><Platform>x64</Platform> </ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{B2222222-2222-2222-2222-222222222222}</ProjectGuid>
<RootNamespace>TimeMockerInjector</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType><UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset><CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType><UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset><WholeProgramOptimization>true</WholeProgramOptimization><CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType><UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset><CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>StaticLibrary</ConfigurationType><UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset><WholeProgramOptimization>true</WholeProgramOptimization><CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ItemDefinitionGroup>
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpp17</LanguageStandard>
<AdditionalIncludeDirectories>$(SolutionDir)packages\detours\include;$(SolutionDir)Shared;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32_LEAN_AND_MEAN;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile><Optimization>Disabled</Optimization><RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary></ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile><Optimization>MaxSpeed</Optimization><RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary></ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile><Optimization>Disabled</Optimization><RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary></ClCompile>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile><Optimization>MaxSpeed</Optimization><RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary></ClCompile>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="InjectionManager.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="InjectionManager.h" />
<ClInclude Include="ProcessWatcher.h" />
<ClInclude Include="..\Shared\MockTimeInfo.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
</Project>
-64
View File
@@ -1,64 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|x64"> <Configuration>Debug</Configuration> <Platform>x64</Platform> </ProjectConfiguration>
<ProjectConfiguration Include="Release|x64"><Configuration>Release</Configuration><Platform>x64</Platform> </ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<ProjectGuid>{C3333333-3333-3333-3333-333333333333}</ProjectGuid>
<RootNamespace>TimeMockerUI</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType><UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset><CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType><UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset><WholeProgramOptimization>true</WholeProgramOptimization><CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ItemDefinitionGroup>
<ClCompile>
<WarningLevel>Level3</WarningLevel><SDLCheck>true</SDLCheck>
<ConformanceMode>true</ConformanceMode><LanguageStandard>stdcpp17</LanguageStandard>
<AdditionalIncludeDirectories>$(ProjectDir)imgui;$(SolutionDir)packages\detours\include;$(SolutionDir)Shared;%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
<PreprocessorDefinitions>WIN32_LEAN_AND_MEAN;NOMINMAX;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<AdditionalDependencies>d3d11.lib;dxgi.lib;d3dcompiler.lib;detours.lib;Psapi.lib;%(AdditionalDependencies)</AdditionalDependencies>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile><Optimization>Disabled</Optimization><RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary></ClCompile>
<Link><AdditionalLibraryDirectories>$(SolutionDir)packages\detours\lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories></Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile><Optimization>MaxSpeed</Optimization><RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary></ClCompile>
<Link>
<AdditionalLibraryDirectories>$(SolutionDir)packages\detours\lib\x64;%(AdditionalLibraryDirectories)</AdditionalLibraryDirectories>
<EnableCOMDATFolding>true</EnableCOMDATFolding><OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="main.cpp" />
<ClCompile Include="..\TimeMocker.Injector\InjectionManager.cpp" />
<ClCompile Include="imgui\imgui.cpp" />
<ClCompile Include="imgui\imgui_draw.cpp" />
<ClCompile Include="imgui\imgui_tables.cpp" />
<ClCompile Include="imgui\imgui_widgets.cpp" />
<ClCompile Include="imgui\imgui_impl_win32.cpp" />
<ClCompile Include="imgui\imgui_impl_dx11.cpp" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="imgui\imgui.h" />
<ClInclude Include="imgui\imgui_impl_win32.h" />
<ClInclude Include="imgui\imgui_impl_dx11.h" />
<ClInclude Include="..\TimeMocker.Injector\InjectionManager.h" />
<ClInclude Include="..\TimeMocker.Injector\ProcessWatcher.h" />
<ClInclude Include="..\Shared\MockTimeInfo.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
</Project>
-22
View File
@@ -1,22 +0,0 @@
# imgui/
This directory must contain Dear ImGui source files.
Run `scripts/setup.ps1` to download them automatically, or place them here manually
from https://github.com/ocornut/imgui (latest release).
Required files:
imgui.h
imgui.cpp
imgui_internal.h
imgui_draw.cpp
imgui_tables.cpp
imgui_widgets.cpp
imgui_impl_win32.h
imgui_impl_win32.cpp
imgui_impl_dx11.h
imgui_impl_dx11.cpp
imconfig.h
imstb_rectpack.h
imstb_textedit.h
imstb_truetype.h
-639
View File
@@ -1,639 +0,0 @@
// =============================================================================
// TimeMocker.UI — ImGui + DirectX 11 frontend
// =============================================================================
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#include <Windows.h>
#include <TlHelp32.h>
#include <Psapi.h>
#include <d3d11.h>
#include <shellapi.h>
#include "imgui/imgui.h"
#include "imgui/imgui_impl_win32.h"
#include "imgui/imgui_impl_dx11.h"
#include <string>
#include <vector>
#include <algorithm>
#include <mutex>
#include <deque>
#include <cstdio>
#include "../TimeMocker.Injector/InjectionManager.h"
#include "../TimeMocker.Injector/ProcessWatcher.h"
#pragma comment(lib, "d3d11.lib")
#pragma comment(lib, "Psapi.lib")
// ─────────────────────────────────────────────────────────────────────────────
// Forward declarations
// ─────────────────────────────────────────────────────────────────────────────
extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND, UINT, WPARAM, LPARAM);
static bool CreateDeviceD3D(HWND);
static void CleanupDeviceD3D();
static void CreateRenderTarget();
static void CleanupRenderTarget();
LRESULT WINAPI WndProc(HWND, UINT, WPARAM, LPARAM);
// ─────────────────────────────────────────────────────────────────────────────
// D3D globals
// ─────────────────────────────────────────────────────────────────────────────
static ID3D11Device* g_pd3dDevice = nullptr;
static ID3D11DeviceContext* g_pd3dDeviceContext = nullptr;
static IDXGISwapChain* g_pSwapChain = nullptr;
static ID3D11RenderTargetView* g_mainRenderTargetView = nullptr;
// ─────────────────────────────────────────────────────────────────────────────
// App state
// ─────────────────────────────────────────────────────────────────────────────
struct ProcessRow { DWORD pid; std::string name, path; bool injected; };
struct RuleRow { std::string pattern; bool useRegex, enabled; };
struct LogEntry { std::string ts, msg; ImVec4 color; };
static InjectionManager* g_injMgr = nullptr;
static ProcessWatcher* g_watcher = nullptr;
static std::vector<ProcessRow> g_procRows;
static char g_procFilter[128] = {};
static std::vector<RuleRow> g_rules;
static std::deque<LogEntry> g_log;
static std::mutex g_logMutex;
static bool g_logScrollToBottom = false;
static int g_fakeYear = 2024, g_fakeMon = 1, g_fakeDay = 1;
static int g_fakeHour = 0, g_fakeMin = 0, g_fakeSec = 0;
static LONGLONG g_fakeUtcTicks = 0;
static bool g_timeApplied = false;
static char g_newPattern[256] = {};
static bool g_newUseRegex = false;
// ─────────────────────────────────────────────────────────────────────────────
// Palette — terminal green on near-black
// ─────────────────────────────────────────────────────────────────────────────
namespace Pal {
const ImVec4 Bg = { 0.07f, 0.08f, 0.09f, 1.f };
const ImVec4 Panel = { 0.10f, 0.11f, 0.13f, 1.f };
const ImVec4 Border = { 0.18f, 0.22f, 0.25f, 1.f };
const ImVec4 Accent = { 0.18f, 0.78f, 0.44f, 1.f };
const ImVec4 AccentDim = { 0.10f, 0.48f, 0.26f, 1.f };
const ImVec4 AccentHot = { 0.30f, 1.00f, 0.60f, 1.f };
const ImVec4 Danger = { 0.82f, 0.22f, 0.22f, 1.f };
const ImVec4 DangerHot = { 1.00f, 0.32f, 0.32f, 1.f };
const ImVec4 Warning = { 0.92f, 0.68f, 0.08f, 1.f };
const ImVec4 Muted = { 0.36f, 0.42f, 0.46f, 1.f };
const ImVec4 Text = { 0.80f, 0.88f, 0.82f, 1.f };
const ImVec4 TextDim = { 0.46f, 0.52f, 0.48f, 1.f };
const ImVec4 LogInfo = { 0.50f, 0.88f, 0.62f, 1.f };
const ImVec4 LogWarn = { 0.92f, 0.76f, 0.28f, 1.f };
const ImVec4 LogErr = { 0.96f, 0.38f, 0.38f, 1.f };
}
// ─────────────────────────────────────────────────────────────────────────────
// Helpers
// ─────────────────────────────────────────────────────────────────────────────
static void AppLog(const std::string& msg, ImVec4 color = Pal::LogInfo)
{
SYSTEMTIME st; GetLocalTime(&st);
char ts[12]; sprintf_s(ts, "%02d:%02d:%02d", st.wHour, st.wMinute, st.wSecond);
std::lock_guard<std::mutex> lk(g_logMutex);
g_log.push_back({ ts, msg, color });
if (g_log.size() > 512) g_log.pop_front();
g_logScrollToBottom = true;
}
static void WLog(const std::wstring& w)
{
char b[1024]; WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, b, sizeof(b), nullptr, nullptr);
AppLog(b);
}
static std::string FormatDelta(LONGLONG d)
{
if (!d) return "+0s";
bool neg = d < 0; LONGLONG a = neg ? -d : d;
LONGLONG s = a/10000000LL, m=s/60; s%=60;
LONGLONG h = m/60; m%=60; LONGLONG dy=h/24; h%=24;
char buf[64];
if (dy) sprintf_s(buf,"%s%lldd%02lldh%02lldm%02llds",neg?"-":"+",dy,h,m,s);
else if (h) sprintf_s(buf,"%s%lldh%02lldm%02llds",neg?"-":"+",h,m,s);
else if (m) sprintf_s(buf,"%s%lldm%02llds",neg?"-":"+",m,s);
else sprintf_s(buf,"%s%llds",neg?"-":"+",s);
return buf;
}
static void RefreshProcessList()
{
g_procRows.clear();
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snap == INVALID_HANDLE_VALUE) return;
PROCESSENTRY32W pe; pe.dwSize = sizeof(pe);
if (!Process32FirstW(snap, &pe)) { CloseHandle(snap); return; }
do {
HANDLE h = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pe.th32ProcessID);
if (!h) continue;
wchar_t pw[MAX_PATH]={}; DWORD l=MAX_PATH; QueryFullProcessImageNameW(h,0,pw,&l); CloseHandle(h);
char n[256]={}, p[512]={};
WideCharToMultiByte(CP_UTF8,0,pe.szExeFile,-1,n,sizeof(n),nullptr,nullptr);
WideCharToMultiByte(CP_UTF8,0,pw,-1,p,sizeof(p),nullptr,nullptr);
g_procRows.push_back({pe.th32ProcessID, n, p, g_injMgr->IsInjected(pe.th32ProcessID)});
} while(Process32NextW(snap,&pe));
CloseHandle(snap);
std::sort(g_procRows.begin(),g_procRows.end(),[](auto&a,auto&b){return _stricmp(a.name.c_str(),b.name.c_str())<0;});
}
static void ApplyTime()
{
SYSTEMTIME st={};
st.wYear=(WORD)g_fakeYear; st.wMonth=(WORD)g_fakeMon; st.wDay=(WORD)g_fakeDay;
st.wHour=(WORD)g_fakeHour; st.wMinute=(WORD)g_fakeMin; st.wSecond=(WORD)g_fakeSec;
g_fakeUtcTicks = TimeUtil::LocalSystemTimeToUtcTicks(st);
g_injMgr->SetFakeTimeAll(g_fakeUtcTicks);
g_watcher->SetFakeUtcTicks(g_fakeUtcTicks);
g_timeApplied = true;
AppLog("Time applied delta=" + FormatDelta(TimeUtil::ComputeDelta(g_fakeUtcTicks)));
}
static void ResetTimeToNow()
{
SYSTEMTIME st; GetLocalTime(&st);
g_fakeYear=st.wYear; g_fakeMon=st.wMonth; g_fakeDay=st.wDay;
g_fakeHour=st.wHour; g_fakeMin=st.wMinute; g_fakeSec=st.wSecond;
g_fakeUtcTicks = TimeUtil::RealUtcTicks();
g_injMgr->SetFakeTimeAll(g_fakeUtcTicks);
g_watcher->SetFakeUtcTicks(g_fakeUtcTicks);
g_timeApplied = false;
AppLog("Time reset to real time", Pal::LogWarn);
}
// ─────────────────────────────────────────────────────────────────────────────
// ImGui style
// ─────────────────────────────────────────────────────────────────────────────
static void ApplyTheme()
{
ImGuiStyle& s = ImGui::GetStyle();
s.WindowRounding=6; s.ChildRounding=4; s.FrameRounding=4;
s.PopupRounding=4; s.TabRounding=5; s.GrabRounding=4;
s.WindowBorderSize=1; s.FrameBorderSize=1;
s.ItemSpacing={8,5}; s.FramePadding={8,4};
s.WindowPadding={12,10}; s.ScrollbarSize=10;
ImVec4* c = s.Colors;
c[ImGuiCol_WindowBg] = Pal::Bg;
c[ImGuiCol_ChildBg] = Pal::Panel;
c[ImGuiCol_PopupBg] = {0.09f,0.10f,0.12f,0.98f};
c[ImGuiCol_Border] = Pal::Border;
c[ImGuiCol_FrameBg] = {0.13f,0.15f,0.17f,1.f};
c[ImGuiCol_FrameBgHovered] = {0.17f,0.20f,0.23f,1.f};
c[ImGuiCol_FrameBgActive] = {0.10f,0.32f,0.20f,1.f};
c[ImGuiCol_TitleBg] = {0.07f,0.08f,0.09f,1.f};
c[ImGuiCol_TitleBgActive] = {0.07f,0.20f,0.13f,1.f};
c[ImGuiCol_ScrollbarBg] = {0.07f,0.08f,0.09f,1.f};
c[ImGuiCol_ScrollbarGrab] = Pal::AccentDim;
c[ImGuiCol_ScrollbarGrabHovered] = Pal::Accent;
c[ImGuiCol_ScrollbarGrabActive] = Pal::AccentHot;
c[ImGuiCol_CheckMark] = Pal::AccentHot;
c[ImGuiCol_SliderGrab] = Pal::Accent;
c[ImGuiCol_SliderGrabActive] = Pal::AccentHot;
c[ImGuiCol_Button] = {0.11f,0.28f,0.18f,1.f};
c[ImGuiCol_ButtonHovered] = {0.15f,0.40f,0.24f,1.f};
c[ImGuiCol_ButtonActive] = {0.18f,0.55f,0.30f,1.f};
c[ImGuiCol_Header] = {0.09f,0.26f,0.16f,1.f};
c[ImGuiCol_HeaderHovered] = {0.12f,0.34f,0.21f,1.f};
c[ImGuiCol_HeaderActive] = {0.14f,0.42f,0.26f,1.f};
c[ImGuiCol_Separator] = Pal::Border;
c[ImGuiCol_Tab] = {0.09f,0.18f,0.12f,1.f};
c[ImGuiCol_TabHovered] = {0.13f,0.36f,0.22f,1.f};
c[ImGuiCol_TabActive] = {0.12f,0.42f,0.26f,1.f};
c[ImGuiCol_TabUnfocused] = {0.07f,0.12f,0.09f,1.f};
c[ImGuiCol_TabUnfocusedActive] = {0.09f,0.24f,0.15f,1.f};
c[ImGuiCol_Text] = Pal::Text;
c[ImGuiCol_TextDisabled] = Pal::Muted;
c[ImGuiCol_TableHeaderBg] = {0.09f,0.20f,0.13f,1.f};
c[ImGuiCol_TableBorderStrong] = Pal::Border;
c[ImGuiCol_TableBorderLight] = {0.14f,0.16f,0.18f,1.f};
c[ImGuiCol_TableRowBg] = {0.10f,0.11f,0.13f,1.f};
c[ImGuiCol_TableRowBgAlt] = {0.12f,0.13f,0.15f,1.f};
c[ImGuiCol_NavHighlight] = Pal::Accent;
}
// ─────────────────────────────────────────────────────────────────────────────
// UI panels
// ─────────────────────────────────────────────────────────────────────────────
static void RenderHeader()
{
ImGui::PushStyleColor(ImGuiCol_ChildBg, ImVec4(0.08f,0.16f,0.11f,1.f));
ImGui::BeginChild("##hdr", ImVec2(0,46), false);
SYSTEMTIME real; GetLocalTime(&real);
char rb[40]; sprintf_s(rb,"REAL %04d-%02d-%02d %02d:%02d:%02d",
real.wYear,real.wMonth,real.wDay,real.wHour,real.wMinute,real.wSecond);
ImGui::SetCursorPos({12,13});
ImGui::TextColored(Pal::Muted, "%s", rb);
// Compute current fake local time (flowing)
LONGLONG curFake = (g_fakeUtcTicks==0)
? TimeUtil::RealUtcTicks()
: TimeUtil::RealUtcTicks() + TimeUtil::ComputeDelta(g_fakeUtcTicks);
FILETIME ft; ULARGE_INTEGER ui; ui.QuadPart=(ULONGLONG)curFake;
ft.dwLowDateTime=ui.LowPart; ft.dwHighDateTime=ui.HighPart;
FILETIME lft; FileTimeToLocalFileTime(&ft,&lft);
SYSTEMTIME fk; FileTimeToSystemTime(&lft,&fk);
char fb[48]; sprintf_s(fb,"MOCK %04d-%02d-%02d %02d:%02d:%02d",
fk.wYear,fk.wMonth,fk.wDay,fk.wHour,fk.wMinute,fk.wSecond);
float tw=ImGui::CalcTextSize(fb).x, ww=ImGui::GetWindowWidth();
ImGui::SetCursorPos({(ww-tw)*.5f,13});
ImGui::TextColored(g_timeApplied ? Pal::AccentHot : Pal::Text, "%s", fb);
LONGLONG delta=(g_fakeUtcTicks==0)?0:TimeUtil::ComputeDelta(g_fakeUtcTicks);
std::string ds=FormatDelta(delta);
float dw2=ImGui::CalcTextSize(ds.c_str()).x;
ImGui::SetCursorPos({ww-dw2-12,13});
ImGui::TextColored(delta==0?Pal::Muted:Pal::Warning,"%s",ds.c_str());
ImGui::EndChild();
ImGui::PopStyleColor();
}
static void RenderTimePanel()
{
ImGui::PushStyleColor(ImGuiCol_ChildBg,ImVec4(0.09f,0.10f,0.12f,1.f));
ImGui::BeginChild("##tp", ImVec2(0,68), true);
ImGui::TextColored(Pal::AccentDim,"SET FAKE TIME"); ImGui::SameLine(0,18);
auto IntW=[](const char* id, int* v, int w){
ImGui::PushItemWidth(w); ImGui::InputInt(id,v,0,0); ImGui::PopItemWidth();
};
IntW("##yr",&g_fakeYear,54); ImGui::SameLine(0,3);
ImGui::TextColored(Pal::Muted,"-"); ImGui::SameLine(0,3);
IntW("##mo",&g_fakeMon,32); ImGui::SameLine(0,3);
ImGui::TextColored(Pal::Muted,"-"); ImGui::SameLine(0,3);
IntW("##dy",&g_fakeDay,32); ImGui::SameLine(0,14);
IntW("##hr",&g_fakeHour,32); ImGui::SameLine(0,3);
ImGui::TextColored(Pal::Muted,":"); ImGui::SameLine(0,3);
IntW("##mn",&g_fakeMin,32); ImGui::SameLine(0,3);
ImGui::TextColored(Pal::Muted,":"); ImGui::SameLine(0,3);
IntW("##sc",&g_fakeSec,32);
g_fakeMon =std::clamp(g_fakeMon,1,12); g_fakeDay =std::clamp(g_fakeDay,1,31);
g_fakeHour=std::clamp(g_fakeHour,0,23);g_fakeMin =std::clamp(g_fakeMin,0,59);
g_fakeSec =std::clamp(g_fakeSec,0,59);
ImGui::SameLine(0,16);
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.08f,0.40f,0.22f,1.f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered,ImVec4(0.12f,0.54f,0.30f,1.f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.16f,0.66f,0.36f,1.f));
if(ImGui::Button(" SET ",{54,0})) ApplyTime();
ImGui::PopStyleColor(3);
ImGui::SameLine(0,6);
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.14f,0.16f,0.18f,1.f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered,ImVec4(0.20f,0.23f,0.26f,1.f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.10f,0.32f,0.20f,1.f));
if(ImGui::Button(" NOW ",{54,0})) ResetTimeToNow();
ImGui::PopStyleColor(3);
ImGui::EndChild();
ImGui::PopStyleColor();
}
static void RenderProcessTab()
{
ImGui::SetNextItemWidth(220);
ImGui::InputTextWithHint("##pf","Search processes...",g_procFilter,sizeof(g_procFilter));
ImGui::SameLine();
if(ImGui::Button(" Refresh ")) RefreshProcessList();
int ic=0; for(auto&r:g_procRows) if(r.injected) ic++;
if(ic>0){
ImGui::SameLine();
char b[32]; sprintf_s(b," %d injected ",ic);
ImGui::PushStyleColor(ImGuiCol_Button,ImVec4(0.08f,0.28f,0.16f,1.f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered,ImVec4(0.08f,0.28f,0.16f,1.f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive,ImVec4(0.08f,0.28f,0.16f,1.f));
ImGui::Button(b); ImGui::PopStyleColor(3);
}
ImGui::Spacing();
ImGuiTableFlags tf = ImGuiTableFlags_Borders|ImGuiTableFlags_RowBg|
ImGuiTableFlags_ScrollY|ImGuiTableFlags_SizingFixedFit|
ImGuiTableFlags_Resizable;
if(ImGui::BeginTable("##pt",4,tf,ImVec2(0,ImGui::GetContentRegionAvail().y)))
{
ImGui::TableSetupScrollFreeze(0,1);
ImGui::TableSetupColumn("PID", ImGuiTableColumnFlags_WidthFixed,62);
ImGui::TableSetupColumn("Name",ImGuiTableColumnFlags_WidthFixed,165);
ImGui::TableSetupColumn("Path",ImGuiTableColumnFlags_WidthStretch);
ImGui::TableSetupColumn("Hook",ImGuiTableColumnFlags_WidthFixed,52);
ImGui::TableHeadersRow();
std::string filt(g_procFilter);
std::transform(filt.begin(),filt.end(),filt.begin(),::tolower);
for(auto& row : g_procRows)
{
if(!filt.empty()){
std::string ln=row.name, lp=row.path;
std::transform(ln.begin(),ln.end(),ln.begin(),::tolower);
std::transform(lp.begin(),lp.end(),lp.begin(),::tolower);
if(ln.find(filt)==std::string::npos && lp.find(filt)==std::string::npos) continue;
}
ImGui::TableNextRow();
ImGui::TableSetColumnIndex(0);
ImGui::TextColored(Pal::Muted,"%lu",row.pid);
ImGui::TableSetColumnIndex(1);
ImGui::TextColored(row.injected?Pal::AccentHot:Pal::Text,"%s",row.name.c_str());
ImGui::TableSetColumnIndex(2);
ImGui::TextColored(Pal::TextDim,"%s",row.path.c_str());
ImGui::TableSetColumnIndex(3);
bool inj=row.injected;
char id[32]; sprintf_s(id,"##i%lu",row.pid);
if(inj){
ImGui::PushStyleColor(ImGuiCol_FrameBg,ImVec4(0.06f,0.26f,0.14f,1.f));
ImGui::PushStyleColor(ImGuiCol_FrameBgHovered,ImVec4(0.08f,0.32f,0.18f,1.f));
}
if(ImGui::Checkbox(id,&inj)){
if(inj){
std::wstring err;
LONGLONG t=g_fakeUtcTicks==0?TimeUtil::RealUtcTicks():g_fakeUtcTicks;
if(g_injMgr->Inject(row.pid,t,&err)){
row.injected=true;
AppLog("Injected ["+std::to_string(row.pid)+"] "+row.name);
} else {
char eb[512]; WideCharToMultiByte(CP_UTF8,0,err.c_str(),-1,eb,sizeof(eb),nullptr,nullptr);
AppLog("FAILED inject ["+std::to_string(row.pid)+"]: "+eb,Pal::LogErr);
}
} else {
g_injMgr->Eject(row.pid);
row.injected=false;
AppLog("Ejected ["+std::to_string(row.pid)+"] "+row.name,Pal::LogWarn);
}
}
if(inj) ImGui::PopStyleColor(2);
}
ImGui::EndTable();
}
}
static void RenderRulesTab()
{
ImGui::SetNextItemWidth(340);
ImGui::InputTextWithHint("##np","e.g. C:\\Games\\* or ^.*\\MyApp\\.exe$",g_newPattern,sizeof(g_newPattern));
ImGui::SameLine(); ImGui::Checkbox("Regex",&g_newUseRegex); ImGui::SameLine();
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.08f,0.36f,0.20f,1.f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered,ImVec4(0.12f,0.48f,0.26f,1.f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.16f,0.60f,0.32f,1.f));
if(ImGui::Button(" + Add Rule ") && g_newPattern[0]){
RuleRow r{g_newPattern,g_newUseRegex,true};
g_rules.push_back(r);
PatternRule pr;
pr.Pattern=std::wstring(r.pattern.begin(),r.pattern.end());
pr.UseRegex=r.useRegex; pr.Enabled=true;
g_watcher->AddRule(pr);
AppLog(std::string("Rule: ")+g_newPattern+(g_newUseRegex?" [regex]":" [glob]"));
g_newPattern[0]=0;
}
ImGui::PopStyleColor(3);
ImGui::Spacing(); ImGui::Separator(); ImGui::Spacing();
ImGuiTableFlags tf=ImGuiTableFlags_Borders|ImGuiTableFlags_RowBg|
ImGuiTableFlags_ScrollY|ImGuiTableFlags_SizingFixedFit;
if(ImGui::BeginTable("##rt",4,tf,ImVec2(0,ImGui::GetContentRegionAvail().y)))
{
ImGui::TableSetupScrollFreeze(0,1);
ImGui::TableSetupColumn("#", ImGuiTableColumnFlags_WidthFixed, 28);
ImGui::TableSetupColumn("Pattern",ImGuiTableColumnFlags_WidthStretch);
ImGui::TableSetupColumn("Type", ImGuiTableColumnFlags_WidthFixed, 56);
ImGui::TableSetupColumn("", ImGuiTableColumnFlags_WidthFixed, 86);
ImGui::TableHeadersRow();
int del=-1;
for(int i=0;i<(int)g_rules.size();i++){
auto& r=g_rules[i];
ImGui::TableNextRow();
ImGui::TableSetColumnIndex(0); ImGui::TextColored(Pal::Muted,"%d",i);
ImGui::TableSetColumnIndex(1); ImGui::TextColored(r.enabled?Pal::Text:Pal::Muted,"%s",r.pattern.c_str());
ImGui::TableSetColumnIndex(2); ImGui::TextColored(r.useRegex?Pal::Warning:Pal::AccentDim,"%s",r.useRegex?"regex":"glob");
ImGui::TableSetColumnIndex(3);
char eid[32]; sprintf_s(eid,"##e%d",i); bool en=r.enabled;
if(ImGui::Checkbox(eid,&en)) r.enabled=en;
ImGui::SameLine(0,6);
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0.30f,0.09f,0.09f,1.f));
ImGui::PushStyleColor(ImGuiCol_ButtonHovered,ImVec4(0.48f,0.12f,0.12f,1.f));
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(0.62f,0.16f,0.16f,1.f));
char did[32]; sprintf_s(did," X ##d%d",i);
if(ImGui::Button(did)) del=i;
ImGui::PopStyleColor(3);
}
if(del>=0){
std::wstring wp(g_rules[del].pattern.begin(),g_rules[del].pattern.end());
AppLog("Rule removed: "+g_rules[del].pattern,Pal::LogWarn);
g_watcher->RemoveRule(wp);
g_rules.erase(g_rules.begin()+del);
}
ImGui::EndTable();
}
}
static void RenderLogTab()
{
if(ImGui::Button(" Clear ")){
std::lock_guard<std::mutex> lk(g_logMutex);
g_log.clear();
}
ImGui::Spacing();
ImGui::PushStyleColor(ImGuiCol_ChildBg,ImVec4(0.05f,0.06f,0.07f,1.f));
ImGui::BeginChild("##lg",ImVec2(0,ImGui::GetContentRegionAvail().y),false,ImGuiWindowFlags_HorizontalScrollbar);
{
std::lock_guard<std::mutex> lk(g_logMutex);
for(auto& e : g_log){
ImGui::TextColored(Pal::Muted,"%s",e.ts.c_str());
ImGui::SameLine(0,8);
ImGui::TextColored(e.color,"%s",e.msg.c_str());
}
}
if(g_logScrollToBottom){ ImGui::SetScrollHereY(1.f); g_logScrollToBottom=false; }
ImGui::EndChild();
ImGui::PopStyleColor();
}
// ─────────────────────────────────────────────────────────────────────────────
// Main render
// ─────────────────────────────────────────────────────────────────────────────
static void RenderUI()
{
const ImGuiViewport* vp=ImGui::GetMainViewport();
ImGui::SetNextWindowPos(vp->WorkPos);
ImGui::SetNextWindowSize(vp->WorkSize);
ImGuiWindowFlags wf=ImGuiWindowFlags_NoDecoration|ImGuiWindowFlags_NoMove|
ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_NoBringToFrontOnFocus;
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding,0);
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize,0);
ImGui::Begin("##root",nullptr,wf);
ImGui::PopStyleVar(2);
// Title bar row
ImGui::TextColored(Pal::Accent,"TIMEMOCKER");
ImGui::SameLine(0,10);
ImGui::TextColored(Pal::Muted,"// Win32 API hook via MS Detours // DirectX 11 UI");
ImGui::Spacing();
RenderHeader();
ImGui::Spacing();
RenderTimePanel();
ImGui::Spacing();
if(ImGui::BeginTabBar("##tabs")){
if(ImGui::BeginTabItem(" Processes ")) { ImGui::Spacing(); RenderProcessTab(); ImGui::EndTabItem(); }
if(ImGui::BeginTabItem(" Auto-Inject ")) { ImGui::Spacing(); RenderRulesTab(); ImGui::EndTabItem(); }
if(ImGui::BeginTabItem(" Log ")) { ImGui::Spacing(); RenderLogTab(); ImGui::EndTabItem(); }
ImGui::EndTabBar();
}
ImGui::End();
}
// ─────────────────────────────────────────────────────────────────────────────
// WinMain
// ─────────────────────────────────────────────────────────────────────────────
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE, LPSTR, int)
{
// Elevation check
{
HANDLE hTok; OpenProcessToken(GetCurrentProcess(),TOKEN_QUERY,&hTok);
TOKEN_ELEVATION e{}; DWORD sz=sizeof(e);
GetTokenInformation(hTok,TokenElevation,&e,sz,&sz); CloseHandle(hTok);
if(!e.TokenIsElevated){
MessageBoxA(nullptr,"TimeMocker requires Administrator.\nRestarting elevated...","Elevation Required",MB_ICONWARNING|MB_OK);
wchar_t p[MAX_PATH]; GetModuleFileNameW(nullptr,p,MAX_PATH);
ShellExecuteW(nullptr,L"runas",p,nullptr,nullptr,SW_SHOWNORMAL);
return 0;
}
}
WNDCLASSEXW wc{};
wc.cbSize=sizeof(wc); wc.style=CS_CLASSDC; wc.lpfnWndProc=WndProc;
wc.hInstance=hInstance; wc.hCursor=LoadCursor(nullptr,IDC_ARROW);
wc.lpszClassName=L"TimeMockerWnd";
RegisterClassExW(&wc);
HWND hwnd=CreateWindowExW(0,L"TimeMockerWnd",L"TimeMocker",WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,CW_USEDEFAULT,1280,780,nullptr,nullptr,hInstance,nullptr);
if(!CreateDeviceD3D(hwnd)){ CleanupDeviceD3D(); return 1; }
ShowWindow(hwnd,SW_SHOWDEFAULT); UpdateWindow(hwnd);
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io=ImGui::GetIO();
io.ConfigFlags|=ImGuiConfigFlags_NavEnableKeyboard;
io.IniFilename=nullptr;
ApplyTheme();
ImGui_ImplWin32_Init(hwnd);
ImGui_ImplDX11_Init(g_pd3dDevice,g_pd3dDeviceContext);
g_injMgr = new InjectionManager();
g_watcher = new ProcessWatcher(*g_injMgr);
g_injMgr->OnLog = WLog;
g_watcher->OnLog = WLog;
g_watcher->OnAutoInjected=[](DWORD pid,const std::wstring& name,const std::wstring&){
char b[256]; WideCharToMultiByte(CP_UTF8,0,name.c_str(),-1,b,sizeof(b),nullptr,nullptr);
AppLog(std::string("[AutoInject] [")+std::to_string(pid)+"] "+b, Pal::AccentHot);
};
ResetTimeToNow();
RefreshProcessList();
g_watcher->Start(1500);
AppLog("TimeMocker started. Watcher active.");
bool done=false;
while(!done){
MSG msg;
while(PeekMessage(&msg,nullptr,0,0,PM_REMOVE)){
TranslateMessage(&msg); DispatchMessage(&msg);
if(msg.message==WM_QUIT) done=true;
}
if(done) break;
ImGui_ImplDX11_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
RenderUI();
ImGui::Render();
const float cc[4]={0.07f,0.08f,0.09f,1.f};
g_pd3dDeviceContext->OMSetRenderTargets(1,&g_mainRenderTargetView,nullptr);
g_pd3dDeviceContext->ClearRenderTargetView(g_mainRenderTargetView,cc);
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
g_pSwapChain->Present(1,0);
}
g_watcher->Stop();
delete g_watcher; delete g_injMgr;
ImGui_ImplDX11_Shutdown();
ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext();
CleanupDeviceD3D();
DestroyWindow(hwnd);
UnregisterClassW(wc.lpszClassName,hInstance);
return 0;
}
// ─────────────────────────────────────────────────────────────────────────────
// D3D boilerplate
// ─────────────────────────────────────────────────────────────────────────────
static bool CreateDeviceD3D(HWND hWnd)
{
DXGI_SWAP_CHAIN_DESC sd{};
sd.BufferCount=2; sd.BufferDesc.Format=DXGI_FORMAT_R8G8B8A8_UNORM;
sd.Flags=DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
sd.BufferUsage=DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow=hWnd; sd.SampleDesc.Count=1; sd.Windowed=TRUE;
sd.SwapEffect=DXGI_SWAP_EFFECT_DISCARD;
D3D_FEATURE_LEVEL fl; const D3D_FEATURE_LEVEL fls[]={D3D_FEATURE_LEVEL_11_0,D3D_FEATURE_LEVEL_10_0};
HRESULT hr=D3D11CreateDeviceAndSwapChain(nullptr,D3D_DRIVER_TYPE_HARDWARE,nullptr,0,fls,2,
D3D11_SDK_VERSION,&sd,&g_pSwapChain,&g_pd3dDevice,&fl,&g_pd3dDeviceContext);
if(hr==DXGI_ERROR_UNSUPPORTED)
hr=D3D11CreateDeviceAndSwapChain(nullptr,D3D_DRIVER_TYPE_WARP,nullptr,0,fls,2,
D3D11_SDK_VERSION,&sd,&g_pSwapChain,&g_pd3dDevice,&fl,&g_pd3dDeviceContext);
if(FAILED(hr)) return false;
CreateRenderTarget(); return true;
}
static void CleanupDeviceD3D(){
CleanupRenderTarget();
if(g_pSwapChain){g_pSwapChain->Release();g_pSwapChain=nullptr;}
if(g_pd3dDeviceContext){g_pd3dDeviceContext->Release();g_pd3dDeviceContext=nullptr;}
if(g_pd3dDevice){g_pd3dDevice->Release();g_pd3dDevice=nullptr;}
}
static void CreateRenderTarget(){
ID3D11Texture2D* bb;
g_pSwapChain->GetBuffer(0,IID_PPV_ARGS(&bb));
g_pd3dDevice->CreateRenderTargetView(bb,nullptr,&g_mainRenderTargetView);
bb->Release();
}
static void CleanupRenderTarget(){
if(g_mainRenderTargetView){g_mainRenderTargetView->Release();g_mainRenderTargetView=nullptr;}
}
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if(ImGui_ImplWin32_WndProcHandler(hWnd,msg,wParam,lParam)) return true;
switch(msg){
case WM_SIZE:
if(g_pd3dDevice && wParam!=SIZE_MINIMIZED){
CleanupRenderTarget();
g_pSwapChain->ResizeBuffers(0,LOWORD(lParam),HIWORD(lParam),DXGI_FORMAT_UNKNOWN,0);
CreateRenderTarget();
}
return 0;
case WM_SYSCOMMAND:
if((wParam&0xfff0)==SC_KEYMENU) return 0;
break;
case WM_DESTROY:
PostQuitMessage(0); return 0;
}
return DefWindowProcW(hWnd,msg,wParam,lParam);
}
-41
View File
@@ -1,41 +0,0 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.11.35222.181
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TimeMocker.Hook", "TimeMocker.Hook\TimeMocker.Hook.vcxproj", "{A1111111-1111-1111-1111-111111111111}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TimeMocker.Injector", "TimeMocker.Injector\TimeMocker.Injector.vcxproj", "{B2222222-2222-2222-2222-222222222222}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "TimeMocker.UI", "TimeMocker.UI\TimeMocker.UI.vcxproj", "{C3333333-3333-3333-3333-333333333333}"
ProjectSection(ProjectDependencies) = postProject
{A1111111-1111-1111-1111-111111111111} = {A1111111-1111-1111-1111-111111111111}
{B2222222-2222-2222-2222-222222222222} = {B2222222-2222-2222-2222-222222222222}
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Release|x64 = Release|x64
Debug|x86 = Debug|x86
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A1111111-1111-1111-1111-111111111111}.Debug|x64.ActiveCfg = Debug|x64
{A1111111-1111-1111-1111-111111111111}.Debug|x64.Build.0 = Debug|x64
{A1111111-1111-1111-1111-111111111111}.Release|x64.ActiveCfg = Release|x64
{A1111111-1111-1111-1111-111111111111}.Release|x64.Build.0 = Release|x64
{A1111111-1111-1111-1111-111111111111}.Debug|x86.ActiveCfg = Debug|Win32
{A1111111-1111-1111-1111-111111111111}.Debug|x86.Build.0 = Debug|Win32
{A1111111-1111-1111-1111-111111111111}.Release|x86.ActiveCfg = Release|Win32
{A1111111-1111-1111-1111-111111111111}.Release|x86.Build.0 = Release|Win32
{B2222222-2222-2222-2222-222222222222}.Debug|x64.ActiveCfg = Debug|x64
{B2222222-2222-2222-2222-222222222222}.Debug|x64.Build.0 = Debug|x64
{B2222222-2222-2222-2222-222222222222}.Release|x64.ActiveCfg = Release|x64
{B2222222-2222-2222-2222-222222222222}.Release|x64.Build.0 = Release|x64
{C3333333-3333-3333-3333-333333333333}.Debug|x64.ActiveCfg = Debug|x64
{C3333333-3333-3333-3333-333333333333}.Debug|x64.Build.0 = Debug|x64
{C3333333-3333-3333-3333-333333333333}.Release|x64.ActiveCfg = Release|x64
{C3333333-3333-3333-3333-333333333333}.Release|x64.Build.0 = Release|x64
EndGlobalSection
EndGlobal
-99
View File
@@ -1,99 +0,0 @@
# =============================================================================
# setup.ps1 — Bootstrap MS Detours + Dear ImGui for TimeMockerCpp
#
# Run once before opening the solution:
# powershell -ExecutionPolicy Bypass -File scripts\setup.ps1
# =============================================================================
$ErrorActionPreference = "Stop"
$repoRoot = Split-Path $PSScriptRoot -Parent
$vcpkgRoot = if ($env:VCPKG_ROOT) { $env:VCPKG_ROOT } else { Join-Path $repoRoot "vcpkg" }
$pkgDir = Join-Path $repoRoot "packages\detours"
$imguiDir = Join-Path $repoRoot "TimeMocker.UI\imgui"
# ── 1. vcpkg ─────────────────────────────────────────────────────────────────
if (!(Test-Path (Join-Path $vcpkgRoot "vcpkg.exe")))
{
Write-Host "Cloning vcpkg..." -ForegroundColor Cyan
git clone https://github.com/microsoft/vcpkg.git $vcpkgRoot
& (Join-Path $vcpkgRoot "bootstrap-vcpkg.bat") -disableMetrics
}
else { Write-Host "vcpkg found at $vcpkgRoot" -ForegroundColor Green }
$vcpkg = Join-Path $vcpkgRoot "vcpkg.exe"
# ── 2. Install Detours ────────────────────────────────────────────────────────
Write-Host "Installing detours:x64-windows..." -ForegroundColor Cyan
& $vcpkg install "detours:x64-windows"
Write-Host "Installing detours:x86-windows..." -ForegroundColor Cyan
& $vcpkg install "detours:x86-windows"
# ── 3. Copy Detours headers + libs ───────────────────────────────────────────
$incDst = Join-Path $pkgDir "include"
New-Item -ItemType Directory -Force -Path $incDst | Out-Null
Copy-Item -Path (Join-Path $vcpkgRoot "installed\x64-windows\include\detours.h") `
-Destination $incDst -Force
foreach ($triplet in @("x64","x86"))
{
$libDst = Join-Path $pkgDir "lib\$triplet"
New-Item -ItemType Directory -Force -Path $libDst | Out-Null
Copy-Item -Path (Join-Path $vcpkgRoot "installed\$triplet-windows\lib\detours.lib") `
-Destination (Join-Path $libDst "detours.lib") -Force
Write-Host " Detours $triplet copied" -ForegroundColor Green
}
# ── 4. Download Dear ImGui ────────────────────────────────────────────────────
Write-Host ""
Write-Host "Fetching Dear ImGui (latest release)..." -ForegroundColor Cyan
New-Item -ItemType Directory -Force -Path $imguiDir | Out-Null
# Use the GitHub API to find the latest release tag
$release = Invoke-RestMethod "https://api.github.com/repos/ocornut/imgui/releases/latest"
$tag = $release.tag_name
Write-Host " Tag: $tag" -ForegroundColor Green
$baseUrl = "https://raw.githubusercontent.com/ocornut/imgui/$tag"
$coreFiles = @(
"imgui.h", "imgui.cpp",
"imgui_internal.h",
"imgui_draw.cpp",
"imgui_tables.cpp",
"imgui_widgets.cpp",
"imconfig.h",
"imstb_rectpack.h",
"imstb_textedit.h",
"imstb_truetype.h"
)
$backendFiles = @(
"imgui_impl_win32.h", "imgui_impl_win32.cpp",
"imgui_impl_dx11.h", "imgui_impl_dx11.cpp"
)
foreach ($f in $coreFiles)
{
$url = "$baseUrl/$f"
$dest = Join-Path $imguiDir $f
Write-Host " Downloading $f" -NoNewline
Invoke-WebRequest -Uri $url -OutFile $dest -UseBasicParsing
Write-Host "" -ForegroundColor Green
}
foreach ($f in $backendFiles)
{
$url = "$baseUrl/backends/$f"
$dest = Join-Path $imguiDir $f
Write-Host " Downloading $f" -NoNewline
Invoke-WebRequest -Uri $url -OutFile $dest -UseBasicParsing
Write-Host "" -ForegroundColor Green
}
Write-Host ""
Write-Host "═══════════════════════════════════════════════════" -ForegroundColor Cyan
Write-Host " Setup complete!" -ForegroundColor Green
Write-Host " Open TimeMocker.sln in Visual Studio 2022" -ForegroundColor Green
Write-Host " Build: Release | x64" -ForegroundColor Green
Write-Host "═══════════════════════════════════════════════════" -ForegroundColor Cyan
-7
View File
@@ -1,7 +0,0 @@
{
"permissions": {
"allow": [
"Bash(dotnet build:*)"
]
}
}
-42
View File
@@ -1,42 +0,0 @@
name: Create Draft Release
on:
push:
tags:
- "v*"
permissions:
contents: write
jobs:
build-and-release:
runs-on: windows-latest
steps:
- name: Checkout
uses: actions/checkout@v6
- name: Setup .NET
uses: actions/setup-dotnet@v5
with:
dotnet-version: 10.x
- name: Build Solution
run: dotnet build TimeMocker.sln -c Release -p:Platform=x64
- name: Prepare Release Artifacts
run: |
mkdir release
copy TimeMocker.UI\bin\x64\Release\net48\* release\
- name: Zip Release
run: Compress-Archive -Path release\* -DestinationPath TimeMocker-x64.zip
- name: Create Draft Release
uses: softprops/action-gh-release@v2
with:
files: TimeMocker-x64.zip
draft: true
generate_release_notes: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
-59
View File
@@ -1,59 +0,0 @@
.idea
*.DotSettings.user
## A streamlined .gitignore for modern .NET projects
## including temporary files, build results, and
## files generated by popular .NET tools. If you are
## developing with Visual Studio, the VS .gitignore
## https://github.com/github/gitignore/blob/main/VisualStudio.gitignore
## has more thorough IDE-specific entries.
##
## Get latest from https://github.com/github/gitignore/blob/main/Dotnet.gitignore
# 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/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# Others
~$*
*~
CodeCoverage/
# MSBuild Binary and Structured Log
*.binlog
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
-141
View File
@@ -1,141 +0,0 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
TimeMocker is a Windows application that injects fake time into running processes by hooking Win32 time APIs. It consists of a WinForms UI controller and an EasyHook-based DLL that gets injected into target processes.
## Build Commands
```bash
# Build the solution (x64 only)
dotnet build TimeMocker.sln -c Release -p:Platform=x64
# Build Debug configuration
dotnet build TimeMocker.sln -c Debug -p:Platform=x64
# Clean and rebuild
dotnet clean TimeMocker.sln && dotnet build TimeMocker.sln -c Release -p:Platform=x64
```
**Important**: This is an x64-only project. The solution only has x64 platform configurations. Building for x86 or AnyCPU will fail.
**Output locations**:
- UI exe: `TimeMocker.UI/bin/x64/Release/net48/TimeMocker.exe`
- Hook DLL: `TimeMocker.UI/bin/x64/Release/net48/TimeMocker.Hook.dll`
The hook DLL must be next to the UI exe (automatically copied via ProjectReference).
## Architecture
```
TimeMocker.sln
├── TimeMocker.UI/ — WinForms controller (requires Admin elevation)
│ ├── Forms/MainForm.cs — Main UI with process selection, time picker, pattern manager
│ ├── Core/InjectionManager.cs — EasyHook-based injector, manages injected processes
│ ├── Core/ProcessWatcher.cs — Background scanner for auto-inject rules (poll-based)
│ └── Core/SharedMemoryManager.cs — Named MMF for IPC with hook DLL
└── TimeMocker.Hook/ — DLL injected into target processes
└── InjectionEntryPoint.cs — Hooks 5 Win32 time APIs via EasyHook
```
### IPC Design
The fake time is stored in a **named Memory-Mapped File** (one per injected process):
- Name format: `TimeMocker_<PID>`
- Size: 12 bytes (`Marshal.SizeOf<MockTimeInfo>()`)
- Layout:
- `[0..7]` FakeUtcTicks (Int64 — DateTime.Ticks)
- `[8..11]` Enabled (Int32 — 0=passthrough, 1=mock)
The hook reads this on every time API call (~50 ns read, no syscall). The UI writes via `SharedMemoryManager.Write()`.
### Hooked APIs
| API | DLL |
|-----|-----|
| `GetSystemTime` | kernel32 |
| `GetLocalTime` | kernel32 |
| `GetSystemTimeAsFileTime` | kernel32 |
| `GetSystemTimePreciseAsFileTime` | kernel32 |
| `NtQuerySystemTime` | ntdll |
All hooked functions share the same `GetFakeUtc()` logic which reads from shared memory and either returns the fake time or real `DateTime.UtcNow` depending on the Enabled flag.
### Auto-Inject Pattern Matching
The `ProcessWatcher` supports both glob and regex patterns for matching process paths or names:
- Glob: `C:\Games\MyGame\*` or `*chrome*` (converted to regex internally)
- Regex: `^.*\\MyApp\.exe$`
Patterns are matched against both the full process path (`MainModule.FileName`) and process name (`ProcessName`).
## Key Components
### InjectionManager
- Manages the dictionary of injected processes (`Dictionary<int, InjectedProcess>`)
- Uses `RemoteHooking.Inject()` to inject `TimeMocker.Hook.dll` into target processes
- Creates a `SharedMemoryManager` instance per process for IPC
- Handles eject by disabling the mock (setting Enabled=0) before disposing shared memory
### SharedMemoryManager
- Creates a named memory-mapped file using `MemoryMappedFile.CreateOrOpen()`
- `MockTimeInfo` struct is blittable (sequential layout) for direct memory write
- Must be disposed when process is ejected
### ProcessWatcher
- Polls running processes every ~1.5 seconds (configurable)
- Tracks seen process IDs to avoid duplicate injections
- Auto-injects when a process matches any enabled rule
- Uses current `FakeUtc` and `MockEnabled` settings at injection time
### InjectionEntryPoint (Hook DLL)
- Implements `IEntryPoint` from EasyHook
- `Run()` method opens the named MMF, installs hooks, and keeps alive with a sleep loop
- Uses `LocalHook.Create()` with thread ACL set to exclude thread 0 (all threads)
- Hook delegates read the shared memory on each call (hot path optimized)
- Logs errors to `%TEMP%\TimeMocker.Hook.log`
## Development Notes
- **Target Framework**: .NET Framework 4.8 (pre-installed on Windows 10+)
- **Unsafe Code**: Both projects use `AllowUnsafeBlocks=true` for memory-mapped file operations
- **Dependencies**: EasyHook 2.7.7030.0 (available via NuGet)
- **Language Version**: C# 8
### Limitations
- **64-bit only**: 32-bit processes require a separate 32-bit hook DLL build
- **No hot-unload support**: EasyHook doesn't fully support DLL ejection; disable mock instead
- **Protected processes**: Anti-cheat services (Epic, BattlEye, etc.) will block injection
- **QueryPerformanceCounter**: Not affected (hardware register, cannot be hooked via EasyHook)
### Time Epoch
FILETIME epoch is January 1, 1601 (UTC). Hooked functions returning FILETIME convert from DateTime.Ticks using:
```csharp
var epoch = new DateTime(1601, 1, 1, 0, 0, 0, DateTimeKind.Utc);
long fileTimeTicks = (fakeUtc - epoch).Ticks;
```
## Common Tasks
### Add a new time API hook
1. Add the hook delegate in `InjectionEntryPoint.cs` with `[UnmanagedFunctionPointer(CallingConvention.StdCall)]`
2. Add a `LocalHook` field for the hook handle
3. Create the hook in `InstallHooks()` using `LocalHook.GetProcAddress(dllName, functionName)`
4. Implement the hook function that calls `GetFakeUtc()` and returns the appropriate format
### Modify auto-inject polling interval
Pass a different interval to `ProcessWatcher.Start(int pollIntervalMs)` when enabling the watcher in `MainForm.cs`.
### Debug hook DLL
The hook writes errors to `%TEMP%\TimeMocker.Hook.log`. For more detailed debugging, you may need to attach a debugger to the target process after injection.
-201
View File
@@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-121
View File
@@ -1,121 +0,0 @@
# TimeMocker
A Windows application that injects fake time into running processes by hooking Win32 time APIs.
## Architecture
```
TimeMocker.sln
├── TimeMocker.UI — WinForms controller app (run as Admin)
│ ├── Forms/MainForm — UI: process list with inject toggle, time picker, pattern manager
│ ├── Core/InjectionManager — EasyHook-based injector per process
│ ├── Core/ProcessWatcher — background scanner for auto-inject patterns
│ └── Core/SharedMemoryManager — named MMF shared with the hook DLL
└── TimeMocker.Hook — DLL injected into target processes
└── InjectionEntryPoint — hooks 5 Win32 time functions via EasyHook
```
## Hooked APIs
| API | DLL |
|-----|-----|
| `GetSystemTime` | kernel32 |
| `GetLocalTime` | kernel32 |
| `GetSystemTimeAsFileTime` | kernel32 |
| `GetSystemTimePreciseAsFileTime` | kernel32 |
| `NtQuerySystemTime` | ntdll |
## Requirements
- **Windows 10/11 x64**
- **.NET Framework 4.8** (pre-installed on Win10+)
- **Visual Studio 2022** or `dotnet build`
- Must run as **Administrator** (UAC prompt shown automatically)
## Build
```bash
# Clone / extract the solution
cd TimeMocker
dotnet restore
dotnet build -c Release -p:Platform=x64
# Outputs go to:
# TimeMocker.UI/bin/x64/Release/net48/TimeMocker.exe
# TimeMocker.UI/bin/x64/Release/net48/TimeMocker.Hook.dll ← must be next to .exe
```
> In Visual Studio: open `TimeMocker.sln`, set platform to **x64**, build solution.
## Usage
### Manual Injection
1. Launch `TimeMocker.exe` (UAC will prompt for elevation)
2. Set the desired date/time in the **Mock Time Settings** bar at the top
3. Click **Set** to apply the time to all injected processes
4. Go to the **Processes** tab
5. Find your target process in the list (use Search if needed)
6. Check the **Injected** checkbox next to the process
7. The target process now sees your fake time immediately
8. To stop mocking for a process, simply uncheck the **Injected** checkbox
### Auto-Inject Rules
The auto-inject watcher starts automatically when TimeMocker launches. Any process matching a rule will be injected automatically.
1. Go to the **Auto-Inject Rules** tab
2. Enter a pattern matching the process path or name, e.g.:
- Glob: `C:\Games\MyGame\*`
- Glob by name: `*chrome*`
- Regex: `^.*\\MyApp\.exe$`
3. Select **Glob** or **Regex** pattern type
4. Click **+ Add Rule**
5. Any process that starts (or is already running) matching the rule gets injected automatically with the current mock time
### Time Flow
TimeMocker uses a **delta-based** approach. When you set a fake time, it calculates the offset between your desired time and the current real time. This offset is stored and applied continuously, so the fake time flows forward naturally at the same rate as real time.
- Click **Now** to reset the date/time pickers to current time
- Click **Set** to apply the selected time to all injected processes
- The offset is recalculated each time you click **Set**
### Process List
- Only user processes are shown (system processes are filtered out)
- Click **⟳ Refresh** to reload the process list
- Dead processes are automatically removed from the injected processes list
## IPC Design
The time offset is stored in a **named Memory-Mapped File** (one per injected process):
```
Name: TimeMocker_<PID>
Size: 8 bytes
[0..7] DeltaTicks (Int64 — offset from DateTime.UtcNow.Ticks)
```
The hook reads this on every time API call and returns `DateTime.UtcNow + DeltaTicks`. This design allows the fake time to flow naturally without requiring timer-based updates from the UI.
## Notes & Limitations
- **64-bit only** — 32-bit processes require a separate 32-bit hook DLL build
- Processes using `QueryPerformanceCounter` for *monotonic* timing are not affected
(QPC is a hardware register; patching it is unsupported by EasyHook)
- Anti-cheat or heavily protected processes (Epic, BattlEye, etc.) will block injection
- Some .NET apps read time through the CLR, which internally calls the hooked APIs — these *will* be affected
- EasyHook does not fully support hot-eject; to restore real time, uncheck the **Injected** checkbox
- Mocked time is always enabled — there is no passthrough mode
## License
MIT
## Related
- [time-mocker](https://github.com/tiennm99/time-mocker) — canonical Rust implementation.
- [time-mocker-cpp](https://github.com/tiennm99/time-mocker-cpp) — C++ / MS Detours implementation.
@@ -1,188 +0,0 @@
using System;
using System.IO;
using System.IO.Pipes;
using System.Runtime.InteropServices;
using System.Threading;
using EasyHook;
namespace TimeMocker.Hook
{
/// <summary>
/// Shared memory layout written by the UI and read by the hook.
/// Stored in a named memory-mapped file so no pipe latency on hot path.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct MockTimeInfo
{
public long DeltaTicks; // Offset to add to DateTime.UtcNow.Ticks (can be negative)
}
// -------------------------------------------------------------------------
// Win32 structs
// -------------------------------------------------------------------------
[StructLayout(LayoutKind.Sequential)]
public struct SYSTEMTIME
{
public ushort wYear, wMonth, wDayOfWeek, wDay;
public ushort wHour, wMinute, wSecond, wMilliseconds;
public static SYSTEMTIME FromDateTime(DateTime dt)
{
return new SYSTEMTIME
{
wYear = (ushort)dt.Year,
wMonth = (ushort)dt.Month,
wDayOfWeek = (ushort)dt.DayOfWeek,
wDay = (ushort)dt.Day,
wHour = (ushort)dt.Hour,
wMinute = (ushort)dt.Minute,
wSecond = (ushort)dt.Second,
wMilliseconds = (ushort)dt.Millisecond
};
}
}
// -------------------------------------------------------------------------
// EasyHook entry point called after DLL is injected
// -------------------------------------------------------------------------
public class InjectionEntryPoint : IEntryPoint
{
private readonly string _mmfName;
private System.IO.MemoryMappedFiles.MemoryMappedFile _mmf;
private System.IO.MemoryMappedFiles.MemoryMappedViewAccessor _view;
// Hook handles
private LocalHook _getSystemTimeHook;
private LocalHook _getLocalTimeHook;
private LocalHook _ntQuerySystemTimeHook;
private LocalHook _getSystemTimeAsFileTimeHook;
private LocalHook _getSystemTimePreciseAsFileTimeHook;
public InjectionEntryPoint(RemoteHooking.IContext context, string mmfName)
{
_mmfName = mmfName;
}
public void Run(RemoteHooking.IContext context, string mmfName)
{
try
{
// Open the shared memory created by the UI process
_mmf = System.IO.MemoryMappedFiles.MemoryMappedFile.OpenExisting(mmfName);
_view = _mmf.CreateViewAccessor(0, Marshal.SizeOf<MockTimeInfo>());
InstallHooks();
RemoteHooking.WakeUpProcess();
// Keep alive until process exits
while (true) Thread.Sleep(500);
}
catch (Exception ex)
{
File.AppendAllText(
Path.Combine(Path.GetTempPath(), "TimeMocker.Hook.log"),
$"[{DateTime.Now}] ERROR: {ex}\r\n");
}
finally
{
_getSystemTimeHook?.Dispose();
_getLocalTimeHook?.Dispose();
_ntQuerySystemTimeHook?.Dispose();
_getSystemTimeAsFileTimeHook?.Dispose();
_getSystemTimePreciseAsFileTimeHook?.Dispose();
_view?.Dispose();
_mmf?.Dispose();
}
}
// -------------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------------
private MockTimeInfo ReadMockInfo()
{
_view.Read(0, out MockTimeInfo info);
return info;
}
private DateTime GetFakeUtc()
{
var info = ReadMockInfo();
// Return real UTC time plus the stored delta offset
return new DateTime(DateTime.UtcNow.Ticks + info.DeltaTicks, DateTimeKind.Utc);
}
private void InstallHooks()
{
_getSystemTimeHook = LocalHook.Create(
LocalHook.GetProcAddress("kernel32.dll", "GetSystemTime"),
new GetSystemTimeDelegate(GetSystemTime_Hook), this);
_getSystemTimeHook.ThreadACL.SetExclusiveACL(new[] { 0 });
_getLocalTimeHook = LocalHook.Create(
LocalHook.GetProcAddress("kernel32.dll", "GetLocalTime"),
new GetLocalTimeDelegate(GetLocalTime_Hook), this);
_getLocalTimeHook.ThreadACL.SetExclusiveACL(new[] { 0 });
_ntQuerySystemTimeHook = LocalHook.Create(
LocalHook.GetProcAddress("ntdll.dll", "NtQuerySystemTime"),
new NtQuerySystemTimeDelegate(NtQuerySystemTime_Hook), this);
_ntQuerySystemTimeHook.ThreadACL.SetExclusiveACL(new[] { 0 });
_getSystemTimeAsFileTimeHook = LocalHook.Create(
LocalHook.GetProcAddress("kernel32.dll", "GetSystemTimeAsFileTime"),
new GetSystemTimeAsFileTimeDelegate(GetSystemTimeAsFileTime_Hook), this);
_getSystemTimeAsFileTimeHook.ThreadACL.SetExclusiveACL(new[] { 0 });
_getSystemTimePreciseAsFileTimeHook = LocalHook.Create(
LocalHook.GetProcAddress("kernel32.dll", "GetSystemTimePreciseAsFileTime"),
new GetSystemTimeAsFileTimeDelegate(GetSystemTimePreciseAsFileTime_Hook), this);
_getSystemTimePreciseAsFileTimeHook.ThreadACL.SetExclusiveACL(new[] { 0 });
}
// -------------------------------------------------------------------------
// Hook implementations
// -------------------------------------------------------------------------
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void GetSystemTimeDelegate(out SYSTEMTIME lpSystemTime);
private void GetSystemTime_Hook(out SYSTEMTIME lpSystemTime)
{
lpSystemTime = SYSTEMTIME.FromDateTime(GetFakeUtc());
}
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void GetLocalTimeDelegate(out SYSTEMTIME lpLocalTime);
private void GetLocalTime_Hook(out SYSTEMTIME lpLocalTime)
{
lpLocalTime = SYSTEMTIME.FromDateTime(GetFakeUtc().ToLocalTime());
}
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate int NtQuerySystemTimeDelegate(out long systemTime);
private int NtQuerySystemTime_Hook(out long systemTime)
{
// FILETIME epoch: Jan 1, 1601
var epoch = new DateTime(1601, 1, 1, 0, 0, 0, DateTimeKind.Utc);
systemTime = (GetFakeUtc() - epoch).Ticks;
return 0; // STATUS_SUCCESS
}
[UnmanagedFunctionPointer(CallingConvention.StdCall)]
private delegate void GetSystemTimeAsFileTimeDelegate(out long lpFileTime);
private void GetSystemTimeAsFileTime_Hook(out long lpFileTime)
{
var epoch = new DateTime(1601, 1, 1, 0, 0, 0, DateTimeKind.Utc);
lpFileTime = (GetFakeUtc() - epoch).Ticks;
}
private void GetSystemTimePreciseAsFileTime_Hook(out long lpFileTime)
{
var epoch = new DateTime(1601, 1, 1, 0, 0, 0, DateTimeKind.Utc);
lpFileTime = (GetFakeUtc() - epoch).Ticks;
}
}
}
@@ -1,14 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net48</TargetFramework>
<Platforms>x64;x86</Platforms>
<AssemblyName>TimeMocker.Hook</AssemblyName>
<RootNamespace>TimeMocker.Hook</RootNamespace>
<OutputType>Library</OutputType>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<PlatformTarget>$(Platform)</PlatformTarget>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="EasyHook" Version="2.7.7097.0"/>
</ItemGroup>
</Project>
@@ -1,133 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using EasyHook;
namespace TimeMocker.UI.Core
{
public class InjectedProcess
{
public int ProcessId { get; set; }
public string ProcessName { get; set; }
public string ProcessPath { get; set; }
public SharedMemoryManager Shm { get; set; }
public bool IsInjected { get; set; }
}
public class InjectionManager : IDisposable
{
private readonly Dictionary<int, InjectedProcess> _injected
= new Dictionary<int, InjectedProcess>();
private static readonly string HookDllPathX64 =
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TimeMocker.Hook.x64.dll");
private static readonly string HookDllPathX86 =
Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TimeMocker.Hook.x86.dll");
public event Action<string> LogMessage;
// -----------------------------------------------------------------------
// Inject into a specific process
// -----------------------------------------------------------------------
public InjectedProcess Inject(Process process)
{
if (_injected.ContainsKey(process.Id))
return _injected[process.Id];
var entry = new InjectedProcess
{
ProcessId = process.Id,
ProcessName = process.ProcessName,
ProcessPath = TryGetPath(process),
Shm = new SharedMemoryManager(process.Id)
};
try
{
// Write initial delta (zero = real time) before hook starts reading
entry.Shm.Write(new MockTimeInfo { DeltaTicks = 0 });
RemoteHooking.Inject(
process.Id,
InjectionOptions.DoNotRequireStrongName,
HookDllPathX86,
HookDllPathX64,
entry.Shm.MmfName);
entry.IsInjected = true;
_injected[process.Id] = entry;
Log($"Injected into [{process.Id}] {process.ProcessName}");
}
catch (Exception ex)
{
entry.Shm.Dispose();
Log($"Failed to inject into [{process.Id}] {process.ProcessName}: {ex.Message}");
throw;
}
return entry;
}
// -----------------------------------------------------------------------
// Update fake time for a process
// -----------------------------------------------------------------------
public void SetFakeTime(int processId, DateTime fakeUtc)
{
if (!_injected.TryGetValue(processId, out var entry)) return;
// Calculate delta: (desired fake time) - (current real UTC time)
long deltaTicks = fakeUtc.Ticks - DateTime.UtcNow.Ticks;
entry.Shm.Write(new MockTimeInfo { DeltaTicks = deltaTicks });
}
public void SetFakeTimeAll(DateTime fakeUtc)
{
foreach (var pid in _injected.Keys)
SetFakeTime(pid, fakeUtc);
}
public bool IsInjected(int processId)
{
return _injected.ContainsKey(processId);
}
public IEnumerable<InjectedProcess> InjectedProcesses => _injected.Values;
// -----------------------------------------------------------------------
// Eject (best-effort EasyHook doesn't fully support unloading)
// -----------------------------------------------------------------------
public void Eject(int processId)
{
if (!_injected.TryGetValue(processId, out var entry)) return;
entry.Shm.Dispose();
_injected.Remove(processId);
Log($"Ejected from [{processId}] {entry.ProcessName}");
}
private static string TryGetPath(Process p)
{
try
{
return p.MainModule?.FileName ?? "";
}
catch
{
return "";
}
}
private void Log(string msg)
{
LogMessage?.Invoke(msg);
}
public void Dispose()
{
foreach (var e in _injected.Values) e.Shm?.Dispose();
_injected.Clear();
}
}
}
-152
View File
@@ -1,152 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Threading;
namespace TimeMocker.UI.Core
{
public class PatternRule
{
public string Pattern { get; set; } // glob or regex
public bool UseRegex { get; set; }
public bool Enabled { get; set; } = true;
private Regex _compiled;
public bool IsMatch(string path)
{
if (string.IsNullOrEmpty(path)) return false;
if (UseRegex)
{
_compiled ??= new Regex(Pattern, RegexOptions.IgnoreCase);
return _compiled.IsMatch(path);
}
// Glob: convert * and ? to regex
var regexStr = "^" + Regex.Escape(Pattern)
.Replace(@"\*", ".*")
.Replace(@"\?", ".") + "$";
return Regex.IsMatch(path, regexStr, RegexOptions.IgnoreCase);
}
}
public class ProcessWatcher : IDisposable
{
private readonly InjectionManager _injectionMgr;
private readonly List<PatternRule> _rules = new List<PatternRule>();
private readonly HashSet<int> _seen = new HashSet<int>();
private Timer _timer;
private bool _running;
// Current fake time settings to apply on auto-inject
public DateTime FakeUtc { get; set; } = DateTime.UtcNow;
public event Action<string> LogMessage;
public event Action<InjectedProcess> ProcessAutoInjected;
public ProcessWatcher(InjectionManager mgr)
{
_injectionMgr = mgr;
}
public void AddRule(PatternRule rule)
{
lock (_rules)
{
_rules.Add(rule);
}
}
public void RemoveRule(PatternRule rule)
{
lock (_rules)
{
_rules.Remove(rule);
}
}
public void ClearRules()
{
lock (_rules)
{
_rules.Clear();
}
}
public void Start(int pollIntervalMs = 5000)
{
if (_running) return;
_running = true;
_timer = new Timer(_ => Scan(), null, 0, pollIntervalMs);
}
public void Stop()
{
_running = false;
_timer?.Dispose();
_timer = null;
}
private void Scan()
{
try
{
var processes = Process.GetProcesses();
lock (_rules)
{
foreach (var p in processes)
{
if (_seen.Contains(p.Id)) continue;
var path = "";
try
{
path = p.MainModule?.FileName ?? "";
}
catch
{
continue;
}
foreach (var rule in _rules)
{
if (!rule.Enabled) continue;
if (!rule.IsMatch(path) && !rule.IsMatch(p.ProcessName)) continue;
_seen.Add(p.Id);
try
{
var entry = _injectionMgr.Inject(p);
_injectionMgr.SetFakeTime(p.Id, FakeUtc);
Log($"[AutoInject] Matched rule '{rule.Pattern}' → [{p.Id}] {p.ProcessName}");
ProcessAutoInjected?.Invoke(entry);
}
catch (Exception ex)
{
Log($"[AutoInject] Failed on [{p.Id}] {p.ProcessName}: {ex.Message}");
}
break;
}
}
}
}
catch
{
/* scan errors are non-fatal */
}
}
private void Log(string msg)
{
LogMessage?.Invoke(msg);
}
public void Dispose()
{
Stop();
}
}
}
@@ -1,51 +0,0 @@
using System;
using System.IO.MemoryMappedFiles;
using System.Runtime.InteropServices;
namespace TimeMocker.UI.Core
{
/// <summary>
/// Creates a named Memory-Mapped File so the injected hook can read
/// the fake time without any IPC latency on the hot path.
/// One SharedMemoryManager per injected process.
/// </summary>
public class SharedMemoryManager : IDisposable
{
public const string MmfPrefix = "TimeMocker_";
private MemoryMappedFile _mmf;
private MemoryMappedViewAccessor _view;
private readonly int _size;
private bool _disposed;
public string MmfName { get; }
public SharedMemoryManager(int processId)
{
MmfName = MmfPrefix + processId;
_size = Marshal.SizeOf<MockTimeInfo>();
_mmf = MemoryMappedFile.CreateOrOpen(MmfName, _size,
MemoryMappedFileAccess.ReadWrite);
_view = _mmf.CreateViewAccessor(0, _size);
}
public void Write(MockTimeInfo info)
{
_view.Write(0, ref info);
_view.Flush();
}
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_view?.Dispose();
_mmf?.Dispose();
}
}
[StructLayout(LayoutKind.Sequential)]
public struct MockTimeInfo
{
public long DeltaTicks; // Offset to add to DateTime.UtcNow.Ticks (can be negative)
}
}
-726
View File
@@ -1,726 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Timers;
using System.Windows.Forms;
using TimeMocker.UI.Core;
namespace TimeMocker.UI.Forms
{
public class PatternRuleDto
{
public string Pattern { get; set; }
public bool UseRegex { get; set; }
public bool Enabled { get; set; } = true;
}
public class AppConfig
{
private static readonly string ConfigPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"TimeMocker",
"timemocker-config.json");
public List<PatternRuleDto> Patterns { get; set; } = new List<PatternRuleDto>();
public void Save()
{
var dir = Path.GetDirectoryName(ConfigPath);
if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
File.WriteAllText(ConfigPath, JsonSerializer.Serialize(this, new JsonSerializerOptions { WriteIndented = true }));
}
public static AppConfig Load()
{
return File.Exists(ConfigPath)
? JsonSerializer.Deserialize<AppConfig>(File.ReadAllText(ConfigPath)) ?? new AppConfig()
: new AppConfig();
}
}
public partial class MainForm : Form
{
private readonly AppConfig _config;
private InjectionManager _injMgr;
private ProcessWatcher _watcher;
// Controls
private TabControl tabMain;
private TabPage tabProcesses, tabPatterns, tabLog;
// -- Process tab
private DataGridView dgvProcesses;
private Button btnRefresh;
private TextBox txtProcSearch;
private Label lblProcSearch;
// -- Time panel (shared)
private GroupBox grpTime;
private DateTimePicker dtpDate;
private DateTimePicker dtpTime;
private Button btnApply;
private Label lblPreview;
// -- Patterns tab
private DataGridView dgvPatterns;
private Button btnAddPattern, btnRemovePattern;
private TextBox txtNewPattern;
private RadioButton rdoGlob, rdoRegex;
// -- Log tab
private RichTextBox rtbLog;
private Button btnClearLog;
private System.Timers.Timer _previewUpdateTimer;
private TimeSpan _fakeDelta = TimeSpan.Zero; // Stored offset from real time
public MainForm()
{
_config = AppConfig.Load();
Text = "TimeMocker Process Time Injection";
Size = new Size(900, 680);
MinimumSize = new Size(750, 560);
StartPosition = FormStartPosition.CenterScreen;
Font = new Font("Segoe UI", 9f);
BackColor = Color.FromArgb(45, 52, 64);
ForeColor = Color.FromArgb(200, 200, 200);
_injMgr = new InjectionManager();
_watcher = new ProcessWatcher(_injMgr);
_injMgr.LogMessage += AppendLog;
_watcher.LogMessage += AppendLog;
_watcher.ProcessAutoInjected += entry =>
BeginInvoke((Action)(() => RefreshProcessList()));
BuildUI();
// Load config settings
foreach (var pattern in _config.Patterns)
{
_watcher.AddRule(new PatternRule
{
Pattern = pattern.Pattern,
UseRegex = pattern.UseRegex,
Enabled = pattern.Enabled
});
dgvPatterns.Rows.Add(pattern.Pattern, pattern.UseRegex ? "Regex" : "Glob", pattern.Enabled);
}
RefreshProcessList();
UpdateTimePreview();
ApplyTime(); // Initialize with current time
// Start auto-inject watcher by default
_watcher.FakeUtc = GetFakeTime().ToUniversalTime();
_watcher.Start();
AppendLog("Process watcher started.");
// Start preview update timer (1 second interval)
_previewUpdateTimer = new System.Timers.Timer(1000);
_previewUpdateTimer.Elapsed += (s, e) => BeginInvoke((Action)(UpdateTimePreview));
_previewUpdateTimer.Start();
}
// =====================================================================
// UI Builder
// =====================================================================
private void BuildUI()
{
// ---- Shared time panel (top) ------------------------------------
grpTime = new GroupBox
{
Text = "Mock Time Settings",
Dock = DockStyle.Top,
Height = 110,
ForeColor = Color.FromArgb(100, 160, 220),
Padding = new Padding(8)
};
var timeFlow = new FlowLayoutPanel
{
Dock = DockStyle.Fill,
FlowDirection = FlowDirection.LeftToRight,
WrapContents = false,
AutoSize = false
};
dtpDate = new DateTimePicker
{
Format = DateTimePickerFormat.Short,
Width = 120,
Height = 26,
Value = DateTime.Now,
Margin = new Padding(4, 10, 4, 0)
};
dtpDate.ValueChanged += (s, e) => UpdateTimePreview();
dtpTime = new DateTimePicker
{
Format = DateTimePickerFormat.Time,
ShowUpDown = true,
Width = 100,
Height = 26,
Value = DateTime.Now,
Margin = new Padding(4, 10, 4, 0)
};
dtpTime.ValueChanged += (s, e) => UpdateTimePreview();
var btnSetNow = MakeButton("Now", 70, Color.FromArgb(100, 110, 120));
btnSetNow.Margin = new Padding(4, 10, 4, 0);
btnSetNow.Click += (s, e) =>
{
dtpDate.Value = dtpTime.Value = DateTime.Now;
};
btnApply = MakeButton("Set", 70, Color.FromArgb(70, 140, 200));
btnApply.Margin = new Padding(4, 10, 4, 0);
btnApply.Click += (s, e) => ApplyTime();
lblPreview = new Label
{
AutoSize = false,
Width = 300,
Height = 20,
ForeColor = Color.FromArgb(140, 150, 160),
Font = new Font("Segoe UI", 8.5f, FontStyle.Italic),
Margin = new Padding(4, 14, 0, 0)
};
timeFlow.Controls.AddRange(new Control[]
{
dtpDate, dtpTime, btnSetNow, btnApply, lblPreview
});
grpTime.Controls.Add(timeFlow);
// ---- Tabs -------------------------------------------------------
tabMain = new TabControl
{
Dock = DockStyle.Fill,
DrawMode = TabDrawMode.OwnerDrawFixed,
SizeMode = TabSizeMode.Fixed,
ItemSize = new Size(120, 28)
};
tabMain.DrawItem += DrawTab;
tabProcesses = new TabPage("Processes");
tabPatterns = new TabPage("Auto-Inject Rules");
tabLog = new TabPage("Log");
StyleTab(tabProcesses);
StyleTab(tabPatterns);
StyleTab(tabLog);
BuildProcessTab();
BuildPatternsTab();
BuildLogTab();
tabMain.TabPages.AddRange(new[] { tabProcesses, tabPatterns, tabLog });
Controls.Add(tabMain);
Controls.Add(grpTime);
}
// =====================================================================
// Process Tab
// =====================================================================
private void BuildProcessTab()
{
var panel = new Panel { Dock = DockStyle.Fill };
// Top toolbar
var toolbar = new FlowLayoutPanel
{
Dock = DockStyle.Top,
Height = 40,
Padding = new Padding(4)
};
lblProcSearch = new Label { Text = "Search:", AutoSize = true, Margin = new Padding(4, 8, 2, 0) };
txtProcSearch = new TextBox { Width = 180, Margin = new Padding(0, 6, 8, 0) };
txtProcSearch.TextChanged += (s, e) => FilterProcessList();
btnRefresh = MakeButton("⟳ Refresh", 90, Color.FromArgb(100, 110, 120));
btnRefresh.Margin = new Padding(0, 6, 4, 0);
btnRefresh.Click += (s, e) => RefreshProcessList();
toolbar.Controls.AddRange(new Control[] { lblProcSearch, txtProcSearch, btnRefresh });
toolbar.BackColor = Color.FromArgb(55, 62, 74);
// Single process list with Inject checkbox
var lblSection = MakeSectionLabel("Processes");
dgvProcesses = MakeGrid();
dgvProcesses.ReadOnly = false;
dgvProcesses.MultiSelect = false;
dgvProcesses.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;
dgvProcesses.Columns.AddRange(
Col("PID", 50), Col("Name", 160), Col("Path", 380), BoolCol("Injected", 70));
// Make all columns read-only except the checkbox
foreach (DataGridViewColumn col in dgvProcesses.Columns)
{
if (col.Name != "Injected")
col.ReadOnly = true;
}
dgvProcesses.CellValueChanged += dgvProcesses_CellValueChanged;
dgvProcesses.CurrentCellDirtyStateChanged += (s, e) =>
{
if (dgvProcesses.IsCurrentCellDirty)
{
dgvProcesses.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
};
panel.Controls.Add(lblSection);
panel.Controls.Add(dgvProcesses);
panel.Controls.Add(toolbar);
tabProcesses.Controls.Add(panel);
}
private List<ProcessRow> _allRows = new List<ProcessRow>();
private class ProcessRow
{
public int Id;
public string Name, Path;
public bool Injected;
}
private void dgvProcesses_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex < 0 || e.ColumnIndex < 0) return;
if (dgvProcesses.Columns[e.ColumnIndex].Name != "Injected") return;
var pidCell = dgvProcesses.Rows[e.RowIndex].Cells[0];
if (pidCell.Value == null) return;
var pid = (int)pidCell.Value;
var shouldInject = (bool)dgvProcesses.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
if (shouldInject)
{
// Inject the process
if (!_injMgr.IsInjected(pid))
{
try
{
var p = Process.GetProcessById(pid);
_injMgr.Inject(p);
var dt = GetFakeTime();
_injMgr.SetFakeTime(p.Id, dt.ToUniversalTime());
AppendLog($"Injected into [{pid}] {p.ProcessName}");
}
catch (Exception ex)
{
MessageBox.Show($"Injection failed:\n{ex.Message}", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
// Revert checkbox on failure
dgvProcesses.BeginInvoke((Action)(() =>
{
dgvProcesses.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = false;
}));
}
}
}
else
{
// Eject the process
if (_injMgr.IsInjected(pid))
{
_injMgr.Eject(pid);
AppendLog($"Ejected from [{pid}]");
}
}
}
private void RefreshProcessList()
{
_allRows.Clear();
// Get current live process IDs
var livePids = new HashSet<int>(Process.GetProcesses().Select(p => p.Id));
// Remove dead processes from injection manager
var deadPids = _injMgr.InjectedProcesses
.Select(x => x.ProcessId)
.Where(pid => !livePids.Contains(pid))
.ToList();
foreach (var deadPid in deadPids)
{
_injMgr.Eject(deadPid);
}
var injectedPids = new HashSet<int>(_injMgr.InjectedProcesses.Select(x => x.ProcessId));
foreach (var p in Process.GetProcesses().OrderBy(x => x.ProcessName))
{
var path = "";
try
{
path = p.MainModule?.FileName ?? "";
}
catch
{
// Skip processes we can't access
continue;
}
_allRows.Add(new ProcessRow
{
Id = p.Id,
Name = p.ProcessName,
Path = path,
Injected = injectedPids.Contains(p.Id)
});
}
FilterProcessList();
}
private void FilterProcessList()
{
var q = txtProcSearch.Text.Trim().ToLower();
dgvProcesses.SuspendLayout();
dgvProcesses.Rows.Clear();
foreach (var r in _allRows)
{
if (q.Length > 0 && !r.Name.ToLower().Contains(q) && !r.Path.ToLower().Contains(q)) continue;
dgvProcesses.Rows.Add(r.Id, r.Name, r.Path, r.Injected);
}
dgvProcesses.ResumeLayout();
}
// =====================================================================
// Patterns Tab
// =====================================================================
// Patterns Tab
// =====================================================================
private void BuildPatternsTab()
{
var panel = new Panel { Dock = DockStyle.Fill };
var toolbar = new FlowLayoutPanel
{
Dock = DockStyle.Top,
Height = 80,
Padding = new Padding(4),
BackColor = Color.FromArgb(55, 62, 74)
};
// Pattern input row
var lblNew = new Label { Text = "Pattern:", AutoSize = true, Margin = new Padding(4, 12, 4, 0) };
txtNewPattern = new TextBox
{ Width = 280, Margin = new Padding(0, 10, 4, 0), Text = "e.g. C:\\Games\\MyGame\\* or ^.*chrome.*$" };
rdoGlob = new RadioButton
{
Text = "Glob", Checked = true, AutoSize = true, Margin = new Padding(4, 12, 4, 0),
ForeColor = Color.FromArgb(200, 200, 200)
};
rdoRegex = new RadioButton
{
Text = "Regex", AutoSize = true, Margin = new Padding(4, 12, 4, 0),
ForeColor = Color.FromArgb(200, 200, 200)
};
btnAddPattern = MakeButton("+ Add Rule", 100, Color.FromArgb(80, 160, 100));
btnAddPattern.Margin = new Padding(8, 8, 4, 0);
btnAddPattern.Click += OnAddPattern;
btnRemovePattern = MakeButton("✕ Remove", 90, Color.FromArgb(190, 90, 90));
btnRemovePattern.Margin = new Padding(4, 8, 4, 0);
btnRemovePattern.Click += OnRemovePattern;
toolbar.Controls.AddRange(new Control[]
{
lblNew, txtNewPattern, rdoGlob, rdoRegex,
btnAddPattern, btnRemovePattern
});
var lblSection = MakeSectionLabel("Auto-Inject Rules (process path or name must match)");
dgvPatterns = MakeGrid();
dgvPatterns.Columns.AddRange(
Col("Pattern", 320), Col("Type", 60), BoolCol("Enabled"));
panel.Controls.Add(dgvPatterns);
panel.Controls.Add(lblSection);
panel.Controls.Add(toolbar);
tabPatterns.Controls.Add(panel);
}
private void OnAddPattern(object sender, EventArgs e)
{
var pat = txtNewPattern.Text.Trim();
if (string.IsNullOrEmpty(pat)) return;
var rule = new PatternRule
{
Pattern = pat,
UseRegex = rdoRegex.Checked,
Enabled = true
};
_watcher.AddRule(rule);
dgvPatterns.Rows.Add(pat, rule.UseRegex ? "Regex" : "Glob", true);
txtNewPattern.Clear();
}
private void OnRemovePattern(object sender, EventArgs e)
{
if (dgvPatterns.SelectedRows.Count == 0) return;
var idx = dgvPatterns.SelectedRows[0].Index;
var pat = dgvPatterns.Rows[idx].Cells[0].Value?.ToString();
_watcher.ClearRules();
dgvPatterns.Rows.RemoveAt(idx);
// Re-add remaining
foreach (DataGridViewRow row in dgvPatterns.Rows)
_watcher.AddRule(new PatternRule
{
Pattern = row.Cells[0].Value?.ToString() ?? "",
UseRegex = row.Cells[1].Value?.ToString() == "Regex",
Enabled = (bool)(row.Cells[2].Value ?? true)
});
}
// =====================================================================
// Log Tab
// =====================================================================
private void BuildLogTab()
{
rtbLog = new RichTextBox
{
Dock = DockStyle.Fill,
BackColor = Color.FromArgb(30, 35, 42),
ForeColor = Color.FromArgb(170, 210, 150),
Font = new Font("Consolas", 9f),
ReadOnly = true,
ScrollBars = RichTextBoxScrollBars.Vertical
};
btnClearLog = MakeButton("Clear", 70, Color.FromArgb(100, 110, 120));
btnClearLog.Dock = DockStyle.Bottom;
btnClearLog.Click += (s, e) => rtbLog.Clear();
tabLog.Controls.Add(rtbLog);
tabLog.Controls.Add(btnClearLog);
}
// =====================================================================
// Time Logic
// =====================================================================
private DateTime GetFakeTime()
{
// Return current real time + stored delta (time advances naturally)
return DateTime.Now + _fakeDelta;
}
private void ApplyTime()
{
// Calculate the desired time from the picker
var desiredTime = dtpDate.Value.Date + dtpTime.Value.TimeOfDay;
// Store the delta (offset from real time)
_fakeDelta = desiredTime - DateTime.Now;
// Apply to all injected processes
var dt = GetFakeTime().ToUniversalTime();
_injMgr.SetFakeTimeAll(dt);
_watcher.FakeUtc = dt;
UpdateTimePreview();
}
private void UpdateTimePreview()
{
var dt = GetFakeTime();
// Use the stored delta (constant offset)
string deltaStr = FormatDelta(_fakeDelta);
lblPreview.Text = $"Fake: {dt:yyyy-MM-dd HH:mm:ss} (local, offset {deltaStr})";
}
private static string FormatDelta(TimeSpan delta)
{
bool isNegative = delta.TotalSeconds < 0;
var absDelta = delta.Duration();
var parts = new List<string>();
// Days
if (absDelta.Days > 0)
parts.Add($"{absDelta.Days}d");
// Hours
if (absDelta.Hours > 0)
parts.Add($"{absDelta.Hours}h");
// Minutes
if (absDelta.Minutes > 0)
parts.Add($"{absDelta.Minutes}m");
// Seconds (always show if no other units, or if under a minute)
if (parts.Count == 0 || absDelta.Seconds > 0)
parts.Add($"{absDelta.Seconds}s");
var result = string.Join("", parts);
return isNegative ? $"-{result}" : $"+{result}";
}
// =====================================================================
// Helpers
// =====================================================================
private void AppendLog(string msg)
{
if (rtbLog == null) return;
if (rtbLog.InvokeRequired)
{
rtbLog.BeginInvoke((Action)(() => AppendLog(msg)));
return;
}
rtbLog.AppendText($"[{DateTime.Now:HH:mm:ss}] {msg}\n");
rtbLog.ScrollToCaret();
}
private static DataGridView MakeGrid()
{
var g = new DataGridView
{
Dock = DockStyle.Fill,
ReadOnly = true,
AllowUserToAddRows = false,
AllowUserToDeleteRows = false,
SelectionMode = DataGridViewSelectionMode.FullRowSelect,
MultiSelect = false,
BackgroundColor = Color.FromArgb(52, 58, 68),
ForeColor = Color.FromArgb(175, 180, 185),
GridColor = Color.FromArgb(85, 92, 102),
BorderStyle = BorderStyle.None,
RowHeadersVisible = false,
AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells,
ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize,
ColumnHeadersHeight = 28
};
g.EnableHeadersVisualStyles = false;
g.ColumnHeadersDefaultCellStyle.BackColor = Color.FromArgb(72, 78, 88);
g.ColumnHeadersDefaultCellStyle.ForeColor = Color.FromArgb(160, 185, 210);
g.DefaultCellStyle.SelectionBackColor = Color.FromArgb(98, 138, 178);
g.AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(58, 64, 74);
return g;
}
private static DataGridViewTextBoxColumn Col(string name, int w)
{
return new DataGridViewTextBoxColumn
{
Name = name,
HeaderText = name,
Width = w,
MinimumWidth = w,
SortMode = DataGridViewColumnSortMode.NotSortable
};
}
private static DataGridViewCheckBoxColumn BoolCol(string name, int width = 65)
{
return new DataGridViewCheckBoxColumn
{
Name = name,
HeaderText = name,
Width = width,
MinimumWidth = width
};
}
private static Button MakeButton(string text, int w, Color bg)
{
return new Button
{
Text = text,
Width = w,
Height = 26,
BackColor = bg,
ForeColor = Color.White,
FlatStyle = FlatStyle.Flat,
Cursor = Cursors.Hand
};
}
private static Label MakeSectionLabel(string text)
{
return new Label
{
Text = text,
Dock = DockStyle.Top,
Height = 22,
ForeColor = Color.FromArgb(150, 180, 220),
Font = new Font("Segoe UI", 8.5f, FontStyle.Bold),
Padding = new Padding(4, 2, 0, 0),
BackColor = Color.FromArgb(50, 57, 69)
};
}
private static void StyleTab(TabPage tab)
{
tab.BackColor = Color.FromArgb(45, 52, 64);
tab.ForeColor = Color.FromArgb(200, 200, 200);
}
private void DrawTab(object sender, DrawItemEventArgs e)
{
var tab = (TabControl)sender;
var page = tab.TabPages[e.Index];
var rect = e.Bounds;
var selected = e.Index == tab.SelectedIndex;
using var bg = new SolidBrush(selected ? Color.FromArgb(80, 130, 180) : Color.FromArgb(60, 68, 80));
e.Graphics.FillRectangle(bg, rect);
var sf = new StringFormat
{ Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center };
using var fg = new SolidBrush(selected ? Color.White : Color.FromArgb(170, 180, 190));
e.Graphics.DrawString(page.Text, Font, fg, rect, sf);
}
private static void ShowInfo(string msg)
{
MessageBox.Show(msg, "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
// Stop preview update timer
_previewUpdateTimer?.Stop();
_previewUpdateTimer?.Dispose();
// Save config
_config.Patterns.Clear();
foreach (DataGridViewRow row in dgvPatterns.Rows)
{
_config.Patterns.Add(new PatternRuleDto
{
Pattern = row.Cells[0].Value?.ToString() ?? "",
UseRegex = row.Cells[1].Value?.ToString() == "Regex",
Enabled = (bool)(row.Cells[2].Value ?? true)
});
}
_config.Save();
_watcher.Stop();
_injMgr.Dispose();
base.OnFormClosing(e);
}
}
}
-58
View File
@@ -1,58 +0,0 @@
using System;
using System.Windows.Forms;
using TimeMocker.UI.Forms;
namespace TimeMocker.UI
{
internal static class Program
{
[STAThread]
private static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// EasyHook requires elevated privileges for cross-process injection
if (!IsElevated())
{
var result = MessageBox.Show(
"TimeMocker needs to run as Administrator to inject into other processes.\n\n" +
"Please restart as Administrator.",
"Elevation Required",
MessageBoxButtons.OKCancel,
MessageBoxIcon.Warning);
if (result == DialogResult.OK)
RestartAsAdmin();
return;
}
Application.Run(new MainForm());
}
private static bool IsElevated()
{
using var id = System.Security.Principal.WindowsIdentity.GetCurrent();
var principal = new System.Security.Principal.WindowsPrincipal(id);
return principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
}
private static void RestartAsAdmin()
{
var info = new System.Diagnostics.ProcessStartInfo
{
FileName = Application.ExecutablePath,
UseShellExecute = true,
Verb = "runas"
};
try
{
System.Diagnostics.Process.Start(info);
}
catch
{
/* user cancelled UAC */
}
}
}
}
-53
View File
@@ -1,53 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net48</TargetFramework>
<Platforms>x64</Platforms>
<OutputType>WinExe</OutputType>
<AssemblyName>TimeMocker</AssemblyName>
<RootNamespace>TimeMocker.UI</RootNamespace>
<UseWindowsForms>true</UseWindowsForms>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<LangVersion>8</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="EasyHook" Version="2.7.7097.0"/>
<PackageReference Include="System.Text.Json" Version="8.0.5"/>
</ItemGroup>
<!-- Build both x86 and x64 versions of the hook DLL and copy with architecture suffix -->
<Target Name="BuildAllHookDlls" AfterTargets="Build" DependsOnTargets="_BuildX64Hook;_BuildX86Hook;_CopyHookDlls">
</Target>
<Target Name="_BuildX64Hook">
<MSBuild Projects="$(SolutionDir)TimeMocker.Hook\TimeMocker.Hook.csproj"
Properties="Platform=x64;Configuration=$(Configuration)"
Targets="Build"
RunEachTargetSeparately="true" />
</Target>
<Target Name="_BuildX86Hook">
<MSBuild Projects="$(SolutionDir)TimeMocker.Hook\TimeMocker.Hook.csproj"
Properties="Platform=x86;Configuration=$(Configuration)"
Targets="Build"
RunEachTargetSeparately="true" />
</Target>
<Target Name="_CopyHookDlls" DependsOnTargets="_BuildX64Hook;_BuildX86Hook">
<PropertyGroup>
<HookBuildDir>$(SolutionDir)TimeMocker.Hook\bin\</HookBuildDir>
<X64DllPath>$(HookBuildDir)x64\$(Configuration)\net48\TimeMocker.Hook.dll</X64DllPath>
<X86DllPath>$(HookBuildDir)x86\$(Configuration)\net48\TimeMocker.Hook.dll</X86DllPath>
<X64Dest>$(OutputPath)TimeMocker.Hook.x64.dll</X64Dest>
<X86Dest>$(OutputPath)TimeMocker.Hook.x86.dll</X86Dest>
</PropertyGroup>
<!-- Copy x64 version with x64 suffix -->
<Copy SourceFiles="$(X64DllPath)"
DestinationFiles="$(X64Dest)"
SkipUnchangedFiles="true" />
<!-- Copy x86 version with x86 suffix -->
<Copy SourceFiles="$(X86DllPath)"
DestinationFiles="$(X86Dest)"
SkipUnchangedFiles="true" />
</Target>
<!-- Clean the renamed DLLs as well -->
<Target Name="CleanRenamedHookDlls" AfterTargets="Clean">
<Delete Files="$(OutputPath)TimeMocker.Hook.x64.dll" TreatErrorsAsWarnings="true" />
<Delete Files="$(OutputPath)TimeMocker.Hook.x86.dll" TreatErrorsAsWarnings="true" />
</Target>
</Project>
-25
View File
@@ -1,25 +0,0 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TimeMocker.UI", "TimeMocker.UI\TimeMocker.UI.csproj", "{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TimeMocker.Hook", "TimeMocker.Hook\TimeMocker.Hook.csproj", "{B2C3D4E5-F6A7-8901-BCDE-F12345678901}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Release|x64 = Release|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Debug|x64.ActiveCfg = Debug|x64
{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Debug|x64.Build.0 = Debug|x64
{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Release|x64.ActiveCfg = Release|x64
{A1B2C3D4-E5F6-7890-ABCD-EF1234567890}.Release|x64.Build.0 = Release|x64
{B2C3D4E5-F6A7-8901-BCDE-F12345678901}.Debug|x64.ActiveCfg = Debug|x64
{B2C3D4E5-F6A7-8901-BCDE-F12345678901}.Debug|x64.Build.0 = Debug|x64
{B2C3D4E5-F6A7-8901-BCDE-F12345678901}.Release|x64.ActiveCfg = Release|x64
{B2C3D4E5-F6A7-8901-BCDE-F12345678901}.Release|x64.Build.0 = Release|x64
EndGlobalSection
EndGlobal
-7
View File
@@ -1,7 +0,0 @@
{
"sdk": {
"version": "10.0.100",
"rollForward": "latestMajor",
"allowPrerelease": true
}
}