-
Notifications
You must be signed in to change notification settings - Fork 0
/
clcache.c
2310 lines (1822 loc) · 58.8 KB
/
clcache.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
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#include <shellapi.h>
#include <ShlObj.h>
#pragma comment(lib, "kernel32.lib")
#pragma comment(lib, "shell32.lib")
#pragma comment(lib, "Version.lib")
#ifdef NO_CRT
int _fltused;
#pragma intrinsic(memset,memcpy,memmove,_byteswap_ulong,_byteswap_uint64)
#endif
#pragma warning(push, 0)
#define XXH_INLINE_ALL
#include "xxhash/xxhash.h"
#pragma warning(pop)
/*
* TODO:
* - Clean up code
* - stats (cache hits, misses etc.)
* - shorten cache path (8 nested directories seems a little too much)
* - clean up old cache entries
* - if an error occurs like not being able to read a file, just invoke the compiler and don't call FatalError
*/
/*
* Macros
*/
#ifdef NDEBUG
#define ASSERT(expr) (void)(0)
#else
#define ASSERT(expr) \
if(!(expr)) \
*(volatile int*)NULL = 0
#endif
#define KILOBYTES(x) ((x) * 1024ULL)
#define MEGABYTES(x) (KILOBYTES(x) * 1024ULL)
#define GIGABYTES(x) (MEGABYTES(x) * 1024ULL)
#define IS_POW2(x) ((x) && !((x) & ((x) - 1)))
#define ALIGN_POW2(val, align) (((val) + (align) - 1) & ~((align) - 1))
#define ALIGNOF(type) offsetof(struct{ char c; type d; }, d)
/*
* Constants
*/
#define INVALID_INDEX (-1)
#define MAX_COMMAND_LINE_LENGTH 32768
#define DEFAULT_CACHE_SIZE GIGABYTES(20)
#define CACHE_PATH_LENGTH 60 // Length of path to a cached file within .clcache dir (not exact, used to check against MAX_PATH)
/*
* Structs
*/
struct cstring{
const char* Data;
size_t Length;
};
#define CSTR(str) (struct cstring){str, sizeof(str) - 1}
struct string{
const WCHAR* Data;
size_t Length;
};
#define STR(str) (struct string){L ## str, sizeof(L ## str) / sizeof(WCHAR) - 1}
struct string_list{
struct string* Strings;
size_t Count;
};
struct string_buffer{
LPWSTR Data;
size_t Size;
size_t Used;
};
struct index_hash{
int* HashIndices;
int* Indices;
unsigned int HashCount;
unsigned int IndexCount;
};
struct cache_config{
BOOL UseStderr; // cl.exe writes warnings and errors to stdout this is optionally redirected to stderr by clcache
UINT64 CacheSize;
WCHAR CachePath[MAX_PATH];
};
struct cache_info{
UINT64 SizeUsed;
UINT32 Hits;
UINT32 Misses;
};
struct memory_arena{
void* Memory;
size_t Size;
size_t Used;
size_t PrevUsed;
};
struct cl_command_info{
struct string Executable;
UINT64 ClVersion;
BOOL NoLogo;
BOOL GeneratesPdb;
struct string ObjFile;
struct string PdbFile;
struct string SrcFile;
struct string_list CompilerFlags;
struct string_list IncludePaths;
struct string_list ExternalIncludePaths;
struct string_list SystemIncludePaths;
};
#define INCLUDE_FILE_LOCAL 1
#define INCLUDE_FILE_EXTERNAL 2
#define INCLUDE_FILE_SYSTEM 3
struct dependency_entry{
UINT64 IncludePathType;
UINT64 Size;
UINT64 LastModified;
UINT64 Hash;
struct string FileName;
};
struct dependency_info{
UINT32 EntryCount;
struct dependency_entry* Entries;
};
/*
* Globals
*/
HANDLE g_StdoutHandle;
HANDLE g_StderrHandle;
WCHAR g_ConfigFilePath[MAX_PATH];
struct cache_config g_Config;
/*
* Helpers
*/
static UINT32 NextPowerOfTwo(UINT32 V)
{
V--;
V |= V >> 1;
V |= V >> 2;
V |= V >> 4;
V |= V >> 8;
V |= V >> 16;
V++;
return V + (V == 0);
}
static UINT32 PreviousPowerOfTwo(UINT32 V)
{
V = NextPowerOfTwo(V);
if(V != 1) /* We don't want this to create super high values when v == 1 */
V >>= 1;
return V;
}
static UINT32 NearestPowerOfTwo(UINT32 V)
{
UINT32 a = PreviousPowerOfTwo(V);
UINT32 b = NextPowerOfTwo(V);
return (V - a) < (b - V) ? a : b;
}
/*
* Output
*/
static void WriteStdout(struct cstring Str)
{
DWORD NumBytesWritten;
WriteFile(g_StdoutHandle, Str.Data, (DWORD)Str.Length, &NumBytesWritten, NULL);
}
static void WriteStderr(struct cstring Str)
{
DWORD NumBytesWritten;
WriteFile(g_StderrHandle, Str.Data, (DWORD)Str.Length, &NumBytesWritten, NULL);
}
/*
* Error
*/
static __declspec(noreturn) void FatalError(struct cstring Msg)
{
WriteStderr(CSTR("ERROR: "));
WriteStderr(Msg);
WriteStderr(CSTR("\n"));
ExitProcess(1);
}
/*
* Memory
*/
static struct memory_arena CreateMemory(size_t Size)
{
struct memory_arena Arena;
// No need to free this. Just let the OS clean it all up when the process exits...
Arena.Memory = VirtualAlloc(NULL, Size, MEM_COMMIT, PAGE_READWRITE);
if(!Arena.Memory)
FatalError(CSTR("Failed to allocate virtual memory"));
Arena.Size = Size;
Arena.Used = 0;
Arena.PrevUsed = 0;
return Arena;
}
static void* PushMem(struct memory_arena* Arena, size_t Size)
{
if(Arena->Used + Size > Arena->Size)
FatalError(CSTR("Out of memory"));
void* Mem = (BYTE*)Arena->Memory + Arena->Used;
Arena->PrevUsed = Arena->Used;
Arena->Used += Size;
Arena->Used = ALIGN_POW2(Arena->Used, MEMORY_ALLOCATION_ALIGNMENT);
return Mem;
}
static void PopMem(struct memory_arena* Arena)
{
if(Arena->PrevUsed > 0)
{
Arena->Used = Arena->PrevUsed;
Arena->PrevUsed = 0;
}
}
static void PopPartialMem(struct memory_arena* Arena, size_t Size)
{
if(Size < Arena->Used && Arena->Used - Size >= Arena->PrevUsed)
{
Arena->Used -= Size;
Arena->Used = ALIGN_POW2(Arena->Used, MEMORY_ALLOCATION_ALIGNMENT);
Arena->PrevUsed = 0;
}
}
/*
* String
*/
static BOOL IsWhitespace(WCHAR C){ return C == ' ' || C == '\t' || C == '\n' || C == '\r'; }
static BOOL IsAlpha(WCHAR C){ return (C >= 'A' && C <= 'Z') || (C >= 'a' && C <= 'z'); };
static BOOL IsDigit(WCHAR C){ return C >= '0' && C <= '9'; }
static BOOL IsPathSeparator(WCHAR C){ return C == '\\' || C == '/'; }
static struct cstring MakeCString(const char* Data, size_t Length)
{
struct cstring Result;
Result.Data = Data;
Result.Length = Length;
return Result;
}
static struct string MakeString(const WCHAR* Data, size_t Length)
{
struct string Result;
Result.Data = Data;
Result.Length = Length;
return Result;
}
static struct string_buffer MakeStringBuffer(WCHAR* Data, size_t Size)
{
struct string_buffer Result;
Result.Data = Data;
Result.Size = Size;
Result.Used = 0;
return Result;
}
static LPWSTR PushChars(size_t Count, struct string_buffer* Buffer)
{
ASSERT(Buffer->Used + Count + 1 <= Buffer->Size);
LPWSTR Result = Buffer->Data + Buffer->Used;
Buffer->Used += Count;
Buffer->Data[Buffer->Used] = '\0';
return Result;
}
static struct string PushString(struct string Str, struct string_buffer* Buffer)
{
struct string Result;
Result.Data = CopyMemory(PushChars(Str.Length, Buffer), Str.Data, Str.Length * sizeof(WCHAR));
Result.Length = Str.Length;
return Result;
}
static void PushStringWithEscapedQuotes(struct string Str, struct string_buffer* Buffer)
{
struct string Temp = Str;
Temp.Length = 0;
for(size_t i = 0; i < Str.Length; ++i)
{
if(Str.Data[i] == '\"')
{
PushString(Temp, Buffer);
PushString(STR("\\\""), Buffer);
Temp = MakeString(Str.Data + i + 1, 0);
}
else
{
++Temp.Length;
}
}
PushString(Temp, Buffer);
}
static void PushCmdLineArg(struct string Flag, struct string Arg, struct string_buffer* Buffer)
{
if(Buffer->Used > 0 && !IsWhitespace(Buffer->Data[Buffer->Used]))
PushString(STR(" \""), Buffer);
else
PushString(STR("\""), Buffer);
PushStringWithEscapedQuotes(Flag, Buffer);
if(Arg.Length > 0)
PushStringWithEscapedQuotes(Arg, Buffer);
PushString(STR("\""), Buffer);
}
static struct cstring StringFromChar(const char* Str)
{
struct cstring Result;
Result.Data = Str;
Result.Length = lstrlenA(Str);
return Result;
}
static struct string StringFromWchar(LPCWSTR Str)
{
struct string Result;
Result.Data = Str;
Result.Length = lstrlenW(Str);
return Result;
}
static struct string TrimStringLeft(struct string Str)
{
while(Str.Length > 0 && IsWhitespace(Str.Data[0]))
{
++Str.Data;
--Str.Length;
}
return Str;
}
static struct string TrimStringRight(struct string Str)
{
while(Str.Length > 0 && IsWhitespace(Str.Data[Str.Length - 1]))
--Str.Length;
return Str;
}
static struct string TrimString(struct string Str)
{
return TrimStringRight(TrimStringLeft(Str));
}
static struct string StringLeft(struct string Str, size_t Count)
{
Str.Length = min(Str.Length, Count);
return Str;
}
static struct string StringRight(struct string Str, size_t Count)
{
size_t Length = min(Str.Length, Count);
Str.Data += Str.Length - Length;
Str.Length = Length;
return Str;
}
static struct string StringMid(struct string Str, size_t Index, size_t Count)
{
if(Index >= Str.Length)
return MakeString(Str.Data + Str.Length, 0);
Str.Data += Index;
Str.Length = Str.Length - Index;
Str.Length = min(Str.Length, Count);
return Str;
}
static int CompareStrings(struct string S1, struct string S2)
{
return CompareStringOrdinal(S1.Data, (int)S1.Length, S2.Data, (int)S2.Length, FALSE) - 2;
}
static int CompareStringsCaseInsensitive(struct string S1, struct string S2)
{
return CompareStringOrdinal(S1.Data, (int)S1.Length, S2.Data, (int)S2.Length, TRUE) - 2;
}
static BOOL StringsAreEqual(struct string S1, struct string S2)
{
return S1.Length == S2.Length && CompareStringOrdinal(S1.Data, (int)S1.Length, S2.Data, (int)S2.Length, FALSE) == CSTR_EQUAL;
}
static BOOL StringsAreEqualCaseInsensitive(struct string S1, struct string S2)
{
return S1.Length == S2.Length && CompareStringOrdinal(S1.Data, (int)S1.Length, S2.Data, (int)S2.Length, TRUE) == CSTR_EQUAL;
}
static BOOL StringStartsWith(struct string Str, struct string Start)
{
return Start.Length <= Str.Length && StringsAreEqual(StringLeft(Str, Start.Length), Start);
}
static BOOL StringStartsWithCaseInsensitive(struct string Str, struct string Start)
{
return Start.Length <= Str.Length && StringsAreEqualCaseInsensitive(StringLeft(Str, Start.Length), Start);
}
static BOOL StringEndsWith(struct string Str, struct string End)
{
return End.Length <= Str.Length && StringsAreEqual(StringRight(Str, End.Length), End);
}
static BOOL StringEndsWithCaseInsensitive(struct string Str, struct string End)
{
return End.Length <= Str.Length && StringsAreEqualCaseInsensitive(StringRight(Str, End.Length), End);
}
static UINT64 StringToUINT64(struct string Str)
{
while(Str.Length > 0 && IsWhitespace(Str.Data[Str.Length - 1]))
{
++Str.Data;
--Str.Length;
}
UINT64 Result = 0;
while(Str.Length && IsDigit(*Str.Data))
{
UINT64 OverflowCheck = Result;
Result *= 10;
if(Result < OverflowCheck)
return 0;
Result += *Str.Data - '0';
++Str.Data;
--Str.Length;
}
return Result;
}
static struct cstring UINT64ToCString(UINT64 Value, char* Buffer)
{
size_t DigitCount = 1;
for(UINT64 i = 10; i <= Value; i *= 10)
++DigitCount;
for(size_t i = DigitCount; i > 0; --i)
{
Buffer[i - 1] = '0' + (Value % 10);
Value /= 10;
}
return MakeCString(Buffer, DigitCount);
}
static struct string UINT64ToString(UINT64 Value, struct string_buffer* Buffer)
{
size_t DigitCount = 1;
for(UINT64 i = 10; i <= Value; i *= 10)
++DigitCount;
WCHAR* Dest = PushChars(DigitCount, Buffer);
for(size_t i = DigitCount; i > 0; --i)
{
Dest[i - 1] = '0' + (Value % 10);
Value /= 10;
}
return MakeString(Dest, DigitCount);
}
static struct cstring FloatToString(float Value, char* Buffer)
{
struct cstring Result = UINT64ToCString((UINT64)Value, Buffer);
Buffer[Result.Length++] = '.';
// 2 digits of precision is enough. This is only used to print percentages for stats.
Result.Length += UINT64ToCString((UINT64)((Value - (float)(UINT64)Value) * 100.0f), Buffer).Length;
return Result;
}
static BOOL IsAbsolutePath(struct string Path)
{
return Path.Length > 2 && IsAlpha(Path.Data[0]) && Path.Data[1] == ':';
}
static struct string FileNameWithoutPath(struct string Path)
{
for(size_t i = Path.Length; i > 0; --i)
{
if(IsPathSeparator(Path.Data[i - 1]))
return MakeString(Path.Data + i, Path.Length - i);
}
return Path;
}
static struct string FilePathWithoutExtension(struct string Path)
{
for(size_t i = Path.Length; i > 0; --i)
{
if(Path.Data[i - 1] == '.')
return MakeString(Path.Data, i - 1);
if(IsPathSeparator(Path.Data[i - 1]))
break;
}
return Path;
}
static struct string PathWithoutFileName(struct string Path)
{
for(size_t i = Path.Length; i > 0; --i)
{
if(IsPathSeparator(Path.Data[i - 1]))
return MakeString(Path.Data, i);
}
return MakeString(Path.Data, 0);
}
static void SortStrings(struct string_list List)
{
struct string Temp;
for(int i = 1; i < List.Count; ++i)
{
if(CompareStrings(List.Strings[i], List.Strings[i - 1]) < 0)
{
Temp = List.Strings[i];
List.Strings[i] = List.Strings[i - 1];
List.Strings[i - 1] = Temp;
for(int j = i - 1; j > 0; --j)
{
if(CompareStrings(List.Strings[j], List.Strings[j - 1]) < 0)
{
Temp = List.Strings[j];
List.Strings[j] = List.Strings[j - 1];
List.Strings[j - 1] = Temp;
}
}
}
}
}
struct string_list SplitString(struct string Str, WCHAR Separator, struct memory_arena* Arena)
{
struct string_list List = {0};
for(size_t i = 0; i < Str.Length; ++i)
{
if(Str.Data[i] == Separator)
++List.Count;
}
if(List.Count == 0)
return List;
List.Strings = PushMem(Arena, List.Count * sizeof(struct string));
struct string* Path = List.Strings;
Path->Data = Str.Data;
Path->Length = 0;
for(size_t i = 0; i < Str.Length; ++i)
{
if(Str.Data[i] == Separator)
{
++Path;
Path->Data = Str.Data + i + 1;
Path->Length = 0;
continue;
}
++Path->Length;
}
return List;
}
static struct string ConcatenateStrings(struct string S1, struct string S2, struct string_buffer* Buffer)
{
size_t CopySize;
size_t ResultSize;
if(S1.Data != Buffer->Data + Buffer->Used - S1.Length)
{
CopySize = Buffer->Size - Buffer->Used;
CopySize = min(S1.Length, CopySize);
CopyMemory(Buffer->Data + Buffer->Used, S1.Data, CopySize * sizeof(WCHAR));
Buffer->Used += CopySize;
ResultSize = CopySize;
}
else
{
ResultSize = S1.Length;
}
CopySize = Buffer->Size - Buffer->Used;
CopySize = min(S2.Length, CopySize);
CopyMemory(Buffer->Data + Buffer->Used, S2.Data, CopySize * sizeof(WCHAR));
Buffer->Used += CopySize;
ResultSize += CopySize;
return MakeString(Buffer->Data + Buffer->Used - ResultSize, ResultSize);
}
static struct string ConcatenatePaths(struct string P1, struct string P2, struct string_buffer* Buffer)
{
struct string Result;
if(P1.Length > 0 && !IsPathSeparator(P1.Data[P1.Length - 1]) && (P2.Length == 0 || !IsPathSeparator(P2.Data[0])))
{
Result = ConcatenateStrings(P1, STR("\\"), Buffer);
Result = ConcatenateStrings(Result, P2, Buffer);
}
else if(P1.Length > 0 && P2.Length > 0 && IsPathSeparator(P1.Data[P1.Length - 1]) && IsPathSeparator(P2.Data[0]))
{
Result = ConcatenateStrings(P1, StringRight(P2, P2.Length - 1), Buffer);
}
else
{
Result = ConcatenateStrings(P1, P2, Buffer);
}
return Result;
}
/*
* Index hash
*/
static void InitializeIndexHash(struct index_hash* Hash, int* HashIndices, unsigned int HashCount, int* Indices, unsigned int IndexCount)
{
ASSERT(IS_POW2(HashCount));
Hash->HashIndices = HashIndices;
Hash->Indices = Indices;
Hash->HashCount = HashCount;
Hash->IndexCount = IndexCount;
for(unsigned int i = 0; i < Hash->HashCount; ++i)
Hash->HashIndices[i] = INVALID_INDEX;
}
static void InsertHashIndex(struct index_hash* Hash, UINT32 HashValue, int Index)
{
ASSERT(Hash->IndexCount > (unsigned int)Index);
unsigned int HashIndex = (unsigned int)(HashValue & (Hash->HashCount - 1));
Hash->Indices[Index] = Hash->HashIndices[HashIndex];
Hash->HashIndices[HashIndex] = Index;
}
static void RemoveHashIndex(struct index_hash* Hash, int Index)
{
int* Tmp = NULL;
/* Search for Index in the hash array */
for(unsigned int i = 0; i < Hash->HashCount; ++i)
{
if(Hash->HashIndices[i] == Index)
{
Tmp = &Hash->HashIndices[i];
break;
}
}
/* If not found, search for Index in the Indices array */
if(!Tmp)
{
for(unsigned int i = 0; i < Hash->IndexCount; ++i)
{
if(Hash->Indices[i] == Index)
{
Tmp = &Hash->Indices[i];
break;
}
}
}
/* If found, remove Index and replace with next value */
if(Tmp)
{
do
{
int* NextIndex = &Hash->Indices[*Tmp];
*Tmp = *NextIndex;
Tmp = NextIndex;
}
while(*Tmp != INVALID_INDEX);
}
}
static int FirstHashIndex(const struct index_hash* Hash, UINT32 HashValue)
{
return Hash->HashCount > 0 ? Hash->HashIndices[HashValue & (Hash->HashCount - 1)] : INVALID_INDEX;
}
static int NextHashIndex(const struct index_hash* Hash, int Index)
{
return Hash->Indices[Index];
}
/*
* File system
*/
static void MakePath(struct string Path)
{
if(Path.Length >= MAX_PATH)
FatalError(CSTR("Path length limit exceeded"));
WCHAR TempPath[MAX_PATH];
CopyMemory(TempPath, Path.Data, Path.Length * sizeof(WCHAR));
TempPath[Path.Length] = '\0';
for(WCHAR* p = TempPath; *p; ++p)
{
while(*p && !IsPathSeparator(*p))
++p;
WCHAR Temp = *p;
*p = '\0';
DWORD Attribs = GetFileAttributesW(TempPath);
if(Attribs == INVALID_FILE_ATTRIBUTES || (Attribs & FILE_ATTRIBUTE_DIRECTORY) == 0)
{
if(!CreateDirectoryW(TempPath, NULL))
FatalError(CSTR("Failed to create directory"));
}
*p = Temp;
}
}
static BOOL FileExists(LPCWSTR Path)
{
return GetFileAttributesW(Path) != INVALID_FILE_ATTRIBUTES;
}
static BOOL GetFileSizeLastModified(LPCWSTR filePath, UINT64* FileSize, UINT64* LastModified)
{
WIN32_FILE_ATTRIBUTE_DATA FileAttribData;
if(GetFileAttributesExW(filePath, GetFileExInfoStandard, &FileAttribData) && (FileAttribData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0)
{
*FileSize = (UINT64)FileAttribData.nFileSizeHigh << 32 | FileAttribData.nFileSizeLow;
*LastModified = (UINT64)FileAttribData.ftLastWriteTime.dwHighDateTime << 32 | FileAttribData.ftLastWriteTime.dwLowDateTime;
return TRUE;
}
return FALSE;
}
static void* ReadDataFromFileHandle(HANDLE Handle, struct memory_arena* Arena, size_t* Size)
{
if(SetFilePointer(Handle, 0, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER)
FatalError(CSTR("Failed to read compiler output file"));
LARGE_INTEGER FileSize;
if(!GetFileSizeEx(Handle, &FileSize))
FatalError(CSTR("Failed to determine file size"));
*Size = FileSize.QuadPart;
void* Content = PushMem(Arena, FileSize.QuadPart);
DWORD NumBytesRead;
if(!ReadFile(Handle, Content, (DWORD)FileSize.QuadPart, &NumBytesRead, NULL))
FatalError(CSTR("Failed to read from file"));
return Content;
}
static void* ReadDataFromFile(LPCWSTR Path, struct memory_arena* Arena, size_t* Size)
{
HANDLE File = CreateFileW(Path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if(File == INVALID_HANDLE_VALUE)
FatalError(CSTR("Failed to open file for reading"));
void* Content = ReadDataFromFileHandle(File, Arena, Size);
CloseHandle(File);
return Content;
}
static void WriteDataToFile(LPCWSTR Path, const void* Data, size_t Size)
{
HANDLE File = CreateFileW(Path, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if(File == INVALID_HANDLE_VALUE)
FatalError(CSTR("Failed to open file for writing"));
DWORD NumBytesWritten;
if(!WriteFile(File, Data, (DWORD)Size, &NumBytesWritten, NULL))
FatalError(CSTR("Failed to write to file"));
CloseHandle(File);
}
/*
* Configuration
*/
static void WriteConfig(struct cache_config* Config)
{
WriteDataToFile(g_ConfigFilePath, Config, sizeof(*Config));
}
static void ReadConfig(struct cache_config* Config)
{
if(FileExists(g_ConfigFilePath))
{
HANDLE File = CreateFileW(g_ConfigFilePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if(File == INVALID_HANDLE_VALUE)
FatalError(CSTR("Failed to open configuration file for reading"));
DWORD NumBytesRead;
BOOL Success = ReadFile(File, Config, sizeof(*Config), &NumBytesRead, NULL);
CloseHandle(File);
if(!Success)
FatalError(CSTR("Failed to read from configuration file"));
}
else // Initialize config with default values and write it to the file
{
PWSTR CachePath;
ZeroMemory(Config, sizeof(*Config));
Config->CacheSize = DEFAULT_CACHE_SIZE;
SHGetKnownFolderPath(&FOLDERID_Profile, 0, NULL, &CachePath);
lstrcpyW(Config->CachePath, CachePath);
lstrcatW(Config->CachePath, L"\\.clcache");
// CoTaskMemFree(CachePath);
if(lstrlenW(Config->CachePath) + CACHE_PATH_LENGTH >= MAX_PATH)
FatalError(CSTR("Invalid cache path"));
WriteConfig(Config);
}
}
/*
* Process
*/
static void StartProcess(LPWSTR CmdLine, LPPROCESS_INFORMATION ProcessInfo, BOOL Detached, HANDLE Out, HANDLE Err)
{
STARTUPINFOW StartupInfo = {0};
DWORD CreationFlags = CREATE_NO_WINDOW;
StartupInfo.cb = sizeof(StartupInfo);
if(Detached)
{
CreationFlags |= DETACHED_PROCESS;
}
else if(Out != INVALID_HANDLE_VALUE || Err != INVALID_HANDLE_VALUE)
{
StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
StartupInfo.hStdOutput = Out == INVALID_HANDLE_VALUE ? g_StdoutHandle : Out;
StartupInfo.hStdError = Err == INVALID_HANDLE_VALUE ? g_StderrHandle : Err;
}
ZeroMemory(ProcessInfo, sizeof(*ProcessInfo));
if(!CreateProcessW(NULL, CmdLine, NULL, NULL, TRUE, CreationFlags, NULL, NULL, &StartupInfo, ProcessInfo))
FatalError(CSTR("Failed to start process"));
}
static DWORD WaitForProcessToFinish(LPPROCESS_INFORMATION ProcessInfo)
{
DWORD ExitCode = 0;
WaitForSingleObject(ProcessInfo->hProcess, INFINITE);
GetExitCodeProcess(ProcessInfo->hProcess, &ExitCode);
CloseHandle(ProcessInfo->hThread);
CloseHandle(ProcessInfo->hProcess);
return ExitCode;
}
/*
* CacheMain
*/
static UINT64 GetCompilerVersion(LPCWSTR ExecutablePath, struct memory_arena* Arena)
{
DWORD Handle = 0;
UINT Size = 0;
LPBYTE Buffer = NULL;
DWORD VerSize = GetFileVersionInfoSizeW( ExecutablePath, &Handle);
UINT64 Version = 0;
if(VerSize > 0)
{
void* VerData = PushMem(Arena, VerSize);
if(GetFileVersionInfoW(ExecutablePath, Handle, VerSize, VerData))
{
if(VerQueryValueW(VerData, L"\\", (LPVOID)&Buffer, &Size))
{
if(Size)
{
VS_FIXEDFILEINFO* VerInfo = (VS_FIXEDFILEINFO*)Buffer;
if(VerInfo->dwSignature == 0xfeef04bd)
Version = ((UINT64)VerInfo->dwFileVersionMS << 32) | VerInfo->dwFileVersionLS;