Fix std::make_unique / new[] using system malloc
authorutatane.tea@gmail.com <utatane.tea@gmail.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Tue, 6 Mar 2018 07:25:14 +0000 (07:25 +0000)
committerutatane.tea@gmail.com <utatane.tea@gmail.com@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Tue, 6 Mar 2018 07:25:14 +0000 (07:25 +0000)
https://bugs.webkit.org/show_bug.cgi?id=182975

Reviewed by JF Bastien.

Source/JavaScriptCore:

Use Vector, FAST_ALLOCATED, or UniqueArray instead.

* API/JSStringRefCF.cpp:
(JSStringCreateWithCFString):
* bytecode/BytecodeKills.h:
* bytecode/BytecodeLivenessAnalysis.cpp:
(JSC::BytecodeLivenessAnalysis::computeKills):
* dfg/DFGDisassembler.cpp:
(JSC::DFG::Disassembler::dumpDisassembly):
* jit/PolymorphicCallStubRoutine.cpp:
(JSC::PolymorphicCallStubRoutine::PolymorphicCallStubRoutine):
* jit/PolymorphicCallStubRoutine.h:
* jit/Repatch.cpp:
(JSC::linkPolymorphicCall):
* jsc.cpp:
(currentWorkingDirectory):
* llint/LLIntData.cpp:
(JSC::LLInt::initialize):
* llint/LLIntData.h:
* runtime/ArgList.h:
* runtime/StructureChain.h:
* runtime/StructureIDTable.cpp:
(JSC::StructureIDTable::StructureIDTable):
(JSC::StructureIDTable::resize):
* runtime/StructureIDTable.h:
* runtime/TypeProfilerLog.cpp:
(JSC::TypeProfilerLog::TypeProfilerLog):
(JSC::TypeProfilerLog::initializeLog): Deleted.
* runtime/TypeProfilerLog.h:
(JSC::TypeProfilerLog::TypeProfilerLog): Deleted.
* runtime/VM.cpp:
(JSC::VM::~VM):
(JSC::VM::acquireRegExpPatternContexBuffer):
* runtime/VM.h:
* testRegExp.cpp:
(runFromFiles):
* tools/HeapVerifier.cpp:
(JSC::HeapVerifier::HeapVerifier):
* tools/HeapVerifier.h:

Source/WebCore:

Use Vector, FAST_ALLOCATED, or UniqueArray instead.

* Modules/webaudio/AudioBufferSourceNode.cpp:
(WebCore::AudioBufferSourceNode::setBuffer):
* Modules/webaudio/AudioBufferSourceNode.h:
* css/StyleRule.h:
* cssjit/CompiledSelector.h:
* html/HTMLFrameSetElement.h:
* html/canvas/WebGLRenderingContextBase.cpp:
(WebCore::WebGLRenderingContextBase::copyTexSubImage2D):
(WebCore::WebGLRenderingContextBase::simulateVertexAttrib0):
(WebCore::WebGLRenderingContextBase::LRUImageBufferCache::LRUImageBufferCache):
(WebCore::WebGLRenderingContextBase::LRUImageBufferCache::imageBuffer):
(WebCore::WebGLRenderingContextBase::LRUImageBufferCache::bubbleToFront):
* html/canvas/WebGLRenderingContextBase.h:
* platform/Length.cpp:
(WebCore::newCoordsArray):
(WebCore::newLengthArray):
(): Deleted.
* platform/Length.h:
* platform/audio/DynamicsCompressor.cpp:
(WebCore::DynamicsCompressor::setNumberOfChannels):
* platform/audio/DynamicsCompressor.h:
* platform/audio/FFTFrame.h:
* platform/audio/gstreamer/FFTFrameGStreamer.cpp:
(WebCore::FFTFrame::FFTFrame):
* platform/graphics/FormatConverter.h:
(WebCore::FormatConverter::FormatConverter):
* platform/graphics/GraphicsContext3D.cpp:
(WebCore::GraphicsContext3D::texImage2DResourceSafe):
* platform/graphics/GraphicsContext3D.h:
* platform/graphics/ca/win/CACFLayerTreeHost.cpp:
(WebCore::getDirtyRects):
* platform/graphics/cairo/CairoUtilities.cpp:
(WebCore::flipImageSurfaceVertically):
* platform/graphics/cg/GraphicsContext3DCG.cpp:
(WebCore::GraphicsContext3D::ImageExtractor::extractImage):
* platform/graphics/gpu/Texture.cpp:
(WebCore::Texture::updateSubRect):
* platform/graphics/opengl/GraphicsContext3DOpenGLCommon.cpp:
(WebCore::GraphicsContext3D::paintRenderingResultsToCanvas):
(WebCore::GraphicsContext3D::compileShader):
(WebCore::GraphicsContext3D::getActiveAttribImpl):
(WebCore::GraphicsContext3D::getActiveUniformImpl):
(WebCore::GraphicsContext3D::getProgramInfoLog):
(WebCore::GraphicsContext3D::getShaderInfoLog):
* platform/graphics/texmap/TextureMapperShaderProgram.cpp:
(WebCore::getShaderLog):
(WebCore::getProgramLog):
* platform/graphics/win/ImageBufferDataDirect2D.cpp:
(WebCore::ImageBufferData::putData):
* platform/image-decoders/png/PNGImageDecoder.cpp:
(WebCore::PNGImageReader::PNGImageReader):
(WebCore::PNGImageReader::close):
(WebCore::PNGImageReader::interlaceBuffer const):
(WebCore::PNGImageReader::createInterlaceBuffer):
* platform/image-decoders/webp/WEBPImageDecoder.cpp:
(WebCore::WEBPImageDecoder::decodeFrame):
* platform/network/curl/SocketStreamHandleImpl.h:
(WebCore::SocketStreamHandleImpl::SocketData::SocketData):
* platform/network/curl/SocketStreamHandleImplCurl.cpp:
(WebCore::createCopy):
(WebCore::SocketStreamHandleImpl::readData):
(): Deleted.
* platform/network/soup/SocketStreamHandleImpl.h:
* platform/network/soup/SocketStreamHandleImplSoup.cpp:
(WebCore::SocketStreamHandleImpl::connected):
* platform/win/LoggingWin.cpp:
(WebCore::logLevelString):

Source/WebCore/PAL:

Use Vector instead.

* pal/win/LoggingWin.cpp:
(PAL::logLevelString):

Source/WebKit:

Use Vector instead.

* NetworkProcess/win/SystemProxyWin.cpp:
(WindowsSystemProxy::getSystemHttpProxy):
* Platform/IPC/unix/ConnectionUnix.cpp:
(IPC::Connection::processMessage):
(IPC::Connection::sendOutputMessage):
* Platform/win/LoggingWin.cpp:
(WebKit::logLevelString):
* Shared/SandboxExtension.h:
* Shared/mac/SandboxExtensionMac.mm:
(WebKit::SandboxExtension::HandleArray::allocate):
(WebKit::SandboxExtension::HandleArray::operator[]):
(WebKit::SandboxExtension::HandleArray::operator[] const):
(WebKit::SandboxExtension::HandleArray::size const):
(WebKit::SandboxExtension::HandleArray::encode const):

Source/WebKitLegacy/win:

Use Vector instead.

* MarshallingHelpers.cpp:
(MarshallingHelpers::safeArrayToStringArray):
(MarshallingHelpers::safeArrayToIntArray):
* Plugins/PluginPackageWin.cpp:
(WebCore::PluginPackage::fetchInfo):
* WebPreferences.cpp:
(WebPreferences::copyWebKitPreferencesToCFPreferences):
* WebView.cpp:
(WebView::onMenuCommand):

Source/WTF:

If we use `make_unique<char[]>(num)` or `new char[num]`, allocation is
done by the system malloc instead of bmalloc. This patch fixes this issue
by following three changes.

1. Introduce UniqueArray<T>. It allocates memory from FastMalloc. While C++
array with `new` need to hold the size to call destructor correctly, our
UniqueArray only supports type T which does not have a non trivial destructor.
It reduces the allocation size since we do not need to track the size of the
array compared to standard `new T[]`. This is basically usable if we want to
have raw array which pointer won't be changed even if the container is moved.
In addition, we also extend UniqueArray<T> for types which have non trivial
destructors.

2. Use Vector<T> instead.

3. Annotate allocated types with MAKE_FAST_ALLOCATED. Since it introduces
new[] and delete[] operators, make_unique<T[]>(num) will allocate memory
from FastMalloc.

* WTF.xcodeproj/project.pbxproj:
* wtf/Assertions.cpp:
* wtf/CMakeLists.txt:
* wtf/FastMalloc.h:
(WTF::FastFree::operator() const):
(WTF::FastFree<T::operator() const):
* wtf/MallocPtr.h:
(WTF::MallocPtr::operator bool const):
* wtf/StackShot.h:
(WTF::StackShot::StackShot):
(WTF::StackShot::operator=):
* wtf/SystemFree.h:
(WTF::SystemFree<T::operator() const):
* wtf/UniqueArray.h: Copied from Source/WebKit/Platform/win/LoggingWin.cpp.
(WTF::makeUniqueArray):
* wtf/Vector.h:
(WTF::VectorTypeOperations::forceInitialize):

Tools:

* TestWebKitAPI/CMakeLists.txt:
* TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj:
* TestWebKitAPI/Tests/WTF/UniqueArray.cpp: Copied from Source/WebKit/Platform/win/LoggingWin.cpp.
(TestWebKitAPI::NonTrivialDestructor::NonTrivialDestructor):
(TestWebKitAPI::NonTrivialDestructor::~NonTrivialDestructor):
(TestWebKitAPI::NonTrivialDestructor::setLog):
(TestWebKitAPI::TEST):

git-svn-id: https://svn.webkit.org/repository/webkit/trunk@229309 268f45cc-cd09-0410-ab3c-d52691b4dbfc

80 files changed:
Source/JavaScriptCore/API/JSStringRefCF.cpp
Source/JavaScriptCore/ChangeLog
Source/JavaScriptCore/bytecode/BytecodeKills.h
Source/JavaScriptCore/bytecode/BytecodeLivenessAnalysis.cpp
Source/JavaScriptCore/dfg/DFGDisassembler.cpp
Source/JavaScriptCore/jit/PolymorphicCallStubRoutine.cpp
Source/JavaScriptCore/jit/PolymorphicCallStubRoutine.h
Source/JavaScriptCore/jit/Repatch.cpp
Source/JavaScriptCore/jsc.cpp
Source/JavaScriptCore/llint/LLIntData.cpp
Source/JavaScriptCore/llint/LLIntData.h
Source/JavaScriptCore/runtime/ArgList.h
Source/JavaScriptCore/runtime/StructureChain.h
Source/JavaScriptCore/runtime/StructureIDTable.cpp
Source/JavaScriptCore/runtime/StructureIDTable.h
Source/JavaScriptCore/runtime/TypeProfilerLog.cpp
Source/JavaScriptCore/runtime/TypeProfilerLog.h
Source/JavaScriptCore/runtime/VM.cpp
Source/JavaScriptCore/runtime/VM.h
Source/JavaScriptCore/testRegExp.cpp
Source/JavaScriptCore/tools/HeapVerifier.cpp
Source/JavaScriptCore/tools/HeapVerifier.h
Source/WTF/ChangeLog
Source/WTF/WTF.xcodeproj/project.pbxproj
Source/WTF/wtf/Assertions.cpp
Source/WTF/wtf/CMakeLists.txt
Source/WTF/wtf/FastMalloc.h
Source/WTF/wtf/MallocPtr.h
Source/WTF/wtf/StackShot.h
Source/WTF/wtf/SystemFree.h
Source/WTF/wtf/UniqueArray.h [new file with mode: 0644]
Source/WTF/wtf/Vector.h
Source/WebCore/ChangeLog
Source/WebCore/Modules/webaudio/AudioBufferSourceNode.cpp
Source/WebCore/Modules/webaudio/AudioBufferSourceNode.h
Source/WebCore/PAL/ChangeLog
Source/WebCore/PAL/pal/win/LoggingWin.cpp
Source/WebCore/css/StyleRule.h
Source/WebCore/cssjit/CompiledSelector.h
Source/WebCore/html/HTMLFrameSetElement.h
Source/WebCore/html/canvas/WebGLRenderingContextBase.cpp
Source/WebCore/html/canvas/WebGLRenderingContextBase.h
Source/WebCore/platform/Length.cpp
Source/WebCore/platform/Length.h
Source/WebCore/platform/audio/DynamicsCompressor.cpp
Source/WebCore/platform/audio/DynamicsCompressor.h
Source/WebCore/platform/audio/FFTFrame.h
Source/WebCore/platform/audio/gstreamer/FFTFrameGStreamer.cpp
Source/WebCore/platform/graphics/FormatConverter.h
Source/WebCore/platform/graphics/GraphicsContext3D.cpp
Source/WebCore/platform/graphics/GraphicsContext3D.h
Source/WebCore/platform/graphics/ca/win/CACFLayerTreeHost.cpp
Source/WebCore/platform/graphics/cairo/CairoUtilities.cpp
Source/WebCore/platform/graphics/cg/GraphicsContext3DCG.cpp
Source/WebCore/platform/graphics/gpu/Texture.cpp
Source/WebCore/platform/graphics/opengl/GraphicsContext3DOpenGLCommon.cpp
Source/WebCore/platform/graphics/texmap/TextureMapperShaderProgram.cpp
Source/WebCore/platform/graphics/win/ImageBufferDataDirect2D.cpp
Source/WebCore/platform/image-decoders/png/PNGImageDecoder.cpp
Source/WebCore/platform/image-decoders/webp/WEBPImageDecoder.cpp
Source/WebCore/platform/network/curl/SocketStreamHandleImpl.h
Source/WebCore/platform/network/curl/SocketStreamHandleImplCurl.cpp
Source/WebCore/platform/network/soup/SocketStreamHandleImpl.h
Source/WebCore/platform/network/soup/SocketStreamHandleImplSoup.cpp
Source/WebCore/platform/win/LoggingWin.cpp
Source/WebKit/ChangeLog
Source/WebKit/NetworkProcess/win/SystemProxyWin.cpp
Source/WebKit/Platform/IPC/unix/ConnectionUnix.cpp
Source/WebKit/Platform/win/LoggingWin.cpp
Source/WebKit/Shared/SandboxExtension.h
Source/WebKit/Shared/mac/SandboxExtensionMac.mm
Source/WebKitLegacy/win/ChangeLog
Source/WebKitLegacy/win/MarshallingHelpers.cpp
Source/WebKitLegacy/win/Plugins/PluginPackageWin.cpp
Source/WebKitLegacy/win/WebPreferences.cpp
Source/WebKitLegacy/win/WebView.cpp
Tools/ChangeLog
Tools/TestWebKitAPI/CMakeLists.txt
Tools/TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj
Tools/TestWebKitAPI/Tests/WTF/UniqueArray.cpp [new file with mode: 0644]

index 0587259..1367715 100644 (file)
@@ -49,10 +49,10 @@ JSStringRef JSStringCreateWithCFString(CFStringRef string)
     if (static_cast<size_t>(convertedSize) == length && static_cast<size_t>(usedBufferLength) == length)
         return &OpaqueJSString::create(lcharBuffer.data(), length).leakRef();
 
-    auto buffer = std::make_unique<UniChar[]>(length);
-    CFStringGetCharacters(string, CFRangeMake(0, length), buffer.get());
+    Vector<UniChar> buffer(length);
+    CFStringGetCharacters(string, CFRangeMake(0, length), buffer.data());
     static_assert(sizeof(UniChar) == sizeof(UChar), "UniChar and UChar must be same size");
-    return &OpaqueJSString::create(reinterpret_cast<UChar*>(buffer.get()), length).leakRef();
+    return &OpaqueJSString::create(reinterpret_cast<UChar*>(buffer.data()), length).leakRef();
 }
 
 CFStringRef JSStringCopyCFString(CFAllocatorRef allocator, JSStringRef string)
index 0f3387e..60c9650 100644 (file)
@@ -1,3 +1,50 @@
+2018-03-05  Yusuke Suzuki  <utatane.tea@gmail.com>
+
+        Fix std::make_unique / new[] using system malloc
+        https://bugs.webkit.org/show_bug.cgi?id=182975
+
+        Reviewed by JF Bastien.
+
+        Use Vector, FAST_ALLOCATED, or UniqueArray instead.
+
+        * API/JSStringRefCF.cpp:
+        (JSStringCreateWithCFString):
+        * bytecode/BytecodeKills.h:
+        * bytecode/BytecodeLivenessAnalysis.cpp:
+        (JSC::BytecodeLivenessAnalysis::computeKills):
+        * dfg/DFGDisassembler.cpp:
+        (JSC::DFG::Disassembler::dumpDisassembly):
+        * jit/PolymorphicCallStubRoutine.cpp:
+        (JSC::PolymorphicCallStubRoutine::PolymorphicCallStubRoutine):
+        * jit/PolymorphicCallStubRoutine.h:
+        * jit/Repatch.cpp:
+        (JSC::linkPolymorphicCall):
+        * jsc.cpp:
+        (currentWorkingDirectory):
+        * llint/LLIntData.cpp:
+        (JSC::LLInt::initialize):
+        * llint/LLIntData.h:
+        * runtime/ArgList.h:
+        * runtime/StructureChain.h:
+        * runtime/StructureIDTable.cpp:
+        (JSC::StructureIDTable::StructureIDTable):
+        (JSC::StructureIDTable::resize):
+        * runtime/StructureIDTable.h:
+        * runtime/TypeProfilerLog.cpp:
+        (JSC::TypeProfilerLog::TypeProfilerLog):
+        (JSC::TypeProfilerLog::initializeLog): Deleted.
+        * runtime/TypeProfilerLog.h:
+        (JSC::TypeProfilerLog::TypeProfilerLog): Deleted.
+        * runtime/VM.cpp:
+        (JSC::VM::~VM):
+        (JSC::VM::acquireRegExpPatternContexBuffer):
+        * runtime/VM.h:
+        * testRegExp.cpp:
+        (runFromFiles):
+        * tools/HeapVerifier.cpp:
+        (JSC::HeapVerifier::HeapVerifier):
+        * tools/HeapVerifier.h:
+
 2018-03-05  Mark Lam  <mark.lam@apple.com>
 
         JITThunk functions should only be called when the JIT is enabled.
index ea859c4..bf2bb3e 100644 (file)
@@ -26,6 +26,7 @@
 #pragma once
 
 #include "CodeBlock.h"
+#include <wtf/UniqueArray.h>
 
 namespace JSC {
 
@@ -74,6 +75,7 @@ private:
     friend class BytecodeLivenessAnalysis;
 
     class KillSet {
+        WTF_MAKE_FAST_ALLOCATED;
     public:
         KillSet()
             : m_word(0)
@@ -170,7 +172,7 @@ private:
     };
     
     CodeBlock* m_codeBlock;
-    std::unique_ptr<KillSet[]> m_killSets;
+    UniqueArray<KillSet> m_killSets;
 };
 
 } // namespace JSC
index 42d9ad6..e0169df 100644 (file)
@@ -89,7 +89,7 @@ void BytecodeLivenessAnalysis::computeKills(CodeBlock* codeBlock, BytecodeKills&
     FastBitVector out;
 
     result.m_codeBlock = codeBlock;
-    result.m_killSets = std::make_unique<BytecodeKills::KillSet[]>(codeBlock->instructions().size());
+    result.m_killSets = makeUniqueArray<BytecodeKills::KillSet>(codeBlock->instructions().size());
     
     for (std::unique_ptr<BytecodeBasicBlock>& block : m_graph.basicBlocksInReverseOrder()) {
         if (block->isEntryBlock() || block->isExitBlock())
index ad0356e..0c20703 100644 (file)
@@ -159,8 +159,8 @@ void Disassembler::dumpDisassembly(PrintStream& out, const char* prefix, LinkBuf
         amountOfNodeWhiteSpace = 0;
     else
         amountOfNodeWhiteSpace = Graph::amountOfNodeWhiteSpace(context);
-    auto prefixBuffer = std::make_unique<char[]>(prefixLength + amountOfNodeWhiteSpace + 1);
-    memcpy(prefixBuffer.get(), prefix, prefixLength);
+    Vector<char> prefixBuffer(prefixLength + amountOfNodeWhiteSpace + 1);
+    memcpy(prefixBuffer.data(), prefix, prefixLength);
     for (int i = 0; i < amountOfNodeWhiteSpace; ++i)
         prefixBuffer[i + prefixLength] = ' ';
     prefixBuffer[prefixLength + amountOfNodeWhiteSpace] = 0;
@@ -169,7 +169,7 @@ void Disassembler::dumpDisassembly(PrintStream& out, const char* prefix, LinkBuf
     CodeLocationLabel end = linkBuffer.locationOf(currentLabel);
     previousLabel = currentLabel;
     ASSERT(end.executableAddress<uintptr_t>() >= start.executableAddress<uintptr_t>());
-    disassemble(start, end.executableAddress<uintptr_t>() - start.executableAddress<uintptr_t>(), prefixBuffer.get(), out);
+    disassemble(start, end.executableAddress<uintptr_t>() - start.executableAddress<uintptr_t>(), prefixBuffer.data(), out);
 }
 
 } } // namespace JSC::DFG
index 858b541..bc0f841 100644 (file)
@@ -71,7 +71,7 @@ void PolymorphicCallCase::dump(PrintStream& out) const
 PolymorphicCallStubRoutine::PolymorphicCallStubRoutine(
     const MacroAssemblerCodeRef& codeRef, VM& vm, const JSCell* owner, ExecState* callerFrame,
     CallLinkInfo& info, const Vector<PolymorphicCallCase>& cases,
-    std::unique_ptr<uint32_t[]> fastCounts)
+    UniqueArray<uint32_t>&& fastCounts)
     : GCAwareJITStubRoutine(codeRef, vm)
     , m_fastCounts(WTFMove(fastCounts))
 {
index d96ae56..2a39577 100644 (file)
@@ -31,6 +31,7 @@
 #include "CallVariant.h"
 #include "GCAwareJITStubRoutine.h"
 #include <wtf/Noncopyable.h>
+#include <wtf/UniqueArray.h>
 #include <wtf/Vector.h>
 
 namespace JSC {
@@ -84,7 +85,7 @@ public:
     PolymorphicCallStubRoutine(
         const MacroAssemblerCodeRef&, VM&, const JSCell* owner,
         ExecState* callerFrame, CallLinkInfo&, const Vector<PolymorphicCallCase>&,
-        std::unique_ptr<uint32_t[]> fastCounts);
+        UniqueArray<uint32_t>&& fastCounts);
     
     virtual ~PolymorphicCallStubRoutine();
     
@@ -100,7 +101,7 @@ protected:
 
 private:
     Vector<WriteBarrier<JSCell>, 2> m_variants;
-    std::unique_ptr<uint32_t[]> m_fastCounts;
+    UniqueArray<uint32_t> m_fastCounts;
     Bag<PolymorphicCallNode> m_callNodes;
 };
 
index 28c0bc6..c96dc48 100644 (file)
@@ -944,10 +944,10 @@ void linkPolymorphicCall(
     
     Vector<int64_t> caseValues(callCases.size());
     Vector<CallToCodePtr> calls(callCases.size());
-    std::unique_ptr<uint32_t[]> fastCounts;
+    UniqueArray<uint32_t> fastCounts;
     
     if (!isWebAssembly && callerCodeBlock->jitType() != JITCode::topTierJIT())
-        fastCounts = std::make_unique<uint32_t[]>(callCases.size());
+        fastCounts = makeUniqueArray<uint32_t>(callCases.size());
     
     for (size_t i = 0; i < callCases.size(); ++i) {
         if (fastCounts)
index f0f4560..f70cc68 100644 (file)
@@ -718,17 +718,17 @@ static std::optional<DirectoryName> currentWorkingDirectory()
     // In Windows, wchar_t is the UTF-16LE.
     // https://msdn.microsoft.com/en-us/library/dd374081.aspx
     // https://msdn.microsoft.com/en-us/library/windows/desktop/ff381407.aspx
-    auto buffer = std::make_unique<wchar_t[]>(bufferLength);
-    DWORD lengthNotIncludingNull = ::GetCurrentDirectoryW(bufferLength, buffer.get());
-    String directoryString = wcharToString(buffer.get(), lengthNotIncludingNull);
+    Vector<wchar_t> buffer(bufferLength);
+    DWORD lengthNotIncludingNull = ::GetCurrentDirectoryW(bufferLength, buffer.data());
+    String directoryString = wcharToString(buffer.data(), lengthNotIncludingNull);
     // We don't support network path like \\host\share\<path name>.
     if (directoryString.startsWith("\\\\"))
         return std::nullopt;
 #else
-    auto buffer = std::make_unique<char[]>(PATH_MAX);
-    if (!getcwd(buffer.get(), PATH_MAX))
+    Vector<char> buffer(PATH_MAX);
+    if (!getcwd(buffer.data(), PATH_MAX))
         return std::nullopt;
-    String directoryString = String::fromUTF8(buffer.get());
+    String directoryString = String::fromUTF8(buffer.data());
 #endif
     if (directoryString.isEmpty())
         return std::nullopt;
index 4cf8c6d..3a1ea37 100644 (file)
@@ -47,7 +47,7 @@
 
 namespace JSC { namespace LLInt {
 
-Instruction* Data::s_exceptionInstructions = 0;
+Instruction Data::s_exceptionInstructions[maxOpcodeLength + 1] = { };
 Opcode Data::s_opcodeMap[numOpcodeIDs] = { };
 OpcodeStatsArray* Data::s_opcodeStatsArray = nullptr;
 
@@ -57,8 +57,6 @@ extern "C" void llint_entry(void*);
 
 void initialize()
 {
-    Data::s_exceptionInstructions = new Instruction[maxOpcodeLength + 1];
-
 #if !ENABLE(JIT)
     CLoop::initialize();
 
index 602dd64..301d077 100644 (file)
@@ -66,7 +66,7 @@ private:
     static void resetStats();
     static void saveStats();
 
-    static Instruction* s_exceptionInstructions;
+    static Instruction s_exceptionInstructions[maxOpcodeLength + 1];
     static Opcode s_opcodeMap[numOpcodeIDs];
     static OpcodeStatsArray* s_opcodeStatsArray;
 
index 39189f8..63c2de9 100644 (file)
@@ -165,6 +165,7 @@ private:
 };
 
 class ArgList {
+    WTF_MAKE_FAST_ALLOCATED;
     friend class Interpreter;
     friend class JIT;
 public:
index 47f3a5f..d62d106 100644 (file)
@@ -29,6 +29,7 @@
 #include "JSObject.h"
 #include "Structure.h"
 #include <wtf/StdLibExtras.h>
+#include <wtf/UniqueArray.h>
 
 namespace JSC {
 
@@ -70,7 +71,7 @@ protected:
         for (JSObject* current = head; current; current = current->structure(vm)->storedPrototypeObject(current))
             ++size;
 
-        std::unique_ptr<WriteBarrier<Structure>[]> vector = std::make_unique<WriteBarrier<Structure>[]>(size + 1);
+        auto vector = makeUniqueArray<WriteBarrier<Structure>>(size + 1);
 
         size_t i = 0;
         for (JSObject* current = head; current; current = current->structure(vm)->storedPrototypeObject(current))
@@ -85,7 +86,7 @@ private:
     friend class LLIntOffsetsExtractor;
 
     StructureChain(VM&, Structure*);
-    std::unique_ptr<WriteBarrier<Structure>[]> m_vector;
+    UniqueArray<WriteBarrier<Structure>> m_vector;
 };
 
 } // namespace JSC
index a2025af..8eeb391 100644 (file)
@@ -33,7 +33,7 @@ namespace JSC {
 
 StructureIDTable::StructureIDTable()
     : m_firstFreeOffset(0)
-    , m_table(std::make_unique<StructureOrOffset[]>(s_initialSize))
+    , m_table(makeUniqueArray<StructureOrOffset>(s_initialSize))
     , m_size(0)
     , m_capacity(s_initialSize)
 {
@@ -45,7 +45,7 @@ StructureIDTable::StructureIDTable()
 void StructureIDTable::resize(size_t newCapacity)
 {
     // Create the new table.
-    auto newTable = std::make_unique<StructureOrOffset[]>(newCapacity);
+    auto newTable = makeUniqueArray<StructureOrOffset>(newCapacity);
 
     // Copy the contents of the old table to the new table.
     memcpy(newTable.get(), table(), m_capacity * sizeof(StructureOrOffset));
index a2c58df..7789df8 100644 (file)
@@ -26,6 +26,7 @@
 #pragma once
 
 #include "UnusedPointer.h"
+#include <wtf/UniqueArray.h>
 #include <wtf/Vector.h>
 
 namespace JSC {
@@ -107,10 +108,10 @@ private:
     
     static const size_t s_initialSize = 256;
 
-    Vector<std::unique_ptr<StructureOrOffset[]>> m_oldTables;
+    Vector<UniqueArray<StructureOrOffset>> m_oldTables;
 
     uint32_t m_firstFreeOffset;
-    std::unique_ptr<StructureOrOffset[]> m_table;
+    UniqueArray<StructureOrOffset> m_table;
 
     size_t m_size;
     size_t m_capacity;
index 2c24690..1ae75e4 100644 (file)
@@ -40,13 +40,13 @@ namespace TypeProfilerLogInternal {
 static const bool verbose = false;
 }
 
-void TypeProfilerLog::initializeLog()
+TypeProfilerLog::TypeProfilerLog()
+    : m_logSize(50000)
+    , m_logStartPtr(new LogEntry[m_logSize])
+    , m_currentLogEntryPtr(m_logStartPtr)
+    , m_logEndPtr(m_logStartPtr + m_logSize)
 {
     ASSERT(!m_logStartPtr);
-    m_logSize = 50000;
-    m_logStartPtr = new LogEntry[m_logSize];
-    m_currentLogEntryPtr = m_logStartPtr;
-    m_logEndPtr = m_logStartPtr + m_logSize;
 }
 
 TypeProfilerLog::~TypeProfilerLog()
index 9b57cc5..3941933 100644 (file)
@@ -39,6 +39,7 @@ class TypeProfilerLog {
     WTF_MAKE_FAST_ALLOCATED;
 public:
     struct LogEntry {
+        WTF_MAKE_STRUCT_FAST_ALLOCATED;
     public:
         friend class LLIntOffsetsExtractor;
 
@@ -52,12 +53,7 @@ public:
     };
 
 
-    TypeProfilerLog()
-        : m_logStartPtr(0)
-    {
-        initializeLog();
-    }
-
+    TypeProfilerLog();
     ~TypeProfilerLog();
 
     JS_EXPORT_PRIVATE void processLogEntries(const String&);
@@ -71,8 +67,6 @@ public:
 private:
     friend class LLIntOffsetsExtractor;
 
-    void initializeLog();
-
     unsigned m_logSize;
     LogEntry* m_logStartPtr;
     LogEntry* m_currentLogEntryPtr;
index bebd7c1..4712eb4 100644 (file)
@@ -539,11 +539,6 @@ VM::~VM()
     delete clientData;
     delete m_regExpCache;
 
-#if ENABLE(YARR_JIT_ALL_PARENS_EXPRESSIONS)
-    if (m_regExpPatternContexBuffer)
-        delete[] m_regExpPatternContexBuffer;
-#endif
-
 #if ENABLE(REGEXP_TRACING)
     delete m_rtTraceList;
 #endif
@@ -911,8 +906,8 @@ char* VM::acquireRegExpPatternContexBuffer()
 
     m_regExpPatternContextLock.lock();
     if (!m_regExpPatternContexBuffer)
-        m_regExpPatternContexBuffer = new char[VM::patternContextBufferSize];
-    return m_regExpPatternContexBuffer;
+        m_regExpPatternContexBuffer = makeUniqueArray<char>(VM::patternContextBufferSize);
+    return m_regExpPatternContexBuffer.get();
 }
 
 void VM::releaseRegExpPatternContexBuffer()
index d73fc6b..76db058 100644 (file)
@@ -69,6 +69,7 @@
 #include <wtf/Stopwatch.h>
 #include <wtf/ThreadSafeRefCounted.h>
 #include <wtf/ThreadSpecific.h>
+#include <wtf/UniqueArray.h>
 #include <wtf/text/SymbolRegistry.h>
 #include <wtf/text/WTFString.h>
 #if ENABLE(REGEXP_TRACING)
@@ -685,7 +686,7 @@ public:
 
 #if ENABLE(YARR_JIT_ALL_PARENS_EXPRESSIONS)
     static constexpr size_t patternContextBufferSize = 8192; // Space allocated to save nested parenthesis context
-    char* m_regExpPatternContexBuffer { nullptr };
+    UniqueArray<char> m_regExpPatternContexBuffer;
     Lock m_regExpPatternContextLock;
     char* acquireRegExpPatternContexBuffer();
     void releaseRegExpPatternContexBuffer();
index a6552f0..e6cdd50 100644 (file)
@@ -28,6 +28,7 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <wtf/Vector.h>
 #include <wtf/text/StringBuilder.h>
 
 #if !OS(WINDOWS)
@@ -415,7 +416,7 @@ static bool runFromFiles(GlobalObject* globalObject, const Vector<String>& files
     Vector<char> scriptBuffer;
     unsigned tests = 0;
     unsigned failures = 0;
-    char* lineBuffer = new char[MaxLineLength + 1];
+    Vector<char> lineBuffer(MaxLineLength + 1);
 
     VM& vm = globalObject->vm();
 
@@ -434,7 +435,7 @@ static bool runFromFiles(GlobalObject* globalObject, const Vector<String>& files
         unsigned int lineNumber = 0;
         const char* regexpError = nullptr;
 
-        while ((linePtr = fgets(&lineBuffer[0], MaxLineLength, testCasesFile))) {
+        while ((linePtr = fgets(lineBuffer.data(), MaxLineLength, testCasesFile))) {
             lineLength = strlen(linePtr);
             if (linePtr[lineLength - 1] == '\n') {
                 linePtr[lineLength - 1] = '\0';
@@ -483,8 +484,6 @@ static bool runFromFiles(GlobalObject* globalObject, const Vector<String>& files
     else
         printf("%u tests passed\n", tests);
 
-    delete[] lineBuffer;
-
 #if ENABLE(REGEXP_TRACING)
     vm.dumpRegExpTrace();
 #endif
index cd91ee1..a7f927f 100644 (file)
@@ -43,7 +43,7 @@ HeapVerifier::HeapVerifier(Heap* heap, unsigned numberOfGCCyclesToRecord)
     , m_numberOfCycles(numberOfGCCyclesToRecord)
 {
     RELEASE_ASSERT(m_numberOfCycles > 0);
-    m_cycles = std::make_unique<GCCycle[]>(m_numberOfCycles);
+    m_cycles = makeUniqueArray<GCCycle>(m_numberOfCycles);
 }
 
 const char* HeapVerifier::phaseName(HeapVerifier::Phase phase)
index 4824b1c..cc201c4 100644 (file)
@@ -28,6 +28,7 @@
 #include "CellList.h"
 #include "Heap.h"
 #include <wtf/MonotonicTime.h>
+#include <wtf/UniqueArray.h>
 
 namespace JSC {
 
@@ -64,6 +65,8 @@ public:
 
 private:
     struct GCCycle {
+        WTF_MAKE_STRUCT_FAST_ALLOCATED;
+
         GCCycle()
             : before("Before Marking")
             , after("After Marking")
@@ -107,7 +110,7 @@ private:
     int m_currentCycle;
     int m_numberOfCycles;
     bool m_didPrintLogs { false };
-    std::unique_ptr<GCCycle[]> m_cycles;
+    UniqueArray<GCCycle> m_cycles;
 };
 
 } // namespace JSC
index ddecb24..8be2f56 100644 (file)
@@ -1,3 +1,47 @@
+2018-03-05  Yusuke Suzuki  <utatane.tea@gmail.com>
+
+        Fix std::make_unique / new[] using system malloc
+        https://bugs.webkit.org/show_bug.cgi?id=182975
+
+        Reviewed by JF Bastien.
+
+        If we use `make_unique<char[]>(num)` or `new char[num]`, allocation is
+        done by the system malloc instead of bmalloc. This patch fixes this issue
+        by following three changes.
+
+        1. Introduce UniqueArray<T>. It allocates memory from FastMalloc. While C++
+        array with `new` need to hold the size to call destructor correctly, our
+        UniqueArray only supports type T which does not have a non trivial destructor.
+        It reduces the allocation size since we do not need to track the size of the
+        array compared to standard `new T[]`. This is basically usable if we want to
+        have raw array which pointer won't be changed even if the container is moved.
+        In addition, we also extend UniqueArray<T> for types which have non trivial
+        destructors.
+
+        2. Use Vector<T> instead.
+
+        3. Annotate allocated types with MAKE_FAST_ALLOCATED. Since it introduces
+        new[] and delete[] operators, make_unique<T[]>(num) will allocate memory
+        from FastMalloc.
+
+        * WTF.xcodeproj/project.pbxproj:
+        * wtf/Assertions.cpp:
+        * wtf/CMakeLists.txt:
+        * wtf/FastMalloc.h:
+        (WTF::FastFree::operator() const):
+        (WTF::FastFree<T::operator() const):
+        * wtf/MallocPtr.h:
+        (WTF::MallocPtr::operator bool const):
+        * wtf/StackShot.h:
+        (WTF::StackShot::StackShot):
+        (WTF::StackShot::operator=):
+        * wtf/SystemFree.h:
+        (WTF::SystemFree<T::operator() const):
+        * wtf/UniqueArray.h: Copied from Source/WebKit/Platform/win/LoggingWin.cpp.
+        (WTF::makeUniqueArray):
+        * wtf/Vector.h:
+        (WTF::VectorTypeOperations::forceInitialize):
+
 2018-03-05  Michael Saboff  <msaboff@apple.com>
 
         Start using MAP_JIT for macOS
index b8c7395..ad81d65 100644 (file)
                DE5A09FB1BA36992003D4424 /* CommonCryptoSPI.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CommonCryptoSPI.h; sourceTree = "<group>"; };
                E15556F318A0CC18006F48FB /* CryptographicUtilities.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CryptographicUtilities.cpp; sourceTree = "<group>"; };
                E15556F418A0CC18006F48FB /* CryptographicUtilities.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CryptographicUtilities.h; sourceTree = "<group>"; };
+               E300E521203D645F00DA79BE /* UniqueArray.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = UniqueArray.h; sourceTree = "<group>"; };
                E311FB151F0A568B003C08DE /* ThreadGroup.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ThreadGroup.cpp; sourceTree = "<group>"; };
                E311FB161F0A568B003C08DE /* ThreadGroup.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ThreadGroup.h; sourceTree = "<group>"; };
                E3200AB41E9A536D003B59D2 /* PlatformRegisters.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = PlatformRegisters.h; sourceTree = "<group>"; };
                                149EF16216BBFE0D000A4331 /* TriState.h */,
                                83FBA93119DF459700F30ADB /* TypeCasts.h */,
                                A8A4735C151A825B004123FF /* UnionFind.h */,
+                               E300E521203D645F00DA79BE /* UniqueArray.h */,
                                5C7C88D31D0A3A0A009D2F6D /* UniqueRef.h */,
                                CD7600FF1F90A3CA00026E26 /* UnsafePointer.h */,
                                7AFEC6B01EB22B5900DADE36 /* UUID.cpp */,
index 061093a..0d973e6 100644 (file)
@@ -150,12 +150,12 @@ static void vprintf_stderr_with_prefix(const char* prefix, const char* format, v
 {
     size_t prefixLength = strlen(prefix);
     size_t formatLength = strlen(format);
-    auto formatWithPrefix = std::make_unique<char[]>(prefixLength + formatLength + 1);
-    memcpy(formatWithPrefix.get(), prefix, prefixLength);
-    memcpy(formatWithPrefix.get() + prefixLength, format, formatLength);
+    Vector<char> formatWithPrefix(prefixLength + formatLength + 1);
+    memcpy(formatWithPrefix.data(), prefix, prefixLength);
+    memcpy(formatWithPrefix.data() + prefixLength, format, formatLength);
     formatWithPrefix[prefixLength + formatLength] = 0;
 
-    vprintf_stderr_common(formatWithPrefix.get(), args);
+    vprintf_stderr_common(formatWithPrefix.data(), args);
 }
 
 static void vprintf_stderr_with_trailing_newline(const char* format, va_list args)
@@ -166,12 +166,12 @@ static void vprintf_stderr_with_trailing_newline(const char* format, va_list arg
         return;
     }
 
-    auto formatWithNewline = std::make_unique<char[]>(formatLength + 2);
-    memcpy(formatWithNewline.get(), format, formatLength);
+    Vector<char> formatWithNewline(formatLength + 2);
+    memcpy(formatWithNewline.data(), format, formatLength);
     formatWithNewline[formatLength] = '\n';
     formatWithNewline[formatLength + 1] = 0;
 
-    vprintf_stderr_common(formatWithNewline.get(), args);
+    vprintf_stderr_common(formatWithNewline.data(), args);
 }
 
 #if COMPILER(GCC_OR_CLANG)
index 29fff29..cff143b 100644 (file)
@@ -232,6 +232,7 @@ set(WTF_HEADERS
     Unexpected.h
     UniStdExtras.h
     UnionFind.h
+    UniqueArray.h
     UniqueRef.h
     UnsafePointer.h
     VMTags.h
index 7ec21ae..6672ce4 100644 (file)
@@ -200,6 +200,26 @@ struct FastMalloc {
     static void free(void* p) { fastFree(p); }
 };
 
+template<typename T>
+struct FastFree {
+    static_assert(std::is_trivially_destructible<T>::value, "");
+
+    void operator()(T* pointer) const
+    {
+        fastFree(const_cast<typename std::remove_cv<T>::type*>(pointer));
+    }
+};
+
+template<typename T>
+struct FastFree<T[]> {
+    static_assert(std::is_trivially_destructible<T>::value, "");
+
+    void operator()(T* pointer) const
+    {
+        fastFree(const_cast<typename std::remove_cv<T>::type*>(pointer));
+    }
+};
+
 } // namespace WTF
 
 #if !defined(NDEBUG)
@@ -208,6 +228,7 @@ using WTF::fastSetMaxSingleAllocationSize;
 
 using WTF::FastAllocator;
 using WTF::FastMalloc;
+using WTF::FastFree;
 using WTF::isFastMallocEnabled;
 using WTF::fastCalloc;
 using WTF::fastFree;
index 7f6a02c..66f10aa 100644 (file)
@@ -66,6 +66,11 @@ public:
         return std::exchange(m_ptr, nullptr);
     }
 
+    explicit operator bool() const
+    {
+        return m_ptr;
+    }
+
     bool operator!() const
     {
         return !m_ptr;
index 6efd074..7e32a35 100644 (file)
@@ -26,6 +26,7 @@
 #pragma once
 
 #include <wtf/Assertions.h>
+#include <wtf/UniqueArray.h>
 
 namespace WTF {
 
@@ -37,7 +38,7 @@ public:
         : m_size(size)
     {
         if (size) {
-            m_array = std::make_unique<void*[]>(size);
+            m_array = makeUniqueArray<void*>(size);
             int intSize = size;
             WTFGetBacktrace(m_array.get(), &intSize);
             RELEASE_ASSERT(static_cast<size_t>(intSize) <= size);
@@ -55,7 +56,7 @@ public:
     
     StackShot& operator=(const StackShot& other)
     {
-        std::unique_ptr<void*[]> newArray = std::make_unique<void*[]>(other.m_size);
+        auto newArray = makeUniqueArray<void*>(other.m_size);
         for (size_t i = other.m_size; i--;)
             newArray[i] = other.m_array[i];
         m_size = other.m_size;
@@ -106,8 +107,8 @@ public:
     
 private:
     static void** deletedValueArray() { return bitwise_cast<void**>(static_cast<uintptr_t>(1)); }
-    
-    std::unique_ptr<void*[]> m_array;
+
+    UniqueArray<void*> m_array;
     size_t m_size { 0 };
 };
 
index 3ef7562..73b693f 100644 (file)
@@ -31,6 +31,8 @@ namespace WTF {
 
 template<typename T>
 struct SystemFree {
+    static_assert(std::is_trivially_destructible<T>::value, "");
+
     void operator()(T* pointer) const
     {
         free(const_cast<typename std::remove_cv<T>::type*>(pointer));
@@ -39,11 +41,12 @@ struct SystemFree {
 
 template<typename T>
 struct SystemFree<T[]> {
+    static_assert(std::is_trivially_destructible<T>::value, "");
+
     void operator()(T* pointer) const
     {
         free(const_cast<typename std::remove_cv<T>::type*>(pointer));
     }
-
 };
 
 } // namespace WTF
diff --git a/Source/WTF/wtf/UniqueArray.h b/Source/WTF/wtf/UniqueArray.h
new file mode 100644 (file)
index 0000000..201ad43
--- /dev/null
@@ -0,0 +1,101 @@
+/*
+ * Copyright (C) 2018 Yusuke Suzuki <utatane.tea@gmail.com>. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+#include <wtf/CheckedArithmetic.h>
+#include <wtf/FastMalloc.h>
+#include <wtf/Vector.h>
+
+namespace WTF {
+
+template<bool isTriviallyDestructible, typename T> struct UniqueArrayMaker;
+
+template<typename T>
+struct UniqueArrayMaker<true, T> {
+    using ResultType = typename std::unique_ptr<T[], FastFree<T[]>>;
+
+    static ResultType make(size_t size)
+    {
+        // C++ `new T[N]` stores its `N` to somewhere. Otherwise, `delete []` cannot destroy
+        // these N elements. But we do not want to increase the size of allocated memory.
+        // If it is acceptable, we can just use Vector<T> instead. So this UniqueArray<T> only
+        // accepts the type T which has a trivial destructor. This allows us to skip calling
+        // destructors for N elements. And this allows UniqueArray<T> not to store its N size.
+        static_assert(std::is_trivially_destructible<T>::value, "");
+
+        // Do not use placement new like `new (storage) T[size]()`. `new T[size]()` requires
+        // larger storage than the `sizeof(T) * size` storage since it want to store `size`
+        // to somewhere.
+        T* storage = static_cast<T*>(fastMalloc((Checked<size_t>(sizeof(T)) * size).unsafeGet()));
+        VectorTypeOperations<T>::forceInitialize(storage, storage + size);
+        return ResultType(storage);
+    }
+};
+
+template<typename T>
+struct UniqueArrayMaker<false, T> {
+    // Since we do not know how to store/retrieve N size to/from allocated memory when calling new [] and delete [],
+    // we use new [] and delete [] operators simply. We create UniqueArrayElement container for the type T.
+    // UniqueArrayElement has new [] and delete [] operators for FastMalloc. We allocate UniqueArrayElement[] and cast
+    // it to T[]. When deleting, the custom deleter casts T[] to UniqueArrayElement[] and deletes it.
+    class UniqueArrayElement {
+        WTF_MAKE_FAST_ALLOCATED;
+    public:
+        struct Deleter {
+            void operator()(T* pointer)
+            {
+                delete [] bitwise_cast<UniqueArrayElement*>(pointer);
+            };
+        };
+
+        UniqueArrayElement() = default;
+
+        T value { };
+    };
+    static_assert(sizeof(T) == sizeof(UniqueArrayElement), "");
+
+    using ResultType = typename std::unique_ptr<T[], typename UniqueArrayElement::Deleter>;
+
+    static ResultType make(size_t size)
+    {
+        return ResultType(bitwise_cast<T*>(new UniqueArrayElement[size]()));
+    }
+};
+
+template<typename T>
+using UniqueArray = typename UniqueArrayMaker<std::is_trivially_destructible<T>::value, T>::ResultType;
+
+template<typename T>
+UniqueArray<T> makeUniqueArray(size_t size)
+{
+    static_assert(std::is_same<typename std::remove_extent<T>::type, T>::value, "");
+    return UniqueArrayMaker<std::is_trivially_destructible<T>::value, T>::make(size);
+}
+
+} // namespace WTF
+
+using WTF::UniqueArray;
+using WTF::makeUniqueArray;
index abcabd0..1c88164 100644 (file)
@@ -65,10 +65,15 @@ struct VectorDestructor<true, T>
 template <bool needsInitialization, bool canInitializeWithMemset, typename T>
 struct VectorInitializer;
 
-template<bool ignore, typename T>
-struct VectorInitializer<false, ignore, T>
+template<bool canInitializeWithMemset, typename T>
+struct VectorInitializer<false, canInitializeWithMemset, T>
 {
     static void initialize(T*, T*) {}
+
+    static void forceInitialize(T* begin, T* end)
+    {
+        VectorInitializer<true, canInitializeWithMemset, T>::forceInitialize(begin, end);
+    }
 };
 
 template<typename T>
@@ -77,7 +82,12 @@ struct VectorInitializer<true, false, T>
     static void initialize(T* begin, T* end) 
     {
         for (T* cur = begin; cur != end; ++cur)
-            new (NotNull, cur) T;
+            new (NotNull, cur) T();
+    }
+
+    static void forceInitialize(T* begin, T* end)
+    {
+        initialize(begin, end);
     }
 };
 
@@ -88,6 +98,11 @@ struct VectorInitializer<true, true, T>
     {
         memset(begin, 0, reinterpret_cast<char*>(end) - reinterpret_cast<char*>(begin));
     }
+
+    static void forceInitialize(T* begin, T* end)
+    {
+        initialize(begin, end);
+    }
 };
 
 template <bool canMoveWithMemcpy, typename T>
@@ -230,6 +245,11 @@ struct VectorTypeOperations
         VectorInitializer<VectorTraits<T>::needsInitialization, VectorTraits<T>::canInitializeWithMemset, T>::initialize(begin, end);
     }
 
+    static void forceInitialize(T* begin, T* end)
+    {
+        VectorInitializer<VectorTraits<T>::needsInitialization, VectorTraits<T>::canInitializeWithMemset, T>::forceInitialize(begin, end);
+    }
+
     static void move(T* src, T* srcEnd, T* dst)
     {
         VectorMover<VectorTraits<T>::canMoveWithMemcpy, T>::move(src, srcEnd, dst);
index 7b79c33..ddc025f 100644 (file)
@@ -1,3 +1,80 @@
+2018-03-05  Yusuke Suzuki  <utatane.tea@gmail.com>
+
+        Fix std::make_unique / new[] using system malloc
+        https://bugs.webkit.org/show_bug.cgi?id=182975
+
+        Reviewed by JF Bastien.
+
+        Use Vector, FAST_ALLOCATED, or UniqueArray instead.
+
+        * Modules/webaudio/AudioBufferSourceNode.cpp:
+        (WebCore::AudioBufferSourceNode::setBuffer):
+        * Modules/webaudio/AudioBufferSourceNode.h:
+        * css/StyleRule.h:
+        * cssjit/CompiledSelector.h:
+        * html/HTMLFrameSetElement.h:
+        * html/canvas/WebGLRenderingContextBase.cpp:
+        (WebCore::WebGLRenderingContextBase::copyTexSubImage2D):
+        (WebCore::WebGLRenderingContextBase::simulateVertexAttrib0):
+        (WebCore::WebGLRenderingContextBase::LRUImageBufferCache::LRUImageBufferCache):
+        (WebCore::WebGLRenderingContextBase::LRUImageBufferCache::imageBuffer):
+        (WebCore::WebGLRenderingContextBase::LRUImageBufferCache::bubbleToFront):
+        * html/canvas/WebGLRenderingContextBase.h:
+        * platform/Length.cpp:
+        (WebCore::newCoordsArray):
+        (WebCore::newLengthArray):
+        (): Deleted.
+        * platform/Length.h:
+        * platform/audio/DynamicsCompressor.cpp:
+        (WebCore::DynamicsCompressor::setNumberOfChannels):
+        * platform/audio/DynamicsCompressor.h:
+        * platform/audio/FFTFrame.h:
+        * platform/audio/gstreamer/FFTFrameGStreamer.cpp:
+        (WebCore::FFTFrame::FFTFrame):
+        * platform/graphics/FormatConverter.h:
+        (WebCore::FormatConverter::FormatConverter):
+        * platform/graphics/GraphicsContext3D.cpp:
+        (WebCore::GraphicsContext3D::texImage2DResourceSafe):
+        * platform/graphics/GraphicsContext3D.h:
+        * platform/graphics/ca/win/CACFLayerTreeHost.cpp:
+        (WebCore::getDirtyRects):
+        * platform/graphics/cairo/CairoUtilities.cpp:
+        (WebCore::flipImageSurfaceVertically):
+        * platform/graphics/cg/GraphicsContext3DCG.cpp:
+        (WebCore::GraphicsContext3D::ImageExtractor::extractImage):
+        * platform/graphics/gpu/Texture.cpp:
+        (WebCore::Texture::updateSubRect):
+        * platform/graphics/opengl/GraphicsContext3DOpenGLCommon.cpp:
+        (WebCore::GraphicsContext3D::paintRenderingResultsToCanvas):
+        (WebCore::GraphicsContext3D::compileShader):
+        (WebCore::GraphicsContext3D::getActiveAttribImpl):
+        (WebCore::GraphicsContext3D::getActiveUniformImpl):
+        (WebCore::GraphicsContext3D::getProgramInfoLog):
+        (WebCore::GraphicsContext3D::getShaderInfoLog):
+        * platform/graphics/texmap/TextureMapperShaderProgram.cpp:
+        (WebCore::getShaderLog):
+        (WebCore::getProgramLog):
+        * platform/graphics/win/ImageBufferDataDirect2D.cpp:
+        (WebCore::ImageBufferData::putData):
+        * platform/image-decoders/png/PNGImageDecoder.cpp:
+        (WebCore::PNGImageReader::PNGImageReader):
+        (WebCore::PNGImageReader::close):
+        (WebCore::PNGImageReader::interlaceBuffer const):
+        (WebCore::PNGImageReader::createInterlaceBuffer):
+        * platform/image-decoders/webp/WEBPImageDecoder.cpp:
+        (WebCore::WEBPImageDecoder::decodeFrame):
+        * platform/network/curl/SocketStreamHandleImpl.h:
+        (WebCore::SocketStreamHandleImpl::SocketData::SocketData):
+        * platform/network/curl/SocketStreamHandleImplCurl.cpp:
+        (WebCore::createCopy):
+        (WebCore::SocketStreamHandleImpl::readData):
+        (): Deleted.
+        * platform/network/soup/SocketStreamHandleImpl.h:
+        * platform/network/soup/SocketStreamHandleImplSoup.cpp:
+        (WebCore::SocketStreamHandleImpl::connected):
+        * platform/win/LoggingWin.cpp:
+        (WebCore::logLevelString):
+
 2018-03-05  Yoav Weiss  <yoav@yoav.ws>
 
         Support for preconnect Link headers
index c71f392..5e62c5a 100644 (file)
@@ -421,8 +421,8 @@ void AudioBufferSourceNode::setBuffer(RefPtr<AudioBuffer>&& buffer)
 
         output(0)->setNumberOfChannels(numberOfChannels);
 
-        m_sourceChannels = std::make_unique<const float*[]>(numberOfChannels);
-        m_destinationChannels = std::make_unique<float*[]>(numberOfChannels);
+        m_sourceChannels = makeUniqueArray<const float*>(numberOfChannels);
+        m_destinationChannels = makeUniqueArray<float*>(numberOfChannels);
 
         for (unsigned i = 0; i < numberOfChannels; ++i) 
             m_sourceChannels[i] = buffer->channelData(i)->data();
index f4e63a8..30b79b7 100644 (file)
@@ -26,6 +26,7 @@
 
 #include "AudioScheduledSourceNode.h"
 #include <wtf/Lock.h>
+#include <wtf/UniqueArray.h>
 
 namespace WebCore {
 
@@ -109,8 +110,8 @@ private:
     RefPtr<AudioBuffer> m_buffer;
 
     // Pointers for the buffer and destination.
-    std::unique_ptr<const float*[]> m_sourceChannels;
-    std::unique_ptr<float*[]> m_destinationChannels;
+    UniqueArray<const float*> m_sourceChannels;
+    UniqueArray<float*> m_destinationChannels;
 
     // Used for the "gain" and "playbackRate" attributes.
     RefPtr<AudioParam> m_gain;
index 13ad88f..6fe6aff 100644 (file)
@@ -1,3 +1,15 @@
+2018-03-05  Yusuke Suzuki  <utatane.tea@gmail.com>
+
+        Fix std::make_unique / new[] using system malloc
+        https://bugs.webkit.org/show_bug.cgi?id=182975
+
+        Reviewed by JF Bastien.
+
+        Use Vector instead.
+
+        * pal/win/LoggingWin.cpp:
+        (PAL::logLevelString):
+
 2018-03-04  Yusuke Suzuki  <utatane.tea@gmail.com>
 
         [WTF] Move currentCPUTime and sleep(Seconds) to CPUTime.h and Seconds.h respectively
index 8ca4c96..95cc8d3 100644 (file)
@@ -42,12 +42,12 @@ String logLevelString()
     if (!length)
         return emptyString();
 
-    auto buffer = std::make_unique<char[]>(length);
+    Vector<char> buffer(length);
 
-    if (!GetEnvironmentVariableA(loggingEnvironmentVariable, buffer.get(), length))
+    if (!GetEnvironmentVariableA(loggingEnvironmentVariable, buffer.data(), length))
         return emptyString();
 
-    return String(buffer.get());
+    return String(buffer.data());
 }
 
 }
index 998ace4..2c1fedd 100644 (file)
@@ -26,6 +26,7 @@
 #include "StyleProperties.h"
 #include <wtf/RefPtr.h>
 #include <wtf/TypeCasts.h>
+#include <wtf/UniqueArray.h>
 
 namespace WebCore {
 
@@ -149,7 +150,7 @@ public:
     CompiledSelector& compiledSelectorForListIndex(unsigned index)
     {
         if (!m_compiledSelectors)
-            m_compiledSelectors = std::make_unique<CompiledSelector[]>(m_selectorList.listSize());
+            m_compiledSelectors = makeUniqueArray<CompiledSelector>(m_selectorList.listSize());
         return m_compiledSelectors[index];
     }
     void releaseCompiledSelectors() const
@@ -170,7 +171,7 @@ private:
     CSSSelectorList m_selectorList;
 
 #if ENABLE(CSS_SELECTOR_JIT)
-    mutable std::unique_ptr<CompiledSelector[]> m_compiledSelectors;
+    mutable UniqueArray<CompiledSelector> m_compiledSelectors;
 #endif
 };
 
index a833dba..099ac93 100644 (file)
@@ -55,6 +55,7 @@ private:
 };
 
 struct CompiledSelector {
+    WTF_MAKE_STRUCT_FAST_ALLOCATED;
     SelectorCompilationStatus status;
     JSC::MacroAssemblerCodeRef codeRef;
 #if defined(CSS_SELECTOR_JIT_PROFILING) && CSS_SELECTOR_JIT_PROFILING
index d54cddc..3fd667f 100644 (file)
@@ -24,7 +24,7 @@
 #pragma once
 
 #include "HTMLElement.h"
-#include <memory>
+#include <wtf/UniqueArray.h>
 
 namespace WebCore {
 
@@ -67,8 +67,8 @@ private:
     InsertedIntoAncestorResult insertedIntoAncestor(InsertionType, ContainerNode&) final;
     void removedFromAncestor(RemovalType, ContainerNode&) final;
 
-    std::unique_ptr<Length[]> m_rowLengths;
-    std::unique_ptr<Length[]> m_colLengths;
+    UniqueArray<Length> m_rowLengths;
+    UniqueArray<Length> m_colLengths;
 
     int m_totalRows;
     int m_totalCols;
index 2cdac91..3aaa47e 100644 (file)
@@ -99,6 +99,7 @@
 #include <JavaScriptCore/Uint32Array.h>
 #include <wtf/CheckedArithmetic.h>
 #include <wtf/StdLibExtras.h>
+#include <wtf/UniqueArray.h>
 #include <wtf/text/CString.h>
 #include <wtf/text/StringBuilder.h>
 
@@ -1553,7 +1554,7 @@ void WebGLRenderingContextBase::copyTexSubImage2D(GC3Denum target, GC3Dint level
             synthesizeGLError(GraphicsContext3D::INVALID_ENUM, "copyTexSubImage2D", "Texture has unknown internal format");
             return;
         }
-        std::unique_ptr<unsigned char[]> zero;
+        UniqueArray<unsigned char> zero;
         if (width && height) {
             unsigned size;
             GC3Denum error = m_context->computeImageSizeInBytes(format, type, width, height, m_unpackAlignment, &size, nullptr);
@@ -1561,7 +1562,7 @@ void WebGLRenderingContextBase::copyTexSubImage2D(GC3Denum target, GC3Dint level
                 synthesizeGLError(error, "copyTexSubImage2D", "bad dimensions");
                 return;
             }
-            zero = std::make_unique<unsigned char[]>(size);
+            zero = makeUniqueArray<unsigned char>(size);
             if (!zero) {
                 synthesizeGLError(GraphicsContext3D::INVALID_VALUE, "copyTexSubImage2D", "out of memory");
                 return;
@@ -5761,7 +5762,7 @@ std::optional<bool> WebGLRenderingContextBase::simulateVertexAttrib0(GC3Duint nu
             || attribValue.value[2] != m_vertexAttrib0BufferValue[2]
             || attribValue.value[3] != m_vertexAttrib0BufferValue[3])) {
 
-        auto bufferData = std::make_unique<GC3Dfloat[]>(bufferSize);
+        auto bufferData = makeUniqueArray<GC3Dfloat>(bufferSize);
         for (GC3Duint ii = 0; ii < numVertex + 1; ++ii) {
             bufferData[ii * 4] = attribValue.value[0];
             bufferData[ii * 4 + 1] = attribValue.value[1];
@@ -5907,15 +5908,14 @@ String WebGLRenderingContextBase::ensureNotNull(const String& text) const
 }
 
 WebGLRenderingContextBase::LRUImageBufferCache::LRUImageBufferCache(int capacity)
-    : m_buffers(std::make_unique<std::unique_ptr<ImageBuffer>[]>(capacity))
-    , m_capacity(capacity)
+    : m_buffers(capacity)
 {
 }
 
 ImageBuffer* WebGLRenderingContextBase::LRUImageBufferCache::imageBuffer(const IntSize& size)
 {
-    int i;
-    for (i = 0; i < m_capacity; ++i) {
+    size_t i;
+    for (i = 0; i < m_buffers.size(); ++i) {
         ImageBuffer* buf = m_buffers[i].get();
         if (!buf)
             break;
@@ -5930,7 +5930,8 @@ ImageBuffer* WebGLRenderingContextBase::LRUImageBufferCache::imageBuffer(const I
     std::unique_ptr<ImageBuffer> temp = ImageBuffer::create(size, Unaccelerated);
     if (!temp)
         return nullptr;
-    i = std::min(m_capacity - 1, i);
+    ASSERT(m_buffers.size() > 0);
+    i = std::min(m_buffers.size() - 1, i);
     m_buffers[i] = WTFMove(temp);
 
     ImageBuffer* buf = m_buffers[i].get();
@@ -5938,9 +5939,9 @@ ImageBuffer* WebGLRenderingContextBase::LRUImageBufferCache::imageBuffer(const I
     return buf;
 }
 
-void WebGLRenderingContextBase::LRUImageBufferCache::bubbleToFront(int idx)
+void WebGLRenderingContextBase::LRUImageBufferCache::bubbleToFront(size_t idx)
 {
-    for (int i = idx; i > 0; --i)
+    for (size_t i = idx; i > 0; --i)
         m_buffers[i].swap(m_buffers[i-1]);
 }
 
index 6a3574b..d2a3919 100644 (file)
@@ -517,9 +517,8 @@ protected:
         // The pointer returned is owned by the image buffer map.
         ImageBuffer* imageBuffer(const IntSize& size);
     private:
-        void bubbleToFront(int idx);
-        std::unique_ptr<std::unique_ptr<ImageBuffer>[]> m_buffers;
-        int m_capacity;
+        void bubbleToFront(size_t idx);
+        Vector<std::unique_ptr<ImageBuffer>> m_buffers;
     };
     LRUImageBufferCache m_generatedImageCache { 0 };
 
index d79e039..4658fd0 100644 (file)
@@ -89,7 +89,7 @@ static unsigned countCharacter(StringImpl& string, UChar character)
     return count;
 }
 
-std::unique_ptr<Length[]> newCoordsArray(const String& string, int& len)
+UniqueArray<Length> newCoordsArray(const String& string, int& len)
 {
     unsigned length = string.length();
     StringBuffer<UChar> spacified(length);
@@ -105,7 +105,7 @@ std::unique_ptr<Length[]> newCoordsArray(const String& string, int& len)
     str = str->simplifyWhiteSpace();
 
     len = countCharacter(*str, ' ') + 1;
-    auto r = std::make_unique<Length[]>(len);
+    auto r = makeUniqueArray<Length>(len);
 
     int i = 0;
     unsigned pos = 0;
@@ -123,7 +123,7 @@ std::unique_ptr<Length[]> newCoordsArray(const String& string, int& len)
     return r;
 }
 
-std::unique_ptr<Length[]> newLengthArray(const String& string, int& len)
+UniqueArray<Length> newLengthArray(const String& string, int& len)
 {
     RefPtr<StringImpl> str = string.impl()->simplifyWhiteSpace();
     if (!str->length()) {
@@ -132,7 +132,7 @@ std::unique_ptr<Length[]> newLengthArray(const String& string, int& len)
     }
 
     len = countCharacter(*str, ',') + 1;
-    auto r = std::make_unique<Length[]>(len);
+    auto r = makeUniqueArray<Length>(len);
 
     int i = 0;
     unsigned pos = 0;
index 57ce0ce..64a08e8 100644 (file)
@@ -29,6 +29,7 @@
 #include <wtf/Assertions.h>
 #include <wtf/FastMalloc.h>
 #include <wtf/Forward.h>
+#include <wtf/UniqueArray.h>
 
 namespace WTF {
 class TextStream;
@@ -138,8 +139,8 @@ private:
 // Blend two lengths to produce a new length that is in between them. Used for animation.
 Length blend(const Length& from, const Length& to, double progress);
 
-std::unique_ptr<Length[]> newCoordsArray(const String&, int& length);
-std::unique_ptr<Length[]> newLengthArray(const String&, int& length);
+UniqueArray<Length> newCoordsArray(const String&, int& length);
+UniqueArray<Length> newLengthArray(const String&, int& length);
 
 inline Length::Length(LengthType type)
     : m_intValue(0), m_hasQuirk(false), m_type(type), m_isFloat(false)
index 30125ae..b25518d 100644 (file)
@@ -275,8 +275,8 @@ void DynamicsCompressor::setNumberOfChannels(unsigned numberOfChannels)
         m_postFilterPacks.append(std::make_unique<ZeroPoleFilterPack4>());
     }
 
-    m_sourceChannels = std::make_unique<const float*[]>(numberOfChannels);
-    m_destinationChannels = std::make_unique<float*[]>(numberOfChannels);
+    m_sourceChannels = makeUniqueArray<const float*>(numberOfChannels);
+    m_destinationChannels = makeUniqueArray<float*>(numberOfChannels);
 
     m_compressor.setNumberOfChannels(numberOfChannels);
     m_numberOfChannels = numberOfChannels;
index a11d87d..f716cef 100644 (file)
@@ -32,6 +32,7 @@
 #include "DynamicsCompressorKernel.h"
 #include "ZeroPole.h"
 #include <memory>
+#include <wtf/UniqueArray.h>
 
 namespace WebCore {
 
@@ -101,8 +102,8 @@ protected:
     Vector<std::unique_ptr<ZeroPoleFilterPack4>> m_preFilterPacks;
     Vector<std::unique_ptr<ZeroPoleFilterPack4>> m_postFilterPacks;
 
-    std::unique_ptr<const float*[]> m_sourceChannels;
-    std::unique_ptr<float*[]> m_destinationChannels;
+    UniqueArray<const float*> m_sourceChannels;
+    UniqueArray<float*> m_destinationChannels;
 
     void setEmphasisStageParameters(unsigned stageIndex, float gain, float normalizedFrequency /* 0 -> 1 */);
     void setEmphasisParameters(float gain, float anchorFreq, float filterStageRatio);
index 40620fb..727c92a 100644 (file)
@@ -44,6 +44,7 @@ G_END_DECLS
 
 #include <memory>
 #include <wtf/Forward.h>
+#include <wtf/UniqueArray.h>
 
 namespace WebCore {
 
@@ -107,7 +108,7 @@ private:
 #if USE(WEBAUDIO_GSTREAMER)
     GstFFTF32* m_fft;
     GstFFTF32* m_inverseFft;
-    std::unique_ptr<GstFFTF32Complex[]> m_complexData;
+    UniqueArray<GstFFTF32Complex> m_complexData;
     AudioFloatArray m_realData;
     AudioFloatArray m_imagData;
 #endif // USE(WEBAUDIO_GSTREAMER)
index 6566c18..1b66e40 100644 (file)
@@ -43,7 +43,7 @@ namespace WebCore {
 FFTFrame::FFTFrame(unsigned fftSize)
     : m_FFTSize(fftSize)
     , m_log2FFTSize(static_cast<unsigned>(log2(fftSize)))
-    , m_complexData(std::make_unique<GstFFTF32Complex[]>(unpackedFFTDataSize(m_FFTSize)))
+    , m_complexData(makeUniqueArray<GstFFTF32Complex>(unpackedFFTDataSize(m_FFTSize)))
     , m_realData(unpackedFFTDataSize(m_FFTSize))
     , m_imagData(unpackedFFTDataSize(m_FFTSize))
 {
@@ -66,7 +66,7 @@ FFTFrame::FFTFrame()
 FFTFrame::FFTFrame(const FFTFrame& frame)
     : m_FFTSize(frame.m_FFTSize)
     , m_log2FFTSize(frame.m_log2FFTSize)
-    , m_complexData(std::make_unique<GstFFTF32Complex[]>(unpackedFFTDataSize(m_FFTSize)))
+    , m_complexData(makeUniqueArray<GstFFTF32Complex>(unpackedFFTDataSize(m_FFTSize)))
     , m_realData(unpackedFFTDataSize(frame.m_FFTSize))
     , m_imagData(unpackedFFTDataSize(frame.m_FFTSize))
 {
index dd97b37..58fce0f 100644 (file)
@@ -29,6 +29,7 @@
 
 #include "GraphicsContext3D.h"
 #include <wtf/StdLibExtras.h>
+#include <wtf/UniqueArray.h>
 
 namespace WebCore {
 
@@ -45,7 +46,7 @@ public:
     {
         const unsigned MaxNumberOfComponents = 4;
         const unsigned MaxBytesPerComponent  = 4;
-        m_unpackedIntermediateSrcData = std::make_unique<uint8_t[]>(m_width * MaxNumberOfComponents * MaxBytesPerComponent);
+        m_unpackedIntermediateSrcData = makeUniqueArray<uint8_t>((Checked<size_t>(m_width) * MaxNumberOfComponents * MaxBytesPerComponent).unsafeGet());
 
         ASSERT(m_unpackedIntermediateSrcData.get());
     }
@@ -68,7 +69,7 @@ private:
     void* const m_dstStart;
     const int m_srcStride, m_dstStride;
     bool m_success;
-    std::unique_ptr<uint8_t[]> m_unpackedIntermediateSrcData;
+    UniqueArray<uint8_t> m_unpackedIntermediateSrcData;
 };
 
 } // namespace WebCore
index 4e757a0..322bed0 100644 (file)
@@ -36,6 +36,7 @@
 #include "Image.h"
 #include "ImageData.h"
 #include "ImageObserver.h"
+#include <wtf/UniqueArray.h>
 
 namespace WebCore {
 
@@ -146,7 +147,7 @@ GraphicsContext3D::DataFormat getDataFormat(GC3Denum destinationFormat, GC3Denum
 bool GraphicsContext3D::texImage2DResourceSafe(GC3Denum target, GC3Dint level, GC3Denum internalformat, GC3Dsizei width, GC3Dsizei height, GC3Dint border, GC3Denum format, GC3Denum type, GC3Dint unpackAlignment)
 {
     ASSERT(unpackAlignment == 1 || unpackAlignment == 2 || unpackAlignment == 4 || unpackAlignment == 8);
-    std::unique_ptr<unsigned char[]> zero;
+    UniqueArray<unsigned char> zero;
     if (width > 0 && height > 0) {
         unsigned int size;
         GC3Denum error = computeImageSizeInBytes(format, type, width, height, unpackAlignment, &size, nullptr);
@@ -154,7 +155,7 @@ bool GraphicsContext3D::texImage2DResourceSafe(GC3Denum target, GC3Dint level, G
             synthesizeGLError(error);
             return false;
         }
-        zero = std::make_unique<unsigned char[]>(size);
+        zero = makeUniqueArray<unsigned char>(size);
         if (!zero) {
             synthesizeGLError(GraphicsContext3D::INVALID_VALUE);
             return false;
index 181b467..2e74879 100644 (file)
@@ -37,6 +37,7 @@
 #include <wtf/ListHashSet.h>
 #include <wtf/RefCounted.h>
 #include <wtf/RetainPtr.h>
+#include <wtf/UniqueArray.h>
 #include <wtf/text/WTFString.h>
 
 #if USE(CA)
@@ -1261,7 +1262,7 @@ public:
         RetainPtr<CGImageRef> m_cgImage;
         RetainPtr<CGImageRef> m_decodedImage;
         RetainPtr<CFDataRef> m_pixelData;
-        std::unique_ptr<uint8_t[]> m_formalizedRGBA8Data;
+        UniqueArray<uint8_t> m_formalizedRGBA8Data;
 #endif
         Image* m_image;
         ImageHtmlDomSource m_imageHtmlDomSource;
index 1504581..bae5ace 100644 (file)
@@ -43,6 +43,7 @@
 #include <limits.h>
 #include <QuartzCore/CABase.h>
 #include <wtf/StdLibExtras.h>
+#include <wtf/UniqueArray.h>
 #include <wtf/win/GDIObject.h>
 
 #ifdef DEBUG_ALL
@@ -261,7 +262,7 @@ static void getDirtyRects(HWND window, Vector<CGRect>& outRects)
     }
 
     DWORD dataSize = ::GetRegionData(region.get(), 0, 0);
-    auto regionDataBuffer = std::make_unique<unsigned char[]>(dataSize);
+    auto regionDataBuffer = makeUniqueArray<unsigned char>(dataSize);
     RGNDATA* regionData = reinterpret_cast<RGNDATA*>(regionDataBuffer.get());
     if (!::GetRegionData(region.get(), dataSize, regionData))
         return;
index 24d4eb5..04d682f 100644 (file)
@@ -40,6 +40,7 @@
 #include "Region.h"
 #include <wtf/Assertions.h>
 #include <wtf/NeverDestroyed.h>
+#include <wtf/UniqueArray.h>
 #include <wtf/Vector.h>
 
 #if ENABLE(ACCELERATED_2D_CANVAS)
@@ -340,7 +341,7 @@ void flipImageSurfaceVertically(cairo_surface_t* surface)
     int halfHeight = size.height() / 2;
 
     uint8_t* source = static_cast<uint8_t*>(cairo_image_surface_get_data(surface));
-    std::unique_ptr<uint8_t[]> tmp = std::make_unique<uint8_t[]>(stride);
+    auto tmp = makeUniqueArray<uint8_t>(stride);
 
     for (int i = 0; i < halfHeight; ++i) {
         uint8_t* top = source + (i * stride);
index 8eb6f4e..9daff78 100644 (file)
@@ -478,7 +478,7 @@ bool GraphicsContext3D::ImageExtractor::extractImage(bool premultiplyAlpha, bool
     // but it would premultiply the alpha channel as a side effect.
     // Prefer to mannually Convert 16bit per-component formats to RGBA8 formats instead.
     if (bitsPerComponent == 16) {
-        m_formalizedRGBA8Data = std::make_unique<uint8_t[]>(m_imageWidth * m_imageHeight * 4);
+        m_formalizedRGBA8Data = makeUniqueArray<uint8_t>((Checked<size_t>(m_imageWidth) * m_imageHeight * 4U).unsafeGet());
         const uint16_t* source = reinterpret_cast<const uint16_t*>(m_imagePixelData);
         uint8_t* destination = m_formalizedRGBA8Data.get();
         const ptrdiff_t srcStrideInElements = bytesPerRow / sizeof(uint16_t);
index ad22b47..8698136 100644 (file)
@@ -40,6 +40,7 @@
 #include "IntRect.h"
 #include <algorithm>
 #include <wtf/StdLibExtras.h>
+#include <wtf/UniqueArray.h>
 
 namespace WebCore {
 
@@ -170,7 +171,7 @@ void Texture::updateSubRect(void* pixels, const IntRect& updateRect)
     int tempBuffSize = // Temporary buffer size is the smaller of the max texture size or the updateRectSanitized
         std::min(m_tiles.maxTextureSize().width(), m_tiles.borderTexels() + updateRectSanitized.width()) *
         std::min(m_tiles.maxTextureSize().height(), m_tiles.borderTexels() + updateRectSanitized.height());
-    auto tempBuff = std::make_unique<uint32_t[]>(tempBuffSize);
+    auto tempBuff = makeUniqueArray<uint32_t>(tempBuffSize);
 
     for (int tile = 0; tile < m_tiles.numTilesX() * m_tiles.numTilesY(); tile++) {
         int xIndex = tile % m_tiles.numTilesX();
index df0a0b8..547274f 100644 (file)
@@ -54,6 +54,7 @@
 #include <wtf/HexNumber.h>
 #include <wtf/MainThread.h>
 #include <wtf/ThreadSpecific.h>
+#include <wtf/UniqueArray.h>
 #include <wtf/text/CString.h>
 #include <wtf/text/StringBuilder.h>
 
@@ -168,7 +169,7 @@ void GraphicsContext3D::paintRenderingResultsToCanvas(ImageBuffer* imageBuffer)
         return;
     int totalBytes = totalBytesChecked.unsafeGet();
 
-    auto pixels = std::make_unique<unsigned char[]>(totalBytes);
+    auto pixels = makeUniqueArray<unsigned char>(totalBytes);
     if (!pixels)
         return;
 
@@ -668,11 +669,11 @@ void GraphicsContext3D::compileShader(Platform3DObject shader)
 
     if (length) {
         GLsizei size = 0;
-        auto info = std::make_unique<GLchar[]>(length);
-        ::glGetShaderInfoLog(shader, length, &size, info.get());
+        Vector<GLchar> info(length);
+        ::glGetShaderInfoLog(shader, length, &size, info.data());
 
         Platform3DObject shaders[2] = { shader, 0 };
-        entry.log = getUnmangledInfoLog(shaders, 1, String(info.get()));
+        entry.log = getUnmangledInfoLog(shaders, 1, String(info.data(), size));
     }
 
     if (compileStatus != GL_TRUE) {
@@ -851,18 +852,18 @@ bool GraphicsContext3D::getActiveAttribImpl(Platform3DObject program, GC3Duint i
     makeContextCurrent();
     GLint maxAttributeSize = 0;
     ::glGetProgramiv(program, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &maxAttributeSize);
-    auto name = std::make_unique<GLchar[]>(maxAttributeSize); // GL_ACTIVE_ATTRIBUTE_MAX_LENGTH includes null termination.
+    Vector<GLchar> name(maxAttributeSize); // GL_ACTIVE_ATTRIBUTE_MAX_LENGTH includes null termination.
     GLsizei nameLength = 0;
     GLint size = 0;
     GLenum type = 0;
-    ::glGetActiveAttrib(program, index, maxAttributeSize, &nameLength, &size, &type, name.get());
+    ::glGetActiveAttrib(program, index, maxAttributeSize, &nameLength, &size, &type, name.data());
     if (!nameLength)
         return false;
     
-    String originalName = originalSymbolName(program, SHADER_SYMBOL_TYPE_ATTRIBUTE, String(name.get(), nameLength));
+    String originalName = originalSymbolName(program, SHADER_SYMBOL_TYPE_ATTRIBUTE, String(name.data(), nameLength));
     
 #ifndef NDEBUG
-    String uniformName(name.get(), nameLength);
+    String uniformName(name.data(), nameLength);
     LOG(WebGL, "Program %d is mapping active attribute %d from '%s' to '%s'", program, index, uniformName.utf8().data(), originalName.utf8().data());
 #endif
 
@@ -898,18 +899,18 @@ bool GraphicsContext3D::getActiveUniformImpl(Platform3DObject program, GC3Duint
     GLint maxUniformSize = 0;
     ::glGetProgramiv(program, GL_ACTIVE_UNIFORM_MAX_LENGTH, &maxUniformSize);
 
-    auto name = std::make_unique<GLchar[]>(maxUniformSize); // GL_ACTIVE_UNIFORM_MAX_LENGTH includes null termination.
+    Vector<GLchar> name(maxUniformSize); // GL_ACTIVE_UNIFORM_MAX_LENGTH includes null termination.
     GLsizei nameLength = 0;
     GLint size = 0;
     GLenum type = 0;
-    ::glGetActiveUniform(program, index, maxUniformSize, &nameLength, &size, &type, name.get());
+    ::glGetActiveUniform(program, index, maxUniformSize, &nameLength, &size, &type, name.data());
     if (!nameLength)
         return false;
     
-    String originalName = originalSymbolName(program, SHADER_SYMBOL_TYPE_UNIFORM, String(name.get(), nameLength));
+    String originalName = originalSymbolName(program, SHADER_SYMBOL_TYPE_UNIFORM, String(name.data(), nameLength));
     
 #ifndef NDEBUG
-    String uniformName(name.get(), nameLength);
+    String uniformName(name.data(), nameLength);
     LOG(WebGL, "Program %d is mapping active uniform %d from '%s' to '%s'", program, index, uniformName.utf8().data(), originalName.utf8().data());
 #endif
     
@@ -1699,14 +1700,14 @@ String GraphicsContext3D::getProgramInfoLog(Platform3DObject program)
         return String(); 
 
     GLsizei size = 0;
-    auto info = std::make_unique<GLchar[]>(length);
-    ::glGetProgramInfoLog(program, length, &size, info.get());
+    Vector<GLchar> info(length);
+    ::glGetProgramInfoLog(program, length, &size, info.data());
 
     GC3Dsizei count;
     Platform3DObject shaders[2];
     getAttachedShaders(program, 2, &count, shaders);
 
-    return getUnmangledInfoLog(shaders, count, String(info.get()));
+    return getUnmangledInfoLog(shaders, count, String(info.data(), size));
 }
 
 void GraphicsContext3D::getRenderbufferParameteriv(GC3Denum target, GC3Denum pname, GC3Dint* value)
@@ -1770,11 +1771,11 @@ String GraphicsContext3D::getShaderInfoLog(Platform3DObject shader)
         return String(); 
 
     GLsizei size = 0;
-    auto info = std::make_unique<GLchar[]>(length);
-    ::glGetShaderInfoLog(shader, length, &size, info.get());
+    Vector<GLchar> info(length);
+    ::glGetShaderInfoLog(shader, length, &size, info.data());
 
     Platform3DObject shaders[2] = { shader, 0 };
-    return getUnmangledInfoLog(shaders, 1, String(info.get()));
+    return getUnmangledInfoLog(shaders, 1, String(info.data(), size));
 }
 
 String GraphicsContext3D::getShaderSource(Platform3DObject shader)
index abedf53..2e6c52c 100644 (file)
@@ -450,12 +450,12 @@ static CString getShaderLog(GLuint shader)
     if (!logLength)
         return { };
 
-    auto info = std::make_unique<GLchar[]>(logLength);
+    Vector<GLchar> info(logLength);
     GLsizei infoLength = 0;
-    glGetShaderInfoLog(shader, logLength, &infoLength, info.get());
+    glGetShaderInfoLog(shader, logLength, &infoLength, info.data());
 
     size_t stringLength = std::max(infoLength, 0);
-    return { info.get(), stringLength };
+    return { info.data(), stringLength };
 }
 
 static CString getProgramLog(GLuint program)
@@ -465,12 +465,12 @@ static CString getProgramLog(GLuint program)
     if (!logLength)
         return { };
 
-    auto info = std::make_unique<GLchar[]>(logLength);
+    Vector<GLchar> info(logLength);
     GLsizei infoLength = 0;
-    glGetProgramInfoLog(program, logLength, &infoLength, info.get());
+    glGetProgramInfoLog(program, logLength, &infoLength, info.data());
 
     size_t stringLength = std::max(infoLength, 0);
-    return { info.get(), stringLength };
+    return { info.data(), stringLength };
 }
 #endif
 
index 3edad18..f0e2580 100644 (file)
@@ -38,6 +38,7 @@
 #include <JavaScriptCore/Uint8ClampedArray.h>
 #include <d2d1.h>
 #include <wtf/Assertions.h>
+#include <wtf/UniqueArray.h>
 
 namespace WebCore {
 
@@ -134,7 +135,7 @@ void ImageBufferData::putData(const Uint8ClampedArray& source, AlphaPremultiplic
     unsigned srcBytesPerRow = 4 * sourceSize.width();
     const uint8_t* srcRows = source.data() + (originy * srcBytesPerRow + originx * 4).unsafeGet();
 
-    uint8_t* row = new uint8_t[srcBytesPerRow];
+    auto row = makeUniqueArray<uint8_t>(srcBytesPerRow);
 
     for (int y = 0; y < height.unsafeGet(); ++y) {
         for (int x = 0; x < width.unsafeGet(); x++) {
@@ -146,17 +147,15 @@ void ImageBufferData::putData(const Uint8ClampedArray& source, AlphaPremultiplic
                 row[basex + 2] = (srcRows[basex + 2] * alpha + 254) / 255;
                 row[basex + 3] = alpha;
             } else
-                reinterpret_cast<uint32_t*>(row + basex)[0] = reinterpret_cast<uint32_t*>(srcRows + basex)[0];
+                reinterpret_cast<uint32_t*>(row.get() + basex)[0] = reinterpret_cast<uint32_t*>(srcRows + basex)[0];
         }
 
         D2D1_RECT_U dstRect = D2D1::RectU(destPoint.x(), destPoint.y() + y, destPoint.x() + size.width(), destPoint.y() + y + 1);
-        hr = bitmap->CopyFromMemory(&dstRect, row, srcBytesPerRow);
+        hr = bitmap->CopyFromMemory(&dstRect, row.get(), srcBytesPerRow);
         ASSERT(SUCCEEDED(hr));
 
         srcRows += srcBytesPerRow;
     }
-
-    delete[] row;
 }
 
 } // namespace WebCore
index d5c9124..a9f3736 100644 (file)
@@ -44,6 +44,7 @@
 #include "Color.h"
 #include <png.h>
 #include <wtf/StdLibExtras.h>
+#include <wtf/UniqueArray.h>
 
 #if defined(PNG_LIBPNG_VER_MAJOR) && defined(PNG_LIBPNG_VER_MINOR) && (PNG_LIBPNG_VER_MAJOR > 1 || (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR >= 4))
 #define JMPBUF(png_ptr) png_jmpbuf(png_ptr)
@@ -120,7 +121,6 @@ public:
         , m_currentBufferSize(0)
         , m_decodingSizeOnly(false)
         , m_hasAlpha(false)
-        , m_interlaceBuffer(0)
     {
         m_png = png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, decodingFailed, decodingWarning);
         m_info = png_create_info_struct(m_png);
@@ -143,8 +143,7 @@ public:
         if (m_png && m_info)
             // This will zero the pointers.
             png_destroy_read_struct(&m_png, &m_info, 0);
-        delete[] m_interlaceBuffer;
-        m_interlaceBuffer = 0;
+        m_interlaceBuffer.reset();
         m_readOffset = 0;
     }
 
@@ -188,8 +187,8 @@ public:
     void setHasAlpha(bool hasAlpha) { m_hasAlpha = hasAlpha; }
     bool hasAlpha() const { return m_hasAlpha; }
 
-    png_bytep interlaceBuffer() const { return m_interlaceBuffer; }
-    void createInterlaceBuffer(int size) { m_interlaceBuffer = new png_byte[size]; }
+    png_bytep interlaceBuffer() const { return m_interlaceBuffer.get(); }
+    void createInterlaceBuffer(int size) { m_interlaceBuffer = makeUniqueArray<png_byte>(size); }
 
 private:
     png_structp m_png;
@@ -198,7 +197,7 @@ private:
     unsigned m_currentBufferSize;
     bool m_decodingSizeOnly;
     bool m_hasAlpha;
-    png_bytep m_interlaceBuffer;
+    UniqueArray<png_byte> m_interlaceBuffer;
 };
 
 PNGImageDecoder::PNGImageDecoder(AlphaOption alphaOption, GammaAndColorProfileOption gammaAndColorProfileOption)
index f5c0eaf..92677b9 100644 (file)
@@ -28,6 +28,7 @@
 
 #include "config.h"
 #include "WEBPImageDecoder.h"
+#include <wtf/UniqueArray.h>
 
 #if USE(WEBP)
 
@@ -185,7 +186,7 @@ void WEBPImageDecoder::decodeFrame(size_t frameIndex, WebPDemuxer* demuxer)
     decoderBuffer.u.RGBA.stride = webpFrame.width * sizeof(uint32_t);
     decoderBuffer.u.RGBA.size = decoderBuffer.u.RGBA.stride * webpFrame.height;
     decoderBuffer.is_external_memory = 1;
-    std::unique_ptr<unsigned char[]> p(new uint8_t[decoderBuffer.u.RGBA.size]());
+    auto p = makeUniqueArray<uint8_t>(decoderBuffer.u.RGBA.size);
     decoderBuffer.u.RGBA.rgba = p.get();
     if (!decoderBuffer.u.RGBA.rgba) {
         setFailed();
index 342be56..5c4ca29 100644 (file)
@@ -45,6 +45,7 @@
 #include <wtf/Seconds.h>
 #include <wtf/StreamBuffer.h>
 #include <wtf/Threading.h>
+#include <wtf/UniqueArray.h>
 
 namespace WebCore {
 
@@ -76,7 +77,7 @@ private:
     void didOpenSocket();
 
     struct SocketData {
-        SocketData(std::unique_ptr<char[]>&& source, size_t length)
+        SocketData(UniqueArray<char>&& source, size_t length)
         {
             data = WTFMove(source);
             size = length;
@@ -89,7 +90,7 @@ private:
             other.size = 0;
         }
 
-        std::unique_ptr<char[]> data;
+        UniqueArray<char> data;
         size_t size { 0 };
     };
 
index 6fcbf83..5a45dd8 100644 (file)
@@ -44,9 +44,9 @@
 
 namespace WebCore {
 
-static std::unique_ptr<char[]> createCopy(const char* data, int length)
+static UniqueArray<char> createCopy(const char* data, int length)
 {
-    std::unique_ptr<char[]> copy(new char[length]);
+    auto copy = makeUniqueArray<char>(length);
     memcpy(copy.get(), data, length);
 
     return copy;
@@ -98,7 +98,7 @@ bool SocketStreamHandleImpl::readData(CURL* curlHandle)
     ASSERT(!isMainThread());
 
     const size_t bufferSize = 1024;
-    std::unique_ptr<char[]> data(new char[bufferSize]);
+    auto data = makeUniqueArray<char>(bufferSize);
     size_t bytesRead = 0;
 
     CURLcode ret = curl_easy_recv(curlHandle, data.get(), bufferSize, &bytesRead);
index e0a8f9d..8a32eb1 100644 (file)
@@ -38,6 +38,7 @@
 
 #include <pal/SessionID.h>
 #include <wtf/StreamBuffer.h>
+#include <wtf/UniqueArray.h>
 #include <wtf/glib/GRefPtr.h>
 
 namespace WebCore {
@@ -76,7 +77,7 @@ private:
     GRefPtr<GPollableOutputStream> m_outputStream;
     GRefPtr<GSource> m_writeReadySource;
     GRefPtr<GCancellable> m_cancellable;
-    std::unique_ptr<char[]> m_readBuffer;
+    UniqueArray<char> m_readBuffer;
 
     StreamBuffer<char, 1024 * 1024> m_buffer;
     static const unsigned maxBufferSize = 100 * 1024 * 1024;
index 44c13db..1788066 100644 (file)
@@ -124,7 +124,7 @@ void SocketStreamHandleImpl::connected(GRefPtr<GIOStream>&& stream)
     m_stream = WTFMove(stream);
     m_outputStream = G_POLLABLE_OUTPUT_STREAM(g_io_stream_get_output_stream(m_stream.get()));
     m_inputStream = g_io_stream_get_input_stream(m_stream.get());
-    m_readBuffer = std::make_unique<char[]>(READ_BUFFER_SIZE);
+    m_readBuffer = makeUniqueArray<char>(READ_BUFFER_SIZE);
 
     RefPtr<SocketStreamHandleImpl> protectedThis(this);
     g_input_stream_read_async(m_inputStream.get(), m_readBuffer.get(), READ_BUFFER_SIZE, RunLoopSourcePriority::AsyncIONetwork, m_cancellable.get(),
index a9ee4ed..35d7698 100644 (file)
@@ -42,12 +42,12 @@ String logLevelString()
     if (!length)
         return emptyString();
 
-    auto buffer = std::make_unique<char[]>(length);
+    Vector<char> buffer(length);
 
-    if (!GetEnvironmentVariableA(loggingEnvironmentVariable, buffer.get(), length))
+    if (!GetEnvironmentVariableA(loggingEnvironmentVariable, buffer.data(), length))
         return emptyString();
 
-    return String(buffer.get());
+    return String(buffer.data());
 }
 
 } // namespace WebCore
index b46fcf0..ab5e561 100644 (file)
@@ -1,3 +1,27 @@
+2018-03-05  Yusuke Suzuki  <utatane.tea@gmail.com>
+
+        Fix std::make_unique / new[] using system malloc
+        https://bugs.webkit.org/show_bug.cgi?id=182975
+
+        Reviewed by JF Bastien.
+
+        Use Vector instead.
+
+        * NetworkProcess/win/SystemProxyWin.cpp:
+        (WindowsSystemProxy::getSystemHttpProxy):
+        * Platform/IPC/unix/ConnectionUnix.cpp:
+        (IPC::Connection::processMessage):
+        (IPC::Connection::sendOutputMessage):
+        * Platform/win/LoggingWin.cpp:
+        (WebKit::logLevelString):
+        * Shared/SandboxExtension.h:
+        * Shared/mac/SandboxExtensionMac.mm:
+        (WebKit::SandboxExtension::HandleArray::allocate):
+        (WebKit::SandboxExtension::HandleArray::operator[]):
+        (WebKit::SandboxExtension::HandleArray::operator[] const):
+        (WebKit::SandboxExtension::HandleArray::size const):
+        (WebKit::SandboxExtension::HandleArray::encode const):
+
 2018-03-05  Andy Estes  <aestes@apple.com>
 
         [Mac] Teach WebCore::Pasteboard about file promise drags
index 95362fa..d1732dd 100644 (file)
 
 bool WindowsSystemProxy::getSystemHttpProxy(char* buffer, int bufferLen, int* port)
 {
-    std::unique_ptr<TCHAR[]> tRegBuffer = std::make_unique<TCHAR[]>(bufferLen);
-    std::unique_ptr<TCHAR[]> tHost = std::make_unique<TCHAR[]>(bufferLen);
-    if (!tRegBuffer || !tHost)
-        return false;
+    Vector<TCHAR> tRegBuffer(bufferLen);
+    Vector<TCHAR> tHost(bufferLen);
     DWORD type;
     DWORD size;
     HKEY key;
@@ -51,16 +49,16 @@ bool WindowsSystemProxy::getSystemHttpProxy(char* buffer, int bufferLen, int* po
         L"ProxyServer",
         nullptr,
         &type,
-        (LPBYTE)tRegBuffer.get(),
+        (LPBYTE)tRegBuffer.data(),
         &size);
 
     if (ret != ERROR_SUCCESS)
         return false;
 
-    if (!parseProxyString(tRegBuffer.get(), tHost.get(), bufferLen, port))
+    if (!parseProxyString(tRegBuffer.data(), tHost.data(), bufferLen, port))
         return false;
 
-    wcstombs(buffer, tHost.get(), bufferLen);
+    wcstombs(buffer, tHost.data(), bufferLen);
     buffer[bufferLen-1] = '\0';
     return true;
 }
index 203c56a..3c46394 100644 (file)
@@ -143,11 +143,10 @@ bool Connection::processMessage()
 
     size_t attachmentFileDescriptorCount = 0;
     size_t attachmentCount = messageInfo.attachmentCount();
-    std::unique_ptr<AttachmentInfo[]> attachmentInfo;
+    Vector<AttachmentInfo> attachmentInfo(attachmentCount);
 
     if (attachmentCount) {
-        attachmentInfo = std::make_unique<AttachmentInfo[]>(attachmentCount);
-        memcpy(attachmentInfo.get(), messageData, sizeof(AttachmentInfo) * attachmentCount);
+        memcpy(attachmentInfo.data(), messageData, sizeof(AttachmentInfo) * attachmentCount);
         messageData += sizeof(AttachmentInfo) * attachmentCount;
 
         for (size_t i = 0; i < attachmentCount; ++i) {
@@ -417,7 +416,7 @@ bool Connection::sendOutputMessage(UnixMessage& outputMessage)
     iov[0].iov_base = reinterpret_cast<void*>(&messageInfo);
     iov[0].iov_len = sizeof(messageInfo);
 
-    std::unique_ptr<AttachmentInfo[]> attachmentInfo;
+    Vector<AttachmentInfo> attachmentInfo;
     MallocPtr<char> attachmentFDBuffer;
 
     auto& attachments = outputMessage.attachments();
@@ -444,7 +443,7 @@ bool Connection::sendOutputMessage(UnixMessage& outputMessage)
             fdPtr = reinterpret_cast<int*>(CMSG_DATA(cmsg));
         }
 
-        attachmentInfo = std::make_unique<AttachmentInfo[]>(attachments.size());
+        attachmentInfo.resize(attachments.size());
         int fdIndex = 0;
         for (size_t i = 0; i < attachments.size(); ++i) {
             attachmentInfo[i].setType(attachments[i].type());
@@ -466,7 +465,7 @@ bool Connection::sendOutputMessage(UnixMessage& outputMessage)
             }
         }
 
-        iov[iovLength].iov_base = attachmentInfo.get();
+        iov[iovLength].iov_base = attachmentInfo.data();
         iov[iovLength].iov_len = sizeof(AttachmentInfo) * attachments.size();
         ++iovLength;
     }
index 6de1bab..d0638d3 100644 (file)
@@ -42,12 +42,12 @@ String logLevelString()
     if (!length)
         return emptyString();
 
-    auto buffer = std::make_unique<char[]>(length);
+    Vector<char> buffer(length);
 
-    if (!GetEnvironmentVariableA(loggingEnvironmentVariable, buffer.get(), length))
+    if (!GetEnvironmentVariableA(loggingEnvironmentVariable, buffer.data(), length))
         return emptyString();
 
-    return String(buffer.get());
+    return String(buffer.data());
 }
 
 } // namespace WebKit
index e527f81..1f76808 100644 (file)
@@ -29,6 +29,7 @@
 #include <wtf/Noncopyable.h>
 #include <wtf/RefCounted.h>
 #include <wtf/RefPtr.h>
+#include <wtf/Vector.h>
 #include <wtf/text/WTFString.h>
 
 namespace IPC {
@@ -86,8 +87,7 @@ public:
        
     private:
 #if ENABLE(SANDBOX_EXTENSIONS)
-        std::unique_ptr<Handle[]> m_data;
-        size_t m_size { 0 };
+        Vector<Handle> m_data;
 #else
         Handle m_emptyHandle;
 #endif
index 9d8b9eb..b8e743d 100644 (file)
@@ -163,34 +163,33 @@ void SandboxExtension::HandleArray::allocate(size_t size)
     if (!size)
         return;
 
-    ASSERT(!m_data);
+    ASSERT(m_data.isEmpty());
 
-    m_data = std::make_unique<SandboxExtension::Handle[]>(size);
-    m_size = size;
+    m_data.resize(size);
 }
 
 SandboxExtension::Handle& SandboxExtension::HandleArray::operator[](size_t i)
 {
-    ASSERT_WITH_SECURITY_IMPLICATION(i < m_size); 
+    RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(i < m_data.size());
     return m_data[i];
 }
 
 const SandboxExtension::Handle& SandboxExtension::HandleArray::operator[](size_t i) const
 {
-    ASSERT_WITH_SECURITY_IMPLICATION(i < m_size);
+    RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(i < m_data.size());
     return m_data[i];
 }
 
 size_t SandboxExtension::HandleArray::size() const
 {
-    return m_size;
+    return m_data.size();
 }
 
 void SandboxExtension::HandleArray::encode(IPC::Encoder& encoder) const
 {
     encoder << static_cast<uint64_t>(size());
-    for (size_t i = 0; i < m_size; ++i)
-        encoder << m_data[i];
+    for (auto& handle : m_data)
+        encoder << handle;
 }
 
 bool SandboxExtension::HandleArray::decode(IPC::Decoder& decoder, SandboxExtension::HandleArray& handles)
index eddca4c..88516c0 100644 (file)
@@ -1,3 +1,22 @@
+2018-03-05  Yusuke Suzuki  <utatane.tea@gmail.com>
+
+        Fix std::make_unique / new[] using system malloc
+        https://bugs.webkit.org/show_bug.cgi?id=182975
+
+        Reviewed by JF Bastien.
+
+        Use Vector instead.
+
+        * MarshallingHelpers.cpp:
+        (MarshallingHelpers::safeArrayToStringArray):
+        (MarshallingHelpers::safeArrayToIntArray):
+        * Plugins/PluginPackageWin.cpp:
+        (WebCore::PluginPackage::fetchInfo):
+        * WebPreferences.cpp:
+        (WebPreferences::copyWebKitPreferencesToCFPreferences):
+        * WebView.cpp:
+        (WebView::onMenuCommand):
+
 2018-03-04  Yusuke Suzuki  <utatane.tea@gmail.com>
 
         [WTF] Move currentCPUTime and sleep(Seconds) to CPUTime.h and Seconds.h respectively
index fb8b735..6af3151 100644 (file)
@@ -210,18 +210,16 @@ CFArrayRef MarshallingHelpers::safeArrayToStringArray(SAFEARRAY* inArray)
     if (SUCCEEDED(hr))
         hr = ::SafeArrayGetUBound(inArray, 1, &uBound);
     long len = (SUCCEEDED(hr)) ? (uBound-lBound+1) : 0;
-    CFStringRef* items = 0;
+    Vector<CFStringRef> items;
     if (len > 0) {
-        items = new CFStringRef[len];
+        items.resize(len);
         for (; lBound <= uBound; lBound++) {
             BString str;
             hr = ::SafeArrayGetElement(inArray, &lBound, &str);
             items[lBound] = BSTRToCFStringRef(str);
         }
     }
-    CFArrayRef result = CFArrayCreate(0, (const void**)items, len, &kCFTypeArrayCallBacks);
-    if (items)
-        delete[] items;
+    CFArrayRef result = CFArrayCreate(0, (const void**)items.data(), len, &kCFTypeArrayCallBacks);
     return result;
 }
 
@@ -232,18 +230,16 @@ CFArrayRef MarshallingHelpers::safeArrayToIntArray(SAFEARRAY* inArray)
     if (SUCCEEDED(hr))
         hr = ::SafeArrayGetUBound(inArray, 1, &uBound);
     long len = (SUCCEEDED(hr)) ? (uBound-lBound+1) : 0;
-    CFNumberRef* items = 0;
+    Vector<CFNumberRef> items;
     if (len > 0) {
-        items = new CFNumberRef[len];
+        items.resize(len);
         for (; lBound <= uBound; lBound++) {
             int num = 0;
             hr = ::SafeArrayGetElement(inArray, &lBound, &num);
             items[lBound] = SUCCEEDED(hr) ? intToCFNumberRef(num) : kCFNumberNaN;
         }
     }
-    CFArrayRef result = CFArrayCreate(0, (const void**) items, len, &kCFTypeArrayCallBacks);
-    if (items)
-        delete[] items;
+    CFArrayRef result = CFArrayCreate(0, (const void**)items.data(), len, &kCFTypeArrayCallBacks);
     return result;
 }
 
index bae7276..152eb53 100644 (file)
@@ -170,19 +170,19 @@ bool PluginPackage::fetchInfo()
     if (versionInfoSize == 0)
         return false;
 
-    auto versionInfoData = std::make_unique<char[]>(versionInfoSize);
+    Vector<char> versionInfoData(versionInfoSize);
 
-    if (!GetFileVersionInfoW(stringToNullTerminatedWChar(m_path).data(), 0, versionInfoSize, versionInfoData.get()))
+    if (!GetFileVersionInfoW(stringToNullTerminatedWChar(m_path).data(), 0, versionInfoSize, versionInfoData.data()))
         return false;
 
-    m_name = getVersionInfo(versionInfoData.get(), "ProductName");
-    m_description = getVersionInfo(versionInfoData.get(), "FileDescription");
+    m_name = getVersionInfo(versionInfoData.data(), "ProductName");
+    m_description = getVersionInfo(versionInfoData.data(), "FileDescription");
     if (m_name.isNull() || m_description.isNull())
         return false;
 
     VS_FIXEDFILEINFO* info;
     UINT infoSize;
-    if (!VerQueryValueW(versionInfoData.get(), L"\\", (LPVOID*) &info, &infoSize) || infoSize < sizeof(VS_FIXEDFILEINFO))
+    if (!VerQueryValueW(versionInfoData.data(), L"\\", (LPVOID*) &info, &infoSize) || infoSize < sizeof(VS_FIXEDFILEINFO))
         return false;
     m_moduleVersion.leastSig = info->dwFileVersionLS;
     m_moduleVersion.mostSig = info->dwFileVersionMS;
@@ -191,11 +191,11 @@ bool PluginPackage::fetchInfo()
         return false;
 
     Vector<String> types;
-    getVersionInfo(versionInfoData.get(), "MIMEType").split('|', types);
+    getVersionInfo(versionInfoData.data(), "MIMEType").split('|', types);
     Vector<String> extensionLists;
-    getVersionInfo(versionInfoData.get(), "FileExtents").split('|', extensionLists);
+    getVersionInfo(versionInfoData.data(), "FileExtents").split('|', extensionLists);
     Vector<String> descriptions;
-    getVersionInfo(versionInfoData.get(), "FileOpenName").split('|', descriptions);
+    getVersionInfo(versionInfoData.data(), "FileOpenName").split('|', descriptions);
 
     for (unsigned i = 0; i < types.size(); i++) {
         String type = types[i].convertToASCIILowercase();
index cb047c5..37cc020 100644 (file)
@@ -534,9 +534,9 @@ void WebPreferences::copyWebKitPreferencesToCFPreferences(CFDictionaryRef dict)
     CFStringRef didRemoveDefaultsKey = CFSTR(WebKitDidMigrateDefaultSettingsFromSafari3BetaPreferenceKey);
     bool omitDefaults = !booleanValueForPreferencesValue(CFDictionaryGetValue(dict, didRemoveDefaultsKey));
 
-    auto keys = std::make_unique<CFTypeRef[]>(count);
-    auto values = std::make_unique<CFTypeRef[]>(count);
-    CFDictionaryGetKeysAndValues(dict, keys.get(), values.get());
+    Vector<CFTypeRef> keys(count);
+    Vector<CFTypeRef> values(count);
+    CFDictionaryGetKeysAndValues(dict, keys.data(), values.data());
 
     for (int i = 0; i < count; ++i) {
         if (!keys[i] || !values[i] || CFGetTypeID(keys[i]) != CFStringGetTypeID())
index c799039..2d957ea 100644 (file)
@@ -1784,8 +1784,8 @@ void WebView::onMenuCommand(WPARAM wParam, LPARAM lParam)
     menuItemInfo.fMask = MIIM_STRING;
     ::GetMenuItemInfo(hMenu, index, true, &menuItemInfo);
 
-    auto buffer = std::make_unique<WCHAR[]>(menuItemInfo.cch + 1);
-    menuItemInfo.dwTypeData = buffer.get();
+    Vector<WCHAR> buffer(menuItemInfo.cch + 1);
+    menuItemInfo.dwTypeData = buffer.data();
     menuItemInfo.cch++;
     menuItemInfo.fMask |= MIIM_ID;
 
@@ -1794,7 +1794,7 @@ void WebView::onMenuCommand(WPARAM wParam, LPARAM lParam)
     ::DestroyMenu(m_currentContextMenu);
     m_currentContextMenu = nullptr;
 
-    String title(buffer.get(), menuItemInfo.cch);
+    String title(buffer.data(), menuItemInfo.cch);
     ContextMenuAction action = static_cast<ContextMenuAction>(menuItemInfo.wID);
 
     if (action >= ContextMenuItemBaseApplicationTag) {
index 3244280..7425feb 100644 (file)
@@ -1,3 +1,18 @@
+2018-03-05  Yusuke Suzuki  <utatane.tea@gmail.com>
+
+        Fix std::make_unique / new[] using system malloc
+        https://bugs.webkit.org/show_bug.cgi?id=182975
+
+        Reviewed by JF Bastien.
+
+        * TestWebKitAPI/CMakeLists.txt:
+        * TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj:
+        * TestWebKitAPI/Tests/WTF/UniqueArray.cpp: Copied from Source/WebKit/Platform/win/LoggingWin.cpp.
+        (TestWebKitAPI::NonTrivialDestructor::NonTrivialDestructor):
+        (TestWebKitAPI::NonTrivialDestructor::~NonTrivialDestructor):
+        (TestWebKitAPI::NonTrivialDestructor::setLog):
+        (TestWebKitAPI::TEST):
+
 2018-03-05  Myles C. Maxfield  <mmaxfield@apple.com>
 
         DumpRenderTree build fix
index df49c21..eb78e9a 100644 (file)
@@ -151,6 +151,7 @@ set(TestWTF_SOURCES
     ${TESTWEBKITAPI_DIR}/Tests/WTF/ThreadMessages.cpp
     ${TESTWEBKITAPI_DIR}/Tests/WTF/Threading.cpp
     ${TESTWEBKITAPI_DIR}/Tests/WTF/Time.cpp
+    ${TESTWEBKITAPI_DIR}/Tests/WTF/UniqueArray.cpp
     ${TESTWEBKITAPI_DIR}/Tests/WTF/UniqueRef.cpp
     ${TESTWEBKITAPI_DIR}/Tests/WTF/Variant.cpp
     ${TESTWEBKITAPI_DIR}/Tests/WTF/Vector.cpp
index 95433d8..f4e7f5f 100644 (file)
                D34E08761E4E42E1005FF14A /* WKWebViewGetContents.mm in Sources */ = {isa = PBXBuildFile; fileRef = D3BE5E341E4CE85E00FD563A /* WKWebViewGetContents.mm */; };
                E1220DCA155B28AA0013E2FC /* MemoryCacheDisableWithinResourceLoadDelegate.html in Copy Resources */ = {isa = PBXBuildFile; fileRef = E1220DC9155B287D0013E2FC /* MemoryCacheDisableWithinResourceLoadDelegate.html */; };
                E194E1BD177E53C7009C4D4E /* StopLoadingFromDidReceiveResponse.html in Copy Resources */ = {isa = PBXBuildFile; fileRef = E194E1BC177E534A009C4D4E /* StopLoadingFromDidReceiveResponse.html */; };
+               E324A6F02041C82000A76593 /* UniqueArray.cpp in Sources */ = {isa = PBXBuildFile; fileRef = E398BC0F2041C76300387136 /* UniqueArray.cpp */; };
                E373D7911F2CF35200C6FAAF /* Signals.cpp in Sources */ = {isa = PBXBuildFile; fileRef = E3953F951F2CF32100A76A2E /* Signals.cpp */; };
                E38A0D351FD50CC300E98C8B /* Threading.cpp in Sources */ = {isa = PBXBuildFile; fileRef = E38A0D341FD50CBC00E98C8B /* Threading.cpp */; };
                E3DEA8111F0A589000CBC2E8 /* ThreadGroup.cpp in Sources */ = {isa = PBXBuildFile; fileRef = E3DEA8101F0A588000CBC2E8 /* ThreadGroup.cpp */; };
                E19DB9781B32137C00DB38D4 /* NavigatorLanguage.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = NavigatorLanguage.mm; sourceTree = "<group>"; };
                E38A0D341FD50CBC00E98C8B /* Threading.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Threading.cpp; sourceTree = "<group>"; };
                E3953F951F2CF32100A76A2E /* Signals.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Signals.cpp; sourceTree = "<group>"; };
+               E398BC0F2041C76300387136 /* UniqueArray.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = UniqueArray.cpp; sourceTree = "<group>"; };
                E3DEA8101F0A588000CBC2E8 /* ThreadGroup.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ThreadGroup.cpp; sourceTree = "<group>"; };
                E40019301ACE9B5C001B0A2A /* BloomFilter.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = BloomFilter.cpp; sourceTree = "<group>"; };
                E490296714E2E3A4002BEDD1 /* TypingStyleCrash.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = TypingStyleCrash.mm; sourceTree = "<group>"; };
                                E38A0D341FD50CBC00E98C8B /* Threading.cpp */,
                                5311BD5D1EA9490D00525281 /* ThreadMessages.cpp */,
                                0F2C20B71DCD544800542D9E /* Time.cpp */,
+                               E398BC0F2041C76300387136 /* UniqueArray.cpp */,
                                5C5E633D1D0B67940085A025 /* UniqueRef.cpp */,
                                7CD0D5AA1D5534DE000CC9E1 /* Variant.cpp */,
                                BC55F5F814AD78EE00484BE1 /* Vector.cpp */,
                                E38A0D351FD50CC300E98C8B /* Threading.cpp in Sources */,
                                5311BD5E1EA9490E00525281 /* ThreadMessages.cpp in Sources */,
                                0F2C20B81DCD545000542D9E /* Time.cpp in Sources */,
+                               E324A6F02041C82000A76593 /* UniqueArray.cpp in Sources */,
                                7C83E03B1D0A602700FEBCF3 /* UtilitiesCocoa.mm in Sources */,
                                7C83FC711D5535A8001DFBCD /* Variant.cpp in Sources */,
                                7C83DF4C1D0A590C00FEBCF3 /* Vector.cpp in Sources */,
diff --git a/Tools/TestWebKitAPI/Tests/WTF/UniqueArray.cpp b/Tools/TestWebKitAPI/Tests/WTF/UniqueArray.cpp
new file mode 100644 (file)
index 0000000..c1d0836
--- /dev/null
@@ -0,0 +1,84 @@
+/*
+ * Copyright (C) 2018 Yusuke Suzuki <utatane.tea@gmail.com>.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
+ * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
+ * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+ * THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include <wtf/UniqueArray.h>
+
+using namespace WTF;
+
+namespace TestWebKitAPI {
+
+static unsigned numberOfConstructions { 0 };
+class NonTrivialDestructor {
+public:
+    NonTrivialDestructor()
+    {
+        numberOfConstructions++;
+    }
+
+    ~NonTrivialDestructor()
+    {
+        (*m_log)++;
+    }
+
+    void setLog(unsigned* log)
+    {
+        m_log = log;
+    }
+
+private:
+    unsigned* m_log { nullptr };
+};
+
+TEST(WTF_UniqueArray, NonTrivialDestructor)
+{
+    unsigned size = 42;
+    unsigned log = 0;
+    {
+        EXPECT_EQ(0U, log);
+        auto array = makeUniqueArray<NonTrivialDestructor>(size);
+        EXPECT_EQ(0U, log);
+        EXPECT_EQ(size, numberOfConstructions);
+        for (unsigned i = 0; i < size; ++i)
+            array[i].setLog(&log);
+    }
+    EXPECT_EQ(log, size);
+}
+
+TEST(WTF_UniqueArray, TrivialDestructor)
+{
+    unsigned size = 42;
+    {
+        auto array = makeUniqueArray<unsigned>(size);
+        for (unsigned i = 0; i < size; ++i) {
+            EXPECT_EQ(0U, array[i]) << i;
+            array[i] = 42;
+        }
+        for (unsigned i = 0; i < size; ++i)
+            EXPECT_EQ(42U, array[i]);
+    }
+}
+
+} // namespace TestWebKitAPI