<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[259760] trunk/Source/WebKit</title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<dl class="meta">
<dt>Revision</dt> <dd><a href="http://trac.webkit.org/projects/webkit/changeset/259760">259760</a></dd>
<dt>Author</dt> <dd>beidson@apple.com</dd>
<dt>Date</dt> <dd>2020-04-08 15:15:16 -0700 (Wed, 08 Apr 2020)</dd>
</dl>

<h3>Log Message</h3>
<pre>Fix handling non-linearized PDFs when incremental PDF loading is enabled.
<rdar://problem/60619506> and https://bugs.webkit.org/show_bug.cgi?id=210208

Reviewed by Tim Horton (and I think Geoff Garen, probably. It's confusing.)

When we try to load a non-linearized PDF with PDFKit, it makes an outlandishly large range request
to try to verify the PDF file size.

That's covered by <rdar://problem/61473378>

Meanwhile we need to detect that and fallback to non-incremental PDF loading.

* WebProcess/Plugins/PDF/PDFPlugin.h:
* WebProcess/Plugins/PDF/PDFPlugin.mm:
(WebKit::PDFPlugin::receivedInvalidRangeRequest):
(WebKit::dataProviderGetBytesAtPositionCallback):
(WebKit::PDFPlugin::threadEntry):
(WebKit::PDFPlugin::installPDFDocument):</pre>

<h3>Modified Paths</h3>
<ul>
<li><a href="#trunkSourceWebKitChangeLog">trunk/Source/WebKit/ChangeLog</a></li>
<li><a href="#trunkSourceWebKitWebProcessPluginsPDFPDFPluginh">trunk/Source/WebKit/WebProcess/Plugins/PDF/PDFPlugin.h</a></li>
<li><a href="#trunkSourceWebKitWebProcessPluginsPDFPDFPluginmm">trunk/Source/WebKit/WebProcess/Plugins/PDF/PDFPlugin.mm</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="trunkSourceWebKitChangeLog"></a>
<div class="modfile"><h4>Modified: trunk/Source/WebKit/ChangeLog (259759 => 259760)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/Source/WebKit/ChangeLog    2020-04-08 22:06:15 UTC (rev 259759)
+++ trunk/Source/WebKit/ChangeLog       2020-04-08 22:15:16 UTC (rev 259760)
</span><span class="lines">@@ -1,3 +1,24 @@
</span><ins>+2020-04-08  Brady Eidson  <beidson@apple.com>
+
+        Fix handling non-linearized PDFs when incremental PDF loading is enabled.
+        <rdar://problem/60619506> and https://bugs.webkit.org/show_bug.cgi?id=210208
+
+        Reviewed by Tim Horton (and I think Geoff Garen, probably. It's confusing.)
+
+        When we try to load a non-linearized PDF with PDFKit, it makes an outlandishly large range request
+        to try to verify the PDF file size.
+        
+        That's covered by <rdar://problem/61473378>
+        
+        Meanwhile we need to detect that and fallback to non-incremental PDF loading.
+
+        * WebProcess/Plugins/PDF/PDFPlugin.h:
+        * WebProcess/Plugins/PDF/PDFPlugin.mm:
+        (WebKit::PDFPlugin::receivedInvalidRangeRequest):
+        (WebKit::dataProviderGetBytesAtPositionCallback):
+        (WebKit::PDFPlugin::threadEntry):
+        (WebKit::PDFPlugin::installPDFDocument):
+
</ins><span class="cx"> 2020-04-08  Per Arne Vollan  <pvollan@apple.com>
</span><span class="cx"> 
</span><span class="cx">         Allow use of syscall from the WebContent sandbox
</span></span></pre></div>
<a id="trunkSourceWebKitWebProcessPluginsPDFPDFPluginh"></a>
<div class="modfile"><h4>Modified: trunk/Source/WebKit/WebProcess/Plugins/PDF/PDFPlugin.h (259759 => 259760)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/Source/WebKit/WebProcess/Plugins/PDF/PDFPlugin.h   2020-04-08 22:06:15 UTC (rev 259759)
+++ trunk/Source/WebKit/WebProcess/Plugins/PDF/PDFPlugin.h      2020-04-08 22:15:16 UTC (rev 259760)
</span><span class="lines">@@ -135,6 +135,8 @@
</span><span class="cx"> #if HAVE(INCREMENTAL_PDF_APIS)
</span><span class="cx">     void getResourceBytesAtPosition(size_t count, off_t position, CompletionHandler<void(const uint8_t*, size_t count)>&&);
</span><span class="cx">     size_t getResourceBytesAtPositionMainThread(void* buffer, off_t position, size_t count);
</span><ins>+    void receivedNonLinearizedPDFSentinel();
+    bool incrementalPDFLoadingEnabled() const { return m_incrementalPDFLoadingEnabled; }
</ins><span class="cx"> #ifndef NDEBUG
</span><span class="cx">     void pdfLog(const String& event);
</span><span class="cx">     size_t incrementThreadsWaitingOnCallback() { return ++m_threadsWaitingOnCallback; }
</span></span></pre></div>
<a id="trunkSourceWebKitWebProcessPluginsPDFPDFPluginmm"></a>
<div class="modfile"><h4>Modified: trunk/Source/WebKit/WebProcess/Plugins/PDF/PDFPlugin.mm (259759 => 259760)</h4>
<pre class="diff"><span>
<span class="info">--- trunk/Source/WebKit/WebProcess/Plugins/PDF/PDFPlugin.mm  2020-04-08 22:06:15 UTC (rev 259759)
+++ trunk/Source/WebKit/WebProcess/Plugins/PDF/PDFPlugin.mm     2020-04-08 22:15:16 UTC (rev 259760)
</span><span class="lines">@@ -90,6 +90,7 @@
</span><span class="cx"> #import <pal/spi/cg/CoreGraphicsSPI.h>
</span><span class="cx"> #import <pal/spi/mac/NSMenuSPI.h>
</span><span class="cx"> #import <wtf/HexNumber.h>
</span><ins>+#import <wtf/Scope.h>
</ins><span class="cx"> #import <wtf/UUID.h>
</span><span class="cx"> #import <wtf/WTFSemaphore.h>
</span><span class="cx"> #import <wtf/WorkQueue.h>
</span><span class="lines">@@ -136,6 +137,11 @@
</span><span class="cx"> // will jump to the next or previous page, to match PDFKit behavior.
</span><span class="cx"> static const int defaultScrollMagnitudeThresholdForPageFlip = 20;
</span><span class="cx"> 
</span><ins>+// <rdar://problem/61473378> - PDFKit asks for a "way too large" range when the PDF it is loading
+// incrementally turns out to be non-linearized.
+// We'll assume any size over 4gb is PDFKit noticing non-linearized data.
+static const uint32_t nonLinearizedPDFSentinel = std::numeric_limits<uint32_t>::max();
+
</ins><span class="cx"> @interface WKPDFPluginAccessibilityObject : NSObject {
</span><span class="cx">     PDFLayerController *_pdfLayerController;
</span><span class="cx">     __unsafe_unretained NSObject *_parent;
</span><span class="lines">@@ -693,22 +699,68 @@
</span><span class="cx"> }
</span><span class="cx"> #endif // !LOG_DISABLED
</span><span class="cx"> 
</span><ins>+void PDFPlugin::receivedNonLinearizedPDFSentinel()
+{
+    m_incrementalPDFLoadingEnabled = false;
+
+    if (!isMainThread()) {
+#if !LOG_DISABLED
+        pdfLog("Disabling incremental PDF loading on background thread");
+#endif
+        callOnMainThread([this, protectedThis = makeRef(*this)] {
+            receivedNonLinearizedPDFSentinel();
+        });
+        return;
+    }
+
+#if !LOG_DISABLED
+    pdfLog(makeString("Cancelling all ", m_streamLoaderMap.size(), " range request loaders"));
+#endif
+
+    for (auto iterator = m_streamLoaderMap.begin(); iterator != m_streamLoaderMap.end(); iterator = m_streamLoaderMap.begin()) {
+        m_outstandingByteRangeRequests.remove(iterator->value);
+        cancelAndForgetLoader(*iterator->key);
+    }
+
+    if (!m_documentFinishedLoading || m_pdfDocument)
+        return;
+
+    m_pdfDocument = adoptNS([[pdfDocumentClass() alloc] initWithData:rawData()]);
+    installPDFDocument();
+    tryRunScriptsInPDFDocument();
+}
+
</ins><span class="cx"> static size_t dataProviderGetBytesAtPositionCallback(void* info, void* buffer, off_t position, size_t count)
</span><span class="cx"> {
</span><ins>+    Ref<PDFPlugin> plugin = *((PDFPlugin*)info);
+
</ins><span class="cx">     if (isMainThread()) {
</span><span class="cx"> #if !LOG_DISABLED
</span><del>-        ((PDFPlugin*)info)->pdfLog(makeString("Handling request for ", count, " bytes at position ", position, " synchronously on the main thread"));
</del><ins>+        plugin->pdfLog(makeString("Handling request for ", count, " bytes at position ", position, " synchronously on the main thread"));
</ins><span class="cx"> #endif
</span><del>-        return ((PDFPlugin*)info)->getResourceBytesAtPositionMainThread(buffer, position, count);
</del><ins>+        return plugin->getResourceBytesAtPositionMainThread(buffer, position, count);
</ins><span class="cx">     }
</span><span class="cx"> 
</span><ins>+    // It's possible we previously encountered an invalid range and therefore disabled incremental loading,
+    // but PDFDocument is still trying to read data using a different strategy.
+    // Always ignore such requests.
+    if (!plugin->incrementalPDFLoadingEnabled())
+        return 0;
+
</ins><span class="cx"> #if !LOG_DISABLED
</span><del>-    Ref<PDFPlugin> debugPluginRef = *((PDFPlugin*)info);
</del><ins>+    auto debugPluginRef = plugin.copyRef();
</ins><span class="cx">     debugPluginRef->incrementThreadsWaitingOnCallback();
</span><span class="cx">     debugPluginRef->pdfLog(makeString("PDF data provider requesting ", count, " bytes at position ", position));
</span><span class="cx"> #endif
</span><span class="cx"> 
</span><del>-    Ref<PDFPlugin> plugin = *((PDFPlugin*)info);
</del><ins>+    if (position > nonLinearizedPDFSentinel) {
+#if !LOG_DISABLED
+        plugin->pdfLog(makeString("Received invalid range request for ", count, " bytes at position ", position, ". PDF is probably not linearized. Falling back to non-incremental loading."));
+#endif
+        plugin->receivedNonLinearizedPDFSentinel();
+        return 0;
+    }
+
</ins><span class="cx">     WTF::Semaphore dataSemaphore { 0 };
</span><span class="cx">     size_t bytesProvided = 0;
</span><span class="cx"> 
</span><span class="lines">@@ -802,6 +854,12 @@
</span><span class="cx">         dataProviderReleaseInfoCallback,
</span><span class="cx">     };
</span><span class="cx"> 
</span><ins>+    auto scopeExit = makeScopeExit([protectedPlugin = WTFMove(protectedPlugin)] () mutable {
+        // Keep the PDFPlugin alive until the end of this function and the end
+        // of the last main thread task submitted by this function.
+        callOnMainThread([protectedPlugin = WTFMove(protectedPlugin)] { });
+    });
+
</ins><span class="cx">     // Balanced by a deref inside of the dataProviderReleaseInfoCallback
</span><span class="cx">     ref();
</span><span class="cx"> 
</span><span class="lines">@@ -809,13 +867,22 @@
</span><span class="cx">     CGDataProviderSetProperty(dataProvider.get(), kCGDataProviderHasHighLatency, kCFBooleanTrue);
</span><span class="cx">     m_backgroundThreadDocument = adoptNS([[pdfDocumentClass() alloc] initWithProvider:dataProvider.get()]);
</span><span class="cx"> 
</span><ins>+    if (!m_incrementalPDFLoadingEnabled) {
+        m_backgroundThreadDocument = nil;
+        return;
+    }
+
</ins><span class="cx">     WTF::Semaphore firstPageSemaphore { 0 };
</span><span class="cx">     auto firstPageQueue = WorkQueue::create("PDF first page work queue");
</span><span class="cx"> 
</span><span class="cx">     [m_backgroundThreadDocument preloadDataOfPagesInRange:NSMakeRange(0, 1) onQueue:firstPageQueue->dispatchQueue() completion:[&firstPageSemaphore, this] (NSIndexSet *) mutable {
</span><del>-        callOnMainThread([this] {
-            adoptBackgroundThreadDocument();
-        });
</del><ins>+        if (m_incrementalPDFLoadingEnabled) {
+            callOnMainThread([this] {
+                adoptBackgroundThreadDocument();
+            });
+        } else
+            m_backgroundThreadDocument = nil;
+
</ins><span class="cx">         firstPageSemaphore.signal();
</span><span class="cx">     }];
</span><span class="cx"> 
</span><span class="lines">@@ -824,10 +891,6 @@
</span><span class="cx"> #if !LOG_DISABLED
</span><span class="cx">     pdfLog("Finished preloading first page");
</span><span class="cx"> #endif
</span><del>-
-    // The main thread dispatch below removes the last reference to the PDF thread.
-    // It must be the last code executed in this function.
-    callOnMainThread([protectedPlugin = WTFMove(protectedPlugin)] { });
</del><span class="cx"> }
</span><span class="cx"> 
</span><span class="cx"> void PDFPlugin::unconditionalCompleteOutstandingRangeRequests()
</span><span class="lines">@@ -1469,6 +1532,7 @@
</span><span class="cx"> {
</span><span class="cx">     ASSERT(m_pdfDocument);
</span><span class="cx">     ASSERT(isMainThread());
</span><ins>+    LOG(IncrementalPDF, "Installing PDF document");
</ins><span class="cx"> 
</span><span class="cx"> #if HAVE(INCREMENTAL_PDF_APIS)
</span><span class="cx">     maybeClearHighLatencyDataProviderFlag();
</span></span></pre>
</div>
</div>

</body>
</html>