blob: 1a768f92e9b1491be10e86b6fa935d0ebac83d4e [file] [log] [blame]
yuezonghe824eb0c2024-06-27 02:32:26 -07001/*
2 * check_desc.c --- Check the group descriptors of an ext2 filesystem
3 *
4 * Copyright (C) 1993, 1994, 1995, 1996 Theodore Ts'o.
5 *
6 * %Begin-Header%
7 * This file may be redistributed under the terms of the GNU Library
8 * General Public License, version 2.
9 * %End-Header%
10 */
11
12#include "config.h"
13#include <stdio.h>
14#include <string.h>
15#if HAVE_UNISTD_H
16#include <unistd.h>
17#endif
18#include <fcntl.h>
19#include <time.h>
20#if HAVE_SYS_STAT_H
21#include <sys/stat.h>
22#endif
23#if HAVE_SYS_TYPES_H
24#include <sys/types.h>
25#endif
26
27#include "ext2_fs.h"
28#include "ext2fs.h"
29
30/*
31 * This routine sanity checks the group descriptors
32 */
33errcode_t ext2fs_check_desc(ext2_filsys fs)
34{
35 ext2fs_block_bitmap bmap;
36 errcode_t retval;
37 dgrp_t i;
38 blk64_t first_block = fs->super->s_first_data_block;
39 blk64_t last_block = ext2fs_blocks_count(fs->super)-1;
40 blk64_t blk, b;
41 unsigned int j;
42
43 EXT2_CHECK_MAGIC(fs, EXT2_ET_MAGIC_EXT2FS_FILSYS);
44
45 if (EXT2_DESC_SIZE(fs->super) & (EXT2_DESC_SIZE(fs->super) - 1))
46 return EXT2_ET_BAD_DESC_SIZE;
47
48 retval = ext2fs_allocate_subcluster_bitmap(fs, "check_desc map", &bmap);
49 if (retval)
50 return retval;
51
52 for (i = 0; i < fs->group_desc_count; i++)
53 ext2fs_reserve_super_and_bgd(fs, i, bmap);
54
55 for (i = 0; i < fs->group_desc_count; i++) {
56 if (!EXT2_HAS_INCOMPAT_FEATURE(fs->super,
57 EXT4_FEATURE_INCOMPAT_FLEX_BG)) {
58 first_block = ext2fs_group_first_block2(fs, i);
59 last_block = ext2fs_group_last_block2(fs, i);
60 }
61
62 /*
63 * Check to make sure the block bitmap for group is sane
64 */
65 blk = ext2fs_block_bitmap_loc(fs, i);
66 if (blk < first_block || blk > last_block ||
67 ext2fs_test_block_bitmap2(bmap, blk)) {
68 retval = EXT2_ET_GDESC_BAD_BLOCK_MAP;
69 goto errout;
70 }
71 ext2fs_mark_block_bitmap2(bmap, blk);
72
73 /*
74 * Check to make sure the inode bitmap for group is sane
75 */
76 blk = ext2fs_inode_bitmap_loc(fs, i);
77 if (blk < first_block || blk > last_block ||
78 ext2fs_test_block_bitmap2(bmap, blk)) {
79 retval = EXT2_ET_GDESC_BAD_INODE_MAP;
80 goto errout;
81 }
82 ext2fs_mark_block_bitmap2(bmap, blk);
83
84 /*
85 * Check to make sure the inode table for group is sane
86 */
87 blk = ext2fs_inode_table_loc(fs, i);
88 if (blk < first_block ||
89 ((blk + fs->inode_blocks_per_group - 1) > last_block)) {
90 retval = EXT2_ET_GDESC_BAD_INODE_TABLE;
91 goto errout;
92 }
93 for (j = 0, b = blk; j < fs->inode_blocks_per_group;
94 j++, b++) {
95 if (ext2fs_test_block_bitmap2(bmap, b)) {
96 retval = EXT2_ET_GDESC_BAD_INODE_TABLE;
97 goto errout;
98 }
99 ext2fs_mark_block_bitmap2(bmap, b);
100 }
101 }
102errout:
103 ext2fs_free_block_bitmap(bmap);
104 return retval;
105}