-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathMCF.au3
2923 lines (2499 loc) · 103 KB
/
MCF.au3
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
; ===============================================================================================================================
; Title .........: MetaCode File (MCF) library
; AutoIt Version : 3.3.12
; Description ...: processes CodeScanner ouput: structural and content files
; Author.........: A.R.T. Jonkers (RTFC)
; Release........: 1.3
; Latest revision: 16 Aug 2014
;
; License........: free for personal use; free distribution allowed provided
; the original author is credited; all other rights reserved.
; Tested on......: W7Pro/64
; Forum Link.....: www.autoitscript.com/forum/topic/155537-mcf-metacode-file-udf/
; Dependencies...: CodeScanner, by RTFC, see www.autoitscript.com/forum/topic/153368-code-scanner/
; ReadCSDataDump, by RTFC (part of CodeScanner package)
; MCFinclude, by RTFC (itself includes AES.au3, by Ward)
; Acknowledgements: Ward, for AES.au3, included in MCFinclude.au3 (IMPORTANT: see AES patch instructions in MCFinclude.au3 remarks)
;============================================================================================
; MCF UDFs
;
; * Input-related:
; _CreateSingleBuild preprocess arrays, call _WriteMCF0(), save new arrays
; _RemoveOrphans remove orphaned globals and/or UDF defs (multi-pass, may take long)
; _MCWords replace code by MetaCode (NB also called by CodeScanner)
; _WriteMCF0 generate MCF0.txt from MCF#.txt (#=1-N), without redundancies (recursive)
;
; * Structure-altering:
; _IndirectMCF replace direct variable assignments with equivalent calls
; _PhraseMCF replace all conditionals and calls with phrases
;
; * Content-altering:
; _EncryptArrays fill arrays stringEncryp and phrasesNew, calls _EncryptEntry
; _EncryptEntry encrypt an inputstring with a given keytype, add fixed-key wrapper if desired
; _ObfuscateArrays creates hex template, calls _ObfuscateNames on arrays variables, functions, and strings
; _ObfuscateNames given a source array, fills destination array
; _TranslateVarsInStrings replaces variable names (without "$") inside strings with their (user-predefined) translation
;
; * Output-related:
; _BackTranslate encode MCF0 with *original* CS-extracted datasets (no processing)
; _CreateNewScript encode MCF0 with *New[] arrays (no processing except what user externally changed in *New[] arrays)
; _RebuildScript encode MCF0 with altered? structure and altered? content arrays
; _EncodeMCF MCF Script Writer
; _ReplaceMCinArray replace MetaCode with code in arrays (strings, phrases)
;
; * Auxiliary:
; _CallStack_Pop update call stack
; _CallStack_Push update call stack
; _ClearArrays clear all buffers (any previous processing is lost)
; _FillCSpath check/set CS_dumppath
; _FillSkipRegExpStrings() ; list RegeExp pattern strings for exclusion in various procedures
; _PrepMCenvironment call _FillCSpath(), (re)load all arrays from files
; _PrepMCFinclude store obfuscated _MCFCC calls for insertion into target
; _RandomHex generate a random hex string of given length
; _ShowMCFile run Notepad on currently processed file
; _TestCCKey check CCkeyp[] def
; _ValidPrefix XLATB table
;
;============================================================================================
; Summary (Wotsit?)
;
; MetaCode processing separates a script's CONTENT from its STRUCTURE,
; allowing you to change one independently of the other, then rebuild the script
;
; These UDFs take CodeScanner metadata output (in *.CS_DATA\ output dir) to create:
; - a Single-Build MetaCode File called MCF0.txt
; - an AutoIt script called MCF0.au3, based upon MCF0.txt and the CS_DATA arrays
; - a copy of MCF0.au3 called MCF0test.au3, in the original source directory,
; for testing (provided no errors occurred in processing)
;
; These UDFs are to be called from other scripts, notably:
; - CodeCrypter, by RTFC
; - CodeScanner, by RTFC
;
;============================================================================================
; Application (WhyBother?)
;
; Short answer: MetaCode!
; Longer answer: code condensing, translation, obfuscation, encryption, possibly even cross-compilation...
; Better answer: see the MetaCode tutorial in the MetaCode thread in the AutoIt Exmple Scripts Forum
;
; Input: CodeScanner output directory (full path)
; (run CodeScanner first with setting WriteMetaData=True)
;
; Outputs:
; * Files: MCF0.txt, MCF0.au3
; * many arrays, stored as text files in CodeScanner's DataDump subdirectory
; NB original CodeScanner arrays are retained as <name>_CS.txt
;
;============================================================================================
; Remarks
;
; * please read the MetaCode tutorial in the MetaCode (MCF.au3) thread in the AutoIt Example Scripts Forum
;
; * Processing sequence:
; 1. <myscript>.au3 + #includes => Codescanner => MCF#.txt (MetaCode: 1-myscript, 2-N = #includes)
; 2. MCF1.txt + MCF2-N.txt => _CreateSingleBuild() => MCF0.txt (MetaCodeFile zero)
; 3. MCF0.txt => _BackTranslate() => MCF0.au3 (AutoIt script from MetaCode)
; NB if BackTranslate is called without a prior call to _CreateSingleBuild(),
; BackTranslate will itself first call _CreateSingleBuild()
;
; * MCF0.txt is the MetaCode equivalent of the complete source, in which:
; - all Autoit calls are replaced by, and refer to array entry:
; {funcA#} = $AU3Functions[#] (complete set)
; - all UDF calls and defined names are replaced by, and refer to, array entry:
; {funcU#} = $functionsUsed[#] (for active subset, see $functionsCalled[])
; - all variables are replaced by, and refer to array entry:
; {var#} = $variablesUsed[#]
; - all strings are replaced by, and refer to array entry:
; {string#} = $stringsUsed[#]
; - all macros are replaced by, and refer to array entry:
; {macro#} = $macros[#]
; - each executable line has a comment suffix specifying:
; {file#} = $includes[#] (original source files)
; {line#} = line number in original source file
; - each global definition has an additional comment suffix specifying:
; {ref#} = $references[#]
;
; * Why create a Single-Build?
; MCF0 is a portable, condensed MCF interpretation of the analysed source:
; - without #includes (all required parts are placed in main script, the rest is out)
; - without redundant UDF definitions (set $MCF_SKIP_UNCALLED_UDFS=False to keep them)
; - without redundant globals (set $MCF_REMOVE_ORPHANS=False to keep them)
;
; * Why use BackTranslation?
; 1. to create a portable (single-source), executable script
; 2. to TEST whether the MetaCode version works, while being able to compare
; with the original source before the former is altered
;
; * BackTranslation creates MCF0.au3; if no errors, it is also copied to
; ..\MCF0test.au3, because(!) its proper functioning may rely on
; local resources, relative paths, etc.
;
; * once generated, load MCF0test.au3 in Scite and run AU3Check;
; if errors, try _CreateSingleBuild() with
; $MCF_SKIP_UNCALLED_UDFS=False, and/or
; $MCF_REMOVE_ORPHANS=False (MCF0.au3 may become larger)
; if no errors, run it to see whether it behaves as expected;
; if so, you're in business (see MetaCode tutorial doc for some powerful applications)
;
; * MCF does not need CodeScanner's full DataDump; setting WriteMetaCode=True in
; CodeScanner will automatically output only those arrays needed for MCFs
;
; * Using Keywords "Execute","Assign","Eval","IsDeclared" results in a flagged
; Self-Modifying Code Issue in BackTranslation, but MCF0.au3 is still
; generated and may work (try with $MCF_SKIP_UNCALLED_UDFS=False and $MCF_REMOVE_ORPHANS=False)
;
; * Optional structure alterations:
; - Indirection: replaces var assignments with indirect calls (more lines encrypted)
; before: $varA = $varB
; after: _VarIsVar($varA,$varB) ; UDF def is in MCFinclude.au3
; - Phrasing: extracts conditionals and calls (faster decryption; default on)
; before: {var}={funcU}(funcA}({string},$var},{macro}),{string},0,1,False)
; after: {var}={phrase}
;
; * Optional content alterations, in sequence:
; - Linguistic translation: YOU replace content of text file(s) *Transl.txt
; - Obfuscation: vars, UDFs, or both; affects strings that contain these automatically
; - Encryption: can affect all arrays, including phrases*[]
; Final source data are stored in arrays *New[]
;
; * MCF content post-processing; which operation affects what, and in what order?
;
; MetaCode Translation -> Obfuscation -> Encryption
; -------------------------------------------------------
; AU3 call - - YES (phrased)
; UDF YES YES YES (phrased)
; variable YES YES -
; string YES - YES
; macros - - YES (phrased)
; phrase - - YES
;
; * Quick language Translation (after calling CreateSingleBuild):
; 1. dump stringsUsed.txt into Google Translate, save result in stringsTransl.txt
; Note: translate UI strings only, not DllCall and WinAPI arguments, etc.
; 2. call _RebuildScript($path,True) with setting $MCF_TRANSLATE_STRINGS=True
; 3. Done.
; NB if you want to translate names of variables and UDFs, edit their *Transl.txt files.
;
; * Quick Obfuscation (after calling CreateSingleBuild):
; 1. call _RebuildScript($path,True) with settings:
; $MCF_OBFUSCATE_UDFS = True
; $MCF_OBFUSCATE_VARS = True
; 2. Done.
;
; * Quick Encryption:
; 1. edit MCFinclude if you wish to define a new keytype, or choose the one(s) you want
; 2. add MCFinclude to your target script (anything below this #include line will by default be encrypted)
; 3. run CodeScanner on the target script (CodeScanner data dump subdirectory = $path used below)
; 4. call CreateSingleBuild($path, True)
; 5. call MCFCC_init(<selected_keytype>) ; UDF is in MCFinclude.au3, itself included in MCF.au3
; 6. call _RebuildScript($path,True) with settings:
; $MCF_ENCRYPT_PHRASES = True
; $MCF_ENCRYPT_STRINGS = True
; 7. Done.
; (of course, CodeCrypter would do most of this automatically for you...)
;
; * Encryption replaces phrases, i.e.:
; - conditionals (code following If/While/Until)
; - calls (native AutoIt and UDFs)
; - macros
; with "Execute(_MCFCC(<encrypted code>))"
; NB Each of these three can be switched off individually by setting:
; $MCF_REPLACE_* = False (* = VARS, UDS, MACROS) prior to calling _PhraseMCF()
; NB always set these booleans back to True before calling _EncodeMCF()
;
; * setting UDF parameter $force_refresh=True => first reload all arrays from file
;
; * do not set $MCF_WRITE_COMMENTS = False PRIOR to creating the final output;
; some UDFs require specific MCF-generated comments as location markers
;
; * you can use any encryption algorithm you want.
; Steps for changing the encryption algorithm:
; - rename a copy of MCFinclude.au3 as <newname>
; - remove #include AES.au3 from <newname>
; - if your algorithm requires some other external #include, add this at the top of <newname>
; - in <newname>'s UDF _MCFCC(), replace the decryption call
; - edit <newname>'s Global $MCFinclude = "MCFinclude.au3" => "<newname>"
; - change in MCF.au3: #include "MCFinclude.au3" => "<newname>"
; - change in MCF.au3: replace all encryption calls in UDF: _EncryptEntry()
; - Test, test, and test, then test again (and do more tests). Then test.
;
;============================================================================================
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Run_AU3Check=Y
#AutoIt3Wrapper_AU3Check_Parameters= -q -w 1 -w 2 -w- 4 -w 6 -w- 7
#AutoIt3Wrapper_UseX64=N
#AutoIt3Wrapper_res_Compatibility=Vista,Windows7
#AutoIt3Wrapper_UseUPX=Y
#AutoIt3Wrapper_Run_Obfuscator=N
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#NoTrayIcon
#include-once
#include <Crypt.au3>
#include <Date.au3>
#include <File.au3>
#include <Math.au3>
#include <Misc.au3>
#include <String.au3>
#include ".\readCSdatadump.au3" ; part of the CodeScanner package
#include ".\MCFinclude.au3" ; default MCFinclude, using AES.au3, by Ward
#region Globals
; input-related booleans
Global $MCF_CREATE_SINGLE =True
Global $MCF_BACKTRANSLATE =False
Global $MCF_CREATE_NEW =False
; content-altering booleans
Global $MCF_TRANSLATE =False ; enable $MCF_TRANSLATE_* settings
Global $MCF_TRANSLATE_STRINGS =False ; encode with $stringsTransl (auto-updated with $variablesTransl and $functionsTransl)
Global $MCF_TRANSLATE_UDFS =False ; encode with $functionsTransl
Global $MCF_TRANSLATE_VARS =False ; encode with $variablesTransl
Global $MCF_OBFUSCATE =False ; enable $MCF_OBFUSCATE_* settings
Global $MCF_OBFUSCATE_UDFS =False ; encode with $functionsObfusc
Global $MCF_OBFUSCATE_VARS =False ; encode with $variablesObfusc
Global $MCF_ENCRYPT =False ; enable $MCF_ENCRYPT_* settings
Global $MCF_ENCRYPT_PHRASES =False ; Execute(decrypt(encrypted call or conditionals))
Global $MCF_ENCRYPT_STRINGS =False ; decrypt(encrypted string)
Global $MCF_ENCRYPT_NESTED =False ; T=encrypt(encrypt(code,dynamickey),statickey), F=encrypt(code,dynamickey)
Global $MCF_ENCRYPT_SUBSET =False ; use $subset_definition to determine which lines will be encrypted
Global $MCF_ENCRYPT_SHUFFLEKEY=False ; T=select a random keytype from a predefined range of keys, F= single dynamic key
; structure-altering booleans
Global $MCF_SKIP_UNCALLED_UDFS=True ; affects WriteMCF0() (part of CreateSingleBuild)
Global $MCF_REMOVE_ORPHANS =True ; enable recursive scan for orphaned global vars and UDFs
Global $MCF_INDIRECTION =False ; replace direct assignments with indirect UDF calls (enhances encryption coverage)
Global $MCF_PHRASING =False ; auto-True if $MCF_ENCRYPT=True
; encoding booleans (always keep all True, unless testing MCF.au3 itself)
Global $MCF_REPLACE_AUFUNCS =True
Global $MCF_REPLACE_UDFS =True
Global $MCF_REPLACE_VARS =True
Global $MCF_REPLACE_STRINGS =True
Global $MCF_REPLACE_MACROS =True
Global $MCF_REPLACE_PHRASES =True
Global $MCF_WRITE_COMMENTS =True ; default = Not($MCF_ENCRYPT); affects final output only
; global arrays
Global $CallStack[1]
Global $phrases[1]
Global $phrasesUsed[1]
Global $phrasesUDF[1]
Global $phrasesEncryp[1]
Global $phrasesNew[1]
Global $strings1[1]
Global $strings2[1]
Global $globalsOrphaned[1]
Global $already_included[1]
Global $fileIncludeOnce[1]
Global $validprefix[256]
Global $namesUsed[1]
Global $SelectedUDFname[1]
Global $SelectedUDFstatus[1]
Global $skipRegExpStrings[1]
; internal call tags and parameters
Global $_MCFCC ="" ; (M)eta(C)ode(F)ile, (C)ode(C)rypter call
Global $_MCFCCXA ="" ; e(X)ecute once
Global $_MCFCCXB ="" ; e(X)ecute twice
Global $decryption_key =""
Global $CCkeytype =3 ; see MCFinclude.au3 for key definition
Global $CCkeyshuffle_start =2 ; do not set < 1 (0 = fixedkey)
Global $CCkeyshuffle_end =5 ; do not set > Ubound(£CCkey)-1
Global $subset_definition =0.5 ; <1 = percentage (random), >1 = ccycled (1 in N lines)
; miscellaneous
Global $CCGUI,$INIvars
Global $ShowErrorMsg =True
Global $showProgress =True ; can also be defined as global in whatever is calling these UDFs
Global $MCF_file_ID =0
Global $section1_lastline=0
Global $section2_lastline=0
Global $section1_lastphrase=0
Global $section2_lastphrase=0
Global $Obfstringwidth=16
Global $fhout =0
Global $totalfiles =0
Global $totalines =0
Global $CS_dumppath =".\"
Global $dumptag =""
Global $errortag ="*** ERROR: " ; inserted in MCF0.au3 at each failed BackTramslation location
Global $timestamptag ="was generated on " ; inserted in MCF0.au3 (should not be empty)
$CallStack[0]=@ScriptName
Global $uselogfile=False ; create a log file? (used only in cmdline mode)
Global $fhlog=""
#endregion Globals
#region Input-related
Func _CreateSingleBuild($path,$force_refresh=False) ; build MCF0.txt, stripping all redundant parts
; parsed $path = CodeScanner DataDump path
$procname="_CreateSingleBuild"
_CallStack_Push($procname)
If $uselogfile Then _FileWriteLog($fhlog,$procname & " started.")
If _PrepMCenvironment($path,$force_refresh)=False Then Return SetError(_ErrorHandler(-1,"preparing MCF environment",$procname),0,False)
; reload original CodeScanner arrays
If $showProgress=True Then SplashTextOn("","Preparing MCF0...",250,40,-1,-1,1+32,"Verdana",10)
Global $stringsUsed =$stringsUsed_CS
Global $variablesUsed =$variablesUsed_CS
Global $functionsUsed =$functionsUsed_CS
Global $macrosUsed =$macrosUsed_CS
Global $functionsCalled =$functionsCalled_CS
Global $FuncEqualsString[1]
SplashOff()
If $uselogfile Then _FileWriteLog($fhlog,$procname & ": processing strings...")
For $rc=1 To $stringsUsed[0]
If $showProgress=True And Mod($rc,500)=0 Then _
SplashTextOn("","Processing Strings (" & _Min(99,Floor(100*$rc/$stringsUsed[0])) & "% done)...",300,40,-1,-1,1+32,"Verdana",10)
If StringLen($stringsUsed[$rc])<3 Then ContinueLoop ; two chars used for quotes
$curstring=StringTrimLeft(StringTrimRight($stringsUsed[$rc],1),1) ; clip quotes
; scan for <entire string> = <UDFname without "(...)">
$index=_ArraySearch($functionsUsed,$curstring,1)
If $index>0 Then
$stringsUsed[$rc]=StringLeft($stringsUsed[$rc],1) & "{funcU" & $index & "}" & StringRight($stringsUsed[$rc],1) ; working assumption here is that a func-ref is intended, not a literal string for output
_ArrayAdd($FuncEqualsString,$curstring,0,Chr(0))
; for safety, we'll include these func defs (possibly called); NB CodeScanner will have missed these calls
If _ArraySearch($functionsCalled,$curstring,1)<1 Then _
_ArrayAdd($functionsCalled,$curstring,0,Chr(0))
ElseIf _ArraySearch($skipRegExpStrings,$rc,1)<1 Then ; skip regexp patterns
$stringsUsed[$rc]=_MCWords($stringsUsed[$rc])
EndIf
Next
_FileWriteFromArray($CS_dumppath & "stringsUsed.txt",$stringsUsed,1)
$stringsTransl=$stringsUsed
FileCopy($CS_dumppath & "stringsUsed.txt",$CS_dumppath & "stringsTransl.txt",1)
SplashOff()
; recursively add all additional funcU calls
If $uselogfile Then _FileWriteLog($fhlog,$procname & ": processing UDF calls...")
$FunctionsCalled[0]=UBound($FunctionsCalled)-1
$rc=$FunctionsCalled_CS[0]+1
While $rc<=UBound($FunctionsCalled)-1
$curdefunc=$FunctionsCalled[$rc]
$funcdef_ID=_ArraySearch($functionsDefined,$curdefunc)
If $funcdef_ID>0 Then
$split=StringSplit($MCinFuncDef[$funcdef_ID],"{") ; lookup all MCtags in this func def
For $cc=2 To $split[0]
If StringLeft($split[$cc],5)="funcU" Then
$func_ID=StringTrimLeft($split[$cc],5)
$curfunc=$FunctionsUsed[$func_ID]
If _ArraySearch($functionsCalled,$curfunc)<1 Then
_ArrayAdd($functionsCalled,$curfunc,0,Chr(0))
_ArrayAdd($FuncEqualsString,$curfunc,0,Chr(0))
EndIf
EndIf
Next
EndIf
$rc+=1
WEnd
$FunctionsCalled[0]=UBound($FunctionsCalled)-1
$FuncEqualsString[0]=UBound($FuncEqualsString)-1
Global $already_included[1]
$newfile=$CS_dumppath & "MCF0.txt"
Global $fhout=FileOpen($newfile,2)
If @error Or $fhout=-1 Then Return SetError(_ErrorHandler(-2,"opening file " & $newfile,$procname),$newfile,False)
FileWrite($fhout,$dumptag)
$timestamp="; This Single-Build "& $timestamptag & @YEAR& "-" & @MON & "-" & @MDAY & ", at " & @HOUR & ":" & @MIN& ":" & @SEC
FileWriteLine($fhout,$timestamp & @CRLF & ";" & _StringRepeat("=",StringLen($timestamp)-1))
; recursive call builds MCF0.txt, inserting all #includes
$totalines=0
If $uselogfile Then _FileWriteLog($fhlog,$procname & ": writing MCF0.txt...")
If _WriteMCF0(1)=False Then Return SetError(_ErrorHandler(-3,"recursive call to _WriteMCF0() failed",$procname),@error,False)
FileClose($fhout)
If $uselogfile Then _FileWriteLog($fhlog,$procname & ": MCF0.txt written.")
$already_included=0
; final totals
$macrosUsed[0] =UBound($macrosUsed)-1
$variablesUsed[0] =UBound($variablesUsed)-1
$globalsredundant[0] =UBound($globalsredundant)-1
$functionsUsed[0] =UBound($functionsUsed)-1
$functionsCalled[0] =UBound($functionsCalled)-1
If $showProgress=True Then SplashTextOn("","Post-Processing Variables...",250,40,-1,-1,1+32,"Verdana",10)
_FileWriteFromArray($CS_dumppath & "variablesUsed.txt",$variablesUsed,1)
_FileWriteFromArray($CS_dumppath & "macrosUsed.txt",$macrosUsed,1)
If $showProgress=True Then SplashTextOn("","Post-Processing Functions...",250,40,-1,-1,1+32,"Verdana",10)
_FileWriteFromArray($CS_dumppath & "FunctionsUsed.txt",$FunctionsUsed,1)
_FileWriteFromArray($CS_dumppath & "FunctionsCalled.txt",$functionsCalled,1)
_FileWriteFromArray($CS_dumppath & "FuncEqualsString.txt",$FuncEqualsString,1)
; file HAS to exist, but may be empty
$curfile=$CS_dumppath & "FuncEqualsString.txt"
If Not FileExists($curfile) Then _FileCreate($curfile)
If $MCF_REMOVE_ORPHANS=True Then
If $uselogfile Then _FileWriteLog($fhlog,$procname & ": removing orphans...")
If _RemoveOrphans($CS_dumppath)=False Then
$err=@error
SplashOff()
Return SetError(_ErrorHandler(-4,"call to _RemoveOrphans() failed",$procname),$err,false)
EndIf
If $uselogfile Then _FileWriteLog($fhlog,$procname & ": orphans removed.")
EndIf
; create all post-processing buffers
_ClearArrays($CS_dumppath)
If $uselogfile Then _FileWriteLog($fhlog,$procname & " finished." & @CRLF & @CRLF)
_CallStack_Pop($procname)
Return True
EndFunc
Func _MCWords($curline,$isCall=False)
; replace vars, macros, AU3 / UDF calls
If $curline="" Then Return $curline
$split=StringSplit($curline,"$")
If Not @error Then
For $cc=2 To $split[0]
If StringStripWS($split[$cc],1+2)="" Then
$split[$cc]="$" ; restore
ContinueLoop ; skip "$"
EndIf
; replace each char that cannot be part of a varname with space
$curvar=StringRegExpReplace($split[$cc],"[^a-zA-Z0-9_]"," ",1) & " " ; added space suffix
$pos=StringInStr($curvar," ")-1 ; always found (added suffix)
If $pos=0 Then
$split[$cc]="$" & $split[$cc] ; restore
ContinueLoop ; not a varname
EndIf
$curvar="$" & StringLeft($curvar,$pos)
$nextchars=StringTrimLeft($split[$cc],$pos)
If StringLeft($nextchars,1)="(" Or StringMid($nextchars,2,1)="(" Then
$split[$cc]="$" & $split[$cc] ; restore
ContinueLoop ; skip functions with $-prefix
EndIf
$index=_ArraySearch($variablesUsed,$curvar,1)
If $index>0 Then
$split[$cc]="{var" & $index & "}" & $nextchars
Else
_ArrayAdd($variablesUsed,$curvar,0,Chr(0))
$split[$cc]="{var" & UBound($variablesUsed)-1 & "}" & $nextchars
$index=_ArraySearch($globalsredundant,$curvar,1)
If $index>0 Then _ArrayDelete($globalsredundant,$index)
EndIf
Next
$curline=_ArrayToString($split,"",1)
EndIf
; extract all macros
$split=StringSplit($curline,"@")
If Not @error Then
For $cc=2 To $split[0]
; replace each char that cannot be part of a macroname with space
$curmacro=StringRegExpReplace($split[$cc],"[^a-zA-Z0-9_]"," ",1) & " "
$curmacro="@" & StringLeft($curmacro,StringInStr($curmacro," ")-1)
$index=_ArraySearch($macros,$curmacro,1)
If $index>0 Then
If _ArraySearch($macrosUsed,$curmacro,1)<1 Then _ArrayAdd($macrosUsed,$curmacro,0,Chr(0))
$split[$cc]="{macro" & $index & "}" & StringTrimLeft($split[$cc],StringLen($curmacro)-1)
Else
$split[$cc]="@" & $split[$cc] ; restore
EndIf
Next
$curline=_ArrayToString($split,"",1)
EndIf
; function names parsed as string parameter (without "(...)") are caught in string processing
$split=StringSplit($curline,"(")
For $cc=2 To $split[0]
$previousword=$split[$cc-1]
$prefix=""
For $rc=StringLen($previousword) To 1 Step -1
If $validprefix[Asc(StringMid($previousword,$rc,1))]=True Then
$prefix=StringLeft($previousword,$rc)
$previousword=StringStripWS(StringTrimLeft($previousword,$rc),1+2)
ExitLoop
EndIf
Next
If StringLeft($previousword,5)<>"{func" And $previousword<>"" Then
$index=_ArraySearch($AU3functions,$previousword,1)
If $index>0 Then
$split[$cc-1]=$prefix & "{funcA" & $index & "} "
Else
$index=_ArraySearch($functionsUsed,$previousword,1)
If $index<1 And $isCall=True Then
_ArrayAdd($functionsUsed,$previousword,0,Chr(0))
$index=UBound($functionsUsed)-1
EndIf
If $index>0 Then
$split[$cc-1]=$prefix & "{funcU" & $index & "} "
If $isCall=True Then
$index=_ArraySearch($functionsCalled,$previousword,1)
If $index<1 Then _ArrayAdd($functionsCalled,$previousword,0,Chr(0))
EndIf
EndIf
EndIf
EndIf
Next
$curline=_ArrayToString($split,"(",1)
Return $curline
EndFunc
Func _RemoveOrphans($path,$force_refresh=False)
$procname="_RemoveOrphans"
_CallStack_Push($procname)
; environment checks/prep
If $force_refresh=True Then
If _PrepMCenvironment($path,$force_refresh)=False Then Return SetError(_ErrorHandler(-1,"preparing MCF environment",$procname),0,False)
Else
If _FillCSpath($path,$force_refresh)=False Then Return SetError(_ErrorHandler(-2,"preparing MCF environment",$procname),0,false)
EndIf
$pass=0
$varorphans=0
$keepscanning=True
While $keepscanning ; iterative, because global A,B,C... may occur once each, but be defined A=1,B=A,C=B, etc.
$pass+=1
Local $funcalled[1]
Local $funcorphans[1]
Local $varonce[1]
Local $vartwice[1]
$inputfile=$CS_dumppath & "MCF0.txt"
If Not FileExists($inputfile) Then Return SetError(_ErrorHandler(-3,"file not found:" & @CR & $inputfile,$procname),0,False)
$fhin=FileOpen($inputfile)
If @error Or $fhin=-1 Then Return SetError(_ErrorHandler(-4,"opening file " & $inputfile,$procname),$inputfile,False)
$tmpfile=$CS_dumppath & "MCF0tmp.txt"
$fh=FileOpen($tmpfile,2)
If @error Or $fh=-1 Then
FileClose($fhin)
Return SetError(_ErrorHandler(-5,"opening file " & $tmpfile,$procname),$tmpfile,False)
EndIf
$linesdone=0
$prevlineblank=false
If $showProgress=True Then SplashTextOn("","Identifying Orphans, pass "&$pass&"...",350,40,-1,-1,1+32,"Verdana",10)
While True
$curline=FileReadLine($fhin)
If @error Then ExitLoop
$curline=StringStripWS($curline,1+2)
$linesdone+=1
If $showProgress=True And Mod($linesdone,500)=0 And $totalines>0 Then _
SplashTextOn("","Identifying Orphans, pass "& $pass&" (" & _Min(99,Floor(100*$linesdone/($totalines))) & "% done)...",350,40,-1,-1,1+32,"Verdana",10)
; empty line
If $curline="" Then
If $prevlineblank=False Then
FileWriteLine($fh,"")
$prevlineblank=True
EndIf
ContinueLoop
EndIf
$prevlineblank=false
; pure comment line
If StringLeft($curline,1)=";" Then
FileWriteLine($fh,$curline)
ContinueLoop
EndIf
; clip comments
$commentail=" "
$pos0=Stringinstr($curline,";",0,-1)
If $pos0>0 Then
$commentail&=StringTrimLeft($curline,$pos0-1)
$curline=StringLeft($curline,$pos0-1)
EndIf
; scan everywhere
$newline=_MCWords($curline)
If StringInStr($newline,"{var") Then
$split=StringSplit($newline,"{var",1)
For $rc=2 To $split[0]
$pos=StringInStr($split[$rc],"}")
If $pos>0 Then
$curvar="{var" & StringLeft($split[$rc],$pos)
$index=_ArraySearch($varonce,$curvar,1)
If $index<1 Then ; found once
_ArrayAdd($varonce,$curvar,0,Chr(0))
Else ; found again
If _ArraySearch($vartwice,$index,1)<1 Then _ArrayAdd($vartwice,$index,0,Chr(0))
EndIf
EndIf
Next
EndIf
If StringInStr($newline,"{funcU") Then
$split=StringSplit($newline,"{funcU",1)
For $rc=2 To $split[0]
If $rc=2 And StringLeft($split[1],5)="Func " Then ContinueLoop
$pos=StringInStr($split[$rc],"}")
If $pos>0 Then
$curfuncindex=StringLeft($split[$rc],$pos-1)
If _ArraySearch($funcalled,$curfuncindex,1)<1 Then _ArrayAdd($funcalled,$curfuncindex,0,Chr(0))
EndIf
Next
EndIf
FileWriteLine($fh, $newline& $commentail)
WEnd
FileClose($fhin)
FileClose($fh)
Sleep(250)
_ArraySort($vartwice)
For $rc=UBound($vartwice)-1 To 1 Step -1
_arraydelete($varonce,$vartwice[$rc])
Next
$varonce[0]=UBound($varonce)-1
$funcalled[0]=UBound($funcalled)-1
For $rc=1 To $funcalled[0]
$funcalled[$rc]=$functionsUsed[$funcalled[$rc]] ; replace with UDF name
Next
For $rc=$functionsCalled[0] To 1 Step -1
$curfunc=$functionsCalled[$rc]
If _ArraySearch($funcalled,$curfunc)<1 And _ArraySearch($FuncEqualsString,$curfunc)<1 Then
_ArrayDelete($functionsCalled,$rc)
$index=_ArraySearch($functionsUsed,$curfunc)
If $index>0 Then _ArrayAdd($funcorphans,"{funcU" & $index & "}",0,Chr(0))
EndIf
Next
$funcorphans[0]=UBound($funcorphans)-1
$FunctionsCalled[0]=UBound($FunctionsCalled)-1
$keepscanning=($varonce[0]>$varorphans Or $funcorphans[0]>0)
$varorphans=$varonce[0]
; replace target with tmp
$fh=FileOpen($inputfile,2)
If @error Or $fh=-1 Then Return SetError(_ErrorHandler(-6,"opening file " & $inputfile,$procname),$inputfile,False)
$fhin=FileOpen($tmpfile)
If @error Or $fhin=-1 Then
FileClose($fh)
Return SetError(_ErrorHandler(-7,"opening file " & $tmpfile,$procname),$tmpfile,False)
EndIf
$linesdone=0
$prevlineblank=false
$skiporphanfuncdef=False
While True
$curline=FileReadLine($fhin)
If @error Then ExitLoop
$linesdone+=1
If $showProgress=True And Mod($linesdone,500)=0 And $totalines>0 Then _
SplashTextOn("","Removing " & $varonce[0]+$funcorphans[0] & " Orphans (" & _Min(99,Floor(100*$linesdone/($totalines))) & "% done)...",300,40,-1,-1,1+32,"Verdana",10)
; empty line
If StringStripWS($curline,1+2)="" Then
If $prevlineblank=False Then
FileWriteLine($fh,"")
$prevlineblank=True
EndIf
ContinueLoop
EndIf
$prevlineblank=false
; early-out(put)
If StringLeft($curline,1)=";" Then
FileWriteLine($fh,$curline)
ContinueLoop
EndIf
If StringLeft($curline,7)="EndFunc" Then
$tmp=$skiporphanfuncdef
$skiporphanfuncdef=False
If $tmp=True Then ContinueLoop
EndIf
If StringLeft($curline,5)="Func " Then
$pos1=StringInStr($curline,"{funcU")
$pos2=stringinstr($curline,"}")
If $pos1*$pos2>0 Then
$curfunc=StringMid($curline,$pos1,1+$pos2-$pos1)
If _ArraySearch($funcorphans,$curfunc)>0 Then $skiporphanfuncdef=True
EndIf
EndIf
; skip writing out this func def (omit from output)
If $skiporphanfuncdef=True Then ContinueLoop
; scan global defs for our orphan vars
If (StringLeft($curline,7)="Global " And StringMid($curline,8,5)<>"Enum ") Then
$pos1=StringInStr($curline,"{var")
If $pos1>0 Then
$pos2=StringInStr($curline,"}",$pos1)
$pos3=StringInStr($curline,"=")
If $pos2>0 And ($pos3<1 Or $pos3>$pos2) Then
$curvar=StringMid($curline,$pos1,1+$pos2-$pos1)
; skip writing out this global def (omit from output)
If _ArraySearch($varonce,$curvar,1)>0 Then ContinueLoop
EndIf
EndIf
EndIf
FileWriteLine($fh, $curline)
WEnd
$totalines=$linesdone
FileClose($fhin)
FileClose($fh)
Sleep(250)
If FileExists($tmpfile) Then FileDelete($tmpfile)
$totalines=$linesdone
WEnd ; keepscanning
SplashOff()
; store updated list
_FileWriteFromArray($CS_dumppath & "functionsCalled.txt",$functionsCalled,1)
_CallStack_Pop($procname)
Return True
EndFunc
Func _WriteMCF0($file_ID) ; create MFC0.txt from MCF#.txt (#: 1-N)
$procname="_WriteMCF0"
_CallStack_Push($procname)
If $file_ID<1 Or $file_ID>$includes[0] Then Return SetError(_ErrorHandler(-1,"file ID out of bounds: " & $file_ID,$procname),$file_ID,False)
$mcfname="mcf" & $file_ID & ".txt"
$curfile=$CS_dumppath & $mcfname
If Not FileExists($curfile) Then Return SetError(_ErrorHandler(-2,"MetaCode file not found:"& @CR & $mcfname,$procname),$file_ID,False)
$original_filename=$includes[$file_ID]
If _ArraySearch($includeonce,$original_filename,1)>0 And _
_ArraySearch($already_included,$original_filename,1)>0 Then
_CallStack_Pop($procname)
Return True
EndIf
_ArrayAdd($already_included,$original_filename,0,Chr(0))
If $showProgress=True Then SplashTextOn("","Processing " & StringUpper($mcfname) & "...",250,40,-1,-1,1+32,"Verdana",10)
Local $fh=FileOpen($curfile)
If @error Or $fh=-1 Then Return SetError(_ErrorHandler(-3,"opening file " & $curfile,$procname),$file_ID,false)
$enumerations=0
$totalenumerations=0
$enumeratedList=""
$prevenumerating=False
$prevcommentail=""
$insidefuncdef=0
$skipfuncdef=False
While True
$enumerating=False
$curline=FileReadLine($fh)
If @error Then ; eof?
FileClose($fh)
FileWriteLine($fhout,$enumeratedlist & $prevcommentail & @CRLF) ; fail-safe; these stringvars should both be empty
$totalines+=1
ExitLoop
EndIf
$skipwrite=False
$pos1=Stringinstr($curline,"{incl")
If $pos1>0 Then
$pos2=Stringinstr($curline,"}",0,1,$pos1+5)
$incl_ID=StringMid($curline,$pos1+5,$pos2-$pos1-5)
FileWriteLine($fhout,@CRLF)
$totalines+=1
_WriteMCF0($incl_ID) ; recursive call
ContinueLoop
EndIf
If StringLeft($curline,7)="EndFunc" Then
$skipwrite=$skipfuncdef
$skipfuncdef=False
$insidefuncdef=0
$curline&=@CRLF ; add blank line after endfunc def
EndIf
If StringLeft($curline,5)="Func " Then
$pos1=Stringinstr($curline,"{func")
$pos2=Stringinstr($curline,"}",0,1,$pos1+5)
$func_ID=StringMid($curline,$pos1+6,$pos2-$pos1-6)
If $func_ID>$FunctionsUsed[0] Then Return SetError(_ErrorHandler(-1,"unrecognised UDF function index " & $func_ID,$procname),$file_ID,False)
If _ArraySearch($FunctionsCalled,$functionsUsed[$func_ID],1)<1 Then $skipfuncdef=$MCF_SKIP_UNCALLED_UDFS
$curline=@CRLF & $curline ; add blank line before func def
$insidefuncdef=1
EndIf
; do not write out func defs that are not called, unless forced
If ($skipfuncdef Or $skipwrite)=True Then ContinueLoop
; remove "{none}" from parameter-less function calls and global defs
$curline=StringReplace($curline,"{none}"," ")
$commentail=" "
$pos0=Stringinstr($curline,";",0,-1)
If $pos0=0 Then
$pos0=StringLen($curline)
Else
$commentail&=StringTrimLeft($curline,$pos0-1)
EndIf
; remove undesired infix spaces
$split=StringSplit(StringLeft($curline,$pos0-1),"")
If $split[0]>2 Then
$newline=$split[1]
For $cc=2 To $split[0]-1
; scientific notation (#E + #)
If $cc>2 And $cc<$split[0]-1 And ($split[$cc]="+" Or $split[$cc]="-") Then
If $split[$cc-2]="E" And $split[$cc-1]=" " Then $split[$cc-1]=""
If ($split[$cc-2]="E" Or $split[$cc-1]="E") And $split[$cc+1]=" " Then $split[$cc+1]=""
EndIf
; operator pairs (e.g., "> =", "< >", etc.)
If Not ($validprefix[Asc($split[$cc-1])]=True And _
$validprefix[Asc($split[$cc+1])]=True And _
$split[$cc]=" ") Then $newline&=$split[$cc]
Next
$curline=$newline
EndIf
If StringLeft($curline,7)="Global " Then
$insertPrefix=""
Select
Case StringMid($curline,8,6)="Const "
$insertPrefix="Const "
Case StringMid($curline,8,5)="Enum " ; can be none or either one, but not both
$enumerating=True
$insertPrefix="Enum "
If StringLeft($curline,13)="Step " Then
$pos=StringInStr($curline," ",14)
If $pos>0 Then $insertPrefix&=StringLeft($curline,$pos-1)
EndIf
EndSelect
$pos1=Stringinstr($curline,"$*")
$pos2=Stringinstr($curline,"[")
$pos4=Stringinstr($commentail,"{ref")
$pos5=Stringinstr($commentail,"}",0,-1)
; get refcontents
$refrec=StringMid($commentail,$pos4+4,$pos5-$pos4-4)
$var=$references[$refrec][4]
If $pos2>0 Then $var=StringLeft($var,StringInStr($var,"[")-1) ; clip any array dims for redundancy scan
; filter out redundant globals
; this misses globals used only to define other redundant globals; these should be caught in _RemoveOrphans()
If _ArraySearch($globalsredundant,$var,1)>0 And $enumerating=False Then ContinueLoop
$MCtag=_MCWords($var)
; build Orphans list (to be pruned later)
If $enumerating=False Then
If _ArraySearch($globalsOrphaned,$var,1)<1 Then
$pos=StringInStr($MCtag,"[")
If $pos<1 Then
_ArrayAdd($globalsOrphaned,$MCtag,0,Chr(0))
Else
_ArrayAdd($globalsOrphaned,StringStripWS(StringLeft($MCtag,$pos-1),2),0,Chr(0))
EndIf
EndIf
EndIf
$posequal=Stringinstr($curline,"=")
If $posequal>0 Then $curline=StringLeft($curline,$posequal) ; clip any square brackets after an equal-sign, if present
$pos3=Stringinstr($curline,"]",0,-1)
$insertdims=" "
If $pos2*$pos3>0 Then $insertdims=StringMid($curline,$pos2,$pos3-$pos2+1) & " "
$params=StringStripWS($references[$refrec][5],1+2)
If $params="" Or $params="{none}" Then
$curline=$MCtag & $insertdims
Else
; any called funcs here should already be stored, either through CS:TrackCalls or through MCF:string processing
$curline=$MCtag & $insertdims & "= " & _MCWords($params,True) ; param2 = IsCall
EndIf
; rebuild Enum list as single line
Select
Case $enumerating=False And $prevenumerating=False ; default, most common case
$curline="Global " & $insertPrefix & $curline
Case $enumerating=True And $prevenumerating=False ; just started
$enumeratedList="Global " & $insertPrefix & $curline
; determine number of comma-separated Enum entries on the original line
$enumerations=1
$totalenumerations=1
$curinclude=$references[$refrec][1]
$linenr=$references[$refrec][2]
For $cc=$refrec+1 To $references[0][0]
If $linenr<>$references[$cc][2] Or $curinclude<>$references[$cc][1] Then ExitLoop
If StringLeft($references[$cc][3],11)="Global Enum" Then $totalenumerations+=1
Next
$prevcommentail=$commentail
$prevenumerating=True
If $enumerations<$totalenumerations Then ContinueLoop ; defer writing out
$curline=$enumeratedList
$enumerating=False ; done with this list
Case ($enumerating=True And $prevenumerating=True) ; still accumulating
$enumeratedList&=", " & $curline ; rebuild single line
$enumerations+=1
$prevcommentail=$commentail
If $enumerations<$totalenumerations Then ContinueLoop ; defer writing out
$curline=$enumeratedList
$enumerating=False ; done with this list
Case ($enumerating=False And $prevenumerating=True) ; encountered something else
$curline=$enumeratedList & $prevcommentail & @CRLF & $curline ; fail-safe, should never happen
EndSelect
EndIf
FileWriteLine($fhout,$curline & $commentail)
$totalines+=1
If $insidefuncdef>0 Then $insidefuncdef+=1
$enumeratedList=""
$totalenumerations=0
$enumerations=0
$prevenumerating=$enumerating
$prevcommentail=""
WEnd
_CallStack_Pop($procname)
Return True
EndFunc
#endregion Input-related
#region Structure-altering
Func _IndirectMCF($path,$inputfile="MCF0.txt",$outputfile="MCF0_indirected.txt")
; replace all variable assignments with their equivalent MCFinclude call
$procname="_IndirectMCF"
_CallStack_Push($procname)
; for skipping lines from MCFinclude.au3
$marker="{file:" & $MCF_file_ID & "}"
Local $indirectcall[7]
$indirectcall[0]=UBound($indirectcall)-1
For $cc=1 To $indirectcall[0]
$indirectcall[$cc]=""
Next
; create a lookup table
For $rc=1 To $functionsUsed[0]
Switch $functionsUsed[$rc]
Case "_VarIsVar"