LibCore: Don't leak proto-Resources when loading non-existent paths

The construct `adopt_ref(*new Obj(TRY(get_resource())))` is another
manifestation of a classic anti-pattern. In old C++, you would leak the
object's memory if the argument threw an exception, or if a member
initializer threw an exception. In our case, we leak if the MappedFile
returns an Error. This is pretty concerning, and we should avoid this
pattern at all costs, and try to use the "safer" helpers whenever
possible.
This commit is contained in:
Andrew Kaster 2023-12-13 12:10:40 -07:00 committed by Tim Flynn
parent 771467f92f
commit d253beb2f7
Notes: sideshowbarker 2024-07-17 09:48:50 +09:00

View file

@ -50,9 +50,11 @@ ErrorOr<NonnullRefPtr<Resource>> ResourceImplementation::load_from_uri(StringVie
if (uri.starts_with(file_scheme)) {
auto path = uri.substring_view(file_scheme.length());
auto utf8_path = TRY(String::from_utf8(path));
if (is_directory(path))
return adopt_ref(*new Resource(TRY(String::from_utf8(path)), Resource::Scheme::File, Resource::DirectoryTag {}));
return adopt_ref(*new Resource(TRY(String::from_utf8(path)), Resource::Scheme::File, TRY(MappedFile::map(path))));
return adopt_ref(*new Resource(utf8_path, Resource::Scheme::File, Resource::DirectoryTag {}));
auto mapped_file = TRY(MappedFile::map(path));
return adopt_ref(*new Resource(utf8_path, Resource::Scheme::File, move(mapped_file)));
}
dbgln("ResourceImplementation: Unknown scheme for {}", uri);