diff --git a/classparser/jdk_constructor_code.bundle.zst b/classparser/jdk_constructor_code.bundle.zst new file mode 100644 index 00000000..6590fa3a Binary files /dev/null and b/classparser/jdk_constructor_code.bundle.zst differ diff --git a/classparser/jdk_constructor_code.go b/classparser/jdk_constructor_code.go index b59f0830..900ee09a 100644 --- a/classparser/jdk_constructor_code.go +++ b/classparser/jdk_constructor_code.go @@ -1,16 +1,22 @@ package javaclassparser import ( - "archive/zip" - "bytes" "crypto/sha256" _ "embed" + "encoding/binary" "encoding/hex" "encoding/json" - "fmt" - "io" "strings" "sync" + + "github.com/klauspost/compress/zstd" +) + +const ( + constructorBundleMagic = "JJCC0001" + constructorBundleMaxManifest = 4 << 20 + constructorBundleMaxChunkRaw = 4 << 20 + constructorBundleMaxClassSize = 2 << 20 ) type constructorCodeProfile struct { @@ -23,6 +29,33 @@ type constructorCodeDocument struct { Profiles []constructorCodeProfile `json:"profiles"` } +type constructorBundleEntry struct { + SHA256 string `json:"s"` + Chunk int `json:"c"` + Offset uint32 `json:"o"` + Length uint32 `json:"l"` +} + +type constructorBundleProfile struct { + Release int `json:"release"` + ArchiveSHA256 string `json:"archive_sha256"` + Classes map[string]constructorBundleEntry `json:"classes"` +} + +type constructorBundleIndex struct { + Schema int `json:"schema"` + Profiles []constructorBundleProfile `json:"profiles"` +} + +type constructorChunkMeta struct { + compOffset uint32 + compLen uint32 + rawLen uint32 + once sync.Once + raw []byte + ok bool +} + // Original classfiles, extracted from the exact platform archives pinned by // the declaration catalog. They are read only as metadata/bytecode: never // loaded by a JVM or used as emitted archive-owned classes. Selection by the @@ -37,19 +70,25 @@ type constructorCodeDocument struct { // when their constructors observe THIS. Independent declaration/reference // provenance pins every indexed class; code membership is never an effect proof. // -//go:embed jdk_constructor_code.zip -var jdkConstructorCodeZIP []byte +// Keep the reviewed ZIP source for regeneration and provenance checks. Only its +// deterministic chunked-zstd representation is linked into applications. +// +//go:generate go run ../tools/compressjdk -constructor-zip jdk_constructor_code.zip +//go:embed jdk_constructor_code.bundle.zst +var jdkConstructorCodeBundle []byte var jdkConstructorCode struct { - once sync.Once - entries map[int]map[string]*zip.File - hashes map[int]map[string]string + once sync.Once + chunks []constructorChunkMeta + chunkData []byte + entries map[int]map[string]constructorBundleEntry + hashes map[int]map[string]string } // jdkConstructorNameCandidate is a conservative namespace gate over the // embedded constructor corpus. A same-package identity probe for an application // class (for example com/example/String) can never resolve here, and must not -// pay the one-time 11 MB catalog + zip index cost. +// pay the one-time catalog + bundle index cost. func jdkConstructorNameCandidate(name string) bool { switch { case strings.HasPrefix(name, "java/"), strings.HasPrefix(name, "javax/"), @@ -62,81 +101,129 @@ func jdkConstructorNameCandidate(name string) bool { return false } +func decodeConstructorZstd(src []byte, maxDecoded int) ([]byte, error) { + decoder, err := zstd.NewReader(nil, + zstd.WithDecoderConcurrency(1), + zstd.WithDecoderLowmem(true), + zstd.WithDecoderMaxMemory(uint64(maxDecoded)*2), + ) + if err != nil { + return nil, err + } + defer decoder.Close() + raw, err := decoder.DecodeAll(src, nil) + if err != nil || len(raw) > maxDecoded { + return nil, err + } + return raw, nil +} + +func jdkConstructorChunkBytes(chunkIdx int) ([]byte, bool) { + if chunkIdx < 0 || chunkIdx >= len(jdkConstructorCode.chunks) { + return nil, false + } + chunk := &jdkConstructorCode.chunks[chunkIdx] + chunk.once.Do(func() { + start := uint64(chunk.compOffset) + end := start + uint64(chunk.compLen) + if end > uint64(len(jdkConstructorCode.chunkData)) || chunk.rawLen > constructorBundleMaxChunkRaw { + return + } + raw, err := decodeConstructorZstd(jdkConstructorCode.chunkData[start:end], int(chunk.rawLen)) + if err != nil || uint32(len(raw)) != chunk.rawLen { + return + } + chunk.raw = raw + chunk.ok = true + }) + return chunk.raw, chunk.ok +} + func jdkConstructorClassBytes(name string, release int) ([]byte, bool) { if !jdkConstructorNameCandidate(name) { return nil, false } jdkConstructorCode.once.Do(func() { - zr, err := zip.NewReader(bytes.NewReader(jdkConstructorCodeZIP), int64(len(jdkConstructorCodeZIP))) - if err != nil { + buf := jdkConstructorCodeBundle + if len(buf) < 16 || string(buf[:8]) != constructorBundleMagic { return } - files := map[string]*zip.File{} - for _, entry := range zr.File { - if files[entry.Name] != nil { - return - } - files[entry.Name] = entry - } - manifest := files["manifest.json"] - if manifest == nil || manifest.UncompressedSize64 > 1<<20 { + manifestCompLen := binary.LittleEndian.Uint32(buf[8:12]) + chunkCount := binary.LittleEndian.Uint32(buf[12:16]) + if manifestCompLen == 0 || chunkCount == 0 || chunkCount > 4096 { return } - f, err := manifest.Open() - if err != nil { + tableEnd := uint64(16) + uint64(chunkCount)*12 + manifestEnd := tableEnd + uint64(manifestCompLen) + if manifestEnd > uint64(len(buf)) { return } - data, err := io.ReadAll(io.LimitReader(f, 1<<20)) - f.Close() - if err != nil { - return + chunks := make([]constructorChunkMeta, chunkCount) + chunkData := buf[manifestEnd:] + for i := uint32(0); i < chunkCount; i++ { + off := 16 + int(i)*12 + compOffset := binary.LittleEndian.Uint32(buf[off : off+4]) + compLen := binary.LittleEndian.Uint32(buf[off+4 : off+8]) + rawLen := binary.LittleEndian.Uint32(buf[off+8 : off+12]) + if uint64(compOffset)+uint64(compLen) > uint64(len(chunkData)) || rawLen > constructorBundleMaxChunkRaw { + return + } + chunks[i].compOffset = compOffset + chunks[i].compLen = compLen + chunks[i].rawLen = rawLen } - var document constructorCodeDocument - if json.Unmarshal(data, &document) != nil || document.Schema != 1 { + manifestRaw, err := decodeConstructorZstd(buf[tableEnd:manifestEnd], constructorBundleMaxManifest) + if err != nil || len(manifestRaw) == 0 { return } - // Runtime integrity is verified against this embedded manifest and the - // class bytes themselves. The cross-check against the invocation catalog - // is a build/release consistency contract and runs in a pure-Go test, so a - // tiny decompile no longer decodes the 11 MB invocation catalog merely to - // prove that the two embedded assets agree. - if len(document.Profiles) == 0 { + var idx constructorBundleIndex + if json.Unmarshal(manifestRaw, &idx) != nil || idx.Schema != 1 || len(idx.Profiles) == 0 { return } - entries := map[int]map[string]*zip.File{} - hashes := map[int]map[string]string{} - for _, profile := range document.Profiles { + entries := make(map[int]map[string]constructorBundleEntry, len(idx.Profiles)) + hashes := make(map[int]map[string]string, len(idx.Profiles)) + for _, profile := range idx.Profiles { if entries[profile.Release] != nil || len(profile.ArchiveSHA256) != 64 || len(profile.Classes) == 0 { return } - table := map[string]*zip.File{} - for name, hash := range profile.Classes { - digest, err := hex.DecodeString(hash) - entry := files[fmt.Sprintf("%d/%s.class", profile.Release, name)] - if err != nil || len(digest) != 32 || entry == nil || entry.UncompressedSize64 > 2<<20 { + table := make(map[string]constructorBundleEntry, len(profile.Classes)) + hashTable := make(map[string]string, len(profile.Classes)) + for className, entry := range profile.Classes { + digest, err := hex.DecodeString(entry.SHA256) + if err != nil || len(digest) != 32 { + return + } + if entry.Chunk < 0 || entry.Chunk >= len(chunks) || entry.Length > constructorBundleMaxClassSize { return } - table[name] = entry + if uint64(entry.Offset)+uint64(entry.Length) > uint64(chunks[entry.Chunk].rawLen) { + return + } + table[className] = entry + hashTable[className] = entry.SHA256 } entries[profile.Release] = table - hashes[profile.Release] = profile.Classes + hashes[profile.Release] = hashTable } + jdkConstructorCode.chunks = chunks + jdkConstructorCode.chunkData = chunkData jdkConstructorCode.entries = entries jdkConstructorCode.hashes = hashes }) - entry := jdkConstructorCode.entries[release][name] - if entry == nil { + entry, ok := jdkConstructorCode.entries[release][name] + if !ok { return nil, false } - f, err := entry.Open() - if err != nil { + chunk, ok := jdkConstructorChunkBytes(entry.Chunk) + if !ok { return nil, false } - raw, err := io.ReadAll(io.LimitReader(f, 2<<20)) - f.Close() - if err != nil { + end := uint64(entry.Offset) + uint64(entry.Length) + if end > uint64(len(chunk)) { return nil, false } + raw := make([]byte, entry.Length) + copy(raw, chunk[entry.Offset:end]) digest := sha256.Sum256(raw) if hex.EncodeToString(digest[:]) != jdkConstructorCode.hashes[release][name] { return nil, false diff --git a/classparser/jdk_constructor_code_data_test.go b/classparser/jdk_constructor_code_data_test.go new file mode 100644 index 00000000..0d7ba69c --- /dev/null +++ b/classparser/jdk_constructor_code_data_test.go @@ -0,0 +1,76 @@ +package javaclassparser + +import ( + "archive/zip" + "bytes" + "encoding/json" + "fmt" + "io" + "testing" +) + +func TestJDKCompressedConstructorCodeMatchesSource(t *testing.T) { + zr, err := zip.OpenReader("jdk_constructor_code.zip") + if err != nil { + t.Fatal(err) + } + defer zr.Close() + + files := make(map[string]*zip.File, len(zr.File)) + for _, f := range zr.File { + files[f.Name] = f + } + mf, err := files["manifest.json"].Open() + if err != nil { + t.Fatal(err) + } + manifestBytes, err := io.ReadAll(mf) + mf.Close() + if err != nil { + t.Fatal(err) + } + var doc constructorCodeDocument + if err := json.Unmarshal(manifestBytes, &doc); err != nil { + t.Fatal(err) + } + if len(doc.Profiles) == 0 { + t.Fatal("empty source constructor profiles") + } + + // Trigger lazy initialization and verify profile/entry count matches source. + if _, ok := jdkConstructorClassBytes("java/lang/Object", doc.Profiles[0].Release); !ok { + t.Fatal("failed to load java/lang/Object from compressed bundle") + } + if len(jdkConstructorCode.entries) != len(doc.Profiles) { + t.Fatalf("profile count mismatch: got %d want %d", len(jdkConstructorCode.entries), len(doc.Profiles)) + } + + for _, profile := range doc.Profiles { + gotProfile := jdkConstructorCode.entries[profile.Release] + if len(gotProfile) != len(profile.Classes) { + t.Fatalf("release %d class count mismatch: got %d want %d", profile.Release, len(gotProfile), len(profile.Classes)) + } + for name := range profile.Classes { + zf := files[fmt.Sprintf("%d/%s.class", profile.Release, name)] + if zf == nil { + t.Fatalf("missing source zip entry %d/%s.class", profile.Release, name) + } + rc, err := zf.Open() + if err != nil { + t.Fatal(err) + } + want, err := io.ReadAll(rc) + rc.Close() + if err != nil { + t.Fatal(err) + } + got, ok := jdkConstructorClassBytes(name, profile.Release) + if !ok { + t.Fatalf("missing %d/%s in compressed bundle", profile.Release, name) + } + if !bytes.Equal(got, want) { + t.Fatalf("byte mismatch for %d/%s; run go generate ./classparser", profile.Release, name) + } + } + } +} diff --git a/classparser/jdk_metadata_catalog.md b/classparser/jdk_metadata_catalog.md index fb0ed547..66c812d4 100644 --- a/classparser/jdk_metadata_catalog.md +++ b/classparser/jdk_metadata_catalog.md @@ -93,12 +93,13 @@ python3 classparser/jdk_metadata_catalog_generate.py \ go generate ./classparser ``` -The reviewed JSON remains the source of truth. Applications embed only -`jdk_metadata_catalog.json.zst`; the catalog is decompressed on its first -required lookup, within the existing one-time loader. The constructor classfile -ZIP and all exact-profile/provenance checks remain unchanged. The required -corpus tests compare decompressed bytes with the JSON source so regeneration -cannot silently omit a catalog update. +The reviewed JSON and constructor classfile ZIP remain the sources of truth. +Applications embed only `jdk_metadata_catalog.json.zst` and the deterministic +chunked-zstd `jdk_constructor_code.bundle.zst`; the catalog and each 1 MiB +constructor chunk are decompressed lazily on first required lookup, and every +lookup verifies the per-class SHA-256 and returns an owned copy. The required +corpus tests compare decompressed bytes against both reviewed sources so +regeneration cannot silently omit an update. ## Evidence and limits diff --git a/internal/omap/dbtype.go b/internal/omap/dbtype.go deleted file mode 100644 index 4b7b7405..00000000 --- a/internal/omap/dbtype.go +++ /dev/null @@ -1 +0,0 @@ -package omap diff --git a/internal/omap/format.go b/internal/omap/format.go deleted file mode 100644 index 4b7b7405..00000000 --- a/internal/omap/format.go +++ /dev/null @@ -1 +0,0 @@ -package omap diff --git a/internal/omap/json.go b/internal/omap/json.go deleted file mode 100644 index 5054a15d..00000000 --- a/internal/omap/json.go +++ /dev/null @@ -1,147 +0,0 @@ -package omap - -import ( - "bytes" - "encoding/json" - - "github.com/tidwall/gjson" - "github.com/yaklang/javajive/internal/log" - "github.com/yaklang/javajive/internal/utils" -) - -func (v *OrderedMap[T, V]) Jsonify() []byte { - raw, err := json.Marshal(v) - if err != nil { - return nil - } - return raw -} - -func (v *OrderedMap[T, V]) UnmarshalJSON(raw []byte) error { - gresult := gjson.ParseBytes(raw) - - // as list - if gresult.IsArray() { - for _, r := range gresult.Array() { - var value V - err := json.Unmarshal([]byte(r.Raw), &value) - if err != nil { - // [WARN] 2024-04-22 00:38:35 [json:29] cannot unmarshal value: json: cannot unmarshal object into Go value of type ssautil.VersionedIF[github.com/yaklang/yaklang/common/yak/ssa.Value] to - log.Warnf("cannot unmarshal value: %v to %T", err, value) - continue - } - v.Push(value) - } - return nil - } else if gresult.IsObject() { - gresult.ForEach(func(key, value gjson.Result) bool { - var val V - err := json.Unmarshal([]byte(value.Raw), &val) - if err != nil { - log.Warnf("cannot unmarshal value: %v to %T", err, val) - return true - } - var keyResult T - err = json.Unmarshal([]byte(key.Raw), &keyResult) - if err != nil { - return true - } - v.Set(keyResult, val) - return true - }) - return nil - } else if gresult.IsBool() { - v.SetLiteralValue(gresult.Bool()) - return nil - } else { - v.SetLiteralValue(gresult.Num) - } - return nil -} - -func (v *OrderedMap[T, V]) MarshalJSONWithKeyValueFetcher(k func(t any) ([]byte, error), vf func(any) ([]byte, error)) ([]byte, error) { - if v.HaveLiteralValue() { - raw, err := json.Marshal(v.LiteralValue()) - if err != nil { - return nil, utils.Errorf("cannot marshal literal val: %T", v.LiteralValue()) - } - return raw, nil - } - if v.CanAsList() { - var buf bytes.Buffer - buf.WriteByte('[') - for index, val := range v.Values() { - if index != 0 { - buf.WriteByte(',') - } - var raw []byte - var err error - if vf != nil { - raw, err = vf(val) - } else { - var vAny any = val - if vIns, ok := vAny.(interface { - MarshalJSONWithKeyValueFetcher(k func(t any) ([]byte, error), vf func(any) ([]byte, error)) ([]byte, error) - }); ok { - raw, err = vIns.MarshalJSONWithKeyValueFetcher(k, vf) - } else { - raw, err = json.Marshal(val) - } - } - if err != nil { - buf.Write([]byte("null")) - continue - } - buf.Write(raw) - } - buf.WriteByte(']') - return buf.Bytes(), nil - } - - var buf = new(bytes.Buffer) - buf.WriteByte('{') - first := true - v.ForEach(func(i T, v V) bool { - if first { - first = false - } else { - buf.WriteByte(',') - } - - var raw []byte - var err error - if k != nil { - raw, err = k(i) - } else { - raw, err = json.Marshal(i) - } - buf.Write(raw) - buf.WriteByte(':') - - if vf != nil { - raw, err = vf(v) - } else { - var vAny any = v - if vIns, ok := vAny.(interface { - MarshalJSONWithKeyValueFetcher(k func(t any) ([]byte, error), vf func(any) ([]byte, error)) ([]byte, error) - }); ok { - raw, err = vIns.MarshalJSONWithKeyValueFetcher(k, vf) - } else { - raw, err = json.Marshal(v) - } - } - if err != nil { - buf.Write([]byte("null")) - return true - } - buf.Write(raw) - return true - }) - buf.WriteByte('}') - - return buf.Bytes(), nil -} - -func (v *OrderedMap[T, V]) MarshalJSON() ([]byte, error) { - return v.MarshalJSONWithKeyValueFetcher(nil, nil) -} diff --git a/internal/omap/ordered.go b/internal/omap/ordered.go index 7cf81c01..b802e14d 100644 --- a/internal/omap/ordered.go +++ b/internal/omap/ordered.go @@ -1,36 +1,12 @@ package omap -import ( - "fmt" - "reflect" - "regexp" - "sort" - "strings" - "sync" - - "github.com/gobwas/glob" - "github.com/segmentio/ksuid" - "github.com/yaklang/javajive/internal/log" - "github.com/yaklang/javajive/internal/utils" -) - -func tryGetParent[V any](v any) *OrderedMap[string, V] { - switch v.(type) { - case *OrderedMap[string, V]: - return v.(*OrderedMap[string, V]) - } - return nil -} +import "sync" type OrderedMap[T comparable, V any] struct { initOnce sync.Once lock *sync.RWMutex m map[T]V - namedKey bool keyChain []T - - parent *OrderedMap[T, V] - literalValue any } func (o *OrderedMap[T, V]) init() { @@ -50,85 +26,14 @@ func (o *OrderedMap[T, V]) init() { }) } -func (i *OrderedMap[T, V]) LiteralValue() any { - if i == nil { - return nil - } - return i.literalValue -} - -func (i *OrderedMap[T, V]) HaveLiteralValue() bool { - if i == nil { - return false - } - return i.literalValue != nil -} - -func (i *OrderedMap[T, V]) SetLiteralValue(val any) { - if i == nil { - return - } - i.literalValue = val -} - func NewEmptyOrderedMap[T comparable, V any]() *OrderedMap[T, V] { - return &OrderedMap[T, V]{ + m := &OrderedMap[T, V]{ lock: new(sync.RWMutex), m: make(map[T]V), keyChain: make([]T, 0), } -} - -func NewGeneralOrderedMap() *OrderedMap[string, any] { - return NewEmptyOrderedMap[string, any]() -} - -func NewOrderedMap[T comparable, V any](m map[T]V, initOrder ...func(int, int) bool) *OrderedMap[T, V] { - if m == nil { - return NewEmptyOrderedMap[T, V]() - } - k := make([]T, 0) - for key := range m { - k = append(k, key) - } - for _, s := range initOrder { - sort.SliceStable(k, s) - } - return &OrderedMap[T, V]{ - lock: new(sync.RWMutex), - m: m, - keyChain: k, - namedKey: len(initOrder) > 0, - } -} - -var nonnamedkeyconst = `[[-non-named-key-]]` - -func (o *OrderedMap[T, V]) Add(v V) error { - if o == nil { - return fmt.Errorf("cannot add to a nil OrderedMap") - } - o.init() - o.lock.Lock() - defer o.lock.Unlock() - - conv := func(i any) (T, bool) { - res, ok := i.(T) - if ok { - return res, true - } - var z T - return z, false - } - - k := ksuid.New().String() + nonnamedkeyconst - val, ok := conv(k) - if !ok { - return utils.Errorf("convert failed: cannot convert %v to %v", k, reflect.TypeOf(val)) - } - o.m[val] = v - o.keyChain = append(o.keyChain, val) - return nil + m.initOnce.Do(func() {}) + return m } func (o *OrderedMap[T, V]) Set(key T, v V) { @@ -137,75 +42,11 @@ func (o *OrderedMap[T, V]) Set(key T, v V) { } o.init() o.lock.Lock() - defer o.lock.Unlock() - - _, ok := o.m[key] - if !ok { - o.m[key] = v + if _, ok := o.m[key]; !ok { o.keyChain = append(o.keyChain, key) - o.namedKey = true - return } - - // existed o.m[key] = v - o.namedKey = true -} - -// OrderInsert inserts (key, v) into the map and places the key in keyChain according to less. -// less(a, b) should return true if a should be ordered before b. -// If key already exists, it will be moved to the new ordered position and its value updated. -// If less is nil, it falls back to Set (append-on-new). -func (o *OrderedMap[T, V]) OrderInsert(key T, v V, less func(a, b T) bool) { - if o == nil { - return - } - if less == nil { - o.Set(key, v) - return - } - o.init() - o.lock.Lock() - defer o.lock.Unlock() - - // Upsert value first. - o.m[key] = v - o.namedKey = true - - // Remove existing key from keyChain if present (to allow repositioning). - for i, k := range o.keyChain { - if k == key { - o.keyChain = append(o.keyChain[:i], o.keyChain[i+1:]...) - break - } - } - - // Find insertion index (stable: insert after existing equals if less is strict). - insertAt := sort.Search(len(o.keyChain), func(i int) bool { - return less(key, o.keyChain[i]) - }) - - // Insert key into keyChain at insertAt. - var zero T - o.keyChain = append(o.keyChain, zero) - copy(o.keyChain[insertAt+1:], o.keyChain[insertAt:]) - o.keyChain[insertAt] = key -} - -func (o *OrderedMap[T, V]) BringKeyToLastOne(target T) { - if o == nil { - return - } - o.init() - o.lock.Lock() - defer o.lock.Unlock() - for key, instance := range o.keyChain { - if instance == target { - o.keyChain = append(o.keyChain[:key], o.keyChain[key+1:]...) - break - } - } - o.keyChain = append(o.keyChain, target) + o.lock.Unlock() } func (o *OrderedMap[T, V]) Get(key T) (V, bool) { @@ -215,31 +56,11 @@ func (o *OrderedMap[T, V]) Get(key T) (V, bool) { } o.init() o.lock.RLock() - defer o.lock.RUnlock() - v, ok := o.m[key] + o.lock.RUnlock() return v, ok } -func (o *OrderedMap[T, V]) GetOrSet(key T, value V) V { - if o == nil { - return value - } - o.init() - o.lock.Lock() - defer o.lock.Unlock() - - existValue, ok := o.m[key] - if !ok { - o.m[key] = value - o.keyChain = append(o.keyChain, key) - o.namedKey = true - return value - } - o.namedKey = true - return existValue -} - func (o *OrderedMap[T, V]) GetMust(key T) V { if o == nil { var zero V @@ -247,170 +68,20 @@ func (o *OrderedMap[T, V]) GetMust(key T) V { } o.init() o.lock.RLock() - defer o.lock.RUnlock() - - v, ok := o.m[key] - if !ok { - var z V - return z - } + v := o.m[key] + o.lock.RUnlock() return v } -func (o *OrderedMap[T, V]) Index(i int) *OrderedMap[string, V] { - if o == nil { - return nil - } - o.init() - o.lock.RLock() - defer o.lock.RUnlock() - - if i < 0 || i >= len(o.keyChain) { - return NewEmptyOrderedMap[string, V]() - } - - result := NewEmptyOrderedMap[string, V]() - err := result.Add(o.m[o.keyChain[i]]) - if err != nil { - log.Errorf("BUG: why? general map type convert failed: %v", err) - } - result.parent = tryGetParent[V](o) - return result -} - -func (o *OrderedMap[T, V]) Field(key T) *OrderedMap[string, V] { - if o == nil { - return nil - } - o.init() - val, ok := o.Get(key) - if !ok { - return NewEmptyOrderedMap[string, V]() - } - result := BuildGeneralMap[V](val) - result.parent = tryGetParent[V](o) - return result -} - -func BuildGeneralMap[V any](m any) *OrderedMap[string, V] { - if m == nil { - t := NewEmptyOrderedMap[string, V]() - return t - } - - ty := reflect.TypeOf(m) - switch ty.Kind() { - case reflect.Map: - vv := reflect.ValueOf(m) - result := NewEmptyOrderedMap[string, V]() - for _, key := range vv.MapKeys() { - value := vv.MapIndex(key).Interface().(V) - result.Set(utils.InterfaceToString(key.Interface()), value) - } - return result - case reflect.Array, reflect.Slice: - vv := reflect.ValueOf(m) - result := NewEmptyOrderedMap[string, V]() - for i := 0; i < vv.Len(); i++ { - result.Add(vv.Index(i).Interface().(V)) - } - return result - case reflect.Ptr: - switch ret := m.(type) { - case *OrderedMap[string, V]: - return ret - } - vv := reflect.ValueOf(m) - return BuildGeneralMap[V](vv.Elem().Interface()) - case reflect.Struct: - vv := reflect.ValueOf(m) - result := NewEmptyOrderedMap[string, V]() - for i := 0; i < vv.NumField(); i++ { - result.Set(vv.Type().Field(i).Name, vv.Field(i).Interface().(V)) - } - return result - default: - result := NewEmptyOrderedMap[string, V]() - result.Set(utils.InterfaceToString(m), m.(V)) - return result - } -} - -func (o *OrderedMap[T, V]) GetByIndex(index int) (V, bool) { - if o == nil { - var zero V - return zero, false - } - o.init() - o.lock.RLock() - defer o.lock.RUnlock() - - if index < 0 || index >= len(o.keyChain) { - var z V - return z, false - } - - return o.m[o.keyChain[index]], true -} - -func (o *OrderedMap[T, V]) GetByIndexMust(index int) V { - if o == nil { - var zero V - return zero - } - o.init() - var r, _ = o.GetByIndex(index) - return r -} - -func (o *OrderedMap[T, V]) First() (T, V, bool) { - if o == nil { - var zt T - var zv V - return zt, zv, false - } - o.init() - o.lock.RLock() - defer o.lock.RUnlock() - - if len(o.keyChain) == 0 { - var z T - var v V - return z, v, false - } - - return o.keyChain[0], o.m[o.keyChain[0]], true -} - -func (o *OrderedMap[T, V]) Last() (T, V, bool) { - if o == nil { - var zt T - var zv V - return zt, zv, false - } - o.init() - o.lock.RLock() - defer o.lock.RUnlock() - - if len(o.keyChain) == 0 { - var z T - var v V - return z, v, false - } - - mi := len(o.keyChain) - 1 - return o.keyChain[mi], o.m[o.keyChain[mi]], true -} - func (o *OrderedMap[T, V]) Len() int { if o == nil { return 0 } o.init() o.lock.RLock() - defer o.lock.RUnlock() - - return len(o.keyChain) + n := len(o.keyChain) + o.lock.RUnlock() + return n } func (o *OrderedMap[T, V]) Delete(key T) { @@ -419,24 +90,21 @@ func (o *OrderedMap[T, V]) Delete(key T) { } o.init() o.lock.Lock() - defer o.lock.Unlock() - delete(o.m, key) - var index = -1 + index := -1 for i, k := range o.keyChain { if k == key { index = i break } } - if index == -1 { - return + if index != -1 { + after := make([]T, len(o.keyChain)-1) + copy(after, o.keyChain[:index]) + copy(after[index:], o.keyChain[index+1:]) + o.keyChain = after } - - after := make([]T, len(o.keyChain)-1) - copy(after, o.keyChain[:index]) - copy(after[index:], o.keyChain[index+1:]) - o.keyChain = after + o.lock.Unlock() } func (o *OrderedMap[T, V]) Keys() []T { @@ -445,9 +113,9 @@ func (o *OrderedMap[T, V]) Keys() []T { } o.init() o.lock.RLock() - defer o.lock.RUnlock() - - return o.keyChain + ks := o.keyChain + o.lock.RUnlock() + return ks } func (o *OrderedMap[T, V]) Values() []V { @@ -456,158 +124,14 @@ func (o *OrderedMap[T, V]) Values() []V { } o.init() o.lock.RLock() - defer o.lock.RUnlock() values := make([]V, len(o.keyChain)) for i, k := range o.keyChain { values[i] = o.m[k] } + o.lock.RUnlock() return values } -func (o *OrderedMap[T, V]) ValuesMap() *OrderedMap[string, V] { - if o == nil { - return nil - } - o.init() - o.lock.RLock() - defer o.lock.RUnlock() - - result := NewEmptyOrderedMap[string, V]() - for _, v := range o.Values() { - vv := reflect.ValueOf(v) - vt := reflect.TypeOf(v) - switch vt.Kind() { - case reflect.Map: - for _, key := range vv.MapKeys() { - value := vv.MapIndex(key).Interface().(V) - result.Set(utils.InterfaceToString(key.Interface()), value) - } - case reflect.Array: - for i := 0; i < vv.Len(); i++ { - result.Add(vv.Index(i).Interface().(V)) - } - case reflect.Slice: - for i := 0; i < vv.Len(); i++ { - result.Add(vv.Index(i).Interface().(V)) - } - default: - result.Add(v) - } - } - result.parent = tryGetParent[V](o) - return result -} - -func (o *OrderedMap[T, V]) Have(i any) bool { - if o == nil { - return false - } - o.init() - o.lock.RLock() - defer o.lock.RUnlock() - - switch i.(type) { - case T: - _, ok := o.m[i.(T)] - return ok - case V: - for _, v := range o.m { - if reflect.DeepEqual(i, v) { - return true - } - } - return false - default: - return false - } -} - -func (o *OrderedMap[T, V]) Filter(f func(T, V) (bool, error)) *OrderedMap[T, V] { - if o == nil { - return nil - } - o.init() - o.lock.Lock() - defer o.lock.Unlock() - - r := NewEmptyOrderedMap[T, V]() - for _, key := range o.keyChain { - v, ok := o.m[key] - if !ok { - continue - } - ok, err := f(key, v) - if err != nil { - break - } - if ok { - var k any = key - if sk, ok := k.(string); ok { - if strings.HasSuffix(sk, nonnamedkeyconst) { - r.Add(v) - } else { - r.Set(key, v) - } - } else { - r.Set(key, v) - } - } - } - r.parent = o - return r -} - -func (o *OrderedMap[T, V]) GetParent() *OrderedMap[T, V] { - if o == nil { - return nil - } - o.init() - return o.parent -} - -func (o *OrderedMap[T, V]) GetRoot() (*OrderedMap[T, V], bool) { - if o == nil { - return nil, false - } - o.init() - if o.parent == nil { - return o, true - } - return o.parent.GetRoot() -} - -func (o *OrderedMap[T, V]) GetMap() map[T]V { - if o == nil { - return nil - } - o.init() - return o.m -} - -func (o *OrderedMap[T, V]) Map(f func(T, V) (T, V, error)) *OrderedMap[T, V] { - if o == nil { - return nil - } - o.init() - o.lock.Lock() - defer o.lock.Unlock() - - var r = NewEmptyOrderedMap[T, V]() - for _, key := range o.keyChain { - v, ok := o.m[key] - if !ok { - continue - } - nk, nv, err := f(key, v) - if err != nil { - break - } - r.Set(nk, nv) - } - r.parent = o - return r -} - // ForEachReadOnly iterates in insertion order without copying the key/value // snapshot. The handler must not mutate o or call a method that takes its // write lock. Read-only analysis loops use this to avoid a per-call allocation. @@ -645,369 +169,25 @@ func (o *OrderedMap[T, V]) ForEach(handler func(i T, v V) bool) { } } -func (o *OrderedMap[T, V]) Flat(f func(T, V) (struct { - Key T - Value V -}, error)) *OrderedMap[T, V] { - if o == nil { - return nil - } - o.init() - o.lock.Lock() - defer o.lock.Unlock() - - var r = NewEmptyOrderedMap[T, V]() - for _, key := range o.keyChain { - v, ok := o.m[key] - if !ok { - continue - } - n, err := f(key, v) - if err != nil { - break - } - r.Set(n.Key, n.Value) - } - r.parent = o - return r -} - func (s *OrderedMap[T, V]) Copy() *OrderedMap[T, V] { if s == nil { return nil } s.init() s.lock.RLock() - defer s.lock.RUnlock() - - m := make(map[T]V) + m := make(map[T]V, len(s.m)) for k, v := range s.m { m[k] = v } ks := make([]T, len(s.keyChain)) copy(ks, s.keyChain) + s.lock.RUnlock() + newMap := &OrderedMap[T, V]{ lock: new(sync.RWMutex), m: m, keyChain: ks, - parent: nil, - namedKey: s.namedKey, } newMap.initOnce.Do(func() {}) - return newMap } - -func (s *OrderedMap[T, V]) SearchKey(i ...string) (*OrderedMap[T, V], error) { - if s == nil { - return nil, nil - } - s.init() - s.lock.RLock() - defer s.lock.RUnlock() - - r := NewEmptyOrderedMap[T, V]() - for _, key := range s.keyChain { - v, ok := s.m[key] - if !ok { - continue - } - for _, j := range i { - if utils.InterfaceToString(key) == j { - r.Set(key, v) - break - } - } - } - r.parent = s - return r, nil -} - -func (s *OrderedMap[T, V]) SearchValue(i ...string) (*OrderedMap[T, V], error) { - if s == nil { - return nil, nil - } - s.init() - s.lock.RLock() - defer s.lock.RUnlock() - - r := NewEmptyOrderedMap[T, V]() - for _, key := range s.keyChain { - v, ok := s.m[key] - if !ok { - continue - } - for _, j := range i { - if utils.InterfaceToString(key) == j { - r.Set(key, v) - break - } - } - } - r.parent = s - return r, nil -} - -func (s *OrderedMap[T, V]) SearchKeyByValue(i ...string) (*OrderedMap[T, V], error) { - if s == nil { - return nil, nil - } - s.init() - s.lock.RLock() - defer s.lock.RUnlock() - - r := NewEmptyOrderedMap[T, V]() - for _, key := range s.keyChain { - v, ok := s.m[key] - if !ok { - continue - } - for _, j := range i { - if utils.InterfaceToString(key) == j { - r.Add(v) - break - } - } - } - r.parent = s - return r, nil -} - -func (s *OrderedMap[T, V]) SearchIndexKey(i ...int) (*OrderedMap[T, V], error) { - if s == nil { - return nil, nil - } - s.init() - s.lock.RLock() - defer s.lock.RUnlock() - - var indexMap = make(map[int]struct{}) - for _, idx := range i { - indexMap[idx] = struct{}{} - } - - r := NewEmptyOrderedMap[T, V]() - for index, key := range s.keyChain { - v, ok := s.m[key] - if !ok { - continue - } - if _, ok := indexMap[index]; ok { - r.Set(key, v) - } - } - r.parent = s - return r, nil -} - -func (s *OrderedMap[T, V]) SearchRegexKey(i string) (*OrderedMap[T, V], error) { - if s == nil { - return nil, nil - } - s.init() - s.lock.RLock() - defer s.lock.RUnlock() - - rule, err := regexp.Compile(i) - if err != nil { - return s, err - } - - r := NewEmptyOrderedMap[T, V]() - for _, key := range s.keyChain { - v, ok := s.m[key] - if !ok { - continue - } - if rule.MatchString(utils.InterfaceToString(key)) { - r.Set(key, v) - } - } - r.parent = s - return r, nil -} - -func (s *OrderedMap[T, V]) WalkSearchRegexpKey(i string) (*OrderedMap[T, V], error) { - if s == nil { - return nil, nil - } - s.init() - s.lock.RLock() - defer s.lock.RUnlock() - - rule, err := regexp.Compile(i) - if err != nil { - return s, err - } - - var m = NewOrderedMap[T, V](map[T]V{}) - Walk(s, func(parent any, key any, value any) bool { - if rule.MatchString(utils.InterfaceToString(key)) { - v, ok := value.(V) - if !ok { - return true - } - m.Add(v) - } - return true - }) - return m, nil -} - -func (s *OrderedMap[T, V]) SearchGlobKey(i string, seps ...string) (*OrderedMap[T, V], error) { - if s == nil { - return nil, nil - } - s.init() - s.lock.RLock() - defer s.lock.RUnlock() - - var sepsChar = []rune(strings.Join(seps, "")) - rule, err := glob.Compile(i, sepsChar...) - if err != nil { - return s, err - } - - r := NewEmptyOrderedMap[T, V]() - for _, key := range s.keyChain { - v, ok := s.m[key] - if !ok { - continue - } - if rule.Match(utils.InterfaceToString(key)) { - r.Set(key, v) - } - } - r.parent = s - return r, nil -} - -func (s *OrderedMap[T, V]) WalkSearchGlobKey(i string, seps ...string) (*OrderedMap[T, V], error) { - if s == nil { - return nil, nil - } - s.init() - s.lock.RLock() - defer s.lock.RUnlock() - - var sepsChar = []rune(strings.Join(seps, "")) - rule, err := glob.Compile(i, sepsChar...) - if err != nil { - return s, err - } - - var m = NewOrderedMap(map[T]V{}) - Walk(s, func(parent any, key any, value any) bool { - if rule.Match(utils.InterfaceToString(key)) { - v, ok := value.(V) - if !ok { - return true - } - m.Add(v) - } - return true - }) - return m, nil -} - -func Merge[T comparable, V any](dicts ...*OrderedMap[T, V]) *OrderedMap[T, V] { - r := NewEmptyOrderedMap[T, V]() - for _, d := range dicts { - for _, key := range d.keyChain { - v, ok := d.m[key] - if !ok { - continue - } - r.Set(key, v) - } - } - return r -} - -func (s *OrderedMap[T, V]) Merge(i ...*OrderedMap[T, V]) *OrderedMap[T, V] { - if s == nil { - return nil - } - s.init() - s.lock.RLock() - defer s.lock.RUnlock() - r := Merge[T, V](append([]*OrderedMap[T, V]{s}, i...)...) - r.parent = s - return r -} - -func (s *OrderedMap[T, V]) String() string { - if s == nil { - return "" - } - s.init() - s.lock.RLock() - defer s.lock.RUnlock() - - var builder strings.Builder - builder.WriteString("{") - for i, k := range s.keyChain { - builder.WriteString(fmt.Sprintf("%v: %#v", k, s.m[k])) - if i != len(s.keyChain)-1 { - builder.WriteString(", ") - } - } - builder.WriteString("}") - return builder.String() -} - -func (s *OrderedMap[T, V]) UnsetParent() { - if s == nil { - return - } - s.parent = nil -} - -func (s *OrderedMap[T, V]) CanAsList() bool { - if s == nil { - return true - } - return !s.namedKey -} - -func (s *OrderedMap[T, V]) Push(a V) error { - if s == nil { - return fmt.Errorf("cannot push to a nil OrderedMap") - } - return s.Add(a) -} - -func (s *OrderedMap[T, V]) PushKey(key T, value V) { - if s == nil { - return - } - s.Set(key, value) -} - -func (s *OrderedMap[T, V]) Pop() V { - if s == nil { - var zero V - return zero - } - key, v, ok := s.Last() - if ok { - s.Delete(key) - return v - } - var ret V - return ret -} - -func (s *OrderedMap[T, V]) Shift() V { - if s == nil { - var zero V - return zero - } - key, v, ok := s.First() - if ok { - s.Delete(key) - return v - } - var ret V - return ret -} diff --git a/internal/omap/ordered_walk.go b/internal/omap/ordered_walk.go deleted file mode 100644 index 18b179b2..00000000 --- a/internal/omap/ordered_walk.go +++ /dev/null @@ -1,106 +0,0 @@ -package omap - -import ( - "reflect" - "sync" -) - -func Walkable(i any) bool { - _, ok := i.(walkif) - if ok { - return true - } - - switch reflect.TypeOf(i).Kind() { - case reflect.Map, reflect.Slice, reflect.Array: - return true - case reflect.Pointer: - return Walkable(reflect.ValueOf(i).Elem().Interface()) - default: - return false - } -} - -func (m *OrderedMap[T, V]) WalkMap(visited *sync.Map, f func(self, key, value any) bool) { - for _, k := range m.Keys() { - v, ok := m.Get(k) - if !ok { - continue - } - var self any = m - var key any = k - var val any = v - if f(self, key, val) { - walk(visited, val, f) - } - } -} - -func Walk(m any, f func(parent any, key any, value any) bool) { - walk(nil, m, f) -} - -type walkif interface { - WalkMap(*sync.Map, func(self, key, value any) bool) -} - -func walk(visited *sync.Map, m any, f func(parent any, key any, value any) bool) { - if visited == nil { - visited = new(sync.Map) - } - - mKind := reflect.TypeOf(m).Kind() - switch mKind { - case reflect.Chan, reflect.Func, reflect.Map, reflect.Pointer, reflect.Slice, reflect.UnsafePointer: - // It panics if v's Kind is not Chan, Func, Map, Pointer, Slice, or UnsafePointer. - mPtr := reflect.ValueOf(m).Pointer() - if _, ok := visited.Load(mPtr); ok { - // prevent infinite loop - return - } - visited.Store(mPtr, true) - default: - - } - - switch mKind { - case reflect.Map: - for _, k := range reflect.ValueOf(m).MapKeys() { - v := reflect.ValueOf(m).MapIndex(k).Interface() - if f(m, k.Interface(), v) { - walk(visited, v, f) - } - } - case reflect.Slice: - for i := 0; i < reflect.ValueOf(m).Len(); i++ { - v := reflect.ValueOf(m).Index(i).Interface() - if f(m, i, v) { - walk(visited, v, f) - } - } - case reflect.Array: - for i := 0; i < reflect.ValueOf(m).Len(); i++ { - v := reflect.ValueOf(m).Index(i).Interface() - if f(m, i, v) { - walk(visited, v, f) - } - } - case reflect.Ptr: - ptrTo := reflect.ValueOf(m).Elem() - switch ptrTo.Kind() { - case reflect.Map, reflect.Slice, reflect.Array: - walk(visited, reflect.ValueOf(m).Elem().Interface(), f) - default: - // do nothing - if result, ok := m.(walkif); ok { - result.WalkMap(visited, f) - } else if result, ok := ptrTo.Interface().(walkif); ok { - result.WalkMap(visited, f) - } - } - default: - if result, ok := m.(walkif); ok { - result.WalkMap(visited, f) - } - } -} diff --git a/javajive.go b/javajive.go index 430549a1..31be3a44 100644 --- a/javajive.go +++ b/javajive.go @@ -38,7 +38,7 @@ import ( ) // Version is the javajive library/CLI version. -const Version = "0.8.0" +const Version = "0.8.1" // --------------------------------------------------------------------------- // Re-exported types diff --git a/tools/compressjdk/main.go b/tools/compressjdk/main.go index b9b2d548..ead8b77a 100644 --- a/tools/compressjdk/main.go +++ b/tools/compressjdk/main.go @@ -1,22 +1,73 @@ -// Command compressjdk deterministically compresses the reviewed JDK catalog. +// Command compressjdk deterministically compresses the reviewed JDK catalog +// and constructor classfile bundle. package main import ( + "archive/zip" + "bytes" + "crypto/sha256" + "encoding/binary" + "encoding/hex" + "encoding/json" "flag" "fmt" + "io" "os" + "sort" + "strings" "github.com/klauspost/compress/zstd" ) +const ( + constructorBundleMagic = "JJCC0001" + constructorChunkTargetBytes = 1 << 20 +) + +type constructorCodeProfile struct { + Release int `json:"release"` + ArchiveSHA256 string `json:"archive_sha256"` + Classes map[string]string `json:"classes"` +} + +type constructorCodeDocument struct { + Schema int `json:"schema"` + Profiles []constructorCodeProfile `json:"profiles"` +} + +type constructorBundleEntry struct { + SHA256 string `json:"s"` + Chunk int `json:"c"` + Offset uint32 `json:"o"` + Length uint32 `json:"l"` +} + +type constructorBundleProfile struct { + Release int `json:"release"` + ArchiveSHA256 string `json:"archive_sha256"` + Classes map[string]constructorBundleEntry `json:"classes"` +} + +type constructorBundleIndex struct { + Schema int `json:"schema"` + Profiles []constructorBundleProfile `json:"profiles"` +} + func main() { input := flag.String("input", "", "reviewed JDK catalog JSON; output is .zst") + constructorZip := flag.String("constructor-zip", "", "reviewed JDK constructor ZIP; output replaces .zip with .bundle.zst") flag.Parse() - if *input == "" || flag.NArg() != 0 { - fmt.Fprintln(os.Stderr, "usage: compressjdk -input jdk_metadata_catalog.json") + if (*input == "" && *constructorZip == "") || (*input != "" && *constructorZip != "") || flag.NArg() != 0 { + fmt.Fprintln(os.Stderr, "usage: compressjdk -input jdk_metadata_catalog.json | -constructor-zip jdk_constructor_code.zip") os.Exit(2) } - if err := compress(*input); err != nil { + var err error + if *input != "" { + err = compress(*input) + } else { + err = compressConstructorZip(*constructorZip) + } + if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } @@ -40,3 +91,171 @@ func compress(input string) error { compressed := encoder.EncodeAll(raw, nil) return os.WriteFile(input+".zst", compressed, 0644) } + +func compressConstructorZip(input string) error { + zr, err := zip.OpenReader(input) + if err != nil { + return err + } + defer zr.Close() + + files := make(map[string]*zip.File, len(zr.File)) + for _, f := range zr.File { + if files[f.Name] != nil { + return fmt.Errorf("duplicate zip entry %q", f.Name) + } + files[f.Name] = f + } + manifestFile := files["manifest.json"] + if manifestFile == nil { + return fmt.Errorf("missing manifest.json in %s", input) + } + mf, err := manifestFile.Open() + if err != nil { + return err + } + manifestBytes, err := io.ReadAll(io.LimitReader(mf, 2<<20)) + mf.Close() + if err != nil { + return err + } + var doc constructorCodeDocument + if err := json.Unmarshal(manifestBytes, &doc); err != nil { + return fmt.Errorf("unmarshal manifest: %w", err) + } + if doc.Schema != 1 || len(doc.Profiles) == 0 { + return fmt.Errorf("invalid manifest schema=%d profiles=%d", doc.Schema, len(doc.Profiles)) + } + + type classRecord struct { + release int + name string + sha256 string + raw []byte + } + var records []classRecord + profileIndex := make([]constructorBundleProfile, len(doc.Profiles)) + profilePos := make(map[int]int, len(doc.Profiles)) + for i, prof := range doc.Profiles { + if _, dup := profilePos[prof.Release]; dup { + return fmt.Errorf("duplicate release %d", prof.Release) + } + profilePos[prof.Release] = i + profileIndex[i] = constructorBundleProfile{ + Release: prof.Release, + ArchiveSHA256: prof.ArchiveSHA256, + Classes: make(map[string]constructorBundleEntry, len(prof.Classes)), + } + for name, wantHash := range prof.Classes { + entry := files[fmt.Sprintf("%d/%s.class", prof.Release, name)] + if entry == nil { + return fmt.Errorf("missing class %d/%s.class", prof.Release, name) + } + rc, err := entry.Open() + if err != nil { + return err + } + raw, err := io.ReadAll(io.LimitReader(rc, 4<<20)) + rc.Close() + if err != nil { + return err + } + sum := sha256.Sum256(raw) + if got := hex.EncodeToString(sum[:]); got != wantHash { + return fmt.Errorf("hash mismatch for %d/%s: got %s want %s", prof.Release, name, got, wantHash) + } + records = append(records, classRecord{ + release: prof.Release, + name: name, + sha256: wantHash, + raw: raw, + }) + } + } + + // Sort by class name first, then release, so versions of the same JDK class + // across releases sit adjacent in the same chunk for strong cross-release + // dictionary compression. + sort.Slice(records, func(i, j int) bool { + if records[i].name != records[j].name { + return records[i].name < records[j].name + } + return records[i].release < records[j].release + }) + + encoder, err := zstd.NewWriter(nil, + zstd.WithEncoderLevel(zstd.SpeedBestCompression), + zstd.WithEncoderConcurrency(1), + zstd.WithWindowSize(2<<20), + zstd.WithEncoderCRC(true), + ) + if err != nil { + return err + } + defer encoder.Close() + + type chunkMeta struct { + compOffset uint32 + compLen uint32 + rawLen uint32 + } + var chunksMeta []chunkMeta + var chunksData bytes.Buffer + var curChunk bytes.Buffer + + flushChunk := func() { + if curChunk.Len() == 0 { + return + } + rawBytes := curChunk.Bytes() + comp := encoder.EncodeAll(rawBytes, nil) + chunksMeta = append(chunksMeta, chunkMeta{ + compOffset: uint32(chunksData.Len()), + compLen: uint32(len(comp)), + rawLen: uint32(len(rawBytes)), + }) + chunksData.Write(comp) + curChunk.Reset() + } + + for _, rec := range records { + if curChunk.Len() > 0 && curChunk.Len()+len(rec.raw) > constructorChunkTargetBytes { + flushChunk() + } + chunkIdx := len(chunksMeta) + offset := uint32(curChunk.Len()) + curChunk.Write(rec.raw) + pidx := profilePos[rec.release] + profileIndex[pidx].Classes[rec.name] = constructorBundleEntry{ + SHA256: rec.sha256, + Chunk: chunkIdx, + Offset: offset, + Length: uint32(len(rec.raw)), + } + } + flushChunk() + + indexJSON, err := json.Marshal(constructorBundleIndex{ + Schema: 1, + Profiles: profileIndex, + }) + if err != nil { + return err + } + manifestComp := encoder.EncodeAll(indexJSON, nil) + + var out bytes.Buffer + out.WriteString(constructorBundleMagic) + _ = binary.Write(&out, binary.LittleEndian, uint32(len(manifestComp))) + _ = binary.Write(&out, binary.LittleEndian, uint32(len(chunksMeta))) + for _, cm := range chunksMeta { + _ = binary.Write(&out, binary.LittleEndian, cm.compOffset) + _ = binary.Write(&out, binary.LittleEndian, cm.compLen) + _ = binary.Write(&out, binary.LittleEndian, cm.rawLen) + } + out.Write(manifestComp) + out.Write(chunksData.Bytes()) + + outPath := strings.TrimSuffix(input, ".zip") + ".bundle.zst" + return os.WriteFile(outPath, out.Bytes(), 0644) +} diff --git a/tools/requiredci/main.go b/tools/requiredci/main.go index 74e25ec5..e49a1c37 100644 --- a/tools/requiredci/main.go +++ b/tools/requiredci/main.go @@ -38,7 +38,7 @@ var requiredSuites = []suite{ {Group: "corpus", Package: "./classparser/jarwar", Tests: 18, TestHash: "b1195066bc29f6a35391695fb815b4eef9eb42a55ef53f7ba9786375a27afc25"}, {Group: "corpus", Package: "./classparser/decompiler/jar", Tests: 1, TestHash: "e84c19ac824483c172a763d735732079fb808d6dd0153c53e573b18513d23553"}, {Group: "corpus", Package: "./jimage", Tests: 16, TestHash: "f68b01a6c2a476c2a5921fc30f5ab3a6c0b700fe04748ac1e1d5d9573e283df8", Exclude: []string{"TestJLinkBigEndianImage", "TestJLinkCompactCPImage", "TestOpenJDKImage"}}, - {Group: "corpus", Package: "./classparser", Tests: 4177, TestHash: "7a0f8f15a3694fc97e99ed38d37f3f621481161e23ea97755762cedf09a847bc", Include: []string{"TestDumpMethodsPointerFastPathKeepsDescriptor", "TestJoinRuleChainExactOutput", "TestSourceRewritePrecisionOuterGateSemantics", "TestRewriteSchedulerOrderMatchesDumperCallSites", "TestRewriteSchedulerPositiveAndNearMissExactOutput", "TestRewriteSchedulerPreservesRecordsDiagnosticsAndHashes", "TestRewriteSchedulerDecompileEquivalence", "TestJDKObjectMetadataMatchesCatalog", "TestJDKCompressedCatalogMatchesSource", "TestAdversarialPlatformConstructorCodeIdentityAndEffectProof", "TestLoopAnalysisCacheMatchesUncachedDecompile", "FuzzDecompileWithLimitsNeverPanics"}}, + {Group: "corpus", Package: "./classparser", Tests: 4178, TestHash: "29359dca2ad616def97bff8a26e1943ab3db060d8a246e13c89447c73181df18", Include: []string{"TestDumpMethodsPointerFastPathKeepsDescriptor", "TestJoinRuleChainExactOutput", "TestSourceRewritePrecisionOuterGateSemantics", "TestRewriteSchedulerOrderMatchesDumperCallSites", "TestRewriteSchedulerPositiveAndNearMissExactOutput", "TestRewriteSchedulerPreservesRecordsDiagnosticsAndHashes", "TestRewriteSchedulerDecompileEquivalence", "TestJDKObjectMetadataMatchesCatalog", "TestJDKCompressedCatalogMatchesSource", "TestJDKCompressedConstructorCodeMatchesSource", "TestAdversarialPlatformConstructorCodeIdentityAndEffectProof", "TestLoopAnalysisCacheMatchesUncachedDecompile", "FuzzDecompileWithLimitsNeverPanics"}}, {Group: "algorithm", Package: "./classparser/decompiler/core", Tests: 413, TestHash: "cf788257ac2b6de14e9ba85f18a6fd70fcdc9f7f31d85b6538bb8b1344fff93b"}, {Group: "algorithm", Package: "./classparser/decompiler/core/callbinding", Tests: 17, TestHash: "e7eafd33ec36c2219f362b5c45872f126dde5a81dab84d931023fd1abc1836cc"},