Coverage Report

Created: 2022-08-24 06:28

/src/solidity/libsolidity/interface/CompilerStack.h
Line
Count
Source (jump to first uncovered line)
1
/*
2
  This file is part of solidity.
3
4
  solidity is free software: you can redistribute it and/or modify
5
  it under the terms of the GNU General Public License as published by
6
  the Free Software Foundation, either version 3 of the License, or
7
  (at your option) any later version.
8
9
  solidity is distributed in the hope that it will be useful,
10
  but WITHOUT ANY WARRANTY; without even the implied warranty of
11
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
  GNU General Public License for more details.
13
14
  You should have received a copy of the GNU General Public License
15
  along with solidity.  If not, see <http://www.gnu.org/licenses/>.
16
*/
17
// SPDX-License-Identifier: GPL-3.0
18
/**
19
 * @author Christian <c@ethdev.com>
20
 * @author Gav Wood <g@ethdev.com>
21
 * @date 2014
22
 * Full-stack compiler that converts a source code string to bytecode.
23
 */
24
25
#pragma once
26
27
#include <libsolidity/analysis/FunctionCallGraph.h>
28
#include <libsolidity/interface/ReadFile.h>
29
#include <libsolidity/interface/ImportRemapper.h>
30
#include <libsolidity/interface/OptimiserSettings.h>
31
#include <libsolidity/interface/Version.h>
32
#include <libsolidity/interface/DebugSettings.h>
33
34
#include <libsolidity/formal/ModelCheckerSettings.h>
35
36
#include <libsmtutil/SolverInterface.h>
37
38
#include <liblangutil/CharStreamProvider.h>
39
#include <liblangutil/DebugInfoSelection.h>
40
#include <liblangutil/ErrorReporter.h>
41
#include <liblangutil/EVMVersion.h>
42
#include <liblangutil/SourceLocation.h>
43
44
#include <libevmasm/LinkerObject.h>
45
46
#include <libsolutil/Common.h>
47
#include <libsolutil/FixedHash.h>
48
#include <libsolutil/LazyInit.h>
49
50
#include <json/json.h>
51
52
#include <functional>
53
#include <memory>
54
#include <ostream>
55
#include <set>
56
#include <string>
57
#include <vector>
58
59
namespace solidity::langutil
60
{
61
class CharStream;
62
}
63
64
65
namespace solidity::evmasm
66
{
67
class Assembly;
68
class AssemblyItem;
69
using AssemblyItems = std::vector<AssemblyItem>;
70
}
71
72
namespace solidity::frontend
73
{
74
75
// forward declarations
76
class ASTNode;
77
class ContractDefinition;
78
class FunctionDefinition;
79
class SourceUnit;
80
class Compiler;
81
class GlobalContext;
82
class Natspec;
83
class DeclarationContainer;
84
85
/**
86
 * Easy to use and self-contained Solidity compiler with as few header dependencies as possible.
87
 * It holds state and can be used to either step through the compilation stages (and abort e.g.
88
 * before compilation to bytecode) or run the whole compilation in one call.
89
 * If error recovery is active, it is possible to progress through the stages even when
90
 * there are errors. In any case, producing code is only possible without errors.
91
 */
92
class CompilerStack: public langutil::CharStreamProvider
93
{
94
public:
95
  /// Noncopyable.
96
  CompilerStack(CompilerStack const&) = delete;
97
  CompilerStack& operator=(CompilerStack const&) = delete;
98
99
  enum State {
100
    Empty,
101
    SourcesSet,
102
    Parsed,
103
    ParsedAndImported,
104
    AnalysisPerformed,
105
    CompilationSuccessful
106
  };
107
108
  enum class MetadataFormat {
109
    WithReleaseVersionTag,
110
    WithPrereleaseVersionTag,
111
    NoMetadata
112
  };
113
114
  enum class MetadataHash {
115
    IPFS,
116
    Bzzr1,
117
    None
118
  };
119
120
  /// Creates a new compiler stack.
121
  /// @param _readFile callback used to read files for import statements. Must return
122
  /// and must not emit exceptions.
123
  explicit CompilerStack(ReadCallback::Callback _readFile = ReadCallback::Callback());
124
125
  ~CompilerStack() override;
126
127
  /// @returns the list of errors that occurred during parsing and type checking.
128
0
  langutil::ErrorList const& errors() const { return m_errorReporter.errors(); }
129
130
  /// @returns the current state.
131
0
  State state() const { return m_stackState; }
132
133
0
  bool hasError() const { return m_hasError; }
134
135
0
  bool compilationSuccessful() const { return m_stackState >= CompilationSuccessful; }
136
137
  /// Resets the compiler to an empty state. Unless @a _keepSettings is set to true,
138
  /// all settings are reset as well.
139
  void reset(bool _keepSettings = false);
140
141
  /// Sets path remappings.
142
  /// Must be set before parsing.
143
  void setRemappings(std::vector<ImportRemapper::Remapping> _remappings);
144
145
  /// Sets library addresses. Addresses are cleared iff @a _libraries is missing.
146
  /// Must be set before parsing.
147
  void setLibraries(std::map<std::string, util::h160> const& _libraries = {});
148
149
  /// Changes the optimiser settings.
150
  /// Must be set before parsing.
151
  void setOptimiserSettings(bool _optimize, size_t _runs = OptimiserSettings{}.expectedExecutionsPerDeployment);
152
153
  /// Changes the optimiser settings.
154
  /// Must be set before parsing.
155
  void setOptimiserSettings(OptimiserSettings _settings);
156
157
  /// Sets whether to strip revert strings, add additional strings or do nothing at all.
158
  void setRevertStringBehaviour(RevertStrings _revertStrings);
159
160
  /// Set whether or not parser error is desired.
161
  /// When called without an argument it will revert to the default.
162
  /// Must be set before parsing.
163
  void setParserErrorRecovery(bool _wantErrorRecovery = false)
164
0
  {
165
0
    m_parserErrorRecovery = _wantErrorRecovery;
166
0
  }
167
168
  /// Sets the pipeline to go through the Yul IR or not.
169
  /// Must be set before parsing.
170
  void setViaIR(bool _viaIR);
171
172
  /// Set the EVM version used before running compile.
173
  /// When called without an argument it will revert to the default version.
174
  /// Must be set before parsing.
175
  void setEVMVersion(langutil::EVMVersion _version = langutil::EVMVersion{});
176
177
  /// Set model checker settings.
178
  void setModelCheckerSettings(ModelCheckerSettings _settings);
179
180
  /// Sets the requested contract names by source.
181
  /// If empty, no filtering is performed and every contract
182
  /// found in the supplied sources is compiled.
183
  /// Names are cleared iff @a _contractNames is missing.
184
  void setRequestedContractNames(std::map<std::string, std::set<std::string>> const& _contractNames = std::map<std::string, std::set<std::string>>{})
185
0
  {
186
0
    m_requestedContractNames = _contractNames;
187
0
  }
188
189
  /// Enable EVM Bytecode generation. This is enabled by default.
190
0
  void enableEvmBytecodeGeneration(bool _enable = true) { m_generateEvmBytecode = _enable; }
191
192
  /// Enable generation of Yul IR code.
193
0
  void enableIRGeneration(bool _enable = true) { m_generateIR = _enable; }
194
195
  /// Enable experimental generation of Ewasm code. If enabled, IR is also generated.
196
0
  void enableEwasmGeneration(bool _enable = true) { m_generateEwasm = _enable; }
197
198
  /// @arg _metadataLiteralSources When true, store sources as literals in the contract metadata.
199
  /// Must be set before parsing.
200
  void useMetadataLiteralSources(bool _metadataLiteralSources);
201
202
  /// Sets whether and which hash should be used
203
  /// to store the metadata in the bytecode.
204
  /// @param _metadataHash can be IPFS, Bzzr1, None
205
  void setMetadataHash(MetadataHash _metadataHash);
206
207
  /// Select components of debug info that should be included in comments in generated assembly.
208
  void selectDebugInfo(langutil::DebugInfoSelection _debugInfoSelection);
209
210
  /// Sets the sources. Must be set before parsing.
211
  void setSources(StringMap _sources);
212
213
  /// Adds a response to an SMTLib2 query (identified by the hash of the query input).
214
  /// Must be set before parsing.
215
  void addSMTLib2Response(util::h256 const& _hash, std::string const& _response);
216
217
  /// Parses all source units that were added
218
  /// @returns false on error.
219
  bool parse();
220
221
  /// Imports given SourceUnits so they can be analyzed. Leads to the same internal state as parse().
222
  /// Will throw errors if the import fails
223
  void importASTs(std::map<std::string, Json::Value> const& _sources);
224
225
  /// Performs the analysis steps (imports, scopesetting, syntaxCheck, referenceResolving,
226
  ///  typechecking, staticAnalysis) on previously parsed sources.
227
  /// @returns false on error.
228
  bool analyze();
229
230
  /// Parses and analyzes all source units that were added
231
  /// @returns false on error.
232
  bool parseAndAnalyze(State _stopAfter = State::CompilationSuccessful);
233
234
  /// Compiles the source units that were previously added and parsed.
235
  /// @returns false on error.
236
  bool compile(State _stopAfter = State::CompilationSuccessful);
237
238
  /// @returns the list of sources (paths) used
239
  std::vector<std::string> sourceNames() const;
240
241
  /// @returns a mapping assigning each source name its index inside the vector returned
242
  /// by sourceNames().
243
  std::map<std::string, unsigned> sourceIndices() const;
244
245
  /// @returns the previously used character stream, useful for counting lines during error reporting.
246
  langutil::CharStream const& charStream(std::string const& _sourceName) const override;
247
248
  /// @returns the parsed source unit with the supplied name.
249
  SourceUnit const& ast(std::string const& _sourceName) const;
250
251
  /// @returns the parsed contract with the supplied name. Throws an exception if the contract
252
  /// does not exist.
253
  ContractDefinition const& contractDefinition(std::string const& _contractName) const;
254
255
  /// @returns a list of unhandled queries to the SMT solver (has to be supplied in a second run
256
  /// by calling @a addSMTLib2Response).
257
0
  std::vector<std::string> const& unhandledSMTLib2Queries() const { return m_unhandledSMTLib2Queries; }
258
259
  /// @returns a list of the contract names in the sources.
260
  std::vector<std::string> contractNames() const;
261
262
  /// @returns the name of the last contract. If _sourceName is defined the last contract of that source will be returned.
263
  std::string const lastContractName(std::optional<std::string> const& _sourceName = std::nullopt) const;
264
265
  /// @returns either the contract's name or a mixture of its name and source file, sanitized for filesystem use
266
  std::string const filesystemFriendlyName(std::string const& _contractName) const;
267
268
  /// @returns the IR representation of a contract.
269
  std::string const& yulIR(std::string const& _contractName) const;
270
271
  /// @returns the optimized IR representation of a contract.
272
  std::string const& yulIROptimized(std::string const& _contractName) const;
273
274
  /// @returns the Ewasm text representation of a contract.
275
  std::string const& ewasm(std::string const& _contractName) const;
276
277
  /// @returns the Ewasm representation of a contract.
278
  evmasm::LinkerObject const& ewasmObject(std::string const& _contractName) const;
279
280
  /// @returns the assembled object for a contract.
281
  evmasm::LinkerObject const& object(std::string const& _contractName) const;
282
283
  /// @returns the runtime object for the contract.
284
  evmasm::LinkerObject const& runtimeObject(std::string const& _contractName) const;
285
286
  /// @returns normal contract assembly items
287
  evmasm::AssemblyItems const* assemblyItems(std::string const& _contractName) const;
288
289
  /// @returns runtime contract assembly items
290
  evmasm::AssemblyItems const* runtimeAssemblyItems(std::string const& _contractName) const;
291
292
  /// @returns an array containing all utility sources generated during compilation.
293
  /// Format: [ { name: string, id: number, language: "Yul", contents: string }, ... ]
294
  Json::Value generatedSources(std::string const& _contractName, bool _runtime = false) const;
295
296
  /// @returns the string that provides a mapping between bytecode and sourcecode or a nullptr
297
  /// if the contract does not (yet) have bytecode.
298
  std::string const* sourceMapping(std::string const& _contractName) const;
299
300
  /// @returns the string that provides a mapping between runtime bytecode and sourcecode.
301
  /// if the contract does not (yet) have bytecode.
302
  std::string const* runtimeSourceMapping(std::string const& _contractName) const;
303
304
  /// @return a verbose text representation of the assembly.
305
  /// @arg _sourceCodes is the map of input files to source code strings
306
  /// Prerequisite: Successful compilation.
307
  std::string assemblyString(std::string const& _contractName, StringMap const& _sourceCodes = StringMap()) const;
308
309
  /// @returns a JSON representation of the assembly.
310
  /// @arg _sourceCodes is the map of input files to source code strings
311
  /// Prerequisite: Successful compilation.
312
  Json::Value assemblyJSON(std::string const& _contractName) const;
313
314
  /// @returns a JSON representing the contract ABI.
315
  /// Prerequisite: Successful call to parse or compile.
316
  Json::Value const& contractABI(std::string const& _contractName) const;
317
318
  /// @returns a JSON representing the storage layout of the contract.
319
  /// Prerequisite: Successful call to parse or compile.
320
  Json::Value const& storageLayout(std::string const& _contractName) const;
321
322
  /// @returns a JSON representing the contract's user documentation.
323
  /// Prerequisite: Successful call to parse or compile.
324
  Json::Value const& natspecUser(std::string const& _contractName) const;
325
326
  /// @returns a JSON representing the contract's developer documentation.
327
  /// Prerequisite: Successful call to parse or compile.
328
  Json::Value const& natspecDev(std::string const& _contractName) const;
329
330
  /// @returns a JSON object with the three members ``methods``, ``events``, ``errors``. Each is a map, mapping identifiers (hashes) to function names.
331
  Json::Value interfaceSymbols(std::string const& _contractName) const;
332
333
  /// @returns the Contract Metadata matching the pipeline selected using the viaIR setting.
334
0
  std::string const& metadata(std::string const& _contractName) const { return metadata(contract(_contractName)); }
335
336
  /// @returns the CBOR-encoded metadata matching the pipeline selected using the viaIR setting.
337
0
  bytes cborMetadata(std::string const& _contractName) const { return cborMetadata(_contractName, m_viaIR); }
338
339
  /// @returns the CBOR-encoded metadata.
340
  /// @param _forIR If true, the metadata for the IR codegen is used. Otherwise it's the metadata
341
  ///               for the EVM codegen
342
  bytes cborMetadata(std::string const& _contractName, bool _forIR) const;
343
344
  /// @returns a JSON representing the estimated gas usage for contract creation, internal and external functions
345
  Json::Value gasEstimates(std::string const& _contractName) const;
346
347
  /// Changes the format of the metadata appended at the end of the bytecode.
348
  /// This is mostly a workaround to avoid bytecode and gas differences between compiler builds
349
  /// caused by differences in metadata. Should only be used for testing.
350
0
  void setMetadataFormat(MetadataFormat _metadataFormat) { m_metadataFormat = _metadataFormat; }
351
352
private:
353
  /// The state per source unit. Filled gradually during parsing.
354
  struct Source
355
  {
356
    std::shared_ptr<langutil::CharStream> charStream;
357
    std::shared_ptr<SourceUnit> ast;
358
    util::h256 mutable keccak256HashCached;
359
    util::h256 mutable swarmHashCached;
360
    std::string mutable ipfsUrlCached;
361
0
    void reset() { *this = Source(); }
362
    util::h256 const& keccak256() const;
363
    util::h256 const& swarmHash() const;
364
    std::string const& ipfsUrl() const;
365
  };
366
367
  /// The state per contract. Filled gradually during compilation.
368
  struct Contract
369
  {
370
    ContractDefinition const* contract = nullptr;
371
    std::shared_ptr<Compiler> compiler;
372
    std::shared_ptr<evmasm::Assembly> evmAssembly;
373
    std::shared_ptr<evmasm::Assembly> evmRuntimeAssembly;
374
    evmasm::LinkerObject object; ///< Deployment object (includes the runtime sub-object).
375
    evmasm::LinkerObject runtimeObject; ///< Runtime object.
376
    std::string yulIR; ///< Yul IR code.
377
    std::string yulIROptimized; ///< Optimized Yul IR code.
378
    std::string ewasm; ///< Experimental Ewasm text representation
379
    evmasm::LinkerObject ewasmObject; ///< Experimental Ewasm code
380
    util::LazyInit<std::string const> metadata; ///< The metadata json that will be hashed into the chain.
381
    util::LazyInit<Json::Value const> abi;
382
    util::LazyInit<Json::Value const> storageLayout;
383
    util::LazyInit<Json::Value const> userDocumentation;
384
    util::LazyInit<Json::Value const> devDocumentation;
385
    util::LazyInit<Json::Value const> generatedSources;
386
    util::LazyInit<Json::Value const> runtimeGeneratedSources;
387
    mutable std::optional<std::string const> sourceMapping;
388
    mutable std::optional<std::string const> runtimeSourceMapping;
389
  };
390
391
  void createAndAssignCallGraphs();
392
  void findAndReportCyclicContractDependencies();
393
394
  /// Loads the missing sources from @a _ast (named @a _path) using the callback
395
  /// @a m_readFile
396
  /// @returns the newly loaded sources.
397
  StringMap loadMissingSources(SourceUnit const& _ast);
398
  std::string applyRemapping(std::string const& _path, std::string const& _context);
399
  void resolveImports();
400
401
  /// Store the contract definitions in m_contracts.
402
  void storeContractDefinitions();
403
404
  /// @returns true if the source is requested to be compiled.
405
  bool isRequestedSource(std::string const& _sourceName) const;
406
407
  /// @returns true if the contract is requested to be compiled.
408
  bool isRequestedContract(ContractDefinition const& _contract) const;
409
410
  /// Assembles the contract.
411
  /// This function should only be internally called by compileContract and generateEVMFromIR.
412
  void assemble(
413
    ContractDefinition const& _contract,
414
    std::shared_ptr<evmasm::Assembly> _assembly,
415
    std::shared_ptr<evmasm::Assembly> _runtimeAssembly
416
  );
417
418
  /// Compile a single contract.
419
  /// @param _otherCompilers provides access to compilers of other contracts, to get
420
  ///                        their bytecode if needed. Only filled after they have been compiled.
421
  void compileContract(
422
    ContractDefinition const& _contract,
423
    std::map<ContractDefinition const*, std::shared_ptr<Compiler const>>& _otherCompilers
424
  );
425
426
  /// Generate Yul IR for a single contract.
427
  /// The IR is stored but otherwise unused.
428
  void generateIR(ContractDefinition const& _contract);
429
430
  /// Generate EVM representation for a single contract.
431
  /// Depends on output generated by generateIR.
432
  void generateEVMFromIR(ContractDefinition const& _contract);
433
434
  /// Generate Ewasm representation for a single contract.
435
  /// Depends on output generated by generateIR.
436
  void generateEwasm(ContractDefinition const& _contract);
437
438
  /// Links all the known library addresses in the available objects. Any unknown
439
  /// library will still be kept as an unlinked placeholder in the objects.
440
  void link();
441
442
  /// @returns the contract object for the given @a _contractName.
443
  /// Can only be called after state is CompilationSuccessful.
444
  Contract const& contract(std::string const& _contractName) const;
445
446
  /// @returns the source object for the given @a _sourceName.
447
  /// Can only be called after state is SourcesSet.
448
  Source const& source(std::string const& _sourceName) const;
449
450
  /// @param _forIR If true, include a flag that indicates that the bytecode comes from IR codegen.
451
  /// @returns the metadata JSON as a compact string for the given contract.
452
  std::string createMetadata(Contract const& _contract, bool _forIR) const;
453
454
  /// @returns the metadata CBOR for the given serialised metadata JSON.
455
  /// @param _forIR If true, use the metadata for the IR codegen. Otherwise the one for EVM codegen.
456
  bytes createCBORMetadata(Contract const& _contract, bool _forIR) const;
457
458
  /// @returns the contract ABI as a JSON object.
459
  /// This will generate the JSON object and store it in the Contract object if it is not present yet.
460
  Json::Value const& contractABI(Contract const&) const;
461
462
  /// @returns the storage layout of the contract as a JSON object.
463
  /// This will generate the JSON object and store it in the Contract object if it is not present yet.
464
  Json::Value const& storageLayout(Contract const&) const;
465
466
  /// @returns the Natspec User documentation as a JSON object.
467
  /// This will generate the JSON object and store it in the Contract object if it is not present yet.
468
  Json::Value const& natspecUser(Contract const&) const;
469
470
  /// @returns the Natspec Developer documentation as a JSON object.
471
  /// This will generate the JSON object and store it in the Contract object if it is not present yet.
472
  Json::Value const& natspecDev(Contract const&) const;
473
474
  /// @returns the Contract Metadata matching the pipeline selected using the viaIR setting.
475
  /// This will generate the metadata and store it in the Contract object if it is not present yet.
476
  std::string const& metadata(Contract const& _contract) const;
477
478
  /// @returns the offset of the entry point of the given function into the list of assembly items
479
  /// or zero if it is not found or does not exist.
480
  size_t functionEntryPoint(
481
    std::string const& _contractName,
482
    FunctionDefinition const& _function
483
  ) const;
484
485
  ReadCallback::Callback m_readFile;
486
  OptimiserSettings m_optimiserSettings;
487
  RevertStrings m_revertStrings = RevertStrings::Default;
488
  State m_stopAfter = State::CompilationSuccessful;
489
  bool m_viaIR = false;
490
  langutil::EVMVersion m_evmVersion;
491
  ModelCheckerSettings m_modelCheckerSettings;
492
  std::map<std::string, std::set<std::string>> m_requestedContractNames;
493
  bool m_generateEvmBytecode = true;
494
  bool m_generateIR = false;
495
  bool m_generateEwasm = false;
496
  std::map<std::string, util::h160> m_libraries;
497
  ImportRemapper m_importRemapper;
498
  std::map<std::string const, Source> m_sources;
499
  // if imported, store AST-JSONS for each filename
500
  std::map<std::string, Json::Value> m_sourceJsons;
501
  std::vector<std::string> m_unhandledSMTLib2Queries;
502
  std::map<util::h256, std::string> m_smtlib2Responses;
503
  std::shared_ptr<GlobalContext> m_globalContext;
504
  std::vector<Source const*> m_sourceOrder;
505
  std::map<std::string const, Contract> m_contracts;
506
507
  langutil::ErrorList m_errorList;
508
  langutil::ErrorReporter m_errorReporter;
509
  bool m_metadataLiteralSources = false;
510
  MetadataHash m_metadataHash = MetadataHash::IPFS;
511
  langutil::DebugInfoSelection m_debugInfoSelection = langutil::DebugInfoSelection::Default();
512
  bool m_parserErrorRecovery = false;
513
  State m_stackState = Empty;
514
  bool m_importedSources = false;
515
  /// Whether or not there has been an error during processing.
516
  /// If this is true, the stack will refuse to generate code.
517
  bool m_hasError = false;
518
  MetadataFormat m_metadataFormat = VersionIsRelease ? MetadataFormat::WithReleaseVersionTag : MetadataFormat::WithPrereleaseVersionTag;
519
};
520
521
}