-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmoduleEncoding.js
More file actions
1801 lines (1687 loc) · 54.9 KB
/
moduleEncoding.js
File metadata and controls
1801 lines (1687 loc) · 54.9 KB
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
const { Flags: ModuleFlags, MODULE_PREFIX_SIZE, MIN_MODULE_SUFFIX_SIZE, MAX_MODULE_SUFFIX_SIZE, ModuleInfoExtension, ModuleFunction } = require('./ModuleInfo.js');
const HalModuleParser = require('./HalModuleParser');
const { crc32 } = require('./utilities');
const crypto = require('crypto');
const zlib = require('zlib');
const { promisify } = require('util');
const ModuleInfo = require('./ModuleInfo.js');
const fs = require('fs');
const fsAsync = fs.promises;
const archiver = require('archiver');
const tmp = require('tmp-promise');
const deflateRawAsync = promisify(zlib.deflateRaw);
const inflateRawAsync = promisify(zlib.inflateRaw);
const { platformsById } = require('@particle/device-constants');
const { schema: protobufSchema } = require('@particle/device-os-protobuf');
const { Readable } = require('stream');
const unzip = require('unzipper');
const path = require('path');
const DEFAULT_START_ALIGNMENT = 8;
const MAX_ENV_VARS_ASSET_DATA_SIZE = 16 * 1024;
function moduleFunctionToString(func) {
switch (func) {
case ModuleInfo.FunctionType.NONE: {
return 'none';
}
case ModuleInfo.FunctionType.RESOURCE: {
return 'resource';
}
case ModuleInfo.FunctionType.BOOTLOADER: {
return 'bootloader';
}
case ModuleInfo.FunctionType.MONO_FIRMWARE: {
return 'monoFirmware';
}
case ModuleInfo.FunctionType.SYSTEM_PART: {
return 'systemPart';
}
case ModuleInfo.FunctionType.USER_PART: {
return 'userPart';
}
case ModuleInfo.FunctionType.SETTINGS: {
return 'settings';
}
case ModuleInfo.FunctionType.NCP_FIRMWARE: {
return 'ncpFirmware';
}
case ModuleInfo.FunctionType.RADIO_STACK: {
return 'radioStack';
}
case ModuleInfo.FunctionType.ASSET: {
return 'asset';
}
default: {
throw new RangeError('Unknown module function');
}
}
}
function firmwareModuleInfoForPlatformAndFunction(id, func, index) {
const p = platformsById[id];
if (!p) {
throw new RangeError(`Unknown platform ID: ${id}`);
}
if (!p.firmwareModules) {
return null;
}
const type = moduleFunctionToString(func);
for (let m of p.firmwareModules) {
if (m.type === type) {
if (index === undefined || m.index === undefined || index === m.index) {
return m;
}
}
}
return null;
}
/**
* An error reported when assets are over the platform-specific limits
*/
class AssetLimitError extends Error {
constructor(details, ...args) {
super(...args);
this.name = this.constructor.name;
this.details = details;
}
}
/**
* An error reported when module data is over the platform-specific limits
*/
class PlatformLimitError extends Error {
constructor(details, ...args) {
super(...args);
this.name = this.constructor.name;
this.details = details;
}
}
// Size of the `compressed_module_header` structure in Device OS
const COMPRESSED_MODULE_HEADER_SIZE = 8;
/**
* Compute and update the module's SHA-256 checksum.
*
* @param {Buffer} data Module data.
* @returns {Buffer}
*/
function updateModuleSha256(data) {
const suffixSize = 38; // Size of the SHA-256, CRC-32 and suffix size fields
if (data.length < suffixSize) {
throw new RangeError('Invalid size of the module data');
}
const shaOffs = data.length - suffixSize;
let hash = crypto.createHash('sha256');
hash.update(data.slice(0, shaOffs));
hash = hash.digest();
hash.copy(data, shaOffs);
return data;
}
/**
* Compute and update the module's CRC-32 checksum.
*
* @param {Buffer} data Module data.
* @returns {Buffer}
*/
function updateModuleCrc32(data) {
if (data.length < 4) {
throw new RangeError('Invalid size of the module data');
}
const crcOffs = data.length - 4;
const crc = crc32(data.slice(0, crcOffs));
crc.copy(data, crcOffs);
return data;
}
/**
* Update the module's prefix data.
*
* Note: This function does not update the checksums of the module.
*
* @param {Buffer} data Module data.
* @param {Object} prefix Prefix info (see `HalModuleParser`).
* @returns {Buffer}
*/
function updateModulePrefix(data, prefix) {
let offs = prefix.prefixOffset || 0;
if (data.length < offs + MODULE_PREFIX_SIZE) {
throw new RangeError('Invalid size of the module data');
}
// Start address
if (prefix.moduleStartAddy !== undefined) {
let addr = prefix.moduleStartAddy;
if (typeof addr === 'string') { // HalModuleParser returns addresses as strings ¯\(ツ)/¯
addr = Number.parseInt(addr, 16);
}
data.writeUInt32LE(addr, offs);
}
offs += 4;
// End address
if (prefix.moduleEndAddy !== undefined) {
addr = prefix.moduleEndAddy;
if (typeof addr === 'string') {
addr = Number.parseInt(addr, 16);
}
data.writeUInt32LE(addr, offs);
}
offs += 4;
// Reserved field (MCU target on Gen 3)
if (prefix.reserved !== undefined) {
data.writeUInt8(prefix.reserved, offs);
}
offs += 1;
// Module flags
if (prefix.moduleFlags !== undefined) {
data.writeUInt8(prefix.moduleFlags, offs);
}
offs += 1;
// Module version
if (prefix.moduleVersion !== undefined) {
data.writeUInt16LE(prefix.moduleVersion, offs);
}
offs += 2;
// Platform ID
if (prefix.platformID !== undefined) {
data.writeUInt16LE(prefix.platformID, offs);
}
offs += 2;
// Module function
if (prefix.moduleFunction !== undefined) {
data.writeUInt8(prefix.moduleFunction, offs);
}
offs += 1;
// Module index
if (prefix.moduleIndex !== undefined) {
data.writeUInt8(prefix.moduleIndex, offs);
}
offs += 1;
// Module function (dependency 1)
if (prefix.depModuleFunction !== undefined) {
data.writeUInt8(prefix.depModuleFunction, offs);
}
offs += 1;
// Module index (dependency 1)
if (prefix.depModuleIndex !== undefined) {
data.writeUInt8(prefix.depModuleIndex, offs);
}
offs += 1;
// Module version (dependency 1)
if (prefix.depModuleVersion !== undefined) {
data.writeUInt16LE(prefix.depModuleVersion, offs);
}
offs += 2;
// Module function (dependency 2)
if (prefix.dep2ModuleFunction !== undefined) {
data.writeUInt8(prefix.dep2ModuleFunction, offs);
}
offs += 1;
// Module index (dependency 2)
if (prefix.dep2ModuleIndex !== undefined) {
data.writeUInt8(prefix.dep2ModuleIndex, offs);
}
offs += 1;
// Module version (dependency 2)
if (prefix.dep2ModuleVersion !== undefined) {
data.writeUInt16LE(prefix.dep2ModuleVersion, offs);
}
offs += 2;
if (prefix.moduleFlags !== undefined && (prefix.moduleFlags & ModuleInfo.Flags.PREFIX_EXTENSIONS)) {
if (prefix.extensions) {
// Validate size
const expectedSize = calculateModulePrefixSize(prefix);
if (expectedSize !== prefix.prefixSize) {
// A sanity check to see whether the caller has resized the Buffer and already expects a certain
// prefix size.
throw new RangeError(`Extensions will not fit current prefix without resizing ${expectedSize} != ${prefix.prefixSize}`);
}
for (let ext of prefix.extensions) {
if (ext.data) {
ext.data.copy(data, offs);
offs += ext.data.length;
} else {
const extData = encodeModuleExtension(ext);
extData.copy(data, offs);
offs += extData.length;
}
}
}
}
return data;
}
/**
* Calculate size of suffix data.
*
* @param {Object} suffix Suffix info (see `HalModuleParser`).
* @returns {Number}
*/
function calculateModuleSuffixSize(suffix) {
let size = ModuleInfo.MIN_MODULE_SUFFIX_SIZE;
let seenProductExtension = false;
if (suffix.extensions && suffix.extensions.length > 0) {
for (let ext of suffix.extensions) {
size += encodeModuleExtension(ext).length;
if (ext.type === ModuleInfo.ModuleInfoExtension.PRODUCT_DATA) {
seenProductExtension = true;
}
}
}
if (!seenProductExtension) {
// For compatibility purposes add raw product id/version data
size += 4;
}
return size;
}
/**
* Calculate size of prefix data.
*
* @param {Object} suffix Prefix info (see `HalModuleParser`).
* @returns {Number}
*/
function calculateModulePrefixSize(prefix) {
let size = ModuleInfo.MODULE_PREFIX_SIZE;
if (prefix.moduleFlags !== undefined && (prefix.moduleFlags & ModuleInfo.Flags.PREFIX_EXTENSIONS) &&
prefix.extensions && prefix.extensions.length > 0) {
for (let ext of prefix.extensions) {
size += encodeModuleExtension(ext).length;
}
}
return size;
}
/**
* Sanitize address type to Number.
*
* @param {Object} address Address either as a string or number
* @returns {Number}
*/
function sanitizeAddress(address) {
if (typeof address === 'string') {
address = Number.parseInt(address, 16);
}
return address;
}
/**
* Encode module extension.
*
* @param {Object} extension Extension data (see `HalModuleParser`).
* @returns {Buffer}
*/
function encodeModuleExtension(extension) {
const EXTENSION_HEADER_SIZE = 4;
let idx = 0;
let buffer;
switch (extension.type) {
case ModuleInfo.ModuleInfoExtension.PRODUCT_DATA: {
buffer = Buffer.alloc(EXTENSION_HEADER_SIZE + 6);
buffer.writeUint16LE(extension.type, idx);
idx += 2;
buffer.writeUint16LE(buffer.length, idx);
idx += 2;
buffer.writeUInt16LE(0xffff, idx);
idx += 2;
buffer.writeUInt16LE(extension.productId, idx);
idx += 2;
buffer.writeUInt16LE(extension.productVersion, idx);
break;
}
case ModuleInfo.ModuleInfoExtension.DYNAMIC_LOCATION: {
buffer = Buffer.alloc(EXTENSION_HEADER_SIZE + 12);
buffer.writeUint16LE(extension.type, idx);
idx += 2;
buffer.writeUint16LE(buffer.length, idx);
idx += 2;
buffer.writeUint32LE(sanitizeAddress(extension.moduleStartAddress), idx);
idx += 4;
buffer.writeUint32LE(sanitizeAddress(extension.dynalibLoadAddress), idx);
idx += 4;
buffer.writeUint32LE(sanitizeAddress(extension.dynalibStartAddress), idx);
break;
}
case ModuleInfo.ModuleInfoExtension.DEPENDENCY: {
buffer = Buffer.alloc(EXTENSION_HEADER_SIZE + 8);
buffer.writeUint16LE(extension.type, idx);
idx += 2;
buffer.writeUint16LE(buffer.length, idx);
idx += 2;
buffer.writeUInt8(extension.moduleFunction, idx);
idx += 1;
buffer.writeUInt8(extension.moduleIndex, idx);
idx += 1;
buffer.writeUInt16LE(extension.moduleVersion, idx);
idx += 2;
buffer.writeUInt32LE(extension.targetId, idx);
break;
}
case ModuleInfo.ModuleInfoExtension.HASH: {
let hash = extension.hash;
if (typeof hash === 'string') {
hash = Buffer.from(hash, 'hex');
}
buffer = Buffer.alloc(EXTENSION_HEADER_SIZE + 2 + hash.length);
buffer.writeUint16LE(extension.type, idx);
idx += 2;
buffer.writeUint16LE(buffer.length, idx);
idx += 2;
buffer.writeUInt8(extension.hashType ? extension.hashType : ModuleInfo.ModuleInfoHashExtensionType.SHA256, idx);
idx += 1;
buffer.writeUInt8(hash.length, idx);
idx += 1;
hash.copy(buffer, idx);
break;
}
case ModuleInfo.ModuleInfoExtension.NAME: {
const name = Buffer.from(extension.name, 'utf8');
buffer = Buffer.alloc(EXTENSION_HEADER_SIZE + name.length);
buffer.writeUint16LE(extension.type, idx);
idx += 2;
buffer.writeUint16LE(buffer.length, idx);
idx += 2;
name.copy(buffer, idx);
break;
}
case ModuleInfo.ModuleInfoExtension.ASSET_DEPENDENCY: {
let hash = extension.hash;
if (typeof hash === 'string') {
hash = Buffer.from(hash, 'hex');
}
const name = Buffer.from(extension.name, 'utf8');
buffer = Buffer.alloc(EXTENSION_HEADER_SIZE + name.length + hash.length + 2);
buffer.writeUint16LE(extension.type, idx);
idx += 2;
buffer.writeUint16LE(buffer.length, idx);
idx += 2;
buffer.writeUInt8(extension.hashType ? extension.hashType : ModuleInfo.ModuleInfoHashExtensionType.SHA256, idx);
idx += 1;
buffer.writeUInt8(hash.length, idx);
idx += 1;
hash.copy(buffer, idx);
idx += hash.length;
name.copy(buffer, idx);
break;
}
case ModuleInfo.ModuleInfoExtension.END: {
let length = EXTENSION_HEADER_SIZE;
if (extension.padding) {
length += extension.padding;
} else if (extension.data) {
// Use same padding
length = extension.data.length;
}
buffer = Buffer.alloc(length);
buffer.writeUint16LE(extension.type, idx);
idx += 2;
buffer.writeUint16LE(buffer.length, idx);
idx += 2;
break;
}
case ModuleInfo.ModuleInfoExtension.SECURITY_MODE: {
let length = EXTENSION_HEADER_SIZE + 1;
if (extension.certificate) {
// This needs to be a buffer
length += extension.certificate.length;
}
buffer = Buffer.alloc(length);
buffer.writeUint16LE(extension.type, idx);
idx += 2;
buffer.writeUint16LE(buffer.length, idx);
idx += 2;
buffer.writeUint8(extension.securityMode, idx);
idx += 1;
if (extension.certificate) {
extension.certificate.copy(buffer, idx);
}
break;
}
case ModuleInfo.ModuleInfoExtension.ASSET_TYPE: {
const assetType = extension.assetType;
if (typeof assetType !== 'number' || assetType < 0 || assetType > 255) {
throw new Error('Invalid asset type');
}
buffer = Buffer.alloc(EXTENSION_HEADER_SIZE + 2);
idx = buffer.writeUInt16LE(extension.type, idx);
idx = buffer.writeUint16LE(buffer.length, idx);
idx = buffer.writeUInt8(assetType, idx);
idx = buffer.writeUInt8(0, idx); // Reserved
break;
}
default: {
if (extension.data && extension.data.length >= EXTENSION_HEADER_SIZE) {
buffer = extension.data;
} else {
throw new RangeError('Unknown extension type');
}
}
}
return buffer;
}
/**
* Update the module's suffix data.
*
* Note: This function can't be used to change the size of the suffix data and it does not update
* the checksums of the module.
*
* @param {Buffer} data Module data.
* @param {Object} suffix Suffix info (see `HalModuleParser`).
* @returns {Buffer}
*/
function updateModuleSuffix(data, suffix) {
const size = suffix.suffixSize;
if (size === undefined || size < MIN_MODULE_SUFFIX_SIZE || size > MAX_MODULE_SUFFIX_SIZE) {
throw new RangeError('Invalid suffix size');
}
if (data.length < size + 4 /* CRC-32 */) {
throw new RangeError('Invalid size of the module data');
}
let offs = data.length - size - 4;
let productOffs = offs;
if (suffix.extensions) {
const expectedSize = calculateModuleSuffixSize(suffix);
if (expectedSize !== size) {
// A sanity check to see whether the caller has resized the Buffer and already expects a certain
// suffix size.
throw new RangeError(`Extensions will not fit current suffix without resizing`);
}
let updatedProductOffs = false;
for (let ext of suffix.extensions) {
if (ext.data) {
ext.data.copy(data, offs);
offs += ext.data.length;
} else {
const extData = encodeModuleExtension(ext);
extData.copy(data, offs);
offs += extData.length;
}
// FIXME: This is not ideal, but by design product data extension
// is at the same location as standalone product data on platforms
// that don't have suffix extensions
if (ext.type === ModuleInfoExtension.PRODUCT_DATA) {
productOffs = offs - 4;
updatedProductOffs = true;
}
}
if (!updatedProductOffs) {
productOffs = offs;
}
}
offs = productOffs;
if (size >= MIN_MODULE_SUFFIX_SIZE + 4) {
// Product ID
if (suffix.productId !== undefined) {
// 16-bit product ID
data.writeUInt16LE(suffix.productId, offs);
}
offs += 2;
// Product version
if (suffix.productVersion !== undefined) {
data.writeUInt16LE(suffix.productVersion, offs);
}
offs += 2;
}
// Reserved field
if (suffix.reserved !== undefined) {
data.writeUInt16LE(suffix.reserved, offs);
}
offs += 2;
// SHA-256 hash
if (suffix.fwUniqueId !== undefined) {
let hash = suffix.fwUniqueId;
if (typeof hash === 'string') {
hash = Buffer.from(hash, 'hex');
}
if (hash.length != 32) {
throw new RangeError('Invalid size of the SHA-256 checksum');
}
hash.copy(data, offs);
}
offs += 32;
// Suffix size
offs = data.writeUInt16LE(size, offs);
// CRC-32 checksum
if (suffix.crcBlock !== undefined) {
let crc = suffix.crcBlock;
if (typeof crc === 'string') {
crc = Buffer.from(crc, 'hex');
}
if (crc.length != 4) {
throw new RangeError('Invalid size of the CRC-32 checksum');
}
crc.copy(data, offs);
}
offs += 4;
return data;
}
/**
* Compress the firmware module.
*
* @param {Buffer} data Module data.
* @param {Object} [options] Options.
* @param {Object} [options.zlib] Compression options (https://nodejs.org/api/zlib.html#zlib_class_options).
* @param {Boolean} [options.updateCrc32] Update CRC-32 of the compressed module (default: `true`).
* @param {Boolean} [options.updateSha256] Update SHA-256 of the compressed module (default: `true`).
* @returns {Promise<Buffer>}
*/
async function compressModule(data, options) {
const parser = new HalModuleParser();
const { prefixInfo: prefix } = await parser.parsePrefix({ fileBuffer: data });
const { suffixInfo: suffix } = await parser.parseSuffix({ fileBuffer: data });
let startAddr = prefix.moduleStartAddy;
if (typeof startAddr === 'string') {
startAddr = Number.parseInt(startAddr, 16);
}
let endAddr = prefix.moduleEndAddy;
if (typeof endAddr === 'string') {
endAddr = Number.parseInt(endAddr, 16);
}
const flags = prefix.moduleFlags;
if (flags & ModuleFlags.COMPRESSED) {
throw new RangeError('Module is already compressed');
}
if (flags & ModuleFlags.COMBINED) {
// Combined modules need to be compressed individually
throw new RangeError('Can\'t compress a combined module');
}
const suffixSize = suffix.suffixSize;
if (suffixSize < MIN_MODULE_SUFFIX_SIZE || suffixSize > MAX_MODULE_SUFFIX_SIZE) {
throw new RangeError('Invalid suffix size');
}
let dataSize = endAddr - startAddr + 4 /* CRC-32 */;
const prefixOffs = prefix.prefixOffset || 0;
if (data.length < prefixOffs + MODULE_PREFIX_SIZE + suffixSize + 4 || data.length !== dataSize) {
throw new RangeError('Invalid size of the module data');
}
let dataOffs = 0;
const prefixSize = prefix.prefixSize;
if (prefixSize < MODULE_PREFIX_SIZE) {
throw new RangeError('Invalid prefix data');
}
if (flags & ModuleFlags.DROP_MODULE_INFO) {
if (prefixOffs !== 0) {
throw new RangeError('DROP_MODULE_INFO can\'t be set for a module with a vector table');
}
// Skip the prefix data
dataOffs = prefixSize;
dataSize -= prefixSize;
// No need to keep suffix around within the compressed section either
dataSize -= suffixSize + 4 /* CRC-32 */;
}
// Compress the module data
let compData = await deflateRawAsync(data.slice(dataOffs, dataOffs + dataSize), options && options.zlib);
const compDataSize = compData.length;
// TODO: Consider using some linked buffers implementation to optimize memory usage,
// e.g. https://www.npmjs.com/package/buffers
const destBuf = Buffer.alloc(prefixSize + COMPRESSED_MODULE_HEADER_SIZE + compDataSize + suffixSize + 4);
// Copy the prefix data
let offs = 0;
offs += data.copy(destBuf, offs, prefixOffs, prefixOffs + prefixSize);
// Encode the header of the compressed data
offs = destBuf.writeUInt16LE(COMPRESSED_MODULE_HEADER_SIZE, offs); // Header size
offs = destBuf.writeUInt8(0, offs); // Compression method (raw Deflate)
offs = destBuf.writeUInt8((options && options.zlib && options.zlib.windowBits) || 0, offs); // Window size
offs = destBuf.writeUInt32LE(dataSize, offs); // Size of the uncompressed data
// Copy the compressed data
offs += compData.copy(destBuf, offs);
compData = null;
// Copy the suffix data
const suffixOffs = data.length - suffixSize - 4;
offs += data.copy(destBuf, offs, suffixOffs, suffixOffs + suffixSize + 4);
// Update the prefix data
updateModulePrefix(destBuf, {
moduleEndAddy: startAddr + prefixSize + COMPRESSED_MODULE_HEADER_SIZE + compDataSize + suffixSize, // CRC-32 is not included
moduleFlags: flags | ModuleFlags.COMPRESSED
});
// Update the checksums
if (!options || options.updateSha256 === undefined || options.updateSha256) {
updateModuleSha256(destBuf);
}
if (!options || options.updateCrc32 === undefined || options.updateCrc32) {
updateModuleCrc32(destBuf);
}
return destBuf;
}
/**
* Add new extensions to module prefix or suffix depending on the platform.
*
* @param {Buffer} module Module to update
* @param {Array} exts List of extensions to add
* @param {Boolean} replaceWithSameType Append extensions as-is or replace existing extensions of the same type
* @returns {Promise<Buffer>}
*/
async function addModuleExtensions({ module, exts = [], replaceWithSameType = false } = {}) {
if (exts.length === 0) {
throw new RangeError('Empty extension list');
}
const parser = new HalModuleParser();
const { prefixInfo: prefix } = await parser.parsePrefix({ fileBuffer: module });
const { suffixInfo: suffix } = await parser.parseSuffix({ fileBuffer: module });
prefix.moduleStartAddy = sanitizeAddress(prefix.moduleStartAddy);
prefix.moduleEndAddy = sanitizeAddress(prefix.moduleEndAddy);
const flags = prefix.moduleFlags;
if (flags & ModuleFlags.COMPRESSED) {
throw new RangeError(`Can't add extensions to a compressed module`);
}
if (flags & ModuleFlags.COMBINED) {
throw new RangeError(`Can\'t add extensions to a combined module`);
}
const suffixSize = suffix.suffixSize;
if (suffixSize < MIN_MODULE_SUFFIX_SIZE || suffixSize > MAX_MODULE_SUFFIX_SIZE) {
throw new RangeError('Invalid suffix size');
}
let dataSize = prefix.moduleEndAddy - prefix.moduleStartAddy + 4 /* CRC-32 */;
const prefixOffs = prefix.prefixOffset || 0;
if (module.length < prefixOffs + MODULE_PREFIX_SIZE + suffixSize + 4 || module.length !== dataSize) {
throw new RangeError('Invalid size of the module data');
}
const moduleInfo = firmwareModuleInfoForPlatformAndFunction(prefix.platformID, prefix.moduleFunction, prefix.moduleIndex);
let extensionsInPrefix = false;
if ((prefix.moduleFlags & ModuleInfo.Flags.PREFIX_EXTENSIONS) || (moduleInfo && moduleInfo.growsLeft)) {
extensionsInPrefix = true;
}
let extensions = [];
if (extensionsInPrefix) {
extensions = prefix.extensions;
} else {
extensions = suffix.extensions;
}
if (!extensions) {
extensions = [];
}
if (replaceWithSameType) {
extensions = extensions.filter((val) => {
for (let ext of exts) {
if (val.type === ext.type) {
return false;
}
}
return true;
});
}
let buffer = null;
if (extensionsInPrefix) {
extensions = extensions.concat(exts);
prefix.extensions = extensions;
} else {
extensions = exts.concat(extensions);
suffix.extensions = extensions;
}
// Always add END extension: it is mandatory to be present in module prefix extensions
// and due to the fact that product data for some of the platforms may not use an extension and just be
// raw data, to indicate end we will also use END extension here.
if (extensions.length > 0 && extensions[extensions.length - 1].type !== ModuleInfo.ModuleInfoExtension.END &&
extensions[extensions.length - 1].type !== ModuleInfo.ModuleInfoExtension.PRODUCT_DATA) {
extensions.push({
type: ModuleInfo.ModuleInfoExtension.END
});
}
if (extensionsInPrefix && extensions.length > 0) {
if (prefixOffs > 0) {
throw new RangeError('Extensions in prefix are not supported for modules with non-zero prefix offset');
}
prefix.moduleFlags |= ModuleInfo.Flags.PREFIX_EXTENSIONS;
prefix.extensions = extensions;
const originalPrefixSize = prefix.prefixSize;
prefix.prefixSize = calculateModulePrefixSize(prefix);
let newSize = module.length + (prefix.prefixSize - originalPrefixSize);
let newStartAddr = prefix.moduleEndAddy - (newSize - 4);
let alignment = 0;
if (newStartAddr % DEFAULT_START_ALIGNMENT !== 0) {
alignment = (newStartAddr % DEFAULT_START_ALIGNMENT);
newSize += alignment;
}
extensions[extensions.length - 1].padding = alignment;
prefix.prefixSize += alignment;
buffer = Buffer.alloc(newSize);
module.copy(buffer, prefix.prefixSize, originalPrefixSize /* source offset */);
prefix.moduleStartAddy = prefix.moduleEndAddy - (buffer.length - 4);
if (suffix.extensions) {
for (let ext of suffix.extensions) {
if (ext.type === ModuleInfo.ModuleInfoExtension.DYNAMIC_LOCATION) {
// This has to be updated for certain platforms if start address is moved
delete ext.data;
ext.moduleStartAddress = prefix.moduleStartAddy;
}
}
}
} else if (extensions.length > 0) {
// In suffix
suffix.extensions = extensions;
const originalSuffixSize = suffix.suffixSize;
suffix.suffixSize = calculateModuleSuffixSize(suffix);
buffer = Buffer.alloc(module.length + (suffix.suffixSize - originalSuffixSize));
module.copy(buffer, 0, 0, module.length - originalSuffixSize - 4 /* CRC-32 */);
prefix.moduleEndAddy = prefix.moduleStartAddy + buffer.length - 4;
}
if (moduleInfo && moduleInfo.maxSize) {
if (buffer.length > moduleInfo.maxSize) {
throw new PlatformLimitError({}, 'Resulting module exceeds platform size limits');
}
}
updateModulePrefix(buffer, prefix);
updateModuleSuffix(buffer, suffix);
updateModuleSha256(buffer);
updateModuleCrc32(buffer);
return buffer;
}
/**
* Remove extensions of a particular type.
*
* @param {Buffer} module Module to update
* @param {Array} exts List of extensions to add
* @param {Boolean} replaceWithSameType Append extensions as-is or replace existing extensions of the same type
* @returns {Promise<Buffer>}
*/
async function removeModuleExtensions({ module, exts = [] } = {}) {
if (exts.length === 0) {
throw new RangeError('Empty extension list');
}
const parser = new HalModuleParser();
const { prefixInfo: prefix } = await parser.parsePrefix({ fileBuffer: module });
const { suffixInfo: suffix } = await parser.parseSuffix({ fileBuffer: module });
prefix.moduleStartAddy = sanitizeAddress(prefix.moduleStartAddy);
prefix.moduleEndAddy = sanitizeAddress(prefix.moduleEndAddy);
const flags = prefix.moduleFlags;
if (flags & ModuleFlags.COMPRESSED) {
throw new RangeError(`Can't add extensions to a compressed module`);
}
if (flags & ModuleFlags.COMBINED) {
throw new RangeError(`Can\'t add extensions to a combined module`);
}
const suffixSize = suffix.suffixSize;
if (suffixSize < MIN_MODULE_SUFFIX_SIZE || suffixSize > MAX_MODULE_SUFFIX_SIZE) {
throw new RangeError('Invalid suffix size');
}
let dataSize = prefix.moduleEndAddy - prefix.moduleStartAddy + 4 /* CRC-32 */;
const prefixOffs = prefix.prefixOffset || 0;
if (module.length < prefixOffs + MODULE_PREFIX_SIZE + suffixSize + 4 || module.length !== dataSize) {
throw new RangeError('Invalid size of the module data');
}
const moduleInfo = firmwareModuleInfoForPlatformAndFunction(prefix.platformID, prefix.moduleFunction, prefix.moduleIndex);
let extensionsInPrefix = false;
if ((prefix.moduleFlags & ModuleInfo.Flags.PREFIX_EXTENSIONS) || (moduleInfo && moduleInfo.growsLeft)) {
extensionsInPrefix = true;
}
let extensions = [];
if (extensionsInPrefix) {
extensions = prefix.extensions;
} else {
extensions = suffix.extensions;
}
if (!extensions) {
extensions = [];
}
extensions = extensions.filter((val) => {
for (let ext of exts) {
if (val.type === ext) {
return false;
}
}
return true;
});
let buffer = null;
if (extensionsInPrefix) {;
prefix.extensions = extensions;
} else {
suffix.extensions = extensions;
}
// Always add END extension: it is mandatory to be present in module prefix extensions
// and due to the fact that product data for some of the platforms may not use an extension and just be
// raw data, to indicate end we will also use END extension here.
if (extensions.length > 0 && extensions[extensions.length - 1].type !== ModuleInfo.ModuleInfoExtension.END &&
extensions[extensions.length - 1].type !== ModuleInfo.ModuleInfoExtension.PRODUCT_DATA) {
extensions.push({
type: ModuleInfo.ModuleInfoExtension.END
});
}
if (extensionsInPrefix && extensions.length > 0) {
if (prefixOffs > 0) {
throw new RangeError('Extensions in prefix are not supported for modules with non-zero prefix offset');
}
prefix.moduleFlags |= ModuleInfo.Flags.PREFIX_EXTENSIONS;
prefix.extensions = extensions;
const originalPrefixSize = prefix.prefixSize;
delete extensions[extensions.length - 1].data;
delete extensions[extensions.length - 1].length;
prefix.prefixSize = calculateModulePrefixSize(prefix);
let newSize = module.length + (prefix.prefixSize - originalPrefixSize);
let newStartAddr = prefix.moduleEndAddy - (newSize - 4);
let alignment = 0;
if (newStartAddr % DEFAULT_START_ALIGNMENT !== 0) {
alignment = (newStartAddr % DEFAULT_START_ALIGNMENT);
newSize += alignment;
}
extensions[extensions.length - 1].padding = alignment;
prefix.prefixSize += alignment;
buffer = Buffer.alloc(newSize);
module.copy(buffer, prefix.prefixSize, originalPrefixSize /* source offset */);
prefix.moduleStartAddy = prefix.moduleEndAddy - (buffer.length - 4);
if (suffix.extensions) {
for (let ext of suffix.extensions) {
if (ext.type === ModuleInfo.ModuleInfoExtension.DYNAMIC_LOCATION) {
// This has to be updated for certain platforms if start address is moved
delete ext.data;
ext.moduleStartAddress = prefix.moduleStartAddy;
}
}
}
} else if (extensions.length > 0) {
// In suffix
suffix.extensions = extensions;
const originalSuffixSize = suffix.suffixSize;
suffix.suffixSize = calculateModuleSuffixSize(suffix);
buffer = Buffer.alloc(module.length + (suffix.suffixSize - originalSuffixSize));
module.copy(buffer, 0, 0, module.length - originalSuffixSize - 4 /* CRC-32 */);
prefix.moduleEndAddy = prefix.moduleStartAddy + buffer.length - 4;
}
if (moduleInfo && moduleInfo.maxSize) {
if (buffer.length > moduleInfo.maxSize) {
throw new PlatformLimitError({}, 'Resulting module exceeds platform size limits');
}
}
updateModulePrefix(buffer, prefix);
updateModuleSuffix(buffer, suffix);
updateModuleSha256(buffer);
updateModuleCrc32(buffer);
return buffer;
}
/**
* list extensions of a particular type.
*
* @param {Buffer} module Module to update
* @param {Array} exts List of extensions to add
* @returns {Promise<[]>}
*/
async function listModuleExtensions({ module, exts = [] } = {}) {
if (exts.length === 0) {
throw new RangeError('Empty extension list');
}
const parser = new HalModuleParser();
const { prefixInfo: prefix } = await parser.parsePrefix({ fileBuffer: module });
const { suffixInfo: suffix } = await parser.parseSuffix({ fileBuffer: module });
prefix.moduleStartAddy = sanitizeAddress(prefix.moduleStartAddy);
prefix.moduleEndAddy = sanitizeAddress(prefix.moduleEndAddy);
const flags = prefix.moduleFlags;
if (flags & ModuleFlags.COMPRESSED) {
throw new RangeError(`Can't add extensions to a compressed module`);
}
if (flags & ModuleFlags.COMBINED) {
throw new RangeError(`Can\'t add extensions to a combined module`);
}
const suffixSize = suffix.suffixSize;
if (suffixSize < MIN_MODULE_SUFFIX_SIZE || suffixSize > MAX_MODULE_SUFFIX_SIZE) {
throw new RangeError('Invalid suffix size');
}
let dataSize = prefix.moduleEndAddy - prefix.moduleStartAddy + 4 /* CRC-32 */;
const prefixOffs = prefix.prefixOffset || 0;
if (module.length < prefixOffs + MODULE_PREFIX_SIZE + suffixSize + 4 || module.length !== dataSize) {
throw new RangeError('Invalid size of the module data');
}
const moduleInfo = firmwareModuleInfoForPlatformAndFunction(prefix.platformID, prefix.moduleFunction, prefix.moduleIndex);
let extensionsInPrefix = false;
if ((prefix.moduleFlags & ModuleInfo.Flags.PREFIX_EXTENSIONS) || (moduleInfo && moduleInfo.growsLeft)) {
extensionsInPrefix = true;
}
let extensions = [];
if (extensionsInPrefix) {
extensions = prefix.extensions;
} else {
extensions = suffix.extensions;
}
if (!extensions) {
extensions = [];
}
extensions = extensions.filter((val) => {
for (let ext of exts) {
if (val.type === ext) {
return true;
}
}
return false;
});
return extensions;
}