1/*
2 * Copyright © 2009 Red Hat, Inc.
3 * Copyright © 2018 Ebrahim Byagowi
4 *
5 * This is part of HarfBuzz, a text shaping library.
6 *
7 * Permission is hereby granted, without written agreement and without
8 * license or royalty fees, to use, copy, modify, and distribute this
9 * software and its documentation for any purpose, provided that the
10 * above copyright notice and the following two paragraphs appear in
11 * all copies of this software.
12 *
13 * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
14 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
15 * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
16 * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
17 * DAMAGE.
18 *
19 * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
20 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
21 * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
22 * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
23 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
24 *
25 * Red Hat Author(s): Behdad Esfahbod
26 */
27
28/* http://www.oracle.com/technetwork/articles/servers-storage-dev/standardheaderfiles-453865.html */
29#ifndef _POSIX_C_SOURCE
30#define _POSIX_C_SOURCE 200809L
31#endif
32
33#include "hb.hh"
34#include "hb-blob.hh"
35
36#ifdef HAVE_SYS_MMAN_H
37#ifdef HAVE_UNISTD_H
38#include <unistd.h>
39#endif /* HAVE_UNISTD_H */
40#include <sys/mman.h>
41#endif /* HAVE_SYS_MMAN_H */
42
43#include <stdio.h>
44#include <errno.h>
45#include <stdlib.h>
46
47
48DEFINE_NULL_INSTANCE (hb_blob_t) =
49{
50 HB_OBJECT_HEADER_STATIC,
51
52 true, /* immutable */
53
54 nullptr, /* data */
55 0, /* length */
56 HB_MEMORY_MODE_READONLY, /* mode */
57
58 nullptr, /* user_data */
59 nullptr /* destroy */
60};
61
62/**
63 * hb_blob_create: (skip)
64 * @data: Pointer to blob data.
65 * @length: Length of @data in bytes.
66 * @mode: Memory mode for @data.
67 * @user_data: Data parameter to pass to @destroy.
68 * @destroy: Callback to call when @data is not needed anymore.
69 *
70 * Creates a new "blob" object wrapping @data. The @mode parameter is used
71 * to negotiate ownership and lifecycle of @data.
72 *
73 * Return value: New blob, or the empty blob if something failed or if @length is
74 * zero. Destroy with hb_blob_destroy().
75 *
76 * Since: 0.9.2
77 **/
78hb_blob_t *
79hb_blob_create (const char *data,
80 unsigned int length,
81 hb_memory_mode_t mode,
82 void *user_data,
83 hb_destroy_func_t destroy)
84{
85 hb_blob_t *blob;
86
87 if (!length ||
88 length >= 1u << 31 ||
89 !(blob = hb_object_create<hb_blob_t> ())) {
90 if (destroy)
91 destroy (user_data);
92 return hb_blob_get_empty ();
93 }
94
95 blob->data = data;
96 blob->length = length;
97 blob->mode = mode;
98
99 blob->user_data = user_data;
100 blob->destroy = destroy;
101
102 if (blob->mode == HB_MEMORY_MODE_DUPLICATE) {
103 blob->mode = HB_MEMORY_MODE_READONLY;
104 if (!blob->try_make_writable ()) {
105 hb_blob_destroy (blob);
106 return hb_blob_get_empty ();
107 }
108 }
109
110 return blob;
111}
112
113static void
114_hb_blob_destroy (void *data)
115{
116 hb_blob_destroy ((hb_blob_t *) data);
117}
118
119/**
120 * hb_blob_create_sub_blob:
121 * @parent: Parent blob.
122 * @offset: Start offset of sub-blob within @parent, in bytes.
123 * @length: Length of sub-blob.
124 *
125 * Returns a blob that represents a range of bytes in @parent. The new
126 * blob is always created with %HB_MEMORY_MODE_READONLY, meaning that it
127 * will never modify data in the parent blob. The parent data is not
128 * expected to be modified, and will result in undefined behavior if it
129 * is.
130 *
131 * Makes @parent immutable.
132 *
133 * Return value: New blob, or the empty blob if something failed or if
134 * @length is zero or @offset is beyond the end of @parent's data. Destroy
135 * with hb_blob_destroy().
136 *
137 * Since: 0.9.2
138 **/
139hb_blob_t *
140hb_blob_create_sub_blob (hb_blob_t *parent,
141 unsigned int offset,
142 unsigned int length)
143{
144 hb_blob_t *blob;
145
146 if (!length || offset >= parent->length)
147 return hb_blob_get_empty ();
148
149 hb_blob_make_immutable (parent);
150
151 blob = hb_blob_create (parent->data + offset,
152 MIN (length, parent->length - offset),
153 HB_MEMORY_MODE_READONLY,
154 hb_blob_reference (parent),
155 _hb_blob_destroy);
156
157 return blob;
158}
159
160/**
161 * hb_blob_copy_writable_or_fail:
162 * @blob: A blob.
163 *
164 * Makes a writable copy of @blob.
165 *
166 * Return value: New blob, or nullptr if allocation failed.
167 *
168 * Since: 1.8.0
169 **/
170hb_blob_t *
171hb_blob_copy_writable_or_fail (hb_blob_t *blob)
172{
173 blob = hb_blob_create (blob->data,
174 blob->length,
175 HB_MEMORY_MODE_DUPLICATE,
176 nullptr,
177 nullptr);
178
179 if (unlikely (blob == hb_blob_get_empty ()))
180 blob = nullptr;
181
182 return blob;
183}
184
185/**
186 * hb_blob_get_empty:
187 *
188 * Returns the singleton empty blob.
189 *
190 * See TODO:link object types for more information.
191 *
192 * Return value: (transfer full): the empty blob.
193 *
194 * Since: 0.9.2
195 **/
196hb_blob_t *
197hb_blob_get_empty (void)
198{
199 return const_cast<hb_blob_t *> (&Null(hb_blob_t));
200}
201
202/**
203 * hb_blob_reference: (skip)
204 * @blob: a blob.
205 *
206 * Increases the reference count on @blob.
207 *
208 * See TODO:link object types for more information.
209 *
210 * Return value: @blob.
211 *
212 * Since: 0.9.2
213 **/
214hb_blob_t *
215hb_blob_reference (hb_blob_t *blob)
216{
217 return hb_object_reference (blob);
218}
219
220/**
221 * hb_blob_destroy: (skip)
222 * @blob: a blob.
223 *
224 * Decreases the reference count on @blob, and if it reaches zero, destroys
225 * @blob, freeing all memory, possibly calling the destroy-callback the blob
226 * was created for if it has not been called already.
227 *
228 * See TODO:link object types for more information.
229 *
230 * Since: 0.9.2
231 **/
232void
233hb_blob_destroy (hb_blob_t *blob)
234{
235 if (!hb_object_destroy (blob)) return;
236
237 blob->fini_shallow ();
238
239 free (blob);
240}
241
242/**
243 * hb_blob_set_user_data: (skip)
244 * @blob: a blob.
245 * @key: key for data to set.
246 * @data: data to set.
247 * @destroy: callback to call when @data is not needed anymore.
248 * @replace: whether to replace an existing data with the same key.
249 *
250 * Return value:
251 *
252 * Since: 0.9.2
253 **/
254hb_bool_t
255hb_blob_set_user_data (hb_blob_t *blob,
256 hb_user_data_key_t *key,
257 void * data,
258 hb_destroy_func_t destroy,
259 hb_bool_t replace)
260{
261 return hb_object_set_user_data (blob, key, data, destroy, replace);
262}
263
264/**
265 * hb_blob_get_user_data: (skip)
266 * @blob: a blob.
267 * @key: key for data to get.
268 *
269 *
270 *
271 * Return value: (transfer none):
272 *
273 * Since: 0.9.2
274 **/
275void *
276hb_blob_get_user_data (hb_blob_t *blob,
277 hb_user_data_key_t *key)
278{
279 return hb_object_get_user_data (blob, key);
280}
281
282
283/**
284 * hb_blob_make_immutable:
285 * @blob: a blob.
286 *
287 *
288 *
289 * Since: 0.9.2
290 **/
291void
292hb_blob_make_immutable (hb_blob_t *blob)
293{
294 if (hb_object_is_inert (blob))
295 return;
296
297 blob->immutable = true;
298}
299
300/**
301 * hb_blob_is_immutable:
302 * @blob: a blob.
303 *
304 *
305 *
306 * Return value: TODO
307 *
308 * Since: 0.9.2
309 **/
310hb_bool_t
311hb_blob_is_immutable (hb_blob_t *blob)
312{
313 return blob->immutable;
314}
315
316
317/**
318 * hb_blob_get_length:
319 * @blob: a blob.
320 *
321 *
322 *
323 * Return value: the length of blob data in bytes.
324 *
325 * Since: 0.9.2
326 **/
327unsigned int
328hb_blob_get_length (hb_blob_t *blob)
329{
330 return blob->length;
331}
332
333/**
334 * hb_blob_get_data:
335 * @blob: a blob.
336 * @length: (out):
337 *
338 *
339 *
340 * Returns: (transfer none) (array length=length):
341 *
342 * Since: 0.9.2
343 **/
344const char *
345hb_blob_get_data (hb_blob_t *blob, unsigned int *length)
346{
347 if (length)
348 *length = blob->length;
349
350 return blob->data;
351}
352
353/**
354 * hb_blob_get_data_writable:
355 * @blob: a blob.
356 * @length: (out): output length of the writable data.
357 *
358 * Tries to make blob data writable (possibly copying it) and
359 * return pointer to data.
360 *
361 * Fails if blob has been made immutable, or if memory allocation
362 * fails.
363 *
364 * Returns: (transfer none) (array length=length): Writable blob data,
365 * or %NULL if failed.
366 *
367 * Since: 0.9.2
368 **/
369char *
370hb_blob_get_data_writable (hb_blob_t *blob, unsigned int *length)
371{
372 if (!blob->try_make_writable ()) {
373 if (length)
374 *length = 0;
375
376 return nullptr;
377 }
378
379 if (length)
380 *length = blob->length;
381
382 return const_cast<char *> (blob->data);
383}
384
385
386bool
387hb_blob_t::try_make_writable_inplace_unix (void)
388{
389#if defined(HAVE_SYS_MMAN_H) && defined(HAVE_MPROTECT)
390 uintptr_t pagesize = -1, mask, length;
391 const char *addr;
392
393#if defined(HAVE_SYSCONF) && defined(_SC_PAGE_SIZE)
394 pagesize = (uintptr_t) sysconf (_SC_PAGE_SIZE);
395#elif defined(HAVE_SYSCONF) && defined(_SC_PAGESIZE)
396 pagesize = (uintptr_t) sysconf (_SC_PAGESIZE);
397#elif defined(HAVE_GETPAGESIZE)
398 pagesize = (uintptr_t) getpagesize ();
399#endif
400
401 if ((uintptr_t) -1L == pagesize) {
402 DEBUG_MSG_FUNC (BLOB, this, "failed to get pagesize: %s", strerror (errno));
403 return false;
404 }
405 DEBUG_MSG_FUNC (BLOB, this, "pagesize is %lu", (unsigned long) pagesize);
406
407 mask = ~(pagesize-1);
408 addr = (const char *) (((uintptr_t) this->data) & mask);
409 length = (const char *) (((uintptr_t) this->data + this->length + pagesize-1) & mask) - addr;
410 DEBUG_MSG_FUNC (BLOB, this,
411 "calling mprotect on [%p..%p] (%lu bytes)",
412 addr, addr+length, (unsigned long) length);
413 if (-1 == mprotect ((void *) addr, length, PROT_READ | PROT_WRITE)) {
414 DEBUG_MSG_FUNC (BLOB, this, "mprotect failed: %s", strerror (errno));
415 return false;
416 }
417
418 this->mode = HB_MEMORY_MODE_WRITABLE;
419
420 DEBUG_MSG_FUNC (BLOB, this,
421 "successfully made [%p..%p] (%lu bytes) writable\n",
422 addr, addr+length, (unsigned long) length);
423 return true;
424#else
425 return false;
426#endif
427}
428
429bool
430hb_blob_t::try_make_writable_inplace (void)
431{
432 DEBUG_MSG_FUNC (BLOB, this, "making writable inplace\n");
433
434 if (this->try_make_writable_inplace_unix ())
435 return true;
436
437 DEBUG_MSG_FUNC (BLOB, this, "making writable -> FAILED\n");
438
439 /* Failed to make writable inplace, mark that */
440 this->mode = HB_MEMORY_MODE_READONLY;
441 return false;
442}
443
444bool
445hb_blob_t::try_make_writable (void)
446{
447 if (this->immutable)
448 return false;
449
450 if (this->mode == HB_MEMORY_MODE_WRITABLE)
451 return true;
452
453 if (this->mode == HB_MEMORY_MODE_READONLY_MAY_MAKE_WRITABLE && this->try_make_writable_inplace ())
454 return true;
455
456 if (this->mode == HB_MEMORY_MODE_WRITABLE)
457 return true;
458
459
460 DEBUG_MSG_FUNC (BLOB, this, "current data is -> %p\n", this->data);
461
462 char *new_data;
463
464 new_data = (char *) malloc (this->length);
465 if (unlikely (!new_data))
466 return false;
467
468 DEBUG_MSG_FUNC (BLOB, this, "dupped successfully -> %p\n", this->data);
469
470 memcpy (new_data, this->data, this->length);
471 this->destroy_user_data ();
472 this->mode = HB_MEMORY_MODE_WRITABLE;
473 this->data = new_data;
474 this->user_data = new_data;
475 this->destroy = free;
476
477 return true;
478}
479
480/*
481 * Mmap
482 */
483
484#ifdef HAVE_MMAP
485# include <sys/types.h>
486# include <sys/stat.h>
487# include <fcntl.h>
488#endif
489
490#if defined(_WIN32) || defined(__CYGWIN__)
491# include <windows.h>
492#else
493# ifndef _O_BINARY
494# define _O_BINARY 0
495# endif
496#endif
497
498#ifndef MAP_NORESERVE
499# define MAP_NORESERVE 0
500#endif
501
502struct hb_mapped_file_t
503{
504 char *contents;
505 unsigned long length;
506#if defined(_WIN32) || defined(__CYGWIN__)
507 HANDLE mapping;
508#endif
509};
510
511#if (defined(HAVE_MMAP) || defined(_WIN32) || defined(__CYGWIN__)) && !defined(HB_NO_MMAP)
512static void
513_hb_mapped_file_destroy (hb_mapped_file_t *file)
514{
515#ifdef HAVE_MMAP
516 munmap (file->contents, file->length);
517#elif defined(_WIN32) || defined(__CYGWIN__)
518 UnmapViewOfFile (file->contents);
519 CloseHandle (file->mapping);
520#else
521 assert (0); // If we don't have mmap we shouldn't reach here
522#endif
523
524 free (file);
525}
526#endif
527
528/**
529 * hb_blob_create_from_file:
530 * @file_name: font filename.
531 *
532 * Returns: A hb_blob_t pointer with the content of the file
533 *
534 * Since: 1.7.7
535 **/
536hb_blob_t *
537hb_blob_create_from_file (const char *file_name)
538{
539 /* Adopted from glib's gmappedfile.c with Matthias Clasen and
540 Allison Lortie permission but changed a lot to suit our need. */
541#if defined(HAVE_MMAP) && !defined(HB_NO_MMAP)
542 hb_mapped_file_t *file = (hb_mapped_file_t *) calloc (1, sizeof (hb_mapped_file_t));
543 if (unlikely (!file)) return hb_blob_get_empty ();
544
545 int fd = open (file_name, O_RDONLY | _O_BINARY, 0);
546 if (unlikely (fd == -1)) goto fail_without_close;
547
548 struct stat st;
549 if (unlikely (fstat (fd, &st) == -1)) goto fail;
550
551 file->length = (unsigned long) st.st_size;
552 file->contents = (char *) mmap (nullptr, file->length, PROT_READ,
553 MAP_PRIVATE | MAP_NORESERVE, fd, 0);
554
555 if (unlikely (file->contents == MAP_FAILED)) goto fail;
556
557 close (fd);
558
559 return hb_blob_create (file->contents, file->length,
560 HB_MEMORY_MODE_READONLY_MAY_MAKE_WRITABLE, (void *) file,
561 (hb_destroy_func_t) _hb_mapped_file_destroy);
562
563fail:
564 close (fd);
565fail_without_close:
566 free (file);
567
568#elif (defined(_WIN32) || defined(__CYGWIN__)) && !defined(HB_NO_MMAP)
569 hb_mapped_file_t *file = (hb_mapped_file_t *) calloc (1, sizeof (hb_mapped_file_t));
570 if (unlikely (!file)) return hb_blob_get_empty ();
571
572 HANDLE fd;
573 unsigned int size = strlen (file_name) + 1;
574 wchar_t * wchar_file_name = (wchar_t *) malloc (sizeof (wchar_t) * size);
575 if (unlikely (wchar_file_name == nullptr)) goto fail_without_close;
576 mbstowcs (wchar_file_name, file_name, size);
577 fd = CreateFileW (wchar_file_name, GENERIC_READ, FILE_SHARE_READ, nullptr,
578 OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED,
579 nullptr);
580 free (wchar_file_name);
581
582 if (unlikely (fd == INVALID_HANDLE_VALUE)) goto fail_without_close;
583
584 file->length = (unsigned long) GetFileSize (fd, nullptr);
585 file->mapping = CreateFileMapping (fd, nullptr, PAGE_READONLY, 0, 0, nullptr);
586 if (unlikely (file->mapping == nullptr)) goto fail;
587
588 file->contents = (char *) MapViewOfFile (file->mapping, FILE_MAP_READ, 0, 0, 0);
589 if (unlikely (file->contents == nullptr)) goto fail;
590
591 CloseHandle (fd);
592 return hb_blob_create (file->contents, file->length,
593 HB_MEMORY_MODE_READONLY_MAY_MAKE_WRITABLE, (void *) file,
594 (hb_destroy_func_t) _hb_mapped_file_destroy);
595
596fail:
597 CloseHandle (fd);
598fail_without_close:
599 free (file);
600
601#endif
602
603 /* The following tries to read a file without knowing its size beforehand
604 It's used as a fallback for systems without mmap or to read from pipes */
605 unsigned long len = 0, allocated = BUFSIZ * 16;
606 char *data = (char *) malloc (allocated);
607 if (unlikely (data == nullptr)) return hb_blob_get_empty ();
608
609 FILE *fp = fopen (file_name, "rb");
610 if (unlikely (fp == nullptr)) goto fread_fail_without_close;
611
612 while (!feof (fp))
613 {
614 if (allocated - len < BUFSIZ)
615 {
616 allocated *= 2;
617 /* Don't allocate and go more than ~536MB, our mmap reader still
618 can cover files like that but lets limit our fallback reader */
619 if (unlikely (allocated > (2 << 28))) goto fread_fail;
620 char *new_data = (char *) realloc (data, allocated);
621 if (unlikely (new_data == nullptr)) goto fread_fail;
622 data = new_data;
623 }
624
625 unsigned long addition = fread (data + len, 1, allocated - len, fp);
626
627 int err = ferror (fp);
628#ifdef EINTR // armcc doesn't have it
629 if (unlikely (err == EINTR)) continue;
630#endif
631 if (unlikely (err)) goto fread_fail;
632
633 len += addition;
634 }
635
636 return hb_blob_create (data, len, HB_MEMORY_MODE_WRITABLE, data,
637 (hb_destroy_func_t) free);
638
639fread_fail:
640 fclose (fp);
641fread_fail_without_close:
642 free (data);
643 return hb_blob_get_empty ();
644}
645