• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright (c) 2010 The Chromium 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 <limits.h>
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 
10 #include <iterator>
11 #include <map>
12 #include <memory>
13 #include <sstream>
14 #include <string>
15 #include <vector>
16 
17 #if defined PDF_ENABLE_SKIA && !defined _SKIA_SUPPORT_
18 #define _SKIA_SUPPORT_
19 #endif
20 
21 #if defined PDF_ENABLE_SKIA_PATHS && !defined _SKIA_SUPPORT_PATHS_
22 #define _SKIA_SUPPORT_PATHS_
23 #endif
24 
25 #include "public/cpp/fpdf_scopers.h"
26 #include "public/fpdf_annot.h"
27 #include "public/fpdf_attachment.h"
28 #include "public/fpdf_dataavail.h"
29 #include "public/fpdf_edit.h"
30 #include "public/fpdf_ext.h"
31 #include "public/fpdf_formfill.h"
32 #include "public/fpdf_progressive.h"
33 #include "public/fpdf_structtree.h"
34 #include "public/fpdf_text.h"
35 #include "public/fpdfview.h"
36 #include "samples/pdfium_test_dump_helper.h"
37 #include "samples/pdfium_test_event_helper.h"
38 #include "samples/pdfium_test_write_helper.h"
39 #include "testing/fx_string_testhelpers.h"
40 #include "testing/test_loader.h"
41 #include "testing/utils/file_util.h"
42 #include "testing/utils/hash.h"
43 #include "testing/utils/path_service.h"
44 #include "third_party/base/logging.h"
45 #include "third_party/base/optional.h"
46 
47 #ifdef _WIN32
48 #include <io.h>
49 #else
50 #include <unistd.h>
51 #endif
52 
53 #ifdef ENABLE_CALLGRIND
54 #include <valgrind/callgrind.h>
55 #endif  // ENABLE_CALLGRIND
56 
57 #ifdef PDF_ENABLE_V8
58 #include "testing/v8_initializer.h"
59 #include "v8/include/libplatform/libplatform.h"
60 #include "v8/include/v8.h"
61 #endif  // PDF_ENABLE_V8
62 
63 #ifdef _WIN32
64 #define access _access
65 #define snprintf _snprintf
66 #define R_OK 4
67 #endif
68 
69 // wordexp is a POSIX function that is only available on OSX and non-Android
70 // Linux platforms.
71 #if defined(__APPLE__) || (defined(__linux__) && !defined(__ANDROID__))
72 #define WORDEXP_AVAILABLE
73 #endif
74 
75 #ifdef WORDEXP_AVAILABLE
76 #include <wordexp.h>
77 #endif  // WORDEXP_AVAILABLE
78 
79 enum OutputFormat {
80   OUTPUT_NONE,
81   OUTPUT_PAGEINFO,
82   OUTPUT_STRUCTURE,
83   OUTPUT_TEXT,
84   OUTPUT_PPM,
85   OUTPUT_PNG,
86   OUTPUT_ANNOT,
87 #ifdef _WIN32
88   OUTPUT_BMP,
89   OUTPUT_EMF,
90   OUTPUT_PS2,
91   OUTPUT_PS3,
92 #endif
93 #ifdef PDF_ENABLE_SKIA
94   OUTPUT_SKP,
95 #endif
96 };
97 
98 namespace {
99 
100 struct Options {
101   Options() = default;
102 
103   bool show_config = false;
104   bool show_metadata = false;
105   bool send_events = false;
106   bool use_load_mem_document = false;
107   bool render_oneshot = false;
108   bool lcd_text = false;
109   bool no_nativetext = false;
110   bool grayscale = false;
111   bool limit_cache = false;
112   bool force_halftone = false;
113   bool printing = false;
114   bool no_smoothtext = false;
115   bool no_smoothimage = false;
116   bool no_smoothpath = false;
117   bool reverse_byte_order = false;
118   bool save_attachments = false;
119   bool save_images = false;
120   bool save_thumbnails = false;
121   bool save_thumbnails_decoded = false;
122   bool save_thumbnails_raw = false;
123 #ifdef PDF_ENABLE_V8
124   bool disable_javascript = false;
125 #ifdef PDF_ENABLE_XFA
126   bool disable_xfa = false;
127 #endif  // PDF_ENABLE_XFA
128 #endif  // PDF_ENABLE_V8
129   bool pages = false;
130   bool md5 = false;
131 #ifdef ENABLE_CALLGRIND
132   bool callgrind_delimiters = false;
133 #endif
134 #if defined(__APPLE__) || (defined(__linux__) && !defined(__ANDROID__))
135   bool linux_no_system_fonts = false;
136 #endif
137   OutputFormat output_format = OUTPUT_NONE;
138   std::string password;
139   std::string scale_factor_as_string;
140   std::string exe_path;
141   std::string bin_directory;
142   std::string font_directory;
143   int first_page = 0;  // First 0-based page number to renderer.
144   int last_page = 0;   // Last 0-based page number to renderer.
145   time_t time = -1;
146 };
147 
PageRenderFlagsFromOptions(const Options & options)148 int PageRenderFlagsFromOptions(const Options& options) {
149   int flags = FPDF_ANNOT;
150   if (options.lcd_text)
151     flags |= FPDF_LCD_TEXT;
152   if (options.no_nativetext)
153     flags |= FPDF_NO_NATIVETEXT;
154   if (options.grayscale)
155     flags |= FPDF_GRAYSCALE;
156   if (options.limit_cache)
157     flags |= FPDF_RENDER_LIMITEDIMAGECACHE;
158   if (options.force_halftone)
159     flags |= FPDF_RENDER_FORCEHALFTONE;
160   if (options.printing)
161     flags |= FPDF_PRINTING;
162   if (options.no_smoothtext)
163     flags |= FPDF_RENDER_NO_SMOOTHTEXT;
164   if (options.no_smoothimage)
165     flags |= FPDF_RENDER_NO_SMOOTHIMAGE;
166   if (options.no_smoothpath)
167     flags |= FPDF_RENDER_NO_SMOOTHPATH;
168   if (options.reverse_byte_order)
169     flags |= FPDF_REVERSE_BYTE_ORDER;
170   return flags;
171 }
172 
ExpandDirectoryPath(const std::string & path)173 Optional<std::string> ExpandDirectoryPath(const std::string& path) {
174 #if defined(WORDEXP_AVAILABLE)
175   wordexp_t expansion;
176   if (wordexp(path.c_str(), &expansion, 0) != 0 || expansion.we_wordc < 1) {
177     wordfree(&expansion);
178     return {};
179   }
180   // Need to contruct the return value before hand, since wordfree will
181   // deallocate |expansion|.
182   Optional<std::string> ret_val = {expansion.we_wordv[0]};
183   wordfree(&expansion);
184   return ret_val;
185 #else
186   return {path};
187 #endif  // WORDEXP_AVAILABLE
188 }
189 
GetCustomFontPath(const Options & options)190 Optional<const char*> GetCustomFontPath(const Options& options) {
191 #if defined(__APPLE__) || (defined(__linux__) && !defined(__ANDROID__))
192   // Set custom font path to an empty path. This avoids the fallback to default
193   // font paths.
194   if (options.linux_no_system_fonts)
195     return nullptr;
196 #endif
197 
198   // No custom font path. Use default.
199   if (options.font_directory.empty())
200     return pdfium::nullopt;
201 
202   // Set custom font path to |options.font_directory|.
203   return options.font_directory.c_str();
204 }
205 
206 struct FPDF_FORMFILLINFO_PDFiumTest final : public FPDF_FORMFILLINFO {
207   // Hold a map of the currently loaded pages in order to avoid them
208   // to get loaded twice.
209   std::map<int, ScopedFPDFPage> loaded_pages;
210 
211   // Hold a pointer of FPDF_FORMHANDLE so that PDFium app hooks can
212   // make use of it.
213   FPDF_FORMHANDLE form_handle;
214 };
215 
ToPDFiumTestFormFillInfo(FPDF_FORMFILLINFO * form_fill_info)216 FPDF_FORMFILLINFO_PDFiumTest* ToPDFiumTestFormFillInfo(
217     FPDF_FORMFILLINFO* form_fill_info) {
218   return static_cast<FPDF_FORMFILLINFO_PDFiumTest*>(form_fill_info);
219 }
220 
OutputMD5Hash(const char * file_name,const uint8_t * buffer,int len)221 void OutputMD5Hash(const char* file_name, const uint8_t* buffer, int len) {
222   // Get the MD5 hash and write it to stdout.
223   std::string hash = GenerateMD5Base16(buffer, len);
224   printf("MD5:%s:%s\n", file_name, hash.c_str());
225 }
226 
227 #ifdef PDF_ENABLE_V8
228 // These example JS platform callback handlers are entirely optional,
229 // and exist here to show the flow of information from a document back
230 // to the embedder.
ExampleAppAlert(IPDF_JSPLATFORM *,FPDF_WIDESTRING msg,FPDF_WIDESTRING title,int type,int icon)231 int ExampleAppAlert(IPDF_JSPLATFORM*,
232                     FPDF_WIDESTRING msg,
233                     FPDF_WIDESTRING title,
234                     int type,
235                     int icon) {
236   printf("%ls", GetPlatformWString(title).c_str());
237   if (icon || type)
238     printf("[icon=%d,type=%d]", icon, type);
239   printf(": %ls\n", GetPlatformWString(msg).c_str());
240   return 0;
241 }
242 
ExampleAppBeep(IPDF_JSPLATFORM *,int type)243 void ExampleAppBeep(IPDF_JSPLATFORM*, int type) {
244   printf("BEEP!!! %d\n", type);
245 }
246 
ExampleAppResponse(IPDF_JSPLATFORM *,FPDF_WIDESTRING question,FPDF_WIDESTRING title,FPDF_WIDESTRING default_value,FPDF_WIDESTRING label,FPDF_BOOL is_password,void * response,int length)247 int ExampleAppResponse(IPDF_JSPLATFORM*,
248                        FPDF_WIDESTRING question,
249                        FPDF_WIDESTRING title,
250                        FPDF_WIDESTRING default_value,
251                        FPDF_WIDESTRING label,
252                        FPDF_BOOL is_password,
253                        void* response,
254                        int length) {
255   printf("%ls: %ls, defaultValue=%ls, label=%ls, isPassword=%d, length=%d\n",
256          GetPlatformWString(title).c_str(),
257          GetPlatformWString(question).c_str(),
258          GetPlatformWString(default_value).c_str(),
259          GetPlatformWString(label).c_str(), is_password, length);
260 
261   // UTF-16, always LE regardless of platform.
262   auto* ptr = static_cast<uint8_t*>(response);
263   ptr[0] = 'N';
264   ptr[1] = 0;
265   ptr[2] = 'o';
266   ptr[3] = 0;
267   return 4;
268 }
269 
ExampleDocGetFilePath(IPDF_JSPLATFORM *,void * file_path,int length)270 int ExampleDocGetFilePath(IPDF_JSPLATFORM*, void* file_path, int length) {
271   static const char kPath[] = "myfile.pdf";
272   constexpr int kRequired = static_cast<int>(sizeof(kPath));
273   if (file_path && length >= kRequired)
274     memcpy(file_path, kPath, kRequired);
275   return kRequired;
276 }
277 
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)278 void ExampleDocMail(IPDF_JSPLATFORM*,
279                     void* mailData,
280                     int length,
281                     FPDF_BOOL UI,
282                     FPDF_WIDESTRING To,
283                     FPDF_WIDESTRING Subject,
284                     FPDF_WIDESTRING CC,
285                     FPDF_WIDESTRING BCC,
286                     FPDF_WIDESTRING Msg) {
287   printf("Mail Msg: %d, to=%ls, cc=%ls, bcc=%ls, subject=%ls, body=%ls\n", UI,
288          GetPlatformWString(To).c_str(), GetPlatformWString(CC).c_str(),
289          GetPlatformWString(BCC).c_str(), GetPlatformWString(Subject).c_str(),
290          GetPlatformWString(Msg).c_str());
291 }
292 
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)293 void ExampleDocPrint(IPDF_JSPLATFORM*,
294                      FPDF_BOOL bUI,
295                      int nStart,
296                      int nEnd,
297                      FPDF_BOOL bSilent,
298                      FPDF_BOOL bShrinkToFit,
299                      FPDF_BOOL bPrintAsImage,
300                      FPDF_BOOL bReverse,
301                      FPDF_BOOL bAnnotations) {
302   printf("Doc Print: %d, %d, %d, %d, %d, %d, %d, %d\n", bUI, nStart, nEnd,
303          bSilent, bShrinkToFit, bPrintAsImage, bReverse, bAnnotations);
304 }
305 
ExampleDocSubmitForm(IPDF_JSPLATFORM *,void * formData,int length,FPDF_WIDESTRING url)306 void ExampleDocSubmitForm(IPDF_JSPLATFORM*,
307                           void* formData,
308                           int length,
309                           FPDF_WIDESTRING url) {
310   printf("Doc Submit Form: url=%ls + %d data bytes:\n",
311          GetPlatformWString(url).c_str(), length);
312   uint8_t* ptr = reinterpret_cast<uint8_t*>(formData);
313   for (int i = 0; i < length; ++i)
314     printf(" %02x", ptr[i]);
315   printf("\n");
316 }
317 
ExampleDocGotoPage(IPDF_JSPLATFORM *,int page_number)318 void ExampleDocGotoPage(IPDF_JSPLATFORM*, int page_number) {
319   printf("Goto Page: %d\n", page_number);
320 }
321 
ExampleFieldBrowse(IPDF_JSPLATFORM *,void * file_path,int length)322 int ExampleFieldBrowse(IPDF_JSPLATFORM*, void* file_path, int length) {
323   static const char kPath[] = "selected.txt";
324   constexpr int kRequired = static_cast<int>(sizeof(kPath));
325   if (file_path && length >= kRequired)
326     memcpy(file_path, kPath, kRequired);
327   return kRequired;
328 }
329 #endif  // PDF_ENABLE_V8
330 
ExampleUnsupportedHandler(UNSUPPORT_INFO *,int type)331 void ExampleUnsupportedHandler(UNSUPPORT_INFO*, int type) {
332   std::string feature = "Unknown";
333   switch (type) {
334     case FPDF_UNSP_DOC_XFAFORM:
335       feature = "XFA";
336       break;
337     case FPDF_UNSP_DOC_PORTABLECOLLECTION:
338       feature = "Portfolios_Packages";
339       break;
340     case FPDF_UNSP_DOC_ATTACHMENT:
341     case FPDF_UNSP_ANNOT_ATTACHMENT:
342       feature = "Attachment";
343       break;
344     case FPDF_UNSP_DOC_SECURITY:
345       feature = "Rights_Management";
346       break;
347     case FPDF_UNSP_DOC_SHAREDREVIEW:
348       feature = "Shared_Review";
349       break;
350     case FPDF_UNSP_DOC_SHAREDFORM_ACROBAT:
351     case FPDF_UNSP_DOC_SHAREDFORM_FILESYSTEM:
352     case FPDF_UNSP_DOC_SHAREDFORM_EMAIL:
353       feature = "Shared_Form";
354       break;
355     case FPDF_UNSP_ANNOT_3DANNOT:
356       feature = "3D";
357       break;
358     case FPDF_UNSP_ANNOT_MOVIE:
359       feature = "Movie";
360       break;
361     case FPDF_UNSP_ANNOT_SOUND:
362       feature = "Sound";
363       break;
364     case FPDF_UNSP_ANNOT_SCREEN_MEDIA:
365     case FPDF_UNSP_ANNOT_SCREEN_RICHMEDIA:
366       feature = "Screen";
367       break;
368     case FPDF_UNSP_ANNOT_SIG:
369       feature = "Digital_Signature";
370       break;
371   }
372   printf("Unsupported feature: %s.\n", feature.c_str());
373 }
374 
375 // |arg| is expected to be "--key=value", and |key| is "--key=".
ParseSwitchKeyValue(const std::string & arg,const std::string & key,std::string * value)376 bool ParseSwitchKeyValue(const std::string& arg,
377                          const std::string& key,
378                          std::string* value) {
379   if (arg.size() <= key.size() || arg.compare(0, key.size(), key) != 0)
380     return false;
381 
382   *value = arg.substr(key.size());
383   return true;
384 }
385 
ParseCommandLine(const std::vector<std::string> & args,Options * options,std::vector<std::string> * files)386 bool ParseCommandLine(const std::vector<std::string>& args,
387                       Options* options,
388                       std::vector<std::string>* files) {
389   if (args.empty())
390     return false;
391 
392   options->exe_path = args[0];
393   size_t cur_idx = 1;
394   std::string value;
395   for (; cur_idx < args.size(); ++cur_idx) {
396     const std::string& cur_arg = args[cur_idx];
397     if (cur_arg == "--show-config") {
398       options->show_config = true;
399     } else if (cur_arg == "--show-metadata") {
400       options->show_metadata = true;
401     } else if (cur_arg == "--send-events") {
402       options->send_events = true;
403     } else if (cur_arg == "--mem-document") {
404       options->use_load_mem_document = true;
405     } else if (cur_arg == "--render-oneshot") {
406       options->render_oneshot = true;
407     } else if (cur_arg == "--lcd-text") {
408       options->lcd_text = true;
409     } else if (cur_arg == "--no-nativetext") {
410       options->no_nativetext = true;
411     } else if (cur_arg == "--grayscale") {
412       options->grayscale = true;
413     } else if (cur_arg == "--limit-cache") {
414       options->limit_cache = true;
415     } else if (cur_arg == "--force-halftone") {
416       options->force_halftone = true;
417     } else if (cur_arg == "--printing") {
418       options->printing = true;
419     } else if (cur_arg == "--no-smoothtext") {
420       options->no_smoothtext = true;
421     } else if (cur_arg == "--no-smoothimage") {
422       options->no_smoothimage = true;
423     } else if (cur_arg == "--no-smoothpath") {
424       options->no_smoothpath = true;
425     } else if (cur_arg == "--reverse-byte-order") {
426       options->reverse_byte_order = true;
427     } else if (cur_arg == "--save-attachments") {
428       options->save_attachments = true;
429     } else if (cur_arg == "--save-images") {
430       options->save_images = true;
431     } else if (cur_arg == "--save-thumbs") {
432       options->save_thumbnails = true;
433     } else if (cur_arg == "--save-thumbs-dec") {
434       options->save_thumbnails_decoded = true;
435     } else if (cur_arg == "--save-thumbs-raw") {
436       options->save_thumbnails_raw = true;
437 #ifdef PDF_ENABLE_V8
438     } else if (cur_arg == "--disable-javascript") {
439       options->disable_javascript = true;
440 #ifdef PDF_ENABLE_XFA
441     } else if (cur_arg == "--disable-xfa") {
442       options->disable_xfa = true;
443 #endif  // PDF_ENABLE_XFA
444 #endif  // PDF_ENABLE_V8
445 #ifdef ENABLE_CALLGRIND
446     } else if (cur_arg == "--callgrind-delim") {
447       options->callgrind_delimiters = true;
448 #endif
449 #if defined(__APPLE__) || (defined(__linux__) && !defined(__ANDROID__))
450     } else if (cur_arg == "--no-system-fonts") {
451       options->linux_no_system_fonts = true;
452 #endif
453     } else if (cur_arg == "--ppm") {
454       if (options->output_format != OUTPUT_NONE) {
455         fprintf(stderr, "Duplicate or conflicting --ppm argument\n");
456         return false;
457       }
458       options->output_format = OUTPUT_PPM;
459     } else if (cur_arg == "--png") {
460       if (options->output_format != OUTPUT_NONE) {
461         fprintf(stderr, "Duplicate or conflicting --png argument\n");
462         return false;
463       }
464       options->output_format = OUTPUT_PNG;
465     } else if (cur_arg == "--txt") {
466       if (options->output_format != OUTPUT_NONE) {
467         fprintf(stderr, "Duplicate or conflicting --txt argument\n");
468         return false;
469       }
470       options->output_format = OUTPUT_TEXT;
471     } else if (cur_arg == "--annot") {
472       if (options->output_format != OUTPUT_NONE) {
473         fprintf(stderr, "Duplicate or conflicting --annot argument\n");
474         return false;
475       }
476       options->output_format = OUTPUT_ANNOT;
477 #ifdef PDF_ENABLE_SKIA
478     } else if (cur_arg == "--skp") {
479       if (options->output_format != OUTPUT_NONE) {
480         fprintf(stderr, "Duplicate or conflicting --skp argument\n");
481         return false;
482       }
483       options->output_format = OUTPUT_SKP;
484 #endif  // PDF_ENABLE_SKIA
485     } else if (ParseSwitchKeyValue(cur_arg, "--font-dir=", &value)) {
486       if (!options->font_directory.empty()) {
487         fprintf(stderr, "Duplicate --font-dir argument\n");
488         return false;
489       }
490       std::string path = value;
491       auto expanded_path = ExpandDirectoryPath(path);
492       if (!expanded_path) {
493         fprintf(stderr, "Failed to expand --font-dir, %s\n", path.c_str());
494         return false;
495       }
496 
497       if (!PathService::DirectoryExists(expanded_path.value())) {
498         fprintf(stderr, "--font-dir, %s, appears to not be a directory\n",
499                 path.c_str());
500         return false;
501       }
502 
503       options->font_directory = expanded_path.value();
504 
505 #ifdef _WIN32
506     } else if (cur_arg == "--emf") {
507       if (options->output_format != OUTPUT_NONE) {
508         fprintf(stderr, "Duplicate or conflicting --emf argument\n");
509         return false;
510       }
511       options->output_format = OUTPUT_EMF;
512     } else if (cur_arg == "--ps2") {
513       if (options->output_format != OUTPUT_NONE) {
514         fprintf(stderr, "Duplicate or conflicting --ps2 argument\n");
515         return false;
516       }
517       options->output_format = OUTPUT_PS2;
518     } else if (cur_arg == "--ps3") {
519       if (options->output_format != OUTPUT_NONE) {
520         fprintf(stderr, "Duplicate or conflicting --ps3 argument\n");
521         return false;
522       }
523       options->output_format = OUTPUT_PS3;
524     } else if (cur_arg == "--bmp") {
525       if (options->output_format != OUTPUT_NONE) {
526         fprintf(stderr, "Duplicate or conflicting --bmp argument\n");
527         return false;
528       }
529       options->output_format = OUTPUT_BMP;
530 #endif  // _WIN32
531 
532 #ifdef PDF_ENABLE_V8
533 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
534     } else if (ParseSwitchKeyValue(cur_arg, "--bin-dir=", &value)) {
535       if (!options->bin_directory.empty()) {
536         fprintf(stderr, "Duplicate --bin-dir argument\n");
537         return false;
538       }
539       std::string path = value;
540       auto expanded_path = ExpandDirectoryPath(path);
541       if (!expanded_path) {
542         fprintf(stderr, "Failed to expand --bin-dir, %s\n", path.c_str());
543         return false;
544       }
545       options->bin_directory = expanded_path.value();
546 #endif  // V8_USE_EXTERNAL_STARTUP_DATA
547 #endif  // PDF_ENABLE_V8
548 
549     } else if (ParseSwitchKeyValue(cur_arg, "--password=", &value)) {
550       if (!options->password.empty()) {
551         fprintf(stderr, "Duplicate --password argument\n");
552         return false;
553       }
554       options->password = value;
555     } else if (ParseSwitchKeyValue(cur_arg, "--scale=", &value)) {
556       if (!options->scale_factor_as_string.empty()) {
557         fprintf(stderr, "Duplicate --scale argument\n");
558         return false;
559       }
560       options->scale_factor_as_string = value;
561     } else if (cur_arg == "--show-pageinfo") {
562       if (options->output_format != OUTPUT_NONE) {
563         fprintf(stderr, "Duplicate or conflicting --show-pageinfo argument\n");
564         return false;
565       }
566       options->output_format = OUTPUT_PAGEINFO;
567     } else if (cur_arg == "--show-structure") {
568       if (options->output_format != OUTPUT_NONE) {
569         fprintf(stderr, "Duplicate or conflicting --show-structure argument\n");
570         return false;
571       }
572       options->output_format = OUTPUT_STRUCTURE;
573     } else if (ParseSwitchKeyValue(cur_arg, "--pages=", &value)) {
574       if (options->pages) {
575         fprintf(stderr, "Duplicate --pages argument\n");
576         return false;
577       }
578       options->pages = true;
579       const std::string pages_string = value;
580       size_t first_dash = pages_string.find("-");
581       if (first_dash == std::string::npos) {
582         std::stringstream(pages_string) >> options->first_page;
583         options->last_page = options->first_page;
584       } else {
585         std::stringstream(pages_string.substr(0, first_dash)) >>
586             options->first_page;
587         std::stringstream(pages_string.substr(first_dash + 1)) >>
588             options->last_page;
589       }
590     } else if (cur_arg == "--md5") {
591       options->md5 = true;
592     } else if (ParseSwitchKeyValue(cur_arg, "--time=", &value)) {
593       if (options->time > -1) {
594         fprintf(stderr, "Duplicate --time argument\n");
595         return false;
596       }
597       const std::string time_string = value;
598       std::stringstream(time_string) >> options->time;
599       if (options->time < 0) {
600         fprintf(stderr, "Invalid --time argument, must be non-negative\n");
601         return false;
602       }
603     } else if (cur_arg.size() >= 2 && cur_arg[0] == '-' && cur_arg[1] == '-') {
604       fprintf(stderr, "Unrecognized argument %s\n", cur_arg.c_str());
605       return false;
606     } else {
607       break;
608     }
609   }
610   for (size_t i = cur_idx; i < args.size(); i++)
611     files->push_back(args[i]);
612 
613   return true;
614 }
615 
PrintLastError()616 void PrintLastError() {
617   unsigned long err = FPDF_GetLastError();
618   fprintf(stderr, "Load pdf docs unsuccessful: ");
619   switch (err) {
620     case FPDF_ERR_SUCCESS:
621       fprintf(stderr, "Success");
622       break;
623     case FPDF_ERR_UNKNOWN:
624       fprintf(stderr, "Unknown error");
625       break;
626     case FPDF_ERR_FILE:
627       fprintf(stderr, "File not found or could not be opened");
628       break;
629     case FPDF_ERR_FORMAT:
630       fprintf(stderr, "File not in PDF format or corrupted");
631       break;
632     case FPDF_ERR_PASSWORD:
633       fprintf(stderr, "Password required or incorrect password");
634       break;
635     case FPDF_ERR_SECURITY:
636       fprintf(stderr, "Unsupported security scheme");
637       break;
638     case FPDF_ERR_PAGE:
639       fprintf(stderr, "Page not found or content error");
640       break;
641     default:
642       fprintf(stderr, "Unknown error %ld", err);
643   }
644   fprintf(stderr, ".\n");
645 }
646 
Is_Data_Avail(FX_FILEAVAIL * avail,size_t offset,size_t size)647 FPDF_BOOL Is_Data_Avail(FX_FILEAVAIL* avail, size_t offset, size_t size) {
648   return true;
649 }
650 
Add_Segment(FX_DOWNLOADHINTS * hints,size_t offset,size_t size)651 void Add_Segment(FX_DOWNLOADHINTS* hints, size_t offset, size_t size) {}
652 
GetPageForIndex(FPDF_FORMFILLINFO * param,FPDF_DOCUMENT doc,int index)653 FPDF_PAGE GetPageForIndex(FPDF_FORMFILLINFO* param,
654                           FPDF_DOCUMENT doc,
655                           int index) {
656   FPDF_FORMFILLINFO_PDFiumTest* form_fill_info =
657       ToPDFiumTestFormFillInfo(param);
658   auto& loaded_pages = form_fill_info->loaded_pages;
659   auto iter = loaded_pages.find(index);
660   if (iter != loaded_pages.end())
661     return iter->second.get();
662 
663   ScopedFPDFPage page(FPDF_LoadPage(doc, index));
664   if (!page)
665     return nullptr;
666 
667   // Mark the page as loaded first to prevent infinite recursion.
668   FPDF_PAGE page_ptr = page.get();
669   loaded_pages[index] = std::move(page);
670 
671   FPDF_FORMHANDLE& form_handle = form_fill_info->form_handle;
672   FORM_OnAfterLoadPage(page_ptr, form_handle);
673   FORM_DoPageAAction(page_ptr, form_handle, FPDFPAGE_AACTION_OPEN);
674   return page_ptr;
675 }
676 
677 // Note, for a client using progressive rendering you'd want to determine if you
678 // need the rendering to pause instead of always saying |true|. This is for
679 // testing to force the renderer to break whenever possible.
NeedToPauseNow(IFSDK_PAUSE * p)680 FPDF_BOOL NeedToPauseNow(IFSDK_PAUSE* p) {
681   return true;
682 }
683 
RenderPage(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)684 bool RenderPage(const std::string& name,
685                 FPDF_DOCUMENT doc,
686                 FPDF_FORMHANDLE form,
687                 FPDF_FORMFILLINFO_PDFiumTest* form_fill_info,
688                 const int page_index,
689                 const Options& options,
690                 const std::string& events) {
691   FPDF_PAGE page = GetPageForIndex(form_fill_info, doc, page_index);
692   if (!page)
693     return false;
694   if (options.send_events)
695     SendPageEvents(form, page, events);
696   if (options.save_images)
697     WriteImages(page, name.c_str(), page_index);
698   if (options.save_thumbnails)
699     WriteThumbnail(page, name.c_str(), page_index);
700   if (options.save_thumbnails_decoded)
701     WriteDecodedThumbnailStream(page, name.c_str(), page_index);
702   if (options.save_thumbnails_raw)
703     WriteRawThumbnailStream(page, name.c_str(), page_index);
704   if (options.output_format == OUTPUT_PAGEINFO) {
705     DumpPageInfo(page, page_index);
706     return true;
707   }
708   if (options.output_format == OUTPUT_STRUCTURE) {
709     DumpPageStructure(page, page_index);
710     return true;
711   }
712 
713   ScopedFPDFTextPage text_page(FPDFText_LoadPage(page));
714   double scale = 1.0;
715   if (!options.scale_factor_as_string.empty())
716     std::stringstream(options.scale_factor_as_string) >> scale;
717 
718   auto width = static_cast<int>(FPDF_GetPageWidthF(page) * scale);
719   auto height = static_cast<int>(FPDF_GetPageHeightF(page) * scale);
720   int alpha = FPDFPage_HasTransparency(page) ? 1 : 0;
721   ScopedFPDFBitmap bitmap(FPDFBitmap_Create(width, height, alpha));
722 
723   if (bitmap) {
724     FPDF_DWORD fill_color = alpha ? 0x00000000 : 0xFFFFFFFF;
725     FPDFBitmap_FillRect(bitmap.get(), 0, 0, width, height, fill_color);
726 
727     int flags = PageRenderFlagsFromOptions(options);
728     if (options.render_oneshot) {
729       // Note, client programs probably want to use this method instead of the
730       // progressive calls. The progressive calls are if you need to pause the
731       // rendering to update the UI, the PDF renderer will break when possible.
732       FPDF_RenderPageBitmap(bitmap.get(), page, 0, 0, width, height, 0, flags);
733     } else {
734       IFSDK_PAUSE pause;
735       pause.version = 1;
736       pause.NeedToPauseNow = &NeedToPauseNow;
737 
738       int rv = FPDF_RenderPageBitmap_Start(bitmap.get(), page, 0, 0, width,
739                                            height, 0, flags, &pause);
740       while (rv == FPDF_RENDER_TOBECONTINUED)
741         rv = FPDF_RenderPage_Continue(page, &pause);
742     }
743 
744     FPDF_FFLDraw(form, bitmap.get(), page, 0, 0, width, height, 0, flags);
745 
746     if (!options.render_oneshot)
747       FPDF_RenderPage_Close(page);
748 
749     int stride = FPDFBitmap_GetStride(bitmap.get());
750     void* buffer = FPDFBitmap_GetBuffer(bitmap.get());
751 
752     std::string image_file_name;
753     switch (options.output_format) {
754 #ifdef _WIN32
755       case OUTPUT_BMP:
756         image_file_name =
757             WriteBmp(name.c_str(), page_index, buffer, stride, width, height);
758         break;
759 
760       case OUTPUT_EMF:
761         WriteEmf(page, name.c_str(), page_index);
762         break;
763 
764       case OUTPUT_PS2:
765       case OUTPUT_PS3:
766         WritePS(page, name.c_str(), page_index);
767         break;
768 #endif
769       case OUTPUT_TEXT:
770         WriteText(page, name.c_str(), page_index);
771         break;
772 
773       case OUTPUT_ANNOT:
774         WriteAnnot(page, name.c_str(), page_index);
775         break;
776 
777       case OUTPUT_PNG:
778         image_file_name =
779             WritePng(name.c_str(), page_index, buffer, stride, width, height);
780         break;
781 
782       case OUTPUT_PPM:
783         image_file_name =
784             WritePpm(name.c_str(), page_index, buffer, stride, width, height);
785         break;
786 
787 #ifdef PDF_ENABLE_SKIA
788       case OUTPUT_SKP: {
789         std::unique_ptr<SkPictureRecorder> recorder(
790             reinterpret_cast<SkPictureRecorder*>(
791                 FPDF_RenderPageSkp(page, width, height)));
792         FPDF_FFLRecord(form, recorder.get(), page, 0, 0, width, height, 0, 0);
793         image_file_name = WriteSkp(name.c_str(), page_index, recorder.get());
794       } break;
795 #endif
796       default:
797         break;
798     }
799 
800     // Write the filename and the MD5 of the buffer to stdout if we wrote a
801     // file.
802     if (options.md5 && !image_file_name.empty()) {
803       OutputMD5Hash(image_file_name.c_str(),
804                     static_cast<const uint8_t*>(buffer), stride * height);
805     }
806   } else {
807     fprintf(stderr, "Page was too large to be rendered.\n");
808   }
809 
810   FORM_DoPageAAction(page, form, FPDFPAGE_AACTION_CLOSE);
811   FORM_OnBeforeClosePage(page, form);
812   return !!bitmap;
813 }
814 
RenderPdf(const std::string & name,const char * buf,size_t len,const Options & options,const std::string & events)815 void RenderPdf(const std::string& name,
816                const char* buf,
817                size_t len,
818                const Options& options,
819                const std::string& events) {
820   TestLoader loader({buf, len});
821 
822   FPDF_FILEACCESS file_access = {};
823   file_access.m_FileLen = static_cast<unsigned long>(len);
824   file_access.m_GetBlock = TestLoader::GetBlock;
825   file_access.m_Param = &loader;
826 
827   FX_FILEAVAIL file_avail = {};
828   file_avail.version = 1;
829   file_avail.IsDataAvail = Is_Data_Avail;
830 
831   FX_DOWNLOADHINTS hints = {};
832   hints.version = 1;
833   hints.AddSegment = Add_Segment;
834 
835   // |pdf_avail| must outlive |doc|.
836   ScopedFPDFAvail pdf_avail(FPDFAvail_Create(&file_avail, &file_access));
837 
838   // |doc| must outlive |form_callbacks.loaded_pages|.
839   ScopedFPDFDocument doc;
840 
841   const char* password =
842       options.password.empty() ? nullptr : options.password.c_str();
843   bool is_linearized = false;
844   if (options.use_load_mem_document) {
845     doc.reset(FPDF_LoadMemDocument(buf, len, password));
846   } else {
847     if (FPDFAvail_IsLinearized(pdf_avail.get()) == PDF_LINEARIZED) {
848       int avail_status = PDF_DATA_NOTAVAIL;
849       doc.reset(FPDFAvail_GetDocument(pdf_avail.get(), password));
850       if (doc) {
851         while (avail_status == PDF_DATA_NOTAVAIL)
852           avail_status = FPDFAvail_IsDocAvail(pdf_avail.get(), &hints);
853 
854         if (avail_status == PDF_DATA_ERROR) {
855           fprintf(stderr, "Unknown error in checking if doc was available.\n");
856           return;
857         }
858         avail_status = FPDFAvail_IsFormAvail(pdf_avail.get(), &hints);
859         if (avail_status == PDF_FORM_ERROR ||
860             avail_status == PDF_FORM_NOTAVAIL) {
861           fprintf(stderr,
862                   "Error %d was returned in checking if form was available.\n",
863                   avail_status);
864           return;
865         }
866         is_linearized = true;
867       }
868     } else {
869       doc.reset(FPDF_LoadCustomDocument(&file_access, password));
870     }
871   }
872 
873   if (!doc) {
874     PrintLastError();
875     return;
876   }
877 
878   if (!FPDF_DocumentHasValidCrossReferenceTable(doc.get()))
879     fprintf(stderr, "Document has invalid cross reference table\n");
880 
881   (void)FPDF_GetDocPermissions(doc.get());
882 
883   if (options.show_metadata)
884     DumpMetaData(doc.get());
885 
886   if (options.save_attachments)
887     WriteAttachments(doc.get(), name);
888 
889 #ifdef PDF_ENABLE_V8
890   IPDF_JSPLATFORM platform_callbacks = {};
891   platform_callbacks.version = 3;
892   platform_callbacks.app_alert = ExampleAppAlert;
893   platform_callbacks.app_beep = ExampleAppBeep;
894   platform_callbacks.app_response = ExampleAppResponse;
895   platform_callbacks.Doc_getFilePath = ExampleDocGetFilePath;
896   platform_callbacks.Doc_mail = ExampleDocMail;
897   platform_callbacks.Doc_print = ExampleDocPrint;
898   platform_callbacks.Doc_submitForm = ExampleDocSubmitForm;
899   platform_callbacks.Doc_gotoPage = ExampleDocGotoPage;
900   platform_callbacks.Field_browse = ExampleFieldBrowse;
901 #endif  // PDF_ENABLE_V8
902 
903   FPDF_FORMFILLINFO_PDFiumTest form_callbacks = {};
904 #ifdef PDF_ENABLE_XFA
905   form_callbacks.version = 2;
906   form_callbacks.xfa_disabled =
907       options.disable_xfa || options.disable_javascript;
908 #else   // PDF_ENABLE_XFA
909   form_callbacks.version = 1;
910 #endif  // PDF_ENABLE_XFA
911   form_callbacks.FFI_GetPage = GetPageForIndex;
912 
913 #ifdef PDF_ENABLE_V8
914   if (!options.disable_javascript)
915     form_callbacks.m_pJsPlatform = &platform_callbacks;
916 #endif  // PDF_ENABLE_V8
917 
918   ScopedFPDFFormHandle form(
919       FPDFDOC_InitFormFillEnvironment(doc.get(), &form_callbacks));
920   form_callbacks.form_handle = form.get();
921 
922 #ifdef PDF_ENABLE_XFA
923   if (!options.disable_xfa && !options.disable_javascript) {
924     int doc_type = FPDF_GetFormType(doc.get());
925     if (doc_type == FORMTYPE_XFA_FULL || doc_type == FORMTYPE_XFA_FOREGROUND) {
926       if (!FPDF_LoadXFA(doc.get()))
927         fprintf(stderr, "LoadXFA unsuccessful, continuing anyway.\n");
928     }
929   }
930 #endif  // PDF_ENABLE_XFA
931 
932   FPDF_SetFormFieldHighlightColor(form.get(), FPDF_FORMFIELD_UNKNOWN, 0xFFE4DD);
933   FPDF_SetFormFieldHighlightAlpha(form.get(), 100);
934   FORM_DoDocumentJSAction(form.get());
935   FORM_DoDocumentOpenAction(form.get());
936 
937 #if _WIN32
938   if (options.output_format == OUTPUT_PS2)
939     FPDF_SetPrintMode(FPDF_PRINTMODE_POSTSCRIPT2);
940   else if (options.output_format == OUTPUT_PS3)
941     FPDF_SetPrintMode(FPDF_PRINTMODE_POSTSCRIPT3);
942 #endif
943 
944   int page_count = FPDF_GetPageCount(doc.get());
945   int rendered_pages = 0;
946   int bad_pages = 0;
947   int first_page = options.pages ? options.first_page : 0;
948   int last_page = options.pages ? options.last_page + 1 : page_count;
949   for (int i = first_page; i < last_page; ++i) {
950     if (is_linearized) {
951       int avail_status = PDF_DATA_NOTAVAIL;
952       while (avail_status == PDF_DATA_NOTAVAIL)
953         avail_status = FPDFAvail_IsPageAvail(pdf_avail.get(), i, &hints);
954 
955       if (avail_status == PDF_DATA_ERROR) {
956         fprintf(stderr, "Unknown error in checking if page %d is available.\n",
957                 i);
958         return;
959       }
960     }
961     if (RenderPage(name, doc.get(), form.get(), &form_callbacks, i, options,
962                    events)) {
963       ++rendered_pages;
964     } else {
965       ++bad_pages;
966     }
967   }
968 
969   FORM_DoDocumentAAction(form.get(), FPDFDOC_AACTION_WC);
970   fprintf(stderr, "Rendered %d pages.\n", rendered_pages);
971   if (bad_pages)
972     fprintf(stderr, "Skipped %d bad pages.\n", bad_pages);
973 }
974 
ShowConfig()975 void ShowConfig() {
976   std::string config;
977   std::string maybe_comma;
978 #ifdef PDF_ENABLE_V8
979   config.append(maybe_comma);
980   config.append("V8");
981   maybe_comma = ",";
982 #endif  // PDF_ENABLE_V8
983 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
984   config.append(maybe_comma);
985   config.append("V8_EXTERNAL");
986   maybe_comma = ",";
987 #endif  // V8_USE_EXTERNAL_STARTUP_DATA
988 #ifdef PDF_ENABLE_XFA
989   config.append(maybe_comma);
990   config.append("XFA");
991   maybe_comma = ",";
992 #endif  // PDF_ENABLE_XFA
993 #ifdef PDF_ENABLE_ASAN
994   config.append(maybe_comma);
995   config.append("ASAN");
996   maybe_comma = ",";
997 #endif  // PDF_ENABLE_ASAN
998 #if defined(PDF_ENABLE_SKIA)
999   config.append(maybe_comma);
1000   config.append("SKIA");
1001   maybe_comma = ",";
1002 #elif defined(PDF_ENABLE_SKIA_PATHS)
1003   config.append(maybe_comma);
1004   config.append("SKIAPATHS");
1005   maybe_comma = ",";
1006 #endif
1007   printf("%s\n", config.c_str());
1008 }
1009 
1010 constexpr char kUsageString[] =
1011     "Usage: pdfium_test [OPTION] [FILE]...\n"
1012     "  --show-config        - print build options and exit\n"
1013     "  --show-metadata      - print the file metadata\n"
1014     "  --show-pageinfo      - print information about pages\n"
1015     "  --show-structure     - print the structure elements from the document\n"
1016     "  --send-events        - send input described by .evt file\n"
1017     "  --mem-document       - load document with FPDF_LoadMemDocument()\n"
1018     "  --render-oneshot     - render image without using progressive renderer\n"
1019     "  --lcd-text           - render text optimized for LCD displays\n"
1020     "  --no-nativetext      - render without using the native text output\n"
1021     "  --grayscale          - render grayscale output\n"
1022     "  --limit-cache        - render limiting image cache size\n"
1023     "  --force-halftone     - render forcing halftone\n"
1024     "  --printing           - render as if for printing\n"
1025     "  --no-smoothtext      - render disabling text anti-aliasing\n"
1026     "  --no-smoothimage     - render disabling image anti-alisasing\n"
1027     "  --no-smoothpath      - render disabling path anti-aliasing\n"
1028     "  --reverse-byte-order - render to BGRA, if supported by the output "
1029     "format\n"
1030     "  --save-attachments   - write embedded attachments "
1031     "<pdf-name>.attachment.<attachment-name>\n"
1032     "  --save-images        - write embedded images "
1033     "<pdf-name>.<page-number>.<object-number>.png\n"
1034     "  --save-thumbs        - write page thumbnails "
1035     "<pdf-name>.thumbnail.<page-number>.png\n"
1036     "  --save-thumbs-dec    - write page thumbnails' decoded stream data"
1037     "<pdf-name>.thumbnail.decoded.<page-number>.png\n"
1038     "  --save-thumbs-raw    - write page thumbnails' raw stream data"
1039     "<pdf-name>.thumbnail.raw.<page-number>.png\n"
1040 #ifdef PDF_ENABLE_V8
1041     "  --disable-javascript - do not execute JS in PDF files\n"
1042 #ifdef PDF_ENABLE_XFA
1043     "  --disable-xfa        - do not process XFA forms\n"
1044 #endif  // PDF_ENABLE_XFA
1045 #endif  // PDF_ENABLE_V8
1046 #ifdef ENABLE_CALLGRIND
1047     "  --callgrind-delim    - delimit interesting section when using "
1048     "callgrind\n"
1049 #endif
1050 #if defined(__APPLE__) || (defined(__linux__) && !defined(__ANDROID__))
1051     "  --no-system-fonts    - do not use system fonts, overrides --font-dir\n"
1052 #endif
1053     "  --bin-dir=<path>     - override path to v8 external data\n"
1054     "  --font-dir=<path>    - override path to external fonts\n"
1055     "  --scale=<number>     - scale output size by number (e.g. 0.5)\n"
1056     "  --pages=<number>(-<number>) - only render the given 0-based page(s)\n"
1057 #ifdef _WIN32
1058     "  --bmp   - write page images <pdf-name>.<page-number>.bmp\n"
1059     "  --emf   - write page meta files <pdf-name>.<page-number>.emf\n"
1060     "  --ps2   - write page raw PostScript (Lvl 2) "
1061     "<pdf-name>.<page-number>.ps\n"
1062     "  --ps3   - write page raw PostScript (Lvl 3) "
1063     "<pdf-name>.<page-number>.ps\n"
1064 #endif
1065     "  --txt   - write page text in UTF32-LE <pdf-name>.<page-number>.txt\n"
1066     "  --png   - write page images <pdf-name>.<page-number>.png\n"
1067     "  --ppm   - write page images <pdf-name>.<page-number>.ppm\n"
1068     "  --annot - write annotation info <pdf-name>.<page-number>.annot.txt\n"
1069 #ifdef PDF_ENABLE_SKIA
1070     "  --skp   - write page images <pdf-name>.<page-number>.skp\n"
1071 #endif
1072     "  --md5   - write output image paths and their md5 hashes to stdout.\n"
1073     "  --time=<number> - Seconds since the epoch to set system time.\n"
1074     "";
1075 
1076 }  // namespace
1077 
main(int argc,const char * argv[])1078 int main(int argc, const char* argv[]) {
1079   std::vector<std::string> args(argv, argv + argc);
1080   Options options;
1081   std::vector<std::string> files;
1082   if (!ParseCommandLine(args, &options, &files)) {
1083     fprintf(stderr, "%s", kUsageString);
1084     return 1;
1085   }
1086 
1087   if (options.show_config) {
1088     ShowConfig();
1089     return 0;
1090   }
1091 
1092   if (files.empty()) {
1093     fprintf(stderr, "No input files.\n");
1094     return 1;
1095   }
1096 
1097 #ifdef PDF_ENABLE_V8
1098   std::unique_ptr<v8::Platform> platform;
1099 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
1100   v8::StartupData snapshot;
1101   if (!options.disable_javascript) {
1102     platform = InitializeV8ForPDFiumWithStartupData(
1103         options.exe_path, options.bin_directory, &snapshot);
1104   }
1105 #else   // V8_USE_EXTERNAL_STARTUP_DATA
1106   if (!options.disable_javascript)
1107     platform = InitializeV8ForPDFium(options.exe_path);
1108 #endif  // V8_USE_EXTERNAL_STARTUP_DATA
1109 #endif  // PDF_ENABLE_V8
1110 
1111   FPDF_LIBRARY_CONFIG config;
1112   config.version = 2;
1113   config.m_pUserFontPaths = nullptr;
1114   config.m_pIsolate = nullptr;
1115   config.m_v8EmbedderSlot = 0;
1116 
1117   const char* path_array[2] = {nullptr, nullptr};
1118   Optional<const char*> custom_font_path = GetCustomFontPath(options);
1119   if (custom_font_path.has_value()) {
1120     path_array[0] = custom_font_path.value();
1121     config.m_pUserFontPaths = path_array;
1122   }
1123 
1124   FPDF_InitLibraryWithConfig(&config);
1125 
1126   UNSUPPORT_INFO unsupported_info = {};
1127   unsupported_info.version = 1;
1128   unsupported_info.FSDK_UnSupport_Handler = ExampleUnsupportedHandler;
1129 
1130   FSDK_SetUnSpObjProcessHandler(&unsupported_info);
1131 
1132   if (options.time > -1) {
1133     // This must be a static var to avoid explicit capture, so the lambda can be
1134     // converted to a function ptr.
1135     static time_t time_ret = options.time;
1136     FSDK_SetTimeFunction([]() { return time_ret; });
1137     FSDK_SetLocaltimeFunction([](const time_t* tp) { return gmtime(tp); });
1138   }
1139 
1140   for (const std::string& filename : files) {
1141     size_t file_length = 0;
1142     std::unique_ptr<char, pdfium::FreeDeleter> file_contents =
1143         GetFileContents(filename.c_str(), &file_length);
1144     if (!file_contents)
1145       continue;
1146     fprintf(stderr, "Rendering PDF file %s.\n", filename.c_str());
1147 
1148 #ifdef ENABLE_CALLGRIND
1149     if (options.callgrind_delimiters)
1150       CALLGRIND_START_INSTRUMENTATION;
1151 #endif  // ENABLE_CALLGRIND
1152 
1153     std::string events;
1154     if (options.send_events) {
1155       std::string event_filename = filename;
1156       size_t event_length = 0;
1157       size_t extension_pos = event_filename.find(".pdf");
1158       if (extension_pos != std::string::npos) {
1159         event_filename.replace(extension_pos, 4, ".evt");
1160         if (access(event_filename.c_str(), R_OK) == 0) {
1161           fprintf(stderr, "Using event file %s.\n", event_filename.c_str());
1162           std::unique_ptr<char, pdfium::FreeDeleter> event_contents =
1163               GetFileContents(event_filename.c_str(), &event_length);
1164           if (event_contents) {
1165             fprintf(stderr, "Sending events from: %s\n",
1166                     event_filename.c_str());
1167             events = std::string(event_contents.get(), event_length);
1168           }
1169         }
1170       }
1171     }
1172     RenderPdf(filename, file_contents.get(), file_length, options, events);
1173 
1174 #ifdef ENABLE_CALLGRIND
1175     if (options.callgrind_delimiters)
1176       CALLGRIND_STOP_INSTRUMENTATION;
1177 #endif  // ENABLE_CALLGRIND
1178   }
1179 
1180   FPDF_DestroyLibrary();
1181 
1182 #ifdef PDF_ENABLE_V8
1183   if (!options.disable_javascript) {
1184     v8::V8::ShutdownPlatform();
1185 #ifdef V8_USE_EXTERNAL_STARTUP_DATA
1186     free(const_cast<char*>(snapshot.data));
1187 #endif  // V8_USE_EXTERNAL_STARTUP_DATA
1188   }
1189 #endif  // PDF_ENABLE_V8
1190 
1191   return 0;
1192 }
1193