package iskra import ( "os" "path/filepath" "sort" "strings" ) // AuditReport is the isomorphism audit of one corpus. type AuditReport struct { Functions int SelfIso int TotalLocals int64 TotalExternals int64 DistinctHash24 int IsoCollisions int PairsChecked int LargestLocals int LargestFuncName string } // AuditCorpus walks the ast/ directory of a corpus and measures, per function // AST dump, the self-isomorphism and the cross-function selectivity of the // signatures. // // The moxie audit tests each signature against itself, which cannot fail for // any function whose extraction produced a signature; the number is 100% by // construction. The measurement that carries information is the last two // fields: how many distinct 24-bit hashes the signatures produce, and how many // of the compared pairs are fully isomorphic for different functions. func AuditCorpus(corpusDir string) (*AuditReport, error) { astDir := filepath.Join(corpusDir, "ast") entries, err := os.ReadDir(astDir) if err != nil { return nil, err } rep := &AuditReport{} type since struct { name string sig *BindingSignature } var sigs []since for _, e := range entries { if e.IsDir() { continue } name := e.Name() if !strings.Contains(name, "func_") && !strings.Contains(name, "metho") { continue } data, err := os.ReadFile(filepath.Join(astDir, name)) if err != nil { return nil, err } st := ExtractSymbols(string(data)) bg := ExtractBindings(st) sig := SignatureWithTypes(st) rep.Functions++ if sig.IsIsomorphic(sig) { rep.SelfIso++ } rep.TotalLocals += int64(len(bg.Bindings)) rep.TotalExternals += int64(len(bg.Externals)) if len(bg.Bindings) > rep.LargestLocals { rep.LargestLocals = len(bg.Bindings) rep.LargestFuncName = name } sigs = append(sigs, since{name: name, sig: sig}) } hashes := make(map[uint32]struct{}, len(sigs)) for _, s := range sigs { hashes[SignatureHash24(s.sig)] = struct{}{} } rep.DistinctHash24 = len(hashes) sort.Slice(sigs, func(i, j int) bool { return sigs[i].name < sigs[j].name }) n := len(sigs) for i := 0; i < n; i++ { limit := i + 51 if limit > n { limit = n } for j := i + 1; j < limit; j++ { rep.PairsChecked++ if sigs[i].sig.IsIsomorphic(sigs[j].sig) { rep.IsoCollisions++ } } } return rep, nil } // SelfIsoRate is the percentage of functions whose signature is isomorphic to // itself. func (r *AuditReport) SelfIsoRate() int { if r.Functions == 0 { return 0 } return r.SelfIso * 100 / r.Functions } // HashUniqueness is the percentage of functions with a distinct 24-bit hash. func (r *AuditReport) HashUniqueness() int { if r.Functions == 0 { return 0 } return r.DistinctHash24 * 100 / r.Functions }