Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added classparser/jdk_constructor_code.bundle.zst
Binary file not shown.
191 changes: 139 additions & 52 deletions classparser/jdk_constructor_code.go
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -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
Expand All @@ -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/"),
Expand All @@ -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
Expand Down
76 changes: 76 additions & 0 deletions classparser/jdk_constructor_code_data_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}
}
13 changes: 7 additions & 6 deletions classparser/jdk_metadata_catalog.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 0 additions & 1 deletion internal/omap/dbtype.go

This file was deleted.

1 change: 0 additions & 1 deletion internal/omap/format.go

This file was deleted.

Loading
Loading