makiri 0.3.0-aarch64-linux → 0.5.0-aarch64-linux

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,266 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Allocation-failure injection sweep for the C extension (run via `rake oom`).
4
+ #
5
+ # The sanitizers and the leak gate prove the happy path is memory-safe; neither
6
+ # proves the OOM branches are CORRECT. Makiri's contract is fail-closed: when a
7
+ # core C allocation fails, a call must either raise a clean Makiri::Error /
8
+ # NoMemoryError or complete with the exact same result as the unfailed run -
9
+ # never a truncated/partial result (the property the XPath node-set caps and
10
+ # the "build OOM -> walk fallback" designs exist for). This gate machine-checks
11
+ # that contract: with the ext built under MAKIRI_ALLOC_INJECT=1, every core
12
+ # allocation site routes through a hook that can be armed to fail the nth
13
+ # attempt once. For each representative workload we record a failure-free
14
+ # BASELINE result and the total number of allocation attempts, then re-run the
15
+ # workload once per allocation site with exactly that site failing, and verify
16
+ # each run either raised cleanly or returned a baseline-identical value.
17
+ #
18
+ # A segfault/abort kills this process; the caller (rake/CI) sees the nonzero
19
+ # exit, which is the verdict too.
20
+ #
21
+ # bundle exec rake oom # rebuild + sweep
22
+ # bundle exec ruby -Ilib script/check_alloc_failures.rb # sweep current build
23
+
24
+ require "makiri"
25
+
26
+ unless Makiri.send(:__alloc_inject?)
27
+ abort "check_alloc_failures: extension built without the injection hook - " \
28
+ "rebuild with MAKIRI_ALLOC_INJECT=1 (`rake oom` does this)"
29
+ end
30
+
31
+ # Each scenario runs one workload END-TO-END and returns a canonical String, so
32
+ # an injected run's result can be compared (==) against the baseline. Fixtures
33
+ # are built INSIDE the lambda (unless reuse is the point) so the sweep covers
34
+ # their parse/build allocations too.
35
+ SCENARIOS = {
36
+ # XML parse covering the syntax surface: declaration, DOCTYPE (SYSTEM id +
37
+ # internal subset), default + prefixed namespaces, prefixed attributes,
38
+ # references, comment, CDATA, PI, nesting, CRLF normalization in an attr.
39
+ "xml_parse" => lambda do
40
+ src = <<~XML
41
+ <?xml version="1.0" encoding="UTF-8"?>
42
+ <!DOCTYPE root SYSTEM "urn:example:dtd" [<!ENTITY local "subset">]>
43
+ <root xmlns="urn:d" xmlns:p="urn:p" p:pa="pv" mixed="A&amp;&#x41; x\r\ny">
44
+ <!-- a comment -->
45
+ <p:branch><leaf depth="2">text &amp; &#x41; refs</leaf></p:branch>
46
+ <![CDATA[raw < cdata & bytes]]>
47
+ <?pi-target some data?>
48
+ <empty/>
49
+ </root>
50
+ XML
51
+ Makiri::XML::Document.parse(src).to_xml
52
+ end,
53
+
54
+ # Fragment parse + serialize + splice into a host document.
55
+ "xml_fragment" => lambda do
56
+ doc = Makiri::XML::Document.parse("<r xmlns='urn:d'><keep>k</keep></r>")
57
+ frag = doc.fragment("<a xmlns:p='u'><p:b>t</p:b></a>text")
58
+ out = frag.to_xml
59
+ doc.root.add_child(frag)
60
+ out + doc.to_xml
61
+ end,
62
+
63
+ # XPath battery: predicates, functions, a union, axes, plus an XPathContext
64
+ # evaluation with a registered namespace and variable.
65
+ "xml_xpath" => lambda do
66
+ doc = Makiri::XML::Document.parse(<<~XML)
67
+ <root xmlns:p="urn:p">
68
+ <a v="1">alpha</a>
69
+ <a v="2">beta</a>
70
+ <b n="3"> gamma delta </b>
71
+ <p:c><a v="9">nested</a></p:c>
72
+ </root>
73
+ XML
74
+ canon = lambda do |r|
75
+ r.is_a?(Makiri::NodeSet) ? r.map(&:to_xml).join("|") : r.inspect
76
+ end
77
+ exprs = [
78
+ "//a[@v='2']",
79
+ "//a[position()=2]",
80
+ "//a[last()]",
81
+ "count(//a)",
82
+ "sum(//b/@n)",
83
+ "concat(string(//a[1]), '-', substring('abcdef', 2, 3))",
84
+ "translate('abc', 'abc', 'xyz')",
85
+ "normalize-space(//b)",
86
+ "contains(//a[1], 'alp')",
87
+ "starts-with(//b, ' g')",
88
+ "//a | //b",
89
+ "//a[1]/ancestor::root",
90
+ "//a[1]/following-sibling::b",
91
+ "//root/descendant-or-self::a",
92
+ ]
93
+ parts = exprs.map { |e| canon.call(doc.xpath(e)) }
94
+ ctx = Makiri::XPathContext.new(doc)
95
+ ctx.register_namespace("p", "urn:p")
96
+ ctx.register_variable("want", "9")
97
+ parts << canon.call(ctx.evaluate("//p:c/a[@v=$want]"))
98
+ parts.join("\n")
99
+ end,
100
+
101
+ # Same battery shape over an HTML5-parsed document.
102
+ "html_xpath" => lambda do
103
+ doc = Makiri::HTML::Document.parse(<<~HTML)
104
+ <html><body>
105
+ <div id="top"><p class="x">one</p><p class="y">two</p></div>
106
+ <ul><li data-n="1">a</li><li data-n="2"> b c </li></ul>
107
+ </body></html>
108
+ HTML
109
+ canon = lambda do |r|
110
+ r.is_a?(Makiri::NodeSet) ? r.map(&:to_html).join("|") : r.inspect
111
+ end
112
+ exprs = [
113
+ "//p[@class='y']",
114
+ "//li[position()=2]",
115
+ "//li[last()]",
116
+ "count(//p)",
117
+ "sum(//li/@data-n)",
118
+ "concat(string(//p[1]), '+', substring(//p[2], 1, 2))",
119
+ "translate('one', 'one', 'uno')",
120
+ "normalize-space(//li[2])",
121
+ "contains(//p[1], 'on')",
122
+ "starts-with(//p[2], 'tw')",
123
+ "//p | //li",
124
+ "//p[1]/ancestor::div",
125
+ "//p[1]/following-sibling::p",
126
+ "//div/descendant-or-self::p",
127
+ ]
128
+ parts = exprs.map { |e| canon.call(doc.xpath(e)) }
129
+ ctx = Makiri::XPathContext.new(doc)
130
+ ctx.register_variable("cls", "x")
131
+ parts << canon.call(ctx.evaluate("//p[@class=$cls]"))
132
+ parts.join("\n")
133
+ end,
134
+
135
+ # The mutation surface: create_*, insertion on every side, rename, content,
136
+ # attributes, replace, remove, and a fragment splice.
137
+ "xml_mutate" => lambda do
138
+ doc = Makiri::XML::Document.parse("<root><old>x</old><gone/></root>")
139
+ el = doc.create_element("made")
140
+ el.add_child(doc.create_text_node("inner"))
141
+ el["k"] = "v"
142
+ doc.root.add_child(el)
143
+ el.name = "renamed"
144
+ el.content = "rewritten"
145
+ el.add_previous_sibling(doc.create_element("before"))
146
+ el.add_next_sibling(doc.create_element("after"))
147
+ doc.root.at_xpath("old").replace(doc.create_element("new"))
148
+ doc.root.at_xpath("gone").remove
149
+ doc.root.add_child(doc.fragment("<f1/>tail<f2 a='b'/>"))
150
+ doc.to_xml
151
+ end,
152
+
153
+ # Serialization over a non-trivial tree (~200 elements built inside the
154
+ # lambda, so the parse is swept too), both tree and deep serializers.
155
+ "html_serialize" => lambda do
156
+ body = (1..50).map { |i|
157
+ "<div id='d#{i}' class='row'><p>cell #{i}</p><span>tail &amp; #{i}</span></div>"
158
+ }.join
159
+ doc = Makiri::HTML::Document.parse("<html><body>#{body}</body></html>")
160
+ doc.to_html + doc.at_css("body").inner_html
161
+ end,
162
+
163
+ # Full-document text extraction (exercises the text-index build, and its
164
+ # fail-closed OOM -> walk fallback).
165
+ "html_text" => lambda do
166
+ body = (1..80).map { |i| "<p>para #{i} <em>em#{i}</em> tail</p>" }.join
167
+ doc = Makiri::HTML::Document.parse("<html><body>#{body}</body></html>")
168
+ doc.text
169
+ end,
170
+
171
+ # CSS: a comma list with combinators through the reused engine, plus the
172
+ # at_css first-match path.
173
+ "css" => lambda do
174
+ doc = Makiri::HTML::Document.parse(<<~HTML)
175
+ <html><body>
176
+ <p class="c">one</p><p>skip</p><p class="c">two</p>
177
+ <div><span>in</span></div><span>out</span>
178
+ <section id="x">target</section>
179
+ </body></html>
180
+ HTML
181
+ doc.css("p.c, div > span").map { |n| n.name }.join(",") +
182
+ doc.at_css("#x")&.name.to_s
183
+ end,
184
+
185
+ # The Builder DSL (pure Ruby over create_*/add_child, so this sweeps the
186
+ # construction factories).
187
+ "xml_builder" => lambda do
188
+ Makiri::XML::Builder.new do |xml|
189
+ xml.feed("xmlns" => "urn:a", "xmlns:dc" => "urn:dc") do
190
+ xml.entry do
191
+ xml.title("Hello")
192
+ xml["dc"].id_("42")
193
+ xml.cdata("a < b")
194
+ xml.comment(" note ")
195
+ end
196
+ end
197
+ end.to_xml
198
+ end,
199
+ }.freeze
200
+
201
+ ALLOWED = [Makiri::Error, NoMemoryError].freeze
202
+ TRUNCATE = 120
203
+
204
+ def disarm = Makiri.send(:__alloc_inject, 0)
205
+
206
+ failures_total = 0
207
+
208
+ SCENARIOS.each do |name, work|
209
+ # Warm twice with injection off: process-global engines (CSS) and lazy
210
+ # builds settle, so the counted run below is representative and stable.
211
+ disarm
212
+ 2.times { work.call }
213
+
214
+ # Counted baseline run: __alloc_inject(0) also resets the counter, so the
215
+ # calls reading right after is exactly this run's allocation-attempt total.
216
+ disarm
217
+ baseline = work.call
218
+ total = Makiri.send(:__alloc_inject_calls)
219
+
220
+ ok_raised = 0
221
+ ok_identical = 0
222
+ failures = []
223
+
224
+ (1..total).each do |n|
225
+ Makiri.send(:__alloc_inject, n)
226
+ begin
227
+ result = work.call
228
+ if result == baseline
229
+ ok_identical += 1
230
+ else
231
+ failures << [n, "truncated/wrong result",
232
+ "baseline=#{baseline.to_s[0, TRUNCATE].inspect} " \
233
+ "got=#{result.to_s[0, TRUNCATE].inspect}"]
234
+ end
235
+ rescue *ALLOWED
236
+ ok_raised += 1
237
+ rescue Exception => e # rubocop:disable Lint/RescueException -- the wrong class IS the finding
238
+ failures << [n, "wrong exception class",
239
+ "#{e.class}: #{e.message.to_s[0, TRUNCATE]}"]
240
+ ensure
241
+ disarm
242
+ end
243
+ end
244
+
245
+ failures_total += failures.size
246
+ puts format("%-16s allocations=%-5d raised=%-5d identical=%-5d failed=%d",
247
+ name, total, ok_raised, ok_identical, failures.size)
248
+ failures.each do |n, kind, detail|
249
+ puts " n=#{n} #{kind}: #{detail}"
250
+ end
251
+ if total.zero?
252
+ # A scenario that never reaches a core allocation sweeps nothing - that is
253
+ # a broken scenario, not a pass.
254
+ failures_total += 1
255
+ puts " scenario performed ZERO core allocations - workload not reaching the C core"
256
+ end
257
+ end
258
+
259
+ if failures_total.zero?
260
+ puts "check_alloc_failures: OK - every injected allocation failure failed closed " \
261
+ "(clean raise or baseline-identical result)"
262
+ else
263
+ puts "check_alloc_failures: FAILED - #{failures_total} injected failure(s) " \
264
+ "produced a wrong exception or a non-baseline result"
265
+ exit 1
266
+ end
@@ -8,9 +8,26 @@ require "yaml"
8
8
  ROOT = Pathname.new(__dir__).join("..").expand_path
9
9
  ALLOWLIST_PATH = ROOT.join("script/check_c_safety_allowlist.yml")
10
10
 
11
- Rule = Struct.new(:id, :message, :regex, keyword_init: true)
11
+ # A rule may carry `paths` (an array of path globs): it then applies ONLY to
12
+ # matching files. Used for the parser-TU reader discipline, where the ban is
13
+ # meaningful only in TUs whose input reads must go through mkr_span_t.
14
+ Rule = Struct.new(:id, :message, :regex, :paths, keyword_init: true)
12
15
  Finding = Struct.new(:path, :line, :rule, :text, keyword_init: true)
13
16
 
17
+ # Byte-scanning parser TUs: every input read goes through the bounded reader
18
+ # (core/mkr_span.h) - see its header comment. The rules below turn that from a
19
+ # convention into a machine-enforced invariant for these files.
20
+ PARSER_TUS = %w[
21
+ ext/makiri/xml/mkr_xml_tree.c
22
+ ext/makiri/xml/mkr_xml_chars.c
23
+ ext/makiri/xml/mkr_xml_node.c
24
+ ext/makiri/xpath/mkr_xpath_lex.c
25
+ ext/makiri/xpath/mkr_xpath_funcs_body.h
26
+ ext/makiri/xpath/mkr_xpath_value_body.h
27
+ ext/makiri/bridge/ruby_string.c
28
+ ext/makiri/dom_adapter/source_loc.c
29
+ ].freeze
30
+
14
31
  RULES = [
15
32
  Rule.new(
16
33
  id: "string_value_cstr",
@@ -60,7 +77,11 @@ RULES = [
60
77
  Rule.new(
61
78
  id: "verified_text_forge",
62
79
  message: "mkr_verified_text_t must be minted only by mkr_verified_text_from_view (the validated boundary)",
63
- regex: /\(\s*mkr_verified_text_t\s*\)\s*\{/
80
+ # Both forge shapes: the compound-literal cast AND the declaration
81
+ # initializer (`mkr_verified_text_t x = {...}`), which the cast-only regex
82
+ # used to miss - that gap let a fuzz harness mint over a non-NUL-terminated
83
+ # buffer unnoticed.
84
+ regex: /\(\s*mkr_verified_text_t\s*\)\s*\{|\bmkr_verified_text_t\s+\w+\s*=\s*\{/
64
85
  ),
65
86
  # --- HTML/XML representation boundary (see docs/html_xml_boundary_hardening) ---
66
87
  # These symbols assume one DOM representation; using them outside their
@@ -94,6 +115,27 @@ RULES = [
94
115
  "to dereference a node use mkr_html_node or mkr_xml_node_unwrap (kind-checked)",
95
116
  regex: /\bmkr_node_raw\s*\(/
96
117
  ),
118
+ # --- parser-TU reader discipline (see core/mkr_span.h) ---
119
+ # In the byte-scanning parser TUs every input read must go through the
120
+ # bounded reader: a raw libc scan reintroduces the "forgot the bounds check"
121
+ # class the span made structurally impossible. memcpy stays allowed (an
122
+ # explicit-length copy, not a scan).
123
+ Rule.new(
124
+ id: "raw_scan_call",
125
+ message: "parser TUs must read input through mkr_span_* / mkr_bytes_eq / mkr_utf8_* " \
126
+ "(core), not raw libc scanning",
127
+ regex: /\b(?:memchr|memcmp|strchr|strrchr|strstr|strn?cmp|strcspn|strspn|strpbrk|strtod|strtol|strtoull?|sscanf)\s*\(/,
128
+ paths: PARSER_TUS
129
+ ),
130
+ # The span's own cursor/bound fields are private to core/mkr_span.h: touching
131
+ # `.p` / `.end` in a parser TU is how a hand-rolled (uncovered) cursor starts.
132
+ Rule.new(
133
+ id: "raw_cursor_member",
134
+ message: "parser TUs must not access a span's .p/.end (or keep a raw cursor struct); " \
135
+ "use the mkr_span_* helpers (mark/since for slice capture)",
136
+ regex: /(?:->|\.)\s*(?:p|end)\b/,
137
+ paths: PARSER_TUS
138
+ ),
97
139
  ].freeze
98
140
 
99
141
  def load_config
@@ -163,6 +205,7 @@ def scan_findings(ignores)
163
205
  next [] unless code_line?(line)
164
206
 
165
207
  RULES.filter_map do |rule|
208
+ next if rule.paths && rule.paths.none? { |pat| path_matches?(pat, rel) }
166
209
  next unless line.match?(rule.regex)
167
210
  next if rule_ignored?(rel, rule.id, ignores)
168
211
 
@@ -33,20 +33,20 @@ ignore_paths:
33
33
  rule: html_doc_unwrap_boundary
34
34
  reason: the HTML branch of mkr_xpath_context_for, entered only after the XML kind returns early.
35
35
  # mkr_parsed_html_doc (asserts kind == HTML)
36
- - path: ext/makiri/lexbor_compat/compat.h
36
+ - path: ext/makiri/dom_adapter/compat.h
37
37
  rule: parsed_html_doc_boundary
38
38
  reason: declaration of the HTML parsed-document accessor.
39
- - path: ext/makiri/lexbor_compat/post_parse.c
39
+ - path: ext/makiri/dom_adapter/post_parse.c
40
40
  rule: parsed_html_doc_boundary
41
41
  reason: definition (the kind assert lives here) + HTML post-parse pipeline.
42
42
  - path: ext/makiri/glue/ruby_doc.c
43
43
  rule: parsed_html_doc_boundary
44
44
  reason: mkr_html_doc_unwrap is defined here over the HTML parsed document.
45
45
  # mkr_parsed_xml_doc (XML arena accessor) — kept out of the pure-HTML glue files
46
- - path: ext/makiri/lexbor_compat/compat.h
46
+ - path: ext/makiri/dom_adapter/compat.h
47
47
  rule: parsed_xml_doc_boundary
48
48
  reason: declaration of the XML parsed-document accessor.
49
- - path: ext/makiri/lexbor_compat/post_parse.c
49
+ - path: ext/makiri/dom_adapter/post_parse.c
50
50
  rule: parsed_xml_doc_boundary
51
51
  reason: definition + XML document wrapping/teardown.
52
52
  - path: ext/makiri/glue/ruby_xml.c
@@ -65,7 +65,7 @@ ignore_paths:
65
65
  rule: parsed_xml_doc_boundary
66
66
  reason: the kind-aware mkr_node_raw resolves an XML Document only after a MKR_DOC_XML check.
67
67
  # owner_document (HTML-only lxb_dom_node_t field)
68
- - path: ext/makiri/lexbor_compat/post_parse.c
68
+ - path: ext/makiri/dom_adapter/post_parse.c
69
69
  rule: owner_document_boundary
70
70
  reason: mkr_lxb_document_bytes resolves a Lexbor node's owner document to size its mraw pools (HTML-only; the XML serializer uses arena_bytes instead).
71
71
  - path: ext/makiri/glue/ruby_html_node.c
@@ -80,6 +80,9 @@ ignore_paths:
80
80
  - path: ext/makiri/xpath/mkr_xpath_node_access_html.h
81
81
  rule: owner_document_boundary
82
82
  reason: the HTML monomorphization of the engine's node-access layer.
83
+ - path: ext/makiri/dom_adapter/cross_import.c
84
+ rule: owner_document_boundary
85
+ reason: mkr_html_ns_uri reads the SOURCE HTML node's owner document ns table to resolve its namespace id to a URI; reached only on the HTML (lxb) side of HTML->XML translation, never on an XML node (no cross-kind document comparison).
83
86
  # mkr_node_raw (kind-agnostic void* raw pointer; never dereferenced as a typed node)
84
87
  - path: ext/makiri/glue/glue.h
85
88
  rule: node_raw_boundary
@@ -93,3 +96,22 @@ ignore_paths:
93
96
  - path: ext/makiri/glue/ruby_node_set.c
94
97
  rule: node_raw_boundary
95
98
  reason: NodeSet.new stores representation-opaque pointers; mkr_node_raw takes a seed node's pointer only after same-document validation guarantees its kind matches the set.
99
+
100
+ # --- parser-TU reader discipline (raw_scan_call / raw_cursor_member) ---
101
+ allowlist:
102
+ - path: ext/makiri/xpath/mkr_xpath_funcs_body.h
103
+ rule: raw_scan_call
104
+ max: 3
105
+ reason: "mkr_lookup_function's three strcmp over compile-time function-name tables: both sides are NUL-terminated (table literals / owned AST text), and the lookup signature takes bare const char* from the evaluator."
106
+
107
+ # --- verified_text_forge: the two Ruby-free test entry points. Neither can use
108
+ # mkr_verified_text_from_view (bridge = Ruby boundary), so each mints the
109
+ # token itself and must supply the contract by construction. ---
110
+ - path: ext/makiri/xpath/mkr_xpath_xml_selftest.c
111
+ rule: verified_text_forge
112
+ max: 2
113
+ reason: "Selftest expressions are compile-time string literals: NUL-terminated, NUL-free, valid UTF-8 by construction."
114
+ - path: ext/makiri/fuzz/xpath_fuzz.c
115
+ rule: verified_text_forge
116
+ max: 1
117
+ reason: "The libFuzzer harness mints over an owned mkr_strndup copy, which supplies NUL-termination and no-interior-NUL; UTF-8 validity is deliberately left to the lexer's strict decoder (its rejection path is fuzz-target behavior)."
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Malloc-leak gate for the C extension (macOS only; run via `rake leaks`).
4
+ #
5
+ # ASan runs everywhere with detect_leaks=0 (Ruby and Lexbor are uninstrumented,
6
+ # so LeakSanitizer drowns in their noise) - which means plain leaks were never
7
+ # machine-checked. This gate fills that hole with macOS's `leaks` tool: it runs
8
+ # script/leaks_harness.rb (the public surface in a loop, INCLUDING rescued
9
+ # failure paths) under MallocStackLogging, then scans the leak report for
10
+ # allocation stacks that (a) pass through makiri.bundle and (b) repeat in
11
+ # proportion to the loop count - i.e. a leak per call, which is what a missing
12
+ # free on some path looks like. One-time Init allocations and Ruby's own
13
+ # at-exit/unscannable noise stay at 1-2 instances and are ignored.
14
+ #
15
+ # Found (and since fixed) by this harness: the transient fragment document
16
+ # leaked by every inner_html=/outer_html=, and the partially-built step leaked
17
+ # by every failing XPath parse.
18
+ #
19
+ # ruby script/check_leaks.rb # threshold = ITERATIONS / 4
20
+ # LEAKS_ITERATIONS=200 rake leaks # more iterations, sharper signal
21
+
22
+ require "rbconfig"
23
+ require "tempfile"
24
+
25
+ abort "check_leaks: the `leaks` tool is macOS-only" unless RUBY_PLATFORM.include?("darwin")
26
+
27
+ iterations = Integer(ENV.fetch("LEAKS_ITERATIONS", "120"))
28
+ threshold = [iterations / 4, 10].max
29
+ harness = File.expand_path("leaks_harness.rb", __dir__)
30
+ lib = File.expand_path("../lib", __dir__)
31
+
32
+ out = Tempfile.create("makiri-leaks")
33
+ ok = system({ "MallocStackLogging" => "1", "LEAKS_ITERATIONS" => iterations.to_s },
34
+ "leaks", "--atExit", "--",
35
+ RbConfig.ruby, "-I#{lib}", harness,
36
+ out: out.path, err: out.path)
37
+ report = File.read(out.path)
38
+ # `leaks` exits non-zero whenever ANY leak exists (Ruby itself always reports
39
+ # some at-exit noise), so the exit status is not the verdict - the scan below
40
+ # is. But the harness itself must have completed.
41
+ abort "check_leaks: harness did not complete:\n#{report[-2000..]}" unless report.include?("leaks harness done")
42
+ abort "check_leaks: no leak report produced (leaks tool failed?)" unless report.include?("STACK OF") || ok
43
+
44
+ offenders = report.split(/\n(?=STACK OF )/).filter_map do |stanza|
45
+ next unless stanza.include?("makiri.bundle")
46
+
47
+ instances = stanza[/STACK OF (\d+) INSTANCES?/, 1].to_i
48
+ next if instances < threshold
49
+
50
+ frames = stanza.lines.grep(/makiri\.bundle/).first(4).map(&:strip)
51
+ [instances, frames]
52
+ end
53
+
54
+ if offenders.empty?
55
+ puts "check_leaks: OK - no repeated (>= #{threshold}x) leak stacks through makiri.bundle " \
56
+ "(#{iterations} iterations)"
57
+ else
58
+ puts "check_leaks: FAILED - #{offenders.size} repeated leak stack(s) through makiri.bundle:"
59
+ offenders.each do |instances, frames|
60
+ puts " #{instances}x:"
61
+ frames.each { |f| puts " #{f}" }
62
+ end
63
+ exit 1
64
+ end
@@ -0,0 +1,71 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Exercise script for the malloc-leak gate (script/check_leaks.rb runs this
4
+ # under macOS `leaks --atExit`). It loops the public surface - parsing, queries,
5
+ # serialization, mutation, fragments, the Builder, XPathContext - and, crucially,
6
+ # RESCUED FAILURE paths (raises that skip cleanup are where leaks hide; both
7
+ # leaks this gate was built on lived there or in a transient-document path).
8
+ #
9
+ # A per-call leak shows up as a leak stack with ~ITERATIONS instances, which the
10
+ # driver flags; one-time/Init allocations stay at 1-2 instances and pass.
11
+
12
+ require "makiri"
13
+
14
+ ITERATIONS = Integer(ENV.fetch("LEAKS_ITERATIONS", "120"))
15
+
16
+ HTML = "<div id=m class='a b'><ul><li class=item>x</li><li>y<svg><path/></svg></li></ul><p>t&amp;</p></div>"
17
+ XML = %(<r xmlns:p="urn:p" xmlns="urn:d"><a id="1">t</a><p:b/><!--c--><![CDATA[z]]></r>)
18
+ CSS = "div.a, #b > span { color: red !important; --v: 1px }\n" \
19
+ "@media (min-width: 600px) { .x { opacity: 0 } }\n@font-face { font-family: y }"
20
+
21
+ handler = Class.new { def my_fn(nodes) = nodes.length.to_s }.new
22
+
23
+ ITERATIONS.times do |i|
24
+ # --- HTML: parse / query / serialize / mutate / fragments ---
25
+ d = Makiri::HTML(HTML)
26
+ d.css("li.item"); d.at_css("#m"); d.at_css("li").matches?("li")
27
+ begin d.css("li[") rescue Makiri::CSS::SyntaxError; end # selector syntax error (engine reset path)
28
+ d.xpath("//li"); d.at_xpath("//p"); d.xpath("count(//li)")
29
+ begin d.xpath("//li[") rescue Makiri::XPath::SyntaxError; end # parse failure (partial-AST/step cleanup)
30
+ begin d.xpath("//li", handler) rescue nil; end
31
+ d.xpath("//*[local-name()='path']")
32
+ d.to_html; d.at_css("ul").inner_html; d.to_html(pretty: true); d.text
33
+ e = d.at_css("li"); e["k#{i}"] = "v"; e.name = "li2"; e.content = "c"
34
+ e.set_attribute_ns("urn:x", "x:y", "1"); e.remove_attribute_ns("urn:x", "y")
35
+ d.at_css("ul").inner_html = "<li>new</li>" # transient fragment document path
36
+ frag = d.fragment("<b>f</b>"); d.at_css("p") << frag
37
+ Makiri::DocumentFragment.parse("<tr><td>1</td></tr>", context: "tbody")
38
+ d.at_css("p").clone_node(true); d.dup
39
+ begin d.fragment("x", context: "no-such-tag") rescue ArgumentError; end
40
+
41
+ # --- XML: parse (ok + failures) / query / serialize / mutate / Builder ---
42
+ x = Makiri::XML(XML)
43
+ begin Makiri::XML("<r>\xC3</r>".b) rescue Makiri::XML::SyntaxError; end
44
+ begin Makiri::XML("<r><a></r>") rescue Makiri::XML::SyntaxError; end
45
+ begin Makiri::XML("<r/>", max_bytes: 1) rescue Makiri::XML::LimitExceeded; end
46
+ begin Makiri::XML(%(<?xml version="1.1"?><r/>)) rescue Makiri::XML::SyntaxError; end
47
+ x.xpath("//d:a", "d" => "urn:d"); x.at_xpath("//p:b", "p" => "urn:p")
48
+ begin x.xpath("//unbound:a") rescue Makiri::Error; end
49
+ x.css("a"); x.at_css("p|b", "p" => "urn:p")
50
+ begin x.css("a[") rescue Makiri::CSS::SyntaxError; end
51
+ x.to_xml; x.to_xml(pretty: true); x.root.canonicalize
52
+ el = x.create_element("n", "t", "k" => "v"); x.root.add_child(el)
53
+ begin x.root.add_child(x.create_element("zz:q")) rescue Makiri::Error; end
54
+ x.root.children.first.replace(x.create_element("rep")); x.fragment("<f1/><f2/>")
55
+ Makiri::XML::Builder.new { |b| b.root("xmlns:d" => "urn:d") { b.item("a"); b["d"].q } }.to_xml
56
+
57
+ # --- XPathContext: AST cache / registrations / failing evaluate ---
58
+ ctx = Makiri::XPathContext.new(x)
59
+ ctx.register_namespace("d", "urn:d"); ctx.register_variable("v", "1")
60
+ ctx.evaluate("//d:a[@id=$v]"); ctx.evaluate("//d:a[@id=$v]")
61
+ begin ctx.evaluate("//(") rescue Makiri::XPath::SyntaxError; end
62
+
63
+ # --- Lexbor CSS stylesheet parser (per-call parser+stylesheet lifetime,
64
+ # freed under rb_ensure) including the NUL-reject raise path ---
65
+ Makiri::Lexbor::CSS.parse_stylesheet(CSS)
66
+ begin Makiri::Lexbor::CSS.parse_stylesheet("a{}\0x") rescue Makiri::Error; end
67
+ end
68
+
69
+ GC.start
70
+ GC.start
71
+ puts "leaks harness done (#{ITERATIONS} iterations)"