Repository navigation
Expand file tree
/
Copy pathols_reader.py
More file actions
1477 lines (1259 loc) · 55.7 KB
/
Copy pathols_reader.py
File metadata and controls
1477 lines (1259 loc) · 55.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
OLS File Reader - Parse WinOLS .ols and .kp (Kennfeld Pack) files
This module provides a clean interface for reading WinOLS .ols files and
.kp (map pack) files, extracting parameter definitions, addresses, and
embedded binary data.
OLS files are proprietary project files used by WinOLS ECU tuning software.
They contain vehicle metadata, parameter definitions with addresses, and
optionally embedded binary data.
KP files (Kennfeld Pack / Map Pack) are a variant used for sharing map
definitions. They use ZIP compression for parameter storage and contain
direct file offsets rather than embedded binary data.
Supported OLS Versions:
- v250-285: Old format (limited binary version support)
- v300-399: Intermediate format (parent ID based versions)
- v400-596: Standard format (parent ID based versions)
- v597+: Multi-version format (edit history with version slots)
- v597+ KP: Map pack format with ZIP-compressed parameters
- v804+: WinOLS 5 format (15 metadata strings, derived version records)
Usage:
from ols_reader import read_ols, OLSReader
# Quick read (works for both .ols and .kp files)
ols = read_ols("file.ols")
print(f"Parameters: {len(ols.parameters)}")
# KP files contain direct file offsets
ols = read_ols("mappack.kp")
for param in ols.parameters:
print(f"{param.name}: @0x{param.data_offset:x}")
# With binary extraction (OLS files only)
reader = OLSReader("file.ols")
ols = reader.parse()
for version in ols.binary_versions:
data = reader.extract_binary(version)
with open(f"{version.name}.bin", "wb") as f:
f.write(data)
"""
from __future__ import annotations
import io
import re
import struct
import zipfile
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional
@dataclass
class FolderEntry:
"""Folder/function entry from ols structure"""
idx: int # Folder index (matches folder_id in parameters)
name: str # Folder name (e.g., "ACQ_KNK_sensor_signal_gen")
description: str = "" # Description (e.g., "Acquisition of knock sensor signal (gen)")
@dataclass
class AxisInfo:
"""Axis definition for CURVE/MAP parameters"""
points: int
address: int = 0 # CAL offset/address for axis data
offset: int = 0 # Conversion offset (physical = raw * factor + offset)
unit: str = ""
factor: float = 1.0 # Conversion factor (physical = raw * factor + offset)
id: str = "" # Axis ID (e.g., "n_32", "_CNV_A_R_LINEAR_____33_CM")
description: str = "" # Axis description (e.g., "Engine speed -Resolution 32 rpm")
data_source: int = 0 # Data source type (1=values, 2=eeprom, etc.)
data_type: str = "UWORD" # Data type (UBYTE, UWORD, etc.)
@dataclass
class Parameter:
"""ECU parameter definition extracted from OLS file"""
name: str
description: str = ""
param_type: str = "VALUE" # VALUE, CURVE, MAP, or MAP_INVERSE
data_type: str = "UWORD" # UBYTE, SBYTE, UWORD, SWORD, ULONG, SLONG
cols: int = 1
rows: int = 1
data_offset: int = 0 # CAL offset for parameter data
x_axis: Optional[AxisInfo] = None
y_axis: Optional[AxisInfo] = None
unit: str = ""
factor: float = 1.0 # Conversion factor (physical = raw * factor + offset)
offset: float = 0.0 # Conversion offset
folder_id: int = 0 # Folder/category ID (numeric ID only - folder names not found in OLS files)
type_code: int = 0 # Raw type code from metadata (2=VALUE, 3=CURVE, 4=MAP, 5=MAP_INVERSE)
@dataclass
class BinaryVersion:
"""
Binary version entry (e.g., "Original", "NOCS", "Daten")
For standard format (v300-596):
- parent_id indicates the parent folder (typically 1)
- blob_offset is the direct file offset to binary data
For multi-version format (v597+):
- version_index is the slot index (0-based)
- version_count is total edit history depth
- blob_offset is calculated from: blob_base + version_index * blob_size
Verification:
- epk: Identification string found in binary (e.g., "SC1C910", "SC8F830")
- epk_offset: Offset relative to blob_offset where EPK was found
"""
name: str
description: str = "" # Import path/creation description
parent_id: Optional[int] = None # None = root folder (0x003fffff marker)
is_root: bool = False
blob_offset: int = 0 # File offset where binary blob starts
blob_size: int = 0 # Binary blob size in bytes
version_index: int = 0 # Version index (0-based) for multi-version files (v597+)
version_count: int = 0 # Total number of version slots (v597+)
epk: str = "" # EPK/identification string found in binary
epk_offset: int = 0 # Offset relative to blob_offset where EPK was found
@dataclass
class CALBlock:
"""Embedded calibration binary data"""
offset: int # File offset where CAL starts
cas_id: str # CAS identifier (e.g., "CASC2E55")
epk: str # EPK string (e.g., "SC8F830")
data: bytes = b""
@dataclass
class OLSFile:
"""Parsed OLS file contents"""
filename: str
version: int = 0 # OLS format version (e.g., 250, 440, 478, 804)
make: str = ""
model: str = ""
engine: str = ""
year: str = ""
fuel_type: str = ""
displacement: str = ""
power: str = ""
gearbox: str = ""
memory_type: str = ""
ecu_manufacturer: str = ""
ecu_type: str = ""
sw_number: str = ""
hw_number: str = ""
hw_code: str = ""
user: str = ""
parameters: list[Parameter] = field(default_factory=list)
binary_versions: list[BinaryVersion] = field(default_factory=list)
cal_block: Optional[CALBlock] = None
is_kp_file: bool = False # True if this is a KP (Kennfeld Pack) file
big_endian_data: bool = False # True if binary data should be read as big-endian (common for KP/DSG)
folders: list[FolderEntry] = field(default_factory=list) # Folder/Function entries
class OLSReader:
"""
Reader for WinOLS .ols project files.
Supports OLS format versions 100 through 834+, including:
- Sequential parameter extraction (reads fields in WinOLS order)
- Binary version extraction (Original, edit history)
- CAL block extraction (Simos-specific)
Usage:
reader = OLSReader("file.ols")
ols = reader.parse()
# Access parameters
for param in ols.parameters:
print(f"{param.name}: offset={param.data_offset}")
# Extract binary data
for version in ols.binary_versions:
data = reader.extract_binary(version)
Attributes:
filepath: Path to the OLS file
data: Raw file bytes
version: OLS format version (set during parsing)
"""
# Format version thresholds (for binary version / folder detection only)
NEW_FORMAT_VERSION = 300
NEWER_FORMAT_VERSION = 400
def __init__(self, filepath: str | Path):
self.filepath = Path(filepath)
self.data = self.filepath.read_bytes()
self.pos = 0
self.version = 0 # Will be set during header parsing
def parse(self) -> OLSFile:
"""Parse the OLS file and return structured data"""
ols = OLSFile(filename=self.filepath.name)
# Parse header for vehicle metadata
self._parse_header(ols)
ols.version = self.version
# Check if this is a KP (Kennfeld Pack) file with ZIP-compressed parameters
if self._is_kp_file():
ols.is_kp_file = True
ols.big_endian_data = True # KP files typically have big-endian data
ols.parameters = self._extract_kp_parameters()
# KP files don't have embedded binary versions or CAL blocks
return ols
# Extract binary versions (Daten, Original, NOCS, etc.)
ols.binary_versions = self._extract_binary_versions()
# Extract parameters with addresses
ols.parameters = self._extract_parameters()
# Find and extract CAL block
ols.cal_block = self._extract_cal_block()
ols.folders = self._extract_folder_entries()
return ols
def _is_kp_file(self) -> bool:
"""
Check if this is a KP (Kennfeld Pack) file.
KP files are v597+ OLS files that contain ZIP-compressed parameter data
instead of raw parameter records. They're identified by:
- Version >= 597
- ZIP signature (PK\\x03\\x04) present after header
- Contains "intern" file in the ZIP archive
"""
if self.version < 597:
return False
# Look for ZIP signature after header (typically around 0x400-0x500)
zip_sig = b'PK\x03\x04'
zip_pos = self.data.find(zip_sig, 0x100, 0x1000)
if zip_pos < 0:
return False
# Verify it's a valid ZIP with "intern" file
try:
zip_data = self.data[zip_pos:]
with zipfile.ZipFile(io.BytesIO(zip_data)) as zf:
return 'intern' in zf.namelist()
except (zipfile.BadZipFile, Exception):
return False
def _extract_kp_parameters(self) -> list[Parameter]:
"""
Extract parameters from KP (Kennfeld Pack) file.
KP files store parameters in a ZIP-compressed "intern" file with structure:
- Metadata (6 x u32): type_code, and dimension info
- Name length (u32) + name string
- Post-name data (~0x9c-0xb0 bytes) containing address
Addresses in KP files are direct file offsets into the corresponding .bin file.
"""
parameters = []
found_names: set[str] = set()
# Find and extract intern file
zip_sig = b'PK\x03\x04'
zip_pos = self.data.find(zip_sig, 0x100, 0x1000)
if zip_pos < 0:
return parameters
try:
zip_data = self.data[zip_pos:]
with zipfile.ZipFile(io.BytesIO(zip_data)) as zf:
intern_data = zf.read('intern')
except (zipfile.BadZipFile, KeyError, Exception):
return parameters
# Parse parameters from intern file
pos = 0
while pos < len(intern_data) - 300:
try:
# Read potential metadata (6 x u32)
meta = struct.unpack_from('<6I', intern_data, pos)
type_code = meta[0]
# Validate metadata pattern
if type_code in (2, 3) or 4 <= type_code <= 20:
if all(m < 1000 for m in meta[1:5]):
# Check for name length at pos + 24
name_len = struct.unpack_from('<I', intern_data, pos + 24)[0]
if 3 < name_len < 60 and pos + 28 + name_len < len(intern_data):
try:
name = intern_data[pos + 28:pos + 28 + name_len].decode('ascii').rstrip('\x00')
# Validate name
clean_name = name.replace('_', '').replace('[', '').replace(']', '').replace('.', '')
if (name.isprintable() and
clean_name.isalnum() and
len(name) >= 3 and
('_' in name or '.' in name) and
name not in found_names):
found_names.add(name)
param = self._parse_kp_parameter_record(
intern_data, pos, name_len, name, meta
)
if param:
parameters.append(param)
# Skip to next record
pos = pos + 28 + name_len + 0x100
continue
except (UnicodeDecodeError, ValueError):
pass
except struct.error:
pass
pos += 4
return parameters
def _parse_kp_parameter_record(
self,
intern_data: bytes,
meta_pos: int,
name_len: int,
name: str,
meta: tuple[int, ...]
) -> Optional[Parameter]:
"""
Parse a single parameter record from KP intern file.
Structure:
- Metadata at meta_pos (6 x u32)
- Name at meta_pos + 28
- Post-name data: ~0xa0 bytes containing address and axis info
- Address is at variable offset 0x9c-0xb0 from name end
"""
name_end = meta_pos + 28 + name_len
if name_end + 0xb0 > len(intern_data):
return None
# Determine type from metadata
type_code = meta[0]
if type_code == 2:
param_type = "VALUE"
elif type_code == 3:
param_type = "CURVE"
else:
param_type = "MAP"
# Extract dimensions from metadata (meta[4] often contains points/cols info)
cols = 1
rows = 1
if param_type == "CURVE":
cols = meta[4] if 1 < meta[4] < 100 else 1
elif param_type == "MAP":
cols = meta[4] if 1 < meta[4] < 100 else 1
rows = meta[5] if 1 < meta[5] < 100 else 1
# Find address - scan range 0x9c-0xb0 from name_end
# KP addresses are direct file offsets stored as little-endian
# Typically in 0x60000-0x80000 range for DSG
data_offset = 0
for off in range(0x9c, 0xb0):
addr_pos = name_end + off
if addr_pos + 4 <= len(intern_data):
candidate = struct.unpack_from('<I', intern_data, addr_pos)[0]
# Valid address range depends on ECU type
# DSG: 0x60000-0x80000, but allow wider range for other ECUs
if 0x1000 <= candidate < 0x800000:
data_offset = candidate
break
# Try to find axis offset (typically 4 bytes after data offset)
x_axis = None
y_axis = None
if data_offset > 0 and param_type in ("CURVE", "MAP"):
for off in range(0x9c, 0xb0):
addr_pos = name_end + off
if addr_pos + 8 <= len(intern_data):
addr1 = struct.unpack_from('<I', intern_data, addr_pos)[0]
addr2 = struct.unpack_from('<I', intern_data, addr_pos + 4)[0]
if addr1 == data_offset and 0x1000 <= addr2 < 0x800000:
x_axis = AxisInfo(points=cols, offset=addr2)
if param_type == "MAP" and rows > 1:
# Y-axis offset typically follows X-axis data
y_axis = AxisInfo(points=rows, offset=addr2 + cols * 2)
break
# Try to extract description (search backwards from metadata)
description = ""
if meta_pos > 50:
# Look for length-prefixed string before metadata
for back in range(4, min(200, meta_pos), 4):
check_pos = meta_pos - back
try:
str_len = struct.unpack_from('<I', intern_data, check_pos)[0]
if 5 < str_len < 200 and check_pos + 4 + str_len <= meta_pos:
desc_bytes = intern_data[check_pos + 4:check_pos + 4 + str_len]
desc = desc_bytes.decode('cp1252', errors='replace').rstrip('\x00').strip()
if desc and len(desc) > 5 and all(c.isprintable() or c in ' \t' for c in desc):
description = desc
break
except (struct.error, UnicodeDecodeError):
pass
return Parameter(
name=name,
description=description,
param_type=param_type,
data_type="UWORD", # KP files typically use UWORD (big-endian in the bin file)
cols=cols,
rows=rows,
data_offset=data_offset,
x_axis=x_axis,
y_axis=y_axis,
)
def _read_u16(self, offset: int) -> int:
"""Read unsigned 16-bit little-endian value"""
return struct.unpack_from('<H', self.data, offset)[0]
def _read_u32(self, offset: int) -> int:
"""Read unsigned 32-bit little-endian value"""
return struct.unpack_from('<I', self.data, offset)[0]
def _read_string(self, offset: int) -> tuple[str, int]:
"""Read length-prefixed string, return (string, bytes_consumed)"""
length = self._read_u32(offset)
if length == 0 or length > 500:
return "", 4
# OLS files use Windows-1252 encoding (Western European), not UTF-8
s = self.data[offset + 4:offset + 4 + length].decode('cp1252', errors='replace')
s = s.rstrip('\x00').strip()
return s, 4 + length
def _parse_header(self, ols: OLSFile) -> bool:
"""
Parse OLS file header.
Header structure:
- [0-3] Magic number (0x0b)
- [4-15] Signature "WinOLS File"
- [16-17] Version (u16)
- [18-21] Flags (u32)
- [22+] Length-prefixed strings (up to 15):
make, model, engine, year, fuel_type, displacement, power,
gearbox, memory_type, ecu_manufacturer, ecu_type, sw_number,
hw_number, hw_code, user
Older OLS versions may have fewer strings (minimum 4).
v597+ typically have all 15 strings (some may be empty).
"""
# Check magic
if self._read_u32(0) != 0x0b:
return False
# Check signature
sig = self.data[4:16].decode('ascii', errors='replace').rstrip('\x00')
if not sig.startswith("WinOLS File"):
return False
# Read version (determines structure format)
self.version = self._read_u16(16)
# Structure: magic(4) + sig(12) + version(2) + flags/timestamp(6) = 24 bytes
# Then length-prefixed strings starting at 0x18
pos = 0x18
ols.make, consumed = self._read_string(pos)
pos += consumed
ols.model, consumed = self._read_string(pos)
pos += consumed
ols.engine, consumed = self._read_string(pos)
pos += consumed
ols.year, consumed = self._read_string(pos)
pos += consumed
# Extended metadata strings (v597+, up to 11 more)
# Each is length-prefixed; older files may stop early
extended_fields = [
'fuel_type', 'displacement', 'power', 'gearbox',
'memory_type', 'ecu_manufacturer', 'ecu_type',
'sw_number', 'hw_number', 'hw_code', 'user',
]
for field_name in extended_fields:
if pos + 4 >= len(self.data):
break
val, consumed = self._read_string(pos)
if consumed <= 0:
break
# Stop if the length field looks like non-string data
# (length-prefixed strings should have length < 200)
raw_len = self._read_u32(pos)
if raw_len > 200:
break
setattr(ols, field_name, val)
pos += consumed
return True
def _extract_binary_versions(self) -> list[BinaryVersion]:
"""
Extract binary version entries (Original, Daten, NOCS, user-defined, etc.)
WinOLS uses a single record format across all observed versions (v100..v804+),
identified by the 0x42007899 class marker:
Base record:
[version_index:4] [blob_offset:4] [blob_size:4] [0x42007899:4]
[version_count:4] [name_len:4] [name] [desc_len:4] [desc]
Derived record (for additional versions like user edits):
[0xFFFFFFFF:4] [name_len:4] [name] [desc_len:4] [desc]
Blob storage layout: blob_offset + i * blob_size for version i.
file_size == blob_offset + version_count * blob_size + 4 (0xFFFFFFFF trailer).
"""
versions = []
BLOB_MARKER = 0x42007899
marker_bytes = struct.pack('<I', BLOB_MARKER)
scan_start = 0x100
scan_end = min(0x2000, len(self.data) - 28)
base_found = False
marker_pos = self.data.find(marker_bytes, scan_start, scan_end)
while marker_pos >= 0 and not base_found:
# Base record: marker is at offset +12 from record start
rec_start = marker_pos - 12
if rec_start < 0:
marker_pos = self.data.find(marker_bytes, marker_pos + 4, scan_end)
continue
version_index = self._read_u32(rec_start)
blob_offset = self._read_u32(rec_start + 4)
blob_size = self._read_u32(rec_start + 8)
# marker at rec_start + 12
version_count = self._read_u32(rec_start + 16)
name_len = self._read_u32(rec_start + 20)
# Validate base record structure
if (version_index < 20 and
version_count > 0 and version_count <= 20 and
version_index < version_count and
0x10000 <= blob_size <= 0x10000000 and
blob_offset + version_count * blob_size <= len(self.data) + 4 and
0 < name_len < 50 and
rec_start + 24 + name_len <= len(self.data)):
try:
name = self.data[rec_start + 24:rec_start + 24 + name_len].decode('cp1252')
if name.isprintable() and name.strip():
name_clean = name.strip()
# Read description after name
desc = ""
desc_pos = rec_start + 24 + name_len
if desc_pos + 4 <= len(self.data):
desc_len = self._read_u32(desc_pos)
if 0 < desc_len < 500 and desc_pos + 4 + desc_len <= len(self.data):
desc = self.data[desc_pos + 4:desc_pos + 4 + desc_len].decode('cp1252', errors='replace').strip()
actual_blob_offset = blob_offset + version_index * blob_size
versions.append(BinaryVersion(
name=name_clean,
blob_offset=actual_blob_offset,
blob_size=blob_size,
version_index=version_index,
version_count=version_count,
description=desc,
))
base_found = True
# Scan forward for derived records (0xFFFFFFFF sentinel)
derived_search_start = marker_pos + 4
derived_search_end = min(derived_search_start + 0x500, len(self.data) - 8)
derived_index = 0 # Next slot to assign
d_pos = derived_search_start
while d_pos < derived_search_end:
if self._read_u32(d_pos) == 0xFFFFFFFF:
if d_pos + 8 <= len(self.data):
d_name_len = self._read_u32(d_pos + 4)
if (0 < d_name_len < 50 and
d_pos + 8 + d_name_len <= len(self.data)):
try:
d_name = self.data[d_pos + 8:d_pos + 8 + d_name_len].decode('cp1252')
if d_name.isprintable() and d_name.strip():
# Skip base record's index
while derived_index == version_index:
derived_index += 1
if derived_index >= version_count:
break
d_desc = ""
d_desc_pos = d_pos + 8 + d_name_len
if d_desc_pos + 4 <= len(self.data):
d_desc_len = self._read_u32(d_desc_pos)
if 0 < d_desc_len < 500 and d_desc_pos + 4 + d_desc_len <= len(self.data):
d_desc = self.data[d_desc_pos + 4:d_desc_pos + 4 + d_desc_len].decode('cp1252', errors='replace').strip()
d_blob_offset = blob_offset + derived_index * blob_size
versions.append(BinaryVersion(
name=d_name.strip(),
blob_offset=d_blob_offset,
blob_size=blob_size,
version_index=derived_index,
version_count=version_count,
description=d_desc,
))
derived_index += 1
# Skip past this derived record
d_pos = d_desc_pos + (4 + d_desc_len if d_desc else 4)
continue
except (UnicodeDecodeError, ValueError):
pass
d_pos += 1
except (UnicodeDecodeError, ValueError):
pass
if not base_found:
marker_pos = self.data.find(marker_bytes, marker_pos + 4, scan_end)
# Find EPK/verification info for each binary version
for v in versions:
if v.blob_offset > 0 and v.blob_size > 0:
epk, epk_offset = self._find_binary_verification(v.blob_offset, v.blob_size)
v.epk = epk
v.epk_offset = epk_offset
return versions
def _find_binary_verification(self, blob_offset: int, blob_size: int) -> tuple[str, int]:
"""
Search for EPK/identification string within a binary block.
First searches at known CAL offsets within the binary, then falls back
to searching the entire file for CAS/EPK patterns.
Returns:
(epk, offset) where offset is relative to blob_offset (or 0 if found outside)
"""
# Known CAL offsets for different ECU types (from EPK prefix)
# Simos18.10 (Aurix TC29x): SCG -> 0x820000
# Simos18.1 (TC1793): SC8 -> 0x800000
# Simos12 (TC1797): SC1, SA3 -> 0x40000
# Simos16: SC4 -> 0x100000
# MED17: S82, S85 -> 0x40000
cal_offsets = [0x40000, 0x100000, 0x800000, 0x820000, 0x0]
# Method 1: Search at known CAL offsets within binary
for cal_off in cal_offsets:
if cal_off + 20 > blob_size:
continue
pos = blob_offset + cal_off
if pos + 20 > len(self.data):
continue
header = self.data[pos:pos + 20]
epk, rel_offset = self._extract_epk_from_header(header)
if epk:
return epk, cal_off + rel_offset
# Method 2: Search entire file for CAS pattern (for files where CAL is separate)
cas_pattern = rb'CAS[A-Z][A-Z0-9]{4}'
for match in re.finditer(cas_pattern, self.data):
cas_pos = match.start()
# EPK is 8 bytes after CAS
epk_pos = cas_pos + 8
if epk_pos + 7 <= len(self.data):
epk_bytes = self.data[epk_pos:epk_pos + 7]
epk = epk_bytes.split(b'\x00')[0].decode('ascii', errors='replace')
if epk and len(epk) >= 6 and epk[0] == 'S':
# Calculate offset relative to binary start
rel_offset = cas_pos - blob_offset + 8
# Use known CAL offset based on EPK prefix
known_offset = self._get_cal_offset_for_epk(epk)
if known_offset > 0:
return epk, known_offset + 8 # +8 for CAS header
return epk, rel_offset if rel_offset >= 0 else 0
return "", 0
def _extract_epk_from_header(self, header: bytes) -> tuple[str, int]:
"""Extract EPK from a 20-byte header area."""
# Look for CAS header, EPK follows at +8
cas_match = re.search(rb'CAS[A-Z][A-Z0-9]{4}', header)
if cas_match:
epk_pos = cas_match.start() + 8
if epk_pos + 7 <= len(header):
epk_bytes = header[epk_pos:epk_pos + 7]
epk = epk_bytes.split(b'\x00')[0].decode('ascii', errors='replace')
if epk and len(epk) >= 6:
return epk, epk_pos
# Direct EPK search (for files without CAS header)
epk_match = re.search(rb'S[A-Z][0-9A-Z]{5}\x00', header)
if epk_match:
epk = epk_match.group()[:-1].decode('ascii')
return epk, epk_match.start()
return "", 0
def _get_cal_offset_for_epk(self, epk: str) -> int:
"""Return CAL offset based on EPK prefix (for full bin files)."""
epk_upper = epk.upper()
# Simos18.10 (Aurix TC29x)
if epk_upper.startswith('SCG'):
return 0x820000
# Simos18.1 (TC1793)
if epk_upper.startswith('SC8'):
return 0x800000
# Simos12 (TC1797)
if epk_upper.startswith('SC1') or epk_upper.startswith('SA3'):
return 0x40000
# Simos16
if epk_upper.startswith('SC4'):
return 0x100000
# MED17
if epk_upper.startswith('S82') or epk_upper.startswith('S85'):
return 0x40000
# Default
return 0
# -------------------------------------------------------------------
# Sequential reading primitives (advance self.pos)
# -------------------------------------------------------------------
def _seq_read_u8(self) -> int:
if self.pos + 1 > len(self.data):
raise EOFError(f"read_u8 at 0x{self.pos:x}")
val = self.data[self.pos]
self.pos += 1
return val
def _seq_read_bool(self) -> bool:
return self._seq_read_u8() != 0
def _seq_read_u16(self) -> int:
if self.pos + 2 > len(self.data):
raise EOFError(f"read_u16 at 0x{self.pos:x}")
val = struct.unpack_from('<H', self.data, self.pos)[0]
self.pos += 2
return val
def _seq_read_u32(self) -> int:
if self.pos + 4 > len(self.data):
raise EOFError(f"read_u32 at 0x{self.pos:x}")
val = struct.unpack_from('<I', self.data, self.pos)[0]
self.pos += 4
return val
def _seq_read_i32(self) -> int:
if self.pos + 4 > len(self.data):
raise EOFError(f"read_i32 at 0x{self.pos:x}")
val = struct.unpack_from('<i', self.data, self.pos)[0]
self.pos += 4
return val
def _seq_read_f64(self) -> float:
if self.pos + 8 > len(self.data):
raise EOFError(f"read_f64 at 0x{self.pos:x}")
val = struct.unpack_from('<d', self.data, self.pos)[0]
self.pos += 8
return val
def _seq_read_bytes(self, count: int) -> bytes:
if self.pos + count > len(self.data):
raise EOFError(f"read_bytes({count}) at 0x{self.pos:x}")
result = self.data[self.pos:self.pos + count]
self.pos += count
return result
def _seq_read_array(self) -> bytes:
"""Read u32(byte_count) + byte_count bytes."""
count = self._seq_read_u32()
if count == 0 or count >= 0xFFFFFFF0:
return b""
if count > 0x1000000:
raise ValueError(f"read_array at 0x{self.pos:x}: count {count}")
if self.pos + count > len(self.data):
raise EOFError(f"read_array at 0x{self.pos:x}: need {count}")
result = self.data[self.pos:self.pos + count]
self.pos += count
return result
def _seq_read_u32_array(self) -> list[int]:
count = self._seq_read_u32()
if count == 0:
return []
if count > 0x100000:
raise ValueError(f"read_u32_array: count {count}")
return [self._seq_read_u32() for _ in range(count)]
def _seq_read_string(self) -> str:
"""Read version-aware length-prefixed string."""
length = self._seq_read_u32()
if length == 0 or length >= 0xFFFFFFF0:
return ""
if length > 0x100000:
raise ValueError(f"read_string at 0x{self.pos:x}: length {length}")
if self.pos + length > len(self.data):
raise EOFError(f"read_string at 0x{self.pos:x}: need {length}")
raw = self.data[self.pos:self.pos + length]
if self._has_feature(439):
self.pos += length
else:
self.pos += length + 1
return raw.decode('cp1252', errors='replace').rstrip('\x00')
def _seq_read_string_array(self) -> list[str]:
count = self._seq_read_u32()
return [self._seq_read_string() for _ in range(count)]
def _seq_read_lang_string(self) -> str:
s = self._seq_read_string()
if self._has_feature(345):
self._seq_read_u32() # lang_id
return s
def _seq_read_multi_lang_string(self) -> str:
if not self._has_feature(330):
return self._seq_read_string()
primary = self._seq_read_lang_string()
if self._has_feature(345):
self._seq_read_u32() # flags
sub_count = self._seq_read_u32()
for _ in range(sub_count):
self._seq_read_lang_string()
return primary
def _has_feature(self, feature_id: int) -> bool:
return feature_id <= self.version
# -------------------------------------------------------------------
# Sequential map list detection
# -------------------------------------------------------------------
def _find_map_list_start(self) -> Optional[tuple[int, int]]:
"""
Find the map list start position and count.
The map list is preceded by checksum 0x11883377, then:
- compressed (bool/u8)
- count (u32)
- map records
Returns (first_map_pos, map_count) or None.
"""
needle = struct.pack('<I', 0x11883377)
idx = self.data.find(needle, 0x100, 0x20000)
if idx < 0:
return None
pos = idx + 4
if pos + 5 > len(self.data):
return None
compressed = self.data[pos]
count = struct.unpack_from('<I', self.data, pos + 1)[0]
first_map = pos + 5
if compressed:
import zlib
# Compressed map list: remaining data after count is zlib-compressed
try:
raw = zlib.decompress(self.data[first_map:])
# Replace data temporarily for sequential reading
self._compressed_backup = self.data
self.data = self.data[:first_map] + raw
return (first_map, count)
except zlib.error:
return None
if count == 0 or count > 0x100000:
return None
return (first_map, count)
# -------------------------------------------------------------------
# Sequential axis unit descriptor reader
# -------------------------------------------------------------------
def _seq_read_axis_unit_desc(self) -> tuple[str, float, float, int, int]:
"""
Read axis unit descriptor.
Returns (unit, factor, offset, data_offset, end_offset).
"""
unit = self._seq_read_string()
self._seq_read_string() # alt_unit
factor = self._seq_read_f64()
offset = self._seq_read_f64()
data_offset = self._seq_read_u32()
end_offset = self._seq_read_u32()
self._seq_read_u32() # field_4c
if self._has_feature(264):
self._seq_read_f64()
if self._has_feature(61):
self._seq_read_u32()
if self._has_feature(105):
self._seq_read_u32()
self._seq_read_u32()
self._seq_read_u32()
self._seq_read_i32()
return (unit, factor, offset, data_offset, end_offset)
# -------------------------------------------------------------------
# Sequential axis data reader
# -------------------------------------------------------------------
def _seq_read_axis_data(self) -> AxisInfo:
"""Read a single axis data block.
Layout per COlsAxisData_ReadFromFile (Ghidra: 0x003d1684):
multi_lang_string description
string axis_id (unit)
double factor
double offset
u32 (type_code) axis+0x64
u32 axis+0x70 — axis data address (where breakpoints live)
u32 axis+0x74 — type_kind: 1=UBYTE, 3=UWORD, 5=ULONG, 7=FLOAT32
(same encoding as param data_type;
read via COlsMap_ReadField98)
u32 axis+0x78 — byte width (1/2/4) — derivable from type_kind
u32 axis+0x7c — data_format (validated 2/10/16, always 0xa
empirically; not the real type)
bool, bool, ... feature-gated
NOTE: the breakpoint COUNT is not in this block — it comes from the
param header (cols for X, rows for Y); _seq_read_one_map fills it in.
"""
description = self._seq_read_multi_lang_string()
axis_id = self._seq_read_string()
factor = self._seq_read_f64()
offset = self._seq_read_f64()
type_code = self._seq_read_u32()
axis_address = self._seq_read_u32()
type_kind = self._seq_read_u32() # 1/3/5/7 → byte/word/long/float
self._seq_read_u32() # byte width — redundant
self._seq_read_u32() # data_format — always 0xa, ignored
data_type = {1: "UBYTE", 3: "UWORD", 5: "ULONG", 7: "FLOAT32"}.get(type_kind, "UWORD")
self._seq_read_bool()
self._seq_read_bool()
if self._has_feature(264):
self._seq_read_f64()
if self._has_feature(241):
self._seq_read_u32()
data_source = 0
if self._has_feature(8):
data_source = self._seq_read_u32()
if self._has_feature(805):
self._seq_read_u32()
if self._has_feature(12):
self._seq_read_bool()
if self._has_feature(73):
self._seq_read_array()
if self._has_feature(77):
self._seq_read_u32()
if self._has_feature(91):
self._seq_read_i32()
if self._has_feature(354):
self._seq_read_string()
if self._has_feature(372):
count_372 = self._seq_read_u32()
for _ in range(count_372):
self._seq_read_multi_lang_string()
if self._has_feature(440):
self._seq_read_i32()
if self._has_feature(805):
self._seq_read_u32()
self._seq_read_u32()
self._seq_read_u32()
self._seq_read_u32()
return AxisInfo(
points=0,
address=axis_address,
unit="",
factor=factor,