Skip to content

Apple's open-source XNU kernel on Android phones: its own loader and drivers, Metal on the Adreno. Runs from RAM; a reboot gives the phone back to Android.

C

OpenGL ES behind EAGLContext: CoreAnimation's GPU renderer draws SpringBoard

vcvkka4138e81c78b
diff --git a/README.md b/README.md
index 6306bf7..f30a849 100644
--- a/README.md
+++ b/README.md
@@ -199,6 +199,11 @@ REST=1 userland/build.sh
список исключений — `DENY` в `userland/mkjobs.py`, пропустить службу из него для опыта: `ALLOW="слово"`.
Остальные переменные (`JOBS`, `OSLOG`, `INJECT`, `RC_JOBS`) описаны в начале `userland/build.sh`.
+`GL=1 REST=1 userland/build.sh` — образ, в котором оконный сервер рисует через OpenGL ES, а не программным
+растеризатором CoreAnimation: за `EAGLContext` встаёт Mesa (пока с программным же драйвером softpipe — проверка
+пути, а не ускорение). Mesa в репозитории нет: `tools/mk-mesa.sh` один раз скачивает и собирает её (нужны meson,
+ninja, bison, flex); прослойка — `userland/src/eagl.c`.
+
После пересборки ядра/загрузчика/программ `tools/update-prebuilt.sh` обновляет `prebuilt/`.
### UEFI для телефона
@@ -242,7 +247,7 @@ Userland не изменён ни в одном байте: всё, чего е
| `mkpackfs.py` | сборщик образов packfs (формат описан в `bsd/miscfs/packfs/packfs.h` ядра) |
| `qemu/` | запуск в QEMU, касания, снимки экрана, разбор стеков |
| `uefi/`, `mkxnuimg.py` | порт UEFI на redwood и упаковка загрузочного образа для `fastboot boot` |
-| `tools/` | `recording.py` (запись экрана → mp4), `update-prebuilt.sh`, `new-workspace.sh` (вторая рабочая копия со своим ядром и QEMU), `mk-zstddec.sh` |
+| `tools/` | `recording.py` (запись экрана → mp4), `update-prebuilt.sh`, `new-workspace.sh` (вторая рабочая копия со своим ядром и QEMU), `mk-zstddec.sh`, `mk-mesa.sh` (Mesa для `GL=1`) |
| `prebuilt/` | собранные ядро, загрузчик, наши программы и куски UEFI |
Скрипты не зависят от того, куда склонирован репозиторий.
@@ -266,6 +271,8 @@ Userland не изменён ни в одном байте: всё, чего е
- `xnu/` — производная работа от XNU, распространяется на условиях APSL 2.0, как и сам XNU; `prebuilt/mach.*` —
ядро, собранное из этих исходников.
- `xnu/files/bsd/miscfs/packfs/zstddeclib.c` — декодер Zstandard (Meta, BSD), сгенерирован `tools/mk-zstddec.sh`;
+- Mesa (лицензия MIT) в репозитории нет: `tools/mk-mesa.sh` берёт выпуск 25.0.7 с archive.mesa3d.org,
+ `tools/mesa/*.patch` — наши правки к нему;
- `xnu-deps/build/lzbitmap/libzbitmap.*` — libzbitmap (Corellium, GPL-2.0+ OR MIT);
`xnu-deps/hostinc/mach-o/{loader,nlist,fat}.h` — заголовки из XNU (APSL 2.0).
- `uefi/files/Binaries/redwood` и `prebuilt/uefi/SILICIUM_UEFI.fd` содержат драйверы UEFI из прошивки Xiaomi
diff --git a/tools/mesa/osmesa-es-profile.patch b/tools/mesa/osmesa-es-profile.patch
new file mode 100644
index 0000000..be8f563
--- /dev/null
+++ b/tools/mesa/osmesa-es-profile.patch
@@ -0,0 +1,33 @@
+--- a/include/GL/osmesa.h
++++ b/include/GL/osmesa.h
+@@ -106,6 +106,7 @@
+ #define OSMESA_COMPAT_PROFILE 0x35
+ #define OSMESA_CONTEXT_MAJOR_VERSION 0x36
+ #define OSMESA_CONTEXT_MINOR_VERSION 0x37
++#define OSMESA_ES_PROFILE 0x38 /* an OpenGL ES 2 or 3 context, by the version asked for */
+
+
+ typedef struct osmesa_context *OSMesaContext;
+--- a/src/gallium/frontends/osmesa/osmesa.c
++++ b/src/gallium/frontends/osmesa/osmesa.c
+@@ -615,7 +615,8 @@
+ case OSMESA_PROFILE:
+ profile = attribList[i+1];
+ if (profile != OSMESA_CORE_PROFILE &&
+- profile != OSMESA_COMPAT_PROFILE)
++ profile != OSMESA_COMPAT_PROFILE &&
++ profile != OSMESA_ES_PROFILE)
+ return NULL;
+ break;
+ case OSMESA_CONTEXT_MAJOR_VERSION:
+@@ -662,8 +663,8 @@
+ * Create the rendering context
+ */
+ memset(&attribs, 0, sizeof(attribs));
+- attribs.profile = (profile == OSMESA_CORE_PROFILE)
+- ? API_OPENGL_CORE : API_OPENGL_COMPAT;
++ attribs.profile = (profile == OSMESA_ES_PROFILE) ? API_OPENGLES2 :
++ (profile == OSMESA_CORE_PROFILE) ? API_OPENGL_CORE : API_OPENGL_COMPAT;
+ attribs.major = version_major;
+ attribs.minor = version_minor;
+ attribs.flags = 0; /* ST_CONTEXT_FLAG_x */
diff --git a/tools/mk-mesa.sh b/tools/mk-mesa.sh
new file mode 100755
index 0000000..69e2694
--- /dev/null
+++ b/tools/mk-mesa.sh
@@ -0,0 +1,76 @@
+#!/bin/bash
+# Build Mesa for the iOS userland: the OpenGL ES library behind userland/src/eagl.c (see there and
+# userland/src/gl_osmesa.c). Mesa is fetched (a pinned release), patched with tools/mesa/*.patch and
+# built with the cross compiler of the kernel (xnu-deps/host/bin/xnu-clang, see xnu-deps/setup.sh)
+# against the iOS SDK that userland/build.sh uses; nothing of it is in the repository.
+#
+# DRIVERS="softpipe" the gallium drivers to build (softpipe: a rasterizer in plain C; it needs
+# no LLVM and nothing of the machine but its processor)
+#
+# What comes out, in xnu-deps/build/mesa/out:
+# libOSMesa.8.dylib everything in one library (install name /redwood/lib/libOSMesa.8.dylib): the
+# OpenGL (ES) entry points gl*, the compiler of the shading language, the driver,
+# and the off-screen interface that hands out contexts
+# exported-gl.txt the gl* functions it exports, and
+# gl.xml their prototypes (the Khronos registry as Mesa has it): for userland/mkeagl.py
+# Needs on this machine: meson, ninja, bison, flex, python3 with venv (Mako is installed into a
+# private environment), llvm-ar.
+set -e
+VERSION=25.0.7
+SHA256=592272df3cf01e85e7db300c449df5061092574d099da275d19e97ef0510f8a6
+ROOT=$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)
+source "$ROOT/xnu-env.sh"
+B=$ROOT/xnu-deps/build/mesa
+SDK=$THEOS/sdks/iPhoneOS16.5.sdk
+CC=$ROOT/xnu-deps/host/bin/xnu-clang
+mkdir -p "$B/out"
+cd "$B"
+
+if [ ! -d mesa-$VERSION ]; then
+ [ -f mesa-$VERSION.tar.xz ] || curl -sL --fail -o mesa-$VERSION.tar.xz https://archive.mesa3d.org/mesa-$VERSION.tar.xz
+ echo "$SHA256 mesa-$VERSION.tar.xz" | sha256sum -c --quiet
+ tar xJf mesa-$VERSION.tar.xz
+ for p in "$ROOT"/tools/mesa/*.patch; do patch -s -d mesa-$VERSION -p1 < "$p"; done
+fi
+if [ ! -x venv/bin/python3 ]; then
+ python3 -m venv venv
+ venv/bin/pip -q install mako pyyaml packaging
+fi
+export PATH=$B/venv/bin:$PATH
+
+# the compiler is the kernel's wrapper: it names the target (arm64-apple-ios) and the linker (ld64)
+cat > cross.ini <<INI
+[binaries]
+c = ['$CC', '-arch', 'arm64', '-isysroot', '$SDK']
+cpp = ['$CC++', '-arch', 'arm64', '-isysroot', '$SDK', '-fuse-cxa-atexit']
+objc = ['$CC', '-arch', 'arm64', '-isysroot', '$SDK']
+ar = 'llvm-ar'
+ranlib = 'llvm-ranlib'
+strip = 'llvm-strip'
+pkg-config = 'false'
+
+[host_machine]
+system = 'darwin'
+subsystem = 'ios'
+cpu_family = 'aarch64'
+cpu = 'arm64'
+endian = 'little'
+
+[properties]
+needs_exe_wrapper = true
+INI
+[ -f build/build.ninja ] || meson setup build mesa-$VERSION --cross-file cross.ini --prefix=/redwood --libdir=lib \
+ --buildtype=release -Db_ndebug=true \
+ -Dplatforms= -Dgallium-drivers="${DRIVERS:-softpipe}" -Dvulkan-drivers= -Dglx=disabled -Degl=disabled -Dgbm=disabled \
+ -Dosmesa=true -Dllvm=disabled -Dshared-glapi=enabled -Dgles1=disabled -Dgles2=enabled -Dopengl=true \
+ -Dzstd=disabled -Dxmlconfig=disabled -Dexpat=disabled -Dshader-cache=disabled -Dvalgrind=disabled \
+ -Dlibunwind=disabled -Dglvnd=disabled -Dvideo-codecs= -Dtools= -Dgallium-vdpau=disabled -Dgallium-va=disabled \
+ -Dgallium-xa=disabled -Dlmsensors=disabled -Dbuild-tests=false > meson-setup.log
+ninja -C build > ninja.log
+
+llvm-strip -x -o out/libOSMesa.8.dylib build/src/gallium/targets/osmesa/libOSMesa.8.dylib
+install_name_tool -id /redwood/lib/libOSMesa.8.dylib out/libOSMesa.8.dylib
+nm -gU out/libOSMesa.8.dylib | awk '$3 ~ /^_gl/ { print substr($3, 2) }' > out/exported-gl.txt
+cp mesa-$VERSION/src/mapi/glapi/registry/gl.xml out/gl.xml
+echo "mk-mesa.sh: Mesa $VERSION (${DRIVERS:-softpipe}): $B/out/libOSMesa.8.dylib, $(stat -c %s out/libOSMesa.8.dylib) bytes," \
+ "$(wc -l < out/exported-gl.txt) gl* functions"
diff --git a/userland/build.sh b/userland/build.sh
index 20dbd0c..416a8f9 100755
--- a/userland/build.sh
+++ b/userland/build.sh
@@ -17,6 +17,10 @@
# RC_JOBS=<file> what the job com.redwood.demo runs: rc.jobs (default), or
# rc.jobs.unlock, which also swipes the lock screen away (for the phone,
# where nothing else can touch the screen yet)
+# GL=1 with an OpenGL ES implementation for the window server: Mesa
+# (tools/mk-mesa.sh fetches and builds it, once) behind src/eagl.c, as
+# lib/libOSMesa.8.dylib (13 MB) and lib/libredwood-gl.dylib. CoreAnimation
+# then draws with its OpenGL ES renderer instead of its software one.
# system.packfs the system image, the root filesystem (second RAM disk, /dev/md1): the part of
# iOS 16.5 chosen by ../ios165/select-system.py at its real paths, the dyld
# shared cache, and src/stage0.c as /sbin/launchd (the real one is
@@ -94,11 +98,21 @@ if [ -d $IOS/rootfs/usr/lib ]; then
-o obj/libredwood.dylib src/inject.c
$DYN -dynamiclib -install_name /redwood/lib/libredwood-sb.dylib -framework CoreFoundation -lobjc \
-o obj/libredwood-sb.dylib src/inject_sb.c
+ if [ -n "$GL" ]; then
+ # the OpenGL ES library, and the table of functions that hands CoreAnimation's calls to it
+ M=../xnu-deps/build/mesa/out
+ [ -f $M/libOSMesa.8.dylib ] || ../tools/mk-mesa.sh
+ ./mkeagl.py src/eagl_slots.txt $M/gl.xml $M/exported-gl.txt src/eagl.c > obj/eagl_gen.h
+ $DYN -dynamiclib -install_name /redwood/lib/libredwood-gl.dylib -Iobj -framework CoreFoundation \
+ -framework IOSurface -lobjc $M/libOSMesa.8.dylib -o obj/libredwood-gl.dylib src/eagl.c src/gl_osmesa.c
+ cp $M/libOSMesa.8.dylib obj/
+ fi
fi
cp obj/hello_dyn obj/svc_test obj/surf_test obj/rwtouch obj/mg_test root/bin/
[ -f obj/cpu_test ] && cp obj/cpu_test root/bin/ # (a prebuilt/ from before this program has none)
mkdir -p root/lib
cp obj/libredwood.dylib obj/libredwood-sb.dylib root/lib/
+ [ -n "$GL" ] && cp obj/libredwood-gl.dylib obj/libOSMesa.8.dylib root/lib/
echo "$INJECT" > root/etc/inject.conf
cp $IOS/var.skel root/etc/var.skel # the directories init creates in /private/var
# time zones: the template's links go in a circle until the time zone daemon has run (/usr/share/zoneinfo
diff --git a/userland/mkeagl.py b/userland/mkeagl.py
new file mode 100755
index 0000000..29b6bce
--- /dev/null
+++ b/userland/mkeagl.py
@@ -0,0 +1,156 @@
+#!/usr/bin/env python3
+"""Make the function table of src/eagl.c: one function of ours for every entry of the table that
+iOS's OpenGLES hands out through -[EAGLContext getMacroContextPrivate] (src/eagl_slots.txt).
+
+ mkeagl.py SLOTS GL.XML EXPORTED EAGL.C > obj/eagl_gen.h
+
+GL.XML is the Khronos registry (it comes with Mesa: src/mapi/glapi/registry/gl.xml) and gives the
+prototypes; EXPORTED lists the gl* functions the OpenGL ES library to be used exports, one a line;
+EAGL.C is searched for the functions written by hand (static ... my_glName(void *context, ...)),
+which take the place of the generated ones.
+
+An entry is called as entry(table[0], arguments...). What is generated for it:
+ - a function that counts the call and passes the arguments on to the library's function of that
+ name, or of the name without its OES/EXT/APPLE/ARB ending where only that one is exported;
+ - where the library has nothing of the sort (OpenGL ES 1 for the most part), a function that says
+ once which entry was called and returns 0;
+ - the same for the offsets between the known entries.
+The header is in two parts: with EAGL_GEN_DECLARATIONS defined, the types and the prototypes of
+the library's functions; with EAGL_GEN_TABLE, the functions and eagl_fill_table().
+"""
+import re
+import sys
+import xml.etree.ElementTree as ET
+
+slots_path, xml_path, exported_path, source_path = sys.argv[1:5]
+
+slots = [] # (offset, used by QuartzCore, [names])
+for line in open(slots_path):
+ line = line.split('#')[0].split()
+ if line:
+ slots.append((int(line[0], 16), line[1] == '*', line[2:]))
+
+protos = {} # name -> (return type, [(type, name)])
+for command in ET.parse(xml_path).getroot().iter('command'):
+ proto = command.find('proto')
+ if proto is None:
+ continue
+ name = proto.find('name').text
+ ret = ''.join(proto.itertext())
+ ret = ret[:ret.rindex(name)].strip()
+ params = []
+ for param in command.findall('param'):
+ text = ''.join(param.itertext()).strip()
+ pname = param.find('name').text
+ params.append((text[:text.rindex(pname)].strip(), pname))
+ protos[name] = (ret, params)
+
+exported = set(open(exported_path).read().split())
+by_hand = set(re.findall(r'^my_(gl\w+)\(', open(source_path).read(), re.M))
+
+def trace_format(ctype):
+ if '*' in ctype or ctype in ('GLsync', 'GLeglImageOES', 'GLDEBUGPROC', 'GLDEBUGPROCKHR'):
+ return '%p'
+ if ctype in ('GLenum', 'GLbitfield'):
+ return '%#x'
+ if ctype in ('GLfloat', 'GLclampf', 'GLdouble', 'GLclampd'):
+ return '%g'
+ if ctype in ('GLintptr', 'GLsizeiptr'):
+ return '%ld'
+ if ctype in ('GLuint64', 'GLint64'):
+ return '%lld'
+ return '%d'
+
+def trace_value(param):
+ ctype, name = param
+ if '*' in ctype or ctype in ('GLsync', 'GLeglImageOES', 'GLDEBUGPROC', 'GLDEBUGPROCKHR'):
+ return '(const void *)%s' % name
+ if ctype in ('GLfloat', 'GLclampf', 'GLdouble', 'GLclampd'):
+ return '(double)%s' % name
+ if ctype in ('GLuint64', 'GLint64'):
+ return '(long long)%s' % name
+ return name
+
+def library_name(name):
+ """The exported function that does what `name` does."""
+ if name in exported:
+ return name
+ plain = re.sub(r'(OES|EXT|APPLE|ARB|IMG)$', '', name)
+ if plain != name and plain in exported and plain in protos:
+ return plain
+ return None
+
+out = []
+emit = out.append
+emit('/* Generated by userland/mkeagl.py from src/eagl_slots.txt; not to be edited. */')
+emit('#ifdef EAGL_GEN_DECLARATIONS')
+needed = {}
+entries = [] # (offset, name, kind, function)
+for offset, used, names in slots:
+ hand = [n for n in names if n in by_hand]
+ if hand:
+ entries.append((offset, names[0], 'hand', 'my_' + hand[0]))
+ continue
+ choice = None
+ for n in names:
+ target = library_name(n)
+ if target and n in protos:
+ choice = (n, target)
+ break
+ if choice is None:
+ entries.append((offset, names[0], 'none', None))
+ else:
+ entries.append((offset, choice[0], 'pass', choice[1]))
+ needed[choice[1]] = protos[choice[0]]
+# ... and what the functions written by hand call
+for name in set(re.findall(r'(?<![\w])(gl[A-Z]\w*)\s*\(', open(source_path).read())):
+ if name in exported and name in protos:
+ needed.setdefault(name, protos[name])
+for name in sorted(needed):
+ ret, params = needed[name]
+ emit('extern %s %s(%s);' % (ret, name, ', '.join('%s %s' % p for p in params) or 'void'))
+emit('#endif')
+emit('#ifdef EAGL_GEN_TABLE')
+known = {}
+for offset, name, kind, function in entries:
+ known[offset] = name
+ if kind == 'pass':
+ ret, params = protos[name]
+ args = ', '.join(p[1] for p in params)
+ emit('static %s\nslot_%04x(void *context%s)\n{' % (ret, offset, ''.join(', %s %s' % p for p in params)))
+ emit('\tEAGL_ENTER(context, %#x);' % offset)
+ emit('\tif (eagl_tracing) {\n\t\teagl_trace("%s(%s)\\n"%s);' % (name, ', '.join(trace_format(p[0]) for p in params),
+ ''.join(', ' + trace_value(p) for p in params)))
+ vector = re.match(r'glUniform(Matrix)?([1-4])fv$', name)
+ if vector:
+ n = int(vector.group(2))
+ emit('\t\teagl_trace_floats(value, count * %d);' % (n * n if vector.group(1) else n))
+ emit('\t}')
+ if ret == 'void':
+ emit('\t%s(%s);\n\tEAGL_LEAVE(context, %#x);\n}' % (function, args, offset))
+ else:
+ emit('\t%s result = %s(%s);\n\tEAGL_LEAVE(context, %#x);\n\treturn result;\n}' % (ret, function, args, offset))
+ elif kind == 'none':
+ emit('static long slot_%04x(void *context) { return eagl_missing(context, %#x); }' % (offset, offset))
+top = max(known) + 0x100
+for offset in range(8, top, 8):
+ if offset not in known:
+ emit('static long slot_%04x(void *context) { return eagl_missing(context, %#x); }' % (offset, offset))
+emit('#define EAGL_TABLE_SIZE %#x' % top)
+emit('static const char *\neagl_slot_name(unsigned offset)\n{\n\tswitch (offset) {')
+for offset in sorted(known):
+ emit('\tcase %#x: return "%s";' % (offset, known[offset]))
+emit('\tdefault: return "?";\n\t}\n}')
+emit('static void\neagl_fill_table(void **table)\n{')
+hand = {offset: function for offset, name, kind, function in entries if kind == 'hand'}
+for offset in range(8, top, 8):
+ emit('\ttable[%#x / 8] = (void *)%s;' % (offset, hand.get(offset, 'slot_%04x' % offset)))
+emit('}')
+emit('#endif')
+print('\n'.join(out))
+passed = sum(1 for e in entries if e[2] == 'pass')
+missing = [e[1] for e in entries if e[2] == 'none']
+used_missing = [name for (offset, used, names), e in zip(slots, entries) if used and e[2] == 'none' for name in [e[1]]]
+print('mkeagl.py: %d entries: %d passed on, %d by hand, %d without a function in the library%s' % (
+ len(entries), passed, len(hand), len(missing),
+ '; of those QuartzCore calls: ' + ' '.join(used_missing) if used_missing else ''), file=sys.stderr)
diff --git a/userland/src/eagl.c b/userland/src/eagl.c
new file mode 100644
index 0000000..460edfb
--- /dev/null
+++ b/userland/src/eagl.c
@@ -0,0 +1,1299 @@
+/*
+ * libredwood-gl.dylib: an OpenGL ES implementation behind iOS's EAGLContext, inside the window
+ * server (backboardd; libredwood.dylib loads this when the image has it: build.sh GL=1).
+ *
+ * CoreAnimation's render server draws with Metal, or else with OpenGL ES, or else with its own
+ * software rasterizer (CA::WindowServer::EAGLServer::renderer()). For OpenGL ES it makes an
+ * EAGLContext of API 3 and asks six things of it, all of which are replaced here:
+ *
+ * -initWithAPI:properties: ours makes a context of the OpenGL ES library behind us
+ * -API 3
+ * -setParameter:to: noted
+ * -getMacroContextPrivate a table of functions, called as entry(table[0], arguments...) at
+ * the offsets of iOS's own OpenGLES (src/eagl_slots.txt); ours is
+ * made by mkeagl.py: each entry counts the call and passes it on,
+ * except the ones written by hand below (my_gl...)
+ * -texImageIOSurface:target:internalFormat:width:height:format:type:plane:invert:
+ * the texture bound to `target` is to show what the IOSurface holds
+ * -attachImage:toCoreSurface:invertedRender:
+ * the texture bound to the target ("image") is to BE the IOSurface:
+ * what is drawn into it (it becomes a framebuffer's colour
+ * attachment) is the screen; or it is a picture to be shown
+ *
+ * A GPU's driver does the last two by using the IOSurface's memory as the texture's. Nothing of
+ * the kind is assumed here: the texture is an ordinary one, filled from the IOSurface when that
+ * has changed (its seed) and read back into it when a frame ends (glFlush, glFinish), with
+ * nothing but OpenGL ES calls. So this file does not know what draws: the library is reached
+ * through its gl* functions and the four functions of redwood_gl.h. A driver that can share the
+ * memory needs surface_to_texture() and target_to_surface() replaced, and nothing else.
+ *
+ * Where CoreAnimation relies on iOS's library being what it is, this stands in between:
+ * blue-first pixels into a texture called GL_RGBA (internal_format()), and shaders that read
+ * textures at coordinates in pixels (my_glShaderSource()).
+ *
+ * What CoreAnimation asks of OpenGL ES is written down as it goes (the log lines "redwood-gl:"):
+ * strings and limits it reads, texture formats and sizes, calls and triangles per frame. More
+ * with the kernel's boot-args: gltrace=FIRST-LAST writes down every call of those frames (lines
+ * "gl:", with a pixel of the framebuffer after each draw), glshaders=1 the text of every shader,
+ * glshow=TEXTURE puts that texture over the corner of the picture.
+ */
+#include <CoreFoundation/CoreFoundation.h>
+#include <IOSurface/IOSurfaceRef.h>
+#include <mach/mach_time.h>
+#include <objc/message.h>
+#include <objc/runtime.h>
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/sysctl.h>
+#include <unistd.h>
+
+#include "redwood_gl.h"
+
+/* ---- OpenGL ES: the types, the few names used here, the library's functions --------------------- */
+
+typedef unsigned int GLenum, GLbitfield, GLuint;
+typedef int GLint, GLsizei, GLfixed, GLclampx;
+typedef unsigned char GLboolean, GLubyte;
+typedef signed char GLbyte;
+typedef short GLshort;
+typedef unsigned short GLushort, GLhalf;
+typedef float GLfloat, GLclampf;
+typedef double GLdouble, GLclampd;
+typedef char GLchar;
+typedef void GLvoid;
+typedef long GLintptr, GLsizeiptr;
+typedef int64_t GLint64;
+typedef uint64_t GLuint64;
+typedef struct __GLsync *GLsync;
+typedef void *GLeglImageOES;
+typedef void (*GLDEBUGPROC)(GLenum, GLenum, GLuint, GLenum, GLsizei, const GLchar *, const void *);
+typedef GLDEBUGPROC GLDEBUGPROCKHR;
+
+#define GL_TRIANGLES 0x0004
+#define GL_TRIANGLE_STRIP 0x0005
+#define GL_TRIANGLE_FAN 0x0006
+#define GL_UNPACK_ROW_LENGTH 0x0cf2
+#define GL_UNPACK_ALIGNMENT 0x0cf5
+#define GL_PACK_ROW_LENGTH 0x0d02
+#define GL_PACK_ALIGNMENT 0x0d05
+#define GL_TEXTURE_2D 0x0de1
+#define GL_UNSIGNED_BYTE 0x1401
+#define GL_RGBA 0x1908
+#define GL_VENDOR 0x1f00
+#define GL_RENDERER 0x1f01
+#define GL_VERSION 0x1f02
+#define GL_EXTENSIONS 0x1f03
+#define GL_TEXTURE_BINDING_2D 0x8069
+#define GL_BGRA 0x80e1
+#define GL_INFO_LOG_LENGTH 0x8b84
+#define GL_COMPILE_STATUS 0x8b81
+#define GL_LINK_STATUS 0x8b82
+#define GL_SHADING_LANGUAGE_VERSION 0x8b8c
+#define GL_COLOR_ATTACHMENT0 0x8ce0
+#define GL_FRAMEBUFFER_COMPLETE 0x8cd5
+#define GL_FRAMEBUFFER 0x8d40
+
+struct eagl;
+static int eagl_tracing; /* this frame's calls are written down (boot-arg gltrace=FIRST-LAST) */
+static void eagl_trace(const char *format, ...) __attribute__((format(printf, 1, 2)));
+static void eagl_trace_floats(const float *values, int count);
+static void eagl_enter(struct eagl *e, unsigned offset);
+static void eagl_leave(struct eagl *e, unsigned offset);
+static long eagl_missing(void *context, unsigned offset);
+#define EAGL_ENTER(context, offset) eagl_enter(context, offset)
+#define EAGL_LEAVE(context, offset) eagl_leave(context, offset)
+
+#define EAGL_GEN_DECLARATIONS
+#include "eagl_gen.h"
+#undef EAGL_GEN_DECLARATIONS
+
+static void
+say(const char *format, ...)
+{
+ char line[1024];
+ va_list ap;
+ int n;
+
+ va_start(ap, format);
+ n = vsnprintf(line, sizeof(line), format, ap);
+ va_end(ap);
+ if (n > (int)sizeof(line) - 1) {
+ n = sizeof(line) - 1;
+ }
+ write(2, line, (size_t)n);
+}
+
+static void
+eagl_trace(const char *format, ...)
+{
+ char line[512] = "gl: ";
+ va_list ap;
+ int n;
+
+ va_start(ap, format);
+ n = vsnprintf(line + 4, sizeof(line) - 4, format, ap) + 4;
+ va_end(ap);
+ write(2, line, n > (int)sizeof(line) - 1 ? sizeof(line) - 1 : (size_t)n);
+}
+
+static void
+eagl_trace_floats(const float *values, int count)
+{
+ char line[512] = "gl: ";
+ int n = 7;
+
+ for (int i = 0; i < count && i < 16 && n < 480; i++) {
+ n += snprintf(line + n, sizeof(line) - (size_t)n, " %g", (double)values[i]);
+ }
+ line[n++] = '\n';
+ write(2, line, (size_t)n);
+}
+
+static uint64_t
+now_us(void)
+{
+ static mach_timebase_info_data_t base;
+
+ if (base.denom == 0) {
+ mach_timebase_info(&base);
+ }
+ return mach_absolute_time() * base.numer / base.denom / 1000;
+}
+
+/* ---- a context -------------------------------------------------------------------------------- */
+
+#define SLOTS 0x440 /* entries of the table: more than iOS's has (checked below) */
+#define FRAMEBUFFERS 4096 /* names of framebuffers followed: they are small numbers */
+
+/* A texture that stands for an IOSurface. */
+struct image {
+ GLuint texture;
+ IOSurfaceRef surface;
+ bool target; /* drawn into (attachImage) rather than shown (texImageIOSurface) */
+ bool invert, drawn;
+ GLenum to, internal, format, type;
+ uint32_t plane, seed;
+ GLsizei width, height;
+};
+
+struct eagl {
+ void *table[SLOTS]; /* [0] is the context itself: what every entry gets as its first argument */
+ id object; /* the EAGLContext */
+ struct redwood_gl *gl;
+ unsigned long api;
+ struct image images[256];
+ unsigned image_count;
+ GLuint framebuffer; /* the one bound */
+ GLuint colour[FRAMEBUFFERS]; /* the texture that is each framebuffer's colour attachment */
+ GLuint reader; /* a framebuffer of ours, to read a texture back */
+ bool in_frame;
+ /* a frame's worth */
+ unsigned calls, draws, triangles, uploads, clears;
+ uint64_t upload_bytes, began;
+ /* everything so far */
+ unsigned frames, shaders, programs, errors;
+ uint64_t all_calls, all_draws, all_triangles, readback_us, frame_us;
+ unsigned most_calls, most_triangles;
+ const char *sources[64]; /* the text of the shaders being made, by name modulo this */
+ bool fragment[64]; /* ... and which of the two kinds each is */
+};
+
+static unsigned trace_first, trace_last; /* the frames whose calls are written down */
+static int all_shaders; /* boot-arg glshaders=1: the text of every shader, not of the first two */
+static __thread struct eagl *current;
+static struct eagl *contexts[8];
+static uint32_t slot_calls[SLOTS];
+static int check_errors = 1; /* ask the library for an error after every call (the first frames) */
+
+static const char *eagl_slot_name(unsigned offset);
+
+static void
+eagl_enter(struct eagl *e, unsigned offset)
+{
+ if (current != e) {
+ if (!redwood_gl_make_current(e->gl)) {
+ say("redwood-gl: the context cannot be made this thread's\n");
+ }
+ current = e;
+ }
+ slot_calls[offset / 8]++;
+ e->calls++;
+}
+
+static void
+eagl_leave(struct eagl *e, unsigned offset)
+{
+ GLenum error;
+
+ if (check_errors && offset != 0x338 && (error = glGetError()) != 0) {
+ if (e->errors++ < 60) {
+ say("redwood-gl: %s: error %#x\n", eagl_slot_name(offset), error);
+ }
+ }
+}
+
+/* An entry the library has no function for: say so, once an entry. */
+static long
+eagl_missing(void *context, unsigned offset)
+{
+ struct eagl *e = context;
+
+ eagl_enter(e, offset);
+ if (slot_calls[offset / 8] == 1) {
+ say("redwood-gl: CALLED AND NOT THERE: entry %#x, %s\n", offset, eagl_slot_name(offset));
+ }
+ return 0;
+}
+
+static struct eagl *
+context_of(id object)
+{
+ for (unsigned i = 0; i < sizeof(contexts) / sizeof(contexts[0]); i++) {
+ if (contexts[i] != NULL && contexts[i]->object == object) {
+ return contexts[i];
+ }
+ }
+ return NULL;
+}
+
+/* ---- what CoreAnimation asks for: kept for the summary ------------------------------------------- */
+
+struct format_use {
+ GLenum internal, format, type;
+ unsigned count, widest, tallest;
+ const char *how;
+};
+static struct format_use formats[48];
+static unsigned widest_texture, tallest_texture;
+
+static void
+note_format(const char *how, GLenum internal, GLenum format, GLenum type, GLsizei width, GLsizei height)
+{
+ struct format_use *use = NULL;
+
+ for (unsigned i = 0; i < sizeof(formats) / sizeof(formats[0]); i++) {
+ if (formats[i].count == 0 || (formats[i].how == how && formats[i].internal == internal &&
+ formats[i].format == format && formats[i].type == type)) {
+ use = &formats[i];
+ break;
+ }
+ }
+ if ((unsigned)width > widest_texture) {
+ widest_texture = (unsigned)width;
+ }
+ if ((unsigned)height > tallest_texture) {
+ tallest_texture = (unsigned)height;
+ }
+ if (use == NULL) {
+ return;
+ }
+ if (use->count++ == 0) {
+ use->how = how;
+ use->internal = internal;
+ use->format = format;
+ use->type = type;
+ say("redwood-gl: a new kind of texture: %s, internal format %#x, format %#x, type %#x, %d x %d\n", how, internal,
+ format, type, width, height);
+ }
+ if ((unsigned)width > use->widest) {
+ use->widest = (unsigned)width;
+ }
+ if ((unsigned)height > use->tallest) {
+ use->tallest = (unsigned)height;
+ }
+}
+
+static void
+summary(struct eagl *e)
+{
+ unsigned frames = e->frames ? e->frames : 1;
+
+ say("redwood-gl: after %u frames: %llu calls, %llu draws and %llu triangles a frame on average; the most in one: "
+ "%u calls, %u triangles; %llu ms a frame, of which %llu copying the picture out; %u shaders, %u programs; "
+ "biggest texture %u x %u; %u errors\n", e->frames, e->all_calls / frames, e->all_draws / frames,
+ e->all_triangles / frames, e->most_calls, e->most_triangles, e->frame_us / frames / 1000,
+ e->readback_us / frames / 1000, e->shaders, e->programs, widest_texture, tallest_texture, e->errors);
+ for (unsigned i = 0; i < sizeof(formats) / sizeof(formats[0]) && formats[i].count; i++) {
+ say("redwood-gl: textures: %s %#x/%#x/%#x: %u times, up to %u x %u\n", formats[i].how, formats[i].internal,
+ formats[i].format, formats[i].type, formats[i].count, formats[i].widest, formats[i].tallest);
+ }
+ for (unsigned offset = 8; offset < SLOTS * 8; offset += 8) {
+ if (slot_calls[offset / 8]) {
+ say("redwood-gl: %-28s %u\n", eagl_slot_name(offset), slot_calls[offset / 8]);
+ }
+ }
+}
+
+/* ---- IOSurfaces ----------------------------------------------------------------------------------- */
+
+static struct image *
+image_of(struct eagl *e, GLuint texture)
+{
+ for (unsigned i = 0; i < e->image_count; i++) {
+ if (e->images[i].texture == texture) {
+ return &e->images[i];
+ }
+ }
+ return NULL;
+}
+
+static struct image *
+image_new(struct eagl *e, GLuint texture, IOSurfaceRef surface)
+{
+ struct image *image = image_of(e, texture);
+
+ if (image == NULL) {
+ if (e->image_count == sizeof(e->images) / sizeof(e->images[0])) {
+ say("redwood-gl: more textures with IOSurfaces than there is room for\n");
+ return NULL;
+ }
+ image = &e->images[e->image_count++];
+ } else {
+ CFRelease(image->surface);
+ }
+ memset(image, 0, sizeof(*image));
+ image->texture = texture;
+ image->surface = (IOSurfaceRef)CFRetain(surface);
+ return image;
+}
+
+static void
+image_forget(struct eagl *e, GLuint texture)
+{
+ struct image *image = image_of(e, texture);
+
+ if (image != NULL) {
+ CFRelease(image->surface);
+ *image = e->images[--e->image_count];
+ }
+}
+
+/* Apple's OpenGL ES takes blue-first pixels into a texture called GL_RGBA; everybody else's calls the texture so too. */
+static GLenum
+internal_format(GLenum internal, GLenum format)
+{
+ return format == GL_BGRA && internal == GL_RGBA ? GL_BGRA : internal;
+}
+
+static unsigned
+bytes_a_pixel(GLenum format, GLenum type)
+{
+ unsigned parts = format == GL_RGBA || format == GL_BGRA ? 4 : format == 0x1907 ? 3 : /* RGB */
+ format == 0x8227 || format == 0x190a ? 2 : 1; /* RG, luminance + alpha */
+
+ switch (type) {
+ case GL_UNSIGNED_BYTE:
+ return parts;
+ case 0x140b: case 0x8d61: case 0x1403: /* half floats, 16 bits */
+ return 2 * parts;
+ case 0x1406: /* floats */
+ return 4 * parts;
+ case 0x8368: /* 2:10:10:10 in a word */
+ return 4;
+ default:
+ return 2; /* the packed 16-bit kinds */
+ }
+}
+
+/*
+ * Fill a texture, which is bound, from its IOSurface. This and target_to_surface() are where a
+ * driver that maps the IOSurface's memory would do something else.
+ */
+static void
+surface_to_texture(struct eagl *e, struct image *image)
+{
+ IOSurfaceRef surface = image->surface;
+ bool planar = IOSurfaceGetPlaneCount(surface) > 0;
+ size_t row = planar ? IOSurfaceGetBytesPerRowOfPlane(surface, image->plane) : IOSurfaceGetBytesPerRow(surface);
+ unsigned pixel = bytes_a_pixel(image->format, image->type);
+ GLint row_length = 0, alignment = 4;
+ uint8_t *base, *flipped = NULL;
+
+ if (IOSurfaceLock(surface, kIOSurfaceLockReadOnly, NULL) != 0) {
+ say("redwood-gl: an IOSurface cannot be locked\n");
+ return;
+ }
+ base = planar ? IOSurfaceGetBaseAddressOfPlane(surface, image->plane) : IOSurfaceGetBaseAddress(surface);
+ if (image->invert && (flipped = malloc(row * (size_t)image->height)) != NULL) {
+ for (GLsizei y = 0; y < image->height; y++) {
+ memcpy(flipped + row * (size_t)y, base + row * (size_t)(image->height - 1 - y), row);
+ }
+ base = flipped;
+ }
+ glGetIntegerv(GL_UNPACK_ROW_LENGTH, &row_length);
+ glGetIntegerv(GL_UNPACK_ALIGNMENT, &alignment);
+ glPixelStorei(GL_UNPACK_ROW_LENGTH, (GLint)(row / pixel));
+ glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
+ glTexImage2D(image->to, 0, (GLint)internal_format(image->internal, image->format), image->width, image->height, 0,
+ image->format, image->type, base);
+ glPixelStorei(GL_UNPACK_ROW_LENGTH, row_length);
+ glPixelStorei(GL_UNPACK_ALIGNMENT, alignment);
+ IOSurfaceUnlock(surface, kIOSurfaceLockReadOnly, NULL);
+ free(flipped);
+ image->seed = IOSurfaceGetSeed(surface);
+ e->uploads++;
+ e->upload_bytes += row * (size_t)image->height;
+}
+
+/* What has been drawn into a texture, into its IOSurface. */
+static void
+target_to_surface(struct eagl *e, struct image *image)
+{
+ IOSurfaceRef surface = image->surface;
+ size_t row = IOSurfaceGetBytesPerRow(surface);
+ uint8_t *base;
+
+ if (e->reader == 0) {
+ glGenFramebuffers(1, &e->reader);
+ }
+ glBindFramebuffer(GL_FRAMEBUFFER, e->reader);
+ glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, image->texture, 0);
+ if (IOSurfaceLock(surface, 0, NULL) == 0) {
+ base = IOSurfaceGetBaseAddress(surface);
+ glPixelStorei(GL_PACK_ROW_LENGTH, (GLint)(row / 4));
+ glPixelStorei(GL_PACK_ALIGNMENT, 4);
+ if (!image->invert) {
+ glReadPixels(0, 0, image->width, image->height, GL_BGRA, GL_UNSIGNED_BYTE, base);
+ } else {
+ for (GLsizei y = 0; y < image->height; y++) {
+ glReadPixels(0, y, image->width, 1, GL_BGRA, GL_UNSIGNED_BYTE, base + row * (size_t)(image->height - 1 - y));
+ }
+ }
+ glPixelStorei(GL_PACK_ROW_LENGTH, 0);
+ IOSurfaceUnlock(surface, 0, NULL);
+ }
+ glBindFramebuffer(GL_FRAMEBUFFER, e->framebuffer);
+ image->drawn = false;
+}
+
+/*
+ * For looking at what is drawn on the way to the picture (boot-arg glshow=TEXTURE): that texture's
+ * pixels are put over the top left corner of the picture as it goes out.
+ */
+#define GL_TEXTURE_WIDTH 0x1000
+#define GL_TEXTURE_HEIGHT 0x1001
+
+static GLuint shown_texture;
+
+static void
+show_texture(struct eagl *e, struct image *image)
+{
+ GLint width = 0, height = 0, bound = 0;
+ size_t row = IOSurfaceGetBytesPerRow(image->surface);
+ uint8_t *pixels, *base;
+
+ glGetIntegerv(GL_TEXTURE_BINDING_2D, &bound);
+ glBindTexture(GL_TEXTURE_2D, shown_texture);
+ glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &width);
+ glGetTexLevelParameteriv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &height);
+ glBindTexture(GL_TEXTURE_2D, (GLuint)bound);
+ if (width <= 0 || height <= 0 || (pixels = malloc((size_t)width * (size_t)height * 4)) == NULL) {
+ return;
+ }
+ glBindFramebuffer(GL_FRAMEBUFFER, e->reader);
+ glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, shown_texture, 0);
+ glPixelStorei(GL_PACK_ALIGNMENT, 1);
+ glReadPixels(0, 0, width, height, GL_BGRA, GL_UNSIGNED_BYTE, pixels);
+ glPixelStorei(GL_PACK_ALIGNMENT, 4);
+ glBindFramebuffer(GL_FRAMEBUFFER, e->framebuffer);
+ if (glGetError() == 0 && IOSurfaceLock(image->surface, 0, NULL) == 0) {
+ base = IOSurfaceGetBaseAddress(image->surface);
+ for (GLint y = 0; y < height && y < image->height; y++) {
+ memcpy(base + row * (size_t)y, pixels + (size_t)y * (size_t)width * 4,
+ (size_t)(width < image->width ? width : image->width) * 4);
+ }
+ IOSurfaceUnlock(image->surface, 0, NULL);
+ }
+ free(pixels);
+}
+
+/* Before the first drawing of a frame: the textures whose IOSurfaces somebody has written to since. */
+static void
+frame_begin(struct eagl *e)
+{
+ GLint bound = 0;
+ bool rebound = false;
+
+ if (e->in_frame) {
+ return;
+ }
+ e->in_frame = true;
+ e->began = now_us();
+ eagl_tracing = e->frames + 1 >= trace_first && e->frames + 1 <= trace_last;
+ if (eagl_tracing) {
+ eagl_trace("---- frame %u (framebuffer %u)\n", e->frames + 1, e->framebuffer);
+ }
+ for (unsigned i = 0; i < e->image_count; i++) {
+ struct image *image = &e->images[i];
+
+ if (image->target || IOSurfaceGetSeed(image->surface) == image->seed) {
+ continue;
+ }
+ if (!rebound) {
+ glGetIntegerv(GL_TEXTURE_BINDING_2D, &bound);
+ rebound = true;
+ }
+ glBindTexture(image->to, image->texture);
+ surface_to_texture(e, image);
+ }
+ if (rebound) {
+ glBindTexture(GL_TEXTURE_2D, (GLuint)bound);
+ }
+}
+
+/* glFlush, glFinish: what was drawn must be where the display takes it from. */
+static void
+frame_end(struct eagl *e)
+{
+ uint64_t before = now_us(), after;
+ unsigned copied = 0;
+
+ for (unsigned i = 0; i < e->image_count; i++) {
+ if (e->images[i].target && e->images[i].drawn) {
+ target_to_surface(e, &e->images[i]);
+ if (shown_texture != 0) {
+ show_texture(e, &e->images[i]);
+ }
+ copied++;
+ }
+ }
+ if (!e->in_frame) {
+ return;
+ }
+ after = now_us();
+ e->in_frame = false;
+ e->frames++;
+ e->all_calls += e->calls;
+ e->all_draws += e->draws;
+ e->all_triangles += e->triangles;
+ e->readback_us += after - before;
+ e->frame_us += after - e->began;
+ if (e->calls > e->most_calls) {
+ e->most_calls = e->calls;
+ }
+ if (e->triangles > e->most_triangles) {
+ e->most_triangles = e->triangles;
+ }
+ if (e->frames <= 40 || e->frames % 20 == 0) {
+ say("redwood-gl: frame %u: %u GL calls, %u draws, %u triangles, %u clears; %u textures refilled from IOSurfaces "
+ "(%llu KB); %u picture%s copied out; %llu ms\n", e->frames, e->calls, e->draws, e->triangles, e->clears,
+ e->uploads, e->upload_bytes >> 10, copied, copied == 1 ? "" : "s", (after - e->began) / 1000);
+ }
+ if (e->frames == 30 || e->frames % 200 == 0) {
+ summary(e);
+ }
+ if (e->frames == 600 && e->errors == 0) {
+ check_errors = 0;
+ }
+ e->calls = e->draws = e->triangles = e->uploads = e->clears = 0;
+ e->upload_bytes = 0;
+}
+
+/* Something is about to be drawn into the framebuffer that is bound. */
+static void
+drawing(struct eagl *e)
+{
+ struct image *image;
+
+ frame_begin(e);
+ if (e->framebuffer != 0 && e->framebuffer < FRAMEBUFFERS && e->colour[e->framebuffer] != 0 &&
+ (image = image_of(e, e->colour[e->framebuffer])) != NULL && image->target) {
+ image->drawn = true;
+ }
+}
+
+/* ---- the entries written by hand ---------------------------------------------------------------- */
+
+static void
+my_glBindTexture(void *context, GLenum target, GLuint texture)
+{
+ struct eagl *e = context;
+ struct image *image;
+
+ EAGL_ENTER(e, 0x30);
+ if (eagl_tracing) {
+ eagl_trace("glBindTexture(%#x, %u)\n", target, texture);
+ }
+ glBindTexture(target, texture);
+ if (texture != 0 && e->image_count != 0 && (image = image_of(e, texture)) != NULL && !image->target &&
+ IOSurfaceGetSeed(image->surface) != image->seed) {
+ surface_to_texture(e, image);
+ }
+ EAGL_LEAVE(e, 0x30);
+}
+
+static void
+my_glClear(void *context, GLbitfield mask)
+{
+ struct eagl *e = context;
+
+ EAGL_ENTER(e, 0x58);
+ drawing(e);
+ e->clears++;
+ if (eagl_tracing) {
+ eagl_trace("glClear(%#x)\n", mask);
+ }
+ glClear(mask);
+ EAGL_LEAVE(e, 0x58);
+}
+
+/* While calls are written down: what a draw has left in the middle of what it drew into, and near its top. */
+#define GL_VIEWPORT 0x0ba2
+
+static void
+trace_pixels(struct eagl *e)
+{
+ GLint view[4] = { 0, 0, 0, 0 };
+ uint8_t middle[4] = { 0, 0, 0, 0 }, low[4] = { 0, 0, 0, 0 };
+
+ glGetIntegerv(GL_VIEWPORT, view);
+ glReadPixels(view[0] + view[2] / 2, view[1] + view[3] / 2, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, middle);
+ glReadPixels(view[0] + view[2] / 2, view[1] + view[3] / 8, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, low);
+ eagl_trace(" framebuffer %u (%d x %d): middle %u %u %u %u, an eighth up %u %u %u %u (red green blue alpha)%s\n",
+ e->framebuffer, view[2], view[3], middle[0], middle[1], middle[2], middle[3], low[0], low[1], low[2], low[3],
+ glGetError() ? " (not readable)" : "");
+}
+
+static unsigned
+triangles_of(GLenum mode, GLsizei count)
+{
+ return mode == GL_TRIANGLES ? (unsigned)count / 3 : (mode == GL_TRIANGLE_STRIP || mode == GL_TRIANGLE_FAN) &&
+ count > 2 ? (unsigned)count - 2 : 0;
+}
+
+static void
+my_glDrawArrays(void *context, GLenum mode, GLint first, GLsizei count)
+{
+ struct eagl *e = context;
+
+ EAGL_ENTER(e, 0x210);
+ drawing(e);
+ e->draws++;
+ e->triangles += triangles_of(mode, count);
+ if (eagl_tracing) {
+ eagl_trace("glDrawArrays(%#x, %d, %d)\n", mode, first, count);
+ }
+ glDrawArrays(mode, first, count);
+ EAGL_LEAVE(e, 0x210);
+ if (eagl_tracing) {
+ trace_pixels(e);
+ }
+}
+
+static void
+my_glDrawElements(void *context, GLenum mode, GLsizei count, GLenum type, const void *indices)
+{
+ struct eagl *e = context;
+
+ EAGL_ENTER(e, 0x220);
+ drawing(e);
+ e->draws++;
+ e->triangles += triangles_of(mode, count);
+ if (eagl_tracing) {
+ eagl_trace("glDrawElements(%#x, %d, %#x, %p)\n", mode, count, type, indices);
+ }
+ glDrawElements(mode, count, type, indices);
+ EAGL_LEAVE(e, 0x220);
+ if (eagl_tracing) {
+ trace_pixels(e);
+ }
+}
+
+static void
+my_glFinish(void *context)
+{
+ struct eagl *e = context;
+
+ EAGL_ENTER(e, 0x2d0);
+ if (eagl_tracing) {
+ eagl_trace("glFinish()\n");
+ }
+ glFinish();
+ frame_end(e);
+ EAGL_LEAVE(e, 0x2d0);
+}
+
+static void
+my_glFlush(void *context)
+{
+ struct eagl *e = context;
+
+ EAGL_ENTER(e, 0x2d8);
+ if (eagl_tracing) {
+ eagl_trace("glFlush()\n");
+ }
+ glFlush();
+ frame_end(e);
+ EAGL_LEAVE(e, 0x2d8);
+}
+
+/* APPLE_fence: wait for one object to be done with. Everything is done with after glFinish. */
+static void
+my_glFinishObjectAPPLE(void *context, GLenum object, GLint name)
+{
+ struct eagl *e = context;
+
+ (void)object;
+ (void)name;
+ EAGL_ENTER(e, 0xeb8);
+ glFinish();
+ frame_end(e);
+ EAGL_LEAVE(e, 0xeb8);
+}
+
+static void
+my_glDeleteTextures(void *context, GLsizei n, const GLuint *textures)
+{
+ struct eagl *e = context;
+
+ EAGL_ENTER(e, 0x1e0);
+ for (GLsizei i = 0; i < n; i++) {
+ image_forget(e, textures[i]);
+ }
+ glDeleteTextures(n, textures);
+ EAGL_LEAVE(e, 0x1e0);
+}
+
+static const GLubyte *
+my_glGetString(void *context, GLenum name)
+{
+ struct eagl *e = context;
+ const GLubyte *string;
+
+ EAGL_ENTER(e, 0x3b0);
+ /* 0x8a1e is no name of OpenGL ES's; iOS's library answers it (the constructor of CA::OGL::GLESContext asks) */
+ string = name == 0x8a1e ? (const GLubyte *)"" : glGetString(name);
+ say("redwood-gl: asked for string %#x: %.900s\n", name, string ? (const char *)string : "(none)");
+ EAGL_LEAVE(e, 0x3b0);
+ return string;
+}
+
+static void
+my_glGetIntegerv(void *context, GLenum name, GLint *values)
+{
+ struct eagl *e = context;
+ static unsigned said;
+
+ EAGL_ENTER(e, 0x348);
+ glGetIntegerv(name, values);
+ if (said < 40) {
+ said++;
+ say("redwood-gl: asked for number %#x: %d\n", name, values[0]);
+ }
+ EAGL_LEAVE(e, 0x348);
+}
+
+static void
+my_glTexImage2D(void *context, GLenum target, GLint level, GLint internal, GLsizei width, GLsizei height, GLint border,
+ GLenum format, GLenum type, const void *pixels)
+{
+ struct eagl *e = context;
+
+ EAGL_ENTER(e, 0x970);
+ if (level == 0) {
+ note_format(pixels ? "filled" : "empty", (GLenum)internal, format, type, width, height);
+ }
+ if (eagl_tracing) {
+ eagl_trace("glTexImage2D(%#x, %d, %#x, %d, %d, %d, %#x, %#x, %p)\n", target, level, internal, width, height, border,
+ format, type, pixels);
+ if (pixels != NULL && type == 0x140b && format == GL_RGBA) { /* half floats: the first and the last pixel */
+ const uint16_t *half = pixels;
+
+ eagl_trace(" half floats: %#x %#x %#x %#x ... %#x %#x %#x %#x\n", half[0], half[1], half[2], half[3],
+ half[4 * (width - 1)], half[4 * (width - 1) + 1], half[4 * (width - 1) + 2], half[4 * (width - 1) + 3]);
+ }
+ }
+ glTexImage2D(target, level, (GLint)internal_format((GLenum)internal, format), width, height, border, format, type, pixels);
+ EAGL_LEAVE(e, 0x970);
+}
+
+static void
+my_glCompressedTexImage2D(void *context, GLenum target, GLint level, GLenum internal, GLsizei width, GLsizei height,
+ GLint border, GLsizei size, const void *data)
+{
+ struct eagl *e = context;
+
+ EAGL_ENTER(e, 0xbe8);
+ if (level == 0) {
+ note_format("compressed", internal, 0, 0, width, height);
+ }
+ glCompressedTexImage2D(target, level, internal, width, height, border, size, data);
+ EAGL_LEAVE(e, 0xbe8);
+}
+
+static void
+my_glBindFramebuffer(void *context, GLenum target, GLuint framebuffer)
+{
+ struct eagl *e = context;
+
+ EAGL_ENTER(e, 0x1508);
+ e->framebuffer = framebuffer;
+ if (eagl_tracing) {
+ eagl_trace("glBindFramebuffer(%#x, %u)\n", target, framebuffer);
+ }
+ glBindFramebuffer(target, framebuffer);
+ EAGL_LEAVE(e, 0x1508);
+}
+
+static void
+my_glFramebufferTexture2D(void *context, GLenum target, GLenum attachment, GLenum to, GLuint texture, GLint level)
+{
+ struct eagl *e = context;
+
+ EAGL_ENTER(e, 0x1530);
+ if (attachment == GL_COLOR_ATTACHMENT0 && e->framebuffer < FRAMEBUFFERS) {
+ e->colour[e->framebuffer] = texture;
+ }
+ if (eagl_tracing) {
+ eagl_trace("glFramebufferTexture2D(%#x, %#x, %#x, %u, %d)\n", target, attachment, to, texture, level);
+ }
+ glFramebufferTexture2D(target, attachment, to, texture, level);
+ EAGL_LEAVE(e, 0x1530);
+}
+
+static void
+my_glDeleteFramebuffers(void *context, GLsizei n, const GLuint *framebuffers)
+{
+ struct eagl *e = context;
+
+ EAGL_ENTER(e, 0x1510);
+ for (GLsizei i = 0; i < n; i++) {
+ if (framebuffers[i] < FRAMEBUFFERS) {
+ e->colour[framebuffers[i]] = 0;
+ }
+ if (framebuffers[i] == e->framebuffer) {
+ e->framebuffer = 0;
+ }
+ }
+ glDeleteFramebuffers(n, framebuffers);
+ EAGL_LEAVE(e, 0x1510);
+}
+
+/* A private entry of iOS's library (CA::OGL::GLESContext::set_surface calls it); nobody else has it. */
+static void
+my_glFramebufferParameteriAPPLE(void *context, GLenum target, GLenum name, GLint value)
+{
+ struct eagl *e = context;
+
+ EAGL_ENTER(e, 0x2008);
+ if (slot_calls[0x2008 / 8] <= 4) {
+ say("redwood-gl: glFramebufferParameteriAPPLE(%#x, %#x, %d): nothing done\n", target, name, value);
+ }
+}
+
+/* EXT_debug_marker: names for a debugger's list of calls. */
+static void
+my_glInsertEventMarkerEXT(void *context, GLsizei length, const GLchar *marker)
+{
+ (void)length;
+ (void)marker;
+ EAGL_ENTER(context, 0x1988);
+}
+
+static void
+my_glPushGroupMarkerEXT(void *context, GLsizei length, const GLchar *marker)
+{
+ (void)length;
+ (void)marker;
+ EAGL_ENTER(context, 0x1990);
+}
+
+static void
+my_glPopGroupMarkerEXT(void *context)
+{
+ EAGL_ENTER(context, 0x1998);
+}
+
+/*
+ * CoreAnimation's shaders are in the first version of the shading language, with one thing of
+ * Apple's own in them: sampler2DRect and texture2DRect(), a texture read at coordinates counted in
+ * its pixels (what it shows of IOSurfaces is read so). The language has no such thing, and in
+ * its first version no way to make one, since a shader cannot ask how big a texture is. In
+ * version 3.00 it can. So every shader is handed on as a 3.00 one: the words of the first
+ * version that 3.00 dropped are defined back, and texture2DRect() divides by textureSize().
+ * (All of a program's shaders must be of one version, so all are treated alike.)
+ */
+#define GL_FRAGMENT_SHADER 0x8b30
+
+static const char fragment_start[] =
+ "#define varying in\n"
+ "#define texture2D texture\n"
+ "#define texture2DProj textureProj\n"
+ "#define texture2DLod textureLod\n"
+ "#define textureCube texture\n"
+ "#define sampler2DRect sampler2D\n"
+ "#define texture2DRect(s, c) texture(s, (c) / vec2(textureSize(s, 0)))\n"
+ "layout(location = 0) out highp vec4 redwood_colour[1];\n"
+ "#define gl_FragData redwood_colour\n"
+ "#define gl_FragColor redwood_colour[0]\n"
+ "#line 1\n";
+static const char vertex_start[] =
+ "#define attribute in\n"
+ "#define varying out\n"
+ "#define texture2D texture\n"
+ "#define texture2DLod textureLod\n"
+ "#line 1\n";
+
+static GLuint
+my_glCreateShader(void *context, GLenum type)
+{
+ struct eagl *e = context;
+ GLuint shader;
+
+ EAGL_ENTER(e, 0x1298);
+ shader = glCreateShader(type);
+ e->fragment[shader % 64] = type == GL_FRAGMENT_SHADER;
+ EAGL_LEAVE(e, 0x1298);
+ return shader;
+}
+
+/*
+ * CoreAnimation does not ask whether its shaders compiled. Here it is asked, and what the
+ * compiler said is written down with the shader's text.
+ */
+static void
+my_glShaderSource(void *context, GLuint shader, GLsizei count, const GLchar *const *strings, const GLint *lengths)
+{
+ struct eagl *e = context;
+ const char *start = e->fragment[shader % 64] ? fragment_start : vertex_start;
+ const GLchar *parts[3] = { "#version 300 es\n", start, NULL };
+ size_t size = 1, extensions = 0;
+ char *text, *line, *head;
+
+ EAGL_ENTER(e, 0x12a0);
+ for (GLsizei i = 0; i < count; i++) {
+ size += lengths != NULL && lengths[i] >= 0 ? (size_t)lengths[i] : strlen(strings[i]);
+ }
+ if ((text = calloc(1, 2 * size + sizeof(fragment_start) + 64)) == NULL) {
+ glShaderSource(shader, count, strings, lengths);
+ return;
+ }
+ for (GLsizei i = 0; i < count; i++) {
+ strncat(text, strings[i], lengths != NULL && lengths[i] >= 0 ? (size_t)lengths[i] : strlen(strings[i]));
+ }
+ /* "#extension" lines must stay ahead of everything that is not the preprocessor's: they move to the top */
+ head = text + size;
+ strcpy(head, parts[0]);
+ for (line = text; (line = strstr(line, "#extension")) != NULL; line += 2) {
+ size_t length = strcspn(line, "\n");
+
+ strncat(head, line, length);
+ strcat(head, "\n");
+ line[0] = line[1] = '/';
+ extensions++;
+ }
+ parts[0] = head;
+ parts[2] = text;
+ free((void *)e->sources[shader % 64]);
+ e->sources[shader % 64] = text;
+ glShaderSource(shader, 3, parts, NULL);
+ EAGL_LEAVE(e, 0x12a0);
+}
+
+static void
+say_long(const char *what, const char *text)
+{
+ say("redwood-gl: %s:\n", what);
+ for (size_t at = 0, length = strlen(text); at < length; at += 900) {
+ write(2, text + at, length - at < 900 ? length - at : 900);
+ }
+ say("\n");
+}
+
+static void
+my_glCompileShader(void *context, GLuint shader)
+{
+ struct eagl *e = context;
+ GLint good = 0;
+ char said[1024] = "";
+
+ EAGL_ENTER(e, 0x12a8);
+ glCompileShader(shader);
+ glGetShaderiv(shader, GL_COMPILE_STATUS, &good);
+ e->shaders++;
+ if (!good) {
+ glGetShaderInfoLog(shader, sizeof(said), NULL, said);
+ say("redwood-gl: A SHADER DOES NOT COMPILE (shader %u): %s\n", shader, said);
+ if (e->sources[shader % 64] != NULL) {
+ say_long("its text", e->sources[shader % 64]);
+ }
+ } else if ((e->shaders <= 2 || all_shaders) && e->sources[shader % 64] != NULL) {
+ say("redwood-gl: shader %u:\n", shader);
+ say_long(all_shaders ? "a shader" : "the first shaders, for the record", e->sources[shader % 64]);
+ }
+ EAGL_LEAVE(e, 0x12a8);
+}
+
+static void
+my_glLinkProgram(void *context, GLuint program)
+{
+ struct eagl *e = context;
+ GLint good = 0;
+ char said[1024] = "";
+
+ EAGL_ENTER(e, 0x12c0);
+ glLinkProgram(program);
+ glGetProgramiv(program, GL_LINK_STATUS, &good);
+ e->programs++;
+ if (!good) {
+ glGetProgramInfoLog(program, sizeof(said), NULL, said);
+ say("redwood-gl: A PROGRAM DOES NOT LINK (program %u): %s\n", program, said);
+ }
+ EAGL_LEAVE(e, 0x12c0);
+}
+
+/* iOS's library has one entry for deleting a program and deleting a shader. */
+static void
+my_glDeleteProgram(void *context, GLuint name)
+{
+ struct eagl *e = context;
+
+ EAGL_ENTER(e, 0x1280);
+ if (glIsProgram(name)) {
+ glDeleteProgram(name);
+ } else {
+ glDeleteShader(name);
+ }
+ EAGL_LEAVE(e, 0x1280);
+}
+
+#define EAGL_GEN_TABLE
+#include "eagl_gen.h"
+#undef EAGL_GEN_TABLE
+
+_Static_assert(EAGL_TABLE_SIZE <= SLOTS * 8, "the table has grown");
+
+/* ---- EAGLContext ---------------------------------------------------------------------------------- */
+
+static id
+my_initWithAPI(id self, SEL selector, unsigned long api, id properties)
+{
+ struct eagl *e;
+ unsigned place;
+
+ (void)selector;
+ (void)properties;
+ for (place = 0; place < sizeof(contexts) / sizeof(contexts[0]) && contexts[place] != NULL; place++) {
+ }
+ if (api < 2 || api > 3 || place == sizeof(contexts) / sizeof(contexts[0]) || (e = calloc(1, sizeof(*e))) == NULL) {
+ say("redwood-gl: no context of API %lu\n", api);
+ return nil;
+ }
+ if ((e->gl = redwood_gl_create((int)api)) == NULL || !redwood_gl_make_current(e->gl)) {
+ say("redwood-gl: %s gives no OpenGL ES %lu context\n", redwood_gl_library(), api);
+ free(e);
+ return nil;
+ }
+ current = e;
+ e->object = self;
+ e->api = api;
+ e->table[0] = e;
+ eagl_fill_table(e->table);
+ contexts[place] = e;
+ say("redwood-gl: an OpenGL ES %lu context for CoreAnimation, by %s: %s; %s; shaders %s\n", api, redwood_gl_library(),
+ (const char *)glGetString(GL_VERSION), (const char *)glGetString(GL_RENDERER),
+ (const char *)glGetString(GL_SHADING_LANGUAGE_VERSION));
+ return self;
+}
+
+static unsigned long
+my_API(id self, SEL selector)
+{
+ struct eagl *e = context_of(self);
+
+ (void)selector;
+ return e ? e->api : 0;
+}
+
+static unsigned long
+my_setParameter(id self, SEL selector, unsigned parameter, const int32_t *values)
+{
+ (void)self;
+ (void)selector;
+ say("redwood-gl: -setParameter:%#x to:%d: noted\n", parameter, values ? values[0] : 0);
+ return 0;
+}
+
+static void *
+my_getMacroContextPrivate(id self, SEL selector)
+{
+ struct eagl *e = context_of(self);
+
+ (void)selector;
+ return e ? e->table : NULL;
+}
+
+/* (the types are the method's own: the last three arrive on the stack, where sizes matter) */
+static BOOL
+my_texImageIOSurface(id self, SEL selector, IOSurfaceRef surface, unsigned long target, unsigned long internal,
+ GLsizei width, GLsizei height, unsigned long format, unsigned long type, uint32_t plane, BOOL invert)
+{
+ static unsigned shown;
+ struct eagl *e = context_of(self);
+ struct image *image;
+ GLint texture = 0;
+
+ (void)selector;
+ if (e == NULL || surface == NULL) {
+ return NO;
+ }
+ eagl_enter(e, 0);
+ glGetIntegerv(GL_TEXTURE_BINDING_2D, &texture);
+ if (target != GL_TEXTURE_2D || texture == 0 || (image = image_new(e, (GLuint)texture, surface)) == NULL) {
+ say("redwood-gl: -texImageIOSurface: target %#lx, texture %d: not done\n", target, texture);
+ return NO;
+ }
+ image->to = (GLenum)target;
+ image->internal = (GLenum)internal;
+ image->format = (GLenum)format;
+ image->type = (GLenum)type;
+ image->plane = plane;
+ image->invert = invert;
+ image->width = width;
+ image->height = height;
+ note_format(invert ? "IOSurface shown, inverted" : "IOSurface shown", image->internal, image->format, image->type, width,
+ height);
+ if (shown++ < 24) {
+ say("redwood-gl: -texImageIOSurface: surface %u ('%.4s' %zu x %zu, %zu planes) as texture %d: %d x %d, plane %u%s\n",
+ IOSurfaceGetID(surface), (const char *)&(uint32_t){ __builtin_bswap32(IOSurfaceGetPixelFormat(surface)) },
+ IOSurfaceGetWidth(surface), IOSurfaceGetHeight(surface), IOSurfaceGetPlaneCount(surface), texture, width,
+ height, plane, invert ? ", inverted" : "");
+ }
+ surface_to_texture(e, image);
+ eagl_leave(e, 0x970);
+ return YES;
+}
+
+/* (the "image" is the target, GL_TEXTURE_2D, and means the texture bound to it) */
+static BOOL
+my_attachImage(id self, SEL selector, unsigned long target, IOSurfaceRef surface, BOOL inverted)
+{
+ struct eagl *e = context_of(self);
+ static unsigned attached;
+ struct image *image;
+ GLint texture = 0;
+ uint32_t pixels;
+
+ (void)selector;
+ if (e == NULL || surface == NULL) {
+ return NO;
+ }
+ eagl_enter(e, 0);
+ glGetIntegerv(GL_TEXTURE_BINDING_2D, &texture);
+ pixels = IOSurfaceGetPixelFormat(surface);
+ if (target != GL_TEXTURE_2D || texture == 0 || (pixels != 'BGRA' && pixels != 0) ||
+ IOSurfaceGetBytesPerElement(surface) != 4 || IOSurfaceGetPlaneCount(surface) != 0 ||
+ (image = image_new(e, (GLuint)texture, surface)) == NULL) {
+ say("redwood-gl: -attachImage: target %#lx, texture %d, an IOSurface of '%.4s': not done\n", target, texture,
+ (const char *)&(uint32_t){ __builtin_bswap32(pixels) });
+ return NO;
+ }
+ image->target = true;
+ image->to = GL_TEXTURE_2D;
+ image->invert = inverted;
+ image->width = (GLsizei)IOSurfaceGetWidth(surface);
+ image->height = (GLsizei)IOSurfaceGetHeight(surface);
+ if (attached++ < 24) {
+ say("redwood-gl: -attachImage: texture %d is IOSurface %u ('%.4s' %d x %d, %zu bytes a row)%s\n", texture,
+ IOSurfaceGetID(surface), (const char *)&(uint32_t){ __builtin_bswap32(pixels) }, image->width, image->height,
+ IOSurfaceGetBytesPerRow(surface), inverted ? ", drawn inverted" : "");
+ }
+ note_format("IOSurface attached", GL_BGRA, GL_BGRA, GL_UNSIGNED_BYTE, image->width, image->height);
+ /*
+ * What is attached is as often read as drawn into (a picture CoreAnimation has made a surface
+ * around, to be shown): the texture starts with what the surface holds.
+ */
+ image->internal = image->format = GL_BGRA;
+ image->type = GL_UNSIGNED_BYTE;
+ surface_to_texture(e, image);
+ eagl_leave(e, 0x970);
+ return YES;
+}
+
+static void
+my_dealloc(id self, SEL selector)
+{
+ struct objc_super super = { self, class_getSuperclass(objc_getClass("EAGLContext")) };
+ struct eagl *e = context_of(self);
+
+ if (e != NULL) {
+ say("redwood-gl: the context goes\n");
+ summary(e);
+ for (unsigned i = 0; i < sizeof(contexts) / sizeof(contexts[0]); i++) {
+ if (contexts[i] == e) {
+ contexts[i] = NULL;
+ }
+ }
+ if (current == e) {
+ redwood_gl_make_current(NULL);
+ current = NULL;
+ }
+ redwood_gl_destroy(e->gl);
+ free(e);
+ }
+ ((void (*)(struct objc_super *, SEL))objc_msgSendSuper)(&super, selector);
+}
+
+__attribute__((constructor)) static void
+install(void)
+{
+ static const struct {
+ const char *name;
+ IMP ours;
+ } methods[] = {
+ { "initWithAPI:properties:", (IMP)my_initWithAPI },
+ { "API", (IMP)my_API },
+ { "setParameter:to:", (IMP)my_setParameter },
+ { "getMacroContextPrivate", (IMP)my_getMacroContextPrivate },
+ { "texImageIOSurface:target:internalFormat:width:height:format:type:plane:invert:", (IMP)my_texImageIOSurface },
+ { "attachImage:toCoreSurface:invertedRender:", (IMP)my_attachImage },
+ { "dealloc", (IMP)my_dealloc },
+ };
+ Class class = objc_getClass("EAGLContext");
+ unsigned replaced = 0;
+ char arguments[1024] = "";
+ size_t size = sizeof(arguments) - 1;
+ const char *argument;
+
+ /* the kernel's boot-args are where a run is told things */
+ if (sysctlbyname("kern.bootargs", arguments, &size, NULL, 0) == 0) {
+ if ((argument = strstr(arguments, "gltrace=")) != NULL) {
+ trace_last = trace_first = (unsigned)strtoul(argument + 8, (char **)&argument, 10);
+ if (*argument == '-') {
+ trace_last = (unsigned)strtoul(argument + 1, NULL, 10);
+ }
+ }
+ all_shaders = strstr(arguments, "glshaders=1") != NULL;
+ if ((argument = strstr(arguments, "glshow=")) != NULL) {
+ shown_texture = (GLuint)strtoul(argument + 7, NULL, 10);
+ }
+ }
+
+ if (class == Nil) {
+ say("redwood-gl: this program has no EAGLContext: nothing to do\n");
+ return;
+ }
+ for (unsigned i = 0; i < sizeof(methods) / sizeof(methods[0]); i++) {
+ SEL selector = sel_registerName(methods[i].name);
+ Method method = class_getInstanceMethod(class, selector);
+
+ if (method == NULL) {
+ say("redwood-gl: EAGLContext has no -%s\n", methods[i].name);
+ continue;
+ }
+ say("redwood-gl: -[EAGLContext %s] (%s) replaced\n", methods[i].name, method_getTypeEncoding(method));
+ if (method == class_getInstanceMethod(class_getSuperclass(class), selector)) {
+ /* inherited: the class gets one of its own, the one it inherits is everybody's */
+ class_addMethod(class, selector, methods[i].ours, method_getTypeEncoding(method));
+ } else {
+ method_setImplementation(method, methods[i].ours);
+ }
+ replaced++;
+ }
+ say("redwood-gl: %u of %zu methods of EAGLContext are ours; OpenGL ES by %s\n", replaced,
+ sizeof(methods) / sizeof(methods[0]), redwood_gl_library());
+}
diff --git a/userland/src/eagl_slots.txt b/userland/src/eagl_slots.txt
new file mode 100644
index 0000000..3a28c2d
--- /dev/null
+++ b/userland/src/eagl_slots.txt
@@ -0,0 +1,414 @@
+# The function table behind -[EAGLContext getMacroContextPrivate] of iOS 16.5 (20F66) OpenGLES: the offset of
+# each entry and the functions of OpenGLES.framework that call through it (read off their code: each loads
+# the table from thread-local storage and jumps through one offset). An entry is called as
+# entry(table[0], arguments...). '*' marks the entries QuartzCore's OpenGL ES renderer is seen to call.
+# userland/mkeagl.py makes the table of our own from this.
+0x0010 * glAlphaFunc
+0x0030 * glBindTexture
+0x0040 * glBlendFunc
+0x0058 * glClear
+0x0068 * glClearColor
+0x0080 * glClearStencil
+0x0130 - glColor4f
+0x0160 - glColor4ub
+0x0190 - glColorMask
+0x01a0 - glColorPointer
+0x01b8 - glCopyTexImage2D
+0x01c8 * glCopyTexSubImage2D
+0x01d0 - glCullFace
+0x01e0 * glDeleteTextures
+0x01e8 - glDepthFunc
+0x01f0 - glDepthMask
+0x0200 * glDisable
+0x0208 - glDisableClientState
+0x0210 * glDrawArrays
+0x0220 * glDrawElements
+0x0248 * glEnable
+0x0250 - glEnableClientState
+0x02d0 * glFinish
+0x02d8 * glFlush
+0x02e0 - glFogf
+0x02e8 - glFogfv
+0x0300 - glFrontFace
+0x0318 * glGenTextures
+0x0320 - glGetBooleanv
+0x0338 * glGetError
+0x0340 - glGetFloatv
+0x0348 * glGetIntegerv
+0x0350 - glGetLightfv
+0x0378 - glGetMaterialfv
+0x03a0 - glGetPointerv
+0x03b0 * glGetString
+0x03b8 - glGetTexEnvfv
+0x03c0 - glGetTexEnviv
+0x03e0 - glGetTexImage
+0x03e8 - glGetTexLevelParameterfv
+0x03f0 - glGetTexLevelParameteriv
+0x03f8 - glGetTexParameterfv
+0x0400 - glGetTexParameteriv
+0x0408 - glHint
+0x0480 - glIsEnabled
+0x0490 - glIsTexture
+0x0498 - glLightModelf
+0x04a0 - glLightModelfv
+0x04b8 - glLightf
+0x04c0 - glLightfv
+0x04e0 - glLineWidth
+0x04f0 - glLoadIdentity
+0x0500 - glLoadMatrixf
+0x0510 - glLogicOp
+0x0558 - glMaterialf
+0x0560 - glMaterialfv
+0x0578 - glMatrixMode
+0x0588 - glMultMatrixf
+0x05b8 - glNormal3f
+0x05e8 - glNormalPointer
+0x0620 * glPixelStorei
+0x0640 - glPointSize
+0x0650 - glPolygonOffset
+0x0670 - glPopMatrix
+0x0698 - glPushMatrix
+0x0768 - glReadBuffer
+0x0770 - glReadPixels
+0x07c8 - glRotatef
+0x07d8 - glScalef
+0x07e0 * glScissor
+0x07f0 - glShadeModel
+0x07f8 - glStencilFunc
+0x0800 - glStencilMask
+0x0808 - glStencilOp
+0x0910 - glTexCoordPointer
+0x0918 - glTexEnvf
+0x0920 - glTexEnvfv
+0x0928 - glTexEnvi
+0x0930 - glTexEnviv
+0x0970 * glTexImage2D
+0x0978 * glTexParameterf
+0x0980 - glTexParameterfv
+0x0988 * glTexParameteri
+0x0990 - glTexParameteriv
+0x09a0 * glTexSubImage2D
+0x09b0 - glTranslatef
+0x0a78 - glVertexPointer
+0x0a80 * glViewport
+0x0a88 * glBlendFuncSeparate glBlendFuncSeparateOES
+0x0a90 - glBlendColor
+0x0a98 * glBlendEquation glBlendEquationOES
+0x0ab0 - glClientActiveTexture
+0x0ab8 * glActiveTexture
+0x0b90 - glMultiTexCoord4f
+0x0be0 - glCompressedTexImage3D
+0x0be8 * glCompressedTexImage2D
+0x0bf8 - glCompressedTexSubImage3D
+0x0c00 - glCompressedTexSubImage2D
+0x0cb0 - glDrawRangeElements
+0x0db8 - glTexImage3D
+0x0dc0 - glTexSubImage3D
+0x0dc8 - glCopyTexSubImage3D
+0x0dd0 - glGetUniformIndices
+0x0dd8 - glGetActiveUniformsiv
+0x0de8 - glGetUniformBlockIndex
+0x0df0 - glGetActiveUniformBlockiv
+0x0df8 - glGetActiveUniformBlockName
+0x0e00 - glUniformBlockBinding
+0x0e58 - glBlendEquationSeparate glBlendEquationSeparateOES
+0x0e60 - glSampleCoverage
+0x0e80 - glGenFencesAPPLE
+0x0e88 - glDeleteFencesAPPLE
+0x0e90 - glSetFenceAPPLE
+0x0e98 - glIsFenceAPPLE
+0x0ea0 - glTestFenceAPPLE
+0x0ea8 - glFinishFenceAPPLE
+0x0eb0 - glTestObjectAPPLE
+0x0eb8 * glFinishObjectAPPLE
+0x0ee8 - glVertexAttrib1f
+0x0f00 - glVertexAttrib2f
+0x0f18 - glVertexAttrib3f
+0x0f30 - glVertexAttrib4f
+0x0f50 - glVertexAttrib1fv
+0x0f68 - glVertexAttrib2fv
+0x0f80 - glVertexAttrib3fv
+0x0fc0 - glVertexAttrib4fv
+0x1000 * glVertexAttribPointer
+0x1008 * glEnableVertexAttribArray
+0x1010 * glDisableVertexAttribArray
+0x1020 - glGetVertexAttribfv
+0x1028 - glGetVertexAttribiv
+0x1030 - glGetVertexAttribPointerv
+0x10e8 - glPointParameterf
+0x10f0 - glPointParameterfv
+0x1258 - glStencilOpSeparate
+0x1280 * glDeleteProgram glDeleteShader
+0x1290 - glDetachShader
+0x1298 * glCreateShader
+0x12a0 * glShaderSource
+0x12a8 * glCompileShader
+0x12b0 * glCreateProgram
+0x12b8 * glAttachShader
+0x12c0 * glLinkProgram
+0x12c8 * glUseProgram
+0x12d0 - glValidateProgram
+0x12d8 * glUniform1f
+0x12e0 - glUniform2f
+0x12e8 - glUniform3f
+0x12f0 * glUniform4f
+0x12f8 * glUniform1i
+0x1300 - glUniform2i
+0x1308 - glUniform3i
+0x1310 - glUniform4i
+0x1318 - glUniform1fv
+0x1320 - glUniform2fv
+0x1328 * glUniform3fv
+0x1330 * glUniform4fv
+0x1338 - glUniform1iv
+0x1340 - glUniform2iv
+0x1348 - glUniform3iv
+0x1350 - glUniform4iv
+0x1358 - glUniformMatrix2fv
+0x1360 * glUniformMatrix3fv
+0x1368 * glUniformMatrix4fv
+0x1390 * glGetUniformLocation
+0x1398 - glGetActiveUniform
+0x13a0 - glGetUniformfv
+0x13a8 - glGetUniformiv
+0x13b0 - glGetShaderSource
+0x13b8 * glBindAttribLocation
+0x13c0 - glGetActiveAttrib
+0x13c8 - glGetAttribLocation
+0x13d8 - glGenQueries glGenQueriesEXT
+0x13e0 - glDeleteQueries glDeleteQueriesEXT
+0x13e8 - glIsQuery glIsQueryEXT
+0x13f0 - glBeginQuery glBeginQueryEXT
+0x13f8 - glEndQuery glEndQueryEXT
+0x1400 - glGetQueryiv glGetQueryivEXT
+0x1408 - glGetQueryObjectivEXT
+0x1410 - glGetQueryObjectuiv glGetQueryObjectuivEXT
+0x1418 - glBindBuffer
+0x1420 - glDeleteBuffers
+0x1428 - glGenBuffers
+0x1430 - glIsBuffer
+0x1438 - glBufferData
+0x1440 - glBufferSubData
+0x1450 - glMapBufferOES
+0x1458 - glUnmapBuffer glUnmapBufferOES
+0x1460 - glGetBufferParameteriv
+0x1468 - glGetBufferPointerv glGetBufferPointervOES
+0x1478 - glDrawBuffers
+0x1480 - glIsShader
+0x1488 - glIsProgram
+0x1490 - glGetShaderiv
+0x1498 - glGetProgramiv
+0x14a0 - glGetShaderInfoLog
+0x14a8 - glGetProgramInfoLog
+0x14b0 - glStencilFuncSeparate
+0x14b8 - glStencilMaskSeparate
+0x14d0 - glIsRenderbuffer glIsRenderbufferOES
+0x14d8 - glBindRenderbuffer glBindRenderbufferOES
+0x14e0 - glDeleteRenderbuffers glDeleteRenderbuffersOES
+0x14e8 - glGenRenderbuffers glGenRenderbuffersOES
+0x14f0 - glRenderbufferStorage glRenderbufferStorageOES
+0x14f8 - glGetRenderbufferParameteriv glGetRenderbufferParameterivOES
+0x1500 - glIsFramebuffer glIsFramebufferOES
+0x1508 * glBindFramebuffer glBindFramebufferOES
+0x1510 * glDeleteFramebuffers glDeleteFramebuffersOES
+0x1518 * glGenFramebuffers glGenFramebuffersOES
+0x1520 - glCheckFramebufferStatus glCheckFramebufferStatusOES
+0x1530 * glFramebufferTexture2D glFramebufferTexture2DOES
+0x1540 - glFramebufferRenderbuffer glFramebufferRenderbufferOES
+0x1548 - glGetFramebufferAttachmentParameteriv glGetFramebufferAttachmentParameterivOES
+0x1550 * glGenerateMipmap glGenerateMipmapOES
+0x1590 - glProgramParameteri glProgramParameteriEXT
+0x15a0 - glFramebufferTextureLayer
+0x15b0 - glBindBufferRange
+0x15c0 - glBindBufferBase
+0x15c8 - glBeginTransformFeedback
+0x15d0 - glEndTransformFeedback
+0x15d8 - glTransformFeedbackVaryings
+0x15e0 - glGetTransformFeedbackVarying
+0x15e8 - glGetIntegeri_v
+0x1658 - glVertexAttribI4i
+0x1678 - glVertexAttribI4ui
+0x1698 - glVertexAttribI4iv
+0x16b8 - glVertexAttribI4uiv
+0x16e0 - glVertexAttribIPointer
+0x16e8 - glGetVertexAttribIiv
+0x16f0 - glGetVertexAttribIuiv
+0x16f8 - glUniform1ui
+0x1700 - glUniform2ui
+0x1708 - glUniform3ui
+0x1710 - glUniform4ui
+0x1718 - glUniform1uiv
+0x1720 - glUniform2uiv
+0x1728 - glUniform3uiv
+0x1730 - glUniform4uiv
+0x1738 - glGetUniformuiv
+0x1748 - glGetFragDataLocation
+0x1770 - glUniformMatrix2x3fv
+0x1778 - glUniformMatrix3x2fv
+0x1780 - glUniformMatrix2x4fv
+0x1788 - glUniformMatrix4x2fv
+0x1790 - glUniformMatrix3x4fv
+0x1798 - glUniformMatrix4x3fv
+0x17a0 - glBlitFramebuffer
+0x17a8 - glRenderbufferStorageMultisample glRenderbufferStorageMultisampleAPPLE
+0x17c0 - glGetAttachedShaders
+0x17d0 - glVertexAttribDivisorEXT glVertexAttribDivisor
+0x17d8 - glDrawArraysInstancedEXT glDrawArraysInstanced
+0x17e0 - glDrawElementsInstancedEXT glDrawElementsInstanced
+0x1808 - glBindVertexArray glBindVertexArrayOES
+0x1810 - glDeleteVertexArrays glDeleteVertexArraysOES
+0x1818 - glGenVertexArrays glGenVertexArraysOES
+0x1820 - glIsVertexArray glIsVertexArrayOES
+0x1828 - glPointSizePointerOES
+0x1838 - glClearBufferiv
+0x1840 - glClearBufferuiv
+0x1848 - glClearBufferfv
+0x1850 - glClearBufferfi
+0x1858 - glGetStringi
+0x1860 * glFenceSync glFenceSyncAPPLE
+0x1868 - glIsSync glIsSyncAPPLE
+0x1870 * glDeleteSync glDeleteSyncAPPLE
+0x1878 * glClientWaitSync glClientWaitSyncAPPLE
+0x1880 - glWaitSync glWaitSyncAPPLE
+0x1888 - glGetInteger64v glGetInteger64vAPPLE
+0x1890 - glGetSynciv glGetSyncivAPPLE
+0x18c0 - glCopyBufferSubData
+0x18e0 - glMapBufferRange glMapBufferRangeEXT
+0x18e8 - glFlushMappedBufferRange glFlushMappedBufferRangeEXT
+0x18f8 - glGetInteger64i_v
+0x1900 - glGetBufferParameteri64v
+0x1908 - glGenSamplers
+0x1910 - glDeleteSamplers
+0x1918 - glIsSampler
+0x1920 - glBindSampler
+0x1928 - glSamplerParameteri
+0x1930 - glSamplerParameteriv
+0x1938 - glSamplerParameterf
+0x1940 - glSamplerParameterfv
+0x1958 - glGetSamplerParameteriv
+0x1960 - glGetSamplerParameterfv
+0x1978 - glLabelObjectEXT
+0x1980 - glGetObjectLabelEXT
+0x1988 * glInsertEventMarkerEXT
+0x1990 * glPushGroupMarkerEXT
+0x1998 * glPopGroupMarkerEXT
+0x19a0 - glUseProgramStagesEXT
+0x19a8 - glActiveShaderProgramEXT
+0x19b0 - glCreateShaderProgramvEXT
+0x19b8 - glBindProgramPipelineEXT
+0x19c0 - glDeleteProgramPipelinesEXT
+0x19c8 - glGenProgramPipelinesEXT
+0x19d0 - glIsProgramPipelineEXT
+0x19d8 - glGetProgramPipelineivEXT
+0x19e0 - glValidateProgramPipelineEXT
+0x19e8 - glGetProgramPipelineInfoLogEXT
+0x19f0 - glProgramUniform1iEXT
+0x19f8 - glProgramUniform2iEXT
+0x1a00 - glProgramUniform3iEXT
+0x1a08 - glProgramUniform4iEXT
+0x1a10 - glProgramUniform1fEXT
+0x1a18 - glProgramUniform2fEXT
+0x1a20 - glProgramUniform3fEXT
+0x1a28 - glProgramUniform4fEXT
+0x1a30 - glProgramUniform1ivEXT
+0x1a38 - glProgramUniform2ivEXT
+0x1a40 - glProgramUniform3ivEXT
+0x1a48 - glProgramUniform4ivEXT
+0x1a50 - glProgramUniform1fvEXT
+0x1a58 - glProgramUniform2fvEXT
+0x1a60 - glProgramUniform3fvEXT
+0x1a68 - glProgramUniform4fvEXT
+0x1a70 - glProgramUniformMatrix2fvEXT
+0x1a78 - glProgramUniformMatrix3fvEXT
+0x1a80 - glProgramUniformMatrix4fvEXT
+0x1a88 - glProgramUniform1uiEXT
+0x1a90 - glProgramUniform2uiEXT
+0x1a98 - glProgramUniform3uiEXT
+0x1aa0 - glProgramUniform4uiEXT
+0x1aa8 - glProgramUniform1uivEXT
+0x1ab0 - glProgramUniform2uivEXT
+0x1ab8 - glProgramUniform3uivEXT
+0x1ac0 - glProgramUniform4uivEXT
+0x1ac8 - glProgramUniformMatrix2x3fvEXT
+0x1ad0 - glProgramUniformMatrix3x2fvEXT
+0x1ad8 - glProgramUniformMatrix2x4fvEXT
+0x1ae0 - glProgramUniformMatrix4x2fvEXT
+0x1ae8 - glProgramUniformMatrix3x4fvEXT
+0x1af0 - glProgramUniformMatrix4x3fvEXT
+0x1b58 - glReleaseShaderCompiler
+0x1b60 - glShaderBinary
+0x1b68 - glGetShaderPrecisionFormat
+0x1b70 - glDepthRangef
+0x1b78 - glClearDepthf
+0x1bc0 - glGetProgramBinary
+0x1bc8 - glProgramBinary
+0x1c48 - glBindTransformFeedback
+0x1c50 - glGenTransformFeedbacks
+0x1c58 - glDeleteTransformFeedbacks
+0x1c60 - glPauseTransformFeedback
+0x1c68 - glResumeTransformFeedback
+0x1c70 - glIsTransformFeedback
+0x1e48 - glAlphaFuncx
+0x1e50 - glClearColorx
+0x1e58 - glClearDepthx
+0x1e60 - glClipPlanef
+0x1e68 - glClipPlanex
+0x1e70 - glColor4x
+0x1e78 - glDepthRangex
+0x1e80 - glFogx
+0x1e88 - glFogxv
+0x1e90 - glFrustumf
+0x1e98 - glFrustumx
+0x1ea0 - glGetClipPlanef
+0x1ea8 - glGetClipPlanex
+0x1eb0 - glGetFixedv
+0x1eb8 - glGetLightxv
+0x1ec0 - glGetMaterialxv
+0x1ec8 - glGetTexEnvxv
+0x1ed0 - glGetTexParameterxv
+0x1ed8 - glLightModelx
+0x1ee0 - glLightModelxv
+0x1ee8 - glLightx
+0x1ef0 - glLightxv
+0x1ef8 - glLineWidthx
+0x1f00 - glLoadMatrixx
+0x1f08 - glMaterialx
+0x1f10 - glMaterialxv
+0x1f18 - glMultMatrixx
+0x1f20 - glNormal3x
+0x1f28 - glOrthof
+0x1f30 - glOrthox
+0x1f38 - glPointSizex
+0x1f40 - glPolygonOffsetx
+0x1f48 - glRotatex
+0x1f50 - glScalex
+0x1f58 - glTexEnvx
+0x1f60 - glTexEnvxv
+0x1f68 - glTexParameterx
+0x1f70 - glTexParameterxv
+0x1f78 - glTranslatex
+0x1f80 - glMultiTexCoord4x
+0x1f88 - glSampleCoveragex
+0x1f90 - glPointParameterx
+0x1f98 - glPointParameterxv
+0x1fa0 - glCurrentPaletteMatrixOES
+0x1fa8 - glLoadPaletteFromModelViewMatrixOES
+0x1fb0 - glMatrixIndexPointerOES
+0x1fb8 - glWeightPointerOES
+0x1fc0 - glDrawTexsOES
+0x1fc8 - glDrawTexiOES
+0x1fd0 - glDrawTexxOES
+0x1fd8 - glDrawTexsvOES
+0x1fe0 - glDrawTexivOES
+0x1fe8 - glDrawTexxvOES
+0x1ff0 - glDrawTexfOES
+0x1ff8 - glDrawTexfvOES
+0x2000 - glInvalidateFramebuffer glDiscardFramebufferEXT
+0x2008 * glFramebufferParameteriAPPLE
+0x2010 - glGetFramebufferParameteriAPPLE
+0x2018 - glResolveMultisampleFramebufferAPPLE
+0x2020 - glCopyTextureLevelsAPPLE
+0x2028 - glInvalidateSubFramebuffer
+0x2030 - glGetInternalformativ
+0x2040 - glTexStorage2D glTexStorage2DEXT
+0x2048 - glTexStorage3D
diff --git a/userland/src/gl_osmesa.c b/userland/src/gl_osmesa.c
new file mode 100644
index 0000000..89c43aa
--- /dev/null
+++ b/userland/src/gl_osmesa.c
@@ -0,0 +1,80 @@
+/*
+ * The OpenGL ES library behind src/eagl.c when that library is Mesa as tools/mk-mesa.sh builds
+ * it: any of its drivers that draws into memory, reached through its off-screen interface
+ * (OSMesa, given an OpenGL ES profile by tools/mesa/osmesa-es-profile.patch).
+ *
+ * This file is all that knows which library draws. eagl.c wants four things besides the gl*
+ * functions themselves: a context of a version of OpenGL ES, that context made the calling
+ * thread's, a context taken away again, and a name for the log. A library with another way to
+ * its contexts gets another file like this one.
+ */
+#include <stddef.h>
+#include <stdlib.h>
+
+#include "redwood_gl.h"
+
+/* GL/osmesa.h of Mesa */
+#define OSMESA_RGBA 0x1908
+#define OSMESA_FORMAT 0x22
+#define OSMESA_DEPTH_BITS 0x30
+#define OSMESA_STENCIL_BITS 0x31
+#define OSMESA_PROFILE 0x33
+#define OSMESA_CONTEXT_MAJOR_VERSION 0x36
+#define OSMESA_CONTEXT_MINOR_VERSION 0x37
+#define OSMESA_ES_PROFILE 0x38
+#define GL_UNSIGNED_BYTE 0x1401
+
+typedef struct osmesa_context *OSMesaContext;
+extern OSMesaContext OSMesaCreateContextAttribs(const int *attributes, OSMesaContext share);
+extern unsigned char OSMesaMakeCurrent(OSMesaContext context, void *buffer, unsigned type, int width, int height);
+extern void OSMesaDestroyContext(OSMesaContext context);
+
+/*
+ * OSMesa draws its "window" into memory handed to it. Nothing here draws into a window (the
+ * window server draws into textures of its own, see eagl.c): a few pixels will do.
+ */
+#define WINDOW 16
+
+struct redwood_gl {
+ OSMesaContext context;
+ unsigned char window[WINDOW * WINDOW * 4];
+};
+
+struct redwood_gl *
+redwood_gl_create(int version)
+{
+ const int attributes[] = {
+ OSMESA_FORMAT, OSMESA_RGBA, OSMESA_DEPTH_BITS, 24, OSMESA_STENCIL_BITS, 8,
+ OSMESA_PROFILE, OSMESA_ES_PROFILE, OSMESA_CONTEXT_MAJOR_VERSION, version, OSMESA_CONTEXT_MINOR_VERSION, 0,
+ 0
+ };
+ struct redwood_gl *gl = calloc(1, sizeof(*gl));
+
+ if (gl != NULL && (gl->context = OSMesaCreateContextAttribs(attributes, NULL)) == NULL) {
+ free(gl);
+ gl = NULL;
+ }
+ return gl;
+}
+
+int
+redwood_gl_make_current(struct redwood_gl *gl)
+{
+ if (gl == NULL) {
+ return OSMesaMakeCurrent(NULL, NULL, 0, 0, 0);
+ }
+ return OSMesaMakeCurrent(gl->context, gl->window, GL_UNSIGNED_BYTE, WINDOW, WINDOW);
+}
+
+void
+redwood_gl_destroy(struct redwood_gl *gl)
+{
+ OSMesaDestroyContext(gl->context);
+ free(gl);
+}
+
+const char *
+redwood_gl_library(void)
+{
+ return "Mesa, off-screen (OSMesa)";
+}
diff --git a/userland/src/inject.c b/userland/src/inject.c
index b1e747d..3ace322 100644
--- a/userland/src/inject.c
+++ b/userland/src/inject.c
@@ -27,6 +27,7 @@
*/
#include <CoreFoundation/CoreFoundation.h>
#include <dispatch/dispatch.h>
+#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <mach/mach.h>
@@ -44,6 +45,7 @@
extern const void *_dyld_get_shared_cache_range(size_t *length);
#define CACHE_BASE 0x180000000UL /* where the cache was built to be, before the slide */
+#define REDWOOD_GL "/redwood/lib/libredwood-gl.dylib"
static uintptr_t slide;
@@ -170,7 +172,7 @@ my_finish_update(void *display, void *update, unsigned flags)
static void *
my_renderer(void *server)
{
- static int failed;
+ static int failed, said;
void *renderer;
if (failed) {
@@ -180,6 +182,9 @@ my_renderer(void *server)
if (renderer == NULL) {
failed = 1;
say("redwood: no accelerated renderer; the software one will draw\n");
+ } else if (!said) {
+ said = 1;
+ say("redwood: the server has an accelerated renderer (%p)\n", renderer);
}
return renderer;
}
@@ -195,6 +200,38 @@ my_render_update(void *server, void *update, unsigned *flags)
return r;
}
+/*
+ * CoreAnimation draws a layer's pixels with one of ninety "functions" (a fragment shader each: an
+ * image as it is, an image through a colour matrix, a blur of so many samples, ...), and asks
+ * its renderer which of them it has. Its OpenGL ES renderer has not half of them (the Metal one
+ * has all). Which ones are asked for and missing is worth knowing: said once each.
+ * (The last of the ninety, "cst", is not asked about: the OpenGL ES renderer draws it with no
+ * program at all, which draws nothing. The lock screen's wallpaper goes that way.)
+ */
+#define VT_GLES_CONTEXT 0x1d5b3b540UL /* vtable for CA::OGL::GLESContext */
+
+static int (*orig_function_supported)(void *context);
+
+static int
+my_function_supported(void *context)
+{
+ static const char names[] =
+ "clr img ida cim cid mua m1a lrp lrc lra add spl s1a cma bds bco bim c33 c3b c4b c4p c3a c3x c4x bia grl ds4 ds6 "
+ "ds8 ups db2 db4 nb7 n11 n15 n19 n23 n27 vrd vrb sb3 axl rad rac con vcm vdk vlt map mpc crv hue clm hom opa met "
+ "srl ega sdr alt p3c edr hrm lut ovr ovl lub aup alm stl pc0 pc1 prc psl ps0 ps1 psm psr pcr pbl peo bib asg a75 "
+ "a50 atc ipc apl 3dl cst ";
+ static uint8_t said[256];
+ int supported = orig_function_supported(context);
+ uint8_t function = *(*(uint8_t **)((char *)context + 0x10) + 0x10);
+
+ if (!supported && !said[function]) {
+ said[function] = 1;
+ say("redwood: CoreAnimation's OpenGL ES renderer has no function %u (\"%.3s\"): what needs it is not drawn\n",
+ function, function < 90 ? names + 4 * function : "?");
+ }
+ return supported;
+}
+
static void
window_server_fixes(void)
{
@@ -208,6 +245,10 @@ window_server_fixes(void)
orig_renderer = replace_virtual("renderer", VSLOT(VT_EAGL_SERVER, 0x1a0), 0x1882e2548UL, my_renderer);
orig_render_update = replace_virtual("render_update", VSLOT(VT_EAGL_SERVER, 0x178), 0x18835770cUL,
my_render_update);
+ if (access(REDWOOD_GL, R_OK) == 0) {
+ orig_function_supported = replace_virtual("function_supported", VSLOT(VT_GLES_CONTEXT, 0x378), 0x1884a9308UL,
+ my_function_supported);
+ }
say("redwood: window server hooks %s\n", orig_is_ready && orig_ignore_update_p && orig_begin_update &&
orig_finish_update && orig_renderer && orig_render_update ? "installed" : "INCOMPLETE");
}
@@ -656,6 +697,16 @@ redwood_init(void)
}
slide = (uintptr_t)cache - CACHE_BASE;
if (strcmp(name, "backboardd") == 0) {
+ /*
+ * An OpenGL ES implementation for CoreAnimation, where the image has one (build.sh GL=1;
+ * src/eagl.c): it puts itself behind EAGLContext as it is loaded, and the renderer the
+ * server then gets is the OpenGL ES one.
+ */
+ if (access(REDWOOD_GL, R_OK) == 0) {
+ if (dlopen(REDWOOD_GL, RTLD_NOW) == NULL) {
+ say("redwood: %s: %s\n", REDWOOD_GL, dlerror());
+ }
+ }
window_server_fixes();
/*
* brightness_fixes() is not used for now: with it backboardd no longer took our touch
diff --git a/userland/src/redwood_gl.h b/userland/src/redwood_gl.h
new file mode 100644
index 0000000..211ff23
--- /dev/null
+++ b/userland/src/redwood_gl.h
@@ -0,0 +1,15 @@
+/*
+ * What src/eagl.c asks of the OpenGL ES library behind it besides the gl* functions: see
+ * src/gl_osmesa.c, the one implementation there is.
+ */
+#ifndef REDWOOD_GL_H
+#define REDWOOD_GL_H
+
+struct redwood_gl;
+
+struct redwood_gl *redwood_gl_create(int version); /* a context of OpenGL ES 2 or 3; NULL: none to be had */
+int redwood_gl_make_current(struct redwood_gl *gl); /* ... the calling thread's (NULL: none); 0 on failure */
+void redwood_gl_destroy(struct redwood_gl *gl);
+const char *redwood_gl_library(void); /* for the log */
+
+#endif