1616from acd .l5x .port_structures import PORT_STRUCTURES
1717
1818
19+ # Characters that are illegal in XML 1.0: everything outside
20+ # #x9 | #xA | #xD | #x20-#xD7FF | #xE000-#xFFFD | #x10000-#x10FFFF.
21+ _XML_ILLEGAL_RE = re .compile ("[\x00 -\x08 \x0b \x0c \x0e -\x1f \ufffe \uffff ]" )
22+
23+
24+ def _escape_xml_attr (value : object ) -> str :
25+ """Escape a value for use inside a double-quoted XML attribute.
26+
27+ Beyond ``html.escape``, this strips characters that are illegal in XML 1.0
28+ and encodes the legal-but-delimiting whitespace (TAB/CR/LF) as numeric
29+ character references. Some binary records decode to garbage when an offset
30+ drifts (e.g. an AOI ``Vendor`` field read with ``errors="replace"``); without
31+ this, those raw control characters and newlines land verbatim in an
32+ attribute value, producing non-well-formed L5X that breaks downstream XML
33+ parsers.
34+ """
35+ text = _XML_ILLEGAL_RE .sub ("" , str (value ))
36+ text = html .escape (text , quote = True )
37+ return text .replace ("\t " , "	" ).replace ("\r " , "
" ).replace ("\n " , "
" )
38+
39+
1940@dataclass
2041class L5xElementBuilder :
2142 _cur : Cursor
@@ -78,7 +99,7 @@ def to_xml(self) -> str:
7899 _overrides = getattr (self , "_xml_attr_overrides" , {})
79100 xml_attr_name = _overrides .get (attribute , attribute .title ().replace ("_" , "" ))
80101 attribute_list .append (
81- f'{ xml_attr_name } ="{ html . escape ( str ( attribute_value ), quote = True )} "'
102+ f'{ xml_attr_name } ="{ _escape_xml_attr ( attribute_value )} "'
82103 )
83104
84105 _export_name = (
@@ -611,7 +632,7 @@ def to_xml(self) -> str:
611632 if self ._comm_method is not None :
612633 conn_parts : List [str ] = []
613634 for (conn_name , rpi_str , conn_type ) in self ._connections :
614- safe_name = html . escape (conn_name , quote = True )
635+ safe_name = _escape_xml_attr (conn_name )
615636 # Derive InputTag / OutputTag stubs based on connection type.
616637 if conn_type == "Output" :
617638 tag_stubs = (
@@ -773,7 +794,7 @@ def to_xml(self) -> str:
773794 )
774795 if rung_xmls :
775796 rll_content = f'<RLLContent>{ "" .join (rung_xmls )} </RLLContent>'
776- return f'<Routine Name="{ html . escape (self .name , quote = True )} " Type="{ self .type } ">{ rll_content } </Routine>'
797+ return f'<Routine Name="{ _escape_xml_attr (self .name )} " Type="{ self .type } ">{ rll_content } </Routine>'
777798
778799
779800@dataclass
@@ -1884,6 +1905,23 @@ def _parse_fffeff(data: bytes, offset: int):
18841905 return s , offset + 4 + length * 2
18851906
18861907
1908+ def _filetime_to_iso (ft : int ) -> str :
1909+ """Convert a Windows FILETIME (100-ns units since 1601-01-01) to ISO8601.
1910+
1911+ Returns "" for an empty or out-of-range value. Some AOI nameless records
1912+ carry a corrupt FILETIME (the variable-length field walk can drift and read
1913+ 8 garbage bytes), which would otherwise overflow ``datetime`` for years
1914+ beyond 9999 and abort the whole export with ``OverflowError``.
1915+ """
1916+ if not ft :
1917+ return ""
1918+ try :
1919+ dt = datetime (1601 , 1 , 1 ) + timedelta (microseconds = ft // 10 )
1920+ except (OverflowError , OSError ):
1921+ return ""
1922+ return dt .strftime ("%Y-%m-%dT%H:%M:%S." ) + f"{ dt .microsecond // 1000 :03d} Z"
1923+
1924+
18871925def _parse_aoi_nameless (data : bytes ) -> dict :
18881926 """Extract AOI metadata from its large nameless record."""
18891927 result : dict = {}
@@ -1912,12 +1950,7 @@ def _parse_aoi_nameless(data: bytes) -> dict:
19121950 _ , offset = _parse_fffeff (data , offset )
19131951
19141952 # CreatedDate FILETIME (8 bytes, Windows FILETIME in 100-ns units)
1915- ft = struct .unpack_from ("<Q" , data , offset )[0 ]
1916- if ft :
1917- dt = datetime (1601 , 1 , 1 ) + timedelta (microseconds = ft // 10 )
1918- result ["created_date" ] = dt .strftime ("%Y-%m-%dT%H:%M:%S." ) + f"{ dt .microsecond // 1000 :03d} Z"
1919- else :
1920- result ["created_date" ] = ""
1953+ result ["created_date" ] = _filetime_to_iso (struct .unpack_from ("<Q" , data , offset )[0 ])
19211954 offset += 8
19221955
19231956 # EditedBy
@@ -1934,12 +1967,7 @@ def _parse_aoi_nameless(data: bytes) -> dict:
19341967 result ["revision_extension" ] = rev_ext or None
19351968
19361969 # EditedDate FILETIME (always last 8 bytes)
1937- ft = struct .unpack_from ("<Q" , data , len (data ) - 8 )[0 ]
1938- if ft :
1939- dt = datetime (1601 , 1 , 1 ) + timedelta (microseconds = ft // 10 )
1940- result ["edited_date" ] = dt .strftime ("%Y-%m-%dT%H:%M:%S." ) + f"{ dt .microsecond // 1000 :03d} Z"
1941- else :
1942- result ["edited_date" ] = ""
1970+ result ["edited_date" ] = _filetime_to_iso (struct .unpack_from ("<Q" , data , len (data ) - 8 )[0 ])
19431971
19441972 return result
19451973
0 commit comments