• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2010 The PDFium Authors
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 <locale.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 
10 #include <functional>
11 #include <iterator>
12 #include <map>
13 #include <memory>
14 #include <sstream>
15 #include <string>
16 #include <vector>
17 
18 #if defined(PDF_ENABLE_SKIA) && !defined(_SKIA_SUPPORT_)
19 #define _SKIA_SUPPORT_
20 #endif
21 
22 #include "public/cpp/fpdf_scopers.h"
23 #include "public/fpdf_annot.h"
24 #include "public/fpdf_attachment.h"
25 #include "public/fpdf_dataavail.h"
26 #include "public/fpdf_edit.h"
27 #include "public/fpdf_ext.h"
28 #include "public/fpdf_formfill.h"
29 #include "public/fpdf_progressive.h"
30 #include "public/fpdf_structtree.h"
31 #include "public/fpdf_text.h"
32 #include "public/fpdfview.h"
33 #include "samples/pdfium_test_dump_helper.h"
34 #include "samples/pdfium_test_event_helper.h"
35 #include "samples/pdfium_test_write_helper.h"
36 #include "testing/command_line_helpers.h"
37 #include "testing/font_renamer.h"
38 #include "testing/fx_string_testhelpers.h"
39 #include "testing/test_loader.h"
40 #include "testing/utils/file_util.h"
41 #include "testing/utils/hash.h"
42 #include "testing/utils/path_service.h"
43 #include "third_party/abseil-cpp/absl/types/optional.h"
44 
45 #ifdef _WIN32
46 #include <crtdbg.h>
47 #include <errhandlingapi.h>
48 #include <io.h>
49 #else
50 #include <unistd.h>
51 #endif  // _WIN32
52 
53 #ifdef ENABLE_CALLGRIND
54 #include <valgrind/callgrind.h>
55 #endif  // ENABLE_CALLGRIND
56 
57 #ifdef PDF_ENABLE_SKIA
58 #include "third_party/skia/include/core/SkCanvas.h"           // nogncheck
59 #include "third_party/skia/include/core/SkColor.h"            // nogncheck
60 #include "third_party/skia/include/core/SkPicture.h"          // nogncheck
61 #include "third_party/skia/include/core/SkPictureRecorder.h"  // nogncheck
62 #include "third_party/skia/include/core/SkPixmap.h"           // nogncheck
63 #include "third_party/skia/include/core/SkRefCnt.h"           // nogncheck
64 #include "third_party/skia/include/core/SkSurface.h"          // nogncheck
65 
66 #ifdef BUILD_WITH_CHROMIUM
67 #include "samples/chromium_support/discardable_memory_allocator.h"  // nogncheck
68 #endif
69 #endif  // PDF_ENABLE_SKIA
70 
71 #ifdef PDF_ENABLE_V8
72 #include "testing/v8_initializer.h"
73 #include "v8/include/libplatform/libplatform.h"
74 #include "v8/include/v8-array-buffer.h"
75 #include "v8/include/v8-isolate.h"
76 #include "v8/include/v8-platform.h"
77 #include "v8/include/v8-snapshot.h"
78 #endif  // PDF_ENABLE_V8
79 
80 #ifdef _WIN32
81 #define access _access
82 #define snprintf _snprintf
83 #define R_OK 4
84 #endif
85 
86 // wordexp is a POSIX function that is only available on macOS and non-Android
87 // Linux platforms.
88 #if defined(__APPLE__) || (defined(__linux__) && !defined(__ANDROID__))
89 #define WORDEXP_AVAILABLE
90 #endif
91 
92 #ifdef WORDEXP_AVAILABLE
93 #include <wordexp.h>
94 #endif  // WORDEXP_AVAILABLE
95 
96 namespace {
97 
98 enum class OutputFormat {
99   kNone,
100   kPageInfo,
101   kStructure,
102   kText,
103   kPpm,
104   kPng,
105   kAnnot,
106 #ifdef _WIN32
107   kBmp,
108   kEmf,
109   kPs2,
110   kPs3,
111   kPs3Type42,
112 #endif
113 #ifdef PDF_ENABLE_SKIA
114   kSkp,
115 #endif
116 };
117 
118 struct Options {
119   Options() = default;
120 
121   bool show_config = false;
122   bool show_metadata = false;
123   bool send_events = false;
124   bool use_load_mem_document = false;
125   bool render_oneshot = false;
126   bool lcd_text = false;
127   bool no_nativetext = false;
128   bool grayscale = false;
129   bool forced_color = false;
130   bool fill_to_stroke = false;
131   bool limit_cache = false;
132   bool force_halftone = false;
133   bool printing = false;
134   bool no_smoothtext = false;
135   bool no_smoothimage = false;
136   bool no_smoothpath = false;
137   bool reverse_byte_order = false;
138   bool save_attachments = false;
139   bool save_images = false;
140   bool save_rendered_images = false;
141   bool save_thumbnails = false;
142   bool save_thumbnails_decoded = false;
143   bool save_thumbnails_raw = false;
144   absl::optional<FPDF_RENDERER_TYPE> use_renderer_type;
145 #ifdef PDF_ENABLE_V8
146   bool disable_javascript = false;
147   std::string js_flags;  // Extra flags to pass to v8 init.
148 #ifdef PDF_ENABLE_XFA
149   bool disable_xfa = false;
150 #endif  // PDF_ENABLE_XFA
151 #endif  // PDF_ENABLE_V8
152   bool pages = false;
153   bool md5 = false;
154 #ifdef ENABLE_CALLGRIND
155   bool callgrind_delimiters = false;
156 #endif
157 #if defined(__APPLE__) || (defined(__linux__) && !defined(__ANDROID__))
158   bool linux_no_system_fonts = false;
159 #endif
160   bool croscore_font_names = false;
161   OutputFormat output_format = OutputFormat::kNone;
162   std::string password;
163   std::string scale_factor_as_string;
164   std::string exe_path;
165   std::string bin_directory;
166   std::string font_directory;
167   int first_page = 0;  // First 0-based page number to renderer.
168   int last_page = 0;   // Last 0-based page number to renderer.
169   time_t time = -1;
170 };
171 
PageRenderFlagsFromOptions(const Options & options)172 int PageRenderFlagsFromOptions(const Options& options) {
173   int flags = FPDF_ANNOT;
174   if (options.lcd_text)
175     flags |= FPDF_LCD_TEXT;
176   if (options.no_nativetext)
177     flags |= FPDF_NO_NATIVETEXT;
178   if (options.grayscale)
179     flags |= FPDF_GRAYSCALE;
180   if (options.fill_to_stroke)
181     flags |= FPDF_CONVERT_FILL_TO_STROKE;
182   if (options.limit_cache)
183     flags |= FPDF_RENDER_LIMITEDIMAGECACHE;
184   if (options.force_halftone)
185     flags |= FPDF_RENDER_FORCEHALFTONE;
186   if (options.printing)
187     flags |= FPDF_PRINTING;
188   if (options.no_smoothtext)
189     flags |= FPDF_RENDER_NO_SMOOTHTEXT;
190   if (options.no_smoothimage)
191     flags |= FPDF_RENDER_NO_SMOOTHIMAGE;
192   if (options.no_smoothpath)
193     flags |= FPDF_RENDER_NO_SMOOTHPATH;
194   if (options.reverse_byte_order)
195     flags |= FPDF_REVERSE_BYTE_ORDER;
196   return flags;
197 }
198 
ExpandDirectoryPath(const std::string & path)199 absl::optional<std::string> ExpandDirectoryPath(const std::string& path) {
200 #if defined(WORDEXP_AVAILABLE)
201   wordexp_t expansion;
202   if (wordexp(path.c_str(), &expansion, 0) != 0 || expansion.we_wordc < 1) {
203     wordfree(&expansion);
204     return {};
205   }
206   // Need to contruct the return value before hand, since wordfree will
207   // deallocate |expansion|.
208   absl::optional<std::string> ret_val = {expansion.we_wordv[0]};
209   wordfree(&expansion);
210   return ret_val;
211 #else
212   return {path};
213 #endif  // WORDEXP_AVAILABLE
214 }
215 
GetCustomFontPath(const Options & options)216 absl::optional<const char*> GetCustomFontPath(const Options& options) {
217 #if defined(__APPLE__) || (defined(__linux__) && !defined(__ANDROID__))
218   // Set custom font path to an empty path. This avoids the fallback to default
219   // font paths.
220   if (options.linux_no_system_fonts)
221     return nullptr;
222 #endif
223 
224   // No custom font path. Use default.
225   if (options.font_directory.empty())
226     return absl::nullopt;
227 
228   // Set custom font path to |options.font_directory|.
229   return options.font_directory.c_str();
230 }
231 
232 struct FPDF_FORMFILLINFO_PDFiumTest final : public FPDF_FORMFILLINFO {
233   // Hold a map of the currently loaded pages in order to avoid them
234   // to get loaded twice.
235   std::map<int, ScopedFPDFPage> loaded_pages;
236 
237   // Hold a pointer of FPDF_FORMHANDLE so that PDFium app hooks can
238   // make use of it.
239   FPDF_FORMHANDLE form_handle;
240 };
241 
ToPDFiumTestFormFillInfo(FPDF_FORMFILLINFO * form_fill_info)242 FPDF_FORMFILLINFO_PDFiumTest* ToPDFiumTestFormFillInfo(
243     FPDF_FORMFILLINFO* form_fill_info) {
244   return static_cast<FPDF_FORMFILLINFO_PDFiumTest*>(form_fill_info);
245 }
246 
OutputMD5Hash(const char * file_name,pdfium::span<const uint8_t> output)247 void OutputMD5Hash(const char* file_name, pdfium::span<const uint8_t> output) {
248   // Get the MD5 hash and write it to stdout.
249   std::string hash = GenerateMD5Base16(output);
250   printf("MD5:%s:%s\n", file_name, hash.c_str());
251 }
252 
253 #ifdef PDF_ENABLE_V8
254 
255 struct V8IsolateDeleter {
operator ()__anon768095c60111::V8IsolateDeleter256   inline void operator()(v8::Isolate* ptr) { ptr->Dispose(); }
257 };
258 
259 // These example JS platform callback handlers are entirely optional,
260 // and exist here to show the flow of information from a document back
261 // to the embedder.
ExampleAppAlert(IPDF_JSPLATFORM *,FPDF_WIDESTRING msg,FPDF_WIDESTRING title,int type,int icon)262 int ExampleAppAlert(IPDF_JSPLATFORM*,
263                     FPDF_WIDESTRING msg,
264                     FPDF_WIDESTRING title,
265                     int type,
266                     int icon) {
267   printf("%ls", GetPlatformWString(title).c_str());
268   if (icon || type)
269     printf("[icon=%d,type=%d]", icon, type);
270   printf(": %ls\n", GetPlatformWString(msg).c_str());
271   return 0;
272 }
273 
ExampleAppBeep(IPDF_JSPLATFORM *,int type)274 void ExampleAppBeep(IPDF_JSPLATFORM*, int type) {
275   printf("BEEP!!! %d\n", type);
276 }
277 
ExampleAppResponse(IPDF_JSPLATFORM *,FPDF_WIDESTRING question,FPDF_WIDESTRING title,FPDF_WIDESTRING default_value,FPDF_WIDESTRING label,FPDF_BOOL is_password,void * response,int length)278 int ExampleAppResponse(IPDF_JSPLATFORM*,
279                        FPDF_WIDESTRING question,
280                        FPDF_WIDESTRING title,
281                        FPDF_WIDESTRING default_value,
282                        FPDF_WIDESTRING label,
283                        FPDF_BOOL is_password,
284                        void* response,
285                        int length) {
286   printf("%ls: %ls, defaultValue=%ls, label=%ls, isPassword=%d, length=%d\n",
287          GetPlatformWString(title).c_str(),
288          GetPlatformWString(question).c_str(),
289          GetPlatformWString(default_value).c_str(),
290          GetPlatformWString(label).c_str(), is_password, length);
291 
292   // UTF-16, always LE regardless of platform.
293   auto* ptr = static_cast<uint8_t*>(response);
294   ptr[0] = 'N';
295   ptr[1] = 0;
296   ptr[2] = 'o';
297   ptr[3] = 0;
298   return 4;
299 }
300 
ExampleDocGetFilePath(IPDF_JSPLATFORM *,void * file_path,int length)301 int ExampleDocGetFilePath(IPDF_JSPLATFORM*, void* file_path, int length) {
302   static const char kPath[] = "myfile.pdf";
303   constexpr int kRequired = static_cast<int>(sizeof(kPath));
304   if (file_path && length >= kRequired)
305     memcpy(file_path, kPath, kRequired);
306   return kRequired;
307 }
308 
ExampleDocMail(IPDF_JSPLATFORM *,void * mailData,int length,FPDF_BOOL UI,FPDF_WIDESTRING To,FPDF_WIDESTRING Subject,FPDF_WIDESTRING CC,FPDF_WIDESTRING BCC,FPDF_WIDESTRING Msg)309 void ExampleDocMail(IPDF_JSPLATFORM*,
310                     void* mailData,
311                     int length,
312                     FPDF_BOOL UI,
313                     FPDF_WIDESTRING To,
314                     FPDF_WIDESTRING Subject,
315                     FPDF_WIDESTRING CC,
316                     FPDF_WIDESTRING BCC,
317                     FPDF_WIDESTRING Msg) {
318   printf("Mail Msg: %d, to=%ls, cc=%ls, bcc=%ls, subject=%ls, body=%ls\n", UI,
319          GetPlatformWString(To).c_str(), GetPlatformWString(CC).c_str(),
320          GetPlatformWString(BCC).c_str(), GetPlatformWString(Subject).c_str(),
321          GetPlatformWString(Msg).c_str());
322 }
323 
ExampleDocPrint(IPDF_JSPLATFORM *,FPDF_BOOL bUI,int nStart,int nEnd,FPDF_BOOL bSilent,FPDF_BOOL bShrinkToFit,FPDF_BOOL bPrintAsImage,FPDF_BOOL bReverse,FPDF_BOOL bAnnotations)324 void ExampleDocPrint(IPDF_JSPLATFORM*,
325                      FPDF_BOOL bUI,
326                      int nStart,
327                      int nEnd,
328                      FPDF_BOOL bSilent,
329                      FPDF_BOOL bShrinkToFit,
330                      FPDF_BOOL bPrintAsImage,
331                      FPDF_BOOL bReverse,
332                      FPDF_BOOL bAnnotations) {
333   printf("Doc Print: %d, %d, %d, %d, %d, %d, %d, %d\n", bUI, nStart, nEnd,
334          bSilent, bShrinkToFit, bPrintAsImage, bReverse, bAnnotations);
335 }
336 
ExampleDocSubmitForm(IPDF_JSPLATFORM *,void * formData,int length,FPDF_WIDESTRING url)337 void ExampleDocSubmitForm(IPDF_JSPLATFORM*,
338                           void* formData,
339                           int length,
340                           FPDF_WIDESTRING url) {
341   printf("Doc Submit Form: url=%ls + %d data bytes:\n",
342          GetPlatformWString(url).c_str(), length);
343   uint8_t* ptr = reinterpret_cast<uint8_t*>(formData);
344   for (int i = 0; i < length; ++i)
345     printf(" %02x", ptr[i]);
346   printf("\n");
347 }
348 
ExampleDocGotoPage(IPDF_JSPLATFORM *,int page_number)349 void ExampleDocGotoPage(IPDF_JSPLATFORM*, int page_number) {
350   printf("Goto Page: %d\n", page_number);
351 }
352 
ExampleFieldBrowse(IPDF_JSPLATFORM *,void * file_path,int length)353 int ExampleFieldBrowse(IPDF_JSPLATFORM*, void* file_path, int length) {
354   static const char kPath[] = "selected.txt";
355   constexpr int kRequired = static_cast<int>(sizeof(kPath));
356   if (file_path && length >= kRequired)
357     memcpy(file_path, kPath, kRequired);
358   return kRequired;
359 }
360 #endif  // PDF_ENABLE_V8
361 
362 #ifdef PDF_ENABLE_XFA
ExamplePopupMenu(FPDF_FORMFILLINFO * pInfo,FPDF_PAGE page,FPDF_WIDGET always_null,int flags,float x,float y)363 FPDF_BOOL ExamplePopupMenu(FPDF_FORMFILLINFO* pInfo,
364                            FPDF_PAGE page,
365                            FPDF_WIDGET always_null,
366                            int flags,
367                            float x,
368                            float y) {
369   printf("Popup: x=%2.1f, y=%2.1f, flags=0x%x\n", x, y, flags);
370   return true;
371 }
372 #endif  // PDF_ENABLE_XFA
373 
ExampleNamedAction(FPDF_FORMFILLINFO * pInfo,FPDF_BYTESTRING name)374 void ExampleNamedAction(FPDF_FORMFILLINFO* pInfo, FPDF_BYTESTRING name) {
375   printf("Execute named action: %s\n", name);
376 }
377 
ExampleUnsupportedHandler(UNSUPPORT_INFO *,int type)378 void ExampleUnsupportedHandler(UNSUPPORT_INFO*, int type) {
379   std::string feature = "Unknown";
380   switch (type) {
381     case FPDF_UNSP_DOC_XFAFORM:
382       feature = "XFA";
383       break;
384     case FPDF_UNSP_DOC_PORTABLECOLLECTION:
385       feature = "Portfolios_Packages";
386       break;
387     case FPDF_UNSP_DOC_ATTACHMENT:
388     case FPDF_UNSP_ANNOT_ATTACHMENT:
389       feature = "Attachment";
390       break;
391     case FPDF_UNSP_DOC_SECURITY:
392       feature = "Rights_Management";
393       break;
394     case FPDF_UNSP_DOC_SHAREDREVIEW:
395       feature = "Shared_Review";
396       break;
397     case FPDF_UNSP_DOC_SHAREDFORM_ACROBAT:
398     case FPDF_UNSP_DOC_SHAREDFORM_FILESYSTEM:
399     case FPDF_UNSP_DOC_SHAREDFORM_EMAIL:
400       feature = "Shared_Form";
401       break;
402     case FPDF_UNSP_ANNOT_3DANNOT:
403       feature = "3D";
404       break;
405     case FPDF_UNSP_ANNOT_MOVIE:
406       feature = "Movie";
407       break;
408     case FPDF_UNSP_ANNOT_SOUND:
409       feature = "Sound";
410       break;
411     case FPDF_UNSP_ANNOT_SCREEN_MEDIA:
412     case FPDF_UNSP_ANNOT_SCREEN_RICHMEDIA:
413       feature = "Screen";
414       break;
415     case FPDF_UNSP_ANNOT_SIG:
416       feature = "Digital_Signature";
417       break;
418   }
419   printf("Unsupported feature: %s.\n", feature.c_str());
420 }
421 
ParseCommandLine(const std::vector<std::string> & args,Options * options,std::vector<std::string> * files)422 bool ParseCommandLine(const std::vector<std::string>& args,
423                       Options* options,
424                       std::vector<std::string>* files) {
425   if (args.empty())
426     return false;
427 
428   options->exe_path = args[0];
429   size_t cur_idx = 1;
430   std::string value;
431   for (; cur_idx < args.size(); ++cur_idx) {
432     const std::string& cur_arg = args[cur_idx];
433     if (cur_arg == "--show-config") {
434       options->show_config = true;
435     } else if (cur_arg == "--show-metadata") {
436       options->show_metadata = true;
437     } else if (cur_arg == "--send-events") {
438       options->send_events = true;
439     } else if (cur_arg == "--mem-document") {
440       options->use_load_mem_document = true;
441     } else if (cur_arg == "--render-oneshot") {
442       options->render_oneshot = true;
443     } else if (cur_arg == "--lcd-text") {
444       options->lcd_text = true;
445     } else if (cur_arg == "--no-nativetext") {
446       options->no_nativetext = true;
447     } else if (cur_arg == "--grayscale") {
448       options->grayscale = true;
449     } else if (cur_arg == "--forced-color") {
450       options->forced_color = true;
451     } else if (cur_arg == "--fill-to-stroke") {
452       options->fill_to_stroke = true;
453     } else if (cur_arg == "--limit-cache") {
454       options->limit_cache = true;
455     } else if (cur_arg == "--force-halftone") {
456       options->force_halftone = true;
457     } else if (cur_arg == "--printing") {
458       options->printing = true;
459     } else if (cur_arg == "--no-smoothtext") {
460       options->no_smoothtext = true;
461     } else if (cur_arg == "--no-smoothimage") {
462       options->no_smoothimage = true;
463     } else if (cur_arg == "--no-smoothpath") {
464       options->no_smoothpath = true;
465     } else if (cur_arg == "--reverse-byte-order") {
466       options->reverse_byte_order = true;
467     } else if (cur_arg == "--save-attachments") {
468       options->save_attachments = true;
469     } else if (cur_arg == "--save-images") {
470       if (options->save_rendered_images) {
471         fprintf(stderr,
472                 "--save-rendered-images conflicts with --save-images\n");
473         return false;
474       }
475       options->save_images = true;
476     } else if (cur_arg == "--save-rendered-images") {
477       if (options->save_images) {
478         fprintf(stderr,
479                 "--save-images conflicts with --save-rendered-images\n");
480         return false;
481       }
482       options->save_rendered_images = true;
483     } else if (cur_arg == "--save-thumbs") {
484       options->save_thumbnails = true;
485     } else if (cur_arg == "--save-thumbs-dec") {
486       options->save_thumbnails_decoded = true;
487     } else if (cur_arg == "--save-thumbs-raw") {
488       options->save_thumbnails_raw = true;
489 #if defined(_SKIA_SUPPORT_)
490     } else if (ParseSwitchKeyValue(cur_arg, "--use-renderer=", &value)) {
491       if (options->use_renderer_type.has_value()) {
492         fprintf(stderr, "Duplicate --use-renderer argument\n");
493         return false;
494       }
495       if (value == "agg") {
496         options->use_renderer_type = FPDF_RENDERERTYPE_AGG;
497       } else if (value == "skia") {
498         options->use_renderer_type = FPDF_RENDERERTYPE_SKIA;
499       } else {
500         fprintf(stderr,
501                 "Invalid --use-renderer argument, value must be one of agg or "
502                 "skia\n");
503         return false;
504       }
505 #endif  // defined(_SKIA_SUPPORT_)
506 #ifdef PDF_ENABLE_V8
507     } else if (cur_arg == "--disable-javascript") {
508       options->disable_javascript = true;
509     } else if (ParseSwitchKeyValue(cur_arg, "--js-flags=", &value)) {
510       if (!options->js_flags.empty()) {
511         fprintf(stderr, "Duplicate --js-flags argument\n");
512         return false;
513       }
514       options->js_flags = value;
515 #ifdef PDF_ENABLE_XFA
516     } else if (cur_arg == "--disable-xfa") {
517       options->disable_xfa = true;
518 #endif  // PDF_ENABLE_XFA
519 #endif  // PDF_ENABLE_V8
520 #ifdef ENABLE_CALLGRIND
521     } else if (cur_arg == "--callgrind-delim") {
522       options->callgrind_delimiters = true;
523 #endif
524 #if defined(__APPLE__) || (defined(__linux__) && !defined(__ANDROID__))
525     } else if (cur_arg == "--no-system-fonts") {
526       options->linux_no_system_fonts = true;
527 #endif
528     } else if (cur_arg == "--croscore-font-names") {
529       options->croscore_font_names = true;
530     } else if (cur_arg == "--ppm") {
531       if (options->output_format != OutputFormat::kNone) {
532         fprintf(stderr, "Duplicate or conflicting --ppm argument\n");
533         return false;
534       }
535       options->output_format = OutputFormat::kPpm;
536     } else if (cur_arg == "--png") {
537       if (options->output_format != OutputFormat::kNone) {
538         fprintf(stderr, "Duplicate or conflicting --png argument\n");
539         return false;
540       }
541       options->output_format = OutputFormat::kPng;
542     } else if (cur_arg == "--txt") {
543       if (options->output_format != OutputFormat::kNone) {
544         fprintf(stderr, "Duplicate or conflicting --txt argument\n");
545         return false;
546       }
547       options->output_format = OutputFormat::kText;
548     } else if (cur_arg == "--annot") {
549       if (options->output_format != OutputFormat::kNone) {
550         fprintf(stderr, "Duplicate or conflicting --annot argument\n");
551         return false;
552       }
553       options->output_format = OutputFormat::kAnnot;
554 #ifdef PDF_ENABLE_SKIA
555     } else if (cur_arg == "--skp") {
556       if (options->output_format != OutputFormat::kNone) {
557         fprintf(stderr, "Duplicate or conflicting --skp argument\n");
558         return false;
559       }
560       options->output_format = OutputFormat::kSkp;
561 #endif  // PDF_ENABLE_SKIA
562     } else if (ParseSwitchKeyValue(cur_arg, "--font-dir=", &value)) {
563       if (!options->font_directory.empty()) {
564         fprintf(stderr, "Duplicate --font-dir argument\n");
565         return false;
566       }
567       std::string path = value;
568       absl::optional<std::string> expanded_path = ExpandDirectoryPath(path);
569       if (!expanded_path.has_value()) {
570         fprintf(stderr, "Failed to expand --font-dir, %s\n", path.c_str());
571         return false;
572       }
573 
574       if (!PathService::DirectoryExists(expanded_path.value())) {
575         fprintf(stderr, "--font-dir, %s, appears to not be a directory\n",
576                 path.c_str());
577         return false;
578       }
579 
580       options->font_directory = expanded_path.value();
581 
582 #ifdef _WIN32
583     } else if (cur_arg == "--emf") {
584       if (options->output_format != OutputFormat::kNone) {
585         fprintf(stderr, "Duplicate or conflicting --emf argument\n");
586         return false;
587       }
588       options->output_format = OutputFormat::kEmf;
589     } else if (cur_arg == "--ps2") {
590       if (options->output_format != OutputFormat::kNone) {
591         fprintf(stderr, "Duplicate or conflicting --ps2 argument\n");
592         return false;
593       }
594       options->output_format = OutputFormat::kPs2;
595     } else if (cur_arg == "--ps3") {
596       if (options->output_format != OutputFormat::kNone) {
597         fprintf(stderr, "Duplicate or conflicting --ps3 argument\n");
598         return false;
599       }
600       options->output_format = OutputFormat::kPs3;
601     } else if (cur_arg == "--ps3-type42") {
602       if (options->output_format != OutputFormat::kNone) {
603         fprintf(stderr, "Duplicate or conflicting --ps3-type42 argument\n");
604         return false;
605       }
606       options->output_format = OutputFormat::kPs3Type42;
607     } else if (cur_arg == "--bmp") {
608       if (options->output_format != OutputFormat::kNone) {
609         fprintf(stderr, "Duplicate or conflicting --bmp argument\n");
610         return false;
611       }
612       options->output_format = OutputFormat::kBmp;
613 #endif  // _WIN32
614 
615 #ifdef PDF_ENABLE_V8
616 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
617     } else if (ParseSwitchKeyValue(cur_arg, "--bin-dir=", &value)) {
618       if (!options->bin_directory.empty()) {
619         fprintf(stderr, "Duplicate --bin-dir argument\n");
620         return false;
621       }
622       std::string path = value;
623       absl::optional<std::string> expanded_path = ExpandDirectoryPath(path);
624       if (!expanded_path.has_value()) {
625         fprintf(stderr, "Failed to expand --bin-dir, %s\n", path.c_str());
626         return false;
627       }
628       options->bin_directory = expanded_path.value();
629 #endif  // V8_USE_EXTERNAL_STARTUP_DATA
630 #endif  // PDF_ENABLE_V8
631 
632     } else if (ParseSwitchKeyValue(cur_arg, "--password=", &value)) {
633       if (!options->password.empty()) {
634         fprintf(stderr, "Duplicate --password argument\n");
635         return false;
636       }
637       options->password = value;
638     } else if (ParseSwitchKeyValue(cur_arg, "--scale=", &value)) {
639       if (!options->scale_factor_as_string.empty()) {
640         fprintf(stderr, "Duplicate --scale argument\n");
641         return false;
642       }
643       options->scale_factor_as_string = value;
644     } else if (cur_arg == "--show-pageinfo") {
645       if (options->output_format != OutputFormat::kNone) {
646         fprintf(stderr, "Duplicate or conflicting --show-pageinfo argument\n");
647         return false;
648       }
649       options->output_format = OutputFormat::kPageInfo;
650     } else if (cur_arg == "--show-structure") {
651       if (options->output_format != OutputFormat::kNone) {
652         fprintf(stderr, "Duplicate or conflicting --show-structure argument\n");
653         return false;
654       }
655       options->output_format = OutputFormat::kStructure;
656     } else if (ParseSwitchKeyValue(cur_arg, "--pages=", &value)) {
657       if (options->pages) {
658         fprintf(stderr, "Duplicate --pages argument\n");
659         return false;
660       }
661       options->pages = true;
662       const std::string pages_string = value;
663       size_t first_dash = pages_string.find('-');
664       if (first_dash == std::string::npos) {
665         std::stringstream(pages_string) >> options->first_page;
666         options->last_page = options->first_page;
667       } else {
668         std::stringstream(pages_string.substr(0, first_dash)) >>
669             options->first_page;
670         std::stringstream(pages_string.substr(first_dash + 1)) >>
671             options->last_page;
672       }
673     } else if (cur_arg == "--md5") {
674       options->md5 = true;
675     } else if (ParseSwitchKeyValue(cur_arg, "--time=", &value)) {
676       if (options->time > -1) {
677         fprintf(stderr, "Duplicate --time argument\n");
678         return false;
679       }
680       const std::string time_string = value;
681       std::stringstream(time_string) >> options->time;
682       if (options->time < 0) {
683         fprintf(stderr, "Invalid --time argument, must be non-negative\n");
684         return false;
685       }
686     } else if (cur_arg.size() >= 2 && cur_arg[0] == '-' && cur_arg[1] == '-') {
687       fprintf(stderr, "Unrecognized argument %s\n", cur_arg.c_str());
688       return false;
689     } else {
690       break;
691     }
692   }
693   for (size_t i = cur_idx; i < args.size(); i++)
694     files->push_back(args[i]);
695 
696   return true;
697 }
698 
PrintLastError()699 void PrintLastError() {
700   unsigned long err = FPDF_GetLastError();
701   fprintf(stderr, "Load pdf docs unsuccessful: ");
702   switch (err) {
703     case FPDF_ERR_SUCCESS:
704       fprintf(stderr, "Success");
705       break;
706     case FPDF_ERR_UNKNOWN:
707       fprintf(stderr, "Unknown error");
708       break;
709     case FPDF_ERR_FILE:
710       fprintf(stderr, "File not found or could not be opened");
711       break;
712     case FPDF_ERR_FORMAT:
713       fprintf(stderr, "File not in PDF format or corrupted");
714       break;
715     case FPDF_ERR_PASSWORD:
716       fprintf(stderr, "Password required or incorrect password");
717       break;
718     case FPDF_ERR_SECURITY:
719       fprintf(stderr, "Unsupported security scheme");
720       break;
721     case FPDF_ERR_PAGE:
722       fprintf(stderr, "Page not found or content error");
723       break;
724     default:
725       fprintf(stderr, "Unknown error %ld", err);
726   }
727   fprintf(stderr, ".\n");
728 }
729 
Is_Data_Avail(FX_FILEAVAIL * avail,size_t offset,size_t size)730 FPDF_BOOL Is_Data_Avail(FX_FILEAVAIL* avail, size_t offset, size_t size) {
731   return true;
732 }
733 
Add_Segment(FX_DOWNLOADHINTS * hints,size_t offset,size_t size)734 void Add_Segment(FX_DOWNLOADHINTS* hints, size_t offset, size_t size) {}
735 
GetPageForIndex(FPDF_FORMFILLINFO * param,FPDF_DOCUMENT doc,int index)736 FPDF_PAGE GetPageForIndex(FPDF_FORMFILLINFO* param,
737                           FPDF_DOCUMENT doc,
738                           int index) {
739   FPDF_FORMFILLINFO_PDFiumTest* form_fill_info =
740       ToPDFiumTestFormFillInfo(param);
741   auto& loaded_pages = form_fill_info->loaded_pages;
742   auto iter = loaded_pages.find(index);
743   if (iter != loaded_pages.end())
744     return iter->second.get();
745 
746   ScopedFPDFPage page(FPDF_LoadPage(doc, index));
747   if (!page)
748     return nullptr;
749 
750   // Mark the page as loaded first to prevent infinite recursion.
751   FPDF_PAGE page_ptr = page.get();
752   loaded_pages[index] = std::move(page);
753 
754   FPDF_FORMHANDLE& form_handle = form_fill_info->form_handle;
755   FORM_OnAfterLoadPage(page_ptr, form_handle);
756   FORM_DoPageAAction(page_ptr, form_handle, FPDFPAGE_AACTION_OPEN);
757   return page_ptr;
758 }
759 
760 // Note, for a client using progressive rendering you'd want to determine if you
761 // need the rendering to pause instead of always saying |true|. This is for
762 // testing to force the renderer to break whenever possible.
NeedToPauseNow(IFSDK_PAUSE * p)763 FPDF_BOOL NeedToPauseNow(IFSDK_PAUSE* p) {
764   return true;
765 }
766 
767 // Renderer for a single page.
768 class PageRenderer {
769  public:
770   virtual ~PageRenderer() = default;
771 
772   // Returns `true` if the rendered output exists. Must call `Finish()` first.
773   virtual bool HasOutput() const = 0;
774 
775   // Starts rendering the page, returning `false` on failure.
776   virtual bool Start() = 0;
777 
778   // Continues rendering the page, returning `false` when complete.
Continue()779   virtual bool Continue() { return false; }
780 
781   // Finishes rendering the page.
782   virtual void Finish(FPDF_FORMHANDLE form) = 0;
783 
784   // Writes rendered output to a file, returning `false` on failure.
785   virtual bool Write(const std::string& name, int page_index, bool md5) = 0;
786 
787  protected:
PageRenderer(FPDF_PAGE page,int width,int height,int flags)788   PageRenderer(FPDF_PAGE page, int width, int height, int flags)
789       : page_(page), width_(width), height_(height), flags_(flags) {}
790 
page()791   FPDF_PAGE page() { return page_; }
width() const792   int width() const { return width_; }
height() const793   int height() const { return height_; }
flags() const794   int flags() const { return flags_; }
795 
796  private:
797   FPDF_PAGE page_;
798   int width_;
799   int height_;
800   int flags_;
801 };
802 
803 // Page renderer with bitmap output.
804 class BitmapPageRenderer : public PageRenderer {
805  public:
806   // Function type that writes a bitmap to an image file. The function returns
807   // the name of the image file on success, or an empty name on failure.
808   //
809   // Intended for use with some of the `pdfium_test_write_helper.h` functions.
810   using BitmapWriter = std::string (*)(const char* pdf_name,
811                                        int num,
812                                        void* buffer,
813                                        int stride,
814                                        int width,
815                                        int height);
816 
HasOutput() const817   bool HasOutput() const override { return !!bitmap_; }
818 
Start()819   bool Start() override {
820     bool alpha = FPDFPage_HasTransparency(page());
821     bitmap_.reset(FPDFBitmap_Create(/*width=*/width(), /*height=*/height(),
822                                     /*alpha=*/alpha));
823     if (!bitmap_)
824       return false;
825 
826     FPDF_DWORD fill_color = alpha ? 0x00000000 : 0xFFFFFFFF;
827     FPDFBitmap_FillRect(bitmap(), /*left=*/0, /*top=*/0, /*width=*/width(),
828                         /*height=*/height(), /*color=*/fill_color);
829     return true;
830   }
831 
Finish(FPDF_FORMHANDLE form)832   void Finish(FPDF_FORMHANDLE form) override {
833     FPDF_FFLDraw(form, bitmap(), page(), /*start_x=*/0, /*start_y=*/0,
834                  /*size_x=*/width(), /*size_y=*/height(), /*rotate=*/0,
835                  /*flags=*/flags());
836     Idle();
837   }
838 
Write(const std::string & name,int page_index,bool md5)839   bool Write(const std::string& name, int page_index, bool md5) override {
840     if (!writer_)
841       return false;
842 
843     int stride = FPDFBitmap_GetStride(bitmap());
844     void* buffer = FPDFBitmap_GetBuffer(bitmap());
845     std::string image_file_name =
846         writer_(name.c_str(), /*num=*/page_index, buffer, /*stride=*/stride,
847                 /*width=*/width(), /*height=*/height());
848     if (image_file_name.empty())
849       return false;
850 
851     if (md5) {
852       // Write the filename and the MD5 of the buffer to stdout.
853       OutputMD5Hash(image_file_name.c_str(),
854                     {static_cast<const uint8_t*>(buffer),
855                      static_cast<size_t>(stride) * height()});
856     }
857     return true;
858   }
859 
860  protected:
BitmapPageRenderer(FPDF_PAGE page,int width,int height,int flags,const std::function<void ()> & idler,BitmapWriter writer)861   BitmapPageRenderer(FPDF_PAGE page,
862                      int width,
863                      int height,
864                      int flags,
865                      const std::function<void()>& idler,
866                      BitmapWriter writer)
867       : PageRenderer(page, /*width=*/width, /*height=*/height, /*flags=*/flags),
868         idler_(idler),
869         writer_(writer) {}
870 
Idle() const871   void Idle() const { idler_(); }
bitmap()872   FPDF_BITMAP bitmap() { return bitmap_.get(); }
873 
874  private:
875   const std::function<void()>& idler_;
876   BitmapWriter writer_;
877   ScopedFPDFBitmap bitmap_;
878 };
879 
880 // Bitmap page renderer completing in a single operation.
881 class OneShotBitmapPageRenderer : public BitmapPageRenderer {
882  public:
OneShotBitmapPageRenderer(FPDF_PAGE page,int width,int height,int flags,const std::function<void ()> & idler,BitmapWriter writer)883   OneShotBitmapPageRenderer(FPDF_PAGE page,
884                             int width,
885                             int height,
886                             int flags,
887                             const std::function<void()>& idler,
888                             BitmapWriter writer)
889       : BitmapPageRenderer(page,
890                            /*width=*/width,
891                            /*height=*/height,
892                            /*flags=*/flags,
893                            idler,
894                            writer) {}
895 
Start()896   bool Start() override {
897     if (!BitmapPageRenderer::Start())
898       return false;
899 
900     // Note, client programs probably want to use this method instead of the
901     // progressive calls. The progressive calls are if you need to pause the
902     // rendering to update the UI, the PDF renderer will break when possible.
903     FPDF_RenderPageBitmap(bitmap(), page(), /*start_x=*/0, /*start_y=*/0,
904                           /*size_x=*/width(), /*size_y=*/height(), /*rotate=*/0,
905                           /*flags=*/flags());
906     return true;
907   }
908 };
909 
910 // Bitmap page renderer completing over multiple operations.
911 class ProgressiveBitmapPageRenderer : public BitmapPageRenderer {
912  public:
ProgressiveBitmapPageRenderer(FPDF_PAGE page,int width,int height,int flags,const std::function<void ()> & idler,BitmapWriter writer,const FPDF_COLORSCHEME * color_scheme)913   ProgressiveBitmapPageRenderer(FPDF_PAGE page,
914                                 int width,
915                                 int height,
916                                 int flags,
917                                 const std::function<void()>& idler,
918                                 BitmapWriter writer,
919                                 const FPDF_COLORSCHEME* color_scheme)
920       : BitmapPageRenderer(page,
921                            /*width=*/width,
922                            /*height=*/height,
923                            /*flags=*/flags,
924                            idler,
925                            writer),
926         color_scheme_(color_scheme) {
927     pause_.version = 1;
928     pause_.NeedToPauseNow = &NeedToPauseNow;
929   }
930 
Start()931   bool Start() override {
932     if (!BitmapPageRenderer::Start())
933       return false;
934 
935     if (FPDF_RenderPageBitmapWithColorScheme_Start(
936             bitmap(), page(), /*start_x=*/0, /*start_y=*/0, /*size_x=*/width(),
937             /*size_y=*/height(), /*rotate=*/0, /*flags=*/flags(), color_scheme_,
938             &pause_) == FPDF_RENDER_TOBECONTINUED) {
939       to_be_continued_ = true;
940     }
941     return true;
942   }
943 
Continue()944   bool Continue() override {
945     if (to_be_continued_) {
946       to_be_continued_ = (FPDF_RenderPage_Continue(page(), &pause_) ==
947                           FPDF_RENDER_TOBECONTINUED);
948     }
949     return to_be_continued_;
950   }
951 
Finish(FPDF_FORMHANDLE form)952   void Finish(FPDF_FORMHANDLE form) override {
953     BitmapPageRenderer::Finish(form);
954     FPDF_RenderPage_Close(page());
955     Idle();
956   }
957 
958  private:
959   const FPDF_COLORSCHEME* color_scheme_;
960   IFSDK_PAUSE pause_;
961   bool to_be_continued_ = false;
962 };
963 
964 #ifdef PDF_ENABLE_SKIA
965 class SkPicturePageRenderer : public PageRenderer {
966  public:
SkPicturePageRenderer(FPDF_PAGE page,int width,int height,int flags)967   SkPicturePageRenderer(FPDF_PAGE page, int width, int height, int flags)
968       : PageRenderer(page,
969                      /*width=*/width,
970                      /*height=*/height,
971                      /*flags=*/flags) {}
972 
HasOutput() const973   bool HasOutput() const override { return !!picture_; }
974 
Start()975   bool Start() override {
976     recorder_.reset(reinterpret_cast<SkPictureRecorder*>(
977         FPDF_RenderPageSkp(page(), /*size_x=*/width(), /*size_y=*/height())));
978     return !!recorder_;
979   }
980 
Finish(FPDF_FORMHANDLE form)981   void Finish(FPDF_FORMHANDLE form) override {
982     FPDF_FFLRecord(form, reinterpret_cast<FPDF_RECORDER>(recorder_.get()),
983                    page(), /*start_x=*/0, /*start_y=*/0, /*size_x=*/width(),
984                    /*size_y=*/height(), /*rotate=*/0, /*flags=*/0);
985 
986     picture_ = recorder_->finishRecordingAsPicture();
987     recorder_.reset();
988   }
989 
Write(const std::string & name,int page_index,bool md5)990   bool Write(const std::string& name, int page_index, bool md5) override {
991     std::string image_file_name = WriteSkp(name.c_str(), page_index, *picture_);
992     if (image_file_name.empty())
993       return false;
994 
995     if (md5) {
996       // Play back the `SkPicture` so we can take a hash of the result.
997       sk_sp<SkSurface> surface = SkSurface::MakeRasterN32Premul(
998           /*width=*/width(), /*height=*/height());
999       if (!surface)
1000         return false;
1001 
1002       // Must clear to white before replay to match initial `CFX_DIBitmap`.
1003       surface->getCanvas()->clear(SK_ColorWHITE);
1004       surface->getCanvas()->drawPicture(picture_);
1005 
1006       // Write the filename and the MD5 of the buffer to stdout.
1007       SkPixmap pixmap;
1008       if (!surface->peekPixels(&pixmap))
1009         return false;
1010 
1011       OutputMD5Hash(image_file_name.c_str(),
1012                     {static_cast<const uint8_t*>(pixmap.addr()),
1013                      pixmap.computeByteSize()});
1014     }
1015     return true;
1016   }
1017 
1018  private:
1019   std::unique_ptr<SkPictureRecorder> recorder_;
1020   sk_sp<SkPicture> picture_;
1021 };
1022 #endif  // PDF_ENABLE_SKIA
1023 
ProcessPage(const std::string & name,FPDF_DOCUMENT doc,FPDF_FORMHANDLE form,FPDF_FORMFILLINFO_PDFiumTest * form_fill_info,const int page_index,const Options & options,const std::string & events,const std::function<void ()> & idler)1024 bool ProcessPage(const std::string& name,
1025                  FPDF_DOCUMENT doc,
1026                  FPDF_FORMHANDLE form,
1027                  FPDF_FORMFILLINFO_PDFiumTest* form_fill_info,
1028                  const int page_index,
1029                  const Options& options,
1030                  const std::string& events,
1031                  const std::function<void()>& idler) {
1032   FPDF_PAGE page = GetPageForIndex(form_fill_info, doc, page_index);
1033   if (!page)
1034     return false;
1035   if (options.send_events)
1036     SendPageEvents(form, page, events, idler);
1037   if (options.save_images)
1038     WriteImages(page, name.c_str(), page_index);
1039   if (options.save_rendered_images)
1040     WriteRenderedImages(doc, page, name.c_str(), page_index);
1041   if (options.save_thumbnails)
1042     WriteThumbnail(page, name.c_str(), page_index);
1043   if (options.save_thumbnails_decoded)
1044     WriteDecodedThumbnailStream(page, name.c_str(), page_index);
1045   if (options.save_thumbnails_raw)
1046     WriteRawThumbnailStream(page, name.c_str(), page_index);
1047   if (options.output_format == OutputFormat::kPageInfo) {
1048     DumpPageInfo(page, page_index);
1049     return true;
1050   }
1051   if (options.output_format == OutputFormat::kStructure) {
1052     DumpPageStructure(page, page_index);
1053     return true;
1054   }
1055 
1056   ScopedFPDFTextPage text_page(FPDFText_LoadPage(page));
1057   double scale = 1.0;
1058   if (!options.scale_factor_as_string.empty())
1059     std::stringstream(options.scale_factor_as_string) >> scale;
1060 
1061   int width = static_cast<int>(FPDF_GetPageWidthF(page) * scale);
1062   int height = static_cast<int>(FPDF_GetPageHeightF(page) * scale);
1063   int flags = PageRenderFlagsFromOptions(options);
1064 
1065   std::unique_ptr<PageRenderer> renderer;
1066 #ifdef PDF_ENABLE_SKIA
1067   if (options.output_format == OutputFormat::kSkp) {
1068     renderer = std::make_unique<SkPicturePageRenderer>(
1069         page, /*width=*/width, /*height=*/height, /*flags=*/flags);
1070   } else {
1071 #else
1072   {
1073 #endif  // PDF_ENABLE_SKIA
1074     BitmapPageRenderer::BitmapWriter writer;
1075     switch (options.output_format) {
1076 #ifdef _WIN32
1077       case OutputFormat::kBmp:
1078         writer = WriteBmp;
1079         break;
1080 #endif  // _WIN32
1081 
1082       case OutputFormat::kPng:
1083         writer = WritePng;
1084         break;
1085 
1086       case OutputFormat::kPpm:
1087         writer = WritePpm;
1088         break;
1089 
1090       default:
1091         // Other formats won't write the output to a file, but still rasterize.
1092         writer = nullptr;
1093         break;
1094     }
1095 
1096     if (options.render_oneshot) {
1097       renderer = std::make_unique<OneShotBitmapPageRenderer>(
1098           page, /*width=*/width, /*height=*/height, /*flags=*/flags, idler,
1099           writer);
1100     } else {
1101       // Client programs will be setting these values when rendering.
1102       // This is a sample color scheme with distinct colors.
1103       // Used only when `options.forced_color` is true.
1104       FPDF_COLORSCHEME color_scheme;
1105       color_scheme.path_fill_color = 0xFFFF0000;
1106       color_scheme.path_stroke_color = 0xFF00FF00;
1107       color_scheme.text_fill_color = 0xFF0000FF;
1108       color_scheme.text_stroke_color = 0xFF00FFFF;
1109 
1110       renderer = std::make_unique<ProgressiveBitmapPageRenderer>(
1111           page, /*width=*/width, /*height=*/height, /*flags=*/flags, idler,
1112           writer, options.forced_color ? &color_scheme : nullptr);
1113     }
1114   }
1115 
1116   if (renderer->Start()) {
1117     while (renderer->Continue())
1118       continue;
1119     renderer->Finish(form);
1120 
1121     switch (options.output_format) {
1122 #ifdef _WIN32
1123       case OutputFormat::kEmf:
1124         WriteEmf(page, name.c_str(), page_index);
1125         break;
1126 
1127       case OutputFormat::kPs2:
1128       case OutputFormat::kPs3:
1129         WritePS(page, name.c_str(), page_index);
1130         break;
1131 #endif  // _WIN32
1132 
1133       case OutputFormat::kText:
1134         WriteText(text_page.get(), name.c_str(), page_index);
1135         break;
1136 
1137       case OutputFormat::kAnnot:
1138         WriteAnnot(page, name.c_str(), page_index);
1139         break;
1140 
1141       default:
1142         renderer->Write(name, page_index, /*md5=*/options.md5);
1143         break;
1144     }
1145   } else {
1146     fprintf(stderr, "Page was too large to be rendered.\n");
1147   }
1148 
1149   FORM_DoPageAAction(page, form, FPDFPAGE_AACTION_CLOSE);
1150   idler();
1151 
1152   FORM_OnBeforeClosePage(page, form);
1153   idler();
1154 
1155   return renderer->HasOutput();
1156 }
1157 
1158 void ProcessPdf(const std::string& name,
1159                 const char* buf,
1160                 size_t len,
1161                 const Options& options,
1162                 const std::string& events,
1163                 const std::function<void()>& idler) {
1164   TestLoader loader({buf, len});
1165 
1166   FPDF_FILEACCESS file_access = {};
1167   file_access.m_FileLen = static_cast<unsigned long>(len);
1168   file_access.m_GetBlock = TestLoader::GetBlock;
1169   file_access.m_Param = &loader;
1170 
1171   FX_FILEAVAIL file_avail = {};
1172   file_avail.version = 1;
1173   file_avail.IsDataAvail = Is_Data_Avail;
1174 
1175   FX_DOWNLOADHINTS hints = {};
1176   hints.version = 1;
1177   hints.AddSegment = Add_Segment;
1178 
1179   // |pdf_avail| must outlive |doc|.
1180   ScopedFPDFAvail pdf_avail(FPDFAvail_Create(&file_avail, &file_access));
1181 
1182   // |doc| must outlive |form_callbacks.loaded_pages|.
1183   ScopedFPDFDocument doc;
1184 
1185   const char* password =
1186       options.password.empty() ? nullptr : options.password.c_str();
1187   bool is_linearized = false;
1188   if (options.use_load_mem_document) {
1189     doc.reset(FPDF_LoadMemDocument(buf, len, password));
1190   } else {
1191     if (FPDFAvail_IsLinearized(pdf_avail.get()) == PDF_LINEARIZED) {
1192       int avail_status = PDF_DATA_NOTAVAIL;
1193       doc.reset(FPDFAvail_GetDocument(pdf_avail.get(), password));
1194       if (doc) {
1195         while (avail_status == PDF_DATA_NOTAVAIL)
1196           avail_status = FPDFAvail_IsDocAvail(pdf_avail.get(), &hints);
1197 
1198         if (avail_status == PDF_DATA_ERROR) {
1199           fprintf(stderr, "Unknown error in checking if doc was available.\n");
1200           return;
1201         }
1202         avail_status = FPDFAvail_IsFormAvail(pdf_avail.get(), &hints);
1203         if (avail_status == PDF_FORM_ERROR ||
1204             avail_status == PDF_FORM_NOTAVAIL) {
1205           fprintf(stderr,
1206                   "Error %d was returned in checking if form was available.\n",
1207                   avail_status);
1208           return;
1209         }
1210         is_linearized = true;
1211       }
1212     } else {
1213       doc.reset(FPDF_LoadCustomDocument(&file_access, password));
1214     }
1215   }
1216 
1217   if (!doc) {
1218     PrintLastError();
1219     return;
1220   }
1221 
1222   if (!FPDF_DocumentHasValidCrossReferenceTable(doc.get()))
1223     fprintf(stderr, "Document has invalid cross reference table\n");
1224 
1225   (void)FPDF_GetDocPermissions(doc.get());
1226 
1227   if (options.show_metadata)
1228     DumpMetaData(doc.get());
1229 
1230   if (options.save_attachments)
1231     WriteAttachments(doc.get(), name);
1232 
1233 #ifdef PDF_ENABLE_V8
1234   IPDF_JSPLATFORM platform_callbacks = {};
1235   platform_callbacks.version = 3;
1236   platform_callbacks.app_alert = ExampleAppAlert;
1237   platform_callbacks.app_beep = ExampleAppBeep;
1238   platform_callbacks.app_response = ExampleAppResponse;
1239   platform_callbacks.Doc_getFilePath = ExampleDocGetFilePath;
1240   platform_callbacks.Doc_mail = ExampleDocMail;
1241   platform_callbacks.Doc_print = ExampleDocPrint;
1242   platform_callbacks.Doc_submitForm = ExampleDocSubmitForm;
1243   platform_callbacks.Doc_gotoPage = ExampleDocGotoPage;
1244   platform_callbacks.Field_browse = ExampleFieldBrowse;
1245 #endif  // PDF_ENABLE_V8
1246 
1247   FPDF_FORMFILLINFO_PDFiumTest form_callbacks = {};
1248 #ifdef PDF_ENABLE_XFA
1249   form_callbacks.version = 2;
1250   form_callbacks.xfa_disabled =
1251       options.disable_xfa || options.disable_javascript;
1252   form_callbacks.FFI_PopupMenu = ExamplePopupMenu;
1253 #else   // PDF_ENABLE_XFA
1254   form_callbacks.version = 1;
1255 #endif  // PDF_ENABLE_XFA
1256   form_callbacks.FFI_ExecuteNamedAction = ExampleNamedAction;
1257   form_callbacks.FFI_GetPage = GetPageForIndex;
1258 
1259 #ifdef PDF_ENABLE_V8
1260   if (!options.disable_javascript)
1261     form_callbacks.m_pJsPlatform = &platform_callbacks;
1262 #endif  // PDF_ENABLE_V8
1263 
1264   ScopedFPDFFormHandle form(
1265       FPDFDOC_InitFormFillEnvironment(doc.get(), &form_callbacks));
1266   form_callbacks.form_handle = form.get();
1267 
1268 #ifdef PDF_ENABLE_XFA
1269   if (!options.disable_xfa && !options.disable_javascript) {
1270     int doc_type = FPDF_GetFormType(doc.get());
1271     if (doc_type == FORMTYPE_XFA_FULL || doc_type == FORMTYPE_XFA_FOREGROUND) {
1272       if (!FPDF_LoadXFA(doc.get()))
1273         fprintf(stderr, "LoadXFA unsuccessful, continuing anyway.\n");
1274     }
1275   }
1276 #endif  // PDF_ENABLE_XFA
1277 
1278   FPDF_SetFormFieldHighlightColor(form.get(), FPDF_FORMFIELD_UNKNOWN, 0xFFE4DD);
1279   FPDF_SetFormFieldHighlightAlpha(form.get(), 100);
1280   FORM_DoDocumentJSAction(form.get());
1281   FORM_DoDocumentOpenAction(form.get());
1282 
1283 #if _WIN32
1284   if (options.output_format == OutputFormat::kPs2)
1285     FPDF_SetPrintMode(FPDF_PRINTMODE_POSTSCRIPT2);
1286   else if (options.output_format == OutputFormat::kPs3)
1287     FPDF_SetPrintMode(FPDF_PRINTMODE_POSTSCRIPT3);
1288   else if (options.output_format == OutputFormat::kPs3Type42)
1289     FPDF_SetPrintMode(FPDF_PRINTMODE_POSTSCRIPT3_TYPE42);
1290 #endif
1291 
1292   int page_count = FPDF_GetPageCount(doc.get());
1293   int processed_pages = 0;
1294   int bad_pages = 0;
1295   int first_page = options.pages ? options.first_page : 0;
1296   int last_page = options.pages ? options.last_page + 1 : page_count;
1297   for (int i = first_page; i < last_page; ++i) {
1298     if (is_linearized) {
1299       int avail_status = PDF_DATA_NOTAVAIL;
1300       while (avail_status == PDF_DATA_NOTAVAIL)
1301         avail_status = FPDFAvail_IsPageAvail(pdf_avail.get(), i, &hints);
1302 
1303       if (avail_status == PDF_DATA_ERROR) {
1304         fprintf(stderr, "Unknown error in checking if page %d is available.\n",
1305                 i);
1306         return;
1307       }
1308     }
1309     if (ProcessPage(name, doc.get(), form.get(), &form_callbacks, i, options,
1310                     events, idler)) {
1311       ++processed_pages;
1312     } else {
1313       ++bad_pages;
1314     }
1315     idler();
1316   }
1317 
1318   FORM_DoDocumentAAction(form.get(), FPDFDOC_AACTION_WC);
1319   idler();
1320 
1321   fprintf(stderr, "Processed %d pages.\n", processed_pages);
1322   if (bad_pages)
1323     fprintf(stderr, "Skipped %d bad pages.\n", bad_pages);
1324 }
1325 
1326 void ShowConfig() {
1327   std::string config;
1328   [[maybe_unused]] auto append_config = [&config](const char* name) {
1329     if (!config.empty())
1330       config += ',';
1331     config += name;
1332   };
1333 
1334 #ifdef PDF_ENABLE_V8
1335   append_config("V8");
1336 #endif
1337 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
1338   append_config("V8_EXTERNAL");
1339 #endif
1340 #ifdef PDF_ENABLE_XFA
1341   append_config("XFA");
1342 #endif
1343 #ifdef PDF_ENABLE_ASAN
1344   append_config("ASAN");
1345 #endif
1346 #ifdef PDF_ENABLE_SKIA
1347   append_config("SKIA");
1348 #endif
1349   printf("%s\n", config.c_str());
1350 }
1351 
1352 constexpr char kUsageString[] =
1353     "Usage: pdfium_test [OPTION] [FILE]...\n"
1354     "  --show-config          - print build options and exit\n"
1355     "  --show-metadata        - print the file metadata\n"
1356     "  --show-pageinfo        - print information about pages\n"
1357     "  --show-structure       - print the structure elements from the "
1358     "document\n"
1359     "  --send-events          - send input described by .evt file\n"
1360     "  --mem-document         - load document with FPDF_LoadMemDocument()\n"
1361     "  --render-oneshot       - render image without using progressive "
1362     "renderer\n"
1363     "  --lcd-text             - render text optimized for LCD displays\n"
1364     "  --no-nativetext        - render without using the native text output\n"
1365     "  --grayscale            - render grayscale output\n"
1366     "  --forced-color         - render in forced color mode\n"
1367     "  --fill-to-stroke       - render fill as stroke in forced color mode\n"
1368     "  --limit-cache          - render limiting image cache size\n"
1369     "  --force-halftone       - render forcing halftone\n"
1370     "  --printing             - render as if for printing\n"
1371     "  --no-smoothtext        - render disabling text anti-aliasing\n"
1372     "  --no-smoothimage       - render disabling image anti-alisasing\n"
1373     "  --no-smoothpath        - render disabling path anti-aliasing\n"
1374     "  --reverse-byte-order   - render to BGRA, if supported by the output "
1375     "format\n"
1376     "  --save-attachments     - write embedded attachments "
1377     "<pdf-name>.attachment.<attachment-name>\n"
1378     "  --save-images          - write raw embedded images "
1379     "<pdf-name>.<page-number>.<object-number>.png\n"
1380     "  --save-rendered-images - write embedded images as rendered on the page "
1381     "<pdf-name>.<page-number>.<object-number>.png\n"
1382     "  --save-thumbs          - write page thumbnails "
1383     "<pdf-name>.thumbnail.<page-number>.png\n"
1384     "  --save-thumbs-dec      - write page thumbnails' decoded stream data"
1385     "<pdf-name>.thumbnail.decoded.<page-number>.png\n"
1386     "  --save-thumbs-raw      - write page thumbnails' raw stream data"
1387     "<pdf-name>.thumbnail.raw.<page-number>.png\n"
1388 #if defined(_SKIA_SUPPORT_)
1389     "  --use-renderer         - renderer to use, one of [agg | skia]\n"
1390 #endif
1391 #ifdef PDF_ENABLE_V8
1392     "  --disable-javascript   - do not execute JS in PDF files\n"
1393     "  --js-flags=<flags>     - additional flags to pass to V8\n"
1394 #ifdef PDF_ENABLE_XFA
1395     "  --disable-xfa          - do not process XFA forms\n"
1396 #endif  // PDF_ENABLE_XFA
1397 #endif  // PDF_ENABLE_V8
1398 #ifdef ENABLE_CALLGRIND
1399     "  --callgrind-delim      - delimit interesting section when using "
1400     "callgrind\n"
1401 #endif
1402 #if defined(__APPLE__) || (defined(__linux__) && !defined(__ANDROID__))
1403     "  --no-system-fonts      - do not use system fonts, overrides --font-dir\n"
1404 #endif
1405     "  --croscore-font-names  - use Croscore font names\n"
1406     "  --bin-dir=<path>       - override path to v8 external data\n"
1407     "  --font-dir=<path>      - override path to external fonts\n"
1408     "  --scale=<number>       - scale output size by number (e.g. 0.5)\n"
1409     "  --password=<secret>    - password to decrypt the PDF with\n"
1410     "  --pages=<number>(-<number>) - only render the given 0-based page(s)\n"
1411 #ifdef _WIN32
1412     "  --bmp   - write page images <pdf-name>.<page-number>.bmp\n"
1413     "  --emf   - write page meta files <pdf-name>.<page-number>.emf\n"
1414     "  --ps2   - write page raw PostScript (Lvl 2) "
1415     "<pdf-name>.<page-number>.ps\n"
1416     "  --ps3   - write page raw PostScript (Lvl 3) "
1417     "<pdf-name>.<page-number>.ps\n"
1418     "  --ps3-type42 - write page raw PostScript (Lvl 3 with Type 42 fonts) "
1419     "<pdf-name>.<page-number>.ps\n"
1420 #endif
1421     "  --txt   - write page text in UTF32-LE <pdf-name>.<page-number>.txt\n"
1422     "  --png   - write page images <pdf-name>.<page-number>.png\n"
1423     "  --ppm   - write page images <pdf-name>.<page-number>.ppm\n"
1424     "  --annot - write annotation info <pdf-name>.<page-number>.annot.txt\n"
1425 #ifdef PDF_ENABLE_SKIA
1426     "  --skp   - write page images <pdf-name>.<page-number>.skp\n"
1427 #endif
1428     "  --md5   - write output image paths and their md5 hashes to stdout.\n"
1429     "  --time=<number> - Seconds since the epoch to set system time.\n"
1430     "";
1431 
1432 void SetUpErrorHandling() {
1433 #ifdef _WIN32
1434   // Suppress various Windows error reporting mechanisms that can pop up dialog
1435   // boxes and cause the program to hang.
1436   SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |
1437                SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);
1438   _set_error_mode(_OUT_TO_STDERR);
1439   _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT);
1440   _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_FILE | _CRTDBG_MODE_DEBUG);
1441   _CrtSetReportFile(_CRT_ASSERT, _CRTDBG_FILE_STDERR);
1442 #endif  // _WIN32
1443 }
1444 
1445 }  // namespace
1446 
main(int argc,const char * argv[])1447 int main(int argc, const char* argv[]) {
1448   SetUpErrorHandling();
1449   setlocale(LC_CTYPE, "en_US.UTF-8");  // For printf() of high-characters.
1450 
1451   std::vector<std::string> args(argv, argv + argc);
1452   Options options;
1453   std::vector<std::string> files;
1454   if (!ParseCommandLine(args, &options, &files)) {
1455     fprintf(stderr, "%s", kUsageString);
1456     return 1;
1457   }
1458 
1459   if (options.show_config) {
1460     ShowConfig();
1461     return 0;
1462   }
1463 
1464   if (files.empty()) {
1465     fprintf(stderr, "No input files.\n");
1466     return 1;
1467   }
1468 
1469   const FPDF_RENDERER_TYPE renderer_type =
1470       options.use_renderer_type.value_or(GetDefaultRendererType());
1471 #if defined(PDF_ENABLE_SKIA) && defined(BUILD_WITH_CHROMIUM)
1472   if (renderer_type == FPDF_RENDERERTYPE_SKIA) {
1473     // Needed to support Chromium's copy of Skia, which uses a
1474     // DiscardableMemoryAllocator.
1475     chromium_support::InitializeDiscardableMemoryAllocator();
1476   }
1477 #endif
1478 
1479   FPDF_LIBRARY_CONFIG config;
1480   config.version = 4;
1481   config.m_pUserFontPaths = nullptr;
1482   config.m_pIsolate = nullptr;
1483   config.m_v8EmbedderSlot = 0;
1484   config.m_pPlatform = nullptr;
1485   config.m_RendererType = renderer_type;
1486 
1487   std::function<void()> idler = []() {};
1488 #ifdef PDF_ENABLE_V8
1489 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
1490   v8::StartupData snapshot;
1491 #endif  // V8_USE_EXTERNAL_STARTUP_DATA
1492   std::unique_ptr<v8::Platform> platform;
1493   std::unique_ptr<v8::Isolate, V8IsolateDeleter> isolate;
1494   if (!options.disable_javascript) {
1495 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
1496     platform = InitializeV8ForPDFiumWithStartupData(
1497         options.exe_path, options.js_flags, options.bin_directory, &snapshot);
1498 #else   // V8_USE_EXTERNAL_STARTUP_DATA
1499     platform = InitializeV8ForPDFium(options.exe_path, options.js_flags);
1500 #endif  // V8_USE_EXTERNAL_STARTUP_DATA
1501     if (!platform) {
1502       fprintf(stderr, "V8 initialization failed.\n");
1503       return 1;
1504     }
1505     config.m_pPlatform = platform.get();
1506 
1507     v8::Isolate::CreateParams params;
1508     params.array_buffer_allocator = static_cast<v8::ArrayBuffer::Allocator*>(
1509         FPDF_GetArrayBufferAllocatorSharedInstance());
1510     isolate.reset(v8::Isolate::New(params));
1511     config.m_pIsolate = isolate.get();
1512 
1513     idler = [&platform, &isolate]() {
1514       int task_count = 0;
1515       while (v8::platform::PumpMessageLoop(platform.get(), isolate.get()))
1516         ++task_count;
1517       if (task_count)
1518         fprintf(stderr, "Pumped %d tasks\n", task_count);
1519     };
1520   }
1521 #endif  // PDF_ENABLE_V8
1522 
1523   const char* path_array[2] = {nullptr, nullptr};
1524   absl::optional<const char*> custom_font_path = GetCustomFontPath(options);
1525   if (custom_font_path.has_value()) {
1526     path_array[0] = custom_font_path.value();
1527     config.m_pUserFontPaths = path_array;
1528   }
1529 
1530   FPDF_InitLibraryWithConfig(&config);
1531 
1532   std::unique_ptr<FontRenamer> font_renamer;
1533   if (options.croscore_font_names)
1534     font_renamer = std::make_unique<FontRenamer>();
1535 
1536   UNSUPPORT_INFO unsupported_info = {};
1537   unsupported_info.version = 1;
1538   unsupported_info.FSDK_UnSupport_Handler = ExampleUnsupportedHandler;
1539 
1540   FSDK_SetUnSpObjProcessHandler(&unsupported_info);
1541 
1542   if (options.time > -1) {
1543     // This must be a static var to avoid explicit capture, so the lambda can be
1544     // converted to a function ptr.
1545     static time_t time_ret = options.time;
1546     FSDK_SetTimeFunction([]() { return time_ret; });
1547     FSDK_SetLocaltimeFunction([](const time_t* tp) { return gmtime(tp); });
1548   }
1549 
1550   for (const std::string& filename : files) {
1551     size_t file_length = 0;
1552     std::unique_ptr<char, pdfium::FreeDeleter> file_contents =
1553         GetFileContents(filename.c_str(), &file_length);
1554     if (!file_contents)
1555       continue;
1556     fprintf(stderr, "Processing PDF file %s.\n", filename.c_str());
1557 
1558 #ifdef ENABLE_CALLGRIND
1559     if (options.callgrind_delimiters)
1560       CALLGRIND_START_INSTRUMENTATION;
1561 #endif  // ENABLE_CALLGRIND
1562 
1563     std::string events;
1564     if (options.send_events) {
1565       std::string event_filename = filename;
1566       size_t event_length = 0;
1567       size_t extension_pos = event_filename.find(".pdf");
1568       if (extension_pos != std::string::npos) {
1569         event_filename.replace(extension_pos, 4, ".evt");
1570         if (access(event_filename.c_str(), R_OK) == 0) {
1571           fprintf(stderr, "Using event file %s.\n", event_filename.c_str());
1572           std::unique_ptr<char, pdfium::FreeDeleter> event_contents =
1573               GetFileContents(event_filename.c_str(), &event_length);
1574           if (event_contents) {
1575             fprintf(stderr, "Sending events from: %s\n",
1576                     event_filename.c_str());
1577             events = std::string(event_contents.get(), event_length);
1578           }
1579         }
1580       }
1581     }
1582 
1583     ProcessPdf(filename, file_contents.get(), file_length, options, events,
1584                idler);
1585 
1586 #ifdef ENABLE_CALLGRIND
1587     if (options.callgrind_delimiters)
1588       CALLGRIND_STOP_INSTRUMENTATION;
1589 #endif  // ENABLE_CALLGRIND
1590   }
1591 
1592   FPDF_DestroyLibrary();
1593 
1594 #ifdef PDF_ENABLE_V8
1595   if (!options.disable_javascript) {
1596     isolate.reset();
1597     ShutdownV8ForPDFium();
1598 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
1599     free(const_cast<char*>(snapshot.data));
1600 #endif  // V8_USE_EXTERNAL_STARTUP_DATA
1601   }
1602 #endif  // PDF_ENABLE_V8
1603 
1604   return 0;
1605 }
1606