Repository navigation
Expand file tree
/
Copy pathprogram_test.cpp
More file actions
1272 lines (1084 loc) · 46 KB
/
Copy pathprogram_test.cpp
File metadata and controls
1272 lines (1084 loc) · 46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <executorch/runtime/executor/program.h>
#include <cctype>
#include <filesystem>
#include <fstream>
#include <system_error>
#include <cstring>
#include <memory>
#include <executorch/extension/data_loader/buffer_data_loader.h>
#include <executorch/extension/data_loader/file_data_loader.h>
#include <executorch/runtime/core/error.h>
#include <executorch/runtime/core/result.h>
#include <executorch/runtime/platform/runtime.h>
#include <executorch/schema/program_generated.h>
#include <executorch/test/utils/DeathTest.h>
#include <gtest/gtest.h>
using namespace ::testing;
using executorch::runtime::DataLoader;
using executorch::runtime::Error;
using executorch::runtime::FreeableBuffer;
using executorch::runtime::Program;
using executorch::runtime::Result;
using torch::executor::util::BufferDataLoader;
using torch::executor::util::FileDataLoader;
// Verification level to use for tests not specifically focused on verification.
// Use the highest level to exercise it more.
constexpr Program::Verification kDefaultVerification =
Program::Verification::InternalConsistency;
class ProgramTest : public ::testing::Test {
protected:
void SetUp() override {
// Since these tests cause ET_LOG to be called, the PAL must be initialized
// first.
executorch::runtime::runtime_init();
// Load the serialized ModuleAdd data.
const char* path = std::getenv("ET_MODULE_ADD_PATH");
Result<FileDataLoader> loader = FileDataLoader::from(path);
ASSERT_EQ(loader.error(), Error::Ok);
// This file should always be compatible.
Result<FreeableBuffer> header = loader->load(
/*offset=*/0,
Program::kMinHeadBytes,
/*segment_info=*/
DataLoader::SegmentInfo(DataLoader::SegmentInfo::Type::Program));
ASSERT_EQ(header.error(), Error::Ok);
EXPECT_EQ(
Program::check_header(header->data(), header->size()),
Program::HeaderStatus::CompatibleVersion);
add_loader_ = std::make_unique<FileDataLoader>(std::move(loader.get()));
// Load the serialized ModuleMultiEntry data.
path = std::getenv("ET_MODULE_MULTI_ENTRY_PATH");
Result<FileDataLoader> multi_loader = FileDataLoader::from(path);
ASSERT_EQ(multi_loader.error(), Error::Ok);
// This file should always be compatible.
Result<FreeableBuffer> multi_header = multi_loader->load(
/*offset=*/0,
Program::kMinHeadBytes,
/*segment_info=*/
DataLoader::SegmentInfo(DataLoader::SegmentInfo::Type::Program));
ASSERT_EQ(multi_header.error(), Error::Ok);
EXPECT_EQ(
Program::check_header(multi_header->data(), multi_header->size()),
Program::HeaderStatus::CompatibleVersion);
multi_loader_ =
std::make_unique<FileDataLoader>(std::move(multi_loader.get()));
}
std::unique_ptr<FileDataLoader> add_loader_;
std::unique_ptr<FileDataLoader> multi_loader_;
};
namespace executorch {
namespace runtime {
namespace testing {
// Provides access to private Program methods.
class ProgramTestFriend final {
public:
ET_NODISCARD static Result<FreeableBuffer> LoadSegment(
const Program* program,
const DataLoader::SegmentInfo& segment_info) {
return program->LoadSegment(segment_info);
}
ET_NODISCARD static Error load_mutable_subsegment_into(
const Program* program,
size_t mutable_data_segments_index,
size_t offset_index,
size_t size,
void* buffer) {
return program->load_mutable_subsegment_into(
mutable_data_segments_index, offset_index, size, buffer);
}
ET_NODISCARD static Result<FreeableBuffer> load_mutable_subsegment(
const Program* program,
size_t mutable_data_segments_index,
size_t offset_index,
size_t size) {
return program->load_mutable_subsegment(
mutable_data_segments_index, offset_index, size);
}
const static executorch_flatbuffer::Program* GetInternalProgram(
const Program* program) {
return program->internal_program_;
}
static Result<const void*> get_constant_buffer_data(
const Program* program,
size_t buffer_index,
size_t nbytes) {
return program->get_constant_buffer_data(buffer_index, nbytes);
}
// Constructs a Program directly with a chosen segment_base_offset and a
// pre-built FlatBuffer body. Used to set up malformed states (e.g.
// segment_base_offset != 0 but segments == null) that Program::load cannot
// produce, since segment_base_offset is driven only by the extended header.
static Program MakeProgram(
DataLoader* loader,
size_t segment_base_offset,
const executorch_flatbuffer::Program* internal_program) {
return Program(
loader,
segment_base_offset,
FreeableBuffer{},
internal_program,
FreeableBuffer{},
std::nullopt);
}
};
} // namespace testing
} // namespace runtime
} // namespace executorch
using executorch::runtime::testing::ProgramTestFriend;
TEST_F(ProgramTest, DataParsesWithMinimalVerification) {
// Parse the Program from the data.
Result<Program> program =
Program::load(add_loader_.get(), Program::Verification::Minimal);
// Should have succeeded.
EXPECT_EQ(program.error(), Error::Ok);
}
TEST_F(ProgramTest, DataParsesWithInternalConsistencyVerification) {
// Parse the Program from the data.
Result<Program> program = Program::load(
add_loader_.get(), Program::Verification::InternalConsistency);
// Should have succeeded.
EXPECT_EQ(program.error(), Error::Ok);
}
TEST_F(ProgramTest, BadMagicFailsToLoad) {
// Make a local copy of the data.
size_t data_len = add_loader_->size().get();
auto data = std::make_unique<char[]>(data_len);
{
Result<FreeableBuffer> src = add_loader_->load(
/*offset=*/0,
data_len,
/*segment_info=*/
DataLoader::SegmentInfo(DataLoader::SegmentInfo::Type::Program));
ASSERT_EQ(src.error(), Error::Ok);
ASSERT_EQ(src->size(), data_len);
memcpy(data.get(), src->data(), data_len);
// FreeableBuffer goes out of scope and frees its data.
}
// Corrupt the magic value.
EXPECT_EQ(data[4], 'E');
data[4] = 'X';
EXPECT_EQ(data[5], 'T');
data[5] = 'Y';
// Wrap the modified data in a loader.
BufferDataLoader data_loader(data.get(), data_len);
{
// Parse the Program from the data. Use minimal verification to show that
// even this catches the header problem.
Result<Program> program =
Program::load(&data_loader, Program::Verification::Minimal);
// Should fail.
ASSERT_EQ(program.error(), Error::InvalidProgram);
}
// Fix the data.
data[4] = 'E';
data[5] = 'T';
{
// Parse the Program from the data again.
Result<Program> program =
Program::load(&data_loader, Program::Verification::Minimal);
// Should now succeed.
ASSERT_EQ(program.error(), Error::Ok);
}
}
namespace {
// Builds the smallest program that Program::load() accepts, stamped with the
// given schema version.
std::vector<uint8_t> CreateProgramWithVersion(uint32_t version) {
flatbuffers::FlatBufferBuilder builder(1024);
auto plan_name = builder.CreateString("forward");
auto empty_values = builder.CreateVector(
std::vector<flatbuffers::Offset<executorch_flatbuffer::EValue>>{});
auto empty_inputs = builder.CreateVector(std::vector<int32_t>{});
auto empty_outputs = builder.CreateVector(std::vector<int32_t>{});
auto empty_chains = builder.CreateVector(
std::vector<flatbuffers::Offset<executorch_flatbuffer::Chain>>{});
auto empty_operators = builder.CreateVector(
std::vector<flatbuffers::Offset<executorch_flatbuffer::Operator>>{});
auto empty_delegates = builder.CreateVector(
std::vector<
flatbuffers::Offset<executorch_flatbuffer::BackendDelegate>>{});
auto buffer_sizes = builder.CreateVector(std::vector<int64_t>{0});
auto execution_plan = executorch_flatbuffer::CreateExecutionPlan(
builder,
plan_name,
/*container_meta_type=*/0,
empty_values,
empty_inputs,
empty_outputs,
empty_chains,
empty_operators,
empty_delegates,
buffer_sizes);
auto execution_plans = builder.CreateVector(
std::vector<flatbuffers::Offset<executorch_flatbuffer::ExecutionPlan>>{
execution_plan});
// A constant segment holding only the placeholder offset means "no
// constants", which keeps this program off the deprecated constant_buffer
// path that OSS builds compile out.
auto constant_segment = executorch_flatbuffer::CreateSubsegmentOffsets(
builder,
/*segment_index=*/0,
builder.CreateVector(std::vector<uint64_t>{0}));
auto program = executorch_flatbuffer::CreateProgram(
builder,
version,
execution_plans,
/*constant_buffer=*/0,
/*backend_delegate_data=*/0,
/*segments=*/0,
constant_segment);
builder.Finish(program, executorch_flatbuffer::ProgramIdentifier());
const uint8_t* data = builder.GetBufferPointer();
return std::vector<uint8_t>(data, data + builder.GetSize());
}
// Builds a program whose constant segment exists but holds no bytes. A program
// whose only constants are zero-length tensors looks exactly like this: the
// offsets vector has a real entry per constant, while the segment itself is
// empty.
std::vector<uint8_t> CreateProgramWithEmptyConstantSegment() {
flatbuffers::FlatBufferBuilder builder(1024);
auto plan_name = builder.CreateString("forward");
auto empty_values = builder.CreateVector(
std::vector<flatbuffers::Offset<executorch_flatbuffer::EValue>>{});
auto empty_inputs = builder.CreateVector(std::vector<int32_t>{});
auto empty_outputs = builder.CreateVector(std::vector<int32_t>{});
auto empty_chains = builder.CreateVector(
std::vector<flatbuffers::Offset<executorch_flatbuffer::Chain>>{});
auto empty_operators = builder.CreateVector(
std::vector<flatbuffers::Offset<executorch_flatbuffer::Operator>>{});
auto empty_delegates = builder.CreateVector(
std::vector<
flatbuffers::Offset<executorch_flatbuffer::BackendDelegate>>{});
auto buffer_sizes = builder.CreateVector(std::vector<int64_t>{0});
auto execution_plan = executorch_flatbuffer::CreateExecutionPlan(
builder,
plan_name,
/*container_meta_type=*/0,
empty_values,
empty_inputs,
empty_outputs,
empty_chains,
empty_operators,
empty_delegates,
buffer_sizes);
auto execution_plans = builder.CreateVector(
std::vector<flatbuffers::Offset<executorch_flatbuffer::ExecutionPlan>>{
execution_plan});
// Index 0 is the usual non-constant placeholder; index 1 is a zero-length
// constant, which occupies no bytes in the segment.
auto constant_segment = executorch_flatbuffer::CreateSubsegmentOffsets(
builder,
/*segment_index=*/0,
builder.CreateVector(std::vector<uint64_t>{0, 0}));
auto segments = builder.CreateVector(
std::vector<flatbuffers::Offset<executorch_flatbuffer::DataSegment>>{
executorch_flatbuffer::CreateDataSegment(
builder, /*offset=*/0, /*size=*/0)});
auto program = executorch_flatbuffer::CreateProgram(
builder,
Program::kMaxSupportedSchemaVersion,
execution_plans,
/*constant_buffer=*/0,
/*backend_delegate_data=*/0,
segments,
constant_segment);
builder.Finish(program, executorch_flatbuffer::ProgramIdentifier());
const uint8_t* data = builder.GetBufferPointer();
return std::vector<uint8_t>(data, data + builder.GetSize());
}
} // namespace
// An empty constant segment loads to a null pointer, which must not be mistaken
// for "this program uses the deprecated inline constant_buffer". Doing so fails
// the load outright in builds that compile that path out.
TEST_F(ProgramTest, EmptyConstantSegmentIsStillASegment) {
std::vector<uint8_t> data = CreateProgramWithEmptyConstantSegment();
// Must go through a loader that returns a null pointer for a zero-length
// read, which is what FileDataLoader does ("don't bother allocating for
// empty segments") and what makes the segment indistinguishable from an
// absent one. BufferDataLoader hands back a pointer into its own buffer and
// would hide this.
// std::filesystem::path, not std::string: path::value_type is wchar_t on
// Windows, so there is no implicit conversion to std::string there.
const std::filesystem::path path = std::filesystem::temp_directory_path() /
"et_empty_constant_segment_test.pte";
{
std::ofstream out(path, std::ios::binary);
ASSERT_TRUE(out.good());
out.write(reinterpret_cast<const char*>(data.data()), data.size());
}
// Declared before the loader so that it runs after the loader has closed the
// file: Windows refuses to delete a file that still has an open handle. The
// non-throwing overload keeps a failed cleanup from failing the test.
struct RemoveOnExit {
const std::filesystem::path& path;
~RemoveOnExit() {
std::error_code ec;
std::filesystem::remove(path, ec);
}
} remove_on_exit{path};
Result<FileDataLoader> loader = FileDataLoader::from(path.string().c_str());
ASSERT_EQ(loader.error(), Error::Ok);
Result<Program> program = Program::load(&loader.get(), kDefaultVerification);
ASSERT_EQ(program.error(), Error::Ok);
// The zero-length constant at index 1 resolves, rather than being rejected.
Result<const void*> constant_data =
program->get_constant_buffer_data(/*buffer_idx=*/1, /*nbytes=*/0);
EXPECT_EQ(constant_data.error(), Error::Ok);
}
TEST_F(ProgramTest, SupportedSchemaVersionLoads) {
std::vector<uint8_t> data =
CreateProgramWithVersion(Program::kMaxSupportedSchemaVersion);
alignas(16) uint8_t aligned_buffer[2048];
ASSERT_LE(data.size(), sizeof(aligned_buffer));
memcpy(aligned_buffer, data.data(), data.size());
BufferDataLoader data_loader(aligned_buffer, data.size());
Result<Program> program = Program::load(&data_loader, kDefaultVerification);
EXPECT_EQ(program.error(), Error::Ok);
}
TEST_F(ProgramTest, NewerSchemaVersionFailsToLoad) {
std::vector<uint8_t> data =
CreateProgramWithVersion(Program::kMaxSupportedSchemaVersion + 1);
alignas(16) uint8_t aligned_buffer[2048];
ASSERT_LE(data.size(), sizeof(aligned_buffer));
memcpy(aligned_buffer, data.data(), data.size());
// Use minimal verification to show that even the cheapest level catches it.
BufferDataLoader data_loader(aligned_buffer, data.size());
Result<Program> program =
Program::load(&data_loader, Program::Verification::Minimal);
EXPECT_EQ(program.error(), Error::InvalidProgram);
}
// These tests require ET_ENABLE_PROGRAM_VERIFICATION to be enabled.
// In Release builds, verification is disabled by default to save binary size.
#ifndef ET_ENABLE_PROGRAM_VERIFICATION
#define ET_ENABLE_PROGRAM_VERIFICATION 1
#endif
// ET_ENABLE_DEPRECATED_CONSTANT_BUFFER is 1 by default, and
// set to 0 in the root CMakeLists.txt for OSS builds.
#ifndef ET_ENABLE_DEPRECATED_CONSTANT_BUFFER
#define ET_ENABLE_DEPRECATED_CONSTANT_BUFFER 1
#endif
#if ET_ENABLE_PROGRAM_VERIFICATION
TEST_F(ProgramTest, VerificationCatchesTruncation) {
// Get the program data.
size_t full_data_len = add_loader_->size().get();
Result<FreeableBuffer> full_data = add_loader_->load(
/*offset=*/0,
full_data_len,
/*segment_info=*/
DataLoader::SegmentInfo(DataLoader::SegmentInfo::Type::Program));
ASSERT_EQ(full_data.error(), Error::Ok);
// Make a loader that only exposes half of the data.
BufferDataLoader half_data_loader(full_data->data(), full_data_len / 2);
// Loading with full verification should fail.
Result<Program> program = Program::load(
&half_data_loader, Program::Verification::InternalConsistency);
ASSERT_EQ(program.error(), Error::InvalidProgram);
}
TEST_F(ProgramTest, VerificationCatchesCorruption) {
// Make a local copy of the data.
size_t data_len = add_loader_->size().get();
auto data = std::make_unique<char[]>(data_len);
{
Result<FreeableBuffer> src = add_loader_->load(
/*offset=*/0,
data_len,
/*segment_info=*/
DataLoader::SegmentInfo(DataLoader::SegmentInfo::Type::Program));
ASSERT_EQ(src.error(), Error::Ok);
ASSERT_EQ(src->size(), data_len);
memcpy(data.get(), src->data(), data_len);
// FreeableBuffer goes out of scope and frees its data.
}
// Corrupt the second half of the data.
std::memset(&data[data_len / 2], 0x55, data_len - (data_len / 2));
// Wrap the corrupted data in a loader.
BufferDataLoader data_loader(data.get(), data_len);
// Should fail to parse corrupted data when using full verification.
Result<Program> program =
Program::load(&data_loader, Program::Verification::InternalConsistency);
ASSERT_EQ(program.error(), Error::InvalidProgram);
}
#endif // ET_ENABLE_PROGRAM_VERIFICATION
TEST_F(ProgramTest, MinimalVerificationCatchesInvalidRootOffset) {
// Make a local copy of the data.
size_t data_len = add_loader_->size().get();
auto data = std::make_unique<char[]>(data_len);
{
Result<FreeableBuffer> src = add_loader_->load(
/*offset=*/0,
data_len,
/*segment_info=*/
DataLoader::SegmentInfo(DataLoader::SegmentInfo::Type::Program));
ASSERT_EQ(src.error(), Error::Ok);
ASSERT_EQ(src->size(), data_len);
memcpy(data.get(), src->data(), data_len);
}
// Corrupt the root offset (first 4 bytes) to point beyond the buffer.
// Use WriteScalar for correct little-endian encoding.
flatbuffers::WriteScalar<flatbuffers::uoffset_t>(
data.get(), static_cast<flatbuffers::uoffset_t>(data_len + 1000));
// Wrap the corrupted data in a loader.
BufferDataLoader data_loader(data.get(), data_len);
// Should fail with Minimal verification due to invalid root offset.
Result<Program> program =
Program::load(&data_loader, Program::Verification::Minimal);
ASSERT_EQ(program.error(), Error::InvalidProgram);
}
TEST_F(ProgramTest, UnalignedProgramDataFails) {
// Make a local copy of the data, on an odd alignment.
size_t data_len = add_loader_->size().get();
auto data = std::make_unique<char[]>(data_len + 1);
{
Result<FreeableBuffer> src = add_loader_->load(
/*offset=*/0,
data_len,
/*segment_info=*/
DataLoader::SegmentInfo(DataLoader::SegmentInfo::Type::Program));
ASSERT_EQ(src.error(), Error::Ok);
ASSERT_EQ(src->size(), data_len);
memcpy(data.get() + 1, src->data(), data_len);
// FreeableBuffer goes out of scope and frees its data.
}
// Wrap the offset data in a loader.
BufferDataLoader data_loader(data.get() + 1, data_len);
// Should refuse to accept unaligned data.
Result<Program> program =
Program::load(&data_loader, Program::Verification::Minimal);
ASSERT_NE(program.error(), Error::Ok);
}
TEST_F(ProgramTest, LoadSegmentWithNoSegments) {
// Load a program with no appended segments.
Result<Program> program =
Program::load(add_loader_.get(), kDefaultVerification);
EXPECT_EQ(program.error(), Error::Ok);
// Loading a non-program segment should fail.
const auto segment_info = DataLoader::SegmentInfo(
DataLoader::SegmentInfo::Type::Backend,
/*segment_index=*/0,
"some-backend");
Result<FreeableBuffer> segment =
ProgramTestFriend::LoadSegment(&program.get(), segment_info);
EXPECT_NE(segment.error(), Error::Ok);
}
TEST_F(ProgramTest, LoadSegmentWithNullSegmentsDoesNotCrash) {
// A non-zero segment_base_offset with an absent `segments` table must return
// InvalidProgram rather than dereferencing null.
flatbuffers::FlatBufferBuilder builder(256);
builder.Finish(
executorch_flatbuffer::CreateProgram(builder),
executorch_flatbuffer::ProgramIdentifier());
const auto* internal_program =
executorch_flatbuffer::GetProgram(builder.GetBufferPointer());
uint8_t dummy[16] = {};
BufferDataLoader loader(dummy, sizeof(dummy));
Program program =
ProgramTestFriend::MakeProgram(&loader, 16, internal_program);
Result<FreeableBuffer> result = ProgramTestFriend::LoadSegment(
&program,
DataLoader::SegmentInfo(
DataLoader::SegmentInfo::Type::Backend, /*segment_index=*/0, "b"));
EXPECT_EQ(result.error(), Error::InvalidProgram);
}
TEST_F(ProgramTest, LoadMutableSubsegmentWithNullSegmentsDoesNotCrash) {
// Same malformed state reached through load_mutable_subsegment_into:
// mutable_data_segments is populated so the function passes its own guards,
// but segments is absent.
flatbuffers::FlatBufferBuilder builder(256);
auto subsegment = executorch_flatbuffer::CreateSubsegmentOffsets(
builder,
/*segment_index=*/0,
builder.CreateVector(std::vector<uint64_t>{0}));
builder.Finish(
executorch_flatbuffer::CreateProgram(
builder,
/*version=*/0,
/*execution_plan=*/0,
/*constant_buffer=*/0,
/*backend_delegate_data=*/0,
/*segments=*/0,
/*constant_segment=*/0,
builder.CreateVector(
std::vector<flatbuffers::Offset<
executorch_flatbuffer::SubsegmentOffsets>>{subsegment})),
executorch_flatbuffer::ProgramIdentifier());
const auto* internal_program =
executorch_flatbuffer::GetProgram(builder.GetBufferPointer());
uint8_t dummy[16] = {};
BufferDataLoader loader(dummy, sizeof(dummy));
Program program =
ProgramTestFriend::MakeProgram(&loader, 16, internal_program);
uint8_t out[4] = {};
EXPECT_EQ(
ProgramTestFriend::load_mutable_subsegment_into(
&program,
/*mutable_data_segments_index=*/0,
/*offset_index=*/0,
sizeof(out),
out),
Error::InvalidProgram);
}
TEST_F(ProgramTest, ShortDataHeader) {
Result<FreeableBuffer> header = add_loader_->load(
/*offset=*/0,
Program::kMinHeadBytes,
/*segment_info=*/
DataLoader::SegmentInfo(DataLoader::SegmentInfo::Type::Program));
ASSERT_EQ(header.error(), Error::Ok);
// Provide less than the required amount of data.
EXPECT_EQ(
Program::check_header(header->data(), Program::kMinHeadBytes - 1),
Program::HeaderStatus::ShortData);
}
TEST_F(ProgramTest, LoadShortDataIsInvalidProgram) {
const uint8_t data[8] = {};
BufferDataLoader loader(data, sizeof(data));
EXPECT_EQ(Program::load(&loader).error(), Error::InvalidProgram);
}
namespace {
// Reads the whole program and gives it a header from before segment_data_size
// existed, which a loader of unknown size can still load.
std::vector<uint8_t> read_with_legacy_header(FileDataLoader& loader) {
const size_t size = loader.size().get();
Result<FreeableBuffer> bytes = loader.load(
0, size, DataLoader::SegmentInfo(DataLoader::SegmentInfo::Type::Program));
EXPECT_EQ(bytes.error(), Error::Ok);
const auto* begin = static_cast<const uint8_t*>(bytes->data());
std::vector<uint8_t> data(begin, begin + size);
EXPECT_EQ(std::memcmp(data.data() + 8, "eh00", 4), 0);
const uint64_t no_segment_data_size = 0;
// segment_data_size follows program_size and segment_base_offset.
std::memcpy(data.data() + 32, &no_segment_data_size, sizeof(uint64_t));
return data;
}
class UnknownSizeLoader final : public DataLoader {
public:
UnknownSizeLoader(const void* data, size_t size) : loader_(data, size) {}
Result<FreeableBuffer> load(
size_t offset,
size_t size,
const SegmentInfo& segment_info) const override {
return loader_.load(offset, size, segment_info);
}
Result<size_t> size() const override {
return Error::NotSupported;
}
private:
BufferDataLoader loader_;
};
} // namespace
TEST_F(ProgramTest, LoadLegacyHeaderWithoutDataSize) {
std::vector<uint8_t> data = read_with_legacy_header(*multi_loader_);
UnknownSizeLoader loader(data.data(), data.size());
EXPECT_EQ(Program::load(&loader).error(), Error::Ok);
}
TEST_F(ProgramTest, LoadProgramShorterThanItsHeaderSaysIsInvalidProgram) {
std::vector<uint8_t> data = read_with_legacy_header(*multi_loader_);
// Keep the header, but less than the program size it states.
BufferDataLoader loader(data.data(), Program::kMinHeadBytes + 16);
EXPECT_EQ(Program::load(&loader).error(), Error::InvalidProgram);
}
TEST_F(ProgramTest, IncompatibleHeader) {
// Make a local copy of the header.
size_t data_len = Program::kMinHeadBytes;
auto data = std::make_unique<char[]>(data_len);
{
Result<FreeableBuffer> src = add_loader_->load(
/*offset=*/0,
data_len,
/*segment_info=*/
DataLoader::SegmentInfo(DataLoader::SegmentInfo::Type::Program));
ASSERT_EQ(src.error(), Error::Ok);
ASSERT_EQ(src->size(), data_len);
memcpy(data.get(), src->data(), data_len);
// FreeableBuffer goes out of scope and frees its data.
}
// Change the number part of the magic value to a different value.
EXPECT_EQ(data[4], 'E');
EXPECT_EQ(data[5], 'T');
EXPECT_TRUE(std::isdigit(data[6])) << "Not a digit: " << data[6];
EXPECT_TRUE(std::isdigit(data[7])) << "Not a digit: " << data[7];
// Modify the tens digit.
if (data[6] == '9') {
data[6] = '0';
} else {
data[6] += 1;
}
EXPECT_TRUE(std::isdigit(data[6])) << "Not a digit: " << data[6];
// Should count as present but incompatible.
EXPECT_EQ(
Program::check_header(data.get(), data_len),
Program::HeaderStatus::IncompatibleVersion);
}
TEST_F(ProgramTest, HeaderNotPresent) {
// Make a local copy of the header.
size_t data_len = Program::kMinHeadBytes;
auto data = std::make_unique<char[]>(data_len);
{
Result<FreeableBuffer> src = add_loader_->load(
/*offset=*/0,
data_len,
/*segment_info=*/
DataLoader::SegmentInfo(DataLoader::SegmentInfo::Type::Program));
ASSERT_EQ(src.error(), Error::Ok);
ASSERT_EQ(src->size(), data_len);
memcpy(data.get(), src->data(), data_len);
// FreeableBuffer goes out of scope and frees its data.
}
// Corrupt the magic value.
EXPECT_EQ(data[4], 'E');
data[4] = 'X';
EXPECT_EQ(data[5], 'T');
data[5] = 'Y';
// The header is not present.
EXPECT_EQ(
Program::check_header(data.get(), data_len),
Program::HeaderStatus::NotPresent);
}
TEST_F(ProgramTest, getMethods) {
// Parse the Program from the data.
Result<Program> program_res =
Program::load(multi_loader_.get(), kDefaultVerification);
EXPECT_EQ(program_res.error(), Error::Ok);
Program program(std::move(program_res.get()));
// Method calls should succeed without hitting ET_CHECK.
EXPECT_EQ(program.num_methods(), 2);
auto res = program.get_method_name(0);
EXPECT_TRUE(res.ok());
EXPECT_EQ(strcmp(res.get(), "forward"), 0);
auto res2 = program.get_method_name(1);
EXPECT_TRUE(res2.ok());
EXPECT_EQ(strcmp(res2.get(), "forward2"), 0);
}
TEST_F(ProgramTest, GetNamedDataMap_Fail) {
Result<Program> program =
Program::load(add_loader_.get(), kDefaultVerification);
ASSERT_EQ(program.error(), Error::Ok);
// Get the named data map. Expect to fail, as add.pte does not have any
// named data segments.
Result<const executorch::runtime::NamedDataMap*> named_data_map =
program->get_named_data_map();
EXPECT_EQ(named_data_map.error(), Error::NotFound);
}
// Test that the deprecated Load method (capital 'L') still works.
TEST_F(ProgramTest, DEPRECATEDLoad) {
// Parse the Program from the data.
// NOLINTNEXTLINE(facebook-hte-Deprecated)
Result<Program> program_res = Program::Load(multi_loader_.get());
EXPECT_EQ(program_res.error(), Error::Ok);
}
TEST_F(ProgramTest, LoadConstantSegmentWithNoConstantSegment) {
Result<Program> program =
Program::load(add_loader_.get(), kDefaultVerification);
ASSERT_EQ(program.error(), Error::Ok);
// Load constant segment data should fail.
const auto segment_info = DataLoader::SegmentInfo(
DataLoader::SegmentInfo::Type::Constant,
/*segment_index=*/0);
Result<FreeableBuffer> segment =
ProgramTestFriend::LoadSegment(&program.get(), segment_info);
EXPECT_NE(segment.error(), Error::Ok);
const executorch_flatbuffer::Program* flatbuffer_program =
ProgramTestFriend::GetInternalProgram(&program.get());
// The constant buffer should be empty.
EXPECT_EQ(flatbuffer_program->constant_buffer()->size(), 0);
// Expect 1 constant segment, placeholder for non-const tensors.
EXPECT_EQ(flatbuffer_program->segments()->size(), 1);
}
TEST_F(ProgramTest, LoadConstantSegment) {
// Load the serialized ModuleAddMul data, with constants in the segment.
const char* linear_path = std::getenv("ET_MODULE_ADD_MUL_PATH");
Result<FileDataLoader> linear_loader = FileDataLoader::from(linear_path);
ASSERT_EQ(linear_loader.error(), Error::Ok);
// This file should always be compatible.
Result<FreeableBuffer> linear_header = linear_loader->load(
/*offset=*/0,
Program::kMinHeadBytes,
/*segment_info=*/
DataLoader::SegmentInfo(DataLoader::SegmentInfo::Type::Program));
ASSERT_EQ(linear_header.error(), Error::Ok);
EXPECT_EQ(
Program::check_header(linear_header->data(), linear_header->size()),
Program::HeaderStatus::CompatibleVersion);
Result<Program> program = Program::load(&linear_loader.get());
ASSERT_EQ(program.error(), Error::Ok);
// Load constant segment data, which is currently always in segment index
// zero.
const auto segment_info = DataLoader::SegmentInfo(
DataLoader::SegmentInfo::Type::Constant,
/*segment_index=*/0);
Result<FreeableBuffer> segment =
ProgramTestFriend::LoadSegment(&program.get(), segment_info);
EXPECT_EQ(segment.error(), Error::Ok);
const executorch_flatbuffer::Program* flatbuffer_program =
ProgramTestFriend::GetInternalProgram(&program.get());
// Expect one segment containing the constants.
EXPECT_EQ(flatbuffer_program->segments()->size(), 1);
// The constant buffer should be empty.
EXPECT_EQ(flatbuffer_program->constant_buffer()->size(), 0);
// Check constant segment offsets.
EXPECT_EQ(flatbuffer_program->constant_segment()->segment_index(), 0);
EXPECT_GE(flatbuffer_program->constant_segment()->offsets()->size(), 1);
}
TEST_F(ProgramTest, LoadConstantSegmentWhenConstantBufferExists) {
// Load the serialized ModuleAddMul data, with constants in the flatbuffer and
// no constants in the segment.
const char* linear_path =
std::getenv("DEPRECATED_ET_MODULE_LINEAR_CONSTANT_BUFFER_PATH");
Result<FileDataLoader> linear_loader = FileDataLoader::from(linear_path);
ASSERT_EQ(linear_loader.error(), Error::Ok);
// This file should always be compatible.
Result<FreeableBuffer> linear_header = linear_loader->load(
/*offset=*/0,
Program::kMinHeadBytes,
/*segment_info=*/
DataLoader::SegmentInfo(DataLoader::SegmentInfo::Type::Program));
ASSERT_EQ(linear_header.error(), Error::Ok);
EXPECT_EQ(
Program::check_header(linear_header->data(), linear_header->size()),
Program::HeaderStatus::CompatibleVersion);
Result<Program> program = Program::load(&linear_loader.get());
#if ET_ENABLE_DEPRECATED_CONSTANT_BUFFER
ASSERT_EQ(program.error(), Error::Ok);
const executorch_flatbuffer::Program* flatbuffer_program =
ProgramTestFriend::GetInternalProgram(&program.get());
// Expect no segments.
EXPECT_EQ(flatbuffer_program->segments()->size(), 0);
// The constant buffer should exist.
EXPECT_GE(flatbuffer_program->constant_buffer()->size(), 1);
#else
// The deprecated in-flatbuffer constant_buffer path is disabled; loading a
// PTE that relies on it must be rejected.
EXPECT_EQ(program.error(), Error::InvalidProgram);
#endif
}
TEST_F(ProgramTest, LoadFromMutableSegment) {
// Load the serialized ModuleSimpleTrain data.
auto path = std::getenv("ET_MODULE_SIMPLE_TRAIN_PATH");
Result<FileDataLoader> training_loader = FileDataLoader::from(path);
ASSERT_EQ(training_loader.error(), Error::Ok);
// This file should always be compatible.
Result<FreeableBuffer> training_header = training_loader->load(
/*offset=*/0,
Program::kMinHeadBytes,
DataLoader::SegmentInfo(DataLoader::SegmentInfo::Type::Program));
ASSERT_EQ(training_header.error(), Error::Ok);
EXPECT_EQ(
Program::check_header(training_header->data(), training_header->size()),
Program::HeaderStatus::CompatibleVersion);
Result<Program> program = Program::load(&training_loader.get());
ASSERT_EQ(program.error(), Error::Ok);
// The linear layer weight tensor is 3x3 floats = 36 bytes.
// Load the full weight data to verify the loading mechanism works correctly.
constexpr size_t kWeightSize = 36;
uint8_t buffer[kWeightSize] = {0};
uint8_t buffer2[kWeightSize] = {0};
// Load the mutable segment data (linear.weight at offset_index 1)
Error err = ProgramTestFriend::load_mutable_subsegment_into(
&program.get(), 0, 1, kWeightSize, buffer);
EXPECT_EQ(err, Error::Ok);
// Load the same data into a second buffer
err = ProgramTestFriend::load_mutable_subsegment_into(
&program.get(), 0, 1, kWeightSize, buffer2);
EXPECT_EQ(err, Error::Ok);
// Verify both loads return identical data
EXPECT_EQ(std::memcmp(buffer, buffer2, kWeightSize), 0)
<< "Loading the same segment twice should return identical data";
// Loading into a new buffer, as for device memory, returns the same data.
Result<FreeableBuffer> loaded = ProgramTestFriend::load_mutable_subsegment(
&program.get(), 0, 1, kWeightSize);
ASSERT_EQ(loaded.error(), Error::Ok);
ASSERT_EQ(loaded->size(), kWeightSize);
EXPECT_EQ(std::memcmp(loaded->data(), buffer, kWeightSize), 0);
// Verify that the loaded data is non-trivial (not all zeros).
bool has_nonzero = false;
for (size_t i = 0; i < kWeightSize; ++i) {
if (buffer[i] != 0) {
has_nonzero = true;
break;
}
}
EXPECT_TRUE(has_nonzero)
<< "Loaded mutable segment data should not be all zeros";
// Mutate the local buffer and reload to verify source immutability
std::memset(buffer, 0xFF, kWeightSize);
err = ProgramTestFriend::load_mutable_subsegment_into(
&program.get(), 0, 1, kWeightSize, buffer);
EXPECT_EQ(err, Error::Ok);
// Verify the reloaded data matches the original (local mutation didn't
// affect the file source)
EXPECT_EQ(std::memcmp(buffer, buffer2, kWeightSize), 0)
<< "Reloading after local mutation should return original data";
const executorch_flatbuffer::Program* flatbuffer_program =
ProgramTestFriend::GetInternalProgram(&program.get());
// Expect 2 segments. 1 mutable segment and 1 constant segment.
EXPECT_EQ(flatbuffer_program->segments()->size(), 2);
// Expect a mutable data segment.
EXPECT_EQ(flatbuffer_program->mutable_data_segments()->size(), 1);
// Expect the 0 index to be reserved and the offsets for weight and bias of
// linear to be indices 1 and 2.
EXPECT_EQ(
flatbuffer_program->mutable_data_segments()->Get(0)->offsets()->size(),
3);
EXPECT_EQ(
flatbuffer_program->mutable_data_segments()->Get(0)->offsets()->Get(0),
0);
EXPECT_EQ(
flatbuffer_program->mutable_data_segments()->Get(0)->offsets()->Get(1),
0);
EXPECT_EQ(
flatbuffer_program->mutable_data_segments()->Get(0)->offsets()->Get(2),
36);
// Loading beyond file should fail
err = ProgramTestFriend::load_mutable_subsegment_into(
&program.get(), 0, 1, 500, buffer);
EXPECT_NE(err, Error::Ok);
// Loading beyond offsets should fail
err = ProgramTestFriend::load_mutable_subsegment_into(
&program.get(), 0, 500, 1, buffer);
EXPECT_NE(err, Error::Ok);
// Loading beyond segments should fail
err = ProgramTestFriend::load_mutable_subsegment_into(
&program.get(), 500, 1, 1, buffer);
EXPECT_NE(err, Error::Ok);
// The new buffer variant checks the same bounds.
EXPECT_NE(
ProgramTestFriend::load_mutable_subsegment(&program.get(), 0, 1, 500)
.error(),
Error::Ok);
EXPECT_NE(