libbin 2.0.0 → 2.1.0

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,387 @@
1
+ module LibBin
2
+
3
+ # Refinement to Range allowing reducing ranges through the + operator.
4
+ module RangeRefinement
5
+ refine Range do
6
+ # Union of two ranges.
7
+ # @return [Range]
8
+ def +(other)
9
+ return other.dup unless min
10
+ return self.dup unless other.min
11
+ Range.new(min <= other.min ? min : other.min,
12
+ max >= other.max ? max : other.max)
13
+ end
14
+ end
15
+ end
16
+
17
+ # Class that can be used to get the shape of a {Structure} or of a {Structure::Scalar}.
18
+ class DataRange
19
+ using RangeRefinement
20
+ attr_reader :range
21
+
22
+ # @overload initialize(min, max)
23
+ # Create a new shape starting at +min+ and ending at +max+.
24
+ # This shape has no members.
25
+ # @param min [Integer] start of the shape
26
+ # @param max [Integer] end of the shape
27
+ # @return [DataShape] a new DataShape
28
+ # @overload initialize(members)
29
+ # Creates a new shape by reducing the shape of its members.
30
+ # @param members [DataShape] the members composing the shape
31
+ # @return [DataShape] a new DataShape
32
+ def initialize(*args)
33
+ if args.length == 2
34
+ @range = Range.new(args[0], args[1])
35
+ else
36
+ list = args[0].kind_of?(Hash) ? args[0].values : args[0]
37
+ @range = list.compact.collect(&:range).compact.reduce(:+)
38
+ end
39
+ end
40
+
41
+ # Return the beginning of the shape.
42
+ # @return [Integer, nil]
43
+ def first
44
+ @range&.first
45
+ end
46
+
47
+ # Return the end of the shape.
48
+ # @return [Integer, nil]
49
+ def last
50
+ @range&.last
51
+ end
52
+
53
+ # Return the size of the shape.
54
+ # @return [Integer]
55
+ def size
56
+ @range ? @range.size : 0
57
+ end
58
+
59
+ # Return whether this shape represents anonymous padding.
60
+ # @return [Boolean]
61
+ def padding?
62
+ false
63
+ end
64
+
65
+ # @!visibility private
66
+ def __extend_range(min_off, max_off)
67
+ extra = Range.new(min_off, max_off)
68
+ @range = @range ? (@range + extra) : extra
69
+ self
70
+ end
71
+ end
72
+
73
+ # Default class used to get the shape of a {Structure} or of a {Structure::Scalar}.
74
+ # It maintains a memory of its members.
75
+ class DataShape # < DataRange
76
+ using RangeRefinement
77
+ attr_reader :members
78
+
79
+ # Shape class used for anonymous padding directives (`skip`, `align_to`).
80
+ class Padding < DataShape
81
+ # @return [Boolean] true
82
+ def padding?
83
+ true
84
+ end
85
+ end
86
+
87
+ # Add method readers for members.
88
+ def method_missing(m, *arg, &block)
89
+ return @members[m] if @members && @members.key?(m)
90
+ super
91
+ end
92
+
93
+ def respond_to_missing?(m, include_private = false)
94
+ (@members && @members.key?(m)) || super
95
+ end
96
+
97
+ # Represents one leaf field span in a {DataShape}.
98
+ Span = Struct.new(:path, :range, :padding, keyword_init: true) do
99
+ # @return [Integer]
100
+ def first
101
+ range.first
102
+ end
103
+
104
+ # @return [Integer]
105
+ def last
106
+ range.last
107
+ end
108
+
109
+ # @return [Integer]
110
+ def size
111
+ range.size
112
+ end
113
+
114
+ # @return [Boolean]
115
+ def padding?
116
+ !!padding
117
+ end
118
+ end
119
+
120
+ # Represents a byte range covered by two or more overlapping non-padding spans.
121
+ Overlap = Struct.new(:range, :entries, keyword_init: true) do
122
+ # @return [Integer]
123
+ def first
124
+ range.first
125
+ end
126
+
127
+ # @return [Integer]
128
+ def last
129
+ range.last
130
+ end
131
+
132
+ # @return [Integer]
133
+ def size
134
+ range.size
135
+ end
136
+ end
137
+
138
+ # @overload initialize(min, max)
139
+ # Create a new shape starting at +min+ and ending at +max+.
140
+ # This shape has no members.
141
+ # @param min [Integer] start of the shape
142
+ # @param max [Integer] end of the shape
143
+ # @return [DataShape] a new DataShape
144
+ # @overload initialize(members)
145
+ # Creates a new shape by reducing the shape of its members.
146
+ # Members can be accessed through {members}.
147
+ # @param members [DataShape] the members composing the shape
148
+ # @return [DataShape] a new DataShape
149
+ def initialize(*args)
150
+ @members = nil
151
+ @members = args[0] if args.length == 1
152
+ super
153
+ end
154
+
155
+ # Return flattened leaf spans from this shape hierarchy sorted by start/end offset.
156
+ # @param include_padding [Boolean] whether to include {DataShape::Padding} spans
157
+ # @param prefix [String, nil] optional path prefix
158
+ # @return [Array<Span>]
159
+ def leaves(include_padding: false, prefix: nil)
160
+ out = []
161
+ collect_leaves(self, prefix, include_padding, out)
162
+ out.sort_by! { |s| [s.first, s.last, s.path] }
163
+ out
164
+ end
165
+
166
+ # Return uncovered byte ranges within this shape's range (or +0...total_size+).
167
+ # @param total_size [Integer, nil] optional total stream/buffer byte size
168
+ # @param ignore_padding [Boolean] treat padding directives as gaps when true
169
+ # @return [Array<Range>]
170
+ def gaps(total_size: nil, ignore_padding: false)
171
+ if total_size
172
+ tot = Integer(total_size)
173
+ return [] if tot <= 0
174
+ win_start = 0
175
+ win_end = tot - 1
176
+ win_end = @range.last if @range && @range.size > 0 && @range.last > win_end
177
+ else
178
+ return [] if @range.nil? || @range.size <= 0
179
+ win_start = @range.first
180
+ win_end = @range.last
181
+ end
182
+
183
+ spans = leaves(include_padding: !ignore_padding).select { |s| s.range && s.range.size > 0 }
184
+ result = []
185
+ cursor = win_start
186
+ spans.each do |s|
187
+ next if s.last < cursor
188
+ break if s.first > win_end
189
+ result << (cursor..(s.first - 1)) if s.first > cursor
190
+ cursor = s.last + 1 if s.last + 1 > cursor
191
+ end
192
+ result << (cursor..win_end) if cursor <= win_end
193
+ result
194
+ end
195
+
196
+ # Detect overlapping non-padding byte ranges.
197
+ # @return [Array<Overlap>]
198
+ def overlaps
199
+ spans = leaves(include_padding: false).select { |s| s.range && s.range.size > 0 }
200
+ return [] if spans.length < 2
201
+
202
+ events = []
203
+ spans.each do |s|
204
+ events << [s.first, 1, s]
205
+ events << [s.last + 1, -1, s]
206
+ end
207
+ events.sort_by! { |pos, kind, _| [pos, kind] }
208
+
209
+ active = []
210
+ result = []
211
+ idx = 0
212
+ n = events.length
213
+ while idx < n
214
+ pos = events[idx][0]
215
+ while idx < n && events[idx][0] == pos
216
+ _, kind, s = events[idx]
217
+ if kind == 1
218
+ active << s
219
+ else
220
+ pos_idx = active.index(s)
221
+ active.delete_at(pos_idx) if pos_idx
222
+ end
223
+ idx += 1
224
+ end
225
+ next unless idx < n && active.length >= 2
226
+
227
+ next_pos = events[idx][0]
228
+ next unless next_pos > pos
229
+
230
+ seg = pos..(next_pos - 1)
231
+ entries = active.dup
232
+ if !result.empty? && result.last.last + 1 == seg.first && result.last.entries == entries
233
+ result[-1] = Overlap.new(range: (result.last.first..seg.last), entries: entries)
234
+ else
235
+ result << Overlap.new(range: seg, entries: entries)
236
+ end
237
+ end
238
+ result
239
+ end
240
+
241
+ # Render an aligned offset/size/field layout table for reverse-engineering.
242
+ # @param max_depth [Integer, nil] maximum nesting depth to expand
243
+ # @param total_size [Integer, nil] optional total stream/buffer byte size for gap reporting
244
+ # @param show_gaps [Boolean] include uncovered byte ranges as +<GAP>+ rows
245
+ # @param show_overlaps [Boolean] annotate rows colliding with overlapping ranges
246
+ # @param collapse_arrays [Boolean] collapse arrays into one summary row
247
+ # @return [String]
248
+ def to_table(max_depth: nil, total_size: nil, show_gaps: true, show_overlaps: true, collapse_arrays: false)
249
+ rows = []
250
+ collect_table_rows(self, nil, 0, max_depth, collapse_arrays, rows)
251
+
252
+ gap_list = gaps(total_size: total_size, ignore_padding: false)
253
+ ov_list = overlaps
254
+
255
+ if show_gaps
256
+ gap_list.each do |g|
257
+ rows << { first: g.first, last: g.last, size: g.size, label: "<GAP>", pad: false, gap: true }
258
+ end
259
+ end
260
+
261
+ rows.sort_by! { |r| [r[:first], r[:last], r[:gap] ? 1 : 0, r[:label]] }
262
+
263
+ max_off = rows.map { |r| r[:last] }.max || 0
264
+ max_off = [max_off, total_size - 1].max if total_size && total_size > 0
265
+ hex_w = [max_off.to_s(16).length, 4].max
266
+
267
+ formatted = rows.map do |r|
268
+ start_s = format("0x%0#{hex_w}x", r[:first])
269
+ end_s = format("0x%0#{hex_w}x", r[:last])
270
+ notes = []
271
+ notes << "<PAD>" if r[:pad]
272
+ if show_overlaps && !r[:gap] && !r[:pad] &&
273
+ ov_list.any? { |ov| ov.first <= r[:last] && ov.last >= r[:first] }
274
+ notes << "[OVERLAP]"
275
+ end
276
+ [start_s, end_s, r[:size].to_s, r[:label], notes.join(" ")]
277
+ end
278
+
279
+ w_start = ["Start".length, formatted.map { |c| c[0].length }.max || 0].max
280
+ w_end = ["End".length, formatted.map { |c| c[1].length }.max || 0].max
281
+ w_size = ["Size".length, formatted.map { |c| c[2].length }.max || 0].max
282
+ w_label = ["Field".length, formatted.map { |c| c[3].length }.max || 0].max
283
+
284
+ lines = []
285
+ lines << format("%-#{w_start}s %-#{w_end}s %#{w_size}s %-#{w_label}s %s", "Start", "End", "Size", "Field", "Notes").rstrip
286
+ lines << "#{'-' * w_start} #{'-' * w_end} #{'-' * w_size} #{'-' * w_label} -----"
287
+ formatted.each do |c|
288
+ lines << format("%-#{w_start}s %-#{w_end}s %#{w_size}s %-#{w_label}s %s", *c).rstrip
289
+ end
290
+
291
+ tot_span = total_size ? [total_size, (@range && @range.size > 0 ? @range.last + 1 : 0)].max : size
292
+ gap_bytes = gap_list.sum(&:size)
293
+ lines << format("Total: %d bytes | Gaps: %d (%d bytes) | Overlaps: %d", tot_span, gap_list.length, gap_bytes, ov_list.length)
294
+ lines.join("\n")
295
+ end
296
+
297
+ private
298
+
299
+ def anon_shape_hash?(key, val)
300
+ key.to_s.match?(/\A__anon_\d+\z/) && val.is_a?(DataShape) && val.members.is_a?(Hash)
301
+ end
302
+
303
+ def collapse_array_row(arr, prefix, out)
304
+ elems = arr.compact.select { |e| e.range && e.range.size > 0 }
305
+ return if elems.empty?
306
+
307
+ r = elems.map(&:range).reduce(:+)
308
+ out << { first: r.first, last: r.last, size: r.size,
309
+ label: "#{prefix}[0..#{elems.length - 1}] (#{elems.length}x)", pad: false, gap: false }
310
+ end
311
+
312
+ def collect_leaves(node, prefix, include_padding, out)
313
+ return if node.nil?
314
+
315
+ case node
316
+ when Array
317
+ node.each_with_index do |elem, i|
318
+ collect_leaves(elem, "#{prefix}[#{i}]", include_padding, out) unless elem.nil?
319
+ end
320
+ when Hash
321
+ node.each do |k, v|
322
+ next if v.nil?
323
+ if anon_shape_hash?(k, v)
324
+ collect_leaves(v.members, prefix, include_padding, out)
325
+ else
326
+ sub_path = prefix ? "#{prefix}.#{k}" : k.to_s
327
+ collect_leaves(v, sub_path, include_padding, out)
328
+ end
329
+ end
330
+ when DataRange
331
+ mem = node.respond_to?(:members) ? node.members : nil
332
+ if mem.nil?
333
+ return if prefix.nil? && !node.padding?
334
+ r = node.range
335
+ return if r.nil? || r.size <= 0
336
+ return if node.padding? && !include_padding
337
+ out << Span.new(path: prefix || "<pad>", range: r, padding: node.padding?)
338
+ else
339
+ collect_leaves(mem, prefix, include_padding, out)
340
+ end
341
+ end
342
+ end
343
+
344
+ def collect_table_rows(node, prefix, depth, max_depth, collapse_arrays, out)
345
+ return if node.nil?
346
+
347
+ case node
348
+ when Array
349
+ if collapse_arrays
350
+ collapse_array_row(node, prefix, out)
351
+ else
352
+ node.each_with_index do |elem, i|
353
+ collect_table_rows(elem, "#{prefix}[#{i}]", depth + 1, max_depth, collapse_arrays, out) unless elem.nil?
354
+ end
355
+ end
356
+ when Hash
357
+ node.each do |k, v|
358
+ next if v.nil?
359
+ if anon_shape_hash?(k, v)
360
+ collect_table_rows(v.members, prefix, depth, max_depth, collapse_arrays, out)
361
+ else
362
+ sub_path = prefix ? "#{prefix}.#{k}" : k.to_s
363
+ collect_table_rows(v, sub_path, depth + 1, max_depth, collapse_arrays, out)
364
+ end
365
+ end
366
+ when DataRange
367
+ mem = node.respond_to?(:members) ? node.members : nil
368
+ if mem.nil?
369
+ return if prefix.nil? && !node.padding?
370
+ r = node.range
371
+ return if r.nil? || r.size <= 0
372
+ out << { first: r.first, last: r.last, size: r.size,
373
+ label: node.padding? ? (prefix || "<PAD>") : prefix, pad: node.padding?, gap: false }
374
+ elsif mem.is_a?(Array) && collapse_arrays
375
+ collapse_array_row(mem, prefix, out)
376
+ elsif max_depth && depth >= max_depth
377
+ r = node.range
378
+ return if r.nil? || r.size <= 0
379
+ out << { first: r.first, last: r.last, size: r.size, label: prefix || "<root>", pad: node.padding?, gap: false }
380
+ else
381
+ collect_table_rows(mem, prefix, depth, max_depth, collapse_arrays, out)
382
+ end
383
+ end
384
+ end
385
+ end
386
+
387
+ end