├── .gitmodules
├── JitTest
├── JitTest
│ ├── main.cpp
│ ├── JitTest.vcxproj.user
│ ├── JitTest.vcxproj.filters
│ └── JitTest.vcxproj
└── JitTest.sln
├── screenshot.png
├── JitMagic
├── JitMagic
│ ├── JitMagic.ico
│ ├── App.xaml.cs
│ ├── App.xaml
│ ├── AssemblyInfo.cs
│ ├── NativeMethods.txt
│ ├── MVVMLibLite
│ │ ├── OurViewModelBase.cs
│ │ ├── ObservableClass.cs
│ │ ├── OurCommand.cs
│ │ └── MVVMSObservableObject.cs
│ ├── JitMagic.csproj
│ ├── Views
│ │ ├── JITSelectorWindow.xaml.cs
│ │ └── JITSelectorWindow.xaml
│ ├── Models
│ │ ├── ProcHelper.cs
│ │ ├── JitDebugger.cs
│ │ ├── CLIManager.cs
│ │ ├── AEDebugManager.cs
│ │ ├── ConfigManager.cs
│ │ └── FileHelper.cs
│ ├── app.manifest
│ └── ViewModels
│ │ └── JITSelectorViewModel.cs
└── JitMagic.sln
├── .gitignore
├── ManagedJitTest
├── ManagedJitTest
│ ├── App.config
│ ├── Program.cs
│ ├── Properties
│ │ └── AssemblyInfo.cs
│ └── ManagedJitTest.csproj
└── ManagedJitTest.sln
├── .github
└── workflows
│ └── continuous.yml
├── README.md
└── LICENSE
/.gitmodules:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/JitTest/JitTest/main.cpp:
--------------------------------------------------------------------------------
1 | int main()
2 | {
3 | __debugbreak();
4 | }
--------------------------------------------------------------------------------
/screenshot.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mrexodia/JitMagic/HEAD/screenshot.png
--------------------------------------------------------------------------------
/JitMagic/JitMagic/JitMagic.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/mrexodia/JitMagic/HEAD/JitMagic/JitMagic/JitMagic.ico
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .vs/
2 | asInvoker/
3 | bin/
4 | obj/
5 | requireAdministrator/
6 | Release/
7 | Debug/
8 | x64/
9 | packages/
10 |
--------------------------------------------------------------------------------
/JitTest/JitTest/JitTest.vcxproj.user:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/ManagedJitTest/ManagedJitTest/App.config:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/JitMagic/JitMagic/App.xaml.cs:
--------------------------------------------------------------------------------
1 | using System.Configuration;
2 | using System.Data;
3 | using System.Windows;
4 |
5 | namespace JitMagic {
6 | ///
7 | /// Interaction logic for App.xaml
8 | ///
9 | public partial class App : Application {
10 | }
11 |
12 | }
13 |
--------------------------------------------------------------------------------
/ManagedJitTest/ManagedJitTest/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 | using System.Threading.Tasks;
6 |
7 | namespace ManagedJitTest
8 | {
9 | class Program
10 | {
11 | static void Main(string[] args)
12 | {
13 | throw new Exception("ManagedJitTest");
14 | }
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/JitMagic/JitMagic/App.xaml:
--------------------------------------------------------------------------------
1 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/JitMagic/JitMagic/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Windows;
2 |
3 | [assembly: ThemeInfo(
4 | ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
5 | //(used if a resource is not found in the page,
6 | // or application resource dictionaries)
7 | ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
8 | //(used if a resource is not found in the page,
9 | // app, or any theme specific resource dictionaries)
10 | )]
11 |
--------------------------------------------------------------------------------
/JitMagic/JitMagic/NativeMethods.txt:
--------------------------------------------------------------------------------
1 | GetFinalPathNameByHandle
2 | CreateFile
3 | FILE_ACCESS_RIGHTS
4 | GENERIC_ACCESS_RIGHTS
5 | SetProcessMitigationPolicy
6 | GetProcessMitigationPolicy
7 | PROCESS_MITIGATION_REDIRECTION_TRUST_POLICY
8 | PROCESS_MITIGATION_DEP_POLICY
9 | DeviceIoControl
10 | MAXIMUM_REPARSE_DATA_BUFFER_SIZE
11 | FSCTL_GET_REPARSE_POINT
12 | REPARSE_DATA_BUFFER
13 | IO_REPARSE_TAG_SYMLINK
14 | IsWow64Process
15 | CreateEvent
16 | SetEvent
17 | WaitForSingleObject
18 | WaitForMultipleObjects
19 | CloseHandle
20 | SYMLINK_FLAG_RELATIVE
21 | IO_REPARSE_TAG_MOUNT_POINT
--------------------------------------------------------------------------------
/.github/workflows/continuous.yml:
--------------------------------------------------------------------------------
1 | env:
2 | NUKE_TELEMETRY_OPTOUT: 1
3 | name: continuous
4 |
5 | on:
6 | push:
7 | branches-ignore:
8 | - trash
9 |
10 | jobs:
11 | continuous:
12 | name: Run
13 | runs-on: windows-latest
14 | defaults:
15 | run:
16 | shell: pwsh
17 |
18 | steps:
19 | - uses: actions/checkout@v2
20 | with:
21 | submodules: recursive
22 | fetch-depth: 0
23 |
24 | - name: Run Build
25 | run: ./build.ps1
26 |
27 | - uses: actions/upload-artifact@v4
28 | with:
29 | name: JitMagic
30 | path: JitMagic\JitMagic\bin\x64\Release\net472\publish
--------------------------------------------------------------------------------
/JitTest/JitTest/JitTest.vcxproj.filters:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF}
6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx
7 |
8 |
9 | {93995380-89BD-4b04-88EB-625FBE52EBFB}
10 | h;hh;hpp;hxx;hm;inl;inc;ipp;xsd
11 |
12 |
13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01}
14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms
15 |
16 |
17 |
18 |
19 | Source Files
20 |
21 |
22 |
--------------------------------------------------------------------------------
/JitMagic/JitMagic.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 17
4 | VisualStudioVersion = 17.12.35417.141
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JitMagic", "JitMagic\JitMagic.csproj", "{63A0047E-64E8-4620-BB50-AE1CA17B3975}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Debug|x64 = Debug|x64
11 | Release|x64 = Release|x64
12 | EndGlobalSection
13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
14 | {63A0047E-64E8-4620-BB50-AE1CA17B3975}.Debug|x64.ActiveCfg = Debug|x64
15 | {63A0047E-64E8-4620-BB50-AE1CA17B3975}.Debug|x64.Build.0 = Debug|x64
16 | {63A0047E-64E8-4620-BB50-AE1CA17B3975}.Release|x64.ActiveCfg = Release|x64
17 | {63A0047E-64E8-4620-BB50-AE1CA17B3975}.Release|x64.Build.0 = Release|x64
18 | EndGlobalSection
19 | GlobalSection(SolutionProperties) = preSolution
20 | HideSolutionNode = FALSE
21 | EndGlobalSection
22 | GlobalSection(ExtensibilityGlobals) = postSolution
23 | SolutionGuid = {D959A076-86C3-4F29-BF66-6ECD4D611E2D}
24 | EndGlobalSection
25 | EndGlobal
26 |
--------------------------------------------------------------------------------
/JitMagic/JitMagic/MVVMLibLite/OurViewModelBase.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.ComponentModel;
4 | using System.Threading.Tasks;
5 | namespace JitMagic.MVVMLibLite {
6 | abstract public class OurViewModelBase : MVVMSObservableObject {
7 | protected Dictionary func_to_cmd;
8 | protected Dictionary, OurCommand> func_to_cmd_tsk;
9 |
10 |
11 | protected OurCommand GetOurCmd(Func func, bool auto_disable = true) {
12 | OurCommand ret;
13 | if (func_to_cmd_tsk == null)
14 | func_to_cmd_tsk = new Dictionary, OurCommand>();
15 | if (func_to_cmd_tsk.TryGetValue(func, out ret))
16 | return ret;
17 | return func_to_cmd_tsk[func] = new OurCommand(func, auto_disable);
18 |
19 | }
20 |
21 | protected OurCommand GetOurCmdSync(Action func, bool auto_disable = true, bool in_background = false) {
22 | OurCommand ret;
23 | if (func_to_cmd == null)
24 | func_to_cmd = new Dictionary();
25 | if (func_to_cmd.TryGetValue(func, out ret))
26 | return ret;
27 | return func_to_cmd[func] = new OurCommand(func, auto_disable, in_background);
28 | }
29 | }
30 | }
--------------------------------------------------------------------------------
/ManagedJitTest/ManagedJitTest/Properties/AssemblyInfo.cs:
--------------------------------------------------------------------------------
1 | using System.Reflection;
2 | using System.Runtime.CompilerServices;
3 | using System.Runtime.InteropServices;
4 |
5 | // General Information about an assembly is controlled through the following
6 | // set of attributes. Change these attribute values to modify the information
7 | // associated with an assembly.
8 | [assembly: AssemblyTitle("ManagedJitTest")]
9 | [assembly: AssemblyDescription("")]
10 | [assembly: AssemblyConfiguration("")]
11 | [assembly: AssemblyCompany("")]
12 | [assembly: AssemblyProduct("ManagedJitTest")]
13 | [assembly: AssemblyCopyright("Copyright © 2018")]
14 | [assembly: AssemblyTrademark("")]
15 | [assembly: AssemblyCulture("")]
16 |
17 | // Setting ComVisible to false makes the types in this assembly not visible
18 | // to COM components. If you need to access a type in this assembly from
19 | // COM, set the ComVisible attribute to true on that type.
20 | [assembly: ComVisible(false)]
21 |
22 | // The following GUID is for the ID of the typelib if this project is exposed to COM
23 | [assembly: Guid("e56f4752-28c7-427d-8ab4-f2e5675aa695")]
24 |
25 | // Version information for an assembly consists of the following four values:
26 | //
27 | // Major Version
28 | // Minor Version
29 | // Build Number
30 | // Revision
31 | //
32 | // You can specify all the values or you can default the Build and Revision Numbers
33 | // by using the '*' as shown below:
34 | // [assembly: AssemblyVersion("1.0.*")]
35 | [assembly: AssemblyVersion("1.0.0.0")]
36 | [assembly: AssemblyFileVersion("1.0.0.0")]
37 |
--------------------------------------------------------------------------------
/JitMagic/JitMagic/MVVMLibLite/ObservableClass.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.ComponentModel;
4 | namespace JitMagic.MVVMLibLite {
5 |
6 | public abstract class ObservableClass : MVVMSObservableObject {
7 | protected virtual void RaisePropertyChanged(string propertyName, T oldValue, T newValue) {
8 | if (string.IsNullOrEmpty(propertyName))
9 | throw new ArgumentException("This method cannot be called with an empty string", "propertyName");
10 | base.RaisePropertyChanged(propertyName);
11 | }
12 | protected virtual void RaisePropertyChanged(System.Linq.Expressions.Expression> propertyExpression, T oldValue, T newValue) {
13 | var propertyChangedHandler = PropertyChangedHandler;
14 | if (propertyChangedHandler == null)
15 | return;
16 | string propertyName = GetPropertyName(propertyExpression);
17 | propertyChangedHandler(this, new PropertyChangedEventArgs(propertyName));
18 | }
19 | protected new bool Set(System.Linq.Expressions.Expression> propertyExpression, ref T field, T newValue) {
20 | if (EqualityComparer.Default.Equals(field, newValue))
21 | return false;
22 | T oldValue = field;
23 | field = newValue;
24 |
25 | RaisePropertyChanged(propertyExpression, oldValue, field);
26 | return true;
27 | }
28 | protected new bool Set(string propertyName, ref T field, T newValue) {
29 | if (EqualityComparer.Default.Equals(field, newValue))
30 | return false;
31 | T oldValue = field;
32 | field = newValue;
33 | RaisePropertyChanged(propertyName, oldValue, field);
34 | return true;
35 | }
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/ManagedJitTest/ManagedJitTest.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.27906.1
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ManagedJitTest", "ManagedJitTest\ManagedJitTest.csproj", "{E56F4752-28C7-427D-8AB4-F2E5675AA695}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | Any CPU|Any CPU = Any CPU|Any CPU
11 | Prefer 32-bit|Any CPU = Prefer 32-bit|Any CPU
12 | x64|Any CPU = x64|Any CPU
13 | x86|Any CPU = x86|Any CPU
14 | EndGlobalSection
15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
16 | {E56F4752-28C7-427D-8AB4-F2E5675AA695}.Any CPU|Any CPU.ActiveCfg = Any CPU|Any CPU
17 | {E56F4752-28C7-427D-8AB4-F2E5675AA695}.Any CPU|Any CPU.Build.0 = Any CPU|Any CPU
18 | {E56F4752-28C7-427D-8AB4-F2E5675AA695}.Prefer 32-bit|Any CPU.ActiveCfg = Prefer 32-bit|Any CPU
19 | {E56F4752-28C7-427D-8AB4-F2E5675AA695}.Prefer 32-bit|Any CPU.Build.0 = Prefer 32-bit|Any CPU
20 | {E56F4752-28C7-427D-8AB4-F2E5675AA695}.x64|Any CPU.ActiveCfg = x64|Any CPU
21 | {E56F4752-28C7-427D-8AB4-F2E5675AA695}.x64|Any CPU.Build.0 = x64|Any CPU
22 | {E56F4752-28C7-427D-8AB4-F2E5675AA695}.x86|Any CPU.ActiveCfg = x86|Any CPU
23 | {E56F4752-28C7-427D-8AB4-F2E5675AA695}.x86|Any CPU.Build.0 = x86|Any CPU
24 | EndGlobalSection
25 | GlobalSection(SolutionProperties) = preSolution
26 | HideSolutionNode = FALSE
27 | EndGlobalSection
28 | GlobalSection(ExtensibilityGlobals) = postSolution
29 | SolutionGuid = {EA417BF5-2CA6-4A99-B859-1F4BC81874B1}
30 | EndGlobalSection
31 | EndGlobal
32 |
--------------------------------------------------------------------------------
/JitTest/JitTest.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio 15
4 | VisualStudioVersion = 15.0.27520.0
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "JitTest", "JitTest\JitTest.vcxproj", "{A63276BB-9346-475E-A332-74700C9F73EE}"
7 | EndProject
8 | Global
9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
10 | asInvoker|x64 = asInvoker|x64
11 | asInvoker|x86 = asInvoker|x86
12 | requireAdministrator|x64 = requireAdministrator|x64
13 | requireAdministrator|x86 = requireAdministrator|x86
14 | EndGlobalSection
15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
16 | {A63276BB-9346-475E-A332-74700C9F73EE}.asInvoker|x64.ActiveCfg = asInvoker|x64
17 | {A63276BB-9346-475E-A332-74700C9F73EE}.asInvoker|x64.Build.0 = asInvoker|x64
18 | {A63276BB-9346-475E-A332-74700C9F73EE}.asInvoker|x86.ActiveCfg = asInvoker|Win32
19 | {A63276BB-9346-475E-A332-74700C9F73EE}.asInvoker|x86.Build.0 = asInvoker|Win32
20 | {A63276BB-9346-475E-A332-74700C9F73EE}.requireAdministrator|x64.ActiveCfg = requireAdministrator|x64
21 | {A63276BB-9346-475E-A332-74700C9F73EE}.requireAdministrator|x64.Build.0 = requireAdministrator|x64
22 | {A63276BB-9346-475E-A332-74700C9F73EE}.requireAdministrator|x86.ActiveCfg = requireAdministrator|Win32
23 | {A63276BB-9346-475E-A332-74700C9F73EE}.requireAdministrator|x86.Build.0 = requireAdministrator|Win32
24 | EndGlobalSection
25 | GlobalSection(SolutionProperties) = preSolution
26 | HideSolutionNode = FALSE
27 | EndGlobalSection
28 | GlobalSection(ExtensibilityGlobals) = postSolution
29 | SolutionGuid = {1657A21C-0659-4DF1-B3C5-FFC510BEDA9C}
30 | EndGlobalSection
31 | EndGlobal
32 |
--------------------------------------------------------------------------------
/JitMagic/JitMagic/JitMagic.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | WinExe
5 | net472
6 | true
7 | JitMagic.ico
8 | x64
9 | preview
10 | app.manifest
11 |
12 | https://github.com/mrexodia/JitMagic
13 | Copyright © x64dbg
14 | x64
15 | $(DefineConstants);IS_WPF
16 | https://github.com/mrexodia/JitMagic
17 | git
18 | 2.0.0.0
19 | $(AssemblyVersion)
20 | $(AssemblyVersion)
21 |
22 |
23 |
24 |
25 |
26 | Never
27 |
28 |
29 |
30 |
31 |
32 |
33 | all
34 | runtime; build; native; contentfiles; analyzers; buildtransitive
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
--------------------------------------------------------------------------------
/JitMagic/JitMagic/MVVMLibLite/OurCommand.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Diagnostics;
3 | using System.Threading.Tasks;
4 | using System.Windows.Input;
5 |
6 | namespace JitMagic.MVVMLibLite {
7 | public class OurCommand : ICommand {
8 | private static Task T(Action action) {
9 | try {
10 | action();
11 | return Task.CompletedTask;
12 | } catch (Exception exception) {
13 | return Task.FromException(exception);
14 | }
15 | }
16 | public TimeSpan CommandMinRunTime = TimeSpan.FromSeconds(1);
17 | public bool CanExecute(object parameter) => (!auto_disable || !_running) && enabled;
18 | public OurCommand(Func action, bool auto_disable = true) {
19 | async_action = action;
20 | this.auto_disable = auto_disable;
21 | }
22 | public OurCommand(Action action, bool auto_disable, bool in_background) {
23 | if (in_background)
24 | async_action = () => Task.Run(action);
25 | else
26 | async_action = () => T(action);
27 | this.auto_disable = auto_disable;
28 | }
29 | private bool running {
30 | set {
31 | if (_running == value)
32 | return;
33 | _running = value;
34 | CanExecuteChanged?.Invoke(this, null);
35 | }
36 | }
37 | private bool _running;
38 | public bool enabled {
39 | get { return _enabled; }
40 | set {
41 | if (_enabled == value)
42 | return;
43 | _enabled = value;
44 | CanExecuteChanged?.Invoke(this, null);
45 | }
46 | }
47 | private bool _enabled = true;
48 | public event EventHandler CanExecuteChanged;
49 | public Func async_action;
50 |
51 | private readonly bool auto_disable;
52 | public void Execute(object parameter) {
53 | #pragma warning disable 4014
54 | Execute();
55 | #pragma warning restore 4014
56 | }
57 | public async Task Execute() {
58 | if (!enabled)
59 | return;
60 | running = true;
61 | var start_time = DateTime.MinValue;
62 | try {
63 | if (auto_disable)
64 | start_time = DateTime.Now;
65 | await async_action.Invoke();
66 | } catch (Exception e) {
67 | Debug.WriteLine($"Unhandled command exception of: {e}");
68 | } finally {
69 | if (auto_disable) {
70 | var diff = DateTime.Now - start_time;
71 | if (diff < CommandMinRunTime)
72 | await Task.Delay(CommandMinRunTime - diff);
73 | }
74 | running = false;
75 | }
76 | }
77 | }
78 | }
--------------------------------------------------------------------------------
/JitMagic/JitMagic/Views/JITSelectorWindow.xaml.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Diagnostics;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 | using System.Windows;
8 | using System.Windows.Controls;
9 | using System.Windows.Data;
10 | using System.Windows.Documents;
11 | using System.Windows.Input;
12 | using System.Windows.Media;
13 | using System.Windows.Media.Imaging;
14 | using System.Windows.Shapes;
15 | using JitMagic.ViewModels;
16 |
17 | namespace JitMagic.Views {
18 | ///
19 | /// Interaction logic for JITSelectorWindow.xaml
20 | ///
21 | public partial class JITSelectorWindow : Window {
22 | public JITSelectorWindow() {
23 | InitializeComponent();
24 | Loaded += JITSelectorWindow_Loaded;
25 | KeyDown += JITSelectorWindow_KeyDown;
26 | Closing += JITSelectorWindow_Closing;
27 | vm.CloseWin += (_, _) => { if (!closing) Close(); };
28 | vm.HideWin += (_,_) => Hide();
29 | }
30 |
31 |
32 |
33 |
34 |
35 | private void JITSelectorWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e) {
36 | closing = true;
37 | vm.Close();
38 | }
39 |
40 | private bool closing;
41 | private void JITSelectorWindow_KeyDown(object sender, KeyEventArgs e) {
42 | if (e.Key == Key.Escape)
43 | Close();
44 | }
45 |
46 | private void JITSelectorWindow_Loaded(object sender, RoutedEventArgs e) {
47 | Visibility = Visibility.Visible;
48 | vm.Loaded();
49 | if (listDebuggers.HasItems) {
50 | var firstUIItem = listDebuggers.ItemContainerGenerator.ContainerFromItem(listDebuggers.SelectedItem);
51 | Keyboard.Focus(firstUIItem as FrameworkElement);
52 | }
53 |
54 | }
55 | public JITSelectorViewModel vm => DataContext as JITSelectorViewModel;
56 |
57 |
58 | private void ListBox_KeyDown(object sender, KeyEventArgs e) {
59 | //sopport wrapping to the next line for selection
60 | var list = sender as ListBox;
61 | switch (e.Key) {
62 | case Key.Right:
63 | if (!list.Items.MoveCurrentToNext())
64 | list.Items.MoveCurrentToLast();
65 | break;
66 | case Key.Left:
67 | if (!list.Items.MoveCurrentToPrevious())
68 | list.Items.MoveCurrentToFirst();
69 | break;
70 | default:
71 | return;
72 | }
73 |
74 | e.Handled = true;
75 | if (list.SelectedItem != null)
76 | list.ScrollIntoView(list.SelectedItem);
77 | }
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/JitMagic/JitMagic/Models/ProcHelper.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Diagnostics;
4 | using System.Linq;
5 | using System.Management;
6 | using System.Reflection;
7 | using System.Security.Principal;
8 | using System.Text;
9 | using System.Threading.Tasks;
10 | using Microsoft.Win32.SafeHandles;
11 |
12 | namespace JitMagic.Models {
13 | static class ProcHelper {
14 | public static bool IsUserAdministrator() {
15 | //bool value to hold our return value
16 | bool isAdmin;
17 | try {
18 | //get the currently logged in user
19 | var user = WindowsIdentity.GetCurrent();
20 | var principal = new WindowsPrincipal(user);
21 | isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
22 | } catch (UnauthorizedAccessException) {
23 | isAdmin = false;
24 | } catch (Exception) {
25 | isAdmin = false;
26 | }
27 | return isAdmin;
28 | }
29 | public static void LaunchUs(bool asAdmin, String args = null) {
30 | Process.Start(new ProcessStartInfo {
31 | FileName = Assembly.GetExecutingAssembly().Location,
32 | UseShellExecute = true,
33 | Verb = asAdmin ? "runas" : "",
34 | Arguments = args,
35 | });
36 | }
37 | public static void EnsureAdminOrRestartWith(String restartWithArg) {
38 | if (IsUserAdministrator())
39 | return;
40 | LaunchUs(true, restartWithArg);
41 | Environment.Exit(0);
42 | }
43 | public static Architecture GetProcessArchitecture(Process p) {
44 | if (p.Id == 0 || p.HasExited)
45 | return Architecture.x64;
46 | if (Environment.Is64BitOperatingSystem) {
47 | if (Windows.Win32.PInvoke.IsWow64Process(new SafeProcessHandle(p.Handle, false), out var iswow64)) {
48 | return iswow64 ? Architecture.x86 : Architecture.x64;
49 | }
50 | throw new Exception("IsWow64Process failed");
51 | } else {
52 | return Architecture.x86;
53 | }
54 | }
55 | public static string GetProcessPath(Process p) {
56 | if (p.Id == 0 || p.HasExited)
57 | return null;
58 | string MethodResult = "";
59 | try {
60 | string Query = "SELECT ExecutablePath FROM Win32_Process WHERE ProcessId = " + p.Id;
61 |
62 | using (ManagementObjectSearcher mos = new ManagementObjectSearcher(Query)) {
63 | using (ManagementObjectCollection moc = mos.Get()) {
64 | string ExecutablePath = (from mo in moc.Cast() select mo["ExecutablePath"]).First().ToString();
65 | MethodResult = ExecutablePath;
66 | }
67 | }
68 | } catch {
69 | }
70 | return MethodResult;
71 | }
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/JitMagic/JitMagic/MVVMLibLite/MVVMSObservableObject.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.ComponentModel;
4 | using System.Reflection;
5 | using System.Linq.Expressions;
6 | using System.Runtime.CompilerServices;
7 |
8 | namespace JitMagic.MVVMLibLite {
9 |
10 | //modified from https://raw.githubusercontent.com/lbugnion/mvvmlight/b23c4d5bf6df654ad885be26ea053fb0efa04973/GalaSoft.MvvmLight/GalaSoft.MvvmLight%20(PCL)/ObservableObject.cs
11 | /* Original copyright */
12 | // ****************************************************************************
13 | //
14 | // Copyright © GalaSoft Laurent Bugnion 2011-2016
15 | //
16 | // ****************************************************************************
17 | // Laurent Bugnion
18 | // laurent@galasoft.ch
19 | // 10.4.2011
20 | // GalaSoft.MvvmLight.Messaging
21 | // http://www.mvvmlight.net
22 | //
23 | // See license.txt in this project or http://www.galasoft.ch/license_MIT.txt
24 | //
25 | // ****************************************************************************
26 |
27 | public class MVVMSObservableObject : INotifyPropertyChanged {
28 | public event PropertyChangedEventHandler PropertyChanged;
29 | protected PropertyChangedEventHandler PropertyChangedHandler => PropertyChanged;
30 |
31 | public virtual void RaisePropertyChanged([CallerMemberName] string propertyName = null) {
32 | var args = new PropertyChangedEventArgs(propertyName);
33 | PropertyChanged?.Invoke(this, args);
34 |
35 | }
36 | public virtual void RaisePropertyChanged(Expression> propertyExpression) {
37 | var handler = PropertyChanged;
38 |
39 | if (handler != null) {
40 | var propertyName = GetPropertyName(propertyExpression);
41 | if (!string.IsNullOrWhiteSpace(propertyName))
42 | RaisePropertyChanged(propertyName);
43 |
44 | }
45 | }
46 |
47 | protected static string GetPropertyName(Expression> propertyExpression) {
48 | var body = propertyExpression.Body as MemberExpression;
49 | var property = body.Member as PropertyInfo;
50 | return property.Name;
51 | }
52 | internal static string IntGetPropertyName(Expression> propertyExpression) => GetPropertyName(propertyExpression);
53 |
54 | protected bool Set(Expression> propertyExpression, ref T field, T newValue) {
55 | if (EqualityComparer.Default.Equals(field, newValue))
56 | return false;
57 |
58 | field = newValue;
59 | RaisePropertyChanged(propertyExpression);
60 | return true;
61 | }
62 | protected bool Set(string propertyName, ref T field, T newValue) {
63 | if (EqualityComparer.Default.Equals(field, newValue))
64 | return false;
65 |
66 | field = newValue;
67 | RaisePropertyChanged(propertyName);
68 | return true;
69 | }
70 |
71 | protected bool Set(ref T field, T newValue, [CallerMemberName] string propertyName = null) => Set(propertyName, ref field, newValue);
72 |
73 | protected bool Set(ref T field, T newValue, Expression> propertyExpression) => Set(propertyExpression, ref field, newValue);
74 |
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/JitMagic/JitMagic/Models/JitDebugger.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Drawing;
3 | using System.IO;
4 | using System.Text.RegularExpressions;
5 | using System.Windows;
6 | #if IS_WPF
7 | using System.Windows.Interop;
8 | using System.Windows.Media;
9 | using System.Windows.Media.Imaging;
10 | #endif
11 | using Newtonsoft.Json;
12 | using Newtonsoft.Json.Converters;
13 |
14 |
15 | namespace JitMagic.Models {
16 | [JsonConverter(typeof(StringEnumConverter))]
17 | public enum Architecture {
18 | x64 = 1 << 0,
19 | x86 = 1 << 1,
20 | All = x86 | x64
21 | }
22 | public class JitDebugger {
23 | public JitDebugger(string name, Architecture architecture) {
24 | Name = name;
25 | Architecture = architecture;
26 | }
27 | public JitDebugger Clone() => (JitDebugger)this.MemberwiseClone();
28 | public string Name { get; set; }
29 | public Architecture Architecture { get; }
30 | public string FileName { get; set; }
31 | public string Arguments { get; set; }
32 | public string IconOverridePath { get; set; }
33 | public int AdditionalDelaySecs { get; set; } = 0; // Additional time after it would normally exit where it exits. Good for misbehaving / non-signalling debuggers.
34 |
35 | [JsonIgnore]
36 | public bool Exists => File.Exists(FileName);
37 | public void LoadIcon(Icon fallback) {
38 | var iconFromAppRegex = new Regex(@"^(?.+[.](?:exe|dll))(?:[,](?[\-0-9]+))?$", RegexOptions.IgnoreCase);
39 |
40 | var GetIconMethod = (string path, int index) => Icon.ExtractAssociatedIcon(path);//backup method, downside is it can't take an index
41 | try {
42 | var mInfo = typeof(Icon).GetMethod(nameof(Icon.ExtractAssociatedIcon), System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic);
43 | if (mInfo != null) {
44 | var args = mInfo.GetParameters();
45 | if (args.Length == 2 && args[0].ParameterType == typeof(string) && args[1].ParameterType == typeof(int))
46 | GetIconMethod = (string path, int index) => (Icon)mInfo.Invoke(null, [path, index]);
47 | }
48 | } catch { }
49 |
50 |
51 |
52 | if (!File.Exists(FileName))
53 | return;
54 | icon = null;
55 | try {
56 | var extractPath = FileName;
57 | var extractIndex = 0;
58 | if (!String.IsNullOrWhiteSpace(IconOverridePath)) {
59 | var extractMatch = iconFromAppRegex.Match(IconOverridePath);
60 | if (extractMatch.Success) {
61 | extractPath = extractMatch.Groups["path"].Value;
62 | if (extractMatch.Groups["index"].Success)
63 | extractIndex = int.Parse(extractMatch.Groups["index"].Value);
64 | } else
65 | icon = new Icon(IconOverridePath);
66 |
67 | }
68 | if (icon == null)
69 | icon = GetIconMethod(extractPath, extractIndex);
70 | } catch { }
71 | if (icon == null)
72 | icon = fallback;
73 | #if IS_WPF
74 | DisplayIcon = ToImageSource(icon);
75 | #endif
76 | }
77 |
78 | public Icon icon;
79 | #if IS_WPF
80 | [JsonIgnore]
81 | public ImageSource DisplayIcon { get; set; }
82 | private static ImageSource ToImageSource(Icon icon) {
83 | ImageSource imageSource = Imaging.CreateBitmapSourceFromHIcon(
84 | icon.Handle,
85 | Int32Rect.Empty,
86 | BitmapSizeOptions.FromEmptyOptions());
87 |
88 | return imageSource;
89 | }
90 | #endif
91 | }
92 | }
93 |
--------------------------------------------------------------------------------
/JitMagic/JitMagic/app.manifest:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
54 |
55 |
56 | true
57 | PerMonitorV2
58 | true
59 |
60 |
61 |
62 |
63 |
71 |
72 |
73 |
74 |
75 |
76 |
--------------------------------------------------------------------------------
/ManagedJitTest/ManagedJitTest/ManagedJitTest.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Debug
6 | AnyCPU
7 | {E56F4752-28C7-427D-8AB4-F2E5675AA695}
8 | Exe
9 | ManagedJitTest
10 | ManagedJitTest
11 | v4.6.1
12 | 512
13 | true
14 | true
15 |
16 |
17 | AnyCPU
18 | pdbonly
19 | true
20 | bin\Any CPU\
21 | TRACE
22 | prompt
23 | 4
24 | false
25 |
26 |
27 | bin\x86\
28 | TRACE
29 | true
30 | pdbonly
31 | x86
32 | prompt
33 | MinimumRecommendedRules.ruleset
34 | false
35 |
36 |
37 | bin\x64\
38 | TRACE
39 | true
40 | pdbonly
41 | x64
42 | prompt
43 | MinimumRecommendedRules.ruleset
44 | false
45 |
46 |
47 | bin\Prefer 32-bit\
48 | TRACE
49 | true
50 | pdbonly
51 | AnyCPU
52 | prompt
53 | MinimumRecommendedRules.ruleset
54 | true
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
--------------------------------------------------------------------------------
/JitMagic/JitMagic/Models/CLIManager.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Diagnostics;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 | using System.Windows;
8 | #if ! IS_WPF
9 | using System.Windows.Forms;
10 | #endif
11 |
12 | namespace JitMagic.Models {
13 | public enum APP_ACTION { None, RegCheck, Register, Unregister, AddDebugger, RemoveDebugger, AEDebug, Screenshot }
14 | public class CLIManager {
15 |
16 |
17 |
18 | public APP_ACTION mode;
19 | private string[] args;
20 | private int CurArg;
21 | private string GetNextArg() {
22 | if (args.Length > CurArg)
23 | return args[CurArg++];
24 | return null;
25 | }
26 | public int ArgsLeft => args.Length - CurArg;
27 | public class RequestedTargetProc {
28 | public int Pid;
29 | public int EventHandleFD;
30 | public string JitDebugStructPtrAddy;
31 | public string ProcPath;
32 | public Architecture Architecture;
33 | }
34 | public RequestedTargetProc target;
35 | public CLIManager(ConfigManager config, AEDebugManager aeDebug, string[] args) {
36 | this.args = args;
37 | var action = GetNextArg();
38 | if (action != null && action.StartsWith("--") && Enum.TryParse(action.Replace("-", ""), true, out var parsed))
39 | mode = parsed;
40 |
41 | if (mode == APP_ACTION.None) {
42 | if (action == "-p") {
43 | try {
44 | target = new();
45 | target.Pid = int.Parse(GetNextArg());
46 | if (GetNextArg() == "-e"){
47 | target.EventHandleFD = int.Parse(GetNextArg());
48 | aeDebug.SetEventFD(new IntPtr(target.EventHandleFD));
49 | }
50 | if (GetNextArg() == "-j")
51 | target.JitDebugStructPtrAddy = GetNextArg();
52 | var process = Process.GetProcessById(target.Pid);
53 | target.ProcPath = ProcHelper.GetProcessPath(process);
54 | if (config.Config.BlacklistedPaths.Any(black => black.Equals(target.ProcPath, StringComparison.CurrentCultureIgnoreCase)))
55 | Environment.Exit(0);
56 |
57 | target.Architecture = ProcHelper.GetProcessArchitecture(process);
58 | mode = APP_ACTION.AEDebug;
59 | } catch (Exception ex) {
60 | MessageBox.Show("Error retrieving information! " + ex);
61 | }
62 | }
63 | }
64 |
65 | if (mode == APP_ACTION.None && config.Config.PerformRegisteredCheckOnStart && !aeDebug.UpdateRegistration(APP_ACTION.RegCheck)) {
66 | if (MessageBox.Show("We are not currently the default JIT debugger, should we set ourselves as the automatic debugger?", "Update JIT debugger to us?",
67 | #if IS_WPF
68 | MessageBoxButton.YesNo
69 | #else
70 | MessageBoxButtons.YesNo
71 | #endif
72 | ) ==
73 | #if IS_WPF
74 | MessageBoxResult.Yes
75 | #else
76 | DialogResult.Yes
77 | #endif
78 | )
79 | mode = APP_ACTION.Register;
80 |
81 | }
82 |
83 | switch (this.mode) {
84 | case APP_ACTION.AddDebugger:
85 | case APP_ACTION.RemoveDebugger:
86 | var name = GetNextArg();
87 | if (String.IsNullOrWhiteSpace(name))
88 | throw new ArgumentException("To add/remove a debugger the name must be passed for the first arg");
89 | if (mode == APP_ACTION.RemoveDebugger)
90 | config.RemoveDebugger(name);
91 | else {
92 | if (ArgsLeft < 3)
93 | throw new Exception($"To add a new debugger the form should be JitMagic.exe --add-debugger \"[DebuggerName]\" \"[DebuggerPath]\" \"[DebuggerArgs]\" [x86|x64|All] [AdditionalDelaySecs(optional)]");
94 |
95 | var path = GetNextArg();
96 | var callArgs = GetNextArg();
97 | var architecture = GetNextArg();
98 | if (!Enum.TryParse(architecture, true, out var arch))
99 | throw new Exception($"Archicture should be x64, x86, or All you passed: {architecture}");
100 | var deb = new JitDebugger(name, arch) { FileName = path, Arguments = callArgs };
101 | if (ArgsLeft > 0 && int.TryParse(GetNextArg(), out var addlDelaySecs))
102 | deb.AdditionalDelaySecs = addlDelaySecs;
103 | config.AddDebugger(deb);
104 |
105 | }
106 | break;
107 | case APP_ACTION.Register:
108 | case APP_ACTION.Unregister:
109 | ProcHelper.EnsureAdminOrRestartWith(this.mode == APP_ACTION.Register ? "--register" : "--unregister");
110 | aeDebug.UpdateRegistration(this.mode);
111 | break;
112 | case APP_ACTION.AEDebug:
113 | if (config.Config.IgnoringUntil > DateTime.Now)
114 | Environment.Exit(0);
115 | break;
116 | }
117 | }
118 | }
119 | }
120 |
--------------------------------------------------------------------------------
/JitMagic/JitMagic/Views/JITSelectorWindow.xaml:
--------------------------------------------------------------------------------
1 |
9 |
10 |
11 |
12 |
13 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
--------------------------------------------------------------------------------
/JitMagic/JitMagic/Models/AEDebugManager.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Reflection;
5 | using System.Runtime.InteropServices;
6 | using System.Text;
7 | using System.Threading.Tasks;
8 | using System.Windows;
9 | using PInvoke = Windows.Win32.PInvoke;
10 | using Microsoft.Win32;
11 | using Microsoft.Win32.SafeHandles;
12 | using System.Diagnostics;
13 | using HANDLE = Windows.Win32.Foundation.HANDLE;
14 | #if ! IS_WPF
15 | using System.Windows.Forms;
16 | #endif
17 |
18 | namespace JitMagic.Models {
19 | public class AEDebugManager {
20 | public const string OurAeDebugArgs = "-p %ld -e %ld -j %p";
21 | ///
22 | /// returns true if we are the current debugger at the end of the request
23 | ///
24 | ///
25 | ///
26 | ///
27 | public bool UpdateRegistration(APP_ACTION mode) {
28 | var spots = new string[] { @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug", @"SOFTWARE\WOW6432Node\Microsoft\Windows NT\CurrentVersion\AeDebug", @"SOFTWARE\WOW6432Node\Microsoft\VisualStudio\Debugger\JIT" };
29 | var us = $@"""{Assembly.GetExecutingAssembly().Location}"" {OurAeDebugArgs}";
30 | foreach (var spot in spots) {
31 | var isVSEntry = spot.EndsWith("JIT");
32 | var debugVal = isVSEntry ? "Native Debugger" : "Debugger";
33 | var bkVal = "DebuggerBackup";
34 |
35 | using var sub = Registry.LocalMachine.OpenSubKey(spot, mode != APP_ACTION.RegCheck);
36 |
37 | var curBk = sub.GetValue(bkVal) as string;
38 | var cur = sub.GetValue(debugVal) as string;
39 | var isUsNow = mode != APP_ACTION.Unregister ? cur.Equals(us, StringComparison.CurrentCultureIgnoreCase) : cur.StartsWith("\"" + Assembly.GetExecutingAssembly().Location, StringComparison.CurrentCultureIgnoreCase); //for unregistering we dont need exact match just to make sure its us
40 |
41 | if (isUsNow ? mode != APP_ACTION.Unregister : mode == APP_ACTION.Unregister)
42 | continue;
43 |
44 | if (mode == APP_ACTION.RegCheck)
45 | return false;
46 |
47 | if (mode == APP_ACTION.Register) {
48 | if (curBk != us && !string.IsNullOrWhiteSpace(cur))
49 | sub.SetValue(bkVal, cur);
50 |
51 | sub.SetValue(debugVal, us);
52 | if (!isVSEntry)
53 | sub.SetValue("Auto", 1);
54 | } else { //unregister
55 | if (string.IsNullOrWhiteSpace(curBk)) {
56 | sub.DeleteValue(debugVal);
57 | if (!isVSEntry)
58 | sub.SetValue("Auto", 0);
59 | } else {
60 | sub.SetValue(debugVal, curBk);
61 | sub.DeleteValue(bkVal);
62 | }
63 | }
64 | }
65 | if (mode == APP_ACTION.Register || mode == APP_ACTION.Unregister)
66 | MessageBox.Show(mode == APP_ACTION.Unregister ? "Removed Us" : "Registered");
67 | return true;
68 | }
69 |
70 | public void SignalResume() {
71 | if (_event != IntPtr.Zero) {
72 | PInvoke.SetEvent(new HANDLE(_event));
73 | PInvoke.CloseHandle(new HANDLE(_event));
74 | }
75 | _event = IntPtr.Zero;
76 | }
77 | IntPtr _event;
78 | public void SetEventFD(IntPtr fd) => _event = fd;
79 | private SafeFileHandle debugSignalEventForChild;
80 | public void StartDebugger(JitDebugger jitDebugger, int targetPid, String JitDebugStructPtrAddy) {
81 |
82 | var sec = new Windows.Win32.Security.SECURITY_ATTRIBUTES { bInheritHandle = true };
83 | sec.nLength = (uint)Marshal.SizeOf(sec);
84 |
85 | debugSignalEventForChild = _event != IntPtr.Zero ? PInvoke.CreateEvent(sec, true, false, null) : default;
86 | var debuggerArgTemplate = jitDebugger.Arguments;
87 | debuggerArgTemplate = debuggerArgTemplate.Replace("{pid", "{0").Replace("{debugSignalFd", "{1").Replace("{jitDebugInfoPtr", "{2");
88 | if (debuggerArgTemplate.Contains("{0}") == false && debuggerArgTemplate.Contains("%ld")) // support standard AeDebug strings but only if they don't have one of the expected existing subs
89 | debuggerArgTemplate = debuggerArgTemplate.Replace("%ld", "{0}").Replace("%ld", "{1}").Replace("%p", "{2}");
90 |
91 | var args = string.Format(debuggerArgTemplate, targetPid, debugSignalEventForChild?.DangerousGetHandle().ToInt32() ?? 0, JitDebugStructPtrAddy);
92 | var psi = new ProcessStartInfo {
93 | UseShellExecute = false,
94 | FileName = jitDebugger.FileName,
95 | Arguments = args,
96 | };
97 | // Undocumented feature of vsjitdebugger.exe that will halt it until a debugger is attached.
98 | //psi.EnvironmentVariables.Add("VS_Debugging_PauseOnStartup", "1");
99 | var p = Process.Start(psi);
100 | if (_event != IntPtr.Zero) {
101 | PInvoke.WaitForMultipleObjects([new HANDLE(debugSignalEventForChild.DangerousGetHandle()), new HANDLE(p.Handle)], false, uint.MaxValue);
102 | }
103 | }
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/JitMagic/JitMagic/Models/ConfigManager.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.IO;
4 | using System.Linq;
5 | using System.Text;
6 | using System.Threading.Tasks;
7 | using Newtonsoft.Json;
8 |
9 | namespace JitMagic.Models {
10 | public class ConfigManager {
11 | public Config Config;
12 |
13 | public void SaveConfig() {
14 | try {
15 | if (File.Exists(ConfigFile))
16 | File.Copy(ConfigFile, BackupConfigFile, true);
17 | } catch { }
18 |
19 | FileHelper.ReadWriteFile(ConfigFile, JsonConvert.SerializeObject(Config, Formatting.Indented));
20 | }
21 |
22 | public string ConfigFile => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "JitMagic.json");
23 | public string BackupConfigFile => ConfigFile + ".bk";
24 |
25 | public void AddDebugger(JitDebugger debugger) => AddRemoveDebugger(debugger.Name, debugger);
26 | public void RemoveDebugger(String DebuggerName) => AddRemoveDebugger(DebuggerName);
27 | private void AddRemoveDebugger(String DebuggerName, JitDebugger NewDebugger = null) {
28 | var debuggers = Config.JitDebuggers.Where(a => a.Name.Equals(DebuggerName, StringComparison.CurrentCultureIgnoreCase) == false).ToList();
29 | if (NewDebugger != null)
30 | debuggers.Insert(0, NewDebugger);
31 | Config.JitDebuggers = debuggers.ToArray();
32 | SaveConfig();
33 | }
34 |
35 |
36 |
37 | public void ReadConfig() {
38 | Config = new();
39 | string json = null;
40 | var configExists = File.Exists(ConfigFile);
41 | if (configExists) {
42 | try {
43 | json = FileHelper.ReadWriteFile(ConfigFile);
44 | if (!String.IsNullOrWhiteSpace(json))
45 | Config = JsonConvert.DeserializeObject(json);
46 | else
47 | configExists = false;
48 | } catch {
49 | try {
50 | if (!String.IsNullOrWhiteSpace(json)) {
51 | Config.JitDebuggers = JsonConvert.DeserializeObject(json);
52 | if (Config.JitDebuggers?.Length > 0 == true)
53 | SaveConfig();//save in new format
54 | }
55 | } catch { }
56 | }
57 | }
58 | if (Config.JitDebuggers?.Length > 0 != true)
59 | Config.JitDebuggers = DefaultDebuggers;
60 | Config.BlacklistedPaths ??= new();
61 | Config.BlacklistedPaths.RemoveAll(String.IsNullOrWhiteSpace);
62 | if (!configExists)
63 | SaveConfig();
64 |
65 | }
66 | private static JitDebugger[] DefaultDebuggers = [
67 | new JitDebugger("Visual Studio", Architecture.All)
68 | {
69 | FileName = @"C:\Windows\System32\vsjitdebugger.exe",
70 | Arguments = "-p {pid} -e {debugSignalFd} -j 0x{jitDebugInfoPtr}"
71 | },
72 | new JitDebugger("x32dbg", Architecture.x86)
73 | {
74 | FileName = @"c:\Program Files\x64Dbg\x32\x32dbg.exe",
75 | Arguments = "-a {pid} -e {debugSignalFd}"
76 | },
77 | new JitDebugger("x64dbg", Architecture.x64)
78 | {
79 | FileName = @"c:\Program Files\x64Dbg\x64\x64dbg.exe",
80 | Arguments = "-a {pid} -e {debugSignalFd}"
81 | },
82 | new JitDebugger("dnSpy (x64)", Architecture.x64) {
83 | FileName = @"c:\Program Files\dnSpy\dnSpy.exe",
84 | Arguments = "--dont-load-files --multiple -p {pid} -e {debugSignalFd} --jdinfo {jitDebugInfoPtr}"
85 | },
86 | new JitDebugger("dnSpy (x86)", Architecture.x86) {
87 | FileName = @"c:\Program Files\dnSpy\x86\dnSpy.exe",
88 | Arguments = "--dont-load-files --multiple -p {pid} -e {debugSignalFd} --jdinfo {jitDebugInfoPtr}"
89 | },
90 | new JitDebugger("WinDbg", Architecture.All)
91 | {
92 | FileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"Microsoft\WindowsApps\WinDbgX.exe"),
93 | Arguments = "-p {pid} -e {debugSignalFd} -g",
94 | IconOverridePath = @"C:\Windows\System32\shell32.dll,15" //it has an icon but is not accessible would need to resolve true path to the appdata dir and get the dbghash exec
95 | },
96 | new JitDebugger("Old WinDbg (x86)", Architecture.x86)
97 | {
98 | FileName = @"C:\Program Files (x86)\Windows Kits\10\Debuggers\x86\windbg.exe",
99 | Arguments = "-p {pid} -e {debugSignalFd} -g"
100 | },
101 | new JitDebugger("Old WinDbg (x64)", Architecture.x64)
102 | {
103 | FileName = @"C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\windbg.exe",
104 | Arguments = "-p {pid} -e {debugSignalFd} -g"
105 | },
106 | new JitDebugger("ProcDump MiniPlus", Architecture.All)
107 | {
108 | FileName = @"c:\Program Files\Sysinternals\procdump.exe",
109 | Arguments = "-accepteula -mp -j \"c:/dumps\" {pid} {debugSignalFd} {jitDebugInfoPtr}",
110 | IconOverridePath = @"C:\Windows\System32\MdRes.exe"
111 | }
112 | ];
113 | }
114 | public class Config {
115 | public JitDebugger[] JitDebuggers { get; set; }
116 | public int DefaultIgnoreMinutes { get; set; } = 3;
117 | public bool PerformRegisteredCheckOnStart { get; set; } = true;
118 | public DateTime IgnoringUntil { get; set; } = DateTime.FromFileTime(0);
119 | public int OverrideWidth { get; set; } = 0;
120 | public int OverrideHeight { get; set; } = 0;
121 | public List BlacklistedPaths { get; set; } = new();
122 | }
123 | }
124 |
--------------------------------------------------------------------------------
/JitMagic/JitMagic/Models/FileHelper.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Windows.Win32.Storage.FileSystem;
3 | using System.ComponentModel;
4 | using System.Linq;
5 | using System.IO;
6 | using Windows.Win32;
7 |
8 | namespace JitMagic.Models {
9 | static class FileHelper {
10 | ///
11 | /// Tries to read or write the file directly, if it fails due to it being a symlink and control flow guard try to work around that. if toWrite is null it reads the file and returns the data otherwise it writes toWrite to the file.
12 | ///
13 | ///
14 | ///
15 | ///
16 | ///
17 | ///
18 | ///
19 | public static unsafe string ReadWriteFile(string ConfigFile, string toWrite = null) {
20 | Func action = (string fileName) => {
21 | if (toWrite == null)
22 | return File.ReadAllText(fileName);
23 | File.WriteAllText(fileName, toWrite);
24 | return null;
25 | };
26 |
27 | try {
28 | return action(ConfigFile);
29 | } catch (IOException) { //This is to try and work around an issue where for actual exceptions (vs debugger.breaks) RedirectionGuard is enabled and it prevents us from reading the config if it is a symlink. This is the only way to read it that I have found.
30 | var fileName = GetSymLink(ConfigFile, RELATIVE_LINK_MODE.Resolve);
31 | if (File.Exists(fileName))
32 | return action(fileName);
33 | throw new Exception("Config file not found");
34 |
35 | }
36 | }
37 | public enum RELATIVE_LINK_MODE { Disallow, Preserve, Resolve }
38 | private const string WIN32_NAMESPACE_PREFIX = @"\??\";
39 | private const string UNC_PREFIX = @"UNC\";
40 | ///
41 | /// Manually resolve a file to its target, needed, for example, if GetFinalPathNameByHandle cannot be called due to RedirectionGuard preventing it in certain security contexts
42 | ///
43 | /// file to resolve to path
44 | /// What to do with relative sym links (ie ../test.txt)
45 | /// Allow junctions that resolve to \??\Volume{«guid»}\....
46 | ///
47 | ///
48 | ///
49 | public static unsafe string GetSymLink(string file, RELATIVE_LINK_MODE rel_mode = RELATIVE_LINK_MODE.Disallow, bool AllowVolumeMountpoints = false) {
50 | using var handle = PInvoke.CreateFile(file, default, default, null, FILE_CREATION_DISPOSITION.OPEN_EXISTING, FILE_FLAGS_AND_ATTRIBUTES.FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAGS_AND_ATTRIBUTES.FILE_FLAG_OPEN_REPARSE_POINT, default);
51 | if (handle.IsInvalid)
52 | throw new Win32Exception();
53 |
54 | Span buffer = new sbyte[PInvoke.MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
55 |
56 | fixed (sbyte* ptr = buffer) {
57 | ref var itm = ref *(Windows.Wdk.Storage.FileSystem.REPARSE_DATA_BUFFER*)ptr;
58 |
59 |
60 | uint bytes;
61 | if (!PInvoke.DeviceIoControl(handle, PInvoke.FSCTL_GET_REPARSE_POINT, null, 0, ptr, (uint)buffer.Length, &bytes, null))
62 | throw new Win32Exception();
63 | Span returnPath = null;
64 |
65 | static Span ParsePathBuffer(ref VariableLengthInlineArray buffer, int nameOffsetInBytes, int lengthInBytes, out bool WasPrefixed) {
66 | var ret = buffer.AsSpan((nameOffsetInBytes + lengthInBytes) / sizeof(char)).Slice(nameOffsetInBytes / sizeof(char));
67 | WasPrefixed = ret.Length >= WIN32_NAMESPACE_PREFIX.Length && ret.StartsWith(WIN32_NAMESPACE_PREFIX.ToArray());
68 | if (WasPrefixed)
69 | ret = ret.Slice(WIN32_NAMESPACE_PREFIX.Length);
70 | return ret;
71 | }
72 |
73 | if (itm.ReparseTag == PInvoke.IO_REPARSE_TAG_SYMLINK) {
74 |
75 | ref var reparse = ref itm.Anonymous.SymbolicLinkReparseBuffer;
76 | returnPath = ParsePathBuffer(ref reparse.PathBuffer, reparse.SubstituteNameOffset, reparse.SubstituteNameLength, out var wasWin32NamespacePrefixed);
77 |
78 | var shouldBeRelativeLink = (reparse.Flags & Windows.Wdk.PInvoke.SYMLINK_FLAG_RELATIVE) != 0;
79 | if (returnPath.Length == 0 || (!wasWin32NamespacePrefixed && !shouldBeRelativeLink))
80 | throw new IOException("Invalid symlink read");
81 | else if (shouldBeRelativeLink) { //this should be a relative link as was not prefixed
82 | if (rel_mode == RELATIVE_LINK_MODE.Disallow)
83 | throw new IOException($"Relative symlink found of: {returnPath.ToString()} but relative links disabled");
84 | else if (rel_mode == RELATIVE_LINK_MODE.Resolve)
85 | return Path.Combine(new FileInfo(file).DirectoryName, returnPath.ToString());
86 | //netcore only: return Path.GetFullPath(returnPath.ToString(), new FileInfo(file).DirectoryName);
87 | }
88 | } else if (itm.ReparseTag == PInvoke.IO_REPARSE_TAG_MOUNT_POINT) {
89 | ref var reparse = ref itm.Anonymous.MountPointReparseBuffer;
90 | returnPath = ParsePathBuffer(ref reparse.PathBuffer, reparse.SubstituteNameOffset, reparse.SubstituteNameLength, out var wasWin32NamespacePrefixed);
91 | if (!wasWin32NamespacePrefixed)
92 | throw new IOException("Invalid junction read");
93 | if (!AllowVolumeMountpoints && (!IsAsciiLetter(returnPath[0]) || returnPath[1] != ':'))
94 | throw new IOException("File is a junction to a volume mount point and that is disabled");
95 | }
96 |
97 | return returnPath.ToString();
98 | }
99 | }
100 | static bool IsAsciiLetter(char c) => (uint)((c | 0x20) - 'a') <= 'z' - 'a';
101 | }
102 | }
103 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # JitMagic
2 |
3 | JitMagic is a tool that allows you to have multiple Just-In-Time debuggers at once. It is able to also pass JIT operations off to other JIT debuggers like Visual Studio's JIT choice form. There should not be any functionality loss with a debugger by switching to JitMagic (full AeDebug featureset and eventing supported).
4 |
5 | 
6 |
7 | [](https://github.com/mrexodia/JitMagic/actions/workflows/continuous.yml?query=branch%3Amaster)
8 |
9 |
10 | - [Features](#features)
11 | - [Installation](#installation)
12 | - [Configuration](#configuration)
13 | - [Debugger Configuration Structure](#debugger-configuration-structure)
14 | - [Removal](#removal)
15 | - [For Debugger Developers](#for-debugger-developers)
16 | - [Adding your debugger to JitMagic](#adding-your-debugger-to-jitmagic)
17 | - [How your debugger should behave](#how-your-debugger-should-behave)
18 | - [Technical details](#technical-details)
19 |
20 |
21 |
22 | ## Features
23 | - Support an unlimited list of user customizable debuggers
24 | - Debuggers can be architecture specific (x86,x64, or both) in terms of what apps they can debug (and will only be offered when appropriate)
25 | - Pass through JIT event signaling for same-as-native JIT operations (no function loss using JitMagic)
26 | - Optional delay assistance for debugger applications that may not fully support normal JIT debugging
27 |
28 | ## Installation
29 |
30 | Run JitMagic.exe it will check if it is the registered debugger and if not it will prompt to update the system JIT debugger it itself. It will backup the existing debugger.
31 |
32 | ## Configuration
33 |
34 | JitMagic configuration is stored in the `JitMagic.json` file that is found next to the executable. If it does not exist it is created on first run. Some of the configuration features are exposed in the UI but most must be manually configured in the JSON file. It comes pre-populated with some standard debuggers, but it expects them at their normal locations. If they are not found they will not show up in the list. To specify your own or update the paths for any pre-populated ones just edit the JSON file with a text editor (or using an online editor like [https://jsoneditoronline.org/]). Some features like blacklisting specific applications may be possible to add to the config using the UI but only possible to remove by editing the JSON file.
35 |
36 | ### Debugger Configuration Structure
37 | A json entry for a debugger looks like:
38 | ```json
39 | {
40 | "Name": "dnSpy",
41 | "Architecture": "x64",
42 | "FileName": "c:\\Program Files\\dnSpy\\dnSpy.exe",
43 | "Arguments": "--dont-load-files --multiple -p {pid} -e {debugSignalFd} --jdinfo {jitDebugInfoPtr}",
44 | "IconOverridePath": "c:\\windows\\System32\\SHELL32.dll,5",
45 | "AdditionalDelaySecs": 0
46 | }
47 | ```
48 | Most fields are self explanatory.
49 | - `IconOverridePath` is the path to a .ico file or a path to an exe/dll to extract the icon from. For an exe/dll you can optionally specify the index into the file (the `,5` above) for which icon other than the default to select.
50 | - `AdditionalDelaySecs` seconds before JitMagic would normally exit that it will wait (when it exits it also signals the system to resume the process). This can be useful for debuggers that signal to a parent process and need time to attach but do not support the debug event signaler.
51 |
52 |
53 | ## Removal
54 | Run `JitMigic.exe --unregister` or launch JitMigic without any command line args and select "Remove as JIT". JitMagic will restore the system debugger to the one that existed when it was installed (or nothing if there wasn't one).
55 |
56 | ## For Debugger Developers
57 | ### Adding your debugger to JitMagic
58 |
59 | Do you have a debugger you want JitMagic to offer? Great. For the most part if your app can already be used as a native AeDebug app it should work seamlessly with JitMagic. If your app does not support AeDebug style debugging already see [How your debugger should behave](#how-your-debugger-should-behave) below for details on how it may still work. The recommend way of registering yourself with JitMagic is to check the AeDebug Debugger key `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug\Debugger` if it contains JitMagic.exe offer your users the option to add the debugger to JitMagic.
60 |
61 | If they want to proceed take the executable path for JitMagic.exe (from the Debugger registry key you can extract its path similar to
62 | ```csharp
63 | string debuggerVal = AeDebugReg.GetValue("Debugger");
64 | string JitMagicPath = debuggerVal.substring(0,debuggerVal.indexOf("JitMagic.exe")).replace("\"","");
65 | ```
66 | and run it with the following command line options:
67 |
68 | `JigMagic.exe --add-debugger "[DebuggerName]" "[DebuggerPath]" "[DebuggerArgs]" [x86|x64|All] [AdditionalDelaySecs(optional)]`
69 |
70 | for example:
71 |
72 | `JigMagic.exe --add-debugger "MyDebugger (x64)" "c:/WinDbg/MyDebugger.exe" "--pid {pid} --event {debugSignalFd} --jitPtr 0x{jitDebugInfoPtr}" x64 3`
73 |
74 | Names should be unique. If your debugger is different for x86 vs x64 just add the architecture to the name. If a debugger entry already exists with that name it is updated with the options passed. It is possible to edit the JSON file directly but that is not recommended as the format may change.
75 |
76 | ### How your debugger should behave
77 | There is nothing special JitMagic requires for debuggers but below are some general notes for how WIndows automatic debuggers should work.
78 |
79 | Like native automatic debugging there are 3 parameters JitMagic can pass to your application that you can use in your arg string:
80 | - The process pid of the target to debug `{0}` or `{pid}`
81 | - The file descriptor that points to the event handle you should use to signal when you are ready for the process to resume `{1}` or `{debugSignalFd}`
82 | - The pointer address to the JIT_DEBUG_INFO in the in the target’s address space `{2}` or `{jitDebugInfoPtr}`
83 |
84 | You can use [SetEvent](https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-setevent) to signal the event handle. Note you are signalling JitMagic not the original event, we then signal the original event shortly before we exit after getting your signal. If your app exits we will automatically signal this event even if you have not told us to do so. To assist apps that do not want (or cannot) use the event signal we support an optional "AdditionalDelaySecs" variable for each debugger in which we will defer signalling for X seconds after your app exits. This may be particularly useful if you have a singleton instance of your app running and the instance of the app the debugger launches exits after telling the main instance what to debug (and you don't want to manually have it signal). There is generally no downside to delaying the signal except for the longer delay for the user before the app resumes. If you signal too quickly or exit before fully attached the app may resume before you are ready for it to do so.
85 |
86 | Technically JitMagic.exe will work with normal AeDebug arg strings too so instead of `-p {pid} -e {debugSignalFd} -j 0x{jitDebugInfoPtr}` you can use a normal registry string like `-p %ld -e %ld -j 0x%p` but we are not using printf (just the c# string.format) so you cannot change the formatters away from `%ld` / `%p` it is simply offered as a convenience.
87 |
88 | ### Technical details
89 |
90 | By default JitMagic.exe registers itself as the automated debugger for the system. This follows standard Microsoft practices, see [Configuring Automatic Debugging](https://docs.microsoft.com/en-us/windows/desktop/debug/configuring-automatic-debugging) for more details. You should not need to manually launch JitMagic to start debugging, but if you wanted to it expects to be called in the form of `JitMagic.exe -p %ld -e %ld -j %p` where those are the standard AeDebug parameters. You can suppress the JitMagic.exe prompt to be registered as a system debugger with the variable in the JSON file.
91 |
92 |
--------------------------------------------------------------------------------
/JitTest/JitTest/JitTest.vcxproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | asInvoker
6 | Win32
7 |
8 |
9 | asInvoker
10 | x64
11 |
12 |
13 | requireAdministrator
14 | Win32
15 |
16 |
17 | requireAdministrator
18 | x64
19 |
20 |
21 |
22 | 15.0
23 | {A63276BB-9346-475E-A332-74700C9F73EE}
24 | JitTest
25 | 7.0
26 |
27 |
28 |
29 | Application
30 | false
31 | v140_xp
32 | true
33 | MultiByte
34 |
35 |
36 | Application
37 | false
38 | v140_xp
39 | true
40 | MultiByte
41 |
42 |
43 | Application
44 | false
45 | v140_xp
46 | true
47 | MultiByte
48 |
49 |
50 | Application
51 | false
52 | v140_xp
53 | true
54 | MultiByte
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 | Level3
78 | MaxSpeed
79 | true
80 | true
81 | true
82 | true
83 | MultiThreaded
84 |
85 |
86 | true
87 | true
88 | Console
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 | Level3
98 | MaxSpeed
99 | true
100 | true
101 | true
102 | true
103 | MultiThreaded
104 |
105 |
106 | true
107 | true
108 | Console
109 | RequireAdministrator
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 | Level3
119 | MaxSpeed
120 | true
121 | true
122 | true
123 | true
124 | MultiThreaded
125 |
126 |
127 | true
128 | true
129 | Console
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 | Level3
139 | MaxSpeed
140 | true
141 | true
142 | true
143 | true
144 | MultiThreaded
145 |
146 |
147 | true
148 | true
149 | Console
150 | RequireAdministrator
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 |
--------------------------------------------------------------------------------
/JitMagic/JitMagic/ViewModels/JITSelectorViewModel.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Collections.ObjectModel;
4 | using System.Diagnostics;
5 | using System.Diagnostics.Eventing.Reader;
6 | using System.Drawing;
7 | using System.IO;
8 | using System.Linq;
9 | using System.Reflection;
10 | using System.Text;
11 | using System.Threading.Tasks;
12 | using System.Windows;
13 | #if ! IS_WPF
14 | using System.Windows.Forms;
15 | #endif
16 | using JitMagic.Models;
17 | using JitMagic.MVVMLibLite;
18 | using Newtonsoft.Json;
19 | using Newtonsoft.Json.Converters;
20 |
21 |
22 | namespace JitMagic.ViewModels {
23 |
24 | public class JITSelectorViewModel : OurViewModelBase {
25 |
26 | public string WindowTitle {
27 | get => _WindowTitle;
28 | set => Set(ref _WindowTitle, value);
29 | }
30 | private string _WindowTitle = "JIT Magic";
31 | #if IS_WPF
32 | public GridLength LeftCommandColWidth {
33 | get => _LeftCommandColWidth;
34 | set => Set(ref _LeftCommandColWidth, value);
35 | }
36 | private GridLength _LeftCommandColWidth = new GridLength(1, GridUnitType.Star);
37 | #endif
38 |
39 | private ConfigManager config = new();
40 | private AEDebugManager aeDebug = new();
41 | private CLIManager cli;
42 | public JITSelectorViewModel() {
43 | var args = Environment.GetCommandLineArgs();
44 | var designMode = args.Length == 0 || (args[0].IndexOf("JitMagic.exe", StringComparison.CurrentCultureIgnoreCase) == -1 && args[0].Contains("VisualStudio"));
45 | config.ReadConfig();
46 | if (!designMode)
47 | cli = new(config, aeDebug, args.Skip(1).ToArray());
48 |
49 |
50 | if (config.Config.OverrideWidth > 100)
51 | WinWidth = config.Config.OverrideWidth;
52 | if (config.Config.OverrideHeight > 100)
53 | WinHeight = config.Config.OverrideHeight;
54 |
55 | IgnoreForMinutes = config.Config.DefaultIgnoreMinutes;
56 | }
57 | public bool TopMost {
58 | get => _TopMost;
59 | set => Set(ref _TopMost, value);
60 | }
61 | private bool _TopMost;
62 | public void Loaded() {
63 | if (cli != null && !new[] { APP_ACTION.None, APP_ACTION.AEDebug, APP_ACTION.Screenshot }.Contains(cli.mode))
64 | Close();
65 |
66 | var fallback = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);
67 | if (cli.mode == APP_ACTION.AEDebug) {
68 | TopMost = !Debugger.IsAttached;
69 | WindowTitle += $" - PID: {cli.target.Pid}";
70 | pid = cli.target.Pid;
71 | processPath = cli.target.ProcPath;
72 | ProcessInfo = $"{Path.GetFileName(processPath)} ({cli.target.Architecture})";
73 | #if IS_WPF
74 |
75 | StandardLaunchOnlyVisibility = Visibility.Collapsed;
76 | } else if (cli.mode == APP_ACTION.Screenshot){
77 | AEDebugOnlyVisibility = Visibility.Collapsed;
78 | WindowTitle += $" - PID: 4";
79 | ProcessInfo = $"lsass.exe (x86)";
80 | } else {
81 | LeftCommandColWidth = new GridLength( 0);
82 | AEDebugOnlyVisibility = Visibility.Collapsed;
83 | AttachText = "Launch";
84 | #endif
85 | }
86 |
87 | foreach (var debugger in config.Config.JitDebuggers) {
88 | if ((cli.mode == APP_ACTION.AEDebug && debugger.Architecture.HasFlag(cli.target.Architecture) == false) || !debugger.Exists)
89 | continue;
90 | debugger.LoadIcon(fallback);
91 | debuggers.Add(debugger);
92 | }
93 | selected_debugger = debuggers.FirstOrDefault();
94 | }
95 | public OurCommand LaunchNormalCmd => GetOurCmdSync(LaunchNormal);
96 | public void LaunchNormal() {
97 | TopMost = false;
98 | ProcHelper.LaunchUs(false);
99 | }
100 |
101 | public int pid {
102 | get => _pid;
103 | set => Set(ref _pid, value);
104 | }
105 | private int _pid;
106 |
107 | public string ProcessInfo {
108 | get => _ProcessInfo;
109 | set => Set(ref _ProcessInfo, value);
110 | }
111 | private string _ProcessInfo = "No Process Loaded";
112 |
113 |
114 | public OurCommand IgnoreAllCmd => GetOurCmdSync(IgnoreAll);
115 | public void IgnoreAll() {
116 | config.Config.IgnoringUntil = DateTime.Now.AddMinutes(IgnoreForMinutes);
117 | config.SaveConfig();
118 | Close();
119 | }
120 |
121 |
122 | public int WinHeight {
123 | get => _WinHeight;
124 | set => Set(ref _WinHeight, value);
125 | }
126 | private int _WinHeight = 210;
127 |
128 | public int WinWidth {
129 | get => _WinWidth;
130 | set => Set(ref _WinWidth, value);
131 | }
132 | private int _WinWidth = 1000;
133 |
134 | public void Close() {
135 | aeDebug.SignalResume();
136 | CloseWin?.Invoke(this, null);
137 | }
138 | public event EventHandler CloseWin;
139 | public event EventHandler HideWin;
140 |
141 | public int IgnoreForMinutes {
142 | get => _IgnoreForMinutes;
143 | set => Set(ref _IgnoreForMinutes, value);
144 | }
145 | private int _IgnoreForMinutes;
146 |
147 | public OurCommand SaveWindowSizeCmd => GetOurCmdSync(SaveWindowSize);
148 | public void SaveWindowSize() {
149 |
150 | config.Config.OverrideWidth = WinWidth;
151 | config.Config.OverrideHeight = WinHeight;
152 | config.SaveConfig();
153 | }
154 | public OurCommand AttachCmd => GetOurCmd(Attach);
155 | public async Task Attach() {
156 | var debugger = selected_debugger;
157 | if (debugger == null)
158 | return;
159 | if (pid != 0)
160 | HideWin?.Invoke(this, null);
161 | await Task.Delay(10);
162 | aeDebug.StartDebugger(debugger, pid, cli.target?.JitDebugStructPtrAddy);
163 | if (pid != 0)
164 | DelayClose(debugger.AdditionalDelaySecs);
165 | }
166 | private async void DelayClose(int extraDelaySecs) {
167 | if (extraDelaySecs > 0)
168 | await Task.Delay(TimeSpan.FromSeconds(extraDelaySecs));
169 | Close();
170 | }
171 |
172 | public OurCommand BlacklistAppCmd => GetOurCmdSync(BlacklistApp);
173 | public void BlacklistApp() {
174 | #if IS_WPF
175 | var confirm = MessageBox.Show($"Are you sure you want to blacklist the executable path: {processPath} from future debugging? The only way to undo this is to manually edit the JitMagic.json file", $"Confirm Blacklist {Path.GetFileName(processPath)}", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No);
176 | if (confirm != MessageBoxResult.Yes)
177 | return;
178 | #else
179 | var confirm = MessageBox.Show($"Are you sure you want to blacklist the executable path: {processPath} from future debugging? The only way to undo this is to manually edit the JitMagic.json file", $"Confirm Blacklist {Path.GetFileName(processPath)}", MessageBoxButtons.YesNo, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button2);
180 | if (confirm != DialogResult.Yes)
181 | return;
182 | #endif
183 | config.Config.BlacklistedPaths.Add(processPath);
184 | config.SaveConfig();
185 | Close();
186 | }
187 |
188 | public string processPath {
189 | get => _processPath;
190 | set => Set(ref _processPath, value);
191 | }
192 | private string _processPath;
193 |
194 |
195 | public string AttachText {
196 | get => _AttachText;
197 | set => Set(ref _AttachText, value);
198 | }
199 | private string _AttachText = "Attach";
200 | #if IS_WPF
201 |
202 | public Visibility AEDebugOnlyVisibility {
203 | get => _AEDebugOnlyVisibility;
204 | set => Set(ref _AEDebugOnlyVisibility, value);
205 | }
206 | private Visibility _AEDebugOnlyVisibility = Visibility.Visible;
207 |
208 |
209 | public Visibility StandardLaunchOnlyVisibility {
210 | get => _StandardLaunchOnlyVisibility;
211 | set => Set(ref _StandardLaunchOnlyVisibility, value);
212 | }
213 | private Visibility _StandardLaunchOnlyVisibility = Visibility.Visible;
214 | #endif
215 |
216 | public OurCommand RemoveAsJITCmd => GetOurCmdSync(RemoveAsJIT);
217 | public void RemoveAsJIT() {
218 | aeDebug.UpdateRegistration(APP_ACTION.Unregister);
219 | }
220 |
221 | public OurCommand DebuggerDoubleClickedCmd => GetOurCmd(DebuggerDoubleClicked);
222 | public async Task DebuggerDoubleClicked() {
223 | await Task.Delay(10);//make sure it has time to updated selected
224 | await AttachCmd.Execute();
225 | }
226 | public OurCommand RemoveSelectedDebuggerCmd => GetOurCmdSync(RemoveSelectedDebugger);
227 | public void RemoveSelectedDebugger() {
228 | if (selected_debugger == null)
229 | return;
230 | config.RemoveDebugger(selected_debugger.Name);
231 | debuggers.Remove(selected_debugger);
232 | selected_debugger = debuggers.FirstOrDefault();
233 | }
234 |
235 | public JitDebugger selected_debugger {
236 | get => _selected_debugger;
237 | set => Set(ref _selected_debugger, value);
238 | }
239 | private JitDebugger _selected_debugger;
240 |
241 |
242 | public ObservableCollection debuggers {
243 | get => _debuggers;
244 | set => Set(ref _debuggers, value);
245 | }
246 | private ObservableCollection _debuggers = new();
247 |
248 | public void test() {
249 | var ico = Icon.ExtractAssociatedIcon("test");
250 |
251 | }
252 |
253 | }
254 | }
255 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 2, June 1991
3 |
4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6 | Everyone is permitted to copy and distribute verbatim copies
7 | of this license document, but changing it is not allowed.
8 |
9 | Preamble
10 |
11 | The licenses for most software are designed to take away your
12 | freedom to share and change it. By contrast, the GNU General Public
13 | License is intended to guarantee your freedom to share and change free
14 | software--to make sure the software is free for all its users. This
15 | General Public License applies to most of the Free Software
16 | Foundation's software and to any other program whose authors commit to
17 | using it. (Some other Free Software Foundation software is covered by
18 | the GNU Lesser General Public License instead.) You can apply it to
19 | your programs, too.
20 |
21 | When we speak of free software, we are referring to freedom, not
22 | price. Our General Public Licenses are designed to make sure that you
23 | have the freedom to distribute copies of free software (and charge for
24 | this service if you wish), that you receive source code or can get it
25 | if you want it, that you can change the software or use pieces of it
26 | in new free programs; and that you know you can do these things.
27 |
28 | To protect your rights, we need to make restrictions that forbid
29 | anyone to deny you these rights or to ask you to surrender the rights.
30 | These restrictions translate to certain responsibilities for you if you
31 | distribute copies of the software, or if you modify it.
32 |
33 | For example, if you distribute copies of such a program, whether
34 | gratis or for a fee, you must give the recipients all the rights that
35 | you have. You must make sure that they, too, receive or can get the
36 | source code. And you must show them these terms so they know their
37 | rights.
38 |
39 | We protect your rights with two steps: (1) copyright the software, and
40 | (2) offer you this license which gives you legal permission to copy,
41 | distribute and/or modify the software.
42 |
43 | Also, for each author's protection and ours, we want to make certain
44 | that everyone understands that there is no warranty for this free
45 | software. If the software is modified by someone else and passed on, we
46 | want its recipients to know that what they have is not the original, so
47 | that any problems introduced by others will not reflect on the original
48 | authors' reputations.
49 |
50 | Finally, any free program is threatened constantly by software
51 | patents. We wish to avoid the danger that redistributors of a free
52 | program will individually obtain patent licenses, in effect making the
53 | program proprietary. To prevent this, we have made it clear that any
54 | patent must be licensed for everyone's free use or not licensed at all.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | GNU GENERAL PUBLIC LICENSE
60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61 |
62 | 0. This License applies to any program or other work which contains
63 | a notice placed by the copyright holder saying it may be distributed
64 | under the terms of this General Public License. The "Program", below,
65 | refers to any such program or work, and a "work based on the Program"
66 | means either the Program or any derivative work under copyright law:
67 | that is to say, a work containing the Program or a portion of it,
68 | either verbatim or with modifications and/or translated into another
69 | language. (Hereinafter, translation is included without limitation in
70 | the term "modification".) Each licensee is addressed as "you".
71 |
72 | Activities other than copying, distribution and modification are not
73 | covered by this License; they are outside its scope. The act of
74 | running the Program is not restricted, and the output from the Program
75 | is covered only if its contents constitute a work based on the
76 | Program (independent of having been made by running the Program).
77 | Whether that is true depends on what the Program does.
78 |
79 | 1. You may copy and distribute verbatim copies of the Program's
80 | source code as you receive it, in any medium, provided that you
81 | conspicuously and appropriately publish on each copy an appropriate
82 | copyright notice and disclaimer of warranty; keep intact all the
83 | notices that refer to this License and to the absence of any warranty;
84 | and give any other recipients of the Program a copy of this License
85 | along with the Program.
86 |
87 | You may charge a fee for the physical act of transferring a copy, and
88 | you may at your option offer warranty protection in exchange for a fee.
89 |
90 | 2. You may modify your copy or copies of the Program or any portion
91 | of it, thus forming a work based on the Program, and copy and
92 | distribute such modifications or work under the terms of Section 1
93 | above, provided that you also meet all of these conditions:
94 |
95 | a) You must cause the modified files to carry prominent notices
96 | stating that you changed the files and the date of any change.
97 |
98 | b) You must cause any work that you distribute or publish, that in
99 | whole or in part contains or is derived from the Program or any
100 | part thereof, to be licensed as a whole at no charge to all third
101 | parties under the terms of this License.
102 |
103 | c) If the modified program normally reads commands interactively
104 | when run, you must cause it, when started running for such
105 | interactive use in the most ordinary way, to print or display an
106 | announcement including an appropriate copyright notice and a
107 | notice that there is no warranty (or else, saying that you provide
108 | a warranty) and that users may redistribute the program under
109 | these conditions, and telling the user how to view a copy of this
110 | License. (Exception: if the Program itself is interactive but
111 | does not normally print such an announcement, your work based on
112 | the Program is not required to print an announcement.)
113 |
114 | These requirements apply to the modified work as a whole. If
115 | identifiable sections of that work are not derived from the Program,
116 | and can be reasonably considered independent and separate works in
117 | themselves, then this License, and its terms, do not apply to those
118 | sections when you distribute them as separate works. But when you
119 | distribute the same sections as part of a whole which is a work based
120 | on the Program, the distribution of the whole must be on the terms of
121 | this License, whose permissions for other licensees extend to the
122 | entire whole, and thus to each and every part regardless of who wrote it.
123 |
124 | Thus, it is not the intent of this section to claim rights or contest
125 | your rights to work written entirely by you; rather, the intent is to
126 | exercise the right to control the distribution of derivative or
127 | collective works based on the Program.
128 |
129 | In addition, mere aggregation of another work not based on the Program
130 | with the Program (or with a work based on the Program) on a volume of
131 | a storage or distribution medium does not bring the other work under
132 | the scope of this License.
133 |
134 | 3. You may copy and distribute the Program (or a work based on it,
135 | under Section 2) in object code or executable form under the terms of
136 | Sections 1 and 2 above provided that you also do one of the following:
137 |
138 | a) Accompany it with the complete corresponding machine-readable
139 | source code, which must be distributed under the terms of Sections
140 | 1 and 2 above on a medium customarily used for software interchange; or,
141 |
142 | b) Accompany it with a written offer, valid for at least three
143 | years, to give any third party, for a charge no more than your
144 | cost of physically performing source distribution, a complete
145 | machine-readable copy of the corresponding source code, to be
146 | distributed under the terms of Sections 1 and 2 above on a medium
147 | customarily used for software interchange; or,
148 |
149 | c) Accompany it with the information you received as to the offer
150 | to distribute corresponding source code. (This alternative is
151 | allowed only for noncommercial distribution and only if you
152 | received the program in object code or executable form with such
153 | an offer, in accord with Subsection b above.)
154 |
155 | The source code for a work means the preferred form of the work for
156 | making modifications to it. For an executable work, complete source
157 | code means all the source code for all modules it contains, plus any
158 | associated interface definition files, plus the scripts used to
159 | control compilation and installation of the executable. However, as a
160 | special exception, the source code distributed need not include
161 | anything that is normally distributed (in either source or binary
162 | form) with the major components (compiler, kernel, and so on) of the
163 | operating system on which the executable runs, unless that component
164 | itself accompanies the executable.
165 |
166 | If distribution of executable or object code is made by offering
167 | access to copy from a designated place, then offering equivalent
168 | access to copy the source code from the same place counts as
169 | distribution of the source code, even though third parties are not
170 | compelled to copy the source along with the object code.
171 |
172 | 4. You may not copy, modify, sublicense, or distribute the Program
173 | except as expressly provided under this License. Any attempt
174 | otherwise to copy, modify, sublicense or distribute the Program is
175 | void, and will automatically terminate your rights under this License.
176 | However, parties who have received copies, or rights, from you under
177 | this License will not have their licenses terminated so long as such
178 | parties remain in full compliance.
179 |
180 | 5. You are not required to accept this License, since you have not
181 | signed it. However, nothing else grants you permission to modify or
182 | distribute the Program or its derivative works. These actions are
183 | prohibited by law if you do not accept this License. Therefore, by
184 | modifying or distributing the Program (or any work based on the
185 | Program), you indicate your acceptance of this License to do so, and
186 | all its terms and conditions for copying, distributing or modifying
187 | the Program or works based on it.
188 |
189 | 6. Each time you redistribute the Program (or any work based on the
190 | Program), the recipient automatically receives a license from the
191 | original licensor to copy, distribute or modify the Program subject to
192 | these terms and conditions. You may not impose any further
193 | restrictions on the recipients' exercise of the rights granted herein.
194 | You are not responsible for enforcing compliance by third parties to
195 | this License.
196 |
197 | 7. If, as a consequence of a court judgment or allegation of patent
198 | infringement or for any other reason (not limited to patent issues),
199 | conditions are imposed on you (whether by court order, agreement or
200 | otherwise) that contradict the conditions of this License, they do not
201 | excuse you from the conditions of this License. If you cannot
202 | distribute so as to satisfy simultaneously your obligations under this
203 | License and any other pertinent obligations, then as a consequence you
204 | may not distribute the Program at all. For example, if a patent
205 | license would not permit royalty-free redistribution of the Program by
206 | all those who receive copies directly or indirectly through you, then
207 | the only way you could satisfy both it and this License would be to
208 | refrain entirely from distribution of the Program.
209 |
210 | If any portion of this section is held invalid or unenforceable under
211 | any particular circumstance, the balance of the section is intended to
212 | apply and the section as a whole is intended to apply in other
213 | circumstances.
214 |
215 | It is not the purpose of this section to induce you to infringe any
216 | patents or other property right claims or to contest validity of any
217 | such claims; this section has the sole purpose of protecting the
218 | integrity of the free software distribution system, which is
219 | implemented by public license practices. Many people have made
220 | generous contributions to the wide range of software distributed
221 | through that system in reliance on consistent application of that
222 | system; it is up to the author/donor to decide if he or she is willing
223 | to distribute software through any other system and a licensee cannot
224 | impose that choice.
225 |
226 | This section is intended to make thoroughly clear what is believed to
227 | be a consequence of the rest of this License.
228 |
229 | 8. If the distribution and/or use of the Program is restricted in
230 | certain countries either by patents or by copyrighted interfaces, the
231 | original copyright holder who places the Program under this License
232 | may add an explicit geographical distribution limitation excluding
233 | those countries, so that distribution is permitted only in or among
234 | countries not thus excluded. In such case, this License incorporates
235 | the limitation as if written in the body of this License.
236 |
237 | 9. The Free Software Foundation may publish revised and/or new versions
238 | of the General Public License from time to time. Such new versions will
239 | be similar in spirit to the present version, but may differ in detail to
240 | address new problems or concerns.
241 |
242 | Each version is given a distinguishing version number. If the Program
243 | specifies a version number of this License which applies to it and "any
244 | later version", you have the option of following the terms and conditions
245 | either of that version or of any later version published by the Free
246 | Software Foundation. If the Program does not specify a version number of
247 | this License, you may choose any version ever published by the Free Software
248 | Foundation.
249 |
250 | 10. If you wish to incorporate parts of the Program into other free
251 | programs whose distribution conditions are different, write to the author
252 | to ask for permission. For software which is copyrighted by the Free
253 | Software Foundation, write to the Free Software Foundation; we sometimes
254 | make exceptions for this. Our decision will be guided by the two goals
255 | of preserving the free status of all derivatives of our free software and
256 | of promoting the sharing and reuse of software generally.
257 |
258 | NO WARRANTY
259 |
260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268 | REPAIR OR CORRECTION.
269 |
270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278 | POSSIBILITY OF SUCH DAMAGES.
279 |
280 | END OF TERMS AND CONDITIONS
281 |
282 | How to Apply These Terms to Your New Programs
283 |
284 | If you develop a new program, and you want it to be of the greatest
285 | possible use to the public, the best way to achieve this is to make it
286 | free software which everyone can redistribute and change under these terms.
287 |
288 | To do so, attach the following notices to the program. It is safest
289 | to attach them to the start of each source file to most effectively
290 | convey the exclusion of warranty; and each file should have at least
291 | the "copyright" line and a pointer to where the full notice is found.
292 |
293 |
294 | Copyright (C)
295 |
296 | This program is free software; you can redistribute it and/or modify
297 | it under the terms of the GNU General Public License as published by
298 | the Free Software Foundation; either version 2 of the License, or
299 | (at your option) any later version.
300 |
301 | This program is distributed in the hope that it will be useful,
302 | but WITHOUT ANY WARRANTY; without even the implied warranty of
303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304 | GNU General Public License for more details.
305 |
306 | You should have received a copy of the GNU General Public License along
307 | with this program; if not, write to the Free Software Foundation, Inc.,
308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309 |
310 | Also add information on how to contact you by electronic and paper mail.
311 |
312 | If the program is interactive, make it output a short notice like this
313 | when it starts in an interactive mode:
314 |
315 | Gnomovision version 69, Copyright (C) year name of author
316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317 | This is free software, and you are welcome to redistribute it
318 | under certain conditions; type `show c' for details.
319 |
320 | The hypothetical commands `show w' and `show c' should show the appropriate
321 | parts of the General Public License. Of course, the commands you use may
322 | be called something other than `show w' and `show c'; they could even be
323 | mouse-clicks or menu items--whatever suits your program.
324 |
325 | You should also get your employer (if you work as a programmer) or your
326 | school, if any, to sign a "copyright disclaimer" for the program, if
327 | necessary. Here is a sample; alter the names:
328 |
329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330 | `Gnomovision' (which makes passes at compilers) written by James Hacker.
331 |
332 | , 1 April 1989
333 | Ty Coon, President of Vice
334 |
335 | This General Public License does not permit incorporating your program into
336 | proprietary programs. If your program is a subroutine library, you may
337 | consider it more useful to permit linking proprietary applications with the
338 | library. If this is what you want to do, use the GNU Lesser General
339 | Public License instead of this License.
340 |
--------------------------------------------------------------------------------