KiCad PCB EDA Suite
Loading...
Searching...
No Matches
altium_binary_parser.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 2019-2020 Thomas Pointhuber <[email protected]>
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
22#include "altium_parser_utils.h"
23
24#include <compoundfilereader.h>
25#include <charconv>
26#include <ki_exception.h>
27#include <math/util.h>
28#include <numeric>
29#include <sstream>
30#include <utf.h>
31#include <wx/log.h>
32#include <wx/translation.h>
33
34
35// Helper for debug logging
36std::string FormatPath( const std::vector<std::string>& aVectorPath )
37{
38 return std::accumulate( aVectorPath.cbegin(), aVectorPath.cend(), std::string(),
39 []( const std::string& ss, const std::string& s )
40 {
41 return ss.empty() ? s : ss + '\\' + s;
42 } );
43}
44
45
49
50
52{
53 // Open file
54 FILE* fp = wxFopen( aFilePath, "rb" );
55
56 if( fp == nullptr )
57 THROW_IO_ERRORF( _( "Cannot open file '%s'." ), aFilePath );
58
59 fseek( fp, 0, SEEK_END );
60 long len = ftell( fp );
61
62 if( len < 0 )
63 {
64 fclose( fp );
65 THROW_IO_ERROR( _( "Error reading file: cannot determine length." ) );
66 }
67
68 // Read into buffer (TODO: add support for memory-mapped files to avoid this copy!)
69 m_buffer.resize( len );
70
71 fseek( fp, 0, SEEK_SET );
72
73 size_t bytesRead = fread( m_buffer.data(), sizeof( unsigned char ), len, fp );
74 fclose( fp );
75
76 if( static_cast<size_t>( len ) != bytesRead )
77 {
78 THROW_IO_ERROR( _( "Error reading file." ) );
79 }
80
81 try
82 {
83 m_reader = std::make_unique<CFB::CompoundFileReader>( m_buffer.data(), m_buffer.size() );
84 }
85 catch( CFB::CFBException& exception )
86 {
87 THROW_IO_ERROR( exception.what() );
88 }
89}
90
91
92ALTIUM_COMPOUND_FILE::ALTIUM_COMPOUND_FILE( const void* aBuffer, size_t aLen )
93{
94 InitFromBuffer( aBuffer, aLen );
95}
96
97
98void ALTIUM_COMPOUND_FILE::InitFromBuffer( const void* aBuffer, size_t aLen )
99{
100 m_buffer.resize( aLen );
101 memcpy( m_buffer.data(), aBuffer, aLen );
102
103 try
104 {
105 m_reader = std::make_unique<CFB::CompoundFileReader>( m_buffer.data(), m_buffer.size() );
106 }
107 catch( CFB::CFBException& exception )
108 {
109 THROW_IO_ERROR( exception.what() );
110 }
111}
112
113
114bool ALTIUM_COMPOUND_FILE::DecodeIntLibStream( const CFB::COMPOUND_FILE_ENTRY& cfe,
115 ALTIUM_COMPOUND_FILE* aOutput )
116{
117 wxCHECK( aOutput, false );
118 wxCHECK( cfe.size >= 1, false );
119
120 size_t streamSize = cfe.size;
121 wxMemoryBuffer buffer( streamSize );
122 buffer.SetDataLen( streamSize );
123
124 // read file into buffer
125 GetCompoundFileReader().ReadFile( &cfe, 0, reinterpret_cast<char*>( buffer.GetData() ),
126 streamSize );
127
128 // 0x02: compressed stream, 0x00: uncompressed
129 if( buffer[0] == 0x02 )
130 {
131 wxMemoryInputStream memoryInputStream( buffer.GetData(), streamSize );
132 memoryInputStream.SeekI( 1, wxFromStart );
133
134 wxZlibInputStream zlibInputStream( memoryInputStream );
135 wxMemoryOutputStream decodedPcbLibStream;
136 decodedPcbLibStream << zlibInputStream;
137
138 wxStreamBuffer* outStream = decodedPcbLibStream.GetOutputStreamBuffer();
139 aOutput->InitFromBuffer( outStream->GetBufferStart(), outStream->GetIntPosition() );
140 return true;
141 }
142 else if( buffer[0] == 0x00 )
143 {
144 aOutput->InitFromBuffer( static_cast<uint8_t*>( buffer.GetData() ) + 1, streamSize - 1 );
145 return true;
146 }
147 else
148 {
149 wxFAIL_MSG( wxString::Format( "Altium IntLib unknown header: %02x %02x %02x %02x %02x",
150 buffer[0], buffer[1], buffer[2], buffer[3], buffer[4] ) );
151 }
152
153 return false;
154}
155
156
157const CFB::COMPOUND_FILE_ENTRY*
158ALTIUM_COMPOUND_FILE::FindStreamSingleLevel( const CFB::COMPOUND_FILE_ENTRY* aEntry,
159 const std::string aName, const bool aIsStream ) const
160{
161 if( !m_reader || !aEntry )
162 return nullptr;
163
164 const CFB::COMPOUND_FILE_ENTRY* ret = nullptr;
165
166 m_reader->EnumFiles( aEntry, 1,
167 [&]( const CFB::COMPOUND_FILE_ENTRY* entry, const CFB::utf16string& dir,
168 int level ) -> int
169 {
170 if( ret != nullptr )
171 return 1;
172
173 if( m_reader->IsStream( entry ) == aIsStream )
174 {
175 std::string name = UTF16ToUTF8( entry->name );
176 if( name == aName.c_str() )
177 {
178 ret = entry;
179 return 1;
180 }
181 }
182
183 return 0;
184 } );
185 return ret;
186}
187
188
189std::map<wxString, ALTIUM_SYMBOL_DATA>
190ALTIUM_COMPOUND_FILE::GetLibSymbols( const CFB::COMPOUND_FILE_ENTRY* aStart ) const
191{
192 const CFB::COMPOUND_FILE_ENTRY* root = aStart ? aStart : m_reader->GetRootEntry();
193
194 if( !root )
195 return {};
196
197 std::map<wxString, ALTIUM_SYMBOL_DATA> folders;
198
199 m_reader->EnumFiles( root, 1, [&]( const CFB::COMPOUND_FILE_ENTRY* tentry,
200 const CFB::utf16string&, int ) -> int
201 {
202 wxString dirName = UTF16ToWstring( tentry->name, tentry->nameLen );
203
204 if( m_reader->IsStream( tentry ) )
205 return 0;
206
207 m_reader->EnumFiles( tentry, 1,
208 [&]( const CFB::COMPOUND_FILE_ENTRY* entry,
209 const CFB::utf16string&, int ) -> int
210 {
211 std::wstring fileName = UTF16ToWstring( entry->name, entry->nameLen );
212
213 if( m_reader->IsStream( entry ) && fileName == L"Data" )
214 folders[dirName].m_symbol = entry;
215
216 if( m_reader->IsStream( entry ) && fileName == L"PinFrac" )
217 folders[dirName].m_pinsFrac = entry;
218
219 if( m_reader->IsStream( entry ) && fileName == L"PinWideText" )
220 folders[dirName].m_pinsWideText = entry;
221
222 if( m_reader->IsStream( entry ) && fileName == L"PinTextData" )
223 folders[dirName].m_pinsTextData = entry;
224
225 return 0;
226 } );
227
228 return 0;
229 } );
230
231 return folders;
232}
233
234
235std::map<wxString, const CFB::COMPOUND_FILE_ENTRY*>
236ALTIUM_COMPOUND_FILE::EnumDir( const std::wstring& aDir ) const
237{
238 const CFB::COMPOUND_FILE_ENTRY* root = m_reader->GetRootEntry();
239
240 if( !root )
241 return {};
242
243 std::map<wxString, const CFB::COMPOUND_FILE_ENTRY*> files;
244
245 m_reader->EnumFiles(
246 root, 1,
247 [&]( const CFB::COMPOUND_FILE_ENTRY* tentry, const CFB::utf16string& dir,
248 int level ) -> int
249 {
250 if( m_reader->IsStream( tentry ) )
251 return 0;
252
253 std::wstring dirName = UTF16ToWstring( tentry->name, tentry->nameLen );
254
255 if( dirName != aDir )
256 return 0;
257
258 m_reader->EnumFiles(
259 tentry, 1,
260 [&]( const CFB::COMPOUND_FILE_ENTRY* entry, const CFB::utf16string&,
261 int ) -> int
262 {
263 if( m_reader->IsStream( entry ) )
264 {
265 std::wstring fileName =
266 UTF16ToWstring( entry->name, entry->nameLen );
267
268 files[fileName] = entry;
269 }
270
271 return 0;
272 } );
273 return 0;
274 } );
275
276 return files;
277}
278
279
280const CFB::COMPOUND_FILE_ENTRY*
281ALTIUM_COMPOUND_FILE::FindStream( const CFB::COMPOUND_FILE_ENTRY* aStart,
282 const std::vector<std::string>& aStreamPath ) const
283{
284 if( !m_reader )
285 return nullptr;
286
287 if( !aStart )
288 aStart = m_reader->GetRootEntry();
289
290 auto it = aStreamPath.cbegin();
291
292 while( aStart != nullptr )
293 {
294 const std::string& name = *it;
295
296 if( ++it == aStreamPath.cend() )
297 {
298 const CFB::COMPOUND_FILE_ENTRY* ret = FindStreamSingleLevel( aStart, name, true );
299 return ret;
300 }
301 else
302 {
303 const CFB::COMPOUND_FILE_ENTRY* ret = FindStreamSingleLevel( aStart, name, false );
304 aStart = ret;
305 }
306 }
307
308 return nullptr;
309}
310
311
312const CFB::COMPOUND_FILE_ENTRY*
313ALTIUM_COMPOUND_FILE::FindStream( const std::vector<std::string>& aStreamPath ) const
314{
315 return FindStream( nullptr, aStreamPath );
316}
317
318
320 const CFB::COMPOUND_FILE_ENTRY* aEntry )
321{
322 m_subrecord_end = nullptr;
323 m_size = static_cast<size_t>( aEntry->size );
324 m_error = false;
325 m_content.reset( new char[m_size] );
326 m_pos = m_content.get();
327
328 // read file into buffer
329 aFile.GetCompoundFileReader().ReadFile( aEntry, 0, m_content.get(), m_size );
330}
331
332
333ALTIUM_BINARY_PARSER::ALTIUM_BINARY_PARSER( std::unique_ptr<char[]>& aContent, size_t aSize )
334{
335 m_subrecord_end = nullptr;
336 m_size = aSize;
337 m_error = false;
338 m_content = std::move( aContent );
339 m_pos = m_content.get();
340}
341
342
343std::map<wxString, wxString> ALTIUM_BINARY_PARSER::ReadProperties(
344 std::function<std::map<wxString, wxString>( const std::string& )> handleBinaryData )
345{
346 // TSAN reports calling this wx macro is not thread-safe
347 static wxCSConv convISO8859_1 = wxConvISO8859_1;
348
349 std::map<wxString, wxString> kv;
350
351 uint32_t length = Read<uint32_t>();
352 bool isBinary = ( length & 0xff000000 ) != 0;
353
354 length &= 0x00ffffff;
355
356 if( length > GetRemainingBytes() )
357 {
358 m_error = true;
359 return kv;
360 }
361
362 if( length == 0 )
363 {
364 return kv;
365 }
366
367 // There is one case by kliment where Board6 ends with "|NEARDISTANCE=1000mi".
368 // Both the 'l' and the null-byte are missing, which looks like Altium swallowed two bytes.
369 bool hasNullByte = m_pos[length - 1] == '\0';
370
371 if( !hasNullByte && !isBinary )
372 {
373 wxLogTrace( "ALTIUM", wxT( "Missing null byte at end of property list. Imported data "
374 "might be malformed or missing." ) );
375 }
376
377 // we use std::string because std::string can handle NULL-bytes
378 // wxString would end the string at the first NULL-byte
379 std::string str = std::string( m_pos, length - ( ( hasNullByte && !isBinary ) ? 1 : 0 ) );
380 m_pos += length;
381
382 if( isBinary )
383 {
384 return handleBinaryData( str );
385 }
386
387 std::size_t token_end = 0;
388
389 while( token_end < str.size() && token_end != std::string::npos )
390 {
391 std::size_t token_start = str.find( '|', token_end );
392 std::size_t token_equal = str.find( '=', token_end );
393 std::size_t key_start;
394
395 if( token_start <= token_equal )
396 {
397 key_start = token_start + 1;
398 }
399 else
400 {
401 // Leading "|" before "RECORD=28" may be missing in older schematic versions.
402 key_start = token_end;
403 }
404
405 token_end = str.find( '|', key_start );
406
407 if( token_equal >= token_end )
408 {
409 continue; // this looks like an error: skip the entry. Also matches on std::string::npos
410 }
411
412 if( token_end == std::string::npos )
413 {
414 token_end = str.size() + 1; // this is the correct offset
415 }
416
417 std::string keyS = str.substr( key_start, token_equal - key_start );
418 std::string valueS = str.substr( token_equal + 1, token_end - token_equal - 1 );
419
420 // convert the strings to wxStrings, since we use them everywhere
421 // value can have non-ASCII characters, so we convert them from LATIN1/ISO8859-1
422 wxString key( keyS.c_str(), convISO8859_1 );
423
424 // Altium stores keys either in Upper, or in CamelCase. Lets unify it.
425 wxString canonicalKey = key.Trim( false ).Trim( true ).MakeUpper();
426
427 // If the key starts with '%UTF8%' we have to parse the value using UTF8
428 wxString value;
429
430 if( canonicalKey.StartsWith( "%UTF8%" ) )
431 value = wxString( valueS.c_str(), wxConvUTF8 );
432 else
433 value = wxString( valueS.c_str(), convISO8859_1 );
434
435 if( canonicalKey != wxS( "PATTERN" ) && canonicalKey != wxS( "SOURCEFOOTPRINTLIBRARY" ) )
436 {
437 // Breathless hack because I haven't a clue what the story is here (but this character
438 // appears in a lot of radial dimensions and is rendered by Altium as a space).
439 value.Replace( wxT( "ÿ" ), wxT( " " ) );
440 }
441
442 kv.insert( { canonicalKey, value.Trim() } );
443 }
444
445 // DESIGNATOR/NAME/TEXT carry Altium overbar markup that must be converted for every record
446 // type except RECORD=4 (LABEL). Older schematics emit those keys ahead of RECORD, so the type
447 // is only reliably known once the whole record has been read; deciding mid-stream both misses
448 // the exemption and, via operator[], leaves an empty RECORD that shadows the real value.
449 auto recordIt = kv.find( wxT( "RECORD" ) );
450
451 if( recordIt == kv.end() || recordIt->second != wxT( "4" ) )
452 {
453 for( const wxString& key : { wxT( "DESIGNATOR" ), wxT( "NAME" ), wxT( "TEXT" ) } )
454 {
455 auto valueIt = kv.find( key );
456
457 if( valueIt != kv.end() )
458 valueIt->second = AltiumPropertyToKiCadString( valueIt->second );
459 }
460 }
461
462 return kv;
463}
const char * name
std::string FormatPath(const std::vector< std::string > &aVectorPath)
Helper for debug logging (vector -> string)
wxString AltiumPropertyToKiCadString(const wxString &aString)
std::unique_ptr< char[]> m_content
ALTIUM_BINARY_PARSER(const ALTIUM_COMPOUND_FILE &aFile, const CFB::COMPOUND_FILE_ENTRY *aEntry)
std::map< wxString, wxString > ReadProperties(std::function< std::map< wxString, wxString >(const std::string &)> handleBinaryData=[](const std::string &) { return std::map< wxString, wxString >();})
ALTIUM_COMPOUND_FILE()
Create an uninitialized file for two-step initialization (e.g. with InitFromBuffer)
const CFB::CompoundFileReader & GetCompoundFileReader() const
const CFB::COMPOUND_FILE_ENTRY * FindStreamSingleLevel(const CFB::COMPOUND_FILE_ENTRY *aEntry, const std::string aName, const bool aIsStream) const
std::map< wxString, const CFB::COMPOUND_FILE_ENTRY * > EnumDir(const std::wstring &aDir) const
void InitFromBuffer(const void *aBuffer, size_t aLen)
Load a CFB file from memory; may throw an IO_ERROR.
std::vector< char > m_buffer
std::unique_ptr< CFB::CompoundFileReader > m_reader
std::map< wxString, ALTIUM_SYMBOL_DATA > GetLibSymbols(const CFB::COMPOUND_FILE_ENTRY *aStart) const
bool DecodeIntLibStream(const CFB::COMPOUND_FILE_ENTRY &cfe, ALTIUM_COMPOUND_FILE *aOutput)
const CFB::COMPOUND_FILE_ENTRY * FindStream(const std::vector< std::string > &aStreamPath) const
#define _(s)
#define THROW_IO_ERROR(msg)
macro which captures the "call site" values of FILE_, __FUNCTION & LINE
#define THROW_IO_ERRORF(msg,...)
#define kv