diff --git a/src/Configuration/Argparse.cpp b/src/Configuration/Argparse.cpp index 96e7f40..cc80939 100644 --- a/src/Configuration/Argparse.cpp +++ b/src/Configuration/Argparse.cpp @@ -115,11 +115,14 @@ Parser& Parser::option_default(std::string_view lng, std::string& out, std::string_view default_value) { - out = std::string{default_value}; + // Copy first: default_value may alias out (e.g. option_default(..., x, x)), + // and assigning to out would free the buffer the view points into. + const std::string default_copy{default_value}; + out = default_copy; options_.push_back(OptionEntry{.lng = std::string{lng}, .sht = std::string{sht}, .desc = std::string{desc}, - .def = std::string{default_value}, + .def = default_copy, .out_str = &out}); return *this; } @@ -145,11 +148,13 @@ Parser& Parser::option_default_checked(std::string_view lng, std::string_view default_value, std::vector allowed) { - out = std::string{default_value}; + // See option_default: default_value may alias out. + const std::string default_copy{default_value}; + out = default_copy; options_.push_back(OptionEntry{.lng = std::string{lng}, .sht = std::string{sht}, .desc = std::string{desc}, - .def = std::string{default_value}, + .def = default_copy, .out_str = &out, .allowed = std::move(allowed)}); return *this; diff --git a/tests/standalone/Configuration/Argparse.cpp b/tests/standalone/Configuration/Argparse.cpp index cfaf142..ea2b277 100644 --- a/tests/standalone/Configuration/Argparse.cpp +++ b/tests/standalone/Configuration/Argparse.cpp @@ -120,6 +120,32 @@ Void::Testing::Test argparse_option_default_overridden() Void::Testing::expect_eq(out, std::string{"xml"}); } +Void::Testing::Test argparse_option_default_aliasing_out_is_safe() +{ + // default_value aliases out: the old code assigned to out before reading + // the view, a use-after-free when the string exceeded the SSO buffer. + std::string out = "a default longer than the small string buffer"; + Parser p{"test"}; + p.option_default("--build-dir", "-B", "build directory", out, out); + const Args a{{"test"}}; + Void::Testing::expect(p.parse(a.argc, a.argv).has_value()); + Void::Testing::expect_eq(out, + std::string{"a default longer than the small string buffer"}); + Void::Testing::expect(p.help().find( + "a default longer than the small string buffer") != std::string::npos); +} + +Void::Testing::Test argparse_option_default_checked_aliasing_out_is_safe() +{ + std::string out = "default-mode-value-longer-than-ssbo"; + Parser p{"test"}; + p.option_default_checked("--mode", "-m", "mode", out, out, + {"default-mode-value-longer-than-ssbo", "other"}); + const Args a{{"test", "--mode=other"}}; + Void::Testing::expect(p.parse(a.argc, a.argv).has_value()); + Void::Testing::expect_eq(out, std::string{"other"}); +} + Void::Testing::Test argparse_option_missing_value_is_error() { std::optional out;