├── .clang-format ├── .gitattributes ├── .gitignore ├── .style.yapf ├── AUTHORS ├── BUILD.gn ├── LICENSE ├── OWNERS ├── README.md ├── base ├── BUILD.gn ├── apple │ ├── bridging.h │ ├── foundation_util.h │ ├── foundation_util.mm │ ├── mach_logging.cc │ ├── mach_logging.h │ ├── scoped_cftyperef.h │ ├── scoped_mach_port.cc │ ├── scoped_mach_port.h │ ├── scoped_mach_vm.cc │ ├── scoped_mach_vm.h │ ├── scoped_nsautorelease_pool.h │ ├── scoped_nsautorelease_pool.mm │ └── scoped_typeref.h ├── atomicops.h ├── atomicops_internals_atomicword_compat.h ├── atomicops_internals_portable.h ├── auto_reset.h ├── bit_cast.h ├── check.h ├── check_op.h ├── compiler_specific.h ├── containers │ ├── checked_iterators.h │ ├── dynamic_extent.h │ ├── heap_array.h │ ├── span.h │ └── util.h ├── cxx17_backports.h ├── debug │ ├── alias.cc │ └── alias.h ├── files │ ├── file_path.cc │ ├── file_path.h │ ├── file_util.h │ ├── file_util_posix.cc │ ├── scoped_file.cc │ └── scoped_file.h ├── format_macros.h ├── fuchsia │ ├── fuchsia_logging.cc │ └── fuchsia_logging.h ├── immediate_crash.h ├── logging.cc ├── logging.h ├── mac │ ├── close_nocancel.cc │ ├── scoped_ioobject.h │ └── scoped_launch_data.h ├── memory │ ├── free_deleter.h │ ├── page_size.h │ ├── page_size_posix.cc │ ├── page_size_win.cc │ ├── raw_ptr_exclusion.h │ └── scoped_policy.h ├── metrics │ ├── histogram_functions.h │ ├── histogram_macros.h │ └── persistent_histogram_allocator.h ├── notreached.h ├── numerics │ ├── basic_ops_impl.h │ ├── byte_conversions.h │ ├── checked_math.h │ ├── checked_math_impl.h │ ├── clamped_math.h │ ├── clamped_math_impl.h │ ├── safe_conversions.h │ ├── safe_conversions_arm_impl.h │ ├── safe_conversions_impl.h │ ├── safe_math.h │ ├── safe_math_arm_impl.h │ ├── safe_math_clang_gcc_impl.h │ └── safe_math_shared_impl.h ├── posix │ ├── eintr_wrapper.h │ ├── safe_strerror.cc │ └── safe_strerror.h ├── process │ ├── memory.cc │ └── memory.h ├── rand_util.cc ├── rand_util.h ├── scoped_clear_last_error.h ├── scoped_clear_last_error_win.cc ├── scoped_generic.h ├── strings │ ├── pattern.cc │ ├── pattern.h │ ├── strcat.cc │ ├── strcat.h │ ├── strcat_internal.h │ ├── string_number_conversions.cc │ ├── string_number_conversions.h │ ├── string_piece.h │ ├── string_util.cc │ ├── string_util.h │ ├── string_util_posix.h │ ├── string_util_win.cc │ ├── string_util_win.h │ ├── stringprintf.cc │ ├── stringprintf.h │ ├── sys_string_conversions.h │ ├── sys_string_conversions_mac.mm │ ├── utf_string_conversion_utils.cc │ ├── utf_string_conversion_utils.h │ ├── utf_string_conversions.cc │ └── utf_string_conversions.h ├── synchronization │ ├── condition_variable.h │ ├── condition_variable_posix.cc │ ├── lock.cc │ ├── lock.h │ ├── lock_impl.h │ ├── lock_impl_posix.cc │ └── lock_impl_win.cc ├── sys_byteorder.h ├── template_util.h ├── third_party │ └── icu │ │ ├── LICENSE │ │ ├── README.chromium │ │ ├── icu_utf.cc │ │ └── icu_utf.h ├── threading │ ├── thread_local_storage.cc │ ├── thread_local_storage.h │ ├── thread_local_storage_posix.cc │ └── thread_local_storage_win.cc └── types │ ├── cxx23_to_underlying.h │ └── to_address.h ├── build ├── BUILD.gn ├── build_config.h ├── buildflag.h ├── buildflag_header.gni ├── compiler.gni ├── config │ └── BUILD.gn ├── find_mac_sdk.py ├── ios │ ├── Application-Info.plist │ ├── BUILD.gn │ ├── BuildInfo.plist │ ├── Module-Info.plist │ ├── XCTRunnerAddition+Info.plist │ ├── codesign.py │ ├── entitlements.plist │ ├── find_signing_identity.py │ ├── ios_sdk.gni │ ├── plist_util.py │ ├── rules.gni │ ├── sdk_info.py │ └── strip_arm64e.py ├── platform.gni ├── sysroot.gni ├── win_helper.py └── write_buildflag_header.py ├── codereview.settings └── testing ├── BUILD.gn └── platform_test.h /.clang-format: -------------------------------------------------------------------------------- 1 | # Copyright 2013 The Chromium Authors 2 | # Use of this source code is governed by a BSD-style license that can be 3 | # found in the LICENSE file. 4 | 5 | { 6 | BasedOnStyle: Chromium, 7 | AlignTrailingComments: false, 8 | BinPackArguments: false, 9 | InsertBraces: true, 10 | InsertNewlineAtEOF: true, 11 | Standard: Cpp11, 12 | } 13 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Copyright 2019 The Chromium Authors 2 | # Use of this source code is governed by a BSD-style license that can be 3 | # found in the LICENSE file. 4 | 5 | *.c text eol=lf 6 | *.cc text eol=lf 7 | *.gn text eol=lf 8 | *.gni text eol=lf 9 | *.gyp text eol=lf 10 | *.gypi text eol=lf 11 | *.h text eol=lf 12 | *.m text eol=lf 13 | *.md text eol=lf 14 | *.mm text eol=lf 15 | *.plist text eol=lf 16 | *.py text eol=lf 17 | .clang-format text eol=lf 18 | .gitattributes text eol=lf 19 | .gitignore text eol=lf 20 | /AUTHORS text eol=lf 21 | /LICENSE text eol=lf 22 | /codereview.settings text eol=lf 23 | README.chromium text eol=lf 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Copyright 2012 The Chromium Authors 2 | # Use of this source code is governed by a BSD-style license that can be 3 | # found in the LICENSE file. 4 | 5 | *.Makefile 6 | *.ninja 7 | *.pyc 8 | *.target.mk 9 | *.xcodeproj 10 | *~ 11 | .*.sw? 12 | .DS_Store 13 | .gdb_history 14 | .gdbinit 15 | /Makefile 16 | /out 17 | /xcodebuild 18 | -------------------------------------------------------------------------------- /.style.yapf: -------------------------------------------------------------------------------- 1 | # Copyright 2022 The Chromium Authors 2 | # Use of this source code is governed by a BSD-style license that can be 3 | # found in the LICENSE file. 4 | 5 | [style] 6 | based_on_style = google 7 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | # Copyright 2012 The Chromium Authors 2 | # Use of this source code is governed by a BSD-style license that can be 3 | # found in the LICENSE file. 4 | 5 | # See https://chromium.googlesource.com/chromium/src/+/main/AUTHORS 6 | -------------------------------------------------------------------------------- /BUILD.gn: -------------------------------------------------------------------------------- 1 | # Copyright 2016 The Chromium Authors 2 | # Use of this source code is governed by a BSD-style license that can be 3 | # found in the LICENSE file. 4 | 5 | group("mini_chromium") { 6 | deps = [ "//base" ] 7 | } 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | // Copyright 2006-2008 The Chromium Authors 2 | // 3 | // Redistribution and use in source and binary forms, with or without 4 | // modification, are permitted provided that the following conditions are 5 | // met: 6 | // 7 | // * Redistributions of source code must retain the above copyright 8 | // notice, this list of conditions and the following disclaimer. 9 | // * Redistributions in binary form must reproduce the above 10 | // copyright notice, this list of conditions and the following disclaimer 11 | // in the documentation and/or other materials provided with the 12 | // distribution. 13 | // * Neither the name of Google Inc. nor the names of its 14 | // contributors may be used to endorse or promote products derived from 15 | // this software without specific prior written permission. 16 | // 17 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 18 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 19 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 20 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 21 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 22 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 23 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 27 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 | -------------------------------------------------------------------------------- /OWNERS: -------------------------------------------------------------------------------- 1 | # Copyright 2025 The Chromium Authors 2 | # Use of this source code is governed by a BSD-style license that can be 3 | # found in the LICENSE file. 4 | 5 | set noparent 6 | 7 | jperaza@chromium.org 8 | justincohen@chromium.org 9 | lgrey@chromium.org 10 | mark@chromium.org 11 | pbos@chromium.org 12 | wfh@chromium.org 13 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 6 | 7 | # mini_chromium 8 | 9 | This is mini_chromium, a small collection of useful low-level (“base”) routines 10 | from the [Chromium open-source project](https://dev.chromium.org/Home). Chromium 11 | is large, sprawling, full of dependencies, and a web browser. mini_chromium is 12 | small, self-contained, and a library. mini_chromium is especially useful as a 13 | dependency of other code that wishes to use Chromium’s base routines. By using 14 | mini_chromium, other projects’ code can function in a standalone environment 15 | outside of Chromium without having to treat all of Chromium as a dependency. 16 | When building as part of Chromium, those projects’ code can use Chromium’s own 17 | (non-mini_chromium) base implementation. 18 | 19 | Code provided in mini_chromium provides the same interface as the equivalent 20 | code in Chromium. 21 | 22 | While it’s a goal of mini_chromium to maintain interface compatibility with 23 | Chromium’s base library for the interfaces it does implement, there’s no 24 | requirement that it use the same implementations as Chromium’s base library. 25 | Many of the implementations used in mini_chromium are identical to Chromium’s, 26 | but many others have been modified to eliminate dependencies that are not 27 | desired in mini_chromium, and a few are completely distinct from Chromium’s 28 | altogether. Additionally, when mini_chromium provides an interface in the form 29 | of a file or class present in Chromium, it’s not bound to provide all functions, 30 | methods, or types that the Chromium equivalent does. The differences noted above 31 | notwithstanding, the interfaces exposed by mini_chromium’s base are and must 32 | remain a strict subset of Chromium’s. 33 | 34 | [Crashpad](https://crashpad.chromium.org/) is the chief consumer of 35 | mini_chromium. 36 | 37 | Mark Mentovai
38 | mark@chromium.org 39 | -------------------------------------------------------------------------------- /base/BUILD.gn: -------------------------------------------------------------------------------- 1 | # Copyright 2016 The Chromium Authors 2 | # Use of this source code is governed by a BSD-style license that can be 3 | # found in the LICENSE file. 4 | 5 | import("../build/platform.gni") 6 | 7 | static_library("base") { 8 | sources = [ 9 | "atomicops.h", 10 | "atomicops_internals_atomicword_compat.h", 11 | "atomicops_internals_portable.h", 12 | "auto_reset.h", 13 | "bit_cast.h", 14 | "check.h", 15 | "check_op.h", 16 | "compiler_specific.h", 17 | "containers/checked_iterators.h", 18 | "containers/dynamic_extent.h", 19 | "containers/span.h", 20 | "containers/util.h", 21 | "debug/alias.cc", 22 | "debug/alias.h", 23 | "files/file_path.cc", 24 | "files/file_path.h", 25 | "files/file_util.h", 26 | "files/scoped_file.cc", 27 | "files/scoped_file.h", 28 | "format_macros.h", 29 | "immediate_crash.h", 30 | "logging.cc", 31 | "logging.h", 32 | "memory/free_deleter.h", 33 | "memory/page_size.h", 34 | "memory/raw_ptr_exclusion.h", 35 | "memory/scoped_policy.h", 36 | "metrics/histogram_functions.h", 37 | "metrics/histogram_macros.h", 38 | "metrics/persistent_histogram_allocator.h", 39 | "notreached.h", 40 | "numerics/basic_ops_impl.h", 41 | "numerics/byte_conversions.h", 42 | "numerics/checked_math.h", 43 | "numerics/checked_math_impl.h", 44 | "numerics/clamped_math.h", 45 | "numerics/clamped_math_impl.h", 46 | "numerics/safe_conversions.h", 47 | "numerics/safe_conversions_arm_impl.h", 48 | "numerics/safe_conversions_impl.h", 49 | "numerics/safe_math.h", 50 | "numerics/safe_math_arm_impl.h", 51 | "numerics/safe_math_clang_gcc_impl.h", 52 | "numerics/safe_math_shared_impl.h", 53 | "process/memory.cc", 54 | "process/memory.h", 55 | "rand_util.cc", 56 | "rand_util.h", 57 | "scoped_clear_last_error.h", 58 | "scoped_generic.h", 59 | "strings/pattern.cc", 60 | "strings/pattern.h", 61 | "strings/strcat.cc", 62 | "strings/strcat.h", 63 | "strings/strcat_internal.h", 64 | "strings/string_number_conversions.cc", 65 | "strings/string_number_conversions.h", 66 | "strings/string_piece.h", 67 | "strings/string_util.h", 68 | "strings/stringprintf.cc", 69 | "strings/stringprintf.h", 70 | "strings/sys_string_conversions.h", 71 | "strings/utf_string_conversion_utils.cc", 72 | "strings/utf_string_conversion_utils.h", 73 | "strings/utf_string_conversions.cc", 74 | "strings/utf_string_conversions.h", 75 | "synchronization/condition_variable.h", 76 | "synchronization/lock.cc", 77 | "synchronization/lock.h", 78 | "synchronization/lock_impl.h", 79 | "sys_byteorder.h", 80 | "template_util.h", 81 | "third_party/icu/icu_utf.cc", 82 | "third_party/icu/icu_utf.h", 83 | "threading/thread_local_storage.cc", 84 | "threading/thread_local_storage.h", 85 | "types/cxx23_to_underlying.h", 86 | "types/to_address.h", 87 | ] 88 | 89 | if (mini_chromium_is_posix || mini_chromium_is_fuchsia) { 90 | sources += [ 91 | "files/file_util_posix.cc", 92 | "memory/page_size_posix.cc", 93 | "posix/eintr_wrapper.h", 94 | "posix/safe_strerror.cc", 95 | "posix/safe_strerror.h", 96 | "strings/string_util_posix.h", 97 | "synchronization/condition_variable_posix.cc", 98 | "synchronization/lock_impl_posix.cc", 99 | "threading/thread_local_storage_posix.cc", 100 | ] 101 | } 102 | 103 | if (mini_chromium_is_apple) { 104 | sources += [ 105 | "apple/bridging.h", 106 | "apple/foundation_util.h", 107 | "apple/foundation_util.mm", 108 | "apple/mach_logging.cc", 109 | "apple/mach_logging.h", 110 | "apple/scoped_cftyperef.h", 111 | "apple/scoped_mach_port.cc", 112 | "apple/scoped_mach_port.h", 113 | "apple/scoped_mach_vm.cc", 114 | "apple/scoped_mach_vm.h", 115 | "apple/scoped_nsautorelease_pool.h", 116 | "apple/scoped_nsautorelease_pool.mm", 117 | "apple/scoped_typeref.h", 118 | "strings/sys_string_conversions_mac.mm", 119 | ] 120 | frameworks = [ 121 | "CoreFoundation.framework", 122 | "Foundation.framework", 123 | "Security.framework", 124 | ] 125 | } 126 | if (mini_chromium_is_mac) { 127 | sources += [ 128 | "mac/close_nocancel.cc", 129 | "mac/scoped_ioobject.h", 130 | "mac/scoped_launch_data.h", 131 | ] 132 | frameworks += [ 133 | "ApplicationServices.framework", 134 | "IOKit.framework", 135 | ] 136 | } else if (mini_chromium_is_ios) { 137 | frameworks += [ 138 | "CoreGraphics.framework", 139 | "CoreText.framework", 140 | ] 141 | } else if (mini_chromium_is_win) { 142 | sources += [ 143 | "memory/page_size_win.cc", 144 | "scoped_clear_last_error_win.cc", 145 | "strings/string_util_win.cc", 146 | "strings/string_util_win.h", 147 | "synchronization/lock_impl_win.cc", 148 | "threading/thread_local_storage_win.cc", 149 | ] 150 | libs = [ "advapi32.lib" ] 151 | } else if (mini_chromium_is_fuchsia) { 152 | sources += [ 153 | "fuchsia/fuchsia_logging.cc", 154 | "fuchsia/fuchsia_logging.h", 155 | ] 156 | 157 | if (defined(is_fuchsia_tree) && is_fuchsia_tree) { 158 | deps = [ "//zircon/system/ulib/syslog" ] 159 | } else { 160 | deps = [ "//third_party/fuchsia/sdk/$host_os-amd64/pkg/syslog" ] 161 | } 162 | } 163 | 164 | public_configs = [ "../build:mini_chromium_config" ] 165 | 166 | public_deps = [ "../build" ] 167 | 168 | if (mini_chromium_is_apple) { 169 | public_configs += [ "../build/config:apple_enable_arc" ] 170 | } 171 | 172 | if (mini_chromium_is_android) { 173 | libs = [ "log" ] 174 | } 175 | } 176 | -------------------------------------------------------------------------------- /base/apple/foundation_util.h: -------------------------------------------------------------------------------- 1 | // Copyright 2008 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_APPLE_FOUNDATION_UTIL_H_ 6 | #define MINI_CHROMIUM_BASE_APPLE_FOUNDATION_UTIL_H_ 7 | 8 | #include "base/logging.h" 9 | #include "build/build_config.h" 10 | 11 | #if BUILDFLAG(IS_IOS) 12 | #include 13 | #else 14 | #include 15 | #endif 16 | 17 | #if defined(__OBJC__) 18 | #import 19 | #else // defined(__OBJC__) 20 | #include 21 | #endif // defined(__OBJC__) 22 | 23 | namespace base { 24 | namespace apple { 25 | 26 | // CFCast<>() and CFCastStrict<>() cast a basic CFTypeRef to a more 27 | // specific CoreFoundation type. The compatibility of the passed 28 | // object is found by comparing its opaque type against the 29 | // requested type identifier. If the supplied object is not 30 | // compatible with the requested return type, CFCast<>() returns 31 | // NULL and CFCastStrict<>() will DCHECK. Providing a NULL pointer 32 | // to either variant results in NULL being returned without 33 | // triggering any DCHECK. 34 | // 35 | // Example usage: 36 | // CFNumberRef some_number = base::apple::CFCast( 37 | // CFArrayGetValueAtIndex(array, index)); 38 | // 39 | // CFTypeRef hello = CFSTR("hello world"); 40 | // CFStringRef some_string = base::apple::CFCastStrict(hello); 41 | 42 | template 43 | T CFCast(const CFTypeRef& cf_val); 44 | 45 | template 46 | T CFCastStrict(const CFTypeRef& cf_val); 47 | 48 | #define CF_CAST_DECL(TypeCF) \ 49 | template <> \ 50 | TypeCF##Ref CFCast(const CFTypeRef& cf_val); \ 51 | \ 52 | template <> \ 53 | TypeCF##Ref CFCastStrict(const CFTypeRef& cf_val) 54 | 55 | CF_CAST_DECL(CFArray); 56 | CF_CAST_DECL(CFBag); 57 | CF_CAST_DECL(CFBoolean); 58 | CF_CAST_DECL(CFData); 59 | CF_CAST_DECL(CFDate); 60 | CF_CAST_DECL(CFDictionary); 61 | CF_CAST_DECL(CFNull); 62 | CF_CAST_DECL(CFNumber); 63 | CF_CAST_DECL(CFSet); 64 | CF_CAST_DECL(CFString); 65 | CF_CAST_DECL(CFURL); 66 | CF_CAST_DECL(CFUUID); 67 | 68 | CF_CAST_DECL(CGColor); 69 | 70 | CF_CAST_DECL(CTFont); 71 | CF_CAST_DECL(CTRun); 72 | 73 | #undef CF_CAST_DECL 74 | 75 | #if defined(__OBJC__) 76 | 77 | // ObjCCast<>() and ObjCCastStrict<>() cast a basic id to a more 78 | // specific (NSObject-derived) type. The compatibility of the passed 79 | // object is found by checking if it's a kind of the requested type 80 | // identifier. If the supplied object is not compatible with the 81 | // requested return type, ObjCCast<>() returns nil and 82 | // ObjCCastStrict<>() will DCHECK. Providing a nil pointer to either 83 | // variant results in nil being returned without triggering any DCHECK. 84 | // 85 | // The strict variant is useful when retrieving a value from a 86 | // collection which only has values of a specific type, e.g. an 87 | // NSArray of NSStrings. The non-strict variant is useful when 88 | // retrieving values from data that you can't fully control. For 89 | // example, a plist read from disk may be beyond your exclusive 90 | // control, so you'd only want to check that the values you retrieve 91 | // from it are of the expected types, but not crash if they're not. 92 | // 93 | // Example usage: 94 | // NSString* version = base::apple::ObjCCast( 95 | // [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"]); 96 | // 97 | // NSString* str = base::apple::ObjCCastStrict( 98 | // [ns_arr_of_ns_strs objectAtIndex:0]); 99 | template 100 | T* ObjCCast(id objc_val) { 101 | if ([objc_val isKindOfClass:[T class]]) { 102 | return reinterpret_cast(objc_val); 103 | } 104 | return nil; 105 | } 106 | 107 | template 108 | T* ObjCCastStrict(id objc_val) { 109 | T* rv = ObjCCast(objc_val); 110 | DCHECK(objc_val == nil || rv); 111 | return rv; 112 | } 113 | 114 | #endif // defined(__OBJC__) 115 | 116 | } // namespace apple 117 | } // namespace base 118 | 119 | #endif // MINI_CHROMIUM_BASE_APPLE_FOUNDATION_UTIL_H_ 120 | -------------------------------------------------------------------------------- /base/apple/foundation_util.mm: -------------------------------------------------------------------------------- 1 | // Copyright 2008 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/apple/foundation_util.h" 6 | 7 | #include "base/check.h" 8 | 9 | namespace base { 10 | namespace apple { 11 | 12 | #define CF_CAST_DEFN(TypeCF) \ 13 | template <> \ 14 | TypeCF##Ref CFCast(const CFTypeRef& cf_val) { \ 15 | if (cf_val == NULL) { \ 16 | return NULL; \ 17 | } \ 18 | if (CFGetTypeID(cf_val) == TypeCF##GetTypeID()) { \ 19 | return (TypeCF##Ref)(cf_val); \ 20 | } \ 21 | return NULL; \ 22 | } \ 23 | \ 24 | template <> \ 25 | TypeCF##Ref CFCastStrict(const CFTypeRef& cf_val) { \ 26 | TypeCF##Ref rv = CFCast(cf_val); \ 27 | DCHECK(cf_val == NULL || rv); \ 28 | return rv; \ 29 | } 30 | 31 | CF_CAST_DEFN(CFArray) 32 | CF_CAST_DEFN(CFBag) 33 | CF_CAST_DEFN(CFBoolean) 34 | CF_CAST_DEFN(CFData) 35 | CF_CAST_DEFN(CFDate) 36 | CF_CAST_DEFN(CFDictionary) 37 | CF_CAST_DEFN(CFNull) 38 | CF_CAST_DEFN(CFNumber) 39 | CF_CAST_DEFN(CFSet) 40 | CF_CAST_DEFN(CFString) 41 | CF_CAST_DEFN(CFURL) 42 | CF_CAST_DEFN(CFUUID) 43 | 44 | CF_CAST_DEFN(CGColor) 45 | 46 | CF_CAST_DEFN(CTFont) 47 | CF_CAST_DEFN(CTRun) 48 | 49 | #undef CF_CAST_DEFN 50 | 51 | } // namespace apple 52 | } // namespace base 53 | -------------------------------------------------------------------------------- /base/apple/mach_logging.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/apple/mach_logging.h" 6 | 7 | #include 8 | #include 9 | 10 | #include "base/immediate_crash.h" 11 | #include "base/strings/stringprintf.h" 12 | 13 | #if !BUILDFLAG(IS_IOS) 14 | #include 15 | #endif // !BUILDFLAG(IS_IOS) 16 | 17 | namespace { 18 | 19 | std::string FormatMachErrorNumber(mach_error_t mach_err) { 20 | // For the os/kern subsystem, give the error number in decimal as in 21 | // . Otherwise, give it in hexadecimal to make it easier 22 | // to visualize the various bits. See . 23 | if (mach_err >= 0 && mach_err < KERN_RETURN_MAX) { 24 | return base::StringPrintf(" (%d)", mach_err); 25 | } 26 | return base::StringPrintf(" (0x%08x)", mach_err); 27 | } 28 | 29 | } // namespace 30 | 31 | namespace logging { 32 | 33 | MachLogMessage::MachLogMessage(const char* function, 34 | const char* file_path, 35 | int line, 36 | LogSeverity severity, 37 | mach_error_t mach_err) 38 | : LogMessage(function, file_path, line, severity), mach_err_(mach_err) {} 39 | 40 | MachLogMessage::~MachLogMessage() { 41 | AppendError(); 42 | } 43 | 44 | void MachLogMessage::AppendError() { 45 | stream() << ": " << mach_error_string(mach_err_) 46 | << FormatMachErrorNumber(mach_err_); 47 | } 48 | 49 | MachLogMessageFatal::~MachLogMessageFatal() { 50 | AppendError(); 51 | Flush(); 52 | base::ImmediateCrash(); 53 | } 54 | 55 | #if !BUILDFLAG(IS_IOS) 56 | 57 | BootstrapLogMessage::BootstrapLogMessage(const char* function, 58 | const char* file_path, 59 | int line, 60 | LogSeverity severity, 61 | kern_return_t bootstrap_err) 62 | : LogMessage(function, file_path, line, severity), 63 | bootstrap_err_(bootstrap_err) {} 64 | 65 | BootstrapLogMessage::~BootstrapLogMessage() { 66 | AppendError(); 67 | } 68 | 69 | void BootstrapLogMessage::AppendError() { 70 | stream() << ": " << bootstrap_strerror(bootstrap_err_); 71 | 72 | switch (bootstrap_err_) { 73 | case BOOTSTRAP_SUCCESS: 74 | case BOOTSTRAP_NOT_PRIVILEGED: 75 | case BOOTSTRAP_NAME_IN_USE: 76 | case BOOTSTRAP_UNKNOWN_SERVICE: 77 | case BOOTSTRAP_SERVICE_ACTIVE: 78 | case BOOTSTRAP_BAD_COUNT: 79 | case BOOTSTRAP_NO_MEMORY: 80 | case BOOTSTRAP_NO_CHILDREN: { 81 | // Show known bootstrap errors in decimal because that's how they're 82 | // defined in . 83 | stream() << " (" << bootstrap_err_ << ")"; 84 | break; 85 | } 86 | 87 | default: { 88 | // bootstrap_strerror passes unknown errors to mach_error_string, so 89 | // format them as they would be if they were handled by 90 | // MachErrorMessage. 91 | stream() << FormatMachErrorNumber(bootstrap_err_); 92 | break; 93 | } 94 | } 95 | } 96 | 97 | BootstrapLogMessageFatal::~BootstrapLogMessageFatal() { 98 | AppendError(); 99 | Flush(); 100 | base::ImmediateCrash(); 101 | } 102 | 103 | #endif // !BUILDFLAG(IS_IOS) 104 | 105 | } // namespace logging 106 | -------------------------------------------------------------------------------- /base/apple/scoped_cftyperef.h: -------------------------------------------------------------------------------- 1 | // Copyright 2006-2008 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_APPLE_SCOPED_CFTYPEREF_H_ 6 | #define MINI_CHROMIUM_BASE_APPLE_SCOPED_CFTYPEREF_H_ 7 | 8 | #include 9 | 10 | #include "base/apple/scoped_typeref.h" 11 | 12 | namespace base { 13 | namespace apple { 14 | 15 | namespace internal { 16 | 17 | template 18 | struct ScopedCFTypeRefTraits { 19 | static CFT InvalidValue() { return nullptr; } 20 | static CFT Retain(CFT object) { 21 | CFRetain(object); 22 | return object; 23 | } 24 | static void Release(CFT object) { CFRelease(object); } 25 | }; 26 | 27 | } // namespace internal 28 | 29 | template 30 | using ScopedCFTypeRef = 31 | ScopedTypeRef>; 32 | 33 | } // namespace apple 34 | } // namespace base 35 | 36 | #endif // MINI_CHROMIUM_BASE_APPLE_SCOPED_CFTYPEREF_H_ 37 | -------------------------------------------------------------------------------- /base/apple/scoped_mach_port.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/apple/scoped_mach_port.h" 6 | 7 | #include "base/apple/mach_logging.h" 8 | 9 | namespace base { 10 | namespace apple { 11 | namespace internal { 12 | 13 | void SendRightTraits::Free(mach_port_t port) { 14 | kern_return_t kr = mach_port_deallocate(mach_task_self(), port); 15 | MACH_LOG_IF(ERROR, kr != KERN_SUCCESS, kr) << "mach_port_deallocate"; 16 | } 17 | 18 | void ReceiveRightTraits::Free(mach_port_t port) { 19 | kern_return_t kr = 20 | mach_port_mod_refs(mach_task_self(), port, MACH_PORT_RIGHT_RECEIVE, -1); 21 | MACH_LOG_IF(ERROR, kr != KERN_SUCCESS, kr) << "mach_port_mod_refs"; 22 | } 23 | 24 | void PortSetTraits::Free(mach_port_t port) { 25 | kern_return_t kr = 26 | mach_port_mod_refs(mach_task_self(), port, MACH_PORT_RIGHT_PORT_SET, -1); 27 | MACH_LOG_IF(ERROR, kr != KERN_SUCCESS, kr) << "mach_port_mod_refs"; 28 | } 29 | 30 | } // namespace internal 31 | } // namespace apple 32 | } // namespace base 33 | -------------------------------------------------------------------------------- /base/apple/scoped_mach_port.h: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_APPLE_SCOPED_MACH_PORT_H_ 6 | #define MINI_CHROMIUM_BASE_APPLE_SCOPED_MACH_PORT_H_ 7 | 8 | #include 9 | 10 | #include "base/scoped_generic.h" 11 | 12 | namespace base { 13 | namespace apple { 14 | 15 | namespace internal { 16 | 17 | struct SendRightTraits { 18 | static mach_port_t InvalidValue() { return MACH_PORT_NULL; } 19 | static void Free(mach_port_t port); 20 | }; 21 | 22 | struct ReceiveRightTraits { 23 | static mach_port_t InvalidValue() { return MACH_PORT_NULL; } 24 | static void Free(mach_port_t port); 25 | }; 26 | 27 | struct PortSetTraits { 28 | static mach_port_t InvalidValue() { return MACH_PORT_NULL; } 29 | static void Free(mach_port_t port); 30 | }; 31 | 32 | } // namespace internal 33 | 34 | using ScopedMachSendRight = 35 | ScopedGeneric; 36 | using ScopedMachReceiveRight = 37 | ScopedGeneric; 38 | using ScopedMachPortSet = ScopedGeneric; 39 | 40 | } // namespace apple 41 | } // namespace base 42 | 43 | #endif // MINI_CHROMIUM_BASE_APPLE_SCOPED_MACH_PORT_H_ 44 | -------------------------------------------------------------------------------- /base/apple/scoped_mach_vm.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/apple/scoped_mach_vm.h" 6 | 7 | namespace base { 8 | namespace apple { 9 | 10 | void ScopedMachVM::reset(vm_address_t address, vm_size_t size) { 11 | DCHECK(address % PAGE_SIZE == 0); 12 | DCHECK(size % PAGE_SIZE == 0); 13 | 14 | if (size_) { 15 | if (address_ < address) { 16 | vm_deallocate( 17 | mach_task_self(), address_, std::min(size_, address - address_)); 18 | } 19 | if (address_ + size_ > address + size) { 20 | vm_address_t deallocate_start = std::max(address_, address + size); 21 | vm_deallocate(mach_task_self(), 22 | deallocate_start, 23 | address_ + size_ - deallocate_start); 24 | } 25 | } 26 | 27 | address_ = address; 28 | size_ = size; 29 | } 30 | 31 | } // namespace apple 32 | } // namespace base 33 | -------------------------------------------------------------------------------- /base/apple/scoped_mach_vm.h: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_APPLE_SCOPED_MACH_VM_H_ 6 | #define MINI_CHROMIUM_BASE_APPLE_SCOPED_MACH_VM_H_ 7 | 8 | #include 9 | 10 | #include 11 | 12 | #include "base/check.h" 13 | 14 | // Use ScopedMachVM to supervise ownership of pages in the current process 15 | // through the Mach VM subsystem. Pages allocated with vm_allocate can be 16 | // released when exiting a scope with ScopedMachVM. 17 | // 18 | // The Mach VM subsystem operates on a page-by-page basis, and a single VM 19 | // allocation managed by a ScopedMachVM object may span multiple pages. As far 20 | // as Mach is concerned, allocated pages may be deallocated individually. This 21 | // is in contrast to higher-level allocators such as malloc, where the base 22 | // address of an allocation implies the size of an allocated block. 23 | // Consequently, it is not sufficient to just pass the base address of an 24 | // allocation to ScopedMachVM, it also needs to know the size of the 25 | // allocation. To avoid any confusion, both the base address and size must 26 | // be page-aligned. 27 | // 28 | // When dealing with Mach VM, base addresses will naturally be page-aligned, 29 | // but user-specified sizes may not be. If there's a concern that a size is 30 | // not page-aligned, use the mach_vm_round_page macro to correct it. 31 | // 32 | // Example: 33 | // 34 | // vm_address_t address = 0; 35 | // vm_size_t size = 12345; // This requested size is not page-aligned. 36 | // kern_return_t kr = 37 | // vm_allocate(mach_task_self(), &address, size, VM_FLAGS_ANYWHERE); 38 | // if (kr != KERN_SUCCESS) { 39 | // return false; 40 | // } 41 | // ScopedMachVM vm_owner(address, mach_vm_round_page(size)); 42 | 43 | namespace base { 44 | namespace apple { 45 | 46 | class ScopedMachVM { 47 | public: 48 | explicit ScopedMachVM(vm_address_t address = 0, vm_size_t size = 0) 49 | : address_(address), size_(size) { 50 | DCHECK(address % PAGE_SIZE == 0); 51 | DCHECK(size % PAGE_SIZE == 0); 52 | } 53 | 54 | ScopedMachVM(const ScopedMachVM&) = delete; 55 | ScopedMachVM& operator=(const ScopedMachVM&) = delete; 56 | 57 | ~ScopedMachVM() { 58 | if (size_) { 59 | vm_deallocate(mach_task_self(), address_, size_); 60 | } 61 | } 62 | 63 | void reset(vm_address_t address = 0, vm_size_t size = 0); 64 | 65 | vm_address_t address() const { return address_; } 66 | 67 | vm_size_t size() const { return size_; } 68 | 69 | void swap(ScopedMachVM& that) { 70 | std::swap(address_, that.address_); 71 | std::swap(size_, that.size_); 72 | } 73 | 74 | void release() { 75 | address_ = 0; 76 | size_ = 0; 77 | } 78 | 79 | private: 80 | vm_address_t address_; 81 | vm_size_t size_; 82 | }; 83 | 84 | } // namespace apple 85 | } // namespace base 86 | 87 | #endif // MINI_CHROMIUM_BASE_APPLE_SCOPED_MACH_VM_H_ 88 | -------------------------------------------------------------------------------- /base/apple/scoped_nsautorelease_pool.h: -------------------------------------------------------------------------------- 1 | // Copyright 2008 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_APPLE_SCOPED_NSAUTORELEASE_POOL_H_ 6 | #define MINI_CHROMIUM_BASE_APPLE_SCOPED_NSAUTORELEASE_POOL_H_ 7 | 8 | #include "build/build_config.h" 9 | 10 | namespace base { 11 | namespace apple { 12 | 13 | // On the Mac, ScopedNSAutoreleasePool creates an autorelease pool when 14 | // instantiated and pops it when destroyed. This allows an autorelease pool to 15 | // be maintained in ordinary C++ code without bringing in any direct Objective-C 16 | // dependency. 17 | // 18 | // On other platforms, ScopedNSAutoreleasePool is an empty object with no 19 | // effects. This allows it to be used directly in cross-platform code without 20 | // ugly #ifdefs. 21 | class ScopedNSAutoreleasePool { 22 | public: 23 | #if !BUILDFLAG(IS_APPLE) 24 | ScopedNSAutoreleasePool() {} 25 | void Recycle() {} 26 | #else // BUILDFLAG(IS_APPLE) 27 | ScopedNSAutoreleasePool(); 28 | 29 | ScopedNSAutoreleasePool(const ScopedNSAutoreleasePool&) = delete; 30 | ScopedNSAutoreleasePool& operator=(const ScopedNSAutoreleasePool&) = delete; 31 | 32 | ~ScopedNSAutoreleasePool(); 33 | 34 | // Clear out the pool in case its position on the stack causes it to be 35 | // alive for long periods of time (such as the entire length of the app). 36 | // Only use then when you're certain the items currently in the pool are 37 | // no longer needed. 38 | void Recycle(); 39 | 40 | private: 41 | void* autorelease_pool_; 42 | #endif // BUILDFLAG(IS_APPLE) 43 | }; 44 | 45 | } // namespace apple 46 | } // namespace base 47 | 48 | #endif // MINI_CHROMIUM_BASE_APPLE_SCOPED_NSAUTORELEASE_POOL_H_ 49 | -------------------------------------------------------------------------------- /base/apple/scoped_nsautorelease_pool.mm: -------------------------------------------------------------------------------- 1 | // Copyright 2008 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/apple/scoped_nsautorelease_pool.h" 6 | 7 | #include "base/logging.h" 8 | 9 | // Note that this uses the direct runtime interface to the autorelease pool. 10 | // https://clang.llvm.org/docs/AutomaticReferenceCounting.html#runtime-support 11 | // This is so this can work when compiled for ARC. 12 | 13 | extern "C" { 14 | void* objc_autoreleasePoolPush(void); 15 | void objc_autoreleasePoolPop(void* pool); 16 | } 17 | 18 | namespace base { 19 | namespace apple { 20 | 21 | ScopedNSAutoreleasePool::ScopedNSAutoreleasePool() 22 | : autorelease_pool_(objc_autoreleasePoolPush()) {} 23 | 24 | ScopedNSAutoreleasePool::~ScopedNSAutoreleasePool() { 25 | objc_autoreleasePoolPop(autorelease_pool_); 26 | } 27 | 28 | // Cycle the internal pool, allowing everything there to get cleaned up and 29 | // start anew. 30 | void ScopedNSAutoreleasePool::Recycle() { 31 | objc_autoreleasePoolPop(autorelease_pool_); 32 | autorelease_pool_ = objc_autoreleasePoolPush(); 33 | } 34 | 35 | } // namespace apple 36 | } // namespace base 37 | -------------------------------------------------------------------------------- /base/apple/scoped_typeref.h: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_APPLE_SCOPED_TYPEREF_H_ 6 | #define MINI_CHROMIUM_BASE_APPLE_SCOPED_TYPEREF_H_ 7 | 8 | #include "base/check.h" 9 | #include "base/memory/scoped_policy.h" 10 | 11 | namespace base { 12 | namespace apple { 13 | 14 | template 15 | struct ScopedTypeRefTraits; 16 | 17 | template > 18 | class ScopedTypeRef { 19 | public: 20 | using element_type = T; 21 | 22 | // Construction from underlying type 23 | 24 | explicit constexpr ScopedTypeRef( 25 | element_type object = Traits::InvalidValue(), 26 | base::scoped_policy::OwnershipPolicy policy = base::scoped_policy::ASSUME) 27 | : object_(object) { 28 | if (object_ != Traits::InvalidValue() && 29 | policy == base::scoped_policy::RETAIN) { 30 | object_ = Traits::Retain(object_); 31 | } 32 | } 33 | 34 | // Copy construction 35 | 36 | ScopedTypeRef(const ScopedTypeRef& that) : object_(that.get()) { 37 | if (object_ != Traits::InvalidValue()) { 38 | object_ = Traits::Retain(object_); 39 | } 40 | } 41 | 42 | template 43 | ScopedTypeRef(const ScopedTypeRef& that) : object_(that.get()) { 44 | if (object_ != Traits::InvalidValue()) { 45 | object_ = Traits::Retain(object_); 46 | } 47 | } 48 | 49 | // Copy assignment 50 | 51 | ScopedTypeRef& operator=(const ScopedTypeRef& that) { 52 | reset(that.get(), base::scoped_policy::RETAIN); 53 | return *this; 54 | } 55 | 56 | template 57 | ScopedTypeRef& operator=(const ScopedTypeRef& that) { 58 | reset(that.get(), base::scoped_policy::RETAIN); 59 | return *this; 60 | } 61 | 62 | // Move construction 63 | 64 | ScopedTypeRef(ScopedTypeRef&& that) : object_(that.release()) {} 65 | 66 | template 67 | ScopedTypeRef(ScopedTypeRef&& that) : object_(that.release()) {} 68 | 69 | // Move assignment 70 | 71 | ScopedTypeRef& operator=(ScopedTypeRef&& that) { 72 | reset(that.release(), base::scoped_policy::ASSUME); 73 | return *this; 74 | } 75 | 76 | template 77 | ScopedTypeRef& operator=(ScopedTypeRef&& that) { 78 | reset(that.release(), base::scoped_policy::ASSUME); 79 | return *this; 80 | } 81 | 82 | // Resetting 83 | 84 | template 85 | void reset(const ScopedTypeRef& that) { 86 | reset(that.get(), base::scoped_policy::RETAIN); 87 | } 88 | 89 | void reset(element_type object = Traits::InvalidValue(), 90 | base::scoped_policy::OwnershipPolicy policy = 91 | base::scoped_policy::ASSUME) { 92 | if (object != Traits::InvalidValue() && 93 | policy == base::scoped_policy::RETAIN) { 94 | object = Traits::Retain(object); 95 | } 96 | if (object_ != Traits::InvalidValue()) { 97 | Traits::Release(object_); 98 | } 99 | object_ = object; 100 | } 101 | 102 | // Destruction 103 | 104 | ~ScopedTypeRef() { 105 | if (object_ != Traits::InvalidValue()) { 106 | Traits::Release(object_); 107 | } 108 | } 109 | 110 | [[nodiscard]] element_type* InitializeInto() { 111 | CHECK_EQ(object_, Traits::InvalidValue()); 112 | return &object_; 113 | } 114 | 115 | bool operator==(const ScopedTypeRef& that) const { 116 | return object_ == that.object_; 117 | } 118 | bool operator!=(const ScopedTypeRef& that) const { 119 | return object_ != that.object_; 120 | } 121 | explicit operator bool() const { return object_ != Traits::InvalidValue(); } 122 | 123 | element_type get() const { return object_; } 124 | 125 | void swap(ScopedTypeRef& that) { 126 | element_type temp = that.object_; 127 | that.object_ = object_; 128 | object_ = temp; 129 | } 130 | 131 | [[nodiscard]] element_type release() { 132 | element_type temp = object_; 133 | object_ = Traits::InvalidValue(); 134 | return temp; 135 | } 136 | 137 | private: 138 | element_type object_; 139 | }; 140 | 141 | } // namespace apple 142 | } // namespace base 143 | 144 | #endif // MINI_CHROMIUM_BASE_APPLE_SCOPED_TYPEREF_H_ 145 | -------------------------------------------------------------------------------- /base/atomicops_internals_atomicword_compat.h: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | // This file is an internal atomic implementation, use base/atomicops.h instead. 6 | 7 | #ifndef MINI_CHROMIUM_BASE_ATOMICOPS_INTERNALS_ATOMICWORD_COMPAT_H_ 8 | #define MINI_CHROMIUM_BASE_ATOMICOPS_INTERNALS_ATOMICWORD_COMPAT_H_ 9 | 10 | // AtomicWord is a synonym for intptr_t, and Atomic32 is a synonym for int32, 11 | // which in turn means int. On some LP32 platforms, intptr_t is an int, but 12 | // on others, it's a long. When AtomicWord and Atomic32 are based on different 13 | // fundamental types, their pointers are incompatible. 14 | // 15 | // This file defines function overloads to allow both AtomicWord and Atomic32 16 | // data to be used with this interface. 17 | // 18 | // On LP64 platforms, AtomicWord and Atomic64 are both always long, 19 | // so this problem doesn't occur. 20 | 21 | #if !defined(ARCH_CPU_64_BITS) 22 | 23 | namespace base { 24 | namespace subtle { 25 | 26 | inline AtomicWord NoBarrier_CompareAndSwap(volatile AtomicWord* ptr, 27 | AtomicWord old_value, 28 | AtomicWord new_value) { 29 | return NoBarrier_CompareAndSwap( 30 | reinterpret_cast(ptr), old_value, new_value); 31 | } 32 | 33 | inline AtomicWord NoBarrier_AtomicExchange(volatile AtomicWord* ptr, 34 | AtomicWord new_value) { 35 | return NoBarrier_AtomicExchange( 36 | reinterpret_cast(ptr), new_value); 37 | } 38 | 39 | inline AtomicWord NoBarrier_AtomicIncrement(volatile AtomicWord* ptr, 40 | AtomicWord increment) { 41 | return NoBarrier_AtomicIncrement( 42 | reinterpret_cast(ptr), increment); 43 | } 44 | 45 | inline AtomicWord Barrier_AtomicIncrement(volatile AtomicWord* ptr, 46 | AtomicWord increment) { 47 | return Barrier_AtomicIncrement( 48 | reinterpret_cast(ptr), increment); 49 | } 50 | 51 | inline AtomicWord Acquire_CompareAndSwap(volatile AtomicWord* ptr, 52 | AtomicWord old_value, 53 | AtomicWord new_value) { 54 | return base::subtle::Acquire_CompareAndSwap( 55 | reinterpret_cast(ptr), old_value, new_value); 56 | } 57 | 58 | inline AtomicWord Release_CompareAndSwap(volatile AtomicWord* ptr, 59 | AtomicWord old_value, 60 | AtomicWord new_value) { 61 | return base::subtle::Release_CompareAndSwap( 62 | reinterpret_cast(ptr), old_value, new_value); 63 | } 64 | 65 | inline void NoBarrier_Store(volatile AtomicWord *ptr, AtomicWord value) { 66 | NoBarrier_Store( 67 | reinterpret_cast(ptr), value); 68 | } 69 | 70 | inline void Acquire_Store(volatile AtomicWord* ptr, AtomicWord value) { 71 | return base::subtle::Acquire_Store( 72 | reinterpret_cast(ptr), value); 73 | } 74 | 75 | inline void Release_Store(volatile AtomicWord* ptr, AtomicWord value) { 76 | return base::subtle::Release_Store( 77 | reinterpret_cast(ptr), value); 78 | } 79 | 80 | inline AtomicWord NoBarrier_Load(volatile const AtomicWord *ptr) { 81 | return NoBarrier_Load( 82 | reinterpret_cast(ptr)); 83 | } 84 | 85 | inline AtomicWord Acquire_Load(volatile const AtomicWord* ptr) { 86 | return base::subtle::Acquire_Load( 87 | reinterpret_cast(ptr)); 88 | } 89 | 90 | inline AtomicWord Release_Load(volatile const AtomicWord* ptr) { 91 | return base::subtle::Release_Load( 92 | reinterpret_cast(ptr)); 93 | } 94 | 95 | } // namespace base::subtle 96 | } // namespace base 97 | 98 | #endif // !defined(ARCH_CPU_64_BITS) 99 | 100 | #endif // MINI_CHROMIUM_BASE_ATOMICOPS_INTERNALS_ATOMICWORD_COMPAT_H_ 101 | -------------------------------------------------------------------------------- /base/auto_reset.h: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_AUTO_RESET_H_ 6 | #define MINI_CHROMIUM_BASE_AUTO_RESET_H_ 7 | 8 | namespace base { 9 | 10 | template 11 | class AutoReset { 12 | public: 13 | AutoReset(T* scoped_variable, T new_value) 14 | : scoped_variable_(scoped_variable), 15 | original_value_(*scoped_variable) { 16 | *scoped_variable_ = new_value; 17 | } 18 | 19 | AutoReset(const AutoReset&) = delete; 20 | AutoReset& operator=(const AutoReset&) = delete; 21 | 22 | ~AutoReset() { *scoped_variable_ = original_value_; } 23 | 24 | private: 25 | T* scoped_variable_; 26 | T original_value_; 27 | }; 28 | 29 | } // namespace base 30 | 31 | #endif // MINI_CHROMIUM_BASE_AUTO_RESET_H_ 32 | -------------------------------------------------------------------------------- /base/bit_cast.h: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_BIT_CAST_H_ 6 | #define MINI_CHROMIUM_BASE_BIT_CAST_H_ 7 | 8 | #include 9 | 10 | namespace base { 11 | 12 | // This is an equivalent to C++20's std::bit_cast<>(), but with additional 13 | // warnings. It morally does what `*reinterpret_cast(&source)` does, but 14 | // the cast/deref pair is undefined behavior, while bit_cast<>() isn't. 15 | // 16 | // This is not a magic "get out of UB free" card. This must only be used on 17 | // values, not on references or pointers. For pointers, use 18 | // reinterpret_cast<>(), and then look at https://eel.is/c++draft/basic.lval#11 19 | // as that's probably UB also. 20 | 21 | template 22 | constexpr Dest bit_cast(const Source& source) { 23 | static_assert(!std::is_pointer_v, 24 | "bit_cast must not be used on pointer types"); 25 | static_assert(!std::is_pointer_v, 26 | "bit_cast must not be used on pointer types"); 27 | static_assert(!std::is_reference_v, 28 | "bit_cast must not be used on reference types"); 29 | static_assert(!std::is_reference_v, 30 | "bit_cast must not be used on reference types"); 31 | static_assert( 32 | sizeof(Dest) == sizeof(Source), 33 | "bit_cast requires source and destination types to be the same size"); 34 | static_assert(std::is_trivially_copyable_v, 35 | "bit_cast requires the source type to be trivially copyable"); 36 | static_assert( 37 | std::is_trivially_copyable_v, 38 | "bit_cast requires the destination type to be trivially copyable"); 39 | 40 | return __builtin_bit_cast(Dest, source); 41 | } 42 | 43 | } // namespace base 44 | 45 | #endif // MINI_CHROMIUM_BASE_BIT_CAST_H_ 46 | -------------------------------------------------------------------------------- /base/check.h: -------------------------------------------------------------------------------- 1 | // Copyright 2020 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_CHECK_H_ 6 | #define MINI_CHROMIUM_BASE_CHECK_H_ 7 | 8 | #include "base/logging.h" 9 | 10 | #define CHECK(condition) \ 11 | LAZY_STREAM(LOG_STREAM(FATAL), !(condition)) \ 12 | << "Check failed: " # condition << ". " 13 | 14 | #define PCHECK(condition) \ 15 | LAZY_STREAM(PLOG_STREAM(FATAL), !(condition)) \ 16 | << "Check failed: " # condition << ". " 17 | 18 | #define DCHECK(condition) \ 19 | LAZY_STREAM(LOG_STREAM(FATAL), DCHECK_IS_ON() ? !(condition) : false) \ 20 | << "Check failed: " # condition << ". " 21 | 22 | #define DPCHECK(condition) \ 23 | LAZY_STREAM(PLOG_STREAM(FATAL), DCHECK_IS_ON() ? !(condition) : false) \ 24 | << "Check failed: " # condition << ". " 25 | 26 | #endif // MINI_CHROMIUM_BASE_CHECK_H_ 27 | -------------------------------------------------------------------------------- /base/check_op.h: -------------------------------------------------------------------------------- 1 | // Copyright 2020 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_CHECK_OP_H_ 6 | #define MINI_CHROMIUM_BASE_CHECK_OP_H_ 7 | 8 | #include "base/check.h" 9 | #include "base/logging.h" 10 | 11 | namespace logging { 12 | 13 | template 14 | std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) { 15 | std::ostringstream ss; 16 | ss << names << " (" << v1 << " vs. " << v2 << ")"; 17 | std::string* msg = new std::string(ss.str()); 18 | return msg; 19 | } 20 | 21 | #define DEFINE_CHECK_OP_IMPL(name, op) \ 22 | template \ 23 | inline std::string* Check ## name ## Impl(const t1& v1, const t2& v2, \ 24 | const char* names) { \ 25 | if (v1 op v2) { \ 26 | return NULL; \ 27 | } else { \ 28 | return MakeCheckOpString(v1, v2, names); \ 29 | } \ 30 | } \ 31 | inline std::string* Check ## name ## Impl(int v1, int v2, \ 32 | const char* names) { \ 33 | if (v1 op v2) { \ 34 | return NULL; \ 35 | } else { \ 36 | return MakeCheckOpString(v1, v2, names); \ 37 | } \ 38 | } 39 | 40 | DEFINE_CHECK_OP_IMPL(EQ, ==) 41 | DEFINE_CHECK_OP_IMPL(NE, !=) 42 | DEFINE_CHECK_OP_IMPL(LE, <=) 43 | DEFINE_CHECK_OP_IMPL(LT, <) 44 | DEFINE_CHECK_OP_IMPL(GE, >=) 45 | DEFINE_CHECK_OP_IMPL(GT, >) 46 | 47 | #undef DEFINE_CHECK_OP_IMPL 48 | 49 | } // namespace logging 50 | 51 | #define CHECK_OP(name, op, val1, val2) \ 52 | if (std::string* _result = \ 53 | logging::Check ## name ## Impl((val1), (val2), \ 54 | # val1 " " # op " " # val2)) \ 55 | logging::LogMessage(FUNCTION_SIGNATURE, __FILE__, __LINE__, \ 56 | _result).stream() 57 | 58 | #define CHECK_EQ(val1, val2) CHECK_OP(EQ, ==, val1, val2) 59 | #define CHECK_NE(val1, val2) CHECK_OP(NE, !=, val1, val2) 60 | #define CHECK_LE(val1, val2) CHECK_OP(LE, <=, val1, val2) 61 | #define CHECK_LT(val1, val2) CHECK_OP(LT, <, val1, val2) 62 | #define CHECK_GE(val1, val2) CHECK_OP(GE, >=, val1, val2) 63 | #define CHECK_GT(val1, val2) CHECK_OP(GT, >, val1, val2) 64 | 65 | 66 | #define DCHECK_OP(name, op, val1, val2) \ 67 | if (DCHECK_IS_ON()) \ 68 | if (std::string* _result = \ 69 | logging::Check ## name ## Impl((val1), (val2), \ 70 | # val1 " " # op " " # val2)) \ 71 | logging::LogMessage(FUNCTION_SIGNATURE, __FILE__, __LINE__, \ 72 | _result).stream() 73 | 74 | #define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2) 75 | #define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2) 76 | #define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2) 77 | #define DCHECK_LT(val1, val2) DCHECK_OP(LT, <, val1, val2) 78 | #define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2) 79 | #define DCHECK_GT(val1, val2) DCHECK_OP(GT, >, val1, val2) 80 | 81 | #endif // MINI_CHROMIUM_BASE_CHECK_OP_H_ 82 | -------------------------------------------------------------------------------- /base/containers/dynamic_extent.h: -------------------------------------------------------------------------------- 1 | // Copyright 2024 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_CONTAINERS_DYNAMIC_EXTENT_H_ 6 | #define MINI_CHROMIUM_BASE_CONTAINERS_DYNAMIC_EXTENT_H_ 7 | 8 | #include 9 | #include 10 | 11 | namespace base { 12 | 13 | // [views.constants] 14 | inline constexpr size_t dynamic_extent = std::numeric_limits::max(); 15 | 16 | } // namespace base 17 | 18 | #endif // MINI_CHROMIUM_BASE_CONTAINERS_DYNAMIC_EXTENT_H_ 19 | -------------------------------------------------------------------------------- /base/containers/util.h: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_CONTAINERS_UTIL_H_ 6 | #define MINI_CHROMIUM_BASE_CONTAINERS_UTIL_H_ 7 | 8 | #include 9 | 10 | namespace base { 11 | 12 | // TODO(crbug.com/817982): What we really need is for checked_math.h to be 13 | // able to do checked arithmetic on pointers. 14 | template 15 | inline uintptr_t get_uintptr(const T* t) { 16 | return reinterpret_cast(t); 17 | } 18 | 19 | } // namespace base 20 | 21 | #endif // MINI_CHROMIUM_BASE_CONTAINERS_UTIL_H_ 22 | -------------------------------------------------------------------------------- /base/cxx17_backports.h: -------------------------------------------------------------------------------- 1 | // Copyright 2006-2008 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_CXX17_BACKPORTS_H_ 6 | #define MINI_CHROMIUM_BASE_CXX17_BACKPORTS_H_ 7 | 8 | #include 9 | 10 | namespace base { 11 | 12 | template 13 | constexpr size_t size(const T (&array)[N]) noexcept { 14 | return N; 15 | } 16 | 17 | } // namespace base 18 | 19 | #endif // MINI_CHROMIUM_BASE_CXX17_BACKPORTS_H_ 20 | -------------------------------------------------------------------------------- /base/debug/alias.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/debug/alias.h" 6 | 7 | #include "build/build_config.h" 8 | 9 | namespace base { 10 | namespace debug { 11 | 12 | #if defined(COMPILER_MSVC) 13 | #pragma optimize("", off) 14 | #endif 15 | 16 | void Alias(const void* var) { 17 | } 18 | 19 | #if defined(COMPILER_MSVC) 20 | #pragma optimize("", on) 21 | #endif 22 | 23 | } // namespace debug 24 | } // namespace base 25 | -------------------------------------------------------------------------------- /base/debug/alias.h: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_DEBUG_ALIAS_H_ 6 | #define MINI_CHROMIUM_BASE_DEBUG_ALIAS_H_ 7 | 8 | namespace base { 9 | namespace debug { 10 | 11 | // Make the optimizer think that var is aliased. This is to prevent it from 12 | // optimizing out variables that that would not otherwise be live at the point 13 | // of a potential crash. 14 | void Alias(const void* var); 15 | 16 | } // namespace debug 17 | } // namespace base 18 | 19 | #endif // MINI_CHROMIUM_BASE_DEBUG_ALIAS_H_ 20 | -------------------------------------------------------------------------------- /base/files/file_util.h: -------------------------------------------------------------------------------- 1 | // Copyright 2006-2008 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_FILES_FILE_UTIL_H_ 6 | #define MINI_CHROMIUM_BASE_FILES_FILE_UTIL_H_ 7 | 8 | #include "build/build_config.h" 9 | 10 | #if BUILDFLAG(IS_POSIX) 11 | 12 | #include 13 | 14 | namespace base { 15 | 16 | bool ReadFromFD(int fd, char* buffer, size_t bytes); 17 | 18 | } // namespace base 19 | 20 | #endif // BUILDFLAG(IS_POSIX) 21 | 22 | #endif // MINI_CHROMIUM_BASE_FILES_FILE_UTIL_H_ 23 | -------------------------------------------------------------------------------- /base/files/file_util_posix.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2006-2008 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/files/file_util.h" 6 | 7 | #include 8 | 9 | #include "base/posix/eintr_wrapper.h" 10 | 11 | namespace base { 12 | 13 | bool ReadFromFD(int fd, char* buffer, size_t bytes) { 14 | size_t total_read = 0; 15 | while (total_read < bytes) { 16 | ssize_t bytes_read = 17 | HANDLE_EINTR(read(fd, buffer + total_read, bytes - total_read)); 18 | if (bytes_read <= 0) { 19 | break; 20 | } 21 | total_read += bytes_read; 22 | } 23 | return total_read == bytes; 24 | } 25 | 26 | } // namespace base 27 | -------------------------------------------------------------------------------- /base/files/scoped_file.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/files/scoped_file.h" 6 | 7 | #include 8 | 9 | #include "base/logging.h" 10 | 11 | #if BUILDFLAG(IS_POSIX) 12 | #include 13 | 14 | #include "base/check.h" 15 | #include "base/posix/eintr_wrapper.h" 16 | #endif 17 | 18 | namespace base { 19 | namespace internal { 20 | 21 | #if BUILDFLAG(IS_POSIX) 22 | void ScopedFDCloseTraits::Free(int fd) { 23 | PCHECK(IGNORE_EINTR(close(fd)) == 0); 24 | } 25 | #endif // BUILDFLAG(IS_POSIX) 26 | 27 | void ScopedFILECloser::operator()(FILE* file) const { 28 | if (file) { 29 | if (fclose(file) < 0) { 30 | PLOG(ERROR) << "fclose"; 31 | } 32 | } 33 | } 34 | 35 | } // namespace internal 36 | } // namespace base 37 | -------------------------------------------------------------------------------- /base/files/scoped_file.h: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_FILES_SCOPED_FILE_H_ 6 | #define MINI_CHROMIUM_BASE_FILES_SCOPED_FILE_H_ 7 | 8 | #include 9 | 10 | #include 11 | 12 | #include "base/scoped_generic.h" 13 | #include "build/build_config.h" 14 | 15 | namespace base { 16 | 17 | namespace internal { 18 | 19 | #if BUILDFLAG(IS_POSIX) 20 | struct ScopedFDCloseTraits { 21 | static int InvalidValue() { 22 | return -1; 23 | } 24 | static void Free(int fd); 25 | }; 26 | #endif // BUILDFLAG(IS_POSIX) 27 | 28 | struct ScopedFILECloser { 29 | void operator()(FILE* file) const; 30 | }; 31 | 32 | } // namespace internal 33 | 34 | #if BUILDFLAG(IS_POSIX) 35 | typedef ScopedGeneric ScopedFD; 36 | #endif // BUILDFLAG(IS_POSIX) 37 | typedef std::unique_ptr ScopedFILE; 38 | 39 | } // namespace base 40 | 41 | #endif // MINI_CHROMIUM_BASE_FILES_SCOPED_FILE_H_ 42 | -------------------------------------------------------------------------------- /base/format_macros.h: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef BASE_FORMAT_MACROS_H_ 6 | #define BASE_FORMAT_MACROS_H_ 7 | 8 | // This file defines the format macros for some integer types. 9 | 10 | // To print a 64-bit value in a portable way: 11 | // int64_t value; 12 | // printf("xyz:%" PRId64, value); 13 | // The "d" in the macro corresponds to %d; you can also use PRIu64 etc. 14 | // 15 | // For wide strings, prepend "Wide" to the macro: 16 | // int64_t value; 17 | // StringPrintf(L"xyz: %" WidePRId64, value); 18 | // 19 | // To print a size_t value in a portable way: 20 | // size_t size; 21 | // printf("xyz: %" PRIuS, size); 22 | // The "u" in the macro corresponds to %u, and S is for "size". 23 | 24 | #include "build/build_config.h" 25 | 26 | #if BUILDFLAG(IS_POSIX) && \ 27 | (defined(_INTTYPES_H) || defined(_INTTYPES_H_)) && !defined(PRId64) 28 | #error "inttypes.h has already been included before this header file, but " 29 | #error "without __STDC_FORMAT_MACROS defined." 30 | #endif 31 | 32 | #if BUILDFLAG(IS_POSIX) && !defined(__STDC_FORMAT_MACROS) 33 | #define __STDC_FORMAT_MACROS 34 | #endif 35 | 36 | #include 37 | 38 | #if !defined(PRIuS) 39 | #define PRIuS "zu" 40 | #endif 41 | 42 | // The size of NSInteger and NSUInteger varies between 32-bit and 64-bit 43 | // architectures and Apple does not provides standard format macros and 44 | // recommends casting. This has many drawbacks, so instead define macros 45 | // for formatting those types. 46 | #if BUILDFLAG(IS_APPLE) 47 | #if defined(ARCH_CPU_64_BITS) 48 | #if !defined(PRIdNS) 49 | #define PRIdNS "ld" 50 | #endif 51 | #if !defined(PRIuNS) 52 | #define PRIuNS "lu" 53 | #endif 54 | #if !defined(PRIxNS) 55 | #define PRIxNS "lx" 56 | #endif 57 | #else // defined(ARCH_CPU_64_BITS) 58 | #if !defined(PRIdNS) 59 | #define PRIdNS "d" 60 | #endif 61 | #if !defined(PRIuNS) 62 | #define PRIuNS "u" 63 | #endif 64 | #if !defined(PRIxNS) 65 | #define PRIxNS "x" 66 | #endif 67 | #endif 68 | #endif // BUILDFLAG(IS_APPLE) 69 | 70 | #endif // BASE_FORMAT_MACROS_H_ 71 | -------------------------------------------------------------------------------- /base/fuchsia/fuchsia_logging.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/fuchsia/fuchsia_logging.h" 6 | 7 | #include 8 | 9 | #include 10 | 11 | #include "base/immediate_crash.h" 12 | 13 | namespace logging { 14 | 15 | ZxLogMessage::ZxLogMessage(const char* function, 16 | const char* file_path, 17 | int line, 18 | LogSeverity severity, 19 | zx_status_t zx_err) 20 | : LogMessage(function, file_path, line, severity), zx_err_(zx_err) {} 21 | 22 | ZxLogMessage::~ZxLogMessage() { 23 | AppendError(); 24 | } 25 | 26 | void ZxLogMessage::AppendError() { 27 | // zx_status_t error values are negative, so log the numeric version as 28 | // decimal rather than hex. This is also useful to match zircon/errors.h for 29 | // grepping. 30 | stream() << ": " << zx_status_get_string(zx_err_) << " (" << zx_err_ << ")"; 31 | } 32 | 33 | ZxLogMessageFatal::~ZxLogMessageFatal() { 34 | AppendError(); 35 | Flush(); 36 | base::ImmediateCrash(); 37 | } 38 | 39 | } // namespace logging 40 | -------------------------------------------------------------------------------- /base/fuchsia/fuchsia_logging.h: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_FUCHSIA_FUCHSIA_LOGGING_H_ 6 | #define MINI_CHROMIUM_BASE_FUCHSIA_FUCHSIA_LOGGING_H_ 7 | 8 | #include 9 | 10 | #include "base/logging.h" 11 | 12 | // Use the ZX_LOG family of macros along with a zx_status_t containing a Zircon 13 | // error. The error value will be decoded so that logged messages explain the 14 | // error. 15 | 16 | namespace logging { 17 | 18 | class ZxLogMessage : public logging::LogMessage { 19 | public: 20 | ZxLogMessage(const char* function, 21 | const char* file_path, 22 | int line, 23 | LogSeverity severity, 24 | zx_status_t zx_err); 25 | 26 | ZxLogMessage(const ZxLogMessage&) = delete; 27 | ZxLogMessage& operator=(const ZxLogMessage&) = delete; 28 | 29 | ~ZxLogMessage(); 30 | 31 | protected: 32 | void AppendError(); 33 | 34 | private: 35 | zx_status_t zx_err_; 36 | }; 37 | 38 | class ZxLogMessageFatal final : public ZxLogMessage { 39 | public: 40 | using ZxLogMessage::ZxLogMessage; 41 | [[noreturn]] ~ZxLogMessageFatal() override; 42 | }; 43 | 44 | } // namespace logging 45 | 46 | #define ZX_LOG_STREAM(severity, zx_err) \ 47 | COMPACT_GOOGLE_LOG_EX_##severity(ZxLogMessage, zx_err).stream() 48 | 49 | #define ZX_LOG(severity, zx_err) \ 50 | LAZY_STREAM(ZX_LOG_STREAM(severity, zx_err), LOG_IS_ON(severity)) 51 | #define ZX_LOG_IF(severity, condition, zx_err) \ 52 | LAZY_STREAM(ZX_LOG_STREAM(severity, zx_err), \ 53 | LOG_IS_ON(severity) && (condition)) 54 | 55 | #define ZX_CHECK(condition, zx_err) \ 56 | LAZY_STREAM(ZX_LOG_STREAM(FATAL, zx_err), !(condition)) \ 57 | << "Check failed: " #condition << ". " 58 | 59 | #define ZX_DLOG(severity, zx_err) \ 60 | LAZY_STREAM(ZX_LOG_STREAM(severity, zx_err), DLOG_IS_ON(severity)) 61 | #define ZX_DLOG_IF(severity, condition, zx_err) \ 62 | LAZY_STREAM(ZX_LOG_STREAM(severity, zx_err), \ 63 | DLOG_IS_ON(severity) && (condition)) 64 | 65 | #define ZX_DCHECK(condition, zx_err) \ 66 | LAZY_STREAM(ZX_LOG_STREAM(FATAL, zx_err), DCHECK_IS_ON() && !(condition)) \ 67 | << "Check failed: " #condition << ". " 68 | 69 | #endif // MINI_CHROMIUM_BASE_FUCHSIA_FUCHSIA_LOGGING_H_ 70 | -------------------------------------------------------------------------------- /base/immediate_crash.h: -------------------------------------------------------------------------------- 1 | // Copyright 2006-2008 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_IMMEDIATE_CRASH_H_ 6 | #define MINI_CHROMIUM_BASE_IMMEDIATE_CRASH_H_ 7 | 8 | #include "build/build_config.h" 9 | 10 | #if BUILDFLAG(IS_WIN) 11 | #include 12 | #endif // BUILDFLAG(IS_WIN) 13 | 14 | #if defined(COMPILER_GCC) 15 | #define IMMEDIATE_CRASH_ALWAYS_INLINE inline __attribute__((__always_inline__)) 16 | #elif defined(COMPILER_MSVC) 17 | #define IMMEDIATE_CRASH_ALWAYS_INLINE __forceinline 18 | #else 19 | #define IMMEDIATE_CRASH_ALWAYS_INLINE inline 20 | #endif 21 | 22 | namespace base { 23 | 24 | [[noreturn]] IMMEDIATE_CRASH_ALWAYS_INLINE void ImmediateCrash() { 25 | #if defined(COMPILER_MSVC) 26 | __debugbreak(); 27 | #if defined(ARCH_CPU_X86_FAMILY) 28 | __ud2(); 29 | #elif defined(ARCH_CPU_ARM64) 30 | __hlt(0); 31 | #else 32 | #error Unsupported Windows Arch 33 | #endif 34 | #elif defined(ARCH_CPU_X86_FAMILY) 35 | asm("int3; ud2;"); 36 | #elif defined(ARCH_CPU_ARMEL) 37 | asm("bkpt #0; udf #0;"); 38 | #elif defined(ARCH_CPU_ARM64) 39 | asm("brk #0; hlt #0;"); 40 | #else 41 | __builtin_trap(); 42 | #endif 43 | #if defined(__clang__) || defined(COMPILER_GCC) 44 | __builtin_unreachable(); 45 | #endif // defined(__clang__) || defined(COMPILER_GCC) 46 | } 47 | 48 | } // namespace base 49 | 50 | #endif // MINI_CHROMIUM_BASE_IMMEDIATE_CRASH_H_ 51 | -------------------------------------------------------------------------------- /base/mac/close_nocancel.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | // http://crbug.com/269623 6 | // http://openradar.appspot.com/14999594 7 | // 8 | // When the default version of close used on Mac OS X fails with EINTR, the 9 | // file descriptor is not in a deterministic state. It may have been closed, 10 | // or it may not have been. This makes it impossible to gracefully recover 11 | // from the error. If the close is retried after the FD has been closed, the 12 | // subsequent close can report EBADF, or worse, it can close an unrelated FD 13 | // opened by another thread. If the close is not retried after the FD has been 14 | // left open, the FD is leaked. Neither of these are good options. 15 | // 16 | // Mac OS X provides an alternate version of close, close$NOCANCEL. This 17 | // version will never fail with EINTR before the FD is actually closed. With 18 | // this version, it is thus safe to call close without checking for EINTR (as 19 | // the HANDLE_EINTR macro does) and not risk leaking the FD. In fact, mixing 20 | // this verison of close with HANDLE_EINTR is hazardous. 21 | // 22 | // The $NOCANCEL variants of various system calls are activated by compiling 23 | // with __DARWIN_NON_CANCELABLE, which prevents them from being pthread 24 | // cancellation points. Rather than taking such a heavy-handed approach, this 25 | // file implements an alternative: to use the $NOCANCEL variant of close (thus 26 | // preventing it from being a pthread cancellation point) without affecting 27 | // any other system calls. 28 | // 29 | // This file operates by providing a close function with the non-$NOCANCEL 30 | // symbol name expected for the compilation environment as set by 31 | // and (the DARWIN_ALIAS_C macro). That name is set by an asm 32 | // label on the declaration of the close function, so the definition of that 33 | // function receives that name. The function calls the $NOCANCEL variant, which 34 | // is resolved from libsyscall. By linking with this version of close prior to 35 | // the libsyscall version, close's implementation is overridden. 36 | 37 | #include 38 | #include 39 | 40 | // If the non-cancelable variants of all system calls have already been 41 | // chosen, do nothing. 42 | #if !__DARWIN_NON_CANCELABLE 43 | 44 | extern "C" { 45 | 46 | #if !__DARWIN_ONLY_UNIX_CONFORMANCE 47 | 48 | // When there's a choice between UNIX2003 and pre-UNIX2003. There's no 49 | // close$NOCANCEL symbol in this case, so use close$NOCANCEL$UNIX2003 as the 50 | // implementation. It does the same thing that close$NOCANCEL would do. 51 | #define close_implementation close$NOCANCEL$UNIX2003 52 | 53 | #else // __DARWIN_ONLY_UNIX_CONFORMANCE 54 | 55 | // When only UNIX2003 is supported: 56 | #define close_implementation close$NOCANCEL 57 | 58 | #endif 59 | 60 | int close_implementation(int fd); 61 | 62 | int close(int fd) { 63 | return close_implementation(fd); 64 | } 65 | 66 | #undef close_implementation 67 | 68 | } // extern "C" 69 | 70 | #endif // !__DARWIN_NON_CANCELABLE 71 | -------------------------------------------------------------------------------- /base/mac/scoped_ioobject.h: -------------------------------------------------------------------------------- 1 | // Copyright 2010 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_MAC_SCOPED_IOOBJECT_H_ 6 | #define MINI_CHROMIUM_BASE_MAC_SCOPED_IOOBJECT_H_ 7 | 8 | #include 9 | 10 | #include "base/apple/scoped_typeref.h" 11 | 12 | namespace base { 13 | namespace mac { 14 | 15 | namespace internal { 16 | 17 | template 18 | struct ScopedIOObjectTraits { 19 | static IOT InvalidValue() { return IO_OBJECT_NULL; } 20 | static IOT Retain(IOT iot) { 21 | IOObjectRetain(iot); 22 | return iot; 23 | } 24 | static void Release(IOT iot) { IOObjectRelease(iot); } 25 | }; 26 | 27 | } // namespce internal 28 | 29 | template 30 | using ScopedIOObject = 31 | apple::ScopedTypeRef>; 32 | 33 | } // namespace mac 34 | } // namespace base 35 | 36 | #endif // MINI_CHROMIUM_BASE_MAC_SCOPED_IOOBJECT_H_ 37 | -------------------------------------------------------------------------------- /base/mac/scoped_launch_data.h: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_MAC_SCOPED_LAUNCH_DATA_H_ 6 | #define MINI_CHROMIUM_BASE_MAC_SCOPED_LAUNCH_DATA_H_ 7 | 8 | #include 9 | 10 | #include "base/scoped_generic.h" 11 | 12 | namespace base { 13 | namespace mac { 14 | 15 | namespace internal { 16 | 17 | struct ScopedLaunchDataTraits { 18 | static launch_data_t InvalidValue() { return nullptr; } 19 | 20 | static void Free(launch_data_t ldt) { 21 | #pragma clang diagnostic push 22 | #pragma clang diagnostic ignored "-Wdeprecated-declarations" 23 | launch_data_free(ldt); 24 | #pragma clang diagnostic pop 25 | } 26 | }; 27 | 28 | } // namespace internal 29 | 30 | using ScopedLaunchData = 31 | ScopedGeneric; 32 | 33 | } // namespace mac 34 | } // namespace base 35 | 36 | #endif // MINI_CHROMIUM_BASE_MAC_SCOPED_LAUNCH_DATA_H_ 37 | -------------------------------------------------------------------------------- /base/memory/free_deleter.h: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_MEMORY_FREE_DELETER_H_ 6 | #define MINI_CHROMIUM_BASE_MEMORY_FREE_DELETER_H_ 7 | 8 | #include 9 | 10 | namespace base { 11 | 12 | // Function object which invokes 'free' on its parameter, which must be 13 | // a pointer. Can be used to store malloc-allocated pointers in std::unique_ptr: 14 | // 15 | // std::unique_ptr foo_ptr( 16 | // static_cast(malloc(sizeof(int)))); 17 | struct FreeDeleter { 18 | inline void operator()(void* ptr) const { 19 | free(ptr); 20 | } 21 | }; 22 | 23 | } // namespace base 24 | 25 | #endif // MINI_CHROMIUM_BASE_MEMORY_FREE_DELETER_H_ 26 | -------------------------------------------------------------------------------- /base/memory/page_size.h: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_PROCESS_PROCESS_METRICS_H_ 6 | #define MINI_CHROMIUM_BASE_PROCESS_PROCESS_METRICS_H_ 7 | 8 | #include 9 | 10 | namespace base { 11 | 12 | size_t GetPageSize(); 13 | 14 | } // namespace base 15 | 16 | #endif // MINI_CHROMIUM_BASE_PROCESS_PROCESS_METRICS_H_ 17 | -------------------------------------------------------------------------------- /base/memory/page_size_posix.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/memory/page_size.h" 6 | 7 | #include 8 | 9 | namespace base { 10 | 11 | size_t GetPageSize() { 12 | return getpagesize(); 13 | } 14 | 15 | } // namespace base 16 | -------------------------------------------------------------------------------- /base/memory/page_size_win.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/memory/page_size.h" 6 | 7 | namespace base { 8 | 9 | size_t GetPageSize() { 10 | return 4 * 1024; 11 | } 12 | 13 | } // namespace base 14 | -------------------------------------------------------------------------------- /base/memory/raw_ptr_exclusion.h: -------------------------------------------------------------------------------- 1 | // Copyright 2023 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_MEMORY_RAW_PTR_EXCLUSION_H_ 6 | #define MINI_CHROMIUM_BASE_MEMORY_RAW_PTR_EXCLUSION_H_ 7 | 8 | // Not provided in mini_chromuim, as it's part of PartitionAlloc. 9 | #ifndef RAW_PTR_EXCLUSION 10 | #define RAW_PTR_EXCLUSION 11 | #endif 12 | 13 | #endif // MINI_CHROMIUM_BASE_MEMORY_RAW_PTR_EXCLUSION_H_ 14 | -------------------------------------------------------------------------------- /base/memory/scoped_policy.h: -------------------------------------------------------------------------------- 1 | // Copyright 2012 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_MEMORY_SCOPED_POLICY_H_ 6 | #define MINI_CHROMIUM_BASE_MEMORY_SCOPED_POLICY_H_ 7 | 8 | namespace base { 9 | namespace scoped_policy { 10 | 11 | // Defines the ownership policy for a scoped object. 12 | enum OwnershipPolicy { 13 | // The scoped object takes ownership of an object by taking over an existing 14 | // ownership claim. 15 | ASSUME, 16 | 17 | // The scoped object will retain the the object and any initial ownership is 18 | // not changed. 19 | RETAIN 20 | }; 21 | 22 | } // namespace scoped_policy 23 | } // namespace base 24 | 25 | #endif // MINI_CHROMIUM_BASE_MEMORY_SCOPED_POLICY_H_ 26 | -------------------------------------------------------------------------------- /base/metrics/histogram_functions.h: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_METRICS_HISTOGRAM_FUNCTIONS_H_ 6 | #define MINI_CHROMIUM_BASE_METRICS_HISTOGRAM_FUNCTIONS_H_ 7 | 8 | #include 9 | 10 | // These are no-op stub versions of a subset of the functions from Chromium's 11 | // base/metrics/histogram_functions.h. This allows us to instrument the Crashpad 12 | // code as necessary, while not affecting out-of-Chromium builds. 13 | namespace base { 14 | 15 | void UmaHistogramSparse(const std::string& name, int sample) {} 16 | 17 | } // namespace base 18 | 19 | #endif // MINI_CHROMIUM_BASE_METRICS_HISTOGRAM_FUNCTIONS_H_ 20 | -------------------------------------------------------------------------------- /base/metrics/histogram_macros.h: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_METRICS_HISTOGRAM_MACROS_H_ 6 | #define MINI_CHROMIUM_BASE_METRICS_HISTOGRAM_MACROS_H_ 7 | 8 | // These are no-op stub versions of a subset of the macros from Chromium's 9 | // base/metrics/histogram_macros.h. This allows us to instrument the Crashpad 10 | // code as necessary, while not affecting out-of-Chromium builds. 11 | 12 | #define UMA_HISTOGRAM_UNUSED(x) (void)(x) 13 | 14 | #define UMA_HISTOGRAM_TIMES(name, sample) \ 15 | UMA_HISTOGRAM_UNUSED(name), UMA_HISTOGRAM_UNUSED(sample) 16 | #define UMA_HISTOGRAM_MEDIUM_TIMES(name, sample) \ 17 | UMA_HISTOGRAM_UNUSED(name), UMA_HISTOGRAM_UNUSED(sample) 18 | #define UMA_HISTOGRAM_LONG_TIMES(name, sample) \ 19 | UMA_HISTOGRAM_UNUSED(name), UMA_HISTOGRAM_UNUSED(sample) 20 | #define UMA_HISTOGRAM_LONG_TIMES_100(name, sample) \ 21 | UMA_HISTOGRAM_UNUSED(name), UMA_HISTOGRAM_UNUSED(sample) 22 | #define UMA_HISTOGRAM_CUSTOM_TIMES(name, sample, min, max, bucket_count) \ 23 | UMA_HISTOGRAM_UNUSED(name), \ 24 | UMA_HISTOGRAM_UNUSED(sample), \ 25 | UMA_HISTOGRAM_UNUSED(min), \ 26 | UMA_HISTOGRAM_UNUSED(max), \ 27 | UMA_HISTOGRAM_UNUSED(bucket_count) 28 | 29 | #define UMA_HISTOGRAM_COUNTS(name, sample) \ 30 | UMA_HISTOGRAM_UNUSED(name), UMA_HISTOGRAM_UNUSED(sample) 31 | #define UMA_HISTOGRAM_COUNTS_100(name, sample) \ 32 | UMA_HISTOGRAM_UNUSED(name), UMA_HISTOGRAM_UNUSED(sample) 33 | #define UMA_HISTOGRAM_COUNTS_1000(name, sample) \ 34 | UMA_HISTOGRAM_UNUSED(name), UMA_HISTOGRAM_UNUSED(sample) 35 | #define UMA_HISTOGRAM_COUNTS_10000(name, sample) \ 36 | UMA_HISTOGRAM_UNUSED(name), UMA_HISTOGRAM_UNUSED(sample) 37 | #define UMA_HISTOGRAM_CUSTOM_COUNTS(name, sample, min, max, bucket_count) \ 38 | UMA_HISTOGRAM_UNUSED(name), \ 39 | UMA_HISTOGRAM_UNUSED(sample), \ 40 | UMA_HISTOGRAM_UNUSED(min), \ 41 | UMA_HISTOGRAM_UNUSED(max), \ 42 | UMA_HISTOGRAM_UNUSED(bucket_count) 43 | 44 | #define UMA_HISTOGRAM_MEMORY_KB(name, sample) \ 45 | UMA_HISTOGRAM_UNUSED(name), UMA_HISTOGRAM_UNUSED(sample) 46 | #define UMA_HISTOGRAM_MEMORY_MB(name, sample) \ 47 | UMA_HISTOGRAM_UNUSED(name), UMA_HISTOGRAM_UNUSED(sample) 48 | #define UMA_HISTOGRAM_MEMORY_LARGE_MB(name, sample) \ 49 | UMA_HISTOGRAM_UNUSED(name), UMA_HISTOGRAM_UNUSED(sample) 50 | 51 | #define UMA_HISTOGRAM_PERCENTAGE(name, under_one_hundred) \ 52 | UMA_HISTOGRAM_UNUSED(name), UMA_HISTOGRAM_UNUSED(under_one_hundred) 53 | 54 | #define UMA_HISTOGRAM_BOOLEAN(name, sample) \ 55 | UMA_HISTOGRAM_UNUSED(name), UMA_HISTOGRAM_UNUSED(sample) 56 | 57 | #define UMA_HISTOGRAM_ENUMERATION(name, sample, boundary_value) \ 58 | UMA_HISTOGRAM_UNUSED(name), \ 59 | UMA_HISTOGRAM_UNUSED(sample), \ 60 | UMA_HISTOGRAM_UNUSED(boundary_value) 61 | #define UMA_STABILITY_HISTOGRAM_ENUMERATION(name, sample, boundary_value) \ 62 | UMA_HISTOGRAM_UNUSED(name), \ 63 | UMA_HISTOGRAM_UNUSED(sample), \ 64 | UMA_HISTOGRAM_UNUSED(boundary_value) 65 | #define UMA_HISTOGRAM_CUSTOM_ENUMERATION(name, sample, custom_ranges) \ 66 | UMA_HISTOGRAM_UNUSED(name), \ 67 | UMA_HISTOGRAM_UNUSED(sample), \ 68 | UMA_HISTOGRAM_UNUSED(custom_ranges) 69 | 70 | #endif // MINI_CHROMIUM_BASE_METRICS_HISTOGRAM_MACROS_H_ 71 | -------------------------------------------------------------------------------- /base/metrics/persistent_histogram_allocator.h: -------------------------------------------------------------------------------- 1 | // Copyright 2016 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_METRICS_PERSISTENT_HISTOGRAM_ALLOCATOR_H_ 6 | #define MINI_CHROMIUM_BASE_METRICS_PERSISTENT_HISTOGRAM_ALLOCATOR_H_ 7 | 8 | #include 9 | #include 10 | 11 | #include "base/files/file_path.h" 12 | #include "base/strings/string_piece.h" 13 | 14 | // This file is a non-functional stub of the Chromium base interface to allow 15 | // Crashpad to set up and tear down histogram storage when built against 16 | // Chromium. When Crashpad is built standalone these stubs are used which 17 | // silently do nothing. 18 | namespace base { 19 | 20 | class GlobalHistogramAllocator { 21 | public: 22 | GlobalHistogramAllocator(const GlobalHistogramAllocator&) = delete; 23 | GlobalHistogramAllocator& operator=(const GlobalHistogramAllocator&) = delete; 24 | 25 | static bool CreateWithActiveFileInDir(const base::FilePath&, 26 | size_t, 27 | uint64_t, 28 | base::StringPiece sp) { 29 | return false; 30 | } 31 | 32 | void CreateTrackingHistograms(base::StringPiece) {} 33 | void DeletePersistentLocation() {} 34 | 35 | static GlobalHistogramAllocator* Get() { return nullptr; } 36 | }; 37 | 38 | } // namespace base 39 | 40 | #endif // MINI_CHROMIUM_BASE_METRICS_PERSISTENT_HISTOGRAM_ALLOCATOR_H_ 41 | -------------------------------------------------------------------------------- /base/notreached.h: -------------------------------------------------------------------------------- 1 | // Copyright 2020 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_NOTREACHED_H_ 6 | #define MINI_CHROMIUM_BASE_NOTREACHED_H_ 7 | 8 | #include "base/check.h" 9 | #include "base/logging.h" 10 | 11 | #define NOTREACHED() LOG(FATAL) << "NOTREACHED hit. " 12 | 13 | #endif // MINI_CHROMIUM_BASE_NOTREACHED_H_ 14 | -------------------------------------------------------------------------------- /base/numerics/basic_ops_impl.h: -------------------------------------------------------------------------------- 1 | // Copyright 2024 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_NUMERICS_BASIC_OPS_IMPL_H_ 6 | #define MINI_CHROMIUM_BASE_NUMERICS_BASIC_OPS_IMPL_H_ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | namespace base::internal { 16 | 17 | // The correct type to perform math operations on given values of type `T`. This 18 | // may be a larger type than `T` to avoid promotion to `int` which involves sign 19 | // conversion! 20 | template 21 | requires(std::is_integral_v) 22 | using MathType = std::conditional_t< 23 | sizeof(T) >= sizeof(int), 24 | T, 25 | std::conditional_t, int, unsigned int>>; 26 | 27 | // Reverses the byte order of the integer. 28 | template 29 | requires(std::is_unsigned_v && std::is_integral_v) 30 | inline constexpr T SwapBytes(T value) { 31 | // MSVC intrinsics are not constexpr, so we provide our own constexpr 32 | // implementation. We provide it unconditionally so we can test it on all 33 | // platforms for correctness. 34 | if (std::is_constant_evaluated()) { 35 | if constexpr (sizeof(T) == 1u) { 36 | return value; 37 | } else if constexpr (sizeof(T) == 2u) { 38 | MathType a = (MathType(value) >> 0) & MathType{0xff}; 39 | MathType b = (MathType(value) >> 8) & MathType{0xff}; 40 | return static_cast((a << 8) | (b << 0)); 41 | } else if constexpr (sizeof(T) == 4u) { 42 | T a = (value >> 0) & T{0xff}; 43 | T b = (value >> 8) & T{0xff}; 44 | T c = (value >> 16) & T{0xff}; 45 | T d = (value >> 24) & T{0xff}; 46 | return (a << 24) | (b << 16) | (c << 8) | (d << 0); 47 | } else { 48 | static_assert(sizeof(T) == 8u); 49 | T a = (value >> 0) & T{0xff}; 50 | T b = (value >> 8) & T{0xff}; 51 | T c = (value >> 16) & T{0xff}; 52 | T d = (value >> 24) & T{0xff}; 53 | T e = (value >> 32) & T{0xff}; 54 | T f = (value >> 40) & T{0xff}; 55 | T g = (value >> 48) & T{0xff}; 56 | T h = (value >> 56) & T{0xff}; 57 | return (a << 56) | (b << 48) | (c << 40) | (d << 32) | // 58 | (e << 24) | (f << 16) | (g << 8) | (h << 0); 59 | } 60 | } 61 | 62 | #if _MSC_VER 63 | if constexpr (sizeof(T) == 1u) { 64 | return value; 65 | } else if constexpr (sizeof(T) == sizeof(unsigned short)) { 66 | using U = unsigned short; 67 | return _byteswap_ushort(U{value}); 68 | } else if constexpr (sizeof(T) == sizeof(unsigned long)) { 69 | using U = unsigned long; 70 | return _byteswap_ulong(U{value}); 71 | } else { 72 | static_assert(sizeof(T) == 8u); 73 | return _byteswap_uint64(value); 74 | } 75 | #else 76 | if constexpr (sizeof(T) == 1u) { 77 | return value; 78 | } else if constexpr (sizeof(T) == 2u) { 79 | return __builtin_bswap16(uint16_t{value}); 80 | } else if constexpr (sizeof(T) == 4u) { 81 | return __builtin_bswap32(value); 82 | } else { 83 | static_assert(sizeof(T) == 8u); 84 | return __builtin_bswap64(value); 85 | } 86 | #endif 87 | } 88 | 89 | // Signed values are byte-swapped as unsigned values. 90 | template 91 | requires(std::is_signed_v && std::is_integral_v) 92 | inline constexpr T SwapBytes(T value) { 93 | return static_cast(SwapBytes(static_cast>(value))); 94 | } 95 | 96 | // Converts from a byte array to an integer. 97 | template 98 | requires(std::is_unsigned_v && std::is_integral_v) 99 | inline constexpr T FromLittleEndian(std::span bytes) { 100 | T val; 101 | if (std::is_constant_evaluated()) { 102 | val = T{0}; 103 | for (size_t i = 0u; i < sizeof(T); i += 1u) { 104 | // SAFETY: `i < sizeof(T)` (the number of bytes in T), so `(8 * i)` is 105 | // less than the number of bits in T. 106 | val |= MathType(bytes[i]) << (8u * i); 107 | } 108 | } else { 109 | // SAFETY: `bytes` has sizeof(T) bytes, and `val` is of type `T` so has 110 | // sizeof(T) bytes, and the two can not alias as `val` is a stack variable. 111 | memcpy(&val, bytes.data(), sizeof(T)); 112 | } 113 | return val; 114 | } 115 | 116 | // Converts to a byte array from an integer. 117 | template 118 | requires(std::is_unsigned_v && std::is_integral_v) 119 | inline constexpr std::array ToLittleEndian(T val) { 120 | auto bytes = std::array(); 121 | if (std::is_constant_evaluated()) { 122 | for (size_t i = 0u; i < sizeof(T); i += 1u) { 123 | const auto last_byte = static_cast(val & 0xff); 124 | // The low bytes go to the front of the array in little endian. 125 | bytes[i] = last_byte; 126 | // If `val` is one byte, this shift would be UB. But it's also not needed 127 | // since the loop will not run again. 128 | if constexpr (sizeof(T) > 1u) { 129 | val >>= 8u; 130 | } 131 | } 132 | } else { 133 | // SAFETY: `bytes` has sizeof(T) bytes, and `val` is of type `T` so has 134 | // sizeof(T) bytes, and the two can not alias as `val` is a stack variable. 135 | memcpy(bytes.data(), &val, sizeof(T)); 136 | } 137 | return bytes; 138 | } 139 | 140 | } // namespace base::internal 141 | 142 | #endif // MINI_CHROMIUM_BASE_NUMERICS_BASIC_OPS_IMPL_H_ 143 | -------------------------------------------------------------------------------- /base/numerics/safe_conversions_arm_impl.h: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_NUMERICS_SAFE_CONVERSIONS_ARM_IMPL_H_ 6 | #define MINI_CHROMIUM_BASE_NUMERICS_SAFE_CONVERSIONS_ARM_IMPL_H_ 7 | 8 | #include 9 | #include 10 | 11 | #include "base/numerics/safe_conversions_impl.h" 12 | 13 | namespace base { 14 | namespace internal { 15 | 16 | // Fast saturation to a destination type. 17 | template 18 | struct SaturateFastAsmOp { 19 | static constexpr bool is_supported = 20 | std::is_signed::value && std::is_integral::value && 21 | std::is_integral::value && 22 | IntegerBitsPlusSign::value <= IntegerBitsPlusSign::value && 23 | IntegerBitsPlusSign::value <= IntegerBitsPlusSign::value && 24 | !IsTypeInRangeForNumericType::value; 25 | 26 | __attribute__((always_inline)) static Dst Do(Src value) { 27 | int32_t src = value; 28 | typename std::conditional::value, int32_t, 29 | uint32_t>::type result; 30 | if (std::is_signed::value) { 31 | asm("ssat %[dst], %[shift], %[src]" 32 | : [dst] "=r"(result) 33 | : [src] "r"(src), [shift] "n"(IntegerBitsPlusSign::value <= 32 34 | ? IntegerBitsPlusSign::value 35 | : 32)); 36 | } else { 37 | asm("usat %[dst], %[shift], %[src]" 38 | : [dst] "=r"(result) 39 | : [src] "r"(src), [shift] "n"(IntegerBitsPlusSign::value < 32 40 | ? IntegerBitsPlusSign::value 41 | : 31)); 42 | } 43 | return static_cast(result); 44 | } 45 | }; 46 | 47 | } // namespace internal 48 | } // namespace base 49 | 50 | #endif // MINI_CHROMIUM_BASE_NUMERICS_SAFE_CONVERSIONS_ARM_IMPL_H_ 51 | -------------------------------------------------------------------------------- /base/numerics/safe_math.h: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_NUMERICS_SAFE_MATH_H_ 6 | #define MINI_CHROMIUM_BASE_NUMERICS_SAFE_MATH_H_ 7 | 8 | #include "base/numerics/checked_math.h" 9 | #include "base/numerics/clamped_math.h" 10 | #include "base/numerics/safe_conversions.h" 11 | 12 | #endif // MINI_CHROMIUM_BASE_NUMERICS_SAFE_MATH_H_ 13 | -------------------------------------------------------------------------------- /base/numerics/safe_math_arm_impl.h: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_NUMERICS_SAFE_MATH_ARM_IMPL_H_ 6 | #define MINI_CHROMIUM_BASE_NUMERICS_SAFE_MATH_ARM_IMPL_H_ 7 | 8 | #include 9 | 10 | #include 11 | #include 12 | 13 | #include "base/numerics/safe_conversions.h" 14 | 15 | namespace base { 16 | namespace internal { 17 | 18 | template 19 | struct CheckedMulFastAsmOp { 20 | static const bool is_supported = 21 | FastIntegerArithmeticPromotion::is_contained; 22 | 23 | // The following is much more efficient than the Clang and GCC builtins for 24 | // performing overflow-checked multiplication when a twice wider type is 25 | // available. The below compiles down to 2-3 instructions, depending on the 26 | // width of the types in use. 27 | // As an example, an int32_t multiply compiles to: 28 | // smull r0, r1, r0, r1 29 | // cmp r1, r1, asr #31 30 | // And an int16_t multiply compiles to: 31 | // smulbb r1, r1, r0 32 | // asr r2, r1, #16 33 | // cmp r2, r1, asr #15 34 | template 35 | __attribute__((always_inline)) static bool Do(T x, U y, V* result) { 36 | using Promotion = typename FastIntegerArithmeticPromotion::type; 37 | Promotion presult; 38 | 39 | presult = static_cast(x) * static_cast(y); 40 | *result = static_cast(presult); 41 | return IsValueInRangeForNumericType(presult); 42 | } 43 | }; 44 | 45 | template 46 | struct ClampedAddFastAsmOp { 47 | static const bool is_supported = 48 | BigEnoughPromotion::is_contained && 49 | IsTypeInRangeForNumericType< 50 | int32_t, 51 | typename BigEnoughPromotion::type>::value; 52 | 53 | template 54 | __attribute__((always_inline)) static V Do(T x, U y) { 55 | // This will get promoted to an int, so let the compiler do whatever is 56 | // clever and rely on the saturated cast to bounds check. 57 | if (IsIntegerArithmeticSafe::value) 58 | return saturated_cast(x + y); 59 | 60 | int32_t result; 61 | int32_t x_i32 = x; 62 | int32_t y_i32 = y; 63 | 64 | asm("qadd %[result], %[first], %[second]" 65 | : [result] "=r"(result) 66 | : [first] "r"(x_i32), [second] "r"(y_i32)); 67 | return saturated_cast(result); 68 | } 69 | }; 70 | 71 | template 72 | struct ClampedSubFastAsmOp { 73 | static const bool is_supported = 74 | BigEnoughPromotion::is_contained && 75 | IsTypeInRangeForNumericType< 76 | int32_t, 77 | typename BigEnoughPromotion::type>::value; 78 | 79 | template 80 | __attribute__((always_inline)) static V Do(T x, U y) { 81 | // This will get promoted to an int, so let the compiler do whatever is 82 | // clever and rely on the saturated cast to bounds check. 83 | if (IsIntegerArithmeticSafe::value) 84 | return saturated_cast(x - y); 85 | 86 | int32_t result; 87 | int32_t x_i32 = x; 88 | int32_t y_i32 = y; 89 | 90 | asm("qsub %[result], %[first], %[second]" 91 | : [result] "=r"(result) 92 | : [first] "r"(x_i32), [second] "r"(y_i32)); 93 | return saturated_cast(result); 94 | } 95 | }; 96 | 97 | template 98 | struct ClampedMulFastAsmOp { 99 | static const bool is_supported = CheckedMulFastAsmOp::is_supported; 100 | 101 | template 102 | __attribute__((always_inline)) static V Do(T x, U y) { 103 | // Use the CheckedMulFastAsmOp for full-width 32-bit values, because 104 | // it's fewer instructions than promoting and then saturating. 105 | if (!IsIntegerArithmeticSafe::value && 106 | !IsIntegerArithmeticSafe::value) { 107 | V result; 108 | if (CheckedMulFastAsmOp::Do(x, y, &result)) 109 | return result; 110 | return CommonMaxOrMin(IsValueNegative(x) ^ IsValueNegative(y)); 111 | } 112 | 113 | assert((FastIntegerArithmeticPromotion::is_contained)); 114 | using Promotion = typename FastIntegerArithmeticPromotion::type; 115 | return saturated_cast(static_cast(x) * 116 | static_cast(y)); 117 | } 118 | }; 119 | 120 | } // namespace internal 121 | } // namespace base 122 | 123 | #endif // MINI_CHROMIUM_BASE_NUMERICS_SAFE_MATH_ARM_IMPL_H_ 124 | -------------------------------------------------------------------------------- /base/numerics/safe_math_clang_gcc_impl.h: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_NUMERICS_SAFE_MATH_CLANG_GCC_IMPL_H_ 6 | #define MINI_CHROMIUM_BASE_NUMERICS_SAFE_MATH_CLANG_GCC_IMPL_H_ 7 | 8 | #include 9 | #include 10 | 11 | #include "base/numerics/safe_conversions.h" 12 | 13 | #if defined(__ARMEL__) || defined(__arch64__) 14 | #include "base/numerics/safe_math_arm_impl.h" 15 | #define BASE_HAS_ASSEMBLER_SAFE_MATH (1) 16 | #else 17 | #define BASE_HAS_ASSEMBLER_SAFE_MATH (0) 18 | #endif 19 | 20 | namespace base { 21 | namespace internal { 22 | 23 | // These are the non-functioning boilerplate implementations of the optimized 24 | // safe math routines. 25 | #if !BASE_HAS_ASSEMBLER_SAFE_MATH 26 | template 27 | struct CheckedMulFastAsmOp { 28 | static const bool is_supported = false; 29 | template 30 | static constexpr bool Do(T, U, V*) { 31 | // Force a compile failure if instantiated. 32 | return CheckOnFailure::template HandleFailure(); 33 | } 34 | }; 35 | 36 | template 37 | struct ClampedAddFastAsmOp { 38 | static const bool is_supported = false; 39 | template 40 | static constexpr V Do(T, U) { 41 | // Force a compile failure if instantiated. 42 | return CheckOnFailure::template HandleFailure(); 43 | } 44 | }; 45 | 46 | template 47 | struct ClampedSubFastAsmOp { 48 | static const bool is_supported = false; 49 | template 50 | static constexpr V Do(T, U) { 51 | // Force a compile failure if instantiated. 52 | return CheckOnFailure::template HandleFailure(); 53 | } 54 | }; 55 | 56 | template 57 | struct ClampedMulFastAsmOp { 58 | static const bool is_supported = false; 59 | template 60 | static constexpr V Do(T, U) { 61 | // Force a compile failure if instantiated. 62 | return CheckOnFailure::template HandleFailure(); 63 | } 64 | }; 65 | #endif // BASE_HAS_ASSEMBLER_SAFE_MATH 66 | #undef BASE_HAS_ASSEMBLER_SAFE_MATH 67 | 68 | template 69 | struct CheckedAddFastOp { 70 | static const bool is_supported = true; 71 | template 72 | __attribute__((always_inline)) static constexpr bool Do(T x, U y, V* result) { 73 | return !__builtin_add_overflow(x, y, result); 74 | } 75 | }; 76 | 77 | template 78 | struct CheckedSubFastOp { 79 | static const bool is_supported = true; 80 | template 81 | __attribute__((always_inline)) static constexpr bool Do(T x, U y, V* result) { 82 | return !__builtin_sub_overflow(x, y, result); 83 | } 84 | }; 85 | 86 | template 87 | struct CheckedMulFastOp { 88 | #if defined(__clang__) 89 | // TODO(jschuh): Get the Clang runtime library issues sorted out so we can 90 | // support full-width, mixed-sign multiply builtins. 91 | // https://crbug.com/613003 92 | // We can support intptr_t, uintptr_t, or a smaller common type. 93 | static const bool is_supported = 94 | (IsTypeInRangeForNumericType::value && 95 | IsTypeInRangeForNumericType::value) || 96 | (IsTypeInRangeForNumericType::value && 97 | IsTypeInRangeForNumericType::value); 98 | #else 99 | static const bool is_supported = true; 100 | #endif 101 | template 102 | __attribute__((always_inline)) static constexpr bool Do(T x, U y, V* result) { 103 | return CheckedMulFastAsmOp::is_supported 104 | ? CheckedMulFastAsmOp::Do(x, y, result) 105 | : !__builtin_mul_overflow(x, y, result); 106 | } 107 | }; 108 | 109 | template 110 | struct ClampedAddFastOp { 111 | static const bool is_supported = ClampedAddFastAsmOp::is_supported; 112 | template 113 | __attribute__((always_inline)) static V Do(T x, U y) { 114 | return ClampedAddFastAsmOp::template Do(x, y); 115 | } 116 | }; 117 | 118 | template 119 | struct ClampedSubFastOp { 120 | static const bool is_supported = ClampedSubFastAsmOp::is_supported; 121 | template 122 | __attribute__((always_inline)) static V Do(T x, U y) { 123 | return ClampedSubFastAsmOp::template Do(x, y); 124 | } 125 | }; 126 | 127 | template 128 | struct ClampedMulFastOp { 129 | static const bool is_supported = ClampedMulFastAsmOp::is_supported; 130 | template 131 | __attribute__((always_inline)) static V Do(T x, U y) { 132 | return ClampedMulFastAsmOp::template Do(x, y); 133 | } 134 | }; 135 | 136 | template 137 | struct ClampedNegFastOp { 138 | static const bool is_supported = std::is_signed::value; 139 | __attribute__((always_inline)) static T Do(T value) { 140 | // Use this when there is no assembler path available. 141 | if (!ClampedSubFastAsmOp::is_supported) { 142 | T result; 143 | return !__builtin_sub_overflow(T(0), value, &result) 144 | ? result 145 | : std::numeric_limits::max(); 146 | } 147 | 148 | // Fallback to the normal subtraction path. 149 | return ClampedSubFastOp::template Do(T(0), value); 150 | } 151 | }; 152 | 153 | } // namespace internal 154 | } // namespace base 155 | 156 | #endif // MINI_CHROMIUM_BASE_NUMERICS_SAFE_MATH_CLANG_GCC_IMPL_H_ 157 | -------------------------------------------------------------------------------- /base/posix/eintr_wrapper.h: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | // This provides a wrapper around system calls which may be interrupted by a 6 | // signal and return EINTR. See man 7 signal. 7 | // 8 | // On Windows, this wrapper macro does nothing. 9 | 10 | #ifndef MINI_CHROMIUM_BASE_POSIX_EINTR_WRAPPER_H_ 11 | #define MINI_CHROMIUM_BASE_POSIX_EINTR_WRAPPER_H_ 12 | 13 | #include "build/build_config.h" 14 | 15 | // On Fuchsia, these wrapper macros do nothing because there are no signals. 16 | #if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_FUCHSIA) 17 | 18 | #include 19 | 20 | #define HANDLE_EINTR(x) ({ \ 21 | decltype(x) eintr_wrapper_result; \ 22 | do { \ 23 | eintr_wrapper_result = (x); \ 24 | } while (eintr_wrapper_result == -1 && errno == EINTR); \ 25 | eintr_wrapper_result; \ 26 | }) 27 | 28 | #define IGNORE_EINTR(x) ({ \ 29 | decltype(x) eintr_wrapper_result; \ 30 | do { \ 31 | eintr_wrapper_result = (x); \ 32 | if (eintr_wrapper_result == -1 && errno == EINTR) { \ 33 | eintr_wrapper_result = 0; \ 34 | } \ 35 | } while (0); \ 36 | eintr_wrapper_result; \ 37 | }) 38 | 39 | #else 40 | 41 | #define HANDLE_EINTR(x) (x) 42 | #define IGNORE_EINTR(x) (x) 43 | 44 | #endif // BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_FUCHSIA) 45 | 46 | #endif // MINI_CHROMIUM_BASE_POSIX_EINTR_WRAPPER_H_ 47 | -------------------------------------------------------------------------------- /base/posix/safe_strerror.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/posix/safe_strerror.h" 6 | 7 | #include 8 | #include 9 | #include 10 | 11 | #include "build/build_config.h" 12 | 13 | #if BUILDFLAG(IS_ANDROID) 14 | #include 15 | #endif 16 | 17 | namespace base { 18 | 19 | void safe_strerror_r(int err, char* buf, size_t len) { 20 | #if defined(__GLIBC__) || \ 21 | (BUILDFLAG(IS_ANDROID) && defined(_GNU_SOURCE) && __ANDROID_API__ >= 23) 22 | char* ret = strerror_r(err, buf, len); 23 | if (ret != buf) { 24 | snprintf(buf, len, "%s", ret); 25 | } 26 | #else 27 | int result = strerror_r(err, buf, len); 28 | if (result != 0) { 29 | snprintf(buf, 30 | len, 31 | "Error %d while retrieving error %d", 32 | result > 0 ? result : errno, 33 | err); 34 | } 35 | #endif 36 | } 37 | 38 | std::string safe_strerror(int err) { 39 | char buf[256]; 40 | safe_strerror_r(err, buf, std::size(buf)); 41 | return std::string(buf); 42 | } 43 | 44 | } // namespace base 45 | -------------------------------------------------------------------------------- /base/posix/safe_strerror.h: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_POSIX_SAFE_STRERROR_H_ 6 | #define MINI_CHROMIUM_BASE_POSIX_SAFE_STRERROR_H_ 7 | 8 | #include 9 | 10 | namespace base { 11 | 12 | void safe_strerror_r(int err, char *buf, size_t len); 13 | std::string safe_strerror(int err); 14 | 15 | } // namespace base 16 | 17 | #endif // MINI_CHROMIUM_BASE_POSIX_SAFE_STRERROR_H_ 18 | -------------------------------------------------------------------------------- /base/process/memory.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/process/memory.h" 6 | 7 | #include 8 | 9 | namespace base { 10 | 11 | bool UncheckedMalloc(size_t size, void** result) { 12 | *result = malloc(size); 13 | return *result != NULL; 14 | } 15 | 16 | } // namespace base 17 | -------------------------------------------------------------------------------- /base/process/memory.h: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_PROCESS_MEMORY_H_ 6 | #define MINI_CHROMIUM_BASE_PROCESS_MEMORY_H_ 7 | 8 | #include 9 | 10 | namespace base { 11 | 12 | // Special allocator function for callers that want to check for OOM. 13 | // On success, *result will contain a pointer that should be dallocated with 14 | // free(). 15 | [[nodiscard]] bool UncheckedMalloc(size_t size, void** result); 16 | 17 | } // namespace base 18 | 19 | #endif // MINI_CHROMIUM_BASE_PROCESS_MEMORY_H_ 20 | -------------------------------------------------------------------------------- /base/rand_util.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2008 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/rand_util.h" 6 | 7 | #include 8 | #include 9 | 10 | #include 11 | #include 12 | #include 13 | 14 | #include "base/check_op.h" 15 | #include "base/files/file_util.h" 16 | #include "build/build_config.h" 17 | 18 | #if BUILDFLAG(IS_FUCHSIA) 19 | #include 20 | #include "base/fuchsia/fuchsia_logging.h" 21 | #elif BUILDFLAG(IS_POSIX) 22 | #include "base/posix/eintr_wrapper.h" 23 | #elif BUILDFLAG(IS_WIN) 24 | #include 25 | 26 | // #define needed to link in RtlGenRandom(), a.k.a. SystemFunction036. See the 27 | // "Community Additions" comment on MSDN here: 28 | // http://msdn.microsoft.com/en-us/library/windows/desktop/aa387694.aspx 29 | #define SystemFunction036 NTAPI SystemFunction036 30 | #include 31 | #undef SystemFunction036 32 | 33 | #endif // BUILDFLAG(IS_WIN) 34 | 35 | #if BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_FUCHSIA) 36 | 37 | namespace { 38 | 39 | int GetUrandomFDInternal() { 40 | int fd = HANDLE_EINTR(open("/dev/urandom", O_RDONLY | O_NOCTTY | O_CLOEXEC)); 41 | PCHECK(fd >= 0) << "open /dev/urandom"; 42 | return fd; 43 | } 44 | 45 | int GetUrandomFD() { 46 | static int fd = GetUrandomFDInternal(); 47 | return fd; 48 | } 49 | 50 | } // namespace 51 | 52 | #endif // BUILDFLAG(IS_POSIX) && !BUILDFLAG(IS_FUCHSIA) 53 | 54 | namespace base { 55 | 56 | uint64_t RandUint64() { 57 | uint64_t number; 58 | RandBytes(byte_span_from_ref(number)); 59 | return number; 60 | } 61 | 62 | int RandInt(int min, int max) { 63 | DCHECK_LE(min, max); 64 | 65 | uint64_t range = static_cast(max) - min + 1; 66 | int result = min + static_cast(base::RandGenerator(range)); 67 | DCHECK_GE(result, min); 68 | DCHECK_LE(result, max); 69 | 70 | return result; 71 | } 72 | 73 | uint64_t RandGenerator(uint64_t range) { 74 | DCHECK_GT(range, 0u); 75 | 76 | uint64_t max_acceptable_value = 77 | (std::numeric_limits::max() / range) * range - 1; 78 | 79 | uint64_t value; 80 | do { 81 | value = base::RandUint64(); 82 | } while (value > max_acceptable_value); 83 | 84 | return value % range; 85 | } 86 | 87 | double RandDouble() { 88 | static_assert(std::numeric_limits::radix == 2, 89 | "otherwise use scalbn"); 90 | static_assert(std::numeric_limits::digits < 91 | std::numeric_limits::digits, 92 | "integer type must be wider than floating-point mantissa"); 93 | 94 | uint64_t random_bits = RandUint64(); 95 | const int kMantissaBits = std::numeric_limits::digits; 96 | 97 | uint64_t mantissa = random_bits & ((UINT64_C(1) << kMantissaBits) - 1); 98 | 99 | double result = std::ldexp(mantissa, -1 * kMantissaBits); 100 | 101 | DCHECK_GE(result, 0.0); 102 | DCHECK_LT(result, 1.0); 103 | 104 | return result; 105 | } 106 | 107 | void RandBytes(span output) { 108 | if (output.empty()) { 109 | return; 110 | } 111 | 112 | #if BUILDFLAG(IS_FUCHSIA) 113 | zx_cprng_draw(output.data(), output.size()); 114 | #elif BUILDFLAG(IS_POSIX) 115 | int fd = GetUrandomFD(); 116 | bool success = 117 | ReadFromFD(fd, reinterpret_cast(output.data()), output.size()); 118 | CHECK(success); 119 | #elif BUILDFLAG(IS_WIN) 120 | while (!output.empty()) { 121 | const ULONG output_bytes_this_pass = static_cast(std::min( 122 | output.size(), static_cast(std::numeric_limits::max()))); 123 | const bool success = 124 | RtlGenRandom(output.data(), output_bytes_this_pass) != FALSE; 125 | CHECK(success); 126 | output = output.subspan(output_bytes_this_pass); 127 | } 128 | #endif 129 | } 130 | 131 | std::string RandBytesAsString(size_t length) { 132 | if (length == 0) { 133 | return std::string(); 134 | } 135 | 136 | std::string result(length, std::string::value_type()); 137 | RandBytes(as_writable_byte_span(result)); 138 | return result; 139 | } 140 | 141 | } // namespace base 142 | -------------------------------------------------------------------------------- /base/rand_util.h: -------------------------------------------------------------------------------- 1 | // Copyright 2008 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_RAND_UTIL_H_ 6 | #define MINI_CHROMIUM_BASE_RAND_UTIL_H_ 7 | 8 | #include 9 | 10 | #include 11 | 12 | #include "base/containers/span.h" 13 | 14 | namespace base { 15 | 16 | uint64_t RandUint64(); 17 | 18 | int RandInt(int min, int max); 19 | 20 | uint64_t RandGenerator(uint64_t range); 21 | 22 | double RandDouble(); 23 | 24 | void RandBytes(span output); 25 | std::string RandBytesAsString(size_t length); 26 | 27 | } // namespace base 28 | 29 | #endif // MINI_CHROMIUM_BASE_RAND_UTIL_H_ 30 | -------------------------------------------------------------------------------- /base/scoped_clear_last_error.h: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_SCOPED_CLEAR_LAST_ERROR_H_ 6 | #define MINI_CHROMIUM_BASE_SCOPED_CLEAR_LAST_ERROR_H_ 7 | 8 | #include 9 | 10 | #include "build/build_config.h" 11 | 12 | namespace base { 13 | 14 | class ScopedClearLastErrorBase { 15 | public: 16 | ScopedClearLastErrorBase() : last_errno_(errno) { errno = 0; } 17 | 18 | ScopedClearLastErrorBase(const ScopedClearLastErrorBase&) = delete; 19 | ScopedClearLastErrorBase& operator=(const ScopedClearLastErrorBase&) = delete; 20 | 21 | ~ScopedClearLastErrorBase() { errno = last_errno_; } 22 | 23 | private: 24 | const int last_errno_; 25 | }; 26 | 27 | #if BUILDFLAG(IS_WIN) 28 | 29 | class ScopedClearLastError : public ScopedClearLastErrorBase { 30 | public: 31 | ScopedClearLastError(); 32 | 33 | ScopedClearLastError(const ScopedClearLastError&) = delete; 34 | ScopedClearLastError& operator=(const ScopedClearLastError&) = delete; 35 | 36 | ~ScopedClearLastError(); 37 | 38 | private: 39 | const unsigned long last_system_error_; 40 | }; 41 | 42 | #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA) 43 | 44 | using ScopedClearLastError = ScopedClearLastErrorBase; 45 | 46 | #endif // BUILDFLAG(IS_WIN) 47 | 48 | } // namespace base 49 | 50 | #endif // MINI_CHROMIUM_BASE_SCOPED_CLEAR_LAST_ERROR_H_ 51 | -------------------------------------------------------------------------------- /base/scoped_clear_last_error_win.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/scoped_clear_last_error.h" 6 | 7 | #include 8 | 9 | namespace base { 10 | 11 | ScopedClearLastError::ScopedClearLastError() 12 | : ScopedClearLastErrorBase(), last_system_error_(GetLastError()) { 13 | SetLastError(0); 14 | } 15 | 16 | ScopedClearLastError::~ScopedClearLastError() { 17 | SetLastError(last_system_error_); 18 | } 19 | 20 | } // namespace base 21 | -------------------------------------------------------------------------------- /base/scoped_generic.h: -------------------------------------------------------------------------------- 1 | // Copyright 2014 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_SCOPED_GENERIC_H_ 6 | #define MINI_CHROMIUM_BASE_SCOPED_GENERIC_H_ 7 | 8 | #include 9 | 10 | #include 11 | 12 | namespace base { 13 | 14 | template 15 | class ScopedGeneric { 16 | private: 17 | struct Data : public Traits { 18 | explicit Data(const T& in) : generic(in) {} 19 | Data(const T& in, const Traits& other) : Traits(other), generic(in) {} 20 | T generic; 21 | }; 22 | 23 | public: 24 | typedef T element_type; 25 | typedef Traits traits_type; 26 | 27 | ScopedGeneric() : data_(traits_type::InvalidValue()) {} 28 | 29 | explicit ScopedGeneric(const element_type& value) : data_(value) {} 30 | 31 | ScopedGeneric(const element_type& value, const traits_type& traits) 32 | : data_(value, traits) { 33 | } 34 | 35 | ScopedGeneric(ScopedGeneric&& rvalue) 36 | : data_(rvalue.release(), rvalue.get_traits()) { 37 | } 38 | 39 | ScopedGeneric(const ScopedGeneric&) = delete; 40 | ScopedGeneric& operator=(const ScopedGeneric&) = delete; 41 | 42 | ~ScopedGeneric() { 43 | FreeIfNecessary(); 44 | } 45 | 46 | ScopedGeneric& operator=(ScopedGeneric&& rvalue) { 47 | reset(rvalue.release()); 48 | return *this; 49 | } 50 | 51 | void reset(const element_type& value = traits_type::InvalidValue()) { 52 | if (data_.generic != traits_type::InvalidValue() && data_.generic == value) 53 | abort(); 54 | FreeIfNecessary(); 55 | data_.generic = value; 56 | } 57 | 58 | void swap(ScopedGeneric& other) { 59 | using std::swap; 60 | swap(static_cast(data_), static_cast(other.data_)); 61 | swap(data_.generic, other.data_.generic); 62 | } 63 | 64 | [[nodiscard]] element_type release() { 65 | element_type old_generic = data_.generic; 66 | data_.generic = traits_type::InvalidValue(); 67 | return old_generic; 68 | } 69 | 70 | const element_type& get() const { return data_.generic; } 71 | 72 | bool is_valid() const { return data_.generic != traits_type::InvalidValue(); } 73 | 74 | bool operator==(const element_type& value) const { 75 | return data_.generic == value; 76 | } 77 | bool operator!=(const element_type& value) const { 78 | return data_.generic != value; 79 | } 80 | 81 | Traits& get_traits() { return data_; } 82 | const Traits& get_traits() const { return data_; } 83 | 84 | private: 85 | void FreeIfNecessary() { 86 | if (data_.generic != traits_type::InvalidValue()) { 87 | data_.Free(data_.generic); 88 | data_.generic = traits_type::InvalidValue(); 89 | } 90 | } 91 | 92 | template bool operator==( 93 | const ScopedGeneric& p2) const; 94 | template bool operator!=( 95 | const ScopedGeneric& p2) const; 96 | 97 | Data data_; 98 | }; 99 | 100 | template 101 | void swap(const ScopedGeneric& a, 102 | const ScopedGeneric& b) { 103 | a.swap(b); 104 | } 105 | 106 | template 107 | bool operator==(const T& value, const ScopedGeneric& scoped) { 108 | return value == scoped.get(); 109 | } 110 | 111 | template 112 | bool operator!=(const T& value, const ScopedGeneric& scoped) { 113 | return value != scoped.get(); 114 | } 115 | 116 | } // namespace base 117 | 118 | #endif // MINI_CHROMIUM_BASE_SCOPED_GENERIC_H_ 119 | -------------------------------------------------------------------------------- /base/strings/pattern.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/strings/pattern.h" 6 | 7 | #include "base/third_party/icu/icu_utf.h" 8 | 9 | namespace base { 10 | 11 | namespace { 12 | 13 | constexpr bool IsWildcard(base_icu::UChar32 character) { 14 | return character == '*' || character == '?'; 15 | } 16 | 17 | // Searches for the next subpattern of |pattern| in |string|, up to the given 18 | // |maximum_distance|. The subpattern extends from the start of |pattern| up to 19 | // the first wildcard character (or the end of the string). If the value of 20 | // |maximum_distance| is negative, the maximum distance is considered infinite. 21 | template 22 | constexpr bool SearchForChars(const CHAR** pattern, 23 | const CHAR* pattern_end, 24 | const CHAR** string, 25 | const CHAR* string_end, 26 | int maximum_distance, 27 | NEXT next) { 28 | const CHAR* pattern_start = *pattern; 29 | const CHAR* string_start = *string; 30 | bool escape = false; 31 | while (true) { 32 | if (*pattern == pattern_end) { 33 | // If this is the end of the pattern, only accept the end of the string; 34 | // anything else falls through to the mismatch case. 35 | if (*string == string_end) 36 | return true; 37 | } else { 38 | // If we have found a wildcard, we're done. 39 | if (!escape && IsWildcard(**pattern)) 40 | return true; 41 | 42 | // Check if the escape character is found. If so, skip it and move to the 43 | // next character. 44 | if (!escape && **pattern == '\\') { 45 | escape = true; 46 | next(pattern, pattern_end); 47 | continue; 48 | } 49 | 50 | escape = false; 51 | 52 | if (*string == string_end) 53 | return false; 54 | 55 | // Check if the chars match, if so, increment the ptrs. 56 | const CHAR* pattern_next = *pattern; 57 | const CHAR* string_next = *string; 58 | base_icu::UChar32 pattern_char = next(&pattern_next, pattern_end); 59 | if (pattern_char == next(&string_next, string_end) && 60 | pattern_char != CBU_SENTINEL) { 61 | *pattern = pattern_next; 62 | *string = string_next; 63 | continue; 64 | } 65 | } 66 | 67 | // Mismatch. If we have reached the maximum distance, return false, 68 | // otherwise restart at the beginning of the pattern with the next character 69 | // in the string. 70 | // TODO(bauerb): This is a naive implementation of substring search, which 71 | // could be implemented with a more efficient algorithm, e.g. 72 | // Knuth-Morris-Pratt (at the expense of requiring preprocessing). 73 | if (maximum_distance == 0) 74 | return false; 75 | 76 | // Because unlimited distance is represented as -1, this will never reach 0 77 | // and therefore fail the match above. 78 | maximum_distance--; 79 | *pattern = pattern_start; 80 | next(&string_start, string_end); 81 | *string = string_start; 82 | } 83 | } 84 | 85 | // Consumes consecutive wildcard characters (? or *). Returns the maximum number 86 | // of characters matched by the sequence of wildcards, or -1 if the wildcards 87 | // match an arbitrary number of characters (which is the case if it contains at 88 | // least one *). 89 | template 90 | constexpr int EatWildcards(const CHAR** pattern, const CHAR* end, NEXT next) { 91 | int num_question_marks = 0; 92 | bool has_asterisk = false; 93 | while (*pattern != end) { 94 | if (**pattern == '?') { 95 | num_question_marks++; 96 | } else if (**pattern == '*') { 97 | has_asterisk = true; 98 | } else { 99 | break; 100 | } 101 | 102 | next(pattern, end); 103 | } 104 | return has_asterisk ? -1 : num_question_marks; 105 | } 106 | 107 | template 108 | constexpr bool MatchPatternT(const CHAR* eval, 109 | const CHAR* eval_end, 110 | const CHAR* pattern, 111 | const CHAR* pattern_end, 112 | NEXT next) { 113 | do { 114 | int maximum_wildcard_length = EatWildcards(&pattern, pattern_end, next); 115 | if (!SearchForChars(&pattern, pattern_end, &eval, eval_end, 116 | maximum_wildcard_length, next)) { 117 | return false; 118 | } 119 | } while (pattern != pattern_end); 120 | return true; 121 | } 122 | 123 | struct NextCharUTF8 { 124 | base_icu::UChar32 operator()(const char** p, const char* end) { 125 | base_icu::UChar32 c; 126 | int offset = 0; 127 | CBU8_NEXT(reinterpret_cast(*p), offset, end - *p, c); 128 | *p += offset; 129 | return c; 130 | } 131 | }; 132 | 133 | struct NextCharUTF16 { 134 | base_icu::UChar32 operator()(const char16_t** p, const char16_t* end) { 135 | base_icu::UChar32 c; 136 | int offset = 0; 137 | CBU16_NEXT(*p, offset, end - *p, c); 138 | *p += offset; 139 | return c; 140 | } 141 | }; 142 | 143 | } // namespace 144 | 145 | bool MatchPattern(StringPiece eval, StringPiece pattern) { 146 | return MatchPatternT(eval.data(), eval.data() + eval.size(), pattern.data(), 147 | pattern.data() + pattern.size(), NextCharUTF8()); 148 | } 149 | 150 | bool MatchPattern(StringPiece16 eval, StringPiece16 pattern) { 151 | return MatchPatternT(eval.data(), eval.data() + eval.size(), pattern.data(), 152 | pattern.data() + pattern.size(), NextCharUTF16()); 153 | } 154 | 155 | } // namespace base 156 | -------------------------------------------------------------------------------- /base/strings/pattern.h: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef BASE_STRINGS_PATTERN_H_ 6 | #define BASE_STRINGS_PATTERN_H_ 7 | 8 | #include "base/strings/string_piece.h" 9 | 10 | namespace base { 11 | 12 | // Returns true if the |string| passed in matches the |pattern|. The pattern 13 | // string can contain wildcards like * and ?. 14 | // 15 | // The backslash character (\) is an escape character for * and ?. 16 | // ? matches 0 or 1 character, while * matches 0 or more characters. 17 | bool MatchPattern(StringPiece string, StringPiece pattern); 18 | bool MatchPattern(StringPiece16 string, StringPiece16 pattern); 19 | 20 | } // namespace base 21 | 22 | #endif // BASE_STRINGS_PATTERN_H_ 23 | -------------------------------------------------------------------------------- /base/strings/strcat.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/strings/strcat.h" 6 | 7 | #include 8 | 9 | #include "base/strings/strcat_internal.h" 10 | 11 | namespace base { 12 | 13 | std::string StrCat(span pieces) { 14 | return internal::StrCatT(pieces); 15 | } 16 | 17 | } // namespace base 18 | -------------------------------------------------------------------------------- /base/strings/strcat.h: -------------------------------------------------------------------------------- 1 | // Copyright 2017 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef BASE_STRINGS_STRCAT_H_ 6 | #define BASE_STRINGS_STRCAT_H_ 7 | 8 | #include 9 | 10 | #include "base/containers/span.h" 11 | #include "base/strings/string_piece.h" 12 | #include "build/build_config.h" 13 | 14 | #if BUILDFLAG(IS_WIN) 15 | // Guard against conflict with Win32 API StrCat macro: 16 | // check StrCat wasn't and will not be redefined. 17 | #define StrCat StrCat 18 | #endif 19 | 20 | namespace base { 21 | 22 | // StrCat ---------------------------------------------------------------------- 23 | // 24 | // StrCat is a function to perform concatenation on a sequence of strings. 25 | // It is preferrable to a sequence of "a + b + c" because it is both faster and 26 | // generates less code. 27 | // 28 | // std::string result = base::StrCat({"foo ", result, "\nfoo ", bar}); 29 | // 30 | // MORE INFO 31 | // 32 | // StrCat can see all arguments at once, so it can allocate one return buffer 33 | // of exactly the right size and copy once, as opposed to a sequence of 34 | // operator+ which generates a series of temporary strings, copying as it goes. 35 | // And by using StringPiece arguments, StrCat can avoid creating temporary 36 | // string objects for char* constants. 37 | // 38 | // ALTERNATIVES 39 | // 40 | // Internal Google / Abseil has a similar StrCat function. That version takes 41 | // an overloaded number of arguments instead of initializer list (overflowing 42 | // to initializer list for many arguments). We don't have any legacy 43 | // requirements and using only initializer_list is simpler and generates 44 | // roughly the same amount of code at the call sites. 45 | // 46 | // Abseil's StrCat also allows numbers by using an intermediate class that can 47 | // be implicitly constructed from either a string or various number types. This 48 | // class formats the numbers into a static buffer for increased performance, 49 | // and the call sites look nice. 50 | // 51 | // As-written Abseil's helper class for numbers generates slightly more code 52 | // than the raw StringPiece version. We can de-inline the helper class' 53 | // constructors which will cause the StringPiece constructors to be de-inlined 54 | // for this call and generate slightly less code. This is something we can 55 | // explore more in the future. 56 | 57 | [[nodiscard]] std::string StrCat(span pieces); 58 | 59 | // Initializer list forwards to the array version. 60 | inline std::string StrCat(std::initializer_list pieces) { 61 | return StrCat(make_span(pieces)); 62 | } 63 | 64 | } // namespace base 65 | 66 | #endif // BASE_STRINGS_STRCAT_H_ 67 | -------------------------------------------------------------------------------- /base/strings/strcat_internal.h: -------------------------------------------------------------------------------- 1 | // Copyright 2020 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef BASE_STRINGS_STRCAT_INTERNAL_H_ 6 | #define BASE_STRINGS_STRCAT_INTERNAL_H_ 7 | 8 | #include 9 | 10 | #include "base/containers/span.h" 11 | #include "base/template_util.h" 12 | 13 | namespace base { 14 | 15 | namespace internal { 16 | 17 | // Optimized version of `std::basic_string::resize()` that skips zero 18 | // initialization of appended characters. Reading from the newly allocated 19 | // characters results in undefined behavior if they are not explicitly 20 | // initialized afterwards. Currently proposed for standardization as 21 | // std::basic_string::resize_and_overwrite: https://wg21.link/P1072R6 22 | template 23 | auto Resize(std::basic_string& str, size_t total_size, priority_tag<1>) 24 | -> decltype(str.__resize_default_init(total_size)) { 25 | str.__resize_default_init(total_size); 26 | } 27 | 28 | // Fallback to regular std::basic_string::resize() if invoking 29 | // __resize_default_init is ill-formed. 30 | template 31 | void Resize(std::basic_string& str, size_t total_size, priority_tag<0>) { 32 | str.resize(total_size); 33 | } 34 | 35 | // Appends `pieces` to `dest`. Instead of simply calling `dest.append()` 36 | // `pieces.size()` times, this method first resizes `dest` to be of the desired 37 | // size, and then appends each piece via `std::char_traits::copy`. This achieves 38 | // two goals: 39 | // 1) Allocating the desired size all at once avoids other allocations that 40 | // could happen if intermediate allocations did not reserve enough capacity. 41 | // 2) Invoking std::char_traits::copy instead of std::basic_string::append 42 | // avoids having to write the terminating '\0' character n times. 43 | template 44 | void StrAppendT(std::basic_string& dest, span pieces) { 45 | const size_t initial_size = dest.size(); 46 | size_t total_size = initial_size; 47 | for (const auto& cur : pieces) 48 | total_size += cur.size(); 49 | 50 | // Note: As opposed to `reserve()` calling `resize()` with an argument smaller 51 | // than the current `capacity()` does not result in the string releasing spare 52 | // capacity. Furthermore, common std::string implementations apply a geometric 53 | // growth strategy if the current capacity is not sufficient for the newly 54 | // added characters. Since this codepath is also triggered by `resize()`, we 55 | // don't have to manage the std::string's capacity ourselves here to avoid 56 | // performance hits in case `StrAppend()` gets called in a loop. 57 | Resize(dest, total_size, priority_tag<1>()); 58 | CharT* dest_char = &dest[initial_size]; 59 | for (const auto& cur : pieces) { 60 | std::char_traits::copy(dest_char, cur.data(), cur.size()); 61 | dest_char += cur.size(); 62 | } 63 | } 64 | 65 | template 66 | auto StrCatT(span pieces) { 67 | std::basic_string result; 68 | StrAppendT(result, pieces); 69 | return result; 70 | } 71 | 72 | } // namespace internal 73 | 74 | } // namespace base 75 | 76 | #endif // BASE_STRINGS_STRCAT_INTERNAL_H_ 77 | -------------------------------------------------------------------------------- /base/strings/string_number_conversions.h: -------------------------------------------------------------------------------- 1 | // Copyright 2010 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_STRINGS_STRING_NUMBER_CONVERSIONS_H_ 6 | #define MINI_CHROMIUM_BASE_STRINGS_STRING_NUMBER_CONVERSIONS_H_ 7 | 8 | #include 9 | 10 | #include 11 | #include 12 | 13 | #include "base/strings/string_piece.h" 14 | 15 | namespace base { 16 | 17 | bool StringToInt(const StringPiece& input, int* output); 18 | bool StringToUint(const StringPiece& input, unsigned int* output); 19 | bool StringToInt64(const StringPiece& input, int64_t* output); 20 | bool StringToUint64(const StringPiece& input, uint64_t* output); 21 | bool StringToSizeT(const StringPiece& input, size_t* output); 22 | 23 | bool HexStringToInt(const StringPiece& input, int* output); 24 | bool HexStringToBytes(const std::string& input, std::vector* output); 25 | 26 | } // namespace base 27 | 28 | #endif // MINI_CHROMIUM_BASE_STRINGS_STRING_NUMBER_CONVERSIONS_H_ 29 | -------------------------------------------------------------------------------- /base/strings/string_util.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/strings/string_util.h" 6 | 7 | namespace base { 8 | 9 | // The following code is compatible with the OpenBSD lcpy interface. See: 10 | // http://www.gratisoft.us/todd/papers/strlcpy.html 11 | // ftp://ftp.openbsd.org/pub/OpenBSD/src/lib/libc/string/{wcs,str}lcpy.c 12 | 13 | namespace { 14 | 15 | template 16 | size_t lcpyT(CHAR* dst, const CHAR* src, size_t dst_size) { 17 | for (size_t i = 0; i < dst_size; ++i) { 18 | if ((dst[i] = src[i]) == 0) // We hit and copied the terminating NULL. 19 | return i; 20 | } 21 | 22 | // We were left off at dst_size. We over copied 1 byte. Null terminate. 23 | if (dst_size != 0) 24 | dst[dst_size - 1] = 0; 25 | 26 | // Count the rest of the |src|, and return it's length in characters. 27 | while (src[dst_size]) ++dst_size; 28 | return dst_size; 29 | } 30 | 31 | } // namespace 32 | 33 | size_t strlcpy(char* dst, const char* src, size_t dst_size) { 34 | return lcpyT(dst, src, dst_size); 35 | } 36 | size_t wcslcpy(wchar_t* dst, const wchar_t* src, size_t dst_size) { 37 | return lcpyT(dst, src, dst_size); 38 | } 39 | 40 | } // namespace base 41 | -------------------------------------------------------------------------------- /base/strings/string_util.h: -------------------------------------------------------------------------------- 1 | // Copyright 2006-2008 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_STRINGS_STRING_UTIL_H_ 6 | #define MINI_CHROMIUM_BASE_STRINGS_STRING_UTIL_H_ 7 | 8 | #include "base/check_op.h" 9 | #include "base/compiler_specific.h" 10 | #include "build/build_config.h" 11 | 12 | namespace base { 13 | 14 | int vsnprintf(char* buffer, size_t size, const char* format, va_list arguments) 15 | PRINTF_FORMAT(3, 0); 16 | 17 | size_t strlcpy(char* dst, const char* src, size_t dst_size); 18 | size_t wcslcpy(wchar_t* dst, const wchar_t* src, size_t dst_size); 19 | 20 | // Determines the type of ASCII character, independent of locale (the C 21 | // library versions will change based on locale). 22 | template 23 | inline bool IsAsciiWhitespace(Char c) { 24 | return c == ' ' || (c >= 0x09 && c <= 0x0d); 25 | } 26 | template 27 | inline bool IsAsciiDigit(Char c) { 28 | return c >= '0' && c <= '9'; 29 | } 30 | 31 | template 32 | inline typename string_type::value_type* WriteInto(string_type* str, 33 | size_t length_with_null) { 34 | DCHECK_NE(0u, length_with_null); 35 | str->reserve(length_with_null); 36 | str->resize(length_with_null - 1); 37 | 38 | if (length_with_null <= 1) 39 | return NULL; 40 | 41 | return &((*str)[0]); 42 | } 43 | 44 | } // namespace base 45 | 46 | #if BUILDFLAG(IS_WIN) 47 | #include "base/strings/string_util_win.h" 48 | #elif BUILDFLAG(IS_POSIX) 49 | #include "base/strings/string_util_posix.h" 50 | #endif 51 | 52 | #endif // MINI_CHROMIUM_BASE_STRINGS_STRING_UTIL_H_ 53 | -------------------------------------------------------------------------------- /base/strings/string_util_posix.h: -------------------------------------------------------------------------------- 1 | // Copyright 2006-2008 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_STRINGS_STRING_UTIL_POSIX_H_ 6 | #define MINI_CHROMIUM_BASE_STRINGS_STRING_UTIL_POSIX_H_ 7 | 8 | #include 9 | #include 10 | 11 | namespace base { 12 | 13 | inline int vsnprintf(char* buffer, 14 | size_t size, 15 | const char* format, va_list arguments) { 16 | return ::vsnprintf(buffer, size, format, arguments); 17 | } 18 | 19 | // Chromium code style is to not use malloc'd strings; this is only for use 20 | // for interaction with APIs that require it. 21 | inline char* strdup(const char* str) { 22 | return ::strdup(str); 23 | } 24 | 25 | } // namespace base 26 | 27 | #endif // MINI_CHROMIUM_BASE_STRINGS_STRING_UTIL_POSIX_H_ 28 | -------------------------------------------------------------------------------- /base/strings/string_util_win.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/strings/string_util.h" 6 | 7 | #include 8 | 9 | namespace base { 10 | 11 | int vsnprintf(char* buffer, 12 | size_t size, 13 | const char* format, 14 | va_list arguments) { 15 | int length = _vsprintf_p(buffer, size, format, arguments); 16 | if (length < 0) { 17 | if (size > 0) 18 | buffer[0] = 0; 19 | return _vscprintf_p(format, arguments); 20 | } 21 | return length; 22 | } 23 | 24 | } // namespace base 25 | -------------------------------------------------------------------------------- /base/strings/string_util_win.h: -------------------------------------------------------------------------------- 1 | // Copyright 2013 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef BASE_STRINGS_STRING_UTIL_WIN_H_ 6 | #define BASE_STRINGS_STRING_UTIL_WIN_H_ 7 | 8 | #include 9 | 10 | namespace base { 11 | 12 | // Chromium code style is to not use malloc'd strings; this is only for use 13 | // for interaction with APIs that require it. 14 | inline char* strdup(const char* str) { 15 | return _strdup(str); 16 | } 17 | 18 | } // namespace base 19 | 20 | #endif // BASE_STRINGS_STRING_UTIL_WIN_H_ 21 | -------------------------------------------------------------------------------- /base/strings/stringprintf.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2010 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/strings/stringprintf.h" 6 | 7 | #include 8 | 9 | #include 10 | 11 | #include "base/logging.h" 12 | #include "base/scoped_clear_last_error.h" 13 | #include "base/strings/string_util.h" 14 | #include "build/build_config.h" 15 | 16 | namespace base { 17 | 18 | namespace { 19 | 20 | inline int vsnprintfT(char* buffer, 21 | size_t buf_size, 22 | const char* format, 23 | va_list argptr) { 24 | return base::vsnprintf(buffer, buf_size, format, argptr); 25 | } 26 | 27 | template 28 | static void StringAppendVT(StringType* dst, 29 | const typename StringType::value_type* format, 30 | va_list ap) { 31 | typename StringType::value_type stack_buf[1024]; 32 | 33 | va_list ap_copy; 34 | va_copy(ap_copy, ap); 35 | 36 | ScopedClearLastError clear_errno; 37 | int result = vsnprintfT(stack_buf, std::size(stack_buf), format, ap_copy); 38 | va_end(ap_copy); 39 | 40 | if (result >= 0 && result < static_cast(std::size(stack_buf))) { 41 | dst->append(stack_buf, result); 42 | return; 43 | } 44 | 45 | // Repeatedly increase buffer size until it fits. 46 | size_t mem_length = std::size(stack_buf); 47 | while (true) { 48 | if (result < 0) { 49 | #if !BUILDFLAG(IS_WIN) 50 | // On Windows, vsnprintfT always returns the number of characters in a 51 | // fully-formatted string, so if we reach this point, something else is 52 | // wrong and no amount of buffer-doubling is going to fix it. 53 | if (errno != 0 && errno != EOVERFLOW) 54 | #endif 55 | { 56 | DLOG(WARNING) << "Unable to printf the requested string due to error."; 57 | return; 58 | } 59 | #if !BUILDFLAG(IS_WIN) 60 | // Try doubling the buffer size. 61 | mem_length *= 2; 62 | #endif 63 | } else { 64 | // We need exactly "result + 1" characters. 65 | mem_length = result + 1; 66 | } 67 | 68 | if (mem_length > 32 * 1024 * 1024) { 69 | // That should be plenty, don't try anything larger. This protects 70 | // against huge allocations when using vsnprintfT implementations that 71 | // return -1 for reasons other than overflow without setting errno. 72 | DLOG(WARNING) << "Unable to printf the requested string due to size."; 73 | return; 74 | } 75 | 76 | std::vector mem_buf(mem_length); 77 | 78 | // NOTE: You can only use a va_list once. Since we're in a while loop, we 79 | // need to make a new copy each time so we don't use up the original. 80 | va_copy(ap_copy, ap); 81 | result = vsnprintfT(&mem_buf[0], mem_length, format, ap_copy); 82 | va_end(ap_copy); 83 | 84 | if ((result >= 0) && static_cast(result) < mem_length) { 85 | // It fit. 86 | dst->append(&mem_buf[0], result); 87 | return; 88 | } 89 | } 90 | } 91 | 92 | } // namespace 93 | 94 | std::string StringPrintf(const char* format, ...) { 95 | va_list ap; 96 | va_start(ap, format); 97 | std::string result; 98 | StringAppendV(&result, format, ap); 99 | va_end(ap); 100 | return result; 101 | } 102 | 103 | void StringAppendV(std::string* dst, const char* format, va_list ap) { 104 | StringAppendVT(dst, format, ap); 105 | } 106 | 107 | } // namespace base 108 | -------------------------------------------------------------------------------- /base/strings/stringprintf.h: -------------------------------------------------------------------------------- 1 | // Copyright 2010 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_STRINGS_STRINGPRINTF_H_ 6 | #define MINI_CHROMIUM_BASE_STRINGS_STRINGPRINTF_H_ 7 | 8 | #include 9 | 10 | #include 11 | 12 | #include "base/compiler_specific.h" 13 | 14 | namespace base { 15 | 16 | std::string StringPrintf(const char* format, ...) 17 | PRINTF_FORMAT(1, 2); 18 | void StringAppendV(std::string* dst, const char* format, va_list ap) 19 | PRINTF_FORMAT(2, 0); 20 | 21 | } // namespace base 22 | 23 | #endif // MINI_CHROMIUM_BASE_STRINGS_STRINGPRINTF_H_ 24 | -------------------------------------------------------------------------------- /base/strings/sys_string_conversions.h: -------------------------------------------------------------------------------- 1 | // Copyright 2008 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_STRINGS_SYS_STRING_CONVERSIONS_H_ 6 | #define MINI_CHROMIUM_BASE_STRINGS_SYS_STRING_CONVERSIONS_H_ 7 | 8 | #include "build/build_config.h" 9 | 10 | #if BUILDFLAG(IS_APPLE) 11 | 12 | #include 13 | 14 | #include 15 | 16 | #if defined(__OBJC__) 17 | #import 18 | #else 19 | class NSString; 20 | #endif 21 | 22 | namespace base { 23 | 24 | std::string SysCFStringRefToUTF8(CFStringRef ref); 25 | std::string SysNSStringToUTF8(NSString* nsstring); 26 | CFStringRef SysUTF8ToCFStringRef(const std::string& utf8); 27 | NSString* SysUTF8ToNSString(const std::string& utf8); 28 | 29 | } // namespace base 30 | 31 | #endif // BUILDFLAG(IS_APPLE) 32 | 33 | #endif // MINI_CHROMIUM_BASE_STRINGS_SYS_STRING_CONVERSIONS_H_ 34 | -------------------------------------------------------------------------------- /base/strings/sys_string_conversions_mac.mm: -------------------------------------------------------------------------------- 1 | // Copyright 2008 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/strings/sys_string_conversions.h" 6 | 7 | #include "base/apple/bridging.h" 8 | #include "base/check_op.h" 9 | 10 | namespace base { 11 | 12 | namespace { 13 | 14 | const CFStringEncoding kNarrowStringEncoding = kCFStringEncodingUTF8; 15 | 16 | template 17 | StringType CFStringToSTLStringWithEncodingT(CFStringRef cfstring, 18 | CFStringEncoding encoding) { 19 | CFIndex length = CFStringGetLength(cfstring); 20 | if (length == 0) { 21 | return StringType(); 22 | } 23 | 24 | CFRange whole_string = CFRangeMake(0, length); 25 | CFIndex out_size; 26 | CFIndex converted = CFStringGetBytes(cfstring, 27 | whole_string, 28 | encoding, 29 | 0, 30 | FALSE, 31 | NULL, 32 | 0, 33 | &out_size); 34 | if (converted == 0 || out_size == 0) { 35 | return StringType(); 36 | } 37 | 38 | DCHECK_EQ(out_size % sizeof(typename StringType::value_type), 0u); 39 | typename StringType::size_type elements = 40 | out_size * sizeof(UInt8) / sizeof(typename StringType::value_type); 41 | StringType out(elements, typename StringType::value_type()); 42 | 43 | converted = CFStringGetBytes(cfstring, 44 | whole_string, 45 | encoding, 46 | 0, 47 | FALSE, 48 | reinterpret_cast(&out[0]), 49 | out_size, 50 | NULL); 51 | if (converted == 0) { 52 | return StringType(); 53 | } 54 | 55 | return out; 56 | } 57 | 58 | template 59 | static CFStringRef STLStringToCFStringWithEncodingsT( 60 | const StringType& in, 61 | CFStringEncoding in_encoding) { 62 | typename StringType::size_type in_length = in.length(); 63 | if (in_length == 0) { 64 | return CFSTR(""); 65 | } 66 | 67 | return CFStringCreateWithBytes(kCFAllocatorDefault, 68 | reinterpret_cast(in.c_str()), 69 | in_length * 70 | sizeof(typename StringType::value_type), 71 | in_encoding, 72 | FALSE); 73 | } 74 | 75 | } // namespace 76 | 77 | std::string SysCFStringRefToUTF8(CFStringRef ref) { 78 | return CFStringToSTLStringWithEncodingT(ref, 79 | kNarrowStringEncoding); 80 | } 81 | 82 | std::string SysNSStringToUTF8(NSString *nsstring) { 83 | if (!nsstring) { 84 | return std::string(); 85 | } 86 | return SysCFStringRefToUTF8(apple::NSToCFPtrCast(nsstring)); 87 | } 88 | 89 | CFStringRef SysUTF8ToCFStringRef(const std::string& utf8) { 90 | return STLStringToCFStringWithEncodingsT(utf8, kNarrowStringEncoding); 91 | } 92 | 93 | NSString* SysUTF8ToNSString(const std::string& utf8) { 94 | return base::apple::CFToNSOwnershipCast(SysUTF8ToCFStringRef(utf8)); 95 | } 96 | 97 | } // namespace base 98 | -------------------------------------------------------------------------------- /base/strings/utf_string_conversion_utils.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/strings/utf_string_conversion_utils.h" 6 | 7 | #include "base/third_party/icu/icu_utf.h" 8 | 9 | namespace base { 10 | 11 | namespace { 12 | 13 | // Appends `code_point` to `*output`. Requires `*output` to be a UTF16 string. 14 | // Returns the number of code units written. 15 | template 16 | size_t WriteUTF16Character(uint32_t code_point, StringT* output) { 17 | using CharT = typename StringT::value_type; 18 | static_assert(sizeof(CharT) == 2, "Error: *output is not a UTF16 string"); 19 | if (CBU16_LENGTH(code_point) == 1) { 20 | output->push_back(static_cast(code_point)); 21 | return 1; 22 | } 23 | size_t char_offset = output->length(); 24 | output->resize(char_offset + CBU16_MAX_LENGTH); 25 | CBU16_APPEND_UNSAFE(&(*output)[0], char_offset, code_point); 26 | return CBU16_MAX_LENGTH; 27 | } 28 | 29 | } // namespace 30 | 31 | bool ReadUnicodeCharacter(const char* src, 32 | int32_t src_len, 33 | int32_t* char_index, 34 | uint32_t* code_point_out) { 35 | base_icu::UChar32 code_point; 36 | CBU8_NEXT(reinterpret_cast(src), *char_index, src_len, 37 | code_point); 38 | *code_point_out = code_point; 39 | 40 | // The ICU macro above moves to the next char, we want to point to the last 41 | // char consumed. 42 | (*char_index)--; 43 | 44 | return IsValidCodepoint(code_point); 45 | } 46 | 47 | bool ReadUnicodeCharacter(const char16_t* src, 48 | int32_t src_len, 49 | int32_t* char_index, 50 | uint32_t* code_point) { 51 | if (CBU16_IS_SURROGATE(src[*char_index])) { 52 | if (!CBU16_IS_SURROGATE_LEAD(src[*char_index]) || 53 | *char_index + 1 >= src_len || 54 | !CBU16_IS_TRAIL(src[*char_index + 1])) { 55 | return false; 56 | } 57 | 58 | *code_point = CBU16_GET_SUPPLEMENTARY(src[*char_index], 59 | src[*char_index + 1]); 60 | (*char_index)++; 61 | } else { 62 | *code_point = src[*char_index]; 63 | } 64 | 65 | return IsValidCodepoint(*code_point); 66 | } 67 | 68 | size_t WriteUnicodeCharacter(uint32_t code_point, std::string* output) { 69 | if (code_point <= 0x7f) { 70 | output->push_back(static_cast(code_point)); 71 | return 1; 72 | } 73 | 74 | size_t char_offset = output->length(); 75 | size_t original_char_offset = char_offset; 76 | output->resize(char_offset + CBU8_MAX_LENGTH); 77 | 78 | CBU8_APPEND_UNSAFE(&(*output)[0], char_offset, code_point); 79 | 80 | output->resize(char_offset); 81 | return char_offset - original_char_offset; 82 | } 83 | 84 | size_t WriteUnicodeCharacter(uint32_t code_point, std::u16string* output) { 85 | return WriteUTF16Character(code_point, output); 86 | } 87 | 88 | template 89 | void PrepareForUTF8Output(const CHAR* src, 90 | size_t src_len, 91 | std::string* output) { 92 | output->clear(); 93 | if (src_len == 0) 94 | return; 95 | if (src[0] < 0x80) { 96 | output->reserve(src_len); 97 | } else { 98 | output->reserve(src_len * 3); 99 | } 100 | } 101 | 102 | template void PrepareForUTF8Output(const wchar_t*, size_t, std::string*); 103 | template void PrepareForUTF8Output(const char16_t*, size_t, std::string*); 104 | 105 | template 106 | void PrepareForUTF16Or32Output(const char* src, 107 | size_t src_len, 108 | STRING* output) { 109 | output->clear(); 110 | if (src_len == 0) 111 | return; 112 | if (static_cast(src[0]) < 0x80) { 113 | output->reserve(src_len); 114 | } else { 115 | output->reserve(src_len / 2); 116 | } 117 | } 118 | 119 | template void PrepareForUTF16Or32Output(const char*, size_t, std::u16string*); 120 | 121 | } // namespace base 122 | -------------------------------------------------------------------------------- /base/strings/utf_string_conversion_utils.h: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_STRINGS_UTF_STRING_CONVERSION_UTILS_H_ 6 | #define MINI_CHROMIUM_BASE_STRINGS_UTF_STRING_CONVERSION_UTILS_H_ 7 | 8 | #include 9 | 10 | #include 11 | 12 | namespace base { 13 | 14 | inline bool IsValidCodepoint(uint32_t code_point) { 15 | return code_point < 0xD800u || 16 | (code_point >= 0xE000u && code_point <= 0x10FFFFu); 17 | } 18 | 19 | bool ReadUnicodeCharacter(const char* src, 20 | int32_t src_len, 21 | int32_t* char_index, 22 | uint32_t* code_point_out); 23 | 24 | bool ReadUnicodeCharacter(const char16_t* src, 25 | int32_t src_len, 26 | int32_t* char_index, 27 | uint32_t* code_point); 28 | 29 | size_t WriteUnicodeCharacter(uint32_t code_point, std::string* output); 30 | 31 | size_t WriteUnicodeCharacter(uint32_t code_point, std::u16string* output); 32 | 33 | template 34 | void PrepareForUTF8Output(const CHAR* src, size_t src_len, std::string* output); 35 | 36 | template 37 | void PrepareForUTF16Or32Output(const char* src, size_t src_len, STRING* output); 38 | 39 | } // namespace base 40 | 41 | #endif // MINI_CHROMIUM_BASE_STRINGS_UTF_STRING_CONVERSION_UTILS_H_ 42 | -------------------------------------------------------------------------------- /base/strings/utf_string_conversions.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/strings/utf_string_conversions.h" 6 | 7 | #include 8 | 9 | #include 10 | #include 11 | 12 | #include "base/strings/utf_string_conversion_utils.h" 13 | #include "build/build_config.h" 14 | 15 | namespace { 16 | 17 | template 18 | bool ConvertUnicode(const SRC_CHAR* src, 19 | size_t src_len, 20 | DEST_STRING* output) { 21 | bool success = true; 22 | int32_t src_len32 = static_cast(src_len); 23 | for (int32_t i = 0; i < src_len32; i++) { 24 | uint32_t code_point; 25 | if (base::ReadUnicodeCharacter(src, src_len32, &i, &code_point)) { 26 | base::WriteUnicodeCharacter(code_point, output); 27 | } else { 28 | base::WriteUnicodeCharacter(0xFFFD, output); 29 | success = false; 30 | } 31 | } 32 | 33 | return success; 34 | } 35 | 36 | } // namespace 37 | 38 | namespace base { 39 | 40 | bool UTF8ToUTF16(const char* src, size_t src_len, std::u16string* output) { 41 | base::PrepareForUTF16Or32Output(src, src_len, output); 42 | return ConvertUnicode(src, src_len, output); 43 | } 44 | 45 | std::u16string UTF8ToUTF16(const StringPiece& utf8) { 46 | std::u16string ret; 47 | UTF8ToUTF16(utf8.data(), utf8.length(), &ret); 48 | return ret; 49 | } 50 | 51 | bool UTF16ToUTF8(const char16_t* src, size_t src_len, std::string* output) { 52 | base::PrepareForUTF8Output(src, src_len, output); 53 | return ConvertUnicode(src, src_len, output); 54 | } 55 | 56 | std::string UTF16ToUTF8(const StringPiece16& utf16) { 57 | std::string ret; 58 | UTF16ToUTF8(utf16.data(), utf16.length(), &ret); 59 | return ret; 60 | } 61 | 62 | #if defined(WCHAR_T_IS_16_BIT) 63 | std::string WideToUTF8(std::wstring_view wide) { 64 | std::string ret; 65 | UTF16ToUTF8( 66 | reinterpret_cast(wide.data()), wide.size(), &ret); 67 | return ret; 68 | } 69 | 70 | std::wstring UTF8ToWide(StringPiece utf8) { 71 | std::u16string utf16 = UTF8ToUTF16(utf8); 72 | return std::wstring(reinterpret_cast(utf16.data()), 73 | utf16.size()); 74 | } 75 | #endif // defined(WCHAR_T_IS_16_BIT) 76 | 77 | } // namespace 78 | -------------------------------------------------------------------------------- /base/strings/utf_string_conversions.h: -------------------------------------------------------------------------------- 1 | // Copyright 2009 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_STRINGS_UTF_STRING_CONVERSIONS_H_ 6 | #define MINI_CHROMIUM_BASE_STRINGS_UTF_STRING_CONVERSIONS_H_ 7 | 8 | #include 9 | #include 10 | 11 | #include "base/strings/string_piece.h" 12 | #include "build/build_config.h" 13 | 14 | namespace base { 15 | 16 | bool UTF8ToUTF16(const char* src, size_t src_len, std::u16string* output); 17 | std::u16string UTF8ToUTF16(const StringPiece& utf8); 18 | bool UTF16ToUTF8(const char16_t* src, size_t src_len, std::string* output); 19 | std::string UTF16ToUTF8(const StringPiece16& utf16); 20 | 21 | #if defined(WCHAR_T_IS_16_BIT) 22 | std::string WideToUTF8(std::wstring_view wide); 23 | std::wstring UTF8ToWide(StringPiece utf8); 24 | #endif // defined(WCHAR_T_IS_16_BIT) 25 | 26 | } // namespace 27 | 28 | #endif // MINI_CHROMIUM_BASE_STRINGS_UTF_STRING_CONVERSIONS_H_ 29 | -------------------------------------------------------------------------------- /base/synchronization/condition_variable.h: -------------------------------------------------------------------------------- 1 | // Copyright 2006-2008 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | // ConditionVariable wraps pthreads condition variable synchronization or, on 6 | // Windows, simulates it. This functionality is very helpful for having 7 | // several threads wait for an event, as is common with a thread pool managed 8 | // by a master. The meaning of such an event in the (worker) thread pool 9 | // scenario is that additional tasks are now available for processing. It is 10 | // used in Chrome in the DNS prefetching system to notify worker threads that 11 | // a queue now has items (tasks) which need to be tended to. A related use 12 | // would have a pool manager waiting on a ConditionVariable, waiting for a 13 | // thread in the pool to announce (signal) that there is now more room in a 14 | // (bounded size) communications queue for the manager to deposit tasks, or, 15 | // as a second example, that the queue of tasks is completely empty and all 16 | // workers are waiting. 17 | // 18 | // USAGE NOTE 1: spurious signal events are possible with this and 19 | // most implementations of condition variables. As a result, be 20 | // *sure* to retest your condition before proceeding. The following 21 | // is a good example of doing this correctly: 22 | // 23 | // while (!work_to_be_done()) Wait(...); 24 | // 25 | // In contrast do NOT do the following: 26 | // 27 | // if (!work_to_be_done()) Wait(...); // Don't do this. 28 | // 29 | // Especially avoid the above if you are relying on some other thread only 30 | // issuing a signal up *if* there is work-to-do. There can/will 31 | // be spurious signals. Recheck state on waiting thread before 32 | // assuming the signal was intentional. Caveat caller ;-). 33 | // 34 | // USAGE NOTE 2: Broadcast() frees up all waiting threads at once, 35 | // which leads to contention for the locks they all held when they 36 | // called Wait(). This results in POOR performance. A much better 37 | // approach to getting a lot of threads out of Wait() is to have each 38 | // thread (upon exiting Wait()) call Signal() to free up another 39 | // Wait'ing thread. Look at condition_variable_unittest.cc for 40 | // both examples. 41 | // 42 | // Broadcast() can be used nicely during teardown, as it gets the job 43 | // done, and leaves no sleeping threads... and performance is less 44 | // critical at that point. 45 | // 46 | // The semantics of Broadcast() are carefully crafted so that *all* 47 | // threads that were waiting when the request was made will indeed 48 | // get signaled. Some implementations mess up, and don't signal them 49 | // all, while others allow the wait to be effectively turned off (for 50 | // a while while waiting threads come around). This implementation 51 | // appears correct, as it will not "lose" any signals, and will guarantee 52 | // that all threads get signaled by Broadcast(). 53 | // 54 | // This implementation offers support for "performance" in its selection of 55 | // which thread to revive. Performance, in direct contrast with "fairness," 56 | // assures that the thread that most recently began to Wait() is selected by 57 | // Signal to revive. Fairness would (if publicly supported) assure that the 58 | // thread that has Wait()ed the longest is selected. The default policy 59 | // may improve performance, as the selected thread may have a greater chance of 60 | // having some of its stack data in various CPU caches. 61 | // 62 | // For a discussion of the many very subtle implementation details, see the FAQ 63 | // at the end of condition_variable_win.cc. 64 | 65 | #ifndef MINI_CHROMIUM_BASE_SYNCHRONIZATION_CONDITION_VARIABLE_H_ 66 | #define MINI_CHROMIUM_BASE_SYNCHRONIZATION_CONDITION_VARIABLE_H_ 67 | 68 | #include "build/build_config.h" 69 | 70 | #include 71 | 72 | #include "base/synchronization/lock.h" 73 | 74 | namespace base { 75 | 76 | class ConditionVarImpl; 77 | 78 | class ConditionVariable { 79 | public: 80 | // Construct a cv for use with ONLY one user lock. 81 | explicit ConditionVariable(Lock* user_lock); 82 | 83 | ConditionVariable(const ConditionVariable&) = delete; 84 | ConditionVariable& operator=(const ConditionVariable&) = delete; 85 | 86 | ~ConditionVariable(); 87 | 88 | // Wait() releases the caller's critical section atomically as it starts to 89 | // sleep, and the reacquires it when it is signaled. 90 | void Wait(); 91 | 92 | // Broadcast() revives all waiting threads. 93 | void Broadcast(); 94 | // Signal() revives one waiting thread. 95 | void Signal(); 96 | 97 | private: 98 | 99 | pthread_cond_t condition_; 100 | pthread_mutex_t* user_mutex_; 101 | #ifndef NDEBUG 102 | base::Lock* user_lock_; // Needed to adjust shadow lock state on wait. 103 | #endif 104 | }; 105 | 106 | } // namespace base 107 | 108 | #endif // MINI_CHROMIUM_BASE_SYNCHRONIZATION_CONDITION_VARIABLE_H_ 109 | -------------------------------------------------------------------------------- /base/synchronization/condition_variable_posix.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2006-2008 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/synchronization/condition_variable.h" 6 | 7 | #include "base/check_op.h" 8 | 9 | namespace base { 10 | 11 | ConditionVariable::ConditionVariable(Lock* user_lock) 12 | : user_mutex_(user_lock->lock_.native_handle()) 13 | #ifndef NDEBUG 14 | , user_lock_(user_lock) 15 | #endif 16 | { 17 | int rv = 0; 18 | rv = pthread_cond_init(&condition_, NULL); 19 | DCHECK_EQ(0, rv); 20 | } 21 | 22 | ConditionVariable::~ConditionVariable() { 23 | int rv = pthread_cond_destroy(&condition_); 24 | DCHECK_EQ(0, rv); 25 | } 26 | 27 | void ConditionVariable::Wait() { 28 | #ifndef NDEBUG 29 | user_lock_->CheckHeldAndUnmark(); 30 | #endif 31 | int rv = pthread_cond_wait(&condition_, user_mutex_); 32 | DCHECK_EQ(0, rv); 33 | #ifndef NDEBUG 34 | user_lock_->CheckUnheldAndMark(); 35 | #endif 36 | } 37 | 38 | void ConditionVariable::Broadcast() { 39 | int rv = pthread_cond_broadcast(&condition_); 40 | DCHECK_EQ(0, rv); 41 | } 42 | 43 | void ConditionVariable::Signal() { 44 | int rv = pthread_cond_signal(&condition_); 45 | DCHECK_EQ(0, rv); 46 | } 47 | 48 | } // namespace base 49 | -------------------------------------------------------------------------------- /base/synchronization/lock.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2006-2008 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | // This file is used for debugging assertion support. The Lock class 6 | // is functionally a wrapper around the LockImpl class, so the only 7 | // real intelligence in the class is in the debugging logic. 8 | 9 | #include "base/synchronization/lock.h" 10 | 11 | #include "base/check_op.h" 12 | 13 | #ifndef NDEBUG 14 | 15 | namespace base { 16 | 17 | namespace { 18 | 19 | ThreadRefType GetCurrentThreadRef() { 20 | #if BUILDFLAG(IS_WIN) 21 | return GetCurrentThreadId(); 22 | #elif BUILDFLAG(IS_POSIX) 23 | return pthread_self(); 24 | #endif 25 | } 26 | 27 | } // namespace 28 | 29 | Lock::Lock() : owning_thread_(), lock_() { 30 | } 31 | 32 | Lock::~Lock() { 33 | DCHECK_EQ(owning_thread_, ThreadRefType()); 34 | } 35 | 36 | void Lock::AssertAcquired() const { 37 | DCHECK_EQ(owning_thread_, GetCurrentThreadRef()); 38 | } 39 | 40 | void Lock::CheckHeldAndUnmark() { 41 | DCHECK_EQ(owning_thread_, GetCurrentThreadRef()); 42 | owning_thread_ = ThreadRefType(); 43 | } 44 | 45 | void Lock::CheckUnheldAndMark() { 46 | DCHECK_EQ(owning_thread_, ThreadRefType()); 47 | owning_thread_ = GetCurrentThreadRef(); 48 | } 49 | 50 | } // namespace base 51 | 52 | #endif 53 | -------------------------------------------------------------------------------- /base/synchronization/lock.h: -------------------------------------------------------------------------------- 1 | // Copyright 2006-2008 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_SYNCHRONIZATION_LOCK_H_ 6 | #define MINI_CHROMIUM_BASE_SYNCHRONIZATION_LOCK_H_ 7 | 8 | #include "build/build_config.h" 9 | 10 | #if BUILDFLAG(IS_WIN) 11 | #include 12 | #elif BUILDFLAG(IS_POSIX) 13 | #include 14 | #endif 15 | 16 | #include "base/synchronization/lock_impl.h" 17 | 18 | namespace base { 19 | 20 | #if BUILDFLAG(IS_WIN) 21 | typedef DWORD ThreadRefType; 22 | #elif BUILDFLAG(IS_POSIX) 23 | typedef pthread_t ThreadRefType; 24 | #endif 25 | 26 | // A convenient wrapper for an OS specific critical section. The only real 27 | // intelligence in this class is in debug mode for the support for the 28 | // AssertAcquired() method. 29 | class Lock { 30 | public: 31 | #ifdef NDEBUG 32 | // Optimized wrapper implementation 33 | Lock() : lock_() {} 34 | 35 | Lock(const Lock&) = delete; 36 | Lock& operator=(const Lock&) = delete; 37 | 38 | ~Lock() {} 39 | void Acquire() { lock_.Lock(); } 40 | void Release() { lock_.Unlock(); } 41 | 42 | // If the lock is not held, take it and return true. If the lock is already 43 | // held by another thread, immediately return false. This must not be called 44 | // by a thread already holding the lock (what happens is undefined and an 45 | // assertion may fail). 46 | bool Try() { return lock_.Try(); } 47 | 48 | // Null implementation if not debug. 49 | void AssertAcquired() const {} 50 | #else 51 | Lock(); 52 | ~Lock(); 53 | 54 | // NOTE: Although windows critical sections support recursive locks, we do not 55 | // allow this, and we will commonly fire a DCHECK() if a thread attempts to 56 | // acquire the lock a second time (while already holding it). 57 | void Acquire() { 58 | lock_.Lock(); 59 | CheckUnheldAndMark(); 60 | } 61 | void Release() { 62 | CheckHeldAndUnmark(); 63 | lock_.Unlock(); 64 | } 65 | 66 | bool Try() { 67 | bool rv = lock_.Try(); 68 | if (rv) { 69 | CheckUnheldAndMark(); 70 | } 71 | return rv; 72 | } 73 | 74 | void AssertAcquired() const; 75 | #endif 76 | 77 | // The posix implementation of ConditionVariable needs to be able 78 | // to see our lock and tweak our debugging counters, as it releases 79 | // and acquires locks inside of pthread_cond_{timed,}wait. 80 | friend class ConditionVariable; 81 | 82 | private: 83 | #ifndef NDEBUG 84 | // Members and routines taking care of locks assertions. 85 | // Note that this checks for recursive locks and allows them 86 | // if the variable is set. This is allowed by the underlying implementation 87 | // on windows but not on Posix, so we're doing unneeded checks on Posix. 88 | // It's worth it to share the code. 89 | void CheckHeldAndUnmark(); 90 | void CheckUnheldAndMark(); 91 | 92 | // All private data is implicitly protected by lock_. 93 | // Be VERY careful to only access members under that lock. 94 | ThreadRefType owning_thread_; 95 | #endif 96 | 97 | // Platform specific underlying lock implementation. 98 | internal::LockImpl lock_; 99 | }; 100 | 101 | // A helper class that acquires the given Lock while the AutoLock is in scope. 102 | class AutoLock { 103 | public: 104 | struct AlreadyAcquired {}; 105 | 106 | explicit AutoLock(Lock& lock) : lock_(lock) { 107 | lock_.Acquire(); 108 | } 109 | 110 | AutoLock(Lock& lock, const AlreadyAcquired&) : lock_(lock) { 111 | lock_.AssertAcquired(); 112 | } 113 | 114 | AutoLock(const AutoLock&) = delete; 115 | AutoLock& operator=(const AutoLock&) = delete; 116 | 117 | ~AutoLock() { 118 | lock_.AssertAcquired(); 119 | lock_.Release(); 120 | } 121 | 122 | private: 123 | Lock& lock_; 124 | }; 125 | 126 | // AutoUnlock is a helper that will Release() the |lock| argument in the 127 | // constructor, and re-Acquire() it in the destructor. 128 | class AutoUnlock { 129 | public: 130 | explicit AutoUnlock(Lock& lock) : lock_(lock) { 131 | // We require our caller to have the lock. 132 | lock_.AssertAcquired(); 133 | lock_.Release(); 134 | } 135 | 136 | AutoUnlock(const AutoUnlock&) = delete; 137 | AutoUnlock& operator=(const AutoUnlock&) = delete; 138 | 139 | ~AutoUnlock() { 140 | lock_.Acquire(); 141 | } 142 | 143 | private: 144 | Lock& lock_; 145 | }; 146 | 147 | } // namespace base 148 | 149 | #endif // MINI_CHROMIUM_BASE_SYNCHRONIZATION_LOCK_H_ 150 | -------------------------------------------------------------------------------- /base/synchronization/lock_impl.h: -------------------------------------------------------------------------------- 1 | // Copyright 2006-2008 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_SYNCHRONIZATION_LOCK_IMPL_H_ 6 | #define MINI_CHROMIUM_BASE_SYNCHRONIZATION_LOCK_IMPL_H_ 7 | 8 | #include "build/build_config.h" 9 | 10 | #if BUILDFLAG(IS_WIN) 11 | #include 12 | #elif BUILDFLAG(IS_POSIX) 13 | #include 14 | #endif 15 | 16 | 17 | namespace base { 18 | namespace internal { 19 | 20 | // This class implements the underlying platform-specific spin-lock mechanism 21 | // used for the Lock class. Most users should not use LockImpl directly, but 22 | // should instead use Lock. 23 | class LockImpl { 24 | public: 25 | #if BUILDFLAG(IS_WIN) 26 | typedef CRITICAL_SECTION NativeHandle; 27 | #elif BUILDFLAG(IS_POSIX) 28 | typedef pthread_mutex_t NativeHandle; 29 | #endif 30 | 31 | LockImpl(); 32 | 33 | LockImpl(const LockImpl&) = delete; 34 | LockImpl& operator=(const LockImpl&) = delete; 35 | 36 | ~LockImpl(); 37 | 38 | // If the lock is not held, take it and return true. If the lock is already 39 | // held by something else, immediately return false. 40 | bool Try(); 41 | 42 | // Take the lock, blocking until it is available if necessary. 43 | void Lock(); 44 | 45 | // Release the lock. This must only be called by the lock's holder: after 46 | // a successful call to Try, or a call to Lock. 47 | void Unlock(); 48 | 49 | // Return the native underlying lock. 50 | // TODO(awalker): refactor lock and condition variables so that this is 51 | // unnecessary. 52 | NativeHandle* native_handle() { return &native_handle_; } 53 | 54 | private: 55 | NativeHandle native_handle_; 56 | }; 57 | 58 | } // namespace internal 59 | } // namespace base 60 | 61 | #endif // MINI_CHROMIUM_BASE_SYNCHRONIZATION_LOCK_IMPL_H_ 62 | -------------------------------------------------------------------------------- /base/synchronization/lock_impl_posix.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2006-2008 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/synchronization/lock_impl.h" 6 | 7 | #include 8 | 9 | #include "base/check_op.h" 10 | 11 | namespace base { 12 | namespace internal { 13 | 14 | LockImpl::LockImpl() { 15 | #ifndef NDEBUG 16 | // In debug, setup attributes for lock error checking. 17 | pthread_mutexattr_t mta; 18 | int rv = pthread_mutexattr_init(&mta); 19 | DCHECK_EQ(rv, 0); 20 | rv = pthread_mutexattr_settype(&mta, PTHREAD_MUTEX_ERRORCHECK); 21 | DCHECK_EQ(rv, 0); 22 | rv = pthread_mutex_init(&native_handle_, &mta); 23 | DCHECK_EQ(rv, 0); 24 | rv = pthread_mutexattr_destroy(&mta); 25 | DCHECK_EQ(rv, 0); 26 | #else 27 | // In release, go with the default lock attributes. 28 | pthread_mutex_init(&native_handle_, NULL); 29 | #endif 30 | } 31 | 32 | LockImpl::~LockImpl() { 33 | int rv = pthread_mutex_destroy(&native_handle_); 34 | DCHECK_EQ(rv, 0); 35 | } 36 | 37 | bool LockImpl::Try() { 38 | int rv = pthread_mutex_trylock(&native_handle_); 39 | DCHECK(rv == 0 || rv == EBUSY); 40 | return rv == 0; 41 | } 42 | 43 | void LockImpl::Lock() { 44 | int rv = pthread_mutex_lock(&native_handle_); 45 | DCHECK_EQ(rv, 0); 46 | } 47 | 48 | void LockImpl::Unlock() { 49 | int rv = pthread_mutex_unlock(&native_handle_); 50 | DCHECK_EQ(rv, 0); 51 | } 52 | 53 | } // namespace internal 54 | } // namespace base 55 | -------------------------------------------------------------------------------- /base/synchronization/lock_impl_win.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/synchronization/lock_impl.h" 6 | 7 | namespace base { 8 | namespace internal { 9 | 10 | LockImpl::LockImpl() { 11 | // The second parameter is the spin count, for short-held locks it avoid the 12 | // contending thread from going to sleep which helps performance greatly. 13 | ::InitializeCriticalSectionAndSpinCount(&native_handle_, 2000); 14 | } 15 | 16 | LockImpl::~LockImpl() { 17 | ::DeleteCriticalSection(&native_handle_); 18 | } 19 | 20 | bool LockImpl::Try() { 21 | if (::TryEnterCriticalSection(&native_handle_) != FALSE) { 22 | return true; 23 | } 24 | return false; 25 | } 26 | 27 | void LockImpl::Lock() { 28 | ::EnterCriticalSection(&native_handle_); 29 | } 30 | 31 | void LockImpl::Unlock() { 32 | ::LeaveCriticalSection(&native_handle_); 33 | } 34 | 35 | } // namespace internal 36 | } // namespace base 37 | -------------------------------------------------------------------------------- /base/sys_byteorder.h: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_SYS_BYTEORDER_H_ 6 | #define MINI_CHROMIUM_BASE_SYS_BYTEORDER_H_ 7 | 8 | #include "build/build_config.h" 9 | 10 | #if BUILDFLAG(IS_APPLE) 11 | #include 12 | #elif BUILDFLAG(IS_WIN) 13 | #include 14 | #else 15 | #include 16 | #endif 17 | 18 | namespace base { 19 | 20 | inline uint16_t ByteSwap(uint16_t x) { 21 | #if BUILDFLAG(IS_APPLE) 22 | return OSSwapInt16(x); 23 | #elif BUILDFLAG(IS_WIN) 24 | return _byteswap_ushort(x); 25 | #else 26 | return bswap_16(x); 27 | #endif 28 | } 29 | 30 | inline uint32_t ByteSwap(uint32_t x) { 31 | #if BUILDFLAG(IS_APPLE) 32 | return OSSwapInt32(x); 33 | #elif BUILDFLAG(IS_WIN) 34 | return _byteswap_ulong(x); 35 | #else 36 | return bswap_32(x); 37 | #endif 38 | } 39 | 40 | inline uint64_t ByteSwap(uint64_t x) { 41 | #if BUILDFLAG(IS_APPLE) 42 | return OSSwapInt64(x); 43 | #elif BUILDFLAG(IS_WIN) 44 | return _byteswap_uint64(x); 45 | #else 46 | return bswap_64(x); 47 | #endif 48 | } 49 | 50 | inline uint16_t NetToHost16(uint16_t x) { 51 | #if defined(ARCH_CPU_LITTLE_ENDIAN) 52 | return ByteSwap(x); 53 | #else 54 | return x; 55 | #endif 56 | } 57 | 58 | inline uint32_t NetToHost32(uint32_t x) { 59 | #if defined(ARCH_CPU_LITTLE_ENDIAN) 60 | return ByteSwap(x); 61 | #else 62 | return x; 63 | #endif 64 | } 65 | 66 | inline uint64_t NetToHost64(uint64_t x) { 67 | #if defined(ARCH_CPU_LITTLE_ENDIAN) 68 | return ByteSwap(x); 69 | #else 70 | return x; 71 | #endif 72 | } 73 | 74 | inline uint16_t HostToNet16(uint16_t x) { 75 | #if defined(ARCH_CPU_LITTLE_ENDIAN) 76 | return ByteSwap(x); 77 | #else 78 | return x; 79 | #endif 80 | } 81 | 82 | inline uint32_t HostToNet32(uint32_t x) { 83 | #if defined(ARCH_CPU_LITTLE_ENDIAN) 84 | return ByteSwap(x); 85 | #else 86 | return x; 87 | #endif 88 | } 89 | 90 | inline uint64_t HostToNet64(uint64_t x) { 91 | #if defined(ARCH_CPU_LITTLE_ENDIAN) 92 | return ByteSwap(x); 93 | #else 94 | return x; 95 | #endif 96 | } 97 | 98 | } // namespace base 99 | 100 | #endif // MINI_CHROMIUM_BASE_SYS_BYTEORDER_H_ 101 | -------------------------------------------------------------------------------- /base/template_util.h: -------------------------------------------------------------------------------- 1 | // Copyright 2011 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_TEMPLATE_UTIL_H_ 6 | #define MINI_CHROMIUM_BASE_TEMPLATE_UTIL_H_ 7 | 8 | #include 9 | 10 | #include 11 | 12 | namespace base { 13 | 14 | namespace internal { 15 | 16 | // Helper to express preferences in an overload set. If more than one overload 17 | // are available for a given set of parameters the overload with the higher 18 | // priority will be chosen. 19 | template 20 | struct priority_tag : priority_tag {}; 21 | 22 | template <> 23 | struct priority_tag<0> {}; 24 | 25 | } // namespace internal 26 | 27 | // Implementation of C++20's std::remove_cvref. 28 | // 29 | // References: 30 | // - https://en.cppreference.com/w/cpp/types/remove_cvref 31 | // - https://wg21.link/meta.trans.other#lib:remove_cvref 32 | template 33 | struct remove_cvref { 34 | using type = std::remove_cv_t>; 35 | }; 36 | 37 | // Implementation of C++20's std::remove_cvref_t. 38 | // 39 | // References: 40 | // - https://en.cppreference.com/w/cpp/types/remove_cvref 41 | // - https://wg21.link/meta.type.synop#lib:remove_cvref_t 42 | template 43 | using remove_cvref_t = typename remove_cvref::type; 44 | 45 | // Simplified implementation of C++20's std::iter_reference_t. 46 | // As opposed to std::iter_reference_t, this implementation does not restrict 47 | // the type of `Iter`. 48 | // 49 | // Reference: https://wg21.link/iterator.synopsis#:~:text=iter_reference_t 50 | template 51 | using iter_reference_t = decltype(*std::declval()); 52 | 53 | } // namespace base 54 | 55 | #endif // MINI_CHROMIUM_BASE_TEMPLATE_UTIL_H_ 56 | -------------------------------------------------------------------------------- /base/third_party/icu/LICENSE: -------------------------------------------------------------------------------- 1 | COPYRIGHT AND PERMISSION NOTICE (ICU 58 and later) 2 | 3 | Copyright © 1991-2017 Unicode, Inc. All rights reserved. 4 | Distributed under the Terms of Use in http://www.unicode.org/copyright.html 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining 7 | a copy of the Unicode data files and any associated documentation 8 | (the "Data Files") or Unicode software and any associated documentation 9 | (the "Software") to deal in the Data Files or Software 10 | without restriction, including without limitation the rights to use, 11 | copy, modify, merge, publish, distribute, and/or sell copies of 12 | the Data Files or Software, and to permit persons to whom the Data Files 13 | or Software are furnished to do so, provided that either 14 | (a) this copyright and permission notice appear with all copies 15 | of the Data Files or Software, or 16 | (b) this copyright and permission notice appear in associated 17 | Documentation. 18 | 19 | THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF 20 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE 21 | WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 22 | NONINFRINGEMENT OF THIRD PARTY RIGHTS. 23 | IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS 24 | NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL 25 | DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, 26 | DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER 27 | TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR 28 | PERFORMANCE OF THE DATA FILES OR SOFTWARE. 29 | 30 | Except as contained in this notice, the name of a copyright holder 31 | shall not be used in advertising or otherwise to promote the sale, 32 | use or other dealings in these Data Files or Software without prior 33 | written authorization of the copyright holder. 34 | 35 | --------------------- 36 | 37 | Third-Party Software Licenses 38 | 39 | This section contains third-party software notices and/or additional 40 | terms for licensed third-party software components included within ICU 41 | libraries. 42 | 43 | 1. ICU License - ICU 1.8.1 to ICU 57.1 44 | 45 | COPYRIGHT AND PERMISSION NOTICE 46 | 47 | Copyright (c) 1995-2016 International Business Machines Corporation and others 48 | All rights reserved. 49 | 50 | Permission is hereby granted, free of charge, to any person obtaining 51 | a copy of this software and associated documentation files (the 52 | "Software"), to deal in the Software without restriction, including 53 | without limitation the rights to use, copy, modify, merge, publish, 54 | distribute, and/or sell copies of the Software, and to permit persons 55 | to whom the Software is furnished to do so, provided that the above 56 | copyright notice(s) and this permission notice appear in all copies of 57 | the Software and that both the above copyright notice(s) and this 58 | permission notice appear in supporting documentation. 59 | 60 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 61 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 62 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT 63 | OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR 64 | HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY 65 | SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER 66 | RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF 67 | CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN 68 | CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 69 | 70 | Except as contained in this notice, the name of a copyright holder 71 | shall not be used in advertising or otherwise to promote the sale, use 72 | or other dealings in this Software without prior written authorization 73 | of the copyright holder. 74 | 75 | All trademarks and registered trademarks mentioned herein are the 76 | property of their respective owners. 77 | -------------------------------------------------------------------------------- /base/third_party/icu/README.chromium: -------------------------------------------------------------------------------- 1 | Name: ICU 2 | URL: http://site.icu-project.org/ 3 | Version: 60 4 | License: Unicode 5 | License File: LICENSE 6 | 7 | This file has the relevant components from ICU copied to handle basic UTF8/16/32 8 | conversions. Components are copied from umachine.h, utf.h, utf8.h, and utf16.h 9 | into icu_utf.h, and from utf_impl.cpp into icu_utf.cc. 10 | 11 | The main change is that U_/U8_/U16_ prefixes have been replaced with 12 | CBU_/CBU8_/CBU16_ (for "Chrome Base") to avoid confusion with the "real" ICU 13 | macros should ICU be in use on the system. For the same reason, the functions 14 | and types have been put in the "base_icu" namespace. 15 | -------------------------------------------------------------------------------- /base/third_party/icu/icu_utf.cc: -------------------------------------------------------------------------------- 1 | // © 2016 and later: Unicode, Inc. and others. 2 | // License & terms of use: http://www.unicode.org/copyright.html 3 | /* 4 | ****************************************************************************** 5 | * 6 | * Copyright (C) 1999-2012, International Business Machines 7 | * Corporation and others. All Rights Reserved. 8 | * 9 | ****************************************************************************** 10 | * file name: utf_impl.cpp 11 | * encoding: UTF-8 12 | * tab size: 8 (not used) 13 | * indentation:4 14 | * 15 | * created on: 1999sep13 16 | * created by: Markus W. Scherer 17 | * 18 | * This file provides implementation functions for macros in the utfXX.h 19 | * that would otherwise be too long as macros. 20 | */ 21 | 22 | #include "base/third_party/icu/icu_utf.h" 23 | 24 | namespace base_icu { 25 | 26 | // source/common/utf_impl.cpp 27 | 28 | static const UChar32 29 | utf8_errorValue[6]={ 30 | // Same values as UTF8_ERROR_VALUE_1, UTF8_ERROR_VALUE_2, UTF_ERROR_VALUE, 31 | // but without relying on the obsolete unicode/utf_old.h. 32 | 0x15, 0x9f, 0xffff, 33 | 0x10ffff 34 | }; 35 | 36 | static UChar32 37 | errorValue(int32_t count, int8_t strict) { 38 | if(strict>=0) { 39 | return utf8_errorValue[count]; 40 | } else if(strict==-3) { 41 | return 0xfffd; 42 | } else { 43 | return CBU_SENTINEL; 44 | } 45 | } 46 | 47 | /* 48 | * Handle the non-inline part of the U8_NEXT() and U8_NEXT_FFFD() macros 49 | * and their obsolete sibling UTF8_NEXT_CHAR_SAFE(). 50 | * 51 | * U8_NEXT() supports NUL-terminated strings indicated via length<0. 52 | * 53 | * The "strict" parameter controls the error behavior: 54 | * <0 "Safe" behavior of U8_NEXT(): 55 | * -1: All illegal byte sequences yield U_SENTINEL=-1. 56 | * -2: Same as -1, except for lenient treatment of surrogate code points as legal. 57 | * Some implementations use this for roundtripping of 58 | * Unicode 16-bit strings that are not well-formed UTF-16, that is, they 59 | * contain unpaired surrogates. 60 | * -3: All illegal byte sequences yield U+FFFD. 61 | * 0 Obsolete "safe" behavior of UTF8_NEXT_CHAR_SAFE(..., FALSE): 62 | * All illegal byte sequences yield a positive code point such that this 63 | * result code point would be encoded with the same number of bytes as 64 | * the illegal sequence. 65 | * >0 Obsolete "strict" behavior of UTF8_NEXT_CHAR_SAFE(..., TRUE): 66 | * Same as the obsolete "safe" behavior, but non-characters are also treated 67 | * like illegal sequences. 68 | * 69 | * Note that a UBool is the same as an int8_t. 70 | */ 71 | UChar32 72 | utf8_nextCharSafeBody(const uint8_t *s, int32_t *pi, int32_t length, UChar32 c, UBool strict) { 73 | // *pi is one after byte c. 74 | int32_t i=*pi; 75 | // length can be negative for NUL-terminated strings: Read and validate one byte at a time. 76 | if(i==length || c>0xf4) { 77 | // end of string, or not a lead byte 78 | } else if(c>=0xf0) { 79 | // Test for 4-byte sequences first because 80 | // U8_NEXT() handles shorter valid sequences inline. 81 | uint8_t t1=s[i], t2, t3; 82 | c&=7; 83 | if(CBU8_IS_VALID_LEAD4_AND_T1(c, t1) && 84 | ++i!=length && (t2=s[i]-0x80)<=0x3f && 85 | ++i!=length && (t3=s[i]-0x80)<=0x3f) { 86 | ++i; 87 | c=(c<<18)|((t1&0x3f)<<12)|(t2<<6)|t3; 88 | // strict: forbid non-characters like U+fffe 89 | if(strict<=0 || !CBU_IS_UNICODE_NONCHAR(c)) { 90 | *pi=i; 91 | return c; 92 | } 93 | } 94 | } else if(c>=0xe0) { 95 | c&=0xf; 96 | if(strict!=-2) { 97 | uint8_t t1=s[i], t2; 98 | if(CBU8_IS_VALID_LEAD3_AND_T1(c, t1) && 99 | ++i!=length && (t2=s[i]-0x80)<=0x3f) { 100 | ++i; 101 | c=(c<<12)|((t1&0x3f)<<6)|t2; 102 | // strict: forbid non-characters like U+fffe 103 | if(strict<=0 || !CBU_IS_UNICODE_NONCHAR(c)) { 104 | *pi=i; 105 | return c; 106 | } 107 | } 108 | } else { 109 | // strict=-2 -> lenient: allow surrogates 110 | uint8_t t1=s[i]-0x80, t2; 111 | if(t1<=0x3f && (c>0 || t1>=0x20) && 112 | ++i!=length && (t2=s[i]-0x80)<=0x3f) { 113 | *pi=i+1; 114 | return (c<<12)|(t1<<6)|t2; 115 | } 116 | } 117 | } else if(c>=0xc2) { 118 | uint8_t t1=s[i]-0x80; 119 | if(t1<=0x3f) { 120 | *pi=i+1; 121 | return ((c-0xc0)<<6)|t1; 122 | } 123 | } // else 0x80<=c<0xc2 is not a lead byte 124 | 125 | /* error handling */ 126 | c=errorValue(i-*pi, strict); 127 | *pi=i; 128 | return c; 129 | } 130 | 131 | } // namespace base_icu 132 | -------------------------------------------------------------------------------- /base/threading/thread_local_storage_posix.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2008 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/threading/thread_local_storage.h" 6 | 7 | #include "base/check_op.h" 8 | 9 | namespace base { 10 | namespace internal { 11 | 12 | bool PlatformThreadLocalStorage::AllocTLS(TLSKey* key) { 13 | return !pthread_key_create(key, 14 | base::internal::PlatformThreadLocalStorage::OnThreadExit); 15 | } 16 | 17 | void PlatformThreadLocalStorage::FreeTLS(TLSKey key) { 18 | int ret = pthread_key_delete(key); 19 | DCHECK_EQ(ret, 0); 20 | } 21 | 22 | void* PlatformThreadLocalStorage::GetTLSValue(TLSKey key) { 23 | return pthread_getspecific(key); 24 | } 25 | 26 | void PlatformThreadLocalStorage::SetTLSValue(TLSKey key, void* value) { 27 | int ret = pthread_setspecific(key, value); 28 | DCHECK_EQ(ret, 0); 29 | } 30 | 31 | } // namespace internal 32 | } // namespace base 33 | -------------------------------------------------------------------------------- /base/threading/thread_local_storage_win.cc: -------------------------------------------------------------------------------- 1 | // Copyright 2007 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #include "base/threading/thread_local_storage.h" 6 | 7 | #include "base/check.h" 8 | 9 | namespace base { 10 | namespace internal { 11 | 12 | bool PlatformThreadLocalStorage::AllocTLS(TLSKey* key) { 13 | TLSKey value = TlsAlloc(); 14 | if (value != TLS_OUT_OF_INDEXES) { 15 | *key = value; 16 | return true; 17 | } 18 | return false; 19 | } 20 | 21 | void PlatformThreadLocalStorage::FreeTLS(TLSKey key) { 22 | BOOL ret = TlsFree(key); 23 | DCHECK(ret); 24 | } 25 | 26 | void* PlatformThreadLocalStorage::GetTLSValue(TLSKey key) { 27 | return TlsGetValue(key); 28 | } 29 | 30 | void PlatformThreadLocalStorage::SetTLSValue(TLSKey key, void* value) { 31 | BOOL ret = TlsSetValue(key, value); 32 | DCHECK(ret); 33 | } 34 | 35 | } // namespace internal 36 | } // namespace base 37 | 38 | // Thread Termination Callbacks. 39 | // Windows doesn't support a per-thread destructor with its 40 | // TLS primitives. So, we build it manually by inserting a 41 | // function to be called on each thread's exit. 42 | // This magic is from http://www.codeproject.com/threads/tls.asp 43 | // and it works for VC++ 7.0 and later. 44 | 45 | // Force a reference to _tls_used to make the linker create the TLS directory 46 | // if it's not already there. (e.g. if __declspec(thread) is not used). 47 | // Force a reference to p_thread_callback_base to prevent whole program 48 | // optimization from discarding the variable. 49 | #ifdef _WIN64 50 | 51 | #pragma comment(linker, "/INCLUDE:_tls_used") 52 | #pragma comment(linker, "/INCLUDE:p_thread_callback_base") 53 | 54 | #else // _WIN64 55 | 56 | #pragma comment(linker, "/INCLUDE:__tls_used") 57 | #pragma comment(linker, "/INCLUDE:_p_thread_callback_base") 58 | 59 | #endif // _WIN64 60 | 61 | // Static callback function to call with each thread termination. 62 | void NTAPI OnThreadExit(PVOID module, DWORD reason, PVOID reserved) { 63 | // On XP SP0 & SP1, the DLL_PROCESS_ATTACH is never seen. It is sent on SP2+ 64 | // and on W2K and W2K3. So don't assume it is sent. 65 | if (DLL_THREAD_DETACH == reason || DLL_PROCESS_DETACH == reason) 66 | base::internal::PlatformThreadLocalStorage::OnThreadExit(); 67 | } 68 | 69 | // .CRT$XLA to .CRT$XLZ is an array of PIMAGE_TLS_CALLBACK pointers that are 70 | // called automatically by the OS loader code (not the CRT) when the module is 71 | // loaded and on thread creation. They are NOT called if the module has been 72 | // loaded by a LoadLibrary() call. It must have implicitly been loaded at 73 | // process startup. 74 | // By implicitly loaded, I mean that it is directly referenced by the main EXE 75 | // or by one of its dependent DLLs. Delay-loaded DLL doesn't count as being 76 | // implicitly loaded. 77 | // 78 | // See VC\crt\src\tlssup.c for reference. 79 | 80 | // extern "C" suppresses C++ name mangling so we know the symbol name for the 81 | // linker /INCLUDE:symbol pragma above. 82 | extern "C" { 83 | // The linker must not discard p_thread_callback_base. (We force a reference 84 | // to this variable with a linker /INCLUDE:symbol pragma to ensure that.) If 85 | // this variable is discarded, the OnThreadExit function will never be called. 86 | #ifdef _WIN64 87 | 88 | // .CRT section is merged with .rdata on x64 so it must be constant data. 89 | #pragma const_seg(".CRT$XLB") 90 | // When defining a const variable, it must have external linkage to be sure the 91 | // linker doesn't discard it. 92 | extern const PIMAGE_TLS_CALLBACK p_thread_callback_base; 93 | const PIMAGE_TLS_CALLBACK p_thread_callback_base = OnThreadExit; 94 | 95 | // Reset the default section. 96 | #pragma const_seg() 97 | 98 | #else // _WIN64 99 | 100 | #pragma data_seg(".CRT$XLB") 101 | PIMAGE_TLS_CALLBACK p_thread_callback_base = OnThreadExit; 102 | 103 | // Reset the default section. 104 | #pragma data_seg() 105 | 106 | #endif // _WIN64 107 | } // extern "C" 108 | -------------------------------------------------------------------------------- /base/types/cxx23_to_underlying.h: -------------------------------------------------------------------------------- 1 | // Copyright 2023 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_TYPES_CXX23_TO_UNDERLYING_H_ 6 | #define MINI_CHROMIUM_BASE_TYPES_CXX23_TO_UNDERLYING_H_ 7 | 8 | #include 9 | 10 | namespace base { 11 | 12 | // Implementation of C++23's std::to_underlying. 13 | // 14 | // Note: This has an additional `std::is_enum` requirement to be SFINAE 15 | // friendly prior to C++20. 16 | // 17 | // Reference: https://en.cppreference.com/w/cpp/utility/to_underlying 18 | template {}>> 19 | constexpr std::underlying_type_t to_underlying(EnumT e) noexcept { 20 | return static_cast>(e); 21 | } 22 | 23 | } // namespace base 24 | 25 | #endif // MINI_CHROMIUM_BASE_TYPES_CXX23_TO_UNDERLYING_H_ 26 | -------------------------------------------------------------------------------- /base/types/to_address.h: -------------------------------------------------------------------------------- 1 | // Copyright 2024 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_BASE_TYPES_TO_ADDRESS_H_ 6 | #define MINI_CHROMIUM_BASE_TYPES_TO_ADDRESS_H_ 7 | 8 | #include 9 | #include 10 | 11 | // SFINAE-compatible wrapper for `std::to_address()`. 12 | // 13 | // The standard does not require `std::to_address()` to be SFINAE-compatible 14 | // when code attempts instantiation with non-pointer-like types, and libstdc++'s 15 | // implementation hard errors. For the sake of templated code that wants simple, 16 | // unified handling, Chromium instead uses this wrapper, which provides that 17 | // guarantee. This allows code to use "`to_address()` would be valid here" as a 18 | // constraint to detect pointer-like types. 19 | namespace base { 20 | 21 | // Note that calling `std::to_address()` with a function pointer renders the 22 | // program ill-formed. 23 | template 24 | requires(!std::is_function_v) 25 | constexpr T* to_address(T* p) noexcept { 26 | return p; 27 | } 28 | 29 | // These constraints cover the cases where `std::to_address()`'s fancy pointer 30 | // overload is well-specified. 31 | template 32 | requires requires(const P& p) { std::pointer_traits

::to_address(p); } || 33 | requires(const P& p) { p.operator->(); } 34 | constexpr auto to_address(const P& p) noexcept { 35 | return std::to_address(p); 36 | } 37 | 38 | } // namespace base 39 | 40 | #endif // MINI_CHROMIUM_BASE_TYPES_TO_ADDRESS_H_ 41 | -------------------------------------------------------------------------------- /build/BUILD.gn: -------------------------------------------------------------------------------- 1 | # Copyright 2020 The Chromium Authors 2 | # Use of this source code is governed by a BSD-style license that can be 3 | # found in the LICENSE file. 4 | 5 | # This is separate from build/config/BUILD.gn to avoid including various .gni 6 | # that it requires, which in turn conflict with settings from BUILDCONFIG.gn 7 | # when building in other trees. 8 | 9 | import("./buildflag_header.gni") 10 | import("./platform.gni") 11 | 12 | config("mini_chromium_config") { 13 | include_dirs = [ 14 | "..", 15 | root_gen_dir, 16 | ] 17 | } 18 | 19 | source_set("build") { 20 | sources = [ "build_config.h" ] 21 | public_configs = [ ":mini_chromium_config" ] 22 | public_deps = [ ":buildflag_header_h" ] 23 | } 24 | 25 | source_set("buildflag_header_h") { 26 | sources = [ "buildflag.h" ] 27 | } 28 | 29 | buildflag_header("chromeos_buildflags") { 30 | header = "chromeos_buildflags.h" 31 | header_dir = "build" 32 | 33 | flags = [ 34 | "IS_CHROMEOS_LACROS=$mini_chromium_is_chromeos_lacros", 35 | "IS_CHROMEOS_ASH=$mini_chromium_is_chromeos_ash", 36 | ] 37 | } 38 | -------------------------------------------------------------------------------- /build/buildflag.h: -------------------------------------------------------------------------------- 1 | // Copyright 2015 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef BUILD_BUILDFLAG_H_ 6 | #define BUILD_BUILDFLAG_H_ 7 | 8 | #define MINI_CHROMIUM_INTERNAL_BUILDFLAG_CAT_INDIRECT(a, b) a##b 9 | #define MINI_CHROMIUM_INTERNAL_BUILDFLAG_CAT(a, b) \ 10 | MINI_CHROMIUM_INTERNAL_BUILDFLAG_CAT_INDIRECT(a, b) 11 | 12 | #define BUILDFLAG(flag) \ 13 | (MINI_CHROMIUM_INTERNAL_BUILDFLAG_CAT( \ 14 | MINI_CHROMIUM_INTERNAL_BUILDFLAG_VALUE_, flag)()) 15 | 16 | #endif // BUILD_BUILDFLAG_H_ 17 | -------------------------------------------------------------------------------- /build/buildflag_header.gni: -------------------------------------------------------------------------------- 1 | # Copyright 2015 The Chromium Authors 2 | # Use of this source code is governed by a BSD-style license that can be 3 | # found in the LICENSE file. 4 | 5 | template("buildflag_header") { 6 | action(target_name) { 7 | script = "write_buildflag_header.py" 8 | 9 | if (defined(invoker.header_dir)) { 10 | header_file = "${invoker.header_dir}/${invoker.header}" 11 | } else { 12 | # Compute the path from the root to this file. 13 | header_file = rebase_path(".", "//") + "/${invoker.header}" 14 | } 15 | 16 | outputs = [ "$root_gen_dir/$header_file" ] 17 | 18 | # Write flags to a file just in case they exceed the system's maximum 19 | # command line length. 20 | # 21 | # Using write_file instead of response_file_contents to avoid a spurious 22 | # rule variable cycle in generated command in Ninja. 23 | # 24 | # See more details from the following bugs: 25 | # * https://bugs.fuchsia.dev/p/fuchsia/issues/detail?id=76068 26 | # * https://github.com/ninja-build/ninja/issues/1966 27 | flags = [ "--flags" ] 28 | if (defined(invoker.flags)) { 29 | flags += invoker.flags 30 | } 31 | flags_file = "${root_gen_dir}/${header_file}.flags" 32 | write_file(flags_file, flags) 33 | inputs = [ flags_file ] 34 | 35 | args = [ 36 | "--output", 37 | header_file, # Not rebased, Python script puts it inside gen-dir. 38 | "--rulename", 39 | get_label_info(":$target_name", "label_no_toolchain"), 40 | "--gen-dir", 41 | rebase_path(root_gen_dir, root_build_dir), 42 | "--definitions", 43 | rebase_path(flags_file, root_build_dir), 44 | ] 45 | 46 | forward_variables_from(invoker, 47 | [ 48 | "deps", 49 | "public_deps", 50 | "testonly", 51 | "visibility", 52 | ]) 53 | 54 | public_deps = [ ":buildflag_header_h" ] 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /build/compiler.gni: -------------------------------------------------------------------------------- 1 | # Copyright 2017 The Chromium Authors 2 | # Use of this source code is governed by a BSD-style license that can be 3 | # found in the LICENSE file. 4 | 5 | import("platform.gni") 6 | 7 | if (mini_chromium_is_win) { 8 | declare_args() { 9 | mini_chromium_is_clang = mini_chromium_is_posix || 10 | mini_chromium_is_fuchsia || mini_chromium_is_win 11 | } 12 | } else { 13 | mini_chromium_is_clang = 14 | mini_chromium_is_posix || mini_chromium_is_fuchsia || mini_chromium_is_win 15 | } 16 | -------------------------------------------------------------------------------- /build/ios/Application-Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleDisplayName 8 | ${PRODUCT_NAME} 9 | CFBundleExecutable 10 | ${EXECUTABLE_NAME} 11 | CFBundleIdentifier 12 | ${IOS_BUNDLE_ID_PREFIX}.googletest.${EXECUTABLE_NAME:rfc1034identifier} 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | ${PRODUCT_NAME} 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | 1.0 21 | CFBundleSignature 22 | ???? 23 | CFBundleVersion 24 | 1.0 25 | LSRequiresIPhoneOS 26 | 27 | UIApplicationDelegate 28 | MiniChromiumApplicationDelegate 29 | UILaunchImages 30 | 31 | 32 | UILaunchImageMinimumOSVersion 33 | 9.0 34 | UILaunchImageName 35 | Default 36 | UILaunchImageSize 37 | {320, 480} 38 | 39 | 40 | UILaunchImageMinimumOSVersion 41 | 9.0 42 | UILaunchImageName 43 | Default 44 | UILaunchImageSize 45 | {320, 568} 46 | 47 | 48 | UILaunchImageMinimumOSVersion 49 | 9.0 50 | UILaunchImageName 51 | Default 52 | UILaunchImageSize 53 | {375, 667} 54 | 55 | 56 | UILaunchImageMinimumOSVersion 57 | 9.0 58 | UILaunchImageName 59 | Default 60 | UILaunchImageSize 61 | {414, 736} 62 | 63 | 64 | UILaunchImageMinimumOSVersion 65 | 9.0 66 | UILaunchImageName 67 | Default 68 | UILaunchImageSize 69 | {375, 812} 70 | 71 | 72 | UILaunchImageMinimumOSVersion 73 | 9.0 74 | UILaunchImageName 75 | Default 76 | UILaunchImageSize 77 | {414, 896} 78 | 79 | 80 | UILaunchImages~ipad 81 | 82 | 83 | UILaunchImageMinimumOSVersion 84 | 9.0 85 | UILaunchImageName 86 | Default 87 | UILaunchImageSize 88 | {768, 1024} 89 | 90 | 91 | UILaunchImageMinimumOSVersion 92 | 9.0 93 | UILaunchImageName 94 | Default 95 | UILaunchImageSize 96 | {1024, 1366} 97 | 98 | 99 | UILaunchImageMinimumOSVersion 100 | 9.0 101 | UILaunchImageName 102 | Default 103 | UILaunchImageSize 104 | {832, 1114} 105 | 106 | 107 | UISupportedInterfaceOrientation 108 | 109 | UIInterfaceOrientationPortrait 110 | UIInterfaceOrientationLandscapeLeft 111 | UIInterfaceOrientationLandscapeRight 112 | 113 | 114 | 115 | -------------------------------------------------------------------------------- /build/ios/BUILD.gn: -------------------------------------------------------------------------------- 1 | # Copyright 2014 The Chromium Authors 2 | # Use of this source code is governed by a BSD-style license that can be 3 | # found in the LICENSE file. 4 | 5 | import("ios_sdk.gni") 6 | 7 | config("xctest_config") { 8 | common_flags = [ 9 | "-F", 10 | "$ios_sdk_platform_path/Developer/Library/Frameworks", 11 | ] 12 | 13 | cflags = common_flags 14 | ldflags = common_flags 15 | 16 | frameworks = [ 17 | "Foundation.framework", 18 | "XCTest.framework", 19 | ] 20 | } 21 | -------------------------------------------------------------------------------- /build/ios/BuildInfo.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | BuildMachineOSBuild 6 | ${BUILD_MACHINE_OS_BUILD} 7 | CFBundleSupportedPlatforms 8 | 9 | ${IOS_SUPPORTED_PLATFORM} 10 | 11 | DTCompiler 12 | ${GCC_VERSION} 13 | DTPlatformBuild 14 | ${IOS_PLATFORM_BUILD} 15 | DTPlatformName 16 | ${IOS_PLATFORM_NAME} 17 | DTPlatformVersion 18 | ${IOS_PLATFORM_VERSION} 19 | DTSDKBuild 20 | ${IOS_SDK_BUILD} 21 | DTSDKName 22 | ${IOS_SDK_NAME} 23 | DTXcode 24 | ${XCODE_VERSION} 25 | DTXcodeBuild 26 | ${XCODE_BUILD} 27 | MinimumOSVersion 28 | ${IOS_DEPLOYMENT_TARGET} 29 | UIDeviceFamily 30 | 31 | 1 32 | 2 33 | 3 34 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /build/ios/Module-Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | ${EXECUTABLE_NAME} 9 | CFBundleIdentifier 10 | ${IOS_BUNDLE_ID_PREFIX}.${MODULE_BUNDLE_ID:rfc1034identifier} 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | ${PRODUCT_NAME} 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1 23 | NSPrincipalClass 24 | ${XCTEST_BUNDLE_PRINCIPAL_CLASS} 25 | 26 | 27 | -------------------------------------------------------------------------------- /build/ios/XCTRunnerAddition+Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleExecutable 6 | ${EXECUTABLE_NAME} 7 | CFBundleIdentifier 8 | ${BUNDLE_IDENTIFIER} 9 | CFBundleName 10 | ${PRODUCT_NAME} 11 | 12 | 13 | -------------------------------------------------------------------------------- /build/ios/entitlements.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | application-identifier 6 | $(AppIdentifierPrefix)$(CFBundleIdentifier) 7 | 8 | 9 | -------------------------------------------------------------------------------- /build/ios/find_signing_identity.py: -------------------------------------------------------------------------------- 1 | # Copyright 2015 The Chromium Authors 2 | # Use of this source code is governed by a BSD-style license that can be 3 | # found in the LICENSE file. 4 | 5 | from __future__ import print_function 6 | 7 | import argparse 8 | import os 9 | import subprocess 10 | import sys 11 | import re 12 | 13 | 14 | def Redact(value, from_nth_char=5): 15 | """Redact value past the N-th character.""" 16 | return value[:from_nth_char] + '*' * (len(value) - from_nth_char) 17 | 18 | 19 | class Identity(object): 20 | """Represents a valid identity.""" 21 | 22 | def __init__(self, identifier, name, team): 23 | self.identifier = identifier 24 | self.name = name 25 | self.team = team 26 | 27 | def redacted(self): 28 | return Identity(Redact(self.identifier), self.name, Redact(self.team)) 29 | 30 | def format(self): 31 | return '%s: "%s (%s)"' % (self.identifier, self.name, self.team) 32 | 33 | 34 | def ListIdentities(): 35 | return subprocess.check_output([ 36 | 'xcrun', 37 | 'security', 38 | 'find-identity', 39 | '-v', 40 | '-p', 41 | 'codesigning', 42 | ]).decode('utf8') 43 | 44 | 45 | def FindValidIdentity(pattern): 46 | """Find all identities matching the pattern.""" 47 | lines = list(l.strip() for l in ListIdentities().splitlines()) 48 | # Look for something like "2) XYZ "iPhone Developer: Name (ABC)"" 49 | regex = re.compile('[0-9]+\) ([A-F0-9]+) "([^"(]*) \(([^)"]*)\)"') 50 | 51 | result = [] 52 | for line in lines: 53 | res = regex.match(line) 54 | if res is None: 55 | continue 56 | if pattern is None or pattern in res.group(2): 57 | result.append(Identity(*res.groups())) 58 | return result 59 | 60 | 61 | def Main(args): 62 | parser = argparse.ArgumentParser('codesign iOS bundles') 63 | parser.add_argument( 64 | '--identity-description', 65 | required=True, 66 | dest='pattern', 67 | help='Text description used to select the code signing identity.') 68 | parsed = parser.parse_args(args) 69 | 70 | identities = FindValidIdentity(parsed.pattern) 71 | if len(identities) == 1: 72 | print(identities[0].identifier, end='') 73 | return 0 74 | 75 | all_identities = FindValidIdentity(None) 76 | 77 | print('Automatic code signing identity selection was enabled but could not') 78 | print('find exactly one codesigning identity matching "%s".' % 79 | parsed.pattern) 80 | print('') 81 | print('Check that the keychain is accessible and that there is exactly one') 82 | print('valid codesigning identity matching the pattern. Here is the parsed') 83 | print('output of `xcrun security find-identity -v -p codesigning`:') 84 | print() 85 | for i, identity in enumerate(all_identities): 86 | print(' %d) %s' % (i + 1, identity.redacted().format())) 87 | print(' %d valid identities found' % (len(all_identities))) 88 | return 1 89 | 90 | 91 | if __name__ == '__main__': 92 | sys.exit(Main(sys.argv[1:])) 93 | -------------------------------------------------------------------------------- /build/ios/ios_sdk.gni: -------------------------------------------------------------------------------- 1 | # Copyright 2015 The Chromium Authors 2 | # Use of this source code is governed by a BSD-style license that can be 3 | # found in the LICENSE file. 4 | 5 | declare_args() { 6 | # The minimum runtime iOS version that built products are expected to run 7 | # on. If empty, the toolchain will choose its own default, typically the 8 | # most recent OS version. 9 | ios_deployment_target = "14.0" 10 | 11 | # SDK path to use. When empty this will use the default SDK based on the 12 | # value of use_ios_simulator. 13 | ios_sdk_path = "" 14 | 15 | # Prefix for CFBundleIdentifier property of iOS bundles (correspond to the 16 | # "Organization Identifier" in Xcode). Code signing will fail if no mobile 17 | # provisioning for the selected code signing identify support that prefix. 18 | ios_app_bundle_id_prefix = "org.chromium" 19 | 20 | # The iOS Code signing identity to use 21 | ios_enable_code_signing = true 22 | ios_code_signing_identity = "" 23 | ios_code_signing_identity_description = "Apple Development" 24 | 25 | # Configure the environment for which to build. Could be either "device", 26 | # "simulator" or "catalyst". If unspecified, then it will be assumed to be 27 | # "simulator" if the target_cpu is "x68" or "x64", "device" otherwise. The 28 | # default is only there for compatibility reasons and will be removed (see 29 | # crbug.com/1138425 for more details). 30 | target_environment = "" 31 | 32 | # The iOS-based platform being targeted. Possible values: "iphoneos", "tvos". 33 | # The default is "iphoneos". 34 | target_platform = "iphoneos" 35 | } 36 | 37 | if (target_environment == "") { 38 | if (current_cpu == "x86" || current_cpu == "x64") { 39 | target_environment = "simulator" 40 | } else { 41 | target_environment = "device" 42 | } 43 | } 44 | 45 | use_ios_simulator = target_environment == "simulator" 46 | 47 | if (ios_sdk_path == "") { 48 | # Compute default target. 49 | if (target_platform == "iphoneos") { 50 | if (use_ios_simulator) { 51 | ios_sdk_name = "iphonesimulator" 52 | ios_sdk_platform = "iPhoneSimulator" 53 | } else { 54 | ios_sdk_name = "iphoneos" 55 | ios_sdk_platform = "iPhoneOS" 56 | } 57 | } else if (target_platform == "tvos") { 58 | if (use_ios_simulator) { 59 | ios_sdk_name = "appletvsimulator" 60 | ios_sdk_platform = "AppleTVSimulator" 61 | } else { 62 | ios_sdk_name = "appletvos" 63 | ios_sdk_platform = "AppleTVOS" 64 | } 65 | } 66 | 67 | ios_sdk_info_args = [ "--get_sdk_info" ] 68 | ios_sdk_info_args += [ ios_sdk_name ] 69 | _ios_sdk_result = exec_script("sdk_info.py", ios_sdk_info_args, "scope") 70 | ios_sdk_path = _ios_sdk_result.sdk_path 71 | ios_sdk_version = _ios_sdk_result.sdk_version 72 | ios_sdk_platform_path = _ios_sdk_result.sdk_platform_path 73 | ios_sdk_build = _ios_sdk_result.sdk_build 74 | xcode_version = _ios_sdk_result.xcode_version 75 | xcode_version_int = _ios_sdk_result.xcode_version_int 76 | xcode_build = _ios_sdk_result.xcode_build 77 | machine_os_build = _ios_sdk_result.machine_os_build 78 | if (use_ios_simulator) { 79 | # This is weird, but Xcode sets DTPlatformBuild to an empty field for 80 | # simulator builds. 81 | ios_platform_build = "" 82 | } else { 83 | ios_platform_build = ios_sdk_build 84 | } 85 | } 86 | 87 | if (ios_enable_code_signing && !use_ios_simulator) { 88 | find_signing_identity_args = [ 89 | "--identity-description", 90 | ios_code_signing_identity_description, 91 | ] 92 | 93 | # If an identity is not provided, look for one on the host 94 | if (ios_code_signing_identity == "") { 95 | _ios_identities = exec_script("find_signing_identity.py", 96 | find_signing_identity_args, 97 | "list lines") 98 | if (_ios_identities == []) { 99 | print("Automatic code signing identity selection was enabled but could") 100 | print("not find exactly one code signing identity matching") 101 | print("$ios_code_signing_identity_description. Check that your keychain") 102 | print("is accessible and that there is a valid code signing identity") 103 | print("listed by `xcrun security find-identity -v -p codesigning`") 104 | print("TIP: Simulator builds don't require code signing...") 105 | assert(false) 106 | } else { 107 | _ios_identities_len = 0 108 | foreach(_, _ios_identities) { 109 | _ios_identities_len += 1 110 | } 111 | 112 | ios_code_signing_identity = _ios_identities[0] 113 | if (_ios_identities_len != 1) { 114 | print("Warning: Multiple codesigning identities match " + 115 | "\"$ios_code_signing_identity_description\"") 116 | foreach(_ios_identity, _ios_identities) { 117 | _selected = "" 118 | if (ios_code_signing_identity == _ios_identity) { 119 | _selected = " (selected)" 120 | } 121 | print("Warning: - $_ios_identity$_selected") 122 | } 123 | print("Warning: Please use either ios_code_signing_identity or ") 124 | print("Warning: ios_code_signing_identity_description variable to ") 125 | print("Warning: control which identity is selected.") 126 | print() 127 | } 128 | } 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /build/ios/strip_arm64e.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 The Chromium Authors 2 | # Use of this source code is governed by a BSD-style license that can be 3 | # found in the LICENSE file. 4 | 5 | """Strip arm64e architecture from a binary if present.""" 6 | 7 | import argparse 8 | import os 9 | import shutil 10 | import subprocess 11 | import sys 12 | 13 | 14 | def check_output(command): 15 | """Returns the output from |command| or propagates error, quitting 16 | script.""" 17 | process = subprocess.Popen(command, 18 | stdout=subprocess.PIPE, 19 | stderr=subprocess.PIPE) 20 | outs, errs = process.communicate() 21 | if process.returncode: 22 | sys.stderr.write('error: command failed with retcode %d: %s\n\n' % 23 | (process.returncode, ' '.join(map(repr, command)))) 24 | sys.stderr.write(errs.decode('UTF-8', errors='ignore')) 25 | sys.exit(process.returncode) 26 | return outs.decode('UTF-8') 27 | 28 | 29 | def check_call(command): 30 | """Invokes |command| or propagates error.""" 31 | check_output(command) 32 | 33 | 34 | def parse_args(args): 35 | """Parses the command-line.""" 36 | parser = argparse.ArgumentParser() 37 | parser.add_argument('--input', required=True, help='Path to input binary') 38 | parser.add_argument('--output', required=True, help='Path to output binary') 39 | return parser.parse_args(args) 40 | 41 | 42 | def get_archs(path): 43 | """Extracts the architectures present in binary at |path|.""" 44 | outputs = check_output(["xcrun", "lipo", "-info", os.path.abspath(path)]) 45 | return outputs.split(': ')[-1].split() 46 | 47 | 48 | def main(args): 49 | parsed = parse_args(args) 50 | 51 | outdir = os.path.dirname(parsed.output) 52 | if not os.path.isdir(outdir): 53 | os.makedirs(outdir) 54 | 55 | if os.path.exists(parsed.output): 56 | os.unlink(parsed.output) 57 | 58 | # As "lipo" fails with an error if asked to remove an architecture that is 59 | # not included, only use it if "arm64e" is present in the binary. Otherwise 60 | # simply copy the file. 61 | if 'arm64e' in get_archs(parsed.input): 62 | check_output([ 63 | "xcrun", "lipo", "-remove", "arm64e", "-output", 64 | os.path.abspath(parsed.output), 65 | os.path.abspath(parsed.input) 66 | ]) 67 | else: 68 | shutil.copy(parsed.input, parsed.output) 69 | 70 | 71 | if __name__ == '__main__': 72 | main(sys.argv[1:]) 73 | -------------------------------------------------------------------------------- /build/platform.gni: -------------------------------------------------------------------------------- 1 | # Copyright 2017 The Chromium Authors 2 | # Use of this source code is governed by a BSD-style license that can be 3 | # found in the LICENSE file. 4 | 5 | mini_chromium_is_mac = false 6 | mini_chromium_is_ios = false 7 | mini_chromium_is_win = false 8 | mini_chromium_is_linux = false 9 | mini_chromium_is_android = false 10 | mini_chromium_is_fuchsia = false 11 | 12 | if (current_os == "mac") { 13 | mini_chromium_is_mac = true 14 | } else if (current_os == "ios") { 15 | mini_chromium_is_ios = true 16 | } else if (current_os == "win") { 17 | mini_chromium_is_win = true 18 | } else if (current_os == "android") { 19 | mini_chromium_is_android = true 20 | } else if (current_os == "linux") { 21 | mini_chromium_is_linux = true 22 | } else if (current_os == "fuchsia") { 23 | mini_chromium_is_fuchsia = true 24 | } 25 | 26 | mini_chromium_is_apple = mini_chromium_is_mac || mini_chromium_is_ios 27 | mini_chromium_is_posix = mini_chromium_is_mac || mini_chromium_is_ios || 28 | mini_chromium_is_linux || mini_chromium_is_android 29 | 30 | declare_args() { 31 | mini_chromium_is_chromeos_lacros = false 32 | mini_chromium_is_chromeos_ash = false 33 | } 34 | 35 | assert(!mini_chromium_is_chromeos_lacros || !mini_chromium_is_chromeos_ash) 36 | assert(!(mini_chromium_is_chromeos_lacros || mini_chromium_is_chromeos_ash) || 37 | mini_chromium_is_linux) 38 | -------------------------------------------------------------------------------- /build/sysroot.gni: -------------------------------------------------------------------------------- 1 | # Copyright 2014 The Chromium Authors 2 | # Use of this source code is governed by a BSD-style license that can be 3 | # found in the LICENSE file. 4 | 5 | import("platform.gni") 6 | 7 | if (mini_chromium_is_posix || mini_chromium_is_fuchsia) { 8 | declare_args() { 9 | # Don't execute if building inside the Fuchsia tree. 10 | if (!(defined(is_fuchsia_tree) && is_fuchsia_tree)) { 11 | # A directory containing the system’s header files and libraries. If empty, 12 | # a suitable default will be chosen. 13 | target_sysroot = "" 14 | } 15 | } 16 | } 17 | 18 | # Don't execute if building inside the Fuchsia tree. 19 | if (mini_chromium_is_mac && !(defined(is_fuchsia_tree) && is_fuchsia_tree)) { 20 | declare_args() { 21 | # The version of the macOS SDK to use. If |target_sysroot| is empty, this 22 | # will inform which SDK version will be chosen. If |mac_sdk| is also empty, 23 | # a suitable default will be chosen. See also |mac_sdk_min|. 24 | mac_sdk = "" 25 | 26 | # The minimum version of the macOS system SDK to use. SDK versions older 27 | # than this will be rejected. If |target_sysroot| and |mac_sdk| are both 28 | # empty, the oldest SDK that’s at least this version will be chosen. If 29 | # empty, the system’s default SDK will be chosen. 30 | mac_sdk_min = "" 31 | } 32 | 33 | find_mac_sdk_args = [] 34 | if (mac_sdk != "") { 35 | find_mac_sdk_args += [ 36 | "--exact", 37 | mac_sdk, 38 | ] 39 | } 40 | if (mac_sdk_min != "") { 41 | find_mac_sdk_args += [ 42 | "--minimum", 43 | mac_sdk_min, 44 | ] 45 | } 46 | if (target_sysroot != "") { 47 | find_mac_sdk_args += [ 48 | "--path", 49 | target_sysroot, 50 | ] 51 | } 52 | 53 | find_mac_sdk_output = 54 | exec_script("find_mac_sdk.py", find_mac_sdk_args, "list lines") 55 | 56 | mac_sdk = find_mac_sdk_output[0] 57 | target_sysroot = find_mac_sdk_output[1] 58 | } else if (mini_chromium_is_ios) { 59 | import("ios/ios_sdk.gni") 60 | target_sysroot = ios_sdk_path 61 | } 62 | 63 | if ((mini_chromium_is_posix || mini_chromium_is_fuchsia) && 64 | (current_os == target_os && current_cpu == target_cpu)) { 65 | sysroot = target_sysroot 66 | } else { 67 | sysroot = "" 68 | } 69 | -------------------------------------------------------------------------------- /build/write_buildflag_header.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | # Copyright 2015 The Chromium Authors 4 | # Use of this source code is governed by a BSD-style license that can be 5 | # found in the LICENSE file. 6 | 7 | # This writes headers for build flags. See buildflag_header.gni for usage of 8 | # this system as a whole. 9 | # 10 | # The parameters are passed in a response file so we don't have to worry about 11 | # command line lengths. The name of the response file is passed on the command 12 | # line. 13 | # 14 | # The format of the response file is: 15 | # [--flags ] 16 | 17 | import optparse 18 | import os 19 | import shlex 20 | import sys 21 | 22 | 23 | class Options: 24 | 25 | def __init__(self, output, rulename, header_guard, flags): 26 | self.output = output 27 | self.rulename = rulename 28 | self.header_guard = header_guard 29 | self.flags = flags 30 | 31 | 32 | def GetOptions(): 33 | parser = optparse.OptionParser() 34 | parser.add_option('--output', help="Output header name inside --gen-dir.") 35 | parser.add_option('--rulename', 36 | help="Helpful name of build rule for including in the " + 37 | "comment at the top of the file.") 38 | parser.add_option('--gen-dir', 39 | help="Path to root of generated file directory tree.") 40 | parser.add_option('--definitions', 41 | help="Name of the response file containing the flags.") 42 | cmdline_options, cmdline_flags = parser.parse_args() 43 | 44 | # Compute header guard by replacing some chars with _ and upper-casing. 45 | header_guard = cmdline_options.output.upper() 46 | header_guard = \ 47 | header_guard.replace('/', '_').replace('\\', '_').replace('.', '_') 48 | header_guard += '_' 49 | 50 | # The actual output file is inside the gen dir. 51 | output = os.path.join(cmdline_options.gen_dir, cmdline_options.output) 52 | 53 | # Definition file in GYP is newline separated, in GN they are shell 54 | # formatted. shlex can parse both of these. 55 | with open(cmdline_options.definitions, 'r') as def_file: 56 | defs = shlex.split(def_file.read()) 57 | flags_index = defs.index('--flags') 58 | 59 | # Everything after --flags are flags. true/false are remapped to 1/0, 60 | # everything else is passed through. 61 | flags = [] 62 | for flag in defs[flags_index + 1:]: 63 | equals_index = flag.index('=') 64 | key = flag[:equals_index] 65 | value = flag[equals_index + 1:] 66 | 67 | # Canonicalize and validate the value. 68 | if value == 'true': 69 | value = '1' 70 | elif value == 'false': 71 | value = '0' 72 | flags.append((key, str(value))) 73 | 74 | return Options(output=output, 75 | rulename=cmdline_options.rulename, 76 | header_guard=header_guard, 77 | flags=flags) 78 | 79 | 80 | def WriteHeader(options): 81 | with open(options.output, 'w') as output_file: 82 | output_file.write("// Generated by build/write_buildflag_header.py\n") 83 | if options.rulename: 84 | output_file.write('// From "' + options.rulename + '"\n') 85 | 86 | output_file.write('\n#ifndef %s\n' % options.header_guard) 87 | output_file.write('#define %s\n\n' % options.header_guard) 88 | output_file.write('#include "build/buildflag.h"\n\n') 89 | 90 | for pair in options.flags: 91 | output_file.write( 92 | '#define MINI_CHROMIUM_INTERNAL_BUILDFLAG_VALUE_%s() (%s)\n' % 93 | pair) 94 | 95 | output_file.write('\n#endif // %s\n' % options.header_guard) 96 | 97 | 98 | def main(): 99 | options = GetOptions() 100 | WriteHeader(options) 101 | 102 | 103 | if __name__ == "__main__": 104 | sys.exit(main()) 105 | -------------------------------------------------------------------------------- /codereview.settings: -------------------------------------------------------------------------------- 1 | # Copyright 2009 The Chromium Authors 2 | # Use of this source code is governed by a BSD-style license that can be 3 | # found in the LICENSE file. 4 | 5 | GERRIT_HOST: True 6 | GERRIT_SQUASH_UPLOADS: True 7 | CODE_REVIEW_SERVER: https://canary-chromium-review.googlesource.com/ 8 | VIEW_VC: https://chromium.googlesource.com/chromium/mini_chromium/+/ 9 | PROJECT: mini_chromium 10 | -------------------------------------------------------------------------------- /testing/BUILD.gn: -------------------------------------------------------------------------------- 1 | # Copyright 2020 The Chromium Authors 2 | # Use of this source code is governed by a BSD-style license that can be 3 | # found in the LICENSE file. 4 | 5 | source_set("testing") { 6 | testonly = true 7 | sources = [ "platform_test.h" ] 8 | } 9 | -------------------------------------------------------------------------------- /testing/platform_test.h: -------------------------------------------------------------------------------- 1 | // Copyright 2020 The Chromium Authors 2 | // Use of this source code is governed by a BSD-style license that can be 3 | // found in the LICENSE file. 4 | 5 | #ifndef MINI_CHROMIUM_TESTING_PLATFORM_TEST_H_ 6 | #define MINI_CHROMIUM_TESTING_PLATFORM_TEST_H_ 7 | 8 | #include "build/build_config.h" 9 | #include "gtest/gtest.h" 10 | 11 | #if BUILDFLAG(IS_APPLE) 12 | 13 | // Note that this uses the direct runtime interface to the autorelease pool. 14 | // https://clang.llvm.org/docs/AutomaticReferenceCounting.html#runtime-support 15 | // This is so this can work when compiled for ARC. 16 | 17 | extern "C" { 18 | void* objc_autoreleasePoolPush(void); 19 | void objc_autoreleasePoolPop(void* pool); 20 | } 21 | 22 | // The implementation is in this header because mini_chromium does not directly 23 | // depend on googletest. Consumers are free to use this interface if they do 24 | // depend on googletest. 25 | class PlatformTest : public testing::Test { 26 | public: 27 | PlatformTest(const PlatformTest&) = delete; 28 | PlatformTest& operator=(const PlatformTest&) = delete; 29 | 30 | ~PlatformTest() override { objc_autoreleasePoolPop(autorelease_pool_); } 31 | 32 | protected: 33 | PlatformTest() : autorelease_pool_(objc_autoreleasePoolPush()) {} 34 | 35 | private: 36 | void* autorelease_pool_; 37 | }; 38 | #else 39 | using PlatformTest = testing::Test; 40 | #endif // BUILDFLAG(IS_APPLE) 41 | 42 | #endif // MINI_CHROMIUM_TESTING_PLATFORM_TEST_H_ 43 | --------------------------------------------------------------------------------