From 3ffaed019d0772e59d6cdb2d0d32fe4834c31f72 Mon Sep 17 00:00:00 2001 From: Allan Sandfeld Jensen Date: Tue, 9 Apr 2019 17:53:07 +0200 Subject: BASELINE: Update GN Change-Id: Ie794eb9f8e5c17c6caea72b89ce954c7ad772eaa Reviewed-by: Michal Klocek --- gn/AUTHORS | 1 + gn/OWNERS | 1 - gn/README.md | 18 +- gn/base/files/file_path.cc | 21 - gn/base/files/file_posix.cc | 16 +- gn/base/files/file_util.cc | 6 - gn/base/files/file_util.h | 73 -- gn/base/files/file_util_mac.mm | 64 -- gn/base/files/file_util_posix.cc | 190 ---- gn/base/files/file_util_win.cc | 199 ---- gn/base/logging.cc | 1 - gn/base/mac/bundle_locations.mm | 83 -- gn/base/mac/foundation_util.h | 406 ------- gn/base/mac/foundation_util.mm | 475 --------- gn/base/numerics/safe_conversions.h | 5 - gn/base/numerics/safe_math_clang_gcc_impl.h | 5 - gn/base/strings/sys_string_conversions.h | 82 -- gn/base/strings/sys_string_conversions_mac.mm | 176 ---- gn/base/strings/sys_string_conversions_posix.cc | 163 --- gn/base/strings/sys_string_conversions_win.cc | 71 -- gn/build/gen.py | 142 +-- gn/docs/faq.md | 6 + gn/docs/hacking.md | 23 - gn/docs/reference.md | 1113 ++++++++++++-------- gn/docs/standalone.md | 2 +- gn/docs/style_guide.md | 50 +- gn/docs/update_binaries.md | 5 - gn/infra/README.recipes.md | 68 +- gn/infra/recipe_modules/macos_sdk/__init__.py | 44 + gn/infra/recipe_modules/macos_sdk/api.py | 92 ++ .../macos_sdk/examples/full.expected/linux.json | 23 + .../macos_sdk/examples/full.expected/mac.json | 83 ++ .../macos_sdk/examples/full.expected/win.json | 23 + gn/infra/recipe_modules/macos_sdk/examples/full.py | 22 + gn/infra/recipe_modules/windows_sdk/__init__.py | 12 +- gn/infra/recipe_modules/windows_sdk/api.py | 55 +- .../windows_sdk/examples/full.expected/win.json | 12 +- .../recipe_modules/windows_sdk/examples/full.py | 2 +- gn/infra/recipes/gn.expected/ci.json | 375 ------- gn/infra/recipes/gn.expected/ci_linux.json | 229 ++++ gn/infra/recipes/gn.expected/ci_mac.json | 295 ++++++ gn/infra/recipes/gn.expected/ci_win.json | 340 ++++++ gn/infra/recipes/gn.expected/cipd_exists.json | 34 +- gn/infra/recipes/gn.expected/cipd_register.json | 38 +- gn/infra/recipes/gn.expected/cq.json | 380 ------- gn/infra/recipes/gn.expected/cq_linux.json | 234 ++++ gn/infra/recipes/gn.expected/cq_mac.json | 300 ++++++ gn/infra/recipes/gn.expected/cq_win.json | 345 ++++++ gn/infra/recipes/gn.py | 99 +- gn/tools/gn/args.cc | 2 + gn/tools/gn/build_settings.cc | 3 +- gn/tools/gn/build_settings.h | 3 + gn/tools/gn/bundle_data.cc | 25 +- gn/tools/gn/bundle_data.h | 15 +- gn/tools/gn/bundle_file_rule.cc | 75 +- gn/tools/gn/bundle_file_rule.h | 19 +- gn/tools/gn/c_include_iterator.cc | 9 +- gn/tools/gn/c_include_iterator_unittest.cc | 17 + gn/tools/gn/command_analyze.cc | 1 + gn/tools/gn/command_args.cc | 7 +- gn/tools/gn/command_check.cc | 23 +- gn/tools/gn/command_clean.cc | 1 + gn/tools/gn/command_desc.cc | 335 ++++-- gn/tools/gn/command_format.cc | 248 +++-- gn/tools/gn/command_format.h | 16 +- gn/tools/gn/command_format_unittest.cc | 14 +- gn/tools/gn/command_gen.cc | 11 +- gn/tools/gn/command_help.cc | 139 ++- gn/tools/gn/command_ls.cc | 1 + gn/tools/gn/command_meta.cc | 163 +++ gn/tools/gn/command_path.cc | 1 + gn/tools/gn/command_refs.cc | 7 +- gn/tools/gn/commands.cc | 1 + gn/tools/gn/commands.h | 11 +- gn/tools/gn/create_bundle_target_generator.cc | 5 +- gn/tools/gn/desc_builder.cc | 91 +- gn/tools/gn/exec_process.cc | 1 + gn/tools/gn/exec_process_unittest.cc | 2 - gn/tools/gn/filesystem_utils.cc | 7 +- gn/tools/gn/filesystem_utils_unittest.cc | 4 + gn/tools/gn/format_test_data/028.golden | 2 +- gn/tools/gn/format_test_data/066.gn | 2 + gn/tools/gn/format_test_data/066.golden | 2 + gn/tools/gn/format_test_data/071.gn | 26 + gn/tools/gn/format_test_data/071.golden | 25 + gn/tools/gn/format_test_data/072.gn | 8 + gn/tools/gn/format_test_data/072.golden | 21 + gn/tools/gn/format_test_data/073.gn | 23 + gn/tools/gn/format_test_data/073.golden | 34 + gn/tools/gn/format_test_data/074.gn | 7 + gn/tools/gn/format_test_data/074.golden | 7 + gn/tools/gn/format_test_data/075.gn | 11 + gn/tools/gn/format_test_data/075.golden | 12 + gn/tools/gn/function_exec_script.cc | 25 +- gn/tools/gn/function_forward_variables_from.cc | 7 + gn/tools/gn/function_get_path_info.cc | 2 +- gn/tools/gn/function_set_defaults.cc | 2 +- gn/tools/gn/function_write_file_unittest.cc | 2 +- gn/tools/gn/functions.cc | 38 +- gn/tools/gn/functions.h | 9 + gn/tools/gn/functions_target.cc | 190 +++- gn/tools/gn/functions_target_unittest.cc | 52 + gn/tools/gn/functions_unittest.cc | 12 + gn/tools/gn/generated_file_target_generator.cc | 168 +++ gn/tools/gn/generated_file_target_generator.h | 49 + gn/tools/gn/header_checker.cc | 101 +- gn/tools/gn/header_checker.h | 31 +- gn/tools/gn/header_checker_unittest.cc | 79 +- gn/tools/gn/input_conversion.cc | 24 +- gn/tools/gn/label_ptr.h | 49 +- gn/tools/gn/metadata.cc | 69 ++ gn/tools/gn/metadata.h | 69 ++ gn/tools/gn/metadata_unittest.cc | 204 ++++ gn/tools/gn/metadata_walk.cc | 24 + gn/tools/gn/metadata_walk.h | 26 + gn/tools/gn/metadata_walk_unittest.cc | 211 ++++ gn/tools/gn/misc/emacs/gn-mode.el | 23 +- gn/tools/gn/misc/tm/GN.tmLanguage | 4 +- gn/tools/gn/misc/vim/README.chromium | 5 - gn/tools/gn/misc/vim/README.md | 29 + gn/tools/gn/misc/vim/syntax/gn.vim | 5 +- gn/tools/gn/ninja_action_target_writer_unittest.cc | 8 +- gn/tools/gn/ninja_build_writer.cc | 36 +- gn/tools/gn/ninja_build_writer.h | 10 + gn/tools/gn/ninja_build_writer_unittest.cc | 86 +- gn/tools/gn/ninja_create_bundle_target_writer.cc | 32 +- .../ninja_create_bundle_target_writer_unittest.cc | 2 - gn/tools/gn/ninja_generated_file_target_writer.cc | 92 ++ gn/tools/gn/ninja_generated_file_target_writer.h | 25 + .../ninja_generated_file_target_writer_unittest.cc | 60 ++ gn/tools/gn/ninja_target_writer.cc | 4 + gn/tools/gn/operators.cc | 5 +- gn/tools/gn/operators_unittest.cc | 43 +- gn/tools/gn/output_conversion.cc | 4 + gn/tools/gn/parse_tree.cc | 200 ++-- gn/tools/gn/parse_tree.h | 51 +- gn/tools/gn/parser.cc | 51 + gn/tools/gn/parser.h | 5 + gn/tools/gn/parser_unittest.cc | 4 +- gn/tools/gn/qt_creator_writer.cc | 128 ++- gn/tools/gn/scheduler.cc | 10 + gn/tools/gn/scheduler.h | 5 + gn/tools/gn/scope.cc | 17 + gn/tools/gn/scope.h | 5 + gn/tools/gn/setup.cc | 100 +- gn/tools/gn/setup.h | 23 +- gn/tools/gn/setup_unittest.cc | 45 + gn/tools/gn/source_dir.h | 10 + gn/tools/gn/source_dir_unittest.cc | 21 + gn/tools/gn/standard_out.cc | 68 +- gn/tools/gn/standard_out.h | 24 +- gn/tools/gn/substitution_pattern.h | 2 + gn/tools/gn/substitution_type.cc | 8 +- gn/tools/gn/substitution_type.h | 1 - gn/tools/gn/substitution_writer.h | 1 + gn/tools/gn/switches.cc | 36 +- gn/tools/gn/switches.h | 12 + gn/tools/gn/target.cc | 112 +- gn/tools/gn/target.h | 47 +- gn/tools/gn/target_generator.cc | 39 + gn/tools/gn/target_generator.h | 1 + gn/tools/gn/target_unittest.cc | 214 ++++ gn/tools/gn/toolchain.cc | 2 + gn/tools/gn/value.cc | 134 ++- gn/tools/gn/value.h | 30 +- gn/tools/gn/value_unittest.cc | 19 +- gn/tools/gn/variables.cc | 142 ++- gn/tools/gn/variables.h | 28 +- gn/tools/gn/visual_studio_writer.cc | 16 +- gn/tools/gn/visual_studio_writer.h | 3 +- gn/tools/gn/xcode_writer.cc | 19 +- gn/util/exe_path.cc | 15 + gn/util/semaphore.cc | 2 +- gn/util/semaphore.h | 4 +- gn/util/ticks.cc | 8 +- 175 files changed, 7276 insertions(+), 4241 deletions(-) delete mode 100644 gn/base/files/file_util_mac.mm delete mode 100644 gn/base/mac/bundle_locations.mm delete mode 100644 gn/base/mac/foundation_util.h delete mode 100644 gn/base/mac/foundation_util.mm delete mode 100644 gn/base/strings/sys_string_conversions.h delete mode 100644 gn/base/strings/sys_string_conversions_mac.mm delete mode 100644 gn/base/strings/sys_string_conversions_posix.cc delete mode 100644 gn/base/strings/sys_string_conversions_win.cc delete mode 100644 gn/docs/hacking.md delete mode 100644 gn/docs/update_binaries.md create mode 100644 gn/infra/recipe_modules/macos_sdk/__init__.py create mode 100644 gn/infra/recipe_modules/macos_sdk/api.py create mode 100644 gn/infra/recipe_modules/macos_sdk/examples/full.expected/linux.json create mode 100644 gn/infra/recipe_modules/macos_sdk/examples/full.expected/mac.json create mode 100644 gn/infra/recipe_modules/macos_sdk/examples/full.expected/win.json create mode 100644 gn/infra/recipe_modules/macos_sdk/examples/full.py delete mode 100644 gn/infra/recipes/gn.expected/ci.json create mode 100644 gn/infra/recipes/gn.expected/ci_linux.json create mode 100644 gn/infra/recipes/gn.expected/ci_mac.json create mode 100644 gn/infra/recipes/gn.expected/ci_win.json delete mode 100644 gn/infra/recipes/gn.expected/cq.json create mode 100644 gn/infra/recipes/gn.expected/cq_linux.json create mode 100644 gn/infra/recipes/gn.expected/cq_mac.json create mode 100644 gn/infra/recipes/gn.expected/cq_win.json create mode 100644 gn/tools/gn/command_meta.cc create mode 100644 gn/tools/gn/format_test_data/071.gn create mode 100644 gn/tools/gn/format_test_data/071.golden create mode 100644 gn/tools/gn/format_test_data/072.gn create mode 100644 gn/tools/gn/format_test_data/072.golden create mode 100644 gn/tools/gn/format_test_data/073.gn create mode 100644 gn/tools/gn/format_test_data/073.golden create mode 100644 gn/tools/gn/format_test_data/074.gn create mode 100644 gn/tools/gn/format_test_data/074.golden create mode 100644 gn/tools/gn/format_test_data/075.gn create mode 100644 gn/tools/gn/format_test_data/075.golden create mode 100644 gn/tools/gn/generated_file_target_generator.cc create mode 100644 gn/tools/gn/generated_file_target_generator.h create mode 100644 gn/tools/gn/metadata.cc create mode 100644 gn/tools/gn/metadata.h create mode 100644 gn/tools/gn/metadata_unittest.cc create mode 100644 gn/tools/gn/metadata_walk.cc create mode 100644 gn/tools/gn/metadata_walk.h create mode 100644 gn/tools/gn/metadata_walk_unittest.cc delete mode 100644 gn/tools/gn/misc/vim/README.chromium create mode 100644 gn/tools/gn/misc/vim/README.md create mode 100644 gn/tools/gn/ninja_generated_file_target_writer.cc create mode 100644 gn/tools/gn/ninja_generated_file_target_writer.h create mode 100644 gn/tools/gn/ninja_generated_file_target_writer_unittest.cc create mode 100644 gn/tools/gn/setup_unittest.cc diff --git a/gn/AUTHORS b/gn/AUTHORS index ca2667131c3..fe152fd3877 100644 --- a/gn/AUTHORS +++ b/gn/AUTHORS @@ -25,6 +25,7 @@ DanCraft99 Gergely Nagy Ilia K Ivan Naydonov +Joe Armstrong Julien Brianceau Kal Conley Kamil Rytarowski diff --git a/gn/OWNERS b/gn/OWNERS index 0200965cc3c..d78697cf06f 100644 --- a/gn/OWNERS +++ b/gn/OWNERS @@ -1,4 +1,3 @@ brettw@chromium.org -dpranke@chromium.org phosek@chromium.org scottmg@chromium.org diff --git a/gn/README.md b/gn/README.md index 5c98d1f4879..a370e008839 100644 --- a/gn/README.md +++ b/gn/README.md @@ -1,14 +1,25 @@ # GN GN is a meta-build system that generates build files for -[Ninja](https://ninja-build.org). +[Ninja](https://ninja-build.org). There is documentation in +[docs/](https://gn.googlesource.com/gn/+/master/docs/) and +[a presentation on it](https://docs.google.com/presentation/d/15Zwb53JcncHfEwHpnG_PoIbbzQ3GQi_cpujYwbpcbZo/edit?usp=sharing). ## Getting started +You can download the latest version of GN binary for +[Linux](https://chrome-infra-packages.appspot.com/dl/gn/gn/linux-amd64/+/latest), +[macOS](https://chrome-infra-packages.appspot.com/dl/gn/gn/mac-amd64/+/latest) and +[Windows](https://chrome-infra-packages.appspot.com/dl/gn/gn/windows-amd64/+/latest). + +Alternatively, you can build GN from source: + git clone https://gn.googlesource.com/gn cd gn python build/gen.py ninja -C out + # To run tests: + out/gn_unittests On Windows, it is expected that `cl.exe`, `link.exe`, and `lib.exe` can be found in `PATH`, so you'll want to run from a Visual Studio command prompt, or @@ -18,6 +29,11 @@ On Linux and Mac, the default compiler is `clang++`, a recent version is expected to be found in `PATH`. This can be overridden by setting `CC`, `CXX`, and `AR`. +## Reporting bugs + +If you find a bug, you can see if it is known or report it in the [bug +database](https://bugs.chromium.org/p/gn/issues/list). + ## Sending patches GN uses [Gerrit](https://www.gerritcodereview.com/) for code review. The short diff --git a/gn/base/files/file_path.cc b/gn/base/files/file_path.cc index a66c8cc1ffc..014bc9e0cf8 100644 --- a/gn/base/files/file_path.cc +++ b/gn/base/files/file_path.cc @@ -11,7 +11,6 @@ #include "base/macros.h" #include "base/strings/string_piece.h" #include "base/strings/string_util.h" -#include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" #include "util/build_config.h" @@ -602,10 +601,6 @@ FilePath FilePath::FromUTF16Unsafe(StringPiece16 utf16) { // See file_path.h for a discussion of the encoding of paths on POSIX // platforms. These encoding conversion functions are not quite correct. -string16 FilePath::LossyDisplayName() const { - return WideToUTF16(SysNativeMBToWide(path_)); -} - std::string FilePath::MaybeAsASCII() const { if (base::IsStringASCII(path_)) return path_; @@ -613,37 +608,21 @@ std::string FilePath::MaybeAsASCII() const { } std::string FilePath::AsUTF8Unsafe() const { -#if defined(SYSTEM_NATIVE_UTF8) return value(); -#else - return WideToUTF8(SysNativeMBToWide(value())); -#endif } string16 FilePath::AsUTF16Unsafe() const { -#if defined(SYSTEM_NATIVE_UTF8) return UTF8ToUTF16(value()); -#else - return WideToUTF16(SysNativeMBToWide(value())); -#endif } // static FilePath FilePath::FromUTF8Unsafe(StringPiece utf8) { -#if defined(SYSTEM_NATIVE_UTF8) return FilePath(utf8); -#else - return FilePath(SysWideToNativeMB(UTF8ToWide(utf8))); -#endif } // static FilePath FilePath::FromUTF16Unsafe(StringPiece16 utf16) { -#if defined(SYSTEM_NATIVE_UTF8) return FilePath(UTF16ToUTF8(utf16)); -#else - return FilePath(SysWideToNativeMB(UTF16ToWide(utf16.as_string()))); -#endif } #endif // defined(OS_WIN) diff --git a/gn/base/files/file_posix.cc b/gn/base/files/file_posix.cc index 4faf77b944a..ed9a5e2a8e3 100644 --- a/gn/base/files/file_posix.cc +++ b/gn/base/files/file_posix.cc @@ -86,14 +86,7 @@ void File::Info::FromStat(const stat_wrapper_t& stat_info) { is_symbolic_link = S_ISLNK(stat_info.st_mode); size = stat_info.st_size; -#if defined(OS_LINUX) - time_t last_modified_sec = stat_info.st_mtim.tv_sec; - int64_t last_modified_nsec = stat_info.st_mtim.tv_nsec; - time_t last_accessed_sec = stat_info.st_atim.tv_sec; - int64_t last_accessed_nsec = stat_info.st_atim.tv_nsec; - time_t creation_time_sec = stat_info.st_ctim.tv_sec; - int64_t creation_time_nsec = stat_info.st_ctim.tv_nsec; -#elif defined(OS_MACOSX) +#if defined(OS_MACOSX) time_t last_modified_sec = stat_info.st_mtimespec.tv_sec; int64_t last_modified_nsec = stat_info.st_mtimespec.tv_nsec; time_t last_accessed_sec = stat_info.st_atimespec.tv_sec; @@ -107,6 +100,13 @@ void File::Info::FromStat(const stat_wrapper_t& stat_info) { int64_t last_accessed_nsec = 0; time_t creation_time_sec = stat_info.st_ctime; int64_t creation_time_nsec = 0; +#elif defined(OS_POSIX) + time_t last_modified_sec = stat_info.st_mtim.tv_sec; + int64_t last_modified_nsec = stat_info.st_mtim.tv_nsec; + time_t last_accessed_sec = stat_info.st_atim.tv_sec; + int64_t last_accessed_nsec = stat_info.st_atim.tv_nsec; + time_t creation_time_sec = stat_info.st_ctim.tv_sec; + int64_t creation_time_nsec = stat_info.st_ctim.tv_nsec; #else #error #endif diff --git a/gn/base/files/file_util.cc b/gn/base/files/file_util.cc index d087b00f6c9..9a98a0b81e0 100644 --- a/gn/base/files/file_util.cc +++ b/gn/base/files/file_util.cc @@ -43,12 +43,6 @@ int64_t ComputeDirectorySize(const FilePath& root_path) { return running_size; } -bool Move(const FilePath& from_path, const FilePath& to_path) { - if (from_path.ReferencesParent() || to_path.ReferencesParent()) - return false; - return internal::MoveUnsafe(from_path, to_path); -} - bool ContentsEqual(const FilePath& filename1, const FilePath& filename2) { // We open the file in binary format even if they are text files because // we are just comparing that bytes are exactly same in both files and not diff --git a/gn/base/files/file_util.h b/gn/base/files/file_util.h index bfcac0169fc..e22f40f8f53 100644 --- a/gn/base/files/file_util.h +++ b/gn/base/files/file_util.h @@ -75,13 +75,6 @@ bool DeleteFile(const FilePath& path, bool recursive); bool DeleteFileAfterReboot(const FilePath& path); #endif -// Moves the given path, whether it's a file or a directory. -// If a simple rename is not possible, such as in the case where the paths are -// on different volumes, this will attempt to copy and delete. Returns -// true for success. -// This function fails if either path contains traversal components ('..'). -bool Move(const FilePath& from_path, const FilePath& to_path); - // Renames file |from_path| to |to_path|. Both paths must be on the same // volume, or the function will fail. Destination file will be created // if it doesn't exist. Prefer this function over Move when dealing with @@ -92,47 +85,6 @@ bool ReplaceFile(const FilePath& from_path, const FilePath& to_path, File::Error* error); -// Copies a single file. Use CopyDirectory() to copy directories. -// This function fails if either path contains traversal components ('..'). -// This function also fails if |to_path| is a directory. -// -// On POSIX, if |to_path| is a symlink, CopyFile() will follow the symlink. This -// may have security implications. Use with care. -// -// If |to_path| already exists and is a regular file, it will be overwritten, -// though its permissions will stay the same. -// -// If |to_path| does not exist, it will be created. The new file's permissions -// varies per platform: -// -// - This function keeps the metadata on Windows. The read only bit is not kept. -// - On Mac and iOS, |to_path| retains |from_path|'s permissions, except user -// read/write permissions are always set. -// - On Linux and Android, |to_path| has user read/write permissions only. i.e. -// Always 0600. -// - On ChromeOS, |to_path| has user read/write permissions and group/others -// read permissions. i.e. Always 0644. -bool CopyFile(const FilePath& from_path, const FilePath& to_path); - -// Copies the given path, and optionally all subdirectories and their contents -// as well. -// -// If there are files existing under to_path, always overwrite. Returns true -// if successful, false otherwise. Wildcards on the names are not supported. -// -// This function has the same metadata behavior as CopyFile(). -// -// If you only need to copy a file use CopyFile, it's faster. -bool CopyDirectory(const FilePath& from_path, - const FilePath& to_path, - bool recursive); - -// Like CopyDirectory() except trying to overwrite an existing file will not -// work and will return false. -bool CopyDirectoryExcl(const FilePath& from_path, - const FilePath& to_path, - bool recursive); - // Returns true if the given path exists on the local filesystem, // false otherwise. bool PathExists(const FilePath& path); @@ -241,14 +193,6 @@ bool IsDirectoryEmpty(const FilePath& dir_path); // they're open (which can lead to security issues). bool GetTempDir(FilePath* path); -// Get the home directory. This is more complicated than just getenv("HOME") -// as it knows to fall back on getpwent() etc. -// -// You should not generally call this directly. Instead use DIR_HOME with the -// path service which will use this function but cache the value. -// Path service may also override DIR_HOME. -FilePath GetHomeDir(); - // Creates a temporary file. The full path is placed in |path|, and the // function returns true if was successful in creating the file. The file will // be empty and all handles closed after this function returns. @@ -446,23 +390,6 @@ bool GetFileSystemType(const FilePath& path, FileSystemType* type); bool GetShmemTempDir(bool executable, FilePath* path); #endif -// Internal -------------------------------------------------------------------- - -namespace internal { - -// Same as Move but allows paths with traversal components. -// Use only with extreme care. -bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path); - -#if defined(OS_WIN) -// Copy from_path to to_path recursively and then delete from_path recursively. -// Returns true if all operations succeed. -// This function simulates Move(), but unlike Move() it works across volumes. -// This function is not transactional. -bool CopyAndDeleteDirectory(const FilePath& from_path, const FilePath& to_path); -#endif // defined(OS_WIN) - -} // namespace internal } // namespace base #endif // BASE_FILES_FILE_UTIL_H_ diff --git a/gn/base/files/file_util_mac.mm b/gn/base/files/file_util_mac.mm deleted file mode 100644 index 35fd27a6699..00000000000 --- a/gn/base/files/file_util_mac.mm +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/files/file_util.h" - -#import -#include -#include -#include - -#include "base/files/file_path.h" -#include "base/logging.h" -#include "base/mac/foundation_util.h" -#include "base/strings/string_util.h" - -namespace base { - -bool CopyFile(const FilePath& from_path, const FilePath& to_path) { - if (from_path.ReferencesParent() || to_path.ReferencesParent()) - return false; - return (copyfile(from_path.value().c_str(), to_path.value().c_str(), NULL, - COPYFILE_DATA) == 0); -} - -bool GetTempDir(base::FilePath* path) { - // In order to facilitate hermetic runs on macOS, first check - // $MAC_CHROMIUM_TMPDIR. We check this instead of $TMPDIR because external - // programs currently set $TMPDIR with no effect, but when we respect it - // directly it can cause crashes (like crbug.com/698759). - const char* env_tmpdir = getenv("MAC_CHROMIUM_TMPDIR"); - if (env_tmpdir) { - DCHECK_LT(strlen(env_tmpdir), 50u) - << "too-long TMPDIR causes socket name length issues."; - *path = base::FilePath(env_tmpdir); - return true; - } - - // If we didn't find it, fall back to the native function. - NSString* tmp = NSTemporaryDirectory(); - if (tmp == nil) - return false; - *path = base::mac::NSStringToFilePath(tmp); - return true; -} - -FilePath GetHomeDir() { - NSString* tmp = NSHomeDirectory(); - if (tmp != nil) { - FilePath mac_home_dir = base::mac::NSStringToFilePath(tmp); - if (!mac_home_dir.empty()) - return mac_home_dir; - } - - // Fall back on temp dir if no home directory is defined. - FilePath rv; - if (GetTempDir(&rv)) - return rv; - - // Last resort. - return FilePath("/tmp"); -} - -} // namespace base diff --git a/gn/base/files/file_util_posix.cc b/gn/base/files/file_util_posix.cc index 23c7cb4abc9..eb07e64f8e2 100644 --- a/gn/base/files/file_util_posix.cc +++ b/gn/base/files/file_util_posix.cc @@ -34,13 +34,11 @@ #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" -#include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" #include "util/build_config.h" #if defined(OS_MACOSX) #include -#include "base/mac/foundation_util.h" #endif #if !defined(OS_IOS) @@ -111,15 +109,7 @@ bool VerifySpecificPathControlledByUser(const FilePath& path, } std::string TempFileName() { -#if defined(OS_MACOSX) - return StringPrintf(".%s.XXXXXX", base::mac::BaseBundleID()); -#endif - -#if defined(GOOGLE_CHROME_BUILD) - return std::string(".com.google.Chrome.XXXXXX"); -#else return std::string(".org.chromium.Chromium.XXXXXX"); -#endif } #if defined(OS_LINUX) || defined(OS_AIX) @@ -189,143 +179,6 @@ bool CopyFileContents(File* infile, File* outfile) { NOTREACHED(); return false; } - -bool DoCopyDirectory(const FilePath& from_path, - const FilePath& to_path, - bool recursive, - bool open_exclusive) { - // Some old callers of CopyDirectory want it to support wildcards. - // After some discussion, we decided to fix those callers. - // Break loudly here if anyone tries to do this. - DCHECK(to_path.value().find('*') == std::string::npos); - DCHECK(from_path.value().find('*') == std::string::npos); - - if (from_path.value().size() >= PATH_MAX) { - return false; - } - - // This function does not properly handle destinations within the source - FilePath real_to_path = to_path; - if (PathExists(real_to_path)) - real_to_path = MakeAbsoluteFilePath(real_to_path); - else - real_to_path = MakeAbsoluteFilePath(real_to_path.DirName()); - if (real_to_path.empty()) - return false; - - FilePath real_from_path = MakeAbsoluteFilePath(from_path); - if (real_from_path.empty()) - return false; - if (real_to_path == real_from_path || real_from_path.IsParent(real_to_path)) - return false; - - int traverse_type = FileEnumerator::FILES | FileEnumerator::SHOW_SYM_LINKS; - if (recursive) - traverse_type |= FileEnumerator::DIRECTORIES; - FileEnumerator traversal(from_path, recursive, traverse_type); - - // We have to mimic windows behavior here. |to_path| may not exist yet, - // start the loop with |to_path|. - struct stat from_stat; - FilePath current = from_path; - if (stat(from_path.value().c_str(), &from_stat) < 0) { - DPLOG(ERROR) << "CopyDirectory() couldn't stat source directory: " - << from_path.value(); - return false; - } - FilePath from_path_base = from_path; - if (recursive && DirectoryExists(to_path)) { - // If the destination already exists and is a directory, then the - // top level of source needs to be copied. - from_path_base = from_path.DirName(); - } - - // The Windows version of this function assumes that non-recursive calls - // will always have a directory for from_path. - // TODO(maruel): This is not necessary anymore. - DCHECK(recursive || S_ISDIR(from_stat.st_mode)); - - do { - // current is the source path, including from_path, so append - // the suffix after from_path to to_path to create the target_path. - FilePath target_path(to_path); - if (from_path_base != current && - !from_path_base.AppendRelativePath(current, &target_path)) { - return false; - } - - if (S_ISDIR(from_stat.st_mode)) { - mode_t mode = (from_stat.st_mode & 01777) | S_IRUSR | S_IXUSR | S_IWUSR; - if (mkdir(target_path.value().c_str(), mode) == 0) - continue; - if (errno == EEXIST && !open_exclusive) - continue; - - DPLOG(ERROR) << "CopyDirectory() couldn't create directory: " - << target_path.value(); - return false; - } - - if (!S_ISREG(from_stat.st_mode)) { - DLOG(WARNING) << "CopyDirectory() skipping non-regular file: " - << current.value(); - continue; - } - - // Add O_NONBLOCK so we can't block opening a pipe. - File infile(open(current.value().c_str(), O_RDONLY | O_NONBLOCK)); - if (!infile.IsValid()) { - DPLOG(ERROR) << "CopyDirectory() couldn't open file: " << current.value(); - return false; - } - - struct stat stat_at_use; - if (fstat(infile.GetPlatformFile(), &stat_at_use) < 0) { - DPLOG(ERROR) << "CopyDirectory() couldn't stat file: " << current.value(); - return false; - } - - if (!S_ISREG(stat_at_use.st_mode)) { - DLOG(WARNING) << "CopyDirectory() skipping non-regular file: " - << current.value(); - continue; - } - - int open_flags = O_WRONLY | O_CREAT; - // If |open_exclusive| is set then we should always create the destination - // file, so O_NONBLOCK is not necessary to ensure we don't block on the - // open call for the target file below, and since the destination will - // always be a regular file it wouldn't affect the behavior of the - // subsequent write calls anyway. - if (open_exclusive) - open_flags |= O_EXCL; - else - open_flags |= O_TRUNC | O_NONBLOCK; -// Each platform has different default file opening modes for CopyFile which -// we want to replicate here. On OS X, we use copyfile(3) which takes the -// source file's permissions into account. On the other platforms, we just -// use the base::File constructor. On Chrome OS, base::File uses a different -// set of permissions than it does on other POSIX platforms. -#if defined(OS_MACOSX) - int mode = 0600 | (stat_at_use.st_mode & 0177); -#else - int mode = 0600; -#endif - File outfile(open(target_path.value().c_str(), open_flags, mode)); - if (!outfile.IsValid()) { - DPLOG(ERROR) << "CopyDirectory() couldn't create file: " - << target_path.value(); - return false; - } - - if (!CopyFileContents(&infile, &outfile)) { - DLOG(ERROR) << "CopyDirectory() couldn't copy file: " << current.value(); - return false; - } - } while (AdvanceEnumeratorWithStat(&traversal, ¤t, &from_stat)); - - return true; -} #endif // !defined(OS_NACL_NONSFI) #if !defined(OS_MACOSX) @@ -398,18 +251,6 @@ bool ReplaceFile(const FilePath& from_path, *error = File::GetLastFileError(); return false; } - -bool CopyDirectory(const FilePath& from_path, - const FilePath& to_path, - bool recursive) { - return DoCopyDirectory(from_path, to_path, recursive, false); -} - -bool CopyDirectoryExcl(const FilePath& from_path, - const FilePath& to_path, - bool recursive) { - return DoCopyDirectory(from_path, to_path, recursive, true); -} #endif // !defined(OS_NACL_NONSFI) bool CreateLocalNonBlockingPipe(int fds[2]) { @@ -578,8 +419,6 @@ bool ExecutableExistsInPath(Environment* env, #endif // !OS_FUCHSIA -#if !defined(OS_MACOSX) -// This is implemented in file_util_mac.mm for Mac. bool GetTempDir(FilePath* path) { const char* tmp = getenv("TMPDIR"); if (tmp) { @@ -590,7 +429,6 @@ bool GetTempDir(FilePath* path) { *path = FilePath("/tmp"); return true; } -#endif // !defined(OS_MACOSX) #if !defined(OS_MACOSX) // Mac implementation is in file_util_mac.mm. FilePath GetHomeDir() { @@ -945,33 +783,5 @@ bool CopyFile(const FilePath& from_path, const FilePath& to_path) { } #endif // !defined(OS_MACOSX) -// ----------------------------------------------------------------------------- - -namespace internal { - -bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) { - // Windows compatibility: if |to_path| exists, |from_path| and |to_path| - // must be the same type, either both files, or both directories. - stat_wrapper_t to_file_info; - if (CallStat(to_path.value().c_str(), &to_file_info) == 0) { - stat_wrapper_t from_file_info; - if (CallStat(from_path.value().c_str(), &from_file_info) != 0) - return false; - if (S_ISDIR(to_file_info.st_mode) != S_ISDIR(from_file_info.st_mode)) - return false; - } - - if (rename(from_path.value().c_str(), to_path.value().c_str()) == 0) - return true; - - if (!CopyDirectory(from_path, to_path, true)) - return false; - - DeleteFile(from_path, true); - return true; -} - -} // namespace internal - #endif // !defined(OS_NACL_NONSFI) } // namespace base diff --git a/gn/base/files/file_util_win.cc b/gn/base/files/file_util_win.cc index 2a1e9ecf704..34d328b5fca 100644 --- a/gn/base/files/file_util_win.cc +++ b/gn/base/files/file_util_win.cc @@ -91,121 +91,6 @@ void AppendModeCharacter(base::char16 mode_char, base::string16* mode) { 1, mode_char); } -bool DoCopyFile(const FilePath& from_path, - const FilePath& to_path, - bool fail_if_exists) { - if (from_path.ReferencesParent() || to_path.ReferencesParent()) - return false; - - // NOTE: I suspect we could support longer paths, but that would involve - // analyzing all our usage of files. - if (from_path.value().length() >= MAX_PATH || - to_path.value().length() >= MAX_PATH) { - return false; - } - - // Unlike the posix implementation that copies the file manually and discards - // the ACL bits, CopyFile() copies the complete SECURITY_DESCRIPTOR and access - // bits, which is usually not what we want. We can't do much about the - // SECURITY_DESCRIPTOR but at least remove the read only bit. - const wchar_t* dest = to_path.value().c_str(); - if (!::CopyFile(from_path.value().c_str(), dest, fail_if_exists)) { - // Copy failed. - return false; - } - DWORD attrs = GetFileAttributes(dest); - if (attrs == INVALID_FILE_ATTRIBUTES) { - return false; - } - if (attrs & FILE_ATTRIBUTE_READONLY) { - SetFileAttributes(dest, attrs & ~FILE_ATTRIBUTE_READONLY); - } - return true; -} - -bool DoCopyDirectory(const FilePath& from_path, - const FilePath& to_path, - bool recursive, - bool fail_if_exists) { - // NOTE: I suspect we could support longer paths, but that would involve - // analyzing all our usage of files. - if (from_path.value().length() >= MAX_PATH || - to_path.value().length() >= MAX_PATH) { - return false; - } - - // This function does not properly handle destinations within the source. - FilePath real_to_path = to_path; - if (PathExists(real_to_path)) { - real_to_path = MakeAbsoluteFilePath(real_to_path); - if (real_to_path.empty()) - return false; - } else { - real_to_path = MakeAbsoluteFilePath(real_to_path.DirName()); - if (real_to_path.empty()) - return false; - } - FilePath real_from_path = MakeAbsoluteFilePath(from_path); - if (real_from_path.empty()) - return false; - if (real_to_path == real_from_path || real_from_path.IsParent(real_to_path)) - return false; - - int traverse_type = FileEnumerator::FILES; - if (recursive) - traverse_type |= FileEnumerator::DIRECTORIES; - FileEnumerator traversal(from_path, recursive, traverse_type); - - if (!PathExists(from_path)) { - DLOG(ERROR) << "CopyDirectory() couldn't stat source directory: " - << from_path.value().c_str(); - return false; - } - // TODO(maruel): This is not necessary anymore. - DCHECK(recursive || DirectoryExists(from_path)); - - FilePath current = from_path; - bool from_is_dir = DirectoryExists(from_path); - bool success = true; - FilePath from_path_base = from_path; - if (recursive && DirectoryExists(to_path)) { - // If the destination already exists and is a directory, then the - // top level of source needs to be copied. - from_path_base = from_path.DirName(); - } - - while (success && !current.empty()) { - // current is the source path, including from_path, so append - // the suffix after from_path to to_path to create the target_path. - FilePath target_path(to_path); - if (from_path_base != current) { - if (!from_path_base.AppendRelativePath(current, &target_path)) { - success = false; - break; - } - } - - if (from_is_dir) { - if (!DirectoryExists(target_path) && - !::CreateDirectory(target_path.value().c_str(), NULL)) { - DLOG(ERROR) << "CopyDirectory() couldn't create directory: " - << target_path.value().c_str(); - success = false; - } - } else if (!DoCopyFile(current, target_path, fail_if_exists)) { - DLOG(ERROR) << "CopyDirectory() couldn't create file: " - << target_path.value().c_str(); - success = false; - } - - current = traversal.Next(); - if (!current.empty()) - from_is_dir = traversal.GetInfo().IsDirectory(); - } - - return success; -} - // Returns ERROR_SUCCESS on success, or a Windows error code on failure. DWORD DoDeleteFile(const FilePath& path, bool recursive) { if (path.empty()) @@ -356,18 +241,6 @@ bool ReplaceFile(const FilePath& from_path, return false; } -bool CopyDirectory(const FilePath& from_path, - const FilePath& to_path, - bool recursive) { - return DoCopyDirectory(from_path, to_path, recursive, false); -} - -bool CopyDirectoryExcl(const FilePath& from_path, - const FilePath& to_path, - bool recursive) { - return DoCopyDirectory(from_path, to_path, recursive, true); -} - bool PathExists(const FilePath& path) { return (GetFileAttributes(path.value().c_str()) != INVALID_FILE_ATTRIBUTES); } @@ -403,23 +276,6 @@ bool GetTempDir(FilePath* path) { return true; } -FilePath GetHomeDir() { - char16 result[MAX_PATH]; - if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_PROFILE, NULL, SHGFP_TYPE_CURRENT, - result)) && - result[0]) { - return FilePath(result); - } - - // Fall back to the temporary directory on failure. - FilePath temp; - if (GetTempDir(&temp)) - return temp; - - // Last resort. - return FilePath(L"C:\\"); -} - bool CreateTemporaryFile(FilePath* path) { FilePath temp_file; @@ -831,10 +687,6 @@ int GetMaximumPathComponentLength(const FilePath& path) { return std::min(whole_path_limit, static_cast(max_length)); } -bool CopyFile(const FilePath& from_path, const FilePath& to_path) { - return DoCopyFile(from_path, to_path, false); -} - bool SetNonBlocking(int fd) { unsigned long nonblocking = 1; if (ioctlsocket(fd, FIONBIO, &nonblocking) == 0) @@ -842,55 +694,4 @@ bool SetNonBlocking(int fd) { return false; } -// ----------------------------------------------------------------------------- - -namespace internal { - -bool MoveUnsafe(const FilePath& from_path, const FilePath& to_path) { - // NOTE: I suspect we could support longer paths, but that would involve - // analyzing all our usage of files. - if (from_path.value().length() >= MAX_PATH || - to_path.value().length() >= MAX_PATH) { - return false; - } - if (MoveFileEx(from_path.value().c_str(), to_path.value().c_str(), - MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING) != 0) - return true; - - // Keep the last error value from MoveFileEx around in case the below - // fails. - bool ret = false; - DWORD last_error = ::GetLastError(); - - if (DirectoryExists(from_path)) { - // MoveFileEx fails if moving directory across volumes. We will simulate - // the move by using Copy and Delete. Ideally we could check whether - // from_path and to_path are indeed in different volumes. - ret = internal::CopyAndDeleteDirectory(from_path, to_path); - } - - if (!ret) { - // Leave a clue about what went wrong so that it can be (at least) picked - // up by a PLOG entry. - ::SetLastError(last_error); - } - - return ret; -} - -bool CopyAndDeleteDirectory(const FilePath& from_path, - const FilePath& to_path) { - if (CopyDirectory(from_path, to_path, true)) { - if (DeleteFile(from_path, true)) - return true; - - // Like Move, this function is not transactional, so we just - // leave the copied bits behind if deleting from_path fails. - // If to_path exists previously then we have already overwritten - // it by now, we don't get better off by deleting the new bits. - } - return false; -} - -} // namespace internal } // namespace base diff --git a/gn/base/logging.cc b/gn/base/logging.cc index c381a284a89..c2c243f38f0 100644 --- a/gn/base/logging.cc +++ b/gn/base/logging.cc @@ -50,7 +50,6 @@ #include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" -#include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" #if defined(OS_POSIX) || defined(OS_FUCHSIA) diff --git a/gn/base/mac/bundle_locations.mm b/gn/base/mac/bundle_locations.mm deleted file mode 100644 index 54021b85ee0..00000000000 --- a/gn/base/mac/bundle_locations.mm +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/mac/bundle_locations.h" - -#include "base/logging.h" -#include "base/mac/foundation_util.h" -#include "base/strings/sys_string_conversions.h" - -namespace base { -namespace mac { - -// NSBundle isn't threadsafe, all functions in this file must be called on the -// main thread. -static NSBundle* g_override_framework_bundle = nil; -static NSBundle* g_override_outer_bundle = nil; - -NSBundle* MainBundle() { - return [NSBundle mainBundle]; -} - -FilePath MainBundlePath() { - NSBundle* bundle = MainBundle(); - return NSStringToFilePath([bundle bundlePath]); -} - -NSBundle* OuterBundle() { - if (g_override_outer_bundle) - return g_override_outer_bundle; - return [NSBundle mainBundle]; -} - -FilePath OuterBundlePath() { - NSBundle* bundle = OuterBundle(); - return NSStringToFilePath([bundle bundlePath]); -} - -NSBundle* FrameworkBundle() { - if (g_override_framework_bundle) - return g_override_framework_bundle; - return [NSBundle mainBundle]; -} - -FilePath FrameworkBundlePath() { - NSBundle* bundle = FrameworkBundle(); - return NSStringToFilePath([bundle bundlePath]); -} - -static void AssignOverrideBundle(NSBundle* new_bundle, - NSBundle** override_bundle) { - if (new_bundle != *override_bundle) { - [*override_bundle release]; - *override_bundle = [new_bundle retain]; - } -} - -static void AssignOverridePath(const FilePath& file_path, - NSBundle** override_bundle) { - NSString* path = base::SysUTF8ToNSString(file_path.value()); - NSBundle* new_bundle = [NSBundle bundleWithPath:path]; - DCHECK(new_bundle) << "Failed to load the bundle at " << file_path.value(); - AssignOverrideBundle(new_bundle, override_bundle); -} - -void SetOverrideOuterBundle(NSBundle* bundle) { - AssignOverrideBundle(bundle, &g_override_outer_bundle); -} - -void SetOverrideFrameworkBundle(NSBundle* bundle) { - AssignOverrideBundle(bundle, &g_override_framework_bundle); -} - -void SetOverrideOuterBundlePath(const FilePath& file_path) { - AssignOverridePath(file_path, &g_override_outer_bundle); -} - -void SetOverrideFrameworkBundlePath(const FilePath& file_path) { - AssignOverridePath(file_path, &g_override_framework_bundle); -} - -} // namespace mac -} // namespace base diff --git a/gn/base/mac/foundation_util.h b/gn/base/mac/foundation_util.h deleted file mode 100644 index 6e1ce55cd2c..00000000000 --- a/gn/base/mac/foundation_util.h +++ /dev/null @@ -1,406 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_MAC_FOUNDATION_UTIL_H_ -#define BASE_MAC_FOUNDATION_UTIL_H_ - -#include - -#include -#include - -#include "base/logging.h" -#include "base/mac/scoped_cftyperef.h" -#include "util/build_config.h" - -#if defined(__OBJC__) -#import -@class NSFont; -@class UIFont; -#else // __OBJC__ -#include -class NSBundle; -class NSFont; -class NSString; -class UIFont; -#endif // __OBJC__ - -#if defined(OS_IOS) -#include -#else -#include -#endif - -// Adapted from NSObjCRuntime.h NS_ENUM definition (used in Foundation starting -// with the OS X 10.8 SDK and the iOS 6.0 SDK). -#if __has_extension(cxx_strong_enums) && \ - (defined(OS_IOS) || \ - (defined(MAC_OS_X_VERSION_10_8) && \ - MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_8)) -#define CR_FORWARD_ENUM(_type, _name) enum _name : _type _name -#else -#define CR_FORWARD_ENUM(_type, _name) _type _name -#endif - -// Adapted from NSPathUtilities.h and NSObjCRuntime.h. -#if __LP64__ || NS_BUILD_32_LIKE_64 -typedef CR_FORWARD_ENUM(unsigned long, NSSearchPathDirectory); -typedef unsigned long NSSearchPathDomainMask; -#else -typedef CR_FORWARD_ENUM(unsigned int, NSSearchPathDirectory); -typedef unsigned int NSSearchPathDomainMask; -#endif - -typedef struct OpaqueSecTrustRef* SecACLRef; -typedef struct OpaqueSecTrustedApplicationRef* SecTrustedApplicationRef; - -#if defined(OS_IOS) -typedef struct CF_BRIDGED_TYPE(id) __SecKey* SecKeyRef; -typedef struct CF_BRIDGED_TYPE(id) __SecPolicy* SecPolicyRef; -#else -typedef struct OpaqueSecKeyRef* SecKeyRef; -typedef struct OpaqueSecPolicyRef* SecPolicyRef; -#endif - -namespace base { - -class FilePath; - -namespace mac { - -// Returns true if the application is running from a bundle -bool AmIBundled(); -void SetOverrideAmIBundled(bool value); - -#if defined(UNIT_TEST) -// This is required because instantiating some tests requires checking the -// directory structure, which sets the AmIBundled cache state. Individual tests -// may or may not be bundled, and this would trip them up if the cache weren't -// cleared. This should not be called from individual tests, just from test -// instantiation code that gets a path from PathService. -void ClearAmIBundledCache(); -#endif - -// Returns true if this process is marked as a "Background only process". -bool IsBackgroundOnlyProcess(); - -// Returns the path to a resource within the framework bundle. -FilePath PathForFrameworkBundleResource(CFStringRef resourceName); - -// Returns the creator code associated with the CFBundleRef at bundle. -OSType CreatorCodeForCFBundleRef(CFBundleRef bundle); - -// Returns the creator code associated with this application, by calling -// CreatorCodeForCFBundleRef for the application's main bundle. If this -// information cannot be determined, returns kUnknownType ('????'). This -// does not respect the override app bundle because it's based on CFBundle -// instead of NSBundle, and because callers probably don't want the override -// app bundle's creator code anyway. -OSType CreatorCodeForApplication(); - -// Searches for directories for the given key in only the given |domain_mask|. -// If found, fills result (which must always be non-NULL) with the -// first found directory and returns true. Otherwise, returns false. -bool GetSearchPathDirectory(NSSearchPathDirectory directory, - NSSearchPathDomainMask domain_mask, - FilePath* result); - -// Searches for directories for the given key in only the local domain. -// If found, fills result (which must always be non-NULL) with the -// first found directory and returns true. Otherwise, returns false. -bool GetLocalDirectory(NSSearchPathDirectory directory, FilePath* result); - -// Searches for directories for the given key in only the user domain. -// If found, fills result (which must always be non-NULL) with the -// first found directory and returns true. Otherwise, returns false. -bool GetUserDirectory(NSSearchPathDirectory directory, FilePath* result); - -// Returns the ~/Library directory. -FilePath GetUserLibraryPath(); - -// Takes a path to an (executable) binary and tries to provide the path to an -// application bundle containing it. It takes the outermost bundle that it can -// find (so for "/Foo/Bar.app/.../Baz.app/..." it produces "/Foo/Bar.app"). -// |exec_name| - path to the binary -// returns - path to the application bundle, or empty on error -FilePath GetAppBundlePath(const FilePath& exec_name); - -#define TYPE_NAME_FOR_CF_TYPE_DECL(TypeCF) \ - std::string TypeNameForCFType(TypeCF##Ref); - -TYPE_NAME_FOR_CF_TYPE_DECL(CFArray); -TYPE_NAME_FOR_CF_TYPE_DECL(CFBag); -TYPE_NAME_FOR_CF_TYPE_DECL(CFBoolean); -TYPE_NAME_FOR_CF_TYPE_DECL(CFData); -TYPE_NAME_FOR_CF_TYPE_DECL(CFDate); -TYPE_NAME_FOR_CF_TYPE_DECL(CFDictionary); -TYPE_NAME_FOR_CF_TYPE_DECL(CFNull); -TYPE_NAME_FOR_CF_TYPE_DECL(CFNumber); -TYPE_NAME_FOR_CF_TYPE_DECL(CFSet); -TYPE_NAME_FOR_CF_TYPE_DECL(CFString); -TYPE_NAME_FOR_CF_TYPE_DECL(CFURL); -TYPE_NAME_FOR_CF_TYPE_DECL(CFUUID); - -TYPE_NAME_FOR_CF_TYPE_DECL(CGColor); - -TYPE_NAME_FOR_CF_TYPE_DECL(CTFont); -TYPE_NAME_FOR_CF_TYPE_DECL(CTRun); - -TYPE_NAME_FOR_CF_TYPE_DECL(SecKey); -TYPE_NAME_FOR_CF_TYPE_DECL(SecPolicy); - -#undef TYPE_NAME_FOR_CF_TYPE_DECL - -// Retain/release calls for memory management in C++. -void NSObjectRetain(void* obj); -void NSObjectRelease(void* obj); - -// CFTypeRefToNSObjectAutorelease transfers ownership of a Core Foundation -// object (one derived from CFTypeRef) to the Foundation memory management -// system. In a traditional managed-memory environment, cf_object is -// autoreleased and returned as an NSObject. In a garbage-collected -// environment, cf_object is marked as eligible for garbage collection. -// -// This function should only be used to convert a concrete CFTypeRef type to -// its equivalent "toll-free bridged" NSObject subclass, for example, -// converting a CFStringRef to NSString. -// -// By calling this function, callers relinquish any ownership claim to -// cf_object. In a managed-memory environment, the object's ownership will be -// managed by the innermost NSAutoreleasePool, so after this function returns, -// callers should not assume that cf_object is valid any longer than the -// returned NSObject. -// -// Returns an id, typed here for C++'s sake as a void*. -void* CFTypeRefToNSObjectAutorelease(CFTypeRef cf_object); - -// Returns the base bundle ID, which can be set by SetBaseBundleID but -// defaults to a reasonable string. This never returns NULL. BaseBundleID -// returns a pointer to static storage that must not be freed. -const char* BaseBundleID(); - -// Sets the base bundle ID to override the default. The implementation will -// make its own copy of new_base_bundle_id. -void SetBaseBundleID(const char* new_base_bundle_id); - -} // namespace mac -} // namespace base - -#if !defined(__OBJC__) -#define OBJC_CPP_CLASS_DECL(x) class x; -#else // __OBJC__ -#define OBJC_CPP_CLASS_DECL(x) -#endif // __OBJC__ - -// Convert toll-free bridged CFTypes to NSTypes and vice-versa. This does not -// autorelease |cf_val|. This is useful for the case where there is a CFType in -// a call that expects an NSType and the compiler is complaining about const -// casting problems. -// The calls are used like this: -// NSString *foo = CFToNSCast(CFSTR("Hello")); -// CFStringRef foo2 = NSToCFCast(@"Hello"); -// The macro magic below is to enforce safe casting. It could possibly have -// been done using template function specialization, but template function -// specialization doesn't always work intuitively, -// (http://www.gotw.ca/publications/mill17.htm) so the trusty combination -// of macros and function overloading is used instead. - -#define CF_TO_NS_CAST_DECL(TypeCF, TypeNS) \ - OBJC_CPP_CLASS_DECL(TypeNS) \ - \ - namespace base { \ - namespace mac { \ - TypeNS* CFToNSCast(TypeCF##Ref cf_val); \ - TypeCF##Ref NSToCFCast(TypeNS* ns_val); \ - } \ - } - -#define CF_TO_NS_MUTABLE_CAST_DECL(name) \ - CF_TO_NS_CAST_DECL(CF##name, NS##name) \ - OBJC_CPP_CLASS_DECL(NSMutable##name) \ - \ - namespace base { \ - namespace mac { \ - NSMutable##name* CFToNSCast(CFMutable##name##Ref cf_val); \ - CFMutable##name##Ref NSToCFCast(NSMutable##name* ns_val); \ - } \ - } - -// List of toll-free bridged types taken from: -// http://www.cocoadev.com/index.pl?TollFreeBridged - -CF_TO_NS_MUTABLE_CAST_DECL(Array); -CF_TO_NS_MUTABLE_CAST_DECL(AttributedString); -CF_TO_NS_CAST_DECL(CFCalendar, NSCalendar); -CF_TO_NS_MUTABLE_CAST_DECL(CharacterSet); -CF_TO_NS_MUTABLE_CAST_DECL(Data); -CF_TO_NS_CAST_DECL(CFDate, NSDate); -CF_TO_NS_MUTABLE_CAST_DECL(Dictionary); -CF_TO_NS_CAST_DECL(CFError, NSError); -CF_TO_NS_CAST_DECL(CFLocale, NSLocale); -CF_TO_NS_CAST_DECL(CFNumber, NSNumber); -CF_TO_NS_CAST_DECL(CFRunLoopTimer, NSTimer); -CF_TO_NS_CAST_DECL(CFTimeZone, NSTimeZone); -CF_TO_NS_MUTABLE_CAST_DECL(Set); -CF_TO_NS_CAST_DECL(CFReadStream, NSInputStream); -CF_TO_NS_CAST_DECL(CFWriteStream, NSOutputStream); -CF_TO_NS_MUTABLE_CAST_DECL(String); -CF_TO_NS_CAST_DECL(CFURL, NSURL); - -#if defined(OS_IOS) -CF_TO_NS_CAST_DECL(CTFont, UIFont); -#else -CF_TO_NS_CAST_DECL(CTFont, NSFont); -#endif - -#undef CF_TO_NS_CAST_DECL -#undef CF_TO_NS_MUTABLE_CAST_DECL -#undef OBJC_CPP_CLASS_DECL - -namespace base { -namespace mac { - -// CFCast<>() and CFCastStrict<>() cast a basic CFTypeRef to a more -// specific CoreFoundation type. The compatibility of the passed -// object is found by comparing its opaque type against the -// requested type identifier. If the supplied object is not -// compatible with the requested return type, CFCast<>() returns -// NULL and CFCastStrict<>() will DCHECK. Providing a NULL pointer -// to either variant results in NULL being returned without -// triggering any DCHECK. -// -// Example usage: -// CFNumberRef some_number = base::mac::CFCast( -// CFArrayGetValueAtIndex(array, index)); -// -// CFTypeRef hello = CFSTR("hello world"); -// CFStringRef some_string = base::mac::CFCastStrict(hello); - -template -T CFCast(const CFTypeRef& cf_val); - -template -T CFCastStrict(const CFTypeRef& cf_val); - -#define CF_CAST_DECL(TypeCF) \ - template <> \ - TypeCF##Ref CFCast(const CFTypeRef& cf_val); \ - \ - template <> \ - TypeCF##Ref CFCastStrict(const CFTypeRef& cf_val); - -CF_CAST_DECL(CFArray); -CF_CAST_DECL(CFBag); -CF_CAST_DECL(CFBoolean); -CF_CAST_DECL(CFData); -CF_CAST_DECL(CFDate); -CF_CAST_DECL(CFDictionary); -CF_CAST_DECL(CFNull); -CF_CAST_DECL(CFNumber); -CF_CAST_DECL(CFSet); -CF_CAST_DECL(CFString); -CF_CAST_DECL(CFURL); -CF_CAST_DECL(CFUUID); - -CF_CAST_DECL(CGColor); - -CF_CAST_DECL(CTFont); -CF_CAST_DECL(CTFontDescriptor); -CF_CAST_DECL(CTRun); - -CF_CAST_DECL(SecACL); -CF_CAST_DECL(SecKey); -CF_CAST_DECL(SecPolicy); -CF_CAST_DECL(SecTrustedApplication); - -#undef CF_CAST_DECL - -#if defined(__OBJC__) - -// ObjCCast<>() and ObjCCastStrict<>() cast a basic id to a more -// specific (NSObject-derived) type. The compatibility of the passed -// object is found by checking if it's a kind of the requested type -// identifier. If the supplied object is not compatible with the -// requested return type, ObjCCast<>() returns nil and -// ObjCCastStrict<>() will DCHECK. Providing a nil pointer to either -// variant results in nil being returned without triggering any DCHECK. -// -// The strict variant is useful when retrieving a value from a -// collection which only has values of a specific type, e.g. an -// NSArray of NSStrings. The non-strict variant is useful when -// retrieving values from data that you can't fully control. For -// example, a plist read from disk may be beyond your exclusive -// control, so you'd only want to check that the values you retrieve -// from it are of the expected types, but not crash if they're not. -// -// Example usage: -// NSString* version = base::mac::ObjCCast( -// [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"]); -// -// NSString* str = base::mac::ObjCCastStrict( -// [ns_arr_of_ns_strs objectAtIndex:0]); -template -T* ObjCCast(id objc_val) { - if ([objc_val isKindOfClass:[T class]]) { - return reinterpret_cast(objc_val); - } - return nil; -} - -template -T* ObjCCastStrict(id objc_val) { - T* rv = ObjCCast(objc_val); - DCHECK(objc_val == nil || rv); - return rv; -} - -#endif // defined(__OBJC__) - -// Helper function for GetValueFromDictionary to create the error message -// that appears when a type mismatch is encountered. -std::string GetValueFromDictionaryErrorMessage(CFStringRef key, - const std::string& expected_type, - CFTypeRef value); - -// Utility function to pull out a value from a dictionary, check its type, and -// return it. Returns NULL if the key is not present or of the wrong type. -template -T GetValueFromDictionary(CFDictionaryRef dict, CFStringRef key) { - CFTypeRef value = CFDictionaryGetValue(dict, key); - T value_specific = CFCast(value); - - if (value && !value_specific) { - std::string expected_type = TypeNameForCFType(value_specific); - DLOG(WARNING) << GetValueFromDictionaryErrorMessage(key, expected_type, - value); - } - - return value_specific; -} - -// Converts |path| to an autoreleased NSString. Returns nil if |path| is empty. -NSString* FilePathToNSString(const FilePath& path); - -// Converts |str| to a FilePath. Returns an empty path if |str| is nil. -FilePath NSStringToFilePath(NSString* str); - -#if defined(__OBJC__) -// Converts |range| to an NSRange, returning the new range in |range_out|. -// Returns true if conversion was successful, false if the values of |range| -// could not be converted to NSUIntegers. -bool CFRangeToNSRange(CFRange range, NSRange* range_out) WARN_UNUSED_RESULT; -#endif // defined(__OBJC__) - -} // namespace mac -} // namespace base - -// Stream operations for CFTypes. They can be used with NSTypes as well -// by using the NSToCFCast methods above. -// e.g. LOG(INFO) << base::mac::NSToCFCast(@"foo"); -// Operator << can not be overloaded for ObjectiveC types as the compiler -// can not distinguish between overloads for id with overloads for void*. -extern std::ostream& operator<<(std::ostream& o, const CFErrorRef err); -extern std::ostream& operator<<(std::ostream& o, const CFStringRef str); - -#endif // BASE_MAC_FOUNDATION_UTIL_H_ diff --git a/gn/base/mac/foundation_util.mm b/gn/base/mac/foundation_util.mm deleted file mode 100644 index d88ada8f395..00000000000 --- a/gn/base/mac/foundation_util.mm +++ /dev/null @@ -1,475 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/mac/foundation_util.h" - -#include -#include -#include - -#include "base/files/file_path.h" -#include "base/logging.h" -#include "base/mac/bundle_locations.h" -#include "base/mac/mac_logging.h" -#include "base/macros.h" -#include "base/numerics/safe_conversions.h" -#include "base/strings/sys_string_conversions.h" -#include "util/build_config.h" - -#if !defined(OS_IOS) -#import -#endif - -extern "C" { -CFTypeID SecKeyGetTypeID(); -#if !defined(OS_IOS) -CFTypeID SecACLGetTypeID(); -CFTypeID SecTrustedApplicationGetTypeID(); -Boolean _CFIsObjC(CFTypeID typeID, CFTypeRef obj); -#endif -} // extern "C" - -namespace base { -namespace mac { - -namespace { - -bool g_cached_am_i_bundled_called = false; -bool g_cached_am_i_bundled_value = false; -bool g_override_am_i_bundled = false; -bool g_override_am_i_bundled_value = false; - -bool UncachedAmIBundled() { -#if defined(OS_IOS) - // All apps are bundled on iOS. - return true; -#else - if (g_override_am_i_bundled) - return g_override_am_i_bundled_value; - - // Yes, this is cheap. - return [[base::mac::OuterBundle() bundlePath] hasSuffix:@".app"]; -#endif -} - -} // namespace - -bool AmIBundled() { - // If the return value is not cached, this function will return different - // values depending on when it's called. This confuses some client code, see - // http://crbug.com/63183 . - if (!g_cached_am_i_bundled_called) { - g_cached_am_i_bundled_called = true; - g_cached_am_i_bundled_value = UncachedAmIBundled(); - } - DCHECK_EQ(g_cached_am_i_bundled_value, UncachedAmIBundled()) - << "The return value of AmIBundled() changed. This will confuse tests. " - << "Call SetAmIBundled() override manually if your test binary " - << "delay-loads the framework."; - return g_cached_am_i_bundled_value; -} - -void SetOverrideAmIBundled(bool value) { -#if defined(OS_IOS) - // It doesn't make sense not to be bundled on iOS. - if (!value) - NOTREACHED(); -#endif - g_override_am_i_bundled = true; - g_override_am_i_bundled_value = value; -} - -void ClearAmIBundledCache() { - g_cached_am_i_bundled_called = false; -} - -bool IsBackgroundOnlyProcess() { - // This function really does want to examine NSBundle's idea of the main - // bundle dictionary. It needs to look at the actual running .app's - // Info.plist to access its LSUIElement property. - NSDictionary* info_dictionary = [base::mac::MainBundle() infoDictionary]; - return [info_dictionary[@"LSUIElement"] boolValue] != NO; -} - -FilePath PathForFrameworkBundleResource(CFStringRef resourceName) { - NSBundle* bundle = base::mac::FrameworkBundle(); - NSString* resourcePath = - [bundle pathForResource:(NSString*)resourceName ofType:nil]; - return NSStringToFilePath(resourcePath); -} - -OSType CreatorCodeForCFBundleRef(CFBundleRef bundle) { - OSType creator = kUnknownType; - CFBundleGetPackageInfo(bundle, NULL, &creator); - return creator; -} - -OSType CreatorCodeForApplication() { - CFBundleRef bundle = CFBundleGetMainBundle(); - if (!bundle) - return kUnknownType; - - return CreatorCodeForCFBundleRef(bundle); -} - -bool GetSearchPathDirectory(NSSearchPathDirectory directory, - NSSearchPathDomainMask domain_mask, - FilePath* result) { - DCHECK(result); - NSArray* dirs = - NSSearchPathForDirectoriesInDomains(directory, domain_mask, YES); - if ([dirs count] < 1) { - return false; - } - *result = NSStringToFilePath(dirs[0]); - return true; -} - -bool GetLocalDirectory(NSSearchPathDirectory directory, FilePath* result) { - return GetSearchPathDirectory(directory, NSLocalDomainMask, result); -} - -bool GetUserDirectory(NSSearchPathDirectory directory, FilePath* result) { - return GetSearchPathDirectory(directory, NSUserDomainMask, result); -} - -FilePath GetUserLibraryPath() { - FilePath user_library_path; - if (!GetUserDirectory(NSLibraryDirectory, &user_library_path)) { - DLOG(WARNING) << "Could not get user library path"; - } - return user_library_path; -} - -// Takes a path to an (executable) binary and tries to provide the path to an -// application bundle containing it. It takes the outermost bundle that it can -// find (so for "/Foo/Bar.app/.../Baz.app/..." it produces "/Foo/Bar.app"). -// |exec_name| - path to the binary -// returns - path to the application bundle, or empty on error -FilePath GetAppBundlePath(const FilePath& exec_name) { - const char kExt[] = ".app"; - const size_t kExtLength = arraysize(kExt) - 1; - - // Split the path into components. - std::vector components; - exec_name.GetComponents(&components); - - // It's an error if we don't get any components. - if (components.empty()) - return FilePath(); - - // Don't prepend '/' to the first component. - std::vector::const_iterator it = components.begin(); - std::string bundle_name = *it; - DCHECK_GT(it->length(), 0U); - // If the first component ends in ".app", we're already done. - if (it->length() > kExtLength && - !it->compare(it->length() - kExtLength, kExtLength, kExt, kExtLength)) - return FilePath(bundle_name); - - // The first component may be "/" or "//", etc. Only append '/' if it doesn't - // already end in '/'. - if (bundle_name.back() != '/') - bundle_name += '/'; - - // Go through the remaining components. - for (++it; it != components.end(); ++it) { - DCHECK_GT(it->length(), 0U); - - bundle_name += *it; - - // If the current component ends in ".app", we're done. - if (it->length() > kExtLength && - !it->compare(it->length() - kExtLength, kExtLength, kExt, kExtLength)) - return FilePath(bundle_name); - - // Separate this component from the next one. - bundle_name += '/'; - } - - return FilePath(); -} - -#define TYPE_NAME_FOR_CF_TYPE_DEFN(TypeCF) \ - std::string TypeNameForCFType(TypeCF##Ref) { return #TypeCF; } - -TYPE_NAME_FOR_CF_TYPE_DEFN(CFArray); -TYPE_NAME_FOR_CF_TYPE_DEFN(CFBag); -TYPE_NAME_FOR_CF_TYPE_DEFN(CFBoolean); -TYPE_NAME_FOR_CF_TYPE_DEFN(CFData); -TYPE_NAME_FOR_CF_TYPE_DEFN(CFDate); -TYPE_NAME_FOR_CF_TYPE_DEFN(CFDictionary); -TYPE_NAME_FOR_CF_TYPE_DEFN(CFNull); -TYPE_NAME_FOR_CF_TYPE_DEFN(CFNumber); -TYPE_NAME_FOR_CF_TYPE_DEFN(CFSet); -TYPE_NAME_FOR_CF_TYPE_DEFN(CFString); -TYPE_NAME_FOR_CF_TYPE_DEFN(CFURL); -TYPE_NAME_FOR_CF_TYPE_DEFN(CFUUID); - -TYPE_NAME_FOR_CF_TYPE_DEFN(CGColor); - -TYPE_NAME_FOR_CF_TYPE_DEFN(CTFont); -TYPE_NAME_FOR_CF_TYPE_DEFN(CTRun); - -#if !defined(OS_IOS) -TYPE_NAME_FOR_CF_TYPE_DEFN(SecKey); -TYPE_NAME_FOR_CF_TYPE_DEFN(SecPolicy); -#endif - -#undef TYPE_NAME_FOR_CF_TYPE_DEFN - -void NSObjectRetain(void* obj) { - id nsobj = static_cast>(obj); - [nsobj retain]; -} - -void NSObjectRelease(void* obj) { - id nsobj = static_cast>(obj); - [nsobj release]; -} - -void* CFTypeRefToNSObjectAutorelease(CFTypeRef cf_object) { - // When GC is on, NSMakeCollectable marks cf_object for GC and autorelease - // is a no-op. - // - // In the traditional GC-less environment, NSMakeCollectable is a no-op, - // and cf_object is autoreleased, balancing out the caller's ownership claim. - // - // NSMakeCollectable returns nil when used on a NULL object. - return [NSMakeCollectable(cf_object) autorelease]; -} - -static const char* base_bundle_id; - -const char* BaseBundleID() { - if (base_bundle_id) { - return base_bundle_id; - } - -#if defined(GOOGLE_CHROME_BUILD) - return "com.google.Chrome"; -#else - return "org.chromium.Chromium"; -#endif -} - -void SetBaseBundleID(const char* new_base_bundle_id) { - if (new_base_bundle_id != base_bundle_id) { - free((void*)base_bundle_id); - base_bundle_id = new_base_bundle_id ? strdup(new_base_bundle_id) : NULL; - } -} - -// Definitions for the corresponding CF_TO_NS_CAST_DECL macros in -// foundation_util.h. -#define CF_TO_NS_CAST_DEFN(TypeCF, TypeNS) \ - \ - TypeNS* CFToNSCast(TypeCF##Ref cf_val) { \ - DCHECK(!cf_val || TypeCF##GetTypeID() == CFGetTypeID(cf_val)); \ - TypeNS* ns_val = \ - const_cast(reinterpret_cast(cf_val)); \ - return ns_val; \ - } \ - \ - TypeCF##Ref NSToCFCast(TypeNS* ns_val) { \ - TypeCF##Ref cf_val = reinterpret_cast(ns_val); \ - DCHECK(!cf_val || TypeCF##GetTypeID() == CFGetTypeID(cf_val)); \ - return cf_val; \ - } - -#define CF_TO_NS_MUTABLE_CAST_DEFN(name) \ - CF_TO_NS_CAST_DEFN(CF##name, NS##name) \ - \ - NSMutable##name* CFToNSCast(CFMutable##name##Ref cf_val) { \ - DCHECK(!cf_val || CF##name##GetTypeID() == CFGetTypeID(cf_val)); \ - NSMutable##name* ns_val = reinterpret_cast(cf_val); \ - return ns_val; \ - } \ - \ - CFMutable##name##Ref NSToCFCast(NSMutable##name* ns_val) { \ - CFMutable##name##Ref cf_val = \ - reinterpret_cast(ns_val); \ - DCHECK(!cf_val || CF##name##GetTypeID() == CFGetTypeID(cf_val)); \ - return cf_val; \ - } - -CF_TO_NS_MUTABLE_CAST_DEFN(Array); -CF_TO_NS_MUTABLE_CAST_DEFN(AttributedString); -CF_TO_NS_CAST_DEFN(CFCalendar, NSCalendar); -CF_TO_NS_MUTABLE_CAST_DEFN(CharacterSet); -CF_TO_NS_MUTABLE_CAST_DEFN(Data); -CF_TO_NS_CAST_DEFN(CFDate, NSDate); -CF_TO_NS_MUTABLE_CAST_DEFN(Dictionary); -CF_TO_NS_CAST_DEFN(CFError, NSError); -CF_TO_NS_CAST_DEFN(CFLocale, NSLocale); -CF_TO_NS_CAST_DEFN(CFNumber, NSNumber); -CF_TO_NS_CAST_DEFN(CFRunLoopTimer, NSTimer); -CF_TO_NS_CAST_DEFN(CFTimeZone, NSTimeZone); -CF_TO_NS_MUTABLE_CAST_DEFN(Set); -CF_TO_NS_CAST_DEFN(CFReadStream, NSInputStream); -CF_TO_NS_CAST_DEFN(CFWriteStream, NSOutputStream); -CF_TO_NS_MUTABLE_CAST_DEFN(String); -CF_TO_NS_CAST_DEFN(CFURL, NSURL); - -#if defined(OS_IOS) -CF_TO_NS_CAST_DEFN(CTFont, UIFont); -#else -// The NSFont/CTFont toll-free bridging is broken when it comes to type -// checking, so do some special-casing. -// http://www.openradar.me/15341349 rdar://15341349 -NSFont* CFToNSCast(CTFontRef cf_val) { - NSFont* ns_val = const_cast(reinterpret_cast(cf_val)); - DCHECK(!cf_val || CTFontGetTypeID() == CFGetTypeID(cf_val) || - (_CFIsObjC(CTFontGetTypeID(), cf_val) && - [ns_val isKindOfClass:[NSFont class]])); - return ns_val; -} - -CTFontRef NSToCFCast(NSFont* ns_val) { - CTFontRef cf_val = reinterpret_cast(ns_val); - DCHECK(!cf_val || CTFontGetTypeID() == CFGetTypeID(cf_val) || - [ns_val isKindOfClass:[NSFont class]]); - return cf_val; -} -#endif - -#undef CF_TO_NS_CAST_DEFN -#undef CF_TO_NS_MUTABLE_CAST_DEFN - -#define CF_CAST_DEFN(TypeCF) \ - template <> \ - TypeCF##Ref CFCast(const CFTypeRef& cf_val) { \ - if (cf_val == NULL) { \ - return NULL; \ - } \ - if (CFGetTypeID(cf_val) == TypeCF##GetTypeID()) { \ - return (TypeCF##Ref)(cf_val); \ - } \ - return NULL; \ - } \ - \ - template <> \ - TypeCF##Ref CFCastStrict(const CFTypeRef& cf_val) { \ - TypeCF##Ref rv = CFCast(cf_val); \ - DCHECK(cf_val == NULL || rv); \ - return rv; \ - } - -CF_CAST_DEFN(CFArray); -CF_CAST_DEFN(CFBag); -CF_CAST_DEFN(CFBoolean); -CF_CAST_DEFN(CFData); -CF_CAST_DEFN(CFDate); -CF_CAST_DEFN(CFDictionary); -CF_CAST_DEFN(CFNull); -CF_CAST_DEFN(CFNumber); -CF_CAST_DEFN(CFSet); -CF_CAST_DEFN(CFString); -CF_CAST_DEFN(CFURL); -CF_CAST_DEFN(CFUUID); - -CF_CAST_DEFN(CGColor); - -CF_CAST_DEFN(CTFontDescriptor); -CF_CAST_DEFN(CTRun); - -#if defined(OS_IOS) -CF_CAST_DEFN(CTFont); -#else -// The NSFont/CTFont toll-free bridging is broken when it comes to type -// checking, so do some special-casing. -// http://www.openradar.me/15341349 rdar://15341349 -template <> -CTFontRef CFCast(const CFTypeRef& cf_val) { - if (cf_val == NULL) { - return NULL; - } - if (CFGetTypeID(cf_val) == CTFontGetTypeID()) { - return (CTFontRef)(cf_val); - } - - if (!_CFIsObjC(CTFontGetTypeID(), cf_val)) - return NULL; - - id ns_val = reinterpret_cast(const_cast(cf_val)); - if ([ns_val isKindOfClass:[NSFont class]]) { - return (CTFontRef)(cf_val); - } - return NULL; -} - -template <> -CTFontRef CFCastStrict(const CFTypeRef& cf_val) { - CTFontRef rv = CFCast(cf_val); - DCHECK(cf_val == NULL || rv); - return rv; -} -#endif - -#if !defined(OS_IOS) -CF_CAST_DEFN(SecACL); -CF_CAST_DEFN(SecKey); -CF_CAST_DEFN(SecPolicy); -CF_CAST_DEFN(SecTrustedApplication); -#endif - -#undef CF_CAST_DEFN - -std::string GetValueFromDictionaryErrorMessage(CFStringRef key, - const std::string& expected_type, - CFTypeRef value) { - ScopedCFTypeRef actual_type_ref( - CFCopyTypeIDDescription(CFGetTypeID(value))); - return "Expected value for key " + base::SysCFStringRefToUTF8(key) + - " to be " + expected_type + " but it was " + - base::SysCFStringRefToUTF8(actual_type_ref) + " instead"; -} - -NSString* FilePathToNSString(const FilePath& path) { - if (path.empty()) - return nil; - return @(path.value().c_str()); // @() does UTF8 conversion. -} - -FilePath NSStringToFilePath(NSString* str) { - if (![str length]) - return FilePath(); - return FilePath([str fileSystemRepresentation]); -} - -bool CFRangeToNSRange(CFRange range, NSRange* range_out) { - if (base::IsValueInRangeForNumericTypelocation)>( - range.location) && - base::IsValueInRangeForNumericTypelength)>( - range.length) && - base::IsValueInRangeForNumericTypelocation)>( - range.location + range.length)) { - *range_out = NSMakeRange(range.location, range.length); - return true; - } - return false; -} - -} // namespace mac -} // namespace base - -std::ostream& operator<<(std::ostream& o, const CFStringRef string) { - return o << base::SysCFStringRefToUTF8(string); -} - -std::ostream& operator<<(std::ostream& o, const CFErrorRef err) { - base::ScopedCFTypeRef desc(CFErrorCopyDescription(err)); - base::ScopedCFTypeRef user_info(CFErrorCopyUserInfo(err)); - CFStringRef errorDesc = NULL; - if (user_info.get()) { - errorDesc = reinterpret_cast( - CFDictionaryGetValue(user_info.get(), kCFErrorDescriptionKey)); - } - o << "Code: " << CFErrorGetCode(err) << " Domain: " << CFErrorGetDomain(err) - << " Desc: " << desc.get(); - if (errorDesc) { - o << "(" << errorDesc << ")"; - } - return o; -} diff --git a/gn/base/numerics/safe_conversions.h b/gn/base/numerics/safe_conversions.h index a4fe387e8a7..71d6e6113f5 100644 --- a/gn/base/numerics/safe_conversions.h +++ b/gn/base/numerics/safe_conversions.h @@ -13,12 +13,7 @@ #include "base/numerics/safe_conversions_impl.h" -#if !defined(__native_client__) && (defined(__ARMEL__) || defined(__arch64__)) -#include "base/numerics/safe_conversions_arm_impl.h" -#define BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS (1) -#else #define BASE_HAS_OPTIMIZED_SAFE_CONVERSIONS (0) -#endif namespace base { namespace internal { diff --git a/gn/base/numerics/safe_math_clang_gcc_impl.h b/gn/base/numerics/safe_math_clang_gcc_impl.h index 1760338b089..660a57f2e7f 100644 --- a/gn/base/numerics/safe_math_clang_gcc_impl.h +++ b/gn/base/numerics/safe_math_clang_gcc_impl.h @@ -11,12 +11,7 @@ #include "base/numerics/safe_conversions.h" -#if !defined(__native_client__) && (defined(__ARMEL__) || defined(__arch64__)) -#include "base/numerics/safe_math_arm_impl.h" -#define BASE_HAS_ASSEMBLER_SAFE_MATH (1) -#else #define BASE_HAS_ASSEMBLER_SAFE_MATH (0) -#endif namespace base { namespace internal { diff --git a/gn/base/strings/sys_string_conversions.h b/gn/base/strings/sys_string_conversions.h deleted file mode 100644 index 9150c05814a..00000000000 --- a/gn/base/strings/sys_string_conversions.h +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef BASE_STRINGS_SYS_STRING_CONVERSIONS_H_ -#define BASE_STRINGS_SYS_STRING_CONVERSIONS_H_ - -// Provides system-dependent string type conversions for cases where it's -// necessary to not use ICU. Generally, you should not need this in Chrome, -// but it is used in some shared code. Dependencies should be minimal. - -#include - -#include - -#include "base/strings/string16.h" -#include "base/strings/string_piece.h" -#include "util/build_config.h" - -#if defined(OS_MACOSX) -#include -#ifdef __OBJC__ -@class NSString; -#else -class NSString; -#endif -#endif // OS_MACOSX - -namespace base { - -// Converts between wide and UTF-8 representations of a string. On error, the -// result is system-dependent. -std::string SysWideToUTF8(const std::wstring& wide); -std::wstring SysUTF8ToWide(StringPiece utf8); - -// Converts between wide and the system multi-byte representations of a string. -// DANGER: This will lose information and can change (on Windows, this can -// change between reboots). -std::string SysWideToNativeMB(const std::wstring& wide); -std::wstring SysNativeMBToWide(StringPiece native_mb); - -// Windows-specific ------------------------------------------------------------ - -#if defined(OS_WIN) - -// Converts between 8-bit and wide strings, using the given code page. The -// code page identifier is one accepted by the Windows function -// MultiByteToWideChar(). -std::wstring SysMultiByteToWide(StringPiece mb, uint32_t code_page); -std::string SysWideToMultiByte(const std::wstring& wide, uint32_t code_page); - -#endif // defined(OS_WIN) - -// Mac-specific ---------------------------------------------------------------- - -#if defined(OS_MACOSX) - -// Converts between STL strings and CFStringRefs/NSStrings. - -// Creates a string, and returns it with a refcount of 1. You are responsible -// for releasing it. Returns NULL on failure. -CFStringRef SysUTF8ToCFStringRef(const std::string& utf8); -CFStringRef SysUTF16ToCFStringRef(const string16& utf16); - -// Same, but returns an autoreleased NSString. -NSString* SysUTF8ToNSString(const std::string& utf8); -NSString* SysUTF16ToNSString(const string16& utf16); - -// Converts a CFStringRef to an STL string. Returns an empty string on failure. -std::string SysCFStringRefToUTF8(CFStringRef ref); -string16 SysCFStringRefToUTF16(CFStringRef ref); - -// Same, but accepts NSString input. Converts nil NSString* to the appropriate -// string type of length 0. -std::string SysNSStringToUTF8(NSString* ref); -string16 SysNSStringToUTF16(NSString* ref); - -#endif // defined(OS_MACOSX) - -} // namespace base - -#endif // BASE_STRINGS_SYS_STRING_CONVERSIONS_H_ diff --git a/gn/base/strings/sys_string_conversions_mac.mm b/gn/base/strings/sys_string_conversions_mac.mm deleted file mode 100644 index 3b78777e5a8..00000000000 --- a/gn/base/strings/sys_string_conversions_mac.mm +++ /dev/null @@ -1,176 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/strings/sys_string_conversions.h" - -#import -#include - -#include - -#include "base/mac/foundation_util.h" -#include "base/mac/scoped_cftyperef.h" -#include "base/strings/string_piece.h" - -namespace base { - -namespace { - -// Convert the supplied CFString into the specified encoding, and return it as -// an STL string of the template type. Returns an empty string on failure. -// -// Do not assert in this function since it is used by the asssertion code! -template -static StringType CFStringToSTLStringWithEncodingT(CFStringRef cfstring, - CFStringEncoding encoding) { - CFIndex length = CFStringGetLength(cfstring); - if (length == 0) - return StringType(); - - CFRange whole_string = CFRangeMake(0, length); - CFIndex out_size; - CFIndex converted = CFStringGetBytes(cfstring, whole_string, encoding, - 0, // lossByte - false, // isExternalRepresentation - NULL, // buffer - 0, // maxBufLen - &out_size); - if (converted == 0 || out_size == 0) - return StringType(); - - // out_size is the number of UInt8-sized units needed in the destination. - // A buffer allocated as UInt8 units might not be properly aligned to - // contain elements of StringType::value_type. Use a container for the - // proper value_type, and convert out_size by figuring the number of - // value_type elements per UInt8. Leave room for a NUL terminator. - typename StringType::size_type elements = - out_size * sizeof(UInt8) / sizeof(typename StringType::value_type) + 1; - - std::vector out_buffer(elements); - converted = - CFStringGetBytes(cfstring, whole_string, encoding, - 0, // lossByte - false, // isExternalRepresentation - reinterpret_cast(&out_buffer[0]), out_size, - NULL); // usedBufLen - if (converted == 0) - return StringType(); - - out_buffer[elements - 1] = '\0'; - return StringType(&out_buffer[0], elements - 1); -} - -// Given an STL string |in| with an encoding specified by |in_encoding|, -// convert it to |out_encoding| and return it as an STL string of the -// |OutStringType| template type. Returns an empty string on failure. -// -// Do not assert in this function since it is used by the asssertion code! -template -static OutStringType STLStringToSTLStringWithEncodingsT( - const InStringType& in, - CFStringEncoding in_encoding, - CFStringEncoding out_encoding) { - typename InStringType::size_type in_length = in.length(); - if (in_length == 0) - return OutStringType(); - - base::ScopedCFTypeRef cfstring(CFStringCreateWithBytesNoCopy( - NULL, reinterpret_cast(in.data()), - in_length * sizeof(typename InStringType::value_type), in_encoding, false, - kCFAllocatorNull)); - if (!cfstring) - return OutStringType(); - - return CFStringToSTLStringWithEncodingT(cfstring, - out_encoding); -} - -// Given an STL string |in| with an encoding specified by |in_encoding|, -// return it as a CFStringRef. Returns NULL on failure. -template -static CFStringRef STLStringToCFStringWithEncodingsT( - const StringType& in, - CFStringEncoding in_encoding) { - typename StringType::size_type in_length = in.length(); - if (in_length == 0) - return CFSTR(""); - - return CFStringCreateWithBytes( - kCFAllocatorDefault, reinterpret_cast(in.data()), - in_length * sizeof(typename StringType::value_type), in_encoding, false); -} - -// Specify the byte ordering explicitly, otherwise CFString will be confused -// when strings don't carry BOMs, as they typically won't. -static const CFStringEncoding kNarrowStringEncoding = kCFStringEncodingUTF8; -#ifdef __BIG_ENDIAN__ -static const CFStringEncoding kMediumStringEncoding = kCFStringEncodingUTF16BE; -static const CFStringEncoding kWideStringEncoding = kCFStringEncodingUTF32BE; -#elif defined(__LITTLE_ENDIAN__) -static const CFStringEncoding kMediumStringEncoding = kCFStringEncodingUTF16LE; -static const CFStringEncoding kWideStringEncoding = kCFStringEncodingUTF32LE; -#endif // __LITTLE_ENDIAN__ - -} // namespace - -// Do not assert in this function since it is used by the asssertion code! -std::string SysWideToUTF8(const std::wstring& wide) { - return STLStringToSTLStringWithEncodingsT( - wide, kWideStringEncoding, kNarrowStringEncoding); -} - -// Do not assert in this function since it is used by the asssertion code! -std::wstring SysUTF8ToWide(StringPiece utf8) { - return STLStringToSTLStringWithEncodingsT( - utf8, kNarrowStringEncoding, kWideStringEncoding); -} - -std::string SysWideToNativeMB(const std::wstring& wide) { - return SysWideToUTF8(wide); -} - -std::wstring SysNativeMBToWide(StringPiece native_mb) { - return SysUTF8ToWide(native_mb); -} - -CFStringRef SysUTF8ToCFStringRef(const std::string& utf8) { - return STLStringToCFStringWithEncodingsT(utf8, kNarrowStringEncoding); -} - -CFStringRef SysUTF16ToCFStringRef(const string16& utf16) { - return STLStringToCFStringWithEncodingsT(utf16, kMediumStringEncoding); -} - -NSString* SysUTF8ToNSString(const std::string& utf8) { - return (NSString*)base::mac::CFTypeRefToNSObjectAutorelease( - SysUTF8ToCFStringRef(utf8)); -} - -NSString* SysUTF16ToNSString(const string16& utf16) { - return (NSString*)base::mac::CFTypeRefToNSObjectAutorelease( - SysUTF16ToCFStringRef(utf16)); -} - -std::string SysCFStringRefToUTF8(CFStringRef ref) { - return CFStringToSTLStringWithEncodingT(ref, - kNarrowStringEncoding); -} - -string16 SysCFStringRefToUTF16(CFStringRef ref) { - return CFStringToSTLStringWithEncodingT(ref, kMediumStringEncoding); -} - -std::string SysNSStringToUTF8(NSString* nsstring) { - if (!nsstring) - return std::string(); - return SysCFStringRefToUTF8(reinterpret_cast(nsstring)); -} - -string16 SysNSStringToUTF16(NSString* nsstring) { - if (!nsstring) - return string16(); - return SysCFStringRefToUTF16(reinterpret_cast(nsstring)); -} - -} // namespace base diff --git a/gn/base/strings/sys_string_conversions_posix.cc b/gn/base/strings/sys_string_conversions_posix.cc deleted file mode 100644 index 0e1442829a2..00000000000 --- a/gn/base/strings/sys_string_conversions_posix.cc +++ /dev/null @@ -1,163 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/strings/sys_string_conversions.h" - -#include -#include - -#include "base/strings/string_piece.h" -#include "base/strings/utf_string_conversions.h" -#include "util/build_config.h" - -namespace base { - -std::string SysWideToUTF8(const std::wstring& wide) { - // In theory this should be using the system-provided conversion rather - // than our ICU, but this will do for now. - return WideToUTF8(wide); -} -std::wstring SysUTF8ToWide(StringPiece utf8) { - // In theory this should be using the system-provided conversion rather - // than our ICU, but this will do for now. - std::wstring out; - UTF8ToWide(utf8.data(), utf8.size(), &out); - return out; -} - -#if defined(SYSTEM_NATIVE_UTF8) || defined(OS_ANDROID) -// TODO(port): Consider reverting the OS_ANDROID when we have wcrtomb() -// support and a better understanding of what calls these routines. - -std::string SysWideToNativeMB(const std::wstring& wide) { - return WideToUTF8(wide); -} - -std::wstring SysNativeMBToWide(StringPiece native_mb) { - return SysUTF8ToWide(native_mb); -} - -#else - -std::string SysWideToNativeMB(const std::wstring& wide) { - mbstate_t ps; - - // Calculate the number of multi-byte characters. We walk through the string - // without writing the output, counting the number of multi-byte characters. - size_t num_out_chars = 0; - memset(&ps, 0, sizeof(ps)); - for (size_t i = 0; i < wide.size(); ++i) { - const wchar_t src = wide[i]; - // Use a temp buffer since calling wcrtomb with an output of NULL does not - // calculate the output length. - char buf[16]; - // Skip NULLs to avoid wcrtomb's special handling of them. - size_t res = src ? wcrtomb(buf, src, &ps) : 0; - switch (res) { - // Handle any errors and return an empty string. - case static_cast(-1): - return std::string(); - break; - case 0: - // We hit an embedded null byte, keep going. - ++num_out_chars; - break; - default: - num_out_chars += res; - break; - } - } - - if (num_out_chars == 0) - return std::string(); - - std::string out; - out.resize(num_out_chars); - - // We walk the input string again, with |i| tracking the index of the - // wide input, and |j| tracking the multi-byte output. - memset(&ps, 0, sizeof(ps)); - for (size_t i = 0, j = 0; i < wide.size(); ++i) { - const wchar_t src = wide[i]; - // We don't want wcrtomb to do its funkiness for embedded NULLs. - size_t res = src ? wcrtomb(&out[j], src, &ps) : 0; - switch (res) { - // Handle any errors and return an empty string. - case static_cast(-1): - return std::string(); - break; - case 0: - // We hit an embedded null byte, keep going. - ++j; // Output is already zeroed. - break; - default: - j += res; - break; - } - } - - return out; -} - -std::wstring SysNativeMBToWide(StringPiece native_mb) { - mbstate_t ps; - - // Calculate the number of wide characters. We walk through the string - // without writing the output, counting the number of wide characters. - size_t num_out_chars = 0; - memset(&ps, 0, sizeof(ps)); - for (size_t i = 0; i < native_mb.size();) { - const char* src = native_mb.data() + i; - size_t res = mbrtowc(nullptr, src, native_mb.size() - i, &ps); - switch (res) { - // Handle any errors and return an empty string. - case static_cast(-2): - case static_cast(-1): - return std::wstring(); - break; - case 0: - // We hit an embedded null byte, keep going. - i += 1; - FALLTHROUGH; - default: - i += res; - ++num_out_chars; - break; - } - } - - if (num_out_chars == 0) - return std::wstring(); - - std::wstring out; - out.resize(num_out_chars); - - memset(&ps, 0, sizeof(ps)); // Clear the shift state. - // We walk the input string again, with |i| tracking the index of the - // multi-byte input, and |j| tracking the wide output. - for (size_t i = 0, j = 0; i < native_mb.size(); ++j) { - const char* src = native_mb.data() + i; - wchar_t* dst = &out[j]; - size_t res = mbrtowc(dst, src, native_mb.size() - i, &ps); - switch (res) { - // Handle any errors and return an empty string. - case static_cast(-2): - case static_cast(-1): - return std::wstring(); - break; - case 0: - i += 1; // Skip null byte. - break; - default: - i += res; - break; - } - } - - return out; -} - -#endif // defined(SYSTEM_NATIVE_UTF8) || defined(OS_ANDROID) - -} // namespace base diff --git a/gn/base/strings/sys_string_conversions_win.cc b/gn/base/strings/sys_string_conversions_win.cc deleted file mode 100644 index 232dd782200..00000000000 --- a/gn/base/strings/sys_string_conversions_win.cc +++ /dev/null @@ -1,71 +0,0 @@ -// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/strings/sys_string_conversions.h" - -#include -#include - -#include "base/strings/string_piece.h" - -namespace base { - -// Do not assert in this function since it is used by the asssertion code! -std::string SysWideToUTF8(const std::wstring& wide) { - return SysWideToMultiByte(wide, CP_UTF8); -} - -// Do not assert in this function since it is used by the asssertion code! -std::wstring SysUTF8ToWide(StringPiece utf8) { - return SysMultiByteToWide(utf8, CP_UTF8); -} - -std::string SysWideToNativeMB(const std::wstring& wide) { - return SysWideToMultiByte(wide, CP_ACP); -} - -std::wstring SysNativeMBToWide(StringPiece native_mb) { - return SysMultiByteToWide(native_mb, CP_ACP); -} - -// Do not assert in this function since it is used by the asssertion code! -std::wstring SysMultiByteToWide(StringPiece mb, uint32_t code_page) { - if (mb.empty()) - return std::wstring(); - - int mb_length = static_cast(mb.length()); - // Compute the length of the buffer. - int charcount = - MultiByteToWideChar(code_page, 0, mb.data(), mb_length, NULL, 0); - if (charcount == 0) - return std::wstring(); - - std::wstring wide; - wide.resize(charcount); - MultiByteToWideChar(code_page, 0, mb.data(), mb_length, &wide[0], charcount); - - return wide; -} - -// Do not assert in this function since it is used by the asssertion code! -std::string SysWideToMultiByte(const std::wstring& wide, uint32_t code_page) { - int wide_length = static_cast(wide.length()); - if (wide_length == 0) - return std::string(); - - // Compute the length of the buffer we'll need. - int charcount = WideCharToMultiByte(code_page, 0, wide.data(), wide_length, - NULL, 0, NULL, NULL); - if (charcount == 0) - return std::string(); - - std::string mb; - mb.resize(charcount); - WideCharToMultiByte(code_page, 0, wide.data(), wide_length, &mb[0], charcount, - NULL, NULL); - - return mb; -} - -} // namespace base diff --git a/gn/build/gen.py b/gn/build/gen.py index 76f88e84224..3edefa7dc60 100755 --- a/gn/build/gen.py +++ b/gn/build/gen.py @@ -11,11 +11,9 @@ import optparse import os import platform import re -import shutil import subprocess import sys import tempfile -import urllib2 SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) REPO_ROOT = os.path.dirname(SCRIPT_DIR) @@ -41,6 +39,8 @@ class Platform(object): self._platform = 'aix' elif self._platform.startswith('fuchsia'): self._platform = 'fuchsia' + elif self._platform.startswith('freebsd'): + self._platform = 'freebsd' @staticmethod def known_platforms(): @@ -68,7 +68,7 @@ class Platform(object): return self._platform == 'aix' def is_posix(self): - return self._platform in ['linux', 'darwin', 'aix'] + return self._platform in ['linux', 'freebsd', 'darwin', 'aix'] def main(argv): @@ -87,12 +87,12 @@ def main(argv): help='Enable the use of LTO') parser.add_option('--use-icf', action='store_true', help='Enable the use of Identical Code Folding') - parser.add_option('--no-sysroot', action='store_true', - help='(Linux only) Do not build with the Debian sysroot.') parser.add_option('--no-last-commit-position', action='store_true', help='Do not generate last_commit_position.h.') parser.add_option('--out-path', help='The path to generate the build files in.') + parser.add_option('--no-strip', action='store_true', + help='Don\'t strip release build. Useful for profiling.') options, args = parser.parse_args(argv) if args: @@ -104,18 +104,13 @@ def main(argv): else: host = platform - linux_sysroot = None - if platform.is_linux() and not options.no_sysroot: - linux_sysroot = UpdateLinuxSysroot() - out_dir = options.out_path or os.path.join(REPO_ROOT, 'out') if not os.path.isdir(out_dir): os.makedirs(out_dir) if not options.no_last_commit_position: GenerateLastCommitPosition(host, os.path.join(out_dir, 'last_commit_position.h')) - WriteGNNinja(os.path.join(out_dir, 'build.ninja'), platform, host, options, - linux_sysroot) + WriteGNNinja(os.path.join(out_dir, 'build.ninja'), platform, host, options) return 0 @@ -124,7 +119,7 @@ def GenerateLastCommitPosition(host, header): describe_output = subprocess.check_output( ['git', 'describe', 'HEAD', '--match', ROOT_TAG], shell=host.is_windows(), cwd=REPO_ROOT) - mo = re.match(ROOT_TAG + '-(\d+)-g([0-9a-f]+)', describe_output) + mo = re.match(ROOT_TAG + '-(\d+)-g([0-9a-f]+)', describe_output.decode()) if not mo: raise ValueError( 'Unexpected output from git describe when generating version header') @@ -142,58 +137,14 @@ def GenerateLastCommitPosition(host, header): # Only write/touch this file if the commit position has changed. old_contents = '' if os.path.isfile(header): - with open(header, 'rb') as f: + with open(header, 'r') as f: old_contents = f.read() if old_contents != contents: - with open(header, 'wb') as f: + with open(header, 'w') as f: f.write(contents) -def UpdateLinuxSysroot(): - # Sysroot revision from: - # https://cs.chromium.org/chromium/src/build/linux/sysroot_scripts/sysroots.json - server = 'https://commondatastorage.googleapis.com' - path = 'chrome-linux-sysroot/toolchain' - revision = '1015a998c2adf188813cca60b558b0ea1a0b6ced' - filename = 'debian_sid_amd64_sysroot.tar.xz' - - url = '%s/%s/%s/%s' % (server, path, revision, filename) - - sysroot = os.path.join(SCRIPT_DIR, os.pardir, '.linux-sysroot') - - stamp = os.path.join(sysroot, '.stamp') - if os.path.exists(stamp): - with open(stamp) as s: - if s.read() == url: - return sysroot - - print 'Installing Debian root image from %s' % url - - if os.path.isdir(sysroot): - shutil.rmtree(sysroot) - os.mkdir(sysroot) - tarball = os.path.join(sysroot, filename) - print 'Downloading %s' % url - - for _ in range(3): - response = urllib2.urlopen(url) - with open(tarball, 'wb') as f: - f.write(response.read()) - break - else: - raise Exception('Failed to download %s' % url) - - subprocess.check_call(['tar', 'xf', tarball, '-C', sysroot]) - - os.remove(tarball) - - with open(stamp, 'w') as s: - s.write(url) - - return sysroot - - def WriteGenericNinja(path, static_libraries, executables, cc, cxx, ar, ld, platform, host, options, cflags=[], cflags_cc=[], ldflags=[], libflags=[], @@ -220,6 +171,7 @@ def WriteGenericNinja(path, static_libraries, executables, 'msvc': 'build_win.ninja.template', 'darwin': 'build_mac.ninja.template', 'linux': 'build_linux.ninja.template', + 'freebsd': 'build_linux.ninja.template', 'aix': 'build_aix.ninja.template', }[platform.platform()]) @@ -259,7 +211,7 @@ def WriteGenericNinja(path, static_libraries, executables, ' '.join(cflags_cc + settings.get('cflags_cc', [])), ]) - for library, settings in static_libraries.iteritems(): + for library, settings in static_libraries.items(): for src_file in settings['sources']: build_source(src_file, settings) @@ -269,7 +221,7 @@ def WriteGenericNinja(path, static_libraries, executables, ninja_lines.append(' libflags = %s' % ' '.join(libflags)) - for executable, settings in executables.iteritems(): + for executable, settings in executables.items(): for src_file in settings['sources']: build_source(src_file, settings) @@ -298,7 +250,7 @@ def WriteGenericNinja(path, static_libraries, executables, os.path.relpath(template_filename, os.path.dirname(path)) + '\n') -def WriteGNNinja(path, platform, host, options, linux_sysroot): +def WriteGNNinja(path, platform, host, options): if platform.is_msvc(): cc = os.environ.get('CC', 'cl.exe') cxx = os.environ.get('CXX', 'cl.exe') @@ -328,6 +280,8 @@ def WriteGNNinja(path, platform, host, options, linux_sysroot): else: cflags.append('-DNDEBUG') cflags.append('-O3') + if options.no_strip: + cflags.append('-g') ldflags.append('-O3') # Use -fdata-sections and -ffunction-sections to place each function # or data item into its own section so --gc-sections can eliminate any @@ -341,15 +295,16 @@ def WriteGNNinja(path, platform, host, options, linux_sysroot): ldflags.append('-Wl,--gc-sections') # Omit all symbol information from the output file. - if platform.is_darwin(): - ldflags.append('-Wl,-S') - elif platform.is_aix(): - ldflags.append('-Wl,-s') - else: - ldflags.append('-Wl,-strip-all') + if options.no_strip is None: + if platform.is_darwin(): + ldflags.append('-Wl,-S') + elif platform.is_aix(): + ldflags.append('-Wl,-s') + else: + ldflags.append('-Wl,-strip-all') # Enable identical code-folding. - if options.use_icf: + if options.use_icf and not platform.is_darwin(): ldflags.append('-Wl,--icf=all') cflags.extend([ @@ -359,30 +314,27 @@ def WriteGNNinja(path, platform, host, options, linux_sysroot): '-pipe', '-fno-exceptions', '-fno-rtti', + '-fdiagnostics-color', ]) cflags_cc.extend(['-std=c++14', '-Wno-c++11-narrowing']) if platform.is_linux(): - if linux_sysroot: - # Use the sid sysroot that UpdateLinuxSysroot() downloads. - cflags.append('--sysroot=' + linux_sysroot) - ldflags.append('--sysroot=' + linux_sysroot) ldflags.extend([ '-static-libstdc++', '-Wl,--as-needed', ]) - libs.extend([ - # These are needed by libc++. - '-ldl', - '-lpthread', - ]) + # This is needed by libc++. + libs.append('-ldl') elif platform.is_darwin(): min_mac_version_flag = '-mmacosx-version-min=10.9' cflags.append(min_mac_version_flag) ldflags.append(min_mac_version_flag) elif platform.is_aix(): cflags_cc.append('-maix64') - ldflags.extend(['-maix64', '-pthread']) + ldflags.append('-maix64') + + if platform.is_posix(): + ldflags.append('-pthread') if options.use_lto: cflags.extend(['-flto', '-fwhole-program-vtables']) @@ -390,7 +342,7 @@ def WriteGNNinja(path, platform, host, options, linux_sysroot): elif platform.is_msvc(): if not options.debug: - cflags.extend(['/Ox', '/DNDEBUG', '/GL']) + cflags.extend(['/O2', '/DNDEBUG', '/GL']) libflags.extend(['/LTCG']) ldflags.extend(['/LTCG', '/OPT:REF', '/OPT:ICF']) @@ -404,7 +356,6 @@ def WriteGNNinja(path, platform, host, options, linux_sysroot): '/D_UNICODE', '/D_WIN32_WINNT=0x0A00', '/FS', - '/Gy', '/W4', '/WX', '/Zi', @@ -413,6 +364,7 @@ def WriteGNNinja(path, platform, host, options, linux_sysroot): '/wd4127', '/wd4244', '/wd4267', + '/wd4505', '/wd4838', '/wd4996', ]) @@ -478,6 +430,7 @@ def WriteGNNinja(path, platform, host, options, linux_sysroot): 'tools/gn/command_format.cc', 'tools/gn/command_gen.cc', 'tools/gn/command_help.cc', + 'tools/gn/command_meta.cc', 'tools/gn/command_ls.cc', 'tools/gn/command_path.cc', 'tools/gn/command_refs.cc', @@ -512,6 +465,7 @@ def WriteGNNinja(path, platform, host, options, linux_sysroot): 'tools/gn/function_template.cc', 'tools/gn/function_toolchain.cc', 'tools/gn/function_write_file.cc', + 'tools/gn/generated_file_target_generator.cc', 'tools/gn/group_target_generator.cc', 'tools/gn/header_checker.cc', 'tools/gn/import_manager.cc', @@ -526,12 +480,15 @@ def WriteGNNinja(path, platform, host, options, linux_sysroot): 'tools/gn/lib_file.cc', 'tools/gn/loader.cc', 'tools/gn/location.cc', + 'tools/gn/metadata.cc', + 'tools/gn/metadata_walk.cc', 'tools/gn/ninja_action_target_writer.cc', 'tools/gn/ninja_binary_target_writer.cc', 'tools/gn/ninja_build_writer.cc', 'tools/gn/ninja_bundle_data_target_writer.cc', 'tools/gn/ninja_copy_target_writer.cc', 'tools/gn/ninja_create_bundle_target_writer.cc', + 'tools/gn/ninja_generated_file_target_writer.cc', 'tools/gn/ninja_group_target_writer.cc', 'tools/gn/ninja_target_command_util.cc', 'tools/gn/ninja_target_writer.cc', @@ -625,12 +582,15 @@ def WriteGNNinja(path, platform, host, options, linux_sysroot): 'tools/gn/label_pattern_unittest.cc', 'tools/gn/label_unittest.cc', 'tools/gn/loader_unittest.cc', + 'tools/gn/metadata_unittest.cc', + 'tools/gn/metadata_walk_unittest.cc', 'tools/gn/ninja_action_target_writer_unittest.cc', 'tools/gn/ninja_binary_target_writer_unittest.cc', 'tools/gn/ninja_build_writer_unittest.cc', 'tools/gn/ninja_bundle_data_target_writer_unittest.cc', 'tools/gn/ninja_copy_target_writer_unittest.cc', 'tools/gn/ninja_create_bundle_target_writer_unittest.cc', + 'tools/gn/ninja_generated_file_target_writer_unittest.cc', 'tools/gn/ninja_group_target_writer_unittest.cc', 'tools/gn/ninja_target_writer_unittest.cc', 'tools/gn/ninja_toolchain_writer_unittest.cc', @@ -643,6 +603,7 @@ def WriteGNNinja(path, platform, host, options, linux_sysroot): 'tools/gn/runtime_deps_unittest.cc', 'tools/gn/scope_per_file_provider_unittest.cc', 'tools/gn/scope_unittest.cc', + 'tools/gn/setup_unittest.cc', 'tools/gn/source_dir_unittest.cc', 'tools/gn/source_file_unittest.cc', 'tools/gn/string_utils_unittest.cc', @@ -674,32 +635,11 @@ def WriteGNNinja(path, platform, host, options, linux_sysroot): 'base/strings/string16.cc', ]) - if platform.is_linux() or platform.is_aix(): - static_libraries['base']['sources'].extend([ - 'base/strings/sys_string_conversions_posix.cc', - ]) - - if platform.is_darwin(): - static_libraries['base']['sources'].extend([ - 'base/files/file_util_mac.mm', - 'base/mac/bundle_locations.mm', - 'base/mac/foundation_util.mm', - 'base/strings/sys_string_conversions_mac.mm', - ]) - - libs.extend([ - '-framework', 'AppKit', - '-framework', 'CoreFoundation', - '-framework', 'Foundation', - '-framework', 'Security', - ]) - if platform.is_windows(): static_libraries['base']['sources'].extend([ 'base/files/file_enumerator_win.cc', 'base/files/file_util_win.cc', 'base/files/file_win.cc', - 'base/strings/sys_string_conversions_win.cc', 'base/win/registry.cc', 'base/win/scoped_handle.cc', 'base/win/scoped_process_information.cc', diff --git a/gn/docs/faq.md b/gn/docs/faq.md index 55d8aeffead..699df3da391 100644 --- a/gn/docs/faq.md +++ b/gn/docs/faq.md @@ -50,3 +50,9 @@ See [GNCrossCompiles](cross_compiles.md) for more info. Yes! If you create a group target called "default" in the top-level (root) build file, i.e., "//:default", GN will tell Ninja to build that by default, rather than building everything. + +## Are there any public presentations on GN? + +[There's at least one](https://docs.google.com/presentation/d/15Zwb53JcncHfEwHpnG_PoIbbzQ3GQi_cpujYwbpcbZo/edit?usp=sharing), from 2015. There +haven't been big changes since then apart from moving it to a standalone +repo, so it should still be relevant. diff --git a/gn/docs/hacking.md b/gn/docs/hacking.md deleted file mode 100644 index be3f1328c30..00000000000 --- a/gn/docs/hacking.md +++ /dev/null @@ -1,23 +0,0 @@ -# Hacking on the GN binary itself - -## Building GN itself - -GN is part of the Chromium tree, in [//tools/gn/](../). If you have a -Chromium checkout, you already have the source and you can do `ninja -C -out/Debug gn` to build it. - -To build gn using gn, run (in the root `src` directory): - -``` -gn gen out/Default -ninja -C out/Default gn -``` - -Change `out/Default` as necessary to put the build directory where you -want. - -## Running GN's unit tests - -``` -ninja -C out/Default gn_unittests && out/Default/gn_unittests -``` diff --git a/gn/docs/reference.md b/gn/docs/reference.md index f2b84f97a19..fe23b196b84 100644 --- a/gn/docs/reference.md +++ b/gn/docs/reference.md @@ -5,135 +5,142 @@ ## Contents * [Commands](#commands) - * [analyze: Analyze which targets are affected by a list of files.](#analyze) - * [args: Display or configure arguments declared by the build.](#args) - * [check: Check header dependencies.](#check) - * [clean: Cleans the output directory.](#clean) - * [desc: Show lots of insightful information about a target or config.](#desc) - * [format: Format .gn file.](#format) - * [gen: Generate ninja files.](#gen) - * [help: Does what you think.](#help) - * [ls: List matching targets.](#ls) - * [path: Find paths between two targets.](#path) - * [refs: Find stuff referencing a target or file.](#refs) + * [analyze: Analyze which targets are affected by a list of files.](#cmd_analyze) + * [args: Display or configure arguments declared by the build.](#cmd_args) + * [check: Check header dependencies.](#cmd_check) + * [clean: Cleans the output directory.](#cmd_clean) + * [desc: Show lots of insightful information about a target or config.](#cmd_desc) + * [format: Format .gn files.](#cmd_format) + * [gen: Generate ninja files.](#cmd_gen) + * [help: Does what you think.](#cmd_help) + * [ls: List matching targets.](#cmd_ls) + * [meta: List target metadata collection results.](#cmd_meta) + * [path: Find paths between two targets.](#cmd_path) + * [refs: Find stuff referencing a target or file.](#cmd_refs) * [Target declarations](#targets) - * [action: Declare a target that runs a script a single time.](#action) - * [action_foreach: Declare a target that runs a script over a set of files.](#action_foreach) - * [bundle_data: [iOS/macOS] Declare a target without output.](#bundle_data) - * [copy: Declare a target that copies files.](#copy) - * [create_bundle: [iOS/macOS] Build an iOS or macOS bundle.](#create_bundle) - * [executable: Declare an executable target.](#executable) - * [group: Declare a named group of targets.](#group) - * [loadable_module: Declare a loadable module target.](#loadable_module) - * [shared_library: Declare a shared library target.](#shared_library) - * [source_set: Declare a source set target.](#source_set) - * [static_library: Declare a static library target.](#static_library) - * [target: Declare an target with the given programmatic type.](#target) + * [action: Declare a target that runs a script a single time.](#func_action) + * [action_foreach: Declare a target that runs a script over a set of files.](#func_action_foreach) + * [bundle_data: [iOS/macOS] Declare a target without output.](#func_bundle_data) + * [copy: Declare a target that copies files.](#func_copy) + * [create_bundle: [iOS/macOS] Build an iOS or macOS bundle.](#func_create_bundle) + * [executable: Declare an executable target.](#func_executable) + * [generated_file: Declare a generated_file target.](#func_generated_file) + * [group: Declare a named group of targets.](#func_group) + * [loadable_module: Declare a loadable module target.](#func_loadable_module) + * [shared_library: Declare a shared library target.](#func_shared_library) + * [source_set: Declare a source set target.](#func_source_set) + * [static_library: Declare a static library target.](#func_static_library) + * [target: Declare an target with the given programmatic type.](#func_target) * [Buildfile functions](#functions) - * [assert: Assert an expression is true at generation time.](#assert) - * [config: Defines a configuration object.](#config) - * [declare_args: Declare build arguments.](#declare_args) - * [defined: Returns whether an identifier is defined.](#defined) - * [exec_script: Synchronously run a script and return the output.](#exec_script) - * [foreach: Iterate over a list.](#foreach) - * [forward_variables_from: Copies variables from a different scope.](#forward_variables_from) - * [get_label_info: Get an attribute from a target's label.](#get_label_info) - * [get_path_info: Extract parts of a file or directory name.](#get_path_info) - * [get_target_outputs: [file list] Get the list of outputs from a target.](#get_target_outputs) - * [getenv: Get an environment variable.](#getenv) - * [import: Import a file into the current scope.](#import) - * [not_needed: Mark variables from scope as not needed.](#not_needed) - * [pool: Defines a pool object.](#pool) - * [print: Prints to the console.](#print) - * [process_file_template: Do template expansion over a list of files.](#process_file_template) - * [read_file: Read a file into a variable.](#read_file) - * [rebase_path: Rebase a file or directory to another location.](#rebase_path) - * [set_default_toolchain: Sets the default toolchain name.](#set_default_toolchain) - * [set_defaults: Set default values for a target type.](#set_defaults) - * [set_sources_assignment_filter: Set a pattern to filter source files.](#set_sources_assignment_filter) - * [split_list: Splits a list into N different sub-lists.](#split_list) - * [string_replace: Replaces substring in the given string.](#string_replace) - * [template: Define a template rule.](#template) - * [tool: Specify arguments to a toolchain tool.](#tool) - * [toolchain: Defines a toolchain.](#toolchain) - * [write_file: Write a file to disk.](#write_file) + * [assert: Assert an expression is true at generation time.](#func_assert) + * [config: Defines a configuration object.](#func_config) + * [declare_args: Declare build arguments.](#func_declare_args) + * [defined: Returns whether an identifier is defined.](#func_defined) + * [exec_script: Synchronously run a script and return the output.](#func_exec_script) + * [foreach: Iterate over a list.](#func_foreach) + * [forward_variables_from: Copies variables from a different scope.](#func_forward_variables_from) + * [get_label_info: Get an attribute from a target's label.](#func_get_label_info) + * [get_path_info: Extract parts of a file or directory name.](#func_get_path_info) + * [get_target_outputs: [file list] Get the list of outputs from a target.](#func_get_target_outputs) + * [getenv: Get an environment variable.](#func_getenv) + * [import: Import a file into the current scope.](#func_import) + * [not_needed: Mark variables from scope as not needed.](#func_not_needed) + * [pool: Defines a pool object.](#func_pool) + * [print: Prints to the console.](#func_print) + * [process_file_template: Do template expansion over a list of files.](#func_process_file_template) + * [read_file: Read a file into a variable.](#func_read_file) + * [rebase_path: Rebase a file or directory to another location.](#func_rebase_path) + * [set_default_toolchain: Sets the default toolchain name.](#func_set_default_toolchain) + * [set_defaults: Set default values for a target type.](#func_set_defaults) + * [set_sources_assignment_filter: Set a pattern to filter source files.](#func_set_sources_assignment_filter) + * [split_list: Splits a list into N different sub-lists.](#func_split_list) + * [string_replace: Replaces substring in the given string.](#func_string_replace) + * [template: Define a template rule.](#func_template) + * [tool: Specify arguments to a toolchain tool.](#func_tool) + * [toolchain: Defines a toolchain.](#func_toolchain) + * [write_file: Write a file to disk.](#func_write_file) * [Built-in predefined variables](#predefined_variables) - * [current_cpu: [string] The processor architecture of the current toolchain.](#current_cpu) - * [current_os: [string] The operating system of the current toolchain.](#current_os) - * [current_toolchain: [string] Label of the current toolchain.](#current_toolchain) - * [default_toolchain: [string] Label of the default toolchain.](#default_toolchain) - * [host_cpu: [string] The processor architecture that GN is running on.](#host_cpu) - * [host_os: [string] The operating system that GN is running on.](#host_os) - * [invoker: [string] The invoking scope inside a template.](#invoker) - * [python_path: [string] Absolute path of Python.](#python_path) - * [root_build_dir: [string] Directory where build commands are run.](#root_build_dir) - * [root_gen_dir: [string] Directory for the toolchain's generated files.](#root_gen_dir) - * [root_out_dir: [string] Root directory for toolchain output files.](#root_out_dir) - * [target_cpu: [string] The desired cpu architecture for the build.](#target_cpu) - * [target_gen_dir: [string] Directory for a target's generated files.](#target_gen_dir) - * [target_name: [string] The name of the current target.](#target_name) - * [target_os: [string] The desired operating system for the build.](#target_os) - * [target_out_dir: [string] Directory for target output files.](#target_out_dir) + * [current_cpu: [string] The processor architecture of the current toolchain.](#var_current_cpu) + * [current_os: [string] The operating system of the current toolchain.](#var_current_os) + * [current_toolchain: [string] Label of the current toolchain.](#var_current_toolchain) + * [default_toolchain: [string] Label of the default toolchain.](#var_default_toolchain) + * [host_cpu: [string] The processor architecture that GN is running on.](#var_host_cpu) + * [host_os: [string] The operating system that GN is running on.](#var_host_os) + * [invoker: [string] The invoking scope inside a template.](#var_invoker) + * [python_path: [string] Absolute path of Python.](#var_python_path) + * [root_build_dir: [string] Directory where build commands are run.](#var_root_build_dir) + * [root_gen_dir: [string] Directory for the toolchain's generated files.](#var_root_gen_dir) + * [root_out_dir: [string] Root directory for toolchain output files.](#var_root_out_dir) + * [target_cpu: [string] The desired cpu architecture for the build.](#var_target_cpu) + * [target_gen_dir: [string] Directory for a target's generated files.](#var_target_gen_dir) + * [target_name: [string] The name of the current target.](#var_target_name) + * [target_os: [string] The desired operating system for the build.](#var_target_os) + * [target_out_dir: [string] Directory for target output files.](#var_target_out_dir) * [Variables you set in targets](#target_variables) - * [all_dependent_configs: [label list] Configs to be forced on dependents.](#all_dependent_configs) - * [allow_circular_includes_from: [label list] Permit includes from deps.](#allow_circular_includes_from) - * [arflags: [string list] Arguments passed to static_library archiver.](#arflags) - * [args: [string list] Arguments passed to an action.](#args) - * [asmflags: [string list] Flags passed to the assembler.](#asmflags) - * [assert_no_deps: [label pattern list] Ensure no deps on these targets.](#assert_no_deps) - * [bundle_contents_dir: Expansion of {{bundle_contents_dir}} in create_bundle.](#bundle_contents_dir) - * [bundle_deps_filter: [label list] A list of labels that are filtered out.](#bundle_deps_filter) - * [bundle_executable_dir: Expansion of {{bundle_executable_dir}} in create_bundle](#bundle_executable_dir) - * [bundle_plugins_dir: Expansion of {{bundle_plugins_dir}} in create_bundle.](#bundle_plugins_dir) - * [bundle_resources_dir: Expansion of {{bundle_resources_dir}} in create_bundle.](#bundle_resources_dir) - * [bundle_root_dir: Expansion of {{bundle_root_dir}} in create_bundle.](#bundle_root_dir) - * [cflags: [string list] Flags passed to all C compiler variants.](#cflags) - * [cflags_c: [string list] Flags passed to the C compiler.](#cflags_c) - * [cflags_cc: [string list] Flags passed to the C++ compiler.](#cflags_cc) - * [cflags_objc: [string list] Flags passed to the Objective C compiler.](#cflags_objc) - * [cflags_objcc: [string list] Flags passed to the Objective C++ compiler.](#cflags_objcc) - * [check_includes: [boolean] Controls whether a target's files are checked.](#check_includes) - * [code_signing_args: [string list] Arguments passed to code signing script.](#code_signing_args) - * [code_signing_outputs: [file list] Output files for code signing step.](#code_signing_outputs) - * [code_signing_script: [file name] Script for code signing.](#code_signing_script) - * [code_signing_sources: [file list] Sources for code signing step.](#code_signing_sources) - * [complete_static_lib: [boolean] Links all deps into a static library.](#complete_static_lib) - * [configs: [label list] Configs applying to this target or config.](#configs) - * [data: [file list] Runtime data file dependencies.](#data) - * [data_deps: [label list] Non-linked dependencies.](#data_deps) - * [defines: [string list] C preprocessor defines.](#defines) - * [depfile: [string] File name for input dependencies for actions.](#depfile) - * [deps: [label list] Private linked dependencies.](#deps) - * [friend: [label pattern list] Allow targets to include private headers.](#friend) - * [include_dirs: [directory list] Additional include directories.](#include_dirs) - * [inputs: [file list] Additional compile-time dependencies.](#inputs) - * [ldflags: [string list] Flags passed to the linker.](#ldflags) - * [lib_dirs: [directory list] Additional library directories.](#lib_dirs) - * [libs: [string list] Additional libraries to link.](#libs) - * [output_dir: [directory] Directory to put output file in.](#output_dir) - * [output_extension: [string] Value to use for the output's file extension.](#output_extension) - * [output_name: [string] Name for the output file other than the default.](#output_name) - * [output_prefix_override: [boolean] Don't use prefix for output name.](#output_prefix_override) - * [outputs: [file list] Output files for actions and copy targets.](#outputs) - * [partial_info_plist: [filename] Path plist from asset catalog compiler.](#partial_info_plist) - * [pool: [string] Label of the pool used by the action.](#pool) - * [precompiled_header: [string] Header file to precompile.](#precompiled_header) - * [precompiled_header_type: [string] "gcc" or "msvc".](#precompiled_header_type) - * [precompiled_source: [file name] Source file to precompile.](#precompiled_source) - * [product_type: [string] Product type for Xcode projects.](#product_type) - * [public: [file list] Declare public header files for a target.](#public) - * [public_configs: [label list] Configs applied to dependents.](#public_configs) - * [public_deps: [label list] Declare public dependencies.](#public_deps) - * [response_file_contents: [string list] Contents of .rsp file for actions.](#response_file_contents) - * [script: [file name] Script file for actions.](#script) - * [sources: [file list] Source files for a target.](#sources) - * [testonly: [boolean] Declares a target must only be used for testing.](#testonly) - * [visibility: [label list] A list of labels that can depend on a target.](#visibility) - * [write_runtime_deps: Writes the target's runtime_deps to the given path.](#write_runtime_deps) - * [xcode_extra_attributes: [scope] Extra attributes for Xcode projects.](#xcode_extra_attributes) - * [test_application_name: [string] Test application name for unit or ui test target.](#test_application_name) + * [all_dependent_configs: [label list] Configs to be forced on dependents.](#var_all_dependent_configs) + * [allow_circular_includes_from: [label list] Permit includes from deps.](#var_allow_circular_includes_from) + * [arflags: [string list] Arguments passed to static_library archiver.](#var_arflags) + * [args: [string list] Arguments passed to an action.](#var_args) + * [asmflags: [string list] Flags passed to the assembler.](#var_asmflags) + * [assert_no_deps: [label pattern list] Ensure no deps on these targets.](#var_assert_no_deps) + * [bundle_contents_dir: Expansion of {{bundle_contents_dir}} in create_bundle.](#var_bundle_contents_dir) + * [bundle_deps_filter: [label list] A list of labels that are filtered out.](#var_bundle_deps_filter) + * [bundle_executable_dir: Expansion of {{bundle_executable_dir}} in create_bundle](#var_bundle_executable_dir) + * [bundle_resources_dir: Expansion of {{bundle_resources_dir}} in create_bundle.](#var_bundle_resources_dir) + * [bundle_root_dir: Expansion of {{bundle_root_dir}} in create_bundle.](#var_bundle_root_dir) + * [cflags: [string list] Flags passed to all C compiler variants.](#var_cflags) + * [cflags_c: [string list] Flags passed to the C compiler.](#var_cflags_c) + * [cflags_cc: [string list] Flags passed to the C++ compiler.](#var_cflags_cc) + * [cflags_objc: [string list] Flags passed to the Objective C compiler.](#var_cflags_objc) + * [cflags_objcc: [string list] Flags passed to the Objective C++ compiler.](#var_cflags_objcc) + * [check_includes: [boolean] Controls whether a target's files are checked.](#var_check_includes) + * [code_signing_args: [string list] Arguments passed to code signing script.](#var_code_signing_args) + * [code_signing_outputs: [file list] Output files for code signing step.](#var_code_signing_outputs) + * [code_signing_script: [file name] Script for code signing.](#var_code_signing_script) + * [code_signing_sources: [file list] Sources for code signing step.](#var_code_signing_sources) + * [complete_static_lib: [boolean] Links all deps into a static library.](#var_complete_static_lib) + * [configs: [label list] Configs applying to this target or config.](#var_configs) + * [contents: Contents to write to file.](#var_contents) + * [data: [file list] Runtime data file dependencies.](#var_data) + * [data_deps: [label list] Non-linked dependencies.](#var_data_deps) + * [data_keys: [string list] Keys from which to collect metadata.](#var_data_keys) + * [defines: [string list] C preprocessor defines.](#var_defines) + * [depfile: [string] File name for input dependencies for actions.](#var_depfile) + * [deps: [label list] Private linked dependencies.](#var_deps) + * [friend: [label pattern list] Allow targets to include private headers.](#var_friend) + * [include_dirs: [directory list] Additional include directories.](#var_include_dirs) + * [inputs: [file list] Additional compile-time dependencies.](#var_inputs) + * [ldflags: [string list] Flags passed to the linker.](#var_ldflags) + * [lib_dirs: [directory list] Additional library directories.](#var_lib_dirs) + * [libs: [string list] Additional libraries to link.](#var_libs) + * [metadata: [scope] Metadata of this target.](#var_metadata) + * [output_conversion: Data format for generated_file targets.](#var_output_conversion) + * [output_dir: [directory] Directory to put output file in.](#var_output_dir) + * [output_extension: [string] Value to use for the output's file extension.](#var_output_extension) + * [output_name: [string] Name for the output file other than the default.](#var_output_name) + * [output_prefix_override: [boolean] Don't use prefix for output name.](#var_output_prefix_override) + * [outputs: [file list] Output files for actions and copy targets.](#var_outputs) + * [partial_info_plist: [filename] Path plist from asset catalog compiler.](#var_partial_info_plist) + * [pool: [string] Label of the pool used by the action.](#var_pool) + * [precompiled_header: [string] Header file to precompile.](#var_precompiled_header) + * [precompiled_header_type: [string] "gcc" or "msvc".](#var_precompiled_header_type) + * [precompiled_source: [file name] Source file to precompile.](#var_precompiled_source) + * [product_type: [string] Product type for Xcode projects.](#var_product_type) + * [public: [file list] Declare public header files for a target.](#var_public) + * [public_configs: [label list] Configs applied to dependents.](#var_public_configs) + * [public_deps: [label list] Declare public dependencies.](#var_public_deps) + * [rebase: [boolean] Rebase collected metadata as files.](#var_rebase) + * [response_file_contents: [string list] Contents of .rsp file for actions.](#var_response_file_contents) + * [script: [file name] Script file for actions.](#var_script) + * [sources: [file list] Source files for a target.](#var_sources) + * [testonly: [boolean] Declares a target must only be used for testing.](#var_testonly) + * [visibility: [label list] A list of labels that can depend on a target.](#var_visibility) + * [walk_keys: [string list] Key(s) for managing the metadata collection walk.](#var_walk_keys) + * [write_runtime_deps: Writes the target's runtime_deps to the given path.](#var_write_runtime_deps) + * [xcode_extra_attributes: [scope] Extra attributes for Xcode projects.](#var_xcode_extra_attributes) + * [xcode_test_application_name: [string] Name for Xcode test target.](#var_xcode_test_application_name) * [Other help topics](#other) - * [all: Print all the help at once](#all) + * all: Print all the help at once * [buildargs: How build arguments work.](#buildargs) * [dotfile: Info about the toplevel .gn file.](#dotfile) * [execution: Build graph and execution overview.](#execution) @@ -146,11 +153,11 @@ * [output_conversion: Specifies how to transform a value to output.](#output_conversion) * [runtime_deps: How runtime dependency computation works.](#runtime_deps) * [source_expansion: Map sources to outputs for scripts.](#source_expansion) - * [switches: Show available command-line switches.](#switches) + * [switches: Show available command-line switches.](#switch_list) ## Commands -### **gn analyze ** +### **gn analyze <out_dir> <input_path> <output_path>** ``` Analyze which targets are affected by a list of files. @@ -220,9 +227,13 @@ tries really hard to always write something to the output JSON and convey errors that way rather than via return codes. ``` -### **gn args [\--list] [\--short] [\--args] [\--overrides-only]** +### **gn args**: (command-line tool) ``` + Display or configure arguments declared by the build. + + gn args [--list] [--short] [--args] [--overrides-only] + See also "gn help buildargs" for a more high-level overview of how build arguments work. ``` @@ -305,7 +316,7 @@ given arguments set (which may affect the values of other arguments). ``` -### **gn check [] [\--force]** +### **gn check <out_dir> [<label_pattern>] [\--force] [\--check-generated]** ``` GN's include header checker validates that the includes for C-like source @@ -326,14 +337,19 @@ --force Ignores specifications of "check_includes = false" and checks all target's files that match the target label. + + --check-generated + Generated files are normally not checked since they do not exist + until after a build. With this flag, those generated files that + can be found on disk are also checked. ``` #### **What gets checked** ``` - The .gn file may specify a list of targets to be checked. Only these targets - will be checked if no label_pattern is specified on the command line. - Otherwise, the command-line list is used instead. See "gn help dotfile". + The .gn file may specify a list of targets to be checked in the list + check_targets (see "gn help dotfile"). If a label pattern is specified + on the command line, check_targets is not used. Targets can opt-out from checking with "check_includes = false" (see "gn help check_includes"). @@ -343,6 +359,9 @@ - GN opens all C-like source files in the targets to be checked and scans the top for includes. + - Generated files (that might not exist yet) are ignored unless + the --check-generated flag is provided. + - Includes with a "nogncheck" annotation are skipped (see "gn help nogncheck"). @@ -420,16 +439,18 @@ gn check out/Default "//foo/* Check only the files in targets in the //foo directory tree. ``` -### **gn clean ** +### **gn clean <out_dir>** ``` Deletes the contents of the output directory except for args.gn and creates a Ninja build environment sufficient to regenerate the build. ``` -### **gn desc