FBXBinaryTokenizer.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2025, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. /** @file FBXBinaryTokenizer.cpp
  34. * @brief Implementation of a fake lexer for binary fbx files -
  35. * we emit tokens so the parser needs almost no special handling
  36. * for binary files.
  37. */
  38. #ifndef ASSIMP_BUILD_NO_FBX_IMPORTER
  39. #include "FBXTokenizer.h"
  40. #include "FBXUtil.h"
  41. #include <assimp/defs.h>
  42. #include <stdint.h>
  43. #include <cstdint>
  44. #include <assimp/Exceptional.h>
  45. #include <assimp/ByteSwapper.h>
  46. #include <assimp/DefaultLogger.hpp>
  47. #include <assimp/StringUtils.h>
  48. namespace Assimp {
  49. namespace FBX {
  50. // ------------------------------------------------------------------------------------------------
  51. Token::Token(const char* sbegin, const char* send, TokenType type, size_t offset) :
  52. #ifdef DEBUG
  53. contents(sbegin, static_cast<size_t>(send-sbegin)),
  54. #endif
  55. sbegin(sbegin),
  56. send(send),
  57. type(type),
  58. line(offset),
  59. column(BINARY_MARKER) {
  60. ai_assert(sbegin);
  61. ai_assert(send);
  62. // binary tokens may have zero length because they are sometimes dummies
  63. // inserted by TokenizeBinary()
  64. ai_assert(send >= sbegin);
  65. }
  66. namespace {
  67. // ------------------------------------------------------------------------------------------------
  68. // signal tokenization error, this is always unrecoverable. Throws DeadlyImportError.
  69. AI_WONT_RETURN void TokenizeError(const std::string& message, size_t offset) AI_WONT_RETURN_SUFFIX;
  70. AI_WONT_RETURN void TokenizeError(const std::string& message, size_t offset)
  71. {
  72. throw DeadlyImportError("FBX-Tokenize", Util::GetOffsetText(offset), message);
  73. }
  74. // ------------------------------------------------------------------------------------------------
  75. size_t Offset(const char* begin, const char* cursor) {
  76. if (begin > cursor) {
  77. return 0;
  78. }
  79. return cursor - begin;
  80. }
  81. // ------------------------------------------------------------------------------------------------
  82. AI_WONT_RETURN void TokenizeError(const std::string& message, const char* begin, const char* cursor) AI_WONT_RETURN_SUFFIX;
  83. void TokenizeError(const std::string& message, const char* begin, const char* cursor) {
  84. TokenizeError(message, Offset(begin, cursor));
  85. }
  86. // ------------------------------------------------------------------------------------------------
  87. uint32_t ReadWord(const char* input, const char*& cursor, const char* end) {
  88. const size_t k_to_read = sizeof( uint32_t );
  89. if(Offset(cursor, end) < k_to_read ) {
  90. TokenizeError("cannot ReadWord, out of bounds",input, cursor);
  91. }
  92. uint32_t word;
  93. ::memcpy(&word, cursor, 4);
  94. AI_SWAP4(word);
  95. cursor += k_to_read;
  96. return word;
  97. }
  98. // ------------------------------------------------------------------------------------------------
  99. uint64_t ReadDoubleWord(const char* input, const char*& cursor, const char* end) {
  100. const size_t k_to_read = sizeof(uint64_t);
  101. if(Offset(cursor, end) < k_to_read) {
  102. TokenizeError("cannot ReadDoubleWord, out of bounds",input, cursor);
  103. }
  104. uint64_t dword /*= *reinterpret_cast<const uint64_t*>(cursor)*/;
  105. ::memcpy( &dword, cursor, sizeof( uint64_t ) );
  106. AI_SWAP8(dword);
  107. cursor += k_to_read;
  108. return dword;
  109. }
  110. // ------------------------------------------------------------------------------------------------
  111. uint8_t ReadByte(const char* input, const char*& cursor, const char* end) {
  112. if(Offset(cursor, end) < sizeof( uint8_t ) ) {
  113. TokenizeError("cannot ReadByte, out of bounds",input, cursor);
  114. }
  115. uint8_t word;/* = *reinterpret_cast< const uint8_t* >( cursor )*/
  116. ::memcpy( &word, cursor, sizeof( uint8_t ) );
  117. ++cursor;
  118. return word;
  119. }
  120. // ------------------------------------------------------------------------------------------------
  121. unsigned int ReadString(const char*& sbegin_out, const char*& send_out, const char* input,
  122. const char*& cursor, const char* end, bool long_length = false, bool allow_null = false) {
  123. const uint32_t len_len = long_length ? 4 : 1;
  124. if(Offset(cursor, end) < len_len) {
  125. TokenizeError("cannot ReadString, out of bounds reading length",input, cursor);
  126. }
  127. const uint32_t length = long_length ? ReadWord(input, cursor, end) : ReadByte(input, cursor, end);
  128. if (Offset(cursor, end) < length) {
  129. TokenizeError("cannot ReadString, length is out of bounds",input, cursor);
  130. }
  131. sbegin_out = cursor;
  132. cursor += length;
  133. send_out = cursor;
  134. if(!allow_null) {
  135. for (unsigned int i = 0; i < length; ++i) {
  136. if(sbegin_out[i] == '\0') {
  137. TokenizeError("failed ReadString, unexpected NUL character in string",input, cursor);
  138. }
  139. }
  140. }
  141. return length;
  142. }
  143. // ------------------------------------------------------------------------------------------------
  144. void ReadData(const char*& sbegin_out, const char*& send_out, const char* input, const char*& cursor, const char* end) {
  145. if(Offset(cursor, end) < 1) {
  146. TokenizeError("cannot ReadData, out of bounds reading length",input, cursor);
  147. }
  148. const char type = *cursor;
  149. sbegin_out = cursor++;
  150. switch(type)
  151. {
  152. // 16 bit int
  153. case 'Y':
  154. cursor += 2;
  155. break;
  156. // 1 bit bool flag (yes/no)
  157. case 'C':
  158. cursor += 1;
  159. break;
  160. // 32 bit int
  161. case 'I':
  162. // <- fall through
  163. // float
  164. case 'F':
  165. cursor += 4;
  166. break;
  167. // double
  168. case 'D':
  169. cursor += 8;
  170. break;
  171. // 64 bit int
  172. case 'L':
  173. cursor += 8;
  174. break;
  175. // note: do not write cursor += ReadWord(...cursor) as this would be UB
  176. // raw binary data
  177. case 'R':
  178. {
  179. const uint32_t length = ReadWord(input, cursor, end);
  180. cursor += length;
  181. break;
  182. }
  183. case 'b':
  184. // TODO: what is the 'b' type code? Right now we just skip over it /
  185. // take the full range we could get
  186. cursor = end;
  187. break;
  188. // array of *
  189. case 'f':
  190. case 'd':
  191. case 'l':
  192. case 'i':
  193. case 'c': {
  194. const uint32_t length = ReadWord(input, cursor, end);
  195. const uint32_t encoding = ReadWord(input, cursor, end);
  196. const uint32_t comp_len = ReadWord(input, cursor, end);
  197. // compute length based on type and check against the stored value
  198. if(encoding == 0) {
  199. uint32_t stride = 0;
  200. switch(type)
  201. {
  202. case 'f':
  203. case 'i':
  204. stride = 4;
  205. break;
  206. case 'd':
  207. case 'l':
  208. stride = 8;
  209. break;
  210. case 'c':
  211. stride = 1;
  212. break;
  213. default:
  214. ai_assert(false);
  215. };
  216. ai_assert(stride > 0);
  217. if(length * stride != comp_len) {
  218. TokenizeError("cannot ReadData, calculated data stride differs from what the file claims",input, cursor);
  219. }
  220. }
  221. // zip/deflate algorithm (encoding==1)? take given length. anything else? die
  222. else if (encoding != 1) {
  223. TokenizeError("cannot ReadData, unknown encoding",input, cursor);
  224. }
  225. cursor += comp_len;
  226. break;
  227. }
  228. // string
  229. case 'S': {
  230. const char* sb, *se;
  231. // 0 characters can legally happen in such strings
  232. ReadString(sb, se, input, cursor, end, true, true);
  233. break;
  234. }
  235. default:
  236. TokenizeError("cannot ReadData, unexpected type code: " + std::string(&type, 1),input, cursor);
  237. }
  238. if(cursor > end) {
  239. TokenizeError("cannot ReadData, the remaining size is too small for the data type: " + std::string(&type, 1),input, cursor);
  240. }
  241. // the type code is contained in the returned range
  242. send_out = cursor;
  243. }
  244. // ------------------------------------------------------------------------------------------------
  245. bool ReadScope(TokenList &output_tokens, StackAllocator &token_allocator, const char *input, const char *&cursor, const char *end, bool const is64bits) {
  246. // the first word contains the offset at which this block ends
  247. const uint64_t end_offset = is64bits ? ReadDoubleWord(input, cursor, end) : ReadWord(input, cursor, end);
  248. // we may get 0 if reading reached the end of the file -
  249. // fbx files have a mysterious extra footer which I don't know
  250. // how to extract any information from, but at least it always
  251. // starts with a 0.
  252. if(!end_offset) {
  253. return false;
  254. }
  255. if(end_offset > Offset(input, end)) {
  256. TokenizeError("block offset is out of range",input, cursor);
  257. }
  258. else if(end_offset < Offset(input, cursor)) {
  259. TokenizeError("block offset is negative out of range",input, cursor);
  260. }
  261. // the second data word contains the number of properties in the scope
  262. const uint64_t prop_count = is64bits ? ReadDoubleWord(input, cursor, end) : ReadWord(input, cursor, end);
  263. // the third data word contains the length of the property list
  264. const uint64_t prop_length = is64bits ? ReadDoubleWord(input, cursor, end) : ReadWord(input, cursor, end);
  265. // now comes the name of the scope/key
  266. const char* sbeg, *send;
  267. ReadString(sbeg, send, input, cursor, end);
  268. output_tokens.push_back(new_Token(sbeg, send, TokenType_KEY, Offset(input, cursor) ));
  269. // now come the individual properties
  270. const char* begin_cursor = cursor;
  271. if ((begin_cursor + prop_length) > end) {
  272. TokenizeError("property length out of bounds reading length ", input, cursor);
  273. }
  274. for (unsigned int i = 0; i < prop_count; ++i) {
  275. ReadData(sbeg, send, input, cursor, begin_cursor + prop_length);
  276. output_tokens.push_back(new_Token(sbeg, send, TokenType_DATA, Offset(input, cursor) ));
  277. if(i != prop_count-1) {
  278. output_tokens.push_back(new_Token(cursor, cursor + 1, TokenType_COMMA, Offset(input, cursor) ));
  279. }
  280. }
  281. if (Offset(begin_cursor, cursor) != prop_length) {
  282. TokenizeError("property length not reached, something is wrong",input, cursor);
  283. }
  284. // at the end of each nested block, there is a NUL record to indicate
  285. // that the sub-scope exists (i.e. to distinguish between P: and P : {})
  286. // this NUL record is 13 bytes long on 32 bit version and 25 bytes long on 64 bit.
  287. const size_t sentinel_block_length = is64bits ? (sizeof(uint64_t)* 3 + 1) : (sizeof(uint32_t)* 3 + 1);
  288. if (Offset(input, cursor) < end_offset) {
  289. if (end_offset - Offset(input, cursor) < sentinel_block_length) {
  290. TokenizeError("insufficient padding bytes at block end",input, cursor);
  291. }
  292. output_tokens.push_back(new_Token(cursor, cursor + 1, TokenType_OPEN_BRACKET, Offset(input, cursor) ));
  293. // XXX this is vulnerable to stack overflowing ..
  294. while(Offset(input, cursor) < end_offset - sentinel_block_length) {
  295. ReadScope(output_tokens, token_allocator, input, cursor, input + end_offset - sentinel_block_length, is64bits);
  296. }
  297. output_tokens.push_back(new_Token(cursor, cursor + 1, TokenType_CLOSE_BRACKET, Offset(input, cursor) ));
  298. for (unsigned int i = 0; i < sentinel_block_length; ++i) {
  299. if(cursor[i] != '\0') {
  300. TokenizeError("failed to read nested block sentinel, expected all bytes to be 0",input, cursor);
  301. }
  302. }
  303. cursor += sentinel_block_length;
  304. }
  305. if (Offset(input, cursor) != end_offset) {
  306. TokenizeError("scope length not reached, something is wrong",input, cursor);
  307. }
  308. return true;
  309. }
  310. } // anonymous namespace
  311. // ------------------------------------------------------------------------------------------------
  312. // TODO: Test FBX Binary files newer than the 7500 version to check if the 64 bits address behaviour is consistent
  313. void TokenizeBinary(TokenList &output_tokens, const char *input, size_t length, StackAllocator &token_allocator) {
  314. ai_assert(input);
  315. ASSIMP_LOG_DEBUG("Tokenizing binary FBX file");
  316. if(length < 0x1b) {
  317. TokenizeError("file is too short",0);
  318. }
  319. //uint32_t offset = 0x15;
  320. /* const char* cursor = input + 0x15;
  321. const uint32_t flags = ReadWord(input, cursor, input + length);
  322. const uint8_t padding_0 = ReadByte(input, cursor, input + length); // unused
  323. const uint8_t padding_1 = ReadByte(input, cursor, input + length); // unused*/
  324. if (strncmp(input,"Kaydara FBX Binary",18)) {
  325. TokenizeError("magic bytes not found",0);
  326. }
  327. const char* cursor = input + 18;
  328. /*Result ignored*/ ReadByte(input, cursor, input + length);
  329. /*Result ignored*/ ReadByte(input, cursor, input + length);
  330. /*Result ignored*/ ReadByte(input, cursor, input + length);
  331. /*Result ignored*/ ReadByte(input, cursor, input + length);
  332. /*Result ignored*/ ReadByte(input, cursor, input + length);
  333. const uint32_t version = ReadWord(input, cursor, input + length);
  334. ASSIMP_LOG_DEBUG("FBX version: ", version);
  335. const bool is64bits = version >= 7500;
  336. const char *end = input + length;
  337. try
  338. {
  339. while (cursor < end ) {
  340. if (!ReadScope(output_tokens, token_allocator, input, cursor, input + length, is64bits)) {
  341. break;
  342. }
  343. }
  344. }
  345. catch (const DeadlyImportError& e)
  346. {
  347. if (!is64bits && (length > std::numeric_limits<uint32_t>::max())) {
  348. throw DeadlyImportError("The FBX file is invalid. This may be because the content is too big for this older version (", ai_to_string(version), ") of the FBX format. (", e.what(), ")");
  349. }
  350. throw;
  351. }
  352. }
  353. } // !FBX
  354. } // !Assimp
  355. #endif