logo raviqqe's logbook

Security audit of Melior

Summary

Scope and method

Severity

SeverityMeaning
CriticalArbitrary memory reads or writes from safe code or untrusted input
HighMemory unsafety or a crash from safe code or untrusted input in common use
MediumWrong results, aborts or contract violations with limited reach
LowEdge cases, panics and leaks
InformationalDocumentation, tests and hygiene

Overview

PackageCriticalHighMediumLowInformational
melior11419207
melior-macro024104
melior-kaleidoscope015104
Repository00123

Fixed findings

IDFindingFixed by
MEL-01Dense elements with a non-builtin element type were read as strings, an arbitrary read#1037
MEL-02Dense element count times width wrapped, so element accessors read out of bounds#1039, #1040
MEL-27Pattern benefits are 16 bits in MLIR, so 65535 never fired and 65537 acted as 1#1042 (merged through #1041)
MEL-39Rewrite patterns and pattern sets carried no context lifetime#1041

melior

Critical

MEL-47: A parenthesized pair in a dense literal reads out of bounds

High

MEL-03: Safe rewriter methods free IR that live handles still reference

MEL-04: Operations don’t keep the owners of their operands alive

MEL-05: Moving operations and blocks between owners is invisible to the borrow checker

MEL-06: Structural preconditions of block and operation manipulation are unchecked

MEL-07: Kind casts without a check

MEL-08: Unchecked constructors build objects whose accessors corrupt memory

MEL-09: Result type inference runs on unverified operands

MEL-10: Null handles are wrapped in non-nullable types

MEL-11: LLVM dialect type constructors need the dialect loaded

MEL-48: Hex literals with wrapped element counts crash MLIR

MEL-49: Loading a dialect after its operations exist leaves dangling operation names

MEL-50: Nested pass manager handles dangle after a run or pipeline parsing

MEL-51: Type::parse and Attribute::parse crash on an empty string

MEL-52: More MLIR crashes from IR text

Medium

MEL-12: Callback contracts are not enforced

MEL-13: Unverified IR reaches passes, translation and the JIT

MEL-14: Pass registration functions race on MLIR’s global registry

MEL-15: Bytes of printed text that aren’t UTF-8 abort diagnostic handlers

MEL-16: MemRefType::strides_and_offset ignores failure

MEL-17: IntegerAttribute accessors truncate wide values

MEL-18: The *Like traits are safe and unsealed

MEL-19: Deeply nested input overflows the stack

MEL-20: cf::switch doesn’t validate list lengths or case values

MEL-21: cf::cond_br derives segment sizes from block argument counts

MEL-22: llvm::call_intrinsic never builds a valid operation

MEL-23: arith::addui_extended panics on every call

MEL-24: llvm::attributes::linkage(Linkage::LinkOnce) panics

MEL-53: Dropping an ExecutionEngine runs code from the module

MEL-54: Nested external passes race on shared IR

MEL-55: Safe calls that abort the process

MEL-56: LLVM dialect element types are not validated, and verified modules crash translation

MEL-57: verify(), Display and Debug segfault on three terminators in a detached block

MEL-58: IntegerAttribute::new zero-extends negative values above 64 bits

Low

IDFindingLocationStatus
MEL-25Leaks: a dropped OperationBuilder leaks its arrays and regions; RewritePattern and Pass have no destructor; RewriterBase::insert without an insertion point leaves the operation detached and unownedir/operation/builder.rs:20-23; rewrite_pattern.rs:17-22; pass.rs:41-46; ir_rewriter.rs:128-130Read; insert reproduced
MEL-26Panics where errors are expected: Module::parse on an interior NUL; previous_in_block is todo!(); fused_location indexes unchecked; constructors based on inference expect when the dialect is not loadedir/module.rs:34; ir/operation/operation_like.rs:242-245; ir/location.rs:166-177; dialect/arith.rs:23, :128; dialect/index.rs:24-61; dialect/memref.rs:116, :269, :278NUL reproduced; read
MEL-28Silent no-ops: set_operands on an operation without operands such as arith.constant; replace_all_op_uses_with_values replaces only a prefix on a count mismatch; ExecutionEngine::new accepts any optimization level; dump_to_object_file reports nothingir/operation/operation_like.rs:536-544; ir_rewriter.rs:325-338; execution_engine.rs:15-42, :87-89Operands and level reproduced; read
MEL-29Integer conversions truncate or change sign: u64 dimensions (1 << 63 becomes dynamic), usize positions narrowed to 32 bits (multi_dim_identity(&context, 1 << 32) has no dimensions), IntegerAttribute::new(i8, 300) is 44, and lines and columns of locationsir/type/ranked_tensor.rs:19-46; ir/affine_expr.rs:39-46; ir/affine_map.rs; ir/location.rs:35-44Reproduced by a sub-audit
MEL-30TypeId::create returns an unbounded lifetime, so a pass ID can come from a dead local; Allocator::allocate_type_id(&mut self) allows one live IDir/type/id.rs:19-54; ir/type/id/allocator.rs:22-24; pass/external.rs:177-179Reproduced by a sub-audit
MEL-31Checked constructors can’t express defaults, and parameter orders and dimension types differ between siblingsir/type/ranked_tensor.rs:31-46; ir/type/mem_ref.rs:38-55Reproduced by a sub-audit
MEL-32Dense elements: a single value is accepted for a zero-element shape; raw_data() returns a pointer without a length; padding bits are not maskedir/attribute/dense_elements.rs:173-189, :273-283, :491-501Reproduced by a sub-audit
MEL-33is_multiple_of(0) and i64::MIN operands reach undefined integer arithmetic in MLIR, which doesn’t trap on Armir/affine_expr.rs:59-61, :103-105, :173-175Read
MEL-34memref::view attaches a stray operand_segment_sizes attribute, and five constructors rely on the legacy aliasdialect/memref.rs:68, :150-153, :180; dialect/cf.rs:71, :147Reproduced by a sub-audit
MEL-35llvm::alloca with default options omits the required elem_type, and the documentation of AllocaOptions is staledialect/llvm.rs:163-176; dialect/llvm/alloca_options.rs:22, :33Reproduced by a sub-audit
MEL-36Helper traits: gep always returns address space 0; GepIndex::Const(i32::MIN) collides with the dynamic marker; alloca alignment is unchecked; store and memcpy reverse the parameter order of the dialect; append_op_result appends before checkinghelpers/llvm.rs:95-111, :248-251, :303-313; helpers/builtin.rs:22-24Reproduced by a sub-audit
MEL-37Duplicate attribute keys: add_attributes appends, so extra attributes of func::func can override sym_name or repeat a key, and the printed form doesn’t parse backir/operation/builder.rs:117-132; dialect/func.rs:67-72; dialect/llvm.rs:218-223Reproduced by a sub-audit
MEL-38melior::dialect! is exported regardless of features, but its output names a module that needs ods-dialects, and CI never builds the default features alonelib.rs:48; dialect.rs:21-22Reproduced by a sub-audit
MEL-59A pattern callback can re-enter itself by applying the frozen set that contains it; the inner call freed a Vec the outer one still borrowed. It needs a leaked &'static Context. Same class as MEL-12rewrite_pattern.rs:52-68Reproduced
MEL-60Unchecked constructors build values that pass verify() but that MLIR can’t parse back: vector<0xi32>, tensor<2xnone>, memref<-5xf32>, and a FloatAttribute of type index. Extends MEL-07 and MEL-08ir/type.rs:157-165, :184-205; ir/type/ranked_tensor.rs:19-28; ir/type/mem_ref.rs:20-35, :58-71; ir/attribute/float.rs:19-27Reproduced by a sub-audit
MEL-61DictionaryAttribute::new accepts duplicate keys, and the printed form doesn’t parse back. Same defect as MEL-37 through another APIir/attribute/dictionary.rs:16-28Reproduced by a sub-audit
MEL-62Dense elements with a dialect element type such as !tosa.mxint8 can only be parsed; new, splat and raw_buffer always fail for themir/attribute/dense_elements.rs:173-189, :474-489, :536-555Reproduced by a sub-audit
MEL-63Silent no-ops that extend MEL-28: driver limits of 0 or below −1 return Ok without calling any pattern; ExecutionEngine::new ignores a library that fails to load; functions reached through lookup run without global constructorsgreedy_rewrite_driver.rs:108-120; execution_engine.rs:22-47Limits reproduced; partly read
MEL-64arith::constant panics for any attribute without a type when the dialect is loaded. Extends MEL-26dialect/arith.rs:14-24Reproduced by a sub-audit
MEL-65memref::global without a value emits an uninitialized definition, and an external declaration can’t be expresseddialect/memref.rs:230-233Reproduced by a sub-audit

Locations in this table are relative to melior/src/.

Informational

IDFindingLocation
MEL-40The README’s safety section cites Region::append_block, which owner lifetimes already prevent, and omits the classes above other than the parser defects documented by #1044README.md:101-118
MEL-41Reference types are transmuted to owned types without #[repr(transparent)], add_regions_vec transmutes a Vec, and about 600 unsafe blocks have no safety commentir/block.rs:175-181; ir/region.rs:107-113; ir/operation.rs:159-164, :275-281; context.rs:216-221; ir/operation/builder.rs:83-96; lib.rs:2-3
MEL-42DistinctAttribute can’t be named outside the crateir/attribute.rs:20-33
MEL-43A panic in the caller’s fmt::Write aborts inside the print callback, and error paths format the whole valueutility.rs:91-107
MEL-44Documentation drift: the range of shift_dims, is_pure_affine, “only valid if” on safe functions, the feature comment in Cargo.toml, extsi and trunci documented as arith.extui, and an incomplete safety section of invoke_packedir/affine_expr.rs:156-200; ir/type.rs:141; Cargo.toml:24-25
MEL-45Test gaps: no tests of wrong kinds or boundaries for the findings above; dump_to_object_file writes to a fixed /tmp/melior/test.o and asserts nothing; the enable_ir_printing test is commented out; convert_module never lowers arith; helpers have no testsexecution_engine.rs:147-173; pass/manager.rs:172-178; dialect/llvm.rs:394-410
MEL-46Coverage: 21 mlirCreate* passes are not wrapped, 16 registered dialects have no generated module, ods::transform has 37 of 234 operations, and there are 15 dialect handlespass/*.rs; dialect/ods.rs; dialect/handle.rs

Locations in this table are relative to melior/src/, except for the README and Cargo.toml.

Reviewed without findings

melior-macro

High

MAC-01: Generated safe builders run type inference on unverified operands

MAC-16: Removing or mistyping a default-valued attribute leaves a verified operation that segfaults

Medium

MAC-02: Valid ODS names make the macro panic or emit invalid identifiers

MAC-03: Generated names collide with ODS names

MAC-04: SameVariadic*Size with an optional element doesn’t compile

MAC-17: Values of the wrong kind for attributes typed as plain Attribute are discarded silently

Low

IDFindingLocationStatus
MAC-05Unnamed regions and successors reject the whole dialect, although mlir-tblgen accepts themdialect/operation.rs:279-300Reproduced by a sub-audit
MAC-06Derived attributes are named after the anonymous record and read from the dictionary (anonymous_365()). It affects custom ODS only, since no installed dialect has a derived attributedialect/operation.rs:480-499Reproduced by a sub-audit
MAC-07Accessors overflow on operations that don’t match the ODS layout, because TryFrom checks only the namedialect/generation/element_accessor.rs:34, :41, :67, :100-103Reproduced by a sub-audit
MAC-08Constructors panic on an empty variadic first operand and on inference failure. It affects exactly irdl.all_of, irdl.any_of and transform.merge_handlesdialect/generation/operation_builder.rs:229-230, :300-303Reproduced by a sub-audit
MAC-09Setters of optional attributes can be called twice, giving duplicate dictionary keysdialect/generation/operation_builder.rs:183-199Reproduced
MAC-10The build script runs llvm-config through a shell with an unquoted prefix, ignores failure, which leaves an empty include directory, and doesn’t rerun when LLVM changesbuild.rs:11, :25-43Reproduced
MAC-11.td files and environment variables read by dialect! don’t trigger recompilationdialect.rs:29-47Reproduced by a sub-audit
MAC-12dialect! without files segfaults the compiler, and a .td file without the classes Dialect or Op makes it exitdialect.rs:41-47, :52, :69-70Reproduced by a sub-audit
MAC-18Properties that aren’t attributes are dropped, so seven bundled operations lose flags: llvm.add, sub, mul, shl, trunc, llvm.getelementptr and affine.linearize_indexdialect/operation.rs:391-408, :460-478Reproduced by a sub-audit
MAC-19On dialects not registered in MLIR, default-valued attributes have no default, so the accessor returns an error, and set_flag(false) on a unit attribute leaves it presentdialect/generation/attribute_accessor.rs:17-31Reproduced by a sub-audit

Locations in this table are relative to melior-macro/src/, except for build.rs.

Informational

IDFindingLocation
MAC-13files paths are spliced unescaped into TableGen source, and the working directory of the compiler shadows include directoriesdialect.rs:42-44, :105-116
MAC-14Two UI tests reach their .td files relative to the target directory and fail under CARGO_TARGET_DIR, and there are no tests for the operation enum, successor accessors, removers, or default-valued and unit attributestests/ui/unnamed_result_conflicting_with_*.rs:4
MAC-15Builders accept unequal SameVariadic*Size groups, and accessors then return wrong rangesdialect/generation/operation_builder.rs:203-213
MAC-20The macro accepts ODS that mlir-tblgen rejects: one variadic group with a segment trait, both size traits together, unnamed attributes, and a variadic region that is not lastdialect/operation.rs:417-429, :463-466; dialect/generation/region_accessor.rs:9-13

Reviewed without findings

melior-kaleidoscope

The Toy compiler (publish = false) miscompiled no valid program: a sub-audit compared about 10,000 generated programs against an independent reference interpreter, optimized and unoptimized, without a mismatch. Two fuzzers with 5,000 mutated and 3,000 random programs produced only exit statuses 0 and 1.

High

KAL-01: Crafted .mlir input crashes the compiler with use-after-free

Medium

KAL-02: Unbounded recursion aborts on small sources

KAL-03: Broadcast constants are expanded element by element

KAL-04: Inlining is exponential on doubling call chains

KAL-05: Reshape folding accepts mismatched element counts and fabricates data

KAL-17: Tensor rank is unbounded, so a flat shape list overflows the stack inside MLIR

Low

IDFindingLocationStatus
KAL-06A zero-sized dimension bypasses the size bound: var a<1152921504606846975, 0> = 1; print(a); printed 279 MB of newlines in 10 secondsgenerate/module.rs:188-196; lower_to_affine.rs:286-316Reproduced
KAL-07inline_functions takes &Module but erases functions, so handles held by the caller dangleinliner.rs:18, :41-47, :159-160Reproduced by a sub-audit
KAL-08run_jit is safe but assumes that main takes and returns nothing; a main in a .mlir file with a memref parameter segfaultscompile.rs:88-95; lower_to_llvm.rs:75-90Reproduced by a sub-audit
KAL-09Lowering patterns insert operations and then return false, which leaves stray memref.alloc pairs after a failed constantlower_to_affine.rs:126-137, :281-323, :453-466; lower_to_llvm.rs:120-182Reproduced by a sub-audit
KAL-10Missing semantic checks: a user function named transpose is silently shadowed; wrong arity passes --emit mlir; duplicate struct members are accepted; functions without a return value can’t be called; dead ill-typed code compilesgenerate/function.rs:115-147, :296-365; generate/module.rs:69-106Reproduced
KAL-11Late errors carry no source location or name the wrong cause, such as shape mismatches, a missing main and element count mismatchesshape_inference.rs:45-100; inliner.rs:109-115; compile.rs:92Reproduced by a sub-audit
KAL-12A comment that contains a lone carriage return is a syntax errorparse.rs:401-410Reproduced by a sub-audit
KAL-13A NUL byte in a .mlir input panics, with MEL-26 as its root causemain.rs:67Reproduced by a sub-audit
KAL-18A tensor passed for a struct parameter compiles and runs: def f(s Foo) { return s; } called with f([1, 2]) prints 1 2. Extends KAL-10generate/function.rs:338-365; inliner.rs:130-142; shape_inference.rs:77Reproduced
KAL-19A reshape of a reshape hides an invalid inner reshape: var a<5> = [1, 2, 3, 4, 5, 6]; var b<2, 3> = a; is accepted, while printing a directly is rejected. Extends KAL-05canonicalize.rs:168-174Reproduced

Locations in this table are relative to melior-kaleidoscope/src/.

Informational

IDFindingLocation
KAL-14Other super-linear behavior: nested struct types print exponentially (766 bytes of source gave 5.9 GB of output), --emit ast is cubic in the length of a chain, --optimize scales steeply with rank, and the inliner scans quadraticallygenerate/module.rs:77-103; main.rs:51; inliner.rs:32-74
KAL-15Test gaps: no reshape of a non-scalar splat, nesting limits, malformed MLIR structure, or comparison of optimized and unoptimized output, and examples/ast.toy promises an error that never occurstests/command.rs; examples/ast.toy:24-26
KAL-16The README doesn’t state the deviations from the tutorial language: parameters written as name Type, print only as a statement, rejected reshapes of computed values, no numbers with leading dots, and shape mismatches of + as errorsREADME.md
KAL-20Parser diagnostics name the wrong cause, such as expected `>` for a dimension out of rangeparse.rs:196-203, :301-332

Locations in this table are relative to melior-kaleidoscope/, and to its src/ for source files.

Reviewed without findings

The lexer and number parsing, scoping and struct handling, shape inference, the canonicalization rewrites, affine lowering, including loop bounds and the transpose mapping up to rank 6, LLVM lowering, the eight uses of ContextRef::to_ref, each of which binds the context reference to a local that outlives the reference, and the exit statuses of the command.

Repository

Medium

INF-01: Dependency updates merge with no human review

Low

INF-02: The release job runs unpinned tools while it can mint publishing credentials

INF-03: Sanitizer and feature coverage

Informational

INF-04: Smaller items

INF-05: The release dry run passes even when a crate fails to package

INF-06: The documentation site is stale

Not covered

Recommendations

  1. Fix MEL-51 and MAC-16. Both are small changes that close crashes in ordinary use.
  2. Fix MEL-49 by loading the dialect of a name when it is first used, and MEL-50 with exclusive borrows of the pass manager.
  3. Decide whether inference (MEL-09 and MAC-01) and the erasing rewriter methods (MEL-03) become unsafe. These two decisions close the most reachable crashes.
  4. Fix MEL-04, MEL-05 and MEL-06 with owner lifetimes for operands and structural checks, which need a design decision.
  5. Fix MEL-07, MEL-08, MEL-10 and MEL-11 with mechanical predicate and null checks that return Result.
  6. Report MEL-47 (with the prepared fix), MEL-48, MEL-52 and MEL-57 upstream, along with the verifier gaps behind MEL-56 and MAC-16.
  7. Fix INF-01, INF-02 and INF-05, and the constructors that always fail (MEL-22, MEL-23 and MEL-24) with a smoke test over every constructor.