Repository navigation
Expand file tree
/
Copy pathmultiimagewritethread.cpp
More file actions
1370 lines (1137 loc) · 42.9 KB
/
Copy pathmultiimagewritethread.cpp
File metadata and controls
1370 lines (1137 loc) · 42.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
#include "multiimagewritethread.h"
#include "dto/blockdevinfo.h"
#include "dto/blockdevpartitioninfo.h"
#include "dto/contentinfo.h"
#include "dto/mtddevinfo.h"
#include "dto/rawfileinfo.h"
#include "dto/ubivolumeinfo.h"
#include "dto/winceimage.h"
#include "config.h"
#include "json.h"
#include "util.h"
#include "mtdnamedevicetranslator.h"
#include <QDir>
#include <QFile>
#include <QDebug>
#include <QProcess>
#include <QProcessEnvironment>
#include <QSettings>
#include <QElapsedTimer>
#include <unistd.h>
#include <linux/fs.h>
#include <sys/ioctl.h>
#include <QtCore>
#include <QtEndian>
#include <QtConcurrent>
MultiImageWriteThread::MultiImageWriteThread(ConfigBlock *configBlock, ModuleInformation *moduleInformation, QObject *parent) :
QThread(parent), _configBlock(configBlock), _moduleInformation(moduleInformation), _extraSpacePerPartition(0), _bytesWritten(0)
{
QDir dir;
if (!dir.exists(TEMP_MOUNT_FOLDER))
dir.mkpath(TEMP_MOUNT_FOLDER);
if (!QFile::exists(PIPEVIEWER_NAMEDPIPE))
makeFifo(PIPEVIEWER_NAMEDPIPE);
if (!QFile::exists(MD5SUM_NAMEDPIPE))
makeFifo(MD5SUM_NAMEDPIPE);
}
void MultiImageWriteThread::setImage(const QString &folder, const QString &infofile, const QString &baseurl, enum ImageSource source)
{
/* Make sure that baseurl is empty for local image sources, we rely on it */
if (ImageInfo::isNetwork(source))
_image = new ImageInfo(folder, infofile, baseurl, source, this);
else
_image = new ImageInfo(folder, infofile, QString(), source, this);
}
void MultiImageWriteThread::updateStatus(QString status)
{
emit statusUpdate(QString("%1: %2").arg(_image->name(), status));
}
void MultiImageWriteThread::run()
{
QList<BlockDevInfo *> *blockdevs = _image->blockdevs();
QList<MtdDevInfo *> *mtddevs = _image->mtddevs();
qDebug() << "Processing Image:" << _image->name();
if (!_configBlock) {
emit error(tr("No valid config block available"));
return;
}
/* Run prepare script */
if (!_image->prepareScript().isEmpty()) {
QString prepareScript = _image->folder() + "/" + _image->prepareScript();
if (!QFile::exists(prepareScript)) {
emit error(tr("Prepare script '%1' does not exist").arg(prepareScript));
return;
}
QByteArray output;
if (!runScript(prepareScript, output)) {
emit error(tr("Error executing prepare script") + "\n" + output);
return;
}
}
foreach (BlockDevInfo *blockdev, *blockdevs) {
qDebug() << "Processing blockdev: " << blockdev->name();
QByteArray blockDevice = "/dev/" + blockdev->name().toLatin1();
if (!QFile::exists(blockDevice)) {
emit error(tr("Block device '%1' does not exist").arg(QString(blockDevice)));
return;
}
blockdev->setBlockDevice(blockDevice);
if (!processBlockDev(blockdev))
return;
}
if (!mtddevs->empty()) {
MtdNameDeviceTranslator mtdNameDev;
foreach (MtdDevInfo *mtddev, *mtddevs) {
QString mtdname = mtddev->name();
QString mtddevname = mtdNameDev.translate(mtdname);
qDebug() << "Processing mtddev: " << mtddevname;
QByteArray mtdDevice = "/dev/" + mtddevname.toLatin1();
if (!QFile::exists(mtdDevice)) {
emit error(tr("Mtd device '%1' does not exist").arg(QString(mtdDevice)));
return;
}
mtddev->setMtdDevice(mtdDevice);
if (!processMtdDev(mtddev))
return;
}
}
/* Write config block if:
* - migrating it from alternate to standard location
* - writing a new config block that was not yet written previously
*/
_moduleInformation->writeConfigBlockIfNeeded(_configBlock);
/* Set U-Boot environment */
if (!_image->uBootEnv().isEmpty()) {
QString uBootEnv = _image->folder() + "/" + _image->uBootEnv();
QByteArray output;
QStringList fwargs;
fwargs << "--config";
fwargs << _moduleInformation->fwEnvConfig();
fwargs << "--defenv";
fwargs << "/dev/null";
fwargs << "--script";
fwargs << uBootEnv;
if (!runCommand("/usr/bin/fw_setenv", fwargs, output))
{
emit error(tr("Error setting U-Boot environment") + "\n" + output);
return;
}
}
/* Run wrap-up script */
if (!_image->wrapupScript().isEmpty()) {
QString wrapupScript = _image->folder() + "/" + _image->wrapupScript();
if (!QFile::exists(wrapupScript)) {
emit error(tr("Wrap-up script '%1' does not exist").arg(wrapupScript));
return;
}
QByteArray output;
if (!runScript(wrapupScript, output)) {
emit error(tr("Error executing wrap-up script") + "\n" + output);
return;
}
}
emit statusUpdate(tr("Finish writing (syncing)"));
sync();
emit completed();
qDebug() << "Write Thread finished";
}
bool MultiImageWriteThread::runScript(QString script, QByteArray &output)
{
QProcess p;
QProcessEnvironment env;
QStringList cmd(script);
/* $1: product id */
cmd.append(_configBlock->getProductNumber());
/* $2: board rev */
cmd.append(_configBlock->getBoardRev());
/* $3: serial */
cmd.append(_configBlock->getSerialNumber());
/* $4: image folder */
cmd.append(_image->folder());
env.insert("PATH", "/bin:/usr/bin:/sbin:/usr/sbin");
qDebug() << "Executing:" << "/bin/sh" << cmd;
qDebug() << "Env:" << env.toStringList();
p.setProcessChannelMode(QProcess::MergedChannels);
p.setProcessEnvironment(env);
p.setWorkingDirectory(_image->folder());
p.start("/bin/sh", cmd);
if (!p.waitForFinished(30000))
qDebug() << "Warning: Script took longer than 30s.";
p.waitForFinished(-1);
output = p.readAll();
qDebug() << "Output:" << output;
qDebug() << "Finished with exit code:" << p.exitCode();
return p.exitCode() == 0;
}
bool MultiImageWriteThread::runCommand(const QString &cmd, const QStringList &args, QByteArray &output, const QByteArray &input, int msecs, const QString &workdir)
{
QProcess p;
qDebug() << "Running Command: " << cmd << args;
p.setProcessChannelMode(QProcess::MergedChannels);
p.setWorkingDirectory(workdir);
p.start(cmd, args);
if (!input.isEmpty()) {
p.write(input);
p.closeWriteChannel();
}
if (!p.waitForFinished(msecs))
qDebug() << "Warning: Command took longer than" << msecs << "ms.";
output = p.readAll();
if (p.exitCode() > 0)
qDebug() << "Output:" << output;
qDebug() << "Finished with exit code:" << p.exitCode();
return p.exitCode() == 0;
}
bool MultiImageWriteThread::processMtdDev(MtdDevInfo *mtddev)
{
QByteArray device = mtddev->mtdDevice();
qint64 totaluncompressedsize = 0;
ContentInfo *content = mtddev->content();
if (content != NULL) {
QList<RawFileInfo *> rawFiles = filterRawFileInfo(content->rawFiles());
foreach (RawFileInfo *rawFile, rawFiles)
totaluncompressedsize += rawFile->size();
}
QList<UbiVolumeInfo *> *volumes = mtddev->ubiVolumes();
if (volumes->length() > 0) {
foreach(UbiVolumeInfo *volume, *volumes) {
if (volume->content() != NULL) {
totaluncompressedsize += volume->content()->uncompressedSize();
QList<RawFileInfo *> rawFiles = filterRawFileInfo(volume->content()->rawFiles());
foreach (RawFileInfo *rawFile, rawFiles)
totaluncompressedsize += rawFile->size();
}
}
}
WinCEImage *winceimage = mtddev->winCEImage();
if (winceimage != NULL)
totaluncompressedsize += winceimage->size();
emit parsedImagesize(totaluncompressedsize * 1024 * 1024);
/* Erase partition if explicit erase is requested or raw content is specified */
if (mtddev->erase() || content != NULL) {
QByteArray output;
updateStatus(tr("Erasing partition"));
if (!eraseMtdDevice(device, output)) {
emit error(tr("Erasing flash failed") + "\n" + output);
return false;
}
}
if (content != NULL) {
if (!processMtdContent(content, device))
return false;
}
if (volumes->length() > 0) {
if (!processUbi(volumes, device))
return false;
}
if (winceimage != NULL) {
if (!processWinCEImage(winceimage, device))
return false;
}
return true;
}
bool MultiImageWriteThread::processBlockDev(BlockDevInfo *blockdev)
{
if (blockdev->erase()) {
updateStatus(tr("Erasing partition"));
/*
* We are erasing the partition which contains the config block! Make sure the config block gets
* written at the end of the erase process
*/
if (blockdev->name() == _moduleInformation->configBlockPartition())
_configBlock->needsWrite = true;
QByteArray output;
if (!eraseBlockDevice(blockdev->blockDevice(), 0, 0, output)) {
emit error(tr("Discarding content on device %1 failed").arg(blockdev->name()) + "\n" + output);
return false;
}
_moduleInformation->writeConfigBlockIfNeeded(_configBlock);
}
QList<BlockDevPartitionInfo *> *partitions = blockdev->partitions();
if (!partitions->isEmpty())
{
/* Writing partition table to this blockdev */
if (!processPartitions(blockdev, partitions))
return false;
}
ContentInfo *content = blockdev->content();
if (content != NULL) {
QByteArray device = blockdev->blockDevice();
if (!processContent(content, device))
return false;
}
/*
* The active eMMC boot partition (see eMMC standard) might change by a U-Boot update mechansim.
* When we flash a new TEZI image and boot partition 1 is still active, we will continue to boot the old U-Boot.
* Here we make sure that we set the active boot partition back to boot0 if it changed.
*/
if (blockdev->name().startsWith("mmcblk") && blockdev->name().endsWith("boot0")) {
return setBootPartition0(blockdev);
}
return true;
}
bool MultiImageWriteThread::processPartitions(BlockDevInfo *blockdev, QList<BlockDevPartitionInfo *> *partitions)
{
int totalnominalsize = 0, totaluncompressedsize = 0, numparts = 0, numexpandparts = 0;
/* Calculate space requirements, and check special requirements */
int totalSectors = getFileContents("/sys/class/block/" + blockdev->name() + "/size").trimmed().toULongLong();
/* Reserve 34 sectors at the end of the disk for the secondary GPT header */
if (blockdev->tableType() == "gpt")
totalSectors -= 34;
/* Currently extended partitions are not supported with MBR */
int max_part_tables = 4;
/* With GPT the maximum partition number can be limited by CONFIG_MMC_BLOCK_MINORS. We have set it to 16 for Tezi kernels. */
if (blockdev->tableType() == "gpt")
max_part_tables = 16;
if (partitions->count() > max_part_tables) {
emit error(tr("The Toradex Easy Installer supports up to %1 partitions on a single device using %2 partition table. %3 partitions have been specified.")
.arg(QString::number(max_part_tables), blockdev->tableType().toUpper(),QString::number(partitions->count())));
return false;
}
/* We need PARTITION_ALIGNMENT sectors at the begining for MBR and general alignment (currently 4MiB) */
int availableMB = (totalSectors - PARTITION_ALIGNMENT) / 2048;
/* key: partition number, value: partition information */
QMap<int, BlockDevPartitionInfo *> partitionMap;
foreach (BlockDevPartitionInfo *partition, *partitions)
{
qDebug() << "Partition:" << numparts << "Type:" << partition->partitionType();
numparts++;
if ( partition->wantMaximised() )
numexpandparts++;
totalnominalsize += partition->partitionSizeNominal();
ContentInfo *content = partition->content();
if (content != NULL)
totaluncompressedsize += content->uncompressedSize();
int reqPart = partition->requiresPartitionNumber();
if (reqPart)
{
if (partitionMap.contains(reqPart))
{
emit error(tr("More than one content requires partition number %1").arg(reqPart));
return false;
}
partition->setPartitionDevice(blockdev->blockDevice() + "p" + QByteArray::number(reqPart));
partitionMap.insert(reqPart, partition);
}
/* Maximum overhead per partition for alignment */
if (partition->wantMaximised() || (partition->partitionSizeNominal()*2048) % PARTITION_ALIGNMENT != 0)
totalnominalsize += PARTITION_ALIGNMENT/2048;
}
if (numexpandparts)
{
/* Extra spare space available for partitions that want to be expanded */
_extraSpacePerPartition = (availableMB-totalnominalsize)/numexpandparts;
}
emit parsedImagesize(qint64(totaluncompressedsize)*1024*1024);
if (totalnominalsize > availableMB)
{
emit error(tr("Not enough disk space. Need %1 MB, got %2 MB").arg(QString::number(totalnominalsize), QString::number(availableMB)));
return false;
}
/* Assign logical partition numbers to partitions that did not reserve a special number */
int pnr = 1;
foreach (BlockDevPartitionInfo *partition, *(blockdev->partitions()))
{
if (!partition->requiresPartitionNumber())
{
while (partitionMap.contains(pnr))
pnr++;
partitionMap.insert(pnr, partition);
partition->setPartitionDevice(blockdev->blockDevice() + "p" + QByteArray::number(pnr));
}
}
/* Set partition starting sectors and sizes. */
int offset = PARTITION_ALIGNMENT;
int id = 0;
QList<BlockDevPartitionInfo *> partitionList = partitionMap.values();
foreach (BlockDevPartitionInfo *p, partitionList)
{
if (p->offset()) /* OS wants its partition at a fixed offset */
{
if (p->offset() < offset)
{
emit error(tr("Fixed partition offset too low (partition %1, minimal offset %2, requested offset %3).")
.arg(QString::number(id), QString::number(offset), QString::number(p->offset())));
return false;
}
offset = p->offset();
}
else
{
/* Adhere to partition alignment */
if (offset % PARTITION_ALIGNMENT != 0)
{
offset += PARTITION_ALIGNMENT-(offset % PARTITION_ALIGNMENT);
}
p->setOffset(offset);
}
int partsizeMB = p->partitionSizeNominal();
if ( p->wantMaximised() )
partsizeMB += _extraSpacePerPartition;
int partsizeSectors = partsizeMB * 2048;
if (p == partitionList.last())
{
/* Let last partition have any remaining space */
if (p->wantMaximised())
partsizeSectors = totalSectors - offset;
}
else
{
if (p->wantMaximised() && partsizeSectors % PARTITION_ALIGNMENT != 0)
{
/* Enlarge partition to close gap to next partition */
partsizeSectors += PARTITION_ALIGNMENT - (partsizeSectors % PARTITION_ALIGNMENT);
}
}
p->setPartitionSizeSectors(partsizeSectors);
offset += partsizeSectors;
id++;
}
emit statusUpdate(tr("Writing partition table"));
if (!writePartitionTable(blockdev->blockDevice(), blockdev->tableType(), partitionMap))
return false;
/* Zero out first sector of partitions, to make sure to get rid of previous file system (label) */
emit statusUpdate(tr("Zero'ing start of each partition"));
foreach (BlockDevPartitionInfo *p, partitionMap.values())
{
if (p->partitionSizeSectors())
QProcess::execute("/bin/dd count=1 bs=512 if=/dev/zero of="+p->partitionDevice());
}
/* Install each partition */
foreach (BlockDevPartitionInfo *p, *partitions)
{
ContentInfo *content = p->content();
if (content != NULL) {
QByteArray partdevice = p->partitionDevice();
if (!processContent(content, partdevice))
return false;
}
}
return true;
}
bool MultiImageWriteThread::writePartitionTable(const QByteArray &blockdevpath, const QString &tableType, const QMap<int, BlockDevPartitionInfo *> &partitionMap)
{
/* Write partition table using sfdisk */
QByteArray partitionTable;
QByteArray cmdOutput;
QStringList cmdArgs;
for (int i = 1; i <= partitionMap.keys().last(); i++)
{
if (partitionMap.contains(i))
{
BlockDevPartitionInfo *p = partitionMap.value(i);
partitionTable.append("start=");
partitionTable.append(QByteArray::number(p->offset()));
partitionTable.append(",size=");
partitionTable.append(QByteArray::number(p->partitionSizeSectors()));
partitionTable.append(",type=");
partitionTable.append(p->partitionType());
if (p->active()) {
if (tableType == "gpt")
partitionTable.append(",attrs=LegacyBIOSBootable");
else
partitionTable.append(",bootable");
}
partitionTable.append("\n");
}
else
{
partitionTable.append("0,0\n");
}
}
qDebug() << "New partition table:";
qDebug() << partitionTable;
cmdArgs << "-uS" << "--label" << tableType << QString(blockdevpath);
if (!runCommand("/usr/sbin/sfdisk", cmdArgs, cmdOutput, partitionTable, -1))
{
emit error(tr("Error creating partition table") + "\n" + cmdOutput);
return false;
}
else
{
qDebug() << "sfdisk done, output:" << cmdOutput;
}
/*
* Since udev can trigger partition table reread thus
* removing asynchronously for a while the partition devices
* we wait for all queued events to be processed.
*/
cmdArgs.clear();
cmdArgs << "settle";
runCommand("/sbin/udevadm", cmdArgs, cmdOutput, nullptr, -1);
for (int i = 1; i <= partitionMap.keys().last(); i++) {
if (partitionMap.contains(i))
{
BlockDevPartitionInfo *p = partitionMap.value(i);
int timeout = 100;
while (!QFile::exists(p->partitionDevice()) && --timeout)
QThread::msleep(10);
if (!timeout)
{
emit error(tr("Timeout waiting for partition device %1.").arg(QString(p->partitionDevice())));
return false;
}
}
}
return true;
}
bool MultiImageWriteThread::setBootPartition0(BlockDevInfo *blockdev)
{
QString mmc_cmd("/usr/bin/mmc");
/* We need the parent device /dev/mmcblk0 without boot0 */
QString mmc_parent = "/dev/" + blockdev->name().remove("boot0");
QStringList args_read = {"extcsd", "read", mmc_parent};
QByteArray extcsd;
if (!runCommand(mmc_cmd, args_read, extcsd)) {
emit error(tr("Error reading extcsd"));
return false;
}
if (!extcsd.contains("Boot Partition 1 enabled")) {
/*
* We check for send_ack here:
* 0x10 -> partition 2 enabled, no send_ack
* 0x50 -> partition 2 enabled, send_ack
* 0x31 -> user partition enabled, no send_ack
* 0x71 -> user partition enabled, send_ack
* We test if bit6 (0x40) in the PARTITION_CONFIG register is set
*/
QRegExp re(".*PARTITION_CONFIG: (0x[0-9a-fA-F]+).*");
if (re.indexIn(extcsd) == -1) {
emit error(tr("Could not get partition configuration (PARTITION_CONFIG)"));
return false;
}
bool ok;
int partition_config = re.cap(1).toInt(&ok, 0);
if (!ok) {
emit error(tr("Could not parse partition configuration (PARTITION_CONFIG)"));
return false;
}
QString send_ack = partition_config & 0x40 ? "1" : "0";
QStringList args_write = {"bootpart", "enable", "1", send_ack, mmc_parent};
QByteArray output;
qDebug() << "Change boot partition from 1 to 0 (factory default)";
if (!runCommand(mmc_cmd, args_write, output)) {
emit error(tr("Failed to change boot partition to 0") + "\n" + output);
return false;
}
}
return true;
}
bool MultiImageWriteThread::eraseMtdDevice(const QByteArray &mtddevice, QByteArray &output)
{
QStringList eraseargs;
eraseargs << "--quiet" << mtddevice << "0" << "0";
return runCommand("/usr/sbin/flash_erase", eraseargs, output, nullptr, -1);
}
bool MultiImageWriteThread::eraseBlockDevice(const QByteArray &blockdevice, qint64 start, qint64 end, QByteArray &output)
{
QStringList args;
/* If start and end is zero, blkdiscard will discard the whole eMMC */
if (start)
args.append(QString("-o %1").arg(start));
if (end)
args.append(QString("-l %1").arg(end));
args.append(blockdevice);
return runCommand("/usr/sbin/blkdiscard", args, output, nullptr, -1);
}
bool MultiImageWriteThread::processUbiContent(ContentInfo *contentInfo, QString ubivoldev)
{
bool result = true;
QString fstype = contentInfo->fsType();
QByteArray output;
if (fstype == "raw") {
updateStatus(tr("Writing raw files"));
QList<RawFileInfo *> rawFiles = filterRawFileInfo(contentInfo->rawFiles());
if (rawFiles.count() > 1)
qDebug() << "Warning: UBI volumes support only one raw file per partition. Will only flash first file.";
/* E.g. when no raw file for this product id... */
if (rawFiles.count() < 1)
return true;
/* Typically Kernel/Device Tree */
if (!ubiflash(_image->baseUrl(), ubivoldev, rawFiles.first()))
return false;
} else if(fstype == "ubifs") {
/* Typically the rootfs */
updateStatus(tr("Creating filesystem (%2)").arg(QString(fstype)));
QStringList mkfsargs;
mkfsargs << ubivoldev;
runCommand("/usr/sbin/mkfs.ubifs", mkfsargs, output);
QStringList mountargs;
mountargs << "-t" << "ubifs" << ubivoldev << TEMP_MOUNT_FOLDER;
if (!runCommand("mount", mountargs, output))
{
emit error(tr("Error mounting file system") + "\n" + output);
return false;
}
QString tarball = contentInfo->filename();
QStringList filelist = contentInfo->filelist();
result = processFileCopy(_image->baseUrl(), tarball, filelist, true, false);
if (!runCommand("umount", QStringList() << TEMP_MOUNT_FOLDER, output)) {
emit error(tr("Error unmounting file system") + "\n" + output);
return false;
}
}
return result;
}
bool MultiImageWriteThread::processUbi(QList<UbiVolumeInfo *> *volumes, QByteArray mtddevice)
{
bool result = true;
QByteArray output;
QStringList ubiformatargs;
ubiformatargs << mtddevice << "-q" << "-y";
if (!runCommand("/usr/sbin/ubiformat", ubiformatargs, output)) {
emit error(tr("Formatting UBI partition failed!") + "\n" + output);
return false;
}
QStringList ubiattachargs;
ubiattachargs << "-p" << mtddevice;
if (!runCommand("/usr/sbin/ubiattach", ubiattachargs, output)) {
emit error(tr("Attaching UBI failed!") + "\n" + output);
return false;
}
/* At this point UBI should be attached, add volumes */
int ubivolid = 0;
foreach (UbiVolumeInfo *ubivol, *volumes) {
QByteArray output;
QStringList ubimkvolargs;
ubimkvolargs << "/dev/ubi0" << "-N" << ubivol->name() << "-n" << QString::number(ubivolid);
if (ubivol->sizeKib() > 0)
ubimkvolargs << "-s" << QString("%1KiB").arg(ubivol->sizeKib());
else
ubimkvolargs << "-m";
if (!ubivol->type().isEmpty())
ubimkvolargs << "-t" << ubivol->type();
result = runCommand("/usr/sbin/ubimkvol", ubimkvolargs, output);
if (!result)
{
emit error(tr("Creating UBI volume failed!") + "\n" + output);
break;
}
QString ubivoldev = QString("/dev/ubi0_%1").arg(ubivolid);
if (ubivol->content())
{
result = processUbiContent(ubivol->content(), ubivoldev);
if (!result)
break;
}
ubivolid++;
}
runCommand("/usr/sbin/ubidetach", ubiattachargs, output);
return result;
}
QList<RawFileInfo *> MultiImageWriteThread::filterRawFileInfo(QList<RawFileInfo *> *rawFiles)
{
QList<RawFileInfo *> newList;
QString pid8 = _configBlock->getPID8();
foreach (RawFileInfo *rawFile, *rawFiles) {
/* Only check against product id if specified */
if (!rawFile->productIds().isEmpty()) {
if (!ConfigBlock::isProductSupported(pid8, rawFile->productIds()))
continue;
}
newList.append(rawFile);
}
return newList;
}
bool MultiImageWriteThread::processWinCEImage(WinCEImage *image, QByteArray mtddevice)
{
QString getfile;
const QString& file = image->imageFilename();
const QString& baseurl = _image->baseUrl();
if (!baseurl.isEmpty())
getfile = DOWNLOAD_COMMAND " '" + baseurl + file + "'";
else
getfile = "cat '" + file + "'";
QString uncompresscmd = getUncompressCommand(file, false);
/* Use pipe viewer to get bytes processed during the command */
QString cmd = QString("%1 | %2 | flash_wince -n %3 %4 -")
.arg(getfile, uncompresscmd, QString::number(image->nonFsSize()), mtddevice);
qDebug() << "Flash WinCE image file" << file;
return runwritecmd(cmd, false);
}
bool MultiImageWriteThread::processMtdContent(ContentInfo *content, QByteArray mtddevice)
{
QByteArray fstype = content->fsType();
if (fstype == "raw")
{
updateStatus(tr("Writing raw files"));
QList<RawFileInfo *> rawFiles = filterRawFileInfo(content->rawFiles());
foreach(RawFileInfo *rawFile, rawFiles) {
if (!nandflash(_image->baseUrl(), mtddevice, rawFile))
return false;
}
}
return true;
}
bool MultiImageWriteThread::processFileCopy(const QString &baseurl, const QString &tarball, const QStringList &filelist, bool linuxfs, bool hasacl)
{
bool resultfile = true;
bool resultfilelist = true;
if (baseurl.isEmpty())
updateStatus(tr("Extracting file(s)"));
else
updateStatus(tr("Downloading and extracting file(s)"));
if (!tarball.isEmpty())
resultfile = untar(baseurl, tarball, "/", linuxfs, hasacl);
if (!filelist.isEmpty()) {
foreach(QString entry, filelist) {
QStringList items = entry.split( ":" );
QString source = items.value(0);
QString destdir = "/";
bool unpack = false;
if (items.length() >= 2) {
if (!items.value(1).isEmpty())
destdir = items.value(1);
if (items.length() >= 3)
unpack = QVariant(items.value(2)).toBool();
}
if (unpack) {
if (!untar(baseurl, source, destdir, linuxfs, hasacl)) {
resultfilelist = false;
break;
}
} else if (!copy(baseurl, source, destdir)) {
resultfilelist = false;
break;
}
}
}
return resultfile && resultfilelist;
}
bool MultiImageWriteThread::processContent(ContentInfo *content, QByteArray partdevice)
{
QByteArray fstype = content->fsType();
QByteArray mkfsopt = content->mkfsOptions();
QByteArray label = content->label();
QString tarball = content->filename();
QStringList filelist = content->filelist();
if (label.size() > 15)
{
label.clear();
}
else if (!isLabelAvailable(label))
{
for (int i = 0; i < 10; i++)
{
if (isLabelAvailable(label + QByteArray::number(i)))
{
label = label + QByteArray::number(i);
break;
}
}
}
if (fstype == "raw")
{
updateStatus(tr("Writing raw files"));
QList<RawFileInfo *> rawFiles = filterRawFileInfo(content->rawFiles());
foreach (RawFileInfo *rawFile, rawFiles) {
if (!dd(_image->baseUrl(), partdevice, rawFile))
return false;
}
}
else if (fstype.startsWith("partclone"))
{
emit statusUpdate(tr("Writing partition clone image"));
if (!partclone_restore(_image->baseUrl(), tarball, partdevice))
return false;
}
else if (fstype != "unformatted")
{
emit statusUpdate(tr("Creating filesystem (%2)").arg(QString(fstype)));
if (!mkfs(partdevice, fstype, label, mkfsopt))
return false;
/* If there is no tarball/filelist specified, its an empty partition which is perfectly ok too */
if (tarball.isEmpty() && filelist.isEmpty())
return true;
bool linuxfs = true;
if (fstype == "fat" || fstype == "FAT" || fstype == "ntfs") {
linuxfs = false;
}
emit statusUpdate(tr("Mounting file system"));
QStringList mountargs;
mountargs << partdevice << TEMP_MOUNT_FOLDER;
/* All Linux block device FS are assumed to support ACL */
if (linuxfs)
mountargs << "-o" << "acl";
QString mountcmd;
if (fstype == "ntfs")
mountcmd = "/sbin/mount.ntfs-3g";
else
mountcmd = "mount";
QByteArray output;
if (!runCommand(mountcmd, mountargs, output))
{
emit error(tr("Error mounting file system") + "\n" + output);
return false;
}
bool resultfilecopy = processFileCopy(_image->baseUrl(), tarball, filelist, linuxfs, linuxfs);
if (!runCommand("umount", QStringList() << TEMP_MOUNT_FOLDER, output)) {
emit error(tr("Error unmounting file system") + "\n" + output);
return false;
}
return resultfilecopy;
}
return true;
}
bool MultiImageWriteThread::mkfs(const QByteArray &device, const QByteArray &fstype, const QByteArray &label, const QByteArray &mkfsopt)
{
QString cmd;
QStringList args;
if (fstype == "fat" || fstype == "FAT")
{
cmd = "/usr/sbin/mkfs.fat";
args << "-F" << "32";
if (!label.isEmpty())
args << "-n" << label;
}
else if (fstype == "ext2")
{
cmd = "/sbin/mkfs.ext2";
if (!label.isEmpty())
args << "-L" << label;
}
else if (fstype == "ext3")
{
cmd = "/sbin/mkfs.ext3";
if (!label.isEmpty())
args << "-L" << label;
}
else if (fstype == "ext4")
{
cmd = "/sbin/mkfs.ext4";
args << "-L" << label;
args << "-O ^metadata_csum";
args << "-T default";
}
else if (fstype == "ntfs")
{
cmd = "/sbin/mkfs.ntfs";
args << "--fast";
if (!label.isEmpty())
args << "-L" << label;
}
else {
emit error(tr("Unkown file system type"));
return false;
}
if (!mkfsopt.isEmpty()) {
foreach (QByteArray arr, mkfsopt.split(' '))
args << arr;
}
args << device;
QByteArray output;
if (!runCommand(cmd, args, output, nullptr, -1))
{
emit error(tr("Error creating file system") + "\n" + output);
return false;
}
return true;
}
bool MultiImageWriteThread::isLabelAvailable(const QByteArray &label)
{
return (QProcess::execute("/sbin/findfs LABEL="+label) != 0);