• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2019 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 "testing/utils/file_util.h"
6 
7 #include <stdio.h>
8 
9 #include <utility>
10 #include <vector>
11 
12 #include "core/fxcrt/numerics/safe_conversions.h"
13 #include "core/fxcrt/span.h"
14 #include "core/fxcrt/stl_util.h"
15 #include "testing/utils/path_service.h"
16 
GetFileContents(const char * filename)17 std::vector<uint8_t> GetFileContents(const char* filename) {
18   FILE* file = fopen(filename, "rb");
19   if (!file) {
20     fprintf(stderr, "Failed to open: %s\n", filename);
21     return {};
22   }
23   (void)fseek(file, 0, SEEK_END);
24   size_t file_length = ftell(file);
25   if (!file_length) {
26     return {};
27   }
28   (void)fseek(file, 0, SEEK_SET);
29   std::vector<uint8_t> buffer(file_length);
30   size_t bytes_read = fread(buffer.data(), 1, file_length, file);
31   (void)fclose(file);
32   if (bytes_read != file_length) {
33     fprintf(stderr, "Failed to read: %s\n", filename);
34     return {};
35   }
36   return buffer;
37 }
38 
FileAccessForTesting(const std::string & file_name)39 FileAccessForTesting::FileAccessForTesting(const std::string& file_name) {
40   std::string file_path = PathService::GetTestFilePath(file_name);
41   if (file_path.empty()) {
42     return;
43   }
44 
45   file_contents_ = GetFileContents(file_path.c_str());
46   if (file_contents_.empty()) {
47     return;
48   }
49 
50   m_FileLen = pdfium::checked_cast<unsigned long>(file_contents_.size());
51   m_GetBlock = SGetBlock;
52   m_Param = this;
53 }
54 
GetBlockImpl(unsigned long pos,unsigned char * pBuf,unsigned long size)55 int FileAccessForTesting::GetBlockImpl(unsigned long pos,
56                                        unsigned char* pBuf,
57                                        unsigned long size) {
58   fxcrt::Copy(pdfium::make_span(file_contents_).subspan(pos, size),
59               pdfium::make_span(pBuf, size));
60   return size ? 1 : 0;
61 }
62 
63 // static
SGetBlock(void * param,unsigned long pos,unsigned char * pBuf,unsigned long size)64 int FileAccessForTesting::SGetBlock(void* param,
65                                     unsigned long pos,
66                                     unsigned char* pBuf,
67                                     unsigned long size) {
68   auto* file_access = static_cast<FileAccessForTesting*>(param);
69   return file_access->GetBlockImpl(pos, pBuf, size);
70 }
71