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/files/file_path.h"
11 #include "base/files/file_util.h"
12 #include "base/logging.h"
13 #include "base/mac/foundation_util.h"
14 #include "base/mac/scoped_cftyperef.h"
15 #include "base/mac/scoped_nsobject.h"
16 #include "base/strings/sys_string_conversions.h"
17 #include "base/threading/thread_restrictions.h"
18 #include "content/common/mac/font_descriptor.h"
24 // Work around http://crbug.com/93191, a really nasty memory smasher bug.
25 // On Mac OS X 10.7 ("Lion"), ATS writes to memory it doesn't own.
26 // SendDeactivateFontsInContainerMessage, called by ATSFontDeactivate,
27 // may trash memory whenever dlsym(RTLD_DEFAULT,
28 // "_CTFontManagerUnregisterFontForData") returns NULL. In that case, it tries
29 // to locate that symbol in the CoreText framework, doing some extremely
30 // sloppy string handling resulting in a likelihood that the string
31 // "Text.framework/Versions/A/CoreText" will be written over memory that it
32 // doesn't own. The kicker here is that Apple dlsym always inserts its own
33 // leading underscore, so ATS actually winds up looking up a
34 // __CTFontManagerUnregisterFontForData symbol, which doesn't even exist in
35 // CoreText. It's only got the single-underscore variant corresponding to an
36 // underscoreless extern "C" name.
38 // Providing a single-underscored extern "C" function by this name results in
39 // a __CTFontManagerUnregisterFontForData symbol that, as long as it's public
40 // (not private extern) and unstripped, ATS will find. If it finds it, it
41 // avoids making amateur string mistakes that ruin everyone else's good time.
43 // Since ATS wouldn't normally be able to call this function anyway, it's just
44 // left as a no-op here.
46 // This file seems as good as any other to place this function. It was chosen
47 // because it already interfaces with ATS for other reasons.
49 // SendDeactivateFontsInContainerMessage on 10.6 ("Snow Leopard") appears to
50 // share this bug but this sort of memory corruption wasn't detected until
51 // 10.7. The implementation in 10.5 ("Leopard") does not have this problem.
52 __attribute__((visibility("default")))
53 void _CTFontManagerUnregisterFontForData(NSUInteger, int) {
60 uint32 GetFontIDForFont(const base::FilePath& font_path) {
61 // content/common can't depend on content/browser, so this cannot call
62 // BrowserThread::CurrentlyOn(). Check this is always called on the same
64 static pthread_t thread_id = pthread_self();
65 DCHECK_EQ(pthread_self(), thread_id);
67 // Font loading used to call ATSFontGetContainer()
68 // and used that as font id.
69 // ATS is deprecated and CTFont doesn't seem to have a obvious fixed id for a
70 // font. Since this function is only called from a single thread, use a static
72 typedef std::map<base::FilePath, uint32> FontIdMap;
73 CR_DEFINE_STATIC_LOCAL(FontIdMap, font_ids, ());
75 auto it = font_ids.find(font_path);
76 if (it != font_ids.end())
79 uint32 font_id = font_ids.size() + 1;
80 font_ids[font_path] = font_id;
87 void FontLoader::LoadFont(const FontDescriptor& font,
88 FontLoader::Result* result) {
89 base::ThreadRestrictions::AssertIOAllowed();
92 result->font_data_size = 0;
95 NSFont* font_to_encode = font.ToNSFont();
97 // Load appropriate NSFont.
98 if (!font_to_encode) {
99 DLOG(ERROR) << "Failed to load font " << font.font_name;
103 // NSFont -> File path.
104 // Warning: Calling this function on a font activated from memory will result
105 // in failure with a -50 - paramErr. This may occur if
106 // CreateCGFontFromBuffer() is called in the same process as this function
107 // e.g. when writing a unit test that exercises these two functions together.
108 // If said unit test were to load a system font and activate it from memory
109 // it becomes impossible for the system to the find the original file ref
110 // since the font now lives in memory as far as it's concerned.
111 CTFontRef ct_font_to_encode = (CTFontRef)font_to_encode;
112 base::scoped_nsobject<NSURL> font_url(
113 base::mac::CFToNSCast(base::mac::CFCastStrict<CFURLRef>(
114 CTFontCopyAttribute(ct_font_to_encode, kCTFontURLAttribute))));
115 if (![font_url isFileURL]) {
116 DLOG(ERROR) << "Failed to find font file for " << font.font_name;
120 base::FilePath font_path = base::mac::NSStringToFilePath([font_url path]);
122 // Load file into shared memory buffer.
123 int64 font_file_size_64 = -1;
124 if (!base::GetFileSize(font_path, &font_file_size_64)) {
125 DLOG(ERROR) << "Couldn't get font file size for " << font_path.value();
129 if (font_file_size_64 <= 0 || font_file_size_64 >= kint32max) {
130 DLOG(ERROR) << "Bad size for font file " << font_path.value();
134 int32 font_file_size_32 = static_cast<int32>(font_file_size_64);
135 if (!result->font_data.CreateAndMapAnonymous(font_file_size_32)) {
136 DLOG(ERROR) << "Failed to create shmem area for " << font.font_name;
140 int32 amt_read = base::ReadFile(font_path,
141 reinterpret_cast<char*>(result->font_data.memory()),
143 if (amt_read != font_file_size_32) {
144 DLOG(ERROR) << "Failed to read font data for " << font_path.value();
148 result->font_data_size = font_file_size_32;
149 result->font_id = GetFontIDForFont(font_path);
153 bool FontLoader::CGFontRefFromBuffer(base::SharedMemoryHandle font_data,
154 uint32 font_data_size,
158 using base::SharedMemory;
159 DCHECK(SharedMemory::IsHandleValid(font_data));
160 DCHECK_GT(font_data_size, 0U);
162 SharedMemory shm(font_data, /*read_only=*/true);
163 if (!shm.Map(font_data_size))
166 NSData* data = [NSData dataWithBytes:shm.memory()
167 length:font_data_size];
168 base::ScopedCFTypeRef<CGDataProviderRef> provider(
169 CGDataProviderCreateWithCFData(base::mac::NSToCFCast(data)));
173 *out = CGFontCreateWithDataProvider(provider.get());