• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2015 PDFium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "testing/embedder_test.h"
6 
7 #include <limits.h>
8 
9 #include <list>
10 #include <map>
11 #include <memory>
12 #include <string>
13 #include <utility>
14 #include <vector>
15 
16 #include "core/fdrm/fx_crypt.h"
17 #include "public/cpp/fpdf_scopers.h"
18 #include "public/fpdf_dataavail.h"
19 #include "public/fpdf_edit.h"
20 #include "public/fpdf_text.h"
21 #include "public/fpdfview.h"
22 #include "testing/gmock/include/gmock/gmock.h"
23 #include "testing/test_loader.h"
24 #include "testing/utils/bitmap_saver.h"
25 #include "testing/utils/file_util.h"
26 #include "testing/utils/hash.h"
27 #include "testing/utils/path_service.h"
28 #include "third_party/base/logging.h"
29 #include "third_party/base/ptr_util.h"
30 #include "third_party/base/stl_util.h"
31 
32 #ifdef PDF_ENABLE_V8
33 #include "v8/include/v8-platform.h"
34 #include "v8/include/v8.h"
35 #endif  // PDF_ENABLE_V8
36 
37 namespace {
38 
GetBitmapBytesPerPixel(FPDF_BITMAP bitmap)39 int GetBitmapBytesPerPixel(FPDF_BITMAP bitmap) {
40   return EmbedderTest::BytesPerPixelForFormat(FPDFBitmap_GetFormat(bitmap));
41 }
42 
43 #if defined(OS_WIN)
GetRecordProc(HDC hdc,HANDLETABLE * handle_table,const ENHMETARECORD * record,int objects_count,LPARAM param)44 int CALLBACK GetRecordProc(HDC hdc,
45                            HANDLETABLE* handle_table,
46                            const ENHMETARECORD* record,
47                            int objects_count,
48                            LPARAM param) {
49   auto& records = *reinterpret_cast<std::vector<const ENHMETARECORD*>*>(param);
50   records.push_back(record);
51   return 1;
52 }
53 #endif  // defined(OS_WIN)
54 
55 }  // namespace
56 
EmbedderTest()57 EmbedderTest::EmbedderTest()
58     : default_delegate_(pdfium::MakeUnique<EmbedderTest::Delegate>()),
59       delegate_(default_delegate_.get()) {
60   FPDF_FILEWRITE::version = 1;
61   FPDF_FILEWRITE::WriteBlock = WriteBlockCallback;
62 }
63 
64 EmbedderTest::~EmbedderTest() = default;
65 
SetUp()66 void EmbedderTest::SetUp() {
67   FPDF_LIBRARY_CONFIG config;
68   config.version = 2;
69   config.m_pUserFontPaths = nullptr;
70   config.m_v8EmbedderSlot = 0;
71   config.m_pIsolate = external_isolate_;
72   FPDF_InitLibraryWithConfig(&config);
73 
74   UNSUPPORT_INFO* info = static_cast<UNSUPPORT_INFO*>(this);
75   memset(info, 0, sizeof(UNSUPPORT_INFO));
76   info->version = 1;
77   info->FSDK_UnSupport_Handler = UnsupportedHandlerTrampoline;
78   FSDK_SetUnSpObjProcessHandler(info);
79 
80   saved_document_ = nullptr;
81 }
82 
TearDown()83 void EmbedderTest::TearDown() {
84   // Use an EXPECT_EQ() here and continue to let TearDown() finish as cleanly as
85   // possible. This can fail when an ASSERT test fails in a test case.
86   EXPECT_EQ(0U, page_map_.size());
87   EXPECT_EQ(0U, saved_page_map_.size());
88 
89   if (document_) {
90     FORM_DoDocumentAAction(form_handle_, FPDFDOC_AACTION_WC);
91     CloseDocument();
92   }
93 
94   FPDFAvail_Destroy(avail_);
95   FPDF_DestroyLibrary();
96   loader_.reset();
97 }
98 
99 #ifdef PDF_ENABLE_V8
SetExternalIsolate(void * isolate)100 void EmbedderTest::SetExternalIsolate(void* isolate) {
101   external_isolate_ = static_cast<v8::Isolate*>(isolate);
102 }
103 #endif  // PDF_ENABLE_V8
104 
CreateEmptyDocument()105 bool EmbedderTest::CreateEmptyDocument() {
106   document_ = FPDF_CreateNewDocument();
107   if (!document_)
108     return false;
109 
110   form_handle_ =
111       SetupFormFillEnvironment(document_, JavaScriptOption::kEnableJavaScript);
112   return true;
113 }
114 
OpenDocument(const std::string & filename)115 bool EmbedderTest::OpenDocument(const std::string& filename) {
116   return OpenDocumentWithOptions(filename, nullptr,
117                                  LinearizeOption::kDefaultLinearize,
118                                  JavaScriptOption::kEnableJavaScript);
119 }
120 
OpenDocumentLinearized(const std::string & filename)121 bool EmbedderTest::OpenDocumentLinearized(const std::string& filename) {
122   return OpenDocumentWithOptions(filename, nullptr,
123                                  LinearizeOption::kMustLinearize,
124                                  JavaScriptOption::kEnableJavaScript);
125 }
126 
OpenDocumentWithPassword(const std::string & filename,const char * password)127 bool EmbedderTest::OpenDocumentWithPassword(const std::string& filename,
128                                             const char* password) {
129   return OpenDocumentWithOptions(filename, password,
130                                  LinearizeOption::kDefaultLinearize,
131                                  JavaScriptOption::kEnableJavaScript);
132 }
133 
OpenDocumentWithoutJavaScript(const std::string & filename)134 bool EmbedderTest::OpenDocumentWithoutJavaScript(const std::string& filename) {
135   return OpenDocumentWithOptions(filename, nullptr,
136                                  LinearizeOption::kDefaultLinearize,
137                                  JavaScriptOption::kDisableJavaScript);
138 }
139 
OpenDocumentWithOptions(const std::string & filename,const char * password,LinearizeOption linearize_option,JavaScriptOption javascript_option)140 bool EmbedderTest::OpenDocumentWithOptions(const std::string& filename,
141                                            const char* password,
142                                            LinearizeOption linearize_option,
143                                            JavaScriptOption javascript_option) {
144   std::string file_path;
145   if (!PathService::GetTestFilePath(filename, &file_path))
146     return false;
147 
148   file_contents_ = GetFileContents(file_path.c_str(), &file_length_);
149   if (!file_contents_)
150     return false;
151 
152   EXPECT_TRUE(!loader_);
153   loader_ = pdfium::MakeUnique<TestLoader>(
154       pdfium::make_span(file_contents_.get(), file_length_));
155 
156   memset(&file_access_, 0, sizeof(file_access_));
157   file_access_.m_FileLen = static_cast<unsigned long>(file_length_);
158   file_access_.m_GetBlock = TestLoader::GetBlock;
159   file_access_.m_Param = loader_.get();
160 
161   fake_file_access_ = pdfium::MakeUnique<FakeFileAccess>(&file_access_);
162   return OpenDocumentHelper(password, linearize_option, javascript_option,
163                             fake_file_access_.get(), &document_, &avail_,
164                             &form_handle_);
165 }
166 
OpenDocumentHelper(const char * password,LinearizeOption linearize_option,JavaScriptOption javascript_option,FakeFileAccess * network_simulator,FPDF_DOCUMENT * document,FPDF_AVAIL * avail,FPDF_FORMHANDLE * form_handle)167 bool EmbedderTest::OpenDocumentHelper(const char* password,
168                                       LinearizeOption linearize_option,
169                                       JavaScriptOption javascript_option,
170                                       FakeFileAccess* network_simulator,
171                                       FPDF_DOCUMENT* document,
172                                       FPDF_AVAIL* avail,
173                                       FPDF_FORMHANDLE* form_handle) {
174   network_simulator->AddSegment(0, 1024);
175   network_simulator->SetRequestedDataAvailable();
176   *avail = FPDFAvail_Create(network_simulator->GetFileAvail(),
177                             network_simulator->GetFileAccess());
178   if (FPDFAvail_IsLinearized(*avail) == PDF_LINEARIZED) {
179     int32_t nRet = PDF_DATA_NOTAVAIL;
180     while (nRet == PDF_DATA_NOTAVAIL) {
181       network_simulator->SetRequestedDataAvailable();
182       nRet =
183           FPDFAvail_IsDocAvail(*avail, network_simulator->GetDownloadHints());
184     }
185     if (nRet == PDF_DATA_ERROR)
186       return false;
187 
188     *document = FPDFAvail_GetDocument(*avail, password);
189     if (!*document)
190       return false;
191 
192     nRet = PDF_DATA_NOTAVAIL;
193     while (nRet == PDF_DATA_NOTAVAIL) {
194       network_simulator->SetRequestedDataAvailable();
195       nRet =
196           FPDFAvail_IsFormAvail(*avail, network_simulator->GetDownloadHints());
197     }
198     if (nRet == PDF_FORM_ERROR)
199       return false;
200 
201     int page_count = FPDF_GetPageCount(*document);
202     for (int i = 0; i < page_count; ++i) {
203       nRet = PDF_DATA_NOTAVAIL;
204       while (nRet == PDF_DATA_NOTAVAIL) {
205         network_simulator->SetRequestedDataAvailable();
206         nRet = FPDFAvail_IsPageAvail(*avail, i,
207                                      network_simulator->GetDownloadHints());
208       }
209       if (nRet == PDF_DATA_ERROR)
210         return false;
211     }
212   } else {
213     if (linearize_option == LinearizeOption::kMustLinearize)
214       return false;
215     network_simulator->SetWholeFileAvailable();
216     *document =
217         FPDF_LoadCustomDocument(network_simulator->GetFileAccess(), password);
218     if (!*document)
219       return false;
220   }
221   *form_handle = SetupFormFillEnvironment(*document, javascript_option);
222 
223   int doc_type = FPDF_GetFormType(*document);
224   if (doc_type == FORMTYPE_XFA_FULL || doc_type == FORMTYPE_XFA_FOREGROUND)
225     FPDF_LoadXFA(*document);
226 
227   (void)FPDF_GetDocPermissions(*document);
228   return true;
229 }
230 
CloseDocument()231 void EmbedderTest::CloseDocument() {
232   FPDFDOC_ExitFormFillEnvironment(form_handle_);
233   form_handle_ = nullptr;
234 
235   FPDF_CloseDocument(document_);
236   document_ = nullptr;
237 }
238 
SetupFormFillEnvironment(FPDF_DOCUMENT doc,JavaScriptOption javascript_option)239 FPDF_FORMHANDLE EmbedderTest::SetupFormFillEnvironment(
240     FPDF_DOCUMENT doc,
241     JavaScriptOption javascript_option) {
242   IPDF_JSPLATFORM* platform = static_cast<IPDF_JSPLATFORM*>(this);
243   memset(platform, '\0', sizeof(IPDF_JSPLATFORM));
244   platform->version = 2;
245   platform->app_alert = AlertTrampoline;
246   platform->m_isolate = external_isolate_;
247 
248   FPDF_FORMFILLINFO* formfillinfo = static_cast<FPDF_FORMFILLINFO*>(this);
249   memset(formfillinfo, 0, sizeof(FPDF_FORMFILLINFO));
250 #ifdef PDF_ENABLE_XFA
251   formfillinfo->version = 2;
252 #else   // PDF_ENABLE_XFA
253   formfillinfo->version = 1;
254 #endif  // PDF_ENABLE_XFA
255   formfillinfo->FFI_SetTimer = SetTimerTrampoline;
256   formfillinfo->FFI_KillTimer = KillTimerTrampoline;
257   formfillinfo->FFI_GetPage = GetPageTrampoline;
258   formfillinfo->FFI_DoURIAction = DoURIActionTrampoline;
259 
260   if (javascript_option == JavaScriptOption::kEnableJavaScript)
261     formfillinfo->m_pJsPlatform = platform;
262 
263   FPDF_FORMHANDLE form_handle =
264       FPDFDOC_InitFormFillEnvironment(doc, formfillinfo);
265   SetInitialFormFieldHighlight(form_handle);
266   return form_handle;
267 }
268 
DoOpenActions()269 void EmbedderTest::DoOpenActions() {
270   ASSERT(form_handle_);
271   FORM_DoDocumentJSAction(form_handle_);
272   FORM_DoDocumentOpenAction(form_handle_);
273 }
274 
GetFirstPageNum()275 int EmbedderTest::GetFirstPageNum() {
276   int first_page = FPDFAvail_GetFirstPageNum(document_);
277   (void)FPDFAvail_IsPageAvail(avail_, first_page,
278                               fake_file_access_->GetDownloadHints());
279   return first_page;
280 }
281 
GetPageCount()282 int EmbedderTest::GetPageCount() {
283   int page_count = FPDF_GetPageCount(document_);
284   for (int i = 0; i < page_count; ++i)
285     (void)FPDFAvail_IsPageAvail(avail_, i,
286                                 fake_file_access_->GetDownloadHints());
287   return page_count;
288 }
289 
LoadPage(int page_number)290 FPDF_PAGE EmbedderTest::LoadPage(int page_number) {
291   return LoadPageCommon(page_number, true);
292 }
293 
LoadPageNoEvents(int page_number)294 FPDF_PAGE EmbedderTest::LoadPageNoEvents(int page_number) {
295   return LoadPageCommon(page_number, false);
296 }
297 
LoadPageCommon(int page_number,bool do_events)298 FPDF_PAGE EmbedderTest::LoadPageCommon(int page_number, bool do_events) {
299   ASSERT(form_handle_);
300   ASSERT(page_number >= 0);
301   ASSERT(!pdfium::ContainsKey(page_map_, page_number));
302 
303   FPDF_PAGE page = FPDF_LoadPage(document_, page_number);
304   if (!page)
305     return nullptr;
306 
307   if (do_events) {
308     FORM_OnAfterLoadPage(page, form_handle_);
309     FORM_DoPageAAction(page, form_handle_, FPDFPAGE_AACTION_OPEN);
310   }
311   page_map_[page_number] = page;
312   return page;
313 }
314 
UnloadPage(FPDF_PAGE page)315 void EmbedderTest::UnloadPage(FPDF_PAGE page) {
316   UnloadPageCommon(page, true);
317 }
318 
UnloadPageNoEvents(FPDF_PAGE page)319 void EmbedderTest::UnloadPageNoEvents(FPDF_PAGE page) {
320   UnloadPageCommon(page, false);
321 }
322 
UnloadPageCommon(FPDF_PAGE page,bool do_events)323 void EmbedderTest::UnloadPageCommon(FPDF_PAGE page, bool do_events) {
324   ASSERT(form_handle_);
325   int page_number = GetPageNumberForLoadedPage(page);
326   if (page_number < 0) {
327     NOTREACHED();
328     return;
329   }
330   if (do_events) {
331     FORM_DoPageAAction(page, form_handle_, FPDFPAGE_AACTION_CLOSE);
332     FORM_OnBeforeClosePage(page, form_handle_);
333   }
334   FPDF_ClosePage(page);
335   page_map_.erase(page_number);
336 }
337 
SetInitialFormFieldHighlight(FPDF_FORMHANDLE form)338 void EmbedderTest::SetInitialFormFieldHighlight(FPDF_FORMHANDLE form) {
339   FPDF_SetFormFieldHighlightColor(form, FPDF_FORMFIELD_UNKNOWN, 0xFFE4DD);
340   FPDF_SetFormFieldHighlightAlpha(form, 100);
341 }
342 
RenderLoadedPage(FPDF_PAGE page)343 ScopedFPDFBitmap EmbedderTest::RenderLoadedPage(FPDF_PAGE page) {
344   return RenderLoadedPageWithFlags(page, 0);
345 }
346 
RenderLoadedPageWithFlags(FPDF_PAGE page,int flags)347 ScopedFPDFBitmap EmbedderTest::RenderLoadedPageWithFlags(FPDF_PAGE page,
348                                                          int flags) {
349   if (GetPageNumberForLoadedPage(page) < 0) {
350     NOTREACHED();
351     return nullptr;
352   }
353   return RenderPageWithFlags(page, form_handle_, flags);
354 }
355 
RenderSavedPage(FPDF_PAGE page)356 ScopedFPDFBitmap EmbedderTest::RenderSavedPage(FPDF_PAGE page) {
357   return RenderSavedPageWithFlags(page, 0);
358 }
359 
RenderSavedPageWithFlags(FPDF_PAGE page,int flags)360 ScopedFPDFBitmap EmbedderTest::RenderSavedPageWithFlags(FPDF_PAGE page,
361                                                         int flags) {
362   if (GetPageNumberForSavedPage(page) < 0) {
363     NOTREACHED();
364     return nullptr;
365   }
366   return RenderPageWithFlags(page, saved_form_handle_, flags);
367 }
368 
369 // static
RenderPageWithFlags(FPDF_PAGE page,FPDF_FORMHANDLE handle,int flags)370 ScopedFPDFBitmap EmbedderTest::RenderPageWithFlags(FPDF_PAGE page,
371                                                    FPDF_FORMHANDLE handle,
372                                                    int flags) {
373   int width = static_cast<int>(FPDF_GetPageWidthF(page));
374   int height = static_cast<int>(FPDF_GetPageHeightF(page));
375   int alpha = FPDFPage_HasTransparency(page) ? 1 : 0;
376   ScopedFPDFBitmap bitmap(FPDFBitmap_Create(width, height, alpha));
377   FPDF_DWORD fill_color = alpha ? 0x00000000 : 0xFFFFFFFF;
378   FPDFBitmap_FillRect(bitmap.get(), 0, 0, width, height, fill_color);
379   FPDF_RenderPageBitmap(bitmap.get(), page, 0, 0, width, height, 0, flags);
380   FPDF_FFLDraw(handle, bitmap.get(), page, 0, 0, width, height, 0, flags);
381   return bitmap;
382 }
383 
384 // static
RenderPage(FPDF_PAGE page)385 ScopedFPDFBitmap EmbedderTest::RenderPage(FPDF_PAGE page) {
386   return RenderPageWithFlags(page, nullptr, 0);
387 }
388 
389 #if defined(OS_WIN)
390 // static
RenderPageWithFlagsToEmf(FPDF_PAGE page,int flags)391 std::vector<uint8_t> EmbedderTest::RenderPageWithFlagsToEmf(FPDF_PAGE page,
392                                                             int flags) {
393   HDC dc = CreateEnhMetaFileA(nullptr, nullptr, nullptr, nullptr);
394 
395   int width = static_cast<int>(FPDF_GetPageWidthF(page));
396   int height = static_cast<int>(FPDF_GetPageHeightF(page));
397   HRGN rgn = CreateRectRgn(0, 0, width, height);
398   SelectClipRgn(dc, rgn);
399   DeleteObject(rgn);
400 
401   SelectObject(dc, GetStockObject(NULL_PEN));
402   SelectObject(dc, GetStockObject(WHITE_BRUSH));
403   // If a PS_NULL pen is used, the dimensions of the rectangle are 1 pixel less.
404   Rectangle(dc, 0, 0, width + 1, height + 1);
405 
406   FPDF_RenderPage(dc, page, 0, 0, width, height, 0, flags);
407 
408   HENHMETAFILE emf = CloseEnhMetaFile(dc);
409   size_t size_in_bytes = GetEnhMetaFileBits(emf, 0, nullptr);
410   std::vector<uint8_t> buffer(size_in_bytes);
411   GetEnhMetaFileBits(emf, size_in_bytes, buffer.data());
412   DeleteEnhMetaFile(emf);
413   return buffer;
414 }
415 
416 // static
GetPostScriptFromEmf(pdfium::span<const uint8_t> emf_data)417 std::string EmbedderTest::GetPostScriptFromEmf(
418     pdfium::span<const uint8_t> emf_data) {
419   // This comes from Emf::InitFromData() in Chromium.
420   HENHMETAFILE emf = SetEnhMetaFileBits(emf_data.size(), emf_data.data());
421   if (!emf)
422     return std::string();
423 
424   // This comes from Emf::Enumerator::Enumerator() in Chromium.
425   std::vector<const ENHMETARECORD*> records;
426   if (!EnumEnhMetaFile(nullptr, emf, &GetRecordProc, &records, nullptr)) {
427     DeleteEnhMetaFile(emf);
428     return std::string();
429   }
430 
431   // This comes from PostScriptMetaFile::SafePlayback() in Chromium.
432   std::string ps_data;
433   for (const auto* record : records) {
434     if (record->iType != EMR_GDICOMMENT)
435       continue;
436 
437     // PostScript data is encapsulated inside EMF comment records.
438     // The first two bytes of the comment indicate the string length. The rest
439     // is the actual string data.
440     const auto* comment = reinterpret_cast<const EMRGDICOMMENT*>(record);
441     const char* data = reinterpret_cast<const char*>(comment->Data);
442     uint16_t size = *reinterpret_cast<const uint16_t*>(data);
443     data += 2;
444     ps_data.append(data, size);
445   }
446   DeleteEnhMetaFile(emf);
447   return ps_data;
448 }
449 #endif  // defined(OS_WIN)
450 
OpenSavedDocument()451 FPDF_DOCUMENT EmbedderTest::OpenSavedDocument() {
452   return OpenSavedDocumentWithPassword(nullptr);
453 }
454 
455 // static
BytesPerPixelForFormat(int format)456 int EmbedderTest::BytesPerPixelForFormat(int format) {
457   switch (format) {
458     case FPDFBitmap_Gray:
459       return 1;
460     case FPDFBitmap_BGR:
461       return 3;
462     case FPDFBitmap_BGRx:
463     case FPDFBitmap_BGRA:
464       return 4;
465     default:
466       NOTREACHED();
467       return 0;
468   }
469 }
470 
OpenSavedDocumentWithPassword(const char * password)471 FPDF_DOCUMENT EmbedderTest::OpenSavedDocumentWithPassword(
472     const char* password) {
473   memset(&saved_file_access_, 0, sizeof(saved_file_access_));
474   saved_file_access_.m_FileLen = data_string_.size();
475   saved_file_access_.m_GetBlock = GetBlockFromString;
476   // Copy data to prevent clearing it before saved document close.
477   saved_document_file_data_ = data_string_;
478   saved_file_access_.m_Param = &saved_document_file_data_;
479 
480   saved_fake_file_access_ =
481       pdfium::MakeUnique<FakeFileAccess>(&saved_file_access_);
482 
483   EXPECT_TRUE(OpenDocumentHelper(
484       password, LinearizeOption::kDefaultLinearize,
485       JavaScriptOption::kEnableJavaScript, saved_fake_file_access_.get(),
486       &saved_document_, &saved_avail_, &saved_form_handle_));
487   return saved_document_;
488 }
489 
CloseSavedDocument()490 void EmbedderTest::CloseSavedDocument() {
491   ASSERT(saved_document_);
492 
493   FPDFDOC_ExitFormFillEnvironment(saved_form_handle_);
494   FPDF_CloseDocument(saved_document_);
495   FPDFAvail_Destroy(saved_avail_);
496 
497   saved_form_handle_ = nullptr;
498   saved_document_ = nullptr;
499   saved_avail_ = nullptr;
500 }
501 
LoadSavedPage(int page_number)502 FPDF_PAGE EmbedderTest::LoadSavedPage(int page_number) {
503   ASSERT(saved_form_handle_);
504   ASSERT(page_number >= 0);
505   ASSERT(!pdfium::ContainsKey(saved_page_map_, page_number));
506 
507   FPDF_PAGE page = FPDF_LoadPage(saved_document_, page_number);
508   if (!page)
509     return nullptr;
510 
511   FORM_OnAfterLoadPage(page, saved_form_handle_);
512   FORM_DoPageAAction(page, saved_form_handle_, FPDFPAGE_AACTION_OPEN);
513   saved_page_map_[page_number] = page;
514   return page;
515 }
516 
CloseSavedPage(FPDF_PAGE page)517 void EmbedderTest::CloseSavedPage(FPDF_PAGE page) {
518   ASSERT(saved_form_handle_);
519 
520   int page_number = GetPageNumberForSavedPage(page);
521   if (page_number < 0) {
522     NOTREACHED();
523     return;
524   }
525 
526   FORM_DoPageAAction(page, saved_form_handle_, FPDFPAGE_AACTION_CLOSE);
527   FORM_OnBeforeClosePage(page, saved_form_handle_);
528   FPDF_ClosePage(page);
529 
530   saved_page_map_.erase(page_number);
531 }
532 
VerifySavedRendering(FPDF_PAGE page,int width,int height,const char * md5)533 void EmbedderTest::VerifySavedRendering(FPDF_PAGE page,
534                                         int width,
535                                         int height,
536                                         const char* md5) {
537   ASSERT(saved_document_);
538   ASSERT(page);
539 
540   ScopedFPDFBitmap bitmap = RenderSavedPageWithFlags(page, FPDF_ANNOT);
541   CompareBitmap(bitmap.get(), width, height, md5);
542 }
543 
VerifySavedDocument(int width,int height,const char * md5)544 void EmbedderTest::VerifySavedDocument(int width, int height, const char* md5) {
545   ASSERT_TRUE(OpenSavedDocument());
546   FPDF_PAGE page = LoadSavedPage(0);
547   VerifySavedRendering(page, width, height, md5);
548   CloseSavedPage(page);
549   CloseSavedDocument();
550 }
551 
SetWholeFileAvailable()552 void EmbedderTest::SetWholeFileAvailable() {
553   ASSERT(fake_file_access_);
554   fake_file_access_->SetWholeFileAvailable();
555 }
556 
GetPage(FPDF_FORMFILLINFO * info,FPDF_DOCUMENT document,int page_index)557 FPDF_PAGE EmbedderTest::Delegate::GetPage(FPDF_FORMFILLINFO* info,
558                                           FPDF_DOCUMENT document,
559                                           int page_index) {
560   EmbedderTest* test = static_cast<EmbedderTest*>(info);
561   auto it = test->page_map_.find(page_index);
562   return it != test->page_map_.end() ? it->second : nullptr;
563 }
564 
565 // static
UnsupportedHandlerTrampoline(UNSUPPORT_INFO * info,int type)566 void EmbedderTest::UnsupportedHandlerTrampoline(UNSUPPORT_INFO* info,
567                                                 int type) {
568   EmbedderTest* test = static_cast<EmbedderTest*>(info);
569   test->delegate_->UnsupportedHandler(type);
570 }
571 
572 // static
AlertTrampoline(IPDF_JSPLATFORM * platform,FPDF_WIDESTRING message,FPDF_WIDESTRING title,int type,int icon)573 int EmbedderTest::AlertTrampoline(IPDF_JSPLATFORM* platform,
574                                   FPDF_WIDESTRING message,
575                                   FPDF_WIDESTRING title,
576                                   int type,
577                                   int icon) {
578   EmbedderTest* test = static_cast<EmbedderTest*>(platform);
579   return test->delegate_->Alert(message, title, type, icon);
580 }
581 
582 // static
SetTimerTrampoline(FPDF_FORMFILLINFO * info,int msecs,TimerCallback fn)583 int EmbedderTest::SetTimerTrampoline(FPDF_FORMFILLINFO* info,
584                                      int msecs,
585                                      TimerCallback fn) {
586   EmbedderTest* test = static_cast<EmbedderTest*>(info);
587   return test->delegate_->SetTimer(msecs, fn);
588 }
589 
590 // static
KillTimerTrampoline(FPDF_FORMFILLINFO * info,int id)591 void EmbedderTest::KillTimerTrampoline(FPDF_FORMFILLINFO* info, int id) {
592   EmbedderTest* test = static_cast<EmbedderTest*>(info);
593   return test->delegate_->KillTimer(id);
594 }
595 
596 // static
GetPageTrampoline(FPDF_FORMFILLINFO * info,FPDF_DOCUMENT document,int page_index)597 FPDF_PAGE EmbedderTest::GetPageTrampoline(FPDF_FORMFILLINFO* info,
598                                           FPDF_DOCUMENT document,
599                                           int page_index) {
600   return static_cast<EmbedderTest*>(info)->delegate_->GetPage(info, document,
601                                                               page_index);
602 }
603 
604 // static
DoURIActionTrampoline(FPDF_FORMFILLINFO * info,FPDF_BYTESTRING uri)605 void EmbedderTest::DoURIActionTrampoline(FPDF_FORMFILLINFO* info,
606                                          FPDF_BYTESTRING uri) {
607   EmbedderTest* test = static_cast<EmbedderTest*>(info);
608   return test->delegate_->DoURIAction(uri);
609 }
610 
611 // static
HashBitmap(FPDF_BITMAP bitmap)612 std::string EmbedderTest::HashBitmap(FPDF_BITMAP bitmap) {
613   int stride = FPDFBitmap_GetStride(bitmap);
614   int usable_bytes_per_row =
615       GetBitmapBytesPerPixel(bitmap) * FPDFBitmap_GetWidth(bitmap);
616   int height = FPDFBitmap_GetHeight(bitmap);
617   auto span = pdfium::make_span(
618       static_cast<uint8_t*>(FPDFBitmap_GetBuffer(bitmap)), stride * height);
619 
620   CRYPT_md5_context context = CRYPT_MD5Start();
621   for (int i = 0; i < height; ++i)
622     CRYPT_MD5Update(&context, span.subspan(i * stride, usable_bytes_per_row));
623   uint8_t digest[16];
624   CRYPT_MD5Finish(&context, digest);
625   return CryptToBase16(digest);
626 }
627 
628 #ifndef NDEBUG
629 // static
WriteBitmapToPng(FPDF_BITMAP bitmap,const std::string & filename)630 void EmbedderTest::WriteBitmapToPng(FPDF_BITMAP bitmap,
631                                     const std::string& filename) {
632   BitmapSaver::WriteBitmapToPng(bitmap, filename);
633 }
634 #endif
635 
636 // static
CompareBitmap(FPDF_BITMAP bitmap,int expected_width,int expected_height,const char * expected_md5sum)637 void EmbedderTest::CompareBitmap(FPDF_BITMAP bitmap,
638                                  int expected_width,
639                                  int expected_height,
640                                  const char* expected_md5sum) {
641   ASSERT_EQ(expected_width, FPDFBitmap_GetWidth(bitmap));
642   ASSERT_EQ(expected_height, FPDFBitmap_GetHeight(bitmap));
643 
644   // The expected stride is calculated using the same formula as in
645   // CFX_DIBitmap::CalculatePitchAndSize(), which sets the bitmap stride.
646   const int expected_stride =
647       (expected_width * GetBitmapBytesPerPixel(bitmap) * 8 + 31) / 32 * 4;
648   ASSERT_EQ(expected_stride, FPDFBitmap_GetStride(bitmap));
649 
650   if (!expected_md5sum)
651     return;
652 
653   EXPECT_EQ(expected_md5sum, HashBitmap(bitmap));
654 }
655 
656 // static
WriteBlockCallback(FPDF_FILEWRITE * pFileWrite,const void * data,unsigned long size)657 int EmbedderTest::WriteBlockCallback(FPDF_FILEWRITE* pFileWrite,
658                                      const void* data,
659                                      unsigned long size) {
660   EmbedderTest* pThis = static_cast<EmbedderTest*>(pFileWrite);
661 
662   pThis->data_string_.append(static_cast<const char*>(data), size);
663 
664   if (pThis->filestream_.is_open())
665     pThis->filestream_.write(static_cast<const char*>(data), size);
666 
667   return 1;
668 }
669 
670 // static
GetBlockFromString(void * param,unsigned long pos,unsigned char * buf,unsigned long size)671 int EmbedderTest::GetBlockFromString(void* param,
672                                      unsigned long pos,
673                                      unsigned char* buf,
674                                      unsigned long size) {
675   std::string* new_file = static_cast<std::string*>(param);
676   if (!new_file || pos + size < pos) {
677     NOTREACHED();
678     return 0;
679   }
680 
681   if (pos + size > new_file->size()) {
682     NOTREACHED();
683     return 0;
684   }
685 
686   memcpy(buf, new_file->data() + pos, size);
687   return 1;
688 }
689 
690 // static
GetPageNumberForPage(const PageNumberToHandleMap & page_map,FPDF_PAGE page)691 int EmbedderTest::GetPageNumberForPage(const PageNumberToHandleMap& page_map,
692                                        FPDF_PAGE page) {
693   for (const auto& it : page_map) {
694     if (it.second == page) {
695       int page_number = it.first;
696       ASSERT(page_number >= 0);
697       return page_number;
698     }
699   }
700   return -1;
701 }
702 
GetPageNumberForLoadedPage(FPDF_PAGE page) const703 int EmbedderTest::GetPageNumberForLoadedPage(FPDF_PAGE page) const {
704   return GetPageNumberForPage(page_map_, page);
705 }
706 
GetPageNumberForSavedPage(FPDF_PAGE page) const707 int EmbedderTest::GetPageNumberForSavedPage(FPDF_PAGE page) const {
708   return GetPageNumberForPage(saved_page_map_, page);
709 }
710 
711 #ifndef NDEBUG
OpenPDFFileForWrite(const std::string & filename)712 void EmbedderTest::OpenPDFFileForWrite(const std::string& filename) {
713   filestream_.open(filename, std::ios_base::binary);
714 }
715 
ClosePDFFileForWrite()716 void EmbedderTest::ClosePDFFileForWrite() {
717   filestream_.close();
718 }
719 #endif
720