-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathandroid-setup.d
3542 lines (3082 loc) · 106 KB
/
android-setup.d
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
/+
Helper program to help you set up your computer for Android development.
+/
module dlang.android_setup;
import std.stdio;
import std.process;
import std.string;
import std.algorithm;
import std.path;
import std.file;
version(X86)
pragma(msg, "You might want to try -m64 build instead so curl is more likely to work. But you can try this anyway.");
int main(string[] args) {
string ndk_path;
if(args.length < 2) {
version(Windows)
string example = r"C:\Users\PC\AppData\Local\Android\Sdk\ndk\21.0.6113669";
else
string example = "/home/me/Android/ndk/android-ndk-r20/";
writeln("Please specify the path to your NDK installation on the command line. It should be an absolute path, for example: ", example);
writeln("Tip: if you are using `dub run`, use `dub run d_android:setup -- your_path_here`");
return 1;
}
ndk_path = args[1].replace("\\", "/");
auto p = executeShell("ldc2 -v");
if(p.status != 0 && p.status != 1) {
writeln("Couldn't execute ldc2. Are you sure it is installed and in your PATH?");
writeln(
"I suggest downloading ldc2 1.19 from here:
https://github.com/ldc-developers/ldc/releases/tag/v1.19.0
(see the assets at the bottom) and putting it in place.
See more info here: https://github.com/ldc-developers/ldc#installation");
return 1;
}
/*
The output should be similar to:
binary /home/me/d/ldc/bin/ldc2
version 1.19.0 (DMD v2.089.1, LLVM 9.0.1)
config /home/me/d/ldc/etc/ldc2.conf (x86_64-unknown-linux-gnu)
I care about the version being at least 1.19 and the location of
the config file.
*/
string ldcVersion;
string ldcConfigFileName;
foreach(line; p.output.splitLines()) {
if(line.startsWith("version")) {
line = line["version".length .. $];
auto idx = line.indexOf("(");
if(idx != -1)
line = line[0 .. idx];
ldcVersion = line.strip();
} else if(line.startsWith("config")) {
line = line["config".length .. $];
auto idx = line.lastIndexOf("(");
if(idx != -1)
line = line[0 .. idx];
ldcConfigFileName = line.strip();
}
}
writefln("Found LDC %s with file %s", ldcVersion, ldcConfigFileName);
if(ldcVersion.startsWith("1.19")) {
writefln("Your LDC is too old. Please get version 1.20 or newer.\nYou can download it from %s", "https://github.com/ldc-developers/ldc/releases");
return 0;
}
version(linux) {
immutable osString = "linux-x86_64";
} else version(Windows) {
// FIXME
immutable osString = "windows-x86_64";
} else static assert(0, "Find the OS string under your NDK/toolchains and let me know");
writefln("Downloading Android runtimes... (about 50 MB total, may take a while)");
File currentFile;
XzDecoder xzd;
// for tar
TarFileHeader tfh;
long size;
ubyte[] remainingCompressedData;
ubyte[] remainingUncompressedData;
bool keep;
// putting the runtimes here with the package means easy spot we should be able
// to write to... but it might make more sense to put them with the ldc install
// instead, just i fear that not being writable.
chdir(dirName(thisExePath()));
void handleChunk(string url, ubyte[] chunk) {
if(chunk.length == 0) {
if(!xzd.finished)
throw new Exception("wtf");
writeln("finished");
return;
}
if(xzd.finished)
throw new Exception("wtf");
if(xzd is XzDecoder.init) {
write("Downloading ", url, "...");
stdout.flush();
xzd = XzDecoder(chunk);
remainingCompressedData = xzd.unprocessed;
} else {
write(".");
stdout.flush();
// I could do this without the GC stuff but tbh I don't care
// given the use here, it shouldn't be a big deal and this is simpler.
remainingCompressedData ~= chunk;
}
do {
ubyte[4096] dest;
auto buffer = xzd.processData(dest[], remainingCompressedData);
remainingCompressedData = xzd.unprocessed;
remainingUncompressedData ~= buffer;
} while(remainingCompressedData.length && !xzd.finished && !xzd.needsMoreData);
while(remainingUncompressedData.length > 512) {
auto a = remainingUncompressedData[0 .. 512];
remainingUncompressedData = remainingUncompressedData[512 .. $];
// process the buffer through the tar file handler
processTar(&tfh, &size, a[],
(header, isNewFile, fileFinished, data) {
if(isNewFile) {
if(
header.filename.endsWith("libphobos2-ldc.a") ||
header.filename.endsWith("libphobos2-ldc-debug.a") ||
header.filename.endsWith("libdruntime-ldc.a") ||
header.filename.endsWith("libdruntime-ldc-debug.a")
)
{
mkdirRecurse(dirName(header.filename));
currentFile = File(header.filename, "wb");
keep = true;
}
}
if(keep)
currentFile.rawWrite(data[]);
if(fileFinished) {
if(keep)
writeln("\n", header.filename, " extracted");
keep = false;
}
});
}
}
// e.g.
// https://github.com/ldc-developers/ldc/releases/download/v1.21.0-beta1/ldc2-1.21.0-beta1-android-armv7a.tar.xz
// https://github.com/ldc-developers/ldc/releases/download/v1.21.0-beta1/ldc2-1.21.0-beta1-android-aarch64.tar.xz
/+
16 files! this is just half the examples
if it ends with
libphobos2-ldc.a
libphobos2-ldc-debug.a
libdruntime-ldc.a
libdruntime-ldc-debug.a
we want it. then just need to identify the target and put it in the right place.
if(lib-i686)
else if armv7a
else if(lib-x86_64)
else if(aarch64)
ldc2-1.19.0-android-armv7a/lib/libphobos2-ldc.a
ldc2-1.19.0-android-armv7a/lib/libphobos2-ldc-debug.a
ldc2-1.19.0-android-armv7a/lib-i686/libphobos2-ldc.a
ldc2-1.19.0-android-armv7a/lib-i686/libphobos2-ldc-debug.a
ldc2-1.19.0-android-aarch64/lib-x86_64/libdruntime-ldc-debug.a
ldc2-1.19.0-android-aarch64/lib-x86_64/libdruntime-ldc.a
ldc2-1.19.0-android-aarch64/lib/libdruntime-ldc-debug.a
ldc2-1.19.0-android-aarch64/lib/libdruntime-ldc.a
+/
doDownload("https://github.com/ldc-developers/ldc/releases/download/v" ~ ldcVersion ~ "/ldc2-" ~ ldcVersion ~ "-android-armv7a.tar.xz", &handleChunk);
xzd = XzDecoder.init;
doDownload("https://github.com/ldc-developers/ldc/releases/download/v" ~ ldcVersion ~ "/ldc2-" ~ ldcVersion ~ "-android-aarch64.tar.xz", &handleChunk);
writefln("Configuring...");
version(Windows)
string osExt = ".cmd";
else
string osExt = "";
auto config = configTemplate
.replace("$NDK", ndk_path)
.replace("$D_ANDROID", dirName(thisExePath()).replace("\\", "/"))
.replace("$OS", osString)
.replace("$LDC_VERSION", ldcVersion)
.replace("$EXT", osExt)
;
std.file.append(ldcConfigFileName, config);
writefln("Ready! Give it a try.");
return 0;
}
immutable string configTemplate = q{
// begin generated by android-setup.d
"armv7a-.*-linux-android":
{
switches = [
"-defaultlib=phobos2-ldc,druntime-ldc",
"-link-defaultlib-shared=false",
"-gcc=$NDK/toolchains/llvm/prebuilt/$OS/bin/armv7a-linux-androideabi21-clang$EXT",
"-linker=bfd",
"-mcpu=cortex-a8",
];
lib-dirs = [
"$D_ANDROID/ldc2-$LDC_VERSION-android-armv7a/lib",
];
rpath = "";
};
"aarch64-.*-linux-android":
{
switches = [
"-defaultlib=phobos2-ldc,druntime-ldc",
"-link-defaultlib-shared=false",
"-gcc=$NDK/toolchains/llvm/prebuilt/$OS/bin/aarch64-linux-android21-clang$EXT",
"-linker=bfd",
];
lib-dirs = [
"$D_ANDROID/ldc2-$LDC_VERSION-android-aarch64/lib/",
];
rpath = "";
};
"i386-.*-linux-android":
{
switches = [
"-defaultlib=phobos2-ldc,druntime-ldc",
"-link-defaultlib-shared=false",
"-gcc=$NDK/toolchains/llvm/prebuilt/$OS/bin/i686-linux-android21-clang$EXT",
"-linker=bfd",
];
lib-dirs = [
"$D_ANDROID/ldc2-$LDC_VERSION-android-armv7a/lib-i686/",
];
rpath = "";
};
"x86_64-.*-linux-android":
{
switches = [
"-defaultlib=phobos2-ldc,druntime-ldc",
"-link-defaultlib-shared=false",
"-gcc=$NDK/toolchains/llvm/prebuilt/$OS/bin/x86_64-linux-android21-clang$EXT",
"-linker=bfd",
];
lib-dirs = [
"$D_ANDROID/ldc2-$LDC_VERSION-android-aarch64/lib-x86_64",
];
rpath = "";
};
// end generated by android-setup.d
};
void doDownload(string url, void delegate(string, ubyte[]) processChunk) {
import std.net.curl;
auto http = HTTP(url);
http.onReceive = (ubyte[] data) {
processChunk(url, data);
return data.length;
};
http.perform();
}
version=WithLzmaDecoder;
// copy/paste of arsd.archive follows
private:
/+
/++
Reads a tar file and passes the chunks to your handler. Use it like:
TarFile f = TarFile("filename.tar");
foreach(part; f) {
if(part.isNewFile) {
}
}
FIXME not implemented
+/
struct TarFile {
this(string filename) {
}
}
+/
inout(char)[] upToZero(inout(char)[] a) {
int i = 0;
while(i < a.length && a[i]) i++;
return a[0 .. i];
}
/++
A header of a file in the archive. This represents the
binary format of the header block.
+/
align(512)
struct TarFileHeader {
align(1):
char[100] fileName_ = 0;
char[8] fileMode_ = 0;
char[8] ownerUid_ = 0;
char[8] ownerGid_ = 0;
char[12] size_ = 0; // in octal
char[12] mtime_ = 0; // octal unix timestamp
char[8] checksum_ = 0; // right?????
char[1] fileType_ = 0; // hard link, soft link, etc
char[100] linkFileName_ = 0;
char[6] ustarMagic_ = 0; // if "ustar\0", remaining fields are set
char[2] ustarVersion_ = 0;
char[32] ownerName_ = 0;
char[32] groupName_ = 0;
char[8] deviceMajorNumber_ = 0;
char[8] deviceMinorNumber_ = 0;
char[155] filenamePrefix_ = 0;
/// Returns the filename. You should cache the return value as long as TarFileHeader is in scope (it returns a slice after calling strlen)
const(char)[] filename() {
import core.stdc.string;
if(filenamePrefix_[0])
return upToZero(filenamePrefix_[]) ~ upToZero(fileName_[]);
return upToZero(fileName_[]);
}
///
ulong size() {
import core.stdc.stdlib;
return strtoul(size_.ptr, null, 8);
}
///
TarFileType type() {
if(fileType_[0] == 0)
return TarFileType.normal;
else
return cast(TarFileType) (fileType_[0] - '0');
}
}
/// There's other types but this is all I care about. You can still detect the char by `((cast(char) type) + '0')`
enum TarFileType {
normal = 0, ///
hardLink = 1, ///
symLink = 2, ///
characterSpecial = 3, ///
blockSpecial = 4, ///
directory = 5, ///
fifo = 6 ///
}
/++
Low level tar file processor. You must pass it a
TarFileHeader buffer as well as a size_t for context.
Both must be initialized to all zeroes on first call,
then not modified in between calls.
Each call must populate the dataBuffer with 512 bytes.
returns true if still work to do.
+/
bool processTar(
TarFileHeader* header,
long* bytesRemainingOnCurrentFile,
ubyte[] dataBuffer,
scope void delegate(TarFileHeader* header, bool isNewFile, bool fileFinished, ubyte[] data) handleData
)
{
assert(dataBuffer.length == 512);
assert(bytesRemainingOnCurrentFile !is null);
assert(header !is null);
if(*bytesRemainingOnCurrentFile) {
bool isNew = *bytesRemainingOnCurrentFile == header.size();
if(*bytesRemainingOnCurrentFile <= 512) {
handleData(header, isNew, true, dataBuffer[0 .. cast(size_t) *bytesRemainingOnCurrentFile]);
*bytesRemainingOnCurrentFile = 0;
} else {
handleData(header, isNew, false, dataBuffer[]);
*bytesRemainingOnCurrentFile -= 512;
}
} else {
*header = *(cast(TarFileHeader*) dataBuffer.ptr);
auto s = header.size();
*bytesRemainingOnCurrentFile = s;
if(header.type() == TarFileType.directory)
handleData(header, true, false, null);
if(s == 0 && header.type == TarFileType.normal)
return false;
}
return true;
}
///
unittest {
void main() {
TarFileHeader tfh;
long size;
import std.stdio;
ubyte[512] buffer;
foreach(chunk; File("/home/me/test/pl.tar", "r").byChunk(buffer[])) {
processTar(&tfh, &size, buffer[],
(header, isNewFile, fileFinished, data) {
if(isNewFile)
writeln("**** " , header.filename, " ", header.size);
write(cast(string) data);
if(fileFinished)
writeln("+++++++++++++++");
});
}
}
main();
}
ulong readVla(ref ubyte[] data) {
ulong n;
n = data[0] & 0x7f;
if(!(data[0] & 0x80))
data = data[1 .. $];
int i = 0;
while(data[0] & 0x80) {
i++;
data = data[1 .. $];
ubyte b = data[0];
if(b == 0) return 0;
n |= cast(ulong) (b & 0x7F) << (i * 7);
}
return n;
}
/++
A simple .xz file decoder.
FIXME: it doesn't implement very many checks, instead
assuming things are what it expects. Don't use this without
assertions enabled!
Use it by feeding it xz file data chunks. It will give you
back decompressed data chunks;
BEWARE OF REUSED BUFFERS. See the example.
+/
version(WithLzmaDecoder)
struct XzDecoder {
/++
Start decoding by feeding it some initial data. You must
send it at least enough bytes for the header (> 16 bytes prolly);
try to send it a reasonably sized chunk.
+/
this(ubyte[] initialData) {
ubyte[6] magic;
magic[] = initialData[0 .. magic.length];
initialData = initialData[magic.length .. $];
if(cast(string) magic != "\xFD7zXZ\0")
throw new Exception("not an xz file");
ubyte[2] streamFlags = initialData[0 .. 2];
initialData = initialData[2 .. $];
// size of the check at the end in the footer. im just ignoring tbh
checkSize = streamFlags[1] == 0 ? 0 : (4 << ((streamFlags[1]-1) / 3));
//uint crc32 = initialData[0 .. 4]; // FIXME just cast it. this is the crc of the flags.
initialData = initialData[4 .. $];
// now we are into an xz block...
int blockHeaderSize = (initialData[0] + 1) * 4;
auto srcPostHeader = initialData[blockHeaderSize .. $];
initialData = initialData[1 .. $];
ubyte blockFlags = initialData[0];
initialData = initialData[1 .. $];
if(blockFlags & 0x40) {
compressedSize = readVla(initialData);
}
if(blockFlags & 0x80) {
uncompressedSize = readVla(initialData);
}
auto filterCount = (blockFlags & 0b11) + 1;
ubyte props;
foreach(f; 0 .. filterCount) {
auto fid = readVla(initialData);
auto sz = readVla(initialData);
assert(fid == 0x21);
assert(sz == 1);
props = initialData[0];
initialData = initialData[1 .. $];
}
//writeln(src.ptr);
//writeln(srcPostHeader.ptr);
// there should be some padding to a multiple of 4...
// three bytes of zeroes given the assumptions here
initialData = initialData[3 .. $];
// and then a header crc
initialData = initialData[4 .. $]; // skip header crc
assert(initialData.ptr is srcPostHeader.ptr);
// skip unknown header bytes
while(initialData.ptr < srcPostHeader.ptr) {
initialData = initialData[1 .. $];
}
// should finally be at compressed data...
//writeln(compressedSize);
//writeln(uncompressedSize);
if(Lzma2Dec_Allocate(&lzmaDecoder, props) != SRes.OK) {
assert(0);
}
Lzma2Dec_Init(&lzmaDecoder);
unprocessed = initialData;
}
~this() {
LzmaDec_FreeProbs(&lzmaDecoder.decoder);
}
/++
You tell it where you want the data.
You must pass it the existing unprocessed data
Returns slice of dest that is actually filled up so far.
+/
ubyte[] processData(ubyte[] dest, ubyte[] src) {
size_t destLen = dest.length;
size_t srcLen = src.length;
ELzmaStatus status;
auto res = Lzma2Dec_DecodeToBuf(
&lzmaDecoder,
dest.ptr,
&destLen,
src.ptr,
&srcLen,
LZMA_FINISH_ANY,
&status
);
if(res != 0) {
import std.conv;
throw new Exception(to!string(res));
}
/+
import std.stdio;
writeln(res, " ", status);
writeln(srcLen);
writeln(destLen, ": ", cast(string) dest[0 .. destLen]);
+/
if(status == LZMA_STATUS_NEEDS_MORE_INPUT) {
unprocessed = src[srcLen .. $];
finished_ = false;
needsMoreData_ = true;
} else if(status == LZMA_STATUS_FINISHED_WITH_MARK || status == LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK) {
unprocessed = null;
finished_ = true;
needsMoreData_ = false;
} else if(status == LZMA_STATUS_NOT_FINISHED) {
unprocessed = src[srcLen .. $];
finished_ = false;
needsMoreData_ = false;
} else {
// wtf
import std.conv;
assert(0, to!string(status));
}
return dest[0 .. destLen];
}
///
bool finished() {
return finished_;
}
///
bool needsMoreData() {
return needsMoreData_;
}
bool finished_;
bool needsMoreData_;
CLzma2Dec lzmaDecoder;
int checkSize;
ulong compressedSize; ///
ulong uncompressedSize; ///
ubyte[] unprocessed; ///
}
///
version(WithLzmaDecoder)
unittest {
void main() {
ubyte[512] dest; // into tar size chunks!
ubyte[1024] src;
import std.stdio;
//auto file = File("/home/me/test/amazing.txt.xz", "rb");
auto file = File("/home/me/Android/ldcdl/test.tar.xz", "rb");
auto bfr = file.rawRead(src[]);
XzDecoder xzd = XzDecoder(bfr);
// not necessarily set, don't rely on them
writeln(xzd.compressedSize, " / ", xzd.uncompressedSize);
// for tar
TarFileHeader tfh;
long size;
long sum = 0;
while(!xzd.finished) {
// as long as your are not finished, there is more work to do. But it doesn't
// necessarily need more data, so that is a separate check.
if(xzd.needsMoreData) {
// if it needs more data, append new stuff to the end of the buffer, after
// the existing unprocessed stuff. If your buffer is too small, you may be
// forced to grow it here, but anything >= 1 KB seems OK in my tests.
bfr = file.rawRead(src[bfr.length - xzd.unprocessed.length .. $]);
} else {
// otherwise, you want to continue working with existing unprocessed data
bfr = xzd.unprocessed;
}
//write(cast(string) xzd.processData(dest[], bfr));
auto buffer = xzd.processData(dest[], bfr);
// if the buffer is empty we are probably done
// or need more data, so continue the loop to evaluate.
if(buffer.length == 0)
continue;
// our tar code requires specifically 512 byte pieces
while(!xzd.finished && buffer.length != 512) {
// need more data hopefully
assert(xzd.needsMoreData);
// using the existing buffer...
bfr = file.rawRead(src[bfr.length - xzd.unprocessed.length .. $]);
auto nbuffer = xzd.processData(dest[buffer.length .. $], bfr);
buffer = dest[0 .. buffer.length + nbuffer.length];
}
sum += buffer.length;
// process the buffer through the tar file handler
processTar(&tfh, &size, buffer[],
(header, isNewFile, fileFinished, data) {
if(isNewFile)
writeln("**** " , header.filename, " ", header.size);
//write(cast(string) data);
if(fileFinished)
writeln("+++++++++++++++");
});
}
writeln(sum);
}
main();
}
version(WithArczCode) {
/* The code in this section was originally written by Ketmar Dark for his arcz.d module. I modified it afterward. */
/** ARZ chunked archive format processor.
*
* This module provides `std.stdio.File`-like interface to ARZ archives.
*
* Copyright: Copyright Ketmar Dark, 2016
*
* License: Boost License 1.0
*/
// module iv.arcz;
// use Balz compressor if available
static if (__traits(compiles, { import iv.balz; })) enum arcz_has_balz = true; else enum arcz_has_balz = false;
static if (__traits(compiles, { import iv.zopfli; })) enum arcz_has_zopfli = true; else enum arcz_has_zopfli = false;
static if (arcz_has_balz) import iv.balz;
static if (arcz_has_zopfli) import iv.zopfli;
// comment this to free pakced chunk buffer right after using
// i.e. `AZFile` will allocate new block for each new chunk
//version = arcz_use_more_memory;
public import core.stdc.stdio : SEEK_SET, SEEK_CUR, SEEK_END;
// ////////////////////////////////////////////////////////////////////////// //
/// ARZ archive accessor. Use this to open ARZ archives, and open packed files from ARZ archives.
public struct ArzArchive {
private:
static assert(size_t.sizeof >= (void*).sizeof);
private import core.stdc.stdio : FILE, fopen, fclose, fread, fseek;
private import etc.c.zlib;
static struct ChunkInfo {
uint ofs; // offset in file
uint pksize; // packed chunk size (same as chunk size: chunk is unpacked)
}
static struct FileInfo {
string name;
uint chunk;
uint chunkofs; // offset of first file byte in unpacked chunk
uint size; // unpacked file size
}
static struct Nfo {
uint rc = 1; // refcounter
ChunkInfo[] chunks;
FileInfo[string] files;
uint chunkSize;
uint lastChunkSize;
bool useBalz;
FILE* afl; // archive file, we'll keep it opened
@disable this (this); // no copies!
static void decRef (size_t me) {
if (me) {
auto nfo = cast(Nfo*)me;
assert(nfo.rc);
if (--nfo.rc == 0) {
import core.memory : GC;
import core.stdc.stdlib : free;
if (nfo.afl !is null) fclose(nfo.afl);
nfo.chunks.destroy;
nfo.files.destroy;
nfo.afl = null;
GC.removeRange(cast(void*)nfo/*, Nfo.sizeof*/);
free(nfo);
debug(arcz_rc) { import core.stdc.stdio : printf; printf("Nfo %p freed\n", nfo); }
}
}
}
}
size_t nfop; // hide it from GC
private @property Nfo* nfo () { pragma(inline, true); return cast(Nfo*)nfop; }
void decRef () { pragma(inline, true); Nfo.decRef(nfop); nfop = 0; }
static uint readUint (FILE* fl) {
if (fl is null) throw new Exception("cannot read from closed file");
uint v;
if (fread(&v, 1, v.sizeof, fl) != v.sizeof) throw new Exception("file reading error");
version(BigEndian) {
import core.bitop : bswap;
v = bswap(v);
} else version(LittleEndian) {
// nothing to do
} else {
static assert(0, "wtf?!");
}
return v;
}
static uint readUbyte (FILE* fl) {
if (fl is null) throw new Exception("cannot read from closed file");
ubyte v;
if (fread(&v, 1, v.sizeof, fl) != v.sizeof) throw new Exception("file reading error");
return v;
}
static void readBuf (FILE* fl, void[] buf) {
if (buf.length > 0) {
if (fl is null) throw new Exception("cannot read from closed file");
if (fread(buf.ptr, 1, buf.length, fl) != buf.length) throw new Exception("file reading error");
}
}
static T* xalloc(T, bool clear=true) (uint mem) if (T.sizeof > 0) {
import core.exception : onOutOfMemoryError;
assert(mem != 0);
static if (clear) {
import core.stdc.stdlib : calloc;
auto res = calloc(mem, T.sizeof);
if (res is null) onOutOfMemoryError();
static if (is(T == struct)) {
import core.stdc.string : memcpy;
static immutable T i = T.init;
foreach (immutable idx; 0..mem) memcpy(res+idx, &i, T.sizeof);
}
debug(arcz_alloc) { import core.stdc.stdio : printf; printf("allocated %u bytes at %p\n", cast(uint)(mem*T.sizeof), res); }
return cast(T*)res;
} else {
import core.stdc.stdlib : malloc;
auto res = malloc(mem*T.sizeof);
if (res is null) onOutOfMemoryError();
static if (is(T == struct)) {
import core.stdc.string : memcpy;
static immutable T i = T.init;
foreach (immutable idx; 0..mem) memcpy(res+idx, &i, T.sizeof);
}
debug(arcz_alloc) { import core.stdc.stdio : printf; printf("allocated %u bytes at %p\n", cast(uint)(mem*T.sizeof), res); }
return cast(T*)res;
}
}
static void xfree(T) (T* ptr) {
if (ptr !is null) {
import core.stdc.stdlib : free;
debug(arcz_alloc) { import core.stdc.stdio : printf; printf("freing at %p\n", ptr); }
free(ptr);
}
}
static if (arcz_has_balz) static ubyte balzDictSize (uint blockSize) {
foreach (ubyte bits; Balz.MinDictBits..Balz.MaxDictBits+1) {
if ((1U<<bits) >= blockSize) return bits;
}
return Balz.MaxDictBits;
}
// unpack exactly `destlen` bytes
static if (arcz_has_balz) static void unpackBlockBalz (void* dest, uint destlen, const(void)* src, uint srclen, uint blocksize) {
Unbalz bz;
bz.reinit(balzDictSize(blocksize));
int ipos, opos;
auto dc = bz.decompress(
// reader
(buf) {
import core.stdc.string : memcpy;
if (ipos >= srclen) return 0;
uint rd = destlen-ipos;
if (rd > buf.length) rd = cast(uint)buf.length;
memcpy(buf.ptr, src+ipos, rd);
ipos += rd;
return rd;
},
// writer
(buf) {
//if (opos+buf.length > destlen) throw new Exception("error unpacking archive");
uint wr = destlen-opos;
if (wr > buf.length) wr = cast(uint)buf.length;
if (wr > 0) {
import core.stdc.string : memcpy;
memcpy(dest+opos, buf.ptr, wr);
opos += wr;
}
},
// unpack length
destlen
);
if (opos != destlen) throw new Exception("error unpacking archive");
}
static void unpackBlockZLib (void* dest, uint destlen, const(void)* src, uint srclen, uint blocksize) {
z_stream zs;
zs.avail_in = 0;
zs.avail_out = 0;
// initialize unpacker
if (inflateInit2(&zs, 15) != Z_OK) throw new Exception("can't initialize zlib");
scope(exit) inflateEnd(&zs);
zs.next_in = cast(typeof(zs.next_in))src;
zs.avail_in = srclen;
zs.next_out = cast(typeof(zs.next_out))dest;
zs.avail_out = destlen;
while (zs.avail_out > 0) {
auto err = inflate(&zs, Z_SYNC_FLUSH);
if (err != Z_STREAM_END && err != Z_OK) throw new Exception("error unpacking archive");
if (err == Z_STREAM_END) break;
}
if (zs.avail_out != 0) throw new Exception("error unpacking archive");
}
static void unpackBlock (void* dest, uint destlen, const(void)* src, uint srclen, uint blocksize, bool useBalz) {
if (useBalz) {
static if (arcz_has_balz) {
unpackBlockBalz(dest, destlen, src, srclen, blocksize);
} else {
throw new Exception("no Balz support was compiled in ArcZ");
}
} else {
unpackBlockZLib(dest, destlen, src, srclen, blocksize);
}
}
public:
this (in ArzArchive arc) {
assert(nfop == 0);
nfop = arc.nfop;
if (nfop) ++nfo.rc;
}
this (this) {
if (nfop) ++nfo.rc;
}
~this () { close(); }
void opAssign (in ArzArchive arc) {
if (arc.nfop) {
auto n = cast(Nfo*)arc.nfop;
++n.rc;
}
decRef();
nfop = arc.nfop;
}
void close () { decRef(); }
@property FileInfo[string] files () { return (nfop ? nfo.files : null); }
void openArchive (const(char)[] filename) {
debug/*(arcz)*/ import core.stdc.stdio : printf;
FILE* fl = null;