1 // Copyright 2020 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include <string>
16
17 #include "../sandboxed.h" // NOLINT(build/include)
18 #include "../tests/libpng.h" // NOLINT(build/include)
19 #include "sandboxed_api/vars.h"
20
LibPNGMain(const std::string & infile,const std::string & outfile)21 absl::Status LibPNGMain(const std::string& infile, const std::string& outfile) {
22 LibPNGSapiSandbox sandbox;
23 sandbox.AddFile(infile);
24 sandbox.AddFile(outfile);
25
26 SAPI_RETURN_IF_ERROR(sandbox.Init());
27 LibPNGApi api(&sandbox);
28
29 sapi::v::Struct<png_image> image;
30 sapi::v::ConstCStr infile_var(infile.c_str());
31 sapi::v::ConstCStr outfile_var(outfile.c_str());
32
33 image.mutable_data()->version = PNG_IMAGE_VERSION;
34
35 SAPI_ASSIGN_OR_RETURN(
36 int result, api.png_image_begin_read_from_file(image.PtrBoth(),
37 infile_var.PtrBefore()));
38 if (!result) {
39 return absl::InternalError(
40 absl::StrCat("begin read error: ", image.mutable_data()->message));
41 }
42
43 image.mutable_data()->format = PNG_FORMAT_RGBA;
44
45 sapi::v::Array<uint8_t> buffer(PNG_IMAGE_SIZE(*image.mutable_data()));
46
47 sapi::v::NullPtr null = sapi::v::NullPtr();
48 SAPI_ASSIGN_OR_RETURN(result,
49 api.png_image_finish_read(image.PtrBoth(), &null,
50 buffer.PtrBoth(), 0, &null));
51 if (!result) {
52 return absl::InternalError(
53 absl::StrCat("finish read error: ", image.mutable_data()->message));
54 }
55
56 SAPI_ASSIGN_OR_RETURN(result, api.png_image_write_to_file(
57 image.PtrBoth(), outfile_var.PtrBefore(), 0,
58 buffer.PtrBoth(), 0, &null));
59 if (!result) {
60 return absl::InternalError(
61 absl::StrCat("write error: ", image.mutable_data()->message));
62 }
63
64 return absl::OkStatus();
65 }
66
main(int argc,char * argv[])67 int main(int argc, char* argv[]) {
68 if (argc != 3) {
69 LOG(ERROR) << "usage: example input-file output-file";
70 return EXIT_FAILURE;
71 }
72
73 auto status = LibPNGMain(argv[1], argv[2]);
74 if (!status.ok()) {
75 LOG(ERROR) << "LibPNGMain failed with error:\n"
76 << status.ToString() << '\n';
77 return EXIT_FAILURE;
78 }
79
80 return EXIT_SUCCESS;
81 }
82