<|start_filename|>oss-internship-2020/lodepng/examples/helpers.h<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef LODEPNG_EXAMPLES_HELPERS_H_
#define LODEPNG_EXAMPLES_HELPERS_H_

#include <cstddef>
#include <cstdint>

#include <glog/logging.h>
#include "sandboxed_api/util/fileops.h"
#include "sandboxed_api/util/temp_file.h"

inline constexpr size_t kWidth = 512;
inline constexpr size_t kHeight = 512;
inline constexpr size_t kImgLen = kWidth * kHeight * 4;

// Returns a vector that contains values used for testing.
// This part of code is taken from
// https://github.com/lvandeve/lodepng/blob/master/examples/example_encode.c#L96-L104.
// The generated image contains square fractals.
std::vector<uint8_t> GenerateValues();

// Creates a temporary directory in the current working directory and returns
// the path.
std::string CreateTempDirAtCWD();

#endif  // LODEPNG_EXAMPLES_HELPERS_H_


<|start_filename|>oss-internship-2020/lodepng/examples/main_unit_test.cc<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "helpers.h"  // NOLINT(build/include)
#include "sandbox.h"  // NOLINT(build/include)
#include "gtest/gtest.h"
#include "sandboxed_api/util/status_matchers.h"

using ::sapi::IsOk;
using ::testing::Eq;
using ::testing::IsTrue;
using ::testing::NotNull;

namespace {

TEST(HelpersTest, CreateTempDirAtCWD) {
  const std::string images_path = CreateTempDirAtCWD();
  ASSERT_THAT(sandbox2::file_util::fileops::Exists(images_path, false),
              IsTrue())
      << "Temporary directory does not exist";

  EXPECT_THAT(sandbox2::file_util::fileops::DeleteRecursively(images_path),
              IsTrue())
      << "Temporary directory could not be deleted";
}

TEST(HelpersTest, GenerateValues) {
  EXPECT_THAT(GenerateValues().size(), Eq(kImgLen));
}

TEST(LodePngTest, Init) {
  const std::string images_path = CreateTempDirAtCWD();
  ASSERT_THAT(sandbox2::file_util::fileops::Exists(images_path, false),
              IsTrue())
      << "Temporary directory does not exist";

  SapiLodepngSandbox sandbox(images_path);
  ASSERT_THAT(sandbox.Init(), IsOk()) << "Error during sandbox init";

  EXPECT_THAT(sandbox2::file_util::fileops::DeleteRecursively(images_path),
              IsTrue())
      << "Temporary directory could not be deleted";
}

// Generate an image, encode it, decode it and compare the pixels with the
// initial values.
TEST(LodePngTest, EncodeDecodeOneStep) {
  const std::string images_path = CreateTempDirAtCWD();
  ASSERT_THAT(sandbox2::file_util::fileops::Exists(images_path, false),
              IsTrue())
      << "Temporary directory does not exist";

  SapiLodepngSandbox sandbox(images_path);
  ASSERT_THAT(sandbox.Init(), IsOk()) << "Error during sandbox initialization";
  LodepngApi api(&sandbox);

  std::vector<uint8_t> image = GenerateValues();

  sapi::v::Array<uint8_t> sapi_image(kImgLen);
  EXPECT_THAT(std::copy(image.begin(), image.end(), sapi_image.GetData()),
              IsTrue())
      << "Could not copy values";

  sapi::v::ConstCStr sapi_filename("/output/out_generated1.png");

  SAPI_ASSERT_OK_AND_ASSIGN(
      unsigned int result,
      api.lodepng_encode32_file(sapi_filename.PtrBefore(),
                                sapi_image.PtrBefore(), kWidth, kHeight));

  ASSERT_THAT(result, Eq(0)) << "Unexpected result from encode32_file call";

  sapi::v::UInt sapi_width, sapi_height;
  sapi::v::IntBase<uint8_t*> sapi_image_ptr(0);

  SAPI_ASSERT_OK_AND_ASSIGN(
      result, api.lodepng_decode32_file(
                  sapi_image_ptr.PtrBoth(), sapi_width.PtrBoth(),
                  sapi_height.PtrBoth(), sapi_filename.PtrBefore()));

  ASSERT_THAT(result, Eq(0)) << "Unexpected result from decode32_file call";

  EXPECT_THAT(sapi_width.GetValue(), Eq(kWidth)) << "Widths differ";
  EXPECT_THAT(sapi_height.GetValue(), Eq(kHeight)) << "Heights differ";

  sapi::v::Array<uint8_t> sapi_pixels(kImgLen);
  sapi_pixels.SetRemote(sapi_image_ptr.GetValue());

  ASSERT_THAT(sandbox.TransferFromSandboxee(&sapi_pixels), IsOk())
      << "Error during transfer from sandboxee";

  EXPECT_THAT(absl::equal(image.begin(), image.end(), sapi_pixels.GetData(),
                          sapi_pixels.GetData() + kImgLen),
              IsTrue())
      << "Values differ";

  EXPECT_THAT(sandbox.GetRpcChannel()->Free(sapi_image_ptr.GetValue()), IsOk())
      << "Could not free memory inside sandboxed process";

  EXPECT_THAT(sandbox2::file_util::fileops::DeleteRecursively(images_path),
              IsTrue())
      << "Temporary directory could not be deleted";
}

// Similar to the previous test, only that we use encoding by saving the data in
// memory and then writing it to the file and decoding by first decoding in
// memory and then getting the actual pixel values.
TEST(LodePngTest, EncodeDecodeTwoSteps) {
  const std::string images_path = CreateTempDirAtCWD();
  ASSERT_THAT(sandbox2::file_util::fileops::Exists(images_path, false),
              IsTrue())
      << "Temporary directory does not exist";

  SapiLodepngSandbox sandbox(images_path);
  ASSERT_THAT(sandbox.Init(), IsOk()) << "Error during sandbox init";
  LodepngApi api(&sandbox);

  std::vector<uint8_t> image = GenerateValues();

  sapi::v::Array<uint8_t> sapi_image(kImgLen);
  EXPECT_THAT(std::copy(image.begin(), image.end(), sapi_image.GetData()),
              IsTrue())
      << "Could not copy values";

  sapi::v::ConstCStr sapi_filename("/output/out_generated2.png");

  sapi::v::ULLong sapi_pngsize;
  sapi::v::IntBase<uint8_t*> sapi_png_ptr(0);

  SAPI_ASSERT_OK_AND_ASSIGN(
      unsigned int result,
      api.lodepng_encode32(sapi_png_ptr.PtrBoth(), sapi_pngsize.PtrBoth(),
                           sapi_image.PtrBefore(), kWidth, kHeight));

  ASSERT_THAT(result, Eq(0)) << "Unexpected result from encode32 call";

  sapi::v::Array<uint8_t> sapi_png_array(sapi_pngsize.GetValue());
  sapi_png_array.SetRemote(sapi_png_ptr.GetValue());

  ASSERT_THAT(sandbox.TransferFromSandboxee(&sapi_png_array), IsOk())
      << "Error during transfer from sandboxee";

  SAPI_ASSERT_OK_AND_ASSIGN(
      result,
      api.lodepng_save_file(sapi_png_array.PtrBefore(), sapi_pngsize.GetValue(),
                            sapi_filename.PtrBefore()));

  ASSERT_THAT(result, Eq(0)) << "Unexpected result from save_file call";

  sapi::v::UInt sapi_width, sapi_height;
  sapi::v::IntBase<uint8_t*> sapi_png_ptr2(0);
  sapi::v::ULLong sapi_pngsize2;

  SAPI_ASSERT_OK_AND_ASSIGN(
      result,
      api.lodepng_load_file(sapi_png_ptr2.PtrBoth(), sapi_pngsize2.PtrBoth(),
                            sapi_filename.PtrBefore()));

  ASSERT_THAT(result, Eq(0)) << "Unexpected result from load_file call";

  EXPECT_THAT(sapi_pngsize.GetValue(), Eq(sapi_pngsize2.GetValue()))
      << "Png sizes differ";

  sapi::v::Array<uint8_t> sapi_png_array2(sapi_pngsize2.GetValue());
  sapi_png_array2.SetRemote(sapi_png_ptr2.GetValue());

  ASSERT_THAT(sandbox.TransferFromSandboxee(&sapi_png_array2), IsOk())
      << "Error during transfer from sandboxee";

  sapi::v::IntBase<uint8_t*> sapi_png_ptr3(0);
  SAPI_ASSERT_OK_AND_ASSIGN(
      result,
      api.lodepng_decode32(sapi_png_ptr3.PtrBoth(), sapi_width.PtrBoth(),
                           sapi_height.PtrBoth(), sapi_png_array2.PtrBefore(),
                           sapi_pngsize2.GetValue()));

  ASSERT_THAT(result, Eq(0)) << "Unexpected result from decode32 call";

  EXPECT_THAT(sapi_width.GetValue(), Eq(kWidth)) << "Widths differ";
  EXPECT_THAT(sapi_height.GetValue(), Eq(kHeight)) << "Heights differ";

  sapi::v::Array<uint8_t> sapi_pixels(kImgLen);
  sapi_pixels.SetRemote(sapi_png_ptr3.GetValue());

  ASSERT_THAT(sandbox.TransferFromSandboxee(&sapi_pixels), IsOk())
      << "Error during transfer from sandboxee";

  EXPECT_THAT(absl::equal(image.begin(), image.end(), sapi_pixels.GetData(),
                          sapi_pixels.GetData() + kImgLen),
              IsTrue())
      << "Values differ";

  EXPECT_THAT(sandbox.GetRpcChannel()->Free(sapi_png_ptr.GetValue()), IsOk());
  EXPECT_THAT(sandbox.GetRpcChannel()->Free(sapi_png_ptr2.GetValue()), IsOk());
  EXPECT_THAT(sandbox.GetRpcChannel()->Free(sapi_png_ptr3.GetValue()), IsOk());

  EXPECT_THAT(sandbox2::file_util::fileops::DeleteRecursively(images_path),
              IsTrue())
      << "Temporary directory could not be deleted";
}

}  // namespace


<|start_filename|>oss-internship-2020/libarchive/ld_preload_example/sapi_minitar.cc<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "sapi_minitar.h"  // NOLINT(build/include)

#include <dlfcn.h>

#include <iostream>
#include <memory>

#include "libarchive_sapi.sapi.h"  // NOLINT(build/include)
#include "sandbox.h"               // NOLINT(build/include)
#include "sandboxed_api/var_array.h"
#include "sandboxed_api/var_ptr.h"

SapiLibarchiveSandboxExtract* sandbox_extract;
LibarchiveApi* api;
char* c_str_tmp = nullptr;

typedef void (*real_extract)(const char*, int, int, int);

void extract(const char* filename, int do_extract, int flags, int verbose) {
  // Here we initialize the sandbox and other objects.
  std::string tmp_dir;
  if (do_extract) {
    tmp_dir = CreateTempDirAtCWD().value();
  }

  std::string filename_absolute = MakeAbsolutePathAtCWD(filename);

  // Initialize sandbox and api objects.
  sandbox_extract =
      new SapiLibarchiveSandboxExtract(filename_absolute, do_extract, tmp_dir);
  CHECK(sandbox_extract->Init().ok()) << "Error during sandbox initialization";
  api = new LibarchiveApi(sandbox_extract);

  // After everything is set up, call the original function (next symbol).

  // TODO getting the mangled name of the function at runtime does not work
  // as intended. At the moment just use the symbol directly.
  const char* y = "_Z7extractPKciii";
  void* x = dlsym(RTLD_NEXT, y);

  CHECK(x != nullptr) << "dlsym call could not find function symbol";
  ((real_extract)x)(filename_absolute.c_str(), do_extract, flags, verbose);

  // clean up
  if (c_str_tmp != nullptr) {
    delete[] c_str_tmp;
  }

  // This is the last function called so we can delete the temporary directory
  // here
  if (do_extract) {
    sandbox2::file_util::fileops::DeleteRecursively(tmp_dir);
  }

  delete api;
  delete sandbox_extract;
}

archive* archive_read_new() {
  archive* ret = api->archive_read_new().value();
  CHECK(ret != nullptr) << "Failed to create archive";
  return ret;
}

archive* archive_write_disk_new() {
  archive* ret = api->archive_write_disk_new().value();
  CHECK(ret != nullptr) << "Failed to create archive";
  return ret;
}

int archive_write_disk_set_options(archive* ext, int flags) {
  sapi::v::RemotePtr ext_ptr(ext);

  return api->archive_write_disk_set_options(&ext_ptr, flags).value();
}

int archive_read_support_filter_bzip2(archive* a) {
  sapi::v::RemotePtr a_ptr(a);
  return api->archive_read_support_filter_bzip2(&a_ptr).value();
}

int archive_read_support_filter_gzip(archive* a) {
  sapi::v::RemotePtr a_ptr(a);
  return api->archive_read_support_filter_gzip(&a_ptr).value();
}

int archive_read_support_filter_compress(archive* a) {
  sapi::v::RemotePtr a_ptr(a);
  return api->archive_read_support_filter_compress(&a_ptr).value();
}
int archive_read_support_format_tar(archive* a) {
  sapi::v::RemotePtr a_ptr(a);
  return api->archive_read_support_format_tar(&a_ptr).value();
}

int archive_read_support_format_cpio(archive* a) {
  sapi::v::RemotePtr a_ptr(a);
  return api->archive_read_support_format_cpio(&a_ptr).value();
}

int archive_write_disk_set_standard_lookup(archive* ext) {
  sapi::v::RemotePtr ext_ptr(ext);

  return api->archive_write_disk_set_standard_lookup(&ext_ptr).value();
}

int archive_read_open_filename(archive* a, const char* _filename,
                               size_t _block_size) {
  sapi::v::RemotePtr a_ptr(a);

  return api
      ->archive_read_open_filename(
          &a_ptr, sapi::v::ConstCStr(_filename).PtrBefore(), _block_size)
      .value();
}

int archive_read_next_header(archive* a, archive_entry** entry) {
  sapi::v::IntBase<archive_entry*> entry_ptr_tmp(0);
  sapi::v::RemotePtr a_ptr(a);
  int rc =
      api->archive_read_next_header(&a_ptr, entry_ptr_tmp.PtrAfter()).value();
  *entry = entry_ptr_tmp.GetValue();
  return rc;
}

// In the following two functions we need to transfer a string from the
// sandboxed process to the client process. However, this string would
// go out of scope after this function so we use a global char * to make
// sure it does not get automatically deleted before it is used.
const char* archive_error_string(archive* a) {
  sapi::v::RemotePtr a_ptr(a);
  char* str = api->archive_error_string(&a_ptr).value();
  CHECK(str != nullptr) << "Could not get error message";

  std::string str_tmp =
      sandbox_extract->GetCString(sapi::v::RemotePtr(str)).value();

  if (c_str_tmp != nullptr) {
    delete[] c_str_tmp;
  }

  c_str_tmp = new char[str_tmp.length() + 1];
  strcpy(c_str_tmp, str_tmp.c_str());  // NOLINT(runtime/printf)

  return c_str_tmp;
}

const char* archive_entry_pathname(archive_entry* entry) {
  sapi::v::RemotePtr entry_ptr(entry);
  char* str = api->archive_entry_pathname(&entry_ptr).value();
  CHECK(str != nullptr) << "Could not get pathname";

  std::string str_tmp =
      sandbox_extract->GetCString(sapi::v::RemotePtr(str)).value();

  if (c_str_tmp != nullptr) {
    delete[] c_str_tmp;
  }

  c_str_tmp = new char[str_tmp.length() + 1];
  strcpy(c_str_tmp, str_tmp.c_str());  // NOLINT(runtime/printf)

  return c_str_tmp;
}

int archive_read_close(archive* a) {
  sapi::v::RemotePtr a_ptr(a);
  return api->archive_read_close(&a_ptr).value();
}

int archive_read_free(archive* a) {
  sapi::v::RemotePtr a_ptr(a);
  return api->archive_read_free(&a_ptr).value();
}

int archive_write_close(archive* a) {
  sapi::v::RemotePtr a_ptr(a);
  return api->archive_write_close(&a_ptr).value();
}

int archive_write_free(archive* a) {
  sapi::v::RemotePtr a_ptr(a);
  return api->archive_write_free(&a_ptr).value();
}

int archive_write_header(archive* a, archive_entry* entry) {
  sapi::v::RemotePtr a_ptr(a), entry_ptr(entry);
  return api->archive_write_header(&a_ptr, &entry_ptr).value();
}

int archive_read_data_block(archive* a, const void** buff, size_t* size,
                            la_int64_t* offset) {
  sapi::v::IntBase<archive_entry*> buff_ptr_tmp(0);
  sapi::v::ULLong size_tmp;
  sapi::v::SLLong offset_tmp;
  sapi::v::RemotePtr a_ptr(a);

  int rv =
      api->archive_read_data_block(&a_ptr, buff_ptr_tmp.PtrAfter(),
                                   size_tmp.PtrAfter(), offset_tmp.PtrAfter())
          .value();
  *buff = buff_ptr_tmp.GetValue();
  *size = size_tmp.GetValue();
  *offset = offset_tmp.GetValue();

  return rv;
}

la_ssize_t archive_write_data_block(archive* a, const void* buff, size_t s,
                                    la_int64_t o) {
  sapi::v::RemotePtr buff_ptr((void*)(buff));
  sapi::v::RemotePtr a_ptr(a);

  return api->archive_write_data_block(&a_ptr, &buff_ptr, s, o).value();
}


<|start_filename|>oss-internship-2020/libarchive/examples/sandbox.h<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef SAPI_LIBARCHIVE_EXAMPLES_SANDBOX_H
#define SAPI_LIBARCHIVE_EXAMPLES_SANDBOX_H

#include <asm/unistd_64.h>
#include <linux/fs.h>

#include "libarchive_sapi.sapi.h"  // NOLINT(build/include)
#include "sandboxed_api/sandbox2/util/bpf_helper.h"
#include "sandboxed_api/util/fileops.h"

// When creating an archive, we need read permissions on each of the
// file/directory added in the archive. Also, in order to create the archive, we
// map "/output" with the basename of the archive. This way, the program can
// create the file without having access to anything else.
class SapiLibarchiveSandboxCreate : public LibarchiveSandbox {
 public:
  SapiLibarchiveSandboxCreate(const std::vector<std::string>& files,
                              absl::string_view archive_path)
      : files_(files), archive_path_(archive_path) {}

 private:
  std::unique_ptr<sandbox2::Policy> ModifyPolicy(
      sandbox2::PolicyBuilder*) override {
    sandbox2::PolicyBuilder policy =
        sandbox2::PolicyBuilder()
            .AddDirectoryAt(archive_path_, "/output", false)
            .AllowRead()
            .AllowWrite()
            .AllowOpen()
            .AllowSystemMalloc()
            .AllowGetIDs()
            .AllowSafeFcntl()
            .AllowStat()
            .AllowExit()
            .AllowSyscalls({
                __NR_futex,
                __NR_lseek,
                __NR_close,
                __NR_gettid,
                __NR_umask,
                __NR_utimensat,
                __NR_unlink,
                __NR_mkdir,
                __NR_fstatfs,
                __NR_socket,
                __NR_connect,
                __NR_flistxattr,
                __NR_recvmsg,
                __NR_getdents64,
            })
            // Allow ioctl only for FS_IOC_GETFLAGS.
            .AddPolicyOnSyscall(__NR_ioctl,
                                {ARG(1), JEQ(FS_IOC_GETFLAGS, ALLOW)});

    // We check whether the entry is a file or a directory.
    for (const auto& i : files_) {
      struct stat s;
      CHECK(stat(i.c_str(), &s) == 0) << "Could not stat " << i;
      if (S_ISDIR(s.st_mode)) {
        policy = policy.AddDirectory(i);
      } else {
        policy = policy.AddFile(i);
      }
    }

    return policy.BuildOrDie();
  }

  const std::vector<std::string> files_;
  absl::string_view archive_path_;
};

// When an archive is extracted, the generated files/directories will be placed
// relative to the current working directory. In order to add permissions to
// this we create a temporary directory at every extraction. Then, we change the
// directory of the sandboxed process to that directory and map it to the
// current "real" working directory. This way the contents of the archived will
// pe placed correctly without offering additional permission.
class SapiLibarchiveSandboxExtract : public LibarchiveSandbox {
 public:
  SapiLibarchiveSandboxExtract(absl::string_view archive_path, int do_extract,
                               absl::string_view tmp_dir)
      : archive_path_(archive_path),
        do_extract_(do_extract),
        tmp_dir_(tmp_dir) {}

 private:
  void ModifyExecutor(sandbox2::Executor* executor) override {
    // If the user only wants to list the entries in the archive, we do
    // not need to worry about changing directories;
    if (do_extract_) {
      executor->set_cwd(std::string(tmp_dir_));
    }
  }

  std::unique_ptr<sandbox2::Policy> ModifyPolicy(
      sandbox2::PolicyBuilder*) override {
    sandbox2::PolicyBuilder policy = sandbox2::PolicyBuilder()
                                         .AllowRead()
                                         .AllowWrite()
                                         .AllowOpen()
                                         .AllowSystemMalloc()
                                         .AllowGetIDs()
                                         .AllowSafeFcntl()
                                         .AllowStat()
                                         .AllowExit()
                                         .AllowSyscalls({
                                             __NR_futex,
                                             __NR_lseek,
                                             __NR_close,
                                             __NR_gettid,
                                             __NR_umask,
                                             __NR_utimensat,
                                             __NR_unlink,
                                             __NR_mkdir,
                                         })
                                         .AddFile(archive_path_);

    if (do_extract_) {
      // Get the real cwd and map it to the temporary directory in which
      // the sandboxed process takes place().
      std::string cwd = sandbox2::file_util::fileops::GetCWD();
      policy = policy.AddDirectoryAt(cwd, tmp_dir_, false);
    }
    return policy.BuildOrDie();
  }

  absl::string_view archive_path_;
  absl::string_view tmp_dir_;
  const int do_extract_;
};

#endif  // SAPI_LIBARCHIVE_EXAMPLES_SANDBOX_H


<|start_filename|>oss-internship-2020/gdal/raster_to_gtiff/utils.h<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef RASTER_TO_GTIFF_UTILS_H_
#define RASTER_TO_GTIFF_UTILS_H_

#include <optional>
#include <string>

#include "absl/strings/string_view.h"

namespace gdal::sandbox::utils {

// RAII wrapper that creates temporary file and automatically unlinks it
class TempFile {
 public:
  explicit TempFile(absl::string_view prefix);
  TempFile(const TempFile&) = delete;
  TempFile& operator=(const TempFile&) = delete;
  TempFile(TempFile&&) = delete;
  TempFile& operator=(TempFile&&) = delete;
  ~TempFile();

  bool HasValue() const;
  int GetFd() const;
  std::string GetPath() const;

 private:
  std::optional<std::pair<std::string, int>> file_data_ = std::nullopt;
};

// Helper function to retrieve potential proj.db path from environment variable
std::optional<std::string> FindProjDbPath();

// Tries to get test folder path from the TEST_SRCDIR environment variable and
// uses CWD path otherwise to join it with the testdata_path
std::string GetTestDataPath(absl::string_view testdata_path);

}  // namespace gdal::sandbox::utils

#endif  // RASTER_TO_GTIFF_UTILS_H_


<|start_filename|>oss-internship-2020/libarchive/examples/sapi_minitar.h<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef SAPI_LIBARCHIVE_EXAMPLES_MINITAR_H
#define SAPI_LIBARCHIVE_EXAMPLES_MINITAR_H

#include <archive.h>
#include <archive_entry.h>
#include <fcntl.h>

#include "libarchive_sapi.sapi.h"  // NOLINT(build/include)
#include "sandbox.h"               // NOLINT(build/include)
#include "sandboxed_api/sandbox2/util.h"
#include "sandboxed_api/util/path.h"
#include "sandboxed_api/util/temp_file.h"

// Creates an archive file at the given filename.
absl::Status CreateArchive(const char* filename, int compress,
                           const char** argv, bool verbose = true);

// Extracts an archive file. If do_extract is true, the files will
// be created relative to the current working directory. If do_extract
// is false then the function will just print the entries of the archive.
absl::Status ExtractArchive(const char* filename, int do_extract, int flags,
                            bool verbose = true);

// This function is only called from the "extract function". It is still
// isolated in order to not modify the code structure as much.
absl::StatusOr<int> CopyData(sapi::v::RemotePtr* ar, sapi::v::RemotePtr* aw,
                             LibarchiveApi& api,
                             SapiLibarchiveSandboxExtract& sandbox);

inline constexpr size_t kBlockSize = 10240;
inline constexpr size_t kBuffSize = 16384;

// Converts one string to an absolute path by prepending the current
// working directory to the relative path.
// The path is also cleaned at the end.
std::string MakeAbsolutePathAtCWD(const std::string& path);

// This function takes a status as argument and after checking the status
// it transfers the string. This is used mostly with archive_error_string
// and other library functions that return a char*.
absl::StatusOr<std::string> CheckStatusAndGetString(
    const absl::StatusOr<char*>& status, LibarchiveSandbox& sandbox);

// Creates a temporary directory in the current working directory and
// returns the path. This is used in the extract function where the sandboxed
// process changes the current working directory to this temporary directory.
absl::StatusOr<std::string> CreateTempDirAtCWD();

#endif  // SAPI_LIBARCHIVE_EXAMPLES_MINITAR_H


<|start_filename|>sandboxed_api/sandbox2/ipc.h<|end_filename|>
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// The sandbox2::IPC class provides routines for exchanging data between sandbox
// and the sandboxee.

#ifndef SANDBOXED_API_SANDBOX2_IPC_H_
#define SANDBOXED_API_SANDBOX2_IPC_H_

#include <memory>
#include <string>
#include <tuple>
#include <vector>

#include "absl/strings/string_view.h"
#include "sandboxed_api/sandbox2/comms.h"

namespace sandbox2 {

class IPC final {
 public:
  IPC() = default;

  IPC(const IPC&) = delete;
  IPC& operator=(const IPC&) = delete;

  ~IPC() { InternalCleanupFdMap(); }

  ABSL_DEPRECATED("Use Sandbox2::comms() instead")
  Comms* comms() const { return comms_.get(); }

  // Marks local_fd so that it should be sent to the remote process (sandboxee),
  // and duplicated onto remote_fd in it. The local_fd will be closed after
  // being sent (in SendFdsOverComms which is called by the Monitor class), so
  // it should not be used from that point on.
  void MapFd(int local_fd, int remote_fd);

  // Creates and returns a socketpair endpoint. The other endpoint of the
  // socketpair is marked as to be sent to the remote process (sandboxee) with
  // SendFdsOverComms() as with MapFd().
  // If a name is specified, uses the Client::GetMappedFD api to retrieve the
  // corresponding file descriptor in the sandboxee.
  int ReceiveFd(int remote_fd, absl::string_view name);
  int ReceiveFd(int remote_fd);
  int ReceiveFd(absl::string_view name);

  // Enable sandboxee logging, this will start a thread that waits for log
  // messages from the sandboxee. You'll also have to call
  // Client::SendLogsToSupervisor in the sandboxee.
  void EnableLogServer();

 private:
  friend class Executor;
  friend class Monitor;
  friend class IpcPeer;  // For testing

  // Uses a pre-connected file descriptor.
  void SetUpServerSideComms(int fd);

  // Sends file descriptors to the sandboxee. Close the local FDs (e.g. passed
  // in MapFd()) - they cannot be used anymore.
  bool SendFdsOverComms();

  void InternalCleanupFdMap();

  // Tuple of file descriptor pairs which will be sent to the sandboxee: in the
  // form of tuple<local_fd, remote_fd>: local_fd: local fd which should be sent
  // to sandboxee, remote_fd: it will be overwritten by local_fd.
  std::vector<std::tuple<int, int, std::string>> fd_map_;

  // Comms channel used to exchange data with the sandboxee.
  std::unique_ptr<Comms> comms_;
};

}  // namespace sandbox2

#endif  // SANDBOXED_API_SANDBOX2_IPC_H_


<|start_filename|>oss-internship-2020/libuv/tests/test_loop.cc<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <linux/futex.h>
#include <syscall.h>
#include <uv.h>

#include "gtest/gtest.h"
#include "sandboxed_api/util/flag.h"
#include "sandboxed_api/util/status_matchers.h"
#include "uv_sapi.sapi.h"  // NOLINT(build/include)

namespace {

class UVTestLoopSapiSandbox : public uv::UVSandbox {
 private:
  std::unique_ptr<sandbox2::Policy> ModifyPolicy(
      sandbox2::PolicyBuilder*) override {
    return sandbox2::PolicyBuilder()
        .AllowDynamicStartup()
        .AllowExit()
        .AllowFutexOp(FUTEX_WAKE_PRIVATE)
        .AllowSyscalls({__NR_epoll_create1, __NR_eventfd2, __NR_pipe2})
        .AllowWrite()
        .BuildOrDie();
  }
};

class UVTestLoop : public ::testing::Test {
 protected:
  void SetUp() override {
    sandbox_ = std::make_unique<UVTestLoopSapiSandbox>();
    ASSERT_THAT(sandbox_->Init(), sapi::IsOk());
    api_ = std::make_unique<uv::UVApi>(sandbox_.get());
  }

  // Check sapi_uv_loop_init
  void UVLoopInit(sapi::v::Ptr* loop) {
    SAPI_ASSERT_OK_AND_ASSIGN(int error_code, api_->sapi_uv_loop_init(loop));
    ASSERT_EQ(error_code, 0);
  }

  // Check sapi_uv_run
  void UVRun(sapi::v::Ptr* loop) {
    SAPI_ASSERT_OK_AND_ASSIGN(int error_code,
                              api_->sapi_uv_run(loop, UV_RUN_DEFAULT));
    ASSERT_EQ(error_code, 0);
  }

  // Check sapi_uv_loop_close
  void UVLoopClose(sapi::v::Ptr* loop) {
    SAPI_ASSERT_OK_AND_ASSIGN(int error_code, api_->sapi_uv_loop_close(loop));
    ASSERT_EQ(error_code, 0);
  }

  // Check sapi_uv_default_loop, set loop to default loop
  void UVDefaultLoop(sapi::v::Ptr* loop) {
    SAPI_ASSERT_OK_AND_ASSIGN(void* loop_voidptr, api_->sapi_uv_default_loop());
    loop->SetRemote(loop_voidptr);
  }

  std::unique_ptr<UVTestLoopSapiSandbox> sandbox_;
  std::unique_ptr<uv::UVApi> api_;
};

TEST_F(UVTestLoop, InitLoop) {
  // Allocate memory for loop
  void* loop_voidptr;
  ASSERT_THAT(
      sandbox_->rpc_channel()->Allocate(sizeof(uv_loop_t), &loop_voidptr),
      sapi::IsOk());
  sapi::v::RemotePtr loop(loop_voidptr);

  // Initialize, run and close the manually initialized loop
  UVLoopInit(loop.PtrBoth());
  UVRun(loop.PtrNone());
  UVLoopClose(loop.PtrNone());

  // Free loop memory
  ASSERT_THAT(sandbox_->rpc_channel()->Free(loop_voidptr), sapi::IsOk());
}

TEST_F(UVTestLoop, DefaultLoop) {
  sapi::v::RemotePtr loop(nullptr);

  // Run the default loop
  UVDefaultLoop(&loop);
  UVRun(loop.PtrNone());

  // Close the default loop
  UVDefaultLoop(&loop);
  UVLoopClose(loop.PtrNone());
}

}  // namespace


<|start_filename|>oss-internship-2020/libarchive/examples/sapi_minitar_main.cc<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// This file contains the main function from the original minitar example:
// https://github.com/libarchive/libarchive/blob/master/examples/minitar/minitar.c
// Most of the logic is the same, it was only simplified a bit since this is
// only used for the command line tool.
// No sandboxing takes place in this function.

#include <iostream>

#include "sapi_minitar.h"  // NOLINT(build/include)

static void PrintUsage() {
  /* Many program options depend on compile options. */
  const char* m =
      "Usage: minitar [-"
      "c"
      "j"
      "tvx"
      "y"
      "Z"
      "z"
      "] [-f file] [file]\n";

  std::cout << m << std::endl;
  exit(EXIT_FAILURE);
}

int main(int unused_argc, const char** argv) {
  google::InitGoogleLogging(argv[0]);
  const char* filename = nullptr;
  int compress;
  int flags;
  int mode;
  int opt;

  mode = 'x';
  int verbose = 0;
  compress = '\0';
  flags = ARCHIVE_EXTRACT_TIME;

  while (*++argv != nullptr && **argv == '-') {
    const char* p = *argv + 1;

    while ((opt = *p++) != '\0') {
      switch (opt) {
        case 'c':
          mode = opt;
          break;
        case 'f':
          if (*p != '\0')
            filename = p;
          else
            filename = *++argv;
          p += strlen(p);
          break;
        case 'j':
          compress = opt;
          break;
        case 'p':
          flags |= ARCHIVE_EXTRACT_PERM;
          flags |= ARCHIVE_EXTRACT_ACL;
          flags |= ARCHIVE_EXTRACT_FFLAGS;
          break;
        case 't':
          mode = opt;
          break;
        case 'v':
          verbose++;
          break;
        case 'x':
          mode = opt;
          break;
        case 'y':
          compress = opt;
          break;
        case 'Z':
          compress = opt;
          break;
        case 'z':
          compress = opt;
          break;
        default:
          PrintUsage();
      }
    }
  }

  absl::Status status;
  switch (mode) {
    case 'c':
      status = CreateArchive(filename, compress, argv, verbose);
      if (!status.ok()) {
        LOG(ERROR) << "Archive creation failed with message: "
                   << status.message();
        return EXIT_FAILURE;
      }
      break;
    case 't':
      status = ExtractArchive(filename, 0, flags, verbose);
      if (!status.ok()) {
        LOG(ERROR) << "Archive extraction failed with message: "
                   << status.message();
        return EXIT_FAILURE;
      }
      break;
    case 'x':
      status = ExtractArchive(filename, 1, flags, verbose);
      if (!status.ok()) {
        LOG(ERROR) << "Archive extraction failed with message: "
                   << status.message();
        return EXIT_FAILURE;
      }
      break;
  }

  return EXIT_SUCCESS;
}


<|start_filename|>oss-internship-2020/libtiff/test/check_tag.h<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef LIBTIFF_TEST_CHECK_TAG_H_
#define LIBTIFF_TEST_CHECK_TAG_H_

#include <cstdint>

#include "helper.h"  // NOLINT(build/include)
#include "tiffio.h"  // NOLINT(build/include)

void CheckShortField(TiffApi&, sapi::v::RemotePtr& tif, const ttag_t field,
                     const uint16_t value);
void CheckShortPairedField(TiffApi& api, sapi::v::RemotePtr& tif,
                           const ttag_t field,
                           const std::array<uint16_t, 2>& values);
void CheckLongField(TiffApi&, sapi::v::RemotePtr& tif, const ttag_t field,
                    const uint32_t value);

#endif  // LIBTIFF_TEST_CHECK_TAG_H_


<|start_filename|>cmake/zlib.cmake<|end_filename|>
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set(workdir "${CMAKE_BINARY_DIR}/_deps/zlib-populate")

set(SAPI_ZLIB_URL https://mirror.bazel.build/zlib.net/zlib-1.2.11.tar.gz
                  CACHE STRING "")
set(SAPI_ZLIB_URL_HASH
  SHA256=c3e5e9fdd5004dcb542feda5ee4f0ff0744628baf8ed2dd5d66f8ca1197cb1a1
  CACHE STRING "") # 2020-04-23
set(SAPI_ZLIB_SOURCE_DIR "${CMAKE_BINARY_DIR}/_deps/zlib-src" CACHE STRING "")
set(SAPI_ZLIB_BINARY_DIR "${CMAKE_BINARY_DIR}/_deps/zlib-build" CACHE STRING "")

file(WRITE "${workdir}/CMakeLists.txt" "\
cmake_minimum_required(VERSION ${CMAKE_VERSION})
project(zlib-populate NONE)
include(ExternalProject)
ExternalProject_Add(zlib
  URL           \"${SAPI_ZLIB_URL}\"
  URL_HASH      \"${SAPI_ZLIB_URL_HASH}\"
  SOURCE_DIR    \"${SAPI_ZLIB_SOURCE_DIR}\"
  BINARY_DIR    \"${SAPI_ZLIB_BINARY_DIR}\"
  PATCH_COMMAND patch -p1
                < \"${SAPI_SOURCE_DIR}/sandboxed_api/bazel/external/zlib.patch\"
  CONFIGURE_COMMAND \"\"
  BUILD_COMMAND     \"\"
  INSTALL_COMMAND   \"\"
  TEST_COMMAND      \"\"
)
")

execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" .
                RESULT_VARIABLE error
                WORKING_DIRECTORY "${workdir}")
if(error)
  message(FATAL_ERROR "CMake step for ${PROJECT_NAME} failed: ${error}")
endif()

execute_process(COMMAND ${CMAKE_COMMAND} --build .
                RESULT_VARIABLE error
                WORKING_DIRECTORY "${workdir}")
if(error)
  message(FATAL_ERROR "Build step for ${PROJECT_NAME} failed: ${error}")
endif()

set(ZLIB_FOUND TRUE)
set(ZLIB_INCLUDE_DIRS ${SAPI_ZLIB_SOURCE_DIR})

add_library(z STATIC
  ${SAPI_ZLIB_SOURCE_DIR}/adler32.c
  ${SAPI_ZLIB_SOURCE_DIR}/compress.c
  ${SAPI_ZLIB_SOURCE_DIR}/crc32.c
  ${SAPI_ZLIB_SOURCE_DIR}/crc32.h
  ${SAPI_ZLIB_SOURCE_DIR}/deflate.c
  ${SAPI_ZLIB_SOURCE_DIR}/deflate.h
  ${SAPI_ZLIB_SOURCE_DIR}/gzclose.c
  ${SAPI_ZLIB_SOURCE_DIR}/gzguts.h
  ${SAPI_ZLIB_SOURCE_DIR}/gzlib.c
  ${SAPI_ZLIB_SOURCE_DIR}/gzread.c
  ${SAPI_ZLIB_SOURCE_DIR}/gzwrite.c
  ${SAPI_ZLIB_SOURCE_DIR}/infback.c
  ${SAPI_ZLIB_SOURCE_DIR}/inffast.c
  ${SAPI_ZLIB_SOURCE_DIR}/inffast.h
  ${SAPI_ZLIB_SOURCE_DIR}/inffixed.h
  ${SAPI_ZLIB_SOURCE_DIR}/inflate.c
  ${SAPI_ZLIB_SOURCE_DIR}/inflate.h
  ${SAPI_ZLIB_SOURCE_DIR}/inftrees.c
  ${SAPI_ZLIB_SOURCE_DIR}/inftrees.h
  ${SAPI_ZLIB_SOURCE_DIR}/trees.c
  ${SAPI_ZLIB_SOURCE_DIR}/trees.h
  ${SAPI_ZLIB_SOURCE_DIR}/uncompr.c
  ${SAPI_ZLIB_SOURCE_DIR}/zconf.h
  ${SAPI_ZLIB_SOURCE_DIR}/zlib.h
  ${SAPI_ZLIB_SOURCE_DIR}/zutil.c
  ${SAPI_ZLIB_SOURCE_DIR}/zutil.h
)
add_library(ZLIB::ZLIB ALIAS z)
target_include_directories(z PUBLIC
  ${SAPI_ZLIB_SOURCE_DIR}
)
target_compile_options(z PRIVATE
  -w
  -Dverbose=-1
)
target_link_libraries(z PRIVATE
  sapi::base
)


<|start_filename|>oss-internship-2020/curl/tests/test_utils.h<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef TESTS_H_
#define TESTS_H_

#include "../sandbox.h"      // NOLINT(build/include)
#include "curl_sapi.sapi.h"  // NOLINT(build/include)
#include "gtest/gtest.h"
#include "sandboxed_api/util/flag.h"
#include "absl/status/statusor.h"
#include "sandboxed_api/util/status_matchers.h"

namespace curl::tests {

// Helper class that can be used to test Curl sandbox.
class CurlTestUtils {
 protected:
  static constexpr char kUrl[] = "http://127.0.0.1/";

  // Starts a mock server (only once) that will manage connections for the
  // tests. The server listens on a port asynchronously by creating a thread.
  // The port number is stored in port_. Responds with "OK" to a GET request,
  // responds with the POST request fields to a POST request.
  static void StartMockServer();

  // Initializes and sets up the curl handle.
  absl::Status CurlTestSetUp();
  // Cleans up the curl handle.
  absl::Status CurlTestTearDown();

  // Performs a request to the mock server, returning the response.
  absl::StatusOr<std::string> PerformRequest();

  static std::thread server_thread_;
  static int port_;

  std::unique_ptr<curl::CurlSapiSandbox> sandbox_;
  std::unique_ptr<curl::CurlApi> api_;
  std::unique_ptr<sapi::v::RemotePtr> curl_;

 private:
  std::unique_ptr<sapi::v::LenVal> chunk_;
};

}  // namespace curl::tests

#endif  // TESTS_H_


<|start_filename|>cmake/gflags.cmake<|end_filename|>
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set(workdir "${CMAKE_BINARY_DIR}/_deps/gflags-populate")

set(SAPI_GFLAGS_GIT_REPOSITORY https://github.com/gflags/gflags.git
                               CACHE STRING "")
set(SAPI_GFLAGS_GIT_TAG addd749114fab4f24b7ea1e0f2f837584389e52c
                        CACHE STRING "") # 2020-03-18
set(SAPI_GFLAGS_SOURCE_DIR "${CMAKE_BINARY_DIR}/_deps/gflags-src"
                            CACHE STRING "")
set(SAPI_GFLAGS_BINARY_DIR "${CMAKE_BINARY_DIR}/_deps/gflags-build"
                           CACHE STRING "")

file(WRITE "${workdir}/CMakeLists.txt" "\
cmake_minimum_required(VERSION ${CMAKE_VERSION})
project(gflags-populate NONE)
include(ExternalProject)
ExternalProject_Add(gflags
  GIT_REPOSITORY    \"${SAPI_GFLAGS_GIT_REPOSITORY}\"
  GIT_TAG           \"${SAPI_GFLAGS_GIT_TAG}\"
  SOURCE_DIR        \"${SAPI_GFLAGS_SOURCE_DIR}\"
  BINARY_DIR        \"${SAPI_GFLAGS_BINARY_DIR}\"
  CONFIGURE_COMMAND \"\"
  BUILD_COMMAND     \"\"
  INSTALL_COMMAND   \"\"
  TEST_COMMAND      \"\"
)
")

execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" .
                RESULT_VARIABLE error
                WORKING_DIRECTORY "${workdir}")
if(error)
  message(FATAL_ERROR "CMake step for ${PROJECT_NAME} failed: ${error}")
endif()

execute_process(COMMAND ${CMAKE_COMMAND} --build .
                RESULT_VARIABLE error
                WORKING_DIRECTORY "${workdir}")
if(error)
  message(FATAL_ERROR "Build step for ${PROJECT_NAME} failed: ${error}")
endif()

set(GFLAGS_IS_SUBPROJECT TRUE)
set(GFLAGS_BUILD_SHARED_LIBS ${SAPI_ENABLE_SHARED_LIBS})
set(GFLAGS_INSTALL_SHARED_LIBS ${SAPI_ENABLE_SHARED_LIBS})
set(GFLAGS_INSTALL_HEADERS OFF) # TODO: Temporary off
set(GFLAGS_BUILD_TESTING FALSE)

add_subdirectory("${SAPI_GFLAGS_SOURCE_DIR}"
                 "${SAPI_GFLAGS_BINARY_DIR}" EXCLUDE_FROM_ALL)


<|start_filename|>cmake/libffi.cmake<|end_filename|>
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set(workdir "${CMAKE_BINARY_DIR}/_deps/libffi-populate")

set(SAPI_LIBFFI_URL
  https://github.com/libffi/libffi/releases/download/v3.3-rc2/libffi-3.3-rc2.tar.gz
  CACHE STRING "")
set(SAPI_LIBFFI_URL_HASH
  SHA256=653ffdfc67fbb865f39c7e5df2a071c0beb17206ebfb0a9ecb18a18f63f6b263
  CACHE STRING "") # 2019-11-02
set(SAPI_LIBFFI_SOURCE_DIR "${CMAKE_BINARY_DIR}/_deps/libffi-src"
                           CACHE STRING "")
set(SAPI_LIBFFI_BINARY_DIR "${CMAKE_BINARY_DIR}/_deps/libffi-build"
                           CACHE STRING "")

file(WRITE "${workdir}/CMakeLists.txt" "\
cmake_minimum_required(VERSION ${CMAKE_VERSION})
project(libffi-populate NONE)
include(ExternalProject)
ExternalProject_Add(libffi
  URL               \"${SAPI_LIBFFI_URL}\"
  URL_HASH          \"${SAPI_LIBFFI_URL_HASH}\"
  SOURCE_DIR        \"${SAPI_LIBFFI_SOURCE_DIR}\"
  CONFIGURE_COMMAND ./configure
                    --disable-dependency-tracking
                    --disable-builddir
                    ${SAPI_THIRD_PARTY_CONFIGUREOPTS}
  BUILD_COMMAND     \"\"
  INSTALL_COMMAND   \"\"
  TEST_COMMAND      \"\"
  BUILD_IN_SOURCE TRUE
)
")

execute_process(COMMAND ${CMAKE_COMMAND} -G "${CMAKE_GENERATOR}" .
                RESULT_VARIABLE error
                WORKING_DIRECTORY "${workdir}")
if(error)
  message(FATAL_ERROR "CMake step for ${PROJECT_NAME} failed: ${error}")
endif()

execute_process(COMMAND ${CMAKE_COMMAND} --build .
                RESULT_VARIABLE error
                WORKING_DIRECTORY "${workdir}")
if(error)
  message(FATAL_ERROR "Build step for ${PROJECT_NAME} failed: ${error}")
endif()

set(libffi_INCLUDE_DIR ${SAPI_LIBFFI_SOURCE_DIR}/libffi/include)

if(CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64")
  list(APPEND _ffi_platform_srcs
    ${SAPI_LIBFFI_SOURCE_DIR}/src/x86/asmnames.h
    ${SAPI_LIBFFI_SOURCE_DIR}/src/x86/ffi.c
    ${SAPI_LIBFFI_SOURCE_DIR}/src/x86/ffi64.c
    ${SAPI_LIBFFI_SOURCE_DIR}/src/x86/ffiw64.c
    ${SAPI_LIBFFI_SOURCE_DIR}/src/x86/internal.h
    ${SAPI_LIBFFI_SOURCE_DIR}/src/x86/internal64.h
    ${SAPI_LIBFFI_SOURCE_DIR}/src/x86/sysv.S
    ${SAPI_LIBFFI_SOURCE_DIR}/src/x86/unix64.S
    ${SAPI_LIBFFI_SOURCE_DIR}/src/x86/win64.S
  )
elseif(CMAKE_SYSTEM_PROCESSOR STREQUAL "ppc64")
  list(APPEND _ffi_platform_srcs
    ${SAPI_LIBFFI_SOURCE_DIR}/src/powerpc/ffi.c
    ${SAPI_LIBFFI_SOURCE_DIR}/src/powerpc/ffi_linux64.c
    ${SAPI_LIBFFI_SOURCE_DIR}/src/powerpc/ffi_sysv.c
    ${SAPI_LIBFFI_SOURCE_DIR}/src/powerpc/linux64.S
    ${SAPI_LIBFFI_SOURCE_DIR}/src/powerpc/linux64_closure.S
    ${SAPI_LIBFFI_SOURCE_DIR}/src/powerpc/ppc_closure.S
    ${SAPI_LIBFFI_SOURCE_DIR}/src/powerpc/sysv.S
    # Textual headers
    ${SAPI_LIBFFI_SOURCE_DIR}/src/powerpc/ffi_powerpc.h
    ${SAPI_LIBFFI_SOURCE_DIR}/src/powerpc/asm.h
  )
elseif(CMAKE_SYSTEM_PROCESSOR STREQUAL "aarch64")
  list(APPEND _ffi_platform_srcs
    ${SAPI_LIBFFI_SOURCE_DIR}/src/aarch64/ffi.c
    ${SAPI_LIBFFI_SOURCE_DIR}/src/aarch64/internal.h
    ${SAPI_LIBFFI_SOURCE_DIR}/src/aarch64/sysv.S
  )
endif()

add_library(ffi STATIC
  ${SAPI_LIBFFI_SOURCE_DIR}/fficonfig.h
  ${SAPI_LIBFFI_SOURCE_DIR}/include/ffi.h
  ${SAPI_LIBFFI_SOURCE_DIR}/include/ffi_cfi.h
  ${SAPI_LIBFFI_SOURCE_DIR}/include/ffi_common.h
  ${SAPI_LIBFFI_SOURCE_DIR}/include/ffitarget.h
  ${SAPI_LIBFFI_SOURCE_DIR}/src/closures.c
  ${SAPI_LIBFFI_SOURCE_DIR}/src/debug.c
  ${SAPI_LIBFFI_SOURCE_DIR}/src/java_raw_api.c
  ${SAPI_LIBFFI_SOURCE_DIR}/src/prep_cif.c
  ${SAPI_LIBFFI_SOURCE_DIR}/src/raw_api.c
  ${SAPI_LIBFFI_SOURCE_DIR}/src/types.c
  ${_ffi_platform_srcs}
)
add_library(libffi::libffi ALIAS ffi)
target_include_directories(ffi PUBLIC
  ${SAPI_LIBFFI_SOURCE_DIR}
  ${SAPI_LIBFFI_SOURCE_DIR}/include
)
target_compile_options(ffi PRIVATE
  -Wno-vla
  -Wno-unused-result
)
target_link_libraries(ffi PRIVATE
  sapi::base
)


<|start_filename|>cmake/SapiOptions.cmake<|end_filename|>
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# These options determine whether CMake should download the libraries that
# Sandboxed API depends on at configure time.
# The CMake script SapiDeps.cmake checks for the presence of certain build
# targets to determine whether a library can be used. Disabling the options
# below enables embedding projects to selectively override/replace these
# dependencies. This is useful for cases where embedding projects already
# depend on some of these libraries (e.g. Abseil).
option(SAPI_DOWNLOAD_ABSL "Download Abseil at config time" ON)
option(SAPI_DOWNLOAD_GOOGLETEST "Download googletest at config time" ON)
option(SAPI_DOWNLOAD_BENCHMARK "Download benchmark at config time" ON)
option(SAPI_DOWNLOAD_GFLAGS "Download gflags at config time" ON)
option(SAPI_DOWNLOAD_GLOG "Download glog at config time" ON)
option(SAPI_DOWNLOAD_PROTOBUF "Download protobuf at config time" ON)
option(SAPI_DOWNLOAD_LIBUNWIND "Download libunwind at config time" ON)
option(SAPI_DOWNLOAD_LIBCAP "Download libcap at config time" ON)
option(SAPI_DOWNLOAD_LIBFFI "Download libffi at config time" ON)

# Options for building examples
option(SAPI_ENABLE_EXAMPLES "Build example code" ON)
option(SAPI_DOWNLOAD_ZLIB "Download zlib at config time (only if SAPI_ENABLE_EXAMPLES is set)" ON)

option(SAPI_ENABLE_TESTS "Build unit tests" ON)
option(SAPI_ENABLE_GENERATOR "Build Clang based code generator from source" OFF)

# This flag should be only enabled for embedded and resource-constrained
# environments
option(SAPI_ENABLE_SHARED_LIBS "Build SAPI shared libs" OFF)

option(SAPI_HARDENED_SOURCE "Build with hardening compiler options" OFF)

option(SAPI_FORCE_COLOR_OUTPUT "Force colored compiler diagnostics when using Ninja" ON)


<|start_filename|>oss-internship-2020/libarchive/test/minitar_test.cc<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <fstream>

#include "sapi_minitar.h"  // NOLINT(build/include)
#include "gtest/gtest.h"
#include "sandboxed_api/sandbox2/util.h"
#include "sandboxed_api/util/fileops.h"
#include "sandboxed_api/util/path.h"
#include "sandboxed_api/util/status_matchers.h"

namespace {

using ::sandbox2::util::VecStringToCharPtrArr;
using ::sapi::IsOk;
using ::sapi::file::JoinPath;
using ::sapi::file_util::fileops::Exists;
using ::testing::Eq;
using ::testing::IsTrue;
using ::testing::StrEq;

// We will use a fixture class for testing which allows us to override the
// SetUp and TearDown functions. Also, data that needs to be initialized
// or destroyed only once (the test files and directories) will be handled
// in the SetUpTestSuite and TearDownTestSuite functions which are executed
// only once.
// All of the testing data will be placed in a temporary directory and each
// test will have it's own temporary directory. At the end of each test
// and all of the tests, the temporary data is deleted.
class MiniTarTest : public ::testing::Test {
 protected:
  // Before running the tests, we create a temporary directory which will
  // store generated files and directories used for testing.
  // The directory will look as follows:
  // -file1
  // -dir1 - file2
  //       - dir2 - file3
  static void SetUpTestSuite() {
    absl::StatusOr<std::string> tmp_status = CreateTempDirAtCWD();
    ASSERT_THAT(tmp_status, IsOk());
    data_dir_ = new std::string(std::move(tmp_status).value());

    init_wd_ = new std::string(sandbox2::file_util::fileops::GetCWD());
    ASSERT_THAT(Exists(data_dir_, false), IsTrue())
        << "Test data directory was not created";
    ASSERT_THAT(chdir(data_dir_.data()), Eq(0))
        << "Could not chdir into test data directory";

    CreateAndWriteToFile(kFile1);
    ASSERT_THAT(mkdir(kDir1.data(), 0755), Eq(0)) << "Could not create dir1";
    CreateAndWriteToFile(kFile2);
    ASSERT_THAT(mkdir(kDir2.data(), 0755), Eq(0)) << "Could not create dir2";
    CreateAndWriteToFile(kFile3);

    test_count_ = 0;
  }

  static void TearDownTestSuite() {
    // The tests have the data directory as their working directory at the end
    // so we move to the initial working directory in order to not delete the
    // directory that we are inside of.
    ASSERT_THAT(chdir(init_wd_->data()), Eq(0))
        << "Could not chdir into initial working directory";
    EXPECT_THAT(sandbox2::file_util::fileops::DeleteRecursively(*data_dir_),
                IsTrue)
        << "Error during test data deletion";
    delete init_wd_;
    delete data_dir_;
  }

  void SetUp() override {
    // We use a unique id based on test count to make sure that files created
    // during tests do not overlap.
    id_ = "test" + std::to_string(test_count_);

    absl::StatusOr<std::string> tmp_status = CreateTempDirAtCWD();
    ASSERT_THAT(tmp_status, IsOk());
    tmp_dir_ = tmp_status.value();

    ASSERT_THAT(Exists(tmp_dir_, false), IsTrue)
        << "Could not create test specific temporary directory";
    ASSERT_THAT(chdir(data_dir_->data()), Eq(0))
        << "Could not chdir into test data directory";
  }

  void TearDown() override {
    // Move to another directory before deleting the temporary folder.
    ASSERT_THAT(chdir(data_dir_->data()), Eq(0))
        << "Could not chdir into test data directory";

    EXPECT_THAT(sandbox2::file_util::fileops::DeleteRecursively(tmp_dir_),
                IsTrue)
        << "Error during test temporary directory deletion";
    ++test_count_;
  }

  // Creates the file specified and writes the same filename.
  // This is done in order to not have completely empty files for the
  // archiving step.
  static void CreateAndWriteToFile(absl::string_view file) {
    std::ofstream fin(file.data());
    ASSERT_THAT(fin.is_open(), IsTrue()) << "Could not create" << file;
    fin << file;
    fin.close();
  }

  // Checks if the files exists and if the contents are correct.
  // In these tests, each file contains the relative path from the test
  // directory.
  // Example: dir1/dir2/file3 will contain dir1/dir2/file3.
  // What the files contain does not matter as much, the only important thing
  // is that they are not empty so we can check if the contents are preserved.
  static void CheckFile(const std::string& file) {
    ASSERT_THAT(Exists(file, false), IsTrue()) << "Could not find " << file;
    std::ifstream fin(file);
    ASSERT_THAT(fin.is_open(), IsTrue()) << "Error when opening " << file;

    std::string file_contents((std::istreambuf_iterator<char>(fin)),
                              std::istreambuf_iterator<char>());

    EXPECT_THAT(file_contents, StrEq(file))
        << "Contents of " << file << " are different after extraction";
    fin.close();
  }

  static int test_count_;
  static std::string* data_dir_;
  static std::string* init_wd_;
  std::string tmp_dir_;
  std::string id_;

  static constexpr absl::string_view kFile1 = "file1";
  static constexpr absl::string_view kFile2 = "dir1/file2";
  static constexpr absl::string_view kFile3 = "dir1/dir2/file3";
  static constexpr absl::string_view kDir1 = "dir1";
  static constexpr absl::string_view kDir2 = "dir1/dir2";
};

int MiniTarTest::test_count_;
std::string* MiniTarTest::data_dir_;
std::string* MiniTarTest::init_wd_;

// The tests have the following pattern:
// 1) From inside the test data directory, call the create function with
// different arguments.
// 2) Move to the test specific temporary directory created during the
// set up phase.
// 3) Extract the archive created at step 1.
// 4) Check that the files in the archive have been extracted correctly
// by first checking if they exist and then checking if the content is the
// same as in the original file.
TEST_F(MiniTarTest, TestFileSimple) {
  std::vector<std::string> v = {kFile1.data()};

  ASSERT_THAT(CreateArchive(id_.data(), 0, VecStringToCharPtrArr(v), false),
              IsOk());

  ASSERT_THAT(chdir(tmp_dir_.data()), Eq(0))
      << "Could not chdir into test data directory";

  ASSERT_THAT(ExtractArchive(JoinPath(*data_dir_, id_).data(), 1, 0, false),
              IsOk());

  CheckFile(std::string(kFile1));
}

TEST_F(MiniTarTest, TestMultipleFiles) {
  std::vector<std::string> v = {kFile1.data(), kFile2.data(), kFile3.data()};
  ASSERT_THAT(CreateArchive(id_.data(), 0, VecStringToCharPtrArr(v), false),
              IsOk());
  ASSERT_THAT(Exists(id_.data(), false), IsTrue())
      << "Archive file was not created";

  ASSERT_THAT(chdir(tmp_dir_.data()), Eq(0))
      << "Could not chdir into test data directory";

  ASSERT_THAT(ExtractArchive(JoinPath(*data_dir_, id_).data(), 1, 0, false),
              IsOk());

  CheckFile(std::string(kFile1));
  CheckFile(std::string(kFile2));
  CheckFile(std::string(kFile3));
}

TEST_F(MiniTarTest, TestDirectorySimple) {
  std::vector<std::string> v = {kDir2.data()};
  ASSERT_THAT(CreateArchive(id_.data(), 0, VecStringToCharPtrArr(v), false),
              IsOk());

  ASSERT_THAT(chdir(tmp_dir_.data()), Eq(0))
      << "Could not chdir into test data directory";

  ASSERT_THAT(ExtractArchive(JoinPath(*data_dir_, id_).data(), 1, 0, false),
              IsOk());

  CheckFile(std::string(kFile3));
}

TEST_F(MiniTarTest, TestDirectoryNested) {
  std::vector<std::string> v = {kDir1.data()};
  ASSERT_THAT(CreateArchive(id_.data(), 0, VecStringToCharPtrArr(v), false),
              IsOk());

  ASSERT_THAT(chdir(tmp_dir_.data()), Eq(0))
      << "Could not chdir into test data directory";

  ASSERT_THAT(ExtractArchive(JoinPath(*data_dir_, id_).data(), 1, 0, false),
              IsOk());

  CheckFile(std::string(kFile2));
  CheckFile(std::string(kFile3));
}

TEST_F(MiniTarTest, TestComplex) {
  std::vector<std::string> v = {kFile1.data(), kDir1.data()};
  ASSERT_THAT(CreateArchive(id_.data(), 0, VecStringToCharPtrArr(v), false),
              IsOk());

  ASSERT_THAT(chdir(tmp_dir_.data()), Eq(0))
      << "Could not chdir into test data directory";

  ASSERT_THAT(ExtractArchive(JoinPath(*data_dir_, id_).data(), 1, 0, false),
              IsOk());

  CheckFile(std::string(kFile1));
  CheckFile(std::string(kFile2));
  CheckFile(std::string(kFile3));
}

TEST_F(MiniTarTest, TestCompress) {
  std::vector<std::string> v = {kFile1.data(), kDir1.data()};
  int compress = 'Z';
  ASSERT_THAT(
      CreateArchive(id_.data(), compress, VecStringToCharPtrArr(v), false),
      IsOk());

  ASSERT_THAT(chdir(tmp_dir_.data()), Eq(0))
      << "Could not chdir into test data directory";
  ASSERT_THAT(ExtractArchive(JoinPath(*data_dir_, id_).data(), 1, 0, false),
              IsOk());

  CheckFile(std::string(kFile1));
  CheckFile(std::string(kFile2));
  CheckFile(std::string(kFile3));
}

TEST_F(MiniTarTest, TestGZIP) {
  std::vector<std::string> v = {kFile1.data(), kDir1.data()};
  int compress = 'z';
  ASSERT_THAT(
      CreateArchive(id_.data(), compress, VecStringToCharPtrArr(v), false),
      IsOk());

  ASSERT_THAT(chdir(tmp_dir_.data()), Eq(0))
      << "Could not chdir into test data directory";
  ASSERT_THAT(ExtractArchive(JoinPath(*data_dir_, id_).data(), 1, 0, false),
              IsOk());

  CheckFile(std::string(kFile1));
  CheckFile(std::string(kFile2));
  CheckFile(std::string(kFile3));
}

TEST_F(MiniTarTest, TestBZIP2) {
  std::vector<std::string> v = {kFile1.data(), kDir1.data()};
  int compress = 'j';
  ASSERT_THAT(
      CreateArchive(id_.data(), compress, VecStringToCharPtrArr(v), false),
      IsOk());

  ASSERT_THAT(chdir(tmp_dir_.data()), Eq(0))
      << "Could not chdir into test data directory";
  ASSERT_THAT(ExtractArchive(JoinPath(*data_dir_, id_).data(), 1, 0, false),
              IsOk());

  CheckFile(std::string(kFile1));
  CheckFile(std::string(kFile2));
  CheckFile(std::string(kFile3));
}

TEST_F(MiniTarTest, TestPaths) {
  // These should be equivalent to kFile1 and kDir1 after cleaning.
  std::vector<std::string> v = {JoinPath("a/b/../../c/../", kFile1).data(),
                                JoinPath("d/../e/././///../", kDir1).data()};
  ASSERT_THAT(CreateArchive(id_.data(), 0, VecStringToCharPtrArr(v), false),
              IsOk());

  ASSERT_THAT(chdir(tmp_dir_.data()), Eq(0))
      << "Could not chdir into test data directory";
  ASSERT_THAT(ExtractArchive(JoinPath(*data_dir_, id_).data(), 1, 0, false),
              IsOk());

  CheckFile(std::string(kFile1));
  CheckFile(std::string(kFile2));
  CheckFile(std::string(kFile3));
}

}  // namespace


<|start_filename|>oss-internship-2020/jsonnet/tests/jsonnet_tests_utils.cc<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "jsonnet_tests.h"  // NOLINT(build/include)

// Prepares what is needed to perform a test.
void JsonnetTestHelper::TestSetUp() {
  // Get paths to where input and output is stored.
  char buffer[256];
  int error = readlink("/proc/self/exe", buffer, 256);
  ASSERT_GE(error, 0);

  std::pair<absl::string_view, absl::string_view> parts_of_path =
      sandbox2::file::SplitPath(buffer);
  absl::string_view binary_path = parts_of_path.first;

  std::string input_path =
      sandbox2::file::JoinPath(binary_path, "tests_input", "dummy_input");
  std::string output_path =
      sandbox2::file::JoinPath(binary_path, "tests_output", "dummy_input");

  // Set up sandbox and api.
  sandbox_ = absl::make_unique<JsonnetBaseSandbox>(input_path, output_path);
  ASSERT_THAT(sandbox_->Init(), sapi::IsOk());
  api_ = absl::make_unique<JsonnetApi>(sandbox_.get());

  // Initialize library's main structure.
  SAPI_ASSERT_OK_AND_ASSIGN(JsonnetVm * vm_ptr, api_->c_jsonnet_make());
  vm_ = absl::make_unique<sapi::v::RemotePtr>(vm_ptr);

  jsonnet_vm_was_used_ = false;
  input_was_read_ = false;
}

// Cleans up after a test.
void JsonnetTestHelper::TestTearDown() {
  if (jsonnet_vm_was_used_) {
    SAPI_ASSERT_OK_AND_ASSIGN(
        char* result, api_->c_jsonnet_realloc(vm_.get(), output_.get(), 0));
  }
  ASSERT_THAT(api_->c_jsonnet_destroy(vm_.get()), sapi::IsOk());
  if (input_was_read_) {
    ASSERT_THAT(api_->c_free_input(input_.get()), sapi::IsOk());
  }
}

// Reads input from file.
void JsonnetTestHelper::ReadInput(const char* filename) {
  std::string in_file_in_sandboxee(std::string("/input/") +
                                   basename(const_cast<char*>(&filename[0])));
  input_filename_in_sandboxee_ = std::move(in_file_in_sandboxee);
  sapi::v::ConstCStr in_file_var(input_filename_in_sandboxee_.c_str());

  SAPI_ASSERT_OK_AND_ASSIGN(char* input_ptr,
                            api_->c_read_input(0, in_file_var.PtrBefore()));
  input_ = absl::make_unique<sapi::v::RemotePtr>(input_ptr);

  input_was_read_ = true;
}

// Evaluates jsonnet code.
void JsonnetTestHelper::Evaluate_jsonnet_code(Evaluation type,
                                              bool expected_correct) {
  sapi::v::ConstCStr in_file_var(input_filename_in_sandboxee_.c_str());
  sapi::v::Int error;
  char* output_ptr;

  switch (type) {
    case kBase: {
      SAPI_ASSERT_OK_AND_ASSIGN(
          output_ptr,
          api_->c_jsonnet_evaluate_snippet(vm_.get(), in_file_var.PtrBefore(),
                                           input_.get(), error.PtrAfter()));
      break;
    }

    case kMultipleFiles: {
      SAPI_ASSERT_OK_AND_ASSIGN(
          output_ptr, api_->c_jsonnet_evaluate_snippet_multi(
                          vm_.get(), in_file_var.PtrBefore(), input_.get(),
                          error.PtrAfter()));
      break;
    }

    case kYamlStream: {
      SAPI_ASSERT_OK_AND_ASSIGN(
          output_ptr, api_->c_jsonnet_evaluate_snippet_stream(
                          vm_.get(), in_file_var.PtrBefore(), input_.get(),
                          error.PtrAfter()));
      break;
    }
  }

  if (expected_correct) {
    ASSERT_THAT(error.GetValue(), testing::Eq(0));
  } else {
    ASSERT_THAT(error.GetValue(), testing::Eq(1));
  }

  output_ = absl::make_unique<sapi::v::RemotePtr>(output_ptr);

  jsonnet_vm_was_used_ = true;
}

// Writes output to file.
void JsonnetTestHelper::WriteOutput(const char* filename_or_directory,
                                    Evaluation type) {
  bool success;

  switch (type) {
    case kBase: {
      std::string out_file_in_sandboxee(
          std::string("/output/") +
          basename(const_cast<char*>(&filename_or_directory[0])));
      sapi::v::ConstCStr out_file_var(out_file_in_sandboxee.c_str());

      SAPI_ASSERT_OK_AND_ASSIGN(
          success,
          api_->c_write_output_file(output_.get(), out_file_var.PtrBefore()));
      break;
    }
    case kMultipleFiles: {
      std::string out_file_in_sandboxee(std::string("/output/"));
      sapi::v::ConstCStr out_file_var(out_file_in_sandboxee.c_str());
      SAPI_ASSERT_OK_AND_ASSIGN(
          success, api_->c_write_multi_output_files(
                       output_.get(), out_file_var.PtrBefore(), false));
      break;
    }

    case kYamlStream: {
      std::string out_file_in_sandboxee(
          std::string("/output/") +
          basename(const_cast<char*>(&filename_or_directory[0])));
      sapi::v::ConstCStr out_file_var(out_file_in_sandboxee.c_str());
      SAPI_ASSERT_OK_AND_ASSIGN(
          success,
          api_->c_write_output_stream(output_.get(), out_file_var.PtrBefore()));
      break;
    }
  }

  ASSERT_THAT(success, testing::Eq(true));
}

// Reads the output written to a file by library function / expected output
std::string JsonnetTestHelper::ReadOutput(const char* filename) {
  std::ifstream input_stream(filename);
  std::string contents((std::istreambuf_iterator<char>(input_stream)),
                       std::istreambuf_iterator<char>());
  return contents;
}


<|start_filename|>oss-internship-2020/guetzli/guetzli_transaction_test.cc<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "guetzli_transaction.h"  // NOLINT(build/include)

#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include <fstream>
#include <memory>
#include <sstream>

#include "gtest/gtest.h"

namespace guetzli::sandbox::tests {

namespace {

constexpr absl::string_view kInPngFilename = "bees.png";
constexpr absl::string_view kInJpegFilename = "nature.jpg";
constexpr absl::string_view kOutJpegFilename = "out_jpeg.jpg";
constexpr absl::string_view kOutPngFilename = "out_png.png";
constexpr absl::string_view kPngReferenceFilename = "bees_reference.jpg";
constexpr absl::string_view kJpegReferenceFIlename = "nature_reference.jpg";

constexpr int kPngExpectedSize = 38'625;
constexpr int kJpegExpectedSize = 10'816;

constexpr int kDefaultQualityTarget = 95;
constexpr int kDefaultMemlimitMb = 6000;

constexpr absl::string_view kRelativePathToTestdata =
    "/guetzli_sandboxed/testdata/";

std::string GetPathToFile(absl::string_view filename) {
  return absl::StrCat(getenv("TEST_SRCDIR"), kRelativePathToTestdata, filename);
}

std::string ReadFromFile(const std::string& filename) {
  std::ifstream stream(filename, std::ios::binary);

  if (!stream.is_open()) {
    return "";
  }

  std::stringstream result;
  result << stream.rdbuf();
  return result.str();
}

// Helper class to delete file after opening
class FileRemover {
 public:
  explicit FileRemover(const char* path)
      : path_(path), fd_(open(path, O_RDONLY)) {}

  ~FileRemover() {
    close(fd_);
    remove(path_);
  }

  int get() const { return fd_; }

 private:
  const char* path_;
  int fd_;
};

}  // namespace

TEST(GuetzliTransactionTest, TestTransactionJpg) {
  std::string in_path = GetPathToFile(kInJpegFilename);
  std::string out_path = GetPathToFile(kOutJpegFilename);

  TransactionParams params = {in_path.c_str(), out_path.c_str(), 0,
                              kDefaultQualityTarget, kDefaultMemlimitMb};
  {
    GuetzliTransaction transaction(std::move(params));
    absl::Status result = transaction.Run();

    ASSERT_TRUE(result.ok()) << result.ToString();
  }
  std::string reference_data =
      ReadFromFile(GetPathToFile(kJpegReferenceFIlename));
  FileRemover file_remover(out_path.c_str());
  ASSERT_TRUE(file_remover.get() != -1) << "Error opening output file";
  off_t output_size = lseek(file_remover.get(), 0, SEEK_END);
  ASSERT_EQ(reference_data.size(), output_size)
      << "Different sizes of reference and returned data";
  ASSERT_EQ(lseek(file_remover.get(), 0, SEEK_SET), 0)
      << "Error repositioning out file";

  std::string output;
  output.resize(output_size);
  ssize_t status = read(file_remover.get(), output.data(), output_size);
  ASSERT_EQ(status, output_size) << "Error reading data from temp output file";

  ASSERT_EQ(output, reference_data) << "Returned data doesn't match reference";
}

TEST(GuetzliTransactionTest, TestTransactionPng) {
  std::string in_path = GetPathToFile(kInPngFilename);
  std::string out_path = GetPathToFile(kOutPngFilename);

  TransactionParams params = {in_path.c_str(), out_path.c_str(), 0,
                              kDefaultQualityTarget, kDefaultMemlimitMb};
  {
    GuetzliTransaction transaction(std::move(params));
    absl::Status result = transaction.Run();

    ASSERT_TRUE(result.ok()) << result.ToString();
  }
  std::string reference_data =
      ReadFromFile(GetPathToFile(kPngReferenceFilename));
  FileRemover file_remover(out_path.c_str());
  ASSERT_TRUE(file_remover.get() != -1) << "Error opening output file";
  off_t output_size = lseek(file_remover.get(), 0, SEEK_END);
  ASSERT_EQ(reference_data.size(), output_size)
      << "Different sizes of reference and returned data";
  ASSERT_EQ(lseek(file_remover.get(), 0, SEEK_SET), 0)
      << "Error repositioning out file";

  std::string output;
  output.resize(output_size);
  ssize_t status = read(file_remover.get(), output.data(), output_size);
  ASSERT_EQ(status, output_size) << "Error reading data from temp output file";

  ASSERT_EQ(output, reference_data) << "Returned data doesn't match refernce";
}

}  // namespace guetzli::sandbox::tests


<|start_filename|>oss-internship-2020/guetzli/guetzli_sandboxed.cc<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <cstdio>
#include <iostream>

#include "guetzli_transaction.h"  // NOLINT(build/include)
#include "sandboxed_api/util/fileops.h"

namespace {

constexpr int kDefaultJPEGQuality = 95;
constexpr int kDefaultMemlimitMB = 6000;

void Usage() {
  fprintf(stderr,
          "Guetzli JPEG compressor. Usage: \n"
          "guetzli [flags] input_filename output_filename\n"
          "\n"
          "Flags:\n"
          "  --verbose    - Print a verbose trace of all attempts to standard "
          "output.\n"
          "  --quality Q  - Visual quality to aim for, expressed as a JPEG "
          "quality value.\n"
          "                 Default value is %d.\n"
          "  --memlimit M - Memory limit in MB. Guetzli will fail if unable to "
          "stay under\n"
          "                 the limit. Default limit is %d MB.\n"
          "  --nomemlimit - Do not limit memory usage.\n",
          kDefaultJPEGQuality, kDefaultMemlimitMB);
  exit(1);
}

}  // namespace

int main(int argc, const char** argv) {
  int verbose = 0;
  int quality = kDefaultJPEGQuality;
  int memlimit_mb = kDefaultMemlimitMB;

  int opt_idx = 1;
  for (; opt_idx < argc; opt_idx++) {
    if (strnlen(argv[opt_idx], 2) < 2 || argv[opt_idx][0] != '-' ||
        argv[opt_idx][1] != '-')
      break;

    if (!strcmp(argv[opt_idx], "--verbose")) {
      verbose = 1;
    } else if (!strcmp(argv[opt_idx], "--quality")) {
      opt_idx++;
      if (opt_idx >= argc) Usage();
      quality = atoi(argv[opt_idx]);  // NOLINT(runtime/deprecated_fn)
    } else if (!strcmp(argv[opt_idx], "--memlimit")) {
      opt_idx++;
      if (opt_idx >= argc) Usage();
      memlimit_mb = atoi(argv[opt_idx]);  // NOLINT(runtime/deprecated_fn)
    } else if (!strcmp(argv[opt_idx], "--nomemlimit")) {
      memlimit_mb = -1;
    } else if (!strcmp(argv[opt_idx], "--")) {
      opt_idx++;
      break;
    } else {
      fprintf(stderr, "Unknown commandline flag: %s\n", argv[opt_idx]);
      Usage();
    }
  }

  if (argc - opt_idx != 2) {
    Usage();
  }

  guetzli::sandbox::TransactionParams params = {
      argv[opt_idx], argv[opt_idx + 1], verbose, quality, memlimit_mb};

  guetzli::sandbox::GuetzliTransaction transaction(std::move(params));
  auto result = transaction.Run();

  if (!result.ok()) {
    std::cerr << result.ToString() << std::endl;
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}


<|start_filename|>oss-internship-2020/gdal/raster_to_gtiff/gtiff_converter.cc<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "gtiff_converter.h"  // NOLINT(build/include)

#include "sandboxed_api/util/fileops.h"

namespace gdal::sandbox {

namespace {

inline constexpr absl::string_view kDriverName = "GTiff";

}  // namespace

RasterToGTiffProcessor::RasterToGTiffProcessor(std::string out_file_full_path,
                                               std::string proj_db_path,
                                               parser::RasterDataset data,
                                               int retry_count)
    : sapi::Transaction(std::make_unique<GdalSapiSandbox>(
          sandbox2::file_util::fileops::StripBasename(out_file_full_path),
          std::move(proj_db_path))),
      out_file_full_path_(std::move(out_file_full_path)),
      data_(std::move(data)) {
  set_retry_count(retry_count);
  SetTimeLimit(absl::InfiniteDuration());
}

absl::Status RasterToGTiffProcessor::Main() {
  GdalApi api(sandbox());
  SAPI_RETURN_IF_ERROR(api.GDALAllRegister());

  sapi::v::CStr driver_name_ptr(kDriverName);

  SAPI_ASSIGN_OR_RETURN(absl::StatusOr<GDALDriverH> driver,
                        api.GDALGetDriverByName(driver_name_ptr.PtrBefore()));

  TRANSACTION_FAIL_IF_NOT(driver.value() != nullptr,
                          "Error getting GTiff driver");
  sapi::v::RemotePtr driver_ptr(driver.value());

  sapi::v::ConstCStr out_file_full_path_ptr(out_file_full_path_.c_str());
  sapi::v::NullPtr create_options;

  GDALDataType type = data_.bands.size() > 0
                          ? static_cast<GDALDataType>(data_.bands[0].data_type)
                          : GDALDataType::GDT_Unknown;

  SAPI_ASSIGN_OR_RETURN(
      absl::StatusOr<GDALDatasetH> dataset,
      api.GDALCreate(&driver_ptr, out_file_full_path_ptr.PtrBefore(),
                     data_.width, data_.height, data_.bands.size(), type,
                     &create_options));

  TRANSACTION_FAIL_IF_NOT(dataset.value(), "Error creating dataset");
  sapi::v::RemotePtr dataset_ptr(dataset.value());

  int current_band = 1;
  for (auto& band_data : data_.bands) {
    SAPI_ASSIGN_OR_RETURN(absl::StatusOr<GDALRasterBandH> band,
                          api.GDALGetRasterBand(&dataset_ptr, current_band));
    TRANSACTION_FAIL_IF_NOT(band.value() != nullptr,
                            "Error getting band from dataset");
    sapi::v::RemotePtr band_ptr(band.value());

    sapi::v::Array<int> data_array(band_data.data.data(),
                                   band_data.data.size());

    SAPI_ASSIGN_OR_RETURN(
        absl::StatusOr<CPLErr> result,
        api.GDALRasterIO(&band_ptr, GF_Write, 0, 0, band_data.width,
                         band_data.height, data_array.PtrBefore(),
                         band_data.width, band_data.height, GDT_Int32, 0, 0));

    TRANSACTION_FAIL_IF_NOT(result.value() == CPLErr::CE_None,
                            "Error writing band to dataset");

    SAPI_ASSIGN_OR_RETURN(
        result,
        api.GDALSetRasterColorInterpretation(
            &band_ptr, static_cast<GDALColorInterp>(band_data.color_interp)));

    TRANSACTION_FAIL_IF_NOT(result.value() == CPLErr::CE_None,
                            "Error setting color interpretation");

    if (band_data.no_data_value.has_value()) {
      SAPI_ASSIGN_OR_RETURN(result,
                            api.GDALSetRasterNoDataValue(
                                &band_ptr, band_data.no_data_value.value()));

      TRANSACTION_FAIL_IF_NOT(result.value() == CPLErr::CE_None,
                              "Error setting no data value for the band");
    }

    ++current_band;
  }

  if (data_.wkt_projection.length() > 0) {
    sapi::v::ConstCStr wkt_projection_ptr(data_.wkt_projection.c_str());
    SAPI_ASSIGN_OR_RETURN(
        absl::StatusOr<CPLErr> result,
        api.GDALSetProjection(&dataset_ptr, wkt_projection_ptr.PtrBefore()));
    TRANSACTION_FAIL_IF_NOT(result.value() == CPLErr::CE_None,
                            "Error setting wkt projection");
  }

  if (data_.geo_transform.size() > 0) {
    sapi::v::Array<double> geo_transform_ptr(data_.geo_transform.data(),
                                             data_.geo_transform.size());
    SAPI_ASSIGN_OR_RETURN(
        absl::StatusOr<CPLErr> result,
        api.GDALSetGeoTransform(&dataset_ptr, geo_transform_ptr.PtrBefore()));

    TRANSACTION_FAIL_IF_NOT(result.value() == CPLErr::CE_None,
                            "Error setting geo transform");
  }

  SAPI_RETURN_IF_ERROR(api.GDALClose(&dataset_ptr));

  return absl::OkStatus();
}

}  // namespace gdal::sandbox


<|start_filename|>oss-internship-2020/gdal/raster_to_gtiff/gtiff_converter.h<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef RASTER_TO_GTIFF_GTIFF_CONVERTER_H_
#define RASTER_TO_GTIFF_GTIFF_CONVERTER_H_

#include <string>

#include "gdal_sandbox.h"     // NOLINT(build/include)
#include "get_raster_data.h"  // NOLINT(build/include)
#include "sandboxed_api/transaction.h"

namespace gdal::sandbox {

class RasterToGTiffProcessor : public sapi::Transaction {
 public:
  RasterToGTiffProcessor(std::string out_file_full_path,
                         std::string proj_db_path, parser::RasterDataset data,
                         int retry_count = 0);

 private:
  absl::Status Main() final;

  const std::string out_file_full_path_;
  parser::RasterDataset data_;
};

}  // namespace gdal::sandbox

#endif  // RASTER_TO_GTIFF_GTIFF_CONVERTER_H_


<|start_filename|>oss-internship-2020/libuv/callbacks/callbacks.cc<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "callbacks.h"  // NOLINT(build/include)

#include <iostream>

size_t g_iterations = 0;
size_t constexpr kMaxIterations = 1'000'000;
static char g_buffer[1024];
static uv_buf_t g_iov;

// Stop the handle if the methods was called kMaxIterations times
void IdleCallback(uv_idle_t* handle) {
  ++g_iterations;
  if (g_iterations > kMaxIterations) {
    std::cout << "IdleCallback was called " << kMaxIterations << " times"
              << std::endl;
    uv_idle_stop(handle);
  }
}

// Called after some chars have been written
// As soon as writing of these bytes is completed, read more
void OnWrite(uv_fs_t* req) {
  if (req->result < 0) {
    std::cerr << "Write error: " << uv_strerror(static_cast<int>(req->result))
              << std::endl;
    return;
  }
  // Start reading more after writing these bytes
  uv_fs_read(uv_default_loop(), &read_req, open_req.result, &g_iov, 1, -1,
             OnRead);
}

// Called after some chars have been read
// As soon as reading of these bytes is completed, write them
void OnRead(uv_fs_t* req) {
  if (req->result < 0) {
    std::cerr << "Read error: " << uv_strerror(req->result) << std::endl;
    return;
  }
  if (req->result == 0) {
    // No more bytes left, close the loop
    uv_fs_t close_req;
    uv_fs_close(uv_default_loop(), &close_req, open_req.result, NULL);
  } else if (req->result > 0) {
    // Start writing after reading some bytes
    g_iov.len = req->result;
    uv_fs_write(uv_default_loop(), &write_req, 1, &g_iov, 1, -1, OnWrite);
  }
}

// Called after the file has been opened
// As soon as opening is completed, read the file
void OnOpen(uv_fs_t* req) {
  if (req != &open_req) {
    std::cerr << "Open error: req != &open_req" << std::endl;
    return;
  }
  if (req->result < 0) {
    std::cerr << "Open error: " << uv_strerror(static_cast<int>(req->result))
              << std::endl;
    return;
  }
  // Initialize uv_buf_t g_buffer
  g_iov = uv_buf_init(g_buffer, sizeof(g_buffer));
  // Start reading after opening
  uv_fs_read(uv_default_loop(), &read_req, req->result, &g_iov, 1, -1, OnRead);
}

// Get the integer pointed by handle->data and increment it by one
// Then close the handle
void TimerCallback(uv_timer_t* handle) {
  int* data = static_cast<int*>(
      uv_handle_get_data(reinterpret_cast<uv_handle_t*>(handle)));
  ++(*data);
  uv_close(reinterpret_cast<uv_handle_t*>(handle), nullptr);
}


<|start_filename|>oss-internship-2020/libuv/tests/test_error.cc<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <linux/futex.h>
#include <uv.h>

#include "gtest/gtest.h"
#include "sandboxed_api/util/flag.h"
#include "sandboxed_api/util/status_matchers.h"
#include "uv_sapi.sapi.h"  // NOLINT(build/include)

namespace {

class UVTestErrorSapiSandbox : public uv::UVSandbox {
 private:
  std::unique_ptr<sandbox2::Policy> ModifyPolicy(
      sandbox2::PolicyBuilder*) override {
    return sandbox2::PolicyBuilder()
        .AllowDynamicStartup()
        .AllowExit()
        .AllowFutexOp(FUTEX_WAKE_PRIVATE)
        .AllowWrite()
        .BuildOrDie();
  }
};

class UVTestError : public ::testing::Test {
 protected:
  void SetUp() override {
    sandbox_ = std::make_unique<UVTestErrorSapiSandbox>();
    ASSERT_THAT(sandbox_->Init(), sapi::IsOk());
    api_ = std::make_unique<uv::UVApi>(sandbox_.get());
  }

  // Check sapi_uv_strerror on error
  void UVStrerror(int error) {
    // Call sapi_uv_strerror
    absl::StatusOr<void*> error_message_ptr = api_->sapi_uv_strerror(error);
    ASSERT_THAT(error_message_ptr, sapi::IsOk());

    // Get error message from the sandboxee
    SAPI_ASSERT_OK_AND_ASSIGN(
        std::string error_message,
        sandbox_->GetCString(sapi::v::RemotePtr{error_message_ptr.value()}));

    // Check that it is equal to expected error message
    ASSERT_EQ(error_message, std::string{uv_strerror(error)});
  }

  // Check sapi_uv_translate_sys_error on error
  void UVTranslateSysError(int error) {
    // Call sapi_uv_translate_sys_error and get error code
    SAPI_ASSERT_OK_AND_ASSIGN(int error_code,
                              api_->sapi_uv_translate_sys_error(error));

    // Check that it is equal to expected error code
    ASSERT_EQ(error_code, uv_translate_sys_error(error));
  }

  std::unique_ptr<UVTestErrorSapiSandbox> sandbox_;
  std::unique_ptr<uv::UVApi> api_;
};

TEST_F(UVTestError, ErrorMessage) {
  // Test sapi_uv_strerror method
  UVStrerror(0);
  UVStrerror(UV_EINVAL);
  UVStrerror(1337);
  UVStrerror(-1337);
}

TEST_F(UVTestError, SystemError) {
  // Test sapi_uv_translate_sys_error method
  UVTranslateSysError(EPERM);
  UVTranslateSysError(EPIPE);
  UVTranslateSysError(EINVAL);
  UVTranslateSysError(UV_EINVAL);
  UVTranslateSysError(UV_ERANGE);
  UVTranslateSysError(UV_EACCES);
  UVTranslateSysError(0);
}

}  // namespace


<|start_filename|>cmake/glog.cmake<|end_filename|>
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Allows use target_link_libraries() with targets in other directories.
if(POLICY CMP0079)
  cmake_policy(SET CMP0079 NEW)
endif()

set(workdir "${CMAKE_BINARY_DIR}/_deps/glog-populate")

set(SAPI_GLOG_GIT_REPOSITORY https://github.com/google/glog.git CACHE STRING "")
set(SAPI_GLOG_GIT_TAG 3ba8976592274bc1f907c402ce22558011d6fc5e
                      CACHE STRING "") # 2020-02-16
set(SAPI_GLOG_SOURCE_DIR "${CMAKE_BINARY_DIR}/_deps/glog-src" CACHE STRING "")
set(SAPI_GLOG_BINARY_DIR "${CMAKE_BINARY_DIR}/_deps/glog-build" CACHE STRING "")

file(WRITE "${workdir}/CMakeLists.txt" "\
cmake_minimum_required(VERSION ${CMAKE_VERSION})
project(glog-populate NONE)
include(ExternalProject)
ExternalProject_Add(glog
  GIT_REPOSITORY    \"${SAPI_GLOG_GIT_REPOSITORY}\"
  GIT_TAG           \"${SAPI_GLOG_GIT_TAG}\"
  SOURCE_DIR        \"${SAPI_GLOG_SOURCE_DIR}\"
  BINARY_DIR        \"${SAPI_GLOG_BINARY_DIR}\"
  CONFIGURE_COMMAND \"\"
  BUILD_COMMAND     \"\"
  INSTALL_COMMAND   \"\"
  TEST_COMMAND      \"\"
)
")

execute_process(COMMAND "${CMAKE_COMMAND}" -G "${CMAKE_GENERATOR}" .
                RESULT_VARIABLE error
                WORKING_DIRECTORY "${workdir}")
if(error)
  message(FATAL_ERROR "CMake step for ${PROJECT_NAME} failed: ${error}")
endif()

execute_process(COMMAND "${CMAKE_COMMAND}" --build .
                RESULT_VARIABLE error
                WORKING_DIRECTORY "${workdir}")
if(error)
  message(FATAL_ERROR "Build step for ${PROJECT_NAME} failed: ${error}")
endif()

set(_sapi_saved_BUILD_TESTING ${BUILD_TESTING})

# Force gflags from subdirectory
set(WITH_GFLAGS FALSE CACHE BOOL "" FORCE)
set(HAVE_LIB_GFLAGS TRUE CACHE STRING "" FORCE)

set(WITH_UNWIND FALSE CACHE BOOL "" FORCE)
set(UNWIND_LIBRARY FALSE)
set(HAVE_PWD_H FALSE)

set(WITH_PKGCONFIG TRUE CACHE BOOL "" FORCE)

set(BUILD_TESTING FALSE)
set(BUILD_SHARED_LIBS ${SAPI_ENABLE_SHARED_LIBS})

add_subdirectory("${SAPI_GLOG_SOURCE_DIR}"
                 "${SAPI_GLOG_BINARY_DIR}" EXCLUDE_FROM_ALL)

target_include_directories(glog PUBLIC
  $<BUILD_INTERFACE:${CMAKE_BINARY_DIR}/_deps/gflags-build/include>
  $<BUILD_INTERFACE:${SAPI_GLOG_BINARY_DIR}>
)
add_library(gflags_nothreads STATIC IMPORTED)
set_target_properties(gflags_nothreads PROPERTIES
  IMPORTED_LOCATION
  "${CMAKE_BINARY_DIR}/_deps/gflags-build/libgflags_nothreads.a")
target_link_libraries(glog PRIVATE
  -Wl,--whole-archive
  gflags_nothreads
  -Wl,--no-whole-archive
)

if(_sapi_saved_BUILD_TESTING)
  set(BUILD_TESTING "${_sapi_saved_BUILD_TESTING}")
endif()


<|start_filename|>oss-internship-2020/guetzli/guetzli_entry_points.cc<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "guetzli_entry_points.h"  // NOLINT(build/include)

#include <sys/stat.h>

#include <algorithm>
#include <cstdio>
#include <iostream>
#include <string>
#include <vector>

#include "guetzli/jpeg_data_reader.h"
#include "guetzli/quality.h"
#include "png.h"  // NOLINT(build/include)
#include "absl/status/statusor.h"
#include "sandboxed_api/util/fileops.h"

namespace {

constexpr int kBytesPerPixel = 350;
constexpr int kLowestMemusageMB = 100;

struct GuetzliInitData {
  std::string in_data;
  guetzli::Params params;
  guetzli::ProcessStats stats;
};

struct ImageData {
  int xsize;
  int ysize;
  std::vector<uint8_t> rgb;
};

sapi::LenValStruct CreateLenValFromData(const void* data, size_t size) {
  void* new_data = malloc(size);
  memcpy(new_data, data, size);
  return {size, new_data};
}

absl::StatusOr<std::string> ReadFromFd(int fd) {
  struct stat file_data;
  int status = fstat(fd, &file_data);

  if (status < 0) {
    return absl::FailedPreconditionError("Error reading input from fd");
  }

  std::string result;
  result.resize(file_data.st_size);
  status = read(fd, result.data(), result.size());

  if (status < 0) {
    return absl::FailedPreconditionError("Error reading input from fd");
  }

  return result;
}

absl::StatusOr<GuetzliInitData> PrepareDataForProcessing(
    const ProcessingParams& processing_params) {
  absl::StatusOr<std::string> input = ReadFromFd(processing_params.remote_fd);

  if (!input.ok()) {
    return input.status();
  }

  guetzli::Params guetzli_params;
  guetzli_params.butteraugli_target = static_cast<float>(
      guetzli::ButteraugliScoreForQuality(processing_params.quality));

  guetzli::ProcessStats stats;

  if (processing_params.verbose) {
    stats.debug_output_file = stderr;
  }

  return GuetzliInitData{std::move(input.value()), guetzli_params, stats};
}

inline uint8_t BlendOnBlack(const uint8_t val, const uint8_t alpha) {
  return (static_cast<int>(val) * static_cast<int>(alpha) + 128) / 255;
}

// Modified version of ReadPNG from original guetzli.cc
absl::StatusOr<ImageData> ReadPNG(const std::string& data) {
  std::vector<uint8_t> rgb;
  int xsize, ysize;
  png_structp png_ptr =
      png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr);
  if (!png_ptr) {
    return absl::FailedPreconditionError(
        "Error reading PNG data from input file");
  }

  png_infop info_ptr = png_create_info_struct(png_ptr);
  if (!info_ptr) {
    png_destroy_read_struct(&png_ptr, nullptr, nullptr);
    return absl::FailedPreconditionError(
        "Error reading PNG data from input file");
  }

  if (setjmp(png_jmpbuf(png_ptr)) != 0) {
    // Ok we are here because of the setjmp.
    png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);
    return absl::FailedPreconditionError(
        "Error reading PNG data from input file");
  }

  std::istringstream memstream(data, std::ios::in | std::ios::binary);
  png_set_read_fn(
      png_ptr, static_cast<void*>(&memstream),
      [](png_structp png_ptr, png_bytep outBytes, png_size_t byteCountToRead) {
        std::istringstream& memstream =
            *static_cast<std::istringstream*>(png_get_io_ptr(png_ptr));

        memstream.read(reinterpret_cast<char*>(outBytes), byteCountToRead);

        if (memstream.eof()) png_error(png_ptr, "unexpected end of data");
        if (memstream.fail()) png_error(png_ptr, "read from memory error");
      });

  // The png_transforms flags are as follows:
  // packing == convert 1,2,4 bit images,
  // strip == 16 -> 8 bits / channel,
  // shift == use sBIT dynamics, and
  // expand == palettes -> rgb, grayscale -> 8 bit images, tRNS -> alpha.
  const unsigned int png_transforms =
      PNG_TRANSFORM_PACKING | PNG_TRANSFORM_EXPAND | PNG_TRANSFORM_STRIP_16;

  png_read_png(png_ptr, info_ptr, png_transforms, nullptr);

  png_bytep* row_pointers = png_get_rows(png_ptr, info_ptr);

  xsize = png_get_image_width(png_ptr, info_ptr);
  ysize = png_get_image_height(png_ptr, info_ptr);
  rgb.resize(3 * xsize * ysize);

  const int components = png_get_channels(png_ptr, info_ptr);
  switch (components) {
    case 1: {
      // GRAYSCALE
      for (int y = 0; y < ysize; ++y) {
        const uint8_t* row_in = row_pointers[y];
        uint8_t* row_out = &rgb[3 * y * xsize];
        for (int x = 0; x < xsize; ++x) {
          const uint8_t gray = row_in[x];
          row_out[3 * x + 0] = gray;
          row_out[3 * x + 1] = gray;
          row_out[3 * x + 2] = gray;
        }
      }
      break;
    }
    case 2: {
      // GRAYSCALE + ALPHA
      for (int y = 0; y < ysize; ++y) {
        const uint8_t* row_in = row_pointers[y];
        uint8_t* row_out = &rgb[3 * y * xsize];
        for (int x = 0; x < xsize; ++x) {
          const uint8_t gray = BlendOnBlack(row_in[2 * x], row_in[2 * x + 1]);
          row_out[3 * x + 0] = gray;
          row_out[3 * x + 1] = gray;
          row_out[3 * x + 2] = gray;
        }
      }
      break;
    }
    case 3: {
      // RGB
      for (int y = 0; y < ysize; ++y) {
        const uint8_t* row_in = row_pointers[y];
        uint8_t* row_out = &rgb[3 * y * xsize];
        memcpy(row_out, row_in, 3 * xsize);
      }
      break;
    }
    case 4: {
      // RGBA
      for (int y = 0; y < ysize; ++y) {
        const uint8_t* row_in = row_pointers[y];
        uint8_t* row_out = &rgb[3 * y * xsize];
        for (int x = 0; x < xsize; ++x) {
          const uint8_t alpha = row_in[4 * x + 3];
          row_out[3 * x + 0] = BlendOnBlack(row_in[4 * x + 0], alpha);
          row_out[3 * x + 1] = BlendOnBlack(row_in[4 * x + 1], alpha);
          row_out[3 * x + 2] = BlendOnBlack(row_in[4 * x + 2], alpha);
        }
      }
      break;
    }
    default:
      png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);
      return absl::FailedPreconditionError(
          "Error reading PNG data from input file");
  }
  png_destroy_read_struct(&png_ptr, &info_ptr, nullptr);

  return ImageData{xsize, ysize, std::move(rgb)};
}

bool CheckMemoryLimitExceeded(int memlimit_mb, int xsize, int ysize) {
  double pixels = static_cast<double>(xsize) * ysize;
  return memlimit_mb != -1 &&
         (pixels * kBytesPerPixel / (1 << 20) > memlimit_mb ||
          memlimit_mb < kLowestMemusageMB);
}

}  // namespace

extern "C" bool ProcessJpeg(const ProcessingParams* processing_params,
                            sapi::LenValStruct* output) {
  auto processing_data = PrepareDataForProcessing(*processing_params);

  if (!processing_data.ok()) {
    std::cerr << processing_data.status().ToString() << std::endl;
    return false;
  }

  guetzli::JPEGData jpg_header;
  if (!guetzli::ReadJpeg(processing_data->in_data, guetzli::JPEG_READ_HEADER,
                         &jpg_header)) {
    std::cerr << "Error reading JPG data from input file" << std::endl;
    return false;
  }

  if (CheckMemoryLimitExceeded(processing_params->memlimit_mb, jpg_header.width,
                               jpg_header.height)) {
    std::cerr << "Memory limit would be exceeded" << std::endl;
    return false;
  }

  std::string out_data;
  if (!guetzli::Process(processing_data->params, &processing_data->stats,
                        processing_data->in_data, &out_data)) {
    std::cerr << "Guezli processing failed" << std::endl;
    return false;
  }

  *output = CreateLenValFromData(out_data.data(), out_data.size());
  return true;
}

extern "C" bool ProcessRgb(const ProcessingParams* processing_params,
                           sapi::LenValStruct* output) {
  auto processing_data = PrepareDataForProcessing(*processing_params);

  if (!processing_data.ok()) {
    std::cerr << processing_data.status().ToString() << std::endl;
    return false;
  }

  auto png_data = ReadPNG(processing_data->in_data);
  if (!png_data.ok()) {
    std::cerr << "Error reading PNG data from input file" << std::endl;
    return false;
  }

  if (CheckMemoryLimitExceeded(processing_params->memlimit_mb, png_data->xsize,
                               png_data->ysize)) {
    std::cerr << "Memory limit would be exceeded" << std::endl;
    return false;
  }

  std::string out_data;
  if (!guetzli::Process(processing_data->params, &processing_data->stats,
                        png_data->rgb, png_data->xsize, png_data->ysize,
                        &out_data)) {
    std::cerr << "Guetzli processing failed" << std::endl;
    return false;
  }

  *output = CreateLenValFromData(out_data.data(), out_data.size());
  return true;
}

extern "C" bool WriteDataToFd(int fd, sapi::LenValStruct* data) {
  return sandbox2::file_util::fileops::WriteToFD(
      fd, static_cast<const char*>(data->data), data->size);
}


<|start_filename|>sandboxed_api/tools/clang_generator/types.cc<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "sandboxed_api/tools/clang_generator/types.h"

#include "absl/strings/str_cat.h"

namespace sapi {
namespace {

bool IsFunctionReferenceType(clang::QualType qual) {
#if LLVM_VERSION_MAJOR >= 9
  return qual->isFunctionReferenceType();
#else
  const auto* ref = qual->getAs<clang::ReferenceType>();
  return ref && ref->getPointeeType()->isFunctionType();
#endif
}

}  // namespace

void TypeCollector::CollectRelatedTypes(clang::QualType qual) {
  if (seen_.count(qual) > 0) {  // contains() is LLVM_VERSION_MAJOR >= 11
    return;
  }
  seen_.insert(qual);

  if (const auto* typedef_type = qual->getAs<clang::TypedefType>()) {
    CollectRelatedTypes(typedef_type->getDecl()->getUnderlyingType());
    collected_.insert(qual);
    return;
  }

  if (qual->isFunctionPointerType() || IsFunctionReferenceType(qual) ||
      qual->isMemberFunctionPointerType()) {
    if (const auto* function_type = qual->getPointeeOrArrayElementType()
                                        ->getAs<clang::FunctionProtoType>()) {
      // Note: Do not add the function type itself, as this will always be a
      //       pointer argument. We only need to collect all its related types.
      CollectRelatedTypes(function_type->getReturnType());
      for (const clang::QualType& param : function_type->getParamTypes()) {
        CollectRelatedTypes(param);
      }
      return;
    }
  }

  if (IsPointerOrReference(qual)) {
    clang::QualType pointee = qual;
    do {
      pointee = pointee->getPointeeType();
    } while (IsPointerOrReference(pointee));
    CollectRelatedTypes(pointee);
    return;
  }

  // C array with specified constant size (i.e. int a[42])?
  if (const clang::ArrayType* array_type = qual->getAsArrayTypeUnsafe()) {
    CollectRelatedTypes(array_type->getElementType());
    return;
  }

  if (IsSimple(qual) || qual->isEnumeralType()) {
    if (const clang::EnumType* enum_type = qual->getAs<clang::EnumType>()) {
      // Collect the underlying integer type of enum classes as well, as it may
      // be a typedef.
      if (const clang::EnumDecl* decl = enum_type->getDecl(); decl->isFixed()) {
        CollectRelatedTypes(decl->getIntegerType());
      }
    }
    collected_.insert(qual);
    return;
  }

  if (const auto* record_type = qual->getAs<clang::RecordType>()) {
    const clang::RecordDecl* decl = record_type->getDecl();
    for (const clang::FieldDecl* field : decl->fields()) {
      CollectRelatedTypes(field->getType());
    }
    collected_.insert(qual);
    return;
  }
}

namespace {

// Removes "const" from a qualified type if it denotes a pointer or reference
// type.
clang::QualType MaybeRemoveConst(const clang::ASTContext& context,
                                 clang::QualType qual) {
  if (IsPointerOrReference(qual)) {
    clang::QualType pointee_qual = qual->getPointeeType();
    pointee_qual.removeLocalConst();
    qual = context.getPointerType(pointee_qual);
  }
  return qual;
}

}  // namespace

std::string MapQualType(const clang::ASTContext& context,
                        clang::QualType qual) {
  if (const auto* builtin = qual->getAs<clang::BuiltinType>()) {
    switch (builtin->getKind()) {
      case clang::BuiltinType::Void:
      case clang::BuiltinType::NullPtr:
        return "::sapi::v::Void";

      /*
       * Unsigned types
       */
      case clang::BuiltinType::Bool:
        return "::sapi::v::Bool";
      // Unsigned character types
      case clang::BuiltinType::Char_U:
      case clang::BuiltinType::UChar:
        return "::sapi::v::UChar";
      case clang::BuiltinType::WChar_U:
        return "::sapi::v::ULong";  // 32-bit, correct for Linux and UTF-32
      // Added in C++20
      case clang::BuiltinType::Char8:  // Underlying type: unsigned char
        return "::sapi::v::UChar";
      case clang::BuiltinType::Char16:  // Underlying type: uint_least16_t
        return "::sapi::v::UShort";
      case clang::BuiltinType::Char32:  // Underlying type: uint_least32_t
        return "::sapi::v::ULong";
      // Standard unsigned types
      case clang::BuiltinType::UShort:
        return "::sapi::v::UShort";
      case clang::BuiltinType::UInt:
        return "::sapi::v::UInt";
      case clang::BuiltinType::ULong:
        return "::sapi::v::ULong";
      case clang::BuiltinType::ULongLong:
        return "::sapi::v::ULLong";
      // TODO(cblichmann): Add 128-bit integer support
      // case clang::BuiltinType::UInt128:
      //   return "::sapi::v::UInt128";

      /*
       * Signed types
       */
      // Signed character types
      case clang::BuiltinType::Char_S:
      case clang::BuiltinType::SChar:
        return "::sapi::v::Char";
      case clang::BuiltinType::WChar_S:
        return "::sapi::v::Long";  // 32-bit, correct for Linux and UTF-32

      // Standard signed types
      case clang::BuiltinType::Short:
        return "::sapi::v::Short";
      case clang::BuiltinType::Int:
        return "::sapi::v::Int";
      case clang::BuiltinType::Long:
        return "::sapi::v::Long";
      case clang::BuiltinType::LongLong:
        return "::sapi::v::LLong";
      // TODO(cblichmann): Add 128-bit integer support
      // case clang::BuiltinType::Int128:
      //   return "::sapi::v::Int128";

      /*
       * Floating-point types
       */
      // TODO(cblichmann): Map half/__fp16, _Float16 and __float128 types
      case clang::BuiltinType::Float:
        return "::sapi::v::Reg<float>";
      case clang::BuiltinType::Double:
        return "::sapi::v::Reg<double>";
      case clang::BuiltinType::LongDouble:
        return "::sapi::v::Reg<long double>";

      default:
        break;
    }
  } else if (const auto* enum_type = qual->getAs<clang::EnumType>()) {
    return absl::StrCat("::sapi::v::IntBase<",
                        enum_type->getDecl()->getQualifiedNameAsString(), ">");
  } else if (IsPointerOrReference(qual)) {
    // Remove "const" qualifier from a pointer or reference type's pointee, as
    // e.g. const pointers do not work well with SAPI.
    return absl::StrCat("::sapi::v::Reg<",
                        MaybeRemoveConst(context, qual).getAsString(), ">");
  }
  // Best-effort mapping to "int", leave a comment.
  return absl::StrCat("::sapi::v::Int /* aka '", qual.getAsString(), "' */");
}

std::string MapQualTypeParameter(const clang::ASTContext& /*context*/,
                                 clang::QualType qual) {
  // TODO(cblichmann): Define additional mappings, as appropriate
  //   _Bool              -> bool
  //   unsigned long long -> uint64_t (where applicable)
  //   ...
  return IsPointerOrReference(qual) ? "::sapi::v::Ptr*" : qual.getAsString();
}

std::string MapQualTypeReturn(const clang::ASTContext& context,
                              clang::QualType qual) {
  if (qual->isVoidType()) {
    return "absl::Status";
  }
  // Remove const qualifier like in MapQualType().
  return absl::StrCat("absl::StatusOr<",
                      MaybeRemoveConst(context, qual).getAsString(), ">");
}

}  // namespace sapi


<|start_filename|>oss-internship-2020/libarchive/ld_preload_example/minitar.h<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef LIBARCHIVE_LD_PRELOAD_EXAMPLE_MINITAR_H_
#define LIBARCHIVE_LD_PRELOAD_EXAMPLE_MINITAR_H_

#include <archive.h>
#include <archive_entry.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include <iostream>

// The declarations below have been extracted from upstream's minitar.c, hence
// the formatting.
//
// clang-format off

/*
 * NO_CREATE implies NO_BZIP2_CREATE and NO_GZIP_CREATE and NO_COMPRESS_CREATE.
 */
#ifdef NO_CREATE
#undef NO_BZIP2_CREATE
#define NO_BZIP2_CREATE
#undef NO_COMPRESS_CREATE
#define NO_COMPRESS_CREATE
#undef NO_GZIP_CREATE
#define NO_GZIP_CREATE
#endif

/*
 * The combination of NO_BZIP2_CREATE and NO_BZIP2_EXTRACT is
 * equivalent to NO_BZIP2.
 */
#ifdef NO_BZIP2_CREATE
#ifdef NO_BZIP2_EXTRACT
#undef NO_BZIP2
#define NO_BZIP2
#endif
#endif

#ifdef NO_BZIP2
#undef NO_BZIP2_EXTRACT
#define NO_BZIP2_EXTRACT
#undef NO_BZIP2_CREATE
#define NO_BZIP2_CREATE
#endif

/*
 * The combination of NO_COMPRESS_CREATE and NO_COMPRESS_EXTRACT is
 * equivalent to NO_COMPRESS.
 */
#ifdef NO_COMPRESS_CREATE
#ifdef NO_COMPRESS_EXTRACT
#undef NO_COMPRESS
#define NO_COMPRESS
#endif
#endif

#ifdef NO_COMPRESS
#undef NO_COMPRESS_EXTRACT
#define NO_COMPRESS_EXTRACT
#undef NO_COMPRESS_CREATE
#define NO_COMPRESS_CREATE
#endif

/*
 * The combination of NO_GZIP_CREATE and NO_GZIP_EXTRACT is
 * equivalent to NO_GZIP.
 */
#ifdef NO_GZIP_CREATE
#ifdef NO_GZIP_EXTRACT
#undef NO_GZIP
#define NO_GZIP
#endif
#endif

#ifdef NO_GZIP
#undef NO_GZIP_EXTRACT
#define NO_GZIP_EXTRACT
#undef NO_GZIP_CREATE
#define NO_GZIP_CREATE
#endif

#ifndef NO_CREATE
void create(const char *filename, int compress, const char **argv,
            int verbose = 1);
#endif
void errmsg(const char *);
void extract(const char *filename, int do_extract, int flags, int verbose = 1);
int copy_data(struct archive *, struct archive *);
void msg(const char *);
void usage(void);

// clang-format on
#endif  // LIBARCHIVE_LD_PRELOAD_EXAMPLE_MINITAR_H_


<|start_filename|>sandboxed_api/var_lenval.cc<|end_filename|>
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "sandboxed_api/var_lenval.h"

#include <sys/uio.h>

#include <glog/logging.h>
#include "sandboxed_api/rpcchannel.h"
#include "sandboxed_api/sandbox2/comms.h"
#include "sandboxed_api/util/status_macros.h"

namespace sapi::v {

absl::Status LenVal::Allocate(RPCChannel* rpc_channel, bool automatic_free) {
  SAPI_RETURN_IF_ERROR(struct_.Allocate(rpc_channel, automatic_free));
  SAPI_RETURN_IF_ERROR(array_.Allocate(rpc_channel, true));

  // Set data pointer.
  struct_.mutable_data()->data = array_.GetRemote();
  return absl::OkStatus();
}

absl::Status LenVal::Free(RPCChannel* rpc_channel) {
  SAPI_RETURN_IF_ERROR(array_.Free(rpc_channel));
  SAPI_RETURN_IF_ERROR(struct_.Free(rpc_channel));
  return absl::OkStatus();
}

absl::Status LenVal::TransferToSandboxee(RPCChannel* rpc_channel, pid_t pid) {
  // Sync the structure and the underlying array.
  SAPI_RETURN_IF_ERROR(struct_.TransferToSandboxee(rpc_channel, pid));
  SAPI_RETURN_IF_ERROR(array_.TransferToSandboxee(rpc_channel, pid));
  return absl::OkStatus();
}

absl::Status LenVal::TransferFromSandboxee(RPCChannel* rpc_channel, pid_t pid) {
  // Sync the structure back.
  SAPI_RETURN_IF_ERROR(struct_.TransferFromSandboxee(rpc_channel, pid));

  // Resize the local array if required. Also make sure we own the buffer, this
  // is the only way we can be sure that the buffer is writable.
  size_t new_size = struct_.data().size;
  SAPI_RETURN_IF_ERROR(array_.EnsureOwnedLocalBuffer(new_size));

  // Remote pointer might have changed, update it.
  array_.SetRemote(struct_.data().data);
  return array_.TransferFromSandboxee(rpc_channel, pid);
}

absl::Status LenVal::ResizeData(RPCChannel* rpc_channel, size_t size) {
  SAPI_RETURN_IF_ERROR(array_.Resize(rpc_channel, size));
  auto* struct_data = struct_.mutable_data();
  struct_data->data = array_.GetRemote();
  struct_data->size = size;
  return absl::OkStatus();
}

}  // namespace sapi::v


<|start_filename|>oss-internship-2020/libuv/examples/uvcat.cc<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <linux/futex.h>
#include <syscall.h>
#include <uv.h>

#include <iostream>

#include "sandboxed_api/util/flag.h"
#include "uv_sapi.sapi.h"  // NOLINT(build/include)

namespace {

class UVSapiUVCatSandbox : public uv::UVSandbox {
 public:
  UVSapiUVCatSandbox(std::string filename) : filename(filename) {}

 private:
  std::unique_ptr<sandbox2::Policy> ModifyPolicy(
      sandbox2::PolicyBuilder*) override {
    return sandbox2::PolicyBuilder()
        .AddFile(filename)
        .AllowDynamicStartup()
        .AllowExit()
        .AllowFork()
        .AllowFutexOp(FUTEX_WAKE_PRIVATE)
        .AllowFutexOp(FUTEX_WAIT_PRIVATE)
        .AllowMmap()
        .AllowOpen()
        .AllowSyscalls({__NR_epoll_create1, __NR_epoll_ctl, __NR_epoll_wait,
                        __NR_eventfd2, __NR_pipe2, __NR_prlimit64})
        .AllowWrite()
        .BuildOrDie();
  }

  std::string filename;
};

absl::Status UVCat(std::string filearg) {
  // Initialize sandbox2 and sapi
  UVSapiUVCatSandbox sandbox(filearg);
  SAPI_RETURN_IF_ERROR(sandbox.Init());
  uv::UVApi api(&sandbox);

  // Get remote pointer to the OnOpen method
  void* function_ptr;
  SAPI_RETURN_IF_ERROR(sandbox.rpc_channel()->Symbol("OnOpen", &function_ptr));
  sapi::v::RemotePtr on_open(function_ptr);

  // Get remote pointer to the open_req variable
  void* open_req_voidptr;
  SAPI_RETURN_IF_ERROR(
      sandbox.rpc_channel()->Symbol("open_req", &open_req_voidptr));
  sapi::v::RemotePtr open_req(open_req_voidptr);

  // Get default loop
  SAPI_ASSIGN_OR_RETURN(void* loop_voidptr, api.sapi_uv_default_loop());
  sapi::v::RemotePtr loop(loop_voidptr);

  int return_code;

  // Open file using the OnOpen callback (which will also read and print it)
  sapi::v::ConstCStr filename(filearg.c_str());
  SAPI_ASSIGN_OR_RETURN(
      return_code, api.sapi_uv_fs_open(&loop, &open_req, filename.PtrBefore(),
                                       O_RDONLY, 0, &on_open));
  if (return_code != 0) {
    return absl::UnavailableError("uv_fs_open returned error " + return_code);
  }

  // Run loop
  SAPI_ASSIGN_OR_RETURN(return_code, api.sapi_uv_run(&loop, UV_RUN_DEFAULT));
  if (return_code != 0) {
    return absl::UnavailableError("uv_run returned error " + return_code);
  }

  // Cleanup the request
  SAPI_RETURN_IF_ERROR(api.sapi_uv_fs_req_cleanup(&open_req));

  return absl::OkStatus();
}

}  // namespace

int main(int argc, char* argv[]) {
  gflags::ParseCommandLineFlags(&argc, &argv, true);
  google::InitGoogleLogging(argv[0]);

  if (argc != 2) {
    LOG(ERROR) << "wrong number of arguments (1 expected)";
    return EXIT_FAILURE;
  }

  if (absl::Status status = UVCat(argv[1]); !status.ok()) {
    LOG(ERROR) << "UVCat failed: " << status.ToString();
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}


<|start_filename|>oss-internship-2020/curl/examples/example4.cc<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Sandboxed version of multi-poll.c
// HTTP GET request with polling

#include <cstdlib>

#include "../curl_util.h"    // NOLINT(build/include)
#include "../sandbox.h"      // NOLINT(build/include)
#include "curl_sapi.sapi.h"  // NOLINT(build/include)
#include "absl/strings/str_cat.h"
#include "sandboxed_api/util/status_macros.h"

namespace {

absl::Status Example4() {
  // Initialize sandbox2 and sapi
  curl::CurlSapiSandbox sandbox;
  SAPI_RETURN_IF_ERROR(sandbox.Init());
  curl::CurlApi api(&sandbox);

  // Number of running handles
  sapi::v::Int still_running(1);

  int curl_code;

  // Initialize curl (CURL_GLOBAL_DEFAULT = 3)
  SAPI_ASSIGN_OR_RETURN(curl_code, api.curl_global_init(3l));
  if (curl_code != 0) {
    return absl::UnavailableError(absl::StrCat(
        "curl_global_init failed: ", curl::StrError(&api, curl_code)));
  }

  // Initialize http_handle
  curl::CURL* curl_handle;
  SAPI_ASSIGN_OR_RETURN(curl_handle, api.curl_easy_init());
  sapi::v::RemotePtr http_handle(curl_handle);
  if (!curl_handle) {
    return absl::UnavailableError("curl_easy_init failed: Invalid curl handle");
  }

  // Specify URL to get
  sapi::v::ConstCStr url("http://example.com");
  SAPI_ASSIGN_OR_RETURN(
      curl_code, api.curl_easy_setopt_ptr(&http_handle, curl::CURLOPT_URL,
                                          url.PtrBefore()));
  if (curl_code != 0) {
    return absl::UnavailableError(absl::StrCat(
        "curl_easy_setopt_ptr failed: ", curl::StrError(&api, curl_code)));
  }

  // Initialize multi_handle
  curl::CURLM* curlm_handle;
  SAPI_ASSIGN_OR_RETURN(curlm_handle, api.curl_multi_init());
  sapi::v::RemotePtr multi_handle(curlm_handle);
  if (!curlm_handle) {
    return absl::UnavailableError(
        "curl_multi_init failed: multi_handle is invalid");
  }

  // Add http_handle to the multi stack
  SAPI_ASSIGN_OR_RETURN(curl_code,
                        api.curl_multi_add_handle(&multi_handle, &http_handle));
  if (curl_code != 0) {
    return absl::UnavailableError(absl::StrCat(
        "curl_multi_add_handle failed: ", curl::StrError(&api, curl_code)));
  }

  while (still_running.GetValue()) {
    sapi::v::Int numfds(0);

    // Perform the request
    SAPI_ASSIGN_OR_RETURN(
        curl_code,
        api.curl_multi_perform(&multi_handle, still_running.PtrBoth()));
    if (curl_code != 0) {
      return absl::UnavailableError(absl::StrCat(
          "curl_mutli_perform failed: ", curl::StrError(&api, curl_code)));
    }

    if (still_running.GetValue()) {
      // Wait for an event or timeout
      sapi::v::NullPtr null_ptr;
      SAPI_ASSIGN_OR_RETURN(
          curl_code, api.curl_multi_poll_sapi(&multi_handle, &null_ptr, 0, 1000,
                                              numfds.PtrBoth()));
      if (curl_code != 0) {
        return absl::UnavailableError(absl::StrCat(
            "curl_multi_poll_sapi failed: ", curl::StrError(&api, curl_code)));
      }
    }
  }

  // Remove http_handle from the multi stack
  SAPI_ASSIGN_OR_RETURN(
      curl_code, api.curl_multi_remove_handle(&multi_handle, &http_handle));
  if (curl_code != 0) {
    return absl::UnavailableError(absl::StrCat(
        "curl_multi_remove_handle failed: ", curl::StrError(&api, curl_code)));
  }

  // Cleanup http_handle
  SAPI_RETURN_IF_ERROR(api.curl_easy_cleanup(&http_handle));

  // Cleanup multi_handle
  SAPI_ASSIGN_OR_RETURN(curl_code, api.curl_multi_cleanup(&multi_handle));
  if (curl_code != 0) {
    return absl::UnavailableError(absl::StrCat(
        "curl_multi_cleanup failed: ", curl::StrError(&api, curl_code)));
  }

  // Cleanup curl
  SAPI_RETURN_IF_ERROR(api.curl_global_cleanup());

  return absl::OkStatus();
}

}  // namespace

int main(int argc, char* argv[]) {
  gflags::ParseCommandLineFlags(&argc, &argv, true);
  google::InitGoogleLogging(argv[0]);

  if (absl::Status status = Example4(); !status.ok()) {
    LOG(ERROR) << "Example4 failed: " << status.ToString();
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}


<|start_filename|>oss-internship-2020/gdal/raster_to_gtiff/get_raster_data.h<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef RASTER_TO_GTIFF_GET_RASTER_DATA_H_
#define RASTER_TO_GTIFF_GET_RASTER_DATA_H_

#include <optional>
#include <string>
#include <vector>

namespace gdal::sandbox::parser {

struct RasterBandData {
  int width;
  int height;
  std::vector<int> data;
  int data_type;     // Corresponds to the GDALDataType enum
  int color_interp;  // Corresponds to the GDALColorInterp enum
  std::optional<double> no_data_value;
};

struct RasterDataset {
  int width;
  int height;
  std::vector<RasterBandData> bands;
  std::string wkt_projection;  // OpenGIS WKT format
  std::vector<double> geo_transform;
};

RasterDataset GetRasterBandsFromFile(const std::string& filename);
bool operator==(const RasterBandData& lhs, const RasterBandData& rhs);
bool operator==(const RasterDataset& lhs, const RasterDataset& rhs);

}  // namespace gdal::sandbox::parser

#endif  // RASTER_TO_GTIFF_GET_RASTER_DATA_H_


<|start_filename|>oss-internship-2020/libpng/wrapper/func.cc<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <cstdlib>

void png_setjmp(png_structrp ptr) { setjmp(png_jmpbuf(ptr)); }

void* png_fdopen(int fd, const char* mode) {
  FILE* f = fdopen(fd, mode);
  return static_cast<void*>(f);
}

void png_rewind(void* f) { rewind(static_cast<FILE*>(f)); }

void png_fread(void* buffer, size_t size, size_t count, void* stream) {
  fread(buffer, size, count, static_cast<FILE*>(stream));
}

void png_fclose(void* f) { fclose(static_cast<FILE*>(f)); }

void png_init_io_wrapper(png_structrp png_ptr, void* f) {
  png_init_io(png_ptr, static_cast<FILE*>(f));
}

png_structp png_create_read_struct_wrapper(png_const_charp user_png_ver,
                                           png_voidp error_ptr) {
  return png_create_read_struct(user_png_ver, error_ptr, NULL, NULL);
}

png_structp png_create_write_struct_wrapper(png_const_charp user_png_ver,
                                            png_voidp error_ptr) {
  return png_create_write_struct(user_png_ver, error_ptr, NULL, NULL);
}

void png_read_image_wrapper(png_structrp png_ptr, png_bytep image,
                            size_t height, size_t rowbytes) {
  png_bytep* ptrs = (png_bytep*)malloc(height * sizeof(png_bytep));
  for (size_t i = 0; i != height; ++i) {
    ptrs[i] = image + (i * rowbytes);
  }
  png_read_image(png_ptr, ptrs);
  free(ptrs);
}

void png_write_image_wrapper(png_structrp png_ptr, png_bytep image,
                             size_t height, size_t rowbytes) {
  png_bytep* ptrs = (png_bytep*)malloc(height * sizeof(png_bytep));
  for (size_t i = 0; i != height; ++i) {
    ptrs[i] = image + (i * rowbytes);
  }
  png_write_image(png_ptr, ptrs);
  free(ptrs);
}


<|start_filename|>sandboxed_api/sandbox2/forkserver_test.cc<|end_filename|>
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "sandboxed_api/sandbox2/forkserver.h"

#include <fcntl.h>
#include <sys/socket.h>
#include <syscall.h>
#include <unistd.h>

#include <utility>

#include <glog/logging.h>
#include "gtest/gtest.h"
#include "absl/strings/str_cat.h"
#include "sandboxed_api/sandbox2/comms.h"
#include "sandboxed_api/sandbox2/forkserver.pb.h"
#include "sandboxed_api/sandbox2/global_forkclient.h"
#include "sandboxed_api/sandbox2/ipc.h"
#include "sandboxed_api/testing.h"

namespace sandbox2 {

using ::sapi::GetTestSourcePath;

class IpcPeer {
 public:
  explicit IpcPeer(IPC* ipc) : ipc_{ipc} {}

  void SetUpServerSideComms(int fd) { ipc_->SetUpServerSideComms(fd); }

 private:
  IPC* ipc_;
};

int GetMinimalTestcaseFd() {
  const std::string path = GetTestSourcePath("sandbox2/testcases/minimal");
  return open(path.c_str(), O_RDONLY);
}

pid_t TestSingleRequest(Mode mode, int exec_fd, int userns_fd) {
  ForkRequest fork_req;
  IPC ipc;
  int sv[2];
  // Setup IPC
  PCHECK(socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != -1);
  IpcPeer{&ipc}.SetUpServerSideComms(sv[1]);
  // Setup fork_req
  fork_req.set_mode(mode);
  fork_req.add_args("/binary");
  fork_req.add_envs("FOO=1");

  pid_t pid =
      GlobalForkClient::SendRequest(fork_req, exec_fd, sv[0], userns_fd);
  if (pid != -1) {
    VLOG(1) << "TestSingleRequest: Waiting for pid=" << pid;
    waitpid(pid, nullptr, 0);
  }

  close(sv[0]);
  return pid;
}

TEST(ForkserverTest, SimpleFork) {
  // Make sure that the regular fork request works.
  ASSERT_NE(TestSingleRequest(FORKSERVER_FORK, -1, -1), -1);
}

TEST(ForkserverTest, SimpleForkNoZombie) {
  // Make sure that we don't create zombies.
  pid_t child = TestSingleRequest(FORKSERVER_FORK, -1, -1);
  ASSERT_NE(child, -1);
  std::string proc = absl::StrCat("/proc/", child, "/cmdline");

  // Give the kernel some time to clean up.
  // Poll every 10ms up to 500 times (5s)
  bool process_reaped = false;
  for (int i = 0; i < 500; i++) {
    if (access(proc.c_str(), F_OK) == -1) {
      process_reaped = true;
      break;
    }
    usleep(10 * 1000);  // 10 ms
  }
  EXPECT_TRUE(process_reaped);
}

TEST(ForkserverTest, ForkExecveWorks) {
  // Run a test binary through the FORK_EXECVE request.
  int exec_fd = GetMinimalTestcaseFd();
  PCHECK(exec_fd != -1) << "Could not open test binary";
  ASSERT_NE(TestSingleRequest(FORKSERVER_FORK_EXECVE, exec_fd, -1), -1);
}

TEST(ForkserverTest, ForkExecveSandboxWithoutPolicy) {
  // Run a test binary through the FORKSERVER_FORK_EXECVE_SANDBOX request.
  int exec_fd = GetMinimalTestcaseFd();
  PCHECK(exec_fd != -1) << "Could not open test binary";
}

}  // namespace sandbox2


<|start_filename|>sandboxed_api/sandbox2/util/minielf_test.cc<|end_filename|>
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "sandboxed_api/sandbox2/util/minielf.h"

#include <cstdint>
#include <string>
#include <vector>

#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/algorithm/container.h"
#include "sandboxed_api/sandbox2/util/maps_parser.h"
#include "sandboxed_api/testing.h"
#include "sandboxed_api/util/file_helpers.h"
#include "sandboxed_api/util/status_matchers.h"

extern "C" void ExportedFunctionName() {
  // Don't do anything - used to generate a symbol.
}

namespace file = ::sapi::file;
using ::sapi::GetTestSourcePath;
using ::sapi::IsOk;
using ::testing::Eq;
using ::testing::IsTrue;
using ::testing::Ne;
using ::testing::StrEq;

namespace sandbox2 {
namespace {

TEST(MinielfTest, Chrome70) {
  SAPI_ASSERT_OK_AND_ASSIGN(
      ElfFile elf,
      ElfFile::ParseFromFile(
          GetTestSourcePath("sandbox2/util/testdata/chrome_grte_header"),
          ElfFile::kGetInterpreter));
  EXPECT_THAT(elf.interpreter(), StrEq("/usr/grte/v4/ld64"));
}

TEST(MinielfTest, SymbolResolutionWorks) {
  SAPI_ASSERT_OK_AND_ASSIGN(
      ElfFile elf,
      ElfFile::ParseFromFile("/proc/self/exe", ElfFile::kLoadSymbols));
  ASSERT_THAT(elf.position_independent(), IsTrue());

  // Load /proc/self/maps to take ASLR into account.
  std::string maps_buffer;
  ASSERT_THAT(
      file::GetContents("/proc/self/maps", &maps_buffer, file::Defaults()),
      IsOk());
  SAPI_ASSERT_OK_AND_ASSIGN(std::vector<MapsEntry> maps,
                            ParseProcMaps(maps_buffer));

  // Find maps entry that covers this entry.
  uint64_t function_address = reinterpret_cast<uint64_t>(ExportedFunctionName);
  auto function_entry =
      absl::c_find_if(maps, [function_address](const MapsEntry& entry) {
        return entry.start <= function_address && entry.end > function_address;
      });
  ASSERT_THAT(function_entry, Ne(maps.end()));
  function_address -= function_entry->start;

  auto function_symbol =
      absl::c_find_if(elf.symbols(), [](const ElfFile::Symbol& symbol) {
        return symbol.name == "ExportedFunctionName";
      });
  ASSERT_THAT(function_symbol, Ne(elf.symbols().end()));
  EXPECT_THAT(function_symbol->address, Eq(function_address));
}

TEST(MinielfTest, ImportedLibraries) {
  SAPI_ASSERT_OK_AND_ASSIGN(
      ElfFile elf, ElfFile::ParseFromFile(
                       GetTestSourcePath("sandbox2/util/testdata/hello_world"),
                       ElfFile::kLoadImportedLibraries));
  std::vector<std::string> imported_libraries = {"libc.so.6"};
  EXPECT_THAT(elf.imported_libraries(), Eq(imported_libraries));
}

}  // namespace
}  // namespace sandbox2


<|start_filename|>sandboxed_api/util/fileops.cc<|end_filename|>
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "sandboxed_api/util/fileops.h"

#include <dirent.h>    // DIR
#include <limits.h>    // PATH_MAX
#include <sys/stat.h>  // stat64
#include <unistd.h>

#include <fstream>
#include <memory>

#include "absl/strings/str_cat.h"
#include "absl/strings/strip.h"
#include "sandboxed_api/util/strerror.h"

namespace sapi::file_util::fileops {

FDCloser::~FDCloser() { Close(); }

bool FDCloser::Close() {
  int fd = Release();
  if (fd == kCanonicalInvalidFd) {
    return false;
  }
  return close(fd) == 0 || errno == EINTR;
}

int FDCloser::Release() {
  int ret = fd_;
  fd_ = kCanonicalInvalidFd;
  return ret;
}

bool GetCWD(std::string* result) {
  // Calling getcwd() with a nullptr buffer is a commonly implemented extension.
  std::unique_ptr<char, void (*)(char*)> cwd(getcwd(nullptr, 0),
                                             [](char* p) { free(p); });
  if (!cwd) {
    return false;
  }
  *result = cwd.get();
  return true;
}

std::string GetCWD() {
  std::string cwd;
  GetCWD(&cwd);
  return cwd;
}

// Makes a path absolute with respect to base. Returns true on success. Result
// may be an alias of base or filename.
bool MakeAbsolute(const std::string& filename, const std::string& base,
                  std::string* result) {
  if (filename.empty()) {
    return false;
  }
  if (filename[0] == '/') {
    if (result != &filename) {
      *result = filename;
    }
    return true;
  }

  std::string actual_base = base;
  if (actual_base.empty() && !GetCWD(&actual_base)) {
    return false;
  }

  actual_base = std::string(absl::StripSuffix(actual_base, "/"));

  if (filename == ".") {
    if (actual_base.empty()) {
      *result = "/";
    } else {
      *result = actual_base;
    }
  } else {
    *result = actual_base + "/" + filename;
  }
  return true;
}

std::string MakeAbsolute(const std::string& filename, const std::string& base) {
  std::string result;
  return !MakeAbsolute(filename, base, &result) ? "" : result;
}

bool RemoveLastPathComponent(const std::string& file, std::string* output) {
  // Point idx at the last non-slash in the string. This should mark the last
  // character of the base name.
  auto idx = file.find_last_not_of('/');
  // If no non-slash is found, we have all slashes or an empty string. Return
  // the appropriate value and false to indicate there was no path component to
  // remove.
  if (idx == std::string::npos) {
    if (file.empty()) {
      output->clear();
    } else {
      *output = "/";
    }
    return false;
  }

  // Otherwise, we have to trim the last path component. Find where it begins.
  // Point idx at the last slash before the base name.
  idx = file.find_last_of('/', idx);
  // If we don't find a slash, then we have something of the form "file/*", so
  // just return the empty string.
  if (idx == std::string::npos) {
    output->clear();
  } else {
    // Then find the last character that isn't a slash, in case the slash is
    // repeated.
    // Point idx at the character at the last character of the path component
    // that precedes the base name. I.e. if you have /foo/bar, idx will point
    // at the last "o" in foo. We remove everything after this index.
    idx = file.find_last_not_of('/', idx);
    // If none is found, then set idx to 0 so the below code will leave the
    // first slash.
    if (idx == std::string::npos) idx = 0;
    // This is an optimization to prevent a copy if output and file are
    // aliased.
    if (&file == output) {
      output->erase(idx + 1, std::string::npos);
    } else {
      output->assign(file, 0, idx + 1);
    }
  }
  return true;
}

std::string ReadLink(const std::string& filename) {
  std::string result(PATH_MAX, '\0');
  const auto size = readlink(filename.c_str(), &result[0], PATH_MAX);
  if (size < 0) {
    return "";
  }
  result.resize(size);
  return result;
}

bool ReadLinkAbsolute(const std::string& filename, std::string* result) {
  std::string base_dir;

  // Do this first. Otherwise, if &filename == result, we won't be able to find
  // it after the ReadLink call.
  RemoveLastPathComponent(filename, &base_dir);

  std::string link = ReadLink(filename);
  if (link.empty()) {
    return false;
  }
  *result = std::move(link);

  // Need two calls in case filename itself is relative.
  return MakeAbsolute(MakeAbsolute(*result, base_dir), "", result);
}

std::string Basename(absl::string_view path) {
  const auto last_slash = path.find_last_of('/');
  return std::string(last_slash == std::string::npos
                         ? path
                         : absl::ClippedSubstr(path, last_slash + 1));
}

std::string StripBasename(absl::string_view path) {
  const auto last_slash = path.find_last_of('/');
  if (last_slash == std::string::npos) {
    return "";
  }
  if (last_slash == 0) {
    return "/";
  }
  return std::string(path.substr(0, last_slash));
}

bool Exists(const std::string& filename, bool fully_resolve) {
  struct stat64 st;
  return (fully_resolve ? stat64(filename.c_str(), &st)
                        : lstat64(filename.c_str(), &st)) != -1;
}

bool ListDirectoryEntries(const std::string& directory,
                          std::vector<std::string>* entries,
                          std::string* error) {
  errno = 0;
  std::unique_ptr<DIR, void (*)(DIR*)> dir{opendir(directory.c_str()),
                                           [](DIR* d) { closedir(d); }};
  if (!dir) {
    *error = absl::StrCat("opendir(", directory, "): ", StrError(errno));
    return false;
  }

  struct dirent64* entry{};
  errno = 0;
  int bufferlen =
      std::max<int>(offsetof(struct dirent64, d_name) +
                        pathconf(directory.c_str(), _PC_NAME_MAX) + 1,
                    sizeof(struct dirent64));
  std::unique_ptr<struct dirent64, void (*)(struct dirent64*)> dirent_buffer{
      static_cast<struct dirent64*>(malloc(bufferlen)),
      [](struct dirent64* p) { free(p); }};
  while (readdir64_r(dir.get(), dirent_buffer.get(), &entry) == 0 && entry) {
    const std::string name(entry->d_name);
    if (name != "." && name != "..") {
      entries->push_back(name);
    }
  }
  if (errno != 0) {
    *error = absl::StrCat("readdir(", directory, "): ", StrError(errno));
    return false;
  }
  return true;
}

bool DeleteRecursively(const std::string& filename) {
  std::vector<std::string> to_delete;
  to_delete.push_back(filename);

  while (!to_delete.empty()) {
    const std::string delfile = to_delete.back();

    struct stat64 st;
    if (lstat64(delfile.c_str(), &st) == -1) {
      if (errno == ENOENT) {
        // Most likely the first file. Either that or someone is deleting the
        // files out from under us.
        to_delete.pop_back();
        continue;
      }
      return false;
    }

    if (S_ISDIR(st.st_mode)) {
      if (rmdir(delfile.c_str()) != 0 && errno != ENOENT) {
        if (errno == ENOTEMPTY) {
          std::string error;
          std::vector<std::string> entries;
          if (!ListDirectoryEntries(delfile, &entries, &error)) {
            return false;
          }
          for (const auto& entry : entries) {
            to_delete.push_back(delfile + "/" + entry);
          }
        } else {
          return false;
        }
      } else {
        to_delete.pop_back();
      }
    } else {
      if (unlink(delfile.c_str()) != 0 && errno != ENOENT) {
        return false;
      }
      to_delete.pop_back();
    }
  }
  return true;
}

bool CopyFile(const std::string& old_path, const std::string& new_path,
              int new_mode) {
  {
    std::ifstream input(old_path, std::ios_base::binary);
    std::ofstream output(new_path,
                         std::ios_base::trunc | std::ios_base::binary);
    output << input.rdbuf();
    if (!input || !output) {
      return false;
    }
  }
  return chmod(new_path.c_str(), new_mode) == 0;
}

bool WriteToFD(int fd, const char* data, size_t size) {
  while (size > 0) {
    ssize_t result = TEMP_FAILURE_RETRY(write(fd, data, size));
    if (result <= 0) {
      return false;
    }
    size -= result;
    data += result;
  }
  return true;
}

}  // namespace sapi::file_util::fileops


<|start_filename|>oss-internship-2020/jsonnet/tests/jsonnet_tests.cc<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "jsonnet_tests.h"  // NOLINT(build/include)

namespace {

class JsonnetTest : public JsonnetTestHelper, public testing::Test {
 protected:
  void SetUp() override { TestSetUp(); }
  void TearDown() override { TestTearDown(); }
};

// Basic test
TEST_F(JsonnetTest, SetUp_TearDown) {
  ASSERT_FALSE(jsonnet_vm_was_used_);
  ASSERT_FALSE(input_was_read_);
}

// One file evaluation to one file
TEST_F(JsonnetTest, One_file_no_dependencies) {
  constexpr char kInputFile[] = "arith.jsonnet";
  constexpr char kOutputFile[] = "arith_output";
  constexpr char kOutputToRead[] = "tests_output/arith_output";
  constexpr char kOutputToExpect[] = "tests_expected_output/arith.golden";

  Read_input(kInputFile);
  EvaluateJsonnetCode(kBase, true);
  WriteOutput(kOutputFile, kBase);

  std::string produced_output = ReadOutput(kOutputToRead);
  std::string expected_output = ReadOutput(kOutputToExpect);

  ASSERT_STREQ(produced_output.c_str(), expected_output.c_str());
}

// One file evaluating to one file, dependent on some other files
TEST_F(JsonnetTest, One_file_some_dependencies) {
  constexpr char kInputFile[] = "negroni.jsonnet";
  constexpr char kOutputFile[] = "negroni_output";
  constexpr char kOutputToRead[] = "tests_output/negroni_output";
  constexpr char kOutputToExpect[] = "tests_expected_output/negroni.golden";

  ReadInput(kInputFile);
  EvaluateJsonnetCode(kBase, true);
  WriteOutput(kOutputFile, kBase);

  const std::string produced_output = Read_output(kOutputToRead);
  const std::string expected_output = Read_output(kOutputToExpect);

  ASSERT_STREQ(produced_output.c_str(), expected_output.c_str());
}

// One file evaluating to two files
TEST_F(JsonnetTest, Multiple_files) {
  constexpr char kInputFile[] = "multiple_files_example.jsonnet";
  constexpr char kOutputFile[] = "";
  constexpr char kOutputToRead1[] = "tests_output/first_file.json";
  constexpr char kOutputToRead2[] = "tests_output/second_file.json";
  constexpr char kOutputToExpect1[] = "tests_expected_output/first_file.json";
  constexpr char kOutputToExpect2[] = "tests_expected_output/second_file.json";

  ReadInput(kInputFile);
  EvaluateJsonnetCode(kMultipleFiles, true);
  WriteOutput(kOutputFile, kMultipleFiles);

  const std::string produced_output_1 = ReadOutput(kOutputToRead1);
  const std::string produced_output_2 = ReadOutput(kOutputToRead2);
  const std::string expected_output_1 = ReadOutput(kOutputToExpect1);
  const std::string expected_output_2 = ReadOutput(kOutputToExpect2);

  ASSERT_STREQ(produced_output_1.c_str(), expected_output_1.c_str());
  ASSERT_STREQ(produced_output_2.c_str(), expected_output_2.c_str());
}

// One file evaluating to yaml stream format
TEST_F(JsonnetTest, Yaml_stream) {
  constexpr char kInputFile[] = "yaml_stream_example.jsonnet";
  constexpr char kOutputFile[] = "yaml_stream_example.yaml";
  constexpr char kOutputToRead[] = "tests_output/yaml_stream_example.yaml";
  constexpr char kOutputToExpect[] =
      "tests_expected_output/yaml_stream_example.yaml";

  ReadInput(kInputFile);
  EvaluateJsonnetCode(kYamlStream, true);
  WriteOutput(kOutputFile, kYamlStream);

  const std::string produced_output = ReadOutput(kOutputToRead);
  const std::string expected_output = ReadOutput(kOutputToExpect);

  ASSERT_STREQ(produced_output.c_str(), expected_output.c_str());
}

// One file depended on some other files not accessible by the sandbox
TEST_F(JsonnetTest, Bad_evaluation) {
  constexpr char kInputFile[] = "imports.jsonnet";

  ReadInput(kInputFile);
  EvaluateJsonnetCode(kBase, false);
}

}  // namespace


<|start_filename|>sandboxed_api/examples/sum/lib/sum.c<|end_filename|>
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/ptrace.h>

int sumsymbol = 5;

typedef struct sum_params_s {
  int a;
  int b;
  int ret;
} sum_params;

extern int ftest(FILE *f) {
  return f->_offset;
}

extern int sum(int a, int b) {
  return a + b;
}

extern void sums(sum_params* params) {
  params->ret =  params->a + params->b;
}

extern long double addf(float a, double b, long double c) {
  return a + b + c;
}

extern int sub(int a, int b) {
  return a - b;
}

extern int mul(int a, int b) {
  return a * b;
}

extern int divs(int a, int b) {
  return a / b;
}

extern double muld(double a, float b) {
  return a * b;
}

extern void crash(void) {
  void(*die)() = (void(*)())(0x0000dead);
  die();
}

extern void violate(void) {
  // Issue a PTRACE_CONT that will always fail, since we are not in stopped
  // state. The actual call should be caught by the sandbox policy.
  ptrace(PTRACE_CONT, 0, NULL, NULL);
}

extern int sumarr(int* input, size_t nelem) {
  int s = 0, i;
  for (i = 0; i < nelem; i++) {
    s += input[i];
  }
  return s;
}

extern void testptr(void *ptr) {
  if (ptr) {
    puts("Is Not a NULL-ptr");
  } else {
    puts("Is a NULL-ptr");
  }
}

extern int read_int(int fd) {
  char buf[10] = {0};
  int ret = read(fd, buf, sizeof(buf) - 1);
  if(ret > 0) {
    ret = atoi(buf);
  }
  return ret;
}

extern void sleep_for_sec(int sec) {
  sleep(sec);
}


<|start_filename|>oss-internship-2020/gdal/raster_to_gtiff/tests.cc<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <optional>
#include <string>

#include "gdal_sandbox.h"     // NOLINT(build/include)
#include "get_raster_data.h"  // NOLINT(build/include)
#include "gtiff_converter.h"  // NOLINT(build/include)
#include "gtest/gtest.h"
#include "sandboxed_api/testing.h"
#include "sandboxed_api/util/fileops.h"
#include "sandboxed_api/util/path.h"
#include "utils.h"  // NOLINT(build/include)

namespace {

inline constexpr absl::string_view kTempFilePrefix = "temp_data";
inline constexpr absl::string_view kFirstTestDataPath = "testdata/cea.tif";
inline constexpr absl::string_view kSecondTestDataPath =
    "testdata/SP27GTIF.tif";

}  // namespace

class TestGTiffProcessor : public testing::TestWithParam<absl::string_view> {
 public:
  TestGTiffProcessor() : tempfile_(sandbox2::GetTestTempPath()) {}

 protected:
  const gdal::sandbox::utils::TempFile tempfile_;
};

TEST_P(TestGTiffProcessor, TestProcessorOnGTiffData) {
  std::string file_path = gdal::sandbox::utils::GetTestDataPath(GetParam());

  ASSERT_TRUE(sandbox2::file_util::fileops::Exists(file_path, false))
      << "Error finding input dataset";

  ASSERT_TRUE(tempfile_.HasValue()) << "Error creating temporary output file";

  gdal::sandbox::parser::RasterDataset original_bands_data =
      gdal::sandbox::parser::GetRasterBandsFromFile(file_path);

  std::optional<std::string> proj_db_path =
      gdal::sandbox::utils::FindProjDbPath();
  ASSERT_TRUE(proj_db_path != std::nullopt)
      << "Specified proj.db does not exist";

  gdal::sandbox::RasterToGTiffProcessor processor(
      tempfile_.GetPath(), std::move(proj_db_path.value()),
      original_bands_data);

  ASSERT_EQ(processor.Run(), absl::OkStatus())
      << "Error creating new GTiff dataset inside sandbox";

  ASSERT_EQ(original_bands_data,
            gdal::sandbox::parser::GetRasterBandsFromFile(tempfile_.GetPath()))
      << "New dataset doesn't match the original one";
}

INSTANTIATE_TEST_CASE_P(GDALTests, TestGTiffProcessor,
                        ::testing::Values(kFirstTestDataPath,
                                          kSecondTestDataPath));


<|start_filename|>sandboxed_api/sandbox2/testcases/namespace.cc<|end_filename|>
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Checks various things related to namespaces, depending on the first argument:
// ./binary 0 <file1> <file2> ... <fileN>:
//    Make sure all provided files exist and are RO, return 0 on OK.
//    Returns the index of the first non-existing file on failure.
// ./binary 1 <file1> <file2> ... <fileN>:
//    Make sure all provided files exist and are RW, return 0 on OK.
//    Returns the index of the first non-existing file on failure.
// ./binary 2
//    Make sure that we run in a PID namespace (this implies getpid() == 1)
//    Returns 0 on OK.
// ./binary 3 <uid> <gid>
//    Make sure getuid()/getgid() returns the provided uid/gid (User namespace).
//    Returns 0 on OK.
// ./binary 4 <file1> <file2> ... <fileN>:
//    Create provided files, return 0 on OK.
//    Returns the index of the first non-creatable file on failure.
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include <cstdlib>

int main(int argc, char* argv[]) {
  if (argc < 2) {
    return 0;
  }

  int mode = atoi(argv[1]);  // NOLINT(runtime/deprecated_fn)

  switch (mode) {
    case 0: {
      // Make sure file exist
      for (int i = 2; i < argc; i++) {
        if (access(argv[i], R_OK)) {
          return i - 1;
        }
      }
    } break;

    case 1: {
      for (int i = 2; i < argc; i++) {
        if (access(argv[i], W_OK)) {
          return i - 1;
        }
      }
    } break;

    case 2: {
      if (getpid() != 2) {
        return -1;
      }
    } break;

    case 3: {
      if (argc != 4) {
        return 1;
      }

      if (getuid() != atoi(argv[2])        // NOLINT(runtime/deprecated_fn)
          || getgid() != atoi(argv[3])) {  // NOLINT(runtime/deprecated_fn)
        return -1;
      }
    } break;

    case 4:
      for (int i = 2; i < argc; ++i) {
        if (open(argv[i], O_CREAT | O_WRONLY, 0644) == -1) {
          return i - 1;
        }
      }
      break;

    default:
      return 1;
  }

  return 0;
}


<|start_filename|>oss-internship-2020/libpng/wrapper/func.h<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef LIBPNG_WRAPPER_FUNC_H_
#define LIBPNG_WRAPPER_FUNC_H_

#include "png.h"  // NOLINT(build/include)

extern "C" {

void* png_fdopen(int fd, const char* mode);
void png_rewind(void* f);
void png_fread(void* buffer, size_t size, size_t count, void* stream);
void png_fclose(void* f);
void png_setjmp(png_structrp ptr);
png_structp png_create_read_struct_wrapper(png_const_charp user_png_ver,
                                           png_voidp error_ptr);
png_structp png_create_write_struct_wrapper(png_const_charp user_png_ver,
                                            png_voidp error_ptr);
void png_init_io_wrapper(png_structrp png_ptr, void* f);
void png_read_image_wrapper(png_structrp png_ptr, png_bytep image,
                            size_t height, size_t rowbytes);
void png_write_image_wrapper(png_structrp png_ptr, png_bytep image,
                             size_t height, size_t rowbytes);

}  // extern "C"

#endif  // LIBPNG_WRAPPER_FUNC_H_


<|start_filename|>oss-internship-2020/jsonnet/headers/jsonnet_tests.h<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef JSONNET_TESTS_H_
#define JSONNET_TESTS_H_

#include <unistd.h>

#include <filesystem>
#include <fstream>
#include <iostream>
#include <memory>
#include <streambuf>
#include <string>

#include "jsonnet_base_sandbox.h"  // NOLINT(build/include)
#include "jsonnet_sapi.sapi.h"     // NOLINT(build/include)
#include "gtest/gtest.h"
#include "sandboxed_api/util/flag.h"
#include "sandboxed_api/util/path.h"
#include "sandboxed_api/util/status_matchers.h"

class JsonnetTestHelper {
 protected:
  enum Evaluation { kBase, kMultipleFiles, kYamlStream };

  void TestSetUp();
  void TestTearDown();

  void ReadInput(const char* filename);
  void EvaluateJsonnetCode(Evaluation type, bool expected_correct);
  void WriteOutput(const char* filename_or_directory, Evaluation type);
  std::string ReadOutput(const char* filename);

  std::unique_ptr<JsonnetBaseSandbox> sandbox_;
  std::unique_ptr<JsonnetApi> api_;
  std::unique_ptr<sapi::v::RemotePtr> input_;
  std::unique_ptr<sapi::v::RemotePtr> output_;
  std::unique_ptr<sapi::v::RemotePtr> vm_;

  std::string input_filename_in_sandboxee_;
  bool jsonnet_vm_was_used_;
  bool input_was_read_;
};

#endif  // JSONNET_TESTS_H_


<|start_filename|>oss-internship-2020/curl/examples/example3.cc<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Sandboxed version of simplessl.c
// HTTPS GET request

#include <cstdlib>

#include "../curl_util.h"    // NOLINT(build/include)
#include "../sandbox.h"      // NOLINT(build/include)
#include "curl_sapi.sapi.h"  // NOLINT(build/include)
#include "absl/strings/str_cat.h"
#include "sandboxed_api/util/status_macros.h"

namespace {

class CurlSapiSandboxEx3 : public curl::CurlSapiSandbox {
 public:
  CurlSapiSandboxEx3(std::string ssl_certificate, std::string ssl_key,
                     std::string ca_certificates)
      : ssl_certificate(std::move(ssl_certificate)),
        ssl_key(std::move(ssl_key)),
        ca_certificates(std::move(ca_certificates)) {}

 private:
  std::unique_ptr<sandbox2::Policy> ModifyPolicy(
      sandbox2::PolicyBuilder*) override {
    // Add the syscalls and files missing in CurlSandbox to a new PolicyBuilder
    auto policy_builder = std::make_unique<sandbox2::PolicyBuilder>();
    (*policy_builder)
        .AllowGetPIDs()
        .AllowGetRandom()
        .AllowHandleSignals()
        .AddFile(ssl_certificate)
        .AddFile(ssl_key)
        .AddFile(ca_certificates);
    // Provide the new PolicyBuilder to ModifyPolicy in CurlSandbox
    return curl::CurlSapiSandbox::ModifyPolicy(policy_builder.get());
  }

  std::string ssl_certificate;
  std::string ssl_key;
  std::string ca_certificates;
};

absl::Status Example3(const std::string& ssl_certificate,
                      const std::string& ssl_key,
                      const std::string& ssl_key_password,
                      const std::string& ca_certificates) {
  // Initialize sandbox2 and sapi
  CurlSapiSandboxEx3 sandbox(ssl_certificate, ssl_key, ca_certificates);
  SAPI_RETURN_IF_ERROR(sandbox.Init());
  curl::CurlApi api(&sandbox);

  int curl_code;

  // Initialize curl (CURL_GLOBAL_DEFAULT = 3)
  SAPI_ASSIGN_OR_RETURN(curl_code, api.curl_global_init(3l));
  if (curl_code != 0) {
    return absl::UnavailableError(absl::StrCat(
        "curl_global_init failed: ", curl::StrError(&api, curl_code)));
  }

  // Initialize curl easy handle
  curl::CURL* curl_handle;
  SAPI_ASSIGN_OR_RETURN(curl_handle, api.curl_easy_init());
  sapi::v::RemotePtr curl(curl_handle);
  if (!curl_handle) {
    return absl::UnavailableError("curl_easy_init failed: Invalid curl handle");
  }

  // Specify URL to get (using HTTPS)
  sapi::v::ConstCStr url("https://example.com");
  SAPI_ASSIGN_OR_RETURN(
      curl_code,
      api.curl_easy_setopt_ptr(&curl, curl::CURLOPT_URL, url.PtrBefore()));
  if (curl_code != 0) {
    return absl::UnavailableError(absl::StrCat(
        "curl_easy_setopt_ptr failed: ", curl::StrError(&api, curl_code)));
  }

  // Set the SSL certificate type to "PEM"
  sapi::v::ConstCStr ssl_cert_type("PEM");
  SAPI_ASSIGN_OR_RETURN(
      curl_code, api.curl_easy_setopt_ptr(&curl, curl::CURLOPT_SSLCERTTYPE,
                                          ssl_cert_type.PtrBefore()));
  if (curl_code != 0) {
    return absl::UnavailableError(absl::StrCat(
        "curl_easy_setopt_ptr failed: ", curl::StrError(&api, curl_code)));
  }

  // Set the certificate for client authentication
  sapi::v::ConstCStr sapi_ssl_certificate(ssl_certificate.c_str());
  SAPI_ASSIGN_OR_RETURN(
      curl_code, api.curl_easy_setopt_ptr(&curl, curl::CURLOPT_SSLCERT,
                                          sapi_ssl_certificate.PtrBefore()));
  if (curl_code != 0) {
    return absl::UnavailableError(absl::StrCat(
        "curl_easy_setopt_ptr failed: ", curl::StrError(&api, curl_code)));
  }

  // Set the private key for client authentication
  sapi::v::ConstCStr sapi_ssl_key(ssl_key.c_str());
  SAPI_ASSIGN_OR_RETURN(curl_code,
                        api.curl_easy_setopt_ptr(&curl, curl::CURLOPT_SSLKEY,
                                                 sapi_ssl_key.PtrBefore()));
  if (curl_code != 0) {
    return absl::UnavailableError(absl::StrCat(
        "curl_easy_setopt_ptr failed: ", curl::StrError(&api, curl_code)));
  }

  // Set the password used to protect the private key
  sapi::v::ConstCStr sapi_ssl_key_password(ssl_key_password.c_str());
  SAPI_ASSIGN_OR_RETURN(
      curl_code, api.curl_easy_setopt_ptr(&curl, curl::CURLOPT_KEYPASSWD,
                                          sapi_ssl_key_password.PtrBefore()));
  if (curl_code != 0) {
    return absl::UnavailableError(absl::StrCat(
        "curl_easy_setopt_ptr failed: ", curl::StrError(&api, curl_code)));
  }

  // Set the file with the certificates vaildating the server
  sapi::v::ConstCStr sapi_ca_certificates(ca_certificates.c_str());
  SAPI_ASSIGN_OR_RETURN(
      curl_code, api.curl_easy_setopt_ptr(&curl, curl::CURLOPT_CAINFO,
                                          sapi_ca_certificates.PtrBefore()));
  if (curl_code != 0) {
    return absl::UnavailableError(absl::StrCat(
        "curl_easy_setopt_ptr failed: ", curl::StrError(&api, curl_code)));
  }

  // Verify the authenticity of the server
  SAPI_ASSIGN_OR_RETURN(
      curl_code,
      api.curl_easy_setopt_long(&curl, curl::CURLOPT_SSL_VERIFYPEER, 1L));
  if (curl_code != 0) {
    return absl::UnavailableError(absl::StrCat(
        "curl_easy_setopt_long failed: ", curl::StrError(&api, curl_code)));
  }

  // Perform the request
  SAPI_ASSIGN_OR_RETURN(curl_code, api.curl_easy_perform(&curl));
  if (curl_code != 0) {
    return absl::UnavailableError(absl::StrCat(
        "curl_easy_perform failed: ", curl::StrError(&api, curl_code)));
  }

  // Cleanup curl easy handle
  SAPI_RETURN_IF_ERROR(api.curl_easy_cleanup(&curl));

  // Cleanup curl
  SAPI_RETURN_IF_ERROR(api.curl_global_cleanup());

  return absl::OkStatus();
}

}  // namespace

int main(int argc, char* argv[]) {
  gflags::ParseCommandLineFlags(&argc, &argv, true);
  google::InitGoogleLogging(argv[0]);

  // Get input parameters (should be absolute paths)
  if (argc != 5) {
    LOG(ERROR) << "wrong number of arguments (4 expected)";
    return EXIT_FAILURE;
  }

  if (absl::Status status = Example3(argv[1], argv[2], argv[3], argv[4]);
      !status.ok()) {
    LOG(ERROR) << "Example3 failed: " << status.ToString();
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}


<|start_filename|>oss-internship-2020/libpng/tests/basic_test.cc<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "../sandboxed.h"  // NOLINT(build/include)
#include "helper.h"        // NOLINT(build/include)
#include "libpng.h"        // NOLINT(build/include)
#include "gtest/gtest.h"
#include "sandboxed_api/util/fileops.h"
#include "sandboxed_api/util/path.h"
#include "sandboxed_api/util/status_matchers.h"
#include "sandboxed_api/util/temp_file.h"

namespace {

using ::sapi::IsOk;
using ::testing::Eq;
using ::testing::IsTrue;

TEST(SandboxTest, ReadWrite) {
  std::string infile = GetFilePath("pngtest.png");

  absl::StatusOr<std::string> status_or_path =
      sapi::CreateNamedTempFileAndClose("output.png");
  ASSERT_THAT(status_or_path, IsOk()) << "Could not create temp output file";

  std::string outfile = sapi::file::JoinPath(sapi::file_util::fileops::GetCWD(),
                                             status_or_path.value());

  LibPNGSapiSandbox sandbox;
  sandbox.AddFile(infile);
  sandbox.AddFile(outfile);

  ASSERT_THAT(sandbox.Init(), IsOk()) << "Couldn't initialize Sandboxed API";

  LibPNGApi api(&sandbox);

  sapi::v::Struct<png_image> image;
  sapi::v::ConstCStr infile_var(infile.c_str());
  sapi::v::ConstCStr outfile_var(outfile.c_str());

  image.mutable_data()->version = PNG_IMAGE_VERSION;

  absl::StatusOr<int> status_or_int = api.png_image_begin_read_from_file(
      image.PtrBoth(), infile_var.PtrBefore());
  ASSERT_THAT(status_or_int, IsOk())
      << "fatal error when invoking png_image_begin_read_from_file";
  ASSERT_THAT(status_or_int.value(), IsTrue())
      << "png_image_begin_read_from_file failed: "
      << image.mutable_data()->message;

  image.mutable_data()->format = PNG_FORMAT_RGBA;
  ASSERT_THAT(image.mutable_data()->version, Eq(PNG_IMAGE_VERSION))
      << "image version changed";

  sapi::v::Array<uint8_t> buffer(PNG_IMAGE_SIZE(*image.mutable_data()));
  sapi::v::NullPtr null = sapi::v::NullPtr();
  status_or_int = api.png_image_finish_read(image.PtrBoth(), &null,
                                            buffer.PtrBoth(), 0, &null);
  ASSERT_THAT(status_or_int, IsOk())
      << "fatal error when invoking png_image_finish_read";
  ASSERT_THAT(status_or_int.value(), IsTrue())
      << "png_image_finish_read failed: " << image.mutable_data()->message;
  ASSERT_THAT(image.mutable_data()->version, Eq(PNG_IMAGE_VERSION))
      << "image version changed";
  ASSERT_THAT(image.mutable_data()->format, Eq(PNG_FORMAT_RGBA))
      << "image format changed";

  status_or_int = api.png_image_write_to_file(
      image.PtrBoth(), outfile_var.PtrBefore(), 0, buffer.PtrBoth(), 0, &null);
  ASSERT_THAT(status_or_int, IsOk())
      << "fatal error when invoking png_image_write_to_file";
  ASSERT_THAT(status_or_int.value(), IsTrue())
      << "png_image_finish_read failed: " << image.mutable_data()->message;
  ASSERT_THAT(image.mutable_data()->version, Eq(PNG_IMAGE_VERSION))
      << "image version changed";
  ASSERT_THAT(image.mutable_data()->format, Eq(PNG_FORMAT_RGBA))
      << "image format changed";
}

}  // namespace


<|start_filename|>oss-internship-2020/libpng/examples/example1.cc<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <string>

#include "../sandboxed.h"     // NOLINT(build/include)
#include "../tests/libpng.h"  // NOLINT(build/include)
#include "sandboxed_api/vars.h"

absl::Status LibPNGMain(const std::string& infile, const std::string& outfile) {
  LibPNGSapiSandbox sandbox;
  sandbox.AddFile(infile);
  sandbox.AddFile(outfile);

  SAPI_RETURN_IF_ERROR(sandbox.Init());
  LibPNGApi api(&sandbox);

  sapi::v::Struct<png_image> image;
  sapi::v::ConstCStr infile_var(infile.c_str());
  sapi::v::ConstCStr outfile_var(outfile.c_str());

  image.mutable_data()->version = PNG_IMAGE_VERSION;

  SAPI_ASSIGN_OR_RETURN(
      int result, api.png_image_begin_read_from_file(image.PtrBoth(),
                                                     infile_var.PtrBefore()));
  if (!result) {
    return absl::InternalError(
        absl::StrCat("begin read error: ", image.mutable_data()->message));
  }

  image.mutable_data()->format = PNG_FORMAT_RGBA;

  sapi::v::Array<uint8_t> buffer(PNG_IMAGE_SIZE(*image.mutable_data()));

  sapi::v::NullPtr null = sapi::v::NullPtr();
  SAPI_ASSIGN_OR_RETURN(result,
                        api.png_image_finish_read(image.PtrBoth(), &null,
                                                  buffer.PtrBoth(), 0, &null));
  if (!result) {
    return absl::InternalError(
        absl::StrCat("finish read error: ", image.mutable_data()->message));
  }

  SAPI_ASSIGN_OR_RETURN(result, api.png_image_write_to_file(
                                    image.PtrBoth(), outfile_var.PtrBefore(), 0,
                                    buffer.PtrBoth(), 0, &null));
  if (!result) {
    return absl::InternalError(
        absl::StrCat("write error: ", image.mutable_data()->message));
  }

  return absl::OkStatus();
}

int main(int argc, const char** argv) {
  if (argc != 3) {
    LOG(ERROR) << "usage: example input-file output-file";
    return EXIT_FAILURE;
  }

  auto status = LibPNGMain(argv[1], argv[2]);
  if (!status.ok()) {
    LOG(ERROR) << "LibPNGMain failed with error:\n"
               << status.ToString() << '\n';
    return EXIT_FAILURE;
  }

  return EXIT_SUCCESS;
}


<|start_filename|>sandboxed_api/testing.cc<|end_filename|>
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "sandboxed_api/testing.h"

#include "absl/strings/string_view.h"
#include "sandboxed_api/util/path.h"

namespace sapi {

std::string GetTestTempPath(absl::string_view name) {
  // When using Bazel, the environment variable TEST_TMPDIR is guaranteed to be
  // set.
  // See https://docs.bazel.build/versions/master/test-encyclopedia.html for
  // details.
  const char* test_tmpdir = getenv("TEST_TMPDIR");
  return file::JoinPath(test_tmpdir ? test_tmpdir : ".", name);
}

std::string GetTestSourcePath(absl::string_view name) {
  // Like in GetTestTempPath(), when using Bazel, the environment variable
  // TEST_SRCDIR is guaranteed to be set.
  const char* test_srcdir = getenv("TEST_SRCDIR");
  return file::JoinPath(test_srcdir ? test_srcdir : ".",
                        "com_google_sandboxed_api/sandboxed_api", name);
}

}  // namespace sapi


<|start_filename|>oss-internship-2020/jsonnet/headers/jsonnet_base_sandbox.h<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef JSONNET_BASE_SANDBOX_H_
#define JSONNET_BASE_SANDBOX_H_

#include <libgen.h>
#include <syscall.h>

#include "jsonnet_sapi.sapi.h"  // NOLINT(build/include)
#include "sandboxed_api/util/flag.h"
#include "sandboxed_api/transaction.h"
#include "sandboxed_api/vars.h"

class JsonnetBaseSandbox : public JsonnetSandbox {
 public:
  explicit JsonnetBaseSandbox(std::string in_file, std::string out_file)
      : in_file_(in_file), out_file_(out_file) {}

  std::unique_ptr<sandbox2::Policy> ModifyPolicy(
      sandbox2::PolicyBuilder *) override {
    return sandbox2::PolicyBuilder()
        .AllowStaticStartup()
        .AllowOpen()
        .AllowRead()
        .AllowWrite()
        .AllowStat()
        .AllowSystemMalloc()
        .AllowExit()
        .AllowSyscalls({
            __NR_futex,
            __NR_close,
        })
        .AddDirectoryAt(dirname(&out_file_[0]), "/output", /*is_ro=*/false)
        .AddDirectoryAt(dirname(&in_file_[0]), "/input", true)
        .BuildOrDie();
  }

 private:
  std::string in_file_;
  std::string out_file_;
};

#endif  // JSONNET_BASE_SANDBOX_H_


<|start_filename|>oss-internship-2020/libuv/tests/test_os.cc<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <linux/futex.h>
#include <syscall.h>
#include <uv.h>

#include "gtest/gtest.h"
#include "sandboxed_api/util/flag.h"
#include "sandboxed_api/util/status_matchers.h"
#include "uv_sapi.sapi.h"  // NOLINT(build/include)

namespace {

class UVTestOSSapiSandbox : public uv::UVSandbox {
 private:
  std::unique_ptr<sandbox2::Policy> ModifyPolicy(
      sandbox2::PolicyBuilder*) override {
    return sandbox2::PolicyBuilder()
        .AllowDynamicStartup()
        .AllowExit()
        .AllowFutexOp(FUTEX_WAKE_PRIVATE)
        .AllowGetIDs()
        .AllowMmap()
        .AllowOpen()
        .AllowWrite()
        .AllowSyscalls({__NR_connect, __NR_socket})
        .DisableNamespaces()
        .BuildOrDie();
  }
};

class UVTestOS : public ::testing::Test {
 protected:
  void SetUp() override {
    sandbox_ = std::make_unique<UVTestOSSapiSandbox>();
    ASSERT_THAT(sandbox_->Init(), sapi::IsOk());
    api_ = std::make_unique<uv::UVApi>(sandbox_.get());
  }

  std::unique_ptr<UVTestOSSapiSandbox> sandbox_;
  std::unique_ptr<uv::UVApi> api_;

  static constexpr size_t kBigBufLen = 4096;
  static constexpr size_t kSmallBufLen = 1;
};

TEST_F(UVTestOS, HomeDirBig) {
  // Get expected home directory
  char expected_homedir[kBigBufLen];
  size_t len = sizeof(expected_homedir);
  ASSERT_GE(uv_os_homedir(expected_homedir, &len), 0);

  // Get home directory from the sandbox
  sapi::v::Array<char> uv_homedir(kBigBufLen);
  uv_homedir[0] = '\0';
  sapi::v::IntBase<size_t> uv_homedir_len(kBigBufLen);
  SAPI_ASSERT_OK_AND_ASSIGN(
      int error_code,
      api_->sapi_uv_os_homedir(uv_homedir.PtrBoth(), uv_homedir_len.PtrBoth()));
  ASSERT_GE(error_code, 0);

  // Test home directory is as expected
  ASSERT_EQ(std::string{uv_homedir.GetData()}, std::string{expected_homedir});
}

TEST_F(UVTestOS, HomeDirSmall) {
  // Try getting expected home directory, error because array is too small
  char expected_homedir[kSmallBufLen];
  size_t len = sizeof(expected_homedir);
  int expected_error_code = uv_os_homedir(expected_homedir, &len);
  ASSERT_NE(expected_error_code, 0);

  // Try getting home directory from sandbox, error because array is too small
  sapi::v::Array<char> uv_homedir(kSmallBufLen);
  uv_homedir[0] = '\0';
  sapi::v::IntBase<size_t> uv_homedir_len(kSmallBufLen);
  SAPI_ASSERT_OK_AND_ASSIGN(
      int error_code,
      api_->sapi_uv_os_homedir(uv_homedir.PtrBoth(), uv_homedir_len.PtrBoth()));
  ASSERT_NE(error_code, 0);

  // Test error code is as expected
  ASSERT_EQ(error_code, expected_error_code);
}

TEST_F(UVTestOS, TmpDirBig) {
  // Get expected tmp directory
  char expected_tmpdir[kBigBufLen];
  size_t len = sizeof(expected_tmpdir);
  ASSERT_GE(uv_os_tmpdir(expected_tmpdir, &len), 0);

  // Get tmp directory from the sandbox
  sapi::v::Array<char> uv_tmpdir(kBigBufLen);
  uv_tmpdir[0] = '\0';
  sapi::v::IntBase<size_t> uv_tmpdir_len(kBigBufLen);
  SAPI_ASSERT_OK_AND_ASSIGN(
      int error_code,
      api_->sapi_uv_os_tmpdir(uv_tmpdir.PtrBoth(), uv_tmpdir_len.PtrBoth()));
  ASSERT_GE(error_code, 0);

  // Test tmp directory is as expected
  ASSERT_EQ(std::string{uv_tmpdir.GetData()}, std::string{expected_tmpdir});
}

TEST_F(UVTestOS, TmpDirSmall) {
  // Try getting expected tmp directory, error because array is too small
  char expected_tmpdir[kSmallBufLen];
  size_t len = sizeof(expected_tmpdir);
  int expected_error_code = uv_os_tmpdir(expected_tmpdir, &len);
  ASSERT_NE(expected_error_code, 0);

  // Try getting tmp directory from sandbox, error because array is too small
  sapi::v::Array<char> uv_tmpdir(kSmallBufLen);
  uv_tmpdir[0] = '\0';
  sapi::v::IntBase<size_t> uv_tmpdir_len(kSmallBufLen);
  SAPI_ASSERT_OK_AND_ASSIGN(
      int error_code,
      api_->sapi_uv_os_tmpdir(uv_tmpdir.PtrBoth(), uv_tmpdir_len.PtrBoth()));
  ASSERT_NE(error_code, 0);

  // Test error code is as expected
  ASSERT_EQ(error_code, expected_error_code);
}

}  // namespace


<|start_filename|>oss-internship-2020/gdal/raster_to_gtiff/get_raster_data.cc<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "get_raster_data.h"  // NOLINT(build/include)

#include <memory>

#include "gdal.h"  // NOLINT(build/include)

namespace gdal::sandbox::parser {

namespace {

inline constexpr int kGeoTransformSize = 6;

}  // namespace

RasterDataset GetRasterBandsFromFile(const std::string& filename) {
  GDALAllRegister();
  GDALDatasetH dataset = GDALOpen(filename.data(), GA_ReadOnly);
  GDALDriverH driver = GDALGetDatasetDriver(dataset);

  RasterDataset result_dataset = {GDALGetRasterXSize(dataset),
                                  GDALGetRasterYSize(dataset)};

  if (GDALGetProjectionRef(dataset) != nullptr) {
    result_dataset.wkt_projection = std::string(GDALGetProjectionRef(dataset));
  }

  std::vector<double> geo_transform(kGeoTransformSize, 0.0);

  if (GDALGetGeoTransform(dataset, geo_transform.data()) == CE_None) {
    result_dataset.geo_transform = std::move(geo_transform);
  }

  int bands_count = GDALGetRasterCount(dataset);

  std::vector<RasterBandData> bands_data;
  bands_data.reserve(bands_count);

  for (int i = 1; i <= bands_count; ++i) {
    GDALRasterBandH band = GDALGetRasterBand(dataset, i);
    int width = GDALGetRasterBandXSize(band);
    int height = GDALGetRasterBandYSize(band);

    std::unique_ptr<int> no_data_result = nullptr;
    double no_data_value = GDALGetRasterNoDataValue(band, no_data_result.get());
    std::optional<double> no_data_value_holder =
        no_data_result.get() == nullptr
            ? std::nullopt
            : std::make_optional<double>(no_data_value);

    int data_type = static_cast<int>(GDALGetRasterDataType(band));
    int color_interp = static_cast<int>(GDALGetRasterColorInterpretation(band));

    std::vector<int32_t> band_raster_data(width * height);

    // GDALRasterIO with GF_Write should use the same type (GDT_Int32)
    GDALRasterIO(band, GF_Read, 0, 0, width, height, band_raster_data.data(),
                 width, height, GDT_Int32, 0, 0);

    bands_data.push_back({width, height, std::move(band_raster_data), data_type,
                          color_interp, std::move(no_data_value_holder)});
  }

  result_dataset.bands = std::move(bands_data);

  GDALClose(dataset);

  return result_dataset;
}

bool operator==(const RasterBandData& lhs, const RasterBandData& rhs) {
  return lhs.width == rhs.width && lhs.height == rhs.height &&
         lhs.data == rhs.data && lhs.data_type == rhs.data_type &&
         lhs.color_interp == rhs.color_interp &&
         lhs.no_data_value == rhs.no_data_value;
}

bool operator==(const RasterDataset& lhs, const RasterDataset& rhs) {
  return lhs.width == rhs.width && lhs.height == rhs.height &&
         lhs.bands == rhs.bands && lhs.wkt_projection == rhs.wkt_projection &&
         lhs.geo_transform == rhs.geo_transform;
}

}  // namespace gdal::sandbox::parser


<|start_filename|>oss-internship-2020/jsonnet/jsonnet_helper.h<|end_filename|>
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef JSONNET_HELPER_H_
#define JSONNET_HELPER_H_

extern "C" {
#include <libjsonnet.h>  // NOLINT(build/include)
#include <libjsonnet_fmt.h>  // NOLINT(build/include)
}

#include "jsonnet/cmd/utils.h"  // NOLINT(build/include)

extern "C" struct JsonnetVm* c_jsonnet_make(void);

extern "C" void c_jsonnet_destroy(struct JsonnetVm* vm);

extern "C" char* c_jsonnet_evaluate_snippet(struct JsonnetVm* vm,
                                            const char* filename, char* snippet,
                                            int* error);

extern "C" char* c_jsonnet_evaluate_snippet_multi(struct JsonnetVm* vm,
                                                  const char* filename,
                                                  const char* snippet,
                                                  int* error);

extern "C" char* c_jsonnet_evaluate_snippet_stream(struct JsonnetVm* vm,
                                                   const char* filename,
                                                   const char* snippet,
                                                   int* error);

extern "C" char* c_read_input(bool filename_is_code, const char* filename);

extern "C" void c_free_input(char* input);

extern "C" bool c_write_output_file(const char* output,
                                    const char* output_file);

extern "C" char* c_jsonnet_realloc(struct JsonnetVm* vm, char* str, size_t sz);

extern "C" bool c_write_multi_output_files(char* output, char* output_dir,
                                           bool show_output_file_names);

bool write_multi_output_files(char* output, const std::string& output_dir,
                              bool show_output_file_names);

extern "C" bool c_write_output_stream(char* output, char* output_file);

bool write_output_stream(char* output, const std::string& output_file);

extern "C" char* c_jsonnet_fmt_snippet(struct JsonnetVm* vm,
                                       const char* filename,
                                       const char* snippet, int* error);

#endif  // JSONNET_HELPER_H_


<|start_filename|>sandboxed_api/sandbox2/global_forkclient.h<|end_filename|>
// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// StartGlobalForkServer() is called early in a process using a constructor, so
// it can fork() safely (in a single-threaded context)

#ifndef SANDBOXED_API_SANDBOX2_GLOBAL_FORKCLIENT_H_
#define SANDBOXED_API_SANDBOX2_GLOBAL_FORKCLIENT_H_

#include <sys/types.h>

#include <bitset>
#include <string>

#include "absl/base/thread_annotations.h"
#include "sandboxed_api/util/flag.h"
#include "absl/strings/string_view.h"
#include "absl/synchronization/mutex.h"
#include "sandboxed_api/sandbox2/comms.h"
#include "sandboxed_api/sandbox2/fork_client.h"
#include "sandboxed_api/sandbox2/forkserver.pb.h"

namespace sandbox2 {

enum class GlobalForkserverStartMode {
  kOnDemand,
  // MUST be the last element
  kNumGlobalForkserverStartModes,
};

class GlobalForkClient {
 public:
  GlobalForkClient(int fd, pid_t pid)
      : comms_(fd), fork_client_(pid, &comms_) {}

  static pid_t SendRequest(const ForkRequest& request, int exec_fd,
                           int comms_fd, int user_ns_fd = -1,
                           pid_t* init_pid = nullptr)
      ABSL_LOCKS_EXCLUDED(instance_mutex_);
  static pid_t GetPid() ABSL_LOCKS_EXCLUDED(instance_mutex_);

  static void EnsureStarted() ABSL_LOCKS_EXCLUDED(instance_mutex_) {
    EnsureStarted(GlobalForkserverStartMode::kOnDemand);
  }
  static void Shutdown() ABSL_LOCKS_EXCLUDED(instance_mutex_);
  static bool IsStarted() ABSL_LOCKS_EXCLUDED(instance_mutex_);

 private:
  friend void StartGlobalForkserverFromLibCtor();

  static void ForceStart() ABSL_LOCKS_EXCLUDED(instance_mutex_);
  static void EnsureStarted(GlobalForkserverStartMode mode)
      ABSL_LOCKS_EXCLUDED(instance_mutex_);
  static void EnsureStartedLocked(GlobalForkserverStartMode mode)
      ABSL_EXCLUSIVE_LOCKS_REQUIRED(instance_mutex_);

  static absl::Mutex instance_mutex_;
  static GlobalForkClient* instance_ ABSL_GUARDED_BY(instance_mutex_);

  Comms comms_;
  ForkClient fork_client_;
};

class GlobalForkserverStartModeSet {
 public:
  static constexpr size_t kSize = static_cast<size_t>(
      GlobalForkserverStartMode::kNumGlobalForkserverStartModes);

  GlobalForkserverStartModeSet() {}
  explicit GlobalForkserverStartModeSet(GlobalForkserverStartMode value) {
    value_[static_cast<size_t>(value)] = true;
  }
  GlobalForkserverStartModeSet& operator|=(GlobalForkserverStartMode value) {
    value_[static_cast<size_t>(value)] = true;
    return *this;
  }
  GlobalForkserverStartModeSet operator|(
      GlobalForkserverStartMode value) const {
    GlobalForkserverStartModeSet rv(*this);
    rv |= value;
    return rv;
  }
  bool contains(GlobalForkserverStartMode value) const {
    return value_[static_cast<size_t>(value)];
  }
  bool empty() { return value_.none(); }

 private:
  std::bitset<kSize> value_;
};

bool AbslParseFlag(absl::string_view text, GlobalForkserverStartModeSet* out,
                   std::string* error);
std::string AbslUnparseFlag(GlobalForkserverStartModeSet in);

}  // namespace sandbox2

ABSL_DECLARE_FLAG(string, sandbox2_forkserver_start_mode);

#endif  // SANDBOXED_API_SANDBOX2_GLOBAL_FORKCLIENT_H_
