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 #include <string.h>
9
10 #include "testing/utils/path_service.h"
11 #include "third_party/base/numerics/safe_conversions.h"
12
GetFileContents(const char * filename,size_t * retlen)13 std::unique_ptr<char, pdfium::FreeDeleter> GetFileContents(const char* filename,
14 size_t* retlen) {
15 FILE* file = fopen(filename, "rb");
16 if (!file) {
17 fprintf(stderr, "Failed to open: %s\n", filename);
18 return nullptr;
19 }
20 (void)fseek(file, 0, SEEK_END);
21 size_t file_length = ftell(file);
22 if (!file_length) {
23 return nullptr;
24 }
25 (void)fseek(file, 0, SEEK_SET);
26 std::unique_ptr<char, pdfium::FreeDeleter> buffer(
27 static_cast<char*>(malloc(file_length)));
28 if (!buffer) {
29 return nullptr;
30 }
31 size_t bytes_read = fread(buffer.get(), 1, file_length, file);
32 (void)fclose(file);
33 if (bytes_read != file_length) {
34 fprintf(stderr, "Failed to read: %s\n", filename);
35 return nullptr;
36 }
37 *retlen = bytes_read;
38 return buffer;
39 }
40
FileAccessForTesting(const std::string & file_name)41 FileAccessForTesting::FileAccessForTesting(const std::string& file_name) {
42 std::string file_path;
43 if (!PathService::GetTestFilePath(file_name, &file_path))
44 return;
45
46 file_contents_ = GetFileContents(file_path.c_str(), &file_length_);
47 if (!file_contents_)
48 return;
49
50 m_FileLen = static_cast<unsigned long>(file_length_);
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 memcpy(pBuf, file_contents_.get() + pos, size);
59 return pdfium::base::checked_cast<int>(size);
60 }
61
62 // static
SGetBlock(void * param,unsigned long pos,unsigned char * pBuf,unsigned long size)63 int FileAccessForTesting::SGetBlock(void* param,
64 unsigned long pos,
65 unsigned char* pBuf,
66 unsigned long size) {
67 auto* file_access = static_cast<FileAccessForTesting*>(param);
68 return file_access->GetBlockImpl(pos, pBuf, size);
69 }
70