• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1  // Copyright 2019 PDFium Authors. All rights reserved.
2  // Use of this source code is governed by a BSD-style license that can be
3  // found in the LICENSE file.
4  
5  #include "testing/utils/file_util.h"
6  
7  #include <stdio.h>
8  #include <string.h>
9  
10  #include "testing/utils/path_service.h"
11  
GetFileContents(const char * filename,size_t * retlen)12  std::unique_ptr<char, pdfium::FreeDeleter> GetFileContents(const char* filename,
13                                                             size_t* retlen) {
14    FILE* file = fopen(filename, "rb");
15    if (!file) {
16      fprintf(stderr, "Failed to open: %s\n", filename);
17      return nullptr;
18    }
19    (void)fseek(file, 0, SEEK_END);
20    size_t file_length = ftell(file);
21    if (!file_length) {
22      return nullptr;
23    }
24    (void)fseek(file, 0, SEEK_SET);
25    std::unique_ptr<char, pdfium::FreeDeleter> buffer(
26        static_cast<char*>(malloc(file_length)));
27    if (!buffer) {
28      return nullptr;
29    }
30    size_t bytes_read = fread(buffer.get(), 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 nullptr;
35    }
36    *retlen = bytes_read;
37    return buffer;
38  }
39  
FileAccessForTesting(const std::string & file_name)40  FileAccessForTesting::FileAccessForTesting(const std::string& file_name) {
41    std::string file_path;
42    if (!PathService::GetTestFilePath(file_name, &file_path))
43      return;
44  
45    file_contents_ = GetFileContents(file_path.c_str(), &file_length_);
46    if (!file_contents_)
47      return;
48  
49    m_FileLen = static_cast<unsigned long>(file_length_);
50    m_GetBlock = SGetBlock;
51    m_Param = this;
52  }
53  
GetBlockImpl(unsigned long pos,unsigned char * pBuf,unsigned long size)54  int FileAccessForTesting::GetBlockImpl(unsigned long pos,
55                                         unsigned char* pBuf,
56                                         unsigned long size) {
57    memcpy(pBuf, file_contents_.get() + pos, size);
58    return size;
59  }
60  
61  // static
SGetBlock(void * param,unsigned long pos,unsigned char * pBuf,unsigned long size)62  int FileAccessForTesting::SGetBlock(void* param,
63                                      unsigned long pos,
64                                      unsigned char* pBuf,
65                                      unsigned long size) {
66    auto* file_access = static_cast<FileAccessForTesting*>(param);
67    return file_access->GetBlockImpl(pos, pBuf, size);
68  }
69