forked from 7Ji/ampart
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathampart.c
1750 lines (1683 loc) · 69.9 KB
/
ampart.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* A simple, fast, yet powerful partition tool for Amlogic's proprietary emmc partition format
*
* Copyright (C) 2022 7Ji ([email protected])
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version * of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdarg.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/sysmacros.h>
#include <dirent.h>
#include <fcntl.h>
#include <getopt.h>
#include <inttypes.h>
#include <libgen.h>
#include <linux/fs.h>
#include <unistd.h>
#include <zlib.h>
//#define VERSION "v0.1" // This should ONLY be uncommented for actual releases, for snapshot builds it will be generated using git commit hash instead
#define PART_NUM 0x20 // This should ALWAYS be 0x20=32, regardless of platform. Defining it here saves some precious time used on sizeof()
#define SIZE_PART 0x28 // This should ALWAYS be 0x28=40, regardless of platform. Defining it here saves some precious time used on sizeof()
#define SIZE_TABLE 0x518 // This should ALWAYS be 0x518=1304, regardless of platform. Defining it here saves some precious time used on sizeof()
#define SIZE_DTB_HEADER 0x28 // This should ALWAYS be 0x28=40, regardless of platform. Defining it here saves some precious time used on sizeof()
#define SIZE_MBR 0x200 // Count of bytes that should be \0 for whole emmc disk, as stock Amlogic emmc should have no MBR. Things may become tricky if users have created a mbr partition table. In that case auto-recognization may not work for dumped image for whole emmc (for whole emmc disk DEVICE though, auto-recognization works without checking MBR)
#define SIZE_DTB 0x40000 //256K
#define SIZE_DTB_UNCOMPRESS 0xA00000 //10M, yeah I know it's a lot, but hey, just in case there is a 'Super Compressor' that can compress this much data into a tiny 256K gzip (wow, a 40:1 ratio)
#define DTB_OFFSET 0x400000 //4M, relative to reserved part
#define PAGE_SIZE 0x800 //Minimum emmc I/O size
#define MAGIC_MULTI_DTB 0x5F4C4D41
#define MAGIC_SINGLE_DTB 0xEDFE0DD0
#define MAGIC_GZIPPED_DTB 0x00008B1F
#define MAGIC_XIAOMI_DTB 0x000089EF // The BS Xiaomi proprietary DTB format, found on a user's Xiaomi mibox3s (Chinese firmware, the global firmware does not have such a format)
#define MAGIC_PHICOMM_DTB 0x000004DA // The BS Phicomm proprietary DTB format, found on a user's Phicomm N1
// These are helper value used to parse around, to save extra process time after the first comparision using those magics listed above
#define DTB_TYPE_ILLEGAL 0 // We consider the initialized value 0 as illegal
#define DTB_TYPE_SINGLE 1
#define DTB_TYPE_MULTI 2
#define DTB_TYPE_GZIP 3
#define SYS_EMMC_DEVICE "emmc:0001"
#define SYS_MMCBLK "/sys/bus/mmc/drivers/mmcblk"
#define SYS_MMCBLK_UNBIND SYS_MMCBLK"/unbind"
#define SYS_MMCBLK_BIND SYS_MMCBLK"/bind"
#define RESERVED_DEV_NAMES "amaudio amaudio_ctl amaudio_utils amstream_abuf amstream_hevc amstream_mpps amstream_mpts amstream_rm amstream_sub amstream_vbuf amstream_vframe amsubtitle amvdac amvecm amvideo amvideo_poll aocec autofs block bus char console cpu_dma_latency cvbs ddr_parameter disk display dtb efuse esm fd firmware_vdec framerate_dev full fuse hwrng initctl input ion kmem kmsg log mali mapper media mem mqueue net network_latency null port ppmgr ppp psaux ptmx pts random rfkill rtc secmem shm snd stderr stdin stdout tsync tty ubi_ctrl uhid uinput unifykeys urandom vad vcs vcsa vfm vhci watchdog wifi_power zero"
#define TABLE_UPDATE_ACTION_NORMAL 0
#define TABLE_UPDATE_ACTION_DELETE 1
#define TABLE_UPDATE_ACTION_CLONE 2
const unsigned char dtb_partitions_start[]={0x70, 0x61, 0x72, 0x74, 0x69, 0x74, 0x69, 0x6F, 0x6E, 0x73};
const unsigned char dtb_partitions_end[]= {0,0,0,2,0,0,0,2,0,0,0,1};
#define LEN_DTB_PARTITIONS_START 10
#define LEN_DTB_PARTITIONS_END 12
struct partition {
char name[16];
uint64_t size;
uint64_t offset;
unsigned mask_flags;
// padding 4byte
};
struct insertion_helper {
struct partition *part;
bool insert;
};
struct partition_table {
char magic[4];
unsigned char version[12];
int part_num;
int checksum;
struct partition partitions[32];
};
struct table_helper {
struct partition_table *table;
struct partition *bootloader;
struct partition *reserved;
struct partition *env;
struct partition *logo;
struct partition *misc;
struct insertion_helper insertion[3];
short insertables;
};
struct disk_helper {
uint64_t start;
uint64_t free;
uint64_t size;
};
struct dtb_header {
uint32_t magic;
uint32_t totalsize; // Change if partitions removed
uint32_t off_dt_struct;
uint32_t off_dt_strings; // Change if partitions removed
uint32_t off_mem_rsvmap;
uint32_t version;
uint32_t last_comp_version;
uint32_t boot_cpuid_phys;
uint32_t size_dt_strings;
uint32_t size_dt_struct; // Change if partitions removed
// The three bad-boys will be decreased on the same level
};
struct options {
bool input_reserved;
bool input_device;
bool snapshot;
bool mode_clone;
bool mode_update;
bool dryrun;
bool no_reload;
bool check_compatibility;
bool no_node;
int dtb_type;
int dtb_subtype; // when type is gzipped, this stores the subtype (multi/single), otherwise always 0
char path_input[128]; // For fuck's sake, will there be a maniac hide their image this deeply?
char path_disk[128];
char dir_input[64];
char name_input[64];
char output[64];
uint64_t offset;
uint64_t size;
} options = {0};
// Dedicated string buffer, so we don't need to allocate over and over again
char s_buffer_1[9];
char s_buffer_2[9];
char s_buffer_3[9];
uint32_t table_checksum(struct partition *part, int part_num) {
int i, j;
uint32_t checksum = 0, *p;
for (i = 0; i < part_num; i++) {
p = (uint32_t *)part;
for (j = SIZE_PART/sizeof(checksum);
j > 0; j--) {
checksum += *p;
p++;
}
}
return checksum;
}
const char suffixes[]="BKMGTPEZY"; // static is not needed, when out of any function's scope
void size_byte_to_human_readable(char* buffer, uint64_t size) {
double num = size;
int i;
for (i=0; i<9; ++i) {
if (num <= 1024.0) {
break;
}
num /= 1024.0;
}
sprintf(buffer, "%4.2f%c", num, suffixes[i]);
return;
}
// Sometimes if you don't want create a buffer and don't mind split printf
void size_byte_to_human_readable_print(uint64_t size) {
double num = size;
int i;
for (i=0; i<9; ++i) {
if (num <= 1024.0) {
break;
}
num /= 1024.0;
}
printf("%4.2f%c", num, suffixes[i]);
return;
}
// Only shrink to the lowest point where size is still an integer
void size_byte_to_human_readable_int(char* buffer, uint64_t size) {
int i;
for (i=0; i<9; ++i) {
if (size <= 0x400 || size % 0x400) {
break;
}
size /= 0x400;
}
sprintf(buffer, "%"PRIu64"%c", size, suffixes[i]);
return;
}
// Fancier die function that supports formatting
void die (const char * format, ...) {
va_list vargs;
va_start (vargs, format);
fprintf (stderr, "ERROR: ");
vfprintf (stderr, format, vargs);
fprintf (stderr, "\n");
va_end (vargs);
exit (EXIT_FAILURE);
}
uint64_t four_kb_alignment(uint64_t size) {
unsigned remainder = size % 0x1000; // Would this even be negative? Guess not
if ( remainder ) {
size_byte_to_human_readable(s_buffer_1, size);
printf("Warning: size/offset %"PRIu64" (%s) is rounded up to ", size, s_buffer_1);
size += (0x1000-remainder);
size_byte_to_human_readable(s_buffer_1, size);
printf("%"PRIu64" (%s) for 4K alignment\n", size, s_buffer_1);
}
return size;
}
uint64_t size_human_readable_to_byte(char * size_h, bool * has_prefix) {
int length; // We manually obtain length here, because the pointer sent by getopt can not be used directly for obtaining the length
if ( !(length=strlen(size_h)) ) { // Die early for 0 length size_h
return 0;
}
int start;
uint64_t multiply;
char *prefix, *ptr = size_h;
char size_h_new[length+1];
prefix = &size_h[0];
if ( *prefix < '0' || *prefix > '9' ) {
if (size_h[0] == '+') {
if (has_prefix) {
*has_prefix = true;
}
strcpy(size_h_new, ++ptr);
start = 1;
}
else {
die("Illegal prefix found! You should only use + as prefix!");
}
}
else {
if (has_prefix) {
*has_prefix = false;
}
strcpy(size_h_new, ptr);
start = 0;
}
char *suffix = &(size_h_new[length-1-start]); // As the last should always be \0(NULL)
if ( *suffix < '0' || *suffix > '9' ) {
if ( *suffix == 'B' ) {
multiply = 1;
}
else if ( *suffix == 'K' ) {
multiply = 0x400;
}
else if ( *suffix == 'M' ) {
multiply = 0x100000;
}
else if ( *suffix == 'G' ) {
multiply = 0x40000000;
}
else {
die("Illegal suffix found! You should only use B, K, M or G as suffix!");
}
*suffix='\0'; // Replace suffix with null, the size string should be shorter now
}
else {
multiply = 1;
}
return strtoull(size_h_new, NULL, 10) * multiply;
}
uint64_t size_human_readable_to_byte_no_prefix(char * size_h, bool allow_empty) {
int length; // We manually obtain length here, because the pointer sent by getopt can not be used directly for obtaining the length
if ( !(length=strlen(size_h)) ) { // Die early for 0 length size_h
if (allow_empty) {
return 0;
}
else {
die("Offset/Size can NOT be empty");
}
}
uint64_t multiply;
char size_h_new[length+1];
strcpy(size_h_new, size_h);
char *suffix = &(size_h_new[length-1]); // As the last should always be \0(NULL)
if ( *suffix < '0' || *suffix > '9' ) {
if ( *suffix == 'B' ) {
multiply = 1;
}
else if ( *suffix == 'K' ) {
multiply = 0x400;
}
else if ( *suffix == 'M' ) {
multiply = 0x100000;
}
else if ( *suffix == 'G' ) {
multiply = 0x40000000;
}
else {
die("Illegal suffix found! You should only use B, K, M or G as suffix for offset/size!");
}
*suffix='\0'; // Replace suffix with null, the size string should be shorter now
}
else {
multiply = 1;
}
return strtoull(size_h_new, NULL, 10) * multiply;
}
void no_device_names(char *name) {
char device_names[] = RESERVED_DEV_NAMES;
char *token = strtok(device_names, " ");
while( token != NULL ) {
if (!strcmp(token, name)) {
die("Illegal partition name: '%s' will be used by other devices and should be AVOIDED", token);
}
token = strtok(NULL, " ");
}
return;
}
void valid_partition_name(char *name, bool allow_reserved) {
int i, length;
bool warned = false, warned_uppercase = false, warned_underscore = false;
char *c;
for(i=0; i<16; ++i) { // i can be 0-16, when it's 16, oops
c = &name[i];
if ( 'a' <= *c && *c <= 'z' ) {
continue;
}
else if ( 'A' <= *c && *c <= 'Z' ) {
if (!warned_uppercase) {
if (!warned) {
printf("Warning: Misbehaviour found in partition name '%s':\n", name);
warned = true;
}
puts(" - Uppercase letter (A-Z) is used, this is not recommended as it may confuse some kernel and bootloader");
warned_uppercase = true;
}
}
else if ( *c == '_' ) {
if (!warned_underscore) {
if (!warned) {
printf("Warning: Misbehaviour found in partition name '%s':\n", name);
warned = true;
}
puts(" - Underscore (_) is used, this is not recommended as it may confuse some kernel and bootloader");
warned_underscore = true;
}
}
else if ( *c == '\0' ) {
break;
}
else {
die("You can only use a-z, A-Z and _ for the partition name!");
}
}
if (i==0) {
die("Empty partition name is not allowed!");
};
if (*c != '\0') {
die("Partition name is too long and not terminated by NULL!");
}
if (!allow_reserved) {
if (!strcmp(name, "bootloader") || !strcmp(name, "reserved") || !strcmp(name, "env")) {
die("Illegal partition name '%s'! You can not use bootloader, reserved or env as partition name! These will be automatically generated by ampart from the old partition table!", name);
}
}
no_device_names(name);
return;
}
int get_part_argument_length (char *argument, bool allow_end) {
// We don't use strtok, as it will ignore an empty arg between : and :
int i;
char *c=argument;
bool valid=false;
for (i=0; i<100; ++i) { // I don't really think you can write an arg that long, but hey, just in case
if (*c == ':') {
*c = '\0'; // rewrite it to NULL so strcpy can play it safe
valid=true;
break;
}
else if (*c == '\0') {
if (allow_end) {
valid=true;
}
break;
}
++c;
}
if (!valid) {
die("Partation argument incomplete!");
}
return i; // the length here does not contain : or \0
}
void partition_from_argument (struct partition *partition, char *argument, struct disk_helper *disk) {
char argument_new[strlen(argument)+1], *arg=argument_new; // A seperate argument is used here so we won't mess up with the original one
strcpy(argument_new, argument);
// Name
int length = get_part_argument_length(argument_new, false);
if (!length) {
die("Partition name must be set!");
}
if ( length > 15 ) {
die("Partition name '%s' too long! It can only be 15 characters long!", arg);
}
valid_partition_name(arg, false);
strcpy(partition->name, arg);
printf(" - Name: %s\n", partition->name);
arg += length + 1;
// Offset
length = get_part_argument_length(arg, false);
if ( !length ) {
partition->offset=disk->start; // Auto increment offset
}
else {
bool relative;
partition->offset = four_kb_alignment(size_human_readable_to_byte(arg, &relative));
if (relative) {
partition->offset += disk->start;
}
if (partition->offset < disk->start) {
size_byte_to_human_readable(s_buffer_1, partition->offset);
size_byte_to_human_readable(s_buffer_2, disk->start);
die("Partition offset smaller than end of last partition: %"PRIu64"(%s) < %"PRIu64"(%s)", partition->offset, s_buffer_1, disk->start, s_buffer_2);
}
if (partition->offset > disk->size) {
size_byte_to_human_readable(s_buffer_1, partition->offset);
size_byte_to_human_readable(s_buffer_2, disk->start);
die("Partition offset greater than disk size: %"PRIu64"(%s) > %"PRIu64"(%s)", partition->offset, s_buffer_1, disk->start, s_buffer_2);
}
}
size_byte_to_human_readable(s_buffer_1, partition->offset);
printf(" - Offset: %"PRIu64" (%s)\n", partition->offset, s_buffer_1);
arg += length + 1;
// Size
length = get_part_argument_length(arg, false);
uint64_t partition_end;
if ( !length ) {
// Auto fill the rest
partition->size = disk->size - partition->offset;
partition_end = disk->size;
}
else {
partition->size=four_kb_alignment(size_human_readable_to_byte_no_prefix(arg, true));
partition_end = partition->offset + partition->size;
if ( partition_end > disk->size) {
size_byte_to_human_readable(s_buffer_1, partition_end);
size_byte_to_human_readable(s_buffer_2, disk->free);
die("Partition end point overflows! End point greater than disk size: %"PRIu64" (%s) > %"PRIu64" (%s)", partition_end, s_buffer_1, disk->free, s_buffer_2);
}
}
disk->start = partition_end;
disk->free = disk->size - partition_end;
size_byte_to_human_readable(s_buffer_1, partition->size);
printf(" - Size: %"PRIu64" (%s)\n", partition->size, s_buffer_1);
arg += length + 1;
// Mask
length = get_part_argument_length(arg, true);
if ( !length ) {
partition->mask_flags=4;
}
else {
partition->mask_flags=atoi(arg);
if ((partition->mask_flags != 1) && (partition->mask_flags != 2) && (partition->mask_flags != 4)) {
//printf("%d\n", partition->mask_flags);
die("Invalid mask %u, must be either 1, 2 or 4, or leave it alone to use default value 4", partition->mask_flags);
}
}
printf(" - Mask: %u\n", partition->mask_flags);
return;
}
// Just basic filtering
void partition_from_argument_clone(struct partition *partition, char *argument) {
char argument_new[strlen(argument)+1], *arg=argument_new; // A seperate argument is used here so we won't mess up with the original one
strcpy(argument_new, argument);
// Name
int length = get_part_argument_length(argument_new, false);
if (!length) {
die("Partition name must be set!");
}
if ( length > 15 ) {
die("Partition name '%s' too long! It can only be 15 characters long!", arg);
}
valid_partition_name(arg, true);
strcpy(partition->name, arg);
printf(" - Name: %s\n", partition->name);
arg += length + 1;
// Offset
length = get_part_argument_length(arg, false);
if ( !length ) {
die("In clone mode part offset MUST be set");
}
partition->offset = size_human_readable_to_byte_no_prefix(arg, false);
size_byte_to_human_readable(s_buffer_1, partition->offset);
printf(" - Offset: %"PRIu64" (%s)\n", partition->offset, s_buffer_1);
arg += length + 1;
// Size
length = get_part_argument_length(arg, false);
uint64_t partition_end;
if ( !length ) {
die("In clone mode part size MUST be set");
}
partition->size=size_human_readable_to_byte_no_prefix(arg, false);
size_byte_to_human_readable(s_buffer_1, partition->size);
printf(" - Size: %"PRIu64" (%s)\n", partition->size, s_buffer_1);
arg += length + 1;
// Mask
length = get_part_argument_length(arg, true);
if ( !length ) {
die("In clone mode part mask MUST be set");
}
partition->mask_flags=atoi(arg);
if ((partition->mask_flags != 0) && (partition->mask_flags != 1) && (partition->mask_flags != 2) && (partition->mask_flags != 4)) {
//printf("%d\n", partition->mask_flags);
die("Invalid mask %u, must be either 0, 1, 2 or 4", partition->mask_flags);
}
printf(" - Mask: %u\n", partition->mask_flags);
return;
}
uint64_t get_max_part_end(struct partition_table *table) {
int i;
uint64_t end=0, part_end=0;
struct partition * part=NULL;
for (i=0; i<table->part_num; ++i) {
part = &(table->partitions[i]);
part_end = part->offset + part->size;
if (part_end>end) {
end=part_end;
}
}
return end;
}
void table_update(struct partition_table *table, char * argument, struct disk_helper *disk) {
disk->start = get_max_part_end(table);
disk->free=disk->size-disk->start;
char argument_new[strlen(argument)+1], *arg=argument_new;
strcpy(argument_new, argument);
int length;
if (argument[0] != '^') { // No selector, creation mode
puts("No selector found, normal creation mode");
if (table->part_num == PART_NUM) {
die("Attempting to add partition when partition count is already at its maximum (32)");
}
partition_from_argument(&(table->partitions[(table->part_num)++]), arg, disk);
return;
}
++arg; // From the selector themselvies
short action=TABLE_UPDATE_ACTION_NORMAL; // 0 for normal, 1 for delete, 2 for clone
short relative=0;
int id;
if (arg[0] == '-') { // Tail selection
puts("Notice: negative selector encountered");
relative=-1;
}
else if (arg[0] >= '0' && arg[0] <= '9') { // Head selection
puts("Notice: positive selector encountered");
relative=1;
}
length=get_part_argument_length(arg, true);
if (!length) {
die("Partition selector must be EXPLICTLY set");
}
if (arg[length-1] == '?') {
action=TABLE_UPDATE_ACTION_DELETE;
arg[length-1] = '\0';
}
else if (arg[length-1] == '%') {
action=TABLE_UPDATE_ACTION_CLONE;
if (table->part_num == PART_NUM) {
die("Trying to clone clone a partition when partition count is already at its maximum (32)");
}
arg[length-1] = '\0';
}
if (!length) {
die("Partition selector must be EXPLICTLY set");
}
int i;
struct partition *part=NULL;
if (relative) {
id = atoi(arg);
printf("Relative selector before parsing: %i\n", id);
if (relative == -1) {
id = table->part_num + id;
}
if (id < 0 || id > table->part_num) {
die("Illegal part id: %d. Max: %i", id, table->part_num);
}
part = &(table->partitions[id]);
}
else {
struct partition *part_cmp=NULL;
for (i=0; i<table->part_num; ++i) {
part_cmp = &(table->partitions[i]);
if (!strcmp(part_cmp->name, arg)) {
id = i;
part=part_cmp;
break;
}
}
if (part == NULL) {
die("Failed to find a partition with name '%s' in the old partition table", arg);
}
}
if (part == NULL) {
// It's really unneccessary to check it again here, but just for safety
die("No partition selected, refuse to continue");
}
printf("Partition selected: %i:%s\n", id, part->name);
if (action==TABLE_UPDATE_ACTION_DELETE) {
for (i=id; i<table->part_num-1; ++i) { // Move all parts one backwards
memcpy(&(table->partitions[i]), &(table->partitions[i+1]), SIZE_PART);
}
memset(&(table->partitions[i]), 0, SIZE_PART);
--(table->part_num);
printf("Deleted partition %i (oh, I forgot what it actually was)\n", id);
return;
}
if (action==TABLE_UPDATE_ACTION_CLONE) {
arg += length + 1;
length = get_part_argument_length(arg, true);
if (!length) {
die("Partition name must be set for the new cloned partition");
}
if (length > 15) {
die("Partition name '%s' for the new cloned partition too long! It can only be 15 characters long!", arg);
}
valid_partition_name(arg, false);
memcpy(&(table->partitions[(table->part_num++)]), part, SIZE_PART);
strcpy(table->partitions[table->part_num-1].name, arg);
return;
}
// Modification mode
// name
arg += length + 1;
length = get_part_argument_length(arg, false);
if (length) {
if (length > 15) {
die("New partition name '%s' too long! It can only be 15 characters long!", arg);
}
valid_partition_name(arg, false);
strcpy(part->name, arg);
printf(" - Name -> %s\n", part->name);
}
// offset
arg += length + 1;
length = get_part_argument_length(arg, false);
relative = 0;
uint64_t temp;
if (length) {
if ( arg[0] == '-' ) {
relative = -1;
}
else if (arg[0] == '+') {
relative = 1;
}
if (relative) {
temp = size_human_readable_to_byte_no_prefix(arg+1, false);
}
if (relative) {
if (relative == 1) {
part->offset += temp;
}
else {
part->offset -= temp;
}
}
else {
part->offset = temp;
}
part->offset = four_kb_alignment(part->offset);
size_byte_to_human_readable(s_buffer_1, part->offset);
printf(" - Offset -> %"PRIu64"(%s)\n", part->offset, s_buffer_1);
}
// Size
arg += length + 1;
length = get_part_argument_length(arg, false);
relative = 0;
if (length) {
if ( arg[0] == '-' ) {
relative = -1;
}
else if (arg[0] == '+') {
relative = 1;
}
if (relative) {
temp = size_human_readable_to_byte_no_prefix(arg+1, false);
}
if (relative) {
if (relative == 1) {
part->size += temp;
}
else {
part->size -= temp;
}
}
else {
part->size = temp;
}
part->size = four_kb_alignment(part->size);
size_byte_to_human_readable(s_buffer_1, part->size);
printf(" - Size -> %"PRIu64"(%s)\n", part->size, s_buffer_1);
}
// Mask
arg += length + 1;
length = get_part_argument_length(arg, true);
if (length) {
printf("%d\n", length);
part->mask_flags=atoi(arg);
printf("%d\n", part->mask_flags);
puts(arg);
if ((part->mask_flags != 1) && (part->mask_flags != 2) && (part->mask_flags != 4)) {
die("Invalid mask %u, must be either 0, 1, 2 or 4, or leave it empty to not touch it", part->mask_flags);
}
printf(" - Mask -> %d", part->mask_flags);
}
return;
}
void valid_table_header(struct partition_table *table) {
char good[] = ", GOOD √";
printf("Partitions count: %d", table->part_num);
if ( table->part_num > 32 || table->part_num < 3 ) {
die("\nPartitions count illegal (%d), it must be between 3 and 32!", table->part_num);
}
else {
puts(good);
}
printf("Magic: %s", table->magic);
if (strcmp(table->magic, "MPT")) {
die("\nMagic not supported (%s), Must be MPT!", table->magic);
}
else {
puts(good);
}
printf("Version: %s", table->version);
if (strcmp(table->version, "01.00.00")) {
die("\nERROR: Version not supported (%s), Must be 01.00.00!", table->version);
}
else {
puts(good);
}
int checksum = table_checksum(table->partitions, table->part_num);
printf("Checksum: calculated %x, recorded %x", checksum, table->checksum);
if ( checksum != table->checksum ) {
die("\nERROR: Checksum mismatch!");
}
else {
puts(good);
}
}
void valid_partition_table(struct table_helper *table_h) {
puts("Validating partition table...");
struct partition_table *table = table_h->table;
valid_table_header(table);
short has_bootloader=false, has_reserved=false, has_env=false;
struct partition *part;
char names[table->part_num][16];
char *name;
int i, j;
for (i=0; i<table->part_num; i++) {
part = &(table->partitions[i]);
name = part->name;
for (j=0; j<i; j++) {
if (!strcmp(name, names[j])) {
die("Duplicated name found in partation table: %s", name);
}
}
if (!strcmp(part->name, "bootloader")) {
table_h->bootloader=part;
has_bootloader = true;
}
else if (!strcmp(part->name, "reserved")) {
if (options.input_reserved) { // We would like to write to corresponding disk, so offset should be updated
options.offset = part->offset;
printf("Notice: offset of reserved partition found in table, using %"PRIu64" instead for the offset of reserved partition\n", options.offset);
}
table_h->reserved=part;
has_reserved = true;
}
else if (!strcmp(part->name, "env")) {
table_h->env=part;
table_h->insertion[table_h->insertables++].part=part;
has_env = true;
}
else if (!strcmp(part->name, "logo")) {
table_h->logo=part;
table_h->insertion[table_h->insertables++].part=part;
}
else if (!strcmp(part->name, "misc")) {
table_h->misc=part;
table_h->insertion[table_h->insertables++].part=part;
}
else {
valid_partition_name(part->name, false);
}
strcpy(names[i], part->name);
}
if (!has_bootloader) {
puts("Partition table does not have bootloader partition!");
}
if (!has_reserved) {
puts("Partition table does not have reserved partition!");
}
if (!has_env) {
puts("Partition table does not have env partition!");
}
if ((has_bootloader + has_reserved + has_env) < 3) {
exit(EXIT_FAILURE);
}
}
uint64_t summary_partition_table(struct partition_table *table) {
char line[]="==============================================================";
bool overlap=false;
uint64_t offset=0, gap;
puts(line);
puts("NAME OFFSET SIZE MARK");
puts(line);
struct partition *part;
for (int i = 0; i < table->part_num; ++i) {
part = &(table->partitions[i]);
if (offset != part->offset) {
if (part->offset > offset) {
gap = part->offset - offset;
printf(" (GAP) ");
}
else {
gap = offset - part->offset;
overlap=true;
printf(" (OVERLAP) ");
}
size_byte_to_human_readable(s_buffer_1, gap);
printf("%+9llx(%+8s)\n", gap, s_buffer_1);
};
offset = part->offset + part->size;
size_byte_to_human_readable(s_buffer_1, part->offset);
size_byte_to_human_readable(s_buffer_2, part->size);
printf("%-16s %+9llx(%+8s) %+9llx(%+8s) %u\t\n", part->name, part->offset, s_buffer_1, part->size, s_buffer_2, part->mask_flags);
}
puts(line);
if (overlap) {
puts("Warning: Overlap found in partition table, this is extremely dangerous as your Android installation might already be broken.");
puts(" - Please confirm if you've failed with other software");
puts(" - Or have run some installtion scripts/tools that may duplicate data partition");
puts(" - If your device bricks, do not blame on ampart as it's just the one helping you discovering it");
}
uint64_t size=get_max_part_end(table);
size_byte_to_human_readable(s_buffer_1, size);
printf("Disk size totalling %"PRIu64" (%s) according to partition table\n", size, s_buffer_1);
return size;
}
void is_reserved(struct options *options) {
if (!strcmp(options->dir_input, "/dev")) {
printf("Path '%s' seems a device file\n", options->path_input);
if (!strncmp(options->name_input, "mmcblk", 6)) {
if (strlen(options->name_input) == 7) {
options->input_reserved = false;
}
else {
bool has_p = false;
bool has_num = false;
for (int i=6; i<strlen(options->name_input); ++i) {
if (options->name_input[i] == '\0') {
break;
}
if (!has_num && options->name_input[i] >= '0' && options->name_input[i] <='9') {
has_num = true;
}
if (!has_p && options->name_input[i] == 'p') {
has_p = true;
}
}
if (!has_num) {
printf("Warning: number not found in name (%s) which seems a device file, maybe your input path is incorret?\n", options->name_input);
}
if (has_p) {
options->input_reserved = true;
}
else {
options->input_reserved = false;
}
}
}
else if (!strcmp(options->name_input, "reserved")) {
options->input_reserved = true;
}
else {
printf("Warning: can not figure out whether '%s' is a reserved partition or a whole emmc disk, defaulting as reserved part", options->path_input);
options->input_reserved = true;
}
}
else { // A normal file
printf("Path '%s' seems a dumped image, checking the head bytes to distinguish it...\n", options->path_input);
char buffer[SIZE_MBR];
FILE *fp = fopen(options->path_input, "r");
if (fp==NULL) {
die("Can not open path '%s' as read-only, check your permission!", options->path_input);
}
fread(buffer, SIZE_MBR, 1, fp);
options->input_reserved = false;
for (int i=0; i<SIZE_MBR; ++i) {
if (buffer[i]) {
options->input_reserved = true;
break;
}
}
fclose(fp);
}
if (options->input_reserved) {
printf("Path '%s' detected as reserved partation\n", options->path_input);
}
else {
printf("Path '%s' detected as whole emmc disk\n", options->path_input);
}
}
void version() {
puts("\nampart (AMLogic emmc partition tool) "VERSION"\nCopyright (C) 2022 7Ji ([email protected])\nLicense GPLv3: GNU GPL version 3 <https://gnu.org/licenses/gpl.html>.\nThis is free software: you are free to change and redistribute it.\nThere is NO WARRANTY, to the extent permitted by law.\n");
}
void help(char *path) {
printf("Usage: %s [reserved/emmc] [partition] ... [option [optarg]]... \n\n", path);
char help_message[] =
"positional arguments:\n"
"\treserved/emmc\tpath to reserved partition (e.g. /dev/reserved) or a whole emmc (e.g. /dev/mmcblk0), can also be dumped image, default:/dev/reserved\n"
"\t\t\tampart auto-recognises its type by name, if failed, assume it a reserved partition\n"
"\tpartition\tpartition you want to add, format: name:offset:size:mask\n"
"\t\t\tname: composed of a-z, A-Z, _(underscore, must not be the 1st character), 15 characters max\n"
"\t\t\toffset: integer offset of the part in the whole disk, or starts with + for after the last part, multiplies of 4KB, can end with B,K,M,G\n"
"\t\t\tsize: integer size of the part, or empty for filling the disk, multiplies of 4KB, can end with B,K,M,G\n"
"\t\t\tmask: mask of the part, either 1, 2 or 4, 0 is reserved for clone mode only, 1 for u-boot parts like logo,2 for system parts, 4 for data parts, default: 4\n"
"\t\t\te.g.\tdata::: a data partition, auto offset, fills all the remaining space, mask 4\n"
"\t\t\t\tsystem::2G:2 a system parrtition, auto offset, 2G, mask 2\n"
"\t\t\t\tcache:+8M:512M:2 a cache partition, offset 8M after the last part, 512M, mask 2\n\n"
"options:\n"
"\t--version-v\tprint the version message, early quit\n"
"\t--help/-h\tdisplay this message, early quit\n"
"\t--disk/-d\tno auto-recognization, treat input as a whole disk\n"
"\t--reserved/-r\tno auto-recognization, treat input as a reserved partition\n"
"\t--offset/-O [offset]\n"
"\t\t\toverwrite the offset of the reserved partition, in case OEM has modified it\n\t\t\tonly valid when input is a whole disk, default:36M\n"
"\t--snapshot/-s\toutputs partition arguments that can be used to restore the partition table to what it looks like now, early quit\n"
"\t--clone/-c\trun in clone mode, parse partition arguments outputed by --snapshot/-s, no filter\n"
"\t--update/-u\trun in update mode, exact partition can be selected and altered\n"
"\t--no-node/-N\tdon't try to remove partitions node from dtb\n"
"\t--dry-run/-D\tdo not actually update the part table\n"
"\t--partprobe/-p\tforce a notification to the kernel about the partition layout change, early quit\n"
"\t--no-reload/-n\tdo not notify kernel about the partition layout changes, remember to end your session with a --partprobe call\n\t\t\tif you are calling ampart for multiple times in a script\n"
"\t--output/-o [path]\n"
"\t\t\twrite the updated part table to somewhere else, instead of the input itself\n";
puts(help_message);
}
void get_options(int argc, char **argv) {
// options is a global variable
int c, option_index = 0;
options.offset = 0x2400000; // default offset, 32M
static struct option long_options[] = {
{"version", no_argument, NULL, 'v'},
{"help", no_argument, NULL, 'h'},
{"disk", no_argument, NULL, 'd'}, // The input file is a whole disk (e.g. /dev/mmcblk0) or image file alike
{"reserved",no_argument, NULL, 'r'}, // The input file is a reserved partation (e.g. /dev/reserved) or image file alike
{"offset", required_argument, NULL, 'O'}, // offset of the reserved partition in disk
{"snapshot",no_argument, NULL, 's'},
{"clone", no_argument, NULL, 'c'},
{"update", no_argument, NULL, 'u'},
{"no-node", no_argument, NULL, 'N'},
{"dry-run", no_argument, NULL, 'D'},
{"partprobe",no_argument, NULL, 'p'},
{"no-reload",no_argument, NULL, 'n'},
{"output", required_argument, NULL, 'o'}, // Optionally write output to a given path, instead of write it back
{NULL, 0, NULL, 0}, // This is needed for when user just mess up with their input
};
char buffer[9];
bool input_disk = false;
while ((c = getopt_long(argc, argv, "vhdrO:scuCNDpno:", long_options, &option_index)) != -1) {
int this_option_optind = optind ? optind : 1;
switch (c) {
case 'v':