-
Notifications
You must be signed in to change notification settings - Fork 6.1k
/
Copy pathAssembly.cpp
1858 lines (1662 loc) · 63.8 KB
/
Assembly.cpp
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
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/** @file Assembly.cpp
* @author Gav Wood <[email protected]>
* @date 2014
*/
#include <libevmasm/Assembly.h>
#include <libevmasm/CommonSubexpressionEliminator.h>
#include <libevmasm/ControlFlowGraph.h>
#include <libevmasm/PeepholeOptimiser.h>
#include <libevmasm/Inliner.h>
#include <libevmasm/JumpdestRemover.h>
#include <libevmasm/BlockDeduplicator.h>
#include <libevmasm/ConstantOptimiser.h>
#include <liblangutil/CharStream.h>
#include <liblangutil/Exceptions.h>
#include <libsolutil/JSON.h>
#include <libsolutil/StringUtils.h>
#include <fmt/format.h>
#include <range/v3/algorithm/any_of.hpp>
#include <range/v3/view/drop_exactly.hpp>
#include <range/v3/view/enumerate.hpp>
#include <range/v3/view/map.hpp>
#include <limits>
#include <iterator>
#include <ostream>
#include <stack>
using namespace solidity;
using namespace solidity::evmasm;
using namespace solidity::langutil;
using namespace solidity::util;
std::map<std::string, std::shared_ptr<std::string const>> Assembly::s_sharedSourceNames;
AssemblyItem const& Assembly::append(AssemblyItem _i)
{
assertThrow(m_deposit >= 0, AssemblyException, "Stack underflow.");
m_deposit += static_cast<int>(_i.deposit());
solAssert(m_currentCodeSection < m_codeSections.size());
auto& currentItems = m_codeSections.at(m_currentCodeSection).items;
currentItems.emplace_back(std::move(_i));
if (!currentItems.back().location().isValid() && m_currentSourceLocation.isValid())
currentItems.back().setLocation(m_currentSourceLocation);
currentItems.back().m_modifierDepth = m_currentModifierDepth;
return currentItems.back();
}
unsigned Assembly::codeSize(unsigned subTagSize) const
{
for (unsigned tagSize = subTagSize; true; ++tagSize)
{
size_t ret = 1;
for (auto const& i: m_data)
ret += i.second.size();
for (auto const& codeSection: m_codeSections)
for (AssemblyItem const& i: codeSection.items)
ret += i.bytesRequired(tagSize, m_evmVersion, Precision::Precise);
if (numberEncodingSize(ret) <= tagSize)
return static_cast<unsigned>(ret);
}
}
void Assembly::importAssemblyItemsFromJSON(Json const& _code, std::vector<std::string> const& _sourceList)
{
// Assembly constructor creates first code section with proper type and empty `items`
solAssert(m_codeSections.size() == 1);
solAssert(m_codeSections[0].items.empty());
// TODO: Add support for EOF and more than one code sections.
solUnimplementedAssert(!m_eofVersion.has_value(), "Assembly import for EOF is not yet implemented.");
solRequire(_code.is_array(), AssemblyImportException, "Supplied JSON is not an array.");
for (auto jsonItemIter = std::begin(_code); jsonItemIter != std::end(_code); ++jsonItemIter)
{
AssemblyItem const& newItem = m_codeSections[0].items.emplace_back(createAssemblyItemFromJSON(*jsonItemIter, _sourceList));
if (newItem == Instruction::JUMPDEST)
solThrow(AssemblyImportException, "JUMPDEST instruction without a tag");
else if (newItem.type() == AssemblyItemType::Tag)
{
++jsonItemIter;
if (jsonItemIter != std::end(_code) && createAssemblyItemFromJSON(*jsonItemIter, _sourceList) != Instruction::JUMPDEST)
solThrow(AssemblyImportException, "JUMPDEST expected after tag.");
}
}
}
AssemblyItem Assembly::createAssemblyItemFromJSON(Json const& _json, std::vector<std::string> const& _sourceList)
{
solRequire(_json.is_object(), AssemblyImportException, "Supplied JSON is not an object.");
static std::set<std::string> const validMembers{"name", "begin", "end", "source", "value", "modifierDepth", "jumpType"};
for (auto const& [member, _]: _json.items())
solRequire(
validMembers.count(member),
AssemblyImportException,
fmt::format(
"Unknown member '{}'. Valid members are: {}.",
member,
solidity::util::joinHumanReadable(validMembers, ", ")
)
);
solRequire(isOfType<std::string>(_json["name"]), AssemblyImportException, "Member 'name' missing or not of type string.");
solRequire(isOfTypeIfExists<int>(_json, "begin"), AssemblyImportException, "Optional member 'begin' not of type int.");
solRequire(isOfTypeIfExists<int>(_json, "end"), AssemblyImportException, "Optional member 'end' not of type int.");
solRequire(isOfTypeIfExists<int>(_json, "source"), AssemblyImportException, "Optional member 'source' not of type int.");
solRequire(isOfTypeIfExists<std::string>(_json, "value"), AssemblyImportException, "Optional member 'value' not of type string.");
solRequire(isOfTypeIfExists<int>(_json, "modifierDepth"), AssemblyImportException, "Optional member 'modifierDepth' not of type int.");
solRequire(isOfTypeIfExists<std::string>(_json, "jumpType"), AssemblyImportException, "Optional member 'jumpType' not of type string.");
std::string name = get<std::string>(_json["name"]);
solRequire(!name.empty(), AssemblyImportException, "Member 'name' is empty.");
SourceLocation location;
if (_json.contains("begin"))
location.start = get<int>(_json["begin"]);
if (_json.contains("end"))
location.end = get<int>(_json["end"]);
int srcIndex = getOrDefault<int>(_json, "source", -1);
size_t modifierDepth = static_cast<size_t>(getOrDefault<int>(_json, "modifierDepth", 0));
std::string value = getOrDefault<std::string>(_json, "value", "");
std::string jumpType = getOrDefault<std::string>(_json, "jumpType", "");
auto updateUsedTags = [&](u256 const& data)
{
m_usedTags = std::max(m_usedTags, static_cast<unsigned>(data) + 1);
return data;
};
auto storeImmutableHash = [&](std::string const& _immutableName) -> h256
{
h256 hash(util::keccak256(_immutableName));
solAssert(m_immutables.count(hash) == 0 || m_immutables[hash] == _immutableName);
m_immutables[hash] = _immutableName;
return hash;
};
auto storeLibraryHash = [&](std::string const& _libraryName) -> h256
{
h256 hash(util::keccak256(_libraryName));
solAssert(m_libraries.count(hash) == 0 || m_libraries[hash] == _libraryName);
m_libraries[hash] = _libraryName;
return hash;
};
auto requireValueDefinedForInstruction = [&](std::string const& _name, std::string const& _value)
{
solRequire(
!_value.empty(),
AssemblyImportException,
"Member 'value' is missing for instruction '" + _name + "', but the instruction needs a value."
);
};
auto requireValueUndefinedForInstruction = [&](std::string const& _name, std::string const& _value)
{
solRequire(
_value.empty(),
AssemblyImportException,
"Member 'value' defined for instruction '" + _name + "', but the instruction does not need a value."
);
};
solRequire(srcIndex >= -1 && srcIndex < static_cast<int>(_sourceList.size()), AssemblyImportException, "Source index out of bounds.");
if (srcIndex != -1)
location.sourceName = sharedSourceName(_sourceList[static_cast<size_t>(srcIndex)]);
AssemblyItem result(0);
if (c_instructions.count(name))
{
AssemblyItem item{c_instructions.at(name), langutil::DebugData::create(location)};
if (!jumpType.empty())
{
if (item.instruction() == Instruction::JUMP || item.instruction() == Instruction::JUMPI)
{
std::optional<AssemblyItem::JumpType> parsedJumpType = AssemblyItem::parseJumpType(jumpType);
if (!parsedJumpType.has_value())
solThrow(AssemblyImportException, "Invalid jump type.");
item.setJumpType(parsedJumpType.value());
}
else
solThrow(
AssemblyImportException,
"Member 'jumpType' set on instruction different from JUMP or JUMPI (was set on instruction '" + name + "')"
);
}
requireValueUndefinedForInstruction(name, value);
result = item;
}
else
{
solRequire(
jumpType.empty(),
AssemblyImportException,
"Member 'jumpType' set on instruction different from JUMP or JUMPI (was set on instruction '" + name + "')"
);
if (name == "PUSH")
{
requireValueDefinedForInstruction(name, value);
result = {AssemblyItemType::Push, u256("0x" + value)};
}
else if (name == "PUSH [ErrorTag]")
{
requireValueUndefinedForInstruction(name, value);
result = {AssemblyItemType::PushTag, 0};
}
else if (name == "PUSH [tag]")
{
requireValueDefinedForInstruction(name, value);
result = {AssemblyItemType::PushTag, updateUsedTags(u256(value))};
}
else if (name == "PUSH [$]")
{
requireValueDefinedForInstruction(name, value);
result = {AssemblyItemType::PushSub, u256("0x" + value)};
}
else if (name == "PUSH #[$]")
{
requireValueDefinedForInstruction(name, value);
result = {AssemblyItemType::PushSubSize, u256("0x" + value)};
}
else if (name == "PUSHSIZE")
{
requireValueUndefinedForInstruction(name, value);
result = {AssemblyItemType::PushProgramSize, 0};
}
else if (name == "PUSHLIB")
{
requireValueDefinedForInstruction(name, value);
result = {AssemblyItemType::PushLibraryAddress, storeLibraryHash(value)};
}
else if (name == "PUSHDEPLOYADDRESS")
{
requireValueUndefinedForInstruction(name, value);
result = {AssemblyItemType::PushDeployTimeAddress, 0};
}
else if (name == "PUSHIMMUTABLE")
{
requireValueDefinedForInstruction(name, value);
result = {AssemblyItemType::PushImmutable, storeImmutableHash(value)};
}
else if (name == "ASSIGNIMMUTABLE")
{
requireValueDefinedForInstruction(name, value);
result = {AssemblyItemType::AssignImmutable, storeImmutableHash(value)};
}
else if (name == "tag")
{
requireValueDefinedForInstruction(name, value);
result = {AssemblyItemType::Tag, updateUsedTags(u256(value))};
}
else if (name == "PUSH data")
{
requireValueDefinedForInstruction(name, value);
result = {AssemblyItemType::PushData, u256("0x" + value)};
}
else if (name == "VERBATIM")
{
requireValueDefinedForInstruction(name, value);
AssemblyItem item(fromHex(value), 0, 0);
result = item;
}
else
solThrow(AssemblyImportException, "Invalid opcode (" + name + ")");
}
result.setLocation(location);
result.m_modifierDepth = modifierDepth;
return result;
}
namespace
{
std::string locationFromSources(StringMap const& _sourceCodes, SourceLocation const& _location)
{
if (!_location.hasText() || _sourceCodes.empty())
return {};
auto it = _sourceCodes.find(*_location.sourceName);
if (it == _sourceCodes.end())
return {};
return CharStream::singleLineSnippet(it->second, _location);
}
class Functionalizer
{
public:
Functionalizer (std::ostream& _out, std::string const& _prefix, StringMap const& _sourceCodes, Assembly const& _assembly):
m_out(_out), m_prefix(_prefix), m_sourceCodes(_sourceCodes), m_assembly(_assembly)
{}
void feed(AssemblyItem const& _item, DebugInfoSelection const& _debugInfoSelection)
{
if (_item.location().isValid() && _item.location() != m_location)
{
flush();
m_location = _item.location();
printLocation(_debugInfoSelection);
}
std::string expression = _item.toAssemblyText(m_assembly);
if (!(
_item.canBeFunctional() &&
_item.returnValues() <= 1 &&
_item.arguments() <= m_pending.size()
))
{
flush();
m_out << m_prefix << (_item.type() == Tag ? "" : " ") << expression << std::endl;
return;
}
if (_item.arguments() > 0)
{
expression += "(";
for (size_t i = 0; i < _item.arguments(); ++i)
{
expression += m_pending.back();
m_pending.pop_back();
if (i + 1 < _item.arguments())
expression += ", ";
}
expression += ")";
}
m_pending.push_back(expression);
if (_item.returnValues() != 1)
flush();
}
void flush()
{
for (std::string const& expression: m_pending)
m_out << m_prefix << " " << expression << std::endl;
m_pending.clear();
}
void printLocation(DebugInfoSelection const& _debugInfoSelection)
{
if (!m_location.isValid() || (!_debugInfoSelection.location && !_debugInfoSelection.snippet))
return;
m_out << m_prefix << " /*";
if (_debugInfoSelection.location)
{
if (m_location.sourceName)
m_out << " " + escapeAndQuoteString(*m_location.sourceName);
if (m_location.hasText())
m_out << ":" << std::to_string(m_location.start) + ":" + std::to_string(m_location.end);
}
if (_debugInfoSelection.snippet)
{
if (_debugInfoSelection.location)
m_out << " ";
m_out << locationFromSources(m_sourceCodes, m_location);
}
m_out << " */" << std::endl;
}
private:
strings m_pending;
SourceLocation m_location;
std::ostream& m_out;
std::string const& m_prefix;
StringMap const& m_sourceCodes;
Assembly const& m_assembly;
};
}
void Assembly::assemblyStream(
std::ostream& _out,
DebugInfoSelection const& _debugInfoSelection,
std::string const& _prefix,
StringMap const& _sourceCodes
) const
{
Functionalizer f(_out, _prefix, _sourceCodes, *this);
for (auto const& i: m_codeSections.front().items)
f.feed(i, _debugInfoSelection);
f.flush();
for (size_t i = 1; i < m_codeSections.size(); ++i)
{
_out << std::endl << _prefix << "code_section_" << i << ": assembly {\n";
Functionalizer codeSectionF(_out, _prefix + " ", _sourceCodes, *this);
for (auto const& item: m_codeSections[i].items)
codeSectionF.feed(item, _debugInfoSelection);
codeSectionF.flush();
_out << _prefix << "}" << std::endl;
}
if (!m_data.empty() || !m_subs.empty())
{
_out << _prefix << "stop" << std::endl;
for (auto const& i: m_data)
if (u256(i.first) >= m_subs.size())
_out << _prefix << "data_" << toHex(u256(i.first)) << " " << util::toHex(i.second) << std::endl;
for (size_t i = 0; i < m_subs.size(); ++i)
{
_out << std::endl << _prefix << "sub_" << i << ": assembly {\n";
m_subs[i]->assemblyStream(_out, _debugInfoSelection, _prefix + " ", _sourceCodes);
_out << _prefix << "}" << std::endl;
}
}
if (m_auxiliaryData.size() > 0)
_out << std::endl << _prefix << "auxdata: 0x" << util::toHex(m_auxiliaryData) << std::endl;
}
std::string Assembly::assemblyString(
DebugInfoSelection const& _debugInfoSelection,
StringMap const& _sourceCodes
) const
{
std::ostringstream tmp;
assemblyStream(tmp, _debugInfoSelection, "", _sourceCodes);
return (_debugInfoSelection.ethdebug ? "/// ethdebug: enabled\n" : "") + tmp.str();
}
Json Assembly::assemblyJSON(std::map<std::string, unsigned> const& _sourceIndices, bool _includeSourceList) const
{
Json root;
root[".code"] = Json::array();
Json& code = root[".code"];
// TODO: support EOF
solUnimplementedAssert(!m_eofVersion.has_value(), "Assembly output for EOF is not yet implemented.");
solAssert(m_codeSections.size() == 1);
for (AssemblyItem const& item: m_codeSections.front().items)
{
int sourceIndex = -1;
if (item.location().sourceName)
{
auto iter = _sourceIndices.find(*item.location().sourceName);
if (iter != _sourceIndices.end())
sourceIndex = static_cast<int>(iter->second);
}
auto [name, data] = item.nameAndData(m_evmVersion);
Json jsonItem;
jsonItem["name"] = name;
jsonItem["begin"] = item.location().start;
jsonItem["end"] = item.location().end;
if (item.m_modifierDepth != 0)
jsonItem["modifierDepth"] = static_cast<int>(item.m_modifierDepth);
std::string jumpType = item.getJumpTypeAsString();
if (!jumpType.empty())
jsonItem["jumpType"] = jumpType;
if (name == "PUSHLIB")
data = m_libraries.at(h256(data));
else if (name == "PUSHIMMUTABLE" || name == "ASSIGNIMMUTABLE")
data = m_immutables.at(h256(data));
if (!data.empty())
jsonItem["value"] = data;
jsonItem["source"] = sourceIndex;
code.emplace_back(std::move(jsonItem));
if (item.type() == AssemblyItemType::Tag)
{
Json jumpdest;
jumpdest["name"] = "JUMPDEST";
jumpdest["begin"] = item.location().start;
jumpdest["end"] = item.location().end;
jumpdest["source"] = sourceIndex;
if (item.m_modifierDepth != 0)
jumpdest["modifierDepth"] = static_cast<int>(item.m_modifierDepth);
code.emplace_back(std::move(jumpdest));
}
}
if (_includeSourceList)
{
root["sourceList"] = Json::array();
Json& jsonSourceList = root["sourceList"];
unsigned maxSourceIndex = 0;
for (auto const& [sourceName, sourceIndex]: _sourceIndices)
{
maxSourceIndex = std::max(sourceIndex, maxSourceIndex);
jsonSourceList[sourceIndex] = sourceName;
}
solAssert(maxSourceIndex + 1 >= _sourceIndices.size());
solRequire(
_sourceIndices.size() == 0 || _sourceIndices.size() == maxSourceIndex + 1,
AssemblyImportException,
"The 'sourceList' array contains invalid 'null' item."
);
}
if (!m_data.empty() || !m_subs.empty())
{
root[".data"] = Json::object();
Json& data = root[".data"];
for (auto const& i: m_data)
if (u256(i.first) >= m_subs.size())
data[util::toHex(toBigEndian((u256)i.first), util::HexPrefix::DontAdd, util::HexCase::Upper)] = util::toHex(i.second);
for (size_t i = 0; i < m_subs.size(); ++i)
{
std::stringstream hexStr;
hexStr << std::hex << i;
data[hexStr.str()] = m_subs[i]->assemblyJSON(_sourceIndices, /*_includeSourceList = */false);
}
}
if (!m_auxiliaryData.empty())
root[".auxdata"] = util::toHex(m_auxiliaryData);
return root;
}
std::pair<std::shared_ptr<Assembly>, std::vector<std::string>> Assembly::fromJSON(
Json const& _json,
std::vector<std::string> const& _sourceList,
size_t _level,
std::optional<uint8_t> _eofVersion
)
{
solRequire(_json.is_object(), AssemblyImportException, "Supplied JSON is not an object.");
static std::set<std::string> const validMembers{".code", ".data", ".auxdata", "sourceList"};
for (auto const& [attribute, _]: _json.items())
solRequire(validMembers.count(attribute), AssemblyImportException, "Unknown attribute '" + attribute + "'.");
if (_level == 0)
{
if (_json.contains("sourceList"))
{
solRequire(_json["sourceList"].is_array(), AssemblyImportException, "Optional member 'sourceList' is not an array.");
for (Json const& sourceName: _json["sourceList"])
{
solRequire(!sourceName.is_null(), AssemblyImportException, "The 'sourceList' array contains invalid 'null' item.");
solRequire(
sourceName.is_string(),
AssemblyImportException,
"The 'sourceList' array contains an item that is not a string."
);
}
}
}
else
solRequire(
!_json.contains("sourceList"),
AssemblyImportException,
"Member 'sourceList' may only be present in the root JSON object."
);
auto result = std::make_shared<Assembly>(EVMVersion{}, _level == 0 /* _creation */, _eofVersion, "" /* _name */);
std::vector<std::string> parsedSourceList;
if (_json.contains("sourceList"))
{
solAssert(_level == 0);
solAssert(_sourceList.empty());
for (Json const& sourceName: _json["sourceList"])
{
solRequire(
std::find(parsedSourceList.begin(), parsedSourceList.end(), sourceName.get<std::string>()) == parsedSourceList.end(),
AssemblyImportException,
"Items in 'sourceList' array are not unique."
);
parsedSourceList.emplace_back(sourceName.get<std::string>());
}
}
solRequire(_json.contains(".code"), AssemblyImportException, "Member '.code' is missing.");
solRequire(_json[".code"].is_array(), AssemblyImportException, "Member '.code' is not an array.");
for (Json const& codeItem: _json[".code"])
solRequire(codeItem.is_object(), AssemblyImportException, "The '.code' array contains an item that is not an object.");
result->importAssemblyItemsFromJSON(_json[".code"], _level == 0 ? parsedSourceList : _sourceList);
if (_json.contains(".auxdata"))
{
solRequire(_json[".auxdata"].is_string(), AssemblyImportException, "Optional member '.auxdata' is not a string.");
result->m_auxiliaryData = fromHex(_json[".auxdata"].get<std::string>());
solRequire(!result->m_auxiliaryData.empty(), AssemblyImportException, "Optional member '.auxdata' is not a valid hexadecimal string.");
}
if (_json.contains(".data"))
{
solRequire(_json[".data"].is_object(), AssemblyImportException, "Optional member '.data' is not an object.");
Json const& data = _json[".data"];
std::map<size_t, std::shared_ptr<Assembly>> subAssemblies;
for (auto const& [key, value] : data.items())
{
if (value.is_string())
{
solRequire(
value.get<std::string>().empty() || !fromHex(value.get<std::string>()).empty(),
AssemblyImportException,
"The value for key '" + key + "' inside '.data' is not a valid hexadecimal string."
);
result->m_data[h256(fromHex(key))] = fromHex(value.get<std::string>());
}
else if (value.is_object())
{
size_t index{};
try
{
// Using signed variant because stoul() still accepts negative numbers and
// just lets them wrap around.
int parsedDataItemID = std::stoi(key, nullptr, 16);
solRequire(parsedDataItemID >= 0, AssemblyImportException, "The key '" + key + "' inside '.data' is out of the supported integer range.");
index = static_cast<size_t>(parsedDataItemID);
}
catch (std::invalid_argument const&)
{
solThrow(AssemblyImportException, "The key '" + key + "' inside '.data' is not an integer.");
}
catch (std::out_of_range const&)
{
solThrow(AssemblyImportException, "The key '" + key + "' inside '.data' is out of the supported integer range.");
}
auto [subAssembly, emptySourceList] = Assembly::fromJSON(value, _level == 0 ? parsedSourceList : _sourceList, _level + 1, _eofVersion);
solAssert(subAssembly);
solAssert(emptySourceList.empty());
solAssert(subAssemblies.count(index) == 0);
subAssemblies[index] = subAssembly;
}
else
solThrow(AssemblyImportException, "The value of key '" + key + "' inside '.data' is neither a hex string nor an object.");
}
if (!subAssemblies.empty())
solRequire(
ranges::max(subAssemblies | ranges::views::keys) == subAssemblies.size() - 1,
AssemblyImportException,
fmt::format(
"Invalid subassembly indices in '.data'. Not all numbers between 0 and {} are present.",
subAssemblies.size() - 1
)
);
result->m_subs = subAssemblies | ranges::views::values | ranges::to<std::vector>;
}
if (_level == 0)
result->encodeAllPossibleSubPathsInAssemblyTree();
return std::make_pair(result, _level == 0 ? parsedSourceList : std::vector<std::string>{});
}
void Assembly::encodeAllPossibleSubPathsInAssemblyTree(std::vector<size_t> _pathFromRoot, std::vector<Assembly*> _assembliesOnPath)
{
_assembliesOnPath.push_back(this);
for (_pathFromRoot.push_back(0); _pathFromRoot.back() < m_subs.size(); ++_pathFromRoot.back())
{
for (size_t distanceFromRoot = 0; distanceFromRoot < _assembliesOnPath.size(); ++distanceFromRoot)
_assembliesOnPath[distanceFromRoot]->encodeSubPath(
_pathFromRoot | ranges::views::drop_exactly(distanceFromRoot) | ranges::to<std::vector>
);
m_subs[_pathFromRoot.back()]->encodeAllPossibleSubPathsInAssemblyTree(_pathFromRoot, _assembliesOnPath);
}
}
std::shared_ptr<std::string const> Assembly::sharedSourceName(std::string const& _name) const
{
if (s_sharedSourceNames.find(_name) == s_sharedSourceNames.end())
s_sharedSourceNames[_name] = std::make_shared<std::string>(_name);
return s_sharedSourceNames[_name];
}
AssemblyItem Assembly::namedTag(std::string const& _name, size_t _params, size_t _returns, std::optional<uint64_t> _sourceID)
{
assertThrow(!_name.empty(), AssemblyException, "Empty named tag.");
if (m_namedTags.count(_name))
{
assertThrow(m_namedTags.at(_name).params == _params, AssemblyException, "");
assertThrow(m_namedTags.at(_name).returns == _returns, AssemblyException, "");
assertThrow(m_namedTags.at(_name).sourceID == _sourceID, AssemblyException, "");
}
else
m_namedTags[_name] = {static_cast<size_t>(newTag().data()), _sourceID, _params, _returns};
return AssemblyItem{Tag, m_namedTags.at(_name).id};
}
AssemblyItem Assembly::newFunctionCall(uint16_t _functionID) const
{
solAssert(_functionID < m_codeSections.size(), "Call to undeclared function.");
solAssert(_functionID > 0, "Cannot call section 0");
auto const& section = m_codeSections.at(_functionID);
if (section.nonReturning)
return AssemblyItem::jumpToFunction(_functionID, section.inputs, section.outputs);
else
return AssemblyItem::functionCall(_functionID, section.inputs, section.outputs);
}
AssemblyItem Assembly::newFunctionReturn() const
{
solAssert(m_currentCodeSection != 0, "Appending function return without begin function.");
return AssemblyItem::functionReturn();
}
uint16_t Assembly::createFunction(uint8_t _args, uint8_t _rets, bool _nonReturning)
{
size_t functionID = m_codeSections.size();
solRequire(functionID < 1024, AssemblyException, "Too many functions for EOF");
solAssert(m_currentCodeSection == 0, "Functions need to be declared from the main block.");
solRequire(_rets <= 127, AssemblyException, "Too many function returns.");
solRequire(_args <= 127, AssemblyException, "Too many function inputs.");
m_codeSections.emplace_back(CodeSection{_args, _rets, _nonReturning, {}});
return static_cast<uint16_t>(functionID);
}
void Assembly::beginFunction(uint16_t _functionID)
{
solAssert(m_currentCodeSection == 0, "Attempted to begin a function before ending the last one.");
solAssert(_functionID != 0, "Attempt to begin a function with id 0");
solAssert(_functionID < m_codeSections.size(), "Attempt to begin an undeclared function.");
auto& section = m_codeSections.at(_functionID);
solAssert(section.items.empty(), "Function already defined.");
m_currentCodeSection = _functionID;
}
void Assembly::endFunction()
{
solAssert(m_currentCodeSection != 0, "End function without begin function.");
m_currentCodeSection = 0;
}
AssemblyItem Assembly::newPushLibraryAddress(std::string const& _identifier)
{
h256 h(util::keccak256(_identifier));
m_libraries[h] = _identifier;
return AssemblyItem{PushLibraryAddress, h};
}
AssemblyItem Assembly::newPushImmutable(std::string const& _identifier)
{
h256 h(util::keccak256(_identifier));
m_immutables[h] = _identifier;
return AssemblyItem{PushImmutable, h};
}
AssemblyItem Assembly::newImmutableAssignment(std::string const& _identifier)
{
h256 h(util::keccak256(_identifier));
m_immutables[h] = _identifier;
return AssemblyItem{AssignImmutable, h};
}
AssemblyItem Assembly::newAuxDataLoadN(size_t _offset) const
{
return AssemblyItem{AuxDataLoadN, _offset};
}
AssemblyItem Assembly::newSwapN(size_t _depth) const
{
return AssemblyItem::swapN(_depth);
}
AssemblyItem Assembly::newDupN(size_t _depth) const
{
return AssemblyItem::dupN(_depth);
}
Assembly& Assembly::optimise(OptimiserSettings const& _settings)
{
optimiseInternal(_settings, {});
return *this;
}
std::map<u256, u256> const& Assembly::optimiseInternal(
OptimiserSettings const& _settings,
std::set<size_t> _tagsReferencedFromOutside
)
{
if (m_tagReplacements)
return *m_tagReplacements;
// Run optimisation for sub-assemblies.
// TODO: verify and double-check this for EOF.
for (size_t subId = 0; subId < m_subs.size(); ++subId)
{
OptimiserSettings settings = _settings;
Assembly& sub = *m_subs[subId];
std::set<size_t> referencedTags;
for (auto& codeSection: m_codeSections)
referencedTags += JumpdestRemover::referencedTags(codeSection.items, subId);
std::map<u256, u256> const& subTagReplacements = sub.optimiseInternal(
settings,
referencedTags
);
// Apply the replacements (can be empty).
for (auto& codeSection: m_codeSections)
BlockDeduplicator::applyTagReplacement(codeSection.items, subTagReplacements, subId);
}
std::map<u256, u256> tagReplacements;
// Iterate until no new optimisation possibilities are found.
for (unsigned count = 1; count > 0;)
{
count = 0;
// TODO: verify this for EOF.
if (_settings.runInliner && !m_eofVersion.has_value())
{
solAssert(m_codeSections.size() == 1);
Inliner{
m_codeSections.front().items,
_tagsReferencedFromOutside,
_settings.expectedExecutionsPerDeployment,
isCreation(),
m_evmVersion
}.optimise();
}
// TODO: verify this for EOF.
if (_settings.runJumpdestRemover && !m_eofVersion.has_value())
{
for (auto& codeSection: m_codeSections)
{
JumpdestRemover jumpdestOpt{codeSection.items};
if (jumpdestOpt.optimise(_tagsReferencedFromOutside))
count++;
}
}
if (_settings.runPeephole)
{
for (auto& codeSection: m_codeSections)
{
PeepholeOptimiser peepOpt{codeSection.items, m_evmVersion};
while (peepOpt.optimise())
{
count++;
assertThrow(count < 64000, OptimizerException, "Peephole optimizer seems to be stuck.");
}
}
}
// This only modifies PushTags, we have to run again to actually remove code.
// TODO: implement for EOF.
if (_settings.runDeduplicate && !m_eofVersion.has_value())
for (auto& section: m_codeSections)
{
BlockDeduplicator deduplicator{section.items};
if (deduplicator.deduplicate())
{
for (auto const& replacement: deduplicator.replacedTags())
{
assertThrow(
replacement.first <= std::numeric_limits<size_t>::max() && replacement.second <= std::numeric_limits<size_t>::max(),
OptimizerException,
"Invalid tag replacement."
);
assertThrow(
!tagReplacements.count(replacement.first),
OptimizerException,
"Replacement already known."
);
tagReplacements[replacement.first] = replacement.second;
if (_tagsReferencedFromOutside.erase(static_cast<size_t>(replacement.first)))
_tagsReferencedFromOutside.insert(static_cast<size_t>(replacement.second));
}
count++;
}
}
// TODO: investigate for EOF
if (_settings.runCSE && !m_eofVersion.has_value())
{
// Control flow graph optimization has been here before but is disabled because it
// assumes we only jump to tags that are pushed. This is not the case anymore with
// function types that can be stored in storage.
AssemblyItems optimisedItems;
solAssert(m_codeSections.size() == 1);
auto& items = m_codeSections.front().items;
bool usesMSize = ranges::any_of(items, [](AssemblyItem const& _i) {
return _i == AssemblyItem{Instruction::MSIZE} || _i.type() == VerbatimBytecode;
});
auto iter = items.begin();
while (iter != items.end())
{
KnownState emptyState;
CommonSubexpressionEliminator eliminator{emptyState};
auto orig = iter;
iter = eliminator.feedItems(iter, items.end(), usesMSize);
bool shouldReplace = false;
AssemblyItems optimisedChunk;
try
{
optimisedChunk = eliminator.getOptimizedItems();
shouldReplace = (optimisedChunk.size() < static_cast<size_t>(iter - orig));
}
catch (StackTooDeepException const&)
{
// This might happen if the opcode reconstruction is not as efficient
// as the hand-crafted code.
}
catch (ItemNotAvailableException const&)
{
// This might happen if e.g. associativity and commutativity rules
// reorganise the expression tree, but not all leaves are available.
}
if (shouldReplace)
{
count++;
optimisedItems += optimisedChunk;
}
else
copy(orig, iter, back_inserter(optimisedItems));
}
if (optimisedItems.size() < items.size())
{
items = std::move(optimisedItems);
count++;
}
}
}
// TODO: investigate for EOF
if (_settings.runConstantOptimiser && !m_eofVersion.has_value())
ConstantOptimisationMethod::optimiseConstants(
isCreation(),
isCreation() ? 1 : _settings.expectedExecutionsPerDeployment,
m_evmVersion,
*this
);
m_tagReplacements = std::move(tagReplacements);
return *m_tagReplacements;
}
namespace
{
template<typename ValueT>
void setBigEndian(bytes& _dest, size_t _offset, size_t _size, ValueT _value)
{
assertThrow(numberEncodingSize(_value) <= _size, AssemblyException, "");
toBigEndian(_value, bytesRef(_dest.data() + _offset, _size));
}
template<typename ValueT>
void appendBigEndian(bytes& _dest, size_t _size, ValueT _value)
{
_dest.resize(_dest.size() + _size);
setBigEndian(_dest, _dest.size() - _size, _size, _value);
}
template<typename ValueT>
void setBigEndianUint16(bytes& _dest, size_t _offset, ValueT _value)
{
setBigEndian(_dest, _offset, 2, _value);
}
template<typename ValueT>
void appendBigEndianUint16(bytes& _dest, ValueT _value)
{
static_assert(!std::numeric_limits<ValueT>::is_signed, "only unsigned types or bigint supported");
assertThrow(_value <= 0xFFFF, AssemblyException, "");
appendBigEndian(_dest, 2, static_cast<size_t>(_value));
}
// Calculates maximum stack height for given code section. According to EIP5450 https://eips.ethereum.org/EIPS/eip-5450
uint16_t calculateMaxStackHeight(Assembly::CodeSection const& _section)
{
static auto constexpr UNVISITED = std::numeric_limits<size_t>::max();
AssemblyItems const& items = _section.items;
solAssert(!items.empty());
uint16_t overallMaxHeight = _section.inputs;
std::stack<size_t> worklist;
std::vector<size_t> maxStackHeights(items.size(), UNVISITED);
// Init first item stack height to number of inputs to the code section
// maxStackHeights stores stack height for an item before the item execution
maxStackHeights[0] = _section.inputs;
// Push first item index to the worklist
worklist.push(0u);