-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathadot.Win.Log.pas
536 lines (466 loc) · 13 KB
/
adot.Win.Log.pas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
unit adot.Win.Log;
interface
uses
Winapi.Windows,
adot.Win.Tools,
adot.Tools,
adot.Log,
adot.Strings,
System.SysUtils,
System.SyncObjs,
System.Math,
System.Classes,
System.Generics.Collections,
System.Generics.Defaults;
type
// buffered + asynchronous, thread-safe.
// most general class for logging.
TWinFileLog = class(TFileLog)
protected
procedure LogSysInfo; override;
function LogLinesPrefix: String; override;
end;
// NOT buffered, NOT asynchronous, thread-safe
// Use it only if you need to see result immediately.
TWinSyncFileLog = class(TSyncFileLog)
protected
procedure LogSysInfo; override;
function LogLinesPrefix: String; override;
end;
// buffered, NOT asynchronous, thread-safe
// Use it only if multithreading is not allowed for some reason.
TWinSyncBufFileLog = class(TSyncBufFileLog)
protected
procedure LogSysInfo; override;
function LogLinesPrefix: String; override;
end;
TWinNullLog = TNullLog;
// Makes any logger to be GetLastError-transparent (for logging from injected
// DLLs etc). Usually it will be TSysErrorTransparentLog
TSysErrorTransparentLog = class(TCustomLog)
protected
type
TCustomLogH = class(TCustomLog);
var
FLog: TCustomLogH;
FOwns: Boolean;
procedure LogSysInfo; override;
function LogLinesPrefix: String; override;
procedure Send(AData: pointer; ASize: Integer); override;
procedure DoFlush; override;
public
constructor Create(ALog: TCustomLog; AOwns: Boolean);
destructor Destroy; override;
end;
// single server, multiple clients (same machine, any process).
TSharedMemoryLog = class
public
type
// Receives data from client and sends to the actual log.
TOnNewLog = reference to function(const ALogfileName: string): TCustomLog;
TCustomLogH = class(TCustomLog);
TCmd = (cmdSend, cmdFlush, cmdClose);
PSharedMemoryLogRec = ^TSharedMemoryLogRec;
TSharedMemoryLogRec = record
// Clients should not perform any operations with closed server,
// all wait operations will never signalated. Normally clients should
// be shut down before server is closed.
ServerClosed: Boolean; // w: server
// Every server object generated uniqueue session ID.
// Named synchronization objects are based on this value
// (check EventCanReadName/EventCanWriteName).
SessionId: TGUID; // w: server
// Information to be send from client to server.
MsgCmd: TCmd;
LogNameLen: integer; // length in chars (not bytes!)
LogName: array[0..255] of Char;
MsgSize: integer; // size in bytes
MsgData: array[0..2047] of Byte;
function BaseName: string;
function EventCanReadName: string;
function EventCanWriteName: string;
procedure SetLogName(const AName: string);
function GetLogName: string;
end;
// Instead of logging it sends data to server.
TClient = class(TCustomLog)
protected
const
WaitWriteBufMs: cardinal = infinite; //3000;
var
FSharedMem: PSharedMemoryLogRec;
FEvtMsgCanRead: THandle;
FEvtMsgCanWrite: THandle;
FLogFileName: String;
FCS: TCriticalSection;
procedure Send(AData: pointer; ASize: Integer); override;
procedure DoFlush; override;
procedure SendClose;
function AquireMsgQueue: Boolean;
procedure ReleaseMsgQueue;
procedure LogSysInfo; override;
function LogLinesPrefix: String; override;
public
constructor Create(ASharedMem: PSharedMemoryLogRec; const ALogFileName: string);
destructor Destroy; override;
end;
TServer = class
protected
type
TLogThread = class(TThread)
protected
FSharedMem: PSharedMemoryLogRec;
FEvtMsgCanRead: TEvent;
FEvtMsgCanWrite: TEvent;
FLogs: TObjectDictionary<String, TCustomLog>;
FSrvStarted: TEvent;
public
constructor Create(ASharedMem: PSharedMemoryLogRec);
destructor Destroy; override;
procedure Execute; override;
end;
var
SrvLog: TLogThread;
public
constructor Create(ASharedMem: PSharedMemoryLogRec; ANewLog: TOnNewLog);
destructor Destroy; override;
end;
end;
implementation
function PCharLen(S: PChar; AMaxLen: integer): integer;
var
i: Integer;
begin
for i := 0 to AMaxLen-1 do
if S[i]=#0 then
begin
Result := i;
Exit;
end;
Result := AMaxLen;
end;
function LogLineExtraPrefix: string;
begin
result := ' ' + TStr.IntToString(GetCurrentThreadId, 9);
end;
procedure LogExtraSysInfo(ADst: TCustomLog);
begin
ADst.Add('PID='+IntToStr(GetCurrentProcessId));
ADst.Add('Ingerity level: '+TProcess.GetIntegrityLevel);
end;
{ TWinFileLog }
function TWinFileLog.LogLinesPrefix: String;
begin
result := inherited LogLinesPrefix + LogLineExtraPrefix;
end;
procedure TWinFileLog.LogSysInfo;
begin
inherited;
LogExtraSysInfo(Self);
end;
{ TWinSyncFileLog }
function TWinSyncFileLog.LogLinesPrefix: String;
begin
result := inherited LogLinesPrefix + LogLineExtraPrefix;
end;
procedure TWinSyncFileLog.LogSysInfo;
begin
inherited;
LogExtraSysInfo(Self);
end;
{ TWinSyncBufFileLog }
function TWinSyncBufFileLog.LogLinesPrefix: String;
begin
result := inherited LogLinesPrefix + LogLineExtraPrefix;
end;
procedure TWinSyncBufFileLog.LogSysInfo;
begin
inherited;
LogExtraSysInfo(Self);
end;
{ TSysErrorTransparentLog }
constructor TSysErrorTransparentLog.Create(ALog: TCustomLog; AOwns: Boolean);
begin
FLog := TCustomLogH(ALog);
FOwns := AOwns;
inherited Create;
end;
destructor TSysErrorTransparentLog.Destroy;
begin
inherited;
if FOwns then
FreeAndNil(FLog)
else
FLog := nil;
end;
procedure TSysErrorTransparentLog.DoFlush;
var
LastError: Cardinal;
begin
LastError := GetLastError;
FLog.DoFlush;
if LastError<>GetLastError then
SetLastError(LastError);
end;
function TSysErrorTransparentLog.LogLinesPrefix: String;
var
LastError: Cardinal;
begin
LastError := GetLastError;
Result := FLog.LogLinesPrefix;
if LastError<>GetLastError then
SetLastError(LastError);
end;
procedure TSysErrorTransparentLog.LogSysInfo;
var
LastError: Cardinal;
begin
if FHeaderSent then
Exit;
FHeaderSent := True;
LastError := GetLastError;
FLog.LogSysInfo;
if LastError<>GetLastError then
SetLastError(LastError);
end;
procedure TSysErrorTransparentLog.Send(AData: pointer; ASize: Integer);
var
LastError: Cardinal;
begin
LastError := GetLastError;
FLog.Send(AData, ASize);
if LastError<>GetLastError then
SetLastError(LastError);
end;
{ TSharedMemoryLog.TSharedMemoryLogRec }
function TSharedMemoryLog.TSharedMemoryLogRec.BaseName: string;
begin
result := THex.Encode(SessionId, SizeOf(SessionId));
end;
function TSharedMemoryLog.TSharedMemoryLogRec.EventCanReadName: string;
begin
Result := 'EvtRd' + BaseName;
end;
function TSharedMemoryLog.TSharedMemoryLogRec.EventCanWriteName: string;
begin
Result := 'EvtWr' + BaseName;
end;
procedure TSharedMemoryLog.TSharedMemoryLogRec.SetLogName(const AName: string);
begin
LogNameLen := Min(Length(AName), Length(LogName));
Move(AName[Low(AName)], LogName, LogNameLen*SizeOf(Char));
end;
function TSharedMemoryLog.TSharedMemoryLogRec.GetLogName: string;
begin
SetLength(Result, LogNameLen);
Move(LogName, Result[Low(Result)], LogNameLen*SizeOf(Char));
end;
{ TSharedMemoryLog.TClient }
constructor TSharedMemoryLog.TClient.Create(ASharedMem: PSharedMemoryLogRec; const ALogFileName: string);
begin
FSharedMem := ASharedMem;
FLogFileName := ALogFileName;
FEvtMsgCanRead := OpenEvent(SYNCHRONIZE or EVENT_MODIFY_STATE, False, PChar(FSharedMem.EventCanReadName));
FEvtMsgCanWrite := OpenEvent(SYNCHRONIZE or EVENT_MODIFY_STATE, False, PChar(FSharedMem.EventCanWriteName));
FCS := TCriticalSection.Create;
inherited Create;
end;
destructor TSharedMemoryLog.TClient.Destroy;
begin
if (FSharedMem<>nil) and
(FEvtMsgCanRead<>0) and
(FEvtMsgCanWrite<>0) and
(FLogFileName<>'') and
(FCS<>nil)
then
SendClose;
CloseHandle(FEvtMsgCanWrite);
CloseHandle(FEvtMsgCanRead);
FSharedMem := nil;
FReeAndNil(FCS);
inherited;
end;
function TSharedMemoryLog.TClient.AquireMsgQueue: Boolean;
const
BreakIntervalMs = 50;
var
RemainDelayMs, IntervalDelayMs: Cardinal;
begin
// Server can became unavailable any time, so we have to break waiting
// operation time to time to make sure, that server is not closed yet.
Result := False;
RemainDelayMs := WaitWriteBufMs;
IntervalDelayMs := Min(BreakIntervalMs, WaitWriteBufMs);
repeat
if FSharedMem.ServerClosed then
Exit;
Result := WaitForSingleObject(FEvtMsgCanWrite,IntervalDelayMs)=WAIT_OBJECT_0;
if Result then
Exit;
if RemainDelayMs<>INFINITE then
if RemainDelayMs<=IntervalDelayMs then
Exit
else
Dec(RemainDelayMs, IntervalDelayMs);
until False;
end;
procedure TSharedMemoryLog.TClient.ReleaseMsgQueue;
begin
// enable server to process the message
SetEvent(FEvtMsgCanRead);
end;
procedure TSharedMemoryLog.TClient.DoFlush;
begin
FCS.Enter;
try
if AquireMsgQueue then
try
FSharedMem.MsgCmd := cmdFlush;
finally
ReleaseMsgQueue;
end;
finally
FCS.Leave;
end;
end;
function TSharedMemoryLog.TClient.LogLinesPrefix: String;
begin
// AH: DLL injected into chrome.exe may fail on GetLocalTime function,
// so we should not use any API call except something really important here,
// timestamp etc can be added on the server side.
result := format('%.9d', [GetCurrentProcessId]);
end;
procedure TSharedMemoryLog.TClient.LogSysInfo;
begin
// AH: we should log here only absolutely required information.
end;
procedure TSharedMemoryLog.TClient.SendClose;
begin
FCS.Enter;
try
if AquireMsgQueue then
try
FSharedMem.MsgCmd := cmdClose;
FSharedMem.SetLogName(FLogFileName);
finally
ReleaseMsgQueue;
end;
finally
FCS.Leave;
end;
end;
procedure TSharedMemoryLog.TClient.Send(AData: pointer; ASize: Integer);
var
n: Integer;
begin
FCS.Enter;
try
while ASize>0 do
begin
n := Min(ASize, SizeOf(FSharedMem.MsgData));
if AquireMsgQueue then
try
FSharedMem.MsgCmd := cmdSend;
FSharedMem.SetLogName(FLogfileName);
Move(AData^, FSharedMem.MsgData, n);
FSharedMem.MsgSize := n;
finally
ReleaseMsgQueue;
end
else
Break;
inc(PByte(AData), n);
dec(ASize, n);
end;
finally
FCS.Leave;
end;
end;
{ TSharedMemoryLog.TServer }
constructor TSharedMemoryLog.TServer.Create(ASharedMem: PSharedMemoryLogRec;
ANewLog: TOnNewLog);
begin
SrvLog := TLogThread.Create(ASharedMem);
SrvLog.FSrvStarted.WaitFor(INFINITE);
end;
destructor TSharedMemoryLog.TServer.Destroy;
begin
FreeAndNil(SrvLog);
inherited;
end;
{ TLogThread }
constructor TSharedMemoryLog.TServer.TLogThread.Create(ASharedMem: PSharedMemoryLogRec);
var
Sec: TSecurity.TDescrAttr;
begin
FSharedMem := ASharedMem;
FSharedMem.ServerClosed := False;
CreateGUID(FSharedMem.SessionId);
TSecurity.NullDACL(Sec);
FEvtMsgCanRead := TEvent.Create(@Sec.Attrs, False, False, FSharedMem.EventCanReadName);
FEvtMsgCanWrite := TEvent.Create(@Sec.Attrs, False, True, FSharedMem.EventCanWriteName);
FLogs := TObjectDictionary<String, TCustomLog>.Create;
FSrvStarted := TEvent.Create;
inherited Create(False);
end;
destructor TSharedMemoryLog.TServer.TLogThread.Destroy;
begin
if FSharedMem<>nil then
FSharedMem.ServerClosed := True;
Terminate;
if FEvtMsgCanRead<>nil then
FEvtMsgCanRead.SetEvent;
inherited;
FreeAndNil(FLogs);
FreeAndNil(FEvtMsgCanWrite);
FreeAndNil(FEvtMsgCanRead);
FSharedMem := nil;
FReeAndNil(FSrvStarted);
end;
procedure TSharedMemoryLog.TServer.TLogThread.Execute;
function GetLog(const AName: string): TCustomLog;
begin
if not FLogs.TryGetValue(AName, TCustomLog(Result)) then
begin
Result := TFileLog.Create(TCustomLog.GetLogFolder + ExtractFileName(AName));
FLogs.Add(AName, Result);
end;
end;
var
L: TCustomLogH;
N: String;
begin
try
FSrvStarted.SetEvent;
// allow to send next msg
// we create it with initial state = true (already signalated)
//FEvtMsgCanWrite.SetEvent;
repeat
// wait for message in the buf
FEvtMsgCanRead.WaitFor(INFINITE);
if Terminated then
Break;
{$IF [Low(FSharedMem.MsgCmd)..High(FSharedMem.MsgCmd)]<>[cmdSend, cmdFlush, cmdClose]} Fix it here! {$ENDIF}
// read & execute log command
N := Trim(FSharedMem.GetLogName);
if N<>'' then
begin
L := TCustomLogH(GetLog(N));
case FSharedMem.MsgCmd of
cmdSend:
L.Send(@FSharedMem.MsgData, FSharedMem.MsgSize);
cmdFlush:
L.Flush;
cmdClose:
FLogs.Remove(N);
end;
end;
// allow to send next msg
FEvtMsgCanWrite.SetEvent;
until False;
except
on e: exception do
raise;
end;
end;
end.