Driver.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * Copyright (c) 2022, Stephan Unverwerth <s.unverwerth@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/HashMap.h>
  7. #include <AK/String.h>
  8. #include <AK/WeakPtr.h>
  9. #ifdef __serenity__
  10. # include <LibDl/dlfcn.h>
  11. #else
  12. # include <dlfcn.h>
  13. #endif
  14. #include <LibGPU/Driver.h>
  15. namespace GPU {
  16. // FIXME: Think of a better way to configure these paths. Maybe use ConfigServer?
  17. static HashMap<String, String> const s_driver_path_map
  18. {
  19. #if defined(__serenity__)
  20. { "softgpu", "libsoftgpu.so" },
  21. #elif defined(__APPLE__)
  22. { "softgpu", "./liblagom-softgpu.dylib" },
  23. #else
  24. { "softgpu", "./liblagom-softgpu.so" },
  25. #endif
  26. };
  27. static HashMap<String, WeakPtr<Driver>> s_loaded_drivers;
  28. ErrorOr<NonnullRefPtr<Driver>> Driver::try_create(StringView driver_name)
  29. {
  30. // Check if the library for this driver is already loaded
  31. auto already_loaded_driver = s_loaded_drivers.find(driver_name);
  32. if (already_loaded_driver != s_loaded_drivers.end() && !already_loaded_driver->value.is_null())
  33. return *already_loaded_driver->value;
  34. // Nope, we need to load the library
  35. auto it = s_driver_path_map.find(driver_name);
  36. if (it == s_driver_path_map.end())
  37. return Error::from_string_literal("The requested GPU driver was not found in the list of allowed driver libraries");
  38. auto lib = dlopen(it->value.characters(), RTLD_NOW);
  39. if (!lib)
  40. return Error::from_string_literal("The library for the requested GPU driver could not be opened");
  41. auto serenity_gpu_create_device = reinterpret_cast<serenity_gpu_create_device_t>(dlsym(lib, "serenity_gpu_create_device"));
  42. if (!serenity_gpu_create_device) {
  43. dlclose(lib);
  44. return Error::from_string_literal("The library for the requested GPU driver does not contain serenity_gpu_create_device()");
  45. }
  46. auto driver = adopt_ref(*new Driver(lib, serenity_gpu_create_device));
  47. s_loaded_drivers.set(driver_name, driver->make_weak_ptr());
  48. return driver;
  49. }
  50. Driver::~Driver()
  51. {
  52. dlclose(m_dlopen_result);
  53. }
  54. ErrorOr<NonnullOwnPtr<Device>> Driver::try_create_device(Gfx::IntSize size)
  55. {
  56. auto device_or_null = m_serenity_gpu_create_device(size);
  57. if (!device_or_null)
  58. return Error::from_string_literal("Could not create GPU device");
  59. return adopt_own(*device_or_null);
  60. }
  61. }