diff --git a/.gitignore b/.gitignore index d88f236..34167ad 100644 --- a/.gitignore +++ b/.gitignore @@ -16,4 +16,13 @@ frontend/dist *.swo *~ .DS_Store -vendor/ \ No newline at end of file +vendor/ +setting.json +Backup/ +WebView/ +Log/ +.setting-*.tmp +# Native cache build intermediates +*.lib +*.exp +*.syso diff --git a/app.go b/app.go index c8e0cf2..b0012e3 100644 --- a/app.go +++ b/app.go @@ -5,7 +5,9 @@ import ( "fmt" "os" "path/filepath" + "slices" "strings" + "sync" "time" wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" @@ -21,40 +23,50 @@ import ( "EngineTools/internal/msi" "EngineTools/internal/process" "EngineTools/internal/registry" + "EngineTools/internal/storage" + "EngineTools/internal/uifix" "EngineTools/internal/unlock" "EngineTools/internal/update" ) type App struct { - ctx context.Context - lang i18n.Lang - Logs []string - InstallPath string - EngineVersion string - WindowsVersion string - UTF8Enabled bool - ManifestConfigured bool - IsAdmin bool - StemsPath string - StemsDetected bool - DBPath string - DBDetected bool - Progress float64 + confirmationMu sync.Mutex + confirmationNext uint32 + confirmations map[uint32]chan bool + closing bool + daily *logs.Daily + logsMu sync.Mutex + syncTagsMu sync.Mutex + cache *uifix.Manager + ctx context.Context + lang i18n.Lang + Logs []string + InstallPath string + EngineVersion string + WindowsVersion string + UTF8Enabled bool + ManifestConfigured bool + IsAdmin bool + StemsPath string + StemsDetected bool + DBPath string + DBDetected bool + Progress float64 } type StatusInfo struct { - InstallPath string `json:"installPath"` - EngineVersion string `json:"engineVersion"` - WindowsVersion string `json:"windowsVersion"` - UTF8Enabled bool `json:"utf8Enabled"` - ACPValue string `json:"acpValue"` - ManifestConfigured bool `json:"manifestConfigured"` - IsAdmin bool `json:"isAdmin"` - StemsDetected bool `json:"stemsDetected"` - DBDetected bool `json:"dbDetected"` - DBPath string `json:"dbPath"` - ProcessRunning bool `json:"processRunning"` - RunningProcesses []ProcessItem `json:"runningProcesses"` + InstallPath string `json:"installPath"` + EngineVersion string `json:"engineVersion"` + WindowsVersion string `json:"windowsVersion"` + UTF8Enabled bool `json:"utf8Enabled"` + ACPValue string `json:"acpValue"` + ManifestConfigured bool `json:"manifestConfigured"` + IsAdmin bool `json:"isAdmin"` + StemsDetected bool `json:"stemsDetected"` + DBDetected bool `json:"dbDetected"` + DBPath string `json:"dbPath"` + ProcessRunning bool `json:"processRunning"` + RunningProcesses []ProcessItem `json:"runningProcesses"` } type ProcessItem struct { @@ -68,8 +80,13 @@ type DriveInfo struct { } func NewApp() *App { + lang := i18n.DetectLang() + if settings, err := storage.ReadSettings(); err == nil && settings.Language != "" { + lang = i18n.Lang(settings.Language) + } return &App{ - lang: i18n.DetectLang(), + daily: logs.New(storage.Path("Log")), + lang: lang, Logs: []string{}, IsAdmin: checkIsAdmin(), } @@ -77,8 +94,11 @@ func NewApp() *App { func (a *App) startup(ctx context.Context) { a.ctx = ctx + a.cache = uifix.New() + a.log("EngineTools started") go a.detectStatus() go a.watchDrives() + go a.watchCacheLogs() } // watchDrives polls the set of mounted logical drives and re-runs detection @@ -128,10 +148,79 @@ func findStemsProcessorDir() (string, bool) { } func (a *App) log(msg string) { - timestamp := time.Now().Format("15:04:05") - entry := fmt.Sprintf("[%s] %s", timestamp, msg) + a.logAt("app", msg, time.Time{}) +} + +func (a *App) logAt(source, msg string, at time.Time) { + a.logsMu.Lock() + defer a.logsMu.Unlock() + entry, err := a.daily.Write(source, msg, at) a.Logs = append(a.Logs, entry) - wailsRuntime.EventsEmit(a.ctx, "log", entry) + if len(a.Logs) > 2000 { + a.Logs = slices.Clone(a.Logs[len(a.Logs)-2000:]) + } + if a.ctx != nil { + wailsRuntime.EventsEmit(a.ctx, "log", entry) + } + if err != nil { + failure := "Log write failed: " + err.Error() + fmt.Fprintln(os.Stderr, failure) + if a.ctx != nil { + wailsRuntime.EventsEmit(a.ctx, "log", failure) + } + } +} + +func (a *App) WriteFrontendLog(message string) { + a.logAt("frontend", message, time.Time{}) +} + +func (a *App) GetLogEntries() []string { + a.logsMu.Lock() + defer a.logsMu.Unlock() + return slices.Clone(a.Logs) +} + +func (a *App) watchCacheLogs() { + ticker := time.NewTicker(2 * time.Second) + defer ticker.Stop() + lastState := "" + for { + select { + case <-a.ctx.Done(): + return + case <-ticker.C: + directory, err := registry.FindEngineDJInstallPath() + if err != nil { + continue + } + state := a.cache.Status(directory) + signature := fmt.Sprintf("%d/%t/%s/%s/%s", state.PID, state.Active, state.InstallStatus, state.Error, state.InstallError) + if signature != lastState { + a.logAt("uifix", fmt.Sprintf("状态 PID=%d running=%t active=%t installation=%s error=%q installError=%q", state.PID, state.Running, state.Active, state.InstallStatus, state.Error, state.InstallError), time.Time{}) + lastState = signature + } + if !state.Running { + continue + } + records, dropped := a.cache.DrainFallbacks(state.PID) + if dropped > 0 { + a.logAt("uifix", fmt.Sprintf("回退诊断缓冲区已覆盖 %d 条旧记录", dropped), time.Time{}) + } + for _, record := range records { + kind := "回退" + if record.ExcludedFromStats { + kind = "空接口查询" + } + a.logAt("uifix", fmt.Sprintf("%s PID=%d seq=%d 原因=%s 接口=%q 调用位置=0x%x", kind, state.PID, record.Sequence, record.Reason, record.Interface, record.Caller), record.At) + } + } + } +} + +func (a *App) shutdown(ctx context.Context) { + a.cancelConfirmations() + a.log("EngineTools stopped") } func (a *App) setProgress(value float64) { @@ -287,14 +376,7 @@ func (a *App) FixUnicodeIssues() string { } confirmMsg := fmt.Sprintf(msgs.ProcessRunningMessage, strings.Join(names, "\n")) - result, err := wailsRuntime.MessageDialog(a.ctx, wailsRuntime.MessageDialogOptions{ - Type: wailsRuntime.QuestionDialog, - Title: msgs.ProcessRunningTitle, - Message: confirmMsg, - Buttons: []string{"Yes", "No"}, - }) - - if err != nil || result != "Yes" { + if !a.confirm(msgs.ProcessRunningTitle, confirmMsg) { a.log("User cancelled process termination") return "cancelled" } @@ -354,12 +436,6 @@ func (a *App) FixUnicodeIssues() string { wailsRuntime.EventsEmit(a.ctx, "statusUpdate", a.GetStatus()) - _, _ = wailsRuntime.MessageDialog(a.ctx, wailsRuntime.MessageDialogOptions{ - Type: wailsRuntime.InfoDialog, - Title: msgs.FixComplete, - Message: msgs.FixCompleteTip, - }) - return "ok" } @@ -368,13 +444,7 @@ func (a *App) FixUnicodeIssues() string { func (a *App) RestoreUnicodeFix() string { msgs := i18n.Get(a.lang) - result, err := wailsRuntime.MessageDialog(a.ctx, wailsRuntime.MessageDialogOptions{ - Type: wailsRuntime.QuestionDialog, - Title: msgs.RestoreConfirmTitle, - Message: msgs.RestoreConfirmMessage, - Buttons: []string{"Yes", "No"}, - }) - if err != nil || result != "Yes" { + if !a.confirm(msgs.RestoreConfirmTitle, msgs.RestoreConfirmMessage) { a.log("User cancelled restore") return "cancelled" } @@ -390,13 +460,7 @@ func (a *App) RestoreUnicodeFix() string { names = append(names, fmt.Sprintf("%s (PID: %d)", p.Name, p.PID)) } confirmMsg := fmt.Sprintf(msgs.ProcessRunningMessage, strings.Join(names, "\n")) - res, err := wailsRuntime.MessageDialog(a.ctx, wailsRuntime.MessageDialogOptions{ - Type: wailsRuntime.QuestionDialog, - Title: msgs.ProcessRunningTitle, - Message: confirmMsg, - Buttons: []string{"Yes", "No"}, - }) - if err != nil || res != "Yes" { + if !a.confirm(msgs.ProcessRunningTitle, confirmMsg) { a.log("User cancelled process termination") return "cancelled" } @@ -450,12 +514,6 @@ func (a *App) RestoreUnicodeFix() string { wailsRuntime.EventsEmit(a.ctx, "statusUpdate", a.GetStatus()) - _, _ = wailsRuntime.MessageDialog(a.ctx, wailsRuntime.MessageDialogOptions{ - Type: wailsRuntime.InfoDialog, - Title: msgs.RestoreComplete, - Message: msgs.RestoreCompleteTip, - }) - return "ok" } @@ -490,13 +548,7 @@ func (a *App) ListBackups() []database.BackupInfo { func (a *App) RestoreDatabase(filename string) string { msgs := i18n.Get(a.lang) - result, err := wailsRuntime.MessageDialog(a.ctx, wailsRuntime.MessageDialogOptions{ - Type: wailsRuntime.QuestionDialog, - Title: msgs.DBRestoreConfirmTitle, - Message: msgs.DBRestoreConfirmMessage, - Buttons: []string{"Yes", "No"}, - }) - if err != nil || result != "Yes" { + if !a.confirm(msgs.DBRestoreConfirmTitle, msgs.DBRestoreConfirmMessage) { a.log("User cancelled database restore") return "cancelled" } @@ -545,8 +597,8 @@ func (a *App) OptimizeDatabase() string { return "ok" } -func (a *App) ListPlaylists() []database.PlaylistInfo { - playlists, err := database.ListPlaylists() +func (a *App) ListPlaylists(targetLibrary string) []database.PlaylistInfo { + playlists, err := database.ListPlaylists(targetLibrary) if err != nil { a.log(fmt.Sprintf("Playlist error: %v", err)) return []database.PlaylistInfo{} @@ -688,13 +740,7 @@ func (a *App) ScanMSIOrphans() []msi.OrphanedMSI { func (a *App) CleanMSIOrphans(productCodes []string) string { msgs := i18n.Get(a.lang) - result, err := wailsRuntime.MessageDialog(a.ctx, wailsRuntime.MessageDialogOptions{ - Type: wailsRuntime.QuestionDialog, - Title: msgs.MSIConfirmTitle, - Message: msgs.MSIConfirmMessage, - Buttons: []string{"Yes", "No"}, - }) - if err != nil || result != "Yes" { + if !a.confirm(msgs.MSIConfirmTitle, msgs.MSIConfirmMessage) { a.log("User cancelled MSI cleanup") return "cancelled" } @@ -717,13 +763,8 @@ func (a *App) CleanMSIOrphans(productCodes []string) string { func (a *App) HandleUTF8AlreadyEnabled() string { msgs := i18n.Get(a.lang) - _, _ = wailsRuntime.MessageDialog(a.ctx, wailsRuntime.MessageDialogOptions{ - Type: wailsRuntime.WarningDialog, - Title: msgs.UTF8AlreadyEnabled, - Message: msgs.UTF8AlreadyEnabledTip, - }) - - return "" + a.log(msgs.UTF8AlreadyEnabledTip) + return msgs.UTF8AlreadyEnabled + "\n" + msgs.UTF8AlreadyEnabledTip } func (a *App) OpenRegionSettings() string { @@ -820,12 +861,44 @@ func (a *App) SelectDrive(drive string) string { } func (a *App) SetLanguage(lang string) string { + if err := storage.UpdateSettings(func(s *storage.Settings) { s.Language = lang }); err != nil { + return err.Error() + } a.lang = i18n.Lang(lang) go a.detectStatus() return "" } // ---- ID3 Editor ---- +func (a *App) GetSettings() (storage.Settings, error) { + s, err := storage.ReadSettings() + if s.Language == "" { + s.Language = string(a.lang) + } + return s, err +} + +func (a *App) ClearCompatibilityRecords(key string) error { + return a.cache.ClearCompatibilityRecords(key) +} + +func (a *App) SaveSettings(settings storage.Settings) error { + if settings.Theme != "orange" && settings.Theme != "dark" && settings.Theme != "light" { + return fmt.Errorf("Unknown UI theme: %s", settings.Theme) + } + switch settings.Language { + case "zh", "en", "ja", "ko": + default: + return fmt.Errorf("Unknown language: %s", settings.Language) + } + return storage.UpdateSettings(func(s *storage.Settings) { + s.Language = settings.Language + s.Theme = settings.Theme + s.SquareCorners = settings.SquareCorners + s.AlwaysOnTop = settings.AlwaysOnTop + s.ExperimentalEnabled = settings.ExperimentalEnabled + }) +} // ID3PickFile opens a native file dialog for the user to select an audio file. func (a *App) ID3PickFile() string { @@ -975,8 +1048,8 @@ func (a *App) ID3AntiPiracyRestorePaths(backupKey string) string { } // ID3AntiPiracyV1Playlist clears tags for all tracks in the given playlist. -func (a *App) ID3AntiPiracyV1Playlist(playlistID int) string { - tracks, err := database.GetPlaylistTrackPaths(playlistID) +func (a *App) ID3AntiPiracyV1Playlist(playlistID int, targetLibrary string) string { + tracks, err := database.GetPlaylistTrackPaths(playlistID, targetLibrary) if err != nil || len(tracks) == 0 { a.log(fmt.Sprintf("Anti-piracy playlist fetch error: %v", err)) return "" @@ -996,8 +1069,8 @@ func (a *App) ID3AntiPiracyV1Playlist(playlistID int) string { } // ID3AntiPiracyV2Playlist shuffles tags among all tracks in the given playlist. -func (a *App) ID3AntiPiracyV2Playlist(playlistID int) string { - tracks, err := database.GetPlaylistTrackPaths(playlistID) +func (a *App) ID3AntiPiracyV2Playlist(playlistID int, targetLibrary string) string { + tracks, err := database.GetPlaylistTrackPaths(playlistID, targetLibrary) if err != nil || len(tracks) == 0 { a.log(fmt.Sprintf("Anti-piracy playlist fetch error: %v", err)) return "" @@ -1159,18 +1232,44 @@ func (a *App) GetAvailableLanguages() []map[string]string { return result } -// shutdown is called by Wails when the application is closing. -// Context cancellation propagates to the watchDrives goroutine via a.ctx.Done(). -func (a *App) shutdown(ctx context.Context) {} +func (a *App) GetEngineCacheStatus() uifix.State { + directory, _ := registry.FindEngineDJInstallPath() + return a.cache.Status(directory) +} + +func (a *App) InstallEngineCache() string { + directory, err := registry.FindEngineDJInstallPath() + if err == nil { + err = a.cache.Install(directory) + } + if err != nil { + a.log(err.Error()) + return err.Error() + } + a.log("Engine DJ cache installed: version.dll") + return "" +} + +func (a *App) UninstallEngineCache() string { + directory, err := registry.FindEngineDJInstallPath() + if err == nil { + err = a.cache.Uninstall(directory) + } + if err != nil { + a.log(err.Error()) + return err.Error() + } + a.log("Engine DJ cache uninstalled") + return "" +} -// LogExperimentalEnabled records an activation timestamp in the -// experimental_allow.xml audit file (hidden + read-only on disk). +// LogExperimentalEnabled records activation in setting.json. func (a *App) LogExperimentalEnabled() string { if err := experimental.LogEnabled(); err != nil { a.log(fmt.Sprintf("experimental log error: %v", err)) return err.Error() } - a.log("实验性功能已开启(记录已写入审计文件)") + a.log("实验性功能已开启(记录已写入 setting.json)") return "ok" } @@ -1180,7 +1279,7 @@ func (a *App) LogExperimentalEnabled() string { // or in a specific playlist. Covers larger than maxKB kilobytes are // re-encoded as JPEG at progressively lower quality until they fit. // Returns a JSON-serialisable summary of the operation. -func (a *App) CompressCovers(playlistID int, maxKB int) map[string]interface{} { +func (a *App) CompressCovers(playlistID int, maxKB int, targetLibrary string) map[string]interface{} { const defaultMaxKB = 1024 if maxKB <= 0 { maxKB = defaultMaxKB @@ -1192,10 +1291,10 @@ func (a *App) CompressCovers(playlistID int, maxKB int) map[string]interface{} { var err error if playlistID < 0 { a.log(fmt.Sprintf("封面压缩:加载全库曲目...")) - tracks, err = database.GetAllTrackPaths() + tracks, err = database.GetAllTrackPaths(targetLibrary) } else { a.log(fmt.Sprintf("封面压缩:加载播放列表 %d 的曲目...", playlistID)) - tracks, err = database.GetPlaylistTrackPaths(playlistID) + tracks, err = database.GetPlaylistTrackPaths(playlistID, targetLibrary) } if err != nil { a.log(fmt.Sprintf("CompressCovers fetch error: %v", err)) @@ -1284,8 +1383,8 @@ func (a *App) GetPlayStats() *database.PlayStats { // ---- Missing Track Scanner ---- // ScanMissingTracks returns all tracks where the file is no longer available. -func (a *App) ScanMissingTracks() []database.MissingTrack { - tracks, err := database.FindMissingTracks() +func (a *App) ScanMissingTracks(targetLibrary string) []database.MissingTrack { + tracks, err := database.FindMissingTracks(targetLibrary) if err != nil { a.log(fmt.Sprintf("ScanMissingTracks error: %v", err)) return []database.MissingTrack{} @@ -1295,7 +1394,7 @@ func (a *App) ScanMissingTracks() []database.MissingTrack { } // RemoveMissingTracks deletes the given track IDs from the library (only if unavailable). -func (a *App) RemoveMissingTracks(ids []int) string { +func (a *App) RemoveMissingTracks(ids []int, targetLibrary string) string { msgs := i18n.Get(a.lang) if a.InstallPath != "" { @@ -1309,7 +1408,7 @@ func (a *App) RemoveMissingTracks(ids []int) string { } } - n, err := database.RemoveMissingTracks(ids) + n, err := database.RemoveMissingTracks(ids, targetLibrary) if err != nil { a.log(fmt.Sprintf("RemoveMissingTracks error: %v", err)) return "" @@ -1321,8 +1420,8 @@ func (a *App) RemoveMissingTracks(ids []int) string { // ---- BPM / Key Sync ---- // GetSyncableTracks returns all analyzed tracks with BPM/Key data ready for write-back. -func (a *App) GetSyncableTracks() []database.SyncableTrack { - tracks, err := database.GetSyncableTracks() +func (a *App) GetSyncableTracks(targetLibrary string) []database.SyncableTrack { + tracks, err := database.GetSyncableTracks(targetLibrary) if err != nil { a.log(fmt.Sprintf("GetSyncableTracks error: %v", err)) return []database.SyncableTrack{} @@ -1333,9 +1432,13 @@ func (a *App) GetSyncableTracks() []database.SyncableTrack { // SyncBPMKeyToTags writes Engine DJ's BPM and musical key analysis back into // each track file's ID3/RIFF tags. Only available, analyzed tracks are processed. // Returns a JSON-serialisable summary of successes and failures. -func (a *App) SyncBPMKeyToTags() map[string]interface{} { +func (a *App) SyncBPMKeyToTags(targetLibrary string) map[string]interface{} { + if !a.syncTagsMu.TryLock() { + return map[string]interface{}{"error": "BPM/Key write-back is already running"} + } + defer a.syncTagsMu.Unlock() a.log("正在获取分析数据...") - tracks, err := database.GetSyncableTracks() + tracks, err := database.GetSyncableTracks(targetLibrary) if err != nil { a.log(fmt.Sprintf("SyncBPMKeyToTags: fetch error: %v", err)) return map[string]interface{}{"error": err.Error()} @@ -1402,4 +1505,4 @@ func checkIsAdmin() bool { return false } return member -} \ No newline at end of file +} diff --git a/build/windows/info.json b/build/windows/info.json index 9727946..38feca5 100644 --- a/build/windows/info.json +++ b/build/windows/info.json @@ -1,10 +1,13 @@ { "fixed": { - "file_version": "{{.Info.ProductVersion}}" + "file_version": "{{.Info.ProductVersion}}", + "product_version": "{{.Info.ProductVersion}}", + "flags": "Prerelease" }, "info": { - "0000": { - "ProductVersion": "{{.Info.ProductVersion}}", + "0409": { + "ProductVersion": "{{.Info.ProductVersion}} Preview", + "FileVersion": "{{.Info.ProductVersion}}.0", "CompanyName": "{{.Info.CompanyName}}", "FileDescription": "{{.Info.ProductName}}", "LegalCopyright": "{{.Info.Copyright}}", diff --git a/build/windows/mingw-no-default-manifest.specs b/build/windows/mingw-no-default-manifest.specs new file mode 100644 index 0000000..aa4489e --- /dev/null +++ b/build/windows/mingw-no-default-manifest.specs @@ -0,0 +1,2 @@ +*endfile: +%{mdaz-ftz:crtfastmath.o%s;Ofast|ffast-math|funsafe-math-optimizations:%{!shared:%{!mno-daz-ftz:crtfastmath.o%s}}} %{fvtable-verify=none:%s; fvtable-verify=preinit:vtv_end.o%s; fvtable-verify=std:vtv_end.o%s} crtend.o%s diff --git a/elevation.go b/elevation.go new file mode 100644 index 0000000..c1ad468 --- /dev/null +++ b/elevation.go @@ -0,0 +1,5 @@ +//go:build !bindings + +package main + +func shouldElevate() bool { return true } diff --git a/elevation_bindings.go b/elevation_bindings.go new file mode 100644 index 0000000..060d4c2 --- /dev/null +++ b/elevation_bindings.go @@ -0,0 +1,6 @@ +//go:build bindings + +package main + +// Binding generation runs a temporary executable without opening the application. +func shouldElevate() bool { return false } diff --git a/frontend/src/App.vue b/frontend/src/App.vue index 08a53cd..0377057 100644 --- a/frontend/src/App.vue +++ b/frontend/src/App.vue @@ -1,9 +1,18 @@ @@ -1490,50 +1936,9 @@ onMounted(async () => { - -
- -
-
{{ msgs.msiCleanupTitle || 'MSI Cleanup' }}
-
- {{ msgs.msiCleanupDescription || 'For Engine DJ install/uninstall/update residual file issues' }} -
- -
- -
-
-
{{ msgs.msiNoOrphans || 'No MSI orphans found' }}
-
-
- -
-
{{ msgs.msiFoundOrphans ? msgs.msiFoundOrphans.replace('%d', msiOrphans.length) : `Found ${msiOrphans.length} orphans` }}
- - -
- + +
+
{{ msgs.id3EditorTitle || 'ID3 标签编辑' }}
@@ -1581,7 +1986,89 @@ onMounted(async () => {
+ +
+ +
+
{{ msgs.bpmKeySyncTitle || 'BPM / Key → ID3 Sync' }}
+
{{ msgs.bpmKeySyncDesc || '将 Engine DJ 分析出的 BPM 和调号写回音频文件标签(TBPM / TKEY)' }}
+ + + +
+
+
+ +
+
{{ msgs.coverCompressTitle || 'Cover Art Compression' }}
+ +
+ {{ msgs.coverCompressTip || 'Compressing covers to ≤1 MB improves Engine OS USB load performance.' }} +
+ + + + + + + + +
+
+
+ + + +
+
{{ msgs.usbUnlockTitle || 'USB Unlock' }}
@@ -1662,7 +2154,8 @@ onMounted(async () => {
- + +
{{ msgs.midi2Title || 'MIDI 2.0 Control' }}
@@ -1715,7 +2208,55 @@ onMounted(async () => {
+
+
+ +
+
{{ msgs.msiCleanupTitle || 'MSI Cleanup' }}
+
+ {{ msgs.msiCleanupDescription || 'For Engine DJ install/uninstall/update residual file issues' }} +
+ +
+
+
+
{{ msgs.msiNoOrphans || 'No MSI orphans found' }}
+
+
+ +
+
{{ msgs.msiFoundOrphans ? msgs.msiFoundOrphans.replace('%d', msiOrphans.length) : `Found ${msiOrphans.length} orphans` }}
+ + +
+
+ + + +
+
{{ msgs.logAnalysisTitle || 'Log Analysis' }}
@@ -1777,86 +2318,8 @@ onMounted(async () => {
- - -
-
{{ msgs.bpmKeySyncTitle || 'BPM / Key → ID3 Sync' }}
-
{{ msgs.bpmKeySyncDesc || '将 Engine DJ 分析出的 BPM 和调号写回音频文件标签(TBPM / TKEY)' }}
- - - -
- - -
-
{{ msgs.coverCompressTitle || 'Cover Art Compression' }}
- - -
- {{ msgs.coverCompressTip || 'Compressing covers to ≤1 MB improves Engine OS USB load performance.' }} -
- - - - - - - - -
- + +
{{ msgs.cacheCleanTitle || 'Cache Cleanup' }}
@@ -1869,10 +2332,62 @@ onMounted(async () => { {{ cacheBusy ? (msgs.cacheClearing || 'Clearing...') : (msgs.cacheCleanButton || 'Clear Cache') }}
+
+
+
+
{{ compatibilityText.title }} {{ compatibilityRecords.length }}
+
+ + +
+
+

{{ compatibilityText.description }}

+

{{ compatibilityText.empty }}

+
+
+
+
Engine DJ · {{ (record.hashes?.['Engine DJ.exe'] || record.key).slice(0, 12) }}
+
{{ compatibilityText.checked }}: {{ formatCheckTime(record.checkedAt) }} · {{ compatibilityText.callers }}: {{ record.callers?.length || 0 }}
+
+ +
+
+ {{ compatibilityText.details }} +
+ +
{{ compatibilityText.validator }}
{{ record.validator }}
+
{{ compatibilityText.callers }} · RVA
{{ (record.callers || []).map(value => '0x' + value.toString(16)).join(', ') }}
+
+
+
+
-
+
+
+
{{ uiText.appearance }}
+

{{ uiText.appearanceDesc }}

+
+ +
+
+
{{ uiText.square }}

{{ uiText.squareDesc }}

+ +
+

{{ uiText.session }}

+
{{ msgs.settingsLanguageLabel || '显示语言' }}
@@ -1886,6 +2401,16 @@ onMounted(async () => {
+ +
+ +
{{ msgs.settingsExperimentalLabel || '实验性功能' }}
@@ -1925,7 +2450,7 @@ onMounted(async () => {
Engine Tools - v{{ APP_VERSION }} + v{{ APP_VERSION_LABEL }}
{{ msgs.settingsContributors || '贡献者' }} @@ -1944,11 +2469,17 @@ onMounted(async () => {
-
-
Console
-
+ +
+ +
+
{{ uiText.emptyLog }}
{{ entry }}
+
@@ -1988,7 +2519,7 @@ onMounted(async () => { height: 100%; background: linear-gradient(90deg, var(--accent) 0%, color-mix(in srgb, var(--accent) 60%, transparent) 100%); border-radius: 2px; - transition: width 0.6s cubic-bezier(.4,0,.2,1); + transition: width var(--motion-duration) var(--motion-ease); } .vis-bar-count { min-width: 24px; @@ -2004,7 +2535,7 @@ onMounted(async () => { padding: 14px 12px; text-align: center; cursor: pointer; - transition: border-color 0.15s, background 0.15s; + transition: border-color var(--motion-duration), background var(--motion-duration); font-size: 12px; color: var(--text-secondary); } @@ -2035,7 +2566,7 @@ onMounted(async () => { border-radius: 11px; position: relative; cursor: pointer; - transition: background 0.2s; + transition: background var(--motion-duration); flex-shrink: 0; } .toggle-switch.on { @@ -2049,7 +2580,7 @@ onMounted(async () => { height: 16px; background: #fff; border-radius: 50%; - transition: transform 0.2s; + transition: transform var(--motion-duration); box-shadow: 0 1px 3px rgba(0,0,0,0.3); } .toggle-switch.on .toggle-knob { @@ -2065,7 +2596,7 @@ onMounted(async () => { font-size: 11px; color: var(--text-secondary); opacity: 0; - animation: marqueeFadeIn 0.4s ease forwards; + animation: marqueeFadeIn var(--motion-duration) ease forwards; max-width: 260px; overflow: hidden; text-overflow: ellipsis; @@ -2079,3 +2610,29 @@ onMounted(async () => { to { opacity: 1; transform: translateY(0); } } + + diff --git a/frontend/src/appearance.js b/frontend/src/appearance.js new file mode 100644 index 0000000..739d1c7 --- /dev/null +++ b/frontend/src/appearance.js @@ -0,0 +1,59 @@ +export const NAV_ITEMS = [ + { id: 'status', icon: 'M3 3h7v7H3z M14 3h7v7h-7z M3 14h7v7H3z M14 14h7v7h-7z', group: 'workspace' }, + { id: 'database', icon: 'M4 5c0-3 16-3 16 0s-16 3-16 0v14c0 3 16 3 16 0V5 M4 12c0 3 16 3 16 0', group: 'workspace' }, + { id: 'audio', icon: 'M9 18V5l12-2v13 M9 9l12-2 M9 18c0 4-7 4-7 0s7-4 7 0 M21 16c0 4-7 4-7 0s7-4 7 0', group: 'workspace' }, + { id: 'devices', icon: 'M4 4h16v11H4z M8 21h8 M12 15v6 M7 8h2 M12 8h5', group: 'maintenance' }, + { id: 'diagnostics', icon: 'M4 3h16v18H4z M7 8h10 M7 12h4 M7 16h7', group: 'maintenance' }, + { id: 'settings', icon: 'M4 6h16 M4 12h16 M4 18h16 M8 3v6 M16 9v6 M10 15v6', group: 'preferences' }, +] + +export const UI_TEXT = { + zh: { + workspace: '工作区', maintenance: '维护工具', preferences: '偏好设置', + status: '状态总览', statusDesc: '查看运行环境、修复编码问题与管理后台缓存。', + database: '曲库管理', databaseDesc: '管理曲库、备份、播放列表与曲目统计。', + audio: '音频文件', audioDesc: '编辑标签、回写分析结果与处理封面。', + devices: '系统与设备', devicesDesc: '检查设备占用、MIDI 设置与安装残留。', + diagnostics: '诊断与清理', diagnosticsDesc: '分析运行日志,清理界面缓存。', + settings: '设置', settingsDesc: '调整外观、语言与窗口行为。', + cacheEnabled: '缓存已启用', compatibility: '字符编码修复', appearance: '界面外观', appearanceDesc: '选择界面样式,立即生效。', + orange: '橙色', dark: '深色', light: '浅色', square: '关闭圆角', squareDesc: '将界面控件切换为直角。', + minimise: '最小化', maximise: '最大化', restoreWindow: '还原窗口', closeWindow: '关闭', session: '设置自动保存,下次启动继续生效', console: '运行日志', expand: '展开日志', collapse: '收起日志', emptyLog: '暂时没有运行日志', + }, + en: { + workspace: 'Workspace', maintenance: 'Maintenance', preferences: 'Preferences', + status: 'Overview', statusDesc: 'Check your environment, fix encoding, and manage the background cache.', + database: 'Music library', databaseDesc: 'Manage libraries, backups, playlists, and track statistics.', + audio: 'Audio files', audioDesc: 'Edit tags, write analysis results, and process cover artwork.', + devices: 'System & devices', devicesDesc: 'Check device locks, MIDI settings, and installer leftovers.', + diagnostics: 'Diagnostics', diagnosticsDesc: 'Review application logs and clear the interface cache.', + settings: 'Settings', settingsDesc: 'Adjust appearance, language, and window behavior.', + cacheEnabled: 'Cache enabled', compatibility: 'Compatibility & encoding', appearance: 'Appearance', appearanceDesc: 'Choose a style. Changes apply immediately.', + orange: 'Orange', dark: 'Dark', light: 'Light', square: 'Square corners', squareDesc: 'Use straight corners for interface controls.', + minimise: 'Minimise', maximise: 'Maximise', restoreWindow: 'Restore window', closeWindow: 'Close', session: 'Settings are saved automatically and restored on startup', console: 'Activity log', expand: 'Expand log', collapse: 'Collapse log', emptyLog: 'No activity yet', + }, + ja: { + workspace: 'ワークスペース', maintenance: 'メンテナンス', preferences: '環境設定', + status: '概要', statusDesc: '動作環境、文字コード修復、バックグラウンドキャッシュを管理します。', + database: '音楽ライブラリ', databaseDesc: 'ライブラリ、バックアップ、プレイリスト、曲の統計を管理します。', + audio: '音声ファイル', audioDesc: 'タグ編集、解析結果の書き込み、カバー画像の処理。', + devices: 'システムとデバイス', devicesDesc: 'デバイスのロック、MIDI 設定、インストール残留を確認します。', + diagnostics: '診断とクリーンアップ', diagnosticsDesc: 'ログを解析し、画面キャッシュを削除します。', + settings: '設定', settingsDesc: '外観、言語、ウィンドウ動作を変更します。', + cacheEnabled: 'キャッシュ有効', compatibility: '互換性と文字コード', appearance: '外観', appearanceDesc: 'スタイルの変更はすぐに反映されます。', + orange: 'オレンジ', dark: 'ダーク', light: 'ライト', square: '角丸を無効化', squareDesc: '操作部品の角を直角にします。', + minimise: '最小化', maximise: '最大化', restoreWindow: '元のサイズに戻す', closeWindow: '閉じる', session: '設定は自動保存され、次回の起動時に復元されます', console: '実行ログ', expand: 'ログを展開', collapse: 'ログを折りたたむ', emptyLog: 'ログはありません', + }, + ko: { + workspace: '작업 공간', maintenance: '유지 관리', preferences: '환경 설정', + status: '개요', statusDesc: '실행 환경, 문자 인코딩 복구 및 백그라운드 캐시를 관리합니다.', + database: '음악 라이브러리', databaseDesc: '라이브러리, 백업, 재생 목록 및 곡 통계를 관리합니다.', + audio: '오디오 파일', audioDesc: '태그 편집, 분석 결과 기록 및 표지 이미지 처리.', + devices: '시스템 및 장치', devicesDesc: '장치 잠금, MIDI 설정 및 설치 잔여물을 확인합니다.', + diagnostics: '진단 및 정리', diagnosticsDesc: '실행 로그를 분석하고 화면 캐시를 정리합니다.', + settings: '설정', settingsDesc: '외관, 언어 및 창 동작을 변경합니다.', + cacheEnabled: '캐시 활성화됨', compatibility: '호환성 및 인코딩', appearance: '화면 스타일', appearanceDesc: '스타일 변경은 즉시 적용됩니다.', + orange: '주황색', dark: '어둡게', light: '밝게', square: '둥근 모서리 끄기', squareDesc: '인터페이스 컨트롤의 모서리를 직각으로 바꿉니다.', + minimise: '최소화', maximise: '최대화', restoreWindow: '창 복원', closeWindow: '닫기', session: '설정은 자동 저장되며 다음 실행 시 복원됩니다', console: '실행 로그', expand: '로그 펼치기', collapse: '로그 접기', emptyLog: '아직 로그가 없습니다', + }, +} diff --git a/frontend/src/main.js b/frontend/src/main.js index f9754fe..6caebeb 100644 --- a/frontend/src/main.js +++ b/frontend/src/main.js @@ -1,5 +1,6 @@ import {createApp} from 'vue' import App from './App.vue' -import './style.css'; +import './style.css' +import './workspace.css' createApp(App).mount('#app') diff --git a/frontend/src/style.css b/frontend/src/style.css index 94e5efb..cce8910 100644 --- a/frontend/src/style.css +++ b/frontend/src/style.css @@ -77,7 +77,7 @@ html, body { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; - animation: marquee-fade 0.4s ease; + animation: marquee-fade var(--motion-duration) ease; } @keyframes marquee-fade { @@ -97,7 +97,7 @@ html, body { align-items: center; cursor: pointer; color: var(--text-dim); - transition: color 0.15s; + transition: color var(--motion-duration); text-decoration: none; } @@ -114,7 +114,7 @@ html, body { font-size: 12px; color: var(--text-dim); cursor: pointer; - transition: color 0.15s; + transition: color var(--motion-duration); white-space: nowrap; } @@ -129,7 +129,7 @@ html, body { background: var(--accent); color: #fff; cursor: pointer; - transition: all 0.15s; + transition: background-color var(--motion-duration), color var(--motion-duration), border-color var(--motion-duration), opacity var(--motion-duration), transform var(--motion-duration); font-weight: 500; } @@ -147,7 +147,7 @@ html, body { font-size: 14px; cursor: pointer; opacity: 0.6; - transition: opacity 0.15s; + transition: opacity var(--motion-duration); background: none; border: none; padding: 0; @@ -236,11 +236,30 @@ html, body { font-weight: 400; } +.status-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + grid-auto-rows: 1fr; + gap: 10px; +} + +.status-grid > .status-card { + min-width: 0; + min-height: 72px; + display: flex; + align-items: center; +} + +.status-grid .status-text { + min-width: 0; + overflow-wrap: anywhere; +} + .status-card { border-radius: var(--radius); padding: 10px 14px; border: 1px solid var(--border); - transition: background 0.15s; + transition: background var(--motion-duration); } .status-success { @@ -305,7 +324,7 @@ html, body { font-weight: 500; font-family: var(--font-sans); cursor: pointer; - transition: all 0.15s; + transition: background-color var(--motion-duration), color var(--motion-duration), border-color var(--motion-duration), opacity var(--motion-duration), transform var(--motion-duration); outline: none; } @@ -354,7 +373,7 @@ html, body { border-radius: 2px; overflow: hidden; opacity: 0; - transition: opacity 0.3s; + transition: opacity var(--motion-duration); } .progress-bar.active { @@ -366,7 +385,7 @@ html, body { background: var(--accent); border-radius: 2px; width: 0%; - transition: width 0.3s ease; + transition: width var(--motion-duration) ease; } .log-section { @@ -518,7 +537,7 @@ html, body { font-weight: 500; font-family: var(--font-sans); cursor: pointer; - transition: all 0.15s; + transition: background-color var(--motion-duration), color var(--motion-duration), border-color var(--motion-duration), opacity var(--motion-duration), transform var(--motion-duration); white-space: nowrap; flex-shrink: 0; } @@ -558,7 +577,7 @@ html, body { font-family: var(--font-sans); padding: 10px 14px; cursor: pointer; - transition: color 0.15s, border-color 0.15s; + transition: color var(--motion-duration), border-color var(--motion-duration); outline: none; margin-bottom: -1px; } @@ -583,7 +602,7 @@ html, body { font-family: var(--font-sans); outline: none; width: 100%; - transition: border-color 0.15s; + transition: border-color var(--motion-duration); } .text-input:focus { @@ -615,7 +634,7 @@ select.text-input { border-radius: var(--radius-sm); padding: 9px 12px; cursor: pointer; - transition: background 0.15s, border-color 0.15s; + transition: background var(--motion-duration), border-color var(--motion-duration); } .msi-item:hover { @@ -660,7 +679,7 @@ select.text-input { border-radius: var(--radius-sm); color: var(--text-dim); cursor: pointer; - transition: background 0.15s, color 0.15s; + transition: background var(--motion-duration), color var(--motion-duration); } .folder-btn:hover { @@ -715,7 +734,7 @@ select.text-input { color: var(--text); font-family: var(--font-sans); cursor: pointer; - transition: background 0.15s, border-color 0.15s, color 0.15s; + transition: background var(--motion-duration), border-color var(--motion-duration), color var(--motion-duration); outline: none; } @@ -876,7 +895,7 @@ select.text-input { font-size: 12px; color: var(--text); cursor: pointer; - transition: background 0.15s, border-color 0.15s; + transition: background var(--motion-duration), border-color var(--motion-duration); } .playlist-chip:hover { @@ -962,26 +981,96 @@ select.text-input { text-align: right; } -/* Toast notification */ -.toast { +/* Operation results and confirmations share the upper-right notification area. */ +.notification-stack { position: fixed; - top: 40px; - left: 50%; - transform: translateX(-50%) translateY(-20px); - background: var(--success); - color: #fff; - padding: 8px 24px; - border-radius: var(--radius-sm); - font-size: 13px; - font-weight: 500; + top: 56px; + right: 16px; z-index: 9999; - opacity: 0; + display: flex; + flex-direction: column; + gap: 10px; + width: min(380px, calc(100vw - 32px)); + overflow: visible; pointer-events: none; - transition: opacity 0.25s, transform 0.25s; } - -.toast.visible { - opacity: 1; - transform: translateX(-50%) translateY(0); +.toast, .confirmation-bubble { + flex-shrink: 0; + padding: 14px 16px; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--bg-card); + color: var(--text); + box-shadow: 0 6px 20px rgba(0,0,0,.2); + font-size: 13px; + line-height: 1.6; + overflow-wrap: anywhere; pointer-events: auto; -} \ No newline at end of file +} +.toast { + display: flex; + align-items: flex-start; + gap: 12px; + border-left: 3px solid var(--success); + width: 100%; +} +.toast-list { position: relative; display: flex; flex-direction: column; gap: 10px; } +.toast-enter-active, .toast-leave-active { transition: opacity 500ms ease, transform 500ms cubic-bezier(.2,.8,.2,1); } +.toast-leave-active { position: absolute; width: 100%; } +.toast-enter-from, .toast-leave-to { opacity: 0; transform: translateX(48px); } +.toast-move { transition: transform 500ms cubic-bezier(.2,.8,.2,1); } +.toast-error { border-left-color: var(--error); } +.toast-warning { border-left-color: var(--warning); } +.toast-info { border-left-color: var(--text-dim); } +.notification-icon { width: 24px; height: 24px; flex-shrink: 0; margin-top: 1px; color: var(--success); } +.toast-error .notification-icon { color: var(--error); } +.toast-warning .notification-icon, .confirmation-bubble .notification-icon { color: var(--warning); } +.toast-info .notification-icon { color: var(--text-dim); } +.toast-copy { flex: 1; min-width: 0; } +.toast-title { display: block; color: var(--text); font-size: 13px; font-weight: 600; line-height: 1.5; } +.toast-description { margin-top: 3px; color: var(--text-dim); font-size: 12px; line-height: 1.6; white-space: pre-line; } +.toast-close { flex-shrink: 0; padding: 0 3px; border: 0; background: transparent; color: var(--text-dim); font: inherit; font-size: 20px; line-height: 1.2; cursor: pointer; } +.toast-close:hover { color: var(--text); } +.confirmation-bubble { display: flex; align-items: flex-start; gap: 12px; border-left: 3px solid var(--warning); } +.confirmation-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 14px; } +.confirmation-actions > .btn { width: auto; margin: 0; min-height: 32px; padding: 6px 14px; } +.confirmation-actions > .btn-primary { color: var(--accent-contrast); } +.status-actions { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); +} + +.status-actions > .btn { + min-width: 0; + min-height: 56px; + padding: 10px 14px; + white-space: normal; + overflow-wrap: anywhere; + line-height: 1.5; + text-align: center; +} + +.status-actions > .btn-secondary, +.status-actions > .btn-primary:only-child { + grid-column: 1 / -1; +} + +.status-actions .fix-button-label { + white-space: pre-line; +} + + +.engine-cache-section { + margin-top: 4px; + padding-top: 14px; + border-top: 1px solid var(--border); +} + +.engine-cache-section > .library-section-title { margin-bottom: 10px; } +.engine-cache-section > .actions { margin-top: 6px; } +.engine-cache-error { + color: var(--error); + font-size: 12px; + line-height: 1.5; + overflow-wrap: anywhere; +} diff --git a/frontend/src/workspace.css b/frontend/src/workspace.css new file mode 100644 index 0000000..3521a19 --- /dev/null +++ b/frontend/src/workspace.css @@ -0,0 +1,429 @@ +/* Workspace layout. Orange keeps the original palette in style.css. */ +:root { + --text-secondary: var(--text-dim); + --accent-contrast: #fff; + --accent-rgb: 255, 107, 0; + --sidebar-bg: var(--bg-card); + --panel-bg: var(--bg-card); + --selection-bg: rgba(255, 107, 0, 0.1); + color-scheme: dark; +} + +:root[data-theme='dark'] { + color-scheme: dark; + --bg: #0a0a0a; + --bg-card: #0a0a0a; + --bg-card-hover: #181818; + --border: #292929; + --control-border: #626262; + --text: #f5f5f5; + --text-dim: #b5b5b5; + --text-muted: #909090; + --accent: #ffffff; + --accent-rgb: 255, 255, 255; + --accent-hover: #dddddd; + --accent-contrast: #0a0a0a; + --success: #4caf50; + --success-border: rgba(76, 175, 80, 0.35); + --warning: #ff9800; + --warning-border: rgba(255, 152, 0, 0.35); + --error: #ff6257; + --error-border: rgba(244, 67, 54, 0.35); + --success-bg: rgba(76, 175, 80, 0.08); + --warning-bg: rgba(255, 152, 0, 0.08); + --error-bg: rgba(244, 67, 54, 0.08); + --selection-bg: rgba(255, 255, 255, 0.1); +} + +:root[data-theme='light'] { + color-scheme: light; + --bg: #ffffff; + --bg-card: #ffffff; + --bg-card-hover: #f0f0f0; + --border: #d8d8d8; + --control-border: #858585; + --text: #111111; + --text-dim: #555555; + --text-muted: #6b6b6b; + --accent: #006972; + --accent-rgb: 30, 204, 217; + --accent-hover: #00545c; + --accent-contrast: #10282a; + --cyan-fill: #1eccd9; + --cyan-selected: #3bd1db; + --cyan-hover: #1ee9f7; + --success: #187426; + --success-border: rgba(33, 133, 41, 0.35); + --warning: #a45100; + --warning-border: rgba(230, 115, 0, 0.40); + --error: #be2020; + --error-border: rgba(211, 34, 34, 0.35); + --success-bg: rgba(33, 133, 41, 0.08); + --warning-bg: rgba(255, 152, 0, 0.10); + --error-bg: rgba(211, 34, 34, 0.08); + --selection-bg: #e3f9fa; +} + +:root[data-theme='light'] :is(.btn-primary, .update-badge:not(.checking), .btn-restore:hover:not(:disabled), .drive-chip.active, .playlist-chip.active) { + background: var(--cyan-fill); + color: var(--accent-contrast); +} + +:root[data-theme='light'] :is(.btn-primary:hover:not(:disabled), .update-badge:hover:not(.checking)) { + background: var(--cyan-hover); +} + +:root[data-theme='light'] :is(.drive-chip.active, .playlist-chip.active, .setting-switch.on, .toggle-switch.on) { + background: var(--cyan-selected); + border-color: var(--accent); +} + +:root[data-theme='light'] .toggle-switch.on .toggle-knob { + background: var(--accent-contrast); +} + +:root[data-theme='light'] .progress-fill, +:root[data-theme='light'] .nav-item.active::before { + background: var(--cyan-fill); +} + +:root[data-corners='square'] { + --radius: 0px; + --radius-sm: 0px; +} + +:root[data-corners='square'] *, +:root[data-corners='square'] *::before, +:root[data-corners='square'] *::after, +:root[data-corners='square'] ::-webkit-scrollbar-thumb { + border-radius: 0 !important; +} + +#app { min-height: 0; height: 100dvh; } +.app-shell { + flex: 1; + min-height: 0; + display: grid; + grid-template-columns: 15% minmax(0, 1fr); + grid-template-rows: 40px minmax(0, 1fr) auto; + grid-template-areas: 'header header' 'sidebar workspace' 'sidebar console'; + background: var(--bg); +} +.app-shell > .header { grid-area: header; min-height: 0; padding: 0 24px 0 12px; background: var(--sidebar-bg); } +.app-shell .app-title { font-size: 16px; letter-spacing: -0.35px; } +.app-shell .header-left { gap: 18px; } +.app-shell .header-right { gap: 16px; } +.sidebar { + grid-area: sidebar; + min-height: 0; + overflow-y: auto; + display: flex; + flex-direction: column; + padding: 16px 10px 12px; + background: var(--sidebar-bg); + border-right: 1px solid var(--border); +} +.nav-group { margin-bottom: 18px; } +.nav-group-title { padding: 0 10px 6px; font-size: 11px; color: var(--text-muted); font-weight: 600; } +.nav-item { + position: relative; + display: flex; + align-items: center; + gap: 9px; + width: 100%; + min-height: 36px; + margin: 2px 0; + padding: 7px 10px; + border: 0; + border-radius: var(--radius-sm); + background: transparent; + color: var(--text-dim); + font: inherit; + font-size: 13px; + text-align: left; + cursor: pointer; + transition: background var(--motion-duration), color var(--motion-duration); +} +.nav-item svg { flex-shrink: 0; } +.nav-item:hover { background: var(--bg-card-hover); color: var(--text); } +.nav-item.active { color: var(--accent); background: var(--selection-bg); font-weight: 600; } +.nav-item.active::before { content: ''; position: absolute; left: 0; top: 10px; bottom: 10px; width: 3px; background: var(--accent); border-radius: 2px; } +.sidebar-version { margin-top: auto; padding: 10px 10px 0; font-size: 11px; color: var(--text-muted); font-variant-numeric: tabular-nums; } +.workspace { grid-area: workspace; min-width: 0; min-height: 0; display: flex; flex-direction: column; overflow: hidden; } +.page-heading { flex-shrink: 0; padding: 25px 28px 19px; } +.page-eyebrow { margin-bottom: 4px; color: var(--text-muted); font-size: 11px; } +.page-heading h1 { color: var(--text); font-size: 25px; font-weight: 600; line-height: 1.3; letter-spacing: -.6px; } +.page-heading p { margin-top: 7px; color: var(--text-dim); font-size: 12px; line-height: 1.6; } +.workspace > .content { padding: 0 28px 24px; gap: 18px; min-height: 0; min-width: 0; } +.workspace > .progress-wrapper { padding: 0; flex-shrink: 0; } +.workspace .btn-primary, .app-shell .update-badge:not(.checking) { color: var(--accent-contrast); } +.workspace .btn { font-weight: 600; font-size: 13px; } +.workspace .text-input { font-size: 13px; } +.workspace .library-section-title { color: var(--text); font-size: 13px; letter-spacing: 0; text-transform: none; } +.workspace .library-stats { line-height: 1.7; } +.workspace .info-value, .workspace .status-detail { font-variant-numeric: tabular-nums; } + +.workspace > .overview-content { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); grid-auto-rows: max-content; align-content: start; } +.overview-content > .info-card { grid-column: 1 / -1; display: grid; grid-template-columns: 1.2fr 2fr .65fr; padding: 16px 20px; gap: 22px; } +.overview-content > .info-card > .info-row { align-items: flex-start; justify-content: flex-start; flex-direction: column; gap: 6px; min-width: 0; } +.overview-content > .info-card .info-value { text-align: left; } +.overview-content > .info-card .info-value-group { max-width: 100%; min-width: 0; justify-content: flex-start; gap: 6px; } +.overview-content > .info-card .info-value { max-width: 100%; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.overview-content > .info-card .folder-btn { width: 20px; height: 20px; } +.overview-panel { min-width: 0; padding: 20px; background: var(--panel-bg); border: 1px solid var(--border); border-radius: var(--radius); } +.panel-heading { margin-bottom: 16px; color: var(--text); font-size: 14px; font-weight: 600; } +.overview-panel .status-grid { gap: 10px; } +.overview-panel .status-grid > .status-card { min-height: 78px; padding: 11px 12px; } +.overview-panel .status-title { font-size: 11px; } +.overview-panel .status-detail { font-size: 13px; } +.overview-panel .status-actions { margin-top: 13px; gap: 10px; padding: 0; } +.overview-panel .status-actions > .btn { min-height: 62px; padding: 9px 10px; font-size: 12px; line-height: 1.5; } +.engine-cache-section.overview-panel { margin: 0; padding: 20px; border-top: 1px solid var(--border); } +.engine-cache-section.overview-panel > .library-section-title { margin-bottom: 16px; font-size: 14px; font-weight: 600; } +.engine-cache-section.overview-panel .status-grid { grid-template-columns: repeat(2,minmax(0,1fr)); } +.engine-cache-section .cache-install-status { grid-area: 1 / 1; } +.engine-cache-section .cache-proxy-version { grid-area: 1 / 2; } +.cache-hit-card .status-text { width: 100%; } +.cache-hit-heading { display: flex; align-items: center; gap: 8px; min-width: 0; } +.cache-hit-heading > .status-title { flex-shrink: 0; } +.cache-hit-stats { flex: 1; min-width: 0; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; color: var(--text-dim); font-size: 10px; text-align: right; } +.cache-panel-heading { display: flex; align-items: center; gap: 8px; } +.cache-help { position: relative; display: inline-flex; flex-shrink: 0; } +.cache-help-button { display: inline-flex; align-items: center; justify-content: center; width: 18px; height: 18px; padding: 0; border: 1px solid var(--text-muted); border-radius: 50%; background: transparent; color: var(--text-dim); font: inherit; font-size: 12px; line-height: 1; cursor: help; } +.cache-help-tooltip { position: absolute; top: 50%; left: calc(100% + 10px); z-index: 100; width: clamp(180px, 22vw, 260px); max-width: 65vw; padding: 10px 12px; border: 1px solid var(--border); border-radius: var(--radius-sm); background: var(--bg-card); color: var(--text); box-shadow: 0 6px 20px rgba(0,0,0,.2); font-size: 12px; font-weight: 400; line-height: 1.6; white-space: normal; overflow-wrap: anywhere; opacity: 0; visibility: hidden; transform: translate(-4px, -50%); transition: opacity var(--motion-duration), transform var(--motion-duration), visibility var(--motion-duration); pointer-events: none; } +.cache-help-tooltip::before { content: ''; position: absolute; top: 50%; left: -5px; width: 8px; height: 8px; border-left: 1px solid var(--border); border-bottom: 1px solid var(--border); background: var(--bg-card); transform: translateY(-50%) rotate(45deg); } +.cache-help:hover .cache-help-tooltip, .cache-help:focus-within .cache-help-tooltip { opacity: 1; visibility: visible; transform: translate(0, -50%); } +.engine-cache-section.overview-panel > .actions { margin-top: 13px; } +.engine-cache-section.overview-panel .engine-cache-error { margin-top: 12px; } + +.workspace > .tools-content { display: grid; grid-template-columns: repeat(2, minmax(0,1fr)); grid-auto-rows: max-content; align-content: start; } +.tool-panel { min-width: 0; padding: 20px; border: 1px solid var(--border); border-radius: var(--radius); background: var(--panel-bg); } +.tool-panel.panel-wide { grid-column: 1 / -1; } +.tool-panel > .library-section:first-of-type { margin-top: 0 !important; } +.tool-panel > .status-card { margin-top: 12px; } +.tool-panel > .library-section + .library-section { margin-top: 16px; } +.tool-panel .btn { align-self: stretch; } +.workspace > .library-content { max-width: 1400px; } +.workspace > .library-content > .library-section { padding: 18px 20px; background: var(--panel-bg); border: 1px solid var(--border); border-radius: var(--radius); margin-top: 0 !important; } +.workspace > .settings-content { display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); grid-auto-rows: max-content; align-content: start; } +.settings-content > .library-section, .appearance-section { min-width: 0; padding: 20px; margin-top: 0 !important; background: var(--panel-bg); border: 1px solid var(--border); border-radius: var(--radius); } +.appearance-section { grid-column: 1 / -1; } +.appearance-section .panel-heading { margin-bottom: 4px; } +.setting-description { color: var(--text-dim); font-size: 12px; line-height: 1.6; } +.theme-choices { display: grid; grid-template-columns: repeat(3,minmax(0,1fr)); gap: 14px; margin: 18px 0 20px; } +.theme-option { padding: 9px; border: 1px solid var(--border); border-radius: var(--radius); background: var(--bg); color: var(--text-dim); cursor: pointer; font: inherit; text-align: left; } +.theme-option:hover { border-color: var(--text-dim); } +.theme-option.selected { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); color: var(--text); } +.theme-option-label { display: flex; justify-content: space-between; align-items: center; padding: 8px 4px 1px; font-size: 12px; font-weight: 600; } +.theme-option-label > span { color: var(--accent); } +.theme-preview { display: flex; height: 86px; overflow: hidden; border-radius: var(--radius-sm); background: #1a1a2e; border: 1px solid rgba(128,128,128,.18); } +.preview-sidebar { width: 24%; background: #16213e; border-right: 1px solid rgba(128,128,128,.15); } +.preview-main { flex: 1; padding: 12px; display: grid; grid-template-columns: 1fr 1fr; grid-template-rows: 1fr 12px; gap: 8px; } +.preview-main > span { background: #22304c; border-radius: 3px; } +.preview-main > i { width: 80%; background: #ff6b00; border-radius: 3px; } +.preview-dark { background: #0a0a0a; border-color: #292929; } +.preview-dark .preview-sidebar { background: #0a0a0a; border-color: #292929; } +.preview-dark .preview-main > span { background: #0a0a0a; border: 1px solid #292929; } +.preview-dark .preview-main > i { background: #ffffff; } +.preview-light { background: #fff; border-color: #d8d8d8; } +.preview-light .preview-sidebar { background: #fff; border-color: #d8d8d8; } +.preview-light .preview-main > span { background: #fff; border: 1px solid #d8d8d8; } +.preview-light .preview-main > i { background: #1eccd9; } +.setting-row { display: flex; align-items: center; justify-content: space-between; gap: 20px; border-top: 1px solid var(--border); padding-top: 18px; } +.setting-label { color: var(--text); font-size: 13px; font-weight: 500; margin-bottom: 3px; } +.setting-switch { flex-shrink: 0; display: inline-flex; align-items: center; width: 38px; height: 22px; padding: 3px; border: 1px solid var(--border); border-radius: 11px; background: var(--bg-card-hover); cursor: pointer; } +.setting-switch > span { display: block; width: 14px; height: 14px; background: var(--text-dim); border-radius: 50%; transition: transform var(--motion-duration); } +.setting-switch.on { background: var(--accent); border-color: var(--accent); } +.setting-switch.on > span { background: var(--accent-contrast); transform: translateX(15px); } +.setting-footnote { margin-top: 14px; color: var(--text-muted); font-size: 11px; } +.settings-content .always-on-top-setting { min-height: 44px; width: 100%; } +.settings-content > .compatibility-records { grid-column: 1 / -1; } +.compatibility-records-heading { display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: wrap; } +.compatibility-records-heading .panel-heading { margin-bottom: 0; } +.compatibility-count { margin-left: 6px; color: var(--text-muted); font-size: 12px; font-weight: 400; } +.compatibility-record-actions { display: flex; gap: 8px; } +.compatibility-records .btn { min-height: 32px; padding: 6px 12px; font-size: 12px; } +.compatibility-records > .setting-description { margin-top: 10px; } +.compatibility-empty { margin-top: 16px; color: var(--text-muted); font-size: 12px; } +.compatibility-record { margin-top: 14px; padding-top: 14px; border-top: 1px solid var(--border); min-width: 0; } +.compatibility-details { margin-top: 10px; color: var(--text-dim); font-size: 12px; } +.compatibility-details summary { cursor: pointer; width: fit-content; } +.compatibility-details dl { margin-top: 10px; padding: 12px; background: var(--bg); border-radius: var(--radius-sm); } +.compatibility-details dt { margin-top: 10px; color: var(--text-muted); } +.compatibility-details dt:first-child { margin-top: 0; } +.compatibility-details dd { margin: 4px 0 0; overflow-wrap: anywhere; } +.compatibility-details code { font-family: Consolas, monospace; font-size: 11px; } +.workspace .vis-bar-outer { background: var(--bg-card-hover); } + +.app-shell > .log-section { grid-area: console; height: 170px; min-height: 0; background: var(--panel-bg); } +.app-shell > .log-section.collapsed { height: 37px; } +.log-section > .log-header { display: flex; flex-shrink: 0; align-items: center; justify-content: space-between; width: 100%; min-height: 36px; padding: 8px 28px; background: transparent; border: 0; color: var(--text-dim); font: inherit; font-size: 11px; letter-spacing: 0; text-transform: none; cursor: pointer; text-align: left; } +.log-header > svg { transition: transform var(--motion-duration); } +.log-header > svg.rotated { transform: rotate(180deg); } +.log-count { margin-left: 8px; color: var(--text-muted); font-variant-numeric: tabular-nums; } +.log-section > .log-body { padding: 0 28px 12px; font-size: 11px; } +.log-empty { color: var(--text-muted); } + +.app-shell :is(button,input,select,textarea,[tabindex]):focus-visible { outline: 2px solid var(--accent); outline-offset: 3px; } +@media (max-width: 1040px) { + .page-heading { padding: 21px 20px 17px; } + .workspace > .content { padding-left: 20px; padding-right: 20px; gap: 14px; } + .overview-panel, .engine-cache-section.overview-panel, .tool-panel { padding: 16px; } + .overview-content > .info-card { gap: 14px; padding: 14px 16px; } +} +@media (max-width: 820px) { + .workspace > :is(.overview-content,.tools-content,.settings-content) { grid-template-columns: minmax(0,1fr); } + .overview-content > .info-card { grid-template-columns: minmax(0,1fr); gap: 10px; } + .theme-choices { gap: 9px; } + .nav-item { gap: 8px; padding-left: 9px; font-size: 12px; } +} +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { animation: none !important; transition: none !important; scroll-behavior: auto !important; } +} +/* Match all controls to the selected theme, including existing switches. */ +:root { --font-sans: 'Segoe UI', 'Microsoft YaHei UI', 'Microsoft YaHei', sans-serif; } +.workspace .drive-chip.active, +.workspace .playlist-chip.active { color: var(--accent-contrast); } +.workspace .drive-chip.active .drive-count { color: var(--accent-contrast); opacity: .8; } +.settings-content .toggle-switch { background: var(--bg-card-hover); border: 1px solid var(--border); } +.settings-content .toggle-switch .toggle-knob { background: var(--text-dim); } +.settings-content .toggle-switch.on { background: var(--accent); border-color: var(--accent); } +.settings-content .toggle-switch.on .toggle-knob { background: var(--accent-contrast); } + +/* Frameless window chrome shares the current theme and native drag region. */ +.app-shell > .header { padding-right: 0; user-select: none; } +.app-shell .header-right { flex-shrink: 0; height: 100%; gap: 12px; } +.window-controls { display: flex; align-items: stretch; align-self: stretch; gap: 0; margin-left: 0; } +.window-control { + display: flex; + align-items: center; + justify-content: center; + width: 40px; + height: 100%; + padding: 0; + border: 0; + border-radius: 0; + background: transparent; + color: var(--text-dim); + cursor: pointer; + --wails-draggable: no-drag; +} +.window-control:hover { background: var(--bg-card-hover); color: var(--text); } +.window-control:active { background: var(--border); } +.window-close:hover, .window-close:active { background: #c42b1c; color: #fff; } +.app-shell .window-control:focus-visible { outline-offset: -4px; } +.window-control > svg { pointer-events: none; } + +.app-logo { + width: 24px; + height: 24px; + flex-shrink: 0; + margin-right: -10px; + object-fit: contain; + pointer-events: none; + user-select: none; +} + +/* Fit the default 1280 x 720 workspace without oversized cards or empty space. */ +@media (max-height: 760px) { + .page-heading { padding: 16px 24px 14px; } + .page-heading h1 { font-size: 23px; } + .page-heading p { margin-top: 4px; } + .workspace > .content { padding: 0 24px 18px; gap: 14px; } + .overview-content > .info-card { padding: 12px 16px; gap: 18px; grid-template-columns: 1.2fr 1.7fr .8fr; } + .overview-panel, .engine-cache-section.overview-panel, .tool-panel, + .settings-content > .library-section, .appearance-section { padding: 16px; } + .panel-heading, .engine-cache-section.overview-panel > .library-section-title { margin-bottom: 12px; } + .overview-panel .status-grid > .status-card { min-height: 68px; padding: 9px 10px; } + .engine-cache-section.overview-panel > .library-stats { margin-bottom: 6px; } + .overview-panel .status-actions, + .engine-cache-section.overview-panel > .actions { margin-top: 10px; gap: 10px; } + .overview-panel .status-actions > .btn { min-height: 48px; padding: 7px 10px; line-height: 1.45; } + .engine-cache-section > p.status-title { margin-top: 8px; line-height: 1.5; } + .theme-choices { margin: 14px 0 16px; } + .theme-preview { height: 68px; } + .log-section > .log-header { padding-left: 24px; padding-right: 24px; } + .log-section > .log-body { padding-left: 24px; padding-right: 24px; } +} + +/* Compact spacing for smaller windows. */ +@media (max-width: 1180px) { + .page-heading { padding: 12px 18px; } + .page-heading h1 { font-size: 21px; } + .workspace > .content { padding: 0 18px 14px; gap: 12px; } + .overview-panel, .engine-cache-section.overview-panel, .tool-panel, + .settings-content > .library-section, .appearance-section { padding: 12px; } + .overview-content > .info-card { padding: 10px 12px; gap: 12px; } + .overview-panel .status-grid { gap: 8px; } + .overview-panel .status-grid > .status-card { min-height: 62px; padding: 8px; } + .overview-panel .status-actions { gap: 8px; } + .nav-item { gap: 7px; padding-left: 8px; padding-right: 8px; } + .sidebar { padding-left: 8px; padding-right: 8px; } + .log-section > .log-header, .log-section > .log-body { padding-left: 18px; padding-right: 18px; } +} + +@media (min-width: 821px) and (max-width: 1040px) { + .overview-content > .info-card { grid-template-columns: minmax(0, 1.15fr) minmax(0, 1.3fr) minmax(0, .85fr); column-gap: 16px; } + .page-heading { padding: 10px 16px; } + .page-heading h1 { font-size: 20px; } + .page-heading p { margin-top: 2px; } + .workspace > .content { padding: 0 16px 12px; gap: 10px; } + .overview-panel .status-grid > .status-card { min-height: 56px; } + .overview-panel .status-actions > .btn { min-height: 44px; padding: 6px 8px; } + .nav-group { margin-bottom: 12px; } + .nav-item { font-size: 12px; } +} + +/* Shared timing for interface feedback and changes of view. */ +:root { + --motion-duration: 300ms; + --motion-ease: cubic-bezier(.2, 0, 0, 1); +} + +html, body, .app-shell, .app-shell > .header, .sidebar, +.workspace, .page-heading, .app-shell > .log-section { + transition: background-color var(--motion-duration) var(--motion-ease), + color var(--motion-duration) var(--motion-ease), + border-color var(--motion-duration) var(--motion-ease); +} + +.app-shell :is(button, input, select, textarea, .nav-item, .status-card, +.info-card, .library-card, .tool-panel, .overview-panel, .appearance-section, +.theme-option, .settings-content > .library-section, .library-content > .library-section, +.drive-chip, .playlist-chip, .playlist-track-row, .id3-drop-zone, .id3-cover-img, +.toggle-switch, .toggle-knob, .setting-switch, .setting-switch > span, +.folder-btn, .status-detail, .status-title, .info-label, .info-value, +.library-section-title, .library-stats, .setting-description, .theme-option-label) { + transition-property: background-color, color, border-color, box-shadow, opacity, transform, border-radius; + transition-duration: var(--motion-duration); + transition-timing-function: var(--motion-ease); +} + +.app-shell :is(.btn, .drive-chip, .playlist-chip, .theme-option):active:not(:disabled) { + transform: translateY(1px); +} + +/* Display changes restart this animation without remounting page state. */ +.workspace > .content, .page-heading { + animation: workspace-enter var(--motion-duration) var(--motion-ease) both; +} +@keyframes workspace-enter { + from { opacity: 0; transform: translateY(6px); } + to { opacity: 1; transform: translateY(0); } +} + +.app-shell > .log-section { + overflow: hidden; + transition: height var(--motion-duration) var(--motion-ease), + background-color var(--motion-duration) var(--motion-ease), + border-color var(--motion-duration) var(--motion-ease); +} +.log-header > svg { transition: transform var(--motion-duration) var(--motion-ease); } + +@media (prefers-reduced-motion: reduce) { + *, *::before, *::after { + animation: none !important; + transition: none !important; + scroll-behavior: auto !important; + } +} diff --git a/frontend/vite.config.js b/frontend/vite.config.js index a30c338..84a50ce 100644 --- a/frontend/vite.config.js +++ b/frontend/vite.config.js @@ -1,7 +1,23 @@ +import {createServer} from 'node:net' import {defineConfig} from 'vite' import vue from '@vitejs/plugin-vue' // https://vitejs.dev/config/ -export default defineConfig({ - plugins: [vue()] -}) +const host = '127.0.0.1' + +function findDevPort() { + return new Promise((resolve, reject) => { + const socket = createServer() + socket.once('error', reject) + socket.listen(0, host, () => { + const {port} = socket.address() + socket.close(error => error ? reject(error) : resolve(port)) + }) + }) +} + +export default defineConfig(async ({command, isPreview}) => ({ + plugins: [vue()], + // Vite treats port 0 as its default port. Resolve a concrete port first. + server: command === 'serve' && !isPreview ? {host, port: await findDevPort()} : undefined, +})) diff --git a/frontend/wailsjs/go/main/App.d.ts b/frontend/wailsjs/go/main/App.d.ts index 9bf16ba..e99631b 100644 --- a/frontend/wailsjs/go/main/App.d.ts +++ b/frontend/wailsjs/go/main/App.d.ts @@ -1,8 +1,10 @@ // Cynhyrchwyd y ffeil hon yn awtomatig. PEIDIWCH Â MODIWL // This file is automatically generated. DO NOT EDIT import {logs} from '../models'; +import {uifix} from '../models'; import {database} from '../models'; import {i18n} from '../models'; +import {storage} from '../models'; import {main} from '../models'; import {id3} from '../models'; import {msi} from '../models'; @@ -18,7 +20,9 @@ export function CleanCache():Promise; export function CleanMSIOrphans(arg1:Array):Promise; -export function CompressCovers(arg1:number,arg2:number):Promise>; +export function ClearCompatibilityRecords(arg1:string):Promise; + +export function CompressCovers(arg1:number,arg2:number,arg3:string):Promise>; export function FixUnicodeIssues():Promise; @@ -26,17 +30,23 @@ export function GetAvailableLanguages():Promise>>; export function GetCacheSize():Promise; +export function GetEngineCacheStatus():Promise; + export function GetLibraryStats():Promise; +export function GetLogEntries():Promise>; + export function GetMessages():Promise; export function GetPlayStats():Promise; export function GetPlaylistTracks(arg1:number):Promise>; +export function GetSettings():Promise; + export function GetStatus():Promise; -export function GetSyncableTracks():Promise>; +export function GetSyncableTracks(arg1:string):Promise>; export function HandleUTF8AlreadyEnabled():Promise; @@ -50,13 +60,13 @@ export function ID3AntiPiracyV1(arg1:string):Promise; export function ID3AntiPiracyV1Paths(arg1:Array,arg2:string):Promise; -export function ID3AntiPiracyV1Playlist(arg1:number):Promise; +export function ID3AntiPiracyV1Playlist(arg1:number,arg2:string):Promise; export function ID3AntiPiracyV2(arg1:string):Promise; export function ID3AntiPiracyV2Paths(arg1:Array,arg2:string):Promise; -export function ID3AntiPiracyV2Playlist(arg1:number):Promise; +export function ID3AntiPiracyV2Playlist(arg1:number,arg2:string):Promise; export function ID3ClearAll(arg1:string):Promise; @@ -74,11 +84,13 @@ export function ID3SetCover(arg1:string):Promise; export function ID3WriteTag(arg1:string,arg2:string,arg3:string,arg4:string,arg5:string,arg6:string):Promise; +export function InstallEngineCache():Promise; + export function ListBackups():Promise>; export function ListDrives():Promise>; -export function ListPlaylists():Promise>; +export function ListPlaylists(arg1:string):Promise>; export function LogExperimentalEnabled():Promise; @@ -104,26 +116,34 @@ export function OptimizeDatabase():Promise; export function Refresh():Promise; -export function RemoveMissingTracks(arg1:Array):Promise; +export function RemoveMissingTracks(arg1:Array,arg2:string):Promise; export function RepairDatabase():Promise; +export function RespondToConfirmation(arg1:number,arg2:boolean):Promise; + export function RestoreDatabase(arg1:string):Promise; export function RestoreUnicodeFix():Promise; +export function SaveSettings(arg1:storage.Settings):Promise; + export function ScanMSIOrphans():Promise>; -export function ScanMissingTracks():Promise>; +export function ScanMissingTracks(arg1:string):Promise>; export function SelectDrive(arg1:string):Promise; export function SetLanguage(arg1:string):Promise; -export function SyncBPMKeyToTags():Promise>; +export function SyncBPMKeyToTags(arg1:string):Promise>; export function USBUnlockAvailable():Promise; export function USBUnlockKill(arg1:string):Promise; export function USBUnlockScan(arg1:string):Promise>; + +export function UninstallEngineCache():Promise; + +export function WriteFrontendLog(arg1:string):Promise; diff --git a/frontend/wailsjs/go/main/App.js b/frontend/wailsjs/go/main/App.js index 379af1a..93b47ef 100644 --- a/frontend/wailsjs/go/main/App.js +++ b/frontend/wailsjs/go/main/App.js @@ -22,8 +22,12 @@ export function CleanMSIOrphans(arg1) { return window['go']['main']['App']['CleanMSIOrphans'](arg1); } -export function CompressCovers(arg1, arg2) { - return window['go']['main']['App']['CompressCovers'](arg1, arg2); +export function ClearCompatibilityRecords(arg1) { + return window['go']['main']['App']['ClearCompatibilityRecords'](arg1); +} + +export function CompressCovers(arg1, arg2, arg3) { + return window['go']['main']['App']['CompressCovers'](arg1, arg2, arg3); } export function FixUnicodeIssues() { @@ -38,10 +42,18 @@ export function GetCacheSize() { return window['go']['main']['App']['GetCacheSize'](); } +export function GetEngineCacheStatus() { + return window['go']['main']['App']['GetEngineCacheStatus'](); +} + export function GetLibraryStats() { return window['go']['main']['App']['GetLibraryStats'](); } +export function GetLogEntries() { + return window['go']['main']['App']['GetLogEntries'](); +} + export function GetMessages() { return window['go']['main']['App']['GetMessages'](); } @@ -54,12 +66,16 @@ export function GetPlaylistTracks(arg1) { return window['go']['main']['App']['GetPlaylistTracks'](arg1); } +export function GetSettings() { + return window['go']['main']['App']['GetSettings'](); +} + export function GetStatus() { return window['go']['main']['App']['GetStatus'](); } -export function GetSyncableTracks() { - return window['go']['main']['App']['GetSyncableTracks'](); +export function GetSyncableTracks(arg1) { + return window['go']['main']['App']['GetSyncableTracks'](arg1); } export function HandleUTF8AlreadyEnabled() { @@ -86,8 +102,8 @@ export function ID3AntiPiracyV1Paths(arg1, arg2) { return window['go']['main']['App']['ID3AntiPiracyV1Paths'](arg1, arg2); } -export function ID3AntiPiracyV1Playlist(arg1) { - return window['go']['main']['App']['ID3AntiPiracyV1Playlist'](arg1); +export function ID3AntiPiracyV1Playlist(arg1, arg2) { + return window['go']['main']['App']['ID3AntiPiracyV1Playlist'](arg1, arg2); } export function ID3AntiPiracyV2(arg1) { @@ -98,8 +114,8 @@ export function ID3AntiPiracyV2Paths(arg1, arg2) { return window['go']['main']['App']['ID3AntiPiracyV2Paths'](arg1, arg2); } -export function ID3AntiPiracyV2Playlist(arg1) { - return window['go']['main']['App']['ID3AntiPiracyV2Playlist'](arg1); +export function ID3AntiPiracyV2Playlist(arg1, arg2) { + return window['go']['main']['App']['ID3AntiPiracyV2Playlist'](arg1, arg2); } export function ID3ClearAll(arg1) { @@ -134,6 +150,10 @@ export function ID3WriteTag(arg1, arg2, arg3, arg4, arg5, arg6) { return window['go']['main']['App']['ID3WriteTag'](arg1, arg2, arg3, arg4, arg5, arg6); } +export function InstallEngineCache() { + return window['go']['main']['App']['InstallEngineCache'](); +} + export function ListBackups() { return window['go']['main']['App']['ListBackups'](); } @@ -142,8 +162,8 @@ export function ListDrives() { return window['go']['main']['App']['ListDrives'](); } -export function ListPlaylists() { - return window['go']['main']['App']['ListPlaylists'](); +export function ListPlaylists(arg1) { + return window['go']['main']['App']['ListPlaylists'](arg1); } export function LogExperimentalEnabled() { @@ -194,14 +214,18 @@ export function Refresh() { return window['go']['main']['App']['Refresh'](); } -export function RemoveMissingTracks(arg1) { - return window['go']['main']['App']['RemoveMissingTracks'](arg1); +export function RemoveMissingTracks(arg1, arg2) { + return window['go']['main']['App']['RemoveMissingTracks'](arg1, arg2); } export function RepairDatabase() { return window['go']['main']['App']['RepairDatabase'](); } +export function RespondToConfirmation(arg1, arg2) { + return window['go']['main']['App']['RespondToConfirmation'](arg1, arg2); +} + export function RestoreDatabase(arg1) { return window['go']['main']['App']['RestoreDatabase'](arg1); } @@ -210,12 +234,16 @@ export function RestoreUnicodeFix() { return window['go']['main']['App']['RestoreUnicodeFix'](); } +export function SaveSettings(arg1) { + return window['go']['main']['App']['SaveSettings'](arg1); +} + export function ScanMSIOrphans() { return window['go']['main']['App']['ScanMSIOrphans'](); } -export function ScanMissingTracks() { - return window['go']['main']['App']['ScanMissingTracks'](); +export function ScanMissingTracks(arg1) { + return window['go']['main']['App']['ScanMissingTracks'](arg1); } export function SelectDrive(arg1) { @@ -226,8 +254,8 @@ export function SetLanguage(arg1) { return window['go']['main']['App']['SetLanguage'](arg1); } -export function SyncBPMKeyToTags() { - return window['go']['main']['App']['SyncBPMKeyToTags'](); +export function SyncBPMKeyToTags(arg1) { + return window['go']['main']['App']['SyncBPMKeyToTags'](arg1); } export function USBUnlockAvailable() { @@ -241,3 +269,11 @@ export function USBUnlockKill(arg1) { export function USBUnlockScan(arg1) { return window['go']['main']['App']['USBUnlockScan'](arg1); } + +export function UninstallEngineCache() { + return window['go']['main']['App']['UninstallEngineCache'](); +} + +export function WriteFrontendLog(arg1) { + return window['go']['main']['App']['WriteFrontendLog'](arg1); +} diff --git a/frontend/wailsjs/go/models.ts b/frontend/wailsjs/go/models.ts index 3585c47..b101237 100644 --- a/frontend/wailsjs/go/models.ts +++ b/frontend/wailsjs/go/models.ts @@ -1,13 +1,13 @@ export namespace database { - + export class BPMBucket { range: string; count: number; - + static createFrom(source: any = {}) { return new BPMBucket(source); } - + constructor(source: any = {}) { if ('string' === typeof source) source = JSON.parse(source); this.range = source["range"]; @@ -19,11 +19,11 @@ export namespace database { date: string; size: number; note: string; - + static createFrom(source: any = {}) { return new BackupInfo(source); } - + constructor(source: any = {}) { if ('string' === typeof source) source = JSON.parse(source); this.filename = source["filename"]; @@ -35,11 +35,11 @@ export namespace database { export class KVCount { key: string; count: number; - + static createFrom(source: any = {}) { return new KVCount(source); } - + constructor(source: any = {}) { if ('string' === typeof source) source = JSON.parse(source); this.key = source["key"]; @@ -56,11 +56,11 @@ export namespace database { playCount: number; lastPlayed: string; dateAdded: string; - + static createFrom(source: any = {}) { return new TrackSummary(source); } - + constructor(source: any = {}) { if ('string' === typeof source) source = JSON.parse(source); this.id = source["id"]; @@ -85,11 +85,11 @@ export namespace database { topGenres: KVCount[]; bpmDistribution: BPMBucket[]; recentlyAdded: TrackSummary[]; - + static createFrom(source: any = {}) { return new LibraryStats(source); } - + constructor(source: any = {}) { if ('string' === typeof source) source = JSON.parse(source); this.totalTracks = source["totalTracks"]; @@ -103,7 +103,7 @@ export namespace database { this.bpmDistribution = this.convertValues(source["bpmDistribution"], BPMBucket); this.recentlyAdded = this.convertValues(source["recentlyAdded"], TrackSummary); } - + convertValues(a: any, classs: any, asMap: boolean = false): any { if (!a) { return a; @@ -128,11 +128,11 @@ export namespace database { artist: string; path: string; filename: string; - + static createFrom(source: any = {}) { return new MissingTrack(source); } - + constructor(source: any = {}) { if ('string' === typeof source) source = JSON.parse(source); this.id = source["id"]; @@ -146,18 +146,18 @@ export namespace database { mostPlayed: TrackSummary[]; recentPlayed: TrackSummary[]; neverPlayed: TrackSummary[]; - + static createFrom(source: any = {}) { return new PlayStats(source); } - + constructor(source: any = {}) { if ('string' === typeof source) source = JSON.parse(source); this.mostPlayed = this.convertValues(source["mostPlayed"], TrackSummary); this.recentPlayed = this.convertValues(source["recentPlayed"], TrackSummary); this.neverPlayed = this.convertValues(source["neverPlayed"], TrackSummary); } - + convertValues(a: any, classs: any, asMap: boolean = false): any { if (!a) { return a; @@ -181,11 +181,11 @@ export namespace database { title: string; parentId: number; count: number; - + static createFrom(source: any = {}) { return new PlaylistInfo(source); } - + constructor(source: any = {}) { if ('string' === typeof source) source = JSON.parse(source); this.id = source["id"]; @@ -203,11 +203,11 @@ export namespace database { key: number; keyName: string; camelot: string; - + static createFrom(source: any = {}) { return new SyncableTrack(source); } - + constructor(source: any = {}) { if ('string' === typeof source) source = JSON.parse(source); this.id = source["id"]; @@ -234,11 +234,11 @@ export namespace database { keyName: string; camelot: string; rating: number; - + static createFrom(source: any = {}) { return new TrackInfo(source); } - + constructor(source: any = {}) { if ('string' === typeof source) source = JSON.parse(source); this.id = source["id"]; @@ -260,7 +260,7 @@ export namespace database { } export namespace i18n { - + export class Messages { appTitle: string; installPathLabel: string; @@ -449,6 +449,7 @@ export namespace i18n { tracksUnit: string; tabSettings: string; settingsLanguageLabel: string; + settingsAlwaysOnTop: string; settingsExperimentalLabel: string; settingsExperimentalDesc: string; settingsExperimentalConfirmTitle: string; @@ -466,11 +467,11 @@ export namespace i18n { id3AlbumPlaceholder: string; id3YearPlaceholder: string; id3GenrePlaceholder: string; - + static createFrom(source: any = {}) { return new Messages(source); } - + constructor(source: any = {}) { if ('string' === typeof source) source = JSON.parse(source); this.appTitle = source["appTitle"]; @@ -660,6 +661,7 @@ export namespace i18n { this.tracksUnit = source["tracksUnit"]; this.tabSettings = source["tabSettings"]; this.settingsLanguageLabel = source["settingsLanguageLabel"]; + this.settingsAlwaysOnTop = source["settingsAlwaysOnTop"]; this.settingsExperimentalLabel = source["settingsExperimentalLabel"]; this.settingsExperimentalDesc = source["settingsExperimentalDesc"]; this.settingsExperimentalConfirmTitle = source["settingsExperimentalConfirmTitle"]; @@ -683,7 +685,7 @@ export namespace i18n { } export namespace id3 { - + export class TagInfo { filePath: string; title: string; @@ -692,11 +694,11 @@ export namespace id3 { year: string; genre: string; hasCover: boolean; - + static createFrom(source: any = {}) { return new TagInfo(source); } - + constructor(source: any = {}) { if ('string' === typeof source) source = JSON.parse(source); this.filePath = source["filePath"]; @@ -712,7 +714,7 @@ export namespace id3 { } export namespace logs { - + export class LogEntry { level: string; // Go type: time @@ -720,11 +722,11 @@ export namespace logs { thread: string; category: string; message: string; - + static createFrom(source: any = {}) { return new LogEntry(source); } - + constructor(source: any = {}) { if ('string' === typeof source) source = JSON.parse(source); this.level = source["level"]; @@ -733,7 +735,7 @@ export namespace logs { this.category = source["category"]; this.message = source["message"]; } - + convertValues(a: any, classs: any, asMap: boolean = false): any { if (!a) { return a; @@ -755,11 +757,11 @@ export namespace logs { export class MessageCount { message: string; count: number; - + static createFrom(source: any = {}) { return new MessageCount(source); } - + constructor(source: any = {}) { if ('string' === typeof source) source = JSON.parse(source); this.message = source["message"]; @@ -776,11 +778,11 @@ export namespace logs { topWarnings: MessageCount[]; topErrors: MessageCount[]; recentEntries: LogEntry[]; - + static createFrom(source: any = {}) { return new LogStats(source); } - + constructor(source: any = {}) { if ('string' === typeof source) source = JSON.parse(source); this.totalFiles = source["totalFiles"]; @@ -793,7 +795,7 @@ export namespace logs { this.topErrors = this.convertValues(source["topErrors"], MessageCount); this.recentEntries = this.convertValues(source["recentEntries"], LogEntry); } - + convertValues(a: any, classs: any, asMap: boolean = false): any { if (!a) { return a; @@ -816,15 +818,15 @@ export namespace logs { } export namespace main { - + export class DriveInfo { letter: string; trackCount: number; - + static createFrom(source: any = {}) { return new DriveInfo(source); } - + constructor(source: any = {}) { if ('string' === typeof source) source = JSON.parse(source); this.letter = source["letter"]; @@ -834,11 +836,11 @@ export namespace main { export class ProcessItem { name: string; pid: number; - + static createFrom(source: any = {}) { return new ProcessItem(source); } - + constructor(source: any = {}) { if ('string' === typeof source) source = JSON.parse(source); this.name = source["name"]; @@ -858,11 +860,11 @@ export namespace main { dbPath: string; processRunning: boolean; runningProcesses: ProcessItem[]; - + static createFrom(source: any = {}) { return new StatusInfo(source); } - + constructor(source: any = {}) { if ('string' === typeof source) source = JSON.parse(source); this.installPath = source["installPath"]; @@ -878,7 +880,7 @@ export namespace main { this.processRunning = source["processRunning"]; this.runningProcesses = this.convertValues(source["runningProcesses"], ProcessItem); } - + convertValues(a: any, classs: any, asMap: boolean = false): any { if (!a) { return a; @@ -901,15 +903,15 @@ export namespace main { } export namespace msi { - + export class OrphanedMSI { productCode: string; displayName: string; - + static createFrom(source: any = {}) { return new OrphanedMSI(source); } - + constructor(source: any = {}) { if ('string' === typeof source) source = JSON.parse(source); this.productCode = source["productCode"]; @@ -919,16 +921,162 @@ export namespace msi { } +export namespace storage { + + export class CompatibilityResult { + hashes: Record; + callers: number[]; + validator: string; + checkedAt: string; + + static createFrom(source: any = {}) { + return new CompatibilityResult(source); + } + + constructor(source: any = {}) { + if ('string' === typeof source) source = JSON.parse(source); + this.hashes = source["hashes"]; + this.callers = source["callers"]; + this.validator = source["validator"]; + this.checkedAt = source["checkedAt"]; + } + } + export class Settings { + engineDJCompatibility?: Record; + language: string; + theme: string; + squareCorners: boolean; + alwaysOnTop: boolean; + experimentalEnabled: boolean; + experimentalActivations?: string[]; + termsAccepted: boolean; + + static createFrom(source: any = {}) { + return new Settings(source); + } + + constructor(source: any = {}) { + if ('string' === typeof source) source = JSON.parse(source); + this.engineDJCompatibility = this.convertValues(source["engineDJCompatibility"], CompatibilityResult, true); + this.language = source["language"]; + this.theme = source["theme"]; + this.squareCorners = source["squareCorners"]; + this.alwaysOnTop = source["alwaysOnTop"]; + this.experimentalEnabled = source["experimentalEnabled"]; + this.experimentalActivations = source["experimentalActivations"]; + this.termsAccepted = source["termsAccepted"]; + } + + convertValues(a: any, classs: any, asMap: boolean = false): any { + if (!a) { + return a; + } + if (a.slice && a.map) { + return (a as any[]).map(elem => this.convertValues(elem, classs)); + } else if ("object" === typeof a) { + if (asMap) { + for (const key of Object.keys(a)) { + a[key] = new classs(a[key]); + } + return a; + } + return new classs(a); + } + return a; + } + } + +} + +export namespace uifix { + + export class Stats { + lookups: number; + hits: number; + misses: number; + refreshes: number; + errors: number; + ageMs: number; + interfaces: number; + + static createFrom(source: any = {}) { + return new Stats(source); + } + + constructor(source: any = {}) { + if ('string' === typeof source) source = JSON.parse(source); + this.lookups = source["lookups"]; + this.hits = source["hits"]; + this.misses = source["misses"]; + this.refreshes = source["refreshes"]; + this.errors = source["errors"]; + this.ageMs = source["ageMs"]; + this.interfaces = source["interfaces"]; + } + } + export class State { + installed: boolean; + installStatus: string; + installError: string; + proxyVersion: string; + running: boolean; + pid: number; + active: boolean; + busy: boolean; + phase: string; + error: string; + stats: Stats; + + static createFrom(source: any = {}) { + return new State(source); + } + + constructor(source: any = {}) { + if ('string' === typeof source) source = JSON.parse(source); + this.installed = source["installed"]; + this.installStatus = source["installStatus"]; + this.installError = source["installError"]; + this.proxyVersion = source["proxyVersion"]; + this.running = source["running"]; + this.pid = source["pid"]; + this.active = source["active"]; + this.busy = source["busy"]; + this.phase = source["phase"]; + this.error = source["error"]; + this.stats = this.convertValues(source["stats"], Stats); + } + + convertValues(a: any, classs: any, asMap: boolean = false): any { + if (!a) { + return a; + } + if (a.slice && a.map) { + return (a as any[]).map(elem => this.convertValues(elem, classs)); + } else if ("object" === typeof a) { + if (asMap) { + for (const key of Object.keys(a)) { + a[key] = new classs(a[key]); + } + return a; + } + return new classs(a); + } + return a; + } + } + +} + export namespace unlock { - + export class HandleInfo { pid: number; name: string; - + static createFrom(source: any = {}) { return new HandleInfo(source); } - + constructor(source: any = {}) { if ('string' === typeof source) source = JSON.parse(source); this.pid = source["pid"]; diff --git a/internal/database/cover.go b/internal/database/cover.go index afa00e3..d2c0c13 100644 --- a/internal/database/cover.go +++ b/internal/database/cover.go @@ -12,13 +12,13 @@ type TrackPath struct { } // GetAllTrackPaths returns the file paths of every available, analyzed track. -func GetAllTrackPaths() ([]TrackPath, error) { - dbPath, err := ResolveLibrary() +func GetAllTrackPaths(target ...string) ([]TrackPath, error) { + dbPath, err := resolveOperationLibrary(target) if err != nil { return nil, fmt.Errorf("no Engine Library found: %w", err) } - db, err := sql.Open("sqlite3", "file:"+dbPath+"?mode=ro&cache=shared") + db, err := sql.Open("sqlite3", sqliteURI(dbPath, "mode=ro&cache=shared")) if err != nil { return nil, fmt.Errorf("failed to open database: %w", err) } @@ -50,13 +50,13 @@ func GetAllTrackPaths() ([]TrackPath, error) { } // GetPlaylistTrackPaths returns file paths for all tracks in the given playlist. -func GetPlaylistTrackPaths(playlistID int) ([]TrackPath, error) { - dbPath, err := ResolveLibrary() +func GetPlaylistTrackPaths(playlistID int, target ...string) ([]TrackPath, error) { + dbPath, err := resolveOperationLibrary(target) if err != nil { return nil, fmt.Errorf("no Engine Library found: %w", err) } - db, err := sql.Open("sqlite3", "file:"+dbPath+"?mode=ro&cache=shared") + db, err := sql.Open("sqlite3", sqliteURI(dbPath, "mode=ro&cache=shared")) if err != nil { return nil, fmt.Errorf("failed to open database: %w", err) } diff --git a/internal/database/database.go b/internal/database/database.go index 017194f..7ce43c7 100644 --- a/internal/database/database.go +++ b/internal/database/database.go @@ -1,6 +1,7 @@ package database import ( + "EngineTools/internal/storage" "database/sql" "fmt" "io" @@ -133,7 +134,7 @@ type BackupInfo struct { } func backupDir() (string, error) { - dir := filepath.Join(os.Getenv("LOCALAPPDATA"), "EngineTools", "Backups") + dir := storage.Path("Backup", "Database") if err := os.MkdirAll(dir, 0755); err != nil { return "", fmt.Errorf("failed to create backup directory: %w", err) } @@ -281,7 +282,7 @@ func OptimizeDatabase() error { // CountTracks returns the number of tracks in the given database. func CountTracks(dbPath string) int { - db, err := sql.Open("sqlite3", "file:"+dbPath+"?mode=ro&cache=shared") + db, err := sql.Open("sqlite3", sqliteURI(dbPath, "mode=ro&cache=shared")) if err != nil { return 0 } @@ -359,3 +360,24 @@ func RepairDatabase() (string, error) { return report, nil } + +func resolveOperationLibrary(target []string) (string, error) { + if len(target) == 0 { + return ResolveLibrary() + } + path := target[0] + if !filepath.IsAbs(path) || !strings.EqualFold(filepath.Base(path), "m.db") { + return "", fmt.Errorf("invalid target library: %q", path) + } + if _, err := os.Stat(path); err != nil { + return "", err + } + return path, nil +} + +// sqliteURI opens exactly the given file. SQLite decodes %HH escapes in file +// URIs, so a literal name such as "DJ%20Set" must keep its percent signs. +func sqliteURI(path, query string) string { + escaped := strings.NewReplacer("%", "%25", "#", "%23", "?", "%3F").Replace(path) + return "file:" + escaped + "?" + query +} diff --git a/internal/database/missing.go b/internal/database/missing.go index 950195c..15c7172 100644 --- a/internal/database/missing.go +++ b/internal/database/missing.go @@ -15,13 +15,13 @@ type MissingTrack struct { } // FindMissingTracks returns all tracks where isAvailable = 0. -func FindMissingTracks() ([]MissingTrack, error) { - dbPath, err := ResolveLibrary() +func FindMissingTracks(target ...string) ([]MissingTrack, error) { + dbPath, err := resolveOperationLibrary(target) if err != nil { return nil, fmt.Errorf("no Engine Library found: %w", err) } - db, err := sql.Open("sqlite3", "file:"+dbPath+"?mode=ro&cache=shared") + db, err := sql.Open("sqlite3", sqliteURI(dbPath, "mode=ro&cache=shared")) if err != nil { return nil, fmt.Errorf("failed to open database: %w", err) } @@ -58,17 +58,17 @@ func FindMissingTracks() ([]MissingTrack, error) { // Only tracks that are actually unavailable (isAvailable = 0) will be removed — // available tracks are silently skipped for safety. // Returns the number of rows deleted. -func RemoveMissingTracks(ids []int) (int, error) { +func RemoveMissingTracks(ids []int, target ...string) (int, error) { if len(ids) == 0 { return 0, nil } - dbPath, err := ResolveLibrary() + dbPath, err := resolveOperationLibrary(target) if err != nil { return 0, fmt.Errorf("no Engine Library found: %w", err) } - db, err := sql.Open("sqlite3", dbPath) + db, err := sql.Open("sqlite3", sqliteURI(dbPath, "mode=rw")) if err != nil { return 0, fmt.Errorf("failed to open database: %w", err) } diff --git a/internal/database/playlist.go b/internal/database/playlist.go index 60e5c75..b00b607 100644 --- a/internal/database/playlist.go +++ b/internal/database/playlist.go @@ -28,13 +28,13 @@ type TrackInfo struct { Rating int `json:"rating"` } -func ListPlaylists() ([]PlaylistInfo, error) { - dbPath, err := ResolveLibrary() +func ListPlaylists(target ...string) ([]PlaylistInfo, error) { + dbPath, err := resolveOperationLibrary(target) if err != nil { return nil, err } - db, err := sql.Open("sqlite3", "file:"+dbPath+"?mode=ro&cache=shared") + db, err := sql.Open("sqlite3", sqliteURI(dbPath, "mode=ro&cache=shared")) if err != nil { return nil, fmt.Errorf("failed to open database: %w", err) } @@ -72,7 +72,7 @@ func GetPlaylistTracks(playlistID int) ([]TrackInfo, error) { return nil, err } - db, err := sql.Open("sqlite3", "file:"+dbPath+"?mode=ro&cache=shared") + db, err := sql.Open("sqlite3", sqliteURI(dbPath, "mode=ro&cache=shared")) if err != nil { return nil, fmt.Errorf("failed to open database: %w", err) } diff --git a/internal/database/stats.go b/internal/database/stats.go index 20461fd..ab2d04a 100644 --- a/internal/database/stats.go +++ b/internal/database/stats.go @@ -55,7 +55,7 @@ func GetLibraryStats() (*LibraryStats, error) { return nil, fmt.Errorf("no Engine Library found: %w", err) } - db, err := sql.Open("sqlite3", "file:"+dbPath+"?mode=ro&cache=shared") + db, err := sql.Open("sqlite3", sqliteURI(dbPath, "mode=ro&cache=shared")) if err != nil { return nil, fmt.Errorf("failed to open database: %w", err) } @@ -168,7 +168,7 @@ func GetPlayStats() (*PlayStats, error) { return nil, fmt.Errorf("no Engine Library found: %w", err) } - db, err := sql.Open("sqlite3", "file:"+dbPath+"?mode=ro&cache=shared") + db, err := sql.Open("sqlite3", sqliteURI(dbPath, "mode=ro&cache=shared")) if err != nil { return nil, fmt.Errorf("failed to open database: %w", err) } diff --git a/internal/database/sync.go b/internal/database/sync.go index adad6e1..1f68c85 100644 --- a/internal/database/sync.go +++ b/internal/database/sync.go @@ -8,14 +8,14 @@ import ( // SyncableTrack holds the analysis data that can be written back to a file's tags. type SyncableTrack struct { - ID int `json:"id"` - Title string `json:"title"` - Artist string `json:"artist"` - Path string `json:"path"` - BPM float64 `json:"bpm"` - Key int `json:"key"` - KeyName string `json:"keyName"` - Camelot string `json:"camelot"` + ID int `json:"id"` + Title string `json:"title"` + Artist string `json:"artist"` + Path string `json:"path"` + BPM float64 `json:"bpm"` + Key int `json:"key"` + KeyName string `json:"keyName"` + Camelot string `json:"camelot"` } // SyncResult summarises the outcome of a BPM/Key write-back operation. @@ -28,13 +28,13 @@ type SyncResult struct { // GetSyncableTracks returns all available, analyzed tracks that have BPM or // key data from Engine DJ, ready for write-back to ID3 tags. -func GetSyncableTracks() ([]SyncableTrack, error) { - dbPath, err := ResolveLibrary() +func GetSyncableTracks(target ...string) ([]SyncableTrack, error) { + dbPath, err := resolveOperationLibrary(target) if err != nil { return nil, fmt.Errorf("no Engine Library found: %w", err) } - db, err := sql.Open("sqlite3", "file:"+dbPath+"?mode=ro&cache=shared") + db, err := sql.Open("sqlite3", sqliteURI(dbPath, "mode=ro&cache=shared")) if err != nil { return nil, fmt.Errorf("failed to open database: %w", err) } diff --git a/internal/experimental/experimental.go b/internal/experimental/experimental.go index 44252aa..4c0cdab 100644 --- a/internal/experimental/experimental.go +++ b/internal/experimental/experimental.go @@ -1,80 +1,14 @@ package experimental import ( - "fmt" - "os" - "path/filepath" - "strings" - "syscall" + "EngineTools/internal/storage" "time" ) -func xmlPath() string { - return filepath.Join(os.Getenv("LOCALAPPDATA"), "EngineTools", "experimental_allow.xml") -} - -// LogEnabled creates or appends a timestamp entry to experimental_allow.xml. -// The file is kept hidden + read-only. Multiple calls append new entries. +// LogEnabled records activation in the shared settings file. func LogEnabled() error { - p := xmlPath() - if err := os.MkdirAll(filepath.Dir(p), 0755); err != nil { - return fmt.Errorf("mkdir: %w", err) - } - - ts := time.Now().Format(time.RFC3339) - newEntry := fmt.Sprintf(" \n", ts) - - if _, err := os.Stat(p); os.IsNotExist(err) { - // First time: create file - content := "\n" + - "\n" + newEntry + "\n" - if err := os.WriteFile(p, []byte(content), 0644); err != nil { - return fmt.Errorf("write: %w", err) - } - } else { - // Subsequent times: remove readonly, append new entry, re-apply attrs - if err := removeReadonly(p); err != nil { - return fmt.Errorf("removeReadonly: %w", err) - } - raw, err := os.ReadFile(p) - if err != nil { - return fmt.Errorf("read: %w", err) - } - content := strings.TrimRight(string(raw), "\r\n\t ") - const closing = "" - if strings.HasSuffix(content, closing) { - content = content[:len(content)-len(closing)] - } - content += "\n" + newEntry + closing + "\n" - if err := os.WriteFile(p, []byte(content), 0644); err != nil { - return fmt.Errorf("rewrite: %w", err) - } - } - return setHiddenReadonly(p) -} - -func setHiddenReadonly(path string) error { - ptr, err := syscall.UTF16PtrFromString(path) - if err != nil { - return err - } - attrs, err := syscall.GetFileAttributes(ptr) - if err != nil { - return err - } - attrs |= syscall.FILE_ATTRIBUTE_HIDDEN | syscall.FILE_ATTRIBUTE_READONLY - return syscall.SetFileAttributes(ptr, attrs) -} - -func removeReadonly(path string) error { - ptr, err := syscall.UTF16PtrFromString(path) - if err != nil { - return err - } - attrs, err := syscall.GetFileAttributes(ptr) - if err != nil { - return err - } - attrs &^= syscall.FILE_ATTRIBUTE_READONLY - return syscall.SetFileAttributes(ptr, attrs) + return storage.UpdateSettings(func(s *storage.Settings) { + s.ExperimentalEnabled = true + s.ExperimentalActivations = append(s.ExperimentalActivations, time.Now().Format(time.RFC3339)) + }) } diff --git a/internal/i18n/i18n.go b/internal/i18n/i18n.go index c7bdc5d..f68f0ff 100644 --- a/internal/i18n/i18n.go +++ b/internal/i18n/i18n.go @@ -211,6 +211,7 @@ type Messages struct { // Settings tab TabSettings string `json:"tabSettings"` SettingsLanguageLabel string `json:"settingsLanguageLabel"` + SettingsAlwaysOnTop string `json:"settingsAlwaysOnTop"` SettingsExperimentalLabel string `json:"settingsExperimentalLabel"` SettingsExperimentalDesc string `json:"settingsExperimentalDesc"` SettingsExperimentalConfirmTitle string `json:"settingsExperimentalConfirmTitle"` @@ -417,6 +418,7 @@ var translations = map[Lang]Messages{ TracksUnit: "首", TabSettings: "设置", SettingsLanguageLabel: "显示语言", + SettingsAlwaysOnTop: "始终置顶", SettingsExperimentalLabel: "开启实验性功能", SettingsExperimentalDesc: "解锁隐藏的开发者功能,请谨慎使用。", SettingsExperimentalConfirmTitle: "开启实验性功能", @@ -620,6 +622,7 @@ var translations = map[Lang]Messages{ TracksUnit: "曲", TabSettings: "設定", SettingsLanguageLabel: "表示言語", + SettingsAlwaysOnTop: "常に最前面に表示", SettingsExperimentalLabel: "実験的機能を有効にする", SettingsExperimentalDesc: "隠された開発者向け機能を解放します。慎重に扱ってください。", SettingsExperimentalConfirmTitle: "実験的機能の有効化", @@ -823,6 +826,7 @@ var translations = map[Lang]Messages{ TracksUnit: "곡", TabSettings: "설정", SettingsLanguageLabel: "표시 언어", + SettingsAlwaysOnTop: "항상 위에 표시", SettingsExperimentalLabel: "실험적 기능 활성화", SettingsExperimentalDesc: "숨겨진 개발자 기능을 활성화합니다. 신중하게 사용하세요.", SettingsExperimentalConfirmTitle: "실험적 기능 활성화", @@ -1026,6 +1030,7 @@ var translations = map[Lang]Messages{ TracksUnit: "more", TabSettings: "Settings", SettingsLanguageLabel: "Display Language", + SettingsAlwaysOnTop: "Always on top", SettingsExperimentalLabel: "Enable Experimental Features", SettingsExperimentalDesc: "Unlock hidden developer features. Handle with care.", SettingsExperimentalConfirmTitle: "Enable Experimental Features", diff --git a/internal/id3/antipiracy.go b/internal/id3/antipiracy.go index daac0f1..8f72931 100644 --- a/internal/id3/antipiracy.go +++ b/internal/id3/antipiracy.go @@ -1,11 +1,15 @@ package id3 import ( + "EngineTools/internal/storage" + "crypto/sha256" "encoding/json" "fmt" "math/rand" "os" "path/filepath" + "runtime" + "strings" "time" ) @@ -25,24 +29,61 @@ type BackupData struct { Tags []TagBackup `json:"tags"` } -func backupPath(dir string) string { - return filepath.Join(dir, ".id3_backup.json") +func backupPath(dir string) (string, error) { + return backupKeyPath(dir) } // backupKeyPath returns the backup file path given an arbitrary key. -// For directories, the backup sits inside the dir; for other keys (e.g. -// a playlist ID), it sits in the system's EngineTools data directory. -func backupKeyPath(key string) string { +// All new backups live beside the executable. Directory keys include a hash +// so different music directories with the same name cannot collide. +func backupKeyPath(key string) (string, error) { + dir := storage.Path("Backup", "ID3") + if err := os.MkdirAll(dir, 0755); err != nil { + return "", err + } if info, err := os.Stat(key); err == nil && info.IsDir() { - return filepath.Join(key, ".id3_backup.json") + absolute, err := filepath.Abs(key) + if err != nil { + return "", err + } + identity := filepath.Clean(absolute) + evaluated := "" + if runtime.GOOS == "windows" { + evaluated, err = filepath.EvalSymlinks(identity) + if err != nil { + return "", err + } + // EvalSymlinks fixes drive letters and directory entries but keeps a + // UNC volume exactly as written, so fold case for a stable identity. + identity = strings.ToLower(evaluated) + } + digest := sha256.Sum256([]byte(identity)) + target := filepath.Join(dir, fmt.Sprintf("directory-%x_backup.json", digest[:12])) + // Retain backups created with an earlier identity spelling. + for _, legacy := range []string{evaluated, absolute} { + if legacy == "" || legacy == identity { + continue + } + if _, err := os.Stat(target); err == nil { + break + } + legacyDigest := sha256.Sum256([]byte(legacy)) + legacyTarget := filepath.Join(dir, fmt.Sprintf("directory-%x_backup.json", legacyDigest[:12])) + if err := storage.Migrate(legacyTarget, target); err != nil { + return "", err + } + } + // Import a legacy backup from beside the audio files. + if err := storage.Migrate(filepath.Join(absolute, ".id3_backup.json"), target); err != nil { + return "", err + } + return target, nil } - dir := filepath.Join(os.Getenv("LOCALAPPDATA"), "EngineTools", "ap_backups") - os.MkdirAll(dir, 0755) safe := filepath.Base(key) if safe == "" || safe == "." { safe = "default" } - return filepath.Join(dir, safe+"_backup.json") + return filepath.Join(dir, safe+"_backup.json"), nil } // AntiPiracyV1Files clears all ID3 tags for the given list of file paths. @@ -61,7 +102,11 @@ func AntiPiracyV1Files(paths []string, backupKey string) (int, error) { } bd := BackupData{Mode: "v1", Timestamp: time.Now().Format(time.RFC3339), Dir: backupKey, Tags: backups} data, _ := json.MarshalIndent(bd, "", " ") - if err := os.WriteFile(backupKeyPath(backupKey), data, 0644); err != nil { + path, err := backupKeyPath(backupKey) + if err != nil { + return 0, err + } + if err := os.WriteFile(path, data, 0644); err != nil { return 0, fmt.Errorf("backup failed: %w", err) } count := 0 @@ -88,7 +133,11 @@ func AntiPiracyV2Files(paths []string, backupKey string) (int, error) { } bd := BackupData{Mode: "v2", Timestamp: time.Now().Format(time.RFC3339), Dir: backupKey, Tags: tags} data, _ := json.MarshalIndent(bd, "", " ") - if err := os.WriteFile(backupKeyPath(backupKey), data, 0644); err != nil { + path, err := backupKeyPath(backupKey) + if err != nil { + return 0, err + } + if err := os.WriteFile(path, data, 0644); err != nil { return 0, fmt.Errorf("backup failed: %w", err) } r := rand.New(rand.NewSource(time.Now().UnixNano())) @@ -113,7 +162,11 @@ func AntiPiracyV2Files(paths []string, backupKey string) (int, error) { // AntiPiracyRestoreFiles restores tags from the backup identified by backupKey. func AntiPiracyRestoreFiles(backupKey string) (int, error) { - data, err := os.ReadFile(backupKeyPath(backupKey)) + path, err := backupKeyPath(backupKey) + if err != nil { + return 0, err + } + data, err := os.ReadFile(path) if err != nil { return 0, fmt.Errorf("no backup found for key %q", backupKey) } @@ -127,7 +180,7 @@ func AntiPiracyRestoreFiles(backupKey string) (int, error) { count++ } } - os.Remove(backupKeyPath(backupKey)) + os.Remove(path) return count, nil } @@ -163,7 +216,11 @@ func AntiPiracyV1(dir string) (int, error) { Tags: backups, } data, _ := json.MarshalIndent(bd, "", " ") - if err := os.WriteFile(backupPath(dir), data, 0644); err != nil { + path, err := backupPath(dir) + if err != nil { + return 0, err + } + if err := os.WriteFile(path, data, 0644); err != nil { return 0, fmt.Errorf("failed to save backup: %w", err) } @@ -213,7 +270,11 @@ func AntiPiracyV2(dir string) (int, error) { Tags: backups, } data, _ := json.MarshalIndent(bd, "", " ") - if err := os.WriteFile(backupPath(dir), data, 0644); err != nil { + path, err := backupPath(dir) + if err != nil { + return 0, err + } + if err := os.WriteFile(path, data, 0644); err != nil { return 0, fmt.Errorf("failed to save backup: %w", err) } @@ -241,7 +302,10 @@ func AntiPiracyV2(dir string) (int, error) { } func AntiPiracyRestore(dir string) (int, error) { - bp := backupPath(dir) + bp, err := backupPath(dir) + if err != nil { + return 0, err + } data, err := os.ReadFile(bp) if err != nil { return 0, fmt.Errorf("no backup found in this directory") @@ -265,6 +329,10 @@ func AntiPiracyRestore(dir string) (int, error) { } func HasAntiPiracyBackup(dir string) bool { - _, err := os.Stat(backupPath(dir)) + path, err := backupPath(dir) + if err != nil { + return false + } + _, err = os.Stat(path) return err == nil } diff --git a/internal/logs/logs.go b/internal/logs/analysis.go similarity index 100% rename from internal/logs/logs.go rename to internal/logs/analysis.go diff --git a/internal/logs/daily.go b/internal/logs/daily.go new file mode 100644 index 0000000..c614298 --- /dev/null +++ b/internal/logs/daily.go @@ -0,0 +1,57 @@ +package logs + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "sync" + "time" +) + +type Daily struct { + Directory string + mu sync.Mutex +} + +func New(directory string) *Daily { return &Daily{Directory: directory} } + +func (d *Daily) Write(source, message string, at time.Time) (string, error) { + if at.IsZero() { + at = time.Now() + } + at = at.Local() + message = strings.ReplaceAll(strings.ReplaceAll(message, "\r\n", "\n"), "\r", "\n") + entry := fmt.Sprintf("[%s] [%s] %s", at.Format("2006-01-02 15:04:05.000"), source, strings.ReplaceAll(message, "\n", "\n ")) + d.mu.Lock() + defer d.mu.Unlock() + if err := os.MkdirAll(d.Directory, 0755); err != nil { + return entry, err + } + f, err := os.OpenFile(filepath.Join(d.Directory, at.Format("2006-01-02")+".log"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) + if err != nil { + return entry, err + } + _, writeErr := f.WriteString(entry + "\n") + closeErr := f.Close() + if writeErr != nil { + return entry, writeErr + } + return entry, closeErr +} + +// Framework logs go directly to disk to avoid recursively emitting UI events. +type Framework struct{ Daily *Daily } + +func (f *Framework) write(level, message string) { + if _, err := f.Daily.Write("framework/"+level, message, time.Time{}); err != nil { + fmt.Fprintln(os.Stderr, "Log write failed:", err) + } +} +func (f *Framework) Print(m string) { f.write("INFO", m) } +func (f *Framework) Trace(m string) { f.write("TRACE", m) } +func (f *Framework) Debug(m string) { f.write("DEBUG", m) } +func (f *Framework) Info(m string) { f.write("INFO", m) } +func (f *Framework) Warning(m string) { f.write("WARN", m) } +func (f *Framework) Error(m string) { f.write("ERROR", m) } +func (f *Framework) Fatal(m string) { f.write("FATAL", m); os.Exit(1) } diff --git a/internal/storage/storage.go b/internal/storage/storage.go new file mode 100644 index 0000000..10944d5 --- /dev/null +++ b/internal/storage/storage.go @@ -0,0 +1,288 @@ +package storage + +import ( + "crypto/sha256" + "encoding/json" + "encoding/xml" + "fmt" + "io" + "os" + "path/filepath" + "strings" + "sync" +) + +var settingsMu sync.Mutex + +// Path is anchored to the executable, never the caller's working directory. +func Path(parts ...string) string { + exe, err := os.Executable() + if err != nil { + panic(err) + } + return filepath.Join(append([]string{filepath.Dir(exe)}, parts...)...) +} + +type CompatibilityResult struct { + Hashes map[string]string `json:"hashes"` + Callers []uint32 `json:"callers"` + Validator string `json:"validator"` + CheckedAt string `json:"checkedAt"` +} + +type Settings struct { + EngineDJCompatibility map[string]CompatibilityResult `json:"engineDJCompatibility,omitempty"` + Language string `json:"language"` + Theme string `json:"theme"` + SquareCorners bool `json:"squareCorners"` + AlwaysOnTop bool `json:"alwaysOnTop"` + ExperimentalEnabled bool `json:"experimentalEnabled"` + ExperimentalActivations []string `json:"experimentalActivations,omitempty"` + TermsAccepted bool `json:"termsAccepted"` +} + +func readSettings() (Settings, error) { + s := Settings{Theme: "orange"} + data, err := os.ReadFile(Path("setting.json")) + if os.IsNotExist(err) { + return s, nil + } + if err != nil { + return s, err + } + if err = json.Unmarshal(data, &s); err != nil { + return s, fmt.Errorf("read setting.json: %w", err) + } + return s, nil +} + +func ReadSettings() (Settings, error) { + settingsMu.Lock() + defer settingsMu.Unlock() + return readSettings() +} + +func UpdateSettings(update func(*Settings)) error { + settingsMu.Lock() + defer settingsMu.Unlock() + s, err := readSettings() + if err != nil { + return err + } + update(&s) + data, err := json.MarshalIndent(s, "", " ") + if err != nil { + return err + } + f, err := os.CreateTemp(Path(), ".setting-*.tmp") + if err != nil { + return err + } + defer os.Remove(f.Name()) + if _, err = f.Write(append(data, '\n')); err != nil { + f.Close() + return err + } + if err = f.Close(); err != nil { + return err + } + return os.Rename(f.Name(), Path("setting.json")) +} + +// CopyMissing preserves originals and never overwrites an existing destination. +func CopyMissing(source, destination string) error { + if _, err := os.Stat(source); os.IsNotExist(err) { + return nil + } else if err != nil { + return err + } + return filepath.WalkDir(source, func(path string, entry os.DirEntry, walkErr error) error { + if walkErr != nil { + return walkErr + } + if entry.Type()&os.ModeSymlink != 0 { + return fmt.Errorf("migration refuses symbolic link: %s", path) + } + rel, err := filepath.Rel(source, path) + if err != nil { + return err + } + target := filepath.Join(destination, rel) + if entry.IsDir() { + return os.MkdirAll(target, 0755) + } + input, err := os.Open(path) + if err != nil { + return err + } + defer input.Close() + if _, err := os.Stat(target); err == nil { + return sameFile(path, target) + } else if !os.IsNotExist(err) { + return err + } + // Copy beside the target first so an interrupted run never leaves a + // partial file that later starts as a migration conflict. + output, err := os.CreateTemp(filepath.Dir(target), ".migration-*") + if err != nil { + return err + } + temp := output.Name() + defer os.Remove(temp) + if _, err = io.Copy(output, input); err != nil { + output.Close() + return err + } + if err = output.Sync(); err != nil { + output.Close() + return err + } + if err = output.Close(); err != nil { + return err + } + if err = os.Rename(temp, target); err != nil { + if _, statErr := os.Stat(target); statErr == nil { + return sameFile(path, target) + } + return err + } + return sameFile(path, target) + }) +} + +func sameFile(source, destination string) error { + hash := func(path string) ([32]byte, error) { + f, err := os.Open(path) + if err != nil { + return [32]byte{}, err + } + defer f.Close() + h := sha256.New() + _, err = io.Copy(h, f) + var result [32]byte + copy(result[:], h.Sum(nil)) + return result, err + } + a, err := hash(source) + if err != nil { + return err + } + b, err := hash(destination) + if err != nil { + return err + } + if a != b { + return fmt.Errorf("migration conflict, original retained: %s", source) + } + return nil +} + +// Migrate verifies every copied file before removing this specific legacy target. +func Migrate(source, destination string) error { + if !filepath.IsAbs(source) || !filepath.IsAbs(destination) || strings.EqualFold(filepath.Clean(source), filepath.Clean(destination)) { + return fmt.Errorf("invalid migration paths: %s -> %s", source, destination) + } + if _, err := os.Lstat(source); os.IsNotExist(err) { + return nil + } else if err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(destination), 0755); err != nil { + return err + } + if err := CopyMissing(source, destination); err != nil { + return err + } + return os.RemoveAll(source) +} + +// Remove only the old executable-specific WebView data, not the new local profile. +func removeLegacyWebView(appData, executableName string) error { + if !filepath.IsAbs(appData) || executableName == "" || filepath.Base(executableName) != executableName || executableName == "." || executableName == ".." { + return fmt.Errorf("invalid legacy WebView path") + } + oldRoot := filepath.Join(appData, executableName) + if err := os.RemoveAll(filepath.Join(oldRoot, "EBWebView")); err != nil { + return err + } + // Remove the parent only if it is empty. + os.Remove(oldRoot) + return nil +} + +func Prepare() error { + for _, part := range []string{"Backup", filepath.Join("Backup", "Database"), filepath.Join("Backup", "ID3"), "WebView", "Log"} { + if err := os.MkdirAll(Path(part), 0755); err != nil { + return err + } + } + local := os.Getenv("LOCALAPPDATA") + if !filepath.IsAbs(local) { + return fmt.Errorf("LOCALAPPDATA must be an absolute directory") + } + legacy := filepath.Join(local, "EngineTools") + for source, destination := range map[string]string{"Backups": "Database", "ap_backups": "ID3"} { + if err := Migrate(filepath.Join(legacy, source), Path("Backup", destination)); err != nil { + return err + } + } + var audit struct { + Activations []struct { + Timestamp string `xml:"timestamp,attr"` + } `xml:"activation"` + } + auditPath := filepath.Join(legacy, "experimental_allow.xml") + if data, err := os.ReadFile(auditPath); err == nil { + if err = xml.Unmarshal(data, &audit); err != nil { + return err + } + } else if !os.IsNotExist(err) { + return err + } + if err := UpdateSettings(func(s *Settings) { + if _, err := os.Stat(filepath.Join(legacy, ".terms_accepted")); err == nil { + s.TermsAccepted = true + } + for _, activation := range audit.Activations { + found := false + for _, existing := range s.ExperimentalActivations { + if existing == activation.Timestamp { + found = true + break + } + } + if !found { + s.ExperimentalActivations = append(s.ExperimentalActivations, activation.Timestamp) + } + } + }); err != nil { + return err + } + for _, name := range []string{".terms_accepted", "experimental_allow.xml"} { + path := filepath.Join(legacy, name) + if _, err := os.Stat(path); os.IsNotExist(err) { + continue + } else if err != nil { + return err + } + if err := os.Chmod(path, 0600); err != nil { + return err + } + if err := os.Remove(path); err != nil { + return err + } + } + exe, err := os.Executable() + if err != nil { + return err + } + if err := removeLegacyWebView(os.Getenv("APPDATA"), filepath.Base(exe)); err != nil { + return err + } + // The retired temporary injection mode has no data worth migrating. + if err := os.RemoveAll(filepath.Join(legacy, "engine-cache")); err != nil { + return err + } + os.Remove(legacy) + return nil +} diff --git a/internal/uifix/README.md b/internal/uifix/README.md new file mode 100644 index 0000000..11152f8 --- /dev/null +++ b/internal/uifix/README.md @@ -0,0 +1,94 @@ +# Engine DJ DLL patch + +Windows x64 cache deployed only as a self-contained version.dll proxy. +EngineTools installs, uninstalls and monitors it; it does not launch, attach to, +or close Engine DJ. Python, Frida and a separate background executable are not used. + +## Installation and monitoring + +Close Engine DJ before installing or uninstalling the DLL. Installation adds +version.dll beside Engine DJ.exe and never overwrites a third-party proxy. +The proxy contains a checksummed configuration trailer with the verified +EXE/Qt hashes and query caller RVAs. No configuration sidecar is installed. +Updates and removal require a validated EngineTools-owned proxy. + +Engine DJ starts caching automatically when launched normally. EngineTools +can be closed and reopened without affecting the cache. Status, hits, +fallbacks, refreshes and errors are read from a read-only view of +Local\\EngineToolsCache-. The mapping belongs to Engine DJ, +requires no external heartbeat and disappears when Engine DJ exits. +There is no temporary injection mode, launch.json or persistent engine-cache directory. + +The proxy forwards the 17 Windows version.dll exports to the real System32 +DLL. DllMain starts a worker only in Engine DJ, without waiting, loading Qt, +hashing or installing hooks under the loader lock. A compatibility probe +loads the same embedded proxy in an isolated process without starting that worker. + +## Compatibility + +Known EXE/Core/Network hash combinations use reviewed profiles (5.1.0 and +5.3.0). Unknown combinations use PE import and x64 instruction-boundary scanning. +Displayed Engine DJ version strings do not select compatibility. + +Unknown builds also run an isolated Qt ABI probe before installation. A +temporary copy of the embedded version.dll is removed after the probe process +exits, including failed probes. Successful file hashes, caller RVAs, validation +time and detector identity are saved in setting.json. Matching EXE/Qt files and +detector identity reuse the result across restarts without scanning or probing. +Any target file or detector change invalidates the saved result. Failed checks +are never saved, and unrelated settings updates preserve verified profiles. +ABI checks cover object sizes, construction/copy/destruction, list traversal, +and lookup/name/index round trips. Missing capabilities, ambiguous call sites, +unsupported architectures, crashes or timeouts reject installation. + +Empty interface names from verified callers return a Qt-constructed invalid +interface directly without enumerating adapters. They are logged separately +and excluded from lookup, hit and fallback counters and the hit-rate display. The ABI +probe checks this result against the target Qt library's original empty lookup. +Only verified interfaceFromName callers use the cache. Other callers, misses +and snapshots older than three seconds use the original Qt function. Snapshot +refresh runs every second. Persistent refresh failure removes the hook; +trampoline memory stays loaded until Engine DJ exits. + +An Engine DJ/Qt update invalidates the installed compatibility hashes. The +proxy keeps forwarding version calls, disables caching and reports the mismatch. +Close Engine DJ and reinstall the DLL to update its configuration. + +## Logging + +EngineTools writes application, frontend and framework messages to +Log/YYYY-MM-DD.log beside its executable, using the system's local date. +Files are appended across restarts and rotate when the date changes. +UI history is capped at 2000 entries; daily files retain the complete collected log. + +Proxy protocol 3 adds an in-memory ring of the latest 64 fallback records: +system timestamp, reason, queried interface name/index and caller RVA. +Reasons distinguish an expired snapshot, invalid name parameters, a missing +snapshot entry and a lookup exception. EngineTools drains the ring every two +seconds into the same daily log. Reopening EngineTools reads retained records; +overwritten records are reported with a lost-record count. No file I/O runs +inside the hooked Qt query. Old protocol-2 proxies still expose counters but +need reinstalling before fallback details can be collected. + +## Build and verification + +Run native\\build.cmd with x64 MSVC. It builds only version.dll and copies it +to assets\\version.bin for Go embedding. It does not build an EngineTools EXE. +Keep native source and this embedded asset synchronized. +The script locates Visual Studio C++ tools with vswhere, or uses an existing +x64 Native Tools Command Prompt environment. + +Native directory layout: + +- `native/src/`: proxy forwarding, cache hooks, shared protocol and exports. +- `native/minhook/`: vendored MinHook sources. +- `native/build/`: generated DLL and compiler intermediates (ignored by Git). +- `native/build.cmd`: x64 MSVC build entry point. +- `assets/version.bin`: embedded DLL payload used by the Go installer. + +Install protection is covered by runtime checks against a closed Engine DJ +installation; the repository has no automated tests for these paths. Run +`go test ./...` to compile the packages. These checks do not start Engine DJ. +Network switching and hardware reconnection require runtime verification. + +MinHook v1.3.4 is vendored at native/minhook; its license is in THIRD_PARTY.txt. diff --git a/internal/uifix/THIRD_PARTY.txt b/internal/uifix/THIRD_PARTY.txt new file mode 100644 index 0000000..74dea27 --- /dev/null +++ b/internal/uifix/THIRD_PARTY.txt @@ -0,0 +1,81 @@ +MinHook - The Minimalistic API Hooking Library for x64/x86 +Copyright (C) 2009-2017 Tsuda Kageyu. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +================================================================================ +Portions of this software are Copyright (c) 2008-2009, Vyacheslav Patkov. +================================================================================ +Hacker Disassembler Engine 32 C +Copyright (c) 2008-2009, Vyacheslav Patkov. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------------------- +Hacker Disassembler Engine 64 C +Copyright (c) 2008-2009, Vyacheslav Patkov. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/internal/uifix/assets/version.bin b/internal/uifix/assets/version.bin new file mode 100644 index 0000000..4ef6e38 Binary files /dev/null and b/internal/uifix/assets/version.bin differ diff --git a/internal/uifix/compatibility.go b/internal/uifix/compatibility.go new file mode 100644 index 0000000..b595902 --- /dev/null +++ b/internal/uifix/compatibility.go @@ -0,0 +1,104 @@ +package uifix + +import ( + "EngineTools/internal/storage" + "crypto/sha256" + "encoding/hex" + "fmt" + "io" + "os" + "path/filepath" +) + +// A profile identifies the complete ABI/call-site combination, not a displayed +// version string. Add a profile only after reviewing and testing that build. +type buildProfile struct { + Name string + Hashes map[string]string + Callers []uint32 + Automatic bool + Cached bool +} + +const maxCacheCallers = 16 +const cacheProtocol = 3 +const cacheSharedWords = 16 + maxCacheCallers + +var supportedBuilds = []buildProfile{ + { + Name: "Engine DJ 5.1.0 / Qt 6.7.2 (Windows x64)", + Hashes: map[string]string{ + "Engine DJ.exe": "68ed3eb6a51cf0db4f0e1f868da71b83e20fca293a2c589693126c0c24414028", + "Qt6Network.dll": "55733e8c1d6cb87a051f9a3c8cf510d1a59d4fa8a25bbf6eebd8254c60eefdf1", + "Qt6Core.dll": "8365fe1700df83c288fbc172113536a77009a8990e3e47ca69d42d3f0a7f9dbd", + }, + Callers: []uint32{0xd1c766, 0xd1d403, 0xd71ff3, 0xd7438c}, + }, + { + Name: "Engine DJ 5.3.0 / Qt 6.7.2 (Windows x64)", + Hashes: map[string]string{ + "Engine DJ.exe": "a4873db163484bcda37952148291e169b634299cf935d50730e5a1f8c6d06082", + "Qt6Network.dll": "117efdc1315137794c184b865b569ea3221b8472fd66715b9bb4d6c5bd54f3fa", + "Qt6Core.dll": "8aa75c154ade9194051d8e781104d51f7717c5f175392c8a44ef0c8ad3dd62d6", + }, + Callers: []uint32{0xd72cc6, 0xd73224, 0xd73963, 0xdc80a4, 0xdc8a13, 0xdcadac, 0xfac564}, + }, +} + +func selectBuild(hashes map[string]string) (*buildProfile, error) { + for i := range supportedBuilds { + profile := &supportedBuilds[i] + match := true + for name, expected := range profile.Hashes { + if hashes[name] != expected { + match = false + break + } + } + if match { + return profile, nil + } + } + return nil, fmt.Errorf("Unsupported Engine DJ/Qt build: no verified compatibility profile matches all three files") +} + +func matchBuild(directory string) (*buildProfile, error) { + hashes, err := hashBuildFiles(directory) + if err != nil { + return nil, err + } + profile, err := selectBuild(hashes) + if err == nil { + return profile, nil + } + settings, err := storage.ReadSettings() + if err != nil { + return nil, err + } + if profile := cachedCompatibility(hashes, settings.EngineDJCompatibility); profile != nil { + return profile, nil + } + profile, err = scanAutomaticBuild(directory, hashes) + if err != nil { + return nil, fmt.Errorf("Unsupported Engine DJ/Qt layout: automatic detection failed: %w", err) + } + return profile, nil +} + +func hashBuildFiles(directory string) (map[string]string, error) { + hashes := make(map[string]string, 3) + for _, name := range []string{"Engine DJ.exe", "Qt6Core.dll", "Qt6Network.dll"} { + file, err := os.Open(filepath.Join(directory, name)) + if err != nil { + return nil, err + } + digest := sha256.New() + _, err = io.Copy(digest, file) + file.Close() + if err != nil { + return nil, err + } + hashes[name] = hex.EncodeToString(digest.Sum(nil)) + } + return hashes, nil +} diff --git a/internal/uifix/diagnostics.go b/internal/uifix/diagnostics.go new file mode 100644 index 0000000..125609a --- /dev/null +++ b/internal/uifix/diagnostics.go @@ -0,0 +1,105 @@ +package uifix + +import ( + "fmt" + "sync/atomic" + "time" + "unsafe" + + "golang.org/x/sys/windows" +) + +const diagnosticCapacity = 64 +const diagnosticEntryBytes = 512 +const diagnosticMappingBytes = 256 + 16 + diagnosticCapacity*diagnosticEntryBytes + +type diagnosticCursor struct{ session, sequence uint64 } +type FallbackRecord struct { + ExcludedFromStats bool + Sequence uint64 + At time.Time + Reason string + Interface string + Caller uint32 +} + +func fallbackReason(reason uint32) string { + switch reason { + case 1: + return "快照超过3秒未更新" + case 2: + return "接口名称参数无效" + case 3: + return "接口名称或索引未命中快照" + case 4: + return "缓存查询发生异常" + case 5: + return "空接口名称,已直接返回无效接口,不计入命中率统计" + default: + return fmt.Sprintf("未知原因(%d)", reason) + } +} + +func (m *Manager) DrainFallbacks(pid uint32) ([]FallbackRecord, uint64) { + m.mu.Lock() + defer m.mu.Unlock() + name, _ := windows.UTF16PtrFromString(fmt.Sprintf("Local\\EngineToolsCache-%d", pid)) + raw, _, _ := kernel.NewProc("OpenFileMappingW").Call(windows.FILE_MAP_READ, 0, uintptr(unsafe.Pointer(name))) + if raw == 0 { + return nil, 0 + } + handle := windows.Handle(raw) + defer windows.CloseHandle(handle) + address, err := windows.MapViewOfFile(handle, windows.FILE_MAP_READ, 0, 0, diagnosticMappingBytes) + if err != nil { + return nil, 0 + } // Older DLLs expose statistics only. + defer windows.UnmapViewOfFile(address) + return m.drainFallbackMapping(pid, address) +} + +func (m *Manager) drainFallbackMapping(pid uint32, address uintptr) ([]FallbackRecord, uint64) { + load := func(offset uintptr) uint64 { return atomic.LoadUint64((*uint64)(unsafe.Pointer(address + offset))) } + if load(0) != 0x45435431 || load(8) != cacheProtocol || load(16) != uint64(pid) { + return nil, 0 + } + if m.diagnostics == nil { + m.diagnostics = make(map[uint32]diagnosticCursor) + } + count, session := load(256), load(264) + cursor := m.diagnostics[pid] + if cursor.session != session || cursor.sequence > count { + cursor = diagnosticCursor{session: session} + } + first := uint64(1) + if count >= diagnosticCapacity { + first = count - diagnosticCapacity + 1 + } + var dropped uint64 + if cursor.sequence+1 < first { + dropped = first - cursor.sequence - 1 + cursor.sequence = first - 1 + } + var records []FallbackRecord + for sequence := cursor.sequence + 1; sequence <= count; sequence++ { + offset := uintptr(272 + ((sequence-1)%diagnosticCapacity)*diagnosticEntryBytes) + if load(offset) != sequence { + break + } + stamp := load(offset + 8) + reason := *(*uint32)(unsafe.Pointer(address + offset + 16)) + caller := *(*uint32)(unsafe.Pointer(address + offset + 20)) + var text [240]uint16 + copy(text[:], (*[240]uint16)(unsafe.Pointer(address + offset + 24))[:]) + if load(offset) != sequence { + break + } + ft := windows.Filetime{LowDateTime: uint32(stamp), HighDateTime: uint32(stamp >> 32)} + records = append(records, FallbackRecord{ExcludedFromStats: reason == 5, Sequence: sequence, At: time.Unix(0, ft.Nanoseconds()), Reason: fallbackReason(reason), Interface: windows.UTF16ToString(text[:]), Caller: caller}) + cursor.sequence = sequence + } + // Only one selected Engine DJ process is monitored at a time. + clear(m.diagnostics) + m.diagnostics[pid] = cursor + return records, dropped +} diff --git a/internal/uifix/install.go b/internal/uifix/install.go new file mode 100644 index 0000000..a2d1ece --- /dev/null +++ b/internal/uifix/install.go @@ -0,0 +1,260 @@ +package uifix + +import ( + "bytes" + "crypto/sha256" + _ "embed" + "encoding/binary" + "encoding/hex" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "sync/atomic" + "unsafe" + + "golang.org/x/sys/windows" +) + +//go:embed assets/version.bin +var proxyBinary []byte + +const proxyMagic = "EngineToolsPrx01" +const proxyFooterSize = 256 + +type proxyConfig struct { + Hashes [3][32]byte + Callers []uint32 +} + +var proxyFiles = []string{"Engine DJ.exe", "Qt6Core.dll", "Qt6Network.dll"} + +func makeProxy(profile *buildProfile) ([]byte, error) { + if len(profile.Callers) == 0 || len(profile.Callers) > maxCacheCallers { + return nil, errors.New("Invalid proxy call-site count") + } + footer := make([]byte, proxyFooterSize) + copy(footer, proxyMagic) + binary.LittleEndian.PutUint32(footer[16:], 1) + binary.LittleEndian.PutUint32(footer[20:], uint32(len(profile.Callers))) + for i, name := range proxyFiles { + hash, err := hex.DecodeString(profile.Hashes[name]) + if err != nil || len(hash) != 32 { + return nil, fmt.Errorf("Invalid compatibility hash: %s", name) + } + copy(footer[24+i*32:], hash) + } + for i, caller := range profile.Callers { + binary.LittleEndian.PutUint32(footer[120+i*4:], caller) + } + digest := sha256.Sum256(proxyBinary) + copy(footer[184:], digest[:]) + binary.LittleEndian.PutUint64(footer[216:], uint64(len(proxyBinary))) + checksum := sha256.Sum256(footer[:224]) + copy(footer[224:], checksum[:]) + return append(append([]byte(nil), proxyBinary...), footer...), nil +} + +// Ownership is established before either update or removal. Unknown version.dll +// files are never renamed, overwritten or deleted. +func parseProxy(data []byte) (*proxyConfig, error) { + if len(data) <= proxyFooterSize { + return nil, errors.New("Not an EngineTools proxy") + } + f := data[len(data)-proxyFooterSize:] + count := binary.LittleEndian.Uint32(f[20:]) + if string(f[:16]) != proxyMagic || binary.LittleEndian.Uint32(f[16:]) != 1 || count == 0 || count > maxCacheCallers || + binary.LittleEndian.Uint64(f[216:]) != uint64(len(data)-proxyFooterSize) { + return nil, errors.New("Unrecognized version.dll; refusing to change it") + } + payload, checksum := sha256.Sum256(data[:len(data)-proxyFooterSize]), sha256.Sum256(f[:224]) + if !bytes.Equal(payload[:], f[184:216]) || !bytes.Equal(checksum[:], f[224:]) { + return nil, errors.New("EngineTools proxy integrity check failed; file left unchanged") + } + c := &proxyConfig{} + for i := range c.Hashes { + copy(c.Hashes[i][:], f[24+i*32:24+(i+1)*32]) + } + for i := uint32(0); i < count; i++ { + c.Callers = append(c.Callers, binary.LittleEndian.Uint32(f[120+i*4:])) + } + return c, nil +} + +func installation(directory string) (bool, string, string) { + if directory == "" { + return false, "missing", "" + } + data, err := os.ReadFile(filepath.Join(directory, "version.dll")) + if os.IsNotExist(err) { + return false, "missing", "" + } + if err != nil { + return false, "conflict", err.Error() + } + if _, err = parseProxy(data); err != nil { + return false, "conflict", err.Error() + } + if !bytes.Equal(data[:len(data)-proxyFooterSize], proxyBinary) { + return true, "outdated", "" + } + return true, "installed", "" +} + +func (m *Manager) Install(directory string) error { + m.mu.Lock() + defer m.mu.Unlock() + if !filepath.IsAbs(directory) { + return errors.New("Engine DJ installation path must be absolute") + } + if pid, err := findEngine(directory); err != nil { + return err + } else if pid != 0 { + return errors.New("Close Engine DJ before installing the cache") + } + target := filepath.Join(directory, "version.dll") + previous, err := os.ReadFile(target) + exists := err == nil + if err != nil && !os.IsNotExist(err) { + return err + } + if exists { + if _, err = parseProxy(previous); err != nil { + return err + } + } + profile, err := matchBuild(directory) + if err != nil { + return err + } + if profile.Automatic && !profile.Cached { + dll, cleanup, err := extractProbeDLL() + if err != nil { + return err + } + defer cleanup() + if err = checkAutomaticABI(directory, dll, profile); err != nil { + return err + } + if err = saveVerifiedCompatibility(directory, profile); err != nil { + return fmt.Errorf("Save compatibility result: %w", err) + } + } + data, err := makeProxy(profile) + if err != nil { + return err + } + file, err := os.CreateTemp(directory, ".enginetools-proxy-*.tmp") + if err != nil { + return err + } + defer os.Remove(file.Name()) + if _, err = file.Write(data); err != nil { + file.Close() + return err + } + if err = file.Sync(); err != nil { + file.Close() + return err + } + if err = file.Close(); err != nil { + return err + } + if pid, err := findEngine(directory); err != nil { + return err + } else if pid != 0 { + return errors.New("Engine DJ started during installation; close it and retry") + } + if exists { + if err := removeOwnedProxy(target, previous); err != nil { + return err + } + } + from, _ := windows.UTF16PtrFromString(file.Name()) + to, _ := windows.UTF16PtrFromString(target) + if err = windows.MoveFileEx(from, to, windows.MOVEFILE_WRITE_THROUGH); err != nil { + if exists { + return fmt.Errorf("Previous EngineTools DLL removed, but replacement failed; close Engine DJ and retry: %w", err) + } + return err + } + return nil +} + +func (m *Manager) Uninstall(directory string) error { + m.mu.Lock() + defer m.mu.Unlock() + if !filepath.IsAbs(directory) { + return errors.New("Engine DJ installation path must be absolute") + } + if pid, err := findEngine(directory); err != nil { + return err + } else if pid != 0 { + return errors.New("Close Engine DJ before uninstalling the cache") + } + target := filepath.Join(directory, "version.dll") + err := removeOwnedProxy(target, nil) + if os.IsNotExist(err) { + return nil + } + return err +} + +// Validate and mark the same file for deletion while denying write/delete sharing. +func removeOwnedProxy(path string, expected []byte) error { + name, err := windows.UTF16PtrFromString(path) + if err != nil { + return err + } + handle, err := windows.CreateFile(name, windows.GENERIC_READ|windows.DELETE, windows.FILE_SHARE_READ, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT, 0) + if err != nil { + return err + } + file := os.NewFile(uintptr(handle), path) + defer file.Close() + data, err := io.ReadAll(file) + if err != nil { + return err + } + if _, err = parseProxy(data); err != nil { + return err + } + if expected != nil && !bytes.Equal(data, expected) { + return errors.New("version.dll changed during installation; file left unchanged") + } + deleteFile := byte(1) // FILE_DISPOSITION_INFO.DeleteFile is a Win32 BOOLEAN. + return windows.SetFileInformationByHandle(handle, windows.FileDispositionInfo, &deleteFile, 1) +} + +func readStandalone(pid uint32, state *State) bool { + name, _ := windows.UTF16PtrFromString(fmt.Sprintf("Local\\EngineToolsCache-%d", pid)) + raw, _, _ := kernel.NewProc("OpenFileMappingW").Call(windows.FILE_MAP_READ, 0, uintptr(unsafe.Pointer(name))) + if raw == 0 { + return false + } + handle := windows.Handle(raw) + defer windows.CloseHandle(handle) + address, err := windows.MapViewOfFile(handle, windows.FILE_MAP_READ, 0, 0, cacheSharedWords*8) + if err != nil { + return false + } + defer windows.UnmapViewOfFile(address) + words := (*[cacheSharedWords]uint64)(unsafe.Pointer(address)) + load := func(i int) uint64 { return atomic.LoadUint64(&words[i]) } + if load(0) != 0x45435431 || (load(1) != cacheProtocol && load(1) != 2) || load(2) != uint64(pid) { + return false + } + phase := load(4) + state.Active, state.Busy = phase == 2, phase == 1 || phase == 5 + state.Phase = map[uint64]string{1: "starting", 2: "active", 3: "idle", 4: "error", 5: "stopping"}[phase] + state.Error = "" + if code := load(5); code != 0 { + state.Error = nativeError(code).Error() + if code == 501 { + state.InstallStatus = "outdated" + } + } + state.Stats = Stats{Lookups: load(7), Hits: load(8), Misses: load(9), Refreshes: load(10), Errors: load(11), Interfaces: load(12), AgeMS: load(6)} + return true +} diff --git a/internal/uifix/manager.go b/internal/uifix/manager.go new file mode 100644 index 0000000..f2a2256 --- /dev/null +++ b/internal/uifix/manager.go @@ -0,0 +1,118 @@ +package uifix + +import ( + "crypto/sha256" + _ "embed" + "encoding/hex" + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "sync" + + "EngineTools/internal/process" + "golang.org/x/sys/windows" +) + +//go:embed THIRD_PARTY.txt +var Licenses string + +type Stats struct { + Lookups uint64 `json:"lookups"` + Hits uint64 `json:"hits"` + Misses uint64 `json:"misses"` + Refreshes uint64 `json:"refreshes"` + Errors uint64 `json:"errors"` + AgeMS uint64 `json:"ageMs"` + Interfaces uint64 `json:"interfaces"` +} + +type State struct { + Installed bool `json:"installed"` + InstallStatus string `json:"installStatus"` + InstallError string `json:"installError"` + ProxyVersion string `json:"proxyVersion"` + Running bool `json:"running"` + PID uint32 `json:"pid"` + Active bool `json:"active"` + Busy bool `json:"busy"` + Phase string `json:"phase"` + Error string `json:"error"` + Stats Stats `json:"stats"` +} + +type Manager struct { + mu sync.Mutex + diagnostics map[uint32]diagnosticCursor +} + +func New() *Manager { return &Manager{} } + +func findEngine(directory string) (uint32, error) { + if directory == "" { + return 0, nil + } + items, err := process.FindRunningExesInDir(directory) + if err != nil { + return 0, err + } + var pid uint32 + expected := filepath.Join(directory, "Engine DJ.exe") + for _, item := range items { + if strings.EqualFold(item.Name, "Engine DJ.exe") { + if !strings.EqualFold(filepath.Clean(item.ExePath), filepath.Clean(expected)) { + return 0, errors.New("Engine DJ is running from a different installation") + } + if pid != 0 { + return 0, errors.New("Multiple Engine DJ processes are running") + } + pid = item.PID + } + } + return pid, nil +} + +func (m *Manager) Status(directory string) State { + m.mu.Lock() + defer m.mu.Unlock() + state := State{Phase: "idle"} + state.Installed, state.InstallStatus, state.InstallError = installation(directory) + if state.Installed { + if data, err := os.ReadFile(filepath.Join(directory, "version.dll")); err == nil && len(data) > proxyFooterSize { + digest := sha256.Sum256(data[:len(data)-proxyFooterSize]) + state.ProxyVersion = hex.EncodeToString(digest[:6]) + } + } + pid, err := findEngine(directory) + state.Running, state.PID = pid != 0, pid + if pid != 0 { + readStandalone(pid, &state) + } + if err != nil { + state.Error = err.Error() + } + return state +} + +var kernel = windows.NewLazySystemDLL("kernel32.dll") + +func nativeError(code uint64) error { + switch code { + case 500: + return errors.New("Installed cache configuration is invalid; reinstall the cache") + case 501: + return errors.New("Engine DJ or Qt has changed; close Engine DJ and reinstall the cache") + case 15: + return errors.New("Engine DJ network query call sites do not match the selected compatibility profile") + case 302: + return errors.New("Network snapshot expired; cache disabled and original queries restored") + case 303: + return errors.New("Cache refresh thread did not stop; restart Engine DJ before enabling the cache again") + default: + if code >= 330 && code < 350 { + return errors.New("Cache hook removal failed; close and restart Engine DJ") + } + return fmt.Errorf("Could not enable the native cache (code %d)", code) + } +} diff --git a/internal/uifix/native/.gitignore b/internal/uifix/native/.gitignore new file mode 100644 index 0000000..84c048a --- /dev/null +++ b/internal/uifix/native/.gitignore @@ -0,0 +1 @@ +/build/ diff --git a/internal/uifix/native/build.cmd b/internal/uifix/native/build.cmd new file mode 100644 index 0000000..7f98b3f --- /dev/null +++ b/internal/uifix/native/build.cmd @@ -0,0 +1,30 @@ +@echo off +setlocal +if /i "%VSCMD_ARG_TGT_ARCH%"=="x64" goto build +set "ENGINETOOLS_VSWHERE=%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" +if not exist "%ENGINETOOLS_VSWHERE%" ( + echo [ERROR] Visual Studio C++ tools not found. Run from an x64 Native Tools Command Prompt. + exit /b 1 +) +for /f "usebackq delims=" %%I in (`"%ENGINETOOLS_VSWHERE%" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath`) do set "ENGINETOOLS_VSROOT=%%I" +if not defined ENGINETOOLS_VSROOT ( + echo [ERROR] Install the Visual Studio Desktop development with C++ workload. + exit /b 1 +) +call "%ENGINETOOLS_VSROOT%\VC\Auxiliary\Build\vcvars64.bat" >nul +if errorlevel 1 exit /b 1 +:build +if not exist "%~dp0build" mkdir "%~dp0build" +cd /d "%~dp0build" +if errorlevel 1 ( + echo [ERROR] Cannot enter "%~dp0build". + exit /b 1 +) +cl /nologo /O2 /MT /W4 /c ..\minhook\src\buffer.c ..\minhook\src\hook.c ..\minhook\src\trampoline.c ..\minhook\src\hde\hde64.c +if errorlevel 1 exit /b 1 +ml64 /nologo /c ..\src\version_exports.asm +if errorlevel 1 exit /b 1 +cl /nologo /std:c++17 /EHsc /O2 /MT /W4 /LD ..\src\interface_cache.cpp ..\src\version_proxy.cpp version_exports.obj buffer.obj hook.obj trampoline.obj hde64.obj bcrypt.lib /link /DEF:..\src\version.def /OUT:version.dll /IMPLIB:version.lib +if errorlevel 1 exit /b 1 +copy /y version.dll ..\..\assets\version.bin >nul +if errorlevel 1 exit /b 1 diff --git a/internal/uifix/native/minhook/AUTHORS.txt b/internal/uifix/native/minhook/AUTHORS.txt new file mode 100644 index 0000000..ebef1a6 --- /dev/null +++ b/internal/uifix/native/minhook/AUTHORS.txt @@ -0,0 +1,8 @@ +Tsuda Kageyu + Creator, maintainer + +Michael Maltsev + Added "Queue" functions. A lot of bug fixes. + +Andrey Unis + Rewrote the hook engine in plain C. diff --git a/internal/uifix/native/minhook/LICENSE.txt b/internal/uifix/native/minhook/LICENSE.txt new file mode 100644 index 0000000..74dea27 --- /dev/null +++ b/internal/uifix/native/minhook/LICENSE.txt @@ -0,0 +1,81 @@ +MinHook - The Minimalistic API Hooking Library for x64/x86 +Copyright (C) 2009-2017 Tsuda Kageyu. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER +OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +================================================================================ +Portions of this software are Copyright (c) 2008-2009, Vyacheslav Patkov. +================================================================================ +Hacker Disassembler Engine 32 C +Copyright (c) 2008-2009, Vyacheslav Patkov. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +------------------------------------------------------------------------------- +Hacker Disassembler Engine 64 C +Copyright (c) 2008-2009, Vyacheslav Patkov. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/internal/uifix/native/minhook/include/MinHook.h b/internal/uifix/native/minhook/include/MinHook.h new file mode 100644 index 0000000..bd86f1d --- /dev/null +++ b/internal/uifix/native/minhook/include/MinHook.h @@ -0,0 +1,187 @@ +/* + * MinHook - The Minimalistic API Hooking Library for x64/x86 + * Copyright (C) 2009-2017 Tsuda Kageyu. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER + * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#if !(defined _M_IX86) && !(defined _M_X64) && !(defined __i386__) && !(defined __x86_64__) + #error MinHook supports only x86 and x64 systems. +#endif + +#include + +// MinHook Error Codes. +typedef enum MH_STATUS +{ + // Unknown error. Should not be returned. + MH_UNKNOWN = -1, + + // Successful. + MH_OK = 0, + + // MinHook is already initialized. + MH_ERROR_ALREADY_INITIALIZED, + + // MinHook is not initialized yet, or already uninitialized. + MH_ERROR_NOT_INITIALIZED, + + // The hook for the specified target function is already created. + MH_ERROR_ALREADY_CREATED, + + // The hook for the specified target function is not created yet. + MH_ERROR_NOT_CREATED, + + // The hook for the specified target function is already enabled. + MH_ERROR_ENABLED, + + // The hook for the specified target function is not enabled yet, or already + // disabled. + MH_ERROR_DISABLED, + + // The specified pointer is invalid. It points the address of non-allocated + // and/or non-executable region. + MH_ERROR_NOT_EXECUTABLE, + + // The specified target function cannot be hooked. + MH_ERROR_UNSUPPORTED_FUNCTION, + + // Failed to allocate memory. + MH_ERROR_MEMORY_ALLOC, + + // Failed to change the memory protection. + MH_ERROR_MEMORY_PROTECT, + + // The specified module is not loaded. + MH_ERROR_MODULE_NOT_FOUND, + + // The specified function is not found. + MH_ERROR_FUNCTION_NOT_FOUND, + MH_ERROR_THREAD_CONTROL, + MH_ERROR_THREAD_BUSY +} +MH_STATUS; + +// Can be passed as a parameter to MH_EnableHook, MH_DisableHook, +// MH_QueueEnableHook or MH_QueueDisableHook. +#define MH_ALL_HOOKS NULL + +#ifdef __cplusplus +extern "C" { +#endif + + // Initialize the MinHook library. You must call this function EXACTLY ONCE + // at the beginning of your program. + MH_STATUS WINAPI MH_Initialize(VOID); + + // Uninitialize the MinHook library. You must call this function EXACTLY + // ONCE at the end of your program. + MH_STATUS WINAPI MH_Uninitialize(VOID); + + // Creates a hook for the specified target function, in disabled state. + // Parameters: + // pTarget [in] A pointer to the target function, which will be + // overridden by the detour function. + // pDetour [in] A pointer to the detour function, which will override + // the target function. + // ppOriginal [out] A pointer to the trampoline function, which will be + // used to call the original target function. + // This parameter can be NULL. + MH_STATUS WINAPI MH_CreateHook(LPVOID pTarget, LPVOID pDetour, LPVOID *ppOriginal); + + // Creates a hook for the specified API function, in disabled state. + // Parameters: + // pszModule [in] A pointer to the loaded module name which contains the + // target function. + // pszProcName [in] A pointer to the target function name, which will be + // overridden by the detour function. + // pDetour [in] A pointer to the detour function, which will override + // the target function. + // ppOriginal [out] A pointer to the trampoline function, which will be + // used to call the original target function. + // This parameter can be NULL. + MH_STATUS WINAPI MH_CreateHookApi( + LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal); + + // Creates a hook for the specified API function, in disabled state. + // Parameters: + // pszModule [in] A pointer to the loaded module name which contains the + // target function. + // pszProcName [in] A pointer to the target function name, which will be + // overridden by the detour function. + // pDetour [in] A pointer to the detour function, which will override + // the target function. + // ppOriginal [out] A pointer to the trampoline function, which will be + // used to call the original target function. + // This parameter can be NULL. + // ppTarget [out] A pointer to the target function, which will be used + // with other functions. + // This parameter can be NULL. + MH_STATUS WINAPI MH_CreateHookApiEx( + LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal, LPVOID *ppTarget); + + // Removes an already created hook. + // Parameters: + // pTarget [in] A pointer to the target function. + MH_STATUS WINAPI MH_RemoveHook(LPVOID pTarget); + + // Enables an already created hook. + // Parameters: + // pTarget [in] A pointer to the target function. + // If this parameter is MH_ALL_HOOKS, all created hooks are + // enabled in one go. + MH_STATUS WINAPI MH_EnableHook(LPVOID pTarget); + + // Disables an already created hook. + // Parameters: + // pTarget [in] A pointer to the target function. + // If this parameter is MH_ALL_HOOKS, all created hooks are + // disabled in one go. + MH_STATUS WINAPI MH_DisableHook(LPVOID pTarget); + + // Queues to enable an already created hook. + // Parameters: + // pTarget [in] A pointer to the target function. + // If this parameter is MH_ALL_HOOKS, all created hooks are + // queued to be enabled. + MH_STATUS WINAPI MH_QueueEnableHook(LPVOID pTarget); + + // Queues to disable an already created hook. + // Parameters: + // pTarget [in] A pointer to the target function. + // If this parameter is MH_ALL_HOOKS, all created hooks are + // queued to be disabled. + MH_STATUS WINAPI MH_QueueDisableHook(LPVOID pTarget); + + // Applies all queued changes in one go. + MH_STATUS WINAPI MH_ApplyQueued(VOID); + + // Translates the MH_STATUS to its name as a string. + const char * WINAPI MH_StatusToString(MH_STATUS status); + +#ifdef __cplusplus +} +#endif diff --git a/internal/uifix/native/minhook/src/buffer.c b/internal/uifix/native/minhook/src/buffer.c new file mode 100644 index 0000000..0647854 --- /dev/null +++ b/internal/uifix/native/minhook/src/buffer.c @@ -0,0 +1,313 @@ +/* + * MinHook - The Minimalistic API Hooking Library for x64/x86 + * Copyright (C) 2009-2017 Tsuda Kageyu. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER + * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include "buffer.h" + +// Size of each memory block. (= page size of VirtualAlloc) +#define MEMORY_BLOCK_SIZE 0x1000 + +// Max range for seeking a memory block. (= 1024MB) +#define MAX_MEMORY_RANGE 0x40000000 + +// Memory protection flags to check the executable address. +#define PAGE_EXECUTE_FLAGS \ + (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY) + +// Memory slot. +typedef struct _MEMORY_SLOT +{ + union + { + struct _MEMORY_SLOT *pNext; + UINT8 buffer[MEMORY_SLOT_SIZE]; + }; +} MEMORY_SLOT, *PMEMORY_SLOT; + +// Memory block info. Placed at the head of each block. +typedef struct _MEMORY_BLOCK +{ + struct _MEMORY_BLOCK *pNext; + PMEMORY_SLOT pFree; // First element of the free slot list. + UINT usedCount; +} MEMORY_BLOCK, *PMEMORY_BLOCK; + +//------------------------------------------------------------------------- +// Global Variables: +//------------------------------------------------------------------------- + +// First element of the memory block list. +PMEMORY_BLOCK g_pMemoryBlocks; + +//------------------------------------------------------------------------- +VOID InitializeBuffer(VOID) +{ + // Nothing to do for now. +} + +//------------------------------------------------------------------------- +VOID UninitializeBuffer(VOID) +{ + PMEMORY_BLOCK pBlock = g_pMemoryBlocks; + g_pMemoryBlocks = NULL; + + while (pBlock) + { + PMEMORY_BLOCK pNext = pBlock->pNext; + VirtualFree(pBlock, 0, MEM_RELEASE); + pBlock = pNext; + } +} + +//------------------------------------------------------------------------- +#if defined(_M_X64) || defined(__x86_64__) +static LPVOID FindPrevFreeRegion(LPVOID pAddress, LPVOID pMinAddr, DWORD dwAllocationGranularity) +{ + ULONG_PTR tryAddr = (ULONG_PTR)pAddress; + + // Round down to the allocation granularity. + tryAddr -= tryAddr % dwAllocationGranularity; + + // Start from the previous allocation granularity multiply. + tryAddr -= dwAllocationGranularity; + + while (tryAddr >= (ULONG_PTR)pMinAddr) + { + MEMORY_BASIC_INFORMATION mbi; + if (VirtualQuery((LPVOID)tryAddr, &mbi, sizeof(mbi)) == 0) + break; + + if (mbi.State == MEM_FREE) + return (LPVOID)tryAddr; + + if ((ULONG_PTR)mbi.AllocationBase < dwAllocationGranularity) + break; + + tryAddr = (ULONG_PTR)mbi.AllocationBase - dwAllocationGranularity; + } + + return NULL; +} +#endif + +//------------------------------------------------------------------------- +#if defined(_M_X64) || defined(__x86_64__) +static LPVOID FindNextFreeRegion(LPVOID pAddress, LPVOID pMaxAddr, DWORD dwAllocationGranularity) +{ + ULONG_PTR tryAddr = (ULONG_PTR)pAddress; + + // Round down to the allocation granularity. + tryAddr -= tryAddr % dwAllocationGranularity; + + // Start from the next allocation granularity multiply. + tryAddr += dwAllocationGranularity; + + while (tryAddr <= (ULONG_PTR)pMaxAddr) + { + MEMORY_BASIC_INFORMATION mbi; + if (VirtualQuery((LPVOID)tryAddr, &mbi, sizeof(mbi)) == 0) + break; + + if (mbi.State == MEM_FREE) + return (LPVOID)tryAddr; + + tryAddr = (ULONG_PTR)mbi.BaseAddress + mbi.RegionSize; + + // Round up to the next allocation granularity. + tryAddr += dwAllocationGranularity - 1; + tryAddr -= tryAddr % dwAllocationGranularity; + } + + return NULL; +} +#endif + +//------------------------------------------------------------------------- +static PMEMORY_BLOCK GetMemoryBlock(LPVOID pOrigin) +{ + PMEMORY_BLOCK pBlock; +#if defined(_M_X64) || defined(__x86_64__) + ULONG_PTR minAddr; + ULONG_PTR maxAddr; + + SYSTEM_INFO si; + GetSystemInfo(&si); + minAddr = (ULONG_PTR)si.lpMinimumApplicationAddress; + maxAddr = (ULONG_PTR)si.lpMaximumApplicationAddress; + + // pOrigin ± 512MB + if ((ULONG_PTR)pOrigin > MAX_MEMORY_RANGE && minAddr < (ULONG_PTR)pOrigin - MAX_MEMORY_RANGE) + minAddr = (ULONG_PTR)pOrigin - MAX_MEMORY_RANGE; + + if (maxAddr > (ULONG_PTR)pOrigin + MAX_MEMORY_RANGE) + maxAddr = (ULONG_PTR)pOrigin + MAX_MEMORY_RANGE; + + // Make room for MEMORY_BLOCK_SIZE bytes. + maxAddr -= MEMORY_BLOCK_SIZE - 1; +#endif + + // Look the registered blocks for a reachable one. + for (pBlock = g_pMemoryBlocks; pBlock != NULL; pBlock = pBlock->pNext) + { +#if defined(_M_X64) || defined(__x86_64__) + // Ignore the blocks too far. + if ((ULONG_PTR)pBlock < minAddr || (ULONG_PTR)pBlock >= maxAddr) + continue; +#endif + // The block has at least one unused slot. + if (pBlock->pFree != NULL) + return pBlock; + } + +#if defined(_M_X64) || defined(__x86_64__) + // Alloc a new block above if not found. + { + LPVOID pAlloc = pOrigin; + while ((ULONG_PTR)pAlloc >= minAddr) + { + pAlloc = FindPrevFreeRegion(pAlloc, (LPVOID)minAddr, si.dwAllocationGranularity); + if (pAlloc == NULL) + break; + + pBlock = (PMEMORY_BLOCK)VirtualAlloc( + pAlloc, MEMORY_BLOCK_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); + if (pBlock != NULL) + break; + } + } + + // Alloc a new block below if not found. + if (pBlock == NULL) + { + LPVOID pAlloc = pOrigin; + while ((ULONG_PTR)pAlloc <= maxAddr) + { + pAlloc = FindNextFreeRegion(pAlloc, (LPVOID)maxAddr, si.dwAllocationGranularity); + if (pAlloc == NULL) + break; + + pBlock = (PMEMORY_BLOCK)VirtualAlloc( + pAlloc, MEMORY_BLOCK_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); + if (pBlock != NULL) + break; + } + } +#else + // In x86 mode, a memory block can be placed anywhere. + pBlock = (PMEMORY_BLOCK)VirtualAlloc( + NULL, MEMORY_BLOCK_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); +#endif + + if (pBlock != NULL) + { + // Build a linked list of all the slots. + PMEMORY_SLOT pSlot = (PMEMORY_SLOT)pBlock + 1; + pBlock->pFree = NULL; + pBlock->usedCount = 0; + do + { + pSlot->pNext = pBlock->pFree; + pBlock->pFree = pSlot; + pSlot++; + } while ((ULONG_PTR)pSlot - (ULONG_PTR)pBlock <= MEMORY_BLOCK_SIZE - MEMORY_SLOT_SIZE); + + pBlock->pNext = g_pMemoryBlocks; + g_pMemoryBlocks = pBlock; + } + + return pBlock; +} + +//------------------------------------------------------------------------- +LPVOID AllocateBuffer(LPVOID pOrigin) +{ + PMEMORY_SLOT pSlot; + PMEMORY_BLOCK pBlock = GetMemoryBlock(pOrigin); + if (pBlock == NULL) + return NULL; + + // Remove an unused slot from the list. + pSlot = pBlock->pFree; + pBlock->pFree = pSlot->pNext; + pBlock->usedCount++; +#ifdef _DEBUG + // Fill the slot with INT3 for debugging. + memset(pSlot, 0xCC, sizeof(MEMORY_SLOT)); +#endif + return pSlot; +} + +//------------------------------------------------------------------------- +VOID FreeBuffer(LPVOID pBuffer) +{ + PMEMORY_BLOCK pBlock = g_pMemoryBlocks; + PMEMORY_BLOCK pPrev = NULL; + ULONG_PTR pTargetBlock = ((ULONG_PTR)pBuffer / MEMORY_BLOCK_SIZE) * MEMORY_BLOCK_SIZE; + + while (pBlock != NULL) + { + if ((ULONG_PTR)pBlock == pTargetBlock) + { + PMEMORY_SLOT pSlot = (PMEMORY_SLOT)pBuffer; +#ifdef _DEBUG + // Clear the released slot for debugging. + memset(pSlot, 0x00, sizeof(MEMORY_SLOT)); +#endif + // Restore the released slot to the list. + pSlot->pNext = pBlock->pFree; + pBlock->pFree = pSlot; + pBlock->usedCount--; + + // Free if unused. + if (pBlock->usedCount == 0) + { + if (pPrev) + pPrev->pNext = pBlock->pNext; + else + g_pMemoryBlocks = pBlock->pNext; + + VirtualFree(pBlock, 0, MEM_RELEASE); + } + + break; + } + + pPrev = pBlock; + pBlock = pBlock->pNext; + } +} + +//------------------------------------------------------------------------- +BOOL IsExecutableAddress(LPVOID pAddress) +{ + MEMORY_BASIC_INFORMATION mi; + if (!VirtualQuery(pAddress, &mi, sizeof(mi))) + return FALSE; + + return (mi.State == MEM_COMMIT && (mi.Protect & PAGE_EXECUTE_FLAGS)); +} diff --git a/internal/uifix/native/minhook/src/buffer.h b/internal/uifix/native/minhook/src/buffer.h new file mode 100644 index 0000000..c74dfad --- /dev/null +++ b/internal/uifix/native/minhook/src/buffer.h @@ -0,0 +1,44 @@ +/* + * MinHook - The Minimalistic API Hooking Library for x64/x86 + * Copyright (C) 2009-2017 Tsuda Kageyu. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER + * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include + +// Size of each memory slot. +#if defined(_M_X64) || defined(__x86_64__) + #define MEMORY_SLOT_SIZE 64 +#else + #define MEMORY_SLOT_SIZE 32 +#endif + +VOID InitializeBuffer(VOID); +VOID UninitializeBuffer(VOID); +LPVOID AllocateBuffer(LPVOID pOrigin); +VOID FreeBuffer(LPVOID pBuffer); +BOOL IsExecutableAddress(LPVOID pAddress); diff --git a/internal/uifix/native/minhook/src/hde/hde64.c b/internal/uifix/native/minhook/src/hde/hde64.c new file mode 100644 index 0000000..882556e --- /dev/null +++ b/internal/uifix/native/minhook/src/hde/hde64.c @@ -0,0 +1,336 @@ +/* + * Hacker Disassembler Engine 64 C + * Copyright (c) 2008-2009, Vyacheslav Patkov. + * All rights reserved. + * + */ + +#if defined(_M_X64) || defined(__x86_64__) + +#include +#include "hde64.h" +#include "table64.h" + +unsigned int hde64_disasm(const void *code, hde64s *hs) +{ + uint8_t x, c, *p = (uint8_t *)code, cflags, opcode, pref = 0; + uint8_t *ht = hde64_table, m_mod, m_reg, m_rm, disp_size = 0; + uint8_t op64 = 0; + + memset(hs, 0, sizeof(hde64s)); + + for (x = 16; x; x--) + switch (c = *p++) { + case 0xf3: + hs->p_rep = c; + pref |= PRE_F3; + break; + case 0xf2: + hs->p_rep = c; + pref |= PRE_F2; + break; + case 0xf0: + hs->p_lock = c; + pref |= PRE_LOCK; + break; + case 0x26: case 0x2e: case 0x36: + case 0x3e: case 0x64: case 0x65: + hs->p_seg = c; + pref |= PRE_SEG; + break; + case 0x66: + hs->p_66 = c; + pref |= PRE_66; + break; + case 0x67: + hs->p_67 = c; + pref |= PRE_67; + break; + default: + goto pref_done; + } + pref_done: + + hs->flags = (uint32_t)pref << 23; + + if (!pref) + pref |= PRE_NONE; + + if ((c & 0xf0) == 0x40) { + hs->flags |= F_PREFIX_REX; + if ((hs->rex_w = (c & 0xf) >> 3) && (*p & 0xf8) == 0xb8) + op64++; + hs->rex_r = (c & 7) >> 2; + hs->rex_x = (c & 3) >> 1; + hs->rex_b = c & 1; + if (((c = *p++) & 0xf0) == 0x40) { + opcode = c; + goto error_opcode; + } + } + + if ((hs->opcode = c) == 0x0f) { + hs->opcode2 = c = *p++; + ht += DELTA_OPCODES; + } + + opcode = c; + cflags = ht[ht[opcode / 4] + (opcode % 4)]; + + if (cflags == C_ERROR) { + error_opcode: + hs->flags |= F_ERROR | F_ERROR_OPCODE; + cflags = 0; + if ((opcode & -3) == 0x24) + cflags++; + } + + x = 0; + if (cflags & C_GROUP) { + uint16_t t; + t = *(uint16_t *)(ht + (cflags & 0x7f)); + cflags = (uint8_t)t; + x = (uint8_t)(t >> 8); + } + + if (hs->opcode2) { + ht = hde64_table + DELTA_PREFIXES; + if (ht[ht[opcode / 4] + (opcode % 4)] & pref) + hs->flags |= F_ERROR | F_ERROR_OPCODE; + } + + if (cflags & C_MODRM) { + hs->flags |= F_MODRM; + hs->modrm = c = *p++; + hs->modrm_mod = m_mod = c >> 6; + hs->modrm_rm = m_rm = c & 7; + hs->modrm_reg = m_reg = (c & 0x3f) >> 3; + + if (x && ((x << m_reg) & 0x80)) + hs->flags |= F_ERROR | F_ERROR_OPCODE; + + if (!hs->opcode2 && opcode >= 0xd9 && opcode <= 0xdf) { + uint8_t t = opcode - 0xd9; + if (m_mod == 3) { + ht = hde64_table + DELTA_FPU_MODRM + t*8; + t = ht[m_reg] << m_rm; + } else { + ht = hde64_table + DELTA_FPU_REG; + t = ht[t] << m_reg; + } + if (t & 0x80) + hs->flags |= F_ERROR | F_ERROR_OPCODE; + } + + if (pref & PRE_LOCK) { + if (m_mod == 3) { + hs->flags |= F_ERROR | F_ERROR_LOCK; + } else { + uint8_t *table_end, op = opcode; + if (hs->opcode2) { + ht = hde64_table + DELTA_OP2_LOCK_OK; + table_end = ht + DELTA_OP_ONLY_MEM - DELTA_OP2_LOCK_OK; + } else { + ht = hde64_table + DELTA_OP_LOCK_OK; + table_end = ht + DELTA_OP2_LOCK_OK - DELTA_OP_LOCK_OK; + op &= -2; + } + for (; ht != table_end; ht++) + if (*ht++ == op) { + if (!((*ht << m_reg) & 0x80)) + goto no_lock_error; + else + break; + } + hs->flags |= F_ERROR | F_ERROR_LOCK; + no_lock_error: + ; + } + } + + if (hs->opcode2) { + switch (opcode) { + case 0x20: case 0x22: + m_mod = 3; + if (m_reg > 4 || m_reg == 1) + goto error_operand; + else + goto no_error_operand; + case 0x21: case 0x23: + m_mod = 3; + if (m_reg == 4 || m_reg == 5) + goto error_operand; + else + goto no_error_operand; + } + } else { + switch (opcode) { + case 0x8c: + if (m_reg > 5) + goto error_operand; + else + goto no_error_operand; + case 0x8e: + if (m_reg == 1 || m_reg > 5) + goto error_operand; + else + goto no_error_operand; + } + } + + if (m_mod == 3) { + uint8_t *table_end; + if (hs->opcode2) { + ht = hde64_table + DELTA_OP2_ONLY_MEM; + table_end = ht + sizeof(hde64_table) - DELTA_OP2_ONLY_MEM; + } else { + ht = hde64_table + DELTA_OP_ONLY_MEM; + table_end = ht + DELTA_OP2_ONLY_MEM - DELTA_OP_ONLY_MEM; + } + for (; ht != table_end; ht += 2) + if (*ht++ == opcode) { + if ((*ht++ & pref) && !((*ht << m_reg) & 0x80)) + goto error_operand; + else + break; + } + goto no_error_operand; + } else if (hs->opcode2) { + switch (opcode) { + case 0x50: case 0xd7: case 0xf7: + if (pref & (PRE_NONE | PRE_66)) + goto error_operand; + break; + case 0xd6: + if (pref & (PRE_F2 | PRE_F3)) + goto error_operand; + break; + case 0xc5: + goto error_operand; + } + goto no_error_operand; + } else + goto no_error_operand; + + error_operand: + hs->flags |= F_ERROR | F_ERROR_OPERAND; + no_error_operand: + + c = *p++; + if (m_reg <= 1) { + if (opcode == 0xf6) + cflags |= C_IMM8; + else if (opcode == 0xf7) + cflags |= C_IMM_P66; + } + + switch (m_mod) { + case 0: + if (m_rm == 5) + disp_size = 4; + break; + case 1: + disp_size = 1; + break; + case 2: + disp_size = 4; + break; + } + + if (m_mod != 3 && m_rm == 4) { + hs->flags |= F_SIB; + p++; + hs->sib = c; + hs->sib_scale = c >> 6; + hs->sib_index = (c & 0x3f) >> 3; + if ((hs->sib_base = c & 7) == 5 && m_mod == 0) + disp_size = 4; + } + + p--; + switch (disp_size) { + case 1: + hs->flags |= F_DISP8; + hs->disp.disp8 = *p; + break; + case 2: + hs->flags |= F_DISP16; + hs->disp.disp16 = *(uint16_t *)p; + break; + case 4: + hs->flags |= F_DISP32; + hs->disp.disp32 = *(uint32_t *)p; + break; + } + p += disp_size; + } else if (pref & PRE_LOCK) + hs->flags |= F_ERROR | F_ERROR_LOCK; + + if (hs->opcode >= 0xa0 && hs->opcode <= 0xa3) { + if (pref & PRE_67) { + hs->flags |= F_IMM32; + hs->imm.imm32 = *(uint32_t *)p; + p += 4; + } else { + hs->flags |= F_IMM64; + hs->imm.imm64 = *(uint64_t *)p; + p += 8; + } + goto disasm_done; + } + + if (cflags & C_IMM_P66) { + if (cflags & C_REL32) { + if (pref & PRE_66) { + hs->flags |= F_IMM16 | F_RELATIVE; + hs->imm.imm16 = *(uint16_t *)p; + p += 2; + goto disasm_done; + } + goto rel32_ok; + } + if (op64) { + hs->flags |= F_IMM64; + hs->imm.imm64 = *(uint64_t *)p; + p += 8; + } else if (!(pref & PRE_66) || hs->rex_w) { + hs->flags |= F_IMM32; + hs->imm.imm32 = *(uint32_t *)p; + p += 4; + } else + goto imm16_ok; + } + + + if (cflags & C_IMM16) { + imm16_ok: + hs->flags |= F_IMM16; + hs->imm.imm16 = *(uint16_t *)p; + p += 2; + } + if (cflags & C_IMM8) { + hs->flags |= F_IMM8; + hs->imm.imm8 = *p++; + } + + if (cflags & C_REL32) { + rel32_ok: + hs->flags |= F_IMM32 | F_RELATIVE; + hs->imm.imm32 = *(uint32_t *)p; + p += 4; + } else if (cflags & C_REL8) { + hs->flags |= F_IMM8 | F_RELATIVE; + hs->imm.imm8 = *p++; + } + + disasm_done: + + if ((hs->len = (uint8_t)(p-(uint8_t *)code)) > 15) { + hs->flags |= F_ERROR | F_ERROR_LENGTH; + hs->len = 15; + } + + return (unsigned int)hs->len; +} + +#endif // defined(_M_X64) || defined(__x86_64__) diff --git a/internal/uifix/native/minhook/src/hde/hde64.h b/internal/uifix/native/minhook/src/hde/hde64.h new file mode 100644 index 0000000..ecbf4df --- /dev/null +++ b/internal/uifix/native/minhook/src/hde/hde64.h @@ -0,0 +1,112 @@ +/* + * Hacker Disassembler Engine 64 + * Copyright (c) 2008-2009, Vyacheslav Patkov. + * All rights reserved. + * + * hde64.h: C/C++ header file + * + */ + +#ifndef _HDE64_H_ +#define _HDE64_H_ + +/* stdint.h - C99 standard header + * http://en.wikipedia.org/wiki/stdint.h + * + * if your compiler doesn't contain "stdint.h" header (for + * example, Microsoft Visual C++), you can download file: + * http://www.azillionmonkeys.com/qed/pstdint.h + * and change next line to: + * #include "pstdint.h" + */ +#include "pstdint.h" + +#define F_MODRM 0x00000001 +#define F_SIB 0x00000002 +#define F_IMM8 0x00000004 +#define F_IMM16 0x00000008 +#define F_IMM32 0x00000010 +#define F_IMM64 0x00000020 +#define F_DISP8 0x00000040 +#define F_DISP16 0x00000080 +#define F_DISP32 0x00000100 +#define F_RELATIVE 0x00000200 +#define F_ERROR 0x00001000 +#define F_ERROR_OPCODE 0x00002000 +#define F_ERROR_LENGTH 0x00004000 +#define F_ERROR_LOCK 0x00008000 +#define F_ERROR_OPERAND 0x00010000 +#define F_PREFIX_REPNZ 0x01000000 +#define F_PREFIX_REPX 0x02000000 +#define F_PREFIX_REP 0x03000000 +#define F_PREFIX_66 0x04000000 +#define F_PREFIX_67 0x08000000 +#define F_PREFIX_LOCK 0x10000000 +#define F_PREFIX_SEG 0x20000000 +#define F_PREFIX_REX 0x40000000 +#define F_PREFIX_ANY 0x7f000000 + +#define PREFIX_SEGMENT_CS 0x2e +#define PREFIX_SEGMENT_SS 0x36 +#define PREFIX_SEGMENT_DS 0x3e +#define PREFIX_SEGMENT_ES 0x26 +#define PREFIX_SEGMENT_FS 0x64 +#define PREFIX_SEGMENT_GS 0x65 +#define PREFIX_LOCK 0xf0 +#define PREFIX_REPNZ 0xf2 +#define PREFIX_REPX 0xf3 +#define PREFIX_OPERAND_SIZE 0x66 +#define PREFIX_ADDRESS_SIZE 0x67 + +#pragma pack(push,1) + +typedef struct { + uint8_t len; + uint8_t p_rep; + uint8_t p_lock; + uint8_t p_seg; + uint8_t p_66; + uint8_t p_67; + uint8_t rex; + uint8_t rex_w; + uint8_t rex_r; + uint8_t rex_x; + uint8_t rex_b; + uint8_t opcode; + uint8_t opcode2; + uint8_t modrm; + uint8_t modrm_mod; + uint8_t modrm_reg; + uint8_t modrm_rm; + uint8_t sib; + uint8_t sib_scale; + uint8_t sib_index; + uint8_t sib_base; + union { + uint8_t imm8; + uint16_t imm16; + uint32_t imm32; + uint64_t imm64; + } imm; + union { + uint8_t disp8; + uint16_t disp16; + uint32_t disp32; + } disp; + uint32_t flags; +} hde64s; + +#pragma pack(pop) + +#ifdef __cplusplus +extern "C" { +#endif + +/* __cdecl */ +unsigned int hde64_disasm(const void *code, hde64s *hs); + +#ifdef __cplusplus +} +#endif + +#endif /* _HDE64_H_ */ diff --git a/internal/uifix/native/minhook/src/hde/pstdint.h b/internal/uifix/native/minhook/src/hde/pstdint.h new file mode 100644 index 0000000..84d82a0 --- /dev/null +++ b/internal/uifix/native/minhook/src/hde/pstdint.h @@ -0,0 +1,39 @@ +/* + * MinHook - The Minimalistic API Hooking Library for x64/x86 + * Copyright (C) 2009-2017 Tsuda Kageyu. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR + * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT + * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF + * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#include + +// Integer types for HDE. +typedef INT8 int8_t; +typedef INT16 int16_t; +typedef INT32 int32_t; +typedef INT64 int64_t; +typedef UINT8 uint8_t; +typedef UINT16 uint16_t; +typedef UINT32 uint32_t; +typedef UINT64 uint64_t; diff --git a/internal/uifix/native/minhook/src/hde/table64.h b/internal/uifix/native/minhook/src/hde/table64.h new file mode 100644 index 0000000..01d4541 --- /dev/null +++ b/internal/uifix/native/minhook/src/hde/table64.h @@ -0,0 +1,74 @@ +/* + * Hacker Disassembler Engine 64 C + * Copyright (c) 2008-2009, Vyacheslav Patkov. + * All rights reserved. + * + */ + +#define C_NONE 0x00 +#define C_MODRM 0x01 +#define C_IMM8 0x02 +#define C_IMM16 0x04 +#define C_IMM_P66 0x10 +#define C_REL8 0x20 +#define C_REL32 0x40 +#define C_GROUP 0x80 +#define C_ERROR 0xff + +#define PRE_ANY 0x00 +#define PRE_NONE 0x01 +#define PRE_F2 0x02 +#define PRE_F3 0x04 +#define PRE_66 0x08 +#define PRE_67 0x10 +#define PRE_LOCK 0x20 +#define PRE_SEG 0x40 +#define PRE_ALL 0xff + +#define DELTA_OPCODES 0x4a +#define DELTA_FPU_REG 0xfd +#define DELTA_FPU_MODRM 0x104 +#define DELTA_PREFIXES 0x13c +#define DELTA_OP_LOCK_OK 0x1ae +#define DELTA_OP2_LOCK_OK 0x1c6 +#define DELTA_OP_ONLY_MEM 0x1d8 +#define DELTA_OP2_ONLY_MEM 0x1e7 + +unsigned char hde64_table[] = { + 0xa5,0xaa,0xa5,0xb8,0xa5,0xaa,0xa5,0xaa,0xa5,0xb8,0xa5,0xb8,0xa5,0xb8,0xa5, + 0xb8,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xac,0xc0,0xcc,0xc0,0xa1,0xa1, + 0xa1,0xa1,0xb1,0xa5,0xa5,0xa6,0xc0,0xc0,0xd7,0xda,0xe0,0xc0,0xe4,0xc0,0xea, + 0xea,0xe0,0xe0,0x98,0xc8,0xee,0xf1,0xa5,0xd3,0xa5,0xa5,0xa1,0xea,0x9e,0xc0, + 0xc0,0xc2,0xc0,0xe6,0x03,0x7f,0x11,0x7f,0x01,0x7f,0x01,0x3f,0x01,0x01,0xab, + 0x8b,0x90,0x64,0x5b,0x5b,0x5b,0x5b,0x5b,0x92,0x5b,0x5b,0x76,0x90,0x92,0x92, + 0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x6a,0x73,0x90, + 0x5b,0x52,0x52,0x52,0x52,0x5b,0x5b,0x5b,0x5b,0x77,0x7c,0x77,0x85,0x5b,0x5b, + 0x70,0x5b,0x7a,0xaf,0x76,0x76,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b, + 0x5b,0x5b,0x86,0x01,0x03,0x01,0x04,0x03,0xd5,0x03,0xd5,0x03,0xcc,0x01,0xbc, + 0x03,0xf0,0x03,0x03,0x04,0x00,0x50,0x50,0x50,0x50,0xff,0x20,0x20,0x20,0x20, + 0x01,0x01,0x01,0x01,0xc4,0x02,0x10,0xff,0xff,0xff,0x01,0x00,0x03,0x11,0xff, + 0x03,0xc4,0xc6,0xc8,0x02,0x10,0x00,0xff,0xcc,0x01,0x01,0x01,0x00,0x00,0x00, + 0x00,0x01,0x01,0x03,0x01,0xff,0xff,0xc0,0xc2,0x10,0x11,0x02,0x03,0x01,0x01, + 0x01,0xff,0xff,0xff,0x00,0x00,0x00,0xff,0x00,0x00,0xff,0xff,0xff,0xff,0x10, + 0x10,0x10,0x10,0x02,0x10,0x00,0x00,0xc6,0xc8,0x02,0x02,0x02,0x02,0x06,0x00, + 0x04,0x00,0x02,0xff,0x00,0xc0,0xc2,0x01,0x01,0x03,0x03,0x03,0xca,0x40,0x00, + 0x0a,0x00,0x04,0x00,0x00,0x00,0x00,0x7f,0x00,0x33,0x01,0x00,0x00,0x00,0x00, + 0x00,0x00,0xff,0xbf,0xff,0xff,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0xff,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff, + 0x00,0x00,0x00,0xbf,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7f,0x00,0x00, + 0xff,0x40,0x40,0x40,0x40,0x41,0x49,0x40,0x40,0x40,0x40,0x4c,0x42,0x40,0x40, + 0x40,0x40,0x40,0x40,0x40,0x40,0x4f,0x44,0x53,0x40,0x40,0x40,0x44,0x57,0x43, + 0x5c,0x40,0x60,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40, + 0x40,0x40,0x64,0x66,0x6e,0x6b,0x40,0x40,0x6a,0x46,0x40,0x40,0x44,0x46,0x40, + 0x40,0x5b,0x44,0x40,0x40,0x00,0x00,0x00,0x00,0x06,0x06,0x06,0x06,0x01,0x06, + 0x06,0x02,0x06,0x06,0x00,0x06,0x00,0x0a,0x0a,0x00,0x00,0x00,0x02,0x07,0x07, + 0x06,0x02,0x0d,0x06,0x06,0x06,0x0e,0x05,0x05,0x02,0x02,0x00,0x00,0x04,0x04, + 0x04,0x04,0x05,0x06,0x06,0x06,0x00,0x00,0x00,0x0e,0x00,0x00,0x08,0x00,0x10, + 0x00,0x18,0x00,0x20,0x00,0x28,0x00,0x30,0x00,0x80,0x01,0x82,0x01,0x86,0x00, + 0xf6,0xcf,0xfe,0x3f,0xab,0x00,0xb0,0x00,0xb1,0x00,0xb3,0x00,0xba,0xf8,0xbb, + 0x00,0xc0,0x00,0xc1,0x00,0xc7,0xbf,0x62,0xff,0x00,0x8d,0xff,0x00,0xc4,0xff, + 0x00,0xc5,0xff,0x00,0xff,0xff,0xeb,0x01,0xff,0x0e,0x12,0x08,0x00,0x13,0x09, + 0x00,0x16,0x08,0x00,0x17,0x09,0x00,0x2b,0x09,0x00,0xae,0xff,0x07,0xb2,0xff, + 0x00,0xb4,0xff,0x00,0xb5,0xff,0x00,0xc3,0x01,0x00,0xc7,0xff,0xbf,0xe7,0x08, + 0x00,0xf0,0x02,0x00 +}; diff --git a/internal/uifix/native/minhook/src/hook.c b/internal/uifix/native/minhook/src/hook.c new file mode 100644 index 0000000..793ae40 --- /dev/null +++ b/internal/uifix/native/minhook/src/hook.c @@ -0,0 +1,879 @@ +/* + * MinHook - The Minimalistic API Hooking Library for x64/x86 + * Copyright (C) 2009-2017 Tsuda Kageyu. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER + * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include +#include +#include + +#include "../include/MinHook.h" +#include "buffer.h" +#include "trampoline.h" + +#ifndef ARRAYSIZE + #define ARRAYSIZE(A) (sizeof(A)/sizeof((A)[0])) +#endif + +// Initial capacity of the HOOK_ENTRY buffer. +#define INITIAL_HOOK_CAPACITY 32 + +// Initial capacity of the thread IDs buffer. +#define INITIAL_THREAD_CAPACITY 128 + +// Special hook position values. +#define INVALID_HOOK_POS UINT_MAX +#define ALL_HOOKS_POS UINT_MAX + + +// Thread access rights for suspending/resuming threads. +#define THREAD_ACCESS \ + (THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION | THREAD_SET_CONTEXT) + +// Hook information. +typedef struct _HOOK_ENTRY +{ + LPVOID pTarget; // Address of the target function. + LPVOID pDetour; // Address of the detour or relay function. + LPVOID pTrampoline; // Address of the trampoline function. + UINT8 backup[8]; // Original prologue of the target function. + + UINT8 patchAbove : 1; // Uses the hot patch area. + UINT8 isEnabled : 1; // Enabled. + UINT8 queueEnable : 1; // Queued for enabling/disabling when != isEnabled. + + UINT nIP : 4; // Count of the instruction boundaries. + UINT8 oldIPs[8]; // Instruction boundaries of the target function. + UINT8 newIPs[8]; // Instruction boundaries of the trampoline function. +} HOOK_ENTRY, *PHOOK_ENTRY; + +// Suspended threads for Freeze()/Unfreeze(). +typedef struct { DWORD id; HANDLE handle; } FROZEN_THREAD; + +typedef struct _FROZEN_THREADS +{ + FROZEN_THREAD *pItems; // Data heap + UINT capacity; // Size of allocated data heap, items + UINT size; // Actual number of data items +} FROZEN_THREADS, *PFROZEN_THREADS; + +//------------------------------------------------------------------------- +// Global Variables: +//------------------------------------------------------------------------- + +// Spin lock flag for EnterSpinLock()/LeaveSpinLock(). +volatile LONG g_isLocked = FALSE; + +// Private heap handle. If not NULL, this library is initialized. +HANDLE g_hHeap = NULL; + +// Hook entries. +struct +{ + PHOOK_ENTRY pItems; // Data heap + UINT capacity; // Size of allocated data heap, items + UINT size; // Actual number of data items +} g_hooks; + +//------------------------------------------------------------------------- +// Returns INVALID_HOOK_POS if not found. +static UINT FindHookEntry(LPVOID pTarget) +{ + UINT i; + for (i = 0; i < g_hooks.size; ++i) + { + if ((ULONG_PTR)pTarget == (ULONG_PTR)g_hooks.pItems[i].pTarget) + return i; + } + + return INVALID_HOOK_POS; +} + +//------------------------------------------------------------------------- +static PHOOK_ENTRY AddHookEntry() +{ + if (g_hooks.pItems == NULL) + { + g_hooks.capacity = INITIAL_HOOK_CAPACITY; + g_hooks.pItems = (PHOOK_ENTRY)HeapAlloc( + g_hHeap, 0, g_hooks.capacity * sizeof(HOOK_ENTRY)); + if (g_hooks.pItems == NULL) + return NULL; + } + else if (g_hooks.size >= g_hooks.capacity) + { + PHOOK_ENTRY p = (PHOOK_ENTRY)HeapReAlloc( + g_hHeap, 0, g_hooks.pItems, (g_hooks.capacity * 2) * sizeof(HOOK_ENTRY)); + if (p == NULL) + return NULL; + + g_hooks.capacity *= 2; + g_hooks.pItems = p; + } + + return &g_hooks.pItems[g_hooks.size++]; +} + +//------------------------------------------------------------------------- +static VOID DeleteHookEntry(UINT pos) +{ + if (pos < g_hooks.size - 1) + g_hooks.pItems[pos] = g_hooks.pItems[g_hooks.size - 1]; + + g_hooks.size--; + + if (g_hooks.capacity / 2 >= INITIAL_HOOK_CAPACITY && g_hooks.capacity / 2 >= g_hooks.size) + { + PHOOK_ENTRY p = (PHOOK_ENTRY)HeapReAlloc( + g_hHeap, 0, g_hooks.pItems, (g_hooks.capacity / 2) * sizeof(HOOK_ENTRY)); + if (p == NULL) + return; + + g_hooks.capacity /= 2; + g_hooks.pItems = p; + } +} + +//------------------------------------------------------------------------- +static DWORD_PTR FindOldIP(PHOOK_ENTRY pHook, DWORD_PTR ip) +{ + UINT i; + + if (pHook->patchAbove && ip == ((DWORD_PTR)pHook->pTarget - sizeof(JMP_REL))) + return (DWORD_PTR)pHook->pTarget; + + for (i = 0; i < pHook->nIP; ++i) + { + if (ip == ((DWORD_PTR)pHook->pTrampoline + pHook->newIPs[i])) + return (DWORD_PTR)pHook->pTarget + pHook->oldIPs[i]; + } + +#if defined(_M_X64) || defined(__x86_64__) + // Check relay function. + if (ip == (DWORD_PTR)pHook->pDetour) + return (DWORD_PTR)pHook->pTarget; +#endif + + return 0; +} + +//------------------------------------------------------------------------- +static DWORD_PTR FindNewIP(PHOOK_ENTRY pHook, DWORD_PTR ip) +{ + UINT i; + for (i = 0; i < pHook->nIP; ++i) + { + if (ip == ((DWORD_PTR)pHook->pTarget + pHook->oldIPs[i])) + return (DWORD_PTR)pHook->pTrampoline + pHook->newIPs[i]; + } + + return 0; +} + +//------------------------------------------------------------------------- +static BOOL EnumerateThreads(PFROZEN_THREADS pThreads) +{ + BOOL succeeded = FALSE; + + HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); + if (hSnapshot != INVALID_HANDLE_VALUE) + { + THREADENTRY32 te; + te.dwSize = sizeof(THREADENTRY32); + if (Thread32First(hSnapshot, &te)) + { + succeeded = TRUE; + do + { + if (te.dwSize >= (FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) + sizeof(DWORD)) + && te.th32OwnerProcessID == GetCurrentProcessId() + && te.th32ThreadID != GetCurrentThreadId()) + { + if (pThreads->pItems == NULL) + { + pThreads->capacity = INITIAL_THREAD_CAPACITY; + pThreads->pItems + = HeapAlloc(g_hHeap, HEAP_ZERO_MEMORY, pThreads->capacity * sizeof(FROZEN_THREAD)); + if (pThreads->pItems == NULL) + { + succeeded = FALSE; + break; + } + } + else if (pThreads->size >= pThreads->capacity) + { + FROZEN_THREAD *p; + pThreads->capacity *= 2; + p = HeapReAlloc( + g_hHeap, HEAP_ZERO_MEMORY, pThreads->pItems, pThreads->capacity * sizeof(FROZEN_THREAD)); + if (p == NULL) + { + succeeded = FALSE; + break; + } + + pThreads->pItems = p; + } + pThreads->pItems[pThreads->size++].id = te.th32ThreadID; + } + + te.dwSize = sizeof(THREADENTRY32); + } while (Thread32Next(hSnapshot, &te)); + + if (succeeded && GetLastError() != ERROR_NO_MORE_FILES) + succeeded = FALSE; + + if (!succeeded && pThreads->pItems != NULL) + { + HeapFree(g_hHeap, 0, pThreads->pItems); + pThreads->pItems = NULL; + } + } + CloseHandle(hSnapshot); + } + + return succeeded; +} + +//------------------------------------------------------------------------- +static VOID Unfreeze(PFROZEN_THREADS threads) +{ + for (UINT i = 0; i < threads->size; ++i) + { + HANDLE thread = threads->pItems[i].handle; + if (thread != NULL) + { + ResumeThread(thread); + CloseHandle(thread); + } + } + if (threads->pItems != NULL) + HeapFree(g_hHeap, 0, threads->pItems); +} + +static MH_STATUS Freeze(PFROZEN_THREADS threads) +{ + ZeroMemory(threads, sizeof(*threads)); + if (!EnumerateThreads(threads)) + return MH_ERROR_THREAD_CONTROL; + + for (UINT i = 0; i < threads->size; ++i) + { + HANDLE thread = OpenThread(THREAD_ACCESS, FALSE, threads->pItems[i].id); + if (thread == NULL) + { + if (GetLastError() == ERROR_INVALID_PARAMETER) + continue; // Exited after the snapshot. + Unfreeze(threads); + return MH_ERROR_THREAD_CONTROL; + } + if (SuspendThread(thread) == (DWORD)-1) + { + CloseHandle(thread); + Unfreeze(threads); + return MH_ERROR_THREAD_CONTROL; + } + threads->pItems[i].handle = thread; + } + return MH_OK; +} +static MH_STATUS EnableHookLL(UINT pos, BOOL enable, const FROZEN_THREADS *threads) +{ + PHOOK_ENTRY pHook = &g_hooks.pItems[pos]; + DWORD oldProtect; + SIZE_T patchSize = sizeof(JMP_REL); + LPBYTE pPatchTarget = (LPBYTE)pHook->pTarget; + + if (pHook->patchAbove) + { + pPatchTarget -= sizeof(JMP_REL); + patchSize += sizeof(JMP_REL_SHORT); + } + + // Inspect every suspended thread before changing either code or registers. + // A single context write can commit atomically with the byte patch. Multiple + // writes could fail halfway through, so let the caller retry after resuming. + HANDLE moving = NULL; + CONTEXT next; + for (UINT i = 0; i < threads->size; ++i) + { + HANDLE thread = threads->pItems[i].handle; + if (thread == NULL) + continue; + CONTEXT context; + context.ContextFlags = CONTEXT_CONTROL; + if (!GetThreadContext(thread, &context)) + return MH_ERROR_THREAD_CONTROL; + DWORD64 ip = enable ? FindNewIP(pHook, context.Rip) : FindOldIP(pHook, context.Rip); + if (ip != 0) + { + if (moving != NULL) + return MH_ERROR_THREAD_BUSY; + moving = thread; + next = context; + next.Rip = ip; + } + } + if (!VirtualProtect(pPatchTarget, patchSize, PAGE_EXECUTE_READWRITE, &oldProtect)) + return MH_ERROR_MEMORY_PROTECT; + if (moving != NULL && !SetThreadContext(moving, &next)) + { + VirtualProtect(pPatchTarget, patchSize, oldProtect, &oldProtect); + return MH_ERROR_THREAD_CONTROL; + } + if (enable) + { + PJMP_REL pJmp = (PJMP_REL)pPatchTarget; + pJmp->opcode = 0xE9; + pJmp->operand = (UINT32)((LPBYTE)pHook->pDetour - (pPatchTarget + sizeof(JMP_REL))); + + if (pHook->patchAbove) + { + PJMP_REL_SHORT pShortJmp = (PJMP_REL_SHORT)pHook->pTarget; + pShortJmp->opcode = 0xEB; + pShortJmp->operand = (UINT8)(0 - (sizeof(JMP_REL_SHORT) + sizeof(JMP_REL))); + } + } + else + { + if (pHook->patchAbove) + memcpy(pPatchTarget, pHook->backup, sizeof(JMP_REL) + sizeof(JMP_REL_SHORT)); + else + memcpy(pPatchTarget, pHook->backup, sizeof(JMP_REL)); + } + + VirtualProtect(pPatchTarget, patchSize, oldProtect, &oldProtect); + + // Just-in-case measure. + FlushInstructionCache(GetCurrentProcess(), pPatchTarget, patchSize); + + pHook->isEnabled = enable; + pHook->queueEnable = enable; + + return MH_OK; +} + +//------------------------------------------------------------------------- +static MH_STATUS EnableAllHooksLL(BOOL enable) +{ + MH_STATUS status = MH_OK; + UINT i, first = INVALID_HOOK_POS; + + for (i = 0; i < g_hooks.size; ++i) + { + if (g_hooks.pItems[i].isEnabled != enable) + { + first = i; + break; + } + } + + if (first != INVALID_HOOK_POS) + { + FROZEN_THREADS threads; + status = Freeze(&threads); + if (status == MH_OK) + { + for (i = first; i < g_hooks.size; ++i) + { + if (g_hooks.pItems[i].isEnabled != enable) + { + status = EnableHookLL(i, enable, &threads); + if (status != MH_OK) + break; + } + } + + Unfreeze(&threads); + } + } + + return status; +} + +//------------------------------------------------------------------------- +static VOID EnterSpinLock(VOID) +{ + SIZE_T spinCount = 0; + + // Wait until the flag is FALSE. + while (InterlockedCompareExchange(&g_isLocked, TRUE, FALSE) != FALSE) + { + // No need to generate a memory barrier here, since InterlockedCompareExchange() + // generates a full memory barrier itself. + + // Prevent the loop from being too busy. + if (spinCount < 32) + Sleep(0); + else + Sleep(1); + + spinCount++; + } +} + +//------------------------------------------------------------------------- +static VOID LeaveSpinLock(VOID) +{ + // No need to generate a memory barrier here, since InterlockedExchange() + // generates a full memory barrier itself. + + InterlockedExchange(&g_isLocked, FALSE); +} + +//------------------------------------------------------------------------- +MH_STATUS WINAPI MH_Initialize(VOID) +{ + MH_STATUS status = MH_OK; + + EnterSpinLock(); + + if (g_hHeap == NULL) + { + g_hHeap = HeapCreate(0, 0, 0); + if (g_hHeap != NULL) + { + // Initialize the internal function buffer. + InitializeBuffer(); + } + else + { + status = MH_ERROR_MEMORY_ALLOC; + } + } + else + { + status = MH_ERROR_ALREADY_INITIALIZED; + } + + LeaveSpinLock(); + + return status; +} + +//------------------------------------------------------------------------- +MH_STATUS WINAPI MH_Uninitialize(VOID) +{ + MH_STATUS status = MH_OK; + + EnterSpinLock(); + + if (g_hHeap != NULL) + { + status = EnableAllHooksLL(FALSE); + if (status == MH_OK) + { + // Free the internal function buffer. + + // HeapFree is actually not required, but some tools detect a false + // memory leak without HeapFree. + + UninitializeBuffer(); + + HeapFree(g_hHeap, 0, g_hooks.pItems); + HeapDestroy(g_hHeap); + + g_hHeap = NULL; + + g_hooks.pItems = NULL; + g_hooks.capacity = 0; + g_hooks.size = 0; + } + } + else + { + status = MH_ERROR_NOT_INITIALIZED; + } + + LeaveSpinLock(); + + return status; +} + +//------------------------------------------------------------------------- +MH_STATUS WINAPI MH_CreateHook(LPVOID pTarget, LPVOID pDetour, LPVOID *ppOriginal) +{ + MH_STATUS status = MH_OK; + + EnterSpinLock(); + + if (g_hHeap != NULL) + { + if (IsExecutableAddress(pTarget) && IsExecutableAddress(pDetour)) + { + UINT pos = FindHookEntry(pTarget); + if (pos == INVALID_HOOK_POS) + { + LPVOID pBuffer = AllocateBuffer(pTarget); + if (pBuffer != NULL) + { + TRAMPOLINE ct; + + ct.pTarget = pTarget; + ct.pDetour = pDetour; + ct.pTrampoline = pBuffer; + if (CreateTrampolineFunction(&ct)) + { + PHOOK_ENTRY pHook = AddHookEntry(); + if (pHook != NULL) + { + pHook->pTarget = ct.pTarget; +#if defined(_M_X64) || defined(__x86_64__) + pHook->pDetour = ct.pRelay; +#else + pHook->pDetour = ct.pDetour; +#endif + pHook->pTrampoline = ct.pTrampoline; + pHook->patchAbove = ct.patchAbove; + pHook->isEnabled = FALSE; + pHook->queueEnable = FALSE; + pHook->nIP = ct.nIP; + memcpy(pHook->oldIPs, ct.oldIPs, ARRAYSIZE(ct.oldIPs)); + memcpy(pHook->newIPs, ct.newIPs, ARRAYSIZE(ct.newIPs)); + + // Back up the target function. + + if (ct.patchAbove) + { + memcpy( + pHook->backup, + (LPBYTE)pTarget - sizeof(JMP_REL), + sizeof(JMP_REL) + sizeof(JMP_REL_SHORT)); + } + else + { + memcpy(pHook->backup, pTarget, sizeof(JMP_REL)); + } + + if (ppOriginal != NULL) + *ppOriginal = pHook->pTrampoline; + } + else + { + status = MH_ERROR_MEMORY_ALLOC; + } + } + else + { + status = MH_ERROR_UNSUPPORTED_FUNCTION; + } + + if (status != MH_OK) + { + FreeBuffer(pBuffer); + } + } + else + { + status = MH_ERROR_MEMORY_ALLOC; + } + } + else + { + status = MH_ERROR_ALREADY_CREATED; + } + } + else + { + status = MH_ERROR_NOT_EXECUTABLE; + } + } + else + { + status = MH_ERROR_NOT_INITIALIZED; + } + + LeaveSpinLock(); + + return status; +} + +//------------------------------------------------------------------------- +MH_STATUS WINAPI MH_RemoveHook(LPVOID pTarget) +{ + MH_STATUS status = MH_OK; + + EnterSpinLock(); + + if (g_hHeap != NULL) + { + UINT pos = FindHookEntry(pTarget); + if (pos != INVALID_HOOK_POS) + { + if (g_hooks.pItems[pos].isEnabled) + { + FROZEN_THREADS threads; + status = Freeze(&threads); + if (status == MH_OK) + { + status = EnableHookLL(pos, FALSE, &threads); + + Unfreeze(&threads); + } + } + + if (status == MH_OK) + { + FreeBuffer(g_hooks.pItems[pos].pTrampoline); + DeleteHookEntry(pos); + } + } + else + { + status = MH_ERROR_NOT_CREATED; + } + } + else + { + status = MH_ERROR_NOT_INITIALIZED; + } + + LeaveSpinLock(); + + return status; +} + +//------------------------------------------------------------------------- +static MH_STATUS EnableHook(LPVOID pTarget, BOOL enable) +{ + MH_STATUS status = MH_OK; + + EnterSpinLock(); + + if (g_hHeap != NULL) + { + if (pTarget == MH_ALL_HOOKS) + { + status = EnableAllHooksLL(enable); + } + else + { + UINT pos = FindHookEntry(pTarget); + if (pos != INVALID_HOOK_POS) + { + if (g_hooks.pItems[pos].isEnabled != enable) + { + FROZEN_THREADS threads; + status = Freeze(&threads); + if (status == MH_OK) + { + status = EnableHookLL(pos, enable, &threads); + + Unfreeze(&threads); + } + } + else + { + status = enable ? MH_ERROR_ENABLED : MH_ERROR_DISABLED; + } + } + else + { + status = MH_ERROR_NOT_CREATED; + } + } + } + else + { + status = MH_ERROR_NOT_INITIALIZED; + } + + LeaveSpinLock(); + + return status; +} + +//------------------------------------------------------------------------- +MH_STATUS WINAPI MH_EnableHook(LPVOID pTarget) +{ + return EnableHook(pTarget, TRUE); +} + +//------------------------------------------------------------------------- +MH_STATUS WINAPI MH_DisableHook(LPVOID pTarget) +{ + return EnableHook(pTarget, FALSE); +} + +//------------------------------------------------------------------------- +static MH_STATUS QueueHook(LPVOID pTarget, BOOL queueEnable) +{ + MH_STATUS status = MH_OK; + + EnterSpinLock(); + + if (g_hHeap != NULL) + { + if (pTarget == MH_ALL_HOOKS) + { + UINT i; + for (i = 0; i < g_hooks.size; ++i) + g_hooks.pItems[i].queueEnable = queueEnable; + } + else + { + UINT pos = FindHookEntry(pTarget); + if (pos != INVALID_HOOK_POS) + { + g_hooks.pItems[pos].queueEnable = queueEnable; + } + else + { + status = MH_ERROR_NOT_CREATED; + } + } + } + else + { + status = MH_ERROR_NOT_INITIALIZED; + } + + LeaveSpinLock(); + + return status; +} + +//------------------------------------------------------------------------- +MH_STATUS WINAPI MH_QueueEnableHook(LPVOID pTarget) +{ + return QueueHook(pTarget, TRUE); +} + +//------------------------------------------------------------------------- +MH_STATUS WINAPI MH_QueueDisableHook(LPVOID pTarget) +{ + return QueueHook(pTarget, FALSE); +} + +//------------------------------------------------------------------------- +MH_STATUS WINAPI MH_ApplyQueued(VOID) +{ + MH_STATUS status = MH_OK; + UINT i, first = INVALID_HOOK_POS; + + EnterSpinLock(); + + if (g_hHeap != NULL) + { + for (i = 0; i < g_hooks.size; ++i) + { + if (g_hooks.pItems[i].isEnabled != g_hooks.pItems[i].queueEnable) + { + first = i; + break; + } + } + + if (first != INVALID_HOOK_POS) + { + FROZEN_THREADS threads; + status = Freeze(&threads); + if (status == MH_OK) + { + for (i = first; i < g_hooks.size; ++i) + { + PHOOK_ENTRY pHook = &g_hooks.pItems[i]; + if (pHook->isEnabled != pHook->queueEnable) + { + status = EnableHookLL(i, pHook->queueEnable, &threads); + if (status != MH_OK) + break; + } + } + + Unfreeze(&threads); + } + } + } + else + { + status = MH_ERROR_NOT_INITIALIZED; + } + + LeaveSpinLock(); + + return status; +} + +//------------------------------------------------------------------------- +MH_STATUS WINAPI MH_CreateHookApiEx( + LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, + LPVOID *ppOriginal, LPVOID *ppTarget) +{ + HMODULE hModule; + LPVOID pTarget; + + hModule = GetModuleHandleW(pszModule); + if (hModule == NULL) + return MH_ERROR_MODULE_NOT_FOUND; + + pTarget = (LPVOID)GetProcAddress(hModule, pszProcName); + if (pTarget == NULL) + return MH_ERROR_FUNCTION_NOT_FOUND; + + if (ppTarget != NULL) + *ppTarget = pTarget; + + return MH_CreateHook(pTarget, pDetour, ppOriginal); +} + +//------------------------------------------------------------------------- +MH_STATUS WINAPI MH_CreateHookApi( + LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal) +{ + return MH_CreateHookApiEx(pszModule, pszProcName, pDetour, ppOriginal, NULL); +} + +//------------------------------------------------------------------------- +const char *WINAPI MH_StatusToString(MH_STATUS status) +{ +#define MH_ST2STR(x) \ + case x: \ + return #x; + + switch (status) { + MH_ST2STR(MH_UNKNOWN) + MH_ST2STR(MH_OK) + MH_ST2STR(MH_ERROR_ALREADY_INITIALIZED) + MH_ST2STR(MH_ERROR_NOT_INITIALIZED) + MH_ST2STR(MH_ERROR_ALREADY_CREATED) + MH_ST2STR(MH_ERROR_NOT_CREATED) + MH_ST2STR(MH_ERROR_ENABLED) + MH_ST2STR(MH_ERROR_DISABLED) + MH_ST2STR(MH_ERROR_NOT_EXECUTABLE) + MH_ST2STR(MH_ERROR_UNSUPPORTED_FUNCTION) + MH_ST2STR(MH_ERROR_MEMORY_ALLOC) + MH_ST2STR(MH_ERROR_MEMORY_PROTECT) + MH_ST2STR(MH_ERROR_MODULE_NOT_FOUND) + MH_ST2STR(MH_ERROR_FUNCTION_NOT_FOUND) + MH_ST2STR(MH_ERROR_THREAD_CONTROL) + MH_ST2STR(MH_ERROR_THREAD_BUSY) + } + +#undef MH_ST2STR + + return "(unknown)"; +} diff --git a/internal/uifix/native/minhook/src/trampoline.c b/internal/uifix/native/minhook/src/trampoline.c new file mode 100644 index 0000000..d4d6f99 --- /dev/null +++ b/internal/uifix/native/minhook/src/trampoline.c @@ -0,0 +1,320 @@ +/* + * MinHook - The Minimalistic API Hooking Library for x64/x86 + * Copyright (C) 2009-2017 Tsuda Kageyu. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER + * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#include + +#if defined(_MSC_VER) && !defined(MINHOOK_DISABLE_INTRINSICS) + #define ALLOW_INTRINSICS + #include +#endif + +#ifndef ARRAYSIZE + #define ARRAYSIZE(A) (sizeof(A)/sizeof((A)[0])) +#endif + +#if defined(_M_X64) || defined(__x86_64__) + #include "./hde/hde64.h" + typedef hde64s HDE; + #define HDE_DISASM(code, hs) hde64_disasm(code, hs) +#else + #include "./hde/hde32.h" + typedef hde32s HDE; + #define HDE_DISASM(code, hs) hde32_disasm(code, hs) +#endif + +#include "trampoline.h" +#include "buffer.h" + +// Maximum size of a trampoline function. +#if defined(_M_X64) || defined(__x86_64__) + #define TRAMPOLINE_MAX_SIZE (MEMORY_SLOT_SIZE - sizeof(JMP_ABS)) +#else + #define TRAMPOLINE_MAX_SIZE MEMORY_SLOT_SIZE +#endif + +//------------------------------------------------------------------------- +static BOOL IsCodePadding(LPBYTE pInst, UINT size) +{ + UINT i; + + if (pInst[0] != 0x00 && pInst[0] != 0x90 && pInst[0] != 0xCC) + return FALSE; + + for (i = 1; i < size; ++i) + { + if (pInst[i] != pInst[0]) + return FALSE; + } + return TRUE; +} + +//------------------------------------------------------------------------- +BOOL CreateTrampolineFunction(PTRAMPOLINE ct) +{ +#if defined(_M_X64) || defined(__x86_64__) + CALL_ABS call = { + 0xFF, 0x15, 0x00000002, // FF15 00000002: CALL [RIP+8] + 0xEB, 0x08, // EB 08: JMP +10 + 0x0000000000000000ULL // Absolute destination address + }; + JMP_ABS jmp = { + 0xFF, 0x25, 0x00000000, // FF25 00000000: JMP [RIP+6] + 0x0000000000000000ULL // Absolute destination address + }; + JCC_ABS jcc = { + 0x70, 0x0E, // 7* 0E: J** +16 + 0xFF, 0x25, 0x00000000, // FF25 00000000: JMP [RIP+6] + 0x0000000000000000ULL // Absolute destination address + }; +#else + CALL_REL call = { + 0xE8, // E8 xxxxxxxx: CALL +5+xxxxxxxx + 0x00000000 // Relative destination address + }; + JMP_REL jmp = { + 0xE9, // E9 xxxxxxxx: JMP +5+xxxxxxxx + 0x00000000 // Relative destination address + }; + JCC_REL jcc = { + 0x0F, 0x80, // 0F8* xxxxxxxx: J** +6+xxxxxxxx + 0x00000000 // Relative destination address + }; +#endif + + UINT8 oldPos = 0; + UINT8 newPos = 0; + ULONG_PTR jmpDest = 0; // Destination address of an internal jump. + BOOL finished = FALSE; // Is the function completed? +#if defined(_M_X64) || defined(__x86_64__) + UINT8 instBuf[16]; +#endif + + ct->patchAbove = FALSE; + ct->nIP = 0; + + do + { + HDE hs; + UINT copySize; + LPVOID pCopySrc; + ULONG_PTR pOldInst = (ULONG_PTR)ct->pTarget + oldPos; + ULONG_PTR pNewInst = (ULONG_PTR)ct->pTrampoline + newPos; + + copySize = HDE_DISASM((LPVOID)pOldInst, &hs); + if (hs.flags & F_ERROR) + return FALSE; + + pCopySrc = (LPVOID)pOldInst; + if (oldPos >= sizeof(JMP_REL)) + { + // The trampoline function is long enough. + // Complete the function with the jump to the target function. +#if defined(_M_X64) || defined(__x86_64__) + jmp.address = pOldInst; +#else + jmp.operand = (UINT32)(pOldInst - (pNewInst + sizeof(jmp))); +#endif + pCopySrc = &jmp; + copySize = sizeof(jmp); + + finished = TRUE; + } +#if defined(_M_X64) || defined(__x86_64__) + else if ((hs.modrm & 0xC7) == 0x05) + { + // Instructions using RIP relative addressing. (ModR/M = 00???101B) + + // Modify the RIP relative address. + PUINT32 pRelAddr; + + // Avoid using memcpy to reduce the footprint. +#ifndef ALLOW_INTRINSICS + memcpy(instBuf, (LPBYTE)pOldInst, copySize); +#else + __movsb(instBuf, (LPBYTE)pOldInst, copySize); +#endif + pCopySrc = instBuf; + + // Relative address is stored at (instruction length - immediate value length - 4). + pRelAddr = (PUINT32)(instBuf + hs.len - ((hs.flags & 0x3C) >> 2) - 4); + *pRelAddr + = (UINT32)((pOldInst + hs.len + (INT32)hs.disp.disp32) - (pNewInst + hs.len)); + + // Complete the function if JMP (FF /4). + if (hs.opcode == 0xFF && hs.modrm_reg == 4) + finished = TRUE; + } +#endif + else if (hs.opcode == 0xE8) + { + // Direct relative CALL + ULONG_PTR dest = pOldInst + hs.len + (INT32)hs.imm.imm32; +#if defined(_M_X64) || defined(__x86_64__) + call.address = dest; +#else + call.operand = (UINT32)(dest - (pNewInst + sizeof(call))); +#endif + pCopySrc = &call; + copySize = sizeof(call); + } + else if ((hs.opcode & 0xFD) == 0xE9) + { + // Direct relative JMP (EB or E9) + ULONG_PTR dest = pOldInst + hs.len; + + if (hs.opcode == 0xEB) // isShort jmp + dest += (INT8)hs.imm.imm8; + else + dest += (INT32)hs.imm.imm32; + + // Simply copy an internal jump. + if ((ULONG_PTR)ct->pTarget <= dest + && dest < ((ULONG_PTR)ct->pTarget + sizeof(JMP_REL))) + { + if (jmpDest < dest) + jmpDest = dest; + } + else + { +#if defined(_M_X64) || defined(__x86_64__) + jmp.address = dest; +#else + jmp.operand = (UINT32)(dest - (pNewInst + sizeof(jmp))); +#endif + pCopySrc = &jmp; + copySize = sizeof(jmp); + + // Exit the function if it is not in the branch. + finished = (pOldInst >= jmpDest); + } + } + else if ((hs.opcode & 0xF0) == 0x70 + || (hs.opcode & 0xFC) == 0xE0 + || (hs.opcode2 & 0xF0) == 0x80) + { + // Direct relative Jcc + ULONG_PTR dest = pOldInst + hs.len; + + if ((hs.opcode & 0xF0) == 0x70 // Jcc + || (hs.opcode & 0xFC) == 0xE0) // LOOPNZ/LOOPZ/LOOP/JECXZ + dest += (INT8)hs.imm.imm8; + else + dest += (INT32)hs.imm.imm32; + + // Simply copy an internal jump. + if ((ULONG_PTR)ct->pTarget <= dest + && dest < ((ULONG_PTR)ct->pTarget + sizeof(JMP_REL))) + { + if (jmpDest < dest) + jmpDest = dest; + } + else if ((hs.opcode & 0xFC) == 0xE0) + { + // LOOPNZ/LOOPZ/LOOP/JCXZ/JECXZ to the outside are not supported. + return FALSE; + } + else + { + UINT8 cond = ((hs.opcode != 0x0F ? hs.opcode : hs.opcode2) & 0x0F); +#if defined(_M_X64) || defined(__x86_64__) + // Invert the condition in x64 mode to simplify the conditional jump logic. + jcc.opcode = 0x71 ^ cond; + jcc.address = dest; +#else + jcc.opcode1 = 0x80 | cond; + jcc.operand = (UINT32)(dest - (pNewInst + sizeof(jcc))); +#endif + pCopySrc = &jcc; + copySize = sizeof(jcc); + } + } + else if ((hs.opcode & 0xFE) == 0xC2) + { + // RET (C2 or C3) + + // Complete the function if not in a branch. + finished = (pOldInst >= jmpDest); + } + + // Can't alter the instruction length in a branch. + if (pOldInst < jmpDest && copySize != hs.len) + return FALSE; + + // Trampoline function is too large. + if ((newPos + copySize) > TRAMPOLINE_MAX_SIZE) + return FALSE; + + // Trampoline function has too many instructions. + if (ct->nIP >= ARRAYSIZE(ct->oldIPs)) + return FALSE; + + ct->oldIPs[ct->nIP] = oldPos; + ct->newIPs[ct->nIP] = newPos; + ct->nIP++; + + // Avoid using memcpy to reduce the footprint. +#ifndef ALLOW_INTRINSICS + memcpy((LPBYTE)ct->pTrampoline + newPos, pCopySrc, copySize); +#else + __movsb((LPBYTE)ct->pTrampoline + newPos, (LPBYTE)pCopySrc, copySize); +#endif + newPos += copySize; + oldPos += hs.len; + } while (!finished); + + // Is there enough place for a long jump? + if (oldPos < sizeof(JMP_REL) + && !IsCodePadding((LPBYTE)ct->pTarget + oldPos, sizeof(JMP_REL) - oldPos)) + { + // Is there enough place for a short jump? + if (oldPos < sizeof(JMP_REL_SHORT) + && !IsCodePadding((LPBYTE)ct->pTarget + oldPos, sizeof(JMP_REL_SHORT) - oldPos)) + { + return FALSE; + } + + // Can we place the long jump above the function? + if (!IsExecutableAddress((LPBYTE)ct->pTarget - sizeof(JMP_REL))) + return FALSE; + + if (!IsCodePadding((LPBYTE)ct->pTarget - sizeof(JMP_REL), sizeof(JMP_REL))) + return FALSE; + + ct->patchAbove = TRUE; + } + +#if defined(_M_X64) || defined(__x86_64__) + // Create a relay function. + jmp.address = (ULONG_PTR)ct->pDetour; + + ct->pRelay = (LPBYTE)ct->pTrampoline + newPos; + memcpy(ct->pRelay, &jmp, sizeof(jmp)); +#endif + + return TRUE; +} diff --git a/internal/uifix/native/minhook/src/trampoline.h b/internal/uifix/native/minhook/src/trampoline.h new file mode 100644 index 0000000..bdffdac --- /dev/null +++ b/internal/uifix/native/minhook/src/trampoline.h @@ -0,0 +1,105 @@ +/* + * MinHook - The Minimalistic API Hooking Library for x64/x86 + * Copyright (C) 2009-2017 Tsuda Kageyu. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED + * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A + * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER + * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +#pragma once + +#pragma pack(push, 1) + +// Structs for writing x86/x64 instructions. + +// 8-bit relative jump. +typedef struct _JMP_REL_SHORT +{ + UINT8 opcode; // EB xx: JMP +2+xx + UINT8 operand; +} JMP_REL_SHORT, *PJMP_REL_SHORT; + +// 32-bit direct relative jump/call. +typedef struct _JMP_REL +{ + UINT8 opcode; // E9/E8 xxxxxxxx: JMP/CALL +5+xxxxxxxx + UINT32 operand; // Relative destination address +} JMP_REL, *PJMP_REL, CALL_REL; + +// 64-bit indirect absolute jump. +typedef struct _JMP_ABS +{ + UINT8 opcode0; // FF25 00000000: JMP [+6] + UINT8 opcode1; + UINT32 dummy; + UINT64 address; // Absolute destination address +} JMP_ABS, *PJMP_ABS; + +// 64-bit indirect absolute call. +typedef struct _CALL_ABS +{ + UINT8 opcode0; // FF15 00000002: CALL [+6] + UINT8 opcode1; + UINT32 dummy0; + UINT8 dummy1; // EB 08: JMP +10 + UINT8 dummy2; + UINT64 address; // Absolute destination address +} CALL_ABS; + +// 32-bit direct relative conditional jumps. +typedef struct _JCC_REL +{ + UINT8 opcode0; // 0F8* xxxxxxxx: J** +6+xxxxxxxx + UINT8 opcode1; + UINT32 operand; // Relative destination address +} JCC_REL; + +// 64bit indirect absolute conditional jumps that x64 lacks. +typedef struct _JCC_ABS +{ + UINT8 opcode; // 7* 0E: J** +16 + UINT8 dummy0; + UINT8 dummy1; // FF25 00000000: JMP [+6] + UINT8 dummy2; + UINT32 dummy3; + UINT64 address; // Absolute destination address +} JCC_ABS; + +#pragma pack(pop) + +typedef struct _TRAMPOLINE +{ + LPVOID pTarget; // [In] Address of the target function. + LPVOID pDetour; // [In] Address of the detour function. + LPVOID pTrampoline; // [In] Buffer address for the trampoline and relay function. + +#if defined(_M_X64) || defined(__x86_64__) + LPVOID pRelay; // [Out] Address of the relay function. +#endif + BOOL patchAbove; // [Out] Should use the hot patch area? + UINT nIP; // [Out] Number of the instruction boundaries. + UINT8 oldIPs[8]; // [Out] Instruction boundaries of the target function. + UINT8 newIPs[8]; // [Out] Instruction boundaries of the trampoline function. +} TRAMPOLINE, *PTRAMPOLINE; + +BOOL CreateTrampolineFunction(PTRAMPOLINE ct); diff --git a/internal/uifix/native/src/cache_protocol.h b/internal/uifix/native/src/cache_protocol.h new file mode 100644 index 0000000..d7b048b --- /dev/null +++ b/internal/uifix/native/src/cache_protocol.h @@ -0,0 +1,22 @@ +#pragma once +#include +#include + +constexpr uint64_t CacheProtocol = 3; +constexpr size_t CacheStatusBytes = 256; +constexpr size_t CacheLogCapacity = 64; +struct CacheLogEntry { + volatile LONG64 sequence; + uint64_t filetime; + uint32_t reason, caller; + wchar_t name[240]; + uint64_t reserved; +}; +static_assert(sizeof(CacheLogEntry) == 512); +struct CacheDiagnostics { + volatile LONG64 count; + uint64_t session; + CacheLogEntry entries[CacheLogCapacity]; +}; +constexpr size_t CacheMappingBytes = CacheStatusBytes + sizeof(CacheDiagnostics); +extern "C" void SetCacheDiagnostics(CacheDiagnostics* diagnostics); diff --git a/internal/uifix/native/src/interface_cache.cpp b/internal/uifix/native/src/interface_cache.cpp new file mode 100644 index 0000000..0f87f27 --- /dev/null +++ b/internal/uifix/native/src/interface_cache.cpp @@ -0,0 +1,474 @@ +#define WIN32_LEAN_AND_MEAN +#include +#include +#include +#include +#include +#include +#include +#include +#include "cache_protocol.h" +#include "../minhook/src/hde/hde64.h" +#include "../minhook/include/MinHook.h" + +// MSVC x64 Qt object layout. Unknown builds must pass an isolated ABI probe. +// Call-site RVAs are supplied through the shared protocol, never guessed from a version label. +// All Qt objects are constructed/copied/destroyed by Qt's own exported functions. +struct Interface { void* d; }; +struct String { void* d; const wchar_t* data; intptr_t size; }; +struct List { volatile LONG* d; Interface* data; intptr_t size; }; +static_assert(sizeof(Interface) == 8 && sizeof(String) == 24 && sizeof(List) == 24); +using DefaultFn = void* (*)(Interface*); +using CopyFn = void* (*)(Interface*, const Interface*); +using DestroyFn = void (*)(Interface*); +using NameFn = void* (*)(const Interface*, String*); +using IndexFn = int (*)(const Interface*); +using ListFn = void* (*)(List*); +using StringDestroyFn = void (*)(String*); +using ArrayFreeFn = void (*)(void*, intptr_t, intptr_t); +static DefaultFn makeDefault; +static CopyFn copyInterface; +static DestroyFn destroyInterface; +static NameFn getName; +static IndexFn getIndex; +static ListFn getAll; +static StringDestroyFn destroyString; +static ArrayFreeFn freeArray; +static SRWLOCK cacheLock = SRWLOCK_INIT; +static HANDLE stopEvent, worker; +static std::atomic initialized{false}; +// lookups, hits, misses, refreshes, errors, lastRefreshMs, interfaceCount, workerTid +static std::atomic counters[8]; + +struct OwnedInterface { + Interface value{}; + explicit OwnedInterface(const Interface& source) { copyInterface(&value, &source); } + ~OwnedInterface() { destroyInterface(&value); } +}; +using Snapshot = std::unordered_map>; +// Process termination may unload Qt before CRT global destructors. StopCache +// releases entries on a controlled stop; process exit lets Windows reclaim them. +static Snapshot& cache = *new Snapshot; +using LookupFn = void* (*)(Interface*, const String*); +static std::atomic originalLookup{nullptr}; +static std::atomic lastSuccess{0}; + +static uint64_t snapshotAge() { + const auto refreshed = lastSuccess.load(); + return refreshed ? GetTickCount64() - refreshed : UINT64_MAX; +} +static uintptr_t engineBase; +static uint32_t allowedCallers[16]{}; +static size_t allowedCallerCount = 0; +extern "C" __declspec(dllexport) void SetOriginalLookup(void* address) { + originalLookup = reinterpret_cast(address); +} +static bool monitoredCaller(uintptr_t address) { + const auto rva = address - engineBase; + for (size_t i = 0; i < allowedCallerCount; ++i) if (rva == allowedCallers[i]) return true; + return false; +} +static CacheDiagnostics* diagnostics; +static SRWLOCK diagnosticsLock = SRWLOCK_INIT; +extern "C" void SetCacheDiagnostics(CacheDiagnostics* value) { diagnostics = value; } +static void copyDiagnosticName(wchar_t* output, const String* name, uint32_t reason) { + if (reason == 2) { wcscpy_s(output, 240, L""); return; } + __try { + if (name && (name->size < 0 || name->size > 4096 || (name->size && !name->data))) { wcscpy_s(output, 240, L""); return; } + if (!name || !name->size) { wcscpy_s(output, 240, L""); return; } + const size_t length = name->size > 239 ? 239 : static_cast(name->size); + memcpy(output, name->data, length * sizeof(wchar_t)); + output[length] = 0; + } __except(EXCEPTION_EXECUTE_HANDLER) { wcscpy_s(output, 240, L""); } +} +static void recordDiagnostic(const String* name, uint32_t reason, uint32_t caller) { + if (!diagnostics) return; + wchar_t text[240]{}; + copyDiagnosticName(text, name, reason); + FILETIME now; + GetSystemTimeAsFileTime(&now); + AcquireSRWLockExclusive(&diagnosticsLock); + const auto sequence = diagnostics->count + 1; + auto& entry = diagnostics->entries[(sequence - 1) % CacheLogCapacity]; + InterlockedExchange64(&entry.sequence, 0); + entry.filetime = (static_cast(now.dwHighDateTime) << 32) | now.dwLowDateTime; + entry.reason = reason; + entry.caller = caller; + memcpy(entry.name, text, sizeof(text)); + InterlockedExchange64(&entry.sequence, sequence); + InterlockedExchange64(&diagnostics->count, sequence); + ReleaseSRWLockExclusive(&diagnosticsLock); +} +static void* fallback(Interface* result, const String* name, uint32_t reason, uint32_t caller) { + ++counters[2]; + recordDiagnostic(name, reason, caller); + auto original = originalLookup.load(); + if (original) return original(result, name); + makeDefault(result); + return result; +} + +struct OwnedString { + String value{}; + ~OwnedString() { destroyString(&value); } +}; +struct OwnedList { + List value{}; + ~OwnedList() { + if (!value.d || *value.d == -1) return; + if (InterlockedDecrement(value.d) != 0) return; + for (intptr_t i = 0; i < value.size; ++i) destroyInterface(value.data + i); + freeArray(const_cast(value.d), sizeof(Interface), alignof(Interface)); + } +}; + +static bool refresh() { + const auto begin = GetTickCount64(); + try { + OwnedList list; + getAll(&list.value); + if (list.value.size < 0 || list.value.size > 4096 || (list.value.size > 0 && !list.value.data)) { + ++counters[4]; + return false; // Preserve last successful snapshot on enumeration failure. + } + Snapshot next; + for (intptr_t i = 0; i < list.value.size; ++i) { + const auto& iface = list.value.data[i]; + OwnedString name; + getName(&iface, &name.value); + if (!name.value.data || name.value.size < 0 || name.value.size > 4096) { + ++counters[4]; return false; + } + auto object = std::make_shared(iface); + next.emplace(std::wstring(name.value.data, size_t(name.value.size)), object); + // Qt also accepts a decimal interface index as its lookup key. + const int index = getIndex(&iface); + if (index > 0) next.emplace(std::to_wstring(index), object); + } + AcquireSRWLockExclusive(&cacheLock); + cache.swap(next); + ReleaseSRWLockExclusive(&cacheLock); + // Old snapshot destruction happens outside the GUI reader's lock. + counters[6] = uint64_t(list.value.size); + counters[5] = GetTickCount64() - begin; + lastSuccess = GetTickCount64(); + ++counters[3]; + return true; + } catch (...) { + ++counters[4]; + return false; + } +} + +static DWORD WINAPI workerMain(void*) { + counters[7] = GetCurrentThreadId(); + while (WaitForSingleObject(stopEvent, 1000) == WAIT_TIMEOUT) refresh(); + return 0; +} + +template static bool resolve(HMODULE module, const char* name, T& target) { + target = reinterpret_cast(GetProcAddress(module, name)); + return target != nullptr; +} + +static bool bindQtFunctions(HMODULE network, HMODULE core) { + return resolve(network, "??0QNetworkInterface@@QEAA@XZ", makeDefault) + && resolve(network, "??0QNetworkInterface@@QEAA@AEBV0@@Z", copyInterface) + && resolve(network, "??1QNetworkInterface@@QEAA@XZ", destroyInterface) + && resolve(network, "?name@QNetworkInterface@@QEBA?AVQString@@XZ", getName) + && resolve(network, "?index@QNetworkInterface@@QEBAHXZ", getIndex) + && resolve(network, "?allInterfaces@QNetworkInterface@@SA?AV?$QList@VQNetworkInterface@@@@XZ", getAll) + && resolve(core, "??1QString@@QEAA@XZ", destroyString) + && resolve(core, "?deallocate@QArrayData@@SAXPEAU1@_J1@Z", freeArray); +} + +extern "C" __declspec(dllexport) int InitializeCache() { + if (initialized) return 1; + for (auto& counter : counters) counter = 0; + lastSuccess = 0; + engineBase = reinterpret_cast(GetModuleHandleW(nullptr)); + HMODULE network = GetModuleHandleW(L"Qt6Network.dll"); + HMODULE core = GetModuleHandleW(L"Qt6Core.dll"); + if (!network || !core) return -1; + if (!bindQtFunctions(network, core)) return -2; + // Initial warm-up runs on the instrumentation thread, before installing the hook. + if (!refresh()) return -3; + stopEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr); + if (!stopEvent) return -4; + worker = CreateThread(nullptr, 0, workerMain, nullptr, 0, nullptr); + if (!worker) { CloseHandle(stopEvent); stopEvent = nullptr; return -5; } + SetThreadPriority(worker, THREAD_PRIORITY_BELOW_NORMAL); + initialized = true; + return 1; +} + +extern "C" __declspec(dllexport) void* CachedInterfaceFromName(Interface* result, const String* name) { + // Cache only the selected profile's verified call sites. Other callers keep Qt semantics. + const auto address = reinterpret_cast(_ReturnAddress()); + if (!monitoredCaller(address)) { + auto original = originalLookup.load(); + if (original) return original(result, name); + makeDefault(result); return result; + } + const auto caller = static_cast(address - engineBase); + if (!name || name->size < 0 || name->size > 4096 || (name->size && !name->data)) { + ++counters[0]; + return fallback(result, name, 2, caller); + } + // An unspecified interface has a stable invalid result, independent of the + // snapshot. Construct it through Qt; do not enumerate adapters for this case. + if (name->size == 0) { + recordDiagnostic(name, 5, caller); + return makeDefault(result); + } + ++counters[0]; + if (snapshotAge() > 3000) return fallback(result, name, 1, caller); + try { + const std::wstring key(name->data ? name->data : L"", size_t(name->size)); + AcquireSRWLockShared(&cacheLock); + auto found = cache.find(key); + if (found != cache.end()) { + // Copy only the implicitly-shared Qt interface handle under the lock. + copyInterface(result, &found->second->value); + ReleaseSRWLockShared(&cacheLock); + ++counters[1]; + return result; + } + ReleaseSRWLockShared(&cacheLock); + } catch (...) { return fallback(result, name, 4, caller); } + return fallback(result, name, 3, caller); +} + +extern "C" __declspec(dllexport) void GetCacheStats(uint64_t* output) { + for (int i = 0; i < 8; ++i) output[i] = counters[i].load(); + output[8] = snapshotAge(); +} + +extern "C" __declspec(dllexport) int StopCache() { + if (worker) { + SetEvent(stopEvent); + // Do not release objects or handles while a worker may still publish. + if (WaitForSingleObject(worker, 10000) != WAIT_OBJECT_0) return 0; + CloseHandle(worker); CloseHandle(stopEvent); + worker = stopEvent = nullptr; + } + Snapshot old; + AcquireSRWLockExclusive(&cacheLock); + cache.swap(old); + ReleaseSRWLockExclusive(&cacheLock); + initialized = false; + return 1; +} + +// Shared status header: 16 status words followed by up to 16 caller RVAs. +// magic, version, owner PID, command, phase, error, age, lookups, hits, misses, +// refreshes, errors, interfaces, refresh duration, heartbeat, caller count. +static void publish(volatile LONG64* shared) { + uint64_t values[9]{}; + GetCacheStats(values); + InterlockedExchange64(shared + 6, static_cast(values[8])); + for (int i = 0; i < 5; ++i) InterlockedExchange64(shared + 7 + i, static_cast(values[i])); + InterlockedExchange64(shared + 12, static_cast(values[6])); + InterlockedExchange64(shared + 13, static_cast(values[5])); +} + +static std::atomic controllerRunning{false}; +static bool hookCreated = false; +static void* hookTarget = nullptr; + +static bool verifiedCallBoundary(uintptr_t call) { + DWORD64 base = 0; + const auto function = RtlLookupFunctionEntry(call, &base, nullptr); + if (!function || base != engineBase || call < base + function->BeginAddress || call + 6 > base + function->EndAddress) return false; + auto cursor = base + function->BeginAddress; + size_t decoded = 0; + while (cursor < call && decoded++ < 65536) { + hde64s instruction{}; + hde64_disasm(reinterpret_cast(cursor), &instruction); + if (!instruction.len || (instruction.flags & F_ERROR) || cursor + instruction.len > call) return false; + cursor += instruction.len; + } + return cursor == call; +} + +static MH_STATUS changeHook(bool enable) { + for (unsigned attempt = 0; ; ++attempt) { + const auto status = enable ? MH_EnableHook(hookTarget) : MH_DisableHook(hookTarget); + if (status != MH_ERROR_THREAD_BUSY || attempt == 7) return status; + Sleep(1); + } +} +extern "C" DWORD WINAPI RunInstalledCache() { + bool expected = false; + if (!controllerRunning.compare_exchange_strong(expected, true)) return 10; + wchar_t mappingName[96]; + swprintf_s(mappingName, L"Local\\EngineToolsCache-%lu", GetCurrentProcessId()); + HANDLE mapping = OpenFileMappingW(FILE_MAP_ALL_ACCESS, FALSE, mappingName); + if (!mapping) { controllerRunning = false; return 11; } + auto shared = static_cast(MapViewOfFile(mapping, FILE_MAP_ALL_ACCESS, 0, 0, 256)); + if (!shared) { CloseHandle(mapping); controllerRunning = false; return 12; } + if (shared[0] != 0x45435431 || shared[1] != CacheProtocol || shared[2] != GetCurrentProcessId()) { + UnmapViewOfFile(const_cast(shared)); CloseHandle(mapping); controllerRunning = false; return 13; + } + // Validate the complete supplied call list before touching Qt or installing a hook. + engineBase = reinterpret_cast(GetModuleHandleW(nullptr)); + const auto image = reinterpret_cast(engineBase); + const auto nt = reinterpret_cast(engineBase + image->e_lfanew); + const auto size = nt->OptionalHeader.SizeOfImage; + const auto target = GetProcAddress(GetModuleHandleW(L"Qt6Network.dll"), "?interfaceFromName@QNetworkInterface@@SA?AV1@AEBVQString@@@Z"); + bool callersValid = shared[15] > 0 && shared[15] <= 16 && target; + allowedCallerCount = 0; + for (LONG64 i = 0; callersValid && i < shared[15]; ++i) { + const auto rva = static_cast(shared[16 + i]); + if (rva < 6 || rva >= size) { callersValid = false; break; } + const auto call = reinterpret_cast(engineBase + rva - 6); + if (call[0] != 0xff || call[1] != 0x15 || !verifiedCallBoundary(reinterpret_cast(call))) { callersValid = false; break; } + int32_t displacement; + memcpy(&displacement, call + 2, sizeof(displacement)); + const auto slot = static_cast(rva) + displacement; + if (slot < 0 || static_cast(slot) + sizeof(void*) > size || + *reinterpret_cast(engineBase + slot) != reinterpret_cast(target)) { + callersValid = false; break; + } + allowedCallers[allowedCallerCount++] = static_cast(rva); + } + if (!callersValid) { + InterlockedExchange64(shared + 5, 15); + InterlockedExchange64(shared + 4, 4); + UnmapViewOfFile(const_cast(shared)); CloseHandle(mapping); + controllerRunning = false; return 15; + } + DWORD error = 0; + bool enabled = false; + if (!error) { + const int result = InitializeCache(); + if (result != 1) error = 100 + DWORD(-result); + } + if (!error) { + if (!hookCreated) { + const auto init = MH_Initialize(); + if (init != MH_OK && init != MH_ERROR_ALREADY_INITIALIZED) error = 200 + init; + hookTarget = reinterpret_cast(GetProcAddress(GetModuleHandleW(L"Qt6Network.dll"), "?interfaceFromName@QNetworkInterface@@SA?AV1@AEBVQString@@@Z")); + if (!hookTarget) error = 220; + void* trampoline = nullptr; + if (!error) { + const auto created = MH_CreateHook(hookTarget, reinterpret_cast(CachedInterfaceFromName), &trampoline); + if (created != MH_OK) error = 230 + created; + else { SetOriginalLookup(trampoline); hookCreated = true; } + } + } + if (!error) { + const auto status = changeHook(true); + if (status != MH_OK) error = 260 + status; + else enabled = true; + } + } + if (!error) { + publish(shared); + InterlockedExchange64(shared + 4, 2); // Active only after the hook is enabled. + while (InterlockedCompareExchange64(shared + 3, 0, 0) == 0) { + publish(shared); + Sleep(100); + if (snapshotAge() > 3000) { error = 302; break; } + } + } + InterlockedExchange64(shared + 4, 5); // Stopping. + if (enabled) { + const auto status = changeHook(false); + if (status != MH_OK) error = 330 + status; + } + // Do not delete the trampoline or unload this DLL: a concurrent caller may + // still be returning through the replacement. Retain them until process exit. + if (!StopCache()) error = 303; + publish(shared); + InterlockedExchange64(shared + 5, error); + InterlockedExchange64(shared + 4, error ? 4 : 3); + UnmapViewOfFile(const_cast(shared)); + CloseHandle(mapping); + // A stuck worker must not be restarted against the same Qt cache objects. + if (error != 303) controllerRunning = false; + return error; +} + +// Executed only in a separate, disposable EngineTools probe process. No hook +// is installed and no Engine DJ process is opened by this entry point. +template struct GuardedQt { + uint64_t before = 0x9a684a7fc75d4a8bULL; + T value{}; + uint64_t after = 0x2ab6c4d92ce4a9d1ULL; + bool intact() const { return before == 0x9a684a7fc75d4a8bULL && after == 0x2ab6c4d92ce4a9d1ULL; } +}; + +static DWORD probeQt(const wchar_t* directory) { + SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); + const std::wstring root(directory); + const auto core = LoadLibraryExW((root + L"\\Qt6Core.dll").c_str(), nullptr, + LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); + const auto network = LoadLibraryExW((root + L"\\Qt6Network.dll").c_str(), nullptr, + LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_DEFAULT_DIRS); + if (!core || !network) return 401; + using VersionFn = const char* (*)(); + auto version = reinterpret_cast(GetProcAddress(core, "qVersion")); + if (!version || strncmp(version(), "6.", 2) != 0) return 402; + if (!bindQtFunctions(network, core)) return 403; + auto lookup = reinterpret_cast(GetProcAddress(network, "?interfaceFromName@QNetworkInterface@@SA?AV1@AEBVQString@@@Z")); + if (!lookup) return 404; + + GuardedQt empty, copied; + makeDefault(&empty.value); + if (!empty.intact() || getIndex(&empty.value) > 0) return 405; + copyInterface(&copied.value, &empty.value); + if (!copied.intact() || copied.value.d != empty.value.d) return 406; + destroyInterface(&copied.value); + destroyInterface(&empty.value); + if (!empty.intact() || !copied.intact()) return 407; + + // Check the actual target Qt library's empty-name semantics before allowing + // this fast path on an automatically detected build. + GuardedQt emptyName; + GuardedQt emptyLookup, fastEmpty; + lookup(&emptyLookup.value, &emptyName.value); + makeDefault(&fastEmpty.value); + const bool equivalentEmpty = emptyName.intact() && emptyLookup.intact() && fastEmpty.intact() && + getIndex(&emptyLookup.value) == 0 && getIndex(&fastEmpty.value) == 0 && + emptyLookup.value.d == fastEmpty.value.d; + destroyInterface(&emptyLookup.value); + destroyInterface(&fastEmpty.value); + if (!equivalentEmpty || !emptyLookup.intact() || !fastEmpty.intact()) return 414; + + GuardedQt raw; + getAll(&raw.value); + if (!raw.intact() || !raw.value.d || !raw.value.data || raw.value.size < 1 || raw.value.size > 4096) return 408; + OwnedList owned; + owned.value = raw.value; + raw.value = {}; + for (intptr_t i = 0; i < owned.value.size && i < 3; ++i) { + const auto& iface = owned.value.data[i]; + const int index = getIndex(&iface); + GuardedQt name, roundtrip; + getName(&iface, &name.value); + if (!name.intact() || !name.value.data || name.value.size < 1 || name.value.size > 4096 || index <= 0) return 409; + GuardedQt result, copy; + lookup(&result.value, &name.value); + if (!result.intact() || getIndex(&result.value) != index) return 410; + copyInterface(©.value, &result.value); + if (!copy.intact() || copy.value.d != result.value.d) return 411; + getName(©.value, &roundtrip.value); + if (!roundtrip.intact() || roundtrip.value.size != name.value.size || + !roundtrip.value.data || memcmp(roundtrip.value.data, name.value.data, name.value.size * sizeof(wchar_t)) != 0) return 412; + destroyString(&roundtrip.value); + destroyString(&name.value); + destroyInterface(©.value); + destroyInterface(&result.value); + if (!roundtrip.intact() || !name.intact() || !result.intact() || !copy.intact()) return 413; + } + return 0; +} + +extern "C" __declspec(dllexport) DWORD WINAPI ProbeABI(const wchar_t* directory) { + __try { + return probeQt(directory); + } __except(EXCEPTION_EXECUTE_HANDLER) { + return 490; + } +} diff --git a/internal/uifix/native/src/version.def b/internal/uifix/native/src/version.def new file mode 100644 index 0000000..551d227 --- /dev/null +++ b/internal/uifix/native/src/version.def @@ -0,0 +1,19 @@ +LIBRARY version +EXPORTS + GetFileVersionInfoA=VersionProxy0 @1 + GetFileVersionInfoByHandle=VersionProxy1 @2 + GetFileVersionInfoExA=VersionProxy2 @3 + GetFileVersionInfoExW=VersionProxy3 @4 + GetFileVersionInfoSizeA=VersionProxy4 @5 + GetFileVersionInfoSizeExA=VersionProxy5 @6 + GetFileVersionInfoSizeExW=VersionProxy6 @7 + GetFileVersionInfoSizeW=VersionProxy7 @8 + GetFileVersionInfoW=VersionProxy8 @9 + VerFindFileA=VersionProxy9 @10 + VerFindFileW=VersionProxy10 @11 + VerInstallFileA=VersionProxy11 @12 + VerInstallFileW=VersionProxy12 @13 + VerLanguageNameA=VersionProxy13 @14 + VerLanguageNameW=VersionProxy14 @15 + VerQueryValueA=VersionProxy15 @16 + VerQueryValueW=VersionProxy16 @17 diff --git a/internal/uifix/native/src/version_exports.asm b/internal/uifix/native/src/version_exports.asm new file mode 100644 index 0000000..6587dce --- /dev/null +++ b/internal/uifix/native/src/version_exports.asm @@ -0,0 +1,49 @@ +; Windows x64 forwarding stubs: preserve register and stack arguments. +EXTERN ResolveVersionProc:PROC +.code +PROXY_STUB MACRO number +PUBLIC VersionProxy&number +VersionProxy&number PROC FRAME + sub rsp, 0A8h + .allocstack 0A8h + .endprolog + mov [rsp+20h], rcx + mov [rsp+28h], rdx + mov [rsp+30h], r8 + mov [rsp+38h], r9 + movdqu [rsp+40h], xmm0 + movdqu [rsp+50h], xmm1 + movdqu [rsp+60h], xmm2 + movdqu [rsp+70h], xmm3 + mov ecx, number + call ResolveVersionProc + mov rcx, [rsp+20h] + mov rdx, [rsp+28h] + mov r8, [rsp+30h] + mov r9, [rsp+38h] + movdqu xmm0, [rsp+40h] + movdqu xmm1, [rsp+50h] + movdqu xmm2, [rsp+60h] + movdqu xmm3, [rsp+70h] + add rsp, 0A8h + jmp rax +VersionProxy&number ENDP +ENDM +PROXY_STUB 0 +PROXY_STUB 1 +PROXY_STUB 2 +PROXY_STUB 3 +PROXY_STUB 4 +PROXY_STUB 5 +PROXY_STUB 6 +PROXY_STUB 7 +PROXY_STUB 8 +PROXY_STUB 9 +PROXY_STUB 10 +PROXY_STUB 11 +PROXY_STUB 12 +PROXY_STUB 13 +PROXY_STUB 14 +PROXY_STUB 15 +PROXY_STUB 16 +END diff --git a/internal/uifix/native/src/version_proxy.cpp b/internal/uifix/native/src/version_proxy.cpp new file mode 100644 index 0000000..f0b4ea8 --- /dev/null +++ b/internal/uifix/native/src/version_proxy.cpp @@ -0,0 +1,166 @@ +#define WIN32_LEAN_AND_MEAN +#include +#include +#include +#include +#include +#include "cache_protocol.h" + +extern "C" DWORD WINAPI RunInstalledCache(); +static HMODULE selfModule; +static INIT_ONCE versionOnce = INIT_ONCE_STATIC_INIT; +static HMODULE systemVersion; +static const char* exports[] = { + "GetFileVersionInfoA", "GetFileVersionInfoByHandle", "GetFileVersionInfoExA", + "GetFileVersionInfoExW", "GetFileVersionInfoSizeA", "GetFileVersionInfoSizeExA", + "GetFileVersionInfoSizeExW", "GetFileVersionInfoSizeW", "GetFileVersionInfoW", + "VerFindFileA", "VerFindFileW", "VerInstallFileA", "VerInstallFileW", + "VerLanguageNameA", "VerLanguageNameW", "VerQueryValueA", "VerQueryValueW" +}; +static BOOL CALLBACK loadVersion(PINIT_ONCE, PVOID, PVOID*) { + wchar_t path[MAX_PATH]; + const UINT size = GetSystemDirectoryW(path, MAX_PATH); + if (!size || size + 13 >= MAX_PATH) return FALSE; + wcscat_s(path, L"\\version.dll"); + systemVersion = LoadLibraryExW(path, nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + return systemVersion != nullptr; +} +extern "C" void* ResolveVersionProc(unsigned index) { + if (index >= _countof(exports) || !InitOnceExecuteOnce(&versionOnce, loadVersion, nullptr, nullptr)) + RaiseFailFastException(nullptr, nullptr, 0); + auto proc = GetProcAddress(systemVersion, exports[index]); + if (!proc) RaiseFailFastException(nullptr, nullptr, 0); + return reinterpret_cast(proc); +} + +#pragma pack(push, 1) +struct Configuration { + char magic[16]; + uint32_t version, count; + unsigned char hashes[3][32]; // Engine DJ.exe, Qt6Core.dll, Qt6Network.dll + uint32_t callers[16]; + unsigned char payloadHash[32]; + uint64_t payloadSize; + unsigned char checksum[32]; +}; +#pragma pack(pop) +static_assert(sizeof(Configuration) == 256); + +static bool hash(HANDLE file, uint64_t length, unsigned char* output) { + BCRYPT_ALG_HANDLE algorithm = nullptr; + BCRYPT_HASH_HANDLE digest = nullptr; + if (BCryptOpenAlgorithmProvider(&algorithm, BCRYPT_SHA256_ALGORITHM, nullptr, 0) < 0) return false; + bool ok = BCryptCreateHash(algorithm, &digest, nullptr, 0, nullptr, 0, 0) >= 0; + unsigned char buffer[65536]; + while (ok && length) { + DWORD read = 0; + const DWORD chunk = length < sizeof(buffer) ? static_cast(length) : sizeof(buffer); + ok = ReadFile(file, buffer, chunk, &read, nullptr) && read == chunk; + if (ok) ok = BCryptHashData(digest, buffer, read, 0) >= 0; + length -= read; + } + if (ok) ok = BCryptFinishHash(digest, output, 32, 0) >= 0; + if (digest) BCryptDestroyHash(digest); + BCryptCloseAlgorithmProvider(algorithm, 0); + return ok; +} +static bool matches(const std::wstring& path, const unsigned char* expected) { + HANDLE file = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); + if (file == INVALID_HANDLE_VALUE) return false; + LARGE_INTEGER size{}; + unsigned char actual[32]; + const bool ok = GetFileSizeEx(file, &size) && size.QuadPart >= 0 && + hash(file, static_cast(size.QuadPart), actual) && memcmp(actual, expected, 32) == 0; + CloseHandle(file); + return ok; +} +static bool readConfiguration(const std::wstring& path, Configuration& config) { + HANDLE file = CreateFileW(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); + if (file == INVALID_HANDLE_VALUE) return false; + LARGE_INTEGER size{}, offset{}; + offset.QuadPart = -static_cast(sizeof(config)); + DWORD read = 0; + bool ok = GetFileSizeEx(file, &size) && size.QuadPart > sizeof(config) && + SetFilePointerEx(file, offset, nullptr, FILE_END) && + ReadFile(file, &config, sizeof(config), &read, nullptr) && read == sizeof(config) && + memcmp(config.magic, "EngineToolsPrx01", 16) == 0 && config.version == 1 && + config.count > 0 && config.count <= 16 && config.payloadSize == size.QuadPart - sizeof(config); + unsigned char actual[32]; + offset.QuadPart = 0; + if (ok) ok = SetFilePointerEx(file, offset, nullptr, FILE_BEGIN) && hash(file, config.payloadSize, actual) && + memcmp(actual, config.payloadHash, 32) == 0; + // Hash the trailer bytes directly with CNG; no persisted configuration file. + if (ok) { + BCRYPT_ALG_HANDLE algorithm = nullptr; + ok = BCryptOpenAlgorithmProvider(&algorithm, BCRYPT_SHA256_ALGORITHM, nullptr, 0) >= 0; + if (ok) { + ok = BCryptHash(algorithm, nullptr, 0, reinterpret_cast(&config), 224, actual, 32) >= 0 && + memcmp(actual, config.checksum, 32) == 0; + BCryptCloseAlgorithmProvider(algorithm, 0); + } + } + CloseHandle(file); + return ok; +} + +static DWORD WINAPI standaloneMain(void*) { + wchar_t executable[32768], proxy[32768]; + if (!GetModuleFileNameW(nullptr, executable, _countof(executable)) || + !GetModuleFileNameW(selfModule, proxy, _countof(proxy))) return 0; + const std::wstring exe(executable), own(proxy); + const auto split = exe.find_last_of(L"\\/"); + if (split == std::wstring::npos || _wcsicmp(exe.c_str() + split + 1, L"Engine DJ.exe") != 0) return 0; + const auto directory = exe.substr(0, split + 1); + if (_wcsicmp(own.c_str(), (directory + L"version.dll").c_str()) != 0) return 0; + + wchar_t name[96]; + swprintf_s(name, L"Local\\EngineToolsCache-%lu", GetCurrentProcessId()); + HANDLE mapping = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, static_cast(CacheMappingBytes), name); + if (!mapping) return 0; + if (GetLastError() == ERROR_ALREADY_EXISTS) { CloseHandle(mapping); return 0; } + auto shared = static_cast(MapViewOfFile(mapping, FILE_MAP_ALL_ACCESS, 0, 0, CacheMappingBytes)); + if (!shared) { CloseHandle(mapping); return 0; } + shared[0] = 0x45435431; shared[1] = CacheProtocol; shared[2] = GetCurrentProcessId(); + auto diagnostics = reinterpret_cast(reinterpret_cast(shared) + CacheStatusBytes); + FILETIME session; + GetSystemTimeAsFileTime(&session); + diagnostics->session = (static_cast(session.dwHighDateTime) << 32) | session.dwLowDateTime; + SetCacheDiagnostics(diagnostics); + InterlockedExchange64(shared + 4, 1); + Configuration config{}; + DWORD error = readConfiguration(own, config) ? 0 : 500; + const wchar_t* files[] = {L"Engine DJ.exe", L"Qt6Core.dll", L"Qt6Network.dll"}; + for (int i = 0; !error && i < 3; ++i) if (!matches(directory + files[i], config.hashes[i])) error = 501; + for (int i = 1; !error && i < 3; ++i) { + wchar_t loaded[32768]; + const auto module = GetModuleHandleW(files[i]); + if (!module || !GetModuleFileNameW(module, loaded, _countof(loaded)) || + _wcsicmp(loaded, (directory + files[i]).c_str()) != 0) error = 501; + } + if (!error) { + shared[15] = config.count; + for (uint32_t i = 0; i < config.count; ++i) shared[16 + i] = config.callers[i]; + error = RunInstalledCache(); + } + if (error) { InterlockedExchange64(shared + 5, error); InterlockedExchange64(shared + 4, 4); } + // Keep diagnostics readable for a later EngineTools instance, including failures. + Sleep(INFINITE); + return 0; +} + +BOOL WINAPI DllMain(HINSTANCE module, DWORD reason, LPVOID) { + if (reason == DLL_PROCESS_ATTACH) { + selfModule = module; + // Loading this DLL for an isolated ABI probe must not create a worker + // which could still execute after the probe unloads the module. + wchar_t executable[32768]; + if (!GetModuleFileNameW(nullptr, executable, _countof(executable))) return TRUE; + const auto filename = wcsrchr(executable, L'\\'); + if (!filename || _wcsicmp(filename + 1, L"Engine DJ.exe") != 0) return TRUE; + // The entry thread cannot execute until process DLL initialization ends. + // Never wait or call Qt/LoadLibrary/scan/hash while holding the loader lock. + HANDLE thread = CreateThread(nullptr, 0, standaloneMain, nullptr, 0, nullptr); + if (thread) CloseHandle(thread); + } + return TRUE; +} diff --git a/internal/uifix/probe.go b/internal/uifix/probe.go new file mode 100644 index 0000000..e64de9e --- /dev/null +++ b/internal/uifix/probe.go @@ -0,0 +1,140 @@ +package uifix + +import ( + "EngineTools/internal/storage" + "context" + "crypto/sha256" + "encoding/json" + "fmt" + "os" + "os/exec" + "path/filepath" + "sync" + "syscall" + "time" + "unsafe" + + "golang.org/x/sys/windows" +) + +const probeArgument = "--uifix-abi-probe" + +// The installed proxy also exports the isolated ABI probe. No second DLL asset +// or persistent extraction directory is needed. +func extractProbeDLL() (string, func(), error) { + file, err := os.CreateTemp(storage.Path(), "enginetools-probe-*.dll") + if err != nil { + return "", nil, err + } + cleanup := func() { os.Remove(file.Name()) } + if _, err = file.Write(proxyBinary); err != nil { + file.Close() + cleanup() + return "", nil, err + } + if err = file.Close(); err != nil { + cleanup() + return "", nil, err + } + return file.Name(), cleanup, nil +} + +var probeResults = struct { + sync.Mutex + passed map[string]bool +}{passed: make(map[string]bool)} + +// RunProbeMode is checked before window creation/elevation in the app entry +// point. Reusing the app executable avoids distributing another executable. +func RunProbeMode(args []string) bool { + if len(args) == 0 || args[0] != probeArgument { + return false + } + result := struct { + OK bool `json:"ok"` + Error string `json:"error,omitempty"` + }{} + var err error + if len(args) != 3 { + err = fmt.Errorf("invalid Qt probe arguments") + } else { + err = probeLocal(args[1], args[2]) + } + result.OK = err == nil + if err != nil { + result.Error = err.Error() + } + json.NewEncoder(os.Stdout).Encode(result) + if err != nil { + os.Exit(1) + } + return true +} + +func probeLocal(directory, dll string) error { + if !filepath.IsAbs(directory) || !filepath.IsAbs(dll) { + return fmt.Errorf("probe paths must be absolute") + } + data, err := os.ReadFile(dll) + if err != nil { + return err + } + if sha256.Sum256(data) != sha256.Sum256(proxyBinary) { + return fmt.Errorf("cache probe DLL integrity check failed") + } + kernel.NewProc("SetErrorMode").Call(0x1 | 0x2) + module, err := windows.LoadLibraryEx(dll, 0, windows.LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR|windows.LOAD_LIBRARY_SEARCH_DEFAULT_DIRS) + if err != nil { + return err + } + defer windows.FreeLibrary(module) + address, err := windows.GetProcAddress(module, "ProbeABI") + if err != nil { + return err + } + path, err := windows.UTF16PtrFromString(directory) + if err != nil { + return err + } + code, _, _ := syscall.SyscallN(address, uintptr(unsafe.Pointer(path))) + if code != 0 { + return fmt.Errorf("Qt object layout/capability validation failed (code %d)", code) + } + return nil +} + +func checkAutomaticABI(directory, dll string, profile *buildProfile) error { + key := compatibilityValidator() + ":" + compatibilityKey(profile.Hashes) + probeResults.Lock() + cached := probeResults.passed[key] + probeResults.Unlock() + if cached { + return nil + } + executable, err := os.Executable() + if err != nil { + return err + } + ctx, stop := context.WithTimeout(context.Background(), 15*time.Second) + defer stop() + command := exec.CommandContext(ctx, executable, probeArgument, directory, dll) + command.SysProcAttr = &syscall.SysProcAttr{HideWindow: true, CreationFlags: 0x08000000} + output, err := command.Output() + if ctx.Err() != nil { + return fmt.Errorf("Qt compatibility probe cancelled or timed out") + } + if err != nil { + return fmt.Errorf("Qt compatibility probe failed; Engine DJ was not modified: %v %s", err, string(output)) + } + var result struct { + OK bool `json:"ok"` + Error string `json:"error"` + } + if json.Unmarshal(output, &result) != nil || !result.OK { + return fmt.Errorf("Qt compatibility probe did not confirm the object layout: %s", result.Error) + } + probeResults.Lock() + probeResults.passed[key] = true + probeResults.Unlock() + return nil +} diff --git a/internal/uifix/scan.go b/internal/uifix/scan.go new file mode 100644 index 0000000..5eafa92 --- /dev/null +++ b/internal/uifix/scan.go @@ -0,0 +1,281 @@ +package uifix + +import ( + "bytes" + "crypto/sha256" + "debug/pe" + "encoding/binary" + "encoding/hex" + "fmt" + "os" + "path/filepath" + "sort" + "strings" +) + +const interfaceLookupSymbol = "?interfaceFromName@QNetworkInterface@@SA?AV1@AEBVQString@@@Z" + +var requiredQtExports = map[string][]string{ + "Qt6Core.dll": {"??1QString@@QEAA@XZ", "?deallocate@QArrayData@@SAXPEAU1@_J1@Z", "qVersion"}, + "Qt6Network.dll": { + interfaceLookupSymbol, + "??0QNetworkInterface@@QEAA@XZ", "??0QNetworkInterface@@QEAA@AEBV0@@Z", "??1QNetworkInterface@@QEAA@XZ", + "?name@QNetworkInterface@@QEBA?AVQString@@XZ", "?index@QNetworkInterface@@QEBAHXZ", + "?allInterfaces@QNetworkInterface@@SA?AV?$QList@VQNetworkInterface@@@@XZ", + }, +} + +type imageReader struct { + file *pe.File + data []byte + header *pe.OptionalHeader64 +} + +func readImage(path, expectedHash string) (*imageReader, error) { + info, err := os.Stat(path) + if err != nil { + return nil, err + } + if !info.Mode().IsRegular() || info.Size() < 64 || info.Size() > 256<<20 { + return nil, fmt.Errorf("unsupported PE file size: %s", path) + } + data, err := os.ReadFile(path) + if err != nil { + return nil, err + } + digest := sha256.Sum256(data) + if expectedHash != "" && hex.EncodeToString(digest[:]) != expectedHash { + return nil, fmt.Errorf("file changed during compatibility scan: %s", path) + } + file, err := pe.NewFile(bytes.NewReader(data)) + if err != nil { + return nil, fmt.Errorf("invalid PE image %s: %w", path, err) + } + header, ok := file.OptionalHeader.(*pe.OptionalHeader64) + if file.Machine != pe.IMAGE_FILE_MACHINE_AMD64 || !ok { + return nil, fmt.Errorf("automatic cache detection requires Windows x64: %s", path) + } + return &imageReader{file: file, data: data, header: header}, nil +} +func (r *imageReader) read(rva uint32, size uint64) ([]byte, error) { + for _, section := range r.file.Sections { + if uint64(rva) >= uint64(section.VirtualAddress) && uint64(rva)+size <= uint64(section.VirtualAddress)+uint64(section.Size) { + start := uint64(section.Offset) + uint64(rva-section.VirtualAddress) + if start+size <= uint64(len(r.data)) { + return r.data[start : start+size], nil + } + } + } + return nil, fmt.Errorf("PE RVA 0x%x is outside file-backed sections", rva) +} +func (r *imageReader) text(rva uint32) (string, error) { + if rva == 0 { + return "", fmt.Errorf("null PE name RVA") + } + var name []byte + for i := uint32(0); i < 4096 && uint64(rva)+uint64(i) <= 0xffffffff; i++ { + b, err := r.read(rva+i, 1) + if err != nil { + return "", err + } + if b[0] == 0 { + return string(name), nil + } + name = append(name, b[0]) + } + return "", fmt.Errorf("unterminated PE name") +} +func (r *imageReader) exports() (map[string]bool, error) { + dir := r.header.DataDirectory[0] + if dir.VirtualAddress == 0 || dir.Size < 40 { + return nil, fmt.Errorf("missing PE exports") + } + table, err := r.read(dir.VirtualAddress, 40) + if err != nil { + return nil, err + } + count := binary.LittleEndian.Uint32(table[24:28]) + names := binary.LittleEndian.Uint32(table[32:36]) + if count > 65536 { + return nil, fmt.Errorf("too many PE exports") + } + array, err := r.read(names, uint64(count)*4) + if err != nil { + return nil, err + } + result := make(map[string]bool, count) + for i := uint32(0); i < count; i++ { + name, err := r.text(binary.LittleEndian.Uint32(array[i*4:])) + if err != nil { + return nil, err + } + result[name] = true + } + return result, nil +} +func (r *imageReader) lookupSlot() (uint32, error) { + dir := r.header.DataDirectory[1] + if dir.VirtualAddress == 0 || dir.Size < 20 || dir.Size > 1<<20 { + return 0, fmt.Errorf("missing/invalid import directory") + } + var slot uint32 + terminated := false + for offset := uint32(0); offset+20 <= dir.Size; offset += 20 { + descriptor, err := r.read(dir.VirtualAddress+offset, 20) + if err != nil { + return 0, err + } + if bytes.Equal(descriptor, make([]byte, 20)) { + terminated = true + break + } + name, err := r.text(binary.LittleEndian.Uint32(descriptor[12:16])) + if err != nil { + return 0, err + } + if !strings.EqualFold(name, "Qt6Network.dll") { + continue + } + original := binary.LittleEndian.Uint32(descriptor[0:4]) + iat := binary.LittleEndian.Uint32(descriptor[16:20]) + if original == 0 || iat == 0 { + return 0, fmt.Errorf("Qt imports have no on-disk lookup table") + } + ended := false + for index := uint32(0); index < 16384; index++ { + thunk, err := r.read(original+index*8, 8) + if err != nil { + return 0, err + } + address := binary.LittleEndian.Uint64(thunk) + if address == 0 { + ended = true + break + } + if address>>63 != 0 { + continue + } + if address > 0xfffffffd { + return 0, fmt.Errorf("invalid import name RVA") + } + symbol, err := r.text(uint32(address) + 2) + if err != nil { + return 0, err + } + if symbol == interfaceLookupSymbol { + if slot != 0 { + return 0, fmt.Errorf("ambiguous Qt interface lookup import") + } + slot = iat + index*8 + if _, err := r.read(slot, 8); err != nil { + return 0, err + } + } + } + if !ended { + return 0, fmt.Errorf("unterminated import lookup table") + } + } + if !terminated || slot == 0 { + return 0, fmt.Errorf("no supported Qt interface lookup import found") + } + return slot, nil +} + +type functionRange struct{ start, end uint32 } + +func (r *imageReader) functions() ([]functionRange, error) { + dir := r.header.DataDirectory[3] + if dir.VirtualAddress == 0 || dir.Size == 0 || dir.Size%12 != 0 || dir.Size > 24<<20 { + return nil, fmt.Errorf("missing/invalid x64 exception directory") + } + data, err := r.read(dir.VirtualAddress, uint64(dir.Size)) + if err != nil { + return nil, err + } + result := make([]functionRange, 0, len(data)/12) + for offset := 0; offset < len(data); offset += 12 { + start := binary.LittleEndian.Uint32(data[offset:]) + end := binary.LittleEndian.Uint32(data[offset+4:]) + if start >= end || end > r.header.SizeOfImage { + return nil, fmt.Errorf("invalid x64 function range") + } + result = append(result, functionRange{start, end}) + } + sort.Slice(result, func(i, j int) bool { return result[i].start < result[j].start }) + return result, nil +} +func (r *imageReader) scanCallers(slot uint32) ([]uint32, error) { + functions, err := r.functions() + if err != nil { + return nil, err + } + var callers []uint32 + for _, section := range r.file.Sections { + if section.Characteristics&pe.IMAGE_SCN_MEM_EXECUTE == 0 { + continue + } + size := section.Size + if section.VirtualSize != 0 && section.VirtualSize < size { + size = section.VirtualSize + } + code, err := r.read(section.VirtualAddress, uint64(size)) + if err != nil { + return nil, err + } + for offset := 0; offset+6 <= len(code); offset++ { + if code[offset] != 0xff || code[offset+1] != 0x15 { + continue + } + call := uint64(section.VirtualAddress) + uint64(offset) + target := int64(call+6) + int64(int32(binary.LittleEndian.Uint32(code[offset+2:]))) + if target != int64(slot) { + continue + } + index := sort.Search(len(functions), func(i int) bool { return uint64(functions[i].start) > call }) - 1 + if index < 0 || uint64(functions[index].end) < call+6 { + return nil, fmt.Errorf("query call outside a recognized x64 function") + } + callers = append(callers, uint32(call+6)) + if len(callers) > maxCacheCallers { + return nil, fmt.Errorf("more than %d query call sites; automatic cache detection is not supported", maxCacheCallers) + } + } + } + if len(callers) == 0 { + return nil, fmt.Errorf("no supported direct Qt query calls found") + } + sort.Slice(callers, func(i, j int) bool { return callers[i] < callers[j] }) + return callers, nil +} + +func scanAutomaticBuild(directory string, hashes map[string]string) (*buildProfile, error) { + for name, required := range requiredQtExports { + image, err := readImage(filepath.Join(directory, name), hashes[name]) + if err != nil { + return nil, err + } + exports, err := image.exports() + if err != nil { + return nil, fmt.Errorf("%s: %w", name, err) + } + for _, symbol := range required { + if !exports[symbol] { + return nil, fmt.Errorf("%s lacks required Qt interface %s", name, symbol) + } + } + } + image, err := readImage(filepath.Join(directory, "Engine DJ.exe"), hashes["Engine DJ.exe"]) + if err != nil { + return nil, err + } + slot, err := image.lookupSlot() + if err != nil { + return nil, err + } + callers, err := image.scanCallers(slot) + if err != nil { + return nil, err + } + return &buildProfile{Name: "Automatic Qt capability detection", Hashes: hashes, Callers: callers, Automatic: true}, nil +} diff --git a/internal/uifix/verified.go b/internal/uifix/verified.go new file mode 100644 index 0000000..61b3c0c --- /dev/null +++ b/internal/uifix/verified.go @@ -0,0 +1,86 @@ +package uifix + +import ( + "EngineTools/internal/storage" + "crypto/sha256" + "encoding/hex" + "fmt" + "slices" + "time" +) + +// Bump this revision when scanner/probe rules change independently of the DLL. +const compatibilityRevision = "1" + +func compatibilityValidator() string { + digest := sha256.Sum256(proxyBinary) + return compatibilityRevision + ":" + hex.EncodeToString(digest[:]) +} + +func compatibilityKey(hashes map[string]string) string { + digest := sha256.New() + for _, name := range proxyFiles { + fmt.Fprintf(digest, "%s:%s\n", name, hashes[name]) + } + return hex.EncodeToString(digest.Sum(nil)) +} + +func cachedCompatibility(hashes map[string]string, records map[string]storage.CompatibilityResult) *buildProfile { + record, ok := records[compatibilityKey(hashes)] + if !ok || record.Validator != compatibilityValidator() || len(record.Callers) == 0 || len(record.Callers) > maxCacheCallers { + return nil + } + for _, name := range proxyFiles { + if len(hashes[name]) != 64 || record.Hashes[name] != hashes[name] { + return nil + } + } + for i, caller := range record.Callers { + if caller < 6 || (i > 0 && caller <= record.Callers[i-1]) { + return nil + } + } + return &buildProfile{Name: "Saved verified Engine DJ/Qt build", Hashes: hashes, Callers: slices.Clone(record.Callers), Automatic: true, Cached: true} +} + +func saveVerifiedCompatibility(directory string, profile *buildProfile) error { + current, err := hashBuildFiles(directory) + if err != nil { + return err + } + for _, name := range proxyFiles { + if current[name] != profile.Hashes[name] { + return fmt.Errorf("%s changed during compatibility validation; retry installation", name) + } + } + record := storage.CompatibilityResult{Hashes: current, Callers: slices.Clone(profile.Callers), Validator: compatibilityValidator(), CheckedAt: time.Now().Format(time.RFC3339)} + return storage.UpdateSettings(func(s *storage.Settings) { + if s.EngineDJCompatibility == nil { + s.EngineDJCompatibility = make(map[string]storage.CompatibilityResult) + } + s.EngineDJCompatibility[compatibilityKey(current)] = record + }) +} + +// Clearing saved checks never changes an installed proxy or its running cache. +func (m *Manager) ClearCompatibilityRecords(key string) error { + m.mu.Lock() + defer m.mu.Unlock() + if err := storage.UpdateSettings(func(s *storage.Settings) { + if key == "" { + s.EngineDJCompatibility = nil + } else { + delete(s.EngineDJCompatibility, key) + } + }); err != nil { + return err + } + probeResults.Lock() + defer probeResults.Unlock() + if key == "" { + clear(probeResults.passed) + } else { + delete(probeResults.passed, compatibilityValidator()+":"+key) + } + return nil +} diff --git a/main.go b/main.go index 23e515c..fa3536a 100644 --- a/main.go +++ b/main.go @@ -1,10 +1,14 @@ package main import ( + "EngineTools/internal/logs" + "EngineTools/internal/storage" + "EngineTools/internal/uifix" "embed" "fmt" "os" "syscall" + "time" "unsafe" "github.com/wailsapp/wails/v2" @@ -64,7 +68,10 @@ func runAsAdmin(exe string) error { } func main() { - if !isAdmin() { + if uifix.RunProbeMode(os.Args[1:]) { + return + } + if shouldElevate() && !isAdmin() { exe, err := os.Executable() if err != nil { fmt.Fprintf(os.Stderr, "Failed to get executable path: %v\n", err) @@ -78,15 +85,25 @@ func main() { return } + // Binding generation also invokes main, but must not migrate user data. + if shouldElevate() { + if err := storage.Prepare(); err != nil { + _, _ = logs.New(storage.Path("Log")).Write("startup/ERROR", err.Error(), time.Time{}) + fmt.Fprintln(os.Stderr, "EngineTools storage error:", err) + return + } + } app := NewApp() err := wails.Run(&options.App{ - Title: "Engine Tools", - Width: 640, - Height: 820, - MinWidth: 600, - MinHeight: 720, - AssetServer: &assetserver.Options{ + Logger: &logs.Framework{Daily: app.daily}, + Title: "Engine Tools", + Frameless: true, + Width: 1280, + Height: 720, + MinWidth: 1280, + MinHeight: 720, + AssetServer: &assetserver.Options{ Assets: assets, }, BackgroundColour: &options.RGBA{R: 0x1a, G: 0x1a, B: 0x2e, A: 255}, @@ -96,15 +113,17 @@ func main() { app, }, Windows: &wailsWindows.Options{ - WebviewIsTransparent: false, - WindowIsTranslucent: false, - DisableWindowIcon: false, - WebviewBrowserPath: "", + WebviewUserDataPath: storage.Path("WebView"), + WebviewIsTransparent: false, + WindowIsTranslucent: false, + DisableWindowIcon: false, + WebviewBrowserPath: "", }, }) if err != nil { + app.log("Application error: " + err.Error()) fmt.Fprintf(os.Stderr, "Error: %v\n", err) os.Exit(1) } -} \ No newline at end of file +} diff --git a/notifications.go b/notifications.go new file mode 100644 index 0000000..81eb23f --- /dev/null +++ b/notifications.go @@ -0,0 +1,58 @@ +package main + +import wailsRuntime "github.com/wailsapp/wails/v2/pkg/runtime" + +// Confirmation requests stay inside the application instead of opening Windows dialogs. +func (a *App) confirm(title, message string) bool { + if a.ctx == nil { + return false + } + a.confirmationMu.Lock() + if a.closing { + a.confirmationMu.Unlock() + return false + } + if a.confirmations == nil { + a.confirmations = make(map[uint32]chan bool) + } + a.confirmationNext++ + id := a.confirmationNext + answer := make(chan bool, 1) + a.confirmations[id] = answer + a.confirmationMu.Unlock() + defer func() { + a.confirmationMu.Lock() + delete(a.confirmations, id) + a.confirmationMu.Unlock() + }() + wailsRuntime.EventsEmit(a.ctx, "confirmation", map[string]interface{}{ + "id": id, "title": title, "message": message, + }) + select { + case accepted := <-answer: + return accepted + case <-a.ctx.Done(): + return false + } +} + +func (a *App) RespondToConfirmation(id uint32, accepted bool) { + a.confirmationMu.Lock() + answer := a.confirmations[id] + delete(a.confirmations, id) + a.confirmationMu.Unlock() + if answer != nil { + answer <- accepted + } +} + +func (a *App) cancelConfirmations() { + a.confirmationMu.Lock() + a.closing = true + pending := a.confirmations + a.confirmations = nil + a.confirmationMu.Unlock() + for _, answer := range pending { + answer <- false + } +} diff --git a/wails.json b/wails.json index 451dbae..d1a5a32 100644 --- a/wails.json +++ b/wails.json @@ -1,7 +1,7 @@ { "$schema": "https://wails.io/schemas/config.v2.json", "name": "EngineTools", - "outputfilename": "EngineTools", + "outputfilename": "EngineTools-1.9.0-Preview", "frontend:install": "npm install", "frontend:build": "npm run build", "frontend:dev:watcher": "npm run dev", @@ -13,7 +13,7 @@ "info": { "companyName": "EngineTools", "productName": "Engine DJ Unicode Fix Tool", - "productVersion": "1.8.0", + "productVersion": "1.9.0", "copyright": "Copyright 2024 EngineTools. Licensed under Apache 2.0.", "comments": "Fix Unicode character display issues in Engine DJ by applying per-application UTF-8 manifest." }