diff --git a/contract_linked_name_info_test.go b/contract_linked_name_info_test.go new file mode 100644 index 0000000..7999f21 --- /dev/null +++ b/contract_linked_name_info_test.go @@ -0,0 +1,115 @@ +package erofs_test + +import ( + "fmt" + "io/fs" + "testing" + "time" + + "github.com/forkcloser/erofs" + "github.com/forkcloser/erofs/internal/corpus" +) + +// describe is what an info says: its name, and the file. +func describe(t *testing.T, info fs.FileInfo) string { + t.Helper() + + st, ok := info.Sys().(*erofs.Stat) + if !ok { + t.Fatalf("Sys is %T, want *erofs.Stat", info.Sys()) + } + + return fmt.Sprintf( + "%s: %d bytes, %v, %d, %d links, uid %d, xattrs %v", + info.Name(), info.Size(), info.Mode(), info.ModTime().Unix(), st.Nlink, st.UID, st.Xattrs, + ) +} + +// TestContractAFilesSecondNameReadsAsTheFile: before Close as after, every +// name of a file answers with the file, and with the name asked: the entry +// a listing gives, Stat, and the info of the file opened. A listing used to +// give a second name an entry of no size, with the mode the file had when +// it was linked and no time, and Stat of a second name answered the first. +func TestContractAFilesSecondNameReadsAsTheFile(t *testing.T) { + t.Parallel() + + out := &testBuffer{} + w := erofs.Create(out, erofs.WithBuildTime(corpus.BuildTime, 0)) + writeFile(t, w, "/d/a", []byte("twelve bytes")) + + call := func(err error) { + t.Helper() + + if err != nil { + t.Fatal(err) + } + } + + // What the file is, set after it got its second name, through either. + when := time.Unix(1_600_000_000, 0) + + call(w.Link("/d/a", "/d/b")) + call(w.Chmod("/d/a", 0o600)) + call(w.Chown("/d/b", 7, 8)) + call(w.Chtimes("/d/a", when, when)) + call(w.Setxattr("/d/b", "user.k", "v")) + + want := map[string]string{ + "a": "a: 12 bytes, -rw-------, 1600000000, 2 links, uid 7, xattrs map[user.k:v]", + "b": "b: 12 bytes, -rw-------, 1600000000, 2 links, uid 7, xattrs map[user.k:v]", + } + + check := func(how, name string, info fs.FileInfo, err error) { + t.Helper() + + if err != nil { + t.Errorf("%s of %s: %v", how, name, err) + + return + } + + if got := describe(t, info); got != want[name] { + t.Errorf("%s of %s says\n %s; want\n %s", how, name, got, want[name]) + } + } + + judge := func(when string, fsys fs.FS, dir string) { + t.Helper() + + entries, err := fs.ReadDir(fsys, dir) + if err != nil || len(entries) != 2 { + t.Fatalf("%s, the listing: %d entries, %v; want two", when, len(entries), err) + } + + for _, e := range entries { + name := e.Name() + if e.Type() != 0 { + t.Errorf("%s, the listing gives %s the type %v; want a regular file's", when, name, e.Type()) + } + + info, err := e.Info() + check(when+", the listing's entry", name, info, err) + + info, err = fs.Stat(fsys, dir+"/"+name) + check(when+", Stat", name, info, err) + + f, err := fsys.Open(dir + "/" + name) + if err != nil { + t.Errorf("%s, Open(%s): %v", when, name, err) + + continue + } + + info, err = f.Stat() + check(when+", the open file", name, info, err) + + if err := f.Close(); err != nil { + t.Errorf("%s, Close(%s): %v", when, name, err) + } + } + } + + judge("before Close", w, "/d") + call(w.Close()) + judge("after Close", openWithDevices(t, out.Bytes()), "d") +} diff --git a/contract_writer_removal_test.go b/contract_writer_removal_test.go new file mode 100644 index 0000000..7134372 --- /dev/null +++ b/contract_writer_removal_test.go @@ -0,0 +1,512 @@ +package erofs_test + +import ( + "errors" + "fmt" + "io/fs" + "maps" + "math/rand/v2" + "path" + "runtime" + "slices" + "strconv" + "strings" + "testing" + "testing/fstest" + + "github.com/forkcloser/erofs" + "github.com/forkcloser/erofs/internal/corpus" +) + +// modelNode is one name of the tree a sequence of Writer calls should leave: +// a directory, or a file by the number of its inode, which its other names +// share and its content is made of. +type modelNode struct { + dir bool + inode int +} + +// modelTree applies the calls of one random sequence to a Writer and to a +// map of what they should leave. +type modelTree struct { + t *testing.T + w *erofs.Writer + nodes map[string]modelNode + next int + log []string +} + +func (m *modelTree) failf(format string, args ...any) { + m.t.Helper() + m.t.Fatalf("%s\nafter:\n %s", fmt.Sprintf(format, args...), strings.Join(m.log, "\n ")) +} + +func (m *modelTree) under(dir string) []string { + var names []string + + for p := range m.nodes { + if strings.HasPrefix(p, dir+"/") { + names = append(names, p) + } + } + + return names +} + +// pick is one of the names for which keep holds, in an order that does not +// depend on the map's. +func (m *modelTree) pick(rnd *rand.Rand, keep func(string, modelNode) bool) (string, bool) { + var names []string + + for p, n := range m.nodes { + if keep(p, n) { + names = append(names, p) + } + } + + if len(names) == 0 { + return "", false + } + + slices.Sort(names) + + return names[rnd.IntN(len(names))], true +} + +// step makes one call, chosen by rnd among those the tree allows. +func (m *modelTree) step(rnd *rand.Rand) { + m.t.Helper() + + isDir := func(_ string, n modelNode) bool { return n.dir } + isFile := func(_ string, n modelNode) bool { return !n.dir } + whatever := func(string, modelNode) bool { return true } + + // A new name under a directory there is, or under the root. + fresh := func() string { + parent, ok := m.pick(rnd, isDir) + if !ok || rnd.IntN(4) == 0 { + parent = "" + } + + for { + if p := parent + "/n" + strconv.Itoa(rnd.IntN(6)); m.nodes[p] == (modelNode{}) { + return p + } + + parent += "/n" + strconv.Itoa(rnd.IntN(6)) + if m.nodes[parent] == (modelNode{}) { + return parent + } + + if !m.nodes[parent].dir { + return "" + } + } + } + + switch rnd.IntN(8) { + case 0, 1: + p := fresh() + if p == "" { + return + } + + m.next++ + m.log = append(m.log, fmt.Sprintf("Create(%s) inode %d", p, m.next)) + writeFile(m.t, m.w, p, []byte("content of "+strconv.Itoa(m.next))) + m.nodes[p] = modelNode{inode: m.next} + case 2: + p := fresh() + if p == "" { + return + } + + m.log = append(m.log, "Mkdir("+p+")") + + if err := m.w.Mkdir(p, 0o755); err != nil { + m.failf("Mkdir(%s): %v", p, err) + } + + m.nodes[p] = modelNode{dir: true} + case 3, 4: + old, ok := m.pick(rnd, isFile) + p := fresh() + + if !ok || p == "" { + return + } + + m.log = append(m.log, fmt.Sprintf("Link(%s, %s)", old, p)) + + if err := m.w.Link(old, p); err != nil { + m.failf("Link(%s, %s): %v", old, p, err) + } + + m.nodes[p] = m.nodes[old] + case 5, 6: + p, ok := m.pick(rnd, whatever) + if !ok { + return + } + + m.log = append(m.log, "Remove("+p+")") + + err := m.w.Remove(p) + + switch full := len(m.under(p)) > 0; { + case full && !errors.Is(err, erofs.ErrDirNotEmpty): + m.failf("Remove(%s), a directory with entries: %v; want ErrDirNotEmpty", p, err) + case !full && err != nil: + m.failf("Remove(%s): %v", p, err) + case !full: + delete(m.nodes, p) + } + default: + p, ok := m.pick(rnd, whatever) + if !ok { + return + } + + m.log = append(m.log, "RemoveAll("+p+")") + + if err := m.w.RemoveAll(p); err != nil { + m.failf("RemoveAll(%s): %v", p, err) + } + + for _, under := range m.under(p) { + delete(m.nodes, under) + } + + delete(m.nodes, p) + } +} + +// check closes the Writer and holds the image to the tree: its names, each +// file's content, one inode for the names that share one and for no others, +// and the link counts that follow. +func (m *modelTree) check(out *testBuffer) { + m.t.Helper() + + if err := m.w.Close(); err != nil { + m.failf("Close: %v", err) + } + + fsys := openWithDevices(m.t, out.Bytes()) + + got := map[string]modelNode{} + inodes := map[uint64]int{} + + err := fs.WalkDir(fsys, ".", func(p string, d fs.DirEntry, err error) error { + if err != nil || p == "." { + return err + } + + info, err := d.Info() + if err != nil { + return err + } + + st, ok := info.Sys().(*erofs.Stat) + if !ok { + m.failf("%s: Sys is %T", p, info.Sys()) + } + + want := m.nodes["/"+p] + + if d.IsDir() { + got["/"+p] = modelNode{dir: true} + + subdirs := 0 + + for q, n := range m.nodes { + if n.dir && path.Dir(q) == "/"+p { + subdirs++ + } + } + + if int(st.Nlink) != 2+subdirs { + m.failf("%s has a link count of %d; want %d", p, st.Nlink, 2+subdirs) + } + + return nil + } + + content, rerr := fs.ReadFile(fsys, p) + if rerr != nil { + return rerr + } + + inode, _ := strconv.Atoi(strings.TrimPrefix(string(content), "content of ")) + got["/"+p] = modelNode{inode: inode} + + if seen, ok := inodes[st.Ino]; ok && seen != inode { + m.failf("%s: inode %d of the image holds the content of %d and of %d", p, st.Ino, seen, inode) + } + + inodes[st.Ino] = inode + + names := 0 + + for _, n := range m.nodes { + if !n.dir && n.inode == want.inode { + names++ + } + } + + if int(st.Nlink) != names { + m.failf("%s has a link count of %d; want %d", p, st.Nlink, names) + } + + return nil + }) + if err != nil { + m.failf("the walk of the image: %v", err) + } + + if !maps.Equal(got, m.nodes) { + m.failf("the image holds %v; want %v", got, m.nodes) + } + + // One inode of the image for each of the tree's. + files := map[int]bool{} + + for _, n := range m.nodes { + if !n.dir { + files[n.inode] = true + } + } + + if len(inodes) != len(files) { + m.failf("the image holds %d inodes of files; want %d", len(inodes), len(files)) + } +} + +// TestContractWriterLeavesWhatItsCallsLeave: random sequences of Create, +// Mkdir, Link, Remove and RemoveAll, each call one the tree allows, and the +// image is the tree they leave: no removed name back, none lost, a removed +// first name's file under its other names, the link counts of what is left. +func TestContractWriterLeavesWhatItsCallsLeave(t *testing.T) { + t.Parallel() + + for seed := range uint64(600) { + rnd := rand.New(rand.NewPCG(seed, 0x6c696e6b)) + + out := &testBuffer{} + m := &modelTree{ + t: t, + w: erofs.Create(out, erofs.WithBuildTime(corpus.BuildTime, 0)), + nodes: map[string]modelNode{}, + log: []string{fmt.Sprintf("seed %d", seed)}, + } + + for range 10 + rnd.IntN(60) { + m.step(rnd) + } + + m.check(out) + } +} + +// namesOf closes w and lists what its image holds, directories with a +// slash after them. +func namesOf(t *testing.T, w *erofs.Writer, out *testBuffer) []string { + t.Helper() + + if err := w.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + + var names []string + + err := fs.WalkDir(openWithDevices(t, out.Bytes()), ".", func(p string, d fs.DirEntry, err error) error { + if err != nil || p == "." { + return err + } + + if d.IsDir() { + p += "/" + } + + names = append(names, p) + + return nil + }) + if err != nil { + t.Fatal(err) + } + + return names +} + +// TestContractRemovingWhatACopyPlaced: a name is removed as any other after +// a copy wrote over it, after a marker sifted its directory around it, and +// after it stopped being a directory: the removal takes that name and no +// other, and what is made afterwards is there. +func TestContractRemovingWhatACopyPlaced(t *testing.T) { + t.Parallel() + + file := func(content string) *fstest.MapFile { return &fstest.MapFile{Data: []byte(content)} } + + for name, tc := range map[string]struct { + layers []fstest.MapFS + merge bool + remove []string + want []string + }{ + "a name a later copy wrote over": { + layers: []fstest.MapFS{ + {"a": file("a"), "b": file("b"), "c": file("c"), "d": file("d")}, + {"c": file("again")}, + }, + remove: []string{"/c"}, + want: []string{"a", "b", "d", "new"}, + }, + "a name its layer's opaque marker spared": { + layers: []fstest.MapFS{ + {"d/a": file("a"), "d/b": file("b"), "d/c": file("c")}, + {"d/-kept": file("kept"), "d/.wh..wh..opq": file(""), "d/z": file("z")}, + }, + merge: true, + remove: []string{"/d/-kept"}, + want: []string{"d/", "d/z", "new"}, + }, + "a directory spared with its marker's layer, what it held before gone": { + layers: []fstest.MapFS{ + {"d/-sub/old": file("old"), "d/-sub/older": file("older"), "d/b": file("b")}, + {"d/-sub/mine": file("mine"), "d/.wh..wh..opq": file("")}, + }, + merge: true, + remove: []string{"/d/-sub/mine", "/d/-sub"}, + want: []string{"d/", "new"}, + }, + "a name that stopped being a directory": { + layers: []fstest.MapFS{ + {"a/b": file("b"), "a/d/e": file("e"), "keep": file("keep")}, + {"a": file("now a file")}, + }, + remove: []string{"/a"}, + want: []string{"keep", "new"}, + }, + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + + out := &testBuffer{} + w := erofs.Create(out, erofs.WithBuildTime(corpus.BuildTime, 0)) + + for i, layer := range tc.layers { + var opts []erofs.CopyOpt + if tc.merge && i > 0 { + opts = append(opts, erofs.Merge()) + } + + if err := w.CopyFrom(layer, opts...); err != nil { + t.Fatalf("the copy of layer %d: %v", i, err) + } + } + + for _, p := range tc.remove { + if err := w.Remove(p); err != nil { + t.Fatalf("Remove(%s): %v", p, err) + } + } + + writeFile(t, w, "/new", []byte("new")) + + if got := namesOf(t, w, out); !slices.Equal(got, tc.want) { + t.Errorf("the image holds %v; want %v", got, tc.want) + } + }) + } +} + +// heapAfter is the heap in use once what can be collected is. +func heapAfter() int64 { + var stats runtime.MemStats + + //revive:disable-next-line:call-to-gc what a Writer holds is measured from a collected heap + runtime.GC() + runtime.ReadMemStats(&stats) + + return int64(stats.HeapInuse) +} + +// TestContractWriterHoldsNothingOfARemovedName: a name made and removed over +// and over costs a Writer nothing that stays: a directory, a file's other +// name beside one that stays, and a directory removed with what it holds. +// Before, every removed name stayed in its directory's list for the Writer's +// life: 300,000 rounds of the first shape held about 90 MiB, and as many +// names made and then removed about 108 MiB, where the map and the list +// that held them now keep 16. +// +//nolint:paralleltest // measures the process's heap in use; a parallel test's live heap would count against the bound +func TestContractWriterHoldsNothingOfARemovedName(t *testing.T) { + const ( + rounds = 300_000 + bound = 8 << 20 + // What a map and a list keep of the most they held at once, which + // neither gives back: far under the names themselves. + boundAfterAll = 32 << 20 + ) + + for _, shape := range []struct { + name string + rounds int + bound int64 + round func(w *erofs.Writer) error + }{ + {"a directory made and removed", rounds, bound, func(w *erofs.Writer) error { + return errors.Join(w.Mkdir("/d/x", 0o755), w.Remove("/d/x")) + }}, + {"a file's other name made and removed", rounds, bound, func(w *erofs.Writer) error { + return errors.Join(w.Link("/d/f", "/d/x"), w.Remove("/d/x")) + }}, + {"a directory removed with what it holds", rounds, bound, func(w *erofs.Writer) error { + return errors.Join(w.Mkdir("/d/x", 0o755), w.Mkdir("/d/x/y", 0o755), w.Link("/d/f", "/d/x/l"), w.RemoveAll("/d/x")) + }}, + // Not one name over and over: as many at once, then each removed, + // the directory that held them staying. + {"every name made, then each removed", 1, boundAfterAll, func(w *erofs.Writer) error { + for i := range rounds { + if err := w.Mkdir("/d/x"+strconv.Itoa(i), 0o755); err != nil { + return err + } + } + + for i := range rounds { + if err := w.Remove("/d/x" + strconv.Itoa(i)); err != nil { + return err + } + } + + return nil + }}, + } { + w := erofs.Create(&testBuffer{}, erofs.WithBuildTime(corpus.BuildTime, 0)) + writeFile(t, w, "/d/f", []byte("content")) + + if err := w.Link("/d/f", "/d/stays"); err != nil { + t.Fatal(err) + } + + before := heapAfter() + + for range shape.rounds { + if err := shape.round(w); err != nil { + t.Fatalf("%s: %v", shape.name, err) + } + } + + if grown := heapAfter() - before; grown > shape.bound { + t.Errorf( + "%s, %d names: the heap in use grew by %d MiB; want under %d", + shape.name, + rounds, + grown>>20, + shape.bound>>20, + ) + } + + runtime.KeepAlive(w) + } +} diff --git a/mkfs.go b/mkfs.go index 03a2ddb..53ea98b 100644 --- a/mkfs.go +++ b/mkfs.go @@ -646,12 +646,8 @@ func (fsys *Writer) Remove(name string) error { return err } - if e.mode&disk.StatTypeMask == disk.StatTypeDir { - for _, c := range e.children { - if !c.removed { - return &fs.PathError{Op: "remove", Path: name, Err: ErrDirNotEmpty} - } - } + if len(e.children) > 0 { + return &fs.PathError{Op: "remove", Path: name, Err: ErrDirNotEmpty} } fsys.unlinkEntry(e) @@ -1087,11 +1083,7 @@ func (fsys *Writer) Stat(name string) (fs.FileInfo, error) { return nil, &fs.PathError{Op: "stat", Path: name, Err: fs.ErrNotExist} } - if e.linkTo != nil { - e = e.linkTo // hardlink: stat the shared inode - } - - return &writerFileInfo{entry: e}, nil + return infoOf(e), nil } // Open opens the named file for reading. For regular files, the file must @@ -1133,7 +1125,7 @@ func (fsys *Writer) Open(name string) (fs.File, error) { switch { case size == 0: case e.holedInDataFile: - return &readFile{entry: e, reader: io.NewSectionReader( + return &readFile{entry: e, path: name, reader: io.NewSectionReader( chunkedData{fsys.dataFile, e.chunks, int64(fsys.resolveBlockSize())}, 0, size, )}, nil case e.reopen != nil: @@ -1142,23 +1134,27 @@ func (fsys *Writer) Open(name string) (fs.File, error) { return nil, fmt.Errorf("mkfs: open %s where it was copied from: %w", name, err) } - return &readFile{entry: e, reader: &copiedBytes{src: src, left: size}, source: src}, nil + return &readFile{entry: e, path: name, reader: &copiedBytes{src: src, left: size}, source: src}, nil case e.metadataOnly || e.directData != nil: // Neither the spool nor the data file holds it: reading them // at this entry's offset, zero, reads another file's bytes. return nil, fmt.Errorf("mkfs: open %s: its data is with its source, which gave no way to open it again: %w", name, ErrNotImplemented) case fsys.dataFile != nil: - return &readFile{entry: e, reader: io.NewSectionReader(fsys.dataFile, e.dataStartOff, size)}, nil + return &readFile{ + entry: e, + path: name, + reader: io.NewSectionReader(fsys.dataFile, e.dataStartOff, size), + }, nil case fsys.spool != nil: - return &readFile{entry: e, reader: io.NewSectionReader(fsys.spool, e.dataStartOff, size)}, nil + return &readFile{entry: e, path: name, reader: io.NewSectionReader(fsys.spool, e.dataStartOff, size)}, nil } - return &readFile{entry: e}, nil + return &readFile{entry: e, path: name}, nil default: // Symlinks, devices, etc.: stat-only, no readable data. - return &readFile{entry: e}, nil + return &readFile{entry: e, path: name}, nil } } @@ -1298,9 +1294,13 @@ type fsEntry struct { linkTo *fsEntry extraLinks uint32 - // Tree structure — maintained during add/remove. + // Tree structure — maintained during add/remove. children holds the + // entries under a directory and none that was removed; at is the + // entry's place among its parent's, which lets a removed name leave + // the list at once (detach). parent *fsEntry children []*fsEntry + at int // placed is the Writer's copySeq when the entry was placed, or placed // again by a later layer. placed uint64 @@ -1315,7 +1315,10 @@ type fsEntry struct { // Close (directData) or for good (metadataOnly). reopen func() (fs.File, error) - removed bool // true if removed by a whiteout in a merge layer + // removed: the name is gone from the tree. The entry may still be held: + // by the list of its inode's other names, by a copy's link map, by a + // caller's handle. + removed bool metadataOnly bool // from a metadata-only CopyFrom; use chunk-based layout } @@ -1496,12 +1499,25 @@ func (fi *entryFileInfo) ModTime() time.Time { return fi.info.ModTime() } func (fi *entryFileInfo) IsDir() bool { return fi.info.IsDir() } func (fi *entryFileInfo) Sys() any { return fi.sys } -// writerFileInfo implements fs.FileInfo for an fsEntry. +// writerFileInfo implements fs.FileInfo for an fsEntry: name is the name +// the info was asked or listed under, and entry the one that holds the +// file, which for a file's second name is another's (linkTo). type writerFileInfo struct { entry *fsEntry + name string +} + +// infoOf is the info of the file e names, under e's name. +func infoOf(e *fsEntry) *writerFileInfo { + fi := &writerFileInfo{entry: e, name: path.Base(e.path)} + if e.linkTo != nil { + fi.entry = e.linkTo + } + + return fi } -func (fi *writerFileInfo) Name() string { return path.Base(fi.entry.path) } +func (fi *writerFileInfo) Name() string { return fi.name } // Size reports e.size as fs.FileInfo spells it. // #nosec G115 -- e.size fits int64: File counts it in an int64, and add and copyFromImage bound it @@ -1564,7 +1580,7 @@ func (e *fsEntry) linkCount() uint32 { var subdirs uint32 for _, c := range e.children { - if !c.removed && c.mode&disk.StatTypeMask == disk.StatTypeDir { + if c.mode&disk.StatTypeMask == disk.StatTypeDir { subdirs++ } } @@ -1577,14 +1593,16 @@ func (e *fsEntry) linkCount() uint32 { // readFile implements fs.File for reading back a finalized file's data. type readFile struct { - entry *fsEntry + entry *fsEntry + // path is the name the file was opened under, one of the entry's. + path string reader io.Reader // nil for empty files or non-regular types source io.Closer // the file a copied entry was opened again as, or nil closed bool } func (f *readFile) Stat() (fs.FileInfo, error) { - return &writerFileInfo{entry: f.entry}, nil + return &writerFileInfo{entry: f.entry, name: path.Base(f.path)}, nil } func (f *readFile) Read(p []byte) (int, error) { @@ -1608,7 +1626,7 @@ func (f *readFile) Close() error { if f.source != nil { if err := f.source.Close(); err != nil { - return fmt.Errorf("mkfs: close %s where it was copied from: %w", f.entry.path, err) + return fmt.Errorf("mkfs: close %s where it was copied from: %w", f.path, err) } } @@ -1657,7 +1675,7 @@ type readDir struct { } func (d *readDir) Stat() (fs.FileInfo, error) { - return &writerFileInfo{entry: d.entry}, nil + return infoOf(d.entry), nil } func (d *readDir) Read([]byte) (int, error) { @@ -1713,10 +1731,6 @@ func (d *readDir) ReadDir(n int) ([]fs.DirEntry, error) { func (d *readDir) collectChildren() []fs.DirEntry { children := make([]fs.DirEntry, 0, len(d.entry.children)) for _, e := range d.entry.children { - if e.removed { - continue - } - children = append(children, &dirEntry{entry: e}) } @@ -1736,7 +1750,7 @@ func (de *dirEntry) Name() string { return path.Base(de.entry.path) } func (de *dirEntry) IsDir() bool { return de.entry.mode&disk.StatTypeMask == disk.StatTypeDir } func (de *dirEntry) Type() fs.FileMode { return disk.EroFSModeToGoFileMode(de.entry.mode).Type() } -func (de *dirEntry) Info() (fs.FileInfo, error) { return &writerFileInfo{entry: de.entry}, nil } +func (de *dirEntry) Info() (fs.FileInfo, error) { return infoOf(de.entry), nil } // addRegular adds the regular file at fpath (p once normalized) whose data // the source did not hand over in be: as chunk indexes in metadata-only @@ -2246,11 +2260,23 @@ func (fsys *Writer) addChild(e *fsEntry) { } e.parent = parent + e.at = len(parent.children) e.placed = fsys.copySeq parent.children = append(parent.children, e) fsys.byPath[e.path] = e } +// detach takes e out of its parent's children: the last child takes its +// place, the order of the list being no one's (ReadDir and Close sort). +func detach(e *fsEntry) { + siblings := e.parent.children + last := len(siblings) - 1 + + siblings[e.at], siblings[last].at = siblings[last], e.at + siblings[last] = nil + e.parent.children = siblings[:last] +} + // removeTree removes an entry and all its descendants, whoever placed them: // RemoveAll's. func (fsys *Writer) removeTree(p string) { @@ -2301,24 +2327,37 @@ func (fsys *Writer) dropEarlier(e *fsEntry, self bool) { fsys.unlinkEntry(e) } + fsys.dropEarlierUnder(e) +} + +// dropEarlierUnder removes what earlier layers placed under e. It walks +// e's children, so a child it removes keeps its place in the list until the +// walk is done and the list is sifted: detached there, it would move the +// last child under the walk. +func (fsys *Writer) dropEarlierUnder(e *fsEntry) { for _, c := range e.children { - if !c.removed { - fsys.dropEarlier(c, true) + if c.placed != fsys.copySeq { + fsys.dropName(c) } + + fsys.dropEarlierUnder(c) + } + + e.children = slices.DeleteFunc(e.children, func(c *fsEntry) bool { return c.removed }) + for i, c := range e.children { + c.at = i } } -// removeSubtree recursively marks all descendants of e as removed. +// removeSubtree removes every descendant of e, which keeps none: the walk +// is over e's children, so none is detached, and the list goes whole. func (fsys *Writer) removeSubtree(e *fsEntry) { for _, c := range e.children { - if !c.removed { - fsys.unlinkEntry(c) - - if c.mode&disk.StatTypeMask == disk.StatTypeDir { - fsys.removeSubtree(c) - } - } + fsys.dropName(c) + fsys.removeSubtree(c) } + + e.children = nil } // unlinkEntry drops one name. It is the single place an entry becomes @@ -2331,6 +2370,14 @@ func (fsys *Writer) removeSubtree(e *fsEntry) { // carry the inode (data, metadata, chunks) and the rest are // repointed at it, so nothing downstream ever sees a dangling linkTo. func (fsys *Writer) unlinkEntry(e *fsEntry) { + fsys.dropName(e) + detach(e) +} + +// dropName is unlinkEntry less the entry's place among its parent's +// children, for a walk over those children, which empties or sifts the list +// itself once it is done. +func (fsys *Writer) dropName(e *fsEntry) { e.removed = true delete(fsys.byPath, e.path) @@ -2379,9 +2426,9 @@ func (fsys *Writer) promoteAlias(target *fsEntry) { // The heir takes over the inode wholesale, keeping only its own name // and place in the tree. - heirPath, heirParent := heir.path, heir.parent + heirPath, heirParent, heirAt := heir.path, heir.parent, heir.at *heir = *target - heir.path, heir.parent = heirPath, heirParent + heir.path, heir.parent, heir.at = heirPath, heirParent, heirAt heir.linkTo = nil heir.removed = false @@ -2438,7 +2485,16 @@ func (fsys *Writer) aliased(target, alias *fsEntry) { fsys.aliases = make(map[*fsEntry][]*fsEntry) } - fsys.aliases[target] = append(fsys.aliases[target], alias) + // unlinkEntry leaves a removed name in the list, and the list is all + // that holds its entry then: once the removed outnumber the live they + // go, at a cost each removal has paid for, so that a name linked and + // removed over and over keeps nothing. + names := fsys.aliases[target] + if len(names) > 2*int(target.extraLinks) { + names = slices.DeleteFunc(names, func(a *fsEntry) bool { return a.removed }) + } + + fsys.aliases[target] = append(names, alias) target.extraLinks++ } @@ -2464,19 +2520,17 @@ func (fsys *Writer) placeEntry(fe *fsEntry) *fsEntry { return fe } - savedParent := existing.parent - savedChildren := existing.children // A directory that stops being one takes its entries with it: under a // file they would stay registered, answer Stat, and be written by Close // as the entries of something that has none. if existing.mode&disk.StatTypeMask == disk.StatTypeDir && fe.mode&disk.StatTypeMask != disk.StatTypeDir { fsys.removeSubtree(existing) - - savedChildren = nil } + savedParent, savedAt, savedChildren := existing.parent, existing.at, existing.children + *existing = *fe - existing.parent = savedParent + existing.parent, existing.at = savedParent, savedAt existing.children = savedChildren existing.placed = fsys.copySeq @@ -2534,7 +2588,7 @@ func (fsys *Writer) buildErofsTree() *erofsEntry { var childDirs uint32 for _, c := range cur.fs.children { - if !c.removed && c.mode&disk.StatTypeMask == disk.StatTypeDir { + if c.mode&disk.StatTypeMask == disk.StatTypeDir { childDirs++ } } @@ -2549,10 +2603,6 @@ func (fsys *Writer) buildErofsTree() *erofsEntry { } for _, c := range cur.fs.children { - if c.removed { - continue - } - if c.linkTo != nil { // Dirent-only alias: name here, inode on the target // (nid/file type copied once the target has one).