xref: /aosp_15_r20/external/executorch/backends/xnnpack/runtime/XNNHeader.cpp (revision 523fa7a60841cd1ecfb9cc4201f1ca8b03ed023a)
1 /*
2  * Copyright (c) Meta Platforms, Inc. and affiliates.
3  * All rights reserved.
4  *
5  * This source code is licensed under the BSD-style license found in the
6  * LICENSE file in the root directory of this source tree.
7  */
8 
9 #include <executorch/backends/xnnpack/runtime/XNNHeader.h>
10 
11 #include <cstring>
12 
13 #include <executorch/runtime/core/error.h>
14 #include <executorch/runtime/core/result.h>
15 
16 #pragma clang diagnostic ignored "-Wdeprecated"
17 
18 namespace executorch {
19 namespace backends {
20 namespace xnnpack {
21 namespace delegate {
22 
23 using executorch::runtime::Error;
24 using executorch::runtime::Result;
25 
26 namespace {
27 /// Interprets the 8 bytes at `data` as a little-endian uint64_t.
GetUInt64LE(const uint8_t * data)28 uint64_t GetUInt64LE(const uint8_t* data) {
29   return (uint64_t)data[0] | ((uint64_t)data[1] << 8) |
30       ((uint64_t)data[2] << 16) | ((uint64_t)data[3] << 24) |
31       ((uint64_t)data[4] << 32) | ((uint64_t)data[5] << 40) |
32       ((uint64_t)data[6] << 48) | ((uint64_t)data[7] << 56);
33 }
34 
35 /// Interprets the 4 bytes at `data` as a little-endian uint32_t.
GetUInt32LE(const uint8_t * data)36 uint32_t GetUInt32LE(const uint8_t* data) {
37   return (uint32_t)data[0] | ((uint32_t)data[1] << 8) |
38       ((uint32_t)data[2] << 16) | ((uint32_t)data[3] << 24);
39 }
40 
41 } // namespace
42 
Parse(const void * data,size_t size)43 Result<XNNHeader> XNNHeader::Parse(const void* data, size_t size) {
44   const uint8_t* header_data = (const uint8_t*)data;
45 
46   if (size < XNNHeader::kMinSize) {
47     return Error::InvalidArgument;
48   }
49 
50   const uint8_t* magic_start = header_data + XNNHeader::kMagicOffset;
51   if (std::memcmp(magic_start, XNNHeader::kMagic, XNNHeader::kMagicSize) != 0) {
52     return Error::NotFound;
53   }
54 
55   uint32_t flatbuffer_offset =
56       GetUInt32LE(header_data + XNNHeader::kFlatbufferDataOffsetOffset);
57 
58   uint32_t flatbuffer_size =
59       GetUInt32LE(header_data + XNNHeader::kFlatbufferDataSizeOffset);
60 
61   uint32_t constant_data_offset =
62       GetUInt32LE(header_data + XNNHeader::kConstantDataOffsetOffset);
63 
64   uint64_t constant_data_size =
65       GetUInt64LE(header_data + XNNHeader::kConstantDataSizeOffset);
66 
67   return XNNHeader{
68       flatbuffer_offset,
69       flatbuffer_size,
70       constant_data_offset,
71       constant_data_size};
72 }
73 
74 // Define storage for the static.
75 constexpr char XNNHeader::kMagic[kMagicSize];
76 
77 } // namespace delegate
78 } // namespace xnnpack
79 } // namespace backends
80 } // namespace executorch
81