Skip to content

Commit

Permalink
Make metrics gathering thread safe
Browse files Browse the repository at this point in the history
  • Loading branch information
myrsloik committed May 25, 2022
1 parent 99ff41f commit 7ec12a5
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions yatta/ymc7/FunctionHooking.pas
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
interface

uses
SysUtils, Windows, Types, Classes, AnsiStrings;
SysUtils, Windows, Types, Classes, AnsiStrings, System.SyncObjs;

const
MH_OK = 0;
Expand All @@ -25,6 +25,7 @@ implementation
var
g_origOutputDebugStringA: TOutputDebugStringAFunc = nil;
g_origOutputDebugStringW: TOutputDebugStringWFunc = nil;
OutputDebugStringLock: TCriticalSection = nil;
Output: TStrings = nil;

procedure SetDbgOutput(AOutput: TStrings);
Expand All @@ -35,21 +36,31 @@ procedure SetDbgOutput(AOutput: TStrings);
procedure MyOutputDebugStringA(Str: PAnsiChar); stdcall;
begin
if Output <> nil then
Output.Append(string(Str));
begin
OutputDebugStringLock.Acquire;
Output.Append(Str);
OutputDebugStringLock.Release;
end;
g_origOutputDebugStringA(Str);
end;

procedure MyOutputDebugStringW(Str: PWideChar); stdcall;
begin
if Output <> nil then
begin
OutputDebugStringLock.Acquire;
Output.Append(Str);
OutputDebugStringLock.Release;
end;
g_origOutputDebugStringW(Str);
end;

procedure HookDbgOut(AOutput: TStrings);
var
Target: Pointer;
begin
if OutputDebugStringLock = nil then
OutputDebugStringLock := TCriticalSection.Create;
MH_Initialize;
MH_CreateHookApiEx('kernel32', 'OutputDebugStringA', @MyOutputDebugStringA, @g_origOutputDebugStringA, Target);
MH_EnableHook(Target);
Expand Down

0 comments on commit 7ec12a5

Please sign in to comment.