aruu

[MIRROR] Actual replacement for Busybox | suckless
git clone https://git.daat.foo/aruu.git
Log | Files | Refs | README | LICENSE

commit 926fa68d54e7abeb55e514a8a9f9d4b561442118
parent 7ab0655151664f60377c4077e26ac4c99150683f
Author: cowmonk <cowmonk@based.pt>
Date:   Sun, 29 Nov 2026 22:29:25 -0700

clang format everything

undid the sort include for a bit to make sure it still builds though

Diffstat:
M.clang-format | 1+
Mcmd/dev/as/arch.h | 12++++++------
Mcmd/dev/as/arch/x64/asm_code.c | 56++++++++++++++++++++++++++++++++------------------------
Mcmd/dev/as/arch/x64/backend.c | 6+++---
Mcmd/dev/as/arch/x64/inst.h | 16++++++++--------
Mcmd/dev/as/arch/x64/parse_x64.c | 51+++++++++++++++++++++++++--------------------------
Mcmd/dev/as/arch/x64/reloc_x64.c | 40++++++++++++++++++++--------------------
Mcmd/dev/as/emit_elf.c | 2+-
Mcmd/dev/as/emit_macho.c | 2+-
Mcmd/dev/as/ir_asm.c | 24++++++++++++------------
Mcmd/dev/as/ir_asm.h | 2+-
Mcmd/dev/as/parse_asm.c | 24++++++++++++------------
Mcmd/dev/as/parse_asm.h | 10+++++-----
Mcmd/dev/cc/cc.h | 14+++++++-------
Mcmd/dev/cc/decl.c | 42+++++++++++++++++++++---------------------
Mcmd/dev/cc/driver.c | 2+-
Mcmd/dev/cc/eval.c | 10+++++-----
Mcmd/dev/cc/expr.c | 50+++++++++++++++++++++++++++-----------------------
Mcmd/dev/cc/include/stdatomic.h | 20+++++++++-----------
Mcmd/dev/cc/init.c | 2+-
Mcmd/dev/cc/ospredef_posix.c | 7++++---
Mcmd/dev/cc/pp.c | 6+++---
Mcmd/dev/cc/qbe.c | 40++++++++++++++++++++++------------------
Mcmd/dev/cc/token.c | 6+++---
Mcmd/dev/cc/tree.c | 28++++++++++++++--------------
Mcmd/dev/cc/type.c | 8++++----
Mcmd/dev/ld/ld.c | 30++++++++++++++----------------
Mcmd/dev/ld/ld.h | 12++++++------
Mcmd/dev/ninqu/expand.c | 12++++++------
Mcmd/dev/ninqu/ninja.c | 10+++++-----
Mcmd/dev/ninqu/parse.c | 8++++----
Mcmd/dev/ninqu/resolve.c | 4++--
Mcmd/dev/xelf/xelf.c | 49++++++++++++++++++++++++++++++++++---------------
Mcmd/extra/fsck.ext4/compat.h | 16++++++++--------
Mcmd/extra/fsck.ext4/dir.c | 1014+++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/extra/fsck.ext4/exitvalues.h | 10+++++-----
Mcmd/extra/fsck.ext4/ext2fs_bswap.c | 165+++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/extra/fsck.ext4/extern.h | 96++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/extra/fsck.ext4/fsck.h | 254++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/extra/fsck.ext4/fsutil.c | 163++++++++++++++++++++++++++++++++++++++-----------------------------------------
Mcmd/extra/fsck.ext4/fsutil.h | 38+++++++++++++++++++++-----------------
Mcmd/extra/fsck.ext4/inode.c | 1094+++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/extra/fsck.ext4/main.c | 340++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/extra/fsck.ext4/pass1.c | 584+++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/extra/fsck.ext4/pass1b.c | 89+++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/extra/fsck.ext4/pass2.c | 694++++++++++++++++++++++++++++++++++++++-----------------------------------------
Mcmd/extra/fsck.ext4/pass3.c | 45+++++++++++++++++++++------------------------
Mcmd/extra/fsck.ext4/pass4.c | 146+++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/extra/fsck.ext4/pass5.c | 332++++++++++++++++++++++++++++++++++++++-----------------------------------------
Mcmd/extra/fsck.ext4/setup.c | 490++++++++++++++++++++++++++++++++++++++-----------------------------------------
Mcmd/extra/fsck.ext4/ufs/ext2fs/ext2fs.h | 651++++++++++++++++++++++++++++++++++++++-----------------------------------------
Mcmd/extra/fsck.ext4/ufs/ext2fs/ext2fs_dinode.h | 287+++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/extra/fsck.ext4/ufs/ext2fs/ext2fs_dir.h | 158++++++++++++++++++++++++++++++++++++++-----------------------------------------
Mcmd/extra/fsck.ext4/utilities.c | 552++++++++++++++++++++++++++++++++++++++++---------------------------------------
Mcmd/extra/fsck.fat/boot.c | 604++++++++++++++++++++++++++++++++++++++-----------------------------------------
Mcmd/extra/fsck.fat/check.c | 294+++++++++++++++++++++++++++++++++++++++++--------------------------------------
Mcmd/extra/fsck.fat/dir.c | 1918+++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/extra/fsck.fat/dosfs.h | 132++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/extra/fsck.fat/ext.h | 42+++++++++++++++++++++---------------------
Mcmd/extra/fsck.fat/fat.c | 1832+++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/extra/fsck.fat/freebsd-compat.h | 26+++++++++++++-------------
Mcmd/extra/fsck.fat/fsck.fat.c | 189+++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/extra/fsck.fat/fsutil.c | 228++++++++++++++++++++++++++++++++++++++-----------------------------------------
Mcmd/extra/fsck.fat/fsutil.h | 39+++++++++++++++++++++------------------
Mcmd/extra/install.c | 2+-
Mcmd/extra/kmap.c | 37++++++++++++++++++++-----------------
Mcmd/extra/mkfs.ext4.c | 121++++++++++++++++++++++++++++++++++++++++++-------------------------------------
Mcmd/extra/mkfs.fat.c | 1447+++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/extra/partplan.c | 102++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------
Mcmd/extra/pgrep.c | 11++++++-----
Mcmd/extra/signify.c | 102+++++++++++++++++++++++++++++++++++++++++--------------------------------------
Mcmd/extra/yap/commands.c | 120++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/extra/yap/display.c | 144++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/extra/yap/getcomm.c | 70+++++++++++++++++++++++++++++++++++-----------------------------------
Mcmd/extra/yap/getline.c | 132++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/extra/yap/help.c | 8++++----
Mcmd/extra/yap/keys.c | 30+++++++++++++++---------------
Mcmd/extra/yap/machine.c | 48++++++++++++++++++++++++------------------------
Mcmd/extra/yap/main.c | 26+++++++++++++-------------
Mcmd/extra/yap/options.c | 12++++++------
Mcmd/extra/yap/process.c | 12++++++------
Mcmd/extra/yap/prompt.c | 12++++++------
Mcmd/extra/yap/term.c | 38+++++++++++++++++++-------------------
Mcmd/linux/mdev.c | 14++++++++------
Mcmd/linux/mkswap.c | 65++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Mcmd/linux/modprobe.c | 2+-
Mcmd/linux/mount.c | 31+++++++++++++++++++++++--------
Mcmd/posix/awk/awk.h | 4++--
Mcmd/posix/awk/b.c | 104++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/posix/awk/lib.c | 16++++++++--------
Mcmd/posix/awk/maketab.c | 2+-
Mcmd/posix/awk/run.c | 44++++++++++++++++++++++----------------------
Mcmd/posix/awk/tran.c | 44++++++++++++++++++++++----------------------
Mcmd/posix/cut.c | 2+-
Mcmd/posix/dd.c | 2+-
Mcmd/posix/ed.c | 28++++++++++++++--------------
Mcmd/posix/expr.c | 2+-
Mcmd/posix/find.c | 62+++++++++++++++++++++++++++++++-------------------------------
Mcmd/posix/grep.c | 2+-
Mcmd/posix/head.c | 6+++---
Mcmd/posix/join.c | 4++--
Mcmd/posix/ln.c | 11+++++------
Mcmd/posix/ls.c | 3++-
Mcmd/posix/make/main.c | 18+++++++++---------
Mcmd/posix/make/parser.c | 37+++++++++++++++++++------------------
Mcmd/posix/od.c | 12+++++++++---
Mcmd/posix/patch.c | 14+++++++-------
Mcmd/posix/pathchk.c | 2+-
Mcmd/posix/pax.c | 16++++++++--------
Mcmd/posix/ps.c | 221++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------
Mcmd/posix/sed.c | 88++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/posix/sh/alias.c | 12++++++------
Mcmd/posix/sh/arith_yacc.c | 4++--
Mcmd/posix/sh/cd.c | 30+++++++++++++++---------------
Mcmd/posix/sh/easter.c | 6+++---
Mcmd/posix/sh/error.c | 18+++++++++---------
Mcmd/posix/sh/eval.c | 80++++++++++++++++++++++++++++++++++++++++----------------------------------------
Mcmd/posix/sh/exec.c | 22+++++++++++-----------
Mcmd/posix/sh/expand.c | 52++++++++++++++++++++++++++--------------------------
Mcmd/posix/sh/input.c | 10+++++-----
Mcmd/posix/sh/jobs.c | 26+++++++++++++-------------
Mcmd/posix/sh/lineedit.c | 6+++---
Mcmd/posix/sh/main.c | 30+++++++++++++++---------------
Mcmd/posix/sh/miscbltin.c | 38+++++++++++++++++++-------------------
Mcmd/posix/sh/options.c | 48++++++++++++++++++++++++------------------------
Mcmd/posix/sh/output.h | 42+++++++++++++++++++++---------------------
Mcmd/posix/sh/parser.c | 820++++++++++++++++++++++++++++++++++++++++---------------------------------------
Mcmd/posix/sh/parser.h | 4++--
Mcmd/posix/sh/printf.c | 32++++++++++++++++----------------
Mcmd/posix/sh/sh_cdefs.h | 6+++---
Mcmd/posix/sh/test.c | 8++++----
Mcmd/posix/sh/trap.c | 52++++++++++++++++++++++++++--------------------------
Mcmd/posix/sh/var.c | 48++++++++++++++++++++++++------------------------
Mcmd/posix/sort.c | 14+++++++-------
Mcmd/posix/tail.c | 6+++---
Mcmd/posix/uudecode.c | 2+-
Mcmd/pseudo/gzip.c | 91+++++++++++++++++++++++++++++++++++++++++++------------------------------------
Mcmd/pseudo/stat.c | 26+++++++++-----------------
Mcmd/pseudo/tar.c | 14+++++++-------
Mcmd/pseudo/useradd.c | 34++++++++++++++++++++++++++--------
Mcmd/pseudo/usermod.c | 26++++++++++++++++++--------
Mcmd/pseudo/watch.c | 6+++---
Mcmd/xsi/passwd.c | 12++++++------
Mscripts/kmap/kmap-vendor.c | 253+++++++++++++++++++++++++++++++++++++++++++++++--------------------------------
Mshared/diskutil.h | 25+++++++++++++------------
Mshared/ed25519.h | 19+++++++++++--------
Mshared/fs.h | 2+-
Mshared/kmap.h | 21++++++++++++++-------
Mshared/libblake3/blake3.c | 16+++++++---------
Mshared/libblake3/blake3.h | 10++++++----
Mshared/libdisk/gpt.c | 48+++++++++++++++++++++++++++++++++---------------
Mshared/libdisk/gpt.h | 8++++----
Mshared/libdisk/label.c | 20+++++++++++---------
Mshared/libdisk/label.h | 7++++---
Mshared/libdisk/label_test.c | 13++++++++-----
Mshared/libdisk/plan.c | 118+++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------
Mshared/libdisk/plan.h | 45++++++++++++++++++++++++++++++++-------------
Mshared/libdisk/plan_test.c | 120++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------------
Mshared/libmagic/magic.c | 58+++++++++++++++++++++++++++++++++++++++++++++-------------
Mshared/libmagic/magic.h | 4+++-
Mshared/libmagic/mgindex.c | 15++++++++++-----
Mshared/libmagic/mgmatch.c | 2+-
Mshared/libmagic/mgtext.c | 6++++--
Mshared/libredline/redline.c | 4++--
Mshared/libtcutil/tcutil.c | 2+-
Mshared/libutf/rune.c | 2+-
Mshared/libutil/accounts.c | 4++--
Mshared/libutil/accounts_linux.c | 27++++++++++++++-------------
Mshared/libutil/base64.c | 7+++----
Mshared/libutil/diskutil.c | 16++++++++++------
Mshared/libutil/diskutil_linux.c | 32+++++++++++++++++---------------
Mshared/libutil/diskutil_posix.c | 2+-
Mshared/libutil/ed25519.c | 162+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
Mshared/libutil/filesystem_linux.c | 4++--
Mshared/libutil/fshut.c | 8++++----
Mshared/libutil/getopt_posix.c | 7++++---
Mshared/libutil/kmap.c | 144++++++++++++++++++++++++++++++++++++++++++++-----------------------------------
Mshared/libutil/kmap_fbsd.c | 50++++++++++++++++++++++++++++++--------------------
Mshared/libutil/kmap_linux.c | 48++++++++++++++++++++++++------------------------
Mshared/libutil/kmap_posix.c | 4++--
Mshared/libutil/kmap_wscons.c | 18+++++++++---------
Mshared/libutil/passwd_linux.c | 8++++----
Mshared/libutil/passwd_posix.c | 7++++---
Mshared/libutil/proc_linux.c | 8++++----
Mshared/libutil/session_linux.c | 4++--
Mshared/libutil/signify.c | 42+++++++++++++++++++++++-------------------
Mshared/libutil/sysinfo_linux.c | 16++++++++--------
Mshared/libutil/timer_posix.c | 2+-
Mshared/libutil/wexec.c | 4++--
Mshared/net.h | 7++++---
Mshared/paths.h | 6+++---
Mshared/proc.h | 24++++++++++++------------
Mshared/session.h | 4++--
Mshared/signify.h | 12++++++++----
Mshared/sysinfo.h | 2+-
Mshared/util.h | 4++--
196 files changed, 10040 insertions(+), 9544 deletions(-)

diff --git a/.clang-format b/.clang-format @@ -11,6 +11,7 @@ IndentWrappedFunctionNames: false NamespaceIndentation: None ColumnLimit: 100 +CommentPragmas: '^[[:space:]]*\?man([[:space:]]|$)' AlignAfterOpenBracket: BlockIndent AlignConsecutiveMacros: Consecutive diff --git a/cmd/dev/as/arch.h b/cmd/dev/as/arch.h @@ -53,12 +53,12 @@ struct arch_backend { const struct ParseInstTable *parse_inst_table; /* scan for instruction prefix keywords (lock, rep, etc). returns - * the prefix flag bit or 0 if no prefix found. advances info->p - * past the keyword and trailing whitespace when a prefix matches */ + * the prefix flag bit or 0 if no prefix found. advances info->p + * past the keyword and trailing whitespace when a prefix matches */ unsigned char (*scan_prefix)(struct ParseInfo *info); /* parse one operand from the input stream. returns a bitmask of - * matched operand-shape flags or 0 on failure */ + * matched operand-shape flags or 0 on failure */ unsigned int (*parse_operand)( struct ParseInfo *info, unsigned int opr_flag, struct Operand *operand ); @@ -70,9 +70,9 @@ struct arch_backend { void (*make_code)(struct Inst *inst, struct Code *code, unsigned char *buf, int len); /* resolve arch-specific relocations for an IR_CODE node. core calls - * this for every code IR during the resolution pass. sets - * size_upgraded if a branch was promoted to long form and the - * fixpoint needs another iteration */ + * this for every code IR during the resolution pass. sets + * size_upgraded if a branch was promoted to long form and the + * fixpoint needs another iteration */ void (*resolve_code_reloc)( struct IR *ir, struct SectionInfo *section, diff --git a/cmd/dev/as/arch/x64/asm_code.c b/cmd/dev/as/arch/x64/asm_code.c @@ -150,7 +150,10 @@ asm_mov_imr(struct Inst *inst, struct Code *code) short buf[] = { MAKE_REX0( - size, 0, opr_regno(&inst->opr[1].u.reg), 0xb0 | (size == REG8 ? 0 : 8) | inst->opr[1].u.reg.no + size, + 0, + opr_regno(&inst->opr[1].u.reg), + 0xb0 | (size == REG8 ? 0 : 8) | inst->opr[1].u.reg.no ), MAKE_IM(size, inst->opr[0].u.immediate), }; @@ -213,7 +216,8 @@ assemble_reg_to_mem( struct Inst *inst, struct Code *code, int escape, unsigned char op8, unsigned char opw ) { - if (inst->opr[1].u.indirect.offset.expr->kind != EX_FIXNUM || inst->opr[1].u.indirect.reg.no == RIP) + if (inst->opr[1].u.indirect.offset.expr->kind != EX_FIXNUM + || inst->opr[1].u.indirect.reg.no == RIP) return NULL; long offset = inst->opr[1].u.indirect.offset.expr->u.fixnum; @@ -480,7 +484,8 @@ asm_movszx_rr(struct Inst *inst, struct Code *code) if (opr_reg8(&inst->opr[0].u.reg) && !inst->opr[1].u.reg.x) { MAKE_CODE(inst, code, 0x66, 0x0f, op, 0xc0 + s + d * 8); } else { - int pre = ((inst->opr[0].u.reg.x & 1) == 0 ? 0x40 : 0x41) + (!inst->opr[1].u.reg.x ? 0 : 4); + int pre = + ((inst->opr[0].u.reg.x & 1) == 0 ? 0x40 : 0x41) + (!inst->opr[1].u.reg.x ? 0 : 4); MAKE_CODE(inst, code, 0x66, pre, 0x0f, op, 0xc0 + s + d * 8); } return p; @@ -488,12 +493,14 @@ asm_movszx_rr(struct Inst *inst, struct Code *code) if (opr_reg8(&inst->opr[0].u.reg) && !inst->opr[1].u.reg.x) { MAKE_CODE(inst, code, 0x0f, op, 0xc0 + s + d * 8); } else { - int pre = ((inst->opr[0].u.reg.x & 1) == 0 ? 0x40 : 0x41) + (!inst->opr[1].u.reg.x ? 0 : 4); + int pre = + ((inst->opr[0].u.reg.x & 1) == 0 ? 0x40 : 0x41) + (!inst->opr[1].u.reg.x ? 0 : 4); MAKE_CODE(inst, code, pre, 0x0f, op, 0xc0 + s + d * 8); } return p; case REG64: { - int pre = ((inst->opr[0].u.reg.x & 1) == 0 ? 0x48 : 0x49) + (!inst->opr[1].u.reg.x ? 0 : 4); + int pre = + ((inst->opr[0].u.reg.x & 1) == 0 ? 0x48 : 0x49) + (!inst->opr[1].u.reg.x ? 0 : 4); MAKE_CODE(inst, code, pre, 0x0f, op, 0xc0 + s + d * 8); return p; } @@ -1557,7 +1564,8 @@ asm_sub_imr(struct Inst *inst, struct Code *code) static unsigned char * asm_sub_ir(struct Inst *inst, struct Code *code) { - if (inst->opr[0].u.indirect.offset.expr->kind == EX_FIXNUM && inst->opr[0].u.indirect.reg.no != RIP) { + if (inst->opr[0].u.indirect.offset.expr->kind == EX_FIXNUM + && inst->opr[0].u.indirect.reg.no != RIP) { long offset = inst->opr[0].u.indirect.offset.expr->u.fixnum; enum RegSize size = inst->opr[1].u.reg.size; unsigned char *p = code->buf; @@ -1694,7 +1702,7 @@ static unsigned char * asm_neg_r(struct Inst *inst, struct Code *code) { unsigned char *p = code->buf; - p = put_rex1(p, inst->opr[0].u.reg.size, 0xd8, opr_regno(&inst->opr[0].u.reg), 0xf7); + p = put_rex1(p, inst->opr[0].u.reg.size, 0xd8, opr_regno(&inst->opr[0].u.reg), 0xf7); return p; } @@ -1702,7 +1710,7 @@ static unsigned char * asm_not_r(struct Inst *inst, struct Code *code) { unsigned char *p = code->buf; - p = put_rex1(p, inst->opr[0].u.reg.size, 0xd0, opr_regno(&inst->opr[0].u.reg), 0xf7); + p = put_rex1(p, inst->opr[0].u.reg.size, 0xd0, opr_regno(&inst->opr[0].u.reg), 0xf7); return p; } @@ -2654,8 +2662,8 @@ static unsigned char * asm_string(struct Inst *inst, struct Code *code) { /* base opcodes: movs=0xa4, stos=0xaa, lods=0xac, scas=0xae, cmps=0xa6 - * the byte form has opcode x, word/dword/qword form has opcode X+1 - * the table below stores the byte-form opcode for each group */ + * the byte form has opcode x, word/dword/qword form has opcode X+1 + * the table below stores the byte-form opcode for each group */ static const unsigned char base[] = { [MOVSB - MOVSB] = 0xa4, [STOSB - MOVSB] = 0xaa, @@ -2966,20 +2974,20 @@ assemble_inst(struct Inst *inst, struct ParseInfo *info, struct Code *code) unsigned char prefix = 0; switch (inst->prefix) { - case 0: - break; - case PREFIX_LOCK: - prefix = 0xf0; - break; - case PREFIX_REP: - prefix = 0xf3; - break; - case PREFIX_REPNE: - prefix = 0xf2; - break; - default: - assemble_error(info, "invalid instruction prefix combination"); - return; + case 0: + break; + case PREFIX_LOCK: + prefix = 0xf0; + break; + case PREFIX_REP: + prefix = 0xf3; + break; + case PREFIX_REPNE: + prefix = 0xf2; + break; + default: + assemble_error(info, "invalid instruction prefix combination"); + return; } const AsmInstFunc *func = NULL; diff --git a/cmd/dev/as/arch/x64/backend.c b/cmd/dev/as/arch/x64/backend.c @@ -12,10 +12,10 @@ extern const char *kRawOpTable[]; extern const struct ParseInstTable kParseInstTable[]; extern unsigned int parse_operand(struct ParseInfo *info, unsigned int opr_flag, struct Operand *operand); -extern void assemble_inst(struct Inst *inst, struct ParseInfo *info, struct Code *code); -extern void make_code(struct Inst *inst, struct Code *code, unsigned char *buf, int len); +extern void assemble_inst(struct Inst *inst, struct ParseInfo *info, struct Code *code); +extern void make_code(struct Inst *inst, struct Code *code, unsigned char *buf, int len); extern unsigned char x64_scan_prefix(struct ParseInfo *info); -extern void x64_resolve_code_reloc( +extern void x64_resolve_code_reloc( struct IR *ir, struct SectionInfo *section, uint64_t address, diff --git a/cmd/dev/as/arch/x64/inst.h b/cmd/dev/as/arch/x64/inst.h @@ -46,10 +46,10 @@ enum Opcode { MOVSX, MOVZX, /* sized extend forms. the gas mnemonics (movzbl, movswl, movslq, ...) - * fix the source size in the mnemonic itself, which the encoder needs - * when the source is a memory operand (a memory operand carries no - * size). each form below names the source width and signedness so a - * single encoder covers register and memory sources uniformly */ + * fix the source size in the mnemonic itself, which the encoder needs + * when the source is a memory operand (a memory operand carries no + * size). each form below names the source width and signedness so a + * single encoder covers register and memory sources uniformly */ MOVZX_B, MOVZX_W, /* zero-extend byte / word source */ MOVSX_B, @@ -664,16 +664,16 @@ struct Operand { enum RegXmmType regxmm; enum RegYmmType regymm; struct { - enum RegType reg; - struct ExprWithFlag offset; + enum RegType reg; + struct ExprWithFlag offset; } segment; } u; }; struct Inst { enum Opcode op; - unsigned char prefix; /* PREFIX_LOCK, PREFIX_REP, etc */ - struct Operand opr[3]; /* src, dst, dst2 (for 3-operand vex) */ + unsigned char prefix; /* PREFIX_LOCK, PREFIX_REP, etc */ + struct Operand opr[3]; /* src, dst, dst2 (for 3-operand vex) */ }; #endif /* AS_ARCH_X64_INST_H */ diff --git a/cmd/dev/as/arch/x64/parse_x64.c b/cmd/dev/as/arch/x64/parse_x64.c @@ -703,7 +703,7 @@ unsigned char x64_scan_prefix(struct ParseInfo *info) { static const struct { - const char *name; + const char *name; unsigned char flag; } prefixes[] = { {"lock", PREFIX_LOCK}, @@ -770,7 +770,7 @@ parse_direct_register(struct ParseInfo *info, struct Operand *operand) { enum RegXmmType regxmm = find_xmm_register(&info->p); if (regxmm != NOREGXMM) { - operand->type = REG_XMM; + operand->type = REG_XMM; operand->u.regxmm = regxmm; return XMM; } @@ -788,7 +788,7 @@ parse_direct_register(struct ParseInfo *info, struct Operand *operand) flag = LF_TPOFF; } } - operand->type = SEGMENT_OFFSET; + operand->type = SEGMENT_OFFSET; operand->u.segment.reg = reg; operand->u.segment.offset.expr = offset; operand->u.segment.offset.flag = flag; @@ -814,7 +814,7 @@ parse_direct_register(struct ParseInfo *info, struct Operand *operand) return 0; } - operand->type = REG; + operand->type = REG; operand->u.reg.size = size; operand->u.reg.no = no & 7; operand->u.reg.x = no >> 3; @@ -895,8 +895,8 @@ parse_indirect_register( parse_error(info, "register expected"); if (index_reg == NOREG) { - char no = base_reg - RAX; - operand->type = INDIRECT; + char no = base_reg - RAX; + operand->type = INDIRECT; operand->u.indirect.reg.size = REG64; operand->u.indirect.reg.no = base_reg != RIP ? no & 7 : RIP; operand->u.indirect.reg.x = (no & 8) >> 3; @@ -906,14 +906,14 @@ parse_indirect_register( if (!is_reg64(index_reg)) parse_error(info, "register expected"); - operand->type = INDIRECT_WITH_INDEX; + operand->type = INDIRECT_WITH_INDEX; operand->u.indirect_with_index.offset = offset->expr; operand->u.indirect_with_index.scale = scale; - char base_no = base_reg - RAX; + char base_no = base_reg - RAX; operand->u.indirect_with_index.base_reg.size = REG64; operand->u.indirect_with_index.base_reg.no = base_no & 7; operand->u.indirect_with_index.base_reg.x = (base_no & 8) >> 3; - char index_no = index_reg - RAX; + char index_no = index_reg - RAX; operand->u.indirect_with_index.index_reg.size = REG64; operand->u.indirect_with_index.index_reg.no = index_no & 7; operand->u.indirect_with_index.index_reg.x = (index_no & 8) >> 3; @@ -928,8 +928,8 @@ parse_deref_register(struct ParseInfo *info, struct Operand *operand) if (!is_reg64(reg)) parse_error(info, "illegal register"); - char no = reg - RAX; - operand->type = DEREF_REG; + char no = reg - RAX; + operand->type = DEREF_REG; operand->u.reg.size = REG64; operand->u.reg.no = no & 7; operand->u.reg.x = (no & 8) >> 3; @@ -979,24 +979,24 @@ parse_deref_indirect(struct ParseInfo *info, struct Operand *operand) parse_error(info, "register expected"); if (index_reg == NOREG) { - operand->type = DEREF_INDIRECT; + operand->type = DEREF_INDIRECT; operand->u.indirect.offset.expr = offset; operand->u.indirect.offset.flag = 0; - char reg_no = base_reg - RAX; + char reg_no = base_reg - RAX; operand->u.indirect.reg.size = REG64; operand->u.indirect.reg.no = reg_no & 7; operand->u.indirect.reg.x = (reg_no & 8) >> 3; return DEI; } else { - operand->type = DEREF_INDIRECT_WITH_INDEX; + operand->type = DEREF_INDIRECT_WITH_INDEX; operand->u.indirect_with_index.offset = offset; operand->u.indirect_with_index.scale = scale; - char base_no = base_reg - RAX; + char base_no = base_reg - RAX; operand->u.indirect_with_index.base_reg.size = REG64; operand->u.indirect_with_index.base_reg.no = base_no & 7; operand->u.indirect_with_index.base_reg.x = (base_no & 8) >> 3; operand->u.indirect_with_index.index_reg.size = REG64; - char index_no = index_reg - RAX; + char index_no = index_reg - RAX; operand->u.indirect_with_index.index_reg.size = REG64; operand->u.indirect_with_index.index_reg.no = index_no & 7; operand->u.indirect_with_index.index_reg.x = (index_no & 8) >> 3; @@ -1063,7 +1063,7 @@ parse_operand(struct ParseInfo *info, unsigned int opr_flag, struct Operand *ope if (expr_with_flag.expr != NULL) { if (expr_with_flag.expr->kind == EX_LABEL || expr_with_flag.expr->kind == EX_FIXNUM || expr_with_flag.expr->kind == EX_ADD || expr_with_flag.expr->kind == EX_SUB) { - operand->type = DIRECT; + operand->type = DIRECT; operand->u.direct.expr = expr_with_flag.expr; return EXP; } @@ -1075,7 +1075,7 @@ parse_operand(struct ParseInfo *info, unsigned int opr_flag, struct Operand *ope if (expr_with_flag.expr == NULL) { struct Expr *expr = calloc_or_die(sizeof(*expr)); expr->kind = EX_FIXNUM; - expr->u.fixnum = 0; + expr->u.fixnum = 0; expr_with_flag.expr = expr; } return parse_indirect_register(info, &expr_with_flag, operand); @@ -1803,14 +1803,13 @@ const struct ParseInstTable kParseInstTable[] = { &(struct ParseOpArray){CMOVE, {R32, R32}}, &(struct ParseOpArray){CMOVE, {R64, R64}} }}, - [R_CMOVNZ] = { - 3, - (const struct ParseOpArray *[]){ - &(struct ParseOpArray){CMOVNE, {R16, R16}}, - &(struct ParseOpArray){CMOVNE, {R32, R32}}, - &(struct ParseOpArray){CMOVNE, {R64, R64}} - } - }, + [R_CMOVNZ] = + {3, + (const struct ParseOpArray *[]){ + &(struct ParseOpArray){CMOVNE, {R16, R16}}, + &(struct ParseOpArray){CMOVNE, {R32, R32}}, + &(struct ParseOpArray){CMOVNE, {R64, R64}} + }}, /* explicit-size gas mnemonics qbe's amd64_sysv backend emits: the * suffix only disambiguates operand width when its unsuffixed diff --git a/cmd/dev/as/arch/x64/reloc_x64.c b/cmd/dev/as/arch/x64/reloc_x64.c @@ -57,12 +57,12 @@ resolve_direct_mov( put_value(ir->u.code.buf + ir->u.code.len - 4, value.offset, sizeof(int32_t)); return; } - info = malloc_or_die(sizeof(*info)); - info->kind = inst->op == MOV_DR && reg->size == REG32 ? UNRES_X64_ABS32S : UNRES_X64_ABS32; - info->label = value.label; - info->src_section = section; - info->offset = address + ir->u.code.len - 4 - start_address; - info->add = value.offset; + info = malloc_or_die(sizeof(*info)); + info->kind = inst->op == MOV_DR && reg->size == REG32 ? UNRES_X64_ABS32S : UNRES_X64_ABS32; + info->label = value.label; + info->src_section = section; + info->offset = address + ir->u.code.len - 4 - start_address; + info->add = value.offset; vec_push(unresolved, info); } @@ -109,12 +109,12 @@ x64_resolve_code_reloc( struct Value value = calc_expr(label_table, inst->opr[0].u.indirect.offset.expr); if (value.label != NULL) { struct UnresolvedInfo *info = malloc_or_die(sizeof(*info)); - info->kind = (inst->opr[0].u.indirect.offset.flag & LF_GOTTPOFF) ? UNRES_X64_GOTTPOFF - : UNRES_X64_GOT_LOAD; - info->label = value.label; - info->src_section = section; - info->offset = address + 3 - start_address; - info->add = value.offset - 4; + info->kind = (inst->opr[0].u.indirect.offset.flag & LF_GOTTPOFF) ? UNRES_X64_GOTTPOFF + : UNRES_X64_GOT_LOAD; + info->label = value.label; + info->src_section = section; + info->offset = address + 3 - start_address; + info->add = value.offset - 4; vec_push(unresolved, info); } } @@ -146,14 +146,14 @@ x64_resolve_code_reloc( once the tls layout is known, like ir_asm.c's unres_abs64 registration for .quad label */ if (inst->opr[0].u.segment.offset.flag & LF_TPOFF) { - struct Value value = calc_expr(label_table, inst->opr[0].u.segment.offset.expr); - int reloc_offset = ir->u.code.len - 4; - struct UnresolvedInfo *info = malloc_or_die(sizeof(*info)); - info->kind = UNRES_X64_TPOFF32; - info->label = value.label; - info->src_section = section; - info->offset = address + reloc_offset - start_address; - info->add = value.offset; + struct Value value = calc_expr(label_table, inst->opr[0].u.segment.offset.expr); + int reloc_offset = ir->u.code.len - 4; + struct UnresolvedInfo *info = malloc_or_die(sizeof(*info)); + info->kind = UNRES_X64_TPOFF32; + info->label = value.label; + info->src_section = section; + info->offset = address + reloc_offset - start_address; + info->add = value.offset; vec_push(unresolved, info); } break; diff --git a/cmd/dev/as/emit_elf.c b/cmd/dev/as/emit_elf.c @@ -159,7 +159,7 @@ construct_symtab(struct Symtab *symtab, struct Vector *sections, struct Table *l shndx = SHN_COMMON; else shndx = info->section->index; /* symbol index for - * local section */ + * local section */ } sym->st_shndx = shndx; } diff --git a/cmd/dev/as/emit_macho.c b/cmd/dev/as/emit_macho.c @@ -403,7 +403,7 @@ construct_load_commands(struct Work *work, uint64_t symbol_start_off, int sectio .ncmds = 4, .sizeofcmds = work->size_of_cmds, .flags = MH_SUBSECTIONS_VIA_SYMBOLS, /* TODO: handle this flag - */ + */ }; uint64_t vmsize = 0, filesize = 0; struct Vector *sections = work->sections; diff --git a/cmd/dev/as/ir_asm.c b/cmd/dev/as/ir_asm.c @@ -20,7 +20,7 @@ new_ir_label(const struct Name *label) { struct IR *ir = calloc_or_die(sizeof(*ir)); ir->kind = IR_LABEL; - ir->u.label = label; + ir->u.label = label; return ir; } @@ -29,17 +29,17 @@ new_ir_code(const struct Code *code) { struct IR *ir = calloc_or_die(sizeof(*ir)); ir->kind = IR_CODE; - ir->u.code = *code; + ir->u.code = *code; return ir; } struct IR * new_ir_data(const void *data, size_t size) { - struct IR *ir = calloc_or_die(sizeof(*ir)); - ir->kind = IR_DATA; - ir->u.data.len = size; - ir->u.data.buf = (unsigned char *)data; + struct IR *ir = calloc_or_die(sizeof(*ir)); + ir->kind = IR_DATA; + ir->u.data.len = size; + ir->u.data.buf = (unsigned char *)data; return ir; } @@ -48,7 +48,7 @@ new_ir_bss(size_t size) { struct IR *ir = calloc_or_die(sizeof(*ir)); ir->kind = IR_BSS; - ir->u.bss = size; + ir->u.bss = size; return ir; } @@ -57,7 +57,7 @@ new_ir_zero(size_t size) { struct IR *ir = calloc_or_die(sizeof(*ir)); ir->kind = IR_ZERO; - ir->u.zero = size; + ir->u.zero = size; return ir; } @@ -66,15 +66,15 @@ new_ir_align(int align) { struct IR *ir = calloc_or_die(sizeof(*ir)); ir->kind = IR_ALIGN; - ir->u.align = align; + ir->u.align = align; return ir; } struct IR * new_ir_expr(enum IrKind kind, const struct Expr *expr) { - struct IR *ir = calloc_or_die(sizeof(*ir)); - ir->kind = kind; + struct IR *ir = calloc_or_die(sizeof(*ir)); + ir->kind = kind; ir->u.expr.expr = expr; ir->u.expr.addend = 0; return ir; @@ -225,7 +225,7 @@ resolve_relative_address( info->src_section = section; info->offset = address - start_address; info->add = value.offset; - ir->u.expr.addend = value.offset; + ir->u.expr.addend = value.offset; vec_push(unresolved, info); } break; case IR_LABEL: diff --git a/cmd/dev/as/ir_asm.h b/cmd/dev/as/ir_asm.h @@ -42,7 +42,7 @@ struct UnresolvedInfo { struct SectionInfo *src_section; int add; /* an enum UnresolvedKind, or an architecture's own from UNRES_ARCH_BASE */ - int kind; + int kind; }; struct Data { diff --git a/cmd/dev/as/parse_asm.c b/cmd/dev/as/parse_asm.c @@ -368,14 +368,14 @@ read_flonum(struct ParseInfo *info, int base) char *next; #ifdef __TC /* long double in the toolchain compiler is same as double, and if the target platform uses - */ + */ /* system library, it makes discrepancy */ Flonum val = strtod(start, &next); #else Flonum val = strtold(start, &next); #endif struct Token *tok = new_token(TK_FLONUM); - tok->u.flonum = val; + tok->u.flonum = val; info->p = next; if (base == 16) { @@ -434,7 +434,7 @@ fetch_token(struct ParseInfo *info) } #endif struct Token *token = new_token(TK_FIXNUM); - token->u.fixnum = v; + token->u.fixnum = v; info->p = q; return token; } @@ -443,7 +443,7 @@ fetch_token(struct ParseInfo *info) const struct Name *label = parse_label(info); if (label != NULL) { struct Token *token = new_token(TK_LABEL); - token->u.label.name = label; + token->u.label.name = label; return token; } } break; @@ -488,7 +488,7 @@ fetch_token(struct ParseInfo *info) while (c = *++p, is_label_chr(c)) ; struct Token *token = new_token(TK_LABEL); - token->u.label.name = alloc_name(label, p, 0); + token->u.label.name = alloc_name(label, p, 0); info->p = p; return token; } @@ -526,14 +526,14 @@ prim(struct ParseInfo *info) struct Expr *expr = NULL; const struct Token *tok; if ((tok = match(info, TK_LABEL)) != NULL) { - expr = new_expr(EX_LABEL); + expr = new_expr(EX_LABEL); expr->u.label.name = tok->u.label.name; } else if ((tok = match(info, TK_FIXNUM)) != NULL) { - expr = new_expr(EX_FIXNUM); + expr = new_expr(EX_FIXNUM); expr->u.fixnum = tok->u.fixnum; #ifndef __NO_FLONUM } else if ((tok = match(info, TK_FLONUM)) != NULL) { - expr = new_expr(EX_FLONUM); + expr = new_expr(EX_FLONUM); expr->u.flonum = tok->u.flonum; #endif } @@ -554,7 +554,7 @@ unary(struct ParseInfo *info) return expr; default: { struct Expr *op = new_expr(EX_POS); - op->u.unary.sub = expr; + op->u.unary.sub = expr; return op; } } @@ -575,7 +575,7 @@ unary(struct ParseInfo *info) #endif default: { struct Expr *op = new_expr(EX_NEG); - op->u.unary.sub = expr; + op->u.unary.sub = expr; return op; } } @@ -614,7 +614,7 @@ parse_mul(struct ParseInfo *info) } } else { expr = new_expr((enum ExprKind)(tok->kind + (EX_MUL - TK_MUL))); /* assume exprkind is same - * order with tokenkind */ + * order with tokenkind */ expr->u.bop.lhs = lhs; expr->u.bop.rhs = rhs; } @@ -652,7 +652,7 @@ parse_add(struct ParseInfo *info) } } else { /* assume exprkind is same order with tokenkind */ - expr = new_expr((enum ExprKind)(tok->kind + (EX_ADD - TK_ADD))); + expr = new_expr((enum ExprKind)(tok->kind + (EX_ADD - TK_ADD))); expr->u.bop.lhs = lhs; expr->u.bop.rhs = rhs; } diff --git a/cmd/dev/as/parse_asm.h b/cmd/dev/as/parse_asm.h @@ -37,16 +37,16 @@ enum DirectiveType { DT_WEAK, DT_EXTERN, /* gas integer-data directives. .int/.word and the explicit .nbyte forms - * are aliases of the sized data emitters but need their own table slots - * because the directive dispatch is table-indexed */ + * are aliases of the sized data emitters but need their own table slots + * because the directive dispatch is table-indexed */ DT_INT, DT_WORD, DT_2BYTE, DT_4BYTE, DT_8BYTE, /* space-filling directives: .fill repeats a sized unit, .space/.skip - * reserve a byte run. in a nobits section a zero fill reserves address - * space instead of emitting file bytes */ + * reserve a byte run. in a nobits section a zero fill reserves address + * space instead of emitting file bytes */ DT_FILL, DT_SPACE, DT_SKIP, @@ -179,7 +179,7 @@ int parse_error(struct ParseInfo *info, const char *message); struct ParseOpArray { /* enum opcode */ int op; - int opr_flags[4 + 1]; + int opr_flags[4 + 1]; }; struct ParseInstTable { diff --git a/cmd/dev/cc/cc.h b/cmd/dev/cc/cc.h @@ -88,9 +88,9 @@ enum typeprop { struct bitfield { short before; /* number of bits in the storage unit before the bit-field - */ + */ short after; /* number of bits in the storage unit after the bit-field - */ + */ }; struct member { @@ -195,13 +195,13 @@ struct decl { union { struct { /* alignment of object storage (may be stricter than - * type requires) */ + * type requires) */ int align; enum storageduration storage; } obj; struct { /* the function might have an "inline definition" - * (C11 6.7.4p7) */ + * (C11 6.7.4p7) */ bool inlinedefn; bool isnoreturn; } func; @@ -228,7 +228,7 @@ enum exprkind { /* postfix expression */ EXPRCALL, /* member E.M gets transformed to *(typeof(e.m) *)((char *)e + - * offsetof(typeof(e), m)) */ + * offsetof(typeof(e), m)) */ EXPRBITFIELD, EXPRINCDEC, EXPRCOMPOUND, @@ -256,12 +256,12 @@ struct expr { /* whether this expression is an lvalue */ bool lvalue; /* whether this expression is a pointer decayed from an array or - * function designator */ + * function designator */ bool decayed; /* the unqualified type of the expression */ struct type *type; /* the type qualifiers of the object this expression refers to (ignored - * for non-lvalues) */ + * for non-lvalues) */ enum typequal qual; enum tokenkind op; struct expr *base; diff --git a/cmd/dev/cc/decl.c b/cmd/dev/cc/decl.c @@ -658,10 +658,10 @@ done: if (!t && (tq || (sc && *sc) || (fs && *fs))) error(&tok.loc, "declaration has no type specifier"); /* - * TODO: consider delaying attribute parsing to declarator(), - * so we can tell the difference between the start of an - * attribute and an array declarator - */ + * TODO: consider delaying attribute parsing to declarator(), + * so we can tell the difference between the start of an + * attribute and an array declarator + */ attr(NULL, 0); return (struct qualtype){t, tq, typeofexpr}; @@ -747,10 +747,10 @@ declaratortypes( error(&tok.loc, "expected '(' or identifier"); } /* - * the aligned attribute is used in the definition of - * max_align_t from gcc/clang (used by other Linux libcs), - * dragonflybsd, freebsd, and openbsd - */ + * the aligned attribute is used in the definition of + * max_align_t from gcc/clang (used by other Linux libcs), + * dragonflybsd, freebsd, and openbsd + */ allowedattr = align ? ATTRALIGNED : 0; } for (;;) { @@ -783,7 +783,7 @@ declaratortypes( expect(TRPAREN, "to close function declarator"); if (funcscope && ptr->prev == result) { /* we may need to re-open the scope later if - * this is a function definition */ + * this is a function definition */ *funcscope = s; s = s->parent; } else { @@ -831,7 +831,7 @@ declaratortypes( gnuattr(&a, allowedattr); attr: /* attribute applies to identifier if ptr->prev == - * result, otherwise type ptr->prev */ + * result, otherwise type ptr->prev */ if (ptr->prev == result) { if (a.kind & ATTRALIGNED && a.align > *align) *align = a.align; @@ -890,10 +890,10 @@ declarator( error(&tok.loc, "array element has function type"); if (t->u.array.ptrqual) { /* TODO: check if we are in a function prototype - * if (?) - * error(&tok.loc, "array type has - * qualifiers outside of a function prototype"); - */ + * if (?) + * error(&tok.loc, "array type has + * qualifiers outside of a function prototype"); + */ if (prev != &result) error( &tok.loc, @@ -979,9 +979,9 @@ addmember( } if (mt.type->prop & PROPFLEX) { /* - * ISO c doesnt allow structures with members containing - * fams, but allow it as an extension - */ + * ISO c doesnt allow structures with members containing + * fams, but allow it as an extension + */ t->prop |= PROPFLEX; } if (mt.type->kind == TYPEFUNC) @@ -1047,7 +1047,7 @@ addmember( align = mt.type->align; if (t->kind == TYPESTRUCT) { /* calculate end of the storage-unit for this bit-field - */ + */ end = ALIGNUP(t->size, mt.type->size); if (!width || width > (end - t->size) * 8 + b->bits) { /* no room, allocate a new storage-unit */ @@ -1204,7 +1204,7 @@ declcommon( linkage = getlinkage(kind, sc, prior, s == &filescope); if (linkage != LINKNONE && s->parent) { /* XXX: should maintain map of identifiers with linkage to their - * declaration, and use that */ + * declaration, and use that */ if (s->parent != &filescope) prior = scopegetdecl(&filescope, name, false); if (prior && prior->linkage != LINKNONE) { @@ -1306,7 +1306,7 @@ decl(struct scope *s, struct func *f) } if (consume(TSEMICOLON)) { /* XXX 6.7p2 error unless in function parameter/struct/union, or - * tag/enum members are declared */ + * tag/enum members are declared */ return true; } for (;;) { @@ -1453,7 +1453,7 @@ decl(struct scope *s, struct func *f) if (d->u.func.isnoreturn) funchlt(f); /* XXX: need to keep track of function in case a - * later declaration specifies extern */ + * later declaration specifies extern */ if (!d->u.func.inlinedefn) emitfunc(f, d->linkage == LINKEXTERN); s = delscope(s); diff --git a/cmd/dev/cc/driver.c b/cmd/dev/cc/driver.c @@ -87,7 +87,7 @@ usage(const char *fmt, ...) stderr, "usage: %s [-c|-S|-E] [-D name[=value]] [-U name] [-I dir] " "[-isystem dir] [-iquote dir] [-idirafter dir] [-std=standard] " - "[-nostdinc] [-L dir] [-l library] [-static] [-pthread] [-P] [-s] " + "[-nostdinc] [-L dir] [-l library] [-static] [-pthread] [-P] [-s] " "[-g] [-o output] input...\n", argv0 diff --git a/cmd/dev/cc/eval.c b/cmd/dev/cc/eval.c @@ -260,11 +260,11 @@ eval(struct expr *expr) cast(expr); } else if (l->type->kind == TYPEPOINTER) { /* - * a cast from a pointer to integer is not a valid constant - * expression, but C11 allows implementations to recognize - * other forms of constant expressions (6.6p10), and some - * programs expect this functionality - */ + * a cast from a pointer to integer is not a valid constant + * expression, but C11 allows implementations to recognize + * other forms of constant expressions (6.6p10), and some + * programs expect this functionality + */ if (t->kind == TYPEPOINTER || (t->prop & PROPINT && t->size == typelong.size)) expr = l; } diff --git a/cmd/dev/cc/expr.c b/cmd/dev/cc/expr.c @@ -57,14 +57,14 @@ delexpr(struct expr *e) delexpr(e->u.cond.f); break; /* - * XXX: compound assignment causes some reuse of expressions, - * so we cant free them without risk of a double-free - * - * case EXPRASSIGN: - * delexpr(e->assign.l); - * delexpr(e->assign.r); - * break; - */ + * XXX: compound assignment causes some reuse of expressions, + * so we cant free them without risk of a double-free + * + * case EXPRASSIGN: + * delexpr(e->assign.l); + * delexpr(e->assign.r); + * break; + */ case EXPRCOMMA: while ((sub = e->base)) { e->base = sub->next; @@ -103,11 +103,11 @@ decay(struct expr *e) switch (t->kind) { case TYPEARRAY: /* - * XXX: qualifiers should be applied to the element - * type of array types, not the array type itself - * - * assert(tq == QUALNONE); - */ + * XXX: qualifiers should be applied to the element + * type of array types, not the array type itself + * + * assert(tq == QUALNONE); + */ e = mkunaryexpr(TBAND, e); e->type = mkpointertype(t->base, t->qual | tq); e->decayed = true; @@ -137,9 +137,9 @@ mkunaryexpr(enum tokenkind op, struct expr *base) free(expr); } /* - * allow struct and union types even if they are not lvalues, - * since we take their address when compiling member access - */ + * allow struct and union types even if they are not lvalues, + * since we take their address when compiling member access + */ if (!base->lvalue && base->type->kind != TYPEFUNC && base->type->kind != TYPESTRUCT && base->type->kind != TYPEUNION) error( @@ -471,7 +471,11 @@ mkbinaryexpr(struct location *loc, enum tokenkind op, struct expr *l, struct exp case TDIV: if (iscomplexop(l, r)) { if (l->type->kind != TYPECOMPLEX || r->type->kind != TYPECOMPLEX || l->type != r->type) - error(loc, "'%s' between complex operands requires the same complex type on both sides", tokenstr(op)); + error( + loc, + "'%s' between complex operands requires the same complex type on both sides", + tokenstr(op) + ); t = l->type; break; } @@ -1198,7 +1202,7 @@ builtinfunc(struct scope *s, enum builtinkind kind) case BUILTINEXPECT: /* just a no-op for now */ /* TODO: check that the expression and the expected value have - * type 'long' */ + * type 'long' */ e = assignexpr(s); expect(TCOMMA, "after expression"); delexpr(assignexpr(s)); @@ -1552,10 +1556,10 @@ unaryexpr(struct scope *s) e->u.szof.type = t; } else { /* - * XXX: __alignof__ is not the same as alignof on 32-bit - * archs this needs to be considered if we gain support for - * those archs - */ + * XXX: __alignof__ is not the same as alignof on 32-bit + * archs this needs to be considered if we gain support for + * those archs + */ e = mkconstexpr(&typeulong, op == TSIZEOF ? t->size : t->align); } break; @@ -1810,7 +1814,7 @@ assignexpr(struct scope *s) if (!op) return mkassignexpr(l, r); /* rewrite `E1 OP= E2` as `t = &E1, *t = *t OP E2`, where t is a - * temporary slot */ + * temporary slot */ if (l->kind == EXPRBITFIELD) { bit = l; l = l->base; diff --git a/cmd/dev/cc/include/stdatomic.h b/cmd/dev/cc/include/stdatomic.h @@ -30,18 +30,17 @@ typedef _Atomic unsigned long atomic_ulong; typedef _Atomic long long atomic_llong; typedef _Atomic unsigned long long atomic_ullong; -#define ATOMIC_VAR_INIT(value) (value) +#define ATOMIC_VAR_INIT(value) (value) #define atomic_init(obj, value) (*(obj) = (value)) -#define atomic_load(obj) __atomic_load_n((obj), memory_order_seq_cst) -#define atomic_load_explicit(obj, order) __atomic_load_n((obj), (order)) -#define atomic_store(obj, val) __atomic_store_n((obj), (val), memory_order_seq_cst) +#define atomic_load(obj) __atomic_load_n((obj), memory_order_seq_cst) +#define atomic_load_explicit(obj, order) __atomic_load_n((obj), (order)) +#define atomic_store(obj, val) __atomic_store_n((obj), (val), memory_order_seq_cst) #define atomic_store_explicit(obj, val, order) __atomic_store_n((obj), (val), (order)) #define atomic_exchange(obj, val) __atomic_exchange_n((obj), (val), memory_order_seq_cst) -#define atomic_exchange_explicit(obj, val, order) \ - __atomic_exchange_n((obj), (val), (order)) +#define atomic_exchange_explicit(obj, val, order) __atomic_exchange_n((obj), (val), (order)) -#define atomic_compare_exchange_strong(obj, exp, val) \ +#define atomic_compare_exchange_strong(obj, exp, val) \ __atomic_compare_exchange_n((obj), (exp), (val), 0, memory_order_seq_cst, memory_order_seq_cst) #define atomic_compare_exchange_weak(obj, exp, val) \ __atomic_compare_exchange_n((obj), (exp), (val), 1, memory_order_seq_cst, memory_order_seq_cst) @@ -56,7 +55,7 @@ typedef _Atomic unsigned long long atomic_ullong; #define atomic_fetch_sub_explicit(obj, val, order) __atomic_fetch_sub((obj), (val), (order)) #define atomic_fetch_and(obj, val) __atomic_fetch_and((obj), (val), memory_order_seq_cst) #define atomic_fetch_and_explicit(obj, val, order) __atomic_fetch_and((obj), (val), (order)) -#define atomic_fetch_or(obj, val) __atomic_fetch_or((obj), (val), memory_order_seq_cst) +#define atomic_fetch_or(obj, val) __atomic_fetch_or((obj), (val), memory_order_seq_cst) #define atomic_fetch_or_explicit(obj, val, order) __atomic_fetch_or((obj), (val), (order)) #define atomic_fetch_xor(obj, val) __atomic_fetch_xor((obj), (val), memory_order_seq_cst) #define atomic_fetch_xor_explicit(obj, val, order) __atomic_fetch_xor((obj), (val), (order)) @@ -67,11 +66,10 @@ typedef struct { atomic_bool _flag; } atomic_flag; -#define ATOMIC_FLAG_INIT \ - { 0 } +#define ATOMIC_FLAG_INIT {0} #define atomic_flag_test_and_set(f) __atomic_exchange_n(&(f)->_flag, 1, memory_order_seq_cst) #define atomic_flag_test_and_set_explicit(f, order) __atomic_exchange_n(&(f)->_flag, 1, (order)) -#define atomic_flag_clear(f) __atomic_store_n(&(f)->_flag, 0, memory_order_seq_cst) +#define atomic_flag_clear(f) __atomic_store_n(&(f)->_flag, 0, memory_order_seq_cst) #define atomic_flag_clear_explicit(f, order) __atomic_store_n(&(f)->_flag, 0, (order)) #define atomic_thread_fence(order) ((void)(order)) diff --git a/cmd/dev/cc/init.c b/cmd/dev/cc/init.c @@ -17,7 +17,7 @@ struct object { struct initparser { /* TODO: keep track of type depth, and allocate maximum possible - * number of nested objects in initializer */ + * number of nested objects in initializer */ struct object obj[32], *cur, *sub; struct init *init, **last; }; diff --git a/cmd/dev/cc/ospredef_posix.c b/cmd/dev/cc/ospredef_posix.c @@ -4,8 +4,9 @@ #include "cc.h" /* a system with no file of its own is taken for some unix */ -#if !(defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) \ - || defined(__APPLE__)) \ - || defined(ARUU_FORCE_POSIX) +#if !( \ + defined(__linux__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) \ + || defined(__APPLE__) \ +) || defined(ARUU_FORCE_POSIX) const char ospredef[] = "#define __unix__ 1\n"; #endif diff --git a/cmd/dev/cc/pp.c b/cmd/dev/cc/pp.c @@ -136,7 +136,7 @@ include(void) if (!f) { static const char *const rel[] = {"include", "../lib/aruu/include", "../include"}; char self[FILENAME_MAX]; - ssize_t n = proc_selfexe(self, sizeof(self) - 1); + ssize_t n = proc_selfexe(self, sizeof(self) - 1); if (n == -1) { n = strlen(argv0); if (n > (ssize_t)sizeof(self) - 1) @@ -902,7 +902,7 @@ directive(void) char *quote; /* XXX: handle escape sequences (reuse string decoding - * from expr.c) */ + * from expr.c) */ quote = strchr(tok.lit, '"'); assert(quote); newloc.file = quote + 1; @@ -1163,7 +1163,7 @@ expandfunc(struct macro *m) error(&t->loc, "EOF when reading macro parameters"); if (macrodepth <= depth) { /* adjust current macro depth, in case it got - * shallower */ + * shallower */ depth = macrodepth; if (paren == 0 && (t->kind == TRPAREN || (t->kind == TCOMMA && !(p->flags & PARAMVAR)))) break; diff --git a/cmd/dev/cc/qbe.c b/cmd/dev/cc/qbe.c @@ -1006,10 +1006,10 @@ funcjnz(struct func *f, struct value *v, struct type *t, struct block *l1, struc if (t) { assert(t->prop & PROPSCALAR); /* - * ideally we would just do this conversion unconditionally, - * but QBE is not currently able to optimize the conversion - * away for int - */ + * ideally we would just do this conversion unconditionally, + * but QBE is not currently able to optimize the conversion + * away for int + */ if (t->prop & PROPINT && t->size < 4) v = convert(f, &typeint, t, v); else if (t->prop & PROPFLOAT || t->size > 4) @@ -1702,8 +1702,12 @@ funcexpr(struct func *f, struct expr *e) case BUILTINATOMICFETCHAND: fn = mkatomicfn(t, "__atomic_fetch_and"); break; - case BUILTINATOMICFETCHOR: fn = mkatomicfn(t, "__atomic_fetch_or"); break; - default: fn = mkatomicfn(t, "__atomic_fetch_xor"); break; + case BUILTINATOMICFETCHOR: + fn = mkatomicfn(t, "__atomic_fetch_or"); + break; + default: + fn = mkatomicfn(t, "__atomic_fetch_xor"); + break; } v = funcinst(f, ICALL, qbetype(t).base, fn, NULL); funcinst(f, IARG, ptrclass, l, NULL); @@ -1799,9 +1803,9 @@ funcinit(struct func *func, struct decl *d, struct init *init, bool hasinit) zero(func, d->value, d->type->align, offset, init->end); dst.addr = d->value; /* - * qbe's memopt does not eliminate the store for ptr + 0, - * so only emit the add if the offset is non-zero - */ + * qbe's memopt does not eliminate the store for ptr + 0, + * so only emit the add if the offset is non-zero + */ if (init->start > 0) dst.addr = funcinst(func, IADD, ptrclass, dst.addr, mkintconst(init->start)); src = funcexpr(func, init->expr); @@ -1955,7 +1959,7 @@ emittype(struct type *t) if (t->value || (t->kind != TYPESTRUCT && t->kind != TYPEUNION && t->kind != TYPEINT128 - && t->kind != TYPECOMPLEX)) + && t->kind != TYPECOMPLEX)) return; if (t->kind == TYPEINT128) { emitpairtype(t, t->u.arith.issigned ? "i128" : "u128", 'l'); @@ -1984,7 +1988,7 @@ emittype(struct type *t) for (m = t->u.structunion.members, off = 0; m;) { if (t->kind == TYPESTRUCT) { /* look for a subsequent member with a larger storage - * unit */ + * unit */ for (other = m->next; other; other = other->next) { if (other->offset >= ALIGNUP(m->offset + 1, 8)) break; @@ -2003,7 +2007,7 @@ emittype(struct type *t) if (t->kind == TYPESTRUCT) { fputs(", ", stdout); /* skip subsequent members contained within the same - * storage unit */ + * storage unit */ do m = m->next; while (m && m->offset < off); @@ -2112,7 +2116,7 @@ emitfunc(struct func *f, bool global) if (f->end->jump.kind == JUMP_NONE) { v = NULL; /* implicitly return 0 from main if we reach the end of the - * function */ + * function */ if (strcmp(f->name, "main") == 0 && f->type->base == &typeint) v = mkintconst(0); funcret(f, v); @@ -2278,7 +2282,7 @@ emitdata(struct decl *d, struct init *init) end = cur->end - (cur->bits.after + 7) / 8; if (offset < start && bits) { printf("b %u, ", (unsigned)bits); /* unfinished byte from previous - * bit-field */ + * bit-field */ ++offset; bits = 0; } @@ -2292,10 +2296,10 @@ emitdata(struct decl *d, struct init *init) for (offset = start; offset < end; ++offset, bits >>= 8) printf("b %u, ", (unsigned)bits & 0xff); /* - * clear the upper `after` bits in the last byte, - * or all bits when `after` is 0 (we ended on a - * byte boundary) - */ + * clear the upper `after` bits in the last byte, + * or all bits when `after` is 0 (we ended on a + * byte boundary) + */ bits &= 0x7f >> (cur->bits.after + 7) % 8; } else { t = cur->expr->type; diff --git a/cmd/dev/cc/token.c b/cmd/dev/cc/token.c @@ -9,9 +9,9 @@ #include "util.h" #include "cc.h" -struct token tok; -static struct map tokmap; /* maps string to token */ -static struct array tokstr; /* maps token to string */ +struct token tok; +static struct map tokmap; /* maps string to token */ +static struct array tokstr; /* maps token to string */ void tokeninit(void) diff --git a/cmd/dev/cc/tree.c b/cmd/dev/cc/tree.c @@ -20,14 +20,14 @@ rot(void **p, struct treenode *x, int dir /* deeper side */) int hz = height(z); if (hz > height(y->child[dir])) { /* - * x - * / \ dir z - * a y / \ - * / \ --> x y - * z d /| |\ - * / \ a b c d - * b c - */ + * x + * / \ dir z + * a y / \ + * / \ --> x y + * z d /| |\ + * / \ a b c d + * b c + */ x->child[dir] = z->child[!dir]; y->child[!dir] = z->child[dir]; z->child[!dir] = x; @@ -37,12 +37,12 @@ rot(void **p, struct treenode *x, int dir /* deeper side */) z->height = hz + 1; } else { /* - * x y - * / \ / \ - * a y --> x d - * / \ / \ - * z d a z - */ + * x y + * / \ / \ + * a y --> x d + * / \ / \ + * z d a z + */ x->child[dir] = z; y->child[!dir] = x; x->height = hz + 1; diff --git a/cmd/dev/cc/type.c b/cmd/dev/cc/type.c @@ -184,10 +184,10 @@ typecompatible(struct type *t1, struct type *t2) return true; if (t1->kind != t2->kind) { /* - * enum types are compatible with their underlying - * type, but not with each other (unless they are the - * same type) - */ + * enum types are compatible with their underlying + * type, but not with each other (unless they are the + * same type) + */ return (t1->kind == TYPEENUM && t2 == t1->base) || (t2->kind == TYPEENUM && t1 == t2->base); } switch (t1->kind) { diff --git a/cmd/dev/ld/ld.c b/cmd/dev/ld/ld.c @@ -211,8 +211,7 @@ symval(struct outelf *oe, struct obj *obj, Elf_Sym *sym) * defines it locally (st_shndx != SHN_UNDEF). musl libc.a has the weak * default and the strong definition in different members, and every * reference must bind to the strong one */ - if (name && *name - && (sym->st_shndx == SHN_UNDEF || ELF_ST_BIND(sym->st_info) == STB_WEAK)) { + if (name && *name && (sym->st_shndx == SHN_UNDEF || ELF_ST_BIND(sym->st_info) == STB_WEAK)) { if (outelf_find(oe, name, &obj, &sym)) { if (is_ldsym(name)) return ldsym_val(oe, name); @@ -292,14 +291,14 @@ outelf_got_prescan(struct outelf *oe) static void outelf_reloc_sec(struct outelf *oe, int o_idx, int s_idx) { - struct obj *obj = &oe->objs[o_idx]; - Elf_Shdr *rel_shdr = &obj->shdr[s_idx]; - Elf_Rela *rels = (Elf_Rela *)(obj->mem + obj->shdr[s_idx].sh_offset); - Elf_Shdr *other_shdr = &obj->shdr[rel_shdr->sh_info]; - char *other = obj->mem + other_shdr->sh_offset; - int nrels = rel_shdr->sh_size / sizeof(*rels); - struct secmap *other_sec = outelf_mapping(oe, other_shdr); - int i; + struct obj *obj = &oe->objs[o_idx]; + Elf_Shdr *rel_shdr = &obj->shdr[s_idx]; + Elf_Rela *rels = (Elf_Rela *)(obj->mem + obj->shdr[s_idx].sh_offset); + Elf_Shdr *other_shdr = &obj->shdr[rel_shdr->sh_info]; + char *other = obj->mem + other_shdr->sh_offset; + int nrels = rel_shdr->sh_size / sizeof(*rels); + struct secmap *other_sec = outelf_mapping(oe, other_shdr); + int i; /* relocations against a section dropped from the output (eh_frame, * notes, debug info) have nothing to apply to */ @@ -629,8 +628,7 @@ link_cs( name = sec->obj->shstr + sec->o_shdr->sh_name; is_init = !strcmp(name, ".init"); is_fini = !strcmp(name, ".fini"); - if ((pass == 0 && !is_init) || (pass == 1 && !is_fini) - || (pass == 2 && (is_init || is_fini))) + if ((pass == 0 && !is_init) || (pass == 1 && !is_fini) || (pass == 2 && (is_init || is_fini))) continue; alignment = pass < 2 ? 1 : MAX(sec->o_shdr->sh_addralign, 4); len = ALIGN(vaddr + len, alignment) - vaddr; @@ -792,7 +790,7 @@ outelf_link(struct outelf *oe) /* tls template follows the got inside the data segment. its tbss tail * has no file bytes, like bss, so it grows p_memsz but not p_filesz */ - has_tls = link_tls(oe, &oe->phdr[3], faddr + len, vaddr + len) != 0; + has_tls = link_tls(oe, &oe->phdr[3], faddr + len, vaddr + len) != 0; oe->phdr[1].p_filesz = ALIGN(len + oe->tls_filesz, 4); len = ALIGN(len + oe->tls_size, 4); oe->phdr[1].p_memsz = len; @@ -972,9 +970,9 @@ filesize(int fd) static char * fileread(char *path) { - int fd = open(path, O_RDONLY); - long size; - char *buf; + int fd = open(path, O_RDONLY); + long size; + char *buf; ssize_t nread; if (fd < 0) diff --git a/cmd/dev/ld/ld.h b/cmd/dev/ld/ld.h @@ -104,22 +104,22 @@ struct outelf { int bss_len; /* got: one entry per GOTPCREL/GOTTPOFF relocation. the entry stores - * the resolved symbol address (or, for a tls symbol, its tp-relative - * offset). the relocation displacement points here */ + * the resolved symbol address (or, for a tls symbol, its tp-relative + * offset). the relocation displacement points here */ struct got_entry got[MAXGOT]; int ngot; unsigned long got_vaddr; unsigned long got_faddr; /* tls template: .tdata/.tbss from every object, merged into one - * block. a tls section's secmap.vaddr holds its offset from the - * start of this block (0-based), not a runtime address, since tls - * variables are addressed tp-relative, not absolutely */ + * block. a tls section's secmap.vaddr holds its offset from the + * start of this block (0-based), not a runtime address, since tls + * variables are addressed tp-relative, not absolutely */ unsigned long tls_size; unsigned long tls_filesz; /* the notes of every object, laid out together after the code, which - * the PT_NOTE segment covers */ + * the PT_NOTE segment covers */ unsigned long note_faddr; unsigned long note_vaddr; unsigned long note_len; diff --git a/cmd/dev/ninqu/expand.c b/cmd/dev/ninqu/expand.c @@ -270,11 +270,11 @@ expand_rule(const char *name) int r_literal = rule_is_literal(r); /* run a codegen producer before globbing only when its output feeds - * this rule's glob, so POSIX_BC_C (produces cmd/posix/bc.c) finishes - * before glob_all() looks for it. other extra_deps (libraries, - * headers) just get registered by expand_rule() so finalize_inst() - * can wire up dep_rule_names. skipped in summary mode: -S must not - * execute */ + * this rule's glob, so POSIX_BC_C (produces cmd/posix/bc.c) finishes + * before glob_all() looks for it. other extra_deps (libraries, + * headers) just get registered by expand_rule() so finalize_inst() + * can wire up dep_rule_names. skipped in summary mode: -S must not + * execute */ if (!summary_mode) { for (j = 0; j < r->extra_deps.n; j++) { char *tok = kv_expand(r->extra_deps.v[j]); @@ -365,7 +365,7 @@ expand_rule(const char *name) struct KvStore ov; /* non-glob rules have no MATCH/DIR/BASE to expose, so the - * overlay only carries IN/OUT for build_cmd */ + * overlay only carries IN/OUT for build_cmd */ setup_inst(inst, r); memset(&ov, 0, sizeof ov); local_overlay = &ov; diff --git a/cmd/dev/ninqu/ninja.c b/cmd/dev/ninqu/ninja.c @@ -67,9 +67,9 @@ fprint_shell_word(FILE *f, const char *s) } /* wrapped in double quotes so the shell treats the substitutions - * result as one word instead of splitting it on whitespace, which - * is exactly what an unquoted $(...) would do to a multi-line - * result */ + * result as one word instead of splitting it on whitespace, which + * is exactly what an unquoted $(...) would do to a multi-line + * result */ fputs("\"$$(printf '%b' '", f); for (; *s; s++) { if (*s == '\'') @@ -261,8 +261,8 @@ emit_ninja(const char *path, struct StrList *wanted) char depbuf[1024]; const char *depout = inst_target(dep, inst->dep_inst[k], depbuf, sizeof depbuf); /* a rule ref that is also a real (dep ...) input already - * forces both order and staleness, listing it again as - * order-only is pure noise */ + * forces both order and staleness, listing it again as + * order-only is pure noise */ if (sl_has(&inst->in, depout) || sl_has(&inst->stale_extra, depout)) continue; if (!printed_bar) { diff --git a/cmd/dev/ninqu/parse.c b/cmd/dev/ninqu/parse.c @@ -247,13 +247,13 @@ apply_rule_clause(struct Rule *r, const char *name, struct SNode *clause) ); } else if (strcmp(h, "group") == 0) { /* display-only: shows up in (query rules) output, no effect on - * resolution. (member ...) below is the enforcing one. the two - * are separate because several rules used (group ...) this way - * before namespacing existed */ + * resolution. (member ...) below is the enforcing one. the two + * are separate because several rules used (group ...) this way + * before namespacing existed */ strlcpy(r->group_name, sole_atom(clause, "(group NAME) takes one name"), sizeof r->group_name); } else if (strcmp(h, "member") == 0) { /* (member GROUP [ALIAS]) hides the bare name from the command - * line. ALIAS defaults to the rule own name */ + * line. ALIAS defaults to the rule own name */ if (clause->nkids < 2 || clause->nkids > 3 || clause->kids[1]->kind != S_ATOM) eprintf("manifest: rule %s: (member GROUP [ALIAS]) needs a group name\n", name); strlcpy(r->member_of, clause->kids[1]->atom, sizeof r->member_of); diff --git a/cmd/dev/ninqu/resolve.c b/cmd/dev/ninqu/resolve.c @@ -140,8 +140,8 @@ resolve_wanted(const char *w) } /* a rule that declared (member ...) does not resolve by bare name - * from the command line, only through GROUP/ALIAS or transitively - * via its owning group ref list */ + * from the command line, only through GROUP/ALIAS or transitively + * via its owning group ref list */ { struct Rule *br = rule_find(w); if (br && br->member_of[0]) diff --git a/cmd/dev/xelf/xelf.c b/cmd/dev/xelf/xelf.c @@ -167,8 +167,8 @@ sh_read(const struct elf *e, const unsigned char *t) struct elf v = *e; struct sh s; - v.b = (unsigned char *)t; - v.n = shentsize(e); + v.b = (unsigned char *)t; + v.n = shentsize(e); s.name = (uint32_t)get(&v, 0, 4); s.type = (uint32_t)get(&v, 4, 4); if (e->wide) { @@ -212,7 +212,15 @@ sh_write(const struct elf *e, unsigned char *at, const struct sh *s) * section of the notes is emptied, so repeated adds do not pile them up. * the bytes go to *tail, from *at on (which they move past) */ static void -sections_tail(struct elf *e, uint64_t note_off, uint64_t note_addr, size_t note_len, unsigned char **tail, size_t *tail_len, size_t *at) +sections_tail( + struct elf *e, + uint64_t note_off, + uint64_t note_addr, + size_t note_len, + unsigned char **tail, + size_t *tail_len, + size_t *at +) { int n = shnum(e), si = shstrndx(e), i, ent = shentsize(e); struct sh names, add_sh; @@ -224,13 +232,13 @@ sections_tail(struct elf *e, uint64_t note_off, uint64_t note_addr, size_t note_ names = sh_read(e, e->b + shoff(e) + (size_t)si * ent); if (names.offset + names.size > e->n) return; - strs_at = (*at + 7) & ~(size_t)7; - name_off = names.size; - strs = ecalloc(1, names.size + sizeof SEC_NAME); + strs_at = (*at + 7) & ~(size_t)7; + name_off = names.size; + strs = ecalloc(1, names.size + sizeof SEC_NAME); memcpy(strs, e->b + names.offset, names.size); memcpy(strs + name_off, SEC_NAME, sizeof SEC_NAME); - table_at = (strs_at + names.size + sizeof SEC_NAME + 7) & ~(size_t)7; - table = ecalloc(n + 1, ent); + table_at = (strs_at + names.size + sizeof SEC_NAME + 7) & ~(size_t)7; + table = ecalloc(n + 1, ent); memcpy(table, e->b + shoff(e), (size_t)n * ent); for (i = 0; i < n; i++) { struct sh x = sh_read(e, table + (size_t)i * ent); @@ -320,7 +328,9 @@ ph_write(const struct elf *e, unsigned char *at, const struct ph *p) * it, and where its desc is. returns the offset of the next, 0 at the end * or on a note that does not fit, which is the end of what can be read */ static size_t -note_at(const struct elf *e, size_t at, size_t end, uint32_t *type, int *ours, size_t *desc, size_t *len) +note_at( + const struct elf *e, size_t at, size_t end, uint32_t *type, int *ours, size_t *desc, size_t *len +) { uint64_t namesz, descsz; size_t next; @@ -430,8 +440,15 @@ dump_note(struct elf *e, size_t at, uint32_t type, size_t desc, size_t len, void /* the file as it is, then zeros to at, then extra, then more */ static void -write_out(const struct elf *e, const char *path, const unsigned char *extra, size_t extra_len, size_t at, - const unsigned char *more, size_t more_len) +write_out( + const struct elf *e, + const char *path, + const unsigned char *extra, + size_t extra_len, + size_t at, + const unsigned char *more, + size_t more_len +) { char tmp[4096]; struct stat st; @@ -461,7 +478,7 @@ static unsigned long qx_width(const unsigned char *b, size_t n) { unsigned long w = 0; - size_t i = 3; + size_t i = 3; if (n < 4 || memcmp(b, "QX ", 3)) return 0; @@ -682,7 +699,7 @@ check_note(struct elf *e, size_t at, uint32_t type, size_t desc, size_t len, voi { (void)at; if (type == T_ICON) { - size_t n = 0; + size_t n = 0; unsigned long said = 0; while (n < len && e->b[desc + n] != '\n') @@ -699,7 +716,9 @@ check_note(struct elf *e, size_t at, uint32_t type, size_t desc, size_t len, voi static void usage(void) { - eprintf("usage: %s add [-p plumb] bin manifest [icon ...] | dump bin | rm bin | check bin\n", argv0); + eprintf( + "usage: %s add [-p plumb] bin manifest [icon ...] | dump bin | rm bin | check bin\n", argv0 + ); } // ?man xelf: records inside an executable @@ -712,7 +731,7 @@ usage(void) int main(int argc, char *argv[]) { - struct elf e; + struct elf e; const char *plumb = NULL; const char *verb; int count = 0; diff --git a/cmd/extra/fsck.ext4/compat.h b/cmd/extra/fsck.ext4/compat.h @@ -7,14 +7,14 @@ #include <sys/stat.h> #define daddr_t int64_t -#define IFMT S_IFMT -#define IFIFO S_IFIFO -#define IFCHR S_IFCHR -#define IFDIR S_IFDIR -#define IFBLK S_IFBLK -#define IFREG S_IFREG -#define IFLNK S_IFLNK -#define IFSOCK S_IFSOCK +#define IFMT S_IFMT +#define IFIFO S_IFIFO +#define IFCHR S_IFCHR +#define IFDIR S_IFDIR +#define IFBLK S_IFBLK +#define IFREG S_IFREG +#define IFLNK S_IFLNK +#define IFSOCK S_IFSOCK #ifndef __RCSID #define __RCSID(s) typedef char rcsid[sizeof(s)] diff --git a/cmd/extra/fsck.ext4/dir.c b/cmd/extra/fsck.ext4/dir.c @@ -67,7 +67,6 @@ __RCSID("$NetBSD: dir.c,v 1.28 2013/06/23 07:28:36 dholland Exp $"); #include <ufs/ext2fs/ext2fs_dir.h> #include <ufs/ext2fs/ext2fs.h> - #include <stdio.h> #include <stdlib.h> #include <string.h> @@ -77,33 +76,33 @@ __RCSID("$NetBSD: dir.c,v 1.28 2013/06/23 07:28:36 dholland Exp $"); #include "fsutil.h" #include "extern.h" -const char *lfname = "lost+found"; -int lfmode = 01700; -struct ext2fs_dirtemplate emptydir = { - .dot_ino = 0, - .dot_reclen = UFS_DIRBLKSIZ, -}; -struct ext2fs_dirtemplate dirhead = { - .dot_ino = 0, - .dot_reclen = 12, - .dot_namlen = 1, - .dot_type = EXT2_FT_DIR, - .dot_name = ".", - .dotdot_ino = 0, - .dotdot_reclen = UFS_DIRBLKSIZ - 12, - .dotdot_namlen = 2, - .dotdot_type = EXT2_FT_DIR, - .dotdot_name = "..", +const char *lfname = "lost+found"; +int lfmode = 01700; +struct ext2fs_dirtemplate emptydir = { + .dot_ino = 0, + .dot_reclen = UFS_DIRBLKSIZ, +}; +struct ext2fs_dirtemplate dirhead = { + .dot_ino = 0, + .dot_reclen = 12, + .dot_namlen = 1, + .dot_type = EXT2_FT_DIR, + .dot_name = ".", + .dotdot_ino = 0, + .dotdot_reclen = UFS_DIRBLKSIZ - 12, + .dotdot_namlen = 2, + .dotdot_type = EXT2_FT_DIR, + .dotdot_name = "..", }; #undef UFS_DIRBLKSIZ -static int expanddir(struct ext2fs_dinode *, char *); -static void freedir(ino_t, ino_t); +static int expanddir(struct ext2fs_dinode *, char *); +static void freedir(ino_t, ino_t); static struct ext2fs_direct *fsck_readdir(struct inodesc *); -static struct bufarea *getdirblk(daddr_t, long); -static int lftempname(char *, ino_t); -static int mkentry(struct inodesc *); -static int chgino(struct inodesc *); +static struct bufarea *getdirblk(daddr_t, long); +static int lftempname(char *, ino_t); +static int mkentry(struct inodesc *); +static int chgino(struct inodesc *); /* * Propagate connected state through the tree. @@ -111,34 +110,32 @@ static int chgino(struct inodesc *); void propagate(void) { - struct inoinfo **inpp, *inp, *pinp; - struct inoinfo **inpend; - - /* - * Create a list of children for each directory. - */ - inpend = &inpsort[inplast]; - for (inpp = inpsort; inpp < inpend; inpp++) { - inp = *inpp; - if (inp->i_parent == 0 || - inp->i_number == EXT2_ROOTINO) - continue; - pinp = getinoinfo(inp->i_parent); - inp->i_parentp = pinp; - inp->i_sibling = pinp->i_child; - pinp->i_child = inp; - } - inp = getinoinfo(EXT2_ROOTINO); - while (inp) { - statemap[inp->i_number] = DFOUND; - if (inp->i_child && - statemap[inp->i_child->i_number] == DSTATE) - inp = inp->i_child; - else if (inp->i_sibling) - inp = inp->i_sibling; - else - inp = inp->i_parentp; - } + struct inoinfo **inpp, *inp, *pinp; + struct inoinfo **inpend; + + /* + * Create a list of children for each directory. + */ + inpend = &inpsort[inplast]; + for (inpp = inpsort; inpp < inpend; inpp++) { + inp = *inpp; + if (inp->i_parent == 0 || inp->i_number == EXT2_ROOTINO) + continue; + pinp = getinoinfo(inp->i_parent); + inp->i_parentp = pinp; + inp->i_sibling = pinp->i_child; + pinp->i_child = inp; + } + inp = getinoinfo(EXT2_ROOTINO); + while (inp) { + statemap[inp->i_number] = DFOUND; + if (inp->i_child && statemap[inp->i_child->i_number] == DSTATE) + inp = inp->i_child; + else if (inp->i_sibling) + inp = inp->i_sibling; + else + inp = inp->i_parentp; + } } /* @@ -147,45 +144,43 @@ propagate(void) int dirscan(struct inodesc *idesc) { - struct ext2fs_direct *dp; - struct bufarea *bp; - int dsize, n; - long blksiz; - char *dbuf = NULL; - - if ((dbuf = malloc(sblock.e2fs_bsize)) == NULL) - err(8, "Can't allocate directory block"); - - if (idesc->id_type != DATA) - errexit("wrong type to dirscan %d", idesc->id_type); - if (idesc->id_entryno == 0 && - (idesc->id_filesize & (sblock.e2fs_bsize - 1)) != 0) - idesc->id_filesize = roundup(idesc->id_filesize, sblock.e2fs_bsize); - blksiz = idesc->id_numfrags * sblock.e2fs_bsize; - if (chkrange(idesc->id_blkno, idesc->id_numfrags)) { - idesc->id_filesize -= blksiz; - free(dbuf); - return (SKIP); - } - idesc->id_loc = 0; - for (dp = fsck_readdir(idesc); dp != NULL; dp = fsck_readdir(idesc)) { - dsize = fs2h16(dp->e2d_reclen); - memcpy(dbuf, dp, (size_t)dsize); - idesc->id_dirp = (struct ext2fs_direct *)dbuf; - if ((n = (*idesc->id_func)(idesc)) & ALTERED) { - bp = getdirblk(idesc->id_blkno, blksiz); - memcpy(bp->b_un.b_buf + idesc->id_loc - dsize, dbuf, - (size_t)dsize); - dirty(bp); - sbdirty(); - } - if (n & STOP) { - free(dbuf); - return (n); - } - } - free(dbuf); - return (idesc->id_filesize > 0 ? KEEPON : STOP); + struct ext2fs_direct *dp; + struct bufarea *bp; + int dsize, n; + long blksiz; + char *dbuf = NULL; + + if ((dbuf = malloc(sblock.e2fs_bsize)) == NULL) + err(8, "Can't allocate directory block"); + + if (idesc->id_type != DATA) + errexit("wrong type to dirscan %d", idesc->id_type); + if (idesc->id_entryno == 0 && (idesc->id_filesize & (sblock.e2fs_bsize - 1)) != 0) + idesc->id_filesize = roundup(idesc->id_filesize, sblock.e2fs_bsize); + blksiz = idesc->id_numfrags * sblock.e2fs_bsize; + if (chkrange(idesc->id_blkno, idesc->id_numfrags)) { + idesc->id_filesize -= blksiz; + free(dbuf); + return (SKIP); + } + idesc->id_loc = 0; + for (dp = fsck_readdir(idesc); dp != NULL; dp = fsck_readdir(idesc)) { + dsize = fs2h16(dp->e2d_reclen); + memcpy(dbuf, dp, (size_t)dsize); + idesc->id_dirp = (struct ext2fs_direct *)dbuf; + if ((n = (*idesc->id_func)(idesc)) & ALTERED) { + bp = getdirblk(idesc->id_blkno, blksiz); + memcpy(bp->b_un.b_buf + idesc->id_loc - dsize, dbuf, (size_t)dsize); + dirty(bp); + sbdirty(); + } + if (n & STOP) { + free(dbuf); + return (n); + } + } + free(dbuf); + return (idesc->id_filesize > 0 ? KEEPON : STOP); } /* @@ -194,58 +189,56 @@ dirscan(struct inodesc *idesc) static struct ext2fs_direct * fsck_readdir(struct inodesc *idesc) { - struct ext2fs_direct *dp, *ndp; - struct bufarea *bp; - long size, blksiz, fix, dploc; - - blksiz = idesc->id_numfrags * sblock.e2fs_bsize; - bp = getdirblk(idesc->id_blkno, blksiz); - if (idesc->id_loc % sblock.e2fs_bsize == 0 && idesc->id_filesize > 0 && - idesc->id_loc < blksiz) { - dp = (struct ext2fs_direct *)(bp->b_un.b_buf + idesc->id_loc); - if (dircheck(idesc, dp)) - goto dpok; - if (idesc->id_fix == IGNORE) - return (0); - fix = dofix(idesc, "DIRECTORY CORRUPTED"); - bp = getdirblk(idesc->id_blkno, blksiz); - dp = (struct ext2fs_direct *)(bp->b_un.b_buf + idesc->id_loc); - dp->e2d_reclen = h2fs16(sblock.e2fs_bsize); - dp->e2d_ino = 0; - dp->e2d_namlen = 0; - dp->e2d_type = 0; - dp->e2d_name[0] = '\0'; - if (fix) - dirty(bp); - idesc->id_loc += sblock.e2fs_bsize; - idesc->id_filesize -= sblock.e2fs_bsize; - return (dp); - } + struct ext2fs_direct *dp, *ndp; + struct bufarea *bp; + long size, blksiz, fix, dploc; + + blksiz = idesc->id_numfrags * sblock.e2fs_bsize; + bp = getdirblk(idesc->id_blkno, blksiz); + if (idesc->id_loc % sblock.e2fs_bsize == 0 && idesc->id_filesize > 0 && idesc->id_loc < blksiz) { + dp = (struct ext2fs_direct *)(bp->b_un.b_buf + idesc->id_loc); + if (dircheck(idesc, dp)) + goto dpok; + if (idesc->id_fix == IGNORE) + return (0); + fix = dofix(idesc, "DIRECTORY CORRUPTED"); + bp = getdirblk(idesc->id_blkno, blksiz); + dp = (struct ext2fs_direct *)(bp->b_un.b_buf + idesc->id_loc); + dp->e2d_reclen = h2fs16(sblock.e2fs_bsize); + dp->e2d_ino = 0; + dp->e2d_namlen = 0; + dp->e2d_type = 0; + dp->e2d_name[0] = '\0'; + if (fix) + dirty(bp); + idesc->id_loc += sblock.e2fs_bsize; + idesc->id_filesize -= sblock.e2fs_bsize; + return (dp); + } dpok: - if (idesc->id_filesize <= 0 || idesc->id_loc >= blksiz) - return NULL; - dploc = idesc->id_loc; - dp = (struct ext2fs_direct *)(bp->b_un.b_buf + dploc); - idesc->id_loc += fs2h16(dp->e2d_reclen); - idesc->id_filesize -= fs2h16(dp->e2d_reclen); - if ((idesc->id_loc % sblock.e2fs_bsize) == 0) - return (dp); - ndp = (struct ext2fs_direct *)(bp->b_un.b_buf + idesc->id_loc); - if (idesc->id_loc < blksiz && idesc->id_filesize > 0 && - dircheck(idesc, ndp) == 0) { - size = sblock.e2fs_bsize - (idesc->id_loc % sblock.e2fs_bsize); - idesc->id_loc += size; - idesc->id_filesize -= size; - if (idesc->id_fix == IGNORE) - return (0); - fix = dofix(idesc, "DIRECTORY CORRUPTED"); - bp = getdirblk(idesc->id_blkno, blksiz); - dp = (struct ext2fs_direct *)(bp->b_un.b_buf + dploc); - dp->e2d_reclen = h2fs16(fs2h16(dp->e2d_reclen) + size); - if (fix) - dirty(bp); - } - return (dp); + if (idesc->id_filesize <= 0 || idesc->id_loc >= blksiz) + return NULL; + dploc = idesc->id_loc; + dp = (struct ext2fs_direct *)(bp->b_un.b_buf + dploc); + idesc->id_loc += fs2h16(dp->e2d_reclen); + idesc->id_filesize -= fs2h16(dp->e2d_reclen); + if ((idesc->id_loc % sblock.e2fs_bsize) == 0) + return (dp); + ndp = (struct ext2fs_direct *)(bp->b_un.b_buf + idesc->id_loc); + if (idesc->id_loc < blksiz && idesc->id_filesize > 0 && dircheck(idesc, ndp) == 0) { + size = sblock.e2fs_bsize - (idesc->id_loc % sblock.e2fs_bsize); + idesc->id_loc += size; + idesc->id_filesize -= size; + if (idesc->id_fix == IGNORE) + return (0); + fix = dofix(idesc, "DIRECTORY CORRUPTED"); + bp = getdirblk(idesc->id_blkno, blksiz); + dp = (struct ext2fs_direct *)(bp->b_un.b_buf + dploc); + dp->e2d_reclen = h2fs16(fs2h16(dp->e2d_reclen) + size); + if (fix) + dirty(bp); + } + return (dp); } /* @@ -255,241 +248,235 @@ dpok: int dircheck(struct inodesc *idesc, struct ext2fs_direct *dp) { - int size; - char *cp; - int spaceleft; - u_int16_t reclen = fs2h16(dp->e2d_reclen); - - spaceleft = sblock.e2fs_bsize - (idesc->id_loc % sblock.e2fs_bsize); - if (fs2h32(dp->e2d_ino) > maxino || - reclen == 0 || - reclen > spaceleft || - (reclen & 0x3) != 0) - return (0); - if (dp->e2d_ino == 0) - return (1); - if (sblock.e2fs.e2fs_rev < E2FS_REV1 || - (sblock.e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE) == 0) - if (dp->e2d_type != 0) - return (1); - size = EXT2FS_DIRSIZ(dp->e2d_namlen); - if (reclen < size || - idesc->id_filesize < size /* || - dp->e2d_namlen > EXT2FS_MAXNAMLEN */) - return (0); - for (cp = dp->e2d_name, size = 0; size < dp->e2d_namlen; size++) - if (*cp == '\0' || (*cp++ == '/')) - return (0); - return (1); + int size; + char *cp; + int spaceleft; + u_int16_t reclen = fs2h16(dp->e2d_reclen); + + spaceleft = sblock.e2fs_bsize - (idesc->id_loc % sblock.e2fs_bsize); + if (fs2h32(dp->e2d_ino) > maxino || reclen == 0 || reclen > spaceleft || (reclen & 0x3) != 0) + return (0); + if (dp->e2d_ino == 0) + return (1); + if (sblock.e2fs.e2fs_rev < E2FS_REV1 + || (sblock.e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE) == 0) + if (dp->e2d_type != 0) + return (1); + size = EXT2FS_DIRSIZ(dp->e2d_namlen); + if ( + reclen < size || idesc->id_filesize < size /* || + dp->e2d_namlen > EXT2FS_MAXNAMLEN */ + ) + return (0); + for (cp = dp->e2d_name, size = 0; size < dp->e2d_namlen; size++) + if (*cp == '\0' || (*cp++ == '/')) + return (0); + return (1); } void direrror(ino_t ino, const char *errmesg) { - - fileerror(ino, ino, errmesg); + fileerror(ino, ino, errmesg); } void fileerror(ino_t cwd, ino_t ino, const char *errmesg) { - struct ext2fs_dinode *dp; - char pathbuf[MAXPATHLEN + 1]; - - pwarn("%s ", errmesg); - pinode(ino); - printf("\n"); - getpathname(pathbuf, sizeof(pathbuf), cwd, ino); - if ((ino < EXT2_FIRSTINO && ino != EXT2_ROOTINO) || ino > maxino) { - pfatal("NAME=%s\n", pathbuf); - return; - } - dp = ginode(ino); - if (ftypeok(dp)) - pfatal("%s=%s\n", - (fs2h16(dp->e2di_mode) & IFMT) == IFDIR ? "DIR" : "FILE", pathbuf); - else - pfatal("NAME=%s\n", pathbuf); + struct ext2fs_dinode *dp; + char pathbuf[MAXPATHLEN + 1]; + + pwarn("%s ", errmesg); + pinode(ino); + printf("\n"); + getpathname(pathbuf, sizeof(pathbuf), cwd, ino); + if ((ino < EXT2_FIRSTINO && ino != EXT2_ROOTINO) || ino > maxino) { + pfatal("NAME=%s\n", pathbuf); + return; + } + dp = ginode(ino); + if (ftypeok(dp)) + pfatal("%s=%s\n", (fs2h16(dp->e2di_mode) & IFMT) == IFDIR ? "DIR" : "FILE", pathbuf); + else + pfatal("NAME=%s\n", pathbuf); } void adjust(struct inodesc *idesc, short lcnt) { - struct ext2fs_dinode *dp; - - dp = ginode(idesc->id_number); - if (fs2h16(dp->e2di_nlink) == lcnt) { - if (linkup(idesc->id_number, (ino_t)0) == 0) - clri(idesc, "UNREF", 0); - } else { - pwarn("LINK COUNT %s", (lfdir == idesc->id_number) ? lfname : - ((fs2h16(dp->e2di_mode) & IFMT) == IFDIR ? "DIR" : "FILE")); - pinode(idesc->id_number); - printf(" COUNT %d SHOULD BE %d", - fs2h16(dp->e2di_nlink), fs2h16(dp->e2di_nlink) - lcnt); - if (preen) { - if (lcnt < 0) { - printf("\n"); - pfatal("LINK COUNT INCREASING"); - } - printf(" (ADJUSTED)\n"); - } - if (preen || reply("ADJUST") == 1) { - dp->e2di_nlink = h2fs16(fs2h16(dp->e2di_nlink) - lcnt); - inodirty(); - } - } + struct ext2fs_dinode *dp; + + dp = ginode(idesc->id_number); + if (fs2h16(dp->e2di_nlink) == lcnt) { + if (linkup(idesc->id_number, (ino_t)0) == 0) + clri(idesc, "UNREF", 0); + } else { + pwarn( + "LINK COUNT %s", + (lfdir == idesc->id_number) ? lfname + : ((fs2h16(dp->e2di_mode) & IFMT) == IFDIR ? "DIR" : "FILE") + ); + pinode(idesc->id_number); + printf(" COUNT %d SHOULD BE %d", fs2h16(dp->e2di_nlink), fs2h16(dp->e2di_nlink) - lcnt); + if (preen) { + if (lcnt < 0) { + printf("\n"); + pfatal("LINK COUNT INCREASING"); + } + printf(" (ADJUSTED)\n"); + } + if (preen || reply("ADJUST") == 1) { + dp->e2di_nlink = h2fs16(fs2h16(dp->e2di_nlink) - lcnt); + inodirty(); + } + } } static int mkentry(struct inodesc *idesc) { - struct ext2fs_direct *dirp = idesc->id_dirp; - struct ext2fs_direct newent; - int newlen, oldlen; - - newent.e2d_type = 0; /* XXX gcc */ - newent.e2d_namlen = strlen(idesc->id_name); - if (sblock.e2fs.e2fs_rev > E2FS_REV0 && - (sblock.e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE)) - newent.e2d_type = inot2ext2dt(typemap[idesc->id_parent]); - newlen = EXT2FS_DIRSIZ(newent.e2d_namlen); - if (dirp->e2d_ino != 0) - oldlen = EXT2FS_DIRSIZ(dirp->e2d_namlen); - else - oldlen = 0; - if (fs2h16(dirp->e2d_reclen) - oldlen < newlen) - return (KEEPON); - newent.e2d_reclen = h2fs16(fs2h16(dirp->e2d_reclen) - oldlen); - dirp->e2d_reclen = h2fs16(oldlen); - dirp = (struct ext2fs_direct *)(((char *)dirp) + oldlen); - dirp->e2d_ino = h2fs32(idesc->id_parent); /* ino to be entered is in id_parent */ - dirp->e2d_reclen = newent.e2d_reclen; - dirp->e2d_namlen = newent.e2d_namlen; - dirp->e2d_type = newent.e2d_type; - memcpy(dirp->e2d_name, idesc->id_name, (size_t)(dirp->e2d_namlen)); - return (ALTERED|STOP); + struct ext2fs_direct *dirp = idesc->id_dirp; + struct ext2fs_direct newent; + int newlen, oldlen; + + newent.e2d_type = 0; /* XXX gcc */ + newent.e2d_namlen = strlen(idesc->id_name); + if (sblock.e2fs.e2fs_rev > E2FS_REV0 + && (sblock.e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE)) + newent.e2d_type = inot2ext2dt(typemap[idesc->id_parent]); + newlen = EXT2FS_DIRSIZ(newent.e2d_namlen); + if (dirp->e2d_ino != 0) + oldlen = EXT2FS_DIRSIZ(dirp->e2d_namlen); + else + oldlen = 0; + if (fs2h16(dirp->e2d_reclen) - oldlen < newlen) + return (KEEPON); + newent.e2d_reclen = h2fs16(fs2h16(dirp->e2d_reclen) - oldlen); + dirp->e2d_reclen = h2fs16(oldlen); + dirp = (struct ext2fs_direct *)(((char *)dirp) + oldlen); + dirp->e2d_ino = h2fs32(idesc->id_parent); /* ino to be entered is in id_parent */ + dirp->e2d_reclen = newent.e2d_reclen; + dirp->e2d_namlen = newent.e2d_namlen; + dirp->e2d_type = newent.e2d_type; + memcpy(dirp->e2d_name, idesc->id_name, (size_t)(dirp->e2d_namlen)); + return (ALTERED | STOP); } static int chgino(struct inodesc *idesc) { - struct ext2fs_direct *dirp = idesc->id_dirp; - u_int16_t namlen = dirp->e2d_namlen; - - if (strlen(idesc->id_name) != namlen || - strncmp(dirp->e2d_name, idesc->id_name, (int)namlen)) - return (KEEPON); - dirp->e2d_ino = h2fs32(idesc->id_parent); - if (sblock.e2fs.e2fs_rev > E2FS_REV0 && - (sblock.e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE)) - dirp->e2d_type = inot2ext2dt(typemap[idesc->id_parent]); - else - dirp->e2d_type = 0; - return (ALTERED|STOP); + struct ext2fs_direct *dirp = idesc->id_dirp; + u_int16_t namlen = dirp->e2d_namlen; + + if (strlen(idesc->id_name) != namlen || strncmp(dirp->e2d_name, idesc->id_name, (int)namlen)) + return (KEEPON); + dirp->e2d_ino = h2fs32(idesc->id_parent); + if (sblock.e2fs.e2fs_rev > E2FS_REV0 + && (sblock.e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE)) + dirp->e2d_type = inot2ext2dt(typemap[idesc->id_parent]); + else + dirp->e2d_type = 0; + return (ALTERED | STOP); } int linkup(ino_t orphan, ino_t parentdir) { - struct ext2fs_dinode *dp; - int lostdir; - ino_t oldlfdir; - struct inodesc idesc; - char tempname[BUFSIZ]; - - memset(&idesc, 0, sizeof(struct inodesc)); - dp = ginode(orphan); - lostdir = (fs2h16(dp->e2di_mode) & IFMT) == IFDIR; - pwarn("UNREF %s ", lostdir ? "DIR" : "FILE"); - pinode(orphan); - if (preen && inosize(dp) == 0) - return (0); - if (preen) - printf(" (RECONNECTED)\n"); - else - if (reply("RECONNECT") == 0) - return (0); - if (lfdir == 0) { - dp = ginode(EXT2_ROOTINO); - idesc.id_name = lfname; - idesc.id_type = DATA; - idesc.id_func = findino; - idesc.id_number = EXT2_ROOTINO; - if ((ckinode(dp, &idesc) & FOUND) != 0) { - lfdir = idesc.id_parent; - } else { - pwarn("NO lost+found DIRECTORY"); - if (preen || reply("CREATE")) { - lfdir = allocdir(EXT2_ROOTINO, (ino_t)0, lfmode); - if (lfdir != 0) { - if (makeentry(EXT2_ROOTINO, lfdir, lfname) != 0) { - if (preen) - printf(" (CREATED)\n"); - } else { - freedir(lfdir, EXT2_ROOTINO); - lfdir = 0; - if (preen) - printf("\n"); - } - } - } - } - if (lfdir == 0) { - pfatal("SORRY. CANNOT CREATE lost+found DIRECTORY"); - printf("\n\n"); - return (0); - } - } - dp = ginode(lfdir); - if ((fs2h16(dp->e2di_mode) & IFMT) != IFDIR) { - pfatal("lost+found IS NOT A DIRECTORY"); - if (reply("REALLOCATE") == 0) - return (0); - oldlfdir = lfdir; - if ((lfdir = allocdir(EXT2_ROOTINO, (ino_t)0, lfmode)) == 0) { - pfatal("SORRY. CANNOT CREATE lost+found DIRECTORY\n\n"); - return (0); - } - if ((changeino(EXT2_ROOTINO, lfname, lfdir) & ALTERED) == 0) { - pfatal("SORRY. CANNOT CREATE lost+found DIRECTORY\n\n"); - return (0); - } - inodirty(); - idesc.id_type = ADDR; - idesc.id_func = pass4check; - idesc.id_number = oldlfdir; - adjust(&idesc, lncntp[oldlfdir] + 1); - lncntp[oldlfdir] = 0; - dp = ginode(lfdir); - } - if (statemap[lfdir] != DFOUND) { - pfatal("SORRY. NO lost+found DIRECTORY\n\n"); - return (0); - } - (void)lftempname(tempname, orphan); - if (makeentry(lfdir, orphan, tempname) == 0) { - pfatal("SORRY. NO SPACE IN lost+found DIRECTORY"); - printf("\n\n"); - return (0); - } - lncntp[orphan]--; - if (lostdir) { - if ((changeino(orphan, "..", lfdir) & ALTERED) == 0 && - parentdir != (ino_t)-1) - (void)makeentry(orphan, lfdir, ".."); - dp = ginode(lfdir); - dp->e2di_nlink = h2fs16(fs2h16(dp->e2di_nlink) +1); - inodirty(); - lncntp[lfdir]++; - pwarn("DIR I=%llu CONNECTED. ", (unsigned long long)orphan); - if (parentdir != (ino_t)-1) - printf("PARENT WAS I=%llu\n", - (unsigned long long)parentdir); - if (preen == 0) - printf("\n"); - } - return (1); + struct ext2fs_dinode *dp; + int lostdir; + ino_t oldlfdir; + struct inodesc idesc; + char tempname[BUFSIZ]; + + memset(&idesc, 0, sizeof(struct inodesc)); + dp = ginode(orphan); + lostdir = (fs2h16(dp->e2di_mode) & IFMT) == IFDIR; + pwarn("UNREF %s ", lostdir ? "DIR" : "FILE"); + pinode(orphan); + if (preen && inosize(dp) == 0) + return (0); + if (preen) + printf(" (RECONNECTED)\n"); + else if (reply("RECONNECT") == 0) + return (0); + if (lfdir == 0) { + dp = ginode(EXT2_ROOTINO); + idesc.id_name = lfname; + idesc.id_type = DATA; + idesc.id_func = findino; + idesc.id_number = EXT2_ROOTINO; + if ((ckinode(dp, &idesc) & FOUND) != 0) { + lfdir = idesc.id_parent; + } else { + pwarn("NO lost+found DIRECTORY"); + if (preen || reply("CREATE")) { + lfdir = allocdir(EXT2_ROOTINO, (ino_t)0, lfmode); + if (lfdir != 0) { + if (makeentry(EXT2_ROOTINO, lfdir, lfname) != 0) { + if (preen) + printf(" (CREATED)\n"); + } else { + freedir(lfdir, EXT2_ROOTINO); + lfdir = 0; + if (preen) + printf("\n"); + } + } + } + } + if (lfdir == 0) { + pfatal("SORRY. CANNOT CREATE lost+found DIRECTORY"); + printf("\n\n"); + return (0); + } + } + dp = ginode(lfdir); + if ((fs2h16(dp->e2di_mode) & IFMT) != IFDIR) { + pfatal("lost+found IS NOT A DIRECTORY"); + if (reply("REALLOCATE") == 0) + return (0); + oldlfdir = lfdir; + if ((lfdir = allocdir(EXT2_ROOTINO, (ino_t)0, lfmode)) == 0) { + pfatal("SORRY. CANNOT CREATE lost+found DIRECTORY\n\n"); + return (0); + } + if ((changeino(EXT2_ROOTINO, lfname, lfdir) & ALTERED) == 0) { + pfatal("SORRY. CANNOT CREATE lost+found DIRECTORY\n\n"); + return (0); + } + inodirty(); + idesc.id_type = ADDR; + idesc.id_func = pass4check; + idesc.id_number = oldlfdir; + adjust(&idesc, lncntp[oldlfdir] + 1); + lncntp[oldlfdir] = 0; + dp = ginode(lfdir); + } + if (statemap[lfdir] != DFOUND) { + pfatal("SORRY. NO lost+found DIRECTORY\n\n"); + return (0); + } + (void)lftempname(tempname, orphan); + if (makeentry(lfdir, orphan, tempname) == 0) { + pfatal("SORRY. NO SPACE IN lost+found DIRECTORY"); + printf("\n\n"); + return (0); + } + lncntp[orphan]--; + if (lostdir) { + if ((changeino(orphan, "..", lfdir) & ALTERED) == 0 && parentdir != (ino_t)-1) + (void)makeentry(orphan, lfdir, ".."); + dp = ginode(lfdir); + dp->e2di_nlink = h2fs16(fs2h16(dp->e2di_nlink) + 1); + inodirty(); + lncntp[lfdir]++; + pwarn("DIR I=%llu CONNECTED. ", (unsigned long long)orphan); + if (parentdir != (ino_t)-1) + printf("PARENT WAS I=%llu\n", (unsigned long long)parentdir); + if (preen == 0) + printf("\n"); + } + return (1); } /* @@ -498,16 +485,16 @@ linkup(ino_t orphan, ino_t parentdir) int changeino(ino_t dir, const char *name, ino_t newnum) { - struct inodesc idesc; - - memset(&idesc, 0, sizeof(struct inodesc)); - idesc.id_type = DATA; - idesc.id_func = chgino; - idesc.id_number = dir; - idesc.id_fix = DONTKNOW; - idesc.id_name = name; - idesc.id_parent = newnum; /* new value for name */ - return (ckinode(ginode(dir), &idesc)); + struct inodesc idesc; + + memset(&idesc, 0, sizeof(struct inodesc)); + idesc.id_type = DATA; + idesc.id_func = chgino; + idesc.id_number = dir; + idesc.id_fix = DONTKNOW; + idesc.id_name = name; + idesc.id_parent = newnum; /* new value for name */ + return (ckinode(ginode(dir), &idesc)); } /* @@ -516,33 +503,32 @@ changeino(ino_t dir, const char *name, ino_t newnum) int makeentry(ino_t parent, ino_t ino, const char *name) { - struct ext2fs_dinode *dp; - struct inodesc idesc; - char pathbuf[MAXPATHLEN + 1]; - - if ((parent < EXT2_FIRSTINO && parent != EXT2_ROOTINO) - || parent >= maxino || - (ino < EXT2_FIRSTINO && ino < EXT2_ROOTINO) || ino >= maxino) - return (0); - memset(&idesc, 0, sizeof(struct inodesc)); - idesc.id_type = DATA; - idesc.id_func = mkentry; - idesc.id_number = parent; - idesc.id_parent = ino; /* this is the inode to enter */ - idesc.id_fix = DONTKNOW; - idesc.id_name = name; - dp = ginode(parent); - if (inosize(dp) % sblock.e2fs_bsize) { - inossize(dp, roundup(inosize(dp), sblock.e2fs_bsize)); - inodirty(); - } - if ((ckinode(dp, &idesc) & ALTERED) != 0) - return (1); - getpathname(pathbuf, sizeof(pathbuf), parent, parent); - dp = ginode(parent); - if (expanddir(dp, pathbuf) == 0) - return (0); - return (ckinode(dp, &idesc) & ALTERED); + struct ext2fs_dinode *dp; + struct inodesc idesc; + char pathbuf[MAXPATHLEN + 1]; + + if ((parent < EXT2_FIRSTINO && parent != EXT2_ROOTINO) || parent >= maxino + || (ino < EXT2_FIRSTINO && ino < EXT2_ROOTINO) || ino >= maxino) + return (0); + memset(&idesc, 0, sizeof(struct inodesc)); + idesc.id_type = DATA; + idesc.id_func = mkentry; + idesc.id_number = parent; + idesc.id_parent = ino; /* this is the inode to enter */ + idesc.id_fix = DONTKNOW; + idesc.id_name = name; + dp = ginode(parent); + if (inosize(dp) % sblock.e2fs_bsize) { + inossize(dp, roundup(inosize(dp), sblock.e2fs_bsize)); + inodirty(); + } + if ((ckinode(dp, &idesc) & ALTERED) != 0) + return (1); + getpathname(pathbuf, sizeof(pathbuf), parent, parent); + dp = ginode(parent); + if (expanddir(dp, pathbuf) == 0) + return (0); + return (ckinode(dp, &idesc) & ALTERED); } /* @@ -551,58 +537,55 @@ makeentry(ino_t parent, ino_t ino, const char *name) static int expanddir(struct ext2fs_dinode *dp, char *name) { - daddr_t lastbn, newblk; - struct bufarea *bp; - char *firstblk; - - lastbn = ext2_lblkno(&sblock, inosize(dp)); - if (lastbn >= EXT2FS_NDADDR - 1 || fs2h32(dp->e2di_blocks[lastbn]) == 0 || - inosize(dp) == 0) { - return (0); - } - if ((newblk = allocblk()) == 0) { - return (0); - } - dp->e2di_blocks[lastbn + 1] = dp->e2di_blocks[lastbn]; - dp->e2di_blocks[lastbn] = h2fs32(newblk); - inossize(dp, inosize(dp) + sblock.e2fs_bsize); - inosnblock(dp, inonblock(dp) + btodb(sblock.e2fs_bsize)); - bp = getdirblk(fs2h32(dp->e2di_blocks[lastbn + 1]), - sblock.e2fs_bsize); - if (bp->b_errs) - goto bad; - if ((firstblk = malloc(sblock.e2fs_bsize)) == NULL) - err(8, "cannot allocate first block"); - memcpy(firstblk, bp->b_un.b_buf, sblock.e2fs_bsize); - bp = getdirblk(newblk, sblock.e2fs_bsize); - if (bp->b_errs) { - free(firstblk); - goto bad; - } - memcpy(bp->b_un.b_buf, firstblk, sblock.e2fs_bsize); - free(firstblk); - dirty(bp); - bp = getdirblk(fs2h32(dp->e2di_blocks[lastbn + 1]), - sblock.e2fs_bsize); - if (bp->b_errs) - goto bad; - emptydir.dot_reclen = h2fs16(sblock.e2fs_bsize); - memcpy(bp->b_un.b_buf, &emptydir, sizeof emptydir); - pwarn("NO SPACE LEFT IN %s", name); - if (preen) - printf(" (EXPANDED)\n"); - else if (reply("EXPAND") == 0) - goto bad; - dirty(bp); - inodirty(); - return (1); + daddr_t lastbn, newblk; + struct bufarea *bp; + char *firstblk; + + lastbn = ext2_lblkno(&sblock, inosize(dp)); + if (lastbn >= EXT2FS_NDADDR - 1 || fs2h32(dp->e2di_blocks[lastbn]) == 0 || inosize(dp) == 0) { + return (0); + } + if ((newblk = allocblk()) == 0) { + return (0); + } + dp->e2di_blocks[lastbn + 1] = dp->e2di_blocks[lastbn]; + dp->e2di_blocks[lastbn] = h2fs32(newblk); + inossize(dp, inosize(dp) + sblock.e2fs_bsize); + inosnblock(dp, inonblock(dp) + btodb(sblock.e2fs_bsize)); + bp = getdirblk(fs2h32(dp->e2di_blocks[lastbn + 1]), sblock.e2fs_bsize); + if (bp->b_errs) + goto bad; + if ((firstblk = malloc(sblock.e2fs_bsize)) == NULL) + err(8, "cannot allocate first block"); + memcpy(firstblk, bp->b_un.b_buf, sblock.e2fs_bsize); + bp = getdirblk(newblk, sblock.e2fs_bsize); + if (bp->b_errs) { + free(firstblk); + goto bad; + } + memcpy(bp->b_un.b_buf, firstblk, sblock.e2fs_bsize); + free(firstblk); + dirty(bp); + bp = getdirblk(fs2h32(dp->e2di_blocks[lastbn + 1]), sblock.e2fs_bsize); + if (bp->b_errs) + goto bad; + emptydir.dot_reclen = h2fs16(sblock.e2fs_bsize); + memcpy(bp->b_un.b_buf, &emptydir, sizeof emptydir); + pwarn("NO SPACE LEFT IN %s", name); + if (preen) + printf(" (EXPANDED)\n"); + else if (reply("EXPAND") == 0) + goto bad; + dirty(bp); + inodirty(); + return (1); bad: - dp->e2di_blocks[lastbn] = dp->e2di_blocks[lastbn + 1]; - dp->e2di_blocks[lastbn + 1] = 0; - inossize(dp, inosize(dp) - sblock.e2fs_bsize); - inosnblock(dp, inonblock(dp) - btodb(sblock.e2fs_bsize)); - freeblk(newblk); - return (0); + dp->e2di_blocks[lastbn] = dp->e2di_blocks[lastbn + 1]; + dp->e2di_blocks[lastbn + 1] = 0; + inossize(dp, inosize(dp) - sblock.e2fs_bsize); + inosnblock(dp, inonblock(dp) - btodb(sblock.e2fs_bsize)); + freeblk(newblk); + return (0); } /* @@ -611,58 +594,58 @@ bad: int allocdir(ino_t parent, ino_t request, int mode) { - ino_t ino; - struct ext2fs_dinode *dp; - struct bufarea *bp; - struct ext2fs_dirtemplate *dirp; - - ino = allocino(request, IFDIR|mode); - dirhead.dot_reclen = h2fs16(12); /* XXX */ - dirhead.dotdot_reclen = h2fs16(sblock.e2fs_bsize - 12); /* XXX */ - dirhead.dot_namlen = 1; - if (sblock.e2fs.e2fs_rev > E2FS_REV0 && - (sblock.e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE)) - dirhead.dot_type = EXT2_FT_DIR; - else - dirhead.dot_type = 0; - dirhead.dotdot_namlen = 2; - if (sblock.e2fs.e2fs_rev > E2FS_REV0 && - (sblock.e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE)) - dirhead.dotdot_type = EXT2_FT_DIR; - else - dirhead.dotdot_type = 0; - dirp = &dirhead; - dirp->dot_ino = h2fs32(ino); - dirp->dotdot_ino = h2fs32(parent); - dp = ginode(ino); - bp = getdirblk(fs2h32(dp->e2di_blocks[0]), sblock.e2fs_bsize); - if (bp->b_errs) { - freeino(ino); - return (0); - } - memcpy(bp->b_un.b_buf, dirp, sizeof(struct ext2fs_dirtemplate)); - dirty(bp); - dp->e2di_nlink = h2fs16(2); - inodirty(); - if (ino == EXT2_ROOTINO) { - lncntp[ino] = fs2h16(dp->e2di_nlink); - cacheino(dp, ino); - return(ino); - } - if (statemap[parent] != DSTATE && statemap[parent] != DFOUND) { - freeino(ino); - return (0); - } - cacheino(dp, ino); - statemap[ino] = statemap[parent]; - if (statemap[ino] == DSTATE) { - lncntp[ino] = fs2h16(dp->e2di_nlink); - lncntp[parent]++; - } - dp = ginode(parent); - dp->e2di_nlink = h2fs16(fs2h16(dp->e2di_nlink) + 1); - inodirty(); - return (ino); + ino_t ino; + struct ext2fs_dinode *dp; + struct bufarea *bp; + struct ext2fs_dirtemplate *dirp; + + ino = allocino(request, IFDIR | mode); + dirhead.dot_reclen = h2fs16(12); /* XXX */ + dirhead.dotdot_reclen = h2fs16(sblock.e2fs_bsize - 12); /* XXX */ + dirhead.dot_namlen = 1; + if (sblock.e2fs.e2fs_rev > E2FS_REV0 + && (sblock.e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE)) + dirhead.dot_type = EXT2_FT_DIR; + else + dirhead.dot_type = 0; + dirhead.dotdot_namlen = 2; + if (sblock.e2fs.e2fs_rev > E2FS_REV0 + && (sblock.e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE)) + dirhead.dotdot_type = EXT2_FT_DIR; + else + dirhead.dotdot_type = 0; + dirp = &dirhead; + dirp->dot_ino = h2fs32(ino); + dirp->dotdot_ino = h2fs32(parent); + dp = ginode(ino); + bp = getdirblk(fs2h32(dp->e2di_blocks[0]), sblock.e2fs_bsize); + if (bp->b_errs) { + freeino(ino); + return (0); + } + memcpy(bp->b_un.b_buf, dirp, sizeof(struct ext2fs_dirtemplate)); + dirty(bp); + dp->e2di_nlink = h2fs16(2); + inodirty(); + if (ino == EXT2_ROOTINO) { + lncntp[ino] = fs2h16(dp->e2di_nlink); + cacheino(dp, ino); + return (ino); + } + if (statemap[parent] != DSTATE && statemap[parent] != DFOUND) { + freeino(ino); + return (0); + } + cacheino(dp, ino); + statemap[ino] = statemap[parent]; + if (statemap[ino] == DSTATE) { + lncntp[ino] = fs2h16(dp->e2di_nlink); + lncntp[parent]++; + } + dp = ginode(parent); + dp->e2di_nlink = h2fs16(fs2h16(dp->e2di_nlink) + 1); + inodirty(); + return (ino); } /* @@ -671,14 +654,14 @@ allocdir(ino_t parent, ino_t request, int mode) static void freedir(ino_t ino, ino_t parent) { - struct ext2fs_dinode *dp; - - if (ino != parent) { - dp = ginode(parent); - dp->e2di_nlink = h2fs16(fs2h16(dp->e2di_nlink) - 1); - inodirty(); - } - freeino(ino); + struct ext2fs_dinode *dp; + + if (ino != parent) { + dp = ginode(parent); + dp->e2di_nlink = h2fs16(fs2h16(dp->e2di_nlink) - 1); + inodirty(); + } + freeino(ino); } /* @@ -687,22 +670,22 @@ freedir(ino_t ino, ino_t parent) static int lftempname(char *bufp, ino_t ino) { - ino_t in; - char *cp; - int namlen; - - cp = bufp + 2; - for (in = maxino; in > 0; in /= 10) - cp++; - *--cp = 0; - namlen = cp - bufp; - in = ino; - while (cp > bufp) { - *--cp = (in % 10) + '0'; - in /= 10; - } - *cp = '#'; - return (namlen); + ino_t in; + char *cp; + int namlen; + + cp = bufp + 2; + for (in = maxino; in > 0; in /= 10) + cp++; + *--cp = 0; + namlen = cp - bufp; + in = ino; + while (cp > bufp) { + *--cp = (in % 10) + '0'; + in /= 10; + } + *cp = '#'; + return (namlen); } /* @@ -712,9 +695,8 @@ lftempname(char *bufp, ino_t ino) static struct bufarea * getdirblk(daddr_t blkno, long size) { - - if (pdirbp != 0) - pdirbp->b_flags &= ~B_INUSE; - pdirbp = getdatablk(blkno, size); - return (pdirbp); + if (pdirbp != 0) + pdirbp->b_flags &= ~B_INUSE; + pdirbp = getdatablk(blkno, size); + return (pdirbp); } diff --git a/cmd/extra/fsck.ext4/exitvalues.h b/cmd/extra/fsck.ext4/exitvalues.h @@ -28,8 +28,8 @@ * POSSIBILITY OF SUCH DAMAGE. */ -#define FSCK_EXIT_OK 0 -#define FSCK_EXIT_UNRESOLVED 4 -#define FSCK_EXIT_CHECK_FAILED 8 -#define FSCK_EXIT_USAGE 16 -#define FSCK_EXIT_SIGNALLED 32 +#define FSCK_EXIT_OK 0 +#define FSCK_EXIT_UNRESOLVED 4 +#define FSCK_EXIT_CHECK_FAILED 8 +#define FSCK_EXIT_USAGE 16 +#define FSCK_EXIT_SIGNALLED 32 diff --git a/cmd/extra/fsck.ext4/ext2fs_bswap.c b/cmd/extra/fsck.ext4/ext2fs_bswap.c @@ -42,97 +42,96 @@ __KERNEL_RCSID(0, "$NetBSD: ext2fs_bswap.c,v 1.26 2025/12/24 15:06:59 nia Exp $" void e2fs_sb_bswap(struct ext2fs *old, struct ext2fs *new) { - - /* preserve unused fields */ - memcpy(new, old, sizeof(struct ext2fs)); - new->e2fs_icount = bswap32(old->e2fs_icount); - new->e2fs_bcount = bswap32(old->e2fs_bcount); - new->e2fs_rbcount = bswap32(old->e2fs_rbcount); - new->e2fs_fbcount = bswap32(old->e2fs_fbcount); - new->e2fs_ficount = bswap32(old->e2fs_ficount); - new->e2fs_first_dblock = bswap32(old->e2fs_first_dblock); - new->e2fs_log_bsize = bswap32(old->e2fs_log_bsize); - new->e2fs_fsize = bswap32(old->e2fs_fsize); - new->e2fs_bpg = bswap32(old->e2fs_bpg); - new->e2fs_fpg = bswap32(old->e2fs_fpg); - new->e2fs_ipg = bswap32(old->e2fs_ipg); - new->e2fs_mtime = bswap32(old->e2fs_mtime); - new->e2fs_wtime = bswap32(old->e2fs_wtime); - new->e2fs_mnt_count = bswap16(old->e2fs_mnt_count); - new->e2fs_max_mnt_count = bswap16(old->e2fs_max_mnt_count); - new->e2fs_magic = bswap16(old->e2fs_magic); - new->e2fs_state = bswap16(old->e2fs_state); - new->e2fs_beh = bswap16(old->e2fs_beh); - new->e2fs_minrev = bswap16(old->e2fs_minrev); - new->e2fs_lastfsck = bswap32(old->e2fs_lastfsck); - new->e2fs_fsckintv = bswap32(old->e2fs_fsckintv); - new->e2fs_creator = bswap32(old->e2fs_creator); - new->e2fs_rev = bswap32(old->e2fs_rev); - new->e2fs_ruid = bswap16(old->e2fs_ruid); - new->e2fs_rgid = bswap16(old->e2fs_rgid); - new->e2fs_first_ino = bswap32(old->e2fs_first_ino); - new->e2fs_inode_size = bswap16(old->e2fs_inode_size); - new->e2fs_block_group_nr = bswap16(old->e2fs_block_group_nr); - new->e2fs_features_compat = bswap32(old->e2fs_features_compat); - new->e2fs_features_incompat = bswap32(old->e2fs_features_incompat); - new->e2fs_features_rocompat = bswap32(old->e2fs_features_rocompat); - new->e2fs_algo = bswap32(old->e2fs_algo); - new->e2fs_reserved_ngdb = bswap16(old->e2fs_reserved_ngdb); - new->e4fs_want_extra_isize = bswap16(old->e4fs_want_extra_isize); + /* preserve unused fields */ + memcpy(new, old, sizeof(struct ext2fs)); + new->e2fs_icount = bswap32(old->e2fs_icount); + new->e2fs_bcount = bswap32(old->e2fs_bcount); + new->e2fs_rbcount = bswap32(old->e2fs_rbcount); + new->e2fs_fbcount = bswap32(old->e2fs_fbcount); + new->e2fs_ficount = bswap32(old->e2fs_ficount); + new->e2fs_first_dblock = bswap32(old->e2fs_first_dblock); + new->e2fs_log_bsize = bswap32(old->e2fs_log_bsize); + new->e2fs_fsize = bswap32(old->e2fs_fsize); + new->e2fs_bpg = bswap32(old->e2fs_bpg); + new->e2fs_fpg = bswap32(old->e2fs_fpg); + new->e2fs_ipg = bswap32(old->e2fs_ipg); + new->e2fs_mtime = bswap32(old->e2fs_mtime); + new->e2fs_wtime = bswap32(old->e2fs_wtime); + new->e2fs_mnt_count = bswap16(old->e2fs_mnt_count); + new->e2fs_max_mnt_count = bswap16(old->e2fs_max_mnt_count); + new->e2fs_magic = bswap16(old->e2fs_magic); + new->e2fs_state = bswap16(old->e2fs_state); + new->e2fs_beh = bswap16(old->e2fs_beh); + new->e2fs_minrev = bswap16(old->e2fs_minrev); + new->e2fs_lastfsck = bswap32(old->e2fs_lastfsck); + new->e2fs_fsckintv = bswap32(old->e2fs_fsckintv); + new->e2fs_creator = bswap32(old->e2fs_creator); + new->e2fs_rev = bswap32(old->e2fs_rev); + new->e2fs_ruid = bswap16(old->e2fs_ruid); + new->e2fs_rgid = bswap16(old->e2fs_rgid); + new->e2fs_first_ino = bswap32(old->e2fs_first_ino); + new->e2fs_inode_size = bswap16(old->e2fs_inode_size); + new->e2fs_block_group_nr = bswap16(old->e2fs_block_group_nr); + new->e2fs_features_compat = bswap32(old->e2fs_features_compat); + new->e2fs_features_incompat = bswap32(old->e2fs_features_incompat); + new->e2fs_features_rocompat = bswap32(old->e2fs_features_rocompat); + new->e2fs_algo = bswap32(old->e2fs_algo); + new->e2fs_reserved_ngdb = bswap16(old->e2fs_reserved_ngdb); + new->e4fs_want_extra_isize = bswap16(old->e4fs_want_extra_isize); } void e2fs_i_bswap(struct ext2fs_dinode *old, struct ext2fs_dinode *new, size_t isize) { - /* preserve non-swapped and unused fields */ - memcpy(new, old, isize); + /* preserve non-swapped and unused fields */ + memcpy(new, old, isize); - /* swap what needs to be swapped */ - new->e2di_mode = bswap16(old->e2di_mode); - new->e2di_uid = bswap16(old->e2di_uid); - new->e2di_gid = bswap16(old->e2di_gid); - new->e2di_nlink = bswap16(old->e2di_nlink); - new->e2di_size = bswap32(old->e2di_size); - new->e2di_atime = bswap32(old->e2di_atime); - new->e2di_ctime = bswap32(old->e2di_ctime); - new->e2di_mtime = bswap32(old->e2di_mtime); - new->e2di_dtime = bswap32(old->e2di_dtime); - new->e2di_nblock = bswap32(old->e2di_nblock); - new->e2di_flags = bswap32(old->e2di_flags); - new->e2di_version = bswap32(old->e2di_version); - new->e2di_gen = bswap32(old->e2di_gen); - new->e2di_facl = bswap32(old->e2di_facl); - new->e2di_size_high = bswap32(old->e2di_size_high); - new->e2di_nblock_high = bswap16(old->e2di_nblock_high); - new->e2di_facl_high = bswap16(old->e2di_facl_high); - new->e2di_uid_high = bswap16(old->e2di_uid_high); - new->e2di_gid_high = bswap16(old->e2di_gid_high); - new->e2di_checksum_low = bswap16(old->e2di_checksum_low); + /* swap what needs to be swapped */ + new->e2di_mode = bswap16(old->e2di_mode); + new->e2di_uid = bswap16(old->e2di_uid); + new->e2di_gid = bswap16(old->e2di_gid); + new->e2di_nlink = bswap16(old->e2di_nlink); + new->e2di_size = bswap32(old->e2di_size); + new->e2di_atime = bswap32(old->e2di_atime); + new->e2di_ctime = bswap32(old->e2di_ctime); + new->e2di_mtime = bswap32(old->e2di_mtime); + new->e2di_dtime = bswap32(old->e2di_dtime); + new->e2di_nblock = bswap32(old->e2di_nblock); + new->e2di_flags = bswap32(old->e2di_flags); + new->e2di_version = bswap32(old->e2di_version); + new->e2di_gen = bswap32(old->e2di_gen); + new->e2di_facl = bswap32(old->e2di_facl); + new->e2di_size_high = bswap32(old->e2di_size_high); + new->e2di_nblock_high = bswap16(old->e2di_nblock_high); + new->e2di_facl_high = bswap16(old->e2di_facl_high); + new->e2di_uid_high = bswap16(old->e2di_uid_high); + new->e2di_gid_high = bswap16(old->e2di_gid_high); + new->e2di_checksum_low = bswap16(old->e2di_checksum_low); - /* - * Following fields are only supported for inode sizes bigger - * than the old ext2 one - */ - if (isize == EXT2_REV0_DINODE_SIZE) - return; + /* + * Following fields are only supported for inode sizes bigger + * than the old ext2 one + */ + if (isize == EXT2_REV0_DINODE_SIZE) + return; - new->e2di_extra_isize = bswap16(old->e2di_extra_isize); - new->e2di_checksum_high = bswap16(old->e2di_checksum_high); + new->e2di_extra_isize = bswap16(old->e2di_extra_isize); + new->e2di_checksum_high = bswap16(old->e2di_checksum_high); - /* Following fields are ext4, might not be actually present */ - if (EXT2_DINODE_FITS(new, e2di_ctime_extra, isize)) - new->e2di_ctime_extra = bswap32(old->e2di_ctime_extra); - if (EXT2_DINODE_FITS(new, e2di_mtime_extra, isize)) - new->e2di_mtime_extra = bswap32(old->e2di_mtime_extra); - if (EXT2_DINODE_FITS(new, e2di_atime_extra, isize)) - new->e2di_atime_extra = bswap32(old->e2di_atime_extra); - if (EXT2_DINODE_FITS(new, e2di_crtime, isize)) - new->e2di_crtime = bswap32(old->e2di_crtime); - if (EXT2_DINODE_FITS(new, e2di_crtime_extra, isize)) - new->e2di_crtime_extra = bswap32(old->e2di_crtime_extra); - if (EXT2_DINODE_FITS(new, e2di_version_high, isize)) - new->e2di_version_high = bswap32(old->e2di_version_high); - if (EXT2_DINODE_FITS(new, e2di_projid, isize)) - new->e2di_projid = bswap32(old->e2di_projid); + /* Following fields are ext4, might not be actually present */ + if (EXT2_DINODE_FITS(new, e2di_ctime_extra, isize)) + new->e2di_ctime_extra = bswap32(old->e2di_ctime_extra); + if (EXT2_DINODE_FITS(new, e2di_mtime_extra, isize)) + new->e2di_mtime_extra = bswap32(old->e2di_mtime_extra); + if (EXT2_DINODE_FITS(new, e2di_atime_extra, isize)) + new->e2di_atime_extra = bswap32(old->e2di_atime_extra); + if (EXT2_DINODE_FITS(new, e2di_crtime, isize)) + new->e2di_crtime = bswap32(old->e2di_crtime); + if (EXT2_DINODE_FITS(new, e2di_crtime_extra, isize)) + new->e2di_crtime_extra = bswap32(old->e2di_crtime_extra); + if (EXT2_DINODE_FITS(new, e2di_version_high, isize)) + new->e2di_version_high = bswap32(old->e2di_version_high); + if (EXT2_DINODE_FITS(new, e2di_projid, isize)) + new->e2di_projid = bswap32(old->e2di_projid); } #endif diff --git a/cmd/extra/fsck.ext4/extern.h b/cmd/extra/fsck.ext4/extern.h @@ -25,51 +25,51 @@ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -void adjust(struct inodesc *, short); -int allocblk(void); -int allocdir(ino_t, ino_t, int); -void blkerror(ino_t, const char *, daddr_t); -int bread(int, char *, daddr_t, long); -void bufinit(void); -void bwrite(int, char *, daddr_t, long); -void cacheino(struct ext2fs_dinode *, ino_t); -int changeino(ino_t, const char *, ino_t); -int chkrange(daddr_t, int); -void ckfini(int); -int ckinode(struct ext2fs_dinode *, struct inodesc *); -void clri(struct inodesc *, const char *, int); -int dircheck(struct inodesc *, struct ext2fs_direct *); -void direrror(ino_t, const char *); -int dirscan(struct inodesc *); -int dofix(struct inodesc *, const char *); -void fileerror(ino_t, ino_t, const char *); -int findino(struct inodesc *); -int findname(struct inodesc *); -void flush(int, struct bufarea *); -void freeblk(daddr_t); -void freeino(ino_t); -void freeinodebuf(void); -int ftypeok(struct ext2fs_dinode *); -void getpathname(char *, size_t, ino_t, ino_t); -void inocleanup(void); -void inodirty(void); -u_int64_t inosize(struct ext2fs_dinode *); -void inossize(struct ext2fs_dinode *, u_int64_t); -int linkup(ino_t, ino_t); -int makeentry(ino_t, ino_t, const char *); -void pass1(void); -void pass1b(void); -void pass2(void); -void pass3(void); -void pass4(void); -int pass1check(struct inodesc *); -int pass4check(struct inodesc *); -void pass5(void); -void pinode(ino_t); -void propagate(void); -int reply(const char *); -void resetinodebuf(void); -int setup(const char *); -struct ext2fs_dinode * getnextinode(ino_t); -uint64_t inonblock(struct ext2fs_dinode *); -void inosnblock(struct ext2fs_dinode *, uint64_t); +void adjust(struct inodesc *, short); +int allocblk(void); +int allocdir(ino_t, ino_t, int); +void blkerror(ino_t, const char *, daddr_t); +int bread(int, char *, daddr_t, long); +void bufinit(void); +void bwrite(int, char *, daddr_t, long); +void cacheino(struct ext2fs_dinode *, ino_t); +int changeino(ino_t, const char *, ino_t); +int chkrange(daddr_t, int); +void ckfini(int); +int ckinode(struct ext2fs_dinode *, struct inodesc *); +void clri(struct inodesc *, const char *, int); +int dircheck(struct inodesc *, struct ext2fs_direct *); +void direrror(ino_t, const char *); +int dirscan(struct inodesc *); +int dofix(struct inodesc *, const char *); +void fileerror(ino_t, ino_t, const char *); +int findino(struct inodesc *); +int findname(struct inodesc *); +void flush(int, struct bufarea *); +void freeblk(daddr_t); +void freeino(ino_t); +void freeinodebuf(void); +int ftypeok(struct ext2fs_dinode *); +void getpathname(char *, size_t, ino_t, ino_t); +void inocleanup(void); +void inodirty(void); +u_int64_t inosize(struct ext2fs_dinode *); +void inossize(struct ext2fs_dinode *, u_int64_t); +int linkup(ino_t, ino_t); +int makeentry(ino_t, ino_t, const char *); +void pass1(void); +void pass1b(void); +void pass2(void); +void pass3(void); +void pass4(void); +int pass1check(struct inodesc *); +int pass4check(struct inodesc *); +void pass5(void); +void pinode(ino_t); +void propagate(void); +int reply(const char *); +void resetinodebuf(void); +int setup(const char *); +struct ext2fs_dinode *getnextinode(ino_t); +uint64_t inonblock(struct ext2fs_dinode *); +void inosnblock(struct ext2fs_dinode *, uint64_t); diff --git a/cmd/extra/fsck.ext4/fsck.h b/cmd/extra/fsck.ext4/fsck.h @@ -57,93 +57,95 @@ * @(#)fsck.h 8.1 (Berkeley) 6/5/93 */ -#define MAXDUP 10 /* limit on dup blks (per inode) */ -#define MAXBAD 10 /* limit on bad blks (per inode) */ -#define MAXBUFSPACE 80*1024 /* maximum space to allocate to buffers */ -#define INOBUFSIZE 128*1024 /* size of buffer to read inodes in pass1 */ +#define MAXDUP 10 /* limit on dup blks (per inode) */ +#define MAXBAD 10 /* limit on bad blks (per inode) */ +#define MAXBUFSPACE 80 * 1024 /* maximum space to allocate to buffers */ +#define INOBUFSIZE 128 * 1024 /* size of buffer to read inodes in pass1 */ #ifndef BUFSIZ #define BUFSIZ 1024 #endif -#define USTATE 01 /* inode not allocated */ -#define FSTATE 02 /* inode is file */ -#define DSTATE 03 /* inode is directory */ -#define DFOUND 04 /* directory found during descent */ -#define DCLEAR 05 /* directory is to be cleared */ -#define FCLEAR 06 /* file is to be cleared */ +#define USTATE 01 /* inode not allocated */ +#define FSTATE 02 /* inode is file */ +#define DSTATE 03 /* inode is directory */ +#define DFOUND 04 /* directory found during descent */ +#define DCLEAR 05 /* directory is to be cleared */ +#define FCLEAR 06 /* file is to be cleared */ /* * buffer cache structure. */ struct bufarea { - struct bufarea *b_next; /* free list queue */ - struct bufarea *b_prev; /* free list queue */ - daddr_t b_bno; - int b_size; - int b_errs; - int b_flags; - union { - char *b_buf; /* buffer space */ - /* XXX ondisk32 */ - int32_t *b_indir; /* indirect block */ - struct ext2fs *b_fs; /* super block */ - struct ext2_gd *b_cgd; /* cylinder group descriptor */ - struct ext2fs_dinode *b_dinode; /* inode block */ - } b_un; - char b_dirty; + struct bufarea *b_next; /* free list queue */ + struct bufarea *b_prev; /* free list queue */ + daddr_t b_bno; + int b_size; + int b_errs; + int b_flags; + union { + char *b_buf; /* buffer space */ + /* XXX ondisk32 */ + int32_t *b_indir; /* indirect block */ + struct ext2fs *b_fs; /* super block */ + struct ext2_gd *b_cgd; /* cylinder group descriptor */ + struct ext2fs_dinode *b_dinode; /* inode block */ + } b_un; + char b_dirty; }; -#define B_INUSE 1 +#define B_INUSE 1 -#define MINBUFS 5 /* minimum number of buffers required */ -extern struct bufarea bufhead; /* head of list of other blks in filesys */ -extern struct bufarea sblk; /* file system superblock */ -extern struct bufarea asblk; /* first alternate superblock */ -extern struct bufarea *pdirbp; /* current directory contents */ -extern struct bufarea *pbp; /* current inode block */ +#define MINBUFS 5 /* minimum number of buffers required */ +extern struct bufarea bufhead; /* head of list of other blks in filesys */ +extern struct bufarea sblk; /* file system superblock */ +extern struct bufarea asblk; /* first alternate superblock */ +extern struct bufarea *pdirbp; /* current directory contents */ +extern struct bufarea *pbp; /* current inode block */ extern struct bufarea *getdatablk(daddr_t, long); extern struct m_ext2fs sblock; -#define dirty(bp) (bp)->b_dirty = 1 -#define initbarea(bp) \ - (bp)->b_dirty = 0; \ - (bp)->b_bno = (daddr_t)-1; \ - (bp)->b_flags = 0; +#define dirty(bp) (bp)->b_dirty = 1 +#define initbarea(bp) \ + (bp)->b_dirty = 0; \ + (bp)->b_bno = (daddr_t) - 1; \ + (bp)->b_flags = 0; -#define sbdirty() copyback_sb(&sblk); sblk.b_dirty = 1 +#define sbdirty() \ + copyback_sb(&sblk); \ + sblk.b_dirty = 1 -enum fixstate {DONTKNOW, NOFIX, FIX, IGNORE}; +enum fixstate { DONTKNOW, NOFIX, FIX, IGNORE }; struct inodesc { - enum fixstate id_fix; /* policy on fixing errors */ - int (*id_func) /* function to be applied to blocks of inode */ - (struct inodesc *); - ino_t id_number; /* inode number described */ - ino_t id_parent; /* for DATA nodes, their parent */ - daddr_t id_blkno; /* current block number being examined */ - int id_numfrags; /* number of frags contained in block */ - quad_t id_filesize; /* for DATA nodes, the size of the directory */ - int id_loc; /* for DATA nodes, current location in dir */ - int id_entryno; /* for DATA nodes, current entry number */ - struct ext2fs_direct *id_dirp; /* for DATA nodes, ptr to current entry */ - const char *id_name; /* for DATA nodes, name to find or enter */ - char id_type; /* type of descriptor, DATA or ADDR */ + enum fixstate id_fix; /* policy on fixing errors */ + int(*id_func) /* function to be applied to blocks of inode */ + (struct inodesc *); + ino_t id_number; /* inode number described */ + ino_t id_parent; /* for DATA nodes, their parent */ + daddr_t id_blkno; /* current block number being examined */ + int id_numfrags; /* number of frags contained in block */ + quad_t id_filesize; /* for DATA nodes, the size of the directory */ + int id_loc; /* for DATA nodes, current location in dir */ + int id_entryno; /* for DATA nodes, current entry number */ + struct ext2fs_direct *id_dirp; /* for DATA nodes, ptr to current entry */ + const char *id_name; /* for DATA nodes, name to find or enter */ + char id_type; /* type of descriptor, DATA or ADDR */ }; /* file types */ -#define DATA 1 -#define ADDR 2 +#define DATA 1 +#define ADDR 2 /* * Linked list of duplicate blocks. - * + * * The list is composed of two parts. The first part of the * list (from duplist through the node pointed to by muldup) - * contains a single copy of each duplicate block that has been + * contains a single copy of each duplicate block that has been * found. The second part of the list (from muldup to the end) * contains duplicate blocks that have been found more than once. * To check if a block has been found as a duplicate it is only - * necessary to search from duplist through muldup. To find the + * necessary to search from duplist through muldup. To find the * total number of times that a block has been found as a duplicate * the entire list must be searched for occurrences of the block * in question. The following diagram shows a sample list where @@ -156,94 +158,92 @@ struct inodesc { * duplist muldup */ struct dups { - struct dups *next; - daddr_t dup; + struct dups *next; + daddr_t dup; }; -extern struct dups *duplist; /* head of dup list */ -extern struct dups *muldup; /* end of unique duplicate dup block numbers */ +extern struct dups *duplist; /* head of dup list */ +extern struct dups *muldup; /* end of unique duplicate dup block numbers */ /* * Linked list of inodes with zero link counts. */ struct zlncnt { - struct zlncnt *next; - ino_t zlncnt; + struct zlncnt *next; + ino_t zlncnt; }; -extern struct zlncnt *zlnhead; /* head of zero link count list */ +extern struct zlncnt *zlnhead; /* head of zero link count list */ /* * Inode cache data structures. */ extern struct inoinfo { - struct inoinfo *i_nexthash; /* next entry in hash chain */ - struct inoinfo *i_child, *i_sibling, *i_parentp; - ino_t i_number; /* inode number of this entry */ - ino_t i_parent; /* inode number of parent */ - ino_t i_dotdot; /* inode number of `..' */ - u_int64_t i_isize; /* size of inode */ - u_int i_numblks; /* size of block array in bytes */ - /* XXX ondisk32 */ - int32_t i_blks[1]; /* actually longer */ -} **inphead, **inpsort; + struct inoinfo *i_nexthash; /* next entry in hash chain */ + struct inoinfo *i_child, *i_sibling, *i_parentp; + ino_t i_number; /* inode number of this entry */ + ino_t i_parent; /* inode number of parent */ + ino_t i_dotdot; /* inode number of `..' */ + u_int64_t i_isize; /* size of inode */ + u_int i_numblks; /* size of block array in bytes */ + /* XXX ondisk32 */ + int32_t i_blks[1]; /* actually longer */ +} **inphead, **inpsort; extern long numdirs, listmax, inplast; -extern long dev_bsize; /* computed value of DEV_BSIZE */ -extern long secsize; /* actual disk sector size */ -extern char nflag; /* assume a no response */ -extern char yflag; /* assume a yes response */ -extern int bflag; /* location of alternate super block */ -extern int Uflag; /* resolve user names */ -extern int debug; /* output debugging info */ -extern int preen; /* just fix normal inconsistencies */ -extern char havesb; /* superblock has been read */ -extern char skipclean; /* skip clean file systems if preening */ -extern int fsmodified; /* 1 => write done to file system */ -extern int fsreadfd; /* file descriptor for reading file system */ -extern int fswritefd; /* file descriptor for writing file system */ -extern int rerun; /* rerun fsck. Only used in non-preen mode */ - -extern daddr_t maxfsblock; /* number of blocks in the file system */ -extern char *blockmap; /* ptr to primary blk allocation map */ -extern ino_t maxino; /* number of inodes in file system */ -extern ino_t lastino; /* last inode in use */ -extern char *statemap; /* ptr to inode state table */ -extern u_char *typemap; /* ptr to inode type table */ -extern int16_t *lncntp; /* ptr to link count table */ - -extern ino_t lfdir; /* lost & found directory inode number */ -extern const char *lfname; /* lost & found directory name */ -extern int lfmode; /* lost & found directory creation mode */ - -extern daddr_t n_blks; /* number of blocks in use */ -extern daddr_t n_files; /* number of files in use */ - -#define clearinode(dp) (*(dp) = zino) -extern struct ext2fs_dinode zino; - -#define setbmap(blkno) setbit(blockmap, blkno) -#define testbmap(blkno) isset(blockmap, blkno) -#define clrbmap(blkno) clrbit(blockmap, blkno) - -#define STOP 0x01 -#define SKIP 0x02 -#define KEEPON 0x04 -#define ALTERED 0x08 -#define FOUND 0x10 +extern long dev_bsize; /* computed value of DEV_BSIZE */ +extern long secsize; /* actual disk sector size */ +extern char nflag; /* assume a no response */ +extern char yflag; /* assume a yes response */ +extern int bflag; /* location of alternate super block */ +extern int Uflag; /* resolve user names */ +extern int debug; /* output debugging info */ +extern int preen; /* just fix normal inconsistencies */ +extern char havesb; /* superblock has been read */ +extern char skipclean; /* skip clean file systems if preening */ +extern int fsmodified; /* 1 => write done to file system */ +extern int fsreadfd; /* file descriptor for reading file system */ +extern int fswritefd; /* file descriptor for writing file system */ +extern int rerun; /* rerun fsck. Only used in non-preen mode */ + +extern daddr_t maxfsblock; /* number of blocks in the file system */ +extern char *blockmap; /* ptr to primary blk allocation map */ +extern ino_t maxino; /* number of inodes in file system */ +extern ino_t lastino; /* last inode in use */ +extern char *statemap; /* ptr to inode state table */ +extern u_char *typemap; /* ptr to inode type table */ +extern int16_t *lncntp; /* ptr to link count table */ + +extern ino_t lfdir; /* lost & found directory inode number */ +extern const char *lfname; /* lost & found directory name */ +extern int lfmode; /* lost & found directory creation mode */ + +extern daddr_t n_blks; /* number of blocks in use */ +extern daddr_t n_files; /* number of files in use */ + +#define clearinode(dp) (*(dp) = zino) +extern struct ext2fs_dinode zino; + +#define setbmap(blkno) setbit(blockmap, blkno) +#define testbmap(blkno) isset(blockmap, blkno) +#define clrbmap(blkno) clrbit(blockmap, blkno) + +#define STOP 0x01 +#define SKIP 0x02 +#define KEEPON 0x04 +#define ALTERED 0x08 +#define FOUND 0x10 /* * Kernel support for features doesn't imply fsck support */ #define EXT2F_COMPAT_SUPP_FSCK (EXT2F_COMPAT_HASJOURNAL | EXT2F_COMPAT_EXTATTR) -#define EXT2F_ROCOMPAT_SUPP_FSCK (EXT2F_ROCOMPAT_SPARSESUPER \ - | EXT2F_ROCOMPAT_LARGEFILE \ - | EXT2F_ROCOMPAT_EXTRA_ISIZE | EXT2F_ROCOMPAT_HUGE_FILE \ - ) -#define EXT2F_INCOMPAT_SUPP_FSCK (EXT2F_INCOMPAT_FTYPE \ - ) +#define EXT2F_ROCOMPAT_SUPP_FSCK \ + (EXT2F_ROCOMPAT_SPARSESUPER | EXT2F_ROCOMPAT_LARGEFILE | EXT2F_ROCOMPAT_EXTRA_ISIZE \ + | EXT2F_ROCOMPAT_HUGE_FILE) +#define EXT2F_INCOMPAT_SUPP_FSCK (EXT2F_INCOMPAT_FTYPE) struct ext2fs_dinode *ginode(ino_t); -struct inoinfo *getinoinfo(ino_t); -void getblk(struct bufarea *, daddr_t, long); -ino_t allocino(ino_t, int); -void copyback_sb(struct bufarea*); -daddr_t cgoverhead(int); /* overhead per cg */ +struct inoinfo *getinoinfo(ino_t); +void getblk(struct bufarea *, daddr_t, long); +ino_t allocino(ino_t, int); +void copyback_sb(struct bufarea *); +daddr_t cgoverhead(int); /* overhead per cg */ diff --git a/cmd/extra/fsck.ext4/fsutil.c b/cmd/extra/fsck.ext4/fsutil.c @@ -68,139 +68,133 @@ volatile sig_atomic_t returntosingle; void (*ckfinish)(int); -static const char *dev = NULL; -static int hot = 0; -static int preen = 0; -int quiet; /* don't report clean filesystems */ -#define F_ERROR 0x80000000 +static const char *dev = NULL; +static int hot = 0; +static int preen = 0; +int quiet; /* don't report clean filesystems */ +#define F_ERROR 0x80000000 void setcdevname(const char *cd, int pr) { - - dev = cd; - preen = pr; + dev = cd; + preen = pr; } const char * cdevname(void) { - - return dev; + return dev; } int hotroot(void) { - - return hot; + return hot; } /*VARARGS*/ void errexit(const char *fmt, ...) { - va_list ap; + va_list ap; - va_start(ap, fmt); - (void) vfprintf(stderr, fmt, ap); - va_end(ap); - (void)fprintf(stderr, "\n"); - exit(FSCK_EXIT_CHECK_FAILED); + va_start(ap, fmt); + (void)vfprintf(stderr, fmt, ap); + va_end(ap); + (void)fprintf(stderr, "\n"); + exit(FSCK_EXIT_CHECK_FAILED); } void vmsg(int fatal, const char *fmt, va_list ap) { - int serr = fatal & F_ERROR; - int serrno = errno; - fatal &= ~F_ERROR; - - if (!fatal && preen) - (void)printf("%s: ", dev); - if (quiet && !preen) { - (void)printf("** %s (vmsg)\n", dev); - quiet = 0; - } - - (void) vprintf(fmt, ap); - if (serr) - printf(" (%s)", strerror(serrno)); - - if (fatal && preen) - (void) printf("\n"); - - if (fatal && preen) { - (void) printf( - "%s: UNEXPECTED INCONSISTENCY; RUN %s MANUALLY.\n", - dev, getprogname()); - exit(FSCK_EXIT_CHECK_FAILED); - } + int serr = fatal & F_ERROR; + int serrno = errno; + fatal &= ~F_ERROR; + + if (!fatal && preen) + (void)printf("%s: ", dev); + if (quiet && !preen) { + (void)printf("** %s (vmsg)\n", dev); + quiet = 0; + } + + (void)vprintf(fmt, ap); + if (serr) + printf(" (%s)", strerror(serrno)); + + if (fatal && preen) + (void)printf("\n"); + + if (fatal && preen) { + (void)printf("%s: UNEXPECTED INCONSISTENCY; RUN %s MANUALLY.\n", dev, getprogname()); + exit(FSCK_EXIT_CHECK_FAILED); + } } /*VARARGS*/ void pfatal(const char *fmt, ...) { - va_list ap; + va_list ap; - unresolved = 1; + unresolved = 1; - va_start(ap, fmt); - vmsg(1, fmt, ap); - va_end(ap); + va_start(ap, fmt); + vmsg(1, fmt, ap); + va_end(ap); } /*VARARGS*/ void pwarn(const char *fmt, ...) { - va_list ap; + va_list ap; - va_start(ap, fmt); - vmsg(0, fmt, ap); - va_end(ap); + va_start(ap, fmt); + vmsg(0, fmt, ap); + va_end(ap); } void perr(const char *fmt, ...) { - va_list ap; + va_list ap; - va_start(ap, fmt); - vmsg(1 | F_ERROR, fmt, ap); - va_end(ap); + va_start(ap, fmt); + vmsg(1 | F_ERROR, fmt, ap); + va_end(ap); } void panic(const char *fmt, ...) { - va_list ap; + va_list ap; - va_start(ap, fmt); - vmsg(1, fmt, ap); - va_end(ap); - exit(FSCK_EXIT_CHECK_FAILED); + va_start(ap, fmt); + vmsg(1, fmt, ap); + va_end(ap); + exit(FSCK_EXIT_CHECK_FAILED); } const char * print_mtime(time_t t) { - static char b[128]; - char *p = ctime(&t); - if (p != NULL) - (void)snprintf(b, sizeof(b), "%12.12s %4.4s ", &p[4], &p[20]); - else - (void)snprintf(b, sizeof(b), "%lld ", (long long)t); - return b; + static char b[128]; + char *p = ctime(&t); + if (p != NULL) + (void)snprintf(b, sizeof(b), "%12.12s %4.4s ", &p[4], &p[20]); + else + (void)snprintf(b, sizeof(b), "%lld ", (long long)t); + return b; } - -void -catch(int n) +void catch (int n) { - if (ckfinish) (*ckfinish)(0); - _exit(FSCK_EXIT_SIGNALLED); + if (ckfinish) + (*ckfinish)(0); + _exit(FSCK_EXIT_SIGNALLED); } /* @@ -211,14 +205,13 @@ catch(int n) void catchquit(int n) { - static const char msg[] = - "returning to single-user after filesystem check\n"; - int serrno = errno; - - (void)write(STDOUT_FILENO, msg, sizeof(msg) - 1); - returntosingle = 1; - (void)signal(SIGQUIT, SIG_DFL); - errno = serrno; + static const char msg[] = "returning to single-user after filesystem check\n"; + int serrno = errno; + + (void)write(STDOUT_FILENO, msg, sizeof(msg) - 1); + returntosingle = 1; + (void)signal(SIGQUIT, SIG_DFL); + errno = serrno; } /* @@ -228,10 +221,10 @@ catchquit(int n) void voidquit(int n) { - int serrno = errno; + int serrno = errno; - sleep(1); - (void)signal(SIGQUIT, SIG_IGN); - (void)signal(SIGQUIT, SIG_DFL); - errno = serrno; + sleep(1); + (void)signal(SIGQUIT, SIG_IGN); + (void)signal(SIGQUIT, SIG_DFL); + errno = serrno; } diff --git a/cmd/extra/fsck.ext4/fsutil.h b/cmd/extra/fsck.ext4/fsutil.h @@ -27,32 +27,36 @@ #include <stdarg.h> #include <signal.h> -void errexit(const char *, ...) __printflike(1, 2) __dead; -void pfatal(const char *, ...) __printflike(1, 2); -void pwarn(const char *, ...) __printflike(1, 2); -void perr(const char *, ...) __printflike(1, 2); -void panic(const char *, ...) __printflike(1, 2) __dead; -void vmsg(int, const char *, va_list) __printflike(2, 0); +void errexit(const char *, ...) __printflike(1, 2) __dead; +void pfatal(const char *, ...) __printflike(1, 2); +void pwarn(const char *, ...) __printflike(1, 2); +void perr(const char *, ...) __printflike(1, 2); +void panic(const char *, ...) __printflike(1, 2) __dead; +void vmsg(int, const char *, va_list) __printflike(2, 0); const char *blockcheck(const char *); const char *cdevname(void); -void setcdevname(const char *, int); -int hotroot(void); +void setcdevname(const char *, int); +int hotroot(void); const char *print_mtime(time_t); -#define CHECK_PREEN 1 -#define CHECK_VERBOSE 2 -#define CHECK_DEBUG 4 -#define CHECK_FORCE 8 -#define CHECK_PROGRESS 16 -#define CHECK_NOFIX 32 +#define CHECK_PREEN 1 +#define CHECK_VERBOSE 2 +#define CHECK_DEBUG 4 +#define CHECK_FORCE 8 +#define CHECK_PROGRESS 16 +#define CHECK_NOFIX 32 struct fstab; -int checkfstab(int, int, void *(*)(struct fstab *), - int (*) (const char *, const char *, const char *, void *, pid_t *)); +int checkfstab( + int, + int, + void *(*)(struct fstab *), + int (*)(const char *, const char *, const char *, void *, pid_t *) +); extern void (*ckfinish)(int); extern volatile sig_atomic_t returntosingle; -void catch(int) __dead; +void catch (int) __dead; void catchquit(int); void voidquit(int); diff --git a/cmd/extra/fsck.ext4/inode.c b/cmd/extra/fsck.ext4/inode.c @@ -84,10 +84,9 @@ __RCSID("$NetBSD: inode.c,v 1.37 2016/08/04 17:43:47 jdolecek Exp $"); * here. */ -#define fsck_ino_to_fsba(fs, x) \ - (fs2h32((fs)->e2fs_gd[ino_to_cg(fs, x)].ext2bgd_i_tables) + \ - (((x)-1) % (fs)->e2fs.e2fs_ipg)/(fs)->e2fs_ipb) - +#define fsck_ino_to_fsba(fs, x) \ + (fs2h32((fs)->e2fs_gd[ino_to_cg(fs, x)].ext2bgd_i_tables) \ + + (((x) - 1) % (fs)->e2fs.e2fs_ipg) / (fs)->e2fs_ipb) static ino_t startinum; @@ -100,234 +99,224 @@ static int sethuge(void); static int setlarge(void) { - if (sblock.e2fs.e2fs_rev < E2FS_REV1) { - pfatal("LARGE FILES UNSUPPORTED ON REVISION 0 FILESYSTEMS"); - return 0; - } - if (!(sblock.e2fs.e2fs_features_rocompat & EXT2F_ROCOMPAT_LARGEFILE)) { - if (preen) - pwarn("SETTING LARGE FILE INDICATOR\n"); - else if (!reply("SET LARGE FILE INDICATOR")) - return 0; - sblock.e2fs.e2fs_features_rocompat |= EXT2F_ROCOMPAT_LARGEFILE; - sbdirty(); - } - return 1; + if (sblock.e2fs.e2fs_rev < E2FS_REV1) { + pfatal("LARGE FILES UNSUPPORTED ON REVISION 0 FILESYSTEMS"); + return 0; + } + if (!(sblock.e2fs.e2fs_features_rocompat & EXT2F_ROCOMPAT_LARGEFILE)) { + if (preen) + pwarn("SETTING LARGE FILE INDICATOR\n"); + else if (!reply("SET LARGE FILE INDICATOR")) + return 0; + sblock.e2fs.e2fs_features_rocompat |= EXT2F_ROCOMPAT_LARGEFILE; + sbdirty(); + } + return 1; } static int sethuge(void) { - if (sblock.e2fs.e2fs_rev < E2FS_REV1) { - pfatal("HUGE FILES UNSUPPORTED ON REVISION 0 FILESYSTEMS"); - return 0; - } - if (!(sblock.e2fs.e2fs_features_rocompat & EXT2F_ROCOMPAT_HUGE_FILE)) { - if (preen) - pwarn("SETTING HUGE FILE FEATURE\n"); - else if (!reply("SET HUGE FILE FEATURE")) - return 0; - sblock.e2fs.e2fs_features_rocompat |= EXT2F_ROCOMPAT_HUGE_FILE; - sbdirty(); - } - return 1; + if (sblock.e2fs.e2fs_rev < E2FS_REV1) { + pfatal("HUGE FILES UNSUPPORTED ON REVISION 0 FILESYSTEMS"); + return 0; + } + if (!(sblock.e2fs.e2fs_features_rocompat & EXT2F_ROCOMPAT_HUGE_FILE)) { + if (preen) + pwarn("SETTING HUGE FILE FEATURE\n"); + else if (!reply("SET HUGE FILE FEATURE")) + return 0; + sblock.e2fs.e2fs_features_rocompat |= EXT2F_ROCOMPAT_HUGE_FILE; + sbdirty(); + } + return 1; } u_int64_t inosize(struct ext2fs_dinode *dp) { - u_int64_t size = fs2h32(dp->e2di_size); + u_int64_t size = fs2h32(dp->e2di_size); - if ((fs2h16(dp->e2di_mode) & IFMT) == IFREG) - size |= (u_int64_t)fs2h32(dp->e2di_size_high) << 32; - if (size > INT32_MAX) - (void)setlarge(); - return size; + if ((fs2h16(dp->e2di_mode) & IFMT) == IFREG) + size |= (u_int64_t)fs2h32(dp->e2di_size_high) << 32; + if (size > INT32_MAX) + (void)setlarge(); + return size; } void inossize(struct ext2fs_dinode *dp, u_int64_t size) { - if ((fs2h16(dp->e2di_mode) & IFMT) == IFREG) { - dp->e2di_size_high = h2fs32(size >> 32); - if (size > INT32_MAX) - if (!setlarge()) - return; - } else if (size > INT32_MAX) { - pfatal("TRYING TO SET FILESIZE TO %llu ON MODE %x FILE\n", - (unsigned long long)size, fs2h16(dp->e2di_mode) & IFMT); - return; - } - dp->e2di_size = h2fs32(size); + if ((fs2h16(dp->e2di_mode) & IFMT) == IFREG) { + dp->e2di_size_high = h2fs32(size >> 32); + if (size > INT32_MAX) + if (!setlarge()) + return; + } else if (size > INT32_MAX) { + pfatal( + "TRYING TO SET FILESIZE TO %llu ON MODE %x FILE\n", + (unsigned long long)size, + fs2h16(dp->e2di_mode) & IFMT + ); + return; + } + dp->e2di_size = h2fs32(size); } int ckinode(struct ext2fs_dinode *dp, struct inodesc *idesc) { - u_int32_t *ap; - long ret, n, ndb; - struct ext2fs_dinode dino; - u_int64_t remsize, sizepb; - mode_t mode; - char pathbuf[MAXPATHLEN + 1]; - - if (idesc->id_fix != IGNORE) - idesc->id_fix = DONTKNOW; - idesc->id_entryno = 0; - idesc->id_filesize = inosize(dp); - mode = fs2h16(dp->e2di_mode) & IFMT; - if (mode == IFBLK || mode == IFCHR || mode == IFIFO || - (mode == IFLNK && (inosize(dp) < EXT2_MAXSYMLINKLEN))) - return (KEEPON); - dino = *dp; - ndb = howmany(inosize(&dino), sblock.e2fs_bsize); - for (ap = &dino.e2di_blocks[0]; ap < &dino.e2di_blocks[EXT2FS_NDADDR]; - ap++,ndb--) { - idesc->id_numfrags = 1; - if (*ap == 0) { - if (idesc->id_type == DATA && ndb > 0) { - /* An empty block in a directory XXX */ - getpathname(pathbuf, sizeof(pathbuf), - idesc->id_number, idesc->id_number); - pfatal("DIRECTORY %s: CONTAINS EMPTY BLOCKS", - pathbuf); - if (reply("ADJUST LENGTH") == 1) { - dp = ginode(idesc->id_number); - inossize(dp, - (ap - &dino.e2di_blocks[0]) * - sblock.e2fs_bsize); - printf( - "YOU MUST RERUN FSCK AFTERWARDS\n"); - rerun = 1; - inodirty(); - } - } - continue; - } - idesc->id_blkno = fs2h32(*ap); - if (idesc->id_type == ADDR) - ret = (*idesc->id_func)(idesc); - else - ret = dirscan(idesc); - if (ret & STOP) - return (ret); - } - idesc->id_numfrags = 1; - remsize = inosize(&dino) - sblock.e2fs_bsize * EXT2FS_NDADDR; - sizepb = sblock.e2fs_bsize; - for (ap = &dino.e2di_blocks[EXT2FS_NDADDR], n = 1; n <= EXT2FS_NIADDR; ap++, n++) { - if (*ap) { - idesc->id_blkno = fs2h32(*ap); - ret = iblock(idesc, n, remsize); - if (ret & STOP) - return (ret); - } else { - if (idesc->id_type == DATA && remsize > 0) { - /* An empty block in a directory XXX */ - getpathname(pathbuf, sizeof(pathbuf), - idesc->id_number, idesc->id_number); - pfatal("DIRECTORY %s: CONTAINS EMPTY BLOCKS", - pathbuf); - if (reply("ADJUST LENGTH") == 1) { - dp = ginode(idesc->id_number); - inossize(dp, inosize(dp) - remsize); - remsize = 0; - printf( - "YOU MUST RERUN FSCK AFTERWARDS\n"); - rerun = 1; - inodirty(); - break; - } - } - } - sizepb *= EXT2_NINDIR(&sblock); - remsize -= sizepb; - } - return (KEEPON); + u_int32_t *ap; + long ret, n, ndb; + struct ext2fs_dinode dino; + u_int64_t remsize, sizepb; + mode_t mode; + char pathbuf[MAXPATHLEN + 1]; + + if (idesc->id_fix != IGNORE) + idesc->id_fix = DONTKNOW; + idesc->id_entryno = 0; + idesc->id_filesize = inosize(dp); + mode = fs2h16(dp->e2di_mode) & IFMT; + if (mode == IFBLK || mode == IFCHR || mode == IFIFO + || (mode == IFLNK && (inosize(dp) < EXT2_MAXSYMLINKLEN))) + return (KEEPON); + dino = *dp; + ndb = howmany(inosize(&dino), sblock.e2fs_bsize); + for (ap = &dino.e2di_blocks[0]; ap < &dino.e2di_blocks[EXT2FS_NDADDR]; ap++, ndb--) { + idesc->id_numfrags = 1; + if (*ap == 0) { + if (idesc->id_type == DATA && ndb > 0) { + /* An empty block in a directory XXX */ + getpathname(pathbuf, sizeof(pathbuf), idesc->id_number, idesc->id_number); + pfatal("DIRECTORY %s: CONTAINS EMPTY BLOCKS", pathbuf); + if (reply("ADJUST LENGTH") == 1) { + dp = ginode(idesc->id_number); + inossize(dp, (ap - &dino.e2di_blocks[0]) * sblock.e2fs_bsize); + printf("YOU MUST RERUN FSCK AFTERWARDS\n"); + rerun = 1; + inodirty(); + } + } + continue; + } + idesc->id_blkno = fs2h32(*ap); + if (idesc->id_type == ADDR) + ret = (*idesc->id_func)(idesc); + else + ret = dirscan(idesc); + if (ret & STOP) + return (ret); + } + idesc->id_numfrags = 1; + remsize = inosize(&dino) - sblock.e2fs_bsize * EXT2FS_NDADDR; + sizepb = sblock.e2fs_bsize; + for (ap = &dino.e2di_blocks[EXT2FS_NDADDR], n = 1; n <= EXT2FS_NIADDR; ap++, n++) { + if (*ap) { + idesc->id_blkno = fs2h32(*ap); + ret = iblock(idesc, n, remsize); + if (ret & STOP) + return (ret); + } else { + if (idesc->id_type == DATA && remsize > 0) { + /* An empty block in a directory XXX */ + getpathname(pathbuf, sizeof(pathbuf), idesc->id_number, idesc->id_number); + pfatal("DIRECTORY %s: CONTAINS EMPTY BLOCKS", pathbuf); + if (reply("ADJUST LENGTH") == 1) { + dp = ginode(idesc->id_number); + inossize(dp, inosize(dp) - remsize); + remsize = 0; + printf("YOU MUST RERUN FSCK AFTERWARDS\n"); + rerun = 1; + inodirty(); + break; + } + } + } + sizepb *= EXT2_NINDIR(&sblock); + remsize -= sizepb; + } + return (KEEPON); } static int iblock(struct inodesc *idesc, long ilevel, u_int64_t isize) { - /* XXX ondisk32 */ - int32_t *ap; - int32_t *aplim; - struct bufarea *bp; - int i, n, (*func)(struct inodesc *); - size_t nif; - u_int64_t sizepb; - char buf[BUFSIZ]; - char pathbuf[MAXPATHLEN + 1]; - struct ext2fs_dinode *dp; - - if (idesc->id_type == ADDR) { - func = idesc->id_func; - if (((n = (*func)(idesc)) & KEEPON) == 0) - return (n); - } else - func = dirscan; - if (chkrange(idesc->id_blkno, idesc->id_numfrags)) - return (SKIP); - bp = getdatablk(idesc->id_blkno, sblock.e2fs_bsize); - ilevel--; - for (sizepb = sblock.e2fs_bsize, i = 0; i < ilevel; i++) - sizepb *= EXT2_NINDIR(&sblock); - if (isize > sizepb * EXT2_NINDIR(&sblock)) - nif = EXT2_NINDIR(&sblock); - else - nif = howmany(isize, sizepb); - if (idesc->id_func == pass1check && - nif < EXT2_NINDIR(&sblock)) { - aplim = &bp->b_un.b_indir[EXT2_NINDIR(&sblock)]; - for (ap = &bp->b_un.b_indir[nif]; ap < aplim; ap++) { - if (*ap == 0) - continue; - (void)snprintf(buf, sizeof(buf), - "PARTIALLY TRUNCATED INODE I=%llu", - (unsigned long long)idesc->id_number); - if (dofix(idesc, buf)) { - *ap = 0; - dirty(bp); - } - } - flush(fswritefd, bp); - } - aplim = &bp->b_un.b_indir[nif]; - for (ap = bp->b_un.b_indir; ap < aplim; ap++) { - if (*ap) { - idesc->id_blkno = fs2h32(*ap); - if (ilevel == 0) - n = (*func)(idesc); - else - n = iblock(idesc, ilevel, isize); - if (n & STOP) { - bp->b_flags &= ~B_INUSE; - return (n); - } - } else { - if (idesc->id_type == DATA && isize > 0) { - /* An empty block in a directory XXX */ - getpathname(pathbuf, sizeof(pathbuf), - idesc->id_number, idesc->id_number); - pfatal("DIRECTORY %s: CONTAINS EMPTY BLOCKS", - pathbuf); - if (reply("ADJUST LENGTH") == 1) { - dp = ginode(idesc->id_number); - inossize(dp, inosize(dp) - isize); - isize = 0; - printf( - "YOU MUST RERUN FSCK AFTERWARDS\n"); - rerun = 1; - inodirty(); - bp->b_flags &= ~B_INUSE; - return(STOP); - } - } - } - isize -= sizepb; - } - bp->b_flags &= ~B_INUSE; - return (KEEPON); + /* XXX ondisk32 */ + int32_t *ap; + int32_t *aplim; + struct bufarea *bp; + int i, n, (*func)(struct inodesc *); + size_t nif; + u_int64_t sizepb; + char buf[BUFSIZ]; + char pathbuf[MAXPATHLEN + 1]; + struct ext2fs_dinode *dp; + + if (idesc->id_type == ADDR) { + func = idesc->id_func; + if (((n = (*func)(idesc)) & KEEPON) == 0) + return (n); + } else + func = dirscan; + if (chkrange(idesc->id_blkno, idesc->id_numfrags)) + return (SKIP); + bp = getdatablk(idesc->id_blkno, sblock.e2fs_bsize); + ilevel--; + for (sizepb = sblock.e2fs_bsize, i = 0; i < ilevel; i++) + sizepb *= EXT2_NINDIR(&sblock); + if (isize > sizepb * EXT2_NINDIR(&sblock)) + nif = EXT2_NINDIR(&sblock); + else + nif = howmany(isize, sizepb); + if (idesc->id_func == pass1check && nif < EXT2_NINDIR(&sblock)) { + aplim = &bp->b_un.b_indir[EXT2_NINDIR(&sblock)]; + for (ap = &bp->b_un.b_indir[nif]; ap < aplim; ap++) { + if (*ap == 0) + continue; + (void)snprintf( + buf, sizeof(buf), "PARTIALLY TRUNCATED INODE I=%llu", (unsigned long long)idesc->id_number + ); + if (dofix(idesc, buf)) { + *ap = 0; + dirty(bp); + } + } + flush(fswritefd, bp); + } + aplim = &bp->b_un.b_indir[nif]; + for (ap = bp->b_un.b_indir; ap < aplim; ap++) { + if (*ap) { + idesc->id_blkno = fs2h32(*ap); + if (ilevel == 0) + n = (*func)(idesc); + else + n = iblock(idesc, ilevel, isize); + if (n & STOP) { + bp->b_flags &= ~B_INUSE; + return (n); + } + } else { + if (idesc->id_type == DATA && isize > 0) { + /* An empty block in a directory XXX */ + getpathname(pathbuf, sizeof(pathbuf), idesc->id_number, idesc->id_number); + pfatal("DIRECTORY %s: CONTAINS EMPTY BLOCKS", pathbuf); + if (reply("ADJUST LENGTH") == 1) { + dp = ginode(idesc->id_number); + inossize(dp, inosize(dp) - isize); + isize = 0; + printf("YOU MUST RERUN FSCK AFTERWARDS\n"); + rerun = 1; + inodirty(); + bp->b_flags &= ~B_INUSE; + return (STOP); + } + } + } + isize -= sizepb; + } + bp->b_flags &= ~B_INUSE; + return (KEEPON); } /* @@ -337,45 +326,46 @@ iblock(struct inodesc *idesc, long ilevel, u_int64_t isize) int chkrange(daddr_t blk, int cnt) { - int c, overh; - - if ((unsigned int)(blk + cnt) > maxfsblock) - return (1); - c = dtog(&sblock, blk); - overh = cgoverhead(c); - if (blk < sblock.e2fs.e2fs_bpg * c + overh + - sblock.e2fs.e2fs_first_dblock) { - if ((blk + cnt) > sblock.e2fs.e2fs_bpg * c + overh + - sblock.e2fs.e2fs_first_dblock) { - if (debug) { - printf("blk %lld < cgdmin %d;", - (long long)blk, - sblock.e2fs.e2fs_bpg * c + overh + - sblock.e2fs.e2fs_first_dblock); - printf(" blk + cnt %lld > cgsbase %d\n", - (long long)(blk + cnt), - sblock.e2fs.e2fs_bpg * c + - overh + sblock.e2fs.e2fs_first_dblock); - } - return (1); - } - } else { - if ((blk + cnt) > sblock.e2fs.e2fs_bpg * (c + 1) + overh + - sblock.e2fs.e2fs_first_dblock) { - if (debug) { - printf("blk %lld >= cgdmin %d;", - (long long)blk, - sblock.e2fs.e2fs_bpg * c + overh + - sblock.e2fs.e2fs_first_dblock); - printf(" blk + cnt %lld > cgdmax %d\n", - (long long)(blk+cnt), - sblock.e2fs.e2fs_bpg * (c + 1) + - overh + sblock.e2fs.e2fs_first_dblock); - } - return (1); - } - } - return (0); + int c, overh; + + if ((unsigned int)(blk + cnt) > maxfsblock) + return (1); + c = dtog(&sblock, blk); + overh = cgoverhead(c); + if (blk < sblock.e2fs.e2fs_bpg * c + overh + sblock.e2fs.e2fs_first_dblock) { + if ((blk + cnt) > sblock.e2fs.e2fs_bpg * c + overh + sblock.e2fs.e2fs_first_dblock) { + if (debug) { + printf( + "blk %lld < cgdmin %d;", + (long long)blk, + sblock.e2fs.e2fs_bpg * c + overh + sblock.e2fs.e2fs_first_dblock + ); + printf( + " blk + cnt %lld > cgsbase %d\n", + (long long)(blk + cnt), + sblock.e2fs.e2fs_bpg * c + overh + sblock.e2fs.e2fs_first_dblock + ); + } + return (1); + } + } else { + if ((blk + cnt) > sblock.e2fs.e2fs_bpg * (c + 1) + overh + sblock.e2fs.e2fs_first_dblock) { + if (debug) { + printf( + "blk %lld >= cgdmin %d;", + (long long)blk, + sblock.e2fs.e2fs_bpg * c + overh + sblock.e2fs.e2fs_first_dblock + ); + printf( + " blk + cnt %lld > cgdmax %d\n", + (long long)(blk + cnt), + sblock.e2fs.e2fs_bpg * (c + 1) + overh + sblock.e2fs.e2fs_first_dblock + ); + } + return (1); + } + } + return (0); } /* @@ -384,29 +374,27 @@ chkrange(daddr_t blk, int cnt) struct ext2fs_dinode * ginode(ino_t inumber) { - daddr_t iblk; - struct ext2fs_dinode *dp; - - if ((inumber < EXT2_FIRSTINO && - inumber != EXT2_ROOTINO && - !(inumber == EXT2_RESIZEINO && - (sblock.e2fs.e2fs_features_compat & EXT2F_COMPAT_RESIZE) != 0)) - || inumber > maxino) - errexit("bad inode number %llu to ginode", - (unsigned long long)inumber); - if (startinum == 0 || - inumber < startinum || inumber >= startinum + sblock.e2fs_ipb) { - iblk = fsck_ino_to_fsba(&sblock, inumber); - if (pbp != 0) - pbp->b_flags &= ~B_INUSE; - pbp = getdatablk(iblk, sblock.e2fs_bsize); - startinum = - ((inumber - 1) / sblock.e2fs_ipb) * sblock.e2fs_ipb + 1; - } - dp = (struct ext2fs_dinode *)(pbp->b_un.b_buf + - EXT2_DINODE_SIZE(&sblock) * ino_to_fsbo(&sblock, inumber)); - - return dp; + daddr_t iblk; + struct ext2fs_dinode *dp; + + if ((inumber < EXT2_FIRSTINO && inumber != EXT2_ROOTINO + && !( + inumber == EXT2_RESIZEINO + && (sblock.e2fs.e2fs_features_compat & EXT2F_COMPAT_RESIZE) != 0 + )) + || inumber > maxino) + errexit("bad inode number %llu to ginode", (unsigned long long)inumber); + if (startinum == 0 || inumber < startinum || inumber >= startinum + sblock.e2fs_ipb) { + iblk = fsck_ino_to_fsba(&sblock, inumber); + if (pbp != 0) + pbp->b_flags &= ~B_INUSE; + pbp = getdatablk(iblk, sblock.e2fs_bsize); + startinum = ((inumber - 1) / sblock.e2fs_ipb) * sblock.e2fs_ipb + 1; + } + dp = (struct ext2fs_dinode *)(pbp->b_un.b_buf + + EXT2_DINODE_SIZE(&sblock) * ino_to_fsbo(&sblock, inumber)); + + return dp; } /* @@ -414,72 +402,68 @@ ginode(ino_t inumber) * over all the inodes in numerical order. */ ino_t nextino, lastinum; -long readcnt, readpercg, fullcnt, inobufsize, partialcnt, partialsize; +long readcnt, readpercg, fullcnt, inobufsize, partialcnt, partialsize; char *inodebuf; struct ext2fs_dinode * getnextinode(ino_t inumber) { - long size; - daddr_t dblk; - struct ext2fs_dinode *dp; - static char *bp; - - if (inumber != nextino++ || inumber > maxino) - errexit("bad inode number %llu to nextinode", - (unsigned long long)inumber); - if (inumber >= lastinum) { - readcnt++; - dblk = EXT2_FSBTODB(&sblock, fsck_ino_to_fsba(&sblock, lastinum)); - if (readcnt % readpercg == 0) { - size = partialsize; - lastinum += partialcnt; - } else { - size = inobufsize; - lastinum += fullcnt; - } - (void)bread(fsreadfd, inodebuf, dblk, size); - bp = inodebuf; - } - dp = (struct ext2fs_dinode *)bp; - bp += EXT2_DINODE_SIZE(&sblock); - - return dp; + long size; + daddr_t dblk; + struct ext2fs_dinode *dp; + static char *bp; + + if (inumber != nextino++ || inumber > maxino) + errexit("bad inode number %llu to nextinode", (unsigned long long)inumber); + if (inumber >= lastinum) { + readcnt++; + dblk = EXT2_FSBTODB(&sblock, fsck_ino_to_fsba(&sblock, lastinum)); + if (readcnt % readpercg == 0) { + size = partialsize; + lastinum += partialcnt; + } else { + size = inobufsize; + lastinum += fullcnt; + } + (void)bread(fsreadfd, inodebuf, dblk, size); + bp = inodebuf; + } + dp = (struct ext2fs_dinode *)bp; + bp += EXT2_DINODE_SIZE(&sblock); + + return dp; } void resetinodebuf(void) { - - startinum = 0; - nextino = 1; - lastinum = 1; - readcnt = 0; - inobufsize = ext2_blkroundup(&sblock, INOBUFSIZE); - fullcnt = inobufsize / EXT2_DINODE_SIZE(&sblock); - readpercg = sblock.e2fs.e2fs_ipg / fullcnt; - partialcnt = sblock.e2fs.e2fs_ipg % fullcnt; - partialsize = partialcnt * EXT2_DINODE_SIZE(&sblock); - if (partialcnt != 0) { - readpercg++; - } else { - partialcnt = fullcnt; - partialsize = inobufsize; - } - if (inodebuf == NULL && - (inodebuf = malloc((unsigned int)inobufsize)) == NULL) - errexit("Cannot allocate space for inode buffer"); - while (nextino < EXT2_ROOTINO) - (void)getnextinode(nextino); + startinum = 0; + nextino = 1; + lastinum = 1; + readcnt = 0; + inobufsize = ext2_blkroundup(&sblock, INOBUFSIZE); + fullcnt = inobufsize / EXT2_DINODE_SIZE(&sblock); + readpercg = sblock.e2fs.e2fs_ipg / fullcnt; + partialcnt = sblock.e2fs.e2fs_ipg % fullcnt; + partialsize = partialcnt * EXT2_DINODE_SIZE(&sblock); + if (partialcnt != 0) { + readpercg++; + } else { + partialcnt = fullcnt; + partialsize = inobufsize; + } + if (inodebuf == NULL && (inodebuf = malloc((unsigned int)inobufsize)) == NULL) + errexit("Cannot allocate space for inode buffer"); + while (nextino < EXT2_ROOTINO) + (void)getnextinode(nextino); } void freeinodebuf(void) { - - if (inodebuf != NULL) - free(inodebuf); - inodebuf = NULL; + if (inodebuf != NULL) + free(inodebuf); + inodebuf = NULL; } /* @@ -492,39 +476,40 @@ freeinodebuf(void) void cacheino(struct ext2fs_dinode *dp, ino_t inumber) { - struct inoinfo *inp; - struct inoinfo **inpp; - unsigned int blks; - - blks = howmany(inosize(dp), sblock.e2fs_bsize); - if (blks > EXT2FS_NDADDR) - blks = EXT2FS_NDADDR + EXT2FS_NIADDR; - /* XXX ondisk32 */ - inp = malloc(sizeof(*inp) + (blks - 1) * sizeof(int32_t)); - if (inp == NULL) - return; - inpp = &inphead[inumber % numdirs]; - inp->i_nexthash = *inpp; - *inpp = inp; - inp->i_child = inp->i_sibling = inp->i_parentp = 0; - if (inumber == EXT2_ROOTINO) - inp->i_parent = EXT2_ROOTINO; - else - inp->i_parent = (ino_t)0; - inp->i_dotdot = (ino_t)0; - inp->i_number = inumber; - inp->i_isize = inosize(dp); - /* XXX ondisk32 */ - inp->i_numblks = blks * sizeof(int32_t); - memcpy(&inp->i_blks[0], &dp->e2di_blocks[0], (size_t)inp->i_numblks); - if (inplast == listmax) { - listmax += 100; - inpsort = (struct inoinfo **)realloc((char *)inpsort, - (unsigned int)listmax * sizeof(struct inoinfo *)); - if (inpsort == NULL) - errexit("cannot increase directory list"); - } - inpsort[inplast++] = inp; + struct inoinfo *inp; + struct inoinfo **inpp; + unsigned int blks; + + blks = howmany(inosize(dp), sblock.e2fs_bsize); + if (blks > EXT2FS_NDADDR) + blks = EXT2FS_NDADDR + EXT2FS_NIADDR; + /* XXX ondisk32 */ + inp = malloc(sizeof(*inp) + (blks - 1) * sizeof(int32_t)); + if (inp == NULL) + return; + inpp = &inphead[inumber % numdirs]; + inp->i_nexthash = *inpp; + *inpp = inp; + inp->i_child = inp->i_sibling = inp->i_parentp = 0; + if (inumber == EXT2_ROOTINO) + inp->i_parent = EXT2_ROOTINO; + else + inp->i_parent = (ino_t)0; + inp->i_dotdot = (ino_t)0; + inp->i_number = inumber; + inp->i_isize = inosize(dp); + /* XXX ondisk32 */ + inp->i_numblks = blks * sizeof(int32_t); + memcpy(&inp->i_blks[0], &dp->e2di_blocks[0], (size_t)inp->i_numblks); + if (inplast == listmax) { + listmax += 100; + inpsort = (struct inoinfo **)realloc( + (char *)inpsort, (unsigned int)listmax * sizeof(struct inoinfo *) + ); + if (inpsort == NULL) + errexit("cannot increase directory list"); + } + inpsort[inplast++] = inp; } /* @@ -533,15 +518,15 @@ cacheino(struct ext2fs_dinode *dp, ino_t inumber) struct inoinfo * getinoinfo(ino_t inumber) { - struct inoinfo *inp; - - for (inp = inphead[inumber % numdirs]; inp; inp = inp->i_nexthash) { - if (inp->i_number != inumber) - continue; - return (inp); - } - errexit("cannot find inode %llu", (unsigned long long)inumber); - return ((struct inoinfo *)0); + struct inoinfo *inp; + + for (inp = inphead[inumber % numdirs]; inp; inp = inp->i_nexthash) { + if (inp->i_number != inumber) + continue; + return (inp); + } + errexit("cannot find inode %llu", (unsigned long long)inumber); + return ((struct inoinfo *)0); } /* @@ -550,134 +535,129 @@ getinoinfo(ino_t inumber) void inocleanup(void) { - struct inoinfo **inpp; - - if (inphead == NULL) - return; - for (inpp = &inpsort[inplast - 1]; inpp >= inpsort; inpp--) - free(*inpp); - free(inphead); - free(inpsort); - inphead = inpsort = NULL; + struct inoinfo **inpp; + + if (inphead == NULL) + return; + for (inpp = &inpsort[inplast - 1]; inpp >= inpsort; inpp--) + free(*inpp); + free(inphead); + free(inpsort); + inphead = inpsort = NULL; } - + void inodirty(void) { - - dirty(pbp); + dirty(pbp); } void clri(struct inodesc *idesc, const char *type, int flag) { - struct ext2fs_dinode *dp; - - dp = ginode(idesc->id_number); - if (flag == 1) { - pwarn("%s %s", type, - (fs2h16(dp->e2di_mode) & IFMT) == IFDIR ? "DIR" : "FILE"); - pinode(idesc->id_number); - } - if (preen || reply("CLEAR") == 1) { - if (preen) - printf(" (CLEARED)\n"); - n_files--; - (void)ckinode(dp, idesc); - clearinode(dp); - statemap[idesc->id_number] = USTATE; - inodirty(); - } + struct ext2fs_dinode *dp; + + dp = ginode(idesc->id_number); + if (flag == 1) { + pwarn("%s %s", type, (fs2h16(dp->e2di_mode) & IFMT) == IFDIR ? "DIR" : "FILE"); + pinode(idesc->id_number); + } + if (preen || reply("CLEAR") == 1) { + if (preen) + printf(" (CLEARED)\n"); + n_files--; + (void)ckinode(dp, idesc); + clearinode(dp); + statemap[idesc->id_number] = USTATE; + inodirty(); + } } int findname(struct inodesc *idesc) { - struct ext2fs_direct *dirp = idesc->id_dirp; - u_int16_t namlen = dirp->e2d_namlen; - /* from utilities.c namebuf[] variable */ - char *buf = __UNCONST(idesc->id_name); - if (namlen > MAXPATHLEN) { - /* XXX: Prevent overflow but don't fix */ - namlen = MAXPATHLEN; - } - - if (fs2h32(dirp->e2d_ino) != idesc->id_parent) - return (KEEPON); - (void)memcpy(buf, dirp->e2d_name, (size_t)namlen); - buf[namlen] = '\0'; - return (STOP|FOUND); + struct ext2fs_direct *dirp = idesc->id_dirp; + u_int16_t namlen = dirp->e2d_namlen; + /* from utilities.c namebuf[] variable */ + char *buf = __UNCONST(idesc->id_name); + if (namlen > MAXPATHLEN) { + /* XXX: Prevent overflow but don't fix */ + namlen = MAXPATHLEN; + } + + if (fs2h32(dirp->e2d_ino) != idesc->id_parent) + return (KEEPON); + (void)memcpy(buf, dirp->e2d_name, (size_t)namlen); + buf[namlen] = '\0'; + return (STOP | FOUND); } int findino(struct inodesc *idesc) { - struct ext2fs_direct *dirp = idesc->id_dirp; - u_int32_t ino = fs2h32(dirp->e2d_ino); - - if (ino == 0) - return (KEEPON); - if (strcmp(dirp->e2d_name, idesc->id_name) == 0 && - (ino == EXT2_ROOTINO || ino >= EXT2_FIRSTINO) - && ino <= maxino) { - idesc->id_parent = ino; - return (STOP|FOUND); - } - return (KEEPON); + struct ext2fs_direct *dirp = idesc->id_dirp; + u_int32_t ino = fs2h32(dirp->e2d_ino); + + if (ino == 0) + return (KEEPON); + if (strcmp(dirp->e2d_name, idesc->id_name) == 0 && (ino == EXT2_ROOTINO || ino >= EXT2_FIRSTINO) + && ino <= maxino) { + idesc->id_parent = ino; + return (STOP | FOUND); + } + return (KEEPON); } void pinode(ino_t ino) { - struct ext2fs_dinode *dp; - struct passwd *pw; - uid_t uid; - - printf(" I=%llu ", (unsigned long long)ino); - if ((ino < EXT2_FIRSTINO && ino != EXT2_ROOTINO) || ino > maxino) - return; - dp = ginode(ino); - uid = fs2h16(dp->e2di_uid); - if (sblock.e2fs.e2fs_rev > E2FS_REV0) - uid |= fs2h16(dp->e2di_uid_high) << 16; - printf(" OWNER="); + struct ext2fs_dinode *dp; + struct passwd *pw; + uid_t uid; + + printf(" I=%llu ", (unsigned long long)ino); + if ((ino < EXT2_FIRSTINO && ino != EXT2_ROOTINO) || ino > maxino) + return; + dp = ginode(ino); + uid = fs2h16(dp->e2di_uid); + if (sblock.e2fs.e2fs_rev > E2FS_REV0) + uid |= fs2h16(dp->e2di_uid_high) << 16; + printf(" OWNER="); #ifndef SMALL - if (Uflag && (pw = getpwuid(uid)) != 0) - printf("%s ", pw->pw_name); - else + if (Uflag && (pw = getpwuid(uid)) != 0) + printf("%s ", pw->pw_name); + else #endif - printf("%u ", (unsigned int)uid); - printf("MODE=%o\n", fs2h16(dp->e2di_mode)); - if (preen) - printf("%s: ", cdevname()); - printf("SIZE=%llu ", (long long)inosize(dp)); - printf("MTIME=%s ", print_mtime(fs2h32(dp->e2di_mtime))); + printf("%u ", (unsigned int)uid); + printf("MODE=%o\n", fs2h16(dp->e2di_mode)); + if (preen) + printf("%s: ", cdevname()); + printf("SIZE=%llu ", (long long)inosize(dp)); + printf("MTIME=%s ", print_mtime(fs2h32(dp->e2di_mtime))); } void blkerror(ino_t ino, const char *type, daddr_t blk) { - - pfatal("%lld %s I=%llu", (long long)blk, type, (unsigned long long)ino); - printf("\n"); - switch (statemap[ino]) { - - case FSTATE: - statemap[ino] = FCLEAR; - return; - - case DSTATE: - statemap[ino] = DCLEAR; - return; - - case FCLEAR: - case DCLEAR: - return; - - default: - errexit("BAD STATE %d TO BLKERR", statemap[ino]); - /* NOTREACHED */ - } + pfatal("%lld %s I=%llu", (long long)blk, type, (unsigned long long)ino); + printf("\n"); + switch (statemap[ino]) { + case FSTATE: + statemap[ino] = FCLEAR; + return; + + case DSTATE: + statemap[ino] = DCLEAR; + return; + + case FCLEAR: + case DCLEAR: + return; + + default: + errexit("BAD STATE %d TO BLKERR", statemap[ino]); + /* NOTREACHED */ + } } /* @@ -686,50 +666,50 @@ blkerror(ino_t ino, const char *type, daddr_t blk) ino_t allocino(ino_t request, int type) { - ino_t ino; - struct ext2fs_dinode *dp; - time_t t; - - if (request == 0) - request = EXT2_ROOTINO; - else if (statemap[request] != USTATE) - return (0); - for (ino = request; ino < maxino; ino++) { - if ((ino > EXT2_ROOTINO) && (ino < EXT2_FIRSTINO)) - continue; - if (statemap[ino] == USTATE) - break; - } - if (ino == maxino) - return (0); - switch (type & IFMT) { - case IFDIR: - statemap[ino] = DSTATE; - break; - case IFREG: - case IFLNK: - statemap[ino] = FSTATE; - break; - default: - return (0); - } - dp = ginode(ino); - dp->e2di_blocks[0] = h2fs32(allocblk()); - if (dp->e2di_blocks[0] == 0) { - statemap[ino] = USTATE; - return (0); - } - dp->e2di_mode = h2fs16(type); - (void)time(&t); - dp->e2di_atime = h2fs32(t); - dp->e2di_mtime = dp->e2di_ctime = dp->e2di_atime; - dp->e2di_dtime = 0; - inossize(dp, sblock.e2fs_bsize); - inosnblock(dp, btodb(sblock.e2fs_bsize)); - n_files++; - inodirty(); - typemap[ino] = E2IFTODT(type); - return (ino); + ino_t ino; + struct ext2fs_dinode *dp; + time_t t; + + if (request == 0) + request = EXT2_ROOTINO; + else if (statemap[request] != USTATE) + return (0); + for (ino = request; ino < maxino; ino++) { + if ((ino > EXT2_ROOTINO) && (ino < EXT2_FIRSTINO)) + continue; + if (statemap[ino] == USTATE) + break; + } + if (ino == maxino) + return (0); + switch (type & IFMT) { + case IFDIR: + statemap[ino] = DSTATE; + break; + case IFREG: + case IFLNK: + statemap[ino] = FSTATE; + break; + default: + return (0); + } + dp = ginode(ino); + dp->e2di_blocks[0] = h2fs32(allocblk()); + if (dp->e2di_blocks[0] == 0) { + statemap[ino] = USTATE; + return (0); + } + dp->e2di_mode = h2fs16(type); + (void)time(&t); + dp->e2di_atime = h2fs32(t); + dp->e2di_mtime = dp->e2di_ctime = dp->e2di_atime; + dp->e2di_dtime = 0; + inossize(dp, sblock.e2fs_bsize); + inosnblock(dp, btodb(sblock.e2fs_bsize)); + n_files++; + inodirty(); + typemap[ino] = E2IFTODT(type); + return (ino); } /* @@ -738,73 +718,73 @@ allocino(ino_t request, int type) void freeino(ino_t ino) { - struct inodesc idesc; - struct ext2fs_dinode *dp; - - memset(&idesc, 0, sizeof(struct inodesc)); - idesc.id_type = ADDR; - idesc.id_func = pass4check; - idesc.id_number = ino; - dp = ginode(ino); - (void)ckinode(dp, &idesc); - clearinode(dp); - inodirty(); - statemap[ino] = USTATE; - n_files--; + struct inodesc idesc; + struct ext2fs_dinode *dp; + + memset(&idesc, 0, sizeof(struct inodesc)); + idesc.id_type = ADDR; + idesc.id_func = pass4check; + idesc.id_number = ino; + dp = ginode(ino); + (void)ckinode(dp, &idesc); + clearinode(dp); + inodirty(); + statemap[ino] = USTATE; + n_files--; } uint64_t inonblock(struct ext2fs_dinode *dp) { - uint64_t nblock; + uint64_t nblock; - /* XXX check for EXT2_HUGE_FILE without EXT2F_ROCOMPAT_HUGE_FILE? */ + /* XXX check for EXT2_HUGE_FILE without EXT2F_ROCOMPAT_HUGE_FILE? */ - nblock = fs2h32(dp->e2di_nblock); + nblock = fs2h32(dp->e2di_nblock); - if ((sblock.e2fs.e2fs_features_rocompat & EXT2F_ROCOMPAT_HUGE_FILE)) { - nblock |= (uint64_t)fs2h16(dp->e2di_nblock_high) << 32; - if (fs2h32(dp->e2di_flags) & EXT2_HUGE_FILE) { - nblock = EXT2_FSBTODB(&sblock, nblock); - } - } + if ((sblock.e2fs.e2fs_features_rocompat & EXT2F_ROCOMPAT_HUGE_FILE)) { + nblock |= (uint64_t)fs2h16(dp->e2di_nblock_high) << 32; + if (fs2h32(dp->e2di_flags) & EXT2_HUGE_FILE) { + nblock = EXT2_FSBTODB(&sblock, nblock); + } + } - return nblock; + return nblock; } void inosnblock(struct ext2fs_dinode *dp, uint64_t nblock) { - uint32_t flags; - - flags = fs2h32(dp->e2di_flags); - - if (nblock <= 0xffffffffULL) { - flags &= ~EXT2_HUGE_FILE; - dp->e2di_flags = h2fs32(flags); - dp->e2di_nblock = h2fs32(nblock); - return; - } - - sethuge(); - - if (nblock <= 0xffffffffffffULL) { - flags &= ~EXT2_HUGE_FILE; - dp->e2di_flags = h2fs32(flags); - dp->e2di_nblock = h2fs32(nblock); - dp->e2di_nblock_high = h2fs16((nblock >> 32)); - return; - } - - if (EXT2_DBTOFSB(&sblock, nblock) <= 0xffffffffffffULL) { - flags |= EXT2_HUGE_FILE; - dp->e2di_flags = h2fs32(flags); - dp->e2di_nblock = h2fs32(EXT2_DBTOFSB(&sblock, nblock)); - dp->e2di_nblock_high = h2fs16((EXT2_DBTOFSB(&sblock, nblock) >> 32)); - return; - } - - pfatal("trying to set nblocks higher than representable"); - - return; + uint32_t flags; + + flags = fs2h32(dp->e2di_flags); + + if (nblock <= 0xffffffffULL) { + flags &= ~EXT2_HUGE_FILE; + dp->e2di_flags = h2fs32(flags); + dp->e2di_nblock = h2fs32(nblock); + return; + } + + sethuge(); + + if (nblock <= 0xffffffffffffULL) { + flags &= ~EXT2_HUGE_FILE; + dp->e2di_flags = h2fs32(flags); + dp->e2di_nblock = h2fs32(nblock); + dp->e2di_nblock_high = h2fs16((nblock >> 32)); + return; + } + + if (EXT2_DBTOFSB(&sblock, nblock) <= 0xffffffffffffULL) { + flags |= EXT2_HUGE_FILE; + dp->e2di_flags = h2fs32(flags); + dp->e2di_nblock = h2fs32(EXT2_DBTOFSB(&sblock, nblock)); + dp->e2di_nblock_high = h2fs16((EXT2_DBTOFSB(&sblock, nblock) >> 32)); + return; + } + + pfatal("trying to set nblocks higher than representable"); + + return; } diff --git a/cmd/extra/fsck.ext4/main.c b/cmd/extra/fsck.ext4/main.c @@ -83,65 +83,67 @@ __RCSID("$NetBSD: main.c,v 1.41 2020/04/05 15:25:39 joerg Exp $"); #include "fsutil.h" #include "exitvalues.h" -struct bufarea bufhead; -struct bufarea sblk; -struct bufarea asblk; -struct bufarea *pdirbp; -struct bufarea *pbp; -struct bufarea *getdatablk(daddr_t, long); -struct m_ext2fs sblock; -struct dups *duplist; -struct dups *muldup; -struct zlncnt *zlnhead; -struct inoinfo **inphead, **inpsort; -long numdirs, listmax, inplast; -long dev_bsize; -long secsize; -char nflag; -char yflag; -int bflag; -int Uflag; -int debug; -int preen; -char havesb; -char skipclean; -int fsmodified; -int fsreadfd; -int fswritefd; -int rerun; -daddr_t maxfsblock; -char *blockmap; -ino_t maxino; -ino_t lastino; -char *statemap; -u_char *typemap; -int16_t *lncntp; -ino_t lfdir; -daddr_t n_blks; -daddr_t n_files; -struct ext2fs_dinode zino; +struct bufarea bufhead; +struct bufarea sblk; +struct bufarea asblk; +struct bufarea *pdirbp; +struct bufarea *pbp; +struct bufarea *getdatablk(daddr_t, long); +struct m_ext2fs sblock; +struct dups *duplist; +struct dups *muldup; +struct zlncnt *zlnhead; +struct inoinfo **inphead, **inpsort; +long numdirs, listmax, inplast; +long dev_bsize; +long secsize; +char nflag; +char yflag; +int bflag; +int Uflag; +int debug; +int preen; +char havesb; +char skipclean; +int fsmodified; +int fsreadfd; +int fswritefd; +int rerun; +daddr_t maxfsblock; +char *blockmap; +ino_t maxino; +ino_t lastino; +char *statemap; +u_char *typemap; +int16_t *lncntp; +ino_t lfdir; +daddr_t n_blks; +daddr_t n_files; +struct ext2fs_dinode zino; -static int checkfilesys(const char *, char *, long, int); +static int checkfilesys(const char *, char *, long, int); static void usage(void) __dead; -int unresolved; +int unresolved; int main(int argc, char *argv[]) { - int result; + int result; - ARGBEGIN { - case 'n': - case 'f': - break; - default: - usage(); - } ARGEND - if (argc != 1) - usage(); - nflag = 1; - result = checkfilesys(argv[0], NULL, 0, 0); - return fshut(stdout, "<stdout>") ? FSCK_EXIT_CHECK_FAILED : result; + ARGBEGIN + { + case 'n': + case 'f': + break; + default: + usage(); + } + ARGEND + if (argc != 1) + usage(); + nflag = 1; + result = checkfilesys(argv[0], NULL, 0, 0); + return fshut(stdout, "<stdout>") ? FSCK_EXIT_CHECK_FAILED : result; } /* @@ -151,134 +153,132 @@ main(int argc, char *argv[]) static int checkfilesys(const char *filesys, char *mntpt, long auxdata, int child) { - daddr_t n_bfree; - struct dups *dp; - struct zlncnt *zlnp; - int i; + daddr_t n_bfree; + struct dups *dp; + struct zlncnt *zlnp; + int i; - if (preen && child) - (void)signal(SIGQUIT, voidquit); - setcdevname(filesys, preen); - if (debug && preen) - pwarn("starting\n"); - switch (setup(filesys)) { - case 0: - return FSCK_EXIT_CHECK_FAILED; - case -1: - return FSCK_EXIT_OK; - } - /* - * 1: scan inodes tallying blocks used - */ - if (preen == 0) { - if (sblock.e2fs.e2fs_rev > E2FS_REV0) { - printf("** Last Mounted on %.64s\n", - sblock.e2fs.e2fs_fsmnt); - } - printf("** Phase 1 - Check Blocks and Sizes\n"); - } - pass1(); + if (preen && child) + (void)signal(SIGQUIT, voidquit); + setcdevname(filesys, preen); + if (debug && preen) + pwarn("starting\n"); + switch (setup(filesys)) { + case 0: + return FSCK_EXIT_CHECK_FAILED; + case -1: + return FSCK_EXIT_OK; + } + /* + * 1: scan inodes tallying blocks used + */ + if (preen == 0) { + if (sblock.e2fs.e2fs_rev > E2FS_REV0) { + printf("** Last Mounted on %.64s\n", sblock.e2fs.e2fs_fsmnt); + } + printf("** Phase 1 - Check Blocks and Sizes\n"); + } + pass1(); - /* - * 1b: locate first references to duplicates, if any - */ - if (duplist) { - if (preen) - pfatal("INTERNAL ERROR: dups with -p"); - printf("** Phase 1b - Rescan For More DUPS\n"); - pass1b(); - } + /* + * 1b: locate first references to duplicates, if any + */ + if (duplist) { + if (preen) + pfatal("INTERNAL ERROR: dups with -p"); + printf("** Phase 1b - Rescan For More DUPS\n"); + pass1b(); + } - /* - * 2: traverse directories from root to mark all connected directories - */ - if (preen == 0) - printf("** Phase 2 - Check Pathnames\n"); - pass2(); + /* + * 2: traverse directories from root to mark all connected directories + */ + if (preen == 0) + printf("** Phase 2 - Check Pathnames\n"); + pass2(); - /* - * 3: scan inodes looking for disconnected directories - */ - if (preen == 0) - printf("** Phase 3 - Check Connectivity\n"); - pass3(); + /* + * 3: scan inodes looking for disconnected directories + */ + if (preen == 0) + printf("** Phase 3 - Check Connectivity\n"); + pass3(); - /* - * 4: scan inodes looking for disconnected files; check reference counts - */ - if (preen == 0) - printf("** Phase 4 - Check Reference Counts\n"); - pass4(); + /* + * 4: scan inodes looking for disconnected files; check reference counts + */ + if (preen == 0) + printf("** Phase 4 - Check Reference Counts\n"); + pass4(); - /* - * 5: check and repair resource counts in cylinder groups - */ - if (preen == 0) - printf("** Phase 5 - Check Cyl groups\n"); - pass5(); + /* + * 5: check and repair resource counts in cylinder groups + */ + if (preen == 0) + printf("** Phase 5 - Check Cyl groups\n"); + pass5(); - /* - * print out summary statistics - */ - n_bfree = sblock.e2fs.e2fs_fbcount; - - pwarn("%lld files, %lld used, %lld free\n", - (long long)n_files, (long long)n_blks, (long long)n_bfree); - if (debug && - /* 9 reserved and unused inodes in FS */ - (n_files -= maxino - 9 - sblock.e2fs.e2fs_ficount)) - printf("%lld files missing\n", (long long)n_files); - if (debug) { - for (i = 0; i < sblock.e2fs_ncg; i++) - n_blks += cgoverhead(i); - n_blks += sblock.e2fs.e2fs_first_dblock; - if (n_blks -= maxfsblock - n_bfree) - printf("%lld blocks missing\n", (long long)n_blks); - if (duplist != NULL) { - printf("The following duplicate blocks remain:"); - for (dp = duplist; dp; dp = dp->next) - printf(" %lld,", (long long)dp->dup); - printf("\n"); - } - if (zlnhead != NULL) { - printf("The following zero link count inodes remain:"); - for (zlnp = zlnhead; zlnp; zlnp = zlnp->next) - printf(" %llu,", - (unsigned long long)zlnp->zlncnt); - printf("\n"); - } - } - zlnhead = (struct zlncnt *)0; - duplist = (struct dups *)0; - muldup = (struct dups *)0; - inocleanup(); - if (fsmodified) { - time_t t; - (void)time(&t); - sblock.e2fs.e2fs_wtime = t; - sblock.e2fs.e2fs_lastfsck = t; - sbdirty(); - } - ckfini(1); - free(blockmap); - free(statemap); - free((char *)lncntp); - if (!fsmodified) - return unresolved ? FSCK_EXIT_UNRESOLVED : FSCK_EXIT_OK; - if (!preen) - printf("\n***** FILE SYSTEM WAS MODIFIED *****\n"); - if (rerun) - printf("\n***** PLEASE RERUN FSCK *****\n"); - return unresolved ? FSCK_EXIT_UNRESOLVED : FSCK_EXIT_OK; + /* + * print out summary statistics + */ + n_bfree = sblock.e2fs.e2fs_fbcount; + + pwarn( + "%lld files, %lld used, %lld free\n", + (long long)n_files, + (long long)n_blks, + (long long)n_bfree + ); + if (debug && + /* 9 reserved and unused inodes in FS */ + (n_files -= maxino - 9 - sblock.e2fs.e2fs_ficount)) + printf("%lld files missing\n", (long long)n_files); + if (debug) { + for (i = 0; i < sblock.e2fs_ncg; i++) + n_blks += cgoverhead(i); + n_blks += sblock.e2fs.e2fs_first_dblock; + if (n_blks -= maxfsblock - n_bfree) + printf("%lld blocks missing\n", (long long)n_blks); + if (duplist != NULL) { + printf("The following duplicate blocks remain:"); + for (dp = duplist; dp; dp = dp->next) + printf(" %lld,", (long long)dp->dup); + printf("\n"); + } + if (zlnhead != NULL) { + printf("The following zero link count inodes remain:"); + for (zlnp = zlnhead; zlnp; zlnp = zlnp->next) + printf(" %llu,", (unsigned long long)zlnp->zlncnt); + printf("\n"); + } + } + zlnhead = (struct zlncnt *)0; + duplist = (struct dups *)0; + muldup = (struct dups *)0; + inocleanup(); + if (fsmodified) { + time_t t; + (void)time(&t); + sblock.e2fs.e2fs_wtime = t; + sblock.e2fs.e2fs_lastfsck = t; + sbdirty(); + } + ckfini(1); + free(blockmap); + free(statemap); + free((char *)lncntp); + if (!fsmodified) + return unresolved ? FSCK_EXIT_UNRESOLVED : FSCK_EXIT_OK; + if (!preen) + printf("\n***** FILE SYSTEM WAS MODIFIED *****\n"); + if (rerun) + printf("\n***** PLEASE RERUN FSCK *****\n"); + return unresolved ? FSCK_EXIT_UNRESOLVED : FSCK_EXIT_OK; } static void usage(void) { - - (void) fprintf(stderr, - "usage: %s [-fn] filesystem\n", - getprogname()); - exit(FSCK_EXIT_USAGE); + (void)fprintf(stderr, "usage: %s [-fn] filesystem\n", getprogname()); + exit(FSCK_EXIT_USAGE); } - diff --git a/cmd/extra/fsck.ext4/pass1.c b/cmd/extra/fsck.ext4/pass1.c @@ -67,7 +67,6 @@ __RCSID("$NetBSD: pass1.c,v 1.26 2017/04/21 19:33:56 christos Exp $"); #include <ufs/ext2fs/ext2fs_dir.h> #include <ufs/ext2fs/ext2fs.h> - #include <stdio.h> #include <stdlib.h> #include <string.h> @@ -80,326 +79,315 @@ __RCSID("$NetBSD: pass1.c,v 1.26 2017/04/21 19:33:56 christos Exp $"); static daddr_t badblk; static daddr_t dupblk; -static void checkinode(ino_t, struct inodesc *); +static void checkinode(ino_t, struct inodesc *); void pass1(void) { - ino_t inumber; - int c, i; - size_t j; - daddr_t dbase; - struct inodesc idesc; - - /* - * Set file system reserved blocks in used block map. - */ - for (c = 0; c < sblock.e2fs_ncg; c++) { - dbase = c * sblock.e2fs.e2fs_bpg + - sblock.e2fs.e2fs_first_dblock; - /* Mark the blocks used for the inode table */ - if (fs2h32(sblock.e2fs_gd[c].ext2bgd_i_tables) >= dbase) { - for (i = 0; i < sblock.e2fs_itpg; i++) - setbmap( - fs2h32(sblock.e2fs_gd[c].ext2bgd_i_tables) - + i); - } - /* Mark the blocks used for the block bitmap */ - if (fs2h32(sblock.e2fs_gd[c].ext2bgd_b_bitmap) >= dbase) - setbmap(fs2h32(sblock.e2fs_gd[c].ext2bgd_b_bitmap)); - /* Mark the blocks used for the inode bitmap */ - if (fs2h32(sblock.e2fs_gd[c].ext2bgd_i_bitmap) >= dbase) - setbmap(fs2h32(sblock.e2fs_gd[c].ext2bgd_i_bitmap)); + ino_t inumber; + int c, i; + size_t j; + daddr_t dbase; + struct inodesc idesc; - if (sblock.e2fs.e2fs_rev == E2FS_REV0 || - (sblock.e2fs.e2fs_features_rocompat & - EXT2F_ROCOMPAT_SPARSESUPER) == 0 || - cg_has_sb(c)) { - /* Mark copuy of SB and descriptors */ - setbmap(dbase); - for (i = 1; i <= sblock.e2fs_ngdb; i++) - setbmap(dbase+i); - } + /* + * Set file system reserved blocks in used block map. + */ + for (c = 0; c < sblock.e2fs_ncg; c++) { + dbase = c * sblock.e2fs.e2fs_bpg + sblock.e2fs.e2fs_first_dblock; + /* Mark the blocks used for the inode table */ + if (fs2h32(sblock.e2fs_gd[c].ext2bgd_i_tables) >= dbase) { + for (i = 0; i < sblock.e2fs_itpg; i++) + setbmap(fs2h32(sblock.e2fs_gd[c].ext2bgd_i_tables) + i); + } + /* Mark the blocks used for the block bitmap */ + if (fs2h32(sblock.e2fs_gd[c].ext2bgd_b_bitmap) >= dbase) + setbmap(fs2h32(sblock.e2fs_gd[c].ext2bgd_b_bitmap)); + /* Mark the blocks used for the inode bitmap */ + if (fs2h32(sblock.e2fs_gd[c].ext2bgd_i_bitmap) >= dbase) + setbmap(fs2h32(sblock.e2fs_gd[c].ext2bgd_i_bitmap)); + if (sblock.e2fs.e2fs_rev == E2FS_REV0 + || (sblock.e2fs.e2fs_features_rocompat & EXT2F_ROCOMPAT_SPARSESUPER) == 0 || cg_has_sb(c)) { + /* Mark copuy of SB and descriptors */ + setbmap(dbase); + for (i = 1; i <= sblock.e2fs_ngdb; i++) + setbmap(dbase + i); + } - if (c == 0) { - for(i = 0; i < dbase; i++) - setbmap(i); - } - } + if (c == 0) { + for (i = 0; i < dbase; i++) + setbmap(i); + } + } - /* - * Find all allocated blocks. - */ - memset(&idesc, 0, sizeof(struct inodesc)); - idesc.id_type = ADDR; - idesc.id_func = pass1check; - inumber = 1; - n_files = n_blks = 0; - resetinodebuf(); - for (c = 0; c < sblock.e2fs_ncg; c++) { - for (j = 0; - j < sblock.e2fs.e2fs_ipg && inumber <= sblock.e2fs.e2fs_icount; - j++, inumber++) { - if (inumber < EXT2_ROOTINO) - continue; - checkinode(inumber, &idesc); - } - } - freeinodebuf(); + /* + * Find all allocated blocks. + */ + memset(&idesc, 0, sizeof(struct inodesc)); + idesc.id_type = ADDR; + idesc.id_func = pass1check; + inumber = 1; + n_files = n_blks = 0; + resetinodebuf(); + for (c = 0; c < sblock.e2fs_ncg; c++) { + for (j = 0; j < sblock.e2fs.e2fs_ipg && inumber <= sblock.e2fs.e2fs_icount; j++, inumber++) { + if (inumber < EXT2_ROOTINO) + continue; + checkinode(inumber, &idesc); + } + } + freeinodebuf(); } static void checkinode(ino_t inumber, struct inodesc *idesc) { - struct ext2fs_dinode *dp; - struct zlncnt *zlnp; - int ndb, j; - mode_t mode; + struct ext2fs_dinode *dp; + struct zlncnt *zlnp; + int ndb, j; + mode_t mode; - dp = getnextinode(inumber); - if (inumber == 8 && - (sblock.e2fs.e2fs_features_compat & EXT2F_COMPAT_HASJOURNAL)) { - if ((fs2h16(dp->e2di_mode) & IFMT) != IFREG) - errexit("invalid journal inode"); - idesc->id_number = inumber; - ckinode(dp, idesc); - return; - } - if (inumber < EXT2_FIRSTINO && - inumber != EXT2_ROOTINO && - !(inumber == EXT2_RESIZEINO && - (sblock.e2fs.e2fs_features_compat & EXT2F_COMPAT_RESIZE) != 0)) - return; + dp = getnextinode(inumber); + if (inumber == 8 && (sblock.e2fs.e2fs_features_compat & EXT2F_COMPAT_HASJOURNAL)) { + if ((fs2h16(dp->e2di_mode) & IFMT) != IFREG) + errexit("invalid journal inode"); + idesc->id_number = inumber; + ckinode(dp, idesc); + return; + } + if (inumber < EXT2_FIRSTINO && inumber != EXT2_ROOTINO + && !( + inumber == EXT2_RESIZEINO && (sblock.e2fs.e2fs_features_compat & EXT2F_COMPAT_RESIZE) != 0 + )) + return; - if (dp->e2di_mode && (dp->e2di_facl || dp->e2di_facl_high)) - errexit("inode %llu has an external attribute block", - (unsigned long long)inumber); + if (dp->e2di_mode && (dp->e2di_facl || dp->e2di_facl_high)) + errexit("inode %llu has an external attribute block", (unsigned long long)inumber); - mode = fs2h16(dp->e2di_mode) & IFMT; - if (mode == 0 || (dp->e2di_dtime != 0 && dp->e2di_nlink == 0)) { - if (mode == 0 && ( - memcmp(dp->e2di_blocks, zino.e2di_blocks, - (EXT2FS_NDADDR + EXT2FS_NIADDR) * sizeof(u_int32_t)) || - dp->e2di_mode || inosize(dp))) { - pfatal("PARTIALLY ALLOCATED INODE I=%llu", - (unsigned long long)inumber); - if (reply("CLEAR") == 1) { - dp = ginode(inumber); - clearinode(dp); - inodirty(); - } - } + mode = fs2h16(dp->e2di_mode) & IFMT; + if (mode == 0 || (dp->e2di_dtime != 0 && dp->e2di_nlink == 0)) { + if (mode == 0 + && (memcmp( + dp->e2di_blocks, + zino.e2di_blocks, + (EXT2FS_NDADDR + EXT2FS_NIADDR) * sizeof(u_int32_t) + ) + || dp->e2di_mode || inosize(dp))) { + pfatal("PARTIALLY ALLOCATED INODE I=%llu", (unsigned long long)inumber); + if (reply("CLEAR") == 1) { + dp = ginode(inumber); + clearinode(dp); + inodirty(); + } + } #ifdef notyet /* it seems that dtime == 0 is valid for a unallocated inode */ - if (dp->e2di_dtime == 0) { - pwarn("DELETED INODE I=%llu HAS A NULL DTIME", - (unsigned long long)inumber); - if (preen) { - printf(" (CORRECTED)\n"); - } - if (preen || reply("CORRECT")) { - time_t t; - time(&t); - dp->e2di_dtime = h2fs32(t); - dp = ginode(inumber); - inodirty(); - } - } + if (dp->e2di_dtime == 0) { + pwarn("DELETED INODE I=%llu HAS A NULL DTIME", (unsigned long long)inumber); + if (preen) { + printf(" (CORRECTED)\n"); + } + if (preen || reply("CORRECT")) { + time_t t; + time(&t); + dp->e2di_dtime = h2fs32(t); + dp = ginode(inumber); + inodirty(); + } + } #endif - statemap[inumber] = USTATE; - return; - } - lastino = inumber; - if (dp->e2di_dtime != 0) { - pwarn("INODE I=%llu HAS DTIME=%s", - (unsigned long long)inumber, - print_mtime(fs2h32(dp->e2di_dtime))); - if (preen) { - printf(" (CORRECTED)\n"); - } - if (preen || reply("CORRECT")) { - dp = ginode(inumber); - dp->e2di_dtime = 0; - inodirty(); - } - } - if (inosize(dp) + sblock.e2fs_bsize - 1 < inosize(dp)) { - if (debug) - printf("bad size %llu:", (unsigned long long)inosize(dp)); - goto unknown; - } - if (!preen && mode == IFMT && reply("HOLD BAD BLOCK") == 1) { - dp = ginode(inumber); - dp->e2di_mode = h2fs16(IFREG|0600); - inossize(dp, sblock.e2fs_bsize); - inodirty(); - } - ndb = howmany(inosize(dp), sblock.e2fs_bsize); - if (ndb < 0) { - if (debug) - printf("bad size %llu ndb %d:", - (unsigned long long)inosize(dp), ndb); - goto unknown; - } - if (mode == IFBLK || mode == IFCHR) - ndb++; - if (mode == IFLNK) { - /* - * Fake ndb value so direct/indirect block checks below - * will detect any garbage after symlink string. - */ - if (inosize(dp) < EXT2_MAXSYMLINKLEN || - (EXT2_MAXSYMLINKLEN == 0 && inonblock(dp) == 0)) { - ndb = howmany(inosize(dp), sizeof(u_int32_t)); - if (ndb > EXT2FS_NDADDR) { - j = ndb - EXT2FS_NDADDR; - for (ndb = 1; j > 1; j--) - ndb *= EXT2_NINDIR(&sblock); - ndb += EXT2FS_NDADDR; - } - } - } - /* Linux puts things in blocks for FIFO, so skip this check */ - if (mode != IFIFO) { - for (j = ndb; j < EXT2FS_NDADDR; j++) - if (dp->e2di_blocks[j] != 0) { - if (debug) - printf("bad direct addr: %d\n", - fs2h32(dp->e2di_blocks[j])); - goto unknown; - } - for (j = 0, ndb -= EXT2FS_NDADDR; ndb > 0; j++) - ndb /= EXT2_NINDIR(&sblock); - for (; j < EXT2FS_NIADDR; j++) { - if (dp->e2di_blocks[j+EXT2FS_NDADDR] != 0) { - if (debug) - printf("bad indirect addr: %d\n", - fs2h32(dp->e2di_blocks[j+EXT2FS_NDADDR])); - goto unknown; - } - } - } - if (ftypeok(dp) == 0) - goto unknown; - if (inumber >= EXT2_FIRSTINO || inumber == EXT2_ROOTINO) { - /* Don't count reserved inodes except root */ - n_files++; - } - lncntp[inumber] = fs2h16(dp->e2di_nlink); - if (dp->e2di_nlink == 0) { - zlnp = malloc(sizeof *zlnp); - if (zlnp == NULL) { - pfatal("LINK COUNT TABLE OVERFLOW"); - if (reply("CONTINUE") == 0) - exit(FSCK_EXIT_CHECK_FAILED); - } else { - zlnp->zlncnt = inumber; - zlnp->next = zlnhead; - zlnhead = zlnp; - } - } - if (mode == IFDIR) { - if (inosize(dp) == 0) - statemap[inumber] = DCLEAR; - else - statemap[inumber] = DSTATE; - cacheino(dp, inumber); - } else { - statemap[inumber] = FSTATE; - } - typemap[inumber] = E2IFTODT(mode); - badblk = dupblk = 0; - idesc->id_number = inumber; - (void)ckinode(dp, idesc); - idesc->id_entryno *= btodb(sblock.e2fs_bsize); - if (inonblock(dp) != (uint32_t)idesc->id_entryno) { - pwarn("INCORRECT BLOCK COUNT I=%llu (%llu should be %d)", - (unsigned long long)inumber, - (unsigned long long)inonblock(dp), - idesc->id_entryno); - if (preen) - printf(" (CORRECTED)\n"); - else if (reply("CORRECT") == 0) - return; - dp = ginode(inumber); - inosnblock(dp, idesc->id_entryno); - inodirty(); - } - return; + statemap[inumber] = USTATE; + return; + } + lastino = inumber; + if (dp->e2di_dtime != 0) { + pwarn( + "INODE I=%llu HAS DTIME=%s", + (unsigned long long)inumber, + print_mtime(fs2h32(dp->e2di_dtime)) + ); + if (preen) { + printf(" (CORRECTED)\n"); + } + if (preen || reply("CORRECT")) { + dp = ginode(inumber); + dp->e2di_dtime = 0; + inodirty(); + } + } + if (inosize(dp) + sblock.e2fs_bsize - 1 < inosize(dp)) { + if (debug) + printf("bad size %llu:", (unsigned long long)inosize(dp)); + goto unknown; + } + if (!preen && mode == IFMT && reply("HOLD BAD BLOCK") == 1) { + dp = ginode(inumber); + dp->e2di_mode = h2fs16(IFREG | 0600); + inossize(dp, sblock.e2fs_bsize); + inodirty(); + } + ndb = howmany(inosize(dp), sblock.e2fs_bsize); + if (ndb < 0) { + if (debug) + printf("bad size %llu ndb %d:", (unsigned long long)inosize(dp), ndb); + goto unknown; + } + if (mode == IFBLK || mode == IFCHR) + ndb++; + if (mode == IFLNK) { + /* + * Fake ndb value so direct/indirect block checks below + * will detect any garbage after symlink string. + */ + if (inosize(dp) < EXT2_MAXSYMLINKLEN || (EXT2_MAXSYMLINKLEN == 0 && inonblock(dp) == 0)) { + ndb = howmany(inosize(dp), sizeof(u_int32_t)); + if (ndb > EXT2FS_NDADDR) { + j = ndb - EXT2FS_NDADDR; + for (ndb = 1; j > 1; j--) + ndb *= EXT2_NINDIR(&sblock); + ndb += EXT2FS_NDADDR; + } + } + } + /* Linux puts things in blocks for FIFO, so skip this check */ + if (mode != IFIFO) { + for (j = ndb; j < EXT2FS_NDADDR; j++) + if (dp->e2di_blocks[j] != 0) { + if (debug) + printf("bad direct addr: %d\n", fs2h32(dp->e2di_blocks[j])); + goto unknown; + } + for (j = 0, ndb -= EXT2FS_NDADDR; ndb > 0; j++) + ndb /= EXT2_NINDIR(&sblock); + for (; j < EXT2FS_NIADDR; j++) { + if (dp->e2di_blocks[j + EXT2FS_NDADDR] != 0) { + if (debug) + printf("bad indirect addr: %d\n", fs2h32(dp->e2di_blocks[j + EXT2FS_NDADDR])); + goto unknown; + } + } + } + if (ftypeok(dp) == 0) + goto unknown; + if (inumber >= EXT2_FIRSTINO || inumber == EXT2_ROOTINO) { + /* Don't count reserved inodes except root */ + n_files++; + } + lncntp[inumber] = fs2h16(dp->e2di_nlink); + if (dp->e2di_nlink == 0) { + zlnp = malloc(sizeof *zlnp); + if (zlnp == NULL) { + pfatal("LINK COUNT TABLE OVERFLOW"); + if (reply("CONTINUE") == 0) + exit(FSCK_EXIT_CHECK_FAILED); + } else { + zlnp->zlncnt = inumber; + zlnp->next = zlnhead; + zlnhead = zlnp; + } + } + if (mode == IFDIR) { + if (inosize(dp) == 0) + statemap[inumber] = DCLEAR; + else + statemap[inumber] = DSTATE; + cacheino(dp, inumber); + } else { + statemap[inumber] = FSTATE; + } + typemap[inumber] = E2IFTODT(mode); + badblk = dupblk = 0; + idesc->id_number = inumber; + (void)ckinode(dp, idesc); + idesc->id_entryno *= btodb(sblock.e2fs_bsize); + if (inonblock(dp) != (uint32_t)idesc->id_entryno) { + pwarn( + "INCORRECT BLOCK COUNT I=%llu (%llu should be %d)", + (unsigned long long)inumber, + (unsigned long long)inonblock(dp), + idesc->id_entryno + ); + if (preen) + printf(" (CORRECTED)\n"); + else if (reply("CORRECT") == 0) + return; + dp = ginode(inumber); + inosnblock(dp, idesc->id_entryno); + inodirty(); + } + return; unknown: - pfatal("UNKNOWN FILE TYPE I=%llu", (unsigned long long)inumber); - statemap[inumber] = FCLEAR; - if (reply("CLEAR") == 1) { - statemap[inumber] = USTATE; - dp = ginode(inumber); - clearinode(dp); - inodirty(); - } + pfatal("UNKNOWN FILE TYPE I=%llu", (unsigned long long)inumber); + statemap[inumber] = FCLEAR; + if (reply("CLEAR") == 1) { + statemap[inumber] = USTATE; + dp = ginode(inumber); + clearinode(dp); + inodirty(); + } } int pass1check(struct inodesc *idesc) { - int res = KEEPON; - int anyout, nfrags; - daddr_t blkno = idesc->id_blkno; - struct dups *dlp; - struct dups *new; + int res = KEEPON; + int anyout, nfrags; + daddr_t blkno = idesc->id_blkno; + struct dups *dlp; + struct dups *new; - if ((anyout = chkrange(blkno, idesc->id_numfrags)) != 0) { - blkerror(idesc->id_number, "BAD", blkno); - if (badblk++ >= MAXBAD) { - pwarn("EXCESSIVE BAD BLKS I=%llu", - (unsigned long long)idesc->id_number); - if (preen) - printf(" (SKIPPING)\n"); - else if (reply("CONTINUE") == 0) - exit(FSCK_EXIT_CHECK_FAILED); - return (STOP); - } - } - for (nfrags = idesc->id_numfrags; nfrags > 0; blkno++, nfrags--) { - if (anyout && chkrange(blkno, 1)) { - res = SKIP; - } else if (!testbmap(blkno)) { - n_blks++; - setbmap(blkno); - } else { - blkerror(idesc->id_number, "DUP", blkno); - if (dupblk++ >= MAXDUP) { - pwarn("EXCESSIVE DUP BLKS I=%llu", - (unsigned long long)idesc->id_number); - if (preen) - printf(" (SKIPPING)\n"); - else if (reply("CONTINUE") == 0) - exit(FSCK_EXIT_CHECK_FAILED); - return (STOP); - } - new = malloc(sizeof(struct dups)); - if (new == NULL) { - pfatal("DUP TABLE OVERFLOW."); - if (reply("CONTINUE") == 0) - exit(FSCK_EXIT_CHECK_FAILED); - return (STOP); - } - new->dup = blkno; - if (muldup == 0) { - duplist = muldup = new; - new->next = 0; - } else { - new->next = muldup->next; - muldup->next = new; - } - for (dlp = duplist; dlp != muldup; dlp = dlp->next) - if (dlp->dup == blkno) - break; - if (dlp == muldup && dlp->dup != blkno) - muldup = new; - } - /* - * count the number of blocks found in id_entryno - */ - idesc->id_entryno++; - } - return (res); + if ((anyout = chkrange(blkno, idesc->id_numfrags)) != 0) { + blkerror(idesc->id_number, "BAD", blkno); + if (badblk++ >= MAXBAD) { + pwarn("EXCESSIVE BAD BLKS I=%llu", (unsigned long long)idesc->id_number); + if (preen) + printf(" (SKIPPING)\n"); + else if (reply("CONTINUE") == 0) + exit(FSCK_EXIT_CHECK_FAILED); + return (STOP); + } + } + for (nfrags = idesc->id_numfrags; nfrags > 0; blkno++, nfrags--) { + if (anyout && chkrange(blkno, 1)) { + res = SKIP; + } else if (!testbmap(blkno)) { + n_blks++; + setbmap(blkno); + } else { + blkerror(idesc->id_number, "DUP", blkno); + if (dupblk++ >= MAXDUP) { + pwarn("EXCESSIVE DUP BLKS I=%llu", (unsigned long long)idesc->id_number); + if (preen) + printf(" (SKIPPING)\n"); + else if (reply("CONTINUE") == 0) + exit(FSCK_EXIT_CHECK_FAILED); + return (STOP); + } + new = malloc(sizeof(struct dups)); + if (new == NULL) { + pfatal("DUP TABLE OVERFLOW."); + if (reply("CONTINUE") == 0) + exit(FSCK_EXIT_CHECK_FAILED); + return (STOP); + } + new->dup = blkno; + if (muldup == 0) { + duplist = muldup = new; + new->next = 0; + } else { + new->next = muldup->next; + muldup->next = new; + } + for (dlp = duplist; dlp != muldup; dlp = dlp->next) + if (dlp->dup == blkno) + break; + if (dlp == muldup && dlp->dup != blkno) + muldup = new; + } + /* + * count the number of blocks found in id_entryno + */ + idesc->id_entryno++; + } + return (res); } diff --git a/cmd/extra/fsck.ext4/pass1b.c b/cmd/extra/fsck.ext4/pass1b.c @@ -70,60 +70,59 @@ __RCSID("$NetBSD: pass1b.c,v 1.8 2009/10/19 18:41:08 bouyer Exp $"); #include "fsck.h" #include "extern.h" -static int pass1bcheck(struct inodesc *); -static struct dups *duphead; +static int pass1bcheck(struct inodesc *); +static struct dups *duphead; void pass1b(void) { - int c; - uint32_t i; - struct ext2fs_dinode *dp; - struct inodesc idesc; - ino_t inumber; + int c; + uint32_t i; + struct ext2fs_dinode *dp; + struct inodesc idesc; + ino_t inumber; - memset(&idesc, 0, sizeof(struct inodesc)); - idesc.id_type = ADDR; - idesc.id_func = pass1bcheck; - duphead = duplist; - inumber = 0; - for (c = 0; c < sblock.e2fs_ncg; c++) { - for (i = 0; i < sblock.e2fs.e2fs_ipg; i++, inumber++) { - if ((inumber < EXT2_FIRSTINO) && (inumber != EXT2_ROOTINO)) - continue; - dp = ginode(inumber); - if (dp == NULL) - continue; - idesc.id_number = inumber; - if (statemap[inumber] != USTATE && - (ckinode(dp, &idesc) & STOP)) - return; - } - } + memset(&idesc, 0, sizeof(struct inodesc)); + idesc.id_type = ADDR; + idesc.id_func = pass1bcheck; + duphead = duplist; + inumber = 0; + for (c = 0; c < sblock.e2fs_ncg; c++) { + for (i = 0; i < sblock.e2fs.e2fs_ipg; i++, inumber++) { + if ((inumber < EXT2_FIRSTINO) && (inumber != EXT2_ROOTINO)) + continue; + dp = ginode(inumber); + if (dp == NULL) + continue; + idesc.id_number = inumber; + if (statemap[inumber] != USTATE && (ckinode(dp, &idesc) & STOP)) + return; + } + } } static int pass1bcheck(struct inodesc *idesc) { - struct dups *dlp; - int nfrags, res = KEEPON; - daddr_t blkno = idesc->id_blkno; + struct dups *dlp; + int nfrags, res = KEEPON; + daddr_t blkno = idesc->id_blkno; - for (nfrags = idesc->id_numfrags; nfrags > 0; blkno++, nfrags--) { - if (chkrange(blkno, 1)) - res = SKIP; - for (dlp = duphead; dlp; dlp = dlp->next) { - if (dlp->dup == blkno) { - blkerror(idesc->id_number, "DUP", blkno); - dlp->dup = duphead->dup; - duphead->dup = blkno; - duphead = duphead->next; - } - if (dlp == muldup) - break; - } - if (muldup == 0 || duphead == muldup->next) - return (STOP); - } - return (res); + for (nfrags = idesc->id_numfrags; nfrags > 0; blkno++, nfrags--) { + if (chkrange(blkno, 1)) + res = SKIP; + for (dlp = duphead; dlp; dlp = dlp->next) { + if (dlp->dup == blkno) { + blkerror(idesc->id_number, "DUP", blkno); + dlp->dup = duphead->dup; + duphead->dup = blkno; + duphead = duphead->next; + } + if (dlp == muldup) + break; + } + if (muldup == 0 || duphead == muldup->next) + return (STOP); + } + return (res); } diff --git a/cmd/extra/fsck.ext4/pass2.c b/cmd/extra/fsck.ext4/pass2.c @@ -67,7 +67,6 @@ __RCSID("$NetBSD: pass2.c,v 1.15 2009/10/19 18:41:08 bouyer Exp $"); #include <ufs/ext2fs/ext2fs_dir.h> #include <ufs/ext2fs/ext2fs.h> - #include <stdio.h> #include <stdlib.h> #include <string.h> @@ -77,7 +76,7 @@ __RCSID("$NetBSD: pass2.c,v 1.15 2009/10/19 18:41:08 bouyer Exp $"); #include "extern.h" #include "exitvalues.h" -#define MINDIRSIZE (sizeof (struct ext2fs_dirtemplate)) +#define MINDIRSIZE (sizeof(struct ext2fs_dirtemplate)) static int pass2check(struct inodesc *); static int blksort(const void *, const void *); @@ -85,376 +84,357 @@ static int blksort(const void *, const void *); void pass2(void) { - struct ext2fs_dinode *dp; - struct inoinfo **inpp, *inp; - struct inoinfo **inpend; - struct inodesc curino; - struct ext2fs_dinode dino; - char pathbuf[MAXPATHLEN + 1]; - - switch (statemap[EXT2_ROOTINO]) { + struct ext2fs_dinode *dp; + struct inoinfo **inpp, *inp; + struct inoinfo **inpend; + struct inodesc curino; + struct ext2fs_dinode dino; + char pathbuf[MAXPATHLEN + 1]; - case USTATE: - pfatal("ROOT INODE UNALLOCATED"); - if (reply("ALLOCATE") == 0) - exit(FSCK_EXIT_CHECK_FAILED); - if (allocdir(EXT2_ROOTINO, EXT2_ROOTINO, 0755) != EXT2_ROOTINO) - errexit("CANNOT ALLOCATE ROOT INODE"); - break; + switch (statemap[EXT2_ROOTINO]) { + case USTATE: + pfatal("ROOT INODE UNALLOCATED"); + if (reply("ALLOCATE") == 0) + exit(FSCK_EXIT_CHECK_FAILED); + if (allocdir(EXT2_ROOTINO, EXT2_ROOTINO, 0755) != EXT2_ROOTINO) + errexit("CANNOT ALLOCATE ROOT INODE"); + break; - case DCLEAR: - pfatal("DUPS/BAD IN ROOT INODE"); - if (reply("REALLOCATE")) { - freeino(EXT2_ROOTINO); - if (allocdir(EXT2_ROOTINO, EXT2_ROOTINO, 0755) != EXT2_ROOTINO) - errexit("CANNOT ALLOCATE ROOT INODE"); - break; - } - if (reply("CONTINUE") == 0) - exit(FSCK_EXIT_CHECK_FAILED); - break; + case DCLEAR: + pfatal("DUPS/BAD IN ROOT INODE"); + if (reply("REALLOCATE")) { + freeino(EXT2_ROOTINO); + if (allocdir(EXT2_ROOTINO, EXT2_ROOTINO, 0755) != EXT2_ROOTINO) + errexit("CANNOT ALLOCATE ROOT INODE"); + break; + } + if (reply("CONTINUE") == 0) + exit(FSCK_EXIT_CHECK_FAILED); + break; - case FSTATE: - case FCLEAR: - pfatal("ROOT INODE NOT DIRECTORY"); - if (reply("REALLOCATE")) { - freeino(EXT2_ROOTINO); - if (allocdir(EXT2_ROOTINO, EXT2_ROOTINO, 0755) != EXT2_ROOTINO) - errexit("CANNOT ALLOCATE ROOT INODE"); - break; - } - if (reply("FIX") == 0) - exit(FSCK_EXIT_CHECK_FAILED); - dp = ginode(EXT2_ROOTINO); - dp->e2di_mode = h2fs16((fs2h16(dp->e2di_mode) & ~IFMT) | IFDIR); - inodirty(); - break; + case FSTATE: + case FCLEAR: + pfatal("ROOT INODE NOT DIRECTORY"); + if (reply("REALLOCATE")) { + freeino(EXT2_ROOTINO); + if (allocdir(EXT2_ROOTINO, EXT2_ROOTINO, 0755) != EXT2_ROOTINO) + errexit("CANNOT ALLOCATE ROOT INODE"); + break; + } + if (reply("FIX") == 0) + exit(FSCK_EXIT_CHECK_FAILED); + dp = ginode(EXT2_ROOTINO); + dp->e2di_mode = h2fs16((fs2h16(dp->e2di_mode) & ~IFMT) | IFDIR); + inodirty(); + break; - case DSTATE: - break; + case DSTATE: + break; - default: - errexit("BAD STATE %d FOR ROOT INODE", statemap[EXT2_ROOTINO]); - } + default: + errexit("BAD STATE %d FOR ROOT INODE", statemap[EXT2_ROOTINO]); + } - /* - * Sort the directory list into disk block order. - */ - qsort((char *)inpsort, (size_t)inplast, sizeof *inpsort, blksort); - /* - * Check the integrity of each directory. - */ - memset(&curino, 0, sizeof(struct inodesc)); - curino.id_type = DATA; - curino.id_func = pass2check; - inpend = &inpsort[inplast]; - for (inpp = inpsort; inpp < inpend; inpp++) { - inp = *inpp; - if (inp->i_isize == 0) - continue; - if (inp->i_isize < MINDIRSIZE) { - direrror(inp->i_number, "DIRECTORY TOO SHORT"); - inp->i_isize = roundup(MINDIRSIZE, sblock.e2fs_bsize); - if (reply("FIX") == 1) { - dp = ginode(inp->i_number); - inossize(dp, inp->i_isize); - inodirty(); - } - } else if ((inp->i_isize & (sblock.e2fs_bsize - 1)) != 0) { - getpathname(pathbuf, sizeof(pathbuf), inp->i_number, - inp->i_number); - pwarn("DIRECTORY %s: LENGTH %lu NOT MULTIPLE OF %d", - pathbuf, (u_long)inp->i_isize, sblock.e2fs_bsize); - if (preen) - printf(" (ADJUSTED)\n"); - inp->i_isize = roundup(inp->i_isize, sblock.e2fs_bsize); - if (preen || reply("ADJUST") == 1) { - dp = ginode(inp->i_number); - inossize(dp, inp->i_isize); - inodirty(); - } - } - memset(&dino, 0, sizeof(struct ext2fs_dinode)); - dino.e2di_mode = h2fs16(IFDIR); - inossize(&dino, inp->i_isize); - memcpy(&dino.e2di_blocks[0], &inp->i_blks[0], (size_t)inp->i_numblks); - curino.id_number = inp->i_number; - curino.id_parent = inp->i_parent; - (void)ckinode(&dino, &curino); - } - /* - * Now that the parents of all directories have been found, - * make another pass to verify the value of `..' - */ - for (inpp = inpsort; inpp < inpend; inpp++) { - inp = *inpp; - if (inp->i_parent == 0 || inp->i_isize == 0) - continue; - if (inp->i_dotdot == inp->i_parent || - inp->i_dotdot == (ino_t)-1) - continue; - if (inp->i_dotdot == 0) { - inp->i_dotdot = inp->i_parent; - fileerror(inp->i_parent, inp->i_number, "MISSING '..'"); - if (reply("FIX") == 0) - continue; - (void)makeentry(inp->i_number, inp->i_parent, ".."); - lncntp[inp->i_parent]--; - continue; - } - fileerror(inp->i_parent, inp->i_number, - "BAD INODE NUMBER FOR '..'"); - if (reply("FIX") == 0) - continue; - lncntp[inp->i_dotdot]++; - lncntp[inp->i_parent]--; - inp->i_dotdot = inp->i_parent; - (void)changeino(inp->i_number, "..", inp->i_parent); - } - /* - * Mark all the directories that can be found from the root. - */ - propagate(); + /* + * Sort the directory list into disk block order. + */ + qsort((char *)inpsort, (size_t)inplast, sizeof *inpsort, blksort); + /* + * Check the integrity of each directory. + */ + memset(&curino, 0, sizeof(struct inodesc)); + curino.id_type = DATA; + curino.id_func = pass2check; + inpend = &inpsort[inplast]; + for (inpp = inpsort; inpp < inpend; inpp++) { + inp = *inpp; + if (inp->i_isize == 0) + continue; + if (inp->i_isize < MINDIRSIZE) { + direrror(inp->i_number, "DIRECTORY TOO SHORT"); + inp->i_isize = roundup(MINDIRSIZE, sblock.e2fs_bsize); + if (reply("FIX") == 1) { + dp = ginode(inp->i_number); + inossize(dp, inp->i_isize); + inodirty(); + } + } else if ((inp->i_isize & (sblock.e2fs_bsize - 1)) != 0) { + getpathname(pathbuf, sizeof(pathbuf), inp->i_number, inp->i_number); + pwarn( + "DIRECTORY %s: LENGTH %lu NOT MULTIPLE OF %d", + pathbuf, + (u_long)inp->i_isize, + sblock.e2fs_bsize + ); + if (preen) + printf(" (ADJUSTED)\n"); + inp->i_isize = roundup(inp->i_isize, sblock.e2fs_bsize); + if (preen || reply("ADJUST") == 1) { + dp = ginode(inp->i_number); + inossize(dp, inp->i_isize); + inodirty(); + } + } + memset(&dino, 0, sizeof(struct ext2fs_dinode)); + dino.e2di_mode = h2fs16(IFDIR); + inossize(&dino, inp->i_isize); + memcpy(&dino.e2di_blocks[0], &inp->i_blks[0], (size_t)inp->i_numblks); + curino.id_number = inp->i_number; + curino.id_parent = inp->i_parent; + (void)ckinode(&dino, &curino); + } + /* + * Now that the parents of all directories have been found, + * make another pass to verify the value of `..' + */ + for (inpp = inpsort; inpp < inpend; inpp++) { + inp = *inpp; + if (inp->i_parent == 0 || inp->i_isize == 0) + continue; + if (inp->i_dotdot == inp->i_parent || inp->i_dotdot == (ino_t)-1) + continue; + if (inp->i_dotdot == 0) { + inp->i_dotdot = inp->i_parent; + fileerror(inp->i_parent, inp->i_number, "MISSING '..'"); + if (reply("FIX") == 0) + continue; + (void)makeentry(inp->i_number, inp->i_parent, ".."); + lncntp[inp->i_parent]--; + continue; + } + fileerror(inp->i_parent, inp->i_number, "BAD INODE NUMBER FOR '..'"); + if (reply("FIX") == 0) + continue; + lncntp[inp->i_dotdot]++; + lncntp[inp->i_parent]--; + inp->i_dotdot = inp->i_parent; + (void)changeino(inp->i_number, "..", inp->i_parent); + } + /* + * Mark all the directories that can be found from the root. + */ + propagate(); } static int pass2check(struct inodesc *idesc) { - struct ext2fs_direct *dirp = idesc->id_dirp; - struct inoinfo *inp; - int n, entrysize, ret = 0; - struct ext2fs_dinode *dp; - const char *errmsg; - struct ext2fs_direct proto; - char namebuf[MAXPATHLEN + 1]; - char pathbuf[MAXPATHLEN + 1]; + struct ext2fs_direct *dirp = idesc->id_dirp; + struct inoinfo *inp; + int n, entrysize, ret = 0; + struct ext2fs_dinode *dp; + const char *errmsg; + struct ext2fs_direct proto; + char namebuf[MAXPATHLEN + 1]; + char pathbuf[MAXPATHLEN + 1]; - /* - * check for "." - */ - if (idesc->id_entryno != 0) - goto chk1; - if (fs2h32(dirp->e2d_ino) != 0 && dirp->e2d_namlen == 1 && - dirp->e2d_name[0] == '.') { - if (fs2h32(dirp->e2d_ino) != idesc->id_number) { - direrror(idesc->id_number, "BAD INODE NUMBER FOR '.'"); - dirp->e2d_ino = h2fs32(idesc->id_number); - if (reply("FIX") == 1) - ret |= ALTERED; - } - if (sblock.e2fs.e2fs_rev > E2FS_REV0 && - (sblock.e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE) - && (dirp->e2d_type != EXT2_FT_DIR)) { - direrror(idesc->id_number, "BAD TYPE VALUE FOR '.'"); - dirp->e2d_type = EXT2_FT_DIR; - if (reply("FIX") == 1) - ret |= ALTERED; - } - goto chk1; - } - direrror(idesc->id_number, "MISSING '.'"); - proto.e2d_ino = h2fs32(idesc->id_number); - proto.e2d_namlen = 1; - if (sblock.e2fs.e2fs_rev > E2FS_REV0 && - (sblock.e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE)) - proto.e2d_type = EXT2_FT_DIR; - else - proto.e2d_type = 0; - (void)strlcpy(proto.e2d_name, ".", sizeof(proto.e2d_name)); - entrysize = EXT2FS_DIRSIZ(proto.e2d_namlen); - if (fs2h32(dirp->e2d_ino) != 0 && strcmp(dirp->e2d_name, "..") != 0) { - pfatal("CANNOT FIX, FIRST ENTRY IN DIRECTORY CONTAINS %s\n", - dirp->e2d_name); - } else if (fs2h16(dirp->e2d_reclen) < entrysize) { - pfatal("CANNOT FIX, INSUFFICIENT SPACE TO ADD '.'\n"); - } else if (fs2h16(dirp->e2d_reclen) < 2 * entrysize) { - proto.e2d_reclen = dirp->e2d_reclen; - memcpy(dirp, &proto, (size_t)entrysize); - if (reply("FIX") == 1) - ret |= ALTERED; - } else { - n = fs2h16(dirp->e2d_reclen) - entrysize; - proto.e2d_reclen = h2fs16(entrysize); - memcpy(dirp, &proto, (size_t)entrysize); - idesc->id_entryno++; - lncntp[fs2h32(dirp->e2d_ino)]--; - dirp = (struct ext2fs_direct *)((char *)(dirp) + entrysize); - memset(dirp, 0, (size_t)n); - dirp->e2d_reclen = h2fs16(n); - if (reply("FIX") == 1) - ret |= ALTERED; - } + /* + * check for "." + */ + if (idesc->id_entryno != 0) + goto chk1; + if (fs2h32(dirp->e2d_ino) != 0 && dirp->e2d_namlen == 1 && dirp->e2d_name[0] == '.') { + if (fs2h32(dirp->e2d_ino) != idesc->id_number) { + direrror(idesc->id_number, "BAD INODE NUMBER FOR '.'"); + dirp->e2d_ino = h2fs32(idesc->id_number); + if (reply("FIX") == 1) + ret |= ALTERED; + } + if (sblock.e2fs.e2fs_rev > E2FS_REV0 + && (sblock.e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE) + && (dirp->e2d_type != EXT2_FT_DIR)) { + direrror(idesc->id_number, "BAD TYPE VALUE FOR '.'"); + dirp->e2d_type = EXT2_FT_DIR; + if (reply("FIX") == 1) + ret |= ALTERED; + } + goto chk1; + } + direrror(idesc->id_number, "MISSING '.'"); + proto.e2d_ino = h2fs32(idesc->id_number); + proto.e2d_namlen = 1; + if (sblock.e2fs.e2fs_rev > E2FS_REV0 + && (sblock.e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE)) + proto.e2d_type = EXT2_FT_DIR; + else + proto.e2d_type = 0; + (void)strlcpy(proto.e2d_name, ".", sizeof(proto.e2d_name)); + entrysize = EXT2FS_DIRSIZ(proto.e2d_namlen); + if (fs2h32(dirp->e2d_ino) != 0 && strcmp(dirp->e2d_name, "..") != 0) { + pfatal("CANNOT FIX, FIRST ENTRY IN DIRECTORY CONTAINS %s\n", dirp->e2d_name); + } else if (fs2h16(dirp->e2d_reclen) < entrysize) { + pfatal("CANNOT FIX, INSUFFICIENT SPACE TO ADD '.'\n"); + } else if (fs2h16(dirp->e2d_reclen) < 2 * entrysize) { + proto.e2d_reclen = dirp->e2d_reclen; + memcpy(dirp, &proto, (size_t)entrysize); + if (reply("FIX") == 1) + ret |= ALTERED; + } else { + n = fs2h16(dirp->e2d_reclen) - entrysize; + proto.e2d_reclen = h2fs16(entrysize); + memcpy(dirp, &proto, (size_t)entrysize); + idesc->id_entryno++; + lncntp[fs2h32(dirp->e2d_ino)]--; + dirp = (struct ext2fs_direct *)((char *)(dirp) + entrysize); + memset(dirp, 0, (size_t)n); + dirp->e2d_reclen = h2fs16(n); + if (reply("FIX") == 1) + ret |= ALTERED; + } chk1: - if (idesc->id_entryno > 1) - goto chk2; - inp = getinoinfo(idesc->id_number); - proto.e2d_ino = h2fs32(inp->i_parent); - proto.e2d_namlen = 2; - if (sblock.e2fs.e2fs_rev > E2FS_REV0 && - (sblock.e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE)) - proto.e2d_type = EXT2_FT_DIR; - else - proto.e2d_type = 0; - (void)strlcpy(proto.e2d_name, "..", sizeof(proto.e2d_name)); - entrysize = EXT2FS_DIRSIZ(2); - if (idesc->id_entryno == 0) { - n = EXT2FS_DIRSIZ(dirp->e2d_namlen); - if (fs2h16(dirp->e2d_reclen) < n + entrysize) - goto chk2; - proto.e2d_reclen = h2fs16(fs2h16(dirp->e2d_reclen) - n); - dirp->e2d_reclen = h2fs16(n); - idesc->id_entryno++; - lncntp[fs2h32(dirp->e2d_ino)]--; - dirp = (struct ext2fs_direct *)((char *)(dirp) + n); - memset(dirp, 0, (size_t)fs2h16(proto.e2d_reclen)); - dirp->e2d_reclen = proto.e2d_reclen; - } - if (fs2h32(dirp->e2d_ino) != 0 && - dirp->e2d_namlen == 2 && - strncmp(dirp->e2d_name, "..", 2) == 0) { - inp->i_dotdot = fs2h32(dirp->e2d_ino); - if (sblock.e2fs.e2fs_rev > E2FS_REV0 && - (sblock.e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE) - && dirp->e2d_type != EXT2_FT_DIR) { - direrror(idesc->id_number, "BAD TYPE VALUE FOR '..'"); - dirp->e2d_type = EXT2_FT_DIR; - if (reply("FIX") == 1) - ret |= ALTERED; - } - goto chk2; - } - if (fs2h32(dirp->e2d_ino) != 0 && - dirp->e2d_namlen == 1 && - strncmp(dirp->e2d_name, ".", 1) != 0) { - fileerror(inp->i_parent, idesc->id_number, "MISSING '..'"); - pfatal("CANNOT FIX, SECOND ENTRY IN DIRECTORY CONTAINS %s\n", - dirp->e2d_name); - inp->i_dotdot = (ino_t)-1; - } else if (fs2h16(dirp->e2d_reclen) < entrysize) { - fileerror(inp->i_parent, idesc->id_number, "MISSING '..'"); - pfatal("CANNOT FIX, INSUFFICIENT SPACE TO ADD '..'\n"); - inp->i_dotdot = (ino_t)-1; - } else if (inp->i_parent != 0) { - /* - * We know the parent, so fix now. - */ - inp->i_dotdot = inp->i_parent; - fileerror(inp->i_parent, idesc->id_number, "MISSING '..'"); - proto.e2d_reclen = dirp->e2d_reclen; - memcpy(dirp, &proto, (size_t)entrysize); - if (reply("FIX") == 1) - ret |= ALTERED; - } - idesc->id_entryno++; - if (fs2h32(dirp->e2d_ino) != 0) - lncntp[fs2h32(dirp->e2d_ino)]--; - return (ret|KEEPON); + if (idesc->id_entryno > 1) + goto chk2; + inp = getinoinfo(idesc->id_number); + proto.e2d_ino = h2fs32(inp->i_parent); + proto.e2d_namlen = 2; + if (sblock.e2fs.e2fs_rev > E2FS_REV0 + && (sblock.e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE)) + proto.e2d_type = EXT2_FT_DIR; + else + proto.e2d_type = 0; + (void)strlcpy(proto.e2d_name, "..", sizeof(proto.e2d_name)); + entrysize = EXT2FS_DIRSIZ(2); + if (idesc->id_entryno == 0) { + n = EXT2FS_DIRSIZ(dirp->e2d_namlen); + if (fs2h16(dirp->e2d_reclen) < n + entrysize) + goto chk2; + proto.e2d_reclen = h2fs16(fs2h16(dirp->e2d_reclen) - n); + dirp->e2d_reclen = h2fs16(n); + idesc->id_entryno++; + lncntp[fs2h32(dirp->e2d_ino)]--; + dirp = (struct ext2fs_direct *)((char *)(dirp) + n); + memset(dirp, 0, (size_t)fs2h16(proto.e2d_reclen)); + dirp->e2d_reclen = proto.e2d_reclen; + } + if (fs2h32(dirp->e2d_ino) != 0 && dirp->e2d_namlen == 2 + && strncmp(dirp->e2d_name, "..", 2) == 0) { + inp->i_dotdot = fs2h32(dirp->e2d_ino); + if (sblock.e2fs.e2fs_rev > E2FS_REV0 + && (sblock.e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE) + && dirp->e2d_type != EXT2_FT_DIR) { + direrror(idesc->id_number, "BAD TYPE VALUE FOR '..'"); + dirp->e2d_type = EXT2_FT_DIR; + if (reply("FIX") == 1) + ret |= ALTERED; + } + goto chk2; + } + if (fs2h32(dirp->e2d_ino) != 0 && dirp->e2d_namlen == 1 && strncmp(dirp->e2d_name, ".", 1) != 0) { + fileerror(inp->i_parent, idesc->id_number, "MISSING '..'"); + pfatal("CANNOT FIX, SECOND ENTRY IN DIRECTORY CONTAINS %s\n", dirp->e2d_name); + inp->i_dotdot = (ino_t)-1; + } else if (fs2h16(dirp->e2d_reclen) < entrysize) { + fileerror(inp->i_parent, idesc->id_number, "MISSING '..'"); + pfatal("CANNOT FIX, INSUFFICIENT SPACE TO ADD '..'\n"); + inp->i_dotdot = (ino_t)-1; + } else if (inp->i_parent != 0) { + /* + * We know the parent, so fix now. + */ + inp->i_dotdot = inp->i_parent; + fileerror(inp->i_parent, idesc->id_number, "MISSING '..'"); + proto.e2d_reclen = dirp->e2d_reclen; + memcpy(dirp, &proto, (size_t)entrysize); + if (reply("FIX") == 1) + ret |= ALTERED; + } + idesc->id_entryno++; + if (fs2h32(dirp->e2d_ino) != 0) + lncntp[fs2h32(dirp->e2d_ino)]--; + return (ret | KEEPON); chk2: - if (fs2h32(dirp->e2d_ino) == 0) - return (ret|KEEPON); - if (dirp->e2d_namlen <= 2 && - dirp->e2d_name[0] == '.' && - idesc->id_entryno >= 2) { - if (dirp->e2d_namlen == 1) { - direrror(idesc->id_number, "EXTRA '.' ENTRY"); - dirp->e2d_ino = 0; - if (reply("FIX") == 1) - ret |= ALTERED; - return (KEEPON | ret); - } - if (dirp->e2d_name[1] == '.') { - direrror(idesc->id_number, "EXTRA '..' ENTRY"); - dirp->e2d_ino = 0; - if (reply("FIX") == 1) - ret |= ALTERED; - return (KEEPON | ret); - } - } - idesc->id_entryno++; - n = 0; - if (fs2h32(dirp->e2d_ino) > maxino || - (fs2h32(dirp->e2d_ino) < EXT2_FIRSTINO && - fs2h32(dirp->e2d_ino) != EXT2_ROOTINO)) { - fileerror(idesc->id_number, fs2h32(dirp->e2d_ino), "I OUT OF RANGE"); - n = reply("REMOVE"); - } else { -again: - switch (statemap[fs2h32(dirp->e2d_ino)]) { - case USTATE: - if (idesc->id_entryno <= 2) - break; - fileerror(idesc->id_number, fs2h32(dirp->e2d_ino), "UNALLOCATED"); - n = reply("REMOVE"); - break; + if (fs2h32(dirp->e2d_ino) == 0) + return (ret | KEEPON); + if (dirp->e2d_namlen <= 2 && dirp->e2d_name[0] == '.' && idesc->id_entryno >= 2) { + if (dirp->e2d_namlen == 1) { + direrror(idesc->id_number, "EXTRA '.' ENTRY"); + dirp->e2d_ino = 0; + if (reply("FIX") == 1) + ret |= ALTERED; + return (KEEPON | ret); + } + if (dirp->e2d_name[1] == '.') { + direrror(idesc->id_number, "EXTRA '..' ENTRY"); + dirp->e2d_ino = 0; + if (reply("FIX") == 1) + ret |= ALTERED; + return (KEEPON | ret); + } + } + idesc->id_entryno++; + n = 0; + if (fs2h32(dirp->e2d_ino) > maxino + || (fs2h32(dirp->e2d_ino) < EXT2_FIRSTINO && fs2h32(dirp->e2d_ino) != EXT2_ROOTINO)) { + fileerror(idesc->id_number, fs2h32(dirp->e2d_ino), "I OUT OF RANGE"); + n = reply("REMOVE"); + } else { + again: + switch (statemap[fs2h32(dirp->e2d_ino)]) { + case USTATE: + if (idesc->id_entryno <= 2) + break; + fileerror(idesc->id_number, fs2h32(dirp->e2d_ino), "UNALLOCATED"); + n = reply("REMOVE"); + break; - case DCLEAR: - case FCLEAR: - if (idesc->id_entryno <= 2) - break; - if (statemap[fs2h32(dirp->e2d_ino)] == FCLEAR) - errmsg = "DUP/BAD"; - else if (!preen) - errmsg = "ZERO LENGTH DIRECTORY"; - else { - n = 1; - break; - } - fileerror(idesc->id_number, fs2h32(dirp->e2d_ino), errmsg); - if ((n = reply("REMOVE")) == 1) - break; - dp = ginode(fs2h32(dirp->e2d_ino)); - statemap[fs2h32(dirp->e2d_ino)] = - (fs2h16(dp->e2di_mode) & IFMT) == IFDIR ? DSTATE : FSTATE; - lncntp[fs2h32(dirp->e2d_ino)] = fs2h16(dp->e2di_nlink); - goto again; + case DCLEAR: + case FCLEAR: + if (idesc->id_entryno <= 2) + break; + if (statemap[fs2h32(dirp->e2d_ino)] == FCLEAR) + errmsg = "DUP/BAD"; + else if (!preen) + errmsg = "ZERO LENGTH DIRECTORY"; + else { + n = 1; + break; + } + fileerror(idesc->id_number, fs2h32(dirp->e2d_ino), errmsg); + if ((n = reply("REMOVE")) == 1) + break; + dp = ginode(fs2h32(dirp->e2d_ino)); + statemap[fs2h32(dirp->e2d_ino)] = (fs2h16(dp->e2di_mode) & IFMT) == IFDIR ? DSTATE : FSTATE; + lncntp[fs2h32(dirp->e2d_ino)] = fs2h16(dp->e2di_nlink); + goto again; - case DSTATE: - case DFOUND: - inp = getinoinfo(fs2h32(dirp->e2d_ino)); - if (inp->i_parent != 0 && idesc->id_entryno > 2) { - getpathname(pathbuf, sizeof(pathbuf), - idesc->id_number, idesc->id_number); - getpathname(namebuf, sizeof(namebuf), - fs2h32(dirp->e2d_ino), - fs2h32(dirp->e2d_ino)); - pwarn("%s %s %s\n", pathbuf, - "IS AN EXTRANEOUS HARD LINK TO DIRECTORY", - namebuf); - if (preen) - printf(" (IGNORED)\n"); - else if ((n = reply("REMOVE")) == 1) - break; - } - if (idesc->id_entryno > 2) - inp->i_parent = idesc->id_number; - /* fall through */ + case DSTATE: + case DFOUND: + inp = getinoinfo(fs2h32(dirp->e2d_ino)); + if (inp->i_parent != 0 && idesc->id_entryno > 2) { + getpathname(pathbuf, sizeof(pathbuf), idesc->id_number, idesc->id_number); + getpathname(namebuf, sizeof(namebuf), fs2h32(dirp->e2d_ino), fs2h32(dirp->e2d_ino)); + pwarn("%s %s %s\n", pathbuf, "IS AN EXTRANEOUS HARD LINK TO DIRECTORY", namebuf); + if (preen) + printf(" (IGNORED)\n"); + else if ((n = reply("REMOVE")) == 1) + break; + } + if (idesc->id_entryno > 2) + inp->i_parent = idesc->id_number; + /* fall through */ - case FSTATE: - if (sblock.e2fs.e2fs_rev > E2FS_REV0 && - (sblock.e2fs.e2fs_features_incompat & - EXT2F_INCOMPAT_FTYPE) && - dirp->e2d_type != - inot2ext2dt(typemap[fs2h32(dirp->e2d_ino)])) { - dirp->e2d_type = - inot2ext2dt(typemap[fs2h32(dirp->e2d_ino)]); - fileerror(idesc->id_number, - fs2h32(dirp->e2d_ino), - "BAD TYPE VALUE"); - if (reply("FIX") == 1) - ret |= ALTERED; - } - lncntp[fs2h32(dirp->e2d_ino)]--; - break; + case FSTATE: + if (sblock.e2fs.e2fs_rev > E2FS_REV0 + && (sblock.e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_FTYPE) + && dirp->e2d_type != inot2ext2dt(typemap[fs2h32(dirp->e2d_ino)])) { + dirp->e2d_type = inot2ext2dt(typemap[fs2h32(dirp->e2d_ino)]); + fileerror(idesc->id_number, fs2h32(dirp->e2d_ino), "BAD TYPE VALUE"); + if (reply("FIX") == 1) + ret |= ALTERED; + } + lncntp[fs2h32(dirp->e2d_ino)]--; + break; - default: - errexit("BAD STATE %d FOR INODE I=%d", - statemap[fs2h32(dirp->e2d_ino)], fs2h32(dirp->e2d_ino)); - } - } - if (n == 0) - return (ret|KEEPON); - dirp->e2d_ino = 0; - return (ret|KEEPON|ALTERED); + default: + errexit( + "BAD STATE %d FOR INODE I=%d", statemap[fs2h32(dirp->e2d_ino)], fs2h32(dirp->e2d_ino) + ); + } + } + if (n == 0) + return (ret | KEEPON); + dirp->e2d_ino = 0; + return (ret | KEEPON | ALTERED); } /* @@ -463,6 +443,8 @@ again: static int blksort(const void *inpp1, const void *inpp2) { - return ((* (const struct inoinfo * const*) inpp1)->i_blks[0] - - (* (const struct inoinfo * const*) inpp2)->i_blks[0]); + return ( + (*(const struct inoinfo *const *)inpp1)->i_blks[0] + - (*(const struct inoinfo *const *)inpp2)->i_blks[0] + ); } diff --git a/cmd/extra/fsck.ext4/pass3.c b/cmd/extra/fsck.ext4/pass3.c @@ -71,29 +71,26 @@ __RCSID("$NetBSD: pass3.c,v 1.7 2009/10/19 18:41:08 bouyer Exp $"); void pass3(void) { - struct inoinfo **inpp, *inp; - ino_t orphan; - int loopcnt; + struct inoinfo **inpp, *inp; + ino_t orphan; + int loopcnt; - for (inpp = &inpsort[inplast - 1]; inpp >= inpsort; inpp--) { - inp = *inpp; - if (inp->i_number == EXT2_ROOTINO || - !(inp->i_parent == 0 || statemap[inp->i_number] == DSTATE)) - continue; - if (statemap[inp->i_number] == DCLEAR) - continue; - for (loopcnt = 0; ; loopcnt++) { - orphan = inp->i_number; - if (inp->i_parent == 0 || - statemap[inp->i_parent] != DSTATE || - loopcnt > numdirs) - break; - inp = getinoinfo(inp->i_parent); - } - (void)linkup(orphan, inp->i_dotdot); - inp->i_parent = inp->i_dotdot = lfdir; - lncntp[lfdir]--; - statemap[orphan] = DFOUND; - propagate(); - } + for (inpp = &inpsort[inplast - 1]; inpp >= inpsort; inpp--) { + inp = *inpp; + if (inp->i_number == EXT2_ROOTINO || !(inp->i_parent == 0 || statemap[inp->i_number] == DSTATE)) + continue; + if (statemap[inp->i_number] == DCLEAR) + continue; + for (loopcnt = 0;; loopcnt++) { + orphan = inp->i_number; + if (inp->i_parent == 0 || statemap[inp->i_parent] != DSTATE || loopcnt > numdirs) + break; + inp = getinoinfo(inp->i_parent); + } + (void)linkup(orphan, inp->i_dotdot); + inp->i_parent = inp->i_dotdot = lfdir; + lncntp[lfdir]--; + statemap[orphan] = DFOUND; + propagate(); + } } diff --git a/cmd/extra/fsck.ext4/pass4.c b/cmd/extra/fsck.ext4/pass4.c @@ -75,89 +75,87 @@ __RCSID("$NetBSD: pass4.c,v 1.10 2009/10/19 18:41:08 bouyer Exp $"); void pass4(void) { - ino_t inumber; - struct zlncnt *zlnp; - struct ext2fs_dinode *dp; - struct inodesc idesc; - int n; + ino_t inumber; + struct zlncnt *zlnp; + struct ext2fs_dinode *dp; + struct inodesc idesc; + int n; - memset(&idesc, 0, sizeof(struct inodesc)); - idesc.id_type = ADDR; - idesc.id_func = pass4check; - for (inumber = EXT2_ROOTINO; inumber <= lastino; inumber++) { - if (inumber < EXT2_FIRSTINO && inumber > EXT2_ROOTINO) - continue; - idesc.id_number = inumber; - switch (statemap[inumber]) { + memset(&idesc, 0, sizeof(struct inodesc)); + idesc.id_type = ADDR; + idesc.id_func = pass4check; + for (inumber = EXT2_ROOTINO; inumber <= lastino; inumber++) { + if (inumber < EXT2_FIRSTINO && inumber > EXT2_ROOTINO) + continue; + idesc.id_number = inumber; + switch (statemap[inumber]) { + case FSTATE: + case DFOUND: + n = lncntp[inumber]; + if (n) + adjust(&idesc, (short)n); + else { + for (zlnp = zlnhead; zlnp; zlnp = zlnp->next) + if (zlnp->zlncnt == inumber) { + zlnp->zlncnt = zlnhead->zlncnt; + zlnp = zlnhead; + zlnhead = zlnhead->next; + free((char *)zlnp); + clri(&idesc, "UNREF", 1); + break; + } + } + break; - case FSTATE: - case DFOUND: - n = lncntp[inumber]; - if (n) - adjust(&idesc, (short)n); - else { - for (zlnp = zlnhead; zlnp; zlnp = zlnp->next) - if (zlnp->zlncnt == inumber) { - zlnp->zlncnt = zlnhead->zlncnt; - zlnp = zlnhead; - zlnhead = zlnhead->next; - free((char *)zlnp); - clri(&idesc, "UNREF", 1); - break; - } - } - break; + case DSTATE: + clri(&idesc, "UNREF", 1); + break; - case DSTATE: - clri(&idesc, "UNREF", 1); - break; + case DCLEAR: + dp = ginode(inumber); + if (inosize(dp) == 0) { + clri(&idesc, "ZERO LENGTH", 1); + break; + } + /* fall through */ + case FCLEAR: + clri(&idesc, "BAD/DUP", 1); + break; - case DCLEAR: - dp = ginode(inumber); - if (inosize(dp) == 0) { - clri(&idesc, "ZERO LENGTH", 1); - break; - } - /* fall through */ - case FCLEAR: - clri(&idesc, "BAD/DUP", 1); - break; + case USTATE: + break; - case USTATE: - break; - - default: - errexit("BAD STATE %d FOR INODE I=%llu", - statemap[inumber], (unsigned long long)inumber); - } - } + default: + errexit("BAD STATE %d FOR INODE I=%llu", statemap[inumber], (unsigned long long)inumber); + } + } } int pass4check(struct inodesc *idesc) { - struct dups *dlp; - int nfrags, res = KEEPON; - daddr_t blkno = idesc->id_blkno; + struct dups *dlp; + int nfrags, res = KEEPON; + daddr_t blkno = idesc->id_blkno; - for (nfrags = idesc->id_numfrags; nfrags > 0; blkno++, nfrags--) { - if (chkrange(blkno, 1)) { - res = SKIP; - } else if (testbmap(blkno)) { - for (dlp = duplist; dlp; dlp = dlp->next) { - if (dlp->dup != blkno) - continue; - dlp->dup = duplist->dup; - dlp = duplist; - duplist = duplist->next; - free((char *)dlp); - break; - } - if (dlp == 0) { - clrbmap(blkno); - n_blks--; - } - } - } - return (res); + for (nfrags = idesc->id_numfrags; nfrags > 0; blkno++, nfrags--) { + if (chkrange(blkno, 1)) { + res = SKIP; + } else if (testbmap(blkno)) { + for (dlp = duplist; dlp; dlp = dlp->next) { + if (dlp->dup != blkno) + continue; + dlp->dup = duplist->dup; + dlp = duplist; + duplist = duplist->next; + free((char *)dlp); + break; + } + if (dlp == 0) { + clrbmap(blkno); + n_blks--; + } + } + } + return (res); } diff --git a/cmd/extra/fsck.ext4/pass5.c b/cmd/extra/fsck.ext4/pass5.c @@ -74,202 +74,190 @@ __RCSID("$NetBSD: pass5.c,v 1.20 2012/08/26 09:33:18 dholland Exp $"); #include "fsck.h" #include "extern.h" - static void print_bmap(char *, uint32_t); void pass5(void) { - int c; - struct m_ext2fs *fs = &sblock; - daddr_t dbase, dmax; - daddr_t d; - uint32_t i, j; - struct inodesc idesc[3]; - struct bufarea *ino_bitmap = NULL, *blk_bitmap = NULL; - char *ibmap, *bbmap; - u_int32_t cs_ndir, cs_nbfree, cs_nifree; - char msg[255]; - - cs_ndir = 0; - cs_nbfree = 0; - cs_nifree = 0; - - ibmap = malloc(fs->e2fs_bsize); - bbmap = malloc(fs->e2fs_bsize); - if (ibmap == NULL || bbmap == NULL) { - errexit("out of memory"); - } - - for (c = 0; c < fs->e2fs_ncg; c++) { - u_int32_t nbfree = 0; - u_int32_t nifree = 0; - u_int32_t ndirs = 0; + int c; + struct m_ext2fs *fs = &sblock; + daddr_t dbase, dmax; + daddr_t d; + uint32_t i, j; + struct inodesc idesc[3]; + struct bufarea *ino_bitmap = NULL, *blk_bitmap = NULL; + char *ibmap, *bbmap; + u_int32_t cs_ndir, cs_nbfree, cs_nifree; + char msg[255]; - nbfree = 0; - nifree = fs->e2fs.e2fs_ipg; - ndirs = 0; + cs_ndir = 0; + cs_nbfree = 0; + cs_nifree = 0; - if (blk_bitmap == NULL) { - blk_bitmap = getdatablk(fs2h32(fs->e2fs_gd[c].ext2bgd_b_bitmap), - fs->e2fs_bsize); - } else { - getblk(blk_bitmap, fs2h32(fs->e2fs_gd[c].ext2bgd_b_bitmap), - fs->e2fs_bsize); - } - if (ino_bitmap == NULL) { - ino_bitmap = getdatablk(fs2h32(fs->e2fs_gd[c].ext2bgd_i_bitmap), - fs->e2fs_bsize); - } else { - getblk(ino_bitmap, fs2h32(fs->e2fs_gd[c].ext2bgd_i_bitmap), - fs->e2fs_bsize); - } - memset(bbmap, 0, fs->e2fs_bsize); - memset(ibmap, 0, fs->e2fs_bsize); - memset(&idesc[0], 0, sizeof idesc); - for (i = 0; i < 3; i++) { - idesc[i].id_type = ADDR; - } + ibmap = malloc(fs->e2fs_bsize); + bbmap = malloc(fs->e2fs_bsize); + if (ibmap == NULL || bbmap == NULL) { + errexit("out of memory"); + } - j = fs->e2fs.e2fs_ipg * c + 1; + for (c = 0; c < fs->e2fs_ncg; c++) { + u_int32_t nbfree = 0; + u_int32_t nifree = 0; + u_int32_t ndirs = 0; - for (i = 0; i < fs->e2fs.e2fs_ipg; j++, i++) { - if ((j < EXT2_FIRSTINO) && (j != EXT2_ROOTINO)) { - setbit(ibmap, i); - nifree--; - continue; - } - if (j > fs->e2fs.e2fs_icount) { - setbit(ibmap, i); - continue; - } - switch (statemap[j]) { + nbfree = 0; + nifree = fs->e2fs.e2fs_ipg; + ndirs = 0; - case USTATE: - break; + if (blk_bitmap == NULL) { + blk_bitmap = getdatablk(fs2h32(fs->e2fs_gd[c].ext2bgd_b_bitmap), fs->e2fs_bsize); + } else { + getblk(blk_bitmap, fs2h32(fs->e2fs_gd[c].ext2bgd_b_bitmap), fs->e2fs_bsize); + } + if (ino_bitmap == NULL) { + ino_bitmap = getdatablk(fs2h32(fs->e2fs_gd[c].ext2bgd_i_bitmap), fs->e2fs_bsize); + } else { + getblk(ino_bitmap, fs2h32(fs->e2fs_gd[c].ext2bgd_i_bitmap), fs->e2fs_bsize); + } + memset(bbmap, 0, fs->e2fs_bsize); + memset(ibmap, 0, fs->e2fs_bsize); + memset(&idesc[0], 0, sizeof idesc); + for (i = 0; i < 3; i++) { + idesc[i].id_type = ADDR; + } - case DSTATE: - case DCLEAR: - case DFOUND: - ndirs++; - /* fall through */ + j = fs->e2fs.e2fs_ipg * c + 1; - case FSTATE: - case FCLEAR: - nifree--; - setbit(ibmap, i); - break; + for (i = 0; i < fs->e2fs.e2fs_ipg; j++, i++) { + if ((j < EXT2_FIRSTINO) && (j != EXT2_ROOTINO)) { + setbit(ibmap, i); + nifree--; + continue; + } + if (j > fs->e2fs.e2fs_icount) { + setbit(ibmap, i); + continue; + } + switch (statemap[j]) { + case USTATE: + break; - default: - errexit("BAD STATE %d FOR INODE I=%"PRIu32, - statemap[j], j); - } - } + case DSTATE: + case DCLEAR: + case DFOUND: + ndirs++; + /* fall through */ - /* fill in unused par of the inode map */ - for (i = fs->e2fs.e2fs_ipg / NBBY; i < (uint32_t)fs->e2fs_bsize; i++) - ibmap[i] = 0xff; + case FSTATE: + case FCLEAR: + nifree--; + setbit(ibmap, i); + break; - dbase = c * sblock.e2fs.e2fs_bpg + - sblock.e2fs.e2fs_first_dblock; - dmax = (daddr_t)(c+1) * sblock.e2fs.e2fs_bpg + - sblock.e2fs.e2fs_first_dblock; + default: + errexit("BAD STATE %d FOR INODE I=%" PRIu32, statemap[j], j); + } + } - for (i = 0, d = dbase; - d < dmax; - d ++, i ++) { - if (d >= sblock.e2fs.e2fs_bcount || testbmap(d)) { - setbit(bbmap, i); - continue; - } else { - nbfree++; - } + /* fill in unused par of the inode map */ + for (i = fs->e2fs.e2fs_ipg / NBBY; i < (uint32_t)fs->e2fs_bsize; i++) + ibmap[i] = 0xff; - } - cs_nbfree += nbfree; - cs_nifree += nifree; - cs_ndir += ndirs; + dbase = c * sblock.e2fs.e2fs_bpg + sblock.e2fs.e2fs_first_dblock; + dmax = (daddr_t)(c + 1) * sblock.e2fs.e2fs_bpg + sblock.e2fs.e2fs_first_dblock; - if (debug && (fs2h16(fs->e2fs_gd[c].ext2bgd_nbfree) != nbfree || - fs2h16(fs->e2fs_gd[c].ext2bgd_nifree) != nifree || - fs2h16(fs->e2fs_gd[c].ext2bgd_ndirs) != ndirs)) { - printf("summary info for cg %d is %d, %d, %d," - "should be %d, %d, %d\n", c, - fs2h16(fs->e2fs_gd[c].ext2bgd_nbfree), - fs2h16(fs->e2fs_gd[c].ext2bgd_nifree), - fs2h16(fs->e2fs_gd[c].ext2bgd_ndirs), - nbfree, - nifree, - ndirs); - } - (void)snprintf(msg, sizeof(msg), - "SUMMARY INFORMATIONS WRONG FOR CG #%d", c); - if ((fs2h16(fs->e2fs_gd[c].ext2bgd_nbfree) != nbfree || - fs2h16(fs->e2fs_gd[c].ext2bgd_nifree) != nifree || - fs2h16(fs->e2fs_gd[c].ext2bgd_ndirs) != ndirs) && - dofix(&idesc[0], msg)) { - fs->e2fs_gd[c].ext2bgd_nbfree = h2fs16(nbfree); - fs->e2fs_gd[c].ext2bgd_nifree = h2fs16(nifree); - fs->e2fs_gd[c].ext2bgd_ndirs = h2fs16(ndirs); - sbdirty(); - } + for (i = 0, d = dbase; d < dmax; d++, i++) { + if (d >= sblock.e2fs.e2fs_bcount || testbmap(d)) { + setbit(bbmap, i); + continue; + } else { + nbfree++; + } + } + cs_nbfree += nbfree; + cs_nifree += nifree; + cs_ndir += ndirs; - if (debug && memcmp(blk_bitmap->b_un.b_buf, bbmap, fs->e2fs_bsize)) { - printf("blk_bitmap:\n"); - print_bmap(blk_bitmap->b_un.b_buf, fs->e2fs_bsize); - printf("bbmap:\n"); - print_bmap(bbmap, fs->e2fs_bsize); - } + if (debug + && (fs2h16(fs->e2fs_gd[c].ext2bgd_nbfree) != nbfree + || fs2h16(fs->e2fs_gd[c].ext2bgd_nifree) != nifree + || fs2h16(fs->e2fs_gd[c].ext2bgd_ndirs) != ndirs)) { + printf( + "summary info for cg %d is %d, %d, %d," + "should be %d, %d, %d\n", + c, + fs2h16(fs->e2fs_gd[c].ext2bgd_nbfree), + fs2h16(fs->e2fs_gd[c].ext2bgd_nifree), + fs2h16(fs->e2fs_gd[c].ext2bgd_ndirs), + nbfree, + nifree, + ndirs + ); + } + (void)snprintf(msg, sizeof(msg), "SUMMARY INFORMATIONS WRONG FOR CG #%d", c); + if ((fs2h16(fs->e2fs_gd[c].ext2bgd_nbfree) != nbfree + || fs2h16(fs->e2fs_gd[c].ext2bgd_nifree) != nifree + || fs2h16(fs->e2fs_gd[c].ext2bgd_ndirs) != ndirs) + && dofix(&idesc[0], msg)) { + fs->e2fs_gd[c].ext2bgd_nbfree = h2fs16(nbfree); + fs->e2fs_gd[c].ext2bgd_nifree = h2fs16(nifree); + fs->e2fs_gd[c].ext2bgd_ndirs = h2fs16(ndirs); + sbdirty(); + } - (void)snprintf(msg, sizeof(msg), - "BLK(S) MISSING IN BIT MAPS #%d", c); - if (memcmp(blk_bitmap->b_un.b_buf, bbmap, fs->e2fs_bsize) && - dofix(&idesc[1], msg)) { - memcpy(blk_bitmap->b_un.b_buf, bbmap, fs->e2fs_bsize); - dirty(blk_bitmap); - } - if (debug && memcmp(ino_bitmap->b_un.b_buf, ibmap, fs->e2fs_bsize)) { - printf("ino_bitmap:\n"); - print_bmap(ino_bitmap->b_un.b_buf, fs->e2fs_bsize); - printf("ibmap:\n"); - print_bmap(ibmap, fs->e2fs_bsize); - } - (void)snprintf(msg, sizeof(msg), - "INODE(S) MISSING IN BIT MAPS #%d", c); - if (memcmp(ino_bitmap->b_un.b_buf, ibmap, fs->e2fs_bsize) && - dofix(&idesc[1], msg)) { - memcpy(ino_bitmap->b_un.b_buf, ibmap, fs->e2fs_bsize); - dirty(ino_bitmap); - } + if (debug && memcmp(blk_bitmap->b_un.b_buf, bbmap, fs->e2fs_bsize)) { + printf("blk_bitmap:\n"); + print_bmap(blk_bitmap->b_un.b_buf, fs->e2fs_bsize); + printf("bbmap:\n"); + print_bmap(bbmap, fs->e2fs_bsize); + } - } - if (debug && (fs->e2fs.e2fs_fbcount != cs_nbfree || - fs->e2fs.e2fs_ficount != cs_nifree)) { - printf("summary info bad in superblock: %d, %d should be %d, %d\n", - fs->e2fs.e2fs_fbcount, fs->e2fs.e2fs_ficount, - cs_nbfree, cs_nifree); - } - if ((fs->e2fs.e2fs_fbcount != cs_nbfree || - fs->e2fs.e2fs_ficount != cs_nifree) - && dofix(&idesc[0], "SUPERBLK SUMMARY INFORMATION BAD")) { - fs->e2fs.e2fs_fbcount = cs_nbfree; - fs->e2fs.e2fs_ficount = cs_nifree; - sbdirty(); - } - free(ibmap); - free(bbmap); + (void)snprintf(msg, sizeof(msg), "BLK(S) MISSING IN BIT MAPS #%d", c); + if (memcmp(blk_bitmap->b_un.b_buf, bbmap, fs->e2fs_bsize) && dofix(&idesc[1], msg)) { + memcpy(blk_bitmap->b_un.b_buf, bbmap, fs->e2fs_bsize); + dirty(blk_bitmap); + } + if (debug && memcmp(ino_bitmap->b_un.b_buf, ibmap, fs->e2fs_bsize)) { + printf("ino_bitmap:\n"); + print_bmap(ino_bitmap->b_un.b_buf, fs->e2fs_bsize); + printf("ibmap:\n"); + print_bmap(ibmap, fs->e2fs_bsize); + } + (void)snprintf(msg, sizeof(msg), "INODE(S) MISSING IN BIT MAPS #%d", c); + if (memcmp(ino_bitmap->b_un.b_buf, ibmap, fs->e2fs_bsize) && dofix(&idesc[1], msg)) { + memcpy(ino_bitmap->b_un.b_buf, ibmap, fs->e2fs_bsize); + dirty(ino_bitmap); + } + } + if (debug && (fs->e2fs.e2fs_fbcount != cs_nbfree || fs->e2fs.e2fs_ficount != cs_nifree)) { + printf( + "summary info bad in superblock: %d, %d should be %d, %d\n", + fs->e2fs.e2fs_fbcount, + fs->e2fs.e2fs_ficount, + cs_nbfree, + cs_nifree + ); + } + if ((fs->e2fs.e2fs_fbcount != cs_nbfree || fs->e2fs.e2fs_ficount != cs_nifree) + && dofix(&idesc[0], "SUPERBLK SUMMARY INFORMATION BAD")) { + fs->e2fs.e2fs_fbcount = cs_nbfree; + fs->e2fs.e2fs_ficount = cs_nifree; + sbdirty(); + } + free(ibmap); + free(bbmap); } -static void +static void print_bmap(char *map, uint32_t size) { - uint32_t i, j; + uint32_t i, j; - i = 0; - while (i < size) { - printf("%04x: ",i); - for (j = 0; j < 16; j++, i++) - printf("%02x ", (unsigned char)map[i] & 0xff); - printf("\n"); - } + i = 0; + while (i < size) { + printf("%04x: ", i); + for (j = 0; j < 16; j++, i++) + printf("%02x ", (unsigned char)map[i] & 0xff); + printf("\n"); + } } diff --git a/cmd/extra/fsck.ext4/setup.c b/cmd/extra/fsck.ext4/setup.c @@ -77,168 +77,160 @@ __RCSID("$NetBSD: setup.c,v 1.39 2019/03/31 13:16:52 mlelstv Exp $"); #include <string.h> #include <ctype.h> - #include "fsck.h" #include "extern.h" #include "fsutil.h" #include "diskutil.h" #include "exitvalues.h" -void badsb(int, const char *); +void badsb(int, const char *); static int readsb(int); static uint64_t volume_bytes; int setup(const char *dev) { - long cg, i; - long bmapsize; - struct stat statb; - struct BlockDev target = {0}; - off_t sizepb; - uint64_t maxfilesize; - int flags = O_RDONLY | O_NONBLOCK | O_NOCTTY; + long cg, i; + long bmapsize; + struct stat statb; + struct BlockDev target = {0}; + off_t sizepb; + uint64_t maxfilesize; + int flags = O_RDONLY | O_NONBLOCK | O_NOCTTY; #if defined(__linux__) && !defined(ARUU_FORCE_POSIX) - flags |= O_EXCL; + flags |= O_EXCL; #endif - havesb = 0; - fswritefd = -1; - if ((fsreadfd = open(dev, flags)) < 0 || fstat(fsreadfd, &statb) < 0) - enprintf(FSCK_EXIT_CHECK_FAILED, "%s:", dev); - if (S_ISREG(statb.st_mode)) - volume_bytes = statb.st_size; - else if (S_ISBLK(statb.st_mode) || S_ISCHR(statb.st_mode)) { - target.fd = fsreadfd; - blockdev_sys_size(&target); - volume_bytes = target.size; - } - if (!volume_bytes) - errexit("%s: cannot determine volume size", dev); - printf("** %s (NO WRITE)\n", dev); - fsmodified = 0; - lfdir = 0; - initbarea(&sblk); - initbarea(&asblk); - sblk.b_un.b_buf = malloc(SBSIZE); - asblk.b_un.b_buf = malloc(SBSIZE); - if (sblk.b_un.b_buf == NULL || asblk.b_un.b_buf == NULL) - errexit("cannot allocate space for superblock"); - dev_bsize = secsize = DEV_BSIZE; - if (!readsb(1)) - return 0; - maxfsblock = sblock.e2fs.e2fs_bcount; - maxino = sblock.e2fs_ncg * sblock.e2fs.e2fs_ipg; - sizepb = sblock.e2fs_bsize; - maxfilesize = sblock.e2fs_bsize * EXT2FS_NDADDR - 1; - for (i = 0; i < EXT2FS_NIADDR; i++) { - sizepb *= EXT2_NINDIR(&sblock); - maxfilesize += sizepb; - } - /* - * Check and potentially fix certain fields in the super block. - */ - if (/* (sblock.e2fs.e2fs_rbcount < 0) || */ - (sblock.e2fs.e2fs_rbcount > sblock.e2fs.e2fs_bcount)) { - pfatal("IMPOSSIBLE RESERVED BLOCK COUNT=%d IN SUPERBLOCK", - sblock.e2fs.e2fs_rbcount); - if (reply("SET TO DEFAULT") == 1) { - sblock.e2fs.e2fs_rbcount = - sblock.e2fs.e2fs_bcount * MINFREE / 100; - sbdirty(); - dirty(&asblk); - } - } - if (sblock.e2fs.e2fs_bpg != sblock.e2fs.e2fs_fpg) { - pfatal("WRONG FPG=%d (BPG=%d) IN SUPERBLOCK", - sblock.e2fs.e2fs_fpg, sblock.e2fs.e2fs_bpg); - return 0; - } - if (asblk.b_dirty && !bflag) { - copyback_sb(&asblk); - flush(fswritefd, &asblk); - } - /* - * read in the summary info. - */ + havesb = 0; + fswritefd = -1; + if ((fsreadfd = open(dev, flags)) < 0 || fstat(fsreadfd, &statb) < 0) + enprintf(FSCK_EXIT_CHECK_FAILED, "%s:", dev); + if (S_ISREG(statb.st_mode)) + volume_bytes = statb.st_size; + else if (S_ISBLK(statb.st_mode) || S_ISCHR(statb.st_mode)) { + target.fd = fsreadfd; + blockdev_sys_size(&target); + volume_bytes = target.size; + } + if (!volume_bytes) + errexit("%s: cannot determine volume size", dev); + printf("** %s (NO WRITE)\n", dev); + fsmodified = 0; + lfdir = 0; + initbarea(&sblk); + initbarea(&asblk); + sblk.b_un.b_buf = malloc(SBSIZE); + asblk.b_un.b_buf = malloc(SBSIZE); + if (sblk.b_un.b_buf == NULL || asblk.b_un.b_buf == NULL) + errexit("cannot allocate space for superblock"); + dev_bsize = secsize = DEV_BSIZE; + if (!readsb(1)) + return 0; + maxfsblock = sblock.e2fs.e2fs_bcount; + maxino = sblock.e2fs_ncg * sblock.e2fs.e2fs_ipg; + sizepb = sblock.e2fs_bsize; + maxfilesize = sblock.e2fs_bsize * EXT2FS_NDADDR - 1; + for (i = 0; i < EXT2FS_NIADDR; i++) { + sizepb *= EXT2_NINDIR(&sblock); + maxfilesize += sizepb; + } + /* + * Check and potentially fix certain fields in the super block. + */ + if (/* (sblock.e2fs.e2fs_rbcount < 0) || */ + (sblock.e2fs.e2fs_rbcount > sblock.e2fs.e2fs_bcount) + ) { + pfatal("IMPOSSIBLE RESERVED BLOCK COUNT=%d IN SUPERBLOCK", sblock.e2fs.e2fs_rbcount); + if (reply("SET TO DEFAULT") == 1) { + sblock.e2fs.e2fs_rbcount = sblock.e2fs.e2fs_bcount * MINFREE / 100; + sbdirty(); + dirty(&asblk); + } + } + if (sblock.e2fs.e2fs_bpg != sblock.e2fs.e2fs_fpg) { + pfatal("WRONG FPG=%d (BPG=%d) IN SUPERBLOCK", sblock.e2fs.e2fs_fpg, sblock.e2fs.e2fs_bpg); + return 0; + } + if (asblk.b_dirty && !bflag) { + copyback_sb(&asblk); + flush(fswritefd, &asblk); + } + /* + * read in the summary info. + */ - sblock.e2fs_gd = ecalloc(sblock.e2fs_ncg, sizeof(*sblock.e2fs_gd)); - for (i = 0; i < sblock.e2fs_ngdb; i++) { - char buf[4096]; - int j; - int perblock = sblock.e2fs_bsize / E2FS_REV0_GD_SIZE; + sblock.e2fs_gd = ecalloc(sblock.e2fs_ncg, sizeof(*sblock.e2fs_gd)); + for (i = 0; i < sblock.e2fs_ngdb; i++) { + char buf[4096]; + int j; + int perblock = sblock.e2fs_bsize / E2FS_REV0_GD_SIZE; - bread(fsreadfd, buf, - EXT2_FSBTODB(&sblock, sblock.e2fs.e2fs_first_dblock + i + 1), - sblock.e2fs_bsize); - for (j = 0; j < perblock && i * perblock + j < sblock.e2fs_ncg; j++) - memcpy(&sblock.e2fs_gd[i * perblock + j], - buf + j * E2FS_REV0_GD_SIZE, E2FS_REV0_GD_SIZE); - } - for (cg = 0; cg < sblock.e2fs_ncg; cg++) { - const struct ext2_gd *gd = &sblock.e2fs_gd[cg]; - uint64_t first = (uint64_t)cg * sblock.e2fs.e2fs_bpg + - sblock.e2fs.e2fs_first_dblock; - uint64_t end = MIN(first + sblock.e2fs.e2fs_bpg, maxfsblock); - uint32_t blockmap = fs2h32(gd->ext2bgd_b_bitmap); - uint32_t inodemap = fs2h32(gd->ext2bgd_i_bitmap); - uint32_t table = fs2h32(gd->ext2bgd_i_tables); + bread( + fsreadfd, + buf, + EXT2_FSBTODB(&sblock, sblock.e2fs.e2fs_first_dblock + i + 1), + sblock.e2fs_bsize + ); + for (j = 0; j < perblock && i * perblock + j < sblock.e2fs_ncg; j++) + memcpy(&sblock.e2fs_gd[i * perblock + j], buf + j * E2FS_REV0_GD_SIZE, E2FS_REV0_GD_SIZE); + } + for (cg = 0; cg < sblock.e2fs_ncg; cg++) { + const struct ext2_gd *gd = &sblock.e2fs_gd[cg]; + uint64_t first = (uint64_t)cg * sblock.e2fs.e2fs_bpg + sblock.e2fs.e2fs_first_dblock; + uint64_t end = MIN(first + sblock.e2fs.e2fs_bpg, maxfsblock); + uint32_t blockmap = fs2h32(gd->ext2bgd_b_bitmap); + uint32_t inodemap = fs2h32(gd->ext2bgd_i_bitmap); + uint32_t table = fs2h32(gd->ext2bgd_i_tables); - if (cgoverhead(cg) > end - first || - (fs2h16(gd->ext2bgd_flags) & ~E2FS_BG_INODE_ZEROED) || - blockmap < first || blockmap >= end || - inodemap < first || inodemap >= end || - table < first || table >= end || - sblock.e2fs_itpg > end - table) - errexit("invalid or unsupported group %ld", cg); - } - /* - * allocate and initialize the necessary maps - */ - bmapsize = roundup(howmany(maxfsblock, NBBY), sizeof(int16_t)); - blockmap = calloc((size_t)bmapsize, sizeof(char)); - if (blockmap == NULL) { - printf("cannot alloc %u bytes for blockmap\n", - (unsigned int)bmapsize); - goto badsblabel; - } - statemap = calloc((size_t)(maxino + 2), sizeof(char)); - if (statemap == NULL) { - printf("cannot alloc %u bytes for statemap\n", - (unsigned int)(maxino + 1)); - goto badsblabel; - } - typemap = calloc((size_t)(maxino + 1), sizeof(char)); - if (typemap == NULL) { - printf("cannot alloc %u bytes for typemap\n", - (unsigned int)(maxino + 1)); - goto badsblabel; - } - lncntp = calloc((size_t)(maxino + 1), sizeof(int16_t)); - if (lncntp == NULL) { - printf("cannot alloc %u bytes for lncntp\n", - (unsigned int)((maxino + 1) * sizeof(int16_t))); - goto badsblabel; - } - for (numdirs = 0, cg = 0; cg < sblock.e2fs_ncg; cg++) { - numdirs += fs2h16(sblock.e2fs_gd[cg].ext2bgd_ndirs); - } - inplast = 0; - numdirs = MAX(numdirs, 1); - listmax = numdirs + 10; - inpsort = calloc((unsigned int)listmax, sizeof(struct inoinfo *)); - inphead = calloc((unsigned int)numdirs, sizeof(struct inoinfo *)); - if (inpsort == NULL || inphead == NULL) { - printf("cannot alloc %u bytes for inphead\n", - (unsigned int)(numdirs * sizeof(struct inoinfo *))); - goto badsblabel; - } - bufinit(); - return 1; + if (cgoverhead(cg) > end - first || (fs2h16(gd->ext2bgd_flags) & ~E2FS_BG_INODE_ZEROED) + || blockmap < first || blockmap >= end || inodemap < first || inodemap >= end + || table < first || table >= end || sblock.e2fs_itpg > end - table) + errexit("invalid or unsupported group %ld", cg); + } + /* + * allocate and initialize the necessary maps + */ + bmapsize = roundup(howmany(maxfsblock, NBBY), sizeof(int16_t)); + blockmap = calloc((size_t)bmapsize, sizeof(char)); + if (blockmap == NULL) { + printf("cannot alloc %u bytes for blockmap\n", (unsigned int)bmapsize); + goto badsblabel; + } + statemap = calloc((size_t)(maxino + 2), sizeof(char)); + if (statemap == NULL) { + printf("cannot alloc %u bytes for statemap\n", (unsigned int)(maxino + 1)); + goto badsblabel; + } + typemap = calloc((size_t)(maxino + 1), sizeof(char)); + if (typemap == NULL) { + printf("cannot alloc %u bytes for typemap\n", (unsigned int)(maxino + 1)); + goto badsblabel; + } + lncntp = calloc((size_t)(maxino + 1), sizeof(int16_t)); + if (lncntp == NULL) { + printf("cannot alloc %u bytes for lncntp\n", (unsigned int)((maxino + 1) * sizeof(int16_t))); + goto badsblabel; + } + for (numdirs = 0, cg = 0; cg < sblock.e2fs_ncg; cg++) { + numdirs += fs2h16(sblock.e2fs_gd[cg].ext2bgd_ndirs); + } + inplast = 0; + numdirs = MAX(numdirs, 1); + listmax = numdirs + 10; + inpsort = calloc((unsigned int)listmax, sizeof(struct inoinfo *)); + inphead = calloc((unsigned int)numdirs, sizeof(struct inoinfo *)); + if (inpsort == NULL || inphead == NULL) { + printf( + "cannot alloc %u bytes for inphead\n", (unsigned int)(numdirs * sizeof(struct inoinfo *)) + ); + goto badsblabel; + } + bufinit(); + return 1; badsblabel: - ckfini(0); - return 0; + ckfini(0); + return 0; } /* @@ -247,122 +239,111 @@ badsblabel: static int readsb(int listerr) { - daddr_t super = bflag ? bflag : SBOFF / dev_bsize; + daddr_t super = bflag ? bflag : SBOFF / dev_bsize; + + if (bread(fsreadfd, (char *)sblk.b_un.b_fs, super, (long)SBSIZE) != 0) + return 0; + sblk.b_bno = super; + sblk.b_size = SBSIZE; - if (bread(fsreadfd, (char *)sblk.b_un.b_fs, super, (long)SBSIZE) != 0) - return 0; - sblk.b_bno = super; - sblk.b_size = SBSIZE; + /* Copy the superblock in memory */ + e2fs_sbload(sblk.b_un.b_fs, &sblock.e2fs); - /* Copy the superblock in memory */ - e2fs_sbload(sblk.b_un.b_fs, &sblock.e2fs); - - /* - * run a few consistency checks of the super block - */ - if (sblock.e2fs.e2fs_magic != E2FS_MAGIC) { - badsb(listerr, "MAGIC NUMBER WRONG"); - return 0; - } - if (sblock.e2fs.e2fs_log_bsize > 2) { - badsb(listerr, "BAD LOG_BSIZE"); - return 0; - } - if (sblock.e2fs.e2fs_rev > E2FS_REV0 && - (!powerof2(sblock.e2fs.e2fs_inode_size) || - sblock.e2fs.e2fs_inode_size < EXT2_REV0_DINODE_SIZE || - sblock.e2fs.e2fs_inode_size > - (1024 << sblock.e2fs.e2fs_log_bsize))) { - badsb(listerr, "BAD INODE_SIZE"); - return 0; - } + /* + * run a few consistency checks of the super block + */ + if (sblock.e2fs.e2fs_magic != E2FS_MAGIC) { + badsb(listerr, "MAGIC NUMBER WRONG"); + return 0; + } + if (sblock.e2fs.e2fs_log_bsize > 2) { + badsb(listerr, "BAD LOG_BSIZE"); + return 0; + } + if (sblock.e2fs.e2fs_rev > E2FS_REV0 + && (!powerof2(sblock.e2fs.e2fs_inode_size) + || sblock.e2fs.e2fs_inode_size < EXT2_REV0_DINODE_SIZE + || sblock.e2fs.e2fs_inode_size > (1024 << sblock.e2fs.e2fs_log_bsize))) { + badsb(listerr, "BAD INODE_SIZE"); + return 0; + } - if (sblock.e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_REPLAY_JOURNAL) - errexit("journal replay required"); - if ((sblock.e2fs.e2fs_features_incompat & ~EXT2F_INCOMPAT_SUPP_FSCK) || - (sblock.e2fs.e2fs_features_rocompat & ~EXT2F_ROCOMPAT_SUPP_FSCK) || - (sblock.e2fs.e2fs_features_compat & ~EXT2F_COMPAT_SUPP_FSCK)) - errexit("unsupported ext layout"); - if ((sblock.e2fs.e2fs_features_compat & EXT2F_COMPAT_HASJOURNAL) && - (fs2h32(sblk.b_un.b_fs->e3fs_journal_inum) != 8 || - sblk.b_un.b_fs->e3fs_journal_dev != 0)) - errexit("unsupported journal layout"); - if (sblk.b_un.b_fs->e3fs_last_orphan || - sblock.e2fs.e2fs_state != E2FS_ISCLEAN) - errexit("filesystem requires recovery"); - if (sblock.e2fs.e2fs_rev > E2FS_REV1 || - sblock.e2fs.e2fs_first_dblock != (sblock.e2fs.e2fs_log_bsize == 0) || - sblock.e2fs.e2fs_bcount <= sblock.e2fs.e2fs_first_dblock || - !sblock.e2fs.e2fs_bpg || !sblock.e2fs.e2fs_ipg || - sblock.e2fs.e2fs_bpg > (8192U << sblock.e2fs.e2fs_log_bsize) || - sblock.e2fs.e2fs_ipg > (8192U << sblock.e2fs.e2fs_log_bsize) || - sblock.e2fs.e2fs_ipg % 8 || - (uint64_t)sblock.e2fs.e2fs_bcount * (1024U << sblock.e2fs.e2fs_log_bsize) > - volume_bytes) - errexit("invalid ext geometry"); - sblock.e2fs_ncg = - howmany((uint64_t)sblock.e2fs.e2fs_bcount - sblock.e2fs.e2fs_first_dblock, - sblock.e2fs.e2fs_bpg); - sblock.e2fs_fsbtodb = sblock.e2fs.e2fs_log_bsize + 1; - sblock.e2fs_bsize = 1024 << sblock.e2fs.e2fs_log_bsize; - sblock.e2fs_bshift = LOG_MINBSIZE + sblock.e2fs.e2fs_log_bsize; - sblock.e2fs_qbmask = sblock.e2fs_bsize - 1; - sblock.e2fs_bmask = ~sblock.e2fs_qbmask; - sblock.e2fs_ngdb = howmany(sblock.e2fs_ncg, - sblock.e2fs_bsize / E2FS_REV0_GD_SIZE); - sblock.e2fs_ipb = sblock.e2fs_bsize / EXT2_DINODE_SIZE(&sblock); - sblock.e2fs_itpg = howmany(sblock.e2fs.e2fs_ipg, sblock.e2fs_ipb); + if (sblock.e2fs.e2fs_features_incompat & EXT2F_INCOMPAT_REPLAY_JOURNAL) + errexit("journal replay required"); + if ((sblock.e2fs.e2fs_features_incompat & ~EXT2F_INCOMPAT_SUPP_FSCK) + || (sblock.e2fs.e2fs_features_rocompat & ~EXT2F_ROCOMPAT_SUPP_FSCK) + || (sblock.e2fs.e2fs_features_compat & ~EXT2F_COMPAT_SUPP_FSCK)) + errexit("unsupported ext layout"); + if ((sblock.e2fs.e2fs_features_compat & EXT2F_COMPAT_HASJOURNAL) + && (fs2h32(sblk.b_un.b_fs->e3fs_journal_inum) != 8 || sblk.b_un.b_fs->e3fs_journal_dev != 0)) + errexit("unsupported journal layout"); + if (sblk.b_un.b_fs->e3fs_last_orphan || sblock.e2fs.e2fs_state != E2FS_ISCLEAN) + errexit("filesystem requires recovery"); + if (sblock.e2fs.e2fs_rev > E2FS_REV1 + || sblock.e2fs.e2fs_first_dblock != (sblock.e2fs.e2fs_log_bsize == 0) + || sblock.e2fs.e2fs_bcount <= sblock.e2fs.e2fs_first_dblock || !sblock.e2fs.e2fs_bpg + || !sblock.e2fs.e2fs_ipg || sblock.e2fs.e2fs_bpg > (8192U << sblock.e2fs.e2fs_log_bsize) + || sblock.e2fs.e2fs_ipg > (8192U << sblock.e2fs.e2fs_log_bsize) || sblock.e2fs.e2fs_ipg % 8 + || (uint64_t)sblock.e2fs.e2fs_bcount * (1024U << sblock.e2fs.e2fs_log_bsize) > volume_bytes) + errexit("invalid ext geometry"); + sblock.e2fs_ncg = howmany( + (uint64_t)sblock.e2fs.e2fs_bcount - sblock.e2fs.e2fs_first_dblock, sblock.e2fs.e2fs_bpg + ); + sblock.e2fs_fsbtodb = sblock.e2fs.e2fs_log_bsize + 1; + sblock.e2fs_bsize = 1024 << sblock.e2fs.e2fs_log_bsize; + sblock.e2fs_bshift = LOG_MINBSIZE + sblock.e2fs.e2fs_log_bsize; + sblock.e2fs_qbmask = sblock.e2fs_bsize - 1; + sblock.e2fs_bmask = ~sblock.e2fs_qbmask; + sblock.e2fs_ngdb = howmany(sblock.e2fs_ncg, sblock.e2fs_bsize / E2FS_REV0_GD_SIZE); + sblock.e2fs_ipb = sblock.e2fs_bsize / EXT2_DINODE_SIZE(&sblock); + sblock.e2fs_itpg = howmany(sblock.e2fs.e2fs_ipg, sblock.e2fs_ipb); - if ((uint64_t)sblock.e2fs_ncg * sblock.e2fs.e2fs_ipg != - sblock.e2fs.e2fs_icount || sblock.e2fs.e2fs_icount < EXT2_FIRSTINO || - sblock.e2fs.e2fs_icount >= UINT32_MAX - 2 || - 1 + sblock.e2fs_ngdb > sblock.e2fs.e2fs_bpg) - errexit("invalid ext group or inode count"); - havesb = 1; - return 1; + if ((uint64_t)sblock.e2fs_ncg * sblock.e2fs.e2fs_ipg != sblock.e2fs.e2fs_icount + || sblock.e2fs.e2fs_icount < EXT2_FIRSTINO || sblock.e2fs.e2fs_icount >= UINT32_MAX - 2 + || 1 + sblock.e2fs_ngdb > sblock.e2fs.e2fs_bpg) + errexit("invalid ext group or inode count"); + havesb = 1; + return 1; } void copyback_sb(struct bufarea *bp) { - /* Copy the in-memory superblock back to buffer */ - bp->b_un.b_fs->e2fs_icount = h2fs32(sblock.e2fs.e2fs_icount); - bp->b_un.b_fs->e2fs_bcount = h2fs32(sblock.e2fs.e2fs_bcount); - bp->b_un.b_fs->e2fs_rbcount = h2fs32(sblock.e2fs.e2fs_rbcount); - bp->b_un.b_fs->e2fs_fbcount = h2fs32(sblock.e2fs.e2fs_fbcount); - bp->b_un.b_fs->e2fs_ficount = h2fs32(sblock.e2fs.e2fs_ficount); - bp->b_un.b_fs->e2fs_first_dblock = - h2fs32(sblock.e2fs.e2fs_first_dblock); - bp->b_un.b_fs->e2fs_log_bsize = h2fs32(sblock.e2fs.e2fs_log_bsize); - bp->b_un.b_fs->e2fs_fsize = h2fs32(sblock.e2fs.e2fs_fsize); - bp->b_un.b_fs->e2fs_bpg = h2fs32(sblock.e2fs.e2fs_bpg); - bp->b_un.b_fs->e2fs_fpg = h2fs32(sblock.e2fs.e2fs_fpg); - bp->b_un.b_fs->e2fs_ipg = h2fs32(sblock.e2fs.e2fs_ipg); - bp->b_un.b_fs->e2fs_mtime = h2fs32(sblock.e2fs.e2fs_mtime); - bp->b_un.b_fs->e2fs_wtime = h2fs32(sblock.e2fs.e2fs_wtime); - bp->b_un.b_fs->e2fs_lastfsck = h2fs32(sblock.e2fs.e2fs_lastfsck); - bp->b_un.b_fs->e2fs_fsckintv = h2fs32(sblock.e2fs.e2fs_fsckintv); - bp->b_un.b_fs->e2fs_creator = h2fs32(sblock.e2fs.e2fs_creator); - bp->b_un.b_fs->e2fs_rev = h2fs32(sblock.e2fs.e2fs_rev); - bp->b_un.b_fs->e2fs_mnt_count = h2fs16(sblock.e2fs.e2fs_mnt_count); - bp->b_un.b_fs->e2fs_max_mnt_count = - h2fs16(sblock.e2fs.e2fs_max_mnt_count); - bp->b_un.b_fs->e2fs_magic = h2fs16(sblock.e2fs.e2fs_magic); - bp->b_un.b_fs->e2fs_state = h2fs16(sblock.e2fs.e2fs_state); - bp->b_un.b_fs->e2fs_beh = h2fs16(sblock.e2fs.e2fs_beh); - bp->b_un.b_fs->e2fs_ruid = h2fs16(sblock.e2fs.e2fs_ruid); - bp->b_un.b_fs->e2fs_rgid = h2fs16(sblock.e2fs.e2fs_rgid); + /* Copy the in-memory superblock back to buffer */ + bp->b_un.b_fs->e2fs_icount = h2fs32(sblock.e2fs.e2fs_icount); + bp->b_un.b_fs->e2fs_bcount = h2fs32(sblock.e2fs.e2fs_bcount); + bp->b_un.b_fs->e2fs_rbcount = h2fs32(sblock.e2fs.e2fs_rbcount); + bp->b_un.b_fs->e2fs_fbcount = h2fs32(sblock.e2fs.e2fs_fbcount); + bp->b_un.b_fs->e2fs_ficount = h2fs32(sblock.e2fs.e2fs_ficount); + bp->b_un.b_fs->e2fs_first_dblock = h2fs32(sblock.e2fs.e2fs_first_dblock); + bp->b_un.b_fs->e2fs_log_bsize = h2fs32(sblock.e2fs.e2fs_log_bsize); + bp->b_un.b_fs->e2fs_fsize = h2fs32(sblock.e2fs.e2fs_fsize); + bp->b_un.b_fs->e2fs_bpg = h2fs32(sblock.e2fs.e2fs_bpg); + bp->b_un.b_fs->e2fs_fpg = h2fs32(sblock.e2fs.e2fs_fpg); + bp->b_un.b_fs->e2fs_ipg = h2fs32(sblock.e2fs.e2fs_ipg); + bp->b_un.b_fs->e2fs_mtime = h2fs32(sblock.e2fs.e2fs_mtime); + bp->b_un.b_fs->e2fs_wtime = h2fs32(sblock.e2fs.e2fs_wtime); + bp->b_un.b_fs->e2fs_lastfsck = h2fs32(sblock.e2fs.e2fs_lastfsck); + bp->b_un.b_fs->e2fs_fsckintv = h2fs32(sblock.e2fs.e2fs_fsckintv); + bp->b_un.b_fs->e2fs_creator = h2fs32(sblock.e2fs.e2fs_creator); + bp->b_un.b_fs->e2fs_rev = h2fs32(sblock.e2fs.e2fs_rev); + bp->b_un.b_fs->e2fs_mnt_count = h2fs16(sblock.e2fs.e2fs_mnt_count); + bp->b_un.b_fs->e2fs_max_mnt_count = h2fs16(sblock.e2fs.e2fs_max_mnt_count); + bp->b_un.b_fs->e2fs_magic = h2fs16(sblock.e2fs.e2fs_magic); + bp->b_un.b_fs->e2fs_state = h2fs16(sblock.e2fs.e2fs_state); + bp->b_un.b_fs->e2fs_beh = h2fs16(sblock.e2fs.e2fs_beh); + bp->b_un.b_fs->e2fs_ruid = h2fs16(sblock.e2fs.e2fs_ruid); + bp->b_un.b_fs->e2fs_rgid = h2fs16(sblock.e2fs.e2fs_rgid); } void badsb(int listerr, const char *s) { - - if (!listerr) - return; - if (preen) - printf("%s: ", cdevname()); - pfatal("BAD SUPER BLOCK: %s\n", s); + if (!listerr) + return; + if (preen) + printf("%s: ", cdevname()); + pfatal("BAD SUPER BLOCK: %s\n", s); } /* @@ -375,16 +356,13 @@ badsb(int listerr, const char *s) daddr_t cgoverhead(int c) { - int overh; - overh = - 1 /* block bitmap */ + - 1 /* inode bitmap */ + - sblock.e2fs_itpg; - if (sblock.e2fs.e2fs_rev > E2FS_REV0 && - sblock.e2fs.e2fs_features_rocompat & EXT2F_ROCOMPAT_SPARSESUPER) { - if (cg_has_sb(c) == 0) - return overh; - } - overh += 1 /* superblock */ + sblock.e2fs_ngdb; - return overh; + int overh; + overh = 1 /* block bitmap */ + 1 /* inode bitmap */ + sblock.e2fs_itpg; + if (sblock.e2fs.e2fs_rev > E2FS_REV0 + && sblock.e2fs.e2fs_features_rocompat & EXT2F_ROCOMPAT_SPARSESUPER) { + if (cg_has_sb(c) == 0) + return overh; + } + overh += 1 /* superblock */ + sblock.e2fs_ngdb; + return overh; } diff --git a/cmd/extra/fsck.ext4/ufs/ext2fs/ext2fs.h b/cmd/extra/fsck.ext4/ufs/ext2fs/ext2fs.h @@ -79,17 +79,17 @@ * The first boot and super blocks are given in absolute disk addresses. * The byte-offset forms are preferred, as they don't imply a sector size. */ -#define BBSIZE 1024 -#define SBSIZE 1024 -#define BBOFF ((off_t)(0)) -#define SBOFF ((off_t)(BBOFF + BBSIZE)) -#define BBLOCK ((daddr_t)(0)) -#define SBLOCK ((daddr_t)(BBLOCK + BBSIZE / DEV_BSIZE)) - -#define fsbtodb(fs, b) ((daddr_t)(b) << (fs)->e2fs_fsbtodb) +#define BBSIZE 1024 +#define SBSIZE 1024 +#define BBOFF ((off_t)(0)) +#define SBOFF ((off_t)(BBOFF + BBSIZE)) +#define BBLOCK ((daddr_t)(0)) +#define SBLOCK ((daddr_t)(BBLOCK + BBSIZE / DEV_BSIZE)) + +#define fsbtodb(fs, b) ((daddr_t)(b) << (fs)->e2fs_fsbtodb) /* calculates (loc / fs->fs_bsize) */ -#define lblkno(fs, loc) ((loc) >> (fs->e2fs_bshift)) -#define blksize(fs, ip, lbn) ((fs)->e2fs_bsize) +#define lblkno(fs, loc) ((loc) >> (fs->e2fs_bshift)) +#define blksize(fs, ip, lbn) ((fs)->e2fs_bsize) /* * Addresses stored in inodes are capable of addressing blocks @@ -103,15 +103,15 @@ * Note that super blocks are always of size SBSIZE, * and that both SBSIZE and MAXBSIZE must be >= MINBSIZE. */ -#define LOG_MINBSIZE 10 -#define MINBSIZE (1 << LOG_MINBSIZE) +#define LOG_MINBSIZE 10 +#define MINBSIZE (1 << LOG_MINBSIZE) /* * The path name on which the file system is mounted is maintained * in fs_fsmnt. MAXMNTLEN defines the amount of space allocated in * the super block for this name. */ -#define MAXMNTLEN 512 +#define MAXMNTLEN 512 /* * MINFREE gives the minimum acceptable percentage of file system @@ -125,229 +125,226 @@ * default value. With 10% free space, fragmentation is not a * problem, so we choose to optimize for time. */ -#define MINFREE 5 +#define MINFREE 5 /* * This is maximum amount of links allowed for files. For directories, * going over this means setting DIR_NLINK feature. */ -#define EXT2FS_LINK_MAX 65000 -#define EXT2FS_LINK_INF 1 /* link count unknown */ +#define EXT2FS_LINK_MAX 65000 +#define EXT2FS_LINK_INF 1 /* link count unknown */ /* * Super block for an ext2fs file system. */ struct ext2fs { - uint32_t e2fs_icount; /* Inode count */ - uint32_t e2fs_bcount; /* blocks count */ - uint32_t e2fs_rbcount; /* reserved blocks count */ - uint32_t e2fs_fbcount; /* free blocks count */ - uint32_t e2fs_ficount; /* free inodes count */ - uint32_t e2fs_first_dblock; /* first data block */ - uint32_t e2fs_log_bsize; /* bsize = 1024*(2^e2fs_log_bsize) */ - uint32_t e2fs_fsize; /* fragment size */ - uint32_t e2fs_bpg; /* blocks per group */ - uint32_t e2fs_fpg; /* frags per group */ - uint32_t e2fs_ipg; /* inodes per group */ - uint32_t e2fs_mtime; /* mount time */ - uint32_t e2fs_wtime; /* write time */ - uint16_t e2fs_mnt_count; /* mount count */ - uint16_t e2fs_max_mnt_count; /* max mount count */ - uint16_t e2fs_magic; /* magic number */ - uint16_t e2fs_state; /* file system state */ - uint16_t e2fs_beh; /* behavior on errors */ - uint16_t e2fs_minrev; /* minor revision level */ - uint32_t e2fs_lastfsck; /* time of last fsck */ - uint32_t e2fs_fsckintv; /* max time between fscks */ - uint32_t e2fs_creator; /* creator OS */ - uint32_t e2fs_rev; /* revision level */ - uint16_t e2fs_ruid; /* default uid for reserved blocks */ - uint16_t e2fs_rgid; /* default gid for reserved blocks */ - /* EXT2_DYNAMIC_REV superblocks */ - uint32_t e2fs_first_ino; /* first non-reserved inode */ - uint16_t e2fs_inode_size; /* size of inode structure */ - uint16_t e2fs_block_group_nr; /* block grp number of this sblk*/ - uint32_t e2fs_features_compat; /* compatible feature set */ - uint32_t e2fs_features_incompat; /* incompatible feature set */ - uint32_t e2fs_features_rocompat; /* RO-compatible feature set */ - uint8_t e2fs_uuid[16]; /* 128-bit uuid for volume */ - char e2fs_vname[16]; /* volume name */ - char e2fs_fsmnt[64]; /* name mounted on */ - uint32_t e2fs_algo; /* For compression */ - uint8_t e2fs_prealloc; /* # of blocks to preallocate */ - uint8_t e2fs_dir_prealloc; /* # of blocks to preallocate for dir */ - uint16_t e2fs_reserved_ngdb; /* # of reserved gd blocks for resize */ - - /* Additional fields */ - char e3fs_journal_uuid[16];/* uuid of journal superblock */ - uint32_t e3fs_journal_inum; /* inode number of journal file */ - uint32_t e3fs_journal_dev; /* device number of journal file */ - uint32_t e3fs_last_orphan; /* start of list of inodes to delete */ - uint32_t e3fs_hash_seed[4]; /* HTREE hash seed */ - char e3fs_def_hash_version;/* Default hash version to use */ - char e3fs_jnl_backup_type; - uint16_t e3fs_desc_size; /* size of group descriptor */ - uint32_t e3fs_default_mount_opts; - uint32_t e3fs_first_meta_bg; /* First metablock block group */ - uint32_t e3fs_mkfs_time; /* when the fs was created */ - uint32_t e3fs_jnl_blks[17]; /* backup of the journal inode */ - uint32_t e4fs_bcount_hi; /* high bits of blocks count */ - uint32_t e4fs_rbcount_hi; /* high bits of reserved blocks count */ - uint32_t e4fs_fbcount_hi; /* high bits of free blocks count */ - uint16_t e4fs_min_extra_isize; /* all inodes have some bytes */ - uint16_t e4fs_want_extra_isize;/* inodes must reserve some bytes */ - uint32_t e4fs_flags; /* miscellaneous flags */ - uint16_t e4fs_raid_stride; /* RAID stride */ - uint16_t e4fs_mmpintv; /* seconds to wait in MMP checking */ - uint64_t e4fs_mmpblk; /* block for multi-mount protection */ - uint32_t e4fs_raid_stripe_wid; /* blocks on data disks (N * stride) */ - uint8_t e4fs_log_gpf; /* FLEX_BG group size */ - uint8_t e4fs_chksum_type; /* metadata checksum algorithm used */ - uint8_t e4fs_encrypt; /* versioning level for encryption */ - uint8_t e4fs_reserved_pad; - uint64_t e4fs_kbytes_written; /* number of lifetime kilobytes */ - uint32_t e4fs_snapinum; /* inode number of active snapshot */ - uint32_t e4fs_snapid; /* sequential ID of active snapshot */ - uint64_t e4fs_snaprbcount; /* rsvd blocks for active snapshot */ - uint32_t e4fs_snaplist; /* inode number for on-disk snapshot */ - uint32_t e4fs_errcount; /* number of file system errors */ - uint32_t e4fs_first_errtime; /* first time an error happened */ - uint32_t e4fs_first_errino; /* inode involved in first error */ - uint64_t e4fs_first_errblk; /* block involved of first error */ - uint8_t e4fs_first_errfunc[32];/* function where error happened */ - uint32_t e4fs_first_errline; /* line number where error happened */ - uint32_t e4fs_last_errtime; /* most recent time of an error */ - uint32_t e4fs_last_errino; /* inode involved in last error */ - uint32_t e4fs_last_errline; /* line number where error happened */ - uint64_t e4fs_last_errblk; /* block involved of last error */ - uint8_t e4fs_last_errfunc[32];/* function where error happened */ - uint8_t e4fs_mount_opts[64]; - uint32_t e4fs_usrquota_inum; /* inode for tracking user quota */ - uint32_t e4fs_grpquota_inum; /* inode for tracking group quota */ - uint32_t e4fs_overhead_clusters;/* overhead blocks/clusters */ - uint32_t e4fs_backup_bgs[2]; /* groups with sparse_super2 SBs */ - uint8_t e4fs_encrypt_algos[4];/* encryption algorithms in use */ - uint8_t e4fs_encrypt_pw_salt[16];/* salt used for string2key */ - uint32_t e4fs_lpf_ino; /* location of the lost+found inode */ - uint32_t e4fs_proj_quota_inum; /* inode for tracking project quota */ - uint32_t e4fs_chksum_seed; /* checksum seed */ - uint32_t e4fs_reserved[98]; /* padding to the end of the block */ - uint32_t e4fs_sbchksum; /* superblock checksum */ + uint32_t e2fs_icount; /* Inode count */ + uint32_t e2fs_bcount; /* blocks count */ + uint32_t e2fs_rbcount; /* reserved blocks count */ + uint32_t e2fs_fbcount; /* free blocks count */ + uint32_t e2fs_ficount; /* free inodes count */ + uint32_t e2fs_first_dblock; /* first data block */ + uint32_t e2fs_log_bsize; /* bsize = 1024*(2^e2fs_log_bsize) */ + uint32_t e2fs_fsize; /* fragment size */ + uint32_t e2fs_bpg; /* blocks per group */ + uint32_t e2fs_fpg; /* frags per group */ + uint32_t e2fs_ipg; /* inodes per group */ + uint32_t e2fs_mtime; /* mount time */ + uint32_t e2fs_wtime; /* write time */ + uint16_t e2fs_mnt_count; /* mount count */ + uint16_t e2fs_max_mnt_count; /* max mount count */ + uint16_t e2fs_magic; /* magic number */ + uint16_t e2fs_state; /* file system state */ + uint16_t e2fs_beh; /* behavior on errors */ + uint16_t e2fs_minrev; /* minor revision level */ + uint32_t e2fs_lastfsck; /* time of last fsck */ + uint32_t e2fs_fsckintv; /* max time between fscks */ + uint32_t e2fs_creator; /* creator OS */ + uint32_t e2fs_rev; /* revision level */ + uint16_t e2fs_ruid; /* default uid for reserved blocks */ + uint16_t e2fs_rgid; /* default gid for reserved blocks */ + /* EXT2_DYNAMIC_REV superblocks */ + uint32_t e2fs_first_ino; /* first non-reserved inode */ + uint16_t e2fs_inode_size; /* size of inode structure */ + uint16_t e2fs_block_group_nr; /* block grp number of this sblk*/ + uint32_t e2fs_features_compat; /* compatible feature set */ + uint32_t e2fs_features_incompat; /* incompatible feature set */ + uint32_t e2fs_features_rocompat; /* RO-compatible feature set */ + uint8_t e2fs_uuid[16]; /* 128-bit uuid for volume */ + char e2fs_vname[16]; /* volume name */ + char e2fs_fsmnt[64]; /* name mounted on */ + uint32_t e2fs_algo; /* For compression */ + uint8_t e2fs_prealloc; /* # of blocks to preallocate */ + uint8_t e2fs_dir_prealloc; /* # of blocks to preallocate for dir */ + uint16_t e2fs_reserved_ngdb; /* # of reserved gd blocks for resize */ + + /* Additional fields */ + char e3fs_journal_uuid[16]; /* uuid of journal superblock */ + uint32_t e3fs_journal_inum; /* inode number of journal file */ + uint32_t e3fs_journal_dev; /* device number of journal file */ + uint32_t e3fs_last_orphan; /* start of list of inodes to delete */ + uint32_t e3fs_hash_seed[4]; /* HTREE hash seed */ + char e3fs_def_hash_version; /* Default hash version to use */ + char e3fs_jnl_backup_type; + uint16_t e3fs_desc_size; /* size of group descriptor */ + uint32_t e3fs_default_mount_opts; + uint32_t e3fs_first_meta_bg; /* First metablock block group */ + uint32_t e3fs_mkfs_time; /* when the fs was created */ + uint32_t e3fs_jnl_blks[17]; /* backup of the journal inode */ + uint32_t e4fs_bcount_hi; /* high bits of blocks count */ + uint32_t e4fs_rbcount_hi; /* high bits of reserved blocks count */ + uint32_t e4fs_fbcount_hi; /* high bits of free blocks count */ + uint16_t e4fs_min_extra_isize; /* all inodes have some bytes */ + uint16_t e4fs_want_extra_isize; /* inodes must reserve some bytes */ + uint32_t e4fs_flags; /* miscellaneous flags */ + uint16_t e4fs_raid_stride; /* RAID stride */ + uint16_t e4fs_mmpintv; /* seconds to wait in MMP checking */ + uint64_t e4fs_mmpblk; /* block for multi-mount protection */ + uint32_t e4fs_raid_stripe_wid; /* blocks on data disks (N * stride) */ + uint8_t e4fs_log_gpf; /* FLEX_BG group size */ + uint8_t e4fs_chksum_type; /* metadata checksum algorithm used */ + uint8_t e4fs_encrypt; /* versioning level for encryption */ + uint8_t e4fs_reserved_pad; + uint64_t e4fs_kbytes_written; /* number of lifetime kilobytes */ + uint32_t e4fs_snapinum; /* inode number of active snapshot */ + uint32_t e4fs_snapid; /* sequential ID of active snapshot */ + uint64_t e4fs_snaprbcount; /* rsvd blocks for active snapshot */ + uint32_t e4fs_snaplist; /* inode number for on-disk snapshot */ + uint32_t e4fs_errcount; /* number of file system errors */ + uint32_t e4fs_first_errtime; /* first time an error happened */ + uint32_t e4fs_first_errino; /* inode involved in first error */ + uint64_t e4fs_first_errblk; /* block involved of first error */ + uint8_t e4fs_first_errfunc[32]; /* function where error happened */ + uint32_t e4fs_first_errline; /* line number where error happened */ + uint32_t e4fs_last_errtime; /* most recent time of an error */ + uint32_t e4fs_last_errino; /* inode involved in last error */ + uint32_t e4fs_last_errline; /* line number where error happened */ + uint64_t e4fs_last_errblk; /* block involved of last error */ + uint8_t e4fs_last_errfunc[32]; /* function where error happened */ + uint8_t e4fs_mount_opts[64]; + uint32_t e4fs_usrquota_inum; /* inode for tracking user quota */ + uint32_t e4fs_grpquota_inum; /* inode for tracking group quota */ + uint32_t e4fs_overhead_clusters; /* overhead blocks/clusters */ + uint32_t e4fs_backup_bgs[2]; /* groups with sparse_super2 SBs */ + uint8_t e4fs_encrypt_algos[4]; /* encryption algorithms in use */ + uint8_t e4fs_encrypt_pw_salt[16]; /* salt used for string2key */ + uint32_t e4fs_lpf_ino; /* location of the lost+found inode */ + uint32_t e4fs_proj_quota_inum; /* inode for tracking project quota */ + uint32_t e4fs_chksum_seed; /* checksum seed */ + uint32_t e4fs_reserved[98]; /* padding to the end of the block */ + uint32_t e4fs_sbchksum; /* superblock checksum */ }; - /* in-memory data for ext2fs */ struct m_ext2fs { - struct ext2fs e2fs; - u_char e2fs_fsmnt[MAXMNTLEN]; /* name mounted on */ - int8_t e2fs_ronly; /* mounted read-only flag */ - int8_t e2fs_fmod; /* super block modified flag */ - int8_t e2fs_uhash; /* 3 if hash should be signed, 0 if not */ - int32_t e2fs_bsize; /* block size */ - int32_t e2fs_bshift; /* ``lblkno'' calc of logical blkno */ - int32_t e2fs_bmask; /* ``blkoff'' calc of blk offsets */ - int64_t e2fs_qbmask; /* ~fs_bmask - for use with quad size */ - int32_t e2fs_fsbtodb; /* fsbtodb and dbtofsb shift constant */ - int32_t e2fs_ncg; /* number of cylinder groups */ - int32_t e2fs_ngdb; /* number of group descriptor blocks */ - int32_t e2fs_ipb; /* number of inodes per block */ - int32_t e2fs_itpg; /* number of inode table blocks per group */ - uint8_t e2fs_group_desc_shift; /* binary log group desc size */ - struct ext2_gd *e2fs_gd; /* group descriptors (data not byteswapped) */ + struct ext2fs e2fs; + u_char e2fs_fsmnt[MAXMNTLEN]; /* name mounted on */ + int8_t e2fs_ronly; /* mounted read-only flag */ + int8_t e2fs_fmod; /* super block modified flag */ + int8_t e2fs_uhash; /* 3 if hash should be signed, 0 if not */ + int32_t e2fs_bsize; /* block size */ + int32_t e2fs_bshift; /* ``lblkno'' calc of logical blkno */ + int32_t e2fs_bmask; /* ``blkoff'' calc of blk offsets */ + int64_t e2fs_qbmask; /* ~fs_bmask - for use with quad size */ + int32_t e2fs_fsbtodb; /* fsbtodb and dbtofsb shift constant */ + int32_t e2fs_ncg; /* number of cylinder groups */ + int32_t e2fs_ngdb; /* number of group descriptor blocks */ + int32_t e2fs_ipb; /* number of inodes per block */ + int32_t e2fs_itpg; /* number of inode table blocks per group */ + uint8_t e2fs_group_desc_shift; /* binary log group desc size */ + struct ext2_gd *e2fs_gd; /* group descriptors (data not byteswapped) */ }; - - /* * Filesystem identification */ -#define E2FS_MAGIC 0xef53 /* the ext2fs magic number */ -#define E2FS_REV0 0 /* GOOD_OLD revision */ -#define E2FS_REV1 1 /* Support compat/incompat features */ +#define E2FS_MAGIC 0xef53 /* the ext2fs magic number */ +#define E2FS_REV0 0 /* GOOD_OLD revision */ +#define E2FS_REV1 1 /* Support compat/incompat features */ /* compatible/incompatible features */ -#define EXT2F_COMPAT_PREALLOC 0x0001 -#define EXT2F_COMPAT_AFS 0x0002 -#define EXT2F_COMPAT_HASJOURNAL 0x0004 -#define EXT2F_COMPAT_EXTATTR 0x0008 -#define EXT2F_COMPAT_RESIZE 0x0010 -#define EXT2F_COMPAT_DIRHASHINDEX 0x0020 -#define EXT2F_COMPAT_SPARSESUPER2 0x0200 -#define EXT2F_COMPAT_BITS \ - "\20" \ - "\12COMPAT_SPARSESUPER2" \ - "\11" \ - "\10" \ - "\07" \ - "\06COMPAT_DIRHASHINDEX" \ - "\05COMPAT_RESIZE" \ - "\04COMPAT_EXTATTR" \ - "\03COMPAT_HASJOURNAL" \ - "\02COMPAT_AFS" \ - "\01COMPAT_PREALLOC" - -#define EXT2F_ROCOMPAT_SPARSESUPER 0x0001 -#define EXT2F_ROCOMPAT_LARGEFILE 0x0002 -#define EXT2F_ROCOMPAT_BTREE_DIR 0x0004 -#define EXT2F_ROCOMPAT_HUGE_FILE 0x0008 -#define EXT2F_ROCOMPAT_GDT_CSUM 0x0010 -#define EXT2F_ROCOMPAT_DIR_NLINK 0x0020 -#define EXT2F_ROCOMPAT_EXTRA_ISIZE 0x0040 -#define EXT2F_ROCOMPAT_QUOTA 0x0100 -#define EXT2F_ROCOMPAT_BIGALLOC 0x0200 -#define EXT2F_ROCOMPAT_METADATA_CKSUM 0x0400 -#define EXT2F_ROCOMPAT_READONLY 0x1000 -#define EXT2F_ROCOMPAT_PROJECT 0x2000 -#define EXT2F_ROCOMPAT_BITS \ - "\20" \ - "\16ROCOMPAT_PROJECT" \ - "\15ROCOMPAT_READONLY" \ - "\14?" \ - "\13ROCOMPAT_METADATA_CKSUM" \ - "\12ROCOMPAT_BIGALLOC" \ - "\11ROCOMPAT_QUOTA" \ - "\10?" \ - "\07ROCOMPAT_EXTRA_ISIZE" \ - "\06ROCOMPAT_DIR_NLINK" \ - "\05ROCOMPAT_GDT_CSUM" \ - "\04ROCOMPAT_HUGE_FILE" \ - "\03ROCOMPAT_BTREE_DIR" \ - "\02ROCOMPAT_LARGEFILE" \ - "\01ROCOMPAT_SPARSESUPER" - -#define EXT2F_INCOMPAT_COMP 0x0001 -#define EXT2F_INCOMPAT_FTYPE 0x0002 -#define EXT2F_INCOMPAT_REPLAY_JOURNAL 0x0004 -#define EXT2F_INCOMPAT_USES_JOURNAL 0x0008 -#define EXT2F_INCOMPAT_META_BG 0x0010 -#define EXT2F_INCOMPAT_EXTENTS 0x0040 -#define EXT2F_INCOMPAT_64BIT 0x0080 -#define EXT2F_INCOMPAT_MMP 0x0100 -#define EXT2F_INCOMPAT_FLEX_BG 0x0200 -#define EXT2F_INCOMPAT_EA_INODE 0x0400 -#define EXT2F_INCOMPAT_DIRDATA 0x1000 -#define EXT2F_INCOMPAT_CSUM_SEED 0x2000 -#define EXT2F_INCOMPAT_LARGEDIR 0x4000 -#define EXT2F_INCOMPAT_INLINE_DATA 0x8000 -#define EXT2F_INCOMPAT_ENCRYPT 0x10000 -#define EXT2F_INCOMPAT_BITS \ - "\20" \ - "\021INCOMPAT_ENCRYPT" \ - "\020INCOMPAT_INLINE_DATA" \ - "\017INCOMPAT_LARGEDIR" \ - "\016INCOMPAT_CSUM_SEED" \ - "\015INCOMPAT_DIRDATA" \ - "\014?" \ - "\013INCOMPAT_EA_INODE" \ - "\012INCOMPAT_FLEX_BG" \ - "\011INCOMPAT_MMP" \ - "\010INCOMPAT_64BIT" \ - "\07INCOMPAT_EXTENTS" \ - "\05INCOMPAT_META_BG" \ - "\04INCOMPAT_USES_JOURNAL" \ - "\03INCOMPAT_REPLAY_JOURNAL" \ - "\02INCOMPAT_FTYPE" \ - "\01INCOMPAT_COMP" +#define EXT2F_COMPAT_PREALLOC 0x0001 +#define EXT2F_COMPAT_AFS 0x0002 +#define EXT2F_COMPAT_HASJOURNAL 0x0004 +#define EXT2F_COMPAT_EXTATTR 0x0008 +#define EXT2F_COMPAT_RESIZE 0x0010 +#define EXT2F_COMPAT_DIRHASHINDEX 0x0020 +#define EXT2F_COMPAT_SPARSESUPER2 0x0200 +#define EXT2F_COMPAT_BITS \ + "\20" \ + "\12COMPAT_SPARSESUPER2" \ + "\11" \ + "\10" \ + "\07" \ + "\06COMPAT_DIRHASHINDEX" \ + "\05COMPAT_RESIZE" \ + "\04COMPAT_EXTATTR" \ + "\03COMPAT_HASJOURNAL" \ + "\02COMPAT_AFS" \ + "\01COMPAT_PREALLOC" + +#define EXT2F_ROCOMPAT_SPARSESUPER 0x0001 +#define EXT2F_ROCOMPAT_LARGEFILE 0x0002 +#define EXT2F_ROCOMPAT_BTREE_DIR 0x0004 +#define EXT2F_ROCOMPAT_HUGE_FILE 0x0008 +#define EXT2F_ROCOMPAT_GDT_CSUM 0x0010 +#define EXT2F_ROCOMPAT_DIR_NLINK 0x0020 +#define EXT2F_ROCOMPAT_EXTRA_ISIZE 0x0040 +#define EXT2F_ROCOMPAT_QUOTA 0x0100 +#define EXT2F_ROCOMPAT_BIGALLOC 0x0200 +#define EXT2F_ROCOMPAT_METADATA_CKSUM 0x0400 +#define EXT2F_ROCOMPAT_READONLY 0x1000 +#define EXT2F_ROCOMPAT_PROJECT 0x2000 +#define EXT2F_ROCOMPAT_BITS \ + "\20" \ + "\16ROCOMPAT_PROJECT" \ + "\15ROCOMPAT_READONLY" \ + "\14?" \ + "\13ROCOMPAT_METADATA_CKSUM" \ + "\12ROCOMPAT_BIGALLOC" \ + "\11ROCOMPAT_QUOTA" \ + "\10?" \ + "\07ROCOMPAT_EXTRA_ISIZE" \ + "\06ROCOMPAT_DIR_NLINK" \ + "\05ROCOMPAT_GDT_CSUM" \ + "\04ROCOMPAT_HUGE_FILE" \ + "\03ROCOMPAT_BTREE_DIR" \ + "\02ROCOMPAT_LARGEFILE" \ + "\01ROCOMPAT_SPARSESUPER" + +#define EXT2F_INCOMPAT_COMP 0x0001 +#define EXT2F_INCOMPAT_FTYPE 0x0002 +#define EXT2F_INCOMPAT_REPLAY_JOURNAL 0x0004 +#define EXT2F_INCOMPAT_USES_JOURNAL 0x0008 +#define EXT2F_INCOMPAT_META_BG 0x0010 +#define EXT2F_INCOMPAT_EXTENTS 0x0040 +#define EXT2F_INCOMPAT_64BIT 0x0080 +#define EXT2F_INCOMPAT_MMP 0x0100 +#define EXT2F_INCOMPAT_FLEX_BG 0x0200 +#define EXT2F_INCOMPAT_EA_INODE 0x0400 +#define EXT2F_INCOMPAT_DIRDATA 0x1000 +#define EXT2F_INCOMPAT_CSUM_SEED 0x2000 +#define EXT2F_INCOMPAT_LARGEDIR 0x4000 +#define EXT2F_INCOMPAT_INLINE_DATA 0x8000 +#define EXT2F_INCOMPAT_ENCRYPT 0x10000 +#define EXT2F_INCOMPAT_BITS \ + "\20" \ + "\021INCOMPAT_ENCRYPT" \ + "\020INCOMPAT_INLINE_DATA" \ + "\017INCOMPAT_LARGEDIR" \ + "\016INCOMPAT_CSUM_SEED" \ + "\015INCOMPAT_DIRDATA" \ + "\014?" \ + "\013INCOMPAT_EA_INODE" \ + "\012INCOMPAT_FLEX_BG" \ + "\011INCOMPAT_MMP" \ + "\010INCOMPAT_64BIT" \ + "\07INCOMPAT_EXTENTS" \ + "\05INCOMPAT_META_BG" \ + "\04INCOMPAT_USES_JOURNAL" \ + "\03INCOMPAT_REPLAY_JOURNAL" \ + "\02INCOMPAT_FTYPE" \ + "\01INCOMPAT_COMP" /* * Features supported in this implementation @@ -362,95 +359,86 @@ struct m_ext2fs { * store file type to e2d_type in struct ext2fs_direct * (on REV0 e2d_namlen is uint16_t and no e2d_type, like ffs) */ -#define EXT2F_COMPAT_SUPP 0x0000 -#define EXT2F_ROCOMPAT_SUPP (EXT2F_ROCOMPAT_SPARSESUPER \ - | EXT2F_ROCOMPAT_LARGEFILE \ - | EXT2F_ROCOMPAT_HUGE_FILE \ - | EXT2F_ROCOMPAT_EXTRA_ISIZE \ - | EXT2F_ROCOMPAT_DIR_NLINK \ - | EXT2F_ROCOMPAT_GDT_CSUM) -#define EXT2F_INCOMPAT_SUPP (EXT2F_INCOMPAT_FTYPE \ - | EXT2F_INCOMPAT_EXTENTS \ - | EXT2F_INCOMPAT_FLEX_BG \ - | EXT2F_INCOMPAT_64BIT) +#define EXT2F_COMPAT_SUPP 0x0000 +#define EXT2F_ROCOMPAT_SUPP \ + (EXT2F_ROCOMPAT_SPARSESUPER | EXT2F_ROCOMPAT_LARGEFILE | EXT2F_ROCOMPAT_HUGE_FILE \ + | EXT2F_ROCOMPAT_EXTRA_ISIZE | EXT2F_ROCOMPAT_DIR_NLINK | EXT2F_ROCOMPAT_GDT_CSUM) +#define EXT2F_INCOMPAT_SUPP \ + (EXT2F_INCOMPAT_FTYPE | EXT2F_INCOMPAT_EXTENTS | EXT2F_INCOMPAT_FLEX_BG | EXT2F_INCOMPAT_64BIT) /* * Feature set definitions */ -#define EXT2F_HAS_COMPAT_FEATURE(fs, feature) \ - ((fs)->e2fs.e2fs_rev >= E2FS_REV1 && \ - ((fs)->e2fs.e2fs_features_compat & (feature)) != 0) - -#define EXT2F_HAS_ROCOMPAT_FEATURE(fs, feature) \ - ((fs)->e2fs.e2fs_rev >= E2FS_REV1 && \ - ((fs)->e2fs.e2fs_features_rocompat & (feature)) != 0) +#define EXT2F_HAS_COMPAT_FEATURE(fs, feature) \ + ((fs)->e2fs.e2fs_rev >= E2FS_REV1 && ((fs)->e2fs.e2fs_features_compat & (feature)) != 0) -#define EXT2F_HAS_INCOMPAT_FEATURE(fs, feature) \ - ((fs)->e2fs.e2fs_rev >= E2FS_REV1 && \ - ((fs)->e2fs.e2fs_features_incompat & (feature)) != 0) +#define EXT2F_HAS_ROCOMPAT_FEATURE(fs, feature) \ + ((fs)->e2fs.e2fs_rev >= E2FS_REV1 && ((fs)->e2fs.e2fs_features_rocompat & (feature)) != 0) +#define EXT2F_HAS_INCOMPAT_FEATURE(fs, feature) \ + ((fs)->e2fs.e2fs_rev >= E2FS_REV1 && ((fs)->e2fs.e2fs_features_incompat & (feature)) != 0) /* * Definitions of behavior on errors */ -#define E2FS_BEH_CONTINUE 1 /* continue operation */ -#define E2FS_BEH_READONLY 2 /* remount fs read only */ -#define E2FS_BEH_PANIC 3 /* cause panic */ -#define E2FS_BEH_DEFAULT E2FS_BEH_CONTINUE +#define E2FS_BEH_CONTINUE 1 /* continue operation */ +#define E2FS_BEH_READONLY 2 /* remount fs read only */ +#define E2FS_BEH_PANIC 3 /* cause panic */ +#define E2FS_BEH_DEFAULT E2FS_BEH_CONTINUE /* * OS identification */ -#define E2FS_OS_LINUX 0 -#define E2FS_OS_HURD 1 -#define E2FS_OS_MASIX 2 -#define E2FS_OS_FREEBSD 3 -#define E2FS_OS_LITES 4 +#define E2FS_OS_LINUX 0 +#define E2FS_OS_HURD 1 +#define E2FS_OS_MASIX 2 +#define E2FS_OS_FREEBSD 3 +#define E2FS_OS_LITES 4 /* * Filesystem clean flags */ -#define E2FS_ISCLEAN 0x01 -#define E2FS_ERRORS 0x02 +#define E2FS_ISCLEAN 0x01 +#define E2FS_ERRORS 0x02 /* ext2 file system block group descriptor */ struct ext2_gd { - uint32_t ext2bgd_b_bitmap; /* blocks bitmap block */ - uint32_t ext2bgd_i_bitmap; /* inodes bitmap block */ - uint32_t ext2bgd_i_tables; /* first inodes table block */ - uint16_t ext2bgd_nbfree; /* number of free blocks */ - uint16_t ext2bgd_nifree; /* number of free inodes */ - uint16_t ext2bgd_ndirs; /* number of directories */ - - /* - * Following only valid when either GDT_CSUM (AKA uninit_bg) - * or METADATA_CKSUM feature is on - */ - uint16_t ext2bgd_flags; /* ext4 bg flags (INODE_UNINIT, ...)*/ - uint32_t ext2bgd_exclude_bitmap_lo; /* snapshot exclude bitmap */ - uint16_t ext2bgd_block_bitmap_csum_lo; /* Low block bitmap checksum */ - uint16_t ext2bgd_inode_bitmap_csum_lo; /* Low inode bitmap checksum */ - uint16_t ext2bgd_itable_unused_lo; /* Low unused inode offset */ - uint16_t ext2bgd_checksum; /* Group desc checksum */ - - uint32_t ext2bgd_b_bitmap_hi; /* blocks bitmap block (high bits) */ - uint32_t ext2bgd_i_bitmap_hi; /* inodes bitmap block (high bits) */ - uint32_t ext2bgd_i_tables_hi; /* inodes table block (high bits) */ - uint16_t ext2bgd_nbfree_hi; /* number of free blocks (high bits) */ - uint16_t ext2bgd_nifree_hi; /* number of free inodes (high bits) */ - uint16_t ext2bgd_ndirs_hi; /* number of directories (high bits) */ - uint16_t reserved_hi; - uint32_t reserved2_hi[3]; + uint32_t ext2bgd_b_bitmap; /* blocks bitmap block */ + uint32_t ext2bgd_i_bitmap; /* inodes bitmap block */ + uint32_t ext2bgd_i_tables; /* first inodes table block */ + uint16_t ext2bgd_nbfree; /* number of free blocks */ + uint16_t ext2bgd_nifree; /* number of free inodes */ + uint16_t ext2bgd_ndirs; /* number of directories */ + + /* + * Following only valid when either GDT_CSUM (AKA uninit_bg) + * or METADATA_CKSUM feature is on + */ + uint16_t ext2bgd_flags; /* ext4 bg flags (INODE_UNINIT, ...)*/ + uint32_t ext2bgd_exclude_bitmap_lo; /* snapshot exclude bitmap */ + uint16_t ext2bgd_block_bitmap_csum_lo; /* Low block bitmap checksum */ + uint16_t ext2bgd_inode_bitmap_csum_lo; /* Low inode bitmap checksum */ + uint16_t ext2bgd_itable_unused_lo; /* Low unused inode offset */ + uint16_t ext2bgd_checksum; /* Group desc checksum */ + + uint32_t ext2bgd_b_bitmap_hi; /* blocks bitmap block (high bits) */ + uint32_t ext2bgd_i_bitmap_hi; /* inodes bitmap block (high bits) */ + uint32_t ext2bgd_i_tables_hi; /* inodes table block (high bits) */ + uint16_t ext2bgd_nbfree_hi; /* number of free blocks (high bits) */ + uint16_t ext2bgd_nifree_hi; /* number of free inodes (high bits) */ + uint16_t ext2bgd_ndirs_hi; /* number of directories (high bits) */ + uint16_t reserved_hi; + uint32_t reserved2_hi[3]; }; -#define E2FS_REV0_GD_SIZE (sizeof(struct ext2_gd) / 2) /* 32 */ -#define E2FS_BG_INODE_UNINIT 0x0001 /* Inode bitmap not used/initialized */ -#define E2FS_BG_BLOCK_UNINIT 0x0002 /* Block bitmap not used/initialized */ -#define E2FS_BG_INODE_ZEROED 0x0004 /* On-disk inode table initialized */ +#define E2FS_REV0_GD_SIZE (sizeof(struct ext2_gd) / 2) /* 32 */ +#define E2FS_BG_INODE_UNINIT 0x0001 /* Inode bitmap not used/initialized */ +#define E2FS_BG_BLOCK_UNINIT 0x0002 /* Block bitmap not used/initialized */ +#define E2FS_BG_INODE_ZEROED 0x0004 /* On-disk inode table initialized */ -#define E2FS_HAS_GD_CSUM(fs) \ - EXT2F_HAS_ROCOMPAT_FEATURE(fs, EXT2F_ROCOMPAT_GDT_CSUM|EXT2F_ROCOMPAT_METADATA_CKSUM) != 0 +#define E2FS_HAS_GD_CSUM(fs) \ + EXT2F_HAS_ROCOMPAT_FEATURE(fs, EXT2F_ROCOMPAT_GDT_CSUM | EXT2F_ROCOMPAT_METADATA_CKSUM) != 0 /* * If the EXT2F_ROCOMPAT_SPARSESUPER flag is set, the cylinder group has a @@ -462,16 +450,14 @@ static __inline int cg_has_sb(int) __unused; static __inline int cg_has_sb(int i) { - int a3, a5, a7; - - if (i == 0 || i == 1) - return 1; - for (a3 = 3, a5 = 5, a7 = 7; - a3 <= i || a5 <= i || a7 <= i; - a3 *= 3, a5 *= 5, a7 *= 7) - if (i == a3 || i == a5 || i == a7) - return 1; - return 0; + int a3, a5, a7; + + if (i == 0 || i == 1) + return 1; + for (a3 = 3, a5 = 5, a7 = 7; a3 <= i || a5 <= i || a7 <= i; a3 *= 3, a5 *= 5, a7 *= 7) + if (i == a3 || i == a5 || i == a7) + return 1; + return 0; } /* EXT2FS metadatas are stored in little-endian byte order. These macros @@ -479,27 +465,27 @@ cg_has_sb(int i) */ #ifdef fsck_little_endian -# define h2fs16(x) (x) -# define h2fs32(x) (x) -# define h2fs64(x) (x) -# define fs2h16(x) (x) -# define fs2h32(x) (x) -# define fs2h64(x) (x) -# define e2fs_sbload(old, new) memcpy((new), (old), SBSIZE) -# define e2fs_sbsave(old, new) memcpy((new), (old), SBSIZE) +#define h2fs16(x) (x) +#define h2fs32(x) (x) +#define h2fs64(x) (x) +#define fs2h16(x) (x) +#define fs2h32(x) (x) +#define fs2h64(x) (x) +#define e2fs_sbload(old, new) memcpy((new), (old), SBSIZE) +#define e2fs_sbsave(old, new) memcpy((new), (old), SBSIZE) #else void e2fs_sb_bswap(struct ext2fs *, struct ext2fs *); -# define h2fs16(x) bswap16(x) -# define h2fs32(x) bswap32(x) -# define h2fs64(x) bswap64(x) -# define fs2h16(x) bswap16(x) -# define fs2h32(x) bswap32(x) -# define fs2h64(x) bswap64(x) -# define e2fs_sbload(old, new) e2fs_sb_bswap((old), (new)) -# define e2fs_sbsave(old, new) e2fs_sb_bswap((old), (new)) +#define h2fs16(x) bswap16(x) +#define h2fs32(x) bswap32(x) +#define h2fs64(x) bswap64(x) +#define fs2h16(x) bswap16(x) +#define fs2h32(x) bswap32(x) +#define fs2h64(x) bswap64(x) +#define e2fs_sbload(old, new) e2fs_sb_bswap((old), (new)) +#define e2fs_sbsave(old, new) e2fs_sb_bswap((old), (new)) #endif -#ifndef _KERNEL /* XXX */ +#ifndef _KERNEL /* XXX */ /* Group descriptors are not byte swapped */ #define e2fs_cgload(old, new, size) memcpy((new), (old), (size)) #define e2fs_cgsave(old, new, size) memcpy((new), (old), (size)) @@ -509,12 +495,11 @@ void e2fs_sb_bswap(struct ext2fs *, struct ext2fs *); * Turn file system block numbers into disk block addresses. * This maps file system blocks to device size blocks. */ -#define EXT2_FSBTODB(fs, b) ((int64_t)(b) << (fs)->e2fs_fsbtodb) -#define EXT2_FSBTODB64(fs, b, b_hi) \ - (((((uint64_t)(b_hi)) << 32) | (b)) << (fs)->e2fs_fsbtodb) -#define EXT2_FSBTODB64OFF(fs, b, b_hi, off) \ - ((((((uint64_t)(b_hi)) << 32) | (b)) + (off)) << (fs)->e2fs_fsbtodb) -#define EXT2_DBTOFSB(fs, b) ((b) >> (fs)->e2fs_fsbtodb) +#define EXT2_FSBTODB(fs, b) ((int64_t)(b) << (fs)->e2fs_fsbtodb) +#define EXT2_FSBTODB64(fs, b, b_hi) (((((uint64_t)(b_hi)) << 32) | (b)) << (fs)->e2fs_fsbtodb) +#define EXT2_FSBTODB64OFF(fs, b, b_hi, off) \ + ((((((uint64_t)(b_hi)) << 32) | (b)) + (off)) << (fs)->e2fs_fsbtodb) +#define EXT2_DBTOFSB(fs, b) ((b) >> (fs)->e2fs_fsbtodb) /* * Macros for handling inode numbers: @@ -522,47 +507,43 @@ void e2fs_sb_bswap(struct ext2fs *, struct ext2fs *); * inode number to cylinder group number. * inode number to file system block address. */ -#define ino_to_cg(fs, x) (((x) - 1) / (fs)->e2fs.e2fs_ipg) -#define _e2fs_gd(fs, x) (fs)->e2fs_gd[ino_to_cg((fs), (x))] -#define ino_to_fsba(fs, x) \ - (fs2h32(_e2fs_gd(fs, x).ext2bgd_i_tables) + \ - (((uint64_t)fs2h32(_e2fs_gd(fs, x).ext2bgd_i_tables_hi)) << 32) + \ - (((x) - 1) % (fs)->e2fs.e2fs_ipg) / (fs)->e2fs_ipb) -#define ino_to_fsbo(fs, x) (((x) - 1) % (fs)->e2fs_ipb) +#define ino_to_cg(fs, x) (((x) - 1) / (fs)->e2fs.e2fs_ipg) +#define _e2fs_gd(fs, x) (fs)->e2fs_gd[ino_to_cg((fs), (x))] +#define ino_to_fsba(fs, x) \ + (fs2h32(_e2fs_gd(fs, x).ext2bgd_i_tables) \ + + (((uint64_t)fs2h32(_e2fs_gd(fs, x).ext2bgd_i_tables_hi)) << 32) \ + + (((x) - 1) % (fs)->e2fs.e2fs_ipg) / (fs)->e2fs_ipb) +#define ino_to_fsbo(fs, x) (((x) - 1) % (fs)->e2fs_ipb) /* * Give cylinder group number for a file system block. * Give cylinder group block number for a file system block. */ -#define dtog(fs, d) (((d) - (fs)->e2fs.e2fs_first_dblock) / (fs)->e2fs.e2fs_fpg) -#define dtogd(fs, d) \ - (((d) - (fs)->e2fs.e2fs_first_dblock) % (fs)->e2fs.e2fs_fpg) +#define dtog(fs, d) (((d) - (fs)->e2fs.e2fs_first_dblock) / (fs)->e2fs.e2fs_fpg) +#define dtogd(fs, d) (((d) - (fs)->e2fs.e2fs_first_dblock) % (fs)->e2fs.e2fs_fpg) /* * The following macros optimize certain frequently calculated * quantities by using shifts and masks in place of divisions * modulos and multiplications. */ -#define ext2_blkoff(fs, loc) /* calculates (loc % fs->e2fs_bsize) */ \ - ((loc) & (fs)->e2fs_qbmask) -#define ext2_lblktosize(fs, blk) /* calculates (blk * fs->e2fs_bsize) */ \ - ((blk) << (fs)->e2fs_bshift) -#define ext2_lblkno(fs, loc) /* calculates (loc / fs->e2fs_bsize) */ \ - ((loc) >> (fs)->e2fs_bshift) -#define ext2_blkroundup(fs, size) /* calculates roundup(size, fs->e2fs_bsize) */ \ - (((size) + (fs)->e2fs_qbmask) & (fs)->e2fs_bmask) -#define ext2_fragroundup(fs, size) /* calculates roundup(size, fs->e2fs_bsize) */ \ - (((size) + (fs)->e2fs_qbmask) & (fs)->e2fs_bmask) +#define ext2_blkoff(fs, loc) /* calculates (loc % fs->e2fs_bsize) */ ((loc) & (fs)->e2fs_qbmask) +#define ext2_lblktosize(fs, blk) /* calculates (blk * fs->e2fs_bsize) */ \ + ((blk) << (fs)->e2fs_bshift) +#define ext2_lblkno(fs, loc) /* calculates (loc / fs->e2fs_bsize) */ ((loc) >> (fs)->e2fs_bshift) +#define ext2_blkroundup(fs, size) /* calculates roundup(size, fs->e2fs_bsize) */ \ + (((size) + (fs)->e2fs_qbmask) & (fs)->e2fs_bmask) +#define ext2_fragroundup(fs, size) /* calculates roundup(size, fs->e2fs_bsize) */ \ + (((size) + (fs)->e2fs_qbmask) & (fs)->e2fs_bmask) /* * Determine the number of available frags given a * percentage to hold in reserve. */ -#define freespace(fs) \ - ((fs)->e2fs.e2fs_fbcount - (fs)->e2fs.e2fs_rbcount) +#define freespace(fs) ((fs)->e2fs.e2fs_fbcount - (fs)->e2fs.e2fs_rbcount) /* * Number of indirects in a file system block. */ -#define EXT2_NINDIR(fs) ((fs)->e2fs_bsize / sizeof(uint32_t)) +#define EXT2_NINDIR(fs) ((fs)->e2fs_bsize / sizeof(uint32_t)) #endif /* !_UFS_EXT2FS_EXT2FS_H_ */ diff --git a/cmd/extra/fsck.ext4/ufs/ext2fs/ext2fs_dinode.h b/cmd/extra/fsck.ext4/ufs/ext2fs/ext2fs_dinode.h @@ -79,15 +79,15 @@ * the root inode is 2. * Inode 3 to 10 are reserved in ext2fs. */ -#define EXT2_BADBLKINO ((ino_t)1) -#define EXT2_ROOTINO ((ino_t)2) -#define EXT2_ACLIDXINO ((ino_t)3) -#define EXT2_ACLDATAINO ((ino_t)4) -#define EXT2_BOOTLOADERINO ((ino_t)5) -#define EXT2_UNDELDIRINO ((ino_t)6) -#define EXT2_RESIZEINO ((ino_t)7) -#define EXT2_JOURNALINO ((ino_t)8) -#define EXT2_FIRSTINO ((ino_t)11) +#define EXT2_BADBLKINO ((ino_t)1) +#define EXT2_ROOTINO ((ino_t)2) +#define EXT2_ACLIDXINO ((ino_t)3) +#define EXT2_ACLDATAINO ((ino_t)4) +#define EXT2_BOOTLOADERINO ((ino_t)5) +#define EXT2_UNDELDIRINO ((ino_t)6) +#define EXT2_RESIZEINO ((ino_t)7) +#define EXT2_JOURNALINO ((ino_t)8) +#define EXT2_FIRSTINO ((ino_t)11) /* * A dinode contains all the meta-data associated with a UFS file. @@ -101,164 +101,165 @@ * far from clear that there isn't code that relies on them being the * same. */ -#define EXT2FS_NDADDR 12 /* Direct addresses in inode. */ -#define EXT2FS_NIADDR 3 /* Indirect addresses in inode. */ +#define EXT2FS_NDADDR 12 /* Direct addresses in inode. */ +#define EXT2FS_NIADDR 3 /* Indirect addresses in inode. */ -#define EXT2_MAXSYMLINKLEN ((EXT2FS_NDADDR+EXT2FS_NIADDR) * sizeof (uint32_t)) -#define E2MAXSYMLINKLEN EXT2_MAXSYMLINKLEN +#define EXT2_MAXSYMLINKLEN ((EXT2FS_NDADDR + EXT2FS_NIADDR) * sizeof(uint32_t)) +#define E2MAXSYMLINKLEN EXT2_MAXSYMLINKLEN struct ext2fs_dinode { - uint16_t e2di_mode; /* 0: IFMT, permissions; see below. */ - uint16_t e2di_uid; /* 2: Owner UID */ - uint32_t e2di_size; /* 4: Size (in bytes) */ - uint32_t e2di_atime; /* 8: Access time */ - uint32_t e2di_ctime; /* 12: Create time */ - uint32_t e2di_mtime; /* 16: Modification time */ - uint32_t e2di_dtime; /* 20: Deletion time */ - uint16_t e2di_gid; /* 24: Owner GID */ - uint16_t e2di_nlink; /* 26: File link count */ - uint32_t e2di_nblock; /* 28: Blocks count */ - uint32_t e2di_flags; /* 32: Status flags (chflags) */ - uint32_t e2di_version; /* 36: was reserved1 */ - uint32_t e2di_blocks[EXT2FS_NDADDR+EXT2FS_NIADDR]; - /* 40: disk blocks */ - uint32_t e2di_gen; /* 100: generation number */ - uint32_t e2di_facl; /* 104: file ACL (ext3) */ - uint32_t e2di_size_high; /* 108: Size (in bytes) high */ - uint32_t e2di_obso_faddr;/* 112: obsolete fragment address (ext2) */ - uint16_t e2di_nblock_high; /* 116: Blocks count bits 47:32 (ext4) */ - uint16_t e2di_facl_high; /* 118: file ACL bits 47:32 (ext4/64bit) */ - uint16_t e2di_uid_high; /* 120: Owner UID top 16 bits (ext4) */ - uint16_t e2di_gid_high; /* 122: Owner GID top 16 bits (ext4) */ - uint16_t e2di_checksum_low; /* 124: crc LE (not implemented) (ext4) */ - uint16_t e2di_reserved; /* 126: reserved */ - uint16_t e2di_extra_isize; /* 128: inode extra size (over 128) actually used (ext4) */ - uint16_t e2di_checksum_high; /* 130: crc BE (not implemented) (ext4) */ - uint32_t e2di_ctime_extra; /* 132: ctime (nsec << 2 | high epoch) (ext4) */ - uint32_t e2di_mtime_extra; /* 136: mtime (nsec << 2 | high epoch) (ext4) */ - uint32_t e2di_atime_extra; /* 140: atime (nsec << 2 | high epoch) (ext4) */ - uint32_t e2di_crtime; /* 144: creation time (epoch) (ext4) */ - uint32_t e2di_crtime_extra; /* 148: creation time (nsec << 2 | high epoch) (ext4) */ - uint32_t e2di_version_high; /* 152: version high (ext4) */ - uint32_t e2di_projid; /* 156: project id (not implemented) (ext4) */ + uint16_t e2di_mode; /* 0: IFMT, permissions; see below. */ + uint16_t e2di_uid; /* 2: Owner UID */ + uint32_t e2di_size; /* 4: Size (in bytes) */ + uint32_t e2di_atime; /* 8: Access time */ + uint32_t e2di_ctime; /* 12: Create time */ + uint32_t e2di_mtime; /* 16: Modification time */ + uint32_t e2di_dtime; /* 20: Deletion time */ + uint16_t e2di_gid; /* 24: Owner GID */ + uint16_t e2di_nlink; /* 26: File link count */ + uint32_t e2di_nblock; /* 28: Blocks count */ + uint32_t e2di_flags; /* 32: Status flags (chflags) */ + uint32_t e2di_version; /* 36: was reserved1 */ + uint32_t e2di_blocks[EXT2FS_NDADDR + EXT2FS_NIADDR]; + /* 40: disk blocks */ + uint32_t e2di_gen; /* 100: generation number */ + uint32_t e2di_facl; /* 104: file ACL (ext3) */ + uint32_t e2di_size_high; /* 108: Size (in bytes) high */ + uint32_t e2di_obso_faddr; /* 112: obsolete fragment address (ext2) */ + uint16_t e2di_nblock_high; /* 116: Blocks count bits 47:32 (ext4) */ + uint16_t e2di_facl_high; /* 118: file ACL bits 47:32 (ext4/64bit) */ + uint16_t e2di_uid_high; /* 120: Owner UID top 16 bits (ext4) */ + uint16_t e2di_gid_high; /* 122: Owner GID top 16 bits (ext4) */ + uint16_t e2di_checksum_low; /* 124: crc LE (not implemented) (ext4) */ + uint16_t e2di_reserved; /* 126: reserved */ + uint16_t e2di_extra_isize; /* 128: inode extra size (over 128) actually used (ext4) */ + uint16_t e2di_checksum_high; /* 130: crc BE (not implemented) (ext4) */ + uint32_t e2di_ctime_extra; /* 132: ctime (nsec << 2 | high epoch) (ext4) */ + uint32_t e2di_mtime_extra; /* 136: mtime (nsec << 2 | high epoch) (ext4) */ + uint32_t e2di_atime_extra; /* 140: atime (nsec << 2 | high epoch) (ext4) */ + uint32_t e2di_crtime; /* 144: creation time (epoch) (ext4) */ + uint32_t e2di_crtime_extra; /* 148: creation time (nsec << 2 | high epoch) (ext4) */ + uint32_t e2di_version_high; /* 152: version high (ext4) */ + uint32_t e2di_projid; /* 156: project id (not implemented) (ext4) */ }; -#define i_e2fs_mode i_din.e2fs_din->e2di_mode -#define i_e2fs_uid i_din.e2fs_din->e2di_uid -#define i_e2fs_size i_din.e2fs_din->e2di_size -#define i_e2fs_atime i_din.e2fs_din->e2di_atime -#define i_e2fs_ctime i_din.e2fs_din->e2di_ctime -#define i_e2fs_mtime i_din.e2fs_din->e2di_mtime -#define i_e2fs_dtime i_din.e2fs_din->e2di_dtime -#define i_e2fs_gid i_din.e2fs_din->e2di_gid -#define i_e2fs_nlink i_din.e2fs_din->e2di_nlink -#define i_e2fs_nblock i_din.e2fs_din->e2di_nblock -#define i_e2fs_flags i_din.e2fs_din->e2di_flags -#define i_e2fs_version i_din.e2fs_din->e2di_version -#define i_e2fs_blocks i_din.e2fs_din->e2di_blocks -#define i_e2fs_rdev i_din.e2fs_din->e2di_rdev -#define i_e2fs_gen i_din.e2fs_din->e2di_gen -#define i_e2fs_facl i_din.e2fs_din->e2di_facl -#define i_e2fs_nblock_high i_din.e2fs_din->e2di_nblock_high -#define i_e2fs_facl_high i_din.e2fs_din->e2di_facl_high -#define i_e2fs_uid_high i_din.e2fs_din->e2di_uid_high -#define i_e2fs_gid_high i_din.e2fs_din->e2di_gid_high +#define i_e2fs_mode i_din.e2fs_din->e2di_mode +#define i_e2fs_uid i_din.e2fs_din->e2di_uid +#define i_e2fs_size i_din.e2fs_din->e2di_size +#define i_e2fs_atime i_din.e2fs_din->e2di_atime +#define i_e2fs_ctime i_din.e2fs_din->e2di_ctime +#define i_e2fs_mtime i_din.e2fs_din->e2di_mtime +#define i_e2fs_dtime i_din.e2fs_din->e2di_dtime +#define i_e2fs_gid i_din.e2fs_din->e2di_gid +#define i_e2fs_nlink i_din.e2fs_din->e2di_nlink +#define i_e2fs_nblock i_din.e2fs_din->e2di_nblock +#define i_e2fs_flags i_din.e2fs_din->e2di_flags +#define i_e2fs_version i_din.e2fs_din->e2di_version +#define i_e2fs_blocks i_din.e2fs_din->e2di_blocks +#define i_e2fs_rdev i_din.e2fs_din->e2di_rdev +#define i_e2fs_gen i_din.e2fs_din->e2di_gen +#define i_e2fs_facl i_din.e2fs_din->e2di_facl +#define i_e2fs_nblock_high i_din.e2fs_din->e2di_nblock_high +#define i_e2fs_facl_high i_din.e2fs_din->e2di_facl_high +#define i_e2fs_uid_high i_din.e2fs_din->e2di_uid_high +#define i_e2fs_gid_high i_din.e2fs_din->e2di_gid_high /* File permissions. */ -#define EXT2_IEXEC 0000100 /* Executable. */ -#define EXT2_IWRITE 0000200 /* Writable. */ -#define EXT2_IREAD 0000400 /* Readable. */ -#define EXT2_ISVTX 0001000 /* Sticky bit. */ -#define EXT2_ISGID 0002000 /* Set-gid. */ -#define EXT2_ISUID 0004000 /* Set-uid. */ +#define EXT2_IEXEC 0000100 /* Executable. */ +#define EXT2_IWRITE 0000200 /* Writable. */ +#define EXT2_IREAD 0000400 /* Readable. */ +#define EXT2_ISVTX 0001000 /* Sticky bit. */ +#define EXT2_ISGID 0002000 /* Set-gid. */ +#define EXT2_ISUID 0004000 /* Set-uid. */ /* File types. */ -#define EXT2_IFMT 0170000 /* Mask of file type. */ -#define EXT2_IFIFO 0010000 /* Named pipe (fifo). */ -#define EXT2_IFCHR 0020000 /* Character device. */ -#define EXT2_IFDIR 0040000 /* Directory file. */ -#define EXT2_IFBLK 0060000 /* Block device. */ -#define EXT2_IFREG 0100000 /* Regular file. */ -#define EXT2_IFLNK 0120000 /* Symbolic link. */ -#define EXT2_IFSOCK 0140000 /* UNIX domain socket. */ +#define EXT2_IFMT 0170000 /* Mask of file type. */ +#define EXT2_IFIFO 0010000 /* Named pipe (fifo). */ +#define EXT2_IFCHR 0020000 /* Character device. */ +#define EXT2_IFDIR 0040000 /* Directory file. */ +#define EXT2_IFBLK 0060000 /* Block device. */ +#define EXT2_IFREG 0100000 /* Regular file. */ +#define EXT2_IFLNK 0120000 /* Symbolic link. */ +#define EXT2_IFSOCK 0140000 /* UNIX domain socket. */ /* file flags */ -#define EXT2_SECRM 0x00000001 /* Secure deletion */ -#define EXT2_UNRM 0x00000002 /* Undelete */ -#define EXT2_COMPR 0x00000004 /* Compress file */ -#define EXT2_SYNC 0x00000008 /* Synchronous updates */ -#define EXT2_IMMUTABLE 0x00000010 /* Immutable file */ -#define EXT2_APPEND 0x00000020 /* writes to file may only append */ -#define EXT2_NODUMP 0x00000040 /* do not dump file */ -#define EXT2_NOATIME 0x00000080 /* do not update atime */ -#define EXT2_INDEX 0x00001000 /* hash-indexed directory */ -#define EXT2_IMAGIC 0x00002000 /* AFS directory */ -#define EXT2_JOURNAL_DATA 0x00004000 /* file data should be journaled */ -#define EXT2_NOTAIL 0x00008000 /* file tail should not be merged */ -#define EXT2_DIRSYNC 0x00010000 /* dirsync behaviour */ -#define EXT2_TOPDIR 0x00020000 /* Top of directory hierarchies*/ -#define EXT2_HUGE_FILE 0x00040000 /* Set to each huge file */ -#define EXT2_EXTENTS 0x00080000 /* Inode uses extents */ -#define EXT2_EA_INODE 0x00200000 /* Inode used for large EA */ -#define EXT2_EOFBLOCKS 0x00400000 /* Blocks allocated beyond EOF */ -#define EXT2_INLINE_DATA 0x10000000 /* Inode has inline data */ -#define EXT2_PROJINHERIT 0x20000000 /* Children inherit project ID */ +#define EXT2_SECRM 0x00000001 /* Secure deletion */ +#define EXT2_UNRM 0x00000002 /* Undelete */ +#define EXT2_COMPR 0x00000004 /* Compress file */ +#define EXT2_SYNC 0x00000008 /* Synchronous updates */ +#define EXT2_IMMUTABLE 0x00000010 /* Immutable file */ +#define EXT2_APPEND 0x00000020 /* writes to file may only append */ +#define EXT2_NODUMP 0x00000040 /* do not dump file */ +#define EXT2_NOATIME 0x00000080 /* do not update atime */ +#define EXT2_INDEX 0x00001000 /* hash-indexed directory */ +#define EXT2_IMAGIC 0x00002000 /* AFS directory */ +#define EXT2_JOURNAL_DATA 0x00004000 /* file data should be journaled */ +#define EXT2_NOTAIL 0x00008000 /* file tail should not be merged */ +#define EXT2_DIRSYNC 0x00010000 /* dirsync behaviour */ +#define EXT2_TOPDIR 0x00020000 /* Top of directory hierarchies*/ +#define EXT2_HUGE_FILE 0x00040000 /* Set to each huge file */ +#define EXT2_EXTENTS 0x00080000 /* Inode uses extents */ +#define EXT2_EA_INODE 0x00200000 /* Inode used for large EA */ +#define EXT2_EOFBLOCKS 0x00400000 /* Blocks allocated beyond EOF */ +#define EXT2_INLINE_DATA 0x10000000 /* Inode has inline data */ +#define EXT2_PROJINHERIT 0x20000000 /* Children inherit project ID */ /* Size of on-disk inode. */ -#define EXT2_REV0_DINODE_SIZE 128U -#define EXT2_DINODE_SIZE(fs) ((fs)->e2fs.e2fs_rev > E2FS_REV0 ? \ - (fs)->e2fs.e2fs_inode_size : \ - EXT2_REV0_DINODE_SIZE) -#define EXT2_DINODE_FITS(dinode, field, isize) (\ - (isize > EXT2_REV0_DINODE_SIZE) \ - && ((EXT2_REV0_DINODE_SIZE + (dinode)->e2di_extra_isize) >= offsetof(struct ext2fs_dinode, field) + sizeof((dinode)->field)) \ - ) +#define EXT2_REV0_DINODE_SIZE 128U +#define EXT2_DINODE_SIZE(fs) \ + ((fs)->e2fs.e2fs_rev > E2FS_REV0 ? (fs)->e2fs.e2fs_inode_size : EXT2_REV0_DINODE_SIZE) +#define EXT2_DINODE_FITS(dinode, field, isize) \ + ((isize > EXT2_REV0_DINODE_SIZE) \ + && ((EXT2_REV0_DINODE_SIZE + (dinode)->e2di_extra_isize) \ + >= offsetof(struct ext2fs_dinode, field) + sizeof((dinode)->field))) /* * Time encoding - * Lower two bits of extra field are extra high bits for epoch; unfortunately still, Linux kernels treat 11 there as 00 for compatibility - * Rest of extra fields are nanoseconds + * Lower two bits of extra field are extra high bits for epoch; unfortunately still, Linux kernels + * treat 11 there as 00 for compatibility Rest of extra fields are nanoseconds */ static __inline void ext2fs_dinode_time_get(struct timespec *ts, uint32_t epoch, uint32_t extra) { - ts->tv_sec = (signed) epoch; + ts->tv_sec = (signed)epoch; - if (extra) { - uint64_t epoch_bits = extra & 0x3; - /* XXX compatibility with linux kernel < 4.20 */ - if (epoch_bits == 3 && ts->tv_sec < 0) - epoch_bits = 0; + if (extra) { + uint64_t epoch_bits = extra & 0x3; + /* XXX compatibility with linux kernel < 4.20 */ + if (epoch_bits == 3 && ts->tv_sec < 0) + epoch_bits = 0; - ts->tv_sec |= epoch_bits << 32; + ts->tv_sec |= epoch_bits << 32; - ts->tv_nsec = extra >> 2; - } else { - ts->tv_nsec = 0; - } + ts->tv_nsec = extra >> 2; + } else { + ts->tv_nsec = 0; + } } -#define EXT2_DINODE_TIME_GET(ts, dinode, field, isize) \ - ext2fs_dinode_time_get(ts, (dinode)->field, \ - EXT2_DINODE_FITS(dinode, field ## _extra, isize) \ - ? (dinode)->field ## _extra : 0 \ - ) +#define EXT2_DINODE_TIME_GET(ts, dinode, field, isize) \ + ext2fs_dinode_time_get( \ + ts, \ + (dinode)->field, \ + EXT2_DINODE_FITS(dinode, field##_extra, isize) ? (dinode)->field##_extra : 0 \ + ) static __inline void ext2fs_dinode_time_set(const struct timespec *ts, uint32_t *epoch, uint32_t *extra) { - *epoch = (int32_t) ts->tv_sec; + *epoch = (int32_t)ts->tv_sec; - if (extra) { - uint32_t epoch_bits = (ts->tv_sec >> 32) & 0x3; + if (extra) { + uint32_t epoch_bits = (ts->tv_sec >> 32) & 0x3; - *extra = (ts->tv_nsec << 2) | epoch_bits; - } + *extra = (ts->tv_nsec << 2) | epoch_bits; + } } -#define EXT2_DINODE_TIME_SET(ts, dinode, field, isize) \ - ext2fs_dinode_time_set(ts, &(dinode)->field, \ - EXT2_DINODE_FITS(dinode, field ## _extra, isize) \ - ? &(dinode)->field ## _extra : NULL \ - ) +#define EXT2_DINODE_TIME_SET(ts, dinode, field, isize) \ + ext2fs_dinode_time_set( \ + ts, \ + &(dinode)->field, \ + EXT2_DINODE_FITS(dinode, field##_extra, isize) ? &(dinode)->field##_extra : NULL \ + ) /* * The e2di_blocks fields may be overlaid with other information for @@ -268,19 +269,17 @@ ext2fs_dinode_time_set(const struct timespec *ts, uint32_t *epoch, uint32_t *ext * di_db area. */ -#define e2di_rdev e2di_blocks[0] -#define e2di_shortlink e2di_blocks +#define e2di_rdev e2di_blocks[0] +#define e2di_shortlink e2di_blocks /* e2fs needs byte swapping on big-endian systems */ #if BYTE_ORDER == LITTLE_ENDIAN -# define e2fs_iload(old, new, isize) \ - memcpy((new),(old),(isize)) -# define e2fs_isave(old, new, isize) \ - memcpy((new),(old),(isize)) +#define e2fs_iload(old, new, isize) memcpy((new), (old), (isize)) +#define e2fs_isave(old, new, isize) memcpy((new), (old), (isize)) #else void e2fs_i_bswap(struct ext2fs_dinode *, struct ext2fs_dinode *, size_t); -# define e2fs_iload(old, new, isize) e2fs_i_bswap((old), (new), (isize)) -# define e2fs_isave(old, new, isize) e2fs_i_bswap((old), (new), (isize)) +#define e2fs_iload(old, new, isize) e2fs_i_bswap((old), (new), (isize)) +#define e2fs_isave(old, new, isize) e2fs_i_bswap((old), (new), (isize)) #endif #endif /* !_UFS_EXT2FS_EXT2FS_DINODE_H_ */ diff --git a/cmd/extra/fsck.ext4/ufs/ext2fs/ext2fs_dir.h b/cmd/extra/fsck.ext4/ufs/ext2fs/ext2fs_dir.h @@ -65,7 +65,7 @@ */ #ifndef _UFS_EXT2FS_EXT2FS_DIR_H_ -#define _UFS_EXT2FS_EXT2FS_DIR_H_ +#define _UFS_EXT2FS_EXT2FS_DIR_H_ #include <dirent.h> #include <ufs/ext2fs/ext2fs_dinode.h> @@ -75,8 +75,8 @@ * practice this seems unlikely. So, we define the type doff_t as a 32-bit * quantity to keep down the cost of doing lookup on a 32-bit machine. */ -#define doff_t int32_t -#define EXT2FS_MAXDIRSIZE INT32_MAX +#define doff_t int32_t +#define EXT2FS_MAXDIRSIZE INT32_MAX /* * A directory consists of some number of blocks of e2fs_bsize bytes. @@ -105,91 +105,86 @@ * It's safe to use this for rev 0 as well because all ext2 are little-endian. */ -#define EXT2FS_MAXNAMLEN 255 +#define EXT2FS_MAXNAMLEN 255 -struct ext2fs_direct { - uint32_t e2d_ino; /* inode number of entry */ - uint16_t e2d_reclen; /* length of this record */ - uint8_t e2d_namlen; /* length of string in d_name */ - uint8_t e2d_type; /* file type */ - char e2d_name[EXT2FS_MAXNAMLEN];/* name with length<=EXT2FS_MAXNAMLEN */ +struct ext2fs_direct { + uint32_t e2d_ino; /* inode number of entry */ + uint16_t e2d_reclen; /* length of this record */ + uint8_t e2d_namlen; /* length of string in d_name */ + uint8_t e2d_type; /* file type */ + char e2d_name[EXT2FS_MAXNAMLEN]; /* name with length<=EXT2FS_MAXNAMLEN */ }; -enum ext2fs_slotstatus { - NONE, - COMPACT, - FOUND -}; +enum ext2fs_slotstatus { NONE, COMPACT, FOUND }; struct ext2fs_searchslot { - enum ext2fs_slotstatus slotstatus; - doff_t slotoffset; /* offset of area with free space */ - int slotsize; /* size of area at slotoffset */ - int slotfreespace; /* amount of space free in slot */ - int slotneeded; /* sizeof the entry we are seeking */ + enum ext2fs_slotstatus slotstatus; + doff_t slotoffset; /* offset of area with free space */ + int slotsize; /* size of area at slotoffset */ + int slotfreespace; /* amount of space free in slot */ + int slotneeded; /* sizeof the entry we are seeking */ }; /* Ext2 directory file types (not the same as FFS. Sigh.) */ -#define EXT2_FT_UNKNOWN 0 -#define EXT2_FT_REG_FILE 1 -#define EXT2_FT_DIR 2 -#define EXT2_FT_CHRDEV 3 -#define EXT2_FT_BLKDEV 4 -#define EXT2_FT_FIFO 5 -#define EXT2_FT_SOCK 6 -#define EXT2_FT_SYMLINK 7 +#define EXT2_FT_UNKNOWN 0 +#define EXT2_FT_REG_FILE 1 +#define EXT2_FT_DIR 2 +#define EXT2_FT_CHRDEV 3 +#define EXT2_FT_BLKDEV 4 +#define EXT2_FT_FIFO 5 +#define EXT2_FT_SOCK 6 +#define EXT2_FT_SYMLINK 7 -#define EXT2_FT_MAX 8 +#define EXT2_FT_MAX 8 -#define E2IFTODT(mode) (((mode) & 0170000) >> 12) +#define E2IFTODT(mode) (((mode) & 0170000) >> 12) static __inline uint8_t inot2ext2dt(uint16_t) __unused; static __inline uint8_t inot2ext2dt(uint16_t type) { - - switch (type) { - case E2IFTODT(EXT2_IFIFO): - return EXT2_FT_FIFO; - case E2IFTODT(EXT2_IFCHR): - return EXT2_FT_CHRDEV; - case E2IFTODT(EXT2_IFDIR): - return EXT2_FT_DIR; - case E2IFTODT(EXT2_IFBLK): - return EXT2_FT_BLKDEV; - case E2IFTODT(EXT2_IFREG): - return EXT2_FT_REG_FILE; - case E2IFTODT(EXT2_IFLNK): - return EXT2_FT_SYMLINK; - case E2IFTODT(EXT2_IFSOCK): - return EXT2_FT_SOCK; - default: - return 0; - } + switch (type) { + case E2IFTODT(EXT2_IFIFO): + return EXT2_FT_FIFO; + case E2IFTODT(EXT2_IFCHR): + return EXT2_FT_CHRDEV; + case E2IFTODT(EXT2_IFDIR): + return EXT2_FT_DIR; + case E2IFTODT(EXT2_IFBLK): + return EXT2_FT_BLKDEV; + case E2IFTODT(EXT2_IFREG): + return EXT2_FT_REG_FILE; + case E2IFTODT(EXT2_IFLNK): + return EXT2_FT_SYMLINK; + case E2IFTODT(EXT2_IFSOCK): + return EXT2_FT_SOCK; + default: + return 0; + } } static __inline uint8_t ext2dt2dt(uint8_t) __unused; static __inline uint8_t ext2dt2dt(uint8_t type) { - switch (type) { - case EXT2_FT_REG_FILE: - return DT_REG; - case EXT2_FT_DIR: - return DT_DIR; - case EXT2_FT_CHRDEV: - return DT_CHR; - case EXT2_FT_BLKDEV: - return DT_BLK; - case EXT2_FT_FIFO: - return DT_FIFO; - case EXT2_FT_SOCK: - return DT_SOCK; - case EXT2_FT_SYMLINK: - return DT_LNK; - default: - return DT_UNKNOWN; - } + switch (type) { + case EXT2_FT_REG_FILE: + return DT_REG; + case EXT2_FT_DIR: + return DT_DIR; + case EXT2_FT_CHRDEV: + return DT_CHR; + case EXT2_FT_BLKDEV: + return DT_BLK; + case EXT2_FT_FIFO: + return DT_FIFO; + case EXT2_FT_SOCK: + return DT_SOCK; + case EXT2_FT_SYMLINK: + return DT_LNK; + default: + return DT_UNKNOWN; + } } /* @@ -199,23 +194,23 @@ ext2dt2dt(uint8_t type) * without the d_name field, plus enough space for the name without a * terminating null byte, rounded up to a 4 byte boundary. */ -#define EXT2FS_DIRSIZ(len) roundup2(8 + len, 4) +#define EXT2FS_DIRSIZ(len) roundup2(8 + len, 4) /* * Template for manipulating directories. Should use struct direct's, * but the name field is EXT2FS_MAXNAMLEN - 1, and this just won't do. */ struct ext2fs_dirtemplate { - uint32_t dot_ino; - int16_t dot_reclen; - uint8_t dot_namlen; - uint8_t dot_type; - char dot_name[4]; /* must be multiple of 4 */ - uint32_t dotdot_ino; - int16_t dotdot_reclen; - uint8_t dotdot_namlen; - uint8_t dotdot_type; - char dotdot_name[4]; /* ditto */ + uint32_t dot_ino; + int16_t dot_reclen; + uint8_t dot_namlen; + uint8_t dot_type; + char dot_name[4]; /* must be multiple of 4 */ + uint32_t dotdot_ino; + int16_t dotdot_reclen; + uint8_t dotdot_namlen; + uint8_t dotdot_type; + char dotdot_name[4]; /* ditto */ }; /* @@ -223,9 +218,8 @@ struct ext2fs_dirtemplate { * * NOTE: It must be a multiple of 4 */ -#define EXT2_DIR_PAD 4 -#define EXT2_DIR_ROUND (EXT2_DIR_PAD - 1) -#define EXT2_DIR_REC_LEN(namelen) \ - (((namelen) + 8 + EXT2_DIR_ROUND) & ~EXT2_DIR_ROUND) +#define EXT2_DIR_PAD 4 +#define EXT2_DIR_ROUND (EXT2_DIR_PAD - 1) +#define EXT2_DIR_REC_LEN(namelen) (((namelen) + 8 + EXT2_DIR_ROUND) & ~EXT2_DIR_ROUND) #endif /* !_UFS_EXT2FS_EXT2FS_DIR_H_ */ diff --git a/cmd/extra/fsck.ext4/utilities.c b/cmd/extra/fsck.ext4/utilities.c @@ -81,61 +81,59 @@ __RCSID("$NetBSD: utilities.c,v 1.23 2013/06/23 02:06:04 dholland Exp $"); extern int unresolved; -long diskreads, totalreads; /* Disk cache statistics */ - +long diskreads, totalreads; /* Disk cache statistics */ int ftypeok(struct ext2fs_dinode *dp) { - switch (fs2h16(dp->e2di_mode) & IFMT) { - - case IFDIR: - case IFREG: - case IFBLK: - case IFCHR: - case IFLNK: - case IFSOCK: - case IFIFO: - return (1); - - default: - if (debug) - printf("bad file type 0%o\n", fs2h16(dp->e2di_mode)); - return (0); - } + switch (fs2h16(dp->e2di_mode) & IFMT) { + case IFDIR: + case IFREG: + case IFBLK: + case IFCHR: + case IFLNK: + case IFSOCK: + case IFIFO: + return (1); + + default: + if (debug) + printf("bad file type 0%o\n", fs2h16(dp->e2di_mode)); + return (0); + } } int reply(const char *question) { - int persevere; - char c; - - if (preen) - pfatal("INTERNAL ERROR: GOT TO reply()"); - persevere = !strcmp(question, "CONTINUE"); - printf("\n"); - if (!persevere && (nflag || fswritefd < 0)) { - unresolved = 1; - printf("%s? no\n\n", question); - return (0); - } - if (yflag || (persevere && nflag)) { - printf("%s? yes\n\n", question); - return (1); - } - do { - printf("%s? [yn] ", question); - (void) fflush(stdout); - c = getc(stdin); - while (c != '\n' && getc(stdin) != '\n') - if (feof(stdin)) - return (0); - } while (c != 'y' && c != 'Y' && c != 'n' && c != 'N'); - printf("\n"); - if (c == 'y' || c == 'Y') - return (1); - return (0); + int persevere; + char c; + + if (preen) + pfatal("INTERNAL ERROR: GOT TO reply()"); + persevere = !strcmp(question, "CONTINUE"); + printf("\n"); + if (!persevere && (nflag || fswritefd < 0)) { + unresolved = 1; + printf("%s? no\n\n", question); + return (0); + } + if (yflag || (persevere && nflag)) { + printf("%s? yes\n\n", question); + return (1); + } + do { + printf("%s? [yn] ", question); + (void)fflush(stdout); + c = getc(stdin); + while (c != '\n' && getc(stdin) != '\n') + if (feof(stdin)) + return (0); + } while (c != 'y' && c != 'Y' && c != 'n' && c != 'N'); + printf("\n"); + if (c == 'y' || c == 'Y') + return (1); + return (0); } /* @@ -144,34 +142,34 @@ reply(const char *question) void bufinit(void) { - struct bufarea *bp; - long bufcnt, i; - char *bufp; - - diskreads = totalreads = 0; - pbp = pdirbp = (struct bufarea *)0; - bufhead.b_next = bufhead.b_prev = &bufhead; - bufcnt = MAXBUFSPACE / sblock.e2fs_bsize; - if (bufcnt < MINBUFS) - bufcnt = MINBUFS; - for (i = 0; i < bufcnt; i++) { - bp = malloc(sizeof(struct bufarea)); - bufp = malloc((size_t)sblock.e2fs_bsize); - if (bp == NULL || bufp == NULL) { - free(bp); - free(bufp); - if (i >= MINBUFS) - break; - errexit("cannot allocate buffer pool"); - } - bp->b_un.b_buf = bufp; - bp->b_prev = &bufhead; - bp->b_next = bufhead.b_next; - bufhead.b_next->b_prev = bp; - bufhead.b_next = bp; - initbarea(bp); - } - bufhead.b_size = i; /* save number of buffers */ + struct bufarea *bp; + long bufcnt, i; + char *bufp; + + diskreads = totalreads = 0; + pbp = pdirbp = (struct bufarea *)0; + bufhead.b_next = bufhead.b_prev = &bufhead; + bufcnt = MAXBUFSPACE / sblock.e2fs_bsize; + if (bufcnt < MINBUFS) + bufcnt = MINBUFS; + for (i = 0; i < bufcnt; i++) { + bp = malloc(sizeof(struct bufarea)); + bufp = malloc((size_t)sblock.e2fs_bsize); + if (bp == NULL || bufp == NULL) { + free(bp); + free(bufp); + if (i >= MINBUFS) + break; + errexit("cannot allocate buffer pool"); + } + bp->b_un.b_buf = bufp; + bp->b_prev = &bufhead; + bp->b_next = bufhead.b_next; + bufhead.b_next->b_prev = bp; + bufhead.b_next = bp; + initbarea(bp); + } + bufhead.b_size = i; /* save number of buffers */ } /* @@ -180,140 +178,147 @@ bufinit(void) struct bufarea * getdatablk(daddr_t blkno, long size) { - struct bufarea *bp; - - for (bp = bufhead.b_next; bp != &bufhead; bp = bp->b_next) - if (bp->b_bno == EXT2_FSBTODB(&sblock, blkno)) - goto foundit; - for (bp = bufhead.b_prev; bp != &bufhead; bp = bp->b_prev) - if ((bp->b_flags & B_INUSE) == 0) - break; - if (bp == &bufhead) - errexit("deadlocked buffer pool"); - getblk(bp, blkno, size); - diskreads++; - /* fall through */ + struct bufarea *bp; + + for (bp = bufhead.b_next; bp != &bufhead; bp = bp->b_next) + if (bp->b_bno == EXT2_FSBTODB(&sblock, blkno)) + goto foundit; + for (bp = bufhead.b_prev; bp != &bufhead; bp = bp->b_prev) + if ((bp->b_flags & B_INUSE) == 0) + break; + if (bp == &bufhead) + errexit("deadlocked buffer pool"); + getblk(bp, blkno, size); + diskreads++; + /* fall through */ foundit: - totalreads++; - bp->b_prev->b_next = bp->b_next; - bp->b_next->b_prev = bp->b_prev; - bp->b_prev = &bufhead; - bp->b_next = bufhead.b_next; - bufhead.b_next->b_prev = bp; - bufhead.b_next = bp; - bp->b_flags |= B_INUSE; - return (bp); + totalreads++; + bp->b_prev->b_next = bp->b_next; + bp->b_next->b_prev = bp->b_prev; + bp->b_prev = &bufhead; + bp->b_next = bufhead.b_next; + bufhead.b_next->b_prev = bp; + bufhead.b_next = bp; + bp->b_flags |= B_INUSE; + return (bp); } void getblk(struct bufarea *bp, daddr_t blk, long size) { - daddr_t dblk; - - dblk = EXT2_FSBTODB(&sblock, blk); - if (bp->b_bno != dblk) { - flush(fswritefd, bp); - bp->b_errs = bread(fsreadfd, bp->b_un.b_buf, dblk, size); - bp->b_bno = dblk; - bp->b_size = size; - } + daddr_t dblk; + + dblk = EXT2_FSBTODB(&sblock, blk); + if (bp->b_bno != dblk) { + flush(fswritefd, bp); + bp->b_errs = bread(fsreadfd, bp->b_un.b_buf, dblk, size); + bp->b_bno = dblk; + bp->b_size = size; + } } void flush(int fd, struct bufarea *bp) { - int i; - - if (!bp->b_dirty) - return; - if (bp->b_errs != 0) - pfatal("WRITING %sZERO'ED BLOCK %lld TO DISK\n", - (bp->b_errs == bp->b_size / dev_bsize) ? "" : "PARTIALLY ", - (long long)bp->b_bno); - bp->b_dirty = 0; - bp->b_errs = 0; - bwrite(fd, bp->b_un.b_buf, bp->b_bno, (long)bp->b_size); - if (bp != &sblk) - return; - for (i = 0; i < sblock.e2fs_ngdb; i++) { - bwrite(fswritefd, (char *) - &sblock.e2fs_gd[i* sblock.e2fs_bsize / sizeof(struct ext2_gd)], - EXT2_FSBTODB(&sblock, ((sblock.e2fs_bsize>1024)?0:1)+i+1), - sblock.e2fs_bsize); - } + int i; + + if (!bp->b_dirty) + return; + if (bp->b_errs != 0) + pfatal( + "WRITING %sZERO'ED BLOCK %lld TO DISK\n", + (bp->b_errs == bp->b_size / dev_bsize) ? "" : "PARTIALLY ", + (long long)bp->b_bno + ); + bp->b_dirty = 0; + bp->b_errs = 0; + bwrite(fd, bp->b_un.b_buf, bp->b_bno, (long)bp->b_size); + if (bp != &sblk) + return; + for (i = 0; i < sblock.e2fs_ngdb; i++) { + bwrite( + fswritefd, + (char *)&sblock.e2fs_gd[i * sblock.e2fs_bsize / sizeof(struct ext2_gd)], + EXT2_FSBTODB(&sblock, ((sblock.e2fs_bsize > 1024) ? 0 : 1) + i + 1), + sblock.e2fs_bsize + ); + } } void ckfini(int markclean) { - struct bufarea *bp, *nbp; - int cnt = 0; - - if (fswritefd < 0) { - (void)close(fsreadfd); - return; - } - flush(fswritefd, &sblk); - if (havesb && sblk.b_bno != SBOFF / dev_bsize && - !preen && reply("UPDATE STANDARD SUPERBLOCKS")) { - sblk.b_bno = SBOFF / dev_bsize; - sbdirty(); - flush(fswritefd, &sblk); - copyback_sb(&asblk); - asblk.b_dirty = 1; - flush(fswritefd, &asblk); - } - for (bp = bufhead.b_prev; bp && bp != &bufhead; bp = nbp) { - cnt++; - flush(fswritefd, bp); - nbp = bp->b_prev; - free(bp->b_un.b_buf); - free(bp); - } - if (bufhead.b_size != cnt) - errexit("Panic: lost %d buffers", bufhead.b_size - cnt); - pbp = pdirbp = (struct bufarea *)0; - if (markclean && (sblock.e2fs.e2fs_state & E2FS_ISCLEAN) == 0) { - /* - * Mark the file system as clean, and sync the superblock. - */ - if (preen) - pwarn("MARKING FILE SYSTEM CLEAN\n"); - else if (!reply("MARK FILE SYSTEM CLEAN")) - markclean = 0; - if (markclean) { - sblock.e2fs.e2fs_state = E2FS_ISCLEAN; - sbdirty(); - flush(fswritefd, &sblk); - } - } - if (debug) - printf("cache missed %ld of %ld (%d%%)\n", diskreads, - totalreads, (int)(diskreads * 100 / totalreads)); - (void)close(fsreadfd); - (void)close(fswritefd); + struct bufarea *bp, *nbp; + int cnt = 0; + + if (fswritefd < 0) { + (void)close(fsreadfd); + return; + } + flush(fswritefd, &sblk); + if (havesb && sblk.b_bno != SBOFF / dev_bsize && !preen && reply("UPDATE STANDARD SUPERBLOCKS")) { + sblk.b_bno = SBOFF / dev_bsize; + sbdirty(); + flush(fswritefd, &sblk); + copyback_sb(&asblk); + asblk.b_dirty = 1; + flush(fswritefd, &asblk); + } + for (bp = bufhead.b_prev; bp && bp != &bufhead; bp = nbp) { + cnt++; + flush(fswritefd, bp); + nbp = bp->b_prev; + free(bp->b_un.b_buf); + free(bp); + } + if (bufhead.b_size != cnt) + errexit("Panic: lost %d buffers", bufhead.b_size - cnt); + pbp = pdirbp = (struct bufarea *)0; + if (markclean && (sblock.e2fs.e2fs_state & E2FS_ISCLEAN) == 0) { + /* + * Mark the file system as clean, and sync the superblock. + */ + if (preen) + pwarn("MARKING FILE SYSTEM CLEAN\n"); + else if (!reply("MARK FILE SYSTEM CLEAN")) + markclean = 0; + if (markclean) { + sblock.e2fs.e2fs_state = E2FS_ISCLEAN; + sbdirty(); + flush(fswritefd, &sblk); + } + } + if (debug) + printf( + "cache missed %ld of %ld (%d%%)\n", + diskreads, + totalreads, + (int)(diskreads * 100 / totalreads) + ); + (void)close(fsreadfd); + (void)close(fswritefd); } int bread(int fd, char *buf, daddr_t blk, long size) { - off_t offset; + off_t offset; - offset = blk; - offset *= dev_bsize; - if (blk < 0 || pread(fd, buf, size, offset) != size) - errexit("cannot read block %lld", (long long)blk); - return 0; + offset = blk; + offset *= dev_bsize; + if (blk < 0 || pread(fd, buf, size, offset) != size) + errexit("cannot read block %lld", (long long)blk); + return 0; } void bwrite(int fd, char *buf, daddr_t blk, long size) { - (void)fd; - (void)buf; - (void)blk; - (void)size; - errexit("write requested in read-only checker"); + (void)fd; + (void)buf; + (void)blk; + (void)size; + errexit("write requested in read-only checker"); } /* @@ -322,16 +327,16 @@ bwrite(int fd, char *buf, daddr_t blk, long size) int allocblk(void) { - int i; - - for (i = 0; i < maxfsblock - 1; i++) { - if (testbmap(i)) - continue; - setbmap(i); - n_blks++; - return (i); - } - return (0); + int i; + + for (i = 0; i < maxfsblock - 1; i++) { + if (testbmap(i)) + continue; + setbmap(i); + n_blks++; + return (i); + } + return (0); } /* @@ -340,11 +345,11 @@ allocblk(void) void freeblk(daddr_t blkno) { - struct inodesc idesc; + struct inodesc idesc; - idesc.id_blkno = blkno; - idesc.id_numfrags = 1; - (void)pass4check(&idesc); + idesc.id_blkno = blkno; + idesc.id_numfrags = 1; + (void)pass4check(&idesc); } /* @@ -353,55 +358,54 @@ freeblk(daddr_t blkno) void getpathname(char *namebuf, size_t namebuflen, ino_t curdir, ino_t ino) { - int len; - char *cp; - struct inodesc idesc; - static int busy = 0; - - if (curdir == ino && ino == EXT2_ROOTINO) { - (void)strlcpy(namebuf, "/", namebuflen); - return; - } - if (busy || - (statemap[curdir] != DSTATE && statemap[curdir] != DFOUND)) { - (void)strlcpy(namebuf, "?", namebuflen); - return; - } - busy = 1; - memset(&idesc, 0, sizeof(struct inodesc)); - idesc.id_type = DATA; - idesc.id_fix = IGNORE; - cp = &namebuf[MAXPATHLEN - 1]; - *cp = '\0'; - if (curdir != ino) { - idesc.id_parent = curdir; - goto namelookup; - } - while (ino != EXT2_ROOTINO) { - idesc.id_number = ino; - idesc.id_func = findino; - idesc.id_name = ".."; - if ((ckinode(ginode(ino), &idesc) & FOUND) == 0) - break; - namelookup: - idesc.id_number = idesc.id_parent; - idesc.id_parent = ino; - idesc.id_func = findname; - idesc.id_name = namebuf; - if ((ckinode(ginode(idesc.id_number), &idesc)&FOUND) == 0) - break; - len = strlen(namebuf); - cp -= len; - memcpy(cp, namebuf, (size_t)len); - *--cp = '/'; - if (cp < &namebuf[EXT2FS_MAXNAMLEN]) - break; - ino = idesc.id_number; - } - busy = 0; - if (ino != EXT2_ROOTINO) - *--cp = '?'; - memcpy(namebuf, cp, (size_t)(&namebuf[MAXPATHLEN] - cp)); + int len; + char *cp; + struct inodesc idesc; + static int busy = 0; + + if (curdir == ino && ino == EXT2_ROOTINO) { + (void)strlcpy(namebuf, "/", namebuflen); + return; + } + if (busy || (statemap[curdir] != DSTATE && statemap[curdir] != DFOUND)) { + (void)strlcpy(namebuf, "?", namebuflen); + return; + } + busy = 1; + memset(&idesc, 0, sizeof(struct inodesc)); + idesc.id_type = DATA; + idesc.id_fix = IGNORE; + cp = &namebuf[MAXPATHLEN - 1]; + *cp = '\0'; + if (curdir != ino) { + idesc.id_parent = curdir; + goto namelookup; + } + while (ino != EXT2_ROOTINO) { + idesc.id_number = ino; + idesc.id_func = findino; + idesc.id_name = ".."; + if ((ckinode(ginode(ino), &idesc) & FOUND) == 0) + break; + namelookup: + idesc.id_number = idesc.id_parent; + idesc.id_parent = ino; + idesc.id_func = findname; + idesc.id_name = namebuf; + if ((ckinode(ginode(idesc.id_number), &idesc) & FOUND) == 0) + break; + len = strlen(namebuf); + cp -= len; + memcpy(cp, namebuf, (size_t)len); + *--cp = '/'; + if (cp < &namebuf[EXT2FS_MAXNAMLEN]) + break; + ino = idesc.id_number; + } + busy = 0; + if (ino != EXT2_ROOTINO) + *--cp = '?'; + memcpy(namebuf, cp, (size_t)(&namebuf[MAXPATHLEN] - cp)); } /* @@ -410,35 +414,33 @@ getpathname(char *namebuf, size_t namebuflen, ino_t curdir, ino_t ino) int dofix(struct inodesc *idesc, const char *msg) { - - switch (idesc->id_fix) { - - case DONTKNOW: - if (idesc->id_type == DATA) - direrror(idesc->id_number, msg); - else - pwarn("%s", msg); - if (preen) { - printf(" (SALVAGED)\n"); - idesc->id_fix = FIX; - return (ALTERED); - } - if (reply("SALVAGE") == 0) { - idesc->id_fix = NOFIX; - return (0); - } - idesc->id_fix = FIX; - return (ALTERED); - - case FIX: - return (ALTERED); - - case NOFIX: - case IGNORE: - return (0); - - default: - errexit("UNKNOWN INODESC FIX MODE %d", idesc->id_fix); - } - /* NOTREACHED */ + switch (idesc->id_fix) { + case DONTKNOW: + if (idesc->id_type == DATA) + direrror(idesc->id_number, msg); + else + pwarn("%s", msg); + if (preen) { + printf(" (SALVAGED)\n"); + idesc->id_fix = FIX; + return (ALTERED); + } + if (reply("SALVAGE") == 0) { + idesc->id_fix = NOFIX; + return (0); + } + idesc->id_fix = FIX; + return (ALTERED); + + case FIX: + return (ALTERED); + + case NOFIX: + case IGNORE: + return (0); + + default: + errexit("UNKNOWN INODESC FIX MODE %d", idesc->id_fix); + } + /* NOTREACHED */ } diff --git a/cmd/extra/fsck.fat/boot.c b/cmd/extra/fsck.fat/boot.c @@ -25,7 +25,6 @@ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "freebsd-compat.h" #if defined(__RCSID) && !defined(lint) __RCSID("$NetBSD: boot.c,v 1.22 2020/01/11 16:29:07 christos Exp $"); @@ -45,323 +44,298 @@ __RCSID("$NetBSD: boot.c,v 1.22 2020/01/11 16:29:07 christos Exp $"); int readboot(int dosfs, struct bootblock *boot) { - u_char block[DOSBOOTBLOCKSIZE]; - u_char fsinfo[DOSBOOTBLOCKSIZE]; - int ret = FSOK; - - if ((size_t)read(dosfs, block, sizeof block) != sizeof block) { - perr("could not read boot block"); - return FSFATAL; - } - - if (block[510] != 0x55 || block[511] != 0xaa) { - pfatal("Invalid signature in boot block: %02x%02x", - block[511], block[510]); - return FSFATAL; - } - - memset(boot, 0, sizeof *boot); - boot->ValidFat = -1; - - /* Decode BIOS Parameter Block */ - - /* Bytes per sector: can only be 512, 1024, 2048 and 4096. */ - boot->bpbBytesPerSec = block[11] + (block[12] << 8); - if (boot->bpbBytesPerSec < DOSBOOTBLOCKSIZE_REAL || - boot->bpbBytesPerSec > DOSBOOTBLOCKSIZE || - !powerof2(boot->bpbBytesPerSec)) { - pfatal("Invalid sector size: %u", boot->bpbBytesPerSec); - return FSFATAL; - } - - /* Sectors per cluster: can only be: 1, 2, 4, 8, 16, 32, 64, 128. */ - boot->bpbSecPerClust = block[13]; - if (boot->bpbSecPerClust == 0 || !powerof2(boot->bpbSecPerClust)) { - pfatal("Invalid cluster size: %u", boot->bpbSecPerClust); - return FSFATAL; - } - - /* Reserved sectors: must be non-zero */ - boot->bpbResSectors = block[14] + (block[15] << 8); - if (boot->bpbResSectors < 1) { - pfatal("Invalid reserved sectors: %u", - boot->bpbResSectors); - return FSFATAL; - } - - /* Number of FATs */ - boot->bpbFATs = block[16]; - if (boot->bpbFATs == 0) { - pfatal("Invalid number of FATs: %u", boot->bpbFATs); - return FSFATAL; - } - - /* Root directory entries for FAT12 and FAT16 */ - boot->bpbRootDirEnts = block[17] + (block[18] << 8); - if (!boot->bpbRootDirEnts) { - /* bpbRootDirEnts = 0 suggests that we are FAT32 */ - boot->flags |= FAT32; - } - - /* Total sectors (16 bits) */ - boot->bpbSectors = block[19] + (block[20] << 8); - if (boot->bpbSectors != 0 && (boot->flags & FAT32)) { - pfatal("Invalid 16-bit total sector count on FAT32: %u", - boot->bpbSectors); - return FSFATAL; - } - - /* Media type: ignored */ - boot->bpbMedia = block[21]; - - /* FAT12/FAT16: 16-bit count of sectors per FAT */ - boot->bpbFATsmall = block[22] + (block[23] << 8); - if (boot->bpbFATsmall != 0 && (boot->flags & FAT32)) { - pfatal("Invalid 16-bit FAT sector count on FAT32: %u", - boot->bpbFATsmall); - return FSFATAL; - } - - /* Legacy CHS geometry numbers: ignored */ - boot->SecPerTrack = block[24] + (block[25] << 8); - boot->bpbHeads = block[26] + (block[27] << 8); - - /* Hidden sectors: ignored */ - boot->bpbHiddenSecs = block[28] + (block[29] << 8) + - (block[30] << 16) + (block[31] << 24); - - /* Total sectors (32 bits) */ - boot->bpbHugeSectors = block[32] + (block[33] << 8) + - (block[34] << 16) + (block[35] << 24); - if (boot->bpbHugeSectors == 0) { - if (boot->flags & FAT32) { - pfatal("FAT32 with sector count of zero"); - return FSFATAL; - } else if (boot->bpbSectors == 0) { - pfatal("FAT with sector count of zero"); - return FSFATAL; - } - boot->NumSectors = boot->bpbSectors; - } else { - if (boot->bpbSectors != 0) { - pfatal("Invalid FAT sector count"); - return FSFATAL; - } - boot->NumSectors = boot->bpbHugeSectors; - } - - if (boot->flags & FAT32) { - /* If the OEM Name field is EXFAT, it's not FAT32, so bail */ - if (!memcmp(&block[3], "EXFAT ", 8)) { - pfatal("exFAT filesystem is not supported."); - return FSFATAL; - } - - /* 32-bit count of sectors per FAT */ - boot->FATsecs = block[36] + (block[37] << 8) - + (block[38] << 16) + (block[39] << 24); - - if (block[40] & 0x80) - boot->ValidFat = block[40] & 0x0f; - - /* FAT32 version, bail out if not 0.0 */ - if (block[42] || block[43]) { - pfatal("Unknown file system version: %x.%x", - block[43], block[42]); - return FSFATAL; - } - - /* - * Cluster number of the first cluster of root directory. - * - * Should be 2 but do not require it. - */ - boot->bpbRootClust = block[44] + (block[45] << 8) - + (block[46] << 16) + (block[47] << 24); - - /* Sector number of the FSInfo structure, usually 1 */ - boot->bpbFSInfo = block[48] + (block[49] << 8); - - /* Sector number of the backup boot block, ignored */ - boot->bpbBackup = block[50] + (block[51] << 8); - - /* Check basic parameters */ - if (boot->bpbFSInfo == 0) { - /* - * Either the BIOS Parameter Block has been corrupted, - * or this is not a FAT32 filesystem, most likely an - * exFAT filesystem. - */ - pfatal("Invalid FAT32 Extended BIOS Parameter Block"); - return FSFATAL; - } - - /* FSInfo occupies one logical sector. */ - if (lseek(dosfs, boot->bpbFSInfo * boot->bpbBytesPerSec, - SEEK_SET) != boot->bpbFSInfo * boot->bpbBytesPerSec - || read(dosfs, fsinfo, boot->bpbBytesPerSec) != - boot->bpbBytesPerSec) { - perr("could not read fsinfo block"); - return FSFATAL; - } - if (memcmp(fsinfo, "RRaA", 4) - || memcmp(fsinfo + 0x1e4, "rrAa", 4) - || fsinfo[0x1fc] - || fsinfo[0x1fd] - || fsinfo[0x1fe] != 0x55 - || fsinfo[0x1ff] != 0xaa) { - pwarn("Invalid signature in fsinfo block\n"); - if (ask(0, "Fix")) { - memcpy(fsinfo, "RRaA", 4); - memcpy(fsinfo + 0x1e4, "rrAa", 4); - fsinfo[0x1fc] = fsinfo[0x1fd] = 0; - fsinfo[0x1fe] = 0x55; - fsinfo[0x1ff] = 0xaa; - if (lseek(dosfs, boot->bpbFSInfo * - boot->bpbBytesPerSec, SEEK_SET) - != boot->bpbFSInfo * boot->bpbBytesPerSec - || write(dosfs, fsinfo, boot->bpbBytesPerSec) - != boot->bpbBytesPerSec) { - perr("Unable to write bpbFSInfo"); - return FSFATAL; - } - ret = FSBOOTMOD; - } else - boot->bpbFSInfo = 0; - } else { - /* We appear to have a valid FSInfo block, decode */ - boot->FSFree = fsinfo[0x1e8] + (fsinfo[0x1e9] << 8) - + (fsinfo[0x1ea] << 16) - + (fsinfo[0x1eb] << 24); - boot->FSNext = fsinfo[0x1ec] + (fsinfo[0x1ed] << 8) - + (fsinfo[0x1ee] << 16) - + (fsinfo[0x1ef] << 24); - } - } else { - /* !FAT32: FAT12/FAT16 */ - boot->FATsecs = boot->bpbFATsmall; - } - - if (boot->FATsecs < 1 || boot->FATsecs > UINT32_MAX / boot->bpbFATs) { - pfatal("Invalid FATs(%u) with FATsecs(%zu)", - boot->bpbFATs, (size_t)boot->FATsecs); - return FSFATAL; - } - - boot->FirstCluster = (boot->bpbRootDirEnts * 32 + - boot->bpbBytesPerSec - 1) / boot->bpbBytesPerSec + - boot->bpbResSectors + boot->bpbFATs * boot->FATsecs; - - if (boot->FirstCluster + boot->bpbSecPerClust > boot->NumSectors) { - pfatal("Cluster offset too large (%u clusters)\n", - boot->FirstCluster); - return FSFATAL; - } - - /* - * The number of clusters is derived from available data sectors, - * divided by sectors per cluster. - */ - boot->NumClusters = - (boot->NumSectors - boot->FirstCluster) / boot->bpbSecPerClust; - - if (boot->flags & FAT32) { - if (boot->NumClusters > (CLUST_RSRVD & CLUST32_MASK)) { - pfatal("Filesystem too big (%u clusters) for FAT32 partition", - boot->NumClusters); - return FSFATAL; - } - if (boot->NumClusters < (CLUST_RSRVD & CLUST16_MASK)) { - pfatal("Filesystem too small (%u clusters) for FAT32 partition", - boot->NumClusters); - return FSFATAL; - } - boot->ClustMask = CLUST32_MASK; - - if (boot->bpbRootClust < CLUST_FIRST || - boot->bpbRootClust >= boot->NumClusters) { - pfatal("Root directory starts with cluster out of range(%u)", - boot->bpbRootClust); - return FSFATAL; - } - } else if (boot->NumClusters < (CLUST_RSRVD&CLUST12_MASK)) { - boot->ClustMask = CLUST12_MASK; - } else if (boot->NumClusters < (CLUST_RSRVD&CLUST16_MASK)) { - boot->ClustMask = CLUST16_MASK; - } else { - pfatal("Filesystem too big (%u clusters) for non-FAT32 partition", - boot->NumClusters); - return FSFATAL; - } - - switch (boot->ClustMask) { - case CLUST32_MASK: - boot->NumFatEntries = (boot->FATsecs * boot->bpbBytesPerSec) / 4; - break; - case CLUST16_MASK: - boot->NumFatEntries = (boot->FATsecs * boot->bpbBytesPerSec) / 2; - break; - default: - boot->NumFatEntries = (boot->FATsecs * boot->bpbBytesPerSec * 2) / 3; - break; - } - - if (boot->NumFatEntries < boot->NumClusters) { - pfatal("FAT size too small, %u entries won't fit into %u sectors\n", - boot->NumClusters, boot->FATsecs); - return FSFATAL; - } - - /* - * There are two reserved clusters. To avoid adding CLUST_FIRST every - * time we perform boundary checks, we increment the NumClusters by 2, - * which is CLUST_FIRST to denote the first out-of-range cluster number. - */ - boot->NumClusters += CLUST_FIRST; - - boot->ClusterSize = boot->bpbBytesPerSec * boot->bpbSecPerClust; - - boot->NumFiles = 1; - boot->NumFree = 0; - - return ret; + u_char block[DOSBOOTBLOCKSIZE]; + u_char fsinfo[DOSBOOTBLOCKSIZE]; + int ret = FSOK; + + if ((size_t)read(dosfs, block, sizeof block) != sizeof block) { + perr("could not read boot block"); + return FSFATAL; + } + + if (block[510] != 0x55 || block[511] != 0xaa) { + pfatal("Invalid signature in boot block: %02x%02x", block[511], block[510]); + return FSFATAL; + } + + memset(boot, 0, sizeof *boot); + boot->ValidFat = -1; + + /* Decode BIOS Parameter Block */ + + /* Bytes per sector: can only be 512, 1024, 2048 and 4096. */ + boot->bpbBytesPerSec = block[11] + (block[12] << 8); + if (boot->bpbBytesPerSec < DOSBOOTBLOCKSIZE_REAL || boot->bpbBytesPerSec > DOSBOOTBLOCKSIZE + || !powerof2(boot->bpbBytesPerSec)) { + pfatal("Invalid sector size: %u", boot->bpbBytesPerSec); + return FSFATAL; + } + + /* Sectors per cluster: can only be: 1, 2, 4, 8, 16, 32, 64, 128. */ + boot->bpbSecPerClust = block[13]; + if (boot->bpbSecPerClust == 0 || !powerof2(boot->bpbSecPerClust)) { + pfatal("Invalid cluster size: %u", boot->bpbSecPerClust); + return FSFATAL; + } + + /* Reserved sectors: must be non-zero */ + boot->bpbResSectors = block[14] + (block[15] << 8); + if (boot->bpbResSectors < 1) { + pfatal("Invalid reserved sectors: %u", boot->bpbResSectors); + return FSFATAL; + } + + /* Number of FATs */ + boot->bpbFATs = block[16]; + if (boot->bpbFATs == 0) { + pfatal("Invalid number of FATs: %u", boot->bpbFATs); + return FSFATAL; + } + + /* Root directory entries for FAT12 and FAT16 */ + boot->bpbRootDirEnts = block[17] + (block[18] << 8); + if (!boot->bpbRootDirEnts) { + /* bpbRootDirEnts = 0 suggests that we are FAT32 */ + boot->flags |= FAT32; + } + + /* Total sectors (16 bits) */ + boot->bpbSectors = block[19] + (block[20] << 8); + if (boot->bpbSectors != 0 && (boot->flags & FAT32)) { + pfatal("Invalid 16-bit total sector count on FAT32: %u", boot->bpbSectors); + return FSFATAL; + } + + /* Media type: ignored */ + boot->bpbMedia = block[21]; + + /* FAT12/FAT16: 16-bit count of sectors per FAT */ + boot->bpbFATsmall = block[22] + (block[23] << 8); + if (boot->bpbFATsmall != 0 && (boot->flags & FAT32)) { + pfatal("Invalid 16-bit FAT sector count on FAT32: %u", boot->bpbFATsmall); + return FSFATAL; + } + + /* Legacy CHS geometry numbers: ignored */ + boot->SecPerTrack = block[24] + (block[25] << 8); + boot->bpbHeads = block[26] + (block[27] << 8); + + /* Hidden sectors: ignored */ + boot->bpbHiddenSecs = block[28] + (block[29] << 8) + (block[30] << 16) + (block[31] << 24); + + /* Total sectors (32 bits) */ + boot->bpbHugeSectors = block[32] + (block[33] << 8) + (block[34] << 16) + (block[35] << 24); + if (boot->bpbHugeSectors == 0) { + if (boot->flags & FAT32) { + pfatal("FAT32 with sector count of zero"); + return FSFATAL; + } else if (boot->bpbSectors == 0) { + pfatal("FAT with sector count of zero"); + return FSFATAL; + } + boot->NumSectors = boot->bpbSectors; + } else { + if (boot->bpbSectors != 0) { + pfatal("Invalid FAT sector count"); + return FSFATAL; + } + boot->NumSectors = boot->bpbHugeSectors; + } + + if (boot->flags & FAT32) { + /* If the OEM Name field is EXFAT, it's not FAT32, so bail */ + if (!memcmp(&block[3], "EXFAT ", 8)) { + pfatal("exFAT filesystem is not supported."); + return FSFATAL; + } + + /* 32-bit count of sectors per FAT */ + boot->FATsecs = block[36] + (block[37] << 8) + (block[38] << 16) + (block[39] << 24); + + if (block[40] & 0x80) + boot->ValidFat = block[40] & 0x0f; + + /* FAT32 version, bail out if not 0.0 */ + if (block[42] || block[43]) { + pfatal("Unknown file system version: %x.%x", block[43], block[42]); + return FSFATAL; + } + + /* + * Cluster number of the first cluster of root directory. + * + * Should be 2 but do not require it. + */ + boot->bpbRootClust = block[44] + (block[45] << 8) + (block[46] << 16) + (block[47] << 24); + + /* Sector number of the FSInfo structure, usually 1 */ + boot->bpbFSInfo = block[48] + (block[49] << 8); + + /* Sector number of the backup boot block, ignored */ + boot->bpbBackup = block[50] + (block[51] << 8); + + /* Check basic parameters */ + if (boot->bpbFSInfo == 0) { + /* + * Either the BIOS Parameter Block has been corrupted, + * or this is not a FAT32 filesystem, most likely an + * exFAT filesystem. + */ + pfatal("Invalid FAT32 Extended BIOS Parameter Block"); + return FSFATAL; + } + + /* FSInfo occupies one logical sector. */ + if (lseek(dosfs, boot->bpbFSInfo * boot->bpbBytesPerSec, SEEK_SET) + != boot->bpbFSInfo * boot->bpbBytesPerSec + || read(dosfs, fsinfo, boot->bpbBytesPerSec) != boot->bpbBytesPerSec) { + perr("could not read fsinfo block"); + return FSFATAL; + } + if (memcmp(fsinfo, "RRaA", 4) || memcmp(fsinfo + 0x1e4, "rrAa", 4) || fsinfo[0x1fc] + || fsinfo[0x1fd] || fsinfo[0x1fe] != 0x55 || fsinfo[0x1ff] != 0xaa) { + pwarn("Invalid signature in fsinfo block\n"); + if (ask(0, "Fix")) { + memcpy(fsinfo, "RRaA", 4); + memcpy(fsinfo + 0x1e4, "rrAa", 4); + fsinfo[0x1fc] = fsinfo[0x1fd] = 0; + fsinfo[0x1fe] = 0x55; + fsinfo[0x1ff] = 0xaa; + if (lseek(dosfs, boot->bpbFSInfo * boot->bpbBytesPerSec, SEEK_SET) + != boot->bpbFSInfo * boot->bpbBytesPerSec + || write(dosfs, fsinfo, boot->bpbBytesPerSec) != boot->bpbBytesPerSec) { + perr("Unable to write bpbFSInfo"); + return FSFATAL; + } + ret = FSBOOTMOD; + } else + boot->bpbFSInfo = 0; + } else { + /* We appear to have a valid FSInfo block, decode */ + boot->FSFree = + fsinfo[0x1e8] + (fsinfo[0x1e9] << 8) + (fsinfo[0x1ea] << 16) + (fsinfo[0x1eb] << 24); + boot->FSNext = + fsinfo[0x1ec] + (fsinfo[0x1ed] << 8) + (fsinfo[0x1ee] << 16) + (fsinfo[0x1ef] << 24); + } + } else { + /* !FAT32: FAT12/FAT16 */ + boot->FATsecs = boot->bpbFATsmall; + } + + if (boot->FATsecs < 1 || boot->FATsecs > UINT32_MAX / boot->bpbFATs) { + pfatal("Invalid FATs(%u) with FATsecs(%zu)", boot->bpbFATs, (size_t)boot->FATsecs); + return FSFATAL; + } + + boot->FirstCluster = (boot->bpbRootDirEnts * 32 + boot->bpbBytesPerSec - 1) / boot->bpbBytesPerSec + + boot->bpbResSectors + boot->bpbFATs * boot->FATsecs; + + if (boot->FirstCluster + boot->bpbSecPerClust > boot->NumSectors) { + pfatal("Cluster offset too large (%u clusters)\n", boot->FirstCluster); + return FSFATAL; + } + + /* + * The number of clusters is derived from available data sectors, + * divided by sectors per cluster. + */ + boot->NumClusters = (boot->NumSectors - boot->FirstCluster) / boot->bpbSecPerClust; + + if (boot->flags & FAT32) { + if (boot->NumClusters > (CLUST_RSRVD & CLUST32_MASK)) { + pfatal("Filesystem too big (%u clusters) for FAT32 partition", boot->NumClusters); + return FSFATAL; + } + if (boot->NumClusters < (CLUST_RSRVD & CLUST16_MASK)) { + pfatal("Filesystem too small (%u clusters) for FAT32 partition", boot->NumClusters); + return FSFATAL; + } + boot->ClustMask = CLUST32_MASK; + + if (boot->bpbRootClust < CLUST_FIRST || boot->bpbRootClust >= boot->NumClusters) { + pfatal("Root directory starts with cluster out of range(%u)", boot->bpbRootClust); + return FSFATAL; + } + } else if (boot->NumClusters < (CLUST_RSRVD & CLUST12_MASK)) { + boot->ClustMask = CLUST12_MASK; + } else if (boot->NumClusters < (CLUST_RSRVD & CLUST16_MASK)) { + boot->ClustMask = CLUST16_MASK; + } else { + pfatal("Filesystem too big (%u clusters) for non-FAT32 partition", boot->NumClusters); + return FSFATAL; + } + + switch (boot->ClustMask) { + case CLUST32_MASK: + boot->NumFatEntries = (boot->FATsecs * boot->bpbBytesPerSec) / 4; + break; + case CLUST16_MASK: + boot->NumFatEntries = (boot->FATsecs * boot->bpbBytesPerSec) / 2; + break; + default: + boot->NumFatEntries = (boot->FATsecs * boot->bpbBytesPerSec * 2) / 3; + break; + } + + if (boot->NumFatEntries < boot->NumClusters) { + pfatal( + "FAT size too small, %u entries won't fit into %u sectors\n", + boot->NumClusters, + boot->FATsecs + ); + return FSFATAL; + } + + /* + * There are two reserved clusters. To avoid adding CLUST_FIRST every + * time we perform boundary checks, we increment the NumClusters by 2, + * which is CLUST_FIRST to denote the first out-of-range cluster number. + */ + boot->NumClusters += CLUST_FIRST; + + boot->ClusterSize = boot->bpbBytesPerSec * boot->bpbSecPerClust; + + boot->NumFiles = 1; + boot->NumFree = 0; + + return ret; } int writefsinfo(int dosfs, struct bootblock *boot) { - u_char fsinfo[DOSBOOTBLOCKSIZE]; - - if (lseek(dosfs, boot->bpbFSInfo * boot->bpbBytesPerSec, SEEK_SET) - != boot->bpbFSInfo * boot->bpbBytesPerSec - || read(dosfs, fsinfo, boot->bpbBytesPerSec) != boot->bpbBytesPerSec) { - perr("could not read fsinfo block"); - return FSFATAL; - } - fsinfo[0x1e8] = (u_char)boot->FSFree; - fsinfo[0x1e9] = (u_char)(boot->FSFree >> 8); - fsinfo[0x1ea] = (u_char)(boot->FSFree >> 16); - fsinfo[0x1eb] = (u_char)(boot->FSFree >> 24); - fsinfo[0x1ec] = (u_char)boot->FSNext; - fsinfo[0x1ed] = (u_char)(boot->FSNext >> 8); - fsinfo[0x1ee] = (u_char)(boot->FSNext >> 16); - fsinfo[0x1ef] = (u_char)(boot->FSNext >> 24); - if (lseek(dosfs, boot->bpbFSInfo * boot->bpbBytesPerSec, SEEK_SET) - != boot->bpbFSInfo * boot->bpbBytesPerSec - || write(dosfs, fsinfo, boot->bpbBytesPerSec) != boot->bpbBytesPerSec) { - perr("Unable to write bpbFSInfo"); - return FSFATAL; - } - /* - * Technically, we should return FSBOOTMOD here. - * - * However, since Win95 OSR2 (the first M$ OS that has - * support for FAT32) doesn't maintain the FSINFO block - * correctly, it has to be fixed pretty often. - * - * Therefore, we handle the FSINFO block only informally, - * fixing it if necessary, but otherwise ignoring the - * fact that it was incorrect. - */ - return 0; + u_char fsinfo[DOSBOOTBLOCKSIZE]; + + if (lseek(dosfs, boot->bpbFSInfo * boot->bpbBytesPerSec, SEEK_SET) + != boot->bpbFSInfo * boot->bpbBytesPerSec + || read(dosfs, fsinfo, boot->bpbBytesPerSec) != boot->bpbBytesPerSec) { + perr("could not read fsinfo block"); + return FSFATAL; + } + fsinfo[0x1e8] = (u_char)boot->FSFree; + fsinfo[0x1e9] = (u_char)(boot->FSFree >> 8); + fsinfo[0x1ea] = (u_char)(boot->FSFree >> 16); + fsinfo[0x1eb] = (u_char)(boot->FSFree >> 24); + fsinfo[0x1ec] = (u_char)boot->FSNext; + fsinfo[0x1ed] = (u_char)(boot->FSNext >> 8); + fsinfo[0x1ee] = (u_char)(boot->FSNext >> 16); + fsinfo[0x1ef] = (u_char)(boot->FSNext >> 24); + if (lseek(dosfs, boot->bpbFSInfo * boot->bpbBytesPerSec, SEEK_SET) + != boot->bpbFSInfo * boot->bpbBytesPerSec + || write(dosfs, fsinfo, boot->bpbBytesPerSec) != boot->bpbBytesPerSec) { + perr("Unable to write bpbFSInfo"); + return FSFATAL; + } + /* + * Technically, we should return FSBOOTMOD here. + * + * However, since Win95 OSR2 (the first M$ OS that has + * support for FAT32) doesn't maintain the FSINFO block + * correctly, it has to be fixed pretty often. + * + * Therefore, we handle the FSINFO block only informally, + * fixing it if necessary, but otherwise ignoring the + * fact that it was incorrect. + */ + return 0; } diff --git a/cmd/extra/fsck.fat/check.c b/cmd/extra/fsck.fat/check.c @@ -25,7 +25,6 @@ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "freebsd-compat.h" #if defined(__RCSID) && !defined(lint) __RCSID("$NetBSD: check.c,v 1.14 2006/06/05 16:51:18 christos Exp $"); @@ -47,157 +46,172 @@ __RCSID("$NetBSD: check.c,v 1.14 2006/06/05 16:51:18 christos Exp $"); int checkfilesys(const char *fname) { - int dosfs; - struct bootblock boot; - struct fat_descriptor *fat = NULL; - int finish_dosdirsection=0; - int flags = O_RDWR; - int mod = 0; - int ret = 8; - int64_t freebytes; - int64_t badbytes; - - rdonly = alwaysno; - if (!preen) - printf("** %s", fname); + int dosfs; + struct bootblock boot; + struct fat_descriptor *fat = NULL; + int finish_dosdirsection = 0; + int flags = O_RDWR; + int mod = 0; + int ret = 8; + int64_t freebytes; + int64_t badbytes; + + rdonly = alwaysno; + if (!preen) + printf("** %s", fname); #if defined(__linux__) && !defined(ARUU_FORCE_POSIX) - /* Claim the block device before repairing it. */ - flags |= O_EXCL; + /* Claim the block device before repairing it. */ + flags |= O_EXCL; #endif - dosfs = open(fname, rdonly ? O_RDONLY : flags); - if (dosfs < 0 && !rdonly && errno == EBUSY) { - if (!preen) - printf("\n"); - perr("`%s' is in use\n", fname); - return 8; - } - if (dosfs < 0 && !rdonly) { - dosfs = open(fname, O_RDONLY, 0); - if (dosfs >= 0) - pwarn(" (NO WRITE)\n"); - else if (!preen) - printf("\n"); - rdonly = 1; - } else if (!preen) - printf("\n"); - - if (dosfs < 0) { - perr("Can't open `%s'", fname); - printf("\n"); - return 8; - } - - if (readboot(dosfs, &boot) == FSFATAL) { - close(dosfs); - printf("\n"); - return 8; - } - - if (skipclean && preen && checkdirty(dosfs, &boot)) { - printf("%s: ", fname); - printf("FILESYSTEM CLEAN; SKIPPING CHECKS\n"); - ret = 0; - goto out; - } - - if (!preen) { - printf("** Phase 1 - Read FAT and checking connectivity\n"); - } - - mod |= readfat(dosfs, &boot, &fat); - if (mod & FSFATAL) { - close(dosfs); - return 8; - } - - if (!preen) - printf("** Phase 2 - Checking Directories\n"); - - mod |= resetDosDirSection(fat); - finish_dosdirsection = 1; - if (mod & FSFATAL) - goto out; - /* delay writing FATs */ - - mod |= handleDirTree(fat); - if (mod & FSFATAL) - goto out; - - if (!preen) - printf("** Phase 3 - Checking for Lost Files\n"); - - mod |= checklost(fat); - if (mod & FSFATAL) - goto out; - - /* now write the FATs */ - if (mod & FSFATMOD) { - if (ask(1, "Update FATs")) { - mod |= writefat(fat); - if (mod & FSFATAL) - goto out; - } else - mod |= FSERROR; - } - - freebytes = (int64_t)boot.NumFree * boot.ClusterSize; - badbytes = (int64_t)boot.NumBad * boot.ClusterSize; + dosfs = open(fname, rdonly ? O_RDONLY : flags); + if (dosfs < 0 && !rdonly && errno == EBUSY) { + if (!preen) + printf("\n"); + perr("`%s' is in use\n", fname); + return 8; + } + if (dosfs < 0 && !rdonly) { + dosfs = open(fname, O_RDONLY, 0); + if (dosfs >= 0) + pwarn(" (NO WRITE)\n"); + else if (!preen) + printf("\n"); + rdonly = 1; + } else if (!preen) + printf("\n"); + + if (dosfs < 0) { + perr("Can't open `%s'", fname); + printf("\n"); + return 8; + } + + if (readboot(dosfs, &boot) == FSFATAL) { + close(dosfs); + printf("\n"); + return 8; + } + + if (skipclean && preen && checkdirty(dosfs, &boot)) { + printf("%s: ", fname); + printf("FILESYSTEM CLEAN; SKIPPING CHECKS\n"); + ret = 0; + goto out; + } + + if (!preen) { + printf("** Phase 1 - Read FAT and checking connectivity\n"); + } + + mod |= readfat(dosfs, &boot, &fat); + if (mod & FSFATAL) { + close(dosfs); + return 8; + } + + if (!preen) + printf("** Phase 2 - Checking Directories\n"); + + mod |= resetDosDirSection(fat); + finish_dosdirsection = 1; + if (mod & FSFATAL) + goto out; + /* delay writing FATs */ + + mod |= handleDirTree(fat); + if (mod & FSFATAL) + goto out; + + if (!preen) + printf("** Phase 3 - Checking for Lost Files\n"); + + mod |= checklost(fat); + if (mod & FSFATAL) + goto out; + + /* now write the FATs */ + if (mod & FSFATMOD) { + if (ask(1, "Update FATs")) { + mod |= writefat(fat); + if (mod & FSFATAL) + goto out; + } else + mod |= FSERROR; + } + + freebytes = (int64_t)boot.NumFree * boot.ClusterSize; + badbytes = (int64_t)boot.NumBad * boot.ClusterSize; #ifdef HAVE_LIBUTIL_H - char freestr[7], badstr[7]; - - humanize_number(freestr, sizeof(freestr), freebytes, "", - HN_AUTOSCALE, HN_DECIMAL | HN_IEC_PREFIXES); - if (boot.NumBad) { - humanize_number(badstr, sizeof(badstr), badbytes, "", - HN_AUTOSCALE, HN_B | HN_DECIMAL | HN_IEC_PREFIXES); - - pwarn("%d files, %sB free (%d clusters), %sB bad (%d clusters)\n", - boot.NumFiles, freestr, boot.NumFree, - badstr, boot.NumBad); - } else { - pwarn("%d files, %sB free (%d clusters)\n", - boot.NumFiles, freestr, boot.NumFree); - } + char freestr[7], badstr[7]; + + humanize_number( + freestr, sizeof(freestr), freebytes, "", HN_AUTOSCALE, HN_DECIMAL | HN_IEC_PREFIXES + ); + if (boot.NumBad) { + humanize_number( + badstr, sizeof(badstr), badbytes, "", HN_AUTOSCALE, HN_B | HN_DECIMAL | HN_IEC_PREFIXES + ); + + pwarn( + "%d files, %sB free (%d clusters), %sB bad (%d clusters)\n", + boot.NumFiles, + freestr, + boot.NumFree, + badstr, + boot.NumBad + ); + } else { + pwarn("%d files, %sB free (%d clusters)\n", boot.NumFiles, freestr, boot.NumFree); + } #else - if (boot.NumBad) - pwarn("%d files, %jd KiB free (%d clusters), %jd KiB bad (%d clusters)\n", - boot.NumFiles, (intmax_t)freebytes / 1024, boot.NumFree, - (intmax_t)badbytes / 1024, boot.NumBad); - else - pwarn("%d files, %jd KiB free (%d clusters)\n", - boot.NumFiles, (intmax_t)freebytes / 1024, boot.NumFree); + if (boot.NumBad) + pwarn( + "%d files, %jd KiB free (%d clusters), %jd KiB bad (%d clusters)\n", + boot.NumFiles, + (intmax_t)freebytes / 1024, + boot.NumFree, + (intmax_t)badbytes / 1024, + boot.NumBad + ); + else + pwarn( + "%d files, %jd KiB free (%d clusters)\n", + boot.NumFiles, + (intmax_t)freebytes / 1024, + boot.NumFree + ); #endif - if (mod && (mod & FSERROR) == 0) { - if (mod & FSDIRTY) { - if (ask(1, "MARK FILE SYSTEM CLEAN") == 0) - mod &= ~FSDIRTY; + if (mod && (mod & FSERROR) == 0) { + if (mod & FSDIRTY) { + if (ask(1, "MARK FILE SYSTEM CLEAN") == 0) + mod &= ~FSDIRTY; - if (mod & FSDIRTY) { - pwarn("MARKING FILE SYSTEM CLEAN\n"); - mod |= cleardirty(fat); - } else { - pwarn("\n***** FILE SYSTEM IS LEFT MARKED AS DIRTY *****\n"); - mod |= FSERROR; /* file system not clean */ - } - } - } + if (mod & FSDIRTY) { + pwarn("MARKING FILE SYSTEM CLEAN\n"); + mod |= cleardirty(fat); + } else { + pwarn("\n***** FILE SYSTEM IS LEFT MARKED AS DIRTY *****\n"); + mod |= FSERROR; /* file system not clean */ + } + } + } - if (mod & (FSFATAL | FSERROR)) - goto out; + if (mod & (FSFATAL | FSERROR)) + goto out; - ret = 0; + ret = 0; - out: - if (finish_dosdirsection) - finishDosDirSection(); - free(fat); - close(dosfs); +out: + if (finish_dosdirsection) + finishDosDirSection(); + free(fat); + close(dosfs); - if (mod & (FSFATMOD|FSDIRMOD)) - pwarn("\n***** FILE SYSTEM WAS MODIFIED *****\n"); + if (mod & (FSFATMOD | FSDIRMOD)) + pwarn("\n***** FILE SYSTEM WAS MODIFIED *****\n"); - return ret; + return ret; } diff --git a/cmd/extra/fsck.fat/dir.c b/cmd/extra/fsck.fat/dir.c @@ -28,7 +28,6 @@ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "freebsd-compat.h" #if defined(__RCSID) && !defined(lint) __RCSID("$NetBSD: dir.c,v 1.20 2006/06/05 16:51:18 christos Exp $"); @@ -49,19 +48,19 @@ __RCSID("$NetBSD: dir.c,v 1.20 2006/06/05 16:51:18 christos Exp $"); #include "fsutil.h" #include "util.h" -#define SLOT_EMPTY 0x00 /* slot has never been used */ -#define SLOT_E5 0x05 /* the real value is 0xe5 */ -#define SLOT_DELETED 0xe5 /* file in this slot deleted */ +#define SLOT_EMPTY 0x00 /* slot has never been used */ +#define SLOT_E5 0x05 /* the real value is 0xe5 */ +#define SLOT_DELETED 0xe5 /* file in this slot deleted */ -#define ATTR_NORMAL 0x00 /* normal file */ -#define ATTR_READONLY 0x01 /* file is readonly */ -#define ATTR_HIDDEN 0x02 /* file is hidden */ -#define ATTR_SYSTEM 0x04 /* file is a system file */ -#define ATTR_VOLUME 0x08 /* entry is a volume label */ -#define ATTR_DIRECTORY 0x10 /* entry is a directory name */ -#define ATTR_ARCHIVE 0x20 /* file is new or modified */ +#define ATTR_NORMAL 0x00 /* normal file */ +#define ATTR_READONLY 0x01 /* file is readonly */ +#define ATTR_HIDDEN 0x02 /* file is hidden */ +#define ATTR_SYSTEM 0x04 /* file is a system file */ +#define ATTR_VOLUME 0x08 /* entry is a volume label */ +#define ATTR_DIRECTORY 0x10 /* entry is a directory name */ +#define ATTR_ARCHIVE 0x20 /* file is new or modified */ -#define ATTR_WIN95 0x0f /* long name record */ +#define ATTR_WIN95 0x0f /* long name record */ /* * This is the format of the contents of the deTime field in the direntry @@ -69,35 +68,33 @@ __RCSID("$NetBSD: dir.c,v 1.20 2006/06/05 16:51:18 christos Exp $"); * We don't use bitfields because we don't know how compilers for * arbitrary machines will lay them out. */ -#define DT_2SECONDS_MASK 0x1F /* seconds divided by 2 */ -#define DT_2SECONDS_SHIFT 0 -#define DT_MINUTES_MASK 0x7E0 /* minutes */ -#define DT_MINUTES_SHIFT 5 -#define DT_HOURS_MASK 0xF800 /* hours */ -#define DT_HOURS_SHIFT 11 +#define DT_2SECONDS_MASK 0x1F /* seconds divided by 2 */ +#define DT_2SECONDS_SHIFT 0 +#define DT_MINUTES_MASK 0x7E0 /* minutes */ +#define DT_MINUTES_SHIFT 5 +#define DT_HOURS_MASK 0xF800 /* hours */ +#define DT_HOURS_SHIFT 11 /* * This is the format of the contents of the deDate field in the direntry * structure. */ -#define DD_DAY_MASK 0x1F /* day of month */ -#define DD_DAY_SHIFT 0 -#define DD_MONTH_MASK 0x1E0 /* month */ -#define DD_MONTH_SHIFT 5 -#define DD_YEAR_MASK 0xFE00 /* year - 1980 */ -#define DD_YEAR_SHIFT 9 - +#define DD_DAY_MASK 0x1F /* day of month */ +#define DD_DAY_SHIFT 0 +#define DD_MONTH_MASK 0x1E0 /* month */ +#define DD_MONTH_SHIFT 5 +#define DD_YEAR_MASK 0xFE00 /* year - 1980 */ +#define DD_YEAR_SHIFT 9 /* dir.c */ static struct dosDirEntry *newDosDirEntry(void); -static void freeDosDirEntry(struct dosDirEntry *); +static void freeDosDirEntry(struct dosDirEntry *); static struct dirTodoNode *newDirTodo(void); -static void freeDirTodo(struct dirTodoNode *); -static char *fullpath(struct dosDirEntry *); -static u_char calcShortSum(u_char *); -static int delete(struct fat_descriptor *, cl_t, int, cl_t, int, int); -static int removede(struct fat_descriptor *, u_char *, u_char *, - cl_t, cl_t, cl_t, char *, int); +static void freeDirTodo(struct dirTodoNode *); +static char *fullpath(struct dosDirEntry *); +static u_char calcShortSum(u_char *); +static int delete (struct fat_descriptor *, cl_t, int, cl_t, int, int); +static int removede(struct fat_descriptor *, u_char *, u_char *, cl_t, cl_t, cl_t, char *, int); static int checksize(struct fat_descriptor *, u_char *, struct dosDirEntry *); static int readDosDirSection(struct fat_descriptor *, struct dosDirEntry *); @@ -109,21 +106,21 @@ static struct dosDirEntry *freede; static struct dosDirEntry * newDosDirEntry(void) { - struct dosDirEntry *de; - - if (!(de = freede)) { - if (!(de = malloc(sizeof *de))) - return (NULL); - } else - freede = de->next; - return de; + struct dosDirEntry *de; + + if (!(de = freede)) { + if (!(de = malloc(sizeof *de))) + return (NULL); + } else + freede = de->next; + return de; } static void freeDosDirEntry(struct dosDirEntry *de) { - de->next = freede; - freede = de; + de->next = freede; + freede = de; } /* @@ -134,21 +131,21 @@ static struct dirTodoNode *freedt; static struct dirTodoNode * newDirTodo(void) { - struct dirTodoNode *dt; - - if (!(dt = freedt)) { - if (!(dt = malloc(sizeof *dt))) - return 0; - } else - freedt = dt->next; - return dt; + struct dirTodoNode *dt; + + if (!(dt = freedt)) { + if (!(dt = malloc(sizeof *dt))) + return 0; + } else + freedt = dt->next; + return dt; } static void freeDirTodo(struct dirTodoNode *dt) { - dt->next = freedt; - freedt = dt; + dt->next = freedt; + freedt = dt; } /* @@ -162,29 +159,29 @@ static struct dirTodoNode *pendingDirectories = NULL; static char * fullpath(struct dosDirEntry *dir) { - static char namebuf[MAXPATHLEN + 1]; - char *cp, *np; - int nl; - - cp = namebuf + sizeof namebuf; - *--cp = '\0'; - - for(;;) { - np = dir->lname[0] ? dir->lname : dir->name; - nl = strlen(np); - if (cp <= namebuf + 1 + nl) { - *--cp = '?'; - break; - } - cp -= nl; - memcpy(cp, np, nl); - dir = dir->parent; - if (!dir) - break; - *--cp = '/'; - } - - return cp; + static char namebuf[MAXPATHLEN + 1]; + char *cp, *np; + int nl; + + cp = namebuf + sizeof namebuf; + *--cp = '\0'; + + for (;;) { + np = dir->lname[0] ? dir->lname : dir->name; + nl = strlen(np); + if (cp <= namebuf + 1 + nl) { + *--cp = '?'; + break; + } + cp -= nl; + memcpy(cp, np, nl); + dir = dir->parent; + if (!dir) + break; + *--cp = '/'; + } + + return cp; } /* @@ -193,23 +190,23 @@ fullpath(struct dosDirEntry *dir) static inline u_char calcShortSum(u_char *p) { - u_char sum = 0; - int i; + u_char sum = 0; + int i; - for (i = 0; i < 11; i++) { - sum = (sum << 7)|(sum >> 1); /* rotate right */ - sum += p[i]; - } + for (i = 0; i < 11; i++) { + sum = (sum << 7) | (sum >> 1); /* rotate right */ + sum += p[i]; + } - return sum; + return sum; } /* * Global variables temporarily used during a directory scan */ -static char longName[DOSLONGNAMELEN] = ""; -static u_char *buffer = NULL; -static u_char *delbuf = NULL; +static char longName[DOSLONGNAMELEN] = ""; +static u_char *buffer = NULL; +static u_char *delbuf = NULL; static struct dosDirEntry *rootDir; static struct dosDirEntry *lostDir; @@ -220,44 +217,44 @@ static struct dosDirEntry *lostDir; int resetDosDirSection(struct fat_descriptor *fat) { - int rootdir_size, cluster_size; - int ret = FSOK; - size_t len; - struct bootblock *boot; - - boot = fat_get_boot(fat); - - rootdir_size = boot->bpbRootDirEnts * 32; - cluster_size = boot->bpbSecPerClust * boot->bpbBytesPerSec; - - if ((buffer = malloc(len = MAX(rootdir_size, cluster_size))) == NULL) { - perr("No space for directory buffer (%zu)", len); - return FSFATAL; - } - - if ((delbuf = malloc(len = cluster_size)) == NULL) { - free(buffer); - perr("No space for directory delbuf (%zu)", len); - return FSFATAL; - } - - if ((rootDir = newDosDirEntry()) == NULL) { - free(buffer); - free(delbuf); - perr("No space for directory entry"); - return FSFATAL; - } - - memset(rootDir, 0, sizeof *rootDir); - if (boot->flags & FAT32) { - if (!fat_is_cl_head(fat, boot->bpbRootClust)) { - pfatal("Root directory doesn't start a cluster chain"); - return FSFATAL; - } - rootDir->head = boot->bpbRootClust; - } - - return ret; + int rootdir_size, cluster_size; + int ret = FSOK; + size_t len; + struct bootblock *boot; + + boot = fat_get_boot(fat); + + rootdir_size = boot->bpbRootDirEnts * 32; + cluster_size = boot->bpbSecPerClust * boot->bpbBytesPerSec; + + if ((buffer = malloc(len = MAX(rootdir_size, cluster_size))) == NULL) { + perr("No space for directory buffer (%zu)", len); + return FSFATAL; + } + + if ((delbuf = malloc(len = cluster_size)) == NULL) { + free(buffer); + perr("No space for directory delbuf (%zu)", len); + return FSFATAL; + } + + if ((rootDir = newDosDirEntry()) == NULL) { + free(buffer); + free(delbuf); + perr("No space for directory entry"); + return FSFATAL; + } + + memset(rootDir, 0, sizeof *rootDir); + if (boot->flags & FAT32) { + if (!fat_is_cl_head(fat, boot->bpbRootClust)) { + pfatal("Root directory doesn't start a cluster chain"); + return FSFATAL; + } + rootDir->head = boot->bpbRootClust; + } + + return ret; } /* @@ -266,118 +263,121 @@ resetDosDirSection(struct fat_descriptor *fat) void finishDosDirSection(void) { - struct dirTodoNode *p, *np; - struct dosDirEntry *d, *nd; - - for (p = pendingDirectories; p; p = np) { - np = p->next; - freeDirTodo(p); - } - pendingDirectories = NULL; - for (d = rootDir; d; d = nd) { - if ((nd = d->child) != NULL) { - d->child = 0; - continue; - } - if (!(nd = d->next)) - nd = d->parent; - freeDosDirEntry(d); - } - rootDir = lostDir = NULL; - free(buffer); - free(delbuf); - buffer = NULL; - delbuf = NULL; + struct dirTodoNode *p, *np; + struct dosDirEntry *d, *nd; + + for (p = pendingDirectories; p; p = np) { + np = p->next; + freeDirTodo(p); + } + pendingDirectories = NULL; + for (d = rootDir; d; d = nd) { + if ((nd = d->child) != NULL) { + d->child = 0; + continue; + } + if (!(nd = d->next)) + nd = d->parent; + freeDosDirEntry(d); + } + rootDir = lostDir = NULL; + free(buffer); + free(delbuf); + buffer = NULL; + delbuf = NULL; } /* * Delete directory entries between startcl, startoff and endcl, endoff. */ -static int -delete(struct fat_descriptor *fat, cl_t startcl, - int startoff, cl_t endcl, int endoff, int notlast) +static int delete ( + struct fat_descriptor *fat, cl_t startcl, int startoff, cl_t endcl, int endoff, int notlast +) { - u_char *s, *e; - off_t off; - int clsz, fd; - struct bootblock *boot; - - boot = fat_get_boot(fat); - fd = fat_get_fd(fat); - clsz = boot->bpbSecPerClust * boot->bpbBytesPerSec; - - s = delbuf + startoff; - e = delbuf + clsz; - while (fat_is_valid_cl(fat, startcl)) { - if (startcl == endcl) { - if (notlast) - break; - e = delbuf + endoff; - } - off = (startcl - CLUST_FIRST) * boot->bpbSecPerClust + boot->FirstCluster; - - off *= boot->bpbBytesPerSec; - if (lseek(fd, off, SEEK_SET) != off) { - perr("Unable to lseek to %" PRId64, off); - return FSFATAL; - } - if (read(fd, delbuf, clsz) != clsz) { - perr("Unable to read directory"); - return FSFATAL; - } - while (s < e) { - *s = SLOT_DELETED; - s += 32; - } - if (lseek(fd, off, SEEK_SET) != off) { - perr("Unable to lseek to %" PRId64, off); - return FSFATAL; - } - if (write(fd, delbuf, clsz) != clsz) { - perr("Unable to write directory"); - return FSFATAL; - } - if (startcl == endcl) - break; - startcl = fat_get_cl_next(fat, startcl); - s = delbuf; - } - return FSOK; + u_char *s, *e; + off_t off; + int clsz, fd; + struct bootblock *boot; + + boot = fat_get_boot(fat); + fd = fat_get_fd(fat); + clsz = boot->bpbSecPerClust * boot->bpbBytesPerSec; + + s = delbuf + startoff; + e = delbuf + clsz; + while (fat_is_valid_cl(fat, startcl)) { + if (startcl == endcl) { + if (notlast) + break; + e = delbuf + endoff; + } + off = (startcl - CLUST_FIRST) * boot->bpbSecPerClust + boot->FirstCluster; + + off *= boot->bpbBytesPerSec; + if (lseek(fd, off, SEEK_SET) != off) { + perr("Unable to lseek to %" PRId64, off); + return FSFATAL; + } + if (read(fd, delbuf, clsz) != clsz) { + perr("Unable to read directory"); + return FSFATAL; + } + while (s < e) { + *s = SLOT_DELETED; + s += 32; + } + if (lseek(fd, off, SEEK_SET) != off) { + perr("Unable to lseek to %" PRId64, off); + return FSFATAL; + } + if (write(fd, delbuf, clsz) != clsz) { + perr("Unable to write directory"); + return FSFATAL; + } + if (startcl == endcl) + break; + startcl = fat_get_cl_next(fat, startcl); + s = delbuf; + } + return FSOK; } static int -removede(struct fat_descriptor *fat, u_char *start, - u_char *end, cl_t startcl, cl_t endcl, cl_t curcl, - char *path, int type) +removede( + struct fat_descriptor *fat, + u_char *start, + u_char *end, + cl_t startcl, + cl_t endcl, + cl_t curcl, + char *path, + int type +) { - switch (type) { - case 0: - pwarn("Invalid long filename entry for %s\n", path); - break; - case 1: - pwarn("Invalid long filename entry at end of directory %s\n", - path); - break; - case 2: - pwarn("Invalid long filename entry for volume label\n"); - break; - } - if (ask(0, "Remove")) { - if (startcl != curcl) { - if (delete(fat, - startcl, start - buffer, - endcl, end - buffer, - endcl == curcl) == FSFATAL) - return FSFATAL; - start = buffer; - } - /* startcl is < CLUST_FIRST for !FAT32 root */ - if ((endcl == curcl) || (startcl < CLUST_FIRST)) - for (; start < end; start += 32) - *start = SLOT_DELETED; - return FSDIRMOD; - } - return FSERROR; + switch (type) { + case 0: + pwarn("Invalid long filename entry for %s\n", path); + break; + case 1: + pwarn("Invalid long filename entry at end of directory %s\n", path); + break; + case 2: + pwarn("Invalid long filename entry for volume label\n"); + break; + } + if (ask(0, "Remove")) { + if (startcl != curcl) { + if (delete (fat, startcl, start - buffer, endcl, end - buffer, endcl == curcl) == FSFATAL) + return FSFATAL; + start = buffer; + } + /* startcl is < CLUST_FIRST for !FAT32 root */ + if ((endcl == curcl) || (startcl < CLUST_FIRST)) + for (; start < end; start += 32) + *start = SLOT_DELETED; + return FSDIRMOD; + } + return FSERROR; } /* @@ -386,82 +386,88 @@ removede(struct fat_descriptor *fat, u_char *start, static int checksize(struct fat_descriptor *fat, u_char *p, struct dosDirEntry *dir) { - int ret = FSOK; - size_t chainsize; - u_int64_t physicalSize; - struct bootblock *boot; - - boot = fat_get_boot(fat); - - /* - * Check size on ordinary files - */ - if (dir->head == CLUST_FREE) { - physicalSize = 0; - } else { - if (!fat_is_valid_cl(fat, dir->head) || !fat_is_cl_head(fat, dir->head)) { - pwarn("Directory entry %s of size %u referencing invalid cluster %u\n", - fullpath(dir), dir->size, dir->head); - if (ask(1, "Truncate")) { - p[28] = p[29] = p[30] = p[31] = 0; - p[26] = p[27] = 0; - if (boot->ClustMask == CLUST32_MASK) - p[20] = p[21] = 0; - dir->size = 0; - dir->head = CLUST_FREE; - return FSDIRMOD; - } else { - return FSERROR; - } - } - ret = checkchain(fat, dir->head, &chainsize); - /* - * Upon return, chainsize would hold the chain length - * that checkchain() was able to validate, but if the user - * refused the proposed repair, it would be unsafe to - * proceed with directory entry fix, so bail out in that - * case. - */ - if (ret == FSERROR) { - return (FSERROR); - } - /* - * The maximum file size on FAT32 is 4GiB - 1, which - * will occupy a cluster chain of exactly 4GiB in - * size. On 32-bit platforms, since size_t is 32-bit, - * it would wrap back to 0. - */ - physicalSize = (u_int64_t)chainsize * boot->ClusterSize; - } - if (physicalSize < dir->size) { - pwarn("size of %s is %u, should at most be %ju\n", - fullpath(dir), dir->size, (uintmax_t)physicalSize); - if (ask(1, "Truncate")) { - dir->size = physicalSize; - p[28] = (u_char)physicalSize; - p[29] = (u_char)(physicalSize >> 8); - p[30] = (u_char)(physicalSize >> 16); - p[31] = (u_char)(physicalSize >> 24); - return FSDIRMOD; - } else - return FSERROR; - } else if (physicalSize - dir->size >= boot->ClusterSize) { - pwarn("%s has too many clusters allocated\n", - fullpath(dir)); - if (ask(1, "Drop superfluous clusters")) { - cl_t cl; - u_int32_t sz, len; - - for (cl = dir->head, len = sz = 0; - (sz += boot->ClusterSize) < dir->size; len++) - cl = fat_get_cl_next(fat, cl); - clearchain(fat, fat_get_cl_next(fat, cl)); - ret = fat_set_cl_next(fat, cl, CLUST_EOF); - return (FSFATMOD | ret); - } else - return FSERROR; - } - return FSOK; + int ret = FSOK; + size_t chainsize; + u_int64_t physicalSize; + struct bootblock *boot; + + boot = fat_get_boot(fat); + + /* + * Check size on ordinary files + */ + if (dir->head == CLUST_FREE) { + physicalSize = 0; + } else { + if (!fat_is_valid_cl(fat, dir->head) || !fat_is_cl_head(fat, dir->head)) { + pwarn( + "Directory entry %s of size %u referencing invalid cluster %u\n", + fullpath(dir), + dir->size, + dir->head + ); + if (ask(1, "Truncate")) { + p[28] = p[29] = p[30] = p[31] = 0; + p[26] = p[27] = 0; + if (boot->ClustMask == CLUST32_MASK) + p[20] = p[21] = 0; + dir->size = 0; + dir->head = CLUST_FREE; + return FSDIRMOD; + } else { + return FSERROR; + } + } + ret = checkchain(fat, dir->head, &chainsize); + /* + * Upon return, chainsize would hold the chain length + * that checkchain() was able to validate, but if the user + * refused the proposed repair, it would be unsafe to + * proceed with directory entry fix, so bail out in that + * case. + */ + if (ret == FSERROR) { + return (FSERROR); + } + /* + * The maximum file size on FAT32 is 4GiB - 1, which + * will occupy a cluster chain of exactly 4GiB in + * size. On 32-bit platforms, since size_t is 32-bit, + * it would wrap back to 0. + */ + physicalSize = (u_int64_t)chainsize * boot->ClusterSize; + } + if (physicalSize < dir->size) { + pwarn( + "size of %s is %u, should at most be %ju\n", + fullpath(dir), + dir->size, + (uintmax_t)physicalSize + ); + if (ask(1, "Truncate")) { + dir->size = physicalSize; + p[28] = (u_char)physicalSize; + p[29] = (u_char)(physicalSize >> 8); + p[30] = (u_char)(physicalSize >> 16); + p[31] = (u_char)(physicalSize >> 24); + return FSDIRMOD; + } else + return FSERROR; + } else if (physicalSize - dir->size >= boot->ClusterSize) { + pwarn("%s has too many clusters allocated\n", fullpath(dir)); + if (ask(1, "Drop superfluous clusters")) { + cl_t cl; + u_int32_t sz, len; + + for (cl = dir->head, len = sz = 0; (sz += boot->ClusterSize) < dir->size; len++) + cl = fat_get_cl_next(fat, cl); + clearchain(fat, fat_get_cl_next(fat, cl)); + ret = fat_set_cl_next(fat, cl, CLUST_EOF); + return (FSFATMOD | ret); + } else + return FSERROR; + } + return FSOK; } static const u_char dot_name[11] = ". "; @@ -475,67 +481,64 @@ static const u_char dotdot_name[11] = ".. "; static int check_subdirectory(struct fat_descriptor *fat, struct dosDirEntry *dir) { - u_char *buf, *cp; - off_t off; - cl_t cl; - int retval = FSOK; - int fd; - struct bootblock *boot; - - boot = fat_get_boot(fat); - fd = fat_get_fd(fat); - - cl = dir->head; - if (dir->parent && !fat_is_valid_cl(fat, cl)) { - return FSERROR; - } - - if (!(boot->flags & FAT32) && !dir->parent) { - off = boot->bpbResSectors + boot->bpbFATs * - boot->FATsecs; - } else { - off = (cl - CLUST_FIRST) * boot->bpbSecPerClust + boot->FirstCluster; - } - - /* - * We only need to check the first two entries of the directory, - * which is found in the first sector of the directory entry, - * so read in only the first sector. - */ - buf = malloc(boot->bpbBytesPerSec); - if (buf == NULL) { - perr("No space for directory buffer (%u)", - boot->bpbBytesPerSec); - return FSFATAL; - } - - off *= boot->bpbBytesPerSec; - if (lseek(fd, off, SEEK_SET) != off || - read(fd, buf, boot->bpbBytesPerSec) != (ssize_t)boot->bpbBytesPerSec) { - perr("Unable to read directory"); - free(buf); - return FSFATAL; - } - - /* - * Both `.' and `..' must be present and be the first two entries - * and be ATTR_DIRECTORY of a valid subdirectory. - */ - cp = buf; - if (memcmp(cp, dot_name, sizeof(dot_name)) != 0 || - (cp[11] & ATTR_DIRECTORY) != ATTR_DIRECTORY) { - pwarn("%s: Incorrect `.' for %s.\n", __func__, dir->name); - retval |= FSERROR; - } - cp += 32; - if (memcmp(cp, dotdot_name, sizeof(dotdot_name)) != 0 || - (cp[11] & ATTR_DIRECTORY) != ATTR_DIRECTORY) { - pwarn("%s: Incorrect `..' for %s. \n", __func__, dir->name); - retval |= FSERROR; - } - - free(buf); - return retval; + u_char *buf, *cp; + off_t off; + cl_t cl; + int retval = FSOK; + int fd; + struct bootblock *boot; + + boot = fat_get_boot(fat); + fd = fat_get_fd(fat); + + cl = dir->head; + if (dir->parent && !fat_is_valid_cl(fat, cl)) { + return FSERROR; + } + + if (!(boot->flags & FAT32) && !dir->parent) { + off = boot->bpbResSectors + boot->bpbFATs * boot->FATsecs; + } else { + off = (cl - CLUST_FIRST) * boot->bpbSecPerClust + boot->FirstCluster; + } + + /* + * We only need to check the first two entries of the directory, + * which is found in the first sector of the directory entry, + * so read in only the first sector. + */ + buf = malloc(boot->bpbBytesPerSec); + if (buf == NULL) { + perr("No space for directory buffer (%u)", boot->bpbBytesPerSec); + return FSFATAL; + } + + off *= boot->bpbBytesPerSec; + if (lseek(fd, off, SEEK_SET) != off + || read(fd, buf, boot->bpbBytesPerSec) != (ssize_t)boot->bpbBytesPerSec) { + perr("Unable to read directory"); + free(buf); + return FSFATAL; + } + + /* + * Both `.' and `..' must be present and be the first two entries + * and be ATTR_DIRECTORY of a valid subdirectory. + */ + cp = buf; + if (memcmp(cp, dot_name, sizeof(dot_name)) != 0 || (cp[11] & ATTR_DIRECTORY) != ATTR_DIRECTORY) { + pwarn("%s: Incorrect `.' for %s.\n", __func__, dir->name); + retval |= FSERROR; + } + cp += 32; + if (memcmp(cp, dotdot_name, sizeof(dotdot_name)) != 0 + || (cp[11] & ATTR_DIRECTORY) != ATTR_DIRECTORY) { + pwarn("%s: Incorrect `..' for %s. \n", __func__, dir->name); + retval |= FSERROR; + } + + free(buf); + return retval; } /* @@ -547,634 +550,605 @@ check_subdirectory(struct fat_descriptor *fat, struct dosDirEntry *dir) static int readDosDirSection(struct fat_descriptor *fat, struct dosDirEntry *dir) { - struct bootblock *boot; - struct dosDirEntry dirent, *d; - u_char *p, *vallfn, *invlfn, *empty; - off_t off; - int fd, i, j, k, iosize, entries; - bool is_legacyroot; - cl_t cl, valcl = ~0, invcl = ~0, empcl = ~0; - char *t; - u_int lidx = 0; - int shortSum; - int mod = FSOK; - size_t dirclusters; -#define THISMOD 0x8000 /* Only used within this routine */ - - boot = fat_get_boot(fat); - fd = fat_get_fd(fat); - - cl = dir->head; - if (dir->parent && (!fat_is_valid_cl(fat, cl))) { - /* - * Already handled somewhere else. - */ - return FSOK; - } - shortSum = -1; - vallfn = invlfn = empty = NULL; - - /* - * If we are checking the legacy root (for FAT12/FAT16), - * we will operate on the whole directory; otherwise, we - * will operate on one cluster at a time, and also take - * this opportunity to examine the chain. - * - * Derive how many entries we are going to encounter from - * the I/O size. - */ - is_legacyroot = (dir->parent == NULL && !(boot->flags & FAT32)); - if (is_legacyroot) { - iosize = boot->bpbRootDirEnts * 32; - entries = boot->bpbRootDirEnts; - } else { - iosize = boot->bpbSecPerClust * boot->bpbBytesPerSec; - entries = iosize / 32; - mod |= checkchain(fat, dir->head, &dirclusters); - } - - do { - if (is_legacyroot) { - /* - * Special case for FAT12/FAT16 root -- read - * in the whole root directory. - */ - off = boot->bpbResSectors + boot->bpbFATs * - boot->FATsecs; - } else { - /* - * Otherwise, read in a cluster of the - * directory. - */ - off = (cl - CLUST_FIRST) * boot->bpbSecPerClust + boot->FirstCluster; - } - - off *= boot->bpbBytesPerSec; - if (lseek(fd, off, SEEK_SET) != off || - read(fd, buffer, iosize) != iosize) { - perr("Unable to read directory"); - return FSFATAL; - } - - for (p = buffer, i = 0; i < entries; i++, p += 32) { - if (dir->fsckflags & DIREMPWARN) { - *p = SLOT_EMPTY; - continue; - } - - if (*p == SLOT_EMPTY || *p == SLOT_DELETED) { - if (*p == SLOT_EMPTY) { - dir->fsckflags |= DIREMPTY; - empty = p; - empcl = cl; - } - continue; - } - - if (dir->fsckflags & DIREMPTY) { - if (!(dir->fsckflags & DIREMPWARN)) { - pwarn("%s has entries after end of directory\n", - fullpath(dir)); - if (ask(1, "Extend")) { - u_char *q; - - dir->fsckflags &= ~DIREMPTY; - if (delete(fat, - empcl, empty - buffer, - cl, p - buffer, 1) == FSFATAL) - return FSFATAL; - q = ((empcl == cl) ? empty : buffer); - assert(q != NULL); - for (; q < p; q += 32) - *q = SLOT_DELETED; - mod |= THISMOD|FSDIRMOD; - } else if (ask(0, "Truncate")) - dir->fsckflags |= DIREMPWARN; - } - if (dir->fsckflags & DIREMPWARN) { - *p = SLOT_DELETED; - mod |= THISMOD|FSDIRMOD; - continue; - } else if (dir->fsckflags & DIREMPTY) - mod |= FSERROR; - empty = NULL; - } - - if (p[11] == ATTR_WIN95) { - if (*p & LRFIRST) { - if (shortSum != -1) { - if (!invlfn) { - invlfn = vallfn; - invcl = valcl; - } - } - memset(longName, 0, sizeof longName); - shortSum = p[13]; - vallfn = p; - valcl = cl; - } else if (shortSum != p[13] - || lidx != (*p & LRNOMASK)) { - if (!invlfn) { - invlfn = vallfn; - invcl = valcl; - } - if (!invlfn) { - invlfn = p; - invcl = cl; - } - vallfn = NULL; - } - lidx = *p & LRNOMASK; - if (lidx == 0) { - pwarn("invalid long name\n"); - if (!invlfn) { - invlfn = vallfn; - invcl = valcl; - } - vallfn = NULL; - continue; - } - t = longName + --lidx * 13; - for (k = 1; k < 11 && t < longName + - sizeof(longName); k += 2) { - if (!p[k] && !p[k + 1]) - break; - *t++ = p[k]; - /* - * Warn about those unusable chars in msdosfs here? XXX - */ - if (p[k + 1]) - t[-1] = '?'; - } - if (k >= 11) - for (k = 14; k < 26 && t < longName + sizeof(longName); k += 2) { - if (!p[k] && !p[k + 1]) - break; - *t++ = p[k]; - if (p[k + 1]) - t[-1] = '?'; - } - if (k >= 26) - for (k = 28; k < 32 && t < longName + sizeof(longName); k += 2) { - if (!p[k] && !p[k + 1]) - break; - *t++ = p[k]; - if (p[k + 1]) - t[-1] = '?'; - } - if (t >= longName + sizeof(longName)) { - pwarn("long filename too long\n"); - if (!invlfn) { - invlfn = vallfn; - invcl = valcl; - } - vallfn = NULL; - } - if (p[26] | (p[27] << 8)) { - pwarn("long filename record cluster start != 0\n"); - if (!invlfn) { - invlfn = vallfn; - invcl = cl; - } - vallfn = NULL; - } - continue; /* long records don't carry further - * information */ - } - - /* - * This is a standard msdosfs directory entry. - */ - memset(&dirent, 0, sizeof dirent); - - /* - * it's a short name record, but we need to know - * more, so get the flags first. - */ - dirent.flags = p[11]; - - /* - * Translate from 850 to ISO here XXX - */ - for (j = 0; j < 8; j++) - dirent.name[j] = p[j]; - dirent.name[8] = '\0'; - for (k = 7; k >= 0 && dirent.name[k] == ' '; k--) - dirent.name[k] = '\0'; - if (k < 0 || dirent.name[k] != '\0') - k++; - if (dirent.name[0] == SLOT_E5) - dirent.name[0] = 0xe5; - - if (dirent.flags & ATTR_VOLUME) { - if (vallfn || invlfn) { - mod |= removede(fat, - invlfn ? invlfn : vallfn, p, - invlfn ? invcl : valcl, -1, 0, - fullpath(dir), 2); - vallfn = NULL; - invlfn = NULL; - } - continue; - } - - if (p[8] != ' ') - dirent.name[k++] = '.'; - for (j = 0; j < 3; j++) - dirent.name[k++] = p[j+8]; - dirent.name[k] = '\0'; - for (k--; k >= 0 && dirent.name[k] == ' '; k--) - dirent.name[k] = '\0'; - - if (vallfn && shortSum != calcShortSum(p)) { - if (!invlfn) { - invlfn = vallfn; - invcl = valcl; - } - vallfn = NULL; - } - dirent.head = p[26] | (p[27] << 8); - if (boot->ClustMask == CLUST32_MASK) - dirent.head |= (p[20] << 16) | (p[21] << 24); - dirent.size = p[28] | (p[29] << 8) | (p[30] << 16) | (p[31] << 24); - if (vallfn) { - strlcpy(dirent.lname, longName, - sizeof(dirent.lname)); - longName[0] = '\0'; - shortSum = -1; - } - - dirent.parent = dir; - dirent.next = dir->child; - - if (invlfn) { - mod |= k = removede(fat, - invlfn, vallfn ? vallfn : p, - invcl, vallfn ? valcl : cl, cl, - fullpath(&dirent), 0); - if (mod & FSFATAL) - return FSFATAL; - if (vallfn - ? (valcl == cl && vallfn != buffer) - : p != buffer) - if (k & FSDIRMOD) - mod |= THISMOD; - } - - vallfn = NULL; /* not used any longer */ - invlfn = NULL; - - /* - * Check if the directory entry is sane. - * - * '.' and '..' are skipped, their sanity is - * checked somewhere else. - * - * For everything else, check if we have a new, - * valid cluster chain (beginning of a file or - * directory that was never previously claimed - * by another file) when it's a non-empty file - * or a directory. The sanity of the cluster - * chain is checked at a later time when we - * traverse into the directory, or examine the - * file's directory entry. - * - * The only possible fix is to delete the entry - * if it's a directory; for file, we have to - * truncate the size to 0. - */ - if (!(dirent.flags & ATTR_DIRECTORY) || - (strcmp(dirent.name, ".") != 0 && - strcmp(dirent.name, "..") != 0)) { - if ((dirent.size != 0 || (dirent.flags & ATTR_DIRECTORY)) && - ((!fat_is_valid_cl(fat, dirent.head) || - !fat_is_cl_head(fat, dirent.head)))) { - if (!fat_is_valid_cl(fat, dirent.head)) { - pwarn("%s starts with cluster out of range(%u)\n", - fullpath(&dirent), - dirent.head); - } else { - pwarn("%s doesn't start a new cluster chain\n", - fullpath(&dirent)); - } - - if (dirent.flags & ATTR_DIRECTORY) { - if (ask(0, "Remove")) { - *p = SLOT_DELETED; - mod |= THISMOD|FSDIRMOD; - } else - mod |= FSERROR; - continue; - } else { - if (ask(1, "Truncate")) { - p[28] = p[29] = p[30] = p[31] = 0; - p[26] = p[27] = 0; - if (boot->ClustMask == CLUST32_MASK) - p[20] = p[21] = 0; - dirent.size = 0; - dirent.head = 0; - mod |= THISMOD|FSDIRMOD; - } else - mod |= FSERROR; - } - } - } - if (dirent.flags & ATTR_DIRECTORY) { - /* - * gather more info for directories - */ - struct dirTodoNode *n; - - if (dirent.size) { - pwarn("Directory %s has size != 0\n", - fullpath(&dirent)); - if (ask(1, "Correct")) { - p[28] = p[29] = p[30] = p[31] = 0; - dirent.size = 0; - mod |= THISMOD|FSDIRMOD; - } else - mod |= FSERROR; - } - /* - * handle `.' and `..' specially - */ - if (strcmp(dirent.name, ".") == 0) { - if (dirent.head != dir->head) { - pwarn("`.' entry in %s has incorrect start cluster\n", - fullpath(dir)); - if (ask(1, "Correct")) { - dirent.head = dir->head; - p[26] = (u_char)dirent.head; - p[27] = (u_char)(dirent.head >> 8); - if (boot->ClustMask == CLUST32_MASK) { - p[20] = (u_char)(dirent.head >> 16); - p[21] = (u_char)(dirent.head >> 24); - } - mod |= THISMOD|FSDIRMOD; - } else - mod |= FSERROR; - } - continue; - } else if (strcmp(dirent.name, "..") == 0) { - if (dir->parent) { /* XXX */ - if (!dir->parent->parent) { - if (dirent.head) { - pwarn("`..' entry in %s has non-zero start cluster\n", - fullpath(dir)); - if (ask(1, "Correct")) { - dirent.head = 0; - p[26] = p[27] = 0; - if (boot->ClustMask == CLUST32_MASK) - p[20] = p[21] = 0; - mod |= THISMOD|FSDIRMOD; - } else - mod |= FSERROR; - } - } else if (dirent.head != dir->parent->head) { - pwarn("`..' entry in %s has incorrect start cluster\n", - fullpath(dir)); - if (ask(1, "Correct")) { - dirent.head = dir->parent->head; - p[26] = (u_char)dirent.head; - p[27] = (u_char)(dirent.head >> 8); - if (boot->ClustMask == CLUST32_MASK) { - p[20] = (u_char)(dirent.head >> 16); - p[21] = (u_char)(dirent.head >> 24); - } - mod |= THISMOD|FSDIRMOD; - } else - mod |= FSERROR; - } - } - continue; - } else { - /* - * Only one directory entry can point - * to dir->head, it's '.'. - */ - if (dirent.head == dir->head) { - pwarn("%s entry in %s has incorrect start cluster\n", - dirent.name, fullpath(dir)); - if (ask(1, "Remove")) { - *p = SLOT_DELETED; - mod |= THISMOD|FSDIRMOD; - } else - mod |= FSERROR; - continue; - } else if ((check_subdirectory(fat, - &dirent) & FSERROR) == FSERROR) { - /* - * A subdirectory should have - * a dot (.) entry and a dot-dot - * (..) entry of ATTR_DIRECTORY, - * we will inspect further when - * traversing into it. - */ - if (ask(1, "Remove")) { - *p = SLOT_DELETED; - mod |= THISMOD|FSDIRMOD; - } else - mod |= FSERROR; - continue; - } - } - - /* create directory tree node */ - if (!(d = newDosDirEntry())) { - perr("No space for directory"); - return FSFATAL; - } - memcpy(d, &dirent, sizeof(struct dosDirEntry)); - /* link it into the tree */ - dir->child = d; - - /* Enter this directory into the todo list */ - if (!(n = newDirTodo())) { - perr("No space for todo list"); - return FSFATAL; - } - n->next = pendingDirectories; - n->dir = d; - pendingDirectories = n; - } else if (!(mod & FSERROR)) { - mod |= k = checksize(fat, p, &dirent); - if (k & FSDIRMOD) - mod |= THISMOD; - } - boot->NumFiles++; - } - - if (is_legacyroot) { - /* - * Don't bother to write back right now because - * we may continue to make modification to the - * non-FAT32 root directory below. - */ - break; - } else if (mod & THISMOD) { - if (lseek(fd, off, SEEK_SET) != off - || write(fd, buffer, iosize) != iosize) { - perr("Unable to write directory"); - return FSFATAL; - } - mod &= ~THISMOD; - } - } while (fat_is_valid_cl(fat, (cl = fat_get_cl_next(fat, cl)))); - if (invlfn || vallfn) - mod |= removede(fat, - invlfn ? invlfn : vallfn, p, - invlfn ? invcl : valcl, -1, 0, - fullpath(dir), 1); - - /* - * The root directory of non-FAT32 filesystems is in a special - * area and may have been modified above removede() without - * being written out. - */ - if ((mod & FSDIRMOD) && is_legacyroot) { - if (lseek(fd, off, SEEK_SET) != off - || write(fd, buffer, iosize) != iosize) { - perr("Unable to write directory"); - return FSFATAL; - } - mod &= ~THISMOD; - } - return mod & ~THISMOD; + struct bootblock *boot; + struct dosDirEntry dirent, *d; + u_char *p, *vallfn, *invlfn, *empty; + off_t off; + int fd, i, j, k, iosize, entries; + bool is_legacyroot; + cl_t cl, valcl = ~0, invcl = ~0, empcl = ~0; + char *t; + u_int lidx = 0; + int shortSum; + int mod = FSOK; + size_t dirclusters; +#define THISMOD 0x8000 /* Only used within this routine */ + + boot = fat_get_boot(fat); + fd = fat_get_fd(fat); + + cl = dir->head; + if (dir->parent && (!fat_is_valid_cl(fat, cl))) { + /* + * Already handled somewhere else. + */ + return FSOK; + } + shortSum = -1; + vallfn = invlfn = empty = NULL; + + /* + * If we are checking the legacy root (for FAT12/FAT16), + * we will operate on the whole directory; otherwise, we + * will operate on one cluster at a time, and also take + * this opportunity to examine the chain. + * + * Derive how many entries we are going to encounter from + * the I/O size. + */ + is_legacyroot = (dir->parent == NULL && !(boot->flags & FAT32)); + if (is_legacyroot) { + iosize = boot->bpbRootDirEnts * 32; + entries = boot->bpbRootDirEnts; + } else { + iosize = boot->bpbSecPerClust * boot->bpbBytesPerSec; + entries = iosize / 32; + mod |= checkchain(fat, dir->head, &dirclusters); + } + + do { + if (is_legacyroot) { + /* + * Special case for FAT12/FAT16 root -- read + * in the whole root directory. + */ + off = boot->bpbResSectors + boot->bpbFATs * boot->FATsecs; + } else { + /* + * Otherwise, read in a cluster of the + * directory. + */ + off = (cl - CLUST_FIRST) * boot->bpbSecPerClust + boot->FirstCluster; + } + + off *= boot->bpbBytesPerSec; + if (lseek(fd, off, SEEK_SET) != off || read(fd, buffer, iosize) != iosize) { + perr("Unable to read directory"); + return FSFATAL; + } + + for (p = buffer, i = 0; i < entries; i++, p += 32) { + if (dir->fsckflags & DIREMPWARN) { + *p = SLOT_EMPTY; + continue; + } + + if (*p == SLOT_EMPTY || *p == SLOT_DELETED) { + if (*p == SLOT_EMPTY) { + dir->fsckflags |= DIREMPTY; + empty = p; + empcl = cl; + } + continue; + } + + if (dir->fsckflags & DIREMPTY) { + if (!(dir->fsckflags & DIREMPWARN)) { + pwarn("%s has entries after end of directory\n", fullpath(dir)); + if (ask(1, "Extend")) { + u_char *q; + + dir->fsckflags &= ~DIREMPTY; + if (delete (fat, empcl, empty - buffer, cl, p - buffer, 1) == FSFATAL) + return FSFATAL; + q = ((empcl == cl) ? empty : buffer); + assert(q != NULL); + for (; q < p; q += 32) + *q = SLOT_DELETED; + mod |= THISMOD | FSDIRMOD; + } else if (ask(0, "Truncate")) + dir->fsckflags |= DIREMPWARN; + } + if (dir->fsckflags & DIREMPWARN) { + *p = SLOT_DELETED; + mod |= THISMOD | FSDIRMOD; + continue; + } else if (dir->fsckflags & DIREMPTY) + mod |= FSERROR; + empty = NULL; + } + + if (p[11] == ATTR_WIN95) { + if (*p & LRFIRST) { + if (shortSum != -1) { + if (!invlfn) { + invlfn = vallfn; + invcl = valcl; + } + } + memset(longName, 0, sizeof longName); + shortSum = p[13]; + vallfn = p; + valcl = cl; + } else if (shortSum != p[13] || lidx != (*p & LRNOMASK)) { + if (!invlfn) { + invlfn = vallfn; + invcl = valcl; + } + if (!invlfn) { + invlfn = p; + invcl = cl; + } + vallfn = NULL; + } + lidx = *p & LRNOMASK; + if (lidx == 0) { + pwarn("invalid long name\n"); + if (!invlfn) { + invlfn = vallfn; + invcl = valcl; + } + vallfn = NULL; + continue; + } + t = longName + --lidx * 13; + for (k = 1; k < 11 && t < longName + sizeof(longName); k += 2) { + if (!p[k] && !p[k + 1]) + break; + *t++ = p[k]; + /* + * Warn about those unusable chars in msdosfs here? XXX + */ + if (p[k + 1]) + t[-1] = '?'; + } + if (k >= 11) + for (k = 14; k < 26 && t < longName + sizeof(longName); k += 2) { + if (!p[k] && !p[k + 1]) + break; + *t++ = p[k]; + if (p[k + 1]) + t[-1] = '?'; + } + if (k >= 26) + for (k = 28; k < 32 && t < longName + sizeof(longName); k += 2) { + if (!p[k] && !p[k + 1]) + break; + *t++ = p[k]; + if (p[k + 1]) + t[-1] = '?'; + } + if (t >= longName + sizeof(longName)) { + pwarn("long filename too long\n"); + if (!invlfn) { + invlfn = vallfn; + invcl = valcl; + } + vallfn = NULL; + } + if (p[26] | (p[27] << 8)) { + pwarn("long filename record cluster start != 0\n"); + if (!invlfn) { + invlfn = vallfn; + invcl = cl; + } + vallfn = NULL; + } + continue; /* long records don't carry further + * information */ + } + + /* + * This is a standard msdosfs directory entry. + */ + memset(&dirent, 0, sizeof dirent); + + /* + * it's a short name record, but we need to know + * more, so get the flags first. + */ + dirent.flags = p[11]; + + /* + * Translate from 850 to ISO here XXX + */ + for (j = 0; j < 8; j++) + dirent.name[j] = p[j]; + dirent.name[8] = '\0'; + for (k = 7; k >= 0 && dirent.name[k] == ' '; k--) + dirent.name[k] = '\0'; + if (k < 0 || dirent.name[k] != '\0') + k++; + if (dirent.name[0] == SLOT_E5) + dirent.name[0] = 0xe5; + + if (dirent.flags & ATTR_VOLUME) { + if (vallfn || invlfn) { + mod |= removede( + fat, invlfn ? invlfn : vallfn, p, invlfn ? invcl : valcl, -1, 0, fullpath(dir), 2 + ); + vallfn = NULL; + invlfn = NULL; + } + continue; + } + + if (p[8] != ' ') + dirent.name[k++] = '.'; + for (j = 0; j < 3; j++) + dirent.name[k++] = p[j + 8]; + dirent.name[k] = '\0'; + for (k--; k >= 0 && dirent.name[k] == ' '; k--) + dirent.name[k] = '\0'; + + if (vallfn && shortSum != calcShortSum(p)) { + if (!invlfn) { + invlfn = vallfn; + invcl = valcl; + } + vallfn = NULL; + } + dirent.head = p[26] | (p[27] << 8); + if (boot->ClustMask == CLUST32_MASK) + dirent.head |= (p[20] << 16) | (p[21] << 24); + dirent.size = p[28] | (p[29] << 8) | (p[30] << 16) | (p[31] << 24); + if (vallfn) { + strlcpy(dirent.lname, longName, sizeof(dirent.lname)); + longName[0] = '\0'; + shortSum = -1; + } + + dirent.parent = dir; + dirent.next = dir->child; + + if (invlfn) { + mod |= k = removede( + fat, invlfn, vallfn ? vallfn : p, invcl, vallfn ? valcl : cl, cl, fullpath(&dirent), 0 + ); + if (mod & FSFATAL) + return FSFATAL; + if (vallfn ? (valcl == cl && vallfn != buffer) : p != buffer) + if (k & FSDIRMOD) + mod |= THISMOD; + } + + vallfn = NULL; /* not used any longer */ + invlfn = NULL; + + /* + * Check if the directory entry is sane. + * + * '.' and '..' are skipped, their sanity is + * checked somewhere else. + * + * For everything else, check if we have a new, + * valid cluster chain (beginning of a file or + * directory that was never previously claimed + * by another file) when it's a non-empty file + * or a directory. The sanity of the cluster + * chain is checked at a later time when we + * traverse into the directory, or examine the + * file's directory entry. + * + * The only possible fix is to delete the entry + * if it's a directory; for file, we have to + * truncate the size to 0. + */ + if (!(dirent.flags & ATTR_DIRECTORY) + || (strcmp(dirent.name, ".") != 0 && strcmp(dirent.name, "..") != 0)) { + if ((dirent.size != 0 || (dirent.flags & ATTR_DIRECTORY)) + && ((!fat_is_valid_cl(fat, dirent.head) || !fat_is_cl_head(fat, dirent.head)))) { + if (!fat_is_valid_cl(fat, dirent.head)) { + pwarn("%s starts with cluster out of range(%u)\n", fullpath(&dirent), dirent.head); + } else { + pwarn("%s doesn't start a new cluster chain\n", fullpath(&dirent)); + } + + if (dirent.flags & ATTR_DIRECTORY) { + if (ask(0, "Remove")) { + *p = SLOT_DELETED; + mod |= THISMOD | FSDIRMOD; + } else + mod |= FSERROR; + continue; + } else { + if (ask(1, "Truncate")) { + p[28] = p[29] = p[30] = p[31] = 0; + p[26] = p[27] = 0; + if (boot->ClustMask == CLUST32_MASK) + p[20] = p[21] = 0; + dirent.size = 0; + dirent.head = 0; + mod |= THISMOD | FSDIRMOD; + } else + mod |= FSERROR; + } + } + } + if (dirent.flags & ATTR_DIRECTORY) { + /* + * gather more info for directories + */ + struct dirTodoNode *n; + + if (dirent.size) { + pwarn("Directory %s has size != 0\n", fullpath(&dirent)); + if (ask(1, "Correct")) { + p[28] = p[29] = p[30] = p[31] = 0; + dirent.size = 0; + mod |= THISMOD | FSDIRMOD; + } else + mod |= FSERROR; + } + /* + * handle `.' and `..' specially + */ + if (strcmp(dirent.name, ".") == 0) { + if (dirent.head != dir->head) { + pwarn("`.' entry in %s has incorrect start cluster\n", fullpath(dir)); + if (ask(1, "Correct")) { + dirent.head = dir->head; + p[26] = (u_char)dirent.head; + p[27] = (u_char)(dirent.head >> 8); + if (boot->ClustMask == CLUST32_MASK) { + p[20] = (u_char)(dirent.head >> 16); + p[21] = (u_char)(dirent.head >> 24); + } + mod |= THISMOD | FSDIRMOD; + } else + mod |= FSERROR; + } + continue; + } else if (strcmp(dirent.name, "..") == 0) { + if (dir->parent) { /* XXX */ + if (!dir->parent->parent) { + if (dirent.head) { + pwarn("`..' entry in %s has non-zero start cluster\n", fullpath(dir)); + if (ask(1, "Correct")) { + dirent.head = 0; + p[26] = p[27] = 0; + if (boot->ClustMask == CLUST32_MASK) + p[20] = p[21] = 0; + mod |= THISMOD | FSDIRMOD; + } else + mod |= FSERROR; + } + } else if (dirent.head != dir->parent->head) { + pwarn("`..' entry in %s has incorrect start cluster\n", fullpath(dir)); + if (ask(1, "Correct")) { + dirent.head = dir->parent->head; + p[26] = (u_char)dirent.head; + p[27] = (u_char)(dirent.head >> 8); + if (boot->ClustMask == CLUST32_MASK) { + p[20] = (u_char)(dirent.head >> 16); + p[21] = (u_char)(dirent.head >> 24); + } + mod |= THISMOD | FSDIRMOD; + } else + mod |= FSERROR; + } + } + continue; + } else { + /* + * Only one directory entry can point + * to dir->head, it's '.'. + */ + if (dirent.head == dir->head) { + pwarn("%s entry in %s has incorrect start cluster\n", dirent.name, fullpath(dir)); + if (ask(1, "Remove")) { + *p = SLOT_DELETED; + mod |= THISMOD | FSDIRMOD; + } else + mod |= FSERROR; + continue; + } else if ((check_subdirectory(fat, &dirent) & FSERROR) == FSERROR) { + /* + * A subdirectory should have + * a dot (.) entry and a dot-dot + * (..) entry of ATTR_DIRECTORY, + * we will inspect further when + * traversing into it. + */ + if (ask(1, "Remove")) { + *p = SLOT_DELETED; + mod |= THISMOD | FSDIRMOD; + } else + mod |= FSERROR; + continue; + } + } + + /* create directory tree node */ + if (!(d = newDosDirEntry())) { + perr("No space for directory"); + return FSFATAL; + } + memcpy(d, &dirent, sizeof(struct dosDirEntry)); + /* link it into the tree */ + dir->child = d; + + /* Enter this directory into the todo list */ + if (!(n = newDirTodo())) { + perr("No space for todo list"); + return FSFATAL; + } + n->next = pendingDirectories; + n->dir = d; + pendingDirectories = n; + } else if (!(mod & FSERROR)) { + mod |= k = checksize(fat, p, &dirent); + if (k & FSDIRMOD) + mod |= THISMOD; + } + boot->NumFiles++; + } + + if (is_legacyroot) { + /* + * Don't bother to write back right now because + * we may continue to make modification to the + * non-FAT32 root directory below. + */ + break; + } else if (mod & THISMOD) { + if (lseek(fd, off, SEEK_SET) != off || write(fd, buffer, iosize) != iosize) { + perr("Unable to write directory"); + return FSFATAL; + } + mod &= ~THISMOD; + } + } while (fat_is_valid_cl(fat, (cl = fat_get_cl_next(fat, cl)))); + if (invlfn || vallfn) + mod |= + removede(fat, invlfn ? invlfn : vallfn, p, invlfn ? invcl : valcl, -1, 0, fullpath(dir), 1); + + /* + * The root directory of non-FAT32 filesystems is in a special + * area and may have been modified above removede() without + * being written out. + */ + if ((mod & FSDIRMOD) && is_legacyroot) { + if (lseek(fd, off, SEEK_SET) != off || write(fd, buffer, iosize) != iosize) { + perr("Unable to write directory"); + return FSFATAL; + } + mod &= ~THISMOD; + } + return mod & ~THISMOD; } int handleDirTree(struct fat_descriptor *fat) { - int mod; - - mod = readDosDirSection(fat, rootDir); - if (mod & FSFATAL) - return FSFATAL; - - /* - * process the directory todo list - */ - while (pendingDirectories) { - struct dosDirEntry *dir = pendingDirectories->dir; - struct dirTodoNode *n = pendingDirectories->next; - - /* - * remove TODO entry now, the list might change during - * directory reads - */ - freeDirTodo(pendingDirectories); - pendingDirectories = n; - - /* - * handle subdirectory - */ - mod |= readDosDirSection(fat, dir); - if (mod & FSFATAL) - return FSFATAL; - } - - return mod; + int mod; + + mod = readDosDirSection(fat, rootDir); + if (mod & FSFATAL) + return FSFATAL; + + /* + * process the directory todo list + */ + while (pendingDirectories) { + struct dosDirEntry *dir = pendingDirectories->dir; + struct dirTodoNode *n = pendingDirectories->next; + + /* + * remove TODO entry now, the list might change during + * directory reads + */ + freeDirTodo(pendingDirectories); + pendingDirectories = n; + + /* + * handle subdirectory + */ + mod |= readDosDirSection(fat, dir); + if (mod & FSFATAL) + return FSFATAL; + } + + return mod; } /* * Try to reconnect a FAT chain into dir */ static u_char *lfbuf; -static cl_t lfcl; -static off_t lfoff; +static cl_t lfcl; +static off_t lfoff; int reconnect(struct fat_descriptor *fat, cl_t head, size_t length) { - struct bootblock *boot = fat_get_boot(fat); - struct dosDirEntry d; - int len, dosfs; - u_char *p; - - dosfs = fat_get_fd(fat); - - if (!ask(1, "Reconnect")) - return FSERROR; - - if (!lostDir) { - for (lostDir = rootDir->child; lostDir; lostDir = lostDir->next) { - if (!strcmp(lostDir->name, LOSTDIR)) - break; - } - if (!lostDir) { /* Create LOSTDIR? XXX */ - pwarn("No %s directory\n", LOSTDIR); - return FSERROR; - } - } - if (!lfbuf) { - lfbuf = malloc(boot->ClusterSize); - if (!lfbuf) { - perr("No space for buffer"); - return FSFATAL; - } - p = NULL; - } else - p = lfbuf; - while (1) { - if (p) - for (; p < lfbuf + boot->ClusterSize; p += 32) - if (*p == SLOT_EMPTY - || *p == SLOT_DELETED) - break; - if (p && p < lfbuf + boot->ClusterSize) - break; - lfcl = p ? fat_get_cl_next(fat, lfcl) : lostDir->head; - if (lfcl < CLUST_FIRST || lfcl >= boot->NumClusters) { - /* Extend LOSTDIR? XXX */ - pwarn("No space in %s\n", LOSTDIR); - lfcl = (lostDir->head < boot->NumClusters) ? lostDir->head : 0; - return FSERROR; - } - lfoff = (lfcl - CLUST_FIRST) * boot->ClusterSize - + boot->FirstCluster * boot->bpbBytesPerSec; - - if (lseek(dosfs, lfoff, SEEK_SET) != lfoff - || (size_t)read(dosfs, lfbuf, boot->ClusterSize) != boot->ClusterSize) { - perr("could not read LOST.DIR"); - return FSFATAL; - } - p = lfbuf; - } - - boot->NumFiles++; - /* Ensure uniqueness of entry here! XXX */ - memset(&d, 0, sizeof d); - /* worst case -1 = 4294967295, 10 digits */ - len = snprintf(d.name, sizeof(d.name), "%u", head); - d.flags = 0; - d.head = head; - d.size = length * boot->ClusterSize; - - memcpy(p, d.name, len); - memset(p + len, ' ', 11 - len); - memset(p + 11, 0, 32 - 11); - p[26] = (u_char)d.head; - p[27] = (u_char)(d.head >> 8); - if (boot->ClustMask == CLUST32_MASK) { - p[20] = (u_char)(d.head >> 16); - p[21] = (u_char)(d.head >> 24); - } - p[28] = (u_char)d.size; - p[29] = (u_char)(d.size >> 8); - p[30] = (u_char)(d.size >> 16); - p[31] = (u_char)(d.size >> 24); - if (lseek(dosfs, lfoff, SEEK_SET) != lfoff - || (size_t)write(dosfs, lfbuf, boot->ClusterSize) != boot->ClusterSize) { - perr("could not write LOST.DIR"); - return FSFATAL; - } - return FSDIRMOD; + struct bootblock *boot = fat_get_boot(fat); + struct dosDirEntry d; + int len, dosfs; + u_char *p; + + dosfs = fat_get_fd(fat); + + if (!ask(1, "Reconnect")) + return FSERROR; + + if (!lostDir) { + for (lostDir = rootDir->child; lostDir; lostDir = lostDir->next) { + if (!strcmp(lostDir->name, LOSTDIR)) + break; + } + if (!lostDir) { /* Create LOSTDIR? XXX */ + pwarn("No %s directory\n", LOSTDIR); + return FSERROR; + } + } + if (!lfbuf) { + lfbuf = malloc(boot->ClusterSize); + if (!lfbuf) { + perr("No space for buffer"); + return FSFATAL; + } + p = NULL; + } else + p = lfbuf; + while (1) { + if (p) + for (; p < lfbuf + boot->ClusterSize; p += 32) + if (*p == SLOT_EMPTY || *p == SLOT_DELETED) + break; + if (p && p < lfbuf + boot->ClusterSize) + break; + lfcl = p ? fat_get_cl_next(fat, lfcl) : lostDir->head; + if (lfcl < CLUST_FIRST || lfcl >= boot->NumClusters) { + /* Extend LOSTDIR? XXX */ + pwarn("No space in %s\n", LOSTDIR); + lfcl = (lostDir->head < boot->NumClusters) ? lostDir->head : 0; + return FSERROR; + } + lfoff = (lfcl - CLUST_FIRST) * boot->ClusterSize + boot->FirstCluster * boot->bpbBytesPerSec; + + if (lseek(dosfs, lfoff, SEEK_SET) != lfoff + || (size_t)read(dosfs, lfbuf, boot->ClusterSize) != boot->ClusterSize) { + perr("could not read LOST.DIR"); + return FSFATAL; + } + p = lfbuf; + } + + boot->NumFiles++; + /* Ensure uniqueness of entry here! XXX */ + memset(&d, 0, sizeof d); + /* worst case -1 = 4294967295, 10 digits */ + len = snprintf(d.name, sizeof(d.name), "%u", head); + d.flags = 0; + d.head = head; + d.size = length * boot->ClusterSize; + + memcpy(p, d.name, len); + memset(p + len, ' ', 11 - len); + memset(p + 11, 0, 32 - 11); + p[26] = (u_char)d.head; + p[27] = (u_char)(d.head >> 8); + if (boot->ClustMask == CLUST32_MASK) { + p[20] = (u_char)(d.head >> 16); + p[21] = (u_char)(d.head >> 24); + } + p[28] = (u_char)d.size; + p[29] = (u_char)(d.size >> 8); + p[30] = (u_char)(d.size >> 16); + p[31] = (u_char)(d.size >> 24); + if (lseek(dosfs, lfoff, SEEK_SET) != lfoff + || (size_t)write(dosfs, lfbuf, boot->ClusterSize) != boot->ClusterSize) { + perr("could not write LOST.DIR"); + return FSFATAL; + } + return FSDIRMOD; } void finishlf(void) { - if (lfbuf) - free(lfbuf); - lfbuf = NULL; + if (lfbuf) + free(lfbuf); + lfbuf = NULL; } diff --git a/cmd/extra/fsck.fat/dosfs.h b/cmd/extra/fsck.fat/dosfs.h @@ -33,100 +33,100 @@ /* support 4Kn disk reads */ #define DOSBOOTBLOCKSIZE_REAL 512 -#define DOSBOOTBLOCKSIZE 4096 +#define DOSBOOTBLOCKSIZE 4096 -typedef u_int32_t cl_t; /* type holding a cluster number */ +typedef u_int32_t cl_t; /* type holding a cluster number */ /* * architecture independent description of all the info stored in a * FAT boot block. */ struct bootblock { - u_int bpbBytesPerSec; /* bytes per sector */ - u_int bpbSecPerClust; /* sectors per cluster */ - u_int bpbResSectors; /* number of reserved sectors */ - u_int bpbFATs; /* number of bpbFATs */ - u_int bpbRootDirEnts; /* number of root directory entries */ - u_int32_t bpbSectors; /* total number of sectors */ - u_int bpbMedia; /* media descriptor */ - u_int bpbFATsmall; /* number of sectors per FAT */ - u_int SecPerTrack; /* sectors per track */ - u_int bpbHeads; /* number of heads */ - u_int32_t bpbHiddenSecs; /* # of hidden sectors */ - u_int32_t bpbHugeSectors; /* # of sectors if bpbbpbSectors == 0 */ - cl_t bpbRootClust; /* Start of Root Directory */ - u_int bpbFSInfo; /* FSInfo sector */ - u_int bpbBackup; /* Backup of Bootblocks */ - cl_t FSFree; /* Number of free clusters acc. FSInfo */ - cl_t FSNext; /* Next free cluster acc. FSInfo */ + u_int bpbBytesPerSec; /* bytes per sector */ + u_int bpbSecPerClust; /* sectors per cluster */ + u_int bpbResSectors; /* number of reserved sectors */ + u_int bpbFATs; /* number of bpbFATs */ + u_int bpbRootDirEnts; /* number of root directory entries */ + u_int32_t bpbSectors; /* total number of sectors */ + u_int bpbMedia; /* media descriptor */ + u_int bpbFATsmall; /* number of sectors per FAT */ + u_int SecPerTrack; /* sectors per track */ + u_int bpbHeads; /* number of heads */ + u_int32_t bpbHiddenSecs; /* # of hidden sectors */ + u_int32_t bpbHugeSectors; /* # of sectors if bpbbpbSectors == 0 */ + cl_t bpbRootClust; /* Start of Root Directory */ + u_int bpbFSInfo; /* FSInfo sector */ + u_int bpbBackup; /* Backup of Bootblocks */ + cl_t FSFree; /* Number of free clusters acc. FSInfo */ + cl_t FSNext; /* Next free cluster acc. FSInfo */ - /* and some more calculated values */ - u_int flags; /* some flags: */ -#define FAT32 1 /* this is a FAT32 file system */ - /* - * Maybe, we should separate out - * various parts of FAT32? XXX - */ - int ValidFat; /* valid fat if FAT32 non-mirrored */ - cl_t ClustMask; /* mask for entries in FAT */ - cl_t NumClusters; /* # of entries in a FAT */ - u_int32_t NumSectors; /* how many sectors are there */ - u_int32_t FATsecs; /* how many sectors are in FAT */ - u_int32_t NumFatEntries; /* how many entries really are there */ - u_int FirstCluster; /* at what sector is Cluster CLUST_FIRST */ - u_int ClusterSize; /* Cluster size in bytes */ + /* and some more calculated values */ + u_int flags; /* some flags: */ +#define FAT32 1 /* this is a FAT32 file system */ + /* + * Maybe, we should separate out + * various parts of FAT32? XXX + */ + int ValidFat; /* valid fat if FAT32 non-mirrored */ + cl_t ClustMask; /* mask for entries in FAT */ + cl_t NumClusters; /* # of entries in a FAT */ + u_int32_t NumSectors; /* how many sectors are there */ + u_int32_t FATsecs; /* how many sectors are in FAT */ + u_int32_t NumFatEntries; /* how many entries really are there */ + u_int FirstCluster; /* at what sector is Cluster CLUST_FIRST */ + u_int ClusterSize; /* Cluster size in bytes */ - /* Now some statistics: */ - u_int NumFiles; /* # of plain files */ - u_int NumFree; /* # of free clusters */ - u_int NumBad; /* # of bad clusters */ + /* Now some statistics: */ + u_int NumFiles; /* # of plain files */ + u_int NumFree; /* # of free clusters */ + u_int NumBad; /* # of bad clusters */ }; -#define CLUST_FREE 0 /* 0 means cluster is free */ -#define CLUST_FIRST 2 /* 2 is the minimum valid cluster number */ -#define CLUST_RSRVD 0xfffffff6 /* start of reserved clusters */ -#define CLUST_BAD 0xfffffff7 /* a cluster with a defect */ -#define CLUST_EOFS 0xfffffff8 /* start of EOF indicators */ -#define CLUST_EOF 0xffffffff /* standard value for last cluster */ -#define CLUST_DEAD 0xfdeadc0d /* error encountered */ +#define CLUST_FREE 0 /* 0 means cluster is free */ +#define CLUST_FIRST 2 /* 2 is the minimum valid cluster number */ +#define CLUST_RSRVD 0xfffffff6 /* start of reserved clusters */ +#define CLUST_BAD 0xfffffff7 /* a cluster with a defect */ +#define CLUST_EOFS 0xfffffff8 /* start of EOF indicators */ +#define CLUST_EOF 0xffffffff /* standard value for last cluster */ +#define CLUST_DEAD 0xfdeadc0d /* error encountered */ /* * Masks for cluster values */ -#define CLUST12_MASK 0xfff -#define CLUST16_MASK 0xffff -#define CLUST32_MASK 0xfffffff +#define CLUST12_MASK 0xfff +#define CLUST16_MASK 0xffff +#define CLUST32_MASK 0xfffffff -#define DOSLONGNAMELEN 256 /* long name maximal length */ -#define LRFIRST 0x40 /* first long name record */ -#define LRNOMASK 0x1f /* mask to extract long record - * sequence number */ +#define DOSLONGNAMELEN 256 /* long name maximal length */ +#define LRFIRST 0x40 /* first long name record */ +#define LRNOMASK \ + 0x1f /* mask to extract long record \ + * sequence number */ /* * Architecture independent description of a directory entry */ struct dosDirEntry { - struct dosDirEntry - *parent, /* previous tree level */ - *next, /* next brother */ - *child; /* if this is a directory */ - char name[8+1+3+1]; /* alias name first part */ - char lname[DOSLONGNAMELEN]; /* real name */ - uint flags; /* attributes */ - cl_t head; /* cluster no */ - u_int32_t size; /* filesize in bytes */ - uint fsckflags; /* flags during fsck */ + struct dosDirEntry *parent, /* previous tree level */ + *next, /* next brother */ + *child; /* if this is a directory */ + char name[8 + 1 + 3 + 1]; /* alias name first part */ + char lname[DOSLONGNAMELEN]; /* real name */ + uint flags; /* attributes */ + cl_t head; /* cluster no */ + u_int32_t size; /* filesize in bytes */ + uint fsckflags; /* flags during fsck */ }; /* Flags in fsckflags: */ -#define DIREMPTY 1 -#define DIREMPWARN 2 +#define DIREMPTY 1 +#define DIREMPWARN 2 /* * TODO-list of unread directories */ struct dirTodoNode { - struct dosDirEntry *dir; - struct dirTodoNode *next; + struct dosDirEntry *dir; + struct dirTodoNode *next; }; #endif diff --git a/cmd/extra/fsck.fat/ext.h b/cmd/extra/fsck.fat/ext.h @@ -27,7 +27,7 @@ */ #ifndef EXT_H -#define EXT_H +#define EXT_H #include <sys/types.h> @@ -35,17 +35,17 @@ #include "dosfs.h" -#define LOSTDIR "LOST.DIR" +#define LOSTDIR "LOST.DIR" /* * Options: */ -extern int alwaysno; /* assume "no" for all questions */ -extern int alwaysyes; /* assume "yes" for all questions */ -extern int preen; /* we are preening */ -extern int rdonly; /* device is opened read only (supersedes above) */ -extern int skipclean; /* skip clean file systems if preening */ -extern int allow_mmap; /* allow the use of mmap() */ +extern int alwaysno; /* assume "no" for all questions */ +extern int alwaysyes; /* assume "yes" for all questions */ +extern int preen; /* we are preening */ +extern int rdonly; /* device is opened read only (supersedes above) */ +extern int skipclean; /* skip clean file systems if preening */ +extern int allow_mmap; /* allow the use of mmap() */ /* * function declarations @@ -67,13 +67,13 @@ int checkfilesys(const char *); /* * Return values of various functions */ -#define FSOK 0 /* Check was OK */ -#define FSBOOTMOD 1 /* Boot block was modified */ -#define FSDIRMOD 2 /* Some directory was modified */ -#define FSFATMOD 4 /* The FAT was modified */ -#define FSERROR 8 /* Some unrecovered error remains */ -#define FSFATAL 16 /* Some unrecoverable error occurred */ -#define FSDIRTY 32 /* File system is dirty */ +#define FSOK 0 /* Check was OK */ +#define FSBOOTMOD 1 /* Boot block was modified */ +#define FSDIRMOD 2 /* Some directory was modified */ +#define FSFATMOD 4 /* The FAT was modified */ +#define FSERROR 8 /* Some unrecovered error remains */ +#define FSFATAL 16 /* Some unrecoverable error occurred */ +#define FSDIRTY 32 /* File system is dirty */ /* * read a boot block in a machine independent fashion and translate @@ -100,9 +100,9 @@ int fat_set_cl_next(struct fat_descriptor *, cl_t, cl_t); cl_t fat_allocate_cluster(struct fat_descriptor *fat); -struct bootblock* fat_get_boot(struct fat_descriptor *); -int fat_get_fd(struct fat_descriptor *); -bool fat_is_valid_cl(struct fat_descriptor *, cl_t); +struct bootblock *fat_get_boot(struct fat_descriptor *); +int fat_get_fd(struct fat_descriptor *); +bool fat_is_valid_cl(struct fat_descriptor *, cl_t); /* * Read the FAT 0 and return a pointer to the newly allocated @@ -118,9 +118,9 @@ int writefat(struct fat_descriptor *); /* * Read a directory */ -int resetDosDirSection(struct fat_descriptor *); +int resetDosDirSection(struct fat_descriptor *); void finishDosDirSection(void); -int handleDirTree(struct fat_descriptor *); +int handleDirTree(struct fat_descriptor *); /* * Cross-check routines run after everything is completely in memory @@ -134,7 +134,7 @@ int checklost(struct fat_descriptor *); /* * Try to reconnect a lost cluster chain */ -int reconnect(struct fat_descriptor *, cl_t, size_t); +int reconnect(struct fat_descriptor *, cl_t, size_t); void finishlf(void); /* diff --git a/cmd/extra/fsck.fat/fat.c b/cmd/extra/fsck.fat/fat.c @@ -26,7 +26,6 @@ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "freebsd-compat.h" #if defined(__RCSID) && !defined(lint) __RCSID("$NetBSD: fat.c,v 1.18 2006/06/05 16:51:18 christos Exp $"); @@ -49,11 +48,10 @@ __RCSID("$NetBSD: fat.c,v 1.18 2006/06/05 16:51:18 christos Exp $"); #include "ext.h" #include "fsutil.h" -static int _readfat(struct fat_descriptor *); -static inline struct bootblock* boot_of_(struct fat_descriptor *); -static inline int fd_of_(struct fat_descriptor *); -static inline bool valid_cl(struct fat_descriptor *, cl_t); - +static int _readfat(struct fat_descriptor *); +static inline struct bootblock *boot_of_(struct fat_descriptor *); +static inline int fd_of_(struct fat_descriptor *); +static inline bool valid_cl(struct fat_descriptor *, cl_t); /* * Head bitmap for FAT scanning. @@ -80,68 +78,68 @@ static inline bool valid_cl(struct fat_descriptor *, cl_t); */ typedef struct long_bitmap { - unsigned long *map; - size_t count; /* Total set bits in the map */ + unsigned long *map; + size_t count; /* Total set bits in the map */ } long_bitmap_t; static inline void bitmap_clear(long_bitmap_t *lbp, cl_t cl) { - cl_t i = cl / LONG_BIT; - unsigned long clearmask = ~(1UL << (cl % LONG_BIT)); + cl_t i = cl / LONG_BIT; + unsigned long clearmask = ~(1UL << (cl % LONG_BIT)); - assert((lbp->map[i] & ~clearmask) != 0); - lbp->map[i] &= clearmask; - lbp->count--; + assert((lbp->map[i] & ~clearmask) != 0); + lbp->map[i] &= clearmask; + lbp->count--; } static inline bool bitmap_get(long_bitmap_t *lbp, cl_t cl) { - cl_t i = cl / LONG_BIT; - unsigned long usedbit = 1UL << (cl % LONG_BIT); + cl_t i = cl / LONG_BIT; + unsigned long usedbit = 1UL << (cl % LONG_BIT); - return ((lbp->map[i] & usedbit) == usedbit); + return ((lbp->map[i] & usedbit) == usedbit); } static inline bool bitmap_none_in_range(long_bitmap_t *lbp, cl_t cl) { - cl_t i = cl / LONG_BIT; + cl_t i = cl / LONG_BIT; - return (lbp->map[i] == 0); + return (lbp->map[i] == 0); } static inline size_t bitmap_count(long_bitmap_t *lbp) { - return (lbp->count); + return (lbp->count); } static int bitmap_ctor(long_bitmap_t *lbp, size_t bits, bool allone) { - size_t bitmap_size = roundup2(bits, LONG_BIT) / (LONG_BIT / 8); - - free(lbp->map); - lbp->map = calloc(1, bitmap_size); - if (lbp->map == NULL) - return FSFATAL; - - if (allone) { - memset(lbp->map, 0xff, bitmap_size); - lbp->count = bits; - } else { - lbp->count = 0; - } - return FSOK; + size_t bitmap_size = roundup2(bits, LONG_BIT) / (LONG_BIT / 8); + + free(lbp->map); + lbp->map = calloc(1, bitmap_size); + if (lbp->map == NULL) + return FSFATAL; + + if (allone) { + memset(lbp->map, 0xff, bitmap_size); + lbp->count = bits; + } else { + lbp->count = 0; + } + return FSOK; } static void bitmap_dtor(long_bitmap_t *lbp) { - free(lbp->map); - lbp->map = NULL; + free(lbp->map); + lbp->map = NULL; } /* @@ -150,60 +148,60 @@ bitmap_dtor(long_bitmap_t *lbp) * cache with chunk size of 128 KiB to manage it. */ struct fat32_cache_entry { - TAILQ_ENTRY(fat32_cache_entry) entries; - uint8_t *chunk; /* pointer to chunk */ - off_t addr; /* offset */ - bool dirty; /* dirty bit */ + TAILQ_ENTRY(fat32_cache_entry) entries; + uint8_t *chunk; /* pointer to chunk */ + off_t addr; /* offset */ + bool dirty; /* dirty bit */ }; -static const size_t fat32_cache_chunk_size = 131072; /* MAXPHYS */ -static const size_t fat32_cache_size = 4194304; -static const size_t fat32_cache_entries = 32; /* XXXgcc: cache_size / cache_chunk_size */ +static const size_t fat32_cache_chunk_size = 131072; /* MAXPHYS */ +static const size_t fat32_cache_size = 4194304; +static const size_t fat32_cache_entries = 32; /* XXXgcc: cache_size / cache_chunk_size */ /* * FAT table descriptor, represents a FAT table that is already loaded * into memory. */ struct fat_descriptor { - struct bootblock *boot; - uint8_t *fatbuf; - cl_t (*get)(struct fat_descriptor *, cl_t); - int (*set)(struct fat_descriptor *, cl_t, cl_t); - long_bitmap_t headbitmap; - int fd; - bool is_mmapped; - bool use_cache; - size_t fatsize; - - size_t fat32_cached_chunks; - TAILQ_HEAD(cachehead, fat32_cache_entry) fat32_cache_head; - struct fat32_cache_entry *fat32_cache_allentries; - off_t fat32_offset; - off_t fat32_lastaddr; + struct bootblock *boot; + uint8_t *fatbuf; + cl_t (*get)(struct fat_descriptor *, cl_t); + int (*set)(struct fat_descriptor *, cl_t, cl_t); + long_bitmap_t headbitmap; + int fd; + bool is_mmapped; + bool use_cache; + size_t fatsize; + + size_t fat32_cached_chunks; + TAILQ_HEAD(cachehead, fat32_cache_entry) fat32_cache_head; + struct fat32_cache_entry *fat32_cache_allentries; + off_t fat32_offset; + off_t fat32_lastaddr; }; void fat_clear_cl_head(struct fat_descriptor *fat, cl_t cl) { - bitmap_clear(&fat->headbitmap, cl); + bitmap_clear(&fat->headbitmap, cl); } bool fat_is_cl_head(struct fat_descriptor *fat, cl_t cl) { - return (bitmap_get(&fat->headbitmap, cl)); + return (bitmap_get(&fat->headbitmap, cl)); } static inline bool fat_is_cl_head_in_range(struct fat_descriptor *fat, cl_t cl) { - return (!(bitmap_none_in_range(&fat->headbitmap, cl))); + return (!(bitmap_none_in_range(&fat->headbitmap, cl))); } static size_t fat_get_head_count(struct fat_descriptor *fat) { - return (bitmap_count(&fat->headbitmap)); + return (bitmap_count(&fat->headbitmap)); } /* @@ -214,53 +212,53 @@ fat_get_head_count(struct fat_descriptor *fat) static inline uint8_t * fat_get_fat12_ptr(struct fat_descriptor *fat, cl_t cl) { - return (fat->fatbuf + ((cl + (cl >> 1)))); + return (fat->fatbuf + ((cl + (cl >> 1)))); } static cl_t fat_get_fat12_next(struct fat_descriptor *fat, cl_t cl) { - const uint8_t *p; - cl_t retval; + const uint8_t *p; + cl_t retval; - p = fat_get_fat12_ptr(fat, cl); - retval = le16dec(p); - /* Odd cluster: lower 4 bits belongs to the subsequent cluster */ - if ((cl & 1) == 1) - retval >>= 4; - retval &= CLUST12_MASK; + p = fat_get_fat12_ptr(fat, cl); + retval = le16dec(p); + /* Odd cluster: lower 4 bits belongs to the subsequent cluster */ + if ((cl & 1) == 1) + retval >>= 4; + retval &= CLUST12_MASK; - if (retval >= (CLUST_BAD & CLUST12_MASK)) - retval |= ~CLUST12_MASK; + if (retval >= (CLUST_BAD & CLUST12_MASK)) + retval |= ~CLUST12_MASK; - return (retval); + return (retval); } static int fat_set_fat12_next(struct fat_descriptor *fat, cl_t cl, cl_t nextcl) { - uint8_t *p; + uint8_t *p; - /* Truncate 'nextcl' value, if needed */ - nextcl &= CLUST12_MASK; + /* Truncate 'nextcl' value, if needed */ + nextcl &= CLUST12_MASK; - p = fat_get_fat12_ptr(fat, cl); + p = fat_get_fat12_ptr(fat, cl); - /* - * Read in the 4 bits from the subsequent (for even clusters) - * or the preceding (for odd clusters) cluster and combine - * it to the nextcl value for encoding - */ - if ((cl & 1) == 0) { - nextcl |= ((p[1] & 0xf0) << 8); - } else { - nextcl <<= 4; - nextcl |= (p[0] & 0x0f); - } + /* + * Read in the 4 bits from the subsequent (for even clusters) + * or the preceding (for odd clusters) cluster and combine + * it to the nextcl value for encoding + */ + if ((cl & 1) == 0) { + nextcl |= ((p[1] & 0xf0) << 8); + } else { + nextcl <<= 4; + nextcl |= (p[0] & 0x0f); + } - le16enc(p, (uint16_t)nextcl); + le16enc(p, (uint16_t)nextcl); - return (0); + return (0); } /* @@ -271,37 +269,37 @@ fat_set_fat12_next(struct fat_descriptor *fat, cl_t cl, cl_t nextcl) static inline uint8_t * fat_get_fat16_ptr(struct fat_descriptor *fat, cl_t cl) { - return (fat->fatbuf + (cl << 1)); + return (fat->fatbuf + (cl << 1)); } static cl_t fat_get_fat16_next(struct fat_descriptor *fat, cl_t cl) { - const uint8_t *p; - cl_t retval; + const uint8_t *p; + cl_t retval; - p = fat_get_fat16_ptr(fat, cl); - retval = le16dec(p) & CLUST16_MASK; + p = fat_get_fat16_ptr(fat, cl); + retval = le16dec(p) & CLUST16_MASK; - if (retval >= (CLUST_BAD & CLUST16_MASK)) - retval |= ~CLUST16_MASK; + if (retval >= (CLUST_BAD & CLUST16_MASK)) + retval |= ~CLUST16_MASK; - return (retval); + return (retval); } static int fat_set_fat16_next(struct fat_descriptor *fat, cl_t cl, cl_t nextcl) { - uint8_t *p; + uint8_t *p; - /* Truncate 'nextcl' value, if needed */ - nextcl &= CLUST16_MASK; + /* Truncate 'nextcl' value, if needed */ + nextcl &= CLUST16_MASK; - p = fat_get_fat16_ptr(fat, cl); + p = fat_get_fat16_ptr(fat, cl); - le16enc(p, (uint16_t)nextcl); + le16enc(p, (uint16_t)nextcl); - return (0); + return (0); } /* @@ -310,235 +308,231 @@ fat_set_fat16_next(struct fat_descriptor *fat, cl_t cl, cl_t nextcl) static inline uint8_t * fat_get_fat32_ptr(struct fat_descriptor *fat, cl_t cl) { - return (fat->fatbuf + (cl << 2)); + return (fat->fatbuf + (cl << 2)); } static cl_t fat_get_fat32_next(struct fat_descriptor *fat, cl_t cl) { - const uint8_t *p; - cl_t retval; + const uint8_t *p; + cl_t retval; - p = fat_get_fat32_ptr(fat, cl); - retval = le32dec(p) & CLUST32_MASK; + p = fat_get_fat32_ptr(fat, cl); + retval = le32dec(p) & CLUST32_MASK; - if (retval >= (CLUST_BAD & CLUST32_MASK)) - retval |= ~CLUST32_MASK; + if (retval >= (CLUST_BAD & CLUST32_MASK)) + retval |= ~CLUST32_MASK; - return (retval); + return (retval); } static int fat_set_fat32_next(struct fat_descriptor *fat, cl_t cl, cl_t nextcl) { - uint8_t *p; + uint8_t *p; - /* Truncate 'nextcl' value, if needed */ - nextcl &= CLUST32_MASK; + /* Truncate 'nextcl' value, if needed */ + nextcl &= CLUST32_MASK; - p = fat_get_fat32_ptr(fat, cl); + p = fat_get_fat32_ptr(fat, cl); - le32enc(p, (uint32_t)nextcl); + le32enc(p, (uint32_t)nextcl); - return (0); + return (0); } static inline size_t fat_get_iosize(struct fat_descriptor *fat, off_t address) { - - if (address == fat->fat32_lastaddr) { - return (fat->fatsize & ((off_t)fat32_cache_chunk_size - 1)); - } else { - return (fat32_cache_chunk_size); - } + if (address == fat->fat32_lastaddr) { + return (fat->fatsize & ((off_t)fat32_cache_chunk_size - 1)); + } else { + return (fat32_cache_chunk_size); + } } static int -fat_flush_fat32_cache_entry(struct fat_descriptor *fat, - struct fat32_cache_entry *entry) +fat_flush_fat32_cache_entry(struct fat_descriptor *fat, struct fat32_cache_entry *entry) { - int fd; - off_t fat_addr; - size_t writesize; + int fd; + off_t fat_addr; + size_t writesize; - fd = fd_of_(fat); + fd = fd_of_(fat); - if (!entry->dirty) - return (FSOK); + if (!entry->dirty) + return (FSOK); - writesize = fat_get_iosize(fat, entry->addr); + writesize = fat_get_iosize(fat, entry->addr); - fat_addr = fat->fat32_offset + entry->addr; - if (lseek(fd, fat_addr, SEEK_SET) != fat_addr || - (size_t)write(fd, entry->chunk, writesize) != writesize) { - pfatal("Unable to write FAT"); - return (FSFATAL); - } + fat_addr = fat->fat32_offset + entry->addr; + if (lseek(fd, fat_addr, SEEK_SET) != fat_addr + || (size_t)write(fd, entry->chunk, writesize) != writesize) { + pfatal("Unable to write FAT"); + return (FSFATAL); + } - entry->dirty = false; - return (FSOK); + entry->dirty = false; + return (FSOK); } static struct fat32_cache_entry * -fat_get_fat32_cache_entry(struct fat_descriptor *fat, off_t addr, - bool writing) +fat_get_fat32_cache_entry(struct fat_descriptor *fat, off_t addr, bool writing) { - int fd; - struct fat32_cache_entry *entry, *first; - off_t fat_addr; - size_t rwsize; - - addr &= ~(fat32_cache_chunk_size - 1); - - first = TAILQ_FIRST(&fat->fat32_cache_head); - - /* - * Cache hit: if we already have the chunk, move it to list head - */ - TAILQ_FOREACH(entry, &fat->fat32_cache_head, entries) { - if (entry->addr == addr) { - if (writing) { - entry->dirty = true; - } - if (entry != first) { - - TAILQ_REMOVE(&fat->fat32_cache_head, entry, entries); - TAILQ_INSERT_HEAD(&fat->fat32_cache_head, entry, entries); - } - return (entry); - } - } - - /* - * Cache miss: detach the chunk at tail of list, overwrite with - * the located chunk, and populate with data from disk. - */ - entry = TAILQ_LAST(&fat->fat32_cache_head, cachehead); - TAILQ_REMOVE(&fat->fat32_cache_head, entry, entries); - if (fat_flush_fat32_cache_entry(fat, entry) != FSOK) { - return (NULL); - } - - rwsize = fat_get_iosize(fat, addr); - fat_addr = fat->fat32_offset + addr; - entry->addr = addr; - fd = fd_of_(fat); - if (lseek(fd, fat_addr, SEEK_SET) != fat_addr || - (size_t)read(fd, entry->chunk, rwsize) != rwsize) { - pfatal("Unable to read FAT"); - return (NULL); - } - if (writing) { - entry->dirty = true; - } - TAILQ_INSERT_HEAD(&fat->fat32_cache_head, entry, entries); - - return (entry); + int fd; + struct fat32_cache_entry *entry, *first; + off_t fat_addr; + size_t rwsize; + + addr &= ~(fat32_cache_chunk_size - 1); + + first = TAILQ_FIRST(&fat->fat32_cache_head); + + /* + * Cache hit: if we already have the chunk, move it to list head + */ + TAILQ_FOREACH(entry, &fat->fat32_cache_head, entries) + { + if (entry->addr == addr) { + if (writing) { + entry->dirty = true; + } + if (entry != first) { + TAILQ_REMOVE(&fat->fat32_cache_head, entry, entries); + TAILQ_INSERT_HEAD(&fat->fat32_cache_head, entry, entries); + } + return (entry); + } + } + + /* + * Cache miss: detach the chunk at tail of list, overwrite with + * the located chunk, and populate with data from disk. + */ + entry = TAILQ_LAST(&fat->fat32_cache_head, cachehead); + TAILQ_REMOVE(&fat->fat32_cache_head, entry, entries); + if (fat_flush_fat32_cache_entry(fat, entry) != FSOK) { + return (NULL); + } + + rwsize = fat_get_iosize(fat, addr); + fat_addr = fat->fat32_offset + addr; + entry->addr = addr; + fd = fd_of_(fat); + if (lseek(fd, fat_addr, SEEK_SET) != fat_addr + || (size_t)read(fd, entry->chunk, rwsize) != rwsize) { + pfatal("Unable to read FAT"); + return (NULL); + } + if (writing) { + entry->dirty = true; + } + TAILQ_INSERT_HEAD(&fat->fat32_cache_head, entry, entries); + + return (entry); } static inline uint8_t * fat_get_fat32_cached_ptr(struct fat_descriptor *fat, cl_t cl, bool writing) { - off_t addr, off; - struct fat32_cache_entry *entry; - - addr = cl << 2; - entry = fat_get_fat32_cache_entry(fat, addr, writing); - - if (entry != NULL) { - off = addr & (fat32_cache_chunk_size - 1); - return (entry->chunk + off); - } else { - return (NULL); - } + off_t addr, off; + struct fat32_cache_entry *entry; + + addr = cl << 2; + entry = fat_get_fat32_cache_entry(fat, addr, writing); + + if (entry != NULL) { + off = addr & (fat32_cache_chunk_size - 1); + return (entry->chunk + off); + } else { + return (NULL); + } } - static cl_t fat_get_fat32_cached_next(struct fat_descriptor *fat, cl_t cl) { - const uint8_t *p; - cl_t retval; - - p = fat_get_fat32_cached_ptr(fat, cl, false); - if (p != NULL) { - retval = le32dec(p) & CLUST32_MASK; - if (retval >= (CLUST_BAD & CLUST32_MASK)) - retval |= ~CLUST32_MASK; - } else { - retval = CLUST_DEAD; - } - - return (retval); + const uint8_t *p; + cl_t retval; + + p = fat_get_fat32_cached_ptr(fat, cl, false); + if (p != NULL) { + retval = le32dec(p) & CLUST32_MASK; + if (retval >= (CLUST_BAD & CLUST32_MASK)) + retval |= ~CLUST32_MASK; + } else { + retval = CLUST_DEAD; + } + + return (retval); } static int fat_set_fat32_cached_next(struct fat_descriptor *fat, cl_t cl, cl_t nextcl) { - uint8_t *p; - - /* Truncate 'nextcl' value, if needed */ - nextcl &= CLUST32_MASK; - - p = fat_get_fat32_cached_ptr(fat, cl, true); - if (p != NULL) { - le32enc(p, (uint32_t)nextcl); - return FSOK; - } else { - return FSFATAL; - } + uint8_t *p; + + /* Truncate 'nextcl' value, if needed */ + nextcl &= CLUST32_MASK; + + p = fat_get_fat32_cached_ptr(fat, cl, true); + if (p != NULL) { + le32enc(p, (uint32_t)nextcl); + return FSOK; + } else { + return FSFATAL; + } } -cl_t fat_get_cl_next(struct fat_descriptor *fat, cl_t cl) +cl_t +fat_get_cl_next(struct fat_descriptor *fat, cl_t cl) { + if (!valid_cl(fat, cl)) { + pfatal("Invalid cluster: %ud", cl); + return CLUST_DEAD; + } - if (!valid_cl(fat, cl)) { - pfatal("Invalid cluster: %ud", cl); - return CLUST_DEAD; - } - - return (fat->get(fat, cl)); + return (fat->get(fat, cl)); } -int fat_set_cl_next(struct fat_descriptor *fat, cl_t cl, cl_t nextcl) +int +fat_set_cl_next(struct fat_descriptor *fat, cl_t cl, cl_t nextcl) { + if (rdonly) { + pwarn(" (NO WRITE)\n"); + return FSFATAL; + } - if (rdonly) { - pwarn(" (NO WRITE)\n"); - return FSFATAL; - } - - if (!valid_cl(fat, cl)) { - pfatal("Invalid cluster: %ud", cl); - return FSFATAL; - } + if (!valid_cl(fat, cl)) { + pfatal("Invalid cluster: %ud", cl); + return FSFATAL; + } - return (fat->set(fat, cl, nextcl)); + return (fat->set(fat, cl, nextcl)); } -static inline struct bootblock* -boot_of_(struct fat_descriptor *fat) { - - return (fat->boot); +static inline struct bootblock * +boot_of_(struct fat_descriptor *fat) +{ + return (fat->boot); } -struct bootblock* -fat_get_boot(struct fat_descriptor *fat) { - - return (boot_of_(fat)); +struct bootblock * +fat_get_boot(struct fat_descriptor *fat) +{ + return (boot_of_(fat)); } static inline int fd_of_(struct fat_descriptor *fat) { - return (fat->fd); + return (fat->fd); } int -fat_get_fd(struct fat_descriptor * fat) +fat_get_fd(struct fat_descriptor *fat) { - return (fd_of_(fat)); + return (fd_of_(fat)); } /* @@ -547,16 +541,15 @@ fat_get_fd(struct fat_descriptor * fat) bool fat_is_valid_cl(struct fat_descriptor *fat, cl_t cl) { - - return (valid_cl(fat, cl)); + return (valid_cl(fat, cl)); } static inline bool valid_cl(struct fat_descriptor *fat, cl_t cl) { - const struct bootblock *boot = boot_of_(fat); + const struct bootblock *boot = boot_of_(fat); - return (cl >= CLUST_FIRST && cl < boot->NumClusters); + return (cl >= CLUST_FIRST && cl < boot->NumClusters); } /* @@ -579,111 +572,109 @@ valid_cl(struct fat_descriptor *fat, cl_t cl) int checkdirty(int fs, struct bootblock *boot) { - off_t off; - u_char *buffer; - int ret = 0; - size_t len; - - if (boot->ClustMask != CLUST16_MASK && boot->ClustMask != CLUST32_MASK) - return 0; - - off = boot->bpbResSectors; - off *= boot->bpbBytesPerSec; - - buffer = malloc(len = boot->bpbBytesPerSec); - if (buffer == NULL) { - perr("No space for FAT sectors (%zu)", len); - return 1; - } - - if (lseek(fs, off, SEEK_SET) != off) { - perr("Unable to read FAT"); - goto err; - } - - if ((size_t)read(fs, buffer, boot->bpbBytesPerSec) != - boot->bpbBytesPerSec) { - perr("Unable to read FAT"); - goto err; - } - - /* - * If we don't understand the FAT, then the file system must be - * assumed to be unclean. - */ - if (buffer[0] != boot->bpbMedia || buffer[1] != 0xff) - goto err; - if (boot->ClustMask == CLUST16_MASK) { - if ((buffer[2] & 0xf8) != 0xf8 || (buffer[3] & 0x3f) != 0x3f) - goto err; - } else { - if (buffer[2] != 0xff || (buffer[3] & 0x0f) != 0x0f - || (buffer[4] & 0xf8) != 0xf8 || buffer[5] != 0xff - || buffer[6] != 0xff || (buffer[7] & 0x03) != 0x03) - goto err; - } - - /* - * Now check the actual clean flag (and the no-error flag). - */ - if (boot->ClustMask == CLUST16_MASK) { - if ((buffer[3] & 0xc0) == 0xc0) - ret = 1; - } else { - if ((buffer[7] & 0x0c) == 0x0c) - ret = 1; - } + off_t off; + u_char *buffer; + int ret = 0; + size_t len; + + if (boot->ClustMask != CLUST16_MASK && boot->ClustMask != CLUST32_MASK) + return 0; + + off = boot->bpbResSectors; + off *= boot->bpbBytesPerSec; + + buffer = malloc(len = boot->bpbBytesPerSec); + if (buffer == NULL) { + perr("No space for FAT sectors (%zu)", len); + return 1; + } + + if (lseek(fs, off, SEEK_SET) != off) { + perr("Unable to read FAT"); + goto err; + } + + if ((size_t)read(fs, buffer, boot->bpbBytesPerSec) != boot->bpbBytesPerSec) { + perr("Unable to read FAT"); + goto err; + } + + /* + * If we don't understand the FAT, then the file system must be + * assumed to be unclean. + */ + if (buffer[0] != boot->bpbMedia || buffer[1] != 0xff) + goto err; + if (boot->ClustMask == CLUST16_MASK) { + if ((buffer[2] & 0xf8) != 0xf8 || (buffer[3] & 0x3f) != 0x3f) + goto err; + } else { + if (buffer[2] != 0xff || (buffer[3] & 0x0f) != 0x0f || (buffer[4] & 0xf8) != 0xf8 + || buffer[5] != 0xff || buffer[6] != 0xff || (buffer[7] & 0x03) != 0x03) + goto err; + } + + /* + * Now check the actual clean flag (and the no-error flag). + */ + if (boot->ClustMask == CLUST16_MASK) { + if ((buffer[3] & 0xc0) == 0xc0) + ret = 1; + } else { + if ((buffer[7] & 0x0c) == 0x0c) + ret = 1; + } err: - free(buffer); - return ret; + free(buffer); + return ret; } int cleardirty(struct fat_descriptor *fat) { - int fd, ret = FSERROR; - struct bootblock *boot; - u_char *buffer; - size_t len; - off_t off; + int fd, ret = FSERROR; + struct bootblock *boot; + u_char *buffer; + size_t len; + off_t off; - boot = boot_of_(fat); - fd = fd_of_(fat); + boot = boot_of_(fat); + fd = fd_of_(fat); - if (boot->ClustMask != CLUST16_MASK && boot->ClustMask != CLUST32_MASK) - return 0; + if (boot->ClustMask != CLUST16_MASK && boot->ClustMask != CLUST32_MASK) + return 0; - off = boot->bpbResSectors; - off *= boot->bpbBytesPerSec; + off = boot->bpbResSectors; + off *= boot->bpbBytesPerSec; - buffer = malloc(len = boot->bpbBytesPerSec); - if (buffer == NULL) { - perr("No memory for FAT sectors (%zu)", len); - return 1; - } + buffer = malloc(len = boot->bpbBytesPerSec); + if (buffer == NULL) { + perr("No memory for FAT sectors (%zu)", len); + return 1; + } - if ((size_t)pread(fd, buffer, len, off) != len) { - perr("Unable to read FAT"); - goto err; - } + if ((size_t)pread(fd, buffer, len, off) != len) { + perr("Unable to read FAT"); + goto err; + } - if (boot->ClustMask == CLUST16_MASK) { - buffer[3] |= 0x80; - } else { - buffer[7] |= 0x08; - } + if (boot->ClustMask == CLUST16_MASK) { + buffer[3] |= 0x80; + } else { + buffer[7] |= 0x08; + } - if ((size_t)pwrite(fd, buffer, len, off) != len) { - perr("Unable to write FAT"); - goto err; - } + if ((size_t)pwrite(fd, buffer, len, off) != len) { + perr("Unable to write FAT"); + goto err; + } - ret = FSOK; + ret = FSOK; err: - free(buffer); - return ret; + free(buffer); + return ret; } /* @@ -692,111 +683,108 @@ err: static int _readfat(struct fat_descriptor *fat) { - int fd; - size_t i; - off_t off; - size_t readsize; - struct bootblock *boot; - struct fat32_cache_entry *entry; - - boot = boot_of_(fat); - fd = fd_of_(fat); - fat->fatsize = boot->FATsecs * boot->bpbBytesPerSec; - - off = boot->bpbResSectors; - off *= boot->bpbBytesPerSec; - - fat->is_mmapped = false; - fat->use_cache = false; - - /* Attempt to mmap() first */ - if (allow_mmap) { - fat->fatbuf = mmap(NULL, fat->fatsize, - PROT_READ | (rdonly ? 0 : PROT_WRITE), - MAP_SHARED, fd_of_(fat), off); - if (fat->fatbuf != MAP_FAILED) { - fat->is_mmapped = true; - return 1; - } - } - - /* - * Unfortunately, we were unable to mmap(). - * - * Only use the cache manager when it's necessary, that is, - * when the FAT is sufficiently large; in that case, only - * read in the first 4 MiB of FAT into memory, and split the - * buffer into chunks and insert to the LRU queue to populate - * the cache with data. - */ - if (boot->ClustMask == CLUST32_MASK && - fat->fatsize >= fat32_cache_size) { - readsize = fat32_cache_size; - fat->use_cache = true; - - fat->fat32_offset = boot->bpbResSectors * boot->bpbBytesPerSec; - fat->fat32_lastaddr = fat->fatsize & ~(fat32_cache_chunk_size); - } else { - readsize = fat->fatsize; - } - fat->fatbuf = malloc(readsize); - if (fat->fatbuf == NULL) { - perr("No space for FAT (%zu)", readsize); - return 0; - } - - if (lseek(fd, off, SEEK_SET) != off) { - perr("Unable to read FAT"); - goto err; - } - if ((size_t)read(fd, fat->fatbuf, readsize) != readsize) { - perr("Unable to read FAT"); - goto err; - } - - /* - * When cache is used, split the buffer into chunks, and - * connect the buffer into the cache. - */ - if (fat->use_cache) { - TAILQ_INIT(&fat->fat32_cache_head); - entry = calloc(fat32_cache_entries, sizeof(*entry)); - if (entry == NULL) { - perr("No space for FAT cache (%zu of %zu)", - fat32_cache_entries, sizeof(entry)); - goto err; - } - for (i = 0; i < fat32_cache_entries; i++) { - entry[i].addr = fat32_cache_chunk_size * i; - entry[i].chunk = &fat->fatbuf[entry[i].addr]; - TAILQ_INSERT_TAIL(&fat->fat32_cache_head, - &entry[i], entries); - } - fat->fat32_cache_allentries = entry; - } - - return 1; + int fd; + size_t i; + off_t off; + size_t readsize; + struct bootblock *boot; + struct fat32_cache_entry *entry; + + boot = boot_of_(fat); + fd = fd_of_(fat); + fat->fatsize = boot->FATsecs * boot->bpbBytesPerSec; + + off = boot->bpbResSectors; + off *= boot->bpbBytesPerSec; + + fat->is_mmapped = false; + fat->use_cache = false; + + /* Attempt to mmap() first */ + if (allow_mmap) { + fat->fatbuf = mmap( + NULL, fat->fatsize, PROT_READ | (rdonly ? 0 : PROT_WRITE), MAP_SHARED, fd_of_(fat), off + ); + if (fat->fatbuf != MAP_FAILED) { + fat->is_mmapped = true; + return 1; + } + } + + /* + * Unfortunately, we were unable to mmap(). + * + * Only use the cache manager when it's necessary, that is, + * when the FAT is sufficiently large; in that case, only + * read in the first 4 MiB of FAT into memory, and split the + * buffer into chunks and insert to the LRU queue to populate + * the cache with data. + */ + if (boot->ClustMask == CLUST32_MASK && fat->fatsize >= fat32_cache_size) { + readsize = fat32_cache_size; + fat->use_cache = true; + + fat->fat32_offset = boot->bpbResSectors * boot->bpbBytesPerSec; + fat->fat32_lastaddr = fat->fatsize & ~(fat32_cache_chunk_size); + } else { + readsize = fat->fatsize; + } + fat->fatbuf = malloc(readsize); + if (fat->fatbuf == NULL) { + perr("No space for FAT (%zu)", readsize); + return 0; + } + + if (lseek(fd, off, SEEK_SET) != off) { + perr("Unable to read FAT"); + goto err; + } + if ((size_t)read(fd, fat->fatbuf, readsize) != readsize) { + perr("Unable to read FAT"); + goto err; + } + + /* + * When cache is used, split the buffer into chunks, and + * connect the buffer into the cache. + */ + if (fat->use_cache) { + TAILQ_INIT(&fat->fat32_cache_head); + entry = calloc(fat32_cache_entries, sizeof(*entry)); + if (entry == NULL) { + perr("No space for FAT cache (%zu of %zu)", fat32_cache_entries, sizeof(entry)); + goto err; + } + for (i = 0; i < fat32_cache_entries; i++) { + entry[i].addr = fat32_cache_chunk_size * i; + entry[i].chunk = &fat->fatbuf[entry[i].addr]; + TAILQ_INSERT_TAIL(&fat->fat32_cache_head, &entry[i], entries); + } + fat->fat32_cache_allentries = entry; + } + + return 1; err: - free(fat->fatbuf); - fat->fatbuf = NULL; - return 0; + free(fat->fatbuf); + fat->fatbuf = NULL; + return 0; } static void releasefat(struct fat_descriptor *fat) { - if (fat->is_mmapped) { - munmap(fat->fatbuf, fat->fatsize); - } else { - if (fat->use_cache) { - free(fat->fat32_cache_allentries); - fat->fat32_cache_allentries = NULL; - } - free(fat->fatbuf); - } - fat->fatbuf = NULL; - bitmap_dtor(&fat->headbitmap); + if (fat->is_mmapped) { + munmap(fat->fatbuf, fat->fatsize); + } else { + if (fat->use_cache) { + free(fat->fat32_cache_allentries); + fat->fat32_cache_allentries = NULL; + } + free(fat->fatbuf); + } + fat->fatbuf = NULL; + bitmap_dtor(&fat->headbitmap); } /* @@ -805,211 +793,220 @@ releasefat(struct fat_descriptor *fat) int readfat(int fs, struct bootblock *boot, struct fat_descriptor **fp) { - struct fat_descriptor *fat; - u_char *buffer, *p; - cl_t cl, nextcl; - int ret = FSOK; - - boot->NumFree = boot->NumBad = 0; - - fat = calloc(1, sizeof(struct fat_descriptor)); - if (fat == NULL) { - perr("No space for FAT descriptor"); - return FSFATAL; - } - - fat->fd = fs; - fat->boot = boot; - - if (!_readfat(fat)) { - free(fat); - return FSFATAL; - } - buffer = fat->fatbuf; - - /* Populate accessors */ - switch(boot->ClustMask) { - case CLUST12_MASK: - fat->get = fat_get_fat12_next; - fat->set = fat_set_fat12_next; - break; - case CLUST16_MASK: - fat->get = fat_get_fat16_next; - fat->set = fat_set_fat16_next; - break; - case CLUST32_MASK: - if (fat->is_mmapped || !fat->use_cache) { - fat->get = fat_get_fat32_next; - fat->set = fat_set_fat32_next; - } else { - fat->get = fat_get_fat32_cached_next; - fat->set = fat_set_fat32_cached_next; - } - break; - default: - pfatal("Invalid ClustMask: %d", boot->ClustMask); - releasefat(fat); - free(fat); - return FSFATAL; - } - - if (bitmap_ctor(&fat->headbitmap, boot->NumClusters, - true) != FSOK) { - perr("No space for head bitmap for FAT clusters (%zu)", - (size_t)boot->NumClusters); - releasefat(fat); - free(fat); - return FSFATAL; - } - - if (buffer[0] != boot->bpbMedia - || buffer[1] != 0xff || buffer[2] != 0xff - || (boot->ClustMask == CLUST16_MASK && buffer[3] != 0xff) - || (boot->ClustMask == CLUST32_MASK - && ((buffer[3]&0x0f) != 0x0f - || buffer[4] != 0xff || buffer[5] != 0xff - || buffer[6] != 0xff || (buffer[7]&0x0f) != 0x0f))) { - - /* Windows 95 OSR2 (and possibly any later) changes - * the FAT signature to 0xXXffff7f for FAT16 and to - * 0xXXffff0fffffff07 for FAT32 upon boot, to know that the - * file system is dirty if it doesn't reboot cleanly. - * Check this special condition before errorring out. - */ - if (buffer[0] == boot->bpbMedia && buffer[1] == 0xff - && buffer[2] == 0xff - && ((boot->ClustMask == CLUST16_MASK && buffer[3] == 0x7f) - || (boot->ClustMask == CLUST32_MASK - && buffer[3] == 0x0f && buffer[4] == 0xff - && buffer[5] == 0xff && buffer[6] == 0xff - && buffer[7] == 0x07))) - ret |= FSDIRTY; - else { - /* just some odd byte sequence in FAT */ - - switch (boot->ClustMask) { - case CLUST32_MASK: - pwarn("%s (%02x%02x%02x%02x%02x%02x%02x%02x)\n", - "FAT starts with odd byte sequence", - buffer[0], buffer[1], buffer[2], buffer[3], - buffer[4], buffer[5], buffer[6], buffer[7]); - break; - case CLUST16_MASK: - pwarn("%s (%02x%02x%02x%02x)\n", - "FAT starts with odd byte sequence", - buffer[0], buffer[1], buffer[2], buffer[3]); - break; - default: - pwarn("%s (%02x%02x%02x)\n", - "FAT starts with odd byte sequence", - buffer[0], buffer[1], buffer[2]); - break; - } - - if (ask(1, "Correct")) { - ret |= FSFATMOD; - p = buffer; - - *p++ = (u_char)boot->bpbMedia; - *p++ = 0xff; - *p++ = 0xff; - switch (boot->ClustMask) { - case CLUST16_MASK: - *p++ = 0xff; - break; - case CLUST32_MASK: - *p++ = 0x0f; - *p++ = 0xff; - *p++ = 0xff; - *p++ = 0xff; - *p++ = 0x0f; - break; - default: - break; - } - } - } - } - - /* - * Traverse the FAT table and populate head map. Initially, we - * consider all clusters as possible head cluster (beginning of - * a file or directory), and traverse the whole allocation table - * by marking every non-head nodes as such (detailed below) and - * fix obvious issues while we walk. - * - * For each "next" cluster, the possible values are: - * - * a) CLUST_FREE or CLUST_BAD. The *current* cluster can't be a - * head node. - * b) An out-of-range value. The only fix would be to truncate at - * the cluster. - * c) A valid cluster. It means that cluster (nextcl) is not a - * head cluster. Note that during the scan, every cluster is - * expected to be seen for at most once, and when we saw them - * twice, it means a cross-linked chain which should be - * truncated at the current cluster. - * - * After scan, the remaining set bits indicates all possible - * head nodes, because they were never claimed by any other - * node as the next node, but we do not know if these chains - * would end with a valid EOF marker. We will check that in - * checkchain() at a later time when checking directories, - * where these head nodes would be marked as non-head. - * - * In the final pass, all head nodes should be cleared, and if - * there is still head nodes, these would be leaders of lost - * chain. - */ - for (cl = CLUST_FIRST; cl < boot->NumClusters; cl++) { - nextcl = fat_get_cl_next(fat, cl); - - /* Check if the next cluster number is valid */ - if (nextcl == CLUST_FREE) { - /* Save a hint for next free cluster */ - if (boot->FSNext == 0) { - boot->FSNext = cl; - } - if (fat_is_cl_head(fat, cl)) { - fat_clear_cl_head(fat, cl); - } - boot->NumFree++; - } else if (nextcl == CLUST_BAD) { - if (fat_is_cl_head(fat, cl)) { - fat_clear_cl_head(fat, cl); - } - boot->NumBad++; - } else if (!valid_cl(fat, nextcl) && nextcl < CLUST_RSRVD) { - pwarn("Cluster %u continues with out of range " - "cluster number %u\n", - cl, - nextcl & boot->ClustMask); - if (ask(0, "Truncate")) { - ret |= fat_set_cl_next(fat, cl, CLUST_EOF); - ret |= FSFATMOD; - } - } else if (valid_cl(fat, nextcl)) { - if (fat_is_cl_head(fat, nextcl)) { - fat_clear_cl_head(fat, nextcl); - } else { - pwarn("Cluster %u crossed another chain at %u\n", - cl, nextcl); - if (ask(0, "Truncate")) { - ret |= fat_set_cl_next(fat, cl, CLUST_EOF); - ret |= FSFATMOD; - } - } - } - - } - - if (ret & FSFATAL) { - releasefat(fat); - free(fat); - *fp = NULL; - } else - *fp = fat; - return ret; + struct fat_descriptor *fat; + u_char *buffer, *p; + cl_t cl, nextcl; + int ret = FSOK; + + boot->NumFree = boot->NumBad = 0; + + fat = calloc(1, sizeof(struct fat_descriptor)); + if (fat == NULL) { + perr("No space for FAT descriptor"); + return FSFATAL; + } + + fat->fd = fs; + fat->boot = boot; + + if (!_readfat(fat)) { + free(fat); + return FSFATAL; + } + buffer = fat->fatbuf; + + /* Populate accessors */ + switch (boot->ClustMask) { + case CLUST12_MASK: + fat->get = fat_get_fat12_next; + fat->set = fat_set_fat12_next; + break; + case CLUST16_MASK: + fat->get = fat_get_fat16_next; + fat->set = fat_set_fat16_next; + break; + case CLUST32_MASK: + if (fat->is_mmapped || !fat->use_cache) { + fat->get = fat_get_fat32_next; + fat->set = fat_set_fat32_next; + } else { + fat->get = fat_get_fat32_cached_next; + fat->set = fat_set_fat32_cached_next; + } + break; + default: + pfatal("Invalid ClustMask: %d", boot->ClustMask); + releasefat(fat); + free(fat); + return FSFATAL; + } + + if (bitmap_ctor(&fat->headbitmap, boot->NumClusters, true) != FSOK) { + perr("No space for head bitmap for FAT clusters (%zu)", (size_t)boot->NumClusters); + releasefat(fat); + free(fat); + return FSFATAL; + } + + if (buffer[0] != boot->bpbMedia || buffer[1] != 0xff || buffer[2] != 0xff + || (boot->ClustMask == CLUST16_MASK && buffer[3] != 0xff) + || (boot->ClustMask == CLUST32_MASK + && ((buffer[3] & 0x0f) != 0x0f || buffer[4] != 0xff || buffer[5] != 0xff + || buffer[6] != 0xff || (buffer[7] & 0x0f) != 0x0f))) { + /* Windows 95 OSR2 (and possibly any later) changes + * the FAT signature to 0xXXffff7f for FAT16 and to + * 0xXXffff0fffffff07 for FAT32 upon boot, to know that the + * file system is dirty if it doesn't reboot cleanly. + * Check this special condition before errorring out. + */ + if (buffer[0] == boot->bpbMedia && buffer[1] == 0xff && buffer[2] == 0xff + && ((boot->ClustMask == CLUST16_MASK && buffer[3] == 0x7f) + || (boot->ClustMask == CLUST32_MASK && buffer[3] == 0x0f && buffer[4] == 0xff + && buffer[5] == 0xff && buffer[6] == 0xff && buffer[7] == 0x07))) + ret |= FSDIRTY; + else { + /* just some odd byte sequence in FAT */ + + switch (boot->ClustMask) { + case CLUST32_MASK: + pwarn( + "%s (%02x%02x%02x%02x%02x%02x%02x%02x)\n", + "FAT starts with odd byte sequence", + buffer[0], + buffer[1], + buffer[2], + buffer[3], + buffer[4], + buffer[5], + buffer[6], + buffer[7] + ); + break; + case CLUST16_MASK: + pwarn( + "%s (%02x%02x%02x%02x)\n", + "FAT starts with odd byte sequence", + buffer[0], + buffer[1], + buffer[2], + buffer[3] + ); + break; + default: + pwarn( + "%s (%02x%02x%02x)\n", + "FAT starts with odd byte sequence", + buffer[0], + buffer[1], + buffer[2] + ); + break; + } + + if (ask(1, "Correct")) { + ret |= FSFATMOD; + p = buffer; + + *p++ = (u_char)boot->bpbMedia; + *p++ = 0xff; + *p++ = 0xff; + switch (boot->ClustMask) { + case CLUST16_MASK: + *p++ = 0xff; + break; + case CLUST32_MASK: + *p++ = 0x0f; + *p++ = 0xff; + *p++ = 0xff; + *p++ = 0xff; + *p++ = 0x0f; + break; + default: + break; + } + } + } + } + + /* + * Traverse the FAT table and populate head map. Initially, we + * consider all clusters as possible head cluster (beginning of + * a file or directory), and traverse the whole allocation table + * by marking every non-head nodes as such (detailed below) and + * fix obvious issues while we walk. + * + * For each "next" cluster, the possible values are: + * + * a) CLUST_FREE or CLUST_BAD. The *current* cluster can't be a + * head node. + * b) An out-of-range value. The only fix would be to truncate at + * the cluster. + * c) A valid cluster. It means that cluster (nextcl) is not a + * head cluster. Note that during the scan, every cluster is + * expected to be seen for at most once, and when we saw them + * twice, it means a cross-linked chain which should be + * truncated at the current cluster. + * + * After scan, the remaining set bits indicates all possible + * head nodes, because they were never claimed by any other + * node as the next node, but we do not know if these chains + * would end with a valid EOF marker. We will check that in + * checkchain() at a later time when checking directories, + * where these head nodes would be marked as non-head. + * + * In the final pass, all head nodes should be cleared, and if + * there is still head nodes, these would be leaders of lost + * chain. + */ + for (cl = CLUST_FIRST; cl < boot->NumClusters; cl++) { + nextcl = fat_get_cl_next(fat, cl); + + /* Check if the next cluster number is valid */ + if (nextcl == CLUST_FREE) { + /* Save a hint for next free cluster */ + if (boot->FSNext == 0) { + boot->FSNext = cl; + } + if (fat_is_cl_head(fat, cl)) { + fat_clear_cl_head(fat, cl); + } + boot->NumFree++; + } else if (nextcl == CLUST_BAD) { + if (fat_is_cl_head(fat, cl)) { + fat_clear_cl_head(fat, cl); + } + boot->NumBad++; + } else if (!valid_cl(fat, nextcl) && nextcl < CLUST_RSRVD) { + pwarn( + "Cluster %u continues with out of range " + "cluster number %u\n", + cl, + nextcl & boot->ClustMask + ); + if (ask(0, "Truncate")) { + ret |= fat_set_cl_next(fat, cl, CLUST_EOF); + ret |= FSFATMOD; + } + } else if (valid_cl(fat, nextcl)) { + if (fat_is_cl_head(fat, nextcl)) { + fat_clear_cl_head(fat, nextcl); + } else { + pwarn("Cluster %u crossed another chain at %u\n", cl, nextcl); + if (ask(0, "Truncate")) { + ret |= fat_set_cl_next(fat, cl, CLUST_EOF); + ret |= FSFATMOD; + } + } + } + } + + if (ret & FSFATAL) { + releasefat(fat); + free(fat); + *fp = NULL; + } else + *fp = fat; + return ret; } /* @@ -1018,13 +1015,13 @@ readfat(int fs, struct bootblock *boot, struct fat_descriptor **fp) const char * rsrvdcltype(cl_t cl) { - if (cl == CLUST_FREE) - return "free"; - if (cl < CLUST_BAD) - return "reserved"; - if (cl > CLUST_BAD) - return "as EOF"; - return "bad"; + if (cl == CLUST_FREE) + return "free"; + if (cl < CLUST_BAD) + return "reserved"; + if (cl > CLUST_BAD) + return "as EOF"; + return "bad"; } /* @@ -1033,84 +1030,84 @@ rsrvdcltype(cl_t cl) int checkchain(struct fat_descriptor *fat, cl_t head, size_t *chainsize) { - cl_t prev_cl, current_cl, next_cl; - const char *op; - - /* - * We expect that the caller to give us a real, unvisited 'head' - * cluster, and it must be a valid cluster. While scanning the - * FAT table, we already excluded all clusters that was claimed - * as a "next" cluster. Assert all the three conditions. - */ - assert(valid_cl(fat, head)); - assert(fat_is_cl_head(fat, head)); - - /* - * Immediately mark the 'head' cluster that we are about to visit. - */ - fat_clear_cl_head(fat, head); - - /* - * The allocation of a non-zero sized file or directory is - * represented as a singly linked list, and the tail node - * would be the EOF marker (>=CLUST_EOFS). - * - * With a valid head node at hand, we expect all subsequent - * cluster to be either a not yet seen and valid cluster (we - * would continue counting), or the EOF marker (we conclude - * the scan of this chain). - * - * For all other cases, the chain is invalid, and the only - * viable fix would be to truncate at the current node (mark - * it as EOF) when the next node violates that. - */ - *chainsize = 0; - prev_cl = current_cl = head; - for (next_cl = fat_get_cl_next(fat, current_cl); - valid_cl(fat, next_cl); - prev_cl = current_cl, current_cl = next_cl, next_cl = fat_get_cl_next(fat, current_cl)) - (*chainsize)++; - - /* A natural end */ - if (next_cl >= CLUST_EOFS) { - (*chainsize)++; - return FSOK; - } - - /* - * The chain ended with an out-of-range cluster number. - * - * If the current node is e.g. CLUST_FREE, CLUST_BAD, etc., - * it should not be present in a chain and we has to truncate - * at the previous node. - * - * If the current cluster points to an invalid cluster, the - * current cluster might have useful data and we truncate at - * the current cluster instead. - */ - if (next_cl == CLUST_FREE || next_cl >= CLUST_RSRVD) { - pwarn("Cluster chain starting at %u ends with cluster marked %s\n", - head, rsrvdcltype(next_cl)); - current_cl = prev_cl; - } else { - pwarn("Cluster chain starting at %u ends with cluster out of range (%u)\n", - head, - next_cl & boot_of_(fat)->ClustMask); - (*chainsize)++; - } - - if (*chainsize > 0) { - op = "Truncate"; - next_cl = CLUST_EOF; - } else { - op = "Clear"; - next_cl = CLUST_FREE; - } - if (ask(0, "%s", op)) { - return (fat_set_cl_next(fat, current_cl, next_cl) | FSFATMOD); - } else { - return (FSERROR); - } + cl_t prev_cl, current_cl, next_cl; + const char *op; + + /* + * We expect that the caller to give us a real, unvisited 'head' + * cluster, and it must be a valid cluster. While scanning the + * FAT table, we already excluded all clusters that was claimed + * as a "next" cluster. Assert all the three conditions. + */ + assert(valid_cl(fat, head)); + assert(fat_is_cl_head(fat, head)); + + /* + * Immediately mark the 'head' cluster that we are about to visit. + */ + fat_clear_cl_head(fat, head); + + /* + * The allocation of a non-zero sized file or directory is + * represented as a singly linked list, and the tail node + * would be the EOF marker (>=CLUST_EOFS). + * + * With a valid head node at hand, we expect all subsequent + * cluster to be either a not yet seen and valid cluster (we + * would continue counting), or the EOF marker (we conclude + * the scan of this chain). + * + * For all other cases, the chain is invalid, and the only + * viable fix would be to truncate at the current node (mark + * it as EOF) when the next node violates that. + */ + *chainsize = 0; + prev_cl = current_cl = head; + for (next_cl = fat_get_cl_next(fat, current_cl); valid_cl(fat, next_cl); + prev_cl = current_cl, current_cl = next_cl, next_cl = fat_get_cl_next(fat, current_cl)) + (*chainsize)++; + + /* A natural end */ + if (next_cl >= CLUST_EOFS) { + (*chainsize)++; + return FSOK; + } + + /* + * The chain ended with an out-of-range cluster number. + * + * If the current node is e.g. CLUST_FREE, CLUST_BAD, etc., + * it should not be present in a chain and we has to truncate + * at the previous node. + * + * If the current cluster points to an invalid cluster, the + * current cluster might have useful data and we truncate at + * the current cluster instead. + */ + if (next_cl == CLUST_FREE || next_cl >= CLUST_RSRVD) { + pwarn("Cluster chain starting at %u ends with cluster marked %s\n", head, rsrvdcltype(next_cl)); + current_cl = prev_cl; + } else { + pwarn( + "Cluster chain starting at %u ends with cluster out of range (%u)\n", + head, + next_cl & boot_of_(fat)->ClustMask + ); + (*chainsize)++; + } + + if (*chainsize > 0) { + op = "Truncate"; + next_cl = CLUST_EOF; + } else { + op = "Clear"; + next_cl = CLUST_FREE; + } + if (ask(0, "%s", op)) { + return (fat_set_cl_next(fat, current_cl, next_cl) | FSFATMOD); + } else { + return (FSERROR); + } } /* @@ -1119,18 +1116,17 @@ checkchain(struct fat_descriptor *fat, cl_t head, size_t *chainsize) void clearchain(struct fat_descriptor *fat, cl_t head) { - cl_t current_cl, next_cl; - struct bootblock *boot = boot_of_(fat); - - current_cl = head; + cl_t current_cl, next_cl; + struct bootblock *boot = boot_of_(fat); - while (valid_cl(fat, current_cl)) { - next_cl = fat_get_cl_next(fat, current_cl); - (void)fat_set_cl_next(fat, current_cl, CLUST_FREE); - boot->NumFree++; - current_cl = next_cl; - } + current_cl = head; + while (valid_cl(fat, current_cl)) { + next_cl = fat_get_cl_next(fat, current_cl); + (void)fat_set_cl_next(fat, current_cl, CLUST_FREE); + boot->NumFree++; + current_cl = next_cl; + } } /* @@ -1139,46 +1135,44 @@ clearchain(struct fat_descriptor *fat, cl_t head) static int copyfat(struct fat_descriptor *fat, int n) { - size_t rwsize, tailsize, blobs, i; - off_t dst_off, src_off; - struct bootblock *boot; - int ret, fd; - - ret = FSOK; - fd = fd_of_(fat); - boot = boot_of_(fat); - - blobs = howmany(fat->fatsize, fat32_cache_size); - tailsize = fat->fatsize % fat32_cache_size; - if (tailsize == 0) { - tailsize = fat32_cache_size; - } - rwsize = fat32_cache_size; - - src_off = fat->fat32_offset; - dst_off = boot->bpbResSectors + n * boot->FATsecs; - dst_off *= boot->bpbBytesPerSec; - - for (i = 0; i < blobs; - i++, src_off += fat32_cache_size, dst_off += fat32_cache_size) { - if (i == blobs - 1) { - rwsize = tailsize; - } - if ((lseek(fd, src_off, SEEK_SET) != src_off || - (size_t)read(fd, fat->fatbuf, rwsize) != rwsize) && - ret == FSOK) { - perr("Unable to read FAT0"); - ret = FSFATAL; - continue; - } - if ((lseek(fd, dst_off, SEEK_SET) != dst_off || - (size_t)write(fd, fat->fatbuf, rwsize) != rwsize) && - ret == FSOK) { - perr("Unable to write FAT %d", n); - ret = FSERROR; - } - } - return (ret); + size_t rwsize, tailsize, blobs, i; + off_t dst_off, src_off; + struct bootblock *boot; + int ret, fd; + + ret = FSOK; + fd = fd_of_(fat); + boot = boot_of_(fat); + + blobs = howmany(fat->fatsize, fat32_cache_size); + tailsize = fat->fatsize % fat32_cache_size; + if (tailsize == 0) { + tailsize = fat32_cache_size; + } + rwsize = fat32_cache_size; + + src_off = fat->fat32_offset; + dst_off = boot->bpbResSectors + n * boot->FATsecs; + dst_off *= boot->bpbBytesPerSec; + + for (i = 0; i < blobs; i++, src_off += fat32_cache_size, dst_off += fat32_cache_size) { + if (i == blobs - 1) { + rwsize = tailsize; + } + if ((lseek(fd, src_off, SEEK_SET) != src_off || (size_t)read(fd, fat->fatbuf, rwsize) != rwsize) + && ret == FSOK) { + perr("Unable to read FAT0"); + ret = FSFATAL; + continue; + } + if ((lseek(fd, dst_off, SEEK_SET) != dst_off + || (size_t)write(fd, fat->fatbuf, rwsize) != rwsize) + && ret == FSOK) { + perr("Unable to write FAT %d", n); + ret = FSERROR; + } + } + return (ret); } /* @@ -1187,55 +1181,56 @@ copyfat(struct fat_descriptor *fat, int n) int writefat(struct fat_descriptor *fat) { - u_int i; - size_t writesz; - off_t dst_base; - int ret = FSOK, fd; - struct bootblock *boot; - struct fat32_cache_entry *entry; - - boot = boot_of_(fat); - fd = fd_of_(fat); - - if (fat->use_cache) { - /* - * Attempt to flush all in-flight cache, and bail out - * if we encountered an error (but only emit error - * message once). Stop proceeding with copyfat() - * if any flush failed. - */ - TAILQ_FOREACH(entry, &fat->fat32_cache_head, entries) { - if (fat_flush_fat32_cache_entry(fat, entry) != FSOK) { - if (ret == FSOK) { - perr("Unable to write FAT"); - ret = FSFATAL; - } - } - } - if (ret != FSOK) - return (ret); - - /* Update backup copies of FAT, error is not fatal */ - for (i = 1; i < boot->bpbFATs; i++) { - if (copyfat(fat, i) != FSOK) - ret = FSERROR; - } - } else { - writesz = fat->fatsize; - - for (i = fat->is_mmapped ? 1 : 0; i < boot->bpbFATs; i++) { - dst_base = boot->bpbResSectors + i * boot->FATsecs; - dst_base *= boot->bpbBytesPerSec; - if ((lseek(fd, dst_base, SEEK_SET) != dst_base || - (size_t)write(fd, fat->fatbuf, writesz) != writesz) && - ret == FSOK) { - perr("Unable to write FAT %d", i); - ret = ((i == 0) ? FSFATAL : FSERROR); - } - } - } - - return ret; + u_int i; + size_t writesz; + off_t dst_base; + int ret = FSOK, fd; + struct bootblock *boot; + struct fat32_cache_entry *entry; + + boot = boot_of_(fat); + fd = fd_of_(fat); + + if (fat->use_cache) { + /* + * Attempt to flush all in-flight cache, and bail out + * if we encountered an error (but only emit error + * message once). Stop proceeding with copyfat() + * if any flush failed. + */ + TAILQ_FOREACH(entry, &fat->fat32_cache_head, entries) + { + if (fat_flush_fat32_cache_entry(fat, entry) != FSOK) { + if (ret == FSOK) { + perr("Unable to write FAT"); + ret = FSFATAL; + } + } + } + if (ret != FSOK) + return (ret); + + /* Update backup copies of FAT, error is not fatal */ + for (i = 1; i < boot->bpbFATs; i++) { + if (copyfat(fat, i) != FSOK) + ret = FSERROR; + } + } else { + writesz = fat->fatsize; + + for (i = fat->is_mmapped ? 1 : 0; i < boot->bpbFATs; i++) { + dst_base = boot->bpbResSectors + i * boot->FATsecs; + dst_base *= boot->bpbBytesPerSec; + if ((lseek(fd, dst_base, SEEK_SET) != dst_base + || (size_t)write(fd, fat->fatbuf, writesz) != writesz) + && ret == FSOK) { + perr("Unable to write FAT %d", i); + ret = ((i == 0) ? FSFATAL : FSERROR); + } + } + } + + return ret; } /* @@ -1244,83 +1239,82 @@ writefat(struct fat_descriptor *fat) int checklost(struct fat_descriptor *fat) { - cl_t head; - int mod = FSOK; - int dosfs, ret; - size_t chains, chainlength; - struct bootblock *boot; - - dosfs = fd_of_(fat); - boot = boot_of_(fat); - - /* - * At this point, we have already traversed all directories. - * All remaining chain heads in the bitmap are heads of lost - * chains. - */ - chains = fat_get_head_count(fat); - for (head = CLUST_FIRST; - chains > 0 && head < boot->NumClusters; - ) { - /* - * We expect the bitmap to be very sparse, so skip if - * the range is full of 0's - */ - if (head % LONG_BIT == 0 && - !fat_is_cl_head_in_range(fat, head)) { - head += LONG_BIT; - continue; - } - if (fat_is_cl_head(fat, head)) { - ret = checkchain(fat, head, &chainlength); - if (ret != FSERROR && chainlength > 0) { - pwarn("Lost cluster chain at cluster %u\n" - "%zd Cluster(s) lost\n", - head, chainlength); - mod |= ret = reconnect(fat, head, - chainlength); - } - if (mod & FSFATAL) - break; - if (ret == FSERROR && ask(0, "Clear")) { - clearchain(fat, head); - mod |= FSFATMOD; - } - chains--; - } - head++; - } - - finishlf(); - - if (boot->bpbFSInfo) { - ret = 0; - if (boot->FSFree != 0xffffffffU && - boot->FSFree != boot->NumFree) { - pwarn("Free space in FSInfo block (%u) not correct (%u)\n", - boot->FSFree, boot->NumFree); - if (ask(1, "Fix")) { - boot->FSFree = boot->NumFree; - ret = 1; - } - } - if (boot->FSNext != 0xffffffffU && - (boot->FSNext >= boot->NumClusters || - (boot->NumFree && fat_get_cl_next(fat, boot->FSNext) != CLUST_FREE))) { - pwarn("Next free cluster in FSInfo block (%u) %s\n", - boot->FSNext, - (boot->FSNext >= boot->NumClusters) ? "invalid" : "not free"); - if (ask(1, "Fix")) - for (head = CLUST_FIRST; head < boot->NumClusters; head++) - if (fat_get_cl_next(fat, head) == CLUST_FREE) { - boot->FSNext = head; - ret = 1; - break; - } - } - if (ret) - mod |= writefsinfo(dosfs, boot); - } - - return mod; + cl_t head; + int mod = FSOK; + int dosfs, ret; + size_t chains, chainlength; + struct bootblock *boot; + + dosfs = fd_of_(fat); + boot = boot_of_(fat); + + /* + * At this point, we have already traversed all directories. + * All remaining chain heads in the bitmap are heads of lost + * chains. + */ + chains = fat_get_head_count(fat); + for (head = CLUST_FIRST; chains > 0 && head < boot->NumClusters;) { + /* + * We expect the bitmap to be very sparse, so skip if + * the range is full of 0's + */ + if (head % LONG_BIT == 0 && !fat_is_cl_head_in_range(fat, head)) { + head += LONG_BIT; + continue; + } + if (fat_is_cl_head(fat, head)) { + ret = checkchain(fat, head, &chainlength); + if (ret != FSERROR && chainlength > 0) { + pwarn( + "Lost cluster chain at cluster %u\n" + "%zd Cluster(s) lost\n", + head, + chainlength + ); + mod |= ret = reconnect(fat, head, chainlength); + } + if (mod & FSFATAL) + break; + if (ret == FSERROR && ask(0, "Clear")) { + clearchain(fat, head); + mod |= FSFATMOD; + } + chains--; + } + head++; + } + + finishlf(); + + if (boot->bpbFSInfo) { + ret = 0; + if (boot->FSFree != 0xffffffffU && boot->FSFree != boot->NumFree) { + pwarn("Free space in FSInfo block (%u) not correct (%u)\n", boot->FSFree, boot->NumFree); + if (ask(1, "Fix")) { + boot->FSFree = boot->NumFree; + ret = 1; + } + } + if (boot->FSNext != 0xffffffffU + && (boot->FSNext >= boot->NumClusters + || (boot->NumFree && fat_get_cl_next(fat, boot->FSNext) != CLUST_FREE))) { + pwarn( + "Next free cluster in FSInfo block (%u) %s\n", + boot->FSNext, + (boot->FSNext >= boot->NumClusters) ? "invalid" : "not free" + ); + if (ask(1, "Fix")) + for (head = CLUST_FIRST; head < boot->NumClusters; head++) + if (fat_get_cl_next(fat, head) == CLUST_FREE) { + boot->FSNext = head; + ret = 1; + break; + } + } + if (ret) + mod |= writefsinfo(dosfs, boot); + } + + return mod; } diff --git a/cmd/extra/fsck.fat/freebsd-compat.h b/cmd/extra/fsck.fat/freebsd-compat.h @@ -53,7 +53,7 @@ /* From FreeBSD sys/sys/param.h */ #ifndef roundup2 -#define roundup2(x, y) (((x)+((y)-1))&(~((y)-1))) /* if y is powers of two */ +#define roundup2(x, y) (((x) + ((y) - 1)) & (~((y) - 1))) /* if y is powers of two */ #endif /*- @@ -95,37 +95,37 @@ static __inline void le16enc(void *pp, uint16_t u) { - uint8_t *p = (uint8_t *)pp; + uint8_t *p = (uint8_t *)pp; - p[0] = u & 0xff; - p[1] = (u >> 8) & 0xff; + p[0] = u & 0xff; + p[1] = (u >> 8) & 0xff; } static __inline void le32enc(void *pp, uint32_t u) { - uint8_t *p = (uint8_t *)pp; + uint8_t *p = (uint8_t *)pp; - p[0] = u & 0xff; - p[1] = (u >> 8) & 0xff; - p[2] = (u >> 16) & 0xff; - p[3] = (u >> 24) & 0xff; + p[0] = u & 0xff; + p[1] = (u >> 8) & 0xff; + p[2] = (u >> 16) & 0xff; + p[3] = (u >> 24) & 0xff; } static __inline uint16_t le16dec(const void *pp) { - uint8_t const *p = (uint8_t const *)pp; + uint8_t const *p = (uint8_t const *)pp; - return ((p[1] << 8) | p[0]); + return ((p[1] << 8) | p[0]); } static __inline uint32_t le32dec(const void *pp) { - uint8_t const *p = (uint8_t const *)pp; + uint8_t const *p = (uint8_t const *)pp; - return (((unsigned)p[3] << 24) | (p[2] << 16) | (p[1] << 8) | p[0]); + return (((unsigned)p[3] << 24) | (p[2] << 16) | (p[1] << 8) | p[0]); } #endif diff --git a/cmd/extra/fsck.fat/fsck.fat.c b/cmd/extra/fsck.fat/fsck.fat.c @@ -25,7 +25,6 @@ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - #include "freebsd-compat.h" #if defined(__RCSID) && !defined(lint) __RCSID("$NetBSD: main.c,v 1.10 1997/10/01 02:18:14 enami Exp $"); @@ -42,20 +41,19 @@ __RCSID("$NetBSD: main.c,v 1.10 1997/10/01 02:18:14 enami Exp $"); #include "ext.h" #include "util.h" -int alwaysno; /* assume "no" for all questions */ -int alwaysyes; /* assume "yes" for all questions */ -int preen; /* set when preening */ -int rdonly; /* device is opened read only (supersedes above) */ -int skipclean; /* skip clean file systems if preening */ -int allow_mmap; /* Allow the use of mmap(), if possible */ +int alwaysno; /* assume "no" for all questions */ +int alwaysyes; /* assume "yes" for all questions */ +int preen; /* set when preening */ +int rdonly; /* device is opened read only (supersedes above) */ +int skipclean; /* skip clean file systems if preening */ +int allow_mmap; /* Allow the use of mmap(), if possible */ static void usage(void) __dead2; static void usage(void) { - - eprintf("usage: %s [-fMnpy] filesystem ...\n", argv0); + eprintf("usage: %s [-fMnpy] filesystem ...\n", argv0); } // ?man fsck.fat: check and repair FAT12, FAT16, and FAT32 filesystems @@ -68,96 +66,97 @@ usage(void) int main(int argc, char **argv) { - int ret = 0, erg; - - skipclean = 1; - allow_mmap = 1; - ARGBEGIN { - case 'C': /* for fsck_ffs compatibility */ - break; - case 'f': - skipclean = 0; - break; - case 'F': - /* - * We can never run in the background. We must exit - * silently with a nonzero exit code so that fsck(8) - * can probe our support for -F. The exit code - * doesn't really matter, but we use an unusual one - * in case someone tries -F directly. The -F flag - * is intentionally left out of the usage message. - */ - exit(5); - case 'n': - alwaysno = 1; - alwaysyes = 0; - break; - case 'y': - alwaysyes = 1; - alwaysno = 0; - break; - - case 'p': - preen = 1; - break; - - case 'M': - allow_mmap = 0; - break; - - default: - usage(); - break; - } ARGEND - - if (!argc) - usage(); - - while (--argc >= 0) { - setcdevname(*argv, preen); - erg = checkfilesys(*argv++); - if (erg > ret) - ret = erg; - } - - if (fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>")) - ret = 8; - return ret; + int ret = 0, erg; + + skipclean = 1; + allow_mmap = 1; + ARGBEGIN + { + case 'C': /* for fsck_ffs compatibility */ + break; + case 'f': + skipclean = 0; + break; + case 'F': + /* + * We can never run in the background. We must exit + * silently with a nonzero exit code so that fsck(8) + * can probe our support for -F. The exit code + * doesn't really matter, but we use an unusual one + * in case someone tries -F directly. The -F flag + * is intentionally left out of the usage message. + */ + exit(5); + case 'n': + alwaysno = 1; + alwaysyes = 0; + break; + case 'y': + alwaysyes = 1; + alwaysno = 0; + break; + + case 'p': + preen = 1; + break; + + case 'M': + allow_mmap = 0; + break; + + default: + usage(); + break; + } + ARGEND + + if (!argc) + usage(); + + while (--argc >= 0) { + setcdevname(*argv, preen); + erg = checkfilesys(*argv++); + if (erg > ret) + ret = erg; + } + + if (fshut(stdin, "<stdin>") | fshut(stdout, "<stdout>")) + ret = 8; + return ret; } - /*VARARGS*/ int ask(int def, const char *fmt, ...) { - va_list ap; - - char prompt[256]; - int c; - - if (alwaysyes || alwaysno || rdonly) - def = (alwaysyes && !rdonly && !alwaysno); - - if (preen) { - if (def) - printf("FIXED\n"); - return def; - } - - va_start(ap, fmt); - vsnprintf(prompt, sizeof(prompt), fmt, ap); - va_end(ap); - if (alwaysyes || alwaysno || rdonly) { - printf("%s? %s\n", prompt, def ? "yes" : "no"); - return def; - } - do { - printf("%s? [yn] ", prompt); - fflush(stdout); - c = getchar(); - while (c != '\n' && getchar() != '\n') - if (feof(stdin)) - return 0; - } while (c != 'y' && c != 'Y' && c != 'n' && c != 'N'); - return c == 'y' || c == 'Y'; + va_list ap; + + char prompt[256]; + int c; + + if (alwaysyes || alwaysno || rdonly) + def = (alwaysyes && !rdonly && !alwaysno); + + if (preen) { + if (def) + printf("FIXED\n"); + return def; + } + + va_start(ap, fmt); + vsnprintf(prompt, sizeof(prompt), fmt, ap); + va_end(ap); + if (alwaysyes || alwaysno || rdonly) { + printf("%s? %s\n", prompt, def ? "yes" : "no"); + return def; + } + do { + printf("%s? [yn] ", prompt); + fflush(stdout); + c = getchar(); + while (c != '\n' && getchar() != '\n') + if (feof(stdin)) + return 0; + } while (c != 'y' && c != 'Y' && c != 'n' && c != 'N'); + return c == 'y' || c == 'Y'; } diff --git a/cmd/extra/fsck.fat/fsutil.c b/cmd/extra/fsck.fat/fsutil.c @@ -49,8 +49,8 @@ __RCSID("$NetBSD: fsutil.c,v 1.15 2006/06/05 16:52:05 christos Exp $"); #include "fsutil.h" #include "util.h" -static const char *dev = NULL; -static int preen = 0; +static const char *dev = NULL; +static int preen = 0; static void vmsg(int, const char *, va_list) __printflike(2, 0); @@ -75,120 +75,118 @@ static void vmsg(int, const char *, va_list) __printflike(2, 0); int getfsopt(struct fstab *fs, const char *option) { - int negative, found; - char *opt, *optbuf; - - if (option[0] == 'n' && option[1] == 'o') { - negative = 1; - option += 2; - } else - negative = 0; - optbuf = strdup(fs->fs_mntops); - found = 0; - for (opt = optbuf; (opt = strtok(opt, ",")) != NULL; opt = NULL) { - if (opt[0] == 'n' && opt[1] == 'o') { - if (!strcasecmp(opt + 2, option)) - found = negative; - } else if (!strcasecmp(opt, option)) - found = !negative; - } - free(optbuf); - return (found); + int negative, found; + char *opt, *optbuf; + + if (option[0] == 'n' && option[1] == 'o') { + negative = 1; + option += 2; + } else + negative = 0; + optbuf = strdup(fs->fs_mntops); + found = 0; + for (opt = optbuf; (opt = strtok(opt, ",")) != NULL; opt = NULL) { + if (opt[0] == 'n' && opt[1] == 'o') { + if (!strcasecmp(opt + 2, option)) + found = negative; + } else if (!strcasecmp(opt, option)) + found = !negative; + } + free(optbuf); + return (found); } #endif void setcdevname(const char *cd, int pr) { - dev = cd; - preen = pr; + dev = cd; + preen = pr; } const char * cdevname(void) { - return dev; + return dev; } static void vmsg(int fatal, const char *fmt, va_list ap) { - if (!fatal && preen) - (void) printf("%s: ", dev); + if (!fatal && preen) + (void)printf("%s: ", dev); - (void) vprintf(fmt, ap); + (void)vprintf(fmt, ap); - if (fatal && preen) - (void) printf("\n"); + if (fatal && preen) + (void)printf("\n"); - if (fatal && preen) { - (void) printf( - "%s: UNEXPECTED INCONSISTENCY; RUN %s MANUALLY.\n", - dev, argv0); - exit(8); - } + if (fatal && preen) { + (void)printf("%s: UNEXPECTED INCONSISTENCY; RUN %s MANUALLY.\n", dev, argv0); + exit(8); + } } /*VARARGS*/ void pfatal(const char *fmt, ...) { - va_list ap; + va_list ap; - va_start(ap, fmt); - vmsg(1, fmt, ap); - va_end(ap); + va_start(ap, fmt); + vmsg(1, fmt, ap); + va_end(ap); } /*VARARGS*/ void pwarn(const char *fmt, ...) { - va_list ap; + va_list ap; - va_start(ap, fmt); - vmsg(0, fmt, ap); - va_end(ap); + va_start(ap, fmt); + vmsg(0, fmt, ap); + va_end(ap); } void perr(const char *fmt, ...) { - va_list ap; + va_list ap; - va_start(ap, fmt); - vmsg(1, fmt, ap); - va_end(ap); + va_start(ap, fmt); + vmsg(1, fmt, ap); + va_end(ap); } void panic(const char *fmt, ...) { - va_list ap; + va_list ap; - va_start(ap, fmt); - vmsg(1, fmt, ap); - va_end(ap); - exit(8); + va_start(ap, fmt); + vmsg(1, fmt, ap); + va_end(ap); + exit(8); } const char * devcheck(const char *origname) { - struct stat stslash, stchar; - - if (stat("/", &stslash) < 0) { - perr("Can't stat `/'"); - return (origname); - } - if (stat(origname, &stchar) < 0) { - perr("Can't stat %s\n", origname); - return (origname); - } - if (!S_ISCHR(stchar.st_mode)) { - perr("%s is not a char device\n", origname); - } - return (origname); + struct stat stslash, stchar; + + if (stat("/", &stslash) < 0) { + perr("Can't stat `/'"); + return (origname); + } + if (stat(origname, &stchar) < 0) { + perr("Can't stat %s\n", origname); + return (origname); + } + if (!S_ISCHR(stchar.st_mode)) { + perr("%s is not a char device\n", origname); + } + return (origname); } #ifdef HAVE_GETMNTINFO @@ -198,74 +196,70 @@ devcheck(const char *origname) struct statfs * getmntpt(const char *name) { - struct stat devstat, mntdevstat; - char device[sizeof(_PATH_DEV) - 1 + MNAMELEN]; - char *dev_name; - struct statfs *mntbuf, *statfsp; - int i, mntsize, isdev; - if (stat(name, &devstat) != 0) - return (NULL); - if (S_ISCHR(devstat.st_mode) || S_ISBLK(devstat.st_mode)) - isdev = 1; - else - isdev = 0; - mntsize = getmntinfo(&mntbuf, MNT_NOWAIT); - for (i = 0; i < mntsize; i++) { - statfsp = &mntbuf[i]; - dev_name = statfsp->f_mntfromname; - if (*dev_name != '/') { - if (strlen(_PATH_DEV) + strlen(dev_name) + 1 > - sizeof(statfsp->f_mntfromname)) - continue; - strcpy(device, _PATH_DEV); - strcat(device, dev_name); - strcpy(statfsp->f_mntfromname, device); - } - if (isdev == 0) { - if (strcmp(name, statfsp->f_mntonname)) - continue; - return (statfsp); - } - if (stat(dev_name, &mntdevstat) == 0 && - mntdevstat.st_rdev == devstat.st_rdev) - return (statfsp); - } - statfsp = NULL; - return (statfsp); + struct stat devstat, mntdevstat; + char device[sizeof(_PATH_DEV) - 1 + MNAMELEN]; + char *dev_name; + struct statfs *mntbuf, *statfsp; + int i, mntsize, isdev; + if (stat(name, &devstat) != 0) + return (NULL); + if (S_ISCHR(devstat.st_mode) || S_ISBLK(devstat.st_mode)) + isdev = 1; + else + isdev = 0; + mntsize = getmntinfo(&mntbuf, MNT_NOWAIT); + for (i = 0; i < mntsize; i++) { + statfsp = &mntbuf[i]; + dev_name = statfsp->f_mntfromname; + if (*dev_name != '/') { + if (strlen(_PATH_DEV) + strlen(dev_name) + 1 > sizeof(statfsp->f_mntfromname)) + continue; + strcpy(device, _PATH_DEV); + strcat(device, dev_name); + strcpy(statfsp->f_mntfromname, device); + } + if (isdev == 0) { + if (strcmp(name, statfsp->f_mntonname)) + continue; + return (statfsp); + } + if (stat(dev_name, &mntdevstat) == 0 && mntdevstat.st_rdev == devstat.st_rdev) + return (statfsp); + } + statfsp = NULL; + return (statfsp); } #endif void * emalloc(size_t s) { - void *p; + void *p; - p = malloc(s); - if (p == NULL) - err(1, "malloc failed"); - return (p); + p = malloc(s); + if (p == NULL) + err(1, "malloc failed"); + return (p); } - void * erealloc(void *p, size_t s) { - void *q; + void *q; - q = realloc(p, s); - if (q == NULL) - err(1, "realloc failed"); - return (q); + q = realloc(p, s); + if (q == NULL) + err(1, "realloc failed"); + return (q); } - char * estrdup(const char *s) { - char *p; + char *p; - p = strdup(s); - if (p == NULL) - err(1, "strdup failed"); - return (p); + p = strdup(s); + if (p == NULL) + err(1, "strdup failed"); + return (p); } diff --git a/cmd/extra/fsck.fat/fsutil.h b/cmd/extra/fsck.fat/fsutil.h @@ -29,27 +29,30 @@ #include <sys/types.h> #ifdef __ANDROID__ -#define __dead2 __attribute__((__noreturn__)) +#define __dead2 __attribute__((__noreturn__)) #endif struct fstab; -int checkfstab(int, int (*)(struct fstab *), - int (*) (const char *, const char *, const char *, const char *, pid_t *)); -int getfsopt(struct fstab *, const char *); -void pfatal(const char *, ...) __printflike(1, 2); -void pwarn(const char *, ...) __printflike(1, 2); -void perr(const char *, ...) __printflike(1, 2); -void panic(const char *, ...) __dead2 __printflike(1, 2); +int checkfstab( + int, + int (*)(struct fstab *), + int (*)(const char *, const char *, const char *, const char *, pid_t *) +); +int getfsopt(struct fstab *, const char *); +void pfatal(const char *, ...) __printflike(1, 2); +void pwarn(const char *, ...) __printflike(1, 2); +void perr(const char *, ...) __printflike(1, 2); +void panic(const char *, ...) __dead2 __printflike(1, 2); const char *devcheck(const char *); const char *cdevname(void); -void setcdevname(const char *, int); -void *emalloc(size_t); -void *erealloc(void *, size_t); -char *estrdup(const char *); +void setcdevname(const char *, int); +void *emalloc(size_t); +void *erealloc(void *, size_t); +char *estrdup(const char *); -#define CHECK_PREEN 0x0001 -#define CHECK_VERBOSE 0x0002 -#define CHECK_DEBUG 0x0004 -#define CHECK_BACKGRD 0x0008 -#define DO_BACKGRD 0x0010 -#define CHECK_CLEAN 0x0020 +#define CHECK_PREEN 0x0001 +#define CHECK_VERBOSE 0x0002 +#define CHECK_DEBUG 0x0004 +#define CHECK_BACKGRD 0x0008 +#define DO_BACKGRD 0x0010 +#define CHECK_CLEAN 0x0020 diff --git a/cmd/extra/install.c b/cmd/extra/install.c @@ -173,7 +173,7 @@ static char ** options_first(int *argcp, char **argv) { int argc = *argcp; - char **out = ecalloc(argc + 2, sizeof(*out)); + char **out = ecalloc(argc + 2, sizeof(*out)); int n = 0, i, rest = 0; out[n++] = argv[0]; diff --git a/cmd/extra/kmap.c b/cmd/extra/kmap.c @@ -14,8 +14,11 @@ static void usage(void) { - eprintf("usage: %s [-d dir] [-l [layout]] [-n] [-x [-o options]]\n" - " [layout[,layout] [variant[,variant]]]\n", argv0); + eprintf( + "usage: %s [-d dir] [-l [layout]] [-n] [-x [-o options]]\n" + " [layout[,layout] [variant[,variant]]]\n", + argv0 + ); } static int @@ -28,9 +31,9 @@ by_name(const void *a, const void *b) static int list(const char *dir, const char *layout) { - char path[PATH_MAX], **names = NULL; - size_t n = 0, i; - DIR *d; + char path[PATH_MAX], **names = NULL; + size_t n = 0, i; + DIR *d; struct dirent *e; snprintf(path, sizeof(path), "%s%s%s", dir, layout ? "/" : "", layout ? layout : ""); @@ -43,7 +46,7 @@ list(const char *dir, const char *layout) continue; if (layout && (l < 6 || strcmp(e->d_name + l - 5, ".kmap"))) continue; - names = ereallocarray(names, n + 1, sizeof(*names)); + names = ereallocarray(names, n + 1, sizeof(*names)); names[n++] = layout ? estrndup(e->d_name, l - 5) : estrdup(e->d_name); } closedir(d); @@ -66,9 +69,9 @@ list(const char *dir, const char *layout) static int configured(char *layout, size_t lsz, char *variant, size_t vsz) { - char line[256], *w[3]; + char line[256], *w[3]; FILE *fp = fopen(ARUU_PATH_ETC "/kmap", "r"); - int n = 0; + int n = 0; if (!fp) return -1; @@ -111,10 +114,10 @@ int main(int argc, char *argv[]) { const char *dir = KMAP_DIR, *options = NULL; - char path[PATH_MAX], layouts[256], variants[256]; + char path[PATH_MAX], layouts[256], variants[256]; struct kmap pc, opts[8]; - int nopts = 0; - int lflag = 0, xflag = 0, nflag = 0, rc = 0, n, i; + int nopts = 0; + int lflag = 0, xflag = 0, nflag = 0, rc = 0, n, i; struct kmap maps[4]; ARGBEGIN @@ -159,7 +162,6 @@ main(int argc, char *argv[]) variants[0] = '\0'; } - // the console has one layout: the first of them memset(maps, 0, sizeof(maps)); memset(&pc, 0, sizeof(pc)); @@ -194,8 +196,8 @@ main(int argc, char *argv[]) } for (const char *o = options; o && *o && nopts < (int)LEN(opts);) { const char *end = strchr(o, ','), *colon; - size_t len = end ? (size_t)(end - o) : strlen(o); - char one[128]; + size_t len = end ? (size_t)(end - o) : strlen(o); + char one[128]; snprintf(one, sizeof(one), "%.*s", (int)(len < sizeof(one) ? len : sizeof(one) - 1), o); o = end ? end + 1 : o + len; @@ -206,7 +208,9 @@ main(int argc, char *argv[]) rc = 1; goto done; } - snprintf(path, sizeof(path), "%s/options/%.*s/%s.kmap", dir, (int)(colon - one), one, colon + 1); + snprintf( + path, sizeof(path), "%s/options/%.*s/%s.kmap", dir, (int)(colon - one), one, colon + 1 + ); if (access(path, F_OK) != 0) { weprintf("%s: kmap has no such option\n", one); rc = 1; @@ -218,8 +222,7 @@ main(int argc, char *argv[]) } } rc = kmap_write_xkb(stdout, dir, &pc, maps, n, opts, nopts); - } - else if (!nflag) + } else if (!nflag) rc = kmap_load_console(&maps[0]); done: for (i = 0; i < (int)LEN(maps); i++) diff --git a/cmd/extra/mkfs.ext4.c b/cmd/extra/mkfs.ext4.c @@ -40,15 +40,21 @@ #include <unistd.h> enum { - BLOCK = MKFS_EXT4_BLOCK_SIZE, INODE = 256, DESC = 32, JOURNAL = 1024, - GROUP_BLOCKS = BLOCK * 8, ROOT = 2, LOG_INO = 8, LOST = 11 + BLOCK = MKFS_EXT4_BLOCK_SIZE, + INODE = 256, + DESC = 32, + JOURNAL = 1024, + GROUP_BLOCKS = BLOCK * 8, + ROOT = 2, + LOG_INO = 8, + LOST = 11 }; struct Volume { const char *path; - int fd; - uint32_t blocks, groups, gdt_blocks, inodes_per_group; - uint32_t table_blocks, now; + int fd; + uint32_t blocks, groups, gdt_blocks, inodes_per_group; + uint32_t table_blocks, now; }; static void @@ -83,8 +89,8 @@ be32(unsigned char *p, uint32_t v) static void volume_uuid(unsigned char uuid[16], const char *s) { - int fd, hi, lo; - size_t i = 0; + int fd, hi, lo; + size_t i = 0; ssize_t n; if (s) { @@ -127,7 +133,7 @@ static int has_super(uint32_t group) { const unsigned bases[] = {3, 5, 7}; - size_t i; + size_t i; if (group <= 1) return 1; @@ -145,11 +151,11 @@ has_super(uint32_t group) static void open_volume(struct Volume *v) { - struct stat st; - struct flock lock = {.l_type = F_WRLCK, .l_whence = SEEK_SET}; - int flags = O_RDWR | O_NONBLOCK | O_NOCTTY; - uint64_t bytes; - time_t now; + struct stat st; + struct flock lock = {.l_type = F_WRLCK, .l_whence = SEEK_SET}; + int flags = O_RDWR | O_NONBLOCK | O_NOCTTY; + uint64_t bytes; + time_t now; #if defined(__linux__) && !defined(ARUU_FORCE_POSIX) flags |= O_EXCL; /* kernel claim on a block device */ @@ -178,20 +184,20 @@ open_volume(struct Volume *v) } else { eprintf("%s: unsupported target type\n", v->path); } - if (bytes % BLOCK || !mkfs_ext4_size_ok(bytes) || - (off_t)bytes <= 0 || (uint64_t)(off_t)bytes != bytes) + if (bytes % BLOCK || !mkfs_ext4_size_ok(bytes) || (off_t)bytes <= 0 + || (uint64_t)(off_t)bytes != bytes) eprintf("%s: expected a 4 KiB aligned size from 8 MiB to below 16 TiB\n", v->path); - v->blocks = bytes / BLOCK; - v->groups = 1 + (v->blocks - 1) / GROUP_BLOCKS; - v->gdt_blocks = 1 + (v->groups - 1) / (BLOCK / DESC); + v->blocks = bytes / BLOCK; + v->groups = 1 + (v->blocks - 1) / GROUP_BLOCKS; + v->gdt_blocks = 1 + (v->groups - 1) / (BLOCK / DESC); v->inodes_per_group = (v->blocks / 4 + v->groups - 1) / v->groups; - v->table_blocks = (v->inodes_per_group + BLOCK / INODE - 1) / (BLOCK / INODE); + v->table_blocks = (v->inodes_per_group + BLOCK / INODE - 1) / (BLOCK / INODE); v->inodes_per_group = v->table_blocks * (BLOCK / INODE); /* As in lwext4, omit a partial last group too small for its own metadata. */ - if (v->groups > 1 && v->blocks % GROUP_BLOCKS && - v->blocks % GROUP_BLOCKS < 2 + v->table_blocks + - (has_super(v->groups - 1) ? 1 + v->gdt_blocks : 0)) { + if (v->groups > 1 && v->blocks % GROUP_BLOCKS + && v->blocks % GROUP_BLOCKS + < 2 + v->table_blocks + (has_super(v->groups - 1) ? 1 + v->gdt_blocks : 0)) { v->blocks -= v->blocks % GROUP_BLOCKS; v->groups--; v->gdt_blocks = 1 + (v->groups - 1) / (BLOCK / DESC); @@ -205,8 +211,8 @@ open_volume(struct Volume *v) static void write_blocks(const struct Volume *v, uint32_t block, const unsigned char *buf, unsigned count) { - off_t off = (off_t)((uint64_t)block * BLOCK); - size_t done = 0, len = (size_t)count * BLOCK; + off_t off = (off_t)((uint64_t)block * BLOCK); + size_t done = 0, len = (size_t)count * BLOCK; ssize_t n; if (block >= v->blocks || count > v->blocks - block) @@ -251,12 +257,13 @@ bitmap(const struct Volume *v, uint32_t block, uint32_t used, uint32_t count) } static void -inode(unsigned char *p, uint32_t now, unsigned mode, unsigned links, - uint32_t bytes, uint32_t blocks) +inode( + unsigned char *p, uint32_t now, unsigned mode, unsigned links, uint32_t bytes, uint32_t blocks +) { le16(p, mode); le32(p + 4, bytes); - le32(p + 8, now); /* atime, ctime, mtime */ + le32(p + 8, now); /* atime, ctime, mtime */ le32(p + 12, now); le32(p + 16, now); le16(p + 26, links); @@ -284,9 +291,9 @@ dirent(unsigned char *p, uint32_t ino, unsigned len, const char *name) static void write_files(const struct Volume *v, uint32_t root, unsigned char *sb) { - unsigned char table[BLOCK] = {0}, buf[BLOCK] = {0}; - unsigned char *log = table + (LOG_INO - 1) * INODE; - uint32_t first = root + 3, i; + unsigned char table[BLOCK] = {0}, buf[BLOCK] = {0}; + unsigned char *log = table + (LOG_INO - 1) * INODE; + uint32_t first = root + 3, i; inode(table + (ROOT - 1) * INODE, v->now, 0040755, 3, BLOCK, 1); le32(table + (ROOT - 1) * INODE + 40, root); @@ -335,11 +342,11 @@ static void format(const struct Volume *v, const char *label, const unsigned char uuid[16]) { static const unsigned char zero[64 * 1024]; - unsigned char sb[1024] = {0}, first[BLOCK], buf[BLOCK] = {0}; - unsigned char *gdt = ecalloc(v->gdt_blocks, BLOCK); - uint32_t g, i, free_blocks = 0; - size_t done = 0; - ssize_t n; + unsigned char sb[1024] = {0}, first[BLOCK], buf[BLOCK] = {0}; + unsigned char *gdt = ecalloc(v->gdt_blocks, BLOCK); + uint32_t g, i, free_blocks = 0; + size_t done = 0; + ssize_t n; /* Read the whole block for devices with 4 KiB logical sectors. Only the * superblock at offset 1024 is invalidated and later published. */ @@ -357,13 +364,13 @@ format(const struct Volume *v, const char *label, const unsigned char uuid[16]) write_block(v, 0, first); sync_volume(v); for (g = 0; g < v->groups; g++) { - uint32_t start = g * GROUP_BLOCKS; - uint32_t count = MIN(v->blocks - start, GROUP_BLOCKS); - uint32_t bitmap_block = start + (has_super(g) ? 1 + v->gdt_blocks : 0); - uint32_t table = bitmap_block + 2; - uint32_t used = table - start + v->table_blocks + (g == 0 ? JOURNAL + 3 : 0); - uint32_t inodes = g == 0 ? LOST : 0; - unsigned char *d = gdt + g * DESC; + uint32_t start = g * GROUP_BLOCKS; + uint32_t count = MIN(v->blocks - start, GROUP_BLOCKS); + uint32_t bitmap_block = start + (has_super(g) ? 1 + v->gdt_blocks : 0); + uint32_t table = bitmap_block + 2; + uint32_t used = table - start + v->table_blocks + (g == 0 ? JOURNAL + 3 : 0); + uint32_t inodes = g == 0 ? LOST : 0; + unsigned char *d = gdt + g * DESC; le32(d, bitmap_block); le32(d + 4, bitmap_block + 1); @@ -406,9 +413,9 @@ format(const struct Volume *v, const char *label, const unsigned char uuid[16]) memcpy(sb + 104, uuid, 16); memcpy(sb + 120, label, strlen(label)); le32(sb + 224, LOG_INO); - sb[253] = 1; /* journal backup type */ + sb[253] = 1; /* journal backup type */ le32(sb + 264, v->now); /* creation time */ - le16(sb + 348, 32); /* required and desired extra inode fields */ + le16(sb + 348, 32); /* required and desired extra inode fields */ le16(sb + 350, 32); write_files(v, 3 + v->gdt_blocks + v->table_blocks, sb); @@ -436,20 +443,22 @@ format(const struct Volume *v, const char *label, const unsigned char uuid[16]) int main(int argc, char **argv) { - struct Volume v = {0}; - const char *label = "", *id = NULL; + struct Volume v = {0}; + const char *label = "", *id = NULL; unsigned char uuid[16]; - ARGBEGIN { - case 'L': - label = EARGF(usage()); - break; - case 'U': - id = EARGF(usage()); - break; - default: - usage(); - } ARGEND + ARGBEGIN + { + case 'L': + label = EARGF(usage()); + break; + case 'U': + id = EARGF(usage()); + break; + default: + usage(); + } + ARGEND if (argc != 1) usage(); if (strlen(label) > 16) diff --git a/cmd/extra/mkfs.fat.c b/cmd/extra/mkfs.fat.c @@ -63,175 +63,159 @@ #define powerof2(x) ((x) && !((x) & ((x) - 1))) #endif -#define MINIMUM(a, b) (((a) < (b)) ? (a) : (b)) -#define MAXIMUM(a, b) (((a) > (b)) ? (a) : (b)) - -#define MAXU16 0xffff /* maximum unsigned 16-bit quantity */ -#define BPN 4 /* bits per nibble */ -#define NPB 2 /* nibbles per byte */ - -#define DOSMAGIC 0xaa55 /* DOS magic number */ -#define MINBPS 512 /* minimum bytes per sector */ -#define MAXSPC 128 /* maximum sectors per cluster */ -#define MAXNFT 16 /* maximum number of FATs */ -#define DEFBLK 4096 /* default block size */ -#define DEFBLK16 2048 /* default block size FAT16 */ -#define DEFRDE 512 /* default root directory entries */ -#define RESFTE 2 /* reserved FAT entries */ -#define MINCLS12 1 /* minimum FAT12 clusters */ -#define MINCLS16 0xff5 /* minimum FAT16 clusters */ -#define MINCLS32 0xfff5 /* minimum FAT32 clusters */ -#define MAXCLS12 0xff4 /* maximum FAT12 clusters */ -#define MAXCLS16 0xfff4 /* maximum FAT16 clusters */ -#define MAXCLS32 0xffffff4 /* maximum FAT32 clusters */ - -#define mincls(fat) ((fat) == 12 ? MINCLS12 : \ - (fat) == 16 ? MINCLS16 : \ - MINCLS32) - -#define maxcls(fat) ((fat) == 12 ? MAXCLS12 : \ - (fat) == 16 ? MAXCLS16 : \ - MAXCLS32) - -#define mk1(p, x) \ - (p) = (uint8_t)(x) - -#define mk2(p, x) \ - (p)[0] = (uint8_t)(x), \ - (p)[1] = (uint8_t)((x) >> 010) - -#define mk4(p, x) \ - (p)[0] = (uint8_t)(x), \ - (p)[1] = (uint8_t)((x) >> 010), \ - (p)[2] = (uint8_t)((x) >> 020), \ - (p)[3] = (uint8_t)((x) >> 030) - -#define argto1(arg, lo, msg) argtou(arg, lo, 0xff, msg) -#define argto2(arg, lo, msg) argtou(arg, lo, 0xffff, msg) -#define argto4(arg, lo, msg) argtou(arg, lo, 0xffffffff, msg) -#define argtox(arg, lo, msg) argtou(arg, lo, UINT_MAX, msg) +#define MINIMUM(a, b) (((a) < (b)) ? (a) : (b)) +#define MAXIMUM(a, b) (((a) > (b)) ? (a) : (b)) + +#define MAXU16 0xffff /* maximum unsigned 16-bit quantity */ +#define BPN 4 /* bits per nibble */ +#define NPB 2 /* nibbles per byte */ + +#define DOSMAGIC 0xaa55 /* DOS magic number */ +#define MINBPS 512 /* minimum bytes per sector */ +#define MAXSPC 128 /* maximum sectors per cluster */ +#define MAXNFT 16 /* maximum number of FATs */ +#define DEFBLK 4096 /* default block size */ +#define DEFBLK16 2048 /* default block size FAT16 */ +#define DEFRDE 512 /* default root directory entries */ +#define RESFTE 2 /* reserved FAT entries */ +#define MINCLS12 1 /* minimum FAT12 clusters */ +#define MINCLS16 0xff5 /* minimum FAT16 clusters */ +#define MINCLS32 0xfff5 /* minimum FAT32 clusters */ +#define MAXCLS12 0xff4 /* maximum FAT12 clusters */ +#define MAXCLS16 0xfff4 /* maximum FAT16 clusters */ +#define MAXCLS32 0xffffff4 /* maximum FAT32 clusters */ + +#define mincls(fat) ((fat) == 12 ? MINCLS12 : (fat) == 16 ? MINCLS16 : MINCLS32) + +#define maxcls(fat) ((fat) == 12 ? MAXCLS12 : (fat) == 16 ? MAXCLS16 : MAXCLS32) + +#define mk1(p, x) (p) = (uint8_t)(x) + +#define mk2(p, x) (p)[0] = (uint8_t)(x), (p)[1] = (uint8_t)((x) >> 010) + +#define mk4(p, x) \ + (p)[0] = (uint8_t)(x), (p)[1] = (uint8_t)((x) >> 010), (p)[2] = (uint8_t)((x) >> 020), \ + (p)[3] = (uint8_t)((x) >> 030) + +#define argto1(arg, lo, msg) argtou(arg, lo, 0xff, msg) +#define argto2(arg, lo, msg) argtou(arg, lo, 0xffff, msg) +#define argto4(arg, lo, msg) argtou(arg, lo, 0xffffffff, msg) +#define argtox(arg, lo, msg) argtou(arg, lo, UINT_MAX, msg) struct bs { - uint8_t jmp[3]; /* bootstrap entry point */ - uint8_t oem[8]; /* OEM name and version */ + uint8_t jmp[3]; /* bootstrap entry point */ + uint8_t oem[8]; /* OEM name and version */ }; struct bsbpb { - uint8_t bps[2]; /* bytes per sector */ - uint8_t spc; /* sectors per cluster */ - uint8_t res[2]; /* reserved sectors */ - uint8_t nft; /* number of FATs */ - uint8_t rde[2]; /* root directory entries */ - uint8_t sec[2]; /* total sectors */ - uint8_t mid; /* media descriptor */ - uint8_t spf[2]; /* sectors per FAT */ - uint8_t spt[2]; /* sectors per track */ - uint8_t hds[2]; /* drive heads */ - uint8_t hid[4]; /* hidden sectors */ - uint8_t bsec[4]; /* big total sectors */ + uint8_t bps[2]; /* bytes per sector */ + uint8_t spc; /* sectors per cluster */ + uint8_t res[2]; /* reserved sectors */ + uint8_t nft; /* number of FATs */ + uint8_t rde[2]; /* root directory entries */ + uint8_t sec[2]; /* total sectors */ + uint8_t mid; /* media descriptor */ + uint8_t spf[2]; /* sectors per FAT */ + uint8_t spt[2]; /* sectors per track */ + uint8_t hds[2]; /* drive heads */ + uint8_t hid[4]; /* hidden sectors */ + uint8_t bsec[4]; /* big total sectors */ }; struct bsxbpb { - uint8_t bspf[4]; /* big sectors per FAT */ - uint8_t xflg[2]; /* FAT control flags */ - uint8_t vers[2]; /* file system version */ - uint8_t rdcl[4]; /* root directory start cluster */ - uint8_t infs[2]; /* file system info sector */ - uint8_t bkbs[2]; /* backup boot sector */ - uint8_t rsvd[12]; /* reserved */ + uint8_t bspf[4]; /* big sectors per FAT */ + uint8_t xflg[2]; /* FAT control flags */ + uint8_t vers[2]; /* file system version */ + uint8_t rdcl[4]; /* root directory start cluster */ + uint8_t infs[2]; /* file system info sector */ + uint8_t bkbs[2]; /* backup boot sector */ + uint8_t rsvd[12]; /* reserved */ }; struct bsx { - uint8_t drv; /* drive number */ - uint8_t rsvd; /* reserved */ - uint8_t sig; /* extended boot signature */ - uint8_t volid[4]; /* volume ID number */ - uint8_t label[11]; /* volume label */ - uint8_t type[8]; /* file system type */ + uint8_t drv; /* drive number */ + uint8_t rsvd; /* reserved */ + uint8_t sig; /* extended boot signature */ + uint8_t volid[4]; /* volume ID number */ + uint8_t label[11]; /* volume label */ + uint8_t type[8]; /* file system type */ }; struct de { - uint8_t namext[11]; /* name and extension */ - uint8_t attr; /* attributes */ - uint8_t rsvd[10]; /* reserved */ - uint8_t time[2]; /* creation time */ - uint8_t date[2]; /* creation date */ - uint8_t clus[2]; /* starting cluster */ - uint8_t size[4]; /* size */ + uint8_t namext[11]; /* name and extension */ + uint8_t attr; /* attributes */ + uint8_t rsvd[10]; /* reserved */ + uint8_t time[2]; /* creation time */ + uint8_t date[2]; /* creation date */ + uint8_t clus[2]; /* starting cluster */ + uint8_t size[4]; /* size */ }; struct bpb { - unsigned int bps; /* bytes per sector */ - unsigned int spc; /* sectors per cluster */ - unsigned int res; /* reserved sectors */ - unsigned int nft; /* number of FATs */ - unsigned int rde; /* root directory entries */ - unsigned int sec; /* total sectors */ - unsigned int mid; /* media descriptor */ - unsigned int spf; /* sectors per FAT */ - unsigned int spt; /* sectors per track */ - unsigned int hds; /* drive heads */ - unsigned int hid; /* hidden sectors */ - unsigned int bsec; /* big total sectors */ - unsigned int bspf; /* big sectors per FAT */ - unsigned int rdcl; /* root directory start cluster */ - unsigned int infs; /* file system info sector */ - unsigned int bkbs; /* backup boot sector */ + unsigned int bps; /* bytes per sector */ + unsigned int spc; /* sectors per cluster */ + unsigned int res; /* reserved sectors */ + unsigned int nft; /* number of FATs */ + unsigned int rde; /* root directory entries */ + unsigned int sec; /* total sectors */ + unsigned int mid; /* media descriptor */ + unsigned int spf; /* sectors per FAT */ + unsigned int spt; /* sectors per track */ + unsigned int hds; /* drive heads */ + unsigned int hid; /* hidden sectors */ + unsigned int bsec; /* big total sectors */ + unsigned int bspf; /* big sectors per FAT */ + unsigned int rdcl; /* root directory start cluster */ + unsigned int infs; /* file system info sector */ + unsigned int bkbs; /* backup boot sector */ }; static struct { - const char *name; - struct bpb bpb; + const char *name; + struct bpb bpb; } stdfmt[] = { - {"160", {512, 1, 1, 2, 64, 320, 0xfe, 1, 8, 1, 0, 0, 0, 0, 0, 0}}, - {"180", {512, 1, 1, 2, 64, 360, 0xfc, 2, 9, 1, 0, 0, 0, 0, 0, 0}}, - {"320", {512, 2, 1, 2, 112, 640, 0xff, 1, 8, 2, 0, 0, 0, 0, 0, 0}}, - {"360", {512, 2, 1, 2, 112, 720, 0xfd, 2, 9, 2, 0, 0, 0, 0, 0, 0}}, - {"720", {512, 2, 1, 2, 112, 1440, 0xf9, 3, 9, 2, 0, 0, 0, 0, 0, 0}}, + {"160", {512, 1, 1, 2, 64, 320, 0xfe, 1, 8, 1, 0, 0, 0, 0, 0, 0}}, + {"180", {512, 1, 1, 2, 64, 360, 0xfc, 2, 9, 1, 0, 0, 0, 0, 0, 0}}, + {"320", {512, 2, 1, 2, 112, 640, 0xff, 1, 8, 2, 0, 0, 0, 0, 0, 0}}, + {"360", {512, 2, 1, 2, 112, 720, 0xfd, 2, 9, 2, 0, 0, 0, 0, 0, 0}}, + {"720", {512, 2, 1, 2, 112, 1440, 0xf9, 3, 9, 2, 0, 0, 0, 0, 0, 0}}, {"1200", {512, 1, 1, 2, 224, 2400, 0xf9, 7, 15, 2, 0, 0, 0, 0, 0, 0}}, {"1440", {512, 1, 1, 2, 224, 2880, 0xf0, 9, 18, 2, 0, 0, 0, 0, 0, 0}}, {"2880", {512, 2, 1, 2, 240, 5760, 0xf0, 9, 36, 2, 0, 0, 0, 0, 0, 0}} }; -static uint8_t bootcode[] = { - 0xfa, /* cli */ - 0x31, 0xc0, /* xor ax,ax */ - 0x8e, 0xd0, /* mov ss,ax */ - 0xbc, 0x00, 0x7c, /* mov sp,7c00h */ - 0xfb, /* sti */ - 0x8e, 0xd8, /* mov ds,ax */ - 0xe8, 0x00, 0x00, /* call $ + 3 */ - 0x5e, /* pop si */ - 0x83, 0xc6, 0x19, /* add si,+19h */ - 0xbb, 0x07, 0x00, /* mov bx,0007h */ - 0xfc, /* cld */ - 0xac, /* lodsb */ - 0x84, 0xc0, /* test al,al */ - 0x74, 0x06, /* jz $ + 8 */ - 0xb4, 0x0e, /* mov ah,0eh */ - 0xcd, 0x10, /* int 10h */ - 0xeb, 0xf5, /* jmp $ - 9 */ - 0x30, 0xe4, /* xor ah,ah */ - 0xcd, 0x16, /* int 16h */ - 0xcd, 0x19, /* int 19h */ - 0x0d, 0x0a, - 'N', 'o', 'n', '-', 's', 'y', 's', 't', - 'e', 'm', ' ', 'd', 'i', 's', 'k', - 0x0d, 0x0a, - 'P', 'r', 'e', 's', 's', ' ', 'a', 'n', - 'y', ' ', 'k', 'e', 'y', ' ', 't', 'o', - ' ', 'r', 'e', 'b', 'o', 'o', 't', - 0x0d, 0x0a, - 0 -}; - -static void gettarget(int, const char *, int, struct bpb *); -static void getstdfmt(const char *, struct bpb *); -static void print_bpb(struct bpb *); +static uint8_t bootcode[] = {0xfa, /* cli */ + 0x31, 0xc0, /* xor ax,ax */ + 0x8e, 0xd0, /* mov ss,ax */ + 0xbc, 0x00, 0x7c, /* mov sp,7c00h */ + 0xfb, /* sti */ + 0x8e, 0xd8, /* mov ds,ax */ + 0xe8, 0x00, 0x00, /* call $ + 3 */ + 0x5e, /* pop si */ + 0x83, 0xc6, 0x19, /* add si,+19h */ + 0xbb, 0x07, 0x00, /* mov bx,0007h */ + 0xfc, /* cld */ + 0xac, /* lodsb */ + 0x84, 0xc0, /* test al,al */ + 0x74, 0x06, /* jz $ + 8 */ + 0xb4, 0x0e, /* mov ah,0eh */ + 0xcd, 0x10, /* int 10h */ + 0xeb, 0xf5, /* jmp $ - 9 */ + 0x30, 0xe4, /* xor ah,ah */ + 0xcd, 0x16, /* int 16h */ + 0xcd, 0x19, /* int 19h */ + 0x0d, 0x0a, 'N', 'o', 'n', '-', 's', 'y', 's', 't', 'e', 'm', + ' ', 'd', 'i', 's', 'k', 0x0d, 0x0a, 'P', 'r', 'e', 's', 's', + ' ', 'a', 'n', 'y', ' ', 'k', 'e', 'y', ' ', 't', 'o', ' ', + 'r', 'e', 'b', 'o', 'o', 't', 0x0d, 0x0a, 0}; + +static void gettarget(int, const char *, int, struct bpb *); +static void getstdfmt(const char *, struct bpb *); +static void print_bpb(struct bpb *); static unsigned int argtou(const char *, unsigned int, unsigned int, const char *); -static int oklabel(const char *); -static void mklabel(uint8_t *, const char *); -static void setstr(uint8_t *, const char *, size_t); +static int oklabel(const char *); +static void mklabel(uint8_t *, const char *); +static void setstr(uint8_t *, const char *, size_t); static void __attribute__((noreturn)) usage(void); /* @@ -240,558 +224,556 @@ static void __attribute__((noreturn)) usage(void); int main(int argc, char *argv[]) { - const char *opt_B = NULL, *opt_L = NULL, *opt_O = NULL, *opt_f = NULL; - unsigned int opt_F = 0, opt_I = 0, opt_S = 0, opt_a = 0, opt_b = 0, opt_c = 0, opt_e = 0; - unsigned int opt_h = 0, opt_i = 0, opt_k = 0, opt_m = 0, opt_n = 0, opt_o = 0, opt_r = 0; - unsigned int opt_s = 0, opt_u = 0; - int opt_N = 0, Iflag = 0, mflag = 0, oflag = 0; - char buf[PATH_MAX]; - struct stat sb; - struct timeval tv; - struct bpb bpb; - struct tm *tm; - struct bs *bs; - struct bsbpb *bsbpb; - struct bsxbpb *bsxbpb; - struct bsx *bsx; - struct de *de; - uint8_t *img; - const char *bname, *fname, *arg; - ssize_t n; - time_t now; - unsigned int fat, bss, rds, cls, dir, lsn, x, x1, x2; - uint64_t capacity, bits; - int fd, fd1, flags; + const char *opt_B = NULL, *opt_L = NULL, *opt_O = NULL, *opt_f = NULL; + unsigned int opt_F = 0, opt_I = 0, opt_S = 0, opt_a = 0, opt_b = 0, opt_c = 0, opt_e = 0; + unsigned int opt_h = 0, opt_i = 0, opt_k = 0, opt_m = 0, opt_n = 0, opt_o = 0, opt_r = 0; + unsigned int opt_s = 0, opt_u = 0; + int opt_N = 0, Iflag = 0, mflag = 0, oflag = 0; + char buf[PATH_MAX]; + struct stat sb; + struct timeval tv; + struct bpb bpb; + struct tm *tm; + struct bs *bs; + struct bsbpb *bsbpb; + struct bsxbpb *bsxbpb; + struct bsx *bsx; + struct de *de; + uint8_t *img; + const char *bname, *fname, *arg; + ssize_t n; + time_t now; + unsigned int fat, bss, rds, cls, dir, lsn, x, x1, x2; + uint64_t capacity, bits; + int fd, fd1, flags; #if defined(__OpenBSD__) && !defined(ARUU_FORCE_POSIX) - if (pledge("stdio rpath wpath disklabel", NULL) == -1) - eprintf("pledge:"); + if (pledge("stdio rpath wpath disklabel", NULL) == -1) + eprintf("pledge:"); #endif - ARGBEGIN { - case 'N': - opt_N = 1; - break; - case 'B': - opt_B = EARGF(usage()); - break; - case 'F': - arg = EARGF(usage()); - opt_F = strtonum(arg, 1, INT_MAX, NULL); - if (!(opt_F == 12 || opt_F == 16 || opt_F == 32)) - eprintf("%s: bad FAT type\n", arg); - break; - case 'I': - opt_I = argto4(EARGF(usage()), 0, "volume ID"); - Iflag = 1; - break; - case 'n': - case 'L': - arg = EARGF(usage()); - if (!oklabel(arg)) - eprintf("%s: bad volume label\n", arg); - opt_L = arg; - break; - case 'O': - arg = EARGF(usage()); - if (strlen(arg) > 8) - eprintf("%s: bad OEM string\n", arg); - opt_O = arg; - break; - case 'S': - opt_S = argto2(EARGF(usage()), 1, "bytes/sector"); - break; - case 'a': - opt_a = argto4(EARGF(usage()), 1, "sectors/FAT"); - break; - case 'b': - opt_b = argtox(EARGF(usage()), 1, "block size"); - opt_c = 0; - break; - case 'c': - opt_c = argto1(EARGF(usage()), 1, "sectors/cluster"); - opt_b = 0; - break; - case 'e': - opt_e = argto2(EARGF(usage()), 1, "directory entries"); - break; - case 'f': - opt_f = EARGF(usage()); - break; - case 'h': - opt_h = argto2(EARGF(usage()), 1, "drive heads"); - break; - case 'i': - opt_i = argto2(EARGF(usage()), 1, "info sector"); - break; - case 'k': - opt_k = argto2(EARGF(usage()), 1, "backup sector"); - break; - case 'm': - opt_m = argto1(EARGF(usage()), 0, "media descriptor"); - mflag = 1; - break; - case 'A': - opt_n = argto1(EARGF(usage()), 1, "number of FATs"); - break; - case 'o': - opt_o = argto4(EARGF(usage()), 0, "hidden sectors"); - oflag = 1; - break; - case 'q': /* Compat with newfs -q */ - break; - case 'r': - opt_r = argto2(EARGF(usage()), 1, "reserved sectors"); - break; - case 's': - opt_s = argto4(EARGF(usage()), 1, "file system size"); - break; - case 't': /* Compat with newfs -t */ - (void)EARGF(usage()); - break; - case 'u': - opt_u = argto2(EARGF(usage()), 1, "sectors/track"); - break; - default: - usage(); - } ARGEND - if (argc != 1) - usage(); - fname = argv[0]; - flags = opt_N ? O_RDONLY : O_RDWR; + ARGBEGIN + { + case 'N': + opt_N = 1; + break; + case 'B': + opt_B = EARGF(usage()); + break; + case 'F': + arg = EARGF(usage()); + opt_F = strtonum(arg, 1, INT_MAX, NULL); + if (!(opt_F == 12 || opt_F == 16 || opt_F == 32)) + eprintf("%s: bad FAT type\n", arg); + break; + case 'I': + opt_I = argto4(EARGF(usage()), 0, "volume ID"); + Iflag = 1; + break; + case 'n': + case 'L': + arg = EARGF(usage()); + if (!oklabel(arg)) + eprintf("%s: bad volume label\n", arg); + opt_L = arg; + break; + case 'O': + arg = EARGF(usage()); + if (strlen(arg) > 8) + eprintf("%s: bad OEM string\n", arg); + opt_O = arg; + break; + case 'S': + opt_S = argto2(EARGF(usage()), 1, "bytes/sector"); + break; + case 'a': + opt_a = argto4(EARGF(usage()), 1, "sectors/FAT"); + break; + case 'b': + opt_b = argtox(EARGF(usage()), 1, "block size"); + opt_c = 0; + break; + case 'c': + opt_c = argto1(EARGF(usage()), 1, "sectors/cluster"); + opt_b = 0; + break; + case 'e': + opt_e = argto2(EARGF(usage()), 1, "directory entries"); + break; + case 'f': + opt_f = EARGF(usage()); + break; + case 'h': + opt_h = argto2(EARGF(usage()), 1, "drive heads"); + break; + case 'i': + opt_i = argto2(EARGF(usage()), 1, "info sector"); + break; + case 'k': + opt_k = argto2(EARGF(usage()), 1, "backup sector"); + break; + case 'm': + opt_m = argto1(EARGF(usage()), 0, "media descriptor"); + mflag = 1; + break; + case 'A': + opt_n = argto1(EARGF(usage()), 1, "number of FATs"); + break; + case 'o': + opt_o = argto4(EARGF(usage()), 0, "hidden sectors"); + oflag = 1; + break; + case 'q': /* Compat with newfs -q */ + break; + case 'r': + opt_r = argto2(EARGF(usage()), 1, "reserved sectors"); + break; + case 's': + opt_s = argto4(EARGF(usage()), 1, "file system size"); + break; + case 't': /* Compat with newfs -t */ + (void)EARGF(usage()); + break; + case 'u': + opt_u = argto2(EARGF(usage()), 1, "sectors/track"); + break; + default: + usage(); + } + ARGEND + if (argc != 1) + usage(); + fname = argv[0]; + flags = opt_N ? O_RDONLY : O_RDWR; #if defined(__linux__) && !defined(ARUU_FORCE_POSIX) - /* The kernel refuses a writable claim on a mounted block device. */ - if (!opt_N) - flags |= O_EXCL; + /* The kernel refuses a writable claim on a mounted block device. */ + if (!opt_N) + flags |= O_EXCL; #endif - fd = open(fname, flags | O_NONBLOCK); - if (fd < 0) - eprintf("%s:", fname); - memset(&bpb, 0, sizeof(bpb)); - if (opt_f) { - getstdfmt(opt_f, &bpb); - bpb.bsec = bpb.sec; - bpb.sec = 0; - bpb.bspf = bpb.spf; - bpb.spf = 0; - } - if (opt_h) - bpb.hds = opt_h; - if (opt_u) - bpb.spt = opt_u; - if (opt_S) - bpb.bps = opt_S; - if (opt_s) - bpb.bsec = opt_s; - gettarget(fd, fname, opt_N, &bpb); - if (oflag) - bpb.hid = opt_o; - if (!powerof2(bpb.bps)) - eprintf("bytes/sector (%u) is not a power of 2\n", bpb.bps); - if (bpb.bps < MINBPS) - eprintf("bytes/sector (%u) is too small; minimum is %u\n", - bpb.bps, MINBPS); - if (!(fat = opt_F)) { - if (opt_f) - fat = 12; - else if (!opt_e && (opt_i || opt_k)) - fat = 32; - } - if ((fat == 32 && opt_e) || (fat != 32 && (opt_i || opt_k))) - eprintf("-%c is not a legal FAT%s option\n", - fat == 32 ? 'e' : opt_i ? 'i' : 'k', - fat == 32 ? "32" : "12/16"); - if (opt_f && fat == 32) - bpb.rde = 0; - if (opt_b) { - if (!powerof2(opt_b)) - eprintf("block size (%u) is not a power of 2\n", opt_b); - if (opt_b < bpb.bps) - eprintf("block size (%u) is too small; minimum is %u\n", - opt_b, bpb.bps); - if (opt_b > bpb.bps * MAXSPC) - eprintf("block size (%u) is too large; maximum is %u\n", - opt_b, bpb.bps * MAXSPC); - bpb.spc = opt_b / bpb.bps; - } - if (opt_c) { - if (!powerof2(opt_c)) - eprintf("sectors/cluster (%u) is not a power of 2\n", opt_c); - bpb.spc = opt_c; - } - if (opt_r) - bpb.res = opt_r; - if (opt_n) { - if (opt_n > MAXNFT) - eprintf("number of FATs (%u) is too large; maximum is %u\n", - opt_n, MAXNFT); - bpb.nft = opt_n; - } - if (opt_e) - bpb.rde = opt_e; - if (mflag) { - if (opt_m < 0xf0) - eprintf("illegal media descriptor (%#x)\n", opt_m); - bpb.mid = opt_m; + fd = open(fname, flags | O_NONBLOCK); + if (fd < 0) + eprintf("%s:", fname); + memset(&bpb, 0, sizeof(bpb)); + if (opt_f) { + getstdfmt(opt_f, &bpb); + bpb.bsec = bpb.sec; + bpb.sec = 0; + bpb.bspf = bpb.spf; + bpb.spf = 0; + } + if (opt_h) + bpb.hds = opt_h; + if (opt_u) + bpb.spt = opt_u; + if (opt_S) + bpb.bps = opt_S; + if (opt_s) + bpb.bsec = opt_s; + gettarget(fd, fname, opt_N, &bpb); + if (oflag) + bpb.hid = opt_o; + if (!powerof2(bpb.bps)) + eprintf("bytes/sector (%u) is not a power of 2\n", bpb.bps); + if (bpb.bps < MINBPS) + eprintf("bytes/sector (%u) is too small; minimum is %u\n", bpb.bps, MINBPS); + if (!(fat = opt_F)) { + if (opt_f) + fat = 12; + else if (!opt_e && (opt_i || opt_k)) + fat = 32; + } + if ((fat == 32 && opt_e) || (fat != 32 && (opt_i || opt_k))) + eprintf( + "-%c is not a legal FAT%s option\n", + fat == 32 ? 'e' + : opt_i ? 'i' + : 'k', + fat == 32 ? "32" : "12/16" + ); + if (opt_f && fat == 32) + bpb.rde = 0; + if (opt_b) { + if (!powerof2(opt_b)) + eprintf("block size (%u) is not a power of 2\n", opt_b); + if (opt_b < bpb.bps) + eprintf("block size (%u) is too small; minimum is %u\n", opt_b, bpb.bps); + if (opt_b > bpb.bps * MAXSPC) + eprintf("block size (%u) is too large; maximum is %u\n", opt_b, bpb.bps * MAXSPC); + bpb.spc = opt_b / bpb.bps; + } + if (opt_c) { + if (!powerof2(opt_c)) + eprintf("sectors/cluster (%u) is not a power of 2\n", opt_c); + bpb.spc = opt_c; + } + if (opt_r) + bpb.res = opt_r; + if (opt_n) { + if (opt_n > MAXNFT) + eprintf("number of FATs (%u) is too large; maximum is %u\n", opt_n, MAXNFT); + bpb.nft = opt_n; + } + if (opt_e) + bpb.rde = opt_e; + if (mflag) { + if (opt_m < 0xf0) + eprintf("illegal media descriptor (%#x)\n", opt_m); + bpb.mid = opt_m; + } + if (opt_a) + bpb.bspf = opt_a; + if (opt_i) + bpb.infs = opt_i; + if (opt_k) + bpb.bkbs = opt_k; + bss = 1; + bname = NULL; + fd1 = -1; + if (opt_B) { + bname = opt_B; + if (!strchr(bname, '/')) { + if (snprintf(buf, sizeof buf, "/boot/%s", bname) >= (int)sizeof buf) + eprintf("bootstrap path too long\n"); + bname = buf; } - if (opt_a) - bpb.bspf = opt_a; - if (opt_i) - bpb.infs = opt_i; - if (opt_k) - bpb.bkbs = opt_k; - bss = 1; - bname = NULL; - fd1 = -1; - if (opt_B) { - bname = opt_B; - if (!strchr(bname, '/')) { - if (snprintf(buf, sizeof buf, "/boot/%s", bname) >= (int)sizeof buf) - eprintf("bootstrap path too long\n"); - bname = buf; - } - if ((fd1 = open(bname, O_RDONLY)) == -1 || fstat(fd1, &sb)) - eprintf("%s:", bname); - if (!S_ISREG(sb.st_mode) || sb.st_size % bpb.bps || - sb.st_size < bpb.bps || sb.st_size > bpb.bps * MAXU16) - eprintf("%s: inappropriate file type or format\n", bname); - bss = sb.st_size / bpb.bps; + if ((fd1 = open(bname, O_RDONLY)) == -1 || fstat(fd1, &sb)) + eprintf("%s:", bname); + if (!S_ISREG(sb.st_mode) || sb.st_size % bpb.bps || sb.st_size < bpb.bps + || sb.st_size > bpb.bps * MAXU16) + eprintf("%s: inappropriate file type or format\n", bname); + bss = sb.st_size / bpb.bps; + } + if (!bpb.nft) + bpb.nft = 2; + if (!fat) { + if (bpb.bsec + < (bpb.res ? bpb.res : bss) + + howmany( + (RESFTE + (bpb.spc ? MINCLS16 : MAXCLS12 + 1)) * ((bpb.spc ? 16 : 12) / BPN), + bpb.bps * NPB + ) * bpb.nft + + howmany(bpb.rde ? bpb.rde : DEFRDE, bpb.bps / sizeof(struct de)) + + (bpb.spc ? MINCLS16 : MAXCLS12 + 1) + * (bpb.spc ? bpb.spc : howmany(DEFBLK, bpb.bps))) + fat = 12; + else if ( + bpb.rde + || bpb.bsec < (bpb.res ? bpb.res : bss) + + howmany((RESFTE + MAXCLS16) * 2, bpb.bps) * bpb.nft + + howmany(DEFRDE, bpb.bps / sizeof(struct de)) + + (MAXCLS16 + 1) * (bpb.spc ? bpb.spc : howmany(8192, bpb.bps)) + ) + fat = 16; + else + fat = 32; + } + x = bss; + if (fat == 32) { + if (!bpb.infs) { + if (x == MAXU16 || x == bpb.bkbs) + eprintf("no room for info sector\n"); + bpb.infs = x; } - if (!bpb.nft) - bpb.nft = 2; - if (!fat) { - if (bpb.bsec < (bpb.res ? bpb.res : bss) + - howmany((RESFTE + (bpb.spc ? MINCLS16 : MAXCLS12 + 1)) * - ((bpb.spc ? 16 : 12) / BPN), bpb.bps * NPB) * - bpb.nft + - howmany(bpb.rde ? bpb.rde : DEFRDE, - bpb.bps / sizeof(struct de)) + - (bpb.spc ? MINCLS16 : MAXCLS12 + 1) * - (bpb.spc ? bpb.spc : howmany(DEFBLK, bpb.bps))) - fat = 12; - else if (bpb.rde || bpb.bsec < - (bpb.res ? bpb.res : bss) + - howmany((RESFTE + MAXCLS16) * 2, bpb.bps) * bpb.nft + - howmany(DEFRDE, bpb.bps / sizeof(struct de)) + - (MAXCLS16 + 1) * - (bpb.spc ? bpb.spc : howmany(8192, bpb.bps))) - fat = 16; - else - fat = 32; + if (bpb.infs != MAXU16 && bpb.infs < bss) + eprintf("info sector would overwrite bootstrap\n"); + if (bpb.infs != MAXU16 && x <= bpb.infs) + x = bpb.infs + 1; + if (!bpb.bkbs) { + if (x == MAXU16) + eprintf("no room for backup sector\n"); + bpb.bkbs = x; + } else if (bpb.bkbs != MAXU16 && bpb.bkbs == bpb.infs) + eprintf("backup sector would overwrite info sector\n"); + if (bpb.bkbs != MAXU16) { + if (bpb.bkbs < bss + || (bpb.infs != MAXU16 && bpb.infs >= bpb.bkbs && bpb.infs < bpb.bkbs + bss)) + eprintf("overlapping backup bootstrap\n"); + x = MAXIMUM(x, bpb.bkbs + bss); + if (bpb.infs != MAXU16) + x = MAXIMUM(x, bpb.bkbs + bpb.infs + 1); + if (x > MAXU16) + eprintf("backup exceeds reserved area\n"); } - x = bss; - if (fat == 32) { - if (!bpb.infs) { - if (x == MAXU16 || x == bpb.bkbs) - eprintf("no room for info sector\n"); - bpb.infs = x; - } - if (bpb.infs != MAXU16 && bpb.infs < bss) - eprintf("info sector would overwrite bootstrap\n"); - if (bpb.infs != MAXU16 && x <= bpb.infs) - x = bpb.infs + 1; - if (!bpb.bkbs) { - if (x == MAXU16) - eprintf("no room for backup sector\n"); - bpb.bkbs = x; - } else if (bpb.bkbs != MAXU16 && bpb.bkbs == bpb.infs) - eprintf("backup sector would overwrite info sector\n"); - if (bpb.bkbs != MAXU16) { - if (bpb.bkbs < bss || (bpb.infs != MAXU16 && - bpb.infs >= bpb.bkbs && bpb.infs < bpb.bkbs + bss)) - eprintf("overlapping backup bootstrap\n"); - x = MAXIMUM(x, bpb.bkbs + bss); - if (bpb.infs != MAXU16) - x = MAXIMUM(x, bpb.bkbs + bpb.infs + 1); - if (x > MAXU16) - eprintf("backup exceeds reserved area\n"); - } + } + if (!bpb.res) + bpb.res = fat == 32 ? MAXIMUM(x, MAXIMUM(16384 / bpb.bps, 4)) : x; + else if (bpb.res < x) + eprintf("too few reserved sectors\n"); + if (fat != 32) { + if (!bpb.rde) + bpb.rde = MAXIMUM(DEFRDE, bpb.bps / sizeof(struct de)); + if (bpb.rde % (bpb.bps / sizeof(struct de))) + eprintf("root directory must occupy whole sectors\n"); + } + rds = howmany(bpb.rde, bpb.bps / sizeof(struct de)); + if (!bpb.spc) { + unsigned int minfat = howmany((RESFTE + mincls(fat)) * (fat / BPN), bpb.bps * NPB); + uint64_t metadata = bpb.res + rds + (uint64_t)bpb.nft * (bpb.bspf ? bpb.bspf : minfat); + + /* A small EFI partition may need clusters below the default 4 KiB. */ + bpb.spc = howmany(fat == 16 ? DEFBLK16 : DEFBLK, bpb.bps); + while (bpb.spc > 1 && metadata + (uint64_t)mincls(fat) * bpb.spc > bpb.bsec) + bpb.spc >>= 1; + while (bpb.spc < MAXSPC + && bpb.res + howmany((RESFTE + maxcls(fat)) * (fat / BPN), bpb.bps * NPB) * bpb.nft + rds + + (uint64_t)(maxcls(fat) + 1) * bpb.spc + <= bpb.bsec) + bpb.spc <<= 1; + } + if (fat != 32 && bpb.bspf > MAXU16) + eprintf("too many sectors/FAT for FAT12/16\n"); + x1 = bpb.res + rds; + if (x1 >= bpb.bsec) + eprintf("metadata exceeds filesystem size\n"); + /* The FAT must cover the data clusters plus its two reserved entries. + * Each sector added to a FAT also removes one sector per copy from data. */ + bits = ((uint64_t)bpb.bsec - x1 + RESFTE * bpb.spc) * fat; + x = bpb.spc * bpb.bps * 8 + bpb.nft * fat; + x2 = howmany(bits, x); + x = howmany((uint64_t)(RESFTE + maxcls(fat)) * fat, bpb.bps * 8); + if (!bpb.bspf) + bpb.bspf = MINIMUM(x2, x); + if (x1 + (uint64_t)bpb.bspf * bpb.nft >= bpb.bsec) + eprintf("metadata exceeds filesystem size\n"); + x1 += bpb.bspf * bpb.nft; + cls = (bpb.bsec - x1) / bpb.spc; + capacity = (uint64_t)bpb.bspf * bpb.bps * 8 / fat - RESFTE; + capacity = MINIMUM(capacity, maxcls(fat)); + if (cls > capacity) { + cls = capacity; + bpb.bsec = x1 + cls * bpb.spc; + weprintf("warning: FAT limits filesystem to %u sectors\n", bpb.bsec); + } + if (cls < mincls(fat)) + eprintf("%u clusters too few for FAT%u, need %u\n", cls, fat, mincls(fat)); + printf( + "%s: %u sector%s in %u FAT%u cluster%s " + "(%u bytes/cluster)\n", + fname, + cls * bpb.spc, + cls * bpb.spc == 1 ? "" : "s", + cls, + fat, + cls == 1 ? "" : "s", + bpb.bps * bpb.spc + ); + if (!bpb.mid) + bpb.mid = !bpb.hid ? 0xf0 : 0xf8; + if (fat == 32) + bpb.rdcl = RESFTE; + if ((uint64_t)bpb.hid + bpb.bsec <= MAXU16) { + bpb.sec = bpb.bsec; + bpb.bsec = 0; + } + if (fat != 32) { + bpb.spf = bpb.bspf; + bpb.bspf = 0; + } + print_bpb(&bpb); + if (!opt_N) { + if (gettimeofday(&tv, NULL) < 0) + eprintf("gettimeofday:"); + now = tv.tv_sec; + if ((tm = localtime(&now)) == NULL) + eprintf("Invalid time\n"); + + img = emalloc(bpb.bps); + dir = bpb.res + (bpb.spf ? bpb.spf : bpb.bspf) * bpb.nft; + for (lsn = 0; lsn < dir + (fat == 32 ? bpb.spc : rds); lsn++) { + x = lsn; + if (opt_B && fat == 32 && bpb.bkbs != MAXU16 && bss <= bpb.bkbs && x >= bpb.bkbs) { + x -= bpb.bkbs; + if (!x && lseek(fd1, 0, SEEK_SET)) + eprintf("%s:", bname); + } + if (opt_B && x < bss) { + if ((n = read(fd1, img, bpb.bps)) == -1) + eprintf("%s:", bname); + if (n != bpb.bps) + eprintf("%s: can't read sector %u\n", bname, x); + } else + memset(img, 0, bpb.bps); + if (!lsn || (fat == 32 && bpb.bkbs != MAXU16 && lsn == bpb.bkbs)) { + x1 = sizeof(struct bs); + bsbpb = (struct bsbpb *)(img + x1); + mk2(bsbpb->bps, bpb.bps); + mk1(bsbpb->spc, bpb.spc); + mk2(bsbpb->res, bpb.res); + mk1(bsbpb->nft, bpb.nft); + mk2(bsbpb->rde, bpb.rde); + mk2(bsbpb->sec, bpb.sec); + mk1(bsbpb->mid, bpb.mid); + mk2(bsbpb->spf, bpb.spf); + mk2(bsbpb->spt, bpb.spt); + mk2(bsbpb->hds, bpb.hds); + mk4(bsbpb->hid, bpb.hid); + mk4(bsbpb->bsec, bpb.bsec); + x1 += sizeof(struct bsbpb); + if (fat == 32) { + bsxbpb = (struct bsxbpb *)(img + x1); + mk4(bsxbpb->bspf, bpb.bspf); + mk2(bsxbpb->xflg, 0); + mk2(bsxbpb->vers, 0); + mk4(bsxbpb->rdcl, bpb.rdcl); + mk2(bsxbpb->infs, bpb.infs); + mk2(bsxbpb->bkbs, bpb.bkbs); + x1 += sizeof(struct bsxbpb); + } + bsx = (struct bsx *)(img + x1); + mk1(bsx->sig, 0x29); + if (Iflag) + x = opt_I; + else + x = (((unsigned int)(1 + tm->tm_mon) << 8 | (unsigned int)tm->tm_mday) + + ((unsigned int)tm->tm_sec << 8 | (unsigned int)(tv.tv_usec / 10))) + << 16 + | ((unsigned int)(1900 + tm->tm_year) + + ((unsigned int)tm->tm_hour << 8 | (unsigned int)tm->tm_min)); + mk4(bsx->volid, x); + mklabel(bsx->label, opt_L ? opt_L : "NO NAME"); + setstr(bsx->type, fat == 12 ? "FAT12" : fat == 16 ? "FAT16" : "FAT32", sizeof(bsx->type)); + if (!opt_B) { + x1 += sizeof(struct bsx); + bs = (struct bs *)img; + mk1(bs->jmp[0], 0xeb); + mk1(bs->jmp[1], x1 - 2); + mk1(bs->jmp[2], 0x90); + setstr(bs->oem, opt_O ? opt_O : "BSD 4.4", sizeof(bs->oem)); + memcpy(img + x1, bootcode, sizeof(bootcode)); + mk2(img + MINBPS - 2, DOSMAGIC); + } + } else if ( + fat == 32 && bpb.infs != MAXU16 + && (lsn == bpb.infs || (bpb.bkbs != MAXU16 && lsn == bpb.bkbs + bpb.infs)) + ) { + mk4(img, 0x41615252); + mk4(img + MINBPS - 28, 0x61417272); + mk4(img + MINBPS - 24, cls - 1); + mk4(img + MINBPS - 20, bpb.rdcl + 1); + mk2(img + MINBPS - 2, DOSMAGIC); + } else if ( + lsn >= bpb.res && lsn < dir && !((lsn - bpb.res) % (bpb.spf ? bpb.spf : bpb.bspf)) + ) { + mk1(img[0], bpb.mid); + for (x = 1; x < fat * (fat == 32 ? 3 : 2) / 8; x++) + mk1(img[x], fat == 32 && x % 4 == 3 ? 0x0f : 0xff); + } else if (lsn == dir && opt_L) { + de = (struct de *)img; + mklabel(de->namext, opt_L); + mk1(de->attr, 0x08); + x = (unsigned int)tm->tm_hour << 11 | (unsigned int)tm->tm_min << 5 + | (unsigned int)tm->tm_sec >> 1; + mk2(de->time, x); + x = (unsigned int)(tm->tm_year - 80) << 9 | (unsigned int)(tm->tm_mon + 1) << 5 + | (unsigned int)tm->tm_mday; + mk2(de->date, x); + } + if ((n = writeall(fd, img, bpb.bps)) == -1) + eprintf("%s:", fname); + if (n != bpb.bps) + eprintf("%s: can't write sector %u\n", fname, lsn); } - if (!bpb.res) - bpb.res = fat == 32 ? MAXIMUM(x, MAXIMUM(16384 / bpb.bps, 4)) : x; - else if (bpb.res < x) - eprintf("too few reserved sectors\n"); - if (fat != 32) { - if (!bpb.rde) - bpb.rde = MAXIMUM(DEFRDE, bpb.bps / sizeof(struct de)); - if (bpb.rde % (bpb.bps / sizeof(struct de))) - eprintf("root directory must occupy whole sectors\n"); - } - rds = howmany(bpb.rde, bpb.bps / sizeof(struct de)); - if (!bpb.spc) { - unsigned int minfat = howmany((RESFTE + mincls(fat)) * (fat / BPN), - bpb.bps * NPB); - uint64_t metadata = bpb.res + rds + - (uint64_t)bpb.nft * (bpb.bspf ? bpb.bspf : minfat); - - /* A small EFI partition may need clusters below the default 4 KiB. */ - bpb.spc = howmany(fat == 16 ? DEFBLK16 : DEFBLK, bpb.bps); - while (bpb.spc > 1 && metadata + (uint64_t)mincls(fat) * bpb.spc > bpb.bsec) - bpb.spc >>= 1; - while (bpb.spc < MAXSPC && - bpb.res + - howmany((RESFTE + maxcls(fat)) * (fat / BPN), - bpb.bps * NPB) * bpb.nft + - rds + - (uint64_t)(maxcls(fat) + 1) * bpb.spc <= bpb.bsec) - bpb.spc <<= 1; - } - if (fat != 32 && bpb.bspf > MAXU16) - eprintf("too many sectors/FAT for FAT12/16\n"); - x1 = bpb.res + rds; - if (x1 >= bpb.bsec) - eprintf("metadata exceeds filesystem size\n"); - /* The FAT must cover the data clusters plus its two reserved entries. - * Each sector added to a FAT also removes one sector per copy from data. */ - bits = ((uint64_t)bpb.bsec - x1 + RESFTE * bpb.spc) * fat; - x = bpb.spc * bpb.bps * 8 + bpb.nft * fat; - x2 = howmany(bits, x); - x = howmany((uint64_t)(RESFTE + maxcls(fat)) * fat, bpb.bps * 8); - if (!bpb.bspf) - bpb.bspf = MINIMUM(x2, x); - if (x1 + (uint64_t)bpb.bspf * bpb.nft >= bpb.bsec) - eprintf("metadata exceeds filesystem size\n"); - x1 += bpb.bspf * bpb.nft; - cls = (bpb.bsec - x1) / bpb.spc; - capacity = (uint64_t)bpb.bspf * bpb.bps * 8 / fat - RESFTE; - capacity = MINIMUM(capacity, maxcls(fat)); - if (cls > capacity) { - cls = capacity; - bpb.bsec = x1 + cls * bpb.spc; - weprintf("warning: FAT limits filesystem to %u sectors\n", bpb.bsec); - } - if (cls < mincls(fat)) - eprintf("%u clusters too few for FAT%u, need %u\n", cls, fat, mincls(fat)); - printf("%s: %u sector%s in %u FAT%u cluster%s " - "(%u bytes/cluster)\n", fname, cls * bpb.spc, - cls * bpb.spc == 1 ? "" : "s", cls, fat, - cls == 1 ? "" : "s", bpb.bps * bpb.spc); - if (!bpb.mid) - bpb.mid = !bpb.hid ? 0xf0 : 0xf8; - if (fat == 32) - bpb.rdcl = RESFTE; - if ((uint64_t)bpb.hid + bpb.bsec <= MAXU16) { - bpb.sec = bpb.bsec; - bpb.bsec = 0; - } - if (fat != 32) { - bpb.spf = bpb.bspf; - bpb.bspf = 0; - } - print_bpb(&bpb); - if (!opt_N) { - if (gettimeofday(&tv, NULL) < 0) - eprintf("gettimeofday:"); - now = tv.tv_sec; - if ((tm = localtime(&now)) == NULL) - eprintf("Invalid time\n"); - - img = emalloc(bpb.bps); - dir = bpb.res + (bpb.spf ? bpb.spf : bpb.bspf) * bpb.nft; - for (lsn = 0; lsn < dir + (fat == 32 ? bpb.spc : rds); lsn++) { - x = lsn; - if (opt_B && - fat == 32 && bpb.bkbs != MAXU16 && - bss <= bpb.bkbs && x >= bpb.bkbs) { - x -= bpb.bkbs; - if (!x && lseek(fd1, 0, SEEK_SET)) - eprintf("%s:", bname); - } - if (opt_B && x < bss) { - if ((n = read(fd1, img, bpb.bps)) == -1) - eprintf("%s:", bname); - if (n != bpb.bps) - eprintf("%s: can't read sector %u\n", bname, x); - } else - memset(img, 0, bpb.bps); - if (!lsn || - (fat == 32 && bpb.bkbs != MAXU16 && lsn == bpb.bkbs)) { - x1 = sizeof(struct bs); - bsbpb = (struct bsbpb *)(img + x1); - mk2(bsbpb->bps, bpb.bps); - mk1(bsbpb->spc, bpb.spc); - mk2(bsbpb->res, bpb.res); - mk1(bsbpb->nft, bpb.nft); - mk2(bsbpb->rde, bpb.rde); - mk2(bsbpb->sec, bpb.sec); - mk1(bsbpb->mid, bpb.mid); - mk2(bsbpb->spf, bpb.spf); - mk2(bsbpb->spt, bpb.spt); - mk2(bsbpb->hds, bpb.hds); - mk4(bsbpb->hid, bpb.hid); - mk4(bsbpb->bsec, bpb.bsec); - x1 += sizeof(struct bsbpb); - if (fat == 32) { - bsxbpb = (struct bsxbpb *)(img + x1); - mk4(bsxbpb->bspf, bpb.bspf); - mk2(bsxbpb->xflg, 0); - mk2(bsxbpb->vers, 0); - mk4(bsxbpb->rdcl, bpb.rdcl); - mk2(bsxbpb->infs, bpb.infs); - mk2(bsxbpb->bkbs, bpb.bkbs); - x1 += sizeof(struct bsxbpb); - } - bsx = (struct bsx *)(img + x1); - mk1(bsx->sig, 0x29); - if (Iflag) - x = opt_I; - else - x = (((unsigned int)(1 + tm->tm_mon) << 8 | - (unsigned int)tm->tm_mday) + - ((unsigned int)tm->tm_sec << 8 | - (unsigned int)(tv.tv_usec / 10))) << 16 | - ((unsigned int)(1900 + tm->tm_year) + - ((unsigned int)tm->tm_hour << 8 | - (unsigned int)tm->tm_min)); - mk4(bsx->volid, x); - mklabel(bsx->label, opt_L ? opt_L : "NO NAME"); - setstr(bsx->type, fat == 12 ? "FAT12" : fat == 16 ? "FAT16" : "FAT32", - sizeof(bsx->type)); - if (!opt_B) { - x1 += sizeof(struct bsx); - bs = (struct bs *)img; - mk1(bs->jmp[0], 0xeb); - mk1(bs->jmp[1], x1 - 2); - mk1(bs->jmp[2], 0x90); - setstr(bs->oem, opt_O ? opt_O : "BSD 4.4", - sizeof(bs->oem)); - memcpy(img + x1, bootcode, sizeof(bootcode)); - mk2(img + MINBPS - 2, DOSMAGIC); - } - } else if (fat == 32 && bpb.infs != MAXU16 && - (lsn == bpb.infs || - (bpb.bkbs != MAXU16 && - lsn == bpb.bkbs + bpb.infs))) { - mk4(img, 0x41615252); - mk4(img + MINBPS - 28, 0x61417272); - mk4(img + MINBPS - 24, cls - 1); - mk4(img + MINBPS - 20, bpb.rdcl + 1); - mk2(img + MINBPS - 2, DOSMAGIC); - } else if (lsn >= bpb.res && lsn < dir && - !((lsn - bpb.res) % - (bpb.spf ? bpb.spf : bpb.bspf))) { - mk1(img[0], bpb.mid); - for (x = 1; x < fat * (fat == 32 ? 3 : 2) / 8; x++) - mk1(img[x], fat == 32 && x % 4 == 3 ? 0x0f : 0xff); - } else if (lsn == dir && opt_L) { - de = (struct de *)img; - mklabel(de->namext, opt_L); - mk1(de->attr, 0x08); - x = (unsigned int)tm->tm_hour << 11 | - (unsigned int)tm->tm_min << 5 | - (unsigned int)tm->tm_sec >> 1; - mk2(de->time, x); - x = (unsigned int)(tm->tm_year - 80) << 9 | - (unsigned int)(tm->tm_mon + 1) << 5 | - (unsigned int)tm->tm_mday; - mk2(de->date, x); - } - if ((n = writeall(fd, img, bpb.bps)) == -1) - eprintf("%s:", fname); - if (n != bpb.bps) - eprintf("%s: can't write sector %u\n", fname, lsn); - } - free(img); - if (fsync(fd) < 0) - eprintf("%s:", fname); - } - if (fd1 >= 0) - close(fd1); - if (close(fd) < 0) - eprintf("%s:", fname); - return fshut(stdout, "<stdout>"); + free(img); + if (fsync(fd) < 0) + eprintf("%s:", fname); + } + if (fd1 >= 0) + close(fd1); + if (close(fd) < 0) + eprintf("%s:", fname); + return fshut(stdout, "<stdout>"); } /* Fill the BPB from the opened partition or the length of an existing image. */ static void gettarget(int fd, const char *path, int dry, struct bpb *bpb) { - struct stat st; - struct BlockDev dev = { .fd = fd }; - uint64_t sectors, start = 0; - - if (fstat(fd, &st) < 0) - eprintf("%s:", path); - if (S_ISREG(st.st_mode)) { - dev.size = st.st_size; - dev.sec_size = MINBPS; + struct stat st; + struct BlockDev dev = {.fd = fd}; + uint64_t sectors, start = 0; + + if (fstat(fd, &st) < 0) + eprintf("%s:", path); + if (S_ISREG(st.st_mode)) { + dev.size = st.st_size; + dev.sec_size = MINBPS; #if defined(__linux__) && !defined(ARUU_FORCE_POSIX) - } else if (S_ISBLK(st.st_mode)) { - struct hd_geometry geo; - - blockdev_sys_size(&dev); - if (ioctl(fd, HDIO_GETGEO, &geo) == 0) { - start = (uint64_t)geo.start * 512; - if (!bpb->spt) - bpb->spt = geo.sectors; - if (!bpb->hds) - bpb->hds = geo.heads; - } + } else if (S_ISBLK(st.st_mode)) { + struct hd_geometry geo; + + blockdev_sys_size(&dev); + if (ioctl(fd, HDIO_GETGEO, &geo) == 0) { + start = (uint64_t)geo.start * 512; + if (!bpb->spt) + bpb->spt = geo.sectors; + if (!bpb->hds) + bpb->hds = geo.heads; + } #elif defined(__FreeBSD__) && !defined(ARUU_FORCE_POSIX) - } else if (S_ISCHR(st.st_mode)) { - blockdev_sys_size(&dev); + } else if (S_ISCHR(st.st_mode)) { + blockdev_sys_size(&dev); #elif defined(__OpenBSD__) && !defined(ARUU_FORCE_POSIX) - } else if (S_ISCHR(st.st_mode)) { - struct disklabel dl; - struct statfs *mp; - size_t part = DISKPART(st.st_rdev); - int n; - - if (ioctl(fd, DIOCGDINFO, &dl) < 0) - eprintf("%s: disklabel:", path); - if (part >= dl.d_npartitions) - eprintf("%s: partition unavailable\n", path); - if (!dry) { - struct stat raw; - char name[PATH_MAX]; - - if (!(n = getmntinfo(&mp, MNT_NOWAIT))) - eprintf("getmntinfo:"); - for (; n--; mp++) { - if (strncmp(mp->f_mntfromname, "/dev/", 5)) - continue; - if (snprintf(name, sizeof name, "/dev/r%s", mp->f_mntfromname + 5) >= (int)sizeof name) - eprintf("mounted device name too long\n"); - if (stat(name, &raw) == 0 && S_ISCHR(raw.st_mode) && - (raw.st_rdev == st.st_rdev || (part == RAW_PART && - DISKLABELDEV(raw.st_rdev) == DISKLABELDEV(st.st_rdev)))) - eprintf("%s is mounted on %s\n", path, mp->f_mntonname); - } - } - dev.sec_size = dl.d_secsize; - dev.size = DL_GETPSIZE(&dl.d_partitions[part]) * (uint64_t)dl.d_secsize; - start = DL_GETPOFFSET(&dl.d_partitions[part]) * (uint64_t)dl.d_secsize; - if (!bpb->spt && dl.d_nsectors <= 63) - bpb->spt = dl.d_nsectors; - if (!bpb->hds && dl.d_ntracks <= MAXU16) - bpb->hds = dl.d_ntracks; -#endif - } else { - eprintf("%s: unsupported file type\n", path); - } - (void)dry; - if (!dev.sec_size || !dev.size) - eprintf("%s: cannot determine a nonzero target size\n", path); - if (!bpb->bps) - bpb->bps = dev.sec_size; - if (bpb->bps < dev.sec_size || bpb->bps > MAXU16) - eprintf("%s: invalid sector size %u\n", path, bpb->bps); - sectors = dev.size / bpb->bps; - if (start / bpb->bps <= UINT32_MAX) - bpb->hid = start / bpb->bps; - if (!bpb->mid && !S_ISREG(st.st_mode)) - bpb->mid = 0xf8; - if (!bpb->bsec) { - if (sectors > UINT32_MAX) - eprintf("%s: too many sectors for FAT\n", path); - bpb->bsec = sectors; + } else if (S_ISCHR(st.st_mode)) { + struct disklabel dl; + struct statfs *mp; + size_t part = DISKPART(st.st_rdev); + int n; + + if (ioctl(fd, DIOCGDINFO, &dl) < 0) + eprintf("%s: disklabel:", path); + if (part >= dl.d_npartitions) + eprintf("%s: partition unavailable\n", path); + if (!dry) { + struct stat raw; + char name[PATH_MAX]; + + if (!(n = getmntinfo(&mp, MNT_NOWAIT))) + eprintf("getmntinfo:"); + for (; n--; mp++) { + if (strncmp(mp->f_mntfromname, "/dev/", 5)) + continue; + if (snprintf(name, sizeof name, "/dev/r%s", mp->f_mntfromname + 5) >= (int)sizeof name) + eprintf("mounted device name too long\n"); + if (stat(name, &raw) == 0 && S_ISCHR(raw.st_mode) + && (raw.st_rdev == st.st_rdev + || (part == RAW_PART && DISKLABELDEV(raw.st_rdev) == DISKLABELDEV(st.st_rdev)))) + eprintf("%s is mounted on %s\n", path, mp->f_mntonname); + } } - if (!bpb->bsec || bpb->bsec > sectors) - eprintf("%s: filesystem does not fit on target\n", path); - if (!bpb->spt) - bpb->spt = 63; - if (!bpb->hds) - bpb->hds = 255; + dev.sec_size = dl.d_secsize; + dev.size = DL_GETPSIZE(&dl.d_partitions[part]) * (uint64_t)dl.d_secsize; + start = DL_GETPOFFSET(&dl.d_partitions[part]) * (uint64_t)dl.d_secsize; + if (!bpb->spt && dl.d_nsectors <= 63) + bpb->spt = dl.d_nsectors; + if (!bpb->hds && dl.d_ntracks <= MAXU16) + bpb->hds = dl.d_ntracks; +#endif + } else { + eprintf("%s: unsupported file type\n", path); + } + (void)dry; + if (!dev.sec_size || !dev.size) + eprintf("%s: cannot determine a nonzero target size\n", path); + if (!bpb->bps) + bpb->bps = dev.sec_size; + if (bpb->bps < dev.sec_size || bpb->bps > MAXU16) + eprintf("%s: invalid sector size %u\n", path, bpb->bps); + sectors = dev.size / bpb->bps; + if (start / bpb->bps <= UINT32_MAX) + bpb->hid = start / bpb->bps; + if (!bpb->mid && !S_ISREG(st.st_mode)) + bpb->mid = 0xf8; + if (!bpb->bsec) { + if (sectors > UINT32_MAX) + eprintf("%s: too many sectors for FAT\n", path); + bpb->bsec = sectors; + } + if (!bpb->bsec || bpb->bsec > sectors) + eprintf("%s: filesystem does not fit on target\n", path); + if (!bpb->spt) + bpb->spt = 63; + if (!bpb->hds) + bpb->hds = 255; } /* @@ -800,14 +782,14 @@ gettarget(int fd, const char *path, int dry, struct bpb *bpb) static void getstdfmt(const char *fmt, struct bpb *bpb) { - unsigned int x, i; - - x = sizeof(stdfmt) / sizeof(stdfmt[0]); - for (i = 0; i < x && strcmp(fmt, stdfmt[i].name); i++) - continue; - if (i == x) - eprintf("%s: unknown standard format\n", fmt); - *bpb = stdfmt[i].bpb; + unsigned int x, i; + + x = sizeof(stdfmt) / sizeof(stdfmt[0]); + for (i = 0; i < x && strcmp(fmt, stdfmt[i].name); i++) + continue; + if (i == x) + eprintf("%s: unknown standard format\n", fmt); + *bpb = stdfmt[i].bpb; } /* @@ -816,26 +798,25 @@ getstdfmt(const char *fmt, struct bpb *bpb) static void print_bpb(struct bpb *bpb) { - printf("bps=%u spc=%u res=%u nft=%u", bpb->bps, bpb->spc, bpb->res, - bpb->nft); - if (bpb->rde) - printf(" rde=%u", bpb->rde); - if (bpb->sec) - printf(" sec=%u", bpb->sec); - printf(" mid=%#x", bpb->mid); - if (bpb->spf) - printf(" spf=%u", bpb->spf); - printf(" spt=%u hds=%u hid=%u", bpb->spt, bpb->hds, bpb->hid); - if (bpb->bsec) - printf(" bsec=%u", bpb->bsec); - if (!bpb->spf) { - printf(" bspf=%u rdcl=%u", bpb->bspf, bpb->rdcl); - printf(" infs="); - printf(bpb->infs == MAXU16 ? "%#x" : "%u", bpb->infs); - printf(" bkbs="); - printf(bpb->bkbs == MAXU16 ? "%#x" : "%u", bpb->bkbs); - } - printf("\n"); + printf("bps=%u spc=%u res=%u nft=%u", bpb->bps, bpb->spc, bpb->res, bpb->nft); + if (bpb->rde) + printf(" rde=%u", bpb->rde); + if (bpb->sec) + printf(" sec=%u", bpb->sec); + printf(" mid=%#x", bpb->mid); + if (bpb->spf) + printf(" spf=%u", bpb->spf); + printf(" spt=%u hds=%u hid=%u", bpb->spt, bpb->hds, bpb->hid); + if (bpb->bsec) + printf(" bsec=%u", bpb->bsec); + if (!bpb->spf) { + printf(" bspf=%u rdcl=%u", bpb->bspf, bpb->rdcl); + printf(" infs="); + printf(bpb->infs == MAXU16 ? "%#x" : "%u", bpb->infs); + printf(" bkbs="); + printf(bpb->bkbs == MAXU16 ? "%#x" : "%u", bpb->bkbs); + } + printf("\n"); } /* @@ -844,14 +825,14 @@ print_bpb(struct bpb *bpb) static unsigned int argtou(const char *arg, unsigned int lo, unsigned int hi, const char *msg) { - char *s; - unsigned long x; - - errno = 0; - x = strtoul(arg, &s, 0); - if (errno || !*arg || *arg == '-' || isspace((unsigned char)*arg) || *s || x < lo || x > hi) - eprintf("%s: bad %s\n", arg, msg); - return x; + char *s; + unsigned long x; + + errno = 0; + x = strtoul(arg, &s, 0); + if (errno || !*arg || *arg == '-' || isspace((unsigned char)*arg) || *s || x < lo || x > hi) + eprintf("%s: bad %s\n", arg, msg); + return x; } /* @@ -860,14 +841,14 @@ argtou(const char *arg, unsigned int lo, unsigned int hi, const char *msg) static int oklabel(const char *src) { - int c = 0, i; - - for (i = 0; i <= 11; i++) { - c = (unsigned char)*src++; - if (c < ' ' + !i || strchr("\"*+,./:;<=>?[\\]|", c)) - break; - } - return i && !c; + int c = 0, i; + + for (i = 0; i <= 11; i++) { + c = (unsigned char)*src++; + if (c < ' ' + !i || strchr("\"*+,./:;<=>?[\\]|", c)) + break; + } + return i && !c; } /* @@ -876,12 +857,12 @@ oklabel(const char *src) static void mklabel(uint8_t *dest, const char *src) { - int c, i; + int c, i; - for (i = 0; i < 11; i++) { - c = *src ? toupper((unsigned char)*src++) : ' '; - *dest++ = !i && c == 0xe5 ? 5 : c; - } + for (i = 0; i < 11; i++) { + c = *src ? toupper((unsigned char)*src++) : ' '; + *dest++ = !i && c == 0xe5 ? 5 : c; + } } /* @@ -890,8 +871,8 @@ mklabel(uint8_t *dest, const char *src) static void setstr(uint8_t *dest, const char *src, size_t len) { - while (len--) - *dest++ = *src ? *src++ : ' '; + while (len--) + *dest++ = *src ? *src++ : ' '; } /* @@ -900,11 +881,13 @@ setstr(uint8_t *dest, const char *src, size_t len) static void __attribute__((noreturn)) usage(void) { - eprintf("usage: %s " - "[-N] [-a FAT-size] [-B boot] [-b block-size]\n" - "\t[-c cluster-size] [-e dirents] [-F FAT-type] [-f format]\n" - "\t[-h heads] [-I volid] [-i info] [-k backup] [-L label]\n" - "\t[-m media] [-n label] [-A FATs] [-O OEM] [-o hidden] [-r reserved]\n" - "\t[-S sector-size] [-s total] [-u track-size] device-or-image\n", - argv0); + eprintf( + "usage: %s " + "[-N] [-a FAT-size] [-B boot] [-b block-size]\n" + "\t[-c cluster-size] [-e dirents] [-F FAT-type] [-f format]\n" + "\t[-h heads] [-I volid] [-i info] [-k backup] [-L label]\n" + "\t[-m media] [-n label] [-A FATs] [-O OEM] [-o hidden] [-r reserved]\n" + "\t[-S sector-size] [-s total] [-u track-size] device-or-image\n", + argv0 + ); } diff --git a/cmd/extra/partplan.c b/cmd/extra/partplan.c @@ -11,16 +11,22 @@ #include <sys/wait.h> #include <unistd.h> -#define SECTORS_ZEROED 16384 /* 8 MiB at 512 byte sectors: old signatures that would be seen again */ +#define SECTORS_ZEROED \ + 16384 /* 8 MiB at 512 byte sectors: old signatures that would be seen again */ static void __attribute__((noreturn)) usage(void) { - eprintf("usage: %s guided [-s swap_mib] [-f root_fs] disk | disks | layout | read disk | new [-m] disk |\n" - " show plan | gaps plan | changes plan | check [-rb] plan | write plan | mkfs plan | mounts plan |\n" - " fstab plan | get plan esp|root|swap|bios|rootfs|rootuuid |\n" - " add [-t type] [-l label] plan size fs [mount] | delete plan n | set [-k] [-l label] plan n fs [mount]\n", - argv0); + eprintf( + "usage: %s guided [-s swap_mib] [-f root_fs] disk | disks | layout | read disk | new [-m] " + "disk |\n" + " show plan | gaps plan | changes plan | check [-rb] plan | write plan | mkfs plan | " + "mounts plan |\n" + " fstab plan | get plan esp|root|swap|bios|rootfs|rootuuid |\n" + " add [-t type] [-l label] plan size fs [mount] | delete plan n | set [-k] [-l label] " + "plan n fs [mount]\n", + argv0 + ); } static int @@ -45,7 +51,7 @@ static int do_disks(void) { static const char *const skip[] = {"loop", "ram", "zram", "sr", "fd", "dm-", "md", "nbd"}; - struct BlockDevInfo *list = blockdev_get_list(), *d; + struct BlockDevInfo *list = blockdev_get_list(), *d; for (d = list; d; d = d->next) { int busy = d->mountpoint[0] != '\0', skipped = 0; @@ -104,7 +110,13 @@ do_show(struct plan *p) { int i; - printf("%s, %s\n", p->disk, p->label.kind == LABEL_GPT ? "GPT" : p->label.kind == LABEL_MBR ? "MBR" : "no table"); + printf( + "%s, %s\n", + p->disk, + p->label.kind == LABEL_GPT ? "GPT" + : p->label.kind == LABEL_MBR ? "MBR" + : "no table" + ); for (i = 0; i < p->label.slots; i++) { const struct label_part *l = &p->label.part[i]; const struct plan_part *a = &p->attr[i]; @@ -114,7 +126,15 @@ do_show(struct plan *p) continue; plan_part_path(p->disk, i, dev, sizeof dev); plan_size((l->end - l->start + 1) * p->label.sec_size, size, sizeof size); - printf("%-14s %9s %-18s %-6s %-12s %s\n", dev, size, label_type_name(l), a->fs, a->mount, a->format ? "format" : ""); + printf( + "%-14s %9s %-18s %-6s %-12s %s\n", + dev, + size, + label_type_name(l), + a->fs, + a->mount, + a->format ? "format" : "" + ); } (void)show_line; return 0; @@ -181,7 +201,7 @@ do_mkfs(struct plan *p) int i, status = 0; for (i = 0; i < p->label.slots; i++) { - char dev[PLAN_PATH + 8]; + char dev[PLAN_PATH + 8]; pid_t pid; int st; @@ -245,7 +265,8 @@ fstab_source(const char *dev, char *out, size_t n) snprintf(out, n, "%s", dev); if (blockdev_open(&bd, dev, 0) < 0) return; - if (blockdev_detect_fs(&bd, type, sizeof type, label, sizeof label, uuid, sizeof uuid) == 0 && uuid[0]) + if (blockdev_detect_fs(&bd, type, sizeof type, label, sizeof label, uuid, sizeof uuid) == 0 + && uuid[0]) snprintf(out, n, "UUID=%s", uuid); blockdev_close(&bd); } @@ -257,7 +278,7 @@ do_fstab(struct plan *p) int slots[LABEL_SLOTS], n = plan_mount_order(p, slots, LABEL_SLOTS), i; for (i = 0; i < n; i++) { - const struct plan_fs *f = plan_filesystem(p->attr[slots[i]].fs); + const struct plan_fs *f = plan_filesystem(p->attr[slots[i]].fs); const char *mp = p->attr[slots[i]].mount; char path[PLAN_PATH + 8], dev[PLAN_PATH + 140]; @@ -319,10 +340,25 @@ sectors_of(const struct plan *p, const char *size) return 0; n = strtoull(size, &end, 10); switch (*end) { - case 'k': case 'K': mul = 1024; end++; break; - case 'm': case 'M': end++; break; - case 'g': case 'G': mul = 1048576ULL * 1024; end++; break; - case 't': case 'T': mul = 1048576ULL * 1024 * 1024; end++; break; + case 'k': + case 'K': + mul = 1024; + end++; + break; + case 'm': + case 'M': + end++; + break; + case 'g': + case 'G': + mul = 1048576ULL * 1024; + end++; + break; + case 't': + case 'T': + mul = 1048576ULL * 1024 * 1024; + end++; + break; } if (*end == 'i' || *end == 'I') end++; @@ -333,7 +369,8 @@ sectors_of(const struct plan *p, const char *size) return (n * mul + p->label.sec_size - 1) / p->label.sec_size; } -/* the type a filesystem is given when none is said: what a firmware, limine and a reader of the table expect */ +/* the type a filesystem is given when none is said: what a firmware, limine and a reader of the + * table expect */ static const char * type_of(const char *fs, const char *mount) { @@ -397,7 +434,12 @@ do_gaps(struct plan *p) for (i = 0; i < n; i++) { plan_size((gaps[i].end - gaps[i].start + 1) * p->label.sec_size, size, sizeof size); - printf("free %9s sectors %llu-%llu\n", size, (unsigned long long)gaps[i].start, (unsigned long long)gaps[i].end); + printf( + "free %9s sectors %llu-%llu\n", + size, + (unsigned long long)gaps[i].start, + (unsigned long long)gaps[i].end + ); } return 0; } @@ -446,11 +488,24 @@ do_add(int argc, char *argv[]) /* the BIOS boot partition holds no filesystem, it is only its type */ if (strcmp(fs, "bios") == 0 || strcmp(fs, "none") == 0) fs = ""; - snprintf(name, sizeof name, "%s", strcmp(type, "ef00") == 0 ? "ESP" : strcmp(type, "ef02") == 0 ? "BIOS" - : strcmp(type, "8200") == 0 ? "SWAP" : strcmp(mount, "/") == 0 ? "ROOT" : "DATA"); + snprintf( + name, + sizeof name, + "%s", + strcmp(type, "ef00") == 0 ? "ESP" + : strcmp(type, "ef02") == 0 ? "BIOS" + : strcmp(type, "8200") == 0 ? "SWAP" + : strcmp(mount, "/") == 0 ? "ROOT" + : "DATA" + ); slot = plan_add(p, 0, sectors_of(p, argv[1]), type, name, fs, mount, label); if (slot < 0) - eprintf("no room for %s, or %s %s is not a partition (gaps shows the room)\n", argv[1], argv[2], mount); + eprintf( + "no room for %s, or %s %s is not a partition (gaps shows the room)\n", + argv[1], + argv[2], + mount + ); save(p, argv[0]); printf("%d\n", slot + 1); free(p); @@ -500,7 +555,10 @@ do_set(int argc, char *argv[]) slot = slot_of(p, argv[1]); if (strcmp(argv[2], "none") == 0) argv[2] = ""; - if (plan_set(p, slot, argv[2], argc == 4 ? argv[3] : "", label ? label : p->attr[slot].label, !keep) < 0) + if (plan_set( + p, slot, argv[2], argc == 4 ? argv[3] : "", label ? label : p->attr[slot].label, !keep + ) + < 0) eprintf("%s is not a filesystem partplan makes, or its label is too long\n", argv[2]); save(p, argv[0]); free(p); diff --git a/cmd/extra/pgrep.c b/cmd/extra/pgrep.c @@ -41,9 +41,9 @@ static regex_t preg; static uid_t user_uid; static int have_user; static pid_t self; -static struct hit *hits; -static size_t nhits, hitscap; -static int count; +static struct hit *hits; +static size_t nhits, hitscap; +static int count; /* newest/oldest are mutually exclusive with each other and with * printing every match as it is found, so they buffer every match @@ -168,7 +168,8 @@ main(int argc, char *argv[]) if (invoked_as("pkill")) { killing = 1; // a leading -TERM or -9 is the signal, as kill takes it - if (argc > 1 && argv[1][0] == '-' && argv[1][1] && (isdigit((unsigned char)argv[1][1]) || isupper((unsigned char)argv[1][1]))) { + if (argc > 1 && argv[1][0] == '-' && argv[1][1] + && (isdigit((unsigned char)argv[1][1]) || isupper((unsigned char)argv[1][1]))) { if (isdigit((unsigned char)argv[1][1])) signo = (int)estrtonum(argv[1] + 1, 0, INT_MAX); else if (str2sig(argv[1] + 1, &signo) < 0) @@ -248,7 +249,7 @@ main(int argc, char *argv[]) pick = 0; for (i = 1; i < nhits; i++) { if (select_mode == PGREP_NEWEST ? hits[i].starttime > hits[pick].starttime - : hits[i].starttime < hits[pick].starttime) + : hits[i].starttime < hits[pick].starttime) pick = i; } if (parsestat(hits[pick].pid, &ps) == 0) diff --git a/cmd/extra/signify.c b/cmd/extra/signify.c @@ -16,20 +16,24 @@ static void usage(void) { - fprintf(stderr, - "usage: %s -G [-n] [-c comment] -p pubkey -s seckey\n" - " %s -S -s seckey -m message [-x sigfile]\n" - " %s -V [-q] -p pubkey -m message [-x sigfile]\n", - argv0, argv0, argv0); + fprintf( + stderr, + "usage: %s -G [-n] [-c comment] -p pubkey -s seckey\n" + " %s -S -s seckey -m message [-x sigfile]\n" + " %s -V [-q] -p pubkey -m message [-x sigfile]\n", + argv0, + argv0, + argv0 + ); exit(1); } static uint8_t * slurp(const char *path, size_t *n) { - FILE *fp = fopen(path, "rb"); + FILE *fp = fopen(path, "rb"); uint8_t *buf = NULL; - size_t cap = 0, r; + size_t cap = 0, r; if (!fp) eprintf("open %s:", path); @@ -50,10 +54,10 @@ int main(int argc, char *argv[]) { const char *pub = NULL, *sec = NULL, *msg = NULL, *sig = NULL, *comment = "signify"; - char sigbuf[4096]; - int mode = 0, quiet = 0; - uint8_t *m; - size_t n; + char sigbuf[4096]; + int mode = 0, quiet = 0; + uint8_t *m; + size_t n; ARGBEGIN { @@ -106,46 +110,46 @@ main(int argc, char *argv[]) sig = sigbuf; } switch (mode) { - case 'G': - if (!pub || !sec) - usage(); - return signify_generate(pub, sec, comment) != 0; - case 'S': { - struct signify_sec k; - const char *base; - char pubname[1024]; - size_t l; + case 'G': + if (!pub || !sec) + usage(); + return signify_generate(pub, sec, comment) != 0; + case 'S': { + struct signify_sec k; + const char *base; + char pubname[1024]; + size_t l; - if (!sec || !msg) - usage(); - if (signify_read_sec(sec, &k)) - return 1; - // the comment names the public key the way signify does: the secret - // key's name with .pub for .sec - base = strrchr(sec, '/'); - base = base ? base + 1 : sec; - l = strlen(base); - if (l > 4 && !strcmp(base + l - 4, ".sec")) - snprintf(pubname, sizeof(pubname), "%.*s.pub", (int)(l - 4), base); - else - snprintf(pubname, sizeof(pubname), "%s", base); - m = slurp(msg, &n); - return signify_sign(&k, m, n, pubname, sig) != 0; - } - case 'V': { - struct signify_pub k; + if (!sec || !msg) + usage(); + if (signify_read_sec(sec, &k)) + return 1; + // the comment names the public key the way signify does: the secret + // key's name with .pub for .sec + base = strrchr(sec, '/'); + base = base ? base + 1 : sec; + l = strlen(base); + if (l > 4 && !strcmp(base + l - 4, ".sec")) + snprintf(pubname, sizeof(pubname), "%.*s.pub", (int)(l - 4), base); + else + snprintf(pubname, sizeof(pubname), "%s", base); + m = slurp(msg, &n); + return signify_sign(&k, m, n, pubname, sig) != 0; + } + case 'V': { + struct signify_pub k; - if (!pub || !msg) - usage(); - if (signify_read_pub(pub, &k)) - return 1; - m = slurp(msg, &n); - if (signify_verify(&k, m, n, sig)) - return 1; - if (!quiet) - puts("Signature Verified"); - return 0; - } + if (!pub || !msg) + usage(); + if (signify_read_pub(pub, &k)) + return 1; + m = slurp(msg, &n); + if (signify_verify(&k, m, n, sig)) + return 1; + if (!quiet) + puts("Signature Verified"); + return 0; + } } usage(); } diff --git a/cmd/extra/yap/commands.c b/cmd/extra/yap/commands.c @@ -91,19 +91,19 @@ do_search(char *str, long cnt, int dir) if (str) { /* - * we have to get a pattern, which we have to prompt for - * with the string "str" - */ + * we have to get a pattern, which we have to prompt for + * with the string "str" + */ if ((p = readline(str)) == 0) { /* - * user cancelled command - */ + * user cancelled command + */ return; } if ((p = re_comp(p))) { /* - * there was an error in the pattern - */ + * there was an error in the pattern + */ error(p); return; } @@ -125,11 +125,11 @@ do_search(char *str, long cnt, int dir) } if (re_exec(p) && --cnt <= 0) { /* - * we found the pattern, and we found it often enough - * pity that we still dont know where the match is - * we only know the linenumber. so, we just hope the - * following will at least bring it on the screen ... - */ + * we found the pattern, and we found it often enough + * pity that we still dont know where the match is + * we only know the linenumber. so, we just hope the + * following will at least bring it on the screen ... + */ (void)display(lineno, 0, pagesize, 0); (void)scrollb(2, 0); redraw(0); @@ -209,10 +209,10 @@ shell_command(int esc_ch, long cnt) putline(TI); if (!p) { /* - * avoid double redraw - * after a "startcomm", a redraw will - * take place anyway - */ + * avoid double redraw + * after a "startcomm", a redraw will + * take place anyway + */ redraw(1); } } @@ -241,8 +241,8 @@ do_writefile(long cnt) if ((p = readline("Filename: ")) == 0 || !*p) { /* - * no file name given - */ + * no file name given + */ return 0; } if ((fd = open(p, O_CREAT | O_EXCL | O_WRONLY, 0644)) < 0) { @@ -288,9 +288,9 @@ do_absolute(long cnt) if (!getline(cnt, 0)) { /* not there or interrupt */ if (!interrupt) { /* - * user did'nt give an interrupt, so the line number - * was too high. go to the last line - */ + * user did'nt give an interrupt, so the line number + * was too high. go to the last line + */ do_lline(cnt); } return 0; @@ -314,8 +314,8 @@ do_visit(long cnt) visitfile(fn); } else { /* - * user typed a return. visit the current file - */ + * user typed a return. visit the current file + */ if (!(p = filenames[filecount])) { error("No current file"); return 0; @@ -347,9 +347,9 @@ prev_screen(int sz, int really) retval = scrollb(sz - 1, really && cflag); if (really && !cflag) { /* - * the previous call did not display anything, but at least we - * know where to start - */ + * the previous call did not display anything, but at least we + * know where to start + */ return display(scr_info.firstline, scr_info.nf, sz, 1); } return retval; @@ -405,9 +405,9 @@ do_forward(long cnt) i = page_size((unsigned)cnt); if (status & EOFILE) { /* - * may seem strange, but actually a visit to the next file - * has already been done here - */ + * may seem strange, but actually a visit to the next file + * has already been done here + */ (void)display(1L, 0, i, 1); return 0; } @@ -430,11 +430,11 @@ do_backward(long cnt) return 0; } /* - * the next part is a bit clumsy - * we want to display the last page of the previous file (for which - * a visit has already been done), but the pagesize may temporarily - * be different because the command had a count - */ + * the next part is a bit clumsy + * we want to display the last page of the previous file (for which + * a visit has already been done), but the pagesize may temporarily + * be different because the command had a count + */ temp = pagesize; pagesize = i; do_lline(cnt); @@ -458,18 +458,18 @@ do_lline(long cnt) if ((cnt = to_lastline()) < 0) { /* - * interrupted by the user - */ + * interrupted by the user + */ return 0; } /* - * display the page such that only the last line of the page is - * a "~", independant of the pagesize - */ + * display the page such that only the last line of the page is + * a "~", independant of the pagesize + */ while (!(display(cnt, i, j, 0) & EOFILE)) { /* - * the last line could of course be very long ... - */ + * the last line could of course be very long ... + */ i += j; } (void)scrollb(j - scr_info.tail->cnt, 0); @@ -671,8 +671,8 @@ lookup(char *s) u = &commands[sizeof(commands) / sizeof(*u) - 1]; do { /* - * perform binary search - */ + * perform binary search + */ m = l + (u - l) / 2; if (strcmp(s, m->c_cmd) > 0) l = m + 1; @@ -713,15 +713,15 @@ do_comm(int comm, long count) flags = pcomm->c_flags; /* - * check the command - * if the last line of the file is displayed and the command goes - * forwards and does'nt have the ability to go to the next file, it - * is an error - * if the first line of the file is displayed and the command goes - * backwards and does'nt have the ability to go to the previous file, - * it is an error - * also check wether we need the next or previous file. if so, get it - */ + * check the command + * if the last line of the file is displayed and the command goes + * forwards and does'nt have the ability to go to the next file, it + * is an error + * if the first line of the file is displayed and the command goes + * backwards and does'nt have the ability to go to the previous file, + * it is an error + * also check wether we need the next or previous file. if so, get it + */ if ((status & EOFILE) && (flags & AHEAD)) { if (qflag || !(flags & TONEXTFILE)) return; @@ -735,8 +735,8 @@ do_comm(int comm, long count) quit(); } /* - * does the command stick around for LASTCOMM? - */ + * does the command stick around for LASTCOMM? + */ if (flags & STICKY) { lastcomm = comm; lastcount = count; @@ -746,8 +746,8 @@ do_comm(int comm, long count) count = 1; } else { /* - * does the command adapt the screensize? - */ + * does the command adapt the screensize? + */ if (flags & SCREENSIZE_ADAPT) { temp = maxpagesize; if ((unsigned)count < (unsigned)temp) { @@ -760,8 +760,8 @@ do_comm(int comm, long count) pagesize = temp; } /* - * does the command adapt the scrollsize? - */ + * does the command adapt the scrollsize? + */ if (flags & SCROLLSIZE_ADAPT) { temp = maxpagesize - 1; if ((unsigned)count < (unsigned)temp) { @@ -772,7 +772,7 @@ do_comm(int comm, long count) } } /* - * now execute the command - */ + * now execute the command + */ (*(pcomm->c_func))(count); } diff --git a/cmd/extra/yap/display.c b/cmd/extra/yap/display.c @@ -110,10 +110,10 @@ display(long n, int nd, int nlines, int reallydispl) char *p; /* pointer to line to be displayed */ if (startcomm) { /* no displaying on a command from the - * yap command line. in this case, displaying - * will be done after executing the command, - * by a redraw - */ + * yap command line. in this case, displaying + * will be done after executing the command, + * by a redraw + */ reallydispl = 0; } if (!n) { @@ -135,8 +135,8 @@ display(long n, int nd, int nlines, int reallydispl) } } /* - * now, do computations and display - */ + * now, do computations and display + */ s->currentpos = 0; s->nf = nd; s->head = s->tail; @@ -145,15 +145,15 @@ display(long n, int nd, int nlines, int reallydispl) p = skiplines(getline(n, 1), nd); while (nlines && p) { /* - * while there is room, - * and there is something left to display ... - */ + * while there is room, + * and there is something left to display ... + */ (s->tail->cnt)++; nlines--; if (*(p = do_line(p, reallydispl)) == '\0') { /* - * file-line finished, get next one ... - */ + * file-line finished, get next one ... + */ p = getline(++n, 1); if (nlines && p) { s->tail = s->tail->next; @@ -185,37 +185,37 @@ scrollf(int n, int reallydispl) int i; /* - * first, find out how many screenlines of the last line were already - * on the screen, and possibly above it - */ + * first, find out how many screenlines of the last line were already + * on the screen, and possibly above it + */ if (n <= 0 || (status & EOFILE)) return status; if (startcomm) reallydispl = 0; /* - * find out where to begin displaying - */ + * find out where to begin displaying + */ i = s->tail->cnt; if ((ll = s->lastline) == s->firstline) i += s->nf; p = skiplines(getline(ll, 1), i); /* - * now, place the cursor at the first free line - */ + * now, place the cursor at the first free line + */ if (reallydispl && !stupid) { clrbline(); mgoto(s->currentpos); } /* - * now display lines, keeping track of which lines are on the screen - */ + * now display lines, keeping track of which lines are on the screen + */ while (n-- > 0) { /* there are still rows to be displayed */ if (!*p) { /* end of line, get next one */ if (!(p = getline(++ll, 1))) { /* - * no lines left. at end of file - */ + * no lines left. at end of file + */ break; } s->tail = s->tail->next; @@ -224,16 +224,16 @@ scrollf(int n, int reallydispl) } if (s->currentpos >= maxpagesize) { /* - * no room, delete first screen-line - */ + * no room, delete first screen-line + */ s->currentpos--; s->nf++; if (--(s->head->cnt) == 0) { /* - * the first file-line on the screen is wiped - * out completely; update administration - * accordingly - */ + * the first file-line on the screen is wiped + * out completely; update administration + * accordingly + */ s->nf = 0; s->head = s->head->next; assert(s->head->cnt > 0); @@ -261,8 +261,8 @@ scrollb(int n, int reallydispl) int cannotscroll; /* stupid or no insert-line */ /* - * first, find out where to start - */ + * first, find out where to start + */ if ((count = n) <= 0 || (status & START)) return status; if (startcomm) @@ -274,10 +274,10 @@ scrollb(int n, int reallydispl) i = nodispl; if (i) { /* - * there were screen-lines of s->firstline that were not - * displayed - * we can use them now, but only "count" of them - */ + * there were screen-lines of s->firstline that were not + * displayed + * we can use them now, but only "count" of them + */ if (i > count) i = count; s->currentpos += i; @@ -288,11 +288,11 @@ scrollb(int n, int reallydispl) break; /* isnt there ... */ p = getline(--ln, 1); /* - * make it the first line of the screen and compute - * how many screenlines it takes. these lines are not - * displayed, but nodispl is set to this count, so - * that it will be nonzero next time around - */ + * make it the first line of the screen and compute + * how many screenlines it takes. these lines are not + * displayed, but nodispl is set to this count, so + * that it will be nonzero next time around + */ nodispl = 0; do { /* find out how many screenlines */ nodispl++; @@ -306,33 +306,33 @@ scrollb(int n, int reallydispl) if (reallydispl && hardcopy) i = n; /* - * now that we know where to start, we can use "display" to do the - * rest of the computing for us, and maybe even the displaying ... - */ + * now that we know where to start, we can use "display" to do the + * rest of the computing for us, and maybe even the displaying ... + */ i = display(ln, nodispl, i, reallydispl && cannotscroll); if (cannotscroll || !reallydispl) { /* - * yes, "display" did the displaying, or we did'nt have to - * display at all - * i like it, but the user obviously does not - * let him buy another (smarter) terminal ... - */ + * yes, "display" did the displaying, or we did'nt have to + * display at all + * i like it, but the user obviously does not + * let him buy another (smarter) terminal ... + */ return i; } /* - * now, all we have to do is the displaying. and we are dealing with - * a smart terminal (it can insert lines or scroll back) - */ + * now, all we have to do is the displaying. and we are dealing with + * a smart terminal (it can insert lines or scroll back) + */ home(); /* - * insert lines all at once - */ + * insert lines all at once + */ for (i = n; i; i--) { if (DB && *CE) { /* - * grumble..., terminal retains lines below, so we have - * to clear the lines that we push off the screen - */ + * grumble..., terminal retains lines below, so we have + * to clear the lines that we push off the screen + */ clrbline(); home(); } @@ -397,13 +397,13 @@ do_line(char *str, int reallydispl) } if (uc < ' ' && (cell_len = match(str, &c2, sppat)) > 0) { /* - * we found a string that matches, and thus must be - * echoed literally - */ + * we found a string that matches, and thus must be + * echoed literally + */ if ((pos - c2) <= 0) { /* - * it did not fit - */ + * it did not fit + */ break; } pos -= c2; @@ -438,8 +438,8 @@ do_line(char *str, int reallydispl) } do_ul = 1; /* - * find underline sequences ... - */ + * find underline sequences ... + */ if (is_underscore && *cursor == '\b' && *(cursor + 1) != '\0') { cell_start = cursor + 1; cell_len = decode_cell(cell_start, &next, &cell_width, &is_underscore); @@ -519,9 +519,9 @@ do_line(char *str, int reallydispl) pos -= cell_width; if (reallydispl && do_ul && *UC && cell_width == 1 && pos > 0) { /* - * underlining apparently is done one - * character at a time - */ + * underlining apparently is done one + * character at a time + */ flush_display_buffer(buf, &p); backspace(); underchar(); @@ -537,13 +537,13 @@ do_line(char *str, int reallydispl) putline("\r\n"); } /* - * the next should be here! i.e. it may not be before printing - * the newline. this has to do with XN. we dont know exactly - * WHEN the terminal will stop ignoring the newline - * i have for example a terminal (ampex a230) that will - * continue to ignore the newline after a clear to end of line - * sequence, but not after an end_underline sequence - */ + * the next should be here! i.e. it may not be before printing + * the newline. this has to do with XN. we dont know exactly + * WHEN the terminal will stop ignoring the newline + * i have for example a terminal (ampex a230) that will + * continue to ignore the newline after a clear to end of line + * sequence, but not after an end_underline sequence + */ if (lastmode) { end_underline(); } diff --git a/cmd/extra/yap/getcomm.c b/cmd/extra/yap/getcomm.c @@ -41,19 +41,19 @@ readline(char *s) while ((ch = getch()) != '\n' && ch != '\r') { if (ch == -1) { /* - * can only occur because of an interrupted read - */ + * can only occur because of an interrupted read + */ ch = erasech; interrupt = 0; } if (ch == erasech) { /* - * erase last char - */ + * erase last char + */ if (p == buf) { /* - * there was none, so return - */ + * there was none, so return + */ return (char *)0; } pos -= killchar(*--p); @@ -62,8 +62,8 @@ readline(char *s) } if (ch == killch) { /* - * erase the whole line - */ + * erase the whole line + */ if (!(p > buf && *(p - 1) == '\\')) { while (p > buf) { pos -= killchar(*--p); @@ -74,9 +74,9 @@ readline(char *s) } if (p > &buf[78] || pos >= COLS - 2) { /* - * line does not fit - * simply refuse to make it any longer - */ + * line does not fit + * simply refuse to make it any longer + */ pos -= killchar(*--p); } *p++ = ch; @@ -134,14 +134,14 @@ shellescape(char *p, int esc_char) cnt = 253; while (*p) { /* - * expand command - */ + * expand command + */ switch (*p++) { case '!': /* - * an unescaped ! expands to the previous - * command, but disappears if there is none - */ + * an unescaped ! expands to the previous + * command, but disappears if there is none + */ if (lastc != '\\') { if (*previous) { id = strlen(previous); @@ -156,9 +156,9 @@ shellescape(char *p, int esc_char) continue; case '%': /* - * an unescaped % will expand to the current - * filename, but disappears is there is none - */ + * an unescaped % will expand to the current + * filename, but disappears is there is none + */ if (lastc != '\\') { if (nopipe) { id = strlen(currentfile); @@ -184,8 +184,8 @@ shellescape(char *p, int esc_char) *p2 = '\0'; if (!stupid) { /* - * display expanded command - */ + * display expanded command + */ cputline(comm); putline("\r\n"); } @@ -225,8 +225,8 @@ shellescape(char *p, int esc_char) } while ((lastc = wait((int *)0)) != id && lastc >= 0) { /* - * wait for child, making sure it is the one we expected ... - */ + * wait for child, making sure it is the one we expected ... + */ } (void)signal(SIGINT, catchdel); (void)signal(SIGQUIT, sigquit); @@ -268,14 +268,14 @@ getcomm(long *plong) for (;;) { if (c == -1) { /* - * this should never happen, but it does, - * when the user gives a TSTP signal (^z) or - * an interrupt while the program is trying - * to read a character from the terminal - * in this case, the read is interrupted, so - * we end up here - * right, we will have to read again - */ + * this should never happen, but it does, + * when the user gives a TSTP signal (^z) or + * an interrupt while the program is trying + * to read a character from the terminal + * in this case, the read is interrupted, so + * we end up here + * right, we will have to read again + */ if (interrupt) return 1; break; @@ -284,15 +284,15 @@ getcomm(long *plong) *p = 0; if ((i = match(buf, &j, currmap->k_mach)) > 0) { /* - * the key sequence matched. we have a command - */ + * the key sequence matched. we have a command + */ return j; } if (i == 0) return 0; /* - * we have a prefix of a command - */ + * we have a prefix of a command + */ assert(i == FSM_ISPREFIX); c = getch(); } diff --git a/cmd/extra/yap/getline.c b/cmd/extra/yap/getline.c @@ -44,16 +44,16 @@ new_block(void) if (!maxblocklist || !(pblock->b_flags & PARTLY)) { /* - * there is no last block, or it was filled completely, - * so allocate a new blockheader - */ + * there is no last block, or it was filled completely, + * so allocate a new blockheader + */ int siz; pblock = blocklist; if (maxblocklist == topblocklist) { /* - * no blockheaders left. allocate new ones - */ + * no blockheaders left. allocate new ones + */ siz = topblocklist - pblock; blocklist = pblock = (struct block *)re_alloc((char *)pblock, (unsigned)((siz + CHUNK) * sizeof(*pblock))); @@ -67,8 +67,8 @@ new_block(void) } if (!siz) { /* - * create dummy header cell - */ + * create dummy header cell + */ maxblocklist++; } } @@ -91,17 +91,17 @@ getblock(long n, int disable_interrupt) if (stdf < 0) { /* - * not file descriptor, so return end of file - */ + * not file descriptor, so return end of file + */ return 0; } pblock = maxblocklist - 1; if (n < lastreadline || (n == lastreadline && !(pblock->b_flags & PARTLY))) { /* - * the line asked for has been read already - * perform binary search in the blocklist to find the block - * where its in - */ + * the line asked for has been read already + * perform binary search in the blocklist to find the block + * where its in + */ struct block *min, *mid; min = blocklist + 1; @@ -117,8 +117,8 @@ getblock(long n, int disable_interrupt) } /* - * the line was'nt read yet, so read blocks until found - */ + * the line was'nt read yet, so read blocks until found + */ for (;;) { if (interrupt && !disable_interrupt) return 0; @@ -128,9 +128,9 @@ getblock(long n, int disable_interrupt) } if (pblock->b_flags & PARTLY) { /* - * we did not find it, and the last block could not be - * read completely, so return 0; - */ + * we did not find it, and the last block could not be + * read completely, so return 0; + */ return 0; } } @@ -158,10 +158,10 @@ to_lastline(void) for (;;) { if (!getline(lastreadline + 1, 0)) { /* - * "lastreadline" always contains the linenumber of - * the last line read. so, if the call to getline - * succeeds, "lastreadline" is affected - */ + * "lastreadline" always contains the linenumber of + * the last line read. so, if the call to getline + * succeeds, "lastreadline" is affected + */ if (interrupt) return -1L; return lastreadline; @@ -220,27 +220,27 @@ nextblock(struct block *pblock) if (pblock->b_flags & PARTLY) { /* - * the block was already partly filled. initialize locals - * accordingly - */ + * the block was already partly filled. initialize locals + * accordingly + */ poff = savedpoff; siz = savedsiz; pblock->b_flags = 0; c1 = savedc1; if (c1 == pblock->b_info || *(c1 - 1)) { /* - * we had incremented "lastreadline" temporarily, - * because the last line could not be completely read - * last time we tried. undo this increment - */ + * we had incremented "lastreadline" temporarily, + * because the last line could not be completely read + * last time we tried. undo this increment + */ poff--; --lastreadline; } } else { if (saved) { /* - * there were leftovers from the previous block - */ + * there were leftovers from the previous block + */ pblock->b_info = saved; c1 = savedc1; saved = 0; @@ -248,8 +248,8 @@ nextblock(struct block *pblock) pblock->b_info = c1 = alloc(BLOCKSIZE + 1); } /* - * allocate some space for line-offsets - */ + * allocate some space for line-offsets + */ pblock->b_offs = poff = (int *)alloc((unsigned)(100 * sizeof(int))); siz = 99; *poff++ = 0; @@ -257,13 +257,13 @@ nextblock(struct block *pblock) c = c1; for (;;) { /* - * read loop - */ + * read loop + */ cnt = read(stdf, c1, BLOCKSIZE - (c1 - pblock->b_info)); if (cnt < 0) { /* - * interrupted read - */ + * interrupted read + */ if (errno == EINTR) continue; error("Could not read input file"); @@ -279,22 +279,22 @@ nextblock(struct block *pblock) assert(c <= c1); while (c < c1) { /* - * now process the block - */ + * now process the block + */ if (*c == '\n') { /* - * newlines are replaced by '\0', so that "getline" - * can deliver one line at a time - */ + * newlines are replaced by '\0', so that "getline" + * can deliver one line at a time + */ *c = 0; lastreadline++; /* - * remember the line-offset - */ + * remember the line-offset + */ if (poff == pblock->b_offs + siz) { /* - * no space for it, allocate some more - */ + * no space for it, allocate some more + */ pblock->b_offs = (int *)re_alloc((char *)pblock->b_offs, (unsigned)((siz + 51) * sizeof(int))); poff = pblock->b_offs + siz; @@ -308,15 +308,15 @@ nextblock(struct block *pblock) *c = 0; if (c != pblock->b_info && *(c - 1) != 0) { /* - * the last line read does not end with a newline, so add one - */ + * the last line read does not end with a newline, so add one + */ lastreadline++; *poff++ = c - pblock->b_info + 1; if (!(pblock->b_flags & PARTLY) && *(poff - 2) != 0) { /* - * save the started line; it will be in the next block - * remove the newline we added just now - */ + * save the started line; it will be in the next block + * remove the newline we added just now + */ saved = c1 = alloc(BLOCKSIZE + 1); c = pblock->b_info + *(--poff - 1); while (*c) @@ -329,9 +329,9 @@ nextblock(struct block *pblock) pblock->b_end = lastreadline; if (pblock->b_flags & PARTLY) { /* - * take care, that we can call "nextblock" again, to fill in - * the rest of this block - */ + * take care, that we can call "nextblock" again, to fill in + * the rest of this block + */ savedsiz = siz; savedpoff = poff; savedc1 = c; @@ -391,17 +391,17 @@ getch(void) flush(); if (startcomm) { /* - * command line option command - */ + * command line option command + */ if (*startcomm) return *startcomm++; return '\n'; } if (stdf >= 0) { /* - * make reads from the terminal non-blocking, so that - * we can see if the user typed something - */ + * make reads from the terminal non-blocking, so that + * we can see if the user typed something + */ flags = fcntl(0, F_GETFL, 0); if (flags != -1 && fcntl(0, F_SETFL, flags | O_NONBLOCK) != -1) { bytes_read = 0; @@ -417,18 +417,18 @@ getch(void) (nopipe || (fstat(stdf, &buf) >= 0 && buf.st_size > 0))) { /* - * do some read ahead, after making sure there - * is input and the user did not type a command - */ + * do some read ahead, after making sure there + * is input and the user did not type a command + */ new_block(); } (void)fcntl(0, F_SETFL, flags); if (bytes_read < 0) { /* - * could this have happened? - * i'm not sure, because the read is - * nonblocking. can it be interrupted then? - */ + * could this have happened? + * i'm not sure, because the read is + * nonblocking. can it be interrupted then? + */ return -1; } if (bytes_read > 0) diff --git a/cmd/extra/yap/help.c b/cmd/extra/yap/help.c @@ -36,8 +36,8 @@ pr_comm(void) c = p->s_char & 0177; if (c < ' ' || c == 0177) { /* - * will take an extra position - */ + * will take an extra position + */ i++; } *pb++ = c; @@ -73,8 +73,8 @@ pr_mach(struct state *currstate, struct state *back) } if (!currstate->s_match) { /* - * end state, print command - */ + * end state, print command + */ pr_comm(); putline(commands[currstate->s_cnt].c_descr); putline("\r\n"); diff --git a/cmd/extra/yap/keys.c b/cmd/extra/yap/keys.c @@ -53,19 +53,19 @@ compile(char *map, struct keymap *commtable) } if (!*map) { /* - * mnemonic should end with '=' - */ + * mnemonic should end with '=' + */ return kerror(mark, ": Syntax error"); } *map++ = 0; while (*map) { /* - * get key sequence - */ + * get key sequence + */ if (*map == ':') { /* - * end of key sequence - */ + * end of key sequence + */ map++; break; } @@ -73,8 +73,8 @@ compile(char *map, struct keymap *commtable) if (*c == '^' || *c == '\\') { if (!(temp = *map++)) { /* - * escape not followed by a character - */ + * escape not followed by a character + */ return kerror(mark, ": Syntax error"); } if (*c == '^') { @@ -109,9 +109,9 @@ compile(char *map, struct keymap *commtable) assert(temp == FSM_OKE); if (!strcmp(mark, "hlp")) { /* - * create an error message to be given when the user - * types an illegal command - */ + * create an error message to be given when the user + * types an illegal command + */ (void)strcpy(commtable->k_help, "Type "); (void)strcat(commtable->k_help, buf); (void)strcat(commtable->k_help, " for help"); @@ -139,8 +139,8 @@ initkeys(void) if (p) { if (!(p = compile(p, othermap))) { /* - * no errors in user defined keymap. so, use it - */ + * no errors in user defined keymap. so, use it + */ do_chkm(0L); return; } @@ -162,8 +162,8 @@ is_escape(int c) } static char keyset[16]; /* bitset indicating which keys are - * used - */ + * used + */ /* * mark key "key" as used */ diff --git a/cmd/extra/yap/machine.c b/cmd/extra/yap/machine.c @@ -21,8 +21,8 @@ addtomach(char *s, int cnt, struct state **list) l = *list; if (!l) { /* - * create new list element - */ + * create new list element + */ *list = l = (struct state *)alloc(sizeof(*l)); l->s_char = *s; l->s_endstate = 0; @@ -31,21 +31,21 @@ addtomach(char *s, int cnt, struct state **list) } if (l->s_char == *s) { /* - * continue with next character - */ + * continue with next character + */ if (!*++s) { /* - * no next character - */ + * no next character + */ j = l->s_endstate; l->s_endstate = 1; if (l->s_match || j) { /* - * if the state already was an endstate, - * or has a successor, the currently - * added string is a prefix of an - * already recognized string - */ + * if the state already was an endstate, + * or has a successor, the currently + * added string is a prefix of an + * already recognized string + */ return FSM_ISPREFIX; } l->s_cnt = cnt; @@ -53,10 +53,10 @@ addtomach(char *s, int cnt, struct state **list) } if (l->s_endstate) { /* - * in this case, the currently added string has - * a prefix that is an already recognized - * string - */ + * in this case, the currently added string has + * a prefix that is an already recognized + * string + */ i = FSM_HASPREFIX; } list = &(l->s_match); @@ -98,9 +98,9 @@ match(char *s, int *i, struct state *mach) while (mach && *s1) { if (mach->s_char == *s1) { /* - * current character matches. carry on with next - * character and next state - */ + * current character matches. carry on with next + * character and next state + */ mach1 = mach; mach = mach->s_match; s1++; @@ -110,21 +110,21 @@ match(char *s, int *i, struct state *mach) } if (!mach1) { /* - * no characters matched - */ + * no characters matched + */ return 0; } if (mach1->s_endstate) { /* - * the string matched - */ + * the string matched + */ *i = mach1->s_cnt; return s1 - s; } if (!*s1) { /* - * the string matched a prefix - */ + * the string matched a prefix + */ return FSM_ISPREFIX; } return 0; diff --git a/cmd/extra/yap/main.c b/cmd/extra/yap/main.c @@ -68,8 +68,8 @@ initialize(int x) { if (!(nopipe = x)) { /* - * reading from pipe - */ + * reading from pipe + */ if (isatty(0)) { return 1; } @@ -77,8 +77,8 @@ initialize(int x) if (no_tty) return 0; /* - * make sure standard input is from the terminal - */ + * make sure standard input is from the terminal + */ (void)close(0); if (open("/dev/tty", O_RDONLY, 0) != 0) { putline("Couldn't open terminal\n"); @@ -89,9 +89,9 @@ initialize(int x) if (no_tty) return 0; /* - * handle signals - * catch QUIT, DELETE and ^z - */ + * handle signals + * catch QUIT, DELETE and ^z + */ (void)signal(SIGQUIT, SIG_IGN); (void)signal(SIGINT, catchdel); ini_terminal(); @@ -134,12 +134,12 @@ suspend(void) (void)signal(SIGTSTP, SIG_DFL); (void)kill(0, SIGTSTP); /* - * we are not here anymore ... - * - * - * - * but we arive here ... - */ + * we are not here anymore ... + * + * + * + * but we arive here ... + */ inittty(); putline(TI); flush(); diff --git a/cmd/extra/yap/options.c b/cmd/extra/yap/options.c @@ -31,8 +31,8 @@ readoptions(char **argv) while (*av && **av == '-') { if (parsopt(*av)) { /* - * error in option - */ + * error in option + */ putline(*av); putline(": illegal option\n"); return (char **)0; @@ -41,8 +41,8 @@ readoptions(char **argv) } if (*av && **av == '+') { /* - * command in command line - */ + * command in command line + */ startcomm = *av + 1; av++; } @@ -58,8 +58,8 @@ parsopt(char *s) s++; if (isdigit(*s)) { /* - * pagesize option - */ + * pagesize option + */ i = 0; do { i = i * 10 + *s++ - '0'; diff --git a/cmd/extra/yap/process.c b/cmd/extra/yap/process.c @@ -32,8 +32,8 @@ visitfile(char *fn) if (stdf > 0) { /* - * close old input file - */ + * close old input file + */ (void)close(stdf); } currentfile = fn; @@ -61,12 +61,12 @@ processfiles(int n, char **argv) if (!(nfiles = n)) { /* - * input from pipe - */ + * input from pipe + */ currentfile = "standard-input"; /* - * take care that *(filenames - 1) and *(filenames + 1) are 0 - */ + * take care that *(filenames - 1) and *(filenames + 1) are 0 + */ filenames = &dummies[1]; d_clean(); do_clean(); diff --git a/cmd/extra/yap/prompt.c b/cmd/extra/yap/prompt.c @@ -50,8 +50,8 @@ give_prompt(void) } if (!stupid) { /* - * fancy prompt - */ + * fancy prompt + */ clrbline(); standout(); pb = copy(pb, &buf[255], display_basename(currentfile, filebuf, sizeof(filebuf))); @@ -66,8 +66,8 @@ give_prompt(void) } if (errorgiven) { /* - * display error message - */ + * display error message + */ pb = copy(pb, &buf[255], " "); pb = copy(pb, &buf[255], errorgiven); if (stupid) { @@ -79,8 +79,8 @@ give_prompt(void) name = &filenames[filecount]; if (status) { /* - * indicate top and/or bottom - */ + * indicate top and/or bottom + */ if (status & START) { if (!*(name - 1)) { pb = copy(pb, &buf[255], "Top"); diff --git a/cmd/extra/yap/term.c b/cmd/extra/yap/term.c @@ -228,8 +228,8 @@ ini_terminal(void) hardcopy = getflag("hc"); /* hard copy terminal? */ if (*(s = getcap("cub1"))) { /* - * backspace if not ^h - */ + * backspace if not ^h + */ BC = s; } UP = getcap("cuu1"); /* move up a line */ @@ -260,8 +260,8 @@ ini_terminal(void) mr = getcap("rev"); /* reversed video attribute */ if (!nflag) { /* - * recognize special strings - */ + * recognize special strings + */ (void)addstring(SO, SG, &sppat); (void)addstring(SE, SG, &sppat); (void)addstring(US, UG, &sppat); @@ -297,14 +297,14 @@ ini_terminal(void) } if (*(s = getcap("ht"))) { /* - * tab (other than ^i or padding) - */ + * tab (other than ^i or padding) + */ TA = s; } if (!*(ll = getcap("ll")) && *CM && i > 0) { /* - * lower left hand corner - */ + * lower left hand corner + */ BO = tiparm(CM, i - 1, 0); } else BO = ll; @@ -331,16 +331,16 @@ ini_terminal(void) } /* - * the next part does not really belong here, but there it is ... - * initialize a circular list for the screenlines - */ + * the next part does not really belong here, but there it is ... + * initialize a circular list for the screenlines + */ scr_info.tail = lp = _X; lp1 = lp + (100 - 1); for (; lp <= lp1; lp++) { /* - * circular doubly linked list - */ + * circular doubly linked list + */ lp->next = lp + 1; lp->prev = lp - 1; } @@ -366,13 +366,13 @@ mgoto(int n) bottom(); else if (*CM) { /* - * cursor addressing - */ + * cursor addressing + */ tputs(tiparm(CM, n, 0), 1, fputch); } else if (*BO && *UP && n >= (maxpagesize >> 1)) { /* - * bottom and then up - */ + * bottom and then up + */ bottom(); while (n++ < maxpagesize) putline(UP); @@ -397,8 +397,8 @@ clrbline(void) bottom(); if (*CE) { /* - * we can clear to end of line - */ + * we can clear to end of line + */ clrtoeol(); return; } diff --git a/cmd/linux/mdev.c b/cmd/linux/mdev.c @@ -48,9 +48,9 @@ struct rule { uid_t uid; gid_t gid; mode_t mode; - char place; /* 0, '=' to move the node, '>' to move it and link it back, '!' for none */ + char place; /* 0, '=' to move the node, '>' to move it and link it back, '!' for none */ char path[PATH_MAX]; - char when; /* 0, '@' after it is added, '$' before it goes, '*' both */ + char when; /* 0, '@' after it is added, '$' before it goes, '*' both */ char cmd[512]; }; @@ -211,7 +211,7 @@ matches(const struct rule *r, const struct event *e, const char *name) static void parents(const char *path) { - char d[PATH_MAX], *s; + char d[PATH_MAX], *s; estrlcpy(d, path, sizeof d); for (s = d + 1; (s = strchr(s, '/')); s++) { @@ -260,7 +260,9 @@ node(const struct rule *r, const char *name, int adding) } else { /* a path ending in / keeps the name under it */ if (r->path[strlen(r->path) - 1] == '/') - snprintf(to, sizeof to, "/dev/%s%s", r->path, strrchr(name, '/') ? strrchr(name, '/') + 1 : name); + snprintf( + to, sizeof to, "/dev/%s%s", r->path, strrchr(name, '/') ? strrchr(name, '/') + 1 : name + ); else snprintf(to, sizeof to, "/dev/%s", r->path); if (adding) { @@ -303,8 +305,8 @@ handle(const struct event *e) continue; if (name) node(r, name, adding); - if ((r->when == '@' && !strcmp(action, "add")) || (r->when == '$' && removing) || - (r->when == '*' && (!strcmp(action, "add") || removing))) + if ((r->when == '@' && !strcmp(action, "add")) || (r->when == '$' && removing) + || (r->when == '*' && (!strcmp(action, "add") || removing))) command(r, e, name); if (!r->cont) break; diff --git a/cmd/linux/mkswap.c b/cmd/linux/mkswap.c @@ -43,9 +43,9 @@ main(int argc, char *argv[]) long pagesize; char *buf; struct swap_hdr *hdr; - uint64_t bytes = 0; - char *label = NULL; - char *uuid_str = NULL; + uint64_t bytes = 0; + char *label = NULL; + char *uuid_str = NULL; char uuid_out[37] = {0}; ARGBEGIN @@ -97,10 +97,27 @@ main(int argc, char *argv[]) if (uuid_str) { unsigned int u[16]; - if (sscanf(uuid_str, - "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", - &u[0], &u[1], &u[2], &u[3], &u[4], &u[5], &u[6], &u[7], - &u[8], &u[9], &u[10], &u[11], &u[12], &u[13], &u[14], &u[15]) == 16) { + if (sscanf( + uuid_str, + "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", + &u[0], + &u[1], + &u[2], + &u[3], + &u[4], + &u[5], + &u[6], + &u[7], + &u[8], + &u[9], + &u[10], + &u[11], + &u[12], + &u[13], + &u[14], + &u[15] + ) + == 16) { int i; for (i = 0; i < 16; i++) hdr->uuid[i] = (unsigned char)u[i]; @@ -121,14 +138,32 @@ main(int argc, char *argv[]) memcpy(buf + pagesize - 10, "SWAPSPACE2", 10); - snprintf(uuid_out, sizeof(uuid_out), - "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", - hdr->uuid[0], hdr->uuid[1], hdr->uuid[2], hdr->uuid[3], - hdr->uuid[4], hdr->uuid[5], hdr->uuid[6], hdr->uuid[7], - hdr->uuid[8], hdr->uuid[9], hdr->uuid[10], hdr->uuid[11], - hdr->uuid[12], hdr->uuid[13], hdr->uuid[14], hdr->uuid[15]); - - printf("Setting up swapspace version 1, size = %luKiB\n", (unsigned long)(pages - 1) * pagesize / 1024); + snprintf( + uuid_out, + sizeof(uuid_out), + "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", + hdr->uuid[0], + hdr->uuid[1], + hdr->uuid[2], + hdr->uuid[3], + hdr->uuid[4], + hdr->uuid[5], + hdr->uuid[6], + hdr->uuid[7], + hdr->uuid[8], + hdr->uuid[9], + hdr->uuid[10], + hdr->uuid[11], + hdr->uuid[12], + hdr->uuid[13], + hdr->uuid[14], + hdr->uuid[15] + ); + + printf( + "Setting up swapspace version 1, size = %luKiB\n", + (unsigned long)(pages - 1) * pagesize / 1024 + ); if (hdr->volume_name[0]) printf("LABEL=%s, ", hdr->volume_name); printf("UUID=%s\n", uuid_out); diff --git a/cmd/linux/modprobe.c b/cmd/linux/modprobe.c @@ -675,7 +675,7 @@ main(int argc, char *argv[]) read_configs(); /* traverse all provided or default base directories for symbol, alias, - * and dependency tracking */ + * and dependency tracking */ for (pn = moddirs; pn; pn = pn->next) { if (chdir(pn->str) < 0) { pr_warn("chdir %s:", pn->str); diff --git a/cmd/linux/mount.c b/cmd/linux/mount.c @@ -209,10 +209,17 @@ resolve_source(const char *src, char *buf, size_t bufsz) for (part = cur->parts; part; part = part->next) { if (blockdev_open(&dev, part->path, 0) != 0) continue; - if (blockdev_detect_fs(&dev, dev_type, sizeof(dev_type), dev_label, - sizeof(dev_label), dev_uuid, sizeof(dev_uuid)) == 0 && - ((is_label && strcmp(dev_label, target_val) == 0) || - (!is_label && strcasecmp(dev_uuid, target_val) == 0))) { + if (blockdev_detect_fs( + &dev, + dev_type, + sizeof(dev_type), + dev_label, + sizeof(dev_label), + dev_uuid, + sizeof(dev_uuid) + ) == 0 + && ((is_label && strcmp(dev_label, target_val) == 0) + || (!is_label && strcasecmp(dev_uuid, target_val) == 0))) { blockdev_close(&dev); estrlcpy(buf, part->path, bufsz); blockdev_free_list(list); @@ -221,8 +228,16 @@ resolve_source(const char *src, char *buf, size_t bufsz) blockdev_close(&dev); } if (blockdev_open(&dev, cur->path, 0) == 0) { - if (blockdev_detect_fs(&dev, dev_type, sizeof(dev_type), dev_label, - sizeof(dev_label), dev_uuid, sizeof(dev_uuid)) == 0) { + if (blockdev_detect_fs( + &dev, + dev_type, + sizeof(dev_type), + dev_label, + sizeof(dev_label), + dev_uuid, + sizeof(dev_uuid) + ) + == 0) { if (is_label && strcmp(dev_label, target_val) == 0) { blockdev_close(&dev); estrlcpy(buf, cur->path, bufsz); @@ -466,8 +481,8 @@ mountall: } parseopts(fsopts, &flags, data, sizeof(data)); /* if -t types specified: - * if non-match, skip - * if match and prefixed with "no", skip */ + * if non-match, skip + * if match and prefixed with "no", skip */ if (types && ((types[0] == 'n' && types[1] == 'o' && findtype(types + 2, me->mnt_type)) || (!findtype(types, me->mnt_type)))) diff --git a/cmd/posix/awk/awk.h b/cmd/posix/awk/awk.h @@ -56,8 +56,8 @@ typedef unsigned char uschar; #define setptr(ptr, a) (*(char *)(intptr_t)(ptr)) = (a) #define NN(p) \ - ((p) ? (p) : "(null)") /* guaranteed non-null for DPRINTF \ - */ + ((p) ? (p) : "(null)") /* guaranteed non-null for DPRINTF \ + */ #define DEBUG #ifdef DEBUG #define DPRINTF(...) \ diff --git a/cmd/posix/awk/b.c b/cmd/posix/awk/b.c @@ -75,7 +75,7 @@ static const uschar *lastre; /* origin of last re */ static const uschar *lastatom; /* origin of last atom */ static const uschar *starttok; static const uschar *basestr; /* starts with original, replaced during - * repetition processing */ + * repetition processing */ static const uschar *firstbasestr; static int setcnt; @@ -452,7 +452,7 @@ cclenter(const char *argp) /* add a character class */ p += n; if (c2 == '\\') c2 = quoted(&p); /* BUG: sets p, has to - * be u8 size */ + * be u8 size */ if (c > c2) { /* empty; ignore */ bp--; i--; @@ -494,7 +494,7 @@ cclenter(const char *argp) /* add a character class */ } *bp = 0; /* dprintf("cclenter: in = |%s|, out = |%s|\n", op, buf); BUG: cant - * print array of int */ + * print array of int */ /* xfree(op); BUG: what are we freeing here? */ retp = (int *)calloc(bp - buf + 1, sizeof(int)); for (i = 0; i < bp - buf + 1; i++) @@ -510,7 +510,7 @@ overflo(const char *s) void cfoll(fa *f, Node *v) /* enter follow set of each leaf of vertex v into - * lfollow[leaf] */ + * lfollow[leaf] */ { int i; int *p; @@ -911,20 +911,20 @@ fnematch(fa *pfa, FILE *f, char **pbuf, int *pbufsize, int quantum) patlen = 0; /* - * buf <= i <= j <= k <= buf+bufsize - * - * i: origin of active substring - * j: current character - * k: destination of the next getc - */ + * buf <= i <= j <= k <= buf+bufsize + * + * i: origin of active substring + * j: current character + * k: destination of the next getc + */ i = j = k = buf; do { /* - * call u8_rune with at least awk_mb_cur_max ahead in - * the buffer until EOF interferes - */ + * call u8_rune with at least awk_mb_cur_max ahead in + * the buffer until EOF interferes + */ if (k - j < (int)awk_mb_cur_max) { if (k + awk_mb_cur_max > buf + bufsize) { char *obuf = buf; @@ -980,16 +980,16 @@ fnematch(fa *pfa, FILE *f, char **pbuf, int *pbufsize, int quantum) if (patlen) { /* - * under no circumstances is the last character fed to - * the automaton part of the match. it is eof's nullbyte, - * or it sent the automaton into a state with no further - * transitions available (s==1), or both. room for a - * terminating nullbyte is guaranteed - * - * ungetc any chars after the end of matching text - * (except for eof's nullbyte, if present) and null - * terminate the buffer - */ + * under no circumstances is the last character fed to + * the automaton part of the match. it is eof's nullbyte, + * or it sent the automaton into a state with no further + * transitions available (s==1), or both. room for a + * terminating nullbyte is guaranteed + * + * ungetc any chars after the end of matching text + * (except for eof's nullbyte, if present) and null + * terminate the buffer + */ do if (*--k && ungetc(*k, f) == EOF) FATAL("unable to ungetc '%c'", *k); @@ -1212,7 +1212,7 @@ replace_repeat( int init_q = (firstnum == 0); /* first added char will be ? */ int n_q_reps = secondnum - firstnum; /* m>n, so reduce until {1,m-n} left */ int prefix_length = reptok - basestr; /* prefix includes first rep - */ + */ int suffix_length = strlen((const char *)reptok) - reptoklen; /* string after rep specifier */ int size = prefix_length + suffix_length; @@ -1283,12 +1283,12 @@ repeat( return 0; /* - * in general, the repetition specifier or "bound" is replaced here - * by an equivalent ERE string, repeating the immediately previous atom - * and appending ? and + as needed. note that the first copy of the - * atom is left in place, except in the special_case of a zero-repeat - * (i.e., {0}) - */ + * in general, the repetition specifier or "bound" is replaced here + * by an equivalent ERE string, repeating the immediately previous atom + * and appending ? and + as needed. note that the first copy of the + * atom is left in place, except in the special_case of a zero-repeat + * (i.e., {0}) + */ if (secondnum < 0) { /* means {n,} -> repeat n-1 times followed by PLUS */ if (firstnum < 2) { /* 0 or 1: should be handled before you get here */ @@ -1301,8 +1301,8 @@ repeat( } else if (firstnum == secondnum) { /* {n} or {n,n} -> simply repeat n-1 times */ if (firstnum == 0) { /* {0} or {0,0} */ /* this case is unusual because the resulting - * replacement string might actually be SMALLER than - * the original ERE */ + * replacement string might actually be SMALLER than + * the original ERE */ return replace_repeat(reptok, reptoklen, atom, atomlen, firstnum, secondnum, REPEAT_ZERO); } else { /* (firstnum >= 1) */ return replace_repeat(reptok, reptoklen, atom, atomlen, firstnum, secondnum, REPEAT_SIMPLE); @@ -1403,10 +1403,10 @@ rescan: *bp++ = c; /* } else if (c == '\n') { */ /* fatal("newline in character class - * %.20s...", lastre); */ + * %.20s...", lastre); */ } else if (c == '[' && *prestr == ':') { /* POSIX char class names, dag-erling smorgrav, - * des@ofug.org */ + * des@ofug.org */ for (cc = charclasses; cc->cc_name; cc++) if (strncmp((const char *)prestr + 1, (const char *)cc->cc_name, cc->cc_namelen) == 0) break; @@ -1414,14 +1414,14 @@ rescan: && prestr[2 + cc->cc_namelen] == ']') { prestr += cc->cc_namelen + 3; /* - * BUG: we begin at 1, instead of 0, - * since we would otherwise prematurely - * terminate the string for classes like - * [[:cntrl:]]. this means that we cant - * match the NUL character, not without - * first adapting the entire program to - * track each string's length - */ + * BUG: we begin at 1, instead of 0, + * since we would otherwise prematurely + * terminate the string for classes like + * [[:cntrl:]]. this means that we cant + * match the NUL character, not without + * first adapting the entire program to + * track each string's length + */ for (i = 1; i <= UCHAR_MAX; i++) { if (!adjbuf((char **)&buf, &bufsz, bp - buf + 2, 100, (char **)&bp, "relex2")) FATAL( @@ -1450,10 +1450,10 @@ rescan: if (*prestr == '.' && prestr[1] == ']') { prestr += 2; /* found it: map via locale TBD: for - * now, simply return this char. this - * is sufficient to pass conformance - * test awk.ex 156 - */ + * now, simply return this char. this + * is sufficient to pass conformance + * test awk.ex 156 + */ if (*prestr == ']') { prestr++; rlxval = collate_char; @@ -1467,10 +1467,10 @@ rescan: if (*prestr == '=' && prestr[1] == ']') { prestr += 2; /* found it: map via locale TBD: for now - * simply return this char. this is - * sufficient to pass conformance test - * awk.ex 156 - */ + * simply return this char. this is + * sufficient to pass conformance test + * awk.ex 156 + */ if (*prestr == ']') { prestr++; rlxval = equiv_char; @@ -1529,7 +1529,7 @@ rescan: } } else { if (digitfound) { /* {n} same as {n,n} - */ + */ n = num; m = num; } else { /* {} */ @@ -1548,7 +1548,7 @@ rescan: goto rescan; } /* failed to replace: eat up {...} characters - * and treat like just PLUS */ + * and treat like just PLUS */ return PLUS; } else if (c == '\0') { FATAL("nonterminated character class %.20s", lastre); diff --git a/cmd/posix/awk/lib.c b/cmd/posix/awk/lib.c @@ -312,7 +312,7 @@ readcsvrec(char **pbuf, int *pbufsize, FILE *inf, bool newflag) /* csv can have bool in_quote = false; sep = '\n'; /* the only separator; have to skip over \n embedded in - * "..." */ + * "..." */ rr = buf; while ((c = getc(inf)) != EOF) { if (c == sep) { @@ -446,11 +446,11 @@ fldbld(void) /* create fields from current record */ for (r++; *r != '\0';) { if (*r == '"' && r[1] != '\0' && r[1] == '"') { r += 2; /* doubled quote - */ + */ *fr++ = '"'; } else if (*r == '"' && (r[1] == '\0' || r[1] == ',')) { r++; /* skip over - * closing quote */ + * closing quote */ break; } else { *fr++ = *r++; @@ -485,9 +485,9 @@ fldbld(void) /* create fields from current record */ *fr = 0; } else if (*r != 0) { /* if 0, its a null field */ /* subtle case: if length(fs) == 1 && length(rs > 0) - * \n is NOT a field separator (cf awk book 61,84) - * this variable is tested in the inner while loop - */ + * \n is NOT a field separator (cf awk book 61,84) + * this variable is tested in the inner while loop + */ int rtest = '\n'; /* normal case */ if (strlen(*RS) > 0) rtest = '\0'; @@ -941,8 +941,8 @@ convert: *result = r; /* - * check for trailing stuff - */ + * check for trailing stuff + */ while (isspace((int)*ep)) ep++; diff --git a/cmd/posix/awk/maketab.c b/cmd/posix/awk/maketab.c @@ -160,7 +160,7 @@ main(int argc, char *argv[]) if (tok < FIRSTTOKEN || tok > LASTTOKEN) { tokentype = TOK_UNKNOWN; /* fprintf(stderr, "maketab funny token %d %s - * ignored\n", tok, buf); */ + * ignored\n", tok, buf); */ continue; } names[tok - FIRSTTOKEN] = strdup(name); diff --git a/cmd/posix/awk/run.c b/cmd/posix/awk/run.c @@ -175,7 +175,7 @@ execute(Node *u) /* execute a node of the parse tree */ return (x); } if (notlegal(a->nobj)) /* probably a cell* but too risky to - * print */ + * print */ FATAL("illegal statement"); proc = proctab[a->nobj - FIRSTTOKEN]; x = (*proc)(a->narg, a->nobj); @@ -253,7 +253,7 @@ call(Node **a, int n) /* function call. very kludgy and fragile */ static const Cell newcopycell = {OCELL, CCOPY, 0, EMPTY, 0.0, NUM | STR | DONTFREE, NULL, NULL}; int i, ncall, ndef; int freed = 0; /* handles potential double freeing when fcn & param - * share a tempcell */ + * share a tempcell */ Node *x; Cell *args[NARGS], *oargs[NARGS]; /* BUG: fixed size arrays */ Cell *y, *z, *fcn; @@ -1130,7 +1130,7 @@ sindex(Node **a, int nnn) /* index(a[0], a[1]) */ int has_utf8(char *s) /* return 1 if s contains any utf-8 (2 bytes or more) - * character */ + * character */ { int n; @@ -1296,7 +1296,7 @@ format(char **pbuf, int *pbufsize, const char *s, Node *a) /* printf-like conver t = getsval(x); n = strlen(t); /* if simple format or no utf-8 in the string, sprintf - * works */ + * works */ if (!has_utf8(t) || strcmp(fmt, "%s") == 0) { if (fmtwd > n) n = fmtwd; @@ -1313,7 +1313,7 @@ format(char **pbuf, int *pbufsize, const char *s, Node *a) /* printf-like conver } /* get here if string has utf-8 chars and fmt is not - * plain %s */ + * plain %s */ /* "%-w.ps", where -, w and .p are all optional */ /* '0' before the w is a flag character */ /* fmt points at % */ @@ -1372,17 +1372,17 @@ format(char **pbuf, int *pbufsize, const char *s, Node *a) /* printf-like conver case 'c': { /* - * if a numeric value is given, awk should just turn - * it into a character and print it: - * BEGIN { printf("%c\n", 65) } - * prints "a" - * - * but what if the numeric value is > 128 and - * represents a valid unicode code point?!? we do - * our best to convert it back into UTF-8. if we - * cant, we output the encoding of the unicode - * "invalid character", 0xfffd - */ + * if a numeric value is given, awk should just turn + * it into a character and print it: + * BEGIN { printf("%c\n", 65) } + * prints "a" + * + * but what if the numeric value is > 128 and + * represents a valid unicode code point?!? we do + * our best to convert it back into UTF-8. if we + * cant, we output the encoding of the unicode + * "invalid character", 0xfffd + */ if (isnum(x)) { int charval = (int)getfval(x); @@ -1409,7 +1409,7 @@ format(char **pbuf, int *pbufsize, const char *s, Node *a) /* printf-like conver } else { *p++ = '\0'; /* explicit null byte */ *p = '\0'; /* next output will start - * here */ + * here */ } break; } @@ -1645,7 +1645,7 @@ assign(Node **a, int n) /* a[0] = a[1], a[0] += a[1], etc */ if (n == ASSIGN) { /* ordinary assignment */ if (x == y && !(x->tval & (FLD | REC)) && x != nfloc) ; /* self-assignment: leave alone unless its a field or - * NF */ + * NF */ else if ((y->tval & (STR | NUM)) == (STR | NUM)) { yf = getfval(y); setsval(x, getsval(y)); @@ -1871,7 +1871,7 @@ split(Node **a, int nnn) /* split(a[0], a[1], a[2]); a[3] is type */ *fr++ = '"'; } else if (*s == '"' && (s[1] == '\0' || s[1] == ',')) { s++; /* skip over closing quote - */ + */ break; } else { *fr++ = *s++; @@ -2224,12 +2224,12 @@ bltin(Node **a, int n) /* builtin functions. a[0] is type, a[1] is arg list */ case FSYSTEM: fflush(stdout); /* in case something is buffered already */ estatus = wsystem(getsval(x)); - u = estatus; + u = estatus; break; case FRAND: /* random() returns numbers in [0..2^31-1] - * in order to get a number in [0, 1), divide it by 2^31 - */ + * in order to get a number in [0, 1), divide it by 2^31 + */ do { /* exact if awkfloat wide enough */ u = (Awkfloat)random(); diff --git a/cmd/posix/awk/tran.c b/cmd/posix/awk/tran.c @@ -478,27 +478,27 @@ get_str_val(Cell *vp, char **fmt) /* get string val of a cell */ recbld(); /* - * ADR: this is complicated and more fragile than is desirable - * retrieving a string value for a number associates the string - * value with the scalar. previously, the string value was - * sticky, meaning if converted via OFMT that became the value - * (even though POSIX wants it to be via CONVFMT). or if CONVFMT - * changed after a string value was retrieved, the original value - * was maintained and used. also not per POSIX - * - * we work around this design by adding two additional flags, - * CONVC and CONVO, indicating how the string value was - * obtained (via CONVFMT or OFMT) and _also_ maintaining a copy - * of the pointer to the xfmt format string used for the - * conversion. this pointer is only read, **never** dereferenced - * the next time we do a conversion, if its coming from the same - * xfmt as last time, and the pointer value is different, we - * know that the xfmt format string changed, and we need to - * redo the conversion. if its the same, we dont have to - * - * there are also several cases where we dont do a conversion, - * such as for a field (see the checks below) - */ + * ADR: this is complicated and more fragile than is desirable + * retrieving a string value for a number associates the string + * value with the scalar. previously, the string value was + * sticky, meaning if converted via OFMT that became the value + * (even though POSIX wants it to be via CONVFMT). or if CONVFMT + * changed after a string value was retrieved, the original value + * was maintained and used. also not per POSIX + * + * we work around this design by adding two additional flags, + * CONVC and CONVO, indicating how the string value was + * obtained (via CONVFMT or OFMT) and _also_ maintaining a copy + * of the pointer to the xfmt format string used for the + * conversion. this pointer is only read, **never** dereferenced + * the next time we do a conversion, if its coming from the same + * xfmt as last time, and the pointer value is different, we + * know that the xfmt format string changed, and we need to + * redo the conversion. if its the same, we dont have to + * + * there are also several cases where we dont do a conversion, + * such as for a field (see the checks below) + */ /* dont duplicate the code for actually updating the value */ #define update_str_val(vp) \ @@ -507,7 +507,7 @@ get_str_val(Cell *vp, char **fmt) /* get string val of a cell */ xfree(vp->sval); \ if ((p = get_inf_nan(vp->fval)) != NULL) \ strcpy(s, p); \ - else if (modf(vp->fval, &dtemp) == 0) /* its integral */ \ + else if (modf(vp->fval, &dtemp) == 0) /* its integral */ \ snprintf(s, sizeof(s), "%.30g", vp->fval); \ else \ snprintf(s, sizeof(s), *fmt, vp->fval); \ diff --git a/cmd/posix/cut.c b/cmd/posix/cut.c @@ -109,7 +109,7 @@ seek(struct line *s, size_t pos, size_t *prev, size_t count) static void cut(FILE *fp, const char *fname) { - struct Range *r; + struct Range *r; struct line s; static struct line line; diff --git a/cmd/posix/dd.c b/cmd/posix/dd.c @@ -99,7 +99,7 @@ main(int argc, char *argv[]) NOERROR = 1 << 3, NOTRUNC = 1 << 4, SYNC = 1 << 5, - } conv = 0; + } conv = 0; enum Status status = STATUS_DEFAULT; char *arg, *val, *end; const char *iname = "-", *oname = "-"; diff --git a/cmd/posix/ed.c b/cmd/posix/ed.c @@ -45,9 +45,9 @@ struct undo { } *vec; }; -static char *prompt = "*"; -static regex_t *pattern; -static regmatch_t matchs[10]; +static char *prompt = "*"; +static regex_t *pattern; +static regmatch_t matchs[10]; static struct String lastre; static int optverbose, optprompt, exstatus, optdiag = 1; @@ -779,8 +779,8 @@ static const char * expandcmd(void) { static struct String cmd; - char *p; - int c, repl = 0; + char *p; + int c, repl = 0; skipblank(); if ((c = input()) != '!') { @@ -1026,7 +1026,7 @@ getfname(int comm) static void append(int num) { - int ch; + int ch; static struct String line; curln = num; @@ -1087,8 +1087,8 @@ move(int where) static void join(void) { - int i; - char *t, c; + int i; + char *t, c; static struct String s; string(&s); @@ -1155,7 +1155,7 @@ execsh(void) static void getrhs(int delim) { - int c; + int c; static struct String s; string(&s); @@ -1257,7 +1257,7 @@ addsub(struct String *s, int nth, int nmatch) static void subline(int num, int nth) { - int i, m, changed; + int i, m, changed; static struct String s; string(&s); @@ -1288,10 +1288,10 @@ subst(int nth) subline(line, nth); /* - * the substitution command can add lines, so - * we have to skip lines until we find the - * index that we saved before the substitution - */ + * the substitution command can add lines, so + * we have to skip lines until we find the + * index that we saved before the substitution + */ do line = nextln(line); while (getindex(line) != next); diff --git a/cmd/posix/expr.c b/cmd/posix/expr.c @@ -238,7 +238,7 @@ parse(char *expr[], int numexpr) switch ((type = lex(*expr, &v))) { case VAL: /* treatment of *expr is not known until - * doop(); treat as a string for now */ + * doop(); treat as a string for now */ valp->str = *expr; valp++; break; diff --git a/cmd/posix/find.c b/cmd/posix/find.c @@ -95,21 +95,21 @@ struct execarg { union { struct { char ***braces; /* NULL terminated list of pointers into - * argv where {} were */ + * argv where {} were */ } s; /* semicolon */ struct { size_t arglen; /* number of bytes in argv before files - * are added */ + * are added */ size_t filelen; /* numer of bytes in file names added to - * argv */ + * argv */ size_t first; /* index one past last arg, where first - * file goes */ + * file goes */ size_t next; /* index where next file goes */ size_t cap; /* capacity of argv */ } p; /* plus */ } u; char **argv; /* NULL terminated list of arguments (allocated if isplus) - */ + */ char isplus; /* -exec + instead of -exec ; */ }; @@ -330,7 +330,7 @@ static struct tok *root; /* points to root of expression tree, inside toks array static struct timespec start; /* time find was started, used for -[acm]time */ static size_t envlen; /* number of bytes in environ, used to calculate against - * ARG_MAX */ + * ARG_MAX */ static size_t argmax; /* value of ARG_MAX retrieved using sysconf(3p) */ static struct { @@ -356,8 +356,8 @@ spawn(char *argv[]) int status; /* flush stdout so that -print output always appears before - * any output from the command and does not get cut-off in - * the middle of a line */ + * any output from the command and does not get cut-off in + * the middle of a line */ fflush(stdout); switch ((pid = fork())) { @@ -539,7 +539,7 @@ pri_exec(struct arg *arg) len = strlen(arg->path) + 1; /* if we reached ARG_MAX, fork, exec, wait, free file names, - * reset list */ + * reset list */ if (len + e->u.p.arglen + e->u.p.filelen + envlen > argmax) { e->argv[e->u.p.next] = NULL; @@ -554,7 +554,7 @@ pri_exec(struct arg *arg) } /* if we have too many files, realloc (with space for NULL - * termination) */ + * termination) */ if (e->u.p.next + 1 == e->u.p.cap) e->argv = ereallocarray(e->argv, e->u.p.cap *= 2, sizeof(*e->argv)); @@ -585,7 +585,7 @@ pri_ok(struct arg *arg) /* throw away rest of line */ while ((c = fgetc(stdin)) != '\n' && c != EOF) /* FIXME: what if the first character of the rest of the line is - * a null byte? */ + * a null byte? */ ; if (feof(stdin) || ferror(stdin)) @@ -965,7 +965,7 @@ parse(int argc, char **argv) pri = find_primary(*arg); if (pri) { /* token is a primary, fill out tok and get arguments - */ + */ if (lasttype == PRIM || lasttype == RPAR) { *tok++ = and; ntok++; @@ -1006,8 +1006,8 @@ parse(int argc, char **argv) /* use shunting-yard to convert from infix to rpn * https:// en.wikipedia.org/wiki/shunting-yard_algorithm - * read from infix, resulting rpn ends up in rpn, next position in rpn - * is out push operators onto stack, next position in stack is top */ + * read from infix, resulting rpn ends up in rpn, next position in rpn + * is out push operators onto stack, next position in stack is top */ rpn = ereallocarray(NULL, ntok + gflags.print, sizeof(*rpn)); stack = ereallocarray(NULL, argc + gflags.print, sizeof(*stack)); for (tok = infix, out = rpn, top = stack; tok->type != END; tok++) { @@ -1026,17 +1026,17 @@ parse(int argc, char **argv) break; default: /* this expression can be simplified, but i decided copy - * the verbage from the wikipedia page in order to more - * clearly explain whats going on */ + * the verbage from the wikipedia page in order to more + * clearly explain whats going on */ while (top-- > stack && ((tok->u.oinfo->lassoc && tok->u.oinfo->prec <= (*top)->u.oinfo->prec) || (!tok->u.oinfo->lassoc && tok->u.oinfo->prec < (*top)->u.oinfo->prec))) *out++ = **top; /* top now points to either an operator we didnt pop, - * or stack[-1] either way we need to increment it - * before using it, then increment again so the stack - * works */ + * or stack[-1] either way we need to increment it + * before using it, then increment again so the stack + * works */ top++; *top++ = tok; break; @@ -1049,8 +1049,8 @@ parse(int argc, char **argv) } /* if there was no expression, use -print - * if there was an expression but no -print, -exec, or -ok, add -a - * -print in rpn, not infix */ + * if there was an expression but no -print, -exec, or -ok, add -a + * -print in rpn, not infix */ if (gflags.print) *out++ = (struct tok){.u.pinfo = find_primary("-print"), .type = PRIM}; if (gflags.print == 2) @@ -1059,10 +1059,10 @@ parse(int argc, char **argv) out->type = END; /* rpn now holds all operators and arguments in reverse polish notation - * values are pushed onto stack, operators pop values off stack into - * left and right pointers, pushing operator node back onto stack could - * probably just do this during shunting-yard, but this is simpler code - * IMO */ + * values are pushed onto stack, operators pop values off stack into + * left and right pointers, pushing operator node back onto stack could + * probably just do this during shunting-yard, but this is simpler code + * IMO */ for (tok = rpn, top = stack; tok->type != END; tok++) { if (tok->type == PRIM) { *top++ = tok; @@ -1391,10 +1391,10 @@ find(char *path, struct findhist *hist) if (gflags.mindepth < 0 || depth >= gflags.mindepth) { /* dont eval now iff we will hit the eval at the bottom which - * means - * 1. we are a directory 2. we have -depth 3. we dont have - * -xdev or we are on same device (so most of the time we eval - * here) */ + * means + * 1. we are a directory 2. we have -depth 3. we dont have + * -xdev or we are on same device (so most of the time we eval + * here) */ if (!S_ISDIR(st.st_mode) || !gflags.depth || (gflags.xdev && hist && st.st_dev != hist->dev)) eval(root, &arg); } @@ -1507,8 +1507,8 @@ main(int argc, char **argv) parse(argc - npaths, argv); /* calculate number of bytes in environ for -exec {} + ARG_MAX avoidance - * libc implementation defined whether null bytes, pointers, and - * alignment are counted, so count them */ + * libc implementation defined whether null bytes, pointers, and + * alignment are counted, so count them */ for (argv = environ; *argv; argv++) envlen += strlen(*argv) + 1 + sizeof(*argv); diff --git a/cmd/posix/grep.c b/cmd/posix/grep.c @@ -20,7 +20,7 @@ static int invoked_as(const char *name) { const char *base = strrchr(argv0, '/'); - base = base ? base + 1 : argv0; + base = base ? base + 1 : argv0; return strcmp(base, name) == 0; } diff --git a/cmd/posix/head.c b/cmd/posix/head.c @@ -36,7 +36,7 @@ head_but(FILE *fp, const char *fname, size_t n) while ((len = getline(&buf, &size, fp)) > 0) { if (nheld < n) { - held = ereallocarray(held, nheld + 1, sizeof(*held)); + held = ereallocarray(held, nheld + 1, sizeof(*held)); held[nheld++] = estrdup(buf); continue; } @@ -70,8 +70,8 @@ main(int argc, char *argv[]) FILE *fp; int ret = 0, newline = 0, many = 0; #if FEATURE_HEAD_NEGATIVE - char *arg; - int drop = 0; + char *arg; + int drop = 0; #endif ARGBEGIN diff --git a/cmd/posix/join.c b/cmd/posix/join.c @@ -379,7 +379,7 @@ join(FILE *fa, FILE *fb, size_t jfa, size_t jfb) prline(spa.lines[0]); if (!addtospan(&spa, fa, RESET)) { if (unpairsb) { /* a is eof'd; print the rest of - * b */ + * b */ do prline(spb.lines[0]); while (addtospan(&spb, fb, RESET)); @@ -393,7 +393,7 @@ join(FILE *fa, FILE *fb, size_t jfa, size_t jfb) prline(spb.lines[0]); if (!addtospan(&spb, fb, RESET)) { if (unpairsa) { /* b is eof'd; print the rest of - * a */ + * a */ do prline(spa.lines[0]); while (addtospan(&spa, fa, RESET)); diff --git a/cmd/posix/ln.c b/cmd/posix/ln.c @@ -33,7 +33,7 @@ split_path(char *path, char **parts, int max) p++; while (*p && n < max) { parts[n++] = p; - p = strchr(p, '/'); + p = strchr(p, '/'); if (!p) break; *p++ = '\0'; @@ -63,8 +63,7 @@ relpath(const char *from_dir, const char *to_path, char *out, size_t outsz) nto = split_path(to_real, to_parts, MAXPATHPARTS); ncommon = 0; - while (ncommon < nfrom && ncommon < nto && - strcmp(from_parts[ncommon], to_parts[ncommon]) == 0) + while (ncommon < nfrom && ncommon < nto && strcmp(from_parts[ncommon], to_parts[ncommon]) == 0) ncommon++; out[0] = '\0'; @@ -260,11 +259,11 @@ main(int argc, char *argv[]) if ((sflag ? #if FEATURE_LN_RELATIVE - symlinkat(rflag ? relbuf : *argv, dirfd, target) + symlinkat(rflag ? relbuf : *argv, dirfd, target) #else - symlinkat(*argv, dirfd, target) + symlinkat(*argv, dirfd, target) #endif - : linkat(AT_FDCWD, *argv, dirfd, target, flags)) + : linkat(AT_FDCWD, *argv, dirfd, target, flags)) < 0) { weprintf("%s %s <- %s/%s:", sflag ? "symlinkat" : "linkat", *argv, targetdir, target); ret = 1; diff --git a/cmd/posix/ls.c b/cmd/posix/ls.c @@ -471,7 +471,8 @@ lsdir(const char *path, const struct entry *dir) estrdup(d->d_name), Fflag || iflag || lflag || pflag || Rflag || sort || should_color(), Lflag - ) < 0) + ) + < 0) n--; } diff --git a/cmd/posix/make/main.c b/cmd/posix/make/main.c @@ -177,14 +177,14 @@ parseflag(int flag, char **args, char ***argv) switch (flag) { case 'j': /* ?man -j:jobs: number of parallel jobs (accepted, runs - * serially) */ + * serially) */ case 'f': /* ?man -f:file: read rules from file instead of makefile or - * makefile */ + * makefile */ break; case 'e': /* ?man -e: environment variables override makefile assignments - */ + */ eflag = 1; appendmakeflags("-e"); break; @@ -209,7 +209,7 @@ parseflag(int flag, char **args, char ***argv) break; case 'q': /* ?man -q: question mode, return zero if up to date, one - * otherwise */ + * otherwise */ qflag = 1; appendmakeflags("-q"); break; @@ -270,9 +270,9 @@ static void parseargv(char **argv, char ***targets, int where, int export) { char *s; - char *hm = NULL; + char *hm = NULL; char **found = NULL; - int n = 0; + int n = 0; for (; *argv; ++argv) { s = *argv; @@ -285,9 +285,9 @@ parseargv(char **argv, char ***targets, int where, int export) continue; if (!targets) break; - found = erealloc(found, (n + 2) * sizeof(*found)); - found[n++] = s; - found[n] = NULL; + found = erealloc(found, (n + 2) * sizeof(*found)); + found[n++] = s; + found[n] = NULL; continue; } while (hm == NULL && *++s) diff --git a/cmd/posix/make/parser.c b/cmd/posix/make/parser.c @@ -140,12 +140,12 @@ setmacro(char *name, char *val, int where, int export) s = macroinfo(name, &owhere, &mp); /* - * default values are defined before anything else, and marked - * as INTERNAL because they are injected as parseable text, and - * MAKEFILE and INTERNAL variables are always overriden. ENVIRON - * macros are generated in macroinfo() and this is why this function - * should not receive a where == ENVIRON ever - */ + * default values are defined before anything else, and marked + * as INTERNAL because they are injected as parseable text, and + * MAKEFILE and INTERNAL variables are always overriden. ENVIRON + * macros are generated in macroinfo() and this is why this function + * should not receive a where == ENVIRON ever + */ switch (owhere) { case UNDEF: case INTERNAL: @@ -515,7 +515,7 @@ nextline(void) FILE *fp; char *s, *lim; #if FEATURE_MAKE_BMAKE - char d[BUFSIZ]; + char d[BUFSIZ]; #endif assert(input->type == FTFILE); @@ -648,7 +648,8 @@ repeat: } /* -include is POSIX 2024's, sinclude is gmake's */ - if ((!strncmp(input->buf, "-include", 8) && isblank(input->buf[8])) + if ( + (!strncmp(input->buf, "-include", 8) && isblank(input->buf[8])) #if FEATURE_MAKE_GMAKE || (!strncmp(input->buf, "sinclude", 8) && isblank(input->buf[8])) #endif @@ -970,12 +971,12 @@ rawref(char *dst, int di, int max) static int nested(char *name, int namei, Target *tp) { - char ref[MAXTOKEN], *val; - int n; + char ref[MAXTOKEN], *val; + int n; rawref(ref, 0, MAXTOKEN); - val = expandstring(ref, tp, getloc()); - n = strlen(val); + val = expandstring(ref, tp, getloc()); + n = strlen(val); if (namei + n >= MAXTOKEN - 1) error("expansion text too long"); memcpy(name + namei, val, n); @@ -1203,10 +1204,10 @@ next(void) repeat: /* - * it is better to avoid skipspaces() here, because - * it can generate the need for 2 calls to back(), - * and we need the character anyway - */ + * it is better to avoid skipspaces() here, because + * it can generate the need for 2 calls to back(), + * and we need the character anyway + */ c = nextc(); if (c == ' ' || c == '\t') goto repeat; @@ -1390,8 +1391,8 @@ globdeps(char ***deps, int n) for (i = 0; i < n; i++) { if (strpbrk((*deps)[i], "*?[") && glob((*deps)[i], 0, NULL, &g) == 0) { for (j = 0; j < (int)g.gl_pathc; j++) { - out = erealloc(out, (m + 1) * sizeof(char *)); - out[m++] = estrdup(g.gl_pathv[j]); + out = erealloc(out, (m + 1) * sizeof(char *)); + out[m++] = estrdup(g.gl_pathv[j]); } globfree(&g); free((*deps)[i]); diff --git a/cmd/posix/od.c b/cmd/posix/od.c @@ -98,9 +98,15 @@ printchunk(const unsigned char *s, unsigned char format, size_t len) fmt[2] = (format == 'x' || format == 'o') ? '0' : ' '; fmt[6] = format; switch (format) { - case 'x': printf(fmt, (int)(2 * len), res); break; - case 'o': printf(fmt, (int)((8 * len + 2) / 3), res); break; - default: printf(fmt, (int)(3 * len + len - 1), res); break; + case 'x': + printf(fmt, (int)(2 * len), res); + break; + case 'o': + printf(fmt, (int)((8 * len + 2) / 3), res); + break; + default: + printf(fmt, (int)(3 * len + len - 1), res); + break; } } } diff --git a/cmd/posix/patch.c b/cmd/posix/patch.c @@ -1147,9 +1147,9 @@ plan_a(const char *filename) #define try(f, a1, a2, a3) (snprintf(lbuf, lbufsz, f, a1, a2, a3), stat(lbuf, &cstat) == 0) - if (try("%s/RCS/%s%s", filedir, filebase, RCSSUFFIX) - || try("%s/RCS/%s%s", filedir, filebase, "") - || try("%s/%s%s", filedir, filebase, RCSSUFFIX)) { + if (try ("%s/RCS/%s%s", filedir, filebase, RCSSUFFIX) + || try ("%s/RCS/%s%s", filedir, filebase, "") + || try ("%s/%s%s", filedir, filebase, RCSSUFFIX)) { if (!statfailed) { if ((filestat.st_mode & 0222) != 0) fatal( @@ -3042,10 +3042,10 @@ checked_in(char *file) #define try(f, a1, a2, a3) \ (snprintf(tmpbuf, sizeof tmpbuf, f, a1, a2, a3), stat(tmpbuf, &filestat) == 0) - if (try("%s/RCS/%s%s", filedir, filebase, RCSSUFFIX) || try("%s/RCS/%s%s", filedir, filebase, "") - || try("%s/%s%s", filedir, filebase, RCSSUFFIX) - || try("%s/SCCS/%s%s", filedir, SCCSPREFIX, filebase) - || try("%s/%s%s", filedir, SCCSPREFIX, filebase)) + if (try ("%s/RCS/%s%s", filedir, filebase, RCSSUFFIX) + || try ("%s/RCS/%s%s", filedir, filebase, "") || try ("%s/%s%s", filedir, filebase, RCSSUFFIX) + || try ("%s/SCCS/%s%s", filedir, SCCSPREFIX, filebase) + || try ("%s/%s%s", filedir, SCCSPREFIX, filebase)) return file; return NULL; diff --git a/cmd/posix/pathchk.c b/cmd/posix/pathchk.c @@ -53,7 +53,7 @@ pathchk(char *filename) /* symlink error? non-searchable directory? */ if (lstat(filename, &st) && errno != ENOENT) { /* lstat rather than stat, so that if filename is a bad symlink, - * but all parents are OK, no error will be detected */ + * but all parents are OK, no error will be detected */ eprintf("%s:", filename); } diff --git a/cmd/posix/pax.c b/cmd/posix/pax.c @@ -850,10 +850,10 @@ readpax(struct bufio *f, struct header *h) case 'g': readexthdr(f, &globexthdr, h->size); break; - case 'x': + case 'x': readexthdr(f, &exthdr, h->size); break; - case 'L': + case 'L': if ((exthdr.delete | opt.delete) & PATH) break; readgnuhdr(f, &exthdr.pathbuf, h->size); @@ -2071,7 +2071,7 @@ writefile(FILE *unused, struct header *h) exitstatus = 1; } else { /* add back setuid/setgid bits if we preserved the - * uid/gid */ + * uid/gid */ mode = h->mode; } } @@ -2174,7 +2174,7 @@ parsereplstr(char *str) case 'p': r->print = 1; break; - case 's': + case 's': r->symlink = 0; break; case 'S': @@ -2454,7 +2454,7 @@ main(int argc, char *argv[]) ARGBEGIN { - case 'a': + case 'a': aflag = 1; break; // ?man -b:str: specify block size or base directory @@ -2509,7 +2509,7 @@ main(int argc, char *argv[]) case 'o': parseopts(EARGF(usage())); break; - case 'p': + case 'p': for (arg = EARGF(usage()); *arg; ++arg) { switch (*arg) { // ?man -a: print or show all entries @@ -2524,10 +2524,10 @@ main(int argc, char *argv[]) case 'm': preserve &= ~MTIME; break; - case 'o': + case 'o': preserve |= UID | GID; break; - // ?man -p:str: preserve file attributes + // ?man -p:str: preserve file attributes case 'p': preserve |= MODE; break; diff --git a/cmd/posix/ps.c b/cmd/posix/ps.c @@ -34,11 +34,11 @@ struct list { int n; }; -static struct list pids, ttys, users, ruser, sids, rgroups; -static char *headers[32]; +static struct list pids, ttys, users, ruser, sids, rgroups; +static char *headers[32]; static const struct column *chosen[32]; -static int nchosen; -static int allheadless; /* every -o column had its own header text, empty */ +static int nchosen; +static int allheadless; /* every -o column had its own header text, empty */ static void username(uid_t uid, char *out, size_t n) @@ -68,22 +68,88 @@ hms(unsigned long secs, char *out, size_t n) snprintf(out, n, "%02lu:%02lu:%02lu", secs / 3600, (secs % 3600) / 60, secs % 60); } -static void put_user(const struct procinfo *p, char *o, size_t n) { username(p->euid, o, n); } -static void put_ruser(const struct procinfo *p, char *o, size_t n) { username(p->ruid, o, n); } -static void put_group(const struct procinfo *p, char *o, size_t n) { groupname(p->egid, o, n); } -static void put_rgroup(const struct procinfo *p, char *o, size_t n) { groupname(p->rgid, o, n); } -static void put_pid(const struct procinfo *p, char *o, size_t n) { snprintf(o, n, "%d", (int)p->pid); } -static void put_ppid(const struct procinfo *p, char *o, size_t n) { snprintf(o, n, "%d", (int)p->ppid); } -static void put_pgid(const struct procinfo *p, char *o, size_t n) { snprintf(o, n, "%d", (int)p->pgid); } -static void put_nice(const struct procinfo *p, char *o, size_t n) { snprintf(o, n, "%ld", p->nice); } -static void put_pri(const struct procinfo *p, char *o, size_t n) { snprintf(o, n, "%ld", p->priority); } -static void put_vsz(const struct procinfo *p, char *o, size_t n) { snprintf(o, n, "%lu", p->vsize_kib); } -static void put_sz(const struct procinfo *p, char *o, size_t n) { snprintf(o, n, "%lu", p->vsize_kib / 4); } -static void put_state(const struct procinfo *p, char *o, size_t n) { snprintf(o, n, "%c", p->state); } -static void put_time(const struct procinfo *p, char *o, size_t n) { hms(p->cpu, o, n); } -static void put_comm(const struct procinfo *p, char *o, size_t n) { snprintf(o, n, "%s", p->comm); } -static void put_zero(const struct procinfo *p, char *o, size_t n) { (void)p; snprintf(o, n, "0"); } -static void put_dash(const struct procinfo *p, char *o, size_t n) { (void)p; snprintf(o, n, "-"); } +static void +put_user(const struct procinfo *p, char *o, size_t n) +{ + username(p->euid, o, n); +} +static void +put_ruser(const struct procinfo *p, char *o, size_t n) +{ + username(p->ruid, o, n); +} +static void +put_group(const struct procinfo *p, char *o, size_t n) +{ + groupname(p->egid, o, n); +} +static void +put_rgroup(const struct procinfo *p, char *o, size_t n) +{ + groupname(p->rgid, o, n); +} +static void +put_pid(const struct procinfo *p, char *o, size_t n) +{ + snprintf(o, n, "%d", (int)p->pid); +} +static void +put_ppid(const struct procinfo *p, char *o, size_t n) +{ + snprintf(o, n, "%d", (int)p->ppid); +} +static void +put_pgid(const struct procinfo *p, char *o, size_t n) +{ + snprintf(o, n, "%d", (int)p->pgid); +} +static void +put_nice(const struct procinfo *p, char *o, size_t n) +{ + snprintf(o, n, "%ld", p->nice); +} +static void +put_pri(const struct procinfo *p, char *o, size_t n) +{ + snprintf(o, n, "%ld", p->priority); +} +static void +put_vsz(const struct procinfo *p, char *o, size_t n) +{ + snprintf(o, n, "%lu", p->vsize_kib); +} +static void +put_sz(const struct procinfo *p, char *o, size_t n) +{ + snprintf(o, n, "%lu", p->vsize_kib / 4); +} +static void +put_state(const struct procinfo *p, char *o, size_t n) +{ + snprintf(o, n, "%c", p->state); +} +static void +put_time(const struct procinfo *p, char *o, size_t n) +{ + hms(p->cpu, o, n); +} +static void +put_comm(const struct procinfo *p, char *o, size_t n) +{ + snprintf(o, n, "%s", p->comm); +} +static void +put_zero(const struct procinfo *p, char *o, size_t n) +{ + (void)p; + snprintf(o, n, "0"); +} +static void +put_dash(const struct procinfo *p, char *o, size_t n) +{ + (void)p; + snprintf(o, n, "-"); +} static void put_tty(const struct procinfo *p, char *o, size_t n) @@ -159,19 +225,31 @@ put_pcpu(const struct procinfo *p, char *o, size_t n) } static const struct column columns[] = { - {"user", "USER", -8, put_user}, {"ruser", "RUSER", -8, put_ruser}, - {"group", "GROUP", -8, put_group}, {"rgroup", "RGROUP", -8, put_rgroup}, - {"uid", "UID", -8, put_user}, {"pid", "PID", 5, put_pid}, - {"ppid", "PPID", 5, put_ppid}, {"pgid", "PGID", 5, put_pgid}, - {"etime", "ELAPSED", 11, put_etime},{"nice", "NI", 3, put_nice}, - {"pcpu", "%CPU", 4, put_pcpu}, {"vsz", "VSZ", 7, put_vsz}, - {"time", "TIME", 8, put_time}, {"tty", "TT", -8, put_tty}, - {"comm", "COMMAND", -15, put_comm}, {"args", "COMMAND", -15, put_args}, + {"user", "USER", -8, put_user}, + {"ruser", "RUSER", -8, put_ruser}, + {"group", "GROUP", -8, put_group}, + {"rgroup", "RGROUP", -8, put_rgroup}, + {"uid", "UID", -8, put_user}, + {"pid", "PID", 5, put_pid}, + {"ppid", "PPID", 5, put_ppid}, + {"pgid", "PGID", 5, put_pgid}, + {"etime", "ELAPSED", 11, put_etime}, + {"nice", "NI", 3, put_nice}, + {"pcpu", "%CPU", 4, put_pcpu}, + {"vsz", "VSZ", 7, put_vsz}, + {"time", "TIME", 8, put_time}, + {"tty", "TT", -8, put_tty}, + {"comm", "COMMAND", -15, put_comm}, + {"args", "COMMAND", -15, put_args}, /* the names of -f and -l, which are not the ones of -o */ - {"f", "F", 1, put_zero}, {"s", "S", 1, put_state}, - {"c", "C", 2, put_zero}, {"pri", "PRI", 3, put_pri}, - {"addr", "ADDR", 4, put_dash}, {"sz", "SZ", 6, put_sz}, - {"wchan", "WCHAN", 6, put_dash}, {"stime", "STIME", 5, put_stime}, + {"f", "F", 1, put_zero}, + {"s", "S", 1, put_state}, + {"c", "C", 2, put_zero}, + {"pri", "PRI", 3, put_pri}, + {"addr", "ADDR", 4, put_dash}, + {"sz", "SZ", 6, put_sz}, + {"wchan", "WCHAN", 6, put_dash}, + {"stime", "STIME", 5, put_stime}, {"cmd", "CMD", -15, put_cmd}, }; @@ -225,7 +303,7 @@ add_list(struct list *l, char *arg) char *tok; for (tok = strtok(arg, ", "); tok; tok = strtok(NULL, ", ")) { - l->w = ereallocarray(l->w, l->n + 1, sizeof(*l->w)); + l->w = ereallocarray(l->w, l->n + 1, sizeof(*l->w)); l->w[l->n++] = tok; } } @@ -271,9 +349,9 @@ tty_in(const struct list *l, const struct procinfo *p) return in_list(l, name) || (!strncmp(name, "pts/", 4) && in_list(l, name + 4)); } -static char mytty[32]; +static char mytty[32]; static uid_t myuid; -static int have_tty; +static int have_tty; /* whether a process is one of those asked for */ static int @@ -283,12 +361,30 @@ wanted(const struct procinfo *p) int selected = 0, listed = 0; snprintf(num, sizeof num, "%d", (int)p->pid); - if (pids.n) { listed = 1; selected |= in_list(&pids, num); } - if (ttys.n) { listed = 1; selected |= tty_in(&ttys, p); } - if (users.n) { listed = 1; selected |= user_in(&users, p->euid); } - if (ruser.n) { listed = 1; selected |= user_in(&ruser, p->ruid); } - if (rgroups.n) { listed = 1; selected |= group_in(&rgroups, p->rgid); } - if (sids.n) { listed = 1; selected |= in_list(&sids, (snprintf(num, sizeof num, "%d", (int)p->sid), num)); } + if (pids.n) { + listed = 1; + selected |= in_list(&pids, num); + } + if (ttys.n) { + listed = 1; + selected |= tty_in(&ttys, p); + } + if (users.n) { + listed = 1; + selected |= user_in(&users, p->euid); + } + if (ruser.n) { + listed = 1; + selected |= user_in(&ruser, p->ruid); + } + if (rgroups.n) { + listed = 1; + selected |= group_in(&rgroups, p->rgid); + } + if (sids.n) { + listed = 1; + selected |= in_list(&sids, (snprintf(num, sizeof num, "%d", (int)p->sid), num)); + } if (flags & PS_A) return 1; if (flags & PS_a) { @@ -320,9 +416,9 @@ static int width; static int show(const struct procinfo *p, void *arg) { - char line[BUFSIZ * 2], cell[BUFSIZ]; + char line[BUFSIZ * 2], cell[BUFSIZ]; size_t at = 0; - int i; + int i; (void)arg; if (!wanted(p)) @@ -333,7 +429,9 @@ show(const struct procinfo *p, void *arg) if (i == nchosen - 1) at += (size_t)snprintf(line + at, sizeof line - at, "%s%s", i ? " " : "", cell); else - at += (size_t)snprintf(line + at, sizeof line - at, "%s%*s", i ? " " : "", chosen[i]->width, cell); + at += (size_t)snprintf( + line + at, sizeof line - at, "%s%*s", i ? " " : "", chosen[i]->width, cell + ); if (at >= sizeof line) at = sizeof line - 1; } @@ -360,8 +458,8 @@ usage(void) int main(int argc, char *argv[]) { - char *name; - int i; + char *name; + int i; struct winsize w = {0}; ARGBEGIN @@ -432,18 +530,35 @@ main(int argc, char *argv[]) /* the default, -f and -l are named lists of columns */ if (!nchosen) { - const char *set[] = {"pid", "tty", "time", "cmd"}; + const char *set[] = {"pid", "tty", "time", "cmd"}; const char *full[] = {"uid", "pid", "ppid", "c", "stime", "tty", "time", "cmd"}; - const char *lng[] = {"f", "s", "uid", "pid", "ppid", "c", "pri", "nice", "addr", "sz", "wchan", "tty", "time", "cmd"}; + const char *lng[] = { + "f", + "s", + "uid", + "pid", + "ppid", + "c", + "pri", + "nice", + "addr", + "sz", + "wchan", + "tty", + "time", + "cmd" + }; const char **l = (flags & PS_l) ? lng : (flags & PS_f) ? full : set; - size_t k, n = (flags & PS_l) ? sizeof lng / sizeof *lng : (flags & PS_f) ? sizeof full / sizeof *full : sizeof set / sizeof *set; + size_t k, n = (flags & PS_l) ? sizeof lng / sizeof *lng + : (flags & PS_f) ? sizeof full / sizeof *full + : sizeof set / sizeof *set; for (k = 0; k < n; k++) choose(l[k], NULL); } if ((name = ttyname(0))) { - unsigned maj = 0, min = 0; + unsigned maj = 0, min = 0; struct procinfo me; if (proc_info(getpid(), &me) == 0) { @@ -460,14 +575,16 @@ main(int argc, char *argv[]) /* a header line, unless every column was given an empty header */ if (allheadless < nchosen) { - char head[BUFSIZ]; + char head[BUFSIZ]; size_t at = 0; for (i = 0; i < nchosen; i++) { if (i == nchosen - 1) at += (size_t)snprintf(head + at, sizeof head - at, "%s%s", i ? " " : "", headers[i]); else - at += (size_t)snprintf(head + at, sizeof head - at, "%s%*s", i ? " " : "", chosen[i]->width, headers[i]); + at += (size_t)snprintf( + head + at, sizeof head - at, "%s%*s", i ? " " : "", chosen[i]->width, headers[i] + ); if (at >= sizeof head) at = sizeof head - 1; } diff --git a/cmd/posix/sed.c b/cmd/posix/sed.c @@ -96,7 +96,7 @@ typedef struct { typedef struct { String str; /* a,c,i text. r file path */ void (*print)(char *, FILE *); /* check_puts for a, write_file for r, - * unused for c,i */ + * unused for c,i */ } ACIRarg; struct Cmd { @@ -109,7 +109,7 @@ struct Cmd { FILE *file; /* used for w */ /* FIXME: should the following be in the union? or pointers and - * malloc? */ + * malloc? */ Sarg s; Yarg y; ACIRarg acir; @@ -251,12 +251,12 @@ static struct { static Fninfo fns[] = { ['a'] = {cmd_a, get_aci_arg, free_acir_arg, 1}, /* schedule write of text for later */ ['b'] = {cmd_b, get_bt_arg, NULL, 2}, /* branch to label char *label when building, cmd *jump - * when running */ + * when running */ ['c'] = {cmd_c, get_aci_arg, free_acir_arg, 2}, /* delete pattern space. at 0 or 1 addr or end - * of 2 addr, write text */ + * of 2 addr, write text */ ['d'] = {cmd_d, NULL, NULL, 2}, /* delete pattern space */ ['D'] = {cmd_D, NULL, NULL, 2}, /* delete to first newline and start new cycle without - * reading (if no newline, d) */ + * reading (if no newline, d) */ ['g'] = {cmd_g, NULL, NULL, 2}, /* replace pattern space with hold space */ ['G'] = {cmd_G, NULL, NULL, 2}, /* append newline and hold space to pattern space */ ['h'] = {cmd_h, NULL, NULL, 2}, /* replace hold space with pattern space */ @@ -264,14 +264,14 @@ static Fninfo fns[] = { ['i'] = {cmd_i, get_aci_arg, free_acir_arg, 1}, /* write text */ ['l'] = {cmd_l, NULL, NULL, 2}, /* write pattern space in 'visually unambiguous form' */ ['n'] = {cmd_n, NULL, NULL, 2}, /* write pattern space (unless -n) read to replace pattern - * space (if no input, quit) */ + * space (if no input, quit) */ ['N'] = {cmd_N, NULL, NULL, 2}, /* append to pattern space separated by newline, line - * number changes (if no input, quit) */ + * number changes (if no input, quit) */ ['p'] = {cmd_p, NULL, NULL, 2}, /* write pattern space */ ['P'] = {cmd_P, NULL, NULL, 2}, /* write pattern space up to first newline */ ['q'] = {cmd_q, NULL, NULL, 1}, /* quit */ ['r'] = {cmd_r, get_r_arg, free_acir_arg, 1}, /* write contents of file (unable to open/read - * treated as empty file) */ + * treated as empty file) */ ['s'] = {cmd_s, get_s_arg, free_s_arg, 2}, /* find/replace/all that crazy s stuff */ ['t'] = {cmd_t, get_bt_arg, NULL, 2}, /* if s// / succeeded (since input or last t) branch to label (branch to end if no label) */ @@ -281,12 +281,12 @@ static Fninfo fns[] = { [':'] = {cmd_colon, get_colon_arg, NULL, 0}, /* defines label for later b and t commands */ ['='] = {cmd_equal, NULL, NULL, 1}, /* printf("%d\n", line_number); */ ['{'] = {cmd_lbrace, get_lbrace_arg, NULL, 2}, /* if we match, run commands, otherwise jump to - * close */ + * close */ ['}'] = {cmd_rbrace, get_rbrace_arg, NULL, 0}, /* noop, hold onto open for ease of building - * scripts */ + * scripts */ [0x7f] = {NULL, NULL, NULL, 0}, /* index is checked with isascii(3p) - * fill out rest of array */ + * fill out rest of array */ }; /* @@ -446,7 +446,7 @@ compile(char *s, int isfile) s = genbuf.str; /* if the first two characters of the script are "#n" default - * output shall be suppressed */ + * output shall be suppressed */ if (++lineno == 1 && *s == '#' && s[1] == 'n') { gflags.n = 1; continue; @@ -599,14 +599,14 @@ find_delim(char *s, Rune delim, int do_brackets) enum { OUTSIDE, /* not in brackets */ BRACKETS_OPENING, /* last char was first [ or last two were - * first [^ */ + * first [^ */ BRACKETS_INSIDE, /* inside [] */ INSIDE_OPENING, /* inside [] and last char was [ */ CLASS_INSIDE, /* inside class [::], or colating element [..] or - * [==], inside [] */ + * [==], inside [] */ CLASS_CLOSING, /* inside class [::], or colating element [..] or - * [==], and last character was the respective : - * . or = */ + * [==], and last character was the respective : + * . or = */ } state = OUTSIDE; Rune r, c = 0; /* no c wont be used uninitialized, shutup -wall */ @@ -723,7 +723,7 @@ escapes(char *beg, char *end, Rune delim, int n_newline) while (src < end) { /* handle escaped backslash specially so we dont think the - * second backslash is escaping something */ + * second backslash is escaping something */ if (*src == '\\' && src[1] == '\\') { *dst++ = *src++; if (delim) @@ -741,7 +741,7 @@ escapes(char *beg, char *end, Rune delim, int n_newline) if (r == 'n' && delim == 'n') { *src = n_newline ? '\n' : 'n'; /* src so we can still - * memmove() */ + * memmove() */ } else if (r == 'n') { *src = '\n'; } else if (r != delim) { @@ -917,7 +917,7 @@ get_s_arg(Cmd *c, char *s) /* find */ if (!gflags.s_cont) { /* NOT continuing from literal newline in - * replacement text */ + * replacement text */ lastre = 0; c->u.s.repl = (String){NULL, 0}; c->u.s.occurrence = 1; @@ -994,7 +994,7 @@ get_s_arg(Cmd *c, char *s) p = semicolon_arg(s = chomp(s)); /* FIXME: currently for simplicity take last of g or occurrence flags - * and ignore multiple p flags. need to fix that */ + * and ignore multiple p flags. need to fix that */ for (; s < p; s++) { if (isdigit(*s)) { c->u.s.occurrence = stol(s, &s); @@ -1009,7 +1009,7 @@ get_s_arg(Cmd *c, char *s) break; case 'w': /* must be last flag, take everything up to - * newline/semicolon s == p after this */ + * newline/semicolon s == p after this */ s = get_w_arg(&buf, chomp(s + 1)); c->u.s.file = buf.u.file; break; @@ -1153,7 +1153,7 @@ run(void) leprintf("extra {"); /* genbuf has already been initialized, patt will be in new_line - * (or we will halt) */ + * (or we will halt) */ stracpy(&hold, ""); insert_labels(); @@ -1343,7 +1343,7 @@ cmd_b(Cmd *c) return; /* if we jump backwards update to end, otherwise update to destination - */ + */ update_ranges(c + 1, c->u.jump > c ? c->u.jump : prog + pcap); pc = c->u.jump; } @@ -1358,7 +1358,7 @@ cmd_c(Cmd *c) if (!c->in_match) check_puts(c->u.acir.str.str, stdout); /* otherwise start the next cycle without printing pattern space - * effectively deleting the text */ + * effectively deleting the text */ new_next(); } @@ -1455,16 +1455,16 @@ cmd_l(Cmd *c) return; /* FIXME: line wrapping. sed(1p) says "length at which folding occurs is - * unspecified, but should be appropraite for the output device" - * just wrap at 80 runes? - */ + * unspecified, but should be appropraite for the output device" + * just wrap at 80 runes? + */ for (p = patt.str, end = p + strlen(p); p < end; p += rlen) { if (isascii(*p) && escapes[(unsigned int)*p]) { fputs(escapes[(unsigned int)*p], stdout); rlen = 1; } else if (!(rlen = charntorune(&r, p, end - p))) { /* ran out of chars, print the bytes of the short - * sequence */ + * sequence */ for (; p < end; p++) printf("\\%03hho", (unsigned char)*p); break; @@ -1573,21 +1573,21 @@ cmd_s(Cmd *c) while (!qflag && !regexec(re, s, plen, pmatch, cflags)) { cflags = REG_NOTBOL; /* match against beginning of line first - * time, but not again */ + * time, but not again */ if (!*s) /* match against empty string first time, but not again - */ + */ qflag = 1; /* dont substitute if last match was not empty but this one is - * s_a*_._g - * foobar -> .f.o.o.b.r - */ + * s_a*_._g + * foobar -> .f.o.o.b.r + */ if ((last_empty || pmatch[0].rm_eo) && (++matches == c->u.s.occurrence || !c->u.s.occurrence)) { /* copy over everything before the match */ strnacat(&genbuf, s, pmatch[0].rm_so); /* copy over replacement text, taking into account &, - * backreferences, and \ escapes */ + * backreferences, and \ escapes */ for (p = c->u.s.repl.str, len = strcspn(p, "\\&"); *p; len = strcspn(++p, "\\&")) { strnacat(&genbuf, p, len); p += len; @@ -1597,8 +1597,8 @@ cmd_s(Cmd *c) break; case '\0': /* we are at the end, back up one so the - * ++p will put us on the null byte to - * break out of the loop */ + * ++p will put us on the null byte to + * break out of the loop */ --p; break; case '&': @@ -1607,8 +1607,8 @@ cmd_s(Cmd *c) case '\\': if (isdigit(*++p)) { /* backreference */ /* only need to check here if - * using lastre, otherwise we - * checked when building */ + * using lastre, otherwise we + * checked when building */ if (!c->u.s.re && (size_t)(*p - '0') > re->re_nsub) leprintf( "back " @@ -1621,8 +1621,8 @@ cmd_s(Cmd *c) rm = &pmatch[*p - '0']; strnacat(&genbuf, s + rm->rm_so, rm->rm_eo - rm->rm_so); } else { /* character after backslash - * taken literally (well one - * byte, but it works) */ + * taken literally (well one + * byte, but it works) */ strnacat(&genbuf, p, 1); } break; @@ -1630,12 +1630,12 @@ cmd_s(Cmd *c) } } else { /* not replacing, copy over everything up to and - * including the match */ + * including the match */ strnacat(&genbuf, s, pmatch[0].rm_eo); } if (!pmatch[0].rm_eo) { /* empty match, advance one rune and add - * it to output */ + * it to output */ end = s + strlen(s); rlen = charntorune(&r, s, end - s); @@ -1676,7 +1676,7 @@ cmd_t(Cmd *c) return; /* if we jump backwards update to end, otherwise update to destination - */ + */ update_ranges(c + 1, c->u.jump > c ? c->u.jump : prog + pcap); pc = c->u.jump; gflags.s = 0; @@ -1725,7 +1725,7 @@ cmd_y(Cmd *c) if (*rp == r) break; if (*rp) { /* found r in set1, replace with rune from - * set2 */ + * set2 */ n = runetochar(buf, c->u.y.set2 + (rp - c->u.y.set1)); strnacat(&genbuf, buf, n); } else { diff --git a/cmd/posix/sh/alias.c b/cmd/posix/sh/alias.c @@ -87,12 +87,12 @@ unalias(const char *name) for (ap = *app; ap; app = &(ap->next), ap = ap->next) { if (equal(name, ap->name)) { /* - * if the alias is currently in use (i.e. its - * buffer is being used by the input routine) we - * just null out the name instead of freeing it - * we could clear it out later, but this situation - * is so rare that it hardly seems worth it - */ + * if the alias is currently in use (i.e. its + * buffer is being used by the input routine) we + * just null out the name instead of freeing it + * we could clear it out later, but this situation + * is so rare that it hardly seems worth it + */ if (ap->flag & ALIASINUSE) *ap->name = '\0'; else { diff --git a/cmd/posix/sh/arith_yacc.c b/cmd/posix/sh/arith_yacc.c @@ -369,8 +369,8 @@ letcmd(int argc, char **argv) p = argv[1]; if (argc > 2) { /* - * concatenate arguments - */ + * concatenate arguments + */ STARTSTACKSTR(concat); ap = argv + 2; for (;;) { diff --git a/cmd/posix/sh/cd.c b/cmd/posix/sh/cd.c @@ -120,8 +120,8 @@ cdcmd(int argc __unused, char **argv __unused) else { if (!print) { /* - * XXX - rethink - */ + * XXX - rethink + */ if (p[0] == '.' && p[1] == '/' && p[2] != '\0') print = strcmp(p + 2, dest); else @@ -157,11 +157,11 @@ docd(char *dest, int print, int phys) if (print && iflag && curdir) { out1fmt("%s\n", curdir); /* - * ignore write errors to preserve the invariant that the - * current directory is changed iff the exit status is 0 - * (or 1 if -e was given and the full pathname could not be - * determined) - */ + * ignore write errors to preserve the invariant that the + * current directory is changed iff the exit status is 0 + * (or 1 if -e was given and the full pathname could not be + * determined) + */ flushout(out1); outclearerror(out1); } @@ -181,10 +181,10 @@ cdlogical(char *dest) int badstat; /* - * check each component of the path. if we find a symlink or - * something we cant stat, clear curdir to force a getcwd() - * next time we get the value of the current directory - */ + * check each component of the path. if we find a symlink or + * something we cant stat, clear curdir to force a getcwd() + * next time we get the value of the current directory + */ badstat = 0; path = stsavestr(dest); STARTSTACKSTR(p); @@ -273,10 +273,10 @@ findcwd(char *dir) char *path; /* - * if our argument is NULL, we dont know the current directory - * any more because we traversed a symbolic link or something - * we couldnt stat() - */ + * if our argument is NULL, we dont know the current directory + * any more because we traversed a symbolic link or something + * we couldnt stat() + */ if (dir == NULL || curdir == NULL) return getpwd2(); path = stsavestr(dir); diff --git a/cmd/posix/sh/easter.c b/cmd/posix/sh/easter.c @@ -261,9 +261,9 @@ detect_lang(const char *name) } /* - * anchored to the end of the name, so arch.txt (which contains "rc" - * but does not end in it) is never mistaken for a shell rc file - */ + * anchored to the end of the name, so arch.txt (which contains "rc" + * but does not end in it) is never mistaken for a shell rc file + */ nlen = strlen(name); if (nlen >= 2 && !strcmp(name + nlen - 2, "rc")) return LANG_SH; diff --git a/cmd/posix/sh/error.c b/cmd/posix/sh/error.c @@ -101,8 +101,8 @@ onint(void) sigprocmask(SIG_SETMASK, &sigs, NULL); /* - * this doesnt seem to be needed, since main() emits a newline - */ + * this doesnt seem to be needed, since main() emits a newline + */ #if 0 if (tcgetpgrp(0) == getpid()) write(STDERR_FILENO, "\n", 1); @@ -145,13 +145,13 @@ static void verrorwithstatus(int status, const char *msg, va_list ap) { /* - * an interrupt trumps an error. certain places catch error - * exceptions or transform them to a plain nonzero exit code - * in child processes, and if an error exception can be handled, - * an interrupt can be handled as well - * - * exraise() will disable interrupts for the exception handler - */ + * an interrupt trumps an error. certain places catch error + * exceptions or transform them to a plain nonzero exit code + * in child processes, and if an error exception can be handled, + * an interrupt can be handled as well + * + * exraise() will disable interrupts for the exception handler + */ FORCEINTON; #ifdef DEBUG diff --git a/cmd/posix/sh/eval.c b/cmd/posix/sh/eval.c @@ -717,11 +717,11 @@ isdeclarationcmd(struct narg *arg) if (arg == NULL) return (0); /* - * to also allow "command -p" and "command --" as part of - * a declaration command, add code here - * we do not do this, as ksh does not do it either and it - * is not required by POSIX - */ + * to also allow "command -p" and "command --" as part of + * a declaration command, add code here + * we do not do this, as ksh does not do it either and it + * is not required by POSIX + */ } return ( mustexpandto(arg->text, "export") || mustexpandto(arg->text, "readonly") @@ -907,30 +907,30 @@ evalcommand(union node *cmd, int flags, struct backcmd *backcmd) int cmd_flags = 0, bltinonly = 0; /* - * modify the command lookup path, if a PATH= assignment - * is present - */ + * modify the command lookup path, if a PATH= assignment + * is present + */ for (i = 0; i < varlist.count; i++) if (strncmp(varlist.args[i], PATH, sizeof(PATH) - 1) == 0) { path = varlist.args[i] + sizeof(PATH) - 1; /* - * on `PATH=... command`, we need to make - * sure that the command isnt using the - * non-updated hash table of the outer PATH - * setting and we need to make sure that - * the hash table isnt filled with items - * from the temporary setting - * - * it would be better to forbid using and - * updating the table while this command - * runs, by the command finding mechanism - * is heavily integrated with hash handling, - * so we just delete the hash before and after - * the command runs. partly deleting like - * changepatch() does doesnt seem worth the - * booking effort, since most such runs add - * directories in front of the new PATH - */ + * on `PATH=... command`, we need to make + * sure that the command isnt using the + * non-updated hash table of the outer PATH + * setting and we need to make sure that + * the hash table isnt filled with items + * from the temporary setting + * + * it would be better to forbid using and + * updating the table while this command + * runs, by the command finding mechanism + * is heavily integrated with hash handling, + * so we just delete the hash before and after + * the command runs. partly deleting like + * changepatch() does doesnt seem worth the + * booking effort, since most such runs add + * directories in front of the new PATH + */ clearcmdentry(); do_clearcmdentry = 1; } @@ -992,9 +992,9 @@ evalcommand(union node *cmd, int flags, struct backcmd *backcmd) break; } /* - * special builtins lose their special properties when - * called via 'command' - */ + * special builtins lose their special properties when + * called via 'command' + */ if (cmd_flags & DO_NOFUNC) cmdentry.special = 0; } @@ -1167,9 +1167,9 @@ evalcommand(union node *cmd, int flags, struct backcmd *backcmd) redirect(cmd->ncmd.redirect, mode); outclearerror(out1); /* - * if there is no command word, redirection errors should - * not be fatal but assignment errors should - */ + * if there is no command word, redirection errors should + * not be fatal but assignment errors should + */ if (argc == 0) cmdentry.special = 1; listsetvar(cmdenviron, cmdentry.special ? 0 : VNOSET); @@ -1285,9 +1285,9 @@ bltincmd(int argc, char **argv) return 127; } /* - * preserve exitstatus of a previous possible command substitution - * as POSIX mandates - */ + * preserve exitstatus of a previous possible command substitution + * as POSIX mandates + */ return exitstatus; } @@ -1359,9 +1359,9 @@ commandcmd(int argc __unused, char **argv __unused) error("commandcmd bad call"); /* - * do nothing successfully if no command was specified; - * ksh also does this - */ + * do nothing successfully if no command was specified; + * ksh also does this + */ return 0; } @@ -1397,9 +1397,9 @@ execcmd(int argc, char **argv) int i; /* - * because we have historically not supported any options, - * only treat "--" specially - */ + * because we have historically not supported any options, + * only treat "--" specially + */ if (argc > 1 && strcmp(argv[1], "--") == 0) argc--, argv++; if (argc > 1) { diff --git a/cmd/posix/sh/exec.c b/cmd/posix/sh/exec.c @@ -173,16 +173,16 @@ isbinary(const char *data, size_t len) if (nul == NULL) return 0; /* - * POSIX says we shall allow execution if the initial part intended - * to be parsed by the shell consists of characters and does not - * contain the NUL character. this allows concatenating a shell - * script (ending with exec or exit) and a binary payload - * - * in order to reject common binary files such as PNG images, check - * that there is a lowercase letter or expansion before the last - * newline before the NUL character, in addition to the check for - * the newline character suggested by POSIX - */ + * POSIX says we shall allow execution if the initial part intended + * to be parsed by the shell consists of characters and does not + * contain the NUL character. this allows concatenating a shell + * script (ending with exec or exit) and a binary payload + * + * in order to reject common binary files such as PNG images, check + * that there is a lowercase letter or expansion before the last + * newline before the NUL character, in addition to the check for + * the newline character suggested by POSIX + */ hasletter = 0; for (p = data; *p != '\0'; p++) { if ((*p >= 'a' && *p <= 'z') || *p == '$' || *p == '`') @@ -413,7 +413,7 @@ find_command(const char *name, struct cmdentry *entry, int act, const char *path #if FEATURE_NOEXEC || FEATURE_NOFORK /* when builtin dispatch is active, registered wexec builtins are available - * even if they are not present on the filesystem */ + * even if they are not present on the filesystem */ if ((wexec_get_noexec() || wexec_get_nofork()) && wexec_is_builtin(name)) { INTOFF; cmdp = cmdlookup(name, 1); diff --git a/cmd/posix/sh/expand.c b/cmd/posix/sh/expand.c @@ -319,9 +319,9 @@ argstr(const char *p, struct nodelist **restrict argbackq, int flag, struct word case ':': case '=': /* - * sort of a hack - expand tildes in variable - * assignments (after the first '=' and after ':'s) - */ + * sort of a hack - expand tildes in variable + * assignments (after the first '=' and after ':'s) + */ if (split_lit && !lit_quoted && strchr(ifsset() ? ifsval() : " \t\n", c) != NULL) { NEXTWORD(c, flag, expdest, dst); break; @@ -426,9 +426,9 @@ expari(const char *p, struct nodelist **restrict argbackq, int flag, struct word adj = strlen(expdest); STADJUST(adj, expdest); /* - * if this is quoted, a '-' must not indicate a range in [...] - * if this is not quoted, splitting may occur - */ + * if this is quoted, a '-' must not indicate a range in [...] + * if this is not quoted, splitting may occur + */ if (quoted ? result < 0 && begoff > 1 && flag & (EXP_GLOB | EXP_CASE) : flag & EXP_SPLIT) reprocess(expdest - adj - stackblock(), flag, VSNORMAL, quoted, dst); return p; @@ -756,9 +756,9 @@ evalvar(const char *p, struct nodelist **restrict argbackq, int flag, struct wor if (!set) break; /* - * terminate the string and start recording the pattern - * right after it - */ + * terminate the string and start recording the pattern + * right after it + */ STPUTC('\0', expdest); patloc = expdest - stackblock(); p = subevalvar_trim(p, argbackq, patloc, subtype, startloc); @@ -1021,8 +1021,8 @@ expandmeta(char *pattern, struct arglist *dstlist) } if (dstlist->count == firstmatch) { /* - * no matches - */ + * no matches + */ rmescapes(pattern); appendarglist(dstlist, pattern); } else { @@ -1250,9 +1250,9 @@ patmatch(const char *pattern, const char *string) if (localeisutf8) { wc = get_wc(&q); /* - * a '?' does not match invalid UTF-8 but a - * '*' does, so backtrack - */ + * a '?' does not match invalid UTF-8 but a + * '*' does, so backtrack + */ if (wc == 0) goto backtrack; } else @@ -1263,17 +1263,17 @@ patmatch(const char *pattern, const char *string) while (c == '*') c = *++p; /* - * if the pattern ends here, we know the string - * matches without needing to look at the rest of it - */ + * if the pattern ends here, we know the string + * matches without needing to look at the rest of it + */ if (c == '\0') return 1; /* - * first try the shortest match for the '*' that - * could work. we can forget any earlier '*' since - * there is no way having it match more characters - * can help us, given that we are already here - */ + * first try the shortest match for the '*' that + * could work. we can forget any earlier '*' since + * there is no way having it match more characters + * can help us, given that we are already here + */ bt_p = p; bt_q = q; break; @@ -1349,10 +1349,10 @@ patmatch(const char *pattern, const char *string) break; backtrack: /* - * if we have a mismatch (other than hitting the end - * of the string), go back to the last '*' seen and - * have it match one additional character - */ + * if we have a mismatch (other than hitting the end + * of the string), go back to the last '*' seen and + * have it match one additional character + */ if (bt_p == NULL) return 0; if (*bt_q == '\0') diff --git a/cmd/posix/sh/input.c b/cmd/posix/sh/input.c @@ -215,10 +215,10 @@ preadbuffer(void) while (parsefile->strpush) { /* - * add a space to the end of an alias to ensure that the - * alias remains in use while parsing its last word - * this avoids alias recursions - */ + * add a space to the end of an alias to ensure that the + * alias remains in use while parsing its last word + * this avoids alias recursions + */ if (parsenleft == -1 && parsefile->strpush->ap != NULL) return ' '; popstring(); @@ -354,7 +354,7 @@ popstring(void) parsenleft = sp->prevnleft; parselleft = sp->prevlleft; /* out2fmt_flush("*** calling popstring: restoring to '%s'\n", - * parsenextc); */ + * parsenextc); */ parsefile->strpush = sp->prev; if (sp != &(parsefile->basestrpush)) ckfree(sp); diff --git a/cmd/posix/sh/jobs.c b/cmd/posix/sh/jobs.c @@ -193,9 +193,9 @@ setjobctl(int on) } if (ttyfd < 10) { /* - * keep our TTY file descriptor out of the way of - * the user's redirections - */ + * keep our TTY file descriptor out of the way of + * the user's redirections + */ if ((i = fcntl(ttyfd, F_DUPFD_CLOEXEC, 10)) < 0) { jobctl_notty(); return; @@ -489,8 +489,8 @@ showjobs(int change, int mode) if (mode == SHOWJOBS_DEFAULT || mode == SHOWJOBS_VERBOSE) { jp->changed = 0; /* hack: discard jobs for which $! has not been - * referenced in interactive mode when they terminate - */ + * referenced in interactive mode when they terminate + */ if (jp->state == JOBDONE && !jp->remembered && (iflag || jp != bgjob)) { freejob(jp); } @@ -553,9 +553,9 @@ waitcmdloop(struct job *job) struct job *jp; /* - * loop until a process is terminated or stopped, or a SIGINT is - * received - */ + * loop until a process is terminated or stopped, or a SIGINT is + * received + */ do { if (job != NULL) { @@ -903,11 +903,11 @@ forkshell(struct job *jp, union node *n, int mode) pgrp = jp->ps[0].pid; if (setpgid(0, pgrp) == 0 && mode == FORK_FG && ttyfd >= 0) { /* - * each process in a pipeline must have the tty - * pgrp set before running its code - * only for pipelines of three or more processes - * could this be reduced to two calls - */ + * each process in a pipeline must have the tty + * pgrp set before running its code + * only for pipelines of three or more processes + * could this be reduced to two calls + */ if (tcsetpgrp(ttyfd, pgrp) < 0) error("tcsetpgrp failed, errno=%d", errno); } diff --git a/cmd/posix/sh/lineedit.c b/cmd/posix/sh/lineedit.c @@ -262,7 +262,7 @@ find_completions_recurse( snprintf(next_user, sizeof(next_user), "%s", user_prefix); if (S_ISDIR(st.st_mode)) { /* if it is a directory and doesnt end with - * slash, add slash */ + * slash, add slash */ len = strlen(next_user); if (len > 0 && next_user[len - 1] != '/') { strlcat(next_user, "/", sizeof(next_user)); @@ -384,7 +384,7 @@ complete_files(const char *word, int is_cmd, struct redlineCompletions *lc) path_to_split = (unescaped_word[1] == '\0') ? "" : (char *)(unescaped_word + 2); } else { /* ~username is not supported for abbreviation, fallback - * to home */ + * to home */ fs_dir = home ? home : "/"; user_prefix = "~/"; path_to_split = (char *)(unescaped_word + 1); @@ -420,7 +420,7 @@ complete_files(const char *word, int is_cmd, struct redlineCompletions *lc) } } else { /* empty path_to_split (e.g. exactly ~ or exactly / or empty - * word) */ + * word) */ comps[comp_count++] = p; } diff --git a/cmd/posix/sh/main.c b/cmd/posix/sh/main.c @@ -90,11 +90,11 @@ int main(int argc, char *argv[]) { /* - * as smark is accessed after a longjmp, it cannot be a local in main() - * the c standard specifies that the values of non-volatile local - * variables are unspecified after a jump if modified between the - * setjmp and longjmp - */ + * as smark is accessed after a longjmp, it cannot be a local in main() + * the c standard specifies that the values of non-volatile local + * variables are unspecified after a jump if modified between the + * setjmp and longjmp + */ static struct stackmark smark, smark2; volatile int state; char *shinit; @@ -130,10 +130,10 @@ main(int argc, char *argv[]) rootpid = getpid(); if (rootpid == 1) { /* - * make sh usable for invocation as interactive init - * substitute with init_path=/bin/sh, by opening - * file descriptors 0, 1, and 2 on /dev/console - */ + * make sh usable for invocation as interactive init + * substitute with init_path=/bin/sh, by opening + * file descriptors 0, 1, and 2 on /dev/console + */ if (fcntl(STDIN_FILENO, F_GETFL, NULL) == -1 && errno == EBADF) { (void)open(ARUU_PATH_DEVCONSOLE, O_RDWR); (void)setsid(); @@ -314,9 +314,9 @@ find_dot_file(char *basename) while ((fullname = padvance(&path, &opt, basename)) != NULL) { if ((stat(fullname, &statb) == 0) && S_ISREG(statb.st_mode)) { /* - * dont bother freeing here, since it will - * be freed by the caller - */ + * dont bother freeing here, since it will + * be freed by the caller + */ return fullname; } stunalloc(fullname); @@ -335,9 +335,9 @@ dotcmd(int argc, char **argv) exitstatus = 0; /* - * because we have historically not supported any options, - * only treat "--" specially - */ + * because we have historically not supported any options, + * only treat "--" specially + */ filename = argc > 2 && strcmp(argv[1], "--") == 0 ? argv[2] : argv[1]; fullname = find_dot_file(filename); diff --git a/cmd/posix/sh/miscbltin.c b/cmd/posix/sh/miscbltin.c @@ -134,18 +134,18 @@ fdctx_destroy(struct fdctx *fdc) if (fdc->buflen > 1) { /* - * reposition the file offset. here is the layout of buf: - * - * | off - * v - * |*****************|-------| - * buf ep buf+buflen - * |<- residue ->| - * - * off: current character - * ep: offset just after read(2) - * residue: length for reposition - */ + * reposition the file offset. here is the layout of buf: + * + * | off + * v + * |*****************|-------| + * buf ep buf+buflen + * |<- residue ->| + * + * off: current character + * ep: offset just after read(2) + * residue: length for reposition + */ residue = (fdc->ep - fdc->buf) - fdc->off; if (residue > 0) (void)lseek(fdc->fd, -residue, SEEK_CUR); @@ -271,8 +271,8 @@ readcmd(int argc __unused, char **argv __unused) if (timeout >= 0) { /* - * wait for something to become available - */ + * wait for something to become available + */ pfd.fd = STDIN_FILENO; pfd.events = POLLIN; status = sig = 0; @@ -297,8 +297,8 @@ readcmd(int argc __unused, char **argv __unused) } sigprocmask(SIG_SETMASK, &oset, NULL); /* - * if theres nothing ready, return an error - */ + * if theres nothing ready, return an error + */ if (status <= 0) { while (*ap != NULL) setvar(*ap++, "", 0); @@ -420,9 +420,9 @@ readcmd(int argc __unused, char **argv __unused) STACKSTRNUL(p); /* - * remove trailing IFS chars: always remove whitespace, dont remove - * non-whitespace unless it was naked - */ + * remove trailing IFS chars: always remove whitespace, dont remove + * non-whitespace unless it was naked + */ if (saveall <= 1) lastnonifsws = lastnonifs; stackblock()[lastnonifsws + 1] = '\0'; diff --git a/cmd/posix/sh/options.c b/cmd/posix/sh/options.c @@ -159,17 +159,17 @@ options(int cmdline) if (p[0] == '-' && p[1] == '\0') goto end_options2; /* * - * for the benefit of `#!' lines in shell scripts, - * treat a string of '-- *#.*' the same as '--' - * this is needed so that a script starting with: - * #!/bin/sh, # -*- perl -*- - * will continue to work after a change is made to - * kern/imgact_shell.c to NOT token-ize the options - * specified on a '#!' line. a bit of a kludge, - * but that trick is recommended in documentation - * for some scripting languages, and we might as - * well continue to support it - */ + * for the benefit of `#!' lines in shell scripts, + * treat a string of '-- *#.*' the same as '--' + * this is needed so that a script starting with: + * #!/bin/sh, # -*- perl -*- + * will continue to work after a change is made to + * kern/imgact_shell.c to NOT token-ize the options + * specified on a '#!' line. a bit of a kludge, + * but that trick is recommended in documentation + * for some scripting languages, and we might as + * well continue to support it + */ if (p[0] == '-') { kp = p + 1; while (*kp == ' ' || *kp == '\t') @@ -211,11 +211,11 @@ end_options1: } /* - * when processing `set', a "--" means the remaining arguments - * replace the positional parameters in the active shell. if - * there are no remaining options, then all the positional - * parameters are cleared (equivalent to doing ``shift $#'') - */ + * when processing `set', a "--" means the remaining arguments + * replace the positional parameters in the active shell. if + * there are no remaining options, then all the positional + * parameters are cleared (equivalent to doing ``shift $#'') + */ end_options2: if (!cmdline) { if (*argptr == NULL) @@ -224,14 +224,14 @@ end_options2: } /* - * at this point we are processing options given to 'sh' on a command - * line. if an end-of-options marker ("-" or "--") is followed by an - * arg of "#", then skip over all remaining arguments. some scripting - * languages (e.g.: perl) document that /bin/sh will implement this - * behavior, and they recommend that users take advantage of it to - * solve certain issues that can come up when writing a perl script - * yes, this feature is in /bin/sh to help users write perl scripts - */ + * at this point we are processing options given to 'sh' on a command + * line. if an end-of-options marker ("-" or "--") is followed by an + * arg of "#", then skip over all remaining arguments. some scripting + * languages (e.g.: perl) document that /bin/sh will implement this + * behavior, and they recommend that users take advantage of it to + * solve certain issues that can come up when writing a perl script + * yes, this feature is in /bin/sh to help users write perl scripts + */ p = *argptr; if (p != NULL && p[0] == '#' && p[1] == '\0') { while (*argptr != NULL) diff --git a/cmd/posix/sh/output.h b/cmd/posix/sh/output.h @@ -54,28 +54,28 @@ extern struct output errout; /* to fd 2 */ extern struct output memout; extern struct output *out1; /* &memout if backquote, otherwise &output */ extern struct output *out2; /* &memout if backquote with 2>&1, otherwise - * &errout */ + * &errout */ -void outcslow(int, struct output *); -void out1str(const char *); -void out1qstr(const char *); -void out2str(const char *); -void out2qstr(const char *); -void outstr(const char *, struct output *); -void outqstr(const char *, struct output *); -void outbin(const void *, size_t, struct output *); -void emptyoutbuf(struct output *); -void flushall(void); -void flushout(struct output *); -void freestdout(void); -int outiserror(struct output *); -void outclearerror(struct output *); -void outfmt(struct output *, const char *, ...) __printflike(2, 3); -void out1fmt(const char *, ...) __printflike(1, 2); -void out2fmt_flush(const char *, ...) __printflike(1, 2); -void fmtstr(char *, int, const char *, ...) __printflike(3, 4); -void doformat(struct output *, const char *, va_list) __printflike(2, 0); -int xwrite(int, const char *, int); +void outcslow(int, struct output *); +void out1str(const char *); +void out1qstr(const char *); +void out2str(const char *); +void out2qstr(const char *); +void outstr(const char *, struct output *); +void outqstr(const char *, struct output *); +void outbin(const void *, size_t, struct output *); +void emptyoutbuf(struct output *); +void flushall(void); +void flushout(struct output *); +void freestdout(void); +int outiserror(struct output *); +void outclearerror(struct output *); +void outfmt(struct output *, const char *, ...) __printflike(2, 3); +void out1fmt(const char *, ...) __printflike(1, 2); +void out2fmt_flush(const char *, ...) __printflike(1, 2); +void fmtstr(char *, int, const char *, ...) __printflike(3, 4); +void doformat(struct output *, const char *, va_list) __printflike(2, 0); +int xwrite(int, const char *, int); #define outc(c, file) \ ((file)->nextc == (file)->bufend ? (emptyoutbuf(file), *(file)->nextc++ = (c)) \ diff --git a/cmd/posix/sh/parser.c b/cmd/posix/sh/parser.c @@ -212,8 +212,8 @@ parsecmd(int interact) int t; /* this assumes the parser is not re-entered, - * which could happen if we add command substitution on PS1/PS2 - */ + * which could happen if we add command substitution on PS1/PS2 + */ parser_temp_free_all(); heredoclist = NULL; @@ -245,8 +245,8 @@ parsewordexp(void) int t; /* this assumes the parser is not re-entered, - * which could happen if we add command substitution on PS1/PS2 - */ + * which could happen if we add command substitution on PS1/PS2 + */ parser_temp_free_all(); heredoclist = NULL; @@ -493,9 +493,9 @@ command(void) n2->narg.next = NULL; n1->nfor.args = n2; /* - * newline or semicolon here is optional (but note - * that the original bourne shell only allowed NL) - */ + * newline or semicolon here is optional (but note + * that the original bourne shell only allowed NL) + */ if (lasttoken != TSEMI) tokpushback++; } @@ -628,10 +628,10 @@ simplecmd(union node **rpp, union node *redir) args = NULL; app = &args; /* - * we save the incoming value, because we need this for shell - * functions. there can not be a redirect or an argument between - * the function name and the open parenthesis - */ + * we save the incoming value, because we need this for shell + * functions. there can not be a redirect or an argument between + * the function name and the open parenthesis + */ orig_rpp = rpp; savecheckkwd = CHKALIAS; @@ -653,11 +653,11 @@ simplecmd(union node **rpp, union node *redir) consumetoken(TRP); funclinno = plinno; /* - * - require plain text - * - functions with '/' cannot be called - * - reject name=() - * - reject ksh extended glob patterns - */ + * - require plain text + * - functions with '/' cannot be called + * - reject name=() + * - reject ksh extended glob patterns + */ if (!noexpand(n->narg.text) || quoteflag || strchr(n->narg.text, '/') || strchr("!%*+-=?@}~", n->narg.text[strlen(n->narg.text) - 1])) synerror("Bad function name"); @@ -819,8 +819,8 @@ top: t = xxreadtoken(); /* - * eat newlines - */ + * eat newlines + */ if (checkkwd & CHKNL) { while (t == TNL) { parseheredoc(); @@ -829,8 +829,8 @@ top: } /* - * check for keywords and aliases - */ + * check for keywords and aliases + */ if (t == TWORD && !quoteflag) { const char *const *pp; @@ -1104,8 +1104,8 @@ parsebackq(char *out, struct nodelist **pbqlist, int oldstyle, int dblquote, int INTON; if (oldstyle) { /* we must read until the closing backquote, giving special - * treatment to some slashes, and then push the string and - * reread it as input, interpreting it normally */ + * treatment to some slashes, and then push the string and + * reread it as input, interpreting it normally */ char *oout; int c; int olen; @@ -1173,9 +1173,9 @@ parsebackq(char *out, struct nodelist **pbqlist, int oldstyle, int dblquote, int (*nlpp)->n = n; if (oldstyle) { /* - * start reading from old file again, ignoring any pushed back - * tokens left from the backquote parsing - */ + * start reading from old file again, ignoring any pushed back + * tokens left from the backquote parsing + */ popfile(); tokpushback = 0; } @@ -1327,9 +1327,9 @@ readcstyleesc(char *out) if (initial_localeisutf8 && v > 127) { CHECKSTRSPACE(4, out); /* - * we cannot use wctomb() as the locale may have - * changed - */ + * we cannot use wctomb() as the locale may have + * changed + */ if (v <= 0x7ff) { USTPUTC(0xc0 | v >> 6, out); USTPUTC(0x80 | (v & 0x3f), out); @@ -1355,9 +1355,9 @@ readcstyleesc(char *out) } vc = (char)v; /* - * we cant handle NUL bytes - * POSIX says we should skip till the closing quote - */ + * we cant handle NUL bytes + * POSIX says we should skip till the closing quote + */ if (vc == '\0') { while ((c = pgetc()) != '\'') { if (c == '\\') @@ -1430,152 +1430,153 @@ readtoken1(int firstc, char const *initialsyntax, const char *eofmark, int strip state[level].category = TSTATE_TOP; STARTSTACKSTR(out); -loop: { /* for each line, until end of word */ - if (eofmark && eofmark != NOEOFMARK) - /* set c to PEOF if at end of here document */ - c = checkend(c, eofmark, striptabs); - for (;;) { /* until end of line or end of word */ - CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */ - - synentry = state[level].syntax[c]; - - switch (synentry) { - case CNL: /* '\n' */ - if (level == 0) - goto endword; /* exit outer loop */ - /* FALLTHROUGH */ - case CQNL: - USTPUTC(c, out); - plinno++; - if (doprompt) - setprompt(2); - else - setprompt(0); - c = pgetc(); - goto loop; /* continue outer loop */ - case CSBACK: - if (sqiscstyle) { - out = readcstyleesc(out); - break; - } - /* FALLTHROUGH */ - case CWORD: - USTPUTC(c, out); - break; - case CCTL: - if (eofmark == NULL || initialsyntax != SQSYNTAX) - USTPUTC(CTLESC, out); - USTPUTC(c, out); - break; - case CBACK: /* backslash */ - c = pgetc(); - if (c == PEOF) { - USTPUTC('\\', out); - pungetc(); - } else if (c == '\n') { +loop: + { /* for each line, until end of word */ + if (eofmark && eofmark != NOEOFMARK) + /* set c to PEOF if at end of here document */ + c = checkend(c, eofmark, striptabs); + for (;;) { /* until end of line or end of word */ + CHECKSTRSPACE(4, out); /* permit 4 calls to USTPUTC */ + + synentry = state[level].syntax[c]; + + switch (synentry) { + case CNL: /* '\n' */ + if (level == 0) + goto endword; /* exit outer loop */ + /* FALLTHROUGH */ + case CQNL: + USTPUTC(c, out); plinno++; if (doprompt) setprompt(2); else setprompt(0); - } else { - if (state[level].syntax == DQSYNTAX && c != '\\' && c != '`' && c != '$' - && (c != '"' || (eofmark != NULL && newvarnest == 0)) - && (c != '}' || state[level].category != TSTATE_VAR_OLD)) - USTPUTC('\\', out); - if ((eofmark == NULL || newvarnest > 0) && state[level].syntax == BASESYNTAX) - USTPUTC(CTLQUOTEMARK, out); - if (SQSYNTAX[c] == CCTL) - USTPUTC(CTLESC, out); - USTPUTC(c, out); - if ((eofmark == NULL || newvarnest > 0) && state[level].syntax == BASESYNTAX - && state[level].category == TSTATE_VAR_OLD) - USTPUTC(CTLQUOTEEND, out); - quotef++; - } - break; - case CSQUOTE: - USTPUTC(CTLQUOTEMARK, out); - state[level].syntax = SQSYNTAX; - sqiscstyle = 0; - break; - case CDQUOTE: - USTPUTC(CTLQUOTEMARK, out); - state[level].syntax = DQSYNTAX; - break; - case CENDQUOTE: - if (eofmark != NULL && newvarnest == 0) + c = pgetc(); + goto loop; /* continue outer loop */ + case CSBACK: + if (sqiscstyle) { + out = readcstyleesc(out); + break; + } + /* FALLTHROUGH */ + case CWORD: USTPUTC(c, out); - else { - if (state[level].category == TSTATE_VAR_OLD) - USTPUTC(CTLQUOTEEND, out); - state[level].syntax = BASESYNTAX; - quotef++; - } - break; - case CVAR: /* '$' */ - PARSESUB(); /* parse substitution */ - break; - case CENDVAR: /* '}' */ - if (level > 0 - && ((state[level].category == TSTATE_VAR_OLD - && state[level].syntax == state[level - 1].syntax) - || (state[level].category == TSTATE_VAR_NEW - && state[level].syntax == BASESYNTAX))) { - if (state[level].category == TSTATE_VAR_NEW) - newvarnest--; - level--; - USTPUTC(CTLENDVAR, out); - } else { + break; + case CCTL: + if (eofmark == NULL || initialsyntax != SQSYNTAX) + USTPUTC(CTLESC, out); USTPUTC(c, out); - } - break; - case CLP: /* '(' in arithmetic */ - state[level].parenlevel++; - USTPUTC(c, out); - break; - case CRP: /* ')' in arithmetic */ - if (state[level].parenlevel > 0) { + break; + case CBACK: /* backslash */ + c = pgetc(); + if (c == PEOF) { + USTPUTC('\\', out); + pungetc(); + } else if (c == '\n') { + plinno++; + if (doprompt) + setprompt(2); + else + setprompt(0); + } else { + if (state[level].syntax == DQSYNTAX && c != '\\' && c != '`' && c != '$' + && (c != '"' || (eofmark != NULL && newvarnest == 0)) + && (c != '}' || state[level].category != TSTATE_VAR_OLD)) + USTPUTC('\\', out); + if ((eofmark == NULL || newvarnest > 0) && state[level].syntax == BASESYNTAX) + USTPUTC(CTLQUOTEMARK, out); + if (SQSYNTAX[c] == CCTL) + USTPUTC(CTLESC, out); + USTPUTC(c, out); + if ((eofmark == NULL || newvarnest > 0) && state[level].syntax == BASESYNTAX + && state[level].category == TSTATE_VAR_OLD) + USTPUTC(CTLQUOTEEND, out); + quotef++; + } + break; + case CSQUOTE: + USTPUTC(CTLQUOTEMARK, out); + state[level].syntax = SQSYNTAX; + sqiscstyle = 0; + break; + case CDQUOTE: + USTPUTC(CTLQUOTEMARK, out); + state[level].syntax = DQSYNTAX; + break; + case CENDQUOTE: + if (eofmark != NULL && newvarnest == 0) + USTPUTC(c, out); + else { + if (state[level].category == TSTATE_VAR_OLD) + USTPUTC(CTLQUOTEEND, out); + state[level].syntax = BASESYNTAX; + quotef++; + } + break; + case CVAR: /* '$' */ + PARSESUB(); /* parse substitution */ + break; + case CENDVAR: /* '}' */ + if (level > 0 + && ((state[level].category == TSTATE_VAR_OLD + && state[level].syntax == state[level - 1].syntax) + || (state[level].category == TSTATE_VAR_NEW + && state[level].syntax == BASESYNTAX))) { + if (state[level].category == TSTATE_VAR_NEW) + newvarnest--; + level--; + USTPUTC(CTLENDVAR, out); + } else { + USTPUTC(c, out); + } + break; + case CLP: /* '(' in arithmetic */ + state[level].parenlevel++; USTPUTC(c, out); - --state[level].parenlevel; - } else { - if (pgetc_linecont() == ')') { - if (level > 0 && state[level].category == TSTATE_ARITH) { - level--; - USTPUTC(CTLENDARI, out); - } else - USTPUTC(')', out); + break; + case CRP: /* ')' in arithmetic */ + if (state[level].parenlevel > 0) { + USTPUTC(c, out); + --state[level].parenlevel; } else { - /* - * unbalanced parens - * (dont 2nd guess - no error) - */ - pungetc(); - USTPUTC(')', out); + if (pgetc_linecont() == ')') { + if (level > 0 && state[level].category == TSTATE_ARITH) { + level--; + USTPUTC(CTLENDARI, out); + } else + USTPUTC(')', out); + } else { + /* + * unbalanced parens + * (dont 2nd guess - no error) + */ + pungetc(); + USTPUTC(')', out); + } } - } - break; - case CBQUOTE: /* '`' */ - out = parsebackq( - out, - &bqlist, - 1, - state[level].syntax == DQSYNTAX && (eofmark == NULL || newvarnest > 0), - state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX - ); - break; - case CEOF: - goto endword; /* exit outer loop */ - case CIGN: - break; - default: - if (level == 0) + break; + case CBQUOTE: /* '`' */ + out = parsebackq( + out, + &bqlist, + 1, + state[level].syntax == DQSYNTAX && (eofmark == NULL || newvarnest > 0), + state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX + ); + break; + case CEOF: goto endword; /* exit outer loop */ - USTPUTC(c, out); + case CIGN: + break; + default: + if (level == 0) + goto endword; /* exit outer loop */ + USTPUTC(c, out); + } + c = pgetc_macro(); } - c = pgetc_macro(); } -} endword: if (state[level].syntax == ARISYNTAX) synerror("Missing '))'"); @@ -1606,216 +1607,219 @@ endword: /* end of readtoken routine */ /* - * parse a substitution. at this point, we have read the dollar sign - * and nothing else - */ + * parse a substitution. at this point, we have read the dollar sign + * and nothing else + */ -parsesub: { - int subtype; - int typeloc; - int flags; - char *p; - static const char types[] = "}-+?="; - int linno; - int length; - int c1; - - c = pgetc_linecont(); - if (c == '(') { /* $(command) or $((arith)) */ - if (pgetc_linecont() == '(') { - PARSEARITH(); - } else { - pungetc(); - out = parsebackq( - out, - &bqlist, - 0, - state[level].syntax == DQSYNTAX && (eofmark == NULL || newvarnest > 0), - state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX - ); - } - } else if (c == '{' || is_name(c) || is_special(c)) { - USTPUTC(CTLVAR, out); - typeloc = out - stackblock(); - USTPUTC(VSNORMAL, out); - subtype = VSNORMAL; - flags = 0; - if (c == '{') { - c = pgetc_linecont(); - subtype = 0; - } - varname: - if (!is_eof(c) && is_name(c)) { - length = 0; - do { - STPUTC(c, out); - c = pgetc_linecont(); - length++; - } while (!is_eof(c) && is_in_name(c)); - if (length == 6 && strncmp(out - length, "LINENO", length) == 0) { - /* replace the variable name with the - * current line number */ - STADJUST(-6, out); - CHECKSTRSPACE(11, out); - linno = plinno; - if (funclinno != 0) - linno -= funclinno - 1; - length = snprintf(out, 11, "%d", linno); - if (length > 10) - length = 10; - out += length; - flags |= VSLINENO; +parsesub: + { + int subtype; + int typeloc; + int flags; + char *p; + static const char types[] = "}-+?="; + int linno; + int length; + int c1; + + c = pgetc_linecont(); + if (c == '(') { /* $(command) or $((arith)) */ + if (pgetc_linecont() == '(') { + PARSEARITH(); + } else { + pungetc(); + out = parsebackq( + out, + &bqlist, + 0, + state[level].syntax == DQSYNTAX && (eofmark == NULL || newvarnest > 0), + state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX + ); } - } else if (is_digit(c)) { - if (subtype != VSNORMAL) { + } else if (c == '{' || is_name(c) || is_special(c)) { + USTPUTC(CTLVAR, out); + typeloc = out - stackblock(); + USTPUTC(VSNORMAL, out); + subtype = VSNORMAL; + flags = 0; + if (c == '{') { + c = pgetc_linecont(); + subtype = 0; + } + varname: + if (!is_eof(c) && is_name(c)) { + length = 0; do { STPUTC(c, out); c = pgetc_linecont(); - } while (is_digit(c)); - } else { - USTPUTC(c, out); - c = pgetc_linecont(); - } - } else if (is_special(c)) { - c1 = c; - c = pgetc_linecont(); - if (subtype == 0 && c1 == '#') { - subtype = VSLENGTH; - if (strchr(types, c) == NULL && c != ':' && c != '#' && c != '%') - goto varname; + length++; + } while (!is_eof(c) && is_in_name(c)); + if (length == 6 && strncmp(out - length, "LINENO", length) == 0) { + /* replace the variable name with the + * current line number */ + STADJUST(-6, out); + CHECKSTRSPACE(11, out); + linno = plinno; + if (funclinno != 0) + linno -= funclinno - 1; + length = snprintf(out, 11, "%d", linno); + if (length > 10) + length = 10; + out += length; + flags |= VSLINENO; + } + } else if (is_digit(c)) { + if (subtype != VSNORMAL) { + do { + STPUTC(c, out); + c = pgetc_linecont(); + } while (is_digit(c)); + } else { + USTPUTC(c, out); + c = pgetc_linecont(); + } + } else if (is_special(c)) { c1 = c; c = pgetc_linecont(); - if (c1 != '}' && c == '}') { + if (subtype == 0 && c1 == '#') { + subtype = VSLENGTH; + if (strchr(types, c) == NULL && c != ':' && c != '#' && c != '%') + goto varname; + c1 = c; + c = pgetc_linecont(); + if (c1 != '}' && c == '}') { + pungetc(); + c = c1; + goto varname; + } pungetc(); - c = c1; - goto varname; + c = c1; + c1 = '#'; + subtype = 0; } - pungetc(); - c = c1; - c1 = '#'; - subtype = 0; + USTPUTC(c1, out); + } else { + subtype = VSERROR; + if (c == '}') + pungetc(); + else if (c == '\n' || c == PEOF) + synerror( + "Unexpected end of line in " + "substitution" + ); + else if (BASESYNTAX[c] != CCTL) + USTPUTC(c, out); } - USTPUTC(c1, out); - } else { - subtype = VSERROR; - if (c == '}') + if (subtype == 0) { + switch (c) { + case ':': + flags |= VSNUL; + c = pgetc_linecont(); + /* FALLTHROUGH */ + default: + p = strchr(types, c); + if (p == NULL) { + if (c == '\n' || c == PEOF) + synerror( + "Unexpected end of " + "line in substitution" + ); + if (flags == VSNUL) + STPUTC(':', out); + if (BASESYNTAX[c] != CCTL) + STPUTC(c, out); + subtype = VSERROR; + } else + subtype = p - types + VSNORMAL; + break; + case '%': + case '#': { + int cc = c; + subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT; + c = pgetc_linecont(); + if (c == cc) + subtype++; + else + pungetc(); + break; + } + } + } else if (subtype != VSERROR) { + if (subtype == VSLENGTH && c != '}') + subtype = VSERROR; pungetc(); - else if (c == '\n' || c == PEOF) - synerror( - "Unexpected end of line in " - "substitution" - ); - else if (BASESYNTAX[c] != CCTL) - USTPUTC(c, out); - } - if (subtype == 0) { - switch (c) { - case ':': - flags |= VSNUL; - c = pgetc_linecont(); - /* FALLTHROUGH */ - default: - p = strchr(types, c); - if (p == NULL) { - if (c == '\n' || c == PEOF) - synerror( - "Unexpected end of " - "line in substitution" - ); - if (flags == VSNUL) - STPUTC(':', out); - if (BASESYNTAX[c] != CCTL) - STPUTC(c, out); - subtype = VSERROR; + } + STPUTC('=', out); + if (state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX) + flags |= VSQUOTE; + *(stackblock() + typeloc) = subtype | flags; + if (subtype != VSNORMAL) { + if (level + 1 >= maxnest) { + maxnest *= 2; + if (state == state_static) { + state = parser_temp_alloc(maxnest * sizeof(*state)); + memcpy(state, state_static, MAXNEST_static * sizeof(*state)); } else - subtype = p - types + VSNORMAL; - break; - case '%': - case '#': { - int cc = c; - subtype = c == '#' ? VSTRIMLEFT : VSTRIMRIGHT; - c = pgetc_linecont(); - if (c == cc) - subtype++; - else - pungetc(); - break; + state = parser_temp_realloc(state, maxnest * sizeof(*state)); + } + level++; + state[level].parenlevel = 0; + if (subtype == VSMINUS || subtype == VSPLUS || subtype == VSQUESTION + || subtype == VSASSIGN) { + /* + * for operators that were in the bourne shell, + * inherit the double-quote state + */ + state[level].syntax = state[level - 1].syntax; + state[level].category = TSTATE_VAR_OLD; + } else { + /* + * the other operators take a pattern, + * so go to BASESYNTAX + * also, ' and " are now special, even + * in here documents + */ + state[level].syntax = BASESYNTAX; + state[level].category = TSTATE_VAR_NEW; + newvarnest++; } } - } else if (subtype != VSERROR) { - if (subtype == VSLENGTH && c != '}') - subtype = VSERROR; + } else if (c == '\'' && state[level].syntax == BASESYNTAX) { + /* $'cstylequotes' */ + USTPUTC(CTLQUOTEMARK, out); + state[level].syntax = SQSYNTAX; + sqiscstyle = 1; + } else { + USTPUTC('$', out); pungetc(); } - STPUTC('=', out); - if (state[level].syntax == DQSYNTAX || state[level].syntax == ARISYNTAX) - flags |= VSQUOTE; - *(stackblock() + typeloc) = subtype | flags; - if (subtype != VSNORMAL) { - if (level + 1 >= maxnest) { - maxnest *= 2; - if (state == state_static) { - state = parser_temp_alloc(maxnest * sizeof(*state)); - memcpy(state, state_static, MAXNEST_static * sizeof(*state)); - } else - state = parser_temp_realloc(state, maxnest * sizeof(*state)); - } - level++; - state[level].parenlevel = 0; - if (subtype == VSMINUS || subtype == VSPLUS || subtype == VSQUESTION || subtype == VSASSIGN) { - /* - * for operators that were in the bourne shell, - * inherit the double-quote state - */ - state[level].syntax = state[level - 1].syntax; - state[level].category = TSTATE_VAR_OLD; - } else { - /* - * the other operators take a pattern, - * so go to BASESYNTAX - * also, ' and " are now special, even - * in here documents - */ - state[level].syntax = BASESYNTAX; - state[level].category = TSTATE_VAR_NEW; - newvarnest++; - } - } - } else if (c == '\'' && state[level].syntax == BASESYNTAX) { - /* $'cstylequotes' */ - USTPUTC(CTLQUOTEMARK, out); - state[level].syntax = SQSYNTAX; - sqiscstyle = 1; - } else { - USTPUTC('$', out); - pungetc(); + goto parsesub_return; } - goto parsesub_return; -} /* * parse an arithmetic expansion (indicate start of one and set state) */ -parsearith: { - if (level + 1 >= maxnest) { - maxnest *= 2; - if (state == state_static) { - state = parser_temp_alloc(maxnest * sizeof(*state)); - memcpy(state, state_static, MAXNEST_static * sizeof(*state)); - } else - state = parser_temp_realloc(state, maxnest * sizeof(*state)); +parsearith: + { + if (level + 1 >= maxnest) { + maxnest *= 2; + if (state == state_static) { + state = parser_temp_alloc(maxnest * sizeof(*state)); + memcpy(state, state_static, MAXNEST_static * sizeof(*state)); + } else + state = parser_temp_realloc(state, maxnest * sizeof(*state)); + } + level++; + state[level].syntax = ARISYNTAX; + state[level].parenlevel = 0; + state[level].category = TSTATE_ARITH; + USTPUTC(CTLARI, out); + if (state[level - 1].syntax == DQSYNTAX) + USTPUTC('"', out); + else + USTPUTC(' ', out); + goto parsearith_return; } - level++; - state[level].syntax = ARISYNTAX; - state[level].parenlevel = 0; - state[level].category = TSTATE_ARITH; - USTPUTC(CTLARI, out); - if (state[level - 1].syntax == DQSYNTAX) - USTPUTC('"', out); - else - USTPUTC(' ', out); - goto parsearith_return; -} } /* end of readtoken */ @@ -1976,11 +1980,11 @@ getusername(char *name, size_t namelen) euid = geteuid(); /* - * handle the case when there is more than one - * login with the same UID, or when the login - * returned by getlogin(2) does no longer match - * the current UID - */ + * handle the case when there is more than one + * login with the same UID, or when the login + * returned by getlogin(2) does no longer match + * the current UID + */ pw = getpwlogin(); if (pw == NULL || pw->pw_uid != euid) pw = getpwuid(euid); @@ -2011,8 +2015,8 @@ getprompt(void *unused __unused) static char internal_error[] = "??"; /* - * select prompt format - */ + * select prompt format + */ switch (whichprompt) { case 0: fmt = ""; @@ -2030,8 +2034,8 @@ getprompt(void *unused __unused) } /* - * format prompt string - */ + * format prompt string + */ for (i = 0; (i < PROMPTLEN - 1) && (*fmt != '\0'); i++, fmt++) { if (*fmt == '$') { const char *varname_start, *varname_end, *value; @@ -2065,9 +2069,9 @@ getprompt(void *unused __unused) varname_end = fmt; } else { /* - * not a valid variable reference - * output literal '$' - */ + * not a valid variable reference + * output literal '$' + */ ps[i] = '$'; if (braced && i < PROMPTLEN - 2) ps[++i] = '{'; @@ -2093,7 +2097,7 @@ getprompt(void *unused __unused) fmt++; } else { /* missing closing brace, treat as - * literal */ + * literal */ ps[i] = '$'; if (i < PROMPTLEN - 2) ps[++i] = '{'; @@ -2149,10 +2153,10 @@ getprompt(void *unused __unused) } /* - * adjust fmt and i for the loop increment - * fmt will be incremented by the for loop, - * so position it one before where we want - */ + * adjust fmt and i for the loop increment + * fmt will be incremented by the for loop, + * so position it one before where we want + */ fmt--; i--; continue; @@ -2163,19 +2167,19 @@ getprompt(void *unused __unused) switch (*++fmt) { /* - * non-printing sequence begin and end - */ + * non-printing sequence begin and end + */ case '[': case ']': ps[i] = '\001'; break; /* - * literal \ and some ASCII characters: - * \a bel - * \e esc - * \r cr - */ + * literal \ and some ASCII characters: + * \a bel + * \e esc + * \r cr + */ case '\\': case 'a': case 'e': @@ -2191,8 +2195,8 @@ getprompt(void *unused __unused) break; /* - * CRLF sequence - */ + * CRLF sequence + */ case 'n': if (i < PROMPTLEN - 3) { ps[i++] = '\r'; @@ -2201,18 +2205,18 @@ getprompt(void *unused __unused) break; /* - * print the current time as per provided strftime format - */ + * print the current time as per provided strftime format + */ case 'D': { char tfmt[128] = "%X"; /* \d{} means %x */ struct tm *now; if (fmt[1] != '{') { /* - * "\d" but not "\d{", so treat the '\' - * literally and rewind fmt to treat 'd' - * literally next iteration - */ + * "\d" but not "\d{", so treat the '\' + * literally and rewind fmt to treat 'd' + * literally next iteration + */ ps[i] = '\\'; fmt--; break; @@ -2224,12 +2228,12 @@ getprompt(void *unused __unused) end = memccpy(tfmt, fmt, '}', sizeof(tfmt)); if (end == NULL) { /* - * format too long or no '}', so - * ignore "\d{" altogether - * the loop will do i++, but nothing - * was written to ps, so do i-- here - * rewind fmt for similar reason - */ + * format too long or no '}', so + * ignore "\d{" altogether + * the loop will do i++, but nothing + * was written to ps, so do i-- here + * rewind fmt for similar reason + */ i--; fmt--; break; @@ -2244,11 +2248,11 @@ getprompt(void *unused __unused) } /* - * hostname - * - * \h specifies just the local hostname, - * \h specifies fully-qualified hostname - */ + * hostname + * + * \h specifies just the local hostname, + * \h specifies fully-qualified hostname + */ case 'h': case 'H': ps[i] = '\0'; @@ -2262,8 +2266,8 @@ getprompt(void *unused __unused) break; /* - * user name - */ + * user name + */ case 'u': ps[i] = '\0'; getusername(&ps[i], PROMPTLEN - i); @@ -2273,11 +2277,11 @@ getprompt(void *unused __unused) break; /* - * working directory - * - * \w specifies just the final component, - * \w specifies the entire path - */ + * working directory + * + * \w specifies just the final component, + * \w specifies the entire path + */ case 'W': case 'w': pwd = lookupvar("PWD"); @@ -2303,17 +2307,17 @@ getprompt(void *unused __unused) break; /* - * superuser status - * - * '$' for normal users, '#' for root - */ + * superuser status + * + * '$' for normal users, '#' for root + */ case '$': ps[i] = (geteuid() != 0) ? '$' : '#'; break; /* - * emit unrecognized formats verbatim - */ + * emit unrecognized formats verbatim + */ default: ps[i] = '\\'; if (i < PROMPTLEN - 2) diff --git a/cmd/posix/sh/parser.h b/cmd/posix/sh/parser.h @@ -48,8 +48,8 @@ #define VSTYPE 0x0f /* type of variable substitution */ #define VSNUL 0x10 /* colon, treat the empty string as unset */ #define VSLINENO \ - 0x20 /* expansion of $LINENO, the line number \ - * follows immediately */ + 0x20 /* expansion of $LINENO, the line number \ + * follows immediately */ #define VSQUOTE 0x80 /* inside double quotes, suppress splitting */ /* values of VSTYPE field */ diff --git a/cmd/posix/sh/printf.c b/cmd/posix/sh/printf.c @@ -126,13 +126,13 @@ main(int argc, char *argv[]) INTOFF; #endif /* - * basic algorithm is to scan the format string for conversion - * specifications, once one is found, find out if the field - * width or precision is a '*'; if it is, gather up value. note, - * format strings are reused as necessary to use up the provided - * arguments, arguments of zero/null string are provided to use - * up the format string - */ + * basic algorithm is to scan the format string for conversion + * specifications, once one is found, find out if the field + * width or precision is a '*'; if it is, gather up value. note, + * format strings are reused as necessary to use up the provided + * arguments, arguments of zero/null string are provided to use + * up the format string + */ fmt = format = *argv; escape(fmt, 1, &len); /* backslash interpretation */ rval = end = 0; @@ -322,15 +322,15 @@ printf_doformat(char *fmt, int *rval) *dptr = 0; /* - * look for a length modifier. POSIX doesnt have these, so - * we only support them for floating-point conversions, which - * are extensions. this is useful because the l modifier can - * be used to gain extra range and precision, while omitting - * it is more likely to produce consistent results on different - * architectures. this is not so important for integers - * because overflow is the only bad thing that can happen to - * them, but consider the command printf %a 1.1 - */ + * look for a length modifier. POSIX doesnt have these, so + * we only support them for floating-point conversions, which + * are extensions. this is useful because the l modifier can + * be used to gain extra range and precision, while omitting + * it is more likely to produce consistent results on different + * architectures. this is not so important for integers + * because overflow is the only bad thing that can happen to + * them, but consider the command printf %a 1.1 + */ if (*fmt == 'L') { mod_ldbl = 1; fmt++; diff --git a/cmd/posix/sh/sh_cdefs.h b/cmd/posix/sh/sh_cdefs.h @@ -38,9 +38,9 @@ #ifndef _SH_POINTER_TYPEDEF #define _SH_POINTER_TYPEDEF typedef void *pointer; /* used in our memalloc.h and bltin.h - * canonical home is shell.h, but we - * want memalloc to be self-contained - * and not pull all of shell.h */ + * canonical home is shell.h, but we + * want memalloc to be self-contained + * and not pull all of shell.h */ #endif #endif /* SH_CDEFS_H */ diff --git a/cmd/posix/sh/test.c b/cmd/posix/sh/test.c @@ -156,7 +156,7 @@ static const struct t_op { {"!", UNOT}, {"(", LPAREN}, {")", RPAREN}, -}, + }, opsm1[] = { {"r", FILRD}, {"w", FILWR}, {"x", FILEX}, {"e", FILEXIST}, {"f", FILREG}, @@ -165,12 +165,12 @@ static const struct t_op { {"n", STRNZ}, {"h", FILSYM}, /* for backwards compat */ {"O", FILUID}, {"G", FILGID}, {"L", FILSYM}, {"S", FILSOCK}, {"a", BAND}, {"o", BOR}, -}, + }, ops2[] = { {"==", STREQ}, {"!=", STRNE}, -}, + }, opsm2[] = { {"eq", INTEQ}, {"ne", INTNE}, @@ -181,7 +181,7 @@ static const struct t_op { {"nt", FILNT}, {"ot", FILOT}, {"ef", FILEQ}, -}; + }; static int nargc; static char **t_wp; diff --git a/cmd/posix/sh/trap.c b/cmd/posix/sh/trap.c @@ -281,14 +281,14 @@ setsignal(int signo) t = &sigmode[signo]; if (*t == 0) { /* - * current setting unknown - */ + * current setting unknown + */ if (!getsigaction(signo, &sigact)) { /* - * pretend it worked; maybe we should give a warning - * here, but other shells dont. we dont alter - * sigmode, so that we retry every time - */ + * pretend it worked; maybe we should give a warning + * here, but other shells dont. we dont alter + * sigmode, so that we retry every time + */ return; } if (sigact == SIG_IGN) { @@ -399,21 +399,21 @@ dotrap(void) gotsig[i] = 0; if (trap[i]) { /* - * ignore SIGCHLD to avoid infinite - * recursion if the trap action does - * a fork - */ + * ignore SIGCHLD to avoid infinite + * recursion if the trap action does + * a fork + */ if (i == SIGCHLD) ignore_sigchld++; /* - * backup current evalskip - * state and reset it before - * executing a trap, so that the - * trap is not disturbed by an - * ongoing break/continue/return - * statement - */ + * backup current evalskip + * state and reset it before + * executing a trap, so that the + * trap is not disturbed by an + * ongoing break/continue/return + * statement + */ prev_evalskip = evalskip; prev_skipcount = skipcount; evalskip = 0; @@ -425,12 +425,12 @@ dotrap(void) popstackmark(&smark); /* - * if such a command was not - * already in progress, allow a - * break/continue/return in the - * trap action to have an effect - * outside of it - */ + * if such a command was not + * already in progress, allow a + * break/continue/return in the + * trap action to have an effect + * outside of it + */ if (evalskip == 0 || prev_evalskip != 0) { evalskip = prev_evalskip; skipcount = prev_skipcount; @@ -497,9 +497,9 @@ exitshell_savedstatus(void) handler = &loc1; if ((p = trap[0]) != NULL && *p != '\0') { /* - * reset evalskip, or the trap on EXIT could be - * interrupted if the last command was a "return" - */ + * reset evalskip, or the trap on EXIT could be + * interrupted if the last command was a "return" + */ evalskip = 0; trap[0] = NULL; FORCEINTON; diff --git a/cmd/posix/sh/var.c b/cmd/posix/sh/var.c @@ -98,8 +98,8 @@ static const struct varinit varinit[] = { {&vmpath, VUNSET, "MAILPATH=", NULL}, {&vpath, 0, "PATH=" ARUU_PATH_DEFPATH, changepath}, /* - * vps1 depends on uid - */ + * vps1 depends on uid + */ {&vps2, 0, "PS2=> ", NULL}, {&vps4, 0, "PS4=+ ", NULL}, #ifndef NO_HISTORY @@ -150,8 +150,8 @@ initvar(void) vp->func = ip->func; } /* - * PS1 depends on uid - */ + * PS1 depends on uid + */ if (find_var("PS1", &vpp, &vps1.name_len) == NULL) { vps1.next = *vpp; *vpp = &vps1; @@ -329,13 +329,13 @@ setvareq(char *s, int flags) vp->text = s; /* - * we could roll this to a function, to handle it as - * a regular variable function callback, but why bother? - * - * note: this assumes iflag is not set to 1 initially - * as part of initvar(), this is called before arguments - * are looked at - */ + * we could roll this to a function, to handle it as + * a regular variable function callback, but why bother? + * + * note: this assumes iflag is not set to 1 initially + * as part of initvar(), this is called before arguments + * are looked at + */ if ((vp == &vmpath || (vp == &vmail && !mpathset())) && iflag == 1) chkmail(1); if ((vp->flags & VEXPORT) && localevar(s)) { @@ -547,10 +547,10 @@ var_compare(const void *a, const void *b) sa = a; sb = b; /* - * this compares two var=value strings which creates a different - * order from what you would probably expect. POSIX is somewhat - * ambiguous on what should be sorted exactly - */ + * this compares two var=value strings which creates a different + * order from what you would probably expect. POSIX is somewhat + * ambiguous on what should be sorted exactly + */ return strcoll(*sa, *sb); } @@ -569,8 +569,8 @@ showvarscmd(int argc __unused, char **argv __unused) int i, n; /* - * POSIX requires us to sort the variables - */ + * POSIX requires us to sort the variables + */ n = 0; for (vpp = vartab; vpp < vartab + VTABSIZE; vpp++) { for (vp = *vpp; vp; vp = vp->next) { @@ -592,9 +592,9 @@ showvarscmd(int argc __unused, char **argv __unused) qsort(vars, n, sizeof(*vars), var_compare); for (i = 0; i < n; i++) { /* - * skip improper variable names so the output remains usable as - * shell input - */ + * skip improper variable names so the output remains usable as + * shell input + */ if (!isassignment(vars[i])) continue; s = strchr(vars[i], '='); @@ -661,10 +661,10 @@ exportcmd(int argc __unused, char **argv) if (vp->flags & flag) { if (values) { /* - * skip improper variable names - * so the output remains usable - * as shell input - */ + * skip improper variable names + * so the output remains usable + * as shell input + */ if (!isassignment(vp->text)) continue; out1str(cmdname); diff --git a/cmd/posix/sort.c b/cmd/posix/sort.c @@ -213,7 +213,7 @@ slinecmp(struct line *a, struct line *b) columns(b, kd, &col2); /* if -u is given, dont use default key definition - * unless it is the only one */ + * unless it is the only one */ if (uflag && kd == TAILQ_LAST(&kdhead, kdhead) && TAILQ_LAST(&kdhead, kdhead) != TAILQ_FIRST(&kdhead)) { res = 0; @@ -332,8 +332,8 @@ addkeydef(char *kdstr, int flags) kd = enmalloc(2, sizeof(*kd)); /* parse key definition kdstr with format - * start_column[.start_char][flags][,end_column[.end_char][flags]] - */ + * start_column[.start_char][flags][,end_column[.end_char][flags]] + */ kd->start_column = 1; kd->start_char = 1; kd->end_column = 0; /* 0 means end of line */ @@ -437,10 +437,10 @@ main(int argc, char *argv[]) // ?man -m: specify mode or limit case 'm': /* more or less for free, but for performance-reasons, - * we should keep this flag in mind and maybe some later - * day implement it properly so we dont run out of memory - * while merging large sorted files - */ + * we should keep this flag in mind and maybe some later + * day implement it properly so we dont run out of memory + * while merging large sorted files + */ break; // ?man -n: print line numbers or counts case 'n': diff --git a/cmd/posix/tail.c b/cmd/posix/tail.c @@ -47,8 +47,8 @@ dropinit(int fd, const char *fname, size_t count) nr = charntorune(&r, p, n); if (!nr) { /* we dont have a full rune, move - * remaining data to beginning and read - * again */ + * remaining data to beginning and read + * again */ memmove(buf, p, n); break; } @@ -105,7 +105,7 @@ taketail(int fd, const char *fname, size_t count) switch (mode) { case 'n': /* lines */ /* ignore the last character; if it is a newline, it - * ends the last line */ + * ends the last line */ for (p = buf + len - 2, left = count; p >= buf; p--) { if (*p != '\n') continue; diff --git a/cmd/posix/uudecode.c b/cmd/posix/uudecode.c @@ -109,7 +109,7 @@ uudecodeb64(FILE *fp, FILE *outfp) switch (b) { case 0: /* expected '=' remaining - * including footer */ + * including footer */ if (--t) { fwrite(out, 1, (po - out), outfp); return; diff --git a/cmd/pseudo/gzip.c b/cmd/pseudo/gzip.c @@ -27,10 +27,10 @@ struct InflateState { unsigned long outcnt; const unsigned char *in; - unsigned long inlen; - unsigned long incnt; - int bitbuf; - int bitcnt; + unsigned long inlen; + unsigned long incnt; + int bitbuf; + int bitcnt; jmp_buf env; }; @@ -100,8 +100,8 @@ inflate_decode(struct InflateState *s, const struct Huffman *h) bitbuf = s->bitbuf; left = s->bitcnt; code = first = index = 0; - len = 1; - next = h->count + 1; + len = 1; + next = h->count + 1; for (;;) { while (left--) { code |= bitbuf & 1; @@ -166,17 +166,16 @@ huffman_construct(struct Huffman *h, const short *length, int n) static int inflate_codes(struct InflateState *s, const struct Huffman *lencode, const struct Huffman *distcode) { - int symbol, len; - unsigned dist; - static const short lens[29] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, - 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, - 163, 195, 227, 258}; - static const short lext[29] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, + int symbol, len; + unsigned dist; + static const short lens[29] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, + 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258}; + static const short lext[29] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; - static const short dists[30] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, - 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, - 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; - static const short dext[30] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, + static const short dists[30] = {1, 2, 3, 4, 5, 7, 9, 13, 17, 25, + 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, + 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; + static const short dext[30] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; do { @@ -222,17 +221,17 @@ inflate_codes(struct InflateState *s, const struct Huffman *lencode, const struc static int inflate_fixed(struct InflateState *s) { - static int built; - static short lencnt[MAXBITS + 1], lensym[FIXLCODES]; - static short distcnt[MAXBITS + 1], distsym[MAXDCODES]; + static int built; + static short lencnt[MAXBITS + 1], lensym[FIXLCODES]; + static short distcnt[MAXBITS + 1], distsym[MAXDCODES]; static struct Huffman lencode, distcode; if (!built) { int symbol; short lengths[FIXLCODES]; - lencode.count = lencnt; - lencode.symbol = lensym; + lencode.count = lencnt; + lencode.symbol = lensym; distcode.count = distcnt; distcode.symbol = distsym; @@ -259,16 +258,15 @@ inflate_fixed(struct InflateState *s) static int inflate_dynamic(struct InflateState *s) { - int nlen, ndist, ncode, index, err; - short lengths[MAXCODES]; - short lencnt[MAXBITS + 1], lensym[MAXLCODES]; - short distcnt[MAXBITS + 1], distsym[MAXDCODES]; - struct Huffman lencode, distcode; - static const short order[19] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, - 11, 4, 12, 3, 13, 2, 14, 1, 15}; - - lencode.count = lencnt; - lencode.symbol = lensym; + int nlen, ndist, ncode, index, err; + short lengths[MAXCODES]; + short lencnt[MAXBITS + 1], lensym[MAXLCODES]; + short distcnt[MAXBITS + 1], distsym[MAXDCODES]; + struct Huffman lencode, distcode; + static const short order[19] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + + lencode.count = lencnt; + lencode.symbol = lensym; distcode.count = distcnt; distcode.symbol = distsym; @@ -331,8 +329,12 @@ inflate_dynamic(struct InflateState *s) /* raw deflate (rfc 1951) decoder; dest null just computes destlen */ static int -inflate_raw(unsigned char *dest, unsigned long *destlen, const unsigned char *source, - unsigned long *sourcelen) +inflate_raw( + unsigned char *dest, + unsigned long *destlen, + const unsigned char *source, + unsigned long *sourcelen +) { struct InflateState s; int last, type, err; @@ -356,7 +358,7 @@ inflate_raw(unsigned char *dest, unsigned long *destlen, const unsigned char *so err = type == 0 ? inflate_stored(&s) : type == 1 ? inflate_fixed(&s) : type == 2 ? inflate_dynamic(&s) - : -1; + : -1; if (err != 0) break; } while (!last); @@ -448,8 +450,8 @@ read_all(FILE *fp, size_t *len) static void gunzip(const unsigned char *in, size_t inlen, FILE *out) { - size_t pos, hdr; - unsigned flg; + size_t pos, hdr; + unsigned flg; unsigned char *dest; unsigned long destlen, srclen; uint32_t want_crc, want_isize, got_crc; @@ -599,11 +601,17 @@ short_names(int argc, char *argv[]) static const struct { const char *name, *letter; } names[] = { - {"--stdout", "-c"}, {"--to-stdout", "-c"}, {"--decompress", "-d"}, {"--uncompress", "-d"}, - {"--force", "-f"}, {"--keep", "-k"}, {"--no-name", "-n"}, {"--fast", "-1"}, - {"--best", "-9"}, + {"--stdout", "-c"}, + {"--to-stdout", "-c"}, + {"--decompress", "-d"}, + {"--uncompress", "-d"}, + {"--force", "-f"}, + {"--keep", "-k"}, + {"--no-name", "-n"}, + {"--fast", "-1"}, + {"--best", "-9"}, }; - int i; + int i; size_t j; for (i = 1; i < argc && argv[i][0] == '-' && strcmp(argv[i], "--") != 0; i++) @@ -666,7 +674,8 @@ main(int argc, char *argv[]) } ARGEND - (void)fflag; + (void) + fflag; crc32_init(); if (argc == 0) { diff --git a/cmd/pseudo/stat.c b/cmd/pseudo/stat.c @@ -58,7 +58,7 @@ print_custom(const char *file, struct stat *st, const char *fmt) case 'n': putchar('\n'); break; - case 't': + case 't': putchar('\t'); break; case 'r': @@ -184,7 +184,7 @@ print_custom(const char *file, struct stat *st, const char *fmt) fmt_spec[fmt_len] = '\0'; printf(fmt_spec, (long long)st->st_size); break; - case 't': + case 't': fmt_spec[fmt_len++] = 'x'; fmt_spec[fmt_len] = '\0'; printf(fmt_spec, fs_devmajor(st->st_rdev)); @@ -243,12 +243,7 @@ static void show_statfs(const char *file, struct FilesystemInfo *st) { printf(" File: \"%s\"\n", file); - printf( - " ID: %llx Namelen: %ld Type: %s\n", - st->id, - (long)st->namelen, - fs_type_name(st->type) - ); + printf(" ID: %llx Namelen: %ld Type: %s\n", st->id, (long)st->namelen, fs_type_name(st->type)); printf( "Block size: %-10ld Fundamental block size: %ld\n", (long)st->bsize, @@ -278,7 +273,7 @@ print_fs_custom(const char *file, struct FilesystemInfo *st, const char *fmt) case 'n': putchar('\n'); break; - case 't': + case 't': putchar('\t'); break; case 'r': @@ -340,7 +335,7 @@ print_fs_custom(const char *file, struct FilesystemInfo *st, const char *fmt) fmt_spec[fmt_len] = '\0'; printf(fmt_spec, (long long)st->blocks); break; - case 'c': + case 'c': fmt_spec[fmt_len++] = 'l'; fmt_spec[fmt_len++] = 'l'; fmt_spec[fmt_len++] = 'd'; @@ -366,10 +361,7 @@ print_fs_custom(const char *file, struct FilesystemInfo *st, const char *fmt) fmt_spec[fmt_len++] = 'l'; fmt_spec[fmt_len++] = 'x'; fmt_spec[fmt_len] = '\0'; - printf( - fmt_spec, - st->id - ); + printf(fmt_spec, st->id); break; case 'l': fmt_spec[fmt_len++] = 'l'; @@ -394,7 +386,7 @@ print_fs_custom(const char *file, struct FilesystemInfo *st, const char *fmt) fmt_spec[fmt_len] = '\0'; printf(fmt_spec, (long)st->frsize ? (long)st->frsize : (long)st->bsize); break; - case 't': + case 't': fmt_spec[fmt_len++] = 'l'; fmt_spec[fmt_len++] = 'x'; fmt_spec[fmt_len] = '\0'; @@ -503,11 +495,11 @@ main(int argc, char *argv[]) fn = stat; fnname = "stat"; break; - case 't': + case 't': showstat = show_stat_terse; break; #if FEATURE_STAT_FILESYSTEM - case 'f': + case 'f': fflag = 1; break; #endif diff --git a/cmd/pseudo/tar.c b/cmd/pseudo/tar.c @@ -323,7 +323,7 @@ decomp(int fd, const char *tool, const char *flags) static ssize_t eread(int fd, void *buf, size_t n) { - size_t got = 0; + size_t got = 0; ssize_t r; while (got < n) { @@ -653,8 +653,8 @@ sanitize(struct header *h) }; /* numeric fields can be terminated with spaces instead of - * nuls as per the ustar specification. patch all of them to - * use nuls so we can perform string operations on them */ + * nuls as per the ustar specification. patch all of them to + * use nuls so we can perform string operations on them */ for (i = 0; i < LEN(fields); i++) { j = 0, l = fields[i].l - 1; for (; j < l && fields[i].f[j] == ' '; j++) @@ -738,7 +738,7 @@ xt(int argc, char *argv[], int mode) } /* convert pax x header with 'path=' field into l header - */ + */ if (h->type == 'x') for (q = fname; q < fname + size - 16; q += n) { if ((n = strtol(q, &p, 10)) < 0 || *p != ' ') @@ -757,14 +757,14 @@ xt(int argc, char *argv[], int mode) fname[size] = '\0'; /* non l-like header (eg. pax 'g') is skipped by setting - * q=null */ + * q=null */ if (h->type != 'L') q = NULL; continue; } /* ustar path is copied into fname if no l header (ie: q is - * NULL) */ + * NULL) */ if (!q) { m = sizeof h->prefix, n = sizeof h->name; p = h->prefix[0] ? "/" : ""; @@ -773,7 +773,7 @@ xt(int argc, char *argv[], int mode) q = NULL; /* if argc > 0 or files_from_cnt > 0 then only extract the - * matching files/dirs */ + * matching files/dirs */ if (argc || files_from_cnt) { match = 0; for (i = 0; i < argc; i++) { diff --git a/cmd/pseudo/useradd.c b/cmd/pseudo/useradd.c @@ -70,18 +70,31 @@ main(int argc, char *argv[]) ARGBEGIN { // ?man -m: make the home from /etc/skel - case 'm': make = 1; break; + case 'm': + make = 1; + break; // ?man -R:str: work in another root - case 'R': root = EARGF(usage()); break; + case 'R': + root = EARGF(usage()); + break; // ?man -d:str: the home, /home/name otherwise - case 'd': home = EARGF(usage()); break; + case 'd': + home = EARGF(usage()); + break; // ?man -s:str: the shell, /bin/sh otherwise - case 's': shell = EARGF(usage()); break; + case 's': + shell = EARGF(usage()); + break; // ?man -p:str: the password as crypt(3) gives it, locked otherwise - case 'p': hash = EARGF(usage()); break; + case 'p': + hash = EARGF(usage()); + break; // ?man -G:str: the groups the person is put in, apart by commas - case 'G': groups = EARGF(usage()); break; - default: usage(); + case 'G': + groups = EARGF(usage()); + break; + default: + usage(); } ARGEND; if (argc != 1) @@ -93,7 +106,12 @@ main(int argc, char *argv[]) home = buf; } if (acct_add(argv[0], home, shell, hash, &uid) < 0) - eprintf(errno == EEXIST ? "%s: there is one already\n" : errno == EINVAL ? "%s: not a name\n" : "%s:", argv[0]); + eprintf( + errno == EEXIST ? "%s: there is one already\n" + : errno == EINVAL ? "%s: not a name\n" + : "%s:", + argv[0] + ); for (g = groups ? strtok_r(groups, ",", &save) : NULL; g; g = strtok_r(NULL, ",", &save)) if (acct_member(g, argv[0], 1) < 0) weprintf("%s:", g); diff --git a/cmd/pseudo/usermod.c b/cmd/pseudo/usermod.c @@ -36,21 +36,30 @@ listed(const char *list, const char *group) int main(int argc, char *argv[]) { - char *root = NULL, *hash = NULL, *groups = NULL, *g, *save; + char *root = NULL, *hash = NULL, *groups = NULL, *g, *save; struct group *gr; - int append = 0; + int append = 0; ARGBEGIN { // ?man -R:str: work in another root - case 'R': root = EARGF(usage()); break; + case 'R': + root = EARGF(usage()); + break; // ?man -p:str: the password as crypt(3) gives it - case 'p': hash = EARGF(usage()); break; + case 'p': + hash = EARGF(usage()); + break; // ?man -a: with -G, only put the person in the groups - case 'a': append = 1; break; + case 'a': + append = 1; + break; // ?man -G:str: the groups the person is in, apart by commas, and no other - case 'G': groups = EARGF(usage()); break; - default: usage(); + case 'G': + groups = EARGF(usage()); + break; + default: + usage(); } ARGEND; if (argc != 1 || (append && !groups)) @@ -63,7 +72,8 @@ main(int argc, char *argv[]) setgrent(); while ((gr = getgrent())) for (char **m = gr->gr_mem; m && *m; m++) - if (!strcmp(*m, argv[0]) && !listed(groups, gr->gr_name) && acct_member(gr->gr_name, argv[0], 0) < 0) + if (!strcmp(*m, argv[0]) && !listed(groups, gr->gr_name) + && acct_member(gr->gr_name, argv[0], 0) < 0) weprintf("%s:", gr->gr_name); endgrent(); } diff --git a/cmd/pseudo/watch.c b/cmd/pseudo/watch.c @@ -23,9 +23,9 @@ main(int argc, char *argv[]) { char cmd[BUFSIZ]; char *end; - struct timespec interval = { .tv_sec = 2, .tv_nsec = 0 }; + struct timespec interval = {.tv_sec = 2, .tv_nsec = 0}; float period; - int i; + int i; ARGBEGIN { @@ -39,7 +39,7 @@ main(int argc, char *argv[]) eprintf("invalid interval\n"); if (period < 0) period = 0.1f; - interval.tv_sec = period; + interval.tv_sec = period; interval.tv_nsec = (period - interval.tv_sec) * 1E9; break; default: diff --git a/cmd/xsi/passwd.c b/cmd/xsi/passwd.c @@ -67,12 +67,12 @@ readpass(const char *prompt) int main(int argc, char *argv[]) { - struct pwdb_entry ent; - struct passwd *self, *target; - char *name, *cur, *new1, *new2, *hash; - char salt[PW_SALT_MAX]; - int lflag = 0, uflag = 0, dflag = 0; - uid_t uid; + struct pwdb_entry ent; + struct passwd *self, *target; + char *name, *cur, *new1, *new2, *hash; + char salt[PW_SALT_MAX]; + int lflag = 0, uflag = 0, dflag = 0; + uid_t uid; ARGBEGIN { diff --git a/scripts/kmap/kmap-vendor.c b/scripts/kmap/kmap-vendor.c @@ -27,17 +27,17 @@ // and z, and the keypad's decimal key. their evdev codes, xkb's minus 8 static const struct { const char *name; - int evdev; + int evdev; } keys[] = { - {"TLDE", 41}, {"AE01", 2}, {"AE02", 3}, {"AE03", 4}, {"AE04", 5}, {"AE05", 6}, - {"AE06", 7}, {"AE07", 8}, {"AE08", 9}, {"AE09", 10}, {"AE10", 11}, {"AE11", 12}, - {"AE12", 13}, {"AE13", 124}, {"AD01", 16}, {"AD02", 17}, {"AD03", 18}, {"AD04", 19}, - {"AD05", 20}, {"AD06", 21}, {"AD07", 22}, {"AD08", 23}, {"AD09", 24}, {"AD10", 25}, - {"AD11", 26}, {"AD12", 27}, {"BKSL", 43}, {"AC01", 30}, {"AC02", 31}, {"AC03", 32}, - {"AC04", 33}, {"AC05", 34}, {"AC06", 35}, {"AC07", 36}, {"AC08", 37}, {"AC09", 38}, - {"AC10", 39}, {"AC11", 40}, {"LSGT", 86}, {"AB01", 44}, {"AB02", 45}, {"AB03", 46}, - {"AB04", 47}, {"AB05", 48}, {"AB06", 49}, {"AB07", 50}, {"AB08", 51}, {"AB09", 52}, - {"AB10", 53}, {"AB11", 89}, {"SPCE", 57}, {"KPDL", 83}, + {"TLDE", 41}, {"AE01", 2}, {"AE02", 3}, {"AE03", 4}, {"AE04", 5}, {"AE05", 6}, + {"AE06", 7}, {"AE07", 8}, {"AE08", 9}, {"AE09", 10}, {"AE10", 11}, {"AE11", 12}, + {"AE12", 13}, {"AE13", 124}, {"AD01", 16}, {"AD02", 17}, {"AD03", 18}, {"AD04", 19}, + {"AD05", 20}, {"AD06", 21}, {"AD07", 22}, {"AD08", 23}, {"AD09", 24}, {"AD10", 25}, + {"AD11", 26}, {"AD12", 27}, {"BKSL", 43}, {"AC01", 30}, {"AC02", 31}, {"AC03", 32}, + {"AC04", 33}, {"AC05", 34}, {"AC06", 35}, {"AC07", 36}, {"AC08", 37}, {"AC09", 38}, + {"AC10", 39}, {"AC11", 40}, {"LSGT", 86}, {"AB01", 44}, {"AB02", 45}, {"AB03", 46}, + {"AB04", 47}, {"AB05", 48}, {"AB06", 49}, {"AB07", 50}, {"AB08", 51}, {"AB09", 52}, + {"AB10", 53}, {"AB11", 89}, {"SPCE", 57}, {"KPDL", 83}, }; static void @@ -50,8 +50,14 @@ put_utf8(FILE *fp, unsigned c) else if (c < 0x10000) fprintf(fp, "%c%c%c", 0xe0 | c >> 12, 0x80 | (c >> 6 & 0x3f), 0x80 | (c & 0x3f)); else - fprintf(fp, "%c%c%c%c", 0xf0 | c >> 18, 0x80 | (c >> 12 & 0x3f), 0x80 | (c >> 6 & 0x3f), - 0x80 | (c & 0x3f)); + fprintf( + fp, + "%c%c%c%c", + 0xf0 | c >> 18, + 0x80 | (c >> 12 & 0x3f), + 0x80 | (c >> 6 & 0x3f), + 0x80 | (c & 0x3f) + ); } // a symbol as a word: the character it types when it types one that reads as @@ -59,7 +65,7 @@ put_utf8(FILE *fp, unsigned c) // every keysym written by name, which the vendored compatibility must know: // the dead keys, the modifiers, the group switches static xkb_keysym_t named[4096]; -static int nnamed; +static int nnamed; static void add_named(xkb_keysym_t ks) @@ -74,7 +80,7 @@ add_named(xkb_keysym_t ks) static void put_sym(FILE *fp, xkb_keysym_t ks) { - char name[64]; + char name[64]; unsigned c; if (ks == XKB_KEY_NoSymbol) { @@ -85,8 +91,8 @@ put_sym(FILE *fp, xkb_keysym_t ks) fputc(' ', fp); // the character only when it is that character's own keysym: KP_1 types // 1 but is the keypad's, and xkb tells them apart - if (xkb_utf32_to_keysym(c) == ks && c > 0x20 && c != 0x7f && !(c >= 0x80 && c < 0xa0) && c != 0xa0 && - !(c >= 0x300 && c < 0x370) && !(c >= 0x200b && c <= 0x200f)) { + if (xkb_utf32_to_keysym(c) == ks && c > 0x20 && c != 0x7f && !(c >= 0x80 && c < 0xa0) && c != 0xa0 + && !(c >= 0x300 && c < 0x370) && !(c >= 0x200b && c <= 0x200f)) { if (c == '\'') fputs("''''", fp); else if (c == '#') @@ -111,19 +117,38 @@ is_main(int evdev) return 0; } -static struct xkb_keymap *us; +static struct xkb_keymap *us; static struct xkb_context *ctx; // the xkb types a key may have, from the complete set xkeyboard-config // compiles every keymap with static const char *types[] = { - "ONE_LEVEL", "TWO_LEVEL", "ALPHABETIC", "KEYPAD", "SHIFT+ALT", "CTRL+ALT", - "THREE_LEVEL", "FOUR_LEVEL", "FOUR_LEVEL_ALPHABETIC", "FOUR_LEVEL_SEMIALPHABETIC", - "FOUR_LEVEL_MIXED_KEYPAD", "FOUR_LEVEL_X", "FOUR_LEVEL_KEYPAD", "FOUR_LEVEL_PLUS_LOCK", - "FOUR_LEVEL_LOCKABLE_LEVEL2", "SEPARATE_CAPS_AND_SHIFT_ALPHABETIC", "EIGHT_LEVEL", - "EIGHT_LEVEL_ALPHABETIC", "EIGHT_LEVEL_SEMIALPHABETIC", "EIGHT_LEVEL_WITH_LEVEL5_LOCK", - "EIGHT_LEVEL_ALPHABETIC_WITH_LEVEL5_LOCK", "PC_ALT_LEVEL2", "PC_CONTROL_LEVEL2", - "PC_SUPER_LEVEL2", "PC_SHIFT_SUPER_LEVEL2", "PC_CONTROL_SUPER_LEVEL2", + "ONE_LEVEL", + "TWO_LEVEL", + "ALPHABETIC", + "KEYPAD", + "SHIFT+ALT", + "CTRL+ALT", + "THREE_LEVEL", + "FOUR_LEVEL", + "FOUR_LEVEL_ALPHABETIC", + "FOUR_LEVEL_SEMIALPHABETIC", + "FOUR_LEVEL_MIXED_KEYPAD", + "FOUR_LEVEL_X", + "FOUR_LEVEL_KEYPAD", + "FOUR_LEVEL_PLUS_LOCK", + "FOUR_LEVEL_LOCKABLE_LEVEL2", + "SEPARATE_CAPS_AND_SHIFT_ALPHABETIC", + "EIGHT_LEVEL", + "EIGHT_LEVEL_ALPHABETIC", + "EIGHT_LEVEL_SEMIALPHABETIC", + "EIGHT_LEVEL_WITH_LEVEL5_LOCK", + "EIGHT_LEVEL_ALPHABETIC_WITH_LEVEL5_LOCK", + "PC_ALT_LEVEL2", + "PC_CONTROL_LEVEL2", + "PC_SUPER_LEVEL2", + "PC_SHIFT_SUPER_LEVEL2", + "PC_CONTROL_SUPER_LEVEL2", }; #define NTYPES (sizeof(types) / sizeof(types[0])) @@ -156,8 +181,8 @@ signature(struct xkb_keymap *km, xkb_keycode_t kc, struct sig *s) for (i = 1; i < s->cnt[l]; i++) for (j = i; j > 0 && s->m[l][j - 1] > s->m[l][j]; j--) { xkb_mod_mask_t t = s->m[l][j]; - s->m[l][j] = s->m[l][j - 1]; - s->m[l][j - 1] = t; + s->m[l][j] = s->m[l][j - 1]; + s->m[l][j - 1] = t; } } } @@ -167,15 +192,18 @@ signature(struct xkb_keymap *km, xkb_keycode_t kc, struct sig *s) static struct xkb_keymap * probe(const struct key *k, int nkeys, const char *type) { - char *buf; - size_t len; - FILE *fp = open_memstream(&buf, &len); + char *buf; + size_t len; + FILE *fp = open_memstream(&buf, &len); struct xkb_keymap *km; - int i, l; - - fputs("xkb_keymap { xkb_keycodes { include \"evdev+aliases(qwerty)\" };" - " xkb_types { include \"complete\" }; xkb_compat { include \"complete\" };" - " xkb_symbols { include \"pc+inet(evdev)\"\n", fp); + int i, l; + + fputs( + "xkb_keymap { xkb_keycodes { include \"evdev+aliases(qwerty)\" };" + " xkb_types { include \"complete\" }; xkb_compat { include \"complete\" };" + " xkb_symbols { include \"pc+inet(evdev)\"\n", + fp + ); for (i = 0; i < nkeys; i++) { fprintf(fp, "replace key <%s> { ", k[i].name); if (type) @@ -196,7 +224,7 @@ static int collect(struct xkb_keymap *km, xkb_keycode_t kc, const char *name, struct key *k) { const xkb_keysym_t *syms; - unsigned l; + unsigned l; memset(k, 0, sizeof(*k)); snprintf(k->name, sizeof(k->name), "%s", name); @@ -204,11 +232,11 @@ collect(struct xkb_keymap *km, xkb_keycode_t kc, const char *name, struct key *k for (l = 0; l < 8; l++) if (xkb_keymap_key_get_syms_by_level(km, kc, 0, l, &syms) >= 1) { k->lv[l] = syms[0]; - k->n = l + 1; + k->n = l + 1; } // caps lock shifts it when its second level is the first's capital - k->caps = k->lv[0] && k->lv[1] && k->lv[0] != k->lv[1] && - xkb_keysym_to_upper(k->lv[0]) == k->lv[1]; + k->caps = + k->lv[0] && k->lv[1] && k->lv[0] != k->lv[1] && xkb_keysym_to_upper(k->lv[0]) == k->lv[1]; // a key the layout leaves without symbols where the pc keyboard has some // is written as none, else the pc keyboard's would show through if (!k->n && km != us && xkb_keymap_num_levels_for_key(us, kc, 0) > 0) { @@ -225,7 +253,7 @@ static int differs(struct xkb_keymap *km, xkb_keycode_t kc) { const xkb_keysym_t *a, *b; - unsigned l; + unsigned l; for (l = 0; l < 8; l++) { int na = xkb_keymap_key_get_syms_by_level(km, kc, 0, l, &a); @@ -243,9 +271,9 @@ static void find_types(struct xkb_keymap *ref, struct key *k, int n) { struct xkb_keymap *auto_km = probe(k, n, NULL); - struct sig want, got; - int i, left = 0; - unsigned t; + struct sig want, got; + int i, left = 0; + unsigned t; if (!auto_km) return; @@ -303,16 +331,17 @@ static int write_layout(const char *dir, const char *layout, const char *variant, const char *desc) { struct xkb_rule_names names = {"evdev", "pc105", layout, variant, NULL}; - struct xkb_keymap *km = xkb_keymap_new_from_names(ctx, &names, 0); - static struct key k[1024]; - char path[1024], id[256]; - const xkb_keysym_t *syms; - int n = 0, i; - FILE *fp; + struct xkb_keymap *km = xkb_keymap_new_from_names(ctx, &names, 0); + static struct key k[1024]; + char path[1024], id[256]; + const xkb_keysym_t *syms; + int n = 0, i; + FILE *fp; if (!km) { - fprintf(stderr, "kmap-vendor: %s %s does not compile, left out\n", layout, - variant ? variant : ""); + fprintf( + stderr, "kmap-vendor: %s %s does not compile, left out\n", layout, variant ? variant : "" + ); return -1; } for (i = 0; i < (int)(sizeof(keys) / sizeof(keys[0])); i++) @@ -326,9 +355,9 @@ write_layout(const char *dir, const char *layout, const char *variant, const cha continue; // right alt as a bare level 3 switch is the level3 line; anything more // (a second level, another modifier) is written as the key - if (kc == 100 + 8 && xkb_keymap_num_levels_for_key(km, kc, 0) == 1 && - xkb_keymap_key_get_syms_by_level(km, kc, 0, 0, &syms) == 1 && - syms[0] == XKB_KEY_ISO_Level3_Shift) + if (kc == 100 + 8 && xkb_keymap_num_levels_for_key(km, kc, 0) == 1 + && xkb_keymap_key_get_syms_by_level(km, kc, 0, 0, &syms) == 1 + && syms[0] == XKB_KEY_ISO_Level3_Shift) continue; if (!strcmp(kn, "LVL3") || !strcmp(kn, "MDSW")) continue; @@ -357,8 +386,8 @@ write_layout(const char *dir, const char *layout, const char *variant, const cha } else fputs(desc, fp); fputc('\n', fp); - if (xkb_keymap_key_get_syms_by_level(km, 100 + 8, 0, 0, &syms) == 1 && - syms[0] == XKB_KEY_ISO_Level3_Shift) + if (xkb_keymap_key_get_syms_by_level(km, 100 + 8, 0, 0, &syms) == 1 + && syms[0] == XKB_KEY_ISO_Level3_Shift) fputs("level3 ralt\n", fp); put_keys(fp, k, n); fclose(fp); @@ -372,8 +401,8 @@ static int write_section(const char *dir, const char *text, const char *head, const char *file) { const char *a = strstr(text, head), *b; - char path[1024]; - FILE *fp; + char path[1024]; + FILE *fp; if (!a || !(b = strstr(a, "\n};\n"))) return -1; @@ -391,7 +420,8 @@ all_keys(struct xkb_keymap *km, struct key *k, int max) { int n = 0; - for (xkb_keycode_t kc = xkb_keymap_min_keycode(km); kc <= xkb_keymap_max_keycode(km) && n < max; kc++) { + for (xkb_keycode_t kc = xkb_keymap_min_keycode(km); kc <= xkb_keymap_max_keycode(km) && n < max; + kc++) { const char *kn = xkb_keymap_key_get_name(km, kc); if (kn) @@ -409,10 +439,10 @@ put_modmaps(FILE *fp, struct xkb_keymap *km, const char *text) const char *p = text; while ((p = strstr(p, "modifier_map "))) { - char mod[16], name[64]; - const char *q = p + strlen("modifier_map "), *end = strchr(p, ';'); + char mod[16], name[64]; + const char *q = p + strlen("modifier_map "), *end = strchr(p, ';'); xkb_keysym_t seen[64]; - int nseen = 0; + int nseen = 0; if (!end || sscanf(q, "%15s", mod) != 1) break; @@ -420,14 +450,16 @@ put_modmaps(FILE *fp, struct xkb_keymap *km, const char *text) for (q = strchr(q, '<'); q && q < end; q = strchr(q + 1, '<')) { xkb_keycode_t kc; - if (sscanf(q, "<%63[^>]>", name) != 1 || (kc = xkb_keymap_key_by_name(km, name)) == XKB_KEYCODE_INVALID) + if (sscanf(q, "<%63[^>]>", name) != 1 + || (kc = xkb_keymap_key_by_name(km, name)) == XKB_KEYCODE_INVALID) continue; for (int l = 0; l < 8; l++) { const xkb_keysym_t *syms; - char ks[64]; - int dup = 0; + char ks[64]; + int dup = 0; - if (xkb_keymap_key_get_syms_by_level(km, kc, 0, l, &syms) < 1 || syms[0] == XKB_KEY_NoSymbol) + if (xkb_keymap_key_get_syms_by_level(km, kc, 0, l, &syms) < 1 + || syms[0] == XKB_KEY_NoSymbol) continue; for (int i = 0; i < nseen; i++) dup |= seen[i] == syms[0]; @@ -450,20 +482,23 @@ put_modmaps(FILE *fp, struct xkb_keymap *km, const char *text) static char * full_base(void) { - char *buf; - size_t len; - FILE *fp = open_memstream(&buf, &len); + char *buf; + size_t len; + FILE *fp = open_memstream(&buf, &len); struct xkb_keymap *km; - unsigned t; - int i, nkeys = (int)NTYPES + (nnamed + 7) / 8; + unsigned t; + int i, nkeys = (int)NTYPES + (nnamed + 7) / 8; // key codes of its own, past every real one: only this keymap has them, // and only its types and compatibility are kept fputs("xkb_keymap { xkb_keycodes { include \"evdev+aliases(qwerty)\"\n", fp); for (i = 0; i < nkeys; i++) fprintf(fp, "<Z%03d> = %d;\n", i, 2000 + i); - fputs("}; xkb_types { include \"complete\" }; xkb_compat { include \"complete\" };" - " xkb_symbols { include \"pc+us+inet(evdev)\"\n", fp); + fputs( + "}; xkb_types { include \"complete\" }; xkb_compat { include \"complete\" };" + " xkb_symbols { include \"pc+us+inet(evdev)\"\n", + fp + ); for (t = 0; t < NTYPES; t++) fprintf(fp, "key <Z%03u> { type = \"%s\", [ a ] };\n", t, types[t]); for (i = 0; i < nnamed; i += 8) { @@ -491,16 +526,17 @@ static int write_pc(const char *dir, const char *full) { static struct key k[1024]; - char *text = xkb_keymap_get_as_string(us, XKB_KEYMAP_FORMAT_TEXT_V1); - char path[1024]; - FILE *fp; - int n; + char *text = xkb_keymap_get_as_string(us, XKB_KEYMAP_FORMAT_TEXT_V1); + char path[1024]; + FILE *fp; + int n; snprintf(path, sizeof(path), "%s/xkb", dir); if (!text || (mkdir(path, 0755) != 0 && errno != EEXIST)) return -1; - if (write_section(dir, text, "xkb_keycodes", "keycodes.xkb") || write_section(dir, full, "xkb_types", "types.xkb") || - write_section(dir, full, "xkb_compatibility", "compat.xkb")) + if (write_section(dir, text, "xkb_keycodes", "keycodes.xkb") + || write_section(dir, full, "xkb_types", "types.xkb") + || write_section(dir, full, "xkb_compatibility", "compat.xkb")) return -1; n = all_keys(us, k, 1024); find_types(us, k, n); @@ -521,9 +557,9 @@ lines_within(const char *a, const char *ae, const char *b, const char *be) if (!a || !ae || !b || !be) return 0; while (a < ae) { - const char *nl = memchr(a, '\n', (size_t)(ae - a)), *p; - size_t len = nl ? (size_t)(nl - a) : (size_t)(ae - a); - int found = 0; + const char *nl = memchr(a, '\n', (size_t)(ae - a)), *p; + size_t len = nl ? (size_t)(nl - a) : (size_t)(ae - a); + int found = 0; // the virtual modifiers declared are listed whole, and differ by which // a keymap's parts use: not a part of their own @@ -533,11 +569,11 @@ lines_within(const char *a, const char *ae, const char *b, const char *be) } for (p = b; p < be && !found;) { - const char *q = memchr(p, '\n', (size_t)(be - p)); - size_t l2 = q ? (size_t)(q - p) : (size_t)(be - p); + const char *q = memchr(p, '\n', (size_t)(be - p)); + size_t l2 = q ? (size_t)(q - p) : (size_t)(be - p); found = l2 == len && !memcmp(p, a, len); - p = q ? q + 1 : be; + p = q ? q + 1 : be; } if (!found) return 0; @@ -553,12 +589,12 @@ static int write_option(const char *dir, const char *name, const char *base_text, int dry) { struct xkb_rule_names names = {"evdev", "pc105", "us", NULL, name}; - struct xkb_keymap *km = xkb_keymap_new_from_names(ctx, &names, 0); - static struct key k[1024]; - char *mine, *base, path[1024], group[64]; - const char *colon = strchr(name, ':'); - int n = 0, rc = 0; - FILE *fp; + struct xkb_keymap *km = xkb_keymap_new_from_names(ctx, &names, 0); + static struct key k[1024]; + char *mine, *base, path[1024], group[64]; + const char *colon = strchr(name, ':'); + int n = 0, rc = 0; + FILE *fp; if (!km || !colon) return km ? (xkb_keymap_unref(km), 0) : 0; @@ -572,19 +608,25 @@ write_option(const char *dir, const char *name, const char *base_text, int dry) if (!xkb_keymap_key_get_name(km, kc) || !differs(km, kc)) continue; for (int l = 0; l < 8; l++) - if (xkb_keymap_key_get_syms_by_level(km, kc, 0, l, &syms) >= 1 && !xkb_keysym_to_utf32(syms[0])) + if (xkb_keymap_key_get_syms_by_level(km, kc, 0, l, &syms) >= 1 + && !xkb_keysym_to_utf32(syms[0])) add_named(syms[0]); } goto done; } // xkb writes only the compatibility its keys use, so an option that takes // a key away has less of it: what matters is that it adds none - if (!lines_within(strstr(mine, "xkb_types"), strstr(mine, "xkb_symbols"), strstr(base, "xkb_types"), - strstr(base, "xkb_symbols"))) { + if (!lines_within( + strstr(mine, "xkb_types"), + strstr(mine, "xkb_symbols"), + strstr(base, "xkb_types"), + strstr(base, "xkb_symbols") + )) { fprintf(stderr, "kmap-vendor: option %s changes more than keys, left out\n", name); goto done; } - for (xkb_keycode_t kc = xkb_keymap_min_keycode(km); kc <= xkb_keymap_max_keycode(km) && n < 1024; kc++) { + for (xkb_keycode_t kc = xkb_keymap_min_keycode(km); kc <= xkb_keymap_max_keycode(km) && n < 1024; + kc++) { const char *kn = xkb_keymap_key_get_name(km, kc); if (kn && differs(km, kc)) @@ -615,8 +657,8 @@ int main(int argc, char *argv[]) { struct rxkb_context *rx; - struct rxkb_layout *lay; - int n = 0, bad = 0; + struct rxkb_layout *lay; + int n = 0, bad = 0; if (argc != 2) { fprintf(stderr, "usage: kmap-vendor dir\n"); @@ -626,7 +668,7 @@ main(int argc, char *argv[]) perror(argv[1]); return 1; } - rx = rxkb_context_new(RXKB_CONTEXT_NO_FLAGS); + rx = rxkb_context_new(RXKB_CONTEXT_NO_FLAGS); ctx = xkb_context_new(XKB_CONTEXT_NO_FLAGS); { struct xkb_rule_names un = {"evdev", "pc105", "us", NULL, NULL}; @@ -638,8 +680,13 @@ main(int argc, char *argv[]) return 1; } for (lay = rxkb_layout_first(rx); lay; lay = rxkb_layout_next(lay)) { - if (write_layout(argv[1], rxkb_layout_get_name(lay), rxkb_layout_get_variant(lay), - rxkb_layout_get_description(lay)) == 0) + if (write_layout( + argv[1], + rxkb_layout_get_name(lay), + rxkb_layout_get_variant(lay), + rxkb_layout_get_description(lay) + ) + == 0) n++; else bad++; @@ -647,11 +694,12 @@ main(int argc, char *argv[]) fprintf(stderr, "kmap-vendor: %d layouts, %d left out\n", n, bad); { char path[1024], *full; - int nopt = 0; + int nopt = 0; // the options' keysyms join the layouts' before the base is made, // then each option is checked against that base and written - for (struct rxkb_option_group *g = rxkb_option_group_first(rx); g; g = rxkb_option_group_next(g)) + for (struct rxkb_option_group *g = rxkb_option_group_first(rx); g; + g = rxkb_option_group_next(g)) for (struct rxkb_option *o = rxkb_option_first(g); o; o = rxkb_option_next(o)) write_option(argv[1], rxkb_option_get_name(o), NULL, 1); if (!(full = full_base()) || write_pc(argv[1], full) != 0) { @@ -660,7 +708,8 @@ main(int argc, char *argv[]) } snprintf(path, sizeof(path), "%s/options", argv[1]); mkdir(path, 0755); - for (struct rxkb_option_group *g = rxkb_option_group_first(rx); g; g = rxkb_option_group_next(g)) + for (struct rxkb_option_group *g = rxkb_option_group_first(rx); g; + g = rxkb_option_group_next(g)) for (struct rxkb_option *o = rxkb_option_first(g); o; o = rxkb_option_next(o)) nopt += write_option(argv[1], rxkb_option_get_name(o), full, 0); fprintf(stderr, "kmap-vendor: %d options that change keys\n", nopt); diff --git a/shared/diskutil.h b/shared/diskutil.h @@ -24,16 +24,16 @@ struct BlockDev { }; struct BlockDevInfo { - char name[32]; - char path[128]; - char type[16]; - uint64_t size; - int major; - int minor; - char mountpoint[256]; - char fstype[32]; - char model[64]; // what the disk calls itself, "" when it does not say - int removable; // made to be pulled out: a USB stick, a card. a partition takes its disk's + char name[32]; + char path[128]; + char type[16]; + uint64_t size; + int major; + int minor; + char mountpoint[256]; + char fstype[32]; + char model[64]; // what the disk calls itself, "" when it does not say + int removable; // made to be pulled out: a USB stick, a card. a partition takes its disk's struct BlockDevInfo *parts; struct BlockDevInfo *next; }; @@ -60,7 +60,7 @@ void blockdev_free_list(struct BlockDevInfo *list); * to it, and the list of disks. blockdev_probe_list opens the names most * systems give disks, for a kernel that has no way to list them */ #if defined(__linux__) && !defined(ARUU_FORCE_POSIX) -void blockdev_check_loop(const struct stat *, const char *); +void blockdev_check_loop(const struct stat *, const char *); #endif void blockdev_sys_size(struct BlockDev *dev); void blockdev_sys_reread(struct BlockDev *dev); @@ -73,7 +73,8 @@ struct BlockDevInfo *blockdev_probe_list(void); #define BLOCKDEV_NOSUID 0x2 #define BLOCKDEV_NODEV 0x4 #define BLOCKDEV_NOEXEC 0x8 -int blockdev_mount(const char *dev, const char *dir, const char *fstype, int flags, const char *data); +int +blockdev_mount(const char *dev, const char *dir, const char *fstype, int flags, const char *data); int blockdev_unmount(const char *dir); /* the unit holding disk, a name as blockdev_get_list gives it, let go and * powered off so it can be pulled. its filesystems must be unmounted first */ diff --git a/shared/ed25519.h b/shared/ed25519.h @@ -12,22 +12,25 @@ */ enum { - ED25519_SEED = 32, + ED25519_SEED = 32, ED25519_PUBLIC = 32, ED25519_SECRET = 64, - ED25519_SIG = 64, + ED25519_SIG = 64, }; /* the key pair of seed: sk is seed then pk */ -void ed25519_keypair(uint8_t pk[ED25519_PUBLIC], uint8_t sk[ED25519_SECRET], - const uint8_t seed[ED25519_SEED]); +void ed25519_keypair( + uint8_t pk[ED25519_PUBLIC], uint8_t sk[ED25519_SECRET], const uint8_t seed[ED25519_SEED] +); /* sig over the n bytes of m */ -void ed25519_sign(uint8_t sig[ED25519_SIG], const uint8_t *m, size_t n, - const uint8_t sk[ED25519_SECRET]); +void ed25519_sign( + uint8_t sig[ED25519_SIG], const uint8_t *m, size_t n, const uint8_t sk[ED25519_SECRET] +); /* 0 when sig is pk's over m, -1 otherwise */ -int ed25519_verify(const uint8_t sig[ED25519_SIG], const uint8_t *m, size_t n, - const uint8_t pk[ED25519_PUBLIC]); +int ed25519_verify( + const uint8_t sig[ED25519_SIG], const uint8_t *m, size_t n, const uint8_t pk[ED25519_PUBLIC] +); #endif diff --git a/shared/fs.h b/shared/fs.h @@ -29,7 +29,7 @@ enum { IGNORE = 1 << 4, /* for a library: nothing printed and nothing asked, failures are only * counted and the first one kept in err */ - QUIET = 1 << 5, + QUIET = 1 << 5, }; extern int cp_aflag; diff --git a/shared/kmap.h b/shared/kmap.h @@ -70,10 +70,10 @@ struct kmap_modmap { }; struct kmap { - char id[64], layout[32], variant[64], name[256]; - int level3_ralt; - struct kmap_modmap modmaps[8]; - int nmodmaps; + char id[64], layout[32], variant[64], name[256]; + int level3_ralt; + struct kmap_modmap modmaps[8]; + int nmodmaps; struct kmap_key *keys; size_t nkeys; struct kmap_compose *compose; @@ -86,7 +86,7 @@ void kmap_path(char *buf, size_t sz, const char *dir, const char *layout, const /* reads path into k, adding to what k has: a layout, then compose.kmap, whose own id and name do not replace the layout's. k starts zeroed. 0, or -1 with the reason said */ -int kmap_read(const char *path, struct kmap *k); +int kmap_read(const char *path, struct kmap *k); void kmap_free(struct kmap *k); /* the unicode character sym is, -1 when it is a name */ @@ -126,7 +126,14 @@ int kmap_load_console(const struct kmap *k); compatibility in dir/xkb, the pc keyboard pc, the n layouts of maps as a group each over it, then the nopts options over every group. 0, or -1 said */ -int kmap_write_xkb(FILE *fp, const char *dir, const struct kmap *pc, const struct kmap *maps, - int n, const struct kmap *opts, int nopts); +int kmap_write_xkb( + FILE *fp, + const char *dir, + const struct kmap *pc, + const struct kmap *maps, + int n, + const struct kmap *opts, + int nopts +); #endif diff --git a/shared/libblake3/blake3.c b/shared/libblake3/blake3.c @@ -513,7 +513,7 @@ blake3_detect_cpu_features(void) if ((regs[EBX] & (1UL << 5)) && (xcr0 & 0x06) == 0x06) features |= AVX2; /* avx512f, avx512vl and xcr0 opmask, zmm_hi256, - * hi16_zmm */ + * hi16_zmm */ if ((regs[EBX] & (1UL << 31 | 1UL << 16)) && (xcr0 & 0xe0) == 0xe0) features |= AVX512; } @@ -4251,27 +4251,26 @@ blake3_compress_subtree_wide( return compress_chunks_parallel(input, input_len, key, chunk_counter, flags, out); } - left_input_len = left_len(input_len); - right_input_len = input_len - left_input_len; - right_input = &input[left_input_len]; + left_input_len = left_len(input_len); + right_input_len = input_len - left_input_len; + right_input = &input[left_input_len]; right_chunk_counter = chunk_counter + (uint64_t)(left_input_len / BLAKE3_CHUNK_LEN); /* MAX_SIMD_DEGREE_OR_2 accounts for the degree=1 special case below, - * which always returns 2 outputs even though degree itself is 1 */ + * which always returns 2 outputs even though degree itself is 1 */ degree = blake3_simd_degree(); if (left_input_len > BLAKE3_CHUNK_LEN && degree == 1) { degree = 2; } right_cvs = &cv_array[degree * BLAKE3_OUT_LEN]; - left_n = - blake3_compress_subtree_wide(input, left_input_len, key, chunk_counter, flags, cv_array); + left_n = blake3_compress_subtree_wide(input, left_input_len, key, chunk_counter, flags, cv_array); right_n = blake3_compress_subtree_wide( right_input, right_input_len, key, right_chunk_counter, flags, right_cvs ); /* degree=1: left_n and right_n are both 1, return both cvs directly - * rather than compressing them, so the caller always sees at least 2 */ + * rather than compressing them, so the caller always sees at least 2 */ if (left_n == 1) { memcpy(out, cv_array, 2 * BLAKE3_OUT_LEN); return 2; @@ -4522,4 +4521,3 @@ blake3_hasher_reset(struct Blake3Hasher *self) chunk_state_reset(&self->chunk, self->key, 0); self->cv_stack_len = 0; } - diff --git a/shared/libblake3/blake3.h b/shared/libblake3/blake3.h @@ -30,12 +30,14 @@ struct Blake3Hasher { void blake3_hasher_init(struct Blake3Hasher *self); void blake3_hasher_init_keyed(struct Blake3Hasher *self, const uint8_t key[BLAKE3_KEY_LEN]); void blake3_hasher_init_derive_key(struct Blake3Hasher *self, const char *context); -void blake3_hasher_init_derive_key_raw(struct Blake3Hasher *self, const void *context, - size_t context_len); +void blake3_hasher_init_derive_key_raw( + struct Blake3Hasher *self, const void *context, size_t context_len +); void blake3_hasher_update(struct Blake3Hasher *self, const void *input, size_t input_len); void blake3_hasher_finalize(const struct Blake3Hasher *self, uint8_t *out, size_t out_len); -void blake3_hasher_finalize_seek(const struct Blake3Hasher *self, uint64_t seek, uint8_t *out, - size_t out_len); +void blake3_hasher_finalize_seek( + const struct Blake3Hasher *self, uint64_t seek, uint8_t *out, size_t out_len +); void blake3_hasher_reset(struct Blake3Hasher *self); const char *blake3_version(void); diff --git a/shared/libdisk/gpt.c b/shared/libdisk/gpt.c @@ -43,14 +43,14 @@ const struct GptType gpt_types[] = { /* short two-byte codes match gdisk/sgdisk's own convention, since * every caller already writing "-t ef00" etc against those tools * expects the same codes here. the last is the default */ - {"ef00", "EFI system", "c12a7328-f81f-11d2-ba4b-00a0c93ec93b", 0xef}, - {"ef02", "BIOS boot", "21686148-6449-6e6f-744e-656564454649", 0x00}, - {"8200", "Linux swap", "0657fd6d-a4ab-43c4-84e5-0933c84b4f4f", 0x82}, - {"0700", "Basic data", "ebd0a0a2-b9e5-4433-87c0-68b6b72699c7", 0x07}, - {"8e00", "Linux LVM", "e6d6d379-f507-44c2-a23c-238f2a3df928", 0x8e}, - {"fd00", "Linux RAID", "a19d880f-05fc-4d3b-a006-743f0f84911e", 0xfd}, - {"8302", "Linux home", "933ac7e1-2eb4-4f13-b844-0e14e2aef915", 0x83}, - {"8300", "Linux filesystem", "0fc63daf-8483-4772-8e79-3d69d8477de4", 0x83}, + {"ef00", "EFI system", "c12a7328-f81f-11d2-ba4b-00a0c93ec93b", 0xef}, + {"ef02", "BIOS boot", "21686148-6449-6e6f-744e-656564454649", 0x00}, + {"8200", "Linux swap", "0657fd6d-a4ab-43c4-84e5-0933c84b4f4f", 0x82}, + {"0700", "Basic data", "ebd0a0a2-b9e5-4433-87c0-68b6b72699c7", 0x07}, + {"8e00", "Linux LVM", "e6d6d379-f507-44c2-a23c-238f2a3df928", 0x8e}, + {"fd00", "Linux RAID", "a19d880f-05fc-4d3b-a006-743f0f84911e", 0xfd}, + {"8302", "Linux home", "933ac7e1-2eb4-4f13-b844-0e14e2aef915", 0x83}, + {"8300", "Linux filesystem", "0fc63daf-8483-4772-8e79-3d69d8477de4", 0x83}, }; const int gpt_ntypes = (int)(sizeof(gpt_types) / sizeof(gpt_types[0])); @@ -60,10 +60,10 @@ const int gpt_ntypes = (int)(sizeof(gpt_types) / sizeof(gpt_types[0])); int parse_guid_string(const char *s, uint8_t out[16]) { - static const int group_len[5] = {8, 4, 4, 4, 12}; - static const int group_le[5] = {1, 1, 1, 0, 0}; - int g, i, hi, lo, byte_idx = 0; - const char *p = s; + static const int group_len[5] = {8, 4, 4, 4, 12}; + static const int group_le[5] = {1, 1, 1, 0, 0}; + int g, i, hi, lo, byte_idx = 0; + const char *p = s; for (g = 0; g < 5; g++) { uint8_t bytes[6]; @@ -96,8 +96,27 @@ parse_guid_string(const char *s, uint8_t out[16]) void format_guid(const uint8_t g[16], char out[37]) { - snprintf(out, 37, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", g[3], g[2], g[1], g[0], g[5], - g[4], g[7], g[6], g[8], g[9], g[10], g[11], g[12], g[13], g[14], g[15]); + snprintf( + out, + 37, + "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", + g[3], + g[2], + g[1], + g[0], + g[5], + g[4], + g[7], + g[6], + g[8], + g[9], + g[10], + g[11], + g[12], + g[13], + g[14], + g[15] + ); } const struct GptType * @@ -240,4 +259,3 @@ gpt_write(struct BlockDev *dev, struct GptHeader *hdr, struct GptPartition *part return 0; } - diff --git a/shared/libdisk/gpt.h b/shared/libdisk/gpt.h @@ -73,9 +73,9 @@ void format_guid(const uint8_t guid[16], char out[37]); void gpt_type_guid(const char *type, uint8_t out[16]); /* the type of a GUID: its table entry, NULL when it is none of them */ const struct GptType *gpt_type_of(const uint8_t guid[16]); -int gpt_random_guid(uint8_t out[16]); -void gpt_set_name(uint16_t name[36], const char *s); -int gpt_read(struct BlockDev *dev, struct GptHeader *hdr, struct GptPartition *parts); -int gpt_write(struct BlockDev *dev, struct GptHeader *hdr, struct GptPartition *parts); +int gpt_random_guid(uint8_t out[16]); +void gpt_set_name(uint16_t name[36], const char *s); +int gpt_read(struct BlockDev *dev, struct GptHeader *hdr, struct GptPartition *parts); +int gpt_write(struct BlockDev *dev, struct GptHeader *hdr, struct GptPartition *parts); #endif diff --git a/shared/libdisk/label.c b/shared/libdisk/label.c @@ -110,17 +110,18 @@ read_gpt(struct BlockDev *dev, struct label *l) if (!(parts = calloc(GPT_ENTRIES, GPT_ENTRY_SZ))) return -1; - if (gpt_read(dev, &hdr, parts) < 0 || hdr.part_size != GPT_ENTRY_SZ || hdr.num_parts > GPT_ENTRIES) { + if (gpt_read(dev, &hdr, parts) < 0 || hdr.part_size != GPT_ENTRY_SZ + || hdr.num_parts > GPT_ENTRIES) { free(parts); return 0; /* no GPT */ } - l->kind = LABEL_GPT; - l->slots = LABEL_SLOTS; - l->first = hdr.first_usable; - l->last = hdr.last_usable; + l->kind = LABEL_GPT; + l->slots = LABEL_SLOTS; + l->first = hdr.first_usable; + l->last = hdr.last_usable; memcpy(l->disk_guid, hdr.disk_guid, 16); for (i = 0; i < hdr.num_parts; i++) { - struct label_part *p = &l->part[i]; + struct label_part *p = &l->part[i]; const struct GptType *t; int c; @@ -165,7 +166,7 @@ read_mbr(struct BlockDev *dev, struct label *l) memcpy(&l->mbr_id, mbr.code + 440, 4); for (i = 0; i < MBR_SLOTS; i++) { struct label_part *p = &l->part[i]; - int t; + int t; if (mbr.parts[i].type == 0 || mbr.parts[i].size == 0) continue; @@ -217,7 +218,8 @@ overlaps(const struct label *l, uint64_t start, uint64_t end, int except) static int by_start(const void *a, const void *b) { - const struct label_part *x = *(const struct label_part *const *)a, *y = *(const struct label_part *const *)b; + const struct label_part *x = *(const struct label_part *const *)a, + *y = *(const struct label_part *const *)b; return x->start < y->start ? -1 : x->start > y->start; } @@ -384,7 +386,7 @@ static void drop_gpt(struct BlockDev *dev) { unsigned char sector[4096]; - uint64_t at[2] = { 1, dev->size / dev->sec_size - 1 }; + uint64_t at[2] = {1, dev->size / dev->sec_size - 1}; int i; if (dev->sec_size > sizeof sector) diff --git a/shared/libdisk/label.h b/shared/libdisk/label.h @@ -49,7 +49,8 @@ int label_init(struct label *l, const struct BlockDev *dev, enum label_kind kind /* a partition of sectors (0: all of the biggest gap) at start (0: the first gap it fits), of type * (a code of label_types) and name. its slot, a negative errno: -ENOSPC no gap, -EINVAL a start * that overlaps, -EEXIST all slots used */ -int label_add(struct label *l, uint64_t start, uint64_t sectors, const char *type, const char *name); +int +label_add(struct label *l, uint64_t start, uint64_t sectors, const char *type, const char *name); int label_delete(struct label *l, int slot); int label_set_type(struct label *l, int slot, const char *type); int label_set_name(struct label *l, int slot, const char *name); @@ -69,7 +70,7 @@ struct label_type { const char *code, *name; int gpt_only; /* MBR has no byte for it */ }; -int label_types(const struct label_type **out); -const char *label_type_name(const struct label_part *p); +int label_types(const struct label_type **out); +const char *label_type_name(const struct label_part *p); #endif diff --git a/shared/libdisk/label_test.c b/shared/libdisk/label_test.c @@ -16,10 +16,10 @@ static void roundtrip(const char *path, enum label_kind kind) { - struct BlockDev dev; - struct label a, b; + struct BlockDev dev; + struct label a, b; struct label_gap gaps[8]; - int esp, root, n; + int esp, root, n; assert(blockdev_open(&dev, path, 1) == 0); assert(label_init(&a, &dev, kind) == 0); @@ -43,7 +43,10 @@ roundtrip(const char *path, enum label_kind kind) assert(b.kind == kind); assert(b.part[0].used && b.part[1].used && !b.part[2].used); assert(b.part[0].start == a.part[0].start && b.part[0].end == a.part[0].end); - assert(!strcmp(b.part[0].type, "8200") && !strcmp(b.part[1].type, kind == LABEL_GPT ? "8302" : "8300")); + assert( + !strcmp(b.part[0].type, "8200") + && !strcmp(b.part[1].type, kind == LABEL_GPT ? "8302" : "8300") + ); if (kind == LABEL_GPT) assert(!strcmp(b.part[0].name, "SWAP") && !strcmp(b.part[1].name, "ROOT")); blockdev_close(&dev); @@ -53,7 +56,7 @@ int main(void) { char path[] = "/tmp/label_test.XXXXXX"; - int fd = mkstemp(path); + int fd = mkstemp(path); assert(fd >= 0 && ftruncate(fd, (off_t)IMAGE_MIB << 20) == 0); close(fd); diff --git a/shared/libdisk/plan.c b/shared/libdisk/plan.c @@ -11,10 +11,10 @@ #include <strings.h> static const struct plan_fs filesystems[] = { - {"ext4", "ext4", "ext4", 1, 16}, - {"f2fs", "f2fs", "f2fs", 1, 512}, + {"ext4", "ext4", "ext4", 1, 16}, + {"f2fs", "f2fs", "f2fs", 1, 512}, {"vfat", "FAT32 (vfat)", "vfat", 0, 11}, - {"swap", "swap", NULL, 0, 15}, + {"swap", "swap", NULL, 0, 15}, }; #define NFS ((int)(sizeof filesystems / sizeof filesystems[0])) @@ -42,15 +42,17 @@ plan_part_path(const char *disk, int slot, char *buf, size_t n) size_t len = strlen(disk); /* a name that ends in a digit takes a p before the number: nvme0n1p1, mmcblk0p1 */ - snprintf(buf, n, "%s%s%d", disk, len && isdigit((unsigned char)disk[len - 1]) ? "p" : "", slot + 1); + snprintf( + buf, n, "%s%s%d", disk, len && isdigit((unsigned char)disk[len - 1]) ? "p" : "", slot + 1 + ); } void plan_size(uint64_t bytes, char *buf, size_t n) { static const char *units[] = {"B", "KiB", "MiB", "GiB", "TiB"}; - double v = (double)bytes; - int u = 0; + double v = (double)bytes; + int u = 0; while (v >= 1024 && u < 4) { v /= 1024; @@ -103,7 +105,7 @@ plan_read_disk(struct plan *p, const char *disk) int plan_set(struct plan *p, int slot, const char *fs, const char *mount, const char *label, int format) { - struct plan_part *a; + struct plan_part *a; const struct plan_fs *f; if (slot < 0 || slot >= p->label.slots || !p->label.part[slot].used) @@ -122,8 +124,16 @@ plan_set(struct plan *p, int slot, const char *fs, const char *mount, const char } int -plan_add(struct plan *p, uint64_t start, uint64_t sectors, const char *type, const char *name, const char *fs, - const char *mount, const char *label) +plan_add( + struct plan *p, + uint64_t start, + uint64_t sectors, + const char *type, + const char *name, + const char *fs, + const char *mount, + const char *label +) { int slot = label_add(&p->label, start, sectors, type, name); @@ -161,17 +171,17 @@ plan_check(const struct plan *p, unsigned need, char *why, size_t n) int i, j, root = 0, esp = 0, bios = 0; for (i = 0; i < p->label.slots; i++) { - const struct plan_part *a = &p->attr[i]; + const struct plan_part *a = &p->attr[i]; const struct label_part *l = &p->label.part[i]; - const struct plan_fs *f = plan_filesystem(a->fs); + const struct plan_fs *f = plan_filesystem(a->fs); if (!l->used) continue; if (a->format && strcmp(a->fs, "ext4") == 0) { uint64_t sectors = l->end - l->start + 1; - if (!p->label.sec_size || MKFS_EXT4_BLOCK_SIZE % p->label.sec_size || - sectors > UINT64_MAX / p->label.sec_size || - !mkfs_ext4_size_ok(sectors * p->label.sec_size)) + if (!p->label.sec_size || MKFS_EXT4_BLOCK_SIZE % p->label.sec_size + || sectors > UINT64_MAX / p->label.sec_size + || !mkfs_ext4_size_ok(sectors * p->label.sec_size)) return fail(why, n, "%s", "ext4 needs 8 MiB to below 16 TiB and sectors dividing 4 KiB"); } if (a->mount[0] && a->mount[0] != '/') @@ -188,7 +198,8 @@ plan_check(const struct plan *p, unsigned need, char *why, size_t n) return fail(why, n, "%s", "the system cannot start from the filesystem at /"); root = 1; } - if (strcmp(a->mount, "/boot/efi") == 0 && strcmp(l->type, "ef00") == 0 && strcmp(a->fs, "vfat") == 0) + if (strcmp(a->mount, "/boot/efi") == 0 && strcmp(l->type, "ef00") == 0 + && strcmp(a->fs, "vfat") == 0) esp = 1; if (strcmp(l->type, "ef02") == 0) bios = 1; @@ -196,23 +207,40 @@ plan_check(const struct plan *p, unsigned need, char *why, size_t n) if ((need & PLAN_NEED_ROOT) && !root) return fail(why, n, "%s", "no partition is mounted at /"); if ((need & PLAN_NEED_BOOT) && !esp && !bios) - return fail(why, n, "%s", "the machine needs a way to start: an EFI system partition mounted at /boot/efi, or a BIOS boot partition"); + return fail( + why, + n, + "%s", + "the machine needs a way to start: an EFI system partition mounted at /boot/efi, or a BIOS " + "boot partition" + ); return 0; } int -plan_changes(const struct plan *before, const struct plan *now, void (*fn)(const char *line, void *arg), void *arg) +plan_changes( + const struct plan *before, + const struct plan *now, + void (*fn)(const char *line, void *arg), + void *arg +) { char line[256], dev[PLAN_PATH + 8], size[32]; int i, n = 0; struct plan *none = NULL; - /* a table of another kind replaces the one there: all it held is gone, all the new one holds is made */ + /* a table of another kind replaces the one there: all it held is gone, all the new one holds is + * made */ if (before->label.kind != now->label.kind) { if (before->label.kind != LABEL_NONE) { - snprintf(line, sizeof line, "write a new %s partition table on %s, every partition on it is lost", - now->label.kind == LABEL_GPT ? "GPT" : "MBR", now->disk); + snprintf( + line, + sizeof line, + "write a new %s partition table on %s, every partition on it is lost", + now->label.kind == LABEL_GPT ? "GPT" : "MBR", + now->disk + ); if (fn) fn(line, arg); n++; @@ -220,13 +248,13 @@ plan_changes(const struct plan *before, const struct plan *now, void (*fn)(const if (!(none = calloc(1, sizeof *none))) return n; none->label.slots = now->label.slots; - before = none; + before = none; } for (i = 0; i < now->label.slots; i++) { const struct label_part *a = &before->label.part[i], *b = &now->label.part[i]; const struct plan_part *x = &before->attr[i], *y = &now->attr[i]; - int same = a->used && b->used && a->start == b->start && a->end == b->end && - strcmp(a->type, b->type) == 0; + int same = a->used && b->used && a->start == b->start && a->end == b->end + && strcmp(a->type, b->type) == 0; plan_part_path(now->disk, i, dev, sizeof dev); if (a->used && !same) { @@ -243,7 +271,15 @@ plan_changes(const struct plan *before, const struct plan *now, void (*fn)(const n++; } if (b->used && y->format && y->fs[0]) { - snprintf(line, sizeof line, "format %s as %s%s%s", dev, y->fs, y->label[0] ? " labelled " : "", y->label); + snprintf( + line, + sizeof line, + "format %s as %s%s%s", + dev, + y->fs, + y->label[0] ? " labelled " : "", + y->label + ); if (fn) fn(line, arg); n++; @@ -339,15 +375,28 @@ plan_save(const struct plan *p, FILE *f) { int i; - fprintf(f, "disk %s\nlabel %s\n", p->disk, p->label.kind == LABEL_GPT ? "gpt" : p->label.kind == LABEL_MBR ? "mbr" : "none"); + fprintf( + f, + "disk %s\nlabel %s\n", + p->disk, + p->label.kind == LABEL_GPT ? "gpt" + : p->label.kind == LABEL_MBR ? "mbr" + : "none" + ); for (i = 0; i < p->label.slots; i++) { const struct label_part *l = &p->label.part[i]; const struct plan_part *a = &p->attr[i]; if (!l->used) continue; - fprintf(f, "part %d start=%llu sectors=%llu type=%s", i + 1, (unsigned long long)l->start, - (unsigned long long)(l->end - l->start + 1), l->type[0] ? l->type : "8300"); + fprintf( + f, + "part %d start=%llu sectors=%llu type=%s", + i + 1, + (unsigned long long)l->start, + (unsigned long long)(l->end - l->start + 1), + l->type[0] ? l->type : "8300" + ); if (l->name[0]) fprintf(f, " name=%s", l->name); if (a->fs[0]) @@ -373,7 +422,7 @@ bad(char *why, size_t n, const char *line) int plan_load(struct plan *p, FILE *f, char *why, size_t n) { - char line[512]; + char line[512]; struct BlockDev dev; memset(p, 0, sizeof *p); @@ -388,15 +437,19 @@ plan_load(struct plan *p, FILE *f, char *why, size_t n) if (strncmp(line, "disk ", 5) == 0) { snprintf(p->disk, sizeof p->disk, "%s", line + 5); } else if (strncmp(line, "label ", 6) == 0) { - enum label_kind kind = strcmp(line + 6, "gpt") == 0 ? LABEL_GPT : strcmp(line + 6, "mbr") == 0 ? LABEL_MBR : LABEL_NONE; + enum label_kind kind = strcmp(line + 6, "gpt") == 0 ? LABEL_GPT + : strcmp(line + 6, "mbr") == 0 ? LABEL_MBR + : LABEL_NONE; /* the table's geometry comes from the disk it is for */ - if (kind == LABEL_NONE || !p->disk[0] || blockdev_open(&dev, p->disk, 0) < 0 || label_init(&p->label, &dev, kind) < 0) + if (kind == LABEL_NONE || !p->disk[0] || blockdev_open(&dev, p->disk, 0) < 0 + || label_init(&p->label, &dev, kind) < 0) return bad(why, n, line); blockdev_close(&dev); } else if (strncmp(line, "part ", 5) == 0) { uint64_t start = 0, sectors = 0; - char type[8] = "8300", name[40] = "", fs[PLAN_FS] = "", mount[PLAN_MOUNT] = "", label[PLAN_LABEL] = ""; + char type[8] = "8300", name[40] = "", fs[PLAN_FS] = "", mount[PLAN_MOUNT] = "", + label[PLAN_LABEL] = ""; int format = 0, index = (int)strtol(line + 5, &word, 10); if (p->label.kind == LABEL_NONE || index < 1 || index > p->label.slots) @@ -453,7 +506,8 @@ plan_guided(struct plan *p, const char *disk, uint64_t swap_mib, const char *roo memset(p, 0, sizeof *p); snprintf(p->disk, sizeof p->disk, "%s", disk); - if (!plan_filesystem(root_fs) || !plan_filesystem(root_fs)->bootable || blockdev_open(&dev, disk, 0) < 0) + if (!plan_filesystem(root_fs) || !plan_filesystem(root_fs)->bootable + || blockdev_open(&dev, disk, 0) < 0) return -1; if (label_init(&p->label, &dev, LABEL_GPT) < 0) { blockdev_close(&dev); diff --git a/shared/libdisk/plan.h b/shared/libdisk/plan.h @@ -46,9 +46,9 @@ struct plan { /* the filesystems a partition can hold */ struct plan_fs { const char *name; - const char *title; /* for a person */ - const char *mount_as; /* the type the system mounts it as, NULL for none (swap) */ - int bootable; /* a root filesystem the system can start from */ + const char *title; /* for a person */ + const char *mount_as; /* the type the system mounts it as, NULL for none (swap) */ + int bootable; /* a root filesystem the system can start from */ int max_label; }; const struct plan_fs *plan_filesystems(int *n); @@ -62,21 +62,38 @@ void plan_part_path(const char *disk, int slot, char *buf, size_t n); int plan_read_disk(struct plan *p, const char *disk); /* the partition's attributes set. false for a filesystem not known or a label too long */ -int plan_set(struct plan *p, int slot, const char *fs, const char *mount, const char *label, int format); +int plan_set( + struct plan *p, int slot, const char *fs, const char *mount, const char *label, int format +); /* label_add, with what it is to hold: the slot or a negative errno */ -int plan_add(struct plan *p, uint64_t start, uint64_t sectors, const char *type, const char *name, const char *fs, - const char *mount, const char *label); +int plan_add( + struct plan *p, + uint64_t start, + uint64_t sectors, + const char *type, + const char *name, + const char *fs, + const char *mount, + const char *label +); int plan_delete(struct plan *p, int slot); /* what the plan needs to be installed to: the checks asked for */ #define PLAN_NEED_ROOT 1 /* a partition mounted at /, of a filesystem to start from */ -#define PLAN_NEED_BOOT 2 /* a way for the machine to start: an EFI system partition at /boot/efi or a BIOS boot one */ +#define PLAN_NEED_BOOT \ + 2 /* a way for the machine to start: an EFI system partition at /boot/efi or a BIOS boot one */ /* 0 when the plan holds, else -1 and why, in words for a person */ int plan_check(const struct plan *p, unsigned need, char *why, size_t n); -/* what applying now would do over before, a line each (fn may be NULL to count), to read before it is done +/* what applying now would do over before, a line each (fn may be NULL to count), to read before it + * is done * ("delete /dev/vda2", "create 512 MiB EFI system", "format /dev/vda3 as ext4"). how many */ -int plan_changes(const struct plan *before, const struct plan *now, void (*fn)(const char *line, void *arg), void *arg); +int plan_changes( + const struct plan *before, + const struct plan *now, + void (*fn)(const char *line, void *arg), + void *arg +); /* the layout an installer makes of a whole disk when it is not asked for another: a 1 MiB BIOS boot * partition, a 512 MiB EFI system one at /boot/efi, swap when swap_mib is not 0, and the rest the @@ -85,20 +102,22 @@ int plan_changes(const struct plan *before, const struct plan *now, void (*fn)(c #define PLAN_ESP_MIB 512 int plan_guided(struct plan *p, const char *disk, uint64_t swap_mib, const char *root_fs); -/* a part of the plan by its role: "esp", "root" and "swap" the device (/dev/vda2), "bios" the number - * of the BIOS boot partition, "rootfs" the filesystem at /. false when the plan has none */ +/* a part of the plan by its role: "esp", "root" and "swap" the device (/dev/vda2), "bios" the + * number of the BIOS boot partition, "rootfs" the filesystem at /. false when the plan has none */ int plan_role(const struct plan *p, const char *role, char *buf, size_t n); /* the slots that have a place to be mounted, in the order to mount them: / before /boot before * /boot/efi. how many, at most max */ int plan_mount_order(const struct plan *p, int *slots, int max); -/* waits for the devices of the partitions to be there after the table is written, up to tenths of a second */ +/* waits for the devices of the partitions to be there after the table is written, up to tenths of a + * second */ int plan_wait_nodes(const struct plan *p, int tenths); /* the table written to the disk, the filesystems left for the caller */ int plan_write_table(const struct plan *p); /* the command that makes the filesystem of slot: its argv into argv (at most max words, * NULL ended) whose words are held in store. 0, -1 when the slot has no filesystem to make */ -int plan_mkfs_argv(const struct plan *p, int slot, char **argv, int max, char *store, size_t store_n); +int +plan_mkfs_argv(const struct plan *p, int slot, char **argv, int max, char *store, size_t store_n); int plan_save(const struct plan *p, FILE *f); /* a plan read: -1 with why for a line that is not one */ diff --git a/shared/libdisk/plan_test.c b/shared/libdisk/plan_test.c @@ -1,8 +1,10 @@ /* see LICENSE file for copyright and license details */ /* a plan made on an image, checked, written, saved and read again: - * cc -D_GNU_SOURCE -Ishared shared/libdisk/plan_test.c shared/libdisk/plan.c shared/libdisk/label.c \ - * shared/libdisk/gpt.c shared/libutil/diskutil.c shared/libutil/hexval.c shared/libutil/eprintf.c \ - * shared/libutil/ealloc.c shared/libutil/strlcpy.c -o plan_test && ./plan_test */ + * cc -D_GNU_SOURCE -Ishared shared/libdisk/plan_test.c shared/libdisk/plan.c + * shared/libdisk/label.c \ + * shared/libdisk/gpt.c shared/libutil/diskutil.c shared/libutil/hexval.c + * shared/libutil/eprintf.c \ shared/libutil/ealloc.c shared/libutil/strlcpy.c -o plan_test && + * ./plan_test */ #include "plan.h" #include <assert.h> #include <fcntl.h> @@ -10,38 +12,86 @@ #include <stdlib.h> #include <string.h> #include <unistd.h> -static int nlines; static void line(const char *l, void *a){ (void)a; nlines++; puts(l); } -int main(void){ - char path[]="/tmp/plan_test.XXXXXX"; int fd=mkstemp(path); assert(fd>=0 && ftruncate(fd,(off_t)1<<40)==0); close(fd); - struct plan before, p; char why[200]; char *argv[16]; char store[256]; - assert(plan_read_disk(&before,path)==0 && before.label.kind==LABEL_NONE); - p=before; - { struct BlockDev d; assert(blockdev_open(&d,path,0)==0); assert(label_init(&p.label,&d,LABEL_GPT)==0); blockdev_close(&d); } - assert(plan_check(&p,PLAN_NEED_ROOT,why,sizeof why)<0); - assert(plan_add(&p,0,2048,"ef02","BIOS","","","")==0); - assert(plan_add(&p,0,64*2048,"ef00","ESP","vfat","/boot/efi","ESP")==1); - assert(plan_add(&p,0,0,"8300","ROOT","ext4","/","")==2); - assert(plan_check(&p,PLAN_NEED_ROOT|PLAN_NEED_BOOT,why,sizeof why)==0); - { uint64_t end = p.label.part[2].end; +static int nlines; +static void +line(const char *l, void *a) +{ + (void)a; + nlines++; + puts(l); +} +int +main(void) +{ + char path[] = "/tmp/plan_test.XXXXXX"; + int fd = mkstemp(path); + assert(fd >= 0 && ftruncate(fd, (off_t)1 << 40) == 0); + close(fd); + struct plan before, p; + char why[200]; + char *argv[16]; + char store[256]; + assert(plan_read_disk(&before, path) == 0 && before.label.kind == LABEL_NONE); + p = before; + { + struct BlockDev d; + assert(blockdev_open(&d, path, 0) == 0); + assert(label_init(&p.label, &d, LABEL_GPT) == 0); + blockdev_close(&d); + } + assert(plan_check(&p, PLAN_NEED_ROOT, why, sizeof why) < 0); + assert(plan_add(&p, 0, 2048, "ef02", "BIOS", "", "", "") == 0); + assert(plan_add(&p, 0, 64 * 2048, "ef00", "ESP", "vfat", "/boot/efi", "ESP") == 1); + assert(plan_add(&p, 0, 0, "8300", "ROOT", "ext4", "/", "") == 2); + assert(plan_check(&p, PLAN_NEED_ROOT | PLAN_NEED_BOOT, why, sizeof why) == 0); + { + uint64_t end = p.label.part[2].end; p.label.part[2].end = p.label.part[2].start + 2047; - assert(plan_check(&p,0,why,sizeof why)<0); - p.label.part[2].end = end; } - assert(plan_changes(&before,&p,line,NULL)>=3); + assert(plan_check(&p, 0, why, sizeof why) < 0); + p.label.part[2].end = end; + } + assert(plan_changes(&before, &p, line, NULL) >= 3); char target[PLAN_PATH + 8]; plan_part_path(p.disk, 2, target, sizeof target); - assert(plan_mkfs_argv(&p,2,argv,16,store,sizeof store)==0 && !strcmp(argv[0],"mkfs.ext4") && !strcmp(argv[1],target) && !argv[2]); - assert(plan_write_table(&p)==0); - FILE *f=tmpfile(); assert(plan_save(&p,f)==0); rewind(f); - struct plan q; assert(plan_load(&q,f,why,sizeof why)==0); - for(int i=0;i<3;i++){ assert(q.label.part[i].start==p.label.part[i].start && q.label.part[i].end==p.label.part[i].end); assert(!strcmp(q.attr[i].fs,p.attr[i].fs)&&!strcmp(q.attr[i].mount,p.attr[i].mount)); } - struct plan r; assert(plan_read_disk(&r,path)==0 && r.label.kind==LABEL_GPT && r.label.part[2].used); - p.attr[1].mount[0]='x'; assert(plan_check(&p,0,why,sizeof why)<0); puts(why); - plan_set(&p,1,"vfat","/",NULL,1); assert(plan_check(&p,0,why,sizeof why)<0); puts(why); - { struct plan g; char dev[64]; int order[8]; - assert(plan_guided(&g,path,128,"ext4")==0); - assert(plan_role(&g,"esp",dev,sizeof dev)==1 && g.label.part[1].used); - assert(plan_role(&g,"bios",dev,sizeof dev)==1 && !strcmp(dev,"1")); - assert(plan_role(&g,"rootfs",dev,sizeof dev)==1 && !strcmp(dev,"ext4")); - assert(plan_mount_order(&g,order,8)==2 && !strcmp(g.attr[order[0]].mount,"/") && !strcmp(g.attr[order[1]].mount,"/boot/efi")); - assert(plan_check(&g,PLAN_NEED_ROOT|PLAN_NEED_BOOT,why,sizeof why)==0); } - unlink(path); puts("plan_test: ok"); return 0; } + assert( + plan_mkfs_argv(&p, 2, argv, 16, store, sizeof store) == 0 && !strcmp(argv[0], "mkfs.ext4") + && !strcmp(argv[1], target) && !argv[2] + ); + assert(plan_write_table(&p) == 0); + FILE *f = tmpfile(); + assert(plan_save(&p, f) == 0); + rewind(f); + struct plan q; + assert(plan_load(&q, f, why, sizeof why) == 0); + for (int i = 0; i < 3; i++) { + assert( + q.label.part[i].start == p.label.part[i].start && q.label.part[i].end == p.label.part[i].end + ); + assert(!strcmp(q.attr[i].fs, p.attr[i].fs) && !strcmp(q.attr[i].mount, p.attr[i].mount)); + } + struct plan r; + assert(plan_read_disk(&r, path) == 0 && r.label.kind == LABEL_GPT && r.label.part[2].used); + p.attr[1].mount[0] = 'x'; + assert(plan_check(&p, 0, why, sizeof why) < 0); + puts(why); + plan_set(&p, 1, "vfat", "/", NULL, 1); + assert(plan_check(&p, 0, why, sizeof why) < 0); + puts(why); + { + struct plan g; + char dev[64]; + int order[8]; + assert(plan_guided(&g, path, 128, "ext4") == 0); + assert(plan_role(&g, "esp", dev, sizeof dev) == 1 && g.label.part[1].used); + assert(plan_role(&g, "bios", dev, sizeof dev) == 1 && !strcmp(dev, "1")); + assert(plan_role(&g, "rootfs", dev, sizeof dev) == 1 && !strcmp(dev, "ext4")); + assert( + plan_mount_order(&g, order, 8) == 2 && !strcmp(g.attr[order[0]].mount, "/") + && !strcmp(g.attr[order[1]].mount, "/boot/efi") + ); + assert(plan_check(&g, PLAN_NEED_ROOT | PLAN_NEED_BOOT, why, sizeof why) == 0); + } + unlink(path); + puts("plan_test: ok"); + return 0; +} diff --git a/shared/libmagic/magic.c b/shared/libmagic/magic.c @@ -519,21 +519,40 @@ run_free(struct MagicRun *r) /* the run over fd's head as read so far */ static void -run_init(struct MagicRun *r, struct Magic *m, int fd, const struct stat *st, const unsigned char *buf, size_t n) +run_init( + struct MagicRun *r, + struct Magic *m, + int fd, + const struct stat *st, + const unsigned char *buf, + size_t n +) { memset(r, 0, sizeof(*r)); - r->m = m; - r->head.p = buf; - r->head.n = n; + r->m = m; + r->head.p = buf; + r->head.n = n; r->head.file = 1; - r->fd = fd; - r->fsize = (long long)st->st_size; + r->fd = fd; + r->fsize = (long long)st->st_size; } /* the hinted pass: 1 with the result in desc and mime when it gave hint */ static int -try_hint(struct Magic *m, int fd, const struct stat *st, const unsigned char *buf, size_t n, const size_t *pick, - size_t npick, const char *hint, char *desc, size_t dn, char *mime, size_t mn) +try_hint( + struct Magic *m, + int fd, + const struct stat *st, + const unsigned char *buf, + size_t n, + const size_t *pick, + size_t npick, + const char *hint, + char *desc, + size_t dn, + char *mime, + size_t mn +) { struct MagicRun r; char got[MG_MIMELEN]; @@ -565,7 +584,15 @@ try_hint(struct Magic *m, int fd, const struct stat *st, const unsigned char *bu /* the far groups over the head as read and their own bytes past it, the * rest zeros: 1 when one of them matches */ static int -try_far(struct Magic *m, int fd, const struct stat *st, unsigned char **buf, size_t have, size_t *cap, size_t want) +try_far( + struct Magic *m, + int fd, + const struct stat *st, + unsigned char **buf, + size_t have, + size_t *cap, + size_t want +) { struct MagicRun r; unsigned char *more; @@ -608,11 +635,13 @@ try_far(struct Magic *m, int fd, const struct stat *st, unsigned char **buf, siz } int -magic_fd_hint(struct Magic *m, int fd, const char *hint, char *desc, size_t dn, char *mime, size_t mn) +magic_fd_hint( + struct Magic *m, int fd, const char *hint, char *desc, size_t dn, char *mime, size_t mn +) { struct MagicRun *r; struct stat st; - unsigned char *buf = NULL; + unsigned char *buf = NULL; size_t have = 0, cap = 0, npick = 0, *pick = NULL, want; long long reach = m->ix ? m->ix->reach : MAGIC_BYTES_MAX; int eof = 0, rv = -1, e; @@ -641,14 +670,17 @@ magic_fd_hint(struct Magic *m, int fd, const char *hint, char *desc, size_t dn, goto out; } reach = m->ix ? m->ix->reach : MAGIC_BYTES_MAX; - want = reach > MAGIC_BYTES_MAX ? MAGIC_BYTES_MAX : reach < MAGIC_CHARSET_MAX ? MAGIC_CHARSET_MAX : (size_t)reach; + want = reach > MAGIC_BYTES_MAX ? MAGIC_BYTES_MAX + : reach < MAGIC_CHARSET_MAX ? MAGIC_CHARSET_MAX + : (size_t)reach; if (grow_head(fd, &buf, &have, &cap, m->ix ? MAGIC_CHARSET_MAX : want, &eof) < 0) { rv = -1; goto done; } run_init(r, m, fd, &st, buf, have); rv = run(m, r, (st.st_mode & 0111) != 0, desc, dn, mime, mn); - if (rv < 0 || eof || have >= want || !m->ix || !m->ix->nfar || !mime || strcmp(mime, "application/octet-stream")) + if (rv < 0 || eof || have >= want || !m->ix || !m->ix->nfar || !mime + || strcmp(mime, "application/octet-stream")) goto done; /* the far tests tried over just the bytes they look at; read the whole * way only for one that matches */ diff --git a/shared/libmagic/magic.h b/shared/libmagic/magic.h @@ -98,7 +98,9 @@ int magic_prepare(struct Magic *m); * bytes already read and as many more as the tests with a known reach * look at. without magic_prepare it reads as magic_fd does */ -int magic_fd_hint(struct Magic *m, int fd, const char *hint, char *desc, size_t dn, char *mime, size_t mn); +int magic_fd_hint( + struct Magic *m, int fd, const char *hint, char *desc, size_t dn, char *mime, size_t mn +); /* * whether a test can give mime: when one can and the file did not come * out so, its name was wrong to say it. 0 without magic_prepare diff --git a/shared/libmagic/mgindex.c b/shared/libmagic/mgindex.c @@ -95,7 +95,11 @@ compile(struct MagicLine *l) return 0; if (!(l->rx = malloc(sizeof(*l->rx)))) return -1; - if (regcomp(l->rx, l->value.s, REG_EXTENDED | REG_NEWLINE | (l->sflags & SF_IGNORE_CASE ? REG_ICASE : 0))) { + if (regcomp( + l->rx, + l->value.s, + REG_EXTENDED | REG_NEWLINE | (l->sflags & SF_IGNORE_CASE ? REG_ICASE : 0) + )) { free(l->rx); l->rx = NULL; l->rxbad = 1; @@ -131,7 +135,8 @@ index_db(struct MagicIndex *ix, struct MagicDb *db, size_t *gcap, size_t *mcap) for (size_t k = i; k < j; k++) { /* a test from the end and what follows it read within the tail, * as far back as the test's own offset */ - if ((v[k].flag & MF_OFFNEG) && (size_t)(uint32_t)v[k].offset + mg_typesize(v[k].type) + v[k].vallen > ix->tail) + if ((v[k].flag & MF_OFFNEG) + && (size_t)(uint32_t)v[k].offset + mg_typesize(v[k].type) + v[k].vallen > ix->tail) ix->tail = (size_t)(uint32_t)v[k].offset + mg_typesize(v[k].type) + v[k].vallen; r = line_reach(&v[k], from_end && !(v[k].flag & MF_OFFPOS)); if (r < 0 || g->reach < 0) @@ -148,7 +153,7 @@ index_db(struct MagicIndex *ix, struct MagicDb *db, size_t *gcap, size_t *mcap) if (!more) return -1; - ix->far = more; + ix->far = more; ix->far[ix->nfar++] = ix->ngroup; } ix->ngroup++; @@ -258,8 +263,8 @@ size_t mg_index_probe(struct MagicRun *r, unsigned char *buf, size_t have, size_t n, size_t *alive) { const struct MagicIndex *ix = r->m->ix; - struct MagicBuf b = {buf, n, 1}; - size_t k = 0; + struct MagicBuf b = {buf, n, 1}; + size_t k = 0; for (size_t i = 0; i < ix->nfar; i++) { const struct MagicGroup *g = &ix->group[ix->far[i]]; diff --git a/shared/libmagic/mgmatch.c b/shared/libmagic/mgmatch.c @@ -2171,7 +2171,7 @@ int mg_top_holds(struct MagicRun *r, struct MagicLine *m, const struct MagicBuf *b) { struct MagicBuf bb; - struct Shared sh = {0, 0, 1}; + struct Shared sh = {0, 0, 1}; int ret = 0, found = 0; memset(&bb, 0, sizeof(bb)); diff --git a/shared/libmagic/mgtext.c b/shared/libmagic/mgtext.c @@ -500,8 +500,10 @@ mg_encoding( *code = "ASCII"; *code_mime = "us-ascii"; } - } else if (n > 3 && buf[0] == 0xef && buf[1] == 0xbb && buf[2] == 0xbf - && mg_looks_utf8(buf + 3, n - 3, ubuf, &ulen) > 0) { + } else if ( + n > 3 && buf[0] == 0xef && buf[1] == 0xbb && buf[2] == 0xbf + && mg_looks_utf8(buf + 3, n - 3, ubuf, &ulen) > 0 + ) { *code = "Unicode text, UTF-8 (with BOM)"; *code_mime = "utf-8"; } else if (mg_looks_utf8(buf, n, ubuf, &ulen) > 1) { diff --git a/shared/libredline/redline.c b/shared/libredline/redline.c @@ -389,7 +389,7 @@ getCursorPosition(int ifd, int ofd) // a terminal that never answers, a serial console with nothing on the // other end, must not leave the shell stuck before its first prompt while (i < sizeof(buf) - 1) { - struct pollfd pfd = { ifd, POLLIN, 0 }; + struct pollfd pfd = {ifd, POLLIN, 0}; if (poll(&pfd, 1, CURSOR_REPLY_MS) != 1) break; @@ -785,7 +785,7 @@ completeLine(struct redlineState *ls, int keypressed) /* prefix cannot be expanded further */ if (ls->in_completion == 0) { /* first tab: beep and wait for the second tab - */ + */ redlineBeep(); ls->in_completion = 1; c = 0; diff --git a/shared/libtcutil/tcutil.c b/shared/libtcutil/tcutil.c @@ -908,7 +908,7 @@ escape_hex(int c) { char *s = malloc_or_die(5); /* hex escapes are not length-limited so following hex chars would - * be consumed, must use octal which is always 3 digits */ + * be consumed, must use octal which is always 3 digits */ snprintf(s, 5, "\\%03o", c & 0xff); return s; } diff --git a/shared/libutf/rune.c b/shared/libutf/rune.c @@ -107,7 +107,7 @@ charntorune(Rune *p, const char *s, size_t len) for (i = 1; i < MIN(n, len); i++) if ((s[i] & 0xC0) == 0x80) { /* add bits from continuation byte to rune value - * cannot overflow: 6 byte sequences contain 31 bits */ + * cannot overflow: 6 byte sequences contain 31 bits */ r = (r << 6) | (s[i] & 0x3F); /* 10xxxxxx */ } else { /* expected continuation */ *p = Runeerror; diff --git a/shared/libutil/accounts.c b/shared/libutil/accounts.c @@ -14,8 +14,8 @@ acct_valid_name(const char *name) if (n == 0 || n > NAME_MAX_ACCT || !(islower((unsigned char)name[0]) || name[0] == '_')) return 0; for (; *name; name++) - if (!islower((unsigned char)*name) && !isdigit((unsigned char)*name) && *name != '_' && *name != '-') + if (!islower((unsigned char)*name) && !isdigit((unsigned char)*name) && *name != '_' + && *name != '-') return 0; return 1; } - diff --git a/shared/libutil/accounts_linux.c b/shared/libutil/accounts_linux.c @@ -39,7 +39,8 @@ rewrite(const char *path, edit_fn *fn, void *arg, const char *add) if (!(in = fopen(path, "r"))) return -1; - if (fstat(fileno(in), &st) < 0 || snprintf(tmp, sizeof(tmp), "%s.acct", path) >= (int)sizeof(tmp)) { + if (fstat(fileno(in), &st) < 0 + || snprintf(tmp, sizeof(tmp), "%s.acct", path) >= (int)sizeof(tmp)) { fclose(in); return -1; } @@ -60,7 +61,7 @@ rewrite(const char *path, edit_fn *fn, void *arg, const char *add) } while (ok && fgets(line, sizeof(line), in)) { line[strcspn(line, "\n")] = '\0'; - r = fn ? fn(line, buf, sizeof(buf), arg) : line; + r = fn ? fn(line, buf, sizeof(buf), arg) : line; if (r && fprintf(out, "%s\n", r) < 0) ok = 0; } @@ -90,7 +91,7 @@ static int has(const char *path, const char *name) { char line[LINE_MAX_ACCT]; - FILE *f = fopen(path, "r"); + FILE *f = fopen(path, "r"); int found = 0; if (!f) @@ -105,7 +106,7 @@ has(const char *path, const char *name) static long free_id(void) { - const char *paths[] = { ARUU_PATH_PASSWD, ARUU_PATH_GROUP }; + const char *paths[] = {ARUU_PATH_PASSWD, ARUU_PATH_GROUP}; char line[LINE_MAX_ACCT], *f; long top = UID_FIRST - 1, id; FILE *fp; @@ -145,10 +146,10 @@ static const char * members(const char *line, char *buf, size_t n, void *arg) { const struct membership *m = arg; - char list[LINE_MAX_ACCT], *tok, *save; - const char *at = line; - size_t len = 0; - int put = 0; + char list[LINE_MAX_ACCT], *tok, *save; + const char *at = line; + size_t len = 0; + int put = 0; /* name:x:gid: then the members */ for (int colons = 0; colons < 3; colons++) @@ -210,16 +211,16 @@ acct_add(const char *name, const char *home, const char *shell, const char *hash int acct_remove(const char *name) { - struct membership m = { NULL, name, 0 }; + struct membership m = {NULL, name, 0}; if (!acct_valid_name(name) || !has(ARUU_PATH_PASSWD, name)) { errno = ENOENT; return -1; } /* passwd first: a person is gone once passwd says so */ - if (rewrite(ARUU_PATH_PASSWD, drop, (void *)name, NULL) < 0 || - rewrite(ARUU_PATH_SHADOW, drop, (void *)name, NULL) < 0 || - rewrite(ARUU_PATH_GROUP, drop, (void *)name, NULL) < 0) + if (rewrite(ARUU_PATH_PASSWD, drop, (void *)name, NULL) < 0 + || rewrite(ARUU_PATH_SHADOW, drop, (void *)name, NULL) < 0 + || rewrite(ARUU_PATH_GROUP, drop, (void *)name, NULL) < 0) return -1; return rewrite(ARUU_PATH_GROUP, members, &m, NULL); } @@ -227,7 +228,7 @@ acct_remove(const char *name) int acct_member(const char *group, const char *name, int in) { - struct membership m = { group, name, in }; + struct membership m = {group, name, in}; if (!has(ARUU_PATH_GROUP, group) || !has(ARUU_PATH_PASSWD, name)) { errno = ENOENT; diff --git a/shared/libutil/base64.c b/shared/libutil/base64.c @@ -4,8 +4,7 @@ #include "../base64.h" -static const char alphabet[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +static const char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; size_t base64_encode(char *out, const uint8_t *in, size_t n) @@ -53,8 +52,8 @@ long base64_decode(uint8_t *out, size_t cap, const char *in, size_t n) { uint32_t acc = 0; - size_t i, o = 0; - int bits = 0, pad = 0, v; + size_t i, o = 0; + int bits = 0, pad = 0, v; for (i = 0; i < n; i++) { if (in[i] == ' ' || in[i] == '\t' || in[i] == '\r' || in[i] == '\n') diff --git a/shared/libutil/diskutil.c b/shared/libutil/diskutil.c @@ -358,14 +358,15 @@ static void exfat_label(struct BlockDev *dev, const unsigned char *boot, char *label, size_t label_sz) { unsigned char *dir, *e; - uint32_t heap = le32(boot + 88); - uint32_t root = le32(boot + 96); + uint32_t heap = le32(boot + 88); + uint32_t root = le32(boot + 96); unsigned sshift = boot[108], cshift = boot[109]; size_t csize, i, used = 0; uint64_t sector; label[0] = '\0'; - if (sshift < 9 || sshift > 12 || cshift > 25 - sshift || root < 2 || (1u << sshift) != dev->sec_size) + if (sshift < 9 || sshift > 12 || cshift > 25 - sshift || root < 2 + || (1u << sshift) != dev->sec_size) return; csize = (size_t)1 << (sshift + cshift); sector = (uint64_t)heap + ((uint64_t)(root - 2) << cshift); @@ -426,14 +427,17 @@ ntfs_label(struct BlockDev *dev, const unsigned char *boot, char *label, size_t rec[k * 512 - 1] = rec[usa + 2 * k + 1]; } for (a = rec[20] | rec[21] << 8; a + 24 <= rsize;) { - uint32_t type = rec[a] | rec[a + 1] << 8 | (uint32_t)rec[a + 2] << 16 | (uint32_t)rec[a + 3] << 24; - uint32_t len = rec[a + 4] | rec[a + 5] << 8 | (uint32_t)rec[a + 6] << 16 | (uint32_t)rec[a + 7] << 24; + uint32_t type = + rec[a] | rec[a + 1] << 8 | (uint32_t)rec[a + 2] << 16 | (uint32_t)rec[a + 3] << 24; + uint32_t len = + rec[a + 4] | rec[a + 5] << 8 | (uint32_t)rec[a + 6] << 16 | (uint32_t)rec[a + 7] << 24; if (type == NTFS_ATTR_END || len < 24 || a + len > rsize) break; /* resident: its value's length and where it starts in the attribute */ if (type == NTFS_ATTR_VOLNAME && !rec[a + 8]) { - uint32_t vlen = rec[a + 16] | rec[a + 17] << 8 | (uint32_t)rec[a + 18] << 16 | (uint32_t)rec[a + 19] << 24; + uint32_t vlen = rec[a + 16] | rec[a + 17] << 8 | (uint32_t)rec[a + 18] << 16 + | (uint32_t)rec[a + 19] << 24; unsigned voff = rec[a + 20] | rec[a + 21] << 8; if (voff + vlen <= len) diff --git a/shared/libutil/diskutil_linux.c b/shared/libutil/diskutil_linux.c @@ -41,12 +41,12 @@ void blockdev_check_loop(const struct stat *target, const char *name) { struct dirent *de; - struct stat st; - char entry[PATH_MAX], *path = NULL; - size_t cap = 0; - ssize_t n; - DIR *dir; - FILE *f; + struct stat st; + char entry[PATH_MAX], *path = NULL; + size_t cap = 0; + ssize_t n; + DIR *dir; + FILE *f; dir = opendir(ARUU_LINUX_PATH_SYS_BLOCK); if (!dir) { @@ -63,8 +63,10 @@ blockdev_check_loop(const struct stat *target, const char *name) } if (strncmp(de->d_name, "loop", 4)) continue; - if (snprintf(entry, sizeof entry, "%s/%s/loop/backing_file", - ARUU_LINUX_PATH_SYS_BLOCK, de->d_name) >= (int)sizeof entry) + if (snprintf( + entry, sizeof entry, "%s/%s/loop/backing_file", ARUU_LINUX_PATH_SYS_BLOCK, de->d_name + ) + >= (int)sizeof entry) eprintf("%s: loop path too long\n", name); if (!(f = fopen(entry, "r"))) { if (errno == ENOENT) @@ -77,8 +79,7 @@ blockdev_check_loop(const struct stat *target, const char *name) fclose(f); if (n > 0 && path[n - 1] == '\n') path[n - 1] = '\0'; - if (n > 0 && stat(path, &st) == 0 && st.st_dev == target->st_dev && - st.st_ino == target->st_ino) + if (n > 0 && stat(path, &st) == 0 && st.st_dev == target->st_dev && st.st_ino == target->st_ino) eprintf("%s: attached to a loop device\n", name); } free(path); @@ -101,8 +102,8 @@ blockdev_sys_reread(struct BlockDev *dev) static void disk_model(const char *name, char *out, size_t n) { - char path[128]; - FILE *f; + char path[128]; + FILE *f; size_t len; out[0] = '\0'; @@ -149,7 +150,8 @@ unescape_mount(char *s) char *w = s; for (; *s; s++) { - if (s[0] == '\\' && s[1] >= '0' && s[1] <= '3' && s[2] >= '0' && s[2] <= '7' && s[3] >= '0' && s[3] <= '7') { + if (s[0] == '\\' && s[1] >= '0' && s[1] <= '3' && s[2] >= '0' && s[2] <= '7' && s[3] >= '0' + && s[3] <= '7') { *w++ = (char)((s[1] - '0') << 6 | (s[2] - '0') << 3 | (s[3] - '0')); s += 3; } else { @@ -195,7 +197,7 @@ blockdev_get_list(void) info->minor = minor; /* search tree topology to link partition node under proper - * target parent disk */ + * target parent disk */ is_part = 0; for (curr = head; curr; curr = curr->next) { size_t len = strlen(curr->name); @@ -210,7 +212,7 @@ blockdev_get_list(void) } if (is_part) { strlcpy(info->type, "part", sizeof(info->type)); - info->removable = curr->removable; + info->removable = curr->removable; struct BlockDevInfo *p = curr->parts; if (!p) { curr->parts = info; diff --git a/shared/libutil/diskutil_posix.c b/shared/libutil/diskutil_posix.c @@ -5,7 +5,7 @@ /* a kernel with no backend: a device's size is what fstat says, and the * list of disks is what opens under the names most systems give them */ -#if !(defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)) \ +#if !(defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__)) \ || defined(ARUU_FORCE_POSIX) void blockdev_sys_size(struct BlockDev *dev) diff --git a/shared/libutil/ed25519.c b/shared/libutil/ed25519.c @@ -10,25 +10,105 @@ typedef int64_t gf[16]; static const gf gf0; static const gf gf1 = {1}; -static const gf D = {0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, - 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203}; -static const gf D2 = {0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, - 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406}; -static const gf X = {0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, - 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169}; -static const gf Y = {0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, - 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666}; -static const gf I = {0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, - 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83}; -static const uint64_t L[32] = {0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, - 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10}; +static const gf D = { + 0x78a3, + 0x1359, + 0x4dca, + 0x75eb, + 0xd8ab, + 0x4141, + 0x0a4d, + 0x0070, + 0xe898, + 0x7779, + 0x4079, + 0x8cc7, + 0xfe73, + 0x2b6f, + 0x6cee, + 0x5203 +}; +static const gf D2 = { + 0xf159, + 0x26b2, + 0x9b94, + 0xebd6, + 0xb156, + 0x8283, + 0x149a, + 0x00e0, + 0xd130, + 0xeef3, + 0x80f2, + 0x198e, + 0xfce7, + 0x56df, + 0xd9dc, + 0x2406 +}; +static const gf X = { + 0xd51a, + 0x8f25, + 0x2d60, + 0xc956, + 0xa7b2, + 0x9525, + 0xc760, + 0x692c, + 0xdc5c, + 0xfdd6, + 0xe231, + 0xc0a4, + 0x53fe, + 0xcd6e, + 0x36d3, + 0x2169 +}; +static const gf Y = { + 0x6658, + 0x6666, + 0x6666, + 0x6666, + 0x6666, + 0x6666, + 0x6666, + 0x6666, + 0x6666, + 0x6666, + 0x6666, + 0x6666, + 0x6666, + 0x6666, + 0x6666, + 0x6666 +}; +static const gf I = { + 0xa0b0, + 0x4a0e, + 0x1b27, + 0xc4ee, + 0xe478, + 0xad2f, + 0x1806, + 0x2f43, + 0xd7a7, + 0x3dfb, + 0x0099, + 0x2b4d, + 0xdf0b, + 0x4fc1, + 0x2480, + 0x2b83 +}; +static const uint64_t L[32] = {0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, + 0xa2, 0xde, 0xf9, 0xde, 0x14, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10}; static int verify32(const uint8_t *x, const uint8_t *y) { uint32_t d = 0; - int i; + int i; for (i = 0; i < 32; i++) d |= x[i] ^ y[i]; @@ -48,7 +128,7 @@ static void car25519(gf o) { int64_t c; - int i; + int i; for (i = 0; i < 16; i++) { o[i] += (int64_t)1 << 16; @@ -62,7 +142,7 @@ static void sel25519(gf p, gf q, int b) { int64_t t, c = ~(b - 1); - int i; + int i; for (i = 0; i < 16; i++) { t = c & (p[i] ^ q[i]); @@ -75,7 +155,7 @@ static void pack25519(uint8_t *o, const gf n) { int i, j, b; - gf m, t; + gf m, t; for (i = 0; i < 16; i++) t[i] = n[i]; @@ -89,12 +169,12 @@ pack25519(uint8_t *o, const gf n) m[i - 1] &= 0xffff; } m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1); - b = (m[15] >> 16) & 1; + b = (m[15] >> 16) & 1; m[14] &= 0xffff; sel25519(t, m, 1 - b); } for (i = 0; i < 16; i++) { - o[2 * i] = t[i] & 0xff; + o[2 * i] = t[i] & 0xff; o[2 * i + 1] = t[i] >> 8; } } @@ -150,7 +230,7 @@ static void M(gf o, const gf a, const gf b) { int64_t t[31]; - int i, j; + int i, j; for (i = 0; i < 31; i++) t[i] = 0; @@ -174,7 +254,7 @@ S(gf o, const gf a) static void inv25519(gf o, const gf i) { - gf c; + gf c; int a; for (a = 0; a < 16; a++) @@ -191,7 +271,7 @@ inv25519(gf o, const gf i) static void pow2523(gf o, const gf i) { - gf c; + gf c; int a; for (a = 0; a < 16; a++) @@ -286,7 +366,7 @@ static void modL(uint8_t *r, int64_t x[64]) { int64_t carry; - int i, j; + int i, j; for (i = 63; i >= 32; --i) { carry = 0; @@ -316,7 +396,7 @@ static void reduce(uint8_t *r) { int64_t x[64]; - int i; + int i; for (i = 0; i < 64; i++) x[i] = (uint64_t)r[i]; @@ -375,11 +455,12 @@ expand(uint8_t d[64], const uint8_t seed[ED25519_SEED]) } void -ed25519_keypair(uint8_t pk[ED25519_PUBLIC], uint8_t sk[ED25519_SECRET], - const uint8_t seed[ED25519_SEED]) +ed25519_keypair( + uint8_t pk[ED25519_PUBLIC], uint8_t sk[ED25519_SECRET], const uint8_t seed[ED25519_SEED] +) { uint8_t d[64]; - gf p[4]; + gf p[4]; expand(d, seed); scalarbase(p, d); @@ -391,8 +472,15 @@ ed25519_keypair(uint8_t pk[ED25519_PUBLIC], uint8_t sk[ED25519_SECRET], /* sha512 of a, b and m, reduced mod L */ static void -hram(uint8_t out[64], const uint8_t *a, size_t na, const uint8_t *b, size_t nb, - const uint8_t *m, size_t n) +hram( + uint8_t out[64], + const uint8_t *a, + size_t na, + const uint8_t *b, + size_t nb, + const uint8_t *m, + size_t n +) { struct sha512 h; @@ -406,13 +494,12 @@ hram(uint8_t out[64], const uint8_t *a, size_t na, const uint8_t *b, size_t nb, } void -ed25519_sign(uint8_t sig[ED25519_SIG], const uint8_t *m, size_t n, - const uint8_t sk[ED25519_SECRET]) +ed25519_sign(uint8_t sig[ED25519_SIG], const uint8_t *m, size_t n, const uint8_t sk[ED25519_SECRET]) { uint8_t d[64], r[64], h[64]; int64_t x[64]; - gf p[4]; - int i, j; + gf p[4]; + int i, j; expand(d, sk); hram(r, d + 32, 32, NULL, 0, m, n); @@ -432,12 +519,13 @@ ed25519_sign(uint8_t sig[ED25519_SIG], const uint8_t *m, size_t n, } int -ed25519_verify(const uint8_t sig[ED25519_SIG], const uint8_t *m, size_t n, - const uint8_t pk[ED25519_PUBLIC]) +ed25519_verify( + const uint8_t sig[ED25519_SIG], const uint8_t *m, size_t n, const uint8_t pk[ED25519_PUBLIC] +) { uint8_t h[64], t[32]; - gf p[4], q[4]; - int i; + gf p[4], q[4]; + int i; /* s must be below L, or the signature is malleable */ for (i = 31; i >= 0; i--) { diff --git a/shared/libutil/filesystem_linux.c b/shared/libutil/filesystem_linux.c @@ -94,8 +94,8 @@ fs_get_info(const char *path, int fd, struct FilesystemInfo *info) if ((path ? statfs(path, &st) : fstatfs(fd, &st)) < 0) return -1; - info->id = (unsigned long long)st.f_fsid.__val[0] - | ((unsigned long long)st.f_fsid.__val[1] << 32); + info->id = + (unsigned long long)st.f_fsid.__val[0] | ((unsigned long long)st.f_fsid.__val[1] << 32); info->namelen = st.f_namelen; info->type = st.f_type; info->bsize = st.f_bsize; diff --git a/shared/libutil/fshut.c b/shared/libutil/fshut.c @@ -10,10 +10,10 @@ fshut(FILE *fp, const char *fname) int ret = 0; /* fflush() is undefined for input streams by ISO c, - * but not POSIX 2008 if you ignore ISO c overrides - * leave it unchecked and rely on the following - * functions to detect errors - */ + * but not POSIX 2008 if you ignore ISO c overrides + * leave it unchecked and rely on the following + * functions to detect errors + */ fflush(fp); if (ferror(fp) && !ret) { diff --git a/shared/libutil/getopt_posix.c b/shared/libutil/getopt_posix.c @@ -4,9 +4,10 @@ #include <unistd.h> /* the one reset posix names */ -#if !(defined(__linux__) || defined(__DragonFly__) || defined(__FreeBSD__) || defined(__NetBSD__) \ - || defined(__OpenBSD__) || defined(__APPLE__)) \ - || defined(ARUU_FORCE_POSIX) +#if !( \ + defined(__linux__) || defined(__DragonFly__) || defined(__FreeBSD__) || defined(__NetBSD__) \ + || defined(__OpenBSD__) || defined(__APPLE__) \ +) || defined(ARUU_FORCE_POSIX) void getopt_reset(void) { diff --git a/shared/libutil/kmap.c b/shared/libutil/kmap.c @@ -9,15 +9,16 @@ void kmap_path(char *buf, size_t sz, const char *dir, const char *layout, const char *variant) { - snprintf(buf, sz, "%s/%s/%s.kmap", dir ? dir : KMAP_DIR, layout, - variant && *variant ? variant : layout); + snprintf( + buf, sz, "%s/%s/%s.kmap", dir ? dir : KMAP_DIR, layout, variant && *variant ? variant : layout + ); } int kmap_words(char *line, char **w, int max) { char *r = line, *o = line; - int n = 0; + int n = 0; while (*r) { while (*r == ' ' || *r == '\t' || *r == '\r' || *r == '\n') @@ -55,8 +56,8 @@ long kmap_char(const char *s) { const unsigned char *u = (const unsigned char *)s; - long c; - int n, i; + long c; + int n, i; if (!u[0]) return -1; @@ -101,9 +102,9 @@ join(char *dst, size_t sz, char **w, int n) int kmap_read(const char *path, struct kmap *k) { - char line[1024], *w[24]; + char line[1024], *w[24]; FILE *fp; - int n, lineno = 0; + int n, lineno = 0; if (!(fp = fopen(path, "r"))) { weprintf("open %s:", path); @@ -127,15 +128,14 @@ kmap_read(const char *path, struct kmap *k) } else if (!strcmp(w[0], "name")) { if (!k->name[0]) join(k->name, sizeof(k->name), w + 1, n - 1); - } - else if (!strcmp(w[0], "level3") && n > 1) + } else if (!strcmp(w[0], "level3") && n > 1) k->level3_ralt = !strcmp(w[1], "ralt"); else if (!strcmp(w[0], "key") && n > 2) { struct kmap_key *key; - int i; + int i; k->keys = ereallocarray(k->keys, k->nkeys + 1, sizeof(*k->keys)); - key = &k->keys[k->nkeys++]; + key = &k->keys[k->nkeys++]; memset(key, 0, sizeof(*key)); copy(key->name, sizeof(key->name), w[1]); for (i = 2; i < n; i++) { @@ -148,7 +148,7 @@ kmap_read(const char *path, struct kmap *k) } } else if (!strcmp(w[0], "modmap") && n > 2 && k->nmodmaps < 8) { struct kmap_modmap *m = &k->modmaps[k->nmodmaps++]; - int i; + int i; copy(m->mod, sizeof(m->mod), w[1]); for (i = 2, m->n = 0; i < n && m->n < 16; i++) @@ -157,7 +157,7 @@ kmap_read(const char *path, struct kmap *k) struct kmap_compose *c; k->compose = ereallocarray(k->compose, k->ncompose + 1, sizeof(*k->compose)); - c = &k->compose[k->ncompose++]; + c = &k->compose[k->ncompose++]; copy(c->dead, sizeof(c->dead), w[1]); copy(c->base, sizeof(c->base), w[2]); copy(c->result, sizeof(c->result), w[3]); @@ -197,9 +197,9 @@ xkb_sym(FILE *fp, const char *s) static int put_file(FILE *fp, const char *dir, const char *name) { - char path[4096], buf[8192]; + char path[4096], buf[8192]; size_t n; - FILE *in; + FILE *in; snprintf(path, sizeof(path), "%s/xkb/%s", dir, name); if (!(in = fopen(path, "r"))) { @@ -243,12 +243,18 @@ put_group(FILE *fp, int g, const struct kmap_key *key, int *first) // what a key is in group g: the last option that names it, the layout of g, // right alt as level 3 where the layout reaches it so, the pc keyboard static const struct kmap_key * -key_in(const char *name, int g, const struct kmap *pc, const struct kmap *maps, - const struct kmap *opts, int nopts) +key_in( + const char *name, + int g, + const struct kmap *pc, + const struct kmap *maps, + const struct kmap *opts, + int nopts +) { static const struct kmap_key lv3 = {"RALT", {"ISO_Level3_Shift"}, 1, 0, "ONE_LEVEL"}; - const struct kmap_key *key; - int o; + const struct kmap_key *key; + int o; for (o = nopts - 1; o >= 0; o--) if ((key = find_key(&opts[o], name))) @@ -261,15 +267,23 @@ key_in(const char *name, int g, const struct kmap *pc, const struct kmap *maps, } int -kmap_write_xkb(FILE *fp, const char *dir, const struct kmap *pc, const struct kmap *maps, int n, - const struct kmap *opts, int nopts) +kmap_write_xkb( + FILE *fp, + const char *dir, + const struct kmap *pc, + const struct kmap *maps, + int n, + const struct kmap *opts, + int nopts +) { const char **names = NULL; - size_t i, j, nnames = 0; - int g, m, s; + size_t i, j, nnames = 0; + int g, m, s; fputs("xkb_keymap {\n", fp); - if (put_file(fp, dir, "keycodes.xkb") || put_file(fp, dir, "types.xkb") || put_file(fp, dir, "compat.xkb")) + if (put_file(fp, dir, "keycodes.xkb") || put_file(fp, dir, "types.xkb") + || put_file(fp, dir, "compat.xkb")) return -1; fputs("xkb_symbols \"kmap\" {\n", fp); for (g = 0; g < n; g++) { @@ -280,14 +294,14 @@ kmap_write_xkb(FILE *fp, const char *dir, const struct kmap *pc, const struct km fputs("\";\n", fp); } // every key the pc keyboard, a layout or an option names, once -#define ADD(km) \ - for (i = 0; i < (km)->nkeys; i++) { \ - for (j = 0; j < nnames && strcmp(names[j], (km)->keys[i].name); j++) \ - ; \ - if (j == nnames) { \ - names = ereallocarray(names, nnames + 1, sizeof(*names)); \ - names[nnames++] = (km)->keys[i].name; \ - } \ +#define ADD(km) \ + for (i = 0; i < (km)->nkeys; i++) { \ + for (j = 0; j < nnames && strcmp(names[j], (km)->keys[i].name); j++) \ + ; \ + if (j == nnames) { \ + names = ereallocarray(names, nnames + 1, sizeof(*names)); \ + names[nnames++] = (km)->keys[i].name; \ + } \ } ADD(pc); for (g = 0; g < n; g++) @@ -306,7 +320,7 @@ kmap_write_xkb(FILE *fp, const char *dir, const struct kmap *pc, const struct km continue; fprintf(fp, "\tkey <%s> { ", names[j]); for (g = 0; g <= last; g++) { - const struct kmap_key *key = key_in(names[j], g, pc, maps, opts, nopts); + const struct kmap_key *key = key_in(names[j], g, pc, maps, opts, nopts); static const struct kmap_key none = {"", {"NoSymbol"}, 1, 0, ""}; put_group(fp, g, key ? key : &none, &first); @@ -331,19 +345,19 @@ static const struct { const char *name; int evdev, pc, hid; } codes[] = { - {"TLDE", 41, 41, 53}, {"AE01", 2, 2, 30}, {"AE02", 3, 3, 31}, {"AE03", 4, 4, 32}, - {"AE04", 5, 5, 33}, {"AE05", 6, 6, 34}, {"AE06", 7, 7, 35}, {"AE07", 8, 8, 36}, - {"AE08", 9, 9, 37}, {"AE09", 10, 10, 38}, {"AE10", 11, 11, 39}, {"AE11", 12, 12, 45}, - {"AE12", 13, 13, 46}, {"AE13", 124, 125, 137}, {"AD01", 16, 16, 20}, {"AD02", 17, 17, 26}, - {"AD03", 18, 18, 8}, {"AD04", 19, 19, 21}, {"AD05", 20, 20, 23}, {"AD06", 21, 21, 28}, - {"AD07", 22, 22, 24}, {"AD08", 23, 23, 12}, {"AD09", 24, 24, 18}, {"AD10", 25, 25, 19}, - {"AD11", 26, 26, 47}, {"AD12", 27, 27, 48}, {"BKSL", 43, 43, 49}, {"AC01", 30, 30, 4}, - {"AC02", 31, 31, 22}, {"AC03", 32, 32, 7}, {"AC04", 33, 33, 9}, {"AC05", 34, 34, 10}, - {"AC06", 35, 35, 11}, {"AC07", 36, 36, 13}, {"AC08", 37, 37, 14}, {"AC09", 38, 38, 15}, - {"AC10", 39, 39, 51}, {"AC11", 40, 40, 52}, {"LSGT", 86, 86, 100}, {"AB01", 44, 44, 29}, - {"AB02", 45, 45, 27}, {"AB03", 46, 46, 6}, {"AB04", 47, 47, 25}, {"AB05", 48, 48, 5}, - {"AB06", 49, 49, 17}, {"AB07", 50, 50, 16}, {"AB08", 51, 51, 54}, {"AB09", 52, 52, 55}, - {"AB10", 53, 53, 56}, {"AB11", 89, 115, 135}, {"SPCE", 57, 57, 44}, {"KPDL", 83, 83, 99}, + {"TLDE", 41, 41, 53}, {"AE01", 2, 2, 30}, {"AE02", 3, 3, 31}, {"AE03", 4, 4, 32}, + {"AE04", 5, 5, 33}, {"AE05", 6, 6, 34}, {"AE06", 7, 7, 35}, {"AE07", 8, 8, 36}, + {"AE08", 9, 9, 37}, {"AE09", 10, 10, 38}, {"AE10", 11, 11, 39}, {"AE11", 12, 12, 45}, + {"AE12", 13, 13, 46}, {"AE13", 124, 125, 137}, {"AD01", 16, 16, 20}, {"AD02", 17, 17, 26}, + {"AD03", 18, 18, 8}, {"AD04", 19, 19, 21}, {"AD05", 20, 20, 23}, {"AD06", 21, 21, 28}, + {"AD07", 22, 22, 24}, {"AD08", 23, 23, 12}, {"AD09", 24, 24, 18}, {"AD10", 25, 25, 19}, + {"AD11", 26, 26, 47}, {"AD12", 27, 27, 48}, {"BKSL", 43, 43, 49}, {"AC01", 30, 30, 4}, + {"AC02", 31, 31, 22}, {"AC03", 32, 32, 7}, {"AC04", 33, 33, 9}, {"AC05", 34, 34, 10}, + {"AC06", 35, 35, 11}, {"AC07", 36, 36, 13}, {"AC08", 37, 37, 14}, {"AC09", 38, 38, 15}, + {"AC10", 39, 39, 51}, {"AC11", 40, 40, 52}, {"LSGT", 86, 86, 100}, {"AB01", 44, 44, 29}, + {"AB02", 45, 45, 27}, {"AB03", 46, 46, 6}, {"AB04", 47, 47, 25}, {"AB05", 48, 48, 5}, + {"AB06", 49, 49, 17}, {"AB07", 50, 50, 16}, {"AB08", 51, 51, 54}, {"AB09", 52, 52, 55}, + {"AB10", 53, 53, 56}, {"AB11", 89, 115, 135}, {"SPCE", 57, 57, 44}, {"KPDL", 83, 83, 99}, }; int @@ -362,21 +376,21 @@ static const struct { const char *name; long c; } named[] = { - {"space", ' '}, - {"nobreakspace", 0xa0}, - {"combining_grave", 0x300}, - {"combining_acute", 0x301}, - {"combining_tilde", 0x303}, - {"combining_hook", 0x309}, - {"combining_belowdot", 0x323}, + {"space", ' '}, + {"nobreakspace", 0xa0}, + {"combining_grave", 0x300}, + {"combining_acute", 0x301}, + {"combining_tilde", 0x303}, + {"combining_hook", 0x309}, + {"combining_belowdot", 0x323}, }; long kmap_unicode(const char *s) { - long c = kmap_char(s); + long c = kmap_char(s); size_t i; - char *end; + char *end; if (c >= 0) return c; @@ -396,14 +410,18 @@ static const struct { const char *name; long c; } deads[] = { - {"dead_grave", 0x300}, {"dead_acute", 0x301}, {"dead_circumflex", 0x302}, - {"dead_tilde", 0x303}, {"dead_macron", 0x304}, {"dead_breve", 0x306}, - {"dead_abovedot", 0x307}, {"dead_diaeresis", 0x308}, {"dead_hook", 0x309}, - {"dead_abovering", 0x30a}, {"dead_doubleacute", 0x30b}, {"dead_caron", 0x30c}, - {"dead_doublegrave", 0x30f}, {"dead_invertedbreve", 0x311}, {"dead_abovecomma", 0x313}, - {"dead_abovereversedcomma", 0x314}, {"dead_horn", 0x31b}, {"dead_belowdot", 0x323}, - {"dead_belowcomma", 0x326}, {"dead_cedilla", 0x327}, {"dead_ogonek", 0x328}, - {"dead_belowmacron", 0x331}, {"dead_stroke", 0x335}, {"dead_iota", 0x345}, + {"dead_grave", 0x300}, {"dead_acute", 0x301}, + {"dead_circumflex", 0x302}, {"dead_tilde", 0x303}, + {"dead_macron", 0x304}, {"dead_breve", 0x306}, + {"dead_abovedot", 0x307}, {"dead_diaeresis", 0x308}, + {"dead_hook", 0x309}, {"dead_abovering", 0x30a}, + {"dead_doubleacute", 0x30b}, {"dead_caron", 0x30c}, + {"dead_doublegrave", 0x30f}, {"dead_invertedbreve", 0x311}, + {"dead_abovecomma", 0x313}, {"dead_abovereversedcomma", 0x314}, + {"dead_horn", 0x31b}, {"dead_belowdot", 0x323}, + {"dead_belowcomma", 0x326}, {"dead_cedilla", 0x327}, + {"dead_ogonek", 0x328}, {"dead_belowmacron", 0x331}, + {"dead_stroke", 0x335}, {"dead_iota", 0x345}, }; long diff --git a/shared/libutil/kmap_fbsd.c b/shared/libutil/kmap_fbsd.c @@ -33,20 +33,30 @@ static const char *ttys[] = {"/dev/ttyv0", "/dev/console"}; // the console's accent keys and the combining characters kmap names them by, // with the spacing character the accent map gives each static const struct { - long comb; - u_int key; - u_int spacing; + long comb; + u_int key; + u_int spacing; } accs[] = { - {0x300, DGRA, '`'}, {0x301, DACU, 0xb4}, {0x302, DCIR, '^'}, {0x303, DTIL, '~'}, - {0x304, DMAC, 0xaf}, {0x306, DBRE, 0x2d8}, {0x307, DDOT, 0x2d9}, {0x308, DDIA, 0xa8}, - {0x335, DSLA, '/'}, {0x30a, DRIN, 0xb0}, {0x327, DCED, 0xb8}, {0x30b, DDAC, 0x2dd}, - {0x328, DOGO, 0x2db}, {0x30c, DCAR, 0x2c7}, + {0x300, DGRA, '`'}, + {0x301, DACU, 0xb4}, + {0x302, DCIR, '^'}, + {0x303, DTIL, '~'}, + {0x304, DMAC, 0xaf}, + {0x306, DBRE, 0x2d8}, + {0x307, DDOT, 0x2d9}, + {0x308, DDIA, 0xa8}, + {0x335, DSLA, '/'}, + {0x30a, DRIN, 0xb0}, + {0x327, DCED, 0xb8}, + {0x30b, DDAC, 0x2dd}, + {0x328, DOGO, 0x2db}, + {0x30c, DCAR, 0x2c7}, }; static int acc_of(const char *s) { - long c = kmap_dead(s); + long c = kmap_dead(s); size_t i; for (i = 0; c >= 0 && i < LEN(accs); i++) @@ -60,7 +70,7 @@ static void put(struct keyent_t *e, int state, const char *s) { long c; - int a; + int a; e->spcl &= ~(0x80 >> state); if ((a = acc_of(s)) >= 0) { @@ -81,10 +91,10 @@ int kmap_load_console(const struct kmap *k) { static const int states[4] = {S_PLAIN, S_SHIFT, S_ALT, S_ALT_SHIFT}; - keymap_t *km = ecalloc(1, sizeof(*km)); - accentmap_t *am = ecalloc(1, sizeof(*am)); - size_t i, j; - int fd = -1, code, l, rc = -1; + keymap_t *km = ecalloc(1, sizeof(*km)); + accentmap_t *am = ecalloc(1, sizeof(*am)); + size_t i, j; + int fd = -1, code, l, rc = -1; if (ioctl(0, GIO_KEYMAP, km) == 0) fd = 0; @@ -99,8 +109,8 @@ kmap_load_console(const struct kmap *k) } for (i = 0; i < k->nkeys; i++) { const struct kmap_key *key = &k->keys[i]; - struct keyent_t *e; - long c0; + struct keyent_t *e; + long c0; if ((code = kmap_code(key->name, KMAP_PC)) < 0 || code >= km->n_keys) continue; @@ -127,14 +137,14 @@ kmap_load_console(const struct kmap *k) memset(am, 0, sizeof(*am)); am->n_accs = NUM_DEADKEYS; for (j = 0; j < k->ncompose; j++) { - const struct kmap_compose *cp = &k->compose[j]; - long base = kmap_unicode(cp->base), res = kmap_unicode(cp->result); - int a = acc_of(cp->dead), n; - struct acc_t *acc; + const struct kmap_compose *cp = &k->compose[j]; + long base = kmap_unicode(cp->base), res = kmap_unicode(cp->result); + int a = acc_of(cp->dead), n; + struct acc_t *acc; if (a < 0 || base < 0 || res < 0) continue; - acc = &am->acc[accs[a].key - F_ACC]; + acc = &am->acc[accs[a].key - F_ACC]; acc->accchar = accs[a].spacing; for (n = 0; n < NUM_ACCENTCHARS && acc->map[n][0]; n++) ; diff --git a/shared/libutil/kmap_linux.c b/shared/libutil/kmap_linux.c @@ -59,28 +59,28 @@ static const struct { int type, value; unsigned diacr; } deads[] = { - {0x300, KT_DEAD, 0, '`'}, {0x301, KT_DEAD, 1, '\''}, {0x302, KT_DEAD, 2, '^'}, - {0x303, KT_DEAD, 3, '~'}, {0x308, KT_DEAD, 4, '"'}, {0x327, KT_DEAD, 5, ','}, - {0x304, KT_DEAD2, 0xaf, 0xaf}, {0x30a, KT_DEAD2, 0xb0, 0xb0}, {0x30c, KT_DEAD2, 0xa6, 0xa6}, - {0x306, KT_DEAD2, 0xa4, 0xa4}, {0x307, KT_DEAD2, 0xb7, 0xb7}, {0x30b, KT_DEAD2, 0xa8, 0xa8}, - {0x328, KT_DEAD2, 0xb8, 0xb8}, {0x323, KT_DEAD2, 0xa7, 0xa7}, {0x309, KT_DEAD2, 0xbf, 0xbf}, - {0x31b, KT_DEAD2, 0xb9, 0xb9}, {0x335, KT_DEAD2, 0xac, 0xac}, {0x326, KT_DEAD2, 0xb5, 0xb5}, - {0x331, KT_DEAD2, 0xb3, 0xb3}, {0x345, KT_DEAD2, 0xbd, 0xbd}, + {0x300, KT_DEAD, 0, '`'}, {0x301, KT_DEAD, 1, '\''}, {0x302, KT_DEAD, 2, '^'}, + {0x303, KT_DEAD, 3, '~'}, {0x308, KT_DEAD, 4, '"'}, {0x327, KT_DEAD, 5, ','}, + {0x304, KT_DEAD2, 0xaf, 0xaf}, {0x30a, KT_DEAD2, 0xb0, 0xb0}, {0x30c, KT_DEAD2, 0xa6, 0xa6}, + {0x306, KT_DEAD2, 0xa4, 0xa4}, {0x307, KT_DEAD2, 0xb7, 0xb7}, {0x30b, KT_DEAD2, 0xa8, 0xa8}, + {0x328, KT_DEAD2, 0xb8, 0xb8}, {0x323, KT_DEAD2, 0xa7, 0xa7}, {0x309, KT_DEAD2, 0xbf, 0xbf}, + {0x31b, KT_DEAD2, 0xb9, 0xb9}, {0x335, KT_DEAD2, 0xac, 0xac}, {0x326, KT_DEAD2, 0xb5, 0xb5}, + {0x331, KT_DEAD2, 0xb3, 0xb3}, {0x345, KT_DEAD2, 0xbd, 0xbd}, }; static char *ttys[] = { - ARUU_LINUX_PATH_PROC "/self/fd/0", - ARUU_PATH_DEVCONSOLE, - ARUU_PATH_DEVTTY, - "/dev/tty0", + ARUU_LINUX_PATH_PROC "/self/fd/0", + ARUU_PATH_DEVCONSOLE, + ARUU_PATH_DEVTTY, + "/dev/tty0", }; static int console(void) { - char type; + char type; size_t i; - int fd; + int fd; for (i = 0; i < LEN(ttys); i++) { if ((fd = open(ttys[i], O_RDWR)) < 0 && (fd = open(ttys[i], O_RDONLY)) < 0) @@ -96,7 +96,7 @@ console(void) static int dead_of(const char *s) { - long c = kmap_dead(s); + long c = kmap_dead(s); size_t i; for (i = 0; c >= 0 && i < LEN(deads); i++) @@ -112,7 +112,7 @@ static unsigned short value_of(const char *s, int caps) { long c; - int d; + int d; if ((d = dead_of(s)) >= 0) return K(deads[d].type, deads[d].value); @@ -145,16 +145,16 @@ int kmap_load_console(const struct kmap *k) { // the console has four of a key's levels - static const int tables[4] = {0, T_SHIFT, T_ALTGR, T_SHIFT | T_ALTGR}; + static const int tables[4] = {0, T_SHIFT, T_ALTGR, T_SHIFT | T_ALTGR}; struct kbdiacrsuc acc; - int fd = console(), rc = 0, l, code; - size_t i, j; + int fd = console(), rc = 0, l, code; + size_t i, j; if (fd < 0) return -1; for (i = 0; i < k->nkeys; i++) { const struct kmap_key *key = &k->keys[i]; - long c0; + long c0; if ((code = kmap_code(key->name, KMAP_EVDEV)) < 0) continue; @@ -183,9 +183,9 @@ kmap_load_console(const struct kmap *k) // one fewer than its table holds memset(&acc, 0, sizeof(acc)); for (j = 0; j < k->ncompose && acc.cnt < LEN(acc.d) - 1; j++) { - const struct kmap_compose *cp = &k->compose[j]; - long base = kmap_unicode(cp->base), res = kmap_unicode(cp->result); - int d = dead_of(cp->dead), used = 0; + const struct kmap_compose *cp = &k->compose[j]; + long base = kmap_unicode(cp->base), res = kmap_unicode(cp->result); + int d = dead_of(cp->dead), used = 0; if (d < 0 || base < 0 || res < 0) continue; @@ -194,8 +194,8 @@ kmap_load_console(const struct kmap *k) used = !strcmp(k->keys[i].sym[l], cp->dead); if (!used) continue; - acc.d[acc.cnt].diacr = deads[d].diacr; - acc.d[acc.cnt].base = base; + acc.d[acc.cnt].diacr = deads[d].diacr; + acc.d[acc.cnt].base = base; acc.d[acc.cnt].result = res; acc.cnt++; } diff --git a/shared/libutil/kmap_posix.c b/shared/libutil/kmap_posix.c @@ -4,8 +4,8 @@ /* a system kmap has no console backend for: the layouts are still listed * and written for xkb, only the console is not set */ -#if !(defined(__linux__) || defined(__NetBSD__) || defined(__OpenBSD__) || \ - defined(__FreeBSD__)) || defined(ARUU_FORCE_POSIX) +#if !(defined(__linux__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__FreeBSD__)) \ + || defined(ARUU_FORCE_POSIX) int kmap_load_console(const struct kmap *k) { diff --git a/shared/libutil/kmap_wscons.c b/shared/libutil/kmap_wscons.c @@ -51,10 +51,10 @@ kmap_load_console(const struct kmap *k) { struct wskbd_map_data md; struct wscons_keymap *map; - enum kmap_codes scheme; - u_int type; - size_t i; - int fd = -1, code, l, rc = 0; + enum kmap_codes scheme; + u_int type; + size_t i; + int fd = -1, code, l, rc = 0; for (i = 0; i < LEN(kbds) && fd < 0; i++) fd = open(kbds[i], O_RDWR); @@ -64,17 +64,17 @@ kmap_load_console(const struct kmap *k) } // a usb keyboard's keys are numbered by hid usage, a pc keyboard's by // its scancodes - scheme = ioctl(fd, WSKBDIO_GTYPE, &type) == 0 && type == WSKBD_TYPE_USB ? KMAP_HID : KMAP_PC; - map = ecalloc(KS_NUMKEYCODES, sizeof(*map)); + scheme = ioctl(fd, WSKBDIO_GTYPE, &type) == 0 && type == WSKBD_TYPE_USB ? KMAP_HID : KMAP_PC; + map = ecalloc(KS_NUMKEYCODES, sizeof(*map)); md.maplen = KS_NUMKEYCODES; - md.map = map; + md.map = map; if (ioctl(fd, WSKBDIO_GETMAP, &md) != 0) { weprintf("WSKBDIO_GETMAP:"); goto fail; } for (i = 0; i < k->nkeys; i++) { const struct kmap_key *key = &k->keys[i]; - keysym_t s[4]; + keysym_t s[4]; if ((code = kmap_code(key->name, scheme)) < 0 || (u_int)code >= md.maplen) continue; @@ -91,7 +91,7 @@ kmap_load_console(const struct kmap *k) if (k->level3_ralt) { code = scheme == KMAP_HID ? HID_RALT : PC_RALT; if ((u_int)code < md.maplen) { - map[code].command = KS_voidSymbol; + map[code].command = KS_voidSymbol; map[code].group1[0] = map[code].group1[1] = KS_Mode_switch; map[code].group2[0] = map[code].group2[1] = KS_Mode_switch; } diff --git a/shared/libutil/passwd_linux.c b/shared/libutil/passwd_linux.c @@ -56,10 +56,10 @@ update_shadow(const char *name, const char *newhash) } /* fgetspent(fp) reads from the stream we already opened above; - * getspent() reads an implicit global shadow stream that musl - * never actually backs with this (or any) file and always - * returns null for, silently turning every update into a - * "no matching entry" failure */ + * getspent() reads an implicit global shadow stream that musl + * never actually backs with this (or any) file and always + * returns null for, silently turning every update into a + * "no matching entry" failure */ while ((spw = fgetspent(fp))) { cur = *spw; if (strcmp(cur.sp_namp, name) == 0) { diff --git a/shared/libutil/passwd_posix.c b/shared/libutil/passwd_posix.c @@ -5,9 +5,10 @@ #include <stddef.h> /* no shadow file: the hash is the one the passwd entry holds */ -#if !(defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \ - || defined(__DragonFly__)) \ - || defined(ARUU_FORCE_POSIX) +#if !( \ + defined(__linux__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) \ + || defined(__DragonFly__) \ +) || defined(ARUU_FORCE_POSIX) char * pw_shadow_hash(const char *name) { diff --git a/shared/libutil/proc_linux.c b/shared/libutil/proc_linux.c @@ -114,7 +114,7 @@ parsestatus(pid_t pid, struct procstatus *pstatus) if (n <= 0) return -1; buf[n] = '\0'; - off = strstr(buf, "Uid:"); + off = strstr(buf, "Uid:"); if (!off) return -1; sscanf(off, "Uid: %u %u", &pstatus->uid, &pstatus->euid); @@ -179,7 +179,7 @@ proc_info(pid_t pid, struct procinfo *p) { struct procstat ps; struct procstatus st; - long hz = sysconf(_SC_CLK_TCK); + long hz = sysconf(_SC_CLK_TCK); long page = sysconf(_SC_PAGESIZE); if (parsestat(pid, &ps) < 0) @@ -214,9 +214,9 @@ proc_info(pid_t pid, struct procinfo *p) int proc_each(proc_fn *fn, void *arg) { - struct dirent *e; + struct dirent *e; struct procinfo p; - DIR *d = opendir(ARUU_LINUX_PATH_PROC); + DIR *d = opendir(ARUU_LINUX_PATH_PROC); if (!d) return -1; diff --git a/shared/libutil/session_linux.c b/shared/libutil/session_linux.c @@ -35,7 +35,7 @@ session_record(const char *user) usr.ut_time = time(NULL); /* utmp: a live table, so this overwrites/appends the one entry for - * this session */ + * this session */ fp = fopen(UTMP_PATH, "r+"); if (fp) { fseek(fp, 0, SEEK_END); @@ -44,7 +44,7 @@ session_record(const char *user) } /* wtmp: an ever-growing append-only log of the same record, just - * opened differently */ + * opened differently */ fp = fopen(WTMP_PATH, "a"); if (fp) { fwrite(&usr, sizeof(usr), 1, fp); diff --git a/shared/libutil/signify.c b/shared/libutil/signify.c @@ -37,9 +37,9 @@ struct sigfile { static int randombytes(uint8_t *buf, size_t n) { - int fd = open("/dev/urandom", O_RDONLY); + int fd = open("/dev/urandom", O_RDONLY); ssize_t r; - size_t got = 0; + size_t got = 0; if (fd < 0) { weprintf("open /dev/urandom:"); @@ -59,9 +59,9 @@ randombytes(uint8_t *buf, size_t n) static int writefile(const char *path, const char *comment, const void *blob, size_t n, int mode) { - char b64[256]; + char b64[256]; FILE *fp; - int fd; + int fd; if ((fd = open(path, O_WRONLY | O_CREAT | O_EXCL, mode)) < 0) { weprintf("open %s:", path); @@ -80,17 +80,16 @@ writefile(const char *path, const char *comment, const void *blob, size_t n, int static int readfile(const char *path, void *blob, size_t n) { - char line[512]; + char line[512]; FILE *fp; - int ok; + int ok; if (!(fp = fopen(path, "r"))) { weprintf("open %s:", path); return -1; } - ok = fgets(line, sizeof(line), fp) && !strncmp(line, COMMENT, strlen(COMMENT)) && - fgets(line, sizeof(line), fp) && - base64_decode(blob, n, line, strlen(line)) == (long)n; + ok = fgets(line, sizeof(line), fp) && !strncmp(line, COMMENT, strlen(COMMENT)) + && fgets(line, sizeof(line), fp) && base64_decode(blob, n, line, strlen(line)) == (long)n; fclose(fp); if (!ok) { weprintf("%s: not a signify file of the right kind\n", path); @@ -107,7 +106,7 @@ static void checksum(uint8_t out[8], const uint8_t sk[ED25519_SECRET]) { struct sha512 h; - uint8_t d[SHA512_DIGEST_LENGTH]; + uint8_t d[SHA512_DIGEST_LENGTH]; sha512_init(&h); sha512_update(&h, sk, ED25519_SECRET); @@ -120,13 +119,13 @@ signify_generate(const char *pubpath, const char *secpath, const char *comment) { struct pubfile pub; struct secfile sec; - uint8_t seed[ED25519_SEED]; - char c[200]; - int rc; + uint8_t seed[ED25519_SEED]; + char c[200]; + int rc; memset(&sec, 0, sizeof(sec)); - if (randombytes(seed, sizeof(seed)) || randombytes(sec.keynum, sizeof(sec.keynum)) || - randombytes(sec.salt, sizeof(sec.salt))) + if (randombytes(seed, sizeof(seed)) || randombytes(sec.keynum, sizeof(sec.keynum)) + || randombytes(sec.salt, sizeof(sec.salt))) return -1; ed25519_keypair(pub.pk, sec.sk, seed); memcpy(sec.alg, "Ed", 2); @@ -162,7 +161,7 @@ int signify_read_sec(const char *path, struct signify_sec *out) { struct secfile f; - uint8_t sum[8]; + uint8_t sum[8]; if (readfile(path, &f, sizeof(f))) return -1; @@ -182,11 +181,16 @@ signify_read_sec(const char *path, struct signify_sec *out) } int -signify_sign(const struct signify_sec *sec, const uint8_t *m, size_t n, const char *pubname, - const char *sigpath) +signify_sign( + const struct signify_sec *sec, + const uint8_t *m, + size_t n, + const char *pubname, + const char *sigpath +) { struct sigfile f; - char c[300]; + char c[300]; memcpy(f.alg, "Ed", 2); memcpy(f.keynum, sec->keynum, 8); diff --git a/shared/libutil/sysinfo_linux.c b/shared/libutil/sysinfo_linux.c @@ -30,15 +30,15 @@ static const struct { const char *name; size_t off; } meminfo_fields[] = { - {"MemTotal:", offsetof(struct MemInfo, total) }, - {"MemFree:", offsetof(struct MemInfo, free) }, + {"MemTotal:", offsetof(struct MemInfo, total)}, + {"MemFree:", offsetof(struct MemInfo, free)}, {"MemAvailable:", offsetof(struct MemInfo, available)}, - {"Shmem:", offsetof(struct MemInfo, shared) }, - {"Buffers:", offsetof(struct MemInfo, buffers) }, - {"Cached:", offsetof(struct MemInfo, cached) }, - {"SReclaimable:", offsetof(struct MemInfo, cached) }, - {"SwapTotal:", offsetof(struct MemInfo, totalswap)}, - {"SwapFree:", offsetof(struct MemInfo, freeswap) }, + {"Shmem:", offsetof(struct MemInfo, shared)}, + {"Buffers:", offsetof(struct MemInfo, buffers)}, + {"Cached:", offsetof(struct MemInfo, cached)}, + {"SReclaimable:", offsetof(struct MemInfo, cached)}, + {"SwapTotal:", offsetof(struct MemInfo, totalswap)}, + {"SwapFree:", offsetof(struct MemInfo, freeswap)}, }; /* sysinfo(2) knows nothing of the page cache, so this is the fallback */ diff --git a/shared/libutil/timer_posix.c b/shared/libutil/timer_posix.c @@ -47,7 +47,7 @@ timer_set(int i, const struct timespec *ts) } if (clock_gettime(CLOCK_MONOTONIC, &now) < 0) return -1; - t = nsec(&now) + nsec(ts); + t = nsec(&now) + nsec(ts); deadline[i].tv_sec = t / 1000000000LL; deadline[i].tv_nsec = t % 1000000000LL; return 0; diff --git a/shared/libutil/wexec.c b/shared/libutil/wexec.c @@ -669,11 +669,11 @@ wexecve_self(const char *path, char *const *argv, char *const *envp) } } - oldenv = environ; + oldenv = environ; environ = (char **)envp; fflush(stdout); fflush(stderr); - ret = wexec_call_builtin(base, argv); + ret = wexec_call_builtin(base, argv); environ = oldenv; fflush(stdout); fflush(stderr); diff --git a/shared/net.h b/shared/net.h @@ -20,9 +20,9 @@ enum NetInterfaceFlag { NET_IF_ALLMULTI = 0x00000100, NET_IF_MULTICAST = 0x00000200, // no device behind it (a bridge, a tunnel); unknown is not virtual - NET_IF_VIRTUAL = 0x00000400, + NET_IF_VIRTUAL = 0x00000400, // a radio; unknown is not wireless - NET_IF_WIRELESS = 0x00000800, + NET_IF_WIRELESS = 0x00000800, }; struct NetStats { @@ -86,6 +86,7 @@ int net_tun_persist(int, int); int net_tun_owner(int, uid_t); int net_bind_device(int, const char *); int net_get_hwaddr(int, const char *, unsigned char *, size_t); -int net_set_lease(const char *, const unsigned char[4], const unsigned char[4], const unsigned char[4]); +int +net_set_lease(const char *, const unsigned char[4], const unsigned char[4], const unsigned char[4]); #endif diff --git a/shared/paths.h b/shared/paths.h @@ -73,10 +73,10 @@ #define ARUU_PATH_DEFPATH ARUU_PATH_BIN ":" ARUU_PATH_USR_BIN #endif -#define ARUU_LINUX_PATH_PROC "/proc" -#define ARUU_LINUX_PATH_SYS "/sys" +#define ARUU_LINUX_PATH_PROC "/proc" +#define ARUU_LINUX_PATH_SYS "/sys" #ifndef ARUU_LINUX_PATH_PROC_MOUNTS -#define ARUU_LINUX_PATH_PROC_MOUNTS ARUU_LINUX_PATH_PROC "/mounts" +#define ARUU_LINUX_PATH_PROC_MOUNTS ARUU_LINUX_PATH_PROC "/mounts" #endif #define ARUU_LINUX_PATH_PROC_PARTITIONS ARUU_LINUX_PATH_PROC "/partitions" #define ARUU_LINUX_PATH_PROC_MEMINFO ARUU_LINUX_PATH_PROC "/meminfo" diff --git a/shared/proc.h b/shared/proc.h @@ -55,18 +55,18 @@ int pidfile(const char *file); * proc_posix.c says a kernel has no backend yet, so ps, pgrep and pkill * are the same code everywhere and a port is one file */ struct procinfo { - pid_t pid, ppid, pgid, sid; - uid_t ruid, euid; - gid_t rgid, egid; - unsigned tty_major, tty_minor; /* 0 0 for no terminal */ - char state; /* R S D Z T, as ps prints it */ - long nice, priority; - long nthreads; - time_t start; /* when it began, seconds since the epoch */ - unsigned long cpu; /* seconds of cpu time, system and user */ - unsigned long vsize_kib; - long rss_kib; - char comm[256]; + pid_t pid, ppid, pgid, sid; + uid_t ruid, euid; + gid_t rgid, egid; + unsigned tty_major, tty_minor; /* 0 0 for no terminal */ + char state; /* R S D Z T, as ps prints it */ + long nice, priority; + long nthreads; + time_t start; /* when it began, seconds since the epoch */ + unsigned long cpu; /* seconds of cpu time, system and user */ + unsigned long vsize_kib; + long rss_kib; + char comm[256]; }; typedef int proc_fn(const struct procinfo *p, void *arg); diff --git a/shared/session.h b/shared/session.h @@ -21,10 +21,10 @@ typedef int session_fn(const struct SessionEntry *e, void *arg); void session_record(const char *user); /* fn for every record of a utmp or wtmp file, until it returns non zero. * -1 with errno set when the file cannot be read */ -int session_each(const char *path, session_fn *fn, void *arg); +int session_each(const char *path, session_fn *fn, void *arg); /* a getty starting on line forgets every record of it */ void session_clear(const char *line); /* the last login of uid, from a lastlog file the caller opened */ -int session_lastlog(FILE *fp, uid_t uid, struct SessionEntry *e); +int session_lastlog(FILE *fp, uid_t uid, struct SessionEntry *e); #endif diff --git a/shared/signify.h b/shared/signify.h @@ -33,11 +33,15 @@ int signify_read_sec(const char *path, struct signify_sec *out); /* the signature of m into sigpath, its comment naming the public key pubname to check it with. 0 when written */ -int signify_sign(const struct signify_sec *sec, const uint8_t *m, size_t n, - const char *pubname, const char *sigpath); +int signify_sign( + const struct signify_sec *sec, + const uint8_t *m, + size_t n, + const char *pubname, + const char *sigpath +); /* 0 when sigpath is pub's signature of m, -1 said otherwise */ -int signify_verify(const struct signify_pub *pub, const uint8_t *m, size_t n, - const char *sigpath); +int signify_verify(const struct signify_pub *pub, const uint8_t *m, size_t n, const char *sigpath); #endif diff --git a/shared/sysinfo.h b/shared/sysinfo.h @@ -10,7 +10,7 @@ struct MemInfo { unsigned long long available; /* free plus what the kernel can take back */ unsigned long long shared; unsigned long long buffers; - unsigned long long cached; /* page cache and reclaimable slab */ + unsigned long long cached; /* page cache and reclaimable slab */ unsigned long long totalswap; unsigned long long freeswap; }; diff --git a/shared/util.h b/shared/util.h @@ -110,8 +110,8 @@ void apathmax(char **, long *); long estrtol(const char *, int); unsigned long estrtoul(const char *, int); #undef explicit_bzero -void explicit_bzero(void *, size_t); -void recurse_dir(const char *, void (*)(const char *)); +void explicit_bzero(void *, size_t); +void recurse_dir(const char *, void (*)(const char *)); void devtotty(int, int *, int *); int ttytostr(int, int, char *, size_t); const char *ttyconsole(void);