Remove all macOS specific code from base and framework dependencies This is no longer needed or necessary. Change-Id: I95586a3ddab8312f7c7a4d25e0db340772714438 Reviewed-on: https://gn-review.googlesource.com/c/2942 Commit-Queue: Petr Hosek <phosek@google.com> Reviewed-by: Scott Graham <scottmg@chromium.org>
diff --git a/base/files/file_path.cc b/base/files/file_path.cc index a66c8cc..014bc9e 100644 --- a/base/files/file_path.cc +++ b/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 @@ // 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::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/base/files/file_util.cc b/base/files/file_util.cc index d087b00..9a98a0b 100644 --- a/base/files/file_util.cc +++ b/base/files/file_util.cc
@@ -43,12 +43,6 @@ 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/base/files/file_util.h b/base/files/file_util.h index bfcac01..e22f40f 100644 --- a/base/files/file_util.h +++ b/base/files/file_util.h
@@ -75,13 +75,6 @@ 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 @@ 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 @@ // 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 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/base/files/file_util_mac.mm b/base/files/file_util_mac.mm deleted file mode 100644 index 35fd27a..0000000 --- a/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 <Foundation/Foundation.h> -#include <copyfile.h> -#include <stdlib.h> -#include <string.h> - -#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/base/files/file_util_posix.cc b/base/files/file_util_posix.cc index 2ef6afc..eb07e64 100644 --- a/base/files/file_util_posix.cc +++ b/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 <AvailabilityMacros.h> -#include "base/mac/foundation_util.h" #endif #if !defined(OS_IOS) @@ -181,143 +179,6 @@ 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) @@ -390,18 +251,6 @@ *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]) { @@ -934,33 +783,5 @@ } #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/base/files/file_util_win.cc b/base/files/file_util_win.cc index 2a1e9ec..34d328b 100644 --- a/base/files/file_util_win.cc +++ b/base/files/file_util_win.cc
@@ -91,121 +91,6 @@ 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 @@ 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 @@ 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 @@ return std::min(whole_path_limit, static_cast<int>(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 @@ 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/base/logging.cc b/base/logging.cc index c381a28..c2c243f 100644 --- a/base/logging.cc +++ b/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/base/mac/bundle_locations.mm b/base/mac/bundle_locations.mm deleted file mode 100644 index 54021b8..0000000 --- a/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/base/mac/foundation_util.h b/base/mac/foundation_util.h deleted file mode 100644 index 6e1ce55..0000000 --- a/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 <CoreFoundation/CoreFoundation.h> - -#include <string> -#include <vector> - -#include "base/logging.h" -#include "base/mac/scoped_cftyperef.h" -#include "util/build_config.h" - -#if defined(__OBJC__) -#import <Foundation/Foundation.h> -@class NSFont; -@class UIFont; -#else // __OBJC__ -#include <CoreFoundation/CoreFoundation.h> -class NSBundle; -class NSFont; -class NSString; -class UIFont; -#endif // __OBJC__ - -#if defined(OS_IOS) -#include <CoreText/CoreText.h> -#else -#include <ApplicationServices/ApplicationServices.h> -#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<CFNumberRef>( -// CFArrayGetValueAtIndex(array, index)); -// -// CFTypeRef hello = CFSTR("hello world"); -// CFStringRef some_string = base::mac::CFCastStrict<CFStringRef>(hello); - -template <typename T> -T CFCast(const CFTypeRef& cf_val); - -template <typename T> -T CFCastStrict(const CFTypeRef& cf_val); - -#define CF_CAST_DECL(TypeCF) \ - template <> \ - TypeCF##Ref CFCast<TypeCF##Ref>(const CFTypeRef& cf_val); \ - \ - template <> \ - TypeCF##Ref CFCastStrict<TypeCF##Ref>(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<NSString>( -// [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"]); -// -// NSString* str = base::mac::ObjCCastStrict<NSString>( -// [ns_arr_of_ns_strs objectAtIndex:0]); -template <typename T> -T* ObjCCast(id objc_val) { - if ([objc_val isKindOfClass:[T class]]) { - return reinterpret_cast<T*>(objc_val); - } - return nil; -} - -template <typename T> -T* ObjCCastStrict(id objc_val) { - T* rv = ObjCCast<T>(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 <typename T> -T GetValueFromDictionary(CFDictionaryRef dict, CFStringRef key) { - CFTypeRef value = CFDictionaryGetValue(dict, key); - T value_specific = CFCast<T>(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/base/mac/foundation_util.mm b/base/mac/foundation_util.mm deleted file mode 100644 index d88ada8..0000000 --- a/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 <stddef.h> -#include <stdlib.h> -#include <string.h> - -#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 <AppKit/AppKit.h> -#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<NSString*>* 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<std::string> 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<std::string>::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<NSObject> nsobj = static_cast<id<NSObject>>(obj); - [nsobj retain]; -} - -void NSObjectRelease(void* obj) { - id<NSObject> nsobj = static_cast<id<NSObject>>(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<TypeNS*>(reinterpret_cast<const TypeNS*>(cf_val)); \ - return ns_val; \ - } \ - \ - TypeCF##Ref NSToCFCast(TypeNS* ns_val) { \ - TypeCF##Ref cf_val = reinterpret_cast<TypeCF##Ref>(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<NSMutable##name*>(cf_val); \ - return ns_val; \ - } \ - \ - CFMutable##name##Ref NSToCFCast(NSMutable##name* ns_val) { \ - CFMutable##name##Ref cf_val = \ - reinterpret_cast<CFMutable##name##Ref>(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<NSFont*>(reinterpret_cast<const NSFont*>(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<CTFontRef>(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<TypeCF##Ref>(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<TypeCF##Ref>(const CFTypeRef& cf_val) { \ - TypeCF##Ref rv = CFCast<TypeCF##Ref>(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<CTFontRef>(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<NSObject> ns_val = reinterpret_cast<id>(const_cast<void*>(cf_val)); - if ([ns_val isKindOfClass:[NSFont class]]) { - return (CTFontRef)(cf_val); - } - return NULL; -} - -template <> -CTFontRef CFCastStrict<CTFontRef>(const CFTypeRef& cf_val) { - CTFontRef rv = CFCast<CTFontRef>(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<CFStringRef> 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::IsValueInRangeForNumericType<decltype(range_out->location)>( - range.location) && - base::IsValueInRangeForNumericType<decltype(range_out->length)>( - range.length) && - base::IsValueInRangeForNumericType<decltype(range_out->location)>( - 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<CFStringRef> desc(CFErrorCopyDescription(err)); - base::ScopedCFTypeRef<CFDictionaryRef> user_info(CFErrorCopyUserInfo(err)); - CFStringRef errorDesc = NULL; - if (user_info.get()) { - errorDesc = reinterpret_cast<CFStringRef>( - CFDictionaryGetValue(user_info.get(), kCFErrorDescriptionKey)); - } - o << "Code: " << CFErrorGetCode(err) << " Domain: " << CFErrorGetDomain(err) - << " Desc: " << desc.get(); - if (errorDesc) { - o << "(" << errorDesc << ")"; - } - return o; -}
diff --git a/base/strings/sys_string_conversions.h b/base/strings/sys_string_conversions.h deleted file mode 100644 index 9150c05..0000000 --- a/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 <stdint.h> - -#include <string> - -#include "base/strings/string16.h" -#include "base/strings/string_piece.h" -#include "util/build_config.h" - -#if defined(OS_MACOSX) -#include <CoreFoundation/CoreFoundation.h> -#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/base/strings/sys_string_conversions_mac.mm b/base/strings/sys_string_conversions_mac.mm deleted file mode 100644 index 3b78777..0000000 --- a/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 <Foundation/Foundation.h> -#include <stddef.h> - -#include <vector> - -#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 <typename StringType> -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<typename StringType::value_type> out_buffer(elements); - converted = - CFStringGetBytes(cfstring, whole_string, encoding, - 0, // lossByte - false, // isExternalRepresentation - reinterpret_cast<UInt8*>(&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 <typename InStringType, typename OutStringType> -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<CFStringRef> cfstring(CFStringCreateWithBytesNoCopy( - NULL, reinterpret_cast<const UInt8*>(in.data()), - in_length * sizeof(typename InStringType::value_type), in_encoding, false, - kCFAllocatorNull)); - if (!cfstring) - return OutStringType(); - - return CFStringToSTLStringWithEncodingT<OutStringType>(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 <typename StringType> -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<const UInt8*>(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<std::wstring, std::string>( - wide, kWideStringEncoding, kNarrowStringEncoding); -} - -// Do not assert in this function since it is used by the asssertion code! -std::wstring SysUTF8ToWide(StringPiece utf8) { - return STLStringToSTLStringWithEncodingsT<StringPiece, std::wstring>( - 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<std::string>(ref, - kNarrowStringEncoding); -} - -string16 SysCFStringRefToUTF16(CFStringRef ref) { - return CFStringToSTLStringWithEncodingT<string16>(ref, kMediumStringEncoding); -} - -std::string SysNSStringToUTF8(NSString* nsstring) { - if (!nsstring) - return std::string(); - return SysCFStringRefToUTF8(reinterpret_cast<CFStringRef>(nsstring)); -} - -string16 SysNSStringToUTF16(NSString* nsstring) { - if (!nsstring) - return string16(); - return SysCFStringRefToUTF16(reinterpret_cast<CFStringRef>(nsstring)); -} - -} // namespace base
diff --git a/base/strings/sys_string_conversions_posix.cc b/base/strings/sys_string_conversions_posix.cc deleted file mode 100644 index 0e14428..0000000 --- a/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 <stddef.h> -#include <wchar.h> - -#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<size_t>(-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<size_t>(-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<size_t>(-2): - case static_cast<size_t>(-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<size_t>(-2): - case static_cast<size_t>(-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/base/strings/sys_string_conversions_win.cc b/base/strings/sys_string_conversions_win.cc deleted file mode 100644 index 232dd78..0000000 --- a/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 <stdint.h> -#include <windows.h> - -#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<int>(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<int>(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/build/gen.py b/build/gen.py index 11c9246..6e23486 100755 --- a/build/gen.py +++ b/build/gen.py
@@ -675,32 +675,11 @@ '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/tools/gn/setup.cc b/tools/gn/setup.cc index 060f17f..9d2e7b1 100644 --- a/tools/gn/setup.cc +++ b/tools/gn/setup.cc
@@ -18,7 +18,6 @@ #include "base/memory/ref_counted.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" -#include "base/strings/sys_string_conversions.h" #include "base/strings/utf_string_conversions.h" #include "tools/gn/command_format.h" #include "tools/gn/commands.h" @@ -191,6 +190,24 @@ #if defined(OS_WIN) +std::wstring SysMultiByteToWide(base::StringPiece mb) { + if (mb.empty()) + return std::wstring(); + + int mb_length = static_cast<int>(mb.length()); + // Compute the length of the buffer. + int charcount = + MultiByteToWideChar(CP_ACP, 0, mb.data(), mb_length, NULL, 0); + if (charcount == 0) + return std::wstring(); + + std::wstring wide; + wide.resize(charcount); + MultiByteToWideChar(CP_ACP, 0, mb.data(), mb_length, &wide[0], charcount); + + return wide; +} + // Given the path to a batch file that runs Python, extracts the name of the // executable actually implementing Python. Generally people write a batch file // to put something named "python" on the path, which then just redirects to @@ -216,7 +233,7 @@ base::TrimWhitespaceASCII(python_path, base::TRIM_ALL, &python_path); // Python uses the system multibyte code page for sys.executable. - base::FilePath exe_path(base::SysNativeMBToWide(python_path)); + base::FilePath exe_path(SysMultiByteToWide(python_path)); // Check for reasonable output, cmd may have output an error message. if (base::PathExists(exe_path))