1 /*
2  * Copyright (C) 2013 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define ATRACE_TAG ATRACE_TAG_VIEW
18 #include <gui/TraceUtils.h>
19 #include <hwui/Typeface.h>
20 #include <minikin/FontCollection.h>
21 #include <minikin/FontFamily.h>
22 #include <minikin/FontFileParser.h>
23 #include <minikin/LocaleList.h>
24 #include <minikin/MinikinFontFactory.h>
25 #include <minikin/SystemFonts.h>
26 #include <nativehelper/ScopedPrimitiveArray.h>
27 #include <nativehelper/ScopedUtfChars.h>
28 
29 #include <mutex>
30 #include <unordered_map>
31 
32 #include "FontUtils.h"
33 #include "GraphicsJNI.h"
34 #include "SkData.h"
35 #include "SkTypeface.h"
36 #include "fonts/Font.h"
37 
38 #ifdef __ANDROID__
39 #include <sys/stat.h>
40 #endif
41 
42 using namespace android;
43 
toTypeface(jlong ptr)44 static inline Typeface* toTypeface(jlong ptr) {
45     return reinterpret_cast<Typeface*>(ptr);
46 }
47 
toJLong(Ptr ptr)48 template<typename Ptr> static inline jlong toJLong(Ptr ptr) {
49     return reinterpret_cast<jlong>(ptr);
50 }
51 
Typeface_createFromTypeface(JNIEnv * env,jobject,jlong familyHandle,jint style)52 static jlong Typeface_createFromTypeface(JNIEnv* env, jobject, jlong familyHandle, jint style) {
53     Typeface* family = toTypeface(familyHandle);
54     Typeface* face = Typeface::createRelative(family, (Typeface::Style)style);
55     // TODO: the following logic shouldn't be necessary, the above should always succeed.
56     // Try to find the closest matching font, using the standard heuristic
57     if (NULL == face) {
58         face = Typeface::createRelative(family, (Typeface::Style)(style ^ Typeface::kItalic));
59     }
60     for (int i = 0; NULL == face && i < 4; i++) {
61         face = Typeface::createRelative(family, (Typeface::Style)i);
62     }
63     return toJLong(face);
64 }
65 
Typeface_createFromTypefaceWithExactStyle(JNIEnv * env,jobject,jlong nativeInstance,jint weight,jboolean italic)66 static jlong Typeface_createFromTypefaceWithExactStyle(JNIEnv* env, jobject, jlong nativeInstance,
67         jint weight, jboolean italic) {
68     return toJLong(Typeface::createAbsolute(toTypeface(nativeInstance), weight, italic));
69 }
70 
Typeface_createFromTypefaceWithVariation(JNIEnv * env,jobject,jlong familyHandle,jobject listOfAxis)71 static jlong Typeface_createFromTypefaceWithVariation(JNIEnv* env, jobject, jlong familyHandle,
72         jobject listOfAxis) {
73     std::vector<minikin::FontVariation> variations;
74     ListHelper list(env, listOfAxis);
75     for (jint i = 0; i < list.size(); i++) {
76         jobject axisObject = list.get(i);
77         if (axisObject == nullptr) {
78             continue;
79         }
80         AxisHelper axis(env, axisObject);
81         variations.push_back(minikin::FontVariation(axis.getTag(), axis.getStyleValue()));
82     }
83     return toJLong(Typeface::createFromTypefaceWithVariation(toTypeface(familyHandle), variations));
84 }
85 
Typeface_createWeightAlias(JNIEnv * env,jobject,jlong familyHandle,jint weight)86 static jlong Typeface_createWeightAlias(JNIEnv* env, jobject, jlong familyHandle, jint weight) {
87     return toJLong(Typeface::createWithDifferentBaseWeight(toTypeface(familyHandle), weight));
88 }
89 
releaseFunc(jlong ptr)90 static void releaseFunc(jlong ptr) {
91     delete toTypeface(ptr);
92 }
93 
94 // CriticalNative
Typeface_getReleaseFunc(CRITICAL_JNI_PARAMS)95 static jlong Typeface_getReleaseFunc(CRITICAL_JNI_PARAMS) {
96     return toJLong(&releaseFunc);
97 }
98 
99 // CriticalNative
Typeface_getStyle(CRITICAL_JNI_PARAMS_COMMA jlong faceHandle)100 static jint Typeface_getStyle(CRITICAL_JNI_PARAMS_COMMA jlong faceHandle) {
101     return toTypeface(faceHandle)->fAPIStyle;
102 }
103 
104 // CriticalNative
Typeface_getWeight(CRITICAL_JNI_PARAMS_COMMA jlong faceHandle)105 static jint Typeface_getWeight(CRITICAL_JNI_PARAMS_COMMA jlong faceHandle) {
106     return toTypeface(faceHandle)->fStyle.weight();
107 }
108 
Typeface_createFromArray(JNIEnv * env,jobject,jlongArray familyArray,jlong fallbackPtr,int weight,int italic)109 static jlong Typeface_createFromArray(JNIEnv *env, jobject, jlongArray familyArray,
110                                       jlong fallbackPtr, int weight, int italic) {
111     ScopedLongArrayRO families(env, familyArray);
112     Typeface* typeface = (fallbackPtr == 0) ? nullptr : toTypeface(fallbackPtr);
113     std::vector<std::shared_ptr<minikin::FontFamily>> familyVec;
114     familyVec.reserve(families.size());
115     for (size_t i = 0; i < families.size(); i++) {
116         FontFamilyWrapper* family = reinterpret_cast<FontFamilyWrapper*>(families[i]);
117         familyVec.emplace_back(family->family);
118     }
119     return toJLong(Typeface::createFromFamilies(std::move(familyVec), weight, italic, typeface));
120 }
121 
122 // CriticalNative
Typeface_setDefault(CRITICAL_JNI_PARAMS_COMMA jlong faceHandle)123 static void Typeface_setDefault(CRITICAL_JNI_PARAMS_COMMA jlong faceHandle) {
124     Typeface::setDefault(toTypeface(faceHandle));
125     minikin::SystemFonts::registerDefault(toTypeface(faceHandle)->fFontCollection);
126 }
127 
Typeface_getSupportedAxes(JNIEnv * env,jobject,jlong faceHandle)128 static jobject Typeface_getSupportedAxes(JNIEnv *env, jobject, jlong faceHandle) {
129     Typeface* face = toTypeface(faceHandle);
130     const size_t length = face->fFontCollection->getSupportedAxesCount();
131     if (length == 0) {
132         return nullptr;
133     }
134     std::vector<jint> tagVec(length);
135     for (size_t i = 0; i < length; i++) {
136         tagVec[i] = face->fFontCollection->getSupportedAxisAt(i);
137     }
138     std::sort(tagVec.begin(), tagVec.end());
139     const jintArray result = env->NewIntArray(length);
140     env->SetIntArrayRegion(result, 0, length, tagVec.data());
141     return result;
142 }
143 
Typeface_registerGenericFamily(JNIEnv * env,jobject,jstring familyName,jlong ptr)144 static void Typeface_registerGenericFamily(JNIEnv *env, jobject, jstring familyName, jlong ptr) {
145     ScopedUtfChars familyNameChars(env, familyName);
146     minikin::SystemFonts::registerFallback(familyNameChars.c_str(),
147                                            toTypeface(ptr)->fFontCollection);
148 }
149 
150 #ifdef __ANDROID__
151 
getVerity(const std::string & path)152 static bool getVerity(const std::string& path) {
153     struct statx out = {};
154     if (statx(AT_FDCWD, path.c_str(), 0 /* flags */, STATX_ALL, &out) != 0) {
155         ALOGE("statx failed for %s, errno = %d", path.c_str(), errno);
156         return false;
157     }
158 
159     // Validity check.
160     if ((out.stx_attributes_mask & STATX_ATTR_VERITY) == 0) {
161         // STATX_ATTR_VERITY not supported by kernel.
162         return false;
163     }
164 
165     return (out.stx_attributes & STATX_ATTR_VERITY) != 0;
166 }
167 
168 #else
169 
getVerity(const std::string &)170 static bool getVerity(const std::string&) {
171     // verity check is not enabled on desktop.
172     return false;
173 }
174 
175 #endif  // __ANDROID__
176 
makeSkDataCached(const std::string & path,bool hasVerity)177 static sk_sp<SkData> makeSkDataCached(const std::string& path, bool hasVerity) {
178     // We don't clear cache as Typeface objects created by Typeface_readTypefaces() will be stored
179     // in a static field and will not be garbage collected.
180     static std::unordered_map<std::string, sk_sp<SkData>> cache;
181     static std::mutex mutex;
182     ALOG_ASSERT(!path.empty());
183     if (hasVerity && !getVerity(path)) {
184         LOG_ALWAYS_FATAL("verity bit was removed from %s", path.c_str());
185         return nullptr;
186     }
187     std::lock_guard lock{mutex};
188     sk_sp<SkData>& entry = cache[path];
189     if (entry.get() == nullptr) {
190         entry = SkData::MakeFromFileName(path.c_str());
191     }
192     return entry;
193 }
194 
195 class MinikinFontSkiaFactory : minikin::MinikinFontFactory {
196 private:
MinikinFontSkiaFactory()197     MinikinFontSkiaFactory() : MinikinFontFactory() { MinikinFontFactory::setInstance(this); }
198 
199 public:
init()200     static void init() { static MinikinFontSkiaFactory factory; }
201     void skip(minikin::BufferReader* reader) const override;
202     std::shared_ptr<minikin::MinikinFont> create(minikin::BufferReader reader) const override;
203     void write(minikin::BufferWriter* writer, const minikin::MinikinFont* typeface) const override;
204 };
205 
skip(minikin::BufferReader * reader) const206 void MinikinFontSkiaFactory::skip(minikin::BufferReader* reader) const {
207     // Advance reader's position.
208     reader->skipString(); // fontPath
209     reader->skip<int>(); // fontIndex
210     reader->skipArray<minikin::FontVariation>(); // axesPtr, axesCount
211     bool hasVerity = static_cast<bool>(reader->read<int8_t>());
212     if (hasVerity) {
213         reader->skip<uint32_t>(); // expectedFontRevision
214         reader->skipString(); // expectedPostScriptName
215     }
216 }
217 
create(minikin::BufferReader reader) const218 std::shared_ptr<minikin::MinikinFont> MinikinFontSkiaFactory::create(
219         minikin::BufferReader reader) const {
220     std::string_view fontPath = reader.readString();
221     std::string path(fontPath.data(), fontPath.size());
222     ATRACE_FORMAT("Loading font %s", path.c_str());
223     int fontIndex = reader.read<int>();
224     const minikin::FontVariation* axesPtr;
225     uint32_t axesCount;
226     std::tie(axesPtr, axesCount) = reader.readArray<minikin::FontVariation>();
227     bool hasVerity = static_cast<bool>(reader.read<int8_t>());
228     uint32_t expectedFontRevision;
229     std::string_view expectedPostScriptName;
230     if (hasVerity) {
231         expectedFontRevision = reader.read<uint32_t>();
232         expectedPostScriptName = reader.readString();
233     }
234     sk_sp<SkData> data = makeSkDataCached(path, hasVerity);
235     if (data.get() == nullptr) {
236         // This may happen if:
237         // 1. When the process failed to open the file (e.g. invalid path or permission).
238         // 2. When the process failed to map the file (e.g. hitting max_map_count limit).
239         ALOGE("Failed to make SkData from file name: %s", path.c_str());
240         return nullptr;
241     }
242     const void* fontPtr = data->data();
243     size_t fontSize = data->size();
244     if (hasVerity) {
245         // Verify font metadata if verity is enabled.
246         minikin::FontFileParser parser(fontPtr, fontSize, fontIndex);
247         std::optional<uint32_t> revision = parser.getFontRevision();
248         if (!revision.has_value() || revision.value() != expectedFontRevision) {
249             LOG_ALWAYS_FATAL("Wrong font revision: %s", path.c_str());
250             return nullptr;
251         }
252         std::optional<std::string> psName = parser.getPostScriptName();
253         if (!psName.has_value() || psName.value() != expectedPostScriptName) {
254             LOG_ALWAYS_FATAL("Wrong PostScript name: %s", path.c_str());
255             return nullptr;
256         }
257     }
258     std::vector<minikin::FontVariation> axes(axesPtr, axesPtr + axesCount);
259     std::shared_ptr<minikin::MinikinFont> minikinFont = fonts::createMinikinFontSkia(
260             std::move(data), fontPath, fontPtr, fontSize, fontIndex, axes);
261     if (minikinFont == nullptr) {
262         ALOGE("Failed to create MinikinFontSkia: %s", path.c_str());
263         return nullptr;
264     }
265     return minikinFont;
266 }
267 
write(minikin::BufferWriter * writer,const minikin::MinikinFont * typeface) const268 void MinikinFontSkiaFactory::write(minikin::BufferWriter* writer,
269                                    const minikin::MinikinFont* typeface) const {
270     // When you change the format of font metadata, please update code to parse
271     // typefaceMetadataReader() in
272     // frameworks/base/libs/hwui/jni/fonts/Font.cpp too.
273     const std::string& path = typeface->GetFontPath();
274     writer->writeString(path);
275     writer->write<int>(typeface->GetFontIndex());
276     const std::vector<minikin::FontVariation>& axes = typeface->GetAxes();
277     writer->writeArray<minikin::FontVariation>(axes.data(), axes.size());
278     bool hasVerity = getVerity(path);
279     writer->write<int8_t>(static_cast<int8_t>(hasVerity));
280     if (hasVerity) {
281         // Write font metadata for verification only when verity is enabled.
282         minikin::FontFileParser parser(typeface->GetFontData(), typeface->GetFontSize(),
283                                        typeface->GetFontIndex());
284         std::optional<uint32_t> revision = parser.getFontRevision();
285         LOG_ALWAYS_FATAL_IF(!revision.has_value());
286         writer->write<uint32_t>(revision.value());
287         std::optional<std::string> psName = parser.getPostScriptName();
288         LOG_ALWAYS_FATAL_IF(!psName.has_value());
289         writer->writeString(psName.value());
290     }
291 }
292 
Typeface_writeTypefaces(JNIEnv * env,jobject,jobject buffer,jint position,jlongArray faceHandles)293 static jint Typeface_writeTypefaces(JNIEnv* env, jobject, jobject buffer, jint position,
294                                     jlongArray faceHandles) {
295     MinikinFontSkiaFactory::init();
296     ScopedLongArrayRO faces(env, faceHandles);
297     std::vector<Typeface*> typefaces;
298     typefaces.reserve(faces.size());
299     for (size_t i = 0; i < faces.size(); i++) {
300         typefaces.push_back(toTypeface(faces[i]));
301     }
302     void* addr = buffer == nullptr ? nullptr : env->GetDirectBufferAddress(buffer);
303     if (addr != nullptr &&
304         reinterpret_cast<intptr_t>(addr) % minikin::BufferReader::kMaxAlignment != 0) {
305         ALOGE("addr (%p) must be aligned at kMaxAlignment, but it was not.", addr);
306         return 0;
307     }
308     minikin::BufferWriter writer(addr, position);
309     std::vector<std::shared_ptr<minikin::FontCollection>> fontCollections;
310     std::unordered_map<std::shared_ptr<minikin::FontCollection>, size_t> fcToIndex;
311     for (Typeface* typeface : typefaces) {
312         bool inserted = fcToIndex.emplace(typeface->fFontCollection, fontCollections.size()).second;
313         if (inserted) {
314             fontCollections.push_back(typeface->fFontCollection);
315         }
316     }
317     minikin::FontCollection::writeVector(&writer, fontCollections);
318     writer.write<uint32_t>(typefaces.size());
319     for (Typeface* typeface : typefaces) {
320       writer.write<uint32_t>(fcToIndex.find(typeface->fFontCollection)->second);
321       typeface->fStyle.writeTo(&writer);
322       writer.write<Typeface::Style>(typeface->fAPIStyle);
323       writer.write<int>(typeface->fBaseWeight);
324     }
325     return static_cast<jint>(writer.size());
326 }
327 
Typeface_readTypefaces(JNIEnv * env,jobject,jobject buffer,jint position)328 static jlongArray Typeface_readTypefaces(JNIEnv* env, jobject, jobject buffer, jint position) {
329     MinikinFontSkiaFactory::init();
330     void* addr = buffer == nullptr ? nullptr : env->GetDirectBufferAddress(buffer);
331     if (addr == nullptr) {
332         ALOGE("Passed a null buffer.");
333         return nullptr;
334     }
335     if (reinterpret_cast<intptr_t>(addr) % minikin::BufferReader::kMaxAlignment != 0) {
336         ALOGE("addr (%p) must be aligned at kMaxAlignment, but it was not.", addr);
337         return nullptr;
338     }
339     minikin::BufferReader reader(addr, position);
340     std::vector<std::shared_ptr<minikin::FontCollection>> fontCollections =
341             minikin::FontCollection::readVector(&reader);
342     uint32_t typefaceCount = reader.read<uint32_t>();
343     std::vector<jlong> faceHandles;
344     faceHandles.reserve(typefaceCount);
345     for (uint32_t i = 0; i < typefaceCount; i++) {
346         Typeface* typeface = new Typeface;
347         typeface->fFontCollection = fontCollections[reader.read<uint32_t>()];
348         typeface->fStyle = minikin::FontStyle(&reader);
349         typeface->fAPIStyle = reader.read<Typeface::Style>();
350         typeface->fBaseWeight = reader.read<int>();
351         faceHandles.push_back(toJLong(typeface));
352     }
353     const jlongArray result = env->NewLongArray(typefaceCount);
354     env->SetLongArrayRegion(result, 0, typefaceCount, faceHandles.data());
355     return result;
356 }
357 
Typeface_forceSetStaticFinalField(JNIEnv * env,jclass cls,jstring fieldName,jobject typeface)358 static void Typeface_forceSetStaticFinalField(JNIEnv *env, jclass cls, jstring fieldName,
359         jobject typeface) {
360     ScopedUtfChars fieldNameChars(env, fieldName);
361     jfieldID fid =
362             env->GetStaticFieldID(cls, fieldNameChars.c_str(), "Landroid/graphics/Typeface;");
363     if (fid == 0) {
364         jniThrowRuntimeException(env, "Unable to find field");
365         return;
366     }
367     env->SetStaticObjectField(cls, fid, typeface);
368 }
369 
370 // Regular JNI
Typeface_warmUpCache(JNIEnv * env,jobject,jstring jFilePath)371 static void Typeface_warmUpCache(JNIEnv* env, jobject, jstring jFilePath) {
372     ScopedUtfChars filePath(env, jFilePath);
373     makeSkDataCached(filePath.c_str(), false /* fs verity */);
374 }
375 
376 // Critical Native
Typeface_addFontCollection(CRITICAL_JNI_PARAMS_COMMA jlong faceHandle)377 static void Typeface_addFontCollection(CRITICAL_JNI_PARAMS_COMMA jlong faceHandle) {
378     std::shared_ptr<minikin::FontCollection> collection = toTypeface(faceHandle)->fFontCollection;
379     minikin::SystemFonts::addFontMap(std::move(collection));
380 }
381 
382 // Fast Native
Typeface_registerLocaleList(JNIEnv * env,jobject,jstring jLocales)383 static void Typeface_registerLocaleList(JNIEnv* env, jobject, jstring jLocales) {
384     ScopedUtfChars locales(env, jLocales);
385     minikin::registerLocaleList(locales.c_str());
386 }
387 
388 ///////////////////////////////////////////////////////////////////////////////
389 
390 static const JNINativeMethod gTypefaceMethods[] = {
391         {"nativeCreateFromTypeface", "(JI)J", (void*)Typeface_createFromTypeface},
392         {"nativeCreateFromTypefaceWithExactStyle", "(JIZ)J",
393          (void*)Typeface_createFromTypefaceWithExactStyle},
394         {"nativeCreateFromTypefaceWithVariation", "(JLjava/util/List;)J",
395          (void*)Typeface_createFromTypefaceWithVariation},
396         {"nativeCreateWeightAlias", "(JI)J", (void*)Typeface_createWeightAlias},
397         {"nativeGetReleaseFunc", "()J", (void*)Typeface_getReleaseFunc},
398         {"nativeGetStyle", "(J)I", (void*)Typeface_getStyle},
399         {"nativeGetWeight", "(J)I", (void*)Typeface_getWeight},
400         {"nativeCreateFromArray", "([JJII)J", (void*)Typeface_createFromArray},
401         {"nativeSetDefault", "(J)V", (void*)Typeface_setDefault},
402         {"nativeGetSupportedAxes", "(J)[I", (void*)Typeface_getSupportedAxes},
403         {"nativeRegisterGenericFamily", "(Ljava/lang/String;J)V",
404          (void*)Typeface_registerGenericFamily},
405         {"nativeWriteTypefaces", "(Ljava/nio/ByteBuffer;I[J)I", (void*)Typeface_writeTypefaces},
406         {"nativeReadTypefaces", "(Ljava/nio/ByteBuffer;I)[J", (void*)Typeface_readTypefaces},
407         {"nativeForceSetStaticFinalField", "(Ljava/lang/String;Landroid/graphics/Typeface;)V",
408          (void*)Typeface_forceSetStaticFinalField},
409         {"nativeWarmUpCache", "(Ljava/lang/String;)V", (void*)Typeface_warmUpCache},
410         {"nativeAddFontCollections", "(J)V", (void*)Typeface_addFontCollection},
411         {"nativeRegisterLocaleList", "(Ljava/lang/String;)V", (void*)Typeface_registerLocaleList},
412 };
413 
register_android_graphics_Typeface(JNIEnv * env)414 int register_android_graphics_Typeface(JNIEnv* env)
415 {
416     return RegisterMethodsOrDie(env, "android/graphics/Typeface", gTypefaceMethods,
417                                 NELEM(gTypefaceMethods));
418 }
419