• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.
4
5#include "content/common/mac/font_loader.h"
6
7#import <Cocoa/Cocoa.h>
8
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/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"
20
21#include <map>
22
23extern "C" {
24
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.
38//
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.
43//
44// Since ATS wouldn't normally be able to call this function anyway, it's just
45// left as a no-op here.
46//
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.
49//
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")))
54void _CTFontManagerUnregisterFontForData(NSUInteger, int) {
55}
56
57}  // extern "C"
58
59namespace {
60
61uint32 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
64  // thread.
65  static pthread_t thread_id = pthread_self();
66  DCHECK_EQ(pthread_self(), thread_id);
67
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
72  // map to store ids.
73  typedef std::map<base::FilePath, uint32> FontIdMap;
74  CR_DEFINE_STATIC_LOCAL(FontIdMap, font_ids, ());
75
76  auto it = font_ids.find(font_path);
77  if (it != font_ids.end())
78    return it->second;
79
80  uint32 font_id = font_ids.size() + 1;
81  font_ids[font_path] = font_id;
82  return font_id;
83}
84
85}  // namespace
86
87// static
88void FontLoader::LoadFont(const FontDescriptor& font,
89                          FontLoader::Result* result) {
90  base::ThreadRestrictions::AssertIOAllowed();
91
92  DCHECK(result);
93  result->font_data_size = 0;
94  result->font_id = 0;
95
96  NSFont* font_to_encode = font.ToNSFont();
97  // Used only for logging.
98  std::string font_name([[font_to_encode fontName] UTF8String]);
99
100  // Load appropriate NSFont.
101  if (!font_to_encode) {
102    DLOG(ERROR) << "Failed to load font " << font_name;
103    return;
104  }
105
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;
120    return;
121  }
122
123  base::FilePath font_path = base::mac::NSStringToFilePath([font_url path]);
124
125  // Load file into shared memory buffer.
126  int64 font_file_size_64 = -1;
127  if (!base::GetFileSize(font_path, &font_file_size_64)) {
128    DLOG(ERROR) << "Couldn't get font file size for " << font_path.value();
129    return;
130  }
131
132  if (font_file_size_64 <= 0 || font_file_size_64 >= kint32max) {
133    DLOG(ERROR) << "Bad size for font file " << font_path.value();
134    return;
135  }
136
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;
140    return;
141  }
142
143  int32 amt_read = base::ReadFile(font_path,
144      reinterpret_cast<char*>(result->font_data.memory()),
145      font_file_size_32);
146  if (amt_read != font_file_size_32) {
147    DLOG(ERROR) << "Failed to read font data for " << font_path.value();
148    return;
149  }
150
151  result->font_data_size = font_file_size_32;
152  result->font_id = GetFontIDForFont(font_path);
153}
154
155// static
156bool FontLoader::CGFontRefFromBuffer(base::SharedMemoryHandle font_data,
157                                     uint32 font_data_size,
158                                     CGFontRef* out) {
159  *out = NULL;
160
161  using base::SharedMemory;
162  DCHECK(SharedMemory::IsHandleValid(font_data));
163  DCHECK_GT(font_data_size, 0U);
164
165  SharedMemory shm(font_data, /*read_only=*/true);
166  if (!shm.Map(font_data_size))
167    return false;
168
169  NSData* data = [NSData dataWithBytes:shm.memory()
170                                length:font_data_size];
171  base::ScopedCFTypeRef<CGDataProviderRef> provider(
172      CGDataProviderCreateWithCFData(base::mac::NSToCFCast(data)));
173  if (!provider)
174    return false;
175
176  *out = CGFontCreateWithDataProvider(provider.get());
177
178  if (*out == NULL)
179    return false;
180
181  return true;
182}
183