1 /* vim: se cin sw=2 ts=2 et : */
2 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*-
3  *
4  * This Source Code Form is subject to the terms of the Mozilla Public
5  * License, v. 2.0. If a copy of the MPL was not distributed with this
6  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 
8 #include "mozilla/ArrayUtils.h"
9 
10 #include "GfxInfoBase.h"
11 
12 #include <mutex>  // std::call_once
13 
14 #include "GfxDriverInfo.h"
15 #include "js/Array.h"  // JS::GetArrayLength, JS::NewArrayObject
16 #include "nsCOMPtr.h"
17 #include "nsCOMArray.h"
18 #include "nsString.h"
19 #include "nsUnicharUtils.h"
20 #include "nsVersionComparator.h"
21 #include "mozilla/Services.h"
22 #include "mozilla/Observer.h"
23 #include "nsIObserver.h"
24 #include "nsIObserverService.h"
25 #include "nsIScreenManager.h"
26 #include "nsTArray.h"
27 #include "nsXULAppAPI.h"
28 #include "nsIXULAppInfo.h"
29 #include "mozilla/ClearOnShutdown.h"
30 #include "mozilla/Preferences.h"
31 #include "mozilla/StaticPrefs_gfx.h"
32 #include "mozilla/gfx/2D.h"
33 #include "mozilla/gfx/GPUProcessManager.h"
34 #include "mozilla/gfx/Logging.h"
35 #include "mozilla/gfx/gfxVars.h"
36 #include "mozilla/layers/PaintThread.h"
37 
38 #include "gfxPlatform.h"
39 #include "gfxConfig.h"
40 #include "DriverCrashGuard.h"
41 
42 using namespace mozilla::widget;
43 using namespace mozilla;
44 using mozilla::MutexAutoLock;
45 
46 nsTArray<GfxDriverInfo>* GfxInfoBase::sDriverInfo;
47 StaticAutoPtr<nsTArray<gfx::GfxInfoFeatureStatus>> GfxInfoBase::sFeatureStatus;
48 bool GfxInfoBase::sDriverInfoObserverInitialized;
49 bool GfxInfoBase::sShutdownOccurred;
50 
51 // Call this when setting sFeatureStatus to a non-null pointer to
52 // ensure destruction even if the GfxInfo component is never instantiated.
InitFeatureStatus(nsTArray<gfx::GfxInfoFeatureStatus> * aPtr)53 static void InitFeatureStatus(nsTArray<gfx::GfxInfoFeatureStatus>* aPtr) {
54   static std::once_flag sOnce;
55   std::call_once(sOnce, [] { ClearOnShutdown(&GfxInfoBase::sFeatureStatus); });
56   GfxInfoBase::sFeatureStatus = aPtr;
57 }
58 
59 // Observes for shutdown so that the child GfxDriverInfo list is freed.
60 class ShutdownObserver : public nsIObserver {
61   virtual ~ShutdownObserver() = default;
62 
63  public:
64   ShutdownObserver() = default;
65 
66   NS_DECL_ISUPPORTS
67 
Observe(nsISupports * subject,const char * aTopic,const char16_t * aData)68   NS_IMETHOD Observe(nsISupports* subject, const char* aTopic,
69                      const char16_t* aData) override {
70     MOZ_ASSERT(strcmp(aTopic, NS_XPCOM_SHUTDOWN_OBSERVER_ID) == 0);
71 
72     delete GfxInfoBase::sDriverInfo;
73     GfxInfoBase::sDriverInfo = nullptr;
74 
75     for (auto& deviceFamily : GfxDriverInfo::sDeviceFamilies) {
76       delete deviceFamily;
77       deviceFamily = nullptr;
78     }
79 
80     for (auto& desktop : GfxDriverInfo::sDesktopEnvironment) {
81       delete desktop;
82       desktop = nullptr;
83     }
84 
85     for (auto& windowProtocol : GfxDriverInfo::sWindowProtocol) {
86       delete windowProtocol;
87       windowProtocol = nullptr;
88     }
89 
90     for (auto& deviceVendor : GfxDriverInfo::sDeviceVendors) {
91       delete deviceVendor;
92       deviceVendor = nullptr;
93     }
94 
95     for (auto& driverVendor : GfxDriverInfo::sDriverVendors) {
96       delete driverVendor;
97       driverVendor = nullptr;
98     }
99 
100     GfxInfoBase::sShutdownOccurred = true;
101 
102     return NS_OK;
103   }
104 };
105 
NS_IMPL_ISUPPORTS(ShutdownObserver,nsIObserver)106 NS_IMPL_ISUPPORTS(ShutdownObserver, nsIObserver)
107 
108 static void InitGfxDriverInfoShutdownObserver() {
109   if (GfxInfoBase::sDriverInfoObserverInitialized) return;
110 
111   GfxInfoBase::sDriverInfoObserverInitialized = true;
112 
113   nsCOMPtr<nsIObserverService> observerService = services::GetObserverService();
114   if (!observerService) {
115     NS_WARNING("Could not get observer service!");
116     return;
117   }
118 
119   ShutdownObserver* obs = new ShutdownObserver();
120   observerService->AddObserver(obs, NS_XPCOM_SHUTDOWN_OBSERVER_ID, false);
121 }
122 
123 using namespace mozilla::widget;
124 using namespace mozilla::gfx;
125 using namespace mozilla;
126 
NS_IMPL_ISUPPORTS(GfxInfoBase,nsIGfxInfo,nsIObserver,nsISupportsWeakReference) const127 NS_IMPL_ISUPPORTS(GfxInfoBase, nsIGfxInfo, nsIObserver,
128                   nsISupportsWeakReference)
129 
130 #define BLOCKLIST_PREF_BRANCH "gfx.blacklist."
131 #define SUGGESTED_VERSION_PREF BLOCKLIST_PREF_BRANCH "suggested-driver-version"
132 
133 static const char* GetPrefNameForFeature(int32_t aFeature) {
134   const char* name = nullptr;
135   switch (aFeature) {
136     case nsIGfxInfo::FEATURE_DIRECT2D:
137       name = BLOCKLIST_PREF_BRANCH "direct2d";
138       break;
139     case nsIGfxInfo::FEATURE_DIRECT3D_9_LAYERS:
140       name = BLOCKLIST_PREF_BRANCH "layers.direct3d9";
141       break;
142     case nsIGfxInfo::FEATURE_DIRECT3D_10_LAYERS:
143       name = BLOCKLIST_PREF_BRANCH "layers.direct3d10";
144       break;
145     case nsIGfxInfo::FEATURE_DIRECT3D_10_1_LAYERS:
146       name = BLOCKLIST_PREF_BRANCH "layers.direct3d10-1";
147       break;
148     case nsIGfxInfo::FEATURE_DIRECT3D_11_LAYERS:
149       name = BLOCKLIST_PREF_BRANCH "layers.direct3d11";
150       break;
151     case nsIGfxInfo::FEATURE_DIRECT3D_11_ANGLE:
152       name = BLOCKLIST_PREF_BRANCH "direct3d11angle";
153       break;
154     case nsIGfxInfo::FEATURE_HARDWARE_VIDEO_DECODING:
155       name = BLOCKLIST_PREF_BRANCH "hardwarevideodecoding";
156       break;
157     case nsIGfxInfo::FEATURE_OPENGL_LAYERS:
158       name = BLOCKLIST_PREF_BRANCH "layers.opengl";
159       break;
160     case nsIGfxInfo::FEATURE_WEBGL_OPENGL:
161       name = BLOCKLIST_PREF_BRANCH "webgl.opengl";
162       break;
163     case nsIGfxInfo::FEATURE_WEBGL_ANGLE:
164       name = BLOCKLIST_PREF_BRANCH "webgl.angle";
165       break;
166     case nsIGfxInfo::UNUSED_FEATURE_WEBGL_MSAA:
167       name = BLOCKLIST_PREF_BRANCH "webgl.msaa";
168       break;
169     case nsIGfxInfo::FEATURE_STAGEFRIGHT:
170       name = BLOCKLIST_PREF_BRANCH "stagefright";
171       break;
172     case nsIGfxInfo::FEATURE_WEBRTC_HW_ACCELERATION_H264:
173       name = BLOCKLIST_PREF_BRANCH "webrtc.hw.acceleration.h264";
174       break;
175     case nsIGfxInfo::FEATURE_WEBRTC_HW_ACCELERATION_ENCODE:
176       name = BLOCKLIST_PREF_BRANCH "webrtc.hw.acceleration.encode";
177       break;
178     case nsIGfxInfo::FEATURE_WEBRTC_HW_ACCELERATION_DECODE:
179       name = BLOCKLIST_PREF_BRANCH "webrtc.hw.acceleration.decode";
180       break;
181     case nsIGfxInfo::FEATURE_CANVAS2D_ACCELERATION:
182       name = BLOCKLIST_PREF_BRANCH "canvas2d.acceleration";
183       break;
184     case nsIGfxInfo::FEATURE_DX_INTEROP2:
185       name = BLOCKLIST_PREF_BRANCH "dx.interop2";
186       break;
187     case nsIGfxInfo::FEATURE_GPU_PROCESS:
188       name = BLOCKLIST_PREF_BRANCH "gpu.process";
189       break;
190     case nsIGfxInfo::FEATURE_WEBGL2:
191       name = BLOCKLIST_PREF_BRANCH "webgl2";
192       break;
193     case nsIGfxInfo::FEATURE_D3D11_KEYED_MUTEX:
194       name = BLOCKLIST_PREF_BRANCH "d3d11.keyed.mutex";
195       break;
196     case nsIGfxInfo::FEATURE_WEBRENDER:
197       name = BLOCKLIST_PREF_BRANCH "webrender";
198       break;
199     case nsIGfxInfo::FEATURE_WEBRENDER_COMPOSITOR:
200       name = BLOCKLIST_PREF_BRANCH "webrender.compositor";
201       break;
202     case nsIGfxInfo::FEATURE_DX_NV12:
203       name = BLOCKLIST_PREF_BRANCH "dx.nv12";
204       break;
205     case nsIGfxInfo::FEATURE_DX_P010:
206       name = BLOCKLIST_PREF_BRANCH "dx.p010";
207       break;
208     case nsIGfxInfo::FEATURE_DX_P016:
209       name = BLOCKLIST_PREF_BRANCH "dx.p016";
210       break;
211     case nsIGfxInfo::FEATURE_VP8_HW_DECODE:
212     case nsIGfxInfo::FEATURE_VP9_HW_DECODE:
213       // We don't provide prefs for these features as these are
214       // not handling downloadable blocklist.
215       break;
216     case nsIGfxInfo::FEATURE_GL_SWIZZLE:
217       name = BLOCKLIST_PREF_BRANCH "gl.swizzle";
218       break;
219     case nsIGfxInfo::FEATURE_WEBRENDER_SCISSORED_CACHE_CLEARS:
220       name = BLOCKLIST_PREF_BRANCH "webrender.scissored_cache_clears";
221       break;
222     case nsIGfxInfo::FEATURE_ALLOW_WEBGL_OUT_OF_PROCESS:
223       name = BLOCKLIST_PREF_BRANCH "webgl.allow-oop";
224       break;
225     case nsIGfxInfo::FEATURE_THREADSAFE_GL:
226       name = BLOCKLIST_PREF_BRANCH "gl.threadsafe";
227       break;
228     case nsIGfxInfo::FEATURE_WEBRENDER_SOFTWARE:
229       name = BLOCKLIST_PREF_BRANCH "webrender.software";
230       break;
231     case nsIGfxInfo::FEATURE_WEBRENDER_OPTIMIZED_SHADERS:
232       name = BLOCKLIST_PREF_BRANCH "webrender.optimized-shaders";
233       break;
234     case nsIGfxInfo::FEATURE_X11_EGL:
235       name = BLOCKLIST_PREF_BRANCH "x11.egl";
236       break;
237     case nsIGfxInfo::FEATURE_DMABUF:
238       name = BLOCKLIST_PREF_BRANCH "dmabuf";
239       break;
240     case nsIGfxInfo::FEATURE_WEBRENDER_SHADER_CACHE:
241       name = BLOCKLIST_PREF_BRANCH "webrender.program-binary-disk";
242       break;
243     default:
244       MOZ_ASSERT_UNREACHABLE("Unexpected nsIGfxInfo feature?!");
245       break;
246   }
247 
248   return name;
249 }
250 
251 // Returns the value of the pref for the relevant feature in aValue.
252 // If the pref doesn't exist, aValue is not touched, and returns false.
GetPrefValueForFeature(int32_t aFeature,int32_t & aValue,nsACString & aFailureId)253 static bool GetPrefValueForFeature(int32_t aFeature, int32_t& aValue,
254                                    nsACString& aFailureId) {
255   const char* prefname = GetPrefNameForFeature(aFeature);
256   if (!prefname) return false;
257 
258   aValue = nsIGfxInfo::FEATURE_STATUS_UNKNOWN;
259   if (!NS_SUCCEEDED(Preferences::GetInt(prefname, &aValue))) {
260     return false;
261   }
262 
263   nsCString failureprefname(prefname);
264   failureprefname += ".failureid";
265   nsAutoCString failureValue;
266   nsresult rv = Preferences::GetCString(failureprefname.get(), failureValue);
267   if (NS_SUCCEEDED(rv)) {
268     aFailureId = failureValue.get();
269   } else {
270     aFailureId = "FEATURE_FAILURE_BLOCKLIST_PREF";
271   }
272 
273   return true;
274 }
275 
SetPrefValueForFeature(int32_t aFeature,int32_t aValue,const nsACString & aFailureId)276 static void SetPrefValueForFeature(int32_t aFeature, int32_t aValue,
277                                    const nsACString& aFailureId) {
278   const char* prefname = GetPrefNameForFeature(aFeature);
279   if (!prefname) return;
280   if (XRE_IsParentProcess()) {
281     GfxInfoBase::sFeatureStatus = nullptr;
282   }
283 
284   Preferences::SetInt(prefname, aValue);
285   if (!aFailureId.IsEmpty()) {
286     nsCString failureprefname(prefname);
287     failureprefname += ".failureid";
288     Preferences::SetCString(failureprefname.get(), aFailureId);
289   }
290 }
291 
RemovePrefForFeature(int32_t aFeature)292 static void RemovePrefForFeature(int32_t aFeature) {
293   const char* prefname = GetPrefNameForFeature(aFeature);
294   if (!prefname) return;
295 
296   if (XRE_IsParentProcess()) {
297     GfxInfoBase::sFeatureStatus = nullptr;
298   }
299   Preferences::ClearUser(prefname);
300 }
301 
GetPrefValueForDriverVersion(nsCString & aVersion)302 static bool GetPrefValueForDriverVersion(nsCString& aVersion) {
303   return NS_SUCCEEDED(
304       Preferences::GetCString(SUGGESTED_VERSION_PREF, aVersion));
305 }
306 
SetPrefValueForDriverVersion(const nsAString & aVersion)307 static void SetPrefValueForDriverVersion(const nsAString& aVersion) {
308   Preferences::SetString(SUGGESTED_VERSION_PREF, aVersion);
309 }
310 
RemovePrefForDriverVersion()311 static void RemovePrefForDriverVersion() {
312   Preferences::ClearUser(SUGGESTED_VERSION_PREF);
313 }
314 
BlocklistOSToOperatingSystem(const nsAString & os)315 static OperatingSystem BlocklistOSToOperatingSystem(const nsAString& os) {
316   if (os.EqualsLiteral("WINNT 6.1")) {
317     return OperatingSystem::Windows7;
318   }
319   if (os.EqualsLiteral("WINNT 6.2")) {
320     return OperatingSystem::Windows8;
321   }
322   if (os.EqualsLiteral("WINNT 6.3")) {
323     return OperatingSystem::Windows8_1;
324   }
325   if (os.EqualsLiteral("WINNT 10.0")) {
326     return OperatingSystem::Windows10;
327   }
328   if (os.EqualsLiteral("Linux")) {
329     return OperatingSystem::Linux;
330   }
331   if (os.EqualsLiteral("Darwin 9")) {
332     return OperatingSystem::OSX10_5;
333   }
334   if (os.EqualsLiteral("Darwin 10")) {
335     return OperatingSystem::OSX10_6;
336   }
337   if (os.EqualsLiteral("Darwin 11")) {
338     return OperatingSystem::OSX10_7;
339   }
340   if (os.EqualsLiteral("Darwin 12")) {
341     return OperatingSystem::OSX10_8;
342   }
343   if (os.EqualsLiteral("Darwin 13")) {
344     return OperatingSystem::OSX10_9;
345   }
346   if (os.EqualsLiteral("Darwin 14")) {
347     return OperatingSystem::OSX10_10;
348   }
349   if (os.EqualsLiteral("Darwin 15")) {
350     return OperatingSystem::OSX10_11;
351   }
352   if (os.EqualsLiteral("Darwin 16")) {
353     return OperatingSystem::OSX10_12;
354   }
355   if (os.EqualsLiteral("Darwin 17")) {
356     return OperatingSystem::OSX10_13;
357   }
358   if (os.EqualsLiteral("Darwin 18")) {
359     return OperatingSystem::OSX10_14;
360   }
361   if (os.EqualsLiteral("Darwin 19")) {
362     return OperatingSystem::OSX10_15;
363   }
364   if (os.EqualsLiteral("Darwin 20")) {
365     return OperatingSystem::OSX11_0;
366   }
367   if (os.EqualsLiteral("Android")) {
368     return OperatingSystem::Android;
369     // For historical reasons, "All" in blocklist means "All Windows"
370   }
371   if (os.EqualsLiteral("All")) {
372     return OperatingSystem::Windows;
373   }
374   if (os.EqualsLiteral("Darwin")) {
375     return OperatingSystem::OSX;
376   }
377 
378   return OperatingSystem::Unknown;
379 }
380 
BlocklistDevicesToDeviceFamily(nsTArray<nsCString> & devices)381 static GfxDeviceFamily* BlocklistDevicesToDeviceFamily(
382     nsTArray<nsCString>& devices) {
383   if (devices.Length() == 0) return nullptr;
384 
385   // For each device, get its device ID, and return a freshly-allocated
386   // GfxDeviceFamily with the contents of that array.
387   GfxDeviceFamily* deviceIds = new GfxDeviceFamily;
388 
389   for (uint32_t i = 0; i < devices.Length(); ++i) {
390     // We make sure we don't add any "empty" device entries to the array, so
391     // we don't need to check if devices[i] is empty.
392     deviceIds->Append(NS_ConvertUTF8toUTF16(devices[i]));
393   }
394 
395   return deviceIds;
396 }
397 
BlocklistFeatureToGfxFeature(const nsAString & aFeature)398 static int32_t BlocklistFeatureToGfxFeature(const nsAString& aFeature) {
399   MOZ_ASSERT(!aFeature.IsEmpty());
400   if (aFeature.EqualsLiteral("DIRECT2D")) {
401     return nsIGfxInfo::FEATURE_DIRECT2D;
402   }
403   if (aFeature.EqualsLiteral("DIRECT3D_9_LAYERS")) {
404     return nsIGfxInfo::FEATURE_DIRECT3D_9_LAYERS;
405   }
406   if (aFeature.EqualsLiteral("DIRECT3D_10_LAYERS")) {
407     return nsIGfxInfo::FEATURE_DIRECT3D_10_LAYERS;
408   }
409   if (aFeature.EqualsLiteral("DIRECT3D_10_1_LAYERS")) {
410     return nsIGfxInfo::FEATURE_DIRECT3D_10_1_LAYERS;
411   }
412   if (aFeature.EqualsLiteral("DIRECT3D_11_LAYERS")) {
413     return nsIGfxInfo::FEATURE_DIRECT3D_11_LAYERS;
414   }
415   if (aFeature.EqualsLiteral("DIRECT3D_11_ANGLE")) {
416     return nsIGfxInfo::FEATURE_DIRECT3D_11_ANGLE;
417   }
418   if (aFeature.EqualsLiteral("HARDWARE_VIDEO_DECODING")) {
419     return nsIGfxInfo::FEATURE_HARDWARE_VIDEO_DECODING;
420   }
421   if (aFeature.EqualsLiteral("OPENGL_LAYERS")) {
422     return nsIGfxInfo::FEATURE_OPENGL_LAYERS;
423   }
424   if (aFeature.EqualsLiteral("WEBGL_OPENGL")) {
425     return nsIGfxInfo::FEATURE_WEBGL_OPENGL;
426   }
427   if (aFeature.EqualsLiteral("WEBGL_ANGLE")) {
428     return nsIGfxInfo::FEATURE_WEBGL_ANGLE;
429   }
430   if (aFeature.EqualsLiteral("WEBGL_MSAA")) {
431     return nsIGfxInfo::UNUSED_FEATURE_WEBGL_MSAA;
432   }
433   if (aFeature.EqualsLiteral("STAGEFRIGHT")) {
434     return nsIGfxInfo::FEATURE_STAGEFRIGHT;
435   }
436   if (aFeature.EqualsLiteral("WEBRTC_HW_ACCELERATION_ENCODE")) {
437     return nsIGfxInfo::FEATURE_WEBRTC_HW_ACCELERATION_ENCODE;
438   }
439   if (aFeature.EqualsLiteral("WEBRTC_HW_ACCELERATION_DECODE")) {
440     return nsIGfxInfo::FEATURE_WEBRTC_HW_ACCELERATION_DECODE;
441   }
442   if (aFeature.EqualsLiteral("WEBRTC_HW_ACCELERATION_H264")) {
443     return nsIGfxInfo::FEATURE_WEBRTC_HW_ACCELERATION_H264;
444   }
445   if (aFeature.EqualsLiteral("CANVAS2D_ACCELERATION")) {
446     return nsIGfxInfo::FEATURE_CANVAS2D_ACCELERATION;
447   }
448   if (aFeature.EqualsLiteral("DX_INTEROP2")) {
449     return nsIGfxInfo::FEATURE_DX_INTEROP2;
450   }
451   if (aFeature.EqualsLiteral("GPU_PROCESS")) {
452     return nsIGfxInfo::FEATURE_GPU_PROCESS;
453   }
454   if (aFeature.EqualsLiteral("WEBGL2")) {
455     return nsIGfxInfo::FEATURE_WEBGL2;
456   }
457   if (aFeature.EqualsLiteral("D3D11_KEYED_MUTEX")) {
458     return nsIGfxInfo::FEATURE_D3D11_KEYED_MUTEX;
459   }
460   if (aFeature.EqualsLiteral("WEBRENDER")) {
461     return nsIGfxInfo::FEATURE_WEBRENDER;
462   }
463   if (aFeature.EqualsLiteral("WEBRENDER_COMPOSITOR")) {
464     return nsIGfxInfo::FEATURE_WEBRENDER_COMPOSITOR;
465   }
466   if (aFeature.EqualsLiteral("DX_NV12")) {
467     return nsIGfxInfo::FEATURE_DX_NV12;
468   }
469   // We do not support FEATURE_VP8_HW_DECODE and FEATURE_VP9_HW_DECODE
470   // in downloadable blocklist.
471   if (aFeature.EqualsLiteral("GL_SWIZZLE")) {
472     return nsIGfxInfo::FEATURE_GL_SWIZZLE;
473   }
474   if (aFeature.EqualsLiteral("WEBRENDER_SCISSORED_CACHE_CLEARS")) {
475     return nsIGfxInfo::FEATURE_WEBRENDER_SCISSORED_CACHE_CLEARS;
476   }
477   if (aFeature.EqualsLiteral("ALLOW_WEBGL_OUT_OF_PROCESS")) {
478     return nsIGfxInfo::FEATURE_ALLOW_WEBGL_OUT_OF_PROCESS;
479   }
480   if (aFeature.EqualsLiteral("THREADSAFE_GL")) {
481     return nsIGfxInfo::FEATURE_THREADSAFE_GL;
482   }
483   if (aFeature.EqualsLiteral("WEBRENDER_SOFTWARE")) {
484     return nsIGfxInfo::FEATURE_WEBRENDER_SOFTWARE;
485   }
486   if (aFeature.EqualsLiteral("X11_EGL")) {
487     return nsIGfxInfo::FEATURE_X11_EGL;
488   }
489   if (aFeature.EqualsLiteral("DMABUF")) {
490     return nsIGfxInfo::FEATURE_DMABUF;
491   }
492 
493   // If we don't recognize the feature, it may be new, and something
494   // this version doesn't understand.  So, nothing to do.  This is
495   // different from feature not being specified at all, in which case
496   // this method should not get called and we should continue with the
497   // "all features" blocklisting.
498   return -1;
499 }
500 
BlocklistFeatureStatusToGfxFeatureStatus(const nsAString & aStatus)501 static int32_t BlocklistFeatureStatusToGfxFeatureStatus(
502     const nsAString& aStatus) {
503   if (aStatus.EqualsLiteral("STATUS_OK")) {
504     return nsIGfxInfo::FEATURE_STATUS_OK;
505   }
506   if (aStatus.EqualsLiteral("BLOCKED_DRIVER_VERSION")) {
507     return nsIGfxInfo::FEATURE_BLOCKED_DRIVER_VERSION;
508   }
509   if (aStatus.EqualsLiteral("BLOCKED_DEVICE")) {
510     return nsIGfxInfo::FEATURE_BLOCKED_DEVICE;
511   }
512   if (aStatus.EqualsLiteral("DISCOURAGED")) {
513     return nsIGfxInfo::FEATURE_DISCOURAGED;
514   }
515   if (aStatus.EqualsLiteral("BLOCKED_OS_VERSION")) {
516     return nsIGfxInfo::FEATURE_BLOCKED_OS_VERSION;
517   }
518   if (aStatus.EqualsLiteral("DENIED")) {
519     return nsIGfxInfo::FEATURE_DENIED;
520   }
521   if (aStatus.EqualsLiteral("ALLOW_QUALIFIED")) {
522     return nsIGfxInfo::FEATURE_ALLOW_QUALIFIED;
523   }
524   if (aStatus.EqualsLiteral("ALLOW_ALWAYS")) {
525     return nsIGfxInfo::FEATURE_ALLOW_ALWAYS;
526   }
527 
528   // Do not allow it to set STATUS_UNKNOWN.  Also, we are not
529   // expecting the "mismatch" status showing up here.
530 
531   return nsIGfxInfo::FEATURE_STATUS_OK;
532 }
533 
BlocklistComparatorToComparisonOp(const nsAString & op)534 static VersionComparisonOp BlocklistComparatorToComparisonOp(
535     const nsAString& op) {
536   if (op.EqualsLiteral("LESS_THAN")) {
537     return DRIVER_LESS_THAN;
538   }
539   if (op.EqualsLiteral("BUILD_ID_LESS_THAN")) {
540     return DRIVER_BUILD_ID_LESS_THAN;
541   }
542   if (op.EqualsLiteral("LESS_THAN_OR_EQUAL")) {
543     return DRIVER_LESS_THAN_OR_EQUAL;
544   }
545   if (op.EqualsLiteral("BUILD_ID_LESS_THAN_OR_EQUAL")) {
546     return DRIVER_BUILD_ID_LESS_THAN_OR_EQUAL;
547   }
548   if (op.EqualsLiteral("GREATER_THAN")) {
549     return DRIVER_GREATER_THAN;
550   }
551   if (op.EqualsLiteral("GREATER_THAN_OR_EQUAL")) {
552     return DRIVER_GREATER_THAN_OR_EQUAL;
553   }
554   if (op.EqualsLiteral("EQUAL")) {
555     return DRIVER_EQUAL;
556   }
557   if (op.EqualsLiteral("NOT_EQUAL")) {
558     return DRIVER_NOT_EQUAL;
559   }
560   if (op.EqualsLiteral("BETWEEN_EXCLUSIVE")) {
561     return DRIVER_BETWEEN_EXCLUSIVE;
562   }
563   if (op.EqualsLiteral("BETWEEN_INCLUSIVE")) {
564     return DRIVER_BETWEEN_INCLUSIVE;
565   }
566   if (op.EqualsLiteral("BETWEEN_INCLUSIVE_START")) {
567     return DRIVER_BETWEEN_INCLUSIVE_START;
568   }
569 
570   return DRIVER_COMPARISON_IGNORED;
571 }
572 
573 /*
574   Deserialize Blocklist entries from string.
575   e.g:
576   os:WINNT 6.0\tvendor:0x8086\tdevices:0x2582,0x2782\tfeature:DIRECT3D_10_LAYERS\tfeatureStatus:BLOCKED_DRIVER_VERSION\tdriverVersion:8.52.322.2202\tdriverVersionComparator:LESS_THAN_OR_EQUAL
577 */
BlocklistEntryToDriverInfo(const nsACString & aBlocklistEntry,GfxDriverInfo & aDriverInfo)578 static bool BlocklistEntryToDriverInfo(const nsACString& aBlocklistEntry,
579                                        GfxDriverInfo& aDriverInfo) {
580   // If we get an application version to be zero, something is not working
581   // and we are not going to bother checking the blocklist versions.
582   // See TestGfxWidgets.cpp for how version comparison works.
583   // <versionRange minVersion="42.0a1" maxVersion="45.0"></versionRange>
584   static mozilla::Version zeroV("0");
585   static mozilla::Version appV(GfxInfoBase::GetApplicationVersion().get());
586   if (appV <= zeroV) {
587     gfxCriticalErrorOnce(gfxCriticalError::DefaultOptions(false))
588         << "Invalid application version "
589         << GfxInfoBase::GetApplicationVersion().get();
590   }
591 
592   aDriverInfo.mRuleId = "FEATURE_FAILURE_DL_BLOCKLIST_NO_ID"_ns;
593 
594   for (const auto& keyValue : aBlocklistEntry.Split('\t')) {
595     nsTArray<nsCString> splitted;
596     ParseString(keyValue, ':', splitted);
597     if (splitted.Length() != 2) {
598       // If we don't recognize the input data, we do not want to proceed.
599       gfxCriticalErrorOnce(CriticalLog::DefaultOptions(false))
600           << "Unrecognized data " << nsCString(keyValue).get();
601       return false;
602     }
603     const nsCString& key = splitted[0];
604     const nsCString& value = splitted[1];
605     NS_ConvertUTF8toUTF16 dataValue(value);
606 
607     if (value.Length() == 0) {
608       // Safety check for empty values.
609       gfxCriticalErrorOnce(CriticalLog::DefaultOptions(false))
610           << "Empty value for " << key.get();
611       return false;
612     }
613 
614     if (key.EqualsLiteral("blockID")) {
615       nsCString blockIdStr = "FEATURE_FAILURE_DL_BLOCKLIST_"_ns + value;
616       aDriverInfo.mRuleId = blockIdStr.get();
617     } else if (key.EqualsLiteral("os")) {
618       aDriverInfo.mOperatingSystem = BlocklistOSToOperatingSystem(dataValue);
619     } else if (key.EqualsLiteral("osversion")) {
620       aDriverInfo.mOperatingSystemVersion = strtoul(value.get(), nullptr, 10);
621     } else if (key.EqualsLiteral("desktopEnvironment")) {
622       aDriverInfo.mDesktopEnvironment = dataValue;
623     } else if (key.EqualsLiteral("windowProtocol")) {
624       aDriverInfo.mWindowProtocol = dataValue;
625     } else if (key.EqualsLiteral("vendor")) {
626       aDriverInfo.mAdapterVendor = dataValue;
627     } else if (key.EqualsLiteral("driverVendor")) {
628       aDriverInfo.mDriverVendor = dataValue;
629     } else if (key.EqualsLiteral("feature")) {
630       aDriverInfo.mFeature = BlocklistFeatureToGfxFeature(dataValue);
631       if (aDriverInfo.mFeature < 0) {
632         // If we don't recognize the feature, we do not want to proceed.
633         gfxCriticalErrorOnce(CriticalLog::DefaultOptions(false))
634             << "Unrecognized feature " << value.get();
635         return false;
636       }
637     } else if (key.EqualsLiteral("featureStatus")) {
638       aDriverInfo.mFeatureStatus =
639           BlocklistFeatureStatusToGfxFeatureStatus(dataValue);
640     } else if (key.EqualsLiteral("driverVersion")) {
641       uint64_t version;
642       if (ParseDriverVersion(dataValue, &version))
643         aDriverInfo.mDriverVersion = version;
644     } else if (key.EqualsLiteral("driverVersionMax")) {
645       uint64_t version;
646       if (ParseDriverVersion(dataValue, &version))
647         aDriverInfo.mDriverVersionMax = version;
648     } else if (key.EqualsLiteral("driverVersionComparator")) {
649       aDriverInfo.mComparisonOp = BlocklistComparatorToComparisonOp(dataValue);
650     } else if (key.EqualsLiteral("model")) {
651       aDriverInfo.mModel = dataValue;
652     } else if (key.EqualsLiteral("product")) {
653       aDriverInfo.mProduct = dataValue;
654     } else if (key.EqualsLiteral("manufacturer")) {
655       aDriverInfo.mManufacturer = dataValue;
656     } else if (key.EqualsLiteral("hardware")) {
657       aDriverInfo.mHardware = dataValue;
658     } else if (key.EqualsLiteral("versionRange")) {
659       nsTArray<nsCString> versionRange;
660       ParseString(value, ',', versionRange);
661       if (versionRange.Length() != 2) {
662         gfxCriticalErrorOnce(CriticalLog::DefaultOptions(false))
663             << "Unrecognized versionRange " << value.get();
664         return false;
665       }
666       const nsCString& minValue = versionRange[0];
667       const nsCString& maxValue = versionRange[1];
668 
669       mozilla::Version minV(minValue.get());
670       mozilla::Version maxV(maxValue.get());
671 
672       if (minV > zeroV && !(appV >= minV)) {
673         // The version of the application is less than the minimal version
674         // this blocklist entry applies to, so we can just ignore it by
675         // returning false and letting the caller deal with it.
676         return false;
677       }
678       if (maxV > zeroV && !(appV <= maxV)) {
679         // The version of the application is more than the maximal version
680         // this blocklist entry applies to, so we can just ignore it by
681         // returning false and letting the caller deal with it.
682         return false;
683       }
684     } else if (key.EqualsLiteral("devices")) {
685       nsTArray<nsCString> devices;
686       ParseString(value, ',', devices);
687       GfxDeviceFamily* deviceIds = BlocklistDevicesToDeviceFamily(devices);
688       if (deviceIds) {
689         // Get GfxDriverInfo to adopt the devices array we created.
690         aDriverInfo.mDeleteDevices = true;
691         aDriverInfo.mDevices = deviceIds;
692       }
693     }
694     // We explicitly ignore unknown elements.
695   }
696 
697   return true;
698 }
699 
700 NS_IMETHODIMP
Observe(nsISupports * aSubject,const char * aTopic,const char16_t * aData)701 GfxInfoBase::Observe(nsISupports* aSubject, const char* aTopic,
702                      const char16_t* aData) {
703   if (strcmp(aTopic, "blocklist-data-gfxItems") == 0) {
704     nsTArray<GfxDriverInfo> driverInfo;
705     NS_ConvertUTF16toUTF8 utf8Data(aData);
706 
707     for (const auto& blocklistEntry : utf8Data.Split('\n')) {
708       GfxDriverInfo di;
709       if (BlocklistEntryToDriverInfo(blocklistEntry, di)) {
710         // XXX Changing this to driverInfo.AppendElement(di) causes leaks.
711         // Probably some non-standard semantics of the copy/move operations?
712         *driverInfo.AppendElement() = di;
713         // Prevent di falling out of scope from destroying the devices.
714         di.mDeleteDevices = false;
715       } else {
716         driverInfo.AppendElement();
717       }
718     }
719 
720     EvaluateDownloadedBlocklist(driverInfo);
721   }
722 
723   return NS_OK;
724 }
725 
GfxInfoBase()726 GfxInfoBase::GfxInfoBase() : mScreenPixels(INT64_MAX), mMutex("GfxInfoBase") {}
727 
728 GfxInfoBase::~GfxInfoBase() = default;
729 
Init()730 nsresult GfxInfoBase::Init() {
731   InitGfxDriverInfoShutdownObserver();
732 
733   nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
734   if (os) {
735     os->AddObserver(this, "blocklist-data-gfxItems", true);
736   }
737 
738   return NS_OK;
739 }
740 
GetData()741 void GfxInfoBase::GetData() {
742   if (mScreenPixels != INT64_MAX) {
743     // Already initialized.
744     return;
745   }
746 
747   nsCOMPtr<nsIScreenManager> manager =
748       do_GetService("@mozilla.org/gfx/screenmanager;1");
749   if (!manager) {
750     MOZ_ASSERT_UNREACHABLE("failed to get nsIScreenManager");
751     return;
752   }
753 
754   manager->GetTotalScreenPixels(&mScreenPixels);
755 }
756 
757 NS_IMETHODIMP
GetFeatureStatus(int32_t aFeature,nsACString & aFailureId,int32_t * aStatus)758 GfxInfoBase::GetFeatureStatus(int32_t aFeature, nsACString& aFailureId,
759                               int32_t* aStatus) {
760   // Ignore the gfx.blocklist.all pref on release and beta.
761 #if defined(RELEASE_OR_BETA)
762   int32_t blocklistAll = 0;
763 #else
764   int32_t blocklistAll = StaticPrefs::gfx_blocklist_all_AtStartup();
765 #endif
766   if (blocklistAll > 0) {
767     gfxCriticalErrorOnce(gfxCriticalError::DefaultOptions(false))
768         << "Forcing blocklisting all features";
769     *aStatus = FEATURE_BLOCKED_DEVICE;
770     aFailureId = "FEATURE_FAILURE_BLOCK_ALL";
771     return NS_OK;
772   }
773 
774   if (blocklistAll < 0) {
775     gfxCriticalErrorOnce(gfxCriticalError::DefaultOptions(false))
776         << "Ignoring any feature blocklisting.";
777     *aStatus = FEATURE_STATUS_OK;
778     return NS_OK;
779   }
780 
781   if (GetPrefValueForFeature(aFeature, *aStatus, aFailureId)) {
782     return NS_OK;
783   }
784 
785   if (XRE_IsContentProcess() || XRE_IsGPUProcess()) {
786     // Use the cached data received from the parent process.
787     MOZ_ASSERT(sFeatureStatus);
788     bool success = false;
789     for (const auto& fs : *sFeatureStatus) {
790       if (fs.feature() == aFeature) {
791         aFailureId = fs.failureId();
792         *aStatus = fs.status();
793         success = true;
794         break;
795       }
796     }
797     return success ? NS_OK : NS_ERROR_FAILURE;
798   }
799 
800   nsString version;
801   nsTArray<GfxDriverInfo> driverInfo;
802   nsresult rv =
803       GetFeatureStatusImpl(aFeature, aStatus, version, driverInfo, aFailureId);
804   return rv;
805 }
806 
GetAllFeatures()807 nsTArray<gfx::GfxInfoFeatureStatus> GfxInfoBase::GetAllFeatures() {
808   MOZ_RELEASE_ASSERT(XRE_IsParentProcess());
809   if (!sFeatureStatus) {
810     InitFeatureStatus(new nsTArray<gfx::GfxInfoFeatureStatus>());
811     for (int32_t i = 1; i <= nsIGfxInfo::FEATURE_MAX_VALUE; ++i) {
812       int32_t status = 0;
813       nsAutoCString failureId;
814       GetFeatureStatus(i, failureId, &status);
815       gfx::GfxInfoFeatureStatus gfxFeatureStatus;
816       gfxFeatureStatus.feature() = i;
817       gfxFeatureStatus.status() = status;
818       gfxFeatureStatus.failureId() = failureId;
819       sFeatureStatus->AppendElement(gfxFeatureStatus);
820     }
821   }
822 
823   nsTArray<gfx::GfxInfoFeatureStatus> features;
824   for (const auto& status : *sFeatureStatus) {
825     gfx::GfxInfoFeatureStatus copy = status;
826     features.AppendElement(copy);
827   }
828   return features;
829 }
830 
MatchingAllowStatus(int32_t aStatus)831 inline bool MatchingAllowStatus(int32_t aStatus) {
832   switch (aStatus) {
833     case nsIGfxInfo::FEATURE_ALLOW_ALWAYS:
834     case nsIGfxInfo::FEATURE_ALLOW_QUALIFIED:
835       return true;
836     default:
837       return false;
838   }
839 }
840 
841 // Matching OS go somewhat beyond the simple equality check because of the
842 // "All Windows" and "All OS X" variations.
843 //
844 // aBlockedOS is describing the system(s) we are trying to block.
845 // aSystemOS is describing the system we are running on.
846 //
847 // aSystemOS should not be "Windows" or "OSX" - it should be set to
848 // a particular version instead.
849 // However, it is valid for aBlockedOS to be one of those generic values,
850 // as we could be blocking all of the versions.
MatchingOperatingSystems(OperatingSystem aBlockedOS,OperatingSystem aSystemOS,uint32_t aSystemOSBuild)851 inline bool MatchingOperatingSystems(OperatingSystem aBlockedOS,
852                                      OperatingSystem aSystemOS,
853                                      uint32_t aSystemOSBuild) {
854   MOZ_ASSERT(aSystemOS != OperatingSystem::Windows &&
855              aSystemOS != OperatingSystem::OSX);
856 
857   // If the block entry OS is unknown, it doesn't match
858   if (aBlockedOS == OperatingSystem::Unknown) {
859     return false;
860   }
861 
862 #if defined(XP_WIN)
863   if (aBlockedOS == OperatingSystem::Windows) {
864     // We do want even "unknown" aSystemOS to fall under "all windows"
865     return true;
866   }
867 
868   constexpr uint32_t kMinWin10BuildNumber = 18362;
869   if (aBlockedOS == OperatingSystem::RecentWindows10 &&
870       aSystemOS == OperatingSystem::Windows10) {
871     // For allowlist purposes, we sometimes want to restrict to only recent
872     // versions of Windows 10. This is a bit of a kludge but easier than adding
873     // complicated blocklist infrastructure for build ID comparisons like driver
874     // versions.
875     return aSystemOSBuild >= kMinWin10BuildNumber;
876   }
877 
878   if (aBlockedOS == OperatingSystem::NotRecentWindows10) {
879     if (aSystemOS == OperatingSystem::Windows10) {
880       return aSystemOSBuild < kMinWin10BuildNumber;
881     } else {
882       return true;
883     }
884   }
885 #endif
886 
887 #if defined(XP_MACOSX)
888   if (aBlockedOS == OperatingSystem::OSX) {
889     // We do want even "unknown" aSystemOS to fall under "all OS X"
890     return true;
891   }
892 #endif
893 
894   return aSystemOS == aBlockedOS;
895 }
896 
MatchingBattery(BatteryStatus aBatteryStatus,bool aHasBattery)897 inline bool MatchingBattery(BatteryStatus aBatteryStatus, bool aHasBattery) {
898   switch (aBatteryStatus) {
899     case BatteryStatus::All:
900       return true;
901     case BatteryStatus::None:
902       return !aHasBattery;
903     case BatteryStatus::Present:
904       return aHasBattery;
905   }
906 
907   MOZ_ASSERT_UNREACHABLE("bad battery status");
908   return false;
909 }
910 
MatchingScreenSize(ScreenSizeStatus aScreenStatus,int64_t aScreenPixels)911 inline bool MatchingScreenSize(ScreenSizeStatus aScreenStatus,
912                                int64_t aScreenPixels) {
913   constexpr int64_t kMaxSmallPixels = 2304000;   // 1920x1200
914   constexpr int64_t kMaxMediumPixels = 4953600;  // 3440x1440
915 
916   switch (aScreenStatus) {
917     case ScreenSizeStatus::All:
918       return true;
919     case ScreenSizeStatus::Small:
920       return aScreenPixels <= kMaxSmallPixels;
921     case ScreenSizeStatus::SmallAndMedium:
922       return aScreenPixels <= kMaxMediumPixels;
923     case ScreenSizeStatus::Medium:
924       return aScreenPixels > kMaxSmallPixels &&
925              aScreenPixels <= kMaxMediumPixels;
926     case ScreenSizeStatus::MediumAndLarge:
927       return aScreenPixels > kMaxSmallPixels;
928     case ScreenSizeStatus::Large:
929       return aScreenPixels > kMaxMediumPixels;
930   }
931 
932   MOZ_ASSERT_UNREACHABLE("bad screen status");
933   return false;
934 }
935 
FindBlocklistedDeviceInList(const nsTArray<GfxDriverInfo> & info,nsAString & aSuggestedVersion,int32_t aFeature,nsACString & aFailureId,OperatingSystem os,bool aForAllowing)936 int32_t GfxInfoBase::FindBlocklistedDeviceInList(
937     const nsTArray<GfxDriverInfo>& info, nsAString& aSuggestedVersion,
938     int32_t aFeature, nsACString& aFailureId, OperatingSystem os,
939     bool aForAllowing) {
940   int32_t status = nsIGfxInfo::FEATURE_STATUS_UNKNOWN;
941 
942   // Some properties are not available on all platforms.
943   nsAutoString desktopEnvironment;
944   nsresult rv = GetDesktopEnvironment(desktopEnvironment);
945   if (NS_FAILED(rv) && rv != NS_ERROR_NOT_IMPLEMENTED) {
946     return 0;
947   }
948 
949   nsAutoString windowProtocol;
950   rv = GetWindowProtocol(windowProtocol);
951   if (NS_FAILED(rv) && rv != NS_ERROR_NOT_IMPLEMENTED) {
952     return 0;
953   }
954 
955   bool hasBattery = false;
956   rv = GetHasBattery(&hasBattery);
957   if (NS_FAILED(rv) && rv != NS_ERROR_NOT_IMPLEMENTED) {
958     return 0;
959   }
960 
961   uint32_t osBuild = OperatingSystemBuild();
962 
963   // Get the adapters once then reuse below
964   nsAutoString adapterVendorID[2];
965   nsAutoString adapterDeviceID[2];
966   nsAutoString adapterDriverVendor[2];
967   nsAutoString adapterDriverVersionString[2];
968   bool adapterInfoFailed[2];
969 
970   adapterInfoFailed[0] =
971       (NS_FAILED(GetAdapterVendorID(adapterVendorID[0])) ||
972        NS_FAILED(GetAdapterDeviceID(adapterDeviceID[0])) ||
973        NS_FAILED(GetAdapterDriverVendor(adapterDriverVendor[0])) ||
974        NS_FAILED(GetAdapterDriverVersion(adapterDriverVersionString[0])));
975   adapterInfoFailed[1] =
976       (NS_FAILED(GetAdapterVendorID2(adapterVendorID[1])) ||
977        NS_FAILED(GetAdapterDeviceID2(adapterDeviceID[1])) ||
978        NS_FAILED(GetAdapterDriverVendor2(adapterDriverVendor[1])) ||
979        NS_FAILED(GetAdapterDriverVersion2(adapterDriverVersionString[1])));
980   // No point in going on if we don't have adapter info
981   if (adapterInfoFailed[0] && adapterInfoFailed[1]) {
982     return 0;
983   }
984 
985 #if defined(XP_WIN) || defined(ANDROID) || defined(MOZ_WIDGET_GTK)
986   uint64_t driverVersion[2] = {0, 0};
987   if (!adapterInfoFailed[0]) {
988     ParseDriverVersion(adapterDriverVersionString[0], &driverVersion[0]);
989   }
990   if (!adapterInfoFailed[1]) {
991     ParseDriverVersion(adapterDriverVersionString[1], &driverVersion[1]);
992   }
993 #endif
994 
995   uint32_t i = 0;
996   for (; i < info.Length(); i++) {
997     // If the status is FEATURE_ALLOW_*, then it is for the allowlist, not
998     // blocklisting. Only consider entries for our search mode.
999     if (MatchingAllowStatus(info[i].mFeatureStatus) != aForAllowing) {
1000       continue;
1001     }
1002 
1003     // If we don't have the info for this GPU, no need to check further.
1004     // It is unclear that we would ever have a mixture of 1st and 2nd
1005     // GPU, but leaving the code in for that possibility for now.
1006     // (Actually, currently mGpu2 will never be true, so this can
1007     // be optimized out.)
1008     uint32_t infoIndex = info[i].mGpu2 ? 1 : 0;
1009     if (adapterInfoFailed[infoIndex]) {
1010       continue;
1011     }
1012 
1013     // Do the operating system check first, no point in getting the driver
1014     // info if we won't need to use it.
1015     if (!MatchingOperatingSystems(info[i].mOperatingSystem, os, osBuild)) {
1016       continue;
1017     }
1018 
1019     if (info[i].mOperatingSystemVersion &&
1020         info[i].mOperatingSystemVersion != OperatingSystemVersion()) {
1021       continue;
1022     }
1023 
1024     if (!MatchingBattery(info[i].mBattery, hasBattery)) {
1025       continue;
1026     }
1027 
1028     if (!MatchingScreenSize(info[i].mScreen, mScreenPixels)) {
1029       continue;
1030     }
1031 
1032     if (!DoesDesktopEnvironmentMatch(info[i].mDesktopEnvironment,
1033                                      desktopEnvironment)) {
1034       continue;
1035     }
1036 
1037     if (!DoesWindowProtocolMatch(info[i].mWindowProtocol, windowProtocol)) {
1038       continue;
1039     }
1040 
1041     if (!DoesVendorMatch(info[i].mAdapterVendor, adapterVendorID[infoIndex])) {
1042       continue;
1043     }
1044 
1045     if (!DoesDriverVendorMatch(info[i].mDriverVendor,
1046                                adapterDriverVendor[infoIndex])) {
1047       continue;
1048     }
1049 
1050     if (info[i].mDevices && !info[i].mDevices->IsEmpty()) {
1051       nsresult rv = info[i].mDevices->Contains(adapterDeviceID[infoIndex]);
1052       if (rv == NS_ERROR_NOT_AVAILABLE) {
1053         // Not found
1054         continue;
1055       }
1056       if (rv != NS_OK) {
1057         // Failed to search, allowlist should not match, blocklist should match
1058         // for safety reasons
1059         if (aForAllowing) {
1060           continue;
1061         }
1062         break;
1063       }
1064     }
1065 
1066     bool match = false;
1067 
1068     if (!info[i].mHardware.IsEmpty() && !info[i].mHardware.Equals(Hardware())) {
1069       continue;
1070     }
1071     if (!info[i].mModel.IsEmpty() && !info[i].mModel.Equals(Model())) {
1072       continue;
1073     }
1074     if (!info[i].mProduct.IsEmpty() && !info[i].mProduct.Equals(Product())) {
1075       continue;
1076     }
1077     if (!info[i].mManufacturer.IsEmpty() &&
1078         !info[i].mManufacturer.Equals(Manufacturer())) {
1079       continue;
1080     }
1081 
1082 #if defined(XP_WIN) || defined(ANDROID) || defined(MOZ_WIDGET_GTK)
1083     switch (info[i].mComparisonOp) {
1084       case DRIVER_LESS_THAN:
1085         match = driverVersion[infoIndex] < info[i].mDriverVersion;
1086         break;
1087       case DRIVER_BUILD_ID_LESS_THAN:
1088         match = (driverVersion[infoIndex] & 0xFFFF) < info[i].mDriverVersion;
1089         break;
1090       case DRIVER_LESS_THAN_OR_EQUAL:
1091         match = driverVersion[infoIndex] <= info[i].mDriverVersion;
1092         break;
1093       case DRIVER_BUILD_ID_LESS_THAN_OR_EQUAL:
1094         match = (driverVersion[infoIndex] & 0xFFFF) <= info[i].mDriverVersion;
1095         break;
1096       case DRIVER_GREATER_THAN:
1097         match = driverVersion[infoIndex] > info[i].mDriverVersion;
1098         break;
1099       case DRIVER_GREATER_THAN_OR_EQUAL:
1100         match = driverVersion[infoIndex] >= info[i].mDriverVersion;
1101         break;
1102       case DRIVER_EQUAL:
1103         match = driverVersion[infoIndex] == info[i].mDriverVersion;
1104         break;
1105       case DRIVER_NOT_EQUAL:
1106         match = driverVersion[infoIndex] != info[i].mDriverVersion;
1107         break;
1108       case DRIVER_BETWEEN_EXCLUSIVE:
1109         match = driverVersion[infoIndex] > info[i].mDriverVersion &&
1110                 driverVersion[infoIndex] < info[i].mDriverVersionMax;
1111         break;
1112       case DRIVER_BETWEEN_INCLUSIVE:
1113         match = driverVersion[infoIndex] >= info[i].mDriverVersion &&
1114                 driverVersion[infoIndex] <= info[i].mDriverVersionMax;
1115         break;
1116       case DRIVER_BETWEEN_INCLUSIVE_START:
1117         match = driverVersion[infoIndex] >= info[i].mDriverVersion &&
1118                 driverVersion[infoIndex] < info[i].mDriverVersionMax;
1119         break;
1120       case DRIVER_COMPARISON_IGNORED:
1121         // We don't have a comparison op, so we match everything.
1122         match = true;
1123         break;
1124       default:
1125         NS_WARNING("Bogus op in GfxDriverInfo");
1126         break;
1127     }
1128 #else
1129     // We don't care what driver version it was. We only check OS version and if
1130     // the device matches.
1131     match = true;
1132 #endif
1133 
1134     if (match || info[i].mDriverVersion == GfxDriverInfo::allDriverVersions) {
1135       if ((info[i].mFeature == GfxDriverInfo::allFeatures &&
1136            aFeature != nsIGfxInfo::FEATURE_WEBRENDER_SOFTWARE) ||
1137           info[i].mFeature == aFeature) {
1138         status = info[i].mFeatureStatus;
1139         if (!info[i].mRuleId.IsEmpty()) {
1140           aFailureId = info[i].mRuleId.get();
1141         } else {
1142           aFailureId = "FEATURE_FAILURE_DL_BLOCKLIST_NO_ID";
1143         }
1144         break;
1145       }
1146     }
1147   }
1148 
1149 #if defined(XP_WIN)
1150   // As a very special case, we block D2D on machines with an NVidia 310M GPU
1151   // as either the primary or secondary adapter.  D2D is also blocked when the
1152   // NV 310M is the primary adapter (using the standard blocklisting mechanism).
1153   // If the primary GPU already matched something in the blocklist then we
1154   // ignore this special rule.  See bug 1008759.
1155   if (status == nsIGfxInfo::FEATURE_STATUS_UNKNOWN &&
1156       (aFeature == nsIGfxInfo::FEATURE_DIRECT2D)) {
1157     if (!adapterInfoFailed[1]) {
1158       nsAString& nvVendorID =
1159           (nsAString&)GfxDriverInfo::GetDeviceVendor(DeviceVendor::NVIDIA);
1160       const nsString nv310mDeviceId = u"0x0A70"_ns;
1161       if (nvVendorID.Equals(adapterVendorID[1],
1162                             nsCaseInsensitiveStringComparator) &&
1163           nv310mDeviceId.Equals(adapterDeviceID[1],
1164                                 nsCaseInsensitiveStringComparator)) {
1165         status = nsIGfxInfo::FEATURE_BLOCKED_DEVICE;
1166         aFailureId = "FEATURE_FAILURE_D2D_NV310M_BLOCK";
1167       }
1168     }
1169   }
1170 
1171   // Depends on Windows driver versioning. We don't pass a GfxDriverInfo object
1172   // back to the Windows handler, so we must handle this here.
1173   if (status == FEATURE_BLOCKED_DRIVER_VERSION) {
1174     if (info[i].mSuggestedVersion) {
1175       aSuggestedVersion.AppendPrintf("%s", info[i].mSuggestedVersion);
1176     } else if (info[i].mComparisonOp == DRIVER_LESS_THAN &&
1177                info[i].mDriverVersion != GfxDriverInfo::allDriverVersions) {
1178       aSuggestedVersion.AppendPrintf(
1179           "%lld.%lld.%lld.%lld",
1180           (info[i].mDriverVersion & 0xffff000000000000) >> 48,
1181           (info[i].mDriverVersion & 0x0000ffff00000000) >> 32,
1182           (info[i].mDriverVersion & 0x00000000ffff0000) >> 16,
1183           (info[i].mDriverVersion & 0x000000000000ffff));
1184     }
1185   }
1186 #endif
1187 
1188   return status;
1189 }
1190 
SetFeatureStatus(nsTArray<gfx::GfxInfoFeatureStatus> && aFS)1191 void GfxInfoBase::SetFeatureStatus(nsTArray<gfx::GfxInfoFeatureStatus>&& aFS) {
1192   MOZ_ASSERT(!sFeatureStatus);
1193   InitFeatureStatus(new nsTArray<gfx::GfxInfoFeatureStatus>(std::move(aFS)));
1194 }
1195 
DoesDesktopEnvironmentMatch(const nsAString & aBlocklistDesktop,const nsAString & aDesktopEnv)1196 bool GfxInfoBase::DoesDesktopEnvironmentMatch(
1197     const nsAString& aBlocklistDesktop, const nsAString& aDesktopEnv) {
1198   return aBlocklistDesktop.Equals(aDesktopEnv,
1199                                   nsCaseInsensitiveStringComparator) ||
1200          aBlocklistDesktop.Equals(
1201              GfxDriverInfo::GetDesktopEnvironment(DesktopEnvironment::All),
1202              nsCaseInsensitiveStringComparator);
1203 }
1204 
DoesWindowProtocolMatch(const nsAString & aBlocklistWindowProtocol,const nsAString & aWindowProtocol)1205 bool GfxInfoBase::DoesWindowProtocolMatch(
1206     const nsAString& aBlocklistWindowProtocol,
1207     const nsAString& aWindowProtocol) {
1208   return aBlocklistWindowProtocol.Equals(aWindowProtocol,
1209                                          nsCaseInsensitiveStringComparator) ||
1210          aBlocklistWindowProtocol.Equals(
1211              GfxDriverInfo::GetWindowProtocol(WindowProtocol::All),
1212              nsCaseInsensitiveStringComparator);
1213 }
1214 
DoesVendorMatch(const nsAString & aBlocklistVendor,const nsAString & aAdapterVendor)1215 bool GfxInfoBase::DoesVendorMatch(const nsAString& aBlocklistVendor,
1216                                   const nsAString& aAdapterVendor) {
1217   return aBlocklistVendor.Equals(aAdapterVendor,
1218                                  nsCaseInsensitiveStringComparator) ||
1219          aBlocklistVendor.Equals(
1220              GfxDriverInfo::GetDeviceVendor(DeviceVendor::All),
1221              nsCaseInsensitiveStringComparator);
1222 }
1223 
DoesDriverVendorMatch(const nsAString & aBlocklistVendor,const nsAString & aDriverVendor)1224 bool GfxInfoBase::DoesDriverVendorMatch(const nsAString& aBlocklistVendor,
1225                                         const nsAString& aDriverVendor) {
1226   return aBlocklistVendor.Equals(aDriverVendor,
1227                                  nsCaseInsensitiveStringComparator) ||
1228          aBlocklistVendor.Equals(
1229              GfxDriverInfo::GetDriverVendor(DriverVendor::All),
1230              nsCaseInsensitiveStringComparator);
1231 }
1232 
IsFeatureAllowlisted(int32_t aFeature) const1233 bool GfxInfoBase::IsFeatureAllowlisted(int32_t aFeature) const {
1234   return aFeature == nsIGfxInfo::FEATURE_WEBRENDER ||
1235          aFeature == nsIGfxInfo::FEATURE_WEBRENDER_SOFTWARE;
1236 }
1237 
GetFeatureStatusImpl(int32_t aFeature,int32_t * aStatus,nsAString & aSuggestedVersion,const nsTArray<GfxDriverInfo> & aDriverInfo,nsACString & aFailureId,OperatingSystem * aOS)1238 nsresult GfxInfoBase::GetFeatureStatusImpl(
1239     int32_t aFeature, int32_t* aStatus, nsAString& aSuggestedVersion,
1240     const nsTArray<GfxDriverInfo>& aDriverInfo, nsACString& aFailureId,
1241     OperatingSystem* aOS /* = nullptr */) {
1242   if (aFeature <= 0) {
1243     gfxWarning() << "Invalid feature <= 0";
1244     return NS_OK;
1245   }
1246 
1247   if (*aStatus != nsIGfxInfo::FEATURE_STATUS_UNKNOWN) {
1248     // Terminate now with the status determined by the derived type (OS-specific
1249     // code).
1250     return NS_OK;
1251   }
1252 
1253   if (sShutdownOccurred) {
1254     // This is futile; we've already commenced shutdown and our blocklists have
1255     // been deleted. We may want to look into resurrecting the blocklist instead
1256     // but for now, just don't even go there.
1257     return NS_OK;
1258   }
1259 
1260   // Ensure any additional initialization required is complete.
1261   GetData();
1262 
1263   // If an operating system was provided by the derived GetFeatureStatusImpl,
1264   // grab it here. Otherwise, the OS is unknown.
1265   OperatingSystem os = (aOS ? *aOS : OperatingSystem::Unknown);
1266 
1267   nsAutoString adapterVendorID;
1268   nsAutoString adapterDeviceID;
1269   nsAutoString adapterDriverVersionString;
1270   if (NS_FAILED(GetAdapterVendorID(adapterVendorID)) ||
1271       NS_FAILED(GetAdapterDeviceID(adapterDeviceID)) ||
1272       NS_FAILED(GetAdapterDriverVersion(adapterDriverVersionString))) {
1273     aFailureId = "FEATURE_FAILURE_CANT_RESOLVE_ADAPTER";
1274     *aStatus = FEATURE_BLOCKED_DEVICE;
1275     return NS_OK;
1276   }
1277 
1278   // Check if the device is blocked from the downloaded blocklist. If not, check
1279   // the static list after that. This order is used so that we can later escape
1280   // out of static blocks (i.e. if we were wrong or something was patched, we
1281   // can back out our static block without doing a release).
1282   int32_t status;
1283   if (aDriverInfo.Length()) {
1284     status =
1285         FindBlocklistedDeviceInList(aDriverInfo, aSuggestedVersion, aFeature,
1286                                     aFailureId, os, /* aForAllowing */ false);
1287   } else {
1288     if (!sDriverInfo) {
1289       sDriverInfo = new nsTArray<GfxDriverInfo>();
1290     }
1291     status = FindBlocklistedDeviceInList(GetGfxDriverInfo(), aSuggestedVersion,
1292                                          aFeature, aFailureId, os,
1293                                          /* aForAllowing */ false);
1294   }
1295 
1296   if (status == nsIGfxInfo::FEATURE_STATUS_UNKNOWN) {
1297     if (IsFeatureAllowlisted(aFeature)) {
1298       // This feature is actually using the allowlist; that means after we pass
1299       // the blocklist to prevent us explicitly from getting the feature, we now
1300       // need to check the allowlist to ensure we are allowed to get it in the
1301       // first place.
1302       if (aDriverInfo.Length()) {
1303         status = FindBlocklistedDeviceInList(aDriverInfo, aSuggestedVersion,
1304                                              aFeature, aFailureId, os,
1305                                              /* aForAllowing */ true);
1306       } else {
1307         status = FindBlocklistedDeviceInList(
1308             GetGfxDriverInfo(), aSuggestedVersion, aFeature, aFailureId, os,
1309             /* aForAllowing */ true);
1310       }
1311 
1312       if (status == nsIGfxInfo::FEATURE_STATUS_UNKNOWN) {
1313         status = nsIGfxInfo::FEATURE_DENIED;
1314       }
1315     } else {
1316       // It's now done being processed. It's safe to set the status to
1317       // STATUS_OK.
1318       status = nsIGfxInfo::FEATURE_STATUS_OK;
1319     }
1320   }
1321 
1322   *aStatus = status;
1323   return NS_OK;
1324 }
1325 
1326 NS_IMETHODIMP
GetFeatureSuggestedDriverVersion(int32_t aFeature,nsAString & aVersion)1327 GfxInfoBase::GetFeatureSuggestedDriverVersion(int32_t aFeature,
1328                                               nsAString& aVersion) {
1329   nsCString version;
1330   if (GetPrefValueForDriverVersion(version)) {
1331     aVersion = NS_ConvertASCIItoUTF16(version);
1332     return NS_OK;
1333   }
1334 
1335   int32_t status;
1336   nsCString discardFailureId;
1337   nsTArray<GfxDriverInfo> driverInfo;
1338   return GetFeatureStatusImpl(aFeature, &status, aVersion, driverInfo,
1339                               discardFailureId);
1340 }
1341 
EvaluateDownloadedBlocklist(nsTArray<GfxDriverInfo> & aDriverInfo)1342 void GfxInfoBase::EvaluateDownloadedBlocklist(
1343     nsTArray<GfxDriverInfo>& aDriverInfo) {
1344   int32_t features[] = {nsIGfxInfo::FEATURE_DIRECT2D,
1345                         nsIGfxInfo::FEATURE_DIRECT3D_9_LAYERS,
1346                         nsIGfxInfo::FEATURE_DIRECT3D_10_LAYERS,
1347                         nsIGfxInfo::FEATURE_DIRECT3D_10_1_LAYERS,
1348                         nsIGfxInfo::FEATURE_DIRECT3D_11_LAYERS,
1349                         nsIGfxInfo::FEATURE_DIRECT3D_11_ANGLE,
1350                         nsIGfxInfo::FEATURE_HARDWARE_VIDEO_DECODING,
1351                         nsIGfxInfo::FEATURE_OPENGL_LAYERS,
1352                         nsIGfxInfo::FEATURE_WEBGL_OPENGL,
1353                         nsIGfxInfo::FEATURE_WEBGL_ANGLE,
1354                         nsIGfxInfo::FEATURE_WEBRTC_HW_ACCELERATION_ENCODE,
1355                         nsIGfxInfo::FEATURE_WEBRTC_HW_ACCELERATION_DECODE,
1356                         nsIGfxInfo::UNUSED_FEATURE_WEBGL_MSAA,
1357                         nsIGfxInfo::FEATURE_STAGEFRIGHT,
1358                         nsIGfxInfo::FEATURE_WEBRTC_HW_ACCELERATION_H264,
1359                         nsIGfxInfo::FEATURE_CANVAS2D_ACCELERATION,
1360                         nsIGfxInfo::FEATURE_VP8_HW_DECODE,
1361                         nsIGfxInfo::FEATURE_VP9_HW_DECODE,
1362                         nsIGfxInfo::FEATURE_DX_INTEROP2,
1363                         nsIGfxInfo::FEATURE_GPU_PROCESS,
1364                         nsIGfxInfo::FEATURE_WEBGL2,
1365                         nsIGfxInfo::FEATURE_D3D11_KEYED_MUTEX,
1366                         nsIGfxInfo::FEATURE_WEBRENDER,
1367                         nsIGfxInfo::FEATURE_WEBRENDER_COMPOSITOR,
1368                         nsIGfxInfo::FEATURE_WEBRENDER_SOFTWARE,
1369                         nsIGfxInfo::FEATURE_DX_NV12,
1370                         nsIGfxInfo::FEATURE_DX_P010,
1371                         nsIGfxInfo::FEATURE_DX_P016,
1372                         nsIGfxInfo::FEATURE_GL_SWIZZLE,
1373                         nsIGfxInfo::FEATURE_ALLOW_WEBGL_OUT_OF_PROCESS,
1374                         nsIGfxInfo::FEATURE_X11_EGL,
1375                         nsIGfxInfo::FEATURE_DMABUF,
1376                         0};
1377 
1378   // For every feature we know about, we evaluate whether this blocklist has a
1379   // non-STATUS_OK status. If it does, we set the pref we evaluate in
1380   // GetFeatureStatus above, so we don't need to hold on to this blocklist
1381   // anywhere permanent.
1382   int i = 0;
1383   while (features[i]) {
1384     int32_t status;
1385     nsCString failureId;
1386     nsAutoString suggestedVersion;
1387     if (NS_SUCCEEDED(GetFeatureStatusImpl(
1388             features[i], &status, suggestedVersion, aDriverInfo, failureId))) {
1389       switch (status) {
1390         default:
1391         case nsIGfxInfo::FEATURE_STATUS_OK:
1392           RemovePrefForFeature(features[i]);
1393           break;
1394 
1395         case nsIGfxInfo::FEATURE_BLOCKED_DRIVER_VERSION:
1396           if (!suggestedVersion.IsEmpty()) {
1397             SetPrefValueForDriverVersion(suggestedVersion);
1398           } else {
1399             RemovePrefForDriverVersion();
1400           }
1401           [[fallthrough]];
1402 
1403         case nsIGfxInfo::FEATURE_BLOCKED_MISMATCHED_VERSION:
1404         case nsIGfxInfo::FEATURE_BLOCKED_DEVICE:
1405         case nsIGfxInfo::FEATURE_DISCOURAGED:
1406         case nsIGfxInfo::FEATURE_BLOCKED_OS_VERSION:
1407           SetPrefValueForFeature(features[i], status, failureId);
1408           break;
1409       }
1410     }
1411 
1412     ++i;
1413   }
1414 }
1415 
NS_IMETHODIMP_(void)1416 NS_IMETHODIMP_(void)
1417 GfxInfoBase::LogFailure(const nsACString& failure) {
1418   // gfxCriticalError has a mutex lock of its own, so we may not actually
1419   // need this lock. ::GetFailures() accesses the data but the LogForwarder
1420   // will not return the copy of the logs unless it can get the same lock
1421   // that gfxCriticalError uses.  Still, that is so much of an implementation
1422   // detail that it's nicer to just add an extra lock here and in
1423   // ::GetFailures()
1424   MutexAutoLock lock(mMutex);
1425 
1426   // By default, gfxCriticalError asserts; make it not assert in this case.
1427   gfxCriticalError(CriticalLog::DefaultOptions(false))
1428       << "(LF) " << failure.BeginReading();
1429 }
1430 
GetFailures(nsTArray<int32_t> & indices,nsTArray<nsCString> & failures)1431 NS_IMETHODIMP GfxInfoBase::GetFailures(nsTArray<int32_t>& indices,
1432                                        nsTArray<nsCString>& failures) {
1433   MutexAutoLock lock(mMutex);
1434 
1435   LogForwarder* logForwarder = Factory::GetLogForwarder();
1436   if (!logForwarder) {
1437     return NS_ERROR_UNEXPECTED;
1438   }
1439 
1440   // There are two string copies in this method, starting with this one. We are
1441   // assuming this is not a big deal, as the size of the array should be small
1442   // and the strings in it should be small as well (the error messages in the
1443   // code.)  The second copy happens with the AppendElement() calls.
1444   // Technically, we don't need the mutex lock after the StringVectorCopy()
1445   // call.
1446   LoggingRecord loggedStrings = logForwarder->LoggingRecordCopy();
1447   LoggingRecord::const_iterator it;
1448   for (it = loggedStrings.begin(); it != loggedStrings.end(); ++it) {
1449     failures.AppendElement(
1450         nsDependentCSubstring(Get<1>(*it).c_str(), Get<1>(*it).size()));
1451     indices.AppendElement(Get<0>(*it));
1452   }
1453 
1454   return NS_OK;
1455 }
1456 
1457 nsTArray<GfxInfoCollectorBase*>* sCollectors;
1458 
InitCollectors()1459 static void InitCollectors() {
1460   if (!sCollectors) sCollectors = new nsTArray<GfxInfoCollectorBase*>;
1461 }
1462 
GetInfo(JSContext * aCx,JS::MutableHandle<JS::Value> aResult)1463 nsresult GfxInfoBase::GetInfo(JSContext* aCx,
1464                               JS::MutableHandle<JS::Value> aResult) {
1465   InitCollectors();
1466   InfoObject obj(aCx);
1467 
1468   for (uint32_t i = 0; i < sCollectors->Length(); i++) {
1469     (*sCollectors)[i]->GetInfo(obj);
1470   }
1471 
1472   // Some example property definitions
1473   // obj.DefineProperty("wordCacheSize", gfxTextRunWordCache::Count());
1474   // obj.DefineProperty("renderer", mRendererIDsString);
1475   // obj.DefineProperty("five", 5);
1476 
1477   if (!obj.mOk) {
1478     return NS_ERROR_FAILURE;
1479   }
1480 
1481   aResult.setObject(*obj.mObj);
1482   return NS_OK;
1483 }
1484 
1485 nsAutoCString gBaseAppVersion;
1486 
GetApplicationVersion()1487 const nsCString& GfxInfoBase::GetApplicationVersion() {
1488   static bool versionInitialized = false;
1489   if (!versionInitialized) {
1490     // If we fail to get the version, we will not try again.
1491     versionInitialized = true;
1492 
1493     // Get the version from xpcom/system/nsIXULAppInfo.idl
1494     nsCOMPtr<nsIXULAppInfo> app = do_GetService("@mozilla.org/xre/app-info;1");
1495     if (app) {
1496       app->GetVersion(gBaseAppVersion);
1497     }
1498   }
1499   return gBaseAppVersion;
1500 }
1501 
AddCollector(GfxInfoCollectorBase * collector)1502 void GfxInfoBase::AddCollector(GfxInfoCollectorBase* collector) {
1503   InitCollectors();
1504   sCollectors->AppendElement(collector);
1505 }
1506 
RemoveCollector(GfxInfoCollectorBase * collector)1507 void GfxInfoBase::RemoveCollector(GfxInfoCollectorBase* collector) {
1508   InitCollectors();
1509   for (uint32_t i = 0; i < sCollectors->Length(); i++) {
1510     if ((*sCollectors)[i] == collector) {
1511       sCollectors->RemoveElementAt(i);
1512       break;
1513     }
1514   }
1515   if (sCollectors->IsEmpty()) {
1516     delete sCollectors;
1517     sCollectors = nullptr;
1518   }
1519 }
1520 
FindMonitors(JSContext * aCx,JS::HandleObject aOutArray)1521 nsresult GfxInfoBase::FindMonitors(JSContext* aCx, JS::HandleObject aOutArray) {
1522   // If we have no platform specific implementation for detecting monitors, we
1523   // can just get the screen size from gfxPlatform as the best guess.
1524   if (!gfxPlatform::Initialized()) {
1525     return NS_OK;
1526   }
1527 
1528   // If the screen size is empty, we are probably in xpcshell.
1529   gfx::IntSize screenSize = gfxPlatform::GetPlatform()->GetScreenSize();
1530 
1531   JS::Rooted<JSObject*> obj(aCx, JS_NewPlainObject(aCx));
1532 
1533   JS::Rooted<JS::Value> screenWidth(aCx, JS::Int32Value(screenSize.width));
1534   JS_SetProperty(aCx, obj, "screenWidth", screenWidth);
1535 
1536   JS::Rooted<JS::Value> screenHeight(aCx, JS::Int32Value(screenSize.height));
1537   JS_SetProperty(aCx, obj, "screenHeight", screenHeight);
1538 
1539   JS::Rooted<JS::Value> element(aCx, JS::ObjectValue(*obj));
1540   JS_SetElement(aCx, aOutArray, 0, element);
1541 
1542   return NS_OK;
1543 }
1544 
1545 NS_IMETHODIMP
GetMonitors(JSContext * aCx,JS::MutableHandleValue aResult)1546 GfxInfoBase::GetMonitors(JSContext* aCx, JS::MutableHandleValue aResult) {
1547   JS::Rooted<JSObject*> array(aCx, JS::NewArrayObject(aCx, 0));
1548 
1549   nsresult rv = FindMonitors(aCx, array);
1550   if (NS_FAILED(rv)) {
1551     return rv;
1552   }
1553 
1554   aResult.setObject(*array);
1555   return NS_OK;
1556 }
1557 
1558 NS_IMETHODIMP
RefreshMonitors()1559 GfxInfoBase::RefreshMonitors() { return NS_ERROR_NOT_IMPLEMENTED; }
1560 
SetJSPropertyString(JSContext * aCx,JS::Handle<JSObject * > aObj,const char * aProp,const char * aString)1561 static inline bool SetJSPropertyString(JSContext* aCx,
1562                                        JS::Handle<JSObject*> aObj,
1563                                        const char* aProp, const char* aString) {
1564   JS::Rooted<JSString*> str(aCx, JS_NewStringCopyZ(aCx, aString));
1565   if (!str) {
1566     return false;
1567   }
1568 
1569   JS::Rooted<JS::Value> val(aCx, JS::StringValue(str));
1570   return JS_SetProperty(aCx, aObj, aProp, val);
1571 }
1572 
1573 template <typename T>
AppendJSElement(JSContext * aCx,JS::Handle<JSObject * > aObj,const T & aValue)1574 static inline bool AppendJSElement(JSContext* aCx, JS::Handle<JSObject*> aObj,
1575                                    const T& aValue) {
1576   uint32_t index;
1577   if (!JS::GetArrayLength(aCx, aObj, &index)) {
1578     return false;
1579   }
1580   return JS_SetElement(aCx, aObj, index, aValue);
1581 }
1582 
GetFeatures(JSContext * aCx,JS::MutableHandle<JS::Value> aOut)1583 nsresult GfxInfoBase::GetFeatures(JSContext* aCx,
1584                                   JS::MutableHandle<JS::Value> aOut) {
1585   JS::Rooted<JSObject*> obj(aCx, JS_NewPlainObject(aCx));
1586   if (!obj) {
1587     return NS_ERROR_OUT_OF_MEMORY;
1588   }
1589   aOut.setObject(*obj);
1590 
1591   layers::LayersBackend backend =
1592       gfxPlatform::Initialized()
1593           ? gfxPlatform::GetPlatform()->GetCompositorBackend()
1594           : layers::LayersBackend::LAYERS_NONE;
1595   const char* backendName = layers::GetLayersBackendName(backend);
1596   SetJSPropertyString(aCx, obj, "compositor", backendName);
1597 
1598   // If graphics isn't initialized yet, just stop now.
1599   if (!gfxPlatform::Initialized()) {
1600     return NS_OK;
1601   }
1602 
1603   DescribeFeatures(aCx, obj);
1604   return NS_OK;
1605 }
1606 
GetFeatureLog(JSContext * aCx,JS::MutableHandle<JS::Value> aOut)1607 nsresult GfxInfoBase::GetFeatureLog(JSContext* aCx,
1608                                     JS::MutableHandle<JS::Value> aOut) {
1609   JS::Rooted<JSObject*> containerObj(aCx, JS_NewPlainObject(aCx));
1610   if (!containerObj) {
1611     return NS_ERROR_OUT_OF_MEMORY;
1612   }
1613   aOut.setObject(*containerObj);
1614 
1615   JS::Rooted<JSObject*> featureArray(aCx, JS::NewArrayObject(aCx, 0));
1616   if (!featureArray) {
1617     return NS_ERROR_OUT_OF_MEMORY;
1618   }
1619 
1620   // Collect features.
1621   gfxConfig::ForEachFeature([&](const char* aName, const char* aDescription,
1622                                 FeatureState& aFeature) -> void {
1623     JS::Rooted<JSObject*> obj(aCx, JS_NewPlainObject(aCx));
1624     if (!obj) {
1625       return;
1626     }
1627     if (!SetJSPropertyString(aCx, obj, "name", aName) ||
1628         !SetJSPropertyString(aCx, obj, "description", aDescription) ||
1629         !SetJSPropertyString(aCx, obj, "status",
1630                              FeatureStatusToString(aFeature.GetValue()))) {
1631       return;
1632     }
1633 
1634     JS::Rooted<JS::Value> log(aCx);
1635     if (!BuildFeatureStateLog(aCx, aFeature, &log)) {
1636       return;
1637     }
1638     if (!JS_SetProperty(aCx, obj, "log", log)) {
1639       return;
1640     }
1641 
1642     if (!AppendJSElement(aCx, featureArray, obj)) {
1643       return;
1644     }
1645   });
1646 
1647   JS::Rooted<JSObject*> fallbackArray(aCx, JS::NewArrayObject(aCx, 0));
1648   if (!fallbackArray) {
1649     return NS_ERROR_OUT_OF_MEMORY;
1650   }
1651 
1652   // Collect fallbacks.
1653   gfxConfig::ForEachFallback(
1654       [&](const char* aName, const char* aMessage) -> void {
1655         JS::Rooted<JSObject*> obj(aCx, JS_NewPlainObject(aCx));
1656         if (!obj) {
1657           return;
1658         }
1659 
1660         if (!SetJSPropertyString(aCx, obj, "name", aName) ||
1661             !SetJSPropertyString(aCx, obj, "message", aMessage)) {
1662           return;
1663         }
1664 
1665         if (!AppendJSElement(aCx, fallbackArray, obj)) {
1666           return;
1667         }
1668       });
1669 
1670   JS::Rooted<JS::Value> val(aCx);
1671 
1672   val = JS::ObjectValue(*featureArray);
1673   JS_SetProperty(aCx, containerObj, "features", val);
1674 
1675   val = JS::ObjectValue(*fallbackArray);
1676   JS_SetProperty(aCx, containerObj, "fallbacks", val);
1677 
1678   return NS_OK;
1679 }
1680 
BuildFeatureStateLog(JSContext * aCx,const FeatureState & aFeature,JS::MutableHandle<JS::Value> aOut)1681 bool GfxInfoBase::BuildFeatureStateLog(JSContext* aCx,
1682                                        const FeatureState& aFeature,
1683                                        JS::MutableHandle<JS::Value> aOut) {
1684   JS::Rooted<JSObject*> log(aCx, JS::NewArrayObject(aCx, 0));
1685   if (!log) {
1686     return false;
1687   }
1688   aOut.setObject(*log);
1689 
1690   aFeature.ForEachStatusChange([&](const char* aType, FeatureStatus aStatus,
1691                                    const char* aMessage,
1692                                    const nsCString& aFailureId) -> void {
1693     JS::Rooted<JSObject*> obj(aCx, JS_NewPlainObject(aCx));
1694     if (!obj) {
1695       return;
1696     }
1697 
1698     if (!SetJSPropertyString(aCx, obj, "type", aType) ||
1699         !SetJSPropertyString(aCx, obj, "status",
1700                              FeatureStatusToString(aStatus)) ||
1701         (aMessage && !SetJSPropertyString(aCx, obj, "message", aMessage))) {
1702       return;
1703     }
1704 
1705     if (!AppendJSElement(aCx, log, obj)) {
1706       return;
1707     }
1708   });
1709 
1710   return true;
1711 }
1712 
DescribeFeatures(JSContext * aCx,JS::Handle<JSObject * > aObj)1713 void GfxInfoBase::DescribeFeatures(JSContext* aCx, JS::Handle<JSObject*> aObj) {
1714   JS::Rooted<JSObject*> obj(aCx);
1715 
1716   gfx::FeatureState& hwCompositing =
1717       gfxConfig::GetFeature(gfx::Feature::HW_COMPOSITING);
1718   InitFeatureObject(aCx, aObj, "hwCompositing", hwCompositing, &obj);
1719 
1720   gfx::FeatureState& gpuProcess =
1721       gfxConfig::GetFeature(gfx::Feature::GPU_PROCESS);
1722   InitFeatureObject(aCx, aObj, "gpuProcess", gpuProcess, &obj);
1723 
1724   gfx::FeatureState& wrQualified =
1725       gfxConfig::GetFeature(gfx::Feature::WEBRENDER_QUALIFIED);
1726   InitFeatureObject(aCx, aObj, "wrQualified", wrQualified, &obj);
1727 
1728   gfx::FeatureState& webrender = gfxConfig::GetFeature(gfx::Feature::WEBRENDER);
1729   InitFeatureObject(aCx, aObj, "webrender", webrender, &obj);
1730 
1731   gfx::FeatureState& wrCompositor =
1732       gfxConfig::GetFeature(gfx::Feature::WEBRENDER_COMPOSITOR);
1733   InitFeatureObject(aCx, aObj, "wrCompositor", wrCompositor, &obj);
1734 
1735   gfx::FeatureState& wrSoftware =
1736       gfxConfig::GetFeature(gfx::Feature::WEBRENDER_SOFTWARE);
1737   InitFeatureObject(aCx, aObj, "wrSoftware", wrSoftware, &obj);
1738 
1739   gfx::FeatureState& openglCompositing =
1740       gfxConfig::GetFeature(gfx::Feature::OPENGL_COMPOSITING);
1741   InitFeatureObject(aCx, aObj, "openglCompositing", openglCompositing, &obj);
1742 
1743   gfx::FeatureState& omtp = gfxConfig::GetFeature(gfx::Feature::OMTP);
1744   InitFeatureObject(aCx, aObj, "omtp", omtp, &obj);
1745 }
1746 
InitFeatureObject(JSContext * aCx,JS::Handle<JSObject * > aContainer,const char * aName,mozilla::gfx::FeatureState & aFeatureState,JS::MutableHandle<JSObject * > aOutObj)1747 bool GfxInfoBase::InitFeatureObject(JSContext* aCx,
1748                                     JS::Handle<JSObject*> aContainer,
1749                                     const char* aName,
1750                                     mozilla::gfx::FeatureState& aFeatureState,
1751                                     JS::MutableHandle<JSObject*> aOutObj) {
1752   JS::Rooted<JSObject*> obj(aCx, JS_NewPlainObject(aCx));
1753   if (!obj) {
1754     return false;
1755   }
1756 
1757   nsCString status = aFeatureState.GetStatusAndFailureIdString();
1758 
1759   JS::Rooted<JSString*> str(aCx, JS_NewStringCopyZ(aCx, status.get()));
1760   JS::Rooted<JS::Value> val(aCx, JS::StringValue(str));
1761   JS_SetProperty(aCx, obj, "status", val);
1762 
1763   // Add the feature object to the container.
1764   {
1765     JS::Rooted<JS::Value> val(aCx, JS::ObjectValue(*obj));
1766     JS_SetProperty(aCx, aContainer, aName, val);
1767   }
1768 
1769   aOutObj.set(obj);
1770   return true;
1771 }
1772 
GetActiveCrashGuards(JSContext * aCx,JS::MutableHandle<JS::Value> aOut)1773 nsresult GfxInfoBase::GetActiveCrashGuards(JSContext* aCx,
1774                                            JS::MutableHandle<JS::Value> aOut) {
1775   JS::Rooted<JSObject*> array(aCx, JS::NewArrayObject(aCx, 0));
1776   if (!array) {
1777     return NS_ERROR_OUT_OF_MEMORY;
1778   }
1779   aOut.setObject(*array);
1780 
1781   DriverCrashGuard::ForEachActiveCrashGuard(
1782       [&](const char* aName, const char* aPrefName) -> void {
1783         JS::Rooted<JSObject*> obj(aCx, JS_NewPlainObject(aCx));
1784         if (!obj) {
1785           return;
1786         }
1787         if (!SetJSPropertyString(aCx, obj, "type", aName)) {
1788           return;
1789         }
1790         if (!SetJSPropertyString(aCx, obj, "prefName", aPrefName)) {
1791           return;
1792         }
1793         if (!AppendJSElement(aCx, array, obj)) {
1794           return;
1795         }
1796       });
1797 
1798   return NS_OK;
1799 }
1800 
1801 NS_IMETHODIMP
GetWebRenderEnabled(bool * aWebRenderEnabled)1802 GfxInfoBase::GetWebRenderEnabled(bool* aWebRenderEnabled) {
1803   *aWebRenderEnabled = gfxVars::UseWebRender();
1804   return NS_OK;
1805 }
1806 
1807 NS_IMETHODIMP
GetUsesTiling(bool * aUsesTiling)1808 GfxInfoBase::GetUsesTiling(bool* aUsesTiling) {
1809   *aUsesTiling = gfxPlatform::GetPlatform()->UsesTiling();
1810   return NS_OK;
1811 }
1812 
1813 NS_IMETHODIMP
GetContentUsesTiling(bool * aUsesTiling)1814 GfxInfoBase::GetContentUsesTiling(bool* aUsesTiling) {
1815   *aUsesTiling = gfxPlatform::GetPlatform()->ContentUsesTiling();
1816   return NS_OK;
1817 }
1818 
1819 NS_IMETHODIMP
GetOffMainThreadPaintEnabled(bool * aOffMainThreadPaintEnabled)1820 GfxInfoBase::GetOffMainThreadPaintEnabled(bool* aOffMainThreadPaintEnabled) {
1821   *aOffMainThreadPaintEnabled = gfxConfig::IsEnabled(gfx::Feature::OMTP);
1822   return NS_OK;
1823 }
1824 
1825 NS_IMETHODIMP
GetOffMainThreadPaintWorkerCount(int32_t * aOffMainThreadPaintWorkerCount)1826 GfxInfoBase::GetOffMainThreadPaintWorkerCount(
1827     int32_t* aOffMainThreadPaintWorkerCount) {
1828   if (gfxConfig::IsEnabled(gfx::Feature::OMTP)) {
1829     *aOffMainThreadPaintWorkerCount =
1830         layers::PaintThread::CalculatePaintWorkerCount();
1831   } else {
1832     *aOffMainThreadPaintWorkerCount = 0;
1833   }
1834   return NS_OK;
1835 }
1836 
1837 NS_IMETHODIMP
GetTargetFrameRate(uint32_t * aTargetFrameRate)1838 GfxInfoBase::GetTargetFrameRate(uint32_t* aTargetFrameRate) {
1839   *aTargetFrameRate = gfxPlatform::TargetFrameRate();
1840   return NS_OK;
1841 }
1842 
1843 NS_IMETHODIMP
GetIsHeadless(bool * aIsHeadless)1844 GfxInfoBase::GetIsHeadless(bool* aIsHeadless) {
1845   *aIsHeadless = gfxPlatform::IsHeadless();
1846   return NS_OK;
1847 }
1848 
1849 NS_IMETHODIMP
GetContentBackend(nsAString & aContentBackend)1850 GfxInfoBase::GetContentBackend(nsAString& aContentBackend) {
1851   BackendType backend = gfxPlatform::GetPlatform()->GetDefaultContentBackend();
1852   nsString outStr;
1853 
1854   switch (backend) {
1855     case BackendType::DIRECT2D1_1: {
1856       outStr.AppendPrintf("Direct2D 1.1");
1857       break;
1858     }
1859     case BackendType::SKIA: {
1860       outStr.AppendPrintf("Skia");
1861       break;
1862     }
1863     case BackendType::CAIRO: {
1864       outStr.AppendPrintf("Cairo");
1865       break;
1866     }
1867     default:
1868       return NS_ERROR_FAILURE;
1869   }
1870 
1871   aContentBackend.Assign(outStr);
1872   return NS_OK;
1873 }
1874 
1875 NS_IMETHODIMP
GetAzureCanvasBackend(nsAString & aBackend)1876 GfxInfoBase::GetAzureCanvasBackend(nsAString& aBackend) {
1877   CopyASCIItoUTF16(mozilla::MakeStringSpan(
1878                        gfxPlatform::GetPlatform()->GetAzureCanvasBackend()),
1879                    aBackend);
1880   return NS_OK;
1881 }
1882 
1883 NS_IMETHODIMP
GetAzureContentBackend(nsAString & aBackend)1884 GfxInfoBase::GetAzureContentBackend(nsAString& aBackend) {
1885   CopyASCIItoUTF16(mozilla::MakeStringSpan(
1886                        gfxPlatform::GetPlatform()->GetAzureContentBackend()),
1887                    aBackend);
1888   return NS_OK;
1889 }
1890 
1891 NS_IMETHODIMP
GetUsingGPUProcess(bool * aOutValue)1892 GfxInfoBase::GetUsingGPUProcess(bool* aOutValue) {
1893   GPUProcessManager* gpu = GPUProcessManager::Get();
1894   if (!gpu) {
1895     // Not supported in content processes.
1896     return NS_ERROR_FAILURE;
1897   }
1898 
1899   *aOutValue = !!gpu->GetGPUChild();
1900   return NS_OK;
1901 }
1902 
1903 NS_IMETHODIMP
ControlGPUProcessForXPCShell(bool aEnable,bool * _retval)1904 GfxInfoBase::ControlGPUProcessForXPCShell(bool aEnable, bool* _retval) {
1905   gfxPlatform::GetPlatform();
1906 
1907   GPUProcessManager* gpm = GPUProcessManager::Get();
1908   if (aEnable) {
1909     if (!gfxConfig::IsEnabled(gfx::Feature::GPU_PROCESS)) {
1910       gfxConfig::UserForceEnable(gfx::Feature::GPU_PROCESS, "xpcshell-test");
1911     }
1912     gpm->LaunchGPUProcess();
1913     gpm->EnsureGPUReady();
1914   } else {
1915     gfxConfig::UserDisable(gfx::Feature::GPU_PROCESS, "xpcshell-test");
1916     gpm->KillProcess();
1917   }
1918 
1919   *_retval = true;
1920   return NS_OK;
1921 }
1922 
GfxInfoCollectorBase()1923 GfxInfoCollectorBase::GfxInfoCollectorBase() {
1924   GfxInfoBase::AddCollector(this);
1925 }
1926 
~GfxInfoCollectorBase()1927 GfxInfoCollectorBase::~GfxInfoCollectorBase() {
1928   GfxInfoBase::RemoveCollector(this);
1929 }
1930