Title: [294017] trunk/Source/_javascript_Core
Revision
294017
Author
[email protected]
Date
2022-05-10 14:55:45 -0700 (Tue, 10 May 2022)

Log Message

Add optional Integrity checks at JSC API boundaries.
https://bugs.webkit.org/show_bug.cgi?id=240264

Reviewed by Yusuke Suzuki.

1. Defined ENABLE_EXTRA_INTEGRITY_CHECKS in Integrity.h.  JSC developers can enable
   this for their local build if they want to enable more prolific Integrity audits.
   This is disabled by default.

   This feature is currently only supported for USE(JSVALUE64) targets.

The following changes only take effect if ENABLE(EXTRA_INTEGRITY_CHECKS) is enabled.
Otherwise, these are no-ops.

2. Added Integrity audits to all toJS and toRef conversion functions in APICast.h.
   This will help us detect if bad values are passed across the API boundary.

3. Added some Integrity audits in JSValue.mm where the APICast ones were insufficient.

The following changes are in effect even when ENABLE(EXTRA_INTEGRITY_CHECKS) is
disabled.  Some of these were made to support ENABLE(EXTRA_INTEGRITY_CHECKS), and
some are just clean up in related code that I had to touch along the way.

4. Moved isSanePointer() to Integrity.h so that it can be used in more places.

5. Changed VM registration with the VMInspector so that it's registered earlier
   and removed later.  Integrity audits may need to audit VM pointers while the
   VM is being constructed and destructed.

6. Added VM::m_isInService to track when the VM is fully constructed or about to
   be destructed since the VM is now registered with the VMInspector differently
   (see (4) above).  Applied this check in places that need it.

7. Fixed VMInspector::isValidExecutableMemory() to check the ExecutableAllocator
   directly without iterating VMs (which is completely unnecessary).

8. Fixed VMInspector::isValidExecutableMemory() and VMInspector::codeBlockForMachinePC()
   to use AdoptLock.  This fixes a race condition where the lock can be contended
   after ensureIsSafeToLock() succeeds.

9. Added VMInspector::isValidVM() to check if a VM pointer is registered or not.
   VMInspector caches the most recently added or found VM so that isValidVM()
   can just check the cache for its fast path.

10. Moved the implementation of VMInspector::verifyCell() to Integrity::analyzeCell()
    and add more checks to it.  VMInspector::verifyCell() now calls Integrity::verifyCell()
    which uses Integrity::analyzeCell() to do the real cell analysis.

11. Also strengten Integrity::auditStructureID() so that it will check if a
    Structure's memory has been released.  This change is enabled on Debug builds
    by default as well as when ENABLE(EXTRA_INTEGRITY_CHECKS).  It is disabled
    on Release builds.

* API/APICast.h:
(toJS):
(toJSForGC):
(uncheckedToJS):
(toRef):
(toGlobalRef):
* API/JSContext.mm:
* API/JSContextRef.cpp:
* API/JSScript.mm:
* API/JSValue.mm:
(ObjcContainerConvertor::convert):
(objectToValueWithoutCopy):
(objectToValue):
* API/JSVirtualMachine.mm:
* API/JSWeakPrivate.cpp:
* API/glib/JSCContext.cpp:
* API/glib/JSCWrapperMap.cpp:
* API/tests/JSObjectGetProxyTargetTest.cpp:
* bytecode/SpeculatedType.cpp:
(JSC::speculationFromCell):
(JSC::isSanePointer): Deleted.
* heap/HeapFinalizerCallback.cpp:
* heap/WeakSet.h:
* runtime/Structure.h:
* runtime/VM.cpp:
(JSC::VM::VM):
(JSC::VM::~VM):
* runtime/VM.h:
(JSC::VM::isInService const):
* tools/HeapVerifier.cpp:
(JSC::HeapVerifier::checkIfRecorded):
* tools/Integrity.cpp:
(JSC::Integrity::Random::reloadAndCheckShouldAuditSlow):
(JSC::Integrity::auditCellMinimallySlow):
(JSC::Integrity::doAudit):
(JSC::Integrity::Analyzer::analyzeVM):
(JSC::Integrity::Analyzer::analyzeCell):
(JSC::Integrity::doAuditSlow):
(JSC::Integrity::verifyCell):
(): Deleted.
(JSC::Integrity::auditCellFully): Deleted.
* tools/Integrity.h:
(JSC::isSanePointer):
(JSC::Integrity::auditCell):
(JSC::Integrity::audit):
* tools/IntegrityInlines.h:
(JSC::Integrity::auditCell):
(JSC::Integrity::auditCellFully):
(JSC::Integrity::auditStructureID):
(JSC::Integrity::doAudit):
* tools/VMInspector.cpp:
(JSC::VMInspector::add):
(JSC::VMInspector::remove):
(JSC::VMInspector::isValidVMSlow):
(JSC::VMInspector::dumpVMs):
(JSC::VMInspector::isValidExecutableMemory):
(JSC::VMInspector::codeBlockForMachinePC):
(JSC::ensureIsSafeToLock): Deleted.
* tools/VMInspector.h:
(JSC::VMInspector::isValidVM):
(): Deleted.
(JSC::VMInspector::unusedVerifier): Deleted.
* tools/VMInspectorInlines.h:
(JSC::VMInspector::verifyCell):
(JSC::VMInspector::verifyCellSize): Deleted.

Modified Paths

Diff

Modified: trunk/Source/_javascript_Core/API/APICast.h (294016 => 294017)


--- trunk/Source/_javascript_Core/API/APICast.h	2022-05-10 21:15:45 UTC (rev 294016)
+++ trunk/Source/_javascript_Core/API/APICast.h	2022-05-10 21:55:45 UTC (rev 294017)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2006-2019 Apple Inc.  All rights reserved.
+ * Copyright (C) 2006-2022 Apple Inc.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -26,6 +26,7 @@
 #ifndef APICast_h
 #define APICast_h
 
+#include "Integrity.h"
 #include "JSAPIValueWrapper.h"
 #include "JSCJSValue.h"
 #include "JSCJSValueInlines.h"
@@ -52,13 +53,13 @@
 inline JSC::JSGlobalObject* toJS(JSContextRef context)
 {
     ASSERT(context);
-    return reinterpret_cast<JSC::JSGlobalObject*>(const_cast<OpaqueJSContext*>(context));
+    return JSC::Integrity::audit(reinterpret_cast<JSC::JSGlobalObject*>(const_cast<OpaqueJSContext*>(context)));
 }
 
 inline JSC::JSGlobalObject* toJS(JSGlobalContextRef context)
 {
     ASSERT(context);
-    return reinterpret_cast<JSC::JSGlobalObject*>(context);
+    return JSC::Integrity::audit(reinterpret_cast<JSC::JSGlobalObject*>(context));
 }
 
 inline JSC::JSGlobalObject* toJSGlobalObject(JSGlobalContextRef context)
@@ -83,8 +84,10 @@
 #endif
     if (!result)
         return JSC::jsNull();
-    if (result.isCell())
+    if (result.isCell()) {
+        JSC::Integrity::audit(result.asCell());
         RELEASE_ASSERT(result.asCell()->methodTable());
+    }
     return result;
 }
 
@@ -91,7 +94,7 @@
 #if CPU(ADDRESS64)
 inline JSC::JSValue toJS(JSValueRef value)
 {
-    return bitwise_cast<JSC::JSValue>(value);
+    return JSC::Integrity::audit(bitwise_cast<JSC::JSValue>(value));
 }
 #endif
 
@@ -106,8 +109,10 @@
 #else
     JSC::JSValue result = bitwise_cast<JSC::JSValue>(v);
 #endif
-    if (result && result.isCell())
+    if (result && result.isCell()) {
+        JSC::Integrity::audit(result.asCell());
         RELEASE_ASSERT(result.asCell()->methodTable());
+    }
     return result;
 }
 
@@ -114,7 +119,7 @@
 // Used in JSObjectGetPrivate as that may be called during finalization
 inline JSC::JSObject* uncheckedToJS(JSObjectRef o)
 {
-    return reinterpret_cast<JSC::JSObject*>(o);
+    return JSC::Integrity::audit(reinterpret_cast<JSC::JSObject*>(o));
 }
 
 inline JSC::JSObject* toJS(JSObjectRef o)
@@ -132,7 +137,7 @@
 
 inline JSC::VM* toJS(JSContextGroupRef g)
 {
-    return reinterpret_cast<JSC::VM*>(const_cast<OpaqueJSContextGroup*>(g));
+    return JSC::Integrity::audit(reinterpret_cast<JSC::VM*>(const_cast<OpaqueJSContextGroup*>(g)));
 }
 
 inline JSValueRef toRef(JSC::VM& vm, JSC::JSValue v)
@@ -146,7 +151,7 @@
     return reinterpret_cast<JSValueRef>(v.asCell());
 #else
     UNUSED_PARAM(vm);
-    return bitwise_cast<JSValueRef>(v);
+    return bitwise_cast<JSValueRef>(JSC::Integrity::audit(v));
 #endif
 }
 
@@ -158,28 +163,28 @@
 #if CPU(ADDRESS64)
 inline JSValueRef toRef(JSC::JSValue v)
 {
-    return bitwise_cast<JSValueRef>(v);
+    return bitwise_cast<JSValueRef>(JSC::Integrity::audit(v));
 }
 #endif
 
 inline JSObjectRef toRef(JSC::JSObject* o)
 {
-    return reinterpret_cast<JSObjectRef>(o);
+    return reinterpret_cast<JSObjectRef>(JSC::Integrity::audit(o));
 }
 
 inline JSObjectRef toRef(const JSC::JSObject* o)
 {
-    return reinterpret_cast<JSObjectRef>(const_cast<JSC::JSObject*>(o));
+    return reinterpret_cast<JSObjectRef>(JSC::Integrity::audit(const_cast<JSC::JSObject*>(o)));
 }
 
 inline JSContextRef toRef(JSC::JSGlobalObject* globalObject)
 {
-    return reinterpret_cast<JSContextRef>(globalObject);
+    return reinterpret_cast<JSContextRef>(JSC::Integrity::audit(globalObject));
 }
 
 inline JSGlobalContextRef toGlobalRef(JSC::JSGlobalObject* globalObject)
 {
-    return reinterpret_cast<JSGlobalContextRef>(globalObject);
+    return reinterpret_cast<JSGlobalContextRef>(JSC::Integrity::audit(globalObject));
 }
 
 inline JSPropertyNameAccumulatorRef toRef(JSC::PropertyNameArray* l)
@@ -189,7 +194,7 @@
 
 inline JSContextGroupRef toRef(JSC::VM* g)
 {
-    return reinterpret_cast<JSContextGroupRef>(g);
+    return reinterpret_cast<JSContextGroupRef>(JSC::Integrity::audit(g));
 }
 
 #endif // APICast_h

Modified: trunk/Source/_javascript_Core/API/JSContext.mm (294016 => 294017)


--- trunk/Source/_javascript_Core/API/JSContext.mm	2022-05-10 21:15:45 UTC (rev 294016)
+++ trunk/Source/_javascript_Core/API/JSContext.mm	2022-05-10 21:55:45 UTC (rev 294017)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013-2021 Apple Inc. All rights reserved.
+ * Copyright (C) 2013-2022 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -27,6 +27,7 @@
 
 #import "APICast.h"
 #import "Completion.h"
+#import "IntegrityInlines.h"
 #import "JSBaseInternal.h"
 #import "JSCInlines.h"
 #import "JSContextInternal.h"

Modified: trunk/Source/_javascript_Core/API/JSContextRef.cpp (294016 => 294017)


--- trunk/Source/_javascript_Core/API/JSContextRef.cpp	2022-05-10 21:15:45 UTC (rev 294016)
+++ trunk/Source/_javascript_Core/API/JSContextRef.cpp	2022-05-10 21:55:45 UTC (rev 294017)
@@ -30,6 +30,7 @@
 #include "APICast.h"
 #include "CallFrame.h"
 #include "InitializeThreading.h"
+#include "IntegrityInlines.h"
 #include "JSAPIGlobalObject.h"
 #include "JSAPIWrapperObject.h"
 #include "JSCallbackObject.h"

Modified: trunk/Source/_javascript_Core/API/JSScript.mm (294016 => 294017)


--- trunk/Source/_javascript_Core/API/JSScript.mm	2022-05-10 21:15:45 UTC (rev 294016)
+++ trunk/Source/_javascript_Core/API/JSScript.mm	2022-05-10 21:55:45 UTC (rev 294017)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2019-2020 Apple Inc. All rights reserved.
+ * Copyright (C) 2019-2022 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -31,6 +31,7 @@
 #import "CachedTypes.h"
 #import "CodeCache.h"
 #import "Identifier.h"
+#import "IntegrityInlines.h"
 #import "JSContextInternal.h"
 #import "JSScriptSourceProvider.h"
 #import "JSSourceCode.h"

Modified: trunk/Source/_javascript_Core/API/JSValue.mm (294016 => 294017)


--- trunk/Source/_javascript_Core/API/JSValue.mm	2022-05-10 21:15:45 UTC (rev 294016)
+++ trunk/Source/_javascript_Core/API/JSValue.mm	2022-05-10 21:55:45 UTC (rev 294017)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013-2018 Apple Inc. All rights reserved.
+ * Copyright (C) 2013-2022 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -58,6 +58,8 @@
 
 #if JSC_OBJC_API_ENABLED
 
+using JSC::Integrity::audit;
+
 NSString * const JSPropertyDescriptorWritableKey = @"writable";
 NSString * const JSPropertyDescriptorEnumerableKey = @"enumerable";
 NSString * const JSPropertyDescriptorConfigurableKey = @"configurable";
@@ -970,11 +972,11 @@
 
     auto it = m_objectMap.find(object);
     if (it != m_objectMap.end())
-        return it->value;
+        return audit(it->value);
 
     ObjcContainerConvertor::Task task = objectToValueWithoutCopy(m_context, object);
     add(task);
-    return task.js;
+    return audit(task.js);
 }
 
 void ObjcContainerConvertor::add(ObjcContainerConvertor::Task task)
@@ -1004,7 +1006,7 @@
 
 static ObjcContainerConvertor::Task objectToValueWithoutCopy(JSContext *context, id object)
 {
-    JSGlobalContextRef contextRef = [context JSGlobalContextRef];
+    JSGlobalContextRef contextRef = audit([context JSGlobalContextRef]);
 
     if (!object)
         return { object, JSValueMakeUndefined(contextRef), ContainerNone };
@@ -1056,7 +1058,7 @@
 
     ObjcContainerConvertor::Task task = objectToValueWithoutCopy(context, object);
     if (task.type == ContainerNone)
-        return task.js;
+        return audit(task.js);
 
     JSC::JSLockHolder locker(toJS(contextRef));
     ObjcContainerConvertor convertor(context);
@@ -1087,7 +1089,7 @@
         }
     } while (!convertor.isWorkListEmpty());
 
-    return task.js;
+    return audit(task.js);
 }
 
 JSValueRef valueInternalValue(JSValue * value)

Modified: trunk/Source/_javascript_Core/API/JSVirtualMachine.mm (294016 => 294017)


--- trunk/Source/_javascript_Core/API/JSVirtualMachine.mm	2022-05-10 21:15:45 UTC (rev 294016)
+++ trunk/Source/_javascript_Core/API/JSVirtualMachine.mm	2022-05-10 21:55:45 UTC (rev 294017)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2013-2021 Apple Inc. All rights reserved.
+ * Copyright (C) 2013-2022 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -30,6 +30,7 @@
 #if JSC_OBJC_API_ENABLED
 
 #import "APICast.h"
+#import "IntegrityInlines.h"
 #import "JITWorklist.h"
 #import "JSManagedValueInternal.h"
 #import "JSVirtualMachineInternal.h"

Modified: trunk/Source/_javascript_Core/API/JSWeakPrivate.cpp (294016 => 294017)


--- trunk/Source/_javascript_Core/API/JSWeakPrivate.cpp	2022-05-10 21:15:45 UTC (rev 294016)
+++ trunk/Source/_javascript_Core/API/JSWeakPrivate.cpp	2022-05-10 21:55:45 UTC (rev 294017)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2017 Apple Inc.  All rights reserved.
+ * Copyright (C) 2017-2022 Apple Inc.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -27,6 +27,7 @@
 #include "JSWeakPrivate.h"
 
 #include "APICast.h"
+#include "IntegrityInlines.h"
 #include "Weak.h"
 #include <wtf/ThreadSafeRefCounted.h>
 

Modified: trunk/Source/_javascript_Core/API/glib/JSCContext.cpp (294016 => 294017)


--- trunk/Source/_javascript_Core/API/glib/JSCContext.cpp	2022-05-10 21:15:45 UTC (rev 294016)
+++ trunk/Source/_javascript_Core/API/glib/JSCContext.cpp	2022-05-10 21:55:45 UTC (rev 294017)
@@ -21,6 +21,7 @@
 #include "JSCContext.h"
 
 #include "APICast.h"
+#include "IntegrityInlines.h"
 #include "JSCClassPrivate.h"
 #include "JSCContextInternal.h"
 #include "JSCContextPrivate.h"

Modified: trunk/Source/_javascript_Core/API/glib/JSCWrapperMap.cpp (294016 => 294017)


--- trunk/Source/_javascript_Core/API/glib/JSCWrapperMap.cpp	2022-05-10 21:15:45 UTC (rev 294016)
+++ trunk/Source/_javascript_Core/API/glib/JSCWrapperMap.cpp	2022-05-10 21:55:45 UTC (rev 294017)
@@ -21,6 +21,7 @@
 #include "JSCWrapperMap.h"
 
 #include "APICast.h"
+#include "IntegrityInlines.h"
 #include "JSAPIWrapperGlobalObject.h"
 #include "JSAPIWrapperObject.h"
 #include "JSCClassPrivate.h"

Modified: trunk/Source/_javascript_Core/API/tests/JSObjectGetProxyTargetTest.cpp (294016 => 294017)


--- trunk/Source/_javascript_Core/API/tests/JSObjectGetProxyTargetTest.cpp	2022-05-10 21:15:45 UTC (rev 294016)
+++ trunk/Source/_javascript_Core/API/tests/JSObjectGetProxyTargetTest.cpp	2022-05-10 21:55:45 UTC (rev 294017)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2017-2018 Apple Inc. All rights reserved.
+ * Copyright (C) 2017-2022 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -27,6 +27,7 @@
 #include "JSObjectGetProxyTargetTest.h"
 
 #include "APICast.h"
+#include "IntegrityInlines.h"
 #include "JSCInlines.h"
 #include "JSObjectRefPrivate.h"
 #include "JSProxy.h"

Modified: trunk/Source/_javascript_Core/ChangeLog (294016 => 294017)


--- trunk/Source/_javascript_Core/ChangeLog	2022-05-10 21:15:45 UTC (rev 294016)
+++ trunk/Source/_javascript_Core/ChangeLog	2022-05-10 21:55:45 UTC (rev 294017)
@@ -1,3 +1,124 @@
+2022-05-10  Mark Lam  <[email protected]>
+
+        Add optional Integrity checks at JSC API boundaries.
+        https://bugs.webkit.org/show_bug.cgi?id=240264
+
+        Reviewed by Yusuke Suzuki.
+
+        1. Defined ENABLE_EXTRA_INTEGRITY_CHECKS in Integrity.h.  JSC developers can enable
+           this for their local build if they want to enable more prolific Integrity audits.
+           This is disabled by default.
+
+           This feature is currently only supported for USE(JSVALUE64) targets.
+
+        The following changes only take effect if ENABLE(EXTRA_INTEGRITY_CHECKS) is enabled.
+        Otherwise, these are no-ops.
+
+        2. Added Integrity audits to all toJS and toRef conversion functions in APICast.h.
+           This will help us detect if bad values are passed across the API boundary.
+
+        3. Added some Integrity audits in JSValue.mm where the APICast ones were insufficient.
+
+        The following changes are in effect even when ENABLE(EXTRA_INTEGRITY_CHECKS) is
+        disabled.  Some of these were made to support ENABLE(EXTRA_INTEGRITY_CHECKS), and
+        some are just clean up in related code that I had to touch along the way.
+
+        4. Moved isSanePointer() to Integrity.h so that it can be used in more places.
+
+        5. Changed VM registration with the VMInspector so that it's registered earlier
+           and removed later.  Integrity audits may need to audit VM pointers while the
+           VM is being constructed and destructed.
+
+        6. Added VM::m_isInService to track when the VM is fully constructed or about to
+           be destructed since the VM is now registered with the VMInspector differently
+           (see (4) above).  Applied this check in places that need it.
+
+        7. Fixed VMInspector::isValidExecutableMemory() to check the ExecutableAllocator
+           directly without iterating VMs (which is completely unnecessary).
+
+        8. Fixed VMInspector::isValidExecutableMemory() and VMInspector::codeBlockForMachinePC()
+           to use AdoptLock.  This fixes a race condition where the lock can be contended
+           after ensureIsSafeToLock() succeeds.
+
+        9. Added VMInspector::isValidVM() to check if a VM pointer is registered or not.
+           VMInspector caches the most recently added or found VM so that isValidVM()
+           can just check the cache for its fast path.
+
+        10. Moved the implementation of VMInspector::verifyCell() to Integrity::analyzeCell()
+            and add more checks to it.  VMInspector::verifyCell() now calls Integrity::verifyCell()
+            which uses Integrity::analyzeCell() to do the real cell analysis.
+
+        11. Also strengten Integrity::auditStructureID() so that it will check if a
+            Structure's memory has been released.  This change is enabled on Debug builds
+            by default as well as when ENABLE(EXTRA_INTEGRITY_CHECKS).  It is disabled
+            on Release builds.
+
+        * API/APICast.h:
+        (toJS):
+        (toJSForGC):
+        (uncheckedToJS):
+        (toRef):
+        (toGlobalRef):
+        * API/JSContext.mm:
+        * API/JSContextRef.cpp:
+        * API/JSScript.mm:
+        * API/JSValue.mm:
+        (ObjcContainerConvertor::convert):
+        (objectToValueWithoutCopy):
+        (objectToValue):
+        * API/JSVirtualMachine.mm:
+        * API/JSWeakPrivate.cpp:
+        * API/glib/JSCContext.cpp:
+        * API/glib/JSCWrapperMap.cpp:
+        * API/tests/JSObjectGetProxyTargetTest.cpp:
+        * bytecode/SpeculatedType.cpp:
+        (JSC::speculationFromCell):
+        (JSC::isSanePointer): Deleted.
+        * heap/HeapFinalizerCallback.cpp:
+        * heap/WeakSet.h:
+        * runtime/Structure.h:
+        * runtime/VM.cpp:
+        (JSC::VM::VM):
+        (JSC::VM::~VM):
+        * runtime/VM.h:
+        (JSC::VM::isInService const):
+        * tools/HeapVerifier.cpp:
+        (JSC::HeapVerifier::checkIfRecorded):
+        * tools/Integrity.cpp:
+        (JSC::Integrity::Random::reloadAndCheckShouldAuditSlow):
+        (JSC::Integrity::auditCellMinimallySlow):
+        (JSC::Integrity::doAudit):
+        (JSC::Integrity::Analyzer::analyzeVM):
+        (JSC::Integrity::Analyzer::analyzeCell):
+        (JSC::Integrity::doAuditSlow):
+        (JSC::Integrity::verifyCell):
+        (): Deleted.
+        (JSC::Integrity::auditCellFully): Deleted.
+        * tools/Integrity.h:
+        (JSC::isSanePointer):
+        (JSC::Integrity::auditCell):
+        (JSC::Integrity::audit):
+        * tools/IntegrityInlines.h:
+        (JSC::Integrity::auditCell):
+        (JSC::Integrity::auditCellFully):
+        (JSC::Integrity::auditStructureID):
+        (JSC::Integrity::doAudit):
+        * tools/VMInspector.cpp:
+        (JSC::VMInspector::add):
+        (JSC::VMInspector::remove):
+        (JSC::VMInspector::isValidVMSlow):
+        (JSC::VMInspector::dumpVMs):
+        (JSC::VMInspector::isValidExecutableMemory):
+        (JSC::VMInspector::codeBlockForMachinePC):
+        (JSC::ensureIsSafeToLock): Deleted.
+        * tools/VMInspector.h:
+        (JSC::VMInspector::isValidVM):
+        (): Deleted.
+        (JSC::VMInspector::unusedVerifier): Deleted.
+        * tools/VMInspectorInlines.h:
+        (JSC::VMInspector::verifyCell):
+        (JSC::VMInspector::verifyCellSize): Deleted.
+
 2022-05-09  Ross Kirsling  <[email protected]>
 
         Unreviewed, address Darin's feedback on r250361.

Modified: trunk/Source/_javascript_Core/bytecode/SpeculatedType.cpp (294016 => 294017)


--- trunk/Source/_javascript_Core/bytecode/SpeculatedType.cpp	2022-05-10 21:15:45 UTC (rev 294016)
+++ trunk/Source/_javascript_Core/bytecode/SpeculatedType.cpp	2022-05-10 21:55:45 UTC (rev 294017)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2011-2020 Apple Inc. All rights reserved.
+ * Copyright (C) 2011-2022 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -31,6 +31,7 @@
 
 #include "DateInstance.h"
 #include "DirectArguments.h"
+#include "Integrity.h"
 #include "JSArray.h"
 #include "JSBigInt.h"
 #include "JSBoundFunction.h"
@@ -564,23 +565,10 @@
     return filteredResult;
 }
 
-ALWAYS_INLINE static bool isSanePointer(const void* pointer)
-{
-    // FIXME: rdar://69036888: remove this when no longer needed.
-#if CPU(ADDRESS64)
-    uintptr_t pointerAsInt = bitwise_cast<uintptr_t>(pointer);
-    uintptr_t canonicalPointerBits = pointerAsInt << (64 - OS_CONSTANT(EFFECTIVE_ADDRESS_WIDTH));
-    uintptr_t nonCanonicalPointerBits = pointerAsInt >> OS_CONSTANT(EFFECTIVE_ADDRESS_WIDTH);
-    return !nonCanonicalPointerBits && canonicalPointerBits;
-#else
-    UNUSED_PARAM(pointer);
-    return true;
-#endif
-}
-
 SpeculatedType speculationFromCell(JSCell* cell)
 {
-    if (UNLIKELY(!isSanePointer(cell))) {
+    // FIXME: rdar://69036888: remove isSanePointer checks when no longer needed.
+    if (UNLIKELY(!Integrity::isSanePointer(cell))) {
         ASSERT_NOT_REACHED();
         return SpecNone;
     }
@@ -587,7 +575,7 @@
     if (cell->isString()) {
         JSString* string = jsCast<JSString*>(cell);
         if (const StringImpl* impl = string->tryGetValueImpl()) {
-            if (UNLIKELY(!isSanePointer(impl))) {
+            if (UNLIKELY(!Integrity::isSanePointer(impl))) {
                 ASSERT_NOT_REACHED();
                 return SpecNone;
             }
@@ -598,7 +586,7 @@
     }
     // FIXME: rdar://69036888: undo this when no longer needed.
     auto* structure = cell->structureID().tryDecode();
-    if (UNLIKELY(!isSanePointer(structure))) {
+    if (UNLIKELY(!Integrity::isSanePointer(structure))) {
         ASSERT_NOT_REACHED();
         return SpecNone;
     }

Modified: trunk/Source/_javascript_Core/heap/HeapFinalizerCallback.cpp (294016 => 294017)


--- trunk/Source/_javascript_Core/heap/HeapFinalizerCallback.cpp	2022-05-10 21:15:45 UTC (rev 294016)
+++ trunk/Source/_javascript_Core/heap/HeapFinalizerCallback.cpp	2022-05-10 21:55:45 UTC (rev 294017)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2017 Apple Inc.  All rights reserved.
+ * Copyright (C) 2017-2022 Apple Inc.  All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -27,6 +27,7 @@
 #include "HeapFinalizerCallback.h"
 
 #include "APICast.h"
+#include "IntegrityInlines.h"
 
 namespace JSC {
 

Modified: trunk/Source/_javascript_Core/heap/WeakSet.h (294016 => 294017)


--- trunk/Source/_javascript_Core/heap/WeakSet.h	2022-05-10 21:15:45 UTC (rev 294016)
+++ trunk/Source/_javascript_Core/heap/WeakSet.h	2022-05-10 21:55:45 UTC (rev 294017)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2012-2021 Apple Inc. All rights reserved.
+ * Copyright (C) 2012-2022 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -34,8 +34,13 @@
 class Heap;
 class WeakImpl;
 
+namespace Integrity {
+class Analyzer;
+}
+
 class WeakSet : public BasicRawSentinelNode<WeakSet> {
     friend class LLIntOffsetsExtractor;
+    friend class Integrity::Analyzer;
 
 public:
     static WeakImpl* allocate(JSValue, WeakHandleOwner* = nullptr, void* context = nullptr);

Modified: trunk/Source/_javascript_Core/runtime/Structure.h (294016 => 294017)


--- trunk/Source/_javascript_Core/runtime/Structure.h	2022-05-10 21:15:45 UTC (rev 294016)
+++ trunk/Source/_javascript_Core/runtime/Structure.h	2022-05-10 21:55:45 UTC (rev 294017)
@@ -69,6 +69,10 @@
 struct HashTable;
 struct HashTableValue;
 
+namespace Integrity {
+class Analyzer;
+}
+
 // The out-of-line property storage capacity to use when first allocating out-of-line
 // storage. Note that all objects start out without having any out-of-line storage;
 // this comes into play only on the first property store that exhausts inline storage.
@@ -990,6 +994,7 @@
 
     friend class VMInspector;
     friend class JSDollarVMHelper;
+    friend class Integrity::Analyzer;
 };
 
 } // namespace JSC

Modified: trunk/Source/_javascript_Core/runtime/VM.cpp (294016 => 294017)


--- trunk/Source/_javascript_Core/runtime/VM.cpp	2022-05-10 21:15:45 UTC (rev 294016)
+++ trunk/Source/_javascript_Core/runtime/VM.cpp	2022-05-10 21:55:45 UTC (rev 294017)
@@ -241,6 +241,8 @@
     if (UNLIKELY(vmCreationShouldCrash))
         CRASH_WITH_INFO(0x4242424220202020, 0xbadbeef0badbeef, 0x1234123412341234, 0x1337133713371337);
 
+    VMInspector::instance().add(this);
+
     interpreter = new Interpreter(*this);
     updateSoftReservedZoneSize(Options::softReservedZoneSize());
     setLastStackTop(Thread::current());
@@ -401,10 +403,12 @@
         jitSizeStatistics = makeUnique<JITSizeStatistics>();
 #endif
 
-    VMInspector::instance().add(this);
-
     if (!g_jscConfig.disabledFreezingForTesting)
         Config::permanentlyFreeze();
+
+    // We must set this at the end only after the VM is fully initialized.
+    WTF::storeStoreFence();
+    m_isInService = true;
 }
 
 static ReadWriteLock s_destructionLock;
@@ -427,7 +431,8 @@
     if (UNLIKELY(m_watchdog))
         m_watchdog->willDestroyVM(this);
     m_traps.willDestroyVM();
-    VMInspector::instance().remove(this);
+    m_isInService = false;
+    WTF::storeStoreFence();
 
     // Never GC, ever again.
     heap.incrementDeferralDepth();
@@ -455,7 +460,9 @@
     heap.lastChanceToFinalize();
 
     JSRunLoopTimer::Manager::shared().unregisterVM(*this);
-    
+
+    VMInspector::instance().remove(this);
+
     delete interpreter;
 #ifndef NDEBUG
     interpreter = reinterpret_cast<Interpreter*>(0xbbadbeef);

Modified: trunk/Source/_javascript_Core/runtime/VM.h (294016 => 294017)


--- trunk/Source/_javascript_Core/runtime/VM.h	2022-05-10 21:15:45 UTC (rev 294016)
+++ trunk/Source/_javascript_Core/runtime/VM.h	2022-05-10 21:55:45 UTC (rev 294017)
@@ -346,6 +346,8 @@
     Heap heap;
     GCClient::Heap clientHeap;
 
+    bool isInService() const { return m_isInService; }
+
     const HeapCellType& cellHeapCellType() { return heap.cellHeapCellType; }
     const JSDestructibleObjectHeapCellType& destructibleObjectHeapCellType() { return heap.destructibleObjectHeapCellType; };
 
@@ -945,6 +947,7 @@
     std::unique_ptr<TypeProfilerLog> m_typeProfilerLog;
     unsigned m_typeProfilerEnabledCount;
     bool m_needToFirePrimitiveGigacageEnabled { false };
+    bool m_isInService { false };
     Lock m_scratchBufferLock;
     Vector<ScratchBuffer*> m_scratchBuffers;
     size_t m_sizeOfLastScratchBuffer { 0 };

Modified: trunk/Source/_javascript_Core/tools/HeapVerifier.cpp (294016 => 294017)


--- trunk/Source/_javascript_Core/tools/HeapVerifier.cpp	2022-05-10 21:15:45 UTC (rev 294016)
+++ trunk/Source/_javascript_Core/tools/HeapVerifier.cpp	2022-05-10 21:55:45 UTC (rev 294017)
@@ -443,6 +443,9 @@
     }
     Locker locker { AdoptLock, inspector.getLock() };
     inspector.iterate([&] (VM& vm) {
+        if (!vm.isInService())
+            return IterationStatus::Continue;
+
         if (!vm.heap.m_verifier)
             return IterationStatus::Continue;
         

Modified: trunk/Source/_javascript_Core/tools/Integrity.cpp (294016 => 294017)


--- trunk/Source/_javascript_Core/tools/Integrity.cpp	2022-05-10 21:15:45 UTC (rev 294016)
+++ trunk/Source/_javascript_Core/tools/Integrity.cpp	2022-05-10 21:55:45 UTC (rev 294017)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2019-2021 Apple Inc. All rights reserved.
+ * Copyright (C) 2019-2022 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -26,7 +26,12 @@
 #include "config.h"
 #include "Integrity.h"
 
+#include "APICast.h"
+#include "CellSize.h"
+#include "IntegrityInlines.h"
+#include "JSCast.h"
 #include "JSCellInlines.h"
+#include "JSGlobalObject.h"
 #include "Options.h"
 #include "VMInspectorInlines.h"
 
@@ -33,8 +38,8 @@
 namespace JSC {
 namespace Integrity {
 
-namespace {
-constexpr bool verbose = false;
+namespace IntegrityInternal {
+static constexpr bool verbose = false;
 }
 
 Random::Random(VM& vm)
@@ -48,7 +53,7 @@
 
     if (!Options::randomIntegrityAuditRate()) {
         m_triggerBits = 0; // Never trigger, and don't bother reloading.
-        if (verbose)
+        if (IntegrityInternal::verbose)
             dataLogLn("disabled Integrity audits: trigger bits ", RawPointer(reinterpret_cast<void*>(m_triggerBits)));
         return false;
     }
@@ -61,27 +66,258 @@
         bool trigger = vm.random().getUint32() <= threshold;
         m_triggerBits = m_triggerBits | (static_cast<uint64_t>(trigger) << i);
     }
-    if (verbose)
+    if (IntegrityInternal::verbose)
         dataLogLn("reloaded Integrity trigger bits ", RawPointer(reinterpret_cast<void*>(m_triggerBits)));
     ASSERT(m_triggerBits >= (1ull << 63));
     return vm.random().getUint32() <= threshold;
 }
 
-void auditCellFully(VM& vm, JSCell* cell)
-{
-    VMInspector::verifyCell<VMInspector::ReleaseAssert>(vm, cell);
-}
-
 void auditCellMinimallySlow(VM&, JSCell* cell)
 {
     if (Gigacage::contains(cell)) {
         if (cell->type() != JSImmutableButterflyType) {
-            if (verbose)
-                dataLogLn("Bad cell ", RawPointer(cell), " ", JSValue(cell));
+            if (IntegrityInternal::verbose)
+                dataLogLn("Integrity ERROR: Bad cell ", RawPointer(cell), " ", JSValue(cell));
             CRASH();
         }
     }
 }
 
+#if USE(JSVALUE64)
+
+JSContextRef doAudit(JSContextRef ctx)
+{
+    IA_ASSERT(ctx, "NULL JSContextRef");
+    toJS(ctx); // toJS will trigger an audit.
+    return ctx;
+}
+
+JSGlobalContextRef doAudit(JSGlobalContextRef ctx)
+{
+    IA_ASSERT(ctx, "NULL JSGlobalContextRef");
+    toJS(ctx); // toJS will trigger an audit.
+    return ctx;
+}
+
+JSObjectRef doAudit(JSObjectRef objectRef)
+{
+    if (!objectRef)
+        return objectRef;
+    toJS(objectRef); // toJS will trigger an audit.
+    return objectRef;
+}
+
+JSValueRef doAudit(JSValueRef valueRef)
+{
+#if CPU(ADDRESS64)
+    if (!valueRef)
+        return valueRef;
+    toJS(valueRef); // toJS will trigger an audit.
+#endif
+    return valueRef;
+}
+
+JSValue doAudit(JSValue value)
+{
+    if (value.isCell())
+        doAudit(value.asCell());
+    return value;
+}
+
+bool Analyzer::analyzeVM(VM& vm, Analyzer::Action action)
+{
+    IA_ASSERT_WITH_ACTION(VMInspector::isValidVM(&vm), {
+        VMInspector::dumpVMs();
+        if (action == Action::LogAndCrash)
+            RELEASE_ASSERT(VMInspector::isValidVM(&vm));
+        else
+            return false;
+    }, "Invalid VM %p", &vm);
+    return true;
+}
+
+#if COMPILER(MSVC) || !VA_OPT_SUPPORTED
+
+#define AUDIT_VERIFY(cond, format, ...) do { \
+        IA_ASSERT_WITH_ACTION(cond, { \
+            WTFLogAlways("    cell %p", cell); \
+            if (action == Action::LogAndCrash) \
+                RELEASE_ASSERT((cond), ##__VA_ARGS__); \
+            else \
+                return false; \
+        }, format, ##__VA_ARGS__); \
+    } while (false)
+
+#else // not (COMPILER(MSVC) || !VA_OPT_SUPPORTED)
+
+#define AUDIT_VERIFY(cond, format, ...) do { \
+        IA_ASSERT_WITH_ACTION(cond, { \
+            WTFLogAlways("    cell %p", cell); \
+            if (action == Action::LogAndCrash) \
+                RELEASE_ASSERT((cond) __VA_OPT__(,) __VA_ARGS__); \
+            else \
+                return false; \
+        }, format __VA_OPT__(,) __VA_ARGS__); \
+    } while (false)
+
+#endif // COMPILER(MSVC) || !VA_OPT_SUPPORTED
+
+bool Analyzer::analyzeCell(VM& vm, JSCell* cell, Analyzer::Action action)
+{
+    AUDIT_VERIFY(isSanePointer(cell), "cell %p cell.type %d", cell, cell->type());
+
+    size_t allocatorCellSize = 0;
+    if (cell->isPreciseAllocation()) {
+        PreciseAllocation& preciseAllocation = cell->preciseAllocation();
+        AUDIT_VERIFY(&preciseAllocation.vm() == &vm,
+            "cell %p cell.type %d preciseAllocation.vm %p vm %p", cell, cell->type(), &preciseAllocation.vm(), &vm);
+
+        bool isValidPreciseAllocation = false;
+        for (auto* i : vm.heap.objectSpace().preciseAllocations()) {
+            if (i == &preciseAllocation) {
+                isValidPreciseAllocation = true;
+                break;
+            }
+        }
+        AUDIT_VERIFY(isValidPreciseAllocation, "cell %p cell.type %d", cell, cell->type());
+
+        allocatorCellSize = preciseAllocation.cellSize();
+    } else {
+        MarkedBlock& block = cell->markedBlock();
+        MarkedBlock::Handle& blockHandle = block.handle();
+        AUDIT_VERIFY(&block.vm() == &vm,
+            "cell %p cell.type %d markedBlock.vm %p vm %p", cell, cell->type(), &block.vm(), &vm);
+
+        uintptr_t blockStartAddress = reinterpret_cast<uintptr_t>(blockHandle.start());
+        AUDIT_VERIFY(blockHandle.contains(cell),
+            "cell %p cell.type %d markedBlock.start %p markedBlock.end %p", cell, cell->type(), blockHandle.start(), blockHandle.end());
+
+        uintptr_t cellAddress = reinterpret_cast<uintptr_t>(cell);
+        uintptr_t cellOffset = cellAddress - blockStartAddress;
+        allocatorCellSize = block.cellSize();
+        bool cellIsProperlyAligned = !(cellOffset % allocatorCellSize);
+        AUDIT_VERIFY(cellIsProperlyAligned,
+            "cell %p cell.type %d allocator.cellSize %zu", cell, cell->type(), allocatorCellSize);
+    }
+
+    JSType cellType = cell->type();
+    if (cell->type() != JSImmutableButterflyType)
+        AUDIT_VERIFY(!Gigacage::contains(cell), "cell %p cell.type %d", cell, cellType);
+
+    WeakSet& weakSet = cell->cellContainer().weakSet();
+    AUDIT_VERIFY(!weakSet.m_allocator || isSanePointer(weakSet.m_allocator),
+        "cell %p cell.type %d weakSet.allocator %p", cell, cell->type(), weakSet.m_allocator);
+    AUDIT_VERIFY(!weakSet.m_nextAllocator || isSanePointer(weakSet.m_nextAllocator),
+        "cell %p cell.type %d weakSet.allocator %p", cell, cell->type(), weakSet.m_nextAllocator);
+
+    // If we're currently destructing the cell, then we can't rely on its
+    // structure being good. Skip the following tests which rely on structure.
+    if (vm.currentlyDestructingCallbackObject == cell)
+        return true;
+
+    auto structureID = cell->structureID();
+
+    Structure* structure = structureID.tryDecode();
+    AUDIT_VERIFY(structure,
+        "cell %p cell.type %d structureID.bits 0x%x", cell, cellType, structureID.bits());
+    if (action == Analyzer::Action::LogAndCrash) {
+        // structure should be pointing to readable memory. Force a read.
+        WTF::opaque(*bitwise_cast<uintptr_t*>(structure));
+    }
+
+    const ClassInfo* classInfo = structure->classInfoForCells();
+    AUDIT_VERIFY(cellType == structure->m_blob.type(),
+        "cell %p cell.type %d structureBlob.type %d", cell, cellType, structure->m_blob.type());
+
+    size_t size = cellSize(cell);
+    AUDIT_VERIFY(size <= allocatorCellSize,
+        "cell %p cell.type %d cell.size %zu allocator.cellSize %zu, classInfo.cellSize %u", cell, cellType, size, allocatorCellSize, classInfo->staticClassSize);
+    if (isDynamicallySizedType(cellType)) {
+        AUDIT_VERIFY(size >= classInfo->staticClassSize,
+            "cell %p cell.type %d cell.size %zu classInfo.cellSize %u", cell, cellType, size, classInfo->staticClassSize);
+    }
+
+    if (cell->isObject()) {
+        AUDIT_VERIFY(jsDynamicCast<JSObject*>(cell),
+            "cell %p cell.type %d", cell, cell->type());
+
+        if (Gigacage::isEnabled(Gigacage::JSValue)) {
+            JSObject* object = bitwise_cast<JSObject*>(cell);
+            const Butterfly* butterfly = object->butterfly();
+            AUDIT_VERIFY(!butterfly || Gigacage::isCaged(Gigacage::JSValue, butterfly),
+                "cell %p cell.type %d butterfly %p", cell, cell->type(), butterfly);
+        }
+    }
+
+    return true;
+}
+
+bool Analyzer::analyzeCell(JSCell* cell, Analyzer::Action action)
+{
+    if (!cell)
+        return cell;
+
+    JSValue value = JSValue::decode(static_cast<EncodedJSValue>(bitwise_cast<uintptr_t>(cell)));
+    AUDIT_VERIFY(value.isCell(), "Invalid cell address: cell %p", cell);
+
+    VM& vm = cell->vm();
+    analyzeVM(vm, action);
+    return analyzeCell(vm, cell, action);
+}
+
+#undef AUDIT_VERIFY
+
+VM* doAuditSlow(VM* vm)
+{
+    Analyzer::analyzeVM(*vm, Analyzer::Action::LogAndCrash);
+    return vm;
+}
+
+JSCell* doAudit(JSCell* cell)
+{
+    Analyzer::analyzeCell(cell, Analyzer::Action::LogAndCrash);
+    return cell;
+}
+
+JSCell* doAudit(VM& vm, JSCell* cell)
+{
+    if (!cell)
+        return cell;
+    Analyzer::analyzeCell(vm, cell, Analyzer::Action::LogAndCrash);
+    return cell;
+}
+
+bool verifyCell(JSCell* cell)
+{
+    bool valid = Analyzer::analyzeCell(cell, Analyzer::Action::LogOnly);
+    WTFLogAlways("Cell %p is %s", cell, valid ? "VALID" : "INVALID");
+    return valid;
+}
+
+bool verifyCell(VM& vm, JSCell* cell)
+{
+    bool valid = Analyzer::analyzeCell(vm, cell, Analyzer::Action::LogOnly);
+    WTFLogAlways("Cell %p is %s", cell, valid ? "VALID" : "INVALID");
+    return valid;
+}
+
+JSObject* doAudit(JSObject* object)
+{
+    if (!object)
+        return object;
+    JSCell* cell = doAudit(reinterpret_cast<JSCell*>(object));
+    IA_ASSERT(cell->isObject(), "Invalid JSObject %p", object);
+    return object;
+}
+
+JSGlobalObject* doAudit(JSGlobalObject* globalObject)
+{
+    doAudit(reinterpret_cast<JSCell*>(globalObject));
+    IA_ASSERT(globalObject->isGlobalObject(), "Invalid JSGlobalObject %p", globalObject);
+    return globalObject;
+}
+
+#endif // USE(JSVALUE64)
+
 } // namespace Integrity
 } // namespace JSC

Modified: trunk/Source/_javascript_Core/tools/Integrity.h (294016 => 294017)


--- trunk/Source/_javascript_Core/tools/Integrity.h	2022-05-10 21:15:45 UTC (rev 294016)
+++ trunk/Source/_javascript_Core/tools/Integrity.h	2022-05-10 21:55:45 UTC (rev 294017)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2019-2021 Apple Inc. All rights reserved.
+ * Copyright (C) 2019-2022 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -25,14 +25,37 @@
 
 #pragma once
 
-#include "JSCJSValue.h"
-#include "StructureID.h"
-#include <wtf/Gigacage.h>
+#include <wtf/Assertions.h>
 #include <wtf/Lock.h>
 
+#if OS(DARWIN)
+#include <mach/vm_param.h>
+#endif
+
+#if USE(JSVALUE32)
+#define ENABLE_EXTRA_INTEGRITY_CHECKS 0 // Not supported.
+#else
+// Force ENABLE_EXTRA_INTEGRITY_CHECKS to 1 for your local build if you want
+// more prolific audits to be enabled.
+#define ENABLE_EXTRA_INTEGRITY_CHECKS 0
+#endif
+
+// From API/JSBase.h
+typedef const struct OpaqueJSContextGroup* JSContextGroupRef;
+typedef const struct OpaqueJSContext* JSContextRef;
+typedef struct OpaqueJSContext* JSGlobalContextRef;
+typedef struct OpaqueJSPropertyNameAccumulator* JSPropertyNameAccumulatorRef;
+typedef const struct OpaqueJSValue* JSValueRef;
+typedef struct OpaqueJSValue* JSObjectRef;
+
 namespace JSC {
 
 class JSCell;
+class JSGlobalObject;
+class JSObject;
+class JSValue;
+class Structure;
+class StructureID;
 class VM;
 
 namespace Integrity {
@@ -67,10 +90,53 @@
     static constexpr int numberOfTriggerBits = (sizeof(m_triggerBits) * CHAR_BIT) - 1;
 };
 
+ALWAYS_INLINE static bool isSanePointer(const void* pointer)
+{
+#if CPU(ADDRESS64)
+    uintptr_t pointerAsInt = bitwise_cast<uintptr_t>(pointer);
+    uintptr_t canonicalPointerBits = pointerAsInt << (64 - OS_CONSTANT(EFFECTIVE_ADDRESS_WIDTH));
+    uintptr_t nonCanonicalPointerBits = pointerAsInt >> OS_CONSTANT(EFFECTIVE_ADDRESS_WIDTH);
+    return !nonCanonicalPointerBits && canonicalPointerBits;
+#else
+    UNUSED_PARAM(pointer);
+    return true;
+#endif
+}
+
+#if USE(JSVALUE64)
+
+class Analyzer {
+public:
+    enum Action { LogOnly, LogAndCrash };
+
+    static bool analyzeVM(VM&, Action);
+    static bool analyzeCell(VM&, JSCell*, Action);
+    static bool analyzeCell(JSCell*, Action);
+};
+
+JS_EXPORT_PRIVATE JSContextRef doAudit(JSContextRef);
+JS_EXPORT_PRIVATE JSGlobalContextRef doAudit(JSGlobalContextRef);
+JS_EXPORT_PRIVATE JSObjectRef doAudit(JSObjectRef);
+JS_EXPORT_PRIVATE JSValueRef doAudit(JSValueRef);
+
+JS_EXPORT_PRIVATE JSValue doAudit(JSValue);
+JS_EXPORT_PRIVATE JSCell* doAudit(JSCell*);
+JS_EXPORT_PRIVATE JSCell* doAudit(VM&, JSCell*);
+JS_EXPORT_PRIVATE JSObject* doAudit(JSObject*);
+JS_EXPORT_PRIVATE JSGlobalObject* doAudit(JSGlobalObject*);
+
+VM* doAudit(VM*); // see IntegrityInlines.h
+
+// These are used for debugging queries, and will not crash.
+JS_EXPORT_PRIVATE bool verifyCell(JSCell*);
+JS_EXPORT_PRIVATE bool verifyCell(VM&, JSCell*);
+
+#endif // USE(JSVALUE64)
+
 ALWAYS_INLINE void auditCellRandomly(VM&, JSCell*);
 ALWAYS_INLINE void auditCellMinimally(VM&, JSCell*);
 JS_EXPORT_PRIVATE void auditCellMinimallySlow(VM&, JSCell*);
-JS_EXPORT_PRIVATE void auditCellFully(VM&, JSCell*);
+ALWAYS_INLINE void auditCellFully(VM&, JSCell*);
 
 template<AuditLevel = AuditLevel::Random, typename T>
 ALWAYS_INLINE void auditCell(VM&, T) { }
@@ -78,30 +144,73 @@
 template<AuditLevel auditLevel = DefaultAuditLevel>
 ALWAYS_INLINE void auditCell(VM& vm, JSCell* cell)
 {
-    switch (auditLevel) {
-    case AuditLevel::None:
+    static_assert(auditLevel == AuditLevel::None || auditLevel == AuditLevel::Minimal || auditLevel == AuditLevel::Full || auditLevel == AuditLevel::Random);
+
+    UNUSED_PARAM(vm);
+    UNUSED_PARAM(cell);
+    if constexpr (auditLevel == AuditLevel::None)
         return;
-    case AuditLevel::Minimal:
+    if constexpr (auditLevel == AuditLevel::Minimal)
         return auditCellMinimally(vm, cell);
-    case AuditLevel::Full:
+    if constexpr (auditLevel == AuditLevel::Full)
         return auditCellFully(vm, cell);
-    case AuditLevel::Random:
+    if constexpr (auditLevel == AuditLevel::Random)
         return auditCellRandomly(vm, cell);
-    }
 }
 
 template<AuditLevel auditLevel = DefaultAuditLevel>
-ALWAYS_INLINE void auditCell(VM& vm, JSValue value)
-{
-    if (auditLevel == AuditLevel::None)
-        return;
+ALWAYS_INLINE void auditCell(VM&, JSValue);
 
-    if (value.isCell())
-        auditCell<auditLevel>(vm, value.asCell());
-}
-
 ALWAYS_INLINE void auditStructureID(StructureID);
 
+#if ENABLE(EXTRA_INTEGRITY_CHECKS) && USE(JSVALUE64)
+template<typename T> ALWAYS_INLINE T audit(T value) { return doAudit(value); }
+#else
+template<typename T> ALWAYS_INLINE T audit(T value) { return value; }
+#endif
+
+#if COMPILER(MSVC) || !VA_OPT_SUPPORTED
+
+#define IA_LOG(assertion, format, ...) do { \
+        WTFLogAlways("Integrity ERROR: %s @ %s:%d\n", #assertion, __FILE__, __LINE__); \
+        WTFLogAlways("    " format, ##__VA_ARGS__); \
+    } while (false)
+
+#define IA_ASSERT_WITH_ACTION(assertion, action, ...) do { \
+        if (UNLIKELY(!(assertion))) { \
+            IA_LOG(assertion, __VA_ARGS__); \
+            WTFReportBacktraceWithPrefix("    "); \
+            action; \
+        } \
+    } while (false)
+
+#define IA_ASSERT(assertion, ...) \
+    IA_ASSERT_WITH_ACTION(assertion, { \
+        RELEASE_ASSERT((assertion), ##__VA_ARGS__); \
+    }, ## __VA_ARGS__)
+
+#else // not (COMPILER(MSVC) || !VA_OPT_SUPPORTED)
+
+#define IA_LOG(assertion, format, ...) do { \
+        WTFLogAlways("Integrity ERROR: %s @ %s:%d\n", #assertion, __FILE__, __LINE__); \
+        WTFLogAlways("    " format __VA_OPT__(,) __VA_ARGS__); \
+    } while (false)
+
+#define IA_ASSERT_WITH_ACTION(assertion, action, ...) do { \
+        if (UNLIKELY(!(assertion))) { \
+            IA_LOG(assertion, __VA_ARGS__); \
+            WTFReportBacktraceWithPrefix("    "); \
+            action; \
+        } \
+    } while (false)
+
+#define IA_ASSERT(assertion, ...) \
+    IA_ASSERT_WITH_ACTION(assertion, { \
+        RELEASE_ASSERT((assertion) __VA_OPT__(,) __VA_ARGS__); \
+    } __VA_OPT__(,) __VA_ARGS__)
+
+#endif // COMPILER(MSVC) || !VA_OPT_SUPPORTED
+
 } // namespace Integrity
 
 } // namespace JSC

Modified: trunk/Source/_javascript_Core/tools/IntegrityInlines.h (294016 => 294017)


--- trunk/Source/_javascript_Core/tools/IntegrityInlines.h	2022-05-10 21:15:45 UTC (rev 294016)
+++ trunk/Source/_javascript_Core/tools/IntegrityInlines.h	2022-05-10 21:55:45 UTC (rev 294017)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2019-2020 Apple Inc. All rights reserved.
+ * Copyright (C) 2019-2022 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -26,7 +26,12 @@
 #pragma once
 
 #include "Integrity.h"
+#include "JSCJSValue.h"
+#include "StructureID.h"
 #include "VM.h"
+#include "VMInspector.h"
+#include <wtf/Atomics.h>
+#include <wtf/Gigacage.h>
 
 namespace JSC {
 namespace Integrity {
@@ -61,6 +66,16 @@
     return true;
 }
 
+template<AuditLevel auditLevel>
+ALWAYS_INLINE void auditCell(VM& vm, JSValue value)
+{
+    if constexpr (auditLevel == AuditLevel::None)
+        return;
+
+    if (value.isCell())
+        auditCell<auditLevel>(vm, value.asCell());
+}
+
 ALWAYS_INLINE void auditCellMinimally(VM& vm, JSCell* cell)
 {
     if (UNLIKELY(Gigacage::contains(cell)))
@@ -73,6 +88,14 @@
         auditCellFully(vm, cell);
 }
 
+ALWAYS_INLINE void auditCellFully(VM& vm, JSCell* cell)
+{
+#if USE(JSVALUE64)
+    doAudit(vm, cell);
+#else
+    auditCellMinimally(vm, cell);
+#endif
+}
 
 ALWAYS_INLINE void auditStructureID(StructureID structureID)
 {
@@ -80,7 +103,26 @@
 #if CPU(ADDRESS64) && !ENABLE(STRUCTURE_ID_WITH_SHIFT)
     ASSERT(static_cast<uintptr_t>(structureID.bits()) <= structureHeapAddressSize + StructureID::nukedStructureIDBit);
 #endif
+#if ENABLE(EXTRA_INTEGRITY_CHECKS) || ASSERT_ENABLED
+    Structure* structure = structureID.tryDecode();
+    IA_ASSERT(structure, "structureID.bits 0x%x", structureID.bits());
+    // structure should be pointing to readable memory. Force a read.
+    WTF::opaque(*bitwise_cast<uintptr_t*>(structure));
+#endif
 }
 
+#if USE(JSVALUE64)
+
+JS_EXPORT_PRIVATE VM* doAuditSlow(VM*);
+
+ALWAYS_INLINE VM* doAudit(VM* vm)
+{
+    if (UNLIKELY(!VMInspector::isValidVM(vm)))
+        return doAuditSlow(vm);
+    return vm;
+}
+
+#endif // USE(JSVALUE64)
+
 } // namespace Integrity
 } // namespace JSC

Modified: trunk/Source/_javascript_Core/tools/VMInspector.cpp (294016 => 294017)


--- trunk/Source/_javascript_Core/tools/VMInspector.cpp	2022-05-10 21:15:45 UTC (rev 294016)
+++ trunk/Source/_javascript_Core/tools/VMInspector.cpp	2022-05-10 21:55:45 UTC (rev 294017)
@@ -38,6 +38,8 @@
 
 namespace JSC {
 
+VM* VMInspector::m_recentVM { nullptr };
+
 VMInspector& VMInspector::instance()
 {
     static VMInspector* manager;
@@ -51,6 +53,7 @@
 void VMInspector::add(VM* vm)
 {
     Locker locker { m_lock };
+    m_recentVM = vm;
     m_vmList.append(vm);
 }
 
@@ -57,24 +60,48 @@
 void VMInspector::remove(VM* vm)
 {
     Locker locker { m_lock };
+    if (m_recentVM == vm)
+        m_recentVM = nullptr;
     m_vmList.remove(vm);
 }
 
 #if ENABLE(JIT)
-static bool ensureIsSafeToLock(Lock& lock)
+static bool ensureIsSafeToLock(Lock& lock) WTF_IGNORES_THREAD_SAFETY_ANALYSIS
 {
     static constexpr unsigned maxRetries = 2;
     unsigned tryCount = 0;
     while (tryCount++ <= maxRetries) {
-        if (lock.tryLock()) {
-            lock.unlock();
+        if (lock.tryLock())
             return true;
-        }
     }
     return false;
 }
 #endif // ENABLE(JIT)
 
+bool VMInspector::isValidVMSlow(VM* vm)
+{
+    bool found = false;
+    forEachVM([&] (VM& nextVM) {
+        if (vm == &nextVM) {
+            m_recentVM = vm;
+            found = true;
+            return IterationStatus::Done;
+        }
+        return IterationStatus::Continue;
+    });
+    return found;
+}
+
+void VMInspector::dumpVMs()
+{
+    unsigned i = 0;
+    WTFLogAlways("Registered VMs:");
+    forEachVM([&] (VM& nextVM) {
+        WTFLogAlways("  [%u] VM %p", i++, &nextVM);
+        return IterationStatus::Continue;
+    });
+}
+
 void VMInspector::forEachVM(Function<IterationStatus(VM&)>&& func)
 {
     VMInspector& inspector = instance();
@@ -82,32 +109,21 @@
     inspector.iterate(func);
 }
 
-auto VMInspector::isValidExecutableMemory(void* machinePC) -> Expected<bool, Error>
+WTF_IGNORES_THREAD_SAFETY_ANALYSIS auto VMInspector::isValidExecutableMemory(void* machinePC) -> Expected<bool, Error>
 {
 #if ENABLE(JIT)
-    bool found = false;
-    bool hasTimeout = false;
-    iterate([&] (VM&) -> IterationStatus {
-        auto& allocator = ExecutableAllocator::singleton();
-        auto& lock = allocator.getLock();
+    auto& allocator = ExecutableAllocator::singleton();
+    auto& lock = allocator.getLock();
 
-        bool isSafeToLock = ensureIsSafeToLock(lock);
-        if (!isSafeToLock) {
-            hasTimeout = true;
-            return IterationStatus::Continue; // Skip this VM.
-        }
+    bool isSafeToLock = ensureIsSafeToLock(lock);
+    if (!isSafeToLock)
+        return makeUnexpected(Error::TimedOut);
 
-        Locker executableAllocatorLocker { lock };
-        if (allocator.isValidExecutableMemory(executableAllocatorLocker, machinePC)) {
-            found = true;
-            return IterationStatus::Done;
-        }
-        return IterationStatus::Continue;
-    });
+    Locker executableAllocatorLocker { AdoptLock, lock };
+    if (allocator.isValidExecutableMemory(executableAllocatorLocker, machinePC))
+        return true;
 
-    if (!found && hasTimeout)
-        return makeUnexpected(Error::TimedOut);
-    return found;
+    return false;
 #else
     UNUSED_PARAM(machinePC);
     return false;
@@ -119,7 +135,10 @@
 #if ENABLE(JIT)
     CodeBlock* codeBlock = nullptr;
     bool hasTimeout = false;
-    iterate([&] (VM& vm) {
+    iterate([&] (VM& vm) WTF_IGNORES_THREAD_SAFETY_ANALYSIS {
+        if (!vm.isInService())
+            return IterationStatus::Continue;
+
         if (!vm.currentThreadIsHoldingAPILock())
             return IterationStatus::Continue;
 
@@ -141,7 +160,7 @@
             return IterationStatus::Continue; // Skip this VM.
         }
 
-        Locker locker { codeBlockSetLock };
+        Locker locker { AdoptLock, codeBlockSetLock };
         vm.heap.forEachCodeBlockIgnoringJITPlans(locker, [&] (CodeBlock* cb) {
             JITCode* jitCode = cb->jitCode().get();
             if (!jitCode) {

Modified: trunk/Source/_javascript_Core/tools/VMInspector.h (294016 => 294017)


--- trunk/Source/_javascript_Core/tools/VMInspector.h	2022-05-10 21:15:45 UTC (rev 294016)
+++ trunk/Source/_javascript_Core/tools/VMInspector.h	2022-05-10 21:55:45 UTC (rev 294017)
@@ -48,6 +48,10 @@
 
     void add(VM*);
     void remove(VM*);
+    ALWAYS_INLINE static bool isValidVM(VM* vm)
+    {
+        return vm == m_recentVM ? true : isValidVMSlow(vm);
+    }
 
     Lock& getLock() WTF_RETURNS_LOCK(m_lock) { return m_lock; }
 
@@ -61,6 +65,7 @@
     }
 
     JS_EXPORT_PRIVATE static void forEachVM(Function<IterationStatus(VM&)>&&);
+    JS_EXPORT_PRIVATE static void dumpVMs();
 
     Expected<bool, Error> isValidExecutableMemory(void*) WTF_REQUIRES_LOCK(m_lock);
     Expected<CodeBlock*, Error> codeBlockForMachinePC(void*) WTF_REQUIRES_LOCK(m_lock);
@@ -80,20 +85,16 @@
     JS_EXPORT_PRIVATE static void dumpCellMemoryToStream(JSCell*, PrintStream&);
     JS_EXPORT_PRIVATE static void dumpSubspaceHashes(VM*);
 
-    enum VerifierAction { ReleaseAssert, Custom };
-
-    using VerifyFunctor = bool(bool condition, const char* description, ...);
-    static bool unusedVerifier(bool, const char*, ...) { return false; }
-
-    template<VerifierAction, VerifyFunctor = unusedVerifier>
-    static bool verifyCellSize(JSCell*, size_t allocatorCellSize);
-
-    template<VerifierAction, VerifyFunctor = unusedVerifier>
+#if USE(JSVALUE64)
     static bool verifyCell(VM&, JSCell*);
+#endif
 
 private:
+    JS_EXPORT_PRIVATE static bool isValidVMSlow(VM*);
+
     Lock m_lock;
     DoublyLinkedList<VM> m_vmList WTF_GUARDED_BY_LOCK(m_lock);
+    JS_EXPORT_PRIVATE static VM* m_recentVM;
 };
 
 } // namespace JSC

Modified: trunk/Source/_javascript_Core/tools/VMInspectorInlines.h (294016 => 294017)


--- trunk/Source/_javascript_Core/tools/VMInspectorInlines.h	2022-05-10 21:15:45 UTC (rev 294016)
+++ trunk/Source/_javascript_Core/tools/VMInspectorInlines.h	2022-05-10 21:55:45 UTC (rev 294017)
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2019 Apple Inc. All rights reserved.
+ * Copyright (C) 2019-2022 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -25,86 +25,16 @@
 
 #pragma once
 
-#include "CellSize.h"
+#include "Integrity.h"
 #include "VMInspector.h"
-#include <wtf/Assertions.h>
 
 namespace JSC {
 
-#define AUDIT_CONDITION(x) (x), #x
-#define AUDIT_VERIFY(action, verifier, cond, ...) do { \
-        if (action == VerifierAction::ReleaseAssert) \
-            RELEASE_ASSERT(cond, __VA_ARGS__); \
-        else if (!verifier(AUDIT_CONDITION(cond), __VA_ARGS__)) \
-            return false; \
-    } while (false)
-
-template<VMInspector::VerifierAction action, VMInspector::VerifyFunctor verifier>
-bool VMInspector::verifyCellSize(JSCell* cell, size_t allocatorCellSize)
+#if USE(JSVALUE64)
+ALWAYS_INLINE bool VMInspector::verifyCell(VM& vm, JSCell* cell)
 {
-    Structure* structure = cell->structure();
-    const ClassInfo* classInfo = structure->classInfoForCells();
-    JSType cellType = cell->type();
-    AUDIT_VERIFY(action, verifier, cellType == structure->m_blob.type(), cell, cellType, structure->m_blob.type());
-
-    size_t size = cellSize(cell);
-    AUDIT_VERIFY(action, verifier, size <= allocatorCellSize, cell, cellType, size, allocatorCellSize, classInfo->staticClassSize);
-    if (isDynamicallySizedType(cellType))
-        AUDIT_VERIFY(action, verifier, size >= classInfo->staticClassSize, cell, cellType, size, classInfo->staticClassSize);
-
-    return true;
+    return Integrity::verifyCell(vm, cell);
 }
+#endif
 
-template<VMInspector::VerifierAction action, VMInspector::VerifyFunctor verifier>
-bool VMInspector::verifyCell(VM& vm, JSCell* cell)
-{
-    size_t allocatorCellSize = 0;
-    if (cell->isPreciseAllocation()) {
-        PreciseAllocation& preciseAllocation = cell->preciseAllocation();
-        AUDIT_VERIFY(action, verifier, &preciseAllocation.vm() == &vm, cell, cell->type(), &preciseAllocation.vm(), &vm);
-
-        bool isValidPreciseAllocation = false;
-        for (auto* i : vm.heap.objectSpace().preciseAllocations()) {
-            if (i == &preciseAllocation) {
-                isValidPreciseAllocation = true;
-                break;
-            }
-        }
-        AUDIT_VERIFY(action, verifier, isValidPreciseAllocation, cell, cell->type());
-
-        allocatorCellSize = preciseAllocation.cellSize();
-    } else {
-        MarkedBlock& block = cell->markedBlock();
-        MarkedBlock::Handle& blockHandle = block.handle();
-        AUDIT_VERIFY(action, verifier, &block.vm() == &vm, cell, cell->type(), &block.vm(), &vm);
-
-        uintptr_t blockStartAddress = reinterpret_cast<uintptr_t>(blockHandle.start());
-        AUDIT_VERIFY(action, verifier, blockHandle.contains(cell), cell, cell->type(), blockStartAddress, blockHandle.end());
-
-        uintptr_t cellAddress = reinterpret_cast<uintptr_t>(cell);
-        uintptr_t cellOffset = cellAddress - blockStartAddress;
-        allocatorCellSize = block.cellSize();
-        bool cellIsProperlyAligned = !(cellOffset % allocatorCellSize);
-        AUDIT_VERIFY(action, verifier, cellIsProperlyAligned, cell, cell->type(), allocatorCellSize);
-    }
-
-    auto cellType = cell->type();
-    if (cell->type() != JSImmutableButterflyType)
-        AUDIT_VERIFY(action, verifier, !Gigacage::contains(cell), cell, cellType);
-
-    if (!verifyCellSize<action, verifier>(cell, allocatorCellSize))
-        return false;
-
-    if (Gigacage::isEnabled(Gigacage::JSValue) && cell->isObject()) {
-        JSObject* object = asObject(cell);
-        const Butterfly* butterfly = object->butterfly();
-        AUDIT_VERIFY(action, verifier, !butterfly || Gigacage::isCaged(Gigacage::JSValue, butterfly), cell, cell->type(), butterfly);
-    }
-
-    return true;
-}
-
-#undef AUDIT_VERIFY
-#undef AUDIT_CONDITION
-
 } // namespace JSC
_______________________________________________
webkit-changes mailing list
[email protected]
https://lists.webkit.org/mailman/listinfo/webkit-changes

Reply via email to