Path: blob/master/src/java.desktop/share/native/libharfbuzz/hb-blob.cc
41149 views
/*1* Copyright © 2009 Red Hat, Inc.2* Copyright © 2018 Ebrahim Byagowi3*4* This is part of HarfBuzz, a text shaping library.5*6* Permission is hereby granted, without written agreement and without7* license or royalty fees, to use, copy, modify, and distribute this8* software and its documentation for any purpose, provided that the9* above copyright notice and the following two paragraphs appear in10* all copies of this software.11*12* IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR13* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES14* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN15* IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH16* DAMAGE.17*18* THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,19* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND20* FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS21* ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO22* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.23*24* Red Hat Author(s): Behdad Esfahbod25*/2627#include "hb.hh"28#include "hb-blob.hh"2930#ifdef HAVE_SYS_MMAN_H31#ifdef HAVE_UNISTD_H32#include <unistd.h>33#endif /* HAVE_UNISTD_H */34#include <sys/mman.h>35#endif /* HAVE_SYS_MMAN_H */363738/**39* SECTION: hb-blob40* @title: hb-blob41* @short_description: Binary data containers42* @include: hb.h43*44* Blobs wrap a chunk of binary data to handle lifecycle management of data45* while it is passed between client and HarfBuzz. Blobs are primarily used46* to create font faces, but also to access font face tables, as well as47* pass around other binary data.48**/495051/**52* hb_blob_create: (skip)53* @data: Pointer to blob data.54* @length: Length of @data in bytes.55* @mode: Memory mode for @data.56* @user_data: Data parameter to pass to @destroy.57* @destroy: (nullable): Callback to call when @data is not needed anymore.58*59* Creates a new "blob" object wrapping @data. The @mode parameter is used60* to negotiate ownership and lifecycle of @data.61*62* Return value: New blob, or the empty blob if something failed or if @length is63* zero. Destroy with hb_blob_destroy().64*65* Since: 0.9.266**/67hb_blob_t *68hb_blob_create (const char *data,69unsigned int length,70hb_memory_mode_t mode,71void *user_data,72hb_destroy_func_t destroy)73{74hb_blob_t *blob;7576if (!length ||77length >= 1u << 31 ||78!(blob = hb_object_create<hb_blob_t> ())) {79if (destroy)80destroy (user_data);81return hb_blob_get_empty ();82}8384blob->data = data;85blob->length = length;86blob->mode = mode;8788blob->user_data = user_data;89blob->destroy = destroy;9091if (blob->mode == HB_MEMORY_MODE_DUPLICATE) {92blob->mode = HB_MEMORY_MODE_READONLY;93if (!blob->try_make_writable ()) {94hb_blob_destroy (blob);95return hb_blob_get_empty ();96}97}9899return blob;100}101102static void103_hb_blob_destroy (void *data)104{105hb_blob_destroy ((hb_blob_t *) data);106}107108/**109* hb_blob_create_sub_blob:110* @parent: Parent blob.111* @offset: Start offset of sub-blob within @parent, in bytes.112* @length: Length of sub-blob.113*114* Returns a blob that represents a range of bytes in @parent. The new115* blob is always created with #HB_MEMORY_MODE_READONLY, meaning that it116* will never modify data in the parent blob. The parent data is not117* expected to be modified, and will result in undefined behavior if it118* is.119*120* Makes @parent immutable.121*122* Return value: New blob, or the empty blob if something failed or if123* @length is zero or @offset is beyond the end of @parent's data. Destroy124* with hb_blob_destroy().125*126* Since: 0.9.2127**/128hb_blob_t *129hb_blob_create_sub_blob (hb_blob_t *parent,130unsigned int offset,131unsigned int length)132{133hb_blob_t *blob;134135if (!length || !parent || offset >= parent->length)136return hb_blob_get_empty ();137138hb_blob_make_immutable (parent);139140blob = hb_blob_create (parent->data + offset,141hb_min (length, parent->length - offset),142HB_MEMORY_MODE_READONLY,143hb_blob_reference (parent),144_hb_blob_destroy);145146return blob;147}148149/**150* hb_blob_copy_writable_or_fail:151* @blob: A blob.152*153* Makes a writable copy of @blob.154*155* Return value: The new blob, or nullptr if allocation failed156*157* Since: 1.8.0158**/159hb_blob_t *160hb_blob_copy_writable_or_fail (hb_blob_t *blob)161{162blob = hb_blob_create (blob->data,163blob->length,164HB_MEMORY_MODE_DUPLICATE,165nullptr,166nullptr);167168if (unlikely (blob == hb_blob_get_empty ()))169blob = nullptr;170171return blob;172}173174/**175* hb_blob_get_empty:176*177* Returns the singleton empty blob.178*179* See TODO:link object types for more information.180*181* Return value: (transfer full): The empty blob.182*183* Since: 0.9.2184**/185hb_blob_t *186hb_blob_get_empty ()187{188return const_cast<hb_blob_t *> (&Null (hb_blob_t));189}190191/**192* hb_blob_reference: (skip)193* @blob: a blob.194*195* Increases the reference count on @blob.196*197* See TODO:link object types for more information.198*199* Return value: @blob.200*201* Since: 0.9.2202**/203hb_blob_t *204hb_blob_reference (hb_blob_t *blob)205{206return hb_object_reference (blob);207}208209/**210* hb_blob_destroy: (skip)211* @blob: a blob.212*213* Decreases the reference count on @blob, and if it reaches zero, destroys214* @blob, freeing all memory, possibly calling the destroy-callback the blob215* was created for if it has not been called already.216*217* See TODO:link object types for more information.218*219* Since: 0.9.2220**/221void222hb_blob_destroy (hb_blob_t *blob)223{224if (!hb_object_destroy (blob)) return;225226blob->fini_shallow ();227228free (blob);229}230231/**232* hb_blob_set_user_data: (skip)233* @blob: An #hb_blob_t234* @key: The user-data key to set235* @data: A pointer to the user data to set236* @destroy: (nullable): A callback to call when @data is not needed anymore237* @replace: Whether to replace an existing data with the same key238*239* Attaches a user-data key/data pair to the specified blob.240*241* Return value: %true if success, %false otherwise242*243* Since: 0.9.2244**/245hb_bool_t246hb_blob_set_user_data (hb_blob_t *blob,247hb_user_data_key_t *key,248void * data,249hb_destroy_func_t destroy,250hb_bool_t replace)251{252return hb_object_set_user_data (blob, key, data, destroy, replace);253}254255/**256* hb_blob_get_user_data: (skip)257* @blob: a blob258* @key: The user-data key to query259*260* Fetches the user data associated with the specified key,261* attached to the specified font-functions structure.262*263* Return value: (transfer none): A pointer to the user data264*265* Since: 0.9.2266**/267void *268hb_blob_get_user_data (hb_blob_t *blob,269hb_user_data_key_t *key)270{271return hb_object_get_user_data (blob, key);272}273274275/**276* hb_blob_make_immutable:277* @blob: a blob278*279* Makes a blob immutable.280*281* Since: 0.9.2282**/283void284hb_blob_make_immutable (hb_blob_t *blob)285{286if (hb_object_is_immutable (blob))287return;288289hb_object_make_immutable (blob);290}291292/**293* hb_blob_is_immutable:294* @blob: a blob.295*296* Tests whether a blob is immutable.297*298* Return value: %true if @blob is immutable, %false otherwise299*300* Since: 0.9.2301**/302hb_bool_t303hb_blob_is_immutable (hb_blob_t *blob)304{305return hb_object_is_immutable (blob);306}307308309/**310* hb_blob_get_length:311* @blob: a blob.312*313* Fetches the length of a blob's data.314*315* Return value: the length of @blob data in bytes.316*317* Since: 0.9.2318**/319unsigned int320hb_blob_get_length (hb_blob_t *blob)321{322return blob->length;323}324325/**326* hb_blob_get_data:327* @blob: a blob.328* @length: (out): The length in bytes of the data retrieved329*330* Fetches the data from a blob.331*332* Returns: (transfer none) (array length=length): the byte data of @blob.333*334* Since: 0.9.2335**/336const char *337hb_blob_get_data (hb_blob_t *blob, unsigned int *length)338{339if (length)340*length = blob->length;341342return blob->data;343}344345/**346* hb_blob_get_data_writable:347* @blob: a blob.348* @length: (out): output length of the writable data.349*350* Tries to make blob data writable (possibly copying it) and351* return pointer to data.352*353* Fails if blob has been made immutable, or if memory allocation354* fails.355*356* Returns: (transfer none) (array length=length): Writable blob data,357* or %NULL if failed.358*359* Since: 0.9.2360**/361char *362hb_blob_get_data_writable (hb_blob_t *blob, unsigned int *length)363{364if (hb_object_is_immutable (blob) ||365!blob->try_make_writable ())366{367if (length) *length = 0;368return nullptr;369}370371if (length) *length = blob->length;372return const_cast<char *> (blob->data);373}374375376bool377hb_blob_t::try_make_writable_inplace_unix ()378{379#if defined(HAVE_SYS_MMAN_H) && defined(HAVE_MPROTECT)380uintptr_t pagesize = -1, mask, length;381const char *addr;382383#if defined(HAVE_SYSCONF) && defined(_SC_PAGE_SIZE)384pagesize = (uintptr_t) sysconf (_SC_PAGE_SIZE);385#elif defined(HAVE_SYSCONF) && defined(_SC_PAGESIZE)386pagesize = (uintptr_t) sysconf (_SC_PAGESIZE);387#elif defined(HAVE_GETPAGESIZE)388pagesize = (uintptr_t) getpagesize ();389#endif390391if ((uintptr_t) -1L == pagesize) {392DEBUG_MSG_FUNC (BLOB, this, "failed to get pagesize: %s", strerror (errno));393return false;394}395DEBUG_MSG_FUNC (BLOB, this, "pagesize is %lu", (unsigned long) pagesize);396397mask = ~(pagesize-1);398addr = (const char *) (((uintptr_t) this->data) & mask);399length = (const char *) (((uintptr_t) this->data + this->length + pagesize-1) & mask) - addr;400DEBUG_MSG_FUNC (BLOB, this,401"calling mprotect on [%p..%p] (%lu bytes)",402addr, addr+length, (unsigned long) length);403if (-1 == mprotect ((void *) addr, length, PROT_READ | PROT_WRITE)) {404DEBUG_MSG_FUNC (BLOB, this, "mprotect failed: %s", strerror (errno));405return false;406}407408this->mode = HB_MEMORY_MODE_WRITABLE;409410DEBUG_MSG_FUNC (BLOB, this,411"successfully made [%p..%p] (%lu bytes) writable\n",412addr, addr+length, (unsigned long) length);413return true;414#else415return false;416#endif417}418419bool420hb_blob_t::try_make_writable_inplace ()421{422DEBUG_MSG_FUNC (BLOB, this, "making writable inplace\n");423424if (this->try_make_writable_inplace_unix ())425return true;426427DEBUG_MSG_FUNC (BLOB, this, "making writable -> FAILED\n");428429/* Failed to make writable inplace, mark that */430this->mode = HB_MEMORY_MODE_READONLY;431return false;432}433434bool435hb_blob_t::try_make_writable ()436{437if (unlikely (!length))438mode = HB_MEMORY_MODE_WRITABLE;439440if (this->mode == HB_MEMORY_MODE_WRITABLE)441return true;442443if (this->mode == HB_MEMORY_MODE_READONLY_MAY_MAKE_WRITABLE && this->try_make_writable_inplace ())444return true;445446if (this->mode == HB_MEMORY_MODE_WRITABLE)447return true;448449450DEBUG_MSG_FUNC (BLOB, this, "current data is -> %p\n", this->data);451452char *new_data;453454new_data = (char *) malloc (this->length);455if (unlikely (!new_data))456return false;457458DEBUG_MSG_FUNC (BLOB, this, "dupped successfully -> %p\n", this->data);459460memcpy (new_data, this->data, this->length);461this->destroy_user_data ();462this->mode = HB_MEMORY_MODE_WRITABLE;463this->data = new_data;464this->user_data = new_data;465this->destroy = free;466467return true;468}469470/*471* Mmap472*/473474#ifndef HB_NO_OPEN475#ifdef HAVE_MMAP476# if !defined(HB_NO_RESOURCE_FORK) && defined(__APPLE__)477# include <sys/paths.h>478# endif479# include <sys/types.h>480# include <sys/stat.h>481# include <fcntl.h>482#endif483484#ifdef _WIN32485# include <windows.h>486#else487# ifndef O_BINARY488# define O_BINARY 0489# endif490#endif491492#ifndef MAP_NORESERVE493# define MAP_NORESERVE 0494#endif495496struct hb_mapped_file_t497{498char *contents;499unsigned long length;500#ifdef _WIN32501HANDLE mapping;502#endif503};504505#if (defined(HAVE_MMAP) || defined(_WIN32)) && !defined(HB_NO_MMAP)506static void507_hb_mapped_file_destroy (void *file_)508{509hb_mapped_file_t *file = (hb_mapped_file_t *) file_;510#ifdef HAVE_MMAP511munmap (file->contents, file->length);512#elif defined(_WIN32)513UnmapViewOfFile (file->contents);514CloseHandle (file->mapping);515#else516assert (0); // If we don't have mmap we shouldn't reach here517#endif518519free (file);520}521#endif522523#ifdef _PATH_RSRCFORKSPEC524static int525_open_resource_fork (const char *file_name, hb_mapped_file_t *file)526{527size_t name_len = strlen (file_name);528size_t len = name_len + sizeof (_PATH_RSRCFORKSPEC);529530char *rsrc_name = (char *) malloc (len);531if (unlikely (!rsrc_name)) return -1;532533strncpy (rsrc_name, file_name, name_len);534strncpy (rsrc_name + name_len, _PATH_RSRCFORKSPEC,535sizeof (_PATH_RSRCFORKSPEC) - 1);536537int fd = open (rsrc_name, O_RDONLY | O_BINARY, 0);538free (rsrc_name);539540if (fd != -1)541{542struct stat st;543if (fstat (fd, &st) != -1)544file->length = (unsigned long) st.st_size;545else546{547close (fd);548fd = -1;549}550}551552return fd;553}554#endif555556/**557* hb_blob_create_from_file:558* @file_name: A font filename559*560* Creates a new blob containing the data from the561* specified binary font file.562*563* Returns: An #hb_blob_t pointer with the content of the file564*565* Since: 1.7.7566**/567hb_blob_t *568hb_blob_create_from_file (const char *file_name)569{570/* Adopted from glib's gmappedfile.c with Matthias Clasen and571Allison Lortie permission but changed a lot to suit our need. */572#if defined(HAVE_MMAP) && !defined(HB_NO_MMAP)573hb_mapped_file_t *file = (hb_mapped_file_t *) calloc (1, sizeof (hb_mapped_file_t));574if (unlikely (!file)) return hb_blob_get_empty ();575576int fd = open (file_name, O_RDONLY | O_BINARY, 0);577if (unlikely (fd == -1)) goto fail_without_close;578579struct stat st;580if (unlikely (fstat (fd, &st) == -1)) goto fail;581582file->length = (unsigned long) st.st_size;583584#ifdef _PATH_RSRCFORKSPEC585if (unlikely (file->length == 0))586{587int rfd = _open_resource_fork (file_name, file);588if (rfd != -1)589{590close (fd);591fd = rfd;592}593}594#endif595596file->contents = (char *) mmap (nullptr, file->length, PROT_READ,597MAP_PRIVATE | MAP_NORESERVE, fd, 0);598599if (unlikely (file->contents == MAP_FAILED)) goto fail;600601close (fd);602603return hb_blob_create (file->contents, file->length,604HB_MEMORY_MODE_READONLY_MAY_MAKE_WRITABLE, (void *) file,605(hb_destroy_func_t) _hb_mapped_file_destroy);606607fail:608close (fd);609fail_without_close:610free (file);611612#elif defined(_WIN32) && !defined(HB_NO_MMAP)613hb_mapped_file_t *file = (hb_mapped_file_t *) calloc (1, sizeof (hb_mapped_file_t));614if (unlikely (!file)) return hb_blob_get_empty ();615616HANDLE fd;617unsigned int size = strlen (file_name) + 1;618wchar_t * wchar_file_name = (wchar_t *) malloc (sizeof (wchar_t) * size);619if (unlikely (!wchar_file_name)) goto fail_without_close;620mbstowcs (wchar_file_name, file_name, size);621#if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)622{623CREATEFILE2_EXTENDED_PARAMETERS ceparams = { 0 };624ceparams.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);625ceparams.dwFileAttributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED & 0xFFFF;626ceparams.dwFileFlags = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED & 0xFFF00000;627ceparams.dwSecurityQosFlags = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED & 0x000F0000;628ceparams.lpSecurityAttributes = nullptr;629ceparams.hTemplateFile = nullptr;630fd = CreateFile2 (wchar_file_name, GENERIC_READ, FILE_SHARE_READ,631OPEN_EXISTING, &ceparams);632}633#else634fd = CreateFileW (wchar_file_name, GENERIC_READ, FILE_SHARE_READ, nullptr,635OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED,636nullptr);637#endif638free (wchar_file_name);639640if (unlikely (fd == INVALID_HANDLE_VALUE)) goto fail_without_close;641642#if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)643{644LARGE_INTEGER length;645GetFileSizeEx (fd, &length);646file->length = length.LowPart;647file->mapping = CreateFileMappingFromApp (fd, nullptr, PAGE_READONLY, length.QuadPart, nullptr);648}649#else650file->length = (unsigned long) GetFileSize (fd, nullptr);651file->mapping = CreateFileMapping (fd, nullptr, PAGE_READONLY, 0, 0, nullptr);652#endif653if (unlikely (!file->mapping)) goto fail;654655#if !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)656file->contents = (char *) MapViewOfFileFromApp (file->mapping, FILE_MAP_READ, 0, 0);657#else658file->contents = (char *) MapViewOfFile (file->mapping, FILE_MAP_READ, 0, 0, 0);659#endif660if (unlikely (!file->contents)) goto fail;661662CloseHandle (fd);663return hb_blob_create (file->contents, file->length,664HB_MEMORY_MODE_READONLY_MAY_MAKE_WRITABLE, (void *) file,665(hb_destroy_func_t) _hb_mapped_file_destroy);666667fail:668CloseHandle (fd);669fail_without_close:670free (file);671672#endif673674/* The following tries to read a file without knowing its size beforehand675It's used as a fallback for systems without mmap or to read from pipes */676unsigned long len = 0, allocated = BUFSIZ * 16;677char *data = (char *) malloc (allocated);678if (unlikely (!data)) return hb_blob_get_empty ();679680FILE *fp = fopen (file_name, "rb");681if (unlikely (!fp)) goto fread_fail_without_close;682683while (!feof (fp))684{685if (allocated - len < BUFSIZ)686{687allocated *= 2;688/* Don't allocate and go more than ~536MB, our mmap reader still689can cover files like that but lets limit our fallback reader */690if (unlikely (allocated > (2 << 28))) goto fread_fail;691char *new_data = (char *) realloc (data, allocated);692if (unlikely (!new_data)) goto fread_fail;693data = new_data;694}695696unsigned long addition = fread (data + len, 1, allocated - len, fp);697698int err = ferror (fp);699#ifdef EINTR // armcc doesn't have it700if (unlikely (err == EINTR)) continue;701#endif702if (unlikely (err)) goto fread_fail;703704len += addition;705}706fclose (fp);707708return hb_blob_create (data, len, HB_MEMORY_MODE_WRITABLE, data,709(hb_destroy_func_t) free);710711fread_fail:712fclose (fp);713fread_fail_without_close:714free (data);715return hb_blob_get_empty ();716}717#endif /* !HB_NO_OPEN */718719720