1 #include <sys/types.h> 2 #include <sys/stat.h> 3 #include <fcntl.h> 4 #include <stdio.h> 5 #include <stdlib.h> 6 7 #include "ext4.h" 8 #include "ext4_utils.h" 9 10 #define SB_OFFSET 1024 11 12 int main(int argc, char *argv[]) 13 { 14 char me[] = "corrupt_gdt_free_blocks"; 15 int fd; 16 int block_size; 17 int num_bgs; 18 int i; 19 struct ext4_super_block sb; 20 struct ext2_group_desc gd; 21 22 if (argc != 2) { 23 fprintf(stderr, "%s: Usage: %s <ext4_block_device>\n", me, me); 24 exit(1); 25 } 26 27 fd = open(argv[1], O_RDWR); 28 29 if (fd < 0) { 30 fprintf(stderr, "%s: Cannot open block device %s\n", me, argv[1]); 31 exit(1); 32 } 33 34 if (lseek(fd, SB_OFFSET, SEEK_SET) == -1) { 35 fprintf(stderr, "%s: Cannot lseek to superblock to read\n", me); 36 exit(1); 37 } 38 39 if (read(fd, &sb, sizeof(sb)) != sizeof(sb)) { 40 fprintf(stderr, "%s: Cannot read superblock\n", me); 41 exit(1); 42 } 43 44 if (sb.s_magic != 0xEF53) { 45 fprintf(stderr, "%s: invalid superblock magic\n", me); 46 exit(1); 47 } 48 49 /* Make sure the block size is 2K or 4K */ 50 if ((sb.s_log_block_size != 1) && (sb.s_log_block_size != 2)) { 51 fprintf(stderr, "%s: block size not 2K or 4K\n", me); 52 exit(1); 53 } 54 55 block_size = 1 << (10 + sb.s_log_block_size); 56 num_bgs = DIV_ROUND_UP(sb.s_blocks_count_lo, sb.s_blocks_per_group); 57 58 if (sb.s_desc_size != sizeof(struct ext2_group_desc)) { 59 fprintf(stderr, "%s: Can't handle block group descriptor size of %d\n", 60 me, sb.s_desc_size); 61 exit(1); 62 } 63 64 /* read first block group descriptor, decrement free block count, and 65 * write it back out 66 */ 67 if (lseek(fd, block_size, SEEK_SET) == -1) { 68 fprintf(stderr, "%s: Cannot lseek to block group descriptor table to read\n", me); 69 exit(1); 70 } 71 72 /* Read in block group descriptors till we read one that has at least one free block */ 73 74 for (i=0; i < num_bgs; i++) { 75 if (read(fd, &gd, sizeof(gd)) != sizeof(gd)) { 76 fprintf(stderr, "%s: Cannot read group descriptor %d\n", me, i); 77 exit(1); 78 } 79 if (gd.bg_free_blocks_count) { 80 break; 81 } 82 } 83 84 gd.bg_free_blocks_count--; 85 86 if (lseek(fd, -sizeof(gd), SEEK_CUR) == -1) { 87 fprintf(stderr, "%s: Cannot lseek to block group descriptor table to write\n", me); 88 exit(1); 89 } 90 91 if (write(fd, &gd, sizeof(gd)) != sizeof(gd)) { 92 fprintf(stderr, "%s: Cannot write modified group descriptor\n", me); 93 exit(1); 94 } 95 96 close(fd); 97 98 return 0; 99 } 100 101