diff --git a/src/graph/classdef-graph.hh b/src/graph/classdef-graph.hh index da98f8e29..91de30063 100644 --- a/src/graph/classdef-graph.hh +++ b/src/graph/classdef-graph.hh @@ -26,6 +26,7 @@ #include "graph.hh" #include "../hb-ot-layout-common.hh" +#include "graph-result.hh" #ifndef GRAPH_CLASSDEF_GRAPH_HH #define GRAPH_CLASSDEF_GRAPH_HH @@ -34,95 +35,99 @@ namespace graph { struct ClassDefFormat1 : public OT::ClassDefFormat1_3 { - bool sanitize (const graph_t::vertex_t& vertex) const + graph_result_t sanitize (const graph_t::vertex_t& vertex) const { - size_t vertex_len = vertex.obj.tail - vertex.obj.head; + size_t vertex_len = vertex.table_size(); constexpr unsigned min_size = OT::ClassDefFormat1_3::min_size; - if (vertex_len < min_size) return false; + if (unlikely (vertex_len < min_size)) return Err(SANITIZE_FAILURE); hb_barrier (); - return vertex_len >= min_size + classValue.get_size () - classValue.len.get_size (); + if (unlikely (vertex_len < min_size + classValue.get_size () - classValue.len.get_size ())) + return Err(SANITIZE_FAILURE); + return Ok(); } }; struct ClassDefFormat2 : public OT::ClassDefFormat2_4 { - bool sanitize (const graph_t::vertex_t& vertex) const + graph_result_t sanitize (const graph_t::vertex_t& vertex) const { - size_t vertex_len = vertex.obj.tail - vertex.obj.head; + size_t vertex_len = vertex.table_size(); constexpr unsigned min_size = OT::ClassDefFormat2_4::min_size; - if (vertex_len < min_size) return false; + if (unlikely (vertex_len < min_size)) return Err(SANITIZE_FAILURE); hb_barrier (); - return vertex_len >= min_size + rangeRecord.get_size () - rangeRecord.len.get_size (); + if (unlikely (vertex_len < min_size + rangeRecord.get_size () - rangeRecord.len.get_size ())) + return Err(SANITIZE_FAILURE); + return Ok(); } }; struct ClassDef : public OT::ClassDef { template - static bool add_class_def (gsubgpos_graph_context_t& c, - unsigned parent_id, - unsigned link_position, - It glyph_and_class, - unsigned max_size) + static graph_result_t add_class_def (gsubgpos_graph_context_t& c, + unsigned parent_id, + unsigned link_position, + It glyph_and_class, + unsigned max_size) { - unsigned class_def_prime_id = c.graph.new_node (nullptr, nullptr); - if (class_def_prime_id == HB_GRAPH_INVALID) return false; + unsigned class_def_prime_id = TRY (c.graph.new_node (nullptr, nullptr)); auto& class_def_prime_vertex = c.graph.vertices_[class_def_prime_id]; - if (!make_class_def (c, glyph_and_class, class_def_prime_id, max_size)) - return false; + TRY (make_class_def (c, glyph_and_class, class_def_prime_id, max_size)); - auto* class_def_link = c.graph.vertices_[parent_id].obj.real_links.push (); - class_def_link->width = SmallTypes::size; - class_def_link->objidx = class_def_prime_id; - class_def_link->position = link_position; - class_def_prime_vertex.add_parent (parent_id, false); + TRY(c.graph.vertices_[parent_id].add_real_link (SmallTypes::size, class_def_prime_id, link_position)); + TRY(class_def_prime_vertex.add_parent (parent_id, false)); - return true; + return Ok(); } template - static bool make_class_def (gsubgpos_graph_context_t& c, - It glyph_and_class, - unsigned dest_obj, - unsigned max_size) + static graph_result_t make_class_def (gsubgpos_graph_context_t& c, + It glyph_and_class, + unsigned dest_obj, + unsigned max_size) { char* buffer = (char*) hb_calloc (1, max_size); + if (unlikely (!buffer)) + return Err(ALLOCATION_FAILURE); + hb_serialize_context_t serializer (buffer, max_size); OT::ClassDef_serialize (&serializer, glyph_and_class); serializer.end_serialize (); - if (serializer.in_error ()) + if (unlikely (serializer.in_error ())) { hb_free (buffer); - return false; + return Err(ALLOCATION_FAILURE); } hb_bytes_t class_def_copy = serializer.copy_bytes (); - if (!class_def_copy.arrayZ) + if (unlikely (!class_def_copy.arrayZ)) { hb_free (buffer); - return false; + return Err(ALLOCATION_FAILURE); } // Give ownership to the context, it will cleanup the buffer. - if (!c.add_buffer ((char *) class_def_copy.arrayZ)) + auto res = c.add_buffer ((char *) class_def_copy.arrayZ); + if (unlikely (!res.is_ok ())) { hb_free (buffer); hb_free ((char *) class_def_copy.arrayZ); - return false; + return res; } - auto& obj = c.graph.vertices_[dest_obj].obj; - obj.head = (char *) class_def_copy.arrayZ; - obj.tail = obj.head + class_def_copy.length; + + auto& v = c.graph.vertices_[dest_obj]; + char* head = (char *) class_def_copy.arrayZ; + v.set_buffer (head, head + class_def_copy.length); hb_free (buffer); - return true; + return Ok(); } - bool sanitize (const graph_t::vertex_t& vertex) const + graph_result_t sanitize (const graph_t::vertex_t& vertex) const { - size_t vertex_len = vertex.obj.tail - vertex.obj.head; - if (vertex_len < OT::ClassDef::min_size) return false; + size_t vertex_len = vertex.table_size(); + if (unlikely (vertex_len < OT::ClassDef::min_size)) return Err(SANITIZE_FAILURE); hb_barrier (); switch (u.format.v) { @@ -133,7 +138,7 @@ struct ClassDef : public OT::ClassDef case 3: case 4: #endif - default: return false; + default: return Err(SANITIZE_FAILURE); } } }; @@ -149,33 +154,33 @@ struct class_def_size_estimator_t constexpr static unsigned bytes_per_glyph = 2; template - class_def_size_estimator_t (It glyph_and_class) - : num_ranges_per_class (), glyphs_per_class () + static graph_result_t create (It glyph_and_class) { - reset(); + class_def_size_estimator_t estimator; + estimator.reset(); for (auto p : + glyph_and_class) { unsigned gid = p.first; unsigned klass = p.second; hb_set_t* glyphs; - if (glyphs_per_class.has (klass, &glyphs) && glyphs) { + if (estimator.glyphs_per_class.has (klass, &glyphs) && glyphs) { glyphs->add (gid); continue; } hb_set_t new_glyphs; new_glyphs.add (gid); - glyphs_per_class.set (klass, std::move (new_glyphs)); + estimator.glyphs_per_class.set (klass, std::move (new_glyphs)); } - if (in_error ()) return; + TRY(estimator.to_result ()); - for (unsigned klass : glyphs_per_class.keys ()) + for (unsigned klass : estimator.glyphs_per_class.keys ()) { if (!klass) continue; // class 0 doesn't get encoded. - const hb_set_t& glyphs = glyphs_per_class.get (klass); + const hb_set_t& glyphs = estimator.glyphs_per_class.get (klass); hb_codepoint_t start = HB_SET_VALUE_INVALID; hb_codepoint_t end = HB_SET_VALUE_INVALID; @@ -183,8 +188,11 @@ struct class_def_size_estimator_t while (glyphs.next_range (&start, &end)) count++; - num_ranges_per_class.set (klass, count); + estimator.num_ranges_per_class.set (klass, count); } + + TRY(estimator.to_result ()); + return estimator; } void reset() { @@ -239,19 +247,22 @@ struct class_def_size_estimator_t return count; } - bool in_error () + private: + graph_result_t to_result() const { - if (num_ranges_per_class.in_error ()) return true; - if (glyphs_per_class.in_error ()) return true; + TRY (graph_result_t::from (num_ranges_per_class, ALLOCATION_FAILURE)); + TRY (graph_result_t::from (glyphs_per_class, ALLOCATION_FAILURE)); for (const hb_set_t& s : glyphs_per_class.values ()) { - if (s.in_error ()) return true; + TRY (graph_result_t::from (s, ALLOCATION_FAILURE)); } - return false; + return Ok(); } - private: + class_def_size_estimator_t () + : num_ranges_per_class (), glyphs_per_class () {} + unsigned compute_coverage_size () const { unsigned format1_size = coverage_base_size + bytes_per_glyph * included_glyphs.get_population(); diff --git a/src/graph/coverage-graph.hh b/src/graph/coverage-graph.hh index aafc5d059..4e2e7feb3 100644 --- a/src/graph/coverage-graph.hh +++ b/src/graph/coverage-graph.hh @@ -32,42 +32,47 @@ namespace graph { -static bool sanitize ( +static graph_result_t sanitize ( const OT::Layout::Common::CoverageFormat1_3* thiz, const graph_t::vertex_t& vertex ) { - size_t vertex_len = vertex.obj.tail - vertex.obj.head; + size_t vertex_len = vertex.table_size(); constexpr unsigned min_size = OT::Layout::Common::CoverageFormat1_3::min_size; - if (vertex_len < min_size) return false; + if (unlikely (vertex_len < min_size)) return Err(SANITIZE_FAILURE); hb_barrier (); - return vertex_len >= min_size + thiz->glyphArray.get_size () - thiz->glyphArray.len.get_size (); + if (unlikely (vertex_len < min_size + thiz->glyphArray.get_size () - thiz->glyphArray.len.get_size ())) + return Err(SANITIZE_FAILURE); + return Ok(); } -static bool sanitize ( +static graph_result_t sanitize ( const OT::Layout::Common::CoverageFormat2_4* thiz, const graph_t::vertex_t& vertex ) { - size_t vertex_len = vertex.obj.tail - vertex.obj.head; + size_t vertex_len = vertex.table_size(); constexpr unsigned min_size = OT::Layout::Common::CoverageFormat2_4::min_size; - if (vertex_len < min_size) return false; + if (unlikely (vertex_len < min_size)) return Err(SANITIZE_FAILURE); hb_barrier (); - return vertex_len >= min_size + thiz->rangeRecord.get_size () - thiz->rangeRecord.len.get_size (); + if (unlikely (vertex_len < min_size + thiz->rangeRecord.get_size () - thiz->rangeRecord.len.get_size ())) + return Err(SANITIZE_FAILURE); + return Ok(); } struct Coverage : public OT::Layout::Common::Coverage { - static Coverage* clone_coverage (gsubgpos_graph_context_t& c, - unsigned coverage_id, - unsigned new_parent_id, - unsigned link_position, - unsigned start, unsigned end) + static graph_result_t clone_coverage (gsubgpos_graph_context_t& c, + unsigned coverage_id, + unsigned new_parent_id, + unsigned link_position, + unsigned start, unsigned end) { unsigned coverage_size = c.graph.vertices_[coverage_id].table_size (); auto& coverage_v = c.graph.vertices_[coverage_id]; - Coverage* coverage_table = (Coverage*) coverage_v.obj.head; - if (!coverage_table || !coverage_table->sanitize (coverage_v)) - return nullptr; + const Coverage* coverage_table = (const Coverage*) coverage_v.obj().head; + if (unlikely (!coverage_table)) + return Err(INVALID_ARGUMENT); + TRY (coverage_table->sanitize (coverage_v)); auto new_coverage = + hb_zip (coverage_table->iter (), hb_range ()) @@ -81,37 +86,32 @@ struct Coverage : public OT::Layout::Common::Coverage } template - static Coverage* add_coverage (gsubgpos_graph_context_t& c, - unsigned parent_id, - unsigned link_position, - It glyphs, - unsigned max_size) + static graph_result_t add_coverage (gsubgpos_graph_context_t& c, + unsigned parent_id, + unsigned link_position, + It glyphs, + unsigned max_size) { - unsigned coverage_prime_id = c.graph.new_node (nullptr, nullptr); - if (coverage_prime_id == HB_GRAPH_INVALID) - return nullptr; + unsigned coverage_prime_id = TRY (c.graph.new_node (nullptr, nullptr)); auto& coverage_prime_vertex = c.graph.vertices_[coverage_prime_id]; - if (!make_coverage (c, glyphs, coverage_prime_id, max_size)) - return nullptr; + TRY (make_coverage (c, glyphs, coverage_prime_id, max_size)); - auto* coverage_link = c.graph.vertices_[parent_id].obj.real_links.push (); - coverage_link->width = SmallTypes::size; - coverage_link->objidx = coverage_prime_id; - coverage_link->position = link_position; - coverage_prime_vertex.add_parent (parent_id, false); + TRY(c.graph.vertices_[parent_id].add_real_link (SmallTypes::size, coverage_prime_id, link_position)); + TRY(coverage_prime_vertex.add_parent (parent_id, false)); - return (Coverage*) coverage_prime_vertex.obj.head; + return Ok(); } // Filter an existing coverage table to glyphs at indices [start, end) and replace it with the filtered version. - static bool filter_coverage (gsubgpos_graph_context_t& c, - unsigned existing_coverage, - unsigned start, unsigned end) { + static graph_result_t filter_coverage (gsubgpos_graph_context_t& c, + unsigned existing_coverage, + unsigned start, unsigned end) { unsigned coverage_size = c.graph.vertices_[existing_coverage].table_size (); auto& coverage_v = c.graph.vertices_[existing_coverage]; - Coverage* coverage_table = (Coverage*) coverage_v.obj.head; - if (!coverage_table || !coverage_table->sanitize (coverage_v)) - return false; + const Coverage* coverage_table = (const Coverage*) coverage_v.obj().head; + if (unlikely (!coverage_table)) + return Err(INVALID_ARGUMENT); + TRY (coverage_table->sanitize (coverage_v)); auto new_coverage = + hb_zip (coverage_table->iter (), hb_range ()) @@ -126,47 +126,51 @@ struct Coverage : public OT::Layout::Common::Coverage // Replace the coverage table at dest obj with one covering 'glyphs'. template - static bool make_coverage (gsubgpos_graph_context_t& c, - It glyphs, - unsigned dest_obj, - unsigned max_size) + static graph_result_t make_coverage (gsubgpos_graph_context_t& c, + It glyphs, + unsigned dest_obj, + unsigned max_size) { char* buffer = (char*) hb_calloc (1, max_size); + if (unlikely (!buffer)) + return Err(ALLOCATION_FAILURE); + hb_serialize_context_t serializer (buffer, max_size); OT::Layout::Common::Coverage_serialize (&serializer, glyphs); serializer.end_serialize (); - if (serializer.in_error ()) + if (unlikely (serializer.in_error ())) { hb_free (buffer); - return false; + return Err(ALLOCATION_FAILURE); } hb_bytes_t coverage_copy = serializer.copy_bytes (); - if (!coverage_copy.arrayZ) { + if (unlikely (!coverage_copy.arrayZ)) { hb_free (buffer); - return false; + return Err(ALLOCATION_FAILURE); } // Give ownership to the context, it will cleanup the buffer. - if (!c.add_buffer ((char *) coverage_copy.arrayZ)) + auto res = c.add_buffer ((char *) coverage_copy.arrayZ); + if (unlikely (!res.is_ok ())) { hb_free (buffer); hb_free ((char *) coverage_copy.arrayZ); - return false; + return res; } - auto& obj = c.graph.vertices_[dest_obj].obj; - obj.head = (char *) coverage_copy.arrayZ; - obj.tail = obj.head + coverage_copy.length; + auto& v = c.graph.vertices_[dest_obj]; + char* head = (char *) coverage_copy.arrayZ; + v.set_buffer (head, head + coverage_copy.length); hb_free (buffer); - return true; + return Ok(); } - bool sanitize (const graph_t::vertex_t& vertex) const + graph_result_t sanitize (const graph_t::vertex_t& vertex) const { - size_t vertex_len = vertex.obj.tail - vertex.obj.head; - if (vertex_len < OT::Layout::Common::Coverage::min_size) return false; + size_t vertex_len = vertex.table_size (); + if (unlikely (vertex_len < OT::Layout::Common::Coverage::min_size)) return Err(SANITIZE_FAILURE); hb_barrier (); switch (u.format.v) { @@ -177,7 +181,7 @@ struct Coverage : public OT::Layout::Common::Coverage case 3: case 4: #endif - default: return false; + default: return Err(SANITIZE_FAILURE); } } }; diff --git a/src/graph/graph-result.hh b/src/graph/graph-result.hh new file mode 100644 index 000000000..ad6029c8c --- /dev/null +++ b/src/graph/graph-result.hh @@ -0,0 +1,67 @@ +/* + * Copyright © 2026 Google, Inc. + * + * This is part of HarfBuzz, a text shaping library. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and its documentation for any purpose, provided that the + * above copyright notice and the following two paragraphs appear in + * all copies of this software. + * + * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES + * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN + * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH + * DAMAGE. + * + * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, + * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. + * + * Google Author(s): Garret Rieger + */ + +#ifndef GRAPH_GRAPH_RESULT_HH +#define GRAPH_GRAPH_RESULT_HH + +#include "../hb-result.hh" + +namespace graph { + +enum graph_error_t { + ALLOCATION_FAILURE, + LIMIT_EXCEEDED, + INVALID_ARGUMENT, + CYCLE_DETECTED, + SANITIZE_FAILURE, + OUT_OF_BOUNDS, + ORPHANED_NODES, + OVERFLOW_RESOLUTION_FAILED, + UNKNOWN, +}; + +static inline const char* to_string(graph_error_t e) { + switch (e) { + case ALLOCATION_FAILURE: return "Memory Allocation Failed"; + case LIMIT_EXCEEDED: return "Limit Exceeded"; + case INVALID_ARGUMENT: return "Invalid Argument"; + case CYCLE_DETECTED: return "Cycle in Graph"; + case SANITIZE_FAILURE: return "Failed Sanitization"; + case OUT_OF_BOUNDS: return "Out of Bounds"; + case ORPHANED_NODES: return "Graph is not fully connected"; + case OVERFLOW_RESOLUTION_FAILED: return "Overflows are not able to be resolved"; + case UNKNOWN: + default: + return "Unknown Error"; + } +} + +template +using graph_result_t = hb_result_t; + +} // namespace graph + +#endif /* GRAPH_GRAPH_RESULT_HH */ diff --git a/src/graph/graph.hh b/src/graph/graph.hh index 4ee0f2495..809b83314 100644 --- a/src/graph/graph.hh +++ b/src/graph/graph.hh @@ -27,6 +27,7 @@ #include "../hb-set.hh" #include "../hb-priority-queue.hh" #include "../hb-serialize.hh" +#include "graph-result.hh" #ifndef GRAPH_GRAPH_HH #define GRAPH_GRAPH_HH @@ -41,15 +42,29 @@ namespace graph { */ struct graph_t { + // TODO(garretrieger): experiment with using scratch vector for visited sets instead of allocating + // a new hb_set_t each time. + struct vertex_t { - hb_serialize_context_t::object_t obj; + // TODO(garretrieger): have vertex_t gaurantee that head/tail are non null and head < tail + // so downstream users don't need to constantly check that. + + // TODO(garretrieger): have vertex_t gaurantee that all link indexes are valid (ie < vertices_.length) + // so downstream users don't need to constantly check that. + + // TODO(garretrieger): track where the real links are currently sorted, and automatically sort + // prior to accessing iterator for real links. Avoids needing to manually trigger sorting by + // downstream users. + int64_t distance = 0 ; unsigned space = 0 ; unsigned start = 0; unsigned end = 0; unsigned priority = 0; + private: + hb_serialize_context_t::object_t obj_; unsigned incoming_edges_ = 0; unsigned single_parent = HB_GRAPH_INVALID; bool has_incoming_virtual_edges_ = false; @@ -57,6 +72,12 @@ struct graph_t hb_set_t virtual_parents; public: + vertex_t () + {} + + explicit vertex_t(const hb_serialize_context_t::object_t& obj) : obj_(obj) + {} + auto parents_iter () const HB_AUTO_RETURN ( hb_concat ( @@ -65,9 +86,75 @@ struct graph_t ) ) - bool in_error () const + void set_buffer (char* head, char* tail) { + obj_.head = head; + obj_.tail = tail; + } + + void shrink_buffer (size_t count) { - return parents.in_error () || virtual_parents.in_error (); + obj_.tail -= count; + } + + auto all_links_writer () HB_AUTO_RETURN (( obj_.all_links_writer() )); + auto real_links_writer () HB_AUTO_RETURN (( obj_.real_links.writer() )); + auto virtual_links_writer () HB_AUTO_RETURN (( obj_.virtual_links.writer() )); + + void sort_real_links () { + obj_.real_links.qsort (); + } + + graph_result_t add_real_link (unsigned width, unsigned obj_idx, unsigned position) { + auto* link = obj_.real_links.push (); + TRY (graph_result_t::from (obj_.real_links, ALLOCATION_FAILURE)); + link->width = width; + link->objidx = obj_idx; + link->position = position; + return Ok(); + } + + graph_result_t add_virtual_link (unsigned obj_idx) { + auto* link = obj_.virtual_links.push (); + TRY (graph_result_t::from (obj_.virtual_links, ALLOCATION_FAILURE)); + link->objidx = obj_idx; + return Ok(); + } + + graph_result_t add_real_link (const hb_serialize_context_t::object_t::link_t& link) + { + obj_.real_links.push (link); + return graph_result_t::from (obj_.real_links, ALLOCATION_FAILURE); + } + + graph_result_t set_real_links (hb_vector_t&& links) + { + TRY(graph_result_t::from (links, ALLOCATION_FAILURE)); + obj_.real_links = links; + return Ok(); + } + + void clear_real_links () + { + obj_.real_links.reset(); + } + + void clear_virtual_links () + { + obj_.virtual_links.reset(); + } + + graph_result_t add_virtual_link (const hb_serialize_context_t::object_t::link_t& link) + { + obj_.virtual_links.push (link); + return graph_result_t::from (obj_.virtual_links, ALLOCATION_FAILURE); + } + + const hb_serialize_context_t::object_t& obj() const { return obj_; } + + template + T as () + { + return reinterpret_cast (obj_.head); } bool has_incoming_virtual_edges () const @@ -75,17 +162,17 @@ struct graph_t return has_incoming_virtual_edges_; } - bool link_positions_valid (unsigned num_objects, bool removed_nil) + graph_result_t link_positions_valid (unsigned num_objects, bool removed_nil) { hb_set_t assigned_bytes; - for (const auto& l : obj.real_links) + for (const auto& l : obj_.real_links) { - if (l.objidx >= num_objects - || (removed_nil && !l.objidx)) + if (unlikely (l.objidx >= num_objects + || (removed_nil && !l.objidx))) { DEBUG_MSG (SUBSET_REPACK, nullptr, "Invalid graph. Invalid object index."); - return false; + return Err(INVALID_ARGUMENT); } unsigned start = l.position; @@ -95,37 +182,37 @@ struct graph_t { DEBUG_MSG (SUBSET_REPACK, nullptr, "Invalid graph. Invalid link width."); - return false; + return Err(INVALID_ARGUMENT); } if (unlikely (end >= table_size ())) { DEBUG_MSG (SUBSET_REPACK, nullptr, "Invalid graph. Link position is out of bounds."); - return false; + return Err(OUT_OF_BOUNDS); } if (unlikely (assigned_bytes.intersects (start, end))) { DEBUG_MSG (SUBSET_REPACK, nullptr, "Invalid graph. Found offsets whose positions overlap."); - return false; + return Err(INVALID_ARGUMENT); } assigned_bytes.add_range (start, end); } - return !assigned_bytes.in_error (); + return graph_result_t::from (assigned_bytes, ALLOCATION_FAILURE); } void normalize () { - obj.real_links.qsort (); - for (auto& l : obj.real_links) + obj_.real_links.qsort (); + for (const auto& l : obj_.real_links) { for (unsigned i = 0; i < l.width; i++) { - obj.head[l.position + i] = 0; + obj_.head[l.position + i] = 0; } } } @@ -159,17 +246,17 @@ struct graph_t return false; } - return links_equal (obj.real_links, other.obj.real_links, graph, other_graph, depth); + return links_equal (obj_.real_links, other.obj_.real_links, graph, other_graph, depth); } hb_bytes_t as_bytes () const { - return hb_bytes_t (obj.head, table_size ()); + return hb_bytes_t (obj_.head, table_size ()); } friend void swap (vertex_t& a, vertex_t& b) { - hb_swap (a.obj, b.obj); + hb_swap (a.obj_, b.obj_); hb_swap (a.distance, b.distance); hb_swap (a.space, b.space); hb_swap (a.single_parent, b.single_parent); @@ -182,17 +269,17 @@ struct graph_t hb_swap (a.priority, b.priority); } - hb_hashmap_t + graph_result_t> position_to_index_map () const { hb_hashmap_t result; - result.alloc (obj.real_links.length); - for (const auto& l : obj.real_links) { + result.alloc (obj_.real_links.length); + for (const auto& l : obj_.real_links) { result.set (l.position, l.objidx); } - return result; + return graph_result_t>::from (std::move(result), ALLOCATION_FAILURE); } bool is_shared () const @@ -228,7 +315,7 @@ struct graph_t virtual_parents.reset (); } - void add_parent (unsigned parent_index, bool is_virtual) + graph_result_t add_parent (unsigned parent_index, bool is_virtual) { assert (parent_index != HB_GRAPH_INVALID); has_incoming_virtual_edges_ |= is_virtual; @@ -239,13 +326,13 @@ struct graph_t { single_parent = parent_index; incoming_edges_ = 1; - return; + return to_result(); } else if (single_parent != HB_GRAPH_INVALID) { assert (incoming_edges_ == 1); if (!parents.set (single_parent, 1)) - return; + return to_result (); single_parent = HB_GRAPH_INVALID; } @@ -257,6 +344,8 @@ struct graph_t } else if (parents.set (parent_index, 1)) incoming_edges_++; + + return to_result(); } void remove_parent (unsigned parent_index) @@ -289,24 +378,28 @@ struct graph_t } } - void remove_real_link (unsigned child_index, const void* offset) + void remove_real_link_unordered (unsigned link_array_index) { + obj_.real_links.remove_unordered (link_array_index); + } + + void remove_real_link_unordered (unsigned child_index, const void* offset) { - unsigned count = obj.real_links.length; + unsigned count = obj_.real_links.length; for (unsigned i = 0; i < count; i++) { - auto& link = obj.real_links.arrayZ[i]; + auto& link = obj_.real_links.arrayZ[i]; if (link.objidx != child_index) continue; - if ((obj.head + link.position) != offset) + if ((obj_.head + link.position) != offset) continue; - obj.real_links.remove_unordered (i); + obj_.real_links.remove_unordered (i); return; } } - void remap_parent (unsigned old_index, unsigned new_index) + graph_result_t remap_parent (unsigned old_index, unsigned new_index) { if (single_parent != HB_GRAPH_INVALID) { @@ -319,7 +412,7 @@ struct graph_t virtual_parents.add (new_index); } } - return; + return graph_result_t::from(virtual_parents, ALLOCATION_FAILURE); } const unsigned *pv; @@ -342,11 +435,13 @@ struct graph_t virtual_parents.del (old_index); virtual_parents.add (new_index); } + + return graph_result_t::from(virtual_parents, ALLOCATION_FAILURE); } bool is_leaf () const { - return !obj.real_links.length && !obj.virtual_links.length; + return !obj_.real_links.length && !obj_.virtual_links.length; } bool raise_priority () @@ -371,7 +466,7 @@ struct graph_t } size_t table_size () const { - return obj.tail - obj.head; + return obj_.tail - obj_.head; } int64_t modified_distance (unsigned order) const @@ -391,7 +486,7 @@ struct graph_t int64_t distance_modifier () const { if (!priority) return 0; - int64_t table_size = obj.tail - obj.head; + int64_t table_size = obj_.tail - obj_.head; if (priority == 1) return -table_size / 2; @@ -400,6 +495,14 @@ struct graph_t } private: + graph_result_t to_result() const { + if (unlikely ( + parents.in_error() || virtual_parents.in_error() || + obj_.real_links.in_error() || obj_.virtual_links.in_error())) + return Err(ALLOCATION_FAILURE); + return Ok(); + } + bool links_equal (const hb_vector_t& this_links, const hb_vector_t& other_links, const graph_t& graph, @@ -457,8 +560,6 @@ struct graph_t typename std::conditional::type vertex; typename std::conditional::type table; - operator bool () const - { return table && vertex; } }; /* @@ -469,29 +570,29 @@ struct graph_t * serializer */ template - graph_t (const T& objects) - : parents_invalid (true), - distance_invalid (true), - positions_invalid (true), - successful (true), - buffers () + static graph_result_t create (const T& objects) { - if (objects.length > HB_REPACKER_MAX_VERTICES) + if (unlikely (objects.length > HB_REPACKER_MAX_VERTICES)) { DEBUG_MSG (SUBSET_REPACK, nullptr, "constructing graph: num of objects %u exceeds HB_REPACKER_MAX_VERTICES.", objects.length); - check_success (false); - return; + return Err(LIMIT_EXCEEDED); } - num_roots_for_space_.push (1); + graph_t g; + g.num_roots_for_space_.push (1); + TRY (graph_result_t::from (g.num_roots_for_space_, ALLOCATION_FAILURE)); + bool removed_nil = false; - vertices_.alloc (objects.length); - ordering_.resize (objects.length); - ordering_scratch_.alloc (objects.length); + const unsigned count = objects.length; + g.vertices_.alloc (count); + g.ordering_.resize (count); + g.ordering_scratch_.alloc (count); + TRY (graph_result_t::from (g.vertices_, ALLOCATION_FAILURE)); + TRY (graph_result_t::from (g.ordering_, ALLOCATION_FAILURE)); + TRY (graph_result_t::from (g.ordering_scratch_, ALLOCATION_FAILURE)); - unsigned count = objects.length; unsigned order = objects.length; unsigned skip = 0; for (unsigned i = 0; i < count; i++) @@ -502,37 +603,57 @@ struct graph_t { removed_nil = true; order--; - ordering_.resize(objects.length - 1); + g.ordering_.resize (count - 1); skip++; continue; } - vertex_t* v = vertices_.push (); - if (check_success (!vertices_.in_error ())) - v->obj = *objects.arrayZ[i]; + hb_serialize_context_t::object_t obj (*objects.arrayZ[i]); + if (unlikely (obj.in_error ())) { + return Err(ALLOCATION_FAILURE); + } + vertex_t* v = g.vertices_.push (std::move (obj)); - check_success (v->link_positions_valid (count, removed_nil)); + TRY (v->link_positions_valid (count, removed_nil)); // To start we set the ordering to match the provided objects // list. Note: objects are provided to us in reverse order (ie. // the last object is the root). unsigned obj_idx = i - skip; - ordering_[--order] = obj_idx; + g.ordering_[--order] = obj_idx; if (!removed_nil) continue; // Fix indices to account for removed nil object. - for (auto& l : v->obj.all_links_writer ()) { + for (auto& l : v->all_links_writer ()) { l.objidx--; } } + + auto r = g.is_fully_connected(); + if (r.is_err() && r.error() == ORPHANED_NODES) { + g.print_orphaned_nodes (); + } + TRY(r); + + return g; } + graph_t (const graph_t&) = delete; + graph_t& operator = (const graph_t&) = delete; + graph_t (graph_t&&) = default; + graph_t& operator = (graph_t&&) = default; + ~graph_t () { for (char* b : buffers) hb_free (b); } +private: + graph_t () = default; + +public: + bool operator== (const graph_t& other) const { return root ().equals (root_idx(), other.root_idx(), other.root (), *this, other, 0); @@ -543,10 +664,10 @@ struct graph_t { const auto& v = vertices_[id]; printf("%u: %u [", id, (unsigned int)v.table_size()); - for (const auto &l : v.obj.real_links) { + for (const auto &l : v.obj().real_links) { printf("%u, ", l.objidx); } - for (const auto &l : v.obj.virtual_links) { + for (const auto &l : v.obj().virtual_links) { printf("v%u, ", l.objidx); } printf("]\n"); @@ -560,14 +681,6 @@ struct graph_t v.normalize (); } - bool in_error () const - { - return !successful || - vertices_.in_error () || - ordering_.in_error() || - num_roots_for_space_.in_error (); - } - const vertex_t& root () const { return vertices_[root_idx ()]; @@ -583,41 +696,38 @@ struct graph_t const hb_serialize_context_t::object_t& object (unsigned i) const { - return vertices_[i].obj; + return vertices_[i].obj(); } - bool add_buffer (char* buffer) + graph_result_t add_buffer (char* buffer) { buffers.push (buffer); - return !buffers.in_error (); + return graph_result_t::from (buffers, ALLOCATION_FAILURE); } /* * Adds a 16 bit link from parent_id to child_id */ template - void add_link (T* offset, - unsigned parent_id, - unsigned child_id) + graph_result_t add_link (T* offset, + unsigned parent_id, + unsigned child_id) { - if (unlikely (!check_success (parent_id < vertices_.length && child_id < vertices_.length))) - return; + if (unlikely (parent_id >= vertices_.length || child_id >= vertices_.length)) + return Err(OUT_OF_BOUNDS); auto& v = vertices_[parent_id]; - auto* link = v.obj.real_links.push (); - link->width = 2; - link->objidx = child_id; - link->position = (char*) offset - (char*) v.obj.head; - vertices_[child_id].add_parent (parent_id, false); + TRY(v.add_real_link(2, child_id, (char*) offset - (char*) v.obj().head)); + return vertices_[child_id].add_parent (parent_id, false); } /* * Generates a new topological sorting of graph ordered by the shortest * distance to each node if positions are marked as invalid. */ - void sort_shortest_distance_if_needed () + graph_result_t sort_shortest_distance_if_needed () { - if (!positions_invalid) return; - sort_shortest_distance (); + if (!positions_invalid) return Ok(); + return sort_shortest_distance (); } @@ -625,25 +735,30 @@ struct graph_t * Generates a new topological sorting of graph ordered by the shortest * distance to each node. */ - void sort_shortest_distance () + graph_result_t sort_shortest_distance () { positions_invalid = true; if (vertices_.length <= 1) { // Graph of 1 or less doesn't need sorting. - return; + return Ok(); } - update_distances (); + TRY (update_distances ()); hb_priority_queue_t queue; queue.alloc (vertices_.length); + TRY (graph_result_t::from (queue, ALLOCATION_FAILURE)); + hb_vector_t &new_ordering = ordering_scratch_; - if (unlikely (!check_success (new_ordering.resize (vertices_.length)))) return; + new_ordering.resize (vertices_.length); + TRY (graph_result_t::from (new_ordering, ALLOCATION_FAILURE)); hb_vector_t removed_edges; - if (unlikely (!check_success (removed_edges.resize (vertices_.length)))) return; - update_parents (); + removed_edges.resize (vertices_.length); + TRY (graph_result_t::from (removed_edges, ALLOCATION_FAILURE)); + + TRY (update_parents ()); queue.insert (root ().modified_distance (0), root_idx ()); unsigned order = 1; @@ -652,18 +767,18 @@ struct graph_t { unsigned next_id = queue.pop_minimum().second; - if (unlikely (!check_success(pos < new_ordering.length))) { + if (unlikely (pos >= new_ordering.length)) { // We are out of ids. Which means we've visited a node more than once. // This graph contains a cycle which is not allowed. DEBUG_MSG (SUBSET_REPACK, nullptr, "Invalid graph. Contains cycle."); - return; + return Err(CYCLE_DETECTED); } new_ordering[pos++] = next_id; const vertex_t& next = vertices_[next_id]; - for (const auto& link : next.obj.all_links ()) { - if (unlikely (!check_success (link.objidx < vertices_.length))) - continue; + for (const auto& link : next.obj().all_links ()) { + if (unlikely (link.objidx >= vertices_.length)) + return Err(OUT_OF_BOUNDS); removed_edges[link.objidx]++; const auto& v = vertices_[link.objidx]; if (!(v.incoming_edges () - removed_edges[link.objidx])) @@ -677,14 +792,17 @@ struct graph_t } } - check_success (!queue.in_error ()); - check_success (!new_ordering.in_error ()); + TRY (graph_result_t::from (queue, ALLOCATION_FAILURE)); + TRY (graph_result_t::from (new_ordering, ALLOCATION_FAILURE)); hb_swap (ordering_, new_ordering); - if (!check_success (pos == vertices_.length)) { + if (unlikely (pos != vertices_.length)) { print_orphaned_nodes (); + return Err(ORPHANED_NODES); } + + return Ok(); } /* @@ -692,7 +810,7 @@ struct graph_t * More specifically this looks for the top most 24 bit or 32 bit links in the graph. * Some special casing is done that is specific to the layout of GSUB/GPOS tables. */ - void find_space_roots (hb_set_t& visited, hb_set_t& roots) + graph_result_t find_space_roots (hb_set_t& visited, hb_set_t& roots) { unsigned root_index = root_idx (); for (unsigned i : ordering_) @@ -700,7 +818,7 @@ struct graph_t if (visited.has (i)) continue; // Only real links can form 32 bit spaces - for (auto& l : vertices_[i].obj.real_links) + for (const auto& l : vertices_[i].obj().real_links) { if (l.is_signed || l.width < 3) continue; @@ -717,59 +835,63 @@ struct graph_t // that extension subtables beneath a 24bit lookup become the spaces instead // of the offset to the lookup. hb_set_t sub_roots; - find_32bit_roots (l.objidx, sub_roots); + TRY (find_32bit_roots (l.objidx, sub_roots)); if (sub_roots) { for (unsigned sub_root_idx : sub_roots) { roots.add (sub_root_idx); - find_subgraph (sub_root_idx, visited); + TRY (find_subgraph (sub_root_idx, visited)); } continue; } } roots.add (l.objidx); - find_subgraph (l.objidx, visited); + TRY (find_subgraph (l.objidx, visited)); } } + + TRY(graph_result_t::from (visited, ALLOCATION_FAILURE)); + TRY(graph_result_t::from (roots, ALLOCATION_FAILURE)); + return Ok(); } template - const vertex_and_table_t as_table (unsigned parent, const void* offset, Ts... ds) + graph_result_t> as_table (unsigned parent, const void* offset, Ts... ds) { - return as_table_from_index (index_for_offset (parent, offset), std::forward(ds)...); + return TRY(as_table_from_index (TRY(index_for_offset (parent, offset)), std::forward(ds)...)); } template - vertex_and_table_t as_mutable_table (unsigned parent, const void* offset, Ts... ds) + graph_result_t> as_mutable_table (unsigned parent, const void* offset, Ts... ds) { - return as_table_from_index (mutable_index_for_offset (parent, offset), std::forward(ds)...); + auto idx = TRY(mutable_index_for_offset (parent, offset)); + return as_table_from_index (idx, std::forward(ds)...); } template - vertex_and_table_t as_table_from_index (unsigned index, Ts... ds) + graph_result_t> as_table_from_index (unsigned index, Ts... ds) { - if (index >= vertices_.length) - return vertex_and_table_t (); + if (unlikely (index >= vertices_.length)) + return Err(OUT_OF_BOUNDS); vertex_and_table_t r; r.vertex = (typename std::conditional::type) &vertices_[index]; - r.table = (typename std::conditional::type) r.vertex->obj.head; + r.table = r.vertex->template as::type> (); r.index = index; - if (!r.table) - return vertex_and_table_t (); - - if (!r.table->sanitize (*(r.vertex), std::forward(ds)...)) - return vertex_and_table_t (); + if (unlikely (!r.table)) + return Err(INVALID_ARGUMENT); + TRY(r.table->sanitize (*(r.vertex), std::forward(ds)...)); return r; } // Finds the object id of the object pointed to by the offset at 'offset' // within object[node_idx]. - unsigned index_for_offset (unsigned node_idx, const void* offset) const + graph_result_t index_for_offset (unsigned node_idx, const void* offset) const { + if (unlikely (node_idx >= vertices_.length)) return Err(OUT_OF_BOUNDS); const auto& node = object (node_idx); - if (offset < node.head || offset >= node.tail) return HB_GRAPH_INVALID; + if (unlikely (offset < node.head || offset >= node.tail)) return Err(OUT_OF_BOUNDS); unsigned count = node.real_links.length; for (unsigned i = 0; i < count; i++) @@ -778,19 +900,22 @@ struct graph_t const auto& link = node.real_links.arrayZ[i]; if (offset != node.head + link.position) continue; - return link.objidx; + return Ok(link.objidx); } - return HB_GRAPH_INVALID; + return Err(INVALID_ARGUMENT); } // Finds the object id of the object pointed to by the offset at 'offset' // within object[node_idx]. Ensures that the returned object is safe to mutate. // That is, if the original child object is shared by parents other than node_idx // it will be duplicated and the duplicate will be returned instead. - unsigned mutable_index_for_offset (unsigned node_idx, const void* offset) + graph_result_t mutable_index_for_offset (unsigned node_idx, const void* offset) { - unsigned child_idx = index_for_offset (node_idx, offset); + unsigned child_idx = TRY(index_for_offset (node_idx, offset)); + if (unlikely (child_idx >= vertices_.length)) + return Err(OUT_OF_BOUNDS); + auto& child = vertices_[child_idx]; for (unsigned p : child.parents_iter ()) { @@ -799,7 +924,7 @@ struct graph_t } } - return child_idx; + return Ok(child_idx); } @@ -808,46 +933,43 @@ struct graph_t * Currently, this is implemented specifically tailored to the structure of a GPOS/GSUB * (including with 24bit offsets) table. */ - bool assign_spaces () + graph_result_t assign_spaces () { - update_parents (); + TRY (update_parents ()); hb_set_t visited; hb_set_t roots; - find_space_roots (visited, roots); + TRY (find_space_roots (visited, roots)); // Mark everything not in the subgraphs of the roots as visited. This prevents // subgraphs from being connected via nodes not in those subgraphs. visited.invert (); - if (!roots) return false; + if (!roots) return Ok(false); while (roots) { uint32_t next = HB_SET_VALUE_INVALID; - if (unlikely (!check_success (!roots.in_error ()))) break; + TRY (graph_result_t::from (roots, ALLOCATION_FAILURE)); if (!roots.next (&next)) break; hb_set_t connected_roots; - find_connected_nodes (next, roots, visited, connected_roots); - if (unlikely (!check_success (!connected_roots.in_error ()))) break; + TRY (find_connected_nodes (next, roots, visited, connected_roots)); + TRY (graph_result_t::from (connected_roots, ALLOCATION_FAILURE)); - isolate_subgraph (connected_roots); - if (unlikely (!check_success (!connected_roots.in_error ()))) break; + TRY (isolate_subgraph (connected_roots)); + TRY (graph_result_t::from (connected_roots, ALLOCATION_FAILURE)); unsigned next_space = this->next_space (); - if (next_space >= HB_REPACKER_MAX_SPACES) + if (unlikely (next_space >= HB_REPACKER_MAX_SPACES)) { DEBUG_MSG (SUBSET_REPACK, nullptr, "num of spaces %u exceeds HB_REPACKER_MAX_SPACES.", next_space); - check_success (false); - break; + return Err(LIMIT_EXCEEDED); } num_roots_for_space_.push (0); - if (unlikely (!check_success (!num_roots_for_space_.in_error()))) { - break; - } + TRY(graph_result_t::from (num_roots_for_space_, ALLOCATION_FAILURE)); for (unsigned root : connected_roots) { @@ -862,7 +984,7 @@ struct graph_t // into the 32 bit space as needed, instead of using isolation. } - return true; + return Ok(true); } /* @@ -872,9 +994,9 @@ struct graph_t * * Indices stored in roots will be updated if any of the roots are duplicated to new indices. */ - bool isolate_subgraph (hb_set_t& roots) + graph_result_t isolate_subgraph (hb_set_t& roots) { - update_parents (); + TRY(update_parents ()); hb_map_t subgraph; // incoming edges to root_idx should be all 32 bit in length so we don't need to de-dup these @@ -882,11 +1004,12 @@ struct graph_t hb_set_t parents; for (unsigned root_idx : roots) { + if (unlikely (root_idx >= vertices_.length)) + return Err(OUT_OF_BOUNDS); subgraph.set (root_idx, wide_parents (root_idx, parents)); - find_subgraph (root_idx, subgraph); + TRY (find_subgraph (root_idx, subgraph)); } - if (subgraph.in_error ()) - return false; + TRY (graph_result_t::from (subgraph, ALLOCATION_FAILURE)); hb_map_t index_map; bool made_changes = false; @@ -900,15 +1023,14 @@ struct graph_t { // Only de-dup objects with incoming links from outside the subgraph. made_changes = true; - duplicate_subgraph (entry.first, index_map); + TRY (duplicate_subgraph (entry.first, index_map)); } } - if (in_error ()) - return false; + TRY (graph_result_t::from (index_map, ALLOCATION_FAILURE)); if (!made_changes) - return false; + return Ok(false); auto new_subgraph = + subgraph.keys () @@ -919,8 +1041,8 @@ struct graph_t }) ; - remap_obj_indices (index_map, new_subgraph); - remap_obj_indices (index_map, parents.iter (), true); + TRY(remap_obj_indices (index_map, new_subgraph)); + TRY(remap_obj_indices (index_map, parents.iter (), true)); // Update roots set with new indices as needed. for (auto next : roots) @@ -933,7 +1055,7 @@ struct graph_t } } - return true; + return Ok(true); } // BFS graph traversal starting at start_idx. @@ -950,22 +1072,22 @@ struct graph_t // This traversal does not use a visited set internally, it is the responsibility of visit_edge // to track and filter visited nodes if required for the particular traversal. template - void traverse_directed_bfs (unsigned start_idx, VisitEdgeFunc&& visit_edge) + graph_result_t traverse_directed_bfs (unsigned start_idx, VisitEdgeFunc&& visit_edge) { - if (unlikely (!check_success(start_idx < vertices_.length))) + if (unlikely (start_idx >= vertices_.length)) { DEBUG_MSG (SUBSET_REPACK, nullptr, "traverse_directed_bfs: unexpected start_idx out of bounds."); - return; + return Err(OUT_OF_BOUNDS); } // For performance we want to avoid allocating extra memory. So use the ordering_scratch_ // buffer to implement a queue for BFS. - if (unlikely (!check_success (ordering_scratch_.resize (vertices_.length)))) - return; + ordering_scratch_.resize (vertices_.length); + TRY (graph_result_t::from (ordering_scratch_, ALLOCATION_FAILURE)); if (!visit_edge (HB_CODEPOINT_INVALID, nullptr, start_idx, 0)) - return; + return Ok(); unsigned head = 0; unsigned tail = 0; @@ -981,34 +1103,35 @@ struct graph_t unsigned node_idx = queue[head++]; const auto& v = vertices_[node_idx]; - unsigned num_real = v.obj.real_links.length; - unsigned total_links = num_real + v.obj.virtual_links.length; + unsigned num_real = v.obj().real_links.length; + unsigned total_links = num_real + v.obj().virtual_links.length; for (unsigned i = 0; i < total_links; i++) { // vertices_ may have re-alloc'd inside an op() call, so reassign the v ref. const auto& v = vertices_[node_idx]; const auto& link = (i < num_real) - ? v.obj.real_links[i] - : v.obj.virtual_links[i - num_real]; + ? v.obj().real_links[i] + : v.obj().virtual_links[i - num_real]; unsigned child_idx = link.objidx; if (!visit_edge (node_idx, &link, child_idx, depth + 1)) continue; - if (unlikely (!check_success (tail < queue.length))) - return; + if (unlikely (tail >= queue.length)) + return Err(CYCLE_DETECTED); queue[tail++] = child_idx; } } depth++; } + return Ok(); } - void find_subgraph (unsigned node_idx, hb_map_t& subgraph) + graph_result_t find_subgraph (unsigned node_idx, hb_map_t& subgraph) { - traverse_directed_bfs (node_idx, [&] ( + return traverse_directed_bfs (node_idx, [&] ( unsigned parent, const hb_serialize_context_t::object_t::link_t* link, unsigned child, @@ -1025,9 +1148,9 @@ struct graph_t }); } - void find_subgraph (unsigned node_idx, hb_set_t& subgraph) + graph_result_t find_subgraph (unsigned node_idx, hb_set_t& subgraph) { - traverse_directed_bfs (node_idx, [&] ( + return traverse_directed_bfs (node_idx, [&] ( unsigned parent, const hb_serialize_context_t::object_t::link_t* link, unsigned child, @@ -1038,10 +1161,10 @@ struct graph_t }); } - size_t find_subgraph_size (unsigned node_idx, hb_set_t& subgraph, unsigned max_depth = HB_GRAPH_INVALID) + graph_result_t find_subgraph_size (unsigned node_idx, hb_set_t& subgraph, unsigned max_depth = HB_GRAPH_INVALID) { size_t size = 0; - traverse_directed_bfs (node_idx, [&] ( + TRY (traverse_directed_bfs (node_idx, [&] ( unsigned parent, const hb_serialize_context_t::object_t::link_t* link, unsigned child, @@ -1049,23 +1172,23 @@ struct graph_t if (subgraph.has (child)) return false; subgraph.add (child); - const auto& o = vertices_[child].obj; + const auto& o = vertices_[child].obj(); size += o.tail - o.head; return depth < max_depth; - }); - return size; + })); + return Ok(size); } /* * Finds the topmost children of 32bit offsets in the subgraph starting * at node_idx. Found indices are placed into 'found'. */ - void find_32bit_roots (unsigned node_idx, hb_set_t& found) + graph_result_t find_32bit_roots (unsigned node_idx, hb_set_t& found) { // Note: this specifically requires a BFS based traversal to ensure we don't recurse through // a node that is accessible via both 32bit and non-32 bit links. hb_set_t visited; - traverse_directed_bfs (node_idx, [&] ( + return traverse_directed_bfs (node_idx, [&] ( unsigned parent, const hb_serialize_context_t::object_t::link_t* link, unsigned child, @@ -1095,38 +1218,35 @@ struct graph_t * Returns the id of the child node that was moved. */ template - unsigned move_child (unsigned old_parent_idx, - const O* old_offset, - unsigned new_parent_idx, - const O* new_offset) + graph_result_t move_child (unsigned old_parent_idx, + const O* old_offset, + unsigned new_parent_idx, + const O* new_offset) { distance_invalid = true; positions_invalid = true; - if (unlikely (!check_success (old_parent_idx < vertices_.length && - new_parent_idx < vertices_.length))) - return HB_GRAPH_INVALID; + if (unlikely (old_parent_idx >= vertices_.length || + new_parent_idx >= vertices_.length)) + return Err(OUT_OF_BOUNDS); auto& old_v = vertices_[old_parent_idx]; auto& new_v = vertices_[new_parent_idx]; - unsigned child_id = index_for_offset (old_parent_idx, - old_offset); - if (unlikely (!check_success (child_id < vertices_.length))) - return HB_GRAPH_INVALID; + unsigned child_id = TRY(index_for_offset (old_parent_idx, + old_offset)); + if (unlikely (child_id >= vertices_.length)) + return Err(OUT_OF_BOUNDS); - auto* new_link = new_v.obj.real_links.push (); - new_link->width = O::static_size; - new_link->objidx = child_id; - new_link->position = (const char*) new_offset - (const char*) new_v.obj.head; + TRY(new_v.add_real_link(O::static_size, child_id, (const char*) new_offset - (const char*) new_v.obj().head)); auto& child = vertices_[child_id]; - child.add_parent (new_parent_idx, false); + TRY(child.add_parent (new_parent_idx, false)); - old_v.remove_real_link (child_id, old_offset); + old_v.remove_real_link_unordered (child_id, old_offset); child.remove_parent (old_parent_idx); - return child_id; + return Ok(child_id); } /* @@ -1136,12 +1256,16 @@ struct graph_t * parent starting at new_pos_start. */ template - void move_children (unsigned old_parent_idx, - unsigned old_pos_start, - unsigned old_pos_end, - unsigned new_parent_idx, - unsigned new_pos_start) + graph_result_t move_children (unsigned old_parent_idx, + unsigned old_pos_start, + unsigned old_pos_end, + unsigned new_parent_idx, + unsigned new_pos_start) { + if (unlikely (old_parent_idx >= vertices_.length || + new_parent_idx >= vertices_.length)) + return Err(OUT_OF_BOUNDS); + distance_invalid = true; positions_invalid = true; @@ -1149,28 +1273,29 @@ struct graph_t auto& new_v = vertices_[new_parent_idx]; hb_vector_t old_links; - for (const auto& l : old_v.obj.real_links) + for (const auto& l : old_v.obj().real_links) { if (l.position < old_pos_start || l.position >= old_pos_end) { - old_links.push(l); + old_links.push (l); continue; } unsigned array_pos = l.position - old_pos_start; unsigned child_id = l.objidx; - auto* new_link = new_v.obj.real_links.push (); - new_link->width = O::static_size; - new_link->objidx = child_id; - new_link->position = new_pos_start + array_pos; + if (unlikely (child_id >= vertices_.length)) + return Err(OUT_OF_BOUNDS); + + TRY(new_v.add_real_link(O::static_size, child_id, new_pos_start + array_pos)); auto& child = vertices_[child_id]; - child.add_parent (new_parent_idx, false); + TRY(child.add_parent (new_parent_idx, false)); child.remove_parent (old_parent_idx); } - old_v.obj.real_links = std::move (old_links); + TRY (graph_result_t::from (old_links, ALLOCATION_FAILURE)); + return old_v.set_real_links(std::move (old_links)); } /* @@ -1178,84 +1303,92 @@ struct graph_t * links. index_map is updated with mappings from old id to new id. If a duplication has already * been performed for a given index, then it will be skipped. */ - void duplicate_subgraph (unsigned node_idx, hb_map_t& index_map) + graph_result_t duplicate_subgraph (unsigned node_idx, hb_map_t& index_map) { - traverse_directed_bfs (node_idx, [&] ( + graph_result_t result = Ok(); + TRY (traverse_directed_bfs (node_idx, [&] ( unsigned parent, const hb_serialize_context_t::object_t::link_t* link, unsigned child, unsigned _) { - if (index_map.has (child)) return false; - unsigned clone_idx = duplicate (child); - if (!check_success (clone_idx != HB_GRAPH_INVALID)) return false; - index_map.set (child, clone_idx); + if (result.is_err () || index_map.has (child)) return false; + auto r = duplicate (child); + if (unlikely (r.is_err ())) + { + result = Err(r.error ()); + return false; + } + index_map.set (child, *r); return true; - }); + })); + + return graph_result_t::from(index_map, ALLOCATION_FAILURE); } /* * Creates a copy of node_idx and returns it's new index. */ - unsigned duplicate (unsigned node_idx, bool copy_table = false) + graph_result_t duplicate (unsigned node_idx, bool copy_table = false) { - if (vertices_.length >= HB_REPACKER_MAX_VERTICES) + if (unlikely (node_idx >= vertices_.length)) + return Err(OUT_OF_BOUNDS); + + if (unlikely (vertices_.length >= HB_REPACKER_MAX_VERTICES)) { DEBUG_MSG (SUBSET_REPACK, nullptr, "duplicating node: num of vertices %u exceeds HB_REPACKER_MAX_VERTICES.", vertices_.length); - check_success (false); - return HB_GRAPH_INVALID; + return Err(LIMIT_EXCEEDED); } positions_invalid = true; distance_invalid = true; auto* clone = vertices_.push (); + TRY (graph_result_t::from (vertices_, ALLOCATION_FAILURE)); + unsigned clone_idx = vertices_.length - 1; - ordering_.push(clone_idx); + ordering_.push (clone_idx); + TRY (graph_result_t::from (ordering_, ALLOCATION_FAILURE)); auto& child = vertices_[node_idx]; - if (vertices_.in_error () || ordering_.in_error()) { - return HB_GRAPH_INVALID; - } - unsigned table_size = child.obj.tail - child.obj.head; + unsigned table_size = child.obj().tail - child.obj().head; if (copy_table && table_size) { char* buffer = (char*) hb_malloc (table_size); - if (!check_success (buffer && add_buffer (buffer))) + if (unlikely (!buffer)) + return Err(ALLOCATION_FAILURE); + auto res = add_buffer (buffer); + if (unlikely (res.is_err ())) { hb_free (buffer); - return HB_GRAPH_INVALID; + return Err(res.error ()); } - hb_memcpy (buffer, child.obj.head, table_size); - clone->obj.head = buffer; - clone->obj.tail = buffer + table_size; + hb_memcpy (buffer, child.obj().head, table_size); + clone->set_buffer(buffer, buffer + table_size); } else { - clone->obj.head = child.obj.head; - clone->obj.tail = child.obj.tail; + clone->set_buffer(child.obj().head, child.obj().tail); } clone->distance = child.distance; clone->space = child.space; clone->reset_parents (); - for (const auto& l : child.obj.real_links) + for (const auto& l : child.obj().real_links) { - clone->obj.real_links.push (l); - vertices_[l.objidx].add_parent (clone_idx, false); - } - for (const auto& l : child.obj.virtual_links) - { - clone->obj.virtual_links.push (l); - vertices_[l.objidx].add_parent (clone_idx, true); + TRY(clone->add_real_link (l)); + TRY(vertices_[l.objidx].add_parent (clone_idx, false)); } - if (unlikely (!check_success (!clone->obj.real_links.in_error ()))) return HB_GRAPH_INVALID; - if (unlikely (!check_success (!clone->obj.virtual_links.in_error ()))) return HB_GRAPH_INVALID; + for (const auto& l : child.obj().virtual_links) + { + TRY(clone->add_virtual_link (l)); + TRY(vertices_[l.objidx].add_parent (clone_idx, true)); + } - return clone_idx; + return Ok(clone_idx); } /* @@ -1266,16 +1399,19 @@ struct graph_t * Returns the index of the newly created duplicate. * * If the child_idx only has incoming edges from parent_idx, - * duplication isn't possible and this will return -1. + * duplication isn't possible and this will return an error. */ - unsigned duplicate (unsigned parent_idx, unsigned child_idx, bool copy_table = false) + graph_result_t duplicate (unsigned parent_idx, unsigned child_idx, bool copy_table = false) { - update_parents (); + if (unlikely (parent_idx >= vertices_.length || child_idx >= vertices_.length)) + return Err(OUT_OF_BOUNDS); + + TRY (update_parents ()); const auto& child = vertices_[child_idx]; - unsigned links_to_child = child.incoming_edges_from_parent(parent_idx); + unsigned links_to_child = child.incoming_edges_from_parent (parent_idx); - if (child.incoming_edges () <= links_to_child || child.has_incoming_virtual_edges()) + if (unlikely (child.incoming_edges () <= links_to_child || child.has_incoming_virtual_edges ())) { // Can't duplicate this node, doing so would orphan the original one as all remaining links // to child are from parent. @@ -1286,30 +1422,29 @@ struct graph_t // to by virtual edges). DEBUG_MSG (SUBSET_REPACK, nullptr, " Not duplicating %u => %u", parent_idx, child_idx); - return HB_GRAPH_INVALID; + return Err(INVALID_ARGUMENT); } DEBUG_MSG (SUBSET_REPACK, nullptr, " Duplicating %u => %u", parent_idx, child_idx); - unsigned clone_idx = duplicate (child_idx, copy_table); - if (clone_idx == HB_GRAPH_INVALID) return HB_GRAPH_INVALID; + unsigned clone_idx = TRY (duplicate (child_idx, copy_table)); // duplicate shifts the root node idx, so if parent_idx was root update it. if (parent_idx == clone_idx) parent_idx++; auto& parent = vertices_[parent_idx]; unsigned count = 0; - unsigned num_real = parent.obj.real_links.length; - for (auto& l : parent.obj.all_links_writer ()) + unsigned num_real = parent.obj().real_links.length; + for (auto& l : parent.all_links_writer ()) { count++; if (l.objidx != child_idx) continue; - reassign_link (l, parent_idx, clone_idx, count > num_real); + TRY(reassign_link (l, parent_idx, clone_idx, count > num_real)); } - return clone_idx; + return Ok(clone_idx); } /* @@ -1321,25 +1456,29 @@ struct graph_t * * If the child_idx only has incoming edges from parents, * duplication isn't possible or duplication fails and this will - * return -1. + * return an error. */ - unsigned duplicate (const hb_set_t* parents, unsigned child_idx) + graph_result_t duplicate (const hb_set_t* parents, unsigned child_idx) { - if (parents->is_empty()) { - return HB_GRAPH_INVALID; - } + if (unlikely (!parents || parents->is_empty ())) + return Err(INVALID_ARGUMENT); - update_parents (); + if (unlikely (child_idx >= vertices_.length)) + return Err(OUT_OF_BOUNDS); + + TRY (update_parents ()); const auto& child = vertices_[child_idx]; unsigned links_to_child = 0; - unsigned last_parent = parents->get_max(); - unsigned first_parent = parents->get_min(); + unsigned last_parent = parents->get_max (); + unsigned first_parent = parents->get_min (); for (unsigned parent_idx : *parents) { - links_to_child += child.incoming_edges_from_parent(parent_idx); + if (unlikely (parent_idx >= vertices_.length)) + return Err(OUT_OF_BOUNDS); + links_to_child += child.incoming_edges_from_parent (parent_idx); } - if (child.incoming_edges () <= links_to_child || child.has_incoming_virtual_edges()) + if (unlikely (child.incoming_edges () <= links_to_child || child.has_incoming_virtual_edges ())) { // Can't duplicate this node, doing so would orphan the original one as all remaining links // to child are from parent. @@ -1349,65 +1488,61 @@ struct graph_t // with virtual edges may end up orphaned by duplication (ie. where one copy is only pointed // to by virtual edges). DEBUG_MSG (SUBSET_REPACK, nullptr, " Not duplicating %u, ..., %u => %u", first_parent, last_parent, child_idx); - return HB_GRAPH_INVALID; + return Err(INVALID_ARGUMENT); } DEBUG_MSG (SUBSET_REPACK, nullptr, " Duplicating %u, ..., %u => %u", first_parent, last_parent, child_idx); - unsigned clone_idx = duplicate (child_idx); - if (clone_idx == HB_GRAPH_INVALID) return HB_GRAPH_INVALID; + unsigned clone_idx = TRY (duplicate (child_idx)); for (unsigned parent_idx : *parents) { // duplicate shifts the root node idx, so if parent_idx was root update it. if (parent_idx == clone_idx) parent_idx++; auto& parent = vertices_[parent_idx]; unsigned count = 0; - unsigned num_real = parent.obj.real_links.length; - for (auto& l : parent.obj.all_links_writer ()) + unsigned num_real = parent.obj().real_links.length; + for (auto& l : parent.all_links_writer ()) { count++; if (l.objidx != child_idx) continue; - reassign_link (l, parent_idx, clone_idx, count > num_real); + TRY(reassign_link (l, parent_idx, clone_idx, count > num_real)); } } - return clone_idx; + return Ok(clone_idx); } /* * Adds a new node to the graph, not connected to anything. */ - unsigned new_node (char* head, char* tail) + graph_result_t new_node (char* head, char* tail) { - if (vertices_.length >= HB_REPACKER_MAX_VERTICES) + if (unlikely (vertices_.length >= HB_REPACKER_MAX_VERTICES)) { DEBUG_MSG (SUBSET_REPACK, nullptr, "creating new node: num of vertices %u exceeds HB_REPACKER_MAX_VERTICES.", vertices_.length); - check_success (false); - return HB_GRAPH_INVALID; + return Err(LIMIT_EXCEEDED); } positions_invalid = true; distance_invalid = true; auto* clone = vertices_.push (); + TRY (graph_result_t::from (vertices_, ALLOCATION_FAILURE)); + unsigned clone_idx = vertices_.length - 1; - ordering_.push(clone_idx); + ordering_.push (clone_idx); + TRY (graph_result_t::from (ordering_, ALLOCATION_FAILURE)); - if (vertices_.in_error () || ordering_.in_error()) { - return HB_GRAPH_INVALID; - } - - clone->obj.head = head; - clone->obj.tail = tail; + clone->set_buffer (head, tail); clone->distance = 0; clone->space = 0; - return clone_idx; + return Ok(clone_idx); } /* @@ -1416,59 +1551,61 @@ struct graph_t * Returns the index of the newly created child. * */ - unsigned remap_child (unsigned parent_idx, unsigned old_child_idx) + graph_result_t remap_child (unsigned parent_idx, unsigned old_child_idx) { - unsigned new_child_idx = duplicate (old_child_idx); - if (new_child_idx == HB_GRAPH_INVALID) return HB_GRAPH_INVALID; + if (unlikely (parent_idx >= vertices_.length || old_child_idx >= vertices_.length)) + return Err(OUT_OF_BOUNDS); + + unsigned new_child_idx = TRY (duplicate (old_child_idx)); auto& parent = vertices_[parent_idx]; - for (auto& l : parent.obj.real_links) + for (auto& l : parent.real_links_writer ()) { if (l.objidx != old_child_idx) continue; - reassign_link (l, parent_idx, new_child_idx, false); + TRY(reassign_link (l, parent_idx, new_child_idx, false)); } - for (auto& l : parent.obj.virtual_links) + for (auto& l : parent.virtual_links_writer ()) { if (l.objidx != old_child_idx) continue; - reassign_link (l, parent_idx, new_child_idx, true); + TRY(reassign_link (l, parent_idx, new_child_idx, true)); } - return new_child_idx; + return Ok(new_child_idx); } /* * Raises the sorting priority of all children. */ - bool raise_childrens_priority (unsigned parent_idx) + graph_result_t raise_childrens_priority (unsigned parent_idx) { DEBUG_MSG (SUBSET_REPACK, nullptr, " Raising priority of all children of %u", parent_idx); // This operation doesn't change ordering until a sort is run, so no need // to invalidate positions. It does not change graph structure so no need // to update distances or edge counts. - auto& parent = vertices_[parent_idx].obj; + if (unlikely (parent_idx >= vertices_.length)) return Err(OUT_OF_BOUNDS); bool made_change = false; - for (auto& l : parent.all_links_writer ()) + for (auto& l : vertices_[parent_idx].all_links_writer ()) made_change |= vertices_[l.objidx].raise_priority (); - return made_change; + return Ok(made_change); } - bool is_fully_connected () + graph_result_t is_fully_connected () { - update_parents(); + TRY(update_parents()); - if (root().incoming_edges ()) + if (unlikely (root().incoming_edges ())) // Root cannot have parents. - return false; + return Err(ORPHANED_NODES); for (unsigned i = 0; i < root_idx (); i++) { - if (!vertices_[i].incoming_edges ()) - return false; + if (unlikely (!vertices_[i].incoming_edges ())) + return Err(ORPHANED_NODES); } - return true; + return Ok(); } #if 0 @@ -1521,27 +1658,6 @@ struct graph_t } #endif - void print_orphaned_nodes () - { - if (!DEBUG_ENABLED(SUBSET_REPACK)) return; - - DEBUG_MSG (SUBSET_REPACK, nullptr, "Graph is not fully connected."); - - parents_invalid = true; - update_parents(); - - if (root().incoming_edges ()) { - DEBUG_MSG (SUBSET_REPACK, nullptr, "Root node has incoming edges."); - } - - for (unsigned i = 0; i < root_idx (); i++) - { - const auto& v = vertices_[i]; - if (!v.incoming_edges ()) - DEBUG_MSG (SUBSET_REPACK, nullptr, "Node %u is orphaned.", i); - } - } - unsigned num_roots_for_space (unsigned space) const { return num_roots_for_space_[space]; @@ -1552,20 +1668,22 @@ struct graph_t return num_roots_for_space_.length; } - void move_to_new_space (const hb_set_t& indices) + graph_result_t move_to_new_space (const hb_set_t& indices) { - if (num_roots_for_space_.length >= HB_REPACKER_MAX_SPACES) + if (unlikely (num_roots_for_space_.length >= HB_REPACKER_MAX_SPACES)) { DEBUG_MSG (SUBSET_REPACK, nullptr, "move_to_new_space: num of spaces %u exceeds HB_REPACKER_MAX_SPACES.", num_roots_for_space_.length); - check_success (false); - return; + return Err(LIMIT_EXCEEDED); } num_roots_for_space_.push (0); + TRY (graph_result_t::from (num_roots_for_space_, ALLOCATION_FAILURE)); unsigned new_space = num_roots_for_space_.length - 1; for (unsigned index : indices) { + if (unlikely (index >= vertices_.length)) + return Err(OUT_OF_BOUNDS); auto& node = vertices_[index]; num_roots_for_space_[node.space] = num_roots_for_space_[node.space] - 1; num_roots_for_space_[new_space] = num_roots_for_space_[new_space] + 1; @@ -1573,39 +1691,38 @@ struct graph_t distance_invalid = true; positions_invalid = true; } + return Ok(); } unsigned space_for (unsigned index, unsigned* root = nullptr) const { - loop: - assert (index < vertices_.length); - const auto& node = vertices_[index]; - if (node.space) + while (true) { - if (root != nullptr) - *root = index; - return node.space; - } + assert (index < vertices_.length); + const auto& node = vertices_[index]; + if (node.space) + { + if (root != nullptr) + *root = index; + return node.space; + } - if (!node.incoming_edges ()) - { - if (root) - *root = index; - return 0; - } + if (!node.incoming_edges ()) + { + if (root) + *root = index; + return 0; + } - index = *node.parents_iter (); - goto loop; + index = *node.parents_iter (); + } } - void err_other_error () { this->successful = false; } - size_t total_size_in_bytes () const { size_t total_size = 0; unsigned count = vertices_.length; for (unsigned i = 0; i < count; i++) { - const auto& obj = vertices_.arrayZ[i].obj; - size_t size = obj.tail - obj.head; + size_t size = vertices_.arrayZ[i].table_size (); total_size += size; } return total_size; @@ -1614,6 +1731,27 @@ struct graph_t private: + void print_orphaned_nodes () + { + if (!DEBUG_ENABLED(SUBSET_REPACK)) return; + + DEBUG_MSG (SUBSET_REPACK, nullptr, "Graph is not fully connected."); + + parents_invalid = true; + (void) update_parents(); + + if (root().incoming_edges ()) { + DEBUG_MSG (SUBSET_REPACK, nullptr, "Root node has incoming edges."); + } + + for (unsigned i = 0; i < vertices_.length; i++) + { + const auto& v = vertices_[i]; + if (!v.incoming_edges ()) + DEBUG_MSG (SUBSET_REPACK, nullptr, "Node %u is orphaned.", i); + } + } + /* * Returns the numbers of incoming edges that are 24 or 32 bits wide. */ @@ -1623,7 +1761,7 @@ struct graph_t for (unsigned p : vertices_[node_idx].parents_iter ()) { // Only real links can be wide - for (const auto& l : vertices_[p].obj.real_links) + for (const auto& l : vertices_[p].obj().real_links) { if (l.objidx == node_idx && (l.width == 3 || l.width == 4) @@ -1637,16 +1775,13 @@ struct graph_t return count; } - bool check_success (bool success) - { return this->successful && (success || ((void) err_other_error (), false)); } - public: /* * Creates a map from objid to # of incoming edges. */ - void update_parents () + graph_result_t update_parents () { - if (!parents_invalid) return; + if (!parents_invalid) return Ok(); unsigned count = vertices_.length; @@ -1655,25 +1790,21 @@ struct graph_t for (unsigned p = 0; p < count; p++) { - for (auto& l : vertices_.arrayZ[p].obj.real_links) + for (const auto& l : vertices_.arrayZ[p].obj().real_links) { - if (unlikely (l.objidx >= count)) { check_success (false); continue; } - vertices_[l.objidx].add_parent (p, false); + if (unlikely (l.objidx >= count)) return Err(INVALID_ARGUMENT); + TRY(vertices_[l.objidx].add_parent (p, false)); } - for (auto& l : vertices_.arrayZ[p].obj.virtual_links) + for (const auto& l : vertices_.arrayZ[p].obj().virtual_links) { - if (unlikely (l.objidx >= count)) { check_success (false); continue; } - vertices_[l.objidx].add_parent (p, true); + if (unlikely (l.objidx >= count)) return Err(INVALID_ARGUMENT); + TRY(vertices_[l.objidx].add_parent (p, true)); } } - for (unsigned i = 0; i < count; i++) - // parents arrays must be accurate or downstream operations like cycle detection - // and sorting won't work correctly. - check_success (!vertices_.arrayZ[i].in_error ()); - parents_invalid = false; + return Ok(); } /* @@ -1688,7 +1819,7 @@ struct graph_t { auto& v = vertices_[i]; v.start = current_pos; - current_pos += v.obj.tail - v.obj.head; + current_pos += v.obj().tail - v.obj().head; v.end = current_pos; } @@ -1699,9 +1830,9 @@ struct graph_t * Finds the distance to each object in the graph * from the initial node. */ - void update_distances () + graph_result_t update_distances () { - if (!distance_invalid) return; + if (!distance_invalid) return Ok(); // Uses Dijkstra's algorithm to find all of the shortest distances. // https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm @@ -1721,11 +1852,11 @@ struct graph_t hb_priority_queue_t queue; queue.alloc (count); queue.insert (0, root_idx ()); + TRY (graph_result_t::from (queue, ALLOCATION_FAILURE)); hb_vector_t visited; - if (unlikely (!check_success (visited.resize (vertices_.length)))) { - return; - } + visited.resize (vertices_.length); + TRY (graph_result_t::from (visited, ALLOCATION_FAILURE)); while (!queue.in_error () && !queue.is_empty ()) { @@ -1735,15 +1866,15 @@ struct graph_t int64_t next_distance = next.distance; visited[next_idx] = true; - for (const auto& link : next.obj.all_links ()) + for (const auto& link : next.obj().all_links ()) { - if (unlikely (!check_success (link.objidx < vertices_.length))) - continue; + if (unlikely (link.objidx >= vertices_.length)) + return Err(OUT_OF_BOUNDS); if (visited[link.objidx]) continue; auto& child_v = vertices_.arrayZ[link.objidx]; - const auto& child = child_v.obj; + const auto& child = child_v.obj (); unsigned link_width = link.width ? link.width : 4; // treat virtual offsets as 32 bits wide int64_t child_weight = (child.tail - child.head) + ((int64_t) 1 << (link_width * 8)) * (child_v.space + 1); @@ -1757,14 +1888,15 @@ struct graph_t } } - check_success (!queue.in_error ()); - if (!check_success (queue.is_empty ())) + TRY (graph_result_t::from (queue, ALLOCATION_FAILURE)); + if (unlikely (!queue.is_empty ())) { print_orphaned_nodes (); - return; + return Err(ORPHANED_NODES); } distance_invalid = false; + return Ok(); } private: @@ -1772,7 +1904,7 @@ struct graph_t * Updates a link in the graph to point to a different object. Corrects the * parents vector on the previous and new child nodes. */ - void reassign_link (hb_serialize_context_t::object_t::link_t& link, + graph_result_t reassign_link (hb_serialize_context_t::object_t::link_t& link, unsigned parent_idx, unsigned new_idx, bool is_virtual) @@ -1780,33 +1912,34 @@ struct graph_t unsigned old_idx = link.objidx; link.objidx = new_idx; vertices_[old_idx].remove_parent (parent_idx); - vertices_[new_idx].add_parent (parent_idx, is_virtual); + return vertices_[new_idx].add_parent (parent_idx, is_virtual); } /* * Updates all objidx's in all links using the provided mapping. Corrects incoming edge counts. */ template - void remap_obj_indices (const hb_map_t& id_map, - Iterator subgraph, - bool only_wide = false) + graph_result_t remap_obj_indices (const hb_map_t& id_map, + Iterator subgraph, + bool only_wide = false) { - if (!id_map) return; + if (!id_map) return Ok(); for (unsigned i : subgraph) { - auto& obj = vertices_[i].obj; - unsigned num_real = obj.real_links.length; + auto& vertex = vertices_[i]; + unsigned num_real = vertex.obj().real_links.length; unsigned count = 0; - for (auto& link : obj.all_links_writer ()) + for (auto& link : vertex.all_links_writer ()) { count++; const uint32_t *v; if (!id_map.has (link.objidx, &v)) continue; if (only_wide && (link.is_signed || (link.width != 4 && link.width != 3))) continue; - reassign_link (link, i, *v, count > num_real); + TRY(reassign_link (link, i, *v, count > num_real)); } } + return Ok(); } /* @@ -1816,27 +1949,29 @@ struct graph_t * Connected targets will be added to connected and removed from targets. All visited nodes * will be added to visited. */ - void find_connected_nodes (unsigned start_idx, - hb_set_t& targets, - hb_set_t& visited, - hb_set_t& connected) + graph_result_t find_connected_nodes (unsigned start_idx, + hb_set_t& targets, + hb_set_t& visited, + hb_set_t& connected) { - if (unlikely (!check_success (!visited.in_error ()))) return; - if (visited.has (start_idx)) return; - if (unlikely (!check_success(start_idx < vertices_.length))) + TRY (graph_result_t::from (visited, ALLOCATION_FAILURE)); + if (visited.has (start_idx)) return Ok(); + if (unlikely (start_idx >= vertices_.length)) { DEBUG_MSG (SUBSET_REPACK, nullptr, "find_connected_nodes: unexpected start_idx out of bounds."); - return; + return Err(OUT_OF_BOUNDS); } // For performance we want to avoid allocating extra memory. So use the ordering_scratch_ // buffer to implement a stack for DFS. - if (unlikely (!check_success (ordering_scratch_.resize (vertices_.length)))) return; + ordering_scratch_.resize (vertices_.length); + TRY (graph_result_t::from (ordering_scratch_, ALLOCATION_FAILURE)); auto& stack = ordering_scratch_; unsigned stack_len = 0; + graph_result_t res = Ok(); auto handle_node = [&] (unsigned node_idx) { visited.add (node_idx); if (targets.has (node_idx)) { @@ -1844,12 +1979,16 @@ struct graph_t connected.add (node_idx); } - if (unlikely (!check_success (stack_len < stack.length))) return false; + if (unlikely (stack_len >= stack.length)) + { + res = Err(CYCLE_DETECTED); + return false; + } stack[stack_len++] = node_idx; return true; }; - if (!handle_node (start_idx)) return; + if (!handle_node (start_idx)) return res; while (stack_len > 0) { @@ -1857,19 +1996,24 @@ struct graph_t const auto& v = vertices_[node_idx]; // Graph is treated as undirected so search children and parents of node_idx - for (const auto& l : v.obj.all_links ()) + for (const auto& l : v.obj().all_links ()) { unsigned child_idx = l.objidx; if (visited.has (child_idx)) continue; - if (!handle_node (child_idx)) return; + if (!handle_node (child_idx)) return res; } for (unsigned parent_idx : v.parents_iter ()) { if (visited.has (parent_idx)) continue; - if (!handle_node (parent_idx)) return; + if (!handle_node (parent_idx)) return res; } } + + TRY (graph_result_t::from (visited, ALLOCATION_FAILURE)); + TRY (graph_result_t::from (connected, ALLOCATION_FAILURE)); + + return Ok(); } public: @@ -1886,10 +2030,9 @@ struct graph_t hb_vector_t ordering_scratch_; private: - bool parents_invalid; - bool distance_invalid; - bool positions_invalid; - bool successful; + bool parents_invalid = true; + bool distance_invalid = true; + bool positions_invalid = true; hb_vector_t num_roots_for_space_; hb_vector_t buffers; }; diff --git a/src/graph/gsubgpos-context.cc b/src/graph/gsubgpos-context.cc index 443281363..63d6ee0ce 100644 --- a/src/graph/gsubgpos-context.cc +++ b/src/graph/gsubgpos-context.cc @@ -28,34 +28,41 @@ namespace graph { +graph_result_t gsubgpos_graph_context_t::create (hb_tag_t table_tag_, + graph_t& graph_) +{ + gsubgpos_graph_context_t context (table_tag_, graph_); + + if (unlikely (table_tag_ != HB_OT_TAG_GPOS + && table_tag_ != HB_OT_TAG_GSUB)) + return Err(INVALID_ARGUMENT); + + const GSTAR* gstar = TRY(graph::GSTAR::graph_to_gstar (context.graph)); + TRY(gstar->find_lookups (context.graph, context.lookups)); + context.lookup_list_index = TRY(gstar->get_lookup_list_index (context.graph)); + + return context; +} + gsubgpos_graph_context_t::gsubgpos_graph_context_t (hb_tag_t table_tag_, graph_t& graph_) : table_tag (table_tag_), graph (graph_), lookup_list_index (0), lookups () -{ - if (table_tag_ != HB_OT_TAG_GPOS - && table_tag_ != HB_OT_TAG_GSUB) - return; +{} - GSTAR* gstar = graph::GSTAR::graph_to_gstar (graph_); - if (gstar) { - gstar->find_lookups (graph, lookups); - lookup_list_index = gstar->get_lookup_list_index (graph_); - } -} - -unsigned gsubgpos_graph_context_t::create_node (unsigned size) +graph_result_t gsubgpos_graph_context_t::create_node (unsigned size) { char* buffer = (char*) hb_calloc (1, size); - if (!buffer) - return HB_GRAPH_INVALID; + if (unlikely (!buffer)) + return Err(ALLOCATION_FAILURE); - if (!add_buffer (buffer)) { + auto res = add_buffer (buffer); + if (unlikely (!res.is_ok ())) { // Allocation did not get stored for freeing later. hb_free (buffer); - return HB_GRAPH_INVALID; + return Err(res.error ()); } return graph.new_node (buffer, buffer + size); diff --git a/src/graph/gsubgpos-context.hh b/src/graph/gsubgpos-context.hh index 8969d0078..947669f87 100644 --- a/src/graph/gsubgpos-context.hh +++ b/src/graph/gsubgpos-context.hh @@ -36,6 +36,9 @@ struct Lookup; struct gsubgpos_graph_context_t { + HB_INTERNAL static graph_result_t create (hb_tag_t table_tag_, + graph_t& graph_); + hb_tag_t table_tag; graph_t& graph; unsigned lookup_list_index; @@ -43,17 +46,18 @@ struct gsubgpos_graph_context_t hb_hashmap_t subtable_to_extension; hb_hashmap_t> split_subtables; - HB_INTERNAL gsubgpos_graph_context_t (hb_tag_t table_tag_, - graph_t& graph_); - HB_INTERNAL unsigned create_node (unsigned size); + HB_INTERNAL graph_result_t create_node (unsigned size); - bool add_buffer (char* buffer) + graph_result_t add_buffer (char* buffer) { return graph.add_buffer (buffer); } private: + HB_INTERNAL gsubgpos_graph_context_t (hb_tag_t table_tag_, + graph_t& graph_); + HB_INTERNAL unsigned num_non_ext_subtables (); }; diff --git a/src/graph/gsubgpos-graph.hh b/src/graph/gsubgpos-graph.hh index 9eedbe7d9..b74dcb768 100644 --- a/src/graph/gsubgpos-graph.hh +++ b/src/graph/gsubgpos-graph.hh @@ -50,10 +50,12 @@ struct ExtensionFormat1 : public OT::ExtensionFormat1 this->extensionOffset = 0; } - bool sanitize (const graph_t::vertex_t& vertex) const + graph_result_t sanitize (const graph_t::vertex_t& vertex) const { - size_t vertex_len = vertex.obj.tail - vertex.obj.head; - return vertex_len >= OT::ExtensionFormat1::static_size; + size_t vertex_len = vertex.table_size (); + if (unlikely (vertex_len < OT::ExtensionFormat1::static_size)) + return Err(SANITIZE_FAILURE); + return Ok(); } unsigned get_lookup_type () const @@ -61,7 +63,7 @@ struct ExtensionFormat1 : public OT::ExtensionFormat1 return this->extensionLookupType; } - unsigned get_subtable_index (graph_t& graph, unsigned this_index) const + graph_result_t get_subtable_index (graph_t& graph, unsigned this_index) const { return graph.index_for_offset (this_index, &this->extensionOffset); } @@ -74,12 +76,13 @@ struct Lookup : public OT::Lookup return subTable.len; } - bool sanitize (const graph_t::vertex_t& vertex) const + graph_result_t sanitize (const graph_t::vertex_t& vertex) const { - size_t vertex_len = vertex.obj.tail - vertex.obj.head; - if (vertex_len < OT::Lookup::min_size) return false; + size_t vertex_len = vertex.table_size (); + if (unlikely (vertex_len < OT::Lookup::min_size)) return Err(SANITIZE_FAILURE); hb_barrier (); - return vertex_len >= this->get_size (); + if (unlikely (vertex_len < this->get_size ())) return Err(SANITIZE_FAILURE); + return Ok(); } bool is_extension (hb_tag_t table_tag) const @@ -93,15 +96,15 @@ struct Lookup : public OT::Lookup return flag & 0x0010u; } - bool make_extension (gsubgpos_graph_context_t& c, - unsigned this_index) + graph_result_t make_extension (gsubgpos_graph_context_t& c, + unsigned this_index) { unsigned type = lookupType; unsigned ext_type = extension_type (c.table_tag); if (!ext_type || is_extension (c.table_tag)) { // NOOP - return true; + return Ok(); } DEBUG_MSG (SUBSET_REPACK, nullptr, @@ -111,42 +114,43 @@ struct Lookup : public OT::Lookup for (unsigned i = 0; i < subTable.len; i++) { - unsigned subtable_index = c.graph.index_for_offset (this_index, &subTable[i]); - if (!make_subtable_extension (c, + unsigned subtable_index = TRY(c.graph.index_for_offset (this_index, &subTable[i])); + TRY (make_subtable_extension (c, this_index, - subtable_index)) - return false; + subtable_index)); } lookupType = ext_type; - return true; + return Ok(); } - bool split_subtables_if_needed (gsubgpos_graph_context_t& c, - unsigned this_index) + graph_result_t split_subtables_if_needed (gsubgpos_graph_context_t& c, + unsigned this_index) { unsigned type = lookupType; bool is_ext = is_extension (c.table_tag); if (c.table_tag != HB_OT_TAG_GPOS && c.table_tag != HB_OT_TAG_GSUB) - return true; + return Ok(); if (!is_ext && !is_supported_gpos_type(type, c) && !is_supported_gsub_type(type, c)) - return true; + return Ok(); hb_vector_t>> all_new_subtables; for (unsigned i = 0; i < subTable.len; i++) { - unsigned subtable_index = c.graph.index_for_offset (this_index, &subTable[i]); + auto idx_res = c.graph.index_for_offset (this_index, &subTable[i]); + if (!idx_res.is_ok ()) continue; + unsigned subtable_index = *idx_res; if (is_ext) { unsigned ext_subtable_index = subtable_index; ExtensionFormat1* extension = (ExtensionFormat1*) c.graph.object (ext_subtable_index).head; - if (!extension || !extension->sanitize (c.graph.vertices_[ext_subtable_index])) + if (!extension || !extension->sanitize (c.graph.vertices_[ext_subtable_index]).is_ok ()) continue; - subtable_index = extension->get_subtable_index (c.graph, ext_subtable_index); + subtable_index = TRY(extension->get_subtable_index (c.graph, ext_subtable_index)); type = extension->get_lookup_type (); if (!is_supported_gpos_type(type, c) && !is_supported_gsub_type(type, c)) continue; @@ -158,6 +162,7 @@ struct Lookup : public OT::Lookup if (split_result->length == 0) continue; all_new_subtables.push (hb_pair(i, *split_result)); + TRY (graph_result_t::from (all_new_subtables, ALLOCATION_FAILURE)); } else { @@ -167,9 +172,9 @@ struct Lookup : public OT::Lookup switch (type) { case 2: - new_sub_tables = split_subtable (c, subtable_index); break; + new_sub_tables = TRY (split_subtable (c, subtable_index)); break; case 4: - new_sub_tables = split_subtable (c, subtable_index); break; + new_sub_tables = TRY (split_subtable (c, subtable_index)); break; default: break; } @@ -177,42 +182,43 @@ struct Lookup : public OT::Lookup switch (type) { case 4: - new_sub_tables = split_subtable (c, subtable_index); break; + new_sub_tables = TRY (split_subtable (c, subtable_index)); break; default: break; } } - if (new_sub_tables.in_error ()) return false; - c.split_subtables.set (subtable_index, new_sub_tables); - if (new_sub_tables) + TRY (graph_result_t::from (c.split_subtables, ALLOCATION_FAILURE)); + if (new_sub_tables) { all_new_subtables.push (hb_pair (i, std::move (new_sub_tables))); + TRY (graph_result_t::from (all_new_subtables, ALLOCATION_FAILURE)); + } } } if (all_new_subtables) { - return add_sub_tables (c, this_index, type, all_new_subtables); + TRY (add_sub_tables (c, this_index, type, all_new_subtables)); } - return true; + return Ok(); } template - hb_vector_t split_subtable (gsubgpos_graph_context_t& c, - unsigned objidx) + graph_result_t> split_subtable (gsubgpos_graph_context_t& c, + unsigned objidx) { T* sub_table = (T*) c.graph.object (objidx).head; - if (!sub_table || !sub_table->sanitize (c.graph.vertices_[objidx])) - return hb_vector_t (); + if (!sub_table || !sub_table->sanitize (c.graph.vertices_[objidx]).is_ok ()) + return Ok(hb_vector_t ()); return sub_table->split_subtables (c, objidx); } - bool add_sub_tables (gsubgpos_graph_context_t& c, - unsigned this_index, - unsigned type, - const hb_vector_t>>& subtable_ids) + graph_result_t add_sub_tables (gsubgpos_graph_context_t& c, + unsigned this_index, + unsigned type, + const hb_vector_t>>& subtable_ids) { bool is_ext = is_extension (c.table_tag); auto* v = &c.graph.vertices_[this_index]; @@ -225,19 +231,19 @@ struct Lookup : public OT::Lookup size_t new_size = v->table_size () + new_subtable_count * OT::Offset16::static_size; char* buffer = (char*) hb_calloc (1, new_size); - if (!buffer) return false; - if (!c.add_buffer (buffer)) + if (unlikely (!buffer)) return Err(ALLOCATION_FAILURE); + auto res = c.add_buffer (buffer); + if (unlikely (!res.is_ok ())) { hb_free (buffer); - return false; + return res; } - hb_memcpy (buffer, v->obj.head, v->table_size()); + hb_memcpy (buffer, v->obj ().head, v->table_size()); if (use_mark_filtering_set ()) - hb_memcpy (buffer + new_size - 2, v->obj.tail - 2, 2); + hb_memcpy (buffer + new_size - 2, v->obj ().tail - 2, 2); - v->obj.head = buffer; - v->obj.tail = buffer + new_size; + v->set_buffer (buffer, buffer + new_size); Lookup* new_lookup = (Lookup*) buffer; @@ -252,29 +258,27 @@ struct Lookup : public OT::Lookup { if (is_ext) { - unsigned ext_id = create_extension_subtable (c, subtable_id, type); - c.graph.vertices_[subtable_id].add_parent (ext_id, false); + unsigned ext_id = TRY (create_extension_subtable (c, subtable_id, type)); + TRY(c.graph.vertices_[subtable_id].add_parent (ext_id, false)); subtable_id = ext_id; // the reference to v may have changed on adding a node, so reassign it. v = &c.graph.vertices_[this_index]; } - auto* link = v->obj.real_links.push (); - link->width = 2; - link->objidx = subtable_id; - link->position = (char*) &new_lookup->subTable[offset_index++] - - (char*) new_lookup; - c.graph.vertices_[subtable_id].add_parent (this_index, false); + TRY(v->add_real_link(2, subtable_id, + (char*) &new_lookup->subTable[offset_index++] - (char*) new_lookup)); + TRY(c.graph.vertices_[subtable_id].add_parent (this_index, false)); } } // Repacker sort order depends on link order, which we've messed up so resort it. - v->obj.real_links.qsort (); + v->sort_real_links (); // The head location of the lookup has changed, invalidating the lookups map entry // in the context. Update the map. c.lookups.set (this_index, new_lookup); - return true; + TRY (graph_result_t::from (c.lookups, ALLOCATION_FAILURE)); + return Ok(); } void fix_existing_subtable_links (gsubgpos_graph_context_t& c, @@ -290,41 +294,35 @@ struct Lookup : public OT::Lookup unsigned insert_offset = Lookup::min_size + insert_index * OT::Offset16::static_size; shift += p.second.length; - for (auto& l : v.obj.all_links_writer ()) + for (auto& l : v.all_links_writer ()) { if (l.position > insert_offset) l.position += pos_offset; } } } - unsigned create_extension_subtable (gsubgpos_graph_context_t& c, - unsigned subtable_index, - unsigned type) + graph_result_t create_extension_subtable (gsubgpos_graph_context_t& c, + unsigned subtable_index, + unsigned type) { unsigned extension_size = OT::ExtensionFormat1::static_size; - unsigned ext_index = c.create_node (extension_size); - if (ext_index == HB_GRAPH_INVALID) - return HB_GRAPH_INVALID; + unsigned ext_index = TRY (c.create_node (extension_size)); auto& ext_vertex = c.graph.vertices_[ext_index]; ExtensionFormat1* extension = - (ExtensionFormat1*) ext_vertex.obj.head; + ext_vertex.as*> (); extension->reset (type); // Make extension point at the subtable. - auto* l = ext_vertex.obj.real_links.push (); + TRY(ext_vertex.add_real_link (4, subtable_index, 4)); - l->width = 4; - l->objidx = subtable_index; - l->position = 4; - - return ext_index; + return Ok(ext_index); } - bool make_subtable_extension (gsubgpos_graph_context_t& c, - unsigned lookup_index, - unsigned subtable_index) + graph_result_t make_subtable_extension (gsubgpos_graph_context_t& c, + unsigned lookup_index, + unsigned subtable_index) { unsigned type = lookupType; unsigned ext_index = HB_GRAPH_INVALID; @@ -332,16 +330,14 @@ struct Lookup : public OT::Lookup if (c.subtable_to_extension.has(subtable_index, &existing_ext_index)) { ext_index = *existing_ext_index; } else { - ext_index = create_extension_subtable(c, subtable_index, type); + ext_index = TRY (create_extension_subtable(c, subtable_index, type)); c.subtable_to_extension.set(subtable_index, ext_index); + TRY (graph_result_t::from (c.subtable_to_extension, ALLOCATION_FAILURE)); } - if (ext_index == HB_GRAPH_INVALID) - return false; - auto& subtable_vertex = c.graph.vertices_[subtable_index]; auto& lookup_vertex = c.graph.vertices_[lookup_index]; - for (auto& l : lookup_vertex.obj.real_links.writer ()) + for (auto& l : lookup_vertex.real_links_writer ()) { if (l.objidx == subtable_index) { // Change lookup to point at the extension. @@ -353,11 +349,11 @@ struct Lookup : public OT::Lookup // Make extension point at the subtable. auto& ext_vertex = c.graph.vertices_[ext_index]; - ext_vertex.add_parent (lookup_index, false); + TRY(ext_vertex.add_parent (lookup_index, false)); if (!existing_ext_index) - subtable_vertex.remap_parent (lookup_index, ext_index); + TRY(subtable_vertex.remap_parent (lookup_index, ext_index)); - return true; + return Ok(); } private: @@ -388,24 +384,25 @@ struct Lookup : public OT::Lookup template struct LookupList : public OT::LookupList { - bool sanitize (const graph_t::vertex_t& vertex) const + graph_result_t sanitize (const graph_t::vertex_t& vertex) const { - size_t vertex_len = vertex.obj.tail - vertex.obj.head; - if (vertex_len < OT::LookupList::min_size) return false; + size_t vertex_len = vertex.table_size (); + if (unlikely (vertex_len < OT::LookupList::min_size)) return Err(SANITIZE_FAILURE); hb_barrier (); - return vertex_len >= OT::LookupList::item_size * this->len; + if (unlikely (vertex_len < OT::LookupList::item_size * this->len)) return Err(SANITIZE_FAILURE); + return Ok(); } }; struct GSTAR : public OT::GSUBGPOS { - static GSTAR* graph_to_gstar (graph_t& graph) + static graph_result_t graph_to_gstar (graph_t& graph) { const auto& r = graph.root (); - GSTAR* gstar = (GSTAR*) r.obj.head; - if (!gstar || !gstar->sanitize (r)) - return nullptr; + const GSTAR* gstar = (GSTAR*) r.obj ().head; + if (unlikely (!gstar)) return Err(INVALID_ARGUMENT); + TRY (gstar->sanitize (r)); hb_barrier (); return gstar; @@ -422,48 +419,59 @@ struct GSTAR : public OT::GSUBGPOS } } - bool sanitize (const graph_t::vertex_t& vertex) + graph_result_t sanitize (const graph_t::vertex_t& vertex) const { - size_t len = vertex.obj.tail - vertex.obj.head; - if (len < OT::GSUBGPOS::min_size) return false; + size_t len = vertex.table_size (); + if (unlikely (len < OT::GSUBGPOS::min_size)) return Err(SANITIZE_FAILURE); hb_barrier (); - return len >= get_size (); + switch (u.version.major) { + case 1: break; +#ifndef HB_NO_BEYOND_64K + case 2: break; +#endif + default: return Err(SANITIZE_FAILURE); + } + if (unlikely (len < get_size ())) return Err(SANITIZE_FAILURE); + return Ok(); } - void find_lookups (graph_t& graph, - hb_hashmap_t& lookups /* OUT */) + graph_result_t find_lookups (graph_t& graph, + hb_hashmap_t& lookups /* OUT */) const { switch (u.version.major) { - case 1: find_lookups (graph, lookups); break; + case 1: TRY(find_lookups (graph, lookups)); break; #ifndef HB_NO_BEYOND_64K - case 2: find_lookups (graph, lookups); break; + case 2: TRY(find_lookups (graph, lookups)); break; #endif } + return Ok(); } - unsigned get_lookup_list_index (graph_t& graph) + graph_result_t get_lookup_list_index (graph_t& graph) const { - return graph.index_for_offset (graph.root_idx (), - get_lookup_list_field_offset()); + const void* offset = get_lookup_list_field_offset (); + if (unlikely (!offset)) return Err(INVALID_ARGUMENT); + return graph.index_for_offset (graph.root_idx (), offset); } template - void find_lookups (graph_t& graph, - hb_hashmap_t& lookups /* OUT */) + graph_result_t find_lookups (graph_t& graph, + hb_hashmap_t& lookups /* OUT */) const { - unsigned lookup_list_idx = get_lookup_list_index (graph); + unsigned lookup_list_idx = TRY(get_lookup_list_index (graph)); const LookupList* lookupList = (const LookupList*) graph.object (lookup_list_idx).head; - if (!lookupList || !lookupList->sanitize (graph.vertices_[lookup_list_idx])) - return; + if (unlikely (!lookupList)) return Err(INVALID_ARGUMENT); + TRY(lookupList->sanitize (graph.vertices_[lookup_list_idx])); for (unsigned i = 0; i < lookupList->len; i++) { - unsigned lookup_idx = graph.index_for_offset (lookup_list_idx, &(lookupList->arrayZ[i])); + unsigned lookup_idx = TRY(graph.index_for_offset (lookup_list_idx, &(lookupList->arrayZ[i]))); Lookup* lookup = (Lookup*) graph.object (lookup_idx).head; - if (!lookup || !lookup->sanitize (graph.vertices_[lookup_idx])) continue; + if (!lookup || !lookup->sanitize (graph.vertices_[lookup_idx]).is_ok ()) continue; lookups.set (lookup_idx, lookup); } + return Ok(); } }; diff --git a/src/graph/ligature-graph.hh b/src/graph/ligature-graph.hh index 2fa458f3d..bdbf17dd4 100644 --- a/src/graph/ligature-graph.hh +++ b/src/graph/ligature-graph.hh @@ -40,85 +40,82 @@ namespace graph { struct LigatureSet : public OT::Layout::GSUB_impl::LigatureSet { - bool sanitize (const graph_t::vertex_t& vertex) const + graph_result_t sanitize (const graph_t::vertex_t& vertex) const { - size_t vertex_len = vertex.obj.tail - vertex.obj.head; - if (vertex_len < OT::Layout::GSUB_impl::LigatureSet::min_size) return false; + size_t vertex_len = vertex.table_size (); + if (unlikely (vertex_len < OT::Layout::GSUB_impl::LigatureSet::min_size)) return Err(SANITIZE_FAILURE); hb_barrier (); size_t total_len = ligature.get_size() + OT::Layout::GSUB_impl::LigatureSet::min_size - ligature.len.get_size(); - if (vertex_len < total_len) { - return false; + if (unlikely (vertex_len < total_len)) { + return Err(SANITIZE_FAILURE); } - return true; + return Ok(); } }; struct LigatureSubstFormat1 : public OT::Layout::GSUB_impl::LigatureSubstFormat1_2 { - bool sanitize (const graph_t::vertex_t& vertex) const + graph_result_t sanitize (const graph_t::vertex_t& vertex) const { - size_t vertex_len = vertex.obj.tail - vertex.obj.head; + size_t vertex_len = vertex.table_size (); unsigned min_size = OT::Layout::GSUB_impl::LigatureSubstFormat1_2::min_size; - if (vertex_len < min_size) return false; + if (unlikely (vertex_len < min_size)) return Err(SANITIZE_FAILURE); hb_barrier (); - return vertex_len >= - min_size + ligatureSet.get_size() - ligatureSet.len.get_size(); + if (unlikely (vertex_len < min_size + ligatureSet.get_size() - ligatureSet.len.get_size())) + return Err(SANITIZE_FAILURE); + return Ok(); } - hb_vector_t split_subtables (gsubgpos_graph_context_t& c, - unsigned this_index) + graph_result_t> split_subtables (gsubgpos_graph_context_t& c, + unsigned this_index) { - auto split_points = compute_split_points(c, this_index); + auto split_points = TRY(compute_split_points(c, this_index)); if (!split_points) - return hb_vector_t (); + return Ok(hb_vector_t ()); split_context_t split_context { c, this, this_index, - total_number_ligas(c, this_index), - liga_counts(c, this_index), + TRY(total_number_ligas(c, this_index)), + TRY(liga_counts(c, this_index)), }; return actuate_subtable_split (split_context, split_points); } private: - unsigned total_number_ligas(gsubgpos_graph_context_t& c, unsigned this_index) const { + graph_result_t total_number_ligas(gsubgpos_graph_context_t& c, unsigned this_index) const { unsigned total = 0; for (unsigned i = 0; i < ligatureSet.len; i++) { - auto liga_set = c.graph.as_table(this_index, &ligatureSet[i]); - if (!liga_set.table) { - return 0; - } + auto liga_set = TRY(c.graph.as_table(this_index, &ligatureSet[i])); total += liga_set.table->ligature.len; } - return total; + return Ok(total); } - hb_vector_t liga_counts(gsubgpos_graph_context_t& c, unsigned this_index) const { + graph_result_t> liga_counts(gsubgpos_graph_context_t& c, unsigned this_index) const { hb_vector_t result; for (unsigned i = 0; i < ligatureSet.len; i++) { - auto liga_set = c.graph.as_table(this_index, &ligatureSet[i]); + auto liga_set = TRY(c.graph.as_table(this_index, &ligatureSet[i])); result.push(!liga_set.table ? 0 : liga_set.table->ligature.len); } - return result; + return graph_result_t>::from(std::move(result), ALLOCATION_FAILURE); } template - hb_vector_t ligature_index_to_object_id(const graph_t::vertex_and_table_t& liga_set) const { + graph_result_t> ligature_index_to_object_id(const graph_t::vertex_and_table_t& liga_set) const { hb_vector_t map; - map.resize_exact(liga_set.table->ligature.len); - if (map.in_error()) return map; + if (!map.resize_exact(liga_set.table->ligature.len)) return Err(ALLOCATION_FAILURE); for (unsigned i = 0; i < map.length; i++) { map[i] = HB_GRAPH_INVALID; } - for (const auto& l : liga_set.vertex->obj.real_links) { + for (const auto& l : liga_set.vertex->obj ().real_links) { if (l.position < 2) continue; unsigned array_index = (l.position - 2) / 2; map[array_index] = l.objidx; @@ -126,8 +123,8 @@ struct LigatureSubstFormat1 : public OT::Layout::GSUB_impl::LigatureSubstFormat1 return map; } - hb_vector_t compute_split_points(gsubgpos_graph_context_t& c, - unsigned this_index) const + graph_result_t> compute_split_points(gsubgpos_graph_context_t& c, + unsigned this_index) const { // For ligature subst coverage is always packed last, and as a result is where an overflow // will happen if there is one, so we can check the estimate length of the @@ -143,16 +140,12 @@ struct LigatureSubstFormat1 : public OT::Layout::GSUB_impl::LigatureSubstFormat1 accumulated += OT::HBUINT16::static_size; // for ligature set offset accumulated += OT::Layout::GSUB_impl::LigatureSet::min_size; // for ligature set table - auto liga_set = c.graph.as_table(this_index, &ligatureSet[i]); - if (!liga_set.table) { - return hb_vector_t {}; - } + auto liga_set = TRY(c.graph.as_table(this_index, &ligatureSet[i])); // Finding the object id associated with an array index is O(n) // so to avoid O(n^2), precompute the mapping by scanning through // all links - auto index_to_id = ligature_index_to_object_id(liga_set); - if (index_to_id.in_error()) return hb_vector_t(); + auto index_to_id = TRY(ligature_index_to_object_id (liga_set)); for (unsigned j = 0; j < liga_set.table->ligature.len; j++) { @@ -194,46 +187,44 @@ struct LigatureSubstFormat1 : public OT::Layout::GSUB_impl::LigatureSubstFormat1 return original_count_; } - unsigned clone_range (unsigned start, unsigned end) + graph_result_t clone_range (unsigned start, unsigned end) { return thiz->clone_range (c, this_index, liga_counts, start, end); } - bool shrink (unsigned count) + graph_result_t shrink (unsigned count) { return thiz->shrink (c, this_index, original_count(), liga_counts, count); } }; - hb_pair_t new_liga_set(gsubgpos_graph_context_t& c, unsigned count) const { + graph_result_t> new_liga_set(gsubgpos_graph_context_t& c, unsigned count) const { unsigned prime_size = OT::Layout::GSUB_impl::LigatureSet::min_size + count * SmallTypes::size; - unsigned prime_id = c.create_node (prime_size); - if (prime_id == HB_GRAPH_INVALID) return hb_pair(HB_GRAPH_INVALID, nullptr); + unsigned prime_id = TRY (c.create_node (prime_size)); LigatureSet* prime = (LigatureSet*) c.graph.object (prime_id).head; prime->ligature.len = count; - return hb_pair(prime_id, prime); + return Ok(hb_pair(prime_id, prime)); } void clear_virtual_links (gsubgpos_graph_context_t& c, unsigned node_index) const { - auto& obj = c.graph.vertices_[node_index].obj; - for (const auto& l : obj.virtual_links) + auto& v = c.graph.vertices_[node_index]; + for (const auto& l : v.obj ().virtual_links) { auto& child = c.graph.vertices_[l.objidx]; child.remove_parent(node_index); } - obj.virtual_links.clear(); + v.clear_virtual_links (); } - void add_virtual_link(gsubgpos_graph_context_t& c, unsigned from, unsigned to) const { - if (from >= c.graph.vertices_.length || to >= c.graph.vertices_.length) return; - auto& from_obj = c.graph.vertices_[from].obj; - c.graph.vertices_[to].add_parent(from, true); - auto& link = *from_obj.virtual_links.push (); - link.objidx = to; + graph_result_t add_virtual_link(gsubgpos_graph_context_t& c, unsigned from, unsigned to) const { + if (unlikely (from >= c.graph.vertices_.length || to >= c.graph.vertices_.length)) return Err(OUT_OF_BOUNDS); + TRY(c.graph.vertices_[to].add_parent (from, true)); + TRY(c.graph.vertices_[from].add_virtual_link (to)); + return Ok(); } hb_pair_t current_liga_set_bounds (gsubgpos_graph_context_t& c, @@ -254,28 +245,29 @@ struct LigatureSubstFormat1 : public OT::Layout::GSUB_impl::LigatureSubstFormat1 return hb_pair(min_index, max_index + 1); } - void compact_liga_set (gsubgpos_graph_context_t& c, LigatureSet* table, hb_serialize_context_t::object_t& obj) const + void compact_liga_set (gsubgpos_graph_context_t& c, LigatureSet* table, graph_t::vertex_t* v) const { + const auto& obj = v->obj (); if (table->ligature.len <= obj.real_links.length) return; // compact the remaining linked liga offsets into a continous array and shrink the node as needed. unsigned to_remove = table->ligature.len - obj.real_links.length; unsigned new_position = SmallTypes::size; - obj.real_links.qsort(); // for this to work we need to process links in order of position. - for (auto& l : obj.real_links) + v->sort_real_links (); // for this to work we need to process links in order of position. + for (auto& l : v->real_links_writer ()) { l.position = new_position; new_position += SmallTypes::size; } table->ligature.len = obj.real_links.length; - obj.tail -= to_remove * SmallTypes::size; + v->shrink_buffer (to_remove * SmallTypes::size); } - unsigned clone_range (gsubgpos_graph_context_t& c, - unsigned this_index, - hb_vector_t liga_counts, - unsigned start, unsigned end) const + graph_result_t clone_range (gsubgpos_graph_context_t& c, + unsigned this_index, + hb_vector_t liga_counts, + unsigned start, unsigned end) const { DEBUG_MSG (SUBSET_REPACK, nullptr, " Cloning LigatureSubstFormat1 (%u) range [%u, %u).", this_index, start, end); @@ -286,8 +278,7 @@ struct LigatureSubstFormat1 : public OT::Layout::GSUB_impl::LigatureSubstFormat1 unsigned prime_size = OT::Layout::GSUB_impl::LigatureSubstFormat1_2::min_size + ligatureSet.get_size() - ligatureSet.len.get_size(); - unsigned liga_subst_prime_id = c.create_node (prime_size); - if (liga_subst_prime_id == HB_GRAPH_INVALID) return HB_GRAPH_INVALID; + unsigned liga_subst_prime_id = TRY (c.create_node (prime_size)); LigatureSubstFormat1* liga_subst_prime = (LigatureSubstFormat1*) c.graph.object (liga_subst_prime_id).head; liga_subst_prime->format = this->format; @@ -295,16 +286,12 @@ struct LigatureSubstFormat1 : public OT::Layout::GSUB_impl::LigatureSubstFormat1 // Create a place holder coverage prime id since we need to add virtual links to it while // generating liga and liga sets. Afterwards it will be updated to have the correct coverage. - unsigned coverage_id = c.graph.index_for_offset (this_index, &coverage); - if (coverage_id == HB_GRAPH_INVALID) return HB_GRAPH_INVALID; - unsigned coverage_prime_id = c.graph.duplicate(coverage_id); - if (coverage_prime_id == HB_GRAPH_INVALID) return HB_GRAPH_INVALID; + unsigned coverage_id = TRY(c.graph.index_for_offset (this_index, &coverage)); + unsigned coverage_prime_id = TRY (c.graph.duplicate(coverage_id)); auto& coverage_prime_vertex = c.graph.vertices_[coverage_prime_id]; - auto* coverage_prime_link = c.graph.vertices_[liga_subst_prime_id].obj.real_links.push (); - coverage_prime_link->width = SmallTypes::size; - coverage_prime_link->objidx = coverage_prime_id; - coverage_prime_link->position = 2; - coverage_prime_vertex.add_parent (liga_subst_prime_id, false); + + TRY(c.graph.vertices_[liga_subst_prime_id].add_real_link (SmallTypes::size, coverage_prime_id, 2)); + TRY(coverage_prime_vertex.add_parent (liga_subst_prime_id, false)); // Locate all liga sets with ligas between start and end. // Clone or move them as needed. @@ -325,14 +312,11 @@ struct LigatureSubstFormat1 : public OT::Layout::GSUB_impl::LigatureSubstFormat1 continue; } - auto liga_set = c.graph.as_mutable_table(this_index, &ligatureSet[i]); - if (!liga_set.table) { - return HB_GRAPH_INVALID; - } + auto liga_set = TRY(c.graph.as_mutable_table(this_index, &ligatureSet[i])); unsigned liga_set_index = liga_set.index; // Bounds may need to be adjusted if some ligas have been previously removed. - hb_pair_t liga_bounds = current_liga_set_bounds(c, liga_set_index, liga_set.vertex->obj); + hb_pair_t liga_bounds = current_liga_set_bounds(c, liga_set_index, liga_set.vertex->obj ()); current_start = hb_max(count + liga_bounds.first, current_start); current_end = hb_min(count + liga_bounds.second, current_end); @@ -342,11 +326,11 @@ struct LigatureSubstFormat1 : public OT::Layout::GSUB_impl::LigatureSubstFormat1 // We can move the entire ligaset to the new liga subset object. liga_set_end = i; if (i < liga_set_start) liga_set_start = i; - liga_set_prime_id = c.graph.move_child<> (this_index, + liga_set_prime_id = TRY (c.graph.move_child<> (this_index, &ligatureSet[i], liga_subst_prime_id, - &liga_subst_prime->ligatureSet[liga_set_count++]); - compact_liga_set(c, liga_set.table, liga_set.vertex->obj); + &liga_subst_prime->ligatureSet[liga_set_count++])); + compact_liga_set (c, liga_set.table, liga_set.vertex); } else { @@ -355,66 +339,61 @@ struct LigatureSubstFormat1 : public OT::Layout::GSUB_impl::LigatureSubstFormat1 unsigned start_index = hb_max(start, current_start) - count; unsigned end_index = hb_min(end, current_end) - count; unsigned liga_count = end_index - start_index; - auto result = new_liga_set(c, liga_count); + auto result = TRY (new_liga_set(c, liga_count)); liga_set_prime_id = result.first; - if (liga_set_prime_id == HB_GRAPH_INVALID) return HB_GRAPH_INVALID; - c.graph.move_children( + TRY (c.graph.move_children( liga_set_index, 2 + start_index * 2, 2 + end_index * 2, liga_set_prime_id, - 2); + 2)); liga_set_end = i; if (i < liga_set_start) liga_set_start = i; - c.graph.add_link(&liga_subst_prime->ligatureSet[liga_set_count++], liga_subst_prime_id, liga_set_prime_id); + TRY (c.graph.add_link(&liga_subst_prime->ligatureSet[liga_set_count++], liga_subst_prime_id, liga_set_prime_id)); } // The new liga and all children set needs to have a virtual link to the new coverage table: - auto& liga_set_prime = c.graph.vertices_[liga_set_prime_id].obj; + const auto& liga_set_prime = c.graph.vertices_[liga_set_prime_id].obj (); clear_virtual_links(c, liga_set_prime_id); - add_virtual_link(c, liga_set_prime_id, coverage_prime_id); + TRY(add_virtual_link(c, liga_set_prime_id, coverage_prime_id)); for (const auto& l : liga_set_prime.real_links) { clear_virtual_links(c, l.objidx); - add_virtual_link(c, l.objidx, coverage_prime_id); + TRY(add_virtual_link(c, l.objidx, coverage_prime_id)); } count += num_ligas; } - c.graph.vertices_[liga_subst_prime_id].obj.tail -= (liga_subst_prime->ligatureSet.len - liga_set_count) * SmallTypes::size; + c.graph.vertices_[liga_subst_prime_id].shrink_buffer ((liga_subst_prime->ligatureSet.len - liga_set_count) * SmallTypes::size); liga_subst_prime->ligatureSet.len = liga_set_count; - if (!Coverage::filter_coverage (c, + TRY (Coverage::filter_coverage (c, coverage_prime_id, - liga_set_start, liga_set_end + 1)) - return HB_GRAPH_INVALID; + liga_set_start, liga_set_end + 1)); - return liga_subst_prime_id; + return Ok(liga_subst_prime_id); } - bool shrink (gsubgpos_graph_context_t& c, - unsigned this_index, - unsigned old_count, - hb_vector_t liga_counts, - unsigned count) + graph_result_t shrink (gsubgpos_graph_context_t& c, + unsigned this_index, + unsigned old_count, + hb_vector_t liga_counts, + unsigned count) { DEBUG_MSG (SUBSET_REPACK, nullptr, " Shrinking LigatureSubstFormat1 (%u) to [0, %u).", this_index, count); if (count >= old_count) - return true; + return Ok(); hb_set_t retained_indices; unsigned new_liga_set_count = 0; for (unsigned i = 0; i < liga_counts.length; i++) { - auto liga_set = c.graph.as_mutable_table(this_index, &ligatureSet[i]); - if (!liga_set.table) { - return false; - } + auto liga_set = TRY(c.graph.as_mutable_table(this_index, &ligatureSet[i])); // We need the virtual links to coverage removed from all descendants on this liga subst. // If any are left when we try to mutate the coverage table later it will be unnessecarily @@ -422,8 +401,7 @@ struct LigatureSubstFormat1 : public OT::Layout::GSUB_impl::LigatureSubstFormat1 clear_virtual_links(c, liga_set.index); retained_indices.add(liga_set.index); - auto index_to_id = ligature_index_to_object_id(liga_set); - if (index_to_id.in_error()) return false; + auto index_to_id = TRY(ligature_index_to_object_id (liga_set)); for (unsigned i = 0; i < liga_set.table->ligature.len; i++) { unsigned liga_index = index_to_id[i]; @@ -438,7 +416,7 @@ struct LigatureSubstFormat1 : public OT::Layout::GSUB_impl::LigatureSubstFormat1 // drop the trailing liga's from this set and all subsequent liga sets unsigned num_ligas_to_remove = num_ligas - count; new_liga_set_count = i + 1; - c.graph.vertices_[liga_set.index].obj.tail -= num_ligas_to_remove * SmallTypes::size; + c.graph.vertices_[liga_set.index].shrink_buffer (num_ligas_to_remove * SmallTypes::size); liga_set.table->ligature.len = count; break; } else { @@ -448,25 +426,23 @@ struct LigatureSubstFormat1 : public OT::Layout::GSUB_impl::LigatureSubstFormat1 // Adjust liga set array auto& this_vertex = c.graph.vertices_[this_index]; - this_vertex.obj.tail -= (ligatureSet.len - new_liga_set_count) * SmallTypes::size; + this_vertex.shrink_buffer ((ligatureSet.len - new_liga_set_count) * SmallTypes::size); ligatureSet.len = new_liga_set_count; // Coverage matches the number of liga sets so rebuild as needed - unsigned coverage_idx = c.graph.index_for_offset (this_index, &this->coverage); - if (coverage_idx == HB_GRAPH_INVALID) return false; + unsigned coverage_idx = TRY(c.graph.index_for_offset (this_index, &this->coverage)); auto& coverage_v = c.graph.vertices_[coverage_idx]; unsigned coverage_size = coverage_v.table_size (); - Coverage* coverage_table = (Coverage*) coverage_v.obj.head; + const Coverage* coverage_table = (const Coverage*) coverage_v.obj ().head; if (coverage_v.is_shared ()) { - coverage_idx = c.graph.remap_child (this_index, coverage_idx); - if (coverage_idx == HB_GRAPH_INVALID) return false; + coverage_idx = TRY (c.graph.remap_child (this_index, coverage_idx)); } for (unsigned i : retained_indices.iter()) - add_virtual_link(c, i, coverage_idx); + TRY(add_virtual_link(c, i, coverage_idx)); auto new_coverage = + hb_zip (coverage_table->iter (), hb_range ()) @@ -483,8 +459,8 @@ struct LigatureSubstFormat1 : public OT::Layout::GSUB_impl::LigatureSubstFormat1 struct LigatureSubst : public OT::Layout::GSUB_impl::LigatureSubst { - hb_vector_t split_subtables (gsubgpos_graph_context_t& c, - unsigned this_index) + graph_result_t> split_subtables (gsubgpos_graph_context_t& c, + unsigned this_index) { switch (u.format.v) { case 1: @@ -495,14 +471,14 @@ struct LigatureSubst : public OT::Layout::GSUB_impl::LigatureSubst // Don't split 24bit Ligature Subs #endif default: - return hb_vector_t (); + return Ok(hb_vector_t ()); } } - bool sanitize (const graph_t::vertex_t& vertex) const + graph_result_t sanitize (const graph_t::vertex_t& vertex) const { - size_t vertex_len = vertex.obj.tail - vertex.obj.head; - if (vertex_len < u.format.v.get_size ()) return false; + size_t vertex_len = vertex.table_size (); + if (unlikely (vertex_len < u.format.v.get_size ())) return Err(SANITIZE_FAILURE); hb_barrier (); switch (u.format.v) { @@ -514,7 +490,7 @@ struct LigatureSubst : public OT::Layout::GSUB_impl::LigatureSubst #endif default: // We don't handle format 2 here. - return false; + return Err(SANITIZE_FAILURE); } } }; diff --git a/src/graph/markbasepos-graph.hh b/src/graph/markbasepos-graph.hh index fe89a669f..8fe8761fa 100644 --- a/src/graph/markbasepos-graph.hh +++ b/src/graph/markbasepos-graph.hh @@ -36,62 +36,67 @@ namespace graph { struct AnchorMatrix : public OT::Layout::GPOS_impl::AnchorMatrix { - bool sanitize (const graph_t::vertex_t& vertex, unsigned class_count) const + graph_result_t sanitize (const graph_t::vertex_t& vertex, unsigned class_count) const { - size_t vertex_len = vertex.obj.tail - vertex.obj.head; - if (vertex_len < AnchorMatrix::min_size) return false; + size_t vertex_len = vertex.table_size(); + if (unlikely (vertex_len < AnchorMatrix::min_size)) return Err(SANITIZE_FAILURE); hb_barrier (); - return vertex_len >= AnchorMatrix::min_size + - OT::Offset16::static_size * class_count * this->rows; + if (unlikely (vertex_len < AnchorMatrix::min_size + + OT::Offset16::static_size * class_count * this->rows)) + return Err(SANITIZE_FAILURE); + return Ok(); } - bool shrink (gsubgpos_graph_context_t& c, - unsigned this_index, - unsigned old_class_count, - unsigned new_class_count) + graph_result_t shrink (gsubgpos_graph_context_t& c, + unsigned this_index, + unsigned old_class_count, + unsigned new_class_count) { - if (new_class_count >= old_class_count) return false; - auto& o = c.graph.vertices_[this_index].obj; + if (unlikely (new_class_count >= old_class_count)) return Err(INVALID_ARGUMENT); + auto& v = c.graph.vertices_[this_index]; + const auto& o = v.obj (); unsigned base_count = rows; - o.tail = o.head + - AnchorMatrix::min_size + - OT::Offset16::static_size * base_count * new_class_count; + v.set_buffer (o.head, + o.head + + AnchorMatrix::min_size + + OT::Offset16::static_size * base_count * new_class_count); // Reposition links into the new indexing scheme. - for (auto& link : o.real_links.writer ()) + for (auto& link : v.real_links_writer ()) { unsigned index = (link.position - 2) / 2; unsigned base = index / old_class_count; unsigned klass = index % old_class_count; - if (klass >= new_class_count) + if (unlikely (klass >= new_class_count)) // should have already been removed - return false; + return Err(INVALID_ARGUMENT); unsigned new_index = base * new_class_count + klass; link.position = (char*) &(this->matrixZ[new_index]) - (char*) this; } - return true; + return Ok(); } - unsigned clone (gsubgpos_graph_context_t& c, - unsigned this_index, - unsigned start, - unsigned end, - unsigned class_count) + graph_result_t clone (gsubgpos_graph_context_t& c, + unsigned this_index, + unsigned start, + unsigned end, + unsigned class_count) { unsigned base_count = rows; unsigned new_class_count = end - start; unsigned size = AnchorMatrix::min_size + OT::Offset16::static_size * new_class_count * rows; - unsigned prime_id = c.create_node (size); - if (prime_id == HB_GRAPH_INVALID) return HB_GRAPH_INVALID; + unsigned prime_id = TRY (c.create_node (size)); AnchorMatrix* prime = (AnchorMatrix*) c.graph.object (prime_id).head; prime->rows = base_count; - auto& o = c.graph.vertices_[this_index].obj; + auto& v = c.graph.vertices_[this_index]; + const auto& o = v.obj (); + int num_links = o.real_links.length; for (int i = 0; i < num_links; i++) { @@ -106,43 +111,48 @@ struct AnchorMatrix : public OT::Layout::GPOS_impl::AnchorMatrix unsigned child_idx = link.objidx; - c.graph.add_link (&(prime->matrixZ[new_index]), - prime_id, - child_idx); + TRY (c.graph.add_link (&(prime->matrixZ[new_index]), + prime_id, + child_idx)); auto& child = c.graph.vertices_[child_idx]; child.remove_parent (this_index); - o.real_links.remove_unordered (i); + v.remove_real_link_unordered (i); num_links--; i--; } - return prime_id; + // Restore correct ordering after the above removes, which mess up link ordering. + v.sort_real_links (); + + return Ok(prime_id); } }; struct MarkArray : public OT::Layout::GPOS_impl::MarkArray { - bool sanitize (const graph_t::vertex_t& vertex) const + graph_result_t sanitize (const graph_t::vertex_t& vertex) const { - size_t vertex_len = vertex.obj.tail - vertex.obj.head; + size_t vertex_len = vertex.table_size(); unsigned min_size = MarkArray::min_size; - if (vertex_len < min_size) return false; + if (unlikely (vertex_len < min_size)) return Err(SANITIZE_FAILURE); hb_barrier (); - return vertex_len >= get_size (); + if (unlikely (vertex_len < get_size ())) return Err(SANITIZE_FAILURE); + return Ok(); } - bool shrink (gsubgpos_graph_context_t& c, - const hb_hashmap_t& mark_array_links, - unsigned this_index, - unsigned new_class_count) + graph_result_t shrink (gsubgpos_graph_context_t& c, + const hb_hashmap_t& mark_array_links, + unsigned this_index, + unsigned new_class_count) { - auto& o = c.graph.vertices_[this_index].obj; + auto& v = c.graph.vertices_[this_index]; + const auto& o = v.obj (); for (const auto& link : o.real_links) c.graph.vertices_[link.objidx].remove_parent (this_index); - o.real_links.reset (); + v.clear_real_links (); unsigned new_index = 0; for (const auto& record : this->iter ()) @@ -159,27 +169,27 @@ struct MarkArray : public OT::Layout::GPOS_impl::MarkArray continue; } - c.graph.add_link (&(*this)[new_index].markAnchor, this_index, *objidx); + TRY (c.graph.add_link (&(*this)[new_index].markAnchor, this_index, *objidx)); new_index++; } this->len = new_index; - o.tail = o.head + MarkArray::min_size + - OT::Layout::GPOS_impl::MarkRecord::static_size * new_index; - return true; + v.set_buffer (o.head, o.head + MarkArray::min_size + + OT::Layout::GPOS_impl::MarkRecord::static_size * new_index); + + return Ok(); } - unsigned clone (gsubgpos_graph_context_t& c, - unsigned this_index, - const hb_hashmap_t& pos_to_index, - hb_set_t& marks, - unsigned start_class) + graph_result_t clone (gsubgpos_graph_context_t& c, + unsigned this_index, + const hb_hashmap_t& pos_to_index, + hb_set_t& marks, + unsigned start_class) { unsigned size = MarkArray::min_size + OT::Layout::GPOS_impl::MarkRecord::static_size * marks.get_population (); - unsigned prime_id = c.create_node (size); - if (prime_id == HB_GRAPH_INVALID) return HB_GRAPH_INVALID; + unsigned prime_id = TRY (c.create_node (size)); MarkArray* prime = (MarkArray*) c.graph.object (prime_id).head; prime->len = marks.get_population (); @@ -191,46 +201,50 @@ struct MarkArray : public OT::Layout::GPOS_impl::MarkArray unsigned offset_pos = (char*) &((*this)[mark].markAnchor) - (char*) this; unsigned* anchor_index; if (pos_to_index.has (offset_pos, &anchor_index)) - c.graph.move_child (this_index, - &((*this)[mark].markAnchor), - prime_id, - &((*prime)[i].markAnchor)); + TRY (c.graph.move_child (this_index, + &((*this)[mark].markAnchor), + prime_id, + &((*prime)[i].markAnchor))); i++; } - return prime_id; + // Restore correct ordering of the vertex links which are disturbed by move_child. + c.graph.vertices_[this_index].sort_real_links (); + + return Ok(prime_id); } }; struct MarkBasePosFormat1 : public OT::Layout::GPOS_impl::MarkBasePosFormat1_2 { - bool sanitize (const graph_t::vertex_t& vertex) const + graph_result_t sanitize (const graph_t::vertex_t& vertex) const { - size_t vertex_len = vertex.obj.tail - vertex.obj.head; - return vertex_len >= MarkBasePosFormat1::static_size; + size_t vertex_len = vertex.table_size (); + if (unlikely (vertex_len < MarkBasePosFormat1::static_size)) + return Err(SANITIZE_FAILURE); + return Ok(); } - hb_vector_t split_subtables (gsubgpos_graph_context_t& c, - unsigned this_index) + graph_result_t> split_subtables (gsubgpos_graph_context_t& c, + unsigned this_index) { hb_set_t visited; - const unsigned base_coverage_id = c.graph.index_for_offset (this_index, &baseCoverage); - if (base_coverage_id == HB_GRAPH_INVALID) return hb_vector_t (); + const unsigned base_coverage_id = TRY(c.graph.index_for_offset (this_index, &baseCoverage)); + const unsigned base_size = OT::Layout::GPOS_impl::MarkBasePosFormat1_2::min_size + MarkArray::min_size + AnchorMatrix::min_size + c.graph.vertices_[base_coverage_id].table_size (); - hb_vector_t class_to_info = get_class_info (c, this_index); + hb_vector_t class_to_info = TRY(get_class_info (c, this_index)); unsigned class_count = classCount; - auto base_array = c.graph.as_table (this_index, - &baseArray, - class_count); - if (!base_array) return hb_vector_t (); + auto base_array = TRY(c.graph.as_table (this_index, + &baseArray, + class_count)); unsigned base_count = base_array.table->rows; unsigned partial_coverage_size = 4; @@ -246,7 +260,7 @@ struct MarkBasePosFormat1 : public OT::Layout::GPOS_impl::MarkBasePosFormat1_2= (1 << 16)) { split_points.push (klass); + TRY (graph_result_t::from (split_points, ALLOCATION_FAILURE)); accumulated = base_size + accumulated_delta; partial_coverage_size = 4 + OT::HBUINT16::static_size * info.marks.get_population (); visited.clear (); // node sharing isn't allowed between splits. @@ -261,14 +276,14 @@ struct MarkBasePosFormat1 : public OT::Layout::GPOS_impl::MarkBasePosFormat1_2 (); + const unsigned mark_array_id = TRY(c.graph.index_for_offset (this_index, &markArray)); + split_context_t split_context { c, this, this_index, std::move (class_to_info), - c.graph.vertices_[mark_array_id].position_to_index_map (), + TRY(c.graph.vertices_[mark_array_id].position_to_index_map ()), }; return actuate_subtable_split (split_context, split_points); @@ -305,30 +320,30 @@ struct MarkBasePosFormat1 : public OT::Layout::GPOS_impl::MarkBasePosFormat1_2classCount; } - unsigned clone_range (unsigned start, unsigned end) + graph_result_t clone_range (unsigned start, unsigned end) { return thiz->clone_range (*this, this->this_index, start, end); } - bool shrink (unsigned count) + graph_result_t shrink (unsigned count) { return thiz->shrink (*this, this->this_index, count); } }; - hb_vector_t get_class_info (gsubgpos_graph_context_t& c, - unsigned this_index) + graph_result_t> get_class_info (gsubgpos_graph_context_t& c, + unsigned this_index) { hb_vector_t class_to_info; unsigned class_count = classCount; if (!class_count) return class_to_info; - if (!class_to_info.resize (class_count)) - return hb_vector_t(); + if (unlikely (!class_to_info.resize (class_count))) + return Err(ALLOCATION_FAILURE); + + auto mark_array = TRY(c.graph.as_table (this_index, &markArray)); - auto mark_array = c.graph.as_table (this_index, &markArray); - if (!mark_array) return hb_vector_t (); unsigned mark_count = mark_array.table->len; for (unsigned mark = 0; mark < mark_count; mark++) { @@ -337,7 +352,7 @@ struct MarkBasePosFormat1 : public OT::Layout::GPOS_impl::MarkBasePosFormat1_2obj.real_links) + for (const auto& link : mark_array.vertex->obj ().real_links) { unsigned mark = (link.position - 2) / OT::Layout::GPOS_impl::MarkRecord::static_size; @@ -347,11 +362,11 @@ struct MarkBasePosFormat1 : public OT::Layout::GPOS_impl::MarkBasePosFormat1_2 (); + TRY(c.graph.index_for_offset (this_index, &baseArray)); + auto& base_array_v = c.graph.vertices_[base_array_id]; - for (const auto& link : base_array_v.obj.real_links) + for (const auto& link : base_array_v.obj ().real_links) { unsigned index = (link.position - 2) / OT::Offset16::static_size; unsigned klass = index % class_count; @@ -361,9 +376,9 @@ struct MarkBasePosFormat1 : public OT::Layout::GPOS_impl::MarkBasePosFormat1_2 shrink (split_context_t& sc, + unsigned this_index, + unsigned count) { DEBUG_MSG (SUBSET_REPACK, nullptr, " Shrinking MarkBasePosFormat1 (%u) to [0, %u).", @@ -372,49 +387,48 @@ struct MarkBasePosFormat1 : public OT::Layout::GPOS_impl::MarkBasePosFormat1_2= old_count) - return true; + return Ok(); classCount = count; - auto mark_coverage = sc.c.graph.as_mutable_table (this_index, - &markCoverage); - if (!mark_coverage) return false; + auto mark_coverage = TRY(sc.c.graph.as_mutable_table (this_index, + &markCoverage)); + hb_set_t marks = sc.marks_for (0, count); auto new_coverage = + hb_enumerate (mark_coverage.table->iter ()) | hb_filter (marks, hb_first) | hb_map_retains_sorting (hb_second) ; - if (!Coverage::make_coverage (sc.c, + new_coverage, + TRY (Coverage::make_coverage (sc.c, + new_coverage, mark_coverage.index, - 4 + 2 * marks.get_population ())) - return false; + 4 + 2 * marks.get_population ())); - auto base_array = sc.c.graph.as_mutable_table (this_index, - &baseArray, - old_count); - if (!base_array || !base_array.table->shrink (sc.c, - base_array.index, - old_count, - count)) - return false; + auto base_array = TRY(sc.c.graph.as_mutable_table (this_index, + &baseArray, + old_count)); - auto mark_array = sc.c.graph.as_mutable_table (this_index, - &markArray); - if (!mark_array || !mark_array.table->shrink (sc.c, - sc.mark_array_links, - mark_array.index, - count)) - return false; + TRY (base_array.table->shrink (sc.c, + base_array.index, + old_count, + count)); - return true; + auto mark_array = TRY(sc.c.graph.as_mutable_table (this_index, + &markArray)); + + TRY (mark_array.table->shrink (sc.c, + sc.mark_array_links, + mark_array.index, + count)); + + return Ok(); } // Create a new MarkBasePos that has all of the data for classes from [start, end). - unsigned clone_range (split_context_t& sc, - unsigned this_index, - unsigned start, unsigned end) const + graph_result_t clone_range (split_context_t& sc, + unsigned this_index, + unsigned start, unsigned end) const { DEBUG_MSG (SUBSET_REPACK, nullptr, " Cloning MarkBasePosFormat1 (%u) range [%u, %u).", this_index, start, end); @@ -422,8 +436,7 @@ struct MarkBasePosFormat1 : public OT::Layout::GPOS_impl::MarkBasePosFormat1_2::static_size; - unsigned prime_id = sc.c.create_node (prime_size); - if (prime_id == HB_GRAPH_INVALID) return HB_GRAPH_INVALID; + unsigned prime_id = TRY (sc.c.create_node (prime_size)); MarkBasePosFormat1* prime = (MarkBasePosFormat1*) graph.object (prime_id).head; prime->format = this->format; @@ -431,58 +444,55 @@ struct MarkBasePosFormat1 : public OT::Layout::GPOS_impl::MarkBasePosFormat1_2classCount = new_class_count; unsigned base_coverage_id = - graph.index_for_offset (sc.this_index, &baseCoverage); - if (base_coverage_id == HB_GRAPH_INVALID) return HB_GRAPH_INVALID; - graph.add_link (&(prime->baseCoverage), prime_id, base_coverage_id); + TRY(graph.index_for_offset (sc.this_index, &baseCoverage)); + + TRY (graph.add_link (&(prime->baseCoverage), prime_id, base_coverage_id)); + + auto mark_coverage = TRY(sc.c.graph.as_table (this_index, + &markCoverage)); - auto mark_coverage = sc.c.graph.as_table (this_index, - &markCoverage); - if (!mark_coverage) return HB_GRAPH_INVALID; hb_set_t marks = sc.marks_for (start, end); auto new_coverage = + hb_enumerate (mark_coverage.table->iter ()) | hb_filter (marks, hb_first) | hb_map_retains_sorting (hb_second) ; - if (!Coverage::add_coverage (sc.c, + TRY (Coverage::add_coverage (sc.c, prime_id, 2, + new_coverage, - marks.get_population () * 2 + 4)) - return HB_GRAPH_INVALID; + marks.get_population () * 2 + 4)); auto mark_array = - graph.as_mutable_table (sc.this_index, &markArray); - if (!mark_array) return HB_GRAPH_INVALID; + TRY(graph.as_mutable_table (sc.this_index, &markArray)); + unsigned new_mark_array = - mark_array.table->clone (sc.c, - mark_array.index, - sc.mark_array_links, - marks, - start); - if (new_mark_array == (unsigned) HB_GRAPH_INVALID) return HB_GRAPH_INVALID; - graph.add_link (&(prime->markArray), prime_id, new_mark_array); + TRY (mark_array.table->clone (sc.c, + mark_array.index, + sc.mark_array_links, + marks, + start)); + TRY (graph.add_link (&(prime->markArray), prime_id, new_mark_array)); unsigned class_count = classCount; auto base_array = - graph.as_mutable_table (sc.this_index, &baseArray, class_count); - if (!base_array) return HB_GRAPH_INVALID; - unsigned new_base_array = - base_array.table->clone (sc.c, - base_array.index, - start, end, this->classCount); - if (new_base_array == HB_GRAPH_INVALID) return HB_GRAPH_INVALID; - graph.add_link (&(prime->baseArray), prime_id, new_base_array); + TRY(graph.as_mutable_table (sc.this_index, &baseArray, class_count)); - return prime_id; + unsigned new_base_array = + TRY (base_array.table->clone (sc.c, + base_array.index, + start, end, this->classCount)); + TRY (graph.add_link (&(prime->baseArray), prime_id, new_base_array)); + + return Ok(prime_id); } }; struct MarkBasePos : public OT::Layout::GPOS_impl::MarkBasePos { - hb_vector_t split_subtables (gsubgpos_graph_context_t& c, - unsigned this_index) + graph_result_t> split_subtables (gsubgpos_graph_context_t& c, + unsigned this_index) { switch (u.format.v) { case 1: @@ -493,14 +503,14 @@ struct MarkBasePos : public OT::Layout::GPOS_impl::MarkBasePos // Don't split 24bit MarkBasePos's. #endif default: - return hb_vector_t (); + return Ok(hb_vector_t ()); } } - bool sanitize (const graph_t::vertex_t& vertex) const + graph_result_t sanitize (const graph_t::vertex_t& vertex) const { - size_t vertex_len = vertex.obj.tail - vertex.obj.head; - if (vertex_len < u.format.v.get_size ()) return false; + size_t vertex_len = vertex.table_size (); + if (unlikely (vertex_len < u.format.v.get_size ())) return Err(SANITIZE_FAILURE); hb_barrier (); switch (u.format.v) { @@ -512,7 +522,7 @@ struct MarkBasePos : public OT::Layout::GPOS_impl::MarkBasePos #endif default: // We don't handle format 3 and 4 here. - return false; + return Err(SANITIZE_FAILURE); } } }; diff --git a/src/graph/pairpos-graph.hh b/src/graph/pairpos-graph.hh index e35590be9..b96d8a0d1 100644 --- a/src/graph/pairpos-graph.hh +++ b/src/graph/pairpos-graph.hh @@ -37,24 +37,24 @@ namespace graph { struct PairPosFormat1 : public OT::Layout::GPOS_impl::PairPosFormat1_3 { - bool sanitize (const graph_t::vertex_t& vertex) const + graph_result_t sanitize (const graph_t::vertex_t& vertex) const { - size_t vertex_len = vertex.obj.tail - vertex.obj.head; + size_t vertex_len = vertex.table_size (); unsigned min_size = OT::Layout::GPOS_impl::PairPosFormat1_3::min_size; - if (vertex_len < min_size) return false; + if (unlikely (vertex_len < min_size)) return Err(SANITIZE_FAILURE); hb_barrier (); - return vertex_len >= - min_size + pairSet.get_size () - pairSet.len.get_size(); + if (unlikely (vertex_len < min_size + pairSet.get_size () - pairSet.len.get_size())) + return Err(SANITIZE_FAILURE); + return Ok(); } - hb_vector_t split_subtables (gsubgpos_graph_context_t& c, - unsigned this_index) + graph_result_t> split_subtables (gsubgpos_graph_context_t& c, + unsigned this_index) { hb_set_t visited; - const unsigned coverage_id = c.graph.index_for_offset (this_index, &coverage); - if (coverage_id == HB_GRAPH_INVALID) return hb_vector_t (); + const unsigned coverage_id = TRY(c.graph.index_for_offset (this_index, &coverage)); const unsigned coverage_size = c.graph.vertices_[coverage_id].table_size (); const unsigned base_size = OT::Layout::GPOS_impl::PairPosFormat1_3::min_size; @@ -63,9 +63,9 @@ struct PairPosFormat1 : public OT::Layout::GPOS_impl::PairPosFormat1_3 split_points; for (unsigned i = 0; i < pairSet.len; i++) { - unsigned pair_set_index = pair_set_graph_index (c, this_index, i); + unsigned pair_set_index = TRY(pair_set_graph_index (c, this_index, i)); unsigned accumulated_delta = - c.graph.find_subgraph_size (pair_set_index, visited) + + c.graph.find_subgraph_size (pair_set_index, visited).value_or (0) + SmallTypes::size; // for PairSet offset. partial_coverage_size += OT::HBUINT16::static_size; @@ -75,6 +75,7 @@ struct PairPosFormat1 : public OT::Layout::GPOS_impl::PairPosFormat1_3= (1 << 16)) { split_points.push (i); + TRY (graph_result_t::from (split_points, ALLOCATION_FAILURE)); accumulated = base_size + accumulated_delta; partial_coverage_size = 6; visited.clear (); // node sharing isn't allowed between splits. @@ -102,20 +103,20 @@ struct PairPosFormat1 : public OT::Layout::GPOS_impl::PairPosFormat1_3pairSet.len; } - unsigned clone_range (unsigned start, unsigned end) + graph_result_t clone_range (unsigned start, unsigned end) { return thiz->clone_range (this->c, this->this_index, start, end); } - bool shrink (unsigned count) + graph_result_t shrink (unsigned count) { return thiz->shrink (this->c, this->this_index, count); } }; - bool shrink (gsubgpos_graph_context_t& c, - unsigned this_index, - unsigned count) + graph_result_t shrink (gsubgpos_graph_context_t& c, + unsigned this_index, + unsigned count) { DEBUG_MSG (SUBSET_REPACK, nullptr, " Shrinking PairPosFormat1 (%u) to [0, %u).", @@ -123,13 +124,12 @@ struct PairPosFormat1 : public OT::Layout::GPOS_impl::PairPosFormat1_3= old_count) - return true; + return Ok(); pairSet.len = count; - c.graph.vertices_[this_index].obj.tail -= (old_count - count) * SmallTypes::size; + c.graph.vertices_[this_index].shrink_buffer ((old_count - count) * SmallTypes::size); - auto coverage = c.graph.as_mutable_table (this_index, &this->coverage); - if (!coverage) return false; + auto coverage = TRY(c.graph.as_mutable_table (this_index, &this->coverage)); unsigned coverage_size = coverage.vertex->table_size (); auto new_coverage = @@ -145,9 +145,9 @@ struct PairPosFormat1 : public OT::Layout::GPOS_impl::PairPosFormat1_3 clone_range (gsubgpos_graph_context_t& c, + unsigned this_index, + unsigned start, unsigned end) const { DEBUG_MSG (SUBSET_REPACK, nullptr, " Cloning PairPosFormat1 (%u) range [%u, %u).", this_index, start, end); @@ -156,8 +156,7 @@ struct PairPosFormat1 : public OT::Layout::GPOS_impl::PairPosFormat1_3::min_size + num_pair_sets * SmallTypes::size; - unsigned pair_pos_prime_id = c.create_node (prime_size); - if (pair_pos_prime_id == HB_GRAPH_INVALID) return HB_GRAPH_INVALID; + unsigned pair_pos_prime_id = TRY (c.create_node (prime_size)); PairPosFormat1* pair_pos_prime = (PairPosFormat1*) c.graph.object (pair_pos_prime_id).head; pair_pos_prime->format = this->format; @@ -167,27 +166,28 @@ struct PairPosFormat1 : public OT::Layout::GPOS_impl::PairPosFormat1_3 (this_index, - &pairSet[i], - pair_pos_prime_id, - &pair_pos_prime->pairSet[i - start]); + TRY (c.graph.move_child<> (this_index, + &pairSet[i], + pair_pos_prime_id, + &pair_pos_prime->pairSet[i - start])); } - unsigned coverage_id = c.graph.index_for_offset (this_index, &coverage); - if (coverage_id == HB_GRAPH_INVALID) return HB_GRAPH_INVALID; - if (!Coverage::clone_coverage (c, + // Restore correct ordering of the vertex links which are disturbed by move_child. + c.graph.vertices_[this_index].sort_real_links (); + + unsigned coverage_id = TRY(c.graph.index_for_offset (this_index, &coverage)); + TRY (Coverage::clone_coverage (c, coverage_id, pair_pos_prime_id, 2, - start, end)) - return HB_GRAPH_INVALID; + start, end)); - return pair_pos_prime_id; + return Ok(pair_pos_prime_id); } - unsigned pair_set_graph_index (gsubgpos_graph_context_t& c, unsigned this_index, unsigned i) const + graph_result_t pair_set_graph_index (gsubgpos_graph_context_t& c, unsigned this_index, unsigned i) const { return c.graph.index_for_offset (this_index, &pairSet[i]); } @@ -195,32 +195,33 @@ struct PairPosFormat1 : public OT::Layout::GPOS_impl::PairPosFormat1_3 { - bool sanitize (const graph_t::vertex_t& vertex) const + graph_result_t sanitize (const graph_t::vertex_t& vertex) const { size_t vertex_len = vertex.table_size (); unsigned min_size = OT::Layout::GPOS_impl::PairPosFormat2_4::min_size; - if (vertex_len < min_size) return false; + if (unlikely (vertex_len < min_size)) return Err(SANITIZE_FAILURE); hb_barrier (); const unsigned class1_count = class1Count; - return vertex_len >= - min_size + class1_count * get_class1_record_size (); + if (unlikely (vertex_len < min_size + class1_count * get_class1_record_size ())) + return Err(SANITIZE_FAILURE); + return Ok(); } - hb_vector_t split_subtables (gsubgpos_graph_context_t& c, - unsigned this_index) + graph_result_t> split_subtables (gsubgpos_graph_context_t& c, + unsigned this_index) { const unsigned base_size = OT::Layout::GPOS_impl::PairPosFormat2_4::min_size; - const unsigned class_def_2_size = size_of (c, this_index, &classDef2); - const Coverage* coverage = get_coverage (c, this_index); - const ClassDef* class_def_1 = get_class_def_1 (c, this_index); + const unsigned class_def_2_size = TRY(size_of (c, this_index, &classDef2)); + const Coverage* coverage = TRY(get_coverage (c, this_index)); + const ClassDef* class_def_1 = TRY(get_class_def_1 (c, this_index)); auto gid_and_class = + coverage->iter () | hb_map_retains_sorting ([&] (hb_codepoint_t gid) { return hb_codepoint_pair_t (gid, class_def_1->get_class (gid)); }) ; - class_def_size_estimator_t estimator (gid_and_class); + class_def_size_estimator_t estimator = TRY (class_def_size_estimator_t::create (gid_and_class)); const unsigned class1_count = class1Count; const unsigned class2_count = class2Count; @@ -238,7 +239,7 @@ struct PairPosFormat2 : public OT::Layout::GPOS_impl::PairPosFormat2_4 split_points; - hb_hashmap_t device_tables = get_all_device_tables (c, this_index); + hb_hashmap_t device_tables = TRY(get_all_device_tables (c, this_index)); hb_vector_t format1_device_table_indices = valueFormat1.get_device_table_indices (); hb_vector_t format2_device_table_indices = valueFormat2.get_device_table_indices (); bool has_device_tables = bool(format1_device_table_indices) || bool(format2_device_table_indices); @@ -278,6 +279,7 @@ struct PairPosFormat2 : public OT::Layout::GPOS_impl::PairPosFormat2_4= (1 << 16)) { split_points.push (i); + TRY (graph_result_t::from (split_points, ALLOCATION_FAILURE)); // split does not include i, so add the size for i when we reset the size counters. accumulated = base_size + accumulated_delta; @@ -328,12 +330,12 @@ struct PairPosFormat2 : public OT::Layout::GPOS_impl::PairPosFormat2_4class1Count; } - unsigned clone_range (unsigned start, unsigned end) + graph_result_t clone_range (unsigned start, unsigned end) { return thiz->clone_range (*this, start, end); } - bool shrink (unsigned count) + graph_result_t shrink (unsigned count) { return thiz->shrink (*this, count); } @@ -346,8 +348,8 @@ struct PairPosFormat2 : public OT::Layout::GPOS_impl::PairPosFormat2_4 clone_range (split_context_t& split_context, + unsigned start, unsigned end) const { DEBUG_MSG (SUBSET_REPACK, nullptr, " Cloning PairPosFormat2 (%u) range [%u, %u).", split_context.this_index, start, end); @@ -358,8 +360,7 @@ struct PairPosFormat2 : public OT::Layout::GPOS_impl::PairPosFormat2_4::min_size + num_records * split_context.class1_record_size; - unsigned pair_pos_prime_id = split_context.c.create_node (prime_size); - if (pair_pos_prime_id == HB_GRAPH_INVALID) return HB_GRAPH_INVALID; + unsigned pair_pos_prime_id = TRY (split_context.c.create_node (prime_size)); PairPosFormat2* pair_pos_prime = (PairPosFormat2*) graph.object (pair_pos_prime_id).head; @@ -368,26 +369,24 @@ struct PairPosFormat2 : public OT::Layout::GPOS_impl::PairPosFormat2_4valueFormat2 = this->valueFormat2; pair_pos_prime->class1Count = num_records; pair_pos_prime->class2Count = this->class2Count; - clone_class1_records (split_context, - pair_pos_prime_id, - start, - end); + TRY (clone_class1_records (split_context, + pair_pos_prime_id, + start, + end)); unsigned coverage_id = - graph.index_for_offset (split_context.this_index, &coverage); + TRY(graph.index_for_offset (split_context.this_index, &coverage)); unsigned class_def_1_id = - graph.index_for_offset (split_context.this_index, &classDef1); - if (coverage_id == HB_GRAPH_INVALID || class_def_1_id == HB_GRAPH_INVALID) - return HB_GRAPH_INVALID; + TRY(graph.index_for_offset (split_context.this_index, &classDef1)); + auto& coverage_v = graph.vertices_[coverage_id]; auto& class_def_1_v = graph.vertices_[class_def_1_id]; - Coverage* coverage_table = (Coverage*) coverage_v.obj.head; - ClassDef* class_def_1_table = (ClassDef*) class_def_1_v.obj.head; - if (!coverage_table - || !coverage_table->sanitize (coverage_v) - || !class_def_1_table - || !class_def_1_table->sanitize (class_def_1_v)) - return HB_GRAPH_INVALID; + const Coverage* coverage_table = (const Coverage*) coverage_v.obj().head; + const ClassDef* class_def_1_table = (const ClassDef*) class_def_1_v.obj().head; + if (unlikely (!coverage_table || !class_def_1_table)) + return Err(INVALID_ARGUMENT); + TRY (coverage_table->sanitize (coverage_v)); + TRY (class_def_1_table->sanitize (class_def_1_v)); auto klass_map = + coverage_table->iter () @@ -403,38 +402,32 @@ struct PairPosFormat2 : public OT::Layout::GPOS_impl::PairPosFormat2_4width = SmallTypes::size; - class_def_link->objidx = class_def_2_id; - class_def_link->position = 10; - graph.vertices_[class_def_2_id].add_parent (pair_pos_prime_id, false); + TRY(graph.index_for_offset (split_context.this_index, &classDef2)); - return pair_pos_prime_id; + TRY(graph.vertices_[pair_pos_prime_id].add_real_link (SmallTypes::size, class_def_2_id, 10)); + TRY(graph.vertices_[class_def_2_id].add_parent (pair_pos_prime_id, false)); + + return Ok(pair_pos_prime_id); } - void clone_class1_records (split_context_t& split_context, - unsigned pair_pos_prime_id, - unsigned start, unsigned end) const + graph_result_t clone_class1_records (split_context_t& split_context, + unsigned pair_pos_prime_id, + unsigned start, unsigned end) const { PairPosFormat2* pair_pos_prime = (PairPosFormat2*) split_context.c.graph.object (pair_pos_prime_id).head; @@ -448,7 +441,7 @@ struct PairPosFormat2 : public OT::Layout::GPOS_impl::PairPosFormat2_4& device_table_indices, - unsigned old_value_record_index, - unsigned new_value_record_index) const + graph_result_t transfer_device_tables (split_context_t& split_context, + unsigned pair_pos_prime_id, + const hb_vector_t& device_table_indices, + unsigned old_value_record_index, + unsigned new_value_record_index) const { PairPosFormat2* pair_pos_prime = (PairPosFormat2*) split_context.c.graph.object (pair_pos_prime_id).head; @@ -491,16 +485,21 @@ struct PairPosFormat2 : public OT::Layout::GPOS_impl::PairPosFormat2_4values[new_value_record_index + i]); + (OT::Offset16*) &pair_pos_prime->values[new_value_record_index + i])); } + + // Restore correct ordering of the vertex links which are disturbed by move_child. + split_context.c.graph.vertices_[split_context.this_index].sort_real_links (); + + return Ok(); } - bool shrink (split_context_t& split_context, - unsigned count) + graph_result_t shrink (split_context_t& split_context, + unsigned count) { DEBUG_MSG (SUBSET_REPACK, nullptr, " Shrinking PairPosFormat2 (%u) to [0, %u).", @@ -508,20 +507,18 @@ struct PairPosFormat2 : public OT::Layout::GPOS_impl::PairPosFormat2_4= old_count) - return true; + return Ok(); graph_t& graph = split_context.c.graph; class1Count = count; - graph.vertices_[split_context.this_index].obj.tail -= - (old_count - count) * split_context.class1_record_size; + graph.vertices_[split_context.this_index].shrink_buffer( + (old_count - count) * split_context.class1_record_size); auto coverage = - graph.as_mutable_table (split_context.this_index, &this->coverage); - if (!coverage) return false; + TRY(graph.as_mutable_table (split_context.this_index, &this->coverage)); auto class_def_1 = - graph.as_mutable_table (split_context.this_index, &classDef1); - if (!class_def_1) return false; + TRY(graph.as_mutable_table (split_context.this_index, &classDef1)); auto klass_map = + coverage.table->iter () @@ -534,13 +531,12 @@ struct PairPosFormat2 : public OT::Layout::GPOS_impl::PairPosFormat2_4table_size ()); } - hb_hashmap_t + graph_result_t> get_all_device_tables (gsubgpos_graph_context_t& c, unsigned this_index) const { @@ -556,31 +552,28 @@ struct PairPosFormat2 : public OT::Layout::GPOS_impl::PairPosFormat2_4 get_coverage (gsubgpos_graph_context_t& c, + unsigned this_index) const { - unsigned coverage_id = c.graph.index_for_offset (this_index, &coverage); - if (coverage_id == HB_GRAPH_INVALID) - return &Null(Coverage); + unsigned coverage_id = TRY(c.graph.index_for_offset (this_index, &coverage)); auto& coverage_v = c.graph.vertices_[coverage_id]; - Coverage* coverage_table = (Coverage*) coverage_v.obj.head; - if (!coverage_table || !coverage_table->sanitize (coverage_v)) - return &Null(Coverage); + const Coverage* coverage_table = (const Coverage*) coverage_v.obj().head; + if (unlikely (!coverage_table)) return Err(INVALID_ARGUMENT); + TRY(coverage_table->sanitize (coverage_v)); + return coverage_table; } - const ClassDef* get_class_def_1 (gsubgpos_graph_context_t& c, - unsigned this_index) const + graph_result_t get_class_def_1 (gsubgpos_graph_context_t& c, + unsigned this_index) const { - unsigned class_def_1_id = c.graph.index_for_offset (this_index, &classDef1); - if (class_def_1_id == HB_GRAPH_INVALID) - return &Null(ClassDef); + unsigned class_def_1_id = TRY(c.graph.index_for_offset (this_index, &classDef1)); auto& class_def_1_v = c.graph.vertices_[class_def_1_id]; - ClassDef* class_def_1_table = (ClassDef*) class_def_1_v.obj.head; - if (!class_def_1_table || !class_def_1_table->sanitize (class_def_1_v)) - return &Null(ClassDef); + const ClassDef* class_def_1_table = (const ClassDef*) class_def_1_v.obj().head; + if (unlikely (!class_def_1_table)) return Err(INVALID_ARGUMENT); + TRY(class_def_1_table->sanitize (class_def_1_v)); return class_def_1_table; } @@ -597,24 +590,24 @@ struct PairPosFormat2 : public OT::Layout::GPOS_impl::PairPosFormat2_4 size_of (gsubgpos_graph_context_t& c, + unsigned this_index, + const void* offset) const { - const unsigned id = c.graph.index_for_offset (this_index, offset); - return c.graph.vertices_[id].table_size (); + const unsigned id = TRY(c.graph.index_for_offset (this_index, offset)); + return Ok(c.graph.vertices_[id].table_size ()); } }; struct PairPos : public OT::Layout::GPOS_impl::PairPos { - hb_vector_t split_subtables (gsubgpos_graph_context_t& c, - unsigned this_index) + graph_result_t> split_subtables (gsubgpos_graph_context_t& c, + unsigned this_index) { switch (u.format.v) { case 1: @@ -629,14 +622,14 @@ struct PairPos : public OT::Layout::GPOS_impl::PairPos // Don't split 24bit PairPos's. #endif default: - return hb_vector_t (); + return Ok(hb_vector_t ()); } } - bool sanitize (const graph_t::vertex_t& vertex) const + graph_result_t sanitize (const graph_t::vertex_t& vertex) const { - size_t vertex_len = vertex.obj.tail - vertex.obj.head; - if (vertex_len < u.format.v.get_size ()) return false; + size_t vertex_len = vertex.table_size(); + if (unlikely (vertex_len < u.format.v.get_size ())) return Err(SANITIZE_FAILURE); hb_barrier (); switch (u.format.v) { @@ -652,7 +645,7 @@ struct PairPos : public OT::Layout::GPOS_impl::PairPos #endif default: // We don't handle format 3 and 4 here. - return false; + return Err(SANITIZE_FAILURE); } } }; diff --git a/src/graph/serialize.hh b/src/graph/serialize.hh index 6723150b5..d33b736ad 100644 --- a/src/graph/serialize.hh +++ b/src/graph/serialize.hh @@ -27,6 +27,8 @@ #ifndef GRAPH_SERIALIZE_HH #define GRAPH_SERIALIZE_HH +#include "graph-result.hh" + namespace graph { struct overflow_record_t @@ -104,7 +106,7 @@ bool is_valid_offset (int64_t offset, /* * Will any offsets overflow on graph when it's serialized? */ -inline bool +inline graph_result_t will_overflow (graph_t& graph, hb_vector_t* overflows = nullptr) { @@ -116,13 +118,13 @@ will_overflow (graph_t& graph, for (unsigned parent_idx : graph.ordering_) { // Don't need to check virtual links for overflow - for (const auto& link : vertices.arrayZ[parent_idx].obj.real_links) + for (const auto& link : vertices.arrayZ[parent_idx].obj ().real_links) { int64_t offset = compute_offset (graph, parent_idx, link); if (likely (is_valid_offset (offset, link))) continue; - if (!overflows) return true; + if (!overflows) return Ok(true); overflow_record_t r; r.parent = parent_idx; @@ -134,8 +136,11 @@ will_overflow (graph_t& graph, } } - if (!overflows || overflows->in_error () || record_set.in_error ()) return false; - return overflows->length; + TRY (graph_result_t::from (record_set, ALLOCATION_FAILURE)); + if (overflows) + TRY (graph_result_t::from (*overflows, ALLOCATION_FAILURE)); + + return Ok((bool) (overflows && overflows->length)); } inline @@ -144,7 +149,13 @@ void print_overflows (graph_t& graph, { if (!DEBUG_ENABLED(SUBSET_REPACK)) return; - graph.update_parents (); + auto r = graph.update_parents (); + if (r.is_err()) { + DEBUG_MSG (SUBSET_REPACK, nullptr, "Unable to print overflows due to error updating parent links: %s", + to_string(r.error())); + return; + } + int limit = 10; for (const auto& o : overflows) { @@ -157,11 +168,11 @@ void print_overflows (graph_t& graph, "%4u (%4u in, %4u out, space %2u)", o.parent, parent.incoming_edges (), - parent.obj.real_links.length + parent.obj.virtual_links.length, + parent.obj ().real_links.length + parent.obj ().virtual_links.length, graph.space_for (o.parent), o.child, child.incoming_edges (), - child.obj.real_links.length + child.obj.virtual_links.length, + child.obj ().real_links.length + child.obj ().virtual_links.length, graph.space_for (o.child)); } if (overflows.length > 10) { @@ -231,16 +242,16 @@ void serialize_link (const hb_serialize_context_t::object_t::link_t& link, /* * serialize graph into the provided serialization buffer. */ -inline hb_blob_t* serialize (const graph_t& graph) +inline graph_result_t serialize (const graph_t& graph) { hb_vector_t buffer; size_t size = graph.total_size_in_bytes (); - if (!size) return hb_blob_get_empty (); + if (!size) return Ok(hb_blob_get_empty ()); - if (!buffer.alloc (size)) { + if (unlikely (!buffer.alloc (size))) { DEBUG_MSG (SUBSET_REPACK, nullptr, "Unable to allocate output buffer."); - return nullptr; + return Err(ALLOCATION_FAILURE); } hb_serialize_context_t c((void *) buffer, size); @@ -252,9 +263,9 @@ inline hb_blob_t* serialize (const graph_t& graph) // Maps from our obj id's to the id's used during this serialization. hb_vector_t id_map; - if (!id_map.resize(graph.ordering_.length)) { + if (unlikely (!id_map.resize(graph.ordering_.length))) { DEBUG_MSG (SUBSET_REPACK, nullptr, "Unable to allocate id_map buffer."); - return nullptr; + return Err(ALLOCATION_FAILURE); } for (int pos = graph.ordering_.length - 1; pos >= 0; pos--) { @@ -263,18 +274,18 @@ inline hb_blob_t* serialize (const graph_t& graph) auto& v = vertices[i]; - size_t size = v.obj.tail - v.obj.head; + size_t size = v.table_size (); char* start = c.allocate_size (size); - if (!start) { + if (unlikely (!start)) { DEBUG_MSG (SUBSET_REPACK, nullptr, "Buffer out of space."); - return nullptr; + return Err(ALLOCATION_FAILURE); } - hb_memcpy (start, v.obj.head, size); + hb_memcpy (start, v.obj ().head, size); // Only real links needs to be serialized. - for (const auto& link : v.obj.real_links) + for (const auto& link : v.obj ().real_links) serialize_link (link, start, size, id_map, &c); // All duplications are already encoded in the graph, so don't @@ -283,13 +294,17 @@ inline hb_blob_t* serialize (const graph_t& graph) } c.end_serialize (); - if (c.in_error ()) { + if (unlikely (c.in_error ())) { DEBUG_MSG (SUBSET_REPACK, nullptr, "Error during serialization. Err flag: %d", c.errors); - return nullptr; + if (c.errors & HB_SERIALIZE_ERROR_OFFSET_OVERFLOW) + return Err(OVERFLOW_RESOLUTION_FAILED); + return Err(ALLOCATION_FAILURE); } - return c.copy_blob (); + auto* blob = c.copy_blob (); + if (unlikely (!blob)) return Err(ALLOCATION_FAILURE); + return Ok(blob); } } // namespace graph diff --git a/src/graph/split-helpers.hh b/src/graph/split-helpers.hh index b6a24fad4..945cd39f3 100644 --- a/src/graph/split-helpers.hh +++ b/src/graph/split-helpers.hh @@ -27,16 +27,18 @@ #ifndef GRAPH_SPLIT_HELPERS_HH #define GRAPH_SPLIT_HELPERS_HH +#include "graph-result.hh" + namespace graph { template HB_INTERNAL -hb_vector_t actuate_subtable_split (Context& split_context, - const hb_vector_t& split_points) +graph_result_t> actuate_subtable_split (Context& split_context, + const hb_vector_t& split_points) { hb_vector_t new_objects; if (!split_points) - return new_objects; + return Ok(new_objects); for (unsigned i = 0; i < split_points.length; i++) { @@ -44,24 +46,14 @@ hb_vector_t actuate_subtable_split (Context& split_context, unsigned end = (i < split_points.length - 1) ? split_points[i + 1] : split_context.original_count (); - unsigned id = split_context.clone_range (start, end); - - if (id == HB_GRAPH_INVALID) - { - new_objects.reset (); - new_objects.ensure_error (); - return new_objects; - } + unsigned id = TRY (split_context.clone_range (start, end)); new_objects.push (id); + TRY (graph_result_t::from (new_objects, ALLOCATION_FAILURE)); } - if (!split_context.shrink (split_points[0])) - { - new_objects.reset (); - new_objects.ensure_error (); - } + TRY (split_context.shrink (split_points[0])); - return new_objects; + return Ok(new_objects); } } diff --git a/src/graph/test-classdef-graph.cc b/src/graph/test-classdef-graph.cc index d3e8d892b..bc198d304 100644 --- a/src/graph/test-classdef-graph.cc +++ b/src/graph/test-classdef-graph.cc @@ -117,7 +117,7 @@ static HB_UNUSED bool check_add_class_def_size(graph::class_def_size_estimator_t static HB_UNUSED bool check_add_class_def_size (const gid_and_class_list_t& list, unsigned klass) { - graph::class_def_size_estimator_t estimator (list.iter ()); + graph::class_def_size_estimator_t estimator = *graph::class_def_size_estimator_t::create (list.iter ()); unsigned result = estimator.add_class_def_size (klass); auto filtered_it = @@ -228,7 +228,7 @@ static void test_running_class_and_coverage_size_estimates () { {12, 3}, }; - graph::class_def_size_estimator_t estimator1(consecutive_map.iter()); + graph::class_def_size_estimator_t estimator1 = *graph::class_def_size_estimator_t::create (consecutive_map.iter()); hb_always_assert(check_add_class_def_size(estimator1, consecutive_map, 1, {1})); hb_always_assert(check_add_class_def_size(estimator1, consecutive_map, 2, {1, 2})); hb_always_assert(check_add_class_def_size(estimator1, consecutive_map, 2, {1, 2})); // check that adding the same class again works @@ -260,7 +260,7 @@ static void test_running_class_and_coverage_size_estimates () { {15, 3}, }; - graph::class_def_size_estimator_t estimator2(non_consecutive_map.iter()); + graph::class_def_size_estimator_t estimator2 = *graph::class_def_size_estimator_t::create (non_consecutive_map.iter()); hb_always_assert(check_add_class_def_size(estimator2, non_consecutive_map, 1, {1})); hb_always_assert(check_add_class_def_size(estimator2, non_consecutive_map, 2, {1, 2})); hb_always_assert(check_add_class_def_size(estimator2, non_consecutive_map, 3, {1, 2, 3})); @@ -277,7 +277,7 @@ static void test_running_class_size_estimates_with_locally_consecutive_glyphs () {7, 3}, }; - graph::class_def_size_estimator_t estimator(map.iter()); + graph::class_def_size_estimator_t estimator = *graph::class_def_size_estimator_t::create (map.iter()); hb_always_assert(check_add_class_def_size(estimator, map, 1, {1})); hb_always_assert(check_add_class_def_size(estimator, map, 2, {1, 2})); hb_always_assert(check_add_class_def_size(estimator, map, 3, {1, 2, 3})); diff --git a/src/hb-repacker.hh b/src/hb-repacker.hh index 3b4b33a26..b64bb2df7 100644 --- a/src/hb-repacker.hh +++ b/src/hb-repacker.hh @@ -35,6 +35,7 @@ #include "graph/serialize.hh" using graph::graph_t; +using graph::graph_result_t; /* * For a detailed writeup on the overflow resolution algorithm see: @@ -69,7 +70,7 @@ struct lookup_size_t }; static inline -bool _presplit_subtables_if_needed (graph::gsubgpos_graph_context_t& ext_context) +graph_result_t _presplit_subtables_if_needed (graph::gsubgpos_graph_context_t& ext_context) { // For each lookup this will check the size of subtables and split them as needed // so that no subtable is at risk of overflowing. (where we support splitting for @@ -87,11 +88,10 @@ bool _presplit_subtables_if_needed (graph::gsubgpos_graph_context_t& ext_context for (unsigned lookup_index : lookup_indices) { graph::Lookup* lookup = ext_context.lookups.get(lookup_index); - if (!lookup->split_subtables_if_needed (ext_context, lookup_index)) - return false; + TRY (lookup->split_subtables_if_needed (ext_context, lookup_index)); } - return true; + return Ok(); } /* @@ -99,7 +99,7 @@ bool _presplit_subtables_if_needed (graph::gsubgpos_graph_context_t& ext_context * to extension lookups. */ static inline -bool _promote_extensions_if_needed (graph::gsubgpos_graph_context_t& ext_context) +graph_result_t _promote_extensions_if_needed (graph::gsubgpos_graph_context_t& ext_context) { // Simple Algorithm (v1, current): // 1. Calculate how many bytes each non-extension lookup consumes. @@ -117,7 +117,7 @@ bool _promote_extensions_if_needed (graph::gsubgpos_graph_context_t& ext_context // TODO(garretrieger): also support extension promotion during iterative resolution phase, then // we can use a less conservative threshold here. // TODO(grieger): skip this for the 24 bit case. - if (!ext_context.lookups) return true; + if (!ext_context.lookups) return Ok(true); unsigned total_lookup_table_sizes = 0; hb_vector_t lookup_sizes; @@ -132,7 +132,7 @@ bool _promote_extensions_if_needed (graph::gsubgpos_graph_context_t& ext_context hb_set_t visited; lookup_sizes.push (lookup_size_t { lookup_index, - ext_context.graph.find_subgraph_size (lookup_index, visited), + ext_context.graph.find_subgraph_size (lookup_index, visited).value_or (0), lookup->number_of_subtables (), }); } @@ -167,7 +167,7 @@ bool _promote_extensions_if_needed (graph::gsubgpos_graph_context_t& ext_context { size_t lookup_size = ext_context.graph.vertices_[p.lookup_index].table_size (); hb_set_t visited; - size_t subtables_size = ext_context.graph.find_subgraph_size (p.lookup_index, visited, 1) - lookup_size; + size_t subtables_size = ext_context.graph.find_subgraph_size (p.lookup_index, visited, 1).value_or (0) - lookup_size; size_t remaining_size = p.size - subtables_size - lookup_size; l3_l4_size += subtables_size; @@ -181,16 +181,15 @@ bool _promote_extensions_if_needed (graph::gsubgpos_graph_context_t& ext_context layers_full = true; } - if (!ext_context.lookups.get(p.lookup_index)->make_extension (ext_context, p.lookup_index)) - return false; + TRY (ext_context.lookups.get(p.lookup_index)->make_extension (ext_context, p.lookup_index)); } - return true; + return Ok(true); } static inline -bool _try_isolating_subgraphs (const hb_vector_t& overflows, - graph_t& sorted_graph) +graph_result_t _try_isolating_subgraphs (const hb_vector_t& overflows, + graph_t& sorted_graph) { unsigned space = 0; hb_set_t roots_to_isolate; @@ -212,7 +211,7 @@ bool _try_isolating_subgraphs (const hb_vector_t& over roots_to_isolate.add(root); } - if (!roots_to_isolate) return false; + if (!roots_to_isolate) return Ok(false); unsigned maximum_to_move = hb_max ((sorted_graph.num_roots_for_space (space) / 2u), 1u); if (roots_to_isolate.get_population () > maximum_to_move) { @@ -238,16 +237,16 @@ bool _try_isolating_subgraphs (const hb_vector_t& over roots_to_isolate.get_population (), sorted_graph.next_space ()); - if (!sorted_graph.isolate_subgraph (roots_to_isolate)) return false; - sorted_graph.move_to_new_space (roots_to_isolate); + if (!TRY (sorted_graph.isolate_subgraph (roots_to_isolate))) return Ok(false); + TRY (sorted_graph.move_to_new_space (roots_to_isolate)); - return true; + return Ok(true); } static inline -bool _resolve_shared_overflow(const hb_vector_t& overflows, - int overflow_index, - graph_t& sorted_graph) +graph_result_t _resolve_shared_overflow(const hb_vector_t& overflows, + int overflow_index, + graph_t& sorted_graph) { const graph::overflow_record_t& r = overflows[overflow_index]; @@ -263,8 +262,8 @@ bool _resolve_shared_overflow(const hb_vector_t& overf } } - unsigned result = sorted_graph.duplicate(&parents, r.child); - if (result == (unsigned) -1 && parents.get_population() > 2) { + auto result = sorted_graph.duplicate(&parents, r.child); + if (!result.is_ok () && parents.get_population() > 2) { // All links to the child are overflowing, so we can't include all // in the duplication. Remove one parent from the duplication. // Remove the lowest index parent, which will be the closest to the child. @@ -272,7 +271,7 @@ bool _resolve_shared_overflow(const hb_vector_t& overf result = sorted_graph.duplicate(&parents, r.child); } - if (result == (unsigned) -1) return false; + if (!result.is_ok ()) return Ok(false); if (parents.get_population() > 1) { // If the duplicated node has more than one parent pre-emptively raise it's priority to the maximum. @@ -286,16 +285,16 @@ bool _resolve_shared_overflow(const hb_vector_t& overf // to move nodes closer, but only for non-shared nodes. Since this node is shared, it will simply be given // further duplication which defeats the attempt to duplicate with multiple parents. To fix this we // pre-emptively raise priority now which allows the duplicated node to pack into the same layer as it's parents. - sorted_graph.vertices_[result].give_max_priority(); + sorted_graph.vertices_[*result].give_max_priority(); } - return true; + return Ok(true); } static inline -bool _process_overflows (const hb_vector_t& overflows, - hb_set_t& priority_bumped_parents, - graph_t& sorted_graph) +graph_result_t _process_overflows (const hb_vector_t& overflows, + hb_set_t& priority_bumped_parents, + graph_t& sorted_graph) { bool resolution_attempted = false; @@ -307,8 +306,8 @@ bool _process_overflows (const hb_vector_t& overflows, { // The child object is shared, we may be able to eliminate the overflow // by duplicating it. - if (_resolve_shared_overflow(overflows, i, sorted_graph)) - return true; + if (TRY (_resolve_shared_overflow(overflows, i, sorted_graph))) + return Ok(true); // Sometimes we can't duplicate a node which looks shared because it's not actually shared // (eg. all links from the same parent) in this case continue on to other resolution options. @@ -327,7 +326,7 @@ bool _process_overflows (const hb_vector_t& overflows, // is < then the total size of the children (and the parent can be moved). // Since in that case moving the parent will cause a smaller increase in // the length of other offsets. - if (sorted_graph.raise_childrens_priority (r.parent)) { + if (TRY (sorted_graph.raise_childrens_priority (r.parent))) { priority_bumped_parents.add (r.parent); resolution_attempted = true; } @@ -339,71 +338,76 @@ bool _process_overflows (const hb_vector_t& overflows, // - Table splitting. } - return resolution_attempted; + return Ok(resolution_attempted); } -inline bool +inline graph_result_t +_assign_spaces_and_sort (graph_t& sorted_graph /* IN/OUT */) +{ + DEBUG_MSG (SUBSET_REPACK, nullptr, "Assigning spaces to 32 bit subgraphs."); + if (TRY (sorted_graph.assign_spaces ())) + return sorted_graph.sort_shortest_distance (); + else + return sorted_graph.sort_shortest_distance_if_needed (); +} + +inline graph_result_t +_gsub_gpos_specialization (hb_tag_t table_tag, + bool always_recalculate_extensions, + graph_t& sorted_graph /* IN/OUT */) +{ + DEBUG_MSG (SUBSET_REPACK, nullptr, "Applying GSUB/GPOS repacking specializations."); + if (!always_recalculate_extensions) return _assign_spaces_and_sort (sorted_graph); + + auto context_res = graph::gsubgpos_graph_context_t::create (table_tag, sorted_graph); + + if (unlikely (context_res.is_err())) { + if (context_res.error() == graph::SANITIZE_FAILURE) + // Sanitize failures are ignored, and we just skip splitting/extension promotion which needs a valid + // GSUB/GPOS + return _assign_spaces_and_sort (sorted_graph); + else + // All other errors are propagated. + return Err(context_res.error()); + } + + // Otherwise we have a valid GSUB/GPOS table and can try extension promotion and splitting + auto& ext_context = *context_res; + DEBUG_MSG (SUBSET_REPACK, nullptr, "Splitting subtables if needed."); + TRY (_presplit_subtables_if_needed (ext_context)); + + DEBUG_MSG (SUBSET_REPACK, nullptr, "Promoting lookups to extensions if needed."); + TRY (_promote_extensions_if_needed (ext_context)); + + // an additional sorting is needed before assign_spaces () which requires + // correct topological ordering to find space roots + TRY (sorted_graph.sort_shortest_distance_if_needed ()); + + if (!TRY (graph::will_overflow (sorted_graph))) return Ok(); + return _assign_spaces_and_sort (sorted_graph); +} + +inline graph_result_t hb_resolve_graph_overflows (hb_tag_t table_tag, unsigned max_rounds , bool always_recalculate_extensions, graph_t& sorted_graph /* IN/OUT */) { DEBUG_MSG (SUBSET_REPACK, nullptr, "Repacking %c%c%c%c.", HB_UNTAG(table_tag)); - sorted_graph.sort_shortest_distance (); - if (sorted_graph.in_error ()) - { - DEBUG_MSG (SUBSET_REPACK, nullptr, "Sorted graph in error state after initial sort."); - return false; - } + TRY (sorted_graph.sort_shortest_distance ()); - bool will_overflow = graph::will_overflow (sorted_graph); - if (!will_overflow) - return true; + if (!TRY (graph::will_overflow (sorted_graph))) + return Ok(); bool is_gsub_or_gpos = (table_tag == HB_OT_TAG_GPOS || table_tag == HB_OT_TAG_GSUB); - graph::gsubgpos_graph_context_t ext_context (table_tag, sorted_graph); - if (is_gsub_or_gpos && will_overflow) - { - DEBUG_MSG (SUBSET_REPACK, nullptr, "Applying GSUB/GPOS repacking specializations."); - if (always_recalculate_extensions) - { - DEBUG_MSG (SUBSET_REPACK, nullptr, "Splitting subtables if needed."); - if (!_presplit_subtables_if_needed (ext_context)) { - DEBUG_MSG (SUBSET_REPACK, nullptr, "Subtable splitting failed."); - return false; - } - - DEBUG_MSG (SUBSET_REPACK, nullptr, "Promoting lookups to extensions if needed."); - if (!_promote_extensions_if_needed (ext_context)) { - DEBUG_MSG (SUBSET_REPACK, nullptr, "Extensions promotion failed."); - return false; - } - - // an additional sorting is needed before assign_spaces () which requires - // correct topological ordering to find space roots - sorted_graph.sort_shortest_distance_if_needed (); - if (sorted_graph.in_error ()) - { - DEBUG_MSG (SUBSET_REPACK, nullptr, "Sorted graph in error state."); - return false; - } - - if (!graph::will_overflow (sorted_graph)) return true; - } - - DEBUG_MSG (SUBSET_REPACK, nullptr, "Assigning spaces to 32 bit subgraphs."); - if (sorted_graph.assign_spaces ()) - sorted_graph.sort_shortest_distance (); - else - sorted_graph.sort_shortest_distance_if_needed (); - } + if (is_gsub_or_gpos) + TRY(_gsub_gpos_specialization (table_tag, always_recalculate_extensions, sorted_graph)); unsigned round = 0; unsigned total_iterations = 0; hb_vector_t overflows; // TODO(garretrieger): select a good limit for max rounds. - while (!sorted_graph.in_error () - && graph::will_overflow (sorted_graph, &overflows) + while (TRY (graph::will_overflow (sorted_graph, &overflows)) && round < max_rounds && total_iterations < HB_REPACKER_MAX_ITERATIONS) { DEBUG_MSG (SUBSET_REPACK, nullptr, "=== Overflow resolution round %u ===", round); @@ -412,32 +416,20 @@ hb_resolve_graph_overflows (hb_tag_t table_tag, total_iterations++; hb_set_t priority_bumped_parents; - if (!_try_isolating_subgraphs (overflows, sorted_graph)) + if (!TRY (_try_isolating_subgraphs (overflows, sorted_graph))) { round++; - if (!_process_overflows (overflows, priority_bumped_parents, sorted_graph)) + if (!TRY (_process_overflows (overflows, priority_bumped_parents, sorted_graph))) { DEBUG_MSG (SUBSET_REPACK, nullptr, "No resolution available :("); break; } } - if (sorted_graph.in_error ()) - { - DEBUG_MSG (SUBSET_REPACK, nullptr, "Sorted graph in error state."); - return false; - } - - sorted_graph.sort_shortest_distance (); + TRY (sorted_graph.sort_shortest_distance ()); } - if (sorted_graph.in_error ()) - { - DEBUG_MSG (SUBSET_REPACK, nullptr, "Sorted graph in error state."); - return false; - } - - if (graph::will_overflow (sorted_graph)) + if (unlikely (TRY (graph::will_overflow (sorted_graph)))) { if (is_gsub_or_gpos && !always_recalculate_extensions) { // If this a GSUB/GPOS table and we didn't try to extension promotion and table splitting then @@ -447,10 +439,10 @@ hb_resolve_graph_overflows (hb_tag_t table_tag, } DEBUG_MSG (SUBSET_REPACK, nullptr, "Offset overflow resolution failed."); - return false; + return Err(graph::OVERFLOW_RESOLUTION_FAILED); } - return true; + return Ok(); } /* @@ -472,31 +464,32 @@ hb_resolve_overflows (const T& packed, hb_tag_t table_tag, unsigned max_rounds = 32, bool recalculate_extensions = false) { - graph_t sorted_graph (packed); - if (sorted_graph.in_error ()) + auto graph_res = graph_t::create (packed); + if (!graph_res.is_ok ()) { - // Invalid graph definition. - return nullptr; - } - - if (!sorted_graph.is_fully_connected ()) - { - sorted_graph.print_orphaned_nodes (); - return nullptr; - } - - if (sorted_graph.in_error ()) - { - // Allocations failed somewhere DEBUG_MSG (SUBSET_REPACK, nullptr, - "Graph is in error, likely due to a memory allocation error."); + "Graph creation failed, cause: %s", graph::to_string(graph_res.error())); + return nullptr; + } + graph_t sorted_graph = std::move (*graph_res); + + auto resolve_res = hb_resolve_graph_overflows (table_tag, max_rounds, recalculate_extensions, sorted_graph); + if (resolve_res.is_err ()) + { + DEBUG_MSG (SUBSET_REPACK, nullptr, + "Overflow resolution failed, cause: %s", graph::to_string(resolve_res.error())); return nullptr; } - if (!hb_resolve_graph_overflows (table_tag, max_rounds, recalculate_extensions, sorted_graph)) + auto serialize_res = graph::serialize (sorted_graph); + if (serialize_res.is_err ()) + { + DEBUG_MSG (SUBSET_REPACK, nullptr, + "Serialization failed, cause: %s", graph::to_string(serialize_res.error())); return nullptr; + } - return graph::serialize (sorted_graph); + return *serialize_res; } #endif /* HB_REPACKER_HH */ diff --git a/src/hb-result.hh b/src/hb-result.hh index 87939a9f3..a6c23325a 100644 --- a/src/hb-result.hh +++ b/src/hb-result.hh @@ -196,6 +196,7 @@ struct HB_NODISCARD_STRUCT hb_result_t new (std::addressof (err_)) E (e.error); } + // TODO XXXX disable direct construction completely. // Construct directly from error E (when neither T or E are convertible into each other) template (v)); } + // Move fallible into a result if it's in_error() method returns false. + // TODO XXXX add test + static hb_result_t from (T&& fallible, E error_value) { + if (fallible.in_error()) { + return Err(error_value); + } + return Ok(fallible); + } + bool is_ok () const { return is_ok_; } bool is_err () const { return !is_ok_; } explicit operator bool () const { return is_ok (); } @@ -404,7 +414,7 @@ struct HB_NODISCARD_STRUCT hb_result_t // V is any class which has an in_error() method. This checks the result // of in_error() and returns either Ok() or Err(error_value). template - static hb_result_t from(const V& fallible, E error_value) { + static hb_result_t from (const V& fallible, E error_value) { if (fallible.in_error()) { return Err(error_value); } diff --git a/src/hb-serialize.hh b/src/hb-serialize.hh index fd91784de..7b2bbb59f 100644 --- a/src/hb-serialize.hh +++ b/src/hb-serialize.hh @@ -87,6 +87,11 @@ struct hb_serialize_context_t virtual_links.push (o.virtual_links[i]); } + bool in_error () const + { + return real_links.in_error() || virtual_links.in_error(); + } + bool add_virtual_link (objidx_t objidx) { if (!objidx) diff --git a/src/meson.build b/src/meson.build index 1415d064e..23386ae74 100644 --- a/src/meson.build +++ b/src/meson.build @@ -418,6 +418,7 @@ hb_subset_sources = files( 'hb-subset-table-cff.cc', 'hb-subset-table-color.cc', 'hb-subset-table-other.cc', + 'graph/graph-result.hh', 'graph/gsubgpos-context.cc', 'graph/gsubgpos-context.hh', 'graph/gsubgpos-graph.hh', diff --git a/src/test-repacker.cc b/src/test-repacker.cc index a888f2e40..6a2f012af 100644 --- a/src/test-repacker.cc +++ b/src/test-repacker.cc @@ -483,30 +483,33 @@ static void run_resolve_overflow_test (const char* name, printf (">>> Testing overflowing resolution for %s\n", name); - graph_t graph (overflowing.object_graph ()); + graph_t graph = graph_t::create (overflowing.object_graph ()).value (); - graph_t expected_graph (expected.object_graph ()); - if (graph::will_overflow (expected_graph)) + graph_t expected_graph = graph_t::create (expected.object_graph ()).value (); + if (graph::will_overflow (expected_graph).value ()) { if (check_binary_equivalence) { printf("when binary equivalence checking is enabled, the expected graph cannot overflow."); hb_always_assert(!check_binary_equivalence); } - expected_graph.assign_spaces (); - expected_graph.sort_shortest_distance (); + hb_always_assert (expected_graph.assign_spaces ().is_ok ()); + hb_always_assert (expected_graph.sort_shortest_distance ().is_ok ()); } // Check that overflow resolution succeeds hb_always_assert (overflowing.offset_overflow ()); - hb_always_assert (hb_resolve_graph_overflows (tag, + auto r = hb_resolve_graph_overflows (tag, num_iterations, recalculate_extensions, - graph)); + graph); + if (r.is_err()) + printf("run_resolve_overflow_test: overflow resolution failed, cause: %s\n", graph::to_string(r.error())); + hb_always_assert (r.is_ok()); // Check the graphs can be serialized. - hb_blob_t* out1 = graph::serialize (graph); + hb_blob_t* out1 = graph::serialize (graph).value (); hb_always_assert (out1); - hb_blob_t* out2 = graph::serialize (expected_graph); + hb_blob_t* out2 = graph::serialize (expected_graph).value (); hb_always_assert (out2); if (check_binary_equivalence) { unsigned l1, l2; @@ -1894,10 +1897,9 @@ static void test_sort_shortest () hb_serialize_context_t e (buffer_e, buffer_size); populate_serializer_complex_2 (&a); - graph_t graph (a.object_graph ()); - graph.sort_shortest_distance (); + graph_t graph = graph_t::create (a.object_graph ()).value (); + hb_always_assert (graph.sort_shortest_distance ().is_ok()); graph.normalize(); - hb_always_assert (!graph.in_error ()); // Expected graph e.start_serialize(); @@ -1920,7 +1922,7 @@ static void test_sort_shortest () e.pop_pack (false); e.end_serialize(); - graph_t expected(e.object_graph()); + graph_t expected = graph_t::create (e.object_graph ()).value (); expected.normalize(); assert(expected == graph); @@ -1938,8 +1940,8 @@ static void test_duplicate_leaf () hb_serialize_context_t e (buffer_e, buffer_size); populate_serializer_complex_2 (&a); - graph_t graph (a.object_graph ()); - graph.duplicate (4, 1, false); + graph_t graph = graph_t::create (a.object_graph ()).value (); + hb_always_assert (graph.duplicate (4, 1, false).is_ok ()); graph.normalize(); e.start_serialize(); @@ -1962,7 +1964,7 @@ static void test_duplicate_leaf () add_offset(mn, &e); e.pop_pack(false); - graph_t expected(e.object_graph()); + graph_t expected = graph_t::create (e.object_graph ()).value (); expected.normalize(); assert(expected == graph); @@ -1978,8 +1980,8 @@ static void test_duplicate_interior () hb_serialize_context_t c (buffer, buffer_size); populate_serializer_complex_3 (&c); - graph_t graph (c.object_graph ()); - graph.duplicate (3, 2, false); + graph_t graph = graph_t::create (c.object_graph ()).value (); + hb_always_assert (graph.duplicate (3, 2, false).is_ok ()); hb_always_assert(strncmp (graph.object (6).head, "jkl", 3) == 0); hb_always_assert(graph.object (6).real_links.length == 1); @@ -2021,8 +2023,8 @@ test_serialize () populate_serializer_simple (&c1); hb_bytes_t expected = c1.copy_bytes (); - graph_t graph (c1.object_graph ()); - hb_blob_t* out = graph::serialize (graph); + graph_t graph = graph_t::create (c1.object_graph ()).value (); + hb_blob_t* out = graph::serialize (graph).value (); free (buffer_1); hb_bytes_t actual = out->as_bytes (); @@ -2038,9 +2040,9 @@ static void test_will_overflow_1 () hb_serialize_context_t c (buffer, buffer_size); populate_serializer_complex_2 (&c); - graph_t graph (c.object_graph ()); + graph_t graph = graph_t::create (c.object_graph ()).value (); - hb_always_assert (!graph::will_overflow (graph, nullptr)); + hb_always_assert (!graph::will_overflow (graph, nullptr).value ()); free (buffer); } @@ -2051,9 +2053,9 @@ static void test_will_overflow_2 () void* buffer = malloc (buffer_size); hb_serialize_context_t c (buffer, buffer_size); populate_serializer_with_overflow (&c); - graph_t graph (c.object_graph ()); + graph_t graph = graph_t::create (c.object_graph ()).value (); - hb_always_assert (graph::will_overflow (graph, nullptr)); + hb_always_assert (graph::will_overflow (graph, nullptr).value ()); free (buffer); } @@ -2064,9 +2066,9 @@ static void test_will_overflow_3 () void* buffer = malloc (buffer_size); hb_serialize_context_t c (buffer, buffer_size); populate_serializer_with_dedup_overflow (&c); - graph_t graph (c.object_graph ()); + graph_t graph = graph_t::create (c.object_graph ()).value (); - hb_always_assert (graph::will_overflow (graph, nullptr)); + hb_always_assert (graph::will_overflow (graph, nullptr).value ()); free (buffer); } @@ -2077,7 +2079,7 @@ static void test_resolve_overflows_via_sort () void* buffer = malloc (buffer_size); hb_serialize_context_t c (buffer, buffer_size); populate_serializer_with_overflow (&c); - graph_t graph (c.object_graph ()); + graph_t graph = graph_t::create (c.object_graph ()).value (); hb_blob_t* out = hb_resolve_overflows (c.object_graph (), HB_TAG_NONE); hb_always_assert (out); @@ -2094,7 +2096,7 @@ static void test_resolve_overflows_via_duplication () void* buffer = malloc (buffer_size); hb_serialize_context_t c (buffer, buffer_size); populate_serializer_with_dedup_overflow (&c); - graph_t graph (c.object_graph ()); + graph_t graph = graph_t::create (c.object_graph ()).value (); hb_blob_t* out = hb_resolve_overflows (c.object_graph (), HB_TAG_NONE); hb_always_assert (out); @@ -2111,7 +2113,7 @@ static void test_resolve_overflows_via_multiple_duplications () void* buffer = malloc (buffer_size); hb_serialize_context_t c (buffer, buffer_size); populate_serializer_with_multiple_dedup_overflow (&c); - graph_t graph (c.object_graph ()); + graph_t graph = graph_t::create (c.object_graph ()).value (); hb_blob_t* out = hb_resolve_overflows (c.object_graph (), HB_TAG_NONE, 5); hb_always_assert (out); @@ -2145,7 +2147,7 @@ static void test_resolve_overflows_via_isolation () void* buffer = malloc (buffer_size); hb_serialize_context_t c (buffer, buffer_size); populate_serializer_with_isolation_overflow (&c); - graph_t graph (c.object_graph ()); + graph_t graph = graph_t::create (c.object_graph ()).value (); hb_always_assert (c.offset_overflow ()); hb_blob_t* out = hb_resolve_overflows (c.object_graph (), HB_TAG ('G', 'S', 'U', 'B'), 0); @@ -2220,7 +2222,7 @@ static void test_resolve_overflows_via_isolation_spaces () void* buffer = malloc (buffer_size); hb_serialize_context_t c (buffer, buffer_size); populate_serializer_with_isolation_overflow_spaces (&c); - graph_t graph (c.object_graph ()); + graph_t graph = graph_t::create (c.object_graph ()).value (); hb_always_assert (c.offset_overflow ()); hb_blob_t* out = hb_resolve_overflows (c.object_graph (), HB_TAG ('G', 'S', 'U', 'B'), 0); @@ -2241,7 +2243,7 @@ static void test_resolve_mixed_overflows_via_isolation_spaces () void* buffer = malloc (buffer_size); hb_serialize_context_t c (buffer, buffer_size); populate_serializer_with_24_and_32_bit_offsets (&c); - graph_t graph (c.object_graph ()); + graph_t graph = graph_t::create (c.object_graph ()).value (); hb_always_assert (c.offset_overflow ()); hb_blob_t* out = hb_resolve_overflows (c.object_graph (), HB_TAG ('G', 'S', 'U', 'B'), 0); @@ -2749,32 +2751,30 @@ test_deep_graph_traversal () } c.end_serialize (); - graph_t graph (c.object_graph ()); - hb_always_assert (!graph.in_error ()); + graph_t graph = graph_t::create (c.object_graph ()).value (); // Test find_subgraph (set) hb_set_t visited_set; - graph.find_subgraph (graph.root_idx (), visited_set); + hb_always_assert (graph.find_subgraph (graph.root_idx (), visited_set).is_ok ()); hb_always_assert (visited_set.get_population () == 2001); // Test find_subgraph_size hb_set_t size_set; - size_t sz = graph.find_subgraph_size (graph.root_idx (), size_set); + size_t sz = graph.find_subgraph_size (graph.root_idx (), size_set).value (); hb_always_assert (sz == 4 + 2000 * 6); // Test find_subgraph (map) hb_map_t map; map.set (graph.root_idx (), 1); - graph.find_subgraph (graph.root_idx (), map); + hb_always_assert (graph.find_subgraph (graph.root_idx (), map).is_ok ()); hb_always_assert (map.get_population () == 2001); // Test assign_spaces (which exercises find_connected_nodes and find_space_roots) - graph.assign_spaces (); - hb_always_assert (!graph.in_error ()); + hb_always_assert (graph.assign_spaces ().is_ok ()); // Test duplicate_subgraph hb_map_t index_map; - graph.duplicate_subgraph (graph.root_idx (), index_map); + hb_always_assert (graph.duplicate_subgraph (graph.root_idx (), index_map).is_ok ()); hb_always_assert (index_map.get_population () == 2001); free (buffer); @@ -2801,11 +2801,10 @@ test_32bit_roots_traversal () c.pop_pack (false); c.end_serialize (); - graph_t graph (c.object_graph ()); - hb_always_assert (!graph.in_error ()); + graph_t graph = graph_t::create (c.object_graph ()).value (); hb_set_t roots; - graph.find_32bit_roots (graph.root_idx (), roots); + hb_always_assert (graph.find_32bit_roots (graph.root_idx (), roots).is_ok ()); hb_always_assert (roots.has (leaf1 - 1)); hb_always_assert (roots.has (leaf2 - 1)); hb_always_assert (!roots.has (mid - 1)); @@ -2840,11 +2839,10 @@ test_32bit_roots_traversal () c2.end_serialize (); - graph_t graph2 (c2.object_graph ()); - hb_always_assert (!graph2.in_error ()); + graph_t graph2 = graph_t::create (c2.object_graph ()).value (); hb_set_t roots2; - graph2.find_32bit_roots (graph2.root_idx (), roots2); + hb_always_assert (graph2.find_32bit_roots (graph2.root_idx (), roots2).is_ok ()); hb_always_assert (roots2.get_population () == 1); hb_always_assert (roots2.has (a - 1)); hb_always_assert (!roots2.has (b - 1)); @@ -2859,16 +2857,15 @@ static void test_invalid_link_objidx () hb_serialize_context_t c (buffer, buffer_size); populate_serializer_complex_2 (&c); - graph_t graph (c.object_graph ()); - hb_always_assert (!graph.in_error ()); + graph_t graph = graph_t::create (c.object_graph ()).value (); // Poison a link to point to (unsigned) -1 - graph.vertices_[graph.root_idx ()].obj.real_links[0].objidx = (unsigned) -1; + auto links = graph.vertices_[graph.root_idx ()].real_links_writer(); + links->objidx = (unsigned) -1; // Running Dijkstra / shortest distance sorting must not crash or OOB access, - // and must mark the graph in error. - graph.sort_shortest_distance (); - hb_always_assert (graph.in_error ()); + // and must return an error. + hb_always_assert (!graph.sort_shortest_distance ().is_ok ()); free (buffer); } @@ -2880,18 +2877,15 @@ static void test_invalid_link_add_and_move () hb_serialize_context_t c (buffer, buffer_size); populate_serializer_complex_2 (&c); - graph_t graph (c.object_graph ()); - hb_always_assert (!graph.in_error ()); + graph_t graph = graph_t::create (c.object_graph ()).value (); // add_link with out-of-bounds child OT::Offset16 dummy; - graph.add_link (&dummy, 0, (unsigned) -1); - hb_always_assert (graph.in_error ()); + hb_always_assert (!graph.add_link (&dummy, 0, (unsigned) -1).is_ok ()); // move_child with non-existent offset - unsigned res = graph.move_child (0, &dummy, 1, &dummy); - hb_always_assert (res == (unsigned) -1); - hb_always_assert (graph.in_error ()); + auto res = graph.move_child (0, &dummy, 1, &dummy); + hb_always_assert (!res.is_ok ()); free (buffer); } diff --git a/src/test-result.cc b/src/test-result.cc index 82b2547a0..f6da6fb6d 100644 --- a/src/test-result.cc +++ b/src/test-result.cc @@ -95,7 +95,7 @@ static result try_caller (bool fail1, bool fail2) static result try_caller_void (bool fail) { TRY (try_callee_void (fail, ERR_C)); - return Ok (); + return Ok(); } static result try_caller_type_change (bool fail) @@ -114,8 +114,8 @@ static void test_ok_basic () hb_always_assert (*r == 42); hb_always_assert (r.value_or (0) == 42); hb_always_assert (r.value_or_default () == 42); - hb_always_assert (r == Ok (42)); - hb_always_assert (Ok (42) == r); + hb_always_assert (r == Ok(42)); + hb_always_assert (Ok(42) == r); } static void test_err_basic () @@ -127,19 +127,19 @@ static void test_err_basic () hb_always_assert (r.error () == ERR_A); hb_always_assert (r.value_or (99) == 99); hb_always_assert (r.value_or_default () == 0); - hb_always_assert (r == Err (ERR_A)); - hb_always_assert (Err (ERR_A) == r); - hb_always_assert (r != Err (ERR_B)); - hb_always_assert (Err (ERR_B) != r); + hb_always_assert (r == Err(ERR_A)); + hb_always_assert (Err(ERR_A) == r); + hb_always_assert (r != Err(ERR_B)); + hb_always_assert (Err(ERR_B) != r); } static void test_explicit_ok_err () { - result r1 = Ok (100u); + result r1 = Ok(100u); hb_always_assert (r1.is_ok ()); hb_always_assert (r1.value () == 100u); - result r2 = Err (ERR_A); + result r2 = Err(ERR_A); hb_always_assert (r2.is_err ()); hb_always_assert (r2.error () == ERR_A); } @@ -157,26 +157,26 @@ static void test_pointers () static void test_void () { - result r1 = Ok (); + result r1 = Ok(); hb_always_assert (r1.is_ok ()); hb_always_assert (!r1.is_err ()); hb_always_assert ((bool) r1); - hb_always_assert (r1 == Ok ()); - hb_always_assert (r1 != Err (ERR_A)); + hb_always_assert (r1 == Ok()); + hb_always_assert (r1 != Err(ERR_A)); hb_always_assert (Ok() == r1); - hb_always_assert (Err (ERR_A) != r1); + hb_always_assert (Err(ERR_A) != r1); - result r2 = Err (ERR_A); + result r2 = Err(ERR_A); hb_always_assert (!r2.is_ok ()); hb_always_assert (r2.is_err ()); hb_always_assert (!r2); hb_always_assert (r2.error () == ERR_A); - hb_always_assert (r2 == Err (ERR_A)); - hb_always_assert (r2 != Err (ERR_B)); - hb_always_assert (r2 != Ok ()); - hb_always_assert (Err (ERR_A) == r2); - hb_always_assert (Err (ERR_B) != r2); - hb_always_assert (Ok () != r2); + hb_always_assert (r2 == Err(ERR_A)); + hb_always_assert (r2 != Err(ERR_B)); + hb_always_assert (r2 != Ok()); + hb_always_assert (Err(ERR_A) == r2); + hb_always_assert (Err(ERR_B) != r2); + hb_always_assert (Ok() != r2); } static void test_resource_cleanup () @@ -203,7 +203,7 @@ static void test_resource_cleanup () { result r = resource_t (3); hb_always_assert (live_instances == 1); - r = Err (ERR_A); + r = Err(ERR_A); hb_always_assert (live_instances == 0); hb_always_assert (r.is_err ()); } @@ -284,19 +284,19 @@ static void test_same_or_convertible_types () static_assert (std::is_constructible, resource_t>::value, ""); static_assert (std::is_constructible, error_code_t>::value, ""); - hb_result_t r_ok = Ok (1); + hb_result_t r_ok = Ok(1); hb_always_assert (r_ok.is_ok ()); hb_always_assert (r_ok.value () == 1); - hb_result_t r_err = Err (2); + hb_result_t r_err = Err(2); hb_always_assert (r_err.is_err ()); hb_always_assert (r_err.error () == 2); - hb_result_t same_ok = Ok (42); + hb_result_t same_ok = Ok(42); hb_always_assert (same_ok.is_ok ()); hb_always_assert (same_ok.value () == 42); - hb_result_t same_err = Err (99); + hb_result_t same_err = Err(99); hb_always_assert (same_err.is_err ()); hb_always_assert (same_err.error () == 99); } @@ -311,10 +311,10 @@ static void test_error_interception() { // Checks that U&& constructor does not intercept mismatched error tags as a success value. static_assert (!std::is_constructible, hb_result_err_t>::value, ""); - hb_result_t r = Err (ERR_A); + hb_result_t r = Err(ERR_A); hb_always_assert (r.is_err ()); - hb_result_t r_ok = Ok (123); + hb_result_t r_ok = Ok(123); hb_always_assert (r_ok.is_ok ()); } @@ -350,7 +350,7 @@ static void test_move_only_types () { // Test hb_result_t with Err(...) { - hb_result_t r = Err (move_only_err_t (123)); + hb_result_t r = Err(move_only_err_t (123)); hb_always_assert (r.is_err ()); hb_always_assert (r.error ().code == 123); @@ -367,7 +367,7 @@ static void test_move_only_types () // Test hb_result_t with Err(...) and direct construction { - hb_result_t v1 = Err (move_only_err_t (789)); + hb_result_t v1 = Err(move_only_err_t (789)); hb_always_assert (v1.is_err ()); hb_always_assert (v1.error ().code == 789); @@ -378,11 +378,11 @@ static void test_move_only_types () // Test value_or with move-only value types { - hb_result_t r_ok = Ok (move_only_val_t (42)); + hb_result_t r_ok = Ok(move_only_val_t (42)); move_only_val_t v = std::move (r_ok).value_or (move_only_val_t (0)); hb_always_assert (v.val == 42); - hb_result_t r_err = Err (ERR_A); + hb_result_t r_err = Err(ERR_A); move_only_val_t v_fallback = std::move (r_err).value_or (move_only_val_t (99)); hb_always_assert (v_fallback.val == 99); }