xref: /aosp_15_r20/external/cronet/base/files/file_util_apple.mm (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1// Copyright 2012 The Chromium Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "base/files/file_util.h"
6
7#import <Foundation/Foundation.h>
8#include <copyfile.h>
9#include <stdlib.h>
10#include <string.h>
11
12#include "base/apple/foundation_util.h"
13#include "base/check_op.h"
14#include "base/files/file_path.h"
15#include "base/strings/string_util.h"
16#include "base/threading/scoped_blocking_call.h"
17
18namespace base {
19
20bool CopyFile(const FilePath& from_path, const FilePath& to_path) {
21  ScopedBlockingCall scoped_blocking_call(FROM_HERE, BlockingType::MAY_BLOCK);
22  if (from_path.ReferencesParent() || to_path.ReferencesParent()) {
23    return false;
24  }
25  return (copyfile(from_path.value().c_str(), to_path.value().c_str(),
26                   /*state=*/nullptr, COPYFILE_DATA) == 0);
27}
28
29bool GetTempDir(base::FilePath* path) {
30  // In order to facilitate hermetic runs on macOS, first check
31  // MAC_CHROMIUM_TMPDIR. This is used instead of TMPDIR for historical reasons.
32  // This was originally done for https://crbug.com/698759 (TMPDIR too long for
33  // process singleton socket path), but is hopefully obsolete as of
34  // https://crbug.com/1266817 (allows a longer process singleton socket path).
35  // Continue tracking MAC_CHROMIUM_TMPDIR as that's what build infrastructure
36  // sets on macOS.
37  const char* env_tmpdir = getenv("MAC_CHROMIUM_TMPDIR");
38  if (env_tmpdir) {
39    *path = base::FilePath(env_tmpdir);
40    return true;
41  }
42
43  // If we didn't find it, fall back to the native function.
44  NSString* tmp = NSTemporaryDirectory();
45  if (tmp == nil) {
46    return false;
47  }
48  *path = base::apple::NSStringToFilePath(tmp);
49  return true;
50}
51
52FilePath GetHomeDir() {
53  NSString* tmp = NSHomeDirectory();
54  if (tmp != nil) {
55    FilePath mac_home_dir = base::apple::NSStringToFilePath(tmp);
56    if (!mac_home_dir.empty()) {
57      return mac_home_dir;
58    }
59  }
60
61  // Fall back on temp dir if no home directory is defined.
62  FilePath rv;
63  if (GetTempDir(&rv)) {
64    return rv;
65  }
66
67  // Last resort.
68  return FilePath("/tmp");
69}
70
71}  // namespace base
72