forked from adoxa/ansicon
/
ANSI.c
1461 lines (1291 loc) · 42.2 KB
/
ANSI.c
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
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
ANSI.c - ANSI escape sequence console driver.
Jason Hood, 21 & 22 October, 2005.
Derived from ANSI.xs by Jean-Louis Morel, from his Perl package
Win32::Console::ANSI. I removed the codepage conversion ("\e(") and added
WriteConsole hooking.
v1.01, 11 & 12 March, 2006:
disable when console has disabled processed output;
\e[5m (blink) is the same as \e[4m (underline);
do not conceal control characters (0 to 31);
\e[m will restore original color.
v1.10, 22 February, 2009:
fix MyWriteConsoleW for strings longer than the buffer;
initialise attributes to current;
hook into child processes.
v1.11, 28 February, 2009:
fix hooking into child processes (only do console executables).
v1.12, 9 March, 2009:
really fix hooking (I didn't realise MinGW didn't generate relocations).
v1.13, 21 & 27 March, 2009:
alternate injection method, to work with DEP;
use Unicode and the current output code page (not OEMCP).
v1.14, 3 April, 2009:
fix test for empty import section.
v1.15, 17 May, 2009:
properly update lpNumberOfCharsWritten in MyWriteConsoleA.
v1.20, 26 & 29 May, 17 to 21 June, 2009:
create an ANSICON environment variable;
hook GetEnvironmentVariable to create ANSICON dynamically;
use another injection method.
v1.22, 5 October, 2009:
hook LoadLibrary to intercept the newly loaded functions.
v1.23, 11 November, 2009:
unload gracefully;
conceal characters by making foreground same as background;
reverse the bold/underline attributes, too.
v1.25, 15, 20 & 21 July, 2010:
hook LoadLibraryEx (now cscript works);
Win7 support.
v1.30, 3 August to 7 September, 2010:
x64 support.
v1.31, 13 & 19 November, 2010:
fix multibyte conversion problems.
v1.32, 4 to 22 December, 2010:
test for lpNumberOfCharsWritten/lpNumberOfBytesWritten being NULL;
recognise DSR and xterm window title;
ignore sequences starting with \e[? & \e[>;
close the handles opened by CreateProcess.
v1.40, 25 & 26 February, 1 March, 2011:
hook GetProcAddress, addresses issues with .NET (work with PowerShell);
implement SO & SI to use the DEC Special Graphics Character Set (enables
line drawing via ASCII); ignore \e(X & \e)X (where X is any character);
add \e[?25h & \e[?25l to show/hide the cursor (DECTCEM).
*/
#include "ansicon.h"
#include <tlhelp32.h>
#define isdigit(c) ('0' <= (c) && (c) <= '9')
// ========== Global variables and constants
// Macro for adding pointers/DWORDs together without C arithmetic interfering
#define MakePtr( cast, ptr, addValue ) (cast)((DWORD_PTR)(ptr)+(DWORD)(addValue))
const char APIKernel[] = "kernel32.dll";
const char APIKernelBase[] = "kernelbase.dll";
const char APIConsole[] = "API-MS-Win-Core-Console-L1-1-0.dll";
const char APIProcessThreads[] = "API-MS-Win-Core-ProcessThreads-L1-1-0.dll";
const char APIProcessEnvironment[] = "API-MS-Win-Core-ProcessEnvironment-L1-1-0.dll";
const char APILibraryLoader[] = "API-MS-Win-Core-LibraryLoader-L1-1-0.dll";
const char APIFile[] = "API-MS-Win-Core-File-L1-1-0.dll";
PCSTR APIs[] =
{
APIKernel,
APIConsole,
APIProcessThreads,
APIProcessEnvironment,
APILibraryLoader,
APIFile,
NULL
};
HMODULE hKernel; // Kernel32 module handle
HINSTANCE hDllInstance; // Dll instance handle
HANDLE hConOut; // handle to CONOUT$
#define ESC '\x1B' // ESCape character
#define BEL '\x07'
#define SO '\x0E' // Shift Out
#define SI '\x0F' // Shift In
#define MAX_ARG 16 // max number of args in an escape sequence
int state; // automata state
TCHAR prefix; // escape sequence prefix ( '[', ']' or '(' );
TCHAR prefix2; // secondary prefix ( '?' or '>' );
TCHAR suffix; // escape sequence suffix
int es_argc; // escape sequence args count
int es_argv[MAX_ARG]; // escape sequence args
TCHAR Pt_arg[MAX_PATH*2]; // text parameter for Operating System Command
int Pt_len;
BOOL shifted;
// DEC Special Graphics Character Set from
// http://vt100.net/docs/vt220-rm/table2-4.html
// Some of these may not look right, depending on the font and code page (in
// particular, the Control Pictures probably won't work at all).
const WCHAR G1[] =
{
' ', // _ - blank
L'\x2666', // ` - Black Diamond Suit
L'\x2592', // a - Medium Shade
L'\x2409', // b - HT
L'\x240c', // c - FF
L'\x240d', // d - CR
L'\x240a', // e - LF
L'\x00b0', // f - Degree Sign
L'\x00b1', // g - Plus-Minus Sign
L'\x2424', // h - NL
L'\x240b', // i - VT
L'\x2518', // j - Box Drawings Light Up And Left
L'\x2510', // k - Box Drawings Light Down And Left
L'\x250c', // l - Box Drawings Light Down And Right
L'\x2514', // m - Box Drawings Light Up And Right
L'\x253c', // n - Box Drawings Light Vertical And Horizontal
L'\x00af', // o - SCAN 1 - Macron
L'\x25ac', // p - SCAN 3 - Black Rectangle
L'\x2500', // q - SCAN 5 - Box Drawings Light Horizontal
L'_', // r - SCAN 7 - Low Line
L'_', // s - SCAN 9 - Low Line
L'\x251c', // t - Box Drawings Light Vertical And Right
L'\x2524', // u - Box Drawings Light Vertical And Left
L'\x2534', // v - Box Drawings Light Up And Horizontal
L'\x252c', // w - Box Drawings Light Down And Horizontal
L'\x2502', // x - Box Drawings Light Vertical
L'\x2264', // y - Less-Than Or Equal To
L'\x2265', // z - Greater-Than Or Equal To
L'\x03c0', // { - Greek Small Letter Pi
L'\x2260', // | - Not Equal To
L'\x00a3', // } - Pound Sign
L'\x00b7', // ~ - Middle Dot
};
#define FIRST_G1 '_'
#define LAST_G1 '~'
// color constants
#define FOREGROUND_BLACK 0
#define FOREGROUND_WHITE FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE
#define BACKGROUND_BLACK 0
#define BACKGROUND_WHITE BACKGROUND_RED|BACKGROUND_GREEN|BACKGROUND_BLUE
WORD foregroundcolor[8] =
{
FOREGROUND_BLACK, // black foreground
FOREGROUND_RED, // red foreground
FOREGROUND_GREEN, // green foreground
FOREGROUND_RED | FOREGROUND_GREEN, // yellow foreground
FOREGROUND_BLUE, // blue foreground
FOREGROUND_BLUE | FOREGROUND_RED, // magenta foreground
FOREGROUND_BLUE | FOREGROUND_GREEN, // cyan foreground
FOREGROUND_WHITE // white foreground
};
WORD backgroundcolor[8] =
{
BACKGROUND_BLACK, // black background
BACKGROUND_RED, // red background
BACKGROUND_GREEN, // green background
BACKGROUND_RED | BACKGROUND_GREEN, // yellow background
BACKGROUND_BLUE, // blue background
BACKGROUND_BLUE | BACKGROUND_RED, // magenta background
BACKGROUND_BLUE | BACKGROUND_GREEN, // cyan background
BACKGROUND_WHITE, // white background
};
// screen attributes
WORD org_fg, org_bg, org_bold, org_ul; // original attributes
WORD foreground;
WORD background;
WORD bold;
WORD underline;
WORD rvideo;
WORD concealed;
// saved cursor position
COORD SavePos;
// ========== Hooking API functions
//
// References about API hooking (and dll injection):
// - Matt Pietrek ~ Windows 95 System Programming Secrets.
// - Jeffrey Richter ~ Programming Applications for Microsoft Windows 4th ed.
typedef struct
{
PCSTR lib;
PSTR name;
PROC newfunc;
PROC oldfunc;
PROC apifunc;
} HookFn, *PHookFn;
HookFn Hooks[];
//-----------------------------------------------------------------------------
// HookAPIOneMod
// Substitute a new function in the Import Address Table (IAT) of the
// specified module.
// Return FALSE on error and TRUE on success.
//-----------------------------------------------------------------------------
BOOL HookAPIOneMod(
HMODULE hFromModule, // Handle of the module to intercept calls from
PHookFn Hooks, // Functions to replace
BOOL restore // Restore the original functions
)
{
PIMAGE_DOS_HEADER pDosHeader;
PIMAGE_NT_HEADERS pNTHeader;
PIMAGE_IMPORT_DESCRIPTOR pImportDesc;
PIMAGE_THUNK_DATA pThunk;
PHookFn hook;
// Tests to make sure we're looking at a module image (the 'MZ' header)
pDosHeader = (PIMAGE_DOS_HEADER)hFromModule;
if (pDosHeader->e_magic != IMAGE_DOS_SIGNATURE)
{
DEBUGSTR( L"error: %S(%d)", __FILE__, __LINE__ );
return FALSE;
}
// The MZ header has a pointer to the PE header
pNTHeader = MakePtr( PIMAGE_NT_HEADERS, pDosHeader, pDosHeader->e_lfanew );
// One more test to make sure we're looking at a "PE" image
if (pNTHeader->Signature != IMAGE_NT_SIGNATURE)
{
DEBUGSTR( L"error: %S(%d)", __FILE__, __LINE__ );
return FALSE;
}
// We now have a valid pointer to the module's PE header.
// Get a pointer to its imports section.
pImportDesc = MakePtr( PIMAGE_IMPORT_DESCRIPTOR,
pDosHeader,
pNTHeader->OptionalHeader.
DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].
VirtualAddress );
// Bail out if the RVA of the imports section is 0 (it doesn't exist)
if (pImportDesc == (PIMAGE_IMPORT_DESCRIPTOR)pDosHeader)
{
return TRUE;
}
// Iterate through the array of imported module descriptors, looking
// for the module whose name matches the pszFunctionModule parameter.
for (; pImportDesc->Name; pImportDesc++)
{
PCSTR* lib;
PSTR pszModName = MakePtr( PSTR, pDosHeader, pImportDesc->Name );
for (lib = APIs; *lib; ++lib)
if (_stricmp( pszModName, *lib ) == 0)
break;
if (*lib == NULL)
continue;
// Get a pointer to the found module's import address table (IAT).
pThunk = MakePtr( PIMAGE_THUNK_DATA, pDosHeader, pImportDesc->FirstThunk );
// Blast through the table of import addresses, looking for the ones
// that match the original addresses.
while (pThunk->u1.Function)
{
for (hook = Hooks; hook->name; ++hook)
{
PROC patch = 0;
if (restore)
{
if ((PROC)pThunk->u1.Function == hook->newfunc)
patch = (lib == APIs) ? hook->oldfunc : hook->apifunc;
}
else if ((PROC)pThunk->u1.Function == hook->oldfunc ||
(PROC)pThunk->u1.Function == hook->apifunc)
{
patch = hook->newfunc;
}
if (patch)
{
DWORD flOldProtect, flNewProtect, flDummy;
MEMORY_BASIC_INFORMATION mbi;
DEBUGSTR( L" %S", hook->name );
// Get the current protection attributes.
VirtualQuery( &pThunk->u1.Function, &mbi, sizeof(mbi) );
// Take the access protection flags.
flNewProtect = mbi.Protect;
// Remove ReadOnly and ExecuteRead flags.
flNewProtect &= ~(PAGE_READONLY | PAGE_EXECUTE_READ);
// Add on ReadWrite flag
flNewProtect |= (PAGE_READWRITE);
// Change the access protection on the region of committed pages in the
// virtual address space of the current process.
VirtualProtect( &pThunk->u1.Function, sizeof(PVOID),
flNewProtect, &flOldProtect );
// Overwrite the original address with the address of the new function.
if (!WriteProcessMemory( GetCurrentProcess(),
&pThunk->u1.Function,
&patch, sizeof(patch), NULL ))
{
DEBUGSTR( L"error: %S(%d)", __FILE__, __LINE__ );
return FALSE;
}
// Put the page attributes back the way they were.
VirtualProtect( &pThunk->u1.Function, sizeof(PVOID),
flOldProtect, &flDummy );
}
}
pThunk++; // Advance to next imported function address
}
}
return TRUE; // Function not found
}
//-----------------------------------------------------------------------------
// HookAPIAllMod
// Substitute a new function in the Import Address Table (IAT) of all
// the modules in the current process.
// Return FALSE on error and TRUE on success.
//-----------------------------------------------------------------------------
BOOL HookAPIAllMod( PHookFn Hooks, BOOL restore )
{
HANDLE hModuleSnap;
MODULEENTRY32 me;
BOOL fOk;
// Take a snapshot of all modules in the current process.
hModuleSnap = CreateToolhelp32Snapshot( TH32CS_SNAPMODULE,
GetCurrentProcessId() );
if (hModuleSnap == INVALID_HANDLE_VALUE)
{
DEBUGSTR( L"error: %S(%d)", __FILE__, __LINE__ );
return FALSE;
}
// Fill the size of the structure before using it.
me.dwSize = sizeof(MODULEENTRY32);
// Walk the module list of the modules.
for (fOk = Module32First( hModuleSnap, &me ); fOk;
fOk = Module32Next( hModuleSnap, &me ))
{
// We don't hook functions in our own module.
if (me.hModule != hDllInstance && me.hModule != hKernel)
{
//attempting to ignore NVIDIA 3D wrapper modules that seem to be in conflict on some systems
if (_wcsnicmp(me.szModule, L"nvd3d9wrap", 10) == 0)
{
DEBUGSTR(L"Ignoring %s", me.szModule);
continue;
}
DEBUGSTR( (restore) ? L"Unhooking from %s" : L"Hooking in %s",
me.szModule );
// Hook this function in this module.
if (!HookAPIOneMod( me.hModule, Hooks, restore ))
{
CloseHandle( hModuleSnap );
return FALSE;
}
}
}
CloseHandle( hModuleSnap );
return TRUE;
}
// ========== Print Buffer functions
#define BUFFER_SIZE (278+512) // fill out the section
int nCharInBuffer;
WCHAR ChBuffer[BUFFER_SIZE];
//-----------------------------------------------------------------------------
// FlushBuffer()
// Writes the buffer to the console and empties it.
//-----------------------------------------------------------------------------
void FlushBuffer( void )
{
DWORD nWritten;
if (nCharInBuffer <= 0) return;
WriteConsole( hConOut, ChBuffer, nCharInBuffer, &nWritten, NULL );
nCharInBuffer = 0;
}
//-----------------------------------------------------------------------------
// PushBuffer( WCHAR c )
// Adds a character in the buffer.
//-----------------------------------------------------------------------------
void PushBuffer( WCHAR c )
{
if (shifted && c >= FIRST_G1 && c <= LAST_G1)
c = G1[c-FIRST_G1];
ChBuffer[nCharInBuffer] = c;
if (++nCharInBuffer == BUFFER_SIZE)
FlushBuffer();
}
//-----------------------------------------------------------------------------
// SendSequence( LPTSTR seq )
// Send the string to the input buffer.
//-----------------------------------------------------------------------------
void SendSequence( LPTSTR seq )
{
DWORD out;
INPUT_RECORD in;
HANDLE hStdIn = GetStdHandle( STD_INPUT_HANDLE );
in.EventType = KEY_EVENT;
in.Event.KeyEvent.bKeyDown = TRUE;
in.Event.KeyEvent.wRepeatCount = 1;
in.Event.KeyEvent.wVirtualKeyCode = 0;
in.Event.KeyEvent.wVirtualScanCode = 0;
in.Event.KeyEvent.dwControlKeyState = 0;
for (; *seq; ++seq)
{
in.Event.KeyEvent.uChar.UnicodeChar = *seq;
WriteConsoleInput( hStdIn, &in, 1, &out );
}
}
// ========== Print functions
//-----------------------------------------------------------------------------
// InterpretEscSeq()
// Interprets the last escape sequence scanned by ParseAndPrintString
// prefix escape sequence prefix
// es_argc escape sequence args count
// es_argv[] escape sequence args array
// suffix escape sequence suffix
//
// for instance, with \e[33;45;1m we have
// prefix = '[',
// es_argc = 3, es_argv[0] = 33, es_argv[1] = 45, es_argv[2] = 1
// suffix = 'm'
//-----------------------------------------------------------------------------
void InterpretEscSeq( void )
{
int i;
WORD attribut;
CONSOLE_SCREEN_BUFFER_INFO Info;
CONSOLE_CURSOR_INFO CursInfo;
DWORD len, NumberOfCharsWritten;
COORD Pos;
SMALL_RECT Rect;
CHAR_INFO CharInfo;
if (prefix == '[')
{
if (prefix2 == '?' && (suffix == 'h' || suffix == 'l'))
{
if (es_argc == 1 && es_argv[0] == 25)
{
GetConsoleCursorInfo( hConOut, &CursInfo );
CursInfo.bVisible = (suffix == 'h');
SetConsoleCursorInfo( hConOut, &CursInfo );
return;
}
}
// Ignore any other \e[? or \e[> sequences.
if (prefix2 != 0)
return;
GetConsoleScreenBufferInfo( hConOut, &Info );
switch (suffix)
{
case 'm':
if (es_argc == 0) es_argv[es_argc++] = 0;
for (i = 0; i < es_argc; i++)
{
switch (es_argv[i])
{
case 0:
foreground = org_fg;
background = org_bg;
bold = (es_argc == 1) ? org_bold : 0;
underline = (es_argc == 1) ? org_ul : 0;
rvideo = 0;
concealed = 0;
break;
case 1: bold = FOREGROUND_INTENSITY; break;
case 5: /* blink */
case 4: underline = BACKGROUND_INTENSITY; break;
case 7: rvideo = 1; break;
case 8: concealed = 1; break;
case 21: bold = 0; break;
case 25:
case 24: underline = 0; break;
case 27: rvideo = 0; break;
case 28: concealed = 0; break;
}
if (30 <= es_argv[i] && es_argv[i] <= 37) foreground = es_argv[i]-30;
if (40 <= es_argv[i] && es_argv[i] <= 47) background = es_argv[i]-40;
}
if (concealed)
{
if (rvideo)
{
attribut = foregroundcolor[foreground]
| backgroundcolor[foreground];
if (bold)
attribut |= FOREGROUND_INTENSITY | BACKGROUND_INTENSITY;
}
else
{
attribut = foregroundcolor[background]
| backgroundcolor[background];
if (underline)
attribut |= FOREGROUND_INTENSITY | BACKGROUND_INTENSITY;
}
}
else if (rvideo)
{
attribut = foregroundcolor[background] | backgroundcolor[foreground];
if (bold)
attribut |= BACKGROUND_INTENSITY;
if (underline)
attribut |= FOREGROUND_INTENSITY;
}
else
attribut = foregroundcolor[foreground] | backgroundcolor[background]
| bold | underline;
SetConsoleTextAttribute( hConOut, attribut );
return;
case 'J':
if (es_argc == 0) es_argv[es_argc++] = 0; // ESC[J == ESC[0J
if (es_argc != 1) return;
switch (es_argv[0])
{
case 0: // ESC[0J erase from cursor to end of display
len = (Info.dwSize.Y - Info.dwCursorPosition.Y - 1) * Info.dwSize.X
+ Info.dwSize.X - Info.dwCursorPosition.X - 1;
FillConsoleOutputCharacter( hConOut, ' ', len,
Info.dwCursorPosition,
&NumberOfCharsWritten );
FillConsoleOutputAttribute( hConOut, Info.wAttributes, len,
Info.dwCursorPosition,
&NumberOfCharsWritten );
return;
case 1: // ESC[1J erase from start to cursor.
Pos.X = 0;
Pos.Y = 0;
len = Info.dwCursorPosition.Y * Info.dwSize.X
+ Info.dwCursorPosition.X + 1;
FillConsoleOutputCharacter( hConOut, ' ', len, Pos,
&NumberOfCharsWritten );
FillConsoleOutputAttribute( hConOut, Info.wAttributes, len, Pos,
&NumberOfCharsWritten );
return;
case 2: // ESC[2J Clear screen and home cursor
Pos.X = 0;
Pos.Y = 0;
len = Info.dwSize.X * Info.dwSize.Y;
FillConsoleOutputCharacter( hConOut, ' ', len, Pos,
&NumberOfCharsWritten );
FillConsoleOutputAttribute( hConOut, Info.wAttributes, len, Pos,
&NumberOfCharsWritten );
SetConsoleCursorPosition( hConOut, Pos );
return;
default:
return;
}
case 'K':
if (es_argc == 0) es_argv[es_argc++] = 0; // ESC[K == ESC[0K
if (es_argc != 1) return;
switch (es_argv[0])
{
case 0: // ESC[0K Clear to end of line
len = Info.srWindow.Right - Info.dwCursorPosition.X + 1;
FillConsoleOutputCharacter( hConOut, ' ', len,
Info.dwCursorPosition,
&NumberOfCharsWritten );
FillConsoleOutputAttribute( hConOut, Info.wAttributes, len,
Info.dwCursorPosition,
&NumberOfCharsWritten );
return;
case 1: // ESC[1K Clear from start of line to cursor
Pos.X = 0;
Pos.Y = Info.dwCursorPosition.Y;
FillConsoleOutputCharacter( hConOut, ' ',
Info.dwCursorPosition.X + 1, Pos,
&NumberOfCharsWritten );
FillConsoleOutputAttribute( hConOut, Info.wAttributes,
Info.dwCursorPosition.X + 1, Pos,
&NumberOfCharsWritten );
return;
case 2: // ESC[2K Clear whole line.
Pos.X = 0;
Pos.Y = Info.dwCursorPosition.Y;
FillConsoleOutputCharacter( hConOut, ' ', Info.dwSize.X, Pos,
&NumberOfCharsWritten );
FillConsoleOutputAttribute( hConOut, Info.wAttributes,
Info.dwSize.X, Pos,
&NumberOfCharsWritten );
return;
default:
return;
}
case 'L': // ESC[#L Insert # blank lines.
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[L == ESC[1L
if (es_argc != 1) return;
Rect.Left = 0;
Rect.Top = Info.dwCursorPosition.Y;
Rect.Right = Info.dwSize.X - 1;
Rect.Bottom = Info.dwSize.Y - 1;
Pos.X = 0;
Pos.Y = Info.dwCursorPosition.Y + es_argv[0];
CharInfo.Char.UnicodeChar = ' ';
CharInfo.Attributes = Info.wAttributes;
ScrollConsoleScreenBuffer( hConOut, &Rect, NULL, Pos, &CharInfo );
return;
case 'M': // ESC[#M Delete # lines.
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[M == ESC[1M
if (es_argc != 1) return;
if (es_argv[0] > Info.dwSize.Y - Info.dwCursorPosition.Y)
es_argv[0] = Info.dwSize.Y - Info.dwCursorPosition.Y;
Rect.Left = 0;
Rect.Top = Info.dwCursorPosition.Y + es_argv[0];
Rect.Right = Info.dwSize.X - 1;
Rect.Bottom = Info.dwSize.Y - 1;
Pos.X = 0;
Pos.Y = Info.dwCursorPosition.Y;
CharInfo.Char.UnicodeChar = ' ';
CharInfo.Attributes = Info.wAttributes;
ScrollConsoleScreenBuffer( hConOut, &Rect, NULL, Pos, &CharInfo );
return;
case 'P': // ESC[#P Delete # characters.
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[P == ESC[1P
if (es_argc != 1) return;
if (Info.dwCursorPosition.X + es_argv[0] > Info.dwSize.X - 1)
es_argv[0] = Info.dwSize.X - Info.dwCursorPosition.X;
Rect.Left = Info.dwCursorPosition.X + es_argv[0];
Rect.Top = Info.dwCursorPosition.Y;
Rect.Right = Info.dwSize.X - 1;
Rect.Bottom = Info.dwCursorPosition.Y;
CharInfo.Char.UnicodeChar = ' ';
CharInfo.Attributes = Info.wAttributes;
ScrollConsoleScreenBuffer( hConOut, &Rect, NULL, Info.dwCursorPosition,
&CharInfo );
return;
case '@': // ESC[#@ Insert # blank characters.
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[@ == ESC[1@
if (es_argc != 1) return;
if (Info.dwCursorPosition.X + es_argv[0] > Info.dwSize.X - 1)
es_argv[0] = Info.dwSize.X - Info.dwCursorPosition.X;
Rect.Left = Info.dwCursorPosition.X;
Rect.Top = Info.dwCursorPosition.Y;
Rect.Right = Info.dwSize.X - 1 - es_argv[0];
Rect.Bottom = Info.dwCursorPosition.Y;
Pos.X = Info.dwCursorPosition.X + es_argv[0];
Pos.Y = Info.dwCursorPosition.Y;
CharInfo.Char.UnicodeChar = ' ';
CharInfo.Attributes = Info.wAttributes;
ScrollConsoleScreenBuffer( hConOut, &Rect, NULL, Pos, &CharInfo );
return;
case 'A': // ESC[#A Moves cursor up # lines
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[A == ESC[1A
if (es_argc != 1) return;
Pos.Y = Info.dwCursorPosition.Y - es_argv[0];
if (Pos.Y < 0) Pos.Y = 0;
Pos.X = Info.dwCursorPosition.X;
SetConsoleCursorPosition( hConOut, Pos );
return;
case 'B': // ESC[#B Moves cursor down # lines
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[B == ESC[1B
if (es_argc != 1) return;
Pos.Y = Info.dwCursorPosition.Y + es_argv[0];
if (Pos.Y >= Info.dwSize.Y) Pos.Y = Info.dwSize.Y - 1;
Pos.X = Info.dwCursorPosition.X;
SetConsoleCursorPosition( hConOut, Pos );
return;
case 'C': // ESC[#C Moves cursor forward # spaces
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[C == ESC[1C
if (es_argc != 1) return;
Pos.X = Info.dwCursorPosition.X + es_argv[0];
if (Pos.X >= Info.dwSize.X) Pos.X = Info.dwSize.X - 1;
Pos.Y = Info.dwCursorPosition.Y;
SetConsoleCursorPosition( hConOut, Pos );
return;
case 'D': // ESC[#D Moves cursor back # spaces
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[D == ESC[1D
if (es_argc != 1) return;
Pos.X = Info.dwCursorPosition.X - es_argv[0];
if (Pos.X < 0) Pos.X = 0;
Pos.Y = Info.dwCursorPosition.Y;
SetConsoleCursorPosition( hConOut, Pos );
return;
case 'E': // ESC[#E Moves cursor down # lines, column 1.
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[E == ESC[1E
if (es_argc != 1) return;
Pos.Y = Info.dwCursorPosition.Y + es_argv[0];
if (Pos.Y >= Info.dwSize.Y) Pos.Y = Info.dwSize.Y - 1;
Pos.X = 0;
SetConsoleCursorPosition( hConOut, Pos );
return;
case 'F': // ESC[#F Moves cursor up # lines, column 1.
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[F == ESC[1F
if (es_argc != 1) return;
Pos.Y = Info.dwCursorPosition.Y - es_argv[0];
if (Pos.Y < 0) Pos.Y = 0;
Pos.X = 0;
SetConsoleCursorPosition( hConOut, Pos );
return;
case 'G': // ESC[#G Moves cursor column # in current row.
if (es_argc == 0) es_argv[es_argc++] = 1; // ESC[G == ESC[1G
if (es_argc != 1) return;
Pos.X = es_argv[0] - 1;
if (Pos.X >= Info.dwSize.X) Pos.X = Info.dwSize.X - 1;
if (Pos.X < 0) Pos.X = 0;
Pos.Y = Info.dwCursorPosition.Y;
SetConsoleCursorPosition( hConOut, Pos );
return;
case 'f': // ESC[#;#f
case 'H': // ESC[#;#H Moves cursor to line #, column #
if (es_argc == 0)
es_argv[es_argc++] = 1; // ESC[H == ESC[1;1H
if (es_argc == 1)
es_argv[es_argc++] = 1; // ESC[#H == ESC[#;1H
if (es_argc > 2) return;
Pos.X = es_argv[1] - 1;
if (Pos.X < 0) Pos.X = 0;
if (Pos.X >= Info.dwSize.X) Pos.X = Info.dwSize.X - 1;
Pos.Y = es_argv[0] - 1;
if (Pos.Y < 0) Pos.Y = 0;
if (Pos.Y >= Info.dwSize.Y) Pos.Y = Info.dwSize.Y - 1;
SetConsoleCursorPosition( hConOut, Pos );
return;
case 's': // ESC[s Saves cursor position for recall later
if (es_argc != 0) return;
SavePos = Info.dwCursorPosition;
return;
case 'u': // ESC[u Return to saved cursor position
if (es_argc != 0) return;
SetConsoleCursorPosition( hConOut, SavePos );
return;
case 'n': // ESC[#n Device status report
if (es_argc != 1) return; // ESC[n == ESC[0n -> ignored
switch (es_argv[0])
{
case 5: // ESC[5n Report status
SendSequence( L"\33[0n" ); // "OK"
return;
case 6: // ESC[6n Report cursor position
{
TCHAR buf[32];
wsprintf( buf, L"\33[%d;%dR", Info.dwCursorPosition.Y + 1,
Info.dwCursorPosition.X + 1 );
SendSequence( buf );
}
return;
default:
return;
}
case 't': // ESC[#t Window manipulation
if (es_argc != 1) return;
if (es_argv[0] == 21) // ESC[21t Report xterm window's title
{
TCHAR buf[MAX_PATH*2];
DWORD len = GetConsoleTitle( buf+3, lenof(buf)-3-2 );
// Too bad if it's too big or fails.
buf[0] = ESC;
buf[1] = ']';
buf[2] = 'l';
buf[3+len] = ESC;
buf[3+len+1] = '\\';
buf[3+len+2] = '\0';
SendSequence( buf );
}
return;
default:
return;
}
}
else // (prefix == ']')
{
// Ignore any \e]? or \e]> sequences.
if (prefix2 != 0)
return;
if (es_argc == 1 && es_argv[0] == 0) // ESC]0;titleST
{
SetConsoleTitle( Pt_arg );
}
}
}
//-----------------------------------------------------------------------------
// ParseAndPrintString(hDev, lpBuffer, nNumberOfBytesToWrite)
// Parses the string lpBuffer, interprets the escapes sequences and prints the
// characters in the device hDev (console).
// The lexer is a three states automata.
// If the number of arguments es_argc > MAX_ARG, only the MAX_ARG-1 firsts and
// the last arguments are processed (no es_argv[] overflow).
//-----------------------------------------------------------------------------
BOOL
ParseAndPrintString( HANDLE hDev,
LPCVOID lpBuffer,
DWORD nNumberOfBytesToWrite,
LPDWORD lpNumberOfBytesWritten
)
{
DWORD i;
LPCTSTR s;
if (hDev != hConOut) // reinit if device has changed
{
hConOut = hDev;
state = 1;
shifted = FALSE;
}
for (i = nNumberOfBytesToWrite, s = (LPCTSTR)lpBuffer; i > 0; i--, s++)
{
if (state == 1)
{
if (*s == ESC) state = 2;
else if (*s == SO) shifted = TRUE;
else if (*s == SI) shifted = FALSE;
else PushBuffer( *s );
}
else if (state == 2)
{
if (*s == ESC) ; // \e\e...\e == \e
else if ((*s == '[') || (*s == ']'))
{
FlushBuffer();
prefix = *s;
prefix2 = 0;
state = 3;
Pt_len = 0;
*Pt_arg = '\0';
}
else if (*s == ')' || *s == '(') state = 6;
else state = 1;
}
else if (state == 3)
{
if (isdigit( *s ))
{
es_argc = 0;
es_argv[0] = *s - '0';
state = 4;
}
else if (*s == ';')
{
es_argc = 1;
es_argv[0] = 0;
es_argv[1] = 0;
state = 4;
}
else if (*s == '?' || *s == '>')
{
prefix2 = *s;
}
else
{
es_argc = 0;
suffix = *s;
InterpretEscSeq();
state = 1;
}
}
else if (state == 4)
{
if (isdigit( *s ))
{
es_argv[es_argc] = 10 * es_argv[es_argc] + (*s - '0');
}
else if (*s == ';')
{
if (es_argc < MAX_ARG-1) es_argc++;
es_argv[es_argc] = 0;
if (prefix == ']')
state = 5;
}
else
{
es_argc++;
suffix = *s;
InterpretEscSeq();
state = 1;
}
}
else if (state == 5)
{
if (*s == BEL)
{
Pt_arg[Pt_len] = '\0';
InterpretEscSeq();
state = 1;
}
else if (*s == '\\' && Pt_len > 0 && Pt_arg[Pt_len-1] == ESC)
{
Pt_arg[--Pt_len] = '\0';
InterpretEscSeq();
state = 1;
}
else if (Pt_len < lenof(Pt_arg)-1)
Pt_arg[Pt_len++] = *s;
}
else if (state == 6)
{
// Ignore it (ESC ) 0 is implicit; nothing else is supported).
state = 1;
}
}
FlushBuffer();
if (lpNumberOfBytesWritten != NULL)
*lpNumberOfBytesWritten = nNumberOfBytesToWrite - i;
return( i == 0 );
}
// ========== Child process injection
// Inject code into the target process to load our DLL.
void Inject( LPPROCESS_INFORMATION pinfo, LPPROCESS_INFORMATION lpi,
DWORD dwCreationFlags )
{
int type = ProcessType( pinfo );
if (type != 0)
{
WCHAR dll[MAX_PATH];
#ifdef _WIN64
DWORD len = GetModuleFileName( GetModuleHandleA( "ANSI64.dll" ),
dll, lenof(dll) );