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 {
58 THROW_IO_ERROR( wxString::Format( _( "Cannot open file '%s'." ), aFilePath ) );
59 }
60
61 fseek( fp, 0, SEEK_END );
62 long len = ftell( fp );
63
64 if( len < 0 )
65 {
66 fclose( fp );
67 THROW_IO_ERROR( _( "Error reading file: cannot determine length." ) );
68 }
69
70 // Read into buffer (TODO: add support for memory-mapped files to avoid this copy!)
71 m_buffer.resize( len );
72
73 fseek( fp, 0, SEEK_SET );
74
75 size_t bytesRead = fread( m_buffer.data(), sizeof( unsigned char ), len, fp );
76 fclose( fp );
77
78 if( static_cast<size_t>( len ) != bytesRead )
79 {
80 THROW_IO_ERROR( _( "Error reading file." ) );
81 }
82
83 try
84 {
85 m_reader = std::make_unique<CFB::CompoundFileReader>( m_buffer.data(), m_buffer.size() );
86 }
87 catch( CFB::CFBException& exception )
88 {
89 THROW_IO_ERROR( exception.what() );
90 }
91}
92
93
94ALTIUM_COMPOUND_FILE::ALTIUM_COMPOUND_FILE( const void* aBuffer, size_t aLen )
95{
96 InitFromBuffer( aBuffer, aLen );
97}
98
99
100void ALTIUM_COMPOUND_FILE::InitFromBuffer( const void* aBuffer, size_t aLen )
101{
102 m_buffer.resize( aLen );
103 memcpy( m_buffer.data(), aBuffer, aLen );
104
105 try
106 {
107 m_reader = std::make_unique<CFB::CompoundFileReader>( m_buffer.data(), m_buffer.size() );
108 }
109 catch( CFB::CFBException& exception )
110 {
111 THROW_IO_ERROR( exception.what() );
112 }
113}
114
115
116bool ALTIUM_COMPOUND_FILE::DecodeIntLibStream( const CFB::COMPOUND_FILE_ENTRY& cfe,
117 ALTIUM_COMPOUND_FILE* aOutput )
118{
119 wxCHECK( aOutput, false );
120 wxCHECK( cfe.size >= 1, false );
121
122 size_t streamSize = cfe.size;
123 wxMemoryBuffer buffer( streamSize );
124 buffer.SetDataLen( streamSize );
125
126 // read file into buffer
127 GetCompoundFileReader().ReadFile( &cfe, 0, reinterpret_cast<char*>( buffer.GetData() ),
128 streamSize );
129
130 // 0x02: compressed stream, 0x00: uncompressed
131 if( buffer[0] == 0x02 )
132 {
133 wxMemoryInputStream memoryInputStream( buffer.GetData(), streamSize );
134 memoryInputStream.SeekI( 1, wxFromStart );
135
136 wxZlibInputStream zlibInputStream( memoryInputStream );
137 wxMemoryOutputStream decodedPcbLibStream;
138 decodedPcbLibStream << zlibInputStream;
139
140 wxStreamBuffer* outStream = decodedPcbLibStream.GetOutputStreamBuffer();
141 aOutput->InitFromBuffer( outStream->GetBufferStart(), outStream->GetIntPosition() );
142 return true;
143 }
144 else if( buffer[0] == 0x00 )
145 {
146 aOutput->InitFromBuffer( static_cast<uint8_t*>( buffer.GetData() ) + 1, streamSize - 1 );
147 return true;
148 }
149 else
150 {
151 wxFAIL_MSG( wxString::Format( "Altium IntLib unknown header: %02x %02x %02x %02x %02x",
152 buffer[0], buffer[1], buffer[2], buffer[3], buffer[4] ) );
153 }
154
155 return false;
156}
157
158
159const CFB::COMPOUND_FILE_ENTRY*
160ALTIUM_COMPOUND_FILE::FindStreamSingleLevel( const CFB::COMPOUND_FILE_ENTRY* aEntry,
161 const std::string aName, const bool aIsStream ) const
162{
163 if( !m_reader || !aEntry )
164 return nullptr;
165
166 const CFB::COMPOUND_FILE_ENTRY* ret = nullptr;
167
168 m_reader->EnumFiles( aEntry, 1,
169 [&]( const CFB::COMPOUND_FILE_ENTRY* entry, const CFB::utf16string& dir,
170 int level ) -> int
171 {
172 if( ret != nullptr )
173 return 1;
174
175 if( m_reader->IsStream( entry ) == aIsStream )
176 {
177 std::string name = UTF16ToUTF8( entry->name );
178 if( name == aName.c_str() )
179 {
180 ret = entry;
181 return 1;
182 }
183 }
184
185 return 0;
186 } );
187 return ret;
188}
189
190
191std::map<wxString, ALTIUM_SYMBOL_DATA>
192ALTIUM_COMPOUND_FILE::GetLibSymbols( const CFB::COMPOUND_FILE_ENTRY* aStart ) const
193{
194 const CFB::COMPOUND_FILE_ENTRY* root = aStart ? aStart : m_reader->GetRootEntry();
195
196 if( !root )
197 return {};
198
199 std::map<wxString, ALTIUM_SYMBOL_DATA> folders;
200
201 m_reader->EnumFiles( root, 1, [&]( const CFB::COMPOUND_FILE_ENTRY* tentry,
202 const CFB::utf16string&, int ) -> int
203 {
204 wxString dirName = UTF16ToWstring( tentry->name, tentry->nameLen );
205
206 if( m_reader->IsStream( tentry ) )
207 return 0;
208
209 m_reader->EnumFiles( tentry, 1,
210 [&]( const CFB::COMPOUND_FILE_ENTRY* entry,
211 const CFB::utf16string&, int ) -> int
212 {
213 std::wstring fileName = UTF16ToWstring( entry->name, entry->nameLen );
214
215 if( m_reader->IsStream( entry ) && fileName == L"Data" )
216 folders[dirName].m_symbol = entry;
217
218 if( m_reader->IsStream( entry ) && fileName == L"PinFrac" )
219 folders[dirName].m_pinsFrac = entry;
220
221 if( m_reader->IsStream( entry ) && fileName == L"PinWideText" )
222 folders[dirName].m_pinsWideText = entry;
223
224 if( m_reader->IsStream( entry ) && fileName == L"PinTextData" )
225 folders[dirName].m_pinsTextData = entry;
226
227 return 0;
228 } );
229
230 return 0;
231 } );
232
233 return folders;
234}
235
236
237std::map<wxString, const CFB::COMPOUND_FILE_ENTRY*>
238ALTIUM_COMPOUND_FILE::EnumDir( const std::wstring& aDir ) const
239{
240 const CFB::COMPOUND_FILE_ENTRY* root = m_reader->GetRootEntry();
241
242 if( !root )
243 return {};
244
245 std::map<wxString, const CFB::COMPOUND_FILE_ENTRY*> files;
246
247 m_reader->EnumFiles(
248 root, 1,
249 [&]( const CFB::COMPOUND_FILE_ENTRY* tentry, const CFB::utf16string& dir,
250 int level ) -> int
251 {
252 if( m_reader->IsStream( tentry ) )
253 return 0;
254
255 std::wstring dirName = UTF16ToWstring( tentry->name, tentry->nameLen );
256
257 if( dirName != aDir )
258 return 0;
259
260 m_reader->EnumFiles(
261 tentry, 1,
262 [&]( const CFB::COMPOUND_FILE_ENTRY* entry, const CFB::utf16string&,
263 int ) -> int
264 {
265 if( m_reader->IsStream( entry ) )
266 {
267 std::wstring fileName =
268 UTF16ToWstring( entry->name, entry->nameLen );
269
270 files[fileName] = entry;
271 }
272
273 return 0;
274 } );
275 return 0;
276 } );
277
278 return files;
279}
280
281
282const CFB::COMPOUND_FILE_ENTRY*
283ALTIUM_COMPOUND_FILE::FindStream( const CFB::COMPOUND_FILE_ENTRY* aStart,
284 const std::vector<std::string>& aStreamPath ) const
285{
286 if( !m_reader )
287 return nullptr;
288
289 if( !aStart )
290 aStart = m_reader->GetRootEntry();
291
292 auto it = aStreamPath.cbegin();
293
294 while( aStart != nullptr )
295 {
296 const std::string& name = *it;
297
298 if( ++it == aStreamPath.cend() )
299 {
300 const CFB::COMPOUND_FILE_ENTRY* ret = FindStreamSingleLevel( aStart, name, true );
301 return ret;
302 }
303 else
304 {
305 const CFB::COMPOUND_FILE_ENTRY* ret = FindStreamSingleLevel( aStart, name, false );
306 aStart = ret;
307 }
308 }
309
310 return nullptr;
311}
312
313
314const CFB::COMPOUND_FILE_ENTRY*
315ALTIUM_COMPOUND_FILE::FindStream( const std::vector<std::string>& aStreamPath ) const
316{
317 return FindStream( nullptr, aStreamPath );
318}
319
320
322 const CFB::COMPOUND_FILE_ENTRY* aEntry )
323{
324 m_subrecord_end = nullptr;
325 m_size = static_cast<size_t>( aEntry->size );
326 m_error = false;
327 m_content.reset( new char[m_size] );
328 m_pos = m_content.get();
329
330 // read file into buffer
331 aFile.GetCompoundFileReader().ReadFile( aEntry, 0, m_content.get(), m_size );
332}
333
334
335ALTIUM_BINARY_PARSER::ALTIUM_BINARY_PARSER( std::unique_ptr<char[]>& aContent, size_t aSize )
336{
337 m_subrecord_end = nullptr;
338 m_size = aSize;
339 m_error = false;
340 m_content = std::move( aContent );
341 m_pos = m_content.get();
342}
343
344
345std::map<wxString, wxString> ALTIUM_BINARY_PARSER::ReadProperties(
346 std::function<std::map<wxString, wxString>( const std::string& )> handleBinaryData )
347{
348 // TSAN reports calling this wx macro is not thread-safe
349 static wxCSConv convISO8859_1 = wxConvISO8859_1;
350
351 std::map<wxString, wxString> kv;
352
353 uint32_t length = Read<uint32_t>();
354 bool isBinary = ( length & 0xff000000 ) != 0;
355
356 length &= 0x00ffffff;
357
358 if( length > GetRemainingBytes() )
359 {
360 m_error = true;
361 return kv;
362 }
363
364 if( length == 0 )
365 {
366 return kv;
367 }
368
369 // There is one case by kliment where Board6 ends with "|NEARDISTANCE=1000mi".
370 // Both the 'l' and the null-byte are missing, which looks like Altium swallowed two bytes.
371 bool hasNullByte = m_pos[length - 1] == '\0';
372
373 if( !hasNullByte && !isBinary )
374 {
375 wxLogTrace( "ALTIUM", wxT( "Missing null byte at end of property list. Imported data "
376 "might be malformed or missing." ) );
377 }
378
379 // we use std::string because std::string can handle NULL-bytes
380 // wxString would end the string at the first NULL-byte
381 std::string str = std::string( m_pos, length - ( ( hasNullByte && !isBinary ) ? 1 : 0 ) );
382 m_pos += length;
383
384 if( isBinary )
385 {
386 return handleBinaryData( str );
387 }
388
389 std::size_t token_end = 0;
390
391 while( token_end < str.size() && token_end != std::string::npos )
392 {
393 std::size_t token_start = str.find( '|', token_end );
394 std::size_t token_equal = str.find( '=', token_end );
395 std::size_t key_start;
396
397 if( token_start <= token_equal )
398 {
399 key_start = token_start + 1;
400 }
401 else
402 {
403 // Leading "|" before "RECORD=28" may be missing in older schematic versions.
404 key_start = token_end;
405 }
406
407 token_end = str.find( '|', key_start );
408
409 if( token_equal >= token_end )
410 {
411 continue; // this looks like an error: skip the entry. Also matches on std::string::npos
412 }
413
414 if( token_end == std::string::npos )
415 {
416 token_end = str.size() + 1; // this is the correct offset
417 }
418
419 std::string keyS = str.substr( key_start, token_equal - key_start );
420 std::string valueS = str.substr( token_equal + 1, token_end - token_equal - 1 );
421
422 // convert the strings to wxStrings, since we use them everywhere
423 // value can have non-ASCII characters, so we convert them from LATIN1/ISO8859-1
424 wxString key( keyS.c_str(), convISO8859_1 );
425
426 // Altium stores keys either in Upper, or in CamelCase. Lets unify it.
427 wxString canonicalKey = key.Trim( false ).Trim( true ).MakeUpper();
428
429 // If the key starts with '%UTF8%' we have to parse the value using UTF8
430 wxString value;
431
432 if( canonicalKey.StartsWith( "%UTF8%" ) )
433 value = wxString( valueS.c_str(), wxConvUTF8 );
434 else
435 value = wxString( valueS.c_str(), convISO8859_1 );
436
437 if( canonicalKey != wxS( "PATTERN" ) && canonicalKey != wxS( "SOURCEFOOTPRINTLIBRARY" ) )
438 {
439 // Breathless hack because I haven't a clue what the story is here (but this character
440 // appears in a lot of radial dimensions and is rendered by Altium as a space).
441 value.Replace( wxT( "ÿ" ), wxT( " " ) );
442 }
443
444 if( canonicalKey == wxT( "DESIGNATOR" )
445 || canonicalKey == wxT( "NAME" )
446 || canonicalKey == wxT( "TEXT" ) )
447 {
448 if( kv[ wxT( "RECORD" ) ] != wxT( "4" ) )
449 value = AltiumPropertyToKiCadString( value.Trim() );
450 }
451
452 kv.insert( { canonicalKey, value.Trim() } );
453 }
454
455 return kv;
456}
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 kv