id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
2,856
|
globalvalues.h
|
flameshot-org_flameshot/src/utils/globalvalues.h
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#pragma once
class QString;
namespace GlobalValues {
int buttonBaseSize();
QString versionInfo();
QString iconPath();
QString iconPathPNG();
}
| 265
|
C++
|
.h
| 10
| 25.1
| 72
| 0.808765
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,857
|
abstractlogger.h
|
flameshot-org_flameshot/src/utils/abstractlogger.h
|
#pragma once
#include <QString>
#include <QTextStream>
/**
* @brief A class that allows you to log events to where they need to go.
*/
class AbstractLogger
{
public:
enum Target
{
Notification = 0x01,
Stderr = 0x02,
LogFile = 0x08,
String = 0x10,
Stdout = 0x20,
Default = Notification | LogFile | Stderr,
};
enum Channel
{
Info,
Warning,
Error
};
AbstractLogger(Channel channel = Info, int targets = Default);
AbstractLogger(QString& str,
Channel channel,
int additionalTargets = String);
~AbstractLogger();
// Convenience functions
static AbstractLogger info(int targets = Default);
static AbstractLogger warning(int targets = Default);
static AbstractLogger error(int targets = Default);
AbstractLogger& sendMessage(const QString& msg, Channel channel);
AbstractLogger& operator<<(const QString& msg);
AbstractLogger& addOutputString(QString& str);
AbstractLogger& attachNotificationPath(const QString& path);
AbstractLogger& enableMessageHeader(bool enable);
private:
QString messageHeader(Channel channel, Target target);
int m_targets;
Channel m_defaultChannel;
QList<QTextStream*> m_textStreams;
QString m_notificationPath;
bool m_enableMessageHeader = true;
};
| 1,384
|
C++
|
.h
| 46
| 24.391304
| 73
| 0.685714
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,858
|
history.h
|
flameshot-org_flameshot/src/utils/history.h
|
#ifndef HISTORY_H
#define HISTORY_H
#define HISTORYPIXMAP_MAX_PREVIEW_WIDTH 250
#define HISTORYPIXMAP_MAX_PREVIEW_HEIGHT 100
#include <QList>
#include <QPixmap>
#include <QString>
struct HistoryFileName
{
QString file;
QString token;
QString type;
};
class History
{
public:
History();
void save(const QPixmap&, const QString&);
const QList<QString>& history();
const QString& path();
const HistoryFileName& unpackFileName(const QString&);
const QString& packFileName(const QString&, const QString&, const QString&);
private:
QString m_historyPath;
QList<QString> m_thumbs;
// temporary variables
QString m_packedFileName;
HistoryFileName m_unpackedFileName;
};
#endif // HISTORY_H
| 747
|
C++
|
.h
| 30
| 21.733333
| 80
| 0.75
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,859
|
confighandler.h
|
flameshot-org_flameshot/src/utils/confighandler.h
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#pragma once
#include "src/widgets/capture/capturetoolbutton.h"
#include <QSettings>
#include <QStringList>
#include <QVariant>
#include <QVector>
#define CONFIG_GROUP_GENERAL "General"
#define CONFIG_GROUP_SHORTCUTS "Shortcuts"
class QFileSystemWatcher;
class ValueHandler;
template<class T>
class QSharedPointer;
class QTextStream;
class AbstractLogger;
/**
* Declare and implement a getter for a config option. `KEY` is the option key
* as it appears in the config file, `TYPE` is the C++ type. At the same time
* `KEY` is the name of the generated getter function.
*/
// clang-format off
#define CONFIG_GETTER(KEY, TYPE) \
TYPE KEY() \
{ \
return value(QStringLiteral(#KEY)).value<TYPE>(); \
}
// clang-format on
/**
* Declare and implement a setter for a config option. `FUNC` is the name of the
* generated function, `KEY` is the option key as it appears in the config file
* and `TYPE` is the C++ type.
*/
#define CONFIG_SETTER(FUNC, KEY, TYPE) \
void FUNC(const TYPE& val) \
{ \
QString key = QStringLiteral(#KEY); \
/* Without this check, multiple `flameshot gui` instances running */ \
/* simultaneously would cause an endless loop of fileWatcher calls */ \
if (QVariant::fromValue(val) != value(key)) { \
setValue(key, QVariant::fromValue(val)); \
} \
}
/**
* Combines the functionality of `CONFIG_GETTER` and `CONFIG_SETTER`. `GETFUNC`
* is simultaneously the name of the getter function and the option key as it
* appears in the config file. `SETFUNC` is the name of the setter function.
* `TYPE` is the C++ type of the value.
*/
#define CONFIG_GETTER_SETTER(GETFUNC, SETFUNC, TYPE) \
CONFIG_GETTER(GETFUNC, TYPE) \
CONFIG_SETTER(SETFUNC, GETFUNC, TYPE)
class ConfigHandler : public QObject
{
Q_OBJECT
public:
explicit ConfigHandler();
static ConfigHandler* getInstance();
// Definitions of getters and setters for config options
// Some special cases are implemented regularly, without the macro
// NOTE: When adding new options, make sure to add an entry in
// recognizedGeneralOptions in the cpp file.
CONFIG_GETTER_SETTER(userColors, setUserColors, QVector<QColor>);
CONFIG_GETTER_SETTER(savePath, setSavePath, QString)
CONFIG_GETTER_SETTER(savePathFixed, setSavePathFixed, bool)
CONFIG_GETTER_SETTER(uiColor, setUiColor, QColor)
CONFIG_GETTER_SETTER(contrastUiColor, setContrastUiColor, QColor)
CONFIG_GETTER_SETTER(drawColor, setDrawColor, QColor)
CONFIG_GETTER_SETTER(predefinedColorPaletteLarge,
setPredefinedColorPaletteLarge,
bool)
CONFIG_GETTER_SETTER(fontFamily, setFontFamily, QString)
CONFIG_GETTER_SETTER(showHelp, setShowHelp, bool)
CONFIG_GETTER_SETTER(showSidePanelButton, setShowSidePanelButton, bool)
CONFIG_GETTER_SETTER(showDesktopNotification,
setShowDesktopNotification,
bool)
CONFIG_GETTER_SETTER(filenamePattern, setFilenamePattern, QString)
CONFIG_GETTER_SETTER(disabledTrayIcon, setDisabledTrayIcon, bool)
CONFIG_GETTER_SETTER(disabledGrimWarning, disabledGrimWarning, bool)
CONFIG_GETTER_SETTER(drawThickness, setDrawThickness, int)
CONFIG_GETTER_SETTER(drawFontSize, setDrawFontSize, int)
CONFIG_GETTER_SETTER(keepOpenAppLauncher, setKeepOpenAppLauncher, bool)
#if !defined(DISABLE_UPDATE_CHECKER)
CONFIG_GETTER_SETTER(checkForUpdates, setCheckForUpdates, bool)
#endif
CONFIG_GETTER_SETTER(allowMultipleGuiInstances,
setAllowMultipleGuiInstances,
bool)
CONFIG_GETTER_SETTER(autoCloseIdleDaemon, setAutoCloseIdleDaemon, bool)
CONFIG_GETTER_SETTER(showStartupLaunchMessage,
setShowStartupLaunchMessage,
bool)
CONFIG_GETTER_SETTER(contrastOpacity, setContrastOpacity, int)
CONFIG_GETTER_SETTER(copyURLAfterUpload, setCopyURLAfterUpload, bool)
CONFIG_GETTER_SETTER(historyConfirmationToDelete,
setHistoryConfirmationToDelete,
bool)
CONFIG_GETTER_SETTER(uploadHistoryMax, setUploadHistoryMax, int)
CONFIG_GETTER_SETTER(saveAfterCopy, setSaveAfterCopy, bool)
CONFIG_GETTER_SETTER(copyPathAfterSave, setCopyPathAfterSave, bool)
CONFIG_GETTER_SETTER(saveAsFileExtension, setSaveAsFileExtension, QString)
CONFIG_GETTER_SETTER(antialiasingPinZoom, setAntialiasingPinZoom, bool)
CONFIG_GETTER_SETTER(useJpgForClipboard, setUseJpgForClipboard, bool)
CONFIG_GETTER_SETTER(uploadWithoutConfirmation,
setUploadWithoutConfirmation,
bool)
CONFIG_GETTER_SETTER(ignoreUpdateToVersion,
setIgnoreUpdateToVersion,
QString)
CONFIG_GETTER_SETTER(undoLimit, setUndoLimit, int)
CONFIG_GETTER_SETTER(buttons, setButtons, QList<CaptureTool::Type>)
CONFIG_GETTER_SETTER(showMagnifier, setShowMagnifier, bool)
CONFIG_GETTER_SETTER(squareMagnifier, setSquareMagnifier, bool)
CONFIG_GETTER_SETTER(copyOnDoubleClick, setCopyOnDoubleClick, bool)
CONFIG_GETTER_SETTER(uploadClientSecret, setUploadClientSecret, QString)
CONFIG_GETTER_SETTER(saveLastRegion, setSaveLastRegion, bool)
CONFIG_GETTER_SETTER(showSelectionGeometry, setShowSelectionGeometry, int)
CONFIG_GETTER_SETTER(jpegQuality, setJpegQuality, int)
CONFIG_GETTER_SETTER(showSelectionGeometryHideTime,
showSelectionGeometryHideTime,
int)
// SPECIAL CASES
bool startupLaunch();
void setStartupLaunch(const bool);
void setAllTheButtons();
void setToolSize(CaptureTool::Type toolType, int size);
int toolSize(CaptureTool::Type toolType);
// DEFAULTS
QString filenamePatternDefault();
void setDefaultSettings();
QString configFilePath() const;
// GENERIC GETTERS AND SETTERS
bool setShortcut(const QString& actionName, const QString& shortcut);
QString shortcut(const QString& actionName);
void setValue(const QString& key, const QVariant& value);
QVariant value(const QString& key) const;
void remove(const QString& key);
void resetValue(const QString& key);
// INFO
static QSet<QString>& recognizedGeneralOptions();
static QSet<QString>& recognizedShortcutNames();
QSet<QString> keysFromGroup(const QString& group) const;
// ERROR HANDLING
bool checkForErrors(AbstractLogger* log = nullptr) const;
bool checkUnrecognizedSettings(AbstractLogger* log = nullptr,
QList<QString>* offenders = nullptr) const;
bool checkShortcutConflicts(AbstractLogger* log = nullptr) const;
bool checkSemantics(AbstractLogger* log = nullptr,
QList<QString>* offenders = nullptr) const;
void checkAndHandleError() const;
void setErrorState(bool error) const;
bool hasError() const;
QString errorMessage() const;
signals:
void error() const;
void errorResolved() const;
void fileChanged() const;
private:
mutable QSettings m_settings;
static bool m_hasError, m_errorCheckPending, m_skipNextErrorCheck;
static QSharedPointer<QFileSystemWatcher> m_configWatcher;
void ensureFileWatched() const;
QSharedPointer<ValueHandler> valueHandler(const QString& key) const;
void assertKeyRecognized(const QString& key) const;
bool isShortcut(const QString& key) const;
QString baseName(const QString& key) const;
void cleanUnusedKeys(const QString& group, const QSet<QString>& keys) const;
};
| 8,387
|
C++
|
.h
| 169
| 43.017751
| 80
| 0.675531
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,860
|
desktopfileparse.h
|
flameshot-org_flameshot/src/utils/desktopfileparse.h
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#pragma once
#include <QIcon>
#include <QMap>
#include <QStringList>
class QDir;
class QString;
class QTextStream;
struct DesktopAppData
{
DesktopAppData()
: showInTerminal()
{}
DesktopAppData(const QString& name,
const QString& description,
const QString& exec,
QIcon icon)
: name(name)
, description(description)
, exec(exec)
, icon(icon)
, showInTerminal(false)
{}
bool operator==(const DesktopAppData& other) const
{
return name == other.name;
}
QString name;
QString description;
QString exec;
QStringList categories;
QIcon icon;
bool showInTerminal;
};
struct DesktopFileParser
{
DesktopFileParser();
DesktopAppData parseDesktopFile(const QString& fileName, bool& ok) const;
int processDirectory(const QDir& dir);
QVector<DesktopAppData> getAppsByCategory(const QString& category);
QMap<QString, QVector<DesktopAppData>> getAppsByCategory(
const QStringList& categories);
private:
QString m_localeName;
QString m_localeDescription;
QString m_localeNameShort;
QString m_localeDescriptionShort;
QIcon m_defaultIcon;
QVector<DesktopAppData> m_appList;
};
| 1,390
|
C++
|
.h
| 51
| 22.058824
| 77
| 0.70256
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,861
|
filenamehandler.h
|
flameshot-org_flameshot/src/utils/filenamehandler.h
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#pragma once
#include <QObject>
class FileNameHandler : public QObject
{
Q_OBJECT
public:
explicit FileNameHandler(QObject* parent = nullptr);
QString parsedPattern();
QString parseFilename(const QString& name);
QString properScreenshotPath(QString filename,
const QString& format = QString());
static const int MAX_CHARACTERS = 70;
private:
QString autoNumerateDuplicate(const QString& path);
};
| 583
|
C++
|
.h
| 17
| 29.294118
| 72
| 0.729875
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,862
|
pathinfo.h
|
flameshot-org_flameshot/src/utils/pathinfo.h
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#pragma once
#include <QStringList>
namespace PathInfo { // namespace
const QString whiteIconPath();
const QString blackIconPath();
QStringList translationsPaths();
} // namespace
| 305
|
C++
|
.h
| 9
| 32.111111
| 72
| 0.806228
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,863
|
waylandutils.h
|
flameshot-org_flameshot/src/utils/waylandutils.h
|
#ifndef WAYLANDUTILS_H
#define WAYLANDUTILS_H
class WaylandUtils
{
public:
WaylandUtils();
static bool waylandDetected();
private:
};
#endif // WAYLANDUTILS_H
| 171
|
C++
|
.h
| 10
| 14.9
| 34
| 0.783439
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,864
|
screenshotsaver.h
|
flameshot-org_flameshot/src/utils/screenshotsaver.h
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#pragma once
#include <QString>
class QPixmap;
bool saveToFilesystem(const QPixmap& capture,
const QString& path,
const QString& messagePrefix = "");
QString ShowSaveFileDialog(const QString& title, const QString& directory);
void saveToClipboardMime(const QPixmap& capture, const QString& imageType);
void saveToClipboard(const QPixmap& capture);
bool saveToFilesystemGUI(const QPixmap& capture);
| 564
|
C++
|
.h
| 12
| 42
| 75
| 0.755474
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,866
|
valuehandler.h
|
flameshot-org_flameshot/src/utils/valuehandler.h
|
#pragma once
#include "src/widgets/capture/capturetoolbutton.h"
#include "src/widgets/colorpickerwidget.h"
#include <QColor>
#include <QList>
#include <QString>
class QVariant;
/**
* @brief Handles the value of a configuration option (abstract class).
*
* Each configuration option is represented as a `QVariant`. If the option was
* not specified in a config file, the `QVariant` will be invalid.
*
* Each option will usually be handled in three different ways:
* - have its value checked for semantic errors (type, format, etc).
* @see ValueHandler::check
* - have its value (that was taken from the config file) adapted for proper
* use.
* @see ValueHandler::value
* - provided a fallback value in case: the config does not explicitly specify
* it, or the config contains an error and is globally falling back to
* defaults.
* @see ValueHandler::fallback.
* - some options may want to be stored in the config file in a different way
* than the default one provided by `QVariant`.
* @see ValueHandler::representation
*
* @note Please see the documentation of the functions to learn when you should
* override each.
*
*/
class ValueHandler
{
public:
/**
* @brief Check the value semantically.
* @param val The value that was read from the config file
* @return Whether the value is correct
* @note The function should presume that `val.isValid()` is true.
*/
virtual bool check(const QVariant& val) = 0;
/**
* @brief Adapt the value for proper use.
* @param val The value that was read from the config file
* @return The modified value
*
* If the value is invalid (unspecified in the config) or does not pass
* `check`, the fallback will be returned. Otherwise the value is processed
* by `process` and then returned.
*
* @note Cannot be overridden
* @see fallback, process
*/
QVariant value(const QVariant& val);
/**
* @brief Fallback value (default value).
*/
virtual QVariant fallback();
/**
* @brief Return the representation of the value in the config file.
*
* Override this if you want to write the value in a different format than
* the one provided by `QVariant`.
*/
virtual QVariant representation(const QVariant& val);
/**
* @brief The expected value (descriptive).
* Used when reporting configuration errors.
*/
virtual QString expected();
protected:
/**
* @brief Process a value, presuming it is a valid `QVariant`.
* @param val The value that was read from the config file
* @return The processed value
* @note You will usually want to override this. In rare cases, you may want
* to override `value`.
*/
virtual QVariant process(const QVariant& val);
};
class Bool : public ValueHandler
{
public:
Bool(bool def);
bool check(const QVariant& val) override;
QVariant fallback() override;
QString expected() override;
private:
bool m_def;
};
class String : public ValueHandler
{
public:
String(QString def);
bool check(const QVariant&) override;
QVariant fallback() override;
QString expected() override;
private:
QString m_def;
};
class Color : public ValueHandler
{
public:
Color(QColor def);
bool check(const QVariant& val) override;
QVariant process(const QVariant& val) override;
QVariant fallback() override;
QVariant representation(const QVariant& val) override;
QString expected() override;
private:
QColor m_def;
};
class BoundedInt : public ValueHandler
{
public:
BoundedInt(int min, int max, int def);
bool check(const QVariant& val) override;
virtual QVariant fallback() override;
QString expected() override;
private:
int m_min, m_max, m_def;
};
class LowerBoundedInt : public ValueHandler
{
public:
LowerBoundedInt(int min, int def);
bool check(const QVariant& val) override;
QVariant fallback() override;
QString expected() override;
private:
int m_min, m_def;
};
class KeySequence : public ValueHandler
{
public:
KeySequence(const QKeySequence& fallback = {});
bool check(const QVariant& val) override;
QVariant fallback() override;
QString expected() override;
QVariant representation(const QVariant& val) override;
private:
QKeySequence m_fallback;
QVariant process(const QVariant& val) override;
};
class ExistingDir : public ValueHandler
{
bool check(const QVariant& val) override;
QVariant fallback() override;
QString expected() override;
};
class FilenamePattern : public ValueHandler
{
bool check(const QVariant&) override;
QVariant fallback() override;
QVariant process(const QVariant&) override;
QString expected() override;
};
class ButtonList : public ValueHandler
{
public:
bool check(const QVariant& val) override;
QVariant process(const QVariant& val) override;
QVariant fallback() override;
QVariant representation(const QVariant& val) override;
QString expected() override;
// UTILITY FUNCTIONS
static QList<CaptureTool::Type> fromIntList(const QList<int>&);
static QList<int> toIntList(const QList<CaptureTool::Type>& l);
static bool normalizeButtons(QList<int>& buttons);
};
class UserColors : public ValueHandler
{
public:
UserColors(int min, int max);
bool check(const QVariant& val) override;
QVariant process(const QVariant& val) override;
QVariant fallback() override;
QString expected() override;
QVariant representation(const QVariant& val) override;
private:
int m_min, m_max;
};
class SaveFileExtension : public ValueHandler
{
bool check(const QVariant& val) override;
QVariant process(const QVariant& val) override;
QString expected() override;
};
class Region : public ValueHandler
{
public:
bool check(const QVariant& val) override;
private:
QVariant process(const QVariant& val) override;
};
| 5,973
|
C++
|
.h
| 195
| 27.030769
| 80
| 0.722783
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,867
|
winlnkfileparse.h
|
flameshot-org_flameshot/src/utils/winlnkfileparse.h
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#pragma once
#include "desktopfileparse.h"
#include <QFileInfo>
#include <QIcon>
#include <QMap>
#include <QStringList>
class QDir;
class QString;
struct CompareAppByName
{
bool operator()(const DesktopAppData a, const DesktopAppData b)
{
return (a.name < b.name);
}
};
struct WinLnkFileParser
{
WinLnkFileParser();
DesktopAppData parseLnkFile(const QFileInfo& fiLnk, bool& ok) const;
int processDirectory(const QDir& dir);
QString getAllUsersStartMenuPath();
QVector<DesktopAppData> getAppsByCategory(const QString& category);
QMap<QString, QVector<DesktopAppData>> getAppsByCategory(
const QStringList& categories);
private:
void getImageFileExtAssociates(const QStringList& sListImgExt);
QVector<DesktopAppData> m_appList;
QStringList m_GraphicAppsList;
};
| 948
|
C++
|
.h
| 31
| 27.322581
| 72
| 0.772277
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,870
|
commandoption.h
|
flameshot-org_flameshot/src/cli/commandoption.h
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#pragma once
#include <QStringList>
#include <functional>
using std::function;
class CommandOption
{
public:
CommandOption(const QString& name,
QString description,
QString valueName = QString(),
QString defaultValue = QString());
CommandOption(QStringList names,
QString description,
QString valueName = QString(),
QString defaultValue = QString());
void setName(const QString& name);
void setNames(const QStringList& names);
QStringList names() const;
QStringList dashedNames() const;
void setValueName(const QString& name);
QString valueName() const;
void setValue(const QString& value);
QString value() const;
void addChecker(const function<bool(QString const&)> checker,
const QString& errMsg);
bool checkValue(const QString& value) const;
QString description() const;
void setDescription(const QString& description);
QString errorMsg() const;
bool operator==(const CommandOption& option) const;
private:
QStringList m_names;
QString m_description;
QString m_valueName;
QString m_value;
function<bool(QString const&)> m_checker;
QString m_errorMsg;
};
| 1,405
|
C++
|
.h
| 40
| 28.375
| 72
| 0.685418
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,871
|
commandlineparser.h
|
flameshot-org_flameshot/src/cli/commandlineparser.h
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#pragma once
#include "src/cli/commandargument.h"
#include "src/cli/commandoption.h"
#include <QMap>
class CommandLineParser
{
public:
CommandLineParser();
bool parse(const QStringList& args);
CommandArgument rootArgument() const { return CommandArgument(); }
CommandOption addVersionOption();
CommandOption addHelpOption();
bool AddArgument(const CommandArgument& arg,
const CommandArgument& parent = CommandArgument());
bool AddOption(const CommandOption& option,
const CommandArgument& parent = CommandArgument());
bool AddOptions(const QList<CommandOption>& options,
const CommandArgument& parent = CommandArgument());
void setGeneralErrorMessage(const QString& msg);
void setDescription(const QString& description);
bool isSet(const CommandArgument& arg) const;
bool isSet(const CommandOption& option) const;
QString value(const CommandOption& option) const;
private:
bool m_withHelp = false;
bool m_withVersion = false;
QString m_description;
QString m_generalErrorMessage;
struct Node
{
explicit Node(const CommandArgument& arg)
: argument(arg)
{}
Node() {}
bool operator==(const Node& n) const
{
return argument == n.argument && options == n.options &&
subNodes == n.subNodes;
}
CommandArgument argument;
QList<CommandOption> options;
QList<Node> subNodes;
};
Node m_parseTree;
QList<CommandOption> m_foundOptions;
QList<CommandArgument> m_foundArgs;
// helper functions
void printVersion();
void printHelp(QStringList args, const Node* node);
Node* findParent(const CommandArgument& parent);
Node* recursiveParentSearch(const CommandArgument& parent,
Node& node) const;
bool processIfOptionIsHelp(const QStringList& args,
QStringList::const_iterator& actualIt,
Node*& actualNode);
bool processArgs(const QStringList& args,
QStringList::const_iterator& actualIt,
Node*& actualNode);
bool processOptions(const QStringList& args,
QStringList::const_iterator& actualIt,
Node* const actualNode);
};
| 2,517
|
C++
|
.h
| 64
| 30.578125
| 72
| 0.657096
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,872
|
commandargument.h
|
flameshot-org_flameshot/src/cli/commandargument.h
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#pragma once
#include <QString>
class CommandArgument
{
public:
CommandArgument();
explicit CommandArgument(QString name, QString description);
void setName(const QString& name);
QString name() const;
void setDescription(const QString& description);
QString description() const;
bool isRoot() const;
bool operator==(const CommandArgument& arg) const;
private:
QString m_name;
QString m_description;
};
| 568
|
C++
|
.h
| 19
| 26.368421
| 72
| 0.756007
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,873
|
setshortcutwidget.h
|
flameshot-org_flameshot/src/config/setshortcutwidget.h
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2020 Yurii Puchkov at Namecheap & Contributors
#ifndef SETSHORTCUTWIDGET_H
#define SETSHORTCUTWIDGET_H
#include <QDialog>
#include <QKeySequence>
#include <QObject>
class QVBoxLayout;
class SetShortcutDialog : public QDialog
{
Q_OBJECT
public:
explicit SetShortcutDialog(QDialog* parent = nullptr,
const QString& shortcutName = "");
const QKeySequence& shortcut();
public:
void keyPressEvent(QKeyEvent*);
void keyReleaseEvent(QKeyEvent* event);
signals:
private:
QVBoxLayout* m_layout;
QString m_modifier;
QKeySequence m_ks;
};
#endif // SETSHORTCUTWIDGET_H
| 701
|
C++
|
.h
| 25
| 24.2
| 73
| 0.744012
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,874
|
shortcutswidget.h
|
flameshot-org_flameshot/src/config/shortcutswidget.h
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2020 Yurii Puchkov at Namecheap & Contributors
#ifndef HOTKEYSCONFIG_H
#define HOTKEYSCONFIG_H
#include "src/utils/confighandler.h"
#include <QStringList>
#include <QVector>
#include <QWidget>
class SetShortcutDialog;
class QTableWidget;
class QVBoxLayout;
class ShortcutsWidget : public QWidget
{
Q_OBJECT
public:
explicit ShortcutsWidget(QWidget* parent = nullptr);
private:
void initInfoTable();
#if (defined(Q_OS_MAC) || defined(Q_OS_MAC64) || defined(Q_OS_MACOS) || \
defined(Q_OS_MACX))
const QString& nativeOSHotKeyText(const QString& text);
#endif
private slots:
void populateInfoTable();
void onShortcutCellClicked(int, int);
private:
#if (defined(Q_OS_MAC) || defined(Q_OS_MAC64) || defined(Q_OS_MACOS) || \
defined(Q_OS_MACX))
QString m_res;
#endif
ConfigHandler m_config;
QTableWidget* m_table;
QVBoxLayout* m_layout;
QList<QStringList> m_shortcuts;
void loadShortcuts();
void appendShortcut(const QString& shortcutName,
const QString& description);
};
#endif // HOTKEYSCONFIG_H
| 1,172
|
C++
|
.h
| 39
| 26.615385
| 80
| 0.725089
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,875
|
configresolver.h
|
flameshot-org_flameshot/src/config/configresolver.h
|
#pragma once
#include <QDialog>
class QGridLayout;
class ConfigResolver : public QDialog
{
public:
ConfigResolver(QWidget* parent = nullptr);
QGridLayout* layout();
private:
void populate();
void resetLayout();
};
| 235
|
C++
|
.h
| 12
| 16.833333
| 46
| 0.747706
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,876
|
colorpickereditmode.h
|
flameshot-org_flameshot/src/config/colorpickereditmode.h
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2022 Dearsh Oberoi
#pragma once
#include "src/utils/confighandler.h"
#include "src/widgets/colorpickerwidget.h"
class ColorPickerEditMode : public ColorPickerWidget
{
Q_OBJECT
public:
explicit ColorPickerEditMode(QWidget* parent = nullptr);
signals:
void colorSelected(int index);
void presetsSwapped(int index);
private:
bool eventFilter(QObject* obj, QEvent* event) override;
bool m_isPressing = false;
bool m_isDragging = false;
QPoint m_mouseMovePos;
QPoint m_mousePressPos;
QPoint m_draggedPresetInitialPos;
ConfigHandler m_config;
};
| 662
|
C++
|
.h
| 22
| 26.818182
| 60
| 0.771293
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,877
|
configwindow.h
|
flameshot-org_flameshot/src/config/configwindow.h
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#pragma once
#include <QTabWidget>
class FileNameEditor;
class ShortcutsWidget;
class GeneralConf;
class QFileSystemWatcher;
class VisualsEditor;
class QWidget;
class ConfigWindow : public QWidget
{
Q_OBJECT
public:
explicit ConfigWindow(QWidget* parent = nullptr);
signals:
void updateChildren();
protected:
void keyPressEvent(QKeyEvent*);
private:
QTabWidget* m_tabWidget;
FileNameEditor* m_filenameEditor;
QWidget* m_filenameEditorTab;
ShortcutsWidget* m_shortcuts;
QWidget* m_shortcutsTab;
GeneralConf* m_generalConfig;
QWidget* m_generalConfigTab;
VisualsEditor* m_visuals;
QWidget* m_visualsTab;
void initErrorIndicator(QWidget* tab, QWidget* widget);
};
| 847
|
C++
|
.h
| 31
| 24.129032
| 72
| 0.782338
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,879
|
generalconf.h
|
flameshot-org_flameshot/src/config/generalconf.h
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#pragma once
#include <QScrollArea>
#include <QWidget>
class QVBoxLayout;
class QCheckBox;
class QPushButton;
class QLabel;
class QLineEdit;
class QSpinBox;
class QComboBox;
class GeneralConf : public QWidget
{
Q_OBJECT
public:
explicit GeneralConf(QWidget* parent = nullptr);
enum xywh_position
{
xywh_none = 0,
xywh_top_left = 1,
xywh_bottom_left = 2,
xywh_top_right = 3,
xywh_bottom_right = 4,
xywh_center = 5
};
public slots:
void updateComponents();
private slots:
void showHelpChanged(bool checked);
void saveLastRegion(bool checked);
void showSidePanelButtonChanged(bool checked);
void showDesktopNotificationChanged(bool checked);
#if !defined(DISABLE_UPDATE_CHECKER)
void checkForUpdatesChanged(bool checked);
#endif
void allowMultipleGuiInstancesChanged(bool checked);
void autoCloseIdleDaemonChanged(bool checked);
void autostartChanged(bool checked);
void historyConfirmationToDelete(bool checked);
void uploadHistoryMaxChanged(int max);
void undoLimit(int limit);
void saveAfterCopyChanged(bool checked);
void changeSavePath();
void importConfiguration();
void exportFileConfiguration();
void resetConfiguration();
void togglePathFixed();
void uploadClientKeyEdited();
void useJpgForClipboardChanged(bool checked);
void setSaveAsFileExtension(const QString& extension);
void setGeometryLocation(int index);
void setSelGeoHideTime(int v);
void setJpegQuality(int v);
private:
const QString chooseFolder(const QString& currentPath = "");
void initAllowMultipleGuiInstances();
void initAntialiasingPinZoom();
void initAutoCloseIdleDaemon();
void initAutostart();
#if !defined(DISABLE_UPDATE_CHECKER)
void initCheckForUpdates();
#endif
void initConfigButtons();
void initCopyAndCloseAfterUpload();
void initCopyOnDoubleClick();
void initCopyPathAfterSave();
void initHistoryConfirmationToDelete();
void initPredefinedColorPaletteLarge();
void initSaveAfterCopy();
void initScrollArea();
void initShowDesktopNotification();
void initShowHelp();
void initShowMagnifier();
void initShowSidePanelButton();
void initShowStartupLaunchMessage();
void initShowTrayIcon();
void initSquareMagnifier();
void initUndoLimit();
void initUploadWithoutConfirmation();
void initUseJpgForClipboard();
void initUploadHistoryMax();
void initUploadClientSecret();
void initSaveLastRegion();
void initShowSelectionGeometry();
void initJpegQuality();
void _updateComponents(bool allowEmptySavePath);
// class members
QVBoxLayout* m_layout;
QVBoxLayout* m_scrollAreaLayout;
QScrollArea* m_scrollArea;
QCheckBox* m_sysNotifications;
QCheckBox* m_showTray;
QCheckBox* m_helpMessage;
QCheckBox* m_sidePanelButton;
#if !defined(DISABLE_UPDATE_CHECKER)
QCheckBox* m_checkForUpdates;
#endif
QCheckBox* m_allowMultipleGuiInstances;
QCheckBox* m_autoCloseIdleDaemon;
QCheckBox* m_autostart;
QCheckBox* m_showStartupLaunchMessage;
QCheckBox* m_copyURLAfterUpload;
QCheckBox* m_copyPathAfterSave;
QCheckBox* m_antialiasingPinZoom;
QCheckBox* m_saveLastRegion;
QCheckBox* m_uploadWithoutConfirmation;
QPushButton* m_importButton;
QPushButton* m_exportButton;
QPushButton* m_resetButton;
QCheckBox* m_saveAfterCopy;
QLineEdit* m_savePath;
QLineEdit* m_uploadClientKey;
QPushButton* m_changeSaveButton;
QCheckBox* m_screenshotPathFixedCheck;
QCheckBox* m_historyConfirmationToDelete;
QCheckBox* m_useJpgForClipboard;
QSpinBox* m_uploadHistoryMax;
QSpinBox* m_undoLimit;
QComboBox* m_setSaveAsFileExtension;
QCheckBox* m_predefinedColorPaletteLarge;
QCheckBox* m_showMagnifier;
QCheckBox* m_squareMagnifier;
QCheckBox* m_copyOnDoubleClick;
QCheckBox* m_showSelectionGeometry;
QComboBox* m_selectGeometryLocation;
QSpinBox* m_xywhTimeout;
QSpinBox* m_jpegQuality;
};
| 4,205
|
C++
|
.h
| 129
| 28.108527
| 72
| 0.759961
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,880
|
strftimechooserwidget.h
|
flameshot-org_flameshot/src/config/strftimechooserwidget.h
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#pragma once
#include <QWidget>
class StrftimeChooserWidget : public QWidget
{
Q_OBJECT
public:
explicit StrftimeChooserWidget(QWidget* parent = nullptr);
signals:
void variableEmitted(const QString&);
private:
static QMap<QString, QString> m_buttonData;
};
| 397
|
C++
|
.h
| 14
| 25.857143
| 72
| 0.785714
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,881
|
colorpickereditor.h
|
flameshot-org_flameshot/src/config/colorpickereditor.h
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2022 Dearsh Oberoi
#pragma once
#include "QtColorWidgets/color_wheel.hpp"
#include "src/utils/confighandler.h"
#include <QWidget>
class ColorPickerEditMode;
class QLabel;
class QPushButton;
class QLineEdit;
class QColor;
class QGridLayout;
class ColorPickerEditor : public QWidget
{
Q_OBJECT
public:
explicit ColorPickerEditor(QWidget* parent = nullptr);
private slots:
void onAddPreset();
void onDeletePreset();
void onUpdatePreset();
private:
void addPreset();
void deletePreset();
void updatePreset();
ColorPickerEditMode* m_colorpicker;
color_widgets::ColorWheel* m_colorWheel;
QLabel* m_colorEditLabel;
QLineEdit* m_colorEdit;
QPushButton* m_deletePresetButton;
QPushButton* m_updatePresetButton;
QLineEdit* m_colorInput;
QLabel* m_addPresetLabel;
QPushButton* m_addPresetButton;
QColor m_color;
int m_selectedIndex;
QVector<QColor> m_colorList;
ConfigHandler m_config;
QGridLayout* m_gLayout;
};
| 1,074
|
C++
|
.h
| 40
| 23.35
| 58
| 0.763209
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,882
|
visualseditor.h
|
flameshot-org_flameshot/src/config/visualseditor.h
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#pragma once
#include <QTabWidget>
#include <QWidget>
class ExtendedSlider;
class QVBoxLayout;
class ButtonListView;
class UIcolorEditor;
class ColorPickerEditor;
class VisualsEditor : public QWidget
{
Q_OBJECT
public:
explicit VisualsEditor(QWidget* parent = nullptr);
public slots:
void updateComponents();
private:
QVBoxLayout* m_layout;
QTabWidget* m_tabWidget;
UIcolorEditor* m_colorEditor;
QWidget* m_colorEditorTab;
ColorPickerEditor* m_colorpickerEditor;
QWidget* m_colorpickerEditorTab;
ButtonListView* m_buttonList;
ExtendedSlider* m_opacitySlider;
void initWidgets();
void initOpacitySlider();
};
| 789
|
C++
|
.h
| 29
| 24.034483
| 72
| 0.783712
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,883
|
cacheutils.h
|
flameshot-org_flameshot/src/config/cacheutils.h
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2021 Jeremy Borgman
#ifndef FLAMESHOT_CACHEUTILS_H
#define FLAMESHOT_CACHEUTILS_H
class QString;
class QRect;
QString getCachePath();
QRect getLastRegion();
void setLastRegion(QRect const& newRegion);
#endif // FLAMESHOT_CACHEUTILS_H
| 310
|
C++
|
.h
| 10
| 29.6
| 46
| 0.820946
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,884
|
styleoverride.h
|
flameshot-org_flameshot/src/config/styleoverride.h
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2020 Jeremy Borgman <borgman.jeremy@pm.me>
//
// Created by jeremy on 9/24/20.
#ifndef FLAMESHOT_STYLEOVERRIDE_H
#define FLAMESHOT_STYLEOVERRIDE_H
#include <QObject>
#include <QProxyStyle>
class StyleOverride : public QProxyStyle
{
Q_OBJECT
public:
int styleHint(StyleHint hint,
const QStyleOption* option = Q_NULLPTR,
const QWidget* widget = Q_NULLPTR,
QStyleHintReturn* returnData = Q_NULLPTR) const;
};
#endif // FLAMESHOT_STYLEOVERRIDE_H
| 580
|
C++
|
.h
| 18
| 27.555556
| 69
| 0.71147
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,885
|
buttonlistview.h
|
flameshot-org_flameshot/src/config/buttonlistview.h
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#pragma once
#include "src/widgets/capture/capturetoolbutton.h"
#include <QListWidget>
class ButtonListView : public QListWidget
{
public:
explicit ButtonListView(QWidget* parent = nullptr);
public slots:
void selectAll();
void updateComponents();
private slots:
void reverseItemCheck(QListWidgetItem*);
protected:
void initButtonList();
private:
QList<CaptureTool::Type> m_listButtons;
QMap<QString, CaptureTool::Type> m_buttonTypeByName;
void updateActiveButtons(QListWidgetItem*);
};
| 645
|
C++
|
.h
| 21
| 27.809524
| 72
| 0.785714
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,886
|
filenameeditor.h
|
flameshot-org_flameshot/src/config/filenameeditor.h
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#pragma once
#include <QPointer>
#include <QWidget>
class QVBoxLayout;
class QLineEdit;
class FileNameHandler;
class QPushButton;
class StrftimeChooserWidget;
class FileNameEditor : public QWidget
{
Q_OBJECT
public:
explicit FileNameEditor(QWidget* parent = nullptr);
private:
QVBoxLayout* m_layout;
QLineEdit* m_outputLabel;
QLineEdit* m_nameEditor;
FileNameHandler* m_nameHandler;
StrftimeChooserWidget* m_helperButtons;
QPushButton* m_saveButton;
QPushButton* m_resetButton;
QPushButton* m_clearButton;
void initLayout();
void initWidgets();
public slots:
void addToNameEditor(const QString& s);
void updateComponents();
private slots:
void savePattern();
void showParsedPattern(const QString&);
void resetName();
};
| 914
|
C++
|
.h
| 34
| 23.647059
| 72
| 0.769495
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,887
|
configerrordetails.h
|
flameshot-org_flameshot/src/config/configerrordetails.h
|
#include <QDialog>
#pragma once
class ConfigErrorDetails : public QDialog
{
public:
ConfigErrorDetails(QWidget* parent = nullptr);
};
| 140
|
C++
|
.h
| 7
| 18.142857
| 50
| 0.793893
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,888
|
uicoloreditor.h
|
flameshot-org_flameshot/src/config/uicoloreditor.h
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#pragma once
#include "QtColorWidgets/color_wheel.hpp"
#include "src/widgets/capture/capturetoolbutton.h"
#include <QGroupBox>
class QVBoxLayout;
class QHBoxLayout;
class CaptureToolButton;
class ClickableLabel;
class UIcolorEditor : public QWidget
{
Q_OBJECT
public:
explicit UIcolorEditor(QWidget* parent = nullptr);
public slots:
void updateComponents();
private slots:
void updateUIcolor();
void updateLocalColor(const QColor);
void changeLastButton(CaptureToolButton*);
private:
QColor m_uiColor, m_contrastColor;
CaptureToolButton* m_buttonMainColor;
ClickableLabel* m_labelMain;
CaptureToolButton* m_buttonContrast;
ClickableLabel* m_labelContrast;
CaptureToolButton* m_lastButtonPressed;
color_widgets::ColorWheel* m_colorWheel;
static const CaptureTool::Type m_buttonIconType = CaptureTool::TYPE_CIRCLE;
QHBoxLayout* m_hLayout;
QVBoxLayout* m_vLayout;
void initColorWheel();
void initButtons();
};
| 1,107
|
C++
|
.h
| 35
| 28.285714
| 79
| 0.784369
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,889
|
extendedslider.h
|
flameshot-org_flameshot/src/config/extendedslider.h
|
// SPDX-License-Identifier: GPL-3.0-or-later
// SPDX-FileCopyrightText: 2017-2019 Alejandro Sirgo Rica & Contributors
#pragma once
#include <QSlider>
#include <QTimer>
class ExtendedSlider : public QSlider
{
Q_OBJECT
public:
explicit ExtendedSlider(QWidget* parent = nullptr);
int mappedValue(int min, int max);
void setMapedValue(int min, int val, int max);
signals:
void modificationsEnded();
private slots:
void updateTooltip();
void fireTimer();
private:
QTimer m_timer;
};
| 517
|
C++
|
.h
| 20
| 22.9
| 72
| 0.74898
|
flameshot-org/flameshot
| 24,603
| 1,577
| 714
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,890
|
CommandLineParser.cpp
|
ethereum_solidity/solc/CommandLineParser.cpp
|
/*
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
#include <solc/CommandLineParser.h>
#include <solc/Exceptions.h>
#include <libyul/optimiser/Suite.h>
#include <liblangutil/EVMVersion.h>
#include <boost/algorithm/string.hpp>
#include <range/v3/view/transform.hpp>
#include <range/v3/view/filter.hpp>
#include <range/v3/range/conversion.hpp>
#include <fmt/format.h>
using namespace solidity::langutil;
using namespace solidity::yul;
namespace po = boost::program_options;
namespace solidity::frontend
{
static std::string const g_strAllowPaths = "allow-paths";
static std::string const g_strBasePath = "base-path";
static std::string const g_strIncludePath = "include-path";
static std::string const g_strAssemble = "assemble";
static std::string const g_strCombinedJson = "combined-json";
static std::string const g_strEVM = "evm";
static std::string const g_strEVMVersion = "evm-version";
static std::string const g_strEOFVersion = "experimental-eof-version";
static std::string const g_strViaIR = "via-ir";
static std::string const g_strExperimentalViaIR = "experimental-via-ir";
static std::string const g_strGas = "gas";
static std::string const g_strHelp = "help";
static std::string const g_strImportAst = "import-ast";
static std::string const g_strImportEvmAssemblerJson = "import-asm-json";
static std::string const g_strInputFile = "input-file";
static std::string const g_strYul = "yul";
static std::string const g_strYulDialect = "yul-dialect";
static std::string const g_strDebugInfo = "debug-info";
static std::string const g_strIPFS = "ipfs";
static std::string const g_strLicense = "license";
static std::string const g_strLibraries = "libraries";
static std::string const g_strLink = "link";
static std::string const g_strLSP = "lsp";
static std::string const g_strMachine = "machine";
static std::string const g_strNoCBORMetadata = "no-cbor-metadata";
static std::string const g_strMetadataHash = "metadata-hash";
static std::string const g_strMetadataLiteral = "metadata-literal";
static std::string const g_strModelCheckerContracts = "model-checker-contracts";
static std::string const g_strModelCheckerDivModNoSlacks = "model-checker-div-mod-no-slacks";
static std::string const g_strModelCheckerEngine = "model-checker-engine";
static std::string const g_strModelCheckerExtCalls = "model-checker-ext-calls";
static std::string const g_strModelCheckerInvariants = "model-checker-invariants";
static std::string const g_strModelCheckerPrintQuery = "model-checker-print-query";
static std::string const g_strModelCheckerShowProvedSafe = "model-checker-show-proved-safe";
static std::string const g_strModelCheckerShowUnproved = "model-checker-show-unproved";
static std::string const g_strModelCheckerShowUnsupported = "model-checker-show-unsupported";
static std::string const g_strModelCheckerSolvers = "model-checker-solvers";
static std::string const g_strModelCheckerTargets = "model-checker-targets";
static std::string const g_strModelCheckerTimeout = "model-checker-timeout";
static std::string const g_strModelCheckerBMCLoopIterations = "model-checker-bmc-loop-iterations";
static std::string const g_strNone = "none";
static std::string const g_strNoOptimizeYul = "no-optimize-yul";
static std::string const g_strNoImportCallback = "no-import-callback";
static std::string const g_strOptimize = "optimize";
static std::string const g_strOptimizeRuns = "optimize-runs";
static std::string const g_strOptimizeYul = "optimize-yul";
static std::string const g_strYulOptimizations = "yul-optimizations";
static std::string const g_strOutputDir = "output-dir";
static std::string const g_strOverwrite = "overwrite";
static std::string const g_strRevertStrings = "revert-strings";
static std::string const g_strStopAfter = "stop-after";
static std::string const g_strParsing = "parsing";
/// Possible arguments to for --revert-strings
static std::set<std::string> const g_revertStringsArgs
{
revertStringsToString(RevertStrings::Default),
revertStringsToString(RevertStrings::Strip),
revertStringsToString(RevertStrings::Debug),
revertStringsToString(RevertStrings::VerboseDebug)
};
static std::string const g_strSources = "sources";
static std::string const g_strSourceList = "sourceList";
static std::string const g_strStandardJSON = "standard-json";
static std::string const g_strStrictAssembly = "strict-assembly";
static std::string const g_strSwarm = "swarm";
static std::string const g_strPrettyJson = "pretty-json";
static std::string const g_strJsonIndent = "json-indent";
static std::string const g_strVersion = "version";
static std::string const g_strIgnoreMissingFiles = "ignore-missing";
static std::string const g_strColor = "color";
static std::string const g_strNoColor = "no-color";
static std::string const g_strErrorIds = "error-codes";
/// Possible arguments to for --machine
static std::set<std::string> const g_machineArgs
{
g_strEVM
};
/// Possible arguments to for --yul-dialect
static std::set<std::string> const g_yulDialectArgs
{
g_strEVM
};
/// Possible arguments to for --metadata-hash
static std::set<std::string> const g_metadataHashArgs
{
g_strIPFS,
g_strSwarm,
g_strNone
};
static std::map<InputMode, std::string> const g_inputModeName = {
{InputMode::Help, "help"},
{InputMode::License, "license"},
{InputMode::Version, "version"},
{InputMode::Compiler, "compiler"},
{InputMode::CompilerWithASTImport, "compiler (AST import)"},
{InputMode::Assembler, "assembler"},
{InputMode::StandardJson, "standard JSON"},
{InputMode::Linker, "linker"},
{InputMode::LanguageServer, "language server (LSP)"},
{InputMode::EVMAssemblerJSON, "EVM assembler (JSON format)"},
};
void CommandLineParser::checkMutuallyExclusive(std::vector<std::string> const& _optionNames)
{
if (countEnabledOptions(_optionNames) > 1)
{
solThrow(
CommandLineValidationError,
"The following options are mutually exclusive: " + joinOptionNames(_optionNames) + ". " +
"Select at most one."
);
}
}
bool CompilerOutputs::operator==(CompilerOutputs const& _other) const noexcept
{
for (bool CompilerOutputs::* member: componentMap() | ranges::views::values)
if (this->*member != _other.*member)
return false;
return true;
}
std::ostream& operator<<(std::ostream& _out, CompilerOutputs const& _selection)
{
std::vector<std::string> serializedSelection;
for (auto&& [componentName, component]: CompilerOutputs::componentMap())
if (_selection.*component)
serializedSelection.push_back(CompilerOutputs::componentName(component));
return _out << util::joinHumanReadable(serializedSelection, ",");
}
std::string const& CompilerOutputs::componentName(bool CompilerOutputs::* _component)
{
solAssert(_component, "");
// NOTE: Linear search is not optimal but it's simpler than getting pointers-to-members to work as map keys.
for (auto const& [componentName, component]: CompilerOutputs::componentMap())
if (component == _component)
return componentName;
solAssert(false, "");
}
bool CombinedJsonRequests::operator==(CombinedJsonRequests const& _other) const noexcept
{
for (bool CombinedJsonRequests::* member: componentMap() | ranges::views::values)
if (this->*member != _other.*member)
return false;
return true;
}
std::ostream& operator<<(std::ostream& _out, CombinedJsonRequests const& _requests)
{
std::vector<std::string> serializedRequests;
for (auto&& [componentName, component]: CombinedJsonRequests::componentMap())
if (_requests.*component)
serializedRequests.push_back(CombinedJsonRequests::componentName(component));
return _out << util::joinHumanReadable(serializedRequests, ",");
}
std::string const& CombinedJsonRequests::componentName(bool CombinedJsonRequests::* _component)
{
solAssert(_component, "");
for (auto const& [componentName, component]: CombinedJsonRequests::componentMap())
if (component == _component)
return componentName;
solAssert(false, "");
}
bool CommandLineOptions::operator==(CommandLineOptions const& _other) const noexcept
{
return
input.paths == _other.input.paths &&
input.remappings == _other.input.remappings &&
input.addStdin == _other.input.addStdin &&
input.basePath == _other.input.basePath &&
input.includePaths == _other.input.includePaths &&
input.allowedDirectories == _other.input.allowedDirectories &&
input.ignoreMissingFiles == _other.input.ignoreMissingFiles &&
input.noImportCallback == _other.input.noImportCallback &&
output.dir == _other.output.dir &&
output.overwriteFiles == _other.output.overwriteFiles &&
output.evmVersion == _other.output.evmVersion &&
output.viaIR == _other.output.viaIR &&
output.revertStrings == _other.output.revertStrings &&
output.debugInfoSelection == _other.output.debugInfoSelection &&
output.stopAfter == _other.output.stopAfter &&
output.eofVersion == _other.output.eofVersion &&
input.mode == _other.input.mode &&
assembly.targetMachine == _other.assembly.targetMachine &&
assembly.inputLanguage == _other.assembly.inputLanguage &&
linker.libraries == _other.linker.libraries &&
formatting.json == _other.formatting.json &&
formatting.coloredOutput == _other.formatting.coloredOutput &&
formatting.withErrorIds == _other.formatting.withErrorIds &&
compiler.outputs == _other.compiler.outputs &&
compiler.estimateGas == _other.compiler.estimateGas &&
compiler.combinedJsonRequests == _other.compiler.combinedJsonRequests &&
metadata.format == _other.metadata.format &&
metadata.hash == _other.metadata.hash &&
metadata.literalSources == _other.metadata.literalSources &&
optimizer.optimizeEvmasm == _other.optimizer.optimizeEvmasm &&
optimizer.optimizeYul == _other.optimizer.optimizeYul &&
optimizer.expectedExecutionsPerDeployment == _other.optimizer.expectedExecutionsPerDeployment &&
optimizer.yulSteps == _other.optimizer.yulSteps &&
modelChecker.initialize == _other.modelChecker.initialize &&
modelChecker.settings == _other.modelChecker.settings;
}
OptimiserSettings CommandLineOptions::optimiserSettings() const
{
OptimiserSettings settings;
if (optimizer.optimizeEvmasm)
settings = OptimiserSettings::standard();
else
settings = OptimiserSettings::minimal();
settings.runYulOptimiser = optimizer.optimizeYul;
if (optimizer.optimizeYul)
// NOTE: Standard JSON disables optimizeStackAllocation by default when yul optimizer is disabled.
// --optimize --no-optimize-yul on the CLI does not have that effect.
settings.optimizeStackAllocation = true;
if (optimizer.expectedExecutionsPerDeployment.has_value())
settings.expectedExecutionsPerDeployment = optimizer.expectedExecutionsPerDeployment.value();
if (optimizer.yulSteps.has_value())
{
std::string const fullSequence = optimizer.yulSteps.value();
auto const delimiterPos = fullSequence.find(":");
settings.yulOptimiserSteps = fullSequence.substr(0, delimiterPos);
if (delimiterPos != std::string::npos)
settings.yulOptimiserCleanupSteps = fullSequence.substr(delimiterPos + 1);
else
solAssert(settings.yulOptimiserCleanupSteps == OptimiserSettings::DefaultYulOptimiserCleanupSteps);
}
return settings;
}
void CommandLineParser::parse(int _argc, char const* const* _argv)
{
parseArgs(_argc, _argv);
processArgs();
}
void CommandLineParser::parseInputPathsAndRemappings()
{
m_options.input.ignoreMissingFiles = (m_args.count(g_strIgnoreMissingFiles) > 0);
if (m_args.count(g_strInputFile))
for (std::string const& positionalArg: m_args[g_strInputFile].as<std::vector<std::string>>())
{
if (ImportRemapper::isRemapping(positionalArg))
{
std::optional<ImportRemapper::Remapping> remapping = ImportRemapper::parseRemapping(positionalArg);
if (!remapping.has_value())
solThrow(CommandLineValidationError, "Invalid remapping: \"" + positionalArg + "\".");
if (m_options.input.mode == InputMode::StandardJson)
solThrow(
CommandLineValidationError,
"Import remappings are not accepted on the command line in Standard JSON mode.\n"
"Please put them under 'settings.remappings' in the JSON input."
);
if (!remapping->target.empty())
{
// If the target is a directory, whitelist it. Otherwise whitelist containing dir.
// NOTE: /a/b/c/ is a directory while /a/b/c is not.
boost::filesystem::path remappingDir = remapping->target;
if (remappingDir.filename() != "..")
// As an exception we'll treat /a/b/c/.. as a directory too. It would be
// unintuitive to whitelist /a/b/c when the target is equivalent to /a/b/.
remappingDir.remove_filename();
m_options.input.allowedDirectories.insert(remappingDir.empty() ? "." : remappingDir);
}
m_options.input.remappings.emplace_back(std::move(remapping.value()));
}
else if (positionalArg == "-")
m_options.input.addStdin = true;
else
m_options.input.paths.insert(positionalArg);
}
if (m_options.input.mode == InputMode::StandardJson)
{
if (m_options.input.paths.size() > 1 || (m_options.input.paths.size() == 1 && m_options.input.addStdin))
solThrow(
CommandLineValidationError,
"Too many input files for --" + g_strStandardJSON + ".\n"
"Please either specify a single file name or provide its content on standard input."
);
else if (m_options.input.paths.size() == 0)
// Standard JSON mode input used to be handled separately and zero files meant "read from stdin".
// Keep it working that way for backwards-compatibility.
m_options.input.addStdin = true;
}
else if (m_options.input.paths.size() == 0 && !m_options.input.addStdin)
solThrow(
CommandLineValidationError,
"No input files given. If you wish to use the standard input please specify \"-\" explicitly."
);
}
void CommandLineParser::parseLibraryOption(std::string const& _input)
{
namespace fs = boost::filesystem;
std::string data = _input;
try
{
if (fs::is_regular_file(_input))
data = util::readFileAsString(_input);
}
catch (fs::filesystem_error const&)
{
// Thrown e.g. if path is too long.
}
catch (util::FileNotFound const&)
{
// Should not happen if `fs::is_regular_file` is correct.
}
catch (util::NotAFile const&)
{
// Should not happen if `fs::is_regular_file` is correct.
}
std::vector<std::string> libraries;
boost::split(libraries, data, boost::is_space() || boost::is_any_of(","), boost::token_compress_on);
for (std::string const& lib: libraries)
if (!lib.empty())
{
//search for equal sign or last colon in string as our binaries output placeholders in the form of file=Name or file:Name
//so we need to search for `=` or `:` in the string
auto separator = lib.rfind('=');
bool isSeparatorEqualSign = true;
if (separator == std::string::npos)
{
separator = lib.rfind(':');
if (separator == std::string::npos)
solThrow(
CommandLineValidationError,
"Equal sign separator missing in library address specifier \"" + lib + "\""
);
else
isSeparatorEqualSign = false; // separator is colon
}
else
if (lib.rfind('=') != lib.find('='))
solThrow(
CommandLineValidationError,
"Only one equal sign \"=\" is allowed in the address string \"" + lib + "\"."
);
std::string libName(lib.begin(), lib.begin() + static_cast<ptrdiff_t>(separator));
boost::trim(libName);
if (m_options.linker.libraries.count(libName))
solThrow(
CommandLineValidationError,
"Address specified more than once for library \"" + libName + "\"."
);
std::string addrString(lib.begin() + static_cast<ptrdiff_t>(separator) + 1, lib.end());
boost::trim(addrString);
if (addrString.empty())
solThrow(
CommandLineValidationError,
"Empty address provided for library \"" + libName + "\".\n"
"Note that there should not be any whitespace after the " +
(isSeparatorEqualSign ? "equal sign" : "colon") + "."
);
if (addrString.substr(0, 2) == "0x")
addrString = addrString.substr(2);
else
solThrow(
CommandLineValidationError,
"The address " + addrString + " is not prefixed with \"0x\".\n"
"Note that the address must be prefixed with \"0x\"."
);
if (addrString.length() != 40)
solThrow(
CommandLineValidationError,
"Invalid length for address for library \"" + libName + "\": " +
std::to_string(addrString.length()) + " instead of 40 characters."
);
if (!util::passesAddressChecksum(addrString, false))
solThrow(
CommandLineValidationError,
"Invalid checksum on address for library \"" + libName + "\": " + addrString + "\n"
"The correct checksum is " + util::getChecksummedAddress(addrString)
);
bytes binAddr = util::fromHex(addrString);
util::h160 address(binAddr, util::h160::AlignRight);
if (binAddr.size() > 20 || address == util::h160())
solThrow(
CommandLineValidationError,
"Invalid address for library \"" + libName + "\": " + addrString
);
m_options.linker.libraries[libName] = address;
}
}
void CommandLineParser::parseOutputSelection()
{
static auto outputSupported = [](InputMode _mode, std::string_view _outputName)
{
static std::set<std::string> const compilerModeOutputs = (
CompilerOutputs::componentMap() |
ranges::views::keys |
ranges::to<std::set>()
);
static std::set<std::string> const assemblerModeOutputs = {
CompilerOutputs::componentName(&CompilerOutputs::asm_),
CompilerOutputs::componentName(&CompilerOutputs::binary),
CompilerOutputs::componentName(&CompilerOutputs::irOptimized),
CompilerOutputs::componentName(&CompilerOutputs::astCompactJson),
CompilerOutputs::componentName(&CompilerOutputs::asmJson),
CompilerOutputs::componentName(&CompilerOutputs::yulCFGJson),
};
static std::set<std::string> const evmAssemblyJsonImportModeOutputs = {
CompilerOutputs::componentName(&CompilerOutputs::asm_),
CompilerOutputs::componentName(&CompilerOutputs::binary),
CompilerOutputs::componentName(&CompilerOutputs::binaryRuntime),
CompilerOutputs::componentName(&CompilerOutputs::opcodes),
CompilerOutputs::componentName(&CompilerOutputs::asmJson),
};
switch (_mode)
{
case InputMode::Help:
case InputMode::License:
case InputMode::Version:
case InputMode::LanguageServer:
solAssert(false);
case InputMode::Compiler:
case InputMode::CompilerWithASTImport:
return util::contains(compilerModeOutputs, _outputName);
case InputMode::EVMAssemblerJSON:
return util::contains(evmAssemblyJsonImportModeOutputs, _outputName);
case InputMode::Assembler:
return util::contains(assemblerModeOutputs, _outputName);
case InputMode::StandardJson:
case InputMode::Linker:
return false;
}
solAssert(false, "");
};
for (auto&& [optionName, outputComponent]: CompilerOutputs::componentMap())
m_options.compiler.outputs.*outputComponent = (m_args.count(optionName) > 0);
if (m_options.input.mode == InputMode::Assembler && m_options.compiler.outputs == CompilerOutputs{})
{
// In assembly mode keep the default outputs enabled for backwards-compatibility.
// TODO: Remove this (must be done in a breaking release).
m_options.compiler.outputs.asm_ = true;
m_options.compiler.outputs.binary = true;
m_options.compiler.outputs.irOptimized = true;
}
std::vector<std::string> unsupportedOutputs;
for (auto&& [optionName, outputComponent]: CompilerOutputs::componentMap())
if (m_options.compiler.outputs.*outputComponent && !outputSupported(m_options.input.mode, optionName))
unsupportedOutputs.push_back(optionName);
if (!unsupportedOutputs.empty())
solThrow(
CommandLineValidationError,
"The following outputs are not supported in " + g_inputModeName.at(m_options.input.mode) + " mode: " +
joinOptionNames(unsupportedOutputs) + "."
);
// TODO: restrict EOF version to correct EVM version.
}
po::options_description CommandLineParser::optionsDescription(bool _forHelp)
{
// Declare the supported options.
po::options_description desc((R"(solc, the Solidity commandline compiler.
This program comes with ABSOLUTELY NO WARRANTY. This is free software, and you
are welcome to redistribute it under certain conditions. See 'solc --)" + g_strLicense + R"('
for details.
Usage: solc [options] [input_file...]
Compiles the given Solidity input files (or the standard input if "-" is
used as a file name) and outputs the components specified in the options
at standard output or in files in the output directory, if specified.
Imports are automatically read from the filesystem, but it is also possible to
remap paths using the context:prefix=path syntax.
Example:
solc --)" + CompilerOutputs::componentName(&CompilerOutputs::binary) + R"( -o /tmp/solcoutput dapp-bin=/usr/local/lib/dapp-bin contract.sol
General Information)").c_str(),
po::options_description::m_default_line_length,
po::options_description::m_default_line_length - 23
);
desc.add_options()
(g_strHelp.c_str(), "Show help message and exit.")
(g_strVersion.c_str(), "Show version and exit.")
(g_strLicense.c_str(), "Show licensing information and exit.")
;
po::options_description inputOptions("Input Options");
inputOptions.add_options()
(
g_strBasePath.c_str(),
po::value<std::string>()->value_name("path"),
"Use the given path as the root of the source tree instead of the root of the filesystem."
)
(
g_strIncludePath.c_str(),
po::value<std::vector<std::string>>()->value_name("path"),
"Make an additional source directory available to the default import callback. "
"Use this option if you want to import contracts whose location is not fixed in relation "
"to your main source tree, e.g. third-party libraries installed using a package manager. "
"Can be used multiple times. "
"Can only be used if base path has a non-empty value."
)
(
g_strAllowPaths.c_str(),
po::value<std::string>()->value_name("path(s)"),
"Allow a given path for imports. A list of paths can be supplied by separating them with a comma."
)
(
g_strIgnoreMissingFiles.c_str(),
"Ignore missing files."
)
(
g_strNoImportCallback.c_str(),
"Disable the default import callback to prevent the compiler from loading any source "
"files not listed on the command line or given in the Standard JSON input."
)
;
desc.add(inputOptions);
auto const annotateEVMVersion = [](EVMVersion const& _version) {
return _version.name() + (_version.isExperimental() ? " (experimental)" : "");
};
std::vector<EVMVersion> allEVMVersions = EVMVersion::allVersions();
std::string annotatedEVMVersions = util::joinHumanReadable(
allEVMVersions | ranges::views::transform(annotateEVMVersion),
", ",
" or "
);
po::options_description outputOptions("Output Options");
outputOptions.add_options()
(
(g_strOutputDir + ",o").c_str(),
po::value<std::string>()->value_name("path"),
"If given, creates one file per output component and contract/file at the specified directory."
)
(
g_strOverwrite.c_str(),
"Overwrite existing files (used together with -o)."
)
(
g_strEVMVersion.c_str(),
po::value<std::string>()->value_name("version")->default_value(EVMVersion{}.name()),
("Select desired EVM version: " + annotatedEVMVersions + ".").c_str()
)
;
if (!_forHelp) // Note: We intentionally keep this undocumented for now.
outputOptions.add_options()
(
g_strEOFVersion.c_str(),
// Declared as uint64_t, since uint8_t will be parsed as character by boost.
po::value<uint64_t>()->value_name("version")->implicit_value(1),
"Select desired EOF version. Currently the only valid value is 1. "
"If not specified, legacy non-EOF bytecode will be generated."
)
(
g_strYul.c_str(), "The typed Yul dialect is no longer supported. For regular Yul compilation use --strict-assembly instead."
)
;
outputOptions.add_options()
(
g_strExperimentalViaIR.c_str(),
"Deprecated synonym of --via-ir."
)
(
g_strViaIR.c_str(),
"Turn on compilation mode via the IR."
)
(
g_strRevertStrings.c_str(),
po::value<std::string>()->value_name(util::joinHumanReadable(g_revertStringsArgs, ",")),
"Strip revert (and require) reason strings or add additional debugging information."
)
(
g_strDebugInfo.c_str(),
po::value<std::string>()->default_value(util::toString(DebugInfoSelection::Default())),
("Debug info components to be included in the produced EVM assembly and Yul code. "
"Value can be all, none or a comma-separated list containing one or more of the "
"following components: " + util::joinHumanReadable(DebugInfoSelection::componentMap() | ranges::views::keys) + ".").c_str()
)
(
g_strStopAfter.c_str(),
po::value<std::string>()->value_name("stage"),
"Stop execution after the given compiler stage. Valid options: \"parsing\"."
)
;
desc.add(outputOptions);
po::options_description alternativeInputModes("Alternative Input Modes");
alternativeInputModes.add_options()
(
g_strStandardJSON.c_str(),
"Switch to Standard JSON input / output mode, ignoring all options. "
"It reads from standard input, if no input file was given, otherwise it reads from the provided input file. The result will be written to standard output."
)
(
g_strLink.c_str(),
("Switch to linker mode, ignoring all options apart from --" + g_strLibraries + " "
"and modify binaries in place.").c_str()
)
(
g_strAssemble.c_str(),
"Switch to assembly mode and assume input is assembly."
)
(
g_strStrictAssembly.c_str(),
"Switch to strict assembly mode and assume input is strict assembly."
)
(
g_strImportAst.c_str(),
("Import ASTs to be compiled, assumes input holds the AST in compact JSON format. "
"Supported Inputs is the output of the --" + g_strStandardJSON + " or the one produced by "
"--" + g_strCombinedJson + " " + CombinedJsonRequests::componentName(&CombinedJsonRequests::ast)).c_str()
)
(
g_strImportEvmAssemblerJson.c_str(),
"Import EVM assembly from JSON. Assumes input is in the format used by --asm-json."
)
(
g_strLSP.c_str(),
"Switch to language server mode (\"LSP\"). Allows the compiler to be used as an analysis backend "
"for your favourite IDE."
)
;
desc.add(alternativeInputModes);
po::options_description assemblyModeOptions("Assembly Mode Options");
assemblyModeOptions.add_options()
(
g_strMachine.c_str(),
po::value<std::string>()->value_name(util::joinHumanReadable(g_machineArgs, ",")),
"Target machine in assembly or Yul mode."
)
(
g_strYulDialect.c_str(),
po::value<std::string>()->value_name(util::joinHumanReadable(g_yulDialectArgs, ",")),
"Input dialect to use in assembly or yul mode."
)
;
desc.add(assemblyModeOptions);
po::options_description linkerModeOptions("Linker Mode Options");
linkerModeOptions.add_options()
(
g_strLibraries.c_str(),
po::value<std::vector<std::string>>()->value_name("libs"),
"Direct string or file containing library addresses. Syntax: "
"<libraryName>=<address> [, or whitespace] ...\n"
"Address is interpreted as a hex string prefixed by 0x."
)
;
desc.add(linkerModeOptions);
po::options_description outputFormatting("Output Formatting");
outputFormatting.add_options()
(
g_strPrettyJson.c_str(),
"Output JSON in pretty format."
)
(
g_strJsonIndent.c_str(),
po::value<uint32_t>()->value_name("N")->default_value(util::JsonFormat::defaultIndent),
"Indent pretty-printed JSON with N spaces. Enables '--pretty-json' automatically."
)
(
g_strColor.c_str(),
"Force colored output."
)
(
g_strNoColor.c_str(),
"Explicitly disable colored output, disabling terminal auto-detection."
)
(
g_strErrorIds.c_str(),
"Output error codes."
)
;
desc.add(outputFormatting);
po::options_description outputComponents("Output Components");
outputComponents.add_options()
(CompilerOutputs::componentName(&CompilerOutputs::astCompactJson).c_str(), "AST of all source files in a compact JSON format.")
(CompilerOutputs::componentName(&CompilerOutputs::asm_).c_str(), "EVM assembly of the contracts.")
(CompilerOutputs::componentName(&CompilerOutputs::asmJson).c_str(), "EVM assembly of the contracts in JSON format.")
(CompilerOutputs::componentName(&CompilerOutputs::opcodes).c_str(), "Opcodes of the contracts.")
(CompilerOutputs::componentName(&CompilerOutputs::binary).c_str(), "Binary of the contracts in hex.")
(CompilerOutputs::componentName(&CompilerOutputs::binaryRuntime).c_str(), "Binary of the runtime part of the contracts in hex.")
(CompilerOutputs::componentName(&CompilerOutputs::abi).c_str(), "ABI specification of the contracts.")
(CompilerOutputs::componentName(&CompilerOutputs::ir).c_str(), "Intermediate Representation (IR) of all contracts.")
(CompilerOutputs::componentName(&CompilerOutputs::irAstJson).c_str(), "AST of Intermediate Representation (IR) of all contracts in a compact JSON format.")
(CompilerOutputs::componentName(&CompilerOutputs::irOptimized).c_str(), "Optimized Intermediate Representation (IR) of all contracts.")
(CompilerOutputs::componentName(&CompilerOutputs::irOptimizedAstJson).c_str(), "AST of optimized Intermediate Representation (IR) of all contracts in a compact JSON format.")
(CompilerOutputs::componentName(&CompilerOutputs::signatureHashes).c_str(), "Function signature hashes of the contracts.")
(CompilerOutputs::componentName(&CompilerOutputs::natspecUser).c_str(), "Natspec user documentation of all contracts.")
(CompilerOutputs::componentName(&CompilerOutputs::natspecDev).c_str(), "Natspec developer documentation of all contracts.")
(CompilerOutputs::componentName(&CompilerOutputs::metadata).c_str(), "Combined Metadata JSON whose IPFS hash is stored on-chain.")
(CompilerOutputs::componentName(&CompilerOutputs::storageLayout).c_str(), "Slots, offsets and types of the contract's state variables located in storage.")
(CompilerOutputs::componentName(&CompilerOutputs::transientStorageLayout).c_str(), "Slots, offsets and types of the contract's state variables located in transient storage.")
;
if (!_forHelp) // Note: We intentionally keep this undocumented for now.
outputComponents.add_options()
(CompilerOutputs::componentName(&CompilerOutputs::yulCFGJson).c_str(), "Control Flow Graph (CFG) of Yul code in JSON format.")
;
desc.add(outputComponents);
po::options_description extraOutput("Extra Output");
extraOutput.add_options()
(
g_strGas.c_str(),
"Print an estimate of the maximal gas usage for each function."
)
(
g_strCombinedJson.c_str(),
po::value<std::string>()->value_name(util::joinHumanReadable(CombinedJsonRequests::componentMap() | ranges::views::keys, ",")),
"Output a single json document containing the specified information."
)
;
desc.add(extraOutput);
po::options_description metadataOptions("Metadata Options");
metadataOptions.add_options()
(
g_strNoCBORMetadata.c_str(),
"Do not append CBOR metadata to the end of the bytecode."
)
(
g_strMetadataHash.c_str(),
po::value<std::string>()->value_name(util::joinHumanReadable(g_metadataHashArgs, ",")),
"Choose hash method for the bytecode metadata or disable it."
)
(
g_strMetadataLiteral.c_str(),
"Store referenced sources as literal data in the metadata output."
)
;
desc.add(metadataOptions);
po::options_description optimizerOptions("Optimizer Options");
optimizerOptions.add_options()
(
g_strOptimize.c_str(),
"Enable optimizer."
)
(
g_strOptimizeRuns.c_str(),
// TODO: The type in OptimiserSettings is size_t but we only accept values up to 2**32-1
// on the CLI and in Standard JSON. We should just switch to uint32_t everywhere.
po::value<unsigned>()->value_name("n")->default_value(static_cast<unsigned>(OptimiserSettings{}.expectedExecutionsPerDeployment)),
"The number of runs specifies roughly how often each opcode of the deployed code will be executed across the lifetime of the contract. "
"Lower values will optimize more for initial deployment cost, higher values will optimize more for high-frequency usage."
)
(
g_strOptimizeYul.c_str(),
("Enable Yul optimizer (independently of the EVM assembly optimizer). "
"The general --" + g_strOptimize + " option automatically enables this unless --" +
g_strNoOptimizeYul + " is specified.").c_str()
)
(
g_strNoOptimizeYul.c_str(),
"Disable Yul optimizer (independently of the EVM assembly optimizer)."
)
(
g_strYulOptimizations.c_str(),
po::value<std::string>()->value_name("steps"),
"Forces Yul optimizer to use the specified sequence of optimization steps instead of the built-in one."
)
;
desc.add(optimizerOptions);
po::options_description smtCheckerOptions("Model Checker Options");
smtCheckerOptions.add_options()
(
g_strModelCheckerContracts.c_str(),
po::value<std::string>()->value_name("default,<source>:<contract>")->default_value("default"),
"Select which contracts should be analyzed using the form <source>:<contract>."
"Multiple pairs <source>:<contract> can be selected at the same time, separated by a comma "
"and no spaces."
)
(
g_strModelCheckerDivModNoSlacks.c_str(),
"Encode division and modulo operations with their precise operators"
" instead of multiplication with slack variables."
)
(
g_strModelCheckerEngine.c_str(),
po::value<std::string>()->value_name("all,bmc,chc,none")->default_value("none"),
"Select model checker engine."
)
(
g_strModelCheckerExtCalls.c_str(),
po::value<std::string>()->value_name("untrusted,trusted")->default_value("untrusted"),
"Select whether to assume (trusted) that external calls always invoke"
" the code given by the type of the contract, if that code is available."
)
(
g_strModelCheckerInvariants.c_str(),
po::value<std::string>()->value_name("default,all,contract,reentrancy")->default_value("default"),
"Select whether to report inferred contract inductive invariants."
" Multiple types of invariants can be selected at the same time, separated by a comma and no spaces."
" By default no invariants are reported."
)
(
g_strModelCheckerPrintQuery.c_str(),
"Print the queries created by the SMTChecker in the SMTLIB2 format."
)
(
g_strModelCheckerShowProvedSafe.c_str(),
"Show all targets that were proved safe separately."
)
(
g_strModelCheckerShowUnproved.c_str(),
"Show all unproved targets separately."
)
(
g_strModelCheckerShowUnsupported.c_str(),
"Show all unsupported language features separately."
)
(
g_strModelCheckerSolvers.c_str(),
po::value<std::string>()->value_name("cvc5,eld,z3,smtlib2")->default_value("z3"),
"Select model checker solvers."
)
(
g_strModelCheckerTargets.c_str(),
po::value<std::string>()->value_name("default,all,constantCondition,underflow,overflow,divByZero,balance,assert,popEmptyArray,outOfBounds")->default_value("default"),
"Select model checker verification targets."
"Multiple targets can be selected at the same time, separated by a comma and no spaces."
" By default all targets except underflow and overflow are selected."
)
(
g_strModelCheckerTimeout.c_str(),
po::value<unsigned>()->value_name("ms"),
"Set model checker timeout per query in milliseconds."
"The default is a deterministic resource limit."
"A timeout of 0 means no resource/time restrictions for any query."
)
(
g_strModelCheckerBMCLoopIterations.c_str(),
po::value<unsigned>(),
"Set loop unrolling depth for BMC engine."
"Default is 1."
)
;
desc.add(smtCheckerOptions);
desc.add_options()(g_strInputFile.c_str(), po::value<std::vector<std::string>>(), "input file");
return desc;
}
po::positional_options_description CommandLineParser::positionalOptionsDescription()
{
// All positional options should be interpreted as input files
po::positional_options_description filesPositions;
filesPositions.add(g_strInputFile.c_str(), -1);
return filesPositions;
}
void CommandLineParser::parseArgs(int _argc, char const* const* _argv)
{
po::options_description allOptions = optionsDescription();
po::positional_options_description filesPositions = positionalOptionsDescription();
m_options = {};
m_args = {};
// parse the compiler arguments
try
{
po::command_line_parser cmdLineParser(_argc, _argv);
cmdLineParser.style(po::command_line_style::default_style & (~po::command_line_style::allow_guessing));
cmdLineParser.options(allOptions).positional(filesPositions);
po::store(cmdLineParser.run(), m_args);
}
catch (po::error const& _exception)
{
solThrow(CommandLineValidationError, _exception.what());
}
po::notify(m_args);
}
void CommandLineParser::processArgs()
{
if (m_args.count(g_strNoColor) > 0)
m_options.formatting.coloredOutput = false;
else if (m_args.count(g_strColor) > 0)
m_options.formatting.coloredOutput = true;
checkMutuallyExclusive({
g_strHelp,
g_strLicense,
g_strVersion,
g_strStandardJSON,
g_strLink,
g_strAssemble,
g_strStrictAssembly,
g_strImportAst,
g_strLSP,
g_strImportEvmAssemblerJson,
});
if (m_args.count(g_strHelp) > 0)
m_options.input.mode = InputMode::Help;
else if (m_args.count(g_strLicense) > 0)
m_options.input.mode = InputMode::License;
else if (m_args.count(g_strVersion) > 0)
m_options.input.mode = InputMode::Version;
else if (m_args.count(g_strStandardJSON) > 0)
m_options.input.mode = InputMode::StandardJson;
else if (m_args.count(g_strLSP))
m_options.input.mode = InputMode::LanguageServer;
else if (m_args.count(g_strAssemble) > 0 || m_args.count(g_strStrictAssembly) > 0)
m_options.input.mode = InputMode::Assembler;
else if (m_args.count(g_strLink) > 0)
m_options.input.mode = InputMode::Linker;
else if (m_args.count(g_strImportAst) > 0)
m_options.input.mode = InputMode::CompilerWithASTImport;
else if (m_args.count(g_strImportEvmAssemblerJson) > 0)
m_options.input.mode = InputMode::EVMAssemblerJSON;
else
m_options.input.mode = InputMode::Compiler;
if (
m_options.input.mode == InputMode::Help ||
m_options.input.mode == InputMode::License ||
m_options.input.mode == InputMode::Version
)
return;
if (m_args.count(g_strYul) > 0)
solThrow(
CommandLineValidationError,
"The typed Yul dialect formerly accessible via --yul is no longer supported, "
"please use --strict-assembly instead."
);
std::map<std::string, std::set<InputMode>> validOptionInputModeCombinations = {
// TODO: This should eventually contain all options.
{g_strExperimentalViaIR, {InputMode::Compiler, InputMode::CompilerWithASTImport}},
{g_strViaIR, {InputMode::Compiler, InputMode::CompilerWithASTImport}},
{g_strMetadataLiteral, {InputMode::Compiler, InputMode::CompilerWithASTImport}},
{g_strNoCBORMetadata, {InputMode::Compiler, InputMode::CompilerWithASTImport}},
{g_strMetadataHash, {InputMode::Compiler, InputMode::CompilerWithASTImport}},
{g_strModelCheckerContracts, {InputMode::Compiler, InputMode::CompilerWithASTImport}},
{g_strModelCheckerDivModNoSlacks, {InputMode::Compiler, InputMode::CompilerWithASTImport}},
{g_strModelCheckerEngine, {InputMode::Compiler, InputMode::CompilerWithASTImport}},
{g_strModelCheckerInvariants, {InputMode::Compiler, InputMode::CompilerWithASTImport}},
{g_strModelCheckerPrintQuery, {InputMode::Compiler, InputMode::CompilerWithASTImport}},
{g_strModelCheckerShowProvedSafe, {InputMode::Compiler, InputMode::CompilerWithASTImport}},
{g_strModelCheckerShowUnproved, {InputMode::Compiler, InputMode::CompilerWithASTImport}},
{g_strModelCheckerShowUnsupported, {InputMode::Compiler, InputMode::CompilerWithASTImport}},
{g_strModelCheckerSolvers, {InputMode::Compiler, InputMode::CompilerWithASTImport}},
{g_strModelCheckerTimeout, {InputMode::Compiler, InputMode::CompilerWithASTImport}},
{g_strModelCheckerBMCLoopIterations, {InputMode::Compiler, InputMode::CompilerWithASTImport}},
{g_strModelCheckerContracts, {InputMode::Compiler, InputMode::CompilerWithASTImport}},
{g_strModelCheckerTargets, {InputMode::Compiler, InputMode::CompilerWithASTImport}}
};
std::vector<std::string> invalidOptionsForCurrentInputMode;
for (auto const& [optionName, inputModes]: validOptionInputModeCombinations)
{
if (
m_args.count(optionName) > 0 &&
inputModes.count(m_options.input.mode) == 0 &&
!m_args[optionName].defaulted()
)
invalidOptionsForCurrentInputMode.push_back(optionName);
}
if (!invalidOptionsForCurrentInputMode.empty())
solThrow(
CommandLineValidationError,
"The following options are not supported in the current input mode: " +
joinOptionNames(invalidOptionsForCurrentInputMode)
);
if (m_options.input.mode == InputMode::LanguageServer)
return;
checkMutuallyExclusive({g_strColor, g_strNoColor});
checkMutuallyExclusive({g_strStopAfter, g_strGas});
for (std::string const& option: CompilerOutputs::componentMap() | ranges::views::keys)
if (option != CompilerOutputs::componentName(&CompilerOutputs::astCompactJson))
checkMutuallyExclusive({g_strStopAfter, option});
if (m_options.input.mode == InputMode::EVMAssemblerJSON)
{
static std::set<std::string> const supportedByEvmAsmJsonImport{
g_strImportEvmAssemblerJson,
CompilerOutputs::componentName(&CompilerOutputs::asm_),
CompilerOutputs::componentName(&CompilerOutputs::binary),
CompilerOutputs::componentName(&CompilerOutputs::binaryRuntime),
CompilerOutputs::componentName(&CompilerOutputs::asmJson),
CompilerOutputs::componentName(&CompilerOutputs::opcodes),
g_strCombinedJson,
g_strInputFile,
g_strJsonIndent,
g_strPrettyJson,
"srcmap",
"srcmap-runtime",
};
for (auto const& [optionName, optionValue]: m_args)
if (!optionValue.defaulted() && !supportedByEvmAsmJsonImport.count(optionName))
solThrow(
CommandLineValidationError,
fmt::format(
"Option --{} is not supported with --{}.",
optionName,
g_strImportEvmAssemblerJson
)
);
}
if (
m_options.input.mode != InputMode::Compiler &&
m_options.input.mode != InputMode::CompilerWithASTImport &&
m_options.input.mode != InputMode::EVMAssemblerJSON &&
m_options.input.mode != InputMode::Assembler
)
{
if (!m_args[g_strOptimizeRuns].defaulted())
solThrow(
CommandLineValidationError,
"Option --" + g_strOptimizeRuns + " is only valid in compiler and assembler modes."
);
for (std::string const& option: {g_strOptimize, g_strNoOptimizeYul, g_strOptimizeYul, g_strYulOptimizations})
if (m_args.count(option) > 0)
solThrow(
CommandLineValidationError,
"Option --" + option + " is only valid in compiler and assembler modes."
);
if (!m_args[g_strDebugInfo].defaulted())
solThrow(
CommandLineValidationError,
"Option --" + g_strDebugInfo + " is only valid in compiler and assembler modes."
);
}
m_options.formatting.withErrorIds = m_args.count(g_strErrorIds);
if (m_args.count(g_strRevertStrings))
{
std::string revertStringsString = m_args[g_strRevertStrings].as<std::string>();
std::optional<RevertStrings> revertStrings = revertStringsFromString(revertStringsString);
if (!revertStrings)
solThrow(
CommandLineValidationError,
"Invalid option for --" + g_strRevertStrings + ": " + revertStringsString
);
if (*revertStrings == RevertStrings::VerboseDebug)
solThrow(
CommandLineValidationError,
"Only \"default\", \"strip\" and \"debug\" are implemented for --" + g_strRevertStrings + " for now."
);
m_options.output.revertStrings = *revertStrings;
}
if (!m_args[g_strDebugInfo].defaulted())
{
std::string optionValue = m_args[g_strDebugInfo].as<std::string>();
m_options.output.debugInfoSelection = DebugInfoSelection::fromString(optionValue);
if (!m_options.output.debugInfoSelection.has_value())
solThrow(CommandLineValidationError, "Invalid value for --" + g_strDebugInfo + " option: " + optionValue);
if (m_options.output.debugInfoSelection->snippet && !m_options.output.debugInfoSelection->location)
solThrow(CommandLineValidationError, "To use 'snippet' with --" + g_strDebugInfo + " you must select also 'location'.");
}
parseCombinedJsonOption();
if (m_args.count(g_strOutputDir))
m_options.output.dir = m_args.at(g_strOutputDir).as<std::string>();
m_options.output.overwriteFiles = (m_args.count(g_strOverwrite) > 0);
if (m_args.count(g_strPrettyJson) > 0)
{
m_options.formatting.json.format = util::JsonFormat::Pretty;
}
if (!m_args[g_strJsonIndent].defaulted())
{
m_options.formatting.json.format = util::JsonFormat::Pretty;
m_options.formatting.json.indent = m_args[g_strJsonIndent].as<uint32_t>();
}
parseOutputSelection();
m_options.compiler.estimateGas = (m_args.count(g_strGas) > 0);
if (m_args.count(g_strBasePath))
m_options.input.basePath = m_args[g_strBasePath].as<std::string>();
if (m_args.count(g_strIncludePath) > 0)
{
if (m_options.input.basePath.empty())
solThrow(CommandLineValidationError, "--" + g_strIncludePath + " option requires a non-empty base path.");
for (std::string const& includePath: m_args[g_strIncludePath].as<std::vector<std::string>>())
{
if (includePath.empty())
solThrow(CommandLineValidationError, "Empty values are not allowed in --" + g_strIncludePath + ".");
m_options.input.includePaths.push_back(includePath);
}
}
checkMutuallyExclusive({g_strNoImportCallback, g_strAllowPaths});
if (m_args.count(g_strNoImportCallback))
m_options.input.noImportCallback = true;
if (m_args.count(g_strAllowPaths))
{
std::vector<std::string> paths;
for (std::string const& allowedPath: boost::split(paths, m_args[g_strAllowPaths].as<std::string>(), boost::is_any_of(",")))
if (!allowedPath.empty())
m_options.input.allowedDirectories.insert(allowedPath);
}
if (m_args.count(g_strStopAfter))
{
if (m_args[g_strStopAfter].as<std::string>() != "parsing")
solThrow(CommandLineValidationError, "Valid options for --" + g_strStopAfter + " are: \"parsing\".\n");
else
m_options.output.stopAfter = CompilerStack::State::Parsed;
}
parseInputPathsAndRemappings();
if (m_options.input.mode == InputMode::StandardJson)
return;
if (m_args.count(g_strLibraries))
for (std::string const& library: m_args[g_strLibraries].as<std::vector<std::string>>())
parseLibraryOption(library);
if (m_options.input.mode == InputMode::Linker)
return;
if (m_args.count(g_strEVMVersion))
{
std::string versionOptionStr = m_args[g_strEVMVersion].as<std::string>();
std::optional<langutil::EVMVersion> versionOption = langutil::EVMVersion::fromString(versionOptionStr);
if (!versionOption)
solThrow(CommandLineValidationError, "Invalid option for --" + g_strEVMVersion + ": " + versionOptionStr);
m_options.output.evmVersion = *versionOption;
}
if (m_args.count(g_strEOFVersion))
{
// Request as uint64_t, since uint8_t will be parsed as character by boost.
uint64_t versionOption = m_args[g_strEOFVersion].as<uint64_t>();
if (versionOption != 1)
solThrow(CommandLineValidationError, "Invalid option for --" + g_strEOFVersion + ": " + std::to_string(versionOption));
m_options.output.eofVersion = 1;
}
if (m_args.count(g_strNoOptimizeYul) > 0 && m_args.count(g_strOptimizeYul) > 0)
solThrow(
CommandLineValidationError,
"Options --" + g_strOptimizeYul + " and --" + g_strNoOptimizeYul + " cannot be used together."
);
m_options.optimizer.optimizeEvmasm = (m_args.count(g_strOptimize) > 0);
m_options.optimizer.optimizeYul = (
(m_args.count(g_strOptimize) > 0 && m_args.count(g_strNoOptimizeYul) == 0) ||
m_args.count(g_strOptimizeYul) > 0
);
if (!m_args[g_strOptimizeRuns].defaulted())
m_options.optimizer.expectedExecutionsPerDeployment = m_args.at(g_strOptimizeRuns).as<unsigned>();
if (m_args.count(g_strYulOptimizations))
{
OptimiserSettings optimiserSettings = m_options.optimiserSettings();
if (
!optimiserSettings.runYulOptimiser &&
!OptimiserSuite::isEmptyOptimizerSequence(m_args[g_strYulOptimizations].as<std::string>())
)
solThrow(
CommandLineValidationError,
"--" + g_strYulOptimizations + " is invalid with a non-empty sequence if Yul optimizer is disabled."
" Note that the empty optimizer sequence is properly denoted by \":\"."
);
try
{
yul::OptimiserSuite::validateSequence(m_args[g_strYulOptimizations].as<std::string>());
}
catch (yul::OptimizerException const& _exception)
{
solThrow(
CommandLineValidationError,
"Invalid optimizer step sequence in --" + g_strYulOptimizations + ": " + _exception.what()
);
}
m_options.optimizer.yulSteps = m_args[g_strYulOptimizations].as<std::string>();
}
if (m_options.input.mode == InputMode::Assembler)
{
std::vector<std::string> const nonAssemblyModeOptions = {
// TODO: The list is not complete. Add more.
g_strOutputDir,
g_strGas,
g_strCombinedJson,
};
if (countEnabledOptions(nonAssemblyModeOptions) >= 1)
{
auto optionEnabled = [&](std::string const& name){ return m_args.count(name) > 0; };
auto enabledOptions = nonAssemblyModeOptions | ranges::views::filter(optionEnabled) | ranges::to_vector;
std::string message = "The following options are invalid in assembly mode: " + joinOptionNames(enabledOptions) + ".";
solThrow(CommandLineValidationError, message);
}
// switch to assembly mode
using Input = yul::YulStack::Language;
using Machine = yul::YulStack::Machine;
m_options.assembly.inputLanguage = m_args.count(g_strStrictAssembly) ? Input::StrictAssembly : Input::Assembly;
if (m_args.count(g_strMachine))
{
std::string machine = m_args[g_strMachine].as<std::string>();
if (machine == g_strEVM)
m_options.assembly.targetMachine = Machine::EVM;
else
solThrow(CommandLineValidationError, "Invalid option for --" + g_strMachine + ": " + machine);
}
if (m_args.count(g_strYulDialect))
{
std::string dialect = m_args[g_strYulDialect].as<std::string>();
if (dialect == g_strEVM)
m_options.assembly.inputLanguage = Input::StrictAssembly;
else
solThrow(CommandLineValidationError, "Invalid option for --" + g_strYulDialect + ": " + dialect);
}
if (
(m_options.optimizer.optimizeEvmasm || m_options.optimizer.optimizeYul) &&
m_options.assembly.inputLanguage != Input::StrictAssembly
)
solThrow(
CommandLineValidationError,
"Optimizer can only be used for strict assembly. Use --" + g_strStrictAssembly + "."
);
return;
}
else if (countEnabledOptions({g_strYulDialect, g_strMachine}) >= 1)
solThrow(
CommandLineValidationError,
"--" + g_strYulDialect + " and --" + g_strMachine + " are only valid in assembly mode."
);
if (m_args.count(g_strMetadataHash))
{
std::string hashStr = m_args[g_strMetadataHash].as<std::string>();
if (hashStr == g_strIPFS)
m_options.metadata.hash = CompilerStack::MetadataHash::IPFS;
else if (hashStr == g_strSwarm)
m_options.metadata.hash = CompilerStack::MetadataHash::Bzzr1;
else if (hashStr == g_strNone)
m_options.metadata.hash = CompilerStack::MetadataHash::None;
else
solThrow(CommandLineValidationError, "Invalid option for --" + g_strMetadataHash + ": " + hashStr);
}
if (m_args.count(g_strNoCBORMetadata))
{
if (
m_args.count(g_strMetadataHash) &&
m_options.metadata.hash != CompilerStack::MetadataHash::None
)
solThrow(
CommandLineValidationError,
"Cannot specify a metadata hashing method when --" +
g_strNoCBORMetadata + " is set."
);
m_options.metadata.format = CompilerStack::MetadataFormat::NoMetadata;
}
if (m_args.count(g_strModelCheckerContracts))
{
std::string contractsStr = m_args[g_strModelCheckerContracts].as<std::string>();
std::optional<ModelCheckerContracts> contracts = ModelCheckerContracts::fromString(contractsStr);
if (!contracts)
solThrow(CommandLineValidationError, "Invalid option for --" + g_strModelCheckerContracts + ": " + contractsStr);
m_options.modelChecker.settings.contracts = std::move(*contracts);
}
if (m_args.count(g_strModelCheckerDivModNoSlacks))
m_options.modelChecker.settings.divModNoSlacks = true;
if (m_args.count(g_strModelCheckerEngine))
{
std::string engineStr = m_args[g_strModelCheckerEngine].as<std::string>();
std::optional<ModelCheckerEngine> engine = ModelCheckerEngine::fromString(engineStr);
if (!engine)
solThrow(CommandLineValidationError, "Invalid option for --" + g_strModelCheckerEngine + ": " + engineStr);
m_options.modelChecker.settings.engine = *engine;
}
if (m_args.count(g_strModelCheckerExtCalls))
{
std::string mode = m_args[g_strModelCheckerExtCalls].as<std::string>();
std::optional<ModelCheckerExtCalls> extCallsMode = ModelCheckerExtCalls::fromString(mode);
if (!extCallsMode)
solThrow(CommandLineValidationError, "Invalid option for --" + g_strModelCheckerExtCalls + ": " + mode);
m_options.modelChecker.settings.externalCalls = *extCallsMode;
}
if (m_args.count(g_strModelCheckerInvariants))
{
std::string invsStr = m_args[g_strModelCheckerInvariants].as<std::string>();
std::optional<ModelCheckerInvariants> invs = ModelCheckerInvariants::fromString(invsStr);
if (!invs)
solThrow(CommandLineValidationError, "Invalid option for --" + g_strModelCheckerInvariants + ": " + invsStr);
m_options.modelChecker.settings.invariants = *invs;
}
if (m_args.count(g_strModelCheckerShowProvedSafe))
m_options.modelChecker.settings.showProvedSafe = true;
if (m_args.count(g_strModelCheckerShowUnproved))
m_options.modelChecker.settings.showUnproved = true;
if (m_args.count(g_strModelCheckerShowUnsupported))
m_options.modelChecker.settings.showUnsupported = true;
if (m_args.count(g_strModelCheckerSolvers))
{
std::string solversStr = m_args[g_strModelCheckerSolvers].as<std::string>();
std::optional<smtutil::SMTSolverChoice> solvers = smtutil::SMTSolverChoice::fromString(solversStr);
if (!solvers)
solThrow(CommandLineValidationError, "Invalid option for --" + g_strModelCheckerSolvers + ": " + solversStr);
m_options.modelChecker.settings.solvers = *solvers;
}
if (m_args.count(g_strModelCheckerPrintQuery))
{
if (!(m_options.modelChecker.settings.solvers == smtutil::SMTSolverChoice::SMTLIB2()))
solThrow(CommandLineValidationError, "Only SMTLib2 solver can be enabled to print queries");
m_options.modelChecker.settings.printQuery = true;
}
if (m_args.count(g_strModelCheckerTargets))
{
std::string targetsStr = m_args[g_strModelCheckerTargets].as<std::string>();
std::optional<ModelCheckerTargets> targets = ModelCheckerTargets::fromString(targetsStr);
if (!targets)
solThrow(CommandLineValidationError, "Invalid option for --" + g_strModelCheckerTargets + ": " + targetsStr);
m_options.modelChecker.settings.targets = *targets;
}
if (m_args.count(g_strModelCheckerTimeout))
m_options.modelChecker.settings.timeout = m_args[g_strModelCheckerTimeout].as<unsigned>();
if (m_args.count(g_strModelCheckerBMCLoopIterations))
{
if (!m_options.modelChecker.settings.engine.bmc)
solThrow(CommandLineValidationError, "BMC loop unrolling requires the BMC engine to be enabled");
m_options.modelChecker.settings.bmcLoopIterations = m_args[g_strModelCheckerBMCLoopIterations].as<unsigned>();
}
m_options.metadata.literalSources = (m_args.count(g_strMetadataLiteral) > 0);
m_options.modelChecker.initialize =
m_args.count(g_strModelCheckerContracts) ||
m_args.count(g_strModelCheckerDivModNoSlacks) ||
m_args.count(g_strModelCheckerEngine) ||
m_args.count(g_strModelCheckerExtCalls) ||
m_args.count(g_strModelCheckerInvariants) ||
m_args.count(g_strModelCheckerShowProvedSafe) ||
m_args.count(g_strModelCheckerShowUnproved) ||
m_args.count(g_strModelCheckerShowUnsupported) ||
m_args.count(g_strModelCheckerSolvers) ||
m_args.count(g_strModelCheckerTargets) ||
m_args.count(g_strModelCheckerTimeout);
m_options.output.viaIR = (m_args.count(g_strExperimentalViaIR) > 0 || m_args.count(g_strViaIR) > 0);
solAssert(
m_options.input.mode == InputMode::Compiler ||
m_options.input.mode == InputMode::CompilerWithASTImport ||
m_options.input.mode == InputMode::EVMAssemblerJSON
);
}
void CommandLineParser::parseCombinedJsonOption()
{
if (!m_args.count(g_strCombinedJson))
return;
std::set<std::string> requests;
for (std::string const& item: boost::split(requests, m_args[g_strCombinedJson].as<std::string>(), boost::is_any_of(",")))
if (CombinedJsonRequests::componentMap().count(item) == 0)
solThrow(CommandLineValidationError, "Invalid option to --" + g_strCombinedJson + ": " + item);
m_options.compiler.combinedJsonRequests = CombinedJsonRequests{};
for (auto&& [componentName, component]: CombinedJsonRequests::componentMap())
m_options.compiler.combinedJsonRequests.value().*component = (requests.count(componentName) > 0);
if (m_options.input.mode == InputMode::EVMAssemblerJSON && m_options.compiler.combinedJsonRequests.has_value())
{
static bool CombinedJsonRequests::* invalidOptions[]{
&CombinedJsonRequests::abi,
&CombinedJsonRequests::ast,
&CombinedJsonRequests::funDebug,
&CombinedJsonRequests::funDebugRuntime,
&CombinedJsonRequests::generatedSources,
&CombinedJsonRequests::generatedSourcesRuntime,
&CombinedJsonRequests::metadata,
&CombinedJsonRequests::natspecDev,
&CombinedJsonRequests::natspecUser,
&CombinedJsonRequests::signatureHashes,
&CombinedJsonRequests::storageLayout,
&CombinedJsonRequests::transientStorageLayout
};
for (auto const invalidOption: invalidOptions)
if (m_options.compiler.combinedJsonRequests.value().*invalidOption)
solThrow(
CommandLineValidationError,
fmt::format(
"The --{} {} output is not available in EVM assembly import mode.",
g_strCombinedJson,
CombinedJsonRequests::componentName(invalidOption)
)
);
}
}
size_t CommandLineParser::countEnabledOptions(std::vector<std::string> const& _optionNames) const
{
size_t count = 0;
for (std::string const& _option: _optionNames)
count += m_args.count(_option);
return count;
}
std::string CommandLineParser::joinOptionNames(std::vector<std::string> const& _optionNames, std::string _separator)
{
return util::joinHumanReadable(
_optionNames | ranges::views::transform([](std::string const& _option){ return "--" + _option; }),
_separator
);
}
} // namespace solidity::frontend
| 58,964
|
C++
|
.cpp
| 1,367
| 40.027067
| 176
| 0.744281
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,891
|
main.cpp
|
ethereum_solidity/solc/main.cpp
|
/*
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
/**
* @author Christian <c@ethdev.com>
* @date 2014
* Solidity commandline compiler.
*/
#include <solc/CommandLineInterface.h>
#include <liblangutil/Exceptions.h>
#include <boost/exception/all.hpp>
#include <iostream>
using namespace solidity;
int main(int argc, char** argv)
{
try
{
solidity::frontend::CommandLineInterface cli(std::cin, std::cout, std::cerr);
return cli.run(argc, argv) ? 0 : 1;
}
catch (smtutil::SMTLogicError const& _exception)
{
std::cerr << "SMT logic error:" << std::endl;
std::cerr << boost::diagnostic_information(_exception);
return 2;
}
catch (langutil::InternalCompilerError const& _exception)
{
std::cerr << "Internal compiler error:" << std::endl;
std::cerr << boost::diagnostic_information(_exception);
return 2;
}
catch (...)
{
std::cerr << "Uncaught exception:" << std::endl;
std::cerr << boost::current_exception_diagnostic_information() << std::endl;
return 2;
}
}
| 1,631
|
C++
|
.cpp
| 50
| 30.44
| 79
| 0.740929
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,892
|
CommandLineInterface.cpp
|
ethereum_solidity/solc/CommandLineInterface.cpp
|
/*
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
/**
* @author Lefteris <lefteris@ethdev.com>
* @author Gav Wood <g@ethdev.com>
* @date 2014
* Solidity command line interface.
*/
#include <solc/CommandLineInterface.h>
#include <solc/Exceptions.h>
#include "license.h"
#include "solidity/BuildInfo.h"
#include <libsolidity/interface/Version.h>
#include <libsolidity/ast/ASTJsonExporter.h>
#include <libsolidity/ast/ASTJsonImporter.h>
#include <libsolidity/analysis/NameAndTypeResolver.h>
#include <libsolidity/interface/CompilerStack.h>
#include <libsolidity/interface/StandardCompiler.h>
#include <libsolidity/interface/GasEstimator.h>
#include <libsolidity/interface/DebugSettings.h>
#include <libsolidity/interface/ImportRemapper.h>
#include <libsolidity/interface/StorageLayout.h>
#include <libsolidity/lsp/LanguageServer.h>
#include <libsolidity/lsp/Transport.h>
#include <libyul/YulStack.h>
#include <libevmasm/Disassemble.h>
#include <liblangutil/Exceptions.h>
#include <liblangutil/SourceReferenceFormatter.h>
#include <libsmtutil/Exceptions.h>
#include <libsolutil/Common.h>
#include <libsolutil/CommonData.h>
#include <libsolutil/CommonIO.h>
#include <libsolutil/JSON.h>
#include <algorithm>
#include <fstream>
#include <memory>
#include <range/v3/view/map.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/algorithm/string.hpp>
#ifdef _WIN32 // windows
#include <io.h>
#define isatty _isatty
#define fileno _fileno
#else // unix
#include <unistd.h>
#endif
#include <fstream>
#if !defined(STDERR_FILENO)
#define STDERR_FILENO 2
#endif
using namespace std::string_literals;
using namespace solidity;
using namespace solidity::util;
using namespace solidity::langutil;
namespace
{
std::set<frontend::InputMode> const CompilerInputModes{
frontend::InputMode::Compiler,
frontend::InputMode::CompilerWithASTImport,
};
} // anonymous namespace
namespace solidity::frontend
{
std::ostream& CommandLineInterface::sout(bool _markAsUsed)
{
if (_markAsUsed)
m_hasOutput = true;
return m_sout;
}
std::ostream& CommandLineInterface::serr(bool _markAsUsed)
{
if (_markAsUsed)
m_hasOutput = true;
return m_serr;
}
#define cin
#define cout
#define cerr
static std::string const g_stdinFileName = "<stdin>";
static std::string const g_strAbi = "abi";
static std::string const g_strAsm = "asm";
static std::string const g_strAst = "ast";
static std::string const g_strBinary = "bin";
static std::string const g_strBinaryRuntime = "bin-runtime";
static std::string const g_strContracts = "contracts";
static std::string const g_strFunDebug = "function-debug";
static std::string const g_strFunDebugRuntime = "function-debug-runtime";
static std::string const g_strGeneratedSources = "generated-sources";
static std::string const g_strGeneratedSourcesRuntime = "generated-sources-runtime";
static std::string const g_strNatspecDev = "devdoc";
static std::string const g_strNatspecUser = "userdoc";
static std::string const g_strOpcodes = "opcodes";
static std::string const g_strSignatureHashes = "hashes";
static std::string const g_strSourceList = "sourceList";
static std::string const g_strSources = "sources";
static std::string const g_strSrcMap = "srcmap";
static std::string const g_strSrcMapRuntime = "srcmap-runtime";
static std::string const g_strStorageLayout = "storage-layout";
static std::string const g_strTransientStorageLayout = "transient-storage-layout";
static std::string const g_strVersion = "version";
static bool needsHumanTargetedStdout(CommandLineOptions const& _options)
{
if (_options.compiler.estimateGas)
return true;
if (!_options.output.dir.empty())
return false;
return
_options.compiler.outputs.abi ||
_options.compiler.outputs.asm_ ||
_options.compiler.outputs.asmJson ||
_options.compiler.outputs.yulCFGJson ||
_options.compiler.outputs.binary ||
_options.compiler.outputs.binaryRuntime ||
_options.compiler.outputs.metadata ||
_options.compiler.outputs.natspecUser ||
_options.compiler.outputs.natspecDev ||
_options.compiler.outputs.opcodes ||
_options.compiler.outputs.signatureHashes ||
_options.compiler.outputs.storageLayout ||
_options.compiler.outputs.transientStorageLayout;
}
static bool coloredOutput(CommandLineOptions const& _options)
{
return
(!_options.formatting.coloredOutput.has_value() && isatty(STDERR_FILENO)) ||
(_options.formatting.coloredOutput.has_value() && _options.formatting.coloredOutput.value());
}
void CommandLineInterface::handleEVMAssembly(std::string const& _contract)
{
solAssert(m_assemblyStack);
solAssert(
CompilerInputModes.count(m_options.input.mode) == 1 ||
m_options.input.mode == frontend::InputMode::EVMAssemblerJSON
);
if (!m_options.compiler.outputs.asm_ && !m_options.compiler.outputs.asmJson)
return;
std::string assembly;
if (m_options.compiler.outputs.asmJson)
assembly = util::jsonPrint(m_assemblyStack->assemblyJSON(_contract), m_options.formatting.json);
else
assembly = m_assemblyStack->assemblyString(_contract, m_fileReader.sourceUnits());
if (!m_options.output.dir.empty())
createFile(
m_compiler->filesystemFriendlyName(_contract) +
(m_options.compiler.outputs.asmJson ? "_evm.json" : ".evm"),
assembly
);
else
sout() << "EVM assembly:" << std::endl << assembly << std::endl;
}
void CommandLineInterface::handleBinary(std::string const& _contract)
{
solAssert(m_assemblyStack);
solAssert(
CompilerInputModes.count(m_options.input.mode) == 1 ||
m_options.input.mode == frontend::InputMode::EVMAssemblerJSON
);
std::string binary;
std::string binaryRuntime;
if (m_options.compiler.outputs.binary)
binary = objectWithLinkRefsHex(m_assemblyStack->object(_contract));
if (m_options.compiler.outputs.binaryRuntime)
binaryRuntime = objectWithLinkRefsHex(m_assemblyStack->runtimeObject(_contract));
if (m_options.compiler.outputs.binary)
{
if (!m_options.output.dir.empty())
createFile(m_assemblyStack->filesystemFriendlyName(_contract) + ".bin", binary);
else
{
sout() << "Binary:" << std::endl;
sout() << binary << std::endl;
}
}
if (m_options.compiler.outputs.binaryRuntime)
{
if (!m_options.output.dir.empty())
createFile(m_assemblyStack->filesystemFriendlyName(_contract) + ".bin-runtime", binaryRuntime);
else
{
sout() << "Binary of the runtime part:" << std::endl;
sout() << binaryRuntime << std::endl;
}
}
}
void CommandLineInterface::handleOpcode(std::string const& _contract)
{
solAssert(m_assemblyStack);
solAssert(
CompilerInputModes.count(m_options.input.mode) == 1 ||
m_options.input.mode == frontend::InputMode::EVMAssemblerJSON
);
std::string opcodes{evmasm::disassemble(m_assemblyStack->object(_contract).bytecode, m_options.output.evmVersion)};
if (!m_options.output.dir.empty())
createFile(m_assemblyStack->filesystemFriendlyName(_contract) + ".opcode", opcodes);
else
{
sout() << "Opcodes:" << std::endl;
sout() << std::uppercase << opcodes;
sout() << std::endl;
}
}
void CommandLineInterface::handleIR(std::string const& _contractName)
{
solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
if (!m_options.compiler.outputs.ir)
return;
std::optional<std::string> const& ir = m_compiler->yulIR(_contractName);
if (!m_options.output.dir.empty())
createFile(m_compiler->filesystemFriendlyName(_contractName) + ".yul", ir.value_or(""));
else
{
sout() << "IR:\n";
sout() << ir.value_or("") << std::endl;
}
}
void CommandLineInterface::handleIRAst(std::string const& _contractName)
{
solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
if (!m_options.compiler.outputs.irAstJson)
return;
std::optional<Json> const& yulIRAst = m_compiler->yulIRAst(_contractName);
if (!m_options.output.dir.empty())
createFile(
m_compiler->filesystemFriendlyName(_contractName) + "_yul_ast.json",
util::jsonPrint(
yulIRAst.value_or(Json{}),
m_options.formatting.json
)
);
else
{
sout() << "IR AST:" << std::endl;
sout() << util::jsonPrint(
yulIRAst.value_or(Json{}),
m_options.formatting.json
) << std::endl;
}
}
void CommandLineInterface::handleYulCFGExport(std::string const& _contractName)
{
solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
if (!m_options.compiler.outputs.yulCFGJson)
return;
std::optional<Json> const& yulCFGJson = m_compiler->yulCFGJson(_contractName);
if (!m_options.output.dir.empty())
createFile(
m_compiler->filesystemFriendlyName(_contractName) + "_yul_cfg.json",
util::jsonPrint(
yulCFGJson.value_or(Json{}),
m_options.formatting.json
)
);
else
{
sout() << "Yul Control Flow Graph:" << std::endl;
sout() << util::jsonPrint(
yulCFGJson.value_or(Json{}),
m_options.formatting.json
) << std::endl;
}
}
void CommandLineInterface::handleIROptimized(std::string const& _contractName)
{
solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
if (!m_options.compiler.outputs.irOptimized)
return;
std::optional<std::string> const& irOptimized = m_compiler->yulIROptimized(_contractName);
if (!m_options.output.dir.empty())
createFile(
m_compiler->filesystemFriendlyName(_contractName) + "_opt.yul",
irOptimized.value_or("")
);
else
{
sout() << "Optimized IR:" << std::endl;
sout() << irOptimized.value_or("") << std::endl;
}
}
void CommandLineInterface::handleIROptimizedAst(std::string const& _contractName)
{
solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
if (!m_options.compiler.outputs.irOptimizedAstJson)
return;
std::optional<Json> const& yulIROptimizedAst = m_compiler->yulIROptimizedAst(_contractName);
if (!m_options.output.dir.empty())
createFile(
m_compiler->filesystemFriendlyName(_contractName) + "_opt_yul_ast.json",
util::jsonPrint(
yulIROptimizedAst.value_or(Json{}),
m_options.formatting.json
)
);
else
{
sout() << "Optimized IR AST:" << std::endl;
sout() << util::jsonPrint(
yulIROptimizedAst.value_or(Json{}),
m_options.formatting.json
) << std::endl;
}
}
void CommandLineInterface::handleBytecode(std::string const& _contract)
{
solAssert(
CompilerInputModes.count(m_options.input.mode) == 1 ||
m_options.input.mode == frontend::InputMode::EVMAssemblerJSON
);
if (m_options.compiler.outputs.opcodes)
handleOpcode(_contract);
if (m_options.compiler.outputs.binary || m_options.compiler.outputs.binaryRuntime)
handleBinary(_contract);
}
void CommandLineInterface::handleSignatureHashes(std::string const& _contract)
{
solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
if (!m_options.compiler.outputs.signatureHashes)
return;
Json interfaceSymbols = m_compiler->interfaceSymbols(_contract);
std::string out = "Function signatures:\n";
for (auto const& [name, value]: interfaceSymbols["methods"].items())
out += value.get<std::string>() + ": " + name + "\n";
if (interfaceSymbols.contains("errors"))
{
out += "\nError signatures:\n";
for (auto const& [name, value]: interfaceSymbols["errors"].items())
out += value.get<std::string>() + ": " + name + "\n";
}
if (interfaceSymbols.contains("events"))
{
out += "\nEvent signatures:\n";
for (auto const& [name, value]: interfaceSymbols["events"].items())
out += value.get<std::string>() + ": " + name + "\n";
}
if (!m_options.output.dir.empty())
createFile(m_compiler->filesystemFriendlyName(_contract) + ".signatures", out);
else
sout() << out;
}
void CommandLineInterface::handleMetadata(std::string const& _contract)
{
solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
if (!m_options.compiler.outputs.metadata)
return;
std::string data = m_compiler->metadata(_contract);
if (!m_options.output.dir.empty())
createFile(m_compiler->filesystemFriendlyName(_contract) + "_meta.json", data);
else
sout() << "Metadata:" << std::endl << data << std::endl;
}
void CommandLineInterface::handleABI(std::string const& _contract)
{
solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
if (!m_options.compiler.outputs.abi)
return;
std::string data = jsonPrint(removeNullMembers(m_compiler->contractABI(_contract)), m_options.formatting.json);
if (!m_options.output.dir.empty())
createFile(m_compiler->filesystemFriendlyName(_contract) + ".abi", data);
else
sout() << "Contract JSON ABI" << std::endl << data << std::endl;
}
void CommandLineInterface::handleStorageLayout(std::string const& _contract)
{
solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
if (!m_options.compiler.outputs.storageLayout)
return;
std::string data = jsonPrint(removeNullMembers(m_compiler->storageLayout(_contract)), m_options.formatting.json);
if (!m_options.output.dir.empty())
createFile(m_compiler->filesystemFriendlyName(_contract) + "_storage.json", data);
else
sout() << "Contract Storage Layout:" << std::endl << data << std::endl;
}
void CommandLineInterface::handleTransientStorageLayout(std::string const& _contract)
{
solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
if (!m_options.compiler.outputs.transientStorageLayout)
return;
std::string data = jsonPrint(removeNullMembers(m_compiler->transientStorageLayout(_contract)), m_options.formatting.json);
if (!m_options.output.dir.empty())
createFile(m_compiler->filesystemFriendlyName(_contract) + "_transient_storage.json", data);
else
sout() << "Contract Transient Storage Layout:" << std::endl << data << std::endl;
}
void CommandLineInterface::handleNatspec(bool _natspecDev, std::string const& _contract)
{
solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
bool enabled = false;
std::string suffix;
std::string title;
if (_natspecDev)
{
enabled = m_options.compiler.outputs.natspecDev;
suffix = ".docdev";
title = "Developer Documentation";
}
else
{
enabled = m_options.compiler.outputs.natspecUser;
suffix = ".docuser";
title = "User Documentation";
}
if (enabled)
{
std::string output = jsonPrint(
removeNullMembers(
_natspecDev ?
m_compiler->natspecDev(_contract) :
m_compiler->natspecUser(_contract)
),
m_options.formatting.json
);
if (!m_options.output.dir.empty())
createFile(m_compiler->filesystemFriendlyName(_contract) + suffix, output);
else
{
sout() << title << std::endl;
sout() << output << std::endl;
}
}
}
void CommandLineInterface::handleGasEstimation(std::string const& _contract)
{
solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
Json estimates = m_compiler->gasEstimates(_contract);
sout() << "Gas estimation:" << std::endl;
if (estimates["creation"].is_object())
{
Json creation = estimates["creation"];
sout() << "construction:" << std::endl;
sout() << " " << creation["executionCost"].get<std::string>();
sout() << " + " << creation["codeDepositCost"].get<std::string>();
sout() << " = " << creation["totalCost"].get<std::string>() << std::endl;
}
if (estimates["external"].is_object())
{
Json externalFunctions = estimates["external"];
sout() << "external:" << std::endl;
for (auto const& [name, value]: externalFunctions.items())
{
if (name.empty())
sout() << " fallback:\t";
else
sout() << " " << name << ":\t";
sout() << value.get<std::string>() << std::endl;
}
}
if (estimates["internal"].is_object())
{
Json internalFunctions = estimates["internal"];
sout() << "internal:" << std::endl;
for (auto const& [name, value]: internalFunctions.items())
{
sout() << " " << name << ":\t";
sout() << value.get<std::string>() << std::endl;
}
}
}
void CommandLineInterface::readInputFiles()
{
solAssert(!m_standardJsonInput.has_value());
if (m_options.input.noImportCallback)
m_universalCallback.resetImportCallback();
static std::set<frontend::InputMode> const noInputFiles{
frontend::InputMode::Help,
frontend::InputMode::License,
frontend::InputMode::Version
};
if (noInputFiles.count(m_options.input.mode) == 1)
return;
m_fileReader.setBasePath(m_options.input.basePath);
if (m_fileReader.basePath() != "")
{
if (!boost::filesystem::exists(m_fileReader.basePath()))
solThrow(CommandLineValidationError, "Base path does not exist: \"" + m_fileReader.basePath().string() + '"');
if (!boost::filesystem::is_directory(m_fileReader.basePath()))
solThrow(CommandLineValidationError, "Base path is not a directory: \"" + m_fileReader.basePath().string() + '"');
}
for (boost::filesystem::path const& includePath: m_options.input.includePaths)
m_fileReader.addIncludePath(includePath);
for (boost::filesystem::path const& allowedDirectory: m_options.input.allowedDirectories)
m_fileReader.allowDirectory(allowedDirectory);
std::map<std::string, std::set<boost::filesystem::path>> collisions =
m_fileReader.detectSourceUnitNameCollisions(m_options.input.paths);
if (!collisions.empty())
{
auto pathToQuotedString = [](boost::filesystem::path const& _path){ return "\"" + _path.string() + "\""; };
std::string message =
"Source unit name collision detected. "
"The specified values of base path and/or include paths would result in multiple "
"input files being assigned the same source unit name:\n";
for (auto const& [sourceUnitName, normalizedInputPaths]: collisions)
{
message += sourceUnitName + " matches: ";
message += util::joinHumanReadable(normalizedInputPaths | ranges::views::transform(pathToQuotedString)) + "\n";
}
solThrow(CommandLineValidationError, message);
}
for (boost::filesystem::path const& infile: m_options.input.paths)
{
if (!boost::filesystem::exists(infile))
{
if (!m_options.input.ignoreMissingFiles)
solThrow(CommandLineValidationError, '"' + infile.string() + "\" is not found.");
else
report(Error::Severity::Info, fmt::format("\"{}\" is not found. Skipping.", infile.string()));
continue;
}
if (!boost::filesystem::is_regular_file(infile))
{
if (!m_options.input.ignoreMissingFiles)
solThrow(CommandLineValidationError, '"' + infile.string() + "\" is not a valid file.");
else
report(Error::Severity::Info, fmt::format("\"{}\" is not a valid file. Skipping.", infile.string()));
continue;
}
// NOTE: we ignore the FileNotFound exception as we manually check above
std::string fileContent = readFileAsString(infile);
if (m_options.input.mode == InputMode::StandardJson)
{
solAssert(!m_standardJsonInput.has_value());
m_standardJsonInput = std::move(fileContent);
}
else
{
m_fileReader.addOrUpdateFile(infile, std::move(fileContent));
m_fileReader.allowDirectory(boost::filesystem::canonical(infile).remove_filename());
}
}
if (m_options.input.addStdin)
{
if (m_options.input.mode == InputMode::StandardJson)
{
solAssert(!m_standardJsonInput.has_value());
m_standardJsonInput = readUntilEnd(m_sin);
}
else
m_fileReader.setStdin(readUntilEnd(m_sin));
}
if (
m_options.input.mode != InputMode::LanguageServer &&
m_fileReader.sourceUnits().empty() &&
!m_standardJsonInput.has_value()
)
solThrow(CommandLineValidationError, "All specified input files either do not exist or are not regular files.");
}
std::map<std::string, Json> CommandLineInterface::parseAstFromInput()
{
solAssert(m_options.input.mode == InputMode::CompilerWithASTImport);
std::map<std::string, Json> sourceJsons;
std::map<std::string, std::string> tmpSources;
for (SourceCode const& sourceCode: m_fileReader.sourceUnits() | ranges::views::values)
{
Json ast;
astAssert(jsonParseStrict(sourceCode, ast), "Input file could not be parsed to JSON");
astAssert(ast.contains("sources"), "Invalid Format for import-JSON: Must have 'sources'-object");
for (auto const& [src, value]: ast["sources"].items())
{
std::string astKey = value.contains("ast") ? "ast" : "AST";
astAssert(ast["sources"][src].contains(astKey), "astkey is not member");
astAssert(ast["sources"][src][astKey]["nodeType"].get<std::string>() == "SourceUnit", "Top-level node should be a 'SourceUnit'");
astAssert(sourceJsons.count(src) == 0, "All sources must have unique names");
sourceJsons.emplace(src, std::move(value[astKey]));
tmpSources[src] = util::jsonCompactPrint(ast);
}
}
m_fileReader.setSourceUnits(tmpSources);
return sourceJsons;
}
void CommandLineInterface::createFile(std::string const& _fileName, std::string const& _data)
{
namespace fs = boost::filesystem;
solAssert(!m_options.output.dir.empty());
// NOTE: create_directories() raises an exception if the path consists solely of '.' or '..'
// (or equivalent such as './././.'). Paths like 'a/b/.' and 'a/b/..' are fine though.
// The simplest workaround is to use an absolute path.
fs::create_directories(fs::absolute(m_options.output.dir));
std::string pathName = (m_options.output.dir / _fileName).string();
if (fs::exists(pathName) && !m_options.output.overwriteFiles)
solThrow(CommandLineOutputError, "Refusing to overwrite existing file \"" + pathName + "\" (use --overwrite to force).");
std::ofstream outFile(pathName);
outFile << _data;
if (!outFile)
solThrow(CommandLineOutputError, "Could not write to file \"" + pathName + "\".");
}
void CommandLineInterface::createJson(std::string const& _fileName, std::string const& _json)
{
createFile(boost::filesystem::path(_fileName).stem().string() + std::string(".json"), _json);
}
bool CommandLineInterface::run(int _argc, char const* const* _argv)
{
try
{
if (!parseArguments(_argc, _argv))
return false;
readInputFiles();
processInput();
return true;
}
catch (CommandLineError const& _exception)
{
m_hasOutput = true;
// There might be no message in the exception itself if the error output is bulky and has
// already been printed to stderr (this happens e.g. for compiler errors).
if (_exception.what() != ""s)
report(Error::Severity::Error, _exception.what());
return false;
}
catch (UnimplementedFeatureError const& _error)
{
solAssert(_error.comment(), "Unimplemented feature errors must include a message for the user");
report(Error::Severity::Error, stringOrDefault(_error.comment(), "Unimplemented feature"));
return false;
}
}
bool CommandLineInterface::parseArguments(int _argc, char const* const* _argv)
{
CommandLineParser parser;
if (isatty(fileno(stdin)) && _argc == 1)
{
// If the terminal is taking input from the user, provide more user-friendly output.
CommandLineParser::printHelp(sout());
// In this case we want to exit with an error but not display any error message.
return false;
}
try
{
parser.parse(_argc, _argv);
}
catch (...)
{
// Even if the overall CLI parsing fails, the --color/--no-color options may have been
// successfully parsed, and if so, should be taken into account when printing errors.
// If no value is present, it's possible that --no-color is still there but parsing failed
// due to other, unrecognized options so play it safe and disable color in that case.
m_options.formatting.coloredOutput = parser.options().formatting.coloredOutput.value_or(false);
throw;
}
m_options = parser.options();
return true;
}
void CommandLineInterface::processInput()
{
if (m_options.output.evmVersion < EVMVersion::constantinople())
report(
Error::Severity::Warning,
"Support for EVM versions older than constantinople is deprecated and will be removed in the future."
);
switch (m_options.input.mode)
{
case InputMode::Help:
CommandLineParser::printHelp(sout());
break;
case InputMode::License:
printLicense();
break;
case InputMode::Version:
printVersion();
break;
case InputMode::StandardJson:
{
solAssert(m_standardJsonInput.has_value());
StandardCompiler compiler(m_universalCallback.callback(), m_options.formatting.json);
sout() << compiler.compile(std::move(m_standardJsonInput.value())) << std::endl;
m_standardJsonInput.reset();
break;
}
case InputMode::LanguageServer:
serveLSP();
break;
case InputMode::Assembler:
assembleYul(m_options.assembly.inputLanguage, m_options.assembly.targetMachine);
break;
case InputMode::Linker:
link();
writeLinkedFiles();
break;
case InputMode::Compiler:
case InputMode::CompilerWithASTImport:
compile();
outputCompilationResults();
break;
case InputMode::EVMAssemblerJSON:
assembleFromEVMAssemblyJSON();
handleCombinedJSON();
handleBytecode(m_assemblyStack->contractNames().front());
handleEVMAssembly(m_assemblyStack->contractNames().front());
break;
}
}
void CommandLineInterface::printVersion()
{
sout() << "solc, the solidity compiler commandline interface" << std::endl;
sout() << "Version: " << solidity::frontend::VersionString << std::endl;
}
void CommandLineInterface::printLicense()
{
sout() << otherLicenses << std::endl;
// This is a static variable generated by cmake from LICENSE.txt
sout() << licenseText << std::endl;
}
void CommandLineInterface::assembleFromEVMAssemblyJSON()
{
solAssert(m_options.input.mode == InputMode::EVMAssemblerJSON);
solAssert(!m_assemblyStack);
solAssert(!m_evmAssemblyStack && !m_compiler);
solAssert(m_fileReader.sourceUnits().size() == 1);
auto&& [sourceUnitName, source] = *m_fileReader.sourceUnits().begin();
auto evmAssemblyStack = std::make_unique<evmasm::EVMAssemblyStack>(m_options.output.evmVersion, m_options.output.eofVersion);
try
{
evmAssemblyStack->parseAndAnalyze(sourceUnitName, source);
}
catch (evmasm::AssemblyImportException const& _exception)
{
solThrow(CommandLineExecutionError, "Assembly Import Error: "s + _exception.what());
}
if (m_options.output.debugInfoSelection.has_value())
evmAssemblyStack->selectDebugInfo(m_options.output.debugInfoSelection.value());
evmAssemblyStack->assemble();
m_evmAssemblyStack = std::move(evmAssemblyStack);
m_assemblyStack = m_evmAssemblyStack.get();
}
void CommandLineInterface::compile()
{
solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
solAssert(!m_assemblyStack);
solAssert(!m_evmAssemblyStack && !m_compiler);
m_compiler = std::make_unique<CompilerStack>(m_universalCallback.callback());
m_assemblyStack = m_compiler.get();
SourceReferenceFormatter formatter(serr(false), *m_compiler, coloredOutput(m_options), m_options.formatting.withErrorIds);
try
{
if (m_options.metadata.literalSources)
m_compiler->useMetadataLiteralSources(true);
m_compiler->setMetadataFormat(m_options.metadata.format);
m_compiler->setMetadataHash(m_options.metadata.hash);
if (m_options.modelChecker.initialize)
m_compiler->setModelCheckerSettings(m_options.modelChecker.settings);
m_compiler->setRemappings(m_options.input.remappings);
m_compiler->setLibraries(m_options.linker.libraries);
m_compiler->setViaIR(m_options.output.viaIR);
m_compiler->setEVMVersion(m_options.output.evmVersion);
m_compiler->setEOFVersion(m_options.output.eofVersion);
m_compiler->setRevertStringBehaviour(m_options.output.revertStrings);
if (m_options.output.debugInfoSelection.has_value())
m_compiler->selectDebugInfo(m_options.output.debugInfoSelection.value());
CompilerStack::PipelineConfig pipelineConfig;
pipelineConfig.irOptimization =
m_options.compiler.outputs.irOptimized ||
m_options.compiler.outputs.irOptimizedAstJson ||
m_options.compiler.outputs.yulCFGJson;
pipelineConfig.irCodegen =
pipelineConfig.irOptimization ||
m_options.compiler.outputs.ir ||
m_options.compiler.outputs.irAstJson;
pipelineConfig.bytecode =
m_options.compiler.estimateGas ||
m_options.compiler.outputs.asm_ ||
m_options.compiler.outputs.asmJson ||
m_options.compiler.outputs.opcodes ||
m_options.compiler.outputs.binary ||
m_options.compiler.outputs.binaryRuntime ||
(m_options.compiler.combinedJsonRequests && (
m_options.compiler.combinedJsonRequests->binary ||
m_options.compiler.combinedJsonRequests->binaryRuntime ||
m_options.compiler.combinedJsonRequests->opcodes ||
m_options.compiler.combinedJsonRequests->asm_ ||
m_options.compiler.combinedJsonRequests->generatedSources ||
m_options.compiler.combinedJsonRequests->generatedSourcesRuntime ||
m_options.compiler.combinedJsonRequests->srcMap ||
m_options.compiler.combinedJsonRequests->srcMapRuntime ||
m_options.compiler.combinedJsonRequests->funDebug ||
m_options.compiler.combinedJsonRequests->funDebugRuntime
));
m_compiler->selectContracts({{"", {{"", pipelineConfig}}}});
m_compiler->setOptimiserSettings(m_options.optimiserSettings());
if (m_options.input.mode == InputMode::CompilerWithASTImport)
{
try
{
m_compiler->importASTs(parseAstFromInput());
if (!m_compiler->analyze())
{
formatter.printErrorInformation(m_compiler->errors());
astAssert(false, "Analysis of the AST failed");
}
}
catch (Exception const& _exc)
{
// FIXME: AST import is missing proper validations. This hack catches failing
// assertions and presents them as if they were compiler errors.
solThrow(CommandLineExecutionError, "Failed to import AST: "s + _exc.what());
}
}
else
m_compiler->setSources(m_fileReader.sourceUnits());
bool successful = m_compiler->compile(m_options.output.stopAfter);
for (auto const& error: m_compiler->errors())
{
m_hasOutput = true;
formatter.printErrorInformation(*error);
}
if (!successful)
solThrow(CommandLineExecutionError, "");
}
catch (CompilerError const& _exception)
{
m_hasOutput = true;
formatter.printExceptionInformation(
_exception,
Error::errorSeverity(Error::Type::CompilerError)
);
solThrow(CommandLineExecutionError, "");
}
}
void CommandLineInterface::handleCombinedJSON()
{
solAssert(m_assemblyStack);
solAssert(
CompilerInputModes.count(m_options.input.mode) == 1 ||
m_options.input.mode == frontend::InputMode::EVMAssemblerJSON
);
if (!m_options.compiler.combinedJsonRequests.has_value())
return;
Json output;
output[g_strVersion] = frontend::VersionString;
std::vector<std::string> contracts = m_assemblyStack->contractNames();
if (!contracts.empty())
output[g_strContracts] = Json::object();
for (std::string const& contractName: contracts)
{
Json& contractData = output[g_strContracts][contractName] = Json::object();
// NOTE: The state checks here are more strict that in Standard JSON. There we allow
// requesting certain outputs even if compilation fails as long as analysis went ok.
if (m_compiler && m_compiler->compilationSuccessful())
{
if (m_options.compiler.combinedJsonRequests->abi)
contractData[g_strAbi] = m_compiler->contractABI(contractName);
if (m_options.compiler.combinedJsonRequests->metadata)
contractData["metadata"] = m_compiler->metadata(contractName);
if (m_options.compiler.combinedJsonRequests->storageLayout)
contractData[g_strStorageLayout] = m_compiler->storageLayout(contractName);
if (m_options.compiler.combinedJsonRequests->transientStorageLayout)
contractData[g_strTransientStorageLayout] = m_compiler->transientStorageLayout(contractName);
if (m_options.compiler.combinedJsonRequests->generatedSources)
contractData[g_strGeneratedSources] = m_compiler->generatedSources(contractName, false);
if (m_options.compiler.combinedJsonRequests->generatedSourcesRuntime)
contractData[g_strGeneratedSourcesRuntime] = m_compiler->generatedSources(contractName, true);
if (m_options.compiler.combinedJsonRequests->signatureHashes)
contractData[g_strSignatureHashes] = m_compiler->interfaceSymbols(contractName)["methods"];
if (m_options.compiler.combinedJsonRequests->natspecDev)
contractData[g_strNatspecDev] = m_compiler->natspecDev(contractName);
if (m_options.compiler.combinedJsonRequests->natspecUser)
contractData[g_strNatspecUser] = m_compiler->natspecUser(contractName);
}
if (m_assemblyStack->compilationSuccessful())
{
if (m_options.compiler.combinedJsonRequests->binary)
contractData[g_strBinary] = m_assemblyStack->object(contractName).toHex();
if (m_options.compiler.combinedJsonRequests->binaryRuntime)
contractData[g_strBinaryRuntime] = m_assemblyStack->runtimeObject(contractName).toHex();
if (m_options.compiler.combinedJsonRequests->opcodes)
contractData[g_strOpcodes] = evmasm::disassemble(m_assemblyStack->object(contractName).bytecode, m_options.output.evmVersion);
if (m_options.compiler.combinedJsonRequests->asm_)
contractData[g_strAsm] = m_assemblyStack->assemblyJSON(contractName);
if (m_options.compiler.combinedJsonRequests->srcMap)
{
auto map = m_assemblyStack->sourceMapping(contractName);
contractData[g_strSrcMap] = map ? *map : "";
}
if (m_options.compiler.combinedJsonRequests->srcMapRuntime)
{
auto map = m_assemblyStack->runtimeSourceMapping(contractName);
contractData[g_strSrcMapRuntime] = map ? *map : "";
}
if (m_options.compiler.combinedJsonRequests->funDebug)
contractData[g_strFunDebug] = StandardCompiler::formatFunctionDebugData(
m_assemblyStack->object(contractName).functionDebugData
);
if (m_options.compiler.combinedJsonRequests->funDebugRuntime)
contractData[g_strFunDebugRuntime] = StandardCompiler::formatFunctionDebugData(
m_assemblyStack->runtimeObject(contractName).functionDebugData
);
}
}
bool needsSourceList =
m_options.compiler.combinedJsonRequests->ast ||
m_options.compiler.combinedJsonRequests->srcMap ||
m_options.compiler.combinedJsonRequests->srcMapRuntime;
if (needsSourceList)
{
// Indices into this array are used to abbreviate source names in source locations.
output[g_strSourceList] = Json::array();
for (auto const& source: m_assemblyStack->sourceNames())
output[g_strSourceList].emplace_back(source);
}
if (m_options.compiler.combinedJsonRequests->ast)
{
solAssert(m_compiler);
output[g_strSources] = Json::object();
for (auto const& sourceCode: m_fileReader.sourceUnits())
{
output[g_strSources][sourceCode.first] = Json::object();
output[g_strSources][sourceCode.first]["AST"] = ASTJsonExporter(
m_compiler->state(),
m_compiler->sourceIndices()
).toJson(m_compiler->ast(sourceCode.first));
output[g_strSources][sourceCode.first]["id"] = m_compiler->sourceIndices().at(sourceCode.first);
}
}
std::string json = jsonPrint(removeNullMembers(std::move(output)), m_options.formatting.json);
if (!m_options.output.dir.empty())
createJson("combined", json);
else
sout() << json << std::endl;
}
void CommandLineInterface::handleAst()
{
solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
if (!m_options.compiler.outputs.astCompactJson)
return;
std::vector<ASTNode const*> asts;
for (auto const& sourceCode: m_fileReader.sourceUnits())
asts.push_back(&m_compiler->ast(sourceCode.first));
if (!m_options.output.dir.empty())
{
for (auto const& sourceCode: m_fileReader.sourceUnits())
{
std::stringstream data;
std::string postfix = "";
ASTJsonExporter(m_compiler->state(), m_compiler->sourceIndices()).print(data, m_compiler->ast(sourceCode.first), m_options.formatting.json);
postfix += "_json";
boost::filesystem::path path(sourceCode.first);
createFile(path.filename().string() + postfix + ".ast", data.str());
}
}
else
{
sout() << "JSON AST (compact format):" << std::endl << std::endl;
for (auto const& sourceCode: m_fileReader.sourceUnits())
{
sout() << std::endl << "======= " << sourceCode.first << " =======" << std::endl;
ASTJsonExporter(m_compiler->state(), m_compiler->sourceIndices()).print(sout(), m_compiler->ast(sourceCode.first), m_options.formatting.json);
}
}
}
void CommandLineInterface::serveLSP()
{
lsp::StdioTransport transport;
if (!lsp::LanguageServer{transport}.run())
solThrow(CommandLineExecutionError, "LSP terminated abnormally.");
}
void CommandLineInterface::link()
{
solAssert(m_options.input.mode == InputMode::Linker);
// Map from how the libraries will be named inside the bytecode to their addresses.
std::map<std::string, h160> librariesReplacements;
int const placeholderSize = 40; // 20 bytes or 40 hex characters
for (auto const& library: m_options.linker.libraries)
{
std::string const& name = library.first;
// Library placeholders are 40 hex digits (20 bytes) that start and end with '__'.
// This leaves 36 characters for the library identifier. The identifier used to
// be just the cropped or '_'-padded library name, but this changed to
// the cropped hex representation of the hash of the library name.
// We support both ways of linking here.
librariesReplacements["__" + evmasm::LinkerObject::libraryPlaceholder(name) + "__"] = library.second;
std::string replacement = "__";
for (size_t i = 0; i < placeholderSize - 4; ++i)
replacement.push_back(i < name.size() ? name[i] : '_');
replacement += "__";
librariesReplacements[replacement] = library.second;
}
FileReader::StringMap sourceCodes = m_fileReader.sourceUnits();
for (auto& src: sourceCodes)
{
auto end = src.second.end();
for (auto it = src.second.begin(); it != end;)
{
while (it != end && *it != '_') ++it;
if (it == end) break;
if (
end - it < placeholderSize ||
*(it + 1) != '_' ||
*(it + placeholderSize - 2) != '_' ||
*(it + placeholderSize - 1) != '_'
)
solThrow(
CommandLineExecutionError,
"Error in binary object file " + src.first + " at position " + std::to_string(it - src.second.begin()) + "\n" +
'"' + std::string(it, it + std::min(placeholderSize, static_cast<int>(end - it))) + "\" is not a valid link reference."
);
std::string foundPlaceholder(it, it + placeholderSize);
if (librariesReplacements.count(foundPlaceholder))
{
std::string hexStr(util::toHex(librariesReplacements.at(foundPlaceholder).asBytes()));
copy(hexStr.begin(), hexStr.end(), it);
}
else
report(
Error::Severity::Warning,
fmt::format("Reference \"{}\" in file \"{}\" still unresolved.", foundPlaceholder, src.first)
);
it += placeholderSize;
}
// Remove hints for resolved libraries.
for (auto const& library: m_options.linker.libraries)
boost::algorithm::erase_all(src.second, "\n" + libraryPlaceholderHint(library.first));
while (!src.second.empty() && *prev(src.second.end()) == '\n')
src.second.resize(src.second.size() - 1);
}
m_fileReader.setSourceUnits(std::move(sourceCodes));
}
void CommandLineInterface::writeLinkedFiles()
{
solAssert(m_options.input.mode == InputMode::Linker);
for (auto const& src: m_fileReader.sourceUnits())
if (src.first == g_stdinFileName)
sout() << src.second << std::endl;
else
{
std::ofstream outFile(src.first);
outFile << src.second;
if (!outFile)
solThrow(CommandLineOutputError, "Could not write to file " + src.first + ". Aborting.");
}
sout() << "Linking completed." << std::endl;
}
std::string CommandLineInterface::libraryPlaceholderHint(std::string const& _libraryName)
{
return "// " + evmasm::LinkerObject::libraryPlaceholder(_libraryName) + " -> " + _libraryName;
}
std::string CommandLineInterface::objectWithLinkRefsHex(evmasm::LinkerObject const& _obj)
{
std::string out = _obj.toHex();
if (!_obj.linkReferences.empty())
{
out += "\n";
for (auto const& linkRef: _obj.linkReferences)
out += "\n" + libraryPlaceholderHint(linkRef.second);
}
return out;
}
void CommandLineInterface::assembleYul(yul::YulStack::Language _language, yul::YulStack::Machine _targetMachine)
{
solAssert(m_options.input.mode == InputMode::Assembler);
bool successful = true;
std::map<std::string, yul::YulStack> yulStacks;
for (auto const& src: m_fileReader.sourceUnits())
{
auto& stack = yulStacks[src.first] = yul::YulStack(
m_options.output.evmVersion,
m_options.output.eofVersion,
_language,
m_options.optimiserSettings(),
m_options.output.debugInfoSelection.has_value() ?
m_options.output.debugInfoSelection.value() :
DebugInfoSelection::Default()
);
if (!stack.parseAndAnalyze(src.first, src.second))
successful = false;
else
stack.optimize();
if (successful && m_options.compiler.outputs.asmJson)
{
std::shared_ptr<yul::Object> result = stack.parserResult();
if (result && !result->hasContiguousSourceIndices())
solThrow(
CommandLineExecutionError,
"Generating the assembly JSON output was not possible. "
"Source indices provided in the @use-src annotation in the Yul input do not start at 0 or are not contiguous."
);
}
}
for (auto const& sourceAndStack: yulStacks)
{
auto const& stack = sourceAndStack.second;
SourceReferenceFormatter formatter(serr(false), stack, coloredOutput(m_options), m_options.formatting.withErrorIds);
for (auto const& error: stack.errors())
{
m_hasOutput = true;
formatter.printErrorInformation(*error);
}
if (Error::containsErrors(stack.errors()))
successful = false;
}
if (!successful)
{
solAssert(m_hasOutput);
solThrow(CommandLineExecutionError, "");
}
for (auto const& src: m_fileReader.sourceUnits())
{
solAssert(_targetMachine == yul::YulStack::Machine::EVM);
std::string machine = "EVM";
sout() << std::endl << "======= " << src.first << " (" << machine << ") =======" << std::endl;
yul::YulStack& stack = yulStacks[src.first];
if (m_options.compiler.outputs.irOptimized)
{
// NOTE: This actually outputs unoptimized code when the optimizer is disabled but
// 'ir' output in StandardCompiler works the same way.
sout() << std::endl << "Pretty printed source:" << std::endl;
sout() << stack.print() << std::endl;
}
yul::MachineAssemblyObject object;
object = stack.assemble(_targetMachine);
object.bytecode->link(m_options.linker.libraries);
if (m_options.compiler.outputs.binary)
{
sout() << std::endl << "Binary representation:" << std::endl;
if (object.bytecode)
sout() << object.bytecode->toHex() << std::endl;
else
report(Error::Severity::Info, "No binary representation found.");
}
if (m_options.compiler.outputs.astCompactJson)
{
sout() << "AST:" << std::endl << std::endl;
sout() << util::jsonPrint(stack.astJson(), m_options.formatting.json) << std::endl;
}
if (m_options.compiler.outputs.yulCFGJson)
{
sout() << "Yul Control Flow Graph:" << std::endl << std::endl;
sout() << util::jsonPrint(stack.cfgJson(), m_options.formatting.json) << std::endl;
}
solAssert(_targetMachine == yul::YulStack::Machine::EVM, "");
if (m_options.compiler.outputs.asm_)
{
sout() << std::endl << "Text representation:" << std::endl;
std::string assemblyText{object.assembly->assemblyString(stack.debugInfoSelection())};
if (!assemblyText.empty())
sout() << assemblyText << std::endl;
else
report(Error::Severity::Info, "No text representation found.");
}
if (m_options.compiler.outputs.asmJson)
{
sout() << std::endl << "EVM assembly:" << std::endl;
std::map<std::string, unsigned> sourceIndices;
stack.parserResult()->collectSourceIndices(sourceIndices);
sout() << util::jsonPrint(
object.assembly->assemblyJSON(sourceIndices),
m_options.formatting.json
) << std::endl;
}
}
}
void CommandLineInterface::outputCompilationResults()
{
solAssert(CompilerInputModes.count(m_options.input.mode) == 1);
handleCombinedJSON();
// do we need AST output?
handleAst();
CompilerOutputs astOutputSelection;
astOutputSelection.astCompactJson = true;
if (m_options.compiler.outputs != CompilerOutputs() && m_options.compiler.outputs != astOutputSelection)
{
// Currently AST is the only output allowed with --stop-after parsing. For all of the others
// we can safely assume that full compilation was performed and successful.
solAssert(m_options.output.stopAfter >= CompilerStack::State::CompilationSuccessful);
for (std::string const& contract: m_compiler->contractNames())
{
if (needsHumanTargetedStdout(m_options))
sout() << std::endl << "======= " << contract << " =======" << std::endl;
handleEVMAssembly(contract);
if (m_options.compiler.estimateGas)
handleGasEstimation(contract);
handleBytecode(contract);
handleIR(contract);
handleIRAst(contract);
handleIROptimized(contract);
handleIROptimizedAst(contract);
handleYulCFGExport(contract);
handleSignatureHashes(contract);
handleMetadata(contract);
handleABI(contract);
handleStorageLayout(contract);
handleTransientStorageLayout(contract);
handleNatspec(true, contract);
handleNatspec(false, contract);
} // end of contracts iteration
}
if (!m_hasOutput)
{
if (!m_options.output.dir.empty())
sout() << "Compiler run successful. Artifact(s) can be found in directory " << m_options.output.dir << "." << std::endl;
else if (m_compiler->contractNames().empty())
sout() << "Compiler run successful. No contracts to compile." << std::endl;
else
sout() << "Compiler run successful. No output generated." << std::endl;
}
}
void CommandLineInterface::report(langutil::Error::Severity _severity, std::string _message)
{
SourceReferenceFormatter::printPrimaryMessage(
serr(),
_message,
_severity,
std::nullopt,
coloredOutput(m_options),
m_options.formatting.withErrorIds
);
}
}
| 45,798
|
C++
|
.cpp
| 1,216
| 34.802632
| 145
| 0.735553
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,893
|
Common.cpp
|
ethereum_solidity/test/Common.cpp
|
/*
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
#include <stdexcept>
#include <iostream>
#include <test/Common.h>
#include <test/EVMHost.h>
#include <test/libsolidity/util/SoltestErrors.h>
#include <libsolutil/Assertions.h>
#include <libsolutil/StringUtils.h>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>
#include <range/v3/all.hpp>
namespace fs = boost::filesystem;
namespace po = boost::program_options;
namespace solidity::test
{
namespace
{
/// If non-empty returns the value of the env. variable ETH_TEST_PATH, otherwise
/// it tries to find a path that contains the directories "libsolidity/syntaxTests"
/// and returns it if found.
/// The routine searches in the current directory, and inside the "test" directory
/// starting from the current directory and up to three levels up.
/// @returns the path of the first match or an empty path if not found.
boost::filesystem::path testPath()
{
if (auto path = getenv("ETH_TEST_PATH"))
return path;
auto const searchPath =
{
fs::current_path() / ".." / ".." / ".." / "test",
fs::current_path() / ".." / ".." / "test",
fs::current_path() / ".." / "test",
fs::current_path() / "test",
fs::current_path()
};
for (auto const& basePath: searchPath)
{
fs::path syntaxTestPath = basePath / "libsolidity" / "syntaxTests";
if (fs::exists(syntaxTestPath) && fs::is_directory(syntaxTestPath))
return basePath;
}
return {};
}
std::optional<fs::path> findInDefaultPath(std::string const& lib_name)
{
auto const searchPath =
{
fs::current_path() / "deps",
fs::current_path() / "deps" / "lib",
fs::current_path() / ".." / "deps",
fs::current_path() / ".." / "deps" / "lib",
fs::current_path() / ".." / ".." / "deps",
fs::current_path() / ".." / ".." / "deps" / "lib",
fs::current_path(),
#ifdef __APPLE__
fs::current_path().root_path() / fs::path("usr") / "local" / "lib",
#endif
};
for (auto const& basePath: searchPath)
{
fs::path p = basePath / lib_name;
if (fs::exists(p))
return p;
}
return std::nullopt;
}
}
CommonOptions::CommonOptions(std::string _caption):
options(_caption,
po::options_description::m_default_line_length,
po::options_description::m_default_line_length - 23
)
{
}
void CommonOptions::addOptions()
{
options.add_options()
("evm-version", po::value(&evmVersionString), "which EVM version to use")
// "eof-version" is declared as uint64_t, since uint8_t will be parsed as character by boost.
("eof-version", po::value<uint64_t>()->implicit_value(1u), "which EOF version to use")
("testpath", po::value<fs::path>(&this->testPath)->default_value(solidity::test::testPath()), "path to test files")
("vm", po::value<std::vector<fs::path>>(&vmPaths), "path to evmc library, can be supplied multiple times.")
("batches", po::value<size_t>(&this->batches)->default_value(1), "set number of batches to split the tests into")
("selected-batch", po::value<size_t>(&this->selectedBatch)->default_value(0), "zero-based number of batch to execute")
("no-semantic-tests", po::bool_switch(&disableSemanticTests)->default_value(disableSemanticTests), "disable semantic tests")
("no-smt", po::bool_switch(&disableSMT)->default_value(disableSMT), "disable SMT checker")
("optimize", po::bool_switch(&optimize)->default_value(optimize), "enables optimization")
("enforce-gas-cost", po::value<bool>(&enforceGasTest)->default_value(enforceGasTest)->implicit_value(true), "Enforce checking gas cost in semantic tests.")
("enforce-gas-cost-min-value", po::value(&enforceGasTestMinValue)->default_value(enforceGasTestMinValue), "Threshold value to enforce adding gas checks to a test.")
("abiencoderv1", po::bool_switch(&useABIEncoderV1)->default_value(useABIEncoderV1), "enables abi encoder v1")
("show-messages", po::bool_switch(&showMessages)->default_value(showMessages), "enables message output")
("show-metadata", po::bool_switch(&showMetadata)->default_value(showMetadata), "enables metadata output");
}
void CommonOptions::validate() const
{
assertThrow(
!testPath.empty(),
ConfigException,
"No test path specified. The --testpath argument must not be empty when given."
);
assertThrow(
fs::exists(testPath),
ConfigException,
"Invalid test path specified."
);
assertThrow(
batches > 0,
ConfigException,
"Batches needs to be at least 1."
);
assertThrow(
selectedBatch < batches,
ConfigException,
"Selected batch has to be less than number of batches."
);
if (!enforceGasTest)
std::cout << std::endl << "WARNING :: Gas cost expectations are not being enforced" << std::endl << std::endl;
else if (evmVersion() != langutil::EVMVersion{} || useABIEncoderV1)
{
std::cout << std::endl << "WARNING :: Enforcing gas cost expectations with non-standard settings:" << std::endl;
if (evmVersion() != langutil::EVMVersion{})
std::cout << "- EVM version: " << evmVersion().name() << " (default: " << langutil::EVMVersion{}.name() << ")" << std::endl;
if (useABIEncoderV1)
std::cout << "- ABI coder: v1 (default: v2)" << std::endl;
std::cout << std::endl << "DO NOT COMMIT THE UPDATED EXPECTATIONS." << std::endl << std::endl;
}
assertThrow(!eofVersion().has_value() || evmVersion() >= langutil::EVMVersion::prague(), ConfigException, "EOF is unavailable before Prague fork.");
}
bool CommonOptions::parse(int argc, char const* const* argv)
{
po::variables_map arguments;
addOptions();
try
{
po::command_line_parser cmdLineParser(argc, argv);
cmdLineParser.options(options);
auto parsedOptions = cmdLineParser.run();
po::store(parsedOptions, arguments);
po::notify(arguments);
if (arguments.count("eof-version"))
{
// Request as uint64_t, since uint8_t will be parsed as character by boost.
uint64_t eofVersion = arguments["eof-version"].as<uint64_t>();
if (eofVersion != 1)
BOOST_THROW_EXCEPTION(std::runtime_error("Invalid EOF version: " + std::to_string(eofVersion)));
m_eofVersion = 1;
}
for (auto const& parsedOption: parsedOptions.options)
if (parsedOption.position_key >= 0)
{
if (
parsedOption.original_tokens.empty() ||
(parsedOption.original_tokens.size() == 1 && parsedOption.original_tokens.front().empty())
)
continue; // ignore empty options
std::stringstream errorMessage;
errorMessage << "Unrecognized option: ";
for (auto const& token: parsedOption.original_tokens)
errorMessage << token;
BOOST_THROW_EXCEPTION(std::runtime_error(errorMessage.str()));
}
}
catch (po::error const& exception)
{
solThrow(ConfigException, exception.what());
}
if (vmPaths.empty())
{
if (auto envPath = getenv("ETH_EVMONE"))
vmPaths.emplace_back(envPath);
else if (auto repoPath = findInDefaultPath(evmoneFilename))
vmPaths.emplace_back(*repoPath);
else
vmPaths.emplace_back(evmoneFilename);
}
return true;
}
std::string CommonOptions::toString(std::vector<std::string> const& _selectedOptions) const
{
if (_selectedOptions.empty())
return "";
auto boolToString = [](bool _value) -> std::string { return _value ? "true" : "false"; };
// Using std::map to avoid if-else/switch-case block
std::map<std::string, std::string> optionValueMap = {
{"evmVersion", evmVersion().name()},
{"optimize", boolToString(optimize)},
{"useABIEncoderV1", boolToString(useABIEncoderV1)},
{"batch", std::to_string(selectedBatch + 1) + "/" + std::to_string(batches)},
{"enforceGasTest", boolToString(enforceGasTest)},
{"enforceGasTestMinValue", enforceGasTestMinValue.str()},
{"disableSemanticTests", boolToString(disableSemanticTests)},
{"disableSMT", boolToString(disableSMT)},
{"showMessages", boolToString(showMessages)},
{"showMetadata", boolToString(showMetadata)}
};
soltestAssert(ranges::all_of(_selectedOptions, [&optionValueMap](std::string const& _option) { return optionValueMap.count(_option) > 0; }));
std::vector<std::string> optionsWithValues = _selectedOptions |
ranges::views::transform([&optionValueMap](std::string const& _option) { return _option + "=" + optionValueMap.at(_option); }) |
ranges::to<std::vector>();
return solidity::util::joinHumanReadable(optionsWithValues);
}
void CommonOptions::printSelectedOptions(std::ostream& _stream, std::string const& _linePrefix, std::vector<std::string> const& _selectedOptions) const
{
_stream << _linePrefix << "Run Settings: " << toString(_selectedOptions) << std::endl;
}
langutil::EVMVersion CommonOptions::evmVersion() const
{
if (!evmVersionString.empty())
{
auto version = langutil::EVMVersion::fromString(evmVersionString);
if (!version)
BOOST_THROW_EXCEPTION(std::runtime_error("Invalid EVM version: " + evmVersionString));
return *version;
}
else
return langutil::EVMVersion();
}
CommonOptions const& CommonOptions::get()
{
if (!m_singleton)
BOOST_THROW_EXCEPTION(std::runtime_error("Options not yet constructed!"));
return *m_singleton;
}
void CommonOptions::setSingleton(std::unique_ptr<CommonOptions const>&& _instance)
{
m_singleton = std::move(_instance);
}
std::unique_ptr<CommonOptions const> CommonOptions::m_singleton = nullptr;
bool isValidSemanticTestPath(boost::filesystem::path const& _testPath)
{
bool insideSemanticTests = false;
fs::path testPathPrefix;
for (auto const& element: _testPath)
{
testPathPrefix /= element;
if (boost::ends_with(canonical(testPathPrefix).generic_string(), "/test/libsolidity/semanticTests"))
insideSemanticTests = true;
if (insideSemanticTests && boost::starts_with(element.string(), "_"))
return false;
}
return true;
}
boost::unit_test::precondition::predicate_t minEVMVersionCheck(langutil::EVMVersion _minEVMVersion)
{
return [_minEVMVersion](boost::unit_test::test_unit_id) {
return test::CommonOptions::get().evmVersion() >= _minEVMVersion;
};
}
bool loadVMs(CommonOptions const& _options)
{
if (_options.disableSemanticTests)
return true;
bool evmSupported = solidity::test::EVMHost::checkVmPaths(_options.vmPaths);
if (!_options.disableSemanticTests && !evmSupported)
{
std::cerr << "Unable to find " << solidity::test::evmoneFilename;
std::cerr << ". Please disable semantics tests with --no-semantic-tests or provide a path using --vm <path>." << std::endl;
std::cerr << "You can download it at" << std::endl;
std::cerr << solidity::test::evmoneDownloadLink << std::endl;
return false;
}
return true;
}
}
| 11,035
|
C++
|
.cpp
| 278
| 37.226619
| 166
| 0.720564
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,896
|
FilesystemUtils.cpp
|
ethereum_solidity/test/FilesystemUtils.cpp
|
/*
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
#include <test/FilesystemUtils.h>
#include <test/libsolidity/util/SoltestErrors.h>
#include <fstream>
using namespace solidity;
using namespace solidity::test;
void solidity::test::createFilesWithParentDirs(std::set<boost::filesystem::path> const& _paths, std::string const& _content)
{
for (boost::filesystem::path const& path: _paths)
{
if (!path.parent_path().empty())
boost::filesystem::create_directories(path.parent_path());
// Use binary mode to avoid line ending conversion on Windows.
std::ofstream newFile(path.string(), std::ofstream::binary);
newFile << _content;
if (newFile.fail() || !boost::filesystem::exists(path))
BOOST_THROW_EXCEPTION(std::runtime_error("Failed to create an empty file: \"" + path.string() + "\"."));
}
}
void solidity::test::createFileWithContent(boost::filesystem::path const& _path, std::string const& _content)
{
if (boost::filesystem::is_regular_file(_path))
BOOST_THROW_EXCEPTION(std::runtime_error("File already exists: \"" + _path.string() + "\".")); \
// Use binary mode to avoid line ending conversion on Windows.
std::ofstream newFile(_path.string(), std::ofstream::binary);
if (newFile.fail() || !boost::filesystem::is_regular_file(_path))
BOOST_THROW_EXCEPTION(std::runtime_error("Failed to create a file: \"" + _path.string() + "\".")); \
newFile << _content;
}
bool solidity::test::createSymlinkIfSupportedByFilesystem(
boost::filesystem::path _targetPath,
boost::filesystem::path const& _linkName,
bool _directorySymlink
)
{
boost::system::error_code symlinkCreationError;
// NOTE: On Windows / works as a separator in a symlink target only if the target is absolute.
// Convert path separators to native ones to avoid this problem.
_targetPath.make_preferred();
if (_directorySymlink)
boost::filesystem::create_directory_symlink(_targetPath, _linkName, symlinkCreationError);
else
boost::filesystem::create_symlink(_targetPath, _linkName, symlinkCreationError);
if (!symlinkCreationError)
return true;
else if (
symlinkCreationError == boost::system::errc::not_supported ||
symlinkCreationError == boost::system::errc::operation_not_supported
)
return false;
else
BOOST_THROW_EXCEPTION(std::runtime_error(
"Failed to create a symbolic link: \"" + _linkName.string() + "\""
" -> " + _targetPath.string() + "\"."
" " + symlinkCreationError.message() + "."
));
}
| 3,078
|
C++
|
.cpp
| 70
| 41.628571
| 124
| 0.74323
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,897
|
CommonSyntaxTest.cpp
|
ethereum_solidity/test/CommonSyntaxTest.cpp
|
/*
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
#include <test/CommonSyntaxTest.h>
#include <test/Common.h>
#include <test/TestCase.h>
#include <liblangutil/SourceReferenceFormatter.h>
#include <libsolutil/CommonIO.h>
#include <libsolutil/StringUtils.h>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/throw_exception.hpp>
#include <fstream>
#include <memory>
#include <stdexcept>
using namespace solidity;
using namespace solidity::util;
using namespace solidity::util::formatting;
using namespace solidity::langutil;
using namespace solidity::frontend;
using namespace solidity::frontend::test;
using namespace solidity::test;
using namespace boost::unit_test;
namespace fs = boost::filesystem;
namespace
{
int parseUnsignedInteger(std::string::iterator& _it, std::string::iterator _end)
{
if (_it == _end || !util::isDigit(*_it))
BOOST_THROW_EXCEPTION(std::runtime_error("Invalid test expectation. Source location expected."));
int result = 0;
while (_it != _end && util::isDigit(*_it))
{
result *= 10;
result += *_it - '0';
++_it;
}
return result;
}
}
CommonSyntaxTest::CommonSyntaxTest(std::string const& _filename, langutil::EVMVersion _evmVersion):
EVMVersionRestrictedTestCase(_filename),
m_sources(m_reader.sources()),
m_expectations(parseExpectations(m_reader.stream())),
m_evmVersion(_evmVersion)
{
}
TestCase::TestResult CommonSyntaxTest::run(std::ostream& _stream, std::string const& _linePrefix, bool _formatted)
{
parseCustomExpectations(m_reader.stream());
parseAndAnalyze();
return conclude(_stream, _linePrefix, _formatted);
}
TestCase::TestResult CommonSyntaxTest::conclude(std::ostream& _stream, std::string const& _linePrefix, bool _formatted)
{
if (expectationsMatch())
return TestResult::Success;
printExpectationAndError(_stream, _linePrefix, _formatted);
return TestResult::Failure;
}
void CommonSyntaxTest::printExpectationAndError(std::ostream& _stream, std::string const& _linePrefix, bool _formatted)
{
std::string nextIndentLevel = _linePrefix + " ";
util::AnsiColorized(_stream, _formatted, {BOLD, CYAN}) << _linePrefix << "Expected result:" << std::endl;
printExpectedResult(_stream, nextIndentLevel, _formatted);
util::AnsiColorized(_stream, _formatted, {BOLD, CYAN}) << _linePrefix << "Obtained result:" << std::endl;
printObtainedResult(_stream, nextIndentLevel, _formatted);
}
void CommonSyntaxTest::printSource(std::ostream& _stream, std::string const& _linePrefix, bool _formatted) const
{
if (m_sources.sources.empty())
return;
assert(m_sources.externalSources.empty());
bool outputSourceNames = (m_sources.sources.size() != 1 || !m_sources.sources.begin()->first.empty());
for (auto const& [name, source]: m_sources.sources)
if (_formatted)
{
if (source.empty())
continue;
if (outputSourceNames)
_stream << _linePrefix << util::formatting::CYAN << "==== Source: " << name << " ====" << util::formatting::RESET << std::endl;
std::vector<char const*> sourceFormatting(source.length(), util::formatting::RESET);
for (auto const& error: m_errorList)
if (error.sourceName == name && error.locationStart >= 0 && error.locationEnd >= 0)
{
assert(static_cast<size_t>(error.locationStart) <= source.length());
assert(static_cast<size_t>(error.locationEnd) <= source.length());
for (int i = error.locationStart; i < error.locationEnd; i++)
{
char const*& cellFormat = sourceFormatting[static_cast<size_t>(i)];
char const* infoBgColor = SourceReferenceFormatter::errorHighlightColor(Error::Severity::Info);
if (
(error.type != Error::Type::Warning && error.type != Error::Type::Info) ||
(error.type == Error::Type::Warning && (cellFormat == RESET || cellFormat == infoBgColor)) ||
(error.type == Error::Type::Info && cellFormat == RESET)
)
cellFormat = SourceReferenceFormatter::errorHighlightColor(Error::errorSeverity(error.type));
}
}
_stream << _linePrefix << sourceFormatting.front() << source.front();
for (size_t i = 1; i < source.length(); i++)
{
if (sourceFormatting[i] != sourceFormatting[i - 1])
_stream << sourceFormatting[i];
if (source[i] != '\n')
_stream << source[i];
else
{
_stream << util::formatting::RESET << std::endl;
if (i + 1 < source.length())
_stream << _linePrefix << sourceFormatting[i];
}
}
_stream << util::formatting::RESET;
}
else
{
if (outputSourceNames)
printPrefixed(_stream, "==== Source: " + name + " ====", _linePrefix);
printPrefixed(_stream, source, _linePrefix);
}
}
void CommonSyntaxTest::parseCustomExpectations(std::istream& _stream)
{
std::string remainingExpectations = boost::trim_copy(readUntilEnd(_stream));
soltestAssert(
remainingExpectations.empty(),
"Found custom expectations not supported by the test case:\n" + remainingExpectations
);
}
bool CommonSyntaxTest::expectationsMatch()
{
return m_expectations == m_errorList;
}
void CommonSyntaxTest::printExpectedResult(std::ostream& _stream, std::string const& _linePrefix, bool _formatted) const
{
printErrorList(_stream, m_expectations, _linePrefix, _formatted);
}
void CommonSyntaxTest::printObtainedResult(std::ostream& _stream, std::string const& _linePrefix, bool _formatted) const
{
printErrorList(_stream, m_errorList, _linePrefix, _formatted);
}
void CommonSyntaxTest::printErrorList(
std::ostream& _stream,
std::vector<SyntaxTestError> const& _errorList,
std::string const& _linePrefix,
bool _formatted
)
{
if (_errorList.empty())
{
if (_formatted)
util::AnsiColorized(_stream, _formatted, {BOLD, GREEN}) << _linePrefix << "Success" << std::endl;
}
else
for (auto const& error: _errorList)
{
{
util::AnsiColorized scope(
_stream,
_formatted,
{BOLD, SourceReferenceFormatter::errorTextColor(Error::errorSeverity(error.type))}
);
_stream << _linePrefix << Error::formatErrorType(error.type);
if (error.errorId.has_value())
_stream << ' ' << error.errorId->error;
_stream << ": ";
}
if (!error.sourceName.empty() || error.locationStart >= 0 || error.locationEnd >= 0)
{
_stream << "(";
if (!error.sourceName.empty())
_stream << error.sourceName << ":";
if (error.locationStart >= 0)
_stream << error.locationStart;
_stream << "-";
if (error.locationEnd >= 0)
_stream << error.locationEnd;
_stream << "): ";
}
_stream << error.message << std::endl;
}
}
std::string CommonSyntaxTest::errorMessage(util::Exception const& _e)
{
if (_e.comment() && !_e.comment()->empty())
return boost::replace_all_copy(*_e.comment(), "\n", "\\n");
else
return "NONE";
}
std::vector<SyntaxTestError> CommonSyntaxTest::parseExpectations(std::istream& _stream)
{
static std::string const customExpectationsDelimiter("// ----");
std::vector<SyntaxTestError> expectations;
std::string line;
while (std::getline(_stream, line))
{
auto it = line.begin();
// Anything below the delimiter is left up to the derived class to process in a custom way.
// The delimiter is optional and identical to the one that starts error expectations in
// TestCaseReader::parseSourcesAndSettingsWithLineNumber().
if (boost::algorithm::starts_with(line, customExpectationsDelimiter))
break;
skipSlashes(it, line.end());
skipWhitespace(it, line.end());
if (it == line.end()) continue;
auto typeBegin = it;
while (it != line.end() && isalpha(*it, std::locale::classic()))
++it;
std::string errorTypeStr(typeBegin, it);
std::optional<Error::Type> errorType = Error::parseErrorType(errorTypeStr);
if (!errorType.has_value())
BOOST_THROW_EXCEPTION(std::runtime_error("Invalid error type: " + errorTypeStr));
skipWhitespace(it, line.end());
std::optional<ErrorId> errorId;
if (it != line.end() && util::isDigit(*it))
errorId = ErrorId{static_cast<unsigned long long>(parseUnsignedInteger(it, line.end()))};
expect(it, line.end(), ':');
skipWhitespace(it, line.end());
int locationStart = -1;
int locationEnd = -1;
std::string sourceName;
if (it != line.end() && *it == '(')
{
++it;
if (it != line.end() && !util::isDigit(*it))
{
auto sourceNameStart = it;
while (it != line.end() && *it != ':')
++it;
sourceName = std::string(sourceNameStart, it);
expect(it, line.end(), ':');
}
locationStart = parseUnsignedInteger(it, line.end());
expect(it, line.end(), '-');
locationEnd = parseUnsignedInteger(it, line.end());
expect(it, line.end(), ')');
expect(it, line.end(), ':');
}
skipWhitespace(it, line.end());
std::string errorMessage(it, line.end());
expectations.emplace_back(SyntaxTestError{
errorType.value(),
std::move(errorId),
std::move(errorMessage),
std::move(sourceName),
locationStart,
locationEnd
});
}
return expectations;
}
| 9,592
|
C++
|
.cpp
| 264
| 33.223485
| 131
| 0.704438
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,898
|
EVMHost.cpp
|
ethereum_solidity/test/EVMHost.cpp
|
/*
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
/**
* EVM execution host, i.e. component that implements a simulated Ethereum blockchain
* for testing purposes.
*/
#include <test/EVMHost.h>
#include <test/evmc/loader.h>
#include <libevmasm/GasMeter.h>
#include <libsolutil/Exceptions.h>
#include <libsolutil/Assertions.h>
#include <libsolutil/Keccak256.h>
#include <libsolutil/picosha2.h>
using namespace solidity;
using namespace solidity::util;
using namespace solidity::test;
using namespace evmc::literals;
evmc::VM& EVMHost::getVM(std::string const& _path)
{
static evmc::VM NullVM{nullptr};
static std::map<std::string, std::unique_ptr<evmc::VM>> vms;
if (vms.count(_path) == 0)
{
evmc_loader_error_code errorCode = {};
auto vm = evmc::VM{evmc_load_and_configure(_path.c_str(), &errorCode)};
if (vm && errorCode == EVMC_LOADER_SUCCESS)
{
if (vm.get_capabilities() & (EVMC_CAPABILITY_EVM1))
vms[_path] = std::make_unique<evmc::VM>(evmc::VM(std::move(vm)));
else
std::cerr << "VM loaded does not support EVM1" << std::endl;
}
else
{
std::cerr << "Error loading VM from " << _path;
if (char const* errorMsg = evmc_last_error_msg())
std::cerr << ":" << std::endl << errorMsg;
std::cerr << std::endl;
}
}
if (vms.count(_path) > 0)
return *vms[_path];
return NullVM;
}
bool EVMHost::checkVmPaths(std::vector<boost::filesystem::path> const& _vmPaths)
{
bool evmVmFound = false;
for (auto const& path: _vmPaths)
{
evmc::VM& vm = EVMHost::getVM(path.string());
if (!vm)
continue;
if (vm.has_capability(EVMC_CAPABILITY_EVM1))
{
if (evmVmFound)
BOOST_THROW_EXCEPTION(std::runtime_error("Multiple evm1 evmc vms defined. Please only define one evm1 evmc vm."));
evmVmFound = true;
}
}
return evmVmFound;
}
EVMHost::EVMHost(langutil::EVMVersion _evmVersion, evmc::VM& _vm):
m_vm(_vm),
m_evmVersion(_evmVersion)
{
if (!m_vm)
{
std::cerr << "Unable to find evmone library" << std::endl;
assertThrow(false, Exception, "");
}
if (_evmVersion == langutil::EVMVersion::homestead())
m_evmRevision = EVMC_HOMESTEAD;
else if (_evmVersion == langutil::EVMVersion::tangerineWhistle())
m_evmRevision = EVMC_TANGERINE_WHISTLE;
else if (_evmVersion == langutil::EVMVersion::spuriousDragon())
m_evmRevision = EVMC_SPURIOUS_DRAGON;
else if (_evmVersion == langutil::EVMVersion::byzantium())
m_evmRevision = EVMC_BYZANTIUM;
else if (_evmVersion == langutil::EVMVersion::constantinople())
m_evmRevision = EVMC_CONSTANTINOPLE;
else if (_evmVersion == langutil::EVMVersion::petersburg())
m_evmRevision = EVMC_PETERSBURG;
else if (_evmVersion == langutil::EVMVersion::istanbul())
m_evmRevision = EVMC_ISTANBUL;
else if (_evmVersion == langutil::EVMVersion::berlin())
m_evmRevision = EVMC_BERLIN;
else if (_evmVersion == langutil::EVMVersion::london())
m_evmRevision = EVMC_LONDON;
else if (_evmVersion == langutil::EVMVersion::paris())
m_evmRevision = EVMC_PARIS;
else if (_evmVersion == langutil::EVMVersion::shanghai())
m_evmRevision = EVMC_SHANGHAI;
else if (_evmVersion == langutil::EVMVersion::cancun())
m_evmRevision = EVMC_CANCUN;
else if (_evmVersion == langutil::EVMVersion::prague())
m_evmRevision = EVMC_PRAGUE;
else
assertThrow(false, Exception, "Unsupported EVM version");
if (m_evmRevision >= EVMC_PARIS)
// This is the value from the merge block.
tx_context.block_prev_randao = 0xa86c2e601b6c44eb4848f7d23d9df3113fbcac42041c49cbed5000cb4f118777_bytes32;
else
tx_context.block_prev_randao = evmc::uint256be{200000000};
tx_context.block_gas_limit = 20000000;
tx_context.block_coinbase = 0x7878787878787878787878787878787878787878_address;
tx_context.tx_gas_price = evmc::uint256be{3000000000};
tx_context.tx_origin = 0x9292929292929292929292929292929292929292_address;
// Mainnet according to EIP-155
tx_context.chain_id = evmc::uint256be{1};
// The minimum value of basefee
tx_context.block_base_fee = evmc::bytes32{7};
// The minimum value of blobbasefee
tx_context.blob_base_fee = evmc::bytes32{1};
static evmc_bytes32 const blob_hashes_array[] = {
0x0100000000000000000000000000000000000000000000000000000000000001_bytes32,
0x0100000000000000000000000000000000000000000000000000000000000002_bytes32
};
tx_context.blob_hashes = blob_hashes_array;
tx_context.blob_hashes_count = sizeof(blob_hashes_array) / sizeof(blob_hashes_array[0]);
// Reserve space for recording calls.
if (!recorded_calls.capacity())
recorded_calls.reserve(max_recorded_calls);
reset();
}
void EVMHost::reset()
{
accounts.clear();
// Clear self destruct records
recorded_selfdestructs.clear();
// Clear call records
recorded_calls.clear();
// Clear EIP-2929 account access indicator
recorded_account_accesses.clear();
m_newlyCreatedAccounts.clear();
m_totalCodeDepositGas = 0;
// Mark all precompiled contracts as existing. Existing here means to have a balance (as per EIP-161).
// NOTE: keep this in sync with `EVMHost::call` below.
//
// A lot of precompile addresses had a balance before they became valid addresses for precompiles.
// For example all the precompile addresses allocated in Byzantium had a 1 wei balance sent to them
// roughly 22 days before the update went live.
for (unsigned precompiledAddress = 1; precompiledAddress <= 8; precompiledAddress++)
{
evmc::address address{precompiledAddress};
// 1wei
accounts[address].balance = evmc::uint256be{1};
// Set according to EIP-1052.
if (precompiledAddress < 5 || m_evmVersion >= langutil::EVMVersion::byzantium())
accounts[address].codehash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470_bytes32;
}
}
void EVMHost::newTransactionFrame()
{
// Clear EIP-2929 account access indicator
recorded_account_accesses.clear();
for (auto& [address, account]: accounts)
{
for (auto& [slot, value]: account.storage)
{
value.access_status = EVMC_ACCESS_COLD; // Clear EIP-2929 storage access indicator
value.original = value.current; // Clear EIP-2200 dirty slot
}
// Clear transient storage according to EIP 1153
account.transient_storage.clear();
}
// Process selfdestruct list
for (auto& [address, _]: recorded_selfdestructs)
if (m_evmVersion < langutil::EVMVersion::cancun() || m_newlyCreatedAccounts.count(address))
// EIP-6780: If SELFDESTRUCT is executed in a transaction different from the one
// in which it was created, we do NOT record it or clear any data.
// Otherwise, the previous behavior (pre-Cancun) is maintained.
accounts.erase(address);
m_newlyCreatedAccounts.clear();
m_totalCodeDepositGas = 0;
recorded_selfdestructs.clear();
}
void EVMHost::transfer(evmc::MockedAccount& _sender, evmc::MockedAccount& _recipient, u256 const& _value) noexcept
{
assertThrow(u256(convertFromEVMC(_sender.balance)) >= _value, Exception, "Insufficient balance for transfer");
_sender.balance = convertToEVMC(u256(convertFromEVMC(_sender.balance)) - _value);
_recipient.balance = convertToEVMC(u256(convertFromEVMC(_recipient.balance)) + _value);
}
bool EVMHost::selfdestruct(const evmc::address& _addr, const evmc::address& _beneficiary) noexcept
{
// TODO actual selfdestruct is even more complicated.
// NOTE: EIP-6780: The transfer of the entire account balance to the beneficiary should still happen
// after cancun.
transfer(accounts[_addr], accounts[_beneficiary], convertFromEVMC(accounts[_addr].balance));
// Record self destructs. Clearing will be done in newTransactionFrame().
return MockedHost::selfdestruct(_addr, _beneficiary);
}
void EVMHost::recordCalls(evmc_message const& _message) noexcept
{
if (recorded_calls.size() < max_recorded_calls)
recorded_calls.emplace_back(_message);
}
// NOTE: this is used for both internal and external calls.
// External calls are triggered from ExecutionFramework and contain only EVMC_CREATE or EVMC_CALL.
evmc::Result EVMHost::call(evmc_message const& _message) noexcept
{
recordCalls(_message);
if (_message.recipient == 0x0000000000000000000000000000000000000001_address)
return precompileECRecover(_message);
else if (_message.recipient == 0x0000000000000000000000000000000000000002_address)
return precompileSha256(_message);
else if (_message.recipient == 0x0000000000000000000000000000000000000003_address)
return precompileRipeMD160(_message);
else if (_message.recipient == 0x0000000000000000000000000000000000000004_address)
return precompileIdentity(_message);
else if (_message.recipient == 0x0000000000000000000000000000000000000005_address && m_evmVersion >= langutil::EVMVersion::byzantium())
return precompileModExp(_message);
else if (_message.recipient == 0x0000000000000000000000000000000000000006_address && m_evmVersion >= langutil::EVMVersion::byzantium())
{
if (m_evmVersion <= langutil::EVMVersion::istanbul())
return precompileALTBN128G1Add<EVMC_ISTANBUL>(_message);
else
return precompileALTBN128G1Add<EVMC_LONDON>(_message);
}
else if (_message.recipient == 0x0000000000000000000000000000000000000007_address && m_evmVersion >= langutil::EVMVersion::byzantium())
{
if (m_evmVersion <= langutil::EVMVersion::istanbul())
return precompileALTBN128G1Mul<EVMC_ISTANBUL>(_message);
else
return precompileALTBN128G1Mul<EVMC_LONDON>(_message);
}
else if (_message.recipient == 0x0000000000000000000000000000000000000008_address && m_evmVersion >= langutil::EVMVersion::byzantium())
{
if (m_evmVersion <= langutil::EVMVersion::istanbul())
return precompileALTBN128PairingProduct<EVMC_ISTANBUL>(_message);
else
return precompileALTBN128PairingProduct<EVMC_LONDON>(_message);
}
else if (_message.recipient == 0x0000000000000000000000000000000000000009_address && m_evmVersion >= langutil::EVMVersion::istanbul())
return precompileBlake2f(_message);
auto const stateBackup = accounts;
u256 value{convertFromEVMC(_message.value)};
auto& sender = accounts[_message.sender];
evmc::bytes code;
evmc_message message = _message;
if (message.depth == 0)
{
message.gas -= message.kind == EVMC_CREATE ? evmasm::GasCosts::txCreateGas : evmasm::GasCosts::txGas;
for (size_t i = 0; i < message.input_size; ++i)
message.gas -= message.input_data[i] == 0 ? evmasm::GasCosts::txDataZeroGas : evmasm::GasCosts::txDataNonZeroGas(m_evmVersion);
if (message.gas < 0)
{
evmc::Result result;
result.status_code = EVMC_OUT_OF_GAS;
accounts = stateBackup;
return result;
}
}
if (message.kind == EVMC_CREATE)
{
// TODO is the nonce incremented on failure, too?
// NOTE: nonce for creation from contracts starts at 1
// TODO: check if sender is an EOA and do not pre-increment
sender.nonce++;
auto encodeRlpInteger = [](int value) -> bytes {
if (value == 0) {
return bytes{128};
} else if (value <= 127) {
return bytes{static_cast<uint8_t>(value)};
} else if (value <= 0xff) {
return bytes{128 + 1, static_cast<uint8_t>(value)};
} else if (value <= 0xffff) {
return bytes{128 + 55 + 2, static_cast<uint8_t>(value >> 8), static_cast<uint8_t>(value)};
} else {
assertThrow(false, Exception, "Can only encode RLP numbers <= 0xffff");
}
};
bytes encodedNonce = encodeRlpInteger(sender.nonce);
h160 createAddress(keccak256(
bytes{static_cast<uint8_t>(0xc0 + 21 + encodedNonce.size())} +
bytes{0x94} +
bytes(std::begin(message.sender.bytes), std::end(message.sender.bytes)) +
encodedNonce
), h160::AlignRight);
message.recipient = convertToEVMC(createAddress);
assertThrow(accounts.count(message.recipient) == 0, Exception, "Account cannot exist");
code = evmc::bytes(message.input_data, message.input_data + message.input_size);
}
else if (message.kind == EVMC_CREATE2)
{
h160 createAddress(keccak256(
bytes{0xff} +
bytes(std::begin(message.sender.bytes), std::end(message.sender.bytes)) +
bytes(std::begin(message.create2_salt.bytes), std::end(message.create2_salt.bytes)) +
keccak256(bytes(message.input_data, message.input_data + message.input_size)).asBytes()
), h160::AlignRight);
message.recipient = convertToEVMC(createAddress);
if (accounts.count(message.recipient) && (
accounts[message.recipient].nonce > 0 ||
!accounts[message.recipient].code.empty()
))
{
evmc::Result result;
result.status_code = EVMC_OUT_OF_GAS;
accounts = stateBackup;
return result;
}
code = evmc::bytes(message.input_data, message.input_data + message.input_size);
}
else
code = accounts[message.code_address].code;
auto& destination = accounts[message.recipient];
if (message.kind == EVMC_CREATE || message.kind == EVMC_CREATE2)
// Mark account as created if it is a CREATE or CREATE2 call
// TODO: Should we roll changes back on failure like we do for `accounts`?
m_newlyCreatedAccounts.emplace(message.recipient);
if (value != 0 && message.kind != EVMC_DELEGATECALL && message.kind != EVMC_CALLCODE)
{
if (value > convertFromEVMC(sender.balance))
{
evmc::Result result;
result.status_code = EVMC_INSUFFICIENT_BALANCE;
accounts = stateBackup;
return result;
}
transfer(sender, destination, value);
}
// Populate the access access list (enabled since Berlin).
// Note, this will also properly touch the created address.
// TODO: support a user supplied access list too
if (m_evmRevision >= EVMC_BERLIN)
{
access_account(message.sender);
access_account(message.recipient);
// EIP-3651 rule
if (m_evmRevision >= EVMC_SHANGHAI)
access_account(tx_context.block_coinbase);
}
if (message.kind == EVMC_CREATE || message.kind == EVMC_CREATE2)
{
message.input_data = nullptr;
message.input_size = 0;
}
evmc::Result result = m_vm.execute(*this, m_evmRevision, message, code.data(), code.size());
if (message.kind == EVMC_CREATE || message.kind == EVMC_CREATE2)
{
int64_t codeDepositGas = static_cast<int64_t>(evmasm::GasCosts::createDataGas * result.output_size);
result.gas_left -= codeDepositGas;
if (result.gas_left < 0)
{
m_totalCodeDepositGas += -result.gas_left;
result.gas_left = 0;
result.status_code = EVMC_OUT_OF_GAS;
// TODO clear some fields?
}
else
{
m_totalCodeDepositGas += codeDepositGas;
result.create_address = message.recipient;
destination.code = evmc::bytes(result.output_data, result.output_data + result.output_size);
destination.codehash = convertToEVMC(keccak256({result.output_data, result.output_size}));
}
}
if (result.status_code != EVMC_SUCCESS)
accounts = stateBackup;
return result;
}
evmc::bytes32 EVMHost::get_block_hash(int64_t _number) const noexcept
{
return convertToEVMC(u256("0x3737373737373737373737373737373737373737373737373737373737373737") + _number);
}
h160 EVMHost::convertFromEVMC(evmc::address const& _addr)
{
return h160(bytes(std::begin(_addr.bytes), std::end(_addr.bytes)));
}
evmc::address EVMHost::convertToEVMC(h160 const& _addr)
{
evmc::address a;
for (unsigned i = 0; i < 20; ++i)
a.bytes[i] = _addr[i];
return a;
}
h256 EVMHost::convertFromEVMC(evmc::bytes32 const& _data)
{
return h256(bytes(std::begin(_data.bytes), std::end(_data.bytes)));
}
evmc::bytes32 EVMHost::convertToEVMC(h256 const& _data)
{
evmc::bytes32 d;
for (unsigned i = 0; i < 32; ++i)
d.bytes[i] = _data[i];
return d;
}
evmc::Result EVMHost::precompileECRecover(evmc_message const& _message) noexcept
{
// NOTE this is a partial implementation for some inputs.
// Fixed cost of 3000 gas.
constexpr int64_t gas_cost = 3000;
static std::map<bytes, EVMPrecompileOutput> const inputOutput{
{
fromHex(
"18c547e4f7b0f325ad1e56f57e26c745b09a3e503d86e00e5255ff7f715d3d1c"
"000000000000000000000000000000000000000000000000000000000000001c"
"73b1693892219d736caba55bdb67216e485557ea6b6af75f37096c9aa6a5a75f"
"eeb940b1d03b21e36b0e47e79769f095fe2ab855bd91e3a38756b7d75a9c4549"
),
{
fromHex("000000000000000000000000a94f5374fce5edbc8e2a8697c15331677e6ebf0b"),
gas_cost
}
},
{
fromHex(
"47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad"
"000000000000000000000000000000000000000000000000000000000000001c"
"debaaa0cddb321b2dcaaf846d39605de7b97e77ba6106587855b9106cb104215"
"61a22d94fa8b8a687ff9c911c844d1c016d1a685a9166858f9c7c1bc85128aca"
),
{
fromHex("0000000000000000000000008743523d96a1b2cbe0c6909653a56da18ed484af"),
gas_cost
}
}
};
evmc::Result result = precompileGeneric(_message, inputOutput);
// ECRecover will return success with empty response in case of failure
if (result.status_code != EVMC_SUCCESS && result.status_code != EVMC_OUT_OF_GAS)
return resultWithGas(_message.gas, gas_cost, {});
return result;
}
evmc::Result EVMHost::precompileSha256(evmc_message const& _message) noexcept
{
// static data so that we do not need a release routine...
bytes static hash;
hash = picosha2::hash256(bytes(
_message.input_data,
_message.input_data + _message.input_size
));
// Base 60 gas + 12 gas / word.
int64_t gas_cost = 60 + 12 * ((static_cast<int64_t>(_message.input_size) + 31) / 32);
return resultWithGas(_message.gas, gas_cost, hash);
}
evmc::Result EVMHost::precompileRipeMD160(evmc_message const& _message) noexcept
{
// NOTE this is a partial implementation for some inputs.
// Base 600 gas + 120 gas / word.
constexpr auto calc_cost = [](int64_t size) -> int64_t {
return 600 + 120 * ((size + 31) / 32);
};
static std::map<bytes, EVMPrecompileOutput> const inputOutput{
{
bytes{},
{
fromHex("0000000000000000000000009c1185a5c5e9fc54612808977ee8f548b2258d31"),
calc_cost(0)
}
},
{
fromHex("0000000000000000000000000000000000000000000000000000000000000004"),
{
fromHex("0000000000000000000000001b0f3c404d12075c68c938f9f60ebea4f74941a0"),
calc_cost(32)
}
},
{
fromHex("0000000000000000000000000000000000000000000000000000000000000005"),
{
fromHex("000000000000000000000000ee54aa84fc32d8fed5a5fe160442ae84626829d9"),
calc_cost(32)
}
},
{
fromHex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),
{
fromHex("0000000000000000000000001cf4e77f5966e13e109703cd8a0df7ceda7f3dc3"),
calc_cost(32)
}
},
{
fromHex("0000000000000000000000000000000000000000000000000000000000000000"),
{
fromHex("000000000000000000000000f93175303eba2a7b372174fc9330237f5ad202fc"),
calc_cost(32)
}
},
{
fromHex(
"0800000000000000000000000000000000000000000000000000000000000000"
"0401000000000000000000000000000000000000000000000000000000000000"
"0000000400000000000000000000000000000000000000000000000000000000"
"00000100"
),
{
fromHex("000000000000000000000000f93175303eba2a7b372174fc9330237f5ad202fc"),
calc_cost(100)
}
},
{
fromHex(
"0800000000000000000000000000000000000000000000000000000000000000"
"0501000000000000000000000000000000000000000000000000000000000000"
"0000000500000000000000000000000000000000000000000000000000000000"
"00000100"
),
{
fromHex("0000000000000000000000004f4fc112e2bfbe0d38f896a46629e08e2fcfad5"),
calc_cost(100)
}
},
{
fromHex(
"08ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
"ff010000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
"ffffffff00000000000000000000000000000000000000000000000000000000"
"00000100"
),
{
fromHex("000000000000000000000000c0a2e4b1f3ff766a9a0089e7a410391730872495"),
calc_cost(100)
}
},
{
fromHex(
"6162636465666768696a6b6c6d6e6f707172737475767778797a414243444546"
"4748494a4b4c4d4e4f505152535455565758595a303132333435363738393f21"
),
{
fromHex("00000000000000000000000036c6b90a49e17d4c1e1b0e634ec74124d9b207da"),
calc_cost(64)
}
},
{
fromHex("6162636465666768696a6b6c6d6e6f707172737475767778797a414243444546"),
{
fromHex("000000000000000000000000ac5ab22e07b0fb80c69b6207902f725e2507e546"),
calc_cost(32)
}
}
};
return precompileGeneric(_message, inputOutput);
}
evmc::Result EVMHost::precompileIdentity(evmc_message const& _message) noexcept
{
// static data so that we do not need a release routine...
bytes static data;
data = bytes(_message.input_data, _message.input_data + _message.input_size);
// Base 15 gas + 3 gas / word.
int64_t gas_cost = 15 + 3 * ((static_cast<int64_t>(_message.input_size) + 31) / 32);
return resultWithGas(_message.gas, gas_cost, data);
}
evmc::Result EVMHost::precompileModExp(evmc_message const&) noexcept
{
// TODO implement
return resultWithFailure();
}
template <evmc_revision Revision>
evmc::Result EVMHost::precompileALTBN128G1Add(evmc_message const& _message) noexcept
{
// NOTE this is a partial implementation for some inputs.
// Fixed 500 or 150 gas.
int64_t gas_cost = (Revision < EVMC_ISTANBUL) ? 500 : 150;
static std::map<bytes, EVMPrecompileOutput> const inputOutput{
{
fromHex(
"0000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000"
"1385281136ff5b2c326807ff0a824b6ca4f21fcc7c8764e9801bc4ad497d5012"
"02254594be8473dcf018a2aa66ea301e38fc865823acf75a9901721d1fc6bf4c"
"0000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000"
),
{
fromHex(
"1385281136ff5b2c326807ff0a824b6ca4f21fcc7c8764e9801bc4ad497d5012"
"02254594be8473dcf018a2aa66ea301e38fc865823acf75a9901721d1fc6bf4c"
),
gas_cost
}
},
{
fromHex(
"0000000000000000000000000000000000000000000000000000000000000001"
"0000000000000000000000000000000000000000000000000000000000000002"
"0000000000000000000000000000000000000000000000000000000000000001"
"0000000000000000000000000000000000000000000000000000000000000002"
"0000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000"
),
{
fromHex(
"030644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd3"
"15ed738c0e0a7c92e7845f96b2ae9c0a68a6a449e3538fc7ff3ebf7a5a18a2c4"
),
gas_cost
}
},
{
fromHex(
"0000000000000000000000000000000000000000000000000000000000000001"
"0000000000000000000000000000000000000000000000000000000000000002"
"0000000000000000000000000000000000000000000000000000000000000001"
"30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd45"
"0000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000"
),
{
fromHex(
"0000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000"
),
gas_cost
}
},
{
fromHex(
"10b4876441e14a6be92a7fe66550848c01c676a12ac31d7cc13b21f49c4307c8"
"09f5528bdb0ef9354837a0f4b4c9da973bd5b805d359976f719ab0b74e0a7368"
"28d3c57516712e7843a5b3cfa7d7274a037943f5bd57c227620ad207728e4283"
"2795fa9df21d4b8b329a45bae120f1fd9df9049ecacaa9dd1eca18bc6a55cd2f"
"0000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000"
),
{
fromHex(
"16aed5ed486df6b2fb38015ded41400009ed4f34bef65b87b1f90f47052f8d94"
"16dabf21b3f25b9665269d98dc17b1da6118251dc0b403ae50e96dfe91239375"
),
gas_cost
}
},
{
fromHex(
"1385281136ff5b2c326807ff0a824b6ca4f21fcc7c8764e9801bc4ad497d5012"
"02254594be8473dcf018a2aa66ea301e38fc865823acf75a9901721d1fc6bf4c"
"1644e84fef7b7fdc98254f0654580173307a3bc44db990581e7ab55a22446dcf"
"28c2916b7e875692b195831945805438fcd30d2693d8a80cf8c88ec6ef4c315d"
"0000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000"
),
{
fromHex(
"1e018816fc9bbd91313301ae9c254bb7d64d6cd54f3b49b92925e43e256b5faa"
"1d1f2259c715327bedb42c095af6c0267e4e1be836b4e04b3f0502552f93cca9"
),
gas_cost
}
},
{
fromHex(
"16aed5ed486df6b2fb38015ded41400009ed4f34bef65b87b1f90f47052f8d94"
"16dabf21b3f25b9665269d98dc17b1da6118251dc0b403ae50e96dfe91239375"
"25ff95a3abccf32adc6a4c3c8caddca67723d8ada802e9b9f612e3ddb40b2005"
"0d82b09bb4ec927bbf182bdc402790429322b7e2f285f2aad8ea135cbf7143d8"
"0000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000"
),
{
fromHex(
"29d160febeef9770d47a32ee3b763850eb0594844fa57dd31b8ed02c78fdb797"
"2c7cdf62c2498486fd52646e577a06723ce97737b3c958262d78c4a413661e8a"
),
gas_cost
}
},
{
fromHex(
"18014701594179c6b9ccae848e3d15c1f76f8a68b8092578296520e46c9bae0c"
"1b5ed0e9e8f3ff35589ea81a45cf63887d4a92c099a3be1d97b26f0db96323dd"
"16a1d378d1a98cf5383cdc512011234287ca43b6a078d1842d5c58c5b1f475cc"
"1309377a7026d08ca1529eab74381a7e0d3a4b79d80bacec207cd52fc8e3769c"
"0000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000"
),
{
fromHex(
"2583ed10e418133e44619c336f1be5ddae9e20d634a7683d9661401c750d7df4"
"0185fbba22de9e698262925665735dbc4d6e8288bc3fc39fae10ca58e16e77f7"
),
gas_cost
}
},
{
fromHex(
"1c76476f4def4bb94541d57ebba1193381ffa7aa76ada664dd31c16024c43f59"
"3034dd2920f673e204fee2811c678745fc819b55d3e9d294e45c9b03a76aef41"
"0f25929bcb43d5a57391564615c9e70a992b10eafa4db109709649cf48c50dd2"
"16da2f5cb6be7a0aa72c440c53c9bbdfec6c36c7d515536431b3a865468acbba"
"0000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000"
),
{
fromHex(
"1496064626ba8bffeb7805f0d16143a65649bb0850333ea512c03fcdaf31e254"
"07b4f210ab542533f1ee5633ae4406cd16c63494b537ce3f1cf4afff6f76a48f"
),
gas_cost
}
},
{
fromHex(
"1e018816fc9bbd91313301ae9c254bb7d64d6cd54f3b49b92925e43e256b5faa"
"1d1f2259c715327bedb42c095af6c0267e4e1be836b4e04b3f0502552f93cca9"
"2364294faf6b89fedeede9986aa777c4f6c2f5c4a4559ee93dfec9b7b94ef80b"
"05aeae62655ea23865ae6661ae371a55c12098703d0f2301f4223e708c92efc6"
"0000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000"
),
{
fromHex(
"2801b21090cbc48409e352647f3857134d373f81741f9d5e3d432f336d76f517"
"13cf106acf943c2a331de21c7d5e3351354e7412f2dba2918483a6593a6828d4"
),
gas_cost
}
},
{
fromHex(
"2583ed10e418133e44619c336f1be5ddae9e20d634a7683d9661401c750d7df4"
"0185fbba22de9e698262925665735dbc4d6e8288bc3fc39fae10ca58e16e77f7"
"258f1faa356e470cca19c928afa5ceed6215c756912af5725b8db5777cc8f3b6"
"175ced8a58d0c132c2b95ba14c16dde93e7f7789214116ff69da6f44daa966e6"
"0000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000"
),
{
fromHex(
"10b4876441e14a6be92a7fe66550848c01c676a12ac31d7cc13b21f49c4307c8"
"09f5528bdb0ef9354837a0f4b4c9da973bd5b805d359976f719ab0b74e0a7368"
),
gas_cost
}
},
{
fromHex(
"26dcfbc2e0bc9d82efb4acd73cb3e99730e27e10177fcfb78b6399a4bfcdf391"
"27c440dbd5053253a3a692f9bf89b9b6e9612127cf97db1e11ffa9679acc933b"
"1496064626ba8bffeb7805f0d16143a65649bb0850333ea512c03fcdaf31e254"
"07b4f210ab542533f1ee5633ae4406cd16c63494b537ce3f1cf4afff6f76a48f"
"0000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000"
),
{
fromHex(
"186bac5188a98c45e6016873d107f5cd131f3a3e339d0375e58bd6219347b008"
"1e396bc242de0214898b0f68035f53ad5a6f96c6c8390ac56ed6ec9561d23159"
),
gas_cost
}
},
{
fromHex(
"26dcfbc2e0bc9d82efb4acd73cb3e99730e27e10177fcfb78b6399a4bfcdf391"
"27c440dbd5053253a3a692f9bf89b9b6e9612127cf97db1e11ffa9679acc933b"
"1c76476f4def4bb94541d57ebba1193381ffa7aa76ada664dd31c16024c43f59"
"3034dd2920f673e204fee2811c678745fc819b55d3e9d294e45c9b03a76aef41"
"0000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000"
),
{
fromHex(
"20a754d2071d4d53903e3b31a7e98ad6882d58aec240ef981fdf0a9d22c5926a"
"29c853fcea789887315916bbeb89ca37edb355b4f980c9a12a94f30deeed3021"
),
gas_cost
}
},
{
fromHex(
"27231d5cdd0011259ff75678cf5a8f7840c22cb71d52b25e21e071205e8d9bc4"
"26dd3d225c9a71476db0cf834232eba84020f3073c6d20c519963e0b98f235e1"
"2174f0221490cd9c15b0387f3251ec3d49517a51c37a8076eac12afb4a95a707"
"1d1c3fcd3161e2a417b4df0955f02db1fffa9005210fb30c5aa3755307e9d1f5"
"0000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000"
),
{
fromHex(
"18014701594179c6b9ccae848e3d15c1f76f8a68b8092578296520e46c9bae0c"
"1b5ed0e9e8f3ff35589ea81a45cf63887d4a92c099a3be1d97b26f0db96323dd"
),
gas_cost
}
},
{
fromHex(
"2801b21090cbc48409e352647f3857134d373f81741f9d5e3d432f336d76f517"
"13cf106acf943c2a331de21c7d5e3351354e7412f2dba2918483a6593a6828d4"
"2a49621e12910cd90f3e731083d454255bf1c533d6e15b8699156778d0f27f5d"
"2590ee31824548d159aa2d22296bf149d564c0872f41b89b7dc5c6e6e3cd1c4d"
"0000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000"
),
{
fromHex(
"27231d5cdd0011259ff75678cf5a8f7840c22cb71d52b25e21e071205e8d9bc4"
"26dd3d225c9a71476db0cf834232eba84020f3073c6d20c519963e0b98f235e1"
),
gas_cost
}
},
{
fromHex(
"29d160febeef9770d47a32ee3b763850eb0594844fa57dd31b8ed02c78fdb797"
"2c7cdf62c2498486fd52646e577a06723ce97737b3c958262d78c4a413661e8a"
"0aee46a7ea6e80a3675026dfa84019deee2a2dedb1bbe11d7fe124cb3efb4b5a"
"044747b6e9176e13ede3a4dfd0d33ccca6321b9acd23bf3683a60adc0366ebaf"
"0000000000000000000000000000000000000000000000000000000000000000"
"0000000000000000000000000000000000000000000000000000000000000000"
),
{
fromHex(
"26dcfbc2e0bc9d82efb4acd73cb3e99730e27e10177fcfb78b6399a4bfcdf391"
"27c440dbd5053253a3a692f9bf89b9b6e9612127cf97db1e11ffa9679acc933b"
),
gas_cost
}
}
};
return precompileGeneric(_message, inputOutput);
}
template <evmc_revision Revision>
evmc::Result EVMHost::precompileALTBN128G1Mul(evmc_message const& _message) noexcept
{
// NOTE this is a partial implementation for some inputs.
// Fixed 40000 or 6000 gas.
int64_t gas_cost = (Revision < EVMC_ISTANBUL) ? 40000 : 6000;
static std::map<bytes, EVMPrecompileOutput> const inputOutput{
{
fromHex("0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000"),
{
fromHex("030644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd315ed738c0e0a7c92e7845f96b2ae9c0a68a6a449e3538fc7ff3ebf7a5a18a2c4"),
gas_cost
}
},
{
fromHex("0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000050000000000000000000000000000000000000000000000000000000000000000"),
{
fromHex("17c139df0efee0f766bc0204762b774362e4ded88953a39ce849a8a7fa163fa901e0559bacb160664764a357af8a9fe70baa9258e0b959273ffc5718c6d4cc7c"),
gas_cost
}
},
{
fromHex("09b54f111d3b2d1b2fe1ae9669b3db3d7bf93b70f00647e65c849275de6dc7fe18b2e77c63a3e400d6d1f1fbc6e1a1167bbca603d34d03edea231eb0ab7b14b4030f7b0c405c888aff922307ea2cd1c70f64664bab76899500341f4260a209290000000000000000000000000000000000000000000000000000000000000000"),
{
fromHex("16a1d378d1a98cf5383cdc512011234287ca43b6a078d1842d5c58c5b1f475cc1309377a7026d08ca1529eab74381a7e0d3a4b79d80bacec207cd52fc8e3769c"),
gas_cost
}
},
{
fromHex("0a6de0e2240aa253f46ce0da883b61976e3588146e01c9d8976548c145fe6e4a04fbaa3a4aed4bb77f30ebb07a3ec1c7d77a7f2edd75636babfeff97b1ea686e1551dcd4965285ef049512d2d30cbfc1a91acd5baad4a6e19e22e93176197f170000000000000000000000000000000000000000000000000000000000000000"),
{
fromHex("28d3c57516712e7843a5b3cfa7d7274a037943f5bd57c227620ad207728e42832795fa9df21d4b8b329a45bae120f1fd9df9049ecacaa9dd1eca18bc6a55cd2f"),
gas_cost
}
},
{
fromHex("0c54b42137b67cc268cbb53ac62b00ecead23984092b494a88befe58445a244a18e3723d37fae9262d58b548a0575f59d9c3266db7afb4d5739555837f6b8b3e0c692b41f1acc961f6ea83bae2c3a1a55c54f766c63ba76989f52c149c17b5e70000000000000000000000000000000000000000000000000000000000000000"),
{
fromHex("258f1faa356e470cca19c928afa5ceed6215c756912af5725b8db5777cc8f3b6175ced8a58d0c132c2b95ba14c16dde93e7f7789214116ff69da6f44daa966e6"),
gas_cost
}
},
{
fromHex("0f103f14a584d4203c27c26155b2c955f8dfa816980b24ba824e1972d6486a5d0c4165133b9f5be17c804203af781bcf168da7386620479f9b885ecbcd27b17b0ea71d0abb524cac7cfff5323e1d0b14ab705842426c978f96753ccce258ed930000000000000000000000000000000000000000000000000000000000000000"),
{
fromHex("2a49621e12910cd90f3e731083d454255bf1c533d6e15b8699156778d0f27f5d2590ee31824548d159aa2d22296bf149d564c0872f41b89b7dc5c6e6e3cd1c4d"),
gas_cost
}
},
{
fromHex("111e2e2a5f8828f80ddad08f9f74db56dac1cc16c1cb278036f79a84cf7a116f1d7d62e192b219b9808faa906c5ced871788f6339e8d91b83ac1343e20a16b3000000000000000000000000000000000000000e40800000000000000008cdcbc0000000000000000000000000000000000000000000000000000000000000000"),
{
fromHex("25ff95a3abccf32adc6a4c3c8caddca67723d8ada802e9b9f612e3ddb40b20050d82b09bb4ec927bbf182bdc402790429322b7e2f285f2aad8ea135cbf7143d8"),
gas_cost
}
},
{
fromHex("17d5d09b4146424bff7e6fb01487c477bbfcd0cdbbc92d5d6457aae0b6717cc502b5636903efbf46db9235bbe74045d21c138897fda32e079040db1a16c1a7a11887420878c0c8e37605291c626585eabbec8d8b97a848fe8d58a37b004583510000000000000000000000000000000000000000000000000000000000000000"),
{
fromHex("2364294faf6b89fedeede9986aa777c4f6c2f5c4a4559ee93dfec9b7b94ef80b05aeae62655ea23865ae6661ae371a55c12098703d0f2301f4223e708c92efc6"),
gas_cost
}
},
{
fromHex("1c36e713d4d54e3a9644dffca1fc524be4868f66572516025a61ca542539d43f042dcc4525b82dfb242b09cb21909d5c22643dcdbe98c4d082cc2877e96b24db016086cc934d5cab679c6991a4efcedbab26d7e4fb23b6a1ad4e6b5c2fb59ce50000000000000000000000000000000000000000000000000000000000000000"),
{
fromHex("1644e84fef7b7fdc98254f0654580173307a3bc44db990581e7ab55a22446dcf28c2916b7e875692b195831945805438fcd30d2693d8a80cf8c88ec6ef4c315d"),
gas_cost
}
},
{
fromHex("1e39e9f0f91fa7ff8047ffd90de08785777fe61c0e3434e728fce4cf35047ddc2e0b64d75ebfa86d7f8f8e08abbe2e7ae6e0a1c0b34d028f19fa56e9450527cb1eec35a0e955cad4bee5846ae0f1d0b742d8636b278450c534e38e06a60509f90000000000000000000000000000000000000000000000000000000000000000"),
{
fromHex("1385281136ff5b2c326807ff0a824b6ca4f21fcc7c8764e9801bc4ad497d501202254594be8473dcf018a2aa66ea301e38fc865823acf75a9901721d1fc6bf4c"),
gas_cost
}
},
{
fromHex("232063b584fb76c8d07995bee3a38fa7565405f3549c6a918ddaa90ab971e7f82ac9b135a81d96425c92d02296322ad56ffb16299633233e4880f95aafa7fda70689c3dc4311426ee11707866b2cbdf9751dacd07245bf99d2113d3f5a8cac470000000000000000000000000000000000000000000000000000000000000000"),
{
fromHex("2174f0221490cd9c15b0387f3251ec3d49517a51c37a8076eac12afb4a95a7071d1c3fcd3161e2a417b4df0955f02db1fffa9005210fb30c5aa3755307e9d1f5"),
gas_cost
}
}
};
return precompileGeneric(_message, inputOutput);
}
template <evmc_revision Revision>
evmc::Result EVMHost::precompileALTBN128PairingProduct(evmc_message const& _message) noexcept
{
// Base + per pairing gas.
constexpr auto calc_cost = [](unsigned points) -> int64_t {
// Number of 192-byte points.
return (Revision < EVMC_ISTANBUL) ?
(100000 + 80000 * points):
(45000 + 34000 * points);
};
// NOTE this is a partial implementation for some inputs.
static std::map<bytes, EVMPrecompileOutput> const inputOutput{
{
fromHex(
"17c139df0efee0f766bc0204762b774362e4ded88953a39ce849a8a7fa163fa9"
"01e0559bacb160664764a357af8a9fe70baa9258e0b959273ffc5718c6d4cc7c"
"198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2"
"1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed"
"090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b"
"12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa"
"0000000000000000000000000000000000000000000000000000000000000001"
"30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd45"
"0a09ccf561b55fd99d1c1208dee1162457b57ac5af3759d50671e510e428b2a1"
"2e539c423b302d13f4e5773c603948eaf5db5df8ae8a9a9113708390a06410d8"
"19b763513924a736e4eebd0d78c91c1bc1d657fee4214057d21414011cfcc763"
"2f8d9f9ab83727c77a2fec063cb7b6e5eb23044ccf535ad49d46d394fb6f6bf6"
),
{
fromHex("0000000000000000000000000000000000000000000000000000000000000001"),
calc_cost(2)
}
},
{
fromHex(
"0000000000000000000000000000000000000000000000000000000000000001"
"0000000000000000000000000000000000000000000000000000000000000002"
"198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2"
"1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed"
"090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b"
"12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa"
"0000000000000000000000000000000000000000000000000000000000000001"
"30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd45"
"198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2"
"1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed"
"090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b"
"12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa"
),
{
fromHex("0000000000000000000000000000000000000000000000000000000000000001"),
calc_cost(2)
}
},
{
fromHex(
"1c76476f4def4bb94541d57ebba1193381ffa7aa76ada664dd31c16024c43f59"
"3034dd2920f673e204fee2811c678745fc819b55d3e9d294e45c9b03a76aef41"
"209dd15ebff5d46c4bd888e51a93cf99a7329636c63514396b4a452003a35bf7"
"04bf11ca01483bfa8b34b43561848d28905960114c8ac04049af4b6315a41678"
"2bb8324af6cfc93537a2ad1a445cfd0ca2a71acd7ac41fadbf933c2a51be344d"
"120a2a4cf30c1bf9845f20c6fe39e07ea2cce61f0c9bb048165fe5e4de877550"
"111e129f1cf1097710d41c4ac70fcdfa5ba2023c6ff1cbeac322de49d1b6df7c"
"2032c61a830e3c17286de9462bf242fca2883585b93870a73853face6a6bf411"
"198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2"
"1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed"
"090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b"
"12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa"
),
{
fromHex("0000000000000000000000000000000000000000000000000000000000000001"),
calc_cost(2)
}
},
{
fromHex(
"2eca0c7238bf16e83e7a1e6c5d49540685ff51380f309842a98561558019fc02"
"03d3260361bb8451de5ff5ecd17f010ff22f5c31cdf184e9020b06fa5997db84"
"1213d2149b006137fcfb23036606f848d638d576a120ca981b5b1a5f9300b3ee"
"2276cf730cf493cd95d64677bbb75fc42db72513a4c1e387b476d056f80aa75f"
"21ee6226d31426322afcda621464d0611d226783262e21bb3bc86b537e986237"
"096df1f82dff337dd5972e32a8ad43e28a78a96a823ef1cd4debe12b6552ea5f"
"06967a1237ebfeca9aaae0d6d0bab8e28c198c5a339ef8a2407e31cdac516db9"
"22160fa257a5fd5b280642ff47b65eca77e626cb685c84fa6d3b6882a283ddd1"
"198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2"
"1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed"
"090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b"
"12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa"
),
{
fromHex("0000000000000000000000000000000000000000000000000000000000000001"),
calc_cost(2)
}
},
{
fromHex(
"0f25929bcb43d5a57391564615c9e70a992b10eafa4db109709649cf48c50dd2"
"16da2f5cb6be7a0aa72c440c53c9bbdfec6c36c7d515536431b3a865468acbba"
"2e89718ad33c8bed92e210e81d1853435399a271913a6520736a4729cf0d51eb"
"01a9e2ffa2e92599b68e44de5bcf354fa2642bd4f26b259daa6f7ce3ed57aeb3"
"14a9a87b789a58af499b314e13c3d65bede56c07ea2d418d6874857b70763713"
"178fb49a2d6cd347dc58973ff49613a20757d0fcc22079f9abd10c3baee24590"
"1b9e027bd5cfc2cb5db82d4dc9677ac795ec500ecd47deee3b5da006d6d049b8"
"11d7511c78158de484232fc68daf8a45cf217d1c2fae693ff5871e8752d73b21"
"198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2"
"1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed"
"090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b"
"12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa"
),
{
fromHex("0000000000000000000000000000000000000000000000000000000000000001"),
calc_cost(2)
}
},
{
fromHex(
"2f2ea0b3da1e8ef11914acf8b2e1b32d99df51f5f4f206fc6b947eae860eddb6"
"068134ddb33dc888ef446b648d72338684d678d2eb2371c61a50734d78da4b72"
"25f83c8b6ab9de74e7da488ef02645c5a16a6652c3c71a15dc37fe3a5dcb7cb1"
"22acdedd6308e3bb230d226d16a105295f523a8a02bfc5e8bd2da135ac4c245d"
"065bbad92e7c4e31bf3757f1fe7362a63fbfee50e7dc68da116e67d600d9bf68"
"06d302580dc0661002994e7cd3a7f224e7ddc27802777486bf80f40e4ca3cfdb"
"186bac5188a98c45e6016873d107f5cd131f3a3e339d0375e58bd6219347b008"
"122ae2b09e539e152ec5364e7e2204b03d11d3caa038bfc7cd499f8176aacbee"
"1f39e4e4afc4bc74790a4a028aff2c3d2538731fb755edefd8cb48d6ea589b5e"
"283f150794b6736f670d6a1033f9b46c6f5204f50813eb85c8dc4b59db1c5d39"
"140d97ee4d2b36d99bc49974d18ecca3e7ad51011956051b464d9e27d46cc25e"
"0764bb98575bd466d32db7b15f582b2d5c452b36aa394b789366e5e3ca5aabd4"
"15794ab061441e51d01e94640b7e3084a07e02c78cf3103c542bc5b298669f21"
"1b88da1679b0b64a63b7e0e7bfe52aae524f73a55be7fe70c7e9bfc94b4cf0da"
"1213d2149b006137fcfb23036606f848d638d576a120ca981b5b1a5f9300b3ee"
"2276cf730cf493cd95d64677bbb75fc42db72513a4c1e387b476d056f80aa75f"
"21ee6226d31426322afcda621464d0611d226783262e21bb3bc86b537e986237"
"096df1f82dff337dd5972e32a8ad43e28a78a96a823ef1cd4debe12b6552ea5f"
),
{
fromHex("0000000000000000000000000000000000000000000000000000000000000001"),
calc_cost(3)
}
},
{
fromHex(
"20a754d2071d4d53903e3b31a7e98ad6882d58aec240ef981fdf0a9d22c5926a"
"29c853fcea789887315916bbeb89ca37edb355b4f980c9a12a94f30deeed3021"
"1213d2149b006137fcfb23036606f848d638d576a120ca981b5b1a5f9300b3ee"
"2276cf730cf493cd95d64677bbb75fc42db72513a4c1e387b476d056f80aa75f"
"21ee6226d31426322afcda621464d0611d226783262e21bb3bc86b537e986237"
"096df1f82dff337dd5972e32a8ad43e28a78a96a823ef1cd4debe12b6552ea5f"
"1abb4a25eb9379ae96c84fff9f0540abcfc0a0d11aeda02d4f37e4baf74cb0c1"
"1073b3ff2cdbb38755f8691ea59e9606696b3ff278acfc098fa8226470d03869"
"217cee0a9ad79a4493b5253e2e4e3a39fc2df38419f230d341f60cb064a0ac29"
"0a3d76f140db8418ba512272381446eb73958670f00cf46f1d9e64cba057b53c"
"26f64a8ec70387a13e41430ed3ee4a7db2059cc5fc13c067194bcc0cb49a9855"
"2fd72bd9edb657346127da132e5b82ab908f5816c826acb499e22f2412d1a2d7"
"0f25929bcb43d5a57391564615c9e70a992b10eafa4db109709649cf48c50dd2"
"198a1f162a73261f112401aa2db79c7dab1533c9935c77290a6ce3b191f2318d"
"198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2"
"1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed"
"090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b"
"12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa"
),
{
fromHex("0000000000000000000000000000000000000000000000000000000000000001"),
calc_cost(3)
}
}
};
return precompileGeneric(_message, inputOutput);
}
evmc::Result EVMHost::precompileBlake2f(evmc_message const&) noexcept
{
// TODO implement
return resultWithFailure();
}
evmc::Result EVMHost::precompileGeneric(
evmc_message const& _message,
std::map<bytes, EVMPrecompileOutput> const& _inOut) noexcept
{
bytes input(_message.input_data, _message.input_data + _message.input_size);
if (_inOut.count(input))
{
auto const& ret = _inOut.at(input);
return resultWithGas(_message.gas, ret.gas_used, ret.output);
}
else
return resultWithFailure();
}
evmc::Result EVMHost::resultWithFailure() noexcept
{
evmc::Result result;
result.status_code = EVMC_FAILURE;
return result;
}
evmc::Result EVMHost::resultWithGas(
int64_t gas_limit,
int64_t gas_required,
bytes const& _data
) noexcept
{
evmc::Result result;
if (gas_limit < gas_required)
{
result.status_code = EVMC_OUT_OF_GAS;
result.gas_left = 0;
}
else
{
result.status_code = EVMC_SUCCESS;
result.gas_left = gas_limit - gas_required;
}
result.output_data = _data.empty() ? nullptr : _data.data();
result.output_size = _data.size();
return result;
}
StorageMap const& EVMHost::get_address_storage(evmc::address const& _addr)
{
assertThrow(account_exists(_addr), Exception, "Account does not exist.");
return accounts[_addr].storage;
}
std::string EVMHostPrinter::state()
{
// Print state and execution trace.
if (m_host.account_exists(m_account))
{
storage();
balance();
}
else
selfdestructRecords();
callRecords();
return m_stateStream.str();
}
void EVMHostPrinter::storage()
{
for (auto const& [slot, value]: m_host.get_address_storage(m_account))
if (m_host.get_storage(m_account, slot))
m_stateStream << " "
<< m_host.convertFromEVMC(slot)
<< ": "
<< m_host.convertFromEVMC(value.current)
<< std::endl;
}
void EVMHostPrinter::balance()
{
m_stateStream << "BALANCE "
<< m_host.convertFromEVMC(m_host.get_balance(m_account))
<< std::endl;
}
void EVMHostPrinter::selfdestructRecords()
{
for (auto const& record: m_host.recorded_selfdestructs)
for (auto const& beneficiary: record.second)
m_stateStream << "SELFDESTRUCT"
<< " BENEFICIARY "
<< m_host.convertFromEVMC(beneficiary)
<< std::endl;
}
void EVMHostPrinter::callRecords()
{
static auto constexpr callKind = [](evmc_call_kind _kind) -> std::string
{
switch (_kind)
{
case evmc_call_kind::EVMC_CALL:
return "CALL";
case evmc_call_kind::EVMC_DELEGATECALL:
return "DELEGATECALL";
case evmc_call_kind::EVMC_CALLCODE:
return "CALLCODE";
case evmc_call_kind::EVMC_CREATE:
return "CREATE";
case evmc_call_kind::EVMC_CREATE2:
return "CREATE2";
default:
assertThrow(false, Exception, "Invalid call kind.");
}
};
for (auto const& record: m_host.recorded_calls)
m_stateStream << callKind(record.kind)
<< " VALUE "
<< m_host.convertFromEVMC(record.value)
<< std::endl;
}
| 47,648
|
C++
|
.cpp
| 1,194
| 36.407035
| 271
| 0.81191
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,899
|
soltest.cpp
|
ethereum_solidity/test/soltest.cpp
|
/*
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 boostTest.cpp
* @author Marko Simovic <markobarko@gmail.com>
* @date 2014
* Stub for generating main boost.test module.
* Original code taken from boost sources.
*/
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable:4535) // calling _set_se_translator requires /EHa
#endif
#include <boost/test/unit_test.hpp>
#include <boost/test/tree/traverse.hpp>
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
#pragma GCC diagnostic pop
#pragma GCC diagnostic pop
#include <test/InteractiveTests.h>
#include <test/Common.h>
#include <test/EVMHost.h>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
#include <string>
using namespace boost::unit_test;
using namespace solidity::frontend::test;
namespace fs = boost::filesystem;
namespace
{
void removeTestSuite(std::string const& _name)
{
master_test_suite_t& master = framework::master_test_suite();
auto id = master.get(_name);
soltestAssert(id != INV_TEST_UNIT_ID, "Removing non-existent test suite!");
master.remove(id);
}
/**
* Class that traverses the boost test tree and removes unit tests that are
* not in the current batch.
*/
class BoostBatcher: public test_tree_visitor
{
public:
BoostBatcher(solidity::test::Batcher& _batcher):
m_batcher(_batcher)
{}
void visit(test_case const& _testCase) override
{
if (!m_batcher.checkAndAdvance())
// disabling them would be nicer, but it does not work like this:
// const_cast<test_case&>(_testCase).p_run_status.value = test_unit::RS_DISABLED;
m_path.back()->remove(_testCase.p_id);
}
bool test_suite_start(test_suite const& _testSuite) override
{
m_path.push_back(&const_cast<test_suite&>(_testSuite));
return test_tree_visitor::test_suite_start(_testSuite);
}
void test_suite_finish(test_suite const& _testSuite) override
{
m_path.pop_back();
test_tree_visitor::test_suite_finish(_testSuite);
}
private:
solidity::test::Batcher& m_batcher;
std::vector<test_suite*> m_path;
};
void runTestCase(TestCase::Config const& _config, TestCase::TestCaseCreator const& _testCaseCreator)
{
try
{
std::stringstream errorStream;
auto testCase = _testCaseCreator(_config);
if (testCase->shouldRun())
switch (testCase->run(errorStream))
{
case TestCase::TestResult::Success:
break;
case TestCase::TestResult::Failure:
BOOST_ERROR("Test expectation mismatch.\n" + errorStream.str());
break;
case TestCase::TestResult::FatalError:
BOOST_ERROR("Fatal error during test.\n" + errorStream.str());
break;
}
}
catch (...)
{
BOOST_ERROR("Exception during extracted test: " << boost::current_exception_diagnostic_information());
}
}
int registerTests(
boost::unit_test::test_suite& _suite,
boost::filesystem::path const& _basepath,
boost::filesystem::path const& _path,
std::vector<std::string> const& _labels,
TestCase::TestCaseCreator _testCaseCreator,
solidity::test::Batcher& _batcher
)
{
int numTestsAdded = 0;
fs::path fullpath = _basepath / _path;
TestCase::Config config{
fullpath.string(),
solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion(),
solidity::test::CommonOptions::get().vmPaths,
solidity::test::CommonOptions::get().enforceGasTest,
solidity::test::CommonOptions::get().enforceGasTestMinValue,
};
if (fs::is_directory(fullpath))
{
test_suite* sub_suite = BOOST_TEST_SUITE(_path.filename().string());
for (auto const& entry: boost::iterator_range<fs::directory_iterator>(
fs::directory_iterator(fullpath),
fs::directory_iterator()
))
if (
solidity::test::isValidSemanticTestPath(entry) &&
(fs::is_directory(entry.path()) || TestCase::isTestFilename(entry.path().filename()))
)
numTestsAdded += registerTests(
*sub_suite,
_basepath, _path / entry.path().filename(),
_labels,
_testCaseCreator,
_batcher
);
_suite.add(sub_suite);
}
else
{
// TODO would be better to set the test to disabled.
if (_batcher.checkAndAdvance())
{
// This must be a vector of unique_ptrs because Boost.Test keeps the equivalent of a string_view to the filename
// that is passed in. If the strings were stored directly in the vector, pointers/references to them would be
// invalidated on reallocation.
static std::vector<std::unique_ptr<std::string const>> filenames;
filenames.emplace_back(std::make_unique<std::string>(_path.string()));
auto test_case = make_test_case(
[config, _testCaseCreator]
{
BOOST_REQUIRE_NO_THROW({
runTestCase(config, _testCaseCreator);
});
},
_path.stem().string(),
*filenames.back(),
0
);
for (auto const& _label: _labels)
test_case->add_label(_label);
_suite.add(test_case);
numTestsAdded = 1;
}
}
return numTestsAdded;
}
bool initializeOptions()
{
auto const& suite = boost::unit_test::framework::master_test_suite();
auto options = std::make_unique<solidity::test::CommonOptions>();
bool shouldContinue = options->parse(suite.argc, suite.argv);
if (!shouldContinue)
return false;
options->validate();
solidity::test::CommonOptions::setSingleton(std::move(options));
return true;
}
}
// TODO: Prototype -- why isn't this declared in the boost headers?
// TODO: replace this with a (global) fixture.
test_suite* init_unit_test_suite(int /*argc*/, char* /*argv*/[]);
test_suite* init_unit_test_suite(int /*argc*/, char* /*argv*/[])
{
using namespace solidity::test;
master_test_suite_t& master = framework::master_test_suite();
master.p_name.value = "SolidityTests";
try
{
bool shouldContinue = initializeOptions();
if (!shouldContinue)
exit(EXIT_SUCCESS);
if (!solidity::test::loadVMs(solidity::test::CommonOptions::get()))
exit(EXIT_FAILURE);
if (solidity::test::CommonOptions::get().disableSemanticTests)
std::cout << std::endl << "--- SKIPPING ALL SEMANTICS TESTS ---" << std::endl << std::endl;
if (!solidity::test::CommonOptions::get().enforceGasTest)
std::cout << std::endl << "WARNING :: Gas Cost Expectations are not being enforced" << std::endl << std::endl;
Batcher batcher(CommonOptions::get().selectedBatch, CommonOptions::get().batches);
if (CommonOptions::get().batches > 1)
std::cout << "Batch " << CommonOptions::get().selectedBatch << " out of " << CommonOptions::get().batches << std::endl;
// Batch the boost tests
BoostBatcher boostBatcher(batcher);
traverse_test_tree(master, boostBatcher, true);
// Include the interactive tests in the automatic tests as well
for (auto const& ts: g_interactiveTestsuites)
{
auto const& options = solidity::test::CommonOptions::get();
if (ts.smt && options.disableSMT)
continue;
if (ts.needsVM && solidity::test::CommonOptions::get().disableSemanticTests)
continue;
//TODO
//solAssert(
registerTests(
master,
options.testPath / ts.path,
ts.subpath,
ts.labels,
ts.testCaseCreator,
batcher
);
// > 0, std::string("no ") + ts.title + " tests found");
}
if (solidity::test::CommonOptions::get().disableSemanticTests)
{
for (auto suite: {
"ABIDecoderTest",
"ABIEncoderTest",
"SolidityAuctionRegistrar",
"SolidityWallet",
"GasMeterTests",
"GasCostTests",
"SolidityEndToEndTest",
"SolidityOptimizer"
})
removeTestSuite(suite);
}
}
catch (solidity::test::ConfigException const& exception)
{
std::cerr << exception.what() << std::endl;
exit(EXIT_FAILURE);
}
catch (std::runtime_error const& exception)
{
std::cerr << exception.what() << std::endl;
exit(EXIT_FAILURE);
}
return nullptr;
}
// BOOST_TEST_DYN_LINK should be defined if user want to link against shared boost test library
#ifdef BOOST_TEST_DYN_LINK
// Because we want to have customized initialization function and support shared boost libraries at the same time,
// we are forced to customize the entry point.
// see: https://www.boost.org/doc/libs/1_67_0/libs/test/doc/html/boost_test/adv_scenarios/shared_lib_customizations/init_func.html
int main(int argc, char* argv[])
{
auto init_unit_test = []() -> bool { init_unit_test_suite(0, nullptr); return true; };
return boost::unit_test::unit_test_main(init_unit_test, argc, argv);
}
#endif
| 9,047
|
C++
|
.cpp
| 270
| 30.622222
| 130
| 0.723475
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,900
|
TestCaseReader.cpp
|
ethereum_solidity/test/TestCaseReader.cpp
|
/*
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
#include <test/TestCaseReader.h>
#include <libsolutil/CommonIO.h>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
using namespace solidity::frontend::test;
namespace fs = boost::filesystem;
TestCaseReader::TestCaseReader(std::string const& _filename): m_fileStream(_filename), m_fileName(_filename)
{
if (!m_fileStream)
BOOST_THROW_EXCEPTION(std::runtime_error("Cannot open file: \"" + _filename + "\"."));
m_fileStream.exceptions(std::ios::badbit);
std::tie(m_sources, m_lineNumber) = parseSourcesAndSettingsWithLineNumber(m_fileStream);
m_unreadSettings = m_settings;
}
TestCaseReader::TestCaseReader(std::istringstream const& _str)
{
std::tie(m_sources, m_lineNumber) = parseSourcesAndSettingsWithLineNumber(
static_cast<std::istream&>(const_cast<std::istringstream&>(_str))
);
}
std::string const& TestCaseReader::source() const
{
if (m_sources.sources.size() != 1)
BOOST_THROW_EXCEPTION(std::runtime_error("Expected single source definition, but got multiple sources."));
return m_sources.sources.at(m_sources.mainSourceFile);
}
std::string TestCaseReader::simpleExpectations()
{
return parseSimpleExpectations(m_fileStream);
}
bool TestCaseReader::boolSetting(std::string const& _name, bool _defaultValue)
{
if (m_settings.count(_name) == 0)
return _defaultValue;
m_unreadSettings.erase(_name);
std::string value = m_settings.at(_name);
if (value == "false")
return false;
if (value == "true")
return true;
BOOST_THROW_EXCEPTION(std::runtime_error("Invalid Boolean value: " + value + "."));
}
size_t TestCaseReader::sizetSetting(std::string const& _name, size_t _defaultValue)
{
if (m_settings.count(_name) == 0)
return _defaultValue;
m_unreadSettings.erase(_name);
static_assert(sizeof(unsigned long) <= sizeof(size_t));
return stoul(m_settings.at(_name));
}
std::string TestCaseReader::stringSetting(std::string const& _name, std::string const& _defaultValue)
{
if (m_settings.count(_name) == 0)
return _defaultValue;
m_unreadSettings.erase(_name);
return m_settings.at(_name);
}
void TestCaseReader::ensureAllSettingsRead() const
{
if (!m_unreadSettings.empty())
BOOST_THROW_EXCEPTION(std::runtime_error(
"Unknown setting(s): " +
util::joinHumanReadable(m_unreadSettings | ranges::views::keys)
));
}
std::pair<SourceMap, size_t> TestCaseReader::parseSourcesAndSettingsWithLineNumber(std::istream& _stream)
{
std::map<std::string, std::string> sources;
std::map<std::string, boost::filesystem::path> externalSources;
std::string currentSourceName;
std::string currentSource;
std::string line;
size_t lineNumber = 1;
static std::string const externalSourceDelimiterStart("==== ExternalSource:");
static std::string const sourceDelimiterStart("==== Source:");
static std::string const sourceDelimiterEnd("====");
static std::string const comment("// ");
static std::string const settingsDelimiter("// ====");
static std::string const expectationsDelimiter("// ----");
bool sourcePart = true;
while (getline(_stream, line))
{
lineNumber++;
// Anything below the delimiter is left up to the test case to process in a custom way.
if (boost::algorithm::starts_with(line, expectationsDelimiter))
break;
if (boost::algorithm::starts_with(line, settingsDelimiter))
sourcePart = false;
else if (sourcePart)
{
if (boost::algorithm::starts_with(line, sourceDelimiterStart) && boost::algorithm::ends_with(line, sourceDelimiterEnd))
{
if (!(currentSourceName.empty() && currentSource.empty()))
sources[currentSourceName] = std::move(currentSource);
currentSource = {};
currentSourceName = boost::trim_copy(line.substr(
sourceDelimiterStart.size(),
line.size() - sourceDelimiterEnd.size() - sourceDelimiterStart.size()
));
if (sources.count(currentSourceName))
BOOST_THROW_EXCEPTION(std::runtime_error("Multiple definitions of test source \"" + currentSourceName + "\"."));
}
else if (boost::algorithm::starts_with(line, externalSourceDelimiterStart) && boost::algorithm::ends_with(line, sourceDelimiterEnd))
{
std::string externalSourceString = boost::trim_copy(line.substr(
externalSourceDelimiterStart.size(),
line.size() - sourceDelimiterEnd.size() - externalSourceDelimiterStart.size()
));
std::string externalSourceName;
size_t remappingPos = externalSourceString.find('=');
// Does the external source define a remapping?
if (remappingPos != std::string::npos)
{
externalSourceName = boost::trim_copy(externalSourceString.substr(0, remappingPos));
externalSourceString = boost::trim_copy(externalSourceString.substr(remappingPos + 1));
}
else
externalSourceName = externalSourceString;
soltestAssert(!externalSourceName.empty(), "");
fs::path externalSourceTarget(externalSourceString);
fs::path testCaseParentDir = m_fileName.parent_path();
if (!externalSourceTarget.is_relative() || !externalSourceTarget.root_path().empty())
// NOTE: UNC paths (ones starting with // or \\) are considered relative by Boost
// since they have an empty root directory (but non-empty root name).
BOOST_THROW_EXCEPTION(std::runtime_error("External Source paths need to be relative to the location of the test case."));
fs::path externalSourceFullPath = testCaseParentDir / externalSourceTarget;
std::string externalSourceContent;
if (!fs::exists(externalSourceFullPath))
BOOST_THROW_EXCEPTION(std::runtime_error("External Source '" + externalSourceTarget.string() + "' not found."));
else
externalSourceContent = util::readFileAsString(externalSourceFullPath);
if (sources.count(externalSourceName))
BOOST_THROW_EXCEPTION(std::runtime_error("Multiple definitions of test source \"" + externalSourceName + "\"."));
sources[externalSourceName] = externalSourceContent;
externalSources[externalSourceName] = externalSourceTarget;
}
else
currentSource += line + "\n";
}
else if (boost::algorithm::starts_with(line, comment))
{
size_t colon = line.find(':');
if (colon == std::string::npos)
BOOST_THROW_EXCEPTION(std::runtime_error(std::string("Expected \":\" inside setting.")));
std::string key = line.substr(comment.size(), colon - comment.size());
std::string value = line.substr(colon + 1);
boost::algorithm::trim(key);
boost::algorithm::trim(value);
m_settings[key] = value;
}
else
BOOST_THROW_EXCEPTION(std::runtime_error(std::string("Expected \"//\" or \"// ---\" to terminate settings and source.")));
}
// Register the last source as the main one
sources[currentSourceName] = currentSource;
return {{std::move(sources), std::move(externalSources), std::move(currentSourceName)}, lineNumber};
}
std::string TestCaseReader::parseSimpleExpectations(std::istream& _file)
{
std::string result;
std::string line;
while (std::getline(_file, line))
if (boost::algorithm::starts_with(line, "// "))
result += line.substr(3) + "\n";
else if (line == "//")
result += "\n";
else
BOOST_THROW_EXCEPTION(std::runtime_error("Test expectations must start with \"// \"."));
return result;
}
| 7,836
|
C++
|
.cpp
| 184
| 39.505435
| 135
| 0.735931
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,901
|
Metadata.cpp
|
ethereum_solidity/test/Metadata.cpp
|
/*
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
/**
* @date 2017
* Metadata processing helpers.
*/
#include <string>
#include <iostream>
#include <libsolutil/Assertions.h>
#include <libsolutil/CommonData.h>
#include <test/Metadata.h>
namespace solidity::test
{
bytes onlyMetadata(bytes const& _bytecode)
{
size_t size = _bytecode.size();
if (size < 5)
return bytes{};
size_t metadataSize = (static_cast<size_t>(_bytecode[size - 2]) << 8ul) + static_cast<size_t>(_bytecode[size - 1]);
if (size < (metadataSize + 2))
return bytes{};
// Sanity check: assume the first byte is a fixed-size CBOR array with 1, 2 or 3 entries
unsigned char firstByte = _bytecode[size - metadataSize - 2];
if (firstByte != 0xa1 && firstByte != 0xa2 && firstByte != 0xa3)
return bytes{};
return bytes(_bytecode.end() - static_cast<ptrdiff_t>(metadataSize) - 2, _bytecode.end() - 2);
}
bytes bytecodeSansMetadata(bytes const& _bytecode)
{
size_t metadataSize = onlyMetadata(_bytecode).size();
if (metadataSize == 0)
return bytes{};
return bytes(_bytecode.begin(), _bytecode.end() - static_cast<ptrdiff_t>(metadataSize) - 2);
}
std::string bytecodeSansMetadata(std::string const& _bytecode)
{
return util::toHex(bytecodeSansMetadata(fromHex(_bytecode, util::WhenError::Throw)));
}
DEV_SIMPLE_EXCEPTION(CBORException);
class TinyCBORParser
{
public:
explicit TinyCBORParser(bytes const& _metadata): m_pos(0), m_metadata(_metadata)
{
assertThrow((m_pos + 1) < _metadata.size(), CBORException, "Input too short.");
}
unsigned mapItemCount()
{
assertThrow(nextType() == MajorType::Map, CBORException, "Fixed-length map expected.");
return readLength();
}
std::string readKey()
{
return readString();
}
std::string readValue()
{
switch(nextType())
{
case MajorType::ByteString:
return util::toHex(readBytes(readLength()));
case MajorType::TextString:
return readString();
case MajorType::SimpleData:
{
unsigned value = nextImmediate();
m_pos++;
if (value == 20)
return "false";
else if (value == 21)
return "true";
else
{
assertThrow(false, CBORException, "Unsupported simple value (not a boolean).");
return ""; // unreachable, but prevents compiler warning.
}
}
default:
assertThrow(false, CBORException, "Unsupported value type.");
}
}
private:
enum class MajorType
{
ByteString,
TextString,
Map,
SimpleData
};
MajorType nextType() const
{
unsigned value = (m_metadata.at(m_pos) >> 5) & 0x7;
switch (value)
{
case 2: return MajorType::ByteString;
case 3: return MajorType::TextString;
case 5: return MajorType::Map;
case 7: return MajorType::SimpleData;
default: assertThrow(false, CBORException, "Unsupported major type.");
}
}
unsigned nextImmediate() const { return m_metadata.at(m_pos) & 0x1f; }
unsigned readLength()
{
unsigned length = m_metadata.at(m_pos++) & 0x1f;
if (length < 24)
return length;
if (length == 24)
return m_metadata.at(m_pos++);
// Unsupported length kind. (Only by this parser.)
assertThrow(false, CBORException, std::string("Unsupported length ") + std::to_string(length));
}
bytes readBytes(unsigned length)
{
bytes ret{m_metadata.begin() + static_cast<int>(m_pos), m_metadata.begin() + static_cast<int>(m_pos + length)};
m_pos += length;
return ret;
}
std::string readString()
{
// Expect a text string.
assertThrow(nextType() == MajorType::TextString, CBORException, "String expected.");
bytes tmp{readBytes(readLength())};
return std::string{tmp.begin(), tmp.end()};
}
unsigned m_pos;
bytes const& m_metadata;
};
std::optional<std::map<std::string, std::string>> parseCBORMetadata(bytes const& _metadata)
{
try
{
TinyCBORParser parser(_metadata);
std::map<std::string, std::string> ret;
unsigned count = parser.mapItemCount();
for (unsigned i = 0; i < count; i++)
{
std::string key = parser.readKey();
std::string value = parser.readValue();
ret[std::move(key)] = std::move(value);
}
return ret;
}
catch (CBORException const&)
{
return {};
}
}
bool isValidMetadata(std::string const& _serialisedMetadata)
{
Json metadata;
if (!util::jsonParseStrict(_serialisedMetadata, metadata))
return false;
return isValidMetadata(metadata);
}
bool isValidMetadata(Json const& _metadata)
{
if (
!_metadata.is_object() ||
!_metadata.contains("version") ||
!_metadata.contains("language") ||
!_metadata.contains("compiler") ||
!_metadata.contains("settings") ||
!_metadata.contains("sources") ||
!_metadata.contains("output") ||
!_metadata["settings"].contains("evmVersion") ||
!_metadata["settings"].contains("metadata") ||
!_metadata["settings"]["metadata"].contains("bytecodeHash")
)
return false;
if (!_metadata["version"].is_number() || _metadata["version"] != 1)
return false;
if (!_metadata["language"].is_string() || _metadata["language"].get<std::string>() != "Solidity")
return false;
/// @TODO add more strict checks
return true;
}
} // end namespaces
| 5,677
|
C++
|
.cpp
| 190
| 27.278947
| 116
| 0.710132
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,902
|
Common.cpp
|
ethereum_solidity/test/solc/Common.cpp
|
/*
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
#include <test/solc/Common.h>
#include <test/libsolidity/util/Common.h>
#include <solc/CommandLineInterface.h>
#include <sstream>
using namespace solidity::frontend;
std::vector<char const*> test::makeArgv(std::vector<std::string> const& _commandLine)
{
size_t argc = _commandLine.size();
std::vector<char const*> argv(_commandLine.size() + 1);
// C++ standard mandates argv[argc] to be NULL
argv[argc] = nullptr;
for (size_t i = 0; i < argc; ++i)
argv[i] = _commandLine[i].c_str();
return argv;
}
test::OptionsReaderAndMessages test::parseCommandLineAndReadInputFiles(
std::vector<std::string> const& _commandLine,
std::string const& _standardInputContent
)
{
std::vector<char const*> argv = makeArgv(_commandLine);
std::stringstream sin(_standardInputContent), sout, serr;
CommandLineInterface cli(sin, sout, serr);
bool success = cli.parseArguments(static_cast<int>(_commandLine.size()), argv.data());
cli.readInputFiles();
return {
success,
cli.options(),
cli.fileReader(),
cli.standardJsonInput(),
sout.str(),
stripPreReleaseWarning(serr.str()),
};
}
test::OptionsReaderAndMessages test::runCLI(
std::vector<std::string> const& _commandLine,
std::string const& _standardInputContent
)
{
std::vector<char const*> argv = makeArgv(_commandLine);
std::stringstream sin(_standardInputContent), sout, serr;
CommandLineInterface cli(sin, sout, serr);
bool success = cli.run(static_cast<int>(_commandLine.size()), argv.data());
return {
success,
cli.options(),
cli.fileReader(),
cli.standardJsonInput(),
sout.str(),
stripPreReleaseWarning(serr.str()),
};
}
| 2,300
|
C++
|
.cpp
| 66
| 32.712121
| 87
| 0.756196
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,903
|
CommandLineParser.cpp
|
ethereum_solidity/test/solc/CommandLineParser.cpp
|
/*
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
/// Unit tests for solc/CommandLineParser.h
#include <solc/CommandLineParser.h>
#include <solc/Exceptions.h>
#include <test/solc/Common.h>
#include <test/Common.h>
#include <test/libsolidity/util/SoltestErrors.h>
#include <libsolutil/CommonData.h>
#include <liblangutil/EVMVersion.h>
#include <libsmtutil/SolverInterface.h>
#include <libsolidity/interface/Version.h>
#include <map>
#include <optional>
#include <ostream>
#include <sstream>
#include <string>
#include <vector>
using namespace solidity::frontend;
using namespace solidity::langutil;
using namespace solidity::util;
using namespace solidity::yul;
namespace
{
CommandLineOptions parseCommandLine(std::vector<std::string> const& _commandLine)
{
std::vector<char const*> argv = test::makeArgv(_commandLine);
CommandLineParser cliParser;
cliParser.parse(static_cast<int>(_commandLine.size()), argv.data());
return cliParser.options();
}
} // namespace
namespace solidity::frontend::test
{
BOOST_AUTO_TEST_SUITE(CommandLineParserTest)
BOOST_AUTO_TEST_CASE(no_options)
{
std::vector<std::string> commandLine = {"solc", "contract.sol"};
CommandLineOptions expectedOptions;
expectedOptions.input.paths = {"contract.sol"};
expectedOptions.modelChecker.initialize = true;
expectedOptions.modelChecker.settings = {};
CommandLineOptions parsedOptions = parseCommandLine(commandLine);
BOOST_TEST(parsedOptions == expectedOptions);
}
BOOST_AUTO_TEST_CASE(help_license_version)
{
std::map<std::string, InputMode> expectedModePerOption = {
{"--help", InputMode::Help},
{"--license", InputMode::License},
{"--version", InputMode::Version},
};
for (auto const& [option, expectedMode]: expectedModePerOption)
{
CommandLineOptions parsedOptions = parseCommandLine({"solc", option});
CommandLineOptions expectedOptions;
expectedOptions.input.mode = expectedMode;
BOOST_TEST(parsedOptions == expectedOptions);
}
}
BOOST_AUTO_TEST_CASE(cli_mode_options)
{
for (InputMode inputMode: {InputMode::Compiler, InputMode::CompilerWithASTImport})
{
std::vector<std::string> commandLine = {
"solc",
"contract.sol", // Both modes do not care about file names, just about
"/tmp/projects/token.sol", // their content. They also both support stdin.
"/home/user/lib/dex.sol",
"file",
"input.json",
"-",
"/tmp=/usr/lib/",
"a:b=c/d",
":contract.sol=",
"--base-path=/home/user/",
"--include-path=/usr/lib/include/",
"--include-path=/home/user/include",
"--allow-paths=/tmp,/home,project,../contracts",
"--ignore-missing",
"--output-dir=/tmp/out",
"--overwrite",
"--evm-version=spuriousDragon",
"--via-ir",
"--experimental-via-ir",
"--revert-strings=strip",
"--debug-info=location",
"--pretty-json",
"--json-indent=7",
"--no-color",
"--error-codes",
"--libraries="
"dir1/file1.sol:L=0x1234567890123456789012345678901234567890,"
"dir2/file2.sol:L=0x1111122222333334444455555666667777788888",
"--ast-compact-json", "--asm", "--asm-json", "--opcodes", "--bin", "--bin-runtime", "--abi",
"--ir", "--ir-ast-json", "--ir-optimized", "--ir-optimized-ast-json", "--hashes", "--userdoc", "--devdoc", "--metadata",
"--yul-cfg-json",
"--storage-layout", "--transient-storage-layout",
"--gas",
"--combined-json="
"abi,metadata,bin,bin-runtime,opcodes,asm,storage-layout,transient-storage-layout,generated-sources,generated-sources-runtime,"
"srcmap,srcmap-runtime,function-debug,function-debug-runtime,hashes,devdoc,userdoc,ast",
"--metadata-hash=swarm",
"--metadata-literal",
"--optimize",
"--optimize-yul",
"--optimize-runs=1000",
"--yul-optimizations=agf",
"--model-checker-bmc-loop-iterations=2",
"--model-checker-contracts=contract1.yul:A,contract2.yul:B",
"--model-checker-div-mod-no-slacks",
"--model-checker-engine=bmc",
"--model-checker-ext-calls=trusted",
"--model-checker-invariants=contract,reentrancy",
"--model-checker-show-proved-safe",
"--model-checker-show-unproved",
"--model-checker-show-unsupported",
"--model-checker-solvers=z3,smtlib2",
"--model-checker-targets=underflow,divByZero",
"--model-checker-timeout=5"
};
if (inputMode == InputMode::CompilerWithASTImport)
commandLine += std::vector<std::string>{
"--import-ast",
};
CommandLineOptions expectedOptions;
expectedOptions.input.mode = inputMode;
expectedOptions.input.paths = {"contract.sol", "/tmp/projects/token.sol", "/home/user/lib/dex.sol", "file", "input.json"};
expectedOptions.input.remappings = {
{"", "/tmp", "/usr/lib/"},
{"a", "b", "c/d"},
{"", "contract.sol", ""},
};
expectedOptions.input.addStdin = true;
expectedOptions.input.basePath = "/home/user/";
expectedOptions.input.includePaths = {"/usr/lib/include/", "/home/user/include"};
expectedOptions.input.allowedDirectories = {"/tmp", "/home", "project", "../contracts", "c", "/usr/lib"};
expectedOptions.input.ignoreMissingFiles = true;
expectedOptions.output.dir = "/tmp/out";
expectedOptions.output.overwriteFiles = true;
expectedOptions.output.evmVersion = EVMVersion::spuriousDragon();
expectedOptions.output.viaIR = true;
expectedOptions.output.revertStrings = RevertStrings::Strip;
expectedOptions.output.debugInfoSelection = DebugInfoSelection::fromString("location");
expectedOptions.formatting.json = JsonFormat{JsonFormat::Pretty, 7};
expectedOptions.linker.libraries = {
{"dir1/file1.sol:L", h160("1234567890123456789012345678901234567890")},
{"dir2/file2.sol:L", h160("1111122222333334444455555666667777788888")},
};
expectedOptions.formatting.coloredOutput = false;
expectedOptions.formatting.withErrorIds = true;
expectedOptions.compiler.outputs = {
true, true, true, true, true,
true, true, true, true, true,
true, true, true, true, true,
true, true, true,
};
expectedOptions.compiler.estimateGas = true;
expectedOptions.compiler.combinedJsonRequests = {
true, true, true, true, true,
true, true, true, true, true,
true, true, true, true, true,
true, true, true,
};
expectedOptions.metadata.hash = CompilerStack::MetadataHash::Bzzr1;
expectedOptions.metadata.literalSources = true;
expectedOptions.optimizer.optimizeEvmasm = true;
expectedOptions.optimizer.optimizeYul = true;
expectedOptions.optimizer.expectedExecutionsPerDeployment = 1000;
expectedOptions.optimizer.yulSteps = "agf";
expectedOptions.modelChecker.initialize = true;
expectedOptions.modelChecker.settings = {
2,
{{{"contract1.yul", {"A"}}, {"contract2.yul", {"B"}}}},
true,
{true, false},
{ModelCheckerExtCalls::Mode::TRUSTED},
{{InvariantType::Contract, InvariantType::Reentrancy}},
false, // --model-checker-print-query
true,
true,
true,
{false, false, true, true},
{{VerificationTargetType::Underflow, VerificationTargetType::DivByZero}},
5,
};
CommandLineOptions parsedOptions = parseCommandLine(commandLine);
BOOST_TEST(parsedOptions == expectedOptions);
}
}
BOOST_AUTO_TEST_CASE(no_cbor_metadata)
{
std::vector<std::string> commandLine = {"solc", "--no-cbor-metadata", "contract.sol"};
CommandLineOptions parsedOptions = parseCommandLine(commandLine);
bool assert = parsedOptions.metadata.format == CompilerStack::MetadataFormat::NoMetadata;
BOOST_TEST(assert);
}
BOOST_AUTO_TEST_CASE(no_import_callback)
{
std::vector<std::vector<std::string>> commandLinePerInputMode = {
{"solc", "--no-import-callback", "contract.sol"},
{"solc", "--standard-json", "--no-import-callback", "input.json"},
{"solc", "--assemble", "--no-import-callback", "input.yul"},
{"solc", "--strict-assembly", "--no-import-callback", "input.yul"},
{"solc", "--import-ast", "--no-import-callback", "ast.json"},
{"solc", "--link", "--no-import-callback", "input.bin"},
};
for (auto const& commandLine: commandLinePerInputMode)
{
CommandLineOptions parsedOptions = parseCommandLine(commandLine);
BOOST_TEST(parsedOptions.input.noImportCallback);
}
}
BOOST_AUTO_TEST_CASE(via_ir_options)
{
BOOST_TEST(!parseCommandLine({"solc", "contract.sol"}).output.viaIR);
for (std::string viaIrOption: {"--via-ir", "--experimental-via-ir"})
BOOST_TEST(parseCommandLine({"solc", viaIrOption, "contract.sol"}).output.viaIR);
}
BOOST_AUTO_TEST_CASE(assembly_mode_options)
{
static std::vector<std::tuple<std::vector<std::string>, YulStack::Machine, YulStack::Language>> const allowedCombinations = {
{{"--machine=evm", "--yul-dialect=evm", "--assemble"}, YulStack::Machine::EVM, YulStack::Language::StrictAssembly},
{{"--machine=evm", "--yul-dialect=evm", "--strict-assembly"}, YulStack::Machine::EVM, YulStack::Language::StrictAssembly},
{{"--machine=evm", "--assemble"}, YulStack::Machine::EVM, YulStack::Language::Assembly},
{{"--machine=evm", "--strict-assembly"}, YulStack::Machine::EVM, YulStack::Language::StrictAssembly},
{{"--assemble"}, YulStack::Machine::EVM, YulStack::Language::Assembly},
{{"--strict-assembly"}, YulStack::Machine::EVM, YulStack::Language::StrictAssembly},
};
for (auto const& [assemblyOptions, expectedMachine, expectedLanguage]: allowedCombinations)
{
std::vector<std::string> commandLine = {
"solc",
"contract.yul",
"/tmp/projects/token.yul",
"/home/user/lib/dex.yul",
"file",
"input.json",
"-",
"/tmp=/usr/lib/",
"a:b=c/d",
":contract.yul=",
"--base-path=/home/user/",
"--include-path=/usr/lib/include/",
"--include-path=/home/user/include",
"--allow-paths=/tmp,/home,project,../contracts",
"--ignore-missing",
"--overwrite",
"--evm-version=spuriousDragon",
"--revert-strings=strip", // Accepted but has no effect in assembly mode
"--debug-info=location",
"--pretty-json",
"--json-indent=1",
"--no-color",
"--error-codes",
"--libraries="
"dir1/file1.sol:L=0x1234567890123456789012345678901234567890,"
"dir2/file2.sol:L=0x1111122222333334444455555666667777788888",
"--asm",
"--asm-json",
"--bin",
"--ir-optimized",
"--ast-compact-json",
};
commandLine += assemblyOptions;
if (expectedLanguage == YulStack::Language::StrictAssembly)
commandLine += std::vector<std::string>{
"--optimize",
"--optimize-runs=1000",
"--yul-optimizations=agf",
};
CommandLineOptions expectedOptions;
expectedOptions.input.mode = InputMode::Assembler;
expectedOptions.input.paths = {"contract.yul", "/tmp/projects/token.yul", "/home/user/lib/dex.yul", "file", "input.json"};
expectedOptions.input.remappings = {
{"", "/tmp", "/usr/lib/"},
{"a", "b", "c/d"},
{"", "contract.yul", ""},
};
expectedOptions.input.addStdin = true;
expectedOptions.input.basePath = "/home/user/";
expectedOptions.input.includePaths = {"/usr/lib/include/", "/home/user/include"};
expectedOptions.input.allowedDirectories = {"/tmp", "/home", "project", "../contracts", "c", "/usr/lib"};
expectedOptions.input.ignoreMissingFiles = true;
expectedOptions.output.overwriteFiles = true;
expectedOptions.output.evmVersion = EVMVersion::spuriousDragon();
expectedOptions.output.revertStrings = RevertStrings::Strip;
expectedOptions.output.debugInfoSelection = DebugInfoSelection::fromString("location");
expectedOptions.formatting.json = JsonFormat {JsonFormat::Pretty, 1};
expectedOptions.assembly.targetMachine = expectedMachine;
expectedOptions.assembly.inputLanguage = expectedLanguage;
expectedOptions.linker.libraries = {
{"dir1/file1.sol:L", h160("1234567890123456789012345678901234567890")},
{"dir2/file2.sol:L", h160("1111122222333334444455555666667777788888")},
};
expectedOptions.formatting.coloredOutput = false;
expectedOptions.formatting.withErrorIds = true;
expectedOptions.compiler.outputs.asm_ = true;
expectedOptions.compiler.outputs.asmJson = true;
expectedOptions.compiler.outputs.binary = true;
expectedOptions.compiler.outputs.irOptimized = true;
expectedOptions.compiler.outputs.astCompactJson = true;
if (expectedLanguage == YulStack::Language::StrictAssembly)
{
expectedOptions.optimizer.optimizeEvmasm = true;
expectedOptions.optimizer.optimizeYul = true;
expectedOptions.optimizer.yulSteps = "agf";
expectedOptions.optimizer.expectedExecutionsPerDeployment = 1000;
}
CommandLineOptions parsedOptions = parseCommandLine(commandLine);
BOOST_TEST(parsedOptions == expectedOptions);
}
}
BOOST_AUTO_TEST_CASE(standard_json_mode_options)
{
std::vector<std::string> commandLine = {
"solc",
"input.json",
"--standard-json",
"--base-path=/home/user/",
"--include-path=/usr/lib/include/",
"--include-path=/home/user/include",
"--allow-paths=/tmp,/home,project,../contracts",
"--ignore-missing",
"--output-dir=/tmp/out", // Accepted but has no effect in Standard JSON mode
"--overwrite", // Accepted but has no effect in Standard JSON mode
"--evm-version=spuriousDragon", // Ignored in Standard JSON mode
"--revert-strings=strip", // Accepted but has no effect in Standard JSON mode
"--pretty-json",
"--json-indent=1",
"--no-color", // Accepted but has no effect in Standard JSON mode
"--error-codes", // Accepted but has no effect in Standard JSON mode
"--libraries=" // Ignored in Standard JSON mode
"dir1/file1.sol:L=0x1234567890123456789012345678901234567890,"
"dir2/file2.sol:L=0x1111122222333334444455555666667777788888",
"--gas", // Accepted but has no effect in Standard JSON mode
"--combined-json=abi,bin", // Accepted but has no effect in Standard JSON mode
};
CommandLineOptions expectedOptions;
expectedOptions.input.mode = InputMode::StandardJson;
expectedOptions.input.paths = {"input.json"};
expectedOptions.input.basePath = "/home/user/";
expectedOptions.input.includePaths = {"/usr/lib/include/", "/home/user/include"};
expectedOptions.input.allowedDirectories = {"/tmp", "/home", "project", "../contracts"};
expectedOptions.input.ignoreMissingFiles = true;
expectedOptions.output.dir = "/tmp/out";
expectedOptions.output.overwriteFiles = true;
expectedOptions.output.revertStrings = RevertStrings::Strip;
expectedOptions.formatting.json = JsonFormat {JsonFormat::Pretty, 1};
expectedOptions.formatting.coloredOutput = false;
expectedOptions.formatting.withErrorIds = true;
expectedOptions.compiler.estimateGas = true;
expectedOptions.compiler.combinedJsonRequests = CombinedJsonRequests{};
expectedOptions.compiler.combinedJsonRequests->abi = true;
expectedOptions.compiler.combinedJsonRequests->binary = true;
CommandLineOptions parsedOptions = parseCommandLine(commandLine);
BOOST_TEST(parsedOptions == expectedOptions);
}
BOOST_AUTO_TEST_CASE(invalid_options_input_modes_combinations)
{
std::map<std::string, std::vector<std::string>> invalidOptionInputModeCombinations = {
// TODO: This should eventually contain all options.
{"--experimental-via-ir", {"--assemble", "--strict-assembly", "--standard-json", "--link"}},
{"--via-ir", {"--assemble", "--strict-assembly", "--standard-json", "--link"}},
{"--metadata-literal", {"--assemble", "--strict-assembly", "--standard-json", "--link"}},
{"--metadata-hash=swarm", {"--assemble", "--strict-assembly", "--standard-json", "--link"}},
{"--model-checker-show-proved-safe", {"--assemble", "--strict-assembly", "--standard-json", "--link"}},
{"--model-checker-show-unproved", {"--assemble", "--strict-assembly", "--standard-json", "--link"}},
{"--model-checker-show-unsupported", {"--assemble", "--strict-assembly", "--standard-json", "--link"}},
{"--model-checker-div-mod-no-slacks", {"--assemble", "--strict-assembly", "--standard-json", "--link"}},
{"--model-checker-engine=bmc", {"--assemble", "--strict-assembly", "--standard-json", "--link"}},
{"--model-checker-invariants=contract,reentrancy", {"--assemble", "--strict-assembly", "--standard-json", "--link"}},
{"--model-checker-solvers=z3,smtlib2", {"--assemble", "--strict-assembly", "--standard-json", "--link"}},
{"--model-checker-timeout=5", {"--assemble", "--strict-assembly", "--standard-json", "--link"}},
{"--model-checker-contracts=contract1.yul:A,contract2.yul:B", {"--assemble", "--strict-assembly", "--standard-json", "--link"}},
{"--model-checker-targets=underflow,divByZero", {"--assemble", "--strict-assembly", "--standard-json", "--link"}}
};
for (auto const& [optionName, inputModes]: invalidOptionInputModeCombinations)
for (std::string const& inputMode: inputModes)
{
std::stringstream serr;
size_t separatorPosition = optionName.find("=");
std::string optionNameWithoutValue = optionName.substr(0, separatorPosition);
soltestAssert(!optionNameWithoutValue.empty());
std::vector<std::string> commandLine = {"solc", optionName, "file", inputMode};
std::string expectedMessage = "The following options are not supported in the current input mode: " + optionNameWithoutValue;
auto hasCorrectMessage = [&](CommandLineValidationError const& _exception) { return _exception.what() == expectedMessage; };
BOOST_CHECK_EXCEPTION(parseCommandLine(commandLine), CommandLineValidationError, hasCorrectMessage);
}
}
BOOST_AUTO_TEST_CASE(optimizer_flags)
{
OptimiserSettings yulOnly = OptimiserSettings::minimal();
yulOnly.runYulOptimiser = true;
yulOnly.optimizeStackAllocation = true;
OptimiserSettings evmasmOnly = OptimiserSettings::standard();
evmasmOnly.runYulOptimiser = false;
std::map<std::vector<std::string>, OptimiserSettings> settingsMap = {
{{}, OptimiserSettings::minimal()},
{{"--optimize"}, OptimiserSettings::standard()},
{{"--no-optimize-yul"}, OptimiserSettings::minimal()},
{{"--optimize-yul"}, yulOnly},
{{"--optimize", "--no-optimize-yul"}, evmasmOnly},
{{"--optimize", "--optimize-yul"}, OptimiserSettings::standard()},
};
std::map<InputMode, std::string> inputModeFlagMap = {
{InputMode::Compiler, ""},
{InputMode::CompilerWithASTImport, "--import-ast"},
{InputMode::Assembler, "--strict-assembly"},
};
for (auto const& [inputMode, inputModeFlag]: inputModeFlagMap)
for (auto const& [optimizerFlags, expectedOptimizerSettings]: settingsMap)
{
std::vector<std::string> commandLine = {"solc", inputModeFlag, "file"};
commandLine += optimizerFlags;
BOOST_CHECK(parseCommandLine(commandLine).optimiserSettings() == expectedOptimizerSettings);
}
}
BOOST_AUTO_TEST_CASE(default_optimiser_sequence)
{
CommandLineOptions const& commandLineOptions = parseCommandLine({"solc", "contract.sol", "--optimize"});
BOOST_CHECK_EQUAL(commandLineOptions.optimiserSettings().yulOptimiserSteps, OptimiserSettings::DefaultYulOptimiserSteps);
BOOST_CHECK_EQUAL(commandLineOptions.optimiserSettings().yulOptimiserCleanupSteps, OptimiserSettings::DefaultYulOptimiserCleanupSteps);
}
BOOST_AUTO_TEST_CASE(valid_optimiser_sequences)
{
std::vector<std::string> validSequenceInputs {
":", // Empty optimization sequence and empty cleanup sequence
" : ", // whitespaces only optimization sequence and whitespaces only cleanup sequence
": ", // Empty optimization sequence and whitespaces only cleanup sequence
" :", // whitespaces only optimization sequence and empty cleanup sequence
":fDn", // Empty optimization sequence and specified cleanup sequence
"dhfoDgvulfnTUtnIf:", // Specified optimization sequence and empty cleanup sequence
"dhfoDgvulfnTUtnIf:fDn", // Specified optimization sequence and cleanup sequence
"dhfo[Dgvulfn]TUtnIf:f[D]n", // Specified and nested optimization and cleanup sequence
"dhfoDgvulfnTUtnIf", // Specified optimizer sequence only
"iDu", // Short optimizer sequence
"a[[a][[aa]aa[aa]][]]aaa[aa[aa[aa]]]a[a][a][a]a[a]" // Nested brackets
};
std::vector<std::tuple<std::string, std::string>> const expectedParsedSequences {
{"", ""},
{" ", " "},
{"", " "},
{" ", ""},
{"", "fDn"},
{"dhfoDgvulfnTUtnIf", ""},
{"dhfoDgvulfnTUtnIf", "fDn"},
{"dhfo[Dgvulfn]TUtnIf", "f[D]n"},
{"dhfoDgvulfnTUtnIf", OptimiserSettings::DefaultYulOptimiserCleanupSteps},
{"iDu", OptimiserSettings::DefaultYulOptimiserCleanupSteps},
{"a[[a][[aa]aa[aa]][]]aaa[aa[aa[aa]]]a[a][a][a]a[a]", OptimiserSettings::DefaultYulOptimiserCleanupSteps}
};
BOOST_CHECK_EQUAL(validSequenceInputs.size(), expectedParsedSequences.size());
for (size_t i = 0; i < validSequenceInputs.size(); ++i)
{
CommandLineOptions const& commandLineOptions = parseCommandLine({"solc", "contract.sol", "--optimize", "--yul-optimizations=" + validSequenceInputs[i]});
auto const& [expectedYulOptimiserSteps, expectedYulCleanupSteps] = expectedParsedSequences[i];
BOOST_CHECK_EQUAL(commandLineOptions.optimiserSettings().yulOptimiserSteps, expectedYulOptimiserSteps);
BOOST_CHECK_EQUAL(commandLineOptions.optimiserSettings().yulOptimiserCleanupSteps, expectedYulCleanupSteps);
}
}
BOOST_AUTO_TEST_CASE(invalid_optimiser_sequences)
{
std::vector<std::string> const invalidSequenceInputs {
"abcdefg{hijklmno}pqr[st]uvwxyz", // Invalid abbreviation
"[[[[[[[[[[[[[[[[[[[[[[[[[[[[[["
"[[[[[[[[[[[[[[[[[[[[[[[[[[[[[["
"[[[[[[[[[[[[[[[[[[[[[[[[[[[[[["
"[[[[[[[[[[[[[[[[[[[[[[[[[[[[[["
"[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[a]"
"]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]"
"]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]"
"]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]"
"]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]"
"]]]]]]]]]]]]]]]]]]]]]]]]]]]]]", // Brackets nested too deep
"a]a][", // Unbalanced closing bracket
"a[a][", // Unbalanced opening bracket
"dhfoDgvulfnTUt[nIf:fd]N", // Nested cleanup sequence delimiter
"dhfoDgvulfnTU:tnIf:fdN" // Too many cleanup sequence delimiters
};
std::vector<std::string> const expectedErrorMessages {
"'b' is not a valid step abbreviation",
"Brackets nested too deep",
"Unbalanced brackets",
"Unbalanced brackets",
"Cleanup sequence delimiter cannot be placed inside the brackets",
"Too many cleanup sequence delimiters"
};
BOOST_CHECK_EQUAL(invalidSequenceInputs.size(), expectedErrorMessages.size());
std::string const baseExpectedErrorMessage = "Invalid optimizer step sequence in --yul-optimizations: ";
for (size_t i = 0; i < invalidSequenceInputs.size(); ++i)
{
std::vector<std::string> const commandLineOptions = {"solc", "contract.sol", "--optimize", "--yul-optimizations=" + invalidSequenceInputs[i]};
std::string const expectedErrorMessage = baseExpectedErrorMessage + expectedErrorMessages[i];
auto hasCorrectMessage = [&](CommandLineValidationError const& _exception) { return _exception.what() == expectedErrorMessage; };
BOOST_CHECK_EXCEPTION(parseCommandLine(commandLineOptions), CommandLineValidationError, hasCorrectMessage);
}
}
BOOST_AUTO_TEST_CASE(valid_empty_optimizer_sequences_without_optimize)
{
std::vector<std::string> const validSequenceInputs {
" :",
": ",
"\n : \n",
":"
};
std::vector<std::tuple<std::string, std::string>> const expectedParsedSequences {
{" ", ""},
{"", " "},
{"\n ", " \n"},
{"", ""}
};
BOOST_CHECK_EQUAL(validSequenceInputs.size(), expectedParsedSequences.size());
for (size_t i = 0; i < validSequenceInputs.size(); ++i)
{
CommandLineOptions const& commandLineOptions = parseCommandLine({"solc", "contract.sol", "--yul-optimizations=" + validSequenceInputs[i]});
auto const& [expectedYulOptimiserSteps, expectedYulCleanupSteps] = expectedParsedSequences[i];
BOOST_CHECK_EQUAL(commandLineOptions.optimiserSettings().yulOptimiserSteps, expectedYulOptimiserSteps);
BOOST_CHECK_EQUAL(commandLineOptions.optimiserSettings().yulOptimiserCleanupSteps, expectedYulCleanupSteps);
}
}
BOOST_AUTO_TEST_CASE(invalid_optimizer_sequence_without_optimize)
{
std::vector<std::string> const invalidSequenceInputs {
{" "},
{"u: "},
{"u:"},
{":f"},
{" :f"}
};
std::string const expectedErrorMessage{
"--yul-optimizations is invalid with a non-empty sequence if Yul optimizer is disabled."
" Note that the empty optimizer sequence is properly denoted by \":\"."
};
auto hasCorrectMessage = [&](CommandLineValidationError const& _exception) { return _exception.what() == expectedErrorMessage; };
for (auto const& invalidSequence: invalidSequenceInputs)
{
std::vector<std::string> commandLineOptions{"solc", "contract.sol", "--yul-optimizations=" + invalidSequence};
BOOST_CHECK_EXCEPTION(parseCommandLine(commandLineOptions), CommandLineValidationError, hasCorrectMessage);
}
}
BOOST_AUTO_TEST_SUITE_END()
} // namespace solidity::frontend::test
| 25,346
|
C++
|
.cpp
| 555
| 42.747748
| 155
| 0.710153
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,904
|
CommandLineInterfaceAllowPaths.cpp
|
ethereum_solidity/test/solc/CommandLineInterfaceAllowPaths.cpp
|
/*
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
/// Unit tests for solc/CommandLineInterface.h
#include <solc/CommandLineInterface.h>
#include <test/solc/Common.h>
#include <test/Common.h>
#include <test/FilesystemUtils.h>
#include <test/libsolidity/util/SoltestErrors.h>
#include <libsolutil/TemporaryDirectory.h>
#include <boost/algorithm/string/predicate.hpp>
#include <fstream>
#include <regex>
#include <string>
#include <vector>
using namespace solidity::frontend;
using namespace solidity::util;
using namespace solidity::test;
#define TEST_CASE_NAME (boost::unit_test::framework::current_test_case().p_name)
namespace
{
struct ImportCheck
{
enum class Result
{
Unknown, ///< Status is unknown due to a failure of the status check.
OK, ///< Passed compilation without errors.
FileNotFound, ///< Error was reported: file not found.
PathDisallowed, ///< Error was reported: file not allowed paths.
};
bool operator==(ImportCheck const& _other) const { return result == _other.result && message == _other.message; }
bool operator!=(ImportCheck const& _other) const { return !(*this == _other); }
operator bool() const { return this->result == Result::OK; }
static ImportCheck const OK() { return {Result::OK, ""}; }
static ImportCheck const FileNotFound() { return {Result::FileNotFound, ""}; }
static ImportCheck const PathDisallowed() { return {Result::PathDisallowed, ""}; }
static ImportCheck const Unknown(const std::string& _message) { return {Result::Unknown, _message}; }
Result result;
std::string message;
};
ImportCheck checkImport(
std::string const& _import,
std::vector<std::string> const& _cliOptions
)
{
soltestAssert(regex_match(_import, std::regex{R"(import '[^']*')"}), "");
for (std::string const& option: _cliOptions)
soltestAssert(
boost::starts_with(option, "--base-path") ||
boost::starts_with(option, "--include-path") ||
boost::starts_with(option, "--allow-paths") ||
!boost::starts_with(option, "--"),
""
);
std::vector<std::string> commandLine = {
"solc",
"-",
"--no-color",
"--error-codes",
};
commandLine += _cliOptions;
std::string standardInputContent =
"// SPDX-License-Identifier: GPL-3.0\n"
"pragma solidity >=0.0;\n" +
_import + ";";
test::OptionsReaderAndMessages cliResult = test::runCLI(commandLine, standardInputContent);
if (cliResult.success)
return ImportCheck::OK();
static std::regex const sourceNotFoundErrorRegex{
R"(^Error \(6275\): Source "[^"]+" not found: (.*)\.\n)"
R"(\s*--> .*<stdin>:\d+:\d+:\n)"
R"(\s*\|\n)"
R"(\d+\s*\| import '.+';\n)"
R"(\s*\| \^+\n\s*$)"
};
std::smatch submatches;
if (!regex_match(cliResult.stderrContent, submatches, sourceNotFoundErrorRegex))
return ImportCheck::Unknown("Unexpected stderr content: '" + cliResult.stderrContent + "'");
if (submatches[1] != "File not found" && !boost::starts_with(std::string(submatches[1]), "File outside of allowed directories"))
return ImportCheck::Unknown("Unexpected error message: '" + cliResult.stderrContent + "'");
if (submatches[1] == "File not found")
return ImportCheck::FileNotFound();
else if (boost::starts_with(std::string(submatches[1]), "File outside of allowed directories"))
return ImportCheck::PathDisallowed();
else
return ImportCheck::Unknown("Unexpected error message '" + submatches[1].str() + "'");
}
class AllowPathsFixture
{
protected:
AllowPathsFixture():
m_tempDir({"code/", "work/"}, TEST_CASE_NAME),
m_tempWorkDir(m_tempDir.path() / "work"),
m_codeDir(m_tempDir.path() / "code"),
m_workDir(m_tempDir.path() / "work"),
m_portablePrefix(("/" / boost::filesystem::canonical(m_codeDir).relative_path()).generic_string())
{
createFilesWithParentDirs(
{
m_codeDir / "a/b/c/d.sol",
m_codeDir / "a/b/c.sol",
m_codeDir / "a/b/X.sol",
m_codeDir / "a/X/c.sol",
m_codeDir / "X/b/c.sol",
m_codeDir / "a/bc/d.sol",
m_codeDir / "X/bc/d.sol",
m_codeDir / "x/y/z.sol",
m_codeDir / "1/2/3.sol",
m_codeDir / "contract.sol",
m_workDir / "a/b/c/d.sol",
m_workDir / "a/b/c.sol",
m_workDir / "a/b/X.sol",
m_workDir / "a/X/c.sol",
m_workDir / "X/b/c.sol",
m_workDir / "contract.sol",
},
"// SPDX-License-Identifier: GPL-3.0\npragma solidity >=0.0;"
);
if (
!createSymlinkIfSupportedByFilesystem("b", m_codeDir / "a/b_sym", true) ||
!createSymlinkIfSupportedByFilesystem("../x/y", m_codeDir / "a/y_sym", true) ||
!createSymlinkIfSupportedByFilesystem("../../a/b/c.sol", m_codeDir / "a/b/c_sym.sol", false) ||
!createSymlinkIfSupportedByFilesystem("../../x/y/z.sol", m_codeDir / "a/b/z_sym.sol", false)
)
return;
m_caseSensitiveFilesystem = boost::filesystem::create_directories(m_codeDir / "A/B/C");
soltestAssert(boost::filesystem::equivalent(m_codeDir / "a/b/c", m_codeDir / "A/B/C") != m_caseSensitiveFilesystem, "");
}
TemporaryDirectory m_tempDir;
TemporaryWorkingDirectory m_tempWorkDir;
boost::filesystem::path const m_codeDir;
boost::filesystem::path const m_workDir;
std::string m_portablePrefix;
bool m_caseSensitiveFilesystem = true;
};
std::ostream& operator<<(std::ostream& _out, ImportCheck const& _value)
{
switch (_value.result)
{
case ImportCheck::Result::Unknown: _out << "Unknown"; break;
case ImportCheck::Result::OK: _out << "OK"; break;
case ImportCheck::Result::FileNotFound: _out << "FileNotFound"; break;
case ImportCheck::Result::PathDisallowed: _out << "PathDisallowed"; break;
}
if (_value.message != "")
_out << "(" << _value.message << ")";
return _out;
}
} // namespace
namespace boost::test_tools::tt_detail
{
// Boost won't find the << operator unless we put it in the std namespace which is illegal.
// The recommended solution is to overload print_log_value<> struct and make it use our operator.
template<>
struct print_log_value<ImportCheck>
{
void operator()(std::ostream& _out, ImportCheck const& _value) { ::operator<<(_out, _value); }
};
} // namespace boost::test_tools::tt_detail
namespace solidity::frontend::test
{
BOOST_AUTO_TEST_SUITE(CommandLineInterfaceAllowPathsTest)
BOOST_FIXTURE_TEST_CASE(allow_path_multiple_paths, AllowPathsFixture)
{
std::string allowedPaths =
m_codeDir.generic_string() + "/a/b/X.sol," +
m_codeDir.generic_string() + "/X/," +
m_codeDir.generic_string() + "/z," +
m_codeDir.generic_string() + "/a/b";
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {"--allow-paths", allowedPaths}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/X.sol'", {"--allow-paths", allowedPaths}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/X/c.sol'", {"--allow-paths", allowedPaths}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/X/b/c.sol'", {"--allow-paths", allowedPaths}));
}
BOOST_FIXTURE_TEST_CASE(allow_path_should_work_with_various_path_forms, AllowPathsFixture)
{
std::string import = "import '" + m_portablePrefix + "/a/b/c.sol'";
// Without --allow-path
BOOST_TEST(checkImport(import, {}) == ImportCheck::PathDisallowed());
// Absolute paths allowed
BOOST_TEST(checkImport(import, {"--allow-paths", m_codeDir.string()}));
BOOST_TEST(checkImport(import, {"--allow-paths", m_codeDir.string() + "/a"}));
BOOST_TEST(checkImport(import, {"--allow-paths", m_codeDir.string() + "/a/"}));
BOOST_TEST(checkImport(import, {"--allow-paths", m_codeDir.string() + "/a/b"}));
BOOST_TEST(checkImport(import, {"--allow-paths", m_codeDir.string() + "/a/b/c.sol"}));
// Relative paths allowed
BOOST_TEST(checkImport(import, {"--allow-paths=../code/a"}));
BOOST_TEST(checkImport(import, {"--allow-paths=../code/a/"}));
BOOST_TEST(checkImport(import, {"--allow-paths=../code/a/b"}));
BOOST_TEST(checkImport(import, {"--allow-paths=../code/a/b/c.sol"}));
// Non-normalized paths allowed
BOOST_TEST(checkImport(import, {"--allow-paths", "./../code/."}));
BOOST_TEST(checkImport(import, {"--allow-paths", "./../code/./"}));
BOOST_TEST(checkImport(import, {"--allow-paths", "./../code/a/.."}));
BOOST_TEST(checkImport(import, {"--allow-paths", "./../code/a/../"}));
BOOST_TEST(checkImport(import, {"--allow-paths", "./../code/a/b"}));
BOOST_TEST(checkImport(import, {"--allow-paths", "./../code/a/./b"}));
BOOST_TEST(checkImport(import, {"--allow-paths", "./../code/a/../a/b"}));
BOOST_TEST(checkImport(import, {"--allow-paths", "./../code/a///b"}));
BOOST_TEST(checkImport(import, {"--allow-paths", "./../code/a/b//"}));
BOOST_TEST(checkImport(import, {"--allow-paths", "./../code/a/b///"}));
// Root path allowed
BOOST_TEST(checkImport(import, {"--allow-paths=/"}));
BOOST_TEST(checkImport(import, {"--allow-paths=///"}));
// UNC paths should be treated differently from normal paths
soltestAssert(FileReader::isUNCPath("/" + m_portablePrefix), "");
BOOST_TEST(checkImport(import, {"--allow-paths=//"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport(import, {"--allow-paths=/" + m_portablePrefix}) == ImportCheck::PathDisallowed());
// Paths going beyond root allowed
BOOST_TEST(checkImport(import, {"--allow-paths=/../../"}));
BOOST_TEST(checkImport(import, {"--allow-paths=/../.."}));
BOOST_TEST(checkImport(import, {"--allow-paths=/../../a/../"}));
BOOST_TEST(checkImport(import, {"--allow-paths=/../../" + m_portablePrefix}));
// File named like a directory
BOOST_TEST(checkImport(import, {"--allow-paths", m_codeDir.string() + "/a/b/c.sol/"}));
}
BOOST_FIXTURE_TEST_CASE(allow_path_should_handle_empty_paths, AllowPathsFixture)
{
// Work dir is base path
BOOST_TEST(checkImport("import 'a/../../work/a/b/c.sol'", {"--allow-paths", ""}));
BOOST_TEST(checkImport("import 'a/../../work/a/b/c.sol'", {"--allow-paths", "x,,y"}));
BOOST_TEST(checkImport("import 'a/../../code/a/b/c.sol'", {"--allow-paths", ""}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import 'a/../../code/a/b/c.sol'", {"--allow-paths", "x,,y"}) == ImportCheck::PathDisallowed());
// Work dir is not base path
BOOST_TEST(checkImport("import 'a/../../work/a/b/c.sol'", {"--allow-paths", "", "--base-path=../code/"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import 'a/../../work/a/b/c.sol'", {"--allow-paths", "x,,y", "--base-path=../code/"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import 'a/../../code/a/b/c.sol'", {"--allow-paths", "", "--base-path=../code/"}));
BOOST_TEST(checkImport("import 'a/../../code/a/b/c.sol'", {"--allow-paths", "x,,y", "--base-path=../code/"}));
}
BOOST_FIXTURE_TEST_CASE(allow_path_case_sensitive, AllowPathsFixture)
{
// Allowed paths are case-sensitive even on case-insensitive filesystems
BOOST_TEST(
checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {"--allow-paths", m_codeDir.string() + "/A/B/"}) ==
ImportCheck::PathDisallowed()
);
}
BOOST_FIXTURE_TEST_CASE(allow_path_should_work_with_various_import_forms, AllowPathsFixture)
{
// Absolute import paths
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {"--allow-paths", "../code/a/b/c.sol"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/X/b/c.sol'", {"--allow-paths", "../code/a/b/c.sol"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/X/c.sol'", {"--allow-paths", "../code/a/b/c.sol"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/X.sol'", {"--allow-paths", "../code/a/b/c.sol"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {"--allow-paths", "../code/a/b/"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/X/b/c.sol'", {"--allow-paths", "../code/a/b/"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/X/c.sol'", {"--allow-paths", "../code/a/b/"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/X.sol'", {"--allow-paths", "../code/a/b/"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {"--allow-paths", "../code/a/b"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/X/b/c.sol'", {"--allow-paths", "../code/a/b"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/X/c.sol'", {"--allow-paths", "../code/a/b"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/X.sol'", {"--allow-paths", "../code/a/b"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {"--allow-paths", "../code/a"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/X/b/c.sol'", {"--allow-paths", "../code/a"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/X/c.sol'", {"--allow-paths", "../code/a"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/X.sol'", {"--allow-paths", "../code/a"}));
// Relative import paths
// NOTE: Base path is whitelisted by default so we need the 'a/../../code/' part to get
// outside of it. And it can't be just '../code/' because that would not be a direct import.
BOOST_TEST(checkImport("import 'a/../../code/a/b/c.sol'", {"--allow-paths", "../code/a/b"}));
BOOST_TEST(checkImport("import 'a/../../code/X/b/c.sol'", {"--allow-paths", "../code/a/b"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import 'a/../../code/a/X/c.sol'", {"--allow-paths", "../code/a/b"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import 'a/../../code/a/b/X.sol'", {"--allow-paths", "../code/a/b"}));
// Non-normalized relative import paths
BOOST_TEST(checkImport("import 'a/../../code/a/./b/c.sol'", {"--allow-paths", "../code/a/b/c.sol"}));
BOOST_TEST(checkImport("import 'a/../../code/a/../a/b/c.sol'", {"--allow-paths", "../code/a/b/c.sol"}));
BOOST_TEST(checkImport("import 'a/../../code/a///b/c.sol'", {"--allow-paths", "../code/a/b/c.sol"}));
#if !defined(_WIN32)
// UNC paths in imports.
// Unfortunately can't test it on Windows without having an existing UNC path. On Linux we can
// at least rely on the fact that `//` works like `/`.
std::string uncImportPath = "/" + m_portablePrefix + "/a/b/c.sol";
soltestAssert(FileReader::isUNCPath(uncImportPath), "");
BOOST_TEST(checkImport("import '" + uncImportPath + "'", {"--allow-paths", "../code/a/b/c.sol"}) == ImportCheck::PathDisallowed());
#endif
}
BOOST_FIXTURE_TEST_CASE(allow_path_automatic_whitelisting_input_files, AllowPathsFixture)
{
// By default none of the files is whitelisted
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c/d.sol'", {}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/X.sol'", {}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/X/c.sol'", {}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/X/b/c.sol'", {}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/bc/d.sol'", {}) == ImportCheck::PathDisallowed());
// Compiling a file whitelists its directory and subdirectories
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {m_codeDir.string() + "/a/b/c.sol"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c/d.sol'", {m_codeDir.string() + "/a/b/c.sol"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/X.sol'", {m_codeDir.string() + "/a/b/c.sol"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/X/c.sol'", {m_codeDir.string() + "/a/b/c.sol"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/X/b/c.sol'", {m_codeDir.string() + "/a/b/c.sol"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/bc/d.sol'", {m_codeDir.string() + "/a/b/c.sol"}) == ImportCheck::PathDisallowed());
// If only file name is specified, its parent dir path is empty. This should be equivalent to
// whitelisting the work dir.
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/contract.sol'", {"contract.sol"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import 'contract.sol'", {"contract.sol"}));
}
BOOST_FIXTURE_TEST_CASE(allow_path_automatic_whitelisting_remappings, AllowPathsFixture)
{
// Adding a remapping whitelists target's parent directory and subdirectories
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {"x=../code/a/b/c.sol"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c/d.sol'", {"x=../code/a/b/c.sol"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/X.sol'", {"x=../code/a/b/c.sol"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/X/c.sol'", {"x=../code/a/b/c.sol"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/X/b/c.sol'", {"x=../code/a/b/c.sol"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/bc/d.sol'", {"x=../code/a/b/c.sol"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {"x=/contract.sol"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {"x=/contract.sol/"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {m_portablePrefix + "/a/b=../code/X/b"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {m_portablePrefix + "/a/b/=../code/X/b/"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/bc/d.sol'", {m_portablePrefix + "/a/b=../code/X/b"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/bc/d.sol'", {m_portablePrefix + "/a/b/=../code/X/b/"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {m_portablePrefix + "/a/b:y/z=x/w"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {m_portablePrefix + "/a/b:y/z=x/w"}) == ImportCheck::PathDisallowed());
// Adding a remapping whitelists the target and subdirectories when the target is a directory
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {"x=../code/a/b/"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c/d.sol'", {"x=../code/a/b/"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/X.sol'", {"x=../code/a/b/"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/X/c.sol'", {"x=../code/a/b/"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/X/b/c.sol'", {"x=../code/a/b/"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/bc/d.sol'", {"x=../code/a/b/"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/bc/d.sol'", {"x=../code/a/c/"}) == ImportCheck::PathDisallowed());
// Adding a remapping whitelists target's parent directory and subdirectories when the target
// is a directory but does not have a trailing slash
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {"x=../code/a/b"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c/d.sol'", {"x=../code/a/b"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/X.sol'", {"x=../code/a/b"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/X/c.sol'", {"x=../code/a/b"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/X/b/c.sol'", {"x=../code/a/b"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/bc/d.sol'", {"x=../code/a/b"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/bc/d.sol'", {"x=../code/a/c"}));
// Adding a remapping to a relative target at VFS root whitelists the work dir
BOOST_TEST(checkImport("import '/../../x/y/z.sol'", {"x=contract.sol", "--base-path=../code/a/b/"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '/../../../work/a/b/c.sol'", {"x=contract.sol", "--base-path=../code/a/b/"}));
BOOST_TEST(checkImport("import '/../../x/y/z.sol'", {"x=contract.sol/", "--base-path=../code/a/b/"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '/../../../work/a/b/c.sol'", {"x=contract.sol/", "--base-path=../code/a/b/"}) == ImportCheck::PathDisallowed());
// Adding a remapping with an empty target does not whitelist anything
BOOST_TEST(checkImport("import '" + m_portablePrefix + m_portablePrefix + "/a/b/c.sol'", {m_portablePrefix + "="}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {"../code/="}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '/../work/a/b/c.sol'", {"../code/=", "--base-path", m_portablePrefix}) == ImportCheck::PathDisallowed());
// Adding a remapping that includes .. or . segments whitelists the parent dir and subdirectories
// of the resolved target
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {"x=."}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/X/b/c.sol'", {"x=."}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {"x=./"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/X/b/c.sol'", {"x=./"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {"x=.."}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/X/b/c.sol'", {"x=.."}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {"x=../"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/X/b/c.sol'", {"x=../"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {"x=../code/a/b/./.."}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/X/c.sol'", {"x=../code/a/b/./.."}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/X/b/c.sol'", {"x=../code/a/b/./.."}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {"x=../code/a/b/./../"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/X/c.sol'", {"x=../code/a/b/./../"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/X/b/c.sol'", {"x=../code/a/b/./../"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {"x=../code/a/b/./../b"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/X/c.sol'", {"x=../code/a/b/./../b"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/X/b/c.sol'", {"x=../code/a/b/./../b"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {"x=../code/a/b/./../b/"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/X/c.sol'", {"x=../code/a/b/./../b/"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/X/b/c.sol'", {"x=../code/a/b/./../b/"}) == ImportCheck::PathDisallowed());
// If the target is just a file name, its parent dir path is empty. This should be equivalent to
// whitelisting the work dir.
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/contract.sol'", {"x=contract.sol"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import 'contract.sol'", {"x=contract.sol"}));
}
BOOST_FIXTURE_TEST_CASE(allow_path_automatic_whitelisting_base_path, AllowPathsFixture)
{
// Relative base path whitelists its content
BOOST_TEST(checkImport("import 'b/c.sol'", {"--base-path=../code/a"}));
BOOST_TEST(checkImport("import 'b/c/d.sol'", {"--base-path=../code/a"}));
BOOST_TEST(checkImport("import 'b/X.sol'", {"--base-path=../code/a"}));
BOOST_TEST(checkImport("import 'X/c.sol'", {"--base-path=../code/a"}));
BOOST_TEST(checkImport("import 'b/c.sol'", {"--base-path=../code/a/"}));
BOOST_TEST(checkImport("import 'b/c/d.sol'", {"--base-path=../code/a/"}));
BOOST_TEST(checkImport("import 'b/X.sol'", {"--base-path=../code/a/"}));
BOOST_TEST(checkImport("import 'X/c.sol'", {"--base-path=../code/a/"}));
BOOST_TEST(checkImport("import 'a/b/c.sol'", {"--base-path=../code/."}));
BOOST_TEST(checkImport("import 'a/b/c.sol'", {"--base-path=../code/./"}));
BOOST_TEST(checkImport("import 'code/a/b/c.sol'", {"--base-path=.."}));
BOOST_TEST(checkImport("import 'code/a/b/c.sol'", {"--base-path=../"}));
// Absolute base path whitelists its content
BOOST_TEST(checkImport("import 'b/c.sol'", {"--base-path", m_codeDir.string() + "/a"}));
BOOST_TEST(checkImport("import 'b/c/d.sol'", {"--base-path", m_codeDir.string() + "/a"}));
BOOST_TEST(checkImport("import 'b/X.sol'", {"--base-path", m_codeDir.string() + "/a"}));
BOOST_TEST(checkImport("import 'X/c.sol'", {"--base-path", m_codeDir.string() + "/a"}));
}
BOOST_FIXTURE_TEST_CASE(allow_path_automatic_whitelisting_work_dir, AllowPathsFixture)
{
// Work dir is only automatically whitelisted if it matches base path
BOOST_TEST(checkImport("import 'b/../../../work/a/b/c.sol'", {"--base-path=../code/a/"}) == ImportCheck::PathDisallowed());
// Compiling a file in the work dir whitelists it even if it's not in base path
BOOST_TEST(checkImport("import 'b/../../../work/a/b/c.sol'", {"--base-path", "../code/a/", "a/b/c.sol"}));
// Work dir can also be whitelisted manually
BOOST_TEST(checkImport("import 'b/../../../work/a/b/c.sol'", {"--base-path", "../code/a/", "--allow-paths=."}));
// Not setting base path whitelists the working directory
BOOST_TEST(checkImport("import 'a/b/c.sol'", {}));
BOOST_TEST(checkImport("import 'a/b/c/d.sol'", {}));
BOOST_TEST(checkImport("import 'a/b/X.sol'", {}));
BOOST_TEST(checkImport("import 'a/X/c.sol'", {}));
// Setting base path to an empty value whitelists the working directory
BOOST_TEST(checkImport("import 'a/b/c.sol'", {"--base-path", ""}));
BOOST_TEST(checkImport("import 'a/b/c/d.sol'", {"--base-path", ""}));
BOOST_TEST(checkImport("import 'a/b/X.sol'", {"--base-path", ""}));
BOOST_TEST(checkImport("import 'a/X/c.sol'", {"--base-path", ""}));
}
BOOST_FIXTURE_TEST_CASE(allow_path_automatic_whitelisting_include_paths, AllowPathsFixture)
{
// Relative include path whitelists its content
BOOST_TEST(checkImport("import 'b/c.sol'", {"--base-path=a/b/c", "--include-path=../code/a"}));
BOOST_TEST(checkImport("import 'b/c/d.sol'", {"--base-path=a/b/c", "--include-path=../code/a"}));
BOOST_TEST(checkImport("import 'b/X.sol'", {"--base-path=a/b/c", "--include-path=../code/a"}));
BOOST_TEST(checkImport("import 'X/c.sol'", {"--base-path=a/b/c", "--include-path=../code/a"}));
BOOST_TEST(checkImport("import 'b/c.sol'", {"--base-path=a/b/c", "--include-path=../code/a/"}));
BOOST_TEST(checkImport("import 'b/c/d.sol'", {"--base-path=a/b/c", "--include-path=../code/a/"}));
BOOST_TEST(checkImport("import 'b/X.sol'", {"--base-path=a/b/c", "--include-path=../code/a/"}));
BOOST_TEST(checkImport("import 'X/c.sol'", {"--base-path=a/b/c", "--include-path=../code/a/"}));
BOOST_TEST(checkImport("import 'a/b/c.sol'", {"--base-path=a/b/c", "--include-path=../code/."}));
BOOST_TEST(checkImport("import 'a/b/c.sol'", {"--base-path=a/b/c", "--include-path=../code/./"}));
BOOST_TEST(checkImport("import 'code/a/b/c.sol'", {"--base-path=a/b/c", "--include-path=.."}));
BOOST_TEST(checkImport("import 'code/a/b/c.sol'", {"--base-path=a/b/c", "--include-path=../"}));
// Absolute include path whitelists its content
BOOST_TEST(checkImport("import 'b/c.sol'", {"--base-path=a/b/c", "--include-path", m_codeDir.string() + "/a"}));
BOOST_TEST(checkImport("import 'b/c/d.sol'", {"--base-path=a/b/c", "--include-path", m_codeDir.string() + "/a"}));
BOOST_TEST(checkImport("import 'b/X.sol'", {"--base-path=a/b/c", "--include-path", m_codeDir.string() + "/a"}));
BOOST_TEST(checkImport("import 'X/c.sol'", {"--base-path=a/b/c", "--include-path", m_codeDir.string() + "/a"}));
// If there are multiple include paths, all of them get whitelisted
BOOST_TEST(checkImport("import 'b/c.sol'", {"--base-path=a/b/c", "--include-path=../code/a", "--include-path=../code/1"}));
BOOST_TEST(checkImport("import '2/3.sol'", {"--base-path=a/b/c", "--include-path=../code/a", "--include-path=../code/1"}));
BOOST_TEST(checkImport("import 'b/c.sol'", {"--base-path=a/b/c", "--include-path=../code/1", "--include-path=../code/a"}));
BOOST_TEST(checkImport("import '2/3.sol'", {"--base-path=a/b/c", "--include-path=../code/1", "--include-path=../code/a"}));
}
BOOST_FIXTURE_TEST_CASE(allow_path_symlinks_within_whitelisted_dir, AllowPathsFixture)
{
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b_sym/c.sol'", {"--allow-paths=../code/a/b/"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {"--allow-paths=../code/a/b_sym/"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b_sym/c.sol'", {"--allow-paths=../code/a/b_sym/"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b_sym/c.sol'", {"--allow-paths=../code/a/b"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {"--allow-paths=../code/a/b_sym"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b_sym/c.sol'", {"--allow-paths=../code/a/b_sym"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c_sym.sol'", {"--allow-paths=../code/a/b/c.sol"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c.sol'", {"--allow-paths=../code/a/b/c_sym.sol"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/c_sym.sol'", {"--allow-paths=../code/a/b/c_sym.sol"}));
}
BOOST_FIXTURE_TEST_CASE(allow_path_symlinks_outside_whitelisted_dir, AllowPathsFixture)
{
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/y_sym/z.sol'", {"--allow-paths=../code/a/"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/y_sym/z.sol'", {"--allow-paths=../code/x/"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/z_sym.sol'", {"--allow-paths=../code/a/"}) == ImportCheck::PathDisallowed());
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/z_sym.sol'", {"--allow-paths=../code/x/"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/z_sym.sol'", {"--allow-paths=../code/a/b/z_sym.sol"}));
BOOST_TEST(checkImport("import '" + m_portablePrefix + "/a/b/z_sym.sol'", {"--allow-paths=../code/x/y/z.sol"}));
}
BOOST_AUTO_TEST_SUITE_END()
} // namespace solidity::frontend::test
| 31,410
|
C++
|
.cpp
| 467
| 64.978587
| 150
| 0.65428
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,905
|
CommandLineInterface.cpp
|
ethereum_solidity/test/solc/CommandLineInterface.cpp
|
/*
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
/// Unit tests for solc/CommandLineInterface.h
#include <solc/CommandLineInterface.h>
#include <solc/Exceptions.h>
#include <test/solc/Common.h>
#include <test/Common.h>
#include <test/libsolidity/util/Common.h>
#include <test/libsolidity/util/SoltestErrors.h>
#include <liblangutil/SemVerHandler.h>
#include <test/FilesystemUtils.h>
#include <libsolutil/JSON.h>
#include <libsolutil/TemporaryDirectory.h>
#include <boost/algorithm/string.hpp>
#include <range/v3/view/transform.hpp>
#include <map>
#include <ostream>
#include <set>
#include <string>
#include <vector>
using namespace solidity::frontend;
using namespace solidity::test;
using namespace solidity::util;
using namespace solidity::langutil;
using PathSet = std::set<boost::filesystem::path>;
#define TEST_CASE_NAME (boost::unit_test::framework::current_test_case().p_name)
namespace
{
std::ostream& operator<<(std::ostream& _out, std::vector<ImportRemapper::Remapping> const& _remappings)
{
static auto remappingToString = [](auto const& _remapping)
{
return _remapping.context + ":" + _remapping.prefix + "=" + _remapping.target;
};
_out << "[" << joinHumanReadable(_remappings | ranges::views::transform(remappingToString)) << "]";
return _out;
}
std::ostream& operator<<(std::ostream& _out, std::map<std::string, std::string> const& _map)
{
_out << "{" << std::endl;
for (auto const& [key, value]: _map)
_out << "" << key << ": " << value << "," << std::endl;
_out << "}";
return _out;
}
std::ostream& operator<<(std::ostream& _out, PathSet const& _paths)
{
static auto pathString = [](auto const& _path) { return _path.string(); };
_out << "{" << joinHumanReadable(_paths | ranges::views::transform(pathString)) << "}";
return _out;
}
} // namespace
namespace boost::test_tools::tt_detail
{
// Boost won't find the << operator unless we put it in the std namespace which is illegal.
// The recommended solution is to overload print_log_value<> struct and make it use our operator.
template<>
struct print_log_value<std::vector<ImportRemapper::Remapping>>
{
void operator()(std::ostream& _out, std::vector<ImportRemapper::Remapping> const& _value) { ::operator<<(_out, _value); }
};
template<>
struct print_log_value<std::map<std::string, std::string>>
{
void operator()(std::ostream& _out, std::map<std::string, std::string> const& _value) { ::operator<<(_out, _value); }
};
template<>
struct print_log_value<PathSet>
{
void operator()(std::ostream& _out, PathSet const& _value) { ::operator<<(_out, _value); }
};
} // namespace boost::test_tools::tt_detail
namespace solidity::frontend::test
{
BOOST_AUTO_TEST_SUITE(CommandLineInterfaceTest)
BOOST_AUTO_TEST_CASE(help)
{
OptionsReaderAndMessages result = runCLI({"solc", "--help"}, "");
BOOST_TEST(result.success);
BOOST_TEST(boost::starts_with(result.stdoutContent, "solc, the Solidity commandline compiler."));
BOOST_TEST(result.stderrContent == "");
BOOST_TEST(result.options.input.mode == InputMode::Help);
}
BOOST_AUTO_TEST_CASE(license)
{
OptionsReaderAndMessages result = runCLI({"solc", "--license"}, "");
BOOST_TEST(result.success);
BOOST_TEST(boost::starts_with(result.stdoutContent, "Most of the code is licensed under GPLv3"));
BOOST_TEST(result.stderrContent == "");
BOOST_TEST(result.options.input.mode == InputMode::License);
}
BOOST_AUTO_TEST_CASE(version)
{
OptionsReaderAndMessages result = runCLI({"solc", "--version"}, "");
BOOST_TEST(result.success);
BOOST_TEST(boost::ends_with(result.stdoutContent, "Version: " + solidity::frontend::VersionString + "\n"));
BOOST_TEST(result.stderrContent == "");
BOOST_TEST(result.options.input.mode == InputMode::Version);
}
BOOST_AUTO_TEST_CASE(multiple_input_modes)
{
std::array inputModeOptions {
"--help",
"--license",
"--version",
"--standard-json",
"--link",
"--assemble",
"--strict-assembly",
"--import-ast",
"--import-asm-json",
};
std::string expectedMessage =
"The following options are mutually exclusive: "
"--help, --license, --version, --standard-json, --link, --assemble, --strict-assembly, --import-ast, --lsp, --import-asm-json. "
"Select at most one.";
for (auto const& mode1: inputModeOptions)
for (auto const& mode2: inputModeOptions)
if (mode1 != mode2)
BOOST_CHECK_EXCEPTION(
parseCommandLineAndReadInputFiles({"solc", mode1, mode2}),
CommandLineValidationError,
[&](auto const& _exception) { BOOST_TEST(_exception.what() == expectedMessage); return true; }
);
}
BOOST_AUTO_TEST_CASE(no_import_callback_allowed_paths)
{
std::array<std::string, 2> options = {
"--no-import-callback",
"--allow-paths"
};
std::string expectedMessage =
"The following options are mutually exclusive: "
"--no-import-callback, --allow-paths. "
"Select at most one.";
BOOST_CHECK_EXCEPTION(
parseCommandLineAndReadInputFiles({"solc", options[0], options[1], "."}),
CommandLineValidationError,
[&](auto const& _exception) { BOOST_TEST(_exception.what() == expectedMessage); return true; }
);
}
BOOST_AUTO_TEST_CASE(cli_input)
{
TemporaryDirectory tempDir1(TEST_CASE_NAME);
TemporaryDirectory tempDir2(TEST_CASE_NAME);
createFilesWithParentDirs({tempDir1.path() / "input1.sol"});
createFilesWithParentDirs({tempDir2.path() / "input2.sol"});
boost::filesystem::path expectedRootPath = FileReader::normalizeCLIRootPathForVFS(tempDir1);
boost::filesystem::path expectedDir1 = expectedRootPath / tempDir1.path().relative_path();
boost::filesystem::path expectedDir2 = expectedRootPath / tempDir2.path().relative_path();
soltestAssert(expectedDir1.is_absolute() || expectedDir1.root_path() == "/", "");
soltestAssert(expectedDir2.is_absolute() || expectedDir2.root_path() == "/", "");
std::vector<ImportRemapper::Remapping> expectedRemappings = {
{"", "a", "b/c/d"},
{"a", "b", "c/d/e/"},
};
std::map<std::string, std::string> expectedSources = {
{"<stdin>", ""},
{(expectedDir1 / "input1.sol").generic_string(), ""},
{(expectedDir2 / "input2.sol").generic_string(), ""},
};
PathSet expectedAllowedPaths = {
boost::filesystem::canonical(tempDir1),
boost::filesystem::canonical(tempDir2),
"b/c",
"c/d/e",
};
OptionsReaderAndMessages result = parseCommandLineAndReadInputFiles({
"solc",
"a=b/c/d",
(tempDir1.path() / "input1.sol").string(),
(tempDir2.path() / "input2.sol").string(),
"a:b=c/d/e/",
"-",
});
BOOST_TEST(result.success);
BOOST_TEST(result.stderrContent == "");
BOOST_TEST(result.options.input.mode == InputMode::Compiler);
BOOST_TEST(result.options.input.addStdin);
BOOST_CHECK_EQUAL(result.options.input.remappings, expectedRemappings);
BOOST_CHECK_EQUAL(result.reader.sourceUnits(), expectedSources);
BOOST_CHECK_EQUAL(result.reader.allowedDirectories(), expectedAllowedPaths);
}
BOOST_AUTO_TEST_CASE(cli_optimizer_disabled_yul_optimization_input_whitespaces_or_empty)
{
TemporaryDirectory tempDir(TEST_CASE_NAME);
createFilesWithParentDirs({tempDir.path() / "input.sol"});
createFilesWithParentDirs({tempDir.path() / "input.yul"});
std::string const expectedMessage =
"--yul-optimizations is invalid with a non-empty sequence if Yul optimizer is disabled."
" Note that the empty optimizer sequence is properly denoted by \":\".";
std::vector<std::vector<std::string>> const commandVariations = {
{"solc", "--strict-assembly", "--yul-optimizations", "", (tempDir.path() / "input.yul").string()},
{"solc", "--strict-assembly", "--yul-optimizations", " ", (tempDir.path() / "input.yul").string()},
{"solc", "--yul-optimizations", "", (tempDir.path() / "input.sol").string()},
{"solc", "--yul-optimizations", " ", (tempDir.path() / "input.sol").string()},
};
for (auto const& command: commandVariations)
BOOST_CHECK_EXCEPTION(
parseCommandLineAndReadInputFiles(command),
CommandLineValidationError,
[&](auto const& _exception) { BOOST_TEST(_exception.what() == expectedMessage); return true; }
);
}
BOOST_AUTO_TEST_CASE(cli_ignore_missing_some_files_exist)
{
TemporaryDirectory tempDir1(TEST_CASE_NAME);
TemporaryDirectory tempDir2(TEST_CASE_NAME);
createFilesWithParentDirs({tempDir1.path() / "input1.sol"});
boost::filesystem::path expectedRootPath = FileReader::normalizeCLIRootPathForVFS(tempDir1);
boost::filesystem::path expectedDir1 = expectedRootPath / tempDir1.path().relative_path();
soltestAssert(expectedDir1.is_absolute() || expectedDir1.root_path() == "/", "");
// NOTE: Allowed paths should not be added for skipped files.
std::map<std::string, std::string> expectedSources = {{(expectedDir1 / "input1.sol").generic_string(), ""}};
PathSet expectedAllowedPaths = {boost::filesystem::canonical(tempDir1)};
OptionsReaderAndMessages result = parseCommandLineAndReadInputFiles({
"solc",
(tempDir1.path() / "input1.sol").string(),
(tempDir2.path() / "input2.sol").string(),
"--ignore-missing",
"--no-color",
});
BOOST_TEST(result.success);
BOOST_TEST(result.stderrContent == "Info: \"" + (tempDir2.path() / "input2.sol").string() + "\" is not found. Skipping.\n");
BOOST_TEST(result.options.input.mode == InputMode::Compiler);
BOOST_TEST(!result.options.input.addStdin);
BOOST_CHECK_EQUAL(result.reader.sourceUnits(), expectedSources);
BOOST_CHECK_EQUAL(result.reader.allowedDirectories(), expectedAllowedPaths);
}
BOOST_AUTO_TEST_CASE(cli_ignore_missing_no_files_exist)
{
TemporaryDirectory tempDir(TEST_CASE_NAME);
std::string expectedMessage =
"Info: \"" + (tempDir.path() / "input1.sol").string() + "\" is not found. Skipping.\n"
"Info: \"" + (tempDir.path() / "input2.sol").string() + "\" is not found. Skipping.\n"
"Error: All specified input files either do not exist or are not regular files.\n";
OptionsReaderAndMessages result = runCLI({
"solc",
(tempDir.path() / "input1.sol").string(),
(tempDir.path() / "input2.sol").string(),
"--ignore-missing",
"--no-color",
});
BOOST_TEST(!result.success);
BOOST_TEST(result.stderrContent == expectedMessage);
}
BOOST_AUTO_TEST_CASE(cli_not_a_file)
{
TemporaryDirectory tempDir(TEST_CASE_NAME);
std::string expectedMessage = "\"" + tempDir.path().string() + "\" is not a valid file.";
BOOST_CHECK_EXCEPTION(
parseCommandLineAndReadInputFiles({"solc", tempDir.path().string()}),
CommandLineValidationError,
[&](auto const& _exception) { BOOST_TEST(_exception.what() == expectedMessage); return true; }
);
}
BOOST_AUTO_TEST_CASE(standard_json_base_path)
{
TemporaryDirectory tempDir(TEST_CASE_NAME);
TemporaryWorkingDirectory tempWorkDir(tempDir.path().root_path());
OptionsReaderAndMessages result = parseCommandLineAndReadInputFiles({
"solc",
"--standard-json",
"--base-path=" + tempDir.path().string(),
});
BOOST_TEST(result.success);
BOOST_TEST(result.stderrContent == "");
BOOST_TEST(result.options.input.mode == InputMode::StandardJson);
BOOST_TEST(result.options.input.addStdin);
BOOST_TEST(result.options.input.paths.empty());
BOOST_TEST(result.reader.sourceUnits().empty());
BOOST_TEST(result.reader.allowedDirectories().empty());
BOOST_TEST(result.reader.basePath() == "/" / tempDir.path().relative_path());
}
BOOST_AUTO_TEST_CASE(standard_json_no_input_file)
{
OptionsReaderAndMessages result = parseCommandLineAndReadInputFiles({"solc", "--standard-json"});
BOOST_TEST(result.success);
BOOST_TEST(result.stderrContent == "");
BOOST_TEST(result.options.input.mode == InputMode::StandardJson);
BOOST_TEST(result.options.input.addStdin);
BOOST_TEST(result.options.input.paths.empty());
BOOST_TEST(result.reader.sourceUnits().empty());
BOOST_TEST(result.reader.allowedDirectories().empty());
}
BOOST_AUTO_TEST_CASE(standard_json_dash)
{
OptionsReaderAndMessages result = parseCommandLineAndReadInputFiles({"solc", "--standard-json", "-"});
BOOST_TEST(result.success);
BOOST_TEST(result.stderrContent == "");
BOOST_TEST(result.options.input.mode == InputMode::StandardJson);
BOOST_TEST(result.options.input.addStdin);
BOOST_TEST(result.reader.sourceUnits().empty());
BOOST_TEST(result.reader.allowedDirectories().empty());
}
BOOST_AUTO_TEST_CASE(standard_json_one_input_file)
{
TemporaryDirectory tempDir(TEST_CASE_NAME);
createFilesWithParentDirs({tempDir.path() / "input.json"});
std::vector<std::string> commandLine = {"solc", "--standard-json", (tempDir.path() / "input.json").string()};
OptionsReaderAndMessages result = parseCommandLineAndReadInputFiles(commandLine);
BOOST_TEST(result.success);
BOOST_TEST(result.stderrContent == "");
BOOST_TEST(result.options.input.mode == InputMode::StandardJson);
BOOST_TEST(!result.options.input.addStdin);
BOOST_TEST(result.options.input.paths == PathSet{tempDir.path() / "input.json"});
BOOST_TEST(result.reader.allowedDirectories().empty());
}
BOOST_AUTO_TEST_CASE(standard_json_two_input_files)
{
std::string expectedMessage =
"Too many input files for --standard-json.\n"
"Please either specify a single file name or provide its content on standard input.";
BOOST_CHECK_EXCEPTION(
parseCommandLineAndReadInputFiles({"solc", "--standard-json", "input1.json", "input2.json"}),
CommandLineValidationError,
[&](auto const& _exception) { BOOST_TEST(_exception.what() == expectedMessage); return true; }
);
}
BOOST_AUTO_TEST_CASE(standard_json_one_input_file_and_stdin)
{
std::string expectedMessage =
"Too many input files for --standard-json.\n"
"Please either specify a single file name or provide its content on standard input.";
BOOST_CHECK_EXCEPTION(
parseCommandLineAndReadInputFiles({"solc", "--standard-json", "input1.json", "-"}),
CommandLineValidationError,
[&](auto const& _exception) { BOOST_TEST(_exception.what() == expectedMessage); return true; }
);
}
BOOST_AUTO_TEST_CASE(standard_json_ignore_missing)
{
TemporaryDirectory tempDir(TEST_CASE_NAME);
// This option is pretty much useless Standard JSON mode.
std::string expectedMessage =
"All specified input files either do not exist or are not regular files.";
BOOST_CHECK_EXCEPTION(
parseCommandLineAndReadInputFiles({
"solc",
"--standard-json",
(tempDir.path() / "input.json").string(),
"--ignore-missing",
}),
CommandLineValidationError,
[&](auto const& _exception) { BOOST_TEST(_exception.what() == expectedMessage); return true; }
);
}
BOOST_AUTO_TEST_CASE(standard_json_remapping)
{
std::string expectedMessage =
"Import remappings are not accepted on the command line in Standard JSON mode.\n"
"Please put them under 'settings.remappings' in the JSON input.";
BOOST_CHECK_EXCEPTION(
parseCommandLineAndReadInputFiles({"solc", "--standard-json", "a=b"}),
CommandLineValidationError,
[&](auto const& _exception) { BOOST_TEST(_exception.what() == expectedMessage); return true; }
);
}
BOOST_AUTO_TEST_CASE(cli_paths_to_source_unit_names_no_base_path)
{
TemporaryDirectory tempDirCurrent(TEST_CASE_NAME);
TemporaryDirectory tempDirOther(TEST_CASE_NAME);
TemporaryWorkingDirectory tempWorkDir(tempDirCurrent);
soltestAssert(tempDirCurrent.path().is_absolute(), "");
soltestAssert(tempDirOther.path().is_absolute(), "");
// NOTE: On macOS the path usually contains symlinks which prevents base path from being stripped.
// Use canonical() to resolve symnlinks and get consistent results on all platforms.
boost::filesystem::path currentDirNoSymlinks = boost::filesystem::canonical(tempDirCurrent);
boost::filesystem::path otherDirNoSymlinks = boost::filesystem::canonical(tempDirOther);
boost::filesystem::path expectedOtherDir = "/" / otherDirNoSymlinks.relative_path();
soltestAssert(expectedOtherDir.is_absolute() || expectedOtherDir.root_path() == "/", "");
std::vector<std::string> commandLine = {
"solc",
"contract1.sol", // Relative path
"c/d/contract2.sol", // Relative path with subdirectories
currentDirNoSymlinks.string() + "/contract3.sol", // Absolute path inside working dir
otherDirNoSymlinks.string() + "/contract4.sol", // Absolute path outside of working dir
};
CommandLineOptions expectedOptions;
expectedOptions.input.paths = {
"contract1.sol",
"c/d/contract2.sol",
currentDirNoSymlinks / "contract3.sol",
otherDirNoSymlinks / "contract4.sol",
};
expectedOptions.modelChecker.initialize = true;
std::map<std::string, std::string> expectedSources = {
{"contract1.sol", ""},
{"c/d/contract2.sol", ""},
{"contract3.sol", ""},
{expectedOtherDir.generic_string() + "/contract4.sol", ""},
};
FileReader::FileSystemPathSet expectedAllowedDirectories = {
currentDirNoSymlinks / "c/d",
currentDirNoSymlinks,
otherDirNoSymlinks,
};
createFilesWithParentDirs(expectedOptions.input.paths);
OptionsReaderAndMessages result = parseCommandLineAndReadInputFiles(commandLine);
BOOST_TEST(result.stderrContent == "");
BOOST_TEST(result.stdoutContent == "");
BOOST_REQUIRE(result.success);
BOOST_TEST(result.options == expectedOptions);
BOOST_TEST(result.reader.sourceUnits() == expectedSources);
BOOST_TEST(result.reader.allowedDirectories() == expectedAllowedDirectories);
BOOST_TEST(result.reader.basePath() == "");
}
BOOST_AUTO_TEST_CASE(cli_paths_to_source_unit_names_base_path_same_as_work_dir)
{
TemporaryDirectory tempDirCurrent(TEST_CASE_NAME);
TemporaryDirectory tempDirOther(TEST_CASE_NAME);
TemporaryWorkingDirectory tempWorkDir(tempDirCurrent);
soltestAssert(tempDirCurrent.path().is_absolute(), "");
soltestAssert(tempDirOther.path().is_absolute(), "");
// NOTE: On macOS the path usually contains symlinks which prevents base path from being stripped.
// Use canonical() to resolve symnlinks and get consistent results on all platforms.
boost::filesystem::path currentDirNoSymlinks = boost::filesystem::canonical(tempDirCurrent);
boost::filesystem::path otherDirNoSymlinks = boost::filesystem::canonical(tempDirOther);
boost::filesystem::path expectedWorkDir = "/" / boost::filesystem::current_path().relative_path();
boost::filesystem::path expectedOtherDir = "/" / otherDirNoSymlinks.relative_path();
soltestAssert(expectedWorkDir.is_absolute() || expectedWorkDir.root_path() == "/", "");
soltestAssert(expectedOtherDir.is_absolute() || expectedOtherDir.root_path() == "/", "");
std::vector<std::string> commandLine = {
"solc",
"--base-path=" + currentDirNoSymlinks.string(),
"contract1.sol", // Relative path
"c/d/contract2.sol", // Relative path with subdirectories
currentDirNoSymlinks.string() + "/contract3.sol", // Absolute path inside working dir
otherDirNoSymlinks.string() + "/contract4.sol", // Absolute path outside of working dir
};
CommandLineOptions expectedOptions;
expectedOptions.input.paths = {
"contract1.sol",
"c/d/contract2.sol",
currentDirNoSymlinks / "contract3.sol",
otherDirNoSymlinks / "contract4.sol",
};
expectedOptions.input.basePath = currentDirNoSymlinks;
expectedOptions.modelChecker.initialize = true;
std::map<std::string, std::string> expectedSources = {
{"contract1.sol", ""},
{"c/d/contract2.sol", ""},
{"contract3.sol", ""},
{expectedOtherDir.generic_string() + "/contract4.sol", ""},
};
FileReader::FileSystemPathSet expectedAllowedDirectories = {
currentDirNoSymlinks / "c/d",
currentDirNoSymlinks,
otherDirNoSymlinks,
};
createFilesWithParentDirs(expectedOptions.input.paths);
OptionsReaderAndMessages result = parseCommandLineAndReadInputFiles(commandLine);
BOOST_TEST(result.stderrContent == "");
BOOST_TEST(result.stdoutContent == "");
BOOST_REQUIRE(result.success);
BOOST_TEST(result.options == expectedOptions);
BOOST_TEST(result.reader.sourceUnits() == expectedSources);
BOOST_TEST(result.reader.allowedDirectories() == expectedAllowedDirectories);
BOOST_TEST(result.reader.basePath() == expectedWorkDir);
}
BOOST_AUTO_TEST_CASE(cli_paths_to_source_unit_names_base_path_different_from_work_dir)
{
TemporaryDirectory tempDirCurrent(TEST_CASE_NAME);
TemporaryDirectory tempDirOther(TEST_CASE_NAME);
TemporaryDirectory tempDirBase(TEST_CASE_NAME);
TemporaryWorkingDirectory tempWorkDir(tempDirCurrent);
soltestAssert(tempDirCurrent.path().is_absolute(), "");
soltestAssert(tempDirOther.path().is_absolute(), "");
soltestAssert(tempDirBase.path().is_absolute(), "");
// NOTE: On macOS the path usually contains symlinks which prevents base path from being stripped.
// Use canonical() to resolve symnlinks and get consistent results on all platforms.
boost::filesystem::path currentDirNoSymlinks = boost::filesystem::canonical(tempDirCurrent);
boost::filesystem::path otherDirNoSymlinks = boost::filesystem::canonical(tempDirOther);
boost::filesystem::path baseDirNoSymlinks = boost::filesystem::canonical(tempDirBase);
boost::filesystem::path expectedWorkDir = "/" / boost::filesystem::current_path().relative_path();
boost::filesystem::path expectedCurrentDir = "/" / currentDirNoSymlinks.relative_path();
boost::filesystem::path expectedOtherDir = "/" / otherDirNoSymlinks.relative_path();
boost::filesystem::path expectedBaseDir = "/" / baseDirNoSymlinks.relative_path();
soltestAssert(expectedWorkDir.is_absolute() || expectedWorkDir.root_path() == "/", "");
soltestAssert(expectedCurrentDir.is_absolute() || expectedCurrentDir.root_path() == "/", "");
soltestAssert(expectedOtherDir.is_absolute() || expectedOtherDir.root_path() == "/", "");
soltestAssert(expectedBaseDir.is_absolute() || expectedBaseDir.root_path() == "/", "");
std::vector<std::string> commandLine = {
"solc",
"--base-path=" + baseDirNoSymlinks.string(),
"contract1.sol", // Relative path
"c/d/contract2.sol", // Relative path with subdirectories
currentDirNoSymlinks.string() + "/contract3.sol", // Absolute path inside working dir
otherDirNoSymlinks.string() + "/contract4.sol", // Absolute path outside of working dir
baseDirNoSymlinks.string() + "/contract5.sol", // Absolute path inside base path
};
CommandLineOptions expectedOptions;
expectedOptions.input.paths = {
"contract1.sol",
"c/d/contract2.sol",
currentDirNoSymlinks / "contract3.sol",
otherDirNoSymlinks / "contract4.sol",
baseDirNoSymlinks / "contract5.sol",
};
expectedOptions.input.basePath = baseDirNoSymlinks;
expectedOptions.modelChecker.initialize = true;
std::map<std::string, std::string> expectedSources = {
{expectedWorkDir.generic_string() + "/contract1.sol", ""},
{expectedWorkDir.generic_string() + "/c/d/contract2.sol", ""},
{expectedCurrentDir.generic_string() + "/contract3.sol", ""},
{expectedOtherDir.generic_string() + "/contract4.sol", ""},
{"contract5.sol", ""},
};
FileReader::FileSystemPathSet expectedAllowedDirectories = {
currentDirNoSymlinks / "c/d",
currentDirNoSymlinks,
otherDirNoSymlinks,
baseDirNoSymlinks,
};
createFilesWithParentDirs(expectedOptions.input.paths);
OptionsReaderAndMessages result = parseCommandLineAndReadInputFiles(commandLine);
BOOST_TEST(result.stderrContent == "");
BOOST_TEST(result.stdoutContent == "");
BOOST_REQUIRE(result.success);
BOOST_TEST(result.options == expectedOptions);
BOOST_TEST(result.reader.sourceUnits() == expectedSources);
BOOST_TEST(result.reader.allowedDirectories() == expectedAllowedDirectories);
BOOST_TEST(result.reader.basePath() == expectedBaseDir);
}
BOOST_AUTO_TEST_CASE(cli_paths_to_source_unit_names_relative_base_path)
{
TemporaryDirectory tempDirCurrent(TEST_CASE_NAME);
TemporaryDirectory tempDirOther(TEST_CASE_NAME);
TemporaryWorkingDirectory tempWorkDir(tempDirCurrent);
soltestAssert(tempDirCurrent.path().is_absolute(), "");
soltestAssert(tempDirOther.path().is_absolute(), "");
// NOTE: On macOS the path usually contains symlinks which prevents base path from being stripped.
// Use canonical() to resolve symnlinks and get consistent results on all platforms.
boost::filesystem::path currentDirNoSymlinks = boost::filesystem::canonical(tempDirCurrent);
boost::filesystem::path otherDirNoSymlinks = boost::filesystem::canonical(tempDirOther);
boost::filesystem::path expectedWorkDir = "/" / boost::filesystem::current_path().relative_path();
boost::filesystem::path expectedOtherDir = "/" / otherDirNoSymlinks.relative_path();
soltestAssert(expectedWorkDir.is_absolute() || expectedWorkDir.root_path() == "/", "");
soltestAssert(expectedOtherDir.is_absolute() || expectedOtherDir.root_path() == "/", "");
std::vector<std::string> commandLine = {
"solc",
"--base-path=base",
"contract1.sol", // Relative path outside of base path
"base/contract2.sol", // Relative path inside base path
currentDirNoSymlinks.string() + "/contract3.sol", // Absolute path inside working dir
currentDirNoSymlinks.string() + "/base/contract4.sol", // Absolute path inside base path
otherDirNoSymlinks.string() + "/contract5.sol", // Absolute path outside of working dir
otherDirNoSymlinks.string() + "/base/contract6.sol", // Absolute path outside of working dir
};
CommandLineOptions expectedOptions;
expectedOptions.input.paths = {
"contract1.sol",
"base/contract2.sol",
currentDirNoSymlinks / "contract3.sol",
currentDirNoSymlinks / "base/contract4.sol",
otherDirNoSymlinks / "contract5.sol",
otherDirNoSymlinks / "base/contract6.sol",
};
expectedOptions.input.basePath = "base";
expectedOptions.modelChecker.initialize = true;
std::map<std::string, std::string> expectedSources = {
{expectedWorkDir.generic_string() + "/contract1.sol", ""},
{"contract2.sol", ""},
{expectedWorkDir.generic_string() + "/contract3.sol", ""},
{"contract4.sol", ""},
{expectedOtherDir.generic_string() + "/contract5.sol", ""},
{expectedOtherDir.generic_string() + "/base/contract6.sol", ""},
};
FileReader::FileSystemPathSet expectedAllowedDirectories = {
currentDirNoSymlinks / "base",
currentDirNoSymlinks,
otherDirNoSymlinks,
otherDirNoSymlinks / "base",
};
createFilesWithParentDirs(expectedOptions.input.paths);
OptionsReaderAndMessages result = parseCommandLineAndReadInputFiles(commandLine);
BOOST_TEST(result.stderrContent == "");
BOOST_TEST(result.stdoutContent == "");
BOOST_REQUIRE(result.success);
BOOST_TEST(result.options == expectedOptions);
BOOST_TEST(result.reader.sourceUnits() == expectedSources);
BOOST_TEST(result.reader.allowedDirectories() == expectedAllowedDirectories);
BOOST_TEST(result.reader.basePath() == expectedWorkDir / "base");
}
BOOST_AUTO_TEST_CASE(cli_paths_to_source_unit_names_normalization_and_weird_names)
{
TemporaryDirectory tempDir({"x/y/z"}, TEST_CASE_NAME);
TemporaryWorkingDirectory tempWorkDir(tempDir.path() / "x/y/z");
soltestAssert(tempDir.path().is_absolute(), "");
std::string uncPath = "//" + tempDir.path().relative_path().generic_string();
soltestAssert(FileReader::isUNCPath(uncPath), "");
boost::filesystem::path tempDirNoSymlinks = boost::filesystem::canonical(tempDir);
boost::filesystem::path expectedWorkDir = "/" / boost::filesystem::current_path().relative_path();
soltestAssert(expectedWorkDir.is_absolute() || expectedWorkDir.root_path() == "/", "");
std::vector<std::string> commandLine = {
"solc",
#if !defined(_WIN32)
// URLs. We interpret them as local paths.
// Note that : is not allowed in file names on Windows.
"file://c/d/contract1.sol",
"file:///c/d/contract2.sol",
"https://example.com/contract3.sol",
#endif
// Redundant slashes
"a/b//contract4.sol",
"a/b///contract5.sol",
"a/b////contract6.sol",
// Dot segments
"./a/b/contract7.sol",
"././a/b/contract8.sol",
"a/./b/contract9.sol",
"a/././b/contract10.sol",
// Dot dot segments
"../a/b/contract11.sol",
"../../a/b/contract12.sol",
"a/../b/contract13.sol",
"a/b/../../contract14.sol",
tempDirNoSymlinks.string() + "/x/y/z/a/../b/contract15.sol",
tempDirNoSymlinks.string() + "/x/y/z/a/b/../../contract16.sol",
// Dot dot segments going beyond filesystem root
"/../" + tempDir.path().relative_path().generic_string() + "/contract17.sol",
"/../../" + tempDir.path().relative_path().generic_string() + "/contract18.sol",
#if !defined(_WIN32)
// Name conflict with source unit name of stdin.
// Note that < and > are not allowed in file names on Windows.
"<stdin>",
// UNC paths on UNIX just resolve into normal paths. On Windows this would be an network
// share (and an error unless the share actually exists so I can't test it here).
uncPath + "/contract19.sol",
// Windows paths on non-Windows systems.
// Note that on Windows we tested them already just by using absolute paths.
"a\\b\\contract20.sol",
"C:\\a\\b\\contract21.sol",
#endif
};
CommandLineOptions expectedOptions;
expectedOptions.input.paths = {
#if !defined(_WIN32)
"file://c/d/contract1.sol",
"file:///c/d/contract2.sol",
"https://example.com/contract3.sol",
#endif
"a/b//contract4.sol",
"a/b///contract5.sol",
"a/b////contract6.sol",
"./a/b/contract7.sol",
"././a/b/contract8.sol",
"a/./b/contract9.sol",
"a/././b/contract10.sol",
"../a/b/contract11.sol",
"../../a/b/contract12.sol",
"a/../b/contract13.sol",
"a/b/../../contract14.sol",
tempDirNoSymlinks.string() + "/x/y/z/a/../b/contract15.sol",
tempDirNoSymlinks.string() + "/x/y/z/a/b/../../contract16.sol",
"/../" + tempDir.path().relative_path().string() + "/contract17.sol",
"/../../" + tempDir.path().relative_path().string() + "/contract18.sol",
#if !defined(_WIN32)
"<stdin>",
uncPath + "/contract19.sol",
"a\\b\\contract20.sol",
"C:\\a\\b\\contract21.sol",
#endif
};
expectedOptions.modelChecker.initialize = true;
std::map<std::string, std::string> expectedSources = {
#if !defined(_WIN32)
{"file:/c/d/contract1.sol", ""},
{"file:/c/d/contract2.sol", ""},
{"https:/example.com/contract3.sol", ""},
#endif
{"a/b/contract4.sol", ""},
{"a/b/contract5.sol", ""},
{"a/b/contract6.sol", ""},
{"a/b/contract7.sol", ""},
{"a/b/contract8.sol", ""},
{"a/b/contract9.sol", ""},
{"a/b/contract10.sol", ""},
{expectedWorkDir.parent_path().generic_string() + "/a/b/contract11.sol", ""},
{expectedWorkDir.parent_path().parent_path().generic_string() + "/a/b/contract12.sol", ""},
{"b/contract13.sol", ""},
{"contract14.sol", ""},
{"b/contract15.sol", ""},
{"contract16.sol", ""},
{"/" + tempDir.path().relative_path().generic_string() + "/contract17.sol", ""},
{"/" + tempDir.path().relative_path().generic_string() + "/contract18.sol", ""},
#if !defined(_WIN32)
{"<stdin>", ""},
{uncPath + "/contract19.sol", ""},
{"a\\b\\contract20.sol", ""},
{"C:\\a\\b\\contract21.sol", ""},
#endif
};
FileReader::FileSystemPathSet expectedAllowedDirectories = {
#if !defined(_WIN32)
tempDirNoSymlinks / "x/y/z/file:/c/d",
tempDirNoSymlinks / "x/y/z/https:/example.com",
#endif
tempDirNoSymlinks / "x/y/z/a/b",
tempDirNoSymlinks / "x/y/z",
tempDirNoSymlinks / "x/y/z/b",
tempDirNoSymlinks / "x/y/a/b",
tempDirNoSymlinks / "x/a/b",
tempDirNoSymlinks,
#if !defined(_WIN32)
boost::filesystem::canonical(uncPath),
#endif
};
createFilesWithParentDirs(expectedOptions.input.paths);
OptionsReaderAndMessages result = parseCommandLineAndReadInputFiles(commandLine);
BOOST_TEST(result.stderrContent == "");
BOOST_TEST(result.stdoutContent == "");
BOOST_REQUIRE(result.success);
BOOST_TEST(result.options == expectedOptions);
BOOST_TEST(result.reader.sourceUnits() == expectedSources);
BOOST_TEST(result.reader.allowedDirectories() == expectedAllowedDirectories);
BOOST_TEST(result.reader.basePath() == expectedOptions.input.basePath);
}
BOOST_AUTO_TEST_CASE(cli_paths_to_source_unit_names_symlinks)
{
TemporaryDirectory tempDir({"r/"}, TEST_CASE_NAME);
createFilesWithParentDirs({tempDir.path() / "x/y/z/contract.sol"});
TemporaryWorkingDirectory tempWorkDir(tempDir.path() / "r");
if (
!createSymlinkIfSupportedByFilesystem("../x/y", tempDir.path() / "r/sym", true) ||
!createSymlinkIfSupportedByFilesystem("contract.sol", tempDir.path() / "x/y/z/contract_symlink.sol", false)
)
return;
boost::filesystem::path expectedWorkDir = "/" / boost::filesystem::current_path().relative_path();
soltestAssert(expectedWorkDir.is_absolute() || expectedWorkDir.root_path() == "/", "");
std::vector<std::string> commandLine = {
"solc",
"--base-path=../r/sym/z/",
"sym/z/contract.sol", // File accessed directly + same dir symlink as base path
"../x/y/z/contract.sol", // File accessed directly + different dir symlink than base path
"sym/z/contract_symlink.sol", // File accessed via symlink + same dir symlink as base path
"../x/y/z/contract_symlink.sol", // File accessed via symlink + different dir symlink than base path
};
CommandLineOptions expectedOptions;
expectedOptions.input.paths = {
"sym/z/contract.sol",
"../x/y/z/contract.sol",
"sym/z/contract_symlink.sol",
"../x/y/z/contract_symlink.sol",
};
expectedOptions.input.basePath = "../r/sym/z/";
expectedOptions.modelChecker.initialize = true;
std::map<std::string, std::string> expectedSources = {
{"contract.sol", ""},
{(expectedWorkDir.parent_path() / "x/y/z/contract.sol").generic_string(), ""},
{"contract_symlink.sol", ""},
{(expectedWorkDir.parent_path() / "x/y/z/contract_symlink.sol").generic_string(), ""},
};
FileReader::FileSystemPathSet expectedAllowedDirectories = {
boost::filesystem::canonical(tempDir) / "x/y/z",
};
OptionsReaderAndMessages result = parseCommandLineAndReadInputFiles(commandLine);
BOOST_TEST(result.stderrContent == "");
BOOST_TEST(result.stdoutContent == "");
BOOST_REQUIRE(result.success);
BOOST_TEST(result.options == expectedOptions);
BOOST_TEST(result.reader.sourceUnits() == expectedSources);
BOOST_TEST(result.reader.allowedDirectories() == expectedAllowedDirectories);
BOOST_TEST(result.reader.basePath() == expectedWorkDir / "sym/z/");
}
BOOST_AUTO_TEST_CASE(cli_paths_to_source_unit_names_base_path_and_stdin)
{
TemporaryDirectory tempDir(TEST_CASE_NAME);
TemporaryWorkingDirectory tempWorkDir(tempDir);
boost::filesystem::create_directories(tempDir.path() / "base");
boost::filesystem::path expectedWorkDir = "/" / boost::filesystem::current_path().relative_path();
std::vector<std::string> commandLine = {"solc", "--base-path=base", "-"};
CommandLineOptions expectedOptions;
expectedOptions.input.addStdin = true;
expectedOptions.input.basePath = "base";
expectedOptions.modelChecker.initialize = true;
std::map<std::string, std::string> expectedSources = {
{"<stdin>", ""},
};
FileReader::FileSystemPathSet expectedAllowedDirectories = {};
createFilesWithParentDirs(expectedOptions.input.paths);
OptionsReaderAndMessages result = parseCommandLineAndReadInputFiles(commandLine);
BOOST_TEST(result.stderrContent == "");
BOOST_TEST(result.stdoutContent == "");
BOOST_REQUIRE(result.success);
BOOST_TEST(result.options == expectedOptions);
BOOST_TEST(result.reader.sourceUnits() == expectedSources);
BOOST_TEST(result.reader.allowedDirectories() == expectedAllowedDirectories);
BOOST_TEST(result.reader.basePath() == expectedWorkDir / "base");
}
BOOST_AUTO_TEST_CASE(cli_include_paths)
{
TemporaryDirectory tempDir({"base/", "include/", "lib/nested/"}, TEST_CASE_NAME);
TemporaryWorkingDirectory tempWorkDir(tempDir);
std::string const mainContractSource = withPreamble(
"import \"contract.sol\";\n"
"import \"contract_via_callback.sol\";\n"
"import \"include.sol\";\n"
"import \"include_via_callback.sol\";\n"
"import \"nested.sol\";\n"
"import \"nested_via_callback.sol\";\n"
"import \"lib.sol\";\n"
"import \"lib_via_callback.sol\";\n"
);
std::string const onlyPreamble = withPreamble("");
createFilesWithParentDirs(
{
tempDir.path() / "base/contract.sol",
tempDir.path() / "base/contract_via_callback.sol",
tempDir.path() / "include/include.sol",
tempDir.path() / "include/include_via_callback.sol",
tempDir.path() / "lib/nested/nested.sol",
tempDir.path() / "lib/nested/nested_via_callback.sol",
tempDir.path() / "lib/lib.sol",
tempDir.path() / "lib/lib_via_callback.sol",
},
onlyPreamble
);
createFilesWithParentDirs({tempDir.path() / "base/main.sol"}, mainContractSource);
boost::filesystem::path canonicalWorkDir = boost::filesystem::canonical(tempDir);
boost::filesystem::path expectedWorkDir = "/" / canonicalWorkDir.relative_path();
std::vector<std::string> commandLine = {
"solc",
"--no-color",
"--base-path=base/",
"--include-path=include/",
"--include-path=lib/nested",
"--include-path=lib/",
"base/main.sol",
"base/contract.sol",
"include/include.sol",
"lib/nested/nested.sol",
"lib/lib.sol",
};
CommandLineOptions expectedOptions;
expectedOptions.input.paths = {
"base/main.sol",
"base/contract.sol",
"include/include.sol",
"lib/nested/nested.sol",
"lib/lib.sol",
};
expectedOptions.input.basePath = "base/";
expectedOptions.input.includePaths = {
"include/",
"lib/nested",
"lib/",
};
expectedOptions.formatting.coloredOutput = false;
expectedOptions.modelChecker.initialize = true;
std::map<std::string, std::string> expectedSources = {
{"main.sol", mainContractSource},
{"contract.sol", onlyPreamble},
{"contract_via_callback.sol", onlyPreamble},
{"include.sol", onlyPreamble},
{"include_via_callback.sol", onlyPreamble},
{"nested.sol", onlyPreamble},
{"nested_via_callback.sol", onlyPreamble},
{"lib.sol", onlyPreamble},
{"lib_via_callback.sol", onlyPreamble},
};
std::vector<boost::filesystem::path> expectedIncludePaths = {
expectedWorkDir / "include/",
expectedWorkDir / "lib/nested",
expectedWorkDir / "lib/",
};
FileReader::FileSystemPathSet expectedAllowedDirectories = {
canonicalWorkDir / "base",
canonicalWorkDir / "include",
canonicalWorkDir / "lib/nested",
canonicalWorkDir / "lib",
};
std::string const expectedStdoutContent = "Compiler run successful. No contracts to compile.\n";
OptionsReaderAndMessages result = runCLI(commandLine, "");
BOOST_TEST(result.stderrContent == "");
if (SemVerVersion{std::string(VersionString)}.isPrerelease())
BOOST_TEST(result.stdoutContent == "");
else
BOOST_TEST(result.stdoutContent == expectedStdoutContent);
BOOST_REQUIRE(result.success);
BOOST_TEST(result.options == expectedOptions);
BOOST_TEST(result.reader.sourceUnits() == expectedSources);
BOOST_TEST(result.reader.includePaths() == expectedIncludePaths);
BOOST_TEST(result.reader.allowedDirectories() == expectedAllowedDirectories);
BOOST_TEST(result.reader.basePath() == expectedWorkDir / "base/");
}
BOOST_AUTO_TEST_CASE(cli_no_contracts_to_compile)
{
std::string const contractSource = R"(
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.0;
enum Status { test }
)";
std::string const expectedStdoutContent = "Compiler run successful. No contracts to compile.\n";
OptionsReaderAndMessages result = runCLI({"solc", "-"}, contractSource);
if (SemVerVersion{std::string(VersionString)}.isPrerelease())
BOOST_TEST(result.stdoutContent == "");
else
BOOST_TEST(result.stdoutContent == expectedStdoutContent);
BOOST_REQUIRE(result.success);
}
BOOST_AUTO_TEST_CASE(cli_no_output)
{
std::string const contractSource = R"(
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.0;
abstract contract A {
function B() public virtual returns(uint);
})";
std::string const expectedStdoutContent = "Compiler run successful. No output generated.\n";
OptionsReaderAndMessages result = runCLI({"solc", "-"}, contractSource);
if (SemVerVersion{std::string(VersionString)}.isPrerelease())
BOOST_TEST(result.stdoutContent == "");
else
BOOST_TEST(result.stdoutContent == expectedStdoutContent);
BOOST_REQUIRE(result.success);
}
BOOST_AUTO_TEST_CASE(standard_json_include_paths)
{
TemporaryDirectory tempDir({"base/", "include/", "lib/nested/"}, TEST_CASE_NAME);
TemporaryWorkingDirectory tempWorkDir(tempDir);
std::string const mainContractSource = withPreamble(
"import 'contract_via_callback.sol';\n"
"import 'include_via_callback.sol';\n"
"import 'nested_via_callback.sol';\n"
"import 'lib_via_callback.sol';\n"
);
std::string const standardJsonInput = R"(
{
"language": "Solidity",
"sources": {
"main.sol": {"content": ")" + mainContractSource + R"("}
}
}
)";
std::string const onlyPreamble = withPreamble("");
createFilesWithParentDirs(
{
tempDir.path() / "base/contract_via_callback.sol",
tempDir.path() / "include/include_via_callback.sol",
tempDir.path() / "lib/nested/nested_via_callback.sol",
tempDir.path() / "lib/lib_via_callback.sol",
},
onlyPreamble
);
boost::filesystem::path expectedWorkDir = "/" / boost::filesystem::canonical(tempDir).relative_path();
std::vector<std::string> commandLine = {
"solc",
"--base-path=base/",
"--include-path=include/",
"--include-path=lib/nested",
"--include-path=lib/",
"--standard-json",
};
CommandLineOptions expectedOptions;
expectedOptions.input.mode = InputMode::StandardJson;
expectedOptions.input.paths = {};
expectedOptions.input.addStdin = true;
expectedOptions.input.basePath = "base/";
expectedOptions.input.includePaths = {
"include/",
"lib/nested",
"lib/",
};
expectedOptions.modelChecker.initialize = false;
// NOTE: Source code from Standard JSON does not end up in FileReader. This is not a problem
// because FileReader is only used once to initialize the compiler stack and after that
// its sources are irrelevant (even though the callback still stores everything it loads).
std::map<std::string, std::string> expectedSources = {
{"contract_via_callback.sol", onlyPreamble},
{"include_via_callback.sol", onlyPreamble},
{"nested_via_callback.sol", onlyPreamble},
{"lib_via_callback.sol", onlyPreamble},
};
std::vector<boost::filesystem::path> expectedIncludePaths = {
expectedWorkDir / "include/",
expectedWorkDir / "lib/nested",
expectedWorkDir / "lib/",
};
FileReader::FileSystemPathSet expectedAllowedDirectories = {};
OptionsReaderAndMessages result = runCLI(commandLine, standardJsonInput);
Json parsedStdout;
std::string jsonParsingErrors;
BOOST_TEST(util::jsonParseStrict(result.stdoutContent, parsedStdout, &jsonParsingErrors));
BOOST_TEST(jsonParsingErrors == "");
for (Json const& errorDict: parsedStdout["errors"])
// The error list might contain pre-release compiler warning
BOOST_TEST(errorDict["severity"] != "error");
// we might be able to use ranges again, but the nlohmann::json support is not yet fully there.
// (parsedStdout["sources"].items() | ranges::views::keys | ranges::to<std::set>)
std::set<std::string> sources;
for (auto const& [key, _]: parsedStdout["sources"].items())
sources.insert(key);
BOOST_TEST(
sources ==
(expectedSources | ranges::views::keys | ranges::to<std::set>) + std::set<std::string>{"main.sol"}
);
BOOST_REQUIRE(result.success);
BOOST_TEST(result.options == expectedOptions);
BOOST_TEST(result.reader.sourceUnits() == expectedSources);
BOOST_TEST(result.reader.includePaths() == expectedIncludePaths);
BOOST_TEST(result.reader.allowedDirectories() == expectedAllowedDirectories);
BOOST_TEST(result.reader.basePath() == expectedWorkDir / "base/");
}
BOOST_AUTO_TEST_CASE(cli_include_paths_empty_path)
{
TemporaryDirectory tempDir({"base/", "include/"}, TEST_CASE_NAME);
TemporaryWorkingDirectory tempWorkDir(tempDir);
createFilesWithParentDirs({tempDir.path() / "base/main.sol"});
std::string expectedMessage = "Empty values are not allowed in --include-path.";
BOOST_CHECK_EXCEPTION(
parseCommandLineAndReadInputFiles({
"solc",
"--base-path=base/",
"--include-path", "include/",
"--include-path", "",
"base/main.sol",
}),
CommandLineValidationError,
[&](auto const& _exception) { BOOST_TEST(_exception.what() == expectedMessage); return true; }
);
}
BOOST_AUTO_TEST_CASE(cli_include_paths_without_base_path)
{
TemporaryDirectory tempDir(TEST_CASE_NAME);
TemporaryWorkingDirectory tempWorkDir(tempDir);
createFilesWithParentDirs({tempDir.path() / "contract.sol"});
std::string expectedMessage = "--include-path option requires a non-empty base path.";
BOOST_CHECK_EXCEPTION(
parseCommandLineAndReadInputFiles({"solc", "--include-path", "include/", "contract.sol"}),
CommandLineValidationError,
[&](auto const& _exception) { BOOST_TEST(_exception.what() == expectedMessage); return true; }
);
}
BOOST_AUTO_TEST_CASE(cli_include_paths_should_detect_source_unit_name_collisions)
{
TemporaryDirectory tempDir({"dir1/", "dir2/", "dir3/"}, TEST_CASE_NAME);
TemporaryWorkingDirectory tempWorkDir(tempDir);
createFilesWithParentDirs({
"dir1/contract1.sol",
"dir1/contract2.sol",
"dir2/contract1.sol",
"dir2/contract2.sol",
});
boost::filesystem::path expectedWorkDir = "/" / boost::filesystem::canonical(tempDir).relative_path();
std::string expectedMessage =
"Source unit name collision detected. "
"The specified values of base path and/or include paths would result in multiple "
"input files being assigned the same source unit name:\n"
"contract1.sol matches: "
"\"" + (expectedWorkDir / "dir1/contract1.sol").generic_string() + "\", "
"\"" + (expectedWorkDir / "dir2/contract1.sol").generic_string() + "\"\n"
"contract2.sol matches: "
"\"" + (expectedWorkDir / "dir1/contract2.sol").generic_string() + "\", "
"\"" + (expectedWorkDir / "dir2/contract2.sol").generic_string() + "\"\n";
{
// import "contract1.sol" and import "contract2.sol" would be ambiguous:
BOOST_CHECK_EXCEPTION(
parseCommandLineAndReadInputFiles({
"solc",
"--base-path=dir1/",
"--include-path=dir2/",
"dir1/contract1.sol",
"dir2/contract1.sol",
"dir1/contract2.sol",
"dir2/contract2.sol",
}),
CommandLineValidationError,
[&](auto const& _exception) { BOOST_TEST(_exception.what() == expectedMessage); return true; }
);
}
{
// import "contract1.sol" and import "contract2.sol" would be ambiguous:
BOOST_CHECK_EXCEPTION(
parseCommandLineAndReadInputFiles({
"solc",
"--base-path=dir3/",
"--include-path=dir1/",
"--include-path=dir2/",
"dir1/contract1.sol",
"dir2/contract1.sol",
"dir1/contract2.sol",
"dir2/contract2.sol",
}),
CommandLineValidationError,
[&](auto const& _exception) { BOOST_TEST(_exception.what() == expectedMessage); return true; }
);
}
{
// No conflict if files with the same name exist but only one is given to the compiler.
std::vector<std::string> commandLine = {
"solc",
"--base-path=dir3/",
"--include-path=dir1/",
"--include-path=dir2/",
"dir1/contract1.sol",
"dir1/contract2.sol",
};
OptionsReaderAndMessages result = parseCommandLineAndReadInputFiles(commandLine);
BOOST_TEST(result.stderrContent == "");
BOOST_REQUIRE(result.success);
}
{
// The same file specified multiple times is not a conflict.
std::vector<std::string> commandLine = {
"solc",
"--base-path=dir3/",
"--include-path=dir1/",
"--include-path=dir2/",
"dir1/contract1.sol",
"dir1/contract1.sol",
"./dir1/contract1.sol",
};
OptionsReaderAndMessages result = parseCommandLineAndReadInputFiles(commandLine);
BOOST_TEST(result.stderrContent == "");
BOOST_REQUIRE(result.success);
}
}
BOOST_AUTO_TEST_CASE(cli_include_paths_should_allow_duplicate_paths)
{
TemporaryDirectory tempDir({"dir1/", "dir2/"}, TEST_CASE_NAME);
TemporaryWorkingDirectory tempWorkDir(tempDir);
createFilesWithParentDirs({"dir1/contract.sol"});
boost::filesystem::path expectedWorkDir = "/" / boost::filesystem::canonical(tempDir).relative_path();
boost::filesystem::path expectedTempDir = "/" / tempDir.path().relative_path();
std::vector<std::string> commandLine = {
"solc",
"--base-path=dir1/",
"--include-path", "dir1",
"--include-path", "dir1",
"--include-path", "dir1/",
"--include-path", "dir1/",
"--include-path", "./dir1/",
"--include-path", "dir2/../dir1/",
"--include-path", (tempDir.path() / "dir1/").string(),
"--include-path", (expectedWorkDir / "dir1/").string(),
"--include-path", "dir1/",
"dir1/contract.sol",
};
// Duplicates do not affect the result but are not removed from the include path list.
std::vector<boost::filesystem::path> expectedIncludePaths = {
expectedWorkDir / "dir1",
expectedWorkDir / "dir1",
expectedWorkDir / "dir1/",
expectedWorkDir / "dir1/",
expectedWorkDir / "dir1/",
expectedWorkDir / "dir1/",
// NOTE: On macOS expectedTempDir usually contains a symlink and therefore for us it's
// different from expectedWorkDir.
expectedTempDir / "dir1/",
expectedWorkDir / "dir1/",
expectedWorkDir / "dir1/",
};
OptionsReaderAndMessages result = parseCommandLineAndReadInputFiles(commandLine);
BOOST_TEST(result.stderrContent == "");
BOOST_REQUIRE(result.success);
BOOST_TEST(result.reader.includePaths() == expectedIncludePaths);
BOOST_TEST(result.reader.basePath() == expectedWorkDir / "dir1/");
}
BOOST_AUTO_TEST_CASE(cli_include_paths_ambiguous_import)
{
TemporaryDirectory tempDir({"base/", "include/"}, TEST_CASE_NAME);
TemporaryWorkingDirectory tempWorkDir(tempDir);
// Ambiguous: both base/contract.sol and include/contract.sol match the import.
std::string const mainContractSource = withPreamble("import \"contract.sol\";");
createFilesWithParentDirs({"base/contract.sol", "include/contract.sol"}, withPreamble(""));
boost::filesystem::path expectedWorkDir = "/" / boost::filesystem::canonical(tempDir).relative_path();
std::vector<std::string> commandLine = {
"solc",
"--no-color",
"--base-path=base/",
"--include-path=include/",
"-",
};
std::string expectedMessage =
"Error: Source \"contract.sol\" not found: Ambiguous import. "
"Multiple matching files found inside base path and/or include paths: \"" +
(expectedWorkDir / "base/contract.sol").generic_string() + "\", \"" +
(expectedWorkDir / "include/contract.sol").generic_string() + "\".\n"
" --> <stdin>:3:1:\n"
" |\n"
"3 | import \"contract.sol\";\n"
" | ^^^^^^^^^^^^^^^^^^^^^^\n\n";
OptionsReaderAndMessages result = runCLI(commandLine, mainContractSource);
BOOST_TEST(result.stderrContent == expectedMessage);
BOOST_REQUIRE(!result.success);
}
BOOST_AUTO_TEST_SUITE_END()
} // namespace solidity::frontend::test
| 50,935
|
C++
|
.cpp
| 1,201
| 39.880933
| 130
| 0.725817
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,906
|
fuzzer_common.cpp
|
ethereum_solidity/test/tools/fuzzer_common.cpp
|
/*
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
#include <test/tools/fuzzer_common.h>
#include <libsolidity/interface/OptimiserSettings.h>
#include <libsolidity/interface/CompilerStack.h>
#include <libsolidity/formal/ModelCheckerSettings.h>
#include <libsolutil/JSON.h>
#include <libevmasm/Assembly.h>
#include <libevmasm/ConstantOptimiser.h>
#include <libsolc/libsolc.h>
#include <liblangutil/Exceptions.h>
#include <sstream>
using namespace solidity;
using namespace solidity::evmasm;
using namespace solidity::frontend;
using namespace solidity::langutil;
using namespace solidity::util;
static std::vector<EVMVersion> s_evmVersions = EVMVersion::allVersions();
void FuzzerUtil::testCompilerJsonInterface(std::string const& _input, bool _optimize, bool _quiet)
{
if (!_quiet)
std::cout << "Testing compiler " << (_optimize ? "with" : "without") << " optimizer." << std::endl;
Json config;
config["language"] = "Solidity";
config["sources"] = Json::object();
config["sources"][""] = Json::object();
config["sources"][""]["content"] = _input;
config["settings"] = Json::object();
config["settings"]["optimizer"] = Json::object();
config["settings"]["optimizer"]["enabled"] = _optimize;
config["settings"]["optimizer"]["runs"] = static_cast<int>(OptimiserSettings{}.expectedExecutionsPerDeployment);
config["settings"]["evmVersion"] = "berlin";
// Enable all SourceUnit-level outputs.
config["settings"]["outputSelection"]["*"][""][0] = "*";
// Enable all Contract-level outputs.
config["settings"]["outputSelection"]["*"]["*"][0] = "*";
runCompiler(jsonCompactPrint(config), _quiet);
}
void FuzzerUtil::forceSMT(StringMap& _input)
{
// Add SMT checker pragma if not already present in source
static auto constexpr smtPragma = "pragma experimental SMTChecker;";
for (auto &sourceUnit: _input)
if (sourceUnit.second.find(smtPragma) == std::string::npos)
sourceUnit.second += smtPragma;
}
void FuzzerUtil::testCompiler(
StringMap& _input,
bool _optimize,
unsigned _rand,
bool _forceSMT,
bool _compileViaYul
)
{
frontend::CompilerStack compiler;
EVMVersion evmVersion = s_evmVersions[_rand % s_evmVersions.size()];
frontend::OptimiserSettings optimiserSettings;
if (_optimize)
optimiserSettings = frontend::OptimiserSettings::standard();
else
optimiserSettings = frontend::OptimiserSettings::minimal();
if (_forceSMT)
{
forceSMT(_input);
compiler.setModelCheckerSettings({
/*bmcLoopIterations*/1,
frontend::ModelCheckerContracts::Default(),
/*divModWithSlacks*/true,
frontend::ModelCheckerEngine::All(),
frontend::ModelCheckerExtCalls{},
frontend::ModelCheckerInvariants::All(),
/*printQuery=*/false,
/*showProvedSafe=*/false,
/*showUnproved=*/false,
/*showUnsupported=*/false,
smtutil::SMTSolverChoice::All(),
frontend::ModelCheckerTargets::Default(),
/*timeout=*/1
});
}
compiler.setSources(_input);
compiler.setEVMVersion(evmVersion);
compiler.setOptimiserSettings(optimiserSettings);
compiler.setViaIR(_compileViaYul);
try
{
compiler.compile();
}
catch (UnimplementedFeatureError const&)
{
}
catch (StackTooDeepError const&)
{
if (_optimize && _compileViaYul)
throw;
}
}
void FuzzerUtil::runCompiler(std::string const& _input, bool _quiet)
{
if (!_quiet)
std::cout << "Input JSON: " << _input << std::endl;
std::string outputString(solidity_compile(_input.c_str(), nullptr, nullptr));
if (!_quiet)
std::cout << "Output JSON: " << outputString << std::endl;
// This should be safe given the above copies the output.
solidity_reset();
Json output;
if (!jsonParseStrict(outputString, output))
{
std::string msg{"Compiler produced invalid JSON output."};
std::cout << msg << std::endl;
BOOST_THROW_EXCEPTION(std::runtime_error(std::move(msg)));
}
if (output.contains("errors"))
for (auto const& error: output["errors"])
{
std::string invalid = findAnyOf(error["type"].get<std::string>(), std::vector<std::string>{
"Exception",
"InternalCompilerError"
});
if (!invalid.empty())
{
std::string msg = "Invalid error: \"" + error["type"].get<std::string>() + "\"";
std::cout << msg << std::endl;
BOOST_THROW_EXCEPTION(std::runtime_error(std::move(msg)));
}
}
}
void FuzzerUtil::testConstantOptimizer(std::string const& _input, bool _quiet)
{
if (!_quiet)
std::cout << "Testing constant optimizer" << std::endl;
std::vector<u256> numbers;
std::stringstream sin(_input);
while (!sin.eof())
{
h256 data;
sin.read(reinterpret_cast<char *>(data.data()), 32);
numbers.push_back(u256(data));
}
if (!_quiet)
std::cout << "Got " << numbers.size() << " inputs:" << std::endl;
for (bool isCreation: {false, true})
{
Assembly assembly{langutil::EVMVersion{}, isCreation, std::nullopt, {}};
for (u256 const& n: numbers)
{
if (!_quiet)
std::cout << n << std::endl;
assembly.append(n);
}
for (unsigned runs: {1u, 2u, 3u, 20u, 40u, 100u, 200u, 400u, 1000u})
{
// Make a copy here so that each time we start with the original state.
Assembly tmp = assembly;
ConstantOptimisationMethod::optimiseConstants(
isCreation,
runs,
langutil::EVMVersion{},
tmp
);
}
}
}
void FuzzerUtil::testStandardCompiler(std::string const& _input, bool _quiet)
{
if (!_quiet)
std::cout << "Testing compiler via JSON interface." << std::endl;
runCompiler(_input, _quiet);
}
| 6,032
|
C++
|
.cpp
| 182
| 30.582418
| 113
| 0.720124
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,907
|
yulrun.cpp
|
ethereum_solidity/test/tools/yulrun.cpp
|
/*
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
/**
* Yul interpreter.
*/
#include <test/tools/yulInterpreter/Interpreter.h>
#include <test/tools/yulInterpreter/Inspector.h>
#include <libyul/AsmAnalysisInfo.h>
#include <libyul/AsmAnalysis.h>
#include <libyul/Dialect.h>
#include <libyul/backends/evm/EVMDialect.h>
#include <libyul/YulStack.h>
#include <liblangutil/DebugInfoSelection.h>
#include <liblangutil/Exceptions.h>
#include <liblangutil/EVMVersion.h>
#include <liblangutil/SourceReferenceFormatter.h>
#include <libsolutil/CommonIO.h>
#include <libsolutil/CommonData.h>
#include <libsolutil/Exceptions.h>
#include <boost/program_options.hpp>
#include <string>
#include <memory>
#include <iostream>
using namespace solidity;
using namespace solidity::util;
using namespace solidity::langutil;
using namespace solidity::yul;
using namespace solidity::yul::test;
namespace po = boost::program_options;
namespace
{
std::pair<std::shared_ptr<AST const>, std::shared_ptr<AsmAnalysisInfo>> parse(std::string const& _source)
{
YulStack stack(
langutil::EVMVersion(),
std::nullopt,
YulStack::Language::StrictAssembly,
solidity::frontend::OptimiserSettings::none(),
DebugInfoSelection::Default()
);
if (stack.parseAndAnalyze("--INPUT--", _source))
{
yulAssert(!Error::hasErrorsWarningsOrInfos(stack.errors()), "Parsed successfully but had errors.");
return make_pair(stack.parserResult()->code(), stack.parserResult()->analysisInfo);
}
else
{
SourceReferenceFormatter(std::cout, stack, true, false).printErrorInformation(stack.errors());
return {};
}
}
void interpret(std::string const& _source, bool _inspect, bool _disableExternalCalls)
{
std::shared_ptr<AST const> ast;
std::shared_ptr<AsmAnalysisInfo> analysisInfo;
tie(ast, analysisInfo) = parse(_source);
if (!ast || !analysisInfo)
return;
InterpreterState state;
state.maxTraceSize = 10000;
try
{
Dialect const& dialect(EVMDialect::strictAssemblyForEVMObjects(langutil::EVMVersion{}, std::nullopt));
if (_inspect)
InspectedInterpreter::run(std::make_shared<Inspector>(_source, state), state, dialect, ast->root(), _disableExternalCalls, /*disableMemoryTracing=*/false);
else
Interpreter::run(state, dialect, ast->root(), _disableExternalCalls, /*disableMemoryTracing=*/false);
}
catch (InterpreterTerminatedGeneric const&)
{
}
state.dumpTraceAndState(std::cout, /*disableMemoryTracing=*/false);
}
}
int main(int argc, char** argv)
{
po::options_description options(
R"(yulrun, the Yul interpreter.
Usage: yulrun [Options] < input
Reads a single source from stdin, runs it and prints a trace of all side-effects.
Allowed options)",
po::options_description::m_default_line_length,
po::options_description::m_default_line_length - 23);
options.add_options()
("help", "Show this help screen.")
("enable-external-calls", "Enable external calls")
("interactive", "Run interactive")
("input-file", po::value<std::vector<std::string>>(), "input file");
po::positional_options_description filesPositions;
filesPositions.add("input-file", -1);
po::variables_map arguments;
try
{
po::command_line_parser cmdLineParser(argc, argv);
cmdLineParser.options(options).positional(filesPositions);
po::store(cmdLineParser.run(), arguments);
}
catch (po::error const& _exception)
{
std::cerr << _exception.what() << std::endl;
return 1;
}
if (arguments.count("help"))
std::cout << options;
else
{
std::string input;
if (arguments.count("input-file"))
for (std::string path: arguments["input-file"].as<std::vector<std::string>>())
{
try
{
input += readFileAsString(path);
}
catch (FileNotFound const&)
{
std::cerr << "File not found: " << path << std::endl;
return 1;
}
catch (NotAFile const&)
{
std::cerr << "Not a regular file: " << path << std::endl;
return 1;
}
}
else
input = readUntilEnd(std::cin);
interpret(input, arguments.count("interactive"), !arguments.count("enable-external-calls"));
}
return 0;
}
| 4,682
|
C++
|
.cpp
| 143
| 30.244755
| 158
| 0.745459
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,908
|
isoltest.cpp
|
ethereum_solidity/test/tools/isoltest.cpp
|
/*
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
#include <libsolutil/CommonIO.h>
#include <libsolutil/AnsiColorized.h>
#include <memory>
#include <test/Common.h>
#include <test/tools/IsolTestOptions.h>
#include <test/InteractiveTests.h>
#include <test/EVMHost.h>
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>
#include <cstdlib>
#include <iostream>
#include <queue>
#include <regex>
#include <utility>
#if defined(_WIN32)
#include <windows.h>
#endif
using namespace solidity;
using namespace solidity::util;
using namespace solidity::frontend;
using namespace solidity::frontend::test;
using namespace solidity::util::formatting;
namespace po = boost::program_options;
namespace fs = boost::filesystem;
using TestCreator = TestCase::TestCaseCreator;
using TestOptions = solidity::test::IsolTestOptions;
struct TestStats
{
int successCount = 0;
int testCount = 0;
int skippedCount = 0;
operator bool() const noexcept { return successCount + skippedCount == testCount; }
TestStats& operator+=(TestStats const& _other) noexcept
{
successCount += _other.successCount;
testCount += _other.testCount;
skippedCount += _other.skippedCount;
return *this;
}
};
class TestFilter
{
public:
explicit TestFilter(std::string _filter): m_filter(std::move(_filter))
{
std::string filter{m_filter};
boost::replace_all(filter, "/", "\\/");
boost::replace_all(filter, "*", ".*");
m_filterExpression = std::regex{"(" + filter + "(\\.sol|\\.yul|\\.stack))"};
}
bool matches(fs::path const& _path, std::string const& _name) const
{
return std::regex_match(_name, m_filterExpression) && solidity::test::isValidSemanticTestPath(_path);
}
private:
std::string m_filter;
std::regex m_filterExpression;
};
class TestTool
{
public:
TestTool(
TestCreator _testCaseCreator,
TestOptions const& _options,
fs::path _path,
std::string _name
):
m_testCaseCreator(_testCaseCreator),
m_options(_options),
m_filter(TestFilter{_options.testFilter}),
m_path(std::move(_path)),
m_name(std::move(_name))
{}
enum class Result
{
Success,
Failure,
Exception,
Skipped
};
Result process();
static TestStats processPath(
TestCreator _testCaseCreator,
TestOptions const& _options,
fs::path const& _basepath,
fs::path const& _path,
solidity::test::Batcher& _batcher
);
private:
enum class Request
{
Skip,
Rerun,
Quit
};
void updateTestCase();
Request handleResponse(bool _exception);
TestCreator m_testCaseCreator;
TestOptions const& m_options;
TestFilter m_filter;
fs::path const m_path;
std::string const m_name;
std::unique_ptr<TestCase> m_test;
static bool m_exitRequested;
};
bool TestTool::m_exitRequested = false;
TestTool::Result TestTool::process()
{
bool formatted{!m_options.noColor};
try
{
if (m_filter.matches(m_path, m_name))
{
(AnsiColorized(std::cout, formatted, {BOLD}) << m_name << ": ").flush();
m_test = m_testCaseCreator(TestCase::Config{
m_path.string(),
m_options.evmVersion(),
m_options.eofVersion(),
m_options.vmPaths,
m_options.enforceGasTest,
m_options.enforceGasTestMinValue
});
if (m_test->shouldRun())
{
std::stringstream outputMessages;
switch (TestCase::TestResult result = m_test->run(outputMessages, " ", formatted))
{
case TestCase::TestResult::Success:
AnsiColorized(std::cout, formatted, {BOLD, GREEN}) << "OK" << std::endl;
return Result::Success;
default:
AnsiColorized(std::cout, formatted, {BOLD, RED}) << "FAIL" << std::endl;
AnsiColorized(std::cout, formatted, {BOLD, CYAN}) << " Contract:" << std::endl;
m_test->printSource(std::cout, " ", formatted);
m_test->printSettings(std::cout, " ", formatted);
std::cout << std::endl << outputMessages.str() << std::endl;
return result == TestCase::TestResult::FatalError ? Result::Exception : Result::Failure;
}
}
else
{
AnsiColorized(std::cout, formatted, {BOLD, YELLOW}) << "NOT RUN" << std::endl;
return Result::Skipped;
}
}
else
return Result::Skipped;
}
catch (...)
{
AnsiColorized(std::cout, formatted, {BOLD, RED}) <<
"Unhandled exception during test: " << boost::current_exception_diagnostic_information() << std::endl;
return Result::Exception;
}
}
void TestTool::updateTestCase()
{
std::ofstream file(m_path.string(), std::ios::trunc);
m_test->printSource(file);
m_test->printUpdatedSettings(file);
file << "// ----" << std::endl;
m_test->printUpdatedExpectations(file, "// ");
}
TestTool::Request TestTool::handleResponse(bool _exception)
{
if (!_exception && m_options.acceptUpdates)
{
updateTestCase();
return Request::Rerun;
}
if (_exception)
std::cout << "(e)dit/(s)kip/(q)uit? ";
else
std::cout << "(e)dit/(u)pdate expectations/(s)kip/(q)uit? ";
std::cout.flush();
while (true)
{
switch(readStandardInputChar())
{
case 's':
std::cout << std::endl;
return Request::Skip;
case 'u':
if (_exception)
break;
else
{
std::cout << std::endl;
updateTestCase();
return Request::Rerun;
}
case 'e':
std::cout << std::endl << std::endl;
if (system((m_options.editor + " \"" + m_path.string() + "\"").c_str()))
std::cerr << "Error running editor command." << std::endl << std::endl;
return Request::Rerun;
case 'q':
std::cout << std::endl;
return Request::Quit;
default:
break;
}
}
}
TestStats TestTool::processPath(
TestCreator _testCaseCreator,
TestOptions const& _options,
fs::path const& _basepath,
fs::path const& _path,
solidity::test::Batcher& _batcher
)
{
std::queue<fs::path> paths;
paths.push(_path);
int successCount = 0;
int testCount = 0;
int skippedCount = 0;
while (!paths.empty())
{
auto currentPath = paths.front();
fs::path fullpath = _basepath / currentPath;
if (fs::is_directory(fullpath))
{
paths.pop();
for (auto const& entry: boost::iterator_range<fs::directory_iterator>(
fs::directory_iterator(fullpath),
fs::directory_iterator()
))
if (fs::is_directory(entry.path()) || TestCase::isTestFilename(entry.path().filename()))
paths.push(currentPath / entry.path().filename());
}
else if (m_exitRequested)
{
++testCount;
paths.pop();
}
else if (!_batcher.checkAndAdvance())
{
paths.pop();
++skippedCount;
}
else
{
++testCount;
TestTool testTool(
_testCaseCreator,
_options,
fullpath,
currentPath.generic_path().string()
);
auto result = testTool.process();
switch(result)
{
case Result::Failure:
case Result::Exception:
switch(testTool.handleResponse(result == Result::Exception))
{
case Request::Quit:
paths.pop();
m_exitRequested = true;
break;
case Request::Rerun:
std::cout << "Re-running test case..." << std::endl;
--testCount;
break;
case Request::Skip:
paths.pop();
++skippedCount;
break;
}
break;
case Result::Success:
paths.pop();
++successCount;
break;
case Result::Skipped:
paths.pop();
++skippedCount;
break;
}
}
}
return { successCount, testCount, skippedCount };
}
namespace
{
void setupTerminal()
{
#if defined(_WIN32) && defined(ENABLE_VIRTUAL_TERMINAL_PROCESSING)
// Set output mode to handle virtual terminal (ANSI escape sequences)
// ignore any error, as this is just a "nice-to-have"
// only windows needs to be taken care of, as other platforms (Linux/OSX) support them natively.
HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE);
if (hOut == INVALID_HANDLE_VALUE)
return;
DWORD dwMode = 0;
if (!GetConsoleMode(hOut, &dwMode))
return;
dwMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING;
if (!SetConsoleMode(hOut, dwMode))
return;
#endif
}
std::optional<TestStats> runTestSuite(
TestCreator _testCaseCreator,
TestOptions const& _options,
fs::path const& _basePath,
fs::path const& _subdirectory,
std::string const& _name,
solidity::test::Batcher& _batcher
)
{
fs::path testPath{_basePath / _subdirectory};
bool formatted{!_options.noColor};
if (!fs::exists(testPath) || !fs::is_directory(testPath))
{
std::cerr << _name << " tests not found. Use the --testpath argument." << std::endl;
return std::nullopt;
}
TestStats stats = TestTool::processPath(
_testCaseCreator,
_options,
_basePath,
_subdirectory,
_batcher
);
if (stats.skippedCount != stats.testCount)
{
std::cout << std::endl << _name << " Test Summary: ";
AnsiColorized(std::cout, formatted, {BOLD, stats ? GREEN : RED}) <<
stats.successCount <<
"/" <<
stats.testCount;
std::cout << " tests successful";
if (stats.skippedCount > 0)
{
std::cout << " (";
AnsiColorized(std::cout, formatted, {BOLD, YELLOW}) << stats.skippedCount;
std::cout<< " tests skipped)";
}
std::cout << "." << std::endl << std::endl;
}
return stats;
}
}
int main(int argc, char const *argv[])
{
using namespace solidity::test;
try
{
setupTerminal();
{
auto options = std::make_unique<IsolTestOptions>();
bool shouldContinue = options->parse(argc, argv);
if (!shouldContinue)
return EXIT_SUCCESS;
options->validate();
CommonOptions::setSingleton(std::move(options));
}
auto& options = dynamic_cast<IsolTestOptions const&>(CommonOptions::get());
if (!solidity::test::loadVMs(options))
return EXIT_FAILURE;
if (options.disableSemanticTests)
std::cout << std::endl << "--- SKIPPING ALL SEMANTICS TESTS ---" << std::endl << std::endl;
TestStats global_stats{0, 0};
std::cout << "Running tests..." << std::endl << std::endl;
Batcher batcher(CommonOptions::get().selectedBatch, CommonOptions::get().batches);
if (CommonOptions::get().batches > 1)
std::cout << "Batch " << CommonOptions::get().selectedBatch << " out of " << CommonOptions::get().batches << std::endl;
// Actually run the tests.
// Interactive tests are added in InteractiveTests.h
for (auto const& ts: g_interactiveTestsuites)
{
if (ts.needsVM && options.disableSemanticTests)
continue;
if (ts.smt && options.disableSMT)
continue;
auto stats = runTestSuite(
ts.testCaseCreator,
options,
options.testPath / ts.path,
ts.subpath,
ts.title,
batcher
);
if (stats)
global_stats += *stats;
else
return EXIT_FAILURE;
}
std::cout << std::endl << "Summary: ";
AnsiColorized(std::cout, !options.noColor, {BOLD, global_stats ? GREEN : RED}) <<
global_stats.successCount << "/" << global_stats.testCount;
std::cout << " tests successful";
if (global_stats.skippedCount > 0)
{
std::cout << " (";
AnsiColorized(std::cout, !options.noColor, {BOLD, YELLOW}) << global_stats.skippedCount;
std::cout << " tests skipped)";
}
std::cout << "." << std::endl;
if (options.disableSemanticTests)
std::cout << "\nNOTE: Skipped semantics tests.\n" << std::endl;
return global_stats ? EXIT_SUCCESS : EXIT_FAILURE;
}
catch (boost::program_options::error const& exception)
{
std::cerr << exception.what() << std::endl;
return 2;
}
catch (std::runtime_error const& exception)
{
std::cerr << exception.what() << std::endl;
return 2;
}
catch (solidity::test::ConfigException const& exception)
{
std::cerr << exception.what() << std::endl;
return 2;
}
catch (...)
{
std::cerr << "Unhandled exception caught." << std::endl;
std::cerr << boost::current_exception_diagnostic_information() << std::endl;
return 2;
}
}
| 12,112
|
C++
|
.cpp
| 441
| 24.394558
| 122
| 0.688755
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,910
|
yulopti.cpp
|
ethereum_solidity/test/tools/yulopti.cpp
|
/*
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
/**
* Interactive yul optimizer
*/
#include <libsolutil/CommonIO.h>
#include <libsolutil/Exceptions.h>
#include <libsolutil/StringUtils.h>
#include <liblangutil/ErrorReporter.h>
#include <libyul/AsmAnalysis.h>
#include <libyul/AsmAnalysisInfo.h>
#include <libsolidity/parsing/Parser.h>
#include <libyul/AST.h>
#include <libyul/AsmParser.h>
#include <libyul/AsmPrinter.h>
#include <libyul/Object.h>
#include <liblangutil/SourceReferenceFormatter.h>
#include <libyul/optimiser/Disambiguator.h>
#include <libyul/optimiser/OptimiserStep.h>
#include <libyul/optimiser/StackCompressor.h>
#include <libyul/optimiser/VarNameCleaner.h>
#include <libyul/optimiser/Suite.h>
#include <libyul/backends/evm/EVMDialect.h>
#include <libsolutil/JSON.h>
#include <libsolidity/interface/OptimiserSettings.h>
#include <liblangutil/CharStreamProvider.h>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/join.hpp>
#include <boost/program_options.hpp>
#include <range/v3/action/sort.hpp>
#include <range/v3/range/conversion.hpp>
#include <range/v3/view/concat.hpp>
#include <range/v3/view/drop.hpp>
#include <range/v3/view/map.hpp>
#include <range/v3/view/set_algorithm.hpp>
#include <range/v3/view/stride.hpp>
#include <range/v3/view/transform.hpp>
#include <string>
#include <iostream>
#include <variant>
using namespace solidity;
using namespace solidity::util;
using namespace solidity::langutil;
using namespace solidity::frontend;
using namespace solidity::yul;
namespace po = boost::program_options;
class YulOpti
{
public:
static void printErrors(CharStream const& _charStream, ErrorList const& _errors)
{
SourceReferenceFormatter{
std::cerr,
SingletonCharStreamProvider(_charStream),
true,
false
}.printErrorInformation(_errors);
}
void parse(std::string const& _input)
{
ErrorList errors;
ErrorReporter errorReporter(errors);
CharStream _charStream(_input, "");
try
{
auto ast = yul::Parser(errorReporter, m_dialect).parse(_charStream);
if (!ast || errorReporter.hasErrors())
{
std::cerr << "Error parsing source." << std::endl;
printErrors(_charStream, errors);
throw std::runtime_error("Could not parse source.");
}
m_astRoot = std::make_shared<yul::Block>(std::get<yul::Block>(ASTCopier{}(ast->root())));
m_analysisInfo = std::make_unique<yul::AsmAnalysisInfo>();
AsmAnalyzer analyzer(
*m_analysisInfo,
errorReporter,
m_dialect
);
if (!analyzer.analyze(*m_astRoot) || errorReporter.hasErrors())
{
std::cerr << "Error analyzing source." << std::endl;
printErrors(_charStream, errors);
throw std::runtime_error("Could not analyze source.");
}
}
catch(...)
{
std::cerr << "Fatal error during parsing: " << std::endl;
printErrors(_charStream, errors);
throw;
}
}
void printUsageBanner(
std::map<char, std::string> const& _extraOptions,
size_t _columns
)
{
yulAssert(_columns > 0);
auto const& optimiserSteps = OptimiserSuite::stepAbbreviationToNameMap();
auto hasShorterString = [](auto const& a, auto const& b) { return a.second.size() < b.second.size(); };
size_t longestDescriptionLength = std::max(
max_element(optimiserSteps.begin(), optimiserSteps.end(), hasShorterString)->second.size(),
max_element(_extraOptions.begin(), _extraOptions.end(), hasShorterString)->second.size()
);
std::vector<std::string> overlappingAbbreviations =
ranges::views::set_intersection(_extraOptions | ranges::views::keys, optimiserSteps | ranges::views::keys) |
ranges::views::transform([](char _abbreviation){ return std::string(1, _abbreviation); }) |
ranges::to<std::vector>();
yulAssert(
overlappingAbbreviations.empty(),
"ERROR: Conflict between yulopti controls and the following Yul optimizer step abbreviations: " +
boost::join(overlappingAbbreviations, ", ") + ".\n"
"This is most likely caused by someone adding a new step abbreviation to "
"OptimiserSuite::stepNameToAbbreviationMap() and not realizing that it's used by yulopti.\n"
"Please update the code to use a different character and recompile yulopti."
);
std::vector<std::tuple<char, std::string>> sortedOptions =
ranges::views::concat(optimiserSteps, _extraOptions) |
ranges::to<std::vector<std::tuple<char, std::string>>>() |
ranges::actions::sort([](std::tuple<char, std::string> const& _a, std::tuple<char, std::string> const& _b) {
return (
!boost::algorithm::iequals(get<1>(_a), get<1>(_b)) ?
boost::algorithm::lexicographical_compare(get<1>(_a), get<1>(_b), boost::algorithm::is_iless()) :
toLower(get<0>(_a)) < toLower(get<0>(_b))
);
});
yulAssert(sortedOptions.size() > 0);
size_t rows = (sortedOptions.size() - 1) / _columns + 1;
for (size_t row = 0; row < rows; ++row)
{
for (auto const& [key, name]: sortedOptions | ranges::views::drop(row) | ranges::views::stride(rows))
std::cout << key << ": " << std::setw(static_cast<int>(longestDescriptionLength)) << std::setiosflags(std::ios::left) << name << " ";
std::cout << std::endl;
}
}
void disambiguate()
{
*m_astRoot = std::get<yul::Block>(Disambiguator(m_dialect, *m_analysisInfo)(*m_astRoot));
m_analysisInfo.reset();
m_nameDispenser.reset(*m_astRoot);
}
void runSteps(std::string _source, std::string _steps)
{
parse(_source);
disambiguate();
OptimiserSuite{m_context}.runSequence(_steps, *m_astRoot);
std::cout << AsmPrinter{m_dialect}(*m_astRoot) << std::endl;
}
void runInteractive(std::string _source, bool _disambiguated = false)
{
bool disambiguated = _disambiguated;
while (true)
{
parse(_source);
disambiguated = disambiguated || (disambiguate(), true);
std::map<char, std::string> const& extraOptions = {
// QUIT starts with a non-letter character on purpose to get it to show up on top of the list
{'#', ">>> QUIT <<<"},
{',', "VarNameCleaner"},
{';', "StackCompressor"}
};
printUsageBanner(extraOptions, 4);
std::cout << "? ";
std::cout.flush();
char option = static_cast<char>(readStandardInputChar());
std::cout << ' ' << option << std::endl;
try
{
switch (option)
{
case 4:
case '#':
return;
case ',':
VarNameCleaner::run(m_context, *m_astRoot);
// VarNameCleaner destroys the unique names guarantee of the disambiguator.
disambiguated = false;
break;
case ';':
{
Object obj{m_dialect};
obj.setCode(std::make_shared<AST>(std::get<yul::Block>(ASTCopier{}(*m_astRoot))));
*m_astRoot = std::get<1>(StackCompressor::run(m_dialect, obj, true, 16));
break;
}
default:
OptimiserSuite{m_context}.runSequence(
std::string_view(&option, 1),
*m_astRoot
);
}
_source = AsmPrinter{m_dialect}(*m_astRoot);
}
catch (...)
{
std::cerr << std::endl << "Exception during optimiser step:" << std::endl;
std::cerr << boost::current_exception_diagnostic_information() << std::endl;
}
std::cout << "----------------------" << std::endl;
std::cout << _source << std::endl;
}
}
private:
std::shared_ptr<yul::Block> m_astRoot;
Dialect const& m_dialect{EVMDialect::strictAssemblyForEVMObjects(EVMVersion{}, std::nullopt)};
std::unique_ptr<AsmAnalysisInfo> m_analysisInfo;
std::set<YulName> const m_reservedIdentifiers = {};
NameDispenser m_nameDispenser{m_dialect, m_reservedIdentifiers};
OptimiserStepContext m_context{
m_dialect,
m_nameDispenser,
m_reservedIdentifiers,
solidity::frontend::OptimiserSettings::standard().expectedExecutionsPerDeployment
};
};
int main(int argc, char** argv)
{
try
{
bool nonInteractive = false;
po::options_description options(
R"(yulopti, yul optimizer exploration tool.
Usage: yulopti [Options] <file>
Reads <file> as yul code and applies optimizer steps to it,
interactively read from stdin.
In non-interactive mode a list of steps has to be provided.
If <file> is -, yul code is read from stdin and run non-interactively.
Allowed options)",
po::options_description::m_default_line_length,
po::options_description::m_default_line_length - 23);
options.add_options()
(
"input-file",
po::value<std::string>(),
"input file"
)
(
"steps",
po::value<std::string>(),
"steps to execute non-interactively"
)
(
"non-interactive,n",
po::bool_switch(&nonInteractive)->default_value(false),
"stop after executing the provided steps"
)
("help,h", "Show this help screen.");
// All positional options should be interpreted as input files
po::positional_options_description filesPositions;
filesPositions.add("input-file", 1);
po::variables_map arguments;
po::command_line_parser cmdLineParser(argc, argv);
cmdLineParser.options(options).positional(filesPositions);
po::store(cmdLineParser.run(), arguments);
po::notify(arguments);
if (arguments.count("help"))
{
std::cout << options;
return 0;
}
std::string input;
if (arguments.count("input-file"))
{
std::string filename = arguments["input-file"].as<std::string>();
if (filename == "-")
{
nonInteractive = true;
input = readUntilEnd(std::cin);
}
else
input = readFileAsString(arguments["input-file"].as<std::string>());
}
else
{
std::cout << options;
return 1;
}
if (nonInteractive && !arguments.count("steps"))
{
std::cout << options;
return 1;
}
YulOpti yulOpti;
bool disambiguated = false;
if (!nonInteractive)
std::cout << input << std::endl;
if (arguments.count("steps"))
{
std::string sequence = arguments["steps"].as<std::string>();
if (!nonInteractive)
std::cout << "----------------------" << std::endl;
yulOpti.runSteps(input, sequence);
disambiguated = true;
}
if (!nonInteractive)
yulOpti.runInteractive(input, disambiguated);
return 0;
}
catch (po::error const& _exception)
{
std::cerr << _exception.what() << std::endl;
return 1;
}
catch (FileNotFound const& _exception)
{
std::cerr << "File not found:" << _exception.comment() << std::endl;
return 1;
}
catch (NotAFile const& _exception)
{
std::cerr << "Not a regular file:" << _exception.comment() << std::endl;
return 1;
}
catch(...)
{
std::cerr << std::endl << "Exception:" << std::endl;
std::cerr << boost::current_exception_diagnostic_information() << std::endl;
return 1;
}
}
| 11,086
|
C++
|
.cpp
| 333
| 29.981982
| 137
| 0.697677
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,912
|
yulProto_diff_ossfuzz.cpp
|
ethereum_solidity/test/tools/ossfuzz/yulProto_diff_ossfuzz.cpp
|
/*
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
#include <fstream>
#include <test/tools/ossfuzz/yulProto.pb.h>
#include <test/tools/fuzzer_common.h>
#include <test/tools/ossfuzz/protoToYul.h>
#include <test/libyul/YulOptimizerTestCommon.h>
#include <src/libfuzzer/libfuzzer_macro.h>
#include <libyul/AST.h>
#include <libyul/YulStack.h>
#include <libyul/backends/evm/EVMDialect.h>
#include <libyul/Exceptions.h>
#include <liblangutil/DebugInfoSelection.h>
#include <liblangutil/EVMVersion.h>
#include <liblangutil/SourceReferenceFormatter.h>
#include <test/tools/ossfuzz/yulFuzzerCommon.h>
using namespace solidity;
using namespace solidity::util;
using namespace solidity::langutil;
using namespace solidity::yul;
using namespace solidity::yul::test;
using namespace solidity::yul::test::yul_fuzzer;
DEFINE_PROTO_FUZZER(Program const& _input)
{
ProtoConverter converter;
std::string yul_source = converter.programToString(_input);
EVMVersion version = converter.version();
if (const char* dump_path = getenv("PROTO_FUZZER_DUMP_PATH"))
{
// With libFuzzer binary run this to generate a YUL source file x.yul:
// PROTO_FUZZER_DUMP_PATH=x.yul ./a.out proto-input
std::ofstream of(dump_path);
of.write(yul_source.data(), static_cast<std::streamsize>(yul_source.size()));
}
YulStringRepository::reset();
// YulStack entry point
YulStack stack(
version,
std::nullopt,
YulStack::Language::StrictAssembly,
solidity::frontend::OptimiserSettings::full(),
DebugInfoSelection::All()
);
// Parse protobuf mutated YUL code
if (
!stack.parseAndAnalyze("source", yul_source) ||
!stack.parserResult()->code() ||
!stack.parserResult()->analysisInfo ||
Error::containsErrors(stack.errors())
)
{
SourceReferenceFormatter{std::cout, stack, false, false}.printErrorInformation(stack.errors());
yulAssert(false, "Proto fuzzer generated malformed program");
}
std::ostringstream os1;
std::ostringstream os2;
// Disable memory tracing to avoid false positive reports
// such as unused write to memory e.g.,
// { mstore(0, 1) }
// that would be removed by the redundant store eliminator.
// TODO: Add EOF support
yulFuzzerUtil::TerminationReason termReason = yulFuzzerUtil::interpret(
os1,
stack.parserResult()->code()->root(),
EVMDialect::strictAssemblyForEVMObjects(version, std::nullopt),
/*disableMemoryTracing=*/true
);
if (yulFuzzerUtil::resourceLimitsExceeded(termReason))
return;
// TODO: Add EOF support
YulOptimizerTestCommon optimizerTest(
stack.parserResult(),
EVMDialect::strictAssemblyForEVMObjects(version, std::nullopt)
);
optimizerTest.setStep(optimizerTest.randomOptimiserStep(_input.step()));
auto const* astRoot = optimizerTest.run();
yulAssert(astRoot != nullptr, "Optimiser error.");
// TODO: Add EOF support
termReason = yulFuzzerUtil::interpret(
os2,
*astRoot,
EVMDialect::strictAssemblyForEVMObjects(version, std::nullopt),
true
);
if (yulFuzzerUtil::resourceLimitsExceeded(termReason))
return;
bool isTraceEq = (os1.str() == os2.str());
if (!isTraceEq)
{
std::cout << os1.str() << std::endl;
std::cout << os2.str() << std::endl;
yulAssert(false, "Interpreted traces for optimized and unoptimized code differ.");
}
return;
}
| 3,878
|
C++
|
.cpp
| 107
| 34.018692
| 97
| 0.769395
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,915
|
yulFuzzerCommon.cpp
|
ethereum_solidity/test/tools/ossfuzz/yulFuzzerCommon.cpp
|
/*
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
#include <test/tools/ossfuzz/yulFuzzerCommon.h>
using namespace solidity;
using namespace solidity::yul;
using namespace solidity::yul::test::yul_fuzzer;
yulFuzzerUtil::TerminationReason yulFuzzerUtil::interpret(
std::ostream& _os,
yul::Block const& _astRoot,
Dialect const& _dialect,
bool _disableMemoryTracing,
bool _outputStorageOnly,
size_t _maxSteps,
size_t _maxTraceSize,
size_t _maxExprNesting
)
{
InterpreterState state;
state.maxTraceSize = _maxTraceSize;
state.maxSteps = _maxSteps;
state.maxExprNesting = _maxExprNesting;
// Add 64 bytes of pseudo-randomly generated calldata so that
// calldata opcodes perform non trivial work.
state.calldata = {
0xe9, 0x96, 0x40, 0x7d, 0xa5, 0xda, 0xb0, 0x2d,
0x97, 0xf5, 0xc3, 0x44, 0xd7, 0x65, 0x0a, 0xd8,
0x2c, 0x14, 0x3a, 0xf3, 0xe7, 0x40, 0x0f, 0x1e,
0x67, 0xce, 0x90, 0x44, 0x2e, 0x92, 0xdb, 0x88,
0xb8, 0x43, 0x9c, 0x41, 0x42, 0x08, 0xf1, 0xd7,
0x65, 0xe9, 0x7f, 0xeb, 0x7b, 0xb9, 0x56, 0x9f,
0xc7, 0x60, 0x5f, 0x7c, 0xcd, 0xfb, 0x92, 0xcd,
0x8e, 0xf3, 0x9b, 0xe4, 0x4f, 0x6c, 0x14, 0xde
};
TerminationReason reason = TerminationReason::None;
try
{
Interpreter::run(state, _dialect, _astRoot, true, _disableMemoryTracing);
}
catch (StepLimitReached const&)
{
reason = TerminationReason::StepLimitReached;
}
catch (TraceLimitReached const&)
{
reason = TerminationReason::TraceLimitReached;
}
catch (ExpressionNestingLimitReached const&)
{
reason = TerminationReason::ExpresionNestingLimitReached;
}
catch (ExplicitlyTerminated const&)
{
reason = TerminationReason::ExplicitlyTerminated;
}
if (_outputStorageOnly)
state.dumpStorage(_os);
else
state.dumpTraceAndState(_os, _disableMemoryTracing);
return reason;
}
bool yulFuzzerUtil::resourceLimitsExceeded(TerminationReason _reason)
{
return
_reason == yulFuzzerUtil::TerminationReason::StepLimitReached ||
_reason == yulFuzzerUtil::TerminationReason::TraceLimitReached ||
_reason == yulFuzzerUtil::TerminationReason::ExpresionNestingLimitReached;
}
| 2,715
|
C++
|
.cpp
| 79
| 32.21519
| 76
| 0.775875
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,917
|
solc_ossfuzz.cpp
|
ethereum_solidity/test/tools/ossfuzz/solc_ossfuzz.cpp
|
/*
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
#include <test/tools/fuzzer_common.h>
#include <test/TestCaseReader.h>
#include <sstream>
using namespace solidity::frontend::test;
// Prototype as we can't use the FuzzerInterface.h header.
extern "C" int LLVMFuzzerTestOneInput(uint8_t const* _data, size_t _size);
extern "C" int LLVMFuzzerTestOneInput(uint8_t const* _data, size_t _size)
{
if (_size <= 600)
{
std::string input(reinterpret_cast<char const*>(_data), _size);
std::map<std::string, std::string> sourceCode;
try
{
TestCaseReader t = TestCaseReader(std::istringstream(input));
sourceCode = t.sources().sources;
std::map<std::string, std::string> settings = t.settings();
bool compileViaYul =
settings.count("compileViaYul") &&
(settings.at("compileViaYul") == "also" || settings.at("compileViaYul") == "true");
bool optimize = settings.count("optimize") && settings.at("optimize") == "true";
FuzzerUtil::testCompiler(
sourceCode,
optimize,
/*_rand=*/static_cast<unsigned>(_size),
/*forceSMT=*/true,
compileViaYul
);
}
catch (std::runtime_error const&)
{
return 0;
}
}
return 0;
}
| 1,807
|
C++
|
.cpp
| 50
| 33.3
| 87
| 0.730549
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,918
|
YulEvmoneInterface.cpp
|
ethereum_solidity/test/tools/ossfuzz/YulEvmoneInterface.cpp
|
/*
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/>.
*/
#include <test/tools/ossfuzz/YulEvmoneInterface.h>
#include <libyul/Exceptions.h>
using namespace solidity;
using namespace solidity::test::fuzzer;
using namespace solidity::yul;
bytes YulAssembler::assemble()
{
if (
!m_stack.parseAndAnalyze("source", m_yulProgram) ||
!m_stack.parserResult()->code() ||
!m_stack.parserResult()->analysisInfo ||
langutil::Error::containsErrors(m_stack.errors())
)
yulAssert(false, "Yul program could not be parsed successfully.");
if (m_optimiseYul)
m_stack.optimize();
return m_stack.assemble(YulStack::Machine::EVM).bytecode->bytecode;
}
std::shared_ptr<yul::Object> YulAssembler::object()
{
return m_stack.parserResult();
}
evmc::Result YulEvmoneUtility::deployCode(bytes const& _input, EVMHost& _host)
{
// Zero initialize all message fields
evmc_message msg = {};
// Gas available (value of type int64_t) is set to its maximum value
msg.gas = std::numeric_limits<int64_t>::max();
solAssert(
_input.size() <= 0xffff,
"Deployed byte code is larger than the permissible 65535 bytes."
);
uint8_t inputSizeHigher = static_cast<uint8_t>(_input.size() >> 8);
uint8_t inputSizeLower = _input.size() & 0xff;
/*
* CODESIZE
* PUSH0 0xc
* PUSH0 0x0
* CODECOPY
* PUSH1 <INPUTSIZE>
* PUSH0 0x0
* RETURN
*/
bytes deployCode = bytes{
0x38, 0x60, 0x0c, 0x60, 0x00, 0x39, 0x61,
inputSizeHigher, inputSizeLower,
0x60, 0x00, 0xf3
} + _input;
msg.input_data = deployCode.data();
msg.input_size = deployCode.size();
msg.kind = EVMC_CREATE;
return _host.call(msg);
}
evmc_message YulEvmoneUtility::callMessage(evmc_address _address)
{
evmc_message call = {};
call.gas = std::numeric_limits<int64_t>::max();
call.recipient = _address;
call.code_address = _address;
call.kind = EVMC_CALL;
return call;
}
bool YulEvmoneUtility::seriousCallError(evmc_status_code _code)
{
if (_code == EVMC_OUT_OF_GAS)
return true;
else if (_code == EVMC_STACK_OVERFLOW)
return true;
else if (_code == EVMC_STACK_UNDERFLOW)
return true;
else if (_code == EVMC_INTERNAL_ERROR)
return true;
else if (_code == EVMC_UNDEFINED_INSTRUCTION)
return true;
else if (_code == EVMC_INVALID_MEMORY_ACCESS)
return true;
else
return false;
}
| 2,898
|
C++
|
.cpp
| 92
| 28.967391
| 78
| 0.733715
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,919
|
solProtoFuzzer.cpp
|
ethereum_solidity/test/tools/ossfuzz/solProtoFuzzer.cpp
|
/*
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
#include <test/tools/ossfuzz/protoToSol.h>
#include <test/tools/ossfuzz/SolidityEvmoneInterface.h>
#include <test/tools/ossfuzz/solProto.pb.h>
#include <test/EVMHost.h>
#include <evmone/evmone.h>
#include <src/libfuzzer/libfuzzer_macro.h>
#include <fstream>
static evmc::VM evmone = evmc::VM{evmc_create_evmone()};
using namespace solidity::test::fuzzer;
using namespace solidity::test::solprotofuzzer;
using namespace solidity;
using namespace solidity::frontend;
using namespace solidity::test;
using namespace solidity::util;
DEFINE_PROTO_FUZZER(Program const& _input)
{
ProtoConverter converter;
std::string sol_source = converter.protoToSolidity(_input);
if (char const* dump_path = getenv("PROTO_FUZZER_DUMP_PATH"))
{
// With libFuzzer binary run this to generate a YUL source file x.yul:
// PROTO_FUZZER_DUMP_PATH=x.yul ./a.out proto-input
std::ofstream of(dump_path);
of.write(sol_source.data(), static_cast<std::streamsize>(sol_source.size()));
}
if (char const* dump_path = getenv("SOL_DEBUG_FILE"))
{
sol_source.clear();
// With libFuzzer binary run this to generate a YUL source file x.yul:
// PROTO_FUZZER_LOAD_PATH=x.yul ./a.out proto-input
std::ifstream ifstr(dump_path);
sol_source = {
std::istreambuf_iterator<char>(ifstr),
std::istreambuf_iterator<char>()
};
std::cout << sol_source << std::endl;
}
// We target the default EVM which is the latest
langutil::EVMVersion version;
EVMHost hostContext(version, evmone);
std::string contractName = "C";
std::string libraryName = converter.libraryTest() ? converter.libraryName() : "";
std::string methodName = "test()";
StringMap source({{"test.sol", sol_source}});
CompilerInput cInput(version, source, contractName, OptimiserSettings::minimal(), {});
EvmoneUtility evmoneUtil(
hostContext,
cInput,
contractName,
libraryName,
methodName
);
auto minimalResult = evmoneUtil.compileDeployAndExecute();
solAssert(minimalResult.status_code != EVMC_REVERT, "Sol proto fuzzer: Evmone reverted.");
if (minimalResult.status_code == EVMC_SUCCESS)
solAssert(
EvmoneUtility::zeroWord(minimalResult.output_data, minimalResult.output_size),
"Proto solc fuzzer: Output incorrect"
);
}
| 2,898
|
C++
|
.cpp
| 74
| 36.905405
| 91
| 0.763429
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,920
|
SolidityEvmoneInterface.cpp
|
ethereum_solidity/test/tools/ossfuzz/SolidityEvmoneInterface.cpp
|
/*
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
#include <test/tools/ossfuzz/SolidityEvmoneInterface.h>
#include <liblangutil/Exceptions.h>
#include <liblangutil/SourceReferenceFormatter.h>
#include <range/v3/algorithm/all_of.hpp>
#include <range/v3/span.hpp>
using namespace solidity::test::fuzzer;
using namespace solidity::frontend;
using namespace solidity::langutil;
using namespace solidity::util;
std::optional<CompilerOutput> SolidityCompilationFramework::compileContract()
{
m_compiler.setSources(m_compilerInput.sourceCode);
m_compiler.setLibraries(m_compilerInput.libraryAddresses);
m_compiler.setEVMVersion(m_compilerInput.evmVersion);
m_compiler.setOptimiserSettings(m_compilerInput.optimiserSettings);
m_compiler.setViaIR(m_compilerInput.viaIR);
if (!m_compiler.compile())
{
if (m_compilerInput.debugFailure)
{
std::cerr << "Compiling contract failed" << std::endl;
std::cerr << SourceReferenceFormatter::formatErrorInformation(
m_compiler.errors(),
m_compiler
);
}
return {};
}
else
{
std::string contractName;
if (m_compilerInput.contractName.empty())
contractName = m_compiler.lastContractName();
else
contractName = m_compilerInput.contractName;
evmasm::LinkerObject obj = m_compiler.object(contractName);
Json methodIdentifiers = m_compiler.interfaceSymbols(contractName)["methods"];
return CompilerOutput{obj.bytecode, methodIdentifiers};
}
}
bool EvmoneUtility::zeroWord(uint8_t const* _result, size_t _length)
{
return _length == 32 &&
ranges::all_of(
ranges::span(_result, static_cast<long>(_length)),
[](uint8_t _v) { return _v == 0; });
}
evmc_message EvmoneUtility::initializeMessage(bytes const& _input)
{
// Zero initialize all message fields
evmc_message msg = {};
// Gas available (value of type int64_t) is set to its maximum
// value.
msg.gas = std::numeric_limits<int64_t>::max();
msg.input_data = _input.data();
msg.input_size = _input.size();
return msg;
}
evmc::Result EvmoneUtility::executeContract(
bytes const& _functionHash,
evmc_address _deployedAddress
)
{
evmc_message message = initializeMessage(_functionHash);
message.recipient = _deployedAddress;
message.code_address = _deployedAddress;
message.kind = EVMC_CALL;
return m_evmHost.call(message);
}
evmc::Result EvmoneUtility::deployContract(bytes const& _code)
{
evmc_message message = initializeMessage(_code);
message.kind = EVMC_CREATE;
return m_evmHost.call(message);
}
evmc::Result EvmoneUtility::deployAndExecute(
bytes const& _byteCode,
std::string const& _hexEncodedInput
)
{
// Deploy contract and signal failure if deploy failed
evmc::Result createResult = deployContract(_byteCode);
solAssert(
createResult.status_code == EVMC_SUCCESS,
"SolidityEvmoneInterface: Contract creation failed"
);
// Execute test function and signal failure if EVM reverted or
// did not return expected output on successful execution.
evmc::Result callResult = executeContract(
util::fromHex(_hexEncodedInput),
createResult.create_address
);
// We don't care about EVM One failures other than EVMC_REVERT
solAssert(
callResult.status_code != EVMC_REVERT,
"SolidityEvmoneInterface: EVM One reverted"
);
return callResult;
}
evmc::Result EvmoneUtility::compileDeployAndExecute(std::string _fuzzIsabelle)
{
std::map<std::string, h160> libraryAddressMap;
// Stage 1: Compile and deploy library if present.
if (!m_libraryName.empty())
{
m_compilationFramework.contractName(m_libraryName);
auto compilationOutput = m_compilationFramework.compileContract();
solAssert(compilationOutput.has_value(), "Compiling library failed");
CompilerOutput cOutput = compilationOutput.value();
// Deploy contract and signal failure if deploy failed
evmc::Result createResult = deployContract(cOutput.byteCode);
solAssert(
createResult.status_code == EVMC_SUCCESS,
"SolidityEvmoneInterface: Library deployment failed"
);
libraryAddressMap[m_libraryName] = EVMHost::convertFromEVMC(createResult.create_address);
m_compilationFramework.libraryAddresses(libraryAddressMap);
}
// Stage 2: Compile, deploy, and execute contract, optionally using library
// address map.
m_compilationFramework.contractName(m_contractName);
auto cOutput = m_compilationFramework.compileContract();
solAssert(cOutput.has_value(), "Compiling contract failed");
solAssert(
!cOutput->byteCode.empty() && !cOutput->methodIdentifiersInContract.empty(),
"SolidityEvmoneInterface: Invalid compilation output."
);
std::string methodName;
if (!_fuzzIsabelle.empty())
// TODO: Remove this once a cleaner solution is found for querying
// isabelle test entry point. At the moment, we are sure that the
// entry point is the second method in the contract (hence the ++)
// but not its name.
methodName = (++cOutput->methodIdentifiersInContract.begin())->get<std::string>() +
_fuzzIsabelle.substr(2, _fuzzIsabelle.size());
else
methodName = cOutput->methodIdentifiersInContract[m_methodName].get<std::string>();
return deployAndExecute(
cOutput->byteCode,
methodName
);
}
std::optional<CompilerOutput> EvmoneUtility::compileContract()
{
try
{
return m_compilationFramework.compileContract();
}
catch (evmasm::StackTooDeepException const&)
{
return {};
}
}
| 5,920
|
C++
|
.cpp
| 167
| 33.167665
| 91
| 0.777952
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,921
|
yulProtoFuzzer.cpp
|
ethereum_solidity/test/tools/ossfuzz/yulProtoFuzzer.cpp
|
/*
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
#include <fstream>
#include <test/tools/ossfuzz/yulProto.pb.h>
#include <test/tools/ossfuzz/protoToYul.h>
#include <test/tools/fuzzer_common.h>
#include <test/libyul/YulOptimizerTestCommon.h>
#include <libyul/YulStack.h>
#include <libyul/Exceptions.h>
#include <libyul/backends/evm/EVMDialect.h>
#include <liblangutil/DebugInfoSelection.h>
#include <liblangutil/EVMVersion.h>
#include <src/libfuzzer/libfuzzer_macro.h>
using namespace solidity;
using namespace solidity::langutil;
using namespace solidity::yul;
using namespace solidity::yul::test;
using namespace solidity::yul::test::yul_fuzzer;
DEFINE_PROTO_FUZZER(Program const& _input)
{
ProtoConverter converter;
std::string yul_source = converter.programToString(_input);
EVMVersion version = converter.version();
if (const char* dump_path = getenv("PROTO_FUZZER_DUMP_PATH"))
{
// With libFuzzer binary run this to generate a YUL source file x.yul:
// PROTO_FUZZER_DUMP_PATH=x.yul ./a.out proto-input
std::ofstream of(dump_path);
of.write(yul_source.data(), static_cast<std::streamsize>(yul_source.size()));
}
if (yul_source.size() > 1200)
return;
YulStringRepository::reset();
// YulStack entry point
YulStack stack(
version,
std::nullopt,
YulStack::Language::StrictAssembly,
solidity::frontend::OptimiserSettings::full(),
DebugInfoSelection::All()
);
// Parse protobuf mutated YUL code
if (
!stack.parseAndAnalyze("source", yul_source) ||
!stack.parserResult()->code() ||
!stack.parserResult()->analysisInfo ||
Error::containsErrors(stack.errors())
)
yulAssert(false, "Proto fuzzer generated malformed program");
// TODO: Add EOF support
// Optimize
YulOptimizerTestCommon optimizerTest(
stack.parserResult(),
EVMDialect::strictAssemblyForEVMObjects(version, std::nullopt)
);
optimizerTest.setStep(optimizerTest.randomOptimiserStep(_input.step()));
auto const* astRoot = optimizerTest.run();
yulAssert(astRoot != nullptr, "Optimiser error.");
}
| 2,660
|
C++
|
.cpp
| 71
| 35.267606
| 79
| 0.775097
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,922
|
StackReuseCodegenFuzzer.cpp
|
ethereum_solidity/test/tools/ossfuzz/StackReuseCodegenFuzzer.cpp
|
/*
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/>.
*/
#include <test/tools/ossfuzz/yulProto.pb.h>
#include <test/tools/ossfuzz/protoToYul.h>
#include <test/EVMHost.h>
#include <test/tools/ossfuzz/YulEvmoneInterface.h>
#include <libyul/Exceptions.h>
#include <libyul/backends/evm/EVMCodeTransform.h>
#include <libyul/backends/evm/EVMDialect.h>
#include <libyul/optimiser/CallGraphGenerator.h>
#include <libyul/CompilabilityChecker.h>
#include <libevmasm/Instruction.h>
#include <liblangutil/EVMVersion.h>
#include <evmone/evmone.h>
#include <src/libfuzzer/libfuzzer_macro.h>
#include <fstream>
using namespace solidity;
using namespace solidity::test;
using namespace solidity::test::fuzzer;
using namespace solidity::yul;
using namespace solidity::yul::test::yul_fuzzer;
using namespace solidity::langutil;
static evmc::VM evmone = evmc::VM{evmc_create_evmone()};
namespace
{
/// @returns true if there are recursive functions, false otherwise.
bool recursiveFunctionExists(Dialect const& _dialect, yul::Object& _object)
{
auto recursiveFunctions = CallGraphGenerator::callGraph(_object.code()->root()).recursiveFunctions();
for(auto&& [function, variables]: CompilabilityChecker{
_dialect,
_object,
true
}.unreachableVariables
)
if(recursiveFunctions.count(function))
return true;
return false;
}
}
DEFINE_PROTO_FUZZER(Program const& _input)
{
// Solidity creates an invalid instruction for subobjects, so we simply
// ignore them in this fuzzer.
if (_input.has_obj())
return;
bool filterStatefulInstructions = true;
bool filterUnboundedLoops = true;
ProtoConverter converter(
filterStatefulInstructions,
filterUnboundedLoops
);
std::string yul_source = converter.programToString(_input);
// Do not fuzz the EVM Version field.
// See https://github.com/ethereum/solidity/issues/12590
langutil::EVMVersion version;
EVMHost hostContext(version, evmone);
hostContext.reset();
if (const char* dump_path = getenv("PROTO_FUZZER_DUMP_PATH"))
{
std::ofstream of(dump_path);
of.write(yul_source.data(), static_cast<std::streamsize>(yul_source.size()));
}
YulStringRepository::reset();
solidity::frontend::OptimiserSettings settings = solidity::frontend::OptimiserSettings::full();
settings.runYulOptimiser = false;
settings.optimizeStackAllocation = false;
bytes unoptimisedByteCode;
bool recursiveFunction = false;
bool unoptimizedStackTooDeep = false;
try
{
YulAssembler assembler{version, std::nullopt, settings, yul_source};
unoptimisedByteCode = assembler.assemble();
auto yulObject = assembler.object();
// TODO: Add EOF support
recursiveFunction = recursiveFunctionExists(
EVMDialect::strictAssemblyForEVMObjects(version, std::nullopt),
*yulObject
);
}
catch (solidity::yul::StackTooDeepError const&)
{
unoptimizedStackTooDeep = true;
}
std::ostringstream unoptimizedState;
bool noRevertInSource = true;
bool noInvalidInSource = true;
if (!unoptimizedStackTooDeep)
{
evmc::Result deployResult = YulEvmoneUtility{}.deployCode(unoptimisedByteCode, hostContext);
if (deployResult.status_code != EVMC_SUCCESS)
return;
auto callMessage = YulEvmoneUtility{}.callMessage(deployResult.create_address);
evmc::Result callResult = hostContext.call(callMessage);
// If the fuzzer synthesized input does not contain the revert opcode which
// we lazily check by string find, the EVM call should not revert.
noRevertInSource = yul_source.find("revert") == std::string::npos;
noInvalidInSource = yul_source.find("invalid") == std::string::npos;
if (noInvalidInSource)
solAssert(
callResult.status_code != EVMC_INVALID_INSTRUCTION,
"Invalid instruction."
);
if (noRevertInSource)
solAssert(
callResult.status_code != EVMC_REVERT,
"SolidityEvmoneInterface: EVM One reverted"
);
// Bail out on serious errors encountered during a call.
if (YulEvmoneUtility{}.seriousCallError(callResult.status_code))
return;
solAssert(
(callResult.status_code == EVMC_SUCCESS ||
(!noRevertInSource && callResult.status_code == EVMC_REVERT) ||
(!noInvalidInSource && callResult.status_code == EVMC_INVALID_INSTRUCTION)),
"Unoptimised call failed."
);
unoptimizedState << EVMHostPrinter{hostContext, deployResult.create_address}.state();
}
settings.runYulOptimiser = true;
settings.optimizeStackAllocation = true;
bytes optimisedByteCode;
try
{
optimisedByteCode = YulAssembler{version, std::nullopt, settings, yul_source}.assemble();
}
catch (solidity::yul::StackTooDeepError const&)
{
if (!recursiveFunction)
throw;
else
return;
}
if (unoptimizedStackTooDeep)
return;
// Reset host before running optimised code.
hostContext.reset();
evmc::Result deployResultOpt = YulEvmoneUtility{}.deployCode(optimisedByteCode, hostContext);
solAssert(
deployResultOpt.status_code == EVMC_SUCCESS,
"Evmone: Optimized contract creation failed"
);
auto callMessageOpt = YulEvmoneUtility{}.callMessage(deployResultOpt.create_address);
evmc::Result callResultOpt = hostContext.call(callMessageOpt);
if (noRevertInSource)
solAssert(
callResultOpt.status_code != EVMC_REVERT,
"SolidityEvmoneInterface: EVM One reverted"
);
if (noInvalidInSource)
solAssert(
callResultOpt.status_code != EVMC_INVALID_INSTRUCTION,
"Invalid instruction."
);
solAssert(
(callResultOpt.status_code == EVMC_SUCCESS ||
(!noRevertInSource && callResultOpt.status_code == EVMC_REVERT) ||
(!noInvalidInSource && callResultOpt.status_code == EVMC_INVALID_INSTRUCTION)),
"Optimised call failed."
);
std::ostringstream optimizedState;
optimizedState << EVMHostPrinter{hostContext, deployResultOpt.create_address}.state();
if (unoptimizedState.str() != optimizedState.str())
{
std::cout << unoptimizedState.str() << std::endl;
std::cout << optimizedState.str() << std::endl;
solAssert(
false,
"State of unoptimised and optimised stack reused code do not match."
);
}
}
| 6,582
|
C++
|
.cpp
| 184
| 33.043478
| 102
| 0.771065
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,923
|
abiV2ProtoFuzzer.cpp
|
ethereum_solidity/test/tools/ossfuzz/abiV2ProtoFuzzer.cpp
|
/*
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
#include <test/tools/ossfuzz/SolidityEvmoneInterface.h>
#include <test/tools/ossfuzz/protoToAbiV2.h>
#include <src/libfuzzer/libfuzzer_macro.h>
#include <fstream>
using namespace solidity::frontend;
using namespace solidity::test::fuzzer;
using namespace solidity::test::abiv2fuzzer;
using namespace solidity::test;
using namespace solidity::util;
using namespace solidity;
static evmc::VM evmone = evmc::VM{evmc_create_evmone()};
DEFINE_PROTO_FUZZER(Contract const& _input)
{
std::string contract_source = ProtoConverter{_input.seed()}.contractToString(_input);
if (const char* dump_path = getenv("PROTO_FUZZER_DUMP_PATH"))
{
// With libFuzzer binary run this to generate the solidity source file x.sol from a proto input:
// PROTO_FUZZER_DUMP_PATH=x.sol ./a.out proto-input
std::ofstream of(dump_path);
of << contract_source;
}
// We target the default EVM which is the latest
langutil::EVMVersion version;
EVMHost hostContext(version, evmone);
std::string contractName = "C";
std::string methodName = "test()";
StringMap source({{"test.sol", contract_source}});
CompilerInput cInput(version, source, contractName, OptimiserSettings::minimal(), {});
EvmoneUtility evmoneUtil(
hostContext,
cInput,
contractName,
{},
methodName
);
// Invoke test function
auto result = evmoneUtil.compileDeployAndExecute();
// We don't care about EVM One failures other than EVMC_REVERT
solAssert(result.status_code != EVMC_REVERT, "Proto ABIv2 fuzzer: EVM One reverted");
if (result.status_code == EVMC_SUCCESS)
if (!EvmoneUtility::zeroWord(result.output_data, result.output_size))
{
solidity::bytes res;
for (std::size_t i = 0; i < result.output_size; i++)
res.push_back(result.output_data[i]);
std::cout << solidity::util::toHex(res) << std::endl;
solAssert(
false,
"Proto ABIv2 fuzzer: ABIv2 coding failure found"
);
}
}
| 2,570
|
C++
|
.cpp
| 66
| 36.560606
| 98
| 0.758524
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,924
|
AbiV2IsabelleFuzzer.cpp
|
ethereum_solidity/test/tools/ossfuzz/AbiV2IsabelleFuzzer.cpp
|
/*
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
#include <test/tools/ossfuzz/SolidityEvmoneInterface.h>
#include <test/tools/ossfuzz/protoToAbiV2.h>
#include <src/libfuzzer/libfuzzer_macro.h>
#include <abicoder.hpp>
#include <fstream>
using namespace solidity::frontend;
using namespace solidity::test::fuzzer;
using namespace solidity::test::abiv2fuzzer;
using namespace solidity::test;
using namespace solidity::util;
using namespace solidity;
static constexpr size_t abiCoderHeapSize = 1024 * 512;
static evmc::VM evmone = evmc::VM{evmc_create_evmone()};
DEFINE_PROTO_FUZZER(Contract const& _contract)
{
ProtoConverter converter(_contract.seed());
std::string contractSource = converter.contractToString(_contract);
if (const char* dump_path = getenv("PROTO_FUZZER_DUMP_PATH"))
{
// With libFuzzer binary run this to generate the solidity source file x.sol from a proto input:
// PROTO_FUZZER_DUMP_PATH=x.sol ./a.out proto-input
std::ofstream of(dump_path);
of << contractSource;
}
std::string typeString = converter.isabelleTypeString();
std::string valueString = converter.isabelleValueString();
abicoder::ABICoder coder(abiCoderHeapSize);
if (!typeString.empty() && converter.coderFunction())
{
auto [encodeStatus, encodedData] = coder.encode(typeString, valueString);
solAssert(encodeStatus, "Isabelle abicoder fuzzer: Encoding failed");
// We target the default EVM which is the latest
langutil::EVMVersion version;
EVMHost hostContext(version, evmone);
std::string contractName = "C";
StringMap source({{"test.sol", contractSource}});
CompilerInput cInput(version, source, contractName, OptimiserSettings::minimal(), {});
EvmoneUtility evmoneUtil(
hostContext,
cInput,
contractName,
{},
{}
);
auto result = evmoneUtil.compileDeployAndExecute(encodedData);
solAssert(result.status_code != EVMC_REVERT, "Proto ABIv2 fuzzer: EVM One reverted.");
if (result.status_code == EVMC_SUCCESS)
solAssert(
EvmoneUtility::zeroWord(result.output_data, result.output_size),
"Proto ABIv2 fuzzer: ABIv2 coding failure found."
);
}
}
| 2,745
|
C++
|
.cpp
| 67
| 38.522388
| 98
| 0.773068
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,925
|
SolidityGenerator.cpp
|
ethereum_solidity/test/tools/ossfuzz/SolidityGenerator.cpp
|
/*
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
#include <test/tools/ossfuzz/SolidityGenerator.h>
#include <libsolutil/Whiskers.h>
#include <libsolutil/Visitor.h>
using namespace solidity::test::fuzzer::mutator;
using namespace solidity::util;
GeneratorBase::GeneratorBase(std::shared_ptr<SolidityGenerator> _mutator)
{
mutator = std::move(_mutator);
state = mutator->testState();
uRandDist = mutator->uniformRandomDist();
}
std::string GeneratorBase::visitChildren()
{
std::ostringstream os;
// Randomise visit order
std::vector<GeneratorPtr> randomisedChildren;
for (auto const& child: generators)
randomisedChildren.push_back(child);
shuffle(randomisedChildren.begin(), randomisedChildren.end(), *uRandDist->randomEngine);
for (auto child: randomisedChildren)
os << std::visit(GenericVisitor{
[&](auto const& _item) { return _item->generate(); }
}, child);
return os.str();
}
std::string TestState::randomPath(std::set<std::string> const& _sourceUnitPaths) const
{
auto it = _sourceUnitPaths.begin();
/// Advance iterator by n where 0 <= n <= sourceUnitPaths.size() - 1
size_t increment = uRandDist->distributionOneToN(_sourceUnitPaths.size()) - 1;
solAssert(
increment >= 0 && increment < _sourceUnitPaths.size(),
"Solc custom mutator: Invalid increment"
);
advance(it, increment);
return *it;
}
std::string TestState::randomPath() const
{
solAssert(!empty(), "Solc custom mutator: Null test state");
return randomPath(sourceUnitPaths);
}
void TestState::print(std::ostream& _os) const
{
_os << "Printing test state" << std::endl;
for (auto const& item: sourceUnitPaths)
_os << "Source path: " << item << std::endl;
}
std::string TestState::randomNonCurrentPath() const
{
/// To obtain a source path that is not the currently visited
/// source unit itself, we require at least one other source
/// unit to be previously visited.
solAssert(size() >= 2, "Solc custom mutator: Invalid test state");
std::set<std::string> filteredSourcePaths;
std::string currentPath = currentSourceUnitPath;
std::copy_if(
sourceUnitPaths.begin(),
sourceUnitPaths.end(),
inserter(filteredSourcePaths, filteredSourcePaths.begin()),
[currentPath](std::string const& _item) {
return _item != currentPath;
}
);
return randomPath(filteredSourcePaths);
}
void TestCaseGenerator::setup()
{
addGenerators({
mutator->generator<SourceUnitGenerator>()
});
}
std::string TestCaseGenerator::visit()
{
std::ostringstream os;
for (unsigned i = 0; i < uRandDist->distributionOneToN(s_maxSourceUnits); i++)
{
std::string sourcePath = path();
os << "\n"
<< "==== Source: "
<< sourcePath
<< " ===="
<< "\n";
updateSourcePath(sourcePath);
m_numSourceUnits++;
os << visitChildren();
}
return os.str();
}
void SourceUnitGenerator::setup()
{
addGenerators({
mutator->generator<ImportGenerator>(),
mutator->generator<PragmaGenerator>()
});
}
std::string SourceUnitGenerator::visit()
{
return visitChildren();
}
std::string PragmaGenerator::visit()
{
static constexpr const char* preamble = R"(
pragma solidity >= 0.0.0;
pragma experimental SMTChecker;
)";
// Choose equally at random from coder v1 and v2
std::string abiPragma = "pragma abicoder v" +
std::to_string(uRandDist->distributionOneToN(2)) +
";\n";
return preamble + abiPragma;
}
std::string ImportGenerator::visit()
{
/*
* Case 1: No source units defined
* Case 2: One source unit defined
* Case 3: At least two source units defined
*/
std::ostringstream os;
// Self import with a small probability only if
// there is one source unit present in test.
if (state->size() == 1)
{
if (uRandDist->probable(s_selfImportInvProb))
os << "import "
<< "\""
<< state->randomPath()
<< "\";";
}
else
{
// Import a different source unit if at least
// two source units available.
os << "import "
<< "\""
<< state->randomNonCurrentPath()
<< "\";";
}
return os.str();
}
template <typename T>
std::shared_ptr<T> SolidityGenerator::generator()
{
for (auto& g: m_generators)
if (std::holds_alternative<std::shared_ptr<T>>(g))
return std::get<std::shared_ptr<T>>(g);
solAssert(false, "");
}
SolidityGenerator::SolidityGenerator(unsigned _seed)
{
m_generators = {};
m_urd = std::make_shared<UniformRandomDistribution>(std::make_unique<RandomEngine>(_seed));
m_state = std::make_shared<TestState>(m_urd);
}
template <size_t I>
void SolidityGenerator::createGenerators()
{
if constexpr (I < std::variant_size_v<Generator>)
{
createGenerator<std::variant_alternative_t<I, Generator>>();
createGenerators<I + 1>();
}
}
std::string SolidityGenerator::generateTestProgram()
{
createGenerators();
for (auto& g: m_generators)
std::visit(GenericVisitor{
[&](auto const& _item) { return _item->setup(); }
}, g);
std::string program = generator<TestCaseGenerator>()->generate();
destroyGenerators();
return program;
}
| 5,566
|
C++
|
.cpp
| 189
| 27.206349
| 92
| 0.727307
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,928
|
SolidityCustomMutatorInterface.cpp
|
ethereum_solidity/test/tools/ossfuzz/SolidityCustomMutatorInterface.cpp
|
/*
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
#include <test/tools/ossfuzz/SolidityCustomMutatorInterface.h>
#include <test/tools/ossfuzz/SolidityGenerator.h>
#include <liblangutil/Exceptions.h>
using namespace solidity::test::fuzzer::mutator;
// Prototype as we can't use the FuzzerInterface.h header.
extern "C" size_t LLVMFuzzerMutate(uint8_t* _data, size_t _size, size_t _maxSize);
extern "C" size_t LLVMFuzzerCustomMutator(uint8_t* _data, size_t size, size_t _maxSize, unsigned int seed);
namespace
{
/// Define Solidity's custom mutator by implementing libFuzzer's
/// custom mutator external interface.
extern "C" size_t LLVMFuzzerCustomMutator(
uint8_t* _data,
size_t _size,
size_t _maxSize,
unsigned int _seed
)
{
solAssert(_data, "libFuzzerInterface: libFuzzer supplied bad buffer");
if (_maxSize <= _size || _size == 0)
return LLVMFuzzerMutate(_data, _size, _maxSize);
return SolidityCustomMutatorInterface{_data, _size, _maxSize, _seed}.generate();
}
}
SolidityCustomMutatorInterface::SolidityCustomMutatorInterface(
uint8_t* _data,
size_t _size,
size_t _maxSize,
unsigned int _seed
):
data(_data),
size(_size),
maxMutantSize(_maxSize),
generator(std::make_shared<SolidityGenerator>(_seed))
{}
size_t SolidityCustomMutatorInterface::generate()
{
std::string testCase = generator->generateTestProgram();
solAssert(
!testCase.empty() && data,
"Solc custom mutator: Invalid mutant or memory pointer"
);
size_t mutantSize = std::min(testCase.size(), maxMutantSize - 1);
mempcpy(data, testCase.data(), mutantSize);
return mutantSize;
}
| 2,216
|
C++
|
.cpp
| 60
| 35.133333
| 107
| 0.774103
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,930
|
protoToAbiV2.cpp
|
ethereum_solidity/test/tools/ossfuzz/protoToAbiV2.cpp
|
#include <test/tools/ossfuzz/protoToAbiV2.h>
#include <boost/preprocessor.hpp>
#include <regex>
/// Convenience macros
/// Returns a valid Solidity integer width w such that 8 <= w <= 256.
#define INTWIDTH(z, n, _ununsed) BOOST_PP_MUL(BOOST_PP_ADD(n, 1), 8)
/// Using declaration that aliases long boost multiprecision types with
/// s(u)<width> where <width> is a valid Solidity integer width and "s"
/// stands for "signed" and "u" for "unsigned".
#define USINGDECL(z, n, sign) \
using BOOST_PP_CAT(BOOST_PP_IF(sign, s, u), INTWIDTH(z, n,)) = \
boost::multiprecision::number< \
boost::multiprecision::cpp_int_backend< \
INTWIDTH(z, n,), \
INTWIDTH(z, n,), \
BOOST_PP_IF( \
sign, \
boost::multiprecision::signed_magnitude, \
boost::multiprecision::unsigned_magnitude \
), \
boost::multiprecision::unchecked, \
void \
> \
>;
/// Instantiate the using declarations for signed and unsigned integer types.
BOOST_PP_REPEAT(32, USINGDECL, 1)
BOOST_PP_REPEAT(32, USINGDECL, 0)
/// Case implementation that returns an integer value of the specified type.
/// For signed integers, we divide by two because the range for boost multiprecision
/// types is double that of Solidity integer types. Example, 8-bit signed boost
/// number range is [-255, 255] but Solidity `int8` range is [-128, 127]
#define CASEIMPL(z, n, sign) \
case INTWIDTH(z, n,): \
stream << BOOST_PP_IF( \
sign, \
integerValue< \
BOOST_PP_CAT( \
BOOST_PP_IF(sign, s, u), \
INTWIDTH(z, n,) \
)>(_counter) / 2, \
integerValue< \
BOOST_PP_CAT( \
BOOST_PP_IF(sign, s, u), \
INTWIDTH(z, n,) \
)>(_counter) \
); \
break;
/// Switch implementation that instantiates case statements for (un)signed
/// Solidity integer types.
#define SWITCHIMPL(sign) \
std::ostringstream stream; \
switch (_intWidth) \
{ \
BOOST_PP_REPEAT(32, CASEIMPL, sign) \
} \
return stream.str();
using namespace solidity::util;
using namespace solidity::test::abiv2fuzzer;
namespace
{
template <typename V>
static V integerValue(unsigned _counter)
{
V value = V(
u256(solidity::util::keccak256(solidity::util::h256(_counter))) % u256(boost::math::tools::max_value<V>())
);
if (boost::multiprecision::is_signed_number<V>::value && value % 2 == 0)
return value * (-1);
else
return value;
}
static std::string signedIntegerValue(unsigned _counter, unsigned _intWidth)
{
SWITCHIMPL(1)
}
static std::string unsignedIntegerValue(unsigned _counter, unsigned _intWidth)
{
SWITCHIMPL(0)
}
static std::string integerValue(unsigned _counter, unsigned _intWidth, bool _signed)
{
if (_signed)
return signedIntegerValue(_counter, _intWidth);
else
return unsignedIntegerValue(_counter, _intWidth);
}
}
std::string ProtoConverter::getVarDecl(
std::string const& _type,
std::string const& _varName,
std::string const& _qualifier
)
{
// One level of indentation for state variable declarations
// Two levels of indentation for local variable declarations
return Whiskers(R"(
<?isLocalVar> </isLocalVar><type><?qual> <qualifier></qual> <varName>;)"
)
("isLocalVar", !m_isStateVar)
("type", _type)
("qual", !_qualifier.empty())
("qualifier", _qualifier)
("varName", _varName)
.render() +
"\n";
}
std::pair<std::string, std::string> ProtoConverter::visit(Type const& _type)
{
switch (_type.type_oneof_case())
{
case Type::kVtype:
return visit(_type.vtype());
case Type::kNvtype:
return visit(_type.nvtype());
case Type::TYPE_ONEOF_NOT_SET:
return std::make_pair("", "");
}
}
std::pair<std::string, std::string> ProtoConverter::visit(ValueType const& _type)
{
switch (_type.value_type_oneof_case())
{
case ValueType::kBoolty:
return visit(_type.boolty());
case ValueType::kInty:
return visit(_type.inty());
case ValueType::kByty:
return visit(_type.byty());
case ValueType::kAdty:
return visit(_type.adty());
case ValueType::VALUE_TYPE_ONEOF_NOT_SET:
return std::make_pair("", "");
}
}
std::pair<std::string, std::string> ProtoConverter::visit(NonValueType const& _type)
{
switch (_type.nonvalue_type_oneof_case())
{
case NonValueType::kDynbytearray:
return visit(_type.dynbytearray());
case NonValueType::kArrtype:
if (ValidityVisitor().visit(_type.arrtype()))
return visit(_type.arrtype());
else
return std::make_pair("", "");
case NonValueType::kStype:
if (ValidityVisitor().visit(_type.stype()))
return visit(_type.stype());
else
return std::make_pair("", "");
case NonValueType::NONVALUE_TYPE_ONEOF_NOT_SET:
return std::make_pair("", "");
}
}
std::pair<std::string, std::string> ProtoConverter::visit(BoolType const& _type)
{
return processType(_type, true);
}
std::pair<std::string, std::string> ProtoConverter::visit(IntegerType const& _type)
{
return processType(_type, true);
}
std::pair<std::string, std::string> ProtoConverter::visit(FixedByteType const& _type)
{
return processType(_type, true);
}
std::pair<std::string, std::string> ProtoConverter::visit(AddressType const& _type)
{
return processType(_type, true);
}
std::pair<std::string, std::string> ProtoConverter::visit(DynamicByteArrayType const& _type)
{
return processType(_type, false);
}
std::pair<std::string, std::string> ProtoConverter::visit(ArrayType const& _type)
{
return processType(_type, false);
}
std::pair<std::string, std::string> ProtoConverter::visit(StructType const& _type)
{
return processType(_type, false);
}
template <typename T>
std::pair<std::string, std::string> ProtoConverter::processType(T const& _type, bool _isValueType)
{
std::ostringstream local, global;
auto [varName, paramName] = newVarNames(getNextVarCounter(), m_isStateVar);
// Add variable name to the argument list of coder function call
if (m_argsCoder.str().empty())
m_argsCoder << varName;
else
m_argsCoder << ", " << varName;
std::string location{};
if (!m_isStateVar && !_isValueType)
location = "memory";
auto varDeclBuffers = varDecl(
varName,
paramName,
_type,
_isValueType,
location
);
global << varDeclBuffers.first;
local << varDeclBuffers.second;
auto assignCheckBuffers = assignChecker(varName, paramName, _type);
global << assignCheckBuffers.first;
local << assignCheckBuffers.second;
m_structCounter += m_numStructsAdded;
return std::make_pair(global.str(), local.str());
}
template <typename T>
std::pair<std::string, std::string> ProtoConverter::varDecl(
std::string const& _varName,
std::string const& _paramName,
T _type,
bool _isValueType,
std::string const& _location
)
{
std::ostringstream local, global;
TypeVisitor tVisitor(m_structCounter);
std::string typeStr = tVisitor.visit(_type);
if (typeStr.empty())
return std::make_pair("", "");
// Append struct defs
global << tVisitor.structDef();
m_numStructsAdded = tVisitor.numStructs();
// variable declaration
if (m_isStateVar)
global << getVarDecl(typeStr, _varName, _location);
else
local << getVarDecl(typeStr, _varName, _location);
// Add typed params for calling public and external functions with said type
appendTypedParams(
CalleeType::PUBLIC,
_isValueType,
typeStr,
_paramName,
((m_varCounter == 1) ? Delimiter::SKIP : Delimiter::ADD)
);
appendTypedParams(
CalleeType::EXTERNAL,
_isValueType,
typeStr,
_paramName,
((m_varCounter == 1) ? Delimiter::SKIP : Delimiter::ADD)
);
appendTypes(
_isValueType,
typeStr,
((m_varCounter == 1) ? Delimiter::SKIP : Delimiter::ADD)
);
appendTypedReturn(
_isValueType,
typeStr,
((m_varCounter == 1) ? Delimiter::SKIP : Delimiter::ADD)
);
appendToIsabelleTypeString(
tVisitor.isabelleTypeString(),
((m_varCounter == 1) ? Delimiter::SKIP : Delimiter::ADD)
);
// Update dyn param only if necessary
if (tVisitor.isLastDynParamRightPadded())
m_isLastDynParamRightPadded = true;
return std::make_pair(global.str(), local.str());
}
template <typename T>
std::pair<std::string, std::string> ProtoConverter::assignChecker(
std::string const& _varName,
std::string const& _paramName,
T _type
)
{
std::ostringstream local;
AssignCheckVisitor acVisitor(
_varName,
_paramName,
m_returnValue,
m_isStateVar,
m_counter,
m_structCounter
);
std::pair<std::string, std::string> assignCheckStrPair = acVisitor.visit(_type);
m_returnValue += acVisitor.errorStmts();
m_counter += acVisitor.counted();
m_checks << assignCheckStrPair.second;
appendToIsabelleValueString(
acVisitor.isabelleValueString(),
((m_varCounter == 1) ? Delimiter::SKIP : Delimiter::ADD)
);
// State variables cannot be assigned in contract-scope
// Therefore, we buffer their assignments and
// render them in function scope later.
local << assignCheckStrPair.first;
return std::make_pair("", local.str());
}
std::pair<std::string, std::string> ProtoConverter::visit(VarDecl const& _x)
{
return visit(_x.type());
}
std::string ProtoConverter::equalityChecksAsString()
{
return m_checks.str();
}
std::string ProtoConverter::delimiterToString(Delimiter _delimiter, bool _space)
{
switch (_delimiter)
{
case Delimiter::ADD:
return _space ? ", " : ",";
case Delimiter::SKIP:
return "";
}
}
/* When a new variable is declared, we can invoke this function
* to prepare the typed param list to be passed to callee functions.
* We independently prepare this list for "public" and "external"
* callee functions.
*/
void ProtoConverter::appendTypedParams(
CalleeType _calleeType,
bool _isValueType,
std::string const& _typeString,
std::string const& _varName,
Delimiter _delimiter
)
{
switch (_calleeType)
{
case CalleeType::PUBLIC:
appendTypedParamsPublic(_isValueType, _typeString, _varName, _delimiter);
break;
case CalleeType::EXTERNAL:
appendTypedParamsExternal(_isValueType, _typeString, _varName, _delimiter);
break;
}
}
void ProtoConverter::appendTypes(
bool _isValueType,
std::string const& _typeString,
Delimiter _delimiter
)
{
std::string qualifiedTypeString = (
_isValueType ?
_typeString :
_typeString + " memory"
);
m_types << Whiskers(R"(<delimiter><type>)")
("delimiter", delimiterToString(_delimiter))
("type", qualifiedTypeString)
.render();
}
void ProtoConverter::appendTypedReturn(
bool _isValueType,
std::string const& _typeString,
Delimiter _delimiter
)
{
std::string qualifiedTypeString = (
_isValueType ?
_typeString :
_typeString + " memory"
);
m_typedReturn << Whiskers(R"(<delimiter><type> <varName>)")
("delimiter", delimiterToString(_delimiter))
("type", qualifiedTypeString)
("varName", "lv_" + std::to_string(m_varCounter - 1))
.render();
}
// Adds the qualifier "calldata" to non-value parameter of an external function.
void ProtoConverter::appendTypedParamsExternal(
bool _isValueType,
std::string const& _typeString,
std::string const& _varName,
Delimiter _delimiter
)
{
m_externalParamsRep.push_back({_delimiter, _isValueType, _typeString, _varName});
m_untypedParamsExternal << Whiskers(R"(<delimiter><varName>)")
("delimiter", delimiterToString(_delimiter))
("varName", _varName)
.render();
}
// Adds the qualifier "memory" to non-value parameter of an external function.
void ProtoConverter::appendTypedParamsPublic(
bool _isValueType,
std::string const& _typeString,
std::string const& _varName,
Delimiter _delimiter
)
{
std::string qualifiedTypeString = (
_isValueType ?
_typeString :
_typeString + " memory"
);
m_typedParamsPublic << Whiskers(R"(<delimiter><type> <varName>)")
("delimiter", delimiterToString(_delimiter))
("type", qualifiedTypeString)
("varName", _varName)
.render();
}
void ProtoConverter::appendToIsabelleTypeString(
std::string const& _typeString,
Delimiter _delimiter
)
{
m_isabelleTypeString << delimiterToString(_delimiter, false) << _typeString;
}
void ProtoConverter::appendToIsabelleValueString(
std::string const& _valueString,
Delimiter _delimiter
)
{
m_isabelleValueString << delimiterToString(_delimiter, false) << _valueString;
}
std::string ProtoConverter::typedParametersAsString(CalleeType _calleeType)
{
switch (_calleeType)
{
case CalleeType::PUBLIC:
return m_typedParamsPublic.str();
case CalleeType::EXTERNAL:
{
std::ostringstream typedParamsExternal;
for (auto const& i: m_externalParamsRep)
{
Delimiter del = std::get<0>(i);
bool valueType = std::get<1>(i);
std::string typeString = std::get<2>(i);
std::string varName = std::get<3>(i);
bool isCalldata = randomBool(/*probability=*/0.5);
std::string location = (isCalldata ? "calldata" : "memory");
std::string qualifiedTypeString = (valueType ? typeString : typeString + " " + location);
typedParamsExternal << Whiskers(R"(<delimiter><type> <varName>)")
("delimiter", delimiterToString(del))
("type", qualifiedTypeString)
("varName", varName)
.render();
}
return typedParamsExternal.str();
}
}
}
std::string ProtoConverter::visit(TestFunction const& _x, std::string const& _storageVarDefs)
{
// TODO: Support more than one but less than N local variables
auto localVarBuffers = visit(_x.local_vars());
std::string structTypeDecl = localVarBuffers.first;
std::string localVarDefs = localVarBuffers.second;
std::ostringstream testBuffer;
std::string testFunction = Whiskers(R"(
function test() public returns (uint) {
<?calldata>return test_calldata_coding();</calldata>
<?returndata>return test_returndata_coding();</returndata>
})")
("calldata", m_test == Contract_Test::Contract_Test_CALLDATA_CODER)
("returndata", m_test == Contract_Test::Contract_Test_RETURNDATA_CODER)
.render();
std::string functionDeclCalldata = "function test_calldata_coding() internal returns (uint)";
std::string functionDeclReturndata = "function test_returndata_coding() internal returns (uint)";
testBuffer << Whiskers(R"(<structTypeDecl>
<testFunction>
<?calldata>
<functionDeclCalldata> {
<storageVarDefs>
<localVarDefs>
<calldataTestCode>
}
<calldataHelperFuncs>
</calldata>
<?returndata>
<functionDeclReturndata> {
<returndataTestCode>
}
<?varsPresent>
function coder_returndata_external() external returns (<return_types>) {
<storageVarDefs>
<localVarDefs>
return (<return_values>);
}
</varsPresent>
</returndata>)")
("testFunction", testFunction)
("calldata", m_test == Contract_Test::Contract_Test_CALLDATA_CODER)
("returndata", m_test == Contract_Test::Contract_Test_RETURNDATA_CODER)
("calldataHelperFuncs", calldataHelperFunctions())
("varsPresent", !m_types.str().empty())
("structTypeDecl", structTypeDecl)
("functionDeclCalldata", functionDeclCalldata)
("functionDeclReturndata", functionDeclReturndata)
("storageVarDefs", _storageVarDefs)
("localVarDefs", localVarDefs)
("calldataTestCode", testCallDataFunction(static_cast<unsigned>(_x.invalid_encoding_length())))
("returndataTestCode", testReturnDataFunction())
("return_types", m_types.str())
("return_values", m_argsCoder.str())
.render();
return testBuffer.str();
}
std::string ProtoConverter::testCallDataFunction(unsigned _invalidLength)
{
return Whiskers(R"(
uint returnVal = this.coder_calldata_public(<argumentNames>);
if (returnVal != 0)
return returnVal;
returnVal = this.coder_calldata_external(<argumentNames>);
if (returnVal != 0)
return uint(200000) + returnVal;
<?atLeastOneVar>
bytes memory argumentEncoding = abi.encode(<argumentNames>);
returnVal = checkEncodedCall(
this.coder_calldata_public.selector,
argumentEncoding,
<invalidLengthFuzz>,
<isRightPadded>
);
if (returnVal != 0)
return returnVal;
returnVal = checkEncodedCall(
this.coder_calldata_external.selector,
argumentEncoding,
<invalidLengthFuzz>,
<isRightPadded>
);
if (returnVal != 0)
return uint(200000) + returnVal;
</atLeastOneVar>
return 0;
)")
("argumentNames", m_argsCoder.str())
("invalidLengthFuzz", std::to_string(_invalidLength))
("isRightPadded", isLastDynParamRightPadded() ? "true" : "false")
("atLeastOneVar", m_varCounter > 0)
.render();
}
std::string ProtoConverter::testReturnDataFunction()
{
return Whiskers(R"(
<?varsPresent>
(<varDecl>) = this.coder_returndata_external();
<equality_checks>
</varsPresent>
return 0;
)")
("varsPresent", !m_typedReturn.str().empty())
("varDecl", m_typedReturn.str())
("equality_checks", m_checks.str())
.render();
}
std::string ProtoConverter::calldataHelperFunctions()
{
std::stringstream calldataHelperFuncs;
calldataHelperFuncs << R"(
/// Accepts function selector, correct argument encoding, and length of
/// invalid encoding and returns the correct and incorrect abi encoding
/// for calling the function specified by the function selector.
function createEncoding(
bytes4 funcSelector,
bytes memory argumentEncoding,
uint invalidLengthFuzz,
bool isRightPadded
) internal pure returns (bytes memory, bytes memory)
{
bytes memory validEncoding = new bytes(4 + argumentEncoding.length);
// Ensure that invalidEncoding crops at least 32 bytes (padding length
// is at most 31 bytes) if `isRightPadded` is true.
// This is because shorter bytes/string values (whose encoding is right
// padded) can lead to successful decoding when fewer than 32 bytes have
// been cropped in the worst case. In other words, if `isRightPadded` is
// true, then
// 0 <= invalidLength <= argumentEncoding.length - 32
// otherwise
// 0 <= invalidLength <= argumentEncoding.length - 1
uint invalidLength;
if (isRightPadded)
invalidLength = invalidLengthFuzz % (argumentEncoding.length - 31);
else
invalidLength = invalidLengthFuzz % argumentEncoding.length;
bytes memory invalidEncoding = new bytes(4 + invalidLength);
for (uint i = 0; i < 4; i++)
validEncoding[i] = invalidEncoding[i] = funcSelector[i];
for (uint i = 0; i < argumentEncoding.length; i++)
validEncoding[i+4] = argumentEncoding[i];
for (uint i = 0; i < invalidLength; i++)
invalidEncoding[i+4] = argumentEncoding[i];
return (validEncoding, invalidEncoding);
}
/// Accepts function selector, correct argument encoding, and an invalid
/// encoding length as input. Returns a non-zero value if either call with
/// correct encoding fails or call with incorrect encoding succeeds.
/// Returns zero if both calls meet expectation.
function checkEncodedCall(
bytes4 funcSelector,
bytes memory argumentEncoding,
uint invalidLengthFuzz,
bool isRightPadded
) public returns (uint)
{
(bytes memory validEncoding, bytes memory invalidEncoding) = createEncoding(
funcSelector,
argumentEncoding,
invalidLengthFuzz,
isRightPadded
);
(bool success, bytes memory returnVal) = address(this).call(validEncoding);
uint returnCode = abi.decode(returnVal, (uint));
// Return non-zero value if call fails for correct encoding
if (success == false || returnCode != 0)
return 400000;
(success, ) = address(this).call(invalidEncoding);
// Return non-zero value if call succeeds for incorrect encoding
if (success == true)
return 400001;
return 0;
})";
/// These are indirections to test memory-calldata codings more robustly.
std::stringstream indirections;
unsigned numIndirections = randomNumberOneToN(s_maxIndirections);
for (unsigned i = 1; i <= numIndirections; i++)
{
bool finalIndirection = i == numIndirections;
std::string mutability = (finalIndirection ? "pure" : "view");
indirections << Whiskers(R"(
function coder_calldata_external_i<N>(<parameters>) external <mutability> returns (uint) {
<?finalIndirection>
<equality_checks>
return 0;
<!finalIndirection>
return this.coder_calldata_external_i<NPlusOne>(<untyped_parameters>);
</finalIndirection>
}
)")
("N", std::to_string(i))
("parameters", typedParametersAsString(CalleeType::EXTERNAL))
("mutability", mutability)
("finalIndirection", finalIndirection)
("equality_checks", equalityChecksAsString())
("NPlusOne", std::to_string(i + 1))
("untyped_parameters", m_untypedParamsExternal.str())
.render();
}
// These are callee functions that encode from storage, decode to
// memory/calldata and check if decoded value matches storage value
// return true on successful match, false otherwise
calldataHelperFuncs << Whiskers(R"(
function coder_calldata_public(<parameters_memory>) public pure returns (uint) {
<equality_checks>
return 0;
}
function coder_calldata_external(<parameters_calldata>) external view returns (uint) {
return this.coder_calldata_external_i1(<untyped_parameters>);
}
<indirections>
)")
("parameters_memory", typedParametersAsString(CalleeType::PUBLIC))
("equality_checks", equalityChecksAsString())
("parameters_calldata", typedParametersAsString(CalleeType::EXTERNAL))
("untyped_parameters", m_untypedParamsExternal.str())
("indirections", indirections.str())
.render();
return calldataHelperFuncs.str();
}
std::string ProtoConverter::commonHelperFunctions()
{
std::stringstream helperFuncs;
helperFuncs << R"(
/// Compares bytes, returning true if they are equal and false otherwise.
function bytesCompare(bytes memory a, bytes memory b) internal pure returns (bool) {
if(a.length != b.length)
return false;
for (uint i = 0; i < a.length; i++)
if (a[i] != b[i])
return false;
return true;
}
)";
return helperFuncs.str();
}
void ProtoConverter::visit(Contract const& _x)
{
std::string pragmas = R"(pragma solidity >=0.0;
pragma experimental ABIEncoderV2;)";
// Record test spec
m_test = _x.test();
// TODO: Support more than one but less than N state variables
auto storageBuffers = visit(_x.state_vars());
std::string storageVarDecls = storageBuffers.first;
std::string storageVarDefs = storageBuffers.second;
m_isStateVar = false;
std::string testFunction = visit(_x.testfunction(), storageVarDefs);
/* Structure of contract body
* - Storage variable declarations
* - Struct definitions
* - Test function
* - Storage variable assignments
* - Local variable definitions and assignments
* - Test code proper (calls public and external functions)
* - Helper functions
*/
std::ostringstream contractBody;
contractBody << storageVarDecls
<< testFunction
<< commonHelperFunctions();
m_output << Whiskers(R"(<pragmas>
<contractStart>
<contractBody>
<contractEnd>)")
("pragmas", pragmas)
("contractStart", "contract C {")
("contractBody", contractBody.str())
("contractEnd", "}")
.render();
}
std::string ProtoConverter::isabelleTypeString() const
{
std::string typeString = m_isabelleTypeString.str();
if (!typeString.empty())
return "(" + typeString + ")";
else
return typeString;
}
std::string ProtoConverter::isabelleValueString() const
{
std::string valueString = m_isabelleValueString.str();
if (!valueString.empty())
return "(" + valueString + ")";
else
return valueString;
}
std::string ProtoConverter::contractToString(Contract const& _input)
{
visit(_input);
return m_output.str();
}
/// Type visitor
void TypeVisitor::StructTupleString::addTypeStringToTuple(std::string& _typeString)
{
index++;
if (index > 1)
stream << ",";
stream << _typeString;
}
void TypeVisitor::StructTupleString::addArrayBracketToType(std::string& _arrayBracket)
{
stream << _arrayBracket;
}
std::string TypeVisitor::visit(BoolType const&)
{
m_baseType = "bool";
m_structTupleString.addTypeStringToTuple(m_baseType);
return m_baseType;
}
std::string TypeVisitor::visit(IntegerType const& _type)
{
m_baseType = getIntTypeAsString(_type);
m_structTupleString.addTypeStringToTuple(m_baseType);
return m_baseType;
}
std::string TypeVisitor::visit(FixedByteType const& _type)
{
m_baseType = getFixedByteTypeAsString(_type);
m_structTupleString.addTypeStringToTuple(m_baseType);
return m_baseType;
}
std::string TypeVisitor::visit(AddressType const&)
{
m_baseType = "address";
m_structTupleString.addTypeStringToTuple(m_baseType);
return m_baseType;
}
std::string TypeVisitor::visit(ArrayType const& _type)
{
if (!ValidityVisitor().visit(_type))
return "";
std::string baseType = visit(_type.t());
solAssert(!baseType.empty(), "");
std::string arrayBracket = _type.is_static() ?
std::string("[") +
std::to_string(getStaticArrayLengthFromFuzz(_type.length())) +
std::string("]") :
std::string("[]");
m_baseType += arrayBracket;
m_structTupleString.addArrayBracketToType(arrayBracket);
// If we don't know yet if the array will be dynamically encoded,
// check again. If we already know that it will be, there's no
// need to do anything.
if (!m_isLastDynParamRightPadded)
m_isLastDynParamRightPadded = DynParamVisitor().visit(_type);
return baseType + arrayBracket;
}
std::string TypeVisitor::visit(DynamicByteArrayType const&)
{
m_isLastDynParamRightPadded = true;
m_baseType = "bytes";
m_structTupleString.addTypeStringToTuple(m_baseType);
return m_baseType;
}
void TypeVisitor::structDefinition(StructType const& _type)
{
// Return an empty string if struct is empty
solAssert(ValidityVisitor().visit(_type), "");
// Reset field counter and indentation
unsigned wasFieldCounter = m_structFieldCounter;
unsigned wasIndentation = m_indentation;
m_indentation = 1;
m_structFieldCounter = 0;
// Commence struct declaration
std::string structDef = lineString(
"struct " +
std::string(s_structNamePrefix) +
std::to_string(m_structCounter) +
" {"
);
// Start tuple of types with parenthesis
m_structTupleString.start();
// Increase indentation for struct fields
m_indentation++;
for (auto const& t: _type.t())
{
std::string type{};
if (!ValidityVisitor().visit(t))
continue;
TypeVisitor tVisitor(m_structCounter + 1);
type = tVisitor.visit(t);
m_structCounter += tVisitor.numStructs();
m_structDef << tVisitor.structDef();
solAssert(!type.empty(), "");
structDef += lineString(
Whiskers(R"(<type> <member>;)")
("type", type)
("member", "m" + std::to_string(m_structFieldCounter++))
.render()
);
std::string isabelleTypeStr = tVisitor.isabelleTypeString();
m_structTupleString.addTypeStringToTuple(isabelleTypeStr);
}
m_indentation--;
structDef += lineString("}");
// End tuple of types with parenthesis
m_structTupleString.end();
m_structCounter++;
m_structDef << structDef;
m_indentation = wasIndentation;
m_structFieldCounter = wasFieldCounter;
}
std::string TypeVisitor::visit(StructType const& _type)
{
if (ValidityVisitor().visit(_type))
{
// Add struct definition
structDefinition(_type);
// Set last dyn param if struct contains a dyn param e.g., bytes, array etc.
m_isLastDynParamRightPadded = DynParamVisitor().visit(_type);
// If top-level struct is a non-empty struct, assign the name S<suffix>
m_baseType = s_structTypeName + std::to_string(m_structStartCounter);
}
else
m_baseType = {};
return m_baseType;
}
/// AssignCheckVisitor implementation
void AssignCheckVisitor::ValueStream::appendValue(std::string& _value)
{
solAssert(!_value.empty(), "Abiv2 fuzzer: Empty value");
index++;
if (index > 1)
stream << ",";
stream << _value;
}
std::pair<std::string, std::string> AssignCheckVisitor::visit(BoolType const& _type)
{
std::string value = ValueGetterVisitor(counter()).visit(_type);
if (!m_forcedVisit)
m_valueStream.appendValue(value);
return assignAndCheckStringPair(m_varName, m_paramName, value, value, DataType::VALUE);
}
std::pair<std::string, std::string> AssignCheckVisitor::visit(IntegerType const& _type)
{
std::string value = ValueGetterVisitor(counter()).visit(_type);
if (!m_forcedVisit)
m_valueStream.appendValue(value);
return assignAndCheckStringPair(m_varName, m_paramName, value, value, DataType::VALUE);
}
std::pair<std::string, std::string> AssignCheckVisitor::visit(FixedByteType const& _type)
{
std::string value = ValueGetterVisitor(counter()).visit(_type);
if (!m_forcedVisit)
{
std::string isabelleValue = ValueGetterVisitor{}.isabelleBytesValueAsString(value);
m_valueStream.appendValue(isabelleValue);
}
return assignAndCheckStringPair(m_varName, m_paramName, value, value, DataType::VALUE);
}
std::pair<std::string, std::string> AssignCheckVisitor::visit(AddressType const& _type)
{
std::string value = ValueGetterVisitor(counter()).visit(_type);
if (!m_forcedVisit)
{
std::string isabelleValue = ValueGetterVisitor{}.isabelleAddressValueAsString(value);
m_valueStream.appendValue(isabelleValue);
}
return assignAndCheckStringPair(m_varName, m_paramName, value, value, DataType::VALUE);
}
std::pair<std::string, std::string> AssignCheckVisitor::visit(DynamicByteArrayType const& _type)
{
std::string value = ValueGetterVisitor(counter()).visit(_type);
if (!m_forcedVisit)
{
std::string isabelleValue = ValueGetterVisitor{}.isabelleBytesValueAsString(value);
m_valueStream.appendValue(isabelleValue);
}
DataType dataType = DataType::BYTES;
return assignAndCheckStringPair(m_varName, m_paramName, value, value, dataType);
}
std::pair<std::string, std::string> AssignCheckVisitor::visit(ArrayType const& _type)
{
if (!ValidityVisitor().visit(_type))
return std::make_pair("", "");
// Obtain type of array to be resized and initialized
std::string typeStr{};
unsigned wasStructCounter = m_structCounter;
TypeVisitor tVisitor(m_structCounter);
typeStr = tVisitor.visit(_type);
std::pair<std::string, std::string> resizeBuffer;
std::string lengthStr;
unsigned length;
// Resize dynamic arrays
if (!_type.is_static())
{
length = getDynArrayLengthFromFuzz(_type.length(), counter());
lengthStr = std::to_string(length);
if (m_stateVar)
{
// Dynamic storage arrays are resized via the empty push() operation
resizeBuffer.first = Whiskers(R"(<indentation>for (uint i = 0; i < <length>; i++) <arrayRef>.push();)")
("indentation", indentation())
("length", lengthStr)
("arrayRef", m_varName)
.render() + "\n";
// Add a dynamic check on the resized length
resizeBuffer.second = checkString(m_paramName + ".length", lengthStr, DataType::VALUE);
}
else
{
// Resizing memory arrays via the new operator
std::string resizeOp = Whiskers(R"(new <fullTypeStr>(<length>))")
("fullTypeStr", typeStr)
("length", lengthStr)
.render();
resizeBuffer = assignAndCheckStringPair(
m_varName,
m_paramName + ".length",
resizeOp,
lengthStr,
DataType::VALUE
);
}
}
else
{
length = getStaticArrayLengthFromFuzz(_type.length());
lengthStr = std::to_string(length);
// Add check on length
resizeBuffer.second = checkString(m_paramName + ".length", lengthStr, DataType::VALUE);
}
// Add assignCheckBuffer and check statements
std::pair<std::string, std::string> assignCheckBuffer;
std::string wasVarName = m_varName;
std::string wasParamName = m_paramName;
if (!m_forcedVisit)
m_valueStream.startArray();
for (unsigned i = 0; i < length; i++)
{
m_varName = wasVarName + "[" + std::to_string(i) + "]";
m_paramName = wasParamName + "[" + std::to_string(i) + "]";
std::pair<std::string, std::string> assign = visit(_type.t());
assignCheckBuffer.first += assign.first;
assignCheckBuffer.second += assign.second;
if (i < length - 1)
m_structCounter = wasStructCounter;
}
// Since struct visitor won't be called for zero-length
// arrays, struct counter will not get incremented. Therefore,
// we need to manually force a recursive struct visit.
if (length == 0 && TypeVisitor().arrayOfStruct(_type))
{
bool previousState = m_forcedVisit;
m_forcedVisit = true;
visit(_type.t());
m_forcedVisit = previousState;
}
if (!m_forcedVisit)
m_valueStream.endArray();
m_varName = wasVarName;
m_paramName = wasParamName;
// Compose resize and initialization assignment and check
return std::make_pair(
resizeBuffer.first + assignCheckBuffer.first,
resizeBuffer.second + assignCheckBuffer.second
);
}
std::pair<std::string, std::string> AssignCheckVisitor::visit(StructType const& _type)
{
if (!ValidityVisitor().visit(_type))
return std::make_pair("", "");
std::pair<std::string, std::string> assignCheckBuffer;
unsigned i = 0;
// Increment struct counter
m_structCounter++;
std::string wasVarName = m_varName;
std::string wasParamName = m_paramName;
if (!m_forcedVisit)
m_valueStream.startStruct();
for (auto const& t: _type.t())
{
m_varName = wasVarName + ".m" + std::to_string(i);
m_paramName = wasParamName + ".m" + std::to_string(i);
std::pair<std::string, std::string> assign = visit(t);
// If type is not well formed continue without
// updating state.
if (assign.first.empty() && assign.second.empty())
continue;
assignCheckBuffer.first += assign.first;
assignCheckBuffer.second += assign.second;
i++;
}
if (!m_forcedVisit)
m_valueStream.endStruct();
m_varName = wasVarName;
m_paramName = wasParamName;
return assignCheckBuffer;
}
std::pair<std::string, std::string> AssignCheckVisitor::assignAndCheckStringPair(
std::string const& _varRef,
std::string const& _checkRef,
std::string const& _assignValue,
std::string const& _checkValue,
DataType _type
)
{
return std::make_pair(assignString(_varRef, _assignValue), checkString(_checkRef, _checkValue, _type));
}
std::string AssignCheckVisitor::assignString(std::string const& _ref, std::string const& _value)
{
std::string assignStmt = Whiskers(R"(<ref> = <value>;)")
("ref", _ref)
("value", _value)
.render();
return indentation() + assignStmt + "\n";
}
std::string AssignCheckVisitor::checkString(std::string const& _ref, std::string const& _value, DataType _type)
{
std::string checkPred;
switch (_type)
{
case DataType::BYTES:
checkPred = Whiskers(R"(!bytesCompare(<varName>, <value>))")
("varName", _ref)
("value", _value)
.render();
break;
case DataType::VALUE:
checkPred = Whiskers(R"(<varName> != <value>)")
("varName", _ref)
("value", _value)
.render();
break;
case DataType::ARRAY:
solUnimplemented("Proto ABIv2 fuzzer: Invalid data type.");
}
std::string checkStmt = Whiskers(R"(if (<checkPred>) return <errCode>;)")
("checkPred", checkPred)
("errCode", std::to_string(m_errorCode++))
.render();
return indentation() + checkStmt + "\n";
}
/// ValueGetterVisitor
std::string ValueGetterVisitor::visit(BoolType const&)
{
return counter() % 2 ? "true" : "false";
}
std::string ValueGetterVisitor::visit(IntegerType const& _type)
{
return integerValue(counter(), getIntWidth(_type), _type.is_signed());
}
std::string ValueGetterVisitor::visit(FixedByteType const& _type)
{
return fixedByteValueAsString(
getFixedByteWidth(_type),
counter()
);
}
std::string ValueGetterVisitor::visit(AddressType const&)
{
return addressValueAsString(counter());
}
std::string ValueGetterVisitor::visit(DynamicByteArrayType const&)
{
return bytesArrayValueAsString(
counter(),
true
);
}
std::string ValueGetterVisitor::croppedString(
unsigned _numBytes,
unsigned _counter,
bool _isHexLiteral
)
{
solAssert(
_numBytes > 0 && _numBytes <= 32,
"Proto ABIv2 fuzzer: Too short or too long a cropped string"
);
// Number of masked nibbles is twice the number of bytes for a
// hex literal of _numBytes bytes. For a string literal, each nibble
// is treated as a character.
unsigned numMaskNibbles = _isHexLiteral ? _numBytes * 2 : _numBytes;
// Start position of substring equals totalHexStringLength - numMaskNibbles
// totalHexStringLength = 64 + 2 = 66
// e.g., 0x12345678901234567890123456789012 is a total of 66 characters
// |---------------------^-----------|
// <--- start position---><--numMask->
// <-----------total length --------->
// Note: This assumes that maskUnsignedIntToHex() invokes toHex(..., HexPrefix::Add)
unsigned startPos = 66 - numMaskNibbles;
// Extracts the least significant numMaskNibbles from the result
// of maskUnsignedIntToHex().
return maskUnsignedIntToHex(
_counter,
numMaskNibbles
).substr(startPos, numMaskNibbles);
}
std::string ValueGetterVisitor::hexValueAsString(
unsigned _numBytes,
unsigned _counter,
bool _isHexLiteral,
bool _decorate
)
{
solAssert(_numBytes > 0 && _numBytes <= 32,
"Proto ABIv2 fuzzer: Invalid hex length"
);
// If _decorate is set, then we return a hex"" or a "" string.
if (_numBytes == 0)
return Whiskers(R"(<?decorate><?isHex>hex</isHex>""</decorate>)")
("decorate", _decorate)
("isHex", _isHexLiteral)
.render();
// This is needed because solidity interprets a 20-byte 0x prefixed hex literal as an address
// payable type.
return Whiskers(R"(<?decorate><?isHex>hex</isHex>"</decorate><value><?decorate>"</decorate>)")
("decorate", _decorate)
("isHex", _isHexLiteral)
("value", croppedString(_numBytes, _counter, _isHexLiteral))
.render();
}
std::string ValueGetterVisitor::fixedByteValueAsString(unsigned _width, unsigned _counter)
{
solAssert(
(_width >= 1 && _width <= 32),
"Proto ABIv2 Fuzzer: Fixed byte width is not between 1--32"
);
return hexValueAsString(_width, _counter, /*isHexLiteral=*/true);
}
std::string ValueGetterVisitor::addressValueAsString(unsigned _counter)
{
return "address(" + maskUnsignedIntToHex(_counter, 40) + ")";
}
std::string ValueGetterVisitor::isabelleAddressValueAsString(std::string& _solAddressString)
{
// Isabelle encoder expects address literal to be exactly
// 20 bytes and a hex string.
// Example: 0x0102030405060708090a0102030405060708090a
std::regex const addressPattern("address\\((.*)\\)");
std::smatch match;
solAssert(std::regex_match(_solAddressString, match, addressPattern), "Abiv2 fuzzer: Invalid address string");
std::string addressHex = match[1].str();
addressHex.erase(2, 24);
return addressHex;
}
std::string ValueGetterVisitor::isabelleBytesValueAsString(std::string& _solBytesString)
{
std::regex const bytesPattern("hex\"(.*)\"");
std::smatch match;
solAssert(std::regex_match(_solBytesString, match, bytesPattern), "Abiv2 fuzzer: Invalid bytes string");
std::string bytesHex = match[1].str();
return "0x" + bytesHex;
}
std::string ValueGetterVisitor::variableLengthValueAsString(
unsigned _numBytes,
unsigned _counter,
bool _isHexLiteral
)
{
if (_numBytes == 0)
return Whiskers(R"(<?isHex>hex</isHex>"")")
("isHex", _isHexLiteral)
.render();
unsigned numBytesRemaining = _numBytes;
// Stores the literal
std::string output{};
// If requested value is shorter than or exactly 32 bytes,
// the literal is the return value of hexValueAsString.
if (numBytesRemaining <= 32)
output = hexValueAsString(
numBytesRemaining,
_counter,
_isHexLiteral,
/*decorate=*/false
);
// If requested value is longer than 32 bytes, the literal
// is obtained by duplicating the return value of hexValueAsString
// until we reach a value of the requested size.
else
{
// Create a 32-byte value to be duplicated and
// update number of bytes to be appended.
// Stores the cached literal that saves us
// (expensive) calls to keccak256.
std::string cachedString = hexValueAsString(
/*numBytes=*/32,
_counter,
_isHexLiteral,
/*decorate=*/false
);
output = cachedString;
numBytesRemaining -= 32;
// Append bytes from cachedString until
// we create a value of desired length.
unsigned numAppendedBytes;
while (numBytesRemaining > 0)
{
// We append at most 32 bytes at a time
numAppendedBytes = numBytesRemaining >= 32 ? 32 : numBytesRemaining;
output += cachedString.substr(
0,
// Double the substring length for hex literals since each
// character is actually half a byte (or a nibble).
_isHexLiteral ? numAppendedBytes * 2 : numAppendedBytes
);
numBytesRemaining -= numAppendedBytes;
}
solAssert(
numBytesRemaining == 0,
"Proto ABIv2 fuzzer: Logic flaw in variable literal creation"
);
}
if (_isHexLiteral)
solAssert(
output.size() == 2 * _numBytes,
"Proto ABIv2 fuzzer: Generated hex literal is of incorrect length"
);
else
solAssert(
output.size() == _numBytes,
"Proto ABIv2 fuzzer: Generated string literal is of incorrect length"
);
// Decorate output
return Whiskers(R"(<?isHexLiteral>hex</isHexLiteral>"<value>")")
("isHexLiteral", _isHexLiteral)
("value", output)
.render();
}
std::string ValueGetterVisitor::bytesArrayValueAsString(unsigned _counter, bool _isHexLiteral)
{
return variableLengthValueAsString(
getVarLength(_counter),
_counter,
_isHexLiteral
);
}
| 42,040
|
C++
|
.cpp
| 1,273
| 30.501178
| 111
| 0.70145
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,931
|
YulProtoMutator.cpp
|
ethereum_solidity/test/tools/ossfuzz/protomutators/YulProtoMutator.cpp
|
#include <test/tools/ossfuzz/protomutators/YulProtoMutator.h>
#include <libyul/Exceptions.h>
#include <src/text_format.h>
using namespace solidity::yul::test::yul_fuzzer;
using namespace protobuf_mutator;
using YPM = YulProtoMutator;
MutationInfo::MutationInfo(ProtobufMessage const* _message, std::string const& _info):
ScopeGuard([&]{ exitInfo(); }),
m_protobufMsg(_message)
{
writeLine("----------------------------------");
writeLine("YULMUTATOR: " + _info);
writeLine("Before");
writeLine(SaveMessageAsText(*m_protobufMsg));
}
void MutationInfo::exitInfo()
{
writeLine("After");
writeLine(SaveMessageAsText(*m_protobufMsg));
}
/// Add m/sstore(0, variable)
static LPMPostProcessor<Block> addStoreToZero(
[](Block* _message, unsigned _seed)
{
if (_seed % YPM::s_highIP == 0)
{
YulRandomNumGenerator yrand(_seed);
MutationInfo m{_message, "Added store to zero"};
auto storeStmt = new StoreFunc();
storeStmt->set_st(YPM::EnumTypeConverter<StoreFunc_Storage>{}.enumFromSeed(yrand()));
storeStmt->set_allocated_loc(YPM::litExpression(0));
storeStmt->set_allocated_val(YPM::refExpression(yrand));
auto stmt = _message->add_statements();
stmt->set_allocated_storage_func(storeStmt);
}
}
);
namespace
{
template <typename T>
struct addControlFlow
{
addControlFlow()
{
function = [](T* _message, unsigned _seed)
{
MutationInfo m{_message, "Added control flow."};
YPM::addControlFlow(_message, _seed);
};
/// Unused variable registers callback.
LPMPostProcessor<T> callback(function);
}
std::function<void(T*, unsigned)> function;
};
}
static addControlFlow<ForStmt> c1;
static addControlFlow<BoundedForStmt> c2;
static addControlFlow<IfStmt> c3;
static addControlFlow<SwitchStmt> c4;
static addControlFlow<FunctionDef> c5;
static addControlFlow<CaseStmt> c6;
static addControlFlow<Code> c7;
static addControlFlow<Program> c8;
Literal* YPM::intLiteral(unsigned _value)
{
auto lit = new Literal();
lit->set_intval(_value);
return lit;
}
VarRef* YPM::varRef(unsigned _seed)
{
auto varref = new VarRef();
varref->set_varnum(_seed);
return varref;
}
Expression* YPM::refExpression(YulRandomNumGenerator& _rand)
{
auto refExpr = new Expression();
refExpr->set_allocated_varref(varRef(_rand()));
return refExpr;
}
Expression* YPM::litExpression(unsigned _value)
{
auto lit = intLiteral(_value);
auto expr = new Expression();
expr->set_allocated_cons(lit);
return expr;
}
template <typename T>
T YPM::EnumTypeConverter<T>::validEnum(unsigned _seed)
{
auto ret = static_cast<T>(_seed % (enumMax() - enumMin() + 1) + enumMin());
if constexpr (std::is_same_v<std::decay_t<T>, StoreFunc_Storage>)
yulAssert(StoreFunc_Storage_IsValid(ret), "Yul proto mutator: Invalid enum");
else if constexpr (std::is_same_v<std::decay_t<T>, NullaryOp_NOp>)
yulAssert(NullaryOp_NOp_IsValid(ret), "Yul proto mutator: Invalid enum");
else if constexpr (std::is_same_v<std::decay_t<T>, BinaryOp_BOp>)
yulAssert(BinaryOp_BOp_IsValid(ret), "Yul proto mutator: Invalid enum");
else if constexpr (std::is_same_v<std::decay_t<T>, UnaryOp_UOp>)
yulAssert(UnaryOp_UOp_IsValid(ret), "Yul proto mutator: Invalid enum");
else if constexpr (std::is_same_v<std::decay_t<T>, LowLevelCall_Type>)
yulAssert(LowLevelCall_Type_IsValid(ret), "Yul proto mutator: Invalid enum");
else if constexpr (std::is_same_v<std::decay_t<T>, Create_Type>)
yulAssert(Create_Type_IsValid(ret), "Yul proto mutator: Invalid enum");
else if constexpr (std::is_same_v<std::decay_t<T>, UnaryOpData_UOpData>)
yulAssert(UnaryOpData_UOpData_IsValid(ret), "Yul proto mutator: Invalid enum");
else
static_assert(AlwaysFalse<T>::value, "Yul proto mutator: non-exhaustive visitor.");
return ret;
}
template <typename T>
unsigned YPM::EnumTypeConverter<T>::enumMax()
{
if constexpr (std::is_same_v<std::decay_t<T>, StoreFunc_Storage>)
return StoreFunc_Storage_Storage_MAX;
else if constexpr (std::is_same_v<std::decay_t<T>, NullaryOp_NOp>)
return NullaryOp_NOp_NOp_MAX;
else if constexpr (std::is_same_v<std::decay_t<T>, BinaryOp_BOp>)
return BinaryOp_BOp_BOp_MAX;
else if constexpr (std::is_same_v<std::decay_t<T>, UnaryOp_UOp>)
return UnaryOp_UOp_UOp_MAX;
else if constexpr (std::is_same_v<std::decay_t<T>, LowLevelCall_Type>)
return LowLevelCall_Type_Type_MAX;
else if constexpr (std::is_same_v<std::decay_t<T>, Create_Type>)
return Create_Type_Type_MAX;
else if constexpr (std::is_same_v<std::decay_t<T>, UnaryOpData_UOpData>)
return UnaryOpData_UOpData_UOpData_MAX;
else
static_assert(AlwaysFalse<T>::value, "Yul proto mutator: non-exhaustive visitor.");
}
template <typename T>
unsigned YPM::EnumTypeConverter<T>::enumMin()
{
if constexpr (std::is_same_v<std::decay_t<T>, StoreFunc_Storage>)
return StoreFunc_Storage_Storage_MIN;
else if constexpr (std::is_same_v<std::decay_t<T>, NullaryOp_NOp>)
return NullaryOp_NOp_NOp_MIN;
else if constexpr (std::is_same_v<std::decay_t<T>, BinaryOp_BOp>)
return BinaryOp_BOp_BOp_MIN;
else if constexpr (std::is_same_v<std::decay_t<T>, UnaryOp_UOp>)
return UnaryOp_UOp_UOp_MIN;
else if constexpr (std::is_same_v<std::decay_t<T>, LowLevelCall_Type>)
return LowLevelCall_Type_Type_MIN;
else if constexpr (std::is_same_v<std::decay_t<T>, Create_Type>)
return Create_Type_Type_MIN;
else if constexpr (std::is_same_v<std::decay_t<T>, UnaryOpData_UOpData>)
return UnaryOpData_UOpData_UOpData_MIN;
else
static_assert(AlwaysFalse<T>::value, "Yul proto mutator: non-exhaustive visitor.");
}
template <typename T>
void YPM::addControlFlow(T* _msg, unsigned _seed)
{
enum class ControlFlowStmt: unsigned
{
For = 0,
BoundedFor,
If,
Switch,
FunctionCall,
Break,
Continue,
Leave,
Termination
};
std::uniform_int_distribution<unsigned> d(
static_cast<unsigned>(ControlFlowStmt::For),
static_cast<unsigned>(ControlFlowStmt::Termination)
);
YulRandomNumGenerator yrand(_seed);
auto random = static_cast<ControlFlowStmt>(d(yrand.m_random));
Statement* s = basicBlock(_msg, _seed)->add_statements();
switch (random)
{
case ControlFlowStmt::For:
s->set_allocated_forstmt(new ForStmt());
break;
case ControlFlowStmt::BoundedFor:
s->set_allocated_boundedforstmt(new BoundedForStmt());
break;
case ControlFlowStmt::If:
s->set_allocated_ifstmt(new IfStmt());
break;
case ControlFlowStmt::Switch:
s->set_allocated_switchstmt(new SwitchStmt());
break;
case ControlFlowStmt::FunctionCall:
s->set_allocated_functioncall(new FunctionCall());
break;
case ControlFlowStmt::Break:
s->set_allocated_breakstmt(new BreakStmt());
break;
case ControlFlowStmt::Continue:
s->set_allocated_contstmt(new ContinueStmt());
break;
case ControlFlowStmt::Leave:
s->set_allocated_leave(new LeaveStmt());
break;
case ControlFlowStmt::Termination:
s->set_allocated_terminatestmt(new TerminatingStmt());
break;
}
}
Block* YPM::randomBlock(ForStmt* _stmt, unsigned _seed)
{
enum class ForBlocks: unsigned
{
Init = 0,
Post = 1,
Body = 2
};
std::uniform_int_distribution<unsigned> d(
static_cast<unsigned>(ForBlocks::Init),
static_cast<unsigned>(ForBlocks::Body)
);
YulRandomNumGenerator yrand(_seed);
switch (static_cast<ForBlocks>(d(yrand.m_random)))
{
case ForBlocks::Init:
return _stmt->mutable_for_init();
case ForBlocks::Post:
return _stmt->mutable_for_post();
case ForBlocks::Body:
return _stmt->mutable_for_body();
}
}
template <typename T>
Block* YPM::basicBlock(T* _msg, unsigned _seed)
{
if constexpr (std::is_same_v<T, ForStmt>)
return randomBlock(_msg, _seed);
else if constexpr (std::is_same_v<T, BoundedForStmt>)
return _msg->mutable_for_body();
else if constexpr (std::is_same_v<T, SwitchStmt>)
return _msg->mutable_default_block();
else if constexpr (std::is_same_v<T, FunctionDef>)
return _msg->mutable_block();
else if constexpr (std::is_same_v<T, IfStmt>)
return _msg->mutable_if_body();
else if constexpr (std::is_same_v<T, CaseStmt>)
return _msg->mutable_case_block();
else if constexpr (std::is_same_v<T, Code>)
return _msg->mutable_block();
else if constexpr (std::is_same_v<T, Program>)
return globalBlock(_msg);
else
static_assert(AlwaysFalse<T>::value, "Yul proto mutator: non-exhaustive visitor.");
}
Block* YPM::globalBlock(Program* _program)
{
switch (_program->program_oneof_case())
{
case Program::kBlock:
return _program->mutable_block();
case Program::kObj:
return _program->mutable_obj()->mutable_code()->mutable_block();
case Program::PROGRAM_ONEOF_NOT_SET:
{
_program->set_allocated_block(new Block());
return _program->mutable_block();
}
}
}
| 8,607
|
C++
|
.cpp
| 263
| 30.51711
| 88
| 0.737715
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,932
|
Inspector.cpp
|
ethereum_solidity/test/tools/yulInterpreter/Inspector.cpp
|
/*
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
/**
* Yul interpreter.
*/
#include <test/tools/yulInterpreter/Inspector.h>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string.hpp>
using namespace solidity;
using namespace solidity::yul;
using namespace solidity::yul::test;
namespace
{
void printVariable(YulString const& _name, u256 const& _value)
{
std::cout << "\t" << _name.str() << " = " << _value.str();
if (_value != 0)
std::cout << " (" << toCompactHexWithPrefix(_value) << ")";
std::cout << std::endl;
}
}
void InspectedInterpreter::run(
std::shared_ptr<Inspector> _inspector,
InterpreterState& _state,
Dialect const& _dialect,
Block const& _ast,
bool _disableExternalCalls,
bool _disableMemoryTrace
)
{
Scope scope;
InspectedInterpreter{_inspector, _state, _dialect, scope, _disableExternalCalls, _disableMemoryTrace}(_ast);
}
Inspector::NodeAction Inspector::queryUser(langutil::DebugData const& _data, std::map<YulString, u256> const& _variables)
{
if (m_stepMode == NodeAction::RunNode)
{
// Output instructions that are being skipped/run
std::cout << "Running " << currentSource(_data) << std::endl;
return NodeAction::StepThroughNode;
}
std::string input;
while (true)
{
// Output sourcecode about to run.
std::cout << "> " << currentSource(_data) << std::endl;
// Ask user for action
std::cout << std::endl
<< "(s)tep/(n)ext/(i)nspect/(p)rint/all (v)ariables?"
<< std::endl
<< "# ";
std::cout.flush();
std::getline(std::cin, input);
boost::algorithm::trim(input);
// Imitate GDB and repeat last cmd for empty string input.
if (input == "")
input = m_lastInput;
else
m_lastInput = input;
if (input == "next" || input == "n")
return NodeAction::RunNode;
else if (input == "step" || input == "s")
return NodeAction::StepThroughNode;
else if (input == "inspect" || input == "i")
m_state.dumpTraceAndState(std::cout, false);
else if (input == "variables" || input == "v")
{
for (auto &&[yulStr, val]: _variables)
printVariable(yulStr, val);
std::cout << std::endl;
}
else if (
boost::starts_with(input, "print") ||
boost::starts_with(input, "p")
)
{
size_t whitespacePos = input.find(' ');
if (whitespacePos == std::string::npos)
std::cout << "Error parsing command! Expected variable name." << std::endl;
std::string const varname = input.substr(whitespacePos + 1);
std::vector<std::string> candidates;
bool found = false;
for (auto &&[yulStr, val]: _variables)
if (yulStr.str() == varname)
{
printVariable(yulStr, val);
found = true;
break;
}
if (!found)
std::cout << varname << " not found." << std::endl;
}
}
}
std::string Inspector::currentSource(langutil::DebugData const& _data) const
{
return m_source.substr(
static_cast<size_t>(_data.nativeLocation.start),
static_cast<size_t>(_data.nativeLocation.end - _data.nativeLocation.start)
);
}
u256 InspectedInterpreter::evaluate(Expression const& _expression)
{
InspectedExpressionEvaluator ev(m_inspector, m_state, m_dialect, *m_scope, m_variables, m_disableExternalCalls, m_disableMemoryTrace);
ev.visit(_expression);
return ev.value();
}
std::vector<u256> InspectedInterpreter::evaluateMulti(Expression const& _expression)
{
InspectedExpressionEvaluator ev(m_inspector, m_state, m_dialect, *m_scope, m_variables, m_disableExternalCalls, m_disableMemoryTrace);
ev.visit(_expression);
return ev.values();
}
| 4,141
|
C++
|
.cpp
| 125
| 30.4
| 135
| 0.709305
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,933
|
Interpreter.cpp
|
ethereum_solidity/test/tools/yulInterpreter/Interpreter.cpp
|
/*
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
/**
* Yul interpreter.
*/
#include <test/tools/yulInterpreter/Interpreter.h>
#include <test/tools/yulInterpreter/EVMInstructionInterpreter.h>
#include <libyul/AST.h>
#include <libyul/Dialect.h>
#include <libyul/Utilities.h>
#include <libyul/backends/evm/EVMDialect.h>
#include <liblangutil/Exceptions.h>
#include <libsolutil/FixedHash.h>
#include <range/v3/view/reverse.hpp>
#include <ostream>
#include <variant>
using namespace solidity;
using namespace solidity::yul;
using namespace solidity::yul::test;
using solidity::util::h256;
void InterpreterState::dumpStorage(std::ostream& _out) const
{
for (auto const& [slot, value]: storage)
if (value != h256{})
_out << " " << slot.hex() << ": " << value.hex() << std::endl;
}
void InterpreterState::dumpTransientStorage(std::ostream& _out) const
{
for (auto const& [slot, value]: transientStorage)
if (value != h256{})
_out << " " << slot.hex() << ": " << value.hex() << std::endl;
}
void InterpreterState::dumpTraceAndState(std::ostream& _out, bool _disableMemoryTrace) const
{
_out << "Trace:" << std::endl;
for (auto const& line: trace)
_out << " " << line << std::endl;
if (!_disableMemoryTrace)
{
_out << "Memory dump:\n";
std::map<u256, u256> words;
for (auto const& [offset, value]: memory)
words[(offset / 0x20) * 0x20] |= u256(uint32_t(value)) << (256 - 8 - 8 * static_cast<size_t>(offset % 0x20));
for (auto const& [offset, value]: words)
if (value != 0)
_out << " " << std::uppercase << std::hex << std::setw(4) << offset << ": " << h256(value).hex() << std::endl;
}
_out << "Storage dump:" << std::endl;
dumpStorage(_out);
_out << "Transient storage dump:" << std::endl;
dumpTransientStorage(_out);
if (!calldata.empty())
{
_out << "Calldata dump:";
for (size_t offset = 0; offset < calldata.size(); ++offset)
if (calldata[offset] != 0)
{
if (offset % 32 == 0)
_out <<
std::endl <<
" " <<
std::uppercase <<
std::hex <<
std::setfill(' ') <<
std::setw(4) <<
offset <<
": ";
_out <<
std::hex <<
std::setw(2) <<
std::setfill('0') <<
static_cast<int>(calldata[offset]);
}
_out << std::endl;
}
}
void Interpreter::run(
InterpreterState& _state,
Dialect const& _dialect,
Block const& _ast,
bool _disableExternalCalls,
bool _disableMemoryTrace
)
{
Scope scope;
Interpreter{_state, _dialect, scope, _disableExternalCalls, _disableMemoryTrace}(_ast);
}
void Interpreter::operator()(ExpressionStatement const& _expressionStatement)
{
evaluateMulti(_expressionStatement.expression);
}
void Interpreter::operator()(Assignment const& _assignment)
{
solAssert(_assignment.value, "");
std::vector<u256> values = evaluateMulti(*_assignment.value);
solAssert(values.size() == _assignment.variableNames.size(), "");
for (size_t i = 0; i < values.size(); ++i)
{
YulName varName = _assignment.variableNames.at(i).name;
solAssert(m_variables.count(varName), "");
m_variables[varName] = values.at(i);
}
}
void Interpreter::operator()(VariableDeclaration const& _declaration)
{
std::vector<u256> values(_declaration.variables.size(), 0);
if (_declaration.value)
values = evaluateMulti(*_declaration.value);
solAssert(values.size() == _declaration.variables.size(), "");
for (size_t i = 0; i < values.size(); ++i)
{
YulName varName = _declaration.variables.at(i).name;
solAssert(!m_variables.count(varName), "");
m_variables[varName] = values.at(i);
m_scope->names.emplace(varName, nullptr);
}
}
void Interpreter::operator()(If const& _if)
{
solAssert(_if.condition, "");
if (evaluate(*_if.condition) != 0)
(*this)(_if.body);
}
void Interpreter::operator()(Switch const& _switch)
{
solAssert(_switch.expression, "");
u256 val = evaluate(*_switch.expression);
solAssert(!_switch.cases.empty(), "");
for (auto const& c: _switch.cases)
// Default case has to be last.
if (!c.value || evaluate(*c.value) == val)
{
(*this)(c.body);
break;
}
}
void Interpreter::operator()(FunctionDefinition const&)
{
}
void Interpreter::operator()(ForLoop const& _forLoop)
{
solAssert(_forLoop.condition, "");
enterScope(_forLoop.pre);
ScopeGuard g([this]{ leaveScope(); });
for (auto const& statement: _forLoop.pre.statements)
{
visit(statement);
if (m_state.controlFlowState == ControlFlowState::Leave)
return;
}
while (evaluate(*_forLoop.condition) != 0)
{
// Increment step for each loop iteration for loops with
// an empty body and post blocks to prevent a deadlock.
if (_forLoop.body.statements.size() == 0 && _forLoop.post.statements.size() == 0)
incrementStep();
m_state.controlFlowState = ControlFlowState::Default;
(*this)(_forLoop.body);
if (m_state.controlFlowState == ControlFlowState::Break || m_state.controlFlowState == ControlFlowState::Leave)
break;
m_state.controlFlowState = ControlFlowState::Default;
(*this)(_forLoop.post);
if (m_state.controlFlowState == ControlFlowState::Leave)
break;
}
if (m_state.controlFlowState != ControlFlowState::Leave)
m_state.controlFlowState = ControlFlowState::Default;
}
void Interpreter::operator()(Break const&)
{
m_state.controlFlowState = ControlFlowState::Break;
}
void Interpreter::operator()(Continue const&)
{
m_state.controlFlowState = ControlFlowState::Continue;
}
void Interpreter::operator()(Leave const&)
{
m_state.controlFlowState = ControlFlowState::Leave;
}
void Interpreter::operator()(Block const& _block)
{
enterScope(_block);
// Register functions.
for (auto const& statement: _block.statements)
if (std::holds_alternative<FunctionDefinition>(statement))
{
FunctionDefinition const& funDef = std::get<FunctionDefinition>(statement);
m_scope->names.emplace(funDef.name, &funDef);
}
for (auto const& statement: _block.statements)
{
incrementStep();
visit(statement);
if (m_state.controlFlowState != ControlFlowState::Default)
break;
}
leaveScope();
}
u256 Interpreter::evaluate(Expression const& _expression)
{
ExpressionEvaluator ev(m_state, m_dialect, *m_scope, m_variables, m_disableExternalCalls, m_disableMemoryTrace);
ev.visit(_expression);
return ev.value();
}
std::vector<u256> Interpreter::evaluateMulti(Expression const& _expression)
{
ExpressionEvaluator ev(m_state, m_dialect, *m_scope, m_variables, m_disableExternalCalls, m_disableMemoryTrace);
ev.visit(_expression);
return ev.values();
}
void Interpreter::enterScope(Block const& _block)
{
if (!m_scope->subScopes.count(&_block))
m_scope->subScopes[&_block] = std::make_unique<Scope>(Scope{
{},
{},
m_scope
});
m_scope = m_scope->subScopes[&_block].get();
}
void Interpreter::leaveScope()
{
for (auto const& [var, funDeclaration]: m_scope->names)
if (!funDeclaration)
m_variables.erase(var);
m_scope = m_scope->parent;
yulAssert(m_scope, "");
}
void Interpreter::incrementStep()
{
m_state.numSteps++;
if (m_state.maxSteps > 0 && m_state.numSteps >= m_state.maxSteps)
{
m_state.trace.emplace_back("Interpreter execution step limit reached.");
BOOST_THROW_EXCEPTION(StepLimitReached());
}
}
void ExpressionEvaluator::operator()(Literal const& _literal)
{
incrementStep();
setValue(_literal.value.value());
}
void ExpressionEvaluator::operator()(Identifier const& _identifier)
{
solAssert(m_variables.count(_identifier.name), "");
incrementStep();
setValue(m_variables.at(_identifier.name));
}
void ExpressionEvaluator::operator()(FunctionCall const& _funCall)
{
std::vector<std::optional<LiteralKind>> const* literalArguments = nullptr;
if (std::optional<BuiltinHandle> builtinHandle = m_dialect.findBuiltin(_funCall.functionName.name.str()))
if (
auto const& args = m_dialect.builtin(*builtinHandle).literalArguments;
!args.empty()
)
literalArguments = &args;
evaluateArgs(_funCall.arguments, literalArguments);
if (EVMDialect const* dialect = dynamic_cast<EVMDialect const*>(&m_dialect))
{
if (std::optional<BuiltinHandle> builtinHandle = dialect->findBuiltin(_funCall.functionName.name.str()))
{
auto const& fun = dialect->builtin(*builtinHandle);
EVMInstructionInterpreter interpreter(dialect->evmVersion(), m_state, m_disableMemoryTrace);
u256 const value = interpreter.evalBuiltin(fun, _funCall.arguments, values());
if (
!m_disableExternalCalls &&
fun.instruction &&
evmasm::isCallInstruction(*fun.instruction)
)
runExternalCall(*fun.instruction);
setValue(value);
return;
}
}
Scope* scope = &m_scope;
for (; scope; scope = scope->parent)
if (scope->names.count(_funCall.functionName.name))
break;
yulAssert(scope, "");
FunctionDefinition const* fun = scope->names.at(_funCall.functionName.name);
yulAssert(fun, "Function not found.");
yulAssert(m_values.size() == fun->parameters.size(), "");
std::map<YulName, u256> variables;
for (size_t i = 0; i < fun->parameters.size(); ++i)
variables[fun->parameters.at(i).name] = m_values.at(i);
for (size_t i = 0; i < fun->returnVariables.size(); ++i)
variables[fun->returnVariables.at(i).name] = 0;
m_state.controlFlowState = ControlFlowState::Default;
std::unique_ptr<Interpreter> interpreter = makeInterpreterCopy(std::move(variables));
(*interpreter)(fun->body);
m_state.controlFlowState = ControlFlowState::Default;
m_values.clear();
for (auto const& retVar: fun->returnVariables)
m_values.emplace_back(interpreter->valueOfVariable(retVar.name));
}
u256 ExpressionEvaluator::value() const
{
solAssert(m_values.size() == 1, "");
return m_values.front();
}
void ExpressionEvaluator::setValue(u256 _value)
{
m_values.clear();
m_values.emplace_back(std::move(_value));
}
void ExpressionEvaluator::evaluateArgs(
std::vector<Expression> const& _expr,
std::vector<std::optional<LiteralKind>> const* _literalArguments
)
{
incrementStep();
std::vector<u256> values;
size_t i = 0;
/// Function arguments are evaluated in reverse.
for (auto const& expr: _expr | ranges::views::reverse)
{
if (!_literalArguments || !_literalArguments->at(_expr.size() - i - 1))
visit(expr);
else
{
if (std::get<Literal>(expr).value.unlimited())
{
yulAssert(std::get<Literal>(expr).kind == LiteralKind::String);
m_values = {0xdeadbeef};
}
else
m_values = {std::get<Literal>(expr).value.value()};
}
values.push_back(value());
++i;
}
m_values = std::move(values);
std::reverse(m_values.begin(), m_values.end());
}
void ExpressionEvaluator::incrementStep()
{
m_nestingLevel++;
if (m_state.maxExprNesting > 0 && m_nestingLevel > m_state.maxExprNesting)
{
m_state.trace.emplace_back("Maximum expression nesting level reached.");
BOOST_THROW_EXCEPTION(ExpressionNestingLimitReached());
}
}
void ExpressionEvaluator::runExternalCall(evmasm::Instruction _instruction)
{
u256 memOutOffset = 0;
u256 memOutSize = 0;
u256 callvalue = 0;
u256 memInOffset = 0;
u256 memInSize = 0;
// Setup memOut* values
if (
_instruction == evmasm::Instruction::CALL ||
_instruction == evmasm::Instruction::CALLCODE
)
{
memOutOffset = values()[5];
memOutSize = values()[6];
callvalue = values()[2];
memInOffset = values()[3];
memInSize = values()[4];
}
else if (
_instruction == evmasm::Instruction::DELEGATECALL ||
_instruction == evmasm::Instruction::STATICCALL
)
{
memOutOffset = values()[4];
memOutSize = values()[5];
memInOffset = values()[2];
memInSize = values()[3];
}
else
yulAssert(false);
// Don't execute external call if it isn't our own address
if (values()[1] != util::h160::Arith(m_state.address))
return;
Scope tmpScope;
InterpreterState tmpState;
tmpState.calldata = m_state.readMemory(memInOffset, memInSize);
tmpState.callvalue = callvalue;
tmpState.numInstance = m_state.numInstance + 1;
yulAssert(tmpState.numInstance < 1024, "Detected more than 1024 recursive calls, aborting...");
// Create new interpreter for the called contract
std::unique_ptr<Interpreter> newInterpreter = makeInterpreterNew(tmpState, tmpScope);
Scope* abstractRootScope = &m_scope;
Scope* fileScope = nullptr;
Block const* ast = nullptr;
// Find file scope
while (abstractRootScope->parent)
{
fileScope = abstractRootScope;
abstractRootScope = abstractRootScope->parent;
}
// Get AST for file scope
for (auto&& [block, scope]: abstractRootScope->subScopes)
if (scope.get() == fileScope)
{
ast = block;
break;
}
yulAssert(ast);
try
{
(*newInterpreter)(*ast);
}
catch (ExplicitlyTerminatedWithReturn const&)
{
// Copy return data to our memory
copyZeroExtended(
m_state.memory,
newInterpreter->returnData(),
memOutOffset.convert_to<size_t>(),
0,
memOutSize.convert_to<size_t>()
);
m_state.returndata = newInterpreter->returnData();
}
}
| 13,416
|
C++
|
.cpp
| 433
| 28.452656
| 115
| 0.716543
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,934
|
EVMInstructionInterpreter.cpp
|
ethereum_solidity/test/tools/yulInterpreter/EVMInstructionInterpreter.cpp
|
/*
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
/**
* Yul interpreter module that evaluates EVM instructions.
*/
#include <test/tools/yulInterpreter/EVMInstructionInterpreter.h>
#include <test/tools/yulInterpreter/Interpreter.h>
#include <libyul/backends/evm/EVMDialect.h>
#include <libyul/AST.h>
#include <libyul/Utilities.h>
#include <libevmasm/Instruction.h>
#include <libevmasm/SemanticInformation.h>
#include <liblangutil/Exceptions.h>
#include <libsolutil/Keccak256.h>
#include <libsolutil/Numeric.h>
#include <libsolutil/picosha2.h>
#include <limits>
using namespace solidity;
using namespace solidity::evmasm;
using namespace solidity::yul;
using namespace solidity::yul::test;
using solidity::util::h160;
using solidity::util::h256;
using solidity::util::keccak256;
namespace
{
/// Reads 32 bytes from @a _data at position @a _offset bytes while
/// interpreting @a _data to be padded with an infinite number of zero
/// bytes beyond its end.
u256 readZeroExtended(bytes const& _data, u256 const& _offset)
{
if (_offset >= _data.size())
return 0;
else if (_offset + 32 <= _data.size())
return *reinterpret_cast<h256 const*>(_data.data() + static_cast<size_t>(_offset));
else
{
size_t off = static_cast<size_t>(_offset);
u256 val;
for (size_t i = 0; i < 32; ++i)
{
val <<= 8;
if (off + i < _data.size())
val += _data[off + i];
}
return val;
}
}
}
namespace solidity::yul::test
{
void copyZeroExtended(
std::map<u256, uint8_t>& _target,
bytes const& _source,
size_t _targetOffset,
size_t _sourceOffset,
size_t _size
)
{
for (size_t i = 0; i < _size; ++i)
_target[_targetOffset + i] = (_sourceOffset + i < _source.size() ? _source[_sourceOffset + i] : 0);
}
void copyZeroExtendedWithOverlap(
std::map<u256, uint8_t>& _target,
std::map<u256, uint8_t> const& _source,
size_t _targetOffset,
size_t _sourceOffset,
size_t _size
)
{
if (_targetOffset >= _sourceOffset)
for (size_t i = _size; i > 0; --i)
_target[_targetOffset + i - 1] = (_source.count(_sourceOffset + i - 1) != 0 ? _source.at(_sourceOffset + i - 1) : 0);
else
for (size_t i = 0; i < _size; ++i)
_target[_targetOffset + i] = (_source.count(_sourceOffset + i) != 0 ? _source.at(_sourceOffset + i) : 0);
}
}
u256 EVMInstructionInterpreter::eval(
evmasm::Instruction _instruction,
std::vector<u256> const& _arguments
)
{
using namespace solidity::evmasm;
using evmasm::Instruction;
auto info = instructionInfo(_instruction, m_evmVersion);
yulAssert(static_cast<size_t>(info.args) == _arguments.size(), "");
auto const& arg = _arguments;
switch (_instruction)
{
case Instruction::STOP:
logTrace(_instruction);
BOOST_THROW_EXCEPTION(ExplicitlyTerminated());
// --------------- arithmetic ---------------
case Instruction::ADD:
return arg[0] + arg[1];
case Instruction::MUL:
return arg[0] * arg[1];
case Instruction::SUB:
return arg[0] - arg[1];
case Instruction::DIV:
return arg[1] == 0 ? 0 : arg[0] / arg[1];
case Instruction::SDIV:
return arg[1] == 0 ? 0 : s2u(u2s(arg[0]) / u2s(arg[1]));
case Instruction::MOD:
return arg[1] == 0 ? 0 : arg[0] % arg[1];
case Instruction::SMOD:
return arg[1] == 0 ? 0 : s2u(u2s(arg[0]) % u2s(arg[1]));
case Instruction::EXP:
return exp256(arg[0], arg[1]);
case Instruction::NOT:
return ~arg[0];
case Instruction::LT:
return arg[0] < arg[1] ? 1 : 0;
case Instruction::GT:
return arg[0] > arg[1] ? 1 : 0;
case Instruction::SLT:
return u2s(arg[0]) < u2s(arg[1]) ? 1 : 0;
case Instruction::SGT:
return u2s(arg[0]) > u2s(arg[1]) ? 1 : 0;
case Instruction::EQ:
return arg[0] == arg[1] ? 1 : 0;
case Instruction::ISZERO:
return arg[0] == 0 ? 1 : 0;
case Instruction::AND:
return arg[0] & arg[1];
case Instruction::OR:
return arg[0] | arg[1];
case Instruction::XOR:
return arg[0] ^ arg[1];
case Instruction::BYTE:
return arg[0] >= 32 ? 0 : (arg[1] >> unsigned(8 * (31 - arg[0]))) & 0xff;
case Instruction::SHL:
return arg[0] > 255 ? 0 : (arg[1] << unsigned(arg[0]));
case Instruction::SHR:
return arg[0] > 255 ? 0 : (arg[1] >> unsigned(arg[0]));
case Instruction::SAR:
{
static u256 const hibit = u256(1) << 255;
if (arg[0] >= 256)
return arg[1] & hibit ? u256(-1) : 0;
else
{
unsigned amount = unsigned(arg[0]);
u256 v = arg[1] >> amount;
if (arg[1] & hibit)
v |= u256(-1) << (256 - amount);
return v;
}
}
case Instruction::ADDMOD:
return arg[2] == 0 ? 0 : u256((u512(arg[0]) + u512(arg[1])) % arg[2]);
case Instruction::MULMOD:
return arg[2] == 0 ? 0 : u256((u512(arg[0]) * u512(arg[1])) % arg[2]);
case Instruction::SIGNEXTEND:
if (arg[0] >= 31)
return arg[1];
else
{
unsigned testBit = unsigned(arg[0]) * 8 + 7;
u256 ret = arg[1];
u256 mask = ((u256(1) << testBit) - 1);
if (boost::multiprecision::bit_test(ret, testBit))
ret |= ~mask;
else
ret &= mask;
return ret;
}
// --------------- blockchain stuff ---------------
case Instruction::KECCAK256:
{
if (!accessMemory(arg[0], arg[1]))
return u256("0x1234cafe1234cafe1234cafe") + arg[0];
uint64_t offset = uint64_t(arg[0] & uint64_t(-1));
uint64_t size = uint64_t(arg[1] & uint64_t(-1));
return u256(keccak256(m_state.readMemory(offset, size)));
}
case Instruction::ADDRESS:
return h256(m_state.address, h256::AlignRight);
case Instruction::BALANCE:
if (arg[0] == h256(m_state.address, h256::AlignRight))
return m_state.selfbalance;
else
return m_state.balance;
case Instruction::SELFBALANCE:
return m_state.selfbalance;
case Instruction::ORIGIN:
return h256(m_state.origin, h256::AlignRight);
case Instruction::CALLER:
return h256(m_state.caller, h256::AlignRight);
case Instruction::CALLVALUE:
return m_state.callvalue;
case Instruction::CALLDATALOAD:
return readZeroExtended(m_state.calldata, arg[0]);
case Instruction::CALLDATASIZE:
return m_state.calldata.size();
case Instruction::CALLDATACOPY:
if (accessMemory(arg[0], arg[2]))
copyZeroExtended(
m_state.memory, m_state.calldata,
size_t(arg[0]), size_t(arg[1]), size_t(arg[2])
);
logTrace(_instruction, arg);
return 0;
case Instruction::CODESIZE:
return m_state.code.size();
case Instruction::CODECOPY:
if (accessMemory(arg[0], arg[2]))
copyZeroExtended(
m_state.memory, m_state.code,
size_t(arg[0]), size_t(arg[1]), size_t(arg[2])
);
logTrace(_instruction, arg);
return 0;
case Instruction::GASPRICE:
return m_state.gasprice;
case Instruction::CHAINID:
return m_state.chainid;
case Instruction::BASEFEE:
return m_state.basefee;
case Instruction::BLOBHASH:
return blobHash(arg[0]);
case Instruction::BLOBBASEFEE:
return m_state.blobbasefee;
case Instruction::EXTCODESIZE:
return u256(keccak256(h256(arg[0]))) & 0xffffff;
case Instruction::EXTCODEHASH:
return u256(keccak256(h256(arg[0] + 1)));
case Instruction::EXTCODECOPY:
if (accessMemory(arg[1], arg[3]))
// TODO this way extcodecopy and codecopy do the same thing.
copyZeroExtended(
m_state.memory, m_state.code,
size_t(arg[1]), size_t(arg[2]), size_t(arg[3])
);
logTrace(_instruction, arg);
return 0;
case Instruction::RETURNDATASIZE:
return m_state.returndata.size();
case Instruction::RETURNDATACOPY:
if (accessMemory(arg[0], arg[2]))
copyZeroExtended(
m_state.memory, m_state.returndata,
size_t(arg[0]), size_t(arg[1]), size_t(arg[2])
);
logTrace(_instruction, arg);
return 0;
case Instruction::MCOPY:
if (accessMemory(arg[1], arg[2]) && accessMemory(arg[0], arg[2]))
copyZeroExtendedWithOverlap(
m_state.memory,
m_state.memory,
static_cast<size_t>(arg[0]),
static_cast<size_t>(arg[1]),
static_cast<size_t>(arg[2])
);
logTrace(_instruction, arg);
return 0;
case Instruction::BLOCKHASH:
if (arg[0] >= m_state.blockNumber || arg[0] + 256 < m_state.blockNumber)
return 0;
else
return 0xaaaaaaaa + (arg[0] - m_state.blockNumber - 256);
case Instruction::COINBASE:
return h256(m_state.coinbase, h256::AlignRight);
case Instruction::TIMESTAMP:
return m_state.timestamp;
case Instruction::NUMBER:
return m_state.blockNumber;
case Instruction::PREVRANDAO:
return (m_evmVersion < langutil::EVMVersion::paris()) ? m_state.difficulty : m_state.prevrandao;
case Instruction::GASLIMIT:
return m_state.gaslimit;
// --------------- memory / storage / logs ---------------
case Instruction::MLOAD:
accessMemory(arg[0], 0x20);
return readMemoryWord(arg[0]);
case Instruction::MSTORE:
accessMemory(arg[0], 0x20);
writeMemoryWord(arg[0], arg[1]);
return 0;
case Instruction::MSTORE8:
accessMemory(arg[0], 1);
m_state.memory[arg[0]] = uint8_t(arg[1] & 0xff);
return 0;
case Instruction::SLOAD:
return m_state.storage[h256(arg[0])];
case Instruction::SSTORE:
m_state.storage[h256(arg[0])] = h256(arg[1]);
return 0;
case Instruction::PC:
return 0x77;
case Instruction::MSIZE:
return m_state.msize;
case Instruction::GAS:
return 0x99;
case Instruction::LOG0:
accessMemory(arg[0], arg[1]);
logTrace(_instruction, arg);
return 0;
case Instruction::LOG1:
accessMemory(arg[0], arg[1]);
logTrace(_instruction, arg);
return 0;
case Instruction::LOG2:
accessMemory(arg[0], arg[1]);
logTrace(_instruction, arg);
return 0;
case Instruction::LOG3:
accessMemory(arg[0], arg[1]);
logTrace(_instruction, arg);
return 0;
case Instruction::LOG4:
accessMemory(arg[0], arg[1]);
logTrace(_instruction, arg);
return 0;
case Instruction::TLOAD:
return m_state.transientStorage[h256(arg[0])];
case Instruction::TSTORE:
m_state.transientStorage[h256(arg[0])] = h256(arg[1]);
return 0;
// --------------- calls ---------------
case Instruction::CREATE:
accessMemory(arg[1], arg[2]);
logTrace(_instruction, arg);
if (arg[2] != 0)
return (0xcccccc + arg[1]) & u256("0xffffffffffffffffffffffffffffffffffffffff");
else
return 0xcccccc;
case Instruction::CREATE2:
accessMemory(arg[1], arg[2]);
logTrace(_instruction, arg);
if (arg[2] != 0)
return (0xdddddd + arg[1]) & u256("0xffffffffffffffffffffffffffffffffffffffff");
else
return 0xdddddd;
case Instruction::CALL:
case Instruction::CALLCODE:
accessMemory(arg[3], arg[4]);
accessMemory(arg[5], arg[6]);
logTrace(_instruction, arg);
// Randomly fail based on the called address if it isn't a call to self.
// Used for fuzzing.
return (
(arg[0] > 0) &&
(arg[1] == util::h160::Arith(m_state.address) || (arg[1] & 1))
) ? 1 : 0;
case Instruction::DELEGATECALL:
case Instruction::STATICCALL:
accessMemory(arg[2], arg[3]);
accessMemory(arg[4], arg[5]);
logTrace(_instruction, arg);
// Randomly fail based on the called address if it isn't a call to self.
// Used for fuzzing.
return (
(arg[0] > 0) &&
(arg[1] == util::h160::Arith(m_state.address) || (arg[1] & 1))
) ? 1 : 0;
case Instruction::RETURN:
{
m_state.returndata = {};
if (accessMemory(arg[0], arg[1]))
m_state.returndata = m_state.readMemory(arg[0], arg[1]);
logTrace(_instruction, arg, m_state.returndata);
BOOST_THROW_EXCEPTION(ExplicitlyTerminatedWithReturn());
}
case Instruction::REVERT:
accessMemory(arg[0], arg[1]);
logTrace(_instruction, arg);
m_state.storage.clear();
m_state.transientStorage.clear();
BOOST_THROW_EXCEPTION(ExplicitlyTerminated());
case Instruction::INVALID:
logTrace(_instruction);
m_state.storage.clear();
m_state.transientStorage.clear();
m_state.trace.clear();
BOOST_THROW_EXCEPTION(ExplicitlyTerminated());
case Instruction::SELFDESTRUCT:
logTrace(_instruction, arg);
m_state.storage.clear();
m_state.transientStorage.clear();
m_state.trace.clear();
BOOST_THROW_EXCEPTION(ExplicitlyTerminated());
case Instruction::POP:
return 0;
// --------------- invalid in strict assembly ---------------
case Instruction::JUMP:
case Instruction::JUMPI:
case Instruction::JUMPDEST:
case Instruction::PUSH0:
case Instruction::PUSH1:
case Instruction::PUSH2:
case Instruction::PUSH3:
case Instruction::PUSH4:
case Instruction::PUSH5:
case Instruction::PUSH6:
case Instruction::PUSH7:
case Instruction::PUSH8:
case Instruction::PUSH9:
case Instruction::PUSH10:
case Instruction::PUSH11:
case Instruction::PUSH12:
case Instruction::PUSH13:
case Instruction::PUSH14:
case Instruction::PUSH15:
case Instruction::PUSH16:
case Instruction::PUSH17:
case Instruction::PUSH18:
case Instruction::PUSH19:
case Instruction::PUSH20:
case Instruction::PUSH21:
case Instruction::PUSH22:
case Instruction::PUSH23:
case Instruction::PUSH24:
case Instruction::PUSH25:
case Instruction::PUSH26:
case Instruction::PUSH27:
case Instruction::PUSH28:
case Instruction::PUSH29:
case Instruction::PUSH30:
case Instruction::PUSH31:
case Instruction::PUSH32:
case Instruction::DUP1:
case Instruction::DUP2:
case Instruction::DUP3:
case Instruction::DUP4:
case Instruction::DUP5:
case Instruction::DUP6:
case Instruction::DUP7:
case Instruction::DUP8:
case Instruction::DUP9:
case Instruction::DUP10:
case Instruction::DUP11:
case Instruction::DUP12:
case Instruction::DUP13:
case Instruction::DUP14:
case Instruction::DUP15:
case Instruction::DUP16:
case Instruction::SWAP1:
case Instruction::SWAP2:
case Instruction::SWAP3:
case Instruction::SWAP4:
case Instruction::SWAP5:
case Instruction::SWAP6:
case Instruction::SWAP7:
case Instruction::SWAP8:
case Instruction::SWAP9:
case Instruction::SWAP10:
case Instruction::SWAP11:
case Instruction::SWAP12:
case Instruction::SWAP13:
case Instruction::SWAP14:
case Instruction::SWAP15:
case Instruction::SWAP16:
yulAssert(false, "Impossible in strict assembly.");
case Instruction::DATALOADN:
case Instruction::EOFCREATE:
case Instruction::RETURNCONTRACT:
solUnimplemented("EOF not yet supported by Yul interpreter.");
}
util::unreachable();
}
u256 EVMInstructionInterpreter::evalBuiltin(
BuiltinFunctionForEVM const& _fun,
std::vector<Expression> const& _arguments,
std::vector<u256> const& _evaluatedArguments
)
{
if (_fun.instruction)
return eval(*_fun.instruction, _evaluatedArguments);
std::string const& fun = _fun.name;
// Evaluate datasize/offset/copy instructions
if (fun == "datasize" || fun == "dataoffset")
{
std::string arg = formatLiteral(std::get<Literal>(_arguments.at(0)));
if (arg.length() < 32)
arg.resize(32, 0);
if (fun == "datasize")
return u256(keccak256(arg)) & 0xfff;
else
{
// Force different value than for datasize
arg[31]++;
arg[31]++;
return u256(keccak256(arg)) & 0xfff;
}
}
else if (fun == "datacopy")
{
// This is identical to codecopy.
if (
_evaluatedArguments.at(2) != 0 &&
accessMemory(_evaluatedArguments.at(0), _evaluatedArguments.at(2))
)
copyZeroExtended(
m_state.memory,
m_state.code,
size_t(_evaluatedArguments.at(0)),
size_t(_evaluatedArguments.at(1) & std::numeric_limits<size_t>::max()),
size_t(_evaluatedArguments.at(2))
);
return 0;
}
else if (fun == "memoryguard")
return _evaluatedArguments.at(0);
else
yulAssert(false, "Unknown builtin: " + fun);
return 0;
}
bool EVMInstructionInterpreter::accessMemory(u256 const& _offset, u256 const& _size)
{
if (_size == 0)
return true;
if (_offset <= (_offset + _size) && (_offset + _size) <= (_offset + _size + 0x1f))
{
u256 newMSize = (_offset + _size + 0x1f) & ~u256(0x1f);
m_state.msize = std::max(m_state.msize, newMSize);
// We only record accesses to contiguous memory chunks that are at most s_maxRangeSize bytes
// in size and at an offset of at most numeric_limits<size_t>::max() - s_maxRangeSize
return _size <= s_maxRangeSize && _offset <= u256(std::numeric_limits<size_t>::max() - s_maxRangeSize);
}
m_state.msize = u256(-1);
return false;
}
bytes EVMInstructionInterpreter::readMemory(u256 const& _offset, u256 const& _size)
{
yulAssert(_size <= s_maxRangeSize, "Too large read.");
bytes data(size_t(_size), uint8_t(0));
for (size_t i = 0; i < data.size(); ++i)
data[i] = m_state.memory[_offset + i];
return data;
}
u256 EVMInstructionInterpreter::readMemoryWord(u256 const& _offset)
{
return u256(h256(m_state.readMemory(_offset, 32)));
}
void EVMInstructionInterpreter::writeMemoryWord(u256 const& _offset, u256 const& _value)
{
for (size_t i = 0; i < 32; i++)
m_state.memory[_offset + i] = uint8_t((_value >> (8 * (31 - i))) & 0xff);
}
void EVMInstructionInterpreter::logTrace(
evmasm::Instruction _instruction,
std::vector<u256> const& _arguments,
bytes const& _data
)
{
logTrace(
evmasm::instructionInfo(_instruction, m_evmVersion).name,
SemanticInformation::memory(_instruction) == SemanticInformation::Effect::Write,
_arguments,
_data
);
}
void EVMInstructionInterpreter::logTrace(
std::string const& _pseudoInstruction,
bool _writesToMemory,
std::vector<u256> const& _arguments,
bytes const& _data
)
{
if (!(_writesToMemory && memWriteTracingDisabled()))
{
std::string message = _pseudoInstruction + "(";
std::pair<bool, size_t> inputMemoryPtrModified = isInputMemoryPtrModified(_pseudoInstruction, _arguments);
for (size_t i = 0; i < _arguments.size(); ++i)
{
bool printZero = inputMemoryPtrModified.first && inputMemoryPtrModified.second == i;
u256 arg = printZero ? 0 : _arguments[i];
message += (i > 0 ? ", " : "") + formatNumber(arg);
}
message += ")";
if (!_data.empty())
message += " [" + util::toHex(_data) + "]";
m_state.trace.emplace_back(std::move(message));
if (m_state.maxTraceSize > 0 && m_state.trace.size() >= m_state.maxTraceSize)
{
m_state.trace.emplace_back("Trace size limit reached.");
BOOST_THROW_EXCEPTION(TraceLimitReached());
}
}
}
std::pair<bool, size_t> EVMInstructionInterpreter::isInputMemoryPtrModified(
std::string const& _pseudoInstruction,
std::vector<u256> const& _arguments
)
{
if (_pseudoInstruction == "RETURN" || _pseudoInstruction == "REVERT")
{
if (_arguments[1] == 0)
return {true, 0};
else
return {false, 0};
}
else if (
_pseudoInstruction == "RETURNDATACOPY" || _pseudoInstruction == "CALLDATACOPY"
|| _pseudoInstruction == "CODECOPY")
{
if (_arguments[2] == 0)
return {true, 0};
else
return {false, 0};
}
else if (_pseudoInstruction == "EXTCODECOPY")
{
if (_arguments[3] == 0)
return {true, 1};
else
return {false, 0};
}
else if (
_pseudoInstruction == "LOG0" || _pseudoInstruction == "LOG1" || _pseudoInstruction == "LOG2"
|| _pseudoInstruction == "LOG3" || _pseudoInstruction == "LOG4")
{
if (_arguments[1] == 0)
return {true, 0};
else
return {false, 0};
}
if (_pseudoInstruction == "CREATE" || _pseudoInstruction == "CREATE2")
{
if (_arguments[2] == 0)
return {true, 1};
else
return {false, 0};
}
if (_pseudoInstruction == "CALL" || _pseudoInstruction == "CALLCODE")
{
if (_arguments[4] == 0)
return {true, 3};
else
return {false, 0};
}
else if (_pseudoInstruction == "DELEGATECALL" || _pseudoInstruction == "STATICCALL")
{
if (_arguments[3] == 0)
return {true, 2};
else
return {false, 0};
}
else
return {false, 0};
}
h256 EVMInstructionInterpreter::blobHash(u256 const& _index)
{
yulAssert(m_evmVersion.hasBlobHash());
if (_index >= m_state.blobCommitments.size())
return util::FixedHash<32>{};
h256 hashedCommitment = h256(picosha2::hash256(toBigEndian(m_state.blobCommitments[static_cast<size_t>(_index)])));
yulAssert(m_state.blobHashVersion.size == 1);
hashedCommitment[0] = *m_state.blobHashVersion.data();
yulAssert(hashedCommitment.size == 32);
return hashedCommitment;
}
| 20,163
|
C++
|
.cpp
| 667
| 27.647676
| 120
| 0.698648
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,935
|
Common.cpp
|
ethereum_solidity/test/yulPhaser/Common.cpp
|
/*
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
#include <test/yulPhaser/TestHelpers.h>
#include <tools/yulPhaser/Common.h>
#include <libsolutil/CommonData.h>
#include <libsolutil/TemporaryDirectory.h>
#include <boost/test/unit_test.hpp>
#include <boost/test/tools/output_test_stream.hpp>
#include <fstream>
#include <sstream>
#include <string>
using namespace boost::test_tools;
using namespace solidity::util;
namespace solidity::phaser::test
{
class ReadLinesFromFileFixture
{
protected:
TemporaryDirectory m_tempDir;
};
namespace
{
enum class TestEnum
{
A,
B,
AB,
CD,
EF,
GH,
};
std::map<TestEnum, std::string> const TestEnumToStringMap =
{
{TestEnum::A, "a"},
{TestEnum::B, "b"},
{TestEnum::AB, "a b"},
{TestEnum::CD, "c-d"},
{TestEnum::EF, "e f"},
};
std::map<std::string, TestEnum> const StringToTestEnumMap = invertMap(TestEnumToStringMap);
}
BOOST_AUTO_TEST_SUITE(Phaser, *boost::unit_test::label("nooptions"))
BOOST_AUTO_TEST_SUITE(CommonTest)
BOOST_FIXTURE_TEST_CASE(readLinesFromFile_should_return_all_lines_from_a_text_file_as_strings_without_newlines, ReadLinesFromFileFixture)
{
{
std::ofstream tmpFile((m_tempDir.path() / "test-file.txt").string());
tmpFile << std::endl << "Line 1" << std::endl << std::endl << std::endl << "Line 2" << std::endl << "#" << std::endl << std::endl;
}
std::vector<std::string> lines = readLinesFromFile((m_tempDir.path() / "test-file.txt").string());
BOOST_TEST((lines == std::vector<std::string>{"", "Line 1", "", "", "Line 2", "#", ""}));
}
BOOST_AUTO_TEST_CASE(deserializeChoice_should_convert_string_to_enum)
{
std::istringstream aStream("a");
TestEnum aResult;
deserializeChoice(aStream, aResult, StringToTestEnumMap);
BOOST_CHECK(aResult == TestEnum::A);
BOOST_TEST(!aStream.fail());
std::istringstream bStream("b");
TestEnum bResult;
deserializeChoice(bStream, bResult, StringToTestEnumMap);
BOOST_CHECK(bResult == TestEnum::B);
BOOST_TEST(!bStream.fail());
std::istringstream cdStream("c-d");
TestEnum cdResult;
deserializeChoice(cdStream, cdResult, StringToTestEnumMap);
BOOST_CHECK(cdResult == TestEnum::CD);
BOOST_TEST(!cdStream.fail());
}
BOOST_AUTO_TEST_CASE(deserializeChoice_should_set_failbit_if_there_is_no_enum_corresponding_to_string)
{
std::istringstream xyzStream("xyz");
TestEnum xyzResult;
deserializeChoice(xyzStream, xyzResult, StringToTestEnumMap);
BOOST_TEST(xyzStream.fail());
}
BOOST_AUTO_TEST_CASE(deserializeChoice_does_not_have_to_support_strings_with_spaces)
{
std::istringstream abStream("a b");
TestEnum abResult;
deserializeChoice(abStream, abResult, StringToTestEnumMap);
BOOST_CHECK(abResult == TestEnum::A);
BOOST_TEST(!abStream.fail());
std::istringstream efStream("e f");
TestEnum efResult;
deserializeChoice(efStream, efResult, StringToTestEnumMap);
BOOST_TEST(efStream.fail());
}
BOOST_AUTO_TEST_CASE(serializeChoice_should_convert_enum_to_string)
{
output_test_stream output;
serializeChoice(output, TestEnum::A, TestEnumToStringMap);
BOOST_CHECK(output.is_equal("a"));
BOOST_TEST(!output.fail());
serializeChoice(output, TestEnum::AB, TestEnumToStringMap);
BOOST_CHECK(output.is_equal("a b"));
BOOST_TEST(!output.fail());
}
BOOST_AUTO_TEST_CASE(serializeChoice_should_set_failbit_if_there_is_no_string_corresponding_to_enum)
{
output_test_stream output;
serializeChoice(output, TestEnum::GH, TestEnumToStringMap);
BOOST_TEST(output.fail());
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
}
| 4,115
|
C++
|
.cpp
| 120
| 32.466667
| 137
| 0.763682
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,936
|
TestHelpersTest.cpp
|
ethereum_solidity/test/yulPhaser/TestHelpersTest.cpp
|
/*
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
#include <test/yulPhaser/TestHelpers.h>
#include <libyul/optimiser/Suite.h>
#include <boost/test/unit_test.hpp>
#include <set>
using namespace solidity::yul;
using namespace boost::test_tools;
namespace solidity::phaser::test
{
BOOST_AUTO_TEST_SUITE(Phaser, *boost::unit_test::label("nooptions"))
BOOST_AUTO_TEST_SUITE(TestHelpersTest)
BOOST_AUTO_TEST_CASE(ChromosomeLengthMetric_evaluate_should_return_chromosome_length)
{
BOOST_TEST(ChromosomeLengthMetric{}.evaluate(Chromosome()) == 0);
BOOST_TEST(ChromosomeLengthMetric{}.evaluate(Chromosome("a")) == 1);
BOOST_TEST(ChromosomeLengthMetric{}.evaluate(Chromosome("aaaaa")) == 5);
}
BOOST_AUTO_TEST_CASE(wholeChromosomeReplacement_should_replace_whole_chromosome_with_another)
{
std::function<Mutation> mutation = wholeChromosomeReplacement(Chromosome("aaa"));
BOOST_TEST(mutation(Chromosome("ccc")) == Chromosome("aaa"));
}
BOOST_AUTO_TEST_CASE(geneSubstitution_should_change_a_single_gene_at_a_given_index)
{
Chromosome chromosome("aaccff");
std::function<Mutation> mutation1 = geneSubstitution(0, chromosome.optimisationSteps()[5]);
BOOST_TEST(mutation1(chromosome) == Chromosome("faccff"));
std::function<Mutation> mutation2 = geneSubstitution(5, chromosome.optimisationSteps()[0]);
BOOST_TEST(mutation2(chromosome) == Chromosome("aaccfa"));
}
BOOST_AUTO_TEST_CASE(chromosomeLengths_should_return_lengths_of_all_chromosomes_in_a_population)
{
std::shared_ptr<FitnessMetric> fitnessMetric = std::make_shared<ChromosomeLengthMetric>();
Population population1(fitnessMetric, {Chromosome(), Chromosome("a"), Chromosome("aa"), Chromosome("aaa")});
BOOST_TEST((chromosomeLengths(population1) == std::vector<size_t>{0, 1, 2, 3}));
Population population2(fitnessMetric);
BOOST_TEST((chromosomeLengths(population2) == std::vector<size_t>{}));
}
BOOST_AUTO_TEST_CASE(countDifferences_should_return_zero_for_identical_chromosomes)
{
BOOST_TEST(countDifferences(Chromosome(), Chromosome()) == 0);
BOOST_TEST(countDifferences(Chromosome("a"), Chromosome("a")) == 0);
BOOST_TEST(countDifferences(Chromosome("afxT"), Chromosome("afxT")) == 0);
}
BOOST_AUTO_TEST_CASE(countDifferences_should_count_mismatched_positions_in_chromosomes_of_the_same_length)
{
BOOST_TEST(countDifferences(Chromosome("a"), Chromosome("f")) == 1);
BOOST_TEST(countDifferences(Chromosome("aa"), Chromosome("ac")) == 1);
BOOST_TEST(countDifferences(Chromosome("ac"), Chromosome("cc")) == 1);
BOOST_TEST(countDifferences(Chromosome("aa"), Chromosome("cc")) == 2);
BOOST_TEST(countDifferences(Chromosome("afxT"), Chromosome("Txfa")) == 4);
}
BOOST_AUTO_TEST_CASE(countDifferences_should_count_missing_characters_as_differences)
{
BOOST_TEST(countDifferences(Chromosome(""), Chromosome("a")) == 1);
BOOST_TEST(countDifferences(Chromosome("a"), Chromosome("")) == 1);
BOOST_TEST(countDifferences(Chromosome("aa"), Chromosome("")) == 2);
BOOST_TEST(countDifferences(Chromosome("aaa"), Chromosome("")) == 3);
BOOST_TEST(countDifferences(Chromosome("aa"), Chromosome("aaaa")) == 2);
BOOST_TEST(countDifferences(Chromosome("aa"), Chromosome("aacc")) == 2);
BOOST_TEST(countDifferences(Chromosome("aa"), Chromosome("cccc")) == 4);
}
BOOST_AUTO_TEST_CASE(enumerateOptimisationSteps_should_assing_indices_to_all_available_optimisation_steps)
{
std::map<std::string, char> stepsAndAbbreviations = OptimiserSuite::stepNameToAbbreviationMap();
std::map<std::string, size_t> stepsAndIndices = enumerateOptmisationSteps();
BOOST_TEST(stepsAndIndices.size() == stepsAndAbbreviations.size());
std::set<std::string> stepsSoFar;
for (auto& [name, index]: stepsAndIndices)
{
BOOST_TEST(index >= 0);
BOOST_TEST(index <= stepsAndAbbreviations.size());
BOOST_TEST(stepsAndAbbreviations.count(name) == 1);
BOOST_TEST(stepsSoFar.count(name) == 0);
stepsSoFar.insert(name);
}
}
BOOST_AUTO_TEST_CASE(stripWhitespace_should_remove_all_whitespace_characters_from_a_string)
{
BOOST_TEST(stripWhitespace("") == "");
BOOST_TEST(stripWhitespace(" ") == "");
BOOST_TEST(stripWhitespace(" \n\t\v ") == "");
BOOST_TEST(stripWhitespace("abc") == "abc");
BOOST_TEST(stripWhitespace(" abc") == "abc");
BOOST_TEST(stripWhitespace("abc ") == "abc");
BOOST_TEST(stripWhitespace(" a b c ") == "abc");
BOOST_TEST(stripWhitespace(" a b\tc\n") == "abc");
BOOST_TEST(stripWhitespace(" a b \n\n c \n\t\v") == "abc");
}
BOOST_AUTO_TEST_CASE(countSubstringOccurrences_should_count_non_overlapping_substring_occurrences_in_a_string)
{
BOOST_TEST(countSubstringOccurrences("aaabcdcbaaa", "a") == 6);
BOOST_TEST(countSubstringOccurrences("aaabcdcbaaa", "aa") == 2);
BOOST_TEST(countSubstringOccurrences("aaabcdcbaaa", "aaa") == 2);
BOOST_TEST(countSubstringOccurrences("aaabcdcbaaa", "aaab") == 1);
BOOST_TEST(countSubstringOccurrences("aaabcdcbaaa", "b") == 2);
BOOST_TEST(countSubstringOccurrences("aaabcdcbaaa", "d") == 1);
BOOST_TEST(countSubstringOccurrences("aaabcdcbaaa", "cdc") == 1);
BOOST_TEST(countSubstringOccurrences("aaabcdcbaaa", "x") == 0);
BOOST_TEST(countSubstringOccurrences("aaabcdcbaaa", "aaaa") == 0);
BOOST_TEST(countSubstringOccurrences("aaabcdcbaaa", "dcd") == 0);
BOOST_TEST(countSubstringOccurrences("", "a") == 0);
BOOST_TEST(countSubstringOccurrences("", "aa") == 0);
BOOST_TEST(countSubstringOccurrences("a", "aa") == 0);
}
BOOST_AUTO_TEST_CASE(mean_should_calculate_statistical_mean)
{
BOOST_TEST(mean<int>({0}) == 0.0);
BOOST_TEST(mean<int>({0, 0, 0, 0}) == 0.0);
BOOST_TEST(mean<int>({5, 5, 5, 5}) == 5.0);
BOOST_TEST(mean<int>({0, 1, 2, 3}) == 1.5);
BOOST_TEST(mean<int>({-4, -3, -2, -1, 0, 1, 2, 3}) == -0.5);
BOOST_TEST(mean<double>({1.3, 1.1, 0.0, 1.5, 1.1, 2.0, 1.5, 1.5}) == 1.25);
}
BOOST_AUTO_TEST_CASE(meanSquaredError_should_calculate_average_squared_difference_between_samples_and_expected_value)
{
BOOST_TEST(meanSquaredError<int>({0}, 0.0) == 0.0);
BOOST_TEST(meanSquaredError<int>({0}, 1.0) == 1.0);
BOOST_TEST(meanSquaredError<int>({0, 0, 0, 0}, 0.0) == 0.0);
BOOST_TEST(meanSquaredError<int>({0, 0, 0, 0}, 1.0) == 1.0);
BOOST_TEST(meanSquaredError<int>({0, 0, 0, 0}, 2.0) == 4.0);
BOOST_TEST(meanSquaredError<int>({5, 5, 5, 5}, 1.0) == 16.0);
BOOST_TEST(meanSquaredError<int>({0, 1, 2, 3}, 2.0) == 1.5);
BOOST_TEST(meanSquaredError<int>({-4, -3, -2, -1, 0, 1, 2, 3}, -4.0) == 17.5);
BOOST_TEST(meanSquaredError<double>({1.3, 1.1, 0.0, 1.5, 1.1, 2.0, 1.5, 1.5}, 1.0) == 0.3575, tolerance(0.0001));
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_AUTO_TEST_SUITE_END()
}
| 7,173
|
C++
|
.cpp
| 142
| 48.591549
| 117
| 0.730808
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,943
|
TestHelpers.cpp
|
ethereum_solidity/test/yulPhaser/TestHelpers.cpp
|
/*
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
#include <test/yulPhaser/TestHelpers.h>
#include <libyul/optimiser/Suite.h>
#include <regex>
using namespace solidity;
using namespace solidity::yul;
using namespace solidity::phaser;
using namespace solidity::phaser::test;
std::function<Mutation> phaser::test::wholeChromosomeReplacement(Chromosome _newChromosome)
{
return [_newChromosome = std::move(_newChromosome)](Chromosome const&) { return _newChromosome; };
}
std::function<Mutation> phaser::test::geneSubstitution(size_t _geneIndex, std::string _geneValue)
{
return [=](Chromosome const& _chromosome)
{
std::vector<std::string> newGenes = _chromosome.optimisationSteps();
assert(_geneIndex < newGenes.size());
newGenes[_geneIndex] = _geneValue;
return Chromosome(newGenes);
};
}
std::vector<size_t> phaser::test::chromosomeLengths(Population const& _population)
{
std::vector<size_t> lengths;
for (auto const& individual: _population.individuals())
lengths.push_back(individual.chromosome.length());
return lengths;
}
std::map<std::string, size_t> phaser::test::enumerateOptmisationSteps()
{
std::map<std::string, size_t> stepIndices;
size_t i = 0;
for (auto const& nameAndAbbreviation: OptimiserSuite::stepNameToAbbreviationMap())
stepIndices.insert({nameAndAbbreviation.first, i++});
return stepIndices;
}
size_t phaser::test::countDifferences(Chromosome const& _chromosome1, Chromosome const& _chromosome2)
{
size_t count = 0;
for (size_t i = 0; i < std::min(_chromosome1.length(), _chromosome2.length()); ++i)
if (_chromosome1.optimisationSteps()[i] != _chromosome2.optimisationSteps()[i])
++count;
return count + static_cast<size_t>(std::abs(
static_cast<long>(_chromosome1.length()) -
static_cast<long>(_chromosome2.length())
));
}
std::string phaser::test::stripWhitespace(std::string const& input)
{
std::regex whitespaceRegex("\\s+");
return regex_replace(input, whitespaceRegex, "");
}
size_t phaser::test::countSubstringOccurrences(std::string const& _inputString, std::string const& _substring)
{
assert(_substring.size() > 0);
size_t count = 0;
size_t lastOccurrence = 0;
while ((lastOccurrence = _inputString.find(_substring, lastOccurrence)) != std::string::npos)
{
++count;
lastOccurrence += _substring.size();
}
return count;
}
| 2,956
|
C++
|
.cpp
| 78
| 35.871795
| 110
| 0.760322
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,951
|
ControlFlowGraphTest.cpp
|
ethereum_solidity/test/libyul/ControlFlowGraphTest.cpp
|
/*
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
#include <test/libyul/ControlFlowGraphTest.h>
#include <test/libyul/Common.h>
#include <test/Common.h>
#include <libyul/backends/evm/ControlFlowGraph.h>
#include <libyul/backends/evm/ControlFlowGraphBuilder.h>
#include <libyul/backends/evm/StackHelpers.h>
#include <libyul/Object.h>
#include <libsolutil/AnsiColorized.h>
#include <libsolutil/Visitor.h>
#ifdef ISOLTEST
#include <boost/process.hpp>
#endif
using namespace solidity;
using namespace solidity::util;
using namespace solidity::langutil;
using namespace solidity::yul;
using namespace solidity::yul::test;
using namespace solidity::frontend;
using namespace solidity::frontend::test;
ControlFlowGraphTest::ControlFlowGraphTest(std::string const& _filename):
TestCase(_filename)
{
m_source = m_reader.source();
auto dialectName = m_reader.stringSetting("dialect", "evm");
m_dialect = &dialect(
dialectName,
solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion()
);
m_expectation = m_reader.simpleExpectations();
}
namespace
{
static std::string variableSlotToString(VariableSlot const& _slot)
{
return _slot.variable.get().name.str();
}
}
class ControlFlowGraphPrinter
{
public:
ControlFlowGraphPrinter(std::ostream& _stream):
m_stream(_stream)
{
}
void operator()(CFG::BasicBlock const& _block, bool _isMainEntry = true)
{
if (_isMainEntry)
{
m_stream << "Entry [label=\"Entry\"];\n";
m_stream << "Entry -> Block" << getBlockId(_block) << ";\n";
}
while (!m_blocksToPrint.empty())
{
CFG::BasicBlock const* block = *m_blocksToPrint.begin();
m_blocksToPrint.erase(m_blocksToPrint.begin());
printBlock(*block);
}
}
void operator()(
CFG::FunctionInfo const& _info
)
{
m_stream << "FunctionEntry_" << _info.function.name.str() << "_" << getBlockId(*_info.entry) << " [label=\"";
m_stream << "function " << _info.function.name.str() << "(";
m_stream << joinHumanReadable(_info.parameters | ranges::views::transform(variableSlotToString));
m_stream << ")";
if (!_info.returnVariables.empty())
{
m_stream << " -> ";
m_stream << joinHumanReadable(_info.returnVariables | ranges::views::transform(variableSlotToString));
}
m_stream << "\"];\n";
m_stream << "FunctionEntry_" << _info.function.name.str() << "_" << getBlockId(*_info.entry) << " -> Block" << getBlockId(*_info.entry) << ";\n";
(*this)(*_info.entry, false);
}
private:
void printBlock(CFG::BasicBlock const& _block)
{
m_stream << "Block" << getBlockId(_block) << " [label=\"\\\n";
// Verify that the entries of this block exit into this block.
for (auto const& entry: _block.entries)
std::visit(util::GenericVisitor{
[&](CFG::BasicBlock::Jump const& _jump)
{
soltestAssert(_jump.target == &_block, "Invalid control flow graph.");
},
[&](CFG::BasicBlock::ConditionalJump const& _conditionalJump)
{
soltestAssert(
_conditionalJump.zero == &_block || _conditionalJump.nonZero == &_block,
"Invalid control flow graph."
);
},
[&](auto const&)
{
soltestAssert(false, "Invalid control flow graph.");
}
}, entry->exit);
for (auto const& operation: _block.operations)
{
std::visit(util::GenericVisitor{
[&](CFG::FunctionCall const& _call) {
m_stream << _call.function.get().name.str() << ": ";
},
[&](CFG::BuiltinCall const& _call) {
m_stream << _call.functionCall.get().functionName.name.str() << ": ";
},
[&](CFG::Assignment const& _assignment) {
m_stream << "Assignment(";
m_stream << joinHumanReadable(_assignment.variables | ranges::views::transform(variableSlotToString));
m_stream << "): ";
}
}, operation.operation);
m_stream << stackToString(operation.input) << " => " << stackToString(operation.output) << "\\l\\\n";
}
m_stream << "\"];\n";
std::visit(util::GenericVisitor{
[&](CFG::BasicBlock::MainExit const&)
{
m_stream << "Block" << getBlockId(_block) << "Exit [label=\"MainExit\"];\n";
m_stream << "Block" << getBlockId(_block) << " -> Block" << getBlockId(_block) << "Exit;\n";
},
[&](CFG::BasicBlock::Jump const& _jump)
{
m_stream << "Block" << getBlockId(_block) << " -> Block" << getBlockId(_block) << "Exit [arrowhead=none];\n";
m_stream << "Block" << getBlockId(_block) << "Exit [label=\"";
if (_jump.backwards)
m_stream << "Backwards";
m_stream << "Jump\" shape=oval];\n";
m_stream << "Block" << getBlockId(_block) << "Exit -> Block" << getBlockId(*_jump.target) << ";\n";
},
[&](CFG::BasicBlock::ConditionalJump const& _conditionalJump)
{
m_stream << "Block" << getBlockId(_block) << " -> Block" << getBlockId(_block) << "Exit;\n";
m_stream << "Block" << getBlockId(_block) << "Exit [label=\"{ ";
m_stream << stackSlotToString(_conditionalJump.condition);
m_stream << "| { <0> Zero | <1> NonZero }}\" shape=Mrecord];\n";
m_stream << "Block" << getBlockId(_block);
m_stream << "Exit:0 -> Block" << getBlockId(*_conditionalJump.zero) << ";\n";
m_stream << "Block" << getBlockId(_block);
m_stream << "Exit:1 -> Block" << getBlockId(*_conditionalJump.nonZero) << ";\n";
},
[&](CFG::BasicBlock::FunctionReturn const& _return)
{
m_stream << "Block" << getBlockId(_block) << "Exit [label=\"FunctionReturn[" << _return.info->function.name.str() << "]\"];\n";
m_stream << "Block" << getBlockId(_block) << " -> Block" << getBlockId(_block) << "Exit;\n";
},
[&](CFG::BasicBlock::Terminated const&)
{
m_stream << "Block" << getBlockId(_block) << "Exit [label=\"Terminated\"];\n";
m_stream << "Block" << getBlockId(_block) << " -> Block" << getBlockId(_block) << "Exit;\n";
}
}, _block.exit);
m_stream << "\n";
}
size_t getBlockId(CFG::BasicBlock const& _block)
{
if (size_t* id = util::valueOrNullptr(m_blockIds, &_block))
return *id;
size_t id = m_blockIds[&_block] = m_blockCount++;
m_blocksToPrint.emplace_back(&_block);
return id;
}
std::ostream& m_stream;
std::map<CFG::BasicBlock const*, size_t> m_blockIds;
size_t m_blockCount = 0;
std::list<CFG::BasicBlock const*> m_blocksToPrint;
};
TestCase::TestResult ControlFlowGraphTest::run(std::ostream& _stream, std::string const& _linePrefix, bool const _formatted)
{
ErrorList errors;
auto [object, analysisInfo] = parse(m_source, *m_dialect, errors);
if (!object || !analysisInfo || Error::containsErrors(errors))
{
AnsiColorized(_stream, _formatted, {formatting::BOLD, formatting::RED}) << _linePrefix << "Error parsing source." << std::endl;
return TestResult::FatalError;
}
std::ostringstream output;
std::unique_ptr<CFG> cfg = ControlFlowGraphBuilder::build(*analysisInfo, *m_dialect, object->code()->root());
output << "digraph CFG {\nnodesep=0.7;\nnode[shape=box];\n\n";
ControlFlowGraphPrinter printer{output};
printer(*cfg->entry);
for (auto function: cfg->functions)
printer(cfg->functionInfo.at(function));
output << "}\n";
m_obtainedResult = output.str();
auto result = checkResult(_stream, _linePrefix, _formatted);
#ifdef ISOLTEST
char* graphDisplayer = nullptr;
// The environment variables specify an optional command that will receive the graph encoded in DOT through stdin.
// Examples for suitable commands are ``dot -Tx11:cairo`` or ``xdot -``.
if (result == TestResult::Failure)
// ISOLTEST_DISPLAY_GRAPHS_ON_FAILURE_COMMAND will run on all failing tests (intended for use during modifications).
graphDisplayer = getenv("ISOLTEST_DISPLAY_GRAPHS_ON_FAILURE_COMMAND");
else if (result == TestResult::Success)
// ISOLTEST_DISPLAY_GRAPHS_ON_FAILURE_COMMAND will run on all succeeding tests (intended for use during reviews).
graphDisplayer = getenv("ISOLTEST_DISPLAY_GRAPHS_ON_SUCCESS_COMMAND");
if (graphDisplayer)
{
if (result == TestResult::Success)
std::cout << std::endl << m_source << std::endl;
boost::process::opstream pipe;
boost::process::child child(graphDisplayer, boost::process::std_in < pipe);
pipe << output.str();
pipe.flush();
pipe.pipe().close();
if (result == TestResult::Success)
child.wait();
else
child.detach();
}
#endif
return result;
}
| 8,842
|
C++
|
.cpp
| 229
| 35.528384
| 147
| 0.677536
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,952
|
KnowledgeBaseTest.cpp
|
ethereum_solidity/test/libyul/KnowledgeBaseTest.cpp
|
/*
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/>.
*/
/**
* Unit tests for KnowledgeBase
*/
#include <test/Common.h>
#include <test/libyul/Common.h>
#include <libyul/Object.h>
#include <libyul/optimiser/ASTCopier.h>
#include <libyul/optimiser/KnowledgeBase.h>
#include <libyul/optimiser/SSAValueTracker.h>
#include <libyul/optimiser/NameDispenser.h>
#include <libyul/optimiser/CommonSubexpressionEliminator.h>
#include <libyul/backends/evm/EVMDialect.h>
#include <liblangutil/ErrorReporter.h>
#include <boost/test/unit_test.hpp>
using namespace solidity::langutil;
namespace solidity::yul::test
{
class KnowledgeBaseTest
{
protected:
KnowledgeBase constructKnowledgeBase(std::string const& _source)
{
ErrorList errorList;
std::shared_ptr<AsmAnalysisInfo> analysisInfo;
std::tie(m_object, analysisInfo) = yul::test::parse(_source, m_dialect, errorList);
BOOST_REQUIRE(m_object && errorList.empty() && m_object->hasCode());
auto astRoot = std::get<Block>(yul::ASTCopier{}(m_object->code()->root()));
NameDispenser dispenser(m_dialect, astRoot);
std::set<YulName> reserved;
OptimiserStepContext context{m_dialect, dispenser, reserved, 0};
CommonSubexpressionEliminator::run(context, astRoot);
m_ssaValues(astRoot);
for (auto const& [name, expression]: m_ssaValues.values())
m_values[name].value = expression;
m_object->setCode(std::make_shared<AST>(std::move(astRoot)));
return KnowledgeBase([this](YulName _var) { return util::valueOrNullptr(m_values, _var); });
}
EVMDialect m_dialect{solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion(), true};
std::shared_ptr<Object> m_object;
SSAValueTracker m_ssaValues;
std::map<YulName, AssignedValue> m_values;
};
BOOST_FIXTURE_TEST_SUITE(KnowledgeBase, KnowledgeBaseTest)
BOOST_AUTO_TEST_CASE(basic)
{
yul::KnowledgeBase kb = constructKnowledgeBase(R"({
let a := calldataload(0)
let b := calldataload(0)
let zero := 0
let c := add(b, 0)
let d := mul(b, 0)
let e := sub(a, b)
})");
BOOST_CHECK(!kb.knownToBeDifferent("a"_yulname, "b"_yulname));
// This only works if the variable names are the same.
// It assumes that SSA+CSE+Simplifier actually replaces the variables.
BOOST_CHECK(!kb.valueIfKnownConstant("a"_yulname));
BOOST_CHECK(kb.valueIfKnownConstant("zero"_yulname) == u256(0));
BOOST_CHECK(kb.differenceIfKnownConstant("a"_yulname, "b"_yulname) == u256(0));
BOOST_CHECK(kb.differenceIfKnownConstant("a"_yulname, "c"_yulname) == u256(0));
BOOST_CHECK(kb.valueIfKnownConstant("e"_yulname) == u256(0));
}
BOOST_AUTO_TEST_CASE(difference)
{
yul::KnowledgeBase kb = constructKnowledgeBase(R"({
let a := calldataload(0)
let b := add(a, 200)
let c := add(a, 220)
let d := add(12, c)
let e := sub(c, 12)
})");
BOOST_CHECK(kb.differenceIfKnownConstant("c"_yulname, "b"_yulname) ==
u256(20)
);
BOOST_CHECK(kb.differenceIfKnownConstant("b"_yulname, "c"_yulname) ==
u256(-20)
);
BOOST_CHECK(!kb.knownToBeDifferentByAtLeast32("b"_yulname, "c"_yulname));
BOOST_CHECK(kb.knownToBeDifferentByAtLeast32("b"_yulname, "d"_yulname));
BOOST_CHECK(kb.knownToBeDifferentByAtLeast32("a"_yulname, "b"_yulname));
BOOST_CHECK(kb.knownToBeDifferentByAtLeast32("b"_yulname, "a"_yulname));
BOOST_CHECK(kb.differenceIfKnownConstant("e"_yulname, "a"_yulname) == u256(208));
BOOST_CHECK(kb.differenceIfKnownConstant("e"_yulname, "b"_yulname) == u256(8));
BOOST_CHECK(kb.differenceIfKnownConstant("a"_yulname, "e"_yulname) == u256(-208));
BOOST_CHECK(kb.differenceIfKnownConstant("b"_yulname, "e"_yulname) == u256(-8));
}
BOOST_AUTO_TEST_SUITE_END()
}
| 4,255
|
C++
|
.cpp
| 102
| 39.166667
| 94
| 0.743279
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,953
|
YulOptimizerTest.cpp
|
ethereum_solidity/test/libyul/YulOptimizerTest.cpp
|
/*
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
#include <test/libyul/YulOptimizerTest.h>
#include <test/libyul/YulOptimizerTestCommon.h>
#include <test/libsolidity/util/SoltestErrors.h>
#include <test/libyul/Common.h>
#include <test/Common.h>
#include <libyul/Object.h>
#include <libyul/AsmPrinter.h>
#include <libyul/AST.h>
#include <liblangutil/CharStreamProvider.h>
#include <liblangutil/SourceReferenceFormatter.h>
#include <liblangutil/Scanner.h>
#include <libsolutil/AnsiColorized.h>
#include <libsolutil/StringUtils.h>
#include <fstream>
using namespace solidity;
using namespace solidity::util;
using namespace solidity::langutil;
using namespace solidity::yul;
using namespace solidity::yul::test;
using namespace solidity::frontend;
using namespace solidity::frontend::test;
YulOptimizerTest::YulOptimizerTest(std::string const& _filename):
EVMVersionRestrictedTestCase(_filename)
{
boost::filesystem::path path(_filename);
if (path.empty() || std::next(path.begin()) == path.end() || std::next(std::next(path.begin())) == path.end())
BOOST_THROW_EXCEPTION(std::runtime_error("Filename path has to contain a directory: \"" + _filename + "\"."));
m_optimizerStep = std::prev(std::prev(path.end()))->string();
m_source = m_reader.source();
auto dialectName = m_reader.stringSetting("dialect", "evm");
m_dialect = &dialect(
dialectName,
solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion()
);
m_expectation = m_reader.simpleExpectations();
}
TestCase::TestResult YulOptimizerTest::run(std::ostream& _stream, std::string const& _linePrefix, bool const _formatted)
{
std::tie(m_object, m_analysisInfo) = parse(_stream, _linePrefix, _formatted, m_source);
if (!m_object)
return TestResult::FatalError;
soltestAssert(m_dialect, "Dialect not set.");
m_object->analysisInfo = m_analysisInfo;
YulOptimizerTestCommon tester(m_object, *m_dialect);
tester.setStep(m_optimizerStep);
if (!tester.runStep())
{
AnsiColorized(_stream, _formatted, {formatting::BOLD, formatting::RED}) << _linePrefix << "Invalid optimizer step: " << m_optimizerStep << std::endl;
return TestResult::FatalError;
}
auto optimizedObject = tester.optimizedObject();
std::string printedOptimizedObject;
if (optimizedObject->subObjects.empty())
printedOptimizedObject = AsmPrinter{optimizedObject->dialect()}(optimizedObject->code()->root());
else
printedOptimizedObject = optimizedObject->toString();
// Re-parse new code for compilability
if (!std::get<0>(parse(_stream, _linePrefix, _formatted, printedOptimizedObject)))
{
util::AnsiColorized(_stream, _formatted, {util::formatting::BOLD, util::formatting::CYAN})
<< _linePrefix << "Result after the optimiser:" << std::endl;
printPrefixed(_stream, printedOptimizedObject, _linePrefix + " ");
return TestResult::FatalError;
}
m_obtainedResult = "step: " + m_optimizerStep + "\n\n" + printedOptimizedObject + "\n";
return checkResult(_stream, _linePrefix, _formatted);
}
std::pair<std::shared_ptr<Object>, std::shared_ptr<AsmAnalysisInfo>> YulOptimizerTest::parse(
std::ostream& _stream,
std::string const& _linePrefix,
bool const _formatted,
std::string const& _source
)
{
ErrorList errors;
soltestAssert(m_dialect, "");
std::shared_ptr<Object> object;
std::shared_ptr<AsmAnalysisInfo> analysisInfo;
std::tie(object, analysisInfo) = yul::test::parse(_source, *m_dialect, errors);
if (!object || !analysisInfo || Error::containsErrors(errors))
{
AnsiColorized(_stream, _formatted, {formatting::BOLD, formatting::RED}) << _linePrefix << "Error parsing source." << std::endl;
CharStream charStream(_source, "");
SourceReferenceFormatter{_stream, SingletonCharStreamProvider(charStream), true, false}
.printErrorInformation(errors);
return {};
}
return {std::move(object), std::move(analysisInfo)};
}
| 4,504
|
C++
|
.cpp
| 104
| 41.221154
| 151
| 0.758739
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,956
|
CompilabilityChecker.cpp
|
ethereum_solidity/test/libyul/CompilabilityChecker.cpp
|
/*
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/>.
*/
/**
* Unit tests for the compilability checker.
*/
#include <test/Common.h>
#include <test/libyul/Common.h>
#include <libyul/backends/evm/EVMDialect.h>
#include <libyul/CompilabilityChecker.h>
#include <boost/test/unit_test.hpp>
namespace solidity::yul::test
{
namespace
{
std::string check(std::string const& _input)
{
auto const& dialect = EVMDialect::strictAssemblyForEVM(
solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion()
);
Object obj{dialect};
auto parsingResult = yul::test::parse(_input);
obj.setCode(parsingResult.first, parsingResult.second);
BOOST_REQUIRE(obj.hasCode());
auto functions = CompilabilityChecker(dialect, obj, true).stackDeficit;
std::string out;
for (auto const& function: functions)
out += function.first.str() + ": " + std::to_string(function.second) + " ";
return out;
}
}
BOOST_AUTO_TEST_SUITE(CompilabilityChecker)
BOOST_AUTO_TEST_CASE(smoke_test)
{
std::string out = check("{}");
BOOST_CHECK_EQUAL(out, "");
}
BOOST_AUTO_TEST_CASE(simple_function)
{
std::string out = check("{ function f(a, b) -> x, y { x := a y := b } }");
BOOST_CHECK_EQUAL(out, "");
}
BOOST_AUTO_TEST_CASE(many_variables_few_uses)
{
std::string out = check(R"({
function f(a, b) -> x, y {
let r1 := 0
let r2 := 0
let r3 := 0
let r4 := 0
let r5 := 0
let r6 := 0
let r7 := 0
let r8 := 0
let r9 := 0
let r10 := 0
let r11 := 0
let r12 := 0
let r13 := 0
let r14 := 0
let r15 := 0
let r16 := 0
let r17 := 0
let r18 := 0
x := add(add(add(add(add(add(add(add(add(x, r9), r8), r7), r6), r5), r4), r3), r2), r1)
}
})");
BOOST_CHECK_EQUAL(out, "f: 4 ");
}
BOOST_AUTO_TEST_CASE(many_variables_many_uses)
{
std::string out = check(R"({
function f(a, b) -> x, y {
let r1 := 0
let r2 := 0
let r3 := 0
let r4 := 0
let r5 := 0
let r6 := 0
let r7 := 0
let r8 := 0
let r9 := 0
let r10 := 0
let r11 := 0
let r12 := 0
let r13 := 0
let r14 := 0
let r15 := 0
let r16 := 0
let r17 := 0
let r18 := 0
x := add(add(add(add(add(add(add(add(add(add(add(add(x, r12), r11), r10), r9), r8), r7), r6), r5), r4), r3), r2), r1)
}
})");
BOOST_CHECK_EQUAL(out, "f: 10 ");
}
BOOST_AUTO_TEST_CASE(many_return_variables_unused_arguments)
{
std::string out = check(R"({
function f(a, b) -> r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15, r16, r17, r18, r19 {
}
})");
BOOST_CHECK_EQUAL(out, "f: 3 ");
}
BOOST_AUTO_TEST_CASE(many_return_variables_used_arguments)
{
std::string out = check(R"({
function f(a, b) -> r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15, r16, r17, r18, r19 {
r1 := 0
sstore(a, b)
}
})");
BOOST_CHECK_EQUAL(out, "f: 5 ");
}
BOOST_AUTO_TEST_CASE(multiple_functions_used_arguments)
{
std::string out = check(R"({
function f(a, b) -> r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15, r16, r17, r18, r19 {
r1 := 0
sstore(a, b)
}
function g(r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15, r16, r17, r18, r19) -> x, y {
x := 0
sstore(r1, r2)
}
function h(x) {
let r1 := 0
let r2 := 0
let r3 := 0
let r4 := 0
let r5 := 0
let r6 := 0
let r7 := 0
let r8 := 0
let r9 := 0
let r10 := 0
let r11 := 0
let r12 := 0
let r13 := 0
let r14 := 0
let r15 := 0
let r16 := 0
let r17 := 0
let r18 := 0
x := add(add(add(add(add(add(add(add(add(add(add(add(x, r12), r11), r10), r9), r8), r7), r6), r5), r4), r3), r2), r1)
}
})");
BOOST_CHECK_EQUAL(out, "h: 9 g: 5 f: 5 ");
}
BOOST_AUTO_TEST_CASE(multiple_functions_unused_arguments)
{
std::string out = check(R"({
function f(a, b) -> r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15, r16, r17, r18, r19 {
}
function g(r1, r2, r3, r4, r5, r6, r7, r8, r9, r10, r11, r12, r13, r14, r15, r16, r17, r18, r19) -> x, y {
}
function h(x) {
let r1 := 0
let r2 := 0
let r3 := 0
let r4 := 0
let r5 := 0
let r6 := 0
let r7 := 0
let r8 := 0
let r9 := 0
let r10 := 0
let r11 := 0
let r12 := 0
let r13 := 0
let r14 := 0
let r15 := 0
let r16 := 0
let r17 := 0
let r18 := 0
x := add(add(add(add(add(add(add(add(add(add(add(add(x, r12), r11), r10), r9), r8), r7), r6), r5), r4), r3), r2), r1)
}
})");
BOOST_CHECK_EQUAL(out, "h: 9 f: 3 ");
}
BOOST_AUTO_TEST_CASE(nested_used_arguments)
{
std::string out = check(R"({
function h(x) {
let r1 := 0
let r2 := 0
let r3 := 0
let r4 := 0
let r5 := 0
let r6 := 0
let r7 := 0
let r8 := 0
let r9 := 0
let r10 := 0
let r11 := 0
let r12 := 0
let r13 := 0
let r14 := 0
let r15 := 0
let r16 := 0
let r17 := 0
let r18 := 0
function f(a, b) -> t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18, t19 {
function g(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19) -> w, v {
w := v
sstore(s1, s2)
}
t1 := t2
sstore(a, b)
}
x := add(add(add(add(add(add(add(add(add(add(add(add(x, r12), r11), r10), r9), r8), r7), r6), r5), r4), r3), r2), r1)
}
})");
BOOST_CHECK_EQUAL(out, "h: 9 g: 5 f: 5 ");
}
BOOST_AUTO_TEST_CASE(nested_unused_arguments)
{
std::string out = check(R"({
function h(x) {
let r1 := 0
let r2 := 0
let r3 := 0
let r4 := 0
let r5 := 0
let r6 := 0
let r7 := 0
let r8 := 0
let r9 := 0
let r10 := 0
let r11 := 0
let r12 := 0
let r13 := 0
let r14 := 0
let r15 := 0
let r16 := 0
let r17 := 0
let r18 := 0
function f(a, b) -> t1, t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17, t18, t19 {
function g(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19) -> w, v {
}
}
x := add(add(add(add(add(add(add(add(add(add(add(add(x, r12), r11), r10), r9), r8), r7), r6), r5), r4), r3), r2), r1)
}
})");
BOOST_CHECK_EQUAL(out, "h: 9 f: 3 ");
}
BOOST_AUTO_TEST_CASE(also_in_outer_block_used_arguments)
{
std::string out = check(R"({
let x := 0
let r1 := 0
let r2 := 0
let r3 := 0
let r4 := 0
let r5 := 0
let r6 := 0
let r7 := 0
let r8 := 0
let r9 := 0
let r10 := 0
let r11 := 0
let r12 := 0
let r13 := 0
let r14 := 0
let r15 := 0
let r16 := 0
let r17 := 0
let r18 := 0
x := add(add(add(add(add(add(add(add(add(add(add(add(x, r12), r11), r10), r9), r8), r7), r6), r5), r4), r3), r2), r1)
function g(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19) -> w, v {
w := v
sstore(s1, s2)
}
})");
BOOST_CHECK_EQUAL(out, "g: 5 : 9 ");
}
BOOST_AUTO_TEST_CASE(also_in_outer_block_unused_arguments)
{
std::string out = check(R"({
let x := 0
let r1 := 0
let r2 := 0
let r3 := 0
let r4 := 0
let r5 := 0
let r6 := 0
let r7 := 0
let r8 := 0
let r9 := 0
let r10 := 0
let r11 := 0
let r12 := 0
let r13 := 0
let r14 := 0
let r15 := 0
let r16 := 0
let r17 := 0
let r18 := 0
x := add(add(add(add(add(add(add(add(add(add(add(add(x, r12), r11), r10), r9), r8), r7), r6), r5), r4), r3), r2), r1)
function g(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18, s19) -> w, v {
}
})");
BOOST_CHECK_EQUAL(out, ": 9 ");
}
BOOST_AUTO_TEST_SUITE_END()
}
| 8,110
|
C++
|
.cpp
| 317
| 22.324921
| 120
| 0.574353
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,957
|
StackLayoutGeneratorTest.cpp
|
ethereum_solidity/test/libyul/StackLayoutGeneratorTest.cpp
|
/*
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
#include <test/libyul/StackLayoutGeneratorTest.h>
#include <test/libyul/Common.h>
#include <test/Common.h>
#include <libyul/backends/evm/ControlFlowGraph.h>
#include <libyul/backends/evm/ControlFlowGraphBuilder.h>
#include <libyul/backends/evm/StackHelpers.h>
#include <libyul/backends/evm/StackLayoutGenerator.h>
#include <libyul/Object.h>
#include <liblangutil/SourceReferenceFormatter.h>
#include <libsolutil/AnsiColorized.h>
#include <libsolutil/Visitor.h>
#include <range/v3/view/reverse.hpp>
#ifdef ISOLTEST
#include <boost/process.hpp>
#endif
using namespace solidity;
using namespace solidity::util;
using namespace solidity::langutil;
using namespace solidity::yul;
using namespace solidity::yul::test;
using namespace solidity::frontend;
using namespace solidity::frontend::test;
StackLayoutGeneratorTest::StackLayoutGeneratorTest(std::string const& _filename):
TestCase(_filename)
{
m_source = m_reader.source();
auto dialectName = m_reader.stringSetting("dialect", "evm");
m_dialect = &dialect(
dialectName,
solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion()
);
m_expectation = m_reader.simpleExpectations();
}
namespace
{
static std::string variableSlotToString(VariableSlot const& _slot)
{
return _slot.variable.get().name.str();
}
}
class StackLayoutPrinter
{
public:
StackLayoutPrinter(std::ostream& _stream, StackLayout const& _stackLayout):
m_stream(_stream), m_stackLayout(_stackLayout)
{
}
void operator()(CFG::BasicBlock const& _block, bool _isMainEntry = true)
{
if (_isMainEntry)
{
m_stream << "Entry [label=\"Entry\"];\n";
m_stream << "Entry -> Block" << getBlockId(_block) << ";\n";
}
while (!m_blocksToPrint.empty())
{
CFG::BasicBlock const* block = *m_blocksToPrint.begin();
m_blocksToPrint.erase(m_blocksToPrint.begin());
printBlock(*block);
}
}
void operator()(
CFG::FunctionInfo const& _info
)
{
m_stream << "FunctionEntry_" << _info.function.name.str() << " [label=\"";
m_stream << "function " << _info.function.name.str() << "(";
m_stream << joinHumanReadable(_info.parameters | ranges::views::transform(variableSlotToString));
m_stream << ")";
if (!_info.returnVariables.empty())
{
m_stream << " -> ";
m_stream << joinHumanReadable(_info.returnVariables | ranges::views::transform(variableSlotToString));
}
m_stream << "\\l\\\n";
Stack functionEntryStack = {FunctionReturnLabelSlot{_info.function}};
functionEntryStack += _info.parameters | ranges::views::reverse;
m_stream << stackToString(functionEntryStack) << "\"];\n";
m_stream << "FunctionEntry_" << _info.function.name.str() << " -> Block" << getBlockId(*_info.entry) << ";\n";
(*this)(*_info.entry, false);
}
private:
void printBlock(CFG::BasicBlock const& _block)
{
m_stream << "Block" << getBlockId(_block) << " [label=\"\\\n";
// Verify that the entries of this block exit into this block.
for (auto const& entry: _block.entries)
std::visit(util::GenericVisitor{
[&](CFG::BasicBlock::Jump const& _jump)
{
soltestAssert(_jump.target == &_block, "Invalid control flow graph.");
},
[&](CFG::BasicBlock::ConditionalJump const& _conditionalJump)
{
soltestAssert(
_conditionalJump.zero == &_block || _conditionalJump.nonZero == &_block,
"Invalid control flow graph."
);
},
[&](auto const&)
{
soltestAssert(false, "Invalid control flow graph.");
}
}, entry->exit);
auto const& blockInfo = m_stackLayout.blockInfos.at(&_block);
m_stream << stackToString(blockInfo.entryLayout) << "\\l\\\n";
for (auto const& operation: _block.operations)
{
auto entryLayout = m_stackLayout.operationEntryLayout.at(&operation);
m_stream << stackToString(m_stackLayout.operationEntryLayout.at(&operation)) << "\\l\\\n";
std::visit(util::GenericVisitor{
[&](CFG::FunctionCall const& _call) {
m_stream << _call.function.get().name.str();
},
[&](CFG::BuiltinCall const& _call) {
m_stream << _call.functionCall.get().functionName.name.str();
},
[&](CFG::Assignment const& _assignment) {
m_stream << "Assignment(";
m_stream << joinHumanReadable(_assignment.variables | ranges::views::transform(variableSlotToString));
m_stream << ")";
}
}, operation.operation);
m_stream << "\\l\\\n";
soltestAssert(operation.input.size() <= entryLayout.size(), "Invalid Stack Layout.");
for (size_t i = 0; i < operation.input.size(); ++i)
entryLayout.pop_back();
entryLayout += operation.output;
m_stream << stackToString(entryLayout) << "\\l\\\n";
}
m_stream << stackToString(blockInfo.exitLayout) << "\\l\\\n";
m_stream << "\"];\n";
std::visit(util::GenericVisitor{
[&](CFG::BasicBlock::MainExit const&)
{
m_stream << "Block" << getBlockId(_block) << "Exit [label=\"MainExit\"];\n";
m_stream << "Block" << getBlockId(_block) << " -> Block" << getBlockId(_block) << "Exit;\n";
},
[&](CFG::BasicBlock::Jump const& _jump)
{
m_stream << "Block" << getBlockId(_block) << " -> Block" << getBlockId(_block) << "Exit [arrowhead=none];\n";
m_stream << "Block" << getBlockId(_block) << "Exit [label=\"";
if (_jump.backwards)
m_stream << "Backwards";
m_stream << "Jump\" shape=oval];\n";
m_stream << "Block" << getBlockId(_block) << "Exit -> Block" << getBlockId(*_jump.target) << ";\n";
},
[&](CFG::BasicBlock::ConditionalJump const& _conditionalJump)
{
m_stream << "Block" << getBlockId(_block) << " -> Block" << getBlockId(_block) << "Exit;\n";
m_stream << "Block" << getBlockId(_block) << "Exit [label=\"{ ";
m_stream << stackSlotToString(_conditionalJump.condition);
m_stream << "| { <0> Zero | <1> NonZero }}\" shape=Mrecord];\n";
m_stream << "Block" << getBlockId(_block);
m_stream << "Exit:0 -> Block" << getBlockId(*_conditionalJump.zero) << ";\n";
m_stream << "Block" << getBlockId(_block);
m_stream << "Exit:1 -> Block" << getBlockId(*_conditionalJump.nonZero) << ";\n";
},
[&](CFG::BasicBlock::FunctionReturn const& _return)
{
m_stream << "Block" << getBlockId(_block) << "Exit [label=\"FunctionReturn[" << _return.info->function.name.str() << "]\"];\n";
m_stream << "Block" << getBlockId(_block) << " -> Block" << getBlockId(_block) << "Exit;\n";
},
[&](CFG::BasicBlock::Terminated const&)
{
m_stream << "Block" << getBlockId(_block) << "Exit [label=\"Terminated\"];\n";
m_stream << "Block" << getBlockId(_block) << " -> Block" << getBlockId(_block) << "Exit;\n";
}
}, _block.exit);
m_stream << "\n";
}
size_t getBlockId(CFG::BasicBlock const& _block)
{
if (size_t* id = util::valueOrNullptr(m_blockIds, &_block))
return *id;
size_t id = m_blockIds[&_block] = m_blockCount++;
m_blocksToPrint.emplace_back(&_block);
return id;
}
std::ostream& m_stream;
StackLayout const& m_stackLayout;
std::map<CFG::BasicBlock const*, size_t> m_blockIds;
size_t m_blockCount = 0;
std::list<CFG::BasicBlock const*> m_blocksToPrint;
};
TestCase::TestResult StackLayoutGeneratorTest::run(std::ostream& _stream, std::string const& _linePrefix, bool const _formatted)
{
ErrorList errors;
auto [object, analysisInfo] = parse(m_source, *m_dialect, errors);
if (!object || !analysisInfo || Error::containsErrors(errors))
{
AnsiColorized(_stream, _formatted, {formatting::BOLD, formatting::RED}) << _linePrefix << "Error parsing source." << std::endl;
return TestResult::FatalError;
}
std::ostringstream output;
std::unique_ptr<CFG> cfg = ControlFlowGraphBuilder::build(*analysisInfo, *m_dialect, object->code()->root());
StackLayout stackLayout = StackLayoutGenerator::run(*cfg);
output << "digraph CFG {\nnodesep=0.7;\nnode[shape=box];\n\n";
StackLayoutPrinter printer{output, stackLayout};
printer(*cfg->entry);
for (auto function: cfg->functions)
printer(cfg->functionInfo.at(function));
output << "}\n";
m_obtainedResult = output.str();
auto result = checkResult(_stream, _linePrefix, _formatted);
#ifdef ISOLTEST
char* graphDisplayer = nullptr;
if (result == TestResult::Failure)
graphDisplayer = getenv("ISOLTEST_DISPLAY_GRAPHS_FAILURE");
else if (result == TestResult::Success)
graphDisplayer = getenv("ISOLTEST_DISPLAY_GRAPHS_SUCCESS");
if (graphDisplayer)
{
if (result == TestResult::Success)
std::cout << std::endl << m_source << std::endl;
boost::process::opstream pipe;
boost::process::child child(graphDisplayer, boost::process::std_in < pipe);
pipe << output.str();
pipe.flush();
pipe.pipe().close();
if (result == TestResult::Success)
child.wait();
else
child.detach();
}
#endif
return result;
}
| 9,366
|
C++
|
.cpp
| 243
| 35.452675
| 131
| 0.682278
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,958
|
ObjectCompilerTest.cpp
|
ethereum_solidity/test/libyul/ObjectCompilerTest.cpp
|
/*
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
#include <test/libyul/ObjectCompilerTest.h>
#include <test/libsolidity/util/SoltestErrors.h>
#include <test/Common.h>
#include <libsolutil/AnsiColorized.h>
#include <libyul/YulStack.h>
#include <libevmasm/Assembly.h>
#include <libevmasm/Disassemble.h>
#include <libevmasm/Instruction.h>
#include <liblangutil/DebugInfoSelection.h>
#include <liblangutil/SourceReferenceFormatter.h>
#include <boost/algorithm/string.hpp>
#include <fstream>
using namespace solidity;
using namespace solidity::util;
using namespace solidity::langutil;
using namespace solidity::yul;
using namespace solidity::yul::test;
using namespace solidity::frontend;
using namespace solidity::frontend::test;
ObjectCompilerTest::ObjectCompilerTest(std::string const& _filename):
solidity::frontend::test::EVMVersionRestrictedTestCase(_filename)
{
m_source = m_reader.source();
m_optimisationPreset = m_reader.enumSetting<OptimisationPreset>(
"optimizationPreset",
{
{"none", OptimisationPreset::None},
{"minimal", OptimisationPreset::Minimal},
{"standard", OptimisationPreset::Standard},
{"full", OptimisationPreset::Full},
},
"minimal"
);
m_expectation = m_reader.simpleExpectations();
}
TestCase::TestResult ObjectCompilerTest::run(std::ostream& _stream, std::string const& _linePrefix, bool const _formatted)
{
YulStack stack(
solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion(),
YulStack::Language::StrictAssembly,
OptimiserSettings::preset(m_optimisationPreset),
DebugInfoSelection::All()
);
if (!stack.parseAndAnalyze("source", m_source))
{
AnsiColorized(_stream, _formatted, {formatting::BOLD, formatting::RED}) << _linePrefix << "Error parsing source." << std::endl;
SourceReferenceFormatter{_stream, stack, true, false}
.printErrorInformation(stack.errors());
return TestResult::FatalError;
}
stack.optimize();
MachineAssemblyObject obj = stack.assemble(YulStack::Machine::EVM);
solAssert(obj.bytecode, "");
solAssert(obj.sourceMappings, "");
m_obtainedResult = "Assembly:\n" + obj.assembly->assemblyString(stack.debugInfoSelection());
if (obj.bytecode->bytecode.empty())
m_obtainedResult += "-- empty bytecode --\n";
else
m_obtainedResult +=
"Bytecode: " +
util::toHex(obj.bytecode->bytecode) +
"\nOpcodes: " +
boost::trim_copy(evmasm::disassemble(obj.bytecode->bytecode, solidity::test::CommonOptions::get().evmVersion())) +
"\nSourceMappings:" +
(obj.sourceMappings->empty() ? "" : " " + *obj.sourceMappings) +
"\n";
return checkResult(_stream, _linePrefix, _formatted);
}
| 3,285
|
C++
|
.cpp
| 83
| 37.240964
| 129
| 0.765704
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,959
|
SyntaxTest.cpp
|
ethereum_solidity/test/libyul/SyntaxTest.cpp
|
/*
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
#include <libyul/AsmAnalysis.h>
#include <libyul/AsmAnalysisInfo.h>
#include <liblangutil/EVMVersion.h>
#include <liblangutil/Exceptions.h>
#include <test/libyul/Common.h>
#include <test/libyul/SyntaxTest.h>
#include <test/TestCaseReader.h>
#include <test/libsolidity/util/SoltestErrors.h>
#include <test/Common.h>
using namespace solidity;
using namespace solidity::util;
using namespace solidity::langutil;
using namespace solidity::yul::test;
using namespace solidity::frontend::test;
void SyntaxTest::parseAndAnalyze()
{
if (m_sources.sources.size() != 1)
BOOST_THROW_EXCEPTION(std::runtime_error{"Expected only one source for yul test."});
std::string const& name = m_sources.sources.begin()->first;
std::string const& source = m_sources.sources.begin()->second;
ErrorList errorList{};
soltestAssert(m_dialect, "");
// Silently ignoring the results.
yul::test::parse(source, *m_dialect, errorList);
for (auto const& error: errorList)
{
int locationStart = -1;
int locationEnd = -1;
if (SourceLocation const* location = error->sourceLocation())
{
locationStart = location->start;
locationEnd = location->end;
}
m_errorList.emplace_back(SyntaxTestError{
error->type(),
error->errorId(),
errorMessage(*error),
name,
locationStart,
locationEnd
});
}
}
SyntaxTest::SyntaxTest(std::string const& _filename, langutil::EVMVersion _evmVersion):
CommonSyntaxTest(_filename, _evmVersion)
{
std::string dialectName = m_reader.stringSetting("dialect", "evm");
m_dialect = &dialect(
dialectName,
solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion()
);
}
| 2,351
|
C++
|
.cpp
| 67
| 32.791045
| 87
| 0.764109
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,960
|
StackShufflingTest.cpp
|
ethereum_solidity/test/libyul/StackShufflingTest.cpp
|
/*
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/>.
*/
#include <test/libyul/StackShufflingTest.h>
#include <liblangutil/Scanner.h>
#include <libsolutil/AnsiColorized.h>
#include <libyul/backends/evm/StackHelpers.h>
using namespace solidity::util;
using namespace solidity::langutil;
using namespace solidity::yul;
using namespace solidity::yul::test;
bool StackShufflingTest::parse(std::string const& _source)
{
CharStream stream(_source, "");
Scanner scanner(stream);
auto expectToken = [&](Token _token)
{
soltestAssert(
scanner.next() == _token,
"Invalid token. Expected: \"" + TokenTraits::friendlyName(_token) + "\"."
);
};
auto parseStack = [&](Stack& stack) -> bool
{
if (scanner.currentToken() != Token::LBrack)
return false;
scanner.next();
while (scanner.currentToken() != Token::RBrack &&
scanner.currentToken() != Token::EOS)
{
std::string literal = scanner.currentLiteral();
if (literal == "RET")
{
scanner.next();
if (scanner.currentToken() == Token::LBrack)
{
scanner.next();
std::string functionName = scanner.currentLiteral();
auto call = yul::FunctionCall{
{}, yul::Identifier{{}, YulName(functionName)}, {}
};
stack.emplace_back(FunctionCallReturnLabelSlot{
m_functions.insert(
make_pair(functionName, call)
).first->second
});
expectToken(Token::RBrack);
}
else
{
static Scope::Function function;
stack.emplace_back(FunctionReturnLabelSlot{function});
continue;
}
}
else if (literal == "TMP")
{
expectToken(Token::LBrack);
scanner.next();
std::string functionName = scanner.currentLiteral();
auto call = yul::FunctionCall{
{}, yul::Identifier{{}, YulName(functionName)}, {}
};
expectToken(Token::Comma);
scanner.next();
size_t index = size_t(atoi(scanner.currentLiteral().c_str()));
stack.emplace_back(TemporarySlot{
m_functions.insert(make_pair(functionName, call)).first->second,
index
});
expectToken(Token::RBrack);
}
else if (literal.find("0x") != std::string::npos || scanner.currentToken() == Token::Number)
{
stack.emplace_back(LiteralSlot{u256(literal)});
}
else if (literal == "JUNK")
{
stack.emplace_back(JunkSlot());
}
else if (literal == "GHOST")
{
expectToken(Token::LBrack);
scanner.next(); // read number of ghost variables as ghostVariableId
std::string ghostVariableId = scanner.currentLiteral();
Scope::Variable ghostVar = Scope::Variable{YulName(literal + "[" + ghostVariableId + "]")};
stack.emplace_back(VariableSlot{
m_variables.insert(std::make_pair(ghostVar.name, ghostVar)).first->second
});
expectToken(Token::RBrack);
}
else
{
Scope::Variable var = Scope::Variable{YulName(literal)};
stack.emplace_back(VariableSlot{
m_variables.insert(
make_pair(literal, var)
).first->second
});
}
scanner.next();
}
return scanner.currentToken() == Token::RBrack;
};
if (!parseStack(m_sourceStack))
return false;
scanner.next();
return parseStack(m_targetStack);
}
StackShufflingTest::StackShufflingTest(std::string const& _filename):
TestCase(_filename)
{
m_source = m_reader.source();
m_expectation = m_reader.simpleExpectations();
}
TestCase::TestResult StackShufflingTest::run(std::ostream& _stream, std::string const& _linePrefix, bool _formatted)
{
if (!parse(m_source))
{
AnsiColorized(_stream, _formatted, {formatting::BOLD, formatting::RED}) << _linePrefix << "Error parsing source." << std::endl;
return TestResult::FatalError;
}
std::ostringstream output;
createStackLayout(
m_sourceStack,
m_targetStack,
[&](unsigned _swapDepth) // swap
{
output << stackToString(m_sourceStack) << std::endl;
output << "SWAP" << _swapDepth << std::endl;
},
[&](StackSlot const& _slot) // dupOrPush
{
output << stackToString(m_sourceStack) << std::endl;
if (canBeFreelyGenerated(_slot))
output << "PUSH " << stackSlotToString(_slot) << std::endl;
else
{
if (auto depth = util::findOffset(m_sourceStack | ranges::views::reverse, _slot))
output << "DUP" << *depth + 1 << std::endl;
else
BOOST_THROW_EXCEPTION(std::runtime_error("Invalid DUP operation."));
}
},
[&](){ // pop
output << stackToString(m_sourceStack) << std::endl;
output << "POP" << std::endl;
}
);
output << stackToString(m_sourceStack) << std::endl;
m_obtainedResult = output.str();
return checkResult(_stream, _linePrefix, _formatted);
}
| 5,199
|
C++
|
.cpp
| 163
| 27.90184
| 129
| 0.683529
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,961
|
Parser.cpp
|
ethereum_solidity/test/libyul/Parser.cpp
|
/*
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/>.
*/
/**
* @date 2017
* Unit tests for parsing Yul.
*/
#include <test/Common.h>
#include <test/libsolidity/ErrorCheck.h>
#include <test/libyul/Common.h>
#include <libyul/AST.h>
#include <libyul/AsmParser.h>
#include <libyul/AsmPrinter.h>
#include <libyul/AsmAnalysis.h>
#include <libyul/AsmAnalysisInfo.h>
#include <libyul/Dialect.h>
#include <liblangutil/ErrorReporter.h>
#include <boost/algorithm/string/replace.hpp>
#include <boost/test/data/monomorphic.hpp>
#include <boost/test/data/test_case.hpp>
#include <boost/test/unit_test.hpp>
#include <memory>
#include <optional>
#include <string>
using namespace solidity;
using namespace solidity::util;
using namespace solidity::langutil;
BOOST_TEST_DONT_PRINT_LOG_VALUE(ErrorId)
BOOST_TEST_DONT_PRINT_LOG_VALUE(Error::Type)
namespace solidity::yul::test
{
namespace
{
std::shared_ptr<AST> parse(std::string const& _source, Dialect const& _dialect, ErrorReporter& errorReporter)
{
auto stream = CharStream(_source, "");
std::map<unsigned, std::shared_ptr<std::string const>> indicesToSourceNames;
indicesToSourceNames[0] = std::make_shared<std::string const>("source0");
indicesToSourceNames[1] = std::make_shared<std::string const>("source1");
auto parserResult = yul::Parser(
errorReporter,
_dialect,
std::move(indicesToSourceNames)
).parse(stream);
if (parserResult)
{
yul::AsmAnalysisInfo analysisInfo;
if (yul::AsmAnalyzer(
analysisInfo,
errorReporter,
_dialect
).analyze(parserResult->root()))
return parserResult;
}
return {};
}
std::optional<Error> parseAndReturnFirstError(std::string const& _source, Dialect const& _dialect, bool _allowWarningsAndInfos = true)
{
ErrorList errors;
ErrorReporter errorReporter(errors);
if (!parse(_source, _dialect, errorReporter))
{
BOOST_REQUIRE(!errors.empty());
BOOST_CHECK_EQUAL(errors.size(), 1);
return *errors.front();
}
else
{
// If success is true, there might still be an error in the assembly stage.
if (_allowWarningsAndInfos && !Error::containsErrors(errors))
return {};
else if (!errors.empty())
{
if (!_allowWarningsAndInfos)
BOOST_CHECK_EQUAL(errors.size(), 1);
return *errors.front();
}
}
return {};
}
bool successParse(std::string const& _source, Dialect const& _dialect, bool _allowWarningsAndInfos = true)
{
return !parseAndReturnFirstError(_source, _dialect, _allowWarningsAndInfos);
}
Error expectError(std::string const& _source, Dialect const& _dialect, bool _allowWarningsAndInfos = false)
{
auto error = parseAndReturnFirstError(_source, _dialect, _allowWarningsAndInfos);
BOOST_REQUIRE(error);
return *error;
}
}
#define CHECK_ERROR_DIALECT(text, typ, substring, dialect) \
do \
{ \
Error err = expectError((text), dialect, false); \
BOOST_CHECK(err.type() == (Error::Type::typ)); \
BOOST_CHECK(solidity::frontend::test::searchErrorMessage(err, (substring))); \
} while(0)
#define CHECK_ERROR(text, typ, substring) CHECK_ERROR_DIALECT(text, typ, substring, Dialect::yulDeprecated())
BOOST_AUTO_TEST_SUITE(YulParser)
BOOST_AUTO_TEST_CASE(builtins_analysis)
{
struct SimpleDialect: Dialect
{
std::optional<BuiltinHandle> findBuiltin(std::string_view _name) const override
{
if (_name == "builtin")
return BuiltinHandle{std::numeric_limits<size_t>::max()};
return std::nullopt;
}
BuiltinFunction const& builtin(BuiltinHandle const& handle) const override
{
BOOST_REQUIRE(handle.id == std::numeric_limits<size_t>::max());
return f;
}
BuiltinFunction f{"builtin", 2, 3, {}, {}, false, {}};
};
SimpleDialect dialect;
BOOST_CHECK(successParse("{ let a, b, c := builtin(1, 2) }", dialect));
CHECK_ERROR_DIALECT("{ let a, b, c := builtin(1) }", TypeError, "Function \"builtin\" expects 2 arguments but got 1", dialect);
CHECK_ERROR_DIALECT("{ let a, b := builtin(1, 2) }", DeclarationError, "Variable count mismatch for declaration of \"a, b\": 2 variables and 3 values.", dialect);
}
#define CHECK_LOCATION(_actual, _sourceName, _start, _end) \
do { \
BOOST_CHECK_EQUAL((_sourceName), ((_actual).sourceName ? *(_actual).sourceName : "")); \
BOOST_CHECK_EQUAL((_start), (_actual).start); \
BOOST_CHECK_EQUAL((_end), (_actual).end); \
} while (0)
BOOST_AUTO_TEST_CASE(customSourceLocations_empty_block)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText =
"/// @src 0:234:543\n"
"{}\n";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result && errorList.size() == 0);
CHECK_LOCATION(result->root().debugData->originLocation, "source0", 234, 543);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_block_with_children)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText =
"/// @src 0:234:543\n"
"{\n"
"let x := true\n"
"/// @src 0:123:432\n"
"let z := true\n"
"let y := add(1, 2)\n"
"}\n";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result);
CHECK_LOCATION(result->root().debugData->originLocation, "source0", 234, 543);
BOOST_REQUIRE_EQUAL(3, result->root().statements.size());
CHECK_LOCATION(originLocationOf(result->root().statements.at(0)), "source0", 234, 543);
CHECK_LOCATION(originLocationOf(result->root().statements.at(1)), "source0", 123, 432);
// [2] is inherited source location
CHECK_LOCATION(originLocationOf(result->root().statements.at(2)), "source0", 123, 432);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_block_different_sources)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText =
"/// @src 0:234:543\n"
"{\n"
"let x := true\n"
"/// @src 1:123:432\n"
"let z := true\n"
"let y := add(1, 2)\n"
"}\n";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result && errorList.size() == 0);
CHECK_LOCATION(result->root().debugData->originLocation, "source0", 234, 543);
BOOST_REQUIRE_EQUAL(3, result->root().statements.size());
CHECK_LOCATION(originLocationOf(result->root().statements.at(0)), "source0", 234, 543);
CHECK_LOCATION(originLocationOf(result->root().statements.at(1)), "source1", 123, 432);
// [2] is inherited source location
CHECK_LOCATION(originLocationOf(result->root().statements.at(2)), "source1", 123, 432);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_block_nested)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText =
"/// @src 0:234:543\n"
"{\n"
"let y := add(1, 2)\n"
"/// @src 0:343:434\n"
"switch y case 0 {} default {}\n"
"}\n";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result && errorList.size() == 0);
CHECK_LOCATION(result->root().debugData->originLocation, "source0", 234, 543);
BOOST_REQUIRE_EQUAL(2, result->root().statements.size());
CHECK_LOCATION(originLocationOf(result->root().statements.at(1)), "source0", 343, 434);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_block_switch_case)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText =
"/// @src 0:234:543\n"
"{\n"
"let y := add(1, 2)\n"
"/// @src 0:343:434\n"
"switch y\n"
"/// @src 0:3141:59265\n"
"case 0 {\n"
" /// @src 0:271:828\n"
" let z := add(3, 4)\n"
"}\n"
"}\n";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result && errorList.size() == 0);
CHECK_LOCATION(result->root().debugData->originLocation, "source0", 234, 543);
BOOST_REQUIRE_EQUAL(2, result->root().statements.size());
BOOST_REQUIRE(std::holds_alternative<Switch>(result->root().statements.at(1)));
auto const& switchStmt = std::get<Switch>(result->root().statements.at(1));
CHECK_LOCATION(switchStmt.debugData->originLocation, "source0", 343, 434);
BOOST_REQUIRE_EQUAL(1, switchStmt.cases.size());
CHECK_LOCATION(switchStmt.cases.at(0).debugData->originLocation, "source0", 3141, 59265);
auto const& caseBody = switchStmt.cases.at(0).body;
BOOST_REQUIRE_EQUAL(1, caseBody.statements.size());
CHECK_LOCATION(originLocationOf(caseBody.statements.at(0)), "source0", 271, 828);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_inherit_into_outer_scope)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText =
"/// @src 0:1:100\n"
"{\n"
"{\n"
"/// @src 0:123:432\n"
"let x := true\n"
"}\n"
"let z := true\n"
"let y := add(1, 2)\n"
"}\n";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result && errorList.size() == 0);
CHECK_LOCATION(result->root().debugData->originLocation, "source0", 1, 100);
BOOST_REQUIRE_EQUAL(3, result->root().statements.size());
CHECK_LOCATION(originLocationOf(result->root().statements.at(0)), "source0", 1, 100);
// First child element must be a block itself with one statement.
BOOST_REQUIRE(std::holds_alternative<Block>(result->root().statements.at(0)));
BOOST_REQUIRE_EQUAL(std::get<Block>(result->root().statements.at(0)).statements.size(), 1);
CHECK_LOCATION(originLocationOf(std::get<Block>(result->root().statements.at(0)).statements.at(0)), "source0", 123, 432);
// The next two elements have an inherited source location from the prior inner scope.
CHECK_LOCATION(originLocationOf(result->root().statements.at(1)), "source0", 123, 432);
CHECK_LOCATION(originLocationOf(result->root().statements.at(2)), "source0", 123, 432);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_assign_empty)
{
// Tests single AST node (e.g. VariableDeclaration) with different source locations for each child.
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText =
"{\n"
"/// @src 0:123:432\n"
"let a\n"
"/// @src 1:1:10\n"
"a := true\n"
"}\n";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result && errorList.size() == 0); // should still parse
BOOST_REQUIRE_EQUAL(2, result->root().statements.size());
CHECK_LOCATION(originLocationOf(result->root().statements.at(0)), "source0", 123, 432);
CHECK_LOCATION(originLocationOf(result->root().statements.at(1)), "source1", 1, 10);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_invalid_source_index)
{
// Tests single AST node (e.g. VariableDeclaration) with different source locations for each child.
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText =
"{\n"
"/// @src 1:123:432\n"
"let a := true\n"
"/// @src 2345:0:8\n"
"let b := true\n"
"\n"
"}\n";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result); // should still parse
BOOST_REQUIRE(errorList.size() == 1);
BOOST_TEST(errorList[0]->type() == Error::Type::SyntaxError);
BOOST_TEST(errorList[0]->errorId() == 2674_error);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_mixed_locations_1)
{
// Tests single AST node (e.g. VariableDeclaration) with different source locations for each child.
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText =
"{\n"
"/// @src 0:123:432\n"
"let x \n"
"/// @src 0:234:2026\n"
":= true\n"
"}\n";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result && errorList.size() == 0);
BOOST_REQUIRE_EQUAL(1, result->root().statements.size());
CHECK_LOCATION(originLocationOf(result->root().statements.at(0)), "source0", 123, 432);
BOOST_REQUIRE(std::holds_alternative<VariableDeclaration>(result->root().statements.at(0)));
VariableDeclaration const& varDecl = std::get<VariableDeclaration>(result->root().statements.at(0));
CHECK_LOCATION(originLocationOf(*varDecl.value), "source0", 234, 2026);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_mixed_locations_2)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @src 0:0:5
{
let x := /// @src 1:2:3
add(1, /// @src 0:4:8
2)
}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result && errorList.size() == 0);
BOOST_REQUIRE_EQUAL(1, result->root().statements.size());
CHECK_LOCATION(result->root().debugData->originLocation, "source0", 0, 5);
// `let x := add(1, `
BOOST_REQUIRE(std::holds_alternative<VariableDeclaration>(result->root().statements.at(0)));
VariableDeclaration const& varDecl = std::get<VariableDeclaration>(result->root().statements.at(0));
CHECK_LOCATION(varDecl.debugData->originLocation, "source0", 0, 5);
BOOST_REQUIRE(!!varDecl.value);
BOOST_REQUIRE(std::holds_alternative<FunctionCall>(*varDecl.value));
FunctionCall const& call = std::get<FunctionCall>(*varDecl.value);
CHECK_LOCATION(call.debugData->originLocation, "source1", 2, 3);
// `2`
BOOST_REQUIRE_EQUAL(2, call.arguments.size());
CHECK_LOCATION(originLocationOf(call.arguments.at(1)), "source0", 4, 8);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_mixed_locations_3)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @src 1:23:45
{ // Block
{ // Block
sstore(0, 1) // FunctionCall
/// @src 0:420:680
}
mstore(1, 2) // FunctionCall
}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result && errorList.size() == 0);
BOOST_REQUIRE_EQUAL(2, result->root().statements.size());
CHECK_LOCATION(result->root().debugData->originLocation, "source1", 23, 45);
BOOST_REQUIRE(std::holds_alternative<Block>(result->root().statements.at(0)));
Block const& innerBlock = std::get<Block>(result->root().statements.at(0));
CHECK_LOCATION(innerBlock.debugData->originLocation, "source1", 23, 45);
BOOST_REQUIRE_EQUAL(1, innerBlock.statements.size());
BOOST_REQUIRE(std::holds_alternative<ExpressionStatement>(result->root().statements.at(1)));
ExpressionStatement const& sstoreStmt = std::get<ExpressionStatement>(innerBlock.statements.at(0));
BOOST_REQUIRE(std::holds_alternative<FunctionCall>(sstoreStmt.expression));
FunctionCall const& sstoreCall = std::get<FunctionCall>(sstoreStmt.expression);
CHECK_LOCATION(sstoreCall.debugData->originLocation, "source1", 23, 45);
BOOST_REQUIRE(std::holds_alternative<ExpressionStatement>(result->root().statements.at(1)));
ExpressionStatement mstoreStmt = std::get<ExpressionStatement>(result->root().statements.at(1));
BOOST_REQUIRE(std::holds_alternative<FunctionCall>(mstoreStmt.expression));
FunctionCall const& mstoreCall = std::get<FunctionCall>(mstoreStmt.expression);
CHECK_LOCATION(mstoreCall.debugData->originLocation, "source0", 420, 680);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_invalid_comments_after_valid)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @src 1:23:45
{
/// @src 0:420:680
/// @invalid
let a := true
}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result && errorList.size() == 0);
BOOST_REQUIRE_EQUAL(1, result->root().statements.size());
CHECK_LOCATION(result->root().debugData->originLocation, "source1", 23, 45);
BOOST_REQUIRE(std::holds_alternative<VariableDeclaration>(result->root().statements.at(0)));
VariableDeclaration const& varDecl = std::get<VariableDeclaration>(result->root().statements.at(0));
CHECK_LOCATION(varDecl.debugData->originLocation, "source0", 420, 680);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_invalid_suffix)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @src 0:420:680foo
{}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result);
BOOST_REQUIRE(errorList.size() == 1);
BOOST_TEST(errorList[0]->type() == Error::Type::SyntaxError);
BOOST_TEST(errorList[0]->errorId() == 8387_error);
CHECK_LOCATION(result->root().debugData->originLocation, "", -1, -1);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_invalid_prefix)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// abc@src 0:111:222
{}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result && errorList.size() == 0);
CHECK_LOCATION(result->root().debugData->originLocation, "", -1, -1);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_unspecified)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @src -1:-1:-1
{}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result && errorList.size() == 0);
CHECK_LOCATION(result->root().debugData->originLocation, "", -1, -1);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_non_integer)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @src a:b:c
{}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result);
BOOST_REQUIRE(errorList.size() == 1);
BOOST_TEST(errorList[0]->type() == Error::Type::SyntaxError);
BOOST_TEST(errorList[0]->errorId() == 8387_error);
CHECK_LOCATION(result->root().debugData->originLocation, "", -1, -1);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_bad_integer)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @src 111111111111111111111:222222222222222222222:333333333333333333333
{}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result);
BOOST_REQUIRE(errorList.size() == 1);
BOOST_TEST(errorList[0]->type() == Error::Type::SyntaxError);
BOOST_TEST(errorList[0]->errorId() == 6367_error);
CHECK_LOCATION(result->root().debugData->originLocation, "", -1, -1);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_ensure_last_match)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @src 0:123:432
{
/// @src 1:10:20
/// @src 0:30:40
let x := true
}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result && errorList.size() == 0);
BOOST_REQUIRE(std::holds_alternative<VariableDeclaration>(result->root().statements.at(0)));
VariableDeclaration const& varDecl = std::get<VariableDeclaration>(result->root().statements.at(0));
// Ensure the latest @src per documentation-comment is used (0:30:40).
CHECK_LOCATION(varDecl.debugData->originLocation, "source0", 30, 40);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_two_locations_no_whitespace)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @src 0:111:222@src 1:333:444
{}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result);
BOOST_REQUIRE(errorList.size() == 1);
BOOST_TEST(errorList[0]->type() == Error::Type::SyntaxError);
BOOST_TEST(errorList[0]->errorId() == 8387_error);
CHECK_LOCATION(result->root().debugData->originLocation, "", -1, -1);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_two_locations_separated_with_single_space)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @src 0:111:222 @src 1:333:444
{}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result && errorList.size() == 0);
CHECK_LOCATION(result->root().debugData->originLocation, "source1", 333, 444);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_leading_trailing_whitespace)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = "/// @src 0:111:222 \n{}";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result && errorList.size() == 0);
CHECK_LOCATION(result->root().debugData->originLocation, "source0", 111, 222);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_reference_original_sloc)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @src 1:2:3
{
/// @src -1:10:20
let x := true
}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result && errorList.size() == 0);
BOOST_REQUIRE(std::holds_alternative<VariableDeclaration>(result->root().statements.at(0)));
VariableDeclaration const& varDecl = std::get<VariableDeclaration>(result->root().statements.at(0));
// -1 points to original source code, which in this case is `"source0"` (which is also
CHECK_LOCATION(varDecl.debugData->originLocation, "", 10, 20);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_with_code_snippets)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"~~~(
{
/// @src 0:149:156 "new C(\"123\")"
let x := 123
let y := /** @src 1:96:165 "contract D {..." */ 128
}
)~~~";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result && errorList.size() == 0);
BOOST_REQUIRE_EQUAL(result->root().statements.size(), 2);
BOOST_REQUIRE(std::holds_alternative<VariableDeclaration>(result->root().statements.at(0)));
VariableDeclaration const& varX = std::get<VariableDeclaration>(result->root().statements.at(0));
CHECK_LOCATION(varX.debugData->originLocation, "source0", 149, 156);
BOOST_REQUIRE(std::holds_alternative<VariableDeclaration>(result->root().statements.at(1)));
VariableDeclaration const& varY = std::get<VariableDeclaration>(result->root().statements.at(1));
BOOST_REQUIRE(!!varY.value);
BOOST_REQUIRE(std::holds_alternative<Literal>(*varY.value));
Literal const& literal128 = std::get<Literal>(*varY.value);
CHECK_LOCATION(literal128.debugData->originLocation, "source1", 96, 165);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_with_code_snippets_empty_snippet)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @src 0:111:222 ""
{}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result && errorList.size() == 0);
CHECK_LOCATION(result->root().debugData->originLocation, "source0", 111, 222);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_with_code_snippets_no_whitespace_before_snippet)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @src 0:111:222"abc" def
{}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result);
BOOST_REQUIRE(errorList.size() == 1);
BOOST_TEST(errorList[0]->type() == Error::Type::SyntaxError);
BOOST_TEST(errorList[0]->errorId() == 8387_error);
CHECK_LOCATION(result->root().debugData->originLocation, "", -1, -1);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_with_code_snippets_no_whitespace_after_snippet)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @src 0:111:222 "abc"def
{}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result && errorList.size() == 0);
CHECK_LOCATION(result->root().debugData->originLocation, "source0", 111, 222);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_two_locations_with_snippets_no_whitespace)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @src 0:111:222 "abc"@src 1:333:444 "abc"
{}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result && errorList.size() == 0);
CHECK_LOCATION(result->root().debugData->originLocation, "source1", 333, 444);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_two_locations_with_snippets_unterminated_quote)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @src 0:111:222 " abc @src 1:333:444
{}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result);
BOOST_REQUIRE(errorList.size() == 1);
BOOST_TEST(errorList[0]->type() == Error::Type::SyntaxError);
BOOST_TEST(errorList[0]->errorId() == 1544_error);
CHECK_LOCATION(result->root().debugData->originLocation, "", -1, -1);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_single_quote)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @src 0:111:222 "
///
{}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result);
BOOST_REQUIRE(errorList.size() == 1);
BOOST_TEST(errorList[0]->type() == Error::Type::SyntaxError);
BOOST_TEST(errorList[0]->errorId() == 1544_error);
CHECK_LOCATION(result->root().debugData->originLocation, "", -1, -1);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_two_snippets_with_hex_comment)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @src 0:111:222 hex"abc"@src 1:333:444 "abc"
{}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result && errorList.size() == 0);
// the second source location is not parsed as such, as the hex string isn't interpreted as snippet but
// as the beginning of the tail in AsmParser
CHECK_LOCATION(result->root().debugData->originLocation, "source0", 111, 222);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_invalid_escapes)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @src 0:111:222 "\n\\x\x\w\uö\xy\z\y\fq"
{}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result && errorList.size() == 0);
CHECK_LOCATION(result->root().debugData->originLocation, "source0", 111, 222);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_single_quote_snippet_with_whitespaces_and_escapes)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @src 0:111:222 '\n\\x\x\w\uö\xy\z\y\fq'
/// @src 1 : 222 : 333 '\x33\u1234\t\n'
{}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result && errorList.size() == 0);
CHECK_LOCATION(result->root().debugData->originLocation, "source1", 222, 333);
}
BOOST_DATA_TEST_CASE(customSourceLocations_scanner_errors_outside_string_lits_are_ignored, boost::unit_test::data::make({"0x ", "/** unterminated comment", "1_23_4"}), invalid)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = fmt::format(R"(
/// @src 0:111:222 {}
/// @src 1:222:333
{{}}
)", invalid);
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result && errorList.empty());
CHECK_LOCATION(result->root().debugData->originLocation, "source1", 222, 333);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_multi_line_source_loc)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @src 1 : 111:
/// 222 "
/// abc\"def
///
/// " @src 0:333:444
{}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result && errorList.empty());
CHECK_LOCATION(result->root().debugData->originLocation, "source0", 333, 444);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_with_code_snippets_with_nested_locations)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"~~~(
{
/// @src 0:149:156 "new C(\"123\") /// @src 1:3:4 "
let x := 123
let y := /** @src 1:96:165 "function f() internal { \"\/** @src 0:6:7 *\/\"; }" */ 128
}
)~~~";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result && errorList.size() == 0);
BOOST_REQUIRE_EQUAL(result->root().statements.size(), 2);
BOOST_REQUIRE(std::holds_alternative<VariableDeclaration>(result->root().statements.at(0)));
VariableDeclaration const& varX = std::get<VariableDeclaration>(result->root().statements.at(0));
CHECK_LOCATION(varX.debugData->originLocation, "source0", 149, 156);
BOOST_REQUIRE(std::holds_alternative<VariableDeclaration>(result->root().statements.at(1)));
VariableDeclaration const& varY = std::get<VariableDeclaration>(result->root().statements.at(1));
BOOST_REQUIRE(!!varY.value);
BOOST_REQUIRE(std::holds_alternative<Literal>(*varY.value));
Literal const& literal128 = std::get<Literal>(*varY.value);
CHECK_LOCATION(literal128.debugData->originLocation, "source1", 96, 165);
}
BOOST_AUTO_TEST_CASE(astid)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @src -1:-1:-1 @ast-id 7
{
/** @ast-id 2 */
function f(x) -> y {}
mstore(1, 2)
}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result);
BOOST_CHECK(result->root().debugData->astID == int64_t(7));
auto const& funDef = std::get<FunctionDefinition>(result->root().statements.at(0));
BOOST_CHECK(funDef.debugData->astID == int64_t(2));
BOOST_CHECK(funDef.parameters.at(0).debugData->astID == std::nullopt);
BOOST_CHECK(debugDataOf(result->root().statements.at(1))->astID == std::nullopt);
}
BOOST_AUTO_TEST_CASE(astid_reset)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @src -1:-1:-1 @ast-id 7 @src 1:1:1
{
/** @ast-id 2 */
function f(x) -> y {}
mstore(1, 2)
}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result);
BOOST_CHECK(result->root().debugData->astID == int64_t(7));
auto const& funDef = std::get<FunctionDefinition>(result->root().statements.at(0));
BOOST_CHECK(funDef.debugData->astID == int64_t(2));
BOOST_CHECK(funDef.parameters.at(0).debugData->astID == std::nullopt);
BOOST_CHECK(debugDataOf(result->root().statements.at(1))->astID == std::nullopt);
}
BOOST_AUTO_TEST_CASE(astid_multi)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @src -1:-1:-1 @ast-id 7 @src 1:1:1 @ast-id 8
{}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result);
BOOST_CHECK(result->root().debugData->astID == int64_t(8));
}
BOOST_AUTO_TEST_CASE(astid_invalid)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @src -1:-1:-1 @ast-id abc @src 1:1:1
{}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result);
BOOST_REQUIRE(errorList.size() == 1);
BOOST_TEST(errorList[0]->type() == Error::Type::SyntaxError);
BOOST_TEST(errorList[0]->errorId() == 1749_error);
CHECK_LOCATION(result->root().debugData->originLocation, "", -1, -1);
}
BOOST_AUTO_TEST_CASE(astid_too_large)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @ast-id 9223372036854775808
{}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result);
BOOST_REQUIRE(errorList.size() == 1);
BOOST_TEST(errorList[0]->type() == Error::Type::SyntaxError);
BOOST_TEST(errorList[0]->errorId() == 1749_error);
}
BOOST_AUTO_TEST_CASE(astid_way_too_large)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @ast-id 999999999999999999999999999999999999999
{}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result);
BOOST_REQUIRE(errorList.size() == 1);
BOOST_TEST(errorList[0]->type() == Error::Type::SyntaxError);
BOOST_TEST(errorList[0]->errorId() == 1749_error);
}
BOOST_AUTO_TEST_CASE(astid_not_fully_numeric)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText = R"(
/// @ast-id 9x
{}
)";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result);
BOOST_REQUIRE(errorList.size() == 1);
BOOST_TEST(errorList[0]->type() == Error::Type::SyntaxError);
BOOST_TEST(errorList[0]->errorId() == 1749_error);
}
BOOST_AUTO_TEST_CASE(customSourceLocations_multiple_src_tags_on_one_line)
{
ErrorList errorList;
ErrorReporter reporter(errorList);
auto const sourceText =
"{\n"
" /// "
R"~~(@src 1:2:3 ""@src 1:2:4 @src-1:2:5@src 1:2:6 @src 1:2:7 "" @src 1:2:8)~~"
R"~~( X "@src 0:10:20 "new C(\"123\") /// @src 1:4:5 "" XYZ)~~"
R"~~( @src0:20:30 "abc"@src0:2:4 @src-0:2:5@)~~"
R"~~( @some text with random @ signs @@@ @- @** 1:6:7 "src 1:8:9")~~"
"\n"
" let x := 123\n"
"}\n";
auto const& dialect = EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
std::shared_ptr<AST> result = parse(sourceText, dialect, reporter);
BOOST_REQUIRE(!!result && errorList.size() == 0);
BOOST_REQUIRE_EQUAL(result->root().statements.size(), 1);
BOOST_REQUIRE(std::holds_alternative<VariableDeclaration>(result->root().statements.at(0)));
VariableDeclaration const& varX = std::get<VariableDeclaration>(result->root().statements.at(0));
CHECK_LOCATION(varX.debugData->originLocation, "source1", 4, 5);
}
BOOST_AUTO_TEST_SUITE_END()
} // end namespaces
| 40,176
|
C++
|
.cpp
| 960
| 39.546875
| 176
| 0.725639
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,962
|
EVMCodeTransformTest.cpp
|
ethereum_solidity/test/libyul/EVMCodeTransformTest.cpp
|
/*
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
#include <test/libyul/EVMCodeTransformTest.h>
#include <test/libyul/Common.h>
#include <test/Common.h>
#include <libyul/YulStack.h>
#include <libyul/backends/evm/EthAssemblyAdapter.h>
#include <libyul/backends/evm/EVMObjectCompiler.h>
#include <libevmasm/Assembly.h>
#include <liblangutil/SourceReferenceFormatter.h>
#include <libsolutil/AnsiColorized.h>
using namespace solidity;
using namespace solidity::util;
using namespace solidity::langutil;
using namespace solidity::yul;
using namespace solidity::yul::test;
using namespace solidity::frontend;
using namespace solidity::frontend::test;
EVMCodeTransformTest::EVMCodeTransformTest(std::string const& _filename):
EVMVersionRestrictedTestCase(_filename)
{
m_source = m_reader.source();
m_stackOpt = m_reader.boolSetting("stackOptimization", false);
m_expectation = m_reader.simpleExpectations();
}
TestCase::TestResult EVMCodeTransformTest::run(std::ostream& _stream, std::string const& _linePrefix, bool const _formatted)
{
solidity::frontend::OptimiserSettings settings = solidity::frontend::OptimiserSettings::none();
settings.runYulOptimiser = false;
settings.optimizeStackAllocation = m_stackOpt;
YulStack stack(
EVMVersion{},
std::nullopt,
YulStack::Language::StrictAssembly,
settings,
DebugInfoSelection::All()
);
if (!stack.parseAndAnalyze("", m_source))
{
AnsiColorized(_stream, _formatted, {formatting::BOLD, formatting::RED}) << _linePrefix << "Error parsing source." << std::endl;
SourceReferenceFormatter{_stream, stack, true, false}
.printErrorInformation(stack.errors());
return TestResult::FatalError;
}
evmasm::Assembly assembly{solidity::test::CommonOptions::get().evmVersion(), false, std::nullopt, {}};
EthAssemblyAdapter adapter(assembly);
EVMObjectCompiler::compile(
*stack.parserResult(),
adapter,
EVMDialect::strictAssemblyForEVMObjects(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion()),
m_stackOpt,
std::nullopt
);
std::ostringstream output;
output << assembly;
m_obtainedResult = output.str();
return checkResult(_stream, _linePrefix, _formatted);
}
| 2,832
|
C++
|
.cpp
| 71
| 37.788732
| 129
| 0.786963
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,963
|
ControlFlowSideEffectsTest.cpp
|
ethereum_solidity/test/libyul/ControlFlowSideEffectsTest.cpp
|
/*
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
#include <test/libyul/ControlFlowSideEffectsTest.h>
#include <test/Common.h>
#include <test/libyul/Common.h>
#include <libyul/Object.h>
#include <libyul/AST.h>
#include <libyul/ControlFlowSideEffects.h>
#include <libyul/ControlFlowSideEffectsCollector.h>
#include <libyul/backends/evm/EVMDialect.h>
using namespace solidity;
using namespace solidity::yul;
using namespace solidity::yul::test;
using namespace solidity::frontend::test;
namespace
{
std::string toString(ControlFlowSideEffects const& _sideEffects)
{
std::vector<std::string> r;
if (_sideEffects.canTerminate)
r.emplace_back("can terminate");
if (_sideEffects.canRevert)
r.emplace_back("can revert");
if (_sideEffects.canContinue)
r.emplace_back("can continue");
return util::joinHumanReadable(r);
}
}
ControlFlowSideEffectsTest::ControlFlowSideEffectsTest(std::string const& _filename):
TestCase(_filename)
{
m_source = m_reader.source();
m_expectation = m_reader.simpleExpectations();
}
TestCase::TestResult ControlFlowSideEffectsTest::run(std::ostream& _stream, std::string const& _linePrefix, bool _formatted)
{
auto const& dialect = EVMDialect::strictAssemblyForEVMObjects(
solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion()
);
Object obj{dialect};
auto parsingResult = yul::test::parse(m_source);
obj.setCode(parsingResult.first, parsingResult.second);
if (!obj.hasCode())
BOOST_THROW_EXCEPTION(std::runtime_error("Parsing input failed."));
ControlFlowSideEffectsCollector sideEffects(
dialect,
obj.code()->root()
);
m_obtainedResult.clear();
forEach<FunctionDefinition const>(obj.code()->root(), [&](FunctionDefinition const& _fun) {
std::string effectStr = toString(sideEffects.functionSideEffects().at(&_fun));
m_obtainedResult += _fun.name.str() + (effectStr.empty() ? ":" : ": " + effectStr) + "\n";
});
return checkResult(_stream, _linePrefix, _formatted);
}
| 2,618
|
C++
|
.cpp
| 68
| 36.573529
| 124
| 0.773838
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,966
|
YulOptimizerTestCommon.cpp
|
ethereum_solidity/test/libyul/YulOptimizerTestCommon.cpp
|
/*
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
#include <test/libyul/YulOptimizerTestCommon.h>
#include <libyul/optimiser/BlockFlattener.h>
#include <libyul/optimiser/VarDeclInitializer.h>
#include <libyul/optimiser/VarNameCleaner.h>
#include <libyul/optimiser/ControlFlowSimplifier.h>
#include <libyul/optimiser/DeadCodeEliminator.h>
#include <libyul/optimiser/Disambiguator.h>
#include <libyul/optimiser/CircularReferencesPruner.h>
#include <libyul/optimiser/ConditionalUnsimplifier.h>
#include <libyul/optimiser/ConditionalSimplifier.h>
#include <libyul/optimiser/CommonSubexpressionEliminator.h>
#include <libyul/optimiser/EqualStoreEliminator.h>
#include <libyul/optimiser/EquivalentFunctionCombiner.h>
#include <libyul/optimiser/ExpressionSplitter.h>
#include <libyul/optimiser/FunctionGrouper.h>
#include <libyul/optimiser/FunctionHoister.h>
#include <libyul/optimiser/FunctionSpecializer.h>
#include <libyul/optimiser/ExpressionInliner.h>
#include <libyul/optimiser/FullInliner.h>
#include <libyul/optimiser/ForLoopConditionIntoBody.h>
#include <libyul/optimiser/ForLoopInitRewriter.h>
#include <libyul/optimiser/LoadResolver.h>
#include <libyul/optimiser/LoopInvariantCodeMotion.h>
#include <libyul/optimiser/StackLimitEvader.h>
#include <libyul/optimiser/NameDisplacer.h>
#include <libyul/optimiser/Rematerialiser.h>
#include <libyul/optimiser/ExpressionSimplifier.h>
#include <libyul/optimiser/UnusedFunctionParameterPruner.h>
#include <libyul/optimiser/UnusedPruner.h>
#include <libyul/optimiser/ExpressionJoiner.h>
#include <libyul/optimiser/OptimiserStep.h>
#include <libyul/optimiser/SSAReverser.h>
#include <libyul/optimiser/SSATransform.h>
#include <libyul/optimiser/Semantics.h>
#include <libyul/optimiser/UnusedAssignEliminator.h>
#include <libyul/optimiser/UnusedStoreEliminator.h>
#include <libyul/optimiser/StructuralSimplifier.h>
#include <libyul/optimiser/StackCompressor.h>
#include <libyul/optimiser/Suite.h>
#include <libyul/backends/evm/ConstantOptimiser.h>
#include <libyul/backends/evm/EVMDialect.h>
#include <libyul/backends/evm/EVMMetrics.h>
#include <libyul/AsmAnalysis.h>
#include <libyul/CompilabilityChecker.h>
#include <libsolidity/interface/OptimiserSettings.h>
#include <random>
using namespace solidity;
using namespace solidity::util;
using namespace solidity::langutil;
using namespace solidity::yul;
using namespace solidity::yul::test;
using namespace solidity::frontend;
YulOptimizerTestCommon::YulOptimizerTestCommon(
std::shared_ptr<Object const> _obj,
Dialect const& _dialect
): m_dialect(&_dialect), m_object(_obj), m_optimizedObject(std::make_shared<Object>(*_obj))
{
if (
std::any_of(
m_object->subObjects.begin(),
m_object->subObjects.end(),
[](auto const& subObject) { return dynamic_cast<Data*>(subObject.get()) == nullptr;}
)
)
solUnimplementedAssert(false, "The current implementation of YulOptimizerTests ignores subobjects that are not Data.");
m_namedSteps = {
{"disambiguator", [&]() { return disambiguate(); }},
{"nameDisplacer", [&]() {
auto block = disambiguate();
updateContext(block);
NameDisplacer{
*m_nameDispenser,
{"illegal1"_yulname, "illegal2"_yulname, "illegal3"_yulname, "illegal4"_yulname, "illegal5"_yulname}
}(block);
return block;
}},
{"blockFlattener", [&]() {
auto block = disambiguate();
updateContext(block);
FunctionGrouper::run(*m_context, block);
BlockFlattener::run(*m_context, block);
return block;
}},
{"constantOptimiser", [&]() {
auto block = std::get<Block>(ASTCopier{}(m_object->code()->root()));
updateContext(block);
GasMeter meter(dynamic_cast<EVMDialect const&>(*m_dialect), false, 200);
ConstantOptimiser{dynamic_cast<EVMDialect const&>(*m_dialect), meter}(block);
return block;
}},
{"varDeclInitializer", [&]() {
auto block = std::get<Block>(ASTCopier{}(m_object->code()->root()));
updateContext(block);
VarDeclInitializer::run(*m_context, block);
return block;
}},
{"varNameCleaner", [&]() {
auto block = disambiguate();
updateContext(block);
FunctionHoister::run(*m_context, block);
FunctionGrouper::run(*m_context, block);
VarNameCleaner::run(*m_context, block);
return block;
}},
{"forLoopConditionIntoBody", [&]() {
auto block = disambiguate();
updateContext(block);
ForLoopConditionIntoBody::run(*m_context, block);
return block;
}},
{"forLoopInitRewriter", [&]() {
auto block = disambiguate();
updateContext(block);
ForLoopInitRewriter::run(*m_context, block);
return block;
}},
{"commonSubexpressionEliminator", [&]() {
auto block = disambiguate();
updateContext(block);
ForLoopInitRewriter::run(*m_context, block);
FunctionHoister::run(*m_context, block);
CommonSubexpressionEliminator::run(*m_context, block);
return block;
}},
{"conditionalUnsimplifier", [&]() {
auto block = disambiguate();
updateContext(block);
ConditionalUnsimplifier::run(*m_context, block);
return block;
}},
{"conditionalSimplifier", [&]() {
auto block = disambiguate();
updateContext(block);
ConditionalSimplifier::run(*m_context, block);
return block;
}},
{"expressionSplitter", [&]() {
auto block = std::get<Block>(ASTCopier{}(m_object->code()->root()));
updateContext(block);
ExpressionSplitter::run(*m_context, block);
return block;
}},
{"expressionJoiner", [&]() {
auto block = disambiguate();
updateContext(block);
ExpressionJoiner::run(*m_context, block);
return block;
}},
{"splitJoin", [&]() {
auto block = disambiguate();
updateContext(block);
ExpressionSplitter::run(*m_context, block);
ExpressionJoiner::run(*m_context, block);
ExpressionJoiner::run(*m_context, block);
return block;
}},
{"functionGrouper", [&]() {
auto block = disambiguate();
updateContext(block);
FunctionGrouper::run(*m_context, block);
return block;
}},
{"functionHoister", [&]() {
auto block = disambiguate();
updateContext(block);
FunctionHoister::run(*m_context, block);
return block;
}},
{"functionSpecializer", [&]() {
auto block = disambiguate();
updateContext(block);
FunctionHoister::run(*m_context, block);
FunctionSpecializer::run(*m_context, block);
return block;
}},
{"expressionInliner", [&]() {
auto block = disambiguate();
updateContext(block);
ExpressionInliner::run(*m_context, block);
return block;
}},
{"fullInliner", [&]() {
auto block = disambiguate();
updateContext(block);
FunctionHoister::run(*m_context, block);
FunctionGrouper::run(*m_context, block);
ExpressionSplitter::run(*m_context, block);
FullInliner::run(*m_context, block);
ExpressionJoiner::run(*m_context, block);
return block;
}},
{"fullInlinerWithoutSplitter", [&]() {
auto block = disambiguate();
updateContext(block);
FunctionHoister::run(*m_context, block);
FunctionGrouper::run(*m_context, block);
FullInliner::run(*m_context, block);
return block;
}},
{"rematerialiser", [&]() {
auto block = disambiguate();
updateContext(block);
ForLoopInitRewriter::run(*m_context, block);
FunctionHoister::run(*m_context, block);
Rematerialiser::run(*m_context, block);
return block;
}},
{"expressionSimplifier", [&]() {
auto block = disambiguate();
updateContext(block);
ForLoopInitRewriter::run(*m_context, block);
FunctionHoister::run(*m_context, block);
ExpressionSplitter::run(*m_context, block);
CommonSubexpressionEliminator::run(*m_context, block);
ExpressionSimplifier::run(*m_context, block);
ExpressionSimplifier::run(*m_context, block);
ExpressionSimplifier::run(*m_context, block);
UnusedPruner::run(*m_context, block);
ExpressionJoiner::run(*m_context, block);
ExpressionJoiner::run(*m_context, block);
return block;
}},
{"fullSimplify", [&]() {
auto block = disambiguate();
updateContext(block);
FunctionGrouper::run(*m_context, block);
BlockFlattener::run(*m_context, block);
ExpressionSplitter::run(*m_context, block);
ForLoopInitRewriter::run(*m_context, block);
FunctionHoister::run(*m_context, block);
CommonSubexpressionEliminator::run(*m_context, block);
ExpressionSimplifier::run(*m_context, block);
UnusedPruner::run(*m_context, block);
CircularReferencesPruner::run(*m_context, block);
DeadCodeEliminator::run(*m_context, block);
ExpressionJoiner::run(*m_context, block);
ExpressionJoiner::run(*m_context, block);
return block;
}},
{"unusedFunctionParameterPruner", [&]() {
auto block = disambiguate();
updateContext(block);
ForLoopInitRewriter::run(*m_context, block);
FunctionHoister::run(*m_context, block);
LiteralRematerialiser::run(*m_context, block);
UnusedFunctionParameterPruner::run(*m_context, block);
return block;
}},
{"unusedPruner", [&]() {
auto block = disambiguate();
updateContext(block);
UnusedPruner::run(*m_context, block);
return block;
}},
{"circularReferencesPruner", [&]() {
auto block = disambiguate();
updateContext(block);
FunctionHoister::run(*m_context, block);
CircularReferencesPruner::run(*m_context, block);
return block;
}},
{"deadCodeEliminator", [&]() {
auto block = disambiguate();
updateContext(block);
ForLoopInitRewriter::run(*m_context, block);
DeadCodeEliminator::run(*m_context, block);
return block;
}},
{"ssaTransform", [&]() {
auto block = disambiguate();
updateContext(block);
ForLoopInitRewriter::run(*m_context, block);
SSATransform::run(*m_context, block);
return block;
}},
{"unusedAssignEliminator", [&]() {
auto block = disambiguate();
updateContext(block);
ForLoopInitRewriter::run(*m_context, block);
UnusedAssignEliminator::run(*m_context, block);
return block;
}},
{"unusedStoreEliminator", [&]() {
auto block = disambiguate();
updateContext(block);
ForLoopInitRewriter::run(*m_context, block);
ExpressionSplitter::run(*m_context, block);
SSATransform::run(*m_context, block);
UnusedStoreEliminator::run(*m_context, block);
SSAReverser::run(*m_context, block);
ExpressionJoiner::run(*m_context, block);
return block;
}},
{"equalStoreEliminator", [&]() {
auto block = disambiguate();
updateContext(block);
FunctionHoister::run(*m_context, block);
ForLoopInitRewriter::run(*m_context, block);
EqualStoreEliminator::run(*m_context, block);
return block;
}},
{"ssaPlusCleanup", [&]() {
auto block = disambiguate();
updateContext(block);
ForLoopInitRewriter::run(*m_context, block);
SSATransform::run(*m_context, block);
UnusedAssignEliminator::run(*m_context, block);
return block;
}},
{"loadResolver", [&]() {
auto block = disambiguate();
updateContext(block);
FunctionGrouper::run(*m_context, block);
BlockFlattener::run(*m_context, block);
ForLoopInitRewriter::run(*m_context, block);
FunctionHoister::run(*m_context, block);
ExpressionSplitter::run(*m_context, block);
CommonSubexpressionEliminator::run(*m_context, block);
ExpressionSimplifier::run(*m_context, block);
LoadResolver::run(*m_context, block);
UnusedPruner::run(*m_context, block);
ExpressionJoiner::run(*m_context, block);
ExpressionJoiner::run(*m_context, block);
return block;
}},
{"loopInvariantCodeMotion", [&]() {
auto block = disambiguate();
updateContext(block);
ForLoopInitRewriter::run(*m_context, block);
FunctionHoister::run(*m_context, block);
LoopInvariantCodeMotion::run(*m_context, block);
return block;
}},
{"controlFlowSimplifier", [&]() {
auto block = disambiguate();
updateContext(block);
ForLoopInitRewriter::run(*m_context, block);
ControlFlowSimplifier::run(*m_context, block);
return block;
}},
{"structuralSimplifier", [&]() {
auto block = disambiguate();
updateContext(block);
ForLoopInitRewriter::run(*m_context, block);
FunctionHoister::run(*m_context, block);
LiteralRematerialiser::run(*m_context, block);
StructuralSimplifier::run(*m_context, block);
return block;
}},
{"equivalentFunctionCombiner", [&]() {
auto block = disambiguate();
updateContext(block);
ForLoopInitRewriter::run(*m_context, block);
FunctionHoister::run(*m_context, block);
EquivalentFunctionCombiner::run(*m_context, block);
return block;
}},
{"ssaReverser", [&]() {
auto block = disambiguate();
updateContext(block);
SSAReverser::run(*m_context, block);
return block;
}},
{"ssaAndBack", [&]() {
auto block = disambiguate();
updateContext(block);
ForLoopInitRewriter::run(*m_context, block);
// apply SSA
SSATransform::run(*m_context, block);
UnusedAssignEliminator::run(*m_context, block);
// reverse SSA
SSAReverser::run(*m_context, block);
FunctionHoister::run(*m_context, block);
CommonSubexpressionEliminator::run(*m_context, block);
UnusedPruner::run(*m_context, block);
return block;
}},
{"stackCompressor", [&]() {
auto block = disambiguate();
updateContext(block);
ForLoopInitRewriter::run(*m_context, block);
FunctionHoister::run(*m_context, block);
FunctionGrouper::run(*m_context, block);
size_t maxIterations = 16;
{
Object object(*m_optimizedObject);
object.setCode(std::make_shared<AST>(std::get<Block>(ASTCopier{}(block))));
block = std::get<1>(StackCompressor::run(*m_dialect, object, true, maxIterations));
}
BlockFlattener::run(*m_context, block);
return block;
}},
{"fullSuite", [&]() {
GasMeter meter(dynamic_cast<EVMDialect const&>(*m_dialect), false, 200);
OptimiserSuite::run(
*m_dialect,
&meter,
*m_optimizedObject,
true,
frontend::OptimiserSettings::DefaultYulOptimiserSteps,
frontend::OptimiserSettings::DefaultYulOptimiserCleanupSteps,
frontend::OptimiserSettings::standard().expectedExecutionsPerDeployment
);
return std::get<Block>(ASTCopier{}(m_optimizedObject->code()->root()));
}},
{"stackLimitEvader", [&]() {
auto block = disambiguate();
updateContext(block);
Object object(*m_optimizedObject);
object.setCode(std::make_shared<AST>(std::get<Block>(ASTCopier{}(block))));
auto const unreachables = CompilabilityChecker{
*m_dialect,
object,
true
}.unreachableVariables;
StackLimitEvader::run(*m_context, block, unreachables);
return block;
}},
{"fakeStackLimitEvader", [&]() {
auto block = disambiguate();
updateContext(block);
// Mark all variables with a name starting with "$" for escalation to memory.
struct FakeUnreachableGenerator: ASTWalker
{
std::map<YulName, std::vector<YulName>> fakeUnreachables;
using ASTWalker::operator();
void operator()(FunctionDefinition const& _function) override
{
YulName originalFunctionName = m_currentFunction;
m_currentFunction = _function.name;
for (NameWithDebugData const& _argument: _function.parameters)
visitVariableName(_argument.name);
for (NameWithDebugData const& _argument: _function.returnVariables)
visitVariableName(_argument.name);
ASTWalker::operator()(_function);
m_currentFunction = originalFunctionName;
}
void visitVariableName(YulName _var)
{
if (!_var.empty() && _var.str().front() == '$')
if (!util::contains(fakeUnreachables[m_currentFunction], _var))
fakeUnreachables[m_currentFunction].emplace_back(_var);
}
void operator()(VariableDeclaration const& _varDecl) override
{
for (auto const& var: _varDecl.variables)
visitVariableName(var.name);
ASTWalker::operator()(_varDecl);
}
void operator()(Identifier const& _identifier) override
{
visitVariableName(_identifier.name);
ASTWalker::operator()(_identifier);
}
YulName m_currentFunction = YulName{};
};
FakeUnreachableGenerator fakeUnreachableGenerator;
fakeUnreachableGenerator(block);
StackLimitEvader::run(*m_context, block, fakeUnreachableGenerator.fakeUnreachables);
return block;
}}
};
}
void YulOptimizerTestCommon::setStep(std::string const& _optimizerStep)
{
m_optimizerStep = _optimizerStep;
}
bool YulOptimizerTestCommon::runStep()
{
yulAssert(m_dialect, "Dialect not set.");
if (m_namedSteps.count(m_optimizerStep))
{
auto block = m_namedSteps[m_optimizerStep]();
m_optimizedObject->setCode(std::make_shared<AST>(std::move(block)));
}
else
return false;
return true;
}
std::string YulOptimizerTestCommon::randomOptimiserStep(unsigned _seed)
{
std::mt19937 prng(_seed);
std::uniform_int_distribution<size_t> dist(1, m_namedSteps.size());
size_t idx = dist(prng);
size_t count = 1;
for (auto &step: m_namedSteps)
{
if (count == idx)
{
std::string optimiserStep = step.first;
// Do not fuzz mainFunction
// because it does not preserve yul code semantics.
// Do not fuzz reasoning based simplifier because
// it can sometimes drain memory.
if (
optimiserStep == "mainFunction"
)
// "Fullsuite" is fuzzed roughly four times more frequently than
// other steps because of the filtering in place above.
return "fullSuite";
else
return optimiserStep;
}
count++;
}
yulAssert(false, "Optimiser step selection failed.");
}
Block const* YulOptimizerTestCommon::run()
{
return runStep() ? &m_optimizedObject->code()->root() : nullptr;
}
Block YulOptimizerTestCommon::disambiguate()
{
auto block = std::get<Block>(Disambiguator(*m_dialect, *m_object->analysisInfo)(m_object->code()->root()));
return block;
}
void YulOptimizerTestCommon::updateContext(Block const& _block)
{
m_nameDispenser = std::make_unique<NameDispenser>(*m_dialect, _block, m_reservedIdentifiers);
m_context = std::make_unique<OptimiserStepContext>(OptimiserStepContext{
*m_dialect,
*m_nameDispenser,
m_reservedIdentifiers,
frontend::OptimiserSettings::standard().expectedExecutionsPerDeployment
});
}
std::shared_ptr<Object> YulOptimizerTestCommon::optimizedObject() const
{
return m_optimizedObject;
}
| 18,654
|
C++
|
.cpp
| 544
| 30.884191
| 121
| 0.722649
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,967
|
ObjectParser.cpp
|
ethereum_solidity/test/libyul/ObjectParser.cpp
|
/*
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/>.
*/
/**
* @date 2018
* Unit tests for the Yul object parser.
*/
#include <test/Common.h>
#include <test/libsolidity/ErrorCheck.h>
#include <liblangutil/DebugInfoSelection.h>
#include <liblangutil/Scanner.h>
#include <libyul/YulStack.h>
#include <libyul/backends/evm/EVMDialect.h>
#include <libsolidity/interface/OptimiserSettings.h>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/test/unit_test.hpp>
#include <range/v3/view/iota.hpp>
#include <memory>
#include <optional>
#include <string>
#include <sstream>
using namespace solidity::frontend;
using namespace solidity::langutil;
using namespace std::string_literals;
namespace solidity::yul::test
{
namespace
{
std::pair<bool, ErrorList> parse(std::string const& _source)
{
YulStack asmStack(
solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion(),
YulStack::Language::StrictAssembly,
solidity::frontend::OptimiserSettings::none(),
DebugInfoSelection::All()
);
bool success = asmStack.parseAndAnalyze("source", _source);
return {success, asmStack.errors()};
}
std::optional<Error> parseAndReturnFirstError(std::string const& _source, bool _allowWarningsAndInfos = true)
{
bool success;
ErrorList errors;
tie(success, errors) = parse(_source);
if (!success)
{
BOOST_REQUIRE_EQUAL(errors.size(), 1);
return *errors.front();
}
else
{
// If success is true, there might still be an error in the assembly stage.
if (_allowWarningsAndInfos && !Error::containsErrors(errors))
return {};
else if (!errors.empty())
{
if (!_allowWarningsAndInfos)
BOOST_CHECK_EQUAL(errors.size(), 1);
return *errors.front();
}
}
return {};
}
bool successParse(std::string const& _source, bool _allowWarningsAndInfos = true)
{
return !parseAndReturnFirstError(_source, _allowWarningsAndInfos);
}
Error expectError(std::string const& _source, bool _allowWarningsAndInfos = false)
{
auto error = parseAndReturnFirstError(_source, _allowWarningsAndInfos);
BOOST_REQUIRE(error);
return *error;
}
std::tuple<std::optional<SourceNameMap>, ErrorList> tryGetSourceLocationMapping(std::string _source)
{
std::vector<std::string> lines;
boost::split(lines, _source, boost::is_any_of("\n"));
std::string source = util::joinHumanReadablePrefixed(lines, "\n///") + "\n{}\n";
ErrorList errors;
ErrorReporter reporter(errors);
Dialect const& dialect = yul::EVMDialect::strictAssemblyForEVM(solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion());
ObjectParser objectParser{reporter, dialect};
CharStream stream(std::move(source), "");
auto object = objectParser.parse(std::make_shared<Scanner>(stream), false);
BOOST_REQUIRE(object && object->debugData);
return {object->debugData->sourceNames, std::move(errors)};
}
}
#define CHECK_ERROR(text, typ, substring) \
do \
{ \
Error err = expectError((text), false); \
BOOST_CHECK(err.type() == (Error::Type::typ)); \
BOOST_CHECK(::solidity::frontend::test::searchErrorMessage(err, (substring))); \
} while(0)
BOOST_AUTO_TEST_SUITE(YulObjectParser)
BOOST_AUTO_TEST_CASE(empty_code)
{
BOOST_CHECK(successParse("{ }"));
}
BOOST_AUTO_TEST_CASE(recursion_depth)
{
std::string input;
for (size_t i = 0; i < 20000; i++)
input += "object \"a" + std::to_string(i) + "\" { code {} ";
for (size_t i = 0; i < 20000; i++)
input += "}";
CHECK_ERROR(input, ParserError, "recursion");
}
BOOST_AUTO_TEST_CASE(to_string)
{
std::string code = R"(
object "O" {
code { let x := mload(0) if x { sstore(0, 1) } }
object "i" { code {} data "j" "def" }
data "j" "abc"
data "k" hex"010203"
}
)";
std::string expectation = R"(object "O" {
code {
let x := mload(0)
if x { sstore(0, 1) }
}
object "i" {
code { }
data "j" hex"646566"
}
data "j" hex"616263"
data "k" hex"010203"
}
)";
expectation = boost::replace_all_copy(expectation, "\t", " ");
YulStack asmStack(
solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion(),
YulStack::Language::StrictAssembly,
solidity::frontend::OptimiserSettings::none(),
DebugInfoSelection::All()
);
BOOST_REQUIRE(asmStack.parseAndAnalyze("source", code));
BOOST_CHECK_EQUAL(asmStack.print(), expectation);
}
BOOST_AUTO_TEST_CASE(use_src_empty)
{
auto const [mapping, _] = tryGetSourceLocationMapping("");
BOOST_REQUIRE(!mapping);
}
BOOST_AUTO_TEST_CASE(use_src_simple)
{
auto const [mapping, _] = tryGetSourceLocationMapping(R"(@use-src 0:"contract.sol")");
BOOST_REQUIRE(mapping.has_value());
BOOST_REQUIRE_EQUAL(mapping->size(), 1);
BOOST_REQUIRE_EQUAL(*mapping->at(0), "contract.sol");
}
BOOST_AUTO_TEST_CASE(use_src_multiple)
{
auto const [mapping, _] = tryGetSourceLocationMapping(R"(@use-src 0:"contract.sol", 1:"misc.yul")");
BOOST_REQUIRE(mapping);
BOOST_REQUIRE_EQUAL(mapping->size(), 2);
BOOST_REQUIRE_EQUAL(*mapping->at(0), "contract.sol");
BOOST_REQUIRE_EQUAL(*mapping->at(1), "misc.yul");
}
BOOST_AUTO_TEST_CASE(use_src_escaped_filenames)
{
auto const [mapping, _] = tryGetSourceLocationMapping(
R"(@use-src 42:"con\"tract@\".sol")"
);
BOOST_REQUIRE(mapping);
BOOST_REQUIRE_EQUAL(mapping->size(), 1);
BOOST_REQUIRE(mapping->count(42));
BOOST_REQUIRE_EQUAL(*mapping->at(42), "con\"tract@\".sol");
}
BOOST_AUTO_TEST_CASE(use_src_invalid_syntax_malformed_param_1)
{
// open quote arg, missing closing quote
auto const [mapping, errors] = tryGetSourceLocationMapping(R"(@use-src 42_"con")");
BOOST_REQUIRE_EQUAL(errors.size(), 1);
BOOST_CHECK_EQUAL(errors.front()->errorId().error, 9804);
}
BOOST_AUTO_TEST_CASE(use_src_invalid_syntax_malformed_param_2)
{
// open quote arg, missing closing quote
auto const [mapping, errors] = tryGetSourceLocationMapping(R"(@use-src 42:"con)");
BOOST_REQUIRE_EQUAL(errors.size(), 1);
BOOST_CHECK_EQUAL(errors.front()->errorId().error, 9804);
}
BOOST_AUTO_TEST_CASE(use_src_error_unexpected_trailing_tokens)
{
auto const [mapping, errors] = tryGetSourceLocationMapping(
R"(@use-src 1:"file.sol" @use-src 2:"foo.sol")"
);
BOOST_REQUIRE_EQUAL(errors.size(), 1);
BOOST_CHECK_EQUAL(errors.front()->errorId().error, 9804);
}
BOOST_AUTO_TEST_CASE(use_src_multiline)
{
auto const [mapping, _] = tryGetSourceLocationMapping(
" @use-src \n 0:\"contract.sol\" \n , \n 1:\"misc.yul\""
);
BOOST_REQUIRE(mapping);
BOOST_REQUIRE_EQUAL(mapping->size(), 2);
BOOST_REQUIRE_EQUAL(*mapping->at(0), "contract.sol");
BOOST_REQUIRE_EQUAL(*mapping->at(1), "misc.yul");
}
BOOST_AUTO_TEST_CASE(use_src_empty_body)
{
auto const [mapping, _] = tryGetSourceLocationMapping("@use-src");
BOOST_REQUIRE(mapping);
BOOST_REQUIRE_EQUAL(mapping->size(), 0);
}
BOOST_AUTO_TEST_CASE(use_src_leading_text)
{
auto const [mapping, _] = tryGetSourceLocationMapping(
"@something else @use-src 0:\"contract.sol\", 1:\"misc.sol\""s
);
BOOST_REQUIRE(mapping);
BOOST_REQUIRE_EQUAL(mapping->size(), 2);
BOOST_REQUIRE(mapping->find(0) != mapping->end());
BOOST_REQUIRE_EQUAL(*mapping->at(0), "contract.sol");
BOOST_REQUIRE_EQUAL(*mapping->at(1), "misc.sol");
}
BOOST_AUTO_TEST_SUITE_END()
}
| 7,887
|
C++
|
.cpp
| 238
| 31
| 114
| 0.72548
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,968
|
SSAControlFlowGraphTest.cpp
|
ethereum_solidity/test/libyul/SSAControlFlowGraphTest.cpp
|
/*
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
#include <test/libyul/SSAControlFlowGraphTest.h>
#include <test/libyul/Common.h>
#include <test/Common.h>
#include <libyul/backends/evm/SSAControlFlowGraphBuilder.h>
#include <libyul/backends/evm/StackHelpers.h>
#include <libyul/AsmAnalysis.h>
#include <libyul/Object.h>
#include <libsolutil/AnsiColorized.h>
#ifdef ISOLTEST
#include <boost/process.hpp>
#endif
using namespace solidity;
using namespace solidity::util;
using namespace solidity::langutil;
using namespace solidity::yul;
using namespace solidity::yul::test;
using namespace solidity::frontend;
using namespace solidity::frontend::test;
std::unique_ptr<TestCase> SSAControlFlowGraphTest::create(TestCase::Config const& _config) {
return std::make_unique<SSAControlFlowGraphTest>(_config.filename);
}
SSAControlFlowGraphTest::SSAControlFlowGraphTest(std::string const& _filename): TestCase(_filename)
{
m_source = m_reader.source();
auto dialectName = m_reader.stringSetting("dialect", "evm");
m_dialect = &dialect(
dialectName,
solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion()
);
m_expectation = m_reader.simpleExpectations();
}
TestCase::TestResult SSAControlFlowGraphTest::run(std::ostream& _stream, std::string const& _linePrefix, bool const _formatted)
{
ErrorList errors;
auto [object, analysisInfo] = parse(m_source, *m_dialect, errors);
if (!object || !analysisInfo || Error::containsErrors(errors))
{
AnsiColorized(_stream, _formatted, {formatting::BOLD, formatting::RED}) << _linePrefix << "Error parsing source." << std::endl;
return TestResult::FatalError;
}
auto info = AsmAnalyzer::analyzeStrictAssertCorrect(*m_dialect, *object);
std::unique_ptr<ControlFlow> controlFlow = SSAControlFlowGraphBuilder::build(
info,
*m_dialect,
object->code()->root()
);
ControlFlowLiveness liveness(*controlFlow);
m_obtainedResult = controlFlow->toDot(&liveness);
auto result = checkResult(_stream, _linePrefix, _formatted);
#ifdef ISOLTEST
char* graphDisplayer = nullptr;
// The environment variables specify an optional command that will receive the graph encoded in DOT through stdin.
// Examples for suitable commands are ``dot -Tx11:cairo`` or ``xdot -``.
if (result == TestResult::Failure)
// ISOLTEST_DISPLAY_GRAPHS_ON_FAILURE_COMMAND will run on all failing tests (intended for use during modifications).
graphDisplayer = getenv("ISOLTEST_DISPLAY_GRAPHS_ON_FAILURE_COMMAND");
else if (result == TestResult::Success)
// ISOLTEST_DISPLAY_GRAPHS_ON_FAILURE_COMMAND will run on all succeeding tests (intended for use during reviews).
graphDisplayer = getenv("ISOLTEST_DISPLAY_GRAPHS_ON_SUCCESS_COMMAND");
if (graphDisplayer)
{
if (result == TestResult::Success)
std::cout << std::endl << m_source << std::endl;
boost::process::opstream pipe;
boost::process::child child(graphDisplayer, boost::process::std_in < pipe);
pipe << m_obtainedResult;
pipe.flush();
pipe.pipe().close();
if (result == TestResult::Success)
child.wait();
else
child.detach();
}
#endif
return result;
}
| 3,766
|
C++
|
.cpp
| 91
| 39.241758
| 129
| 0.770304
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,970
|
FunctionDependencyGraphTest.cpp
|
ethereum_solidity/test/libsolidity/FunctionDependencyGraphTest.cpp
|
/*
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
#include <test/libsolidity/FunctionDependencyGraphTest.h>
#include <libsolidity/experimental/analysis/Analysis.h>
#include <libsolidity/experimental/analysis/FunctionDependencyAnalysis.h>
#include <libyul/backends/evm/EVMDialect.h>
#include <libyul/optimiser/FunctionCallFinder.h>
#include <libsolutil/StringUtils.h>
#include <fstream>
#include <stdexcept>
using namespace solidity;
using namespace solidity::util;
using namespace solidity::util::formatting;
using namespace solidity::langutil;
using namespace solidity::frontend;
using namespace solidity::frontend::test;
TestCase::TestResult FunctionDependencyGraphTest::run(std::ostream& _stream, std::string const& _linePrefix, bool _formatted)
{
compiler().reset();
compiler().setSources(StringMap{{"", m_source}});
compiler().setViaIR(true);
compiler().setOptimiserSettings(OptimiserSettings::none());
if (!compiler().compile(CompilerStack::AnalysisSuccessful))
{
printPrefixed(_stream, formatErrors(filteredErrors(), _formatted), _linePrefix);
return TestResult::FatalError;
}
m_obtainedResult.clear();
for (auto [top, subs]: compiler().experimentalAnalysis().annotation<experimental::FunctionDependencyAnalysis>().functionCallGraph.edges)
{
std::string topName = top->name().empty() ? "fallback" : top->name();
m_obtainedResult += "(" + topName + ") --> {";
for (auto sub: subs)
m_obtainedResult += sub->name() + ",";
m_obtainedResult += "}\n";
}
return checkResult(_stream, _linePrefix, _formatted);
}
| 2,182
|
C++
|
.cpp
| 50
| 41.64
| 137
| 0.777358
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,972
|
SMTCheckerTest.cpp
|
ethereum_solidity/test/libsolidity/SMTCheckerTest.cpp
|
/*
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
#include <test/libsolidity/SMTCheckerTest.h>
#include <test/Common.h>
#include <range/v3/action/remove_if.hpp>
using namespace solidity;
using namespace solidity::langutil;
using namespace solidity::frontend;
using namespace solidity::frontend::test;
using namespace solidity::test;
SMTCheckerTest::SMTCheckerTest(std::string const& _filename):
SyntaxTest(_filename, EVMVersion{}),
universalCallback(nullptr, smtCommand)
{
auto contract = m_reader.stringSetting("SMTContract", "");
if (!contract.empty())
m_modelCheckerSettings.contracts.contracts[""] = {contract};
auto extCallsMode = ModelCheckerExtCalls::fromString(m_reader.stringSetting("SMTExtCalls", "untrusted"));
if (extCallsMode)
m_modelCheckerSettings.externalCalls = *extCallsMode;
else
BOOST_THROW_EXCEPTION(std::runtime_error("Invalid SMT external calls mode."));
auto const& showProvedSafe = m_reader.stringSetting("SMTShowProvedSafe", "no");
if (showProvedSafe == "no")
m_modelCheckerSettings.showProvedSafe = false;
else if (showProvedSafe == "yes")
m_modelCheckerSettings.showProvedSafe = true;
else
BOOST_THROW_EXCEPTION(std::runtime_error("Invalid SMT \"show proved safe\" choice."));
auto const& showUnproved = m_reader.stringSetting("SMTShowUnproved", "yes");
if (showUnproved == "no")
m_modelCheckerSettings.showUnproved = false;
else if (showUnproved == "yes")
m_modelCheckerSettings.showUnproved = true;
else
BOOST_THROW_EXCEPTION(std::runtime_error("Invalid SMT \"show unproved\" choice."));
auto const& showUnsupported = m_reader.stringSetting("SMTShowUnsupported", "yes");
if (showUnsupported == "no")
m_modelCheckerSettings.showUnsupported = false;
else if (showUnsupported == "yes")
m_modelCheckerSettings.showUnsupported = true;
else
BOOST_THROW_EXCEPTION(std::runtime_error("Invalid SMT \"show unsupported\" choice."));
m_modelCheckerSettings.solvers = smtutil::SMTSolverChoice::None();
auto const& choice = m_reader.stringSetting("SMTSolvers", "z3");
if (choice == "none")
m_modelCheckerSettings.solvers = smtutil::SMTSolverChoice::None();
else if (!m_modelCheckerSettings.solvers.setSolver(choice))
BOOST_THROW_EXCEPTION(std::runtime_error("Invalid SMT solver choice."));
m_modelCheckerSettings.solvers &= ModelChecker::availableSolvers();
/// Underflow and Overflow are not enabled by default for Solidity >=0.8.7,
/// so we explicitly enable all targets for the tests,
/// if the targets were not explicitly set by the test.
auto targets = ModelCheckerTargets::fromString(m_reader.stringSetting("SMTTargets", "all"));
if (targets)
m_modelCheckerSettings.targets = *targets;
else
BOOST_THROW_EXCEPTION(std::runtime_error("Invalid SMT targets."));
auto engine = ModelCheckerEngine::fromString(m_reader.stringSetting("SMTEngine", "all"));
if (engine)
m_modelCheckerSettings.engine = *engine;
else
BOOST_THROW_EXCEPTION(std::runtime_error("Invalid SMT engine choice."));
if (m_modelCheckerSettings.solvers.none() || m_modelCheckerSettings.engine.none())
m_shouldRun = false;
auto const& ignoreCex = m_reader.stringSetting("SMTIgnoreCex", "yes");
if (ignoreCex == "no")
m_ignoreCex = false;
else if (ignoreCex == "yes")
m_ignoreCex = true;
else
BOOST_THROW_EXCEPTION(std::runtime_error("Invalid SMT counterexample choice."));
static auto removeInv = [](std::vector<SyntaxTestError>&& errors) {
std::vector<SyntaxTestError> filtered;
for (auto&& e: errors)
if (e.errorId != 1180_error)
filtered.emplace_back(e);
return filtered;
};
auto const& ignoreInv = m_reader.stringSetting("SMTIgnoreInv", "yes");
if (ignoreInv == "no")
m_modelCheckerSettings.invariants = ModelCheckerInvariants::All();
else if (ignoreInv == "yes")
m_modelCheckerSettings.invariants = ModelCheckerInvariants::None();
else
BOOST_THROW_EXCEPTION(std::runtime_error("Invalid SMT invariant choice."));
if (m_modelCheckerSettings.invariants.invariants.empty())
m_expectations = removeInv(std::move(m_expectations));
auto const& ignoreOSSetting = m_reader.stringSetting("SMTIgnoreOS", "none");
for (std::string const& os: ignoreOSSetting | ranges::views::split(',') | ranges::to<std::vector<std::string>>())
{
#ifdef __APPLE__
if (os == "macos")
m_shouldRun = false;
#elif _WIN32
if (os == "windows")
m_shouldRun = false;
#elif __linux__
if (os == "linux")
m_shouldRun = false;
#endif
}
auto const& bmcLoopIterations = m_reader.sizetSetting("BMCLoopIterations", 1);
m_modelCheckerSettings.bmcLoopIterations = std::optional<unsigned>{bmcLoopIterations};
}
void SMTCheckerTest::setupCompiler(CompilerStack& _compiler)
{
SyntaxTest::setupCompiler(_compiler);
_compiler.setModelCheckerSettings(m_modelCheckerSettings);
}
void SMTCheckerTest::filterObtainedErrors()
{
SyntaxTest::filterObtainedErrors();
m_unfilteredErrorList = m_errorList;
static auto removeCex = [](std::vector<SyntaxTestError>& errors) {
for (auto& e: errors)
if (
auto cexPos = e.message.find("\\nCounterexample");
cexPos != std::string::npos
)
e.message = e.message.substr(0, cexPos);
};
if (m_ignoreCex)
{
removeCex(m_expectations);
removeCex(m_errorList);
}
}
void SMTCheckerTest::printUpdatedExpectations(std::ostream &_stream, const std::string &_linePrefix) const {
if (!m_unfilteredErrorList.empty())
printErrorList(_stream, m_unfilteredErrorList, _linePrefix, false);
else
CommonSyntaxTest::printUpdatedExpectations(_stream, _linePrefix);
}
std::unique_ptr<CompilerStack> SMTCheckerTest::createStack() const {
return std::make_unique<CompilerStack>(universalCallback.callback());
}
| 6,285
|
C++
|
.cpp
| 149
| 39.765101
| 114
| 0.761749
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,974
|
ASTJSONTest.cpp
|
ethereum_solidity/test/libsolidity/ASTJSONTest.cpp
|
/*
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
#include <liblangutil/SourceReferenceFormatter.h>
#include <libsolidity/ast/ASTJsonExporter.h>
#include <libsolutil/AnsiColorized.h>
#include <libsolutil/CommonIO.h>
#include <libsolutil/JSON.h>
#include <test/Common.h>
#include <test/libsolidity/ASTJSONTest.h>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/throw_exception.hpp>
#include <fstream>
#include <memory>
#include <stdexcept>
using namespace solidity;
using namespace solidity::langutil;
using namespace solidity::frontend;
using namespace solidity::frontend::test;
using namespace solidity::util::formatting;
using namespace solidity::util;
namespace fs = boost::filesystem;
using namespace boost::unit_test;
using namespace std::string_literals;
namespace
{
std::string const sourceDelimiter("==== Source: ");
std::string compilerStateToString(CompilerStack::State _state)
{
switch (_state)
{
case CompilerStack::State::Empty: return "Empty";
case CompilerStack::State::SourcesSet: return "SourcesSet";
case CompilerStack::State::Parsed: return "Parsed";
case CompilerStack::State::ParsedAndImported: return "ParsedAndImported";
case CompilerStack::State::AnalysisSuccessful: return "AnalysisSuccessful";
case CompilerStack::State::CompilationSuccessful: return "CompilationSuccessful";
}
soltestAssert(false, "Unexpected value of state parameter");
}
CompilerStack::State stringToCompilerState(const std::string& _state)
{
for (unsigned int i = CompilerStack::State::Empty; i <= CompilerStack::State::CompilationSuccessful; ++i)
{
if (_state == compilerStateToString(CompilerStack::State(i)))
return CompilerStack::State(i);
}
BOOST_THROW_EXCEPTION(std::runtime_error("Unsupported compiler state (" + _state + ") in test contract file"));
}
void replaceVersionWithTag(std::string& _input)
{
boost::algorithm::replace_all(
_input,
"\"" + solidity::test::CommonOptions::get().evmVersion().name() + "\"",
"%EVMVERSION%"
);
}
void replaceTagWithVersion(std::string& _input)
{
boost::algorithm::replace_all(
_input,
"%EVMVERSION%",
"\"" + solidity::test::CommonOptions::get().evmVersion().name() + "\""
);
}
}
void ASTJSONTest::generateTestVariants(std::string const& _filename)
{
std::string_view baseName = _filename;
baseName.remove_suffix(4);
const std::vector<CompilerStack::State> variantCompileStates = {
CompilerStack::State::Parsed,
CompilerStack::State::AnalysisSuccessful,
};
for (const auto state: variantCompileStates)
{
auto variant = TestVariant(baseName, state);
if (boost::filesystem::exists(variant.astFilename()))
{
variant.expectation = readFileAsString(variant.astFilename());
boost::replace_all(variant.expectation, "\r\n", "\n");
m_variants.push_back(variant);
}
}
}
void ASTJSONTest::fillSources(std::string const& _filename)
{
std::ifstream file(_filename);
if (!file)
BOOST_THROW_EXCEPTION(std::runtime_error("Cannot open test contract: \"" + _filename + "\"."));
file.exceptions(std::ios::badbit);
std::string sourceName;
std::string source;
std::string line;
std::string const delimiter("// ----");
std::string const failMarker("// failAfter:");
while (getline(file, line))
{
if (boost::algorithm::starts_with(line, sourceDelimiter))
{
if (!sourceName.empty())
m_sources.emplace_back(sourceName, source);
sourceName = line.substr(
sourceDelimiter.size(),
line.size() - " ===="s.size() - sourceDelimiter.size()
);
source = std::string();
}
else if (boost::algorithm::starts_with(line, failMarker))
{
std::string state = line.substr(failMarker.size());
boost::algorithm::trim(state);
if (m_expectedFailAfter.has_value())
BOOST_THROW_EXCEPTION(std::runtime_error("Duplicated \"failAfter\" directive"));
m_expectedFailAfter = stringToCompilerState(state);
}
else if (!line.empty() && !boost::algorithm::starts_with(line, delimiter))
source += line + "\n";
}
m_sources.emplace_back(sourceName.empty() ? "a" : sourceName, source);
file.close();
}
void ASTJSONTest::validateTestConfiguration() const
{
if (m_variants.empty())
BOOST_THROW_EXCEPTION(std::runtime_error("No file with expected result found."));
if (m_expectedFailAfter.has_value())
{
auto unexpectedTestVariant = std::find_if(
m_variants.begin(), m_variants.end(),
[failAfter = m_expectedFailAfter](TestVariant v) { return v.stopAfter > failAfter; }
);
if (unexpectedTestVariant != m_variants.end())
BOOST_THROW_EXCEPTION(
std::runtime_error(
std::string("Unexpected JSON file: ") + unexpectedTestVariant->astFilename() +
" in \"failAfter: " +
compilerStateToString(m_expectedFailAfter.value()) + "\" scenario."
)
);
}
}
ASTJSONTest::ASTJSONTest(std::string const& _filename):
EVMVersionRestrictedTestCase(_filename)
{
if (!boost::algorithm::ends_with(_filename, ".sol"))
BOOST_THROW_EXCEPTION(std::runtime_error("Invalid test contract file name: \"" + _filename + "\"."));
generateTestVariants(_filename);
fillSources(_filename);
validateTestConfiguration();
}
TestCase::TestResult ASTJSONTest::run(std::ostream& _stream, std::string const& _linePrefix, bool const _formatted)
{
CompilerStack c;
StringMap sources;
std::map<std::string, unsigned> sourceIndices;
for (size_t i = 0; i < m_sources.size(); i++)
{
sources[m_sources[i].first] = m_sources[i].second;
sourceIndices[m_sources[i].first] = static_cast<unsigned>(i + 1);
}
bool resultsMatch = true;
for (TestVariant& variant: m_variants)
{
c.reset();
c.setSources(sources);
c.setEVMVersion(solidity::test::CommonOptions::get().evmVersion());
if (!c.parseAndAnalyze(variant.stopAfter))
{
if (!m_expectedFailAfter.has_value() || m_expectedFailAfter.value() + 1 != c.state())
{
SourceReferenceFormatter formatter(_stream, c, _formatted, false);
formatter.printErrorInformation(c.errors());
return TestResult::FatalError;
}
}
resultsMatch = resultsMatch && runTest(
variant,
sourceIndices,
c,
_stream,
_linePrefix,
_formatted
);
}
return resultsMatch ? TestResult::Success : TestResult::Failure;
}
bool ASTJSONTest::runTest(
TestVariant& _variant,
std::map<std::string, unsigned> const& _sourceIndices,
CompilerStack& _compiler,
std::ostream& _stream,
std::string const& _linePrefix,
bool const _formatted
)
{
if (m_sources.size() > 1)
_variant.result += "[\n";
for (size_t i = 0; i < m_sources.size(); i++)
{
std::ostringstream result;
ASTJsonExporter(_compiler.state(), _sourceIndices).print(result, _compiler.ast(m_sources[i].first), JsonFormat{ JsonFormat::Pretty });
_variant.result += result.str();
if (i != m_sources.size() - 1)
_variant.result += ",";
_variant.result += "\n";
}
if (m_sources.size() > 1)
_variant.result += "]\n";
replaceTagWithVersion(_variant.expectation);
if (_variant.expectation != _variant.result)
{
std::string nextIndentLevel = _linePrefix + " ";
AnsiColorized(_stream, _formatted, {BOLD, CYAN}) <<
_linePrefix <<
"Expected result" <<
(!_variant.name().empty() ? " (" + _variant.name() + "):" : ":") <<
std::endl;
printPrefixed(_stream, _variant.expectation, nextIndentLevel);
_stream << std::endl;
AnsiColorized(_stream, _formatted, {BOLD, CYAN}) <<
_linePrefix <<
"Obtained result" <<
(!_variant.name().empty() ? " (" + _variant.name() + "):" : ":") <<
std::endl;
printPrefixed(_stream, _variant.result, nextIndentLevel);
_stream << std::endl;
return false;
}
return true;
}
void ASTJSONTest::printSource(std::ostream& _stream, std::string const& _linePrefix, bool const) const
{
for (auto const& source: m_sources)
{
if (m_sources.size() > 1 || source.first != "a")
printPrefixed(_stream, sourceDelimiter + source.first + " ====\n", _linePrefix);
printPrefixed(_stream, source.second, _linePrefix);
_stream << std::endl;
}
}
void ASTJSONTest::printUpdatedExpectations(std::ostream&, std::string const&) const
{
for (TestVariant const& variant: m_variants)
updateExpectation(
variant.astFilename(),
variant.result,
variant.name().empty() ? "" : variant.name() + " "
);
}
void ASTJSONTest::updateExpectation(std::string const& _filename, std::string const& _expectation, std::string const& _variant) const
{
std::ofstream file(_filename.c_str());
if (!file) BOOST_THROW_EXCEPTION(std::runtime_error("Cannot write " + _variant + "AST expectation to \"" + _filename + "\"."));
file.exceptions(std::ios::badbit);
std::string replacedResult = _expectation;
replaceVersionWithTag(replacedResult);
file << replacedResult;
file.flush();
file.close();
}
| 9,458
|
C++
|
.cpp
| 276
| 31.713768
| 136
| 0.724059
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,975
|
GasTest.cpp
|
ethereum_solidity/test/libsolidity/GasTest.cpp
|
/*
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
#include <test/libsolidity/GasTest.h>
#include <test/libsolidity/util/Common.h>
#include <test/Common.h>
#include <libsolutil/CommonIO.h>
#include <libsolutil/JSON.h>
#include <libsolutil/StringUtils.h>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/throw_exception.hpp>
#include <fstream>
#include <stdexcept>
using namespace solidity::langutil;
using namespace solidity::frontend;
using namespace solidity::frontend::test;
using namespace solidity;
using namespace boost::unit_test;
GasTest::GasTest(std::string const& _filename):
TestCase(_filename)
{
m_source = m_reader.source();
m_optimise = m_reader.boolSetting("optimize", false);
m_optimiseYul = m_reader.boolSetting("optimize-yul", false);
m_optimiseRuns = m_reader.sizetSetting("optimize-runs", OptimiserSettings{}.expectedExecutionsPerDeployment);
parseExpectations(m_reader.stream());
}
void GasTest::parseExpectations(std::istream& _stream)
{
std::map<std::string, std::string>* currentKind = nullptr;
std::string line;
while (getline(_stream, line))
if (!boost::starts_with(line, "// "))
BOOST_THROW_EXCEPTION(std::runtime_error("Invalid expectation: expected \"// \"."));
else if (boost::ends_with(line, ":"))
{
std::string kind = line.substr(3, line.length() - 4);
boost::trim(kind);
currentKind = &m_expectations[std::move(kind)];
}
else if (!currentKind)
BOOST_THROW_EXCEPTION(std::runtime_error("No function kind specified. Expected \"creation:\", \"external:\" or \"internal:\"."));
else
{
auto it = line.begin() + 3;
skipWhitespace(it, line.end());
auto functionNameBegin = it;
while (it != line.end() && *it != ':')
++it;
std::string functionName(functionNameBegin, it);
if (functionName == "fallback")
functionName.clear();
expect(it, line.end(), ':');
skipWhitespace(it, line.end());
if (it == line.end())
BOOST_THROW_EXCEPTION(std::runtime_error("Invalid expectation: expected gas cost."));
(*currentKind)[functionName] = std::string(it, line.end());
}
}
void GasTest::printUpdatedExpectations(std::ostream& _stream, std::string const& _linePrefix) const
{
Json estimates = compiler().gasEstimates(compiler().lastContractName());
for (auto& [key, group] : estimates.items())
{
_stream << _linePrefix << key << ":" << std::endl;
for (auto& [elementKey, value] : group.items())
{
_stream << _linePrefix << " ";
if (elementKey.empty())
_stream << "fallback";
else
_stream << elementKey;
_stream << ": " << value.get<std::string>() << std::endl;
}
}
}
void GasTest::setupCompiler(CompilerStack& _compiler)
{
AnalysisFramework::setupCompiler(_compiler);
// Prerelease CBOR metadata varies in size due to changing version numbers and build dates.
// This leads to volatile creation cost estimates. Therefore we force the compiler to
// release mode for testing gas estimates.
_compiler.setMetadataFormat(CompilerStack::MetadataFormat::NoMetadata);
OptimiserSettings settings = m_optimise ? OptimiserSettings::standard() : OptimiserSettings::minimal();
if (m_optimiseYul)
{
settings.runYulOptimiser = m_optimise;
settings.optimizeStackAllocation = m_optimise;
}
settings.expectedExecutionsPerDeployment = m_optimiseRuns;
_compiler.setOptimiserSettings(settings);
// Intentionally ignoring EVM version specified on the command line.
// Gas expectations are only valid for the default version.
_compiler.setEVMVersion(EVMVersion{});
}
TestCase::TestResult GasTest::run(std::ostream& _stream, std::string const& _linePrefix, bool _formatted)
{
if (!runFramework(withPreamble(m_source), PipelineStage::Compilation))
{
util::printPrefixed(_stream, formatErrors(filteredErrors(), _formatted), _linePrefix);
return TestResult::FatalError;
}
Json estimateGroups = compiler().gasEstimates(compiler().lastContractName());
if (
m_expectations.size() == estimateGroups.size() &&
boost::all(m_expectations, [&](auto const& expectations) {
auto const& estimates = estimateGroups[expectations.first];
return estimates.size() == expectations.second.size() &&
boost::all(expectations.second, [&](auto const& entry) {
return entry.second == estimates[entry.first].template get<std::string>();
});
})
)
return TestResult::Success;
else
{
_stream << _linePrefix << "Expected:" << std::endl;
for (auto const& expectations: m_expectations)
{
_stream << _linePrefix << " " << expectations.first << ":" << std::endl;
for (auto const& entry: expectations.second)
_stream << _linePrefix
<< " "
<< (entry.first.empty() ? "fallback" : entry.first)
<< ": "
<< entry.second
<< std::endl;
}
_stream << _linePrefix << "Obtained:" << std::endl;
printUpdatedExpectations(_stream, _linePrefix + " ");
return TestResult::Failure;
}
}
| 5,608
|
C++
|
.cpp
| 147
| 35.510204
| 132
| 0.724619
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,976
|
SolidityExpressionCompiler.cpp
|
ethereum_solidity/test/libsolidity/SolidityExpressionCompiler.cpp
|
/*
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
/**
* @author Christian <c@ethdev.com>
* @date 2014
* Unit tests for the solidity expression compiler.
*/
#include <string>
#include <liblangutil/Scanner.h>
#include <libsolidity/parsing/Parser.h>
#include <libsolidity/analysis/NameAndTypeResolver.h>
#include <libsolidity/analysis/Scoper.h>
#include <libsolidity/analysis/SyntaxChecker.h>
#include <libsolidity/analysis/DeclarationTypeChecker.h>
#include <libsolidity/codegen/CompilerContext.h>
#include <libsolidity/codegen/ExpressionCompiler.h>
#include <libsolidity/ast/AST.h>
#include <libsolidity/ast/TypeProvider.h>
#include <libsolidity/analysis/TypeChecker.h>
#include <liblangutil/ErrorReporter.h>
#include <libevmasm/LinkerObject.h>
#include <test/Common.h>
#include <boost/test/unit_test.hpp>
using namespace solidity::evmasm;
using namespace solidity::langutil;
using namespace solidity::test;
namespace solidity::frontend::test
{
namespace
{
/// Helper class that extracts the first expression in an AST.
class FirstExpressionExtractor: private ASTVisitor
{
public:
FirstExpressionExtractor(ASTNode& _node): m_expression(nullptr) { _node.accept(*this); }
Expression* expression() const { return m_expression; }
private:
bool visit(Assignment& _expression) override { return checkExpression(_expression); }
bool visit(UnaryOperation& _expression) override { return checkExpression(_expression); }
bool visit(BinaryOperation& _expression) override { return checkExpression(_expression); }
bool visit(FunctionCall& _expression) override { return checkExpression(_expression); }
bool visit(MemberAccess& _expression) override { return checkExpression(_expression); }
bool visit(IndexAccess& _expression) override { return checkExpression(_expression); }
bool visit(Identifier& _expression) override { return checkExpression(_expression); }
bool visit(ElementaryTypeNameExpression& _expression) override { return checkExpression(_expression); }
bool visit(Literal& _expression) override { return checkExpression(_expression); }
bool checkExpression(Expression& _expression)
{
if (m_expression == nullptr)
m_expression = &_expression;
return false;
}
private:
Expression* m_expression;
};
Declaration const& resolveDeclaration(
SourceUnit const& _sourceUnit,
std::vector<std::string> const& _namespacedName,
NameAndTypeResolver const& _resolver
)
{
ASTNode const* scope = &_sourceUnit;
// bracers are required, cause msvc couldn't handle this macro in for statement
for (std::string const& namePart: _namespacedName)
{
auto declarations = _resolver.resolveName(namePart, scope);
BOOST_REQUIRE(!declarations.empty());
BOOST_REQUIRE(scope = *declarations.begin());
}
BOOST_REQUIRE(scope);
return dynamic_cast<Declaration const&>(*scope);
}
bytes compileFirstExpression(
std::string const& _sourceCode,
std::vector<std::vector<std::string>> _functions = {},
std::vector<std::vector<std::string>> _localVariables = {}
)
{
std::string sourceCode = "pragma solidity >=0.0; // SPDX-License-Identifier: GPL-3\n" + _sourceCode;
CharStream stream(sourceCode, "");
ASTPointer<SourceUnit> sourceUnit;
try
{
ErrorList errors;
ErrorReporter errorReporter(errors);
sourceUnit = Parser(
errorReporter,
solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion()
).parse(stream);
if (!sourceUnit)
return bytes();
}
catch (...)
{
std::string msg = "Parsing source code failed with:\n" + boost::current_exception_diagnostic_information();
BOOST_FAIL(msg);
}
ErrorList errors;
ErrorReporter errorReporter(errors);
GlobalContext globalContext(solidity::test::CommonOptions::get().evmVersion());
Scoper::assignScopes(*sourceUnit);
BOOST_REQUIRE(SyntaxChecker(errorReporter, false).checkSyntax(*sourceUnit));
NameAndTypeResolver resolver(globalContext, solidity::test::CommonOptions::get().evmVersion(), errorReporter, false);
resolver.registerDeclarations(*sourceUnit);
BOOST_REQUIRE_MESSAGE(resolver.resolveNamesAndTypes(*sourceUnit), "Resolving names failed");
DeclarationTypeChecker declarationTypeChecker(errorReporter, solidity::test::CommonOptions::get().evmVersion());
for (ASTPointer<ASTNode> const& node: sourceUnit->nodes())
BOOST_REQUIRE(declarationTypeChecker.check(*node));
TypeChecker typeChecker(solidity::test::CommonOptions::get().evmVersion(), errorReporter);
BOOST_REQUIRE(typeChecker.checkTypeRequirements(*sourceUnit));
for (ASTPointer<ASTNode> const& node: sourceUnit->nodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{
FirstExpressionExtractor extractor(*contract);
BOOST_REQUIRE(extractor.expression() != nullptr);
CompilerContext context(
solidity::test::CommonOptions::get().evmVersion(),
RevertStrings::Default
);
context.resetVisitedNodes(contract);
context.setMostDerivedContract(*contract);
context.setArithmetic(Arithmetic::Wrapping);
size_t parametersSize = _localVariables.size(); // assume they are all one slot on the stack
context.adjustStackOffset(static_cast<int>(parametersSize));
for (std::vector<std::string> const& variable: _localVariables)
context.addVariable(
dynamic_cast<VariableDeclaration const&>(resolveDeclaration(*sourceUnit, variable, resolver)),
static_cast<unsigned>(parametersSize--)
);
ExpressionCompiler(
context,
solidity::test::CommonOptions::get().optimize
).compile(*extractor.expression());
for (std::vector<std::string> const& function: _functions)
context << context.functionEntryLabel(dynamic_cast<FunctionDefinition const&>(
resolveDeclaration(*sourceUnit, function, resolver)
));
context.appendMissingLowLevelFunctions();
// NOTE: We intentionally disable optimisations for utility functions to simplify the tests
context.appendYulUtilityFunctions({});
BOOST_REQUIRE(context.appendYulUtilityFunctionsRan());
BOOST_REQUIRE(context.assemblyPtr());
LinkerObject const& object = context.assemblyPtr()->assemble();
BOOST_REQUIRE(object.immutableReferences.empty());
bytes instructions = object.bytecode;
// debug
// cout << evmasm::disassemble(instructions) << endl;
return instructions;
}
BOOST_FAIL("No contract found in source.");
return bytes();
}
} // end anonymous namespace
BOOST_AUTO_TEST_SUITE(SolidityExpressionCompiler)
BOOST_AUTO_TEST_CASE(literal_true)
{
char const* sourceCode = R"(
contract test {
function f() public { bool x = true; }
}
)";
bytes code = compileFirstExpression(sourceCode);
bytes expectation({uint8_t(Instruction::PUSH1), 0x1});
BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end());
}
BOOST_AUTO_TEST_CASE(literal_false)
{
char const* sourceCode = R"(
contract test {
function f() public { bool x = false; }
}
)";
bytes code = compileFirstExpression(sourceCode);
bytes expectation = solidity::test::CommonOptions::get().evmVersion().hasPush0() ?
bytes{uint8_t(Instruction::PUSH0)} :
bytes{uint8_t(Instruction::PUSH1), 0x0};
BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end());
}
BOOST_AUTO_TEST_CASE(int_literal)
{
char const* sourceCode = R"(
contract test {
function f() public { uint x = 0x12345678901234567890; }
}
)";
bytes code = compileFirstExpression(sourceCode);
bytes expectation({uint8_t(Instruction::PUSH10), 0x12, 0x34, 0x56, 0x78, 0x90,
0x12, 0x34, 0x56, 0x78, 0x90});
BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end());
}
BOOST_AUTO_TEST_CASE(int_with_wei_ether_subdenomination)
{
char const* sourceCode = R"(
contract test {
constructor() {
uint x = 1 wei;
}
}
)";
bytes code = compileFirstExpression(sourceCode);
bytes expectation({uint8_t(Instruction::PUSH1), 0x1});
BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end());
}
BOOST_AUTO_TEST_CASE(int_with_gwei_ether_subdenomination)
{
char const* sourceCode = R"(
contract test {
function f() public {
uint x = 1 gwei;
}
}
)";
bytes code = compileFirstExpression(sourceCode);
bytes expectation({uint8_t(Instruction::PUSH4), 0x3b, 0x9a, 0xca, 0x00});
BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end());
}
BOOST_AUTO_TEST_CASE(int_with_ether_ether_subdenomination)
{
char const* sourceCode = R"(
contract test {
constructor() {
uint x = 1 ether;
}
}
)";
bytes code = compileFirstExpression(sourceCode);
bytes expectation({uint8_t(Instruction::PUSH8), 0xd, 0xe0, 0xb6, 0xb3, 0xa7, 0x64, 0x00, 0x00});
BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end());
}
BOOST_AUTO_TEST_CASE(comparison)
{
char const* sourceCode = R"(
contract test {
function f() public { bool x = (0x10aa < 0x11aa) != true; }
}
)";
bytes code = compileFirstExpression(sourceCode);
bytes expectation;
if (solidity::test::CommonOptions::get().optimize)
expectation = {
uint8_t(Instruction::PUSH2), 0x11, 0xaa,
uint8_t(Instruction::PUSH2), 0x10, 0xaa,
uint8_t(Instruction::LT), uint8_t(Instruction::ISZERO), uint8_t(Instruction::ISZERO),
uint8_t(Instruction::PUSH1), 0x1,
uint8_t(Instruction::ISZERO), uint8_t(Instruction::ISZERO),
uint8_t(Instruction::EQ),
uint8_t(Instruction::ISZERO)
};
else
expectation = {
uint8_t(Instruction::PUSH1), 0x1, uint8_t(Instruction::ISZERO), uint8_t(Instruction::ISZERO),
uint8_t(Instruction::PUSH2), 0x11, 0xaa,
uint8_t(Instruction::PUSH2), 0x10, 0xaa,
uint8_t(Instruction::LT), uint8_t(Instruction::ISZERO), uint8_t(Instruction::ISZERO),
uint8_t(Instruction::EQ),
uint8_t(Instruction::ISZERO)
};
BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end());
}
BOOST_AUTO_TEST_CASE(short_circuiting)
{
char const* sourceCode = R"(
contract test {
function f() public { bool x = true != (4 <= 8 + 10 || 9 != 2); }
}
)";
bytes code = compileFirstExpression(sourceCode);
bytes expectation{
uint8_t(Instruction::PUSH1), 0x12, // 8 + 10
uint8_t(Instruction::PUSH1), 0x4,
uint8_t(Instruction::GT),
uint8_t(Instruction::ISZERO), // after this we have 4 <= 8 + 10
uint8_t(Instruction::DUP1),
uint8_t(Instruction::PUSH1), 0x11,
uint8_t(Instruction::JUMPI), // short-circuit if it is true
uint8_t(Instruction::POP),
uint8_t(Instruction::PUSH1), 0x2,
uint8_t(Instruction::PUSH1), 0x9,
uint8_t(Instruction::EQ),
uint8_t(Instruction::ISZERO), // after this we have 9 != 2
uint8_t(Instruction::JUMPDEST),
uint8_t(Instruction::ISZERO), uint8_t(Instruction::ISZERO),
uint8_t(Instruction::PUSH1), 0x1, uint8_t(Instruction::ISZERO), uint8_t(Instruction::ISZERO),
uint8_t(Instruction::EQ),
uint8_t(Instruction::ISZERO)
};
BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end());
}
BOOST_AUTO_TEST_CASE(arithmetic)
{
char const* sourceCode = R"(
contract test {
function f(uint y) public { unchecked { ((((((((y ^ 8) & 7) | 6) - 5) + 4) % 3) / 2) * 1); } }
}
)";
bytes code = compileFirstExpression(sourceCode, {}, {{"test", "f", "y"}});
bool hasPush0 = solidity::test::CommonOptions::get().evmVersion().hasPush0();
bytes push0Bytes = hasPush0 ?
bytes{uint8_t(Instruction::PUSH0)} :
bytes{uint8_t(Instruction::PUSH1), 0x0};
uint8_t size = hasPush0 ? 0x65: 0x67;
bytes panic =
bytes{
uint8_t(Instruction::JUMPDEST),
uint8_t(Instruction::PUSH32)
} +
util::fromHex("4E487B7100000000000000000000000000000000000000000000000000000000") +
push0Bytes +
bytes{
uint8_t(Instruction::MSTORE),
uint8_t(Instruction::PUSH1), 0x12,
uint8_t(Instruction::PUSH1), 0x4,
uint8_t(Instruction::MSTORE),
uint8_t(Instruction::PUSH1), 0x24
} +
push0Bytes +
bytes{
uint8_t(Instruction::REVERT),
uint8_t(Instruction::JUMPDEST),
uint8_t(Instruction::JUMP),
uint8_t(Instruction::JUMPDEST)
};
bytes expectation;
if (solidity::test::CommonOptions::get().optimize)
expectation = bytes{
uint8_t(Instruction::PUSH1), 0x2,
uint8_t(Instruction::PUSH1), 0x3,
uint8_t(Instruction::PUSH1), 0x5,
uint8_t(Instruction::DUP4),
uint8_t(Instruction::PUSH1), 0x8,
uint8_t(Instruction::XOR),
uint8_t(Instruction::PUSH1), 0x7,
uint8_t(Instruction::AND),
uint8_t(Instruction::PUSH1), 0x6,
uint8_t(Instruction::OR),
uint8_t(Instruction::SUB),
uint8_t(Instruction::PUSH1), 0x4,
uint8_t(Instruction::ADD),
uint8_t(Instruction::DUP2),
uint8_t(Instruction::ISZERO),
uint8_t(Instruction::ISZERO),
uint8_t(Instruction::PUSH1), 0x20,
uint8_t(Instruction::JUMPI),
uint8_t(Instruction::PUSH1), 0x1f,
uint8_t(Instruction::PUSH1), 0x36,
uint8_t(Instruction::JUMP),
uint8_t(Instruction::JUMPDEST),
uint8_t(Instruction::JUMPDEST),
uint8_t(Instruction::MOD),
uint8_t(Instruction::DUP2),
uint8_t(Instruction::ISZERO),
uint8_t(Instruction::ISZERO),
uint8_t(Instruction::PUSH1), 0x2e,
uint8_t(Instruction::JUMPI),
uint8_t(Instruction::PUSH1), 0x2d,
uint8_t(Instruction::PUSH1), 0x36,
uint8_t(Instruction::JUMP),
uint8_t(Instruction::JUMPDEST),
uint8_t(Instruction::JUMPDEST),
uint8_t(Instruction::DIV),
uint8_t(Instruction::PUSH1), 0x1,
uint8_t(Instruction::MUL),
uint8_t(Instruction::PUSH1), size,
uint8_t(Instruction::JUMP)
} + panic;
else
expectation = bytes{
uint8_t(Instruction::PUSH1), 0x1,
uint8_t(Instruction::PUSH1), 0x2,
uint8_t(Instruction::PUSH1), 0x3,
uint8_t(Instruction::PUSH1), 0x4,
uint8_t(Instruction::PUSH1), 0x5,
uint8_t(Instruction::PUSH1), 0x6,
uint8_t(Instruction::PUSH1), 0x7,
uint8_t(Instruction::PUSH1), 0x8,
uint8_t(Instruction::DUP9),
uint8_t(Instruction::XOR),
uint8_t(Instruction::AND),
uint8_t(Instruction::OR),
uint8_t(Instruction::SUB),
uint8_t(Instruction::ADD),
uint8_t(Instruction::DUP2),
uint8_t(Instruction::ISZERO),
uint8_t(Instruction::ISZERO),
uint8_t(Instruction::PUSH1), 0x22,
uint8_t(Instruction::JUMPI),
uint8_t(Instruction::PUSH1), 0x21,
uint8_t(Instruction::PUSH1), 0x36,
uint8_t(Instruction::JUMP),
uint8_t(Instruction::JUMPDEST),
uint8_t(Instruction::JUMPDEST),
uint8_t(Instruction::MOD),
uint8_t(Instruction::DUP2),
uint8_t(Instruction::ISZERO),
uint8_t(Instruction::ISZERO),
uint8_t(Instruction::PUSH1), 0x30,
uint8_t(Instruction::JUMPI),
uint8_t(Instruction::PUSH1), 0x2f,
uint8_t(Instruction::PUSH1), 0x36,
uint8_t(Instruction::JUMP),
uint8_t(Instruction::JUMPDEST),
uint8_t(Instruction::JUMPDEST),
uint8_t(Instruction::DIV),
uint8_t(Instruction::MUL),
uint8_t(Instruction::PUSH1), size,
uint8_t(Instruction::JUMP)
} + panic;
BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end());
}
BOOST_AUTO_TEST_CASE(unary_operators)
{
char const* sourceCode = R"(
contract test {
function f(int y) public { unchecked { !(~- y == 2); } }
}
)";
bytes code = compileFirstExpression(sourceCode, {}, {{"test", "f", "y"}});
bytes push0Bytes = solidity::test::CommonOptions::get().evmVersion().hasPush0() ?
bytes{uint8_t(Instruction::PUSH0)} :
bytes{uint8_t(Instruction::PUSH1), 0x0};
bytes expectation;
if (solidity::test::CommonOptions::get().optimize)
expectation = bytes{
uint8_t(Instruction::DUP1),
} +
push0Bytes +
bytes{
uint8_t(Instruction::SUB),
uint8_t(Instruction::NOT),
uint8_t(Instruction::PUSH1), 0x2,
uint8_t(Instruction::EQ),
uint8_t(Instruction::ISZERO)
};
else
expectation = bytes{
uint8_t(Instruction::PUSH1), 0x2,
uint8_t(Instruction::DUP2),
} +
push0Bytes +
bytes{
uint8_t(Instruction::SUB),
uint8_t(Instruction::NOT),
uint8_t(Instruction::EQ),
uint8_t(Instruction::ISZERO)
};
BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end());
}
BOOST_AUTO_TEST_CASE(unary_inc_dec)
{
char const* sourceCode = R"(
contract test {
function f(uint a) public returns (uint x) { unchecked { x = --a ^ (a-- ^ (++a ^ a++)); } }
}
)";
bytes code = compileFirstExpression(sourceCode, {}, {{"test", "f", "a"}, {"test", "f", "x"}});
// Stack: a, x
bytes expectation{
uint8_t(Instruction::DUP2),
uint8_t(Instruction::DUP1),
uint8_t(Instruction::PUSH1), 0x1,
uint8_t(Instruction::ADD),
// Stack here: a x a (a+1)
uint8_t(Instruction::SWAP3),
uint8_t(Instruction::POP), // first ++
// Stack here: (a+1) x a
uint8_t(Instruction::DUP3),
uint8_t(Instruction::PUSH1), 0x1,
uint8_t(Instruction::ADD),
// Stack here: (a+1) x a (a+2)
uint8_t(Instruction::SWAP3),
uint8_t(Instruction::POP),
// Stack here: (a+2) x a
uint8_t(Instruction::DUP3), // second ++
uint8_t(Instruction::XOR),
// Stack here: (a+2) x a^(a+2)
uint8_t(Instruction::DUP3),
uint8_t(Instruction::DUP1),
uint8_t(Instruction::PUSH1), 0x1,
uint8_t(Instruction::SWAP1),
uint8_t(Instruction::SUB),
// Stack here: (a+2) x a^(a+2) (a+2) (a+1)
uint8_t(Instruction::SWAP4),
uint8_t(Instruction::POP), // first --
uint8_t(Instruction::XOR),
// Stack here: (a+1) x a^(a+2)^(a+2)
uint8_t(Instruction::DUP3),
uint8_t(Instruction::PUSH1), 0x1,
uint8_t(Instruction::SWAP1),
uint8_t(Instruction::SUB),
// Stack here: (a+1) x a^(a+2)^(a+2) a
uint8_t(Instruction::SWAP3),
uint8_t(Instruction::POP), // second ++
// Stack here: a x a^(a+2)^(a+2)
uint8_t(Instruction::DUP3), // will change
uint8_t(Instruction::XOR),
uint8_t(Instruction::SWAP1),
uint8_t(Instruction::POP),
uint8_t(Instruction::DUP1)
};
// Stack here: a x a^(a+2)^(a+2)^a
BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end());
}
BOOST_AUTO_TEST_CASE(assignment)
{
char const* sourceCode = R"(
contract test {
function f(uint a, uint b) public { unchecked { (a += b) * 2; } }
}
)";
bytes code = compileFirstExpression(sourceCode, {}, {{"test", "f", "a"}, {"test", "f", "b"}});
// Stack: a, b
bytes expectation;
if (solidity::test::CommonOptions::get().optimize)
expectation = {
uint8_t(Instruction::DUP1),
uint8_t(Instruction::DUP3),
uint8_t(Instruction::ADD),
uint8_t(Instruction::SWAP2),
uint8_t(Instruction::POP),
uint8_t(Instruction::DUP2),
uint8_t(Instruction::PUSH1), 0x2,
uint8_t(Instruction::MUL)
};
else
expectation = {
uint8_t(Instruction::PUSH1), 0x2,
uint8_t(Instruction::DUP2),
uint8_t(Instruction::DUP4),
uint8_t(Instruction::ADD),
// Stack here: a b 2 a+b
uint8_t(Instruction::SWAP3),
uint8_t(Instruction::POP),
uint8_t(Instruction::DUP3),
// Stack here: a+b b 2 a+b
uint8_t(Instruction::MUL)
};
BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end());
}
BOOST_AUTO_TEST_CASE(negative_literals_8bits)
{
char const* sourceCode = R"(
contract test {
function f() public { int8 x = -0x80; }
}
)";
bytes code = compileFirstExpression(sourceCode);
bytes expectation(bytes({uint8_t(Instruction::PUSH32)}) + bytes(31, 0xff) + bytes(1, 0x80));
BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end());
}
BOOST_AUTO_TEST_CASE(negative_literals_16bits)
{
char const* sourceCode = R"(
contract test {
function f() public { int64 x = ~0xabc; }
}
)";
bytes code = compileFirstExpression(sourceCode);
bytes expectation(bytes({uint8_t(Instruction::PUSH32)}) + bytes(30, 0xff) + bytes{0xf5, 0x43});
BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end());
}
BOOST_AUTO_TEST_CASE(intermediately_overflowing_literals)
{
// first literal itself is too large for 256 bits but it fits after all constant operations
// have been applied
char const* sourceCode = R"(
contract test {
function f() public { uint8 x = (0x00ffffffffffffffffffffffffffffffffffffffff * 0xffffffffffffffffffffffffff01) & 0xbf; }
}
)";
bytes code = compileFirstExpression(sourceCode);
bytes expectation(bytes({uint8_t(Instruction::PUSH1), 0xbf}));
BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end());
}
BOOST_AUTO_TEST_CASE(blockhash)
{
char const* sourceCode = R"(
contract test {
function f() public {
blockhash(3);
}
}
)";
bytes code = compileFirstExpression(sourceCode, {}, {});
bytes expectation({uint8_t(Instruction::PUSH1), 0x03,
uint8_t(Instruction::BLOCKHASH)});
BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end());
}
BOOST_AUTO_TEST_CASE(
blobhash,
*boost::unit_test::precondition(minEVMVersionCheck(EVMVersion::cancun()))
)
{
char const* sourceCode = R"(
contract test {
function f() public {
blobhash(3);
}
}
)";
bytes code = compileFirstExpression(sourceCode, {}, {});
bytes expectation({
uint8_t(Instruction::PUSH1), 0x03,
uint8_t(Instruction::BLOBHASH)
});
BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end());
}
BOOST_AUTO_TEST_CASE(gas_left)
{
char const* sourceCode = R"(
contract test {
function f() public returns (uint256 val) {
return gasleft();
}
}
)";
bytes code = compileFirstExpression(sourceCode, {}, {});
bytes expectation = bytes({uint8_t(Instruction::GAS)});
BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end());
}
BOOST_AUTO_TEST_CASE(selfbalance)
{
char const* sourceCode = R"(
contract test {
function f() public returns (uint) {
return address(this).balance;
}
}
)";
bytes code = compileFirstExpression(sourceCode, {}, {});
if (solidity::test::CommonOptions::get().evmVersion().hasSelfBalance())
{
bytes expectation({uint8_t(Instruction::SELFBALANCE)});
BOOST_CHECK_EQUAL_COLLECTIONS(code.begin(), code.end(), expectation.begin(), expectation.end());
}
}
BOOST_AUTO_TEST_SUITE_END()
} // end namespaces
| 22,683
|
C++
|
.cpp
| 650
| 32.013846
| 124
| 0.721888
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,978
|
NatspecJSONTest.cpp
|
ethereum_solidity/test/libsolidity/NatspecJSONTest.cpp
|
/*
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/>.
*/
/**
* Unit tests for the solidity compiler ABI JSON Interface output.
*/
#include <test/libsolidity/NatspecJSONTest.h>
#include <libsolutil/CommonIO.h>
#include <libsolutil/StringUtils.h>
#include <boost/algorithm/string/predicate.hpp>
#include <fmt/format.h>
#include <vector>
using namespace solidity::frontend::test;
using namespace solidity::util;
using namespace std::string_literals;
std::ostream& solidity::frontend::test::operator<<(std::ostream& _output, NatspecJSONKind _kind)
{
switch (_kind) {
case NatspecJSONKind::Devdoc: _output << "devdoc"; break;
case NatspecJSONKind::Userdoc: _output << "userdoc"; break;
}
return _output;
}
std::unique_ptr<TestCase> NatspecJSONTest::create(Config const& _config)
{
return std::make_unique<NatspecJSONTest>(_config.filename, _config.evmVersion);
}
void NatspecJSONTest::parseCustomExpectations(std::istream& _stream)
{
soltestAssert(m_expectedNatspecJSON.empty());
// We expect a series of expectations in the following format:
//
// // <qualified contract name> <devdoc|userdoc>
// // <json>
std::string line;
while (getline(_stream, line))
{
std::string_view strippedLine = expectLinePrefix(line);
if (strippedLine.empty())
continue;
auto [contractName, kind] = parseExpectationHeader(strippedLine);
std::string rawJSON = extractExpectationJSON(_stream);
std::string jsonErrors;
Json parsedJSON;
bool jsonParsingSuccessful = jsonParseStrict(rawJSON, parsedJSON, &jsonErrors);
if (!jsonParsingSuccessful)
BOOST_THROW_EXCEPTION(std::runtime_error(fmt::format(
"Malformed JSON in {} expectation for contract {}.\n"
"Note that JSON expectations must be pretty-printed to be split correctly. "
"The object is assumed to and at the first unindented closing brace.\n"
"{}",
toString(kind),
contractName,
rawJSON
)));
m_expectedNatspecJSON[std::string(contractName)][kind] = parsedJSON;
}
}
bool NatspecJSONTest::expectationsMatch()
{
// NOTE: Comparing pretty printed Jsons to avoid using its operator==, which fails to
// compare equal numbers as equal. For example, for 'version' field the value is sometimes int,
// sometimes uint and they compare as different even when both are 1.
return
SyntaxTest::expectationsMatch() &&
prettyPrinted(obtainedNatspec()) == prettyPrinted(m_expectedNatspecJSON);
}
void NatspecJSONTest::printExpectedResult(std::ostream& _stream, std::string const& _linePrefix, bool _formatted) const
{
SyntaxTest::printExpectedResult(_stream, _linePrefix, _formatted);
if (!m_expectedNatspecJSON.empty())
{
_stream << _linePrefix << "----" << std::endl;
printPrefixed(_stream, formatNatspecExpectations(m_expectedNatspecJSON), _linePrefix);
}
}
void NatspecJSONTest::printObtainedResult(std::ostream& _stream, std::string const& _linePrefix, bool _formatted) const
{
SyntaxTest::printObtainedResult(_stream, _linePrefix, _formatted);
NatspecMap natspecJSON = obtainedNatspec();
if (!natspecJSON.empty())
{
_stream << _linePrefix << "----" << std::endl;
// TODO: Diff both versions and highlight differences.
// We should have a helper for doing that in newly defined test cases without much effort.
printPrefixed(_stream, formatNatspecExpectations(natspecJSON), _linePrefix);
}
}
std::tuple<std::string_view, NatspecJSONKind> NatspecJSONTest::parseExpectationHeader(std::string_view _line)
{
for (NatspecJSONKind kind: {NatspecJSONKind::Devdoc, NatspecJSONKind::Userdoc})
{
std::string kindSuffix = " " + toString(kind);
if (boost::algorithm::ends_with(_line, kindSuffix))
return {_line.substr(0, _line.size() - kindSuffix.size()), kind};
}
BOOST_THROW_EXCEPTION(std::runtime_error(
"Natspec kind (devdoc/userdoc) not present in the expectation: "s.append(_line)
));
}
std::string NatspecJSONTest::extractExpectationJSON(std::istream& _stream)
{
std::string rawJSON;
std::string line;
while (getline(_stream, line))
{
std::string_view strippedLine = expectLinePrefix(line);
rawJSON += strippedLine;
rawJSON += "\n";
if (boost::algorithm::starts_with(strippedLine, "}"))
break;
}
return rawJSON;
}
std::string_view NatspecJSONTest::expectLinePrefix(std::string_view _line)
{
size_t startPosition = 0;
if (!boost::algorithm::starts_with(_line, "//"))
BOOST_THROW_EXCEPTION(std::runtime_error(
"Expectation line is not a comment: "s.append(_line)
));
startPosition += 2;
if (startPosition < _line.size() && _line[startPosition] == ' ')
++startPosition;
return _line.substr(startPosition, _line.size() - startPosition);
}
std::string NatspecJSONTest::formatNatspecExpectations(NatspecMap const& _expectations) const
{
std::string output;
bool first = true;
// NOTE: Not sorting explicitly because CompilerStack seems to put contracts roughly in the
// order in which they appear in the source, which is much better than alphabetical order.
for (auto const& [contractName, expectationsForAllKinds]: _expectations)
for (auto const& [jsonKind, natspecJSON]: expectationsForAllKinds)
{
if (!first)
output += "\n\n";
first = false;
output += contractName + " " + toString(jsonKind) + "\n";
output += jsonPrint(natspecJSON, {JsonFormat::Pretty, 4});
}
return output;
}
NatspecMap NatspecJSONTest::obtainedNatspec() const
{
if (compiler().state() < CompilerStack::AnalysisSuccessful)
return {};
NatspecMap result;
for (std::string contractName: compiler().contractNames())
{
result[contractName][NatspecJSONKind::Devdoc] = compiler().natspecDev(contractName);
result[contractName][NatspecJSONKind::Userdoc] = compiler().natspecUser(contractName);
}
return result;
}
SerializedNatspecMap NatspecJSONTest::prettyPrinted(NatspecMap const& _expectations) const
{
SerializedNatspecMap result;
for (auto const& [contractName, expectationsForAllKinds]: _expectations)
for (auto const& [jsonKind, natspecJSON]: expectationsForAllKinds)
result[contractName][jsonKind] = jsonPrint(natspecJSON, {JsonFormat::Pretty, 4});
return result;
}
| 6,676
|
C++
|
.cpp
| 173
| 36.179191
| 119
| 0.757618
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,981
|
InlineAssembly.cpp
|
ethereum_solidity/test/libsolidity/InlineAssembly.cpp
|
/*
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/>.
*/
/**
* @author Christian <c@ethdev.com>
* @date 2016
* Unit tests for inline assembly.
*/
#include <test/Common.h>
#include <test/libsolidity/ErrorCheck.h>
#include <libsolidity/ast/AST.h>
#include <libyul/YulStack.h>
#include <liblangutil/DebugInfoSelection.h>
#include <liblangutil/Exceptions.h>
#include <liblangutil/Scanner.h>
#include <liblangutil/SourceReferenceFormatter.h>
#include <libevmasm/Assembly.h>
#include <boost/algorithm/string/replace.hpp>
#include <boost/test/unit_test.hpp>
#include <memory>
#include <optional>
#include <string>
using namespace solidity::langutil;
using namespace solidity::yul;
namespace solidity::frontend::test
{
namespace
{
std::optional<Error> parseAndReturnFirstError(
std::string const& _source,
bool _assemble = false,
bool _allowWarnings = true,
YulStack::Language _language = YulStack::Language::Assembly,
YulStack::Machine _machine = YulStack::Machine::EVM
)
{
YulStack stack(
solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion(),
_language,
solidity::frontend::OptimiserSettings::none(),
DebugInfoSelection::None()
);
bool success = stack.parseAndAnalyze("", _source);
if (success && _assemble)
stack.assemble(_machine);
std::shared_ptr<Error const> error;
for (auto const& e: stack.errors())
{
if (_allowWarnings && e->type() == Error::Type::Warning)
continue;
if (error)
BOOST_FAIL(
"Found more than one error:\n" +
SourceReferenceFormatter::formatErrorInformation(stack.errors(), stack)
);
error = e;
}
if (!success)
BOOST_REQUIRE(error);
if (error)
return *error;
return {};
}
bool successParse(
std::string const& _source,
bool _assemble = false,
bool _allowWarnings = true,
YulStack::Language _language = YulStack::Language::Assembly,
YulStack::Machine _machine = YulStack::Machine::EVM
)
{
return !parseAndReturnFirstError(_source, _assemble, _allowWarnings, _language, _machine);
}
bool successAssemble(std::string const& _source, bool _allowWarnings = true, YulStack::Language _language = YulStack::Language::Assembly)
{
return
successParse(_source, true, _allowWarnings, _language, YulStack::Machine::EVM);
}
Error expectError(
std::string const& _source,
bool _assemble,
bool _allowWarnings = false,
YulStack::Language _language = YulStack::Language::Assembly
)
{
auto error = parseAndReturnFirstError(_source, _assemble, _allowWarnings, _language);
BOOST_REQUIRE(error);
return *error;
}
void parsePrintCompare(std::string const& _source, bool _canWarn = false)
{
YulStack stack(
solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion(),
YulStack::Language::Assembly,
OptimiserSettings::none(),
DebugInfoSelection::None()
);
BOOST_REQUIRE(stack.parseAndAnalyze("", _source));
if (_canWarn)
BOOST_REQUIRE(!Error::containsErrors(stack.errors()));
else
BOOST_REQUIRE(!Error::hasErrorsWarningsOrInfos(stack.errors()));
std::string expectation = "object \"object\" {\n code " + boost::replace_all_copy(_source, "\n", "\n ") + "\n}\n";
BOOST_CHECK_EQUAL(stack.print(), expectation);
}
}
#define CHECK_ERROR_LANG(text, assemble, typ, substring, warnings, language) \
do \
{ \
Error err = expectError((text), (assemble), warnings, (language)); \
BOOST_CHECK(err.type() == (Error::Type::typ)); \
BOOST_CHECK(searchErrorMessage(err, (substring))); \
} while(0)
#define CHECK_ERROR(text, assemble, typ, substring, warnings) \
CHECK_ERROR_LANG(text, assemble, typ, substring, warnings, YulStack::Language::Assembly)
#define CHECK_PARSE_ERROR(text, type, substring) \
CHECK_ERROR(text, false, type, substring, false)
#define CHECK_PARSE_WARNING(text, type, substring) \
CHECK_ERROR(text, false, type, substring, false)
#define CHECK_ASSEMBLE_ERROR(text, type, substring) \
CHECK_ERROR(text, true, type, substring, false)
#define CHECK_STRICT_ERROR(text, type, substring) \
CHECK_ERROR_LANG(text, false, type, substring, false, YulStack::Language::StrictAssembly)
#define CHECK_STRICT_WARNING(text, type, substring) \
CHECK_ERROR(text, false, type, substring, false, YulStack::Language::StrictAssembly)
#define SUCCESS_STRICT(text) \
do { successParse((text), false, false, YulStack::Language::StrictAssembly); } while (false)
BOOST_AUTO_TEST_SUITE(SolidityInlineAssembly)
BOOST_AUTO_TEST_SUITE(Printing) // {{{
BOOST_AUTO_TEST_CASE(print_smoke)
{
parsePrintCompare("{ }");
}
BOOST_AUTO_TEST_CASE(print_instructions)
{
parsePrintCompare("{ pop(7) }");
}
BOOST_AUTO_TEST_CASE(print_subblock)
{
parsePrintCompare("{ { pop(7) } }");
}
BOOST_AUTO_TEST_CASE(print_functional)
{
parsePrintCompare("{ let x := mul(sload(0x12), 7) }");
}
BOOST_AUTO_TEST_CASE(print_assignments)
{
parsePrintCompare("{\n let x := mul(2, 3)\n pop(7)\n x := add(1, 2)\n}");
}
BOOST_AUTO_TEST_CASE(print_multi_assignments)
{
parsePrintCompare("{\n function f() -> x, y\n { }\n let x, y := f()\n}");
}
BOOST_AUTO_TEST_CASE(print_string_literals)
{
parsePrintCompare("{ let x := \"\\n'\\xab\\x95\\\"\" }");
}
BOOST_AUTO_TEST_CASE(print_string_literal_unicode)
{
std::string source = "{ let x := \"\\u1bac\" }";
std::string parsed = "object \"object\" {\n code { let x := \"\\xe1\\xae\\xac\" }\n}\n";
YulStack stack(
solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion(),
YulStack::Language::Assembly,
OptimiserSettings::none(),
DebugInfoSelection::None()
);
BOOST_REQUIRE(stack.parseAndAnalyze("", source));
BOOST_REQUIRE(!Error::hasErrorsWarningsOrInfos(stack.errors()));
BOOST_CHECK_EQUAL(stack.print(), parsed);
std::string parsedInner = "{ let x := \"\\xe1\\xae\\xac\" }";
parsePrintCompare(parsedInner);
}
BOOST_AUTO_TEST_CASE(print_if)
{
parsePrintCompare("{ if 2 { pop(mload(0)) } }");
}
BOOST_AUTO_TEST_CASE(print_switch)
{
parsePrintCompare("{\n switch 42\n case 1 { }\n case 2 { }\n default { }\n}");
}
BOOST_AUTO_TEST_CASE(print_for)
{
parsePrintCompare("{\n let ret := 5\n for { let i := 1 } lt(i, 15) { i := add(i, 1) }\n { ret := mul(ret, i) }\n}");
}
BOOST_AUTO_TEST_CASE(function_definitions_multiple_args)
{
parsePrintCompare("{\n function f(a, d)\n { mstore(a, d) }\n function g(a, d) -> x, y\n { }\n}");
}
BOOST_AUTO_TEST_CASE(function_calls)
{
std::string source = R"({
function y()
{ }
function f(a) -> b
{ }
function g(a, b, c)
{ }
g(1, mul(2, address()), f(mul(2, caller())))
y()
})";
boost::replace_all(source, "\t", " ");
parsePrintCompare(source);
}
BOOST_AUTO_TEST_SUITE_END()
// }}}
BOOST_AUTO_TEST_SUITE(Analysis) // {{{
BOOST_AUTO_TEST_CASE(string_literals)
{
BOOST_CHECK(successAssemble("{ let x := \"12345678901234567890123456789012\" }"));
}
BOOST_AUTO_TEST_CASE(oversize_string_literals)
{
CHECK_ASSEMBLE_ERROR("{ let x := \"123456789012345678901234567890123\" }", TypeError, "String literal too long");
}
BOOST_AUTO_TEST_CASE(magic_variables)
{
CHECK_ASSEMBLE_ERROR("{ pop(this) }", DeclarationError, "Identifier \"this\" not found");
CHECK_ASSEMBLE_ERROR("{ pop(ecrecover) }", DeclarationError, "Identifier \"ecrecover\" not found");
BOOST_CHECK(successAssemble("{ let ecrecover := 1 pop(ecrecover) }"));
}
BOOST_AUTO_TEST_CASE(stack_variables)
{
BOOST_CHECK(successAssemble("{ let y := 3 { let z := 2 { let x := y } } }"));
}
BOOST_AUTO_TEST_CASE(designated_invalid_instruction)
{
BOOST_CHECK(successAssemble("{ invalid() }"));
}
BOOST_AUTO_TEST_CASE(inline_assembly_shadowed_instruction_declaration)
{
CHECK_ASSEMBLE_ERROR("{ let gas := 1 }", ParserError, "Cannot use builtin");
}
BOOST_AUTO_TEST_CASE(revert)
{
BOOST_CHECK(successAssemble("{ revert(0, 0) }"));
}
BOOST_AUTO_TEST_CASE(large_constant)
{
auto source = R"({
switch mul(1, 2)
case 0x0000000000000000000000000000000000000000000000000000000026121ff0 {
}
})";
BOOST_CHECK(successAssemble(source));
}
BOOST_AUTO_TEST_CASE(keccak256)
{
BOOST_CHECK(successAssemble("{ pop(keccak256(0, 0)) }"));
}
BOOST_AUTO_TEST_CASE(returndatasize)
{
if (!solidity::test::CommonOptions::get().evmVersion().supportsReturndata())
return;
BOOST_CHECK(successAssemble("{ let r := returndatasize() }"));
}
BOOST_AUTO_TEST_CASE(returndatacopy)
{
if (!solidity::test::CommonOptions::get().evmVersion().supportsReturndata())
return;
BOOST_CHECK(successAssemble("{ returndatacopy(0, 32, 64) }"));
}
BOOST_AUTO_TEST_CASE(staticcall)
{
if (!solidity::test::CommonOptions::get().evmVersion().hasStaticCall())
return;
BOOST_CHECK(successAssemble("{ pop(staticcall(10000, 0x123, 64, 0x10, 128, 0x10)) }"));
}
BOOST_AUTO_TEST_CASE(create2)
{
if (!solidity::test::CommonOptions::get().evmVersion().hasCreate2())
return;
BOOST_CHECK(successAssemble("{ pop(create2(10, 0x123, 32, 64)) }"));
}
BOOST_AUTO_TEST_CASE(shift)
{
if (!solidity::test::CommonOptions::get().evmVersion().hasBitwiseShifting())
return;
BOOST_CHECK(successAssemble("{ pop(shl(10, 32)) }"));
BOOST_CHECK(successAssemble("{ pop(shr(10, 32)) }"));
BOOST_CHECK(successAssemble("{ pop(sar(10, 32)) }"));
}
BOOST_AUTO_TEST_CASE(shift_constantinople_warning)
{
if (solidity::test::CommonOptions::get().evmVersion().hasBitwiseShifting())
return;
CHECK_PARSE_WARNING("{ shl(10, 32) }", TypeError, "The \"shl\" instruction is only available for Constantinople-compatible VMs");
CHECK_PARSE_WARNING("{ shr(10, 32) }", TypeError, "The \"shr\" instruction is only available for Constantinople-compatible VMs");
CHECK_PARSE_WARNING("{ sar(10, 32) }", TypeError, "The \"sar\" instruction is only available for Constantinople-compatible VMs");
}
BOOST_AUTO_TEST_SUITE_END() // }}}
BOOST_AUTO_TEST_SUITE_END()
} // end namespaces
| 10,397
|
C++
|
.cpp
| 306
| 32.006536
| 137
| 0.719601
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,983
|
StandardCompiler.cpp
|
ethereum_solidity/test/libsolidity/StandardCompiler.cpp
|
/*
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
/**
* @date 2017
* Unit tests for interface/StandardCompiler.h.
*/
#include <string>
#include <boost/test/unit_test.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <libsolidity/interface/OptimiserSettings.h>
#include <libsolidity/interface/StandardCompiler.h>
#include <libsolidity/interface/Version.h>
#include <libsolutil/JSON.h>
#include <libsolutil/CommonData.h>
#include <test/Metadata.h>
#include <test/Common.h>
#include <algorithm>
#include <set>
using namespace solidity::evmasm;
using namespace std::string_literals;
namespace solidity::frontend::test
{
namespace
{
langutil::Error::Severity str2Severity(std::string const& _cat)
{
std::map<std::string, langutil::Error::Severity> cats{
{"info", langutil::Error::Severity::Info},
{"Info", langutil::Error::Severity::Info},
{"warning", langutil::Error::Severity::Warning},
{"Warning", langutil::Error::Severity::Warning},
{"error", langutil::Error::Severity::Error},
{"Error", langutil::Error::Severity::Error}
};
return cats.at(_cat);
}
/// Helper to match a specific error type and message
bool containsError(Json const& _compilerResult, std::string const& _type, std::string const& _message)
{
if (!_compilerResult.contains("errors"))
return false;
for (auto const& error: _compilerResult["errors"])
{
BOOST_REQUIRE(error.is_object());
BOOST_REQUIRE(error["type"].is_string());
BOOST_REQUIRE(error["message"].is_string());
if ((error["type"].get<std::string>() == _type) && (error["message"].get<std::string>() == _message))
return true;
}
return false;
}
bool containsAtMostWarnings(Json const& _compilerResult)
{
if (!_compilerResult.contains("errors"))
return true;
for (auto const& error: _compilerResult["errors"])
{
BOOST_REQUIRE(error.is_object());
BOOST_REQUIRE(error["severity"].is_string());
if (langutil::Error::isError(str2Severity(error["severity"].get<std::string>())))
return false;
}
return true;
}
Json getContractResult(Json const& _compilerResult, std::string const& _file, std::string const& _name)
{
if (!_compilerResult.contains("contracts") ||
!_compilerResult["contracts"].is_object() ||
!_compilerResult["contracts"][_file].is_object() ||
!_compilerResult["contracts"][_file][_name].is_object()
)
return Json();
return _compilerResult["contracts"][_file][_name];
}
void checkLinkReferencesSchema(Json const& _contractResult)
{
BOOST_TEST_REQUIRE(_contractResult.is_object());
BOOST_TEST_REQUIRE(_contractResult["evm"]["bytecode"].is_object());
Json const& linkReferenceResult = _contractResult["evm"]["bytecode"]["linkReferences"];
BOOST_TEST_REQUIRE(linkReferenceResult.is_object());
for (auto const& [fileName, references]: linkReferenceResult.items())
{
BOOST_TEST_REQUIRE(references.is_object());
for (auto const& [libraryName, libraryValue]: references.items())
{
BOOST_TEST_REQUIRE(libraryValue.is_array());
BOOST_TEST_REQUIRE(!libraryValue.empty());
for (size_t i = 0; i < static_cast<size_t>(linkReferenceResult.size()); ++i)
{
BOOST_TEST_REQUIRE(libraryValue[i].is_object());
BOOST_TEST_REQUIRE(libraryValue[i].size() == 2);
BOOST_TEST_REQUIRE(libraryValue[i]["length"].is_number_unsigned());
BOOST_TEST_REQUIRE(libraryValue[i]["start"].is_number_unsigned());
}
}
}
}
void expectLinkReferences(Json const& _contractResult, std::map<std::string, std::set<std::string>> const& _expectedLinkReferences)
{
checkLinkReferencesSchema(_contractResult);
Json const& linkReferenceResult = _contractResult["evm"]["bytecode"]["linkReferences"];
BOOST_TEST(linkReferenceResult.size() == _expectedLinkReferences.size());
for (auto const& [fileName, libraries]: _expectedLinkReferences)
{
BOOST_TEST(linkReferenceResult.contains(fileName));
BOOST_TEST(linkReferenceResult[fileName].size() == libraries.size());
for (std::string const& libraryName: libraries)
BOOST_TEST(linkReferenceResult[fileName].contains(libraryName));
}
}
Json compile(std::string _input)
{
StandardCompiler compiler;
std::string output = compiler.compile(std::move(_input));
Json ret;
BOOST_REQUIRE(util::jsonParseStrict(output, ret));
return ret;
}
} // end anonymous namespace
BOOST_AUTO_TEST_SUITE(StandardCompiler)
BOOST_AUTO_TEST_CASE(assume_object_input)
{
Json result;
/// Use the native JSON interface of StandardCompiler to trigger these
frontend::StandardCompiler compiler;
result = compiler.compile(Json());
BOOST_CHECK(containsError(result, "JSONError", "Input is not a JSON object."));
result = compiler.compile(Json("INVALID"));
BOOST_CHECK(containsError(result, "JSONError", "Input is not a JSON object."));
/// Use the string interface of StandardCompiler to trigger these
result = compile("");
BOOST_CHECK(containsError(result, "JSONError", "parse error at line 1, column 1: attempting to parse an empty input; check that your input string or stream contains the expected JSON"));
result = compile("invalid");
BOOST_CHECK(containsError(result, "JSONError", "parse error at line 1, column 1: syntax error while parsing value - invalid literal; last read: 'i'"));
result = compile("\"invalid\"");
BOOST_CHECK(containsError(result, "JSONError", "Input is not a JSON object."));
result = compile("{}");
BOOST_CHECK(containsError(result, "JSONError", "No input sources specified."));
BOOST_CHECK(!containsAtMostWarnings(result));
}
BOOST_AUTO_TEST_CASE(invalid_language)
{
char const* input = R"(
{
"language": "INVALID",
"sources": { "name": { "content": "abc" } }
}
)";
Json result = compile(input);
BOOST_CHECK(containsError(result, "JSONError", "Only \"Solidity\", \"Yul\", \"SolidityAST\" or \"EVMAssembly\" is supported as a language."));
}
BOOST_AUTO_TEST_CASE(valid_language)
{
char const* input = R"(
{
"language": "Solidity"
}
)";
Json result = compile(input);
BOOST_CHECK(!containsError(result, "JSONError", "Only \"Solidity\" or \"Yul\" is supported as a language."));
}
BOOST_AUTO_TEST_CASE(no_sources)
{
char const* input = R"(
{
"language": "Solidity"
}
)";
Json result = compile(input);
BOOST_CHECK(containsError(result, "JSONError", "No input sources specified."));
}
BOOST_AUTO_TEST_CASE(no_sources_empty_object)
{
char const* input = R"(
{
"language": "Solidity",
"sources": {}
}
)";
Json result = compile(input);
BOOST_CHECK(containsError(result, "JSONError", "No input sources specified."));
}
BOOST_AUTO_TEST_CASE(no_sources_empty_array)
{
char const* input = R"(
{
"language": "Solidity",
"sources": []
}
)";
Json result = compile(input);
BOOST_CHECK(containsError(result, "JSONError", "\"sources\" is not a JSON object."));
}
BOOST_AUTO_TEST_CASE(sources_is_array)
{
char const* input = R"(
{
"language": "Solidity",
"sources": ["aa", "bb"]
}
)";
Json result = compile(input);
BOOST_CHECK(containsError(result, "JSONError", "\"sources\" is not a JSON object."));
}
BOOST_AUTO_TEST_CASE(unexpected_trailing_test)
{
char const* input = R"(
{
"language": "Solidity",
"sources": {
"A": {
"content": "contract A { function f() {} }"
}
}
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsError(result, "JSONError", "parse error at line 10, column 2: syntax error while parsing value - unexpected '}'; expected end of input"));
}
BOOST_AUTO_TEST_CASE(smoke_test)
{
char const* input = R"(
{
"language": "Solidity",
"sources": {
"empty": {
"content": ""
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsAtMostWarnings(result));
}
BOOST_AUTO_TEST_CASE(optimizer_enabled_not_boolean)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"optimizer": {
"enabled": "wrong"
}
},
"sources": {
"empty": {
"content": ""
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsError(result, "JSONError", "The \"enabled\" setting must be a Boolean."));
}
BOOST_AUTO_TEST_CASE(optimizer_runs_not_a_number)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"optimizer": {
"enabled": true,
"runs": "not a number"
}
},
"sources": {
"empty": {
"content": ""
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsError(result, "JSONError", "The \"runs\" setting must be an unsigned number."));
}
BOOST_AUTO_TEST_CASE(optimizer_runs_not_an_unsigned_number)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"optimizer": {
"enabled": true,
"runs": -1
}
},
"sources": {
"empty": {
"content": ""
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsError(result, "JSONError", "The \"runs\" setting must be an unsigned number."));
}
BOOST_AUTO_TEST_CASE(basic_compilation)
{
char const* input = R"(
{
"language": "Solidity",
"sources": {
"fileA": {
"content": "contract A { }"
}
},
"settings": {
"outputSelection": {
"fileA": {
"A": [ "abi", "devdoc", "userdoc", "evm.bytecode", "evm.assembly", "evm.gasEstimates", "evm.legacyAssembly", "metadata" ],
"": [ "ast" ]
}
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsAtMostWarnings(result));
Json contract = getContractResult(result, "fileA", "A");
BOOST_CHECK(contract.is_object());
BOOST_CHECK(contract["abi"].is_array());
BOOST_CHECK_EQUAL(util::jsonCompactPrint(contract["abi"]), "[]");
BOOST_CHECK(contract["devdoc"].is_object());
BOOST_CHECK_EQUAL(util::jsonCompactPrint(contract["devdoc"]), R"({"kind":"dev","methods":{},"version":1})");
BOOST_CHECK(contract["userdoc"].is_object());
BOOST_CHECK_EQUAL(util::jsonCompactPrint(contract["userdoc"]), R"({"kind":"user","methods":{},"version":1})");
BOOST_CHECK(contract["evm"].is_object());
/// @TODO check evm.methodIdentifiers, legacyAssembly, bytecode, deployedBytecode
BOOST_CHECK(contract["evm"]["bytecode"].is_object());
BOOST_CHECK(contract["evm"]["bytecode"]["object"].is_string());
BOOST_CHECK_EQUAL(
solidity::test::bytecodeSansMetadata(contract["evm"]["bytecode"]["object"].get<std::string>()),
std::string("6080604052348015600e575f5ffd5b5060") +
(VersionIsRelease ? "3e" : util::toHex(bytes{uint8_t(60 + VersionStringStrict.size())})) +
"80601a5f395ff3fe60806040525f5ffdfe"
);
BOOST_CHECK(contract["evm"]["assembly"].is_string());
BOOST_CHECK(contract["evm"]["assembly"].get<std::string>().find(
" /* \"fileA\":0:14 contract A { } */\n mstore(0x40, 0x80)\n "
"callvalue\n dup1\n "
"iszero\n tag_1\n jumpi\n "
"revert(0x00, 0x00)\n"
"tag_1:\n pop\n dataSize(sub_0)\n dup1\n "
"dataOffset(sub_0)\n 0x00\n codecopy\n 0x00\n return\nstop\n\nsub_0: assembly {\n "
"/* \"fileA\":0:14 contract A { } */\n mstore(0x40, 0x80)\n "
"revert(0x00, 0x00)\n\n auxdata: 0xa26469706673582212"
) == 0);
BOOST_CHECK(contract["evm"]["gasEstimates"].is_object());
BOOST_CHECK_EQUAL(contract["evm"]["gasEstimates"].size(), 1);
BOOST_CHECK(contract["evm"]["gasEstimates"]["creation"].is_object());
BOOST_CHECK_EQUAL(contract["evm"]["gasEstimates"]["creation"].size(), 3);
BOOST_CHECK(contract["evm"]["gasEstimates"]["creation"]["codeDepositCost"].is_string());
BOOST_CHECK(contract["evm"]["gasEstimates"]["creation"]["executionCost"].is_string());
BOOST_CHECK(contract["evm"]["gasEstimates"]["creation"]["totalCost"].is_string());
BOOST_CHECK_EQUAL(
u256(contract["evm"]["gasEstimates"]["creation"]["codeDepositCost"].get<std::string>()) +
u256(contract["evm"]["gasEstimates"]["creation"]["executionCost"].get<std::string>()),
u256(contract["evm"]["gasEstimates"]["creation"]["totalCost"].get<std::string>())
);
// Lets take the top level `.code` section (the "deployer code"), that should expose most of the features of
// the assembly JSON. What we want to check here is Operation, Push, PushTag, PushSub, PushSubSize and Tag.
BOOST_CHECK(contract["evm"]["legacyAssembly"].is_object());
BOOST_CHECK(contract["evm"]["legacyAssembly"][".code"].is_array());
BOOST_CHECK_EQUAL(
util::jsonCompactPrint(contract["evm"]["legacyAssembly"][".code"]),
"[{\"begin\":0,\"end\":14,\"name\":\"PUSH\",\"source\":0,\"value\":\"80\"},"
"{\"begin\":0,\"end\":14,\"name\":\"PUSH\",\"source\":0,\"value\":\"40\"},"
"{\"begin\":0,\"end\":14,\"name\":\"MSTORE\",\"source\":0},"
"{\"begin\":0,\"end\":14,\"name\":\"CALLVALUE\",\"source\":0},"
"{\"begin\":0,\"end\":14,\"name\":\"DUP1\",\"source\":0},"
"{\"begin\":0,\"end\":14,\"name\":\"ISZERO\",\"source\":0},"
"{\"begin\":0,\"end\":14,\"name\":\"PUSH [tag]\",\"source\":0,\"value\":\"1\"},"
"{\"begin\":0,\"end\":14,\"name\":\"JUMPI\",\"source\":0},"
"{\"begin\":0,\"end\":14,\"name\":\"PUSH\",\"source\":0,\"value\":\"0\"},"
"{\"begin\":0,\"end\":14,\"name\":\"PUSH\",\"source\":0,\"value\":\"0\"},"
"{\"begin\":0,\"end\":14,\"name\":\"REVERT\",\"source\":0},"
"{\"begin\":0,\"end\":14,\"name\":\"tag\",\"source\":0,\"value\":\"1\"},"
"{\"begin\":0,\"end\":14,\"name\":\"JUMPDEST\",\"source\":0},"
"{\"begin\":0,\"end\":14,\"name\":\"POP\",\"source\":0},"
"{\"begin\":0,\"end\":14,\"name\":\"PUSH #[$]\",\"source\":0,\"value\":\"0000000000000000000000000000000000000000000000000000000000000000\"},"
"{\"begin\":0,\"end\":14,\"name\":\"DUP1\",\"source\":0},"
"{\"begin\":0,\"end\":14,\"name\":\"PUSH [$]\",\"source\":0,\"value\":\"0000000000000000000000000000000000000000000000000000000000000000\"},"
"{\"begin\":0,\"end\":14,\"name\":\"PUSH\",\"source\":0,\"value\":\"0\"},"
"{\"begin\":0,\"end\":14,\"name\":\"CODECOPY\",\"source\":0},"
"{\"begin\":0,\"end\":14,\"name\":\"PUSH\",\"source\":0,\"value\":\"0\"},"
"{\"begin\":0,\"end\":14,\"name\":\"RETURN\",\"source\":0}]"
);
BOOST_CHECK(contract["metadata"].is_string());
BOOST_CHECK(solidity::test::isValidMetadata(contract["metadata"].get<std::string>()));
BOOST_CHECK(result["sources"].is_object());
BOOST_CHECK(result["sources"]["fileA"].is_object());
BOOST_CHECK(result["sources"]["fileA"]["ast"].is_object());
BOOST_CHECK_EQUAL(
util::jsonCompactPrint(result["sources"]["fileA"]["ast"]),
"{\"absolutePath\":\"fileA\",\"exportedSymbols\":{\"A\":[1]},\"id\":2,\"nodeType\":\"SourceUnit\",\"nodes\":[{\"abstract\":false,"
"\"baseContracts\":[],\"canonicalName\":\"A\",\"contractDependencies\":[],"
"\"contractKind\":\"contract\",\"fullyImplemented\":true,\"id\":1,"
"\"linearizedBaseContracts\":[1],\"name\":\"A\",\"nameLocation\":\"9:1:0\",\"nodeType\":\"ContractDefinition\",\"nodes\":[],\"scope\":2,"
"\"src\":\"0:14:0\",\"usedErrors\":[],\"usedEvents\":[]}],\"src\":\"0:14:0\"}"
);
}
BOOST_AUTO_TEST_CASE(compilation_error)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"outputSelection": {
"fileA": {
"A": [
"abi"
]
}
}
},
"sources": {
"fileA": {
"content": "contract A { function }"
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(result.contains("errors"));
BOOST_CHECK(result["errors"].size() >= 1);
for (auto const& error: result["errors"])
{
BOOST_REQUIRE(error.is_object());
BOOST_REQUIRE(error["message"].is_string());
if (error["message"].get<std::string>().find("pre-release compiler") == std::string::npos)
{
BOOST_CHECK_EQUAL(
util::jsonCompactPrint(error),
"{\"component\":\"general\",\"errorCode\":\"2314\",\"formattedMessage\":\"ParserError: Expected identifier but got '}'\\n"
" --> fileA:1:23:\\n |\\n1 | contract A { function }\\n | ^\\n\\n\",\"message\":\"Expected identifier but got '}'\","
"\"severity\":\"error\",\"sourceLocation\":{\"end\":23,\"file\":\"fileA\",\"start\":22},\"type\":\"ParserError\"}"
);
}
}
}
BOOST_AUTO_TEST_CASE(output_selection_explicit)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"outputSelection": {
"fileA": {
"A": [
"abi"
]
}
}
},
"sources": {
"fileA": {
"content": "contract A { }"
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsAtMostWarnings(result));
Json contract = getContractResult(result, "fileA", "A");
BOOST_CHECK(contract.is_object());
BOOST_CHECK(contract["abi"].is_array());
BOOST_CHECK_EQUAL(util::jsonCompactPrint(contract["abi"]), "[]");
}
BOOST_AUTO_TEST_CASE(output_selection_all_contracts)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"outputSelection": {
"fileA": {
"*": [
"abi"
]
}
}
},
"sources": {
"fileA": {
"content": "contract A { }"
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsAtMostWarnings(result));
Json contract = getContractResult(result, "fileA", "A");
BOOST_CHECK(contract.is_object());
BOOST_CHECK(contract["abi"].is_array());
BOOST_CHECK_EQUAL(util::jsonCompactPrint(contract["abi"]), "[]");
}
BOOST_AUTO_TEST_CASE(output_selection_all_files_single_contract)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"outputSelection": {
"*": {
"A": [
"abi"
]
}
}
},
"sources": {
"fileA": {
"content": "contract A { }"
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsAtMostWarnings(result));
Json contract = getContractResult(result, "fileA", "A");
BOOST_CHECK(contract.is_object());
BOOST_CHECK(contract["abi"].is_array());
BOOST_CHECK_EQUAL(util::jsonCompactPrint(contract["abi"]), "[]");
}
BOOST_AUTO_TEST_CASE(output_selection_all_files_all_contracts)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"outputSelection": {
"*": {
"*": [
"abi"
]
}
}
},
"sources": {
"fileA": {
"content": "contract A { }"
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsAtMostWarnings(result));
Json contract = getContractResult(result, "fileA", "A");
BOOST_CHECK(contract.is_object());
BOOST_CHECK(contract["abi"].is_array());
BOOST_CHECK_EQUAL(util::jsonCompactPrint(contract["abi"]), "[]");
}
BOOST_AUTO_TEST_CASE(output_selection_dependent_contract)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"outputSelection": {
"*": {
"A": [
"abi"
]
}
}
},
"sources": {
"fileA": {
"content": "contract B { } contract A { function f() public { new B(); } }"
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsAtMostWarnings(result));
Json contract = getContractResult(result, "fileA", "A");
BOOST_CHECK(contract.is_object());
BOOST_CHECK(contract["abi"].is_array());
BOOST_CHECK_EQUAL(util::jsonCompactPrint(contract["abi"]), "[{\"inputs\":[],\"name\":\"f\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]");
}
BOOST_AUTO_TEST_CASE(output_selection_dependent_contract_with_import)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"outputSelection": {
"*": {
"A": [
"abi"
]
}
}
},
"sources": {
"fileA": {
"content": "import \"fileB\"; contract A { function f() public { new B(); } }"
},
"fileB": {
"content": "contract B { }"
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsAtMostWarnings(result));
Json contract = getContractResult(result, "fileA", "A");
BOOST_CHECK(contract.is_object());
BOOST_CHECK(contract["abi"].is_array());
BOOST_CHECK_EQUAL(util::jsonCompactPrint(contract["abi"]), "[{\"inputs\":[],\"name\":\"f\",\"outputs\":[],\"stateMutability\":\"nonpayable\",\"type\":\"function\"}]");
}
BOOST_AUTO_TEST_CASE(filename_with_colon)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"outputSelection": {
"http://github.com/ethereum/solidity/std/StandardToken.sol": {
"A": [
"abi"
]
}
}
},
"sources": {
"http://github.com/ethereum/solidity/std/StandardToken.sol": {
"content": "contract A { }"
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsAtMostWarnings(result));
Json contract = getContractResult(result, "http://github.com/ethereum/solidity/std/StandardToken.sol", "A");
BOOST_CHECK(contract.is_object());
BOOST_CHECK(contract["abi"].is_array());
BOOST_CHECK_EQUAL(util::jsonCompactPrint(contract["abi"]), "[]");
}
BOOST_AUTO_TEST_CASE(library_filename_with_colon)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"outputSelection": {
"fileA": {
"A": [
"evm.bytecode"
]
}
}
},
"sources": {
"fileA": {
"content": "import \"git:library.sol\"; contract A { function f() public returns (uint) { return L.g(); } }"
},
"git:library.sol": {
"content": "library L { function g() public returns (uint) { return 1; } }"
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsAtMostWarnings(result));
Json contract = getContractResult(result, "fileA", "A");
BOOST_CHECK(contract.is_object());
expectLinkReferences(contract, {{"git:library.sol", {"L"}}});
}
BOOST_AUTO_TEST_CASE(libraries_invalid_top_level)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"libraries": "42"
},
"sources": {
"empty": {
"content": ""
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsError(result, "JSONError", "\"libraries\" is not a JSON object."));
}
BOOST_AUTO_TEST_CASE(libraries_invalid_entry)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"libraries": {
"L": "42"
}
},
"sources": {
"empty": {
"content": ""
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsError(result, "JSONError", "Library entry is not a JSON object."));
}
BOOST_AUTO_TEST_CASE(libraries_invalid_hex)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"libraries": {
"library.sol": {
"L": "0x4200000000000000000000000000000000000xx1"
}
}
},
"sources": {
"empty": {
"content": ""
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsError(result, "JSONError", "Invalid library address (\"0x4200000000000000000000000000000000000xx1\") supplied."));
}
BOOST_AUTO_TEST_CASE(libraries_invalid_length)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"libraries": {
"library.sol": {
"L1": "0x42",
"L2": "0x4200000000000000000000000000000000000001ff"
}
}
},
"sources": {
"empty": {
"content": ""
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsError(result, "JSONError", "Library address is of invalid length."));
}
BOOST_AUTO_TEST_CASE(libraries_missing_hex_prefix)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"libraries": {
"library.sol": {
"L": "4200000000000000000000000000000000000001"
}
}
},
"sources": {
"empty": {
"content": ""
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsError(result, "JSONError", "Library address is not prefixed with \"0x\"."));
}
BOOST_AUTO_TEST_CASE(library_linking)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"libraries": {
"library.sol": {
"L": "0x4200000000000000000000000000000000000001"
}
},
"outputSelection": {
"fileA": {
"A": [
"evm.bytecode"
]
}
}
},
"sources": {
"fileA": {
"content": "import \"library.sol\"; import \"library2.sol\"; contract A { function f() public returns (uint) { L2.g(); return L.g(); } }"
},
"library.sol": {
"content": "library L { function g() public returns (uint) { return 1; } }"
},
"library2.sol": {
"content": "library L2 { function g() public { } }"
}
}
}
)";
Json result = compile(input);
BOOST_TEST(containsAtMostWarnings(result));
Json contractResult = getContractResult(result, "fileA", "A");
expectLinkReferences(contractResult, {{"library2.sol", {"L2"}}});
}
BOOST_AUTO_TEST_CASE(linking_yul)
{
char const* input = R"(
{
"language": "Yul",
"settings": {
"libraries": {
"fileB": {
"L": "0x4200000000000000000000000000000000000001"
}
},
"outputSelection": {
"fileA": {
"*": [
"evm.bytecode.linkReferences"
]
}
}
},
"sources": {
"fileA": {
"content": "object \"a\" { code { let addr := linkersymbol(\"fileB:L\") sstore(0, addr) } }"
}
}
}
)";
Json result = compile(input);
BOOST_TEST(containsAtMostWarnings(result));
Json contractResult = getContractResult(result, "fileA", "a");
expectLinkReferences(contractResult, {});
}
BOOST_AUTO_TEST_CASE(linking_yul_empty_link_reference)
{
char const* input = R"(
{
"language": "Yul",
"settings": {
"libraries": {
"": {
"": "0x4200000000000000000000000000000000000001"
}
},
"outputSelection": {
"fileA": {
"*": [
"evm.bytecode.linkReferences"
]
}
}
},
"sources": {
"fileA": {
"content": "object \"a\" { code { let addr := linkersymbol(\"\") sstore(0, addr) } }"
}
}
}
)";
Json result = compile(input);
BOOST_TEST(containsAtMostWarnings(result));
Json contractResult = getContractResult(result, "fileA", "a");
expectLinkReferences(contractResult, {{"", {""}}});
}
BOOST_AUTO_TEST_CASE(linking_yul_no_filename_in_link_reference)
{
char const* input = R"(
{
"language": "Yul",
"settings": {
"libraries": {
"": {
"L": "0x4200000000000000000000000000000000000001"
}
},
"outputSelection": {
"fileA": {
"*": [
"evm.bytecode.linkReferences"
]
}
}
},
"sources": {
"fileA": {
"content": "object \"a\" { code { let addr := linkersymbol(\"L\") sstore(0, addr) } }"
}
}
}
)";
Json result = compile(input);
BOOST_TEST(containsAtMostWarnings(result));
Json contractResult = getContractResult(result, "fileA", "a");
expectLinkReferences(contractResult, {{"", {"L"}}});
}
BOOST_AUTO_TEST_CASE(linking_yul_same_library_name_different_files)
{
char const* input = R"(
{
"language": "Yul",
"settings": {
"libraries": {
"fileB": {
"L": "0x4200000000000000000000000000000000000001"
}
},
"outputSelection": {
"fileA": {
"*": [
"evm.bytecode.linkReferences"
]
}
}
},
"sources": {
"fileA": {
"content": "object \"a\" { code { let addr := linkersymbol(\"fileC:L\") sstore(0, addr) } }"
}
}
}
)";
Json result = compile(input);
BOOST_TEST(containsAtMostWarnings(result));
Json contractResult = getContractResult(result, "fileA", "a");
expectLinkReferences(contractResult, {{"fileC", {"L"}}});
}
BOOST_AUTO_TEST_CASE(evm_version)
{
auto inputForVersion = [](std::string const& _version)
{
return R"(
{
"language": "Solidity",
"sources": { "fileA": { "content": "contract A { }" } },
"settings": {
)" + _version + R"(
"outputSelection": {
"fileA": {
"A": [ "metadata" ]
}
}
}
}
)";
};
Json result;
result = compile(inputForVersion("\"evmVersion\": \"homestead\","));
BOOST_CHECK(result["contracts"]["fileA"]["A"]["metadata"].get<std::string>().find("\"evmVersion\":\"homestead\"") != std::string::npos);
result = compile(inputForVersion("\"evmVersion\": \"tangerineWhistle\","));
BOOST_CHECK(result["contracts"]["fileA"]["A"]["metadata"].get<std::string>().find("\"evmVersion\":\"tangerineWhistle\"") != std::string::npos);
result = compile(inputForVersion("\"evmVersion\": \"spuriousDragon\","));
BOOST_CHECK(result["contracts"]["fileA"]["A"]["metadata"].get<std::string>().find("\"evmVersion\":\"spuriousDragon\"") != std::string::npos);
result = compile(inputForVersion("\"evmVersion\": \"byzantium\","));
BOOST_CHECK(result["contracts"]["fileA"]["A"]["metadata"].get<std::string>().find("\"evmVersion\":\"byzantium\"") != std::string::npos);
result = compile(inputForVersion("\"evmVersion\": \"constantinople\","));
BOOST_CHECK(result["contracts"]["fileA"]["A"]["metadata"].get<std::string>().find("\"evmVersion\":\"constantinople\"") != std::string::npos);
result = compile(inputForVersion("\"evmVersion\": \"petersburg\","));
BOOST_CHECK(result["contracts"]["fileA"]["A"]["metadata"].get<std::string>().find("\"evmVersion\":\"petersburg\"") != std::string::npos);
result = compile(inputForVersion("\"evmVersion\": \"istanbul\","));
BOOST_CHECK(result["contracts"]["fileA"]["A"]["metadata"].get<std::string>().find("\"evmVersion\":\"istanbul\"") != std::string::npos);
result = compile(inputForVersion("\"evmVersion\": \"berlin\","));
BOOST_CHECK(result["contracts"]["fileA"]["A"]["metadata"].get<std::string>().find("\"evmVersion\":\"berlin\"") != std::string::npos);
result = compile(inputForVersion("\"evmVersion\": \"london\","));
BOOST_CHECK(result["contracts"]["fileA"]["A"]["metadata"].get<std::string>().find("\"evmVersion\":\"london\"") != std::string::npos);
result = compile(inputForVersion("\"evmVersion\": \"paris\","));
BOOST_CHECK(result["contracts"]["fileA"]["A"]["metadata"].get<std::string>().find("\"evmVersion\":\"paris\"") != std::string::npos);
result = compile(inputForVersion("\"evmVersion\": \"shanghai\","));
BOOST_CHECK(result["contracts"]["fileA"]["A"]["metadata"].get<std::string>().find("\"evmVersion\":\"shanghai\"") != std::string::npos);
result = compile(inputForVersion("\"evmVersion\": \"cancun\","));
BOOST_CHECK(result["contracts"]["fileA"]["A"]["metadata"].get<std::string>().find("\"evmVersion\":\"cancun\"") != std::string::npos);
// test default
result = compile(inputForVersion(""));
BOOST_CHECK(result["contracts"]["fileA"]["A"]["metadata"].get<std::string>().find("\"evmVersion\":\"cancun\"") != std::string::npos);
// test invalid
result = compile(inputForVersion("\"evmVersion\": \"invalid\","));
BOOST_CHECK(result["errors"][0]["message"].get<std::string>() == "Invalid EVM version requested.");
}
BOOST_AUTO_TEST_CASE(optimizer_settings_default_disabled)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"outputSelection": {
"fileA": { "A": [ "metadata" ] }
}
},
"sources": {
"fileA": {
"content": "contract A { }"
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsAtMostWarnings(result));
Json contract = getContractResult(result, "fileA", "A");
BOOST_CHECK(contract.is_object());
BOOST_CHECK(contract["metadata"].is_string());
Json metadata;
BOOST_CHECK(util::jsonParseStrict(contract["metadata"].get<std::string>(), metadata));
Json const& optimizer = metadata["settings"]["optimizer"];
BOOST_CHECK(optimizer.contains("enabled"));
BOOST_CHECK(optimizer["enabled"].get<bool>() == false);
BOOST_CHECK(!optimizer.contains("details"));
BOOST_CHECK(optimizer["runs"].get<unsigned>() == 200);
}
BOOST_AUTO_TEST_CASE(optimizer_settings_default_enabled)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"outputSelection": {
"fileA": { "A": [ "metadata" ] }
},
"optimizer": { "enabled": true }
},
"sources": {
"fileA": {
"content": "contract A { }"
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsAtMostWarnings(result));
Json contract = getContractResult(result, "fileA", "A");
BOOST_CHECK(contract.is_object());
BOOST_CHECK(contract["metadata"].is_string());
Json metadata;
BOOST_CHECK(util::jsonParseStrict(contract["metadata"].get<std::string>(), metadata));
Json const& optimizer = metadata["settings"]["optimizer"];
BOOST_CHECK(optimizer.contains("enabled"));
BOOST_CHECK(optimizer["enabled"].get<bool>() == true);
BOOST_CHECK(!optimizer.contains("details"));
BOOST_CHECK(optimizer["runs"].get<unsigned>() == 200);
}
BOOST_AUTO_TEST_CASE(optimizer_settings_details_exactly_as_default_disabled)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"outputSelection": {
"fileA": { "A": [ "metadata" ] }
},
"optimizer": { "details": {
"constantOptimizer" : false,
"cse" : false,
"deduplicate" : false,
"jumpdestRemover" : true,
"orderLiterals" : false,
"peephole" : true
} }
},
"sources": {
"fileA": {
"content": "contract A { }"
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsAtMostWarnings(result));
Json contract = getContractResult(result, "fileA", "A");
BOOST_CHECK(contract.is_object());
BOOST_CHECK(contract["metadata"].is_string());
Json metadata;
BOOST_CHECK(util::jsonParseStrict(contract["metadata"].get<std::string>(), metadata));
Json const& optimizer = metadata["settings"]["optimizer"];
BOOST_CHECK(optimizer.contains("enabled"));
// enabled is switched to false instead!
BOOST_CHECK(optimizer["enabled"].get<bool>() == false);
BOOST_CHECK(!optimizer.contains("details"));
BOOST_CHECK(optimizer["runs"].get<unsigned>() == 200);
}
BOOST_AUTO_TEST_CASE(optimizer_settings_details_different)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"outputSelection": {
"fileA": { "A": [ "metadata" ] }
},
"optimizer": { "runs": 600, "details": {
"constantOptimizer" : true,
"cse" : false,
"deduplicate" : true,
"jumpdestRemover" : true,
"orderLiterals" : false,
"peephole" : true,
"yul": true,
"inliner": true
} }
},
"sources": {
"fileA": {
"content": "contract A { }"
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsAtMostWarnings(result));
Json contract = getContractResult(result, "fileA", "A");
BOOST_CHECK(contract.is_object());
BOOST_CHECK(contract["metadata"].is_string());
Json metadata;
BOOST_CHECK(util::jsonParseStrict(contract["metadata"].get<std::string>(), metadata));
Json const& optimizer = metadata["settings"]["optimizer"];
BOOST_CHECK(!optimizer.contains("enabled"));
BOOST_CHECK(optimizer.contains("details"));
BOOST_CHECK(optimizer["details"]["constantOptimizer"].get<bool>() == true);
BOOST_CHECK(optimizer["details"]["cse"].get<bool>() == false);
BOOST_CHECK(optimizer["details"]["deduplicate"].get<bool>() == true);
BOOST_CHECK(optimizer["details"]["jumpdestRemover"].get<bool>() == true);
BOOST_CHECK(optimizer["details"]["orderLiterals"].get<bool>() == false);
BOOST_CHECK(optimizer["details"]["peephole"].get<bool>() == true);
BOOST_CHECK(optimizer["details"]["yul"].get<bool>() == true);
BOOST_CHECK(optimizer["details"]["yulDetails"].is_object());
// BOOST_CHECK(
// util::convertContainer<std::set<std::string>>(optimizer["details"]["yulDetails"].getMemberNames()) ==
// (std::set<std::string>{"stackAllocation", "optimizerSteps"})
// );
BOOST_CHECK(optimizer["details"]["yulDetails"]["stackAllocation"].get<bool>() == true);
BOOST_CHECK(
optimizer["details"]["yulDetails"]["optimizerSteps"].get<std::string>() ==
OptimiserSettings::DefaultYulOptimiserSteps + ":"s + OptimiserSettings::DefaultYulOptimiserCleanupSteps
);
BOOST_CHECK_EQUAL(optimizer["details"].size(), 10);
BOOST_CHECK(optimizer["runs"].get<unsigned>() == 600);
}
BOOST_AUTO_TEST_CASE(metadata_without_compilation)
{
// NOTE: the contract code here should fail to compile due to "out of stack"
// If the metadata is successfully returned, that means no compilation was attempted.
char const* input = R"(
{
"language": "Solidity",
"settings": {
"outputSelection": {
"fileA": { "A": [ "metadata" ] }
}
},
"sources": {
"fileA": {
"content": "contract A {
function x(uint a, uint b, uint c, uint d, uint e, uint f, uint g, uint h, uint i, uint j, uint k, uint l, uint m, uint n, uint o, uint p) pure public {}
function y() pure public {
uint a; uint b; uint c; uint d; uint e; uint f; uint g; uint h; uint i; uint j; uint k; uint l; uint m; uint n; uint o; uint p;
x(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p);
}
}"
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsAtMostWarnings(result));
Json contract = getContractResult(result, "fileA", "A");
BOOST_CHECK(contract.is_object());
BOOST_CHECK(contract["metadata"].is_string());
BOOST_CHECK(solidity::test::isValidMetadata(contract["metadata"].get<std::string>()));
}
BOOST_AUTO_TEST_CASE(license_in_metadata)
{
std::string const input = R"(
{
"language": "Solidity",
"sources": {
"fileA": { "content": "import \"fileB\"; contract A { } // SPDX-License-Identifier: GPL-3.0 \n" },
"fileB": { "content": "import \"fileC\"; /* SPDX-License-Identifier: MIT */ contract B { }" },
"fileC": { "content": "import \"fileD\"; /* SPDX-License-Identifier: MIT AND GPL-3.0 */ contract C { }" },
"fileD": { "content": "// SPDX-License-Identifier: (GPL-3.0+ OR MIT) AND MIT \n import \"fileE\"; contract D { }" },
"fileE": { "content": "import \"fileF\"; /// SPDX-License-Identifier: MIT \n contract E { }" },
"fileF": { "content": "/*\n * SPDX-License-Identifier: MIT\n */ contract F { }" }
},
"settings": {
"outputSelection": {
"fileA": {
"*": [ "metadata" ]
}
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsAtMostWarnings(result));
Json contract = getContractResult(result, "fileA", "A");
BOOST_CHECK(contract.is_object());
BOOST_CHECK(contract["metadata"].is_string());
Json metadata;
BOOST_REQUIRE(util::jsonParseStrict(contract["metadata"].get<std::string>(), metadata));
BOOST_CHECK_EQUAL(metadata["sources"]["fileA"]["license"], "GPL-3.0");
BOOST_CHECK_EQUAL(metadata["sources"]["fileB"]["license"], "MIT");
BOOST_CHECK_EQUAL(metadata["sources"]["fileC"]["license"], "MIT AND GPL-3.0");
BOOST_CHECK_EQUAL(metadata["sources"]["fileD"]["license"], "(GPL-3.0+ OR MIT) AND MIT");
// This is actually part of the docstring, but still picked up
// because the source location of the contract does not cover the docstring.
BOOST_CHECK_EQUAL(metadata["sources"]["fileE"]["license"], "MIT");
BOOST_CHECK_EQUAL(metadata["sources"]["fileF"]["license"], "MIT");
}
BOOST_AUTO_TEST_CASE(common_pattern)
{
char const* input = R"(
{
"language": "Solidity",
"settings": {
"outputSelection": {
"*": {
"*": [ "evm.bytecode.object", "metadata" ]
}
}
},
"sources": {
"fileA": {
"content": "contract A { function f() pure public {} }"
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsAtMostWarnings(result));
Json contract = getContractResult(result, "fileA", "A");
BOOST_CHECK(contract.is_object());
BOOST_CHECK(contract["metadata"].is_string());
BOOST_CHECK(solidity::test::isValidMetadata(contract["metadata"].get<std::string>()));
BOOST_CHECK(contract["evm"]["bytecode"].is_object());
BOOST_CHECK(contract["evm"]["bytecode"]["object"].is_string());
}
BOOST_AUTO_TEST_CASE(use_stack_optimization)
{
// NOTE: the contract code here should fail to compile due to "out of stack"
// If we enable stack optimization, though, it will compile.
char const* input = R"(
{
"language": "Solidity",
"settings": {
"optimizer": { "enabled": true, "details": { "yul": true } },
"outputSelection": {
"fileA": { "A": [ "evm.bytecode.object" ] }
}
},
"sources": {
"fileA": {
"content": "contract A {
function y() public {
assembly {
function fun() -> a3, b3, c3, d3, e3, f3, g3, h3, i3, j3, k3, l3, m3, n3, o3, p3
{
let a := 1
let b := 1
let z3 := 1
sstore(a, b)
sstore(add(a, 1), b)
sstore(add(a, 2), b)
sstore(add(a, 3), b)
sstore(add(a, 4), b)
sstore(add(a, 5), b)
sstore(add(a, 6), b)
sstore(add(a, 7), b)
sstore(add(a, 8), b)
sstore(add(a, 9), b)
sstore(add(a, 10), b)
sstore(add(a, 11), b)
sstore(add(a, 12), b)
}
let a1, b1, c1, d1, e1, f1, g1, h1, i1, j1, k1, l1, m1, n1, o1, p1 := fun()
let a2, b2, c2, d2, e2, f2, g2, h2, i2, j2, k2, l2, m2, n2, o2, p2 := fun()
sstore(a1, a2)
}
}
}"
}
}
}
)";
Json parsedInput;
BOOST_REQUIRE(util::jsonParseStrict(input, parsedInput));
solidity::frontend::StandardCompiler compiler;
Json result = compiler.compile(parsedInput);
BOOST_CHECK(containsAtMostWarnings(result));
Json contract = getContractResult(result, "fileA", "A");
BOOST_REQUIRE(contract.is_object());
BOOST_REQUIRE(contract["evm"]["bytecode"]["object"].is_string());
BOOST_CHECK(contract["evm"]["bytecode"]["object"].get<std::string>().length() > 20);
// Now disable stack optimizations and UnusedFunctionParameterPruner (p)
// results in "stack too deep"
std::string optimiserSteps = OptimiserSettings::DefaultYulOptimiserSteps;
optimiserSteps.erase(
remove_if(optimiserSteps.begin(), optimiserSteps.end(), [](char ch) { return ch == 'p'; }),
optimiserSteps.end()
);
parsedInput["settings"]["optimizer"]["details"]["yulDetails"]["stackAllocation"] = false;
parsedInput["settings"]["optimizer"]["details"]["yulDetails"]["optimizerSteps"] = optimiserSteps;
result = compiler.compile(parsedInput);
BOOST_REQUIRE(result["errors"].is_array());
BOOST_CHECK(result["errors"][0]["severity"] == "error");
BOOST_REQUIRE(result["errors"][0]["message"].is_string());
BOOST_CHECK(result["errors"][0]["message"].get<std::string>().find("When compiling inline assembly") != std::string::npos);
BOOST_CHECK(result["errors"][0]["type"] == "CompilerError");
}
BOOST_AUTO_TEST_CASE(standard_output_selection_wildcard)
{
char const* input = R"(
{
"language": "Solidity",
"sources":
{
"A":
{
"content": "pragma solidity >=0.0; contract C { function f() public pure {} }"
}
},
"settings":
{
"outputSelection":
{
"*": { "C": ["evm.bytecode"] }
}
}
}
)";
Json parsedInput;
BOOST_REQUIRE(util::jsonParseStrict(input, parsedInput));
solidity::frontend::StandardCompiler compiler;
Json result = compiler.compile(parsedInput);
BOOST_REQUIRE(result["contracts"].is_object());
BOOST_REQUIRE(result["contracts"].size() == 1);
BOOST_REQUIRE(result["contracts"]["A"].is_object());
BOOST_REQUIRE(result["contracts"]["A"].size() == 1);
BOOST_REQUIRE(result["contracts"]["A"]["C"].is_object());
BOOST_REQUIRE(result["contracts"]["A"]["C"]["evm"].is_object());
BOOST_REQUIRE(result["contracts"]["A"]["C"]["evm"]["bytecode"].is_object());
BOOST_REQUIRE(result["sources"].is_object());
BOOST_REQUIRE(result["sources"].size() == 1);
BOOST_REQUIRE(result["sources"]["A"].is_object());
}
BOOST_AUTO_TEST_CASE(standard_output_selection_wildcard_colon_source)
{
char const* input = R"(
{
"language": "Solidity",
"sources":
{
":A":
{
"content": "pragma solidity >=0.0; contract C { function f() public pure {} }"
}
},
"settings":
{
"outputSelection":
{
"*": { "C": ["evm.bytecode"] }
}
}
}
)";
Json parsedInput;
BOOST_REQUIRE(util::jsonParseStrict(input, parsedInput));
solidity::frontend::StandardCompiler compiler;
Json result = compiler.compile(parsedInput);
BOOST_REQUIRE(result["contracts"].is_object());
BOOST_REQUIRE(result["contracts"].size() == 1);
BOOST_REQUIRE(result["contracts"][":A"].is_object());
BOOST_REQUIRE(result["contracts"][":A"].size() == 1);
BOOST_REQUIRE(result["contracts"][":A"]["C"].is_object());
BOOST_REQUIRE(result["contracts"][":A"]["C"]["evm"].is_object());
BOOST_REQUIRE(result["contracts"][":A"]["C"]["evm"]["bytecode"].is_object());
BOOST_REQUIRE(result["sources"].is_object());
BOOST_REQUIRE(result["sources"].size() == 1);
BOOST_REQUIRE(result["sources"][":A"].is_object());
}
BOOST_AUTO_TEST_CASE(standard_output_selection_wildcard_empty_source)
{
char const* input = R"(
{
"language": "Solidity",
"sources":
{
"":
{
"content": "pragma solidity >=0.0; contract C { function f() public pure {} }"
}
},
"settings":
{
"outputSelection":
{
"*": { "C": ["evm.bytecode"] }
}
}
}
)";
Json parsedInput;
BOOST_REQUIRE(util::jsonParseStrict(input, parsedInput));
solidity::frontend::StandardCompiler compiler;
Json result = compiler.compile(parsedInput);
BOOST_REQUIRE(result["contracts"].is_object());
BOOST_REQUIRE(result["contracts"].size() == 1);
BOOST_REQUIRE(result["contracts"][""].is_object());
BOOST_REQUIRE(result["contracts"][""].size() == 1);
BOOST_REQUIRE(result["contracts"][""]["C"].is_object());
BOOST_REQUIRE(result["contracts"][""]["C"]["evm"].is_object());
BOOST_REQUIRE(result["contracts"][""]["C"]["evm"]["bytecode"].is_object());
BOOST_REQUIRE(result["sources"].is_object());
BOOST_REQUIRE(result["sources"].size() == 1);
BOOST_REQUIRE(result["sources"][""].is_object());
}
BOOST_AUTO_TEST_CASE(standard_output_selection_wildcard_multiple_sources)
{
char const* input = R"(
{
"language": "Solidity",
"sources":
{
"A":
{
"content": "pragma solidity >=0.0; contract C { function f() public pure {} }"
},
"B":
{
"content": "pragma solidity >=0.0; contract D { function f() public pure {} }"
}
},
"settings":
{
"outputSelection":
{
"*": { "D": ["evm.bytecode"] }
}
}
}
)";
Json parsedInput;
BOOST_REQUIRE(util::jsonParseStrict(input, parsedInput));
solidity::frontend::StandardCompiler compiler;
Json result = compiler.compile(parsedInput);
BOOST_REQUIRE(result["contracts"].is_object());
BOOST_REQUIRE(result["contracts"].size() == 1);
BOOST_REQUIRE(result["contracts"]["B"].is_object());
BOOST_REQUIRE(result["contracts"]["B"].size() == 1);
BOOST_REQUIRE(result["contracts"]["B"]["D"].is_object());
BOOST_REQUIRE(result["contracts"]["B"]["D"]["evm"].is_object());
BOOST_REQUIRE(result["contracts"]["B"]["D"]["evm"]["bytecode"].is_object());
BOOST_REQUIRE(result["sources"].is_object());
BOOST_REQUIRE(result["sources"].size() == 2);
BOOST_REQUIRE(result["sources"]["A"].is_object());
BOOST_REQUIRE(result["sources"]["B"].is_object());
}
BOOST_AUTO_TEST_CASE(stopAfter_invalid_value)
{
char const* input = R"(
{
"language": "Solidity",
"sources":
{ "": { "content": "pragma solidity >=0.0; contract C { function f() public pure {} }" } },
"settings":
{
"stopAfter": "rrr",
"outputSelection":
{
"*": { "C": ["evm.bytecode"] }
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsError(result, "JSONError", "Invalid value for \"settings.stopAfter\". Only valid value is \"parsing\"."));
}
BOOST_AUTO_TEST_CASE(stopAfter_invalid_type)
{
char const* input = R"(
{
"language": "Solidity",
"sources":
{ "": { "content": "pragma solidity >=0.0; contract C { function f() public pure {} }" } },
"settings":
{
"stopAfter": 3,
"outputSelection":
{
"*": { "C": ["evm.bytecode"] }
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsError(result, "JSONError", "\"settings.stopAfter\" must be a string."));
}
BOOST_AUTO_TEST_CASE(stopAfter_bin_conflict)
{
char const* input = R"(
{
"language": "Solidity",
"sources":
{ "": { "content": "pragma solidity >=0.0; contract C { function f() public pure {} }" } },
"settings":
{
"stopAfter": "parsing",
"outputSelection":
{
"*": { "C": ["evm.bytecode"] }
}
}
}
)";
Json result = compile(input);
BOOST_CHECK(containsError(result, "JSONError", "Requested output selection conflicts with \"settings.stopAfter\"."));
}
BOOST_AUTO_TEST_CASE(stopAfter_ast_output)
{
char const* input = R"(
{
"language": "Solidity",
"sources": {
"a.sol": {
"content": "// SPDX-License-Identifier: GPL-3.0\nimport \"tes32.sol\";\n contract C is X { constructor() {} }"
}
},
"settings": {
"stopAfter": "parsing",
"outputSelection": { "*": { "": [ "ast" ] } }
}
}
)";
Json result = compile(input);
BOOST_CHECK(result["sources"].is_object());
BOOST_CHECK(result["sources"]["a.sol"].is_object());
BOOST_CHECK(result["sources"]["a.sol"]["ast"].is_object());
}
BOOST_AUTO_TEST_CASE(dependency_tracking_of_abstract_contract)
{
char const* input = R"(
{
"language": "Solidity",
"sources": {
"BlockRewardAuRaBase.sol": {
"content": " contract Sacrifice { constructor() payable {} } abstract contract BlockRewardAuRaBase { function _transferNativeReward() internal { new Sacrifice(); } function _distributeTokenRewards() internal virtual; } "
},
"BlockRewardAuRaCoins.sol": {
"content": " import \"./BlockRewardAuRaBase.sol\"; contract BlockRewardAuRaCoins is BlockRewardAuRaBase { function transferReward() public { _transferNativeReward(); } function _distributeTokenRewards() internal override {} } "
}
},
"settings": {
"outputSelection": {
"BlockRewardAuRaCoins.sol": {
"BlockRewardAuRaCoins": ["ir", "evm.bytecode.sourceMap"]
}
}
}
}
)";
Json parsedInput;
BOOST_REQUIRE(util::jsonParseStrict(input, parsedInput));
solidity::frontend::StandardCompiler compiler;
Json result = compiler.compile(parsedInput);
BOOST_REQUIRE(result["contracts"].is_object());
BOOST_REQUIRE(result["contracts"].size() == 1);
BOOST_REQUIRE(result["contracts"]["BlockRewardAuRaCoins.sol"].is_object());
BOOST_REQUIRE(result["contracts"]["BlockRewardAuRaCoins.sol"].size() == 1);
BOOST_REQUIRE(result["contracts"]["BlockRewardAuRaCoins.sol"]["BlockRewardAuRaCoins"].is_object());
BOOST_REQUIRE(result["contracts"]["BlockRewardAuRaCoins.sol"]["BlockRewardAuRaCoins"]["evm"].is_object());
BOOST_REQUIRE(result["contracts"]["BlockRewardAuRaCoins.sol"]["BlockRewardAuRaCoins"]["ir"].is_string());
BOOST_REQUIRE(result["contracts"]["BlockRewardAuRaCoins.sol"]["BlockRewardAuRaCoins"]["evm"]["bytecode"].is_object());
BOOST_REQUIRE(result["sources"].is_object());
BOOST_REQUIRE(result["sources"].size() == 2);
}
BOOST_AUTO_TEST_CASE(dependency_tracking_of_abstract_contract_yul)
{
char const* input = R"(
{
"language": "Solidity",
"sources": {
"A.sol": {
"content": "contract A {} contract B {} contract C { constructor() { new B(); } } contract D {}"
}
},
"settings": {
"outputSelection": {
"A.sol": {
"C": ["ir"]
}
}
}
}
)";
Json parsedInput;
BOOST_REQUIRE(util::jsonParseStrict(input, parsedInput));
solidity::frontend::StandardCompiler compiler;
Json result = compiler.compile(parsedInput);
BOOST_REQUIRE(result["contracts"].is_object());
BOOST_REQUIRE(result["contracts"].size() == 1);
BOOST_REQUIRE(result["contracts"]["A.sol"].is_object());
BOOST_REQUIRE(result["contracts"]["A.sol"].size() == 1);
BOOST_REQUIRE(result["contracts"]["A.sol"]["C"].is_object());
BOOST_REQUIRE(result["contracts"]["A.sol"]["C"]["ir"].is_string());
const std::string& irCode = result["contracts"]["A.sol"]["C"]["ir"].get<std::string>();
// Make sure C and B contracts are deployed
BOOST_REQUIRE(irCode.find("object \"C") != std::string::npos);
BOOST_REQUIRE(irCode.find("object \"B") != std::string::npos);
// Make sure A and D are NOT deployed as they were not requested and are not
// in any dependency
BOOST_REQUIRE(irCode.find("object \"A") == std::string::npos);
BOOST_REQUIRE(irCode.find("object \"D") == std::string::npos);
BOOST_REQUIRE(result["sources"].is_object());
BOOST_REQUIRE(result["sources"].size() == 1);
}
BOOST_AUTO_TEST_CASE(source_location_of_bare_block)
{
char const* input = R"(
{
"language": "Solidity",
"sources": {
"A.sol": {
"content": "contract A { constructor() { uint x = 2; { uint y = 3; } } }"
}
},
"settings": {
"outputSelection": {
"A.sol": {
"A": ["evm.bytecode.sourceMap"]
}
}
}
}
)";
Json parsedInput;
BOOST_REQUIRE(util::jsonParseStrict(input, parsedInput));
solidity::frontend::StandardCompiler compiler;
Json result = compiler.compile(parsedInput);
std::string sourceMap = result["contracts"]["A.sol"]["A"]["evm"]["bytecode"]["sourceMap"].get<std::string>();
// Check that the bare block's source location is referenced.
std::string sourceRef =
";" +
std::to_string(std::string{"contract A { constructor() { uint x = 2; "}.size()) +
":" +
std::to_string(std::string{"{ uint y = 3; }"}.size());
BOOST_REQUIRE(sourceMap.find(sourceRef) != std::string::npos);
}
BOOST_AUTO_TEST_SUITE_END()
} // end namespaces
| 52,456
|
C++
|
.cpp
| 1,668
| 28.482614
| 231
| 0.648483
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,984
|
AnalysisFramework.cpp
|
ethereum_solidity/test/libsolidity/AnalysisFramework.cpp
|
/*
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
/**
* Framework for testing features from the analysis phase of compiler.
*/
#include <test/libsolidity/AnalysisFramework.h>
#include <test/libsolidity/util/Common.h>
#include <test/libsolidity/util/SoltestErrors.h>
#include <test/Common.h>
#include <libsolidity/interface/CompilerStack.h>
#include <liblangutil/SourceReferenceFormatter.h>
#include <libsolidity/ast/AST.h>
#include <liblangutil/Scanner.h>
#include <libsolutil/FunctionSelector.h>
#include <boost/test/unit_test.hpp>
using namespace solidity;
using namespace solidity::util;
using namespace solidity::langutil;
using namespace solidity::frontend;
using namespace solidity::frontend::test;
std::pair<SourceUnit const*, ErrorList> AnalysisFramework::runAnalysisAndExpectNoParsingErrors(
std::string const& _source,
bool _includeWarningsAndInfos,
bool _addPreamble,
bool _allowMultiple
)
{
runFramework(_addPreamble ? withPreamble(_source) : _source, PipelineStage::Analysis);
if (!stageSuccessful(PipelineStage::Parsing))
BOOST_FAIL("Parsing contract failed in analysis test suite:" + formatErrors(m_compiler->errors()));
ErrorList errors = filteredErrors(_includeWarningsAndInfos);
if (errors.size() > 1 && !_allowMultiple)
BOOST_FAIL("Multiple errors found: " + formatErrors(errors));
return make_pair(&compiler().ast(""), std::move(errors));
}
bool AnalysisFramework::runFramework(StringMap _sources, PipelineStage _targetStage)
{
resetFramework();
m_targetStage = _targetStage;
soltestAssert(m_compiler);
m_compiler->setSources(std::move(_sources));
setupCompiler(*m_compiler);
executeCompilationPipeline();
return pipelineSuccessful();
}
void AnalysisFramework::resetFramework()
{
compiler().reset();
m_targetStage = PipelineStage::Compilation;
}
std::unique_ptr<CompilerStack> AnalysisFramework::createStack() const
{
return std::make_unique<CompilerStack>();
}
void AnalysisFramework::setupCompiler(CompilerStack& _compiler)
{
// These are just defaults based on the (global) CLI options.
// Technically, every TestCase should override these with values passed to it in TestCase::Config.
// In practice TestCase::Config always matches global config so most test cases don't care.
_compiler.setEVMVersion(solidity::test::CommonOptions::get().evmVersion());
_compiler.setEOFVersion(solidity::test::CommonOptions::get().eofVersion());
_compiler.setOptimiserSettings(solidity::test::CommonOptions::get().optimize);
}
void AnalysisFramework::executeCompilationPipeline()
{
soltestAssert(m_compiler);
// If you add a new stage, remember to handle it below.
soltestAssert(
m_targetStage == PipelineStage::Parsing ||
m_targetStage == PipelineStage::Analysis ||
m_targetStage == PipelineStage::Compilation
);
bool parsingSuccessful = m_compiler->parse();
soltestAssert(parsingSuccessful || !filteredErrors(false /* _includeWarningsAndInfos */).empty());
if (!parsingSuccessful || stageSuccessful(m_targetStage))
return;
bool analysisSuccessful = m_compiler->analyze();
soltestAssert(analysisSuccessful || !filteredErrors(false /* _includeWarningsAndInfos */).empty());
if (!analysisSuccessful || stageSuccessful(m_targetStage))
return;
bool compilationSuccessful = m_compiler->compile();
soltestAssert(compilationSuccessful || !filteredErrors(false /* _includeWarningsAndInfos */).empty());
soltestAssert(stageSuccessful(m_targetStage) == compilationSuccessful);
}
ErrorList AnalysisFramework::filterErrors(ErrorList const& _errorList, bool _includeWarningsAndInfos) const
{
ErrorList errors;
for (auto const& currentError: _errorList)
{
solAssert(currentError->comment(), "");
if (!Error::isError(currentError->type()))
{
if (!_includeWarningsAndInfos)
continue;
bool ignoreWarningsAndInfos = false;
for (auto const& filter: m_warningsToFilter)
if (currentError->comment()->find(filter) == 0)
{
ignoreWarningsAndInfos = true;
break;
}
if (ignoreWarningsAndInfos)
continue;
}
std::shared_ptr<Error const> newError = currentError;
for (auto const& messagePrefix: m_messagesToCut)
if (currentError->comment()->find(messagePrefix) == 0)
{
SourceLocation const* location = currentError->sourceLocation();
// sufficient for now, but in future we might clone the error completely, including the secondary location
newError = std::make_shared<Error>(
currentError->errorId(),
currentError->type(),
messagePrefix + " ....",
location ? *location : SourceLocation()
);
break;
}
errors.emplace_back(newError);
}
return errors;
}
bool AnalysisFramework::stageSuccessful(PipelineStage _stage) const
{
switch (_stage) {
case PipelineStage::Parsing: return compiler().state() >= CompilerStack::Parsed;
case PipelineStage::Analysis: return compiler().state() >= CompilerStack::AnalysisSuccessful;
case PipelineStage::Compilation: return compiler().state() >= CompilerStack::CompilationSuccessful;
}
unreachable();
}
ErrorList AnalysisFramework::runAnalysisAndExpectError(
std::string const& _source,
bool _includeWarningsAndInfos,
bool _allowMultiple
)
{
auto [ast, errors] = runAnalysisAndExpectNoParsingErrors(_source, _includeWarningsAndInfos, true, _allowMultiple);
BOOST_REQUIRE(!errors.empty());
BOOST_REQUIRE_MESSAGE(ast, "Expected error, but no error happened.");
return errors;
}
std::string AnalysisFramework::formatErrors(
langutil::ErrorList const& _errors,
bool _colored,
bool _withErrorIds
) const
{
return SourceReferenceFormatter::formatErrorInformation(
_errors,
*m_compiler,
_colored,
_withErrorIds
);
}
std::string AnalysisFramework::formatError(
Error const& _error,
bool _colored,
bool _withErrorIds
) const
{
return SourceReferenceFormatter::formatErrorInformation(
_error,
*m_compiler,
_colored,
_withErrorIds
);
}
ContractDefinition const* AnalysisFramework::retrieveContractByName(SourceUnit const& _source, std::string const& _name)
{
ContractDefinition* contract = nullptr;
for (std::shared_ptr<ASTNode> const& node: _source.nodes())
if ((contract = dynamic_cast<ContractDefinition*>(node.get())) && contract->name() == _name)
return contract;
return nullptr;
}
FunctionTypePointer AnalysisFramework::retrieveFunctionBySignature(
ContractDefinition const& _contract,
std::string const& _signature
)
{
return _contract.interfaceFunctions()[util::selectorFromSignatureH32(_signature)];
}
| 7,095
|
C++
|
.cpp
| 195
| 34.025641
| 120
| 0.778085
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,985
|
SyntaxTest.cpp
|
ethereum_solidity/test/libsolidity/SyntaxTest.cpp
|
/*
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
#include <test/libsolidity/SyntaxTest.h>
#include <test/libsolidity/util/Common.h>
#include <test/Common.h>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/throw_exception.hpp>
#include <range/v3/algorithm/find_if.hpp>
#include <fstream>
#include <memory>
#include <stdexcept>
using namespace solidity;
using namespace solidity::util;
using namespace solidity::util::formatting;
using namespace solidity::langutil;
using namespace solidity::frontend;
using namespace solidity::frontend::test;
using namespace boost::unit_test;
namespace fs = boost::filesystem;
SyntaxTest::SyntaxTest(
std::string const& _filename,
langutil::EVMVersion _evmVersion,
Error::Severity _minSeverity
):
CommonSyntaxTest(_filename, _evmVersion),
m_minSeverity(_minSeverity)
{
static std::set<std::string> const compileViaYulAllowedValues{"true", "false"};
m_compileViaYul = m_reader.stringSetting("compileViaYul", "false");
if (!util::contains(compileViaYulAllowedValues, m_compileViaYul))
BOOST_THROW_EXCEPTION(std::runtime_error("Invalid compileViaYul value: " + m_compileViaYul + "."));
m_optimiseYul = m_reader.boolSetting("optimize-yul", true);
static std::map<std::string, PipelineStage> const pipelineStages = {
{"parsing", PipelineStage::Parsing},
{"analysis", PipelineStage::Analysis},
{"compilation", PipelineStage::Compilation}
};
std::string stopAfter = m_reader.stringSetting("stopAfter", "compilation");
if (!pipelineStages.count(stopAfter))
BOOST_THROW_EXCEPTION(std::runtime_error("Invalid stopAfter value: " + stopAfter + "."));
m_stopAfter = pipelineStages.at(stopAfter);
}
void SyntaxTest::setupCompiler(CompilerStack& _compiler)
{
AnalysisFramework::setupCompiler(_compiler);
_compiler.setEVMVersion(m_evmVersion);
_compiler.setOptimiserSettings(
m_optimiseYul ?
OptimiserSettings::full() :
OptimiserSettings::minimal()
);
_compiler.setViaIR(m_compileViaYul == "true");
_compiler.setMetadataFormat(CompilerStack::MetadataFormat::NoMetadata);
_compiler.setMetadataHash(CompilerStack::MetadataHash::None);
}
void SyntaxTest::parseAndAnalyze()
{
runFramework(withPreamble(m_sources.sources), m_stopAfter);
if (!pipelineSuccessful() && stageSuccessful(PipelineStage::Analysis) && !compiler().isExperimentalAnalysis())
{
ErrorList const& errors = compiler().errors();
static auto isInternalError = [](std::shared_ptr<Error const> const& _error) {
return
Error::isError(_error->type()) &&
_error->type() != Error::Type::CodeGenerationError &&
_error->type() != Error::Type::UnimplementedFeatureError
;
};
// Most errors are detected during analysis, and should not happen during code generation.
// There are some exceptions, e.g. unimplemented features or stack too deep, but anything else at this stage
// is an internal error that signals a bug in the compiler (rather than in user's code).
if (
auto error = ranges::find_if(errors, isInternalError);
error != ranges::end(errors)
)
BOOST_THROW_EXCEPTION(std::runtime_error(
"Unexpected " + Error::formatErrorType((*error)->type()) + " at compilation stage."
" This error should NOT be encoded as expectation and should be fixed instead."
));
}
filterObtainedErrors();
}
void SyntaxTest::filterObtainedErrors()
{
for (auto const& currentError: filteredErrors())
{
if (currentError->severity() < m_minSeverity)
continue;
int locationStart = -1;
int locationEnd = -1;
std::string sourceName;
if (SourceLocation const* location = currentError->sourceLocation())
{
locationStart = location->start;
locationEnd = location->end;
solAssert(location->sourceName, "");
sourceName = *location->sourceName;
if(m_sources.sources.count(sourceName) == 1)
{
int preambleSize =
static_cast<int>(compiler().charStream(sourceName).size()) -
static_cast<int>(m_sources.sources[sourceName].size());
solAssert(preambleSize >= 0, "");
// ignore the version & license pragma inserted by the testing tool when calculating locations.
if (location->start != -1)
{
solAssert(location->start >= preambleSize, "");
locationStart = location->start - preambleSize;
}
if (location->end != -1)
{
solAssert(location->end >= preambleSize, "");
locationEnd = location->end - preambleSize;
}
}
}
m_errorList.emplace_back(SyntaxTestError{
currentError->type(),
currentError->errorId(),
errorMessage(*currentError),
sourceName,
locationStart,
locationEnd
});
}
}
| 5,282
|
C++
|
.cpp
| 140
| 34.914286
| 111
| 0.748732
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,986
|
ABIDecoderTests.cpp
|
ethereum_solidity/test/libsolidity/ABIDecoderTests.cpp
|
/*
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
/**
* Unit tests for Solidity's ABI decoder.
*/
#include <functional>
#include <string>
#include <tuple>
#include <boost/test/unit_test.hpp>
#include <liblangutil/Exceptions.h>
#include <test/libsolidity/SolidityExecutionFramework.h>
#include <test/libsolidity/ABITestsCommon.h>
using namespace std::placeholders;
using namespace solidity::test;
namespace solidity::frontend::test
{
BOOST_FIXTURE_TEST_SUITE(ABIDecoderTest, SolidityExecutionFramework)
BOOST_AUTO_TEST_CASE(value_types)
{
std::string sourceCode = R"(
contract C {
function f(uint a, uint16 b, uint24 c, int24 d, bytes3 x, bool e, C g) public returns (uint) {
if (a != 1) return 1;
if (b != 2) return 2;
if (c != 3) return 3;
if (d != 4) return 4;
if (x != "abc") return 5;
if (e != true) return 6;
if (g != this) return 7;
return 20;
}
}
)";
BOTH_ENCODERS(
compileAndRun(sourceCode);
ABI_CHECK(callContractFunction(
"f(uint256,uint16,uint24,int24,bytes3,bool,address)",
1, 2, 3, 4, std::string("abc"), true, m_contractAddress
), encodeArgs(u256(20)));
)
}
BOOST_AUTO_TEST_CASE(decode_from_memory_simple)
{
std::string sourceCode = R"(
contract C {
uint public _a;
uint[] public _b;
constructor(uint a, uint[] memory b) {
_a = a;
_b = b;
}
}
)";
BOTH_ENCODERS(
compileAndRun(sourceCode, 0, "C", encodeArgs(
7, 0x40,
// b
3, 0x21, 0x22, 0x23
));
ABI_CHECK(callContractFunction("_a()"), encodeArgs(7));
ABI_CHECK(callContractFunction("_b(uint256)", 0), encodeArgs(0x21));
ABI_CHECK(callContractFunction("_b(uint256)", 1), encodeArgs(0x22));
ABI_CHECK(callContractFunction("_b(uint256)", 2), encodeArgs(0x23));
ABI_CHECK(callContractFunction("_b(uint256)", 3), encodeArgs());
)
}
BOOST_AUTO_TEST_CASE(decode_function_type)
{
std::string sourceCode = R"(
contract D {
function () external returns (uint) public _a;
constructor(function () external returns (uint) a) {
_a = a;
}
}
contract C {
function f() public returns (uint) {
return 3;
}
function g(function () external returns (uint) _f) public returns (uint) {
return _f();
}
// uses "decode from memory"
function test1() public returns (uint) {
D d = new D(this.f);
return d._a()();
}
// uses "decode from calldata"
function test2() public returns (uint) {
return this.g(this.f);
}
}
)";
BOTH_ENCODERS(
compileAndRun(sourceCode, 0, "C");
ABI_CHECK(callContractFunction("test1()"), encodeArgs(3));
ABI_CHECK(callContractFunction("test2()"), encodeArgs(3));
)
}
BOOST_AUTO_TEST_CASE(decode_function_type_array)
{
std::string sourceCode = R"(
contract D {
function () external returns (uint)[] public _a;
constructor(function () external returns (uint)[] memory a) {
_a = a;
}
}
contract E {
function () external returns (uint)[3] public _a;
constructor(function () external returns (uint)[3] memory a) {
_a = a;
}
}
contract C {
function f1() public returns (uint) {
return 1;
}
function f2() public returns (uint) {
return 2;
}
function f3() public returns (uint) {
return 3;
}
function g(function () external returns (uint)[] memory _f, uint i) public returns (uint) {
return _f[i]();
}
function h(function () external returns (uint)[3] memory _f, uint i) public returns (uint) {
return _f[i]();
}
// uses "decode from memory"
function test1_dynamic() public returns (uint) {
function () external returns (uint)[] memory x = new function() external returns (uint)[](4);
x[0] = this.f1;
x[1] = this.f2;
x[2] = this.f3;
D d = new D(x);
return d._a(2)();
}
function test1_static() public returns (uint) {
E e = new E([this.f1, this.f2, this.f3]);
return e._a(2)();
}
// uses "decode from calldata"
function test2_dynamic() public returns (uint) {
function () external returns (uint)[] memory x = new function() external returns (uint)[](3);
x[0] = this.f1;
x[1] = this.f2;
x[2] = this.f3;
return this.g(x, 0);
}
function test2_static() public returns (uint) {
return this.h([this.f1, this.f2, this.f3], 0);
}
}
)";
BOTH_ENCODERS(
compileAndRun(sourceCode, 0, "C");
ABI_CHECK(callContractFunction("test1_static()"), encodeArgs(3));
ABI_CHECK(callContractFunction("test1_dynamic()"), encodeArgs(3));
ABI_CHECK(callContractFunction("test2_static()"), encodeArgs(1));
ABI_CHECK(callContractFunction("test2_dynamic()"), encodeArgs(1));
)
}
BOOST_AUTO_TEST_CASE(decode_from_memory_complex)
{
std::string sourceCode = R"(
contract C {
uint public _a;
uint[] public _b;
bytes[2] public _c;
constructor(uint a, uint[] memory b, bytes[2] memory c) {
_a = a;
_b = b;
_c = c;
}
}
)";
NEW_ENCODER(
compileAndRun(sourceCode, 0, "C", encodeArgs(
7, 0x60, 7 * 0x20,
// b
3, 0x21, 0x22, 0x23,
// c
0x40, 0x80,
8, std::string("abcdefgh"),
52, std::string("ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ")
));
ABI_CHECK(callContractFunction("_a()"), encodeArgs(7));
ABI_CHECK(callContractFunction("_b(uint256)", 0), encodeArgs(0x21));
ABI_CHECK(callContractFunction("_b(uint256)", 1), encodeArgs(0x22));
ABI_CHECK(callContractFunction("_b(uint256)", 2), encodeArgs(0x23));
ABI_CHECK(callContractFunction("_b(uint256)", 3), encodeArgs());
ABI_CHECK(callContractFunction("_c(uint256)", 0), encodeArgs(0x20, 8, std::string("abcdefgh")));
ABI_CHECK(callContractFunction("_c(uint256)", 1), encodeArgs(0x20, 52, std::string("ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ")));
ABI_CHECK(callContractFunction("_c(uint256)", 2), encodeArgs());
)
}
BOOST_AUTO_TEST_CASE(short_input_value_type)
{
std::string sourceCode = R"(
contract C {
function f(uint a, uint b) public pure returns (uint) { return a; }
}
)";
BOTH_ENCODERS(
compileAndRun(sourceCode);
ABI_CHECK(callContractFunction("f(uint256,uint256)", 1, 2), encodeArgs(1));
ABI_CHECK(callContractFunctionNoEncoding("f(uint256,uint256)", bytes(64, 0)), encodeArgs(0));
ABI_CHECK(callContractFunctionNoEncoding("f(uint256,uint256)", bytes(63, 0)), encodeArgs());
)
}
BOOST_AUTO_TEST_CASE(short_input_array)
{
std::string sourceCode = R"(
contract C {
function f(uint[] memory a) public pure returns (uint) { return 7; }
}
)";
BOTH_ENCODERS(
compileAndRun(sourceCode);
ABI_CHECK(callContractFunctionNoEncoding("f(uint256[])", encodeArgs(0x20, 0)), encodeArgs(7));
ABI_CHECK(callContractFunctionNoEncoding("f(uint256[])", encodeArgs(0x20, 1)), encodeArgs());
ABI_CHECK(callContractFunctionNoEncoding("f(uint256[])", encodeArgs(0x20, 1) + bytes(31, 0)), encodeArgs());
ABI_CHECK(callContractFunctionNoEncoding("f(uint256[])", encodeArgs(0x20, 1) + bytes(32, 0)), encodeArgs(7));
ABI_CHECK(callContractFunctionNoEncoding("f(uint256[])", encodeArgs(0x20, 2, 5, 6)), encodeArgs(7));
)
}
BOOST_AUTO_TEST_CASE(short_dynamic_input_array)
{
std::string sourceCode = R"(
contract C {
function f(bytes[1] memory a) public pure returns (uint) { return 7; }
}
)";
NEW_ENCODER(
compileAndRun(sourceCode);
ABI_CHECK(callContractFunctionNoEncoding("f(bytes[1])", encodeArgs(0x20)), encodeArgs());
)
}
BOOST_AUTO_TEST_CASE(short_input_bytes)
{
std::string sourceCode = R"(
contract C {
function e(bytes memory a) public pure returns (uint) { return 7; }
function f(bytes[] memory a) public pure returns (uint) { return 7; }
}
)";
NEW_ENCODER(
compileAndRun(sourceCode);
ABI_CHECK(callContractFunctionNoEncoding("e(bytes)", encodeArgs(0x20, 7) + bytes(5, 0)), encodeArgs());
ABI_CHECK(callContractFunctionNoEncoding("e(bytes)", encodeArgs(0x20, 7) + bytes(6, 0)), encodeArgs());
ABI_CHECK(callContractFunctionNoEncoding("e(bytes)", encodeArgs(0x20, 7) + bytes(7, 0)), encodeArgs(7));
ABI_CHECK(callContractFunctionNoEncoding("e(bytes)", encodeArgs(0x20, 7) + bytes(8, 0)), encodeArgs(7));
ABI_CHECK(callContractFunctionNoEncoding("f(bytes[])", encodeArgs(0x20, 1, 0x20, 7) + bytes(5, 0)), encodeArgs());
ABI_CHECK(callContractFunctionNoEncoding("f(bytes[])", encodeArgs(0x20, 1, 0x20, 7) + bytes(6, 0)), encodeArgs());
ABI_CHECK(callContractFunctionNoEncoding("f(bytes[])", encodeArgs(0x20, 1, 0x20, 7) + bytes(7, 0)), encodeArgs(7));
ABI_CHECK(callContractFunctionNoEncoding("f(bytes[])", encodeArgs(0x20, 1, 0x20, 7) + bytes(8, 0)), encodeArgs(7));
)
}
BOOST_AUTO_TEST_CASE(validation_int_inside_arrays)
{
std::string sourceCode = R"(
contract C {
enum E { A, B }
function f(uint16[] memory a) public pure returns (uint r) { assembly { r := mload(add(a, 0x20)) } }
function g(int16[] memory a) public pure returns (uint r) { assembly { r := mload(add(a, 0x20)) } }
function h(E[] memory a) public pure returns (uint r) { assembly { r := mload(add(a, 0x20)) } }
}
)";
NEW_ENCODER(
compileAndRun(sourceCode);
ABI_CHECK(callContractFunction("f(uint16[])", 0x20, 1, 7), encodeArgs(7));
ABI_CHECK(callContractFunction("g(int16[])", 0x20, 1, 7), encodeArgs(7));
ABI_CHECK(callContractFunction("f(uint16[])", 0x20, 1, u256("0xffff")), encodeArgs(u256("0xffff")));
ABI_CHECK(callContractFunction("g(int16[])", 0x20, 1, u256("0xffff")), encodeArgs());
ABI_CHECK(callContractFunction("f(uint16[])", 0x20, 1, u256("0x1ffff")), encodeArgs());
ABI_CHECK(callContractFunction("g(int16[])", 0x20, 1, u256("0x10fff")), encodeArgs());
ABI_CHECK(callContractFunction("h(uint8[])", 0x20, 1, 0), encodeArgs(u256(0)));
ABI_CHECK(callContractFunction("h(uint8[])", 0x20, 1, 1), encodeArgs(u256(1)));
ABI_CHECK(callContractFunction("h(uint8[])", 0x20, 1, 2), encodeArgs());
)
}
BOOST_AUTO_TEST_CASE(validation_function_type)
{
std::string sourceCode = R"(
contract C {
function f(function () external) public pure returns (uint r) { r = 1; }
function g(function () external[] memory) public pure returns (uint r) { r = 2; }
function h(function () external[] calldata) external pure returns (uint r) { r = 3; }
function i(function () external[] calldata a) external pure returns (uint r) { a[0]; r = 4; }
}
)";
bool newDecoder = false;
std::string validFun{"01234567890123456789abcd"};
std::string invalidFun{"01234567890123456789abcdX"};
BOTH_ENCODERS(
compileAndRun(sourceCode);
ABI_CHECK(callContractFunction("f(function)", validFun), encodeArgs(1));
ABI_CHECK(callContractFunction("f(function)", invalidFun), newDecoder ? bytes{} : encodeArgs(1));
ABI_CHECK(callContractFunction("g(function[])", 0x20, 1, validFun), encodeArgs(2));
ABI_CHECK(callContractFunction("g(function[])", 0x20, 1, invalidFun), newDecoder ? bytes{} : encodeArgs(2));
ABI_CHECK(callContractFunction("h(function[])", 0x20, 1, validFun), encodeArgs(3));
// No failure because the data is not accessed.
ABI_CHECK(callContractFunction("h(function[])", 0x20, 1, invalidFun), encodeArgs(3));
ABI_CHECK(callContractFunction("i(function[])", 0x20, 1, validFun), encodeArgs(4));
ABI_CHECK(callContractFunction("i(function[])", 0x20, 1, invalidFun), newDecoder ? bytes{} : encodeArgs(4));
newDecoder = true;
)
}
BOOST_AUTO_TEST_CASE(struct_short)
{
std::string sourceCode = R"(
contract C {
struct S { int a; uint b; bytes16 c; }
function f(S memory s) public pure returns (S memory q) {
q = s;
}
}
)";
NEW_ENCODER(
compileAndRun(sourceCode, 0, "C");
ABI_CHECK(
callContractFunction("f((int256,uint256,bytes16))", 0xff010, 0xff0002, "abcd"),
encodeArgs(0xff010, 0xff0002, "abcd")
);
ABI_CHECK(
callContractFunctionNoEncoding("f((int256,uint256,bytes16))", encodeArgs(0xff010, 0xff0002) + bytes(32, 0)),
encodeArgs(0xff010, 0xff0002, 0)
);
ABI_CHECK(
callContractFunctionNoEncoding("f((int256,uint256,bytes16))", encodeArgs(0xff010, 0xff0002) + bytes(31, 0)),
encodeArgs()
);
)
}
BOOST_AUTO_TEST_CASE(complex_struct)
{
std::string sourceCode = R"(
contract C {
enum E {A, B, C}
struct T { uint x; E e; uint8 y; }
struct S { C c; T[] t;}
function f(uint a, S[2] memory s1, S[] memory s2, uint b) public returns
(uint r1, C r2, uint r3, uint r4, C r5, uint r6, E r7, uint8 r8) {
r1 = a;
r2 = s1[0].c;
r3 = b;
r4 = s2.length;
r5 = s2[1].c;
r6 = s2[1].t.length;
r7 = s2[1].t[1].e;
r8 = s2[1].t[1].y;
}
}
)";
NEW_ENCODER(
compileAndRun(sourceCode, 0, "C");
std::string sig = "f(uint256,(address,(uint256,uint8,uint8)[])[2],(address,(uint256,uint8,uint8)[])[],uint256)";
bytes args = encodeArgs(
7, 0x80, 0x1e0, 8,
// S[2] s1
0x40,
0x100,
// S s1[0]
m_contractAddress,
0x40,
// T s1[0].t
1, // length
// s1[0].t[0]
0x11, 1, 0x12,
// S s1[1]
0, 0x40,
// T s1[1].t
0,
// S[] s2 (0x1e0)
2, // length
0x40, 0xa0,
// S s2[0]
0, 0x40, 0,
// S s2[1]
0x1234, 0x40,
// s2[1].t
3, // length
0, 0, 0,
0x21, 2, 0x22,
0, 0, 0
);
ABI_CHECK(callContractFunction(sig, args), encodeArgs(7, m_contractAddress, 8, 2, 0x1234, 3, 2, 0x22));
// invalid enum value
args.data()[0x20 * 28] = 3;
ABI_CHECK(callContractFunction(sig, args), encodeArgs());
)
}
BOOST_AUTO_TEST_SUITE_END()
} // end namespaces
| 13,897
|
C++
|
.cpp
| 408
| 30.919118
| 143
| 0.676073
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,988
|
MemoryGuardTest.cpp
|
ethereum_solidity/test/libsolidity/MemoryGuardTest.cpp
|
/*
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
#include <test/libsolidity/MemoryGuardTest.h>
#include <test/Common.h>
#include <test/libyul/Common.h>
#include <libsolidity/codegen/ir/Common.h>
#include <libsolutil/Algorithms.h>
#include <libsolutil/StringUtils.h>
#include <libyul/Object.h>
#include <libyul/backends/evm/EVMDialect.h>
#include <libyul/optimiser/FunctionCallFinder.h>
#include <libyul/AST.h>
#include <fstream>
#include <memory>
#include <stdexcept>
using namespace solidity;
using namespace solidity::util;
using namespace solidity::util::formatting;
using namespace solidity::langutil;
using namespace solidity::frontend;
using namespace solidity::frontend::test;
using namespace solidity::test;
using namespace yul;
void MemoryGuardTest::setupCompiler(CompilerStack& _compiler)
{
AnalysisFramework::setupCompiler(_compiler);
_compiler.setViaIR(true);
_compiler.setOptimiserSettings(OptimiserSettings::none());
}
TestCase::TestResult MemoryGuardTest::run(std::ostream& _stream, std::string const& _linePrefix, bool _formatted)
{
if (!runFramework(m_source, PipelineStage::Compilation))
{
printPrefixed(_stream, formatErrors(filteredErrors(), _formatted), _linePrefix);
return TestResult::FatalError;
}
m_obtainedResult.clear();
for (std::string contractName: compiler().contractNames())
{
ErrorList errors;
std::optional<std::string> const& ir = compiler().yulIR(contractName);
solAssert(ir);
auto [object, analysisInfo] = yul::test::parse(
*ir,
EVMDialect::strictAssemblyForEVMObjects(CommonOptions::get().evmVersion(), CommonOptions::get().eofVersion()),
errors
);
if (!object || !analysisInfo || Error::containsErrors(errors))
{
AnsiColorized(_stream, _formatted, {formatting::BOLD, formatting::RED}) << _linePrefix << "Error parsing IR:" << std::endl;
printPrefixed(_stream, formatErrors(filterErrors(errors), _formatted), _linePrefix);
return TestResult::FatalError;
}
auto handleObject = [&](std::string const& _kind, Object const& _object) {
m_obtainedResult += contractName + "(" + _kind + ") " + (findFunctionCalls(
_object.code()->root(),
"memoryguard"_yulname
).empty() ? "false" : "true") + "\n";
};
handleObject("creation", *object);
size_t deployedIndex = object->subIndexByName.at(
IRNames::deployedObject(compiler().contractDefinition(contractName))
);
handleObject("runtime", dynamic_cast<Object const&>(*object->subObjects[deployedIndex]));
}
return checkResult(_stream, _linePrefix, _formatted);
}
| 3,160
|
C++
|
.cpp
| 79
| 37.721519
| 126
| 0.762789
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,993
|
SemanticTest.cpp
|
ethereum_solidity/test/libsolidity/SemanticTest.cpp
|
/*
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/>.
*/
#include <test/libsolidity/SemanticTest.h>
#include <libsolutil/Whiskers.h>
#include <libyul/Exceptions.h>
#include <test/Common.h>
#include <test/libsolidity/util/BytesUtils.h>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/throw_exception.hpp>
#include <algorithm>
#include <cctype>
#include <fstream>
#include <functional>
#include <memory>
#include <optional>
#include <stdexcept>
#include <string>
#include <utility>
using namespace solidity;
using namespace solidity::yul;
using namespace solidity::langutil;
using namespace solidity::util;
using namespace solidity::util::formatting;
using namespace solidity::frontend::test;
using namespace boost::algorithm;
using namespace boost::unit_test;
using namespace std::string_literals;
namespace fs = boost::filesystem;
std::ostream& solidity::frontend::test::operator<<(std::ostream& _output, RequiresYulOptimizer _requiresYulOptimizer)
{
switch (_requiresYulOptimizer)
{
case RequiresYulOptimizer::False: _output << "false"; break;
case RequiresYulOptimizer::MinimalStack: _output << "minimalStack"; break;
case RequiresYulOptimizer::Full: _output << "full"; break;
}
return _output;
}
SemanticTest::SemanticTest(
std::string const& _filename,
langutil::EVMVersion _evmVersion,
std::optional<uint8_t> _eofVersion,
std::vector<boost::filesystem::path> const& _vmPaths,
bool _enforceGasCost,
u256 _enforceGasCostMinValue
):
SolidityExecutionFramework(_evmVersion, _eofVersion, _vmPaths, false),
EVMVersionRestrictedTestCase(_filename),
m_sources(m_reader.sources()),
m_lineOffset(m_reader.lineNumber()),
m_builtins(makeBuiltins()),
m_sideEffectHooks(makeSideEffectHooks()),
m_enforceGasCost(_enforceGasCost),
m_enforceGasCostMinValue(std::move(_enforceGasCostMinValue))
{
static std::set<std::string> const compileViaYulAllowedValues{"also", "true", "false"};
static std::set<std::string> const yulRunTriggers{"also", "true"};
static std::set<std::string> const legacyRunTriggers{"also", "false", "default"};
m_requiresYulOptimizer = m_reader.enumSetting<RequiresYulOptimizer>(
"requiresYulOptimizer",
{
{toString(RequiresYulOptimizer::False), RequiresYulOptimizer::False},
{toString(RequiresYulOptimizer::MinimalStack), RequiresYulOptimizer::MinimalStack},
{toString(RequiresYulOptimizer::Full), RequiresYulOptimizer::Full},
},
toString(RequiresYulOptimizer::False)
);
m_runWithABIEncoderV1Only = m_reader.boolSetting("ABIEncoderV1Only", false);
if (m_runWithABIEncoderV1Only && !solidity::test::CommonOptions::get().useABIEncoderV1)
m_shouldRun = false;
std::string compileViaYul = m_reader.stringSetting("compileViaYul", "also");
if (m_runWithABIEncoderV1Only && compileViaYul != "false")
BOOST_THROW_EXCEPTION(std::runtime_error(
"ABIEncoderV1Only tests cannot be run via yul, "
"so they need to also specify ``compileViaYul: false``"
));
if (!util::contains(compileViaYulAllowedValues, compileViaYul))
BOOST_THROW_EXCEPTION(std::runtime_error("Invalid compileViaYul value: " + compileViaYul + "."));
m_testCaseWantsYulRun = util::contains(yulRunTriggers, compileViaYul);
m_testCaseWantsLegacyRun = util::contains(legacyRunTriggers, compileViaYul);
auto revertStrings = revertStringsFromString(m_reader.stringSetting("revertStrings", "default"));
soltestAssert(revertStrings, "Invalid revertStrings setting.");
m_revertStrings = revertStrings.value();
m_allowNonExistingFunctions = m_reader.boolSetting("allowNonExistingFunctions", false);
parseExpectations(m_reader.stream());
soltestAssert(!m_tests.empty(), "No tests specified in " + _filename);
if (m_enforceGasCost)
{
m_compiler.setMetadataFormat(CompilerStack::MetadataFormat::NoMetadata);
m_compiler.setMetadataHash(CompilerStack::MetadataHash::None);
}
}
std::map<std::string, Builtin> SemanticTest::makeBuiltins()
{
return {
{
"isoltest_builtin_test",
[](FunctionCall const&) -> std::optional<bytes>
{
return toBigEndian(u256(0x1234));
}
},
{
"isoltest_side_effects_test",
[](FunctionCall const& _call) -> std::optional<bytes>
{
if (_call.arguments.parameters.empty())
return toBigEndian(0);
else
return _call.arguments.rawBytes();
}
},
{
"balance",
[this](FunctionCall const& _call) -> std::optional<bytes>
{
soltestAssert(_call.arguments.parameters.size() <= 1, "Account address expected.");
h160 address;
if (_call.arguments.parameters.size() == 1)
address = h160(_call.arguments.parameters.at(0).rawString);
else
address = m_contractAddress;
return toBigEndian(balanceAt(address));
}
},
{
"storageEmpty",
[this](FunctionCall const& _call) -> std::optional<bytes>
{
soltestAssert(_call.arguments.parameters.empty(), "No arguments expected.");
return toBigEndian(u256(storageEmpty(m_contractAddress) ? 1 : 0));
}
},
{
"account",
[this](FunctionCall const& _call) -> std::optional<bytes>
{
soltestAssert(_call.arguments.parameters.size() == 1, "Account number expected.");
size_t accountNumber = static_cast<size_t>(stoi(_call.arguments.parameters.at(0).rawString));
// Need to pad it to 32-bytes to workaround limitations in BytesUtils::formatHex.
return toBigEndian(h256(ExecutionFramework::setAccount(accountNumber).asBytes(), h256::AlignRight));
}
},
};
}
std::vector<SideEffectHook> SemanticTest::makeSideEffectHooks() const
{
using namespace std::placeholders;
return {
[](FunctionCall const& _call) -> std::vector<std::string>
{
if (_call.signature == "isoltest_side_effects_test")
{
std::vector<std::string> result;
for (auto const& argument: _call.arguments.parameters)
result.emplace_back(util::toHex(argument.rawBytes));
return result;
}
return {};
},
bind(&SemanticTest::eventSideEffectHook, this, _1)
};
}
std::string SemanticTest::formatEventParameter(std::optional<AnnotatedEventSignature> _signature, bool _indexed, size_t _index, bytes const& _data)
{
auto isPrintableASCII = [](bytes const& s)
{
bool zeroes = true;
for (auto c: s)
{
if (static_cast<unsigned>(c) != 0x00)
{
zeroes = false;
if (static_cast<unsigned>(c) <= 0x1f || static_cast<unsigned>(c) >= 0x7f)
return false;
} else
break;
}
return !zeroes;
};
ABIType abiType(ABIType::Type::Hex);
if (isPrintableASCII(_data))
abiType = ABIType(ABIType::Type::String);
if (_signature.has_value())
{
std::vector<std::string> const& types = _indexed ? _signature->indexedTypes : _signature->nonIndexedTypes;
if (_index < types.size())
{
if (types.at(_index) == "bool")
abiType = ABIType(ABIType::Type::Boolean);
}
}
return BytesUtils::formatBytes(_data, abiType);
}
std::vector<std::string> SemanticTest::eventSideEffectHook(FunctionCall const&) const
{
std::vector<std::string> sideEffects;
std::vector<LogRecord> recordedLogs = ExecutionFramework::recordedLogs();
for (LogRecord const& log: recordedLogs)
{
std::optional<AnnotatedEventSignature> eventSignature;
if (!log.topics.empty())
eventSignature = matchEvent(log.topics[0]);
std::stringstream sideEffect;
sideEffect << "emit ";
if (eventSignature.has_value())
sideEffect << eventSignature.value().signature;
else
sideEffect << "<anonymous>";
if (m_contractAddress != log.creator)
sideEffect << " from 0x" << log.creator;
std::vector<std::string> eventStrings;
size_t index{0};
for (h256 const& topic: log.topics)
{
if (!eventSignature.has_value() || index != 0)
eventStrings.push_back("#" + formatEventParameter(eventSignature, true, index, topic.asBytes()));
++index;
}
soltestAssert(log.data.size() % 32 == 0, "");
for (size_t index = 0; index < log.data.size() / 32; ++index)
{
auto begin = log.data.begin() + static_cast<long>(index * 32);
bytes const& data = bytes{begin, begin + 32};
eventStrings.emplace_back(formatEventParameter(eventSignature, false, index, data));
}
if (!eventStrings.empty())
sideEffect << ": ";
sideEffect << joinHumanReadable(eventStrings);
sideEffects.emplace_back(sideEffect.str());
}
return sideEffects;
}
std::optional<AnnotatedEventSignature> SemanticTest::matchEvent(util::h256 const& hash) const
{
std::optional<AnnotatedEventSignature> result;
for (std::string& contractName: m_compiler.contractNames())
{
ContractDefinition const& contract = m_compiler.contractDefinition(contractName);
for (EventDefinition const* event: contract.events() + contract.usedInterfaceEvents())
{
FunctionTypePointer eventFunctionType = event->functionType(true);
if (!event->isAnonymous() && keccak256(eventFunctionType->externalSignature()) == hash)
{
AnnotatedEventSignature eventInfo;
eventInfo.signature = eventFunctionType->externalSignature();
for (auto const& param: event->parameters())
if (param->isIndexed())
eventInfo.indexedTypes.emplace_back(param->type()->toString(true));
else
eventInfo.nonIndexedTypes.emplace_back(param->type()->toString(true));
result = eventInfo;
}
}
}
return result;
}
frontend::OptimiserSettings SemanticTest::optimizerSettingsFor(RequiresYulOptimizer _requiresYulOptimizer)
{
switch (_requiresYulOptimizer)
{
case RequiresYulOptimizer::False:
return OptimiserSettings::minimal();
case RequiresYulOptimizer::MinimalStack:
{
OptimiserSettings settings = OptimiserSettings::minimal();
settings.runYulOptimiser = true;
settings.yulOptimiserSteps = "uljmul jmul";
return settings;
}
case RequiresYulOptimizer::Full:
return OptimiserSettings::full();
}
unreachable();
}
TestCase::TestResult SemanticTest::run(std::ostream& _stream, std::string const& _linePrefix, bool _formatted)
{
TestResult result = TestResult::Success;
if (m_testCaseWantsLegacyRun && !m_eofVersion.has_value())
result = runTest(_stream, _linePrefix, _formatted, false /* _isYulRun */);
if (m_testCaseWantsYulRun && result == TestResult::Success)
{
if (solidity::test::CommonOptions::get().optimize)
result = runTest(_stream, _linePrefix, _formatted, true /* _isYulRun */);
else
result = tryRunTestWithYulOptimizer(_stream, _linePrefix, _formatted);
}
if (result != TestResult::Success)
solidity::test::CommonOptions::get().printSelectedOptions(
_stream,
_linePrefix,
{"evmVersion", "optimize", "useABIEncoderV1", "batch"}
);
return result;
}
TestCase::TestResult SemanticTest::runTest(
std::ostream& _stream,
std::string const& _linePrefix,
bool _formatted,
bool _isYulRun
)
{
bool success = true;
m_gasCostFailure = false;
selectVM(evmc_capabilities::EVMC_CAPABILITY_EVM1);
reset();
m_compileViaYul = _isYulRun;
if (_isYulRun)
AnsiColorized(_stream, _formatted, {BOLD, CYAN}) << _linePrefix << "Running via Yul: " << std::endl;
for (TestFunctionCall& test: m_tests)
test.reset();
std::map<std::string, solidity::test::Address> libraries;
bool constructed = false;
for (TestFunctionCall& test: m_tests)
{
if (constructed)
{
soltestAssert(
test.call().kind != FunctionCall::Kind::Library,
"Libraries have to be deployed before any other call."
);
soltestAssert(
test.call().kind != FunctionCall::Kind::Constructor,
"Constructor has to be the first function call expect for library deployments."
);
}
else if (test.call().kind == FunctionCall::Kind::Library)
{
soltestAssert(
deploy(test.call().signature, 0, {}, libraries) && m_transactionSuccessful,
"Failed to deploy library " + test.call().signature);
// For convenience, in semantic tests we assume that an unqualified name like `L` is equivalent to one
// with an empty source unit name (`:L`). This is fine because the compiler never uses unqualified
// names in the Yul code it produces and does not allow `linkersymbol()` at all in inline assembly.
libraries[test.call().libraryFile + ":" + test.call().signature] = m_contractAddress;
continue;
}
else
{
if (test.call().kind == FunctionCall::Kind::Constructor)
deploy("", test.call().value.value, test.call().arguments.rawBytes(), libraries);
else
soltestAssert(deploy("", 0, bytes(), libraries), "Failed to deploy contract.");
constructed = true;
}
if (test.call().kind == FunctionCall::Kind::Constructor)
{
if (m_transactionSuccessful == test.call().expectations.failure)
success = false;
if (success && !checkGasCostExpectation(test, _isYulRun))
{
success = false;
m_gasCostFailure = true;
}
test.setFailure(!m_transactionSuccessful);
test.setRawBytes(bytes());
}
else
{
bytes output;
if (test.call().kind == FunctionCall::Kind::LowLevel)
output = callLowLevel(test.call().arguments.rawBytes(), test.call().value.value);
else if (test.call().kind == FunctionCall::Kind::Builtin)
{
std::optional<bytes> builtinOutput = m_builtins.at(test.call().signature)(test.call());
if (builtinOutput.has_value())
{
m_transactionSuccessful = true;
output = builtinOutput.value();
}
else
m_transactionSuccessful = false;
}
else
{
soltestAssert(
m_allowNonExistingFunctions ||
m_compiler.interfaceSymbols(m_compiler.lastContractName(m_sources.mainSourceFile))["methods"].contains(test.call().signature),
"The function " + test.call().signature + " is not known to the compiler"
);
output = callContractFunctionWithValueNoEncoding(
test.call().signature,
test.call().value.value,
test.call().arguments.rawBytes()
);
}
bool outputMismatch = (output != test.call().expectations.rawBytes());
if (!outputMismatch && !checkGasCostExpectation(test, _isYulRun))
{
success = false;
m_gasCostFailure = true;
}
// Pre byzantium, it was not possible to return failure data, so we disregard
// output mismatch for those EVM versions.
if (test.call().expectations.failure && !m_transactionSuccessful && !m_evmVersion.supportsReturndata())
outputMismatch = false;
if (m_transactionSuccessful != !test.call().expectations.failure || outputMismatch)
success = false;
test.setFailure(!m_transactionSuccessful);
test.setRawBytes(std::move(output));
if (test.call().kind != FunctionCall::Kind::LowLevel)
test.setContractABI(m_compiler.contractABI(m_compiler.lastContractName(m_sources.mainSourceFile)));
}
std::vector<std::string> effects;
for (SideEffectHook const& hook: m_sideEffectHooks)
effects += hook(test.call());
test.setSideEffects(std::move(effects));
success &= test.call().expectedSideEffects == test.call().actualSideEffects;
}
if (!success)
{
AnsiColorized(_stream, _formatted, {BOLD, CYAN}) << _linePrefix << "Expected result:" << std::endl;
for (TestFunctionCall const& test: m_tests)
{
ErrorReporter errorReporter;
_stream << test.format(
errorReporter,
_linePrefix,
TestFunctionCall::RenderMode::ExpectedValuesExpectedGas,
_formatted,
/* _interactivePrint */ true
) << std::endl;
_stream << errorReporter.format(_linePrefix, _formatted);
}
_stream << std::endl;
AnsiColorized(_stream, _formatted, {BOLD, CYAN}) << _linePrefix << "Obtained result:" << std::endl;
for (TestFunctionCall const& test: m_tests)
{
ErrorReporter errorReporter;
_stream << test.format(
errorReporter,
_linePrefix,
m_gasCostFailure ? TestFunctionCall::RenderMode::ExpectedValuesActualGas : TestFunctionCall::RenderMode::ActualValuesExpectedGas,
_formatted,
/* _interactivePrint */ true
) << std::endl;
_stream << errorReporter.format(_linePrefix, _formatted);
}
AnsiColorized(_stream, _formatted, {BOLD, RED})
<< _linePrefix << std::endl
<< _linePrefix << "Attention: Updates on the test will apply the detected format displayed." << std::endl;
if (_isYulRun && m_testCaseWantsLegacyRun)
{
_stream << _linePrefix << std::endl << _linePrefix;
AnsiColorized(_stream, _formatted, {RED_BACKGROUND}) << "Note that the test passed without Yul.";
_stream << std::endl;
}
else if (!_isYulRun && m_testCaseWantsYulRun)
AnsiColorized(_stream, _formatted, {BOLD, YELLOW})
<< _linePrefix << std::endl
<< _linePrefix << "Note that the test also has to pass via Yul." << std::endl;
return TestResult::Failure;
}
return TestResult::Success;
}
TestCase::TestResult SemanticTest::tryRunTestWithYulOptimizer(
std::ostream& _stream,
std::string const& _linePrefix,
bool _formatted
)
{
TestResult result{};
for (auto requiresYulOptimizer: {
RequiresYulOptimizer::False,
RequiresYulOptimizer::MinimalStack,
RequiresYulOptimizer::Full,
})
{
ScopedSaveAndRestore optimizerSettings(
m_optimiserSettings,
optimizerSettingsFor(requiresYulOptimizer)
);
try
{
result = runTest(_stream, _linePrefix, _formatted, true /* _isYulRun */);
}
catch (yul::StackTooDeepError const&)
{
if (requiresYulOptimizer == RequiresYulOptimizer::Full)
throw;
else
continue;
}
if (m_requiresYulOptimizer != requiresYulOptimizer && result != TestResult::FatalError)
{
soltestAssert(result == TestResult::Success || result == TestResult::Failure);
AnsiColorized(_stream, _formatted, {BOLD, YELLOW})
<< _linePrefix << std::endl
<< _linePrefix << "requiresYulOptimizer is set to " << m_requiresYulOptimizer
<< " but should be " << requiresYulOptimizer << std::endl;
m_requiresYulOptimizer = requiresYulOptimizer;
return TestResult::Failure;
}
return result;
}
unreachable();
}
bool SemanticTest::checkGasCostExpectation(TestFunctionCall& io_test, bool _compileViaYul) const
{
std::string setting =
(_compileViaYul ? "ir"s : "legacy"s) +
(m_optimiserSettings == OptimiserSettings::full() ? "Optimized" : "");
soltestAssert(
io_test.call().expectations.gasUsedExcludingCode.count(setting) ==
io_test.call().expectations.gasUsedForCodeDeposit.count(setting)
);
// We don't check gas if enforce gas cost is not active
// or test is run with abi encoder v1 only
// or gas used less than threshold for enforcing feature
// or the test has used up all available gas (test will fail anyway)
// or setting is "ir" and it's not included in expectations
// or if the called function is an isoltest builtin e.g. `smokeTest` or `storageEmpty`
if (
!m_enforceGasCost ||
m_gasUsed < m_enforceGasCostMinValue ||
m_gasUsed >= InitialGas ||
(setting == "ir" && io_test.call().expectations.gasUsedExcludingCode.count(setting) == 0) ||
io_test.call().kind == FunctionCall::Kind::Builtin
)
return true;
solAssert(!m_runWithABIEncoderV1Only, "");
// NOTE: Cost excluding code is unlikely to be negative but it may still be possible due to refunds.
// We'll deal with it when we actually have a test case like that.
solUnimplementedAssert(m_gasUsed >= m_gasUsedForCodeDeposit);
io_test.setGasCostExcludingCode(setting, m_gasUsed - m_gasUsedForCodeDeposit);
io_test.setCodeDepositGasCost(setting, m_gasUsedForCodeDeposit);
return
io_test.call().expectations.gasUsedExcludingCode.count(setting) > 0 &&
m_gasUsed - m_gasUsedForCodeDeposit == io_test.call().expectations.gasUsedExcludingCode.at(setting) &&
m_gasUsedForCodeDeposit == io_test.call().expectations.gasUsedForCodeDeposit.at(setting);
}
void SemanticTest::printSource(std::ostream& _stream, std::string const& _linePrefix, bool _formatted) const
{
if (m_sources.sources.empty())
return;
bool outputNames = (m_sources.sources.size() - m_sources.externalSources.size() != 1 || !m_sources.sources.begin()->first.empty());
std::set<std::string> externals;
for (auto const& [name, path]: m_sources.externalSources)
{
externals.insert(name);
std::string externalSource;
if (name == path)
externalSource = name;
else
externalSource = name + "=" + path.generic_string();
if (_formatted)
_stream << _linePrefix << formatting::CYAN << "==== ExternalSource: " << externalSource << " ===="s << formatting::RESET << std::endl;
else
_stream << _linePrefix << "==== ExternalSource: " << externalSource << " ===="s << std::endl;
}
for (auto const& [name, source]: m_sources.sources)
if (externals.find(name) == externals.end())
{
if (_formatted)
{
if (source.empty())
continue;
if (outputNames)
_stream << _linePrefix << formatting::CYAN << "==== Source: " << name
<< " ====" << formatting::RESET << std::endl;
std::vector<char const*> sourceFormatting(source.length(), formatting::RESET);
_stream << _linePrefix << sourceFormatting.front() << source.front();
for (size_t i = 1; i < source.length(); i++)
{
if (sourceFormatting[i] != sourceFormatting[i - 1])
_stream << sourceFormatting[i];
if (source[i] != '\n')
_stream << source[i];
else
{
_stream << formatting::RESET << std::endl;
if (i + 1 < source.length())
_stream << _linePrefix << sourceFormatting[i];
}
}
_stream << formatting::RESET;
}
else
{
if (outputNames)
printPrefixed(_stream, "==== Source: " + name + " ====", _linePrefix);
printPrefixed(_stream, source, _linePrefix);
}
}
}
void SemanticTest::printUpdatedExpectations(std::ostream& _stream, std::string const&) const
{
for (TestFunctionCall const& test: m_tests)
_stream << test.format(
"",
m_gasCostFailure ? TestFunctionCall::RenderMode::ExpectedValuesActualGas : TestFunctionCall::RenderMode::ActualValuesExpectedGas,
/* _highlight = */ false
) << std::endl;
}
void SemanticTest::printUpdatedSettings(std::ostream& _stream, std::string const& _linePrefix)
{
auto& settings = m_reader.settings();
if (settings.empty() && m_requiresYulOptimizer == RequiresYulOptimizer::False)
return;
_stream << _linePrefix << "// ====" << std::endl;
if (m_requiresYulOptimizer != RequiresYulOptimizer::False)
_stream << _linePrefix << "// requiresYulOptimizer: " << m_requiresYulOptimizer << std::endl;
for (auto const& [settingName, settingValue]: settings)
if (settingName != "requiresYulOptimizer")
_stream << _linePrefix << "// " << settingName << ": " << settingValue<< std::endl;
}
void SemanticTest::parseExpectations(std::istream& _stream)
{
m_tests += TestFileParser{_stream, m_builtins}.parseFunctionCalls(m_lineOffset);
}
bool SemanticTest::deploy(
std::string const& _contractName,
u256 const& _value,
bytes const& _arguments,
std::map<std::string, solidity::test::Address> const& _libraries
)
{
auto output = compileAndRunWithoutCheck(m_sources.sources, _value, _contractName, _arguments, _libraries, m_sources.mainSourceFile);
return !output.empty() && m_transactionSuccessful;
}
| 23,337
|
C++
|
.cpp
| 633
| 33.650869
| 147
| 0.723698
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,994
|
GasMeter.cpp
|
ethereum_solidity/test/libsolidity/GasMeter.cpp
|
/*
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
/**
* @author Christian <c@ethdev.com>
* @date 2015
* Unit tests for the gas estimator.
*/
#include <test/libsolidity/SolidityExecutionFramework.h>
#include <libevmasm/GasMeter.h>
#include <libevmasm/KnownState.h>
#include <libevmasm/PathGasMeter.h>
#include <libsolidity/ast/AST.h>
#include <libsolidity/interface/GasEstimator.h>
using namespace solidity::langutil;
using namespace solidity::evmasm;
using namespace solidity::frontend;
using namespace solidity::frontend::test;
using namespace solidity::test;
namespace solidity::frontend::test
{
class GasMeterTestFramework: public SolidityExecutionFramework
{
public:
void compile(std::string const& _sourceCode)
{
m_compiler.reset();
m_compiler.setSources({{"", "pragma solidity >=0.0;\n"
"// SPDX-License-Identifier: GPL-3.0\n" + _sourceCode}});
m_compiler.setOptimiserSettings(solidity::test::CommonOptions::get().optimize);
m_compiler.setEVMVersion(m_evmVersion);
BOOST_REQUIRE_MESSAGE(m_compiler.compile(), "Compiling contract failed");
}
void testCreationTimeGas(std::string const& _sourceCode, u256 const& _tolerance = u256(0))
{
compileAndRun(_sourceCode);
auto state = std::make_shared<KnownState>();
PathGasMeter meter(*m_compiler.assemblyItems(m_compiler.lastContractName()), solidity::test::CommonOptions::get().evmVersion());
GasMeter::GasConsumption gas = meter.estimateMax(0, state);
u256 bytecodeSize(m_compiler.runtimeObject(m_compiler.lastContractName()).bytecode.size());
// costs for deployment
gas += bytecodeSize * GasCosts::createDataGas;
// costs for transaction
gas += gasForTransaction(m_compiler.object(m_compiler.lastContractName()).bytecode, true);
BOOST_REQUIRE(!gas.isInfinite);
BOOST_CHECK_LE(m_gasUsed, gas.value);
BOOST_CHECK_LE(gas.value - _tolerance, m_gasUsed);
}
/// Compares the gas computed by PathGasMeter for the given signature (but unknown arguments)
/// against the actual gas usage computed by the VM on the given set of argument variants.
void testRunTimeGas(std::string const& _sig, std::vector<bytes> _argumentVariants, u256 const& _tolerance = u256(0))
{
u256 gasUsed = 0;
GasMeter::GasConsumption gas;
util::FixedHash<4> hash = util::selectorFromSignatureH32(_sig);
for (bytes const& arguments: _argumentVariants)
{
sendMessage(hash.asBytes() + arguments, false, 0);
BOOST_CHECK(m_transactionSuccessful);
gasUsed = std::max(gasUsed, m_gasUsed);
gas = std::max(gas, gasForTransaction(hash.asBytes() + arguments, false));
}
gas += GasEstimator(solidity::test::CommonOptions::get().evmVersion()).functionalEstimation(
*m_compiler.runtimeAssemblyItems(m_compiler.lastContractName()),
_sig
);
BOOST_REQUIRE(!gas.isInfinite);
BOOST_CHECK_LE(m_gasUsed, gas.value);
BOOST_CHECK_LE(gas.value - _tolerance, m_gasUsed);
}
static GasMeter::GasConsumption gasForTransaction(bytes const& _data, bool _isCreation)
{
auto evmVersion = solidity::test::CommonOptions::get().evmVersion();
GasMeter::GasConsumption gas = _isCreation ? GasCosts::txCreateGas : GasCosts::txGas;
for (auto i: _data)
gas += i != 0 ? GasCosts::txDataNonZeroGas(evmVersion) : GasCosts::txDataZeroGas;
return gas;
}
};
BOOST_FIXTURE_TEST_SUITE(GasMeterTests, GasMeterTestFramework)
BOOST_AUTO_TEST_CASE(simple_contract)
{
// Tests a simple "deploy contract" code without constructor. The actual contract is not relevant.
char const* sourceCode = R"(
contract test {
bytes32 public shaValue;
function f(uint a) public {
shaValue = keccak256(abi.encodePacked(a));
}
}
)";
testCreationTimeGas(sourceCode);
}
BOOST_AUTO_TEST_CASE(store_keccak256)
{
char const* sourceCode = R"(
// TODO: We should enable v2 again once the yul optimizer is activated.
pragma abicoder v1;
contract test {
bytes32 public shaValue;
constructor() {
shaValue = keccak256(abi.encodePacked(this));
}
}
)";
testCreationTimeGas(sourceCode);
}
BOOST_AUTO_TEST_CASE(updating_store)
{
char const* sourceCode = R"(
contract test {
uint data;
uint data2;
constructor() {
data = 1;
data = 2;
data2 = 0;
}
}
)";
testCreationTimeGas(sourceCode, m_evmVersion < langutil::EVMVersion::constantinople() ? u256(0) : u256(9600));
}
BOOST_AUTO_TEST_CASE(branches)
{
char const* sourceCode = R"(
contract test {
uint data;
uint data2;
function f(uint x) public {
if (x > 7)
data2 = 1;
else
data = 1;
}
}
)";
testCreationTimeGas(sourceCode, 1);
testRunTimeGas("f(uint256)", std::vector<bytes>{encodeArgs(2), encodeArgs(8)}, 1);
}
BOOST_AUTO_TEST_CASE(function_calls)
{
char const* sourceCode = R"(
contract test {
uint data;
uint data2;
function f(uint x) public {
if (x > 7)
{ unchecked { data2 = g(x**8) + 1; } }
else
data = 1;
}
function g(uint x) internal returns (uint) {
return data2;
}
}
)";
testCreationTimeGas(sourceCode);
// In f, data2 is accessed twice, so there is a reduction of 2200 to 100 in actual costs.
// However, GasMeter always assumes cold costs.
testRunTimeGas(
"f(uint256)",
std::vector<bytes>{encodeArgs(2), encodeArgs(8)},
m_evmVersion < EVMVersion::berlin() ?
u256(0) :
u256(2100)
);
}
BOOST_AUTO_TEST_CASE(multiple_external_functions)
{
char const* sourceCode = R"(
// TODO: We should enable v2 again once the yul optimizer is activated.
pragma abicoder v1;
contract test {
uint data;
uint data2;
function f(uint x) public {
if (x > 7)
{ unchecked { data2 = g(x**8) + 1; } }
else
data = 1;
}
function g(uint x) public returns (uint) {
return data2;
}
}
)";
testCreationTimeGas(sourceCode);
// In f, data2 is accessed twice, so there is a reduction of 2200 to 100 in actual costs.
// However, GasMeter always assumes cold costs.
testRunTimeGas(
"f(uint256)",
std::vector<bytes>{encodeArgs(2), encodeArgs(8)},
m_evmVersion < EVMVersion::berlin() ?
u256(0) :
u256(2100)
);
testRunTimeGas("g(uint256)", std::vector<bytes>{encodeArgs(2)});
}
BOOST_AUTO_TEST_CASE(exponent_size)
{
char const* sourceCode = R"(
// TODO: We should enable v2 again once the yul optimizer is activated.
pragma abicoder v1;
contract A {
function f(uint x) public returns (uint) {
unchecked { return x ** 0; }
}
function g(uint x) public returns (uint) {
unchecked { return x ** 0x100; }
}
function h(uint x) public returns (uint) {
unchecked { return x ** 0x10000; }
}
}
)";
testCreationTimeGas(sourceCode);
testRunTimeGas("f(uint256)", std::vector<bytes>{encodeArgs(2)});
testRunTimeGas("g(uint256)", std::vector<bytes>{encodeArgs(2)});
testRunTimeGas("h(uint256)", std::vector<bytes>{encodeArgs(2)});
}
BOOST_AUTO_TEST_CASE(balance_gas)
{
char const* sourceCode = R"(
contract A {
function lookup_balance(address a) public returns (uint) {
return a.balance;
}
}
)";
testCreationTimeGas(sourceCode);
testRunTimeGas("lookup_balance(address)", std::vector<bytes>{encodeArgs(2), encodeArgs(100)});
}
BOOST_AUTO_TEST_CASE(extcodesize_gas)
{
char const* sourceCode = R"(
contract A {
function f() public returns (uint _s) {
assembly {
_s := extcodesize(0x30)
}
}
}
)";
testCreationTimeGas(sourceCode);
testRunTimeGas("f()", std::vector<bytes>{encodeArgs()});
}
BOOST_AUTO_TEST_CASE(regular_functions_exclude_fallback)
{
// A bug in the estimator caused the costs for a specific function
// to always include the costs for the fallback.
char const* sourceCode = R"(
contract A {
uint public x;
fallback() external { x = 2; }
}
)";
testCreationTimeGas(sourceCode);
testRunTimeGas("x()", std::vector<bytes>{encodeArgs()});
}
BOOST_AUTO_TEST_CASE(complex_control_flow)
{
// This crashed the gas estimator previously (or took a very long time).
// Now we do not follow branches if they start out with lower gas costs than the ones
// we previously considered. This of course reduces accuracy.
char const* sourceCode = R"(
// TODO: We should enable v2 again once the yul optimizer is activated.
pragma abicoder v1;
contract log {
function ln(int128 x) public pure returns (int128 result) {
unchecked {
int128 t = x / 256;
int128 y = 5545177;
x = t;
t = x * 16; if (t <= 1000000) { x = t; y = y - 2772588; }
t = x * 4; if (t <= 1000000) { x = t; y = y - 1386294; }
t = x * 2; if (t <= 1000000) { x = t; y = y - 693147; }
t = x + x / 2; if (t <= 1000000) { x = t; y = y - 405465; }
t = x + x / 4; if (t <= 1000000) { x = t; y = y - 223144; }
t = x + x / 8; if (t <= 1000000) { x = t; y = y - 117783; }
t = x + x / 16; if (t <= 1000000) { x = t; y = y - 60624; }
t = x + x / 32; if (t <= 1000000) { x = t; y = y - 30771; }
t = x + x / 64; if (t <= 1000000) { x = t; y = y - 15504; }
t = x + x / 128; if (t <= 1000000) { x = t; y = y - 7782; }
t = x + x / 256; if (t <= 1000000) { x = t; y = y - 3898; }
t = x + x / 512; if (t <= 1000000) { x = t; y = y - 1951; }
t = x + x / 1024; if (t <= 1000000) { x = t; y = y - 976; }
t = x + x / 2048; if (t <= 1000000) { x = t; y = y - 488; }
t = x + x / 4096; if (t <= 1000000) { x = t; y = y - 244; }
t = x + x / 8192; if (t <= 1000000) { x = t; y = y - 122; }
t = x + x / 16384; if (t <= 1000000) { x = t; y = y - 61; }
t = x + x / 32768; if (t <= 1000000) { x = t; y = y - 31; }
t = x + x / 65536; if (t <= 1000000) { y = y - 15; }
return y;
}
}
}
)";
testCreationTimeGas(sourceCode);
// max gas is used for small x
testRunTimeGas("ln(int128)", std::vector<bytes>{encodeArgs(0), encodeArgs(10), encodeArgs(105), encodeArgs(30000)});
}
BOOST_AUTO_TEST_CASE(
mcopy_memory_expansion_gas,
*boost::unit_test::precondition(minEVMVersionCheck(EVMVersion::cancun()))
)
{
char const* sourceCode = R"(
contract C {
function no_expansion() public {
assembly {
mstore(0xffe0, 1) // expand memory before using mcopy
mcopy(0, 0xffff, 1)
return(0, 1)
}
}
function expansion_on_write() public {
assembly {
mcopy(0xffff, 0, 1)
return(0xffff, 1)
}
}
function expansion_on_read() public {
assembly {
mcopy(0, 0xffff, 1)
return(0, 1)
}
}
function expansion_on_read_write() public {
assembly {
mcopy(0xffff, 0xffff, 1)
return(0, 1)
}
}
function expansion_on_zero_size() public {
assembly {
mcopy(0xffff, 0xffff, 0)
return(0, 1)
}
}
function expansion_on_0_0_0() public {
assembly {
mcopy(0, 0, 0)
return(0, 1)
}
}
}
)";
testCreationTimeGas(sourceCode);
testRunTimeGas("no_expansion()", {encodeArgs()});
testRunTimeGas("expansion_on_write()", {encodeArgs()});
testRunTimeGas("expansion_on_read()", {encodeArgs()});
testRunTimeGas("expansion_on_read_write()", {encodeArgs()});
testRunTimeGas("expansion_on_zero_size()", {encodeArgs()});
testRunTimeGas("expansion_on_0_0_0()", {encodeArgs()});
}
BOOST_AUTO_TEST_CASE(
mcopy_word_gas,
*boost::unit_test::precondition(minEVMVersionCheck(EVMVersion::cancun()))
)
{
char const* sourceCode = R"(
contract C {
function no_overlap() public {
assembly {
mstore(0xffe0, 1) // expand memory before using mcopy
mcopy(0x4000, 0x2000, 0x2000)
return(0, 0x10000)
}
}
function overlap_right() public {
assembly {
mstore(0xffe0, 1) // expand memory before using mcopy
mcopy(0x3000, 0x2000, 0x2000)
return(0, 0x10000)
}
}
function overlap_left() public {
assembly {
mstore(0xffe0, 1) // expand memory before using mcopy
mcopy(0x1000, 0x2000, 0x2000)
return(0, 0x10000)
}
}
function overlap_full() public {
assembly {
mstore(0xffe0, 1) // expand memory before using mcopy
mcopy(0x2000, 0x2000, 0x2000)
return(0, 0x10000)
}
}
}
)";
testCreationTimeGas(sourceCode);
testRunTimeGas("no_overlap()", {encodeArgs()});
testRunTimeGas("overlap_right()", {encodeArgs()});
testRunTimeGas("overlap_left()", {encodeArgs()});
testRunTimeGas("overlap_full()", {encodeArgs()});
}
BOOST_AUTO_TEST_SUITE_END()
}
| 12,861
|
C++
|
.cpp
| 411
| 27.997567
| 130
| 0.676364
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,996
|
Assembly.cpp
|
ethereum_solidity/test/libsolidity/Assembly.cpp
|
/*
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
/**
* @author Lefteris Karapetsas <lefteris@ethdev.com>
* @date 2015
* Unit tests for Assembly Items from evmasm/Assembly.h
*/
#include <test/Common.h>
#include <liblangutil/SourceLocation.h>
#include <libevmasm/Assembly.h>
#include <liblangutil/CharStream.h>
#include <libsolidity/parsing/Parser.h>
#include <libsolidity/analysis/DeclarationTypeChecker.h>
#include <libsolidity/analysis/NameAndTypeResolver.h>
#include <libsolidity/analysis/Scoper.h>
#include <libsolidity/codegen/Compiler.h>
#include <libsolidity/ast/AST.h>
#include <libsolidity/analysis/TypeChecker.h>
#include <libsolidity/analysis/SyntaxChecker.h>
#include <liblangutil/ErrorReporter.h>
#include <boost/test/unit_test.hpp>
#include <string>
#include <iostream>
using namespace solidity::langutil;
using namespace solidity::evmasm;
namespace solidity::frontend::test
{
namespace
{
evmasm::AssemblyItems compileContract(std::shared_ptr<CharStream> _sourceCode)
{
ErrorList errors;
ErrorReporter errorReporter(errors);
Parser parser(
errorReporter,
solidity::test::CommonOptions::get().evmVersion(),
solidity::test::CommonOptions::get().eofVersion()
);
ASTPointer<SourceUnit> sourceUnit;
BOOST_REQUIRE_NO_THROW(sourceUnit = parser.parse(*_sourceCode));
BOOST_CHECK(!!sourceUnit);
Scoper::assignScopes(*sourceUnit);
BOOST_REQUIRE(SyntaxChecker(errorReporter, false).checkSyntax(*sourceUnit));
GlobalContext globalContext(solidity::test::CommonOptions::get().evmVersion());
NameAndTypeResolver resolver(globalContext, solidity::test::CommonOptions::get().evmVersion(), errorReporter, false);
DeclarationTypeChecker declarationTypeChecker(errorReporter, solidity::test::CommonOptions::get().evmVersion());
solAssert(!Error::containsErrors(errorReporter.errors()), "");
resolver.registerDeclarations(*sourceUnit);
BOOST_REQUIRE_NO_THROW(resolver.resolveNamesAndTypes(*sourceUnit));
if (Error::containsErrors(errorReporter.errors()))
return AssemblyItems();
for (ASTPointer<ASTNode> const& node: sourceUnit->nodes())
{
BOOST_REQUIRE_NO_THROW(declarationTypeChecker.check(*node));
if (Error::containsErrors(errorReporter.errors()))
return AssemblyItems();
}
TypeChecker checker(solidity::test::CommonOptions::get().evmVersion(), errorReporter);
BOOST_REQUIRE_NO_THROW(checker.checkTypeRequirements(*sourceUnit));
if (Error::containsErrors(errorReporter.errors()))
return AssemblyItems();
for (ASTPointer<ASTNode> const& node: sourceUnit->nodes())
if (ContractDefinition* contract = dynamic_cast<ContractDefinition*>(node.get()))
{
Compiler compiler(
solidity::test::CommonOptions::get().evmVersion(),
RevertStrings::Default,
solidity::test::CommonOptions::get().optimize ? OptimiserSettings::standard() : OptimiserSettings::minimal()
);
compiler.compileContract(*contract, std::map<ContractDefinition const*, std::shared_ptr<Compiler const>>{}, bytes());
BOOST_REQUIRE(compiler.runtimeAssembly().codeSections().size() == 1);
return compiler.runtimeAssembly().codeSections().at(0).items;
}
BOOST_FAIL("No contract found in source.");
return AssemblyItems();
}
void printAssemblyLocations(AssemblyItems const& _items)
{
auto printRepeated = [](SourceLocation const& _loc, size_t _repetitions)
{
std::cout <<
"\t\tvector<SourceLocation>(" <<
_repetitions <<
", SourceLocation{" <<
_loc.start <<
", " <<
_loc.end <<
", make_shared<string>(\"" <<
*_loc.sourceName <<
"\")}) +" << std::endl;
};
std::vector<SourceLocation> locations;
for (auto const& item: _items)
locations.push_back(item.location());
size_t repetitions = 0;
SourceLocation const* previousLoc = nullptr;
for (size_t i = 0; i < locations.size(); ++i)
{
SourceLocation& loc = locations[i];
if (previousLoc && *previousLoc == loc)
repetitions++;
else
{
if (previousLoc)
printRepeated(*previousLoc, repetitions);
previousLoc = &loc;
repetitions = 1;
}
}
if (previousLoc)
printRepeated(*previousLoc, repetitions);
}
void checkAssemblyLocations(AssemblyItems const& _items, std::vector<SourceLocation> const& _locations)
{
BOOST_CHECK_EQUAL(_items.size(), _locations.size());
for (size_t i = 0; i < std::min(_items.size(), _locations.size()); ++i)
{
if (_items[i].location().start != _locations[i].start ||
_items[i].location().end != _locations[i].end)
{
BOOST_CHECK_MESSAGE(false, "Location mismatch for item " + std::to_string(i) + ". Found the following locations:");
printAssemblyLocations(_items);
return;
}
}
}
} // end anonymous namespace
BOOST_AUTO_TEST_SUITE(Assembly)
BOOST_AUTO_TEST_CASE(location_test)
{
std::string sourceCode = R"(
pragma abicoder v1;
contract test {
function f() public returns (uint256 a) {
return 16;
}
}
)";
AssemblyItems items = compileContract(std::make_shared<CharStream>(sourceCode, ""));
std::shared_ptr<std::string> sourceName = std::make_shared<std::string>();
bool hasShifts = solidity::test::CommonOptions::get().evmVersion().hasBitwiseShifting();
auto codegenCharStream = std::make_shared<CharStream>("", "--CODEGEN--");
std::vector<SourceLocation> locations;
if (solidity::test::CommonOptions::get().optimize)
locations =
std::vector<SourceLocation>(31, SourceLocation{23, 103, sourceName}) +
std::vector<SourceLocation>(1, SourceLocation{41, 100, sourceName}) +
std::vector<SourceLocation>(1, SourceLocation{93, 95, sourceName}) +
std::vector<SourceLocation>(15, SourceLocation{41, 100, sourceName});
else
locations =
std::vector<SourceLocation>(hasShifts ? 31 : 32, SourceLocation{23, 103, sourceName}) +
std::vector<SourceLocation>(24, SourceLocation{41, 100, sourceName}) +
std::vector<SourceLocation>(1, SourceLocation{70, 79, sourceName}) +
std::vector<SourceLocation>(1, SourceLocation{93, 95, sourceName}) +
std::vector<SourceLocation>(2, SourceLocation{86, 95, sourceName}) +
std::vector<SourceLocation>(2, SourceLocation{41, 100, sourceName});
checkAssemblyLocations(items, locations);
}
BOOST_AUTO_TEST_CASE(jump_type)
{
auto sourceCode = std::make_shared<CharStream>(R"(
pragma abicoder v1;
contract C {
function f(uint a) public pure returns (uint t) {
assembly {
function g(x) -> y { if x { leave } y := 8 }
t := g(a)
}
}
}
)", "");
AssemblyItems items = compileContract(sourceCode);
std::string jumpTypes;
for (AssemblyItem const& item: items)
if (item.getJumpType() != AssemblyItem::JumpType::Ordinary)
jumpTypes += item.getJumpTypeAsString() + "\n";
if (solidity::test::CommonOptions::get().optimize)
BOOST_CHECK_EQUAL(jumpTypes, "[in]\n[out]\n[out]\n[in]\n[out]\n");
else
BOOST_CHECK_EQUAL(jumpTypes, "[in]\n[out]\n[in]\n[out]\n");
}
BOOST_AUTO_TEST_SUITE_END()
} // end namespaces
| 7,441
|
C++
|
.cpp
| 196
| 35.413265
| 120
| 0.744247
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
2,997
|
OptimizedIRCachingTest.cpp
|
ethereum_solidity/test/libsolidity/OptimizedIRCachingTest.cpp
|
/*
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
#include <test/libsolidity/OptimizedIRCachingTest.h>
#include <test/libsolidity/util/SoltestErrors.h>
#include <liblangutil/Exceptions.h>
#include <libsolutil/StringUtils.h>
using namespace solidity::util;
using namespace solidity::langutil;
using namespace solidity::frontend;
using namespace solidity::frontend::test;
void OptimizedIRCachingTest::setupCompiler(CompilerStack& _compiler)
{
AnalysisFramework::setupCompiler(_compiler);
_compiler.setOptimiserSettings(true);
_compiler.setViaIR(true);
}
TestCase::TestResult OptimizedIRCachingTest::run(std::ostream& _stream, std::string const& _linePrefix, bool _formatted)
{
soltestAssert(compiler().objectOptimizer().size() == 0);
if (!runFramework(m_source, PipelineStage::Compilation))
{
printPrefixed(_stream, formatErrors(filteredErrors(), _formatted), _linePrefix);
return TestResult::FatalError;
}
m_obtainedResult = "cachedObjects: " + toString(compiler().objectOptimizer().size()) + "\n";
return checkResult(_stream, _linePrefix, _formatted);
}
| 1,710
|
C++
|
.cpp
| 39
| 41.948718
| 120
| 0.793976
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,998
|
ASTPropertyTest.cpp
|
ethereum_solidity/test/libsolidity/ASTPropertyTest.cpp
|
/*
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
#include <test/libsolidity/ASTPropertyTest.h>
#include <test/Common.h>
#include <libsolidity/ast/ASTJsonExporter.h>
#include <libsolidity/interface/CompilerStack.h>
#include <liblangutil/Common.h>
#include <liblangutil/SourceReferenceFormatter.h>
#include <libsolutil/JSON.h>
#include <boost/algorithm/string.hpp>
#include <boost/throw_exception.hpp>
#include <range/v3/algorithm/find_if.hpp>
#include <range/v3/range/conversion.hpp>
#include <range/v3/view/split.hpp>
#include <queue>
using namespace solidity::util;
using namespace solidity::langutil;
using namespace solidity::frontend;
using namespace solidity::frontend::test;
using namespace solidity;
using namespace std::string_literals;
ASTPropertyTest::ASTPropertyTest(std::string const& _filename):
EVMVersionRestrictedTestCase(_filename)
{
if (!boost::algorithm::ends_with(_filename, ".sol"))
BOOST_THROW_EXCEPTION(std::runtime_error("Not a Solidity file: \"" + _filename + "\"."));
m_source = m_reader.source();
readExpectations();
soltestAssert(m_tests.size() > 0, "No tests specified in " + _filename);
}
std::string ASTPropertyTest::formatExpectations(bool _obtainedResult)
{
std::string expectations;
for (std::string const& testId: m_testOrder)
{
soltestAssert(m_tests.count(testId) > 0);
expectations +=
testId +
": " +
(_obtainedResult ? m_tests[testId].obtainedValue : m_tests[testId].expectedValue)
+ "\n";
}
return expectations;
}
std::vector<StringPair> ASTPropertyTest::readKeyValuePairs(std::string const& _input)
{
std::vector<StringPair> result;
for (std::string line: _input | ranges::views::split('\n') | ranges::to<std::vector<std::string>>)
{
boost::trim(line);
if (line.empty())
continue;
soltestAssert(
ranges::all_of(line, [](char c) { return isprint(c); }),
"Non-printable character(s) found in property test: " + line
);
auto colonPosition = line.find_first_of(':');
soltestAssert(colonPosition != std::string::npos, "Property test is missing a colon: " + line);
StringPair pair{
boost::trim_copy(line.substr(0, colonPosition)),
boost::trim_copy(line.substr(colonPosition + 1))
};
soltestAssert(!std::get<0>(pair).empty() != false, "Empty key in property test: " + line);
soltestAssert(!std::get<1>(pair).empty() != false, "Empty value in property test: " + line);
result.push_back(pair);
}
return result;
}
void ASTPropertyTest::readExpectations()
{
for (auto const& [testId, testExpectation]: readKeyValuePairs(m_reader.simpleExpectations()))
{
soltestAssert(m_tests.count(testId) == 0, "More than one expectation for test \"" + testId + "\"");
m_tests.emplace(testId, Test{"", testExpectation, ""});
m_testOrder.push_back(testId);
}
m_expectation = formatExpectations(false /* _obtainedResult */);
}
void ASTPropertyTest::extractTestsFromAST(Json const& _astJson)
{
std::queue<Json> nodesToVisit;
nodesToVisit.push(_astJson);
while (!nodesToVisit.empty())
{
Json& node = nodesToVisit.front();
if (node.is_array())
for (auto&& member: node)
nodesToVisit.push(member);
else if (node.is_object())
for (auto const& [memberName, value]: node.items())
{
if (memberName != "documentation")
{
nodesToVisit.push(node[memberName]);
continue;
}
std::string nodeDocstring = value.is_object() ?
value["text"].get<std::string>() : value.get<std::string>();
soltestAssert(!nodeDocstring.empty());
std::vector<StringPair> pairs = readKeyValuePairs(nodeDocstring);
if (pairs.empty())
continue;
for (auto const& [testId, testedProperty]: pairs)
{
soltestAssert(
m_tests.count(testId) > 0,
"Test \"" + testId + "\" does not have a corresponding expected value."
);
soltestAssert(
m_tests[testId].property.empty(),
"Test \"" + testId + "\" was already defined before."
);
m_tests[testId].property = testedProperty;
soltestAssert(node.contains("nodeType"));
std::optional<Json> propertyNode = jsonValueByPath(node, testedProperty);
soltestAssert(
propertyNode.has_value(),
node["nodeType"].get<std::string>() + " node does not have a property named \""s + testedProperty + "\""
);
soltestAssert(
!propertyNode->is_object() && !propertyNode->is_array(),
"Property \"" + testedProperty + "\" is an object or an array."
);
if (propertyNode->is_string())
m_tests[testId].obtainedValue = propertyNode->get<std::string>();
else if (propertyNode->is_boolean())
m_tests[testId].obtainedValue = fmt::format("{}", propertyNode->get<bool>());
else
soltestAssert(false);
}
}
nodesToVisit.pop();
}
auto firstTestWithoutProperty = ranges::find_if(
m_tests,
[&](auto const& _testCase) { return _testCase.second.property.empty(); }
);
soltestAssert(
firstTestWithoutProperty == ranges::end(m_tests),
"AST property not defined for test \"" + firstTestWithoutProperty->first + "\""
);
m_obtainedResult = formatExpectations(true /* _obtainedResult */);
}
TestCase::TestResult ASTPropertyTest::run(std::ostream& _stream, std::string const& _linePrefix, bool const _formatted)
{
CompilerStack compiler;
compiler.setSources({{
"A",
"pragma solidity >=0.0;\n// SPDX-License-Identifier: GPL-3.0\n" + m_source
}});
compiler.setEVMVersion(solidity::test::CommonOptions::get().evmVersion());
compiler.setOptimiserSettings(solidity::test::CommonOptions::get().optimize);
if (!compiler.parseAndAnalyze())
BOOST_THROW_EXCEPTION(std::runtime_error(
"Parsing contract failed" +
SourceReferenceFormatter::formatErrorInformation(compiler.errors(), compiler, _formatted)
));
Json astJson = ASTJsonExporter(compiler.state()).toJson(compiler.ast("A"));
soltestAssert(!astJson.empty());
extractTestsFromAST(astJson);
return checkResult(_stream, _linePrefix, _formatted);
}
| 6,563
|
C++
|
.cpp
| 174
| 34.494253
| 119
| 0.719434
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
2,999
|
Metadata.cpp
|
ethereum_solidity/test/libsolidity/Metadata.cpp
|
/*
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/>.
*/
/**
* @date 2017
* Unit tests for the metadata output.
*/
#include <test/Metadata.h>
#include <test/Common.h>
#include <libsolidity/interface/CompilerStack.h>
#include <libsolidity/interface/Version.h>
#include <libsolutil/SwarmHash.h>
#include <libsolutil/IpfsHash.h>
#include <libsolutil/JSON.h>
#include <boost/test/unit_test.hpp>
namespace solidity::frontend::test
{
namespace
{
std::map<std::string, std::string> requireParsedCBORMetadata(bytes const& _bytecode, CompilerStack::MetadataFormat _metadataFormat)
{
bytes cborMetadata = solidity::test::onlyMetadata(_bytecode);
if (_metadataFormat != CompilerStack::MetadataFormat::NoMetadata)
{
BOOST_REQUIRE(!cborMetadata.empty());
std::optional<std::map<std::string, std::string>> tmp = solidity::test::parseCBORMetadata(cborMetadata);
BOOST_REQUIRE(tmp);
return *tmp;
}
BOOST_REQUIRE(cborMetadata.empty());
return {};
}
std::optional<std::string> compileAndCheckLicenseMetadata(std::string const& _contractName, char const* _sourceCode)
{
CompilerStack compilerStack;
compilerStack.setSources({{"A.sol", _sourceCode}});
BOOST_REQUIRE_MESSAGE(compilerStack.compile(), "Compiling contract failed");
std::string const& serialisedMetadata = compilerStack.metadata(_contractName);
Json metadata;
BOOST_REQUIRE(util::jsonParseStrict(serialisedMetadata, metadata));
BOOST_CHECK(solidity::test::isValidMetadata(metadata));
BOOST_CHECK_EQUAL(metadata["sources"].size(), 1);
BOOST_REQUIRE(metadata["sources"].contains("A.sol"));
if (metadata["sources"]["A.sol"].contains("license"))
{
BOOST_REQUIRE(metadata["sources"]["A.sol"]["license"].is_string());
return metadata["sources"]["A.sol"]["license"].get<std::string>();
}
else
return std::nullopt;
}
}
BOOST_AUTO_TEST_SUITE(Metadata)
BOOST_AUTO_TEST_CASE(metadata_stamp)
{
// Check that the metadata stamp is at the end of the runtime bytecode.
char const* sourceCode = R"(
pragma solidity >=0.0;
pragma experimental __testOnlyAnalysis;
contract test {
function g(function(uint) external returns (uint) x) public {}
}
)";
for (auto metadataFormat: std::set<CompilerStack::MetadataFormat>{
CompilerStack::MetadataFormat::NoMetadata,
CompilerStack::MetadataFormat::WithReleaseVersionTag,
CompilerStack::MetadataFormat::WithPrereleaseVersionTag
})
for (auto metadataHash: std::set<CompilerStack::MetadataHash>{
CompilerStack::MetadataHash::IPFS,
CompilerStack::MetadataHash::Bzzr1,
CompilerStack::MetadataHash::None
})
{
CompilerStack compilerStack;
compilerStack.setMetadataFormat(metadataFormat);
compilerStack.setSources({{"", sourceCode}});
compilerStack.setEVMVersion(solidity::test::CommonOptions::get().evmVersion());
compilerStack.setOptimiserSettings(solidity::test::CommonOptions::get().optimize);
compilerStack.setMetadataHash(metadataHash);
BOOST_REQUIRE_MESSAGE(compilerStack.compile(), "Compiling contract failed");
bytes const& bytecode = compilerStack.runtimeObject("test").bytecode;
std::string const& metadata = compilerStack.metadata("test");
BOOST_CHECK(solidity::test::isValidMetadata(metadata));
auto const cborMetadata = requireParsedCBORMetadata(bytecode, metadataFormat);
if (metadataHash == CompilerStack::MetadataHash::None)
BOOST_CHECK(cborMetadata.size() == (metadataFormat == CompilerStack::MetadataFormat::NoMetadata ? 0 : 1));
else
{
bytes hash;
std::string hashMethod;
if (metadataHash == CompilerStack::MetadataHash::IPFS)
{
hash = util::ipfsHash(metadata);
BOOST_REQUIRE(hash.size() == 34);
hashMethod = "ipfs";
}
else
{
hash = util::bzzr1Hash(metadata).asBytes();
BOOST_REQUIRE(hash.size() == 32);
hashMethod = "bzzr1";
}
if (metadataFormat != CompilerStack::MetadataFormat::NoMetadata)
{
BOOST_CHECK(cborMetadata.size() == 2);
BOOST_CHECK(cborMetadata.count(hashMethod) == 1);
BOOST_CHECK(cborMetadata.at(hashMethod) == util::toHex(hash));
}
}
if (metadataFormat == CompilerStack::MetadataFormat::NoMetadata)
BOOST_CHECK(cborMetadata.count("solc") == 0);
else
{
BOOST_CHECK(cborMetadata.count("solc") == 1);
if (metadataFormat == CompilerStack::MetadataFormat::WithReleaseVersionTag)
BOOST_CHECK(cborMetadata.at("solc") == util::toHex(VersionCompactBytes));
else
BOOST_CHECK(cborMetadata.at("solc") == VersionStringStrict);
}
}
}
BOOST_AUTO_TEST_CASE(metadata_stamp_experimental)
{
// Check that the metadata stamp is at the end of the runtime bytecode.
char const* sourceCode = R"(
pragma solidity >=0.0;
pragma experimental __test;
contract test {
function g(function(uint) external returns (uint) x) public {}
}
)";
for (auto metadataFormat: std::set<CompilerStack::MetadataFormat>{
CompilerStack::MetadataFormat::NoMetadata,
CompilerStack::MetadataFormat::WithReleaseVersionTag,
CompilerStack::MetadataFormat::WithPrereleaseVersionTag
})
for (auto metadataHash: std::set<CompilerStack::MetadataHash>{
CompilerStack::MetadataHash::IPFS,
CompilerStack::MetadataHash::Bzzr1,
CompilerStack::MetadataHash::None
})
{
CompilerStack compilerStack;
compilerStack.setMetadataFormat(metadataFormat);
compilerStack.setSources({{"", sourceCode}});
compilerStack.setEVMVersion(solidity::test::CommonOptions::get().evmVersion());
compilerStack.setOptimiserSettings(solidity::test::CommonOptions::get().optimize);
compilerStack.setMetadataHash(metadataHash);
BOOST_REQUIRE_MESSAGE(compilerStack.compile(), "Compiling contract failed");
bytes const& bytecode = compilerStack.runtimeObject("test").bytecode;
std::string const& metadata = compilerStack.metadata("test");
BOOST_CHECK(solidity::test::isValidMetadata(metadata));
auto const cborMetadata = requireParsedCBORMetadata(bytecode, metadataFormat);
if (metadataHash == CompilerStack::MetadataHash::None)
BOOST_CHECK(cborMetadata.size() == (metadataFormat == CompilerStack::MetadataFormat::NoMetadata ? 0 : 2));
else
{
bytes hash;
std::string hashMethod;
if (metadataHash == CompilerStack::MetadataHash::IPFS)
{
hash = util::ipfsHash(metadata);
BOOST_REQUIRE(hash.size() == 34);
hashMethod = "ipfs";
}
else
{
hash = util::bzzr1Hash(metadata).asBytes();
BOOST_REQUIRE(hash.size() == 32);
hashMethod = "bzzr1";
}
if (metadataFormat != CompilerStack::MetadataFormat::NoMetadata)
{
BOOST_CHECK(cborMetadata.size() == 3);
BOOST_CHECK(cborMetadata.count(hashMethod) == 1);
BOOST_CHECK(cborMetadata.at(hashMethod) == util::toHex(hash));
}
}
if (metadataFormat == CompilerStack::MetadataFormat::NoMetadata)
BOOST_CHECK(cborMetadata.count("solc") == 0);
else
{
BOOST_CHECK(cborMetadata.count("solc") == 1);
if (metadataFormat == CompilerStack::MetadataFormat::WithReleaseVersionTag)
BOOST_CHECK(cborMetadata.at("solc") == util::toHex(VersionCompactBytes));
else
BOOST_CHECK(cborMetadata.at("solc") == VersionStringStrict);
BOOST_CHECK(cborMetadata.count("experimental") == 1);
BOOST_CHECK(cborMetadata.at("experimental") == "true");
}
}
}
BOOST_AUTO_TEST_CASE(metadata_relevant_sources)
{
CompilerStack compilerStack;
char const* sourceCodeA = R"(
pragma solidity >=0.0;
contract A {
function g(function(uint) external returns (uint) x) public {}
}
)";
char const* sourceCodeB = R"(
pragma solidity >=0.0;
contract B {
function g(function(uint) external returns (uint) x) public {}
}
)";
compilerStack.setSources({
{"A", sourceCodeA},
{"B", sourceCodeB},
});
compilerStack.setEVMVersion(solidity::test::CommonOptions::get().evmVersion());
compilerStack.setOptimiserSettings(solidity::test::CommonOptions::get().optimize);
BOOST_REQUIRE_MESSAGE(compilerStack.compile(), "Compiling contract failed");
std::string const& serialisedMetadata = compilerStack.metadata("A");
Json metadata;
BOOST_REQUIRE(util::jsonParseStrict(serialisedMetadata, metadata));
BOOST_CHECK(solidity::test::isValidMetadata(metadata));
BOOST_CHECK_EQUAL(metadata["sources"].size(), 1);
BOOST_CHECK(metadata["sources"].contains("A"));
}
BOOST_AUTO_TEST_CASE(metadata_relevant_sources_imports)
{
CompilerStack compilerStack;
char const* sourceCodeA = R"(
pragma solidity >=0.0;
contract A {
function g(function(uint) external returns (uint) x) public virtual {}
}
)";
char const* sourceCodeB = R"(
pragma solidity >=0.0;
import "./A";
contract B is A {
function g(function(uint) external returns (uint) x) public virtual override {}
}
)";
char const* sourceCodeC = R"(
pragma solidity >=0.0;
import "./B";
contract C is B {
function g(function(uint) external returns (uint) x) public override {}
}
)";
compilerStack.setSources({
{"A", sourceCodeA},
{"B", sourceCodeB},
{"C", sourceCodeC}
});
compilerStack.setEVMVersion(solidity::test::CommonOptions::get().evmVersion());
compilerStack.setOptimiserSettings(solidity::test::CommonOptions::get().optimize);
BOOST_REQUIRE_MESSAGE(compilerStack.compile(), "Compiling contract failed");
std::string const& serialisedMetadata = compilerStack.metadata("C");
Json metadata;
BOOST_REQUIRE(util::jsonParseStrict(serialisedMetadata, metadata));
BOOST_CHECK(solidity::test::isValidMetadata(metadata));
BOOST_CHECK_EQUAL(metadata["sources"].size(), 3);
BOOST_CHECK(metadata["sources"].contains("A"));
BOOST_CHECK(metadata["sources"].contains("B"));
BOOST_CHECK(metadata["sources"].contains("C"));
}
BOOST_AUTO_TEST_CASE(metadata_useLiteralContent)
{
// Check that the metadata contains "useLiteralContent"
char const* sourceCode = R"(
pragma solidity >=0.0;
contract test {
}
)";
auto check = [](char const* _src, bool _literal)
{
CompilerStack compilerStack;
compilerStack.setSources({{"", _src}});
compilerStack.setEVMVersion(solidity::test::CommonOptions::get().evmVersion());
compilerStack.setOptimiserSettings(solidity::test::CommonOptions::get().optimize);
compilerStack.useMetadataLiteralSources(_literal);
BOOST_REQUIRE_MESSAGE(compilerStack.compile(), "Compiling contract failed");
std::string metadata_str = compilerStack.metadata("test");
Json metadata;
BOOST_REQUIRE(util::jsonParseStrict(metadata_str, metadata));
BOOST_CHECK(solidity::test::isValidMetadata(metadata));
BOOST_CHECK(metadata.contains("settings"));
BOOST_CHECK(metadata["settings"].contains("metadata"));
BOOST_CHECK(metadata["settings"]["metadata"].contains("bytecodeHash"));
if (_literal)
{
BOOST_CHECK(metadata["settings"]["metadata"].contains("useLiteralContent"));
BOOST_CHECK(metadata["settings"]["metadata"]["useLiteralContent"].get<bool>());
}
};
check(sourceCode, true);
check(sourceCode, false);
}
BOOST_AUTO_TEST_CASE(metadata_viair)
{
char const* sourceCode = R"(
pragma solidity >=0.0;
contract test {
}
)";
auto check = [](char const* _src, bool _viaIR)
{
CompilerStack compilerStack;
compilerStack.setSources({{"", _src}});
compilerStack.setEVMVersion(solidity::test::CommonOptions::get().evmVersion());
compilerStack.setOptimiserSettings(solidity::test::CommonOptions::get().optimize);
compilerStack.setViaIR(_viaIR);
BOOST_REQUIRE_MESSAGE(compilerStack.compile(), "Compiling contract failed");
Json metadata;
BOOST_REQUIRE(util::jsonParseStrict(compilerStack.metadata("test"), metadata));
BOOST_CHECK(solidity::test::isValidMetadata(metadata));
BOOST_CHECK(metadata.contains("settings"));
if (_viaIR)
{
BOOST_CHECK(metadata["settings"].contains("viaIR"));
BOOST_CHECK(metadata["settings"]["viaIR"].get<bool>());
}
else
BOOST_CHECK(!metadata["settings"].contains("viaIR"));
BOOST_CHECK(compilerStack.cborMetadata("test") == compilerStack.cborMetadata("test", _viaIR));
BOOST_CHECK(compilerStack.cborMetadata("test") != compilerStack.cborMetadata("test", !_viaIR));
std::map<std::string, std::string> const parsedCBORMetadata = requireParsedCBORMetadata(
compilerStack.runtimeObject("test").bytecode,
CompilerStack::MetadataFormat::WithReleaseVersionTag
);
BOOST_CHECK(parsedCBORMetadata.count("experimental") == 0);
};
check(sourceCode, true);
check(sourceCode, false);
}
BOOST_AUTO_TEST_CASE(metadata_revert_strings)
{
CompilerStack compilerStack;
char const* sourceCodeA = R"(
pragma solidity >=0.0;
contract A {
}
)";
compilerStack.setSources({{"A", sourceCodeA}});
compilerStack.setRevertStringBehaviour(RevertStrings::Strip);
BOOST_REQUIRE_MESSAGE(compilerStack.compile(), "Compiling contract failed");
std::string const& serialisedMetadata = compilerStack.metadata("A");
Json metadata;
BOOST_REQUIRE(util::jsonParseStrict(serialisedMetadata, metadata));
BOOST_CHECK(solidity::test::isValidMetadata(metadata));
BOOST_CHECK_EQUAL(metadata["settings"]["debug"]["revertStrings"], "strip");
}
BOOST_AUTO_TEST_CASE(metadata_optimiser_sequence)
{
char const* sourceCode = R"(
pragma solidity >=0.0;
contract C {
}
)";
std::vector<std::tuple<std::string, std::string>> sequences =
{
// {"<optimizer sequence>", "<optimizer cleanup sequence>"}
{"", ""},
{"", "fDn"},
{"dhfoDgvulfnTUtnIf", "" },
{"dhfoDgvulfnTUtnIf", "fDn"}
};
auto check = [sourceCode](std::string const& _optimizerSequence, std::string const& _optimizerCleanupSequence)
{
OptimiserSettings optimizerSettings = OptimiserSettings::minimal();
optimizerSettings.runYulOptimiser = true;
optimizerSettings.yulOptimiserSteps = _optimizerSequence;
optimizerSettings.yulOptimiserCleanupSteps = _optimizerCleanupSequence;
CompilerStack compilerStack;
compilerStack.setSources({{"", sourceCode}});
compilerStack.setEVMVersion(solidity::test::CommonOptions::get().evmVersion());
compilerStack.setOptimiserSettings(optimizerSettings);
BOOST_REQUIRE_MESSAGE(compilerStack.compile(), "Compiling contract failed");
std::string const& serialisedMetadata = compilerStack.metadata("C");
Json metadata;
BOOST_REQUIRE(util::jsonParseStrict(serialisedMetadata, metadata));
BOOST_CHECK(solidity::test::isValidMetadata(metadata));
BOOST_CHECK(metadata["settings"]["optimizer"].contains("details"));
BOOST_CHECK(metadata["settings"]["optimizer"]["details"].contains("yulDetails"));
BOOST_CHECK(metadata["settings"]["optimizer"]["details"]["yulDetails"].contains("optimizerSteps"));
std::string const metadataOptimizerSteps = metadata["settings"]["optimizer"]["details"]["yulDetails"]["optimizerSteps"].get<std::string>();
std::string const expectedMetadataOptimiserSteps = _optimizerSequence + ":" + _optimizerCleanupSequence;
BOOST_CHECK_EQUAL(metadataOptimizerSteps, expectedMetadataOptimiserSteps);
};
for (auto const& [sequence, cleanupSequence] : sequences)
check(sequence, cleanupSequence);
}
BOOST_AUTO_TEST_CASE(metadata_license_missing)
{
char const* sourceCode = R"(
pragma solidity >=0.0;
contract C {
}
)";
BOOST_CHECK(compileAndCheckLicenseMetadata("C", sourceCode) == std::nullopt);
}
BOOST_AUTO_TEST_CASE(metadata_license_gpl3)
{
// Can't use a raw string here due to the stylechecker.
char const* sourceCode =
"// NOTE: we also add trailing whitespace after the license, to see it is trimmed.\n"
"// SPDX-License-Identifier: GPL-3.0 \n"
"pragma solidity >=0.0;\n"
"contract C {\n"
"}\n";
BOOST_CHECK(compileAndCheckLicenseMetadata("C", sourceCode) == "GPL-3.0");
}
BOOST_AUTO_TEST_CASE(metadata_license_whitespace_before_spdx)
{
char const* sourceCode = R"(
// SPDX-License-Identifier: GPL-3.0
contract C {}
)";
BOOST_CHECK(compileAndCheckLicenseMetadata("C", sourceCode) == "GPL-3.0");
}
BOOST_AUTO_TEST_CASE(metadata_license_whitespace_after_colon)
{
char const* sourceCode = R"(
// SPDX-License-Identifier: GPL-3.0
contract C {}
)";
BOOST_CHECK(compileAndCheckLicenseMetadata("C", sourceCode) == "GPL-3.0");
}
BOOST_AUTO_TEST_CASE(metadata_license_gpl3_or_apache2)
{
char const* sourceCode = R"(
// SPDX-License-Identifier: GPL-3.0 OR Apache-2.0
pragma solidity >=0.0;
contract C {
}
)";
BOOST_CHECK(compileAndCheckLicenseMetadata("C", sourceCode) == "GPL-3.0 OR Apache-2.0");
}
BOOST_AUTO_TEST_CASE(metadata_license_bidi_marks)
{
char const* sourceCode =
"// \xE2\x80\xAE""0.3-LPG :reifitnedI-esneciL-XDPS\xE2\x80\xAC\n"
"// NOTE: The text above is reversed using Unicode directional marks. In raw form it would look like this:\n"
"// <LRO>0.3-LPG :reifitnedI-esneciL-XDPS<PDF>\n"
"contract C {}\n";
BOOST_CHECK(compileAndCheckLicenseMetadata("C", sourceCode) == std::nullopt);
}
BOOST_AUTO_TEST_CASE(metadata_license_bottom)
{
char const* sourceCode = R"(
contract C {}
// SPDX-License-Identifier: GPL-3.0
)";
BOOST_CHECK(compileAndCheckLicenseMetadata("C", sourceCode) == "GPL-3.0");
}
BOOST_AUTO_TEST_CASE(metadata_cr_endings)
{
char const* sourceCode =
"// SPDX-License-Identifier: GPL-3.0\r"
"contract C {}\r";
BOOST_CHECK(compileAndCheckLicenseMetadata("C", sourceCode) == "GPL-3.0");
}
BOOST_AUTO_TEST_CASE(metadata_crlf_endings)
{
char const* sourceCode =
"// SPDX-License-Identifier: GPL-3.0\r\n"
"contract C {}\r\n";
BOOST_CHECK(compileAndCheckLicenseMetadata("C", sourceCode) == "GPL-3.0");
}
BOOST_AUTO_TEST_CASE(metadata_license_in_string)
{
char const* sourceCode = R"(
contract C {
bytes license = "// SPDX-License-Identifier: GPL-3.0";
}
)";
BOOST_CHECK(compileAndCheckLicenseMetadata("C", sourceCode) == std::nullopt);
}
BOOST_AUTO_TEST_CASE(metadata_license_in_contract)
{
char const* sourceCode = R"(
contract C {
// SPDX-License-Identifier: GPL-3.0
}
)";
BOOST_CHECK(compileAndCheckLicenseMetadata("C", sourceCode) == std::nullopt);
}
BOOST_AUTO_TEST_CASE(metadata_license_missing_colon)
{
char const* sourceCode = R"(
// SPDX-License-Identifier GPL-3.0
contract C {}
)";
BOOST_CHECK(compileAndCheckLicenseMetadata("C", sourceCode) == std::nullopt);
}
BOOST_AUTO_TEST_CASE(metadata_license_multiline)
{
char const* sourceCode = R"(
/* SPDX-License-Identifier: GPL-3.0 */
contract C {}
)";
BOOST_CHECK(compileAndCheckLicenseMetadata("C", sourceCode) == "GPL-3.0");
}
BOOST_AUTO_TEST_CASE(metadata_license_natspec)
{
char const* sourceCode = R"(
/// SPDX-License-Identifier: GPL-3.0
contract C {}
)";
BOOST_CHECK(compileAndCheckLicenseMetadata("C", sourceCode) == "GPL-3.0");
}
BOOST_AUTO_TEST_CASE(metadata_license_natspec_multiline)
{
char const* sourceCode = R"(
/** SPDX-License-Identifier: GPL-3.0 */
contract C {}
)";
BOOST_CHECK(compileAndCheckLicenseMetadata("C", sourceCode) == "GPL-3.0");
}
BOOST_AUTO_TEST_CASE(metadata_license_no_whitespace_multiline)
{
char const* sourceCode = R"(
/*SPDX-License-Identifier:GPL-3.0*/
contract C {}
)";
BOOST_CHECK(compileAndCheckLicenseMetadata("C", sourceCode) == "GPL-3.0");
}
BOOST_AUTO_TEST_CASE(metadata_license_nonempty_line)
{
char const* sourceCode = R"(
pragma solidity >= 0.0; // SPDX-License-Identifier: GPL-3.0
contract C {}
)";
BOOST_CHECK(compileAndCheckLicenseMetadata("C", sourceCode) == "GPL-3.0");
}
BOOST_AUTO_TEST_CASE(metadata_license_no_whitespace)
{
char const* sourceCode = R"(
//SPDX-License-Identifier:GPL-3.0
contract C {}
)";
BOOST_CHECK(compileAndCheckLicenseMetadata("C", sourceCode) == "GPL-3.0");
}
BOOST_AUTO_TEST_SUITE_END()
}
| 19,989
|
C++
|
.cpp
| 551
| 33.46824
| 141
| 0.74072
|
ethereum/solidity
| 23,062
| 5,715
| 501
|
GPL-3.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.