1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "content/common/mac/font_loader.h"
7 #import <Cocoa/Cocoa.h>
9 #include "base/basictypes.h"
10 #include "base/file_util.h"
11 #include "base/files/file_path.h"
12 #include "base/logging.h"
13 #include "base/mac/foundation_util.h"
14 #include "base/mac/mac_util.h"
15 #include "base/mac/scoped_cftyperef.h"
16 #include "base/mac/scoped_nsobject.h"
17 #include "base/strings/sys_string_conversions.h"
18 #include "base/threading/thread_restrictions.h"
19 #include "content/common/mac/font_descriptor.h"
25 // Work around http://crbug.com/93191, a really nasty memory smasher bug.
26 // On Mac OS X 10.7 ("Lion"), ATS writes to memory it doesn't own.
27 // SendDeactivateFontsInContainerMessage, called by ATSFontDeactivate,
28 // may trash memory whenever dlsym(RTLD_DEFAULT,
29 // "_CTFontManagerUnregisterFontForData") returns NULL. In that case, it tries
30 // to locate that symbol in the CoreText framework, doing some extremely
31 // sloppy string handling resulting in a likelihood that the string
32 // "Text.framework/Versions/A/CoreText" will be written over memory that it
33 // doesn't own. The kicker here is that Apple dlsym always inserts its own
34 // leading underscore, so ATS actually winds up looking up a
35 // __CTFontManagerUnregisterFontForData symbol, which doesn't even exist in
36 // CoreText. It's only got the single-underscore variant corresponding to an
37 // underscoreless extern "C" name.
39 // Providing a single-underscored extern "C" function by this name results in
40 // a __CTFontManagerUnregisterFontForData symbol that, as long as it's public
41 // (not private extern) and unstripped, ATS will find. If it finds it, it
42 // avoids making amateur string mistakes that ruin everyone else's good time.
44 // Since ATS wouldn't normally be able to call this function anyway, it's just
45 // left as a no-op here.
47 // This file seems as good as any other to place this function. It was chosen
48 // because it already interfaces with ATS for other reasons.
50 // SendDeactivateFontsInContainerMessage on 10.6 ("Snow Leopard") appears to
51 // share this bug but this sort of memory corruption wasn't detected until
52 // 10.7. The implementation in 10.5 ("Leopard") does not have this problem.
53 __attribute__((visibility("default")))
54 void _CTFontManagerUnregisterFontForData(NSUInteger, int) {
61 uint32 GetFontIDForFont(const base::FilePath& font_path) {
62 // content/common can't depend on content/browser, so this cannot call
63 // BrowserThread::CurrentlyOn(). Check this is always called on the same
65 static pthread_t thread_id = pthread_self();
66 DCHECK_EQ(pthread_self(), thread_id);
68 // Font loading used to call ATSFontGetContainer()
69 // and used that as font id.
70 // ATS is deprecated and CTFont doesn't seem to have a obvious fixed id for a
71 // font. Since this function is only called from a single thread, use a static
73 typedef std::map<base::FilePath, uint32> FontIdMap;
74 CR_DEFINE_STATIC_LOCAL(FontIdMap, font_ids, ());
76 auto it = font_ids.find(font_path);
77 if (it != font_ids.end())
80 uint32 font_id = font_ids.size() + 1;
81 font_ids[font_path] = font_id;
88 void FontLoader::LoadFont(const FontDescriptor& font,
89 FontLoader::Result* result) {
90 base::ThreadRestrictions::AssertIOAllowed();
93 result->font_data_size = 0;
96 NSFont* font_to_encode = font.ToNSFont();
97 // Used only for logging.
98 std::string font_name([[font_to_encode fontName] UTF8String]);
100 // Load appropriate NSFont.
101 if (!font_to_encode) {
102 DLOG(ERROR) << "Failed to load font " << font_name;
106 // NSFont -> File path.
107 // Warning: Calling this function on a font activated from memory will result
108 // in failure with a -50 - paramErr. This may occur if
109 // CreateCGFontFromBuffer() is called in the same process as this function
110 // e.g. when writing a unit test that exercises these two functions together.
111 // If said unit test were to load a system font and activate it from memory
112 // it becomes impossible for the system to the find the original file ref
113 // since the font now lives in memory as far as it's concerned.
114 CTFontRef ct_font_to_encode = (CTFontRef)font_to_encode;
115 base::scoped_nsobject<NSURL> font_url(
116 base::mac::CFToNSCast(base::mac::CFCastStrict<CFURLRef>(
117 CTFontCopyAttribute(ct_font_to_encode, kCTFontURLAttribute))));
118 if (![font_url isFileURL]) {
119 DLOG(ERROR) << "Failed to find font file for " << font_name;
123 base::FilePath font_path = base::mac::NSStringToFilePath([font_url path]);
125 // Load file into shared memory buffer.
126 int64 font_file_size_64 = -1;
127 if (!file_util::GetFileSize(font_path, &font_file_size_64)) {
128 DLOG(ERROR) << "Couldn't get font file size for " << font_path.value();
132 if (font_file_size_64 <= 0 || font_file_size_64 >= kint32max) {
133 DLOG(ERROR) << "Bad size for font file " << font_path.value();
137 int32 font_file_size_32 = static_cast<int32>(font_file_size_64);
138 if (!result->font_data.CreateAndMapAnonymous(font_file_size_32)) {
139 DLOG(ERROR) << "Failed to create shmem area for " << font_name;
143 int32 amt_read = file_util::ReadFile(font_path,
144 reinterpret_cast<char*>(result->font_data.memory()),
146 if (amt_read != font_file_size_32) {
147 DLOG(ERROR) << "Failed to read font data for " << font_path.value();
151 result->font_data_size = font_file_size_32;
152 result->font_id = GetFontIDForFont(font_path);
156 bool FontLoader::CGFontRefFromBuffer(base::SharedMemoryHandle font_data,
157 uint32 font_data_size,
161 using base::SharedMemory;
162 DCHECK(SharedMemory::IsHandleValid(font_data));
163 DCHECK_GT(font_data_size, 0U);
165 SharedMemory shm(font_data, /*read_only=*/true);
166 if (!shm.Map(font_data_size))
169 NSData* data = [NSData dataWithBytes:shm.memory()
170 length:font_data_size];
171 base::ScopedCFTypeRef<CGDataProviderRef> provider(
172 CGDataProviderCreateWithCFData(base::mac::NSToCFCast(data)));
176 *out = CGFontCreateWithDataProvider(provider.get());