blob: aac2fbee7649b9b6fbbee83c98845a6f0485bed8 [file] [log] [blame]
Garret Rieger20b02a62022-06-24 18:58:17 +00001/*
2 * Copyright © 2022 Google, Inc.
3 *
4 * This is part of HarfBuzz, a text shaping library.
5 *
6 * Permission is hereby granted, without written agreement and without
7 * license or royalty fees, to use, copy, modify, and distribute this
8 * software and its documentation for any purpose, provided that the
9 * above copyright notice and the following two paragraphs appear in
10 * all copies of this software.
11 *
12 * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
13 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
14 * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
15 * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
16 * DAMAGE.
17 *
18 * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
19 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
20 * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
21 * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
22 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
23 *
24 * Google Author(s): Garret Rieger
25 */
26
Garret Rieger241ebc92022-07-26 00:04:20 +000027#include "../hb-set.hh"
28#include "../hb-priority-queue.hh"
29#include "../hb-serialize.hh"
Garret Riegerce03c352022-07-21 19:07:55 +000030
Garret Rieger20b02a62022-06-24 18:58:17 +000031#ifndef GRAPH_GRAPH_HH
32#define GRAPH_GRAPH_HH
33
34namespace graph {
35
Garret Rieger26749622022-06-24 21:00:54 +000036/**
37 * Represents a serialized table in the form of a graph.
38 * Provides methods for modifying and reordering the graph.
39 */
Garret Rieger20b02a62022-06-24 18:58:17 +000040struct graph_t
41{
42 struct vertex_t
43 {
44 hb_serialize_context_t::object_t obj;
45 int64_t distance = 0 ;
46 int64_t space = 0 ;
47 hb_vector_t<unsigned> parents;
48 unsigned start = 0;
49 unsigned end = 0;
50 unsigned priority = 0;
51
Garret Riegeredf7a292022-09-08 22:59:34 +000052
Garret Rieger30e405e2022-12-01 22:12:59 +000053 bool link_positions_valid (unsigned num_objects)
Garret Riegeredf7a292022-09-08 22:59:34 +000054 {
55 hb_set_t assigned_bytes;
56 for (const auto& l : obj.real_links)
57 {
Garret Rieger30e405e2022-12-01 22:12:59 +000058 if (l.objidx >= num_objects)
59 {
60 DEBUG_MSG (SUBSET_REPACK, nullptr,
61 "Invalid graph. Invalid object index.");
62 return false;
63 }
64
Garret Riegeredf7a292022-09-08 22:59:34 +000065 unsigned start = l.position;
66 unsigned end = start + l.width - 1;
67
Garret Rieger9e99d082022-09-08 23:19:02 +000068 if (unlikely (l.width < 2 || l.width > 4))
69 {
70 DEBUG_MSG (SUBSET_REPACK, nullptr,
71 "Invalid graph. Invalid link width.");
72 return false;
73 }
74
Garret Riegeredf7a292022-09-08 22:59:34 +000075 if (unlikely (end >= table_size ()))
76 {
77 DEBUG_MSG (SUBSET_REPACK, nullptr,
78 "Invalid graph. Link position is out of bounds.");
79 return false;
80 }
81
82 if (unlikely (assigned_bytes.intersects (start, end)))
83 {
84 DEBUG_MSG (SUBSET_REPACK, nullptr,
85 "Invalid graph. Found offsets whose positions overlap.");
86 return false;
87 }
88
89 assigned_bytes.add_range (start, end);
90 }
91 return true;
92 }
93
Garret Rieger1405f962022-08-15 23:48:00 +000094 void normalize ()
Garret Rieger07fd0522022-08-15 23:16:51 +000095 {
Garret Rieger1405f962022-08-15 23:48:00 +000096 obj.real_links.qsort ();
97 for (auto& l : obj.real_links)
98 {
99 for (unsigned i = 0; i < l.width; i++)
100 {
101 obj.head[l.position + i] = 0;
102 }
103 }
104 }
105
Garret Riegera3ed9f92022-08-17 23:39:11 +0000106 bool equals (const vertex_t& other,
107 const graph_t& graph,
108 const graph_t& other_graph,
109 unsigned depth) const
Garret Rieger1405f962022-08-15 23:48:00 +0000110 {
111 if (!(as_bytes () == other.as_bytes ()))
Garret Riegera3ed9f92022-08-17 23:39:11 +0000112 {
113 DEBUG_MSG (SUBSET_REPACK, nullptr,
114 "vertex [%lu] bytes != [%lu] bytes, depth = %u",
Behdad Esfahbod56c46702022-09-20 17:39:54 -0600115 (unsigned long) table_size (),
116 (unsigned long) other.table_size (),
Garret Riegera3ed9f92022-08-17 23:39:11 +0000117 depth);
Garret Rieger07fd0522022-08-15 23:16:51 +0000118
Garret Riegera3ed9f92022-08-17 23:39:11 +0000119 auto a = as_bytes ();
120 auto b = other.as_bytes ();
121 while (a || b)
122 {
123 DEBUG_MSG (SUBSET_REPACK, nullptr,
124 " 0x%x %s 0x%x", *a, (*a == *b) ? "==" : "!=", *b);
125 a++;
126 b++;
127 }
128 return false;
129 }
130
131 return links_equal (obj.real_links, other.obj.real_links, graph, other_graph, depth);
Garret Rieger07fd0522022-08-15 23:16:51 +0000132 }
133
Garret Rieger1405f962022-08-15 23:48:00 +0000134 hb_bytes_t as_bytes () const
Garret Rieger07fd0522022-08-15 23:16:51 +0000135 {
136 return hb_bytes_t (obj.head, table_size ());
137 }
138
Garret Rieger20b02a62022-06-24 18:58:17 +0000139 friend void swap (vertex_t& a, vertex_t& b)
140 {
141 hb_swap (a.obj, b.obj);
142 hb_swap (a.distance, b.distance);
143 hb_swap (a.space, b.space);
144 hb_swap (a.parents, b.parents);
145 hb_swap (a.start, b.start);
146 hb_swap (a.end, b.end);
147 hb_swap (a.priority, b.priority);
148 }
149
Garret Rieger1acd2a82022-08-11 20:22:31 +0000150 hb_hashmap_t<unsigned, unsigned>
151 position_to_index_map () const
152 {
153 hb_hashmap_t<unsigned, unsigned> result;
154
155 for (const auto& l : obj.real_links) {
156 result.set (l.position, l.objidx);
157 }
158
159 return result;
160 }
161
Garret Rieger20b02a62022-06-24 18:58:17 +0000162 bool is_shared () const
163 {
164 return parents.length > 1;
165 }
166
167 unsigned incoming_edges () const
168 {
169 return parents.length;
170 }
171
172 void remove_parent (unsigned parent_index)
173 {
174 for (unsigned i = 0; i < parents.length; i++)
175 {
176 if (parents[i] != parent_index) continue;
Behdad Esfahbod915c1a02022-11-26 14:48:57 -0700177 parents.remove_unordered (i);
Garret Rieger20b02a62022-06-24 18:58:17 +0000178 break;
179 }
180 }
181
Garret Rieger1002a3d2022-07-28 20:17:36 +0000182 void remove_real_link (unsigned child_index, const void* offset)
Garret Rieger8d63f602022-07-27 20:36:20 +0000183 {
184 for (unsigned i = 0; i < obj.real_links.length; i++)
185 {
Garret Rieger29e3b242022-08-18 01:19:54 +0000186 auto& link = obj.real_links.arrayZ[i];
Garret Rieger1002a3d2022-07-28 20:17:36 +0000187 if (link.objidx != child_index)
188 continue;
189
190 if ((obj.head + link.position) != offset)
191 continue;
192
Behdad Esfahbod915c1a02022-11-26 14:48:57 -0700193 obj.real_links.remove_unordered (i);
Garret Rieger1002a3d2022-07-28 20:17:36 +0000194 return;
Garret Rieger8d63f602022-07-27 20:36:20 +0000195 }
196 }
197
Garret Rieger20b02a62022-06-24 18:58:17 +0000198 void remap_parents (const hb_vector_t<unsigned>& id_map)
199 {
200 for (unsigned i = 0; i < parents.length; i++)
201 parents[i] = id_map[parents[i]];
202 }
203
204 void remap_parent (unsigned old_index, unsigned new_index)
205 {
206 for (unsigned i = 0; i < parents.length; i++)
207 {
208 if (parents[i] == old_index)
209 parents[i] = new_index;
210 }
211 }
212
213 bool is_leaf () const
214 {
215 return !obj.real_links.length && !obj.virtual_links.length;
216 }
217
218 bool raise_priority ()
219 {
220 if (has_max_priority ()) return false;
221 priority++;
222 return true;
223 }
224
225 bool has_max_priority () const {
226 return priority >= 3;
227 }
228
Garret Rieger9db3beb2022-07-25 19:42:58 +0000229 size_t table_size () const {
230 return obj.tail - obj.head;
231 }
232
Garret Rieger20b02a62022-06-24 18:58:17 +0000233 int64_t modified_distance (unsigned order) const
234 {
235 // TODO(garretrieger): once priority is high enough, should try
236 // setting distance = 0 which will force to sort immediately after
237 // it's parent where possible.
238
239 int64_t modified_distance =
240 hb_min (hb_max(distance + distance_modifier (), 0), 0x7FFFFFFFFFF);
241 if (has_max_priority ()) {
242 modified_distance = 0;
243 }
244 return (modified_distance << 18) | (0x003FFFF & order);
245 }
246
247 int64_t distance_modifier () const
248 {
249 if (!priority) return 0;
250 int64_t table_size = obj.tail - obj.head;
251
252 if (priority == 1)
253 return -table_size / 2;
254
255 return -table_size;
256 }
Garret Rieger07fd0522022-08-15 23:16:51 +0000257
258 private:
Garret Riegera3ed9f92022-08-17 23:39:11 +0000259 bool links_equal (const hb_vector_t<hb_serialize_context_t::object_t::link_t>& this_links,
260 const hb_vector_t<hb_serialize_context_t::object_t::link_t>& other_links,
261 const graph_t& graph,
262 const graph_t& other_graph,
263 unsigned depth) const
Garret Rieger07fd0522022-08-15 23:16:51 +0000264 {
265 auto a = this_links.iter ();
266 auto b = other_links.iter ();
267
268 while (a && b)
269 {
270 const auto& link_a = *a;
271 const auto& link_b = *b;
272
273 if (link_a.width != link_b.width ||
274 link_a.is_signed != link_b.is_signed ||
275 link_a.whence != link_b.whence ||
276 link_a.position != link_b.position ||
277 link_a.bias != link_b.bias)
278 return false;
279
Garret Riegera3ed9f92022-08-17 23:39:11 +0000280 if (!graph.vertices_[link_a.objidx].equals (
281 other_graph.vertices_[link_b.objidx], graph, other_graph, depth + 1))
Garret Rieger07fd0522022-08-15 23:16:51 +0000282 return false;
283
284 a++;
285 b++;
286 }
287
288 if (bool (a) != bool (b))
289 return false;
290
291 return true;
292 }
Garret Rieger20b02a62022-06-24 18:58:17 +0000293 };
294
Garret Rieger0083fd12022-08-11 22:09:46 +0000295 template <typename T>
296 struct vertex_and_table_t
297 {
298 vertex_and_table_t () : index (0), vertex (nullptr), table (nullptr)
299 {}
300
301 unsigned index;
302 vertex_t* vertex;
303 T* table;
304
305 operator bool () {
306 return table && vertex;
307 }
308 };
309
Garret Rieger20b02a62022-06-24 18:58:17 +0000310 /*
311 * A topological sorting of an object graph. Ordered
312 * in reverse serialization order (first object in the
313 * serialization is at the end of the list). This matches
314 * the 'packed' object stack used internally in the
315 * serializer
316 */
317 template<typename T>
318 graph_t (const T& objects)
319 : parents_invalid (true),
320 distance_invalid (true),
321 positions_invalid (true),
Garret Rieger5cf2a252022-08-15 22:49:24 +0000322 successful (true),
323 buffers ()
Garret Rieger20b02a62022-06-24 18:58:17 +0000324 {
325 num_roots_for_space_.push (1);
326 bool removed_nil = false;
327 vertices_.alloc (objects.length);
328 vertices_scratch_.alloc (objects.length);
329 for (unsigned i = 0; i < objects.length; i++)
330 {
Garret Rieger20b02a62022-06-24 18:58:17 +0000331 // If this graph came from a serialization buffer object 0 is the
332 // nil object. We don't need it for our purposes here so drop it.
333 if (i == 0 && !objects[i])
334 {
335 removed_nil = true;
336 continue;
337 }
338
339 vertex_t* v = vertices_.push ();
340 if (check_success (!vertices_.in_error ()))
341 v->obj = *objects[i];
Garret Riegeredf7a292022-09-08 22:59:34 +0000342
Garret Rieger30e405e2022-12-01 22:12:59 +0000343 check_success (v->link_positions_valid (objects.length));
Garret Rieger554ed062022-12-01 21:51:17 +0000344
Garret Rieger20b02a62022-06-24 18:58:17 +0000345 if (!removed_nil) continue;
346 // Fix indices to account for removed nil object.
347 for (auto& l : v->obj.all_links_writer ()) {
348 l.objidx--;
349 }
350 }
351 }
352
353 ~graph_t ()
354 {
355 vertices_.fini ();
Garret Rieger5cf2a252022-08-15 22:49:24 +0000356 for (char* b : buffers)
357 hb_free (b);
Garret Rieger20b02a62022-06-24 18:58:17 +0000358 }
359
Garret Rieger1405f962022-08-15 23:48:00 +0000360 bool operator== (const graph_t& other) const
Garret Rieger07fd0522022-08-15 23:16:51 +0000361 {
Garret Riegera3ed9f92022-08-17 23:39:11 +0000362 return root ().equals (other.root (), *this, other, 0);
Garret Rieger1405f962022-08-15 23:48:00 +0000363 }
364
365 // Sorts links of all objects in a consistent manner and zeroes all offsets.
366 void normalize ()
367 {
368 for (auto& v : vertices_.writer ())
369 v.normalize ();
Garret Rieger07fd0522022-08-15 23:16:51 +0000370 }
371
Garret Rieger20b02a62022-06-24 18:58:17 +0000372 bool in_error () const
373 {
374 return !successful ||
375 vertices_.in_error () ||
376 num_roots_for_space_.in_error ();
377 }
378
379 const vertex_t& root () const
380 {
381 return vertices_[root_idx ()];
382 }
383
384 unsigned root_idx () const
385 {
386 // Object graphs are in reverse order, the first object is at the end
387 // of the vector. Since the graph is topologically sorted it's safe to
388 // assume the first object has no incoming edges.
389 return vertices_.length - 1;
390 }
391
Garret Riegerb1d38a62022-07-19 23:33:16 +0000392 const hb_serialize_context_t::object_t& object (unsigned i) const
Garret Rieger20b02a62022-06-24 18:58:17 +0000393 {
394 return vertices_[i].obj;
395 }
396
Garret Rieger5cf2a252022-08-15 22:49:24 +0000397 void add_buffer (char* buffer)
398 {
399 buffers.push (buffer);
400 }
401
Garret Rieger20b02a62022-06-24 18:58:17 +0000402 /*
Garret Riegerb00eb772022-08-11 20:33:21 +0000403 * Adds a 16 bit link from parent_id to child_id
404 */
405 template<typename T>
406 void add_link (T* offset,
407 unsigned parent_id,
408 unsigned child_id)
409 {
410 auto& v = vertices_[parent_id];
411 auto* link = v.obj.real_links.push ();
412 link->width = 2;
413 link->objidx = child_id;
414 link->position = (char*) offset - (char*) v.obj.head;
415 vertices_[child_id].parents.push (parent_id);
416 }
417
418 /*
Garret Rieger20b02a62022-06-24 18:58:17 +0000419 * Generates a new topological sorting of graph ordered by the shortest
Garret Rieger65afed02022-07-28 20:54:28 +0000420 * distance to each node if positions are marked as invalid.
421 */
422 void sort_shortest_distance_if_needed ()
423 {
424 if (!positions_invalid) return;
425 sort_shortest_distance ();
426 }
427
428
429 /*
430 * Generates a new topological sorting of graph ordered by the shortest
Garret Rieger20b02a62022-06-24 18:58:17 +0000431 * distance to each node.
432 */
433 void sort_shortest_distance ()
434 {
435 positions_invalid = true;
436
437 if (vertices_.length <= 1) {
438 // Graph of 1 or less doesn't need sorting.
439 return;
440 }
441
442 update_distances ();
443
444 hb_priority_queue_t queue;
445 hb_vector_t<vertex_t> &sorted_graph = vertices_scratch_;
446 if (unlikely (!check_success (sorted_graph.resize (vertices_.length)))) return;
447 hb_vector_t<unsigned> id_map;
448 if (unlikely (!check_success (id_map.resize (vertices_.length)))) return;
449
450 hb_vector_t<unsigned> removed_edges;
451 if (unlikely (!check_success (removed_edges.resize (vertices_.length)))) return;
452 update_parents ();
453
454 queue.insert (root ().modified_distance (0), root_idx ());
455 int new_id = root_idx ();
456 unsigned order = 1;
457 while (!queue.in_error () && !queue.is_empty ())
458 {
459 unsigned next_id = queue.pop_minimum().second;
460
461 hb_swap (sorted_graph[new_id], vertices_[next_id]);
462 const vertex_t& next = sorted_graph[new_id];
463
Garret Rieger554ed062022-12-01 21:51:17 +0000464 if (unlikely (!check_success(new_id >= 0))) {
465 // We are out of ids. Which means we've visited a node more than once.
466 // This graph contains a cycle which is not allowed.
467 DEBUG_MSG (SUBSET_REPACK, nullptr, "Invalid graph. Contains cycle.");
468 return;
469 }
470
Garret Rieger20b02a62022-06-24 18:58:17 +0000471 id_map[next_id] = new_id--;
472
473 for (const auto& link : next.obj.all_links ()) {
474 removed_edges[link.objidx]++;
475 if (!(vertices_[link.objidx].incoming_edges () - removed_edges[link.objidx]))
476 // Add the order that the links were encountered to the priority.
477 // This ensures that ties between priorities objects are broken in a consistent
478 // way. More specifically this is set up so that if a set of objects have the same
479 // distance they'll be added to the topological order in the order that they are
480 // referenced from the parent object.
481 queue.insert (vertices_[link.objidx].modified_distance (order++),
482 link.objidx);
483 }
484 }
485
486 check_success (!queue.in_error ());
487 check_success (!sorted_graph.in_error ());
Garret Rieger20b02a62022-06-24 18:58:17 +0000488
489 remap_all_obj_indices (id_map, &sorted_graph);
Garret Rieger20b02a62022-06-24 18:58:17 +0000490 hb_swap (vertices_, sorted_graph);
Garret Riegerfb3f6ad2022-07-29 00:25:19 +0000491
492 if (!check_success (new_id == -1))
493 print_orphaned_nodes ();
Garret Rieger20b02a62022-06-24 18:58:17 +0000494 }
495
Garret Riegerb4f561d2022-07-06 18:49:23 +0000496 /*
497 * Finds the set of nodes (placed into roots) that should be assigned unique spaces.
498 * More specifically this looks for the top most 24 bit or 32 bit links in the graph.
499 * Some special casing is done that is specific to the layout of GSUB/GPOS tables.
500 */
Garret Rieger401066b2022-07-06 18:44:40 +0000501 void find_space_roots (hb_set_t& visited, hb_set_t& roots)
Garret Rieger20b02a62022-06-24 18:58:17 +0000502 {
Garret Rieger401066b2022-07-06 18:44:40 +0000503 int root_index = (int) root_idx ();
504 for (int i = root_index; i >= 0; i--)
Garret Rieger20b02a62022-06-24 18:58:17 +0000505 {
Garret Rieger401066b2022-07-06 18:44:40 +0000506 if (visited.has (i)) continue;
507
Garret Rieger20b02a62022-06-24 18:58:17 +0000508 // Only real links can form 32 bit spaces
509 for (auto& l : vertices_[i].obj.real_links)
510 {
Garret Rieger401066b2022-07-06 18:44:40 +0000511 if (l.is_signed || l.width < 3)
512 continue;
513
514 if (i == root_index && l.width == 3)
515 // Ignore 24bit links from the root node, this skips past the single 24bit
516 // pointer to the lookup list.
517 continue;
518
519 if (l.width == 3)
Garret Rieger20b02a62022-06-24 18:58:17 +0000520 {
Garret Rieger401066b2022-07-06 18:44:40 +0000521 // A 24bit offset forms a root, unless there is 32bit offsets somewhere
Garret Riegerb4f561d2022-07-06 18:49:23 +0000522 // in it's subgraph, then those become the roots instead. This is to make sure
523 // that extension subtables beneath a 24bit lookup become the spaces instead
524 // of the offset to the lookup.
Garret Rieger401066b2022-07-06 18:44:40 +0000525 hb_set_t sub_roots;
526 find_32bit_roots (l.objidx, sub_roots);
527 if (sub_roots) {
528 for (unsigned sub_root_idx : sub_roots) {
529 roots.add (sub_root_idx);
530 find_subgraph (sub_root_idx, visited);
531 }
532 continue;
533 }
Garret Rieger20b02a62022-06-24 18:58:17 +0000534 }
Garret Rieger401066b2022-07-06 18:44:40 +0000535
536 roots.add (l.objidx);
537 find_subgraph (l.objidx, visited);
Garret Rieger20b02a62022-06-24 18:58:17 +0000538 }
539 }
Garret Rieger401066b2022-07-06 18:44:40 +0000540 }
Garret Rieger20b02a62022-06-24 18:58:17 +0000541
Garret Riegerac1a8532022-08-18 00:55:47 +0000542 template <typename T, typename ...Ts>
543 vertex_and_table_t<T> as_table (unsigned parent, const void* offset, Ts... ds)
Garret Rieger0083fd12022-08-11 22:09:46 +0000544 {
Garret Riegerac1a8532022-08-18 00:55:47 +0000545 return as_table_from_index<T> (index_for_offset (parent, offset), std::forward<Ts>(ds)...);
Garret Rieger0083fd12022-08-11 22:09:46 +0000546 }
547
Garret Riegerac1a8532022-08-18 00:55:47 +0000548 template <typename T, typename ...Ts>
Garret Rieger99f46682022-09-29 19:39:59 +0000549 vertex_and_table_t<T> as_mutable_table (unsigned parent, const void* offset, Ts... ds)
550 {
551 return as_table_from_index<T> (mutable_index_for_offset (parent, offset), std::forward<Ts>(ds)...);
552 }
553
554 template <typename T, typename ...Ts>
Garret Riegerac1a8532022-08-18 00:55:47 +0000555 vertex_and_table_t<T> as_table_from_index (unsigned index, Ts... ds)
Garret Rieger0083fd12022-08-11 22:09:46 +0000556 {
557 if (index >= vertices_.length)
558 return vertex_and_table_t<T> ();
559
560 vertex_and_table_t<T> r;
561 r.vertex = &vertices_[index];
562 r.table = (T*) r.vertex->obj.head;
563 r.index = index;
564 if (!r.table)
565 return vertex_and_table_t<T> ();
566
Garret Riegerac1a8532022-08-18 00:55:47 +0000567 if (!r.table->sanitize (*(r.vertex), std::forward<Ts>(ds)...))
Garret Rieger0083fd12022-08-11 22:09:46 +0000568 return vertex_and_table_t<T> ();
569
570 return r;
571 }
572
Garret Rieger5d824c02022-08-05 01:37:14 +0000573 // Finds the object id of the object pointed to by the offset at 'offset'
574 // within object[node_idx].
575 unsigned index_for_offset (unsigned node_idx, const void* offset) const
Garret Rieger3f7a74f2022-07-19 21:50:13 +0000576 {
577 const auto& node = object (node_idx);
578 if (offset < node.head || offset >= node.tail) return -1;
579
Garret Rieger46b5dbd2022-08-18 01:18:16 +0000580 unsigned length = node.real_links.length;
581 for (unsigned i = 0; i < length; i++)
Garret Rieger3f7a74f2022-07-19 21:50:13 +0000582 {
Garret Rieger46b5dbd2022-08-18 01:18:16 +0000583 // Use direct access for increased performance, this is a hot method.
584 const auto& link = node.real_links.arrayZ[i];
Garret Rieger3f7a74f2022-07-19 21:50:13 +0000585 if (offset != node.head + link.position)
586 continue;
587 return link.objidx;
588 }
589
590 return -1;
591 }
592
Garret Rieger5d824c02022-08-05 01:37:14 +0000593 // Finds the object id of the object pointed to by the offset at 'offset'
594 // within object[node_idx]. Ensures that the returned object is safe to mutate.
595 // That is, if the original child object is shared by parents other than node_idx
596 // it will be duplicated and the duplicate will be returned instead.
597 unsigned mutable_index_for_offset (unsigned node_idx, const void* offset)
598 {
599 unsigned child_idx = index_for_offset (node_idx, offset);
600 auto& child = vertices_[child_idx];
601 for (unsigned p : child.parents)
602 {
603 if (p != node_idx) {
604 return duplicate (node_idx, child_idx);
605 }
606 }
607
608 return child_idx;
609 }
610
Garret Rieger3f7a74f2022-07-19 21:50:13 +0000611
Garret Rieger401066b2022-07-06 18:44:40 +0000612 /*
613 * Assign unique space numbers to each connected subgraph of 24 bit and/or 32 bit offset(s).
614 * Currently, this is implemented specifically tailored to the structure of a GPOS/GSUB
615 * (including with 24bit offsets) table.
616 */
617 bool assign_spaces ()
618 {
Garret Riegerb1d38a62022-07-19 23:33:16 +0000619 update_parents ();
620
Garret Rieger401066b2022-07-06 18:44:40 +0000621 hb_set_t visited;
622 hb_set_t roots;
623 find_space_roots (visited, roots);
624
625 // Mark everything not in the subgraphs of the roots as visited. This prevents
626 // subgraphs from being connected via nodes not in those subgraphs.
Garret Rieger20b02a62022-06-24 18:58:17 +0000627 visited.invert ();
628
629 if (!roots) return false;
630
631 while (roots)
632 {
Joel Autersonc813f842022-10-20 19:45:23 +0100633 uint32_t next = HB_SET_VALUE_INVALID;
Garret Rieger20b02a62022-06-24 18:58:17 +0000634 if (unlikely (!check_success (!roots.in_error ()))) break;
635 if (!roots.next (&next)) break;
636
637 hb_set_t connected_roots;
638 find_connected_nodes (next, roots, visited, connected_roots);
639 if (unlikely (!check_success (!connected_roots.in_error ()))) break;
640
641 isolate_subgraph (connected_roots);
642 if (unlikely (!check_success (!connected_roots.in_error ()))) break;
643
644 unsigned next_space = this->next_space ();
645 num_roots_for_space_.push (0);
646 for (unsigned root : connected_roots)
647 {
648 DEBUG_MSG (SUBSET_REPACK, nullptr, "Subgraph %u gets space %u", root, next_space);
649 vertices_[root].space = next_space;
650 num_roots_for_space_[next_space] = num_roots_for_space_[next_space] + 1;
651 distance_invalid = true;
652 positions_invalid = true;
653 }
654
655 // TODO(grieger): special case for GSUB/GPOS use extension promotions to move 16 bit space
656 // into the 32 bit space as needed, instead of using isolation.
657 }
658
659
660
661 return true;
662 }
663
664 /*
665 * Isolates the subgraph of nodes reachable from root. Any links to nodes in the subgraph
666 * that originate from outside of the subgraph will be removed by duplicating the linked to
667 * object.
668 *
669 * Indices stored in roots will be updated if any of the roots are duplicated to new indices.
670 */
671 bool isolate_subgraph (hb_set_t& roots)
672 {
673 update_parents ();
674 hb_map_t subgraph;
675
676 // incoming edges to root_idx should be all 32 bit in length so we don't need to de-dup these
677 // set the subgraph incoming edge count to match all of root_idx's incoming edges
678 hb_set_t parents;
679 for (unsigned root_idx : roots)
680 {
681 subgraph.set (root_idx, wide_parents (root_idx, parents));
682 find_subgraph (root_idx, subgraph);
683 }
684
685 unsigned original_root_idx = root_idx ();
686 hb_map_t index_map;
687 bool made_changes = false;
688 for (auto entry : subgraph.iter ())
689 {
690 const auto& node = vertices_[entry.first];
691 unsigned subgraph_incoming_edges = entry.second;
692
693 if (subgraph_incoming_edges < node.incoming_edges ())
694 {
695 // Only de-dup objects with incoming links from outside the subgraph.
696 made_changes = true;
697 duplicate_subgraph (entry.first, index_map);
698 }
699 }
700
701 if (!made_changes)
702 return false;
703
704 if (original_root_idx != root_idx ()
705 && parents.has (original_root_idx))
706 {
707 // If the root idx has changed since parents was determined, update root idx in parents
708 parents.add (root_idx ());
709 parents.del (original_root_idx);
710 }
711
712 auto new_subgraph =
713 + subgraph.keys ()
Joel Autersonc813f842022-10-20 19:45:23 +0100714 | hb_map([&] (uint32_t node_idx) {
715 const uint32_t *v;
Garret Rieger20b02a62022-06-24 18:58:17 +0000716 if (index_map.has (node_idx, &v)) return *v;
717 return node_idx;
718 })
719 ;
720
721 remap_obj_indices (index_map, new_subgraph);
722 remap_obj_indices (index_map, parents.iter (), true);
723
724 // Update roots set with new indices as needed.
Joel Autersonc813f842022-10-20 19:45:23 +0100725 uint32_t next = HB_SET_VALUE_INVALID;
Garret Rieger20b02a62022-06-24 18:58:17 +0000726 while (roots.next (&next))
727 {
Joel Autersonc813f842022-10-20 19:45:23 +0100728 const uint32_t *v;
Garret Rieger20b02a62022-06-24 18:58:17 +0000729 if (index_map.has (next, &v))
730 {
731 roots.del (next);
732 roots.add (*v);
733 }
734 }
735
736 return true;
737 }
738
739 void find_subgraph (unsigned node_idx, hb_map_t& subgraph)
740 {
741 for (const auto& link : vertices_[node_idx].obj.all_links ())
742 {
Joel Autersonc813f842022-10-20 19:45:23 +0100743 const uint32_t *v;
Garret Rieger20b02a62022-06-24 18:58:17 +0000744 if (subgraph.has (link.objidx, &v))
745 {
746 subgraph.set (link.objidx, *v + 1);
747 continue;
748 }
749 subgraph.set (link.objidx, 1);
750 find_subgraph (link.objidx, subgraph);
751 }
752 }
753
754 void find_subgraph (unsigned node_idx, hb_set_t& subgraph)
755 {
756 if (subgraph.has (node_idx)) return;
757 subgraph.add (node_idx);
758 for (const auto& link : vertices_[node_idx].obj.all_links ())
759 find_subgraph (link.objidx, subgraph);
760 }
761
Garret Rieger9d0b2da2022-07-25 20:46:49 +0000762 size_t find_subgraph_size (unsigned node_idx, hb_set_t& subgraph, unsigned max_depth = -1)
Garret Riegerad0041f2022-07-21 22:50:14 +0000763 {
764 if (subgraph.has (node_idx)) return 0;
765 subgraph.add (node_idx);
766
767 const auto& o = vertices_[node_idx].obj;
768 size_t size = o.tail - o.head;
Garret Rieger9d0b2da2022-07-25 20:46:49 +0000769 if (max_depth == 0)
770 return size;
771
Garret Riegerad0041f2022-07-21 22:50:14 +0000772 for (const auto& link : o.all_links ())
Garret Rieger9d0b2da2022-07-25 20:46:49 +0000773 size += find_subgraph_size (link.objidx, subgraph, max_depth - 1);
Garret Riegerad0041f2022-07-21 22:50:14 +0000774 return size;
775 }
776
Garret Riegerb4f561d2022-07-06 18:49:23 +0000777 /*
778 * Finds the topmost children of 32bit offsets in the subgraph starting
779 * at node_idx. Found indices are placed into 'found'.
780 */
Garret Rieger401066b2022-07-06 18:44:40 +0000781 void find_32bit_roots (unsigned node_idx, hb_set_t& found)
782 {
783 for (const auto& link : vertices_[node_idx].obj.all_links ())
784 {
785 if (!link.is_signed && link.width == 4) {
786 found.add (link.objidx);
787 continue;
788 }
789 find_32bit_roots (link.objidx, found);
790 }
791 }
792
Garret Rieger20b02a62022-06-24 18:58:17 +0000793 /*
Garret Rieger8d63f602022-07-27 20:36:20 +0000794 * Moves the child of old_parent_idx pointed to by old_offset to a new
795 * vertex at the new_offset.
796 */
797 template<typename O>
798 void move_child (unsigned old_parent_idx,
799 const O* old_offset,
800 unsigned new_parent_idx,
801 const O* new_offset)
802 {
Garret Rieger65afed02022-07-28 20:54:28 +0000803 distance_invalid = true;
804 positions_invalid = true;
805
Garret Rieger8d63f602022-07-27 20:36:20 +0000806 auto& old_v = vertices_[old_parent_idx];
807 auto& new_v = vertices_[new_parent_idx];
808
809 unsigned child_id = index_for_offset (old_parent_idx,
810 old_offset);
811
812 auto* new_link = new_v.obj.real_links.push ();
813 new_link->width = O::static_size;
814 new_link->objidx = child_id;
Garret Rieger1002a3d2022-07-28 20:17:36 +0000815 new_link->position = (const char*) new_offset - (const char*) new_v.obj.head;
Garret Rieger8d63f602022-07-27 20:36:20 +0000816
817 auto& child = vertices_[child_id];
818 child.parents.push (new_parent_idx);
819
Garret Rieger3b91fb22022-07-29 20:04:42 +0000820 old_v.remove_real_link (child_id, old_offset);
Garret Rieger8d63f602022-07-27 20:36:20 +0000821 child.remove_parent (old_parent_idx);
822 }
823
824 /*
Garret Rieger20b02a62022-06-24 18:58:17 +0000825 * duplicates all nodes in the subgraph reachable from node_idx. Does not re-assign
826 * links. index_map is updated with mappings from old id to new id. If a duplication has already
827 * been performed for a given index, then it will be skipped.
828 */
829 void duplicate_subgraph (unsigned node_idx, hb_map_t& index_map)
830 {
831 if (index_map.has (node_idx))
832 return;
833
834 index_map.set (node_idx, duplicate (node_idx));
835 for (const auto& l : object (node_idx).all_links ()) {
836 duplicate_subgraph (l.objidx, index_map);
837 }
838 }
839
840 /*
841 * Creates a copy of node_idx and returns it's new index.
842 */
843 unsigned duplicate (unsigned node_idx)
844 {
845 positions_invalid = true;
846 distance_invalid = true;
847
848 auto* clone = vertices_.push ();
849 auto& child = vertices_[node_idx];
850 if (vertices_.in_error ()) {
851 return -1;
852 }
853
854 clone->obj.head = child.obj.head;
855 clone->obj.tail = child.obj.tail;
856 clone->distance = child.distance;
857 clone->space = child.space;
858 clone->parents.reset ();
859
860 unsigned clone_idx = vertices_.length - 2;
861 for (const auto& l : child.obj.real_links)
862 {
863 clone->obj.real_links.push (l);
864 vertices_[l.objidx].parents.push (clone_idx);
865 }
866 for (const auto& l : child.obj.virtual_links)
867 {
868 clone->obj.virtual_links.push (l);
869 vertices_[l.objidx].parents.push (clone_idx);
870 }
871
872 check_success (!clone->obj.real_links.in_error ());
873 check_success (!clone->obj.virtual_links.in_error ());
874
875 // The last object is the root of the graph, so swap back the root to the end.
876 // The root's obj idx does change, however since it's root nothing else refers to it.
877 // all other obj idx's will be unaffected.
878 hb_swap (vertices_[vertices_.length - 2], *clone);
879
880 // Since the root moved, update the parents arrays of all children on the root.
881 for (const auto& l : root ().obj.all_links ())
882 vertices_[l.objidx].remap_parent (root_idx () - 1, root_idx ());
883
884 return clone_idx;
885 }
886
887 /*
888 * Creates a copy of child and re-assigns the link from
889 * parent to the clone. The copy is a shallow copy, objects
890 * linked from child are not duplicated.
891 */
Garret Rieger99f46682022-09-29 19:39:59 +0000892 unsigned duplicate_if_shared (unsigned parent_idx, unsigned child_idx)
893 {
894 unsigned new_idx = duplicate (parent_idx, child_idx);
895 if (new_idx == (unsigned) -1) return child_idx;
896 return new_idx;
897 }
898
899
900 /*
901 * Creates a copy of child and re-assigns the link from
902 * parent to the clone. The copy is a shallow copy, objects
903 * linked from child are not duplicated.
904 */
905 unsigned duplicate (unsigned parent_idx, unsigned child_idx)
Garret Rieger20b02a62022-06-24 18:58:17 +0000906 {
907 update_parents ();
908
909 unsigned links_to_child = 0;
910 for (const auto& l : vertices_[parent_idx].obj.all_links ())
911 {
912 if (l.objidx == child_idx) links_to_child++;
913 }
914
915 if (vertices_[child_idx].incoming_edges () <= links_to_child)
916 {
917 // Can't duplicate this node, doing so would orphan the original one as all remaining links
918 // to child are from parent.
919 DEBUG_MSG (SUBSET_REPACK, nullptr, " Not duplicating %d => %d",
920 parent_idx, child_idx);
Garret Rieger99f46682022-09-29 19:39:59 +0000921 return -1;
Garret Rieger20b02a62022-06-24 18:58:17 +0000922 }
923
924 DEBUG_MSG (SUBSET_REPACK, nullptr, " Duplicating %d => %d",
925 parent_idx, child_idx);
926
927 unsigned clone_idx = duplicate (child_idx);
928 if (clone_idx == (unsigned) -1) return false;
929 // duplicate shifts the root node idx, so if parent_idx was root update it.
930 if (parent_idx == clone_idx) parent_idx++;
931
932 auto& parent = vertices_[parent_idx];
933 for (auto& l : parent.obj.all_links_writer ())
934 {
935 if (l.objidx != child_idx)
936 continue;
937
938 reassign_link (l, parent_idx, clone_idx);
939 }
940
Garret Rieger99f46682022-09-29 19:39:59 +0000941 return clone_idx;
Garret Rieger20b02a62022-06-24 18:58:17 +0000942 }
943
Garret Riegerb1d38a62022-07-19 23:33:16 +0000944
945 /*
946 * Adds a new node to the graph, not connected to anything.
947 */
948 unsigned new_node (char* head, char* tail)
949 {
950 positions_invalid = true;
951 distance_invalid = true;
Garret Riegerb1d38a62022-07-19 23:33:16 +0000952
953 auto* clone = vertices_.push ();
954 if (vertices_.in_error ()) {
955 return -1;
956 }
957
958 clone->obj.head = head;
959 clone->obj.tail = tail;
960 clone->distance = 0;
961 clone->space = 0;
962
963 unsigned clone_idx = vertices_.length - 2;
964
965 // The last object is the root of the graph, so swap back the root to the end.
966 // The root's obj idx does change, however since it's root nothing else refers to it.
967 // all other obj idx's will be unaffected.
968 hb_swap (vertices_[vertices_.length - 2], *clone);
969
970 // Since the root moved, update the parents arrays of all children on the root.
971 for (const auto& l : root ().obj.all_links ())
972 vertices_[l.objidx].remap_parent (root_idx () - 1, root_idx ());
973
974 return clone_idx;
975 }
976
Garret Rieger20b02a62022-06-24 18:58:17 +0000977 /*
978 * Raises the sorting priority of all children.
979 */
980 bool raise_childrens_priority (unsigned parent_idx)
981 {
982 DEBUG_MSG (SUBSET_REPACK, nullptr, " Raising priority of all children of %d",
983 parent_idx);
984 // This operation doesn't change ordering until a sort is run, so no need
985 // to invalidate positions. It does not change graph structure so no need
986 // to update distances or edge counts.
987 auto& parent = vertices_[parent_idx].obj;
988 bool made_change = false;
989 for (auto& l : parent.all_links_writer ())
990 made_change |= vertices_[l.objidx].raise_priority ();
991 return made_change;
992 }
993
Garret Rieger985b19f2022-09-07 22:21:16 +0000994 bool is_fully_connected ()
995 {
996 update_parents();
997
998 for (unsigned i = 0; i < root_idx (); i++)
999 {
1000 if (!vertices_[i].parents)
1001 return false;
1002 }
1003 return true;
1004 }
1005
Garret Riegerdeca30b2022-09-08 21:10:06 +00001006#if 0
1007 /*
1008 * Saves the current graph to a packed binary format which the repacker fuzzer takes
1009 * as a seed.
1010 */
1011 void save_fuzzer_seed (hb_tag_t tag) const
1012 {
1013 FILE* f = fopen ("./repacker_fuzzer_seed", "w");
1014 fwrite ((void*) &tag, sizeof (tag), 1, f);
1015
1016 uint16_t num_objects = vertices_.length;
1017 fwrite ((void*) &num_objects, sizeof (num_objects), 1, f);
1018
1019 for (const auto& v : vertices_)
1020 {
1021 uint16_t blob_size = v.table_size ();
1022 fwrite ((void*) &blob_size, sizeof (blob_size), 1, f);
1023 fwrite ((const void*) v.obj.head, blob_size, 1, f);
1024 }
1025
1026 uint16_t link_count = 0;
1027 for (const auto& v : vertices_)
1028 link_count += v.obj.real_links.length;
1029
1030 fwrite ((void*) &link_count, sizeof (link_count), 1, f);
1031
1032 typedef struct
1033 {
1034 uint16_t parent;
1035 uint16_t child;
1036 uint16_t position;
1037 uint8_t width;
1038 } link_t;
1039
1040 for (unsigned i = 0; i < vertices_.length; i++)
1041 {
1042 for (const auto& l : vertices_[i].obj.real_links)
1043 {
1044 link_t link {
1045 (uint16_t) i, (uint16_t) l.objidx,
1046 (uint16_t) l.position, (uint8_t) l.width
1047 };
1048 fwrite ((void*) &link, sizeof (link), 1, f);
1049 }
1050 }
1051
1052 fclose (f);
1053 }
1054#endif
1055
Garret Rieger20b02a62022-06-24 18:58:17 +00001056 void print_orphaned_nodes ()
1057 {
1058 if (!DEBUG_ENABLED(SUBSET_REPACK)) return;
1059
1060 DEBUG_MSG (SUBSET_REPACK, nullptr, "Graph is not fully connected.");
1061 parents_invalid = true;
1062 update_parents();
1063
1064 for (unsigned i = 0; i < root_idx (); i++)
1065 {
1066 const auto& v = vertices_[i];
1067 if (!v.parents)
1068 DEBUG_MSG (SUBSET_REPACK, nullptr, "Node %u is orphaned.", i);
1069 }
1070 }
1071
Garret Rieger20b02a62022-06-24 18:58:17 +00001072 unsigned num_roots_for_space (unsigned space) const
1073 {
1074 return num_roots_for_space_[space];
1075 }
1076
1077 unsigned next_space () const
1078 {
1079 return num_roots_for_space_.length;
1080 }
1081
1082 void move_to_new_space (const hb_set_t& indices)
1083 {
1084 num_roots_for_space_.push (0);
1085 unsigned new_space = num_roots_for_space_.length - 1;
1086
1087 for (unsigned index : indices) {
1088 auto& node = vertices_[index];
1089 num_roots_for_space_[node.space] = num_roots_for_space_[node.space] - 1;
1090 num_roots_for_space_[new_space] = num_roots_for_space_[new_space] + 1;
1091 node.space = new_space;
1092 distance_invalid = true;
1093 positions_invalid = true;
1094 }
1095 }
1096
1097 unsigned space_for (unsigned index, unsigned* root = nullptr) const
1098 {
1099 const auto& node = vertices_[index];
1100 if (node.space)
1101 {
1102 if (root != nullptr)
1103 *root = index;
1104 return node.space;
1105 }
1106
1107 if (!node.parents)
1108 {
1109 if (root)
1110 *root = index;
1111 return 0;
1112 }
1113
1114 return space_for (node.parents[0], root);
1115 }
1116
1117 void err_other_error () { this->successful = false; }
1118
1119 size_t total_size_in_bytes () const {
1120 size_t total_size = 0;
1121 for (unsigned i = 0; i < vertices_.length; i++) {
1122 size_t size = vertices_[i].obj.tail - vertices_[i].obj.head;
1123 total_size += size;
1124 }
1125 return total_size;
1126 }
1127
1128
1129 private:
1130
1131 /*
Garret Rieger401066b2022-07-06 18:44:40 +00001132 * Returns the numbers of incoming edges that are 24 or 32 bits wide.
Garret Rieger20b02a62022-06-24 18:58:17 +00001133 */
1134 unsigned wide_parents (unsigned node_idx, hb_set_t& parents) const
1135 {
1136 unsigned count = 0;
1137 hb_set_t visited;
1138 for (unsigned p : vertices_[node_idx].parents)
1139 {
1140 if (visited.has (p)) continue;
1141 visited.add (p);
1142
1143 // Only real links can be wide
1144 for (const auto& l : vertices_[p].obj.real_links)
1145 {
Garret Rieger401066b2022-07-06 18:44:40 +00001146 if (l.objidx == node_idx
1147 && (l.width == 3 || l.width == 4)
1148 && !l.is_signed)
Garret Rieger20b02a62022-06-24 18:58:17 +00001149 {
1150 count++;
1151 parents.add (p);
1152 }
1153 }
1154 }
1155 return count;
1156 }
1157
1158 bool check_success (bool success)
1159 { return this->successful && (success || ((void) err_other_error (), false)); }
1160
Garret Rieger70785602022-06-24 19:20:20 +00001161 public:
Garret Rieger20b02a62022-06-24 18:58:17 +00001162 /*
1163 * Creates a map from objid to # of incoming edges.
1164 */
1165 void update_parents ()
1166 {
1167 if (!parents_invalid) return;
1168
1169 for (unsigned i = 0; i < vertices_.length; i++)
1170 vertices_[i].parents.reset ();
1171
1172 for (unsigned p = 0; p < vertices_.length; p++)
1173 {
1174 for (auto& l : vertices_[p].obj.all_links ())
1175 {
1176 vertices_[l.objidx].parents.push (p);
1177 }
1178 }
1179
1180 parents_invalid = false;
1181 }
1182
1183 /*
1184 * compute the serialized start and end positions for each vertex.
1185 */
1186 void update_positions ()
1187 {
1188 if (!positions_invalid) return;
1189
1190 unsigned current_pos = 0;
1191 for (int i = root_idx (); i >= 0; i--)
1192 {
1193 auto& v = vertices_[i];
1194 v.start = current_pos;
1195 current_pos += v.obj.tail - v.obj.head;
1196 v.end = current_pos;
1197 }
1198
1199 positions_invalid = false;
1200 }
1201
1202 /*
1203 * Finds the distance to each object in the graph
1204 * from the initial node.
1205 */
1206 void update_distances ()
1207 {
1208 if (!distance_invalid) return;
1209
1210 // Uses Dijkstra's algorithm to find all of the shortest distances.
1211 // https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
1212 //
1213 // Implementation Note:
1214 // Since our priority queue doesn't support fast priority decreases
1215 // we instead just add new entries into the queue when a priority changes.
1216 // Redundant ones are filtered out later on by the visited set.
1217 // According to https://www3.cs.stonybrook.edu/~rezaul/papers/TR-07-54.pdf
1218 // for practical performance this is faster then using a more advanced queue
1219 // (such as a fibonacci queue) with a fast decrease priority.
1220 for (unsigned i = 0; i < vertices_.length; i++)
1221 {
1222 if (i == vertices_.length - 1)
1223 vertices_[i].distance = 0;
1224 else
1225 vertices_[i].distance = hb_int_max (int64_t);
1226 }
1227
1228 hb_priority_queue_t queue;
1229 queue.insert (0, vertices_.length - 1);
1230
1231 hb_vector_t<bool> visited;
1232 visited.resize (vertices_.length);
1233
1234 while (!queue.in_error () && !queue.is_empty ())
1235 {
1236 unsigned next_idx = queue.pop_minimum ().second;
1237 if (visited[next_idx]) continue;
1238 const auto& next = vertices_[next_idx];
1239 int64_t next_distance = vertices_[next_idx].distance;
1240 visited[next_idx] = true;
1241
1242 for (const auto& link : next.obj.all_links ())
1243 {
1244 if (visited[link.objidx]) continue;
1245
1246 const auto& child = vertices_[link.objidx].obj;
1247 unsigned link_width = link.width ? link.width : 4; // treat virtual offsets as 32 bits wide
1248 int64_t child_weight = (child.tail - child.head) +
1249 ((int64_t) 1 << (link_width * 8)) * (vertices_[link.objidx].space + 1);
1250 int64_t child_distance = next_distance + child_weight;
1251
1252 if (child_distance < vertices_[link.objidx].distance)
1253 {
1254 vertices_[link.objidx].distance = child_distance;
1255 queue.insert (child_distance, link.objidx);
1256 }
1257 }
1258 }
1259
1260 check_success (!queue.in_error ());
1261 if (!check_success (queue.is_empty ()))
1262 {
1263 print_orphaned_nodes ();
1264 return;
1265 }
1266
1267 distance_invalid = false;
1268 }
1269
Garret Rieger70785602022-06-24 19:20:20 +00001270 private:
Garret Rieger20b02a62022-06-24 18:58:17 +00001271 /*
1272 * Updates a link in the graph to point to a different object. Corrects the
1273 * parents vector on the previous and new child nodes.
1274 */
1275 void reassign_link (hb_serialize_context_t::object_t::link_t& link,
1276 unsigned parent_idx,
1277 unsigned new_idx)
1278 {
1279 unsigned old_idx = link.objidx;
1280 link.objidx = new_idx;
1281 vertices_[old_idx].remove_parent (parent_idx);
1282 vertices_[new_idx].parents.push (parent_idx);
1283 }
1284
1285 /*
1286 * Updates all objidx's in all links using the provided mapping. Corrects incoming edge counts.
1287 */
1288 template<typename Iterator, hb_requires (hb_is_iterator (Iterator))>
1289 void remap_obj_indices (const hb_map_t& id_map,
1290 Iterator subgraph,
1291 bool only_wide = false)
1292 {
1293 if (!id_map) return;
1294 for (unsigned i : subgraph)
1295 {
1296 for (auto& link : vertices_[i].obj.all_links_writer ())
1297 {
Joel Autersonc813f842022-10-20 19:45:23 +01001298 const uint32_t *v;
Garret Rieger20b02a62022-06-24 18:58:17 +00001299 if (!id_map.has (link.objidx, &v)) continue;
1300 if (only_wide && !(link.width == 4 && !link.is_signed)) continue;
1301
1302 reassign_link (link, i, *v);
1303 }
1304 }
1305 }
1306
1307 /*
1308 * Updates all objidx's in all links using the provided mapping.
1309 */
1310 void remap_all_obj_indices (const hb_vector_t<unsigned>& id_map,
1311 hb_vector_t<vertex_t>* sorted_graph) const
1312 {
1313 for (unsigned i = 0; i < sorted_graph->length; i++)
1314 {
1315 (*sorted_graph)[i].remap_parents (id_map);
1316 for (auto& link : (*sorted_graph)[i].obj.all_links_writer ())
1317 {
1318 link.objidx = id_map[link.objidx];
1319 }
1320 }
1321 }
1322
1323 /*
1324 * Finds all nodes in targets that are reachable from start_idx, nodes in visited will be skipped.
1325 * For this search the graph is treated as being undirected.
1326 *
1327 * Connected targets will be added to connected and removed from targets. All visited nodes
1328 * will be added to visited.
1329 */
1330 void find_connected_nodes (unsigned start_idx,
1331 hb_set_t& targets,
1332 hb_set_t& visited,
1333 hb_set_t& connected)
1334 {
1335 if (unlikely (!check_success (!visited.in_error ()))) return;
1336 if (visited.has (start_idx)) return;
1337 visited.add (start_idx);
1338
1339 if (targets.has (start_idx))
1340 {
1341 targets.del (start_idx);
1342 connected.add (start_idx);
1343 }
1344
1345 const auto& v = vertices_[start_idx];
1346
1347 // Graph is treated as undirected so search children and parents of start_idx
1348 for (const auto& l : v.obj.all_links ())
1349 find_connected_nodes (l.objidx, targets, visited, connected);
1350
1351 for (unsigned p : v.parents)
1352 find_connected_nodes (p, targets, visited, connected);
1353 }
1354
1355 public:
1356 // TODO(garretrieger): make private, will need to move most of offset overflow code into graph.
1357 hb_vector_t<vertex_t> vertices_;
1358 hb_vector_t<vertex_t> vertices_scratch_;
1359 private:
1360 bool parents_invalid;
1361 bool distance_invalid;
1362 bool positions_invalid;
1363 bool successful;
1364 hb_vector_t<unsigned> num_roots_for_space_;
Garret Rieger5cf2a252022-08-15 22:49:24 +00001365 hb_vector_t<char*> buffers;
Garret Rieger20b02a62022-06-24 18:58:17 +00001366};
1367
1368}
1369
1370#endif // GRAPH_GRAPH_HH