avatar_url stringlengths 47 116 ⌀ | name stringlengths 1 46 | full_name stringlengths 7 60 | created_at stringdate 2016-04-01 08:17:56 2025-05-20 11:38:17 | description stringlengths 0 387 ⌀ | default_branch stringclasses 44
values | open_issues int64 0 4.93k | stargazers_count int64 0 78.2k | forks_count int64 0 3.09k | watchers_count int64 0 78.2k | tags_url stringlengths 0 94 | license stringclasses 27
values | topics listlengths 1 20 | size int64 0 4.82M | fork bool 2
classes | updated_at stringdate 2018-11-13 14:41:18 2025-05-22 08:23:54 | has_build_zig bool 2
classes | has_build_zig_zon bool 2
classes | zig_minimum_version stringclasses 50
values | repo_from stringclasses 3
values | dependencies listlengths 0 38 | readme_content stringlengths 0 437k | dependents listlengths 0 21 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
https://avatars.githubusercontent.com/u/5453785?v=4 | zig-netip | ikavalio/zig-netip | 2023-01-16T20:53:27Z | A simple IP address library for zig | main | 0 | 0 | 1 | 0 | https://api.github.com/repos/ikavalio/zig-netip/tags | Unlicense | [
"ip",
"zig",
"zig-package",
"ziglang"
] | 83 | false | 2024-07-23T09:18:49Z | true | true | unknown | github | [] | zig-netip
This is mostly an educational project to implement a library similar to go's <a>netip</a>
using zig idioms and comptime features.
The library targets the latest stable release which is currently <code>0.13</code>.
Definitions
<ul>
<li><code>Ip4Addr</code>, <code>Ip6Addr</code>, <code>Ip6AddrScoped</code> (and an <code>Addr</code> union) address types that're small value types.
They can be converted to <code>std.net.Ip4Address</code> or
<code>std.net.Ip6Address</code>. All types have a bunch of comptime
friendly methods, e.g. <code>parse</code>, <code>get</code>, <code>toArray</code>, and
flexible-ish <code>format</code> specifiers.</li>
<li><code>Ip4Prefix</code>, <code>Ip6Prefix</code> (and a <code>Prefix</code> union) address types that're built on top of
<code>Ip4Addr</code> and <code>Ip6Addr</code> abstractions.</li>
</ul>
Examples
Check <a>the netip tests</a> for more.
```zig
test "Addr Example" {
// ipv4 create
const v4_addr1 = comptime try Ip4Addr.parse("192.0.2.1");
const v4_addr2 = try Addr.parse("192.0.2.1");
const v4_addr3 = Ip4Addr.fromArray(u8, [<em>]u8{ 192, 0, 2, 2 });
const v4_addr4 = Ip4Addr.fromArray(u16, [</em>]u16{ 0xC000, 0x0202 });
const v4_addr5 = Addr.init4(Ip4Addr.init(0xC0000203));
const v4_addr6 = Ip4Addr.fromNetAddress(try std.net.Ip4Address.parse("192.0.2.3", 1));
<code>// ipv6 create
const v6_addr1 = comptime try Ip6Addr.parse("2001:db8::1");
const v6_addr2 = try Addr.parse("2001:db8::1");
const v6_addr3 = Ip6Addr.fromArray(u8, [_]u8{ 0x20, 0x1, 0xd, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2 });
const v6_addr4 = Ip6Addr.fromArray(u16, [_]u16{ 0x2001, 0xdb8, 0, 0, 0, 0, 0, 0x2 });
const v6_addr5 = Addr.init6(Ip6Addr.init(0x2001_0db8_0000_0000_0000_0000_0000_0003));
const v6_addr6 = Ip6Addr.fromNetAddress(try std.net.Ip6Address.parse("2001:db8::3", 1));
// ipv6 scoped
const v6_scoped1 = comptime try Ip6AddrScoped.parse("2001:db8::1%eth2");
const v6_scoped2 = try Addr.parse("2001:db8::2%4");
// handle parsing errors
try testing.expect(Ip4Addr.parse("-=_=-") == Ip4Addr.ParseError.InvalidCharacter);
try testing.expect(Addr.parse("0.-=_=-") == Addr.ParseError.InvalidCharacter);
try testing.expect(Ip6Addr.parse("-=_=-") == Ip6Addr.ParseError.InvalidCharacter);
try testing.expect(Addr.parse("::-=_=-") == Addr.ParseError.InvalidCharacter);
// copy
const v4_addr7 = v4_addr5;
const v6_addr8 = v6_addr3;
_ = .{v4_addr7, v4_addr4, v4_addr6, v6_scoped1, v6_scoped2, v6_addr4, v6_addr6};
// compare via values
try testing.expectEqual(math.Order.eq, order(v4_addr1, v4_addr2.v4));
try testing.expectEqual(math.Order.lt, order(v6_addr1, v6_addr8));
try testing.expectEqual(math.Order.gt, order(v6_addr8, v6_addr1));
try testing.expectEqual(math.Order.gt, order(v6_addr2, v4_addr2)); // cross AF comparison
// print
try testing.expectFmt("192.0.2.1", "{}", .{v4_addr1});
try testing.expectFmt("c0.00.02.02", "{X}", .{v4_addr3});
try testing.expectFmt("11000000.0.10.11", "{b}", .{v4_addr5});
try testing.expectFmt("2001:db8::1", "{}", .{v6_addr1});
try testing.expectFmt("2001:db8:0:0:0:0:0:2", "{xE}", .{v6_addr3});
try testing.expectFmt("2001:0db8::0003", "{X}", .{v6_addr5});
try testing.expectFmt("2001:0db8:0000:0000:0000:0000:0000:0001", "{XE}", .{v6_addr2});
</code>
}
test "Prefix Example" {
// create a ipv6 prefix
const v6_prefix1 = try Ip6Prefix.init(try Ip6Addr.parse("2001:db8:85a3::1"), 48);
const v6_prefix2 = try Prefix.parse("2001:db8:85a3::/48");
<code>// create a prefix
const v4_prefix1 = try Ip4Prefix.init(try Ip4Addr.parse("192.0.2.1"), 24);
const v4_prefix2 = try Prefix.parse("192.0.2.1/24");
// compare mask bits
try testing.expectEqual(v6_prefix1.maskBits(), v6_prefix2.v6.maskBits());
try testing.expectEqual(v4_prefix1.maskBits(), v4_prefix2.v4.maskBits());
// handle parsing errors
try testing.expectError(Prefix.ParseError.Overflow, Prefix.parse("2001:db8::/256"));
try testing.expectError(Prefix.ParseError.Overflow, Prefix.parse("1.1.1.1/33"));
// print
try testing.expectFmt("2001:db8:85a3::1/48", "{}", .{v6_prefix1});
try testing.expectFmt("2001:0db8:85a3::0001/48", "{X}", .{v6_prefix1});
try testing.expectFmt("2001:db8:85a3::-2001:db8:85a3:ffff:ffff:ffff:ffff:ffff", "{R}", .{v6_prefix1});
try testing.expectFmt("192.0.2.0/24", "{}", .{v4_prefix1.canonical()});
try testing.expectFmt("192.0.2.0-192.0.2.255", "{R}", .{v4_prefix1});
// contains address
try testing.expect(v6_prefix2.containsAddr(try Addr.parse("2001:db8:85a3:cafe::efac")));
try testing.expect(v4_prefix2.containsAddr(try Addr.parse("192.0.2.42")));
// inclusion and overlap test
try testing.expectEqual(PrefixInclusion.sub, v6_prefix1.testInclusion(try Ip6Prefix.parse("2001:db8::/32")));
try testing.expect(v6_prefix2.overlaps(try Prefix.parse("2001:db8::/32")));
try testing.expectEqual(PrefixInclusion.sub, v4_prefix1.testInclusion(try Ip4Prefix.parse("192.0.2.0/16")));
try testing.expect(v4_prefix2.overlaps(try Prefix.parse("192.0.2.0/16")));
</code>
}
``` | [] |
https://avatars.githubusercontent.com/u/8497012?v=4 | zig-cat | apple-x-co/zig-cat | 2022-08-03T23:40:20Z | for learning | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/apple-x-co/zig-cat/tags | - | [
"zig"
] | 7 | false | 2023-11-01T17:25:32Z | true | false | unknown | github | [] | zig-cat
Build
<code>bash
zig build -Doptimize=ReleaseFast</code>
Run
```bash
zig build run -- README.md
OR echo Hello | zig build run
``` | [] |
https://avatars.githubusercontent.com/u/8497012?v=4 | zig-random | apple-x-co/zig-random | 2022-09-21T23:15:59Z | for learning | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/apple-x-co/zig-random/tags | - | [
"zig"
] | 5 | false | 2023-11-01T17:25:25Z | true | true | unknown | github | [
{
"commit": "refs",
"name": "uuid",
"tar_url": "https://github.com/dmgk/zig-uuid/archive/refs.tar.gz",
"type": "remote",
"url": "https://github.com/dmgk/zig-uuid"
}
] | zig-random
Build
<code>bash
zig build -Doptimize=ReleaseFast</code>
Run
<code>bash
zig build run -- uuidv4</code>
Random number
<code>./zig-random number</code>
UUIDv4
<code>./zig-random uuidv4</code> | [] |
https://avatars.githubusercontent.com/u/100539203?v=4 | xrwm-quest | xrwm/xrwm-quest | 2022-04-08T20:00:43Z | Cross platform VR/AR window manager | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/xrwm/xrwm-quest/tags | GPL-3.0 | [
"augmented-reality",
"cross-platform",
"linux",
"virtual-reality",
"vulkan",
"window-manager",
"zig"
] | 2,554 | false | 2023-01-27T23:37:27Z | true | false | unknown | github | [] |
About
A window manager based on <a>wlroots</a> specifically designed around use in virtual reality. Official support is currently only planned for the Oculus Quest 2. | [] |
https://avatars.githubusercontent.com/u/85593302?v=4 | switch | svelterust/switch | 2022-11-18T23:08:59Z | Simple switch development setup that uses Nix and Zig | master | 0 | 0 | 0 | 0 | https://api.github.com/repos/svelterust/switch/tags | - | [
"nix",
"zig"
] | 7 | false | 2022-11-18T23:22:42Z | true | false | unknown | github | [] | switch
<code>git clone https://github.com/knarkzel/switch
cd switch
nix-shell
zig build</code>
Resources
<ul>
<li><a>switch-examples</a></li>
<li><a>libnx repository</a></li>
<li><a>libnx documentation</a></li>
</ul> | [] |
https://avatars.githubusercontent.com/u/67346305?v=4 | moetranslate2 | rlapz/moetranslate2 | 2022-04-16T15:57:47Z | A beautiful and simple language translator | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/rlapz/moetranslate2/tags | MIT | [
"translator",
"zig"
] | 115 | false | 2023-04-19T14:07:38Z | true | false | unknown | github | [] | moetranslate2
A beautiful and simple language translator written in Zig
Currently Supported:
<ol>
<li>Google Translate API</li>
</ol>
How to Install:
Git clone:
<code>git clone https://github.com/rlapz/moetranslate2 --recursive --depth 1</code>
Zig version: 0.10.x
```
zig build -Drelease-safe -p /usr
OR
zig build -Drelease-fast -p /usr
```
How to Uninstall:
<code>zig build uninstall -p /usr</code>
How to Use:
```
moetranslate2 [OPT] [SOURCE:TARGET] [TEXT]
-b Brief output.
-f Full/detail output.
-r Raw output (json).
-d Detect language.
-i Interactive input mode.
-h Show help.
```
<ol>
<li>
Brief output:
<code>moetranslate2 -b auto:id "Hello world\!"</code>
<code>auto</code> -> automatic detection
<code>id</code> -> Indonesian language code
2. Full/detail output:
<code>moetranslate2 -f en:id "Hello wrld\!"</code>
<code>en</code> -> English language code
Will show translated WORD/SENTENCE with more information.
3. Interactive input mode:
<code>moetranslate2 -i
moetranslate2 -i -f auto:en hello
moetranslate2 -if auto:en</code>
4. Show help:
<code>moetranslate2 -h</code>
</li>
</ol>
Language Code:
https://cloud.google.com/translate/docs/languages
License
MIT | [] |
https://avatars.githubusercontent.com/u/49767738?v=4 | smc | quentin-k/smc | 2022-03-24T22:59:48Z | Self modifying code in zig | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/quentin-k/smc/tags | - | [
"zig"
] | 5 | false | 2022-03-24T23:01:27Z | true | false | unknown | github | [] | Self Modifying Code PoC in Zig
This code has only been tested on x86_64 linux.
Special thanks to InKryption in the zig discord for helping me getting this to work.
Valgrind
If you want to analyze the program's memory usage you will have to use <code>-Dvalgrind</code> | [] |
https://avatars.githubusercontent.com/u/14140226?v=4 | zig_playground | dxps/zig_playground | 2022-03-18T08:08:10Z | A playground for study and experiments using Zig programming language | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/dxps/zig_playground/tags | - | [
"zig",
"ziglang"
] | 267 | false | 2025-02-03T08:41:08Z | false | false | unknown | github | [] | Zig Playground
This is a playground for study and experiments using <a>Zig</a> programming language. | [] |
https://avatars.githubusercontent.com/u/8497012?v=4 | zig-pdflib-lite-test | apple-x-co/zig-pdflib-lite-test | 2022-12-13T00:44:57Z | for learning | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/apple-x-co/zig-pdflib-lite-test/tags | - | [
"zig"
] | 0 | false | 2022-12-16T08:26:04Z | false | false | unknown | github | [] | zig-pdflib-lite-test | [] |
https://avatars.githubusercontent.com/u/24885580?v=4 | lox-zig | mcmcgrath13/lox-zig | 2022-10-10T00:56:57Z | a bytecode virtual machine for lox | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/mcmcgrath13/lox-zig/tags | MIT | [
"zig"
] | 107 | false | 2022-10-13T19:47:23Z | true | false | unknown | github | [] | lox-zig
a bytecode virtual machine for lox
Setup
Prerequesites:
* zig 0.9.1
Run a REPL
<code>zig build run</code>
Run a file
<code>zig build run -- file.lox</code> | [] |
https://avatars.githubusercontent.com/u/8497012?v=4 | zig-sleep | apple-x-co/zig-sleep | 2022-10-23T23:16:00Z | for learning | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/apple-x-co/zig-sleep/tags | - | [
"zig"
] | 13 | false | 2023-11-01T17:25:22Z | true | false | unknown | github | [] | zig-sleep
Build
<code>bash
zig build -Doptimize=ReleaseFast</code>
Run
<code>bash
zig build run -- 1</code>
Demo
https://user-images.githubusercontent.com/8497012/202054665-789af9f8-7b1a-496a-b7f9-6d04c452b131.mov | [] |
https://avatars.githubusercontent.com/u/8497012?v=4 | ziglings | apple-x-co/ziglings | 2022-08-20T08:27:24Z | null | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/apple-x-co/ziglings/tags | MIT | [
"zig"
] | 168 | false | 2022-12-16T08:25:42Z | true | false | unknown | github | [] | Ziglings
Welcome to Ziglings! This project contains a series of tiny broken programs.
By fixing them, you'll learn how to read and write
<a>Zig</a>
code.
Those tiny broken programs need your help! (You'll also save the planet from
evil aliens and help some friendly elephants stick together, which is very
sweet of you.)
This project was directly inspired by the brilliant and fun
<a>rustlings</a>
project for the <a>Rust</a> language.
Indirect inspiration comes from <a>Ruby Koans</a>
and the Little LISPer/Little Schemer series of books.
Intended Audience
This will probably be difficult if you've <em>never</em> programmed before.
But no specific programming experience is required. And in particular,
you are <em>not</em> expected to have any prior experience with "systems programming"
or a "systems" level language such as C.
Each exercise is self-contained and self-explained. However, you're encouraged
to also check out these Zig language resources for more detail:
<ul>
<li>https://ziglearn.org/</li>
<li>https://ziglang.org/documentation/master/</li>
</ul>
Also, the <a>Zig community</a> is incredibly friendly and helpful!
Getting Started
Install a <a>development build</a> of the Zig compiler.
(See the "master" section of the downloads page.)
Verify the installation and build number of <code>zig</code> like so:
<code>bash
$ zig version
0.10.0-dev.3385+xxxxxxxxx</code>
Clone this repository with Git:
<code>bash
$ git clone https://github.com/ratfactor/ziglings
$ cd ziglings</code>
Then run <code>zig build</code> and follow the instructions to begin!
<code>bash
$ zig build</code>
A Note About Versions
The Zig language is under very active development. In order to be current,
Ziglings tracks <strong>development</strong> builds of the Zig compiler rather than
versioned <strong>release</strong> builds. The last stable release was <code>0.9.1</code>, but Ziglings
needs a dev build with pre-release version "0.10.0" and a build number at least
as high as that shown in the example version check above.
It is likely that you'll download a build which is <em>greater</em> than the minimum.
<em>(For those who cannot easily update Zig, there are also community-supported
branches in this repo. At the moment, there's one for v0.8.1. Older version
branches may or may not have all exercises and/or bugfixes.)</em>
Once you have a build of the Zig compiler that works with Ziglings, they'll
continue to work together. But keep in mind that if you update one, you may
need to also update the other.
Also note that the current "stage 1" Zig compiler is very strict
about input:
<a>no tab characters or Windows CR/LF newlines are allowed</a>.
Version Changes
<ul>
<li><em>2022-07-31</em> zig 0.10.0-dev.3385 - std lib string fmt() option changes</li>
<li><em>2022-03-19</em> zig 0.10.0-dev.1427 - method for getting sentinel of type changed</li>
<li><em>2021-12-20</em> zig 0.9.0-dev.2025 - <code>c_void</code> is now <code>anyopaque</code></li>
<li><em>2021-06-14</em> zig 0.9.0-dev.137 - std.build.Id <code>.Custom</code> is now <code>.custom</code></li>
<li><em>2021-04-21</em> zig 0.8.0-dev.1983 - std.fmt.format() <code>any</code> format string required</li>
<li><em>2021-02-12</em> zig 0.8.0-dev.1065 - std.fmt.format() <code>s</code> (string) format string required</li>
</ul>
Advanced Usage
It can be handy to check just a single exercise or <em>start</em> from a single
exercise:
<code>bash
zig build 19
zig build 19_start</code>
You can also run without checking for correctness:
<code>bash
zig build 19_test</code>
Or skip the build system entirely and interact directly with the compiler
if you're into that sort of thing:
<code>bash
zig run exercises/001_hello.zig</code>
Calling all wizards: To prepare an executable for debugging, install it
to zig-cache/bin with:
<code>bash
zig build 19_install</code>
What's Covered
I've decide to limit Ziglings to the core language and not
attempt coverage of the Standard Library. Perhaps you can change
my mind?
Core Language
<ul>
<li>[x] Hello world (main needs to be public)</li>
<li>[x] Importing standard library</li>
<li>[x] Assignment</li>
<li>[x] Arrays</li>
<li>[x] Strings</li>
<li>[x] If</li>
<li>[x] While</li>
<li>[x] For</li>
<li>[x] Functions</li>
<li>[x] Errors (error/try/catch/if-else-err)</li>
<li>[x] Defer (and errdefer)</li>
<li>[x] Switch</li>
<li>[x] Unreachable</li>
<li>[x] Enums</li>
<li>[x] Structs</li>
<li>[x] Pointers</li>
<li>[x] Optionals</li>
<li>[x] Struct methods</li>
<li>[x] Slices</li>
<li>[x] Many-item pointers</li>
<li>[x] Unions</li>
<li>[x] Numeric types (integers, floats)</li>
<li>[x] Labelled blocks and loops</li>
<li>[x] Loops as expressions</li>
<li>[x] Builtins</li>
<li>[x] Inline loops</li>
<li>[x] Comptime</li>
<li>[x] Sentinel termination</li>
<li>[x] Quoted identifiers @""</li>
<li>[x] Anonymous structs/tuples/lists</li>
<li>[ ] Async <--- IN PROGRESS!</li>
</ul>
Contributing
Contributions are very welcome! I'm writing this to teach myself and to create
the learning resource I wished for. There will be tons of room for improvement:
<ul>
<li>Wording of explanations</li>
<li>Idiomatic usage of Zig</li>
<li>Maybe additional exercises?</li>
</ul>
Please see CONTRIBUTING.md in this repo for the full details. | [] |
https://avatars.githubusercontent.com/u/410846?v=4 | zaper | whytheplatypus/zaper | 2022-09-22T14:23:58Z | yet another gif wallpaper tool (and my excuse to learn some zig) | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/whytheplatypus/zaper/tags | - | [
"animated",
"desktop",
"gif",
"linux",
"wallpaper",
"x11",
"zig"
] | 34 | false | 2022-10-16T13:56:06Z | true | false | unknown | github | [] | Zaper
Zaper is an animated desktop background setter for X11
This was created as an excuse to experiment with zig and generally practice.
Inspired by <a>paperview</a> with a goal of getting it to work with compositors like picom.
Build
zig build -Drelease-safe
Usage
Creating a scene
<code>mkdir ascene
cd ascene
convert -coalesce path/to/animated.gif out.bmp</code>
Setting a scene
<code>zap ascene..</code>
To set a scene per monitor supply a folder for each:
```
for example I have two monitors:
zap left right
```
Known Issues
In order to work with picom this creates a new x11 desktop to paint the animation on, I'm betting this could cause some people problems. | [] |
https://avatars.githubusercontent.com/u/50817549?v=4 | zigr | Fuwn/zigr | 2022-08-02T22:35:03Z | 🦎 Experimental Zig bindings to TIGR | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/Fuwn/zigr/tags | NOASSERTION | [
"bindings",
"tigr",
"zig"
] | 7 | false | 2022-08-02T22:37:59Z | true | false | unknown | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/20910059?v=4 | zig_string | AS400JPLPC/zig_string | 2022-10-08T18:48:25Z | UTF-8 String Library | master | 0 | 0 | 0 | 0 | https://api.github.com/repos/AS400JPLPC/zig_string/tags | - | [
"string",
"string-manipulation",
"zig",
"zoned"
] | 1,976 | false | 2025-03-12T06:28:53Z | false | false | unknown | github | [] | zig_string
UTF-8 String Library
FORK
<a>JakubSzark/zig-string</a>
<strong>a big thank-you Jakub Szarkowicz real work</strong>
This library is a UTF-8 compatible <strong>string</strong> library for the <strong>Zig</strong> programming language.
I made this for the sole purpose to further my experience and understanding of zig.
Also it may be useful for some people who need it (including myself), with future projects. Project is also open for people to add to and improve. Please check the <strong>issues</strong> to view requested features.
If you use an uninitialized or already uninitialized field, this will trigger an @panic error. --> CRTL
The special feature: the addition of normalization to match the use in databases as well as when using screens or for lists.
Basic Usage
```zig
const zfld = @import("zfield");
// ...
// Create your String
// nbc = 0 usual string
// nbc > 0 usual varchar(..) --> zoned
var myString = zfld.ZFIELD.init(30);
defer myString.deinit();
// Use functions provided
try myString.concat("🔥 Hello!");
_ = myString.pop();
try myString.concat(", World 🔥");
std.debug.print("{s}",.{myString.string()});
```
<em>Look at the test.zig and testmem.zig files</em>
Things needed
<ul>
<li>Optimizations</li>
<li>Better documentation</li>
<li>More Testing</li>
</ul>
How to Contribute
<ol>
<li>Fork</li>
<li>debug</li>
<li>Make a Test</li>
</ol>
(I'm no expert when it comes to complexity)
<code>var arenaZfld = std.heap.ArenaAllocator.init(std.heap.page_allocator);
var allocZfld = arenaZfld.allocator();
pub fn deinitZfld() void {
arenaZfld.deinit();
arenaZfld = std.heap.ArenaAllocator.init(std.heap.page_allocator);
allocZfld = arenaZfld.allocator();
}</code>
|Function | Description | Pub |Debug|Option|bool|Panic|Crtl |
|--------------|------------------------------------------|-----|-----|------|----|-----|-----|
|init | Creates String with Allocator & nbr char | x | | | | | |
|deinit | De-allocates the String | x | | | | | |
| | | | | | | | |
|allocate | Sets the internal buffer size | | | | | | x |
|capacity | Returns the capacity of the String | x | | | | | x |
|getnbc | Return the numbers init char | x | | | | | |
|Count | Returns count of characters stored | x | | | | | x |
| | | | | | | | |
|clear | Clears the contents of the String | x | | | | | x |
|cmpeql | Compares to (zlfd,zfld) | x | | | x | | x |
|cmpeqlStr | Compares to string literal | x | | | x | | x |
|cmpxx | Compares to (zlfd,zfld) l EQ LT GT | x | | | | | x |
|cmpxxStr | Compares to string literal EQ LT GT | x | | | x | | x |
| | | | | | | | |
|setZfld | Erase append string literal of normalize | x | | | | | x |
|Normalize | Truncate for SQL Screen ex:varchar(10) | | | | | | |
|getstr | Returns the String as a slice | | | | | | |
|string | Returns the Field string | x | | | | | x |
| | | | | | | | |
|clone | Duplicate field | x | | | | | x |
|pop | Removes the last character | x | x | | | | x |
|copy | Copies this string to a new one field | x | | | | | x |
| | | | | | | | |
|substr | Sub-string a range of characters | x | x | | | x | x |
|remove | Removes a range of characters | x | x | | | x | x |
| | | | | | | | |
|isEmpty | Checks if length is zero | x | | | | | |
|find | Finds first string literal appearance | x | | x | x | | x |
|rfind | Finds last string literal appearance | x | | x | | | x |
|findpos | Finds position occurrence of literal | x | | x | | | x |
| | | | | | | | |
|concat | Appends a characters of the field | x | | | | | x |
|concatStr | Appends a characters of the literal | x | | | | | x |
|truncat | Reallocates the buffer to size | x | x | | | x | x |
| | | | | | | | |
|replace | Replaces all occurrences of a zstring | x | | | x | | x |
|reverse | Reverses the characters in this zstring | x | | | | | x |
| | | | | | | | |
|lowercase | Converts to lowercase | x | | | | | x |
|uppercase | Converts to uppercase | x | | | | | x |
|capitalized | Converts to uppercase first word | x | | | | | x |
| | | | | | | | |
|trim | trim(zstring,whitelist) | x | | | | | x |
|trimLeft | trimLef(zstring,whitelist) | x | | | | | x |
|trim | trimRight(zstring,whitelist) | x | | | | | x |
| | | | | | | | |
|check | Checks if the needle zstring | x | | | x | | x |
|checkStr | Checks if the needle Literal | x | | | x | | x |
| | | | | | | | |
|charAt | Returns character at index | x | x | | | x | x |
| | | | | | | | |
|zfldIterator | Struct Iterator | x | | | | | |
|next | next iterator Char(UTF8) | x | | | | | |
|iterator | Returns a StringIterator over the String | x | | | | | |
|isUTF8Byte | Checks if byte is part of UTF-8 character| | | | | | |
|getUTF8Size | Returns the UTF-8 character's size | | | | | | |
|getIndex | Returns the real index of a unicode | | | x | | | |
global allocator
```
var arenaZfld = std.heap.ArenaAllocator.init(std.heap.page_allocator);
var allocZfld = arenaZfld.allocator();
<code>pub fn deinitZfld() void {
arenaZfld.deinit();
arenaZfld = std.heap.ArenaAllocator.init(std.heap.page_allocator);
allocZfld = arenaZfld.allocator();
}
</code>
```
if use zlfd.deinitZfld();
<strong>All tests comply with AS400 processing requirements</strong>
Progress:
<ul>
<li>2025-01-30 18:53 -> Control, test and lock, security, compliance, a few hours or days... test the principle.
I'm not satisfied, I'd like to have a "job-logs"' a bit like the system log,
I'm thinking of a follow-up done with SQLite with a mini-server ... for optimum traceability.</li>
<li>2025-03-07 04:55 -> zig 0.14.0 </li>
<li>2025-03-10 17:25 -> Resuming diagnostics with the better-understood 0.14.0 @src deciphering @panic</li>
</ul>
→ 2025-03-12 06:40 unicode.Decode deprecated change Utf8View
| [] |
https://avatars.githubusercontent.com/u/4615889?v=4 | zig-plain-argparse | Techcable/zig-plain-argparse | 2022-05-23T08:41:40Z | [WIP] An lightweight argument parser for Zig. Uses imperative (rather than declarative) parsing. | master | 2 | 0 | 0 | 0 | https://api.github.com/repos/Techcable/zig-plain-argparse/tags | MIT | [
"argparse",
"zig"
] | 12 | false | 2022-05-23T08:43:10Z | true | false | unknown | github | [] | zig-plain-argparse
[WIP] A "plain" argument parsing library for Zig.
The key feature is that it parses arguments imperatively (not declaratively).
This makes it lower-level than <a>zig-clap</a>, which is more declarative (and probably better for general use).
Motiviation
Hopefully this more imperitive design reduce the amount of compile time magic . :)
I couldn't understand zig-clap well enough to implement "proper" subcommands.
In this more imperative style of parsing, subcommands are not a problem because they are just positional values.
You can parse a subcommand as a Zig enum, then create a new parser for the remaining arguments.
Also another plus side is zero allocation ;)
Features
<ul>
<li>Good error messages (descriptive errors)</li>
<li>Zero allocation (<code>Parser</code> is a thin wrapper around <code>[][]const u8</code>)</li>
<li>Imperative argument parsing (hopefully) minimizes comptime complexity</li>
<li>Support for subcommands follows nicely from the simplicity</li>
<li>See examples for this (TODO)</li>
</ul>
Missing features (TODO?)
<ul>
<li>Automatic help generation</li>
<li>This would be nice</li>
<li>More tests</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/166043157?v=4 | git | FnCtrlOption/git | 2022-03-02T17:51:03Z | Git fork, experimenting with Zig | zig | 0 | 0 | 0 | 0 | https://api.github.com/repos/FnCtrlOption/git/tags | NOASSERTION | [
"zig"
] | 182,218 | true | 2024-08-24T22:55:11Z | false | false | unknown | github | [] | <a></a>
Git - fast, scalable, distributed revision control system
Git is a fast, scalable, distributed revision control system with an
unusually rich command set that provides both high-level operations
and full access to internals.
Git is an Open Source project covered by the GNU General Public
License version 2 (some parts of it are under different licenses,
compatible with the GPLv2). It was originally written by Linus
Torvalds with help of a group of hackers around the net.
Please read the file <a>INSTALL</a> for installation instructions.
Many Git online resources are accessible from <a>https://git-scm.com/</a>
including full documentation and Git related tools.
See <a>Documentation/gittutorial.txt</a> to get started, then see
<a>Documentation/giteveryday.txt</a> for a useful minimum set of commands, and
<code>Documentation/git-<commandname>.txt</code> for documentation of each command.
If git has been correctly installed, then the tutorial can also be
read with <code>man gittutorial</code> or <code>git help tutorial</code>, and the
documentation of each command with <code>man git-<commandname></code> or <code>git help
<commandname></code>.
CVS users may also want to read <a>Documentation/gitcvs-migration.txt</a>
(<code>man gitcvs-migration</code> or <code>git help cvs-migration</code> if git is
installed).
The user discussion and development of Git take place on the Git
mailing list -- everyone is welcome to post bug reports, feature
requests, comments and patches to git@vger.kernel.org (read
<a>Documentation/SubmittingPatches</a> for instructions on patch submission
and <a>Documentation/CodingGuidelines</a>).
Those wishing to help with error message, usage and informational message
string translations (localization l10) should see <a>po/README.md</a>
(a <code>po</code> file is a Portable Object file that holds the translations).
To subscribe to the list, send an email with just "subscribe git" in
the body to majordomo@vger.kernel.org (not the Git list). The mailing
list archives are available at <a>https://lore.kernel.org/git/</a>,
<a>http://marc.info/?l=git</a> and other archival sites.
Issues which are security relevant should be disclosed privately to
the Git Security mailing list <a>git-security@googlegroups.com</a>.
The maintainer frequently sends the "What's cooking" reports that
list the current status of various development topics to the mailing
list. The discussion following them give a good reference for
project status, development direction and remaining tasks.
The name "git" was given by Linus Torvalds when he wrote the very
first version. He described the tool as "the stupid content tracker"
and the name as (depending on your mood):
<ul>
<li>random three-letter combination that is pronounceable, and not
actually used by any common UNIX command. The fact that it is a
mispronunciation of "get" may or may not be relevant.</li>
<li>stupid. contemptible and despicable. simple. Take your pick from the
dictionary of slang.</li>
<li>"global information tracker": you're in a good mood, and it actually
works for you. Angels sing, and a light suddenly fills the room.</li>
<li>"goddamn idiotic truckload of sh*t": when it breaks</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/44317699?v=4 | fasthttpparser | ajkachnic/fasthttpparser | 2022-02-25T20:52:31Z | A moderately fast HTTP 1.1 parser written in Zig. | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/ajkachnic/fasthttpparser/tags | - | [
"zig",
"zig-package"
] | 45 | false | 2022-02-25T20:53:33Z | true | false | unknown | github | [] | fasthttpparser
<em>Note: this is unstable and the API is likely to change; use at your own risk</em>
A HTTP 1.1 parser written in Zig. Currently competes with <a><code>httparse</code></a> and is beaten by <a><code>picohttpparser</code></a>
Benchmarks
| parser | one-long | one-short | smaller | bigger |
|----------------|----------|------------|------------|------------|
| fasthttpparser | 1.08gb/s | 987.54mb/s | 986.80mb/s | 984.49mb/s |
| picohttpparser | 3.04gb/s | 2.99gb/s | 3.06gb/s | 3.06gb/s |
You can run these yourself with <code>zig build bench</code>. I'll eventually extend the benchmark suite to include httparse, but I don't feel like dealing with Rust-Zig interop (test harness is written in Zig) at the moment.
Installation
Since the parser ships as a single file (<code>fasthttpparser.zig</code>), you can just drop that into your project.
Then, you could add it to your <code>build.zig</code> file as a package, or just import it directly. | [] |
https://avatars.githubusercontent.com/u/16129167?v=4 | autofixture | tris790/autofixture | 2022-04-30T00:58:29Z | Proof of concept of an autofixture library | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/tris790/autofixture/tags | - | [
"autofixture",
"metaprogramming",
"reflection",
"test",
"zig"
] | 1 | false | 2022-04-30T01:07:44Z | true | false | unknown | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/10215376?v=4 | aoc2022 | ymndoseijin/aoc2022 | 2022-12-01T05:37:36Z | written in Zig | master | 0 | 0 | 0 | 0 | https://api.github.com/repos/ymndoseijin/aoc2022/tags | Unlicense | [
"aoc2022",
"zig"
] | 59 | false | 2022-12-01T05:46:43Z | false | false | unknown | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/8497012?v=4 | zig-grep | apple-x-co/zig-grep | 2022-08-06T08:35:29Z | for learning | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/apple-x-co/zig-grep/tags | - | [
"zig"
] | 9 | false | 2023-11-01T17:25:24Z | true | true | unknown | github | [
{
"commit": "refs",
"name": "regex",
"tar_url": "https://github.com/psyGamer/zig-regex/archive/refs.tar.gz",
"type": "remote",
"url": "https://github.com/psyGamer/zig-regex"
}
] | zig-grep
Build
<code>bash
zig build -Doptimize=ReleaseFast</code>
Run
<code>bash
zig build run</code> | [] |
https://avatars.githubusercontent.com/u/1007628?v=4 | defense_of_ufeff | jcmoyer/defense_of_ufeff | 2022-10-14T18:57:17Z | Tower defense for a gamejam | master | 0 | 0 | 1 | 0 | https://api.github.com/repos/jcmoyer/defense_of_ufeff/tags | - | [
"game",
"gamedev",
"tower-defense",
"zig"
] | 1,233 | false | 2024-08-25T04:04:54Z | true | true | unknown | github | [
{
"commit": null,
"name": "zmath",
"tar_url": null,
"type": "relative",
"url": "thirdparty/zmath"
},
{
"commit": null,
"name": "stb",
"tar_url": null,
"type": "relative",
"url": "thirdparty/stb"
},
{
"commit": null,
"name": "gl33",
"tar_url": null,
"ty... | Building
Requires a zig compiler, and optionally python3 to install dependencies.
```
<blockquote>
python3 install-deps.py
zig build
```
</blockquote>
Dependencies
<ul>
<li><a>SDL</a>. zlib license.</li>
<li><a>zmath</a>. MIT license.</li>
<li><a>stb_image, stb_vorbis</a>. MIT license.</li>
<li><a>zig-opengl</a>. Bindings are in the
public domain.</li>
</ul>
License
All code under <code>src/</code> explicitly has no license, with the exception of:
<ol>
<li><code>src/sdl.zig</code>: this file contains handwritten bindings with portions of code
copied from SDL. It is likewise licensed under the zlib license.</li>
</ol>
<code>thirdparty/stb/</code> contains additional zig bindings that are likewise licensed
under the MIT License or as Public Domain (unlicense.org), whichever you prefer. | [] |
https://avatars.githubusercontent.com/u/67513038?v=4 | zig_lang_exercises | YoungHaKim7/zig_lang_exercises | 2022-07-13T14:10:45Z | My Youtube Channel - GlobalYoung https://www.youtube.com/@GlobalYoung7 | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/YoungHaKim7/zig_lang_exercises/tags | - | [
"zig"
] | 8,266 | false | 2025-04-21T07:40:30Z | false | false | unknown | github | [] |
link
<ul>
<li><a>zig-snippets정리중..</a></li>
</ul>
zig영상 모아보기(내가 공부하려고 만듬)
<ul>
<li>
https://youtube.com/playlist?list=PLcMveqN_07mbgfnYY9YIXo_Ls9FTSvDPx&si=5BwBs3uxkXolyOzb
</li>
<li>
<a>zig언어 100초 설명 | Fireship</a>
</li>
</ul>
Zig
https://ziglang.org/
Zig LSP (zls)
https://github.com/zigtools/zls
Zig 문서 검색
<ul>
<li>https://ziglang.org/learn/</li>
</ul>
Zig Tutorial
<ul>
<li>https://zig.guide/</li>
</ul>
zig(.gitignore)
<ul>
<li>https://github.com/ziglang/zig/blob/master/.gitignore
```gitignore</li>
</ul>
https://github.com/ziglang/zig/blob/master/.gitignore
.DS_Store
This file is for zig-specific build artifacts.
If you have OS-specific or editor-specific files to ignore,
such as *.swp or .DS_Store, put those in your global
~/.gitignore and put this in your ~/.gitconfig:
[core]
excludesfile = ~/.gitignore
Cheers!
-andrewrk
.zig-cache/
zig-out/
/release/
/debug/
/build/
/build-*/
/docgen_tmp/
Although this was renamed to .zig-cache, let's leave it here for a few
releases to make it less annoying to work with multiple branches.
zig-cache/
```
Learning Zig basics, multi threading and sockets in 30 minutes! | CallousCoder
https://youtu.be/E-MPhgtC_2s?si=vvFLBWZrCRDBcmhS
FLTK Zig: Basics(GUI)
https://youtu.be/D2ijlrDStdM
Awesome Zig
https://www.trackawesomelist.com/catdevnull/awesome-zig/readme/
Ziglings
<a>https://github.com/ratfactor/ziglings</a>
<a>답을 다 푼분이 있다. 역시 괴물이 많다. ㅋㅋㅋ </a>
<ul>
<li>Welcome to Ziglings! This project contains a series of tiny broken programs. By fixing them, you'll learn how to read and write Zig code.</li>
</ul>
Those tiny broken programs need your help! (You'll also save the planet from evil aliens and help some friendly elephants stick together, which is very sweet of you.)
This project was directly inspired by the brilliant and fun rustlings project for the Rust language. Indirect inspiration comes from Ruby Koans and the Little LISPer/Little Schemer series of books.
Intended Audience
This will probably be difficult if you've never programmed before. But no specific programming experience is required. And in particular, you are not expected to have any prior experience with "systems programming" or a "systems" level language such as C.
Each exercise is self-contained and self-explained. However, you're encouraged to also check out these Zig language resources for more detail:
<ul>
<li><a>https://ziglearn.org/</a></li>
<li><a>https://ziglang.org/documentation/master/</a></li>
</ul>
Also, the Zig community is incredibly friendly and helpful!
Zig tutorial part1
<a>Zig Tutorial part 1 __ Simon Clavet
</a>
<ul>
<li>
https://www.openmymind.net/learning_zig/
</li>
<li>
Zig 프로그래밍 언어 배우기 (openmymind.net)
https://news.hada.io/topic?id=11006&utm_source=discord&utm_medium=bot&utm_campaign=1480
Zig 설치하기
언어 개요
스타일 가이드
포인터
스택 메모리
힙 메모리 및 할당자
제네릭
Zig로 코딩하기
</li>
<li>
Zig 프로그래밍 언어 배우기 (openmymind.net)
https://news.hada.io/topic?id=10938
Zig 설치하기
언어 개요
스타일 가이드
포인터
스택 메모리
힙 메모리 및 할당자
제네릭
Zig로 코딩하기
</li>
</ul>
<strong><a>Zig의 comptime이 하지 않는 일들</a></strong>
<ul>
<li>Zig의 <strong>comptime</strong> 기능은 매우 <strong>강력한 컴파일 타임 평가 기능</strong>을 제공하지만 <strong>의도적으로 제한적</strong>임 </li>
<li>컴파일 타임 코드 실행 시 <strong>호스트 정보에 접근 불가능</strong>, 크로스 컴파일에 적합한 설계임 </li>
<li><strong>동적 코드 생성, DSL, RTTI, I/O 등은 지원하지 않음</strong>, 대신 명시적인 타입 기반 코드 특수화 사용 </li>
</ul>
GlobalYoung Youtube
<a>(zig_lings)Global Young __ zig languages exerciese</a>
Zig Exercieses
<a>series</a>
<ul>
<li>
<ol>
<li>hello zig, std, assignment</li>
</ol>
</li>
</ul>
<a>한글지그Zig강의_001_hello world_std_assignment_Zig Programming Language tutorial</a>
<ul>
<li>
<ol>
<li>array</li>
</ol>
</li>
</ul>
Zig Language Exercises series
<a>한글지그Zig강의 __ 모아 보기 Series Zig Language tutorial</a>
| [] |
https://avatars.githubusercontent.com/u/2982698?v=4 | zigwasm | voigt/zigwasm | 2022-04-25T21:15:13Z | Some experiments compiling Zig code to Wasm. | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/voigt/zigwasm/tags | - | [
"wasi",
"wasm",
"webassembly",
"zig"
] | 6 | false | 2022-04-25T21:18:21Z | false | false | unknown | github | [] | zigwasm
Some experiments compiling Zig code to Wasm.
<code>zig
$ zig version
0.10.0-dev.1837+4c83b11f7</code> | [] |
https://avatars.githubusercontent.com/u/6756180?v=4 | zigup | kassane/zigup | 2022-07-10T17:00:35Z | Download and manage zig compilers. | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/kassane/zigup/tags | MIT-0 | [
"version-manager",
"zig",
"ziglang"
] | 172 | true | 2025-01-20T13:06:48Z | true | true | unknown | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/14206587?v=4 | kioto | Tau-0/kioto | 2022-04-20T18:17:20Z | Concurrency library for Zig | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/Tau-0/kioto/tags | MIT | [
"channels",
"concurrency",
"coroutines",
"fibers",
"futures",
"zig",
"ziglang"
] | 1,724 | false | 2025-05-18T15:40:19Z | true | true | 0.14.0 | github | [] | kioto
Concurrency library for Zig | [] |
https://avatars.githubusercontent.com/u/54503497?v=4 | micro_snake | RetroDev256/micro_snake | 2022-09-01T17:42:26Z | null | master | 0 | 0 | 0 | 0 | https://api.github.com/repos/RetroDev256/micro_snake/tags | MIT | [
"zig"
] | 53 | false | 2025-05-17T08:54:10Z | true | true | unknown | github | [] | micro_snake
Attempt to create a workable, standalone linux console game - snake - in less than 1 KiB
<code>+-------------------------+-------------------------+--------+--------+
| 7f 45 4c 46 01 01 01 00 | 00 00 00 00 00 00 00 00 |•ELF•••⋄|⋄⋄⋄⋄⋄⋄⋄⋄|
| 02 00 03 00 01 00 00 00 | 54 00 01 00 34 00 00 00 |•⋄•⋄•⋄⋄⋄|T⋄•⋄4⋄⋄⋄|
| 00 00 00 00 00 00 00 00 | 34 00 20 00 01 00 28 00 |⋄⋄⋄⋄⋄⋄⋄⋄|4⋄ ⋄•⋄(⋄|
| 00 00 00 00 01 00 00 00 | 54 00 00 00 54 00 01 00 |⋄⋄⋄⋄•⋄⋄⋄|T⋄⋄⋄T⋄•⋄|
| 54 00 01 00 2a 02 00 00 | 2d 02 00 00 07 00 00 00 |T⋄•⋄*•⋄⋄|-•⋄⋄•⋄⋄⋄|
| 00 10 00 00 55 53 57 56 | 81 ec 50 1e 00 00 6a 36 |⋄•⋄⋄USWV|××P•⋄⋄j6|
| 5e 8d 54 24 14 89 f0 31 | db b9 01 54 00 00 cd 80 |^×T$•××1|×וT⋄⋄××|
| c6 42 17 00 80 62 0c fd | 89 f0 31 db b9 04 54 00 |×B•⋄×b_×|××1×וT⋄|
| 00 cd 80 31 ed 45 be 80 | 07 00 00 6a 04 58 89 eb |⋄××1×E××|•⋄⋄j•X××|
| b9 56 02 01 00 6a 14 5a | cd 80 b8 a2 00 00 00 bb |×V••⋄j•Z|××××⋄⋄⋄×|
| 6d 02 01 00 31 c9 cd 80 | 31 c0 b9 80 07 00 00 8d |m••⋄1×××|1××ו⋄⋄×|
| 7c 24 50 f3 ab c6 44 24 | 0c 02 c7 44 24 10 9a 02 ||$P×××D$|_•×D$•ו|
| 00 00 bf 34 05 00 00 b0 | 02 89 44 24 08 6a 05 58 |⋄⋄×4•⋄⋄×|•×D$•j•X|
| 89 44 24 04 6a 03 58 31 | db 8d 4c 24 14 89 ea cd |×D$•j•X1|××L$•×××|
| 80 85 c0 74 1a 8a 44 24 | 14 04 bf 8b 4c 24 08 30 |×××t•×D$|••××L$•0|
| c1 3c 03 77 df 80 e1 03 | 80 f9 01 74 d7 eb 04 8b |×<•w××ו|×וt×ו×|
| 44 24 08 24 03 88 04 24 | b8 00 e2 ff ff 8b 5c 24 |D$•$•ו$|×⋄××××\$|
| 10 85 c0 74 1c 8b 94 04 | 50 1e 00 00 31 c9 83 ea |•××t•×ו|P•⋄⋄1×××|
| 01 72 02 89 d1 89 8c 04 | 50 1e 00 00 83 c0 04 eb |•r•×××ו|P•⋄⋄×ו×|
| e0 89 d8 31 d2 6a 50 59 | f7 f1 0f b6 04 24 89 44 |×××1×jPY|×וו$×D|
| 24 08 83 e0 03 ff 24 85 | 42 02 01 00 83 fb 50 6a |$•×ו×$×|B••⋄××Pj|
| b0 eb 27 83 fa 4f 89 e8 | 0f 84 2d ff ff ff eb 21 |××'××O××|•×-××××!|
| 85 d2 b8 ff ff ff ff 0f | 84 1e ff ff ff eb 12 8d |××××××ו|ו×××ו×|
| 83 d0 f8 ff ff 83 f8 50 | 6a 50 58 0f 82 0a ff ff |×××××××P|jPX•×_××|
| ff 01 c3 83 7c 9c 50 00 | 0f 85 fd fe ff ff 8b 44 |ו××|×P⋄|•××××××D|
| 24 04 89 44 9c 50 39 fb | 89 5c 24 10 75 27 8b 0d |$•×D×P9×|×\$•u'×_|
| 7d 02 01 00 69 c9 cd 0d | 01 00 41 89 c8 31 d2 f7 |}••⋄i××_|•⋄A××1××|
| f6 83 7c 94 50 00 75 ec | 89 d7 83 44 24 04 05 89 |××|×P⋄u×|×××D$••×|
| 0d 7d 02 01 00 6a 04 58 | 89 eb b9 52 02 01 00 6a |_}••⋄j•X|×××R••⋄j|
| 03 5a cd 80 31 f6 81 fe | 80 07 00 00 74 4c b0 2b |•Z××1×××|ו⋄⋄tL×+|
| 39 f7 74 14 8b 4c b4 50 | b0 40 3b 4c 24 04 74 08 |9×t•×L×P|×@;L$•t•|
| 85 c9 b0 2e 74 02 b0 6f | 88 44 24 14 6a 04 58 89 |×××.t•×o|×D$•j•X×|
| eb 8d 4c 24 14 89 ea cd | 80 46 89 f0 31 d2 66 b9 |××L$•×××|×F××1×f×|
| 50 00 66 f7 f1 66 85 d2 | 75 bc 6a 04 58 89 eb b9 |P⋄f××f××|u×j•X×××|
| 6b 02 01 00 89 ea cd 80 | eb ac b8 a2 00 00 00 bb |k••⋄××××|××××⋄⋄⋄×|
| 75 02 01 00 31 c9 cd 80 | be 80 07 00 00 e9 92 fe |u••⋄1×××|×ו⋄⋄×××|
| ff ff 4c 01 01 00 6f 01 | 01 00 53 01 01 00 60 01 |××L••⋄o•|•⋄S••⋄`•|
| 01 00 1b 5b 48 00 1b 5b | 32 4a 1b 5b 31 32 3b 33 |•⋄•[H⋄•[|2J•[12;3|
| 36 48 ce bc 2d 53 6e 65 | 6b 21 00 0a 00 00 00 00 |6H××-Sne|k!⋄_⋄⋄⋄⋄|
| 00 80 f8 a9 32 00 00 00 | 00 c0 68 78 04 01 |⋄×××2⋄⋄⋄|⋄×hx•• |
+-------------------------+-------------------------+--------+--------+</code> | [] |
https://avatars.githubusercontent.com/u/68133?v=4 | go-version-cgo-zig | afriza/go-version-cgo-zig | 2022-09-08T05:06:57Z | Compare output of `go version -m` between gcc & zig | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/afriza/go-version-cgo-zig/tags | - | [
"go",
"golang",
"zig",
"ziglang"
] | 3 | false | 2022-09-08T10:48:38Z | false | false | unknown | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/181018?v=4 | zorrent | lg/zorrent | 2022-10-10T04:08:44Z | zorrent - zig torrent client (WIP) | master | 0 | 0 | 0 | 0 | https://api.github.com/repos/lg/zorrent/tags | - | [
"torrent",
"zig"
] | 112 | false | 2022-10-10T04:11:19Z | true | false | unknown | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/45506003?v=4 | zirc | izonu/zirc | 2022-11-16T09:38:16Z | IRC terminal client written in Zig | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/izonu/zirc/tags | MIT | [
"irc",
"zig"
] | 5 | false | 2023-09-02T14:37:31Z | true | false | unknown | github | [] | Zirc
Zirc is an irc client written in zig
development moved to https://codeberg.org/phantom32/zirc | [] |
https://avatars.githubusercontent.com/u/8743306?v=4 | zwc | dmbfm/zwc | 2022-09-30T01:38:57Z | A WC clone written in zig | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/dmbfm/zwc/tags | - | [
"cli",
"wc",
"zig"
] | 8 | false | 2022-09-30T01:40:45Z | true | false | unknown | github | [] | zwc
A clone of the <code>wc</code> utility written in zig. That's it. Just a
line/word/character counter written in zig for learning purposes.
Should work as a drop-in replacement, but I haven't tested it extensively yet.
Building and Installation
Assuming you have zig installed and that <code>~/.local/bin</code> is in your path:
<code>$ zig build -Drelease-fast -p ~/.local/bin
$ echo "hello" | zwc
1 1 6</code> | [] |
https://avatars.githubusercontent.com/u/35064754?v=4 | AoC-2022 | wooster0/AoC-2022 | 2022-12-02T12:20:59Z | Advent of Code 2022 | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/wooster0/AoC-2022/tags | - | [
"ada",
"advent-of-code",
"advent-of-code-2022",
"aoc",
"aoc-2022",
"aoc2022",
"bash",
"c",
"cpp",
"rust",
"zig"
] | 32 | false | 2022-12-06T18:40:25Z | false | false | unknown | github | [] | AoC-2022
My solutions for <a>Advent of Code</a> 2022. | [] |
https://avatars.githubusercontent.com/u/45411401?v=4 | levy-aecs | tauoverpi/levy-aecs | 2022-06-30T05:40:00Z | Archetype Entity Component System for zig | master | 0 | 0 | 0 | 0 | https://api.github.com/repos/tauoverpi/levy-aecs/tags | MIT | [
"entity-component-system",
"zig"
] | 41 | false | 2022-06-30T05:51:20Z | true | false | unknown | github | [] | Archetype Entity Component System
AECS is an entity component system which manages entities by sorting them into separate buckets based on the components they have. Buckets in memory make use of the <a>structure of arrays</a> (SoA) layout which is computed at runtime based on the currently available archetypes.
NOTE: this is currently in progress thus nothing really works yet
Usage
```zig
const Data = struct {
position: Vec2,
velocity: Vec2,
health: u32,
};
const Model = aecs.Model(Data);
``` | [] |
https://avatars.githubusercontent.com/u/15983269?v=4 | zig-spng | SasLuca/zig-spng | 2022-08-01T14:20:02Z | Simple, modern libpng alternative, now with Zig bindings. | master | 0 | 0 | 0 | 0 | https://api.github.com/repos/SasLuca/zig-spng/tags | - | [
"codec",
"decoding",
"decoding-images",
"encoder",
"oss-fuzz",
"png",
"png-decoder",
"png-encoder",
"spng",
"zig"
] | 869 | false | 2023-06-30T13:15:09Z | true | false | unknown | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/2828351?v=4 | Zig-SX | bcrist/Zig-SX | 2022-10-21T04:46:37Z | S-Expression [de]serialization in Zig | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/bcrist/Zig-SX/tags | MIT | [
"encoding",
"s-expression",
"s-expressions",
"sexp",
"zig",
"zig-library",
"zig-package",
"ziglang"
] | 175 | false | 2025-03-22T07:11:02Z | true | true | 0.14.0 | github | [] | Zig-SX
A simple Zig library for reading and writing S-Expressions.
Ideal for human-readable configuration or data files containing lots of compound structures.
Parsing and writing is always done interactively with the user program; there is no intermediate "document" representation.
Reader Example
```zig
const std = @import("std");
const sx = @import("sx");
var source =
\(box my-box
\ (dimensions 4.3 7 14)
\ (color red)
\ (contents
\ 42
\ "Big Phil's To Do List:
\ - paint it black
\ - clean up around the house
\")
\)
\
;
var stream = std.io.fixedBufferStream(source);
var reader = sx.reader(std.testing.allocator, stream.reader());
defer reader.deinit();
try reader.require_expression("box");
_ = try reader.require_any_string();
var color: []const u8 = "";
var width: f32 = 0;
var depth: f32 = 0;
var height: f32 = 0;
while (try reader.any_expression()) |expr| {
if (std.mem.eql(u8, expr, "dimensions")) {
width = try reader.require_any_float(f32);
depth = try reader.require_any_float(f32);
height = try reader.require_any_float(f32);
try reader.require_close();
<code>} else if (std.mem.eql(u8, expr, "color")) {
color = try std.testing.allocator.dupe(u8, try reader.require_any_string());
try reader.require_close();
} else if (std.mem.eql(u8, expr, "contents")) {
while (try reader.any_string()) |contents| {
std.debug.print("Phil's box contains: {s}\n", .{ contents });
}
try reader.require_close();
} else {
try reader.ignore_remaining_expression();
}
</code>
}
try reader.require_close();
try reader.require_done();
```
Writer Example
```zig
const std = @import("std");
const sx = @import("sx");
var writer = sx.writer(std.testing.allocator, std.io.getStdOut().writer());
defer writer.deinit();
try writer.expression("box");
try writer.string("my-box");
writer.set_compact(false);
try writer.expression("dimensions");
try writer.float(4.3);
try writer.float(7);
try writer.float(14);
_ = try writer.close();
try writer.expression("color");
try writer.string("red");
_ = try writer.close();
try writer.expression_expanded("contents");
try writer.int(42, 10);
try writer.string(
\Big Phil's To Do List:
\ - paint it black
\ - clean up around the house
\
);
try writer.done();
```
Building
This library is designed to be used with the Zig package manager. To use it, add a <code>build.zig.zon</code> file next to your <code>build.zig</code> file:
<code>zig
.{
.name = "Your Project Name",
.version = "0.0.0",
.dependencies = .{
.@"Zig-SX" = .{
.url = "https://github.com/bcrist/Zig-SX/archive/xxxxxx.tar.gz",
},
},
}</code>
Replace <code>xxxxxx</code> with the full commit hash for the version of the library you want to use. The first time you run <code>zig build</code> after adding this, it will tell you a hash to put after <code>.url = ...</code>. This helps zig ensure that the file wasn't corrupted during download, and that the URL hasn't been hijacked.
Then in your <code>build.zig</code> file you can get a reference to the package:
<code>zig
const zig_sx = b.dependency("Zig-SX", .{});
const exe = b.addExecutable(.{
.name = "my_exe_name",
.root_source_file = .{ .path = "my_main_file.zig" },
.target = b.standardTargetOptions(.{}),
.optimize = b.standardOptimizeOption(.{}),
});
exe.addModule("sx", zig_sx.module("sx"));</code> | [] |
https://avatars.githubusercontent.com/u/410588?v=4 | marbles | 2bt/marbles | 2022-10-28T17:08:43Z | A clone of the game Swing aka Marble Master | master | 0 | 0 | 0 | 0 | https://api.github.com/repos/2bt/marbles/tags | - | [
"puzzle-game",
"zig"
] | 30 | false | 2022-10-28T17:15:39Z | true | false | unknown | github | [] | Marbles
A clone of the game Swing aka Marble Master.
Try it out <a>here</a>. | [] |
https://avatars.githubusercontent.com/u/3036610?v=4 | starlark-zig | emcfarlane/starlark-zig | 2022-04-13T22:08:33Z | Starlark in ZIG | main | 2 | 0 | 0 | 0 | https://api.github.com/repos/emcfarlane/starlark-zig/tags | - | [
"wip",
"zig"
] | 18 | false | 2022-04-13T23:08:05Z | true | false | unknown | github | [] | [wip] starlark-zig
Implementation of starlark in zig, translated from starlark-go.
First zig project, please leave feedback :D.
devlog
<ul>
<li>AST impl https://github.com/ziglang/zig/pull/7920</li>
</ul>
ideas
Parser
Currently the parser is based on the zig parser.
We could use something prebuilt like treesitter: https://github.com/tree-sitter/py-tree-sitter | [] |
https://avatars.githubusercontent.com/u/99486674?v=4 | touch-id-sudo | yamashitax/touch-id-sudo | 2022-08-27T04:12:33Z | Enable using Touch ID and Apple Watch for sudo | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/yamashitax/touch-id-sudo/tags | - | [
"zig"
] | 1 | false | 2022-09-01T00:09:15Z | true | false | unknown | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/41062858?v=4 | csv2json | berquerant/csv2json | 2022-11-22T03:05:45Z | Convert csv data from stdin into json. | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/berquerant/csv2json/tags | MIT | [
"zig"
] | 33 | false | 2025-04-20T07:43:35Z | true | false | unknown | github | [] | csv2json
Convert csv data from stdin into json.
<code>$ cat account.csv
id,name,department
1,account1,HR
2,account2,Dev
4,account4,HR
3,account3,PR
$ csv2json -i < account.csv
{"id":1,"name":"account1","department":"HR"}
{"id":2,"name":"account2","department":"Dev"}
{"id":4,"name":"account4","department":"HR"}
{"id":3,"name":"account3","department":"PR"}
$ csv2json < account.csv
["id","name","department"]
[1,"account1","HR"]
[2,"account2","Dev"]
[4,"account4","HR"]
[3,"account3","PR"]</code>
Package management
Depends on:
<ul>
<li><a>build.zig</a></li>
<li><a>requirements.txt</a></li>
<li><a>package.sh</a></li>
</ul>
The format of a row of requirements.txt is:
<code>LOCATION VERSION ENTRANCE</code>
<code>LOCATION</code> is a part of the repo url with schema stripped.
<code>VERSION</code> is a tag or a commit hash.
<code>ENTRANCE</code> is a target zig file to <code>@import</code>, relative to the root of the repo.
Requirements
<ul>
<li>zig 0.10.0 or later</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/109846069?v=4 | hyonz | noiryuh/hyonz | 2022-09-22T20:28:44Z | Various encoding codec implementations written in Zig. | master | 0 | 0 | 0 | 0 | https://api.github.com/repos/noiryuh/hyonz/tags | MIT | [
"zig"
] | 7 | false | 2022-09-22T20:58:19Z | true | false | unknown | github | [] | hyonz
Various encoding codec implementations written in Zig.
Usage
In <code>build.zig</code>:
```zig
const std = @import("std");
const hyonz = @import("hyonz/build.zig");
pub fn build(b: *std.build.Builder) void {
// ....
hyonz.linkPkg(exe);
}
```
In <code>main.zig</code>:
```zig
const std = @import("std");
const hyonz = @import("hyonz");
const base16 = hyonz.base16;
pub fn main() !void {
const x = base16.standard_upper.Encoder.encodeComptime("!?");
_ = x; // x == "213F"
}
``` | [] |
https://avatars.githubusercontent.com/u/8216064?v=4 | dev-zig-lang-with-vim-at-docker | shinshin86/dev-zig-lang-with-vim-at-docker | 2022-07-26T22:09:09Z | Dev Zig with vim at docker. | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/shinshin86/dev-zig-lang-with-vim-at-docker/tags | - | [
"docker-image",
"vim",
"zig"
] | 1 | false | 2022-07-26T22:16:45Z | false | false | unknown | github | [] | dev-zig-lang-with-vim-at-docker
Dev <a>Zig</a> with vim at docker.
Getting started
Build image and Run docker
```bash
docker build -t dev-zig-vim .
docker run -it --rm --name dev-zig-vim-01 dev-zig-vim /bin/bash
or if want to share local file to docker
docker run -it --rm -v $(pwd)/work:/tmp/share --name dev-zig-vim-01 dev-zig-vim /bin/bash
```
PlugInstall must be done
After connecting to Docker, launch vim and hit this command.
<code>vim
:PlugInstall</code> | [] |
https://avatars.githubusercontent.com/u/8497012?v=4 | zig-jq | apple-x-co/zig-jq | 2022-08-17T08:41:26Z | for learning | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/apple-x-co/zig-jq/tags | - | [
"zig"
] | 6 | false | 2023-11-01T17:25:08Z | true | false | unknown | github | [] | zig-jq
Build
<code>bash
zig build -Doptimize=ReleaseFast</code>
Run
```bash
zig build run -- sample.json
OR echo "{\"a\": \"b\"}" | zig build run
``` | [] |
https://avatars.githubusercontent.com/u/166043157?v=4 | mruby-zig | FnCtrlOption/mruby-zig | 2022-11-08T23:49:58Z | mruby bindings for zig | master | 0 | 0 | 0 | 0 | https://api.github.com/repos/FnCtrlOption/mruby-zig/tags | MIT | [
"ruby",
"zig"
] | 131 | true | 2024-08-24T23:24:51Z | true | false | unknown | github | [] | mruby-zig
<a>mruby</a> bindings for <a>zig</a>!
Mruby is the lightweight implementation of the Ruby language complying with part of the ISO standard.
Mruby documentation can be found <a>here</a>.
Embedding
To embed <code>mruby</code> into another zig project, you just need to
recursively clone this repository and add a couple of lines to your
<code>build.zig</code>.
<ul>
<li>Add the following lines to <code>build.zig</code>, with the paths changed to match the correct location</li>
</ul>
```zig
const addMruby = @import("mruby-zig/build.zig").addMruby;
pub fn build(b: *std.build.Builder) void {
[...]
const exe = b.addExecutable("example", "src/main.zig");
addMruby(exe);
[...]
}
```
<ul>
<li>Import <code>mruby</code> and start a new interpreter</li>
</ul>
```zig
const std = @import("std");
const mruby = @import("mruby");
pub fn main() anyerror!void {
// Opening a state
var mrb = try mruby.open();
defer mrb.close();
<code>// Loading a program from a string
mrb.load_string("puts 'hello from ruby!'");
</code>
}
```
Example
See <code>examples/main.zig</code> | [] |
https://avatars.githubusercontent.com/u/14120644?v=4 | sometoml | tato/sometoml | 2022-08-18T08:08:25Z | a little bit of toml for you | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/tato/sometoml/tags | BSD-2-Clause | [
"toml",
"zig"
] | 204 | false | 2024-05-12T06:43:35Z | true | false | unknown | github | [] |
sometoml
<ul>
<li>is a toml v1.0.0 library for zig </li>
<li>supports serialization and deserialization</li>
<li>is still in early stages</li>
</ul>
not yet implemented
<ul>
<li>date types</li>
<li>good error reporting</li>
</ul>
also planned
<ul>
<li>deserializing into arbitrary zig structs</li>
<li>customizable serializing and deserializing</li>
<li>and then, who knows???</li>
</ul>
how to use it
<ul>
<li><code>git submodule add https://github.com/tato/sometoml</code></li>
<li><code>exe.addPackagePath("toml", "sometoml/toml.zig");</code></li>
<li><code>const toml = @import("toml");</code></li>
<li><code>const doc = toml.parse(allocator, reader);</code></li>
</ul>
🙌
| [] |
https://avatars.githubusercontent.com/u/101372000?v=4 | mr-ema.github.io | mr-ema/mr-ema.github.io | 2022-05-09T02:05:33Z | null | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/mr-ema/mr-ema.github.io/tags | NOASSERTION | [
"zig",
"zig-zine",
"zine"
] | 5,985 | false | 2024-11-23T16:58:23Z | true | true | unknown | github | [
{
"commit": "master",
"name": "zine",
"tar_url": "https://github.com/kristoff-it/zine/archive/master.tar.gz",
"type": "remote",
"url": "https://github.com/kristoff-it/zine"
}
] | 404 | [] |
https://avatars.githubusercontent.com/u/6756180?v=4 | zwid | kassane/zwid | 2022-10-29T17:21:54Z | [WIP] Utilities for embedding CoSWID tags in EFI binaries - written on Zig | main | 1 | 0 | 0 | 0 | https://api.github.com/repos/kassane/zwid/tags | BSD-3-Clause | [
"firmware",
"swid",
"zig"
] | 8 | false | 2022-10-30T16:21:46Z | true | false | unknown | github | [] | zwid
Utilities for embedding CoSWID tags in EFI binaries - written on Zig
Introduction
Software Identification (SWID) tags provide an extensible XML-based structure to
identify and describe individual software components, patches, and installation
bundles. SWID tag representations can be too large for devices with network and
storage constraints.
CoSWID supports a similar set of semantics and features as SWID tags, as well
as new semantics that allow us to describe additional types of information, all
in a more memory efficient format.
We wanted to write up some text recommending a particular tool to be integrated
into the tianocore build process, but they all are not exactly awesome:
<ul>
<li>
The <a>official tool from NIST</a> is a
huge Java codebase that hasn't been updated for some time and doesn't work
with any versions than Java 9 and that's been end-of-support since 2018.
</li>
<li>
A <a>go & rust implementation</a> exists for <a>coreboot</a> utilities.
</li>
</ul>
Installing
Requires: <a>zig v0.10.0</a>
<strong>Commands:</strong>
<code>bash
$> zig build run -D{Options: debug|release-fast|release-safe|release-small} -- path/firmware.bin</code> | [] |
https://avatars.githubusercontent.com/u/48591413?v=4 | zigcalc | chrboesch/zigcalc | 2022-09-18T11:54:59Z | A simple calculator in zig | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/chrboesch/zigcalc/tags | - | [
"zig",
"ziglang"
] | 7 | false | 2022-10-29T11:17:11Z | false | false | unknown | github | [] | zigcalc
A simple calculator in zig
Inspired by the video <a>Build a Simple Calculator in C</a> a rebuilt of this calculator in zig.
Compile with the following command: <code>zig build-exe -O ReleaseSmall --strip calc.zig</code> or just run <code>zig run calc.zig</code> | [] |
https://avatars.githubusercontent.com/u/39071861?v=4 | eisuu | MrPicklePinosaur/eisuu | 2022-08-30T05:14:32Z | image asciizer written in ziglang | master | 0 | 0 | 0 | 0 | https://api.github.com/repos/MrPicklePinosaur/eisuu/tags | - | [
"ascii-art",
"cli",
"zig"
] | 6 | false | 2022-08-30T07:00:11Z | true | false | unknown | github | [] |
【英数変換機】 eisuu henkanki
image asciizer written in zig lang
SETTING UP FOR DEVELOPMENT
ensure that you are using zig 0.9.1
RESOURCES
this project was written to learn some zig, here are some resources that i
used:
- <a>ziglang docs</a>
- <a>ziglearn.org</a>
- <a>zig build explained</a> | [] |
https://avatars.githubusercontent.com/u/62779291?v=4 | zXFL | shimamura-sakura/zXFL | 2022-08-15T03:02:02Z | An extractor for XFL archive files written in Zig language. | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/shimamura-sakura/zXFL/tags | GPL-3.0 | [
"reverse-engineering",
"zig"
] | 15 | false | 2022-09-03T10:20:05Z | false | false | unknown | github | [] | zXFL
Tested on files from "Okujou no Yurirei-san"
Build
<code>sh
$ zig build-exe main.zig</code>
Usage
<code>sh
$ ./main [path_to_xfl_file] [folder_to_place_extracted_files]</code>
Example:
<code>sh
$ ./main bgm.xfl ./bgm</code> | [] |
https://avatars.githubusercontent.com/u/12962448?v=4 | mnist-predictor | star-tek-mb/mnist-predictor | 2022-12-25T05:11:56Z | Hand written digit recognizer written in Zig | master | 0 | 0 | 0 | 0 | https://api.github.com/repos/star-tek-mb/mnist-predictor/tags | - | [
"zig"
] | 676 | false | 2022-12-25T05:13:22Z | true | false | unknown | github | [] | Overview
This is a MNIST handwritten digit recognizer written in zig with raylib.
Installation
Install raylib first for GUI
<code>git clone https://github.com/raysan5/raylib.git --single-branch --depth 1</code>
For training you also need MNIST data from <a>here</a>.
Place it in data folder and use <code>src/main_training.zig</code>
Two implementations
One implementation is in pure zig <code>src/main_pure.zig</code> - neural network training.
Second implementation is in C <code>src/main.zig</code> exported from tensorflow.
Both implementations are a bit stupid.
Screenshot
| [] |
https://avatars.githubusercontent.com/u/135217?v=4 | zig_sandkasten | gthvn1/zig_sandkasten | 2023-01-30T15:57:05Z | 🚧 Zig trials 🚧 | master | 0 | 0 | 0 | 0 | https://api.github.com/repos/gthvn1/zig_sandkasten/tags | GPL-3.0 | [
"zig"
] | 69 | false | 2024-08-21T19:12:56Z | false | false | unknown | github | [] | Topics
<ul>
<li><a>Testing Raylib Bindings</a>: Try to use raylib bindins from Zig<ul>
<li>Currently we are drawing a ball and make it bounce...</li>
</ul>
</li>
<li><a>Wasm & Web server</a><ul>
<li>Play with Zig and Wasm in order to understand:<ul>
<li>how we can convert a Zig code to Wasm,</li>
<li>how we can load this wasm file<ul>
<li>maybe using our own server</li>
</ul>
</li>
<li>how to export/import functions,</li>
<li>...</li>
</ul>
</li>
</ul>
</li>
<li><a>Chip8 in the browser</a><ul>
<li>Run a chip8 emulator in the browser</li>
<li>Implement the emulator in Zig and cross compile it...</li>
</ul>
</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/45176912?v=4 | exercism | alternateved/exercism | 2022-12-21T20:12:50Z | My solutions to Exercism exercises | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/alternateved/exercism/tags | MIT | [
"clojure",
"exercism",
"haskell",
"julia",
"scheme",
"zig"
] | 1,311 | false | 2023-11-01T17:10:30Z | false | false | unknown | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/22148308?v=4 | AdventOfCode2022 | hazeycode/AdventOfCode2022 | 2022-12-01T15:39:52Z | My solutions to Advent of Code 2022 using Zig 0.10.0 | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/hazeycode/AdventOfCode2022/tags | - | [
"advent-of-code-2022",
"aoc2022",
"zig"
] | 99 | false | 2022-12-06T17:27:22Z | true | false | unknown | github | [] | AdventOfCode2022
My solutions to <a>Advent of Code 2022</a> using <a>Zig</a> 0.10.0
There is a program for each day in <code>src/</code>, input data for each day is located in <code>src/data/</code>
```shell
Build and run a particular day
zig build run-day06
Build and run any tests for a particular day
zig build test-day06
``` | [] |
https://avatars.githubusercontent.com/u/61101524?v=4 | cryptopals | tkieras/cryptopals | 2022-07-08T01:20:04Z | Cryptopals in Zig! | master | 0 | 0 | 0 | 0 | https://api.github.com/repos/tkieras/cryptopals/tags | - | [
"cryptopals",
"zig"
] | 90 | false | 2022-07-08T01:28:39Z | false | false | unknown | github | [] | 404 | [] |
https://avatars.githubusercontent.com/u/26470129?v=4 | ego.github.io | ego/ego.github.io | 2022-12-16T17:12:02Z | Personal web blog at ego.systemdef.com | main | 0 | 0 | 0 | 0 | https://api.github.com/repos/ego/ego.github.io/tags | MIT | [
"aiops",
"aws",
"blog",
"clojure",
"dataops",
"devops",
"engineering",
"kotlin",
"mlops",
"nodejs",
"python3",
"sofware",
"vlang",
"zig"
] | 54,605 | false | 2023-09-13T11:37:33Z | false | false | unknown | github | [] | Personal web blog at ego.systemdef.com
Prerequisites
Make sure your were installed
<ul>
<li><a>Git</a></li>
<li><a>Hugo</a></li>
</ul>
Static site tool
<a>Hugo</a>
<a>Github Hugo</a>
<a>Hugo quick start</a>
Theme templates
<ul>
<li><a>All hugo themes</a></li>
<li><a>Hugo theme next</a> current theme in use.</li>
<li><a>Hugo theme next starter</a> current starter in use.</li>
<li><a>Hugo theme bootstrap</a></li>
<li>[Hugo theme bootstrap github]https://github.com/razonyang/hugo-theme-bootstrap</li>
<li><a>Hugo theme bootstrap skeleton</a></li>
<li><a>Hugo theme bootstrap docs</a></li>
</ul>
Current Theme
<a>Upgraded Ego Hugo theme Next</a>
Click the green button which name call <code>Use this template</code>.
After do that click the green button which name call <code>Create repository from template</code>, then will create your site code automatic.
Remember that need use <code>git submodule</code> command to pull all things from <code>hugo-theme-next</code> at first time.
```
First time
git submodule add https://github.com/ego/hugo-theme-next.git themes/hugo-theme-next
git submodule update --init --recursive
Next time
git submodule update --remote --merge
```
Update Theme
<code>bash
./scripts/update-ego-hugo-theme-next.sh
git add .
git commit -m "Update theme up to `cat themes/hugo-theme-next/VERSION`"
git push</code>
Update forked customized Theme
Update <a>ego/hugo-theme-next</a> from <a>upstream/hugo-theme-next</a>
Main branch is <code>main</code>
<code>shell
git remote add upstream https://github.com/hugo-next/hugo-theme-next.git
git fetch --all
git checkout develop/ego
git merge upstream/main
git push origin develop/ego</code>
Local development
Just run
<code>bash
./scripts/hugo-run-server.sh</code>
and visit <a>http://localhost:1414/</a>.
New Post
It is recommended to use the following Hugo command to quickly create a new post
```bash
Note
hugo new note/{full-url}.md
Template
hugo new {root-category}/{second-category}/{main-tags}/{full-url}.md --debug --verbose
Engineering
hugo new engineering/git/code-stats-metrics/code-stats-metrics-analytics-and-tools.md \
&& mkdir -p engineering/git/code-stats-metrics/assets
Projects
hugo new projects/{main-category}/{main-tags}/{full-url}.md
AI
hugo new ai/{main-category}/{main-tags}/{full-url}.md
Open source
hugo new open-source/{main-category}/{main-tags}/{full-url}.md
Courses
hugo new courses/{main-category}/{main-tags}/{full-url}.md
Books
hugo new books/{main-category}/{main-tags}/{full-url}.md
```
<blockquote>
<strong>Note</strong>
By defalut <code>hugo new</code> command will create new post under <code>content</code> root directory, so in here <code>posts</code> were you custom subfolder in <code>content</code> directory.
</blockquote>
Archetypes are content template files.
<a>Archetypes</a>
All front matter parameter's description in post as below:
```yml
title: "{{ replace .Name "-" " " | title }}"
description: "{{ .Name }}"
keywords: "{{replace .Name "-" ","}}"
date: {{ .Date }}
lastmod: {{ .Date }}
categories:
-
tags:
-
Post's origin author name
author:
Post's origin link URL
link:
Image source link that will use in open graph and twitter card
imgs:
Expand content on the home page
expand: true
It's means that will redirecting to external links
extlink:
Disabled comment plugins in this post
comment:
enable: false
Disable table of content int this post
Notice: By default will automatic build table of content
with h2-h4 title in post and without other settings
toc: false
Absolute link for visit
url: "{{ lower .Name }}.html"
Sticky post set-top in home page and the smaller nubmer will more forward.
weight: 1
Support Math Formulas render, options: mathjax, katex
math: mathjax
Enable chart render, such as: flow, sequence, classes etc
mermaid: true
Custom page params:
js:
- "1.js"
```
Deployment
GitHub Pages
<ul>
<li><a>Github Pages</a></li>
<li><a>Hugo hosting on github</a></li>
<li>Github Actions <code>.github/workflows/gh-pages.yml</code></li>
<li>Edit production config file <code>config/_default/params.yaml</code> before deploy, such as comment, analytis, share and so on.</li>
</ul>
Published to
<ul>
<li><a>ego.github.io</a></li>
<li><a>ego.systemdef.com</a></li>
</ul>
Make the release.
<code>bash
./scripts/release.sh</code>
Tools
Custom shortcode templates
<ul>
<li><a>shortcode templates</a></li>
<li><a>syntax highlighting</a></li>
</ul>
Code from file
<code>markdown
{{< read_code src="post/engineering/bit-computing-compilers-and-hardware/logic_gate_full_adder_8_bit.py" hl_lines="4-8" >}}</code>
PyScript
```markdown
{{< read_code src="/note/test.py" >}}
{{< expand_block "<b>REPL test.py</b>" >}}
{{< iframe_srcdoc >}}
{{< pyscript/js >}}
{{< pyscript/py-repl >}}
{{< read_file src="/note/test.py" >}}
{{< /pyscript/py-repl >}}
{{< /iframe_srcdoc >}}
{{< /read_code >}}
{{< /expand_block >}}
```
<a>iframe</a>
Python venv
<code>bash
python3 -m venv .env
source .env/bin/activate
pip install -r requirements.txt</code>
Auto generate keywords and tags for post.
<code>bash
./tools/post-keywords-tags.py</code>
GoHugo documentation
<ul>
<li><a>Page variables</a>
Usefully for post template <code>archetypes/default.md</code></li>
</ul>
License
<a>MIT License</a> | [] |
https://avatars.githubusercontent.com/u/145980012?v=4 | browser | lightpanda-io/browser | 2023-02-07T15:19:34Z | Lightpanda: the headless browser designed for AI and automation | main | 82 | 8,950 | 219 | 8,950 | https://api.github.com/repos/lightpanda-io/browser/tags | AGPL-3.0 | [
"browser",
"browser-automation",
"cdp",
"headless",
"playwright",
"puppeteer",
"zig"
] | 3,278 | false | 2025-05-22T07:57:06Z | true | true | unknown | github | [
{
"commit": "b29a8b45fc59fc2d202769c4f54509bb9e17d0a2.tar.gz",
"name": "tls",
"tar_url": "https://github.com/ianic/tls.zig/archive/b29a8b45fc59fc2d202769c4f54509bb9e17d0a2.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/ianic/tls.zig"
},
{
"commit": "61d9652f1a957b7f4db723ea... |
<a></a>
Lightpanda Browser
<a>lightpanda.io</a>
[](https://github.com/lightpanda-io/browser/blob/main/LICENSE)
[](https://twitter.com/lightpanda_io)
[](https://github.com/lightpanda-io/browser)
Lightpanda is the open-source browser made for headless usage:
<ul>
<li>Javascript execution</li>
<li>Support of Web APIs (partial, WIP)</li>
<li>Compatible with Playwright[^1], Puppeteer through CDP (WIP)</li>
</ul>
Fast web automation for AI agents, LLM training, scraping and testing:
<ul>
<li>Ultra-low memory footprint (9x less than Chrome)</li>
<li>Exceptionally fast execution (11x faster than Chrome)</li>
<li>Instant startup</li>
</ul>
<a>
</a>
 
<a>
</a>
<em>Puppeteer requesting 100 pages from a local website on a AWS EC2 m5.large instance.
See <a>benchmark details</a>.</em>
[^1]: <strong>Playwright support disclaimer:</strong>
Due to the nature of Playwright, a script that works with the current version of the browser may not function correctly with a future version. Playwright uses an intermediate JavaScript layer that selects an execution strategy based on the browser's available features. If Lightpanda adds a new <a>Web API</a>, Playwright may choose to execute different code for the same script. This new code path could attempt to use features that are not yet implemented. Lightpanda makes an effort to add compatibility tests, but we can't cover all scenarios. If you encounter an issue, please create a <a>GitHub issue</a> and include the last known working version of the script.
Quick start
Install from the nightly builds
You can download the last binary from the <a>nightly
builds</a> for
Linux x86_64 and MacOS aarch64.
<em>For Linux</em>
<code>console
curl -L -o lightpanda https://github.com/lightpanda-io/browser/releases/download/nightly/lightpanda-x86_64-linux && \
chmod a+x ./lightpanda</code>
<em>For MacOS</em>
<code>console
curl -L -o lightpanda https://github.com/lightpanda-io/browser/releases/download/nightly/lightpanda-aarch64-macos && \
chmod a+x ./lightpanda</code>
<em>For Windows + WSL2</em>
The Lightpanda browser is compatible to run on windows inside WSL. Follow the Linux instruction for installation from a WSL terminal.
It is recommended to install clients like Puppeteer on the Windows host.
Dump a URL
<code>console
./lightpanda fetch --dump https://lightpanda.io</code>
```console
info(browser): GET https://lightpanda.io/ http.Status.ok
info(browser): fetch script https://api.website.lightpanda.io/js/script.js: http.Status.ok
info(browser): eval remote https://api.website.lightpanda.io/js/script.js: TypeError: Cannot read properties of undefined (reading 'pushState')
```
Start a CDP server
<code>console
./lightpanda serve --host 127.0.0.1 --port 9222</code>
<code>console
info(websocket): starting blocking worker to listen on 127.0.0.1:9222
info(server): accepting new conn...</code>
Once the CDP server started, you can run a Puppeteer script by configuring the
<code>browserWSEndpoint</code>.
```js
'use strict'
import puppeteer from 'puppeteer-core';
// use browserWSEndpoint to pass the Lightpanda's CDP server address.
const browser = await puppeteer.connect({
browserWSEndpoint: "ws://127.0.0.1:9222",
});
// The rest of your script remains the same.
const context = await browser.createBrowserContext();
const page = await context.newPage();
// Dump all the links from the page.
await page.goto('https://wikipedia.com/');
const links = await page.evaluate(() => {
return Array.from(document.querySelectorAll('a')).map(row => {
return row.getAttribute('href');
});
});
console.log(links);
await page.close();
await context.close();
await browser.disconnect();
```
Telemetry
By default, Lightpanda collects and sends usage telemetry. This can be disabled by setting an environment variable <code>LIGHTPANDA_DISABLE_TELEMETRY=true</code>. You can read Lightpanda's privacy policy at: <a>https://lightpanda.io/privacy-policy</a>.
Status
Lightpanda is still a work in progress and is currently at a Beta stage.
:warning: You should expect most websites to fail or crash.
Here are the key features we have implemented:
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> HTTP loader
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> HTML parser and DOM tree (based on Netsurf libs)
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Javascript support (v8)
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Basic DOM APIs
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Ajax
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> XHR API
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Fetch API
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> DOM dump
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Basic CDP/websockets server
NOTE: There are hundreds of Web APIs. Developing a browser (even just for headless mode) is a huge task. Coverage will increase over time.
You can also follow the progress of our Javascript support in our dedicated <a>zig-js-runtime</a> project.
Build from sources
Prerequisites
Lightpanda is written with <a>Zig</a> <code>0.14.0</code>. You have to
install it with the right version in order to build the project.
Lightpanda also depends on
<a>zig-js-runtime</a> (with v8),
<a>Netsurf libs</a> and
<a>Mimalloc</a>.
To be able to build the v8 engine for zig-js-runtime, you have to install some libs:
For Debian/Ubuntu based Linux:
<code>sudo apt install xz-utils \
python3 ca-certificates git \
pkg-config libglib2.0-dev \
gperf libexpat1-dev unzip \
cmake clang</code>
For systems with <a>Nix</a>, you can use the devShell:
<code>nix develop</code>
For MacOS, you only need cmake:
<code>brew install cmake</code>
Install and build dependencies
All in one build
You can run <code>make install</code> to install deps all in one (or <code>make install-dev</code> if you need the development versions).
Be aware that the build task is very long and cpu consuming, as you will build from sources all dependencies, including the v8 Javascript engine.
Step by step build dependency
The project uses git submodules for dependencies.
To init or update the submodules in the <code>vendor/</code> directory:
<code>make install-submodule</code>
<strong>iconv</strong>
libiconv is an internationalization library used by Netsurf.
<code>make install-libiconv</code>
<strong>Netsurf libs</strong>
Netsurf libs are used for HTML parsing and DOM tree generation.
<code>make install-netsurf</code>
For dev env, use <code>make install-netsurf-dev</code>.
<strong>Mimalloc</strong>
Mimalloc is used as a C memory allocator.
<code>make install-mimalloc</code>
For dev env, use <code>make install-mimalloc-dev</code>.
Note: when Mimalloc is built in dev mode, you can dump memory stats with the
env var <code>MIMALLOC_SHOW_STATS=1</code>. See
<a>https://microsoft.github.io/mimalloc/environment.html</a>.
<strong>v8</strong>
First, get the tools necessary for building V8, as well as the V8 source code:
<code>make get-v8</code>
Next, build v8. This build task is very long and cpu consuming, as you will build v8 from sources.
<code>make build-v8</code>
For dev env, use <code>make build-v8-dev</code>.
Test
Unit Tests
You can test Lightpanda by running <code>make test</code>.
End to end tests
To run end to end tests, you need to clone the <a>demo
repository</a> into <code>../demo</code> dir.
You have to install the <a>demo's node
requirements</a>
You also need to install <a>Go</a> > v1.24.
<code>make end2end</code>
Web Platform Tests
Lightpanda is tested against the standardized <a>Web Platform
Tests</a>.
The relevant tests cases are committed in a <a>dedicated repository</a> which is fetched by the <code>make install-submodule</code> command.
All the tests cases executed are located in the <code>tests/wpt</code> sub-directory.
For reference, you can easily execute a WPT test case with your browser via
<a>wpt.live</a>.
Run WPT test suite
To run all the tests:
<code>make wpt</code>
Or one specific test:
<code>make wpt Node-childNodes.html</code>
Add a new WPT test case
We add new relevant tests cases files when we implemented changes in Lightpanda.
To add a new test, copy the file you want from the <a>WPT
repo</a> into the <code>tests/wpt</code> directory.
:warning: Please keep the original directory tree structure of <code>tests/wpt</code>.
Contributing
Lightpanda accepts pull requests through GitHub.
You have to sign our <a>CLA</a> during the pull request process otherwise
we're not able to accept your contributions.
Why?
Javascript execution is mandatory for the modern web
In the good old days, scraping a webpage was as easy as making an HTTP request, cURL-like. It’s not possible anymore, because Javascript is everywhere, like it or not:
<ul>
<li>Ajax, Single Page App, infinite loading, “click to display”, instant search, etc.</li>
<li>JS web frameworks: React, Vue, Angular & others</li>
</ul>
Chrome is not the right tool
If we need Javascript, why not use a real web browser? Take a huge desktop application, hack it, and run it on the server. Hundreds or thousands of instances of Chrome if you use it at scale. Are you sure it’s such a good idea?
<ul>
<li>Heavy on RAM and CPU, expensive to run</li>
<li>Hard to package, deploy and maintain at scale</li>
<li>Bloated, lots of features are not useful in headless usage</li>
</ul>
Lightpanda is built for performance
If we want both Javascript and performance in a true headless browser, we need to start from scratch. Not another iteration of Chromium, really from a blank page. Crazy right? But that’s what we did:
<ul>
<li>Not based on Chromium, Blink or WebKit</li>
<li>Low-level system programming language (Zig) with optimisations in mind</li>
<li>Opinionated: without graphical rendering</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/84687501?v=4 | extism | extism/extism | 2022-08-13T06:55:30Z | The framework for building with WebAssembly (wasm). Easily & securely load wasm modules, move data, call functions, and build extensible apps. | main | 36 | 4,960 | 136 | 4,960 | https://api.github.com/repos/extism/extism/tags | BSD-3-Clause | [
"browser",
"c",
"cpp",
"csharp",
"dotnet",
"elixir",
"go",
"haskell",
"java",
"javascript",
"node",
"ocaml",
"plugin-system",
"python",
"ruby",
"rust",
"serverless",
"wasm",
"webassembly",
"zig"
] | 9,439 | false | 2025-05-22T00:01:10Z | false | false | unknown | github | [] |
<a>
</a>
[](https://extism.org/discord)




Overview
Extism is a lightweight framework for building with WebAssembly (Wasm). It
supports running Wasm code on servers, the edge, CLIs, IoT, browsers and
everything in between. Extism is designed to be "universal" in that it supports
a common interface, no matter where it runs.
<blockquote>
<strong>Note:</strong> One of the primary use cases for Extism is <strong>building extensible
software & plugins</strong>. You want to be able to execute arbitrary, untrusted code
from your users? Extism makes this safe and practical to do.
</blockquote>
Additionally, Extism adds some extra utilities on top of standard Wasm runtimes.
For example, we support persistent memory/module-scope variables, secure &
host-controlled HTTP without WASI, runtime limiters & timers, simpler host
function linking, and more. Extism users build:
<ul>
<li>plug-in systems</li>
<li>FaaS platforms</li>
<li>code generators</li>
<li>web applications</li>
<li>& much more...</li>
</ul>
Supported Targets
We currently provide releases for the following targets:
<ul>
<li>aarch64-apple-darwin</li>
<li>aarch64-unknown-linux-gnu</li>
<li>aarch64-unknown-linux-musl</li>
<li>x86_64-apple-darwin</li>
<li>x86_64-pc-windows-gnu</li>
<li>x86_64-pc-windows-msvc</li>
<li>x86_64-unknown-linux-gnu</li>
<li>x86_64-unknown-linux-musl</li>
</ul>
For Android we suggest taking a look at the <a>Chicory SDK</a> for a pure Java
Extism runtime.
Run WebAssembly In Your App
Pick a SDK to import into your program, and refer to the documentation to get
started:
| Type | Language | Source Code | Package |
| ----------- | ---------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| Rust SDK | | https://github.com/extism/extism/tree/main/runtime | <a>Crates.io</a> |
| JS SDK | | https://github.com/extism/js-sdk (supports Web, Node, Deno & Bun!) | <a>NPM</a> |
| Elixir SDK | | https://github.com/extism/elixir-sdk | <a>Hex</a> |
| Go SDK | | https://github.com/extism/go-sdk | <a>Go mod</a> |
| Haskell SDK | | https://github.com/extism/haskell-sdk | <a>Hackage</a> |
| Java SDK | | https://github.com/extism/java-sdk | <a>Sonatype</a> |
| .NET SDK | | https://github.com/extism/dotnet-sdk (supports C# & F#!) | <a>Nuget</a> |
| OCaml SDK | | https://github.com/extism/ocaml-sdk | <a>opam</a> |
| Perl SDK | | https://github.com/extism/perl-sdk | <a>CPAN</a> |
| PHP SDK | | https://github.com/extism/php-sdk | <a>Packagist</a> |
| Python SDK | | https://github.com/extism/python-sdk | <a>PyPi</a> |
| Ruby SDK | | https://github.com/extism/ruby-sdk | <a>RubyGems</a> |
| Zig SDK | | https://github.com/extism/zig-sdk | N/A |
| C SDK | | https://github.com/extism/extism/tree/main/libextism | N/A |
| C++ SDK | | https://github.com/extism/cpp-sdk | N/A |
Compile WebAssembly to run in Extism Hosts
Extism Hosts (running the SDK) must execute WebAssembly code that has a
<a>PDK, or Plug-in Development Kit</a>, library
compiled in to the <code>.wasm</code> binary. PDKs make it easy for plug-in / extension
code authors to read input from the host and return data back, read provided
configuration, set/get variables, make outbound HTTP calls if allowed, and more.
Pick a PDK to import into your Wasm program, and refer to the documentation to
get started:
| Type | Language | Source Code | Package |
| ------------------ | ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- | --------------------------------------------------------- |
| Rust PDK | | https://github.com/extism/rust-pdk | <a>Crates.io</a> |
| JS PDK | | https://github.com/extism/js-pdk | N/A |
| Python PDK | | https://github.com/extism/python-pdk | N/A |
| Go PDK | | https://github.com/extism/go-pdk | <a>Go mod</a> |
| Haskell PDK | | https://github.com/extism/haskell-pdk | <a>Hackage</a> |
| AssemblyScript PDK | | https://github.com/extism/assemblyscript-pdk | <a>NPM</a> |
| .NET PDK | | https://github.com/extism/dotnet-pdk (supports C# & F#!) | <a>Nuget</a> |
| C PDK | | https://github.com/extism/c-pdk | N/A |
| C++ PDK | | https://github.com/extism/cpp-pdk | N/A |
| Zig PDK | | https://github.com/extism/zig-pdk | N/A |
Generating Bindings
It's often very useful to define a schema to describe the function signatures
and types you want to use between Extism SDK and PDK languages.
<a>XTP Bindgen</a> is an open source
framework to generate PDK bindings for Extism plug-ins. It's used by the
<a>XTP Platform</a>, but can be used outside of the platform
to define any Extism compatible plug-in system.
1. Install the <code>xtp</code> CLI.
See installation instructions
<a>here</a>.
2. Create a schema using our OpenAPI-inspired IDL:
```yaml
version: v1-draft
exports:
CountVowels:
input:
type: string
contentType: text/plain; charset=utf-8
output:
$ref: "#/components/schemas/VowelReport"
contentType: application/json
components.schemas defined in example-schema.yaml...
```
<blockquote>
See an example in <a>example-schema.yaml</a>, or a full
"kitchen sink" example on
<a>the docs page</a>.
</blockquote>
3. Generate bindings to use from your plugins:
```
xtp plugin init --schema-file ./example-schema.yaml
<blockquote>
<ol>
<li>TypeScript <ol>
<li>Go </li>
<li>Rust </li>
<li>Python </li>
<li>C# </li>
<li>Zig </li>
<li>C++ </li>
<li>GitHub Template </li>
<li>Local Template
```</li>
</ol>
</li>
</ol>
</blockquote>
This will create an entire boilerplate plugin project for you to get started
with. Implement the empty function(s), and run <code>xtp plugin build</code> to compile
your plugin.
<blockquote>
For more information about XTP Bindgen, see the
<a>dylibso/xtp-bindgen</a> repository and
the official
<a>XTP Schema documentation</a>.
</blockquote>
Support
Discord
If you experience any problems or have any questions, please join our
<a>Discord</a> and let us know. Our community is very
responsive and happy to help get you started.
Usage
Head to the <a>project website</a> for more information and docs.
Also, consider reading an <a>overview</a> of Extism
and its goals & approach.
Contribution
Thank you for considering a contribution to Extism, we are happy to help you
make a PR or find something to work on!
The easiest way to start would be to join the
<a>Discord</a> or open an issue on the
<a><code>extism/proposals</code></a> issue tracker, which
can eventually become an Extism Improvement Proposal (EIP).
For more information, please read the
<a>Contributing</a> guide.
Who's behind this?
Extism is an open-source product from the team at:
<a></a>
<em>Reach out and tell us what you're building! We'd love to help:</em>
<a>hello@dylibso.com</a> | [] |
https://avatars.githubusercontent.com/u/125233599?v=4 | zap | zigzap/zap | 2023-01-12T21:36:31Z | blazingly fast backends in zig | master | 22 | 2,877 | 97 | 2,877 | https://api.github.com/repos/zigzap/zap/tags | MIT | [
"api",
"blazingly",
"fast",
"http",
"rest",
"zig",
"zig-package"
] | 11,398 | false | 2025-05-22T06:15:05Z | true | true | unknown | github | [] | ⚡zap⚡ - blazingly fast backends in zig
<a></a>
Zap is the <a>zig</a> replacement for the REST APIs I used to
write in <a>python</a> with
<a>Flask</a> and
<a>mongodb</a>, etc. It can be considered to be a
microframework for web applications.
What I needed as a replacement was a blazingly fast and robust HTTP server that
I could use with Zig, and I chose to wrap the superb evented networking C
library <a>facil.io</a>. Zap wraps and patches <a>facil.io - the C
web application framework</a>.
<strong>⚡ZAP⚡ IS FAST, ROBUST, AND STABLE</strong>
After having used ZAP in production for years, I can confidently assert that it
proved to be:
<ul>
<li>⚡ <strong>blazingly fast</strong> ⚡</li>
<li>💪 <strong>extremely robust</strong> 💪</li>
</ul>
FAQ:
<ul>
<li>Q: <strong>What version of Zig does Zap support?</strong><ul>
<li>Zap uses the latest stable zig release (0.14.0), so you don't have to keep
up with frequent breaking changes. It's an "LTS feature".</li>
</ul>
</li>
<li>Q: <strong>Can Zap build with Zig's master branch?</strong><ul>
<li>See the <code>zig-master</code> branch. Please note that the zig-master branch is not
the official master branch of ZAP. Be aware that I don't provide tagged
releases for it. If you know what you are doing, that shouldn't stop you
from using it with zig master though.</li>
</ul>
</li>
<li>Q: <strong>Where is the API documentation?</strong><ul>
<li>Docs are a work in progress. You can check them out
<a>here</a>.</li>
<li>Run <code>zig build run-docserver</code> to serve them locally.</li>
</ul>
</li>
<li>Q: <strong>Does ZAP work on Windows?</strong><ul>
<li>No. This is due to the underlying facil.io C library. Future versions
of facil.io might support Windows but there is no timeline yet. Your best
options on Windows are <strong>WSL2 or a docker container</strong>.</li>
</ul>
</li>
<li>Q: <strong>Does ZAP support TLS / HTTPS?</strong><ul>
<li>Yes, ZAP supports using the system's openssl. See the
<a>https</a> example and make sure to build with
the <code>-Dopenssl</code> flag or the environment variable <code>ZAP_USE_OPENSSL=true</code>:</li>
<li><code>.openssl = true,</code> (in dependent projects' build.zig,
<code>b.dependency("zap" .{...})</code>)</li>
<li><code>ZAP_USE_OPENSSL=true zig build https</code></li>
<li><code>zig build -Dopenssl=true https</code></li>
</ul>
</li>
</ul>
Here's what works
I recommend checking out <strong>the new App-based</strong> or the Endpoint-based
examples, as they reflect how I intended Zap to be used.
Most of the examples are super stripped down to only include what's necessary to
show a feature.
<strong>To see API docs, run <code>zig build run-docserver</code>.</strong> To specify a custom
port and docs dir: <code>zig build docserver && zig-out/bin/docserver --port=8989
--docs=path/to/docs</code>.
New App-Based Examples
<ul>
<li><strong><a>app_basic</a></strong>: Shows how to use zap.App with a
simple Endpoint.</li>
<li><strong><a>app_auth</a></strong>: Shows how to use zap.App with an
Endpoint using an Authenticator.</li>
</ul>
See the other examples for specific uses of Zap.
Benefits of using <code>zap.App</code>:
<ul>
<li>Provides a global, user-defined "Application Context" to all endpoints.</li>
<li>Made to work with "Endpoints": an endpoint is a struct that covers a <code>/slug</code>
of the requested URL and provides a callback for each supported request method
(get, put, delete, options, post, head, patch).</li>
<li>Each request callback receives:</li>
<li>a per-thread arena allocator you can use for throwaway allocations without
worrying about freeing them.</li>
<li>the global "Application Context" of your app's choice</li>
<li>Endpoint request callbacks are allowed to return errors:</li>
<li>you can use <code>try</code>.</li>
<li>the endpoint's ErrorStrategy defines if runtime errors should be reported to
the console, to the response (=browser for debugging), or if the error
should be returned.</li>
</ul>
Legacy Endpoint-based examples
<ul>
<li><strong><a>endpoint</a></strong>: a simple JSON REST API example featuring a
<code>/users</code> endpoint for performing PUT/DELETE/GET/POST operations and listing
users, together with a simple frontend to play with. <strong>It also introduces a
<code>/stop</code> endpoint</strong> that shuts down Zap, so <strong>memory leak detection</strong> can be
performed in main().<ul>
<li>Check out how <a>main.zig</a> uses ZIG's awesome
<code>GeneralPurposeAllocator</code> to report memory leaks when ZAP is shut down.
The <a>StopEndpoint</a> just stops ZAP when
receiving a request on the <code>/stop</code> route.</li>
</ul>
</li>
<li><strong><a>endpoint authentication</a></strong>: a
simple authenticated endpoint. Read more about authentication
<a>here</a>.</li>
</ul>
Legacy Middleware-Style examples
<ul>
<li><strong><a>MIDDLEWARE support</a></strong>: chain together
request handlers in middleware style. Provide custom context structs, totally
type-safe. If you come from GO this might appeal to you.</li>
<li><strong><a>MIDDLEWARE with endpoint
support</a></strong>:
Same as the example above, but this time we use an endpoint at the end of the
chain, by wrapping it via <code>zap.Middleware.EndpointHandler</code>. Mixing endpoints
in your middleware chain allows for usage of Zap's authenticated endpoints and
your custom endpoints. Since Endpoints use a simpler API, you have to use
<code>r.setUserContext()</code> and <code>r.getUserContext()</code> with the request if you want to
access the middleware context from a wrapped endpoint. Since this mechanism
uses an <code>*anyopaque</code> pointer underneath (to not break the Endpoint API), it is
less type-safe than <code>zap.Middleware</code>'s use of contexts.</li>
<li><a><strong>Per Request Contexts</strong></a> : With the introduction of
<code>setUserContext()</code> and <code>getUserContext()</code>, you can, of course use those two in
projects that don't use <code>zap.Endpoint</code> or <code>zap.Middleware</code>, too, if you
really, really, absolutely don't find another way to solve your context
problem. <strong>We recommend using a <code>zap.Endpoint</code></strong> inside of a struct that
can provide all the context you need <strong>instead</strong>. You get access to your
struct in the callbacks via the <code>@fieldParentPtr()</code> trick that is used
extensively in Zap's examples, like the <a>endpoint
example</a>.</li>
</ul>
Specific and Very Basic Examples
<ul>
<li><strong><a>hello</a></strong>: welcomes you with some static HTML</li>
<li><strong><a>routes</a></strong>: a super easy example dispatching on
the HTTP path. <strong>NOTE</strong>: The dispatch in the example is a super-basic
DIY-style dispatch. See endpoint-based examples for more realistic use cases.</li>
<li><a><strong>simple_router</strong></a>: See how you
can use <code>zap.Router</code> to dispatch to handlers by HTTP path.</li>
<li><strong><a>serve</a></strong>: the traditional static web server with
optional dynamic request handling</li>
<li><strong><a>sendfile</a></strong>: simple example of how to send
a file, honoring compression headers, etc.</li>
<li><strong><a>bindataformpost</a></strong>: example
to receive binary files via form post.</li>
<li><strong><a>hello_json</a></strong>: serves you json
dependent on HTTP path</li>
<li><strong><a>mustache</a></strong>: a simple example using
<a>mustache</a> templating.</li>
<li><strong><a>http parameters</a></strong>: a simple example
sending itself query parameters of all supported types.</li>
<li><strong><a>cookies</a></strong>: a simple example sending itself a
cookie and responding with a session cookie.</li>
<li><strong><a>websockets</a></strong>: a simple websockets chat for the
browser.</li>
<li><strong><a>Username/Password Session
Authentication</a></strong>: A convenience
authenticator that redirects un-authenticated requests to a login page and
sends cookies containing session tokens based on username/password pairs
received via POST request.</li>
<li><a><strong>Error Trace Responses</strong></a>: You can now
call <code>r.sendError(err, status_code)</code> when you catch an error and a stack trace
will be returned to the client / browser.</li>
<li><a><strong>HTTPS</strong></a>: Shows how easy it is to use facil.io's
openssl support. Must be compiled with <code>-Dopenssl=true</code> or the environment
variable <code>ZAP_USE_OPENSSL</code> set to <code>true</code> and requires openssl dev dependencies
(headers, lib) to be installed on the system.</li>
<li>run it like this: <code>ZAP_USE_OPENSSL=true zig build run-https</code>
OR like this: <code>zig build -Dopenssl=true run-https</code></li>
<li>it will tell you how to generate certificates</li>
</ul>
⚡blazingly fast⚡
Claiming to be blazingly fast is the new black. At least, Zap doesn't slow you
down and if your server performs poorly, it's probably not exactly Zap's fault.
Zap relies on the <a>facil.io</a> framework and so it can't really
claim any performance fame for itself. In this initial implementation of Zap,
I didn't care about optimizations at all.
But, how fast is it? Being blazingly fast is relative. When compared with a
simple GO HTTP server, a simple Zig Zap HTTP server performed really well on my
machine (x86_64-linux):
<ul>
<li>Zig Zap was nearly 30% faster than GO</li>
<li>Zig Zap had over 50% more throughput than GO</li>
<li><strong>YMMV!!!</strong></li>
</ul>
So, being somewhere in the ballpark of basic GO performance, zig zap seems to be
... of reasonable performance 😎.
I can rest my case that developing ZAP was a good idea because it's faster than
both alternatives: a) staying with Python, and b) creating a GO + Zig hybrid.
On (now missing) Micro-Benchmarks
I used to have some micro-benchmarks in this repo, showing that Zap beat all the
other things I tried, and eventually got tired of the meaningless discussions
they provoked, the endless issues and PRs that followed, wanting me to add and
maintain even more contestants, do more justice to beloved other frameworks,
etc.
Case in point, even for me the micro-benchmarks became meaningless. They were
just some rough indicator to me confirming that I didn't do anything terribly
wrong to facil.io, and that facil.io proved to be a reasonable choice, also from
a performance perspective.
However, none of the projects I use Zap for, ever even remotely resembled
anything close to a static HTTP response micro-benchmark.
For my more CPU-heavy than IO-heavy use-cases, a thread-based microframework
that's super robust is still my preferred choice, to this day.
Having said that, I would <strong>still love</strong> for other, pure-zig HTTP frameworks to
eventually make Zap obsolete. Now, in 2025, the list of candidates is looking
really promising.
📣 Shout-Outs
<ul>
<li><a>http.zig</a> : Pure Zig! Close to Zap's
model. Performance = good!</li>
<li><a>jetzig</a> : Comfortably develop
modern web applications quickly, using http.zig under the hood</li>
<li><a>zzz</a> : Super promising, super-fast,
especially for IO-heavy tasks, io_uring support - need I say more?</li>
</ul>
💪 Robust
ZAP is <strong>very robust</strong>. In fact, it is so robust that I was confidently able to
only work with in-memory data (RAM) in all my ZAP projects so far: over 5 large
online research experiments. No database, no file persistence, until I hit
"save" at the end 😊.
So I was able to postpone my cunning data persistence strategy that's similar to
a mark-and-sweep garbage collector and would only persist "dirty" data when
traffic is low, in favor of getting stuff online more quickly. But even if
implemented, such a persistence strategy is risky because when traffic is not
low, it means the system is under (heavy) load. Would you confidently NOT save
data when load is high and the data changes most frequently -> the potential
data loss is maximized?
To answer that question, I just skipped it. I skipped saving any data until
receiving a "save" signal via API. And it worked. ZAP just kept on zapping. When
traffic calmed down or all experiment participants had finished, I hit "save"
and went on analyzing the data.
Handling all errors does pay off after all. No hidden control flow, no hidden
errors or exceptions is one of Zig's strengths.
To be honest: There are still pitfalls. E.g. if you request large stack sizes
for worker threads, Zig won't like that and panic. So make sure you don't have
local variables that require tens of megabytes of stack space.
🛡️ Memory-safe
See the <a>StopEndpoint</a> in the
<a>endpoint</a> example. The <code>StopEndpoint</code> just stops ZAP when
receiving a request on the <code>/stop</code> route. That example uses ZIG's awesome
<code>GeneralPurposeAllocator</code> in <a>main.zig</a> to report
memory leaks when ZAP is shut down.
You can use the same strategy in your debug builds and tests to check if your
code leaks memory.
Getting started
Make sure you have <strong>zig 0.14.0</strong> installed. Fetch it from
<a>here</a>.
<code>shell
$ git clone https://github.com/zigzap/zap.git
$ cd zap
$ zig build run-hello
$ # open http://localhost:3000 in your browser</code>
... and open <a>http://localhost:3000</a> in your browser.
Using ⚡zap⚡ in your own projects
Make sure you have <strong>the latest zig release (0.14.0)</strong> installed. Fetch it from
<a>here</a>.
If you don't have an existing zig project, create one like this:
<code>shell
$ mkdir zaptest && cd zaptest
$ zig init</code>
With an existing Zig project, adding Zap to it is easy:
<ol>
<li>Zig fetch zap</li>
<li>Add zap to your <code>build.zig</code></li>
</ol>
In your zig project folder (where <code>build.zig</code> is located), run:
<code>zig fetch --save "git+https://github.com/zigzap/zap#v0.10.1"</code>
Then, in your <code>build.zig</code>'s <code>build</code> function, add the following before
<code>b.installArtifact(exe)</code>:
```zig
const zap = b.dependency("zap", .{
.target = target,
.optimize = optimize,
.openssl = false, // set to true to enable TLS support
});
<code>exe.root_module.addImport("zap", zap.module("zap"));
</code>
```
From then on, you can use the Zap package in your project via <code>const zap =
@import("zap");</code>. Check out the examples to see how to use Zap.
Contribute to ⚡zap⚡ - blazingly fast
At the current time, I can only add to zap what I need for my personal and
professional projects. While this happens <strong>blazingly fast</strong>, some if not all
nice-to-have additions will have to wait. You are very welcome to help make the
world a blazingly fast place by providing patches or pull requests, add
documentation or examples, or interesting issues and bug reports - you'll know
what to do when you receive your calling 👼.
<strong>We have our own <a>ZAP discord</a> server!!!</strong>
Support ⚡zap⚡
Being blazingly fast requires a constant feed of caffeine. I usually manage to
provide that to myself for myself. However, to support keeping the juices
flowing and putting a smile on my face and that warm and cozy feeling into my
heart, you can always <a>buy me a coffee</a>
☕. All donations are welcomed 🙏 blazingly fast! That being said, just saying
"hi" also works wonders with the smiles, warmth, and coziness 😊.
Examples
You build and run the examples via:
<code>shell
$ zig build [EXAMPLE]
$ ./zig-out/bin/[EXAMPLE]</code>
... where <code>[EXAMPLE]</code> is one of <code>hello</code>, <code>routes</code>, <code>serve</code>, ... see the <a>list of
examples above</a>.
Example: building and running the hello example:
<code>shell
$ zig build hello
$ ./zig-out/bin/hello</code>
To just run an example, like <code>routes</code>, without generating an executable, run:
<code>shell
$ zig build run-[EXAMPLE]</code>
Example: building and running the routes example:
<code>shell
$ zig build run-routes</code>
<a>hello</a>
```zig
const std = @import("std");
const zap = @import("zap");
fn on_request(r: zap.Request) !void {
if (r.path) |the_path| {
std.debug.print("PATH: {s}\n", .{the_path});
}
<code>if (r.query) |the_query| {
std.debug.print("QUERY: {s}\n", .{the_query});
}
r.sendBody("<html><body><h1>Hello from ZAP!!!</h1></body></html>") catch return;
</code>
}
pub fn main() !void {
var listener = zap.HttpListener.init(.{
.port = 3000,
.on_request = on_request,
.log = true,
});
try listener.listen();
<code>std.debug.print("Listening on 0.0.0.0:3000\n", .{});
// start worker threads
zap.start(.{
.threads = 2,
.workers = 2,
});
</code>
}
``` | [] |
https://avatars.githubusercontent.com/u/1299?v=4 | libxev | mitchellh/libxev | 2023-01-07T19:52:16Z | libxev is a cross-platform, high-performance event loop that provides abstractions for non-blocking IO, timers, events, and more and works on Linux (io_uring or epoll), macOS (kqueue), and Wasm + WASI. Available as both a Zig and C API. | main | 40 | 2,719 | 113 | 2,719 | https://api.github.com/repos/mitchellh/libxev/tags | MIT | [
"async",
"c",
"epoll",
"io-uring",
"kqueue",
"wasi",
"webassembly",
"zig"
] | 1,144 | false | 2025-05-21T20:18:05Z | true | true | 0.14.0 | github | [] | libxev
libxev is a cross-platform event loop. libxev provides a unified event loop
abstraction for non-blocking IO, timers, signals, events, and more that
works on macOS, Windows, Linux, and WebAssembly (browser and WASI). It is
written in <a>Zig</a> but exports a C-compatible API (which
further makes it compatible with any language out there that can communicate
with C APIs).
<strong>Project Status: Stable for most use cases.</strong> libxev is in daily use by
large projects such as <a>Ghostty</a>,
<a>zml</a>, and more. For most use cases, libxev
has been shown to be stable at scale. libxev has a broad featureset and
there are likely less well-used corners of the library, but for most
use cases libxev is already heavily used in production environments.
<strong>Why a new event loop library?</strong> A few reasons. One, I think Zig lacks
a generalized event loop comparable to libuv in features ("generalized"
being a key word here). Two, I wanted to build a library like this around
the design patterns of <a>io_uring</a>,
even mimicking its style on top of other OS primitives (
<a>credit to this awesome blog post</a>).
Three, I wanted an event loop library that could build to WebAssembly
(both WASI and freestanding) and that didn't really fit well
into the goals of API style of existing libraries without bringing in
something super heavy like Emscripten. The motivation for this library
primarily though is scratching my own itch!
Features
<strong>Cross-platform.</strong> Linux (<code>io_uring</code> and <code>epoll</code>), macOS (<code>kqueue</code>),
WebAssembly + WASI (<code>poll_oneoff</code>, threaded and non-threaded runtimes).
(Windows support is planned and coming soon)
<strong><a>Proactor API</a>.</strong> Work
is submitted to the libxev event loop and the caller is notified of
work <em>completion</em>, as opposed to work <em>readiness</em>.
<strong>Zero runtime allocations.</strong> This helps make runtime performance more
predictable and makes libxev well suited for embedded environments.
<strong>Timers, TCP, UDP, Files, Processes.</strong> High-level platform-agnostic APIs for
interacting with timers, TCP/UDP sockets, files, processes, and more. For
platforms that don't support async IO, the file operations are automatically
scheduled to a thread pool.
<strong>Generic Thread Pool (Optional).</strong> You can create a generic thread pool,
configure its resource utilization, and use this to perform custom background
tasks. The thread pool is used by some backends to do non-blocking tasks that
don't have reliable non-blocking APIs (such as local file operations with
<code>kqueue</code>). The thread pool can be shared across multiple threads and event
loops to optimize resource utilization.
<strong>Low-level and High-Level API.</strong> The high-level API is platform-agnostic
but has some opinionated behavior and limited flexibility. The high-level
API is recommended but the low-level API is always an available escape hatch.
The low-level API is platform-specific and provides a mechanism for libxev
users to squeeze out maximum performance. The low-level API is <em>just enough
abstraction</em> above the OS interface to make it easier to use without
sacrificing noticable performance.
<strong>Tree Shaking (Zig).</strong> This is a feature of Zig, but substantially benefits
libraries such as libxev. Zig will only include function calls and features
that you actually use. If you don't use a particular kind of high-level
watcher (such as UDP sockets), then the functionality related to that
abstraction is not compiled into your final binary at all. This lets libxev
support optional "nice-to-have" functionality that may be considered
"bloat" in some cases, but the end user doesn't have to pay for it.
<strong>Dependency-free.</strong> libxev has no dependencies other than the built-in
OS APIs at runtime. The C library depends on libc. This makes it very
easy to cross-compile.
Roadmap
There are plenty of missing features that I still want to add:
<ul>
<li>Pipe high-level API</li>
<li>Signal handlers</li>
<li>Filesystem events</li>
<li>Windows backend</li>
<li>Freestanding WebAssembly support via an external event loop (i.e. the browser)</li>
</ul>
And more...
Performance
There is plenty of room for performance improvements, and I want to be
fully clear that I haven't done a lot of optimization work. Still,
performance is looking good. I've tried to port many of
<a>libuv benchmarks</a> to use the libxev
API.
I won't post specific benchmark results until I have a better
environment to run them in. As a <em>very broad generalization</em>,
you shouldn't notice a slowdown using libxev compared to other
major event loops. This may differ on a feature-by-feature basis, and
if you can show really poor performance in an issue I'm interested
in resolving it!
Example
The example below shows an identical program written in Zig and in C
that uses libxev to run a single 5s timer. This is almost silly how
simple it is but is meant to just convey the overall feel of the library
rather than a practical use case.
Zig C
```zig
const xev = @import("xev");
pub fn main() !void {
var loop = try xev.Loop.init(.{});
defer loop.deinit();
const w = try xev.Timer.init();
defer w.deinit();
// 5s timer
var c: xev.Completion = undefined;
w.run(&loop, &c, 5000, void, null, &timerCallback);
try loop.run(.until_done);
}
fn timerCallback(
userdata: ?*void,
loop: *xev.Loop,
c: *xev.Completion,
result: xev.Timer.RunError!void,
) xev.CallbackAction {
_ = userdata;
_ = loop;
_ = c;
_ = result catch unreachable;
return .disarm;
}
```
```zig
#include
#include
#include
xev_cb_action timerCallback(xev_loop* loop, xev_completion* c, int result, void *userdata) {
return XEV_DISARM;
}
int main(void) {
xev_loop loop;
if (xev_loop_init(&loop) != 0) {
printf("xev_loop_init failure\n");
return 1;
}
xev_watcher w;
if (xev_timer_init(&w) != 0) {
printf("xev_timer_init failure\n");
return 1;
}
xev_completion c;
xev_timer_run(&w, &loop, &c, 5000, NULL, &timerCallback);
xev_loop_run(&loop, XEV_RUN_UNTIL_DONE);
xev_timer_deinit(&w);
xev_loop_deinit(&loop);
return 0;
}
```
Installation (Zig)
<strong>These instructions are for Zig downstream users only.</strong> If you are
using the C API to libxev, see the "Build" section.
This package works with the Zig package manager introduced in Zig 0.11.
Create a <code>build.zig.zon</code> file like this:
<code>zig
.{
.name = "my-project",
.version = "0.0.0",
.dependencies = .{
.libxev = .{
.url = "https://github.com/mitchellh/libxev/archive/<git-ref-here>.tar.gz",
.hash = "12208070233b17de6be05e32af096a6760682b48598323234824def41789e993432c",
},
},
}</code>
And in your <code>build.zig</code>:
<code>zig
const xev = b.dependency("libxev", .{ .target = target, .optimize = optimize });
exe.addModule("xev", xev.module("xev"));</code>
Documentation
🚧 Documentation is a work-in-progress. 🚧
Currently, documentation is available in three forms: <strong>man pages</strong>,
<strong>examples</strong>, and <strong>code comments.</strong> In the future, I plan on writing detailed
guides and API documentation in website form, but that isn't currently
available.
Man Pages
The man pages are relatively detailed! <code>xev(7)</code> will
give you a good overview of the entire library. <code>xev-zig(7)</code> and
<code>xev-c(7)</code> will provide overviews of the Zig and C API, respectively.
From there, API-specifc man pages such as <code>xev_loop_init(3)</code> are
available. This is the best documentation currently.
There are multiple ways to browse the man pages. The most immediately friendly
is to just browse the raw man page sources in the <code>docs/</code> directory in
your web browser. The man page source is a <em>markdown-like</em> syntax so it
renders <em>okay</em> in your browser via GitHub.
Another approach is to run <code>zig build -Dman-pages</code> and the man pages
will be available in <code>zig-out</code>. This requires
<a>scdoc</a>
to be installed (this is available in most package managers).
Once you've built the man pages, you can render them by path:
<code>$ man zig-out/share/man/man7/xev.7</code>
And the final approach is to install libxev via your favorite package
manager (if and when available), which should hopefully put your man pages
into your man path, so you can just do <code>man 7 xev</code>.
Examples
There are examples available in the <code>examples/</code> folder. The examples are
available in both C and Zig, and you can tell which one is which using
the file extension.
To build an example, use the following:
<code>$ zig build -Dexample-name=_basic.zig
...
$ zig-out/bin/example-basic
...</code>
The <code>-Dexample-name</code> value should be the filename including the extension.
Code Comments
The Zig code is well commented. If you're comfortable reading code comments
you can find a lot of insight within them. The source is in the <code>src/</code>
directory.
Build
Build requires the installation of the Zig 0.14.0. libxev follows stable
Zig releases and generally does not support nightly builds. When a stable
release is imminent we may have a branch that supports it.
<strong>libxev has no other build dependencies.</strong>
Once installed, <code>zig build install</code> on its own will build the full library and output
a <a>FHS-compatible</a>
directory in <code>zig-out</code>. You can customize the output directory with the
<code>--prefix</code> flag.
Tests
libxev has a large and growing test suite. To run the tests for the current
platform:
<code>sh
$ zig build test
...</code>
This will run all the tests for all the supported features for the current
host platform. For example, on Linux this will run both the full io_uring
and epoll test suite.
<strong>You can build and run tests for other platforms</strong> by cross-compiling the
test executable, copying it to a target machine and executing it. For example,
the below shows how to cross-compile and build the tests for macOS from Linux:
```sh
$ zig build -Dtarget=aarch64-macos -Dinstall-tests
...
$ file zig-out/bin/xev-test
zig-out/bin/xev-test: Mach-O 64-bit arm64 executable
```
<strong>WASI is a special-case.</strong> You can run tests for WASI if you have
<a>wasmtime</a> installed:
<code>$ zig build test -Dtarget=wasm32-wasi -Dwasmtime
...</code> | [
"https://github.com/Scythe-Technology/Zune",
"https://github.com/Thomvanoorschot/backstage",
"https://github.com/Thomvanoorschot/jolt",
"https://github.com/Thomvanoorschot/wire",
"https://github.com/dacheng-zig/ziro",
"https://github.com/dacheng-zig/ziro-sleep",
"https://github.com/elton2048/glizp",
"... |
https://avatars.githubusercontent.com/u/120156414?v=4 | cargo-zigbuild | rust-cross/cargo-zigbuild | 2022-02-16T06:38:36Z | Compile Cargo project with zig as linker | main | 32 | 1,923 | 70 | 1,923 | https://api.github.com/repos/rust-cross/cargo-zigbuild/tags | MIT | [
"cargo-subcommand",
"cross-compile",
"zig"
] | 861 | false | 2025-05-19T09:57:55Z | false | false | unknown | github | [] | cargo-zigbuild
<a></a>
<a></a>
<a></a>
<a></a>
<a></a>
<blockquote>
🚀 Help me to become a full-time open-source developer by <a>sponsoring me on GitHub</a>
</blockquote>
Compile Cargo project with <a>zig</a> as <a>linker</a> for
<a>easier cross compiling</a>.
Installation
<code>bash
cargo install --locked cargo-zigbuild</code>
You can also install it using pip which will also install <a><code>ziglang</code></a> automatically:
<code>bash
pip install cargo-zigbuild</code>
We also provide Docker images which has macOS SDK pre-installed in addition to cargo-zigbuild and Rust, for example to build for x86_64 macOS:
<ul>
<li>
Linux docker image (<a>ghcr.io</a>, <a>Docker Hub</a>):
<code>bash
docker run --rm -it -v $(pwd):/io -w /io ghcr.io/rust-cross/cargo-zigbuild \
cargo zigbuild --release --target x86_64-apple-darwin</code>
</li>
<li>
Windows docker image (<a>ghcr.io</a>, <a>Docker Hub</a>):
<code>powershell
docker run --rm -it -v ${pwd}:c:\io -w c:\io ghcr.io/rust-cross/cargo-zigbuild.windows `
cargo zigbuild --target x86_64-apple-darwin</code>
</li>
</ul>
<a></a>
Usage
<ol>
<li>Install <a>zig</a> following the <a>official documentation</a>,
on macOS, Windows and Linux you can also install zig from PyPI via <code>pip3 install ziglang</code></li>
<li>Install Rust target via rustup, for example, <code>rustup target add aarch64-unknown-linux-gnu</code></li>
<li>Run <code>cargo zigbuild</code>, for example, <code>cargo zigbuild --target aarch64-unknown-linux-gnu</code></li>
</ol>
Specify glibc version
<code>cargo zigbuild</code> supports passing glibc version in <code>--target</code> option, for example,
to compile for glibc 2.17 with the <code>aarch64-unknown-linux-gnu</code> target:
<code>bash
cargo zigbuild --target aarch64-unknown-linux-gnu.2.17</code>
<blockquote>
<span class="bg-blue-100 text-blue-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-blue-900 dark:text-blue-300">NOTE</span>
There are <a>various caveats</a> with the glibc version targeting feature:
- If you do not provide a <code>--target</code>, Zig is not used and the command effectively runs a regular <code>cargo build</code>.
- If you specify an invalid glibc version, <code>cargo zigbuild</code> will not relay the warning emitted from <code>zig cc</code> about the fallback version selected.
- This feature does not necessarily match the behaviour of dynamically linking to a specific version of glibc on the build host.
- Version 2.32 can be specified, but runs on a host with only 2.31 available when it should instead abort with an error.
- Meanwhile specifying 2.33 will correctly be detected as incompatible when run on a host with glibc 2.31.
- Certain <code>RUSTFLAGS</code> like <code>-C linker</code> opt-out of using Zig, while <code>-L path/to/files</code> will have Zig ignore <code>-C target-feature=+crt-static</code>.
- <code>-C target-feature=+crt-static</code> for statically linking to a glibc version is <strong>not supported</strong> (<em>upstream <code>zig cc</code> lacks support</em>)
</blockquote>
macOS universal2 target
<code>cargo zigbuild</code> supports a special <code>universal2-apple-darwin</code> target for building macOS universal2 binaries/libraries on Rust 1.64.0 and later.
<code>bash
rustup target add x86_64-apple-darwin
rustup target add aarch64-apple-darwin
cargo zigbuild --target universal2-apple-darwin</code>
<blockquote>
<strong>Note</strong>
Note that Cargo <code>--message-format</code> option doesn't work with universal2 target currently.
</blockquote>
Caveats
<ol>
<li>Currently only Linux and macOS targets are supported,
other target platforms can be added if you can make it work,
pull requests are welcome.</li>
<li>Only current Rust <strong>stable</strong> and <strong>nightly</strong> versions are regularly tested on CI, other versions may not work.</li>
</ol>
Known upstream zig <a>issues</a>:
<ol>
<li><a>zig cc: parse <code>-target</code> and <code>-mcpu</code>/<code>-march</code>/<code>-mtune</code> flags according to clang</a>:
Some Rust targets aren't recognized by <code>zig cc</code>, for example <code>armv7-unknown-linux-gnueabihf</code>, workaround by using <code>-mcpu=generic</code> and
explicitly passing target features in <a>#58</a></li>
<li><a>ability to link against darwin frameworks (such as CoreFoundation) when cross compiling</a>:
Set the <code>SDKROOT</code> environment variable to a macOS SDK path to workaround it</li>
<li><a>zig misses some <code>compiler_rt</code> functions</a> that may lead to undefined symbol error for certain
targets. See also: <a>zig compiler-rt status</a>.</li>
<li><a>CPU features are not passed to clang</a></li>
</ol>
License
This work is released under the MIT license. A copy of the license is provided
in the <a>LICENSE</a> file. | [] |
https://avatars.githubusercontent.com/u/109492796?v=4 | awesome-zig | zigcc/awesome-zig | 2022-12-17T03:52:10Z | A collection of some awesome public Zig programming language projects. | main | 0 | 1,415 | 75 | 1,415 | https://api.github.com/repos/zigcc/awesome-zig/tags | MIT | [
"andrew-kelley",
"awesome-list",
"bun",
"mach",
"zig",
"zig-lib",
"zig-library",
"zig-package",
"ziglang"
] | 291 | false | 2025-05-22T02:02:13Z | false | false | unknown | github | [] | Awesome Zig
This repository lists "awesome" projects written in Zig, maintained by <a>ZigCC community</a>.
<blockquote>
<span class="bg-green-100 text-green-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-green-900 dark:text-green-300">IMPORTANT</span>
The word "awesome" does not signify stability; instead, it might suggest something is somewhat old-fashioned or lacking novelty. Hence, exercise caution.
</blockquote>
Contributing
If you find a well-maintained library that is not yet included here, welcome to submit it via a pull request. Just be sure to execute <code>make all</code> before you open a PR.
Contents
<ul>
<li><a>Learning Resources</a></li>
<li><a>Tools</a></li>
<li><a>Text Editors</a></li>
<li><a>Linter</a></li>
<li><a>Documentation and Testing</a></li>
<li><a>Package and Version Manager</a></li>
<li><a>Utility</a></li>
<li><a>Linker</a></li>
<li><a>Data Structure and Algorithm</a></li>
<li><a>String Processing</a></li>
<li><a>File format processing</a></li>
<li><a>Logging Processing</a></li>
<li><a>Audio Processing</a></li>
<li><a>Image and Video Processing</a></li>
<li><a>Date, Time and Timezones</a></li>
<li><a>Command Line and Argument Parser</a></li>
<li><a>Memory Allocator and Management</a></li>
<li><a>Asynchronous Runtime</a></li>
<li><a>Multithreading</a></li>
<li><a>Embedded Development</a></li>
<li><a>General Operating System</a></li>
<li><a>Robot Operating System</a></li>
<li><a>Compilers and Interpreters</a></li>
<li><a>FFI Bindings</a></li>
<li><a>Zigged Project</a></li>
<li><a>GPU Computing</a></li>
<li><a>Scientific Computation</a></li>
<li><a>Linear Algebra</a></li>
<li><a>Machine Learning</a></li>
<li><a>Machine Learning Framework</a></li>
<li><a>Large Language Model</a></li>
<li><a>Database</a></li>
<li><a>Sensor and Communication Interface</a></li>
<li><a>Finite State Machine</a></li>
<li><a>Game Field</a></li>
<li><a>Emulators</a></li>
<li><a>Encryption</a></li>
<li><a>Network</a></li>
<li><a>Web Framework</a></li>
<li><a>Web3 Framework</a></li>
<li><a>WebAssembly</a></li>
<li><a>Performance Benchmark</a></li>
<li><a>Graphics Library</a></li>
<li><a>GUI</a></li>
<li><a>Misc</a></li>
</ul>
TOC is generated by <a>markdown-toc</a>.
Learning Resources
<ul>
<li><a>Zig Language Reference</a> : Zig Language Reference.</li>
<li><a>Zig In-depth Overview</a> : Zig In-depth Overview.</li>
<li><a>Zig Guide</a> : Get started with the Zig programming language.</li>
<li><a>Zig cookbook</a> : A collection of simple Zig programs that demonstrate good practices to accomplish common programming tasks.</li>
<li><a>Zig in 30 minutes</a> : A half-hour to learn Zig.</li>
<li><a>Ziglings</a> : Learn the Zig programming language by fixing tiny broken programs.</li>
<li><a>Awesome zig wiki</a>: Other interesting materials about Zig.</li>
<li><a>Learning Zig</a> : This guide aims to make you comfortable with Zig. It assumes prior programming experience, though not in any particular language.</li>
<li><a>Zig 圣经</a> : 简单、快速地学习 Zig.</li>
</ul>
Tools
Text Editors
<ul>
<li><a>FalsePattern/ZigBrains</a> : JetBrains IDEs (CLion, IntelliJ IDEA and others) plugin for Zig</li>
<li><a>isaachier/ztags</a> : ctags implementation for Zig written in Zig.</li>
<li><a>jinzhongjia/znvim</a> : neovim remote rpc client implementation with Zig.</li>
<li><a>Tetralux/sublime-zig</a> : My own, more lightweight, syntax highlighting for the Zig Programming Language.</li>
<li><a>ziglang/sublime-zig-language</a> : Zig language support for Sublime Text.</li>
<li><a>ziglang/vscode-zig</a> : Zig language support for VSCode.</li>
<li><a>ziglang/zig.vim</a> : Vim configuration for Zig.</li>
<li><a>ziglang/zig-mode</a> : Zig mode for Emacs.</li>
<li><a>zigtools/zls</a> : The @ziglang language server for all your Zig editor tooling needs, from autocomplete to goto-def! <a>install.zigtools.org/</a></li>
<li><a>jinzhongjia/zig-lamp</a> : Improve the Zig development experience in Neovim.</li>
<li><a>neurocyte/flow</a> : Flow Control - a programmer's text editor written in Zig.</li>
</ul>
Linter
<ul>
<li><a>nektro/ziglint</a> : linting suite for Zig</li>
</ul>
Documentation and Testing
<ul>
<li><a>kristoff-it/zig-doctest</a> : A tool for testing snippets of code, useful for websites and books that talk about Zig.</li>
</ul>
Package and Version Manager
<ul>
<li><a>zigcc/asdf-zig</a> : zig plugin for asdf version manager. <a>https://github.com/asdf-vm/asdf</a></li>
<li><a>marler8997/zigup</a> : Download and manage zig compilers.</li>
<li><a>zigtools/zpm</a> : Zig package manager helper.</li>
<li><a>goto-bus-stop/setup-zig</a> : Setup Zig for GitHub Action Workflows.</li>
<li><a>korandoru/setup-zig</a> : Set up your GitHub Actions workflow with a specific version of Zig.</li>
<li><a>jsomedon/night.zig</a> : Simple tool that just install & update zig nightly.</li>
<li><a>matklad/hello-getzig</a> : getzig is an idea for a zig version manager along the lines of gradle wrapper.</li>
<li><a>mitchellh/zig-overlay</a> : Nix flake for the Zig compiler.</li>
<li><a>Cloudef/zig2nix</a> : Flake for packaging, building and running Zig projects.</li>
<li><a>nix-community/zon2nix</a> : Convert dependencies in build.zig.zon files to Nix expressions.</li>
<li><a>Cloudef/nix-zig-stdenv</a> : Zig based cross-compiling toolchain.</li>
<li><a>joachimschmidt557/zigpkgs</a> : A collection of zig packages built with Nix.</li>
<li><a>nektro/zigmod</a> : 📦 A package manager for the Zig programming language.</li>
<li><a>mattnite/gyro</a> : A Zig package manager with an index, build runner, and build dependencies.</li>
<li><a>vezel-dev/zig-sdk</a> : An MSBuild SDK for building Zig, C, and C++ projects using the Zig compiler.</li>
<li><a>tristanisham/zvm</a> : lets you easily install/upgrade between different versions of Zig. ZLS install can be included.</li>
</ul>
Utility
<ul>
<li><a>BrookJeynes/jido</a> : Jido (formerly known as zte) is a small terminal file explorer, written in Zig.</li>
<li><a>fearedbliss/Honeydew</a> : A simple snapshot cleaner for OpenZFS written in Zig.</li>
<li><a>fearedbliss/Cantaloupe</a> : A simple backup replication tool for OpenZFS written in Zig.</li>
<li><a>Arnau478/hevi</a> : A minimalistic and modernized hex viewer, written in Zig.</li>
<li><a>gaskam/workspace</a> : A powerful Zig-based tool to manage all your GitHub repositories with ease.</li>
<li><a>rockorager.dev/lsr</a> : Efficient and fast <code>ls</code> alternative, written in Zig.</li>
</ul>
Linker
<ul>
<li><a>kubkon/bold</a> : <strong>bold</strong> is a drop-in replacement for Apple’s system linker <code>ld</code></li>
</ul>
Data Structure and Algorithm
<ul>
<li><a>hello-algo-zig</a> : <strong>Zig</strong> programming language codes for the famous public project <a>《Hello, Algorithm》|《 Hello,算法 》</a> about data structures and algorithms.</li>
<li><a>TheAlgorithms/Zig</a> : Collection of Algorithms implemented in Zig.</li>
<li><a>ramsyana/Zig-Math-Algorithms</a> : A collection of math algorithms in Zig—primes, Fibonacci, GCD, Euler's Totient, & more! Perfect for learning Zig & math.</li>
<li><a>alichraghi/zort</a> : Zort: Sorting algorithms in zig.</li>
<li><a>Srekel/zig-sparse-set</a> : 🎡 zig-sparse-set 🎡. Sparse sets for zig, supporting both SOA and AOS style.</li>
<li><a>mitchellh/zig-graph</a> : Directed graph data structure for Zig.</li>
<li><a>ok-ryoko/multiring.zig</a> : Singly linked, cyclic and hierarchical abstract data type in Zig.</li>
<li><a>jakubgiesler/VecZig</a> : Vector implementation in Zig.</li>
<li><a>JacobCrabill/btree.zig</a> : Behavior Tree library written in Zig.</li>
<li><a>DutchGhost/ArrayVec</a> : A library with an ArrayList-like API, except its a static array.</li>
<li><a>emekoi/deque.zig</a> : a lock free chase-lev deque for zig.</li>
<li><a>kristoff-it/zig-cuckoofilter</a> : Production-ready Cuckoo Filters for any C ABI compatible target.</li>
<li><a>BarabasGitHub/LZig4</a> : Implementing lz4 in zig.</li>
<li><a>marijnfs/zigtimsort</a> : TimSort implementation for Zig.</li>
<li><a>Sahnvour/zig-containers</a> : A set of containers for Zig.</li>
<li><a>booniepepper/zig-data-structures</a> : Home to some experiments in Zig data structures.</li>
<li><a>deckarep/ziglang-set</a> : A generic and general purpose Set implementation for the Zig language.</li>
<li><a>yamafaktory/hypergraphz</a> : HypergraphZ - A Hypergraph Implementation in Zig.</li>
<li><a>williamw520/toposort</a> : Topological sort library that produces topological ordered nodes and dependence-free subsets.</li>
<li><a>kobolds-io/stdx</a> : Helpful extensions to the zig standard library.</li>
</ul>
String Processing
<ul>
<li><a>JakubSzark/zig-string</a> : Zig String (A UTF-8 String Library). This library is a UTF-8 compatible string library for the Zig programming language.</li>
<li><a>jecolon/zigstr</a> : Zigstr is a UTF-8 string type for Zig programs.</li>
<li><a>ziglibs/string-searching</a> : String(not limited to []const u8)-searching algorithms in zig.</li>
<li><a>hwu1001/zig-string</a> : A String struct made for Zig.</li>
</ul>
File format processing
<ul>
<li><a>ziglibs/known-folders</a> Provides access to well-known folders across several operating systems.</li>
<li><a>tiehuis/zig-regex</a> : A regex implementation for the zig programming language.</li>
<li><a>getty-zig/getty</a> : Getty is a framework for building robust, optimal, and reusable (de)serializers in Zig. <a>getty.so</a></li>
<li><a>jecolon/ziglyph</a> : Unicode text processing for the Zig programming language.</li>
<li><a>kubkon/zig-yaml</a> : YAML parser for Zig.</li>
<li><a>nektro/zig-json</a> : A JSON library for inspecting arbitrary values.</li>
<li><a>getty-zig/json</a> : Getty JSON is a (de)serialization library for the JSON data format.</li>
<li><a>MahBestBro/regex</a> : A single file regex library written in and for Zig.</li>
<li><a>karlseguin/log.zig</a> : A structured logger for Zig.</li>
<li><a>mattyhall/tomlz</a> : A well-tested TOML parsing library for Zig.</li>
<li><a>mitchellh/zig-libxml2</a> : libxml2 built using Zig build system.</li>
<li><a>travisstaloch/protobuf-zig</a> : A protocol buffers implementation in zig.</li>
<li><a>sam701/zig-toml</a> : Zig TOML (v1.0.0) parser.</li>
<li><a>ziglibs/tres</a> : ValueTree-based JSON parser.</li>
<li><a>ziglibs/s2s</a> : A zig binary serialization format.</li>
<li><a>Arwalk/zig-protobuf</a> : a protobuf 3 implementation for zig.</li>
<li><a>aeronavery/zig-toml</a> : A TOML parser written in Zig.</li>
<li><a>goto-bus-stop/ziguid</a> : GUID parsing/stringifying with zig.</li>
<li><a>ducdetronquito/hppy</a> : The happy HTML parser ᕕ( ᐛ )ᕗ.</li>
<li><a>kivikakk/libpcre.zig</a> : Zig bindings to libpcre.</li>
<li><a>kivikakk/koino</a> : CommonMark + GFM compatible Markdown parser and renderer.</li>
<li><a>m-r-hunt/tjp</a> : Typed JSON Parser.</li>
<li><a>tiehuis/zig-ryu</a> : Zig port of <a>https://github.com/ulfjack/ryu</a>.</li>
<li><a>vi/zigmkv</a> : [wip] Matroska/webm (mkv) parser in Zig.</li>
<li><a>winksaville/zig-parse-number</a> : Implement ParseNumber which can parse any TypeId.Int or TypeId.Float.</li>
<li><a>demizer/markzig</a> : Pure Zig Markdown Parser.</li>
<li><a>thejoshwolfe/hexdump-zip</a> : produce an annotated hexdump of a zipfile.</li>
<li><a>javiorfo/prettizy</a> : Zig library to prettify JSON and XML strings.</li>
<li><a>javiorfo/zig-epub</a> : Minimal Zig library for creating EPUB files.</li>
</ul>
Logging Processing
<ul>
<li><a>emekoi/log.zig</a> : a thread-safe logging library for zig.</li>
<li><a>g41797/syslog</a> : <a>syslog</a> RFC5424 client library.</li>
<li><a>chrischtel/nexlog</a> : A modern, feature-rich logging library for Zig with thread-safety, file rotation, and colorized output.</li>
<li><a>sam701/slog</a> : a configurable, structured logging package for Zig with support for hierarchical loggers.</li>
</ul>
Audio Processing
<ul>
<li><a>orhun/linuxwave</a> : Generate music from the entropy of Linux 🐧🎵. <a>orhun.dev/linuxwave/</a></li>
<li><a>hexops/mach-sysaudio</a> : cross-platform low-level audio IO in Zig.</li>
<li><a>Hejsil/zig-midi</a> : zig-midi.</li>
</ul>
Image and Video Processing
<ul>
<li><a>zigimg/zigimg</a> : Zig library for reading and writing different image formats.</li>
<li><a>ryoppippi/zigcv</a> : opencv bindings for zig.</li>
<li><a>kassane/libvlc-zig</a> : Zig bindings for libVLC media framework.</li>
<li><a>marler8997/image-viewer</a> : An image-viewer experiment written in Zig.</li>
<li><a>bfactory-ai/zignal</a> : Image processing library in Zig, heavily inspired by dlib .</li>
</ul>
Date, Time and Timezones
<ul>
<li><a>scento/zig-date</a> : 🕒 time and date for Zig. zig-date is a date and time library for the Zig, inspired by the popular Rust library <a>chrono</a>.</li>
<li><a>frmdstryr/zig-datetime</a> : A datetime module for Zig with an api similar to python's Arrow.</li>
<li><a>nektro/zig-time</a> : A date and time parsing and formatting library for Zig.</li>
<li><a>travisstaloch/date-zig</a> : fast calendar algorithms ported to Zig (Cassio Neri's <a>EAF</a>).</li>
<li><a>leroycep/chrono-zig</a> : Zig port of the Rust chrono crate.</li>
<li><a>karlseguin/zul</a> : some date/time handling functionality among the other functionality.</li>
<li><a>clickingbuttons/datetime</a> : Generic Date, Time, and DateTime library.</li>
<li><a>leroycep/zig-tzif</a> : <a>TZif</a> parser that also handles POSIX timezone strings</li>
<li><a>FObersteiner/zdt</a> : Timezoned Datetime in Zig. For learning purposes.</li>
<li><a>rockorager/zeit</a> : Generic date/time library, including time zone loading and conversion.</li>
<li><a>deatil/zig-time</a> : A date and time parse and format library for Zig.</li>
</ul>
Command Line and Argument Parser
<ul>
<li><a>Hejsil/zig-clap</a> : A simple and easy to use command line argument parser library for Zig.</li>
<li><a>MasterQ32/zig-args</a> : Simple-to-use argument parser with struct-based config.</li>
<li><a>jiacai2050/zigcli</a> : A toolkit for building command lines programs in Zig.</li>
<li><a>PrajwalCH/yazap</a> : 🔧 The ultimate Zig library for seamless command line parsing. Effortlessly handles options, subcommands, and custom arguments with ease. <a>prajwalch.github.io/yazap</a></li>
<li><a>00JCIV00/cova</a> : Commands, Options, Values, Arguments. A simple yet robust cross-platform command line argument parsing library for Zig.</li>
<li><a>BanchouBoo/accord</a> : A simple argument parser for Zig.</li>
<li><a>judofyr/parg</a> : Lightweight argument parser for Zig.</li>
<li><a>sam701/zig-cli</a> : A simple package for building command line apps in Zig.</li>
<li><a>GabrieleInvernizzi/zig-prompter</a> : A flexible library for building interactive command line prompts.</li>
<li><a>kioz-wang/zargs</a> : Another Comptime-argparse for Zig.</li>
</ul>
Memory Allocator and Management
<ul>
<li><a>Aandreba/zigrc</a> : Zig reference-counted pointers inspired by Rust's Rc and Arc. <a>aandreba.github.io/zigrc/</a></li>
<li><a>DutchGhost/zorrow</a> : Borrowchecker in Zig. This is a userlevel implementation of borrowchk in Zig.</li>
<li><a>mdsteele/ziegfried</a> : A general-purpose memory allocator for Zig.</li>
<li><a>fengb/zee_alloc</a> : tiny Zig allocator primarily targeting WebAssembly.</li>
<li><a>suirad/Seal</a> : An allocator that wraps another allocator and detects if memory is leaked after usage.</li>
<li><a>rvcas/mpool</a> : A memory pool library written in Zig.</li>
<li><a>nsmryan/zig_sealed_and_compact</a> : Zig functions for memory management.</li>
<li><a>suirad/adma</a> : A general purpose, multithreaded capable slab allocator for Zig.</li>
<li><a>hmusgrave/zcirc</a> : A dynamic circular buffer allocator for zig.</li>
<li><a>dweiller/zig-composable-allocators</a> : Comptime-generic composable allocators.</li>
<li><a>bcrist/Zig-TempAllocator</a> : Arena allocator for interactive programs and simulations.</li>
<li><a>rdunnington/zig-stable-array</a> : Address-stable array with a max size that allocates directly from virtual memory.</li>
<li><a>dweiller/zimalloc</a> : zimalloc is general purpose allocator for Zig, inspired by <a>mimalloc</a>.</li>
<li><a>Hejsil/zig-gc</a> :A super simple mark-and-sweep garbage collector written in Zig.</li>
</ul>
Asynchronous Runtime
<ul>
<li><a>mitchellh/libxev</a> : libxev is a cross-platform, high-performance event loop that provides abstractions for non-blocking IO, timers, events, and more and works on Linux (io_uring or epoll), macOS (kqueue), and Wasm + WASI. Available as both a Zig and C API.</li>
<li><a>kprotty/zap</a> : An asynchronous runtime with a focus on performance and resource efficiency.</li>
<li><a>lithdew/pike</a> : Async I/O for Zig.</li>
</ul>
Multithreading
<ul>
<li><a>g41797/mailbox</a> : mailbox is convenient inter-thread communication mechanizm.</li>
</ul>
Embedded Development
<ul>
<li><a>ZigEmbeddedGroup/microzig</a> : Unified abstraction layer and HAL for several microcontrollers.</li>
<li><a>ZigEmbeddedGroup/stmicro-stm32</a> : HAL for stm32 (STMicro) devices.</li>
<li><a>ZigEmbeddedGroup/raspberrypi-rp2040</a> : MicroZig Hardware Support Package for Raspberry Pi RP2040.</li>
<li><a>ZigEmbeddedGroup/regz</a> : Generate zig code from ATDF or SVD files for microcontrollers.</li>
<li><a>nmeum/zig-riscv-embedded</a> : Experimental Zig-based CoAP node for the HiFive1 RISC-V board.</li>
<li><a>lupyuen/pinephone-nuttx</a> : Apache NuttX RTOS for PinePhone. Apache NuttX is a lightweight Real-Time Operating System (RTOS) that runs on PINE64 PinePhone. <a>lupyuen.github.io/articles/what</a></li>
<li><a>lupyuen/zig-bl602-nuttx</a> : Zig on RISC-V BL602 with Apache NuttX RTOS and LoRaWAN.</li>
<li><a>leecannon/zig-sbi</a> : Zig wrapper around the RISC-V SBI specification.</li>
<li><a>eastonman/zesty-core</a> : A RISC-V OS written in Zig.</li>
<li><a>kivikakk/daintree</a> : ARMv8-A/RISC-V kernel (with UEFI bootloader). An operating system plus a UEFI bootloader, all written in Zig.</li>
<li><a>markfirmware/zig-bare-metal-microbit</a> : Bare metal microbit program written in zig.</li>
<li><a>markfirmware/zig-bare-metal-raspberry-pi</a> : Bare metal raspberry pi program written in zig.</li>
<li><a>tralamazza/embedded_zig</a> : minimal Zig embedded ARM example (STM32F103 blue pill).</li>
<li><a>yvt/zig-armv8m-test</a> : Example Zig-based app for Armv8-M + TrustZone.</li>
<li><a>hspak/brightnessztl</a> : A CLI to control device backlight.</li>
<li><a>justinbalexander/svd2zig</a> : Convert System View Description (svd) files to Zig headers for baremetal development.</li>
<li><a>mqttiotstuff/iotmonitor</a> : PainLess, Monitor and State server for iot mqtt devices, and software agents. This daemon permit to maintain the execution of constellations of mqtt devices and associated agents.</li>
<li><a>Elara6331/zig-gpio</a>: A Zig library for controlling GPIO lines on Linux systems.</li>
<li><a>ringtailsoftware/zeptolibc</a> : Essential libc functions in Zig for freestanding targets</li>
</ul>
General Operating System
<ul>
<li><a>ZystemOS/Pluto</a> : An x86 kernel written in Zig.</li>
<li><a>davidgm94/birth</a> : Rise: an attempt to write a better operating system.</li>
<li><a>iguessthislldo/georgios</a> : Hobby Operating System.</li>
<li><a>rafaelbreno/zig-os</a> : A simple OS written in Zig following Philipp Oppermann's posts <a>Writing an OS in Rust</a>.</li>
<li><a>jzck/kernel-zig</a> : 💾 hobby x86 kernel zig.</li>
<li><a>andrewrk/HellOS</a> : "hello world" x86 kernel example.</li>
<li><a>marlersoft/zigwin32</a> : A complete autogenerated set of Zig bindings for the Win32 API.</li>
<li><a>a1393323447/zcore-os</a> : A RISC-V OS written in Zig. rCore-OS translated in Zig language.</li>
<li><a>b0bleet/zvisor</a> : Zvisor is an open-source hypervisor written in the Zig programming language, which provides a modern and efficient approach to systems programming.</li>
<li><a>TalonFloof/zorroOS</a> : Hobby operating system written in Zig.</li>
<li><a>CascadeOS/CascadeOS</a> : General purpose operating system targeting standard desktops and laptops.</li>
<li><a>AndreaOrru/zen</a> : Experimental operating system written in Zig.</li>
<li><a>DorianXGH/Lukarnel</a> : A microkernel in zig with rust microservices.</li>
<li><a>liampwll/zig-efi-os</a> : zig-efi-os.</li>
<li><a>nrdmn/uefi-examples</a> UEFI examples in Zig.</li>
<li><a>nrdmn/uefi-paint</a> : UEFI-bootable touch paint app.</li>
<li><a>sjdh02/trOS</a> : tiny aarch64 baremetal OS thingy.</li>
<li><a>ZeeBoppityZagZiggity/ZBZZ.OS</a> : An operating system built with RISCV and Zig.</li>
<li><a>pbui-project/pbui-main</a> : The PBUI (POSIX-compliant BSD/Linux Userland Implementation) project is a a free and open source project intended to implement some standard library toolsets in the Zig programming language.</li>
<li><a>momumi/x86-zig</a> : library for assembling x86 in zig (WIP).</li>
<li><a>javiorfo/zig-syslinfo</a> : Linux sysinfo Zig library.</li>
</ul>
Robot Operating System
<ul>
<li><a>jacobperron/rclzig</a> : ROS 2 client library in Zig.</li>
<li><a>luickk/MinimalRoboticsPlatform</a> : MRP is a minimal microkernel that supports the most fundamental robotic domains. It's thought for highly integrated robotics development.</li>
</ul>
Compilers and Interpreters
<ul>
<li><a>Aro</a> : Aro. A C compiler with the goal of providing fast compilation and low memory usage with good diagnostics.</li>
<li><a>buzz</a>: A small/lightweight statically typed scripting language.</li>
<li><a>fubark/cyber</a> : Fast and concurrent scripting.</li>
<li><a>squeek502/zua</a> : An implementation of Lua 5.1 in Zig, for learning purposes.</li>
<li><a>Vexu/bog</a> : Small, strongly typed, embeddable language.</li>
<li><a>fury</a> : Fury, a gradual, safe systems language.</li>
</ul>
FFI Bindings
<ul>
<li><a>natecraddock/ziglua</a> : Zig bindings for the Lua C API.</li>
<li><a>sackosoft/zig-luajit</a> : Zig bindings for the LuaJIT C API.</li>
<li><a>mitchellh/zig-objc</a> : Objective-C runtime bindings for Zig (Zig calling ObjC).</li>
<li><a>fulcrum-so/ziggy-pydust</a> : A toolkit for building Python extensions in Zig. <a>pydust.fulcrum.so/</a></li>
<li><a>katafrakt/zig-ruby</a> : This repo contains an experiment of building a Ruby extension with Zig programming language. It implements a slightly altered version of 100 doors from Rosetta Code.</li>
<li><a>ExpidusOS/zig-flutter</a> : Flutter w/ Zig.</li>
<li><a>lassade/c2z</a> : C++ to Zig bindings and transpiler.</li>
<li><a>floooh/sokol-zig</a> : Zig bindings for the sokol headers</li>
<li><a>jiacai2050/zig-curl</a> : Zig bindings for libcurl</li>
<li><a>jiacai2050/zig-rocksdb</a> : Zig bindings for RocksDB.</li>
<li><a>jiacai2050/zig-jemalloc</a> : Zig allocator baked by jemalloc</li>
<li><a>arshidkv12/zig-php</a> : Write PHP extension in Zig</li>
<li><a>OnlyF0uR/pqc-zig</a> : Zig bindings and abstractions for <a>PQClean</a>, post-quantum cryptography.</li>
</ul>
Zigged Project
<ul>
<li><a>libz</a>: zlib with the build system replaced by zig</li>
<li><a>libmp3lame</a>: libmp3lame with the build system replaced by zig</li>
<li><a>libvorbis</a>: libvorbis with the build system replaced by zig</li>
<li><a>libogg</a>: libogg with the build system replaced by zig</li>
<li><a>nasm</a>: nasm with the build system replaced by zig</li>
<li><a>ffmpeg</a>: ffmpeg with the build system replaced by zig</li>
<li><a>libebur128</a>: libebur128 with the build system replaced by zig</li>
<li><a>pulseaudio</a>: pulseaudio with the build system replaced by zig</li>
<li><a>libchromaprint</a>: chromaprint with the build system replaced by zig</li>
<li><a>raylib</a>: A simple and easy-to-use library to enjoy videogames programming</li>
<li><a>openssl</a>: TLS/SSL and crypto library (uses Zig Build)</li>
<li><a>wolfssl</a>: WolfSSL library - Using Zig Build</li>
<li><a>fmt</a>: A modern formatting library (uses zig build-system)</li>
<li><a>boost unordered</a>: Boost.org unordered module (uses zig build)</li>
<li><a>boost async</a>: Coroutines for C++20 & asio (uses zig build for testing)</li>
<li><a>json</a>: JSON for Modern C++ (uses zig build-system)</li>
<li><a>context</a>: <code>boost.context</code> library using zig build</li>
<li><a>fiber</a>: userland threads uses zig build</li>
<li><a>outcome</a>: Provides very lightweight outcome<T> and result<T> (non-Boost edition) (uses zig build-system)</li>
<li><a>Standalone</a>: Asio standalone C++ HTTP/S Server (uses zig build-system)</li>
<li><a>asio</a>: Asio C++ Library (uses zig build-system)</li>
<li><a>observable</a>: : Unique-ownership smart pointers with observable lifetime.</li>
<li><a>Catch2</a>: A modern, C++-native, test framework for unit-tests, TDD and BDD - using C++14, C++17 and later (C++11 support is in v2.x branch, and C++03 on the Catch1.x branch) - uses zig build-system</li>
<li><a>cppfront</a>: Build Cppfront w/ zig build</li>
<li><a>hana</a>: Your standard library for metaprogramming</li>
<li><a>intrusive</a>: Boost.org intrusive module</li>
<li><a>range</a>: Range library for C++14/17/20, basis for C++20's std::ranges</li>
<li><a>zig-libxml2</a>: libxml2 built using Zig build system</li>
<li><a>benchmark</a>: A microbenchmark support library
First post at <a>here</a>.</li>
<li><a>libffi</a>: libffi with a Zig build script.</li>
</ul>
GPU Computing
<ul>
<li><a>gwenzek/cudaz</a> : Toy Cuda wrapper for Zig.</li>
<li><a>lennyerik/cutransform</a> : CUDA kernels in any language supported by LLVM.</li>
<li><a>Snektron/vulkan-zig</a> : Vulkan binding generator for Zig.</li>
<li><a>hexops/mach-gpu</a> : mach/gpu provides a truly cross-platform graphics API for Zig (desktop, mobile, and web) with unified low-level graphics & compute backed by Vulkan, Metal, D3D12, and OpenGL (as a best-effort fallback.)</li>
<li><a>hexops/mach-gpu-dawn</a> : Google's Dawn WebGPU implementation, cross-compiled with Zig into a single static library.</li>
<li><a>ckrowland/simulations</a> : GPU accelerated visual simulations.</li>
<li><a>Avokadoen/zig_vulkan</a> : Voxel ray tracing using Vulkan compute.</li>
<li><a>akhildevelops/cudaz</a> : Cuda wrapper for interacting with GPUs in zig.</li>
<li><a>e253/zig-ocl</a> : Static Zig Build of the OpenCL ICD Loader from Khronos Group.</li>
</ul>
Scientific Computation
<ul>
<li>
Linear Algebra
</li>
<li>
<a>kooparse/zalgebra</a> : Linear algebra library for games and real-time graphics.
</li>
<li><a>ziglibs/zlm</a> : Zig linear mathematics.</li>
<li><a>omaraaa/VecFns</a> : Automatic Vector Math Functions In Zig.</li>
<li><a>Laremere/alg</a> : Algebra for Zig.</li>
<li><a>BanchouBoo/algae</a> : Zig math library focused on game development.</li>
<li><a>JungerBoyo/zmath</a> : simple linear algebra library written in zig.</li>
<li><a>pblischak/zprob</a> : A Zig Library for Probability Distributions.</li>
</ul>
Machine Learning
<ul>
<li>
Machine Learning Framework
</li>
<li>
<a>ggml</a> : Tensor library for machine learning. Written in C.
</li>
<li><a>ggml-zig</a> : <a>ggml: Tensor library for machine learning</a> written in zig.</li>
<li><a>rockcarry/ffcnn</a> : ffcnn is a cnn neural network inference framework, written in 600 lines C language.</li>
<li><a>xboot/libonnx</a> : A lightweight, portable pure C99 onnx inference engine for embedded devices with hardware acceleration support.</li>
<li><a>kraiskil/onnx2c</a> : Open Neural Network Exchange to C compiler. Onnx2c is a <a>ONNX</a> to C compiler. It will read an ONNX file, and generate C code to be included in your project. Onnx2c's target is "Tiny ML", meaning running the inference on microcontrollers.</li>
<li><a>candrewlee14/zgml</a> : Tensor library for machine learning, inspired by ggml.</li>
<li><a>maihd/zten</a> : Tensor library for Zig, based on ggml.</li>
<li><a>andrewCodeDev/ZEIN</a> : Zig-based implementation of tensors.</li>
<li><a>recursiveGecko/onnxruntime.zig</a> : Experimental Zig wrapper for ONNX Runtime with examples (Silero VAD, NSNet2).</li>
<li><a>Gonzih/onnx-worker.zig</a> : onnx-worker.zig</li>
<li><a>zml</a> : zml is a machine learning framework</li>
<li><a>Zigrad</a> : A deep learning framework built on an autograd engine with high level abstractions and low level control. Trains neural networks 2.5x faster than Pytorch on Apple Silicon and 1.5x faster on CPU.</li>
<li>
<a>SilasMarvin/dnns from scratch in zig</a> : a very simple implementation of deep neural networks written in the Zig programming language. https://silasmarvin.dev/dnns-from-scratch-in-zig
</li>
<li>
Large Language Model
</li>
<li>
<a>ollama-zig</a> : Ollama Zig library.
</li>
<li><a>llama.cpp</a> : Inference of <a>LLaMA</a> model in pure C/C++.</li>
<li><a>cgbur/llama2.zig</a> : Inference Llama 2 in one file of pure Zig.</li>
<li><a>clebert/llama2.zig</a> : Inference Llama 2 in pure Zig.</li>
<li><a>renerocksai/gpt4all.zig</a> : ZIG build for a terminal-based chat client for an assistant-style large language model with ~800k GPT-3.5-Turbo Generations based on LLaMa.</li>
<li><a>EugenHotaj/zig_gpt2</a> : Neural Network Inference Engine in Zig. GPT2 inference engine written in Zig. The inference engine can run <a>NanoGPT</a>.</li>
</ul>
Database
<ul>
<li><a>tigerbeetle</a> : The distributed financial accounting database designed for mission critical safety and performance. <a>tigerbeetle.com</a></li>
<li><a>vrischmann/zig-sqlite</a> : zig-sqlite is a small wrapper around sqlite's C API, making it easier to use with Zig.</li>
<li><a>leroycep/sqlite-zig</a> : This repository has zig bindings for sqlite. It tries to make the sqlite c API more ziggish.</li>
<li><a>nDimensional/zig-sqlite</a> : Simple, low-level, explicitly-typed SQLite bindings for Zig.</li>
<li><a>mjoerussell/zdb</a> : A library for interacting with databases in Zig.</li>
<li><a>kristoff-it/redis-cuckoofilter</a> : Hashing-function agnostic Cuckoo filters for Redis.</li>
<li><a>kristoff-it/zig-okredis</a> : Zero-allocation Client for Redis 6+.</li>
<li><a>vrischmann/zig-cassandra</a> : Client for Cassandra 2.1+</li>
<li><a>speed2exe/myzql</a> : MySQL and MariaDB driver in native Zig</li>
<li><a>karlseguin/pg.zig</a> : Native PostgreSQL driver / client for Zig</li>
<li><a>karlseguin/zuckdb.zig</a> : A DuckDB driver for Zig</li>
</ul>
Sensor and Communication Interface
<ul>
<li><a>MasterQ32/zig-network</a> : A smallest-common-subset of socket functions for crossplatform networking, TCP & UDP.</li>
<li><a>ZigEmbeddedGroup/serial</a> : Serial port configuration library for Zig.</li>
<li><a>tetsu-koba/v4l2capture</a> : v4l2 video capturer written in Zig.</li>
<li><a>kdchambers/reel</a> : Screen capture software for Linux / Wayland.</li>
<li><a>ringtailsoftware/commy</a> : Serial terminal monitor for Linux, Mac and Windows</li>
</ul>
Finite State Machine
<ul>
<li><a>cryptocode/zigfsm</a> : zigfsm is a <a>finite state machine</a> library for Zig.</li>
</ul>
Game Field
<ul>
<li><a>Mach</a> : Mach is a game engine & graphics toolkit for the future. machengine.org.</li>
<li><a>zig-gamedev/zig-gamedev</a> : Building game development ecosystem for @ziglang!</li>
<li><a>ryupold/zecsi</a> : Small game framework made with Zig utilizing the awesome raylib.</li>
<li><a>wendigojaeger/ZigGBA</a> : Work in progress SDK for creating Game Boy Advance games using Zig programming language.</li>
<li><a>zPSP-Dev/Zig-PSP</a> : A project to bring the Zig Programming Language to the Sony PlayStation Portable!</li>
<li><a>prime31/zig-gamekit</a> : Companion repo for zig-renderkit for making 2D games.</li>
<li><a>Jack-Ji/jok</a> : A minimal 2d/3d game framework for zig.</li>
<li><a>star-tek-mb/Paradise</a> : Paradise is a wasm first game engine written in zig.</li>
<li><a>zkburke/quanta</a> : A game engine/framework written in and for zig.</li>
<li><a>andrewrk/tetris</a> : A simple tetris clone written in zig programming language. <a>www.youtube.com/watch?v=AiintPutWrE</a></li>
<li><a>DanB91/Zig-Playdate-Template</a> : Starter code for a Playdate program written in Zig.</li>
<li><a>foxnne/aftersun</a> : Top-down 2D RPG.</li>
<li><a>4imothy/termy48</a> : A 2048 game to run in terminal.</li>
<li><a>andrewrk/clashos</a> multiplayer arcade game for bare metal Raspberry Pi 3 B+.</li>
<li><a>MasterQ32/Ziguana-Game-System</a> A retro-style gaming console running on bare x86 metal written in Zig.</li>
<li><a>Srekel/zag</a> : Game dev project written in Zig and C.</li>
<li><a>TM35-Metronome/metronome</a> : A set of tools for modifying and randomizing Pokémon games. <a>tm35-metronome.github.io/</a></li>
<li><a>Akuli/curses-minesweeper</a> : Minesweeper game written in curses with zig.</li>
<li><a>thejoshwolfe/legend-of-swarkland</a> : Turn-based action fantasy puzzle game inspired by NetHack and Crypt of the Necrodancer. <a>wolfesoftware.com/legend-of-swarkland/</a></li>
<li><a>emekoi/ziglet</a> : a small zig game library.</li>
<li><a>kristianhasselknippe/zig-game-engine</a> : Learning zig through game engine</li>
<li><a>TM35-Metronome/tm35-nds</a> : A library for working with Nintendo DS roms.</li>
<li><a>fabioarnold/snake-zig</a> : A simple snake game written in the Zig programming language using OpenGL 2.</li>
<li><a>Stenodyon/blink</a> : A game about building logic with lasers.</li>
<li><a>tiehuis/zstack</a> : Line-race tetris mode in Zig.</li>
<li><a>godot-zig/godot-zig</a> : Zig bindings for Godot 4.</li>
<li><a>Avokadoen/ecez</a> : An archetype based ECS library written in pure zig.</li>
<li><a>nitanmarcel/ScriptHookVZig</a> : Library to write GTA V mods in Zig.</li>
<li><a>PixelGuys/Cubyz</a> : Voxel sandbox game with a large render distance, procedurally generated content and some cool graphical effects.</li>
<li><a>deckarep/dungeon-rush</a> : An SDL snake style game ported to Zig. Originally written in C.</li>
<li><a>ringtailsoftware/zigtris</a> : Zigtris, a terminal tetris</li>
<li><a>ringtailsoftware/zoridor</a> : Zoridor, a Quoridor game for terminal and web with a machine opponent</li>
<li><a>ringtailsoftware/zero-jetpack</a> : Zero-Jetpack a web game about Ziguanas carrying eggs</li>
<li><a>six519/YieArKUNGFUZig</a> : A Yie Ar Kung-Fu clone created in Zig with raylib</li>
</ul>
Emulators
<ul>
<li><a>Ronsor/riscv-zig</a> : A RISC-V emulator written in Zig.</li>
<li><a>leecannon/zriscv</a> : RISC-V emulator in Zig.</li>
<li><a>jtgoen/zig-chip-8</a> : Zig Implementation of a Chip-8 Emulator.</li>
<li><a>paoda/zba</a> : Game Boy Advance Emulator. Yes, I'm awful with project names.</li>
<li><a>fengb/fundude</a> Gameboy emulator: Zig -> wasm.</li>
<li><a>GrooveStomp/chip8-zig</a> : A CHIP-8 emulator written in Zig.</li>
<li><a>isaachier/gbemu</a> : Zig Game Boy emulator.</li>
<li><a>tiehuis/zig-gameboy</a> : A gameboy emulator in zig.</li>
<li><a>emekoi/c8</a> : chip 8 emulator in zig.</li>
<li><a>ringtailsoftware/zig-minirv32</a> : Zig RISC-V emulator with Linux and baremetal examples</li>
</ul>
Encryption
<ul>
<li><a>gernest/base32</a> : base32 encoding/decoding for ziglang</li>
<li><a>deatil/zpem</a> : A pem parse and encode library for Zig.</li>
<li><a>deatil/zig-md2</a> : A MD2 hash function library for Zig.</li>
<li><a>deatil/zig-md4</a> : A MD4 hash function library for Zig.</li>
<li><a>deatil/zig-sm3</a> : A SM3 hash function library for Zig.</li>
</ul>
Network
<ul>
<li><a>Vexu/routez</a> : Http server for Zig. <a>routez.vexu.eu</a></li>
<li><a>Vexu/zuri</a> : URI parser for Zig.</li>
<li><a>karlseguin/http.zig</a> : An HTTP/1.1 server for zig.</li>
<li><a>ducdetronquito/h11</a> : I/O-free HTTP/1.1 implementation inspired by hyper/h11.</li>
<li><a>lun-4/zigdig</a> : naive dns client library in zig.</li>
<li><a>connectFree/ZigZag</a> : Noise Framework implementation in Zig Language for use in EVER/IP and WireGuard.</li>
<li><a>euantorano/ip.zig</a> : A Zig library for working with IP Addresses.</li>
<li><a>lun-4/ziget</a> : simple wget in zig without libc.</li>
<li><a>marler8997/netpunch</a> : Punch Protocol.</li>
<li><a>mstroecker/zig-robotstxt</a> : Lightweight docker image for serving a disallow robots.txt file using the zig programming language.</li>
<li><a>remeh/statsd-zig</a> : Basic DogStatsD UDP/UDS server supporting gauges and counters and sending these metrics to Datadog.</li>
<li><a>gernest/url</a> : This is RFC 3986 compliant url parser for zig.</li>
<li><a>ringtailsoftware/misshod</a> : Experimental minimalist SSH client and server in zig</li>
<li><a>g41797/beanstalkz</a> : Thread-safe client library for <a>beanstalkd</a> - queue for background job processing.</li>
<li><a>vascocosta/zircon</a> : A simple IRC library written in Zig.</li>
<li><a>tardy-org/zzz</a> : A framework for writing performant and reliable networked services in Zig. Supports HTTP and HTTPS.</li>
</ul>
Web Framework
<ul>
<li><a>oven-sh/bun</a> : Incredibly fast JavaScript runtime, bundler, transpiler and package manager – all in one.</li>
<li><a>zigzap/zap</a> : ⚡zap⚡ - blazingly fast web backends in zig.</li>
<li><a>frmdstryr/zhp</a> : frmdstryr/zhp.</li>
<li><a>karlseguin/websocket.zig</a> : A websocket implementation for zig.</li>
<li><a>nikneym/ws</a> : WebSocket library for Zig ⚡</li>
<li><a>kivikakk/htmlentities.zig</a> : HTML entity data for Zig.</li>
<li><a>shritesh/zigfmt-web</a> : zig fmt on the web.</li>
<li><a>leroycep/zig-jwt</a> : JSON Web Tokens for Zig.</li>
<li><a>zon-dev/zinc</a> : Zinc is a web framework written in pure Zig with a focus on high performance, usability, security, and extensibility.</li>
<li><a>cztomsik/tokamak</a> : Web framework that leverages dependency injection for clean, modular application development.</li>
<li><a>jetzig-framework/jetzig</a> : Jetzig is a web framework written in Zig.</li>
<li><a>by-nir/aws-lambda-zig</a> : Super-fast AWS Lambda runtime for Zig.</li>
<li><a>deatil/zig-totp</a> : A TOTP(Time-based One-Time Password) library for zig.</li>
<li><a>deatil/zig-jwt</a> : A JWT(JSON Web Token) library for zig.</li>
<li><a>kristoff-it/zine</a> : Static Site Generator written in Zig.</li>
<li><a>uzyn/passcay</a> : Secure Passkey authentication (WebAuthn) library for Zig.</li>
</ul>
Web3 Framework
<ul>
<li><a>Syndica/sig</a> : a Solana Zig RPC Client implementation.</li>
<li><a>lithdew/rheia</a> : A blockchain written in Zig.</li>
<li><a>zen-eth/multiformats-zig</a> : This is the zig implementation of the multiformats <a>spec</a>.</li>
<li><a>zen-eth/zig-libp2p</a> : Zig implementation of <a>libp2p</a>, a modular network stack that allows you to build your own peer-to-peer applications.</li>
<li><a>EclesioMeloJunior/libp2p-zig</a> : A <a>libp2p</a> written in Zig.</li>
<li><a>Raiden1411/zabi</a> : Zabi aims to add support for interacting with ethereum or any compatible EVM based chain.</li>
<li><a>gballet/zevem/</a> : Ethereum Virtual Machine written in Zig.</li>
<li><a>blockblaz/ssz.zig</a> : A Zig implementation of the <a>SSZ serialization protocol</a>.</li>
<li><a>blockblaz/zeam</a> : A <a>Beam Chain</a> written in Zig.</li>
<li><a>jsign/verkle-crypto</a> : Cryptography for Ethereum Verkle Trees.</li>
<li><a>Ultra-Code/recblock</a> : Blockchain for a record management and money transfer system.</li>
<li><a>keep-starknet-strange/ziggy-starkdust</a> : A Zig implementation of Cairo VM for Cairo, the STARK powered provable language.</li>
<li><a>iskyd/walle</a> : A Bitcoin Wallet written in Zig.</li>
</ul>
WebAssembly
<ul>
<li><a>zig-wasi</a> : Minimal WASI Interpreter.</li>
<li><a>zware</a> : Zig WebAssembly Runtime Engine. zware is a library for executing WebAssembly embedded in <a>Zig</a> programs.</li>
<li><a>wazm</a> : wazm — Web Assembly Zig Machine.</li>
<li><a>zig-wasm-dom</a> : Zig + WebAssembly + JS + DOM.</li>
<li><a>mitchellh/zig-js</a> : Access the JS host environment from Zig compiled to WebAssembly.</li>
<li><a>zigwasm/wasm-zig</a> : Common Wasm runtime binding to C API.</li>
<li><a>zigwasm/wasmtime-zig</a> : Zig embedding of Wasmtime.</li>
<li><a>sleibrock/zigtoys</a> : All about Zig + WASM and seeing what we can do. <a>sleibrock.github.io/zigtoys/</a></li>
<li><a>andrewrk/lua-in-the-browser</a> : using zig to build lua for webassembly.</li>
<li><a>meheleventyone/zig-wasm-test</a> : A minimal Web Assembly example using Zig's build system.</li>
<li><a>thi.ng/wasm-api</a> : Modular, extensible API bridge and infrastructure for hybrid JS & WebAssembly projects.</li>
<li><a>oltdaniel/zig-js-interplay</a> : Seamless integration of Zig and JavaScript in WebAssembly.</li>
<li><a>ringtailsoftware/zig-wasm-audio-framebuffer</a> : Examples of integrating Zig and Wasm (and C) for audio and graphics on the web (including DOOM)</li>
</ul>
Performance Benchmark
<ul>
<li><a>zackradisic/rust-vs-zig</a> : This is an experiment to evaluate Rust vs. Zig by writing a bytecode interpreter with GC in both languages and comparing them.</li>
<li><a>lucascompython/zigXrustXc</a> : Performance of Zig vs Rust vs C.</li>
<li><a>CoalNova/BasicCompare</a> : A basic comparative analysis of C, C++, Rust, and Zig.</li>
<li><a>ziglang/gotta-go-fast</a> : Performance Tracking for Zig.</li>
<li><a>hendriknielaender/zBench</a> : Simple benchmarking library.</li>
<li><a>andrewrk/poop</a> : CLI Performance Observer written in Zig.</li>
</ul>
Graphics Library
<ul>
<li><a>hexops/mach-glfw</a> : Ziggified GLFW bindings with 100% API coverage, zero-fuss installation, cross compilation, and more.</li>
<li><a>ziglibs/zgl</a> : Zig OpenGL Wrapper.</li>
<li><a>MasterQ32/SDL.zig</a> : A shallow wrapper around SDL that provides object API and error handling.</li>
<li><a>andrewrk/SDL</a> : SDL with the build system replaced by Zig. <a>libsdl.org</a></li>
<li><a>MasterQ32/zig-opengl</a> : OpenGL binding generator based on the opengl registry.</li>
<li><a>MasterQ32/zero-graphics</a> : Application framework based on OpenGL ES 2.0. Runs on desktop machines, Android phones and the web.</li>
<li><a>JonSnowbd/ZT</a> : A zig based Imgui Application framework.</li>
<li><a>craftlinks/zig_learn_opengl</a> : Follow the Learn-OpenGL book using Zig.</li>
<li><a>ashpil/moonshine</a> : Moonshine: A general purpose ray traced renderer built with Zig + Vulkan.</li>
<li><a>fabioarnold/nanovg-zig</a> : <a>NanoVG</a> - Zig Version. A small anti-aliased hardware-accelerated vector graphics library. <a>fabioarnold.github.io/nanovg-zig/</a></li>
<li><a>fubark/cosmic</a> : A platform for computing and creating applications. <a>cosmic.ooo</a></li>
<li><a>renerocksai/slides</a> : This project is both a case study and also marks my first steps in the programming language Zig, towards creating a simple but powerful <a>imgui</a> based, OpenGL-rendered slideshow app in Zig.</li>
<li><a>TinyVG/sdk</a> : TinyVG software development kit. <a>tinyvg.tech/</a></li>
<li><a>andrewrk/zig-vulkan-triangle</a> : simple triangle displayed using vulkan, glfw, and zig.</li>
<li><a>cshenton/learnopengl</a> : Zig Learn OpenGL.</li>
<li><a>river</a> : A dynamic tiling Wayland compositor.</li>
<li><a>Nelarius/weekend-raytracer-zig</a> : A Zig implementation of the "Ray Tracing in One Weekend" book.</li>
<li><a>SpexGuy/Zig-Gltf-Display</a> : A program that displays glTF files using Vulkan, written in Zig.</li>
<li><a>tiehuis/zig-raytrace</a> : simple raytracer in zig.</li>
<li><a>tiehuis/zig-sdl2</a> : SDL2 bindings for Zig.</li>
<li><a>winksaville/zig-3d-soft-engine</a> : An attempt to create a 3D engine in software using zig.</li>
</ul>
GUI
<ul>
<li><a>Capy</a> : 💻Build one codebase and get native UI on Windows, Linux and Web. <a>capy-ui.org</a></li>
<li><a>david-vanderson/dvui</a> : Easy to Integrate Immediate Mode GUI for Zig.</li>
<li><a>kassane/qml_zig</a> : QML bindings for the Zig programming language.</li>
<li><a>MoAlyousef/zfltk</a> : Zig bindings for the FLTK gui library.</li>
<li><a>Aransentin/ZWL</a> : A Zig Windowing Library.</li>
<li><a>batiati/IUPforZig</a> : IUP (Portable User Interface Toolkit) bindings for the Zig language.</li>
<li><a>donpdonp/zootdeck</a> : Fediverse GTK Desktop Reader. <a>donpdonp.github.io/zootdeck/</a></li>
<li><a>lupyuen/zig-lvgl-nuttx</a> : Zig LVGL Touchscreen App on Apache NuttX RTOS.</li>
<li><a>lupyuen/pinephone-lvgl-zig</a> : LVGL for PinePhone (and WebAssembly) with Zig and Apache NuttX RTOS. <a>lupyuen.github.io/articles/lvgl2</a></li>
<li><a>ziglibs/positron</a> : A web renderer frontend for zig applications.</li>
<li><a>webui-dev/zig-webui</a> : Use any web browser or WebView as GUI, with your preferred language in the backend and HTML5 in the frontend, all in a lightweight portable lib.</li>
<li><a>star-tek-mb/zig-tray</a> : Create tray applications with zig.</li>
</ul>
Misc
<ul>
<li><a>BraedonWooding/Lazy-Zig</a> : Linq in Zig.</li>
<li><a>DutchGhost/maybeuninit</a> MaybeUninit in Zig.</li>
<li><a>hspak/geteltorito-zig</a> : geteltorito re-write in Zig.</li>
<li><a>NilsIrl/dockerc</a>: container image to single executable compiler.</li>
<li><a>nrdmn/ilo_license_key</a> : iLO license key library.</li>
<li><a>shepherdjerred/macos-cross-compiler</a> : Compile binaries for macOS on Linux.</li>
<li><a>tw4452852/zbpf</a> : Writing eBPF in Zig</li>
<li><a>rockorager/zzdoc</a> : scdoc-compatible manpage compiler for use in build.zig</li>
<li><a>rockorager/libvaxis</a> : Modern TUI library written in zig</li>
<li><a>Avokadoen/ecez_vulkan</a> : A scene editor built on <a>ecez</a> and Vulkan</li>
<li><a>attron/astroz</a> : Spacecraft and Astronomical Toolkit</li>
<li><a>Zigistry/Zigistry</a>: A place where you can find all the libraries that suit your Zig lang needs.</li>
<li><a>freref/fancy-cat</a>: PDF reader inside the terminal.</li>
<li><a>ghostty</a>: Modern terminal emulator written in zig.</li>
<li><a>zerotech-studio/zack</a> : Backtesting engine for trading strategies, written in Zig.</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/4644332?v=4 | karmem | inkeliz/karmem | 2022-05-11T16:13:34Z | Karmem is a fast binary serialization format, faster than Google Flatbuffers and optimized for TinyGo and WASM. | master | 38 | 666 | 29 | 666 | https://api.github.com/repos/inkeliz/karmem/tags | BSD-3-Clause | [
"assemblyscript",
"c",
"csharp",
"dotnet",
"dotnet7",
"go",
"golang",
"odin-lang",
"random-access",
"serialization",
"swift",
"webassembly",
"zig"
] | 8,232 | false | 2025-05-21T06:43:08Z | false | false | unknown | github | [] | KARMEM
<a></a> <a></a> <a></a>
Karmem is a fast binary serialization format. The priority of Karmem is to be
easy to use while been fast as possible. It's optimized to take Golang and
TinyGo's maximum performance and is efficient for repeatable reads, reading
different content of the same type. Karmem demonstrates to be ten times faster
than Google Flatbuffers, with the additional overhead of bounds-checking
included.
<blockquote>
⚠️ Karmem still under development, the API is not stable. However, serialization-format itself is unlike to change and
should remain backward compatible with older versions.
</blockquote>
Contents
<ul>
<li><a>🧐 Motivation</a></li>
<li><a>🧠 Usage</a></li>
<li><a>🏃 Benchmark</a></li>
<li><a>🌎 Languages</a></li>
<li><a>📙 Schema</a><ul>
<li>Example</li>
<li>Types</li>
<li>Structs</li>
<li>Enum</li>
</ul>
</li>
<li><a>🛠️ Generator</a></li>
<li><a>🔒 Security</a></li>
</ul>
Motivation
Karmem was create to solve one single issue: make easy to transfer data between WebAssembly host and guest. While still
portable for non-WebAssembly languages. We are experimenting with an "event-command pattern" between wasm-host and
wasm-guest in one project, but sharing data is very expensive, and FFI calls are not cheap either. Karmem encodes once
and shares the same content with multiple guests, regardless of the language, making it very efficient. Also, even using
Object-API to decode, it's fast enough, and Karmem was designed to take advantage of that pattern, avoid allocations,
and re-use the same struct for multiple data.
Why not use <a>Witx</a>? It is good project and aimed to WASM, however it seems
more complex and defines not just data-structure, but functions, which I'm trying to avoid. Also, it is not intended to
be portable to non-wasm. Why not use <a>Flatbuffers</a>? We tried, but it's not fast
enough and also causes panics due to the lack of bound-checking. Why not use <a>Cap'n'Proto</a>? It's
a good alternative but lacks implementation for Zig and AssemblyScript, which is top-priority, it also has more
allocations and the generated API is harder to use, compared than Karmem.
Usage
That is a small example of how use Karmem.
Schema
<code>``go
karmem app @packed(true) @golang.package(</code>app`);
enum SocialNetwork uint8 { Unknown; Facebook; Instagram; Twitter; TikTok; }
struct ProfileData table {
Network SocialNetwork;
Username []char;
ID uint64;
}
struct Profile inline {
Data ProfileData;
}
struct AccountData table {
ID uint64;
Email []char;
Profiles []Profile;
}
```
Generate the code using <code>go run karmem.org/cmd/karmem build --golang -o "km" app.km</code>.
Encoding
In order to encode, use should create an native struct and then encode it.
```go
var writerPool = sync.Pool{New: func() any { return karmem.NewWriter(1024) }}
func main() {
writer := writerPool.Get().(*karmem.Writer)
<code>content := app.AccountData{
ID: 42,
Email: "example@email.com",
Profiles: []app.Profile{
{Data: app.ProfileData{
Network: app.SocialNetworkFacebook,
Username: "inkeliz",
ID: 123,
}},
{Data: app.ProfileData{
Network: app.SocialNetworkFacebook,
Username: "karmem",
ID: 231,
}},
{Data: app.ProfileData{
Network: app.SocialNetworkInstagram,
Username: "inkeliz",
ID: 312,
}},
},
}
if _, err := content.WriteAsRoot(writer); err != nil {
panic(err)
}
encoded := writer.Bytes()
_ = encoded // Do something with encoded data
writer.Reset()
writerPool.Put(writer)
</code>
}
```
Reading
Instead of decoding it to another struct, you can read some fields directly, without any additional decoding. In this
example, we only need the username of each profile.
```go
func decodes(encoded []byte) {
reader := karmem.NewReader(encoded)
account := app.NewAccountDataViewer(reader, 0)
<code>profiles := account.Profiles(reader)
for i := range profiles {
fmt.Println(profiles[i].Data(reader).Username(reader))
}
</code>
}
```
Notice: we use <code>NewAccountDataViewer</code>, any <code>Viewer</code> is just a Viewer, and doesn't copy the backend data. Some
languages (C#, AssemblyScript) uses UTF-16, while Karmem uses UTF-8, in those cases you have some performance
penalty.
Decoding
You can also decode it to an existent struct. In some cases, it's better if you re-use the same struct for multiples
reads.
```go
var accountPool = sync.Pool{New: func() any { return new(app.AccountData) }}
func decodes(encoded []byte) {
account := accountPool.Get().(*app.AccountData)
account.ReadAsRoot(karmem.NewReader(encoded))
<code>profiles := account.Profiles
for i := range profiles {
fmt.Println(profiles[i].Data.Username)
}
accountPool.Put(account)
</code>
}
```
Benchmark
Flatbuffers vs Karmem
Using similar schema with Flatbuffers and Karmem. Karmem is almost 10 times faster than Google Flatbuffers.
<strong>Native (MacOS/ARM64 - M1):</strong>
```
name old time/op new time/op delta
EncodeObjectAPI-8 2.54ms ± 0% 0.51ms ± 0% -79.85% (p=0.008 n=5+5)
DecodeObjectAPI-8 3.57ms ± 0% 0.20ms ± 0% -94.30% (p=0.008 n=5+5)
DecodeSumVec3-8 1.44ms ± 0% 0.16ms ± 0% -88.86% (p=0.008 n=5+5)
name old alloc/op new alloc/op delta
EncodeObjectAPI-8 12.1kB ± 0% 0.0kB -100.00% (p=0.008 n=5+5)
DecodeObjectAPI-8 2.87MB ± 0% 0.00MB -100.00% (p=0.008 n=5+5)
DecodeSumVec3-8 0.00B 0.00B ~ (all equal)
name old allocs/op new allocs/op delta
EncodeObjectAPI-8 1.00k ± 0% 0.00k -100.00% (p=0.008 n=5+5)
DecodeObjectAPI-8 110k ± 0% 0k -100.00% (p=0.008 n=5+5)
DecodeSumVec3-8 0.00 0.00 ~ (all equal)
```
<strong>WebAssembly on Wazero (MacOS/ARM64 - M1):</strong>
```
name old time/op new time/op delta
EncodeObjectAPI-8 17.2ms ± 0% 4.0ms ± 0% -76.51% (p=0.008 n=5+5)
DecodeObjectAPI-8 50.7ms ± 2% 1.9ms ± 0% -96.18% (p=0.008 n=5+5)
DecodeSumVec3-8 5.74ms ± 0% 0.75ms ± 0% -86.87% (p=0.008 n=5+5)
name old alloc/op new alloc/op delta
EncodeObjectAPI-8 3.28kB ± 0% 3.02kB ± 0% -7.80% (p=0.008 n=5+5)
DecodeObjectAPI-8 3.47MB ± 2% 0.02MB ± 0% -99.56% (p=0.008 n=5+5)
DecodeSumVec3-8 1.25kB ± 0% 1.25kB ± 0% ~ (all equal)
name old allocs/op new allocs/op delta
EncodeObjectAPI-8 4.00 ± 0% 4.00 ± 0% ~ (all equal)
DecodeObjectAPI-8 5.00 ± 0% 4.00 ± 0% -20.00% (p=0.008 n=5+5)
DecodeSumVec3-8 5.00 ± 0% 5.00 ± 0% ~ (all equal)
```
Raw-Struct vs Karmem
The performance is nearly the same when comparing reading non-serialized data from a native struct and reading it from a
karmem-serialized data.
<strong>Native (MacOS/ARM64 - M1):</strong>
```
name old time/op new time/op delta
DecodeSumVec3-8 154µs ± 0% 160µs ± 0% +4.36% (p=0.008 n=5+5)
name old alloc/op new alloc/op delta
DecodeSumVec3-8 0.00B 0.00B ~ (all equal)
name old allocs/op new allocs/op delta
DecodeSumVec3-8 0.00 0.00 ~ (all equal)
```
Karmem vs Karmem
That is an comparison with all supported languages.
<strong>WebAssembly on Wazero (MacOS/ARM64 - M1):</strong>
```
name \ time/op result/wasi-go-km.out result/wasi-as-km.out result/wasi-zig-km.out result/wasi-swift-km.out result/wasi-c-km.out result/wasi-odin-km.out result/wasi-dotnet-km.out
DecodeSumVec3-8 757µs ± 0% 1651µs ± 0% 369µs ± 0% 9145µs ± 6% 368µs ± 0% 1330µs ± 0% 75671µs ± 0%
DecodeObjectAPI-8 1.59ms ± 0% 6.13ms ± 0% 1.04ms ± 0% 30.59ms ±34% 0.90ms ± 1% 4.06ms ± 0% 231.72ms ± 0%
EncodeObjectAPI-8 3.96ms ± 0% 4.51ms ± 1% 1.20ms ± 0% 8.26ms ± 0% 1.03ms ± 0% 5.19ms ± 0% 237.99ms ± 0%
name \ alloc/op result/wasi-go-km.out result/wasi-as-km.out result/wasi-zig-km.out result/wasi-swift-km.out result/wasi-c-km.out result/wasi-odin-km.out result/wasi-dotnet-km.out
DecodeSumVec3-8 1.25kB ± 0% 21.75kB ± 0% 1.25kB ± 0% 1.82kB ± 0% 1.25kB ± 0% 5.34kB ± 0% 321.65kB ± 0%
DecodeObjectAPI-8 15.0kB ± 0% 122.3kB ± 1% 280.8kB ± 1% 108.6kB ± 3% 1.2kB ± 0% 23.8kB ± 0% 386.5kB ± 0%
EncodeObjectAPI-8 3.02kB ± 0% 58.00kB ± 1% 1.23kB ± 0% 1.82kB ± 0% 1.23kB ± 0% 8.91kB ± 0% 375.82kB ± 0%
name \ allocs/op result/wasi-go-km.out result/wasi-as-km.out result/wasi-zig-km.out result/wasi-swift-km.out result/wasi-c-km.out result/wasi-odin-km.out result/wasi-dotnet-km.out
DecodeSumVec3-8 5.00 ± 0% 5.00 ± 0% 5.00 ± 0% 32.00 ± 0% 5.00 ± 0% 6.00 ± 0% 11.00 ± 0%
DecodeObjectAPI-8 5.00 ± 0% 4.00 ± 0% 4.00 ± 0% 32.00 ± 0% 4.00 ± 0% 6.00 ± 0% 340.00 ± 0%
EncodeObjectAPI-8 4.00 ± 0% 3.00 ± 0% 3.00 ± 0% 30.00 ± 0% 3.00 ± 0% 5.00 ± 0% 40.00 ± 0%
```
Languages
Currently, we have focus on WebAssembly, and because of that those are the languages supported:
<ul>
<li>AssemblyScript 0.20.16</li>
<li>C/Emscripten</li>
<li>C#/.NET 7</li>
<li>Golang 1.19/TinyGo 0.25.0</li>
<li>Odin</li>
<li>Swift 5.7/SwiftWasm 5.7</li>
<li>Zig 0.10</li>
</ul>
Some languages still under development, and doesn't have any backward compatibility promise. We will try
to keep up with the latest version. Currently, the API generated and the libraries should not consider stable.
Features
| Features | Go/TinyGo | Zig | AssemblyScript | Swift | C | C#/.NET | Odin |
| -- | -- | -- | -- | -- | -- | -- | -- |
| Performance | Good | Excellent | Good | Poor | Excellent | Horrible | Good |
| Priority | High | High | High | Low | High | Medium | Low |
| <strong>Encoding</strong> | | | | | | | |
| Object Encoding | ✔️ |✔️ |✔️ | ✔️ | ✔️| ✔️ | ✔️ |
| Raw Encoding | ❌ |❌ | ❌| ❌ | ❌ | ❌ | ❌ |
| Zero-Copy |❌ | ❌ |❌ | ❌ | ❌ | ❌ | ❌ |
| <strong>Decoding</strong> | | | | | | | |
| Object Decoding |✔️ |✔️ |✔️ | ✔️ |✔️ | ✔️ | ✔️|
| Object Re-Use |✔️ |✔️ |✔️ | ❌ |✔️ | ✔️| ✔️ |
| Random-Access |✔️ |✔️ |✔️ | ✔️ |✔️ | ✔️ | ✔️|
| Zero-Copy |✔️ | ✔️ |✔️ | ❌ |✔️ | ✔️| ✔️|
| Zero-Copy-String |✔️ | ✔️ |❌ | ✔️ |✔️ | ❌| ✔️|
| Native Array | ✔️ |✔️ |❌ | ❌ |✔️ | ❌️| ✔️|
Schema
Karmem uses a custom schema language, which defines structs, enums and types.
Example
The schema is very simple to understand and define:
<code>``go
karmem game @packed(true) @golang.package(</code>km<code>) @assemblyscript.import(</code>../../assemblyscript/karmem`);
enum Team uint8 {Humans;Orcs;Zombies;Robots;Aliens;}
struct Vec3 inline {
X float32;
Y float32;
Z float32;
}
struct MonsterData table {
Pos Vec3;
Mana int16;
Health int16;
Name []char;
Team Team;
Inventory [<128]byte;
Hitbox [4]float64;
Status []int32;
Path [<128]Vec3;
}
struct Monster inline {
Data MonsterData;
}
struct State table {
Monsters [<2000]Monster;
}
```
Header:
Every file must begin with: <code>karmem {name} [@tag()];</code>. Other optional tags can be defined, as shown above, it's
recommended to use the <code>@packed(true)</code> option.
Types:
<strong>Primitives</strong>:
<ul>
<li>Unsigned Integers:
<code>uint8</code>, <code>uint16</code>, <code>uint32</code>, <code>uint64</code></li>
<li>Signed Integers:
<code>int8</code>, <code>int16</code>, <code>int32,</code> <code>int64</code></li>
<li>Floats:
<code>float32</code>, <code>float64</code></li>
<li>Boolean:
<code>bool</code></li>
<li>Byte:
<code>byte</code>, <code>char</code></li>
</ul>
It's not possible to define optional or nullable types.
<strong>Arrays</strong>:
<ul>
<li>Fixed:
<code>[{Length}]{Type}</code> (example: <code>[123]uint16</code>, <code>[3]float32</code>)</li>
<li>Dynamic:
<code>[]{Type}</code> (example: <code>[]char</code>, <code>[]uint64</code>)</li>
<li>Limited:
<code>[<{Length}]{Type}</code> (example: <code>[<512]float64</code>, <code>[<42]byte</code>)</li>
</ul>
It's not possible to have slice of tables or slices of enums or slice of slices. However, it's possible to wrap those
types inside one inline-struct.
Struct:
Currently, Karmem has two structs types: inline and table.
<strong>Inline:</strong>
Inline structs, as the name suggests, are inlined when used. That reduces the size and may improve the performance.
However, it can't have their definition changed. In order words: you can't edit the field of one inline struct
without breaking compatibility.
<code>go
struct Vec3 inline {
X float32;
Y float32;
Z float32;
}</code>
<em>That struct is exactly the same of <code>[3]float32</code> and will have the same serialization result. Because of that, any
change of this struct (for instance, change it to <code>float64</code> or adding new fields) will break the compatibility.</em>
<strong>Tables:</strong>
Tables can be used when backward compatibility matters. For example, tables can have new fields append at the bottom
without breaking compatibility.
<code>go
struct User table {
Name []char;
Email []char;
Password []char;
}</code>
Let's consider that you need another field... For tables, it's not an issue:
<code>go
struct User table {
Name []char;
Email []char;
Password []char;
Telephone []char;
}</code>
Since it's a table, you can add new fields at the bottom of the struct, and both versions are compatible between them. If
the message is sent to a client that doesn't understand the new field, it will be ignored. If one outdated client sends a
message to a newer client, the new field will have the default value (0, false, empty string, etc).
Enums:
Enums can be used as an alias to Integers type, such as <code>uint8</code>.
<code>go
enum Team uint8 {
Unknown;
Humans;
Orcs;
Zombies = 255;
}</code>
Enums must start with a zero value, the default value in all cases. If the value of any enum is omitted, it will use the
order of enum as value.
Generator
Once you have a schema defined, you can generate the code. First, you need to <code>karmem</code> installed, get it from the
releases page or run it with go.
<code>karmem build --assemblyscript -o "output-folder" your-schema.km</code>
<em>If you already have Golang installed, you can use <code>go karmem.org/cmd/karmem build --zig -o "output-folder" your-schema.km</code>
instead.</em>
<strong>Commands:</strong>
<strong><code>build</code></strong>
<ul>
<li><code>--zig</code>: Enable generation for Zig</li>
<li><code>--swift</code>: Enable generation for Swift/SwiftWasm</li>
<li><code>--odin</code>: Enable generation for Odin</li>
<li><code>--golang</code>: Enable generation for Golang/TinyGo</li>
<li><code>--dotnet</code>: Enable generation for .NET</li>
<li><code>--c</code>: Enable generation for C</li>
<li><code>--assemblyscript</code>: Enable generation for AssemblyScript</li>
<li><code>-o <dir></code>: Defines the output folder</li>
<li><code><input-file></code>: Defines the input schema</li>
</ul>
Security
Karmem is fast and is also aimed to be secure and stable for general usage.
<strong>Out Of Bounds</strong>
Karmem includes bounds-checking to prevent out-of-bounds reading and avoid crashes and panics. That is something that
Google Flatbuffers doesn't have, and malformed content will cause panic. However, it doesn't fix all possible
vulnerabilities.
<strong>Resource Exhaustion</strong>
Karmem allows one pointer/offset can be re-used multiple times in the same message. Unfortunately, that behaviour makes
it possible for a short message to generate more extensive arrays than the message size. Currently, the only mitigation
for that issue is using Limited-Arrays instead of Arrays and avoiding Object-API decode.
<strong>Data Leak</strong>
Karmem doesn't clear the memory before encoding, that may leak information from the previous message or from system
memory itself. That can be solved using <code>@packed(true)</code> tag, as previously described. The <code>packed</code> tag will remove
padding from the message, which will prevent the leak. Alternatively, you can clear the memory before encoding,
manually.
Limitations
Karmem have some limitations compared to other serialization libraries, such as:
<strong>Maximum Size</strong>
Similar to Google Protobuf and Google Flatbuffers, Karmem has a maximum size of 2GB. That is the maximum size of the entire
message, not the maximum size of each array. This limitation is due to the fact that WASM is designed to be 32-bit,
and the maximum size of 2GB seems adequate for the current needs. The current Writer doesn't enforce this limitation,
but reading a message that is bigger than 2GB will cause undefined behaviour.
<strong>Arrays of Arrays/Tables</strong>
Karmem doesn't support arrays of arrays or arrays of tables. However, it's possible to wrap those types inside one
inline-struct, as mentioned above. That limitation was imposed to take advantage of native arrays/slice from the
language. Most languages encapsulates the pointer and the size of the array inside a struct-like, that requires
the size of each element to be known, consequently preventing arrays of items with variable size/strides.
<strong>UTF-8</strong>
Karmem only supports UTF-8 and doesn't support other encodings. | [] |
https://avatars.githubusercontent.com/u/23124818?v=4 | zvm | tristanisham/zvm | 2022-11-09T05:55:03Z | zvm (Zig Version Manager) lets you easily install/upgrade between different versions of Zig. | master | 7 | 660 | 46 | 660 | https://api.github.com/repos/tristanisham/zvm/tags | MIT | [
"version-control",
"version-manager",
"versioning",
"zig",
"ziglang"
] | 31,265 | false | 2025-05-19T06:08:39Z | false | false | unknown | github | [] |
Zig Version Manager (zvm) is a tool for managing your
<a>Zig</a> installs. With std under heavy development and a
large feature roadmap, Zig is bound to continue changing. Breaking existing
builds, updating valid syntax, and introducing new features like a package
manager. While this is great for developers, it also can lead to headaches when
you need multiple versions of a language installed to compile your projects, or
a language gets updated frequently.
Donate
<ul>
<li><a>Paypal</a></li>
</ul>
Join our Community
<ul>
<li><a>Twitch</a></li>
<li><a>Twitter|X</a></li>
</ul>
<a></a>
Installing ZVM
ZVM lives entirely in <code>$HOME/.zvm</code> on all platforms it supports. Inside of the
directory, ZVM will download new ZIG versions and symlink whichever version you
specify with <code>zvm use</code> to <code>$HOME/.zvm/bin</code>. You should add this folder to your
path. After ZVM 0.2.3, ZVM's installer will now add ZVM to <code>$HOME/.zvm/self</code>.
You should also add this directory as the environment variable <code>ZVM_INSTALL</code>.
The installer scripts should handle this for you automatically on *nix and
Windows systems.
If you don't want to use <code>ZVM_INSTALL</code> (like you already have ZVM in a place you
like), then ZVM will update the exact executable you've called <code>upgrade</code> from.
Linux, BSD, MacOS, *nix
<code>sh
curl https://raw.githubusercontent.com/tristanisham/zvm/master/install.sh | bash</code>
Windows
PowerShell
<code>ps1
irm https://raw.githubusercontent.com/tristanisham/zvm/master/install.ps1 | iex</code>
Command Prompt
<code>cmd
powershell -c "irm https://raw.githubusercontent.com/tristanisham/zvm/master/install.ps1 | iex"</code>
If You Have a Valid Version of Go Installed
<code>sh
go install -ldflags "-s -w" github.com/tristanisham/zvm@latest</code>
Manually
Please grab the
<a>latest release</a>.
Putting ZVM on your Path
ZVM requires a few directories to be on your <code>$PATH</code>. If you don't know how to
update your environment variables permanently on Windows, you can follow
<a>this guide</a>. Once you're in
the appropriate menu, add or append to the following environment variables:
Add
<ul>
<li>ZVM_INSTALL: <code>%USERPROFILE%\.zvm\self</code></li>
</ul>
Append
<ul>
<li>PATH: <code>%USERPROFILE%\.zvm\bin</code></li>
<li>PATH: <code>%ZVM_INSTALL%</code></li>
</ul>
Configure ZVM path
It is possible to overwrite the default behavior of ZVM to adhere to XDG
specification on Linux. There's an environment variable <code>ZVM_PATH</code>. Setting it
to <code>$XDG_DATA_HOME/zvm</code> will do the trick.
Community Package
AUR
<code>zvm</code> on the <a>Arch AUR</a> is a
community-maintained package, and may be out of date.
Why should I use ZVM?
While Zig is still pre-1.0 if you're going to stay up-to-date with the master
branch, you're going to be downloading Zig quite often. You could do it
manually, having to scoll around to find your appropriate version, decompress
it, and install it on your <code>$PATH</code>. Or, you could install ZVM and run
<code>zvm i master</code> every time you want to update. <code>zvm</code> is a static binary under a
permissive license. It supports more platforms than any other Zig version
manager. Its only dependency is <code>tar</code> on Unix-based systems. Whether you're on
Windows, MacOS, Linux, a flavor of BSD, or Plan 9 <code>zvm</code> will let you install,
switch between, and run multiple versions of Zig.
Contributing and Notice
<code>zvm</code> is stable software. Pre-v1.0.0 any breaking changes will be clearly
labeled, and any commands potentially on the chopping block will print notice.
The program is under constant development, and the author is very willing to
work with contributors. <strong>If you have any issues, ideas, or contributions you'd
like to suggest
<a>create a GitHub issue</a></strong>.
How to use ZVM
Install
```sh
zvm install
Or
zvm i
```
Use <code>install</code> or <code>i</code> to download a specific version of Zig. To install the
latest version, use "master".
```sh
Example
zvm i master
```
Force Install
As of <code>v0.7.6</code> ZVM will now skip downloading a version if it is already
installed. You can always force an install with the <code>--force</code> or <code>-f</code> flag.
<code>sh
zvm i --force master</code>
You can also enable the old behavior by setting the new <code>alwaysForceInstall</code>
field to <code>true</code> in <code>~/.zvm/settings.json</code>.
Install ZLS with ZVM
You can now install ZLS with your Zig download! To install ZLS with ZVM, simply
pass the <code>--zls</code> flag with <code>zvm i</code>. For example:
<code>sh
zvm i --zls master</code>
Select ZLS compatibility mode
By default, ZVM will install a ZLS build, which can be used with the given Zig
version, but may not be able to build ZLS from source. If you want to use a ZLS
build, which can be built using the selected Zig version, pass the <code>--full</code> flag
with <code>zvm i --zls</code>. For example:
<code>sh
zvm i --zls --full master</code>
<blockquote>
<span class="bg-green-100 text-green-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-green-900 dark:text-green-300">IMPORTANT</span>
This does not apply to tagged releases, e.g.: <code>0.13.0</code>
</blockquote>
Switch between installed Zig versions
<code>sh
zvm use <version></code>
Use <code>use</code> to switch between versions of Zig.
```sh
Example
zvm use master
```
List installed Zig versions
```sh
Example
zvm ls
```
Use <code>ls</code> to list all installed version of Zig.
List all versions of Zig available
<code>sh
zvm ls --all</code>
The <code>--all</code> flag will list the available verisons of Zig for download. Not the
versions locally installed.
List set version maps
<code>sh
zvm ls --vmu</code>
The <code>--vmu</code> flag will list set version maps for Zig and ZLS downloads.
Uninstall a Zig version
```sh
Example
zvm rm 0.10.0
```
Use <code>uninstall</code> or <code>rm</code> to remove an uninstalled version from your system.
Upgrade your ZVM installation
As of <code>zvm v0.2.3</code> you can now upgrade your ZVM installation from, well, zvm.
Just run:
<code>sh
zvm upgrade</code>
The latest version of ZVM should install on your machine, regardless of where
your binary lives (though if you have your binary in a privaledged folder, you
may have to run this command with <code>sudo</code>).
Clean up build artifacts
```sh
Example
zvm clean
```
Use <code>clean</code> to remove build artifacts (Good if you're on Windows).
Run installed version of Zig without switching your default
If you want to run a version of Zig without setting it as your default, the new
<code>run</code> command is your friend.
```sh
zig version
0.13.0
zvm run 0.11.0 version
0.11.0
zig version
0.13.0
```
This can be helpful if you want to test your project on a newer version of Zig
without having to switch between bins, or on alternative flavor of Zig.
How to use with alternative VMUs
Make sure you switch your VMU before using <code>run</code>.
```sh
zvm vmu zig mach
run mach-latest version
0.14.0-dev.1911+3bf89f55c
```
If you would like to run the currently set Zig, please keep using the standard
<code>zig</code> command.
Set Version Map Source
ZVM lets choose your vendor for Zig and ZLS. This is great if your company hosts
it's own internal fork of Zig, you prefer a different flavor of the language,
like Mach.
```sh
zvm vmu zig "https://machengine.org/zig/index.json" # Change the source ZVM pulls Zig release information from.
zvm vmu zls https://validurl.local/vmu.json
# ZVM only supports schemas that match the offical version map schema.
# Run <code>vmu default</code> to reset your version map.
zvm vmu zig default # Resets back to default Zig releases.
zvm vmu zig mach # Sets ZVM to pull from Mach nominated Zig.
zvm vmu zls default # Resets back to default ZLS releases.
```
Print program help
Print global help information by running:
<code>sh
zvm --help</code>
Print help information about a specific command or subcommand.
<code>sh
zvm list --help</code>
<code>``
NAME:
zvm list - list installed Zig versions. Flag</code>--all` to see remote options
USAGE:
zvm list [command options] [arguments...]
OPTIONS:
--all, -a list remote Zig versions available for download, based on your version map (default: false)
--vmu list set version maps (default: false)
--help, -h show help
```
Print program version
<code>sh
zvm --version</code>
Prints the version of ZVM you have installed.
Option flags
Color Toggle
Enable or disable colored ZVM output. No value toggles colors.
Enable
<ul>
<li>on</li>
<li>yes/y</li>
<li>enabled</li>
<li>true</li>
</ul>
Disabled
<ul>
<li>off</li>
<li>no/n</li>
<li>disabled</li>
<li>false</li>
</ul>
<code>sh
--color # Toggle ANSI color printing on or off for ZVM's output, i.e. --color=true</code>
Environment Variables
<ul>
<li><code>ZVM_DEBUG</code> enables DEBUG logging for your executable. This is meant for
contributors and developers.</li>
<li><code>ZVM_SET_CU</code> Toggle the automatic upgrade checker. If you want to reenable the
checker, just <code>uset ZVM_SET_CU</code>.</li>
<li><code>ZVM_PATH</code> replaces the default install location for ZVM Set the environment
variable to the parent directory of where you've placed the <code>.zvm</code> directory.</li>
<li><code>ZVM_SKIP_TLS_VERIFY</code> Do you have problems using TLS in your evironment?
Toggle off verifying TLS by setting this environment variable.</li>
<li>By default when this is enabled ZVM will print a warning. Set this variable
to <code>no-warn</code> to silence this warning.</li>
</ul>
Settings
ZVM has additional setting stored in <code>~/.zvm/settings.json</code>. You can manually
update version maps, toggle color support, and disable the automatic upgrade
checker here. All settings are also exposed as flags or environment variables.
This file is stateful, and ZVM will create it if it does not exist and utilizes
it for its operation.
Please Consider Giving the Repo a Star ⭐
<a>
</a> | [] |
https://avatars.githubusercontent.com/u/11307305?v=4 | cowasm | sagemathinc/cowasm | 2022-06-27T00:42:22Z | CoWasm: Collaborative WebAssembly for Servers and Browsers. Built using Zig. Supports Python with extension modules, including numpy. | main | 15 | 527 | 27 | 527 | https://api.github.com/repos/sagemathinc/cowasm/tags | BSD-3-Clause | [
"python",
"wasm",
"webassembly",
"zig"
] | 15,668 | false | 2025-05-19T09:39:59Z | false | false | unknown | github | [] | CoWasm: Collaborative WebAssembly for Servers and Browsers
URL: https://github.com/sagemathinc/cowasm
DEMOS:
<ul>
<li>https://cowasm.org - Python using SharedArrayBuffers</li>
<li>https://zython.org - Python using Service Workers</li>
<li>https://cowasm.sh - Dash Shell with Python, Sqlite, Lua, etc., using SharedArrayBuffers</li>
</ul>
TEST STATUS:
<ul>
<li><a></a></li>
</ul>
Or Type this if you have nodejs at least version 16 installed:
```sh
~$ npx python-wasm@latest
Python 3.11.0 (main, Oct 27 2022, 10:03:11) [Clang 15.0.3 (git@github.com:ziglang/zig-bootstrap.git 0ce789d0f7a4d89fdc4d9571 on wasi
Type "help", "copyright", "credits" or "license" for more information.
<blockquote>
<blockquote>
<blockquote>
2 + 3
5
import numpy
import sympy
...
```
</blockquote>
</blockquote>
</blockquote>
NOTE: On Microsoft Windows you have to enter a few times, and there is an issue with terminal echo. We are working on this.
Packages
There are four subdirectories that each contain packages:
<ul>
<li><strong>core</strong> - core functionality, including dynamic linking, a WASI implementation, openssl, and nontrivial posix extensions to node.js written in Zig. (This is analogous to <a>emscripten.org.</a>)</li>
<li><strong>python</strong> - a WebAssembly build of Python, along with some nontrivial scientific libraries (This is analogous to <a>pyodide.org.)</a></li>
<li><strong>web</strong> - examples of how to use the other packages in web applications; this includes building https://cowasm.org.</li>
<li><strong>desktop</strong> - a native Electron app that provides a sandboxed WebAssembly Python terminal running on your native filesystem.</li>
<li><strong>sagemath</strong> - beginning of a port of https://sagemath.org to WebAssembly. Vasts amounts of work remain.</li>
</ul>
What is this?
CoWasm means "collaborative WebAssembly", and goes far beyond just Python. The collaboration aspects will be part of https://cocalc.com at some point in the future. CoWasm will support various technologies (such as libgit2 and realtime sync) that are important foundations for collaboration.
The underlying software components that CoWasm is built on (i.e., that we didn't write) are mostly extremely stable and mature. Zig is less stable, but we mostly use Zig for its amazing cross compilation support and packaging of clang/llvm and musl-libc, which are themselves both very mature. Many other components, such as Python, Dash, Numpy, etc., are ridiculously mature multidecade old projects. Moreover, other components of CoWasm such as memfs are libraries with 10M+ downloads per week that are heavily used in production.
The goal of CoWasm is overall somewhat similar to all of emscripten, <a>WebAssembly.sh</a>, <a>wapm.io</a>, and <a>Pyodide</a> combined, in various ways.
<ul>
<li>Unlike <a>WebAssembly.sh</a> and <a>wapm.io</a> (but similar to <a>Pyodide</a>), we make <em><strong>VERY heavy use of shared dynamic libraries</strong></em> (e.g., <code>-fPIC</code> code), which is only possible because of a plugin contributed from emscripten to LLVM. The "Co" in CoWasm suggestion "collaboration" or "sharing", which also reflects how the binaries in this project are structured.</li>
<li>We use actual editline (similar to readline) instead of a Javascript terminal. Moreover, unlike other webassembly shells, we just use a real command line shell (dash = Debian Almquist Shell). We also have a userspace including ports of many coreutils, e.g., ls, head, tail, etc.</li>
<li>Unlike emscripten, we use modern Typescript, our code is more modular, and we make use of existing components when possible (e.g., the nodejs memfs project), instead of using our own.</li>
<li>A core design constraint is to efficiently run on a wide range of platforms, not mainly in the browser like emscripten, and not mainly on servers like wasmer. CoWasm should run on servers, desktops (e.g., as an electron app), an iPad/iOS app, and in web browsers.</li>
<li><strong>There is no business unfriendly GPL code in CoWasm.</strong> CoWasm itself is extremely liberally licensed and business friendly. The license of all new code and most components is 3-clause BSD. CoWasm will serve as a foundation for other projects with more restrictive licenses:</li>
<li>CoCalc will build on top of CoWasm to provide a graphical interface and realtime collaboration, and that will be a commercial product.</li>
<li>Products like GP/PARI SageMath will build on CoWasm to provide GPL-licensed mathematics software.</li>
</ul>
Python
An exciting package in CoWasm is <a>python-wasm</a>, which is a build of Python for WebAssembly, which supports both servers and browsers. It also supports extension modules such as numpy. See <a>python/README.md</a> for more details.
Try python-wasm
Try the python-wasm REPL under node.js (version at least 16):
```py
~$ npx python-wasm@latest
Python 3.11.0 (main, Oct 27 2022, 10:03:11) [Clang 15.0.3 (git@github.com:ziglang/zig-bootstrap.git 0ce789d0f7a4d89fdc4d9571 on wasi
Type "help", "copyright", "credits" or "license" for more information.
<blockquote>
<blockquote>
<blockquote>
2 + 3
5
import sys; sys.version
'3.11.0 (main, Oct 27 2022, 10:03:11) [Clang 15.0.3 (git@github.com:ziglang/zig-bootstrap.git 0ce789d0f7a4d89fdc4d9571'
sys.platform
'wasi'
```
</blockquote>
</blockquote>
</blockquote>
Install python-wasm
Install python-wasm into your project, and try it via the library interface and the node.js terminal.
<code>sh
npm install python-wasm</code>
Then from the nodejs REPL:
```js
~/cowasm/core/python-wasm$ node
Welcome to Node.js v19.0.0.
Type ".help" for more information.
<blockquote>
{syncPython, asyncPython} = require('.')
{
syncPython: [AsyncFunction: syncPython],
asyncPython: [AsyncFunction: asyncPython],
default: [AsyncFunction: asyncPython]
}
python = await syncPython(); 0;
0
python.exec('import sys')
undefined
python.repr('sys.version')
"'3.11.0b3 (main, Jul 14 2022, 22:22:40) [Clang 13.0.1 (git@github.com:ziglang/zig-bootstrap.git 623481199fe17f4311cbdbbf'"
python.exec('import numpy')
undefined
python.repr('numpy.linspace(0, 10, num=5)')
'array([ 0. , 2.5, 5. , 7.5, 10. ])'
```
</blockquote>
There is also a Python REPL that is part of python-wasm:
```py
<blockquote>
python.terminal()
Python 3.11.0 (main, Oct 27 2022, 10:03:11) [Clang 15.0.3 (git@github.com:ziglang/zig-bootstrap.git 0ce789d0f7a4d89fdc4d9571 on wasi
Type "help", "copyright", "credits" or "license" for more information.
<blockquote>
<blockquote>
2 + 3 # you can edit using readline
5
input('name? ')*3
name? william <-- I just typed "william"
'williamwilliamwilliam'
import time; time.sleep(3) # sleep works
while True: pass # ctrl+c works, but exits this terminal
</blockquote>
</blockquote>
back in node.
```
</blockquote>
You can also use python-wasm in your own <a>web applications via webpack</a>. In the browser, this transparently uses SharedArrayBuffers if available, and falls back to ServiceWorkers.
Build from Source
We support and regularly test building CoWasm from source on the following platforms:
<ul>
<li>x86 macOS and aarch64 macOS (Apple Silicon M1)</li>
<li>x86 and aarch64 Linux</li>
</ul>
Prerequisites
You need Node.js version at least 16.x, pnpm and several standard dev tools listed below. The dependency you need for every possible package are as follows:
<ul>
<li>
On <strong>MacOS</strong>, install the <a>XCode command line tools.</a>
</li>
<li>
On <strong>Linux apt-based system, e.g., on Ubuntu 22.04</strong>:
</li>
</ul>
<code>sh
sudo apt-get update && sudo apt-get install git make cmake curl dpkg-dev m4 yasm texinfo python-is-python3 libtool tcl zip libncurses-dev</code>
If you also want to install node v18 and pnpm on Ubuntu, you could do:
<code>sh
sudo curl -sL https://deb.nodesource.com/setup_18.x | bash - \
&& sudo apt-get install -y nodejs \
&& curl -fsSL https://get.pnpm.io/install.sh | sh -</code>
<ul>
<li>On <strong>Linux RPM based system, e.g., Fedora 37:</strong></li>
</ul>
<code>sh
dnf install git make cmake curl dpkg-dev m4 yasm texinfo libtool tcl zip ncurses-devel perl</code>
<ul>
<li>On <strong>ArchLinux</strong>:</li>
</ul>
<code>sh
pacman -Sy binutils git nodejs npm cmake curl m4 yasm texinfo python libtool tcl zip unzip patch binutils diffutils</code>
NOTE: <code>pnpm</code> is not in the Arch Linux official package sets. You may want to install it from Arch User Repository (AUR) <a>AUR (en) - pnpm</a>.
<ul>
<li>Currently, the only way to build CoWasm from source on MS Windows is to use a Docker container running Linux. Using WSL2 (maybe) works but is too slow.</li>
</ul>
In addition you need to <a>install Node.js version at least 16.x</a> and <a>install the pnpm package manager</a>.
Notes about Zig
<em><strong>You do NOT need to install Zig,</strong></em> and it doesn't matter if
you have a random version of Zig on your system already. A zig binary is download automatically. We use zig (instead of any system-wide clang, etc. compilers) for building all compiled code and write some code in the zig language. Since zig is fairly unstable it is critical to use the exact version that we provide.
Build
To build any package in the <code>src/packages</code> directory, cd into that directory, then:
<code>sh
make</code>
That's it, usually. You do not have to run build at the top level and you can start with building any specific package -- it will automatically cause any required dependencies to get installed or built.
You can also force building of every single package and running its test suite if you want:
```sh
~/cowasm$ make test
...
CONGRATULATIONS -- FULL COWASM TEST SUITE PASSED!
Fri Oct 28 12:32:19 AM UTC 2022
Linux aarch64
Git Branch: main
```
Depending on your computer, the build should take less than 30 minutes, and about 6GB's of disk space.
This installs a specific tested version of Zig and Nodejs, then builds native and WebAssembly versions of CPython and many dependencies, and also builds all the Typescript code. It also builds many other interesting programs with ports to WebAssembly, though many are not completely finished (e.g., there is the dash shell and ports of tar and BSD coreutils). As mentioned, building from source is regularly <em><strong>tested on Linux and MacOS with both x86_64 and ARM (M1) processors</strong></em>:
<ul>
<li>Linux: tested on both x86_64 and aarch64 Ubuntu</li>
<li>MacOS: tested on both x86_64 and M1 mac with standard XCode command live dev tools installed.</li>
</ul>
CoWasm <em><strong>does not</strong></em> use the compilers on the system, and instead uses clang/llvm as shipped with Zig. If you're using Windows, you'll have to use Linux via a virtual machine or Docker.
Pull latest code, build and test
At the top level run <code>./bin/rebuild-all</code> :
<code>sh
~/cowasm$ ./bin/rebuild-all</code>
This does <code>make clean,</code> pulls the latest code, then runs the full build and test suite. Fortunately, <code>zig</code> caches a lot of build artifacts, so subsequent builds are faster.
<strong>NOTE/WARNING:</strong> Zig's cache is in <code>~/.cache/zig</code> and it can get HUGE. As far as I can tell, I think it just grows and grows without bound (it's not an LRU cache), and I think there are no tools to "manage" it besides just <code>rm -rf</code> it periodically.
What is tested?
Note that running <code>make test</code> at the top level does NOT run the <strong>full</strong> test suite of every package, since it takes quite a while and there are <strong>still some failing tests</strong>, since CoWasm doesn't support enough of what Python expects. It does run a large supported subset of the cpython test suite (it's the part that I got to pass so far, which is over 80%). As an example, the sympy test suite is massive, takes a very long time to run, and doesn't even work for me natively; instead, we just run a handful of small tests to ensure sympy is working at all. Similarly, for Cython, we run all their demos, but not the full test suite. A longer term goal of CoWasm is to support a second more thorough testing regime that runs the full test suite of each package. There will likely always be issues due to WASM not being a multiuser POSIX system, but it's good to know what those issues are!
You can also use the WebAssembly Python REPL directly on the command line.
```sh
~/cowasm$ ./bin/python-wasm
Python 3.11.0 (main, Oct 27 2022, 10:03:11) [Clang 15.0.3 (git@github.com:ziglang/zig-bootstrap.git 0ce789d0f7a4d89fdc4d9571 on wasi
Type "help", "copyright", "credits" or "license" for more information.
<blockquote>
<blockquote>
<blockquote>
2 + 3
5
import sys
sys.platform
'wasi'
sys.executable
'/Users/wstein/build/cocalc/src/data/projects/2c9318d1-4f8b-4910-8da7-68a965514c95/cowasm/core/cpython/bin/python-wasm'
^D
~/cowasm$
```
</blockquote>
</blockquote>
</blockquote>
The above directly runs the `python.wasm` executable produced by building cPython. You can instead run an enhanced version (e.g., with signal support) with more options in the python-wasm package:
```py
~/cowasm$ . bin/env.sh
~/cowasm$ cd core/python-wasm/
~/cowasm/core/python-wasm$ ./bin/python-wasm
Python 3.11.0 (main, Oct 27 2022, 10:03:11) [Clang 15.0.3 (git@github.com:ziglang/zig-bootstrap.git 0ce789d0f7a4d89fdc4d9571 on wasi
Type "help", "copyright", "credits" or "license" for more information.
<blockquote>
<blockquote>
<blockquote>
import time; t=time.time(); print(sum(range(10**7)), time.time()-t)
49999995000000 0.8989999294281006
^D
~/cowasm/core/python-wasm$
```
</blockquote>
</blockquote>
</blockquote>
As mentioned above, you can use python-wasm as a library in node.js. There is a synchronous api that runs in the same thread as the import, and an asynchronous api that runs in a worker thread.
```py
~/cowasm$ . bin/env.sh
~/cowasm$ cd core/python-wasm/
~/cowasm/core/python-wasm$ node
Welcome to Node.js v19.0.0.
Type ".help" for more information.
<blockquote>
python = require('.')
{
syncPython: [AsyncFunction: syncPython],
asyncPython: [AsyncFunction: asyncPython],
default: [AsyncFunction: asyncPython]
}
const { exec, repr} = await python.asyncPython();
undefined
await repr('31<strong>37')
'15148954872646847105498509334067131813327318808179940511'
await exec('import time; t=time.time(); print(sum(range(10</strong>7)), time.time()-t)')
49999995000000 0.8880000114440918
```
</blockquote>
And yes you can run many async Python's in parallel in the same node.js process, with each running in its own thread:
```sh
~/cowasm/core/python-wasm$ nodeWelcome to Node.js v19.0.0.
Type ".help" for more information.
<blockquote>
python = require('.')
{
syncPython: [AsyncFunction: syncPython],
asyncPython: [AsyncFunction: asyncPython],
default: [AsyncFunction: asyncPython]
}
const { exec, repr} = await python.asyncPython();
undefined
await exec('import time; t=time.time(); print(sum(range(10**7)), time.time()-t)')
49999995000000 0.8880000114440918
undefined
const v = [await python.asyncPython(), await python.asyncPython(), await python.asyncPython()]; 0;
0
s = 'import time; t=time.time(); print(sum(range(10<strong>7)), time.time()-t)'
'import time; t=time.time(); print(sum(range(10</strong>7)), time.time()-t)'
d = new Date(); console.log(await Promise.all([v[0].exec(s), v[1].exec(s), v[2].exec(s)]), new Date() - d)
49999995000000 0.8919999599456787
49999995000000 0.8959999084472656
49999995000000 0.8929998874664307
[ undefined, undefined, undefined ] 905
undefined
```
</blockquote>
What's the goal?
Our <strong>initial goal</strong> is to create a WebAssembly build of the core Python and dependent packages, which runs both on the command line with Node.js and in the major web browsers (via npm modules that you can include via webpack). This is done. It should also be relatively easy to <em>build from source</em> on both Linux and MacOS (x86_64 and aarch64) and to easily run the cpython test suite,_ with a clearly defined supported list of passing tests. The compilation system is based on <a>Zig</a>, which provides excellent caching and cross compilation, and each package is built using make.
How does CoWasm compare to Emscripten and Pyodide?
Pyodide currently provides far more packages. However, there is no reason that CoWasm couldn't eventually support as much or more than Pyodide.
Our main longterm application is to make <a>CoCalc</a> available on a much wider range of computers. As such, we are building a foundation here on which to support a substantial part of the scientific Python ecosystem and the <a>SageMath packages</a> (a pure math analogue of the scientific Python stack). <em><strong>I'm the founder of SageMath</strong></em>, hence this motivation (some relevant work has been done <a>here)</a>.
Some of our code will be written in the <a>Zig</a> language. However, we are mostly targeting just the parts that are used for Python, which is a small subset of the general problem. Our software license -- <em><strong>BSD 3-clause</strong></em> -- is compatible with their's and we hope to at least learn from their solutions to problems.
<a>More about how Pyodide and python-wasm differ...</a>
More about building from source
How to build
Just type make. (Do <strong>NOT</strong> type <code>make -j8;</code> it probably won't work.)
<code>sh
...$ make</code>
This runs a single top level Makefile that builds all the packages. The build process for each individual package is <em>also</em> accomplished using a Makefile with two includes that impose some structure. We don't use shell scripts or Python code to orchestrate building anything, since <code>make</code> is much cleaner and easier to read, maintain and debug... and of course make contains shell scripts in it. (History lesson: homebrew is a lot more successful than Macports.)
What happens
In most subdirectories <code>foo/</code> of <code>core</code>, this makefile creates some subdirectories:
<ul>
<li><code>core/foo/dist/[native|wasm]</code> -- a native or WebAssembly build of the package; this has binaries, headers, and libs. These get used by other packages. We rarely build the native version.</li>
<li><code>core/build/[native|wasm]</code> - build artifacts for the native or WebAssembly build; can be safely deleted</li>
</ul>
No common prefix directory
Unlike some systems, where everything is built and installed into a single <code>prefix</code> directory, here we build everything in its own self-contained package dist directory. When a package like <code>cpython</code> depends on another package like <code>lzma</code> , our Makefile for <code>cpython</code> explicitly references <code>packages/lzma/dist</code>. This makes it easier to uninstall packages, update them, etc., without having to track what files are in any package, whereas using a common directory for everything can be a mess with possibly conflicting versions of files, and makes versioning and dependencies very explicit. Of course, it makes the environment variables and build commands potentially much longer. In some cases, we gather together files from these dist directories in distributions, e.g., see <code>make bin-wasm.</code>
Native and Wasm
The build typically create directories <code>dist/native</code>and <code>dist/wasm.</code> The <code>dist/native</code> artifacts are only of value on the computer where you ran the build, since they are architecture dependent and can easily depend on libraries on your system. In contrast, the <code>dist/wasm</code> artifacts are platform independent. They can be used nearly everywhere: on servers via WASM, on ARM computers (e.g., aarch64 linux, Apple Silicon, etc.), and in modern web browsers.
Standalone WASM executables
The bin directory has scripts <code>zcc</code> and <code>z++</code> that are C and C++ compiler wrappers around Zig + Node. They create binaries that you can run on the command line as normal. Under the hood there's a wrapper script that calls node.js and the wasi runtime.
<code>sh
$ . bin/env.sh
$ echo 'int main() { printf("hello from Web Assembly: %d\n", 2+2); }' > a.c
$ zcc a.c
$ ls -l
a.c a.out a.out.wasm ...
$ ./a.out # this actually runs nodejs + python-wasm
hello from Web Assembly: 4</code>
This isn't currently used here for building python-wasm, but it's an extremely powerful tool. (For example, I used it with JSage to cross compile the NTL library to Web Assembly...)
Run a script from the terminal:
<code>sh
~/cowasm$ echo "import sys; print(f'hi from {sys.platform}')" > a.py
~/cowasm$ bin/python-wasm a.py
hi from wasi</code>
The python-wasm package has a bin/python-wasm script that can run
Python programs that including interactive blocking input:
<code>sh
~/cowasm/core/python-wasm$ echo "name = input('name? '); print(name*3)" > a.py
~/cowasm/core/python-wasm$ ./bin/python-wasm a.py
name? william
williamwilliamwilliam</code>
Contact
Email <a>wstein@cocalc.com</a> or <a>@wstein389</a> if find this interesting and want to help out.
<strong>CoWasm is an open source 3-clause BSD licensed project. It includes components and dependencies that may be licensed in other ways, but nothing is GPL licensed, <em>except</em> some code in the sagemath subdirectory (which nothing else depends on).</strong> | [] |
https://avatars.githubusercontent.com/u/206480?v=4 | websocket.zig | karlseguin/websocket.zig | 2022-05-28T14:35:01Z | A websocket implementation for zig | master | 5 | 407 | 38 | 407 | https://api.github.com/repos/karlseguin/websocket.zig/tags | MIT | [
"websocket",
"zig",
"zig-library",
"zig-package"
] | 561 | false | 2025-05-19T00:09:50Z | true | true | unknown | github | [] | A zig websocket server.
This project follows Zig master. See available branches if you're targeting a specific version.
Skip to the <a>client section</a>.
If you're upgrading from a previous version, check out the <a>Server Migration</a> and <a>Client Migration</a> wikis.
Server
```zig
const std = @import("std");
const ws = @import("websocket");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
<code>var server = try ws.Server(Handler).init(allocator, .{
.port = 9224,
.address = "127.0.0.1",
.handshake = .{
.timeout = 3,
.max_size = 1024,
// since we aren't using hanshake.headers
// we can set this to 0 to save a few bytes.
.max_headers = 0,
},
});
// Arbitrary (application-specific) data to pass into each handler
// Pass void ({}) into listen if you have none
var app = App{};
// this blocks
try server.listen(&app);
</code>
}
// This is your application-specific wrapper around a websocket connection
const Handler = struct {
app: <em>App,
conn: </em>ws.Conn,
<code>// You must define a public init function which takes
pub fn init(h: *ws.Handshake, conn: *ws.Conn, app: *App) !Handler {
// `h` contains the initial websocket "handshake" request
// It can be used to apply application-specific logic to verify / allow
// the connection (e.g. valid url, query string parameters, or headers)
_ = h; // we're not using this in our simple case
return .{
.app = app,
.conn = conn,
};
}
// You must defined a public clientMessage method
pub fn clientMessage(self: *Handler, data: []const u8) !void {
try self.conn.write(data); // echo the message back
}
</code>
};
// This is application-specific you want passed into your Handler's
// init function.
const App = struct {
// maybe a db pool
// maybe a list of rooms
};
```
Handler
When you create a <code>websocket.Server(Handler)</code>, the specified <code>Handler</code> is your structure which will receive messages. It must have a public <code>init</code> function and <code>clientMessage</code> method. Other methods, such as <code>close</code> can optionally be defined.
init
The <code>init</code> method is called with a <code>*websocket.Handshake</code>, a <code>*websocket.Conn</code> and whatever app-specific value was passed into <code>Server(H).init</code>.
When <code>init</code> is called, the handshake response has not yet been sent to the client (this allows your <code>init</code> method to return an error which will cause websocket.zig to send an error response and close the connection). As such, you should not use/write to the <code>*websocket.Conn</code> at this point. Instead, use the <code>afterInit</code> method, described next.
The websocket specification requires the initial "handshake" to contain certain headers and values. The library validates these headers. However applications may have additional requirements before allowing the connection to be "upgraded" to a websocket connection. For example, a one-time-use token could be required in the querystring. Applications should use the provided <code>websocket.Handshake</code> to apply any application-specific verification and optionally return an error to terminate the connection.
The <code>*websocket.Handshake</code> exposes the following fields:
<ul>
<li><code>url: []const u8</code> - URL of the request in its original casing</li>
<li><code>method: []const u8</code> - Method of the request in its original casing</li>
<li><code>raw_headers: []const u8</code> - The raw "key1: value1\r\nkey2: value2\r\n" headers. Keys are lowercase.</li>
</ul>
If you set the <code>max_headers</code> configuration value to > 0, then you can use <code>req.headers.get("HEADER_NAME")</code> to extract a header value from the given name:
If you set the <code>max_res_headers</code> configuration value to > 0, then you can set headers to be sent in the handshake response:
<code>zig
pub fn init(h: *ws.Handshake, conn: *ws.Conn, app: *App) !Handler {
h.res_headers.add("set-cookie", "delicious")
//...
}</code>
Note that, currently, the total length of the headers added to <code>res_headers</code> should not exceed 1024 characters, else you will exeperience an out of bounds segfault.
```zig
// the last parameter, an <em>App in this case, is an application-specific
// value that you passed into server.listen()
pub fn init(h: </em>websocket.Handshake, conn: websocket.Conn, app: *App) !Handler {
// get returns a ?[]const u8
// the name is lowercase
// the value is in its original case
const token = handshake.headers.get("authorization") orelse {
return error.NotAuthorized;
}
<code>return .{
.app = app,
.conn = conn,
};
</code>
}
```
You can iterate through all the headers:
<code>zig
var it = handshake.headers.iterator();
while (it.next) |kv| {
std.debug.print("{s} = {s}\n", .{kv.key, kv.value});
}</code>
Memory referenced by the <code>websocket.Handshake</code>, including headers from <code>handshake.headers</code> will be freed after the call to <code>init</code> completes. Application that need these values to exist beyond the call to <code>init</code> must make a copy.
afterInit
If your handler defines a <code>afterInit(handler: *Handler) !void</code> method, the method is called after the handshake response has been sent. This is the first time the connection can safely be used.
<code>afterInit</code> supports two overloads:
<code>zig
pub fn afterInit(handler: *Handler) !void
pub fn afterInit(handler: *Handler, ctx: anytype) !void</code>
The <code>ctx</code> is the same <code>ctx</code> passed into <code>init</code>. It is passed here for cases where the value is only needed once when the connection is established.
clientMessage
The <code>clientMessage</code> method is called whenever a text or binary message is received.
The <code>clientMessage</code> method can take one of four shapes. The simplest, shown in the first example, is:
<code>zig
// simple clientMessage
clientMessage(h: *Handler, data: []u8) !void</code>
The Websocket specific has a distinct message type for text and binary. Text messages must be valid UTF-8. Websocket.zig does not do this validation (it's expensive and most apps don't care). However, if you do care about the distinction, your <code>clientMessage</code> can take another parameter:
<code>zig
// clientMessage that accepts a tpe to differentiate between messages
// sent as `text` vs those sent as `binary`. Either way, Websocket.zig
// does not validate that text data is valid UTF-8.
clientMessage(h: *Handler, data: []u8, tpe: ws.MessageTextType) !void</code>
Finally, <code>clientMessage</code> can take an optional <code>std.mem.Allocator</code>. If you need to dynamically allocate memory within <code>clientMessage</code>, consider using this allocator. It is a fast thread-local buffer that fallsback to an arena allocator. Allocations made with this allocator are freed after <code>clientMessage</code> returns:
```zig
// clientMessage that takes an allocator
clientMessage(h: *Handler, allocator: Allocator, data: []u8) !void
// cilentMessage that takes an allocator AND a MessageTextType
clientMessage(h: *Handler, allocator: Allocator, data: []u8, tpe: ws.MessageTextType) !void`
```
If <code>clientMessage</code> returns an error, the connection is closed. You can also call <code>conn.close()</code> within the method.
close
If your handler defines a <code>close(handler: *Handler)</code> method, the method is called whenever the connection is being closed. Guaranteed to be called exactly once, so it is safe to deinitialize the <code>handler</code> at this point. This is called no mater the reason for the closure (on shutdown, if the client closed the connection, if your code close the connection, ...)
The socket may or may not still be alive.
clientClose
If your handler defines a <code>clientClose(handler: *Handler, data: []u8) !void</code> method, the function will be called whenever a <code>close</code> message is received from the client.
You almost certainly <em>do not</em> want to define this method and instead want to use <code>close()</code>. When not defined, websocket.zig follows the websocket specific and replies with its own matching close message.
clientPong
If your handler defines a <code>clientPong(handler: *Handler, data: []u8) !void</code> method, the function will be called whenever a <code>pong</code> message is received from the client. When not defined, no action is taken.
clientPing
If your handler defines a <code>clientPing(handler: *Handler, data: []u8) !void</code> method, the function will be called whenever <code>ping</code> message is received from the client. When not defined, websocket.zig will write a corresponding <code>pong</code> reply.
websocket.Conn
The call to <code>init</code> includes a <code>*websocket.Conn</code>. It is expected that handlers will keep a reference to it. The main purpose of the <code>*Conn</code> is to write data via <code>conn.write([]const u8)</code> and <code>conn.writeBin([]const u8)</code>. The websocket protocol differentiates between a "text" and "binary" message, with the only difference that "text" must be valid UTF-8. This library does not enforce this. Which you use really depends on what your client expects. For browsers, text messages appear as strings, and binary messages appear as a Blob or ArrayBuffer (depending on how the client is configured).
<code>conn.close(.{})</code> can also be called to close the connection. Calling <code>conn.close()</code> <strong>will</strong> result in the handler's <code>close</code> callback being called.
<code>close</code> takes an optional value where you can specify the <code>code</code> and/or <code>reason</code>: <code>conn.close(.{.code = 4000, .reason = "bye bye"})</code> Refer to <a>RFC6455</a> for valid codes. The <code>reason</code> must be <= 123 bytes.
Writer
It's possible to get a <code>std.io.Writer</code> from a <code>*Conn</code>. Because websocket messages are framed, the writter will buffer the message in memory and requires an explicit "flush". Buffering requires an allocator.
<code>zig
// .text or .binary
var wb = conn.writeBuffer(allocator, .text);
defer wb.deinit();
try std.fmt.format(wb.writer(), "it's over {d}!!!", .{9000});
try wb.flush();</code>
Consider using the <code>clientMessage</code> overload which accepts an allocator. Not only is this allocator fast (it's a thread-local buffer than fallsback to an arena), but it also eliminates the need to call <code>deinit</code>:
<code>``zig
pub fn clientMessage(h: *Handler, allocator: Allocator, data: []const u8) !void {
// Use the provided allocator.
// It's faster and doesn't require</code>deinit` to be called
<code>var wb = conn.writeBuffer(allocator, .text);
try std.fmt.format(wb.writer(), "it's over {d}!!!", .{9000});
try wb.flush();
</code>
}
```
Thread Safety
Websocket.zig ensures that only 1 message per connection/handler is processed at a time. Therefore, you will never have concurrent calls to <code>clientMessage</code>, <code>clientPing</code>, <code>clientPong</code> or <code>clientClose</code>. Conversely, concurrent calls to methods of <code>*websocket.Conn</code> are allowed (i.e. <code>conn.write</code> and <code>conn.close</code>).
Config
The 2nd parameter to <code>Server(H).init</code> is a configuration object.
```zig
pub const Config = struct {
port: u16 = 9882,
<code>// Ignored if unix_path is set
address: []const u8 = "127.0.0.1",
// Not valid on windows
unix_path: ?[]const u8 = null,
// In nonblocking mode (Linux/Mac/BSD), sets the number of
// listening threads. Defaults to 1.
// In blocking mode, this is ignored and always set to 1.
worker_count: ?u8 = null,
// The maximum number of connections, per worker.
// default: 16_384
max_conn: ?usize = null,
// The maximium allows message size.
// A websocket message can have up to 14 bytes of overhead/header
// Default: 65_536
max_message_size: ?usize = null,
handshake: Config.Handshake = .{},
thread_pool: ThreadPool = .{},
buffers: Config.Buffers = .{},
// compression is disabled by default
compression: ?Compression = null,
// In blocking mode the thread pool isn't used
pub const ThreadPool = struct {
// Number of threads to process messages.
// These threads are where your `clientXYZ` method will execute.
// Default: 4.
count: ?u16 = null,
// The maximum number of pending requests that the thread pool will accept
// This applies back pressure to worker and ensures that, under load
// pending requests get precedence over processing new requests.
// Default: 500.
backlog: ?u32 = null,
// Size of the static buffer to give each thread. Memory usage will be
// `count * buffer_size`.
// If clientMessage isn't defined with an Allocator, this defaults to 0.
// Else it default to 32768
buffer_size: ?usize = null,
};
const Handshake = struct {
// time, in seconds, to timeout the initial handshake request
timeout: u32 = 10,
// Max size, in bytes, allowed for the initial handshake request.
// If you're expected a large handshake (many headers, large cookies, etc)
// you'll need to set this larger.
// Default: 1024
max_size: ?u16 = null,
// Max number of headers to capture. These become available as
// handshake.headers.get(...).
// Default: 0
max_headers: ?u16 = null,
// Count of handshake objects to keep in a pool. More are created
// as needed.
// Default: 32
count: ?u16 = null,
};
const Buffers = struct {
// The number of "small" buffers to keep pooled.
//
// When `null`, the small buffer pool is disabled and each connection
// gets its own dedicated small buffer (of `size`). This is reasonable
// when you expect most clients to be sending a steady stream of data.
// When set > 0, a pool is created (of `size` buffers) and buffers are
// assigned as messages are received. This is reasonable when you expect
// sporadic and messages from clients.
//
// Default: `null`
small_pool: ?usize = null,
// The size of each "small" buffer. Depending on the value of `pool`
// this is either a per-connection buffer, or the size of pool buffers
// shared between all connections
// Default: 2048
small_size: ?usize = null,
// The number of large buffers to have in the pool.
// Messages larger than `buffers.small_size` but smaller than `max_message_size`
// will attempt to use a large buffer from the pool.
// If the pool is empty, a dynamic buffer is created.
// Default: 8
large_pool: ?u16 = null,
// The size of each large buffer.
// Default: min(2 * buffers.small_size, max_message_size)
large_size: ?usize = null,
};
// Compression is disabled by default, to enable it and accept the default
// values, set it to a defautl struct: .{}
const Compression = struct {
// The mimimum size of data before messages will be compressed
// null = message are never compressed when writing messages to the client
// If you want to enable compression, 512 is a reasonable default
write_threshold: ?usize = null,
// When compression is enable, and write_treshold != null, every connection
// gets an std.ArrayList(u8) to write the compressed message to. When this
// is true, the memory allocated to the ArrayList is kept for subsequent
// messages (i.e. it calls `clearRetainingCapacity`). When false, the memory
// is freed after each message.
// true = more memory, but fewer allocations
retain_write_buffer: bool = true,
// Advanced options that are part of the permessage-deflate specification.
// You can set these to true to try and save a bit of memory. But if you
// want to save memory, don't use compression at all.
client_no_context_takeover: bool = false,
server_no_context_takeover: bool = false,
};
</code>
}
```
Logging
websocket.zig uses Zig's built-in scope logging. You can control the log level by having an <code>std_options</code> decleration in your program's main file:
<code>zig
pub const std_options = std.Options{
.log_scope_levels = &[_]std.log.ScopeLevel{
.{ .scope = .websocket, .level = .err },
}
};</code>
Advanced
Pre-Framed Comptime Message
Websocket message have their own special framing. When you use <code>conn.write</code> or <code>conn.writeBin</code> the data you provide is "framed" into a correct websocket message. Framing is fast and cheap (e.g., it DOES NOT require an O(N) loop through the data). Nonetheless, there may be be cases where pre-framing messages at compile-time is desired. The <code>websocket.frameText</code> and <code>websocket.frameBin</code> can be used for this purpose:
```zig
const UNKNOWN_COMMAND = websocket.frameText("unknown command");
...
pub fn clientMessage(self: *Handler, data: []const u8) !void {
if (std.mem.startsWith(u8, data, "join: ")) {
self.handleJoin(data)
} else if (std.mem.startsWith(u8, data, "leave: ")) {
self.handleLead(data)
} else {
try self.conn.writeFramed(UNKNOWN_COMMAND);
}
}
```
Blocking Mode
kqueue (BSD, MacOS) or epoll (Linux) are used on supported platforms. On all other platforms (most notably Windows), a more naive thread-per-connection with blocking sockets is used.
The comptime-safe, <code>websocket.blockingMode() bool</code> function can be called to determine which mode websocket is running in (when it returns <code>true</code>, then you're running the simpler blocking mode).
Per-Connection Buffers
In non-blocking mode, the <code>buffers.small_pool</code> and <code>buffers.small_size</code> should be set for your particular use case. When <code>buffers.small_pool == null</code>, each connection gets its own buffer of <code>buffers.small_size</code> bytes. This is a good option if you expect most of your clients to be sending a steady stream of data. While it might take more memory (# of connections * buffers.small_size), its faster and minimizes multi-threading overhead.
However, if you expect clients to only send messages sporadically, such as a chat application, enabling the pool can reduce memory usage at the cost of a bit of overhead.
In blocking mode, these settings are ignored and each connection always gets its own buffer (though there is still a shared large buffer pool).
Stopping
<code>server.stop()</code> can be called to stop the webserver. It is safe to call this from a different thread (i.e. a <code>sigaction</code> handler).
Testing
The library comes with some helpers for testing.
```zig
const wt = @import("websocket").testing;
test "handler: echo" {
var wtt = wt.init();
defer wtt.deinit();
<code>// create an instance of your handler (however you want)
// and use &tww.conn as the *ws.Conn field
var handler = Handler{
.conn = &wtt.conn,
};
// execute the methods of your handler
try handler.clientMessage("hello world");
// assert what the client should have received
try wtt.expectMessage(.text, "hello world");
</code>
}
```
Besides <code>expectMessage</code> you can also call <code>expectClose()</code>.
Note that this testing is heavy-handed. It opens up a pair of sockets with one side listening on <code>127.0.0.1</code> and accepting a connection from the other. <code>wtt.conn</code> is the "server" side of the connection, and assertion happens on the client side.
Client
The <code>*websocket.Client</code> can be used in one of two ways. At its simplest, after creating a client and initiating a handshake, you simply use <code>write</code> to send messages and <code>read</code> to receive them. First, we create the client and initiate the handshake:
```zig
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
// create the client
var client = try websocket.Client.init(allocator, .{
.port = 9224,
.host = "localhost",
});
defer client.deinit();
// send the initial handshake request
const request_path = "/ws";
try client.handshake(request_path, .{
.timeout_ms = 1000,
// Raw headers to send, if any.
// A lot of servers require a Host header.
// Separate multiple headers using \r\n
.headers = "Host: localhost:9224",
});
}
```
We can then use <code>read</code> and <code>write</code>. By default, <code>read</code> blocks until a message is received (or an error occurs). We can make it return <code>null</code> by setting a timeout:
```zig
// optional, read will return null after 1 second
try client.readTimeout(std.time.ms_per_s * 1);
// echo messages back to the server until the connection is closed
while (true) {
// since we didn't set a timeout, client.read() will either
// return a message or an error (i.e. it won't return null)
const message = (try client.read()) orelse {
// no message after our 1 second
std.debug.print(".", .{});
continue;
};
<code>// must be called once you're done processing the request
defer client.done(message);
switch (message.type) {
.text, .binary => {
std.debug.print("received: {s}\n", .{message.data});
try client.write(message.data);
},
.ping => try client.writePong(message.data),
.pong => {},
.close => {
try client.close(.{});
break;
}
}
</code>
}
}
```
Config
When creating a Client, the 2nd parameter is a configuration object:
<ul>
<li><code>port</code> - The port to connect to. Required.</li>
<li><code>host</code> - The host/IP address to connect to. The Host:IP value IS NOT automatically put in the header of the handshake request. Required.</li>
<li><code>max_size</code> - Maximum incoming message size to allow. The library will dynamically allocate up to this much space per request. Default: <code>65536</code>.</li>
<li><code>buffer_size</code> - Size of the static buffer that's available for the client to process incoming messages. While there's other overhead, the minimal memory usage of the server will be <code># of active clients * buffer_size</code>. Default: <code>4096</code>.</li>
<li><code>tls</code> - Whether or not to connect over TLS. Only TLS 1.3 is supported. Default: <code>false</code>.</li>
<li><code>ca_bundle</code> - Provide a custom <code>std.crypto.Certificate.Bundle</code>. Only meaningful when <code>tls = true</code>. Default: <code>null</code>.</li>
</ul>
Setting <code>max_size == buffer_size</code> is valid and will ensure that no dynamic memory allocation occurs once the connection is established.
Zig only supports TLS 1.3, so this library can only connect to hosts using TLS 1.3. If no <code>ca_bundle</code> is provided, the library will create a default bundle per connection.
Handshake
<code>client.handshake()</code> takes two parameters. The first is the request path. The second is handshake configuration value:
<ul>
<li><code>timeout_ms</code> - Timeout, in milliseconds, for the handshake. Default: <code>10_000</code> (10 seconds).</li>
<li><code>headers</code> - Raw headers to include in the handshake. Multiple headers should be separated by by "\r\n". Many servers require a Host header. Example: <code>"Host: server\r\nAuthorization: Something"</code>. Defaul: <code>null</code></li>
</ul>
Custom Wrapper
In more advanced cases, you'll likely want to wrap a <code>*ws.Client</code> in your own type and use a background read loop with "callback" methods. Like in the above example, you'll first want to create a client and initialize a handshake:
```zig
const ws = @import("websocket");
const Handler = struct {
client: ws.Client,
fn init(allocator: std.mem.Allocator) !Handler {
var client = try ws.Client.init(allocator, .{
.port = 9224,
.host = "localhost",
});
defer client.deinit();
<code> // send the initial handshake request
const request_path = "/ws";
try client.handshake(request_path, .{
.timeout_ms = 1000,
.headers = "host: localhost:9224\r\n",
});
return .{
.client = client,
};
</code>
}
```
You can then call <code>client.readLoopInNewThread()</code> to start a background listener. Your handler must define a <code>serverMessage</code> method:
```zig
pub fn startLoop(self: *Handler) !void {
// use readLoop for a blocking version
const thread = try self.client.readLoopInNewThread(self);
thread.detach();
}
pub fn serverMessage(self: *Handler, data: []u8) !void {
// echo back to server
return self.client.write(data);
}
}
```
Websockets have a number of different message types. <code>serverMessage</code> only receives text and binary messages. If you care about the distinction, you can use an overload:
<code>zig
pub fn serverMessage(self: *Handler, data: []u8, tpe: ws.MessageTextType) !void</code>
where <code>tpe</code> will be either <code>.text</code> or <code>.binary</code>. Different callbacks are used for the other message types.
Optional Callbacks
In addition to the required <code>serverMessage</code>, you can define optional callbacks.
```zig
// Guaranteed to be called exactly once when the readLoop exits
pub fn close(self: *Handler) void
// If omitted, websocket.zig will automatically reply with a pong
pub fn serverPing(self: *Handler, data: []u8) !void
// If omitted, websocket.zig will ignore this message
pub fn serverPong(self: *Handler) !void
// If omitted, websocket.zig will automatically reply with a close message
pub fn serverClose(self: *Handler) !void
```
You almost certainly <strong>do not</strong> want to define a <code>serverClose</code> method, but instead what do define a <code>close</code> method. In your <code>close</code> callback, you should call <code>client.close(.{})</code> (and optionally pass a code and reason).
Client
Whether you're calling <code>client.read()</code> explicitly or using <code>client.readLoopInNewThread()</code> (or <code>client.readLoop()</code>), the <code>client</code> API is the same. In both cases, the various <code>write</code> methods, as well as <code>close()</code> are thread-safe.
Writing
It may come as a surprise, but every variation of <code>write</code> expects a <code>[]u8</code>, not a <code>[]const u8</code>. Websocket payloads sent from a client need to be masked, which the websocket.zig library handles. It is obviously more efficient to mutate the given payload versus creating a copy. By taking a <code>[]u8</code>, applications with mutable buffers benefit from avoiding the clone. Applications that have immutable buffers will need to create a mutable clone.
```zig
// write a text message
pub fn write(self: *Client, data: []u8) !void
// write a text message (same as client.write(data))
pub fn writeText(self: *Client, data: []u8) !void
// write a binary message
pub fn writeBin(self: *Client, data: []u8) !void
// write a ping message
pub fn writePing(self: *Client, data: []u8) !void
// write a pong message
// if you don't define a handlePong message, websocket.zig
// will automatically answer any ping with a pong
pub fn writePong(self: *Client, data: []u8) !void
// lower-level, use by all of the above
pub fn writeFrame(self: *Client, op_code: proto.OpCode, data: []u8) !void
```
Reading
As seen above, most applications will either chose to call <code>read()</code> explicitly or use a <code>readLoop</code>. It is *<em>not safe</em> to call <code>read</code> while the read loop is running.
<code>``zig
// Reads 1 message. Returns null on timeout
// Set a timeout using</code>client.readTimeout(ms)`
pub fn read(self: *Client) !?ws.Message
// Starts a readloop in the calling thread.
// <code>@TypeOf(handler)</code> must define the <code>serverMessage</code> callback
// (and may define other optional callbacks)
pub fn readLoop(self: *Client, handler: anytype) !void
// Same as <code>readLoop</code> but starts the readLoop in a new thread
pub fn readLoopInNewThread(self: *Client, h: anytype) !std.Thread
```
Closing
Use <code>try client.close(.{.code = 4000, .reason = "bye"})</code> to both send a close frame and close the connection. Noop if the connection is already known to be close. Thread safe.
Both <code>code</code> and <code>reason</code> are optional. Refer to <a>RFC6455</a> for valid codes. The <code>reason</code> must be <= 123 bytes.
Performance Optimization 1 - CA Bundle
For a high number of connections, it might be beneficial to manage our own CA bundle:
<code>zig
// some global data
var ca_bundle = std.crypto.Certificate.Bundle{}
try ca_bundle.rescan(allocator);
defer ca_bundle.deinit(allocator);</code>
And then assign this <code>ca_bundle</code> into the the configuration's <code>ca_bundle</code> field. This way the library does not have to create and scan the installed CA certificates for each client connection.
Performance Optimization 2 - Buffer Provider
For a high nummber of connections a large buffer pool can be created and provided to each client:
```zig
// Create a buffer pool of 10 buffers, each being 32K
const buffer_provider = try websocket.bufferProvider(allocator, 10, 32768);
defer buffer_provider.deinit();
// create your client(s) using the above created buffer_provider
var client = try websocket.connect(allocator, "localhost", 9001, .{
...
.buffer_provider = buffer_provider,
});
```
This allows each client to have a reasonable <code>buffer_size</code> that can accomodate most messages, while having an efficient fallback for the occasional large message. When <code>max_size</code> is greater than the large buffer pool size (32K in the above example) or when all pooled buffers are used, a dynamic buffer is created. | [] |
https://avatars.githubusercontent.com/u/7967463?v=4 | ziglua | natecraddock/ziglua | 2022-06-02T04:37:17Z | Zig bindings for the Lua C API | main | 24 | 360 | 52 | 360 | https://api.github.com/repos/natecraddock/ziglua/tags | MIT | [
"binding",
"library",
"lua",
"lua-bindings",
"package",
"zig",
"zig-package"
] | 1,517 | false | 2025-05-20T09:08:27Z | true | true | unknown | github | [
{
"commit": null,
"name": "lua51",
"tar_url": null,
"type": "remote",
"url": "https://www.lua.org/ftp/lua-5.1.5.tar.gz"
},
{
"commit": null,
"name": "lua52",
"tar_url": null,
"type": "remote",
"url": "https://www.lua.org/ftp/lua-5.2.4.tar.gz"
},
{
"commit": null,
... | Ziglua
<a></a>
<a></a>
Zig bindings for the <a>Lua C API</a>. Ziglua currently supports the latest releases of Lua 5.1, 5.2, 5.3, 5.4, and <a>Luau</a>.
Ziglua can be used in two ways, either
* <strong>embedded</strong> to statically embed the Lua VM in a Zig program,
* or as a shared <strong>module</strong> to create Lua libraries that can be loaded at runtime in other Lua-based software.
In both cases, Ziglua will compile Lua from source and link against your Zig code making it easy to create software that integrates with Lua without requiring any system Lua libraries.
Ziglua <code>main</code> is kept up to date with Zig <code>master</code>. See the <a><code>zig-0.13.0</code></a> branch for Zig 0.13.0 support.
Documentation
Docs are a work in progress and are automatically generated. Most functions and public declarations are documented:
* <a>Ziglua Docs</a>
See <a>docs.md</a> for more general information on Ziglua and how it differs from the C API.
Example code is included in the <a>examples</a> directory.
* Run an example with <code>zig build run-example-<name></code>
* Install an example with <code>zig build install-example-<name></code>
Why use Ziglua?
In a nutshell, Ziglua is a simple wrapper around the C API you would get by using Zig's <code>@cImport()</code>. Ziglua aims to mirror the <a>Lua C API</a> as closely as possible, while improving ergonomics using Zig's features. For example:
<ul>
<li>Zig error unions to require failure state handling</li>
<li>Null-terminated slices instead of C strings</li>
<li>Type-checked enums for parameters and return values</li>
<li>Compiler-enforced checking of optional pointers</li>
<li>Better types in many cases (e.g. <code>bool</code> instead of <code>int</code>)</li>
<li>Comptime convenience functions to make binding creation easier</li>
</ul>
Nearly every function in the C API is exposed in Ziglua. Additional convenience functions like <code>toAny</code> and <code>pushAny</code> use comptime reflection to make the API easier to use.
Integrating Ziglua in your project
Run <code>zig fetch --save git+https://github.com/natecraddock/ziglua</code> to add the most recent commit of ziglua to your <code>build.zig.zon</code> file.
Add a <code>#<tag></code> to the url to use a specific tagged release or commit like <code>zig fetch --save git+https://github.com/natecraddock/ziglua#0.3.0</code>
Then in your <code>build.zig</code> file you can use the dependency.
```zig
pub fn build(b: *std.Build) void {
// ... snip ...
<code>const lua_dep = b.dependency("zlua", .{
.target = target,
.optimize = optimize,
});
// ... snip ...
// add the zlua module and lua artifact
exe.root_module.addImport("zlua", lua_dep.module("zlua"));
</code>
}
```
This will compile the Lua C sources and link with your project.
There are currently three additional options that can be passed to <code>b.dependency()</code>:
<ul>
<li><code>.lang</code>: Set the Lua language to build and embed. Defaults to <code>.lua54</code>. Possible values are <code>.lua51</code>, <code>.lua52</code>, <code>.lua53</code>, <code>.lua54</code>, and <code>luau</code>.</li>
<li><code>.shared</code>: Defaults to <code>false</code> for embedding in a Zig program. Set to <code>true</code> to dynamically link the Lua source code (useful for creating shared modules).</li>
<li><code>luau_use_4_vector</code>: defaults to false. Set to true to use 4-vectors instead of the default 3-vector in Luau.</li>
</ul>
For example, here is a <code>b.dependency()</code> call that and links against a shared Lua 5.2 library:
```zig
const zlua = b.dependency("zlua", .{
.target = target,
.optimize = optimize,
.lang = .lua52,
.shared = true,
});
``````
The <code>zlua</code> module will now be available in your code. Here is a simple example that pushes and inspects an integer on the Lua stack:
```zig
const std = @import("std");
const zlua = @import("zlua");
const Lua = zlua.Lua;
pub fn main() anyerror!void {
// Create an allocator
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
defer _ = gpa.deinit();
<code>// Initialize the Lua vm
var lua = try Lua.init(allocator);
defer lua.deinit();
// Add an integer to the Lua stack and retrieve it
lua.pushInteger(42);
std.debug.print("{}\n", .{try lua.toInteger(1)});
</code>
}
```
Contributing
Please make suggestions, report bugs, and create pull requests. Anyone is welcome to contribute!
I only use a subset of the Lua API through Ziglua, so if there are parts that aren't easy to use or understand, please fix it yourself or let me know!
Thank you to the <a>Lua</a> team for creating such a great language! | [
"https://github.com/JacobCrabill/zigdown"
] |
https://avatars.githubusercontent.com/u/49629865?v=4 | aftersun | foxnne/aftersun | 2022-08-20T20:10:55Z | Top-down 2D RPG | main | 3 | 262 | 9 | 262 | https://api.github.com/repos/foxnne/aftersun/tags | MIT | [
"2d",
"gamedev",
"rpg",
"topdown",
"zig"
] | 15,712 | false | 2025-05-05T02:01:44Z | true | true | unknown | github | [
{
"commit": null,
"name": "mach",
"tar_url": null,
"type": "remote",
"url": "https://pkg.machengine.org/mach/b72f0e11b6d292c2b60789359a61f7ee6d7dc371.tar.gz"
},
{
"commit": "d5790495da5ec0282aa65e7eecf541f951afb44f.tar.gz",
"name": "zig_imgui",
"tar_url": "https://github.com/foxn... |
An ongoing pet-project top-down RPG written in <a>zig</a>.
Installation
<ul>
<li>Build with Zig 0.12.0-dev.3180+83e578a18 (<code>zigup 0.12.0-dev.3180+83e578a18</code>). This is required by Mach, see https://machengine.org/about/zig-version </li>
</ul>
<code>git clone git@github.com:foxnne/aftersun.git --recurse-submodules
cd aftersun
zig build run</code>
Credits
<a>flecs</a>
<a>zig-gamedev</a>
<a>mach-core</a> | [] |
https://avatars.githubusercontent.com/u/196310?v=4 | raylib.zig | ryupold/raylib.zig | 2022-04-06T21:03:44Z | Idiomatic Zig bindings for raylib utilizing raylib_parser | main | 12 | 246 | 35 | 246 | https://api.github.com/repos/ryupold/raylib.zig/tags | MIT | [
"bindings",
"raylib",
"zig"
] | 2,273 | false | 2025-05-20T19:58:07Z | true | false | unknown | github | [] |
raylib.zig
Idiomatic <a>raylib</a> (5.1-dev) bindings for <a>Zig</a> (master).
<a>Example Usage</a>
Additional infos and WebGL examples <a>here</a>.
supported platforms
<ul>
<li>Windows</li>
<li>macOS</li>
<li>Linux</li>
<li>HTML5/WebGL (emscripten)</li>
</ul>
supported APIs
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> RLAPI (raylib.h)
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> RLAPI (rlgl.h)
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> RMAPI (raymath.h)
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Constants
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> int, float, string
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Colors
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Versions
For <a>raygui</a> bindings see: https://github.com/ryupold/raygui.zig
<a>usage</a>
The easy way would be adding this as submodule directly in your source folder.
Thats what I do until there is an official package manager for Zig.
<code>sh
cd $YOUR_SRC_FOLDER
git submodule add https://github.com/ryupold/raylib.zig raylib
git submodule update --init --recursive</code>
The bindings have been prebuilt so you just need to add raylib as module
build.zig:
```zig
const raylib = @import("path/to/raylib.zig/build.zig");
pub fn build(b: *std.Build) !void {
const target = b.standardTargetOptions(.{});
const mode = b.standardOptimizeOption(.{});
const exe = ...;
raylib.addTo(b, exe, target, mode, .{});
}
```
and import in main.zig:
```zig
const raylib = @import("raylib");
pub fn main() void {
raylib.SetConfigFlags(raylib.ConfigFlags{ .FLAG_WINDOW_RESIZABLE = true });
raylib.InitWindow(800, 800, "hello world!");
raylib.SetTargetFPS(60);
<code>defer raylib.CloseWindow();
while (!raylib.WindowShouldClose()) {
raylib.BeginDrawing();
defer raylib.EndDrawing();
raylib.ClearBackground(raylib.BLACK);
raylib.DrawFPS(10, 10);
raylib.DrawText("hello world!", 100, 100, 20, raylib.YELLOW);
}
</code>
}
```
WebGL (emscripten) builds
For Webassembly builds see <a>examples-raylib.zig/build.zig</a>
This weird workaround with <code>marshal.h/marshal.c</code> I actually had to make for Webassembly builds to work, because passing structs as function parameters or returning them cannot be done on the Zig side somehow. If I try it, I get a runtime error "index out of bounds". This happens only in WebAssembly builds. So <code>marshal.c</code> must be compiled with <code>emcc</code>. See <a>build.zig</a> in the examples.
custom definitions
An easy way to fix binding mistakes is to edit them in <code>bindings.json</code> and setting the custom flag to true. This way the binding will not be overriden when calling <code>zig build intermediate</code>.
Additionally you can add custom definitions into <code>inject.zig, inject.h, inject.c</code> these files will be prepended accordingly.
disclaimer
I have NOT tested most of the generated functions, so there might be bugs. Especially when it comes to pointers as it is not decidable (for the generator) what a pointer to C means. Could be single item, array, sentinel terminated and/or nullable. If you run into crashes using one of the functions or types in <code>raylib.zig</code> feel free to <a>create an issue</a> and I will look into it.
memory
Some of the functions may return pointers to memory allocated within raylib.
Usually there will be a corresponding Unload/Free function to dispose it. You cannot use a Zig allocator to free that:
```zig
const data = LoadFileData("test.png");
defer UnloadFileData(data);
// using data...
```
generate bindings
for current raylib source (submodule)
<code>sh
zig build parse # create JSON files with raylib_parser
zig build intermediate # generate bindings.json (keeps definitions with custom=true)
zig build bindings # write all intermediate bindings to raylib.zig</code>
For easier diffing and to follow changes to the raylib repository I commit also the generated json files.
build raylib_parser (executable)
If you want to build the raylib_parser executable without a C compiler.
<code>sh
zig build raylib_parser</code>
you can then find the executable in <code>./zig-out/bin/</code> | [] |
https://avatars.githubusercontent.com/u/20487725?v=4 | Zig | TheAlgorithms/Zig | 2022-12-27T18:02:19Z | Collection of Algorithms implemented in Zig. | main | 1 | 241 | 42 | 241 | https://api.github.com/repos/TheAlgorithms/Zig/tags | MIT | [
"algorithms",
"data-structures",
"dynamic-programming",
"interview-questions",
"learning",
"math",
"mathematics",
"search",
"sorting",
"sorting-algorithms",
"zig",
"ziglang"
] | 87 | false | 2025-05-19T08:29:20Z | true | true | 0.14.0 | github | [
{
"commit": null,
"name": "runner",
"tar_url": null,
"type": "remote",
"url": "git+https://gist.github.com/karlseguin/c6bea5b35e4e8d26af6f81c22cb5d76b/#1f317ebc9cd09bc50fd5591d09c34255e15d1d85"
}
] |
<a></a>
<a>The Algorithms</a> - Zig
<a>
</a>
<a>
</a>
Collection of algorithms implemented in Zig - for education
Resources
Learn
<ul>
<li><a>Introduction | ZigLang.org</a></li>
<li><a>Download & Documentation | ZigLang.org</a></li>
<li><a>Chapter 0 - Getting Started | ZigLearn.org</a></li>
<li><a>Frequently Asked Questions | ZigLang/Wiki</a></li>
</ul>
#### Project
<ul>
<li><a>Algorithms</a></li>
<li><a>Contributing</a></li>
<li><a>Code of Conduct</a></li>
</ul>
How to build
<strong>Require:</strong>
- <a>Zig v0.14 or higher</a>, self-hosting (stage3) compiler.
Test all
Run:
<code>bash
$> sh runall.sh</code> | [] |
https://avatars.githubusercontent.com/u/146390816?v=4 | ffmpeg | allyourcodebase/ffmpeg | 2023-01-08T01:31:26Z | FFmpeg Zig package | main | 7 | 217 | 35 | 217 | https://api.github.com/repos/allyourcodebase/ffmpeg/tags | NOASSERTION | [
"ffmpeg",
"zig",
"zig-package"
] | 169,081 | false | 2025-05-17T16:27:17Z | true | true | 0.14.0 | github | [
{
"commit": "6c72830882690c1eb2567a537525c3f432c1da50.tar.gz",
"name": "libz",
"tar_url": "https://github.com/allyourcodebase/zlib/archive/6c72830882690c1eb2567a537525c3f432c1da50.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/allyourcodebase/zlib"
},
{
"commit": "7d862fe61... | FFmpeg Packaged for Zig
This is a fork of <a>ffmpeg</a>, packaged for Zig. Unnecessary
files have been deleted, and the build system has been replaced with
<code>build.zig</code>.
There are no system dependencies; the only thing required to build this package
is <a>Zig</a>.
Zig API bindings are also provided via the "av" module. See <code>doc/examples</code> for
API usage examples.
Differences from Upstream
<ul>
<li>Only a single static library is produced. There is no option to create a
dynamic library.</li>
<li>The ffmpeg command line tool is not provided. Perhaps this could be added if
desired.</li>
<li>Documentation, tests, and tools are not provided.</li>
<li>This package enables everything supported by the target; it does not expose
configuration options to choose the set of supported codecs and formats.</li>
<li>The set of external library integrations is fixed.</li>
</ul>
External Libraries Included
<ul>
<li>[x] libmp3lame</li>
<li>[x] libvorbis</li>
<li>[x] libogg</li>
</ul>
More can be added as desired.
Update Process
These are the instructions to update this package when a new FFmpeg version is
released upstream.
<ol>
<li>Merge the new tag into main and resolve all conflicts by replacing the
conflicting files with the files from upstream.</li>
<li><code>find libavcodec/ libavdevice/ libavfilter/ libavformat libavutil/ libswscale/ libswresample/ -type f -name "*.asm" -o -name "*.c" -o -name "*.S"</code></li>
<li>Edit to omit files ending in <code>_template.c</code> or <code>_tablegen.c</code></li>
<li>Sort the list</li>
<li>Update the <code>all_sources</code> list in <code>build.zig</code>.</li>
<li>Inspect the git diff to keep some of the source files commented out like
they were before. Some handy filtering rules apply:</li>
<li><code>/L</code> prefix means Linux-only</li>
<li><code>/W</code> prefix means Windows-only</li>
<li>Run <code>./configure --prefix=$HOME/local/ffmpeg --disable-doc --disable-htmlpages --disable-manpages --disable-podpages --disable-txtpages --disable-programs --enable-libmp3lame --enable-libvorbis --disable-shared --enable-static</code>
against upstream and diff the generated <code>config.h</code> file to the one generated
by this build script. Apply appropriate changes to <code>build.zig</code>.</li>
<li>Update these files which are generated by the upstream configure script:</li>
<li><code>config_components.h</code></li>
<li><code>libavfilter/filter_list.c</code></li>
<li><code>libavcodec/codec_list.c</code></li>
<li><code>libavcodec/parser_list.c</code></li>
<li><code>libavcodec/bsf_list.c</code></li>
<li><code>libavformat/demuxer_list.c</code></li>
<li><code>libavformat/muxer_list.c</code></li>
<li><code>libavdevice/indev_list.c</code></li>
<li><code>libavdevice/outdev_list.c</code></li>
<li><code>libavformat/protocol_list.c</code></li>
<li>Update the <code>headers</code> list in <code>build.zig</code> based on what files are present in
<code>$HOME/local/ffmpeg/include</code>.</li>
</ol> | [
"https://github.com/neurocyte/notcurses-zig"
] |
https://avatars.githubusercontent.com/u/473672?v=4 | nanovg-zig | fabioarnold/nanovg-zig | 2022-04-03T20:47:06Z | A small anti-aliased hardware-accelerated vector graphics library | main | 1 | 209 | 23 | 209 | https://api.github.com/repos/fabioarnold/nanovg-zig/tags | Zlib | [
"2d",
"gamedev",
"graphics",
"opengl",
"vector",
"vector-graphics",
"zig",
"zig-package"
] | 2,242 | false | 2025-05-18T07:36:09Z | true | true | 0.11.0 | github | [] | NanoVG - Zig Version
This is a rewrite of the original <a>NanoVG library</a> using the <a>Zig programming language</a>.
NanoVG is a small anti-aliased hardware-accelerated vector graphics library. It has a lean API modeled after the HTML5 canvas API. It is aimed to be a practical and fun toolset for building scalable user interfaces or any other real time visualizations.
Screenshot
Examples
There's a WebAssembly example using WebGL which you can immediately try here: https://fabioarnold.github.io/nanovg-zig. The source for this example can be found in <a>example_wasm.zig</a> and can be built by running <code>zig build -Dtarget=wasm32-freestanding</code>.
A native cross-platform example using <a>GLFW</a> can be found in <a>example_glfw.zig</a> and can be built and run with <code>zig build run</code>. It requires GLFW to be installed. On Windows <a>vcpkg</a> is an additional requirement.
For an example on how to use nanovg-zig in your project's <code>build.zig</code> you can take a look at https://github.com/fabioarnold/MiniPixel/blob/main/build.zig.
Features
<ul>
<li>Basic shapes: rect, rounded rect, ellipse, arc</li>
<li>Arbitrary paths of bezier curves with holes</li>
<li>Arbitrary stack-based 2D transforms</li>
<li>Strokes with different types of caps and joins</li>
<li>Fills with gradient support</li>
<li>Types of gradients: linear, box (useful for shadows), radial</li>
<li>Text with automatic linebreaks and blurring</li>
<li>Images as pattern for fills and strokes</li>
</ul>
Features exclusive to the Zig version
<ul>
<li>Clip paths</li>
<li>Image blurring</li>
</ul>
Usage
The NanoVG API is modeled loosely on the HTML5 canvas API. If you know canvas, you're up to speed with NanoVG in no time.
Creating a drawing context
The drawing context is created using a backend-specific initialization function. If you're using the OpenGL backend the context is created as follows:
<code>zig
const nvg = @import("nanovg");
...
var vg = try nvg.gl.init(allocator, .{
.debug = true,
});
defer vg.deinit();</code>
The second parameter defines options for creating the renderer.
<ul>
<li><code>antialias</code> means that the renderer adjusts the geometry to include anti-aliasing. If you're using MSAA, you can omit this option to be default initialized as false.</li>
<li><code>stencil_strokes</code> means that the render uses better quality rendering for (overlapping) strokes. The quality is mostly visible on wider strokes. If you want speed, you can omit this option to be default initialized as false.</li>
</ul>
Currently, there is an OpenGL backend for NanoVG: <a>nanovg_gl.zig</a> for OpenGL 2.0 and WebGL. WebGL is automatically chosen when targeting WebAssembly. There's an interface called <code>Params</code> defined in <a>internal.zig</a>, which can be implemented by additional backends.
<em>NOTE:</em> The render target you're rendering to must have a stencil buffer.
Drawing shapes with NanoVG
Drawing a simple shape using NanoVG consists of four steps:
1) begin a new shape,
2) define the path to draw,
3) set fill or stroke,
4) and finally fill or stroke the path.
<code>zig
vg.beginPath();
vg.rect(100,100, 120,30);
vg.fillColor(nvg.rgba(255,192,0,255));
vg.fill();</code>
Calling <code>beginPath()</code> will clear any existing paths and start drawing from a blank slate. There are a number of functions to define the path to draw, such as rectangle, rounded rectangle and ellipse, or you can use the common moveTo, lineTo, bezierTo and arcTo API to compose a path step-by-step.
Understanding Composite Paths
Because of the way the rendering backend is built in NanoVG, drawing a composite path - that is a path consisting of multiple paths defining holes and fills - is a bit more involved. NanoVG uses the even-odd filling rule and by default the paths are wound in counterclockwise order. Keep that in mind when drawing using the low-level drawing API. In order to wind one of the predefined shapes as a hole, you should call <code>pathWinding(nvg.Winding.solidity(.hole))</code>, or <code>pathWinding(.cw)</code> <strong><em>after</em></strong> defining the path.
<code>zig
vg.beginPath();
vg.rect(100,100, 120,30);
vg.circle(120,120, 5);
vg.pathWinding(.cw); // Mark circle as a hole.
vg.fillColor(nvg.rgba(255,192,0,255));
vg.fill();</code>
Building a Program with nanovg-zig
Here's how to integrate <code>nanovg-zig</code> into your Zig project:
<ol>
<li>
<strong>Add the library as a dependency:</strong>
Run the following command in your project directory to fetch and save <code>nanovg-zig</code> as a dependency:
<code>bash
zig fetch --save git+https://github.com/fabioarnold/nanovg-zig.git</code>
</li>
<li>
<strong>Import the library in your <code>build.zig</code> file:</strong>
Add the following code snippet to your <code>build.zig</code> file. This creates a dependency on <code>nanovg-zig</code> and imports the <code>nanovg</code> module into your executable:
<code>zig
const nanovg_zig = b.dependency("nanovg-zig", .{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("nanovg", nanovg_zig.module("nanovg"));</code>
Replace <code>exe</code> with your target executable.
</li>
<li>
<strong>Link against OpenGL:</strong>
<code>nanovg-zig</code> relies on OpenGL for rendering. <em>You must manually link against OpenGL in your <code>build.zig</code> file.</em> The <a>build.zig</a> file in the repository demonstrates how to do this.
</li>
<li>
<strong>Use NanoVG in your code:</strong>
You can now import and use the <code>nanovg</code> module in your Zig source files:
<code>zig
const nvg = @import("nanovg");</code>
Refer to the "Creating a drawing context" and "Drawing shapes with NanoVG" sections above for examples of how to use the NanoVG API.
</li>
</ol>
API Reference
See <a>nanovg.zig</a> for an API reference.
Projects using nanovg-zig
<ul>
<li><a>MiniPixel by fabioarnold</a></li>
<li><a>Snake by fabioarnold</a></li>
</ul>
License
The original library and this rewrite are licensed under the <a>zlib license</a>
Fonts used in the examples:
- Roboto licensed under <a>Apache license</a>
- Entypo licensed under CC BY-SA 4.0.
- Noto Emoji licensed under <a>SIL Open Font License, Version 1.1</a>
Links
Uses <a>stb_truetype</a> for font rendering. Uses <a>stb_image</a> for image loading. | [] |
https://avatars.githubusercontent.com/u/99468136?v=4 | beaver | beaver-lodge/beaver | 2022-04-20T01:06:16Z | MLIR Toolkit in Elixir and Zig. | main | 6 | 199 | 9 | 199 | https://api.github.com/repos/beaver-lodge/beaver/tags | MIT | [
"compiler",
"elixir",
"gpu",
"mlir",
"zig"
] | 1,529 | false | 2025-05-19T11:03:46Z | false | false | unknown | github | [] | <a></a>
Beaver 🦫
<a></a> <a></a>
<a></a>
<strong>Boost the almighty blue-silver dragon with some magical elixir!</strong> 🧙🧙♀️🧙♂️
Motivation
In the de-facto way of using MLIR, we need to work with C/C++, TableGen, CMake and Python (in most of cases). Each language or tool here has some functionalities and convenience we want to leverage. There is nothing wrong choosing the most popular and upstream-supported solution, but having alternative ways to build MLIR-based projects is still valuable or at least worth trying.
Elixir could actually be a good fit as a MLIR front end. Elixir has SSA, pattern-matching, pipe-operator. We can use these language features to define MLIR patterns and pass pipeline in a natural and uniformed way. Elixir is strong-typed but not static-typed which makes it a great choice for quickly building prototypes to validate and explore new ideas.
To build a piece of IR in Beaver:
```elixir
Func.func some_func(function_type: Type.function([], [Type.i(32)])) do
region do
block _() do
v0 = Arith.constant(value: Attribute.integer(Type.i(32), 0)) >>> Type.i(32)
cond0 = Arith.constant(true) >>> Type.i(1)
CF.cond_br(cond0, Beaver.Env.block(bb1), {Beaver.Env.block(bb2), [v0]}) >>> []
end
<code>block bb1() do
v1 = Arith.constant(value: Attribute.integer(Type.i(32), 0)) >>> Type.i(32)
_add = Arith.addi(v0, v0) >>> Type.i(32)
CF.br({Beaver.Env.block(bb2), [v1]}) >>> []
end
block bb2(arg >>> Type.i(32)) do
v2 = Arith.constant(value: Attribute.integer(Type.i(32), 0)) >>> Type.i(32)
add = Arith.addi(arg, v2) >>> Type.i(32)
Func.return(add) >>> []
end
</code>
end
end
```
And a small example to showcase what it is like to define and run a pass in Beaver (with some monad magic):
```elixir
defmodule ToyPass do
@moduledoc false
use Beaver
alias MLIR.Dialect.{Func, TOSA}
require Func
import Beaver.Pattern
use MLIR.Pass, on: "builtin.module"
defpat replace_add_op() do
a = value()
b = value()
res = type()
{op, _t} = TOSA.add(a, b) >>> {:op, [res]}
<code>rewrite op do
{r, _} = TOSA.sub(a, b) >>> {:op, [res]}
replace(op, with: r)
end
</code>
end
def run(%MLIR.Operation{} = operation, <em>state) do
with 1 <- Beaver.Walker.regions(operation) |> Enum.count(),
{:ok, </em>} <-
MLIR.apply_(MLIR.Module.from_operation(operation), [replace_add_op(benefit: 2)]) do
:ok
else
_ -> raise "unreachable"
end
end
end
use Beaver
import MLIR.Transform
ctx = MLIR.Context.create()
~m"""
module {
func.func @tosa_add(%arg0: tensor<1x3xf32>, %arg1: tensor<2x1xf32>) -> tensor<2x3xf32> {
%0 = "tosa.add"(%arg0, %arg1) : (tensor<1x3xf32>, tensor<2x1xf32>) -> tensor<2x3xf32>
return %0 : tensor<2x3xf32>
}
}
""".(ctx)
|> Beaver.Composer.append(ToyPass)
|> canonicalize
|> Beaver.Composer.run!()
```
Goals
<ul>
<li>Powered by Elixir's composable modularity and meta-programming features, provide a simple, intuitive, and extensible interface for MLIR.</li>
<li>Edit-Build-Test-Debug Loop at seconds. Everything in Elixir and Zig are compiled in parallel.</li>
<li>Compile Elixir to native/WASM/GPU with the help from MLIR.</li>
<li>Revisit and reincarnate symbolic AI in the HW-accelerated world. Erlang/Elixir has <a>a Prolog root</a>!</li>
<li>Introduce a new stack to machine learning.</li>
<li>Higher-level: Elixir</li>
<li>Representation: MLIR</li>
<li>Lower-level: Zig</li>
</ul>
Why is it called Beaver?
Beaver is an umbrella species increase biodiversity. We hope this project could enable other compilers and applications in the way a beaver pond becomes the habitat of many other creatures. Many Elixir projects also use animal names as their package names and it is often about raising awareness of endangered species. To read more about why beavers are important to our planet, check out <a>this National Geographic article</a>.
Quick introduction
Beaver is essentially LLVM/MLIR on Erlang/Elixir. It is kind of interesting to see a crossover of two well established communities and four sub-communities. Here are some brief information about each of them.
For Erlang/Elixir forks
<ul>
<li>Explain this MLIR thing to me in one sentence</li>
</ul>
MLIR could be regarded as the XML for compilers and an MLIR dialect acts like HTTP standard which gives the generic format real-world semantics and functionalities.
<ul>
<li>Check out <a>the home page</a> of MLIR.</li>
</ul>
For LLVM/MLIR forks
<ul>
<li>
What's so good about this programming language Elixir?
</li>
<li>
It gets compiled to Erlang and runs on BEAM (Erlang's VM). So it has all the fault-tolerance and concurrency features of Erlang.
</li>
<li>As a Lisp, Elixir has all the good stuff of a Lisp-y language including hygienic macro, protocol-based polymorphism.</li>
<li>Elixir has a powerful <a>module system</a> to persist compile-time data and this allows library users to easily adjust runtime behavior.</li>
<li>Minimum, very few keywords. Most of the language is built with itself.</li>
</ul>
<ul>
<li>Check out <a>the official guide</a> of Elixir.</li>
</ul>
Getting started
<ul>
<li>Tutorial: <a>Your first compiler with Beaver!</a></li>
</ul>
Installation
The package can be installed
by adding <code>beaver</code> to your list of dependencies in <code>mix.exs</code>:
<code>elixir
def deps do
[
{:beaver, "~> 0.4.0"}
]
end</code>
Add this to your <code>.formatter.exs</code> will have the formatter properly transform the macros introduced by <code>beaver</code>
<code>elixir
import_deps: [:beaver],</code>
Projects built on top of Beaver
<ul>
<li><a>Charm</a>: Compile a subset of Elixir to native targets.</li>
<li><a>MLIR Accelerated Nx</a>: A backend for <a>Nx</a>.</li>
</ul>
How it works?
To implement a MLIR toolkit, we at least need these group of APIs:
<ul>
<li>IR API, to create and update Ops and blocks in the IR</li>
<li>Pass API, to create and run passes</li>
<li>Pattern API, in which you declare the transformation of a specific structure of Ops</li>
</ul>
We implement the IR API and Pass API with the help of the <a>MLIR C API</a>. There are both lower level APIs generated from the C headers and higher level APIs that are more idiomatic in Elixir.
The Pattern API is implemented with the help from the <a>PDL dialect</a>. We are using the lower level IR APIs to compile your Elixir code to PDL. Another way to look at this is that Elixir/Erlang pattern matching is serving as a frontend alternative to <a>PDLL</a>.
Design principles
Transformation over builder
It is very common to use builder pattern to construct IR, especially in an OO programming language like C++/Python.
One problem this approach has is that the compiler code looks very different from the code it is generating.
Because Erlang/Elixir is SSA by its nature, in Beaver a MLIR Op's creation is very declarative and its container will transform it with the correct contextual information. By doing this, we could:
<ul>
<li>Keep compiler code's structure as close as possible to the generated code, with less noise and more readability.</li>
<li>Allow dialects of different targets and semantic to introduce different DSL. For instance, CPU, SIMD, GPU could all have their specialized transformation tailored for their own unique concepts.</li>
</ul>
One example:
```elixir
module do
v2 = Arith.constant(1) >>> ~t
end
module/1 is a macro, it will transformed the SSA <code>v2= Arith.constant..</code> to:
v2 =
%Beaver.SSA{}
|> Beaver.SSA.put_arguments(value: ~a{1})
|> Beaver.SSA.put_block(Beaver.Env.block())
|> Beaver.SSA.put_ctx(Beaver.Env.context())
|> Beaver.SSA.put_results(~t)
|> Arith.constant()
```
Also, using the declarative way to construct IR, proper dominance and operand reference is formed naturally.
```elixir
SomeDialect.some_op do
region do
block entry() do
x = Arith.constant(1) >>> ~t
y = Arith.constant(1) >>> ~t
end
end
region do
block entry() do
z = Arith.addi(x, y) >>> ~t
end
end
end
will be transformed to:
SomeDialect.some_op(
regions: fn -> do
region = Beaver.Env.region() # first region created
block = Beaver.Env.block()
x = Arith.constant(...)
y = Arith.constant(...)
<code>region = Beaver.Env.region() # second region created
block = Beaver.Env.block()
z = Arith.addi([x, y, ...]) # x and y dominate z
</code>
end
)
```
Beaver DSL as higher level AST for MLIR
There should be a 1:1 mapping between Beaver SSA DSL to MLIR SSA. It is possible to do a roundtrip parsing MLIR text format and dump it to Beaver DSL which is Elixir AST essentially. This makes it possible to easily debug a piece of IR in a more programmable and readable way.
In Beaver, working with MLIR should be in one format, no matter it is generating, transforming, debugging.
High level API in Erlang/Elixir idiom
When possible, lower level C APIs should be wrapped as Elixir struct with support to common Elixir protocols.
For instance the iteration over one MLIR operation's operands, results, successors, attributes, regions should be implemented in Elixir's Enumerable protocol.
This enable the possibility to use the rich collection of functions in Elixir standard libraries and Hex packages.
Is Beaver a compiler or binding to LLVM/MLIR?
Elixir is a programming language built for all purposes. There are multiple sub-ecosystems in the general Erlang/Elixir ecosystem.
Each sub-ecosystem appears distinct/unrelated to each other, but they actually complement each other in the real world production.
To name a few:
<ul>
<li><a>Phoenix Framework</a> for web application and realtime message</li>
<li><a>Nerves Project</a> for embedded device and IoT</li>
<li><a>Nx</a> for tensor and numerical</li>
</ul>
Each of these sub-ecosystems starts with a seed project/library. Beaver should evolve to become a sub-ecosystem for compilers built with Elixir and MLIR.
MLIR context management
When calling higher-level APIs, it is ideal not to have MLIR context passing around everywhere.
If no MLIR context provided, an attribute and type getter should return an anonymous function with MLIR context as argument.
In Erlang, all values are copied, so it is very safe to pass around these anonymous functions.
When creating an operation, these functions will be called with the MLIR context in an operation state.
With this approach we achieve both succinctness and modularity, not having a global MLIR context.
Usually a function accepting a MLIR context to create an operation or type is called a "creator" in Beaver.
Development
Please refer to <a>Beaver's contributing guide</a> | [] |
https://avatars.githubusercontent.com/u/42384293?v=4 | yazap | prajwalch/yazap | 2022-03-13T14:59:46Z | 🔧 The ultimate Zig library for seamless command line argument parsing. | main | 4 | 183 | 19 | 183 | https://api.github.com/repos/prajwalch/yazap/tags | MIT | [
"argument-parser",
"argument-parsing",
"cli",
"command-line-arguments-parser",
"flags",
"parser",
"subcommands",
"zig",
"ziglang"
] | 18,498 | false | 2025-05-21T06:23:59Z | true | true | unknown | github | [] | <a></a>
<a></a>
Yazap
<blockquote>
<span class="bg-blue-100 text-blue-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-blue-900 dark:text-blue-300">NOTE</span>
This branch targets the <a>master branch of zig</a>.
See <a>supported versions table</a>.
</blockquote>
The ultimate <a>zig</a> library for seamless command-line parsing.
Effortlessly handles options, subcommands, and custom arguments with ease.
Inspired by <a>clap-rs</a> and <a>andrewrk/ziglang: src-self-hosted/arg.zig</a>
Supported versions table
| yazap | Zig |
| ----------------------------------------------------------------- | ---------------------------------------- |
| main | <a>master</a> |
| <a><code>0.6.3</code></a> | <code>0.14.0</code> |
| <a><code>0.5.1</code></a> | <code>0.12.0</code>, <code>0.12.1</code> and <code>0.13.0</code> |
| <= <code>0.5.0</code> | Not supported to any |
Key Features:
<ul>
<li><a><strong>Options (short and long)</strong></a>:</li>
<li>Providing values with <code>=</code>, space, or no space (<code>-f=value</code>, <code>-f value</code>, <code>-fvalue</code>).</li>
<li>Supports delimiter-separated values with <code>=</code> or without space (<code>-f=v1,v2,v3</code>, <code>-fv1:v2:v3</code>).</li>
<li>Chaining multiple short boolean options (<code>-abc</code>).</li>
<li>Providing values and delimiter-separated values for multiple chained options using <code>=</code> (<code>-abc=val</code>, <code>-abc=v1,v2,v3</code>).</li>
<li>
Specifying an option multiple times (<code>-a 1 -a 2 -a 3</code>).
</li>
<li>
<a><strong>Positional arguments</strong></a>:
</li>
<li>
Supports positional arguments alongside options for more flexible command-line inputs. For example:
<ul>
<li><code>command <positional_arg></code></li>
<li><code>command <arg1> <arg2> <arg3></code></li>
</ul>
</li>
<li>
<a><strong>Nested subcommands</strong></a>:
</li>
<li>
Organize commands with nested subcommands for a structured command-line interface. For example:
<ul>
<li><code>command subcommand</code></li>
<li><code>command subcommand subsubcommand</code></li>
</ul>
</li>
<li>
<a><strong>Automatic help handling and generation</strong></a>
</li>
<li>
<strong>Custom Argument definition</strong>:
</li>
<li>Define custom <a>Argument</a> types for specific application requirements.</li>
</ul>
Limitations:
<ul>
<li>Does not support delimiter-separated values using space (<code>-f v1,v2,v3</code>).</li>
<li>Does not support providing value and delimiter-separated values for multiple
chained options using space (<code>-abc value, -abc v1,v2,v3</code>).</li>
</ul>
Installing
<ol>
<li>Run the following command:</li>
</ol>
<code>sh
zig fetch --save git+https://github.com/prajwalch/yazap</code>
<ol>
<li>Add the following to <code>build.zig</code>:</li>
</ol>
<code>zig
const yazap = b.dependency("yazap", .{});
exe.root_module.addImport("yazap", yazap.module("yazap"));</code>
Documentation
For detailed and comprehensive documentation, please visit
<a>this link</a>.
<blockquote>
<span class="bg-yellow-100 text-yellow-800 text-xs font-medium me-2 px-2.5 py-0.5 rounded dark:bg-yellow-900 dark:text-yellow-300">WARNING</span>
The documentation site is currently broken, in the meantime check out the source code.
</blockquote>
Usage
Initializing Yazap
To begin using <code>yazap</code>, the first step is to create an instance of
<a>App</a> by calling
<code>App.init(allocator, "Your app name", "optional description")</code>. This function
internally creates a root command for your application.
<code>zig
var app = App.init(allocator, "myls", "My custom ls");
defer app.deinit();</code>
Obtaining the Root Command
The <a>App</a> itself does not provide
any methods for adding arguments to your command. Its main purpose is to
initialize the library, to invoke the parser with necessary arguments, and to
deinitilize the library.
To add arguments and subcommands, acquire the root command by calling <code>App.rootCommand()</code>.
This gives you access to the core command of your application by returning a pointer to it.
<code>zig
var myls = app.rootCommand();</code>
Adding Arguments
Once you have obtained the root command, you can proceed to add arguments and
<a>subcommands</a> using the methods available in the <code>Command</code>. For a complete list
of available methods, refer to the <a>Command API</a>
documentation.
```zig
try myls.addArg(Arg.positional("FILE", null, null));
try myls.addArg(Arg.booleanOption("all", 'a', "Don't ignore the hidden directories"));
try myls.addArg(Arg.booleanOption("recursive", 'R', "List subdirectories recursively"));
try myls.addArg(Arg.booleanOption("one-line", '1', null));
try myls.addArg(Arg.booleanOption("size", 's', null));
try myls.addArg(Arg.booleanOption("version", null, null));
try myls.addArg(Arg.singleValueOption("ignore", 'I', null));
try myls.addArg(Arg.singleValueOption("hide", null, null));
try myls.addArg(Arg.singleValueOptionWithValidValues(
"color",
'C',
"Colorize the output",
&[_][]const u8{ "always", "auto", "never" }
));
```
Alternatively, you can add multiple arguments in a single function call using
<code>Command.addArgs()</code>:
```zig
try myls.addArgs(&[_]Arg {
Arg.positional("FILE", null, null),
Arg.booleanOption("all", 'a', "Don't ignore the hidden directories"),
Arg.booleanOption("recursive", 'R', "List subdirectories recursively"),
Arg.booleanOption("one-line", '1', null),
Arg.booleanOption("size", 's', null),
Arg.booleanOption("version", null, null),
<code>Arg.singleValueOption("ignore", 'I', null),
Arg.singleValueOption("hide", null, null),
Arg.singleValueOptionWithValidValues(
"color",
'C',
"Colorize the output",
&[_][]const u8{ "always", "auto", "never" }
),
</code>
});
```
Note that for any option that accepts value, you can set its value placeholder to display in the
help message. If you don't set the placeholder, the option name will be displayed by default.
```zig
var ignore_opt = Arg.singleValueOption("ignore", 'I', null);
ignore_opt.setValuePlaceholder("PATTERN");
var hide_opt = Arg.singleValueOption("hide", null, null);
hide_opt.setValuesPlaceholder("PATTERN");
var color_opt = Arg.singleValueOptionWithValidValues(
"color",
'C',
"Colorize the output",
&[_][]const u8{ "always", "auto", "never" }
);
color_opt.setValuePlaceholder("WHEN");
try myls.addArgs(&[_]Arg{ ignore_opt, hide_opt, color_opt });
```
Adding Subcommands
To create a subcommand, use <code>App.createCommand("name", "optional description")</code> then
you can add its own arguments and subcommands just like the root command. After you
finish adding arguments, add it as a root subcommand by calling <code>Command.addSubcommand()</code>.
```zig
var update_cmd = app.createCommand("update", "Update the app or check for new updates");
try update_cmd.addArg(Arg.booleanOption("check-only", null, "Only check for new update"));
try update_cmd.addArg(Arg.singleValueOptionWithValidValues(
"branch",
'b',
"Branch to update",
&[_][]const u8{ "stable", "nightly", "beta" }
));
try myls.addSubcommand(update_cmd);
```
Parsing Arguments
Once you have finished adding all the arguments and subcommands, call <code>App.parseProcess()</code>
to start parsing the arguments given to the current process. This function internally utilizes
<a><code>std.process.argsAlloc</code></a>
to obtain the raw arguments. Alternatively, you can use <code>App.parseFrom()</code> and pass your own raw
arguments, which can be useful during testing. Both functions returns
<a><code>ArgMatches</code></a>.
```zig
const matches = try app.parseProcess();
if (matches.containsArg("version")) {
log.info("v0.1.0", .{});
return;
}
if (matches.getSingleValue("FILE")) |f| {
log.info("List contents of {f}");
return;
}
if (matches.subcommandMatches("update")) |update_cmd_matches| {
if (update_cmd_matches.containsArg("check-only")) {
std.log.info("Check and report new update", .{});
return;
}
<code>if (update_cmd_matches.getSingleValue("branch")) |branch| {
std.log.info("Branch to update: {s}", .{branch});
return;
}
return;
</code>
}
if (matches.containsArg("all")) {
log.info("show all", .{});
return;
}
if (matches.containsArg("recursive")) {
log.info("show recursive", .{});
return;
}
if (matches.getSingleValue("ignore")) |pattern| {
log.info("ignore pattern = {s}", .{pattern});
return;
}
if (matches.containsArg("color")) {
const when = matches.getSingleValue("color").?;
<code>log.info("color={s}", .{when});
return;
</code>
}
```
Handling Help
<code>-h</code> and <code>--h</code> flag is globally available to all the commands and subcommands and
handled automatically when they are passed to command line. However, if you need to
manually display the help message there are currently two ways to do it.
1. By invoking <code>App.displayHelp()</code> and <code>App.displaySubcommandHelp()</code>.
<code>App.displayHelp()</code> displays the help message for the root command and
other hand <code>App.displaySubcommandHelp()</code> displays the help message for the
active subcommand.
For e.x.: if <code>gh auth login</code> were passed then <code>App.displayHelp()</code> would display the
help for <code>gh</code> and <code>App.displaySubcommandHelp()</code> display the help for <code>login</code>.
Example:
```zig
if (!matches.containsArgs()) {
try app.displayHelp();
return;
}
if (matches.subcommandMatches("update")) |update_cmd_matches| {
if (!update_cmd_matches.containsArgs()) {
try app.displaySubcommandHelp();
return;
}
}
```
2. By setting <code>.help_on_empty_args</code> property to the command.
The <code>.help_on_empty_args</code> property which when set to a command, it instructs
the handler to display the help message for that particular command when arguments
are not provided. It behaves exactly like the code shown at the example above.
Example:
```zig
var app = App.init(allocator, "myls", "My custom ls");
defer app.deinit();
var myls = app.rootCommand();
myls.setProperty(.help_on_empty_args);
var update_cmd = app.createCommand("update", "Update the app or check for new updates");
update_cmd.setProperty(.help_on_empty_args);
try myls.addSubcommand(update_cmd);
const matches = try myls.parseProcess();
// --snip--
```
Putting it All Together
```zig
const std = @import("std");
const yazap = @import("yazap");
const allocator = std.heap.page_allocator;
const log = std.log;
const App = yazap.App;
const Arg = yazap.Arg;
pub fn main() anyerror!void {
var app = App.init(allocator, "myls", "My custom ls");
defer app.deinit();
<code>var myls = app.rootCommand();
myls.setProperty(.help_on_empty_args);
try myls.addArgs(&[_]Arg {
Arg.positional("FILE", null, null),
Arg.booleanOption("all", 'a', "Don't ignore the hidden directories"),
Arg.booleanOption("recursive", 'R', "List subdirectories recursively"),
Arg.booleanOption("one-line", '1', null),
Arg.booleanOption("size", 's', null),
Arg.booleanOption("version", null, null),
});
var ignore_opt = Arg.singleValueOption("ignore", 'I', null);
ignore_opt.setValuePlaceholder("PATTERN");
var hide_opt = Arg.singleValueOption("hide", null, null);
hide_opt.setValuesPlaceholder("PATTERN");
var color_opt = Arg.singleValueOptionWithValidValues(
"color",
'C',
"Colorize the output",
&[_][]const u8{ "always", "auto", "never" }
);
color_opt.setValuePlaceholder("WHEN");
try myls.addArgs(&[_]Arg{ ignore_opt, hide_opt, color_opt });
// Update subcommand.
var update_cmd = app.createCommand("update", "Update the app or check for new updates");
update_cmd.setProperty(.help_on_empty_args);
try update_cmd.addArg(Arg.booleanOption("check-only", null, "Only check for new update"));
try update_cmd.addArg(Arg.singleValueOptionWithValidValues(
"branch",
'b',
"Branch to update",
&[_][]const u8{ "stable", "nightly", "beta" }
));
try myls.addSubcommand(update_cmd);
// Get the parse result.
const matches = try app.parseProcess();
if (matches.containsArg("version")) {
log.info("v0.1.0", .{});
return;
}
if (matches.getSingleValue("FILE")) |f| {
log.info("List contents of {f}");
return;
}
if (matches.subcommandMatches("update")) |update_cmd_matches| {
if (update_cmd_matches.containsArg("check-only")) {
std.log.info("Check and report new update", .{});
return;
}
if (update_cmd_matches.getSingleValue("branch")) |branch| {
std.log.info("Branch to update: {s}", .{branch});
return;
}
return;
}
if (matches.containsArg("all")) {
log.info("show all", .{});
return;
}
if (matches.containsArg("recursive")) {
log.info("show recursive", .{});
return;
}
if (matches.getSingleValue("ignore")) |pattern| {
log.info("ignore pattern = {s}", .{pattern});
return;
}
if (matches.containsArg("color")) {
const when = matches.getSingleValue("color").?;
log.info("color={s}", .{when});
return;
}
</code>
}
```
Alternate Parsers
<ul>
<li><a>Hejsil/zig-clap</a> - Simple command line argument parsing library</li>
<li><a>winksaville/zig-parse-args</a> - Parse command line arguments</li>
<li><a>MasterQ32/zig-args</a> - Simple-to-use argument parser with struct-based config</li>
</ul> | [
"https://github.com/Chanyon/Xjournal",
"https://github.com/aidanaden/schnorr-zig",
"https://github.com/aidanaden/shamir-zig",
"https://github.com/epilif3sotnas/debt-profit",
"https://github.com/ringtailsoftware/commy",
"https://github.com/ringtailsoftware/zoridor",
"https://github.com/tulilirockz/dough"... |
https://avatars.githubusercontent.com/u/145980012?v=4 | zig-js-runtime | lightpanda-io/zig-js-runtime | 2022-09-15T15:48:29Z | Add a JS runtime in your Zig project | main | 41 | 157 | 7 | 157 | https://api.github.com/repos/lightpanda-io/zig-js-runtime/tags | Apache-2.0 | [
"javascript-runtime",
"v8",
"zig"
] | 871 | false | 2025-05-17T09:30:58Z | true | false | unknown | github | [] | zig-js-runtime
A fast and easy library to add a Javascript runtime into your Zig project.
With this library you can:
<ul>
<li>add Javascript as a scripting language for your Zig project (eg. plugin system, game scripting)</li>
<li>build a web browser (this library as been developed for the <a>Lightpanda headless browser</a>)</li>
<li>build a Javascript runtime (ie. a Node/Bun like)</li>
</ul>
Features:
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Setup and configure the Javascript engine
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Expose Zig structs as Javascript functions and objects (at compile time)
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Bi-directional "link" between Zig structs and Javascript objects
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Support for inheritance (on Zig structs) and prototype chain (on Javascript objects)
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Support for Javascript asynchronous code (I/O event loop)
Currently only v8 is supported as a Javascript engine, but other engines might be added in the future.
This library is fully single-threaded to matches the nature of Javascript and avoid any cost of context switching for the Javascript engine.
Rationale
Integrate a Javascript engine into a Zig project is not just embeding an external library and making language bindings.
You need to handle other stuffs:
<ul>
<li>the generation of your Zig structs as Javascript functions and objects (<em>ObjectTemplate</em> and <em>FunctionTemplate</em> in v8)</li>
<li>the callbacks of Javascript actions into your Zig functions (constructors, getters, setters, methods)</li>
<li>the memory management between the Javascript engine and your Zig code</li>
<li>the I/O event loop to support asynchronous Javascript code</li>
</ul>
This library takes care of all this, with no overhead thanks to Zig awesome compile time capabilities.
Getting started
In your Zig project, let's say you have this basic struct that you want to expose in Javascript:
```zig
const Person = struct {
first_name: []u8,
last_name: []u8,
age: u32,
<code>// Constructor
// if there is no 'constructor' defined 'new Person()' will raise a TypeError in JS
pub fn constructor(first_name: []u8, last_name: []u8, age: u32) Person {
return .{
.first_name = first_name,
.last_name = last_name,
.age = age,
};
}
// Getter, 'get_<field_name>'
pub fn get_age(self: Person) u32 {
return self.age;
}
// Setter, 'set_<field_name>'
pub fn set_age(self: *Person, age: u32) void {
self.age = age;
}
// Method, '_<method_name>'
pub fn _lastName(self: Person) []u8 {
return self.last_name;
}
</code>
};
```
You can generate the corresponding Javascript functions at comptime with:
<code>zig
const jsruntime = @import("jsruntime");
pub const Types = jsruntime.reflect(.{Person});</code>
And then use it in a Javascript script:
```javascript
// Creating a new instance of Person
let p = new Person('John', 'Doe', 40);
// Getter
p.age; // => 40
// Setter
p.age = 41;
p.age; // => 41
// Method
p.lastName(); // => 'Doe'
```
Let's add some inheritance (ie. prototype chain):
```zig
const User = struct {
proto: Person,
role: u8,
<code>pub const prototype = *Person;
pub fn constructor(first_name: []u8, last_name: []u8, age: u32, role: u8) User {
const proto = Person.constructor(first_name, last_name, age);
return .{ .proto = proto, .role = role };
}
pub fn get_role(self: User) u8 {
return self.role;
}
</code>
};
pub const Types = jsruntime.reflect(.{Person, User});
```
And use it in a Javascript script:
```javascript
// Creating a new instance of User
let u = new User('Jane', 'Smith', 35, 1); // eg. 1 for admin
// we can use the User getters/setters/methods
u.role; // => 1
// but also the Person getters/setters/methods
u.age; // => 35
u.age = 36;
u.age; // => 36
u.lastName(); // => 'Smith'
// checking the prototype chain
u instanceof User == true;
u instanceof Person == true;
User.prototype.<strong>proto</strong> === Person.prototype;
```
Javascript shell
A Javascript shell is provided as an example in <code>src/main_shell.zig</code>.
```sh
$ make shell
zig-js-runtime - Javascript Shell
exit with Ctrl+D or "exit"
<blockquote>
```
</blockquote>
Build
Prerequisites
zig-js-runtime is written with <a>Zig</a> <code>0.14.0</code>. You have to
install it with the right version in order to build the project.
To be able to build the v8 engine, you have to install some libs:
For Debian/Ubuntu based Linux:
<code>sh
sudo apt install xz-utils \
python3 ca-certificates git \
pkg-config libglib2.0-dev clang</code>
For MacOS, you only need Python 3.
Install and build dependencies
The project uses git submodule for dependencies.
The <code>make install-submodule</code> will init and update the submodules in the <code>vendor/</code>
directory.
<code>sh
make install-submodule</code>
Build v8
The command <code>make install-v8-dev</code> uses <code>zig-v8</code> dependency to build v8 engine lib.
Be aware the build task is very long and cpu consuming.
Build v8 engine for debug/dev version, it creates
<code>vendor/v8/$ARCH/debug/libc_v8.a</code> file.
<code>sh
make install-v8-dev</code>
You should also build a release vesion of v8 with:
<code>sh
make install-v8</code>
All in one build
You can run <code>make install</code> and <code>make install-dev</code> to install deps all in one.
Development
Some Javascript features are not supported yet:
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> <a>Promises</a> and <a>micro-tasks</a>
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Some Javascript types, including <a>Arrays</a>
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> <a>Function overloading</a>
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> <a>Types static methods</a>
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> <a>Non-optional nullable types</a>
Test
You can test the zig-js-runtime library by running <code>make test</code>.
Credits
<ul>
<li><a>zig-v8</a> for v8 bindings and build</li>
<li><a>Tigerbeetle</a> for the IO loop based on <em>io_uring</em></li>
<li>The v8 team for the <a>v8 Javascript engine</a></li>
<li>The Zig team for <a>Zig</a></li>
</ul> | [] |
https://avatars.githubusercontent.com/u/2458265?v=4 | zig-cross | mrexodia/zig-cross | 2022-05-23T15:26:30Z | Example of using as a CMake Toolchain for cross compiling. | main | 1 | 145 | 9 | 145 | https://api.github.com/repos/mrexodia/zig-cross/tags | BSL-1.0 | [
"cmake",
"cmake-toolchain",
"cpp",
"cross-compilation",
"cross-compiler-toolchain",
"zig"
] | 50 | false | 2025-05-08T19:04:48Z | false | false | unknown | github | [] | zig--cross
Wrapper to make it easy to use <a>Zig</a> as a cross compiler with <a>CMake</a>.
Building
<code>cmake -B build
cmake --build build</code>
Modify <code>cmake.toml</code> to change the build settings. For more information: https://cmkr.build.
Installation
You can rename the <code>zig--cross</code> executable to <code>zig--<command></code> and put it in your PATH:
```
zig--ar.exe
zig--dlltool.exe
zig--lib.exe
zig--ranlib.exe
zig--c++.exe
zig--cc.exe
```
<strong>Note</strong>: You also need <code>zig</code> in your PATH for this to work.
Example (aarch64-linux-gnu)
First create <code>cmake/zig-aarch64-toolchain.cmake</code> in your project folder with the following contents:
<code>cmake
if(CMAKE_GENERATOR MATCHES "Visual Studio")
message(FATAL_ERROR "Visual Studio generator not supported, use: cmake -G Ninja")
endif()
set(CMAKE_SYSTEM_NAME "Linux")
set(CMAKE_SYSTEM_VERSION 1)
set(CMAKE_SYSTEM_PROCESSOR "aarch64")
set(CMAKE_C_COMPILER "zig" cc -target aarch64-linux-gnu)
set(CMAKE_CXX_COMPILER "zig" c++ -target aarch64-linux-gnu)
set(CMAKE_AR "zig--ar")
set(CMAKE_RANLIB "zig--ranlib")</code>
Then configure and build your project:
<code>sh
cmake -B build-aarch64 -G Ninja -DCMAKE_TOOLCHAIN_FILE=cmake/zig-aarch64-toolchain.cmake
cmake --build build-aarch64</code> | [] |
https://avatars.githubusercontent.com/u/65570835?v=4 | s2s | ziglibs/s2s | 2022-02-21T08:07:25Z | A zig binary serialization format. | master | 3 | 142 | 23 | 142 | https://api.github.com/repos/ziglibs/s2s/tags | MIT | [
"binary-data",
"serialization",
"serialization-library",
"zig",
"zig-package"
] | 3,787 | false | 2025-04-06T18:40:41Z | true | true | unknown | github | [] | struct to stream | stream to struct
A Zig binary serialization format and library.
Features
<ul>
<li>Convert (nearly) any Zig runtime datatype to binary data and back.</li>
<li>Computes a stream signature that prevents deserialization of invalid data.</li>
<li>No support for graph like structures. Everything is considered to be tree data.</li>
</ul>
<strong>Unsupported types</strong>:
<ul>
<li>All <code>comptime</code> only types</li>
<li>Unbound pointers (c pointers, pointer to many)</li>
<li><code>volatile</code> pointers</li>
<li>Untagged or <code>external</code> unions</li>
<li>Opaque types</li>
<li>Function pointers</li>
<li>Frames</li>
</ul>
API
The library itself provides only some APIs, as most of the serialization process is not configurable.
<code>``zig
/// Serializes the given</code>value: T<code>into the</code>stream<code>.
/// -</code>stream<code>is a instance of</code>std.io.Writer<code>/// -</code>T<code>is the type to serialize
/// -</code>value` is the instance to serialize.
fn serialize(stream: anytype, comptime T: type, value: T) StreamError!void;
/// Deserializes a value of type <code>T</code> from the <code>stream</code>.
/// - <code>stream</code> is a instance of <code>std.io.Reader</code>
/// - <code>T</code> is the type to deserialize
fn deserialize(stream: anytype, comptime T: type) (StreamError || error{UnexpectedData,EndOfStream})!T;
/// Deserializes a value of type <code>T</code> from the <code>stream</code>.
/// - <code>stream</code> is a instance of <code>std.io.Reader</code>
/// - <code>T</code> is the type to deserialize
/// - <code>allocator</code> is an allocator require to allocate slices and pointers.
/// Result must be freed by using <code>free()</code>.
fn deserializeAlloc(stream: anytype, comptime T: type, allocator: std.mem.Allocator) (StreamError || error{ UnexpectedData, OutOfMemory,EndOfStream })!T;
/// Releases all memory allocated by <code>deserializeAlloc</code>.
/// - <code>allocator</code> is the allocator passed to <code>deserializeAlloc</code>.
/// - <code>T</code> is the type that was passed to <code>deserializeAlloc</code>.
/// - <code>value</code> is the value that was returned by <code>deserializeAlloc</code>.
fn free(allocator: std.mem.Allocator, comptime T: type, value: T) void;
```
Usage and Development
Adding the library
Just add the <code>s2s.zig</code> as a package to your Zig project. It has no external dependencies.
Running the test suite
<code>sh-session
[user@host s2s]$ zig test s2s.zig
All 3 tests passed.
[user@host s2s]$</code>
Project Status
Most of the serialization/deserialization is implemented for the <em>trivial</em> case.
Pointers/slices with non-standard alignment aren't properly supported yet. | [] |
https://avatars.githubusercontent.com/u/99103623?v=4 | NextWM | waycrate/NextWM | 2022-03-12T16:19:50Z | Manual tiling wayland compositor. ( Work In Progress ) | master | 1 | 125 | 0 | 125 | https://api.github.com/repos/waycrate/NextWM/tags | BSD-2-Clause | [
"bspwm",
"sxhkd",
"wayland",
"wayland-client",
"wayland-compositor",
"window-manager",
"wlroots",
"zig"
] | 431 | false | 2025-04-17T11:35:44Z | true | false | unknown | github | [] | NextWM
Manual tiling wayland compositor written with wlroots aimed to be a bspwm clone.
Note: NextWM is still a work in progress project. It won't be useable anytime soon, but when it is I will be the first one to spam screenshots of it in the readme.
<a>
</a><a>
</a><a></a>
License:
The entire project is licensed as BSD-2 "Simplified" unless stated otherwise in the file header.
Aim
I want to learn how to write wlroots compositors with this project.
Why multiple implementations of Nextctl?
Since this project is meant to teach others, why not show people how wayland clients are written in different languages :) ?
To-Do
<ul>
<li>Compress man pages using zig stdlib.</li>
<li>Simple inbuilt bar.</li>
<li>Toplevel location data export?</li>
<li>focused_wlr_output and focused_toplevel data export?</li>
</ul>
Building
Note: All Nextctl implementations are exactly identical.
Build Flags
<ul>
<li><code>-Dxwayland</code> flag enables Xwayland supoprt.</li>
<li><code>-Dxwayland-lazy</code> lazy load Xwayland (might have slightly worse xwayland startup times but reduces resource consumption).</li>
<li><code>-Dnextctl-rs</code> Compile the Rust version of Nextctl (Default is C codebase).</li>
<li><code>-Dnextctl-go</code> Compile the Go version of Nextctl (Default is C codebase).</li>
</ul>
Depedencies
<ol>
<li><code>cargo</code> (Optional. Required if you build Rust implementation of Nextctl) *</li>
<li><code>go</code> 1.18 (Optional. Required if you build Go implementation of Nextctl) *</li>
<li><code>libevdev</code></li>
<li><code>libinput</code></li>
<li><code>make</code> *</li>
<li><code>pixman</code></li>
<li><code>pkg-config</code> *</li>
<li><code>scdoc</code> (Optional. If scdoc binary is not found, man pages are not generated.) *</li>
<li><code>wayland-protocols</code> *</li>
<li><code>wayland</code></li>
<li><code>wlroots</code> 0.16</li>
<li><code>scenefx</code> (Currently chasing master as there's no tagged release.)</li>
<li><code>xkbcommon</code></li>
<li><code>xwayland</code> (Optional. Required if you want Xwayland support.)</li>
<li><code>zig</code> 0.11.0 *</li>
</ol>
<em>* Compile-time dependencies</em>
Steps
<code>bash
git clone --recursive https://git.sr.ht/~shinyzenith/NextWM
sudo make install</code>
Keybind handling
Consider using the compositors in-built key mapper or <a>swhkd</a> if you're looking for a sxhkd like experience.
Contributing:
Send patches to:
<a>~shinyzenith/NextWM@lists.sr.ht</a>
Bug tracker:
https://todo.sr.ht/~shinyzenith/NextWM
Support
<ul>
<li>https://matrix.to/#/#waycrate-tools:matrix.org</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/105325988?v=4 | zorroOS | TalonFloof/zorroOS | 2022-05-12T22:11:38Z | A hobby operating system written in Zig & C that reimagines classic UNIX ideas for modern technology | main | 1 | 122 | 9 | 122 | https://api.github.com/repos/TalonFloof/zorroOS/tags | MIT | [
"baremetal",
"hobby-kernel",
"hobby-os",
"kernel",
"limine",
"operating-system",
"operating-systems",
"os",
"osdev",
"x86-64",
"zig",
"zorro-os"
] | 51,766 | false | 2025-05-21T01:19:57Z | false | false | unknown | github | [] |
<strong>zorroOS</strong> is a hobby operating system written in Zig, currently targeting x86_64 PCs.
Building
Building zorroOS is simple.
First, ensure that you have the following depenedencies:
- <code>zig</code> Version: 0.13.0 (Please open an issue if the specificied version isn't building zorroOS correctly)
- <code>nasm</code>
- <code>python3</code> (To generate the Icon Pack)
- <code>xorriso</code>
- <code>git</code>
Then, clone the repository
<code>sh
$ git clone https://github.com/TalonFox/zorroOS --recursive
$ cd zorroOS</code>
After cloning it, simply run <code>make iso</code> and a ISO named <code>zorroOS.iso</code> will be generated.
You can then run this using an virtual machine/emulator such as QEMU, Bochs, VirtualBox, or VMWare.
You can also flash this onto a USB drive and boot it onto real hardware, if you would rather do that.
License
zorroOS is licensed under the MIT License.
The full text of the license is included in the license file of this software package, which can be accessed <a>here</a>. | [] |
https://avatars.githubusercontent.com/u/7550632?v=4 | redis-rope | ekzhang/redis-rope | 2022-07-24T03:44:27Z | 🪢 A fast native data type for manipulating large strings in Redis | main | 0 | 122 | 3 | 122 | https://api.github.com/repos/ekzhang/redis-rope/tags | MIT | [
"algorithms",
"data-structures",
"redis",
"redis-module",
"rope",
"rust",
"splay-tree",
"zig"
] | 189 | false | 2025-01-16T17:28:43Z | true | false | unknown | github | [] |
A fast and versatile <a>rope</a> data type for large strings in <a>Redis</a>, distributed as a native <a>module</a>.
Overview
Ropes are a more efficient data structure for large strings (indexed sequences of bytes). Unlike ordinary strings, ropes let you do some operations up to exponentially faster than their counterparts:
<ul>
<li><strong>Add bytes</strong> to the beginning, middle, or end — any index you want.</li>
<li><strong>Delete any rope substring</strong> or move it to a different position within the rope.</li>
<li><strong>Splice / concatenate any substring</strong> of a rope with any other rope.</li>
<li><strong>Read any substring</strong> with random access.</li>
</ul>
The ropes in this module are backed by <a>splay trees</a>, which are a self-adjusting data structure that has logarithmic amortized worst-case performance, while recently-accessed indices are also quick to access in subsequent operations. Each splay tree node stores between 64 and 127 bytes of data.
Design
Some data structures tend to be too theoretical. This module attempts to provide practical guarantees:
<ul>
<li><strong>The memory usage of a rope is proportional to its length.</strong> It must be a small constant factor more than the number of bytes stored. (Data is stored in chunks; the constant varies based on fragmentation.)</li>
<li><strong>All operations should be fast in practice.</strong> We aim to approach the speed of ordinary strings for simple operations and to be hundreds of times faster for complex operations.</li>
<li><strong>This module never panics.</strong> If a memory allocation fails, it exits gracefully with an error. The database will never be left in a partially modified or inconsistent state.</li>
<li><strong>Stack size is limited and should not overflow.</strong> No operations on arbitrary trees are implemented recursively. We do not create unbounded stack buffers.</li>
<li><strong>Micro-optimizations are not accepted if they make the code less clear.</strong> Safety and correctness is paramount, and code needs to be easily understood by the reader.</li>
</ul>
Example / Benchmark
Ropes are particularly good at speeding up complex operations on large strings. The following graph shows how performance for ropes scales on 1000 random string SPLICE operations, compared to an equivalent implementation with ordinary Redis strings. (These operations are pipelined to better measure their CPU performance; see the <a>benchmark code in Rust</a>.)
For small strings, there is not much difference. However, each time the length of the string doubles, the basic type gets exponentially slower because it does not scale to large data as well, while the <code>redis-rope</code> type provided by this module stays fast.
Installation
The <code>redis-rope</code> module has been tested with Redis 7.0+. To install, download the appropriate shared library <code>libredisrope.so</code> for your platform and load the module from the command line:
<code>sh-session
redis-server --loadmodule path/to/libredisrope.so</code>
Or by configuration directive in <code>redis.conf</code>:
<code>loadmodule path/to/libredisrope.so</code>
Or from the Redis CLI, using the <code>MODULE LOAD</code> command:
```
<blockquote>
MODULE LOAD path/to/libredisrope.so
```
</blockquote>
Prebuilt binaries
We will build shared libraries for each version of redis-rope on Linux and macOS, using x86-64 and ARM64 architectures. These files are small, portable artifacts and are available on the <a>releases page</a>.
Building from source
<code>redis-rope</code> is written in Zig, which makes building the module from source and cross-compiling very fast (<10 seconds). This is a reasonable option, especially if you want to try out the latest version of the module from the main branch.
<code>zig build -Drelease-fast</code>
This requires Zig 0.9, which you can install <a>here</a>. The project can also be built targeting different platforms with a command-line flag, for example:
<code>zig build -Drelease-fast -Dtarget=x86_64-linux-gnu
zig build -Drelease-fast -Dtarget=aarch64-linux-gnu</code>
Build outputs are located in the <code>zig-out/lib</code> folder.
Commands
Read operations
These are fairly straightfoward: get the length of the rope, any individual byte, or a range of bytes as a string.
<ul>
<li><code>ROPE.LEN</code> <em>key</em>: <strong>O(1)</strong></li>
<li><code>ROPE.GET</code> <em>key</em> <em>index</em>: <strong>O(log N)</strong></li>
<li><code>ROPE.GETRANGE</code> <em>key</em> <em>start</em> <em>stop</em>: <strong>O(log N + K)</strong>, where K is the length of the returned string</li>
</ul>
All operations support negative indices, which count backward from the end of the rope.
Write operations
The append and insert operations push data to the end of the rope, or at an index in the middle of the rope, while the delrange operation deletes a byte range from the rope.
The splice operation is the most complicated and powerful. Given the keys of two ropes, <code>source</code> and <code>destination</code>, it appends <code>destination</code> to the end of <code>source</code> and deletes <code>destination</code>. If <code>start</code> is provided, the string is inserted at that index rather than appended to the end. If <code>stop</code> is provided, then the range of bytes from <code>start</code> to <code>stop</code> is also deleted from <code>source</code> and swapped with the rope at <code>destination</code>.
<ul>
<li><code>ROPE.APPEND</code> <em>key</em> <em>str</em>: <strong>O(1)</strong></li>
<li><code>ROPE.INSERT</code> <em>key</em> <em>index</em> <em>str</em>: <strong>O(log N)</strong>, or <strong>O(1)</strong> if <em>index</em> is 0</li>
<li><code>ROPE.DELRANGE</code> <em>key</em> <em>start</em> <em>stop</em>: <strong>O(log N)</strong></li>
<li><code>ROPE.SPLICE</code> <em>source</em> <em>destination</em> [<em>start</em> [<em>stop</em>]]: <strong>O(log N)</strong></li>
</ul>
Despite being quite powerful, each operation above takes logarithmic time, so they will remain fast for arbitrarily long ropes.
Other operations
The rope data type supports exact calculations from the <code>MEMORY USAGE</code> command, both methods of <a>Redis persistence</a> using RDB and AOF, asynchronous <code>DEL</code> operations, and primary-replica replication.
Example usage
<code>scala
redis:6379> ROPE.APPEND key1 "hello"
(integer) 5
redis:6379> ROPE.LEN key1
(integer) 5
redis:6379> ROPE.GET key1 2
"l"
redis:6379> ROPE.APPEND key1 " world!"
(integer) 12
redis:6379> ROPE.GETRANGE key1 0 -1
"hello world!"
redis:6379> ROPE.INSERT key1 6 "rope "
(integer) 17
redis:6379> ROPE.GETRANGE key1 0 -1
"hello rope world!"
redis:6379> ROPE.DELRANGE key1 -9 -3
(integer) 10
redis:6379> ROPE.GETRANGE key1 0 -1
"hello rod!"
redis:6379> ROPE.APPEND key2 "goodbye"
(integer) 7
redis:6379> ROPE.SPLICE key1 key2 0 4
1) (integer) 12
2) (integer) 5
redis:6379> ROPE.GETRANGE key1 0 -1
"goodbye rod!"
redis:6379> ROPE.GETRANGE key2 0 -1
"hello"
redis:6379> ROPE.SPLICE key1 key2
1) (integer) 17
2) (integer) 0
redis:6379> ROPE.GETRANGE key1 0 -1
"goodbye rod!hello"
redis:6379> MEMORY USAGE key1
(integer) 128
redis:6379> GET key2
(nil)
redis:6379> DEL key1
(integer) 1
redis:6379> GET key1
(nil)</code>
Acknowledgements
Created by Eric Zhang (<a>@ekzhang1</a>). Licensed under the <a>MIT license</a>.
Thanks to <a>antirez</a> for creating Redis and <a>Sleator & Tarjan</a> for discovering splay trees. | [] |
https://avatars.githubusercontent.com/u/90352073?v=4 | zig_learn_opengl | craftlinks/zig_learn_opengl | 2023-01-12T18:56:19Z | Follow the Learn-OpenGL book using Zig | main | 1 | 121 | 6 | 121 | https://api.github.com/repos/craftlinks/zig_learn_opengl/tags | NOASSERTION | [
"graphics",
"opengl",
"zig"
] | 1,580 | false | 2025-05-09T00:14:11Z | true | false | unknown | github | [] | <a><strong>Learn OpenGL</strong></a> using <a>Zig</a>.
Windowing library: <a>mach/glfw - Ziggified GLFW bindings</a> by slimsag
(Stephen Gutekanst).
OpenGL bindings for Zig were generated by the <a>zig-opengl</a> project by MasterQ32 (Felix Queißner).
<a>zstbi</a> - stb image bindings, <a>zmath</a> - SIMD math library, provided by <a>Michal Ziulek</a>, part of the <a>zig-gamedev</a> project.
Sample programs can be used together with the reference book: <a>Learn OpenGL - Graphics Programming</a> by <a>Joey de Vries</a>.
Zig Language installation <a>How-to instructions</a>.
<strong>I. Getting Started</strong>
Hello Triangle
<ul>
<li><a><strong>hello_triangle</strong></a>: Minimal setup for drawing a trianlge on screen.<code>zig build hello_triangle-run</code>
<a></a></li>
<li><a><strong>hello_rectangle</strong></a>: Draw a rectangle efficiently with indexed rendering using the <strong>'Element Buffer Object'</strong>. <code>zig build hello_rectangle-run</code>
<a></a></li>
</ul>
Shaders
<ul>
<li>
<a><strong>shaders</strong></a>: Little programs that rest on the GPU
<code>zig build shaders-run</code>
<a></a>
<a>Shader</a> struct mirrors the C++ Shader Class in the book.
</li>
</ul>
Textures
<ul>
<li><a><strong>textures</strong></a>: Decorate objects with textures
<code>zig build textures-run</code>
<a></a></li>
</ul>
Transformations
<ul>
<li><a><strong>Transformations</strong></a>: Apply a transformation matrix to vertex data
<code>zig build transformations-run</code>
<a></a></li>
</ul>
Coordinate Systems
<ul>
<li><a><strong>Coordinate systems</strong></a>: Model, View, Projection matrices
<code>zig build coordinate_systems-run</code>
<a></a></li>
</ul>
Camera
<ul>
<li>
<a><strong>Camera rotation</strong></a>: Camera rotation around world origin
<code>zig build camera_rotate-run</code>
</li>
<li>
<a><strong>Simple camera</strong></a>: Fly-like camera
<code>zig build simple_camera-run</code>
</li>
</ul>
<strong>II. Lighting</strong>
Basic Lighting
<ul>
<li><a><strong>Basic Lighting</strong></a>: Phong lighting model
<code>zig build basic_lighting-run</code>
<a></a></li>
</ul> | [] |
https://avatars.githubusercontent.com/u/1560508?v=4 | zigcv | ryoppippi/zigcv | 2022-08-21T08:11:05Z | zig bindings for OpenCV4 | main | 25 | 119 | 16 | 119 | https://api.github.com/repos/ryoppippi/zigcv/tags | MIT | [
"opencv",
"zig",
"ziglang"
] | 855 | false | 2025-05-11T21:25:40Z | true | false | unknown | github | [] | ZIGCV
<a></a>
The ZIGCV library provides Zig language bindings for the <a>OpenCV 4</a> computer vision library.
The ZIGCV library supports the head/master of zig and OpenCV (v4.6.0) on Linux, macOS, and Windows.
Caution
Still under development, so the zig APIs will be dynamically changed.
You can use <code>const c_api = @import("zigcv").c_api;</code> to call c bindings directly.
This C-API is currently fixed.
How to execute
Use your own package manager
At first, install openCV 4.6. (maybe you can read how to install from <a>here</a>).
Then:
<code>sh
git clone --recursive https://github.com/ryoppippi/zigcv
cd zigcv
zig build</code>
Currently this repo works with zig 0.11.0, so make sure you have it installed.
We are working on updating to zig 0.12.0.
Use devbox
We also provide a devbox config to manage dependencies and build environments.
```sh
git clone --recursive https://github.com/zigcv
cd zigcv
devbox init
```
Checkout <a>devbox.json</a> for more details.
Demos
you can build some demos.
For example:
<code>sh
zig build examples
./zig-out/bin/face_detection 0</code>
Or you can run the demo with the following command:
<code>sh
devbox run build examples
./zig-out/bin/face_detection 0</code>
You can see the full demo list by <code>zig build --help</code>.
Technical restrictions
Due to zig being a relatively new language it does <a>not have full C ABI support</a> at the moment.
For use that mainly means we can't use any functions that return structs that are less than 16 bytes large on x86, and passing structs to any functions may cause memory error on arm.
License
MIT
Author
Ryotaro "Justin" Kimura (a.k.a. ryoppippi) | [] |
https://avatars.githubusercontent.com/u/40190339?v=4 | minimal-zig-wasm-canvas | daneelsan/minimal-zig-wasm-canvas | 2022-04-14T03:45:38Z | A minimal example showing how HTML5's canvas, wasm memory and zig can interact. | master | 4 | 116 | 11 | 116 | https://api.github.com/repos/daneelsan/minimal-zig-wasm-canvas/tags | - | [
"html5-canvas",
"javascript",
"wasm",
"webassembly",
"zig"
] | 285 | false | 2025-04-25T18:09:17Z | true | false | unknown | github | [] | Minimal zig-wasm-canvas example
A minimal example showing how HTML5's canvas, wasm memory and zig can interact.
https://daneelsan.github.io/minimal-zig-wasm-canvas/
This example was mostly adapted from: https://wasmbyexample.dev/examples/reading-and-writing-graphics/reading-and-writing-graphics.rust.en-us.html. The difference (aside from using Zig instead of Rust), is that this example
does not depend on any external package, library or extra bindings. As with most Zig related projects, the <code>zig</code> command is everything you will need.
Summary
<code>checkerboard.zig</code> defines a global 8 by 8 pixel array: <code>checkerboard_buffer</code>.
There are two functions exported: <code>getCheckerboardBufferPointer()</code> and <code>colorCheckerboard(...)</code>.
<code>getCheckerboardBufferPointer()</code> returns a pointer to the start of <code>checkerboard_buffer</code>, which will be used inside <code>script.js</code> (described later). The other function, <code>colorCheckerboard(...)</code>, is in charge of (re-)coloring the different squares in the checkerboard according to colors passed down by <code>script.js</code>.
<code>checkerboard.zig</code> is compiled into the wasm module <code>checkerboard.wasm</code> by <code>build.zig</code> (see the <a>Build Section</a>).
<code>script.js</code> first creates a <a>WebAssembly.Memory</a>, named <code>memory</code>, which will be used by the wasm module's memory. Next step is to compile and instantiate the fetched wasm module using <a>WebAssembly.instantiateStreaming()</a>. The returned object is a <a>Promise</a> which contains the <code>instance</code> field (<a>WebAssembly.Instance</a>). This is where all the exported symbols from <code>checkerboard.wasm</code> will be stored.
What follows is mostly straightforward:
<ul>
<li>Create a <em>Uint8Array</em> from the WebAssembly.Memory <code>memory</code> buffer, called <code>wasmMemoryArray</code>.</li>
<li>Get the <code>"checkerboard"</code> canvas defined in <code>index.html</code> and create an <a>ImageData</a> object from the canvas' context, called <code>imageData</code>.</li>
<li>In a loop:<ul>
<li>Call <code>colorCheckerboard(...)</code>, passing down random RGB colors. This will modify the values inside <code>checkerboard_buffer</code>.</li>
<li>Extract the contents of the <code>checkerboard_buffer</code>, which is an slice of <code>wasmMemoryArray</code> offseted by <code>getCheckerboardBufferPointer()</code> and of length <code>8 * 8 * 4</code> (bytes).</li>
<li>Copy the contents of the previous slice, i.e. the contents of <code>checkerboard_buffer</code>, into the <code>imageData</code>'s data.</li>
<li>Put the <code>imageData</code> into the canvas.</li>
</ul>
</li>
</ul>
Build
The default (and only) target for this example is <code>wasm32-freestanding-musl</code>.
The latest zig version used to build this project is:
<code>shell
$ zig version
0.12.0-dev.2341+92211135f</code>
To build the wasm module, run:
```shell
$ zig build
$ ls zig-out/lib/ checkerboard.*
checkerboard.wasm
$ wc -c zig-out/bin/checkerboard.wasm
580 zig-out/bin/checkerboard.wasm
```
Note: <code>build.zig</code> specifies various wasm-ld parameters. For example, it sets the initial memory size
and maximum size to be 2 pages, where each page consists of 64kB. Use the <code>--verbose</code> flag to see the complete list of flags the build uses.
Run
Start up the server in this repository's directory:
<code>shell
python3 -m http.server</code>
Go to your favorite browser and type to the URL <code>localhost:8000</code>. You should see the checkboard changing colors.
Resources
<ul>
<li>https://developer.mozilla.org/en-US/docs/WebAssembly/Using_the_JavaScript_API</li>
<li>https://github.com/ern0/howto-wasm-minimal</li>
<li>https://wasmbyexample.dev/examples/reading-and-writing-graphics/reading-and-writing-graphics.rust.en-us.html</li>
<li>https://radu-matei.com/blog/practical-guide-to-wasm-memory/</li>
</ul> | [] |
https://avatars.githubusercontent.com/u/2389051?v=4 | resinator | squeek502/resinator | 2022-10-23T21:00:47Z | Cross-platform Windows resource-definition script (.rc) to resource file (.res) compiler | master | 14 | 116 | 4 | 116 | https://api.github.com/repos/squeek502/resinator/tags | 0BSD | [
"rc",
"win32",
"windows-resource-file",
"zig"
] | 1,561 | false | 2025-05-17T16:26:18Z | true | true | unknown | github | [
{
"commit": "d768f7dd38de9e99e3a3a78b2f5f674b34e62c7b.tar.gz",
"name": "aro",
"tar_url": "https://github.com/Vexu/arocc/archive/d768f7dd38de9e99e3a3a78b2f5f674b34e62c7b.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/Vexu/arocc"
},
{
"commit": "master",
"name": "compress... | resinator
A cross-platform Windows resource-definition script (.rc) to resource file (.res) compiler. It has been merged into the Zig compiler (<a>#17069</a>, <a>#17412</a>), but it is also maintained as a separate standalone tool.
<ul>
<li>This is a fully from-scratch and <a>clean-room</a> implementation, using <a>fuzz testing</a> as the primary method of determining how <code>rc.exe</code> works and how compatible <code>resinator</code> is with its implementation.</li>
<li>See <a>this talk</a> for a deeper dive into this</li>
<li><code>resinator</code> can successfully compile every <code>.rc</code> file in the <a>Windows-classic-samples repo</a> byte-for-byte identically to the Windows RC compiler when using the includes from MSVC/the Windows SDK. This is tested via <a>win32-samples-rc-tests</a>.</li>
<li><code>resinator</code> has zero external dependencies at runtime (it embeds <a>Aro</a> for preprocessing) and can be used to cross-compile from any system out-of-the-box (if Windows system include paths are not found, a complete set of <a>MinGW</a> include files are extracted on-demand).</li>
<li><a>Documentation</a> (really just a dumping ground for documentation-adjacent stuff; to-be-improved-upon)</li>
</ul>
Overview
A Windows resource-definition file (<code>.rc</code>) is made up of both C/C++ preprocessor commands and resource definitions.
<ul>
<li>The preprocessor commands are evaluated first via <a>Aro</a></li>
<li>The preprocessed <code>.rc</code> file is then compiled into a <code>.res</code> file</li>
<li>The <code>.res</code> file can then be linked into an executable by a linker</li>
</ul>
<code>resinator</code> is similar to <code>llvm-rc</code> and GNU's <code>windres</code>, in that it aims to be a cross-platform alternative to <a>the Windows <code>rc.exe</code> tool</a>.
However, unlike <code>llvm-rc</code> and <code>windres</code> (see <a>this section</a>), <code>resinator</code> aims to get as close to 1:1 compatibility with the Windows <code>rc.exe</code> implementation as possible. That is, the ideal would be:
<ul>
<li>The <code>.res</code> output of <code>resinator</code> should match the <code>.res</code> output of the Windows <code>rc.exe</code> in as many cases as possible (if not exactly, then functionally). However, <code>resinator</code> will not support all valid <code>.rc</code> files (i.e. <code>#pragma code_page</code> support will be limited to particular code pages).</li>
<li><code>resinator</code> should fail to compile <code>.rc</code> files that the Windows <code>rc.exe</code> tool fails to compile.</li>
</ul>
In practice, though, 1:1 compatibility is not actually desirable, as there are quirks/bugs in the <code>rc.exe</code> implementation that <code>resinator</code> attempts to handle better.
Comparison to <code>rc.exe</code> (the Win32 RC compiler)
<code>resinator</code> is a drop-in replacement for <code>rc.exe</code> with some improvements, some known exceptions, and some caveats.
<code>resinator</code> has better error messages
<code>resinator</code> handles edge cases better and avoids miscompilations
<code>resinator</code> avoids some miscompilations of the Win32 RC compiler and generally handles edge cases better (e.g. resource data size overflow). See <a>this exhaustive list of intentional differences between <code>resinator</code> and <code>rc.exe</code></a>.
Also, <code>resinator</code> will emit helpful warnings/errors for many of these differences:
<code>resinator</code> does not support UTF-16 encoded scripts
This is a limitation of the preprocessor that is used by <code>resinator</code> (see <a>this issue</a>).
<code>resinator</code> will auto-detect system include paths by default
<code>.rc</code> files can <code>#include</code> files from MSVC/Windows SDKs (most commonly, <code>windows.h</code>). The paths for these files are typically provided via the <code>INCLUDE</code> environment variable or the <code>/i</code> command line option. <code>resinator</code> supports the same options, but it will also try to auto-detect system include paths on Windows, or extract a full set of MinGW includes on-demand (meaning <code>#include "windows.h"</code> in a <code>.rc</code> file will work out-of-the-box on Linux/MacOS/etc).
This behavior can be controlled with the <code>/:auto-includes</code> CLI option.
Comparison to <code>windres</code> and <code>llvm-rc</code>
| Feature | <code>resinator</code> | <code>windres</code> | <code>llvm-rc</code> | <code>rc.exe</code> |
| --- | --- | --- | --- | --- |
| Cross-platform | ✅ | ✅ | ✅ | ❌ |
| Identical <a><code>win32-samples-rc-tests</code></a> outputs as <code>rc.exe</code> | ✅ | ❌ | ❌ | ✅ |
| Support for UTF-16 encoded <code>.rc</code> files | ❌ <a>(TODO)</a> | ❌ | ❌ | ✅ |
| CLI compatibility with <code>rc.exe</code> | ✅ | ❌ | ✅ | ✅ |
| Includes preprocessor | ✅ | ❌ | ❌ | ✅ |
| Support for outputting <code>.rc</code> files | ❌ | ✅ | ❌ | ❌ |
| Support for outputting COFF object files | ❌ <a>(TODO)</a> | ✅ | ❌ | ❌ |
An example of the differences between the implementations
Here is an example <code>.rc</code> script that is handled differently by each of <code>windres</code>, <code>llvm-rc</code>, and the canonical Windows <code>rc.exe</code> implementation:
<code>c
// <id> <resource type> { <data> }
1 "FOO" { "bar" }</code>
<ul>
<li><code>rc.exe</code> compiles this to a <code>.res</code> file with a resource of ID <code>1</code> that has the type <code>"FOO"</code> (the quotes are part of the user-defined resource type name)</li>
<li><code>windres</code> compiles this to a <code>.res</code> file with a resource of ID <code>1</code> that has the type <code>FOO</code> (the <code>"FOO"</code> is parsed as a quoted string)</li>
<li><code>llvm-rc</code> errors on this file with: <code>Error: expected int or identifier, got "FOO"</code></li>
<li><code>resinator</code> matches the <code>rc.exe</code> behavior exactly in this case</li>
</ul>
This particular example is mostly inconsequential in terms of real-world <code>.rc</code> files, but it is indicative of how closely the different implementations conform with the <code>rc.exe</code> behavior. See <a>win32-samples-rc-tests</a> for a more wide-ranging comparison on real-world <code>.rc</code> files.
Compiling <code>resinator</code>
See <a>the version of Zig used in CI</a> to determine which version of Zig should be used to build <code>resinator</code>.
<code>git clone https://github.com/squeek502/resinator
cd resinator
zig build</code>
Testing <code>resinator</code>
<code>zig build test</code>
'Fuzzy' tests
The 'fuzzy' tests are a collection of tests that may be similar to either fuzz testing or property testing. With default settings, the more fuzzing-like tests will run for 1000 iterations. These tests rely on <code>rc.exe</code> being available on <code>PATH</code> since each test uses <code>rc.exe</code> as an oracle to determine if <code>resinator</code> behavior is expected or not.
<code>zig build test_fuzzy</code>
will run all of the 'fuzzy' tests.
Each 'fuzzy' test can be run individually, too. For example, this will run the <code>fuzzy_numbers</code> test infinitely:
<code>zig build test_fuzzy_numbers -Diterations=0</code>
Fuzz testing
On Windows
<ul>
<li>Requires <a>winafl</a> to be installed/built.</li>
<li>Requires <code>rc.exe</code> to be available on the <code>PATH</code></li>
</ul>
To build the fuzzer:
<code>zig build fuzz_winafl</code>
To run the fuzzer, from within the <code>winafl/build64/bin</code> directory (replace <code>C:\path\to\</code> with the actual path to the relevant directories):
<code>set PATH_TO_INPUTS_DIR=C:\path\to\resinator\test\inputs
set PATH_TO_OUTPUTS_DIR=C:\path\to\resinator\test\outputs
set PATH_TO_DYNAMORIO_BIN=C:\path\to\DynamoRIO-Windows\bin64
set PATH_TO_RESINATOR_FUZZER=C:\path\to\resinator\zig-out\bin\fuzz_winafl.exe
afl-fuzz.exe -i "%PATH_TO_INPUTS_DIR%" -o "%PATH_TO_OUTPUTS_DIR%" -D "%PATH_TO_DYNAMORIO_BIN%" -t 20000 -- -coverage_module fuzz_winafl.exe -target_module fuzz_winafl.exe -target_method fuzzMain -fuzz_iterations 5000 -nargs 2 -- "%PATH_TO_RESINATOR_FUZZER%" @@</code>
On Linux
Currently, Linux fuzz testing only tests the <code>resinator</code> implementation for crashes/bugs, and does not check for correctness against <code>rc.exe</code>.
<ul>
<li>Requires <a>afl++</a> with <code>afl-clang-lto</code> to be installed.</li>
</ul>
<code>zig build fuzz_rc</code>
To run the fuzzer:
<code>afl-fuzz -i test/inputs -o test/outputs -- ./zig-out/bin/fuzz_rc</code>
Ideally, this fuzzer would compare the outputs against <code>rc.exe</code> but <code>wine</code> was not able to perfectly emulate <code>rc.exe</code> last I tried (need to investigate this more, I was using a rather old version of wine). | [] |
https://avatars.githubusercontent.com/u/54114156?v=4 | zigglgen | castholm/zigglgen | 2023-01-15T23:09:41Z | Zig OpenGL binding generator | master | 0 | 111 | 14 | 111 | https://api.github.com/repos/castholm/zigglgen/tags | NOASSERTION | [
"bindings",
"opengl",
"zig",
"zig-package"
] | 1,560 | false | 2025-05-16T10:51:07Z | true | true | 0.14.0 | github | [] |
zigglgen
The only Zig OpenGL binding generator you need.
Installation and usage
zigglgen currently supports the following versions of the Zig compiler:
<ul>
<li><code>0.14.0</code></li>
<li><code>0.15.0-dev</code> (master)</li>
</ul>
Older or more recent versions of the compiler are not guaranteed to be compatible.
1. Run <code>zig fetch</code> to add the zigglgen package to your <code>build.zig.zon</code> manifest:
<code>sh
zig fetch --save git+https://github.com/castholm/zigglgen.git</code>
2. Generate a set of OpenGL bindings in your <code>build.zig</code> build script:
```zig
const std = @import("std");
pub fn build(b: *std.Build) void {
const exe_mod = b.createModule(...);
<code>// Choose the OpenGL API, version, profile and extensions you want to generate bindings for.
const gl_bindings = @import("zigglgen").generateBindingsModule(b, .{
.api = .gl,
.version = .@"4.1",
.profile = .core,
.extensions = &.{ .ARB_clip_control, .NV_scissor_exclusive },
});
// Import the generated module.
exe_mod.addImport("gl", gl_bindings);
</code>
}
```
3. Initialize OpenGL and start issuing commands:
```zig
const windowing = @import(...);
const gl = @import("gl");
// Procedure table that will hold OpenGL functions loaded at runtime.
var procs: gl.ProcTable = undefined;
pub fn main() !void {
// Create an OpenGL context using a windowing system of your choice.
const context = windowing.createContext(...);
defer context.destroy();
<code>// Make the OpenGL context current on the calling thread.
windowing.makeContextCurrent(context);
defer windowing.makeContextCurrent(null);
// Initialize the procedure table.
if (!procs.init(windowing.getProcAddress)) return error.InitFailed;
// Make the procedure table current on the calling thread.
gl.makeProcTableCurrent(&procs);
defer gl.makeProcTableCurrent(null);
// Issue OpenGL commands to your heart's content!
const alpha: gl.float = 1;
gl.ClearColor(1, 1, 1, alpha);
gl.Clear(gl.COLOR_BUFFER_BIT);
</code>
}
```
See <a>castholm/zig-examples</a> for example projects.
API
See <a>this gist</a> for a preview of what the generated
code might look like.
OpenGL symbols
zigglgen generates declarations for OpenGL functions, constants, types and extensions using the original names as
defined in the various OpenGL specifications (as opposed to the prefixed names used in C).
| | C | Zig |
|-----------|:----------------------|:-------------------|
| Command | <code>glClearColor</code> | <code>ClearColor</code> |
| Constant | <code>GL_TRIANGLES</code> | <code>TRIANGLES</code> |
| Type | <code>GLfloat</code> | <code>float</code> |
| Extension | <code>GL_ARB_clip_control</code> | <code>ARB_clip_control</code> |
<code>info</code>
<code>zig
pub const info = struct {};</code>
Contains information about the generated set of OpenGL bindings, such as the OpenGL API, version and profile the
bindings were generated for.
<code>ProcTable</code>
<code>zig
pub const ProcTable = struct {};</code>
Holds pointers to OpenGL functions loaded at runtime.
This struct is very large, so you should avoid storing instances of it on the stack. Use global variables or allocate
them on the heap instead.
<code>ProcTable.init</code>
<code>zig
pub fn init(procs: *ProcTable, loader: anytype) bool {}</code>
Initializes the specified procedure table and returns <code>true</code> if successful, <code>false</code> otherwise.
A procedure table must be successfully initialized before passing it to <code>makeProcTableCurrent</code> or accessing any of
its fields.
<code>loader</code> is duck-typed. Given the prefixed name of an OpenGL command (e.g. <code>"glClear"</code>), it should return a pointer to
the corresponding function. It should be able to be used in one of the following two ways:
<ul>
<li><code>@as(?PROC, loader(@as([*:0]const u8, prefixed_name)))</code></li>
<li><code>@as(?PROC, loader.getProcAddress(@as([*:0]const u8, prefixed_name)))</code></li>
</ul>
If your windowing system has a "get procedure address" function, it is usually enough to simply pass that function as
the <code>loader</code> argument.
No references to <code>loader</code> are retained after this function returns.
There is no corresponding <code>deinit</code> function.
<code>makeProcTableCurrent</code>
<code>zig
pub fn makeProcTableCurrent(procs: ?*const ProcTable) void {}</code>
Makes the specified procedure table current on the calling thread.
A valid procedure table must be made current on a thread before issuing any OpenGL commands from that same thread.
<code>getCurrentProcTable</code>
<code>zig
pub fn getCurrentProcTable() ?*const ProcTable {}</code>
Returns the procedure table that is current on the calling thread.
<code>extensionSupported</code>
(Only generated if at least one extension is specified.)
<code>zig
pub fn extensionSupported(comptime extension: Extension) bool {}</code>
Returns <code>true</code> if the specified OpenGL extension is supported by the procedure table that is current on the calling
thread, <code>false</code> otherwise.
FAQ
Which OpenGL APIs are supported?
Any APIs, versions, profiles and extensions included in Khronos's <a>OpenGL XML API
Registry</a> are supported. These include:
<ul>
<li>OpenGL 1.0 through 3.1</li>
<li>OpenGL 3.2 through 4.6 (Compatibility/Core profile)</li>
<li>OpenGL ES 1.1 (Common/Common-Lite profile)</li>
<li>OpenGL ES 2.0 through 3.2</li>
<li>OpenGL SC 2.0</li>
</ul>
The <a><code>updateApiRegistry.ps1</code></a> PowerShell script is used to fetch the API registry and convert it
to a set of Zig source files that are committed to revision control and used by zigglgen.
Why is a thread-local procedure table required?
Per the OpenGL spec, OpenGL function pointers loaded when one OpenGL context is current are not guaranteed to remain
valid when a different context becomes current. This means that it would be incorrect to load a single set of function
pointers to global memory just once at application startup and then have them be shared by all current and future
OpenGL contexts.
In order to support portable multi-threaded multi-context OpenGL applications, it must be possible to load multiple sets
of function pointers. Because OpenGL contexts are already thread-local, it makes a lot of sense to handle function
pointers in a similar manner.
Why aren't OpenGL constants represented as Zig enums?
The short answer is that it's simply not possible to represent groups of OpenGL constants as Zig enums in a
satisfying manner:
<ul>
<li>The API registry currently specifies some of these groups, but far from all of them, and the groups are not guaranteed
to be complete. Groups can be extended by extensions, so Zig enums would need to be defined as non-exhaustive, and
using constants not specified as part of a group would require casting.</li>
<li>Some commands like <em>GetIntegerv</em> that can return constants will return them as plain integers. Comparing the returned
values against Zig enum fields would require casting.</li>
<li>Some constants in the same group are aliases for the same value, which makes them impossible to represent as
Zig enums.</li>
</ul>
Why did calling a supported extension function result in a null pointer dereference?
Certain OpenGL extension add features that are only conditionally available under certain OpenGL versions/profiles or
when certain other extensions are also supported; for example, the <em>VertexWeighthNV</em> command from the <em>NV_half_float</em>
extension is only available when the <em>EXT_vertex_weighting</em> extension is also supported. Unfortunately, the API registry
does not specify these interactions in a consistent manner, so it's not possible for zigglgen to generate code that
ensures that calls to supported extension functions are always safe.
If you use OpenGL extensions it is your responsibility to read the extension specifications carefully and understand
under which conditions their features are available.
Why can't I pass my windowing system's <code>getProcAddress</code> function to <code>ProcTable.init</code>?
It might have the wrong signature, such as taking a <code>[:0]const u8</code> (0-terminated slice) instead of a <code>[*:0]const u8</code>
(0-terminated many-pointer), or returning a pointer without an alignment qualifier. To fix this, define your own
function that wraps the windowing system's function and corrects the mismatch:
```zig
fn fixedGetProcAddress(prefixed_name: [*:0]const u8) ?gl.PROC {
return @alignCast(windowing.getProcAddress(std.mem.span(prefixed_name)));
}
// ...
if (!gl_procs.init(fixedGetProcAddress)) return error.InitFailed;
```
Contributing
If you have any issues or suggestions, please open an issue or a pull request.
Help us define overrides for function parameters and return types!
Due to the nature of the API Registry being designed for C, zigglgen currently generates most pointers types as <code>[*c]</code>
pointers, which is less than ideal. A long-term goal for zigglgen is for every single pointer type to be correctly
annotated. There are approximately 3300 commands defined in the API registry and if we work together, we can achieve
that goal sooner. Even fixing up just a few commands would mean a lot!
Overriding parameters/return types is very easy; all you need to do is add additional entries to the
<code>paramOverride</code>/<code>returnTypeOverride</code> functions in <a><code>zigglgen.zig</code></a>, then open a pull request with your
changes (bonus points if you also reference relevant OpenGL references page or specifications in the description of your
pull request).
License
This repository is <a>REUSE-compliant</a>. The effective SPDX license expression for the repository as a whole is:
<code>Apache-2.0 AND MIT</code>
Copyright notices and license texts have been reproduced in <a><code>LICENSE.txt</code></a>, for your convenience. | [
"https://github.com/PaNDa2code/zterm",
"https://github.com/anyputer/retro-zig",
"https://github.com/eddineimad0/widow",
"https://github.com/griush/CoreX",
"https://github.com/griush/zig-opengl-example",
"https://github.com/pierrekraemer/zgp",
"https://github.com/tiawl/cimgui.zig",
"https://github.com/... |
https://avatars.githubusercontent.com/u/15330989?v=4 | zigtoys | sleibrock/zigtoys | 2022-08-02T03:32:53Z | All about Zig + WASM and seeing what we can do | main | 0 | 109 | 4 | 109 | https://api.github.com/repos/sleibrock/zigtoys/tags | MIT | [
"js",
"wasm",
"zig"
] | 287 | false | 2025-04-23T22:35:34Z | false | false | unknown | github | [] | Zigtoys - Demos with WASM
Update: Pause on Developments
In a <a>recent issue submitted by the lead developer on Zig, Andrew Kelley</a>, it seems that Zig will be parting ways with LLVM in the near (or far) future. WebAssembly is a tier 1 target, but I suspect that gutting LLVM from Zig will impact the ability of Zig to create stable WASM output for a while. The last version used in this project was <code>0.11</code>, so should you have continued interest in this project, please keep using <code>0.11</code>.
I will be pausing active development on this repo for the time until a decision is made about the future of Zig and LLVM. As much as I would love to continue writing Zig, as I believe is an interesting and fun language, the fact that I have to consider and weigh long-term options like this make my continued interest in Zig more difficult. The repo will still be open until then for any and all PRs.
Zigtoys is a collection of "toy" applications I have written in Zig, targeting WebAssembly. It is a demonstration of what you can do with some very minimal Zig. The goal is to focus on design and creating composable code that is easy to re-use, with simplicity in mind.
<a>dev.to</a> articles I have written using this repo:
* <a>WebAssembly with Zig, Part 1</a>
* <a>WebAssembly with Zig, Part 2</a>
Build Command
The Zig compiler options are prone to change, and most recently have changed with version <code>0.11</code>. The command to build all source files here with current Zig is as follows:
<code>shell
$ zig build-lib <file> -target wasm32-freestanding -dynamic -rdynamic -O ReleaseSmall</code>
Behavior was changed in Zig's compiler to remove certain implicit behavior, so the <code>-rdynamic</code> flag is now required in order to export WASM binaries.
(As it stands, I currently cannot figure out for my life how to navigate the <code>build.zig</code> library, so I am ignoring it for now until it's relatively "stable", as just like the compiler options, should be considered always changing)
Personal Notes on Zig/WASM
Below is a collection of notes I have written when I got started with Zig and WASM compilation. Do not take them as official documentation; there are multiple ways you can approach problems. I try to cover all bases, but this is mostly a self-discovery project.
Calling Zig from JavaScript
The first thing that you'll want to familiarize yourself is the convention of invoking Zig functions from JavaScript space. In reality you're not calling Zig, you're calling WASM functions, which were compiled from Zig. When Zig is compiled to WASM, they're compiled in a way that conforms to the WebAssembly standard, so there's a basic ABI that Zig must compile for in order for this all to work.
To WebAssembly, there's only four data types: <code>i32</code>, <code>i64</code>, <code>f32</code>, and <code>f64</code>. That's right, there's no unsigned values here; it's just enough to make us compatible with probably every JavaScript runtime with minimal issues. If you're passing integers or pointers, they're going to be signed integers. Booleans will be considered integers as well. Anything needing a decimal point is floating-point.
Zig has a lot of types, but has to cram all their typing to meet this ABI. Any <code>u32</code> you use in Zig code will more likely than not end up as an <code>i32</code>, and anything smaller than that is going to get chucked into an <code>i32</code> and padded appropriately. The careful use of your <code>u8</code> or <code>u16</code>'s or even <code>u1</code> may get disregarded, so get yourself comfortable with the 32-bits of space you'll get assigned for almost every variable.
So, for the most part, when you try to call a Zig function, remember that it really only understands <em>numbers</em>. Anything else would be futile.
Okay, So Strings
Passing a string into a WebAssembly function isn't quite so easy. There are ways of working around it with two different trains of thought. But right off that bat:
<code>javascript
WASMblob.function("Hello world!");</code>
Won't amount to much good for us. JavaScript is a dynamically-typed language, meaning it allows us to allocate dynamic-length types like strings on the fly. Once the string is used, it gets deallocated almost immediately after since there's no point in keeping it alive.
Even then, the above function is tricky, because Zig doesn't play the nicest with unknown-sized types. It also can't take slices as inputs, it needs <em>pointers</em> to the string in some capacity. JavaScript, when you pass a string like that, doesn't pass a pointer. Most likely because there is no permanent binding for the above-used string. Once the garbage collector throws it away, what is Zig supposed to do about that? It's gone and done.
In some capacity, I find it easier to work with Zig when you treat it as a simple machine with basic interactions. Should you have need to copy string data over, and you want to do it without allocations, consider using static-sized input copy-arrays to copy information over from JavaScript. Use small chunk sizes to
```zig
const buflen: usize = 32;
var stringbuf: [buflen]u8 = undefined;
export fn setCharAt(index: u32, val: u8) bool {
if (index >= buflen)
return false;
stringbuf[index] = val;
return true;
}
```
This is a simple function by which WASM will set aside memory for a 32-byte long string to copy information from JavaScript space one byte at a time. It's not hard to implement this in the JavaScript side.
<code>javascript
var pass_string = function(str) {
for(var i=0; i < str.length; i++) {
WASM.setCharAt(i, str[i]);
}
};</code>
Now you have a simple interface to copy strings over slow one at a time, and a Boolean return value indicates if the copy was successful or not.
However, it would be dishonest to say that this is the only way to copy strings into WASM space. When a string in JavaScript is made, it's allocated as a buffer of integers, but in order to pass it along to WASM, you must use a specific array of clamped integers to do so and pass it as a pointer. <code>UInt8ClampedArray</code> is a way of doing so. It needs to not get cleaned up by the garbage collector, so it must be bound to a variable in a safe lexical scope area. On top of that, the length of the array must also be passed as well.
So what about Pointers?
In order for Zig to be compliant to a C ABI for WASM purposes, we first must learn how Zig handles pointers to values.
<ul>
<li><code>*T</code> - a pointer to a single item of type <code>T</code></li>
<li><code>[*]T</code> - a pointer an unknown-sized array of items of type <code>T</code></li>
</ul>
The asterisk in the middle of square brackets sort of makes sense when you look at definitions like <code>[10]u8</code>, which is an array of 10 <code>u8</code> integers. However it changes when we look at fix-sized arrays.
<ul>
<li><code>*[N]T</code> - a pointer to an <code>N</code>-sized array of type <code>T</code></li>
</ul>
The normal declaration for arrays uses the <code>[N]T</code> format, so it makes sense, moving the asterisk is anothing quirk, but okay. Fine.
<ul>
<li><code>[]T</code> - this is a <em>slice</em>; it contains a pointer to <code>[*]T</code> and a length.</li>
</ul>
Alright, things are fine up until now. However, there's one type of array/slice we left out, called "sentinel-terminated", which means that we can define a type of an array with a value that sits at the end of an array. Meaning if we define <code>[_]u8{ 1, 2, 3, 4 }</code>, in the fifth position (index 4) sits a zero to indicate a null-termination. Most things can be zero-terminated, but some arrays will not be, so you can define what the terminator value will be with this syntax.
<ul>
<li><code>[N:x]T</code> - an <code>N</code>-sized array where the last value in position <code>N</code> is expected to be the value of <code>x</code> for a given type <code>T</code></li>
</ul>
This also works on slices, with:
<ul>
<li><code>[:x]T</code> - a slice where the last value should be <code>x</code> for a slice of type <code>T</code></li>
</ul>
That felt like an exhausting amount of work, but the null-terminating syntax is helpful. It was always implicit in C language that most arrays should end with <code>\0</code> as the terminating character, but here we can define that as part of the <em>type</em> itself, so the compiler can do some extra work to figure things out.
Now, a way you can pass strings around to WASM and back would be to pass a pointer to an array of characters, so this would mean a type of <code>[*]u8</code>. If you wrote a function to work on top of that, then you're getting somewhere.
<code>zig
fn do_stuff(buffer: [*]u8) void {
// do stuff with a buffer
for (buffer) |char| {
// ~~ code ~~
}
}</code>
However, this lacks a length. The length of this array is unknown, thanks to the typing, so this doesn't really work. It would be a better idea to use a null-terminating string instead.
<code>zig
fn do_stuff(buffer: [*:0]u8) void {
// ...</code>
...But JavaScript strings by default aren't null-terminated. In order to get a string fully-working from JavaScript into WASM space, you'd have to fully-copy the string into WASM memory, insert a null-terminator character, then you can pass the pointer to that memory over to Zig. The whole process is honestly quite tedious.
<code>javascript
var my_string = "hello!";
var ptr_to_str = WASM.allocate_string(my_string.length + 1);
var buffer = Uint8Array(WASM.memory, ptr_to_str, my_string.length + 1);
buffer.set(my_string); // O(n) copy
buffer[my_string.length + 1] = 0; // null terminate it
WASM.do_stuff(ptr_to_str);</code>
Note that the allocation <em>can</em> fail, so you must also handle a case for if and when that can occur. I didn't define what <code>allocate_string</code> might look like, but I leave that up to the reader as an exercise.
Performance - WASM isn't always the solution
When I say WASM isn't always the solution, I mean it in a very nice way. WASM is an engine that lives inside a C/C++ codebase, and is interpreted in a very deterministic way. That being said, because it lives inside a C/C++ codebase, any WASM code is inherently never going to be as fast as the <em>actual</em> browser running it. You can get close, but you'll never reach the sun.
This model of execution can be thought of as the following graph:
<code>[JavaScript]
^ ^
/ \
v v
[WASM] <---> [Browser]</code>
It is impossible to have WASM without JavaScript being ran somewhere, but once WASM starts running, you don't necessarily need much JavaScript to keep it afloat. Life is easier when you use JavaScript that is <em>directly</em> connected to browser-specific code. Web APIs that are dependent upon the browser implementation are fast and are machine code backed in the browser.
You can do a lot of things in WASM and use JavaScript to plug in some holes without creating performance dips, but sometimes it might end up being a lot more peaceful to use external references to functions that the Web APIs can provide. You can fill a 4K resolution video buffer all by yourself with WASM so you can write byte streams to it, or you can let the browser manage the video output aspects by using things like Canvas or WebGL. Your call on whatever makes your life easier. But the browser code will likely be faster.
Memory - use the allocator!
A hot take issue is that Zig is a radically different language from C/C++ and Rust because of it's approach to memory allocation. Memory isn't implicitly allocated throughout the program via fancy stuff like classes, templates, generics or extreme compile-time magic. Memory is either compile-time known, or dependent upon a runtime allocator.
With this in mind, you can write Zig programs that do not involve allocators, and it's cool! You'll have less memory bugs to worry about and less hair-pulling when you write code that is deterministic, statically known, and no worries about having to assign or free memory from the program space. However, static no-allocation programs can only get you so far in the world before you have to start creating large buffer pools.
In WASM, when exporting Zig, if you have a 1000 element array, and you set it to define, WebAssembly <em>doesn't know</em> what that can mean by default, and as such, Zig will provide code that fills the entire thing <em>with zeroes</em>. That's right, in your output WASM blob will be an array of elements 1000-wide with all zeroes. That can be 1000 bytes, or it can be 4000 bytes.... or worse, depending if you you use structs with lots of fields.
This affects your WASM size, and the larger your static arrays get, the larger the WASM buffer grows, meaning the slower it will take to carry over the network. This is pretty much not ideal at all, and as such you should defer to memory assignment with allocators and get familiar with them, because they're pretty easy to work with.
The default <code>std.mem.page_allocator</code> works really well and when loading WASM modules, the memory management is pretty hands-off and requires zero effort on my part. The only hang-up is that you have to deal with errors yourself in a "C" style way, instead of using mechanisms inside Zig that help us deal with errors (error values, <code>try</code> keyword, etc).
No Zig Errors
That's right, we can't use Zig errors, something pretty fundamental to the language. Oh well, maybe one day. But for now, any code that makes use of <code>try</code> needs to be refactored to use <code>catch</code> in the code and deal with the error explicitly.
```zig
// bad - can't use the !T error return
export fn init(alloc: *Allocator) !void {
var some_mem: [1000]u32 = try alloc.initCapacity(u32, 1000);
}
// ok - using catch to "catch" the error
export fn init(alloc: *Allocator) u32 {
var some_mem: [1000]u32 = alloc.initCapacity(u32, 1000) catch |err| {
switch (err) {
else => { return 0; },
}
};
}
```
Zig cannot for some obscure reasons to me use the errors to export to a C ABI. Maybe something about the errors just isn't compatible with C, who knows. But this is fine with me. You normally shouldn't be introducing error-stricken code into your programs that often with WASM; WASM is a tiny little car engine with some memory, the only reasons it should really be failing are out-of-bounds errors, networking failure, or parsing issues. Past that, you should engineer your WASM code in a way that reduces errors to the smallest possible error vector imaginable. It will save you headaches later on in life.
Defer
The <code>defer</code> keyword is popular in programs to release system resources so we don't forget about it much later in larger programs. At the end of scope, if a <code>defer</code> keyword was used, it'll execute whatever expression was combined with it.
The <code>defer</code> keyword probably... shouldn't be used, if we're dealing with WASM applications. Depending on your applications, it might not be required to allocate and free your memory; because that's not really required. When a user quits your application, the memory is freed by the WebAssembly virtual machine running your code. It's not entirely your responsibility, it's the host environment's job.
If I'm designing a game world and it's goal is to live and run until the user closes out of the webpage/PWA, then it's not entirely necessary to free memory. Maybe if you had a more fleshed out game, then going to menu and starting/loading savefiles, yeah, maybe freeing memory is a fine thing to do. But other than that, these functions may share different scopes, and the <code>defer</code> keyword may not make sense when sharing memory across many different Zig functions.
Enumeration Safety
Lastly a word about enumerations. If you do this:
```zig
const Entity = enum(u8) {
CellA = 0,
CellB = 1,
CellC = 2,
};
pub fn doWithEntity(ent: Entity) u32 {
return switch(ent) {
.CellA => 0,
.CellB => 1,
.CellC => 2,
};
}
```
This code is valid Zig and passes the compiler. What it <em>doesn't</em> pass is the user test, because this will not work in a way you would like it to.
```javascript
var do_ent = function(x) {
return ZIG.doWithEntity(x);
}
console.log(do_ent(3));
```
What is the expected output of this? That's because we don't know! I have no idea what this should actually be returning because the logic just isn't there, and Zig can't do anything with it. The Zig compiler says the enumeration is fully mapped out and checked within the <code>switch</code>, but as this gets converted to WASM, there is no check in place for this, because <code>Entity</code> gets converted into a <code>u8</code>, and instead of checking for <code>.CellA</code> or <code>.CellB</code>, it actually only checks for <code>1</code> or <code>2</code>, and these are converted into jump (<code>JMP</code>) instructions which move the instruction pointer forwards or backwards. Since none of these cases pass true, then... it probably either doesn't work or gives you zero, which isn't ideal.
In fact I even ran it through Godbolt and this was the output.
<code>do:
push rbp
mov rbp, rsp
sub rsp, 16
mov al, dil
mov byte ptr [rbp - 5], al
test al, al
je .LBB0_2
jmp .LBB0_6
.LBB0_6:
mov al, byte ptr [rbp - 5]
sub al, 1
je .LBB0_3
jmp .LBB0_7
.LBB0_7:
mov al, byte ptr [rbp - 5]
sub al, 2
je .LBB0_4
jmp .LBB0_1
.LBB0_1:
movabs rdi, offset example.do__anon_212
mov esi, 23
xor eax, eax
mov edx, eax
movabs rcx, offset .L__unnamed_1
call example.panic</code>
The <code>je</code> instruction jumps on equivalence, but if it doesn't, it'll hop to the next <code>jmp</code> instruction to then look at other cases. When all else fails, it proceeds to <code>.LBB0_1</code> which will yield a <code>call</code> to some panic function. If that panic function doesn't exist, then.... Undefined behavior in WASM maybe?
Either way, consider this a bit of a footgun and don't write state machines without including an extra case to handle for invalid numerical inputs. That way you can include an <code>else</code> in the <code>switch</code> branch while still covering valid use cases.
```zig
const Entity = enum(u8) {
CellA = 0,
CellB = 1,
CellC = 2,
Bad = 3,
};
pub fn doWithEntity(ent: Entity) u32 {
return switch(ent) {
.CellA => 0,
.CellB => 1,
.CellC => 2,
else => 99, // handles all non-valid values now
};
}
```
Remember to be conscious of using <code>enum(T)</code> to remember exactly what type you put in it. It allows you an easy way of assigning names to numerical values, but WASM will translate it and it won't be technically safe when exposed to the JavaScript environment. | [] |
https://avatars.githubusercontent.com/u/9960133?v=4 | pinephone-nuttx | lupyuen/pinephone-nuttx | 2022-08-21T08:03:52Z | Apache NuttX RTOS for PinePhone | main | 0 | 99 | 8 | 99 | https://api.github.com/repos/lupyuen/pinephone-nuttx/tags | Apache-2.0 | [
"allwinner-a64",
"arm64",
"cortex-a53",
"de2",
"mipi-dsi",
"nuttx",
"osdev",
"pinephone",
"zig"
] | 667 | false | 2025-05-11T04:36:09Z | false | false | unknown | github | [] |
Apache NuttX RTOS for PinePhone
<a></a>
Apache NuttX is a lightweight <strong>Real-Time Operating System (RTOS)</strong> that runs on PINE64 PinePhone. Read the articles...
<ul>
<li>
<a>"NuttX RTOS for PinePhone: What is it?"</a>
<a>(Watch the Demo on YouTube)</a>
</li>
<li>
<a>"NuttX RTOS for PinePhone: The First Year"</a>
<a>(Watch the Presentation on Google Drive)</a>
</li>
</ul>
<strong>PinePhone Display</strong>
<ul>
<li>
<a>"NuttX RTOS for PinePhone: MIPI Display Serial Interface"</a>
</li>
<li>
<a>"NuttX RTOS for PinePhone: Display Engine"</a>
</li>
</ul>
<strong>LCD Touch Panel</strong>
<ul>
<li>
<a>"NuttX RTOS for PinePhone: LCD Panel"</a>
</li>
<li>
<a>"NuttX RTOS for PinePhone: Framebuffer"</a>
</li>
<li>
<a>"NuttX RTOS for PinePhone: Touch Panel"</a>
</li>
</ul>
<strong>LVGL Graphics</strong>
<ul>
<li>
<a>"NuttX RTOS for PinePhone: Boot to LVGL"</a>
</li>
<li>
<a>"NuttX RTOS for PinePhone: LVGL Terminal for NSH Shell"</a>
</li>
<li>
<a>"(Possibly) LVGL in WebAssembly with Zig Compiler"</a>
</li>
<li>
<a>"NuttX RTOS for PinePhone: Feature Phone UI in LVGL, Zig and WebAssembly"</a>
</li>
</ul>
<strong>Accelerometer and Gyroscope</strong>
<ul>
<li><a>"Inside a Smartphone Accelerometer: PinePhone with NuttX RTOS"</a></li>
</ul>
<strong>4G LTE Modem</strong>
<ul>
<li>
<a>"NuttX RTOS for PinePhone: 4G LTE Modem"</a>
</li>
<li>
<a>"NuttX RTOS for PinePhone: Phone Calls and Text Messages"</a>
</li>
</ul>
<strong>GPIO</strong>
<ul>
<li><a>"NuttX RTOS for PinePhone: Blinking the LEDs"</a></li>
</ul>
<strong>UART</strong>
<ul>
<li><a>"NuttX RTOS for PinePhone: UART Driver"</a></li>
</ul>
<strong>USB</strong>
<ul>
<li>
<a>"NuttX RTOS for PinePhone: Simpler USB with EHCI (Enhanced Host Controller Interface)"</a>
</li>
<li>
<a>"NuttX RTOS for PinePhone: Exploring USB"</a>
</li>
</ul>
<strong>Power Management Integrated Circuit</strong>
<ul>
<li><a>"Power Management Integrated Circuit (PMIC)"</a></li>
</ul>
<strong>Interrupts</strong>
<ul>
<li><a>"NuttX RTOS for PinePhone: Fixing the Interrupts"</a></li>
</ul>
<strong>Boot Sequence</strong>
<ul>
<li>
<a>"PinePhone Boots NuttX"</a>
</li>
<li>
<a>"PinePhone Continues Booting NuttX"</a>
</li>
</ul>
<strong>Arm64 Emulation</strong>
<ul>
<li>
<a>"(Possibly) Emulate PinePhone with Unicorn Emulator"</a>
</li>
<li>
<a>"(Clickable) Call Graph for Apache NuttX Real-Time Operating System"</a>
</li>
</ul>
<strong>Build and Boot NuttX</strong>
<ul>
<li>
<a>"Build Apache NuttX RTOS for PinePhone"</a>
</li>
<li>
<a>"Boot Apache NuttX RTOS on PinePhone"</a>
</li>
</ul>
<strong>Download NuttX Binaries</strong>
<ul>
<li>
<a>Apache NuttX RTOS for PinePhone (Boot to LVGL Terminal)</a>
</li>
<li>
<a>Apache NuttX RTOS for PinePhone (Boot to LVGL Demo)</a>
</li>
</ul>
<strong>How It Started</strong>
<ul>
<li>
<a>"Apache NuttX RTOS on Arm Cortex-A53: How it might run on PinePhone"</a>
</li>
<li>
<a>"PinePhone boots Apache NuttX RTOS"</a>
</li>
<li>
<a>"Preparing a Pull Request for Apache NuttX RTOS"</a>
</li>
</ul>
<strong>Older Articles</strong>
<ul>
<li>
<a>"Understanding PinePhone's Display (MIPI DSI)"</a>
</li>
<li>
<a>"NuttX RTOS for PinePhone: Display Driver in Zig"</a>
</li>
<li>
<a>"Rendering PinePhone's Display (DE and TCON0)"</a>
</li>
<li>
<a>"NuttX RTOS for PinePhone: Render Graphics in Zig"</a>
</li>
</ul>
<strong>Can AI Help?</strong>
<ul>
<li><a>"Apache NuttX RTOS trips ChatGPT"</a></li>
</ul>
<em>What's NuttX? Why run it on PinePhone?</em>
If we're new to NuttX, here's a gentle intro...
<ul>
<li><a>"NuttX RTOS for PinePhone: What is it?"</a></li>
</ul>
The following is a journal that documents the porting of NuttX to PinePhone. It looks super messy and unstructured, please read the articles (at the top of this page) instead.
<strong>Table of Contents</strong>
<ul>
<li><a>NuttX Automated Daily Build for PinePhone</a></li>
<li><a>NuttX on QEMU</a></li>
<li><a>Download NuttX</a></li>
<li><a>Download Toolchain</a></li>
<li><a>Download QEMU</a></li>
<li><a>Build NuttX: Single Core</a></li>
<li><a>Test NuttX with QEMU: Single Core</a></li>
<li><a>Build NuttX: Multi Core</a></li>
<li><a>Test NuttX with QEMU: Multi Core</a></li>
<li><a>Inside NuttX for Cortex-A53</a></li>
<li><a>NuttX Image</a></li>
<li><a>PinePhone Image</a></li>
<li><a>Will NuttX Boot On PinePhone?</a></li>
<li><a>UART Driver for NuttX</a></li>
<li><a>Garbled Console Output</a></li>
<li><a>Configure UART Port</a></li>
<li><a>Test UART3 Port</a></li>
<li><a>Boot NuttX on PinePhone</a></li>
<li><a>PinePhone U-Boot Log</a></li>
<li><a>NuttX Boots On PinePhone</a></li>
<li><a>NuttX Boot Log</a></li>
<li><a>Interrupt Controller</a></li>
<li><a>Multi Core SMP</a></li>
<li><a>System Timer</a></li>
<li><a>Timer Interrupt Isn't Handled</a></li>
<li><a>Arm64 Vector Table Is Wrong</a></li>
<li><a>Test PinePhone GIC with QEMU</a></li>
<li><a>Handling Interrupts</a></li>
<li><a>Dump Interrupt Vector Table</a></li>
<li><a>Interrupt Debugging</a></li>
<li><a>Memory Map</a></li>
<li><a>Boot Sequence</a></li>
<li><a>Boot Debugging</a></li>
<li><a>UART Interrupts</a></li>
<li><a>Backlight and LEDs</a></li>
<li><a>BASIC Blinks The LEDs</a></li>
<li><a>NuttX Drivers for Allwinner A64 PIO and PinePhone LEDs</a></li>
<li><a>PinePhone Device Tree</a></li>
<li><a>LCD Controller (TCON0)</a></li>
<li><a>MIPI DSI Interface</a></li>
<li><a>Display PHY</a></li>
<li><a>Backlight PWM</a></li>
<li><a>LED</a></li>
<li><a>Framebuffer</a></li>
<li><a>Display Engine</a></li>
<li><a>Touch Panel</a></li>
<li><a>Video Codec</a></li>
<li><a>GPU</a></li>
<li><a>Deinterlace</a></li>
<li><a>Zig on PinePhone</a></li>
<li><a>PinePhone Display Driver</a></li>
<li><a>Zig Driver for PinePhone MIPI DSI</a></li>
<li><a>Compose MIPI DSI Long Packet in Zig</a></li>
<li><a>Compose MIPI DSI Short Packet in Zig</a></li>
<li><a>Compute Error Correction Code in Zig</a></li>
<li><a>Compute Cyclic Redundancy Check in Zig</a></li>
<li><a>Test PinePhone MIPI DSI Driver with QEMU</a></li>
<li><a>Test Case for PinePhone MIPI DSI Driver</a></li>
<li><a>Initialise ST7703 LCD Controller in Zig</a></li>
<li><a>Test Zig Display Driver for PinePhone</a></li>
<li><a>Display Engine in Allwinner A64</a></li>
<li><a>Display Engine Mixers</a></li>
<li><a>Render Colours</a></li>
<li><a>Render Mandelbrot Set</a></li>
<li><a>Animate Madelbrot Set</a></li>
<li><a>Render Square Overlay</a></li>
<li><a>Render Circle Overlay</a></li>
<li><a>Test PinePhone Display Engine</a></li>
<li><a>Display Engine Usage</a></li>
<li><a>Other Display Engine Features</a></li>
<li><a>Timing Controller in Allwinner A64</a></li>
<li><a>Zig Driver for PinePhone Display Engine</a></li>
<li><a>Test Zig Driver for PinePhone Display Engine</a></li>
<li><a>Complete PinePhone Display Driver in Zig</a></li>
<li><a>Add MIPI DSI to NuttX Kernel</a></li>
<li><a>Test MIPI DSI for NuttX Kernel</a></li>
<li><a>Test Timing Controller TCON0 Driver for NuttX Kernel</a></li>
<li><a>Test Display Engine Driver for NuttX Kernel</a></li>
<li><a>Missing Pixels in PinePhone Image</a></li>
<li><a>Fix Missing Pixels in PinePhone Image</a></li>
<li><a>Merge PinePhone into NuttX Mainline</a></li>
<li><a>LVGL on NuttX on PinePhone</a></li>
<li><a>LVGL Settings for PinePhone</a></li>
<li><a>LVGL Demos on PinePhone</a></li>
<li><a>Boot to LVGL on PinePhone</a></li>
<li><a>PinePhone Touch Panel</a></li>
<li><a>Handle Interrupts from Touch Panel</a></li>
<li><a>NuttX Touch Panel Driver for PinePhone</a></li>
<li><a>LVGL Terminal for NuttX</a></li>
<li><a>Pipe a Command to NuttX NSH Shell</a></li>
<li><a>Poll for NSH Output</a></li>
<li><a>Timer for LVGL Terminal</a></li>
<li><a>Poll for NSH Output in LVGL Timer</a></li>
<li><a>Render Terminal with LVGL Widgets</a></li>
<li><a>Set LVGL Terminal Font to Monospace</a></li>
<li><a>Handle Input from LVGL Keyboard</a></li>
<li><a>Handle Output from NSH Shell</a></li>
<li><a>PinePhone on NuttX becomes a Feature Phone</a></li>
<li><a>USB Driver and LTE Modem Driver for PinePhone</a></li>
<li><a>4G LTE Modem</a></li>
<li><a>Outgoing Phone Call</a></li>
<li><a>Send SMS in Text Mode</a></li>
<li><a>Send SMS in PDU Mode</a></li>
<li><a>SMS PDU Format</a></li>
<li><a>SMS Text Mode vs PDU Mode</a></li>
<li><a>PinePhone Accelerometer and Gyroscope</a></li>
<li><a>Compile NuttX on Android with Termux</a></li>
<li><a>Emulate PinePhone with Unicorn Emulator</a></li>
<li><a>Simulate PinePhone UI with Zig, LVGL and WebAssembly</a></li>
<li><a>Apache NuttX RTOS for PinePhone Pro</a></li>
<li><a>Test Logs</a></li>
<li><a>USB Devices on PinePhone</a></li>
<li><a>Testing Zig Backlight Driver on PinePhone</a></li>
<li><a>Testing Zig Display Engine Driver on PinePhone</a></li>
<li><a>Testing Zig Display Engine Driver on QEMU</a></li>
<li><a>Testing p-boot Display Engine on PinePhone</a></li>
<li><a>Testing NuttX Zig Driver for MIPI DSI on PinePhone</a></li>
<li><a>Testing NuttX Zig Driver for MIPI DSI on QEMU</a></li>
<li><a>Testing p-boot Driver for MIPI DSI (with logging)</a></li>
<li><a>Testing p-boot Driver for MIPI DSI (without logging)</a></li>
<li><a>Testing Zig on PinePhone</a></li>
<li><a>Testing GIC Version 2 on PinePhone</a></li>
<li><a>Testing GIC Version 2 on QEMU</a></li>
<li><a>Boot Files for Manjaro Phosh on PinePhone</a></li>
<li><a>GIC Register Dump</a></li>
</ul>
NuttX Automated Daily Build for PinePhone
NuttX for PinePhone is now built automatically every day via GitHub Actions.
The Daily Releases are available here...
<ul>
<li><a>pinephone-nuttx/releases</a></li>
</ul>
<a>nuttx.hash</a> contains the Commit Hash of the NuttX Kernel and NuttX Apps repos...
<code>text
NuttX Source: https://github.com/apache/nuttx/tree/4bb30ab0c136dc36182cf43995337fc1d44f0a37
NuttX Apps: https://github.com/apache/nuttx-apps/tree/5a4e9e4389264522d02dae78bcb3f9813743300f</code>
The GitHub Actions Workflow is here...
<ul>
<li><a>pinephone.yml</a></li>
</ul>
NuttX on QEMU
Note: This section is outdated, please check this article for updates...
<ul>
<li><a>"Apache NuttX RTOS on Arm Cortex-A53: How it might run on PinePhone"</a></li>
</ul>
<a>Apache NuttX RTOS</a> now runs on Arm Cortex-A53 with Multi-Core SMP...
<ul>
<li><a>nuttx/boards/arm64/qemu/qemu-a53</a></li>
</ul>
PinePhone is based on <a>Allwinner A64 SoC</a> with 4 Cores of Arm Cortex-A53...
<ul>
<li><a>PinePhone Wiki</a></li>
</ul>
We start with NuttX Mainline, run it on QEMU, then mod it for PinePhone.
Download NuttX
Download the Source Code for NuttX Mainline, which supports Arm Cortex-A53...
```bash
Create NuttX Directory
mkdir nuttx
cd nuttx
Download NuttX OS
git clone \
--recursive \
--branch arm64 \
https://github.com/lupyuen/incubator-nuttx \
nuttx
Download NuttX Apps
git clone \
--recursive \
--branch arm64 \
https://github.com/lupyuen/incubator-nuttx-apps \
apps
We'll build NuttX inside nuttx/nuttx
cd nuttx
```
Install the Build Prerequisites, skip the RISC-V Toolchain...
<ul>
<li><a>"Install Prerequisites"</a></li>
</ul>
Download Toolchain
Download the Arm Toolchain for AArch64 ELF Bare-Metal Target (<code>aarch64-none-elf</code>)...
<ul>
<li><a>Arm GNU Toolchain Downloads</a></li>
</ul>
For Linux x64 and WSL:
<ul>
<li><a>gcc-arm-11.2-2022.02-x86_64-aarch64-none-elf.tar.xz</a></li>
</ul>
For macOS:
<ul>
<li><a>arm-gnu-toolchain-11.3.rel1-darwin-x86_64-aarch64-none-elf.pkg</a></li>
</ul>
(I don't recommend building NuttX on Plain Old Windows CMD, please use WSL instead)
Add it to the <code>PATH</code>...
```bash
For Linux x64 and WSL:
export PATH="$PATH:$HOME/gcc-arm-11.2-2022.02-x86_64-aarch64-none-elf/bin"
For macOS:
export PATH="$PATH:/Applications/ArmGNUToolchain/11.3.rel1/aarch64-none-elf/bin"
```
Check the toolchain...
<code>bash
aarch64-none-elf-gcc -v</code>
<a>(Based on the instructions here)</a>
Download QEMU
Download and install QEMU...
<ul>
<li><a>Download QEMU</a></li>
</ul>
For macOS we may use <code>brew</code>...
<code>bash
brew install qemu</code>
Build NuttX: Single Core
First we build NuttX for a Single Core of Arm Cortex-A53...
```bash
Configure NuttX for Single Core
./tools/configure.sh -l qemu-a53:nsh
Build NuttX
make
Dump the disassembly to nuttx.S
aarch64-none-elf-objdump \
-t -S --demangle --line-numbers --wide \
nuttx \
<blockquote>
nuttx.S \
2>&1
```
</blockquote>
The NuttX Output Files may be found here...
<ul>
<li><a>NuttX for Arm Cortex-A53 Single Core</a></li>
</ul>
Test NuttX with QEMU: Single Core
This is how we test NuttX on QEMU with a Single Core of Arm Cortex-A53...
```bash
Start QEMU (Single Core) with NuttX
qemu-system-aarch64 \
-cpu cortex-a53 \
-nographic \
-machine virt,virtualization=on,gic-version=3 \
-net none \
-chardev stdio,id=con,mux=on \
-serial chardev:con \
-mon chardev=con,mode=readline \
-kernel ./nuttx
```
Here's NuttX with a Single Core running on QEMU...
```text
- Ready to Boot CPU
- Boot from EL2
- Boot from EL1
- Boot to C runtime for OS Initialize
nx_start: Entry
up_allocate_heap: heap_start=0x0x402c4000, heap_size=0x7d3c000
gic_validate_dist_version: GICv3 version detect
gic_validate_dist_version: GICD_TYPER = 0x37a0007
gic_validate_dist_version: 224 SPIs implemented
gic_validate_dist_version: 0 Extended SPIs implemented
gic_validate_dist_version: Distributor has no Range Selector support
gic_validate_redist_version: GICD_TYPER = 0x1000011
gic_validate_redist_version: 16 PPIs implemented
gic_validate_redist_version: no VLPI support, no direct LPI support
up_timer_initialize: up_timer_initialize: cp15 timer(s) running at 62.50MHz, cycle 62500
uart_register: Registering /dev/console
uart_register: Registering /dev/ttyS0
work_start_highpri: Starting high-priority kernel worker thread(s)
nx_start_application: Starting init thread
lib_cxx_initialize: _sinit: 0x402a7000 _einit: 0x402a7000 _stext: 0x40280000 _etext: 0x402a8000
nsh: sysinit: fopen failed: 2
nsh: mkfatfs: command not found
NuttShell (NSH) NuttX-10.3.0-RC2
nsh> nx_start: CPU0: Beginning Idle Loop
nsh> help
help usage: help [-v] []
. cd dmesg help mount rmdir true xd
[ cp echo hexdump mv set truncate
? cmp exec kill printf sleep uname
basename dirname exit ls ps source umount
break dd false mkdir pwd test unset
cat df free mkrd rm time usleep
Builtin Apps:
getprime hello nsh ostest sh
nsh> uname -a
NuttX 10.3.0-RC2 1e8f2a8 Aug 23 2022 07:04:54 arm64 qemu-a53
nsh> hello
task_spawn: name=hello entry=0x4029b594 file_actions=0x402c9580 attr=0x402c9588 argv=0x402c96d0
spawn_execattrs: Setting policy=2 priority=100 for pid=3
Hello, World!!
nsh> ls /
/:
dev/
etc/
proc/
nsh> ls /dev
/dev:
console
null
ram0
ram2
ttyS0
zero
nsh> ls /proc
/proc:
0/
1/
2/
meminfo
memdump
fs/
self/
uptime
version
nsh> ls /etc
/etc:
init.d/
nsh> ls /etc/init.d
/etc/init.d:
rcS
nsh> cat /etc/init.d/rcS
Create a RAMDISK and mount it at /tmp
mkrd -m 2 -s 512 1024
mkfatfs /dev/ram2
mount -t vfat /dev/ram2 /tmp
```
NuttX is <a>POSIX Compliant</a>, so the developer experience feels very much like Linux. (But much smaller)
And NuttX runs everything in RAM, no File System needed. (For now)
Build NuttX: Multi Core
From Single Core to Multi Core! Now we build NuttX for 4 Cores of Arm Cortex-A53...
```bash
Erase the NuttX Configuration
make distclean
Configure NuttX for 4 Cores
./tools/configure.sh -l qemu-a53:nsh_smp
Build NuttX
make
Dump the disassembly to nuttx.S
aarch64-none-elf-objdump \
-t -S --demangle --line-numbers --wide \
nuttx \
<blockquote>
nuttx.S \
2>&1
```
</blockquote>
The NuttX Output Files may be found here...
<ul>
<li><a>NuttX for Arm Cortex-A53 Multi-Core</a></li>
</ul>
Test NuttX with QEMU: Multi Core
And this is how we test NuttX on QEMU with 4 Cores of Arm Cortex-A53...
```bash
Start QEMU (4 Cores) with NuttX
qemu-system-aarch64 \
-smp 4 \
-cpu cortex-a53 \
-nographic \
-machine virt,virtualization=on,gic-version=3 \
-net none \
-chardev stdio,id=con,mux=on \
-serial chardev:con \
-mon chardev=con,mode=readline \
-kernel ./nuttx
```
Note that <code>smp</code> is set to 4. <a>(Symmetric Multi-Processing)</a>
Here's NuttX with 4 Cores running on QEMU...
```text
- Ready to Boot CPU
- Boot from EL2
- Boot from EL1
- Boot to C runtime for OS Initialize
[CPU0] psci_detect: Detected PSCI v1.1
[CPU0] nx_start: Entry
[CPU0] up_allocate_heap: heap_start=0x0x402db000, heap_size=0x7d25000
[CPU0] gic_validate_dist_version: GICv3 version detect
[CPU0] gic_validate_dist_version: GICD_TYPER = 0x37a0007
[CPU0] gic_validate_dist_version: 224 SPIs implemented
[CPU0] gic_validate_dist_version: 0 Extended SPIs implemented
[CPU0] gic_validate_dist_version: Distributor has no Range Selector support
[CPU0] gic_validate_redist_version: GICD_TYPER = 0x1000001
[CPU0] gic_validate_redist_version: 16 PPIs implemented
[CPU0] gic_validate_redist_version: no VLPI support, no direct LPI support
[CPU0] up_timer_initialize: up_timer_initialize: cp15 timer(s) running at 62.50MHz, cycle 62500
[CPU0] uart_register: Registering /dev/console
[CPU0] uart_register: Registering /dev/ttyS0
<ul>
<li>Ready to Boot CPU</li>
<li>Boot from EL2</li>
<li>Boot from EL1</li>
<li>Boot to C runtime for OS Initialize</li>
</ul>
[CPU1] gic_validate_redist_version: GICD_TYPER = 0x101000101
[CPU1] gic_validate_redist_version: 16 PPIs implemented
[CPU1] gic_validate_redist_version: no VLPI support, no direct LPI support
[CPU1] nx_idle_trampoline: CPU1: Beginning Idle Loop
[CPU0] arm64_start_cpu: Secondary CPU core 1 (MPID:0x1) is up
<ul>
<li>Ready to Boot CPU</li>
<li>Boot from EL2</li>
<li>Boot from EL1</li>
<li>Boot to C runtime for OS Initialize</li>
</ul>
[CPU2] gic_validate_redist_version: GICD_TYPER = 0x201000201
[CPU2] gic_validate_redist_version: 16 PPIs implemented
[CPU2] gic_validate_redist_version: no VLPI support, no direct LPI support
[CPU2] nx_idle_trampoline: CPU2: Beginning Idle Loop
[CPU0] arm64_start_cpu: Secondary CPU core 2 (MPID:0x2) is up
<ul>
<li>Ready to Boot CPU</li>
<li>Boot from EL2</li>
<li>Boot from EL1</li>
<li>Boot to C runtime for OS Initialize</li>
</ul>
[CPU3] gic_validate_redist_version: GICD_TYPER = 0x301000311
[CPU3] gic_validate_redist_version: 16 PPIs implemented
[CPU3] gic_validate_redist_version: no VLPI support, no direct LPI support
[CPU0] arm64_start_cpu: Secondary CPU core 3 (MPID:0x3) is up
[CPU0] work_start_highpri: Starting high-priority kernel worker thread(s)
[CPU0] nx_start_application: Starting init thread
[CPU3] nx_idle_trampoline: CPU3: Beginning Idle Loop
[CPU0] nx_start: CPU0: Beginning Idle Loop
nsh: sysinit: fopen failed: 2
nsh: mkfatfs: command not found
NuttShell (NSH) NuttX-10.3.0-RC2
nsh> help
help usage: help [-v] []
. cd dmesg help mount rmdir true xd
[ cp echo hexdump mv set truncate
? cmp exec kill printf sleep uname
basename dirname exit ls ps source umount
break dd false mkdir pwd test unset
cat df free mkrd rm time usleep
Builtin Apps:
getprime hello nsh ostest sh smp taskset
nsh> uname -a
NuttX 10.3.0-RC2 1e8f2a8 Aug 21 2022 15:57:35 arm64 qemu-a53
nsh> hello
[CPU0] task_spawn: name=hello entry=0x4029cee4 file_actions=0x402e52b0 attr=0x402e52b8 argv=0x402e5400
[CPU0] spawn_execattrs: Setting policy=2 priority=100 for pid=6
Hello, World!
```
We see each of the 4 Cores starting NuttX (CPU0 to CPU3). That's so cool!
(Can we use QEMU to partially emulate PinePhone? That would be extremely helpful!)
Inside NuttX for Cortex-A53
Now we browse the Source Files for the implementation of Cortex-A53 on NuttX.
NuttX treats QEMU as a Target Board (as though it was a dev board). Here are the Source Files and Build Configuration for the QEMU Board...
<ul>
<li><a>nuttx/boards/arm64/qemu/qemu-a53</a></li>
</ul>
(We'll clone this to create a Target Board for PinePhone)
The Board-Specific Drivers for QEMU are started in <a>qemu-a53/src/qemu_bringup.c</a>
(We'll start the PinePhone Drivers here)
The QEMU Board calls the QEMU Architecture-Specific Drivers at...
<ul>
<li><a>nuttx/arch/arm64/src/qemu</a></li>
</ul>
The UART Driver is located at <a>qemu/qemu_serial.c</a> and <a>qemu/qemu_lowputc.S</a>
(For PinePhone we'll create a UART Driver for Allwinner A64 SoC. I2C, SPI and other Low-Level A64 Drivers will be located here too)
The QEMU Functions (Board and Architecture) call the Arm64 Architecture Functions at...
<ul>
<li><a>nuttx/arch/arm64/src/common</a></li>
</ul>
Which implements all kinds of Arm64 Features: <a>FPU</a>, <a>Interrupts</a>, <a>MMU</a>, <a>Tasks</a>, <a>Timers</a>...
(We'll reuse them for PinePhone)
NuttX Image
Next we analyse the NuttX Image with <a>Ghidra</a>, to understand the NuttX Image Header and Startup Code.
Here's the <a>NuttX ELF Image <code>nuttx</code></a> analysed by Ghidra...
Note that the NuttX Image jumps to <code>real_start</code> (to skip the Image Header)...
<code>text
40280000 4d 5a 00 91 add x13,x18,#0x16
40280004 0f 00 00 14 b real_start</code>
<code>real_start</code> is defined at 0x4028 0040 with the Startup Code...
We see something interesting: The Magic Number <code>ARM\x64</code> appears at address 0x4028 0038.
Searching the net for this Magic Number reveals that it's actually an Arm64 Linux Kernel Header!
When we refer to the <a>NuttX Arm64 Disassembly <code>nuttx.S</code></a>, we find happiness: <a>arch/arm64/src/common/arm64_head.S</a>
```text
/<em> Kernel startup entry point.
* ---------------------------
*
* The requirements are:
* MMU = off, D-cache = off, I-cache = on or off,
* x0 = physical address to the FDT blob.
* it will be used when NuttX support device tree in the future
*
* This must be the very first address in the loaded image.
* It should be loaded at any 4K-aligned address.
</em>/
.globl __start;
__start:
<code>/* DO NOT MODIFY. Image header expected by Linux boot-loaders.
*
* This add instruction has no meaningful effect except that
* its opcode forms the magic "MZ" signature of a PE/COFF file
* that is required for UEFI applications.
*
* Some bootloader (such imx8 uboot) checking the magic "MZ" to see
* if the image is a valid Linux image. but modifying the bootLoader is
* unnecessary unless we need to do a customize secure boot.
* so just put the ''MZ" in the header to make bootloader happiness
*/
add x13, x18, #0x16 /* the magic "MZ" signature */
b real_start /* branch to kernel start */
.quad 0x480000 /* Image load offset from start of RAM */
.quad _e_initstack - __start /* Effective size of kernel image, little-endian */
.quad __HEAD_FLAGS /* Informative flags, little-endian */
.quad 0 /* reserved */
.quad 0 /* reserved */
.quad 0 /* reserved */
.ascii "ARM\x64" /* Magic number, "ARM\x64" */
.long 0 /* reserved */
</code>
real_start:
/<em> Disable all exceptions and interrupts </em>/
```
NuttX Image actually follows the Arm64 Linux Kernel Image Format! As defined here...
<ul>
<li><a>"Booting AArch64 Linux"</a></li>
</ul>
Arm64 Linux Kernel Image contains a 64-byte header...
<code>text
u32 code0; /* Executable code */
u32 code1; /* Executable code */
u64 text_offset; /* Image load offset, little endian */
u64 image_size; /* Effective Image size, little endian */
u64 flags; /* kernel flags, little endian */
u64 res2 = 0; /* reserved */
u64 res3 = 0; /* reserved */
u64 res4 = 0; /* reserved */
u32 magic = 0x644d5241; /* Magic number, little endian, "ARM\x64" */
u32 res5; /* reserved (used for PE COFF offset) */</code>
Start of RAM is 0x4000 0000. The Image Load Offset in our NuttX Image Header is 0x48 0000 according to <a>arch/arm64/src/common/arm64_head.S</a>
<code>text
.quad 0x480000 /* Image load offset from start of RAM */</code>
This means that our NuttX Image will be loaded at 0x4048 0000.
I wonder if this Image Load Offset should have been 0x28 0000? (Instead of 0x48 0000)
Remember that Ghidra (and the Arm Disassembly) says that our NuttX Image is actually loaded at 0x4028 0000. (Instead of 0x4048 0000)
RAM Size and RAM Start are defined in the NuttX Configuration: <a>boards/arm64/qemu/qemu-a53/configs/nsh_smp/defconfig</a>
<code>text
CONFIG_RAM_SIZE=134217728
CONFIG_RAM_START=0x40000000</code>
That's 128 MB RAM. Which should fit inside PinePhone's 2 GB RAM.
The NuttX Image was built with this Linker Command, based on <code>make --trace</code>...
<code>bash
aarch64-none-elf-ld \
--entry=__start \
-nostdlib \
--cref \
-Map=nuttx/nuttx/nuttx.map \
-Tnuttx/nuttx/boards/arm64/qemu/qemu-a53/scripts/dramboot.ld \
-L nuttx/nuttx/staging \
-L nuttx/nuttx/arch/arm64/src/board \
-o nuttx/nuttx/nuttx arm64_head.o \
--start-group \
-lsched \
-ldrivers \
-lboards \
-lc \
-lmm \
-larch \
-lapps \
-lfs \
-lbinfmt \
-lboard /Applications/ArmGNUToolchain/11.3.rel1/aarch64-none-elf/bin/../lib/gcc/aarch64-none-elf/11.3.1/libgcc.a /Applications/ArmGNUToolchain/11.3.rel1/aarch64-none-elf/bin/../lib/gcc/aarch64-none-elf/11.3.1/../../../../aarch64-none-elf/lib/libm.a \
--end-group</code>
NuttX Image begins at <code>__start</code>, which is defined as 0x4028 0000 in the NuttX Linker Script: <a>boards/arm64/qemu/qemu-a53/scripts/dramboot.ld</a>
<code>text
SECTIONS
{
. = 0x40280000; /* uboot load address */
_start = .;</code>
We'll change this to 0x4008 0000 for PinePhone, since Kernel Start Address is 0x4008 0000 and Image Load Offset is 0. (See below)
We've seen the NuttX Image (which looks like a Linux Kernel Image), let's compare with a PinePhone Linux Kernel Image and see how NuttX needs to be tweaked...
PinePhone Image
Will NuttX run on PinePhone? Let's analyse a PinePhone Linux Kernel Image with Ghidra, to look at the Linux Kernel Header and Startup Code.
We'll use the PinePhone Jumpdrive Image, since it's small...
https://github.com/dreemurrs-embedded/Jumpdrive
Download https://github.com/dreemurrs-embedded/Jumpdrive/releases/download/0.8/pine64-pinephone.img.xz
Expand <code>pine64-pinephone.img.xz</code>
Expand the files inside...
<code>bash
gunzip Image.gz
gunzip initramfs.gz
tar xvf initramfs</code>
Import the uncompressed <code>Image</code> (Linux Kernel) into Ghidra.
For "Language" select AARCH64:LE:v8A:default...
- Processor: AARCH64
- Variant: v8A
- Size: 64
- Endian: little
- Compiler: default
Here's the Jumpdrive <code>Image</code> (Linux Kernel) in Ghidra...
According to the Linux Kernel Header...
<ul>
<li><a>"Booting AArch64 Linux"</a></li>
</ul>
We see Linux Kernel Magic Number <code>ARM\x64</code> at offset 0x38.
Image Load Offset is 0, according to the header.
Kernel Start Address on PinePhone is 0x4008 0000.
So we shift <code>Image</code> in Ghidra to start at 0x4008 0000...
<ul>
<li>
Click Window > Memory Map
</li>
<li>
Click "ram"
</li>
<li>
Click the 4-Arrows icon ("Move a block to another address")
</li>
<li>
Change "New Start Address" to 40080000
</li>
</ul>
Will NuttX Boot On PinePhone?
<em>So will NuttX boot on PinePhone?</em>
It's highly plausible! We discovered (with happiness) that NuttX already generates an Arm64 Linux Kernel Header.
So NuttX could be a drop-in replacement for the PinePhone Linux Kernel! We just need to...
<ul>
<li>
Write PinePhone Jumpdrive to a microSD Card (with Etcher, in FAT format)
</li>
<li>
Overwrite <code>Image.gz</code> by the (gzipped) NuttX Binary Image <code>nuttx.bin.gz</code>
</li>
<li>
Insert the microSD Card into PinePhone
</li>
<li>
Power on PinePhone
</li>
</ul>
And NuttX should (theoretically) boot on PinePhone!
As mentioned earlier, we should rebuild NuttX so that <code>__start</code> is changed to 0x4008 0000 (from 0x4028 0000), as defined in the NuttX Linker Script: <a>boards/arm64/qemu/qemu-a53/scripts/dramboot.ld</a>
<code>text
SECTIONS
{
SECTIONS
{
. = 0x40080000; /* PinePhone uboot load address (kernel_addr_r) */
/* Previously: . = 0x40280000; */ /* uboot load address */
_start = .;</code>
Also the Image Load Offset in our NuttX Image Header should be changed to 0x0 (from 0x48 0000): <a>arch/arm64/src/common/arm64_head.S</a>
<code>text
.quad 0x0000 /* PinePhone Image load offset from start of RAM */
# Previously: .quad 0x480000 /* Image load offset from start of RAM */</code>
Later we'll increase the RAM Size to 2 GB (from 128 MB): <a>boards/arm64/qemu/qemu-a53/configs/nsh_smp/defconfig</a>
<code>text
/* TODO: Increase to 2 GB for PinePhone */
CONFIG_RAM_SIZE=134217728
CONFIG_RAM_START=0x40000000</code>
But not right now, because it might clash with the Device Tree and RAM File System.
<em>But will we see anything when NuttX boots on PinePhone?</em>
Not yet. We'll need to implement the UART Driver for NuttX...
UART Driver for NuttX
Read the article...
<ul>
<li><a>"NuttX RTOS for PinePhone: UART Driver"</a></li>
</ul>
We won't see any output from NuttX until we implement the UART Driver for NuttX.
These are the Source Files for the QEMU UART Driver (PL011)...
<ul>
<li>
<a>arch/arm64/src/qemu/qemu_serial.c</a>
</li>
<li>
<a>arch/arm64/src/qemu/qemu_lowputc.S</a>
<a>(More about PL011 UART)</a>
</li>
</ul>
We'll replace the code above with the UART Driver for Allwinner A64 SoC...
<ul>
<li>
<a>UART0 Memory Map</a>
</li>
<li>
<a>Allwinner A64 UART</a>
</li>
<li>
<a>Allwinner A64 User Manual</a>
</li>
<li>
<a>Allwinner A64 Info</a>
</li>
</ul>
To access the UART Port on PinePhone, we'll use this USB Serial Debug Cable...
<ul>
<li><a>PinePhone Serial Debug Cable</a></li>
</ul>
Which connects to the Headphone Port. Genius!
<a>(Remember to flip the Headphone Switch to OFF)</a>
<a><em>PinePhone UART Port in disguise</em></a>
Garbled Console Output
The log appears garbled when <code>printf</code> is called by our NuttX Test Apps, due to concurrent printing by multiple tasks...
<code>text
nx_start_application: Starting init thread
lib_cxx_initialize: _sinit: 0x400e9000 _einit: 0x400e9000
nsh: sysinit: fopen failed: 2
nshn:x _msktfaarttf:s :C PcUo0m:m aBnedg innonti nfgo uInddleLoNouptt
Shell (NSH) NuttX-11.0.0-RC2</code>
<a>(Source)</a>
It's supposed to show...
<code>text
nsh: sysinit: fopen failed: 2
nsh: mkfatfs: command not found
NuttShell (NSH) NuttX-11.0.0-RC2
nsh> nx_start: CPU0: Beginning Idle Loop</code>
<a>(Source)</a>
<em>Why is the output garbled?</em>
The output is garbled because there 2 ways of writing to the Console Output...
<ul>
<li>
<code>up_putc</code>: Called by the NuttX Kernel to log messages (like <code>_info</code>)
</li>
<li>
<code>a64_uart_send</code>: Allwinner A64 UART Driver is called by NuttX Apps to print messages (like <code>printf</code>)
</li>
</ul>
To fix the output garbled at startup: Disable "Scheduler Informational Output" in...
"Build Setup > Debug Options > Enable Debug Features > Scheduler Debug Features"
This prevents <code>sinfo</code> from garbling the <code>printf</code> output...
<ul>
<li><code>sinfo</code> writes directly to UART Port character by character...</li>
</ul>
<code>text
nx_start: CPU0: Beginning Idle Loop</code>
<ul>
<li>Whereas <code>printf</code> is buffered and writes the buffer to the UART Driver...</li>
</ul>
<code>text
nsh: mkfatfs: command not found
NuttShell (NSH) NuttX-11.0.0-RC2</code>
Also we have a temporary workaround until this gets fixed: <a>a64_serial.c</a>
```c
static void a64_uart_send(struct uart_dev_s <em>dev, int ch)
{
const struct a64_uart_port_s </em>port = (struct a64_uart_port_s <em>)dev->priv;
const struct a64_uart_config </em>config = &port->config;
define BUFFER_UART
ifdef BUFFER_UART
//// TODO: Fix the garbled output. Buffer the chars until we see CR or LF.
static char buf[256];
static int pos = 0;
if (ch != '>' && ch != '\r' && ch != '\n' && pos < sizeof(buf))
{
buf[pos] = ch;
pos += 1;
return;
}
for (int i = 0; i < pos; i++)
{
up_putc(buf[i]);
}
pos = 0;
up_putc(ch);
UNUSED(config);
else
/<em> Write char to Transmit Holding Register (UART_THR) </em>/
putreg8(ch, UART_THR(config->uart));
endif // BUFFER_UART
}
```
This forces <code>a64_uart_send</code> to call <code>up_putc</code> to print an entire line of text. (Instead of character by character)
This also means that the <code>nsh</code> prompt will no longer echo text character by character. We need to press Enter to see the <code>nsh</code> output.
FYI: <code>printf</code> Console Output Stream is locked and unlocked with a Mutex. Let's log the locking and unlocking of the Mutex...
<a>nuttx/libs/libc/stdio/lib_libfilelock.c</a>
<code>c
void flockfile(FAR struct file_struct *stream)
{
up_putc('{'); // Log the Mutex Locking
nxrmutex_lock(&stream->fs_lock);
}
...
void funlockfile(FAR struct file_struct *stream)
{
up_putc('}'); // Log the Mutex Unlocking
nxrmutex_unlock(&stream->fs_lock);
}</code>
Output log shows that <code>{</code> and <code>}</code> (Mutex Locking and Unlocking) are nested...
<code>text
nx_start_application: Starting init thread
lib_cxx_initialize: _sinit: 0x400e9000 _einit: 0x400e9000
{{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{n}s}h{:} {s}y{s}i{n}i{t}:{ }f{o}p{e}n{ }f{a}i{l}e{d}:{ }2{
}
{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{}{{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{{}}{n}s}h{:} {m{k}f}a{t}f{s{:} }c{o{m}m}a{n{d} }n{o{t} }f{o{u}n}d{</code>
How can be it locked twice without unlocking?
<a><code>nxrmutex_lock</code></a> calls...
- <a><code>nxmutex_lock</code></a>, which calls...
- <a><code>nxsem_wait</code></a>, which calls...
- <a><code>up_switch_context</code></a>
Let's print the Thread ID and Mutex Count...
```text
void flockfile(FAR struct file_struct *stream)
{
nxrmutex_lock(&stream->fs_lock);
_info("%p, thread=%d, mutex.count=%d\n", stream, gettid(), stream->fs_lock.count); // Log the Thread ID and Mutex Count
}
void funlockfile(FAR struct file_struct *stream)
{
_info("%p, thread=%d, mutex.count=%d\n", stream, gettid(), stream->fs_lock.count); // Log the Thread ID and Mutex Count
nxrmutex_unlock(&stream->fs_lock);
}
```
Thread ID is always the same. Mutex Count goes from 1 to 3 and drops to 2...
<code>text
lib_cxx_initialize: _sinit: 0x400e9000 _einit: 0x400e9000
flockfile: 0x40a5cc78, thread=2, mutex.count=1
flockfile: 0x40a5cc78, thread=2, mutex.count=2
flockfile: 0x40a5cc78, thread=2, mutex.count=3
funlockfile: 0x40a5cc78, thread=2, mutex.count=3
funlockfile: 0x40a5cc78, thread=2, mutex.count=2</code>
Why? That's because <a><code>nxrmutex_lock</code></a> allows the Mutex to be locked multiple times <strong>within the same thread.</strong>
FYI: Here's how we verify whether our code is called by multiple CPU Cores...
```c
include "../arch/arm64/src/common/arm64_arch.h"
_info("up_cpu_index=%d\n", MPIDR_TO_CORE(GET_MPIDR()));
// Shows: <code>up_cpu_index=0</code>
_info("mpidr_el1=%p\n", read_sysreg(mpidr_el1));
// Shows <code>mpidr_el1=0x80000000</code>
```
FYI: How <code>printf</code> works...
<a><code>printf</code></a> calls...
- <a><code>vfprintf</code></a>, which calls...
- <a><code>libvsprintf</code></a>, which calls...
- <a><code>vsprintf_internal</code></a>, which calls...
- <a><code>stream_putc</code></a>, which calls...
- ???, which calls...
- <a><code>fputc</code></a>, which calls...
- <a><code>libfwrite</code></a>
<a><code>fputc</code></a> also calls...
- <a><code>lib_libfflush</code></a>
Configure UART Port
To support multiple UART Ports, we copied the following functions from the <a>Allwinner A1X UART Driver</a>...
<ul>
<li><a><code>arm64_earlyserialinit</code></a></li>
</ul>
(Init the UART Ports)
<ul>
<li><a><code>a64_uart_init</code></a></li>
</ul>
(Init the UART Pins. Called by <a><code>arm64_earlyserialinit</code></a>)
<ul>
<li><a><code>a64_uart_setup</code></a></li>
</ul>
(Configure the UART Port. Called when the UART Port is opened)
<ul>
<li><a><code>a64_uart_irq_handler</code></a></li>
</ul>
(UART Interrupt Handler)
<ul>
<li><a><code>a64_uart_receive</code></a></li>
</ul>
(Receive UART Data)
<a>(Here's the log)</a>
Inside the UART Driver, be careful when logging to the UART Port!
If the UART Port is busy doing logging, it won't allow us to the Baud Rate...
<blockquote>
"This register may only be accessed when the DLAB bit (UART_LCR[7]) is set and the UART is not busy (UART_USR[0] is zero)"
</blockquote>
<a>(Allwinner A64 User Manual, Page 564)</a>
That's why we always wait for UART Not Busy before setting the Baud Rate. <a>(Like this)</a>
<em>What happens if UART Is Busy when we set the Baud Rate?</em>
<code>text
up_setup: Enter DLAB=1
up_serialout: addr=0x1c2800c, before=0x3, after=0x83
up_setup: Set the BAUD divisor
up_serialout: addr=0x1c28004, before=0x0, after=0x0
up_serialout: addr=0x1c28000, before=0x0, after=0xd
up_setup: Clear DLAB
up_serialout: addr=0x1c2800c, before=0x3, after=0x3</code>
<a>(Source)</a>
From above, we see that the Baud Rate is not read correctly...
<code>text
up_serialout: addr=0x1c28000, before=0x0, after=0xd
// For UART0: Before should be 0xd</code>
And DLAB doesn't get cleared correctly...
<code>text
up_setup: Enter DLAB=1
up_serialout: addr=0x1c2800c, before=0x3, after=0x83
...
up_setup: Clear DLAB
up_serialout: addr=0x1c2800c, before=0x3, after=0x3
// Before should be 0x83, not 0x3</code>
We fix this by disabling the logging and waiting for UART Not Busy before setting the Baud Rate. <a>(Like this)</a>
The changes have been upstreamed to NuttX Mainline...
<ul>
<li><a><strong>Pull Request: Support multiple UART Ports</strong></a></li>
</ul>
<em>How do we enable a UART Port? Like UART3?</em>
Head over to the NuttX Build Configuration...
<code>bash
make menuconfig</code>
Then select...
<ul>
<li>System Type > Allwinner A64 Peripheral Selection > UART3</li>
</ul>
To configure the Baud Rate, Parity and Stop Bits...
<ul>
<li>Device Drivers > Serial Driver Support > UART3 Configuration</li>
</ul>
(The default Baud Rate / Bits / Parity / Stop Bits work OK with the PinePhone LTE Modem on UART3: 115.2 kbps / 8 Bits / No Parity / 1 Stop Bit)
Let's test the PinePhone LTE Modem on UART3...
Test UART3 Port
In the previous section we have configured UART3 for PinePhone's <a>4G LTE Modem</a>.
This is how we read and write the UART3 port via <code>/dev/ttyS1</code>: <a>hello_main.c</a>
```c
// Open /dev/ttyS1 (UART3)
int fd = open("/dev/ttyS1", O_RDWR);
printf("Open /dev/ttyS1: fd=%d\n", fd);
assert(fd > 0);
// Repeat 5 times: Write command and read response
for (int i = 0; i < 5; i++) {
// Write command
const char cmd[] = "AT\r";
ssize_t nbytes = write(fd, cmd, sizeof(cmd));
printf("Write command: nbytes=%ld\n", nbytes);
assert(nbytes == sizeof(cmd));
// Read response
static char buf[1024];
nbytes = read(fd, buf, sizeof(buf) - 1);
if (nbytes >= 0) { buf[nbytes] = 0; }
printf("Response: nbytes=%ld\n%s\n", nbytes, buf);
// Wait a while
sleep(2);
}
// Close the device
close(fd);
```
LTE Modem works OK with UART3 on NuttX yay! See the test log here...
<ul>
<li><a>"Test UART with NuttX"</a></li>
</ul>
<strong>Note:</strong> Modem UART flow control is broken
<blockquote>
"Not resolved in v1.2 -- assumption is that USB will be used for high-bandwidth modem I/O.
BB-TX and BB-RX are connected to UART3 (PD0/PD1). BB-RTS and BB-CTS are connected to UART4 (PD4/PD5). To use hardware flow control, TX/RX would need to be connected to UART4, swapping PD0/PD1 with the motor control and rear camera reset GPIOs at PD2/PD3. This would need a device tree change.
Hardware flow control can be disabled with the AT+IFC command, and USB can also be used for commands instead of the UART. So the impact of this problem is unclear."
</blockquote>
<a>(Source)</a>
Boot NuttX on PinePhone
Read the article...
<ul>
<li><a>"PinePhone boots Apache NuttX RTOS"</a></li>
</ul>
PinePhone U-Boot Log
Before starting the Linux Kernel, PinePhone boots by running the U-Boot Bootloader...
<ul>
<li>
<a>A64 Boot ROM</a>
</li>
<li>
<a>A64 U-Boot</a>
</li>
<li>
<a>A64 U-Boot SPL</a>
</li>
<li>
<a>SD Card Layout</a>
</li>
</ul>
Here's the PinePhone U-Boot Log captured with the USB Serial Debug Cable...
(Press Enter repeatedly when PinePhone powers on to enter the U-Boot Prompt)
```text
$ screen /dev/ttyUSB0 115200
DRAM: 2048 MiB
Trying to boot from MMC1
NOTICE: BL31: v2.2(release):v2.2-904-gf9ea3a629
NOTICE: BL31: Built : 15:32:12, Apr 9 2020
NOTICE: BL31: Detected Allwinner A64/H64/R18 SoC (1689)
NOTICE: BL31: Found U-Boot DTB at 0x4064410, model: PinePhone
NOTICE: PSCI: System suspend is unavailable
U-Boot 2020.07 (Nov 08 2020 - 00:15:12 +0100)
DRAM: 2 GiB
MMC: Device 'mmc@1c11000': seq 1 is in use by 'mmc@1c10000'
mmc@1c0f000: 0, mmc@1c10000: 2, mmc@1c11000: 1
Loading Environment from FAT... *** Warning - bad CRC, using default environment
starting USB...
No working controllers found
Hit any key to stop autoboot:
=> help
? - alias for 'help'
base - print or set address offset
bdinfo - print Board Info structure
blkcache - block cache diagnostics and control
boot - boot default, i.e., run 'bootcmd'
bootd - boot default, i.e., run 'bootcmd'
bootelf - Boot from an ELF image in memory
booti - boot Linux kernel 'Image' format from memory
bootm - boot application image from memory
bootvx - Boot vxWorks from an ELF image
cmp - memory compare
coninfo - print console devices and information
cp - memory copy
crc32 - checksum calculation
dm - Driver model low level access
echo - echo args to console
editenv - edit environment variable
env - environment handling commands
exit - exit script
ext2load - load binary file from a Ext2 filesystem
ext2ls - list files in a directory (default /)
ext4load - load binary file from a Ext4 filesystem
ext4ls - list files in a directory (default /)
ext4size - determine a file's size
false - do nothing, unsuccessfully
fatinfo - print information about filesystem
fatload - load binary file from a dos filesystem
fatls - list files in a directory (default /)
fatmkdir - create a directory
fatrm - delete a file
fatsize - determine a file's size
fatwrite - write file into a dos filesystem
fdt - flattened device tree utility commands
fstype - Look up a filesystem type
go - start application at address 'addr'
gpio - query and control gpio pins
gpt - GUID Partition Table
gzwrite - unzip and write memory to block device
help - print command description/usage
iminfo - print header information for application image
imxtract - extract a part of a multi-image
itest - return true/false on integer compare
ln - Create a symbolic link
load - load binary file from a filesystem
loadb - load binary file over serial line (kermit mode)
loads - load S-Record file over serial line
loadx - load binary file over serial line (xmodem mode)
loady - load binary file over serial line (ymodem mode)
loop - infinite loop on address range
ls - list files in a directory (default /)
lzmadec - lzma uncompress a memory region
md - memory display
mm - memory modify (auto-incrementing address)
mmc - MMC sub system
mmcinfo - display MMC info
mw - memory write (fill)
nm - memory modify (constant address)
part - disk partition related commands
poweroff - Perform POWEROFF of the device
printenv - print environment variables
random - fill memory with random pattern
reset - Perform RESET of the CPU
run - run commands in an environment variable
save - save file to a filesystem
saveenv - save environment variables to persistent storage
setenv - set environment variables
setexpr - set environment variable as the result of eval expression
sf - SPI flash sub-system
showvar - print local hushshell variables
size - determine a file's size
sleep - delay execution for some time
source - run script from memory
sysboot - command to get and boot from syslinux files
test - minimal test like /bin/sh
true - do nothing, successfully
unlz4 - lz4 uncompress a memory region
unzip - unzip a memory region
usb - USB sub-system
usbboot - boot from USB device
version - print monitor, compiler and linker version
=> printenv
arch=arm
baudrate=115200
board=sunxi
board_name=sunxi
boot_a_script=load ${devtype} ${devnum}:${distro_bootpart} ${scriptaddr} ${prefix}${script}; source ${scriptaddr}
boot_extlinux=sysboot ${devtype} ${devnum}:${distro_bootpart} any ${scriptaddr} ${prefix}${boot_syslinux_conf}
boot_net_usb_start=usb start
boot_prefixes=/ /boot/
boot_script_dhcp=boot.scr.uimg
boot_scripts=boot.scr.uimg boot.scr
boot_syslinux_conf=extlinux/extlinux.conf
boot_targets=fel mmc_auto usb0
bootcmd=run distro_bootcmd
bootcmd_fel=if test -n ${fel_booted} && test -n ${fel_scriptaddr}; then echo '(FEL boot)'; source ${fel_scriptaddr}; fi
bootcmd_mmc0=devnum=0; run mmc_boot
bootcmd_mmc1=devnum=1; run mmc_boot
bootcmd_mmc_auto=if test ${mmc_bootdev} -eq 1; then run bootcmd_mmc1; run bootcmd_mmc0; elif test ${mmc_bootdev} -eq 0; then run bootcmd_mmc0; run bootcmd_mmc1; fi
bootcmd_usb0=devnum=0; run usb_boot
bootdelay=0
bootm_size=0xa000000
console=ttyS0,115200
cpu=armv8
dfu_alt_info_ram=kernel ram 0x40080000 0x1000000;fdt ram 0x4FA00000 0x100000;ramdisk ram 0x4FE00000 0x4000000
distro_bootcmd=for target in ${boot_targets}; do run bootcmd_${target}; done
ethaddr=02:ba:8c:73:bf:ca
fdt_addr_r=0x4FA00000
fdtcontroladdr=bbf4dd40
fdtfile=allwinner/sun50i-a64-pinephone.dtb
kernel_addr_r=0x40080000
mmc_boot=if mmc dev ${devnum}; then devtype=mmc; run scan_dev_for_boot_part; fi
mmc_bootdev=0
partitions=name=loader1,start=8k,size=32k,uuid=${uuid_gpt_loader1};name=loader2,size=984k,uuid=${uuid_gpt_loader2};name=esp,size=128M,bootable,uuid=${uuid_gpt_esp};name=system,size=-,uuid=${uuid_gpt_system};
preboot=usb start
pxefile_addr_r=0x4FD00000
ramdisk_addr_r=0x4FE00000
scan_dev_for_boot=echo Scanning ${devtype} ${devnum}:${distro_bootpart}...; for prefix in ${boot_prefixes}; do run scan_dev_for_extlinux; run scan_dev_for_scripts; done;
scan_dev_for_boot_part=part list ${devtype} ${devnum} -bootable devplist; env exists devplist || setenv devplist 1; for distro_bootpart in ${devplist}; do if fstype ${devtype} ${devnum}:${distro_bootpart} bootfstype; then run scan_dev_for_boot; fi; done; setenv devplist
scan_dev_for_extlinux=if test -e ${devtype} ${devnum}:${distro_bootpart} ${prefix}${boot_syslinux_conf}; then echo Found ${prefix}${boot_syslinux_conf}; run boot_extlinux; echo SCRIPT FAILED: continuing...; fi
scan_dev_for_scripts=for script in ${boot_scripts}; do if test -e ${devtype} ${devnum}:${distro_bootpart} ${prefix}${script}; then echo Found U-Boot script ${prefix}${script}; run boot_a_script; echo SCRIPT FAILED: continuing...; fi; done?
scriptaddr=0x4FC00000
serial#=92c07dba8c73bfca
soc=sunxi
stderr=serial@1c28000
stdin=serial@1c28000
stdout=serial@1c28000
usb_boot=usb start; if usb dev ${devnum}; then devtype=usb; run scan_dev_for_boot_part; fi
uuid_gpt_esp=c12a7328-f81f-11d2-ba4b-00a0c93ec93b
uuid_gpt_system=b921b045-1df0-41c3-af44-4c6f280d3fae
Environment size: 2861/131068 bytes
=> boot
switch to partitions #0, OK
mmc0 is current device
Scanning mmc 0:1...
Found U-Boot script /boot.scr
653 bytes read in 3 ms (211.9 KiB/s)
Executing script at 4fc00000
gpio: pin 114 (gpio 114) value is 1
4275261 bytes read in 192 ms (21.2 MiB/s)
Uncompressed size: 10170376 = 0x9B3008
36162 bytes read in 4 ms (8.6 MiB/s)
1078500 bytes read in 51 ms (20.2 MiB/s)
Flattened Device Tree blob at 4fa00000
Booting using the fdt blob at 0x4fa00000
Loading Ramdisk to 49ef8000, end 49fff4e4 ... OK
Loading Device Tree to 0000000049eec000, end 0000000049ef7d41 ... OK
Starting kernel ...
/ #
```
According to the U-Boot Log, the Start of RAM <code>kernel_addr_r</code> is 0x4008 0000.
We need to set this in the NuttX Linker Script and the NuttX Header...
NuttX Boots On PinePhone
In the previous section, U-Boot says that the Start of RAM <code>kernel_addr_r</code> is 0x4008 0000.
Let's set this in the NuttX Linker Script and the NuttX Header...
<ul>
<li>
Change Image Load Offset in NuttX Header to 0x0 (from 0x48000)
<a>(See the changes)</a>
</li>
<li>
Change NuttX Linker Script to set the Start Address <code>_start</code> to 0x4008 0000 (from 0x4028 0000)
<a>(See the changes)</a>
</li>
</ul>
For PinePhone Allwinner A64 UART: We reused the previous code for transmitting output to UART...
```text
/<em> PL011 UART transmit character
* xb: register which contains the UART base address
* wt: register which contains the character to transmit
</em>/
.macro early_uart_transmit xb, wt
strb \wt, [\xb] /<em> -> UARTDR (Data Register) </em>/
.endm
```
<a>(Source)</a>
But we updated the UART Register Address for Allwinner A64 UART...
```text
/<em> 32-bit register definition for qemu pl011 uart </em>/
/<em> PinePhone Allwinner A64 UART0 Base Address: </em>/
#define UART1_BASE_ADDRESS 0x01C28000
/<em> Previously: #define UART1_BASE_ADDRESS 0x9000000 </em>/
#define EARLY_UART_PL011_BAUD_RATE 115200
```
<a>(Source)</a>
Right now we don't check if UART is ready to transmit, so our UART output will have missing characters. This needs to be fixed...
```text
/<em> PL011 UART wait UART to be ready to transmit
* xb: register which contains the UART base address
* c: scratch register number
</em>/
.macro early_uart_ready xb, wt
1:
# TODO: Wait for PinePhone Allwinner A64 UART
# ldrh \wt, [\xb, #0x18] /<em> <- UARTFR (Flag register) </em>/
# tst \wt, #0x8 /<em> Check BUSY bit </em>/
# b.ne 1b /<em> Wait for the UART to be ready </em>/
.endm
```
<a>(Source)</a>
We don't init the UART Port because U-Boot has kindly done it for us. This needs to be fixed...
```text
/<em> PL011 UART initialization
* xb: register which contains the UART base address
* c: scratch register number
</em>/
GTEXT(up_earlyserialinit)
SECTION_FUNC(text, up_earlyserialinit)
# TODO: Set PinePhone Allwinner A64 Baud Rate Divisor: UART_LCR (DLAB), UART_DLL, UART_DLH
# ldr x15, =UART1_BASE_ADDRESS
# mov x0, #(7372800 / EARLY_UART_PL011_BAUD_RATE % 16)
# strh w0, [x15, #0x28] /<em> -> UARTFBRD (Baud divisor fraction) </em>/
# mov x0, #(7372800 / EARLY_UART_PL011_BAUD_RATE / 16)
# strh w0, [x15, #0x24] /<em> -> UARTIBRD (Baud divisor integer) </em>/
# mov x0, #0x60 /<em> 8n1 </em>/
# str w0, [x15, #0x2C] /<em> -> UARTLCR_H (Line control) </em>/
# ldr x0, =0x00000301 /<em> RXE | TXE | UARTEN </em>/
# str w0, [x15, #0x30] /<em> -> UARTCR (Control Register) </em>/
ret
```
<a>(Source)</a>
With the above changes, NuttX boots on PinePhone yay!
<a><strong>Watch the Demo on YouTube</strong></a>
NuttX Boot Log
This is how we build NuttX for PinePhone...
```bash
TODO: Install Build Prerequisites
https://lupyuen.github.io/articles/uboot#install-prerequisites
Create NuttX Directory
mkdir nuttx
cd nuttx
Download NuttX OS for PinePhone
git clone \
--recursive \
--branch pinephone \
https://github.com/lupyuen/incubator-nuttx \
nuttx
Download NuttX Apps for PinePhone
git clone \
--recursive \
--branch pinephone \
https://github.com/lupyuen/incubator-nuttx-apps \
apps
We'll build NuttX inside nuttx/nuttx
cd nuttx
Configure NuttX for Single Core
./tools/configure.sh -l qemu-a53:nsh
Build NuttX
make
Dump the disassembly to nuttx.S
aarch64-none-elf-objdump \
-t -S --demangle --line-numbers --wide \
nuttx \
<blockquote>
nuttx.S \
2>&1
</blockquote>
Compress the NuttX Binary Image
cp nuttx.bin Image
rm -f Image.gz
gzip Image
Copy compressed NuttX Binary Image to Jumpdrive microSD.
How to create Jumpdrive microSD: https://lupyuen.github.io/articles/uboot#pinephone-jumpdrive
TODO: Change the microSD Path
cp Image.gz "/Volumes/NO NAME"
```
Insert the Jumpdrive microSD into PinePhone and power up.
Here's the UART Log of NuttX booting on PinePhone...
```text
DRAM: 2048 MiB
Trying to boot from MMC1
NOTICE: BL31: v2.2(release):v2.2-904-gf9ea3a629
NOTICE: BL31: Built : 15:32:12, Apr 9 2020
NOTICE: BL31: Detected Allwinner A64/H64/R18 SoC (1689)
NOTICE: BL31: Found U-Boot DTB at 0x4064410, model: PinePhone
NOTICE: PSCI: System suspend is unavailable
U-Boot 2020.07 (Nov 08 2020 - 00:15:12 +0100)
DRAM: 2 GiB
MMC: Device 'mmc@1c11000': seq 1 is in use by 'mmc@1c10000'
mmc@1c0f000: 0, mmc@1c10000: 2, mmc@1c11000: 1
Loading Environment from FAT... *** Warning - bad CRC, using default environment
starting USB...
No working controllers found
Hit any key to stop autoboot: 0
switch to partitions #0, OK
mmc0 is current device
Scanning mmc 0:1...
Found U-Boot script /boot.scr
653 bytes read in 3 ms (211.9 KiB/s)
Executing script at 4fc00000
gpio: pin 114 (gpio 114) value is 1
99784 bytes read in 8 ms (11.9 MiB/s)
Uncompressed size: 278528 = 0x44000
36162 bytes read in 4 ms (8.6 MiB/s)
1078500 bytes read in 51 ms (20.2 MiB/s)
Flattened Device Tree blob at 4fa00000
Booting using the fdt blob at 0x4fa00000
Loading Ramdisk to 49ef8000, end 49fff4e4 ... OK
Loading Device Tree to 0000000049eec000, end 0000000049ef7d41 ... OK
Starting kernel ...
HELLO NUTTX ON PINEPHONE!
- Ready to Boot CPU
- Boot from EL2
- Boot from EL1
- Boot to C runtime for OS Initialize
nx_start: Entry
up_allocate_heap: heap_start=0x0x400c4000, heap_size=0x7f3c000
arm64_gic_initialize: TODO: Init GIC for PinePhone
arm64_gic_initialize: CONFIG_GICD_BASE=0x1c81000
arm64_gic_initialize: CONFIG_GICR_BASE=0x1c82000
arm64_gic_initialize: GIC Version is 2
up_timer_initialize: up_timer_initialize: cp15 timer(s) running at 24.00MHz, cycle 24000
up_timer_initialize: _vector_table=0x400a7000
up_timer_initialize: Before writing: vbar_el1=0x40227000
up_timer_initialize: After writing: vbar_el1=0x400a7000
uart_register: Registering /dev/console
uart_register: Registering /dev/ttyS0
work_start_highpri: Starting high-priority kernel worker thread(s)
nx_start_application: Starting init thread
lib_cxx_initialize: _sinit: 0x400a7000 _einit: 0x400a7000 _stext: 0x40080000 _etext: 0x400a8000
nsh: sysinit: fopen failed: 2
nshn:x _msktfaarttf:s :C PcUo0m:m aBnedg innonti nfgo uInddle L oNouptt
Shell (NSH) NuttX-10.3.0-RC2
nsh> uname -a
NuttX 10.3.0-RC2 fc909c6-dirty Sep 1 2022 17:05:44 arm64 qemu-a53
nsh> help
help usage: help [-v] []
. cd dmesg help mount rmdir true xd
[ cp echo hexdump mv set truncate
? cmp exec kill printf sleep uname
basename dirname exit ls ps source umount
break dd false mkdir pwd test unset
cat df free mkrd rm time usleep
Builtin Apps:
getprime hello nsh ostest sh
nsh> hello
task_spawn: name=hello entry=0x4009b1a0 file_actions=0x400c9580 attr=0x400c9588 argv=0x400c96d0
spawn_execattrs: Setting policy=2 priority=100 for pid=3
Hello, World!!
nsh> ls /dev
/dev:
console
null
ram0
ram2
ttyS0
zero
```
<a><strong>Watch the Demo on YouTube</strong></a>
The output is slightly garbled, the UART Driver needs fixing.
Interrupt Controller
Read the article...
<ul>
<li><a>"NuttX RTOS for PinePhone: Fixing the Interrupts"</a></li>
</ul>
Let's talk about the <strong>Arm Generic Interrupt Controller (GIC)</strong> for PinePhone...
<code>text
arm64_gic_initialize: TODO: Init GIC for PinePhone
arm64_gic_initialize: CONFIG_GICD_BASE=0x1c81000
arm64_gic_initialize: CONFIG_GICR_BASE=0x1c82000
arm64_gic_initialize: GIC Version is 2</code>
This is the current implementation of <a>Arm GIC Version 3</a> in NuttX Arm64...
<ul>
<li>
<a>arch/arm64/src/common/arm64_gicv3.c</a>
</li>
<li>
<a>arch/arm64/src/common/arm64_gic.h</a>
</li>
</ul>
This implementation won't work on PinePhone, so we have commented out the existing code and inserted our own implementation.
<em>Why won't Arm GIC Version 3 work on PinePhone?</em>
According to the Allwinner A64 SoC User Manual (page 210, "GIC"), PinePhone's Interrupt Controller runs on...
<ul>
<li>
<a>Arm GIC PL400</a>, which is based on...
</li>
<li>
<a>Arm GIC Version 2</a>
</li>
</ul>
We'll have to downgrade <a>arm64_gicv3.c</a> to support Arm GIC Version 2 for PinePhone.
<em>Does NuttX implement Arm GIC Version 2?</em>
NuttX has an implementation of Arm GIC Version 2, but it's based on Arm32. We'll port it from Arm32 to Arm64...
<ul>
<li>
<a>arch/arm/src/armv7-a/arm_gicv2.c</a>
</li>
<li>
<a>arch/arm/src/armv7-a/arm_gicv2_dump.c</a>
</li>
<li>
<a>arch/arm/src/armv7-a/gic.h</a>
</li>
<li>
<a>arch/arm/src/armv7-a/mpcore.h</a>
</li>
<li>
<a>arch/arm/src/imx6/chip.h</a>
</li>
<li>
<a>arch/arm/src/imx6/hardware/imx_memorymap.h</a>
</li>
</ul>
By reusing the code above, we have implemented Arm GIC Version 2 for PinePhone...
<ul>
<li><a>arch/arm64/src/common/arm64_gicv3.c</a></li>
</ul>
We made minor tweaks to NuttX's implementation of GIC Version 2...
<ul>
<li>
<a>Changes for arch/arm/src/armv7-a/arm_gicv2.c</a>
</li>
<li>
<a>Changes for arch/arm/src/armv7-a/arm_gicv2_dump.c</a>
</li>
<li>
<a>Changes for arch/arm/src/armv7-a/gic.h</a>
</li>
</ul>
<em>Where in memory is the GIC located?</em>
According to the Allwinner A64 SoC User Manual (page 74, "Memory Mapping"), the GIC is located at this address...
| Module | Address (It is for Cluster CPU) | Remarks
| :----- | :------ | :------
|SCU space | 0x01C80000| (What's this?)
| | GIC_DIST: 0x01C80000 + 0x1000| GIC Distributor (GICD)
|CPUS can’t access | GIC_CPUIF:0x01C80000 + 0x2000| GIC CPU Interface (GICC)
(Why "CPUS can’t access"?)
The <strong>Interrupt Sources</strong> are defined in the Allwinner A64 SoC User Manual (page 210, "GIC")...
<ul>
<li>
16 x Software-Generated Interrupts (SGI)
"This is an interrupt generated by software writing to a GICD_SGIR register in the GIC. The system uses SGIs for interprocessor communication."
</li>
<li>
16 x Private Peripheral Interrupts (PPI)
"This is a peripheral interrupt that is specific to a single processor"
</li>
<li>
125 x Shared Peripheral Interrupts (SPI)
"This is a peripheral interrupt that the Distributor can route to any of a specified combination of processors"
</li>
</ul>
To verify the GIC Version, read the <strong>Peripheral ID2 Register (ICPIDR2)</strong> at Offset 0xFE8 of GIC Distributor.
Bits 4 to 7 of ICPIDR2 are...
<ul>
<li>0x1 for GIC Version 1</li>
<li>0x2 for GIC Version 2</li>
</ul>
This is how we implement the GIC Version verification: <a>arch/arm64/src/common/arm64_gicv3.c</a>
```c
// Init GIC v2 for PinePhone. See https://github.com/lupyuen/pinephone-nuttx#interrupt-controller
int arm64_gic_initialize(void)
{
sinfo("TODO: Init GIC for PinePhone\n");
// To verify the GIC Version, read the Peripheral ID2 Register (ICPIDR2) at Offset 0xFE8 of GIC Distributor.
// Bits 4 to 7 of ICPIDR2 are...
// - 0x1 for GIC Version 1
// - 0x2 for GIC Version 2
// GIC Distributor is at 0x01C80000 + 0x1000.
// See https://github.com/lupyuen/pinephone-nuttx#interrupt-controller
const uint8_t <em>ICPIDR2 = (const uint8_t </em>) (CONFIG_GICD_BASE + 0xFE8);
uint8_t version = (*ICPIDR2 >> 4) & 0b1111;
sinfo("GIC Version is %d\n", version);
DEBUGASSERT(version == 2);
// arm_gic0_initialize must be called on CPU0
arm_gic0_initialize();
// arm_gic_initialize must be called for all CPUs
// TODO: Move to arm64_gic_secondary_init
arm_gic_initialize();
return 0;
}
```
See below for the <a>GIC Register Dump</a>.
Multi Core SMP
Right now NuttX is configured to run on a Single Core for PinePhone.
To support all 4 Cores on PinePhone with SMP (Symmetric Multi-Processing), we need to fix these in the Generic Interrupt Controller Version 2...
https://github.com/lupyuen/incubator-nuttx/blob/pinephone/arch/arm64/src/common/arm64_gicv3.c#L717-L743
```c
// Init GIC v2 for PinePhone. See https://github.com/lupyuen/pinephone-nuttx#interrupt-controller
int arm64_gic_initialize(void)
{
...
// arm_gic0_initialize must be called on CPU0
arm_gic0_initialize();
// arm_gic_initialize must be called for all CPUs
// TODO: Move to arm64_gic_secondary_init
arm_gic_initialize();
```
https://github.com/lupyuen/incubator-nuttx/blob/pinephone/arch/arm64/src/common/arm64_gicv3.c#L746-L761
```c
ifdef CONFIG_SMP
...
// TODO: Init GIC for PinePhone
void arm64_gic_secondary_init(void)
{
sinfo("TODO: Init GIC Secondary for PinePhone\n");
// TODO: arm_gic_initialize must be called for all CPUs.
arm_gic_initialize();
}
endif // NOTUSED
```
And we rebuild NuttX for Multi Core...
```bash
Erase the NuttX Configuration
make distclean
Configure NuttX for 4 Cores
./tools/configure.sh -l qemu-a53:nsh_smp
Build NuttX
make
Dump the disassembly to nuttx.S
aarch64-none-elf-objdump \
-t -S --demangle --line-numbers --wide \
nuttx \
<blockquote>
nuttx.S \
2>&1
```
</blockquote>
System Timer
NuttX starts the System Timer when it boots. Here's how the System Timer is started: <a>arch/arm64/src/common/arm64_arch_timer.c</a>
```c
void up_timer_initialize(void)
{
uint64_t curr_cycle;
arch_timer_rate = arm64_arch_timer_get_cntfrq();
cycle_per_tick = ((uint64_t)arch_timer_rate / (uint64_t)TICK_PER_SEC);
sinfo("%s: cp15 timer(s) running at %lu.%02luMHz, cycle %ld\n", <strong>func</strong>,
(unsigned long)arch_timer_rate / 1000000,
(unsigned long)(arch_timer_rate / 10000) % 100, cycle_per_tick);
irq_attach(ARM_ARCH_TIMER_IRQ, arm64_arch_timer_compare_isr, 0);
arm64_gic_irq_set_priority(ARM_ARCH_TIMER_IRQ, ARM_ARCH_TIMER_PRIO,
ARM_ARCH_TIMER_FLAGS);
curr_cycle = arm64_arch_timer_count();
arm64_arch_timer_set_compare(curr_cycle + cycle_per_tick);
arm64_arch_timer_enable(true);
up_enable_irq(ARM_ARCH_TIMER_IRQ);
arm64_arch_timer_set_irq_mask(false);
}
```
At every tick, the System Timer triggers an interrupt that calls <a><code>arm64_arch_timer_compare_isr</code></a>
(<code>CONFIG_SCHED_TICKLESS</code> is undefined)
<strong>Timer IRQ <code>ARM_ARCH_TIMER_IRQ</code></strong> is defined in <a>arch/arm64/src/common/arm64_arch_timer.h</a>
```c
define CONFIG_ARM_TIMER_SECURE_IRQ (GIC_PPI_INT_BASE + 13)
define CONFIG_ARM_TIMER_NON_SECURE_IRQ (GIC_PPI_INT_BASE + 14)
define CONFIG_ARM_TIMER_VIRTUAL_IRQ (GIC_PPI_INT_BASE + 11)
define CONFIG_ARM_TIMER_HYP_IRQ (GIC_PPI_INT_BASE + 10)
define ARM_ARCH_TIMER_IRQ CONFIG_ARM_TIMER_VIRTUAL_IRQ
define ARM_ARCH_TIMER_PRIO IRQ_DEFAULT_PRIORITY
define ARM_ARCH_TIMER_FLAGS IRQ_TYPE_LEVEL
```
<code>GIC_PPI_INT_BASE</code> is defined in <a>arch/arm64/src/common/arm64_gic.h</a>
```c
define GIC_SGI_INT_BASE 0
define GIC_PPI_INT_BASE 16
#define GIC_IS_SGI(intid) (((intid) >= GIC_SGI_INT_BASE) && \
((intid) < GIC_PPI_INT_BASE))
define GIC_SPI_INT_BASE 32
define GIC_NUM_INTR_PER_REG 32
define GIC_NUM_CFG_PER_REG 16
define GIC_NUM_PRI_PER_REG 4
```
Timer Interrupt Isn't Handled
Previously NuttX hangs midsentence while booting on PinePhone, let's find out how we fixed it...
<code>text
arm64_gic_initialize: TODO: Init GIC for PinePhone
arm64_gic_initialize: CONFIG_GICD_BASE=0x1c81000
arm64_gic_initialize: CONFIG_GICR_BASE=0x1c82000
arm64_gic_initialize: GIC Version is 2
up_timer_initialize: up_timer_initialize: cp15 timer(s) running at 24.00MHz, cycle 24000
uart_regi</code>
Based on our experiments, it seems the <a>System Timer</a> triggered a Timer Interrupt, and NuttX hangs while attempting to handle the Timer Interrupt.
The Timer Interrupt Handler <a><code>arm64_arch_timer_compare_isr</code></a> is never called. (We checked using <a><code>up_putc</code></a>)
<em>Is it caused by PinePhone's GIC?</em>
This problem doesn't seem to be caused by <a>PinePhone's Generic Interrupt Controller (GIC)</a> that we have implemented. We <a>successfully tested PinePhone's GIC</a> with QEMU.
Let's troubleshoot the Timer Interrupt...
<ul>
<li>
We called <a><code>up_putc</code></a> to understand <a>how Interrupts are handled on NuttX</a>.
We also added Debug Code to the <a>Arm64 Interrupt Handler</a>.
<a>(Maybe we should have used GDB with QEMU)</a>
</li>
<li>
We <a>dumped the Interrupt Vector Table</a>.
We verified that the Timer Interrupt Handler Address in the table is correct.
</li>
<li>
We confirmed that <a>Interrupt Dispatcher <code>irq_dispatch</code></a> isn't called.
And <a>Unexpected Interrupt Handler <code>irq_unexpected_isr</code></a> isn't called either.
</li>
<li>
Let's backtrack, maybe there's a problem in the Arm64 Interrupt Handler?
But <a><code>arm64_enter_exception</code></a> and <a><code>arm64_irq_handler</code></a> aren't called either.
</li>
<li>
Maybe the <strong>Arm64 Vector Table <code>_vector_table</code></strong> isn't correctly configured?
<a>arch/arm64/src/common/arm64_vector_table.S</a>
</li>
</ul>
And we're right! The Arm64 Vector Table is indeed incorrectly configured! Here why...
Arm64 Vector Table Is Wrong
Earlier we saw that the Interrupt Handler wasn't called for System Timer Interrupt. And it might be due to problems in the <strong>Arm64 Vector Table <code>_vector_table</code></strong>: <a>arch/arm64/src/common/arm64_vector_table.S</a>
Let's check whether the Arm64 Vector Table <code>_vector_table</code> is correctly configured in the Arm CPU: <a>arch/arm64/src/common/arm64_arch_timer.c</a>
```c
void up_timer_initialize(void)
{
...
// Attach System Timer Interrupt Handler
irq_attach(ARM_ARCH_TIMER_IRQ, arm64_arch_timer_compare_isr, 0);
// For PinePhone: Read Vector Base Address Register EL1
extern void *_vector_table[];
sinfo("_vector_table=%p\n", _vector_table);
sinfo("Before writing: vbar_el1=%p\n", read_sysreg(vbar_el1));
```
After attaching the Interrupt Handler for System Timer, we read the Arm64 <a>Vector Base Address Register EL1</a>. Here's the output...
<code>text
up_timer_initialize: up_timer_initialize: cp15 timer(s) running at 24.00MHz, cycle 24000
up_timer_initialize: _vector_table=0x400a7000
up_timer_initialize: Before writing: vbar_el1=0x40227000</code>
Aha! <code>_vector_table</code> is at 0x400a7000... But Vector Base Address Register EL1 says 0x40227000!
Our Arm64 CPU is pointing to the wrong Arm64 Vector Table... Hence our Interrupt Handler is never called!
Let's fix the Vector Base Address Register EL1: <a>arch/arm64/src/common/arm64_arch_timer.c</a>
```c
// For PinePhone: Write Vector Base Address Register EL1
write_sysreg((uint64_t)_vector_table, vbar_el1);
ARM64_ISB();
// For PinePhone: Read Vector Base Address Register EL1
sinfo("After writing: vbar_el1=%p\n", read_sysreg(vbar_el1));
```
This writes the correct value of <code>_vector_table</code> back into Vector Base Address Register EL1. Here's the output...
<code>text
up_timer_initialize: up_timer_initialize: cp15 timer(s) running at 24.00MHz, cycle 24000
up_timer_initialize: _vector_table=0x400a7000
up_timer_initialize: Before writing: vbar_el1=0x40227000
up_timer_initialize: After writing: vbar_el1=0x400a7000</code>
Yep Vector Base Address Register EL1 is now correct.
And our Interrupt Handlers are now working fine yay!
Test PinePhone GIC with QEMU
This is how we build NuttX for QEMU with <a>Generic Interrupt Controller (GIC) Version 2</a>...
```bash
TODO: Install Build Prerequisites
https://lupyuen.github.io/articles/uboot#install-prerequisites
Create NuttX Directory
mkdir nuttx
cd nuttx
Download NuttX OS for QEMU with GIC Version 2
git clone \
--recursive \
--branch gicv2 \
https://github.com/lupyuen/incubator-nuttx \
nuttx
Download NuttX Apps for QEMU
git clone \
--recursive \
--branch arm64 \
https://github.com/lupyuen/incubator-nuttx-apps \
apps
We'll build NuttX inside nuttx/nuttx
cd nuttx
Configure NuttX for Single Core
./tools/configure.sh -l qemu-a53:nsh
Build NuttX
make
Dump the disassembly to nuttx.S
aarch64-none-elf-objdump \
-t -S --demangle --line-numbers --wide \
nuttx \
<blockquote>
nuttx.S \
2>&1
```
</blockquote>
And this is how we tested PinePhone's GIC Version 2 with QEMU...
```bash
Run GIC v2 with QEMU
qemu-system-aarch64 \
-smp 4 \
-cpu cortex-a53 \
-nographic \
-machine virt,virtualization=on,gic-version=2 \
-net none \
-chardev stdio,id=con,mux=on \
-serial chardev:con \
-mon chardev=con,mode=readline \
-kernel ./nuttx
```
Note that <code>gic-version=2</code>, instead of the usual GIC Version 3 for NuttX Arm64.
Also we simulated 4 Cores of Arm Cortex-A53 (similar to PinePhone): <code>-smp 4</code>
QEMU boots OK with PinePhone's GIC Version 2...
```text
- Ready to Boot CPU
- Boot from EL2
- Boot from EL1
- Boot to C runtime for OS Initialize
nx_start: Entry
up_allocate_heap: heap_start=0x0x402c4000, heap_size=0x7d3c000
arm64_gic_initialize: TODO: Init GIC for PinePhone
arm64_gic_initialize: CONFIG_GICD_BASE=0x8000000
arm64_gic_initialize: CONFIG_GICR_BASE=0x8010000
arm64_gic_initialize: GIC Version is 2
EFGHup_timer_initialize: up_timer_initialize: cp15 timer(s) running at 62.50MHz, cycle 62500
AKLMNOPBIJuart_register: Registering /dev/console
uart_register: Registering /dev/ttyS0
AKLMNOPBIJwork_start_highpri: Starting high-priority kernel worker thread(s)
nx_start_application: Starting init thread
lib_cxx_initialize: _sinit: 0x402a7000 _einit: 0x402a7000 _stext: 0x40280000 _etext: 0x402a8000
nsh: sysinit: fopen failed: 2
nsh: mkfatfs: command not found
NuttShell (NSH) NuttX-10.3.0-RC2
nsh> nx_start: CPU0: Beginning Idle Loop
```
So our implementation of GIC Version 2 for PinePhone is probably OK.
<em>Is the Timer Interrupt triggered correctly with PinePhone GIC?</em>
Yes, we verified that the Timer Interrupt Handler <a><code>arm64_arch_timer_compare_isr</code></a> is called periodically. (We checked using <a><code>up_putc</code></a>)
<em>How did we get the GIC Base Addresses?</em>
<code>text
arm64_gic_initialize: CONFIG_GICD_BASE=0x8000000
arm64_gic_initialize: CONFIG_GICR_BASE=0x8010000</code>
We got the GIC v2 Base Addresses for GIC Distributor (<code>CONFIG_GICD_BASE</code>) and GIC CPU Interface (<code>CONFIG_GICR_BASE</code>) by dumping the Device Tree from QEMU...
```bash
GIC v2 Dump Device Tree
qemu-system-aarch64 \
-smp 4 \
-cpu cortex-a53 \
-nographic \
-machine virt,virtualization=on,gic-version=2,dumpdtb=gicv2.dtb \
-net none \
-chardev stdio,id=con,mux=on \
-serial chardev:con \
-mon chardev=con,mode=readline \
-kernel ./nuttx
Convert Device Tree to text format
dtc -o gicv2.dts -O dts -I dtb gicv2.dtb
```
The Base Addresses are revealed in the GIC v2 Device Tree: <a>gicv2.dts</a>...
```text
intc@8000000 {
reg = <
0x00 0x8000000 0x00 0x10000 // GIC Distributor: 0x8000000
0x00 0x8010000 0x00 0x10000 // GIC CPU Interface: 0x8010000
0x00 0x8030000 0x00 0x10000 // VGIC Virtual Interface Control: 0x8030000
0x00 0x8040000 0x00 0x10000 // VGIC Virtual CPU Interface: 0x8040000
<blockquote>
;
compatible = "arm,cortex-a15-gic";
```
</blockquote>
<a>(More about this)</a>
We defined the Base Addresses in <a>arch/arm64/include/qemu/chip.h</a>
Compare the above Base Addresses with the GIC v3 Device Tree: <a>gicv3.dts</a>
```text
intc@8000000 {
reg = <
0x00 0x8000000 0x00 0x10000 // GIC Distributor: 0x8000000
0x00 0x80a0000 0x00 0xf60000 // GIC CPU Interface: 0x80a0000
<blockquote>
;
</blockquote>
redistributor-regions = <0x01>;
compatible = "arm,gic-v3";
```
This is how we copied the PinePhone GIC v2 Source Files into NuttX QEMU Arm64 for testing...
<code>bash
cp ~/PinePhone/nuttx/nuttx/arch/arm64/src/common/arm64_gicv3.c ~/gicv2/nuttx/nuttx/arch/arm64/src/common/arm64_gicv3.c
cp ~/PinePhone/nuttx/nuttx/arch/arm/src/armv7-a/arm_gicv2.c ~/gicv2/nuttx/nuttx/arch/arm/src/armv7-a/arm_gicv2.c
cp ~/PinePhone/nuttx/nuttx/arch/arm/src/armv7-a/gic.h ~/gicv2/nuttx/nuttx/arch/arm/src/armv7-a/gic.h
cp ~/PinePhone/nuttx/nuttx/arch/arm/src/armv7-a/arm_gicv2_dump.c ~/gicv2/nuttx/nuttx/arch/arm/src/armv7-a/arm_gicv2_dump.c
cp ~/PinePhone/nuttx/nuttx/arch/arm64/src/common/arm64_arch_timer.c ~/gicv2/nuttx/nuttx/arch/arm64/src/common/arm64_arch_timer.c</code>
Handling Interrupts
Let's talk about NuttX and how it handles interrupts.
The <strong>Interrupt Vector Table</strong> is defined in <a>sched/irq/irq_initialize.c</a>
<code>c
/* This is the interrupt vector table */
struct irq_info_s g_irqvector[NR_IRQS];</code>
(Next section talks about dumping the Interrupt Vector Table)
At startup, the Interrupt Vector Table is initialised to the <strong>Unexpected Interrupt Handler <code>irq_unexpected_isr</code></strong>: <a>sched/irq/irq_initialize.c</a>
<code>c
/****************************************************************************
* Name: irq_initialize
* Description:
* Configure the IRQ subsystem
****************************************************************************/
void irq_initialize(void)
{
/* Point all interrupt vectors to the unexpected interrupt */
for (i = 0; i < NR_IRQS; i++)
{
g_irqvector[i].handler = irq_unexpected_isr;
}
up_irqinitialize();
}</code>
<strong>Unexpected Interrupt Handler <code>irq_unexpected_isr</code></strong> is called when an Interrupt is triggered and there's no Interrupt Handler attached to the Interrupt: <a>sched/irq/irq_unexpectedisr.c</a>
<code>c
/****************************************************************************
* Name: irq_unexpected_isr
* Description:
* An interrupt has been received for an IRQ that was never registered
* with the system.
****************************************************************************/
int irq_unexpected_isr(int irq, FAR void *context, FAR void *arg)
{
up_irq_save();
_err("ERROR irq: %d\n", irq);
PANIC();</code>
To <strong>attach an Interrupt Handler</strong>, we set the Handler and the Argument in the Interrupt Vector Table: <a>sched/irq/irq_attach.c</a>
<code>c
/****************************************************************************
* Name: irq_attach
* Description:
* Configure the IRQ subsystem so that IRQ number 'irq' is dispatched to
* 'isr'
****************************************************************************/
int irq_attach(int irq, xcpt_t isr, FAR void *arg)
{
...
/* Save the new ISR and its argument in the table. */
g_irqvector[irq].handler = isr;
g_irqvector[irq].arg = arg;</code>
When an <strong>Interrupt is triggered</strong>...
<ol>
<li>
Arm CPU looks up the <strong>Arm64 Vector Table <code>_vector_table</code></strong>: <a>arch/arm64/src/common/arm64_vector_table.S</a>
<code>text
/* Four types of exceptions:
* - synchronous: aborts from MMU, SP/CP alignment checking, unallocated
* instructions, SVCs/SMCs/HVCs, ...)
* - IRQ: group 1 (normal) interrupts
* - FIQ: group 0 or secure interrupts
* - SError: fatal system errors
*
* Four different contexts:
* - from same exception level, when using the SP_EL0 stack pointer
* - from same exception level, when using the SP_ELx stack pointer
* - from lower exception level, when this is AArch64
* - from lower exception level, when this is AArch32
*
* +------------------+------------------+-------------------------+
* | Address | Exception type | Description |
* +------------------+------------------+-------------------------+
* | VBAR_ELn + 0x000 | Synchronous | Current EL with SP0 |
* | + 0x080 | IRQ / vIRQ | |
* | + 0x100 | FIQ / vFIQ | |
* | + 0x180 | SError / vSError | |
* +------------------+------------------+-------------------------+
* | + 0x200 | Synchronous | Current EL with SPx |
* | + 0x280 | IRQ / vIRQ | |
* | + 0x300 | FIQ / vFIQ | |
* | + 0x380 | SError / vSError | |
* +------------------+------------------+-------------------------+
* | + 0x400 | Synchronous | Lower EL using AArch64 |
* | + 0x480 | IRQ / vIRQ | |
* | + 0x500 | FIQ / vFIQ | |
* | + 0x580 | SError / vSError | |
* +------------------+------------------+-------------------------+
* | + 0x600 | Synchronous | Lower EL using AArch64 |
* | + 0x680 | IRQ / vIRQ | |
* | + 0x700 | FIQ / vFIQ | |
* | + 0x780 | SError / vSError | |
* +------------------+------------------+-------------------------+
*/
GTEXT(_vector_table)
SECTION_SUBSEC_FUNC(exc_vector_table,_vector_table_section,_vector_table)
...
/* Current EL with SP0 / IRQ */
.align 7
arm64_enter_exception x0, x1
b arm64_irq_handler
...
/* Current EL with SPx / IRQ */
.align 7
arm64_enter_exception x0, x1
b arm64_irq_handler</code>
<a>(<code>arm64_enter_exception</code> is defined here)</a>
</li>
<li>
Based on the Arm64 Vector Table <code>_vector_table</code>, Arm CPU jumps to <code>arm64_irq_handler</code>: <a>arch/arm64/src/common/arm64_vectors.S</a>
<code>text
/****************************************************************************
* Name: arm64_irq_handler
* Description:
* Interrupt exception handler
****************************************************************************/
GTEXT(arm64_irq_handler)
SECTION_FUNC(text, arm64_irq_handler)
...
/* Call arm64_decodeirq() on the interrupt stack
* with interrupts disabled
*/
bl arm64_decodeirq</code>
</li>
<li>
<code>arm64_irq_handler</code> calls <code>arm64_decodeirq</code> to decode the Interrupt: <a>arch/arm64/src/common/arm64_gicv3.c</a>
```c
/<strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em>
* Name: arm64_decodeirq
* Description:
* This function is called from the IRQ vector handler in arm64_vectors.S.
* At this point, the interrupt has been taken and the registers have
* been saved on the stack. This function simply needs to determine the
* the irq number of the interrupt and then to call arm_doirq to dispatch
* the interrupt.
* Input Parameters:
* regs - A pointer to the register save area on the stack.
</strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong>*<em><em>/
// Decode IRQ for PinePhone, based on arm_decodeirq in arm_gicv2.c
uint64_t * arm64_decodeirq(uint64_t * regs)
{
...
if (irq < NR_IRQS)
{
/</em> Dispatch the interrupt </em>/
<code> regs = arm64_doirq(irq, regs);
</code>
```
</li>
<li>
<code>arm64_decodeirq</code> calls <code>arm64_doirq</code> to dispatch the Interrupt: <a>arch/arm64/src/common/arm64_doirq.c</a>
<code>c
/****************************************************************************
* Name: arm64_doirq
* Description:
* Receives the decoded GIC interrupt information and dispatches control
* to the attached interrupt handler.
*
****************************************************************************/
uint64_t *arm64_doirq(int irq, uint64_t * regs)
{
...
/* Deliver the IRQ */
irq_dispatch(irq, regs);</code>
</li>
<li>
<code>irq_dispatch</code> calls the Interrupt Handler fetched from the Interrupt Vector Table: <a>sched/irq/irq_dispatch.c</a>
<code>c
/****************************************************************************
* Name: irq_dispatch
* Description:
* This function must be called from the architecture-specific logic in
* order to dispatch an interrupt to the appropriate, registered handling
* logic.
****************************************************************************/
void irq_dispatch(int irq, FAR void *context)
{
if ((unsigned)irq < NR_IRQS)
{
if (g_irqvector[ndx].handler)
{
vector = g_irqvector[ndx].handler;
arg = g_irqvector[ndx].arg;
}
}
/* Then dispatch to the interrupt handler */
CALL_VECTOR(ndx, vector, irq, context, arg);</code>
</li>
</ol>
<em>How is the <a>Arm64 Vector Table <code>_vector_table</code></a> configured in the Arm CPU?</em>
The <a>Arm64 Vector Table <code>_vector_table</code></a> is configured in the Arm CPU during EL1 Init by <code>arm64_boot_el1_init</code>: <a>arch/arm64/src/common/arm64_boot.c</a>
<code>c
void arm64_boot_el1_init(void)
{
/* Setup vector table */
write_sysreg((uint64_t)_vector_table, vbar_el1);
ARM64_ISB();</code>
<code>vbar_el1</code> refers to <strong>Vector Base Address Register EL1</strong>.
<a>(See Arm Cortex-A53 Technical Reference Manual, page 4-121, "Vector Base Address Register, EL1")</a>
<a>(Arm64 Vector Table is also configured during EL3 Init by <code>arm64_boot_el3_init</code>)</a>
EL1 Init <code>arm64_boot_el1_init</code> is called by our Startup Code: <a>arch/arm64/src/common/arm64_head.S</a>
```text
PRINT(switch_el1, "- Boot from EL1\r\n")
<code>/* EL1 init */
bl arm64_boot_el1_init
/* set SP_ELx and Enable SError interrupts */
msr SPSel, #1
msr DAIFClr, #(DAIFCLR_ABT_BIT)
isb
</code>
jump_to_c_entry:
PRINT(jump_to_c_entry, "- Boot to C runtime for OS Initialize\r\n")
ret x25
```
<em>What are EL1 and EL3?</em>
According to <a>Arm Cortex-A53 Technical Reference Manual</a> page 3-5 ("Exception Level")...
<blockquote>
The ARMv8 exception model defines exception levels EL0-EL3, where:
<ul>
<li>
EL0 has the lowest software execution privilege, and execution at EL0 is called unprivileged execution.
</li>
<li>
Increased exception levels, from 1 to 3, indicate increased software execution privilege.
</li>
<li>
EL2 provides support for processor virtualization.
</li>
<li>
EL3 provides support for a secure state, see Security state on page 3-6.
</li>
</ul>
</blockquote>
PinePhone only uses EL1 and EL2 (but not EL3)...
<code>text
HELLO NUTTX ON PINEPHONE!
- Ready to Boot CPU
- Boot from EL2
- Boot from EL1
- Boot to C runtime for OS Initialize</code>
From this we see that NuttX runs mostly in EL1.
(EL1 is less privileged than EL2, which supports Processor Virtualization)
Dump Interrupt Vector Table
This is how we dump the Interrupt Vector Table to troubleshoot Interrupts...
Based on <a>arch/arm64/src/common/arm64_arch_timer.c</a>
```c
include "irq/irq.h" // For dumping Interrupt Vector Table
void up_timer_initialize(void)
{
...
// Attach System Timer Interrupt Handler
irq_attach(ARM_ARCH_TIMER_IRQ, arm64_arch_timer_compare_isr, 0);
// Begin dumping Interrupt Vector Table
sinfo("ARM_ARCH_TIMER_IRQ=%d\n", ARM_ARCH_TIMER_IRQ);
sinfo("arm64_arch_timer_compare_isr=%p\n", arm64_arch_timer_compare_isr);
sinfo("irq_unexpected_isr=%p\n", irq_unexpected_isr);
for (int i = 0; i < NR_IRQS; i++)
{
sinfo("g_irqvector[%d].handler=%p\n", i, g_irqvector[i].handler);
}
// End dumping Interrupt Vector Table
```
This code runs at startup to attach the very first Interrupt Handler, for the <a>System Timer Interrupt</a>.
We see that the System Timer Interrupt Number (IRQ) is 27...
```text
up_timer_initialize: ARM_ARCH_TIMER_IRQ=27
up_timer_initialize: arm64_arch_timer_compare_isr=0x4009ae18
up_timer_initialize: irq_unexpected_isr=0x400820e0
up_timer_initialize: g_irqvector[0].handler=0x400820e0
...
up_timer_initialize: g_irqvector[26].handler=0x400820e0
up_timer_initialize: g_irqvector[27].handler=0x4009ae18
up_timer_initialize: g_irqvector[28].handler=0x400820e0
...
up_timer_initialize: g_irqvector[219].handler=0x400820e0
```
All entries in the Interrupt Vector Table point to the <a>Unexpected Interrupt Handler <code>irq_unexpected_isr</code></a>, except for <code>g_irqvector[27]</code> which points to the <a>System Timer Interrupt Handler <code>arm64_arch_timer_compare_isr</code></a>.
Interrupt Debugging
<em>Can we debug the Arm64 Interrupt Handler?</em>
Yep we can write to the UART Port like this...
Based on <a>arch/arm64/src/common/arm64_vectors.S</a>
```text
PinePhone Allwinner A64 UART0 Base Address
define UART1_BASE_ADDRESS 0x01C28000
QEMU UART Base Address
Previously: #define UART1_BASE_ADDRESS 0x9000000
/<strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em>*
* Name: arm64_irq_handler
* Description:
* Interrupt exception handler
</strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong>****/
GTEXT(arm64_irq_handler)
SECTION_FUNC(text, arm64_irq_handler)
<code>mov x0, #84 /* For Debug: 'T' */
ldr x1, =UART1_BASE_ADDRESS /* For Debug */
strb w0, [x1] /* For Debug */
/* switch to IRQ stack and save current sp on it. */
...
</code>
```
This will print "T" on the console whenever the Arm64 CPU triggers an Interrupt. (Assuming that the UART Buffer hasn't overflowed)
We can insert this debug code for every handler in <a>arch/arm64/src/common/arm64_vectors.S</a>...
<ul>
<li>
<a><code>arm64_sync_exc</code></a>: Handle synchronous exception
</li>
<li>
<a><code>arm64_irq_handler</code></a>: Interrupt exception handler
</li>
<li>
<a><code>arm64_serror_handler</code></a>: SError handler (Fatal System Errors)
</li>
<li>
<a><code>arm64_mode32_error</code></a>: Mode32 Error
</li>
<li>
<a><code>arm64_irq_spurious</code></a>: Spurious Interrupt
</li>
</ul>
This is how we insert the debug code for every handler in <a>arm64_vectors.S</a>: https://gist.github.com/lupyuen/4bea83c61704080f1af18abfda63c77e
We can do the same for the <strong>Arm64 Vector Table</strong>: <a>arch/arm64/src/common/arm64_vector_table.S</a>
```text
PinePhone Allwinner A64 UART0 Base Address
define UART1_BASE_ADDRESS 0x01C28000
QEMU UART Base Address
Previously: #define UART1_BASE_ADDRESS 0x9000000
/<em> Save Corruptible Registers and exception context
* on the task stack
* note: allocate stackframe with XCPTCONTEXT_GP_REGS
* which is ARM64_ESF_REGS + ARM64_CS_REGS
* but only save ARM64_ESF_REGS
</em>/
.macro arm64_enter_exception xreg0, xreg1
sub sp, sp, #8 * XCPTCONTEXT_GP_REGS
<code>stp x0, x1, [sp, #8 * REG_X0]
stp x2, x3, [sp, #8 * REG_X2]
...
stp x28, x29, [sp, #8 * REG_X28]
mov x0, #88 /* For Debug: 'X' */
ldr x1, =UART1_BASE_ADDRESS /* For Debug */
strb w0, [x1] /* For Debug */
</code>
```
Memory Map
PinePhone depends on Arm's Memory Management Unit (MMU). We defined two MMU Memory Regions for PinePhone: RAM and Device I/O: <a>arch/arm64/include/qemu/chip.h</a>
```c
// PinePhone Generic Interrupt Controller
// GIC_DIST: 0x01C80000 + 0x1000
// GIC_CPUIF: 0x01C80000 + 0x2000
define CONFIG_GICD_BASE 0x01C81000
define CONFIG_GICR_BASE 0x01C82000
// Previously:
// #define CONFIG_GICD_BASE 0x8000000
// #define CONFIG_GICR_BASE 0x80a0000
// PinePhone RAM: 0x4000 0000 to 0x4800 0000
define CONFIG_RAMBANK1_ADDR 0x40000000
define CONFIG_RAMBANK1_SIZE MB(128)
// PinePhone Device I/O: 0x0 to 0x2000 0000
define CONFIG_DEVICEIO_BASEADDR 0x00000000
define CONFIG_DEVICEIO_SIZE MB(512)
// Previously:
// #define CONFIG_DEVICEIO_BASEADDR 0x7000000
// #define CONFIG_DEVICEIO_SIZE MB(512)
// PinePhone uboot load address (kernel_addr_r)
define CONFIG_LOAD_BASE 0x40080000
// Previously: #define CONFIG_LOAD_BASE 0x40280000
```
We also changed CONFIG_LOAD_BASE for PinePhone's Kernel Start Address (kernel_addr_r).
<em>How are the MMU Memory Regions used?</em>
NuttX initialises the Arm MMU with the MMU Memory Regions at startup: <a>arch/arm64/src/qemu/qemu_boot.c</a>
```c
static const struct arm_mmu_region mmu_regions[] =
{
MMU_REGION_FLAT_ENTRY("DEVICE_REGION",
CONFIG_DEVICEIO_BASEADDR, MB(512),
MT_DEVICE_NGNRNE | MT_RW | MT_SECURE),
MMU_REGION_FLAT_ENTRY("DRAM0_S0",
CONFIG_RAMBANK1_ADDR, MB(512),
MT_NORMAL | MT_RW | MT_SECURE),
};
const struct arm_mmu_config mmu_config =
{
.num_regions = ARRAY_SIZE(mmu_regions),
.mmu_regions = mmu_regions,
};
```
The Arm MMU Initialisation is done by <code>arm64_mmu_init</code>, defined in <a>arch/arm64/src/common/arm64_mmu.c</a>
We'll talk more about the Arm MMU in the next section...
Boot Sequence
Read the article...
<ul>
<li>
<a>"PinePhone Boots NuttX"</a>
</li>
<li>
<a>"PinePhone Continues Booting NuttX"</a>
</li>
<li>
<a>"Start NSH Shell"</a>
</li>
</ul>
This section describes the Boot Sequence for NuttX on PinePhone...
<ol>
<li>
<a>Startup Code</a> (in Arm64 Assembly) inits the Arm64 System Registers and UART Port.
</li>
<li>
<a>Startup Code</a> prints the Hello Message...
<code>text
HELLO NUTTX ON PINEPHONE!
Ready to Boot CPU</code>
</li>
<li>
<a>Startup Code</a> calls <a><code>arm64_boot_el2_init</code></a> to Init EL2
<code>text
Boot from EL2</code>
</li>
<li>
<a>Startup Code</a> calls <a><code>arm64_boot_el1_init</code></a> to Init EL1 and load the <a>Vector Base Address Register EL1</a>
<code>text
Boot from EL1</code>
</li>
<li>
<a>Startup Code</a> jumps to <code>arm64_boot_secondary_c_routine</code>: <a>arch/arm64/src/common/arm64_head.S</a>
<code>text
ldr x25, =arm64_boot_secondary_c_routine
...
jump_to_c_entry:
PRINT(jump_to_c_entry, "- Boot to C runtime for OS Initialize\r\n")
ret x25</code>
Which appears as...
<code>text
Boot to C runtime for OS Initialize</code>
</li>
<li>
TODO: Who calls <code>qemu_pl011_setup</code> to init the UART Port?
</li>
<li>
<code>arm64_boot_primary_c_routine</code> inits the BSS, calls <code>arm64_chip_boot</code> to init the Arm64 CPU, and <code>nx_start</code> to start the NuttX processes: <a>arch/arm64/src/common/arm64_boot.c</a>
<code>c
void arm64_boot_primary_c_routine(void)
{
boot_early_memset(_START_BSS, 0, _END_BSS - _START_BSS);
arm64_chip_boot();
nx_start();
}</code>
Which appears as...
<code>text
nx_start: Entry</code>
</li>
<li>
<code>arm64_chip_boot</code> calls <code>arm64_mmu_init</code> to enable the Arm Memory Management Unit, and <code>qemu_board_initialize</code> to init the Board Drivers: <a>arch/arm64/src/qemu/qemu_boot.c</a>
```c
void arm64_chip_boot(void)
{
/<em> MAP IO and DRAM, enable MMU. </em>/
arm64_mmu_init(true);
ifdef CONFIG_SMP
arm64_psci_init("smc");
endif
/<em> Perform board-specific device initialization. This would include
* configuration of board specific resources such as GPIOs, LEDs, etc.
</em>/
qemu_board_initialize();
ifdef USE_EARLYSERIALINIT
/<em> Perform early serial initialization if we are going to use the serial
* driver.
</em>/
qemu_earlyserialinit();
endif
}
```
<code>arm64_mmu_init</code> is defined in <a>arch/arm64/src/common/arm64_mmu.c</a>
</li>
<li>
TODO: Who calls <code>up_allocate_heap</code> to allocate the heap?
<code>text
up_allocate_heap: heap_start=0x0x400c4000, heap_size=0x7f3c000</code>
</li>
<li>
TODO: Who calls <a><code>arm64_gic_initialize</code></a> to init the GIC?
<code>text
arm64_gic_initialize: TODO: Init GIC for PinePhone
arm64_gic_initialize: CONFIG_GICD_BASE=0x1c81000
arm64_gic_initialize: CONFIG_GICR_BASE=0x1c82000
arm64_gic_initialize: GIC Version is 2</code>
</li>
<li>
TODO: Who calls <a><code>up_timer_initialize</code></a> to start the System Timer?
</li>
<li>
TODO: Who calls <code>uart_register</code> to register <code>/dev/console</code> and <code>/dev/ttyS0</code>?
</li>
<li>
TODO: Who calls <code>qemu_pl011_attach</code> to Attach UART Interrupt and <code>qemu_pl011_rxint</code> to Enable UART Receive Interrupt?
</li>
<li>
TODO: Who calls <code>work_start_highpri</code> to start high-priority kernel worker thread(s)?
</li>
<li>
TODO: Who calls <code>nx_start_application</code> to starting init thread?
</li>
<li>
TODO: Who calls <code>nxtask_start</code> to start the NuttX Shell?
</li>
<li>
<a><code>nxtask_start</code></a> calls <a><code>nxtask_startup</code></a> to start the NuttX Shell
</li>
<li>
<a><code>nxtask_startup</code></a> calls <a><code>lib_cxx_initialize</code></a> to init the C++ Constructors.
<code>text
lib_cxx_initialize: _sinit: 0x400a7000 _einit: 0x400a7000 _stext: 0x40080000 _etext: 0x400a8000</code>
Then <a><code>nxtask_startup</code></a> calls the Main Entry Point for the NuttX Shell, <a><code>entrypt</code></a>
</li>
<li>
<a><code>entrypt</code></a> points to <a><code>nsh_main</code></a>, the Main Function for the NuttX Shell
</li>
<li>
<a><code>nsh_main</code></a>, starts the NuttX Shell.
UART Transmit and Receive Interrupts must work, otherwise nothing appears in NuttX Shell.
(Because NuttX Shell calls Stream I/O with the Serial Driver)
</li>
<li>
TODO: Who calls <code>qemu_pl011_txint</code> to Enable UART Transmit Interrupt?
<code>text
HHHHHHHHHHHH: qemu_pl011_txint</code>
</li>
<li>
TODO: Who calls <code>qemu_pl011_rxint</code> to Enable UART Receive Interrupt?
<code>text
GG: qemu_pl011_rxint</code>
</li>
<li>
<code>nx_start</code> starts the Idle Loop
<code>text
nx_start: CPU0: Beginning Idle Loop</code>
</li>
</ol>
The next section talks about debugging the Boot Sequence...
Boot Debugging
<em>How can we debug NuttX while it boots?</em>
We may call <code>up_putc</code> to print characters to the Serial Console and troubleshoot the Boot Sequence: <a>arch/arm64/src/common/arm64_boot.c</a>
<code>c
void arm64_boot_primary_c_routine(void)
{
int up_putc(int ch); // For debugging
up_putc('0'); // For debugging
boot_early_memset(_START_BSS, 0, _END_BSS - _START_BSS);
up_putc('1'); // For debugging
arm64_chip_boot();
up_putc('2'); // For debugging
nx_start();
}</code>
This prints "012" to the Serial Console as NuttX boots.
<a><code>up_putc</code></a> calls <a><code>up_lowputc</code></a> to print directly to the UART Port by writing to the UART Register. So it's safe to be called as NuttX boots.
UART Interrupts
Previously we noticed that NuttX Shell wasn't generating output on the Serial Console.
We discovered that <code>sinfo</code> (<code>syslog</code>) works, but <code>printf</code> (<code>puts</code>) doesn't!
Here's what we tested with NuttX Shell: <a>system/nsh/nsh_main.c</a>
```c
/<strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em>*
* Name: nsh_main
*
* Description:
* This is the main logic for the case of the NSH task. It will perform
* one-time NSH initialization and start an interactive session on the
* current console device.
*
</strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong><strong><em>*</em></strong>****/
int main(int argc, FAR char <em>argv[])
{
sinfo("</em><strong><em>main\n");////
printf("</em></strong><em>main2\n");////
sinfo("</em>***main3\n");////
```
<code>main2</code> never appears in the output because UART Transmit Interrupts (<code>qemu_pl011_txint</code>) haven't been implemented...
<code>text
nsh_main: ****main
HH: qemu_pl011_txint
nsh_main: ****main3</code>
This is the sequence of calls to <code>qemu_pl011_attach</code>, <code>qemu_pl011_rxint</code> and <code>qemu_pl011_txint</code> for UART Transmit and Receive Interrupts...
<code>text
uart_register: Registering /dev/console
uart_register: Registering /dev/ttyS0
K: qemu_pl011_attach
G: qemu_pl011_rxint
work_start_highpri: Starting high-priority kernel worker thread(s)
nx_start_application: Starting init thread
lib_cxx_initialize: _sinit: 0x400a7000 _einit: 0x400a7000 _stext: 0x40080000 _etext: 0x400a8000
nsh_main: ****main
puts: A
HH: qemu_pl011_txint
puts: B
nsh_main: ****main3
HHHHHHHHHHHH: qemu_pl011_txint
GG: qemu_pl011_rxint
nx_start: CPU0: Beginning Idle Loop</code>
We need to implement UART Transmit and Receive Interrupts to support NuttX Shell.
Here's our implementation...
<ul>
<li><a>"NuttX RTOS on PinePhone: UART Driver"</a></li>
</ul>
Backlight and LEDs
Read the article...
<ul>
<li><a>"NuttX RTOS for PinePhone: Blinking the LEDs"</a></li>
</ul>
Let's light up the PinePhone Backlight and the Red / Green / Blue LEDs.
Based on the <a>PinePhone Schematic</a>...
<ul>
<li>
Backlight Enable is connected to GPIO PH10
(PH10-LCD-BL-EN)
</li>
<li>
Backlight PWM is connected to PWM PL10
(PL10-LCD-PWM)
</li>
</ul>
This is how we turn on GPIO PH10 in Allwinner A64 Port Controller (PIO): <a>examples/hello/hello_main.c</a>
```c
// PIO Base Address for PinePhone Allwinner A64 Port Controller (GPIO)
define PIO_BASE_ADDRESS 0x01C20800
// Turn on the PinePhone Backlight
static void test_backlight(void)
{
// From PinePhone Schematic: https://files.pine64.org/doc/PinePhone/PinePhone%20v1.2b%20Released%20Schematic.pdf
// - Backlight Enable: GPIO PH10 (PH10-LCD-BL-EN)
// - Backlight PWM: PWM PL10 (PL10-LCD-PWM)
// We won't handle the PWM yet
// Write to PH Configure Register 1 (PH_CFG1_REG)
// Offset: 0x100
uint32_t <em>ph_cfg1_reg = (uint32_t </em>)
(PIO_BASE_ADDRESS + 0x100);
// Bits 10 to 8: PH10_SELECT (Default 0x7)
// 000: Input 001: Output
// 010: MIC_CLK 011: Reserved
// 100: Reserved 101: Reserved
// 110: PH_EINT10 111: IO Disable
<em>ph_cfg1_reg =
(</em>ph_cfg1_reg & ~(0b111 << 8)) // Clear the bits
| (0b001 << 8); // Set the bits for Output
printf("ph_cfg1_reg=0x%x\n", *ph_cfg1_reg);
// Write to PH Data Register (PH_DATA_REG)
// Offset: 0x10C
uint32_t <em>ph_data_reg = (uint32_t </em>)
(PIO_BASE_ADDRESS + 0x10C);
// Bits 11 to 0: PH_DAT (Default 0)
// If the port is configured as input, the corresponding bit is the pin state. If
// the port is configured as output, the pin state is the same as the
// corresponding bit. The read bit value is the value setup by software.
// If the port is configured as functional pin, the undefined value will
// be read.
<em>ph_data_reg |= (1 << 10); // Set Bit 10 for PH10
printf("ph_data_reg=0x%x\n", </em>ph_data_reg);
}
```
The Backlight lights up and the output shows...
<code>text
ph_cfg1_reg=0x7177
ph_data_reg=0x400</code>
Now for the LEDs. Based on the <a>PinePhone Schematic</a>...
<ul>
<li>
Red LED is connected to GPIO PD18
(PD18-LED-R)
</li>
<li>
Green LED is connected to GPIO PD19
(PD19-LED-G)
</li>
<li>
Blue LED is connected to GPIO PD20
(PD20-LED-B)
</li>
</ul>
This is how we turn on GPIOs PD18, PD19, PD20 in Allwinner A64 Port Controller (PIO): <a>examples/hello/hello_main.c</a>
```c
// PIO Base Address for PinePhone Allwinner A64 Port Controller (GPIO)
define PIO_BASE_ADDRESS 0x01C20800
// Turn on the PinePhone Red, Green and Blue LEDs
static void test_led(void)
{
// From PinePhone Schematic: https://files.pine64.org/doc/PinePhone/PinePhone%20v1.2b%20Released%20Schematic.pdf
// - Red LED: GPIO PD18 (PD18-LED-R)
// - Green LED: GPIO PD19 (PD19-LED-G)
// - Blue LED: GPIO PD20 (PD20-LED-B)
// Write to PD Configure Register 2 (PD_CFG2_REG)
// Offset: 0x74
uint32_t <em>pd_cfg2_reg = (uint32_t </em>)
(PIO_BASE_ADDRESS + 0x74);
// Bits 10 to 8: PD18_SELECT (Default 0x7)
// 000: Input 001: Output
// 010: LCD_CLK 011: LVDS_VPC
// 100: RGMII_TXD0/MII_TXD0/RMII_TXD0 101: Reserved
// 110: Reserved 111: IO Disable
<em>pd_cfg2_reg =
(</em>pd_cfg2_reg & ~(0b111 << 8)) // Clear the bits
| (0b001 << 8); // Set the bits for Output
// Bits 14 to 12: PD19_SELECT (Default 0x7)
// 000: Input 001: Output
// 010: LCD_DE 011: LVDS_VNC
// 100: RGMII_TXCK/MII_TXCK/RMII_TXCK 101: Reserved
// 110: Reserved 111: IO Disable
<em>pd_cfg2_reg =
(</em>pd_cfg2_reg & ~(0b111 << 12)) // Clear the bits
| (0b001 << 12); // Set the bits for Output
// Bits 18 to 16: PD20_SELECT (Default 0x7)
// 000: Input 001: Output
// 010: LCD_HSYNC 011: LVDS_VP3
// 100: RGMII_TXCTL/MII_TXEN/RMII_TXEN 101: Reserved
// 110: Reserved 111: IO Disable
<em>pd_cfg2_reg =
(</em>pd_cfg2_reg & ~(0b111 << 16)) // Clear the bits
| (0b001 << 16); // Set the bits for Output
printf("pd_cfg2_reg=0x%x\n", *pd_cfg2_reg);
// Write to PD Data Register (PD_DATA_REG)
// Offset: 0x7C
uint32_t <em>pd_data_reg = (uint32_t </em>)
(PIO_BASE_ADDRESS + 0x7C);
// Bits 24 to 0: PD_DAT (Default 0)
// If the port is configured as input, the corresponding bit is the pin state. If
// the port is configured as output, the pin state is the same as the
// corresponding bit. The read bit value is the value setup by software. If the
// port is configured as functional pin, the undefined value will be read.
<em>pd_data_reg |= (1 << 18); // Set Bit 18 for PD18
</em>pd_data_reg |= (1 << 19); // Set Bit 19 for PD19
<em>pd_data_reg |= (1 << 20); // Set Bit 20 for PD20
printf("pd_data_reg=0x%x\n", </em>pd_data_reg);
}
```
The Red, Green and Blue LEDs turn on (appearing as white) and the output shows...
<code>text
pd_cfg2_reg=0x77711177
pd_data_reg=0x1c0000</code>
<a><strong>Watch the Demo on YouTube</strong></a>
Here's the complete log for <a>examples/hello/hello_main.c</a>...
<code>text
nsh> hello
task_spawn: name=hello entry=0x4009b1a4 file_actions=0x400c9580 attr=0x400c9588 argv=0x400c96d0
spawn_execattrs: Setting policy=2 priority=100 for pid=3
ABHello, World!!
ph_cfg1_reg=0x7177
ph_data_reg=0x400
pd_cfg2_reg=0x77711177
pd_data_reg=0x1c0000
tcon_gctl_reg=0x80000000
tcon0_3d_fifo_reg=0x80000631
tcon0_ctl_reg=0x80000000
tcon0_basic0_reg=0x630063
tcon0_lvds_if_reg=0x80000000
nsh></code>
BASIC Blinks The LEDs
In the previous section we lit up PinePhone's Red, Green and Blue LEDs. Below are the values we wrote to the Allwinner A64 Port Controller...
<code>text
pd_cfg2_reg=0x77711177
pd_data_reg=0x1c0000</code>
Let's do the same in BASIC! Which is great for interactive experimenting with PinePhone Hardware.
This will enable GPIO Output for PD18 (Red), PD19 (Green), PD20 (Blue) in the Register <code>pd_cfg2_reg</code> (0x1C20874)...
<code>text
poke &h1C20874, &h77711177</code>
This will light up Red, Green and Blue LEDs via the Register <code>pd_data_reg</code> (0x1C2087C)...
<code>text
poke &h1C2087C, &h1C0000</code>
And this will turn off all 3 LEDs via <code>pd_data_reg</code> (0x1C2087C)...
<code>text
poke &h1C2087C, &h0000</code>
Install the BASIC Interpreter in NuttX...
<ul>
<li><a>"Enable BASIC"</a></li>
</ul>
And enter these commands to blink the PinePhone LEDs (off and on)...
<a><strong>Watch the Demo on YouTube</strong></a>
```text
nsh> bas
task_spawn: name=bas entry=0x4009b340 file_actions=0x400f3580 attr=0x400f3588 argv=0x400f36d0
spawn_execattrs: Setting policy=2 priority=100 for pid=7
bas 2.4
Copyright 1999-2014 Michael Haardt.
This is free software with ABSOLUTELY NO WARRANTY.
<blockquote>
print peek(&h1C20874)
2004316535
poke &h1C20874, &h77711177
print peek(&h1C20874)
2003898743
print peek(&h1C2087C)
262144
poke &h1C2087C, &h0000
print peek(&h1C2087C)
0
poke &h1C2087C, &h1C0000
print peek(&h1C2087C)
1835008
```
</blockquote>
Or run it in a loop like so...
<code>text
10 'Enable GPIO Output for PD18, PD19 and PD20
20 poke &h1C20874, &h77711177
30 'Turn off GPIOs PD18, PD19 and PD20
40 poke &h1C2087C, &h0
50 sleep 5
60 'Turn on GPIOs PD18, PD19 and PD20
70 poke &h1C2087C, &h1C0000
80 sleep 5
90 goto 40
run</code>
We patched NuttX BASIC so that it supports <code>peek</code> and <code>poke</code>: <a>interpreters/bas/bas_fs.c</a>
```c
int FS_memInput(int address)
{
// Return the 32-bit word at the specified address.
// TODO: Quit if address is invalid.
return <em>(int </em>)(uint64_t) address;
// Previously:
// FS_errmsg = _("Direct memory access not available");
// return -1;
}
int FS_memOutput(int address, int value)
{
// Set the 32-bit word at the specified address
// TODO: Quit if address is invalid.
<em>(int </em>)(uint64_t) address = value;
return 0;
// Previously:
// FS_errmsg = _("Direct memory access not available");
// return -1;
}
```
Note that addresses are passed as 32-bit <code>int</code>, so some 64-bit addresses will not be accessible via <code>peek</code> and <code>poke</code>.
NuttX Drivers for Allwinner A64 PIO and PinePhone LEDs
We built the NuttX Driver for Allwinner A64 PIO (Programmable I/O)...
<ul>
<li><a>arch/arm64/src/a64/a64_pio.c</a></li>
</ul>
Which is based on the existing NuttX Driver for Allwinner A10 PIO...
<ul>
<li><a>arch/arm/src/a1x/a1x_pio.c</a></li>
</ul>
By calling the PIO Driver, we created the NuttX Driver for PinePhone Red / Green / Blue LEDs...
<ul>
<li>
<a>boards/arm64/a64/pinephone/src/pinephone_autoleds.c</a>
</li>
<li>
<a>boards/arm64/a64/pinephone/src/pinephone_userleds.c</a>
</li>
</ul>
We tested the LED Driver with the <code>leds</code> Test App, here's the Test Log...
<ul>
<li><a>nuttx-pinephone-led.log</a></li>
</ul>
From the Test Log we see the Red / Green / Blue LEDs set to the colour combinations...
<code>text
led_daemon: LED set 0x00 (black)
led_daemon: LED set 0x01 (green)
led_daemon: LED set 0x02 (red)
led_daemon: LED set 0x03 (yellow)
led_daemon: LED set 0x04 (blue)
led_daemon: LED set 0x05 (cyan)
led_daemon: LED set 0x06 (magenta)
led_daemon: LED set 0x07 (white)</code>
PinePhone PIO and LEDs are now supported in NuttX Mainline...
https://github.com/apache/nuttx/pull/7796
PinePhone Device Tree
Let's figure out how Allwinner A64's Display Timing Controller (TCON0) talks to PinePhone's MIPI DSI Display. (So we can build NuttX Drivers)
More info on PinePhone Display...
<ul>
<li><a>"Genode Operating System Framework 22.05"</a>, pages 171 to 197.</li>
</ul>
We tried tweaking the TCON0 Controller but the display is still blank (maybe backlight is off?)
<ul>
<li><a>examples/hello/hello_main.c</a></li>
</ul>
Below is the Device Tree for PinePhone's Linux Kernel...
<ul>
<li><a>PinePhone Device Tree: sun50i-a64-pinephone-1.2.dts</a></li>
</ul>
We converted the Device Tree with this command...
```
Convert Device Tree to text format
dtc \
-o sun50i-a64-pinephone-1.2.dts \
-O dts \
-I dtb \
sun50i-a64-pinephone-1.2.dtb
```
<code>sun50i-a64-pinephone-1.2.dtb</code> came from the <a>Jumpdrive microSD</a>.
High-level doc of Linux Drivers...
<ul>
<li><a>devicetree/bindings/display/sunxi/sun4i-drm.txt</a></li>
</ul>
PinePhone Schematic shows the connections for Display, Touch Panel and Backlight...
<ul>
<li><a>PinePhone v1.2b Released Schematic</a></li>
</ul>
Here are the interesting bits from the PinePhone Linux Device Tree: <a>sun50i-a64-pinephone-1.2.dts</a>
LCD Controller (TCON0)
```text
lcd-controller@1c0c000 {
compatible = "allwinner,sun50i-a64-tcon-lcd\0allwinner,sun8i-a83t-tcon-lcd";
reg = <0x1c0c000 0x1000>;
interrupts = <0x00 0x56 0x04>;
clocks = <0x02 0x2f 0x02 0x64>;
clock-names = "ahb\0tcon-ch0";
clock-output-names = "tcon-pixel-clock";
#clock-cells = <0x00>;
resets = <0x02 0x18 0x02 0x23>;
reset-names = "lcd\0lvds";
ports {
#address-cells = <0x01>;
#size-cells = <0x00>;
<code>// TCON0: MIPI DSI Display
port@0 {
#address-cells = <0x01>;
#size-cells = <0x00>;
reg = <0x00>;
endpoint@0 {
reg = <0x00>;
remote-endpoint = <0x22>;
phandle = <0x1e>;
};
endpoint@1 {
reg = <0x01>;
remote-endpoint = <0x23>;
phandle = <0x20>;
};
};
// TCON1: HDMI
port@1 { ... };
</code>
};
};
```
<a>(Source)</a>
MIPI DSI Interface
```text
dsi@1ca0000 {
compatible = "allwinner,sun50i-a64-mipi-dsi";
reg = <0x1ca0000 0x1000>;
interrupts = <0x00 0x59 0x04>;
clocks = <0x02 0x1c>;
resets = <0x02 0x05>;
phys = <0x53>;
phy-names = "dphy";
status = "okay";
#address-cells = <0x01>;
#size-cells = <0x00>;
vcc-dsi-supply = <0x45>;
port {
<code>endpoint {
remote-endpoint = <0x54>;
phandle = <0x24>;
};
</code>
};
panel@0 {
compatible = "xingbangda,xbd599";
reg = <0x00>;
reset-gpios = <0x2b 0x03 0x17 0x01>;
iovcc-supply = <0x55>;
vcc-supply = <0x48>;
backlight = <0x56>;
};
};
```
<a>(Source)</a>
Display PHY
<code>text
d-phy@1ca1000 {
compatible = "allwinner,sun50i-a64-mipi-dphy\0allwinner,sun6i-a31-mipi-dphy";
reg = <0x1ca1000 0x1000>;
clocks = <0x02 0x1c 0x02 0x71>;
clock-names = "bus\0mod";
resets = <0x02 0x05>;
status = "okay";
#phy-cells = <0x00>;
phandle = <0x53>;
};</code>
<a>(Source)</a>
Backlight PWM
<code>text
backlight {
compatible = "pwm-backlight";
pwms = <0x62 0x00 0xc350 0x01>;
enable-gpios = <0x2b 0x07 0x0a 0x00>;
power-supply = <0x48>;
brightness-levels = <0x1388 0x1480 0x1582 0x16e2 0x18c9 0x1b4b 0x1e7d 0x2277 0x274e 0x2d17 0x33e7 0x3bd5 0x44f6 0x4f5f 0x5b28 0x6864 0x7729 0x878e 0x99a7 0xad8b 0xc350>;
num-interpolated-steps = <0x32>;
default-brightness-level = <0x1f4>;
phandle = <0x56>;
};</code>
<a>(Source)</a>
From <a>PinePhone Schematic</a>...
<ul>
<li>
Backlight Enable: GPIO PH10 (PH10-LCD-BL-EN)
</li>
<li>
Backlight PWM: PWM PL10 (PL10-LCD-PWM)
</li>
</ul>
LED
```text
leds {
compatible = "gpio-leds";
blue {
function = "indicator";
color = <0x03>;
gpios = <0x2b 0x03 0x14 0x00>;
retain-state-suspended;
};
green {
function = "indicator";
color = <0x02>;
gpios = <0x2b 0x03 0x12 0x00>;
retain-state-suspended;
};
red {
function = "indicator";
color = <0x01>;
gpios = <0x2b 0x03 0x13 0x00>;
retain-state-suspended;
};
};
```
<a>(Source)</a>
From <a>PinePhone Schematic</a>...
<ul>
<li>
Red LED: GPIO PD18 (PD18-LED-R)
</li>
<li>
Green LED: GPIO PD19 (PD19-LED-G)
</li>
<li>
Blue LED: GPIO PD20 (PD20-LED-B)
</li>
</ul>
Framebuffer
<code>text
framebuffer-lcd {
compatible = "allwinner,simple-framebuffer\0simple-framebuffer";
allwinner,pipeline = "mixer0-lcd0";
clocks = <0x02 0x64 0x03 0x06>;
status = "disabled";
};</code>
<a>(Source)</a>
Display Engine
<code>text
display-engine {
compatible = "allwinner,sun50i-a64-display-engine";
allwinner,pipelines = <0x07 0x08>;
status = "okay";
};</code>
<a>(Source)</a>
Touch Panel
<code>text
touchscreen@5d {
compatible = "goodix,gt917s";
reg = <0x5d>;
interrupt-parent = <0x2b>;
interrupts = <0x07 0x04 0x04>;
irq-gpios = <0x2b 0x07 0x04 0x00>;
reset-gpios = <0x2b 0x07 0x0b 0x00>;
AVDD28-supply = <0x48>;
VDDIO-supply = <0x48>;
touchscreen-size-x = <0x2d0>;
touchscreen-size-y = <0x5a0>;
};</code>
<a>(Source)</a>
Video Codec
<code>text
video-codec@1c0e000 {
compatible = "allwinner,sun50i-a64-video-engine";
reg = <0x1c0e000 0x1000>;
clocks = <0x02 0x2e 0x02 0x6a 0x02 0x5f>;
clock-names = "ahb\0mod\0ram";
resets = <0x02 0x17>;
interrupts = <0x00 0x3a 0x04>;
allwinner,sram = <0x28 0x01>;
};</code>
<a>(Source)</a>
GPU
<code>text
gpu@1c40000 {
compatible = "allwinner,sun50i-a64-mali\0arm,mali-400";
reg = <0x1c40000 0x10000>;
interrupts = <0x00 0x61 0x04 0x00 0x62 0x04 0x00 0x63 0x04 0x00 0x64 0x04 0x00 0x66 0x04 0x00 0x67 0x04 0x00 0x65 0x04>;
interrupt-names = "gp\0gpmmu\0pp0\0ppmmu0\0pp1\0ppmmu1\0pmu";
clocks = <0x02 0x35 0x02 0x72>;
clock-names = "bus\0core";
resets = <0x02 0x1f>;
assigned-clocks = <0x02 0x72>;
assigned-clock-rates = <0x1dcd6500>;
};</code>
<a>(Source)</a>
Deinterlace
<code>text
deinterlace@1e00000 {
compatible = "allwinner,sun50i-a64-deinterlace\0allwinner,sun8i-h3-deinterlace";
reg = <0x1e00000 0x20000>;
clocks = <0x02 0x31 0x02 0x66 0x02 0x61>;
clock-names = "bus\0mod\0ram";
resets = <0x02 0x1a>;
interrupts = <0x00 0x5d 0x04>;
interconnects = <0x57 0x09>;
interconnect-names = "dma-mem";
};</code>
<a>(Source)</a>
Zig on PinePhone
Let's run this Zig App on NuttX for PinePhone: <a>display.zig</a>
In NuttX, enable the Null Example App: make menuconfig, select "Application Configuration" > "Examples" > "Null Example"
Compile the Zig App (based on the GCC Compiler Options, see below)...
```bash
Change "$HOME/nuttx" for your NuttX Project Directory
cd $HOME/nuttx
Download the Zig App
git clone --recursive https://github.com/lupyuen/pinephone-nuttx
cd pinephone-nuttx
Compile the Zig App for PinePhone
(armv8-a with cortex-a53)
TODO: Change "$HOME/nuttx" to your NuttX Project Directory
zig build-obj \
--verbose-cimport \
-target aarch64-freestanding-none \
-mcpu cortex_a53 \
-isystem "$HOME/nuttx/nuttx/include" \
-I "$HOME/nuttx/apps/include" \
display.zig
Copy the compiled app to NuttX and overwrite <code>null.o</code>
TODO: Change "$HOME/nuttx" to your NuttX Project Directory
cp display.o \
$HOME/nuttx/apps/examples/null/*null.o
Build NuttX to link the Zig Object from <code>null.o</code>
TODO: Change "$HOME/nuttx" to your NuttX Project Directory
cd $HOME/nuttx/nuttx
make
```
Run the Zig App...
<code>text
nsh> null
HELLO ZIG ON PINEPHONE!</code>
<em>How did we get the Zig Compiler options <code>-target</code>, <code>-mcpu</code>, <code>-isystem</code> and <code>-I</code>?</em>
<code>make --trace</code> shows these GCC Compiler Options when building Nuttx for PinePhone...
<code>bash
aarch64-none-elf-gcc
-c
-fno-common
-Wall
-Wstrict-prototypes
-Wshadow
-Wundef
-Werror
-Os
-fno-strict-aliasing
-fomit-frame-pointer
-g
-march=armv8-a
-mtune=cortex-a53
-isystem "/Users/Luppy/PinePhone/nuttx/nuttx/include"
-D__NuttX__
-pipe
-I "/Users/Luppy/PinePhone/nuttx/apps/include"
-Dmain=hello_main hello_main.c
-o hello_main.c.Users.Luppy.PinePhone.nuttx.apps.examples.hello.o</code>
We copied and modified these GCC Compiler Options for Zig.
<em>What about <code>-D__NuttX__</code>?</em>
The Zig Compiler won't let us specify C Macros at the Command Line, so we defined the macro <code>__NuttX__</code> in our Zig App...
https://github.com/lupyuen/pinephone-nuttx/blob/2d938b9f09a165c0ff82b5dbbb12f1c4c6db61f2/display.zig#L27-L42
PinePhone Display Driver
Read the articles...
<ul>
<li>
<a>"NuttX RTOS for PinePhone: MIPI Display Serial Interface"</a>
</li>
<li>
<a>"NuttX RTOS for PinePhone: Display Engine"</a>
</li>
</ul>
Let's talk about the NuttX Driver for PinePhone MIPI DSI, Display Engine and Timing Controller...
Zig Driver for PinePhone MIPI DSI
With Zig, we create a Quick Prototype of the NuttX Driver for MIPI DSI: <a>display.zig</a>
https://github.com/lupyuen/pinephone-nuttx/blob/4840d2f1bd42d6bc596040f5417fd8cf8a6dcfeb/display.zig#L62-L167
This MIPI DSI Interface is compatible with Zephyr MIPI DSI...
<ul>
<li><a>zephyr/drivers/mipi_dsi.h</a></li>
</ul>
<em>Why Zig for the MIPI DSI Driver?</em>
We're doing Quick Prototyping, so it's great to have Zig catch any Runtime Problems caused by our Bad Coding. (Underflow / Overflow / Array Out Of Bounds)
And yet Zig is so similar to C that we can test the Zig Driver with the rest of the C code.
Also <code>comptime</code> Compile-Time Expressions in Zig will be helpful when we initialise the ST7703 LCD Controller. <a>(See this)</a>
Compose MIPI DSI Long Packet in Zig
To initialise PinePhone's ST7703 LCD Controller, our PinePhone Display Driver for NuttX shall send MIPI DSI Long Packets to ST7703...
<ul>
<li><a>"Long Packet for MIPI DSI"</a></li>
</ul>
This is how our Zig Driver composes a MIPI DSI Long Packet...
https://github.com/lupyuen/pinephone-nuttx/blob/1262f46622dc07442cf2aa59a4bbc57871308ed1/display.zig#L140-L204
Compose MIPI DSI Short Packet in Zig
For 1 or 2 bytes of data, our PinePhone Display Driver shall send MIPI DSI Short Packets (instead of Long Packets)...
<ul>
<li><a>"Short Packet for MIPI DSI"</a></li>
</ul>
This is how our Zig Driver composes a MIPI DSI Short Packet...
https://github.com/lupyuen/pinephone-nuttx/blob/1262f46622dc07442cf2aa59a4bbc57871308ed1/display.zig#L206-L261
Compute Error Correction Code in Zig
In our PinePhone Display Driver for NuttX, this is how we compute the Error Correction Code for a MIPI DSI Packet...
https://github.com/lupyuen/pinephone-nuttx/blob/1262f46622dc07442cf2aa59a4bbc57871308ed1/display.zig#L263-L304
The Error Correction Code is the last byte of the 4-byte Packet Header for Long Packets and Short Packets.
Compute Cyclic Redundancy Check in Zig
This is how our PinePhone Display Driver computes the 16-bit Cyclic Redundancy Check (CCITT) in Zig...
https://github.com/lupyuen/pinephone-nuttx/blob/1262f46622dc07442cf2aa59a4bbc57871308ed1/display.zig#L306-L366
The Cyclic Redundancy Check is the 2-byte Packet Footer for Long Packets.
Test PinePhone MIPI DSI Driver with QEMU
The above Zig Code for composing Long Packets and Short Packets was tested in QEMU for Arm64 with GIC Version 2...
```bash
TODO: Install Build Prerequisites
https://lupyuen.github.io/articles/uboot#install-prerequisites
Create NuttX Directory
mkdir nuttx
cd nuttx
Download NuttX OS for QEMU with GIC Version 2
git clone \
--recursive \
--branch gicv2 \
https://github.com/lupyuen/incubator-nuttx \
nuttx
Download NuttX Apps for QEMU
git clone \
--recursive \
--branch arm64 \
https://github.com/lupyuen/incubator-nuttx-apps \
apps
We'll build NuttX inside nuttx/nuttx
cd nuttx
Configure NuttX for Single Core
./tools/configure.sh -l qemu-a53:nsh
Build NuttX
make
Dump the disassembly to nuttx.S
aarch64-none-elf-objdump \
-t -S --demangle --line-numbers --wide \
nuttx \
<blockquote>
nuttx.S \
2>&1
```
</blockquote>
Follow these steps to compile our Zig App and link into NuttX...
<ul>
<li><a>"Zig on PinePhone"</a></li>
</ul>
Start NuttX on QEMU Arm64...
```bash
Run GIC v2 with QEMU
qemu-system-aarch64 \
-smp 4 \
-cpu cortex-a53 \
-nographic \
-machine virt,virtualization=on,gic-version=2 \
-net none \
-chardev stdio,id=con,mux=on \
-serial chardev:con \
-mon chardev=con,mode=readline \
-kernel ./nuttx
```
Here's the NuttX Test Log for our Zig App on QEMU Arm64...
```text
NuttShell (NSH) NuttX-11.0.0-RC2
nsh> uname -a
NuttX 11.0.0-RC2 c938291 Oct 7 2022 16:54:31 arm64 qemu-a53
nsh> null
HELLO ZIG ON PINEPHONE!
Testing Compose Short Packet (Without Parameter)...
composeShortPacket: channel=0, cmd=0x5, len=1
Result:
05 11 00 36
Testing Compose Short Packet (With Parameter)...
composeShortPacket: channel=0, cmd=0x15, len=2
Result:
15 bc 4e 35
Testing Compose Long Packet...
composeLongPacket: channel=0, cmd=0x39, len=64
Result:
39 40 00 25 e9 82 10 06
05 a2 0a a5 12 31 23 37
83 04 bc 27 38 0c 00 03
00 00 00 0c 00 03 00 00
00 75 75 31 88 88 88 88
88 88 13 88 64 64 20 88
88 88 88 88 88 02 88 00
00 00 00 00 00 00 00 00
00 00 00 00 65 03
```
Test Case for PinePhone MIPI DSI Driver
This is how we write a Test Case for the PinePhone MIPI DSI Driver on NuttX...
https://github.com/lupyuen/pinephone-nuttx/blob/aaf0ed0fb3e8ada663fe9c64f16ea9cb1e3235ed/display.zig#L593-L639
The above Test Case shows this output on QEMU Arm64...
<code>text
Testing Compose Long Packet...
composeLongPacket: channel=0, cmd=0x39, len=64
Result:
39 40 00 25 e9 82 10 06
05 a2 0a a5 12 31 23 37
83 04 bc 27 38 0c 00 03
00 00 00 0c 00 03 00 00
00 75 75 31 88 88 88 88
88 88 13 88 64 64 20 88
88 88 88 88 88 02 88 00
00 00 00 00 00 00 00 00
00 00 00 00 65 03</code>
Initialise ST7703 LCD Controller in Zig
PinePhone's ST7703 LCD Controller needs to be initialised with these 20 Commands...
<ul>
<li><a>"Initialise LCD Controller"</a></li>
</ul>
This is how we send the 20 Commands with our NuttX Driver in Zig, as DCS Short Writes and DCS Long Writes...
https://github.com/lupyuen/pinephone-nuttx/blob/40098cd9ea37ab5e0192b2dc006a98630fa6a7e8/display.zig#L62-L429
To send a command, <code>writeDcs</code> executes a DCS Short Write or DCS Long Write, depending on the length of the command...
https://github.com/lupyuen/pinephone-nuttx/blob/40098cd9ea37ab5e0192b2dc006a98630fa6a7e8/display.zig#L431-L453
Test Zig Display Driver for PinePhone
To test our Zig Display Driver with NuttX on PinePhone, we'll run this p-boot Display Code...
<ul>
<li><a>p-boot Display Code</a></li>
</ul>
Here are the steps to download and run the NuttX Binary Image on PinePhone...
<ol>
<li>
Prepare a microSD Card with PinePhone Jumpdrive...
<a>PinePhone Jumpdrive microSD</a>
</li>
<li>
Download the compressed NuttX Binary Image...
<a>Image.gz</a>
</li>
<li>
Copy the compressed NuttX Binary Image to Jumpdrive microSD...
```bash
Copy compressed NuttX Binary Image to Jumpdrive microSD.
How to create Jumpdrive microSD: https://lupyuen.github.io/articles/uboot#pinephone-jumpdrive
TODO: Change the microSD Path
cp Image.gz "/Volumes/NO NAME"
```
</li>
<li>
To access the UART Port on PinePhone, we'll connect this USB Serial Debug Cable (at 115.2 kbps)...
<a>PinePhone Serial Debug Cable</a>
</li>
<li>
Insert the Jumpdrive microSD into PinePhone and power up
</li>
<li>
At the NuttX Shell, enter <code>hello</code>
</li>
</ol>
We should see...
<code>text
HELLO NUTTX ON PINEPHONE!
...
Shell (NSH) NuttX-11.0.0-RC2
nsh> hello
...
writeDcs: len=4
b9 f1 12 83
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=4
composeLongPacket: channel=0, cmd=0x39, len=4
packet: len=10
39 04 00 2c b9 f1 12 83
84 5d
modifyreg32: addr=0x300, val=0x2c000439
modifyreg32: addr=0x304, val=0x8312f1b9
modifyreg32: addr=0x308, val=0x00005d84
modifyreg32: addr=0x200, val=0x00000009
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
...</code>
<a>(Source)</a>
Our NuttX Zig Display Driver powers on the PinePhone Display and works exactly like the C Driver! 🎉
If we prefer to build the NuttX Binary Image ourselves, here are the steps to download the following Source Files and build them...
<code>text
nuttx
├── apps (NuttX Apps for PinePhone including Display Engine)
│ ├── Application.mk
│ ├── DISCLAIMER
│ ├── Directory.mk
...
├── nuttx (NuttX OS for PinePhone)
│ ├── AUTHORS
│ ├── CONTRIBUTING.md
│ ├── DISCLAIMER
...
├── p-boot (Modified p-boot Display Code)
│ ├── HACKING
│ ├── LICENSE
│ ├── NEWS
...
├── pinephone-nuttx (Zig Display Driver for PinePhone)
│ ├── LICENSE
│ ├── README.md
│ ├── display.o
│ └── display.zig
...
└── test_display.c (Test Zig Display Driver)</code>
<ol>
<li>
Create the NuttX Directory...
<code>bash
mkdir nuttx
cd nuttx</code>
</li>
<li>
Download <code>test-display.c</code> into the <code>nuttx</code> folder...
<a><code>test-display.c</code></a>
</li>
<li>
Download the Modified p-boot Display Code <code>p-boot.4.zip</code> from...
<a>pinephone-nuttx/releases/tag/pboot4</a>
Extract into the <code>nuttx</code> folder and rename as <code>p-boot</code>
</li>
<li>
Download and build NuttX for PinePhone inside the <code>nuttx</code> folder...
```bash
TODO: Install Build Prerequisites
https://lupyuen.github.io/articles/uboot#install-prerequisites
Download NuttX OS for PinePhone
git clone \
--recursive \
--branch pinephone \
https://github.com/lupyuen/incubator-nuttx \
nuttx
Download NuttX Apps for PinePhone including Display Engine
git clone \
--recursive \
--branch de \
https://github.com/lupyuen/incubator-nuttx-apps \
apps
We'll build NuttX inside nuttx/nuttx
cd nuttx
Configure NuttX for Single Core
./tools/configure.sh -l qemu-a53:nsh
Build NuttX. Ignore the Linker Errors
make
```
</li>
<li>
Follow these steps to compile our Zig App and link into NuttX...
<ul>
<li><a>"Zig on PinePhone"</a></li>
</ul>
</li>
<li>
Compress the NuttX Binary Image...
<code>bash
cp nuttx.bin Image
rm -f Image.gz
gzip Image</code>
</li>
<li>
Copy the compressed NuttX Binary Image <code>Image.gz</code> to Jumpdrive microSD according to the steps above.
Insert the Jumpdrive microSD into PinePhone and power up.
At the NuttX Shell, enter <code>hello</code>
</li>
</ol>
(The steps look messy today, hopefully we'll remove p-boot after we have created our NuttX Display Driver)
<em>Can our driver render graphics on PinePhone Display?</em>
Our PinePhone Display Driver isn't complete. It handles MIPI DSI (for initialising ST7703) but doesn't support Allwinner A64's Display Engine (DE) and Timing Controller (TCON), which are needed for rendering graphics.
We'll implement DE and TCON next.
Display Engine in Allwinner A64
Let's look inside PinePhone's Allwinner A64 Display Engine ... And render some graphics with Apache NuttX RTOS.
Here's the doc for the Display Engine...
<ul>
<li><a><strong>Allwinner Display Engine 2.0 Specifications</strong></a></li>
</ul>
<em>Which Display Engine for A64 (sun50iw1): H8, H3, H5 or A83?</em>
PinePhone's A64 Display Engine is hidden in the Allwinner H3 Docs, because Allwinner A64 is actually a H3 upgraded with 64-bit Cores...
<blockquote>
The A64 is basically an Allwinner H3 with the Cortex-A7 cores replaced with Cortex-A53 cores (ARM64 architecture). They share most of the memory map, clocks, interrupts and also uses the same IP blocks.
</blockquote>
<a>(Source)</a>
According to the doc, DE Base Address is 0x0100 0000 (Page 24)
Let's look at the DE Mixers...
Display Engine Mixers
<em>What's a Display Engine Mixer?</em>
<strong>DE RT-MIXER:</strong> (Page 87)
<blockquote>
The RT-mixer Core consist of dma, overlay, scaler and blender block. It supports 4 layers overlay in one pipe, and its result can scaler up or down to blender in the next processing.
</blockquote>
The Display Engine has 2 Mixers: RT-MIXER0 and RT-MIXER1...
<strong>DE RT-MIXER0</strong> has 4 Channels (DE Offset 0x10 0000, Page 87)
- Channel 0 for Video: DMA0, Video Overlay, Video Scaler
- Channels 1, 2, 3 for UI: DMA1 / 2 / 3, UI Overlays, UI Scalers, UI Blenders
- 4 Overlay Layers per Channel
- Layer priority is Layer 3 > Layer2 > Layer 1 > Layer 0 (Page 89)
- Channel 0 is unused (we don't use video right now)
- Channel 1 has format XRGB 8888
- Channels 2 and 3 have format ARGB 8888
- MIXER0 Registers:
- GLB at MIXER0 Offset 0x00000 (de_glb_regs)
- BLD (Blender) at MIXER0 Offset 0x01000 (de_bld_regs)
- OVL_V(CH0) (Video Overlay / Channel 0) at MIXER0 Offset 0x2000 (Unused)
- OVL_UI(CH1) (UI Overlay / Channel 1) at MIXER0 Offset 0x3000
- OVL_UI(CH2) (UI Overlay / Channel 2) at MIXER0 Offset 0x4000
- OVL_UI(CH3) (UI Overlay / Channel 3) at MIXER0 Offset 0x5000
- POST_PROC2 at MIXER0 Offset 0xB0000 (de_csc_regs)
<strong>DE RT-MIXER1</strong> has 2 Channels (DE Offset 0x20 0000, Page 23)
- Channel 0 for Video: DMA0, Video Overlay, Video Scaler
- Channel 1 for UI: DMA1, UI Overlay, UI Scaler, UI Blender
- We don't use MIXER1 right now
RT-MIXER0 and RT-MIXER1 are multiplexed to Timing Controller TCON0.
(TCON0 is connected to ST7703 over MIPI DSI)
So MIXER0 mixes 1 Video Channel with 3 UI Channels over DMA ... And pumps the pixels continuously to ST7703 LCD Controller (via the Timing Controller)
Let's use the 3 UI Channels to render: 1️⃣ Mandelbrot Set 2️⃣ Blue Square 3️⃣ Green Circle
<em>Why 2 Mixers in A64 Display Engine?</em>
Maybe because A64 (or H3) was designed for <a>OTT Set-Top Boxes</a> with Picture-In-Picture Overlay Videos?
The 3 UI Overlay Channels would be useful for overlaying a Text UI on top of a Video Channel.
(Is that why Allwinner calls them "Channels"?)
<a>(Wait... Wasn't Pine64 created thanks to OTT Boxes? 🤔)</a>
Render Colours
Let's render simple colour blocks on the PinePhone Display.
We allocate the Framebuffer: <a>test_display.c</a>
<code>c
// Init Framebuffer 0:
// Fullscreen 720 x 1440 (4 bytes per RGBA pixel)
static uint32_t fb0[720 * 1440];
int fb0_len = sizeof(fb0) / sizeof(fb0[0]);</code>
We fill the Framebuffer with Blue, Green and Red: <a>test_display.c</a>
<code>c
// Fill with Blue, Green and Red
for (int i = 0; i < fb0_len; i++) {
// Colours are in ARGB format
if (i < fb0_len / 4) {
// Blue for top quarter
fb0[i] = 0x80000080;
} else if (i < fb0_len / 2) {
// Green for next quarter
fb0[i] = 0x80008000;
} else {
// Red for lower half
fb0[i] = 0x80800000;
}
}</code>
We allocate 3 UI Channels: <a>test_display.c</a>
<code>c
// Allocate 3 UI Channels
static struct display disp;
memset(&disp, 0, sizeof(disp));
struct display *d = &disp;</code>
We init the 3 Channels and render them: <a>test_display.c</a>
```c
// Init UI Channel 1: (Base Channel)
// Fullscreen 720 x 1440
d->planes[0].fb_start = (uintptr_t) fb0; // Framebuffer Address
d->planes[0].fb_pitch = 720 * 4; // Framebuffer Pitch
d->planes[0].src_w = 720; // Source Width
d->planes[0].src_h = 1440; // Source Height
d->planes[0].dst_w = 720; // Dest Width
d->planes[0].dst_h = 1440; // Dest Height
// Init UI Channel 2: (First Overlay)
// Square 600 x 600
d->planes[1].fb_start = 0; // To Disable Channel
// Init UI Channel 3: (Second Overlay)
// Fullscreen 720 x 1440 with Alpha Blending
d->planes[2].fb_start = 0; // To Disable Channel
// Render the UI Channels
display_commit(d);
```
<code>display_commit</code> is defined in the p-boot Display Code: <a>display.c</a>
We should see these Blue, Green and Red Blocks...
(Why the black lines?)
Channels 2 and 3 are disabled for now. We'll use them to render UI Overlays later.
Render Mandelbrot Set
Let's render something more interesting... Mandelbrot Set: <a>test_display.c</a>
```c
// Fill with Mandelbrot Set
for (int y = 0; y < 1440; y++) {
for (int x = 0; x < 720; x++) {
// Convert Pixel Coordinates to a Complex Number
float cx = x_start + (y / 1440.0) * (x_end - x_start);
float cy = y_start + (x / 720.0) * (y_end - y_start);
<code> // Compute Manelbrot Set
int m = mandelbrot(cx, cy);
// Color depends on the number of iterations
uint8_t hue = 255.0 * m / MAX_ITER;
uint8_t saturation = 255;
uint8_t value = (m < MAX_ITER) ? 255 : 0;
// Convert Hue / Saturation / Value to RGB
uint32_t rgb = hsvToRgb(hue, saturation, value);
// Set the Pixel Colour (ARGB Format)
int p = (y * 720) + x;
assert(p < fb0_len);
fb0[p] = 0x80000000 | rgb;
}
</code>
}
```
<code>mandelbrot</code> and <code>hsvToRgb</code> are defined here: <a>test_display.c</a>
We should see this Mandelbrot Set...
Animate Madelbrot Set
Now we animate the Mandelbrot Set: <a>test_display.c</a>
```c
// Omitted: Init UI Channels 1, 2 and 3
...
// Render the UI Channels
display_commit(d);
// Animate the Mandelbrot Set forever...
for (;;) {
// Fill with Mandelbrot Set
for (int y = 0; y < 1440; y++) {
for (int x = 0; x < 720; x++) {
// Convert Pixel Coordinates to a Complex Number
float cx = x_start + (y / 1440.0) * (x_end - x_start);
float cy = y_start + (x / 720.0) * (y_end - y_start);
<code> // Compute Manelbrot Set
int m = mandelbrot(cx, cy);
// Color depends on the number of iterations
uint8_t hue = 255.0 * m / MAX_ITER;
uint8_t saturation = 255;
uint8_t value = (m < MAX_ITER) ? 255 : 0;
// Convert Hue / Saturation / Value to RGB
uint32_t rgb = hsvToRgb(hue, saturation, value);
// Set the Pixel Colour (ARGB Format)
int p = (y * 720) + x;
assert(p < fb0_len);
fb0[p] = 0x80000000 | rgb;
}
}
// Zoom in to (-1.4, 0)
float x_dest = -1.4;
float y_dest = 0;
x_start += (x_dest - x_start) * 0.05;
x_end -= (x_end - x_dest) * 0.05;
y_start += (y_dest - y_start) * 0.05;
y_end -= (y_end - y_dest) * 0.05;
</code>
}
```
We should see the Animated Mandelbrot Set...
<ul>
<li><a>Demo Video on YouTube</a></li>
</ul>
<em>Don't we need to call <code>display_commit</code> after every frame?</em>
Nope, remember that the Display Engine reads our Framebuffer directly via DMA.
So any updates to the Framebuffer will be pushed to the display instantly.
Render Square Overlay
This is how we render a Blue Square as an Overlay on UI Channel 2: <a>test_display.c</a>
```c
// Init Framebuffer 1:
// Square 600 x 600 (4 bytes per RGBA pixel)
static uint32_t fb1[600 * 600];
int fb1_len = sizeof(fb1) / sizeof(fb1[0]);
// Fill with Blue
for (int i = 0; i < fb1_len; i++) {
// Colours are in ARGB format
fb1[i] = 0x80000080;
}
// Init UI Channel 2: (First Overlay)
// Square 600 x 600
d->planes[1].fb_start = (uintptr_t) fb1; // Framebuffer Address
d->planes[1].fb_pitch = 600 * 4; // Framebuffer Pitch
d->planes[1].src_w = 600; // Source Width
d->planes[1].src_h = 600; // Source Height
d->planes[1].dst_w = 600; // Dest Width
d->planes[1].dst_h = 600; // Dest Height
d->planes[1].dst_x = 52; // Dest X
d->planes[1].dst_y = 52; // Dest Y
```
Render Circle Overlay
This is how we render a Green Circle as an Overlay on UI Channel 3: <a>test_display.c</a>
```c
// Init Framebuffer 2:
// Fullscreen 720 x 1440 (4 bytes per RGBA pixel)
static uint32_t fb2[720 * 1440];
int fb2_len = sizeof(fb2) / sizeof(fb2[0]);
// Fill with Green Circle
for (int y = 0; y < 1440; y++) {
for (int x = 0; x < 720; x++) {
// Get pixel index
int p = (y * 720) + x;
assert(p < fb2_len);
<code> // Shift coordinates so that centre of screen is (0,0)
int x_shift = x - 360;
int y_shift = y - 720;
// If x^2 + y^2 < radius^2, set the pixel to Green
if (x_shift*x_shift + y_shift*y_shift < 360*360) {
fb2[p] = 0x80008000; // Green in ARGB Format
} else { // Otherwise set to Black
fb2[p] = 0x00000000; // Black in ARGB Format
}
}
</code>
}
// Init UI Channel 3: (Second Overlay)
// Fullscreen 720 x 1440 with Alpha Blending
d->planes[2].fb_start = (uintptr_t) fb2; // Framebuffer Address
d->planes[2].fb_pitch = 720 * 4; // Framebuffer Pitch
d->planes[2].src_w = 720; // Source Width
d->planes[2].src_h = 1440; // Source Height
d->planes[2].dst_w = 720; // Dest Width
d->planes[2].dst_h = 1440; // Dest Height
d->planes[2].dst_x = 0; // Dest X
d->planes[2].dst_y = 0; // Dest Y
d->planes[2].alpha = 128; // Dest Alpha
```
Note that we set the Destination Alpha. So the green will appear nearly invisible.
We should see the Animated Mandelbrot Set, with Blue Square and Green Circle as Overlays...
(Why the missing horizontal lines in the Blue Square and Green Circle?)
Test PinePhone Display Engine
To test the A64 Display Engine with NuttX on PinePhone, we'll run this p-boot Display Code...
<ul>
<li><a>display.c</a></li>
</ul>
With our Test App...
<ul>
<li><a>test_display.c</a></li>
</ul>
Here are the steps to download and run the NuttX Binary Image on PinePhone...
<ol>
<li>
Prepare a microSD Card with PinePhone Jumpdrive...
<a>PinePhone Jumpdrive microSD</a>
</li>
<li>
Download the compressed NuttX Binary Image...
<a>Image.gz</a>
</li>
<li>
Copy the compressed NuttX Binary Image to Jumpdrive microSD...
```bash
Copy compressed NuttX Binary Image to Jumpdrive microSD.
How to create Jumpdrive microSD: https://lupyuen.github.io/articles/uboot#pinephone-jumpdrive
TODO: Change the microSD Path
cp Image.gz "/Volumes/NO NAME"
```
</li>
<li>
To access the UART Port on PinePhone, we'll connect this USB Serial Debug Cable (at 115.2 kbps)...
<a>PinePhone Serial Debug Cable</a>
</li>
<li>
Insert the Jumpdrive microSD into PinePhone and power up
</li>
<li>
At the NuttX Shell, enter <code>hello</code>
</li>
</ol>
We should see the Animated Mandelbrot Set, with Blue Square and Green Circle as Overlays...
(Why the missing horizontal lines in the Blue Square and Green Circle?)
If we prefer to build the NuttX Binary Image ourselves, here are the steps to download the following Source Files and build them...
<code>text
nuttx
├── apps (NuttX Apps for PinePhone including Display Engine Version 2)
│ ├── Application.mk
│ ├── DISCLAIMER
│ ├── Directory.mk
...
├── nuttx (NuttX OS for PinePhone)
│ ├── AUTHORS
│ ├── CONTRIBUTING.md
│ ├── DISCLAIMER
...
├── p-boot (Modified p-boot Display Code)
│ ├── HACKING
│ ├── LICENSE
│ ├── NEWS
...
└── pinephone-nuttx (Zig MIPI DSI Driver for PinePhone)
├── LICENSE
├── README.md
├── display.o
└── display.zig</code>
<ol>
<li>
Create the NuttX Directory...
<code>bash
mkdir nuttx
cd nuttx</code>
</li>
<li>
Download the Modified Instrumented p-boot Display Code <code>p-boot.6.zip</code> from...
<a>pinephone-nuttx/releases/tag/pboot6</a>
Extract into the <code>nuttx</code> folder and rename as <code>p-boot</code>
</li>
<li>
Download and build NuttX for PinePhone inside the <code>nuttx</code> folder...
```bash
TODO: Install Build Prerequisites
https://lupyuen.github.io/articles/uboot#install-prerequisites
Download NuttX OS for PinePhone
git clone \
--recursive \
--branch pinephone \
https://github.com/lupyuen/incubator-nuttx \
nuttx
Download NuttX Apps for PinePhone including Display Engine (Version 2)
git clone \
--recursive \
--branch de2 \
https://github.com/lupyuen/incubator-nuttx-apps \
apps
We'll build NuttX inside nuttx/nuttx
cd nuttx
Configure NuttX for Single Core
./tools/configure.sh -l qemu-a53:nsh
Build NuttX. Ignore the Linker Errors
make
```
</li>
<li>
Follow these steps to compile our Zig MIPI DSI Driver and link into NuttX...
<ul>
<li><a>"Zig on PinePhone"</a></li>
</ul>
</li>
<li>
Compress the NuttX Binary Image...
<code>bash
cp nuttx.bin Image
rm -f Image.gz
gzip Image</code>
</li>
<li>
Copy the compressed NuttX Binary Image <code>Image.gz</code> to Jumpdrive microSD according to the steps above.
Insert the Jumpdrive microSD into PinePhone and power up.
At the NuttX Shell, enter <code>hello</code>
</li>
</ol>
(The steps look messy today, hopefully we'll remove p-boot after we have created our NuttX Display Driver)
Display Engine Usage
Based on the log captured from our instrumented <a>test_display.c</a>, we have identified the steps to render 3 UI Channels (1 to 3) with the Display Engine <a>(<code>display_commit</code>)</a>
This is how we'll create a NuttX Driver for PinePhone's A64 Display Engine that implements Display Rendering...
<ol>
<li>
Configure Blender...
<ul>
<li>BLD BkColor (BLD_BK_COLOR Offset 0x88): BLD background color register</li>
<li>BLD Premultiply (BLD_PREMUL_CTL Offset 0x84): BLD pre-multiply control register</li>
</ul>
<code>text
Configure Blender
BLD BkColor: 0x110 1088 = 0xff000000
BLD Premultiply: 0x110 1084 = 0x0</code>
</li>
<li>
For Channels 1 to 3...
<ol>
<li>
If Channel is unused, disable Overlay, Pipe and Scaler. Skip to next Channel
<ul>
<li>UI Config Attr (OVL_UI_ATTCTL @ OVL_UI Offset 0x00): OVL_UI attribute control register</li>
<li>Mixer (??? @ 0x113 0000 + 0x10000 * Channel)</li>
</ul>
```text
Channel 2: Disable Overlay and Pipe
UI Config Attr: 0x110 4000 = 0x0
Channel 3: Disable Overlay and Pipe
UI Config Attr: 0x110 5000 = 0x0
Channel 2: Disable Scaler
Mixer: 0x115 0000 = 0x0
Channel 3: Disable Scaler
Mixer: 0x116 0000 = 0x0
```
</li>
<li>
Channel 1 has format XRGB 8888, Channel 2 and 3 have format ARGB 8888
</li>
<li>
Set Overlay (Assume Layer = 0)
<ul>
<li>UI Config Attr (OVL_UI_ATTCTL @ OVL_UI Offset 0x00): OVL_UI attribute control register</li>
<li>UI Config Top LAddr (OVL_UI_TOP_LADD @ OVL_UI Offset 0x10): OVL_UI top field memory block low address register</li>
<li>UI Config Pitch (OVL_UI_PITCH @ OVL_UI Offset 0x0C): OVL_UI memory pitch register</li>
<li>UI Config Size (OVL_UI_MBSIZE @ OVL_UI Offset 0x04): OVL_UI memory block size register</li>
<li>UI Overlay Size (OVL_UI_SIZE @ OVL_UI Offset 0x88): OVL_UI overlay window size register</li>
<li>IO Config Coord (OVL_UI_COOR @ OVL_UI Offset 0x08): OVL_UI memory block coordinate register</li>
</ul>
```text
Channel 1: Set Overlay (fb0 is 720 x 1440)
UI Config Attr: 0x110 3000 = 0xff00 0405
UI Config Top LAddr: 0x110 3010 = 0x4064 a6ac (Address of fb0)
UI Config Pitch: 0x110 300c = 0xb40 (720 * 4)
UI Config Size: 0x110 3004 = 0x59f 02cf (1439 << 16 + 719)
UI Overlay Size: 0x110 3088 = 0x59f 02cf (1439 << 16 + 719)
IO Config Coord: 0x110 3008 = 0x0
Channel 2: Set Overlay (fb1 is 600 x 600)
UI Config Attr: 0x110 4000 = 0xff00 0005
UI Config Top LAddr: 0x110 4010 = 0x404e adac (Address of fb1)
UI Config Pitch: 0x110 400c = 0x960 (600 * 4)
UI Config Size: 0x110 4004 = 0x257 0257 (599 << 16 + 599)
UI Overlay Size: 0x110 4088 = 0x257 0257 (599 << 16 + 599)
IO Config Coord: 0x110 4008 = 0x0
Channel 3: Set Overlay (fb2 is 720 x 1440)
UI Config Attr: 0x110 5000 = 0x7f00 0005
UI Config Top LAddr: 0x110 5010 = 0x400f 65ac (Address of fb2)
UI Config Pitch: 0x110 500c = 0xb40 (720 * 4)
UI Config Size: 0x110 5004 = 0x59f 02cf (1439 << 16 + 719)
UI Overlay Size: 0x110 5088 = 0x59f 02cf (1439 << 16 + 719)
IO Config Coord: 0x110 5008 = 0x0
```
Note that UI Config Size and UI Overlay Size are <code>(height-1) << 16 + (width-1)</code>
</li>
<li>
For Channel 1: Set Blender Output
<ul>
<li>BLD Output Size (BLD_SIZE @ BLD Offset 0x08C): BLD output size setting register</li>
<li>GLB Size (GLB_SIZE @ GLB Offset 0x00C): Global size register</li>
</ul>
<code>text
Channel 1: Set Blender Output
BLD Output Size: 0x110 108c = 0x59f 02cf (1439 * 16 + 719)
GLB Size: 0x110 000c = 0x59f 02cf (1439 * 16 + 719)</code>
</li>
<li>
Set Blender Input Pipe (N = Pipe Number, from 0 to 2 for Channels 1 to 3)
<ul>
<li>BLD Pipe InSize (BLD_CH_ISIZE @ BLD Offset 0x008 + N*0x14): BLD input memory size register(N=0,1,2,3,4)</li>
<li>BLD Pipe FColor (BLD_FILL_COLOR @ BLD Offset 0x004 + N*0x14): BLD fill color register(N=0,1,2,3,4)</li>
<li>BLD Pipe Offset (BLD_CH_OFFSET @ BLD Offset 0x00C + N*0x14): BLD input memory offset register(N=0,1,2,3,4)</li>
<li>BLD Pipe Mode (BLD_CTL @ BLD Offset 0x090 – 0x09C): BLD control register</li>
</ul>
(Should <code>N*0x14</code> be <code>N*0x10</code> instead?)
```text
Channel 1: Set Blender Input Pipe 0 (fb0 is 720 x 1440)
BLD Pipe InSize: 0x110 1008 = 0x59f 02cf (1439 * 16 + 719)
BLD Pipe FColor: 0x110 1004 = 0xff00 0000
BLD Pipe Offset: 0x110 100c = 0x0
BLD Pipe Mode: 0x110 1090 = 0x301 0301
Channel 2: Set Blender Input Pipe 1 (fb1 is 600 x 600)
BLD Pipe InSize: 0x110 1018 = 0x257 0257 (599 << 16 + 599)
BLD Pipe FColor: 0x110 1014 = 0xff00 0000
BLD Pipe Offset: 0x110 101c = 0x34 0034
BLD Pipe Mode: 0x110 1094 = 0x301 0301
Channel 3: Set Blender Input Pipe 2 (fb2 is 720 x 1440)
BLD Pipe InSize: 0x110 1028 = 0x59f 02cf (1439 * 16 + 719)
BLD Pipe FColor: 0x110 1024 = 0xff00 0000
BLD Pipe Offset: 0x110 102c = 0x0
BLD Pipe Mode: 0x110 1098 = 0x301 0301
```
Note that BLD Pipe InSize is <code>(height-1) << 16 + (width-1)</code>
</li>
<li>
Disable Scaler (assuming we're not using Scaler)
```text
Channel 1: Disable Scaler
Mixer: 0x114 0000 = 0x0
Channel 2: Disable Scaler
Mixer: 0x115 0000 = 0x0
Channel 3: Disable Scaler
Mixer: 0x116 0000 = 0x0
```
</li>
</ol>
</li>
<li>
Set BLD Route and BLD FColor Control
<ul>
<li>BLD Route (BLD_CH_RTCTL @ BLD Offset 0x080): BLD routing control register</li>
<li>BLD FColor Control (BLD_FILLCOLOR_CTL @ BLD Offset 0x000): BLD fill color control register</li>
</ul>
<code>text
Set BLD Route and BLD FColor Control
BLD Route: 0x110 1080 = 0x321
BLD FColor Control: 0x110 1000 = 0x701</code>
</li>
<li>
Apply Settings: GLB DBuff
<ul>
<li>GLB DBuff (GLB_DBUFFER @ GLB Offset 0x008): Global double buffer control register</li>
</ul>
<code>text
Apply Settings
GLB DBuff: 0x110 0008 = 0x1</code>
</li>
</ol>
<a>(See the Complete Log)</a>
(See Memory Mapping List and Register List at Page 90)
Other Display Engine Features
We won't use these Display Engine Features today...
<strong>DE RT-WB:</strong> (Page 116)
<blockquote>
The Real-time write-back controller (RT-WB) provides data capture function for display engine. It captures data from RT-mixer module, performs the image resizing function, and then write-back to SDRAM.
</blockquote>
(For screen capture?)
<strong>DE VSU:</strong> (Page 128)
<blockquote>
The Video Scaler (VS) provides YUV format image resizing function for display engine. It receives data from overlay module, performs the image resizing function, and outputs to video post-processing modules.
</blockquote>
<strong>DE Rotation:</strong> (Page 137)
<blockquote>
There are several types of rotation: clockwise 0/90/180/270 degree Rotation and H-Flip/V-Flip. Operation of Copy is the same as a 0 degree rotation.
</blockquote>
Timing Controller in Allwinner A64
See this...
<ul>
<li><a>"Timing Controller (TCON0)"</a></li>
</ul>
Zig Driver for PinePhone Display Engine
We have created a Zig Driver for PinePhone's Allwinner A64 Display Engine that will render graphics...
<ul>
<li>
<a>"NuttX RTOS for PinePhone: Render Graphics in Zig"</a>
</li>
<li>
<a>"Rendering PinePhone's Display (DE and TCON0)"</a>
</li>
</ul>
To test the rendering of graphics, let's run this Zig App on NuttX for PinePhone...
<ul>
<li>
<a>render.zig</a>
</li>
<li>
<a>display.zig</a>
</li>
</ul>
Follow the instructions in the next section to download and build the NuttX Source Code for PinePhone.
In NuttX, enable the Null Example App: <code>make menuconfig</code>, select "Application Configuration" > "Examples" > "Null Example"
Compile the Zig App (based on the GCC Compiler Options, see below)...
```bash
Change "$HOME/nuttx" for your NuttX Project Directory
cd $HOME/nuttx
Download the Zig App
git clone --recursive https://github.com/lupyuen/pinephone-nuttx
cd pinephone-nuttx
Compile the Zig App for PinePhone
(armv8-a with cortex-a53)
TODO: Change "$HOME/nuttx" to your NuttX Project Directory
zig build-obj \
--verbose-cimport \
-target aarch64-freestanding-none \
-mcpu cortex_a53 \
-isystem "$HOME/nuttx/nuttx/include" \
-I "$HOME/nuttx/apps/include" \
render.zig
Copy the compiled app to NuttX and overwrite <code>null.o</code>
TODO: Change "$HOME/nuttx" to your NuttX Project Directory
cp render.o \
$HOME/nuttx/apps/examples/null/*null.o
Build NuttX to link the Zig Object from <code>null.o</code>
TODO: Change "$HOME/nuttx" to your NuttX Project Directory
cd $HOME/nuttx/nuttx
make
```
To run the Zig App...
```text
Render colour bars (pic above)
hello 1
Render colour bars with overlays (pic below)
hello 3
```
<em>How did we get the Zig Compiler options <code>-target</code>, <code>-mcpu</code>, <code>-isystem</code> and <code>-I</code>?</em>
<code>make --trace</code> shows these GCC Compiler Options when building Nuttx for PinePhone...
<code>bash
aarch64-none-elf-gcc
-c
-fno-common
-Wall
-Wstrict-prototypes
-Wshadow
-Wundef
-Werror
-Os
-fno-strict-aliasing
-fomit-frame-pointer
-g
-march=armv8-a
-mtune=cortex-a53
-isystem "/Users/Luppy/PinePhone/nuttx/nuttx/include"
-D__NuttX__
-pipe
-I "/Users/Luppy/PinePhone/nuttx/apps/include"
-Dmain=hello_main hello_main.c
-o hello_main.c.Users.Luppy.PinePhone.nuttx.apps.examples.hello.o</code>
We copied and modified these GCC Compiler Options for Zig.
<em>What about <code>-D__NuttX__</code>?</em>
The Zig Compiler won't let us specify C Macros at the Command Line, so we defined the macro <code>__NuttX__</code> in our Zig App...
https://github.com/lupyuen/pinephone-nuttx/blob/6ba90edb155a0132400ce66752eea7612c0d022e/render.zig#L32-L53
Test Zig Driver for PinePhone Display Engine
To test the A64 Display Engine with NuttX on PinePhone, we'll run our NuttX Test App...
<ul>
<li><a>test_display.c</a></li>
</ul>
Which calls our Zig Display Driver for PinePhone...
<ul>
<li>
<a>render.zig</a>
</li>
<li>
<a>display.zig</a>
</li>
</ul>
Here are the steps to download and run the NuttX Binary Image on PinePhone...
<ol>
<li>
Prepare a microSD Card with PinePhone Jumpdrive...
<a>PinePhone Jumpdrive microSD</a>
</li>
<li>
Download the compressed NuttX Binary Image...
<a>Image.gz</a>
</li>
<li>
Copy the compressed NuttX Binary Image to Jumpdrive microSD...
```bash
Copy compressed NuttX Binary Image to Jumpdrive microSD.
How to create Jumpdrive microSD: https://lupyuen.github.io/articles/uboot#pinephone-jumpdrive
TODO: Change the microSD Path
cp Image.gz "/Volumes/NO NAME"
```
</li>
<li>
To access the UART Port on PinePhone, we'll connect this USB Serial Debug Cable (at 115.2 kbps)...
<a>PinePhone Serial Debug Cable</a>
</li>
<li>
Insert the Jumpdrive microSD into PinePhone and power up
</li>
<li>
At the NuttX Shell, enter <code>hello 1</code> to render the Blue, Green and Red colour bars
<a>(See the Complete Log)</a>
</li>
<li>
Or enter <code>hello 3</code> to render the same colour bars with Blue Square and Green Circle as Overlays
<a>(See the Complete Log)</a>
</li>
</ol>
If we prefer to build the NuttX Binary Image ourselves, here are the steps to download the following Source Files and build them...
<code>text
nuttx
├── apps (NuttX Apps for PinePhone including Display Engine Version 2)
│ ├── Application.mk
│ ├── DISCLAIMER
│ ├── Directory.mk
...
├── nuttx (NuttX OS for PinePhone)
│ ├── AUTHORS
│ ├── CONTRIBUTING.md
│ ├── DISCLAIMER
...
├── p-boot (Modified p-boot Display Code)
│ ├── HACKING
│ ├── LICENSE
│ ├── NEWS
...
└── pinephone-nuttx (Zig MIPI DSI / Display Engine Driver for PinePhone)
├── LICENSE
├── README.md
├── display.zig
└── render.zig</code>
<ol>
<li>
Create the NuttX Directory...
<code>bash
mkdir nuttx
cd nuttx</code>
</li>
<li>
Download the Modified p-boot Display Code <code>p-boot.11.zip</code> from...
<a>pinephone-nuttx/releases/tag/pboot11</a>
Extract into the <code>nuttx</code> folder and rename as <code>p-boot</code>
</li>
<li>
Download and build NuttX for PinePhone inside the <code>nuttx</code> folder...
```bash
TODO: Install Build Prerequisites
https://lupyuen.github.io/articles/uboot#install-prerequisites
Download NuttX OS for PinePhone
git clone \
--recursive \
--branch pinephone \
https://github.com/lupyuen/incubator-nuttx \
nuttx
Download NuttX Apps for PinePhone including Display Engine (Version 3)
git clone \
--recursive \
--branch de3 \
https://github.com/lupyuen/incubator-nuttx-apps \
apps
We'll build NuttX inside nuttx/nuttx
cd nuttx
Configure NuttX for Single Core
./tools/configure.sh -l qemu-a53:nsh
Build NuttX. Ignore the Linker Errors
make
```
</li>
<li>
Follow these steps to compile our Zig MIPI DSI Driver and link into NuttX...
<a>"Zig Driver for PinePhone Display Engine"</a>
</li>
<li>
Compress the NuttX Binary Image...
<code>bash
cp nuttx.bin Image
rm -f Image.gz
gzip Image</code>
</li>
<li>
Copy the compressed NuttX Binary Image <code>Image.gz</code> to Jumpdrive microSD according to the steps above.
Insert the Jumpdrive microSD into PinePhone and power up.
At the NuttX Shell, enter <code>hello 1</code> or <code>hello 3</code>
</li>
</ol>
(The steps look messy today, hopefully we'll remove p-boot after we have created our NuttX Display Driver)
Complete PinePhone Display Driver in Zig
We have completed the entire PinePhone Display Driver in Zig!
https://github.com/lupyuen/pinephone-nuttx/blob/432c15a55d97fd044f291aba292b1c4efb431f41/render.zig#L176-L226
Here are the Zig Modules...
<ul>
<li>
<a><code>render.zig</code></a>: Allwinner A64 Display Engine (DE)
</li>
<li>
<a><code>display.zig</code></a>: Allwinner A64 MIPI Display Serial Interface (DSI)
</li>
<li>
<a><code>dphy.zig</code></a>: Allwinner A64 MIPI Display Physical Layer (DPHY)
</li>
<li>
<a><code>tcon.zig</code></a>: Allwinner A64 Timing Controller (TCON0)
</li>
<li>
<a><code>backlight.zig</code></a>: PinePhone Display Backlight
</li>
<li>
<a><code>pmic.zig</code></a>: PinePhone Power Management Integrated Circuit
</li>
<li>
<a><code>panel.zig</code></a>: PinePhone LCD Panel
</li>
</ul>
This is the detailed output of the Zig Driver, with Register Addresses and Values...
<ul>
<li><a>"Testing Zig Driver on PinePhone"</a></li>
</ul>
We'll merge these modules to NuttX Mainline as a NuttX Framebuffer Driver.
We created these modules by reverse-engineering the log generated by the <a>p-boot Display Code</a>.
Add MIPI DSI to NuttX Kernel
We're adding the MIPI DSI Driver to the NuttX Kernel...
<ul>
<li>
<a>mipi_dsi.c</a>: Compose MIPI DSI Packets (Long, Short, Short with Parameter)
</li>
<li>
<a>a64_mipi_dsi.c</a>: MIPI Display Serial Interface (DSI) for Allwinner A64
</li>
<li>
<a>a64_mipi_dphy.c</a>: MIPI Display Physical Layer (D-PHY) for Allwinner A64
</li>
</ul>
We created the above NuttX Source Files (in C) by converting our Zig MIPI DSI Driver to C...
<ul>
<li>
<a>display.zig</a>: Zig Driver for MIPI DSI
</li>
<li>
<a>dphy.zig</a>: Zig Driver for MIPI D-PHY
</li>
</ul>
That we Reverse-Engineered from the logs that we captured from PinePhone p-boot...
<ul>
<li>
<a>"Understanding PinePhone's Display (MIPI DSI)"</a>
</li>
<li>
<a>"NuttX RTOS for PinePhone: Display Driver in Zig"</a>
</li>
<li>
<a>"Rendering PinePhone's Display (DE and TCON0)"</a>
</li>
<li>
<a>"NuttX RTOS for PinePhone: Render Graphics in Zig"</a>
</li>
</ul>
<em>Was it difficult to convert Zig to C?</em>
Not at all!
Here's the Zig code for our MIPI DSI Driver...
https://github.com/lupyuen/pinephone-nuttx/blob/3d33e5a49a5a3857c39fe8aa79af60902a70088e/display.zig#L115-L170
And here's the converted C code for NuttX: <a>mipi_dsi.c</a>
```c
ssize_t mipi_dsi_short_packet(FAR uint8_t <em>pktbuf,
size_t pktlen,
uint8_t channel,
enum mipi_dsi_e cmd,
FAR const uint8_t </em>txbuf,
size_t txlen)
{
/<em> Data Identifier (DI) (1 byte):
* Virtual Channel Identifier (Bits 6 to 7)
* Data Type (Bits 0 to 5) </em>/
const uint8_t vc = channel;
const uint8_t dt = cmd;
const uint8_t di = (vc << 6) |
dt;
/<em> Data (2 bytes): Fill with 0 if Second Byte is missing </em>/
const uint8_t data[2] =
{
txbuf[0], /<em> First Byte </em>/
(txlen == 2) ? txbuf[1] : 0, /<em> Second Byte </em>/
};
/<em> Data Identifier + Data (3 bytes):
* For computing Error Correction Code (ECC) </em>/
const uint8_t di_data[3] =
{
di,
data[0],
data[1]
};
/<em> Compute ECC for Data Identifier + Word Count </em>/
const uint8_t ecc = compute_ecc(di_data,
sizeof(di_data));
/<em> Packet Header (4 bytes):
* Data Identifier + Data + Error Correction Code </em>/
const uint8_t header[4] =
{
di_data[0],
di_data[1],
di_data[2],
ecc
};
/<em> Packet Length is Packet Header Size (4 bytes) </em>/
const size_t len = sizeof(header);
ginfo("channel=%d, cmd=0x%x, txlen=%ld\n", channel, cmd, txlen);
DEBUGASSERT(pktbuf != NULL && txbuf != NULL);
DEBUGASSERT(channel < 4);
DEBUGASSERT(cmd < (1 << 6));
if (txlen < 1 || txlen > 2) { DEBUGPANIC(); return ERROR; }
if (len > pktlen) { DEBUGPANIC(); return ERROR; }
/<em> Copy Packet Header to Packet Buffer </em>/
memcpy(pktbuf,
header,
sizeof(header)); /<em> 4 bytes </em>/
/<em> Return the Packet Length </em>/
return len;
}
```
The code looks highly similar!
Test MIPI DSI for NuttX Kernel
<em>How do we test the MIPI DSI Driver in the NuttX Kernel?</em>
Right now we have implemented the following in the NuttX Kernel...
<ul>
<li>Driver for MIPI Display Serial Interface (DSI)</li>
<li>Driver for MIPI Display Physical Layer (D-PHY)</li>
</ul>
But to render graphics on PinePhone we need the following drivers, which are still in Zig, pending conversion to C...
<ul>
<li>Driver for Display Backlight</li>
<li>Driver for Timing Controller TCON0</li>
<li>Driver for Power Mgmt IC</li>
<li>Driver for LCD Panel</li>
<li>Driver for Display Engine</li>
</ul>
Running an Integration Test across the C and Zig Drivers will be a little interesting. Here's how we run the Integration Test...
We created this program in Zig that calls the C and Zig Drivers, in the right sequence...
https://github.com/lupyuen/pinephone-nuttx/blob/bc560cea04f601542eb1d3d71fb00dbc647d982d/render.zig#L1143-L1176
Then we compile the Zig Test Program targeting PinePhone...
```bash
## Configure NuttX
cd nuttx
./tools/configure.sh pinephone:nsh
make menuconfig
## Select "System Type > Allwinner A64 Peripheral Selection > DE"
## Select "System Type > Allwinner A64 Peripheral Selection > RSB"
## Select "Build Setup > Debug Options > Graphics Debug Features > Error + Warnings + Info"
## Select "Build Setup > Debug Options > Battery-related Debug Features > Error + Warnings + Info"
## Select "Device Drivers > Framebuffer Overlay Support"
## Save and exit menuconfig
## Build NuttX
make
## Download the Zig Test Program
pushd $HOME
git clone https://github.com/lupyuen/pinephone-nuttx
cd pinephone-nuttx
## Compile the Zig App for PinePhone
## (armv8-a with cortex-a53)
## TODO: Change "$HOME/nuttx" to your NuttX Project Directory
zig build-obj \
--verbose-cimport \
-target aarch64-freestanding-none \
-mcpu cortex_a53 \
-isystem "$HOME/nuttx/nuttx/include" \
-I "$HOME/nuttx/apps/include" \
render.zig
## Copy the compiled app to NuttX and overwrite <code>hello.o</code>
## TODO: Change "$HOME/nuttx" to your NuttX Project Directory
cp render.o \
$HOME/nuttx/apps/examples/hello/*hello.o
## Return to the NuttX Folder
popd
## Link the Compiled Zig App with NuttX
make
```
<a>(Or download the binaries here)</a>
We boot NuttX on PinePhone and run the Zig Test Program...
```text
NuttShell (NSH) NuttX-11.0.0-pinephone
nsh> uname -a
NuttX 11.0.0-pinephone 2a1577a-dirty Dec 9 2022 13:57:47 arm64 pinephone
nsh> hello 0
```
<a>(Source)</a>
Yep our Zig Test Program renders graphics successfully on PinePhone! (Pic above)
Which means the NuttX Kernel Drivers for MIPI DSI are working OK!
Here's the Test Log for our Zig Test Program running on NuttX and PinePhone...
<ul>
<li><a>Test Log for NuttX MIPI DSI on PinePhone</a></li>
</ul>
<em>What about Unit Testing? Can we test the MIPI DSI / D-PHY Driver without other drivers?</em>
Yep! Our MIPI DSI Driver simply writes values to a bunch of A64 Hardware Registers, like so: <a>a64_mipi_dsi.c</a>
```c
/<em> DSI Configuration Register 1 (A31 Page 846)
* Set Video_Start_Delay (Bits 4 to 16) to 1468 (Line Delay)
* Set Video_Precision_Mode_Align (Bit 2) to 1 (Fill Mode)
* Set Video_Frame_Start (Bit 1) to 1 (Precision Mode)
* Set DSI_Mode (Bit 0) to 1 (Video Mode)
* Note: Video_Start_Delay is actually 13 bits, not 8 bits as stated
* in A31 User Manual
</em>/
#define DSI_BASIC_CTL1_REG (A64_DSI_ADDR + 0x14)
#define DSI_MODE (1 << 0)
#define VIDEO_FRAME_START (1 << 1)
#define VIDEO_PRECISION_MODE_ALIGN (1 << 2)
#define VIDEO_START_DELAY(n) (n << 4)
dsi_basic_ctl1 = VIDEO_START_DELAY(1468) |
VIDEO_PRECISION_MODE_ALIGN |
VIDEO_FRAME_START |
DSI_MODE;
putreg32(dsi_basic_ctl1, DSI_BASIC_CTL1_REG);
// Include Test Code
#include "../../pinephone-nuttx/test/test_a64_mipi_dsi2.c"
```
So we only need to ensure that the Hardware Addresses and the Written Values are correct.
To do that, we use Assertion Checks to verify the Addresses and Values: <a>test_a64_mipi_dsi2.c</a>
<code>c
// Test Code
DEBUGASSERT(DSI_BASIC_CTL1_REG == 0x1ca0014);
DEBUGASSERT(dsi_basic_ctl1 == 0x5bc7);</code>
If the Addresses or Values are incorrect, our MIPI DSI Driver halts with an Assertion Failure.
(We remove the Assertion Checks in the final version of our driver)
<em>What about a smaller, self-contained Unit Test for MIPI DSI?</em>
Here's the Unit Test that verifies MIPI DSI Packets (Long / Short / Short with Parameter) are composed correctly...
https://github.com/lupyuen/pinephone-nuttx/blob/46f055eceae268fa7ba20d69c12d4823491a89b9/test/test_mipi_dsi.c#L1-L109
<em>Can we test the MIPI DSI Driver on our Local Computer? Without running on PinePhone?</em>
Most certainly! In fact we test the MIPI DSI Driver on our Local Computer first before testing on PinePhone. Here's how...
Remember that our MIPI DSI Driver simply writes values to a bunch of A64 Hardware Registers. So we only need to ensure that the Hardware Addresses and the Written Values are correct.
We created a Test Scaffold that simulates the NuttX Build Environment...
https://github.com/lupyuen/pinephone-nuttx/blob/44167d81edbd054d3285ca3a6087926e6fc9ce79/test/test.c#L7-L51
Then we compile the Test Scaffold and run it on our Local Computer...
https://github.com/lupyuen/pinephone-nuttx/blob/cdb6bbc8e57ef02104bdbde721f8ff6787d74efc/test/run.sh#L9-L36
Note that we capture the <a>Actual Test Log</a> and we <code>diff</code> it with the <a>Expected Test Log</a>. That's how we detect discrepancies in the Hardware Addresses and the Written Values...
https://github.com/lupyuen/pinephone-nuttx/blob/c04f1447933665df207a42f626c726ef7a7def65/test/test.log#L4-L20
Test Timing Controller TCON0 Driver for NuttX Kernel
We're adding the Timing Controller TCON0 Driver to NuttX Kernel...
<ul>
<li><a>arch/arm64/src/a64/a64_tcon0.c</a></li>
</ul>
Right now we have implemented the following in the NuttX Kernel...
<ul>
<li>Driver for MIPI Display Serial Interface (DSI)</li>
<li>Driver for MIPI Display Physical Layer (D-PHY)</li>
<li>Driver for Timing Controller TCON0</li>
</ul>
But to render graphics on PinePhone we need the following drivers, which are still in Zig, pending conversion to C...
<ul>
<li>Driver for Display Backlight</li>
<li>Driver for Power Mgmt IC</li>
<li>Driver for LCD Panel</li>
<li>Driver for Display Engine</li>
</ul>
So we created this Test Program in Zig that calls the C and Zig Drivers, in the right sequence...
https://github.com/lupyuen/pinephone-nuttx/blob/15111a227a62204b2bd6b13c489ff4a972e6d8ad/render.zig#L1146-L1199
<a>(Download the binaries here)</a>
We boot NuttX on PinePhone and run the Zig Test Program...
```text
NuttShell (NSH) NuttX-11.0.0-pinephone
nsh> uname -a
NuttX 11.0.0-pinephone 893b147 Dec 14 2022 23:01:27 arm64 pinephone
nsh> hello 0
```
<a>(Source)</a>
Our Zig Test Program renders the Test Pattern successfully on PinePhone. <a>(Like this)</a>
Here's the Test Log, with Graphics Logging Enabled...
<ul>
<li><a>NuttX Kernel TCON0 Test Log</a></li>
</ul>
We also tested with Graphics Logging Disabled, to preempt any timing issues...
<ul>
<li><a>NuttX Kernel TCON0 Test Log (Graphics Logging Disabled)</a></li>
</ul>
Test Display Engine Driver for NuttX Kernel
We're adding the Display Engine Driver to NuttX Kernel...
<ul>
<li><a>arch/arm64/src/a64/a64_de.c</a></li>
</ul>
Right now we have implemented the following in the NuttX Kernel...
<ul>
<li>Driver for MIPI Display Serial Interface (DSI)</li>
<li>Driver for MIPI Display Physical Layer (D-PHY)</li>
<li>Driver for Timing Controller TCON0</li>
<li>Driver for Display Engine</li>
</ul>
But to render graphics on PinePhone we need the following drivers, which are still in Zig, pending conversion to C...
<ul>
<li>Driver for Display Backlight</li>
<li>Driver for Power Mgmt IC</li>
<li>Driver for LCD Panel</li>
<li>Driver for Pulse-Width Modulation</li>
<li>Driver for Reduced Serial Bus</li>
</ul>
So we created this Test Program in Zig that calls the C and Zig Drivers, in the right sequence...
https://github.com/lupyuen/pinephone-nuttx/blob/720b8042aa2f86b336947b8ce4744872a77d13f5/render.zig#L1146-L1194
<a>(Download the binaries here)</a>
We boot NuttX on PinePhone and run the Zig Test Program...
```text
NuttShell (NSH) NuttX-11.0.0-pinephone
nsh> uname -a
NuttX 11.0.0-pinephone 7d85079-dirty Dec 17 2022 11:43:03 arm64 pinephone
nsh> hello 0
```
<a>(Source)</a>
Our Zig Test Program renders the Test Pattern successfully on PinePhone. <a>(Like this)</a>
Here's the Test Log, with Graphics Logging Enabled...
<ul>
<li><a>NuttX Kernel Display Engine Test Log</a></li>
</ul>
We also tested with Graphics Logging Disabled, to preempt any timing issues...
<ul>
<li><a>NuttX Kernel TCON0 Test Log (Graphics Logging Disabled)</a></li>
</ul>
Missing Pixels in PinePhone Image
We've just implemented the NuttX Kernel Drivers for MIPI Display Serial Interface, Timing Controller TCON0, Display Engine, Reduced Serial Bus, Power Management Integrated Circuit and LCD Panel...
<ul>
<li>
<a>"NuttX RTOS for PinePhone: MIPI Display Serial Interface"</a>
</li>
<li>
<a>"NuttX RTOS for PinePhone: Display Engine"</a>
</li>
<li>
<a>"NuttX RTOS for PinePhone: LCD Panel"</a>
</li>
</ul>
And we're adding the Framebuffer Driver to NuttX Kernel...
https://github.com/apache/nuttx/pull/7988
When we run the <code>fb</code> NuttX Example App, we see missing pixels in the rendered image...
<ul>
<li>
Inside the Yellow Box is supposed to be an Orange Box
</li>
<li>
Inside the Orange Box is supposed to be a Red Box
</li>
</ul>
The missing pixels magically appear later in a curious pattern...
<ul>
<li><a>Watch the Demo on YouTube</a></li>
</ul>
There seems to be a problem with Framebuffer DMA / Display Engine / Timing Controller TCON0?
According to the video, the pixels are actually written correctly to the RAM Framebuffer. But the pixels at the lower half don't get pushed to the display until the next screen refresh.
There seems to be a lag between the writing of pixels to framebuffer, and the pushing of pixels to the display over DMA / Display Engine / Timing Controller TCON0.
Here's the fix for this lag...
Fix Missing Pixels in PinePhone Image
In the previous section we saw that there was a lag pushing pixels from the RAM Framebuffer to the PinePhone Display (over DMA / Display Engine / Timing Controller TCON0).
Can we overcome this lag by copying the RAM Framebuffer to itself, forcing the display to refresh? This sounds very strange, but yes it works!
From <a>pinephone_display.c</a>:
```c
// Update the display when there is a change to the framebuffer.
// (ioctl Entrypoint: FBIO_UPDATE)
static int pinephone_updatearea(
struct fb_vtable_s <em>vtable, // Framebuffer driver object
const struct fb_area_s </em>area // Updated area of framebuffer
) {
uint8_t <em>fb = (uint8_t </em>)g_pinephone_fb0;
const size_t fbsize = sizeof(g_pinephone_fb0);
// Copy the entire framebuffer to itself,
// to fix the missing pixels.
// Not sure why this works.
for (int i = 0; i < fbsize; i++) {
<code>// Declare as volatile to prevent compiler optimization
volatile uint8_t v = fb[i];
fb[i] = v;
</code>
}
return OK;
}
```
With the code above, the Red, Orange and Yellow Boxes are now rendered correctly in our NuttX Framebuffer Driver for PinePhone. (Pic below)
<em>Who calls pinephone_updatearea?</em>
After writing the pixels to the RAM Framebuffer, NuttX Apps will call <code>ioctl(FBIO_UPDATE)</code> to update the display.
This triggers <code>pinephone_updatearea</code> in our NuttX Framebuffer Driver: <a>fb_main.c</a>
```c
// Omitted: NuttX App writes pixels to RAM Framebuffer
// Update the Framebuffer
ifdef CONFIG_FB_UPDATE
ret = ioctl( // I/O Command
state->fd, // Framebuffer File Descriptor
FBIO_UPDATE, // Update the Framebuffer
(unsigned long)((uintptr_t)area) // Updated area
);
endif
```
<em>How do other PinePhone operating systems handle this?</em>
We might need to handle TCON0 Vertical Blanking (<code>TCON0_Vb_Int_En</code> / <code>TCON0_Vb_Int_Flag</code>) and TCON0 CPU Trigger Mode Finish (<code>TCON0_Tri_Finish_Int_En</code> / <code>TCON0_Tri_Finish_Int_Flag</code>) like this...
<ul>
<li>
<a>sun4i_tcon_enable_vblank</a>
</li>
<li>
<a>sun4i_tcon_handler</a>
<a>(More about sun4i_tcon_handler)</a>
</li>
</ul>
p-boot Bootloader seems to handle every TCON0 CPU Trigger Mode Finish (<code>TCON0_Tri_Finish_Int_En</code> / <code>TCON0_Tri_Finish_Int_Flag</code>) by updating the Display Engine Registers. Which sounds odd...
<ol>
<li>
Render Loop waits forever for <code>EV_VBLANK</code>: <a>dtest.c</a>
</li>
<li>
<code>EV_VBLANK</code> is triggered by <code>display_frame_done</code>: <a>gui.c</a>
</li>
<li>
<code>display_frame_done</code> is triggered by TCON0 CPU Trigger Mode Finish: <a>display.c</a>
</li>
<li>
Render Loop handles <code>EV_VBLANK</code> by redrawing and calling <code>display_commit</code>: <a>dtest.c</a>
</li>
<li>
<code>display_commit</code> updates the Display Engine Registers, including the Framebuffer Addresses: <a>display.c</a>
</li>
</ol>
Can we handle TCON0 CPU Trigger Mode Finish without refreshing the Display Engine Registers?
Merge PinePhone into NuttX Mainline
Read the article...
<ul>
<li><a>"Preparing a Pull Request for Apache NuttX RTOS"</a></li>
</ul>
We're merging PinePhone into NuttX Mainline!
NuttX Mainline now supports Generic Interrupt Controller Version 2...
<ul>
<li><a>"arch/arm64: Add support for Generic Interrupt Controller Version 2"</a></li>
</ul>
We created a NuttX Board Configuration for PinePhone that will boot to NuttX Shell (NSH)...
<ul>
<li><a>"arch/arm64: Add support for PINE64 PinePhone"</a></li>
</ul>
And now PinePhone is officially supported by Apache NuttX RTOS!
<ul>
<li><a>"PinePhone is now supported by Apache NuttX RTOS"</a></li>
</ul>
Here's how we prepared the Pull Requests for NuttX...
<ul>
<li><a>"Preparing a Pull Request for Apache NuttX RTOS"</a></li>
</ul>
LVGL on NuttX on PinePhone
Read the article...
<ul>
<li><a>"NuttX RTOS for PinePhone: Boot to LVGL"</a></li>
</ul>
LVGL on Apache NuttX RTOS (Mainline) renders correctly on PinePhone! (Pic below)
Just select the LVGL Demo App that's bundled with Apache NuttX RTOS. Here are the settings in <code>make menuconfig</code>...
Enable "<strong>Application Configuration</strong> > <strong>Graphics Support</strong> > <strong>Light and Versatile Graphics Library (LVGL)</strong>"
Enable "<strong>LVGL</strong> > <strong>Enable Framebuffer Port</strong>"
Browse into "<strong>LVGL</strong> > <strong>LVGL Configuration</strong>"
<ul>
<li>
In "<strong>Color Settings</strong>"
Set <strong>Color Depth</strong> to "<strong>32: ARGB8888</strong>"
</li>
<li>
In "<strong>Memory settings</strong>"
Set <strong>Size of Memory</strong> to <strong>64</strong>
</li>
<li>
In "<strong>HAL Settings</strong>"
Set <strong>Default Dots Per Inch</strong> to <strong>250</strong>
</li>
<li>
In "<strong>Demos</strong>"
Enable "<strong>Show Some Widgets</strong>"
</li>
</ul>
Enable "<strong>Application Configuration</strong> > <strong>Examples</strong> > <strong>LVGL Demo</strong>"
Touch Input is not supported yet. We're working on it!
For details on the NuttX Framebuffer for PinePhone (and how it works with LVGL) check out this article...
<ul>
<li><a>"NuttX RTOS for PinePhone: Framebuffer"</a></li>
</ul>
LVGL Settings for PinePhone
When we run the LVGL Demo App on PinePhone with Apache NuttX RTOS, it renders a dense screen that's not so Touch-Friendly...
Let's tweak the LVGL Settings to make our LVGL App more accessible. Modify this LVGL Source File...
<a>apps/graphics/lvgl/lvgl/demos/widgets/lv_demo_widgets.c</a>
```c
// Insert this
include
// Modify this function
void lv_demo_widgets(void)
{
// Note: PinePhone has width 720 pixels.
// LVGL will set Display Size to Large, which looks really tiny.
// Shouldn't this code depend on DPI? (267 DPI for PinePhone)
if(LV_HOR_RES <= 320) disp_size = DISP_SMALL;
else if(LV_HOR_RES < 720) disp_size = DISP_MEDIUM;
else disp_size = DISP_LARGE;
<code>// Insert this: Print warning if font is missing
#undef LV_LOG_WARN
#define LV_LOG_WARN(s) puts(s)
// Insert this: Change Display Size from Large to Medium, to make Widgets easier to tap
printf("Before: disp_size=%d\n", disp_size);
disp_size = DISP_MEDIUM;
printf("After: disp_size=%d\n", disp_size);
// Existing Code
font_large = LV_FONT_DEFAULT;
font_normal = LV_FONT_DEFAULT;
lv_coord_t tab_h;
if(disp_size == DISP_LARGE) {
...
}
// For Medium Display Size...
else if(disp_size == DISP_MEDIUM) {
// Change this: Increase Tab Height from 45 to 70, to make Tabs easier to tap
tab_h = 70;
// Previously: tab_h = 45;
</code>
if LV_FONT_MONTSERRAT_20
<code> font_large = &lv_font_montserrat_20;
</code>
else
<code> LV_LOG_WARN("LV_FONT_MONTSERRAT_20 is not enabled for the widgets demo. Using LV_FONT_DEFAULT instead.");
</code>
endif
if LV_FONT_MONTSERRAT_14
<code> font_normal = &lv_font_montserrat_14;
</code>
else
<code> LV_LOG_WARN("LV_FONT_MONTSERRAT_14 is not enabled for the widgets demo. Using LV_FONT_DEFAULT instead.");
</code>
endif
<code>}
</code>
```
(Maybe we should modify the code above to include DPI? PinePhone's Display has 267 DPI)
Configure LVGL with these settings...
<ul>
<li><a>"LVGL Calls Our Driver"</a></li>
</ul>
And add the fonts...
<ul>
<li>
Browse into "<strong>LVGL</strong> > <strong>LVGL Configuration</strong>"
<ul>
<li>
In "<strong>Font usage</strong> > <strong>Enable built-in fonts</strong>"
Enable "<strong>Montserrat 20</strong>"
</li>
</ul>
</li>
</ul>
The LVGL Demo App is now less dense and easier to use...
<ul>
<li>
<a>Watch the Demo on YouTube</a>
(Shot at ISO 800, F/5.6, Manual Focus on Sony NEX-7. Post-processed for Brightness, Constrast and White Point)
</li>
</ul>
<em>What if we increase the Default Font Size? From Montserrat 14 to Montserrat 20?</em>
Let's increase the Default Font Size from 14 to 20...
<ul>
<li>
Browse into "<strong>LVGL</strong> > <strong>LVGL Configuration</strong>"
<ul>
<li>
In "<strong>Font usage</strong> > <strong>Select theme default title font</strong>"
Select "<strong>Montserrat 20</strong>"
</li>
</ul>
</li>
</ul>
We run the LVGL Demo App as is, leaving Display Size <code>disp_size</code> as default <code>DISP_LARGE</code>.
Now the text is legible, but some controls are squished...
<ul>
<li>
<a>Watch the Demo on YouTube</a>
(Shot at ISO 400, F/5.0, Manual Focus, Exposure 0.3 on Sony NEX-7. No post-processing)
</li>
</ul>
We need to increase the Default Font Size from 14 to 20, AND set Display Size <code>disp_size</code> to <code>DISP_MEDIUM</code>. And we will get this...
More details here...
<ul>
<li><a>"NuttX RTOS for PinePhone: Boot to LVGL"</a></li>
</ul>
LVGL Demos on PinePhone
<em>We've seen the LVGL Widgets Demo on NuttX for PinePhone. What about other demos?</em>
Yep there are 5 LVGL Demos available in <code>make menuconfig</code>...
<ul>
<li>
Browse into "<strong>LVGL</strong> > <strong>LVGL Configuration</strong>"
<ul>
<li>
In "<strong>Demos</strong>", select one or more of the these demos...
"<strong>Show Some Widgets</strong>"
"<strong>Demonstrate the usage of encoder and keyboard</strong>"
"<strong>Benchmark your system</strong>"
"<strong>Stress test for LVGL</strong>"
"<strong>Music player demo</strong>"
</li>
</ul>
</li>
</ul>
For Music Player Demo, we need these fonts...
<ul>
<li>
Browse into "<strong>LVGL</strong> > <strong>LVGL Configuration</strong>"
<ul>
<li>
In "<strong>Font usage</strong>", select...
"<strong>Montserrat 16</strong>"
"<strong>Montserrat 20</strong>"
"<strong>Montserrat 22</strong>"
"<strong>Montserrat 32</strong>"
</li>
</ul>
</li>
</ul>
To run the demos on PinePhone...
<code>text
nsh> lvgldemo
Usage: lvgldemo demo_name
demo_name:
widgets
keypad_encoder
benchmark
stress
music</code>
<a>(Source)</a>
We've seen the LVGL Widgets Demo...
<ul>
<li><a>LVGL Widgets Demo on YouTube</a></li>
</ul>
Here's the LVGL Music Player Demo...
<ul>
<li><a>LVGL Music Player Demo on YouTube</a></li>
</ul>
And the LVGL Benchmark Demo...
<ul>
<li><a>LVGL Benchmark Demo on YouTube</a></li>
</ul>
From the video we see the LVGL Benchmark Numbers...
<ul>
<li>Weighted Frames Per Second: 20</li>
<li>Opa Speed: 100%</li>
</ul>
| Slow but common cases | Frames Per Sec |
|-----------------------|-------------------|
| Image RGB | 19
| Image RGB + Opa | 17
| Image ARGB | 18
| Image ARGB + Opa | 17
| Image ARGB Recolor | 17
| Image ARGB Recolor + Opa | 16
| Substr Image | 19
| All Cases | Frames Per Sec |
|-----------|-------------------|
| Rectangle | 24
| Rectangle + Opa | 23
| Rectangle Rounded | 23
| Rectangle Rounded + Opa | 21
| Circle | 23
| Circle + Opa | 20
| Border | 24
| Border + Opa | 24
| Border Rounded | 24
| (Many many more) |
More details here...
<ul>
<li><a>"NuttX RTOS for PinePhone: Boot to LVGL"</a></li>
</ul>
Note that the LVGL Demos start automatically when NuttX boots on PinePhone. Let's talk about this...
Boot to LVGL on PinePhone
<em>Can we boot NuttX on PinePhone, directly to LVGL? Without a Serial Cable?</em>
Sure can! In the previous section we talked about selecting the LVGL Demos.
To boot directly to an LVGL Demo, make sure only 1 LVGL Demo is selected.
<a>(Because of this)</a>
Then in <code>make menuconfig</code>...
<ol>
<li>
RTOS Features > Tasks and Scheduling
</li>
<li>
Set "Application entry point" to <code>lvgldemo_main</code>
(INIT_ENTRYPOINT)
</li>
<li>
Set "Application entry name" to <code>lvgldemo_main</code>
(INIT_ENTRYNAME)
</li>
<li>
Application Configuration > NSH Library
<ul>
<li>Disable "Have architecture-specific initialization"</li>
</ul>
(NSH_ARCHINIT)
</li>
</ol>
NuttX on PinePhone now boots to the LVGL Touchscreen Demo, without a Serial Cable! (Pic below)
<ul>
<li><a>LVGL Music Player Demo on YouTube</a></li>
</ul>
<em>Why disable "NSH Architecture-Specific Initialization"?</em>
Normally the NSH NuttX Shell initialises the Display Driver and Touch Panel on PinePhone.
But since we're not running NSH Shell, we'll have to initialise the Display Driver and Touch Panel in our LVGL Demo App.
This is explained here...
<ul>
<li><a>lvgldemo.c</a></li>
</ul>
<em>Now that we can boot NuttX to an LVGL Touchscreen App, what next?</em>
Maybe we can create an LVGL Terminal App? That will let us interact with the NSH NuttX Shell?
LVGL already provides an Onscreen Keyboard that works on PinePhone NuttX.
More details here...
<ul>
<li><a>"NuttX RTOS for PinePhone: Boot to LVGL"</a></li>
</ul>
PinePhone Touch Panel
Read the article...
<ul>
<li><a>"NuttX RTOS for PinePhone: Touch Panel"</a></li>
</ul>
Now that we can render LVGL Graphical User Interfaces, let's handle Touch Input!
Here's everything we know about PinePhone's Touch Panel...
<ul>
<li><a><strong>"Touch Panel"</strong></a></li>
</ul>
According to our <a><strong>Test Code</strong></a>...
<ul>
<li>
<strong>I2C Address</strong> is <strong>0x5D</strong>
</li>
<li>
<strong>I2C Frequency</strong> is <strong>400 kHz</strong>
(What's the max?)
</li>
<li>
<strong>I2C Register Addresses</strong> are 16-bit
(Send MSB before LSB, so we should swap the bytes)
</li>
<li>
Reading I2C Register <strong>0x8140</strong> (Product ID) will return the bytes...
<code>text
39 31 37 53</code>
Which is ASCII for "<strong><code>917S</code></strong>"
(Goodix GT917S Touch Panel)
</li>
</ul>
This is how we read the Product ID from the Touch Panel: <a>pinephone_bringup.c</a>
```c
// Product ID (LSB 4 bytes)
define GOODIX_REG_ID 0x8140
// Read Touch Panel over I2C
static void touch_panel_read(struct i2c_master_s *i2c)
{
uint32_t freq = 400000; // 400 kHz
uint16_t addr = 0x5d; // Default I2C Address for Goodix GT917S
uint16_t reg = GOODIX_REG_ID; // Read Product ID
uint8_t regbuf[2] = { reg >> 8, reg & 0xff }; // Flip the bytes
// Erase the receive buffer
uint8_t buf[4];
ssize_t buflen = sizeof(buf);
memset(buf, 0xff, sizeof(buf));
// Compose the I2C Messages
struct i2c_msg_s msgv[2] =
{
{
.frequency = freq,
.addr = addr,
.flags = 0,
.buffer = regbuf,
.length = sizeof(regbuf)
},
{
.frequency = freq,
.addr = addr,
.flags = I2C_M_READ,
.buffer = buf,
.length = buflen
}
};
// Execute the I2C Transfer
int ret = I2C_TRANSFER(i2c, msgv, 2);
if (ret < 0) { _err("I2C Error: %d\n", ret); return; }
// Dump the receive buffer
infodumpbuffer("buf", buf, buflen);
// Shows "39 31 37 53" or "917S"
}
```
To detect Touch Events, we'll need to handle the Interrupts triggered by Touch Panel.
Based on our research, PinePhone's Touch Panel Interrupt (CTP-INT) is connected at PH4.
Right now we poll PH4 (instead of handling interrupts) because it's easier: <a>pinephone_bringup.c</a>
```c
// Test Touch Panel Interrupt by Polling as GPIO Input.
// Touch Panel Interrupt (CTP-INT) is at PH4.
// Configure for GPIO Input
define CTP_INT (PIO_INPUT | PIO_PORT_PIOH | PIO_PIN4)
static void touch_panel_read(struct i2c_master_s *i2c);
// Poll for Touch Panel Interrupt (PH4) by reading as GPIO Input
void touch_panel_initialize(struct i2c_master_s *i2c)
{
// Configure the Touch Panel Interrupt for GPIO Input
int ret = a64_pio_config(CTP_INT);
DEBUGASSERT(ret == 0);
// Poll the Touch Panel Interrupt as GPIO Input
bool prev_val = false;
for (int i = 0; i < 6000; i++) { // Poll for 60 seconds
<code>// Read the GPIO Input
bool val = a64_pio_read(CTP_INT);
// If value has changed...
if (val != prev_val) {
// Print the value
if (val) { up_putc('+'); }
else { up_putc('-'); }
prev_val = val;
// If we have just transitioned from Low to High...
if (val) {
// Read the Touch Panel over I2C
touch_panel_read(i2c);
}
}
// Wait a while
up_mdelay(10);
</code>
}
}
```
To read the Touch Coordinates, we do this: <a>pinephone_bringup.c</a>
```c
define GOODIX_REG_ID 0x8140
define GOODIX_READ_COORD_ADDR 0x814E
define GOODIX_POINT1_X_ADDR 0x8150
// Read Touch Panel over I2C
static void touch_panel_read(struct i2c_master_s *i2c)
{
// Read the Product ID
uint8_t id[4];
touch_panel_i2c_read(i2c, GOODIX_REG_ID, id, sizeof(id));
// Shows "39 31 37 53" or "917S"
// Read the Touch Panel Status
uint8_t status[1];
touch_panel_i2c_read(i2c, GOODIX_READ_COORD_ADDR, status, sizeof(status));
// Shows "81"
const uint8_t status_code = status[0] & 0x80; // Set to 0x80
const uint8_t touched_points = status[0] & 0x0f; // Set to 0x01
if (status_code != 0 && // If Touch Panel Status is OK and...
touched_points >= 1) { // Touched Points is 1 or more
<code>// Read the First Touch Coordinates
uint8_t touch[6];
touch_panel_i2c_read(i2c, GOODIX_POINT1_X_ADDR, touch, sizeof(touch));
// Shows "92 02 59 05 1b 00"
// Decode the Touch Coordinates
const uint16_t x = touch[0] + (touch[1] << 8);
const uint16_t y = touch[2] + (touch[3] << 8);
_info("touch x=%d, y=%d\n", x, y);
// Shows "touch x=658, y=1369"
</code>
}
// Set the Touch Panel Status to 0
touch_panel_set_status(i2c, 0);
}
```
When we touch PinePhone near the Lower Right Corner, we see the Touch Coordinates x=658, y=1369 (which is quite close to the 720 x 1440 screen size)...
<code>text
twi_transfer: TWI0 count: 1
twi_wait: TWI0 Waiting...
twi_put_addr: TWI address 7bits+r/w = 0xba
twi_wait: TWI0 Awakened with result: 0
-+twi_transfer: TWI0 count: 2
twi_wait: TWI0 Waiting...
twi_put_addr: TWI address 7bits+r/w = 0xba
twi_put_addr: TWI address 7bits+r/w = 0xbb
twi_wait: TWI0 Awakened with result: 0
buf (0x40a8fd18):
0000 39 31 37 53 917S
twi_transfer: TWI0 count: 2
twi_wait: TWI0 Waiting...
twi_put_addr: TWI address 7bits+r/w = 0xba
twi_put_addr: TWI address 7bits+r/w = 0xbb
twi_wait: TWI0 Awakened with result: 0
buf (0x40a8fd08):
0000 81 .
twi_transfer: TWI0 count: 2
twi_wait: TWI0 Waiting...
twi_put_addr: TWI address 7bits+r/w = 0xba
twi_put_addr: TWI address 7bits+r/w = 0xbb
twi_wait: TWI0 Awakened with result: 0
buf (0x40a8fd20):
0000 92 02 59 05 1b 00 ..Y...
touch_panel_read: touch x=658, y=1369</code>
<a>(Source)</a>
Yep we can read the Touch Coordinates correctly, with polling! (But not so efficient)
Let's handle Interrupts from the Touch Panel...
Handle Interrupts from Touch Panel
In the previous section we've read the Touch Panel by Polling. Which is easier but inefficient.
Eventually we'll use an Interrupt Handler to monitor Touch Panel Interrupts. This is how we monitor PH4 for interrupts: <a>pinephone_bringup.c</a>
```c
// Touch Panel Interrupt (CTP-INT) is at PH4
define CTP_INT (PIO_EINT | PIO_PORT_PIOH | PIO_PIN4)
// Register the Interrupt Handler for Touch Panel
void touch_panel_initialize(void) {
// Attach the PIO Interrupt Handler for Port PH
if (irq_attach(A64_IRQ_PH_EINT, touch_panel_interrupt, NULL) < 0) {
_err("irq_attach failed\n");
return ERROR;
}
// Enable the PIO Interrupt for Port PH
up_enable_irq(A64_IRQ_PH_EINT);
// Configure the Touch Panel Interrupt
int ret = a64_pio_config(CTP_INT);
DEBUGASSERT(ret == 0);
// Enable the Touch Panel Interrupt
ret = a64_pio_irqenable(CTP_INT);
DEBUGASSERT(ret == 0);
}
// Interrupt Handler for Touch Panel
static int touch_panel_interrupt(int irq, void <em>context, void </em>arg) {
// Print something when interrupt is triggered
up_putc('.');
return OK;
}
```
When we run this code, it generates a non-stop stream of "." characters.
Which means that the Touch Input Interrupt is generated continuously. Without touching the screen!
<em>Is our Interrupt Handler code correct?</em>
Yep our Interrupt Handler code is correct! But through our experiments we discovered one thing...
To stop the repeated Touch Input Interrupts, we need to set the <strong>Touch Panel Status to 0</strong>! Like so: <a>pinephone_bringup.c</a>
```c
// When the Touch Input Interrupt is triggered...
// Set the Touch Panel Status to 0
touch_panel_set_status(i2c, 0);
...
define GOODIX_READ_COORD_ADDR 0x814E // Touch Panel Status (Read / Write)
define CTP_FREQ 400000 // I2C Frequency: 400 kHz
define CTP_I2C_ADDR 0x5d // Default I2C Address for Goodix GT917S
// Set the Touch Panel Status
static int touch_panel_set_status(
struct i2c_master_s *i2c, // I2C Bus
uint8_t status // Status value to be set
) {
uint16_t reg = GOODIX_READ_COORD_ADDR; // I2C Register
uint32_t freq = CTP_FREQ; // 400 kHz
uint16_t addr = CTP_I2C_ADDR; // Default I2C Address for Goodix GT917S
uint8_t buf[3] = {
reg >> 8, // Swap the bytes
reg & 0xff, // Swap the bytes
status
};
// Compose the I2C Message
struct i2c_msg_s msgv[1] =
{
{
.frequency = freq,
.addr = addr,
.flags = 0,
.buffer = buf,
.length = sizeof(buf)
}
};
// Execute the I2C Transfer
const int msgv_len = sizeof(msgv) / sizeof(msgv[0]);
int ret = I2C_TRANSFER(i2c, msgv, msgv_len);
if (ret < 0) { _err("I2C Error: %d\n", ret); return ret; }
return OK;
}
```
<em>So we set the Touch Panel Status inside our Interrupt Handler?</em>
But Interrupt Handlers aren't allowed to make I2C Calls!
We need to <strong>forward the Interrupt</strong> to a Background Thread to handle. Like so: <a>pinephone_bringup.c</a>
```c
// Interrupt Handler for Touch Panel
static int gt9xx_isr_handler(int irq, FAR void <em>context, FAR void </em>arg)
{
FAR struct gt9xx_dev_s <em>priv = (FAR struct gt9xx_dev_s </em>)arg;
// Set the Interrupt Pending Flag
irqstate_t flags = enter_critical_section();
priv->int_pending = true;
leave_critical_section(flags);
// Notify the Poll Waiters
poll_notify(priv->fds, GT9XX_NPOLLWAITERS, POLLIN);
return 0;
}
```
This notifies the File Descriptors <code>fds</code> that are waiting for Touch Input Interrupts to be triggered.
When the File Descriptor is notified, the Background Thread will become unblocked, and can call I2C to read the Touch Input.
Right now we don't have a Background Thread, so we poll and wait for the Touch Input Interrupt to be triggered: <a>pinephone_bringup.c</a>
```c
// Poll for Touch Panel Interrupt
// TODO: Move this
for (int i = 0; i < 6000; i++) { // Poll for 60 seconds
<code>// If Touch Panel Interrupt has been triggered...
if (priv->int_pending) {
// Read the Touch Panel over I2C
touch_panel_read(i2c_dev);
// Reset the Interrupt Pending Flag
priv->int_pending = false;
}
// Wait a while
up_mdelay(10); // 10 milliseconds
</code>
}
```
And it works!
<code>text
- Ready to Boot CPU
- Boot from EL2
- Boot from EL1
- Boot to C runtime for OS Initialize
a64_pio_config: cfgaddr=0x1c208fc, intaddr=0x1c20a40, value=0x0, shift=16
touch_panel_initialize: v=0x10, m=0x10, a=0x1c20a50
buf (0x40a8fd20):
0000 39 31 37 53 917S
buf (0x40a8fd10):
0000 81 .
buf (0x40a8fd28):
0000 19 01 e6 02 2a 00 ....*.
touch_panel_read: touch x=281, y=742
...
buf (0x40a8fd20):
0000 39 31 37 53 917S
buf (0x40a8fd10):
0000 81 .
buf (0x40a8fd28):
0000 81 02 33 00 25 00 ..3.%.
touch_panel_read: touch x=641, y=51
...
buf (0x40a8fd20):
0000 39 31 37 53 917S
buf (0x40a8fd10):
0000 81 .
buf (0x40a8fd28):
0000 0f 00 72 05 14 00 ..r...
touch_panel_read: touch x=15, y=1394</code>
<a>(Source)</a>
Let's move this code into the NuttX Touch Panel Driver for PinePhone...
NuttX Touch Panel Driver for PinePhone
We moved the code above into the NuttX Touch Panel Driver for PinePhone...
<ul>
<li><a>drivers/input/gt9xx.c</a></li>
</ul>
This is how we start the driver when NuttX boots: <a>pinephone_bringup.c</a>
```c
define CTP_I2C_ADDR 0x5d // Default I2C Address for Goodix GT917S
ret = gt9xx_register("/dev/input0", i2c, CTP_I2C_ADDR, &g_pinephone_gt9xx);
```
And it works with the LVGL Demo App!
<ul>
<li><a>Watch the Demo on YouTube</a></li>
</ul>
Read the article...
<ul>
<li><a>"NuttX RTOS for PinePhone: Touch Panel"</a></li>
</ul>
LVGL Terminal for NuttX
Read the article...
<ul>
<li><a>"NuttX RTOS for PinePhone: LVGL Terminal for NSH Shell"</a></li>
</ul>
Let's create a Terminal App in LVGL, that will let us interact with the NuttX NSH Shell...
<ul>
<li>
<a>Watch the Demo on YouTube</a>
</li>
<li>
<a>Source Code: lvglterm.c</a>
</li>
<li>
<a>How to compile LVGL Terminal</a>
</li>
<li>
<a>Download the NuttX Image for PinePhone</a>
</li>
</ul>
We begin by starting the NSH Task and piping a command to NSH Shell...
Pipe a Command to NuttX NSH Shell
Our LVGL Terminal App needs to...
<ol>
<li>
Start the NuttX Task for NSH Shell
</li>
<li>
Redirect the NSH Console Input / Output to LVGL
</li>
</ol>
Here's a simple test that starts the NSH Task and sends a command to NSH Console via a POSIX Pipe: <a>lvgldemo.c</a>
```c
void test_terminal(void) {
// Create the pipes
int nsh_stdin[2];
int nsh_stdout[2];
int nsh_stderr[2];
int ret;
ret = pipe(nsh_stdin); if (ret < 0) { _err("stdin pipe failed: %d\n", errno); return; }
ret = pipe(nsh_stdout); if (ret < 0) { _err("stdout pipe failed: %d\n", errno); return; }
ret = pipe(nsh_stderr); if (ret < 0) { _err("stderr pipe failed: %d\n", errno); return; }
// Close default stdin, stdout and stderr
close(0);
close(1);
close(2);
// Use the pipes as stdin, stdout and stderr
#define READ_PIPE 0 // Read Pipes: stdin, stdout, stderr
#define WRITE_PIPE 1 // Write Pipes: stdin, stdout, stderr
dup2(nsh_stdin[READ_PIPE], 0);
dup2(nsh_stdout[WRITE_PIPE], 1);
dup2(nsh_stderr[WRITE_PIPE], 2);
// Create a new NSH Task using the pipes
char *argv[] = { NULL };
pid_t pid = task_create(
"NSH Console",
100, // Priority
CONFIG_DEFAULT_TASK_STACKSIZE,
nsh_consolemain,
argv
);
if (pid < 0) { _err("task_create failed: %d\n", errno); return; }
_info("pid=%d\n", pid);
// Wait a while
sleep(1);
// Send a few commands to NSH
for (int i = 0; i < 5; i++) {
<code>// Send a command to NSH stdin
const char cmd[] = "ls\r";
ret = write(
nsh_stdin[WRITE_PIPE],
cmd,
sizeof(cmd)
);
_info("write nsh_stdin: %d\n", ret);
// Wait a while
sleep(1);
// Read the output from NSH stdout.
// TODO: This will block if there's nothing to read.
static char buf[64];
ret = read(
nsh_stdout[READ_PIPE],
buf,
sizeof(buf) - 1
);
if (ret > 0) { buf[ret] = 0; _info("%s\n", buf); }
// Wait a while
sleep(1);
</code>
ifdef NOTUSED
<code>// Read the output from NSH stderr.
// TODO: This will block if there's nothing to read.
ret = read(
nsh_stderr[READ_PIPE],
buf,
sizeof(buf) - 1
);
if (ret > 0) { buf[ret] = 0; _info("%s\n", buf); }
</code>
endif
}
}
```
And it works! Here's the NSH Task auto-running the <code>ls</code> Command received via our Pipe...
<code>text
NuttShell (NSH) NuttX-12.0.0
nsh> ls
/:
dev/
var/
nsh> est_terminal: write nsh_stdin: 9
test_terminal: read nsh_stdout: 63
test_terminal: K
...
nsh> ls
/:
dev/
var/
test_terminal: write nsh_stdin: 9
test_terminal: read nsh_stdout: 63
test_terminal:
...</code>
<a>(See the Complete Log)</a>
There's a problem with the code above... Calling <code>read()</code> on <code>nsh_stdout</code> will block if there's no NSH Output to be read.
Let's call <code>poll()</code> on <code>nsh_stdout</code> to check if there's NSH Output to be read...
Poll for NSH Output
In the previous sections we started an NSH Shell that will execute NSH Commands that we pipe to it.
But there's a problem: Calling <code>read()</code> on <code>nsh_stdout</code> will block if there's no NSH Output to be read. And we can't block our LVGL App, since it needs to handle UI Events periodically.
Solution: We call <code>has_input</code> to check if there's NSH Output ready to be read, before reading the output: <a>lvgldemo.c</a>
```c
// Read the output from NSH stdout
static char buf[64];
if (has_input(nsh_stdout[READ_PIPE])) {
ret = read(
nsh_stdout[READ_PIPE],
buf,
sizeof(buf) - 1
);
if (ret > 0) { buf[ret] = 0; _info("%s\n", buf); }
}
// Read the output from NSH stderr
if (has_input(nsh_stderr[READ_PIPE])) {
ret = read(
nsh_stderr[READ_PIPE],
buf,
sizeof(buf) - 1
);
if (ret > 0) { buf[ret] = 0; _info("%s\n", buf); }
}
```
<code>has_input</code> calls <code>poll()</code> on <code>nsh_stdout</code> to check if there's NSH Output ready to be read: <a>lvgldemo.c</a>
```c
// Return true if the File Descriptor has data to be read
static bool has_input(int fd) {
// Poll the File Descriptor for Input
struct pollfd fdp;
fdp.fd = fd;
fdp.events = POLLIN;
int ret = poll(
(struct pollfd *)&fdp, // File Descriptors
1, // Number of File Descriptors
0 // Poll Timeout (Milliseconds)
);
if (ret > 0) {
// If Poll is OK and there is Input...
if ((fdp.revents & POLLIN) != 0) {
// Report that there's Input
_info("has input: fd=%d\n", fd);
return true;
}
<code>// Else report No Input
_info("no input: fd=%d\n", fd);
return false;
</code>
} else if (ret == 0) {
// Ignore Timeout
_info("timeout: fd=%d\n", fd);
return false;
} else if (ret < 0) {
// Handle Error
_err("poll failed: %d, fd=%d\n", ret, fd);
return false;
}
// Never comes here
DEBUGASSERT(false);
return false;
}
```
<code>has_input</code> returns True if there's NSH Output waiting to be read...
<code>text
has_input: has input: fd=8</code>
And <code>has_input</code> returns False (due to timeout) if there's nothing waiting to be read...
<code>text
has_input: timeout: fd=8</code>
<a>(See the Complete Log)</a>
This polling needs to be done in an LVGL Timer, here's why...
Timer for LVGL Terminal
In the previous sections we started an NSH Shell that will execute NSH Commands that we pipe to it.
Our LVGL Terminal for NSH Shell shall periodically check for output from the NSH Shell, and write the output to the LVGL Display...
<ul>
<li>
Every couple of milliseconds...
<ul>
<li>
We call <code>poll()</code> to check if NSH Shell has output data
</li>
<li>
We read the output from NSH Shell
</li>
<li>
We display the NSH Output in an LVGL Label Widget
</li>
</ul>
</li>
</ul>
We'll do this with an <a>LVGL Timer</a> like so: <a>lvgldemo.c</a>
```c
// Create an LVGL Terminal that will let us interact with NuttX NSH Shell
void test_terminal(void) {
// Create an LVGL Timer to poll for output from NSH Shell
static uint32_t user_data = 10;
lv_timer_t *timer = lv_timer_create(
my_timer, // Callback
5000, // Timer Period (Milliseconds)
&user_data // Callback Data
);
```
<code>my_timer</code> is our Timer Callback Function: <a>lvgldemo.c</a>
```c
// Callback for LVGL Timer
void my_timer(lv_timer_t *timer) {
// Get the Callback Data
uint32_t <em>user_data = timer->user_data;
_info("my_timer called with callback data: %d\n", </em>user_data);
*user_data += 1;
// TODO: Call poll() to check if NSH Stdout has output to be read
// TODO: Read the NSH Stdout
// TODO: Write the NSH Output to LVGL Label Widget
}
```
When we run this, LVGL calls our Timer Callback Function every 5 seconds...
<code>text
my_timer: my_timer called with callback data: 10
my_timer: my_timer called with callback data: 11
my_timer: my_timer called with callback data: 12</code>
<a>(See the Complete Log)</a>
<em>Why poll for NSH Output? Why not run a Background Thread that will block on NSH Output?</em>
If we ran a Background Thread that will block until NSH Output is available, we still need to write the NSH Output to an LVGL Widget for display.
But LVGL is NOT Thread-Safe. Thus we need a Mutex to lock the LVGL Widgets, which gets messy.
For now, it's simpler to run an LVGL Timer to poll for NSH Output.
Let's add the polling to the LVGL Timer Callback...
Poll for NSH Output in LVGL Timer
In the previous section we've created an LVGL Timer that's triggered periodically.
Inside the LVGL Timer Callback, let's poll the NSH Output and check if there's any output to be read: <a>lvgldemo.c</a>
```c
// Callback for LVGL Timer
static void my_timer(lv_timer_t *timer) {
...
// Read the output from NSH stdout
static char buf[64];
DEBUGASSERT(nsh_stdout[READ_PIPE] != 0);
if (has_input(nsh_stdout[READ_PIPE])) {
ret = read(
nsh_stdout[READ_PIPE],
buf,
sizeof(buf) - 1
);
_info("read nsh_stdout: %d\n", ret);
if (ret > 0) { buf[ret] = 0; _info("%s\n", buf); }
}
// Read the output from NSH stderr
DEBUGASSERT(nsh_stderr[READ_PIPE] != 0);
if (has_input(nsh_stderr[READ_PIPE])) {
ret = read(
nsh_stderr[READ_PIPE],
buf,
sizeof(buf) - 1
);
_info("read nsh_stderr: %d\n", ret);
if (ret > 0) { buf[ret] = 0; _info("%s\n", buf); }
}
// TODO: Write the NSH Output to LVGL Label Widget
```
NSH won't emit any output until we run some NSH Commands. So let's trigger some NSH Commands inside the LVGL Timer Callback: <a>lvgldemo.c</a>
```c
// Callback for LVGL Timer
static void my_timer(lv_timer_t *timer) {
// Get the Callback Data
uint32_t <em>user_data = timer->user_data;
_info("my_timer called with callback data: %d\n", </em>user_data);
*user_data += 1;
// Send a command to NSH stdin
if (*user_data % 5 == 0) {
const char cmd[] = "ls\r";
DEBUGASSERT(nsh_stdin[WRITE_PIPE] != 0);
ret = write(
nsh_stdin[WRITE_PIPE],
cmd,
sizeof(cmd)
);
_info("write nsh_stdin: %d\n", ret);
}
// Read the output from NSH stdout
...
```
When we run this, we see the LVGL Timer Callback sending NSH Commands and printing the NSH Output...
<code>text
my_timer: my_timer called with callback data: 10
has_input: has input: fd=8
my_timer: read nsh_stdout: 63
my_timer: createWidgetsWrapped: start
createWidgetsWrapped: end
NuttShel
has_input: timeout: fd=10
my_timer: my_timer called with callback data: 11
has_input: has input: fd=8
my_timer: read nsh_stdout: 29
my_timer: l (NSH) NuttX-12.0.0
nsh>
has_input: timeout: fd=10
my_timer: my_timer called with callback data: 12
has_input: timeout: fd=8
has_input: timeout: fd=10
my_timer: my_timer called with callback data: 13
has_input: timeout: fd=8
has_input: timeout: fd=10
my_timer: my_timer called with callback data: 14
my_timer: write nsh_stdin: 4
has_input: timeout: fd=8
has_input: timeout: fd=10
my_timer: my_timer called with callback data: 15
has_input: has input: fd=8
my_timer: read nsh_stdout: 33
my_timer: ls
/:
dev/
proc/
var/
nsh></code>
<a>(See the Complete Log)</a>
Now that our background processing is ready, let's render the LVGL Widgets for our terminal...
Render Terminal with LVGL Widgets
Our LVGL Terminal will have 3 LVGL Widgets...
<ul>
<li>
<a>LVGL Text Area Widget</a> that shows the NSH Output
(At the top)
</li>
<li>
<a>LVGL Text Area Widget</a> for NSH Input, to enter commands
(At the middle)
</li>
<li>
<a>LVGL Keyboard Widget</a> for typing commands into NSH Input
(At the bottom)
</li>
</ul>
This is how we render the 3 LVGL Widgets: <a>lvgldemo.c</a>
```c
// PinePhone LCD Panel Width and Height (pixels)
define PINEPHONE_LCD_PANEL_WIDTH 720
define PINEPHONE_LCD_PANEL_HEIGHT 1440
// Margin of 10 pixels all around
define TERMINAL_MARGIN 10
// Terminal Width is LCD Width minus Left and Right Margins
define TERMINAL_WIDTH (PINEPHONE_LCD_PANEL_WIDTH - 2 * TERMINAL_MARGIN)
// Keyboard is Lower Half of LCD.
// Terminal Height is Upper Half of LCD minus Top and Bottom Margins.
define TERMINAL_HEIGHT ((PINEPHONE_LCD_PANEL_HEIGHT / 2) - 2 * TERMINAL_MARGIN)
// Height of Input Text Area
define INPUT_HEIGHT 100
// Height of Output Text Area is Terminal Height minus Input Height minus Middle Margin
define OUTPUT_HEIGHT (TERMINAL_HEIGHT - INPUT_HEIGHT - TERMINAL_MARGIN)
// Create the LVGL Widgets for the LVGL Terminal.
// Based on https://docs.lvgl.io/master/widgets/keyboard.html#keyboard-with-text-area
static void create_widgets(void) {
// Create an LVGL Keyboard Widget
lv_obj_t *kb = lv_keyboard_create(lv_scr_act());
// Create an LVGL Text Area Widget for NSH Output
output = lv_textarea_create(lv_scr_act());
lv_obj_align(output, LV_ALIGN_TOP_LEFT, TERMINAL_MARGIN, TERMINAL_MARGIN);
lv_textarea_set_placeholder_text(output, "Hello");
lv_obj_set_size(output, TERMINAL_WIDTH, OUTPUT_HEIGHT);
// Create an LVGL Text Area Widget for NSH Input
input = lv_textarea_create(lv_scr_act());
lv_obj_align(input, LV_ALIGN_TOP_LEFT, TERMINAL_MARGIN, OUTPUT_HEIGHT + 2 * TERMINAL_MARGIN);
lv_obj_add_event_cb(input, input_callback, LV_EVENT_ALL, kb);
lv_obj_set_size(input, TERMINAL_WIDTH, INPUT_HEIGHT);
// Set the Keyboard to populate the NSH Input Text Area
lv_keyboard_set_textarea(kb, input);
}
```
<code>input_callback</code> is the Callback Function for our LVGL Keyboard. Which we'll cover in a while.
Note that we're using the LVGL Default Font for all 3 LVGL Widgets. Which has a problem...
Set LVGL Terminal Font to Monospace
Our LVGL Terminal looks nicer with a Monospace Font.
But watch what happens if we change the LVGL Default Font from Montserrat 20 (proportional) to UNSCII 16 (monospace)...
The LVGL Keyboard has missing symbols! Enter, Backspace, ...
Thus we set the LVGL Default Font back to Montserrat 20.
And instead we set the Font Style for NSH Input and Output to UNSCII 16: <a>lvgldemo.c</a>
```c
// Set the Font Style for NSH Input and Output to a Monospaced Font
static lv_style_t terminal_style;
lv_style_init(&terminal_style);
lv_style_set_text_font(&terminal_style, &lv_font_unscii_16);
// Create an LVGL Text Area Widget for NSH Output
output = lv_textarea_create(lv_scr_act());
lv_obj_add_style(output, &terminal_style, 0);
...
// Create an LVGL Text Area Widget for NSH Input
input = lv_textarea_create(lv_scr_act());
lv_obj_add_style(input, &terminal_style, 0);
...
```
Now we see the LVGL Keyboard without missing symbols (pic below)...
<ul>
<li><a>Watch the Demo on YouTube</a></li>
</ul>
Let's look at our Callback Function for the LVGL Keyboard...
Handle Input from LVGL Keyboard
Here's the Callback Function that handles input from the LVGL Keyboard.
It waits for the Enter key to be pressed, then it sends the typed command to NSH Shell via a POSIX Pipe: <a>lvgldemo.c</a>
```c
// Callback Function for NSH Input Text Area.
// Based on https://docs.lvgl.io/master/widgets/keyboard.html#keyboard-with-text-area
static void input_callback(lv_event_t *e) {
int ret;
// Decode the LVGL Event
const lv_event_code_t code = lv_event_get_code(e);
// If Enter has been pressed, send the Command to NSH Input
if (code == LV_EVENT_VALUE_CHANGED) {
<code>// Get the Keyboard Widget from the LVGL Event
const lv_obj_t *kb = lv_event_get_user_data(e);
DEBUGASSERT(kb != NULL);
// Get the Button Index of the Keyboard Button Pressed
const uint16_t id = lv_keyboard_get_selected_btn(kb);
// Get the Text of the Keyboard Button
const char *key = lv_keyboard_get_btn_text(kb, id);
if (key == NULL) { return; }
// If Enter is pressed...
if (key[0] == 0xef && key[1] == 0xa2 && key[2] == 0xa2) {
// Read the NSH Input
DEBUGASSERT(input != NULL);
const char *cmd = lv_textarea_get_text(input);
if (cmd == NULL || cmd[0] == 0) { return; }
// Send the Command to NSH stdin
DEBUGASSERT(nsh_stdin[WRITE_PIPE] != 0);
ret = write(
nsh_stdin[WRITE_PIPE],
cmd,
strlen(cmd)
);
// Erase the NSH Input
lv_textarea_set_text(input, "");
}
</code>
}
}
```
The command runs in NSH Shell and produces NSH Output. Which is handled by the LVGL Timer Callback Function...
Handle Output from NSH Shell
Our LVGL Timer Callback Function checks periodically whether there's any NSH Output waiting to be processed.
If there's NSH Output, the Callback Function writes the output to the NSH Output Text Area:
<a>lvgldemo.c</a>
```c
// Callback Function for LVGL Timer.
// Based on https://docs.lvgl.io/master/overview/timer.html#create-a-timer
static void timer_callback(lv_timer_t *timer) {
// Read the output from NSH stdout
static char buf[64];
DEBUGASSERT(nsh_stdout[READ_PIPE] != 0);
if (has_input(nsh_stdout[READ_PIPE])) {
ret = read(
nsh_stdout[READ_PIPE],
buf,
sizeof(buf) - 1
);
if (ret > 0) {
// Add to NSH Output Text Area
buf[ret] = 0;
remove_escape_codes(buf, ret);
DEBUGASSERT(output != NULL);
lv_textarea_add_text(output, buf);
}
}
```
<code>remove_escape_codes</code> searches for Escape Codes in the NSH Output and replaces them by spaces.
That's why we see 3 spaces between the <code>nsh></code> prompt and the NSH Command. (Pic below)
For more details, check out the article...
<ul>
<li><a>"NuttX RTOS for PinePhone: LVGL Terminal for NSH Shell"</a></li>
</ul>
PinePhone on NuttX becomes a Feature Phone
<em>Now that NuttX can run Touchscreen Apps on PinePhone... What next?</em>
Maybe we can turn NuttX on PinePhone into a <strong>Feature Phone</strong>?
Just <strong>Voice Calls and SMS</strong>, using PinePhone's LTE Modem.
<em>This is useful because...?</em>
So we can pop a microSD Card (and SIM) into any PinePhone...
And turn it instantly into an <strong>Emergency Phone</strong>?
<em>What NuttX Drivers would we need?</em>
We need a NuttX Driver for the PinePhone's <strong>Quectel LTE Modem</strong>.
Which talks over USB Serial. Thus we also need a NuttX Driver for PinePhone's <strong>Allwinner A64 USB Controller</strong>.
More about this in the next section.
<em>And if there's no LTE Network Coverage? Like in a Natural Disaster?</em>
The Long-Range, Low-Power <strong>LoRa Network</strong> might be good for search and rescue communications.
(Short Text Messages only plus GPS Geolocation, non-guaranteed message delivery)
Just attach the LoRa Case to PinePhone...
<ul>
<li>
<a>PineDio LoRa Add-On Case</a>
(Still in stock!)
</li>
</ul>
We might use JF's Driver...
<ul>
<li><a>JF002/pinedio-lora-driver</a></li>
</ul>
Or the LoRa Driver that we have ported to NuttX...
<ul>
<li><a>"LoRa SX1262 on Apache NuttX RTOS"</a></li>
</ul>
Or maybe Meshtastic (with Portduino), since it has a complete LoRa Messaging App...
<ul>
<li>
<a>Meshtastic</a>
</li>
<li>
<a>Portduino</a>
</li>
</ul>
<em>Will PinePhone on NuttX become a fully-functional smartphone?</em>
Maybe someday? We're still lacking plenty of drivers: WiFi, Bluetooth LE, GPS, Audio, ...
Probably better to start as a Feature Phone (or LoRa Communication) and build up.
USB Driver and LTE Modem Driver for PinePhone
Read the articles...
<ul>
<li>
<a>"NuttX RTOS for PinePhone: Exploring USB"</a>
</li>
<li>
<a>"NuttX RTOS for PinePhone: Simpler USB with EHCI (Enhanced Host Controller Interface)"</a>
</li>
<li>
<a>"NuttX RTOS for PinePhone: 4G LTE Modem"</a>
</li>
<li>
<a>"NuttX RTOS for PinePhone: Phone Calls and Text Messages"</a>
</li>
</ul>
<em>What NuttX Drivers would we need to turn PinePhone into a Feature Phone? (Voice Calls and SMS only)</em>
We need a NuttX Driver for the PinePhone's <strong>Quectel LTE Modem</strong>...
Which talks over USB Serial. Thus we also need a NuttX Driver for PinePhone's <strong>Allwinner A64 USB Controller</strong>.
Here are the docs for Allwinner A64 USB Controller...
<ul>
<li>
<a>Allwinner A64 User Manual</a>, Section 7.5 "USB" (Page 583)
</li>
<li>
<a>Allwinner A20 User Manual</a>, Section 6.7 "USB DRD" (Page 682), Section 6.8 "USB Host" (Page 683)
</li>
<li>
<a>Allwinner USB OTG Controller Register Guide</a>
</li>
<li>
<a>Mentor Graphics MUSBMHDRC USB 2.0 Multi-Point Dual-Role Controller: Product Specification and Programming Guide</a>
</li>
</ul>
<em>Any sample code for Allwinner A64 USB?</em>
Refer to the Allwinner A64 USB Drivers in FreeBSD and NetBSD...
<ul>
<li>
<a>freebsd/sys/dev/usb/controller/musb_otg_allwinner.c</a>
<a>freebsd/sys/dev/usb/controller/musb_otg.c</a>
<a>freebsd/sys/arm/allwinner/aw_usbphy.c</a>
</li>
<li>
<a>NetBSD/sys/arch/arm/sunxi/sunxi_musb.c</a>
<a>NetBSD/sys/arch/arm/sunxi/sunxi_usbphy.c</a>
</li>
</ul>
<em>But Allwinner A64's Official Docs are horrigibly lacking...</em>
Maybe we refer to the <a>NXP i.MX 8 USB Docs</a>, and we compare with the FreeBSD / NetBSD USB Drivers for i.MX 8?
(Since NXP i.MX 8 is so much better documented than Allwinner A64)
<em>How do USB Drivers work in NuttX?</em>
Check out this NuttX Doc on USB Drivers...
<ul>
<li><a>"USB Host-Side Drivers"</a></li>
</ul>
And the NuttX USB Driver for STM32...
<ul>
<li>
<a>stm32_otgfshost.c</a>
</li>
<li>
<a>stm32_otgfsdev.c</a>
</li>
<li>
<a>stm32_usbfs.c</a>
</li>
<li>
<a>stm32_usbhost.c</a>
</li>
</ul>
(USB OTG FS: Able to act as a device/host/OTG peripheral, at full speed 12Mbps)
(USB OTG HS: Able to act as a device/host/OTG peripheral, at full speed 12Mbps or high speed 480Mbps)
<em>How did we get the FreeBSD and NetBSD USB Drivers for Allwinner A64?</em>
PinePhone's Device Tree says that the USB Drivers are...
<code>text
usb@1c19000 {
compatible = "allwinner,sun8i-a33-musb";
...
phy@1c19400 {
compatible = "allwinner,sun50i-a64-usb-phy";</code>
So we searched for <code>allwinner,sun8i-a33-musb</code> and <code>allwinner,sun50i-a64-usb-phy</code>.
Here's the PinePhone USB Device Tree: <a>sun50i-a64-pinephone-1.2.dts</a>
```text
usb@1c19000 {
compatible = "allwinner,sun8i-a33-musb";
reg = <0x1c19000 0x400>;
clocks = <0x02 0x29>;
resets = <0x02 0x12>;
interrupts = <0x00 0x47 0x04>;
interrupt-names = "mc";
phys = <0x31 0x00>;
phy-names = "usb";
extcon = <0x31 0x00>;
dr_mode = "otg";
status = "okay";
};
phy@1c19400 {
compatible = "allwinner,sun50i-a64-usb-phy";
reg = <0x1c19400 0x14 0x1c1a800 0x04 0x1c1b800 0x04>;
reg-names = "phy_ctrl\0pmu0\0pmu1";
clocks = <0x02 0x56 0x02 0x57>;
clock-names = "usb0_phy\0usb1_phy";
resets = <0x02 0x00 0x02 0x01>;
reset-names = "usb0_reset\0usb1_reset";
status = "okay";
#phy-cells = <0x01>;
usb-role-switch;
phandle = <0x31>;
port {
<code>endpoint {
remote-endpoint = <0x32>;
phandle = <0x47>;
};
</code>
};
};
usb@1c1a000 {
compatible = "allwinner,sun50i-a64-ehci\0generic-ehci";
reg = <0x1c1a000 0x100>;
interrupts = <0x00 0x48 0x04>;
clocks = <0x02 0x2c 0x02 0x2a 0x02 0x5b>;
resets = <0x02 0x15 0x02 0x13>;
status = "okay";
};
usb@1c1a400 {
compatible = "allwinner,sun50i-a64-ohci\0generic-ohci";
reg = <0x1c1a400 0x100>;
interrupts = <0x00 0x49 0x04>;
clocks = <0x02 0x2c 0x02 0x5b>;
resets = <0x02 0x15>;
status = "okay";
};
usb@1c1b000 {
compatible = "allwinner,sun50i-a64-ehci\0generic-ehci";
reg = <0x1c1b000 0x100>;
interrupts = <0x00 0x4a 0x04>;
clocks = <0x02 0x2d 0x02 0x2b 0x02 0x5d>;
resets = <0x02 0x16 0x02 0x14>;
phys = <0x31 0x01>;
phy-names = "usb";
status = "okay";
};
usb@1c1b400 {
compatible = "allwinner,sun50i-a64-ohci\0generic-ohci";
reg = <0x1c1b400 0x100>;
interrupts = <0x00 0x4b 0x04>;
clocks = <0x02 0x2d 0x02 0x5d>;
resets = <0x02 0x16>;
phys = <0x31 0x01>;
phy-names = "usb";
status = "okay";
};
```
4G LTE Modem
Read the article...
<ul>
<li><a>"NuttX RTOS for PinePhone: Phone Calls and Text Messages"</a></li>
</ul>
We're now upstreaming the driver for 4G LTE Modem to NuttX Mainline...
<ul>
<li><a>arm64/pinephone: Add driver for PinePhone LTE Modem (Quectel EG25-G)</a></li>
</ul>
TODO: Disable UART2 and /dev/ttyS2 so that UART3 maps neatly to /dev/ttyS3. <a>(See this)</a>
This is how we make a Phone Call and send a Text Message...
Outgoing Phone Call
Read the article...
<ul>
<li><a>"NuttX RTOS for PinePhone: Phone Calls and Text Messages"</a></li>
</ul>
This is the NuttX App that makes a Phone Call on PinePhone: <a>dial_number</a>
Here's the output...
```text
NuttShell (NSH) NuttX-12.0.3
nsh> hello
// Check Modem Status
Command: AT
Response:
RDY
+CFUN: 1
+CPIN: READY
+QUSIM: 1
+QIND: SMS DONE
// SIM and SMS are ready
// Check Network Status
Command: AT+CREG?
Response:
+CREG: 0,1
+QIND: PB DONE
// Network and Phonebook are ready
// Get Network Operator
Command: AT+COPS?
Response: +COPS: 0,0,"SGP-M1",7
// Get Range of PCM Parameters for Digital Audio
Command: AT+QDAI=?
Response: +QDAI: (1-4),(0,1),(0,1),(0-5),(0-2),(0,1)(1)(1-16)
// Get Current PCM Configuration for Digital Audio
Command: AT+QDAI?
Response: +QDAI: 1,1,0,1,0,0,1,1
// Make Outgoing Phone Call
Command: ATDyourphonenumber;
Response:
OK
// Receiver has hung up
Response:
NO CARRIER
// Hang up Phone Call
Command: ATH
Response: OK
```
<a>(See the Complete Log)</a>
<em>What does this say: <code>+QDAI: 1,1,0,1,0,0,1,1</code></em>
The above <strong>PCM Digital Audio Configuration</strong> for the LTE Modem says...
<ul>
<li><strong>io = 1</strong></li>
</ul>
Digital PCM Output
<ul>
<li><strong>mode = 1</strong></li>
</ul>
Slave Mode
<ul>
<li><strong>fsync = 0</strong></li>
</ul>
Primary Mode (short-synchronization)
<ul>
<li><strong>clock = 1</strong></li>
</ul>
Clock Frequency is 256 kHz
<ul>
<li><strong>format = 0</strong></li>
</ul>
Data Format is 16-bit linear
<ul>
<li><strong>sample = 0</strong></li>
</ul>
Sampling Rate is 8 kHz
<ul>
<li><strong>num_slots = 1</strong></li>
</ul>
Number of Slot is 1
<ul>
<li><strong>slot_mapping = 1</strong></li>
</ul>
Slot Mapping Value is 1
Send SMS in Text Mode
Read the article...
<ul>
<li><a>"NuttX RTOS for PinePhone: Phone Calls and Text Messages"</a></li>
</ul>
This is how we send an SMS in Text Mode: <a>send_sms_text</a>
Here's the log...
```text
// Set Message Format to Text Mode
Command: AT+CMGF=1
Response: OK
// Set Character Set to GSM
Command: AT+CSCS="GSM"
Response: OK
// Send an SMS to the Phone Number.
// yourphonenumber looks like +1234567890
// Works without country code, like 234567890
Command:
AT+CMGS="yourphonenumber"
// We wait for Modem to respond with ">"
Response:
<blockquote></blockquote>
// SMS Message in Text Format, terminate with Ctrl-Z
Command:
Hello from Apache NuttX RTOS on PinePhone! (SMS Text Mode)
// Modem sends the SMS Message
Response:
+CMGS: 13
OK
```
<a>(See the Complete Log)</a>
<em>Why do we get Error 350 sometimes? (Rejected by SMSC)</em>
<code>text
+CMS ERROR: 350</code>
Check with the telco. I got this error when the telco blocked my outgoing SMS messages.
Send SMS in PDU Mode
Read the article...
<ul>
<li><a>"NuttX RTOS for PinePhone: Phone Calls and Text Messages"</a></li>
</ul>
Now we send an SMS Message in PDU Mode. Based on...
<ul>
<li>
<a>Quectel GSM AT Commands Application Note</a>, Section 9.3.2 "Send SMS in PDU mode", Page 26
</li>
<li>
<a>ETSI GSM 07.05 Spec</a> (AT Commands)
</li>
<li>
<a>ETSI GSM 03.40 Spec</a> (PDU Format)
</li>
</ul>
This is how we send an SMS in PDU Mode: <a>send_sms_pdu</a>
Suppose we're sending an SMS to this Phone Number (International Format)...
```text
define PHONE_NUMBER "+1234567890"
define PHONE_NUMBER_PDU "2143658709"
```
Note that we flip the nibbles (half-bytes) from the Original Phone Number to produce the PDU Phone Number.
If the number of nibbles (half-bytes) is odd, insert "F" into the PDU Phone Number like this...
```text
define PHONE_NUMBER "+123456789"
define PHONE_NUMBER_PDU "214365870F9"
```
Assuming there are 10 decimal digits in our Phone Number "+1234567890", here's the AT Command...
<code>text
// Send SMS Command
const char cmd[] =
"AT+CMGS="
"41" // TODO: PDU Length in bytes, excluding the Length of SMSC
"\r";</code>
(We'll talk about PDU Length in a while)
And here's the SMS Message PDU that we'll send in the AT Command...
<code>text
// SMS Message in PDU Format
const char cmd[] =
"00" // Length of SMSC information (None)
"11" // SMS-SUBMIT message
"00" // TP-Message-Reference: 00 to let the phone set the message reference number itself
"0A" // TODO: Address-Length: Length of phone number (Number of Decimal Digits in Phone Number)
"91" // Type-of-Address: 91 for International Format of phone number
PHONE_NUMBER_PDU // TODO: Phone Number in PDU Format
"00" // TP-PID: Protocol identifier
"08" // TP-DCS: Data coding scheme
"01" // TP-Validity-Period
"1C" // TP-User-Data-Length: Length of Encoded Message Text in bytes
// TP-User-Data: Encoded Message Text "Hello,Quectel!"
"00480065006C006C006F002C005100750065006300740065006C0021"
"\x1A"; // End of Message (Ctrl-Z)</code>
(We'll talk about Encoded Message Text in a while)
(Remember to update "Address-Length" according to your phone number)
Here's the log...
```text
// Set Message Format to PDU Mode
Command: AT+CMGF=0
Response: OK
// Send an SMS with 41 bytes (excluding SMSC)
Command: AT+CMGS=41
// We wait for Modem to respond with ">"
Response: >
// SMS Message in PDU Format, terminate with Ctrl-Z.
// yourphonenumberpdu looks like 2143658709, which represents +1234567890
// Country Code is mandatory. Remember to insert "F" for odd number of nibbles.
Command:
0011000A91yourphonenumberpdu0008011C00480065006C006C006F002C005100750065006300740065006C0021
// Modem sends the SMS Message
Response:
+CMGS: 14
OK
```
<a>(See the Complete Log)</a>
Let's talk about the SMS PDU...
SMS PDU Format
Read the article...
<ul>
<li><a>"NuttX RTOS for PinePhone: Phone Calls and Text Messages"</a></li>
</ul>
<em>What's the PDU Length?</em>
Our SMS Message PDU has 42 total bytes...
<code>text
"00" // Length of SMSC information (None)
"11" // SMS-SUBMIT message
"00" // TP-Message-Reference: 00 to let the phone set the message reference number itself
"0A" // TODO: Address-Length: Length of phone number (Assume 10 Decimal Digits in Phone Number)
"91" // Type-of-Address: 91 for International Format of phone number
PHONE_NUMBER_PDU // TODO: Assume 5 bytes in PDU Phone Number (10 Decimal Digits)
"00" // TP-PID: Protocol identifier
"08" // TP-DCS: Data coding scheme
"01" // TP-Validity-Period
"1C" // TP-User-Data-Length: Length of Encoded Message Text in bytes
// TP-User-Data: Assume 28 bytes in Encoded Message Text
"00480065006C006C006F002C005100750065006300740065006C0021"</code>
PDU Length excludes the SMSC Information (First Byte).
Thus our PDU Length is 41 bytes...
<code>text
// Send SMS Command
const char cmd[] =
"AT+CMGS="
"41" // TODO: PDU Length in bytes, excluding the Length of SMSC
"\r";</code>
Remember to update the PDU Length according to your phone number and message text.
<em>What do the fields mean?</em>
<code>text
"00" // Length of SMSC information (None)
"11" // SMS-SUBMIT message
"00" // TP-Message-Reference: 00 to let the phone set the message reference number itself
"0A" // TODO: Address-Length: Length of phone number (Assume 10 Decimal Digits in Phone Number)
"91" // Type-of-Address: 91 for International Format of phone number
PHONE_NUMBER_PDU // TODO: Assume 5 bytes in PDU Phone Number (10 Decimal Digits)
"00" // TP-PID: Protocol identifier
"08" // TP-DCS: Data coding scheme
"01" // TP-Validity-Period
"1C" // TP-User-Data-Length: Length of Encoded Message Text in bytes
// TP-User-Data: Assume 28 bytes in Encoded Message Text
"00480065006C006C006F002C005100750065006300740065006C0021"</code>
<ul>
<li>Length of SMSC information: "00"</li>
</ul>
We use the default SMS Centre (SMSC), so the SMSC Info Length is 0.
<ul>
<li>SM-TL (Short Message Transfer Protocol) TPDU (Transfer Protocol Data Unit) is SMS-SUBMIT Message: "11"</li>
</ul>
<a>(GSM 03.40, TPDU Fields)</a>
TP-Message-Type-Indicator (TP-MTI, Bits 0 and 1) is <code>0b01</code> (SMS-SUBMIT):
<ul>
<li>
Submit a message to SMSC for transmission.
<a>(GSM 03.40, TPDU Types)</a>
</li>
</ul>
TP-Validity-Period-Format (TP-VPF, Bits 3 and 4) is <code>0b10</code> (Relative Format):
<ul>
<li>
Message Validity Period is in Relative Format.
<a>(GSM 03.40, Validity Period)</a>
Value of Message Validity Period is in TP-Validity-Period below.
</li>
<li>
TP-Message-Reference (TP-MR): "00"
</li>
</ul>
"00" will let the phone generate the Message Reference Number itself
<a>(GSM 03.40, Message Reference)</a>
<ul>
<li>Address-Length: "0A"</li>
</ul>
Length of phone number (Number of Decimal Digits in Phone Number, excluding "F")
<a>(GSM 03.40, Addresses)</a>
<ul>
<li>Type-of-Address: "91"</li>
</ul>
91 for International Format of phone number
Numbering Plan Identification (NPI, Bits 0 to 3) = <code>0b0001</code> (ISDN / Telephone Numbering Plan)
Type Of Number (TON, Bits 4 to 6) = <code>0b001</code> (International Number)
EXT (Bit 7) = <code>1</code> (No Extension)
<a>(GSM 03.40, Addresses)</a>
<ul>
<li>PHONE_NUMBER_PDU: Phone Number in PDU Format (nibbles swapped)</li>
</ul>
Remember to insert "F" for odd number of nibbles...
<code>text
#define PHONE_NUMBER "+123456789"
#define PHONE_NUMBER_PDU "214365870F9"</code>
<a>(GSM 03.40, Address Examples)</a>
<ul>
<li>TP-Protocol-Identifier (TP-PID): "00"</li>
</ul>
Default Store-and-Forward Short Message
<a>(GSM 03.40, Protocol Identifier)</a>
<ul>
<li>TP-Data-Coding-Scheme (TP-DCS): "08"</li>
</ul>
Message Text is encoded with UCS2 Character Set
<a>(GSM 03.40, Data Coding Scheme)</a>
<a>(SMS Data Coding Scheme)</a>
<ul>
<li>TP-Validity-Period (TP-VP): "01"</li>
</ul>
Message is valid for 10 minutes, relative to current time:
(<code>"01"</code> + 1) x 5 minutes
<a>(GSM 03.40, Validity Period)</a>
(See TP-Validity-Period-Format above)
<ul>
<li>TP-User-Data-Length (TP-UDL): "1C"</li>
</ul>
Length of Encoded Message Text in bytes
<a>(GSM 03.40, Message Content)</a>
<ul>
<li>TP-User-Data (TP-UD): Encoded Message Text</li>
</ul>
Message Text is encoded with UCS2 Character Set
(Because of TP-Data-Coding-Scheme above)
<a>(GSM 03.40, Message Content)</a>
<em>How do we encode the Message Text?</em>
From above we see that the Message Text is encoded with UCS2 Character Set...
<ul>
<li>TP-Data-Coding-Scheme (TP-DCS): "08"</li>
</ul>
Message Text is encoded in UCS2 Character Set
<a>(GSM 03.40, Data Coding Scheme)</a>
<a>(SMS Data Coding Scheme)</a>
The UCS2 Encoding is actually <a>Unicode UTF-16</a>...
<blockquote>
"the SMS standard specifies UCS-2, but almost all users actually implement UTF-16 so that emojis work"
</blockquote>
<a>(Source)</a>
So this Encoded Message Text...
<code>text
// TP-User-Data: Message Text encoded with UCS2 Character Set
"00480065006C006C006F002C005100750065006300740065006C0021"</code>
Comes from the <a>Unicode UTF-16 Encoding</a> of the Message Text "Hello,Quectel!"...
| Character | UTF-16 Encoding |
|:---------:|:---------------:|
| <code>H</code> | <code>0048</code>
| <code>e</code> | <code>0065</code>
| <code>l</code> | <code>006C</code>
| <code>l</code> | <code>006C</code>
| <code>o</code> | <code>006F</code>
| <code>,</code> | <code>002C</code>
| <code>Q</code> | <code>0051</code>
| <code>u</code> | <code>0075</code>
| <code>e</code> | <code>0065</code>
| <code>c</code> | <code>0063</code>
| <code>t</code> | <code>0074</code>
| <code>e</code> | <code>0065</code>
| <code>l</code> | <code>006C</code>
| <code>!</code> | <code>0021</code>
(These are 7-Bit ASCII Characters, so the UTF-16 Encoding looks identical to ASCII)
SMS Text Mode vs PDU Mode
Read the article...
<ul>
<li><a>"NuttX RTOS for PinePhone: Phone Calls and Text Messages"</a></li>
</ul>
<em>Why send SMS in PDU Mode instead of Text Mode?</em>
Sending SMS Messages in Text Mode looks easier. But we <strong>should use PDU Mode</strong> instead. Here's why...
<strong>In Text Mode:</strong> This is how we send an SMS...
<code>text
// Text Mode: How many characters in this SMS?
AT+CMGS="+1234567890"</code>
<strong>In PDU Mode:</strong> We do it like so...
<code>text
// PDU Mode: 41 bytes in this SMS (excluding SMSC)
AT+CMGS=41</code>
See the difference? <strong>PDU Mode is more precise</strong> because we state exactly how many bytes there are in the SMS.
With Text Mode, there's a risk of garbled messages when characters are dropped during UART Transmission. (Which happens!)
<em>But what if characters are dropped in PDU Mode?</em>
The LTE Modem will say it's an <strong>Invalid PDU</strong>...
<code>text
+CMS ERROR: 304</code>
Our app should catch this error and resend.
PinePhone Accelerometer and Gyroscope
To read PinePhone's InvenSense MPU-6050 Accelerometer and Gyroscope, check out this article...
<ul>
<li><a>"Inside a Smartphone Accelerometer: PinePhone with NuttX RTOS"</a></li>
</ul>
Compile NuttX on Android with Termux
<em>Can we compile NuttX on an Android Phone (or Tablet) with Termux?</em>
That would be really cool for checking whether the Latest NuttX Updates are building OK for our target device... All we need is an Android Phone!
We managed to install the NuttX Build Tools on Android Termux (including <code>kconfig</code>)...
<ul>
<li><a>"Compile Apache NuttX RTOS on Android with Termux"</a></li>
</ul>
NuttX <code>make</code> starts OK, but it fails later because we couldn't build the GCC Arm64 Toolchain on Android Termux.
Emulate PinePhone with Unicorn Emulator
<em>To make PinePhone testing easier...</em>
<em>Can we emulate Arm64 PinePhone with <a>Unicorn Emulator</a>?</em>
Read the articles...
<ul>
<li>
<a>"(Possibly) Emulate PinePhone with Unicorn Emulator"</a>
</li>
<li>
<a>"(Clickable) Call Graph for Apache NuttX Real-Time Operating System"</a>
</li>
</ul>
Simulate PinePhone UI with Zig, LVGL and WebAssembly
Read the articles...
<ul>
<li>
<a>"NuttX RTOS for PinePhone: Feature Phone UI in LVGL, Zig and WebAssembly"</a>
</li>
<li>
<a>"(Possibly) LVGL in WebAssembly with Zig Compiler"</a>
</li>
</ul>
We're now building a <strong>Feature Phone UI</strong> for NuttX on PinePhone...
Can we simulate the Feature Phone UI with <strong>Zig, LVGL and WebAssembly</strong> in a Web Browser? To make the UI Coding a little easier?
We have previously created a simple <strong>LVGL App with Zig</strong> for PinePhone...
<ul>
<li><a>pinephone-lvgl-zig</a></li>
</ul>
Zig natively supports <strong>WebAssembly</strong>...
<ul>
<li><a>WebAssembly on Zig</a></li>
</ul>
So we might run <strong>Zig + JavaScript</strong> in a Web Browser like so...
<ul>
<li><a>WebAssembly With Zig in a Web Browser</a></li>
</ul>
But LVGL doesn't work with JavaScript yet. LVGL runs in a Web Browser by compiling with Emscripten and SDL...
<ul>
<li><a>LVGL with Emscripten and SDL</a></li>
</ul>
Therefore we shall do this...
<ol>
<li>
Use Zig to compile LVGL from C to WebAssembly <a>(With <code>zig cc</code>)</a>
</li>
<li>
Use Zig to connect the JavaScript UI (canvas rendering + input events) to LVGL WebAssembly <a>(Like this)</a>
</li>
</ol>
Check out the updates here...
<ul>
<li><a>"Simulate PinePhone UI with Zig, LVGL and WebAssembly"</a></li>
</ul>
Apache NuttX RTOS for PinePhone Pro
TODO: <a>WIP port of NuttX to PinePhone Pro</a>
(1) Would be good to provide the <strong>Arm64 Disassembly</strong>.
(So that I can locate the addresses, also peek at the code snippets)
```bash
Dump the disassembly to nuttx.S
aarch64-none-elf-objdump \
-t -S --demangle --line-numbers --wide \
nuttx \
<blockquote>
nuttx.S \
2>&1
```
</blockquote>
(2) What's the <strong>Boot Address kernel_addr_r</strong> for PinePhone Pro?
I can't find it in the docs, so I assume that this value is correct:
```c
/<em> U-Boot loads NuttX at this address (kernel_addr_r) </em>/
define CONFIG_LOAD_BASE 0x02080000
```
Here's how we get kernel_addr_r from U-Boot (is it the same for Tow-Boot?):
https://lupyuen.github.io/articles/uboot#boot-address
(3) Change the <strong>Memory Map (RAM and I/O)</strong> to this, based on the Address Mapping from RK3399 Tech Ref Manual (Part 1) Page 560:
https://github.com/apache/nuttx/blob/master/arch/arm64/include/a64/chip.h#L45-L51
```c
// RAM Base Address: I'm guessing this based on CONFIG_LOAD_BASE (kernel_addr_r)
define CONFIG_RAMBANK1_ADDR 0x02000000
// RAM Size: Let's keep this for now, we'll expand later
define CONFIG_RAMBANK1_SIZE MB(512)
// I/O Addresses begin at F800_0000
define CONFIG_DEVICEIO_BASEADDR 0xF8000000
// Up to FFFF_FFFF
define CONFIG_DEVICEIO_SIZE MB(128)
```
(4) <strong>Arm64 Generic Interrupt Controller (GIC)</strong> is Version 3 (instead of PinePhone's Version 2)
According to RK3399 Tech Ref Manual (Part 1) Page 560, RK3399 uses GIC-500, which is based on GIC v3. (PinePhone uses GIC v2)
To change GIC from v2 to v3:
```bash
make menuconfig
Go to System Type > GIC version
Change from 2 to 3
Save and exit menuconfig
Verify that GIC version is now 3:
grep ARM_GIC_VERSION .config
```
More about GIC: https://lupyuen.github.io/articles/interrupt#generic-interrupt-controller
More about ARM_GIC_VERSION: https://github.com/apache/nuttx/blob/master/arch/arm64/Kconfig#L200-L209
(5) Next we need to fill in the <strong>GIC Base Address</strong>:
https://github.com/apache/nuttx/blob/master/arch/arm64/include/a64/chip.h
```c
/<em> Allwinner A64 Generic Interrupt Controller v2: Distributor and Redist </em>/
define CONFIG_GICD_BASE 0x1C81000
define CONFIG_GICR_BASE 0x1C82000
```
But GIC v3 requires an additional field CONFIG_GICR_OFFSET, like this code from NuttX QEMU:
https://github.com/apache/nuttx/blob/master/arch/arm64/include/qemu/chip.h#L47-L51
```c
define CONFIG_GICD_BASE 0x8000000
define CONFIG_GICR_BASE 0x80a0000
define CONFIG_GICR_OFFSET 0x20000
```
According to the <a>Linux Device Tree for RK3399</a>:
- GICD = 0xfee00000
- GICR = 0xfef00000
But I'm not sure what's <a>CONFIG_GICR_OFFSET</a>. (Offset to the GIC Registers for each CPU?)
Maybe we stick with the current value and test whether <a>UART Interrupts</a> are OK?
<a>(See the Linux doc for GIC)</a>
RK3399 UART0 is at <a>GIC Shared Peripheral Interrupt 99</a>
RK3399 UART is a <a>DesignWare APB UART (dw-apb-uart)</a>, which maps to the <a>Linux DesignWare 8250 Driver (8250_dw.c)</a>.
Which is compatible with the <a>NuttX 16550 UART Driver</a>. So remember to enable 16550_WAIT_LCR, and set 16550_REGINCR=4. <a>(Because regshift=2)</a>
The IRQs (Interrupt IDs) might need to change:
https://github.com/apache/nuttx/blob/master/arch/arm64/include/a64/irq.h
This should follow RK3399 Tech Ref Manual (Part 1) Page 15.
Eventually the I/O Peripherals will have completely different addresses too:
https://github.com/apache/nuttx/blob/master/arch/arm64/src/a64/hardware/a64_memorymap.h
TODO
Test Logs
This section contains PinePhone NuttX Logs captured from various tests...
USB Devices on PinePhone
We captured this log of USB Devices on PinePhone, which will be helpful when we build the NuttX USB Driver for PinePhone's Quectel LTE Modem...
<code>text
[manjaro@manjaro-arm ~]$ sudo lsusb -v
Bus 004 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Device Descriptor:
bLength 18
bDescriptorType 1
bcdUSB 1.10
bDeviceClass 9 Hub
bDeviceSubClass 0
bDeviceProtocol 0 Full speed (or root) hub
bMaxPacketSize0 64
idVendor 0x1d6b Linux Foundation
idProduct 0x0001 1.1 root hub
bcdDevice 5.18
iManufacturer 3 Linux 5.18.9-1-MANJARO-ARM ohci_hcd
iProduct 2 Generic Platform OHCI controller
iSerial 1 1c1b400.usb
bNumConfigurations 1
Configuration Descriptor:
bLength 9
bDescriptorType 2
wTotalLength 0x0019
bNumInterfaces 1
bConfigurationValue 1
iConfiguration 0
bmAttributes 0xe0
Self Powered
Remote Wakeup
MaxPower 0mA
Interface Descriptor:
bLength 9
bDescriptorType 4
bInterfaceNumber 0
bAlternateSetting 0
bNumEndpoints 1
bInterfaceClass 9 Hub
bInterfaceSubClass 0
bInterfaceProtocol 0 Full speed (or root) hub
iInterface 0
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x81 EP 1 IN
bmAttributes 3
Transfer Type Interrupt
Synch Type None
Usage Type Data
wMaxPacketSize 0x0002 1x 2 bytes
bInterval 255
Hub Descriptor:
bLength 9
bDescriptorType 41
nNbrPorts 1
wHubCharacteristic 0x000a
No power switching (usb 1.0)
Per-port overcurrent protection
bPwrOn2PwrGood 2 * 2 milli seconds
bHubContrCurrent 0 milli Ampere
DeviceRemovable 0x00
PortPwrCtrlMask 0xff
Hub Port Status:
Port 1: 0000.0100 power
Device Status: 0x0001
Self Powered
Bus 002 Device 002: ID 2c7c:0125 Quectel Wireless Solutions Co., Ltd. EC25 LTE modem
Device Descriptor:
bLength 18
bDescriptorType 1
bcdUSB 2.00
bDeviceClass 239 Miscellaneous Device
bDeviceSubClass 2
bDeviceProtocol 1 Interface Association
bMaxPacketSize0 64
idVendor 0x2c7c Quectel Wireless Solutions Co., Ltd.
idProduct 0x0125 EC25 LTE modem
bcdDevice 3.18
iManufacturer 1 Quectel
iProduct 2 EG25-G
iSerial 0
bNumConfigurations 1
Configuration Descriptor:
bLength 9
bDescriptorType 2
wTotalLength 0x00d1
bNumInterfaces 5
bConfigurationValue 1
iConfiguration 0
bmAttributes 0xa0
(Bus Powered)
Remote Wakeup
MaxPower 500mA
Interface Descriptor:
bLength 9
bDescriptorType 4
bInterfaceNumber 0
bAlternateSetting 0
bNumEndpoints 2
bInterfaceClass 255 Vendor Specific Class
bInterfaceSubClass 255 Vendor Specific Subclass
bInterfaceProtocol 255 Vendor Specific Protocol
iInterface 0
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x81 EP 1 IN
bmAttributes 2
Transfer Type Bulk
Synch Type None
Usage Type Data
wMaxPacketSize 0x0200 1x 512 bytes
bInterval 0
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x01 EP 1 OUT
bmAttributes 2
Transfer Type Bulk
Synch Type None
Usage Type Data
wMaxPacketSize 0x0200 1x 512 bytes
bInterval 0
Interface Descriptor:
bLength 9
bDescriptorType 4
bInterfaceNumber 1
bAlternateSetting 0
bNumEndpoints 3
bInterfaceClass 255 Vendor Specific Class
bInterfaceSubClass 0
bInterfaceProtocol 0
iInterface 0
** UNRECOGNIZED: 05 24 00 10 01
** UNRECOGNIZED: 05 24 01 00 00
** UNRECOGNIZED: 04 24 02 02
** UNRECOGNIZED: 05 24 06 00 00
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x83 EP 3 IN
bmAttributes 3
Transfer Type Interrupt
Synch Type None
Usage Type Data
wMaxPacketSize 0x000a 1x 10 bytes
bInterval 9
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x82 EP 2 IN
bmAttributes 2
Transfer Type Bulk
Synch Type None
Usage Type Data
wMaxPacketSize 0x0200 1x 512 bytes
bInterval 0
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x02 EP 2 OUT
bmAttributes 2
Transfer Type Bulk
Synch Type None
Usage Type Data
wMaxPacketSize 0x0200 1x 512 bytes
bInterval 0
Interface Descriptor:
bLength 9
bDescriptorType 4
bInterfaceNumber 2
bAlternateSetting 0
bNumEndpoints 3
bInterfaceClass 255 Vendor Specific Class
bInterfaceSubClass 0
bInterfaceProtocol 0
iInterface 0
** UNRECOGNIZED: 05 24 00 10 01
** UNRECOGNIZED: 05 24 01 00 00
** UNRECOGNIZED: 04 24 02 02
** UNRECOGNIZED: 05 24 06 00 00
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x85 EP 5 IN
bmAttributes 3
Transfer Type Interrupt
Synch Type None
Usage Type Data
wMaxPacketSize 0x000a 1x 10 bytes
bInterval 9
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x84 EP 4 IN
bmAttributes 2
Transfer Type Bulk
Synch Type None
Usage Type Data
wMaxPacketSize 0x0200 1x 512 bytes
bInterval 0
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x03 EP 3 OUT
bmAttributes 2
Transfer Type Bulk
Synch Type None
Usage Type Data
wMaxPacketSize 0x0200 1x 512 bytes
bInterval 0
Interface Descriptor:
bLength 9
bDescriptorType 4
bInterfaceNumber 3
bAlternateSetting 0
bNumEndpoints 3
bInterfaceClass 255 Vendor Specific Class
bInterfaceSubClass 0
bInterfaceProtocol 0
iInterface 0
** UNRECOGNIZED: 05 24 00 10 01
** UNRECOGNIZED: 05 24 01 00 00
** UNRECOGNIZED: 04 24 02 02
** UNRECOGNIZED: 05 24 06 00 00
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x87 EP 7 IN
bmAttributes 3
Transfer Type Interrupt
Synch Type None
Usage Type Data
wMaxPacketSize 0x000a 1x 10 bytes
bInterval 9
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x86 EP 6 IN
bmAttributes 2
Transfer Type Bulk
Synch Type None
Usage Type Data
wMaxPacketSize 0x0200 1x 512 bytes
bInterval 0
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x04 EP 4 OUT
bmAttributes 2
Transfer Type Bulk
Synch Type None
Usage Type Data
wMaxPacketSize 0x0200 1x 512 bytes
bInterval 0
Interface Descriptor:
bLength 9
bDescriptorType 4
bInterfaceNumber 4
bAlternateSetting 0
bNumEndpoints 3
bInterfaceClass 255 Vendor Specific Class
bInterfaceSubClass 255 Vendor Specific Subclass
bInterfaceProtocol 255 Vendor Specific Protocol
iInterface 0
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x89 EP 9 IN
bmAttributes 3
Transfer Type Interrupt
Synch Type None
Usage Type Data
wMaxPacketSize 0x0008 1x 8 bytes
bInterval 9
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x88 EP 8 IN
bmAttributes 2
Transfer Type Bulk
Synch Type None
Usage Type Data
wMaxPacketSize 0x0200 1x 512 bytes
bInterval 0
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x05 EP 5 OUT
bmAttributes 2
Transfer Type Bulk
Synch Type None
Usage Type Data
wMaxPacketSize 0x0200 1x 512 bytes
bInterval 0
Device Qualifier (for other device speed):
bLength 10
bDescriptorType 6
bcdUSB 2.00
bDeviceClass 239 Miscellaneous Device
bDeviceSubClass 2
bDeviceProtocol 1 Interface Association
bMaxPacketSize0 64
bNumConfigurations 1
Device Status: 0x0000
(Bus Powered)
Bus 002 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Device Descriptor:
bLength 18
bDescriptorType 1
bcdUSB 2.00
bDeviceClass 9 Hub
bDeviceSubClass 0
bDeviceProtocol 0 Full speed (or root) hub
bMaxPacketSize0 64
idVendor 0x1d6b Linux Foundation
idProduct 0x0002 2.0 root hub
bcdDevice 5.18
iManufacturer 3 Linux 5.18.9-1-MANJARO-ARM ehci_hcd
iProduct 2 EHCI Host Controller
iSerial 1 1c1b000.usb
bNumConfigurations 1
Configuration Descriptor:
bLength 9
bDescriptorType 2
wTotalLength 0x0019
bNumInterfaces 1
bConfigurationValue 1
iConfiguration 0
bmAttributes 0xe0
Self Powered
Remote Wakeup
MaxPower 0mA
Interface Descriptor:
bLength 9
bDescriptorType 4
bInterfaceNumber 0
bAlternateSetting 0
bNumEndpoints 1
bInterfaceClass 9 Hub
bInterfaceSubClass 0
bInterfaceProtocol 0 Full speed (or root) hub
iInterface 0
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x81 EP 1 IN
bmAttributes 3
Transfer Type Interrupt
Synch Type None
Usage Type Data
wMaxPacketSize 0x0004 1x 4 bytes
bInterval 12
Hub Descriptor:
bLength 9
bDescriptorType 41
nNbrPorts 1
wHubCharacteristic 0x000a
No power switching (usb 1.0)
Per-port overcurrent protection
bPwrOn2PwrGood 10 * 2 milli seconds
bHubContrCurrent 0 milli Ampere
DeviceRemovable 0x00
PortPwrCtrlMask 0xff
Hub Port Status:
Port 1: 0000.0503 highspeed power enable connect
Device Status: 0x0001
Self Powered
Bus 003 Device 001: ID 1d6b:0001 Linux Foundation 1.1 root hub
Device Descriptor:
bLength 18
bDescriptorType 1
bcdUSB 1.10
bDeviceClass 9 Hub
bDeviceSubClass 0
bDeviceProtocol 0 Full speed (or root) hub
bMaxPacketSize0 64
idVendor 0x1d6b Linux Foundation
idProduct 0x0001 1.1 root hub
bcdDevice 5.18
iManufacturer 3 Linux 5.18.9-1-MANJARO-ARM ohci_hcd
iProduct 2 Generic Platform OHCI controller
iSerial 1 1c1a400.usb
bNumConfigurations 1
Configuration Descriptor:
bLength 9
bDescriptorType 2
wTotalLength 0x0019
bNumInterfaces 1
bConfigurationValue 1
iConfiguration 0
bmAttributes 0xe0
Self Powered
Remote Wakeup
MaxPower 0mA
Interface Descriptor:
bLength 9
bDescriptorType 4
bInterfaceNumber 0
bAlternateSetting 0
bNumEndpoints 1
bInterfaceClass 9 Hub
bInterfaceSubClass 0
bInterfaceProtocol 0 Full speed (or root) hub
iInterface 0
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x81 EP 1 IN
bmAttributes 3
Transfer Type Interrupt
Synch Type None
Usage Type Data
wMaxPacketSize 0x0002 1x 2 bytes
bInterval 255
Hub Descriptor:
bLength 9
bDescriptorType 41
nNbrPorts 1
wHubCharacteristic 0x000a
No power switching (usb 1.0)
Per-port overcurrent protection
bPwrOn2PwrGood 2 * 2 milli seconds
bHubContrCurrent 0 milli Ampere
DeviceRemovable 0x00
PortPwrCtrlMask 0xff
Hub Port Status:
Port 1: 0000.0100 power
Device Status: 0x0001
Self Powered
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Device Descriptor:
bLength 18
bDescriptorType 1
bcdUSB 2.00
bDeviceClass 9 Hub
bDeviceSubClass 0
bDeviceProtocol 0 Full speed (or root) hub
bMaxPacketSize0 64
idVendor 0x1d6b Linux Foundation
idProduct 0x0002 2.0 root hub
bcdDevice 5.18
iManufacturer 3 Linux 5.18.9-1-MANJARO-ARM ehci_hcd
iProduct 2 EHCI Host Controller
iSerial 1 1c1a000.usb
bNumConfigurations 1
Configuration Descriptor:
bLength 9
bDescriptorType 2
wTotalLength 0x0019
bNumInterfaces 1
bConfigurationValue 1
iConfiguration 0
bmAttributes 0xe0
Self Powered
Remote Wakeup
MaxPower 0mA
Interface Descriptor:
bLength 9
bDescriptorType 4
bInterfaceNumber 0
bAlternateSetting 0
bNumEndpoints 1
bInterfaceClass 9 Hub
bInterfaceSubClass 0
bInterfaceProtocol 0 Full speed (or root) hub
iInterface 0
Endpoint Descriptor:
bLength 7
bDescriptorType 5
bEndpointAddress 0x81 EP 1 IN
bmAttributes 3
Transfer Type Interrupt
Synch Type None
Usage Type Data
wMaxPacketSize 0x0004 1x 4 bytes
bInterval 12
Hub Descriptor:
bLength 9
bDescriptorType 41
nNbrPorts 1
wHubCharacteristic 0x000a
No power switching (usb 1.0)
Per-port overcurrent protection
bPwrOn2PwrGood 10 * 2 milli seconds
bHubContrCurrent 0 milli Ampere
DeviceRemovable 0x00
PortPwrCtrlMask 0xff
Hub Port Status:
Port 1: 0000.0100 power
Device Status: 0x0001
Self Powered</code>
Testing Zig Backlight Driver on PinePhone
PinePhone Test Log for the following Zig Drivers...
<ul>
<li>
<a>"Display Backlight"</a>
</li>
<li>
<a>"Power Management Integrated Circuit"</a>
</li>
<li>
<a>"Timing Controller (TCON0)"</a>
</li>
<li>
<a>"Enable MIPI DSI Block"</a>
</li>
<li>
<a>"Enable MIPI Display Physical Layer (DPHY)"</a>
</li>
<li>
<a>"Reset LCD Panel"</a>
</li>
<li>
<a>"Start MIPI DSI HSC and HSD"</a>
</li>
</ul>
```text
DRAM: 2048 MiB
Trying to boot from MMC1
NOTICE: BL31: v2.2(release):v2.2-904-gf9ea3a629
NOTICE: BL31: Built : 15:32:12, Apr 9 2020
NOTICE: BL31: Detected Allwinner A64/H64/R18 SoC (1689)
NOTICE: BL31: Found U-Boot DTB at 0x4064410, model: PinePhone
NOTICE: PSCI: System suspend is unavailable
U-Boot 2020.07 (Nov 08 2020 - 00:15:12 +0100)
DRAM: 2 GiB
MMC: Device 'mmc@1c11000': seq 1 is in use by 'mmc@1c10000'
mmc@1c0f000: 0, mmc@1c10000: 2, mmc@1c11000: 1
Loading Environment from FAT... *** Warning - bad CRC, using default environment
starting USB...
No working controllers found
Hit any key to stop autoboot: 0
switch to partitions #0, OK
mmc0 is current device
Scanning mmc 0:1...
Found U-Boot script /boot.scr
653 bytes read in 3 ms (211.9 KiB/s)
Executing script at 4fc00000
gpio: pin 114 (gpio 114) value is 1
246286 bytes read in 14 ms (16.8 MiB/s)
Uncompressed size: 10465280 = 0x9FB000
36162 bytes read in 4 ms (8.6 MiB/s)
1078500 bytes read in 51 ms (20.2 MiB/s)
Flattened Device Tree blob at 4fa00000
Booting using the fdt blob at 0x4fa00000
Loading Ramdisk to 49ef8000, end 49fff4e4 ... OK
Loading Device Tree to 0000000049eec000, end 0000000049ef7d41 ... OK
Starting kernel ...
HELLO NUTTX ON PINEPHONE!
- Ready to Boot CPU
- Boot from EL2
- Boot from EL1
- Boot to C runtime for OS Initialize
nx_start: Entry
up_allocate_heap: heap_start=0x0x40a7b000, heap_size=0x7585000
arm64_gic_initialize: TODO: Init GIC for PinePhone
arm64_gic_initialize: CONFIG_GICD_BASE=0x1c81000
arm64_gic_initialize: CONFIG_GICR_BASE=0x1c82000
arm64_gic_initialize: GIC Version is 2
up_timer_initialize: up_timer_initialize: cp15 timer(s) running at 24.00MHz, cycle 24000
up_timer_initialize: _vector_table=0x40100000
up_timer_initialize: Before writing: vbar_el1=0x40280000
up_timer_initialize: After writing: vbar_el1=0x40100000
uart_register: Registering /dev/console
uart_register: Registering /dev/ttyS0
work_start_highpri: Starting high-priority kernel worker thread(s)
nx_start_application: Starting init thread
lib_cxx_initialize: _sinit: 0x40100000 _einit: 0x40100000 _stext: 0x40080000 _etext: 0x40101000
nsh: sysinit: fopen failed: 2
nshn:x _msktfaarttf:s :C PcUo0m:m aBnedg innonti nfgo uInddl
e
L
oNoupt
t
Shell (NSH) NuttX-11.0.0-RC2
nsh>
nsh>
nsh> uname -a
NuttX 11.0.0-RC2 a33f82d Dec 2 2022 17:57:39 arm64 qemu-a53
nsh>
nsh> hello 3
task_spawn: name=hello entry=0x4009b4f8 file_actions=0x40a80580 attr=0x40a80588 argv=0x40a806d0
spawn_execattrs: Setting policy=2 priority=100 for pid=3
ABHello, World!!
pd_cfg2_reg=0x77711177
pd_data_reg=0x1c0000
test_render: start, channels=3
backlight_enable: start, percent=90
Configure PL10 for PWM
<em>0x1f02c04: clear 0x700, set 0x200
</em>0x1f02c04 = 0x77277
Disable R_PWM
<em>0x1f03800: clear 0x40, set 0x0
</em>0x1f03800 = 0x0
Configure R_PWM Period
<em>0x1f03804 = 0x4af0437
Enable R_PWM
</em>0x1f03800 = 0x5f
Configure PH10 for Output
<em>0x1c20900: clear 0x700, set 0x100
</em>0x1c20900 = 0x7177
Set PH10 to High
<em>0x1c2090c: clear 0x400, set 0x400
</em>0x1c2090c = 0x400
backlight_enable: end
tcon0_init: start
Configure PLL_VIDEO0
<em>0x1c20010 = 0x81006207
Enable LDO1 and LDO2
</em>0x1c20040 = 0xc00000
Configure MIPI PLL
<em>0x1c20040 = 0x80c0071a
Set TCON0 Clock Source to MIPI PLL
</em>0x1c20118 = 0x80000000
Enable TCON0 Clock
<em>0x1c20064 = 0x8
Deassert TCON0 Reset
</em>0x1c202c4 = 0x8
Disable TCON0 and Interrupts
<em>0x1c0c000 = 0x0
</em>0x1c0c004 = 0x0
<em>0x1c0c008 = 0x0
Enable Tristate Output
</em>0x1c0c08c = 0xffffffff
<em>0x1c0c0f4 = 0xffffffff
Set DCLK to MIPI PLL / 6
</em>0x1c0c044 = 0x80000006
<em>0x1c0c040 = 0x81000000
</em>0x1c0c048 = 0x2cf059f
<em>0x1c0c0f8 = 0x8
</em>0x1c0c060 = 0x10010005
Set CPU Panel Trigger
<em>0x1c0c160 = 0x2f02cf
</em>0x1c0c164 = 0x59f
<em>0x1c0c168 = 0x1bc2000a
Set Safe Period
</em>0x1c0c1f0 = 0xbb80003
Enable Output Triggers
<em>0x1c0c08c = 0xe0000000
Enable TCON0
</em>0x1c0c000: clear 0x80000000, set 0x80000000
<em>0x1c0c000 = 0x80000000
tcon0_init: end
display_board_init: start
Configure PD23 for Output
</em>0x1c20874: clear 0x70000000, set 0x10000000
<em>0x1c20874 = 0x17711177
Set PD23 to Low
</em>0x1c2087c: clear 0x800000, set 0x0
<em>0x1c2087c = 0x1c0000
Set DLDO1 Voltage to 3.3V
pmic_write: reg=0x15, val=0x1a
rsb_write: rt_addr=0x2d, reg_addr=0x15, value=0x1a
</em>0x1f0342c = 0x4e
<em>0x1f03430 = 0x2d0000
</em>0x1f03410 = 0x15
<em>0x1f0341c = 0x1a
</em>0x1f03400 = 0x80
pmic_clrsetbits: reg=0x12, clr_mask=0x0, set_mask=0x8
rsb_read: rt_addr=0x2d, reg_addr=0x12
<em>0x1f0342c = 0x8b
</em>0x1f03430 = 0x2d0000
<em>0x1f03410 = 0x12
</em>0x1f03400 = 0x80
rsb_write: rt_addr=0x2d, reg_addr=0x12, value=0xd9
<em>0x1f0342c = 0x4e
</em>0x1f03430 = 0x2d0000
<em>0x1f03410 = 0x12
</em>0x1f0341c = 0xd9
<em>0x1f03400 = 0x80
Set LDO Voltage to 3.3V
pmic_write: reg=0x91, val=0x1a
rsb_write: rt_addr=0x2d, reg_addr=0x91, value=0x1a
</em>0x1f0342c = 0x4e
<em>0x1f03430 = 0x2d0000
</em>0x1f03410 = 0x91
<em>0x1f0341c = 0x1a
</em>0x1f03400 = 0x80
Enable LDO mode on GPIO0
pmic_write: reg=0x90, val=0x3
rsb_write: rt_addr=0x2d, reg_addr=0x90, value=0x3
<em>0x1f0342c = 0x4e
</em>0x1f03430 = 0x2d0000
<em>0x1f03410 = 0x90
</em>0x1f0341c = 0x3
<em>0x1f03400 = 0x80
Set DLDO2 Voltage to 1.8V
pmic_write: reg=0x16, val=0xb
rsb_write: rt_addr=0x2d, reg_addr=0x16, value=0xb
</em>0x1f0342c = 0x4e
<em>0x1f03430 = 0x2d0000
</em>0x1f03410 = 0x16
<em>0x1f0341c = 0xb
</em>0x1f03400 = 0x80
pmic_clrsetbits: reg=0x12, clr_mask=0x0, set_mask=0x10
rsb_read: rt_addr=0x2d, reg_addr=0x12
<em>0x1f0342c = 0x8b
</em>0x1f03430 = 0x2d0000
<em>0x1f03410 = 0x12
</em>0x1f03400 = 0x80
rsb_write: rt_addr=0x2d, reg_addr=0x12, value=0xd9
<em>0x1f0342c = 0x4e
</em>0x1f03430 = 0x2d0000
<em>0x1f03410 = 0x12
</em>0x1f0341c = 0xd9
<em>0x1f03400 = 0x80
Wait for power supply and power-on init
display_board_init: end
enable_dsi_block: start
Enable MIPI DSI Bus
</em>0x1c20060: clear 0x2, set 0x2
<em>0x1c20060 = 0x4742
</em>0x1c202c0: clear 0x2, set 0x2
<em>0x1c202c0 = 0x4742
Enable DSI Block
</em>0x1ca0000 = 0x1
<em>0x1ca0010 = 0x30000
</em>0x1ca0060 = 0xa
<em>0x1ca0078 = 0x0
Set Instructions
</em>0x1ca0020 = 0x1f
<em>0x1ca0024 = 0x10000001
</em>0x1ca0028 = 0x20000010
<em>0x1ca002c = 0x2000000f
</em>0x1ca0030 = 0x30100001
<em>0x1ca0034 = 0x40000010
</em>0x1ca0038 = 0xf
<em>0x1ca003c = 0x5000001f
Configure Jump Instructions
</em>0x1ca004c = 0x560001
<em>0x1ca02f8 = 0xff
Set Video Start Delay
</em>0x1ca0014 = 0x5bc7
Set Burst
<em>0x1ca007c = 0x10000007
Set Instruction Loop
</em>0x1ca0040 = 0x30000002
<em>0x1ca0044 = 0x310031
</em>0x1ca0054 = 0x310031
Set Pixel Format
<em>0x1ca0090 = 0x1308703e
</em>0x1ca0098 = 0xffff
<em>0x1ca009c = 0xffffffff
</em>0x1ca0080 = 0x10008
Set Sync Timings
<em>0x1ca000c = 0x0
</em>0x1ca00b0 = 0x12000021
<em>0x1ca00b4 = 0x1000031
</em>0x1ca00b8 = 0x7000001
<em>0x1ca00bc = 0x14000011
Set Basic Size
</em>0x1ca0018 = 0x11000a
<em>0x1ca001c = 0x5cd05a0
Set Horizontal Blanking
</em>0x1ca00c0 = 0x9004a19
<em>0x1ca00c4 = 0x50b40000
</em>0x1ca00c8 = 0x35005419
<em>0x1ca00cc = 0x757a0000
</em>0x1ca00d0 = 0x9004a19
<em>0x1ca00d4 = 0x50b40000
</em>0x1ca00e0 = 0xc091a19
<em>0x1ca00e4 = 0x72bd0000
Set Vertical Blanking
</em>0x1ca00e8 = 0x1a000019
<em>0x1ca00ec = 0xffff0000
enable_dsi_block: end
dphy_enable: start
Set DSI Clock to 150 MHz
</em>0x1c20168 = 0x8203
Power on DPHY Tx
<em>0x1ca1004 = 0x10000000
</em>0x1ca1010 = 0xa06000e
<em>0x1ca1014 = 0xa033207
</em>0x1ca1018 = 0x1e
<em>0x1ca101c = 0x0
</em>0x1ca1020 = 0x303
Enable DPHY
<em>0x1ca1000 = 0x31
</em>0x1ca104c = 0x9f007f00
<em>0x1ca1050 = 0x17000000
</em>0x1ca105c = 0x1f01555
<em>0x1ca1054 = 0x2
Enable LDOR, LDOC, LDOD
</em>0x1ca1058 = 0x3040000
<em>0x1ca1058: clear 0xf8000000, set 0xf8000000
</em>0x1ca1058 = 0xfb040000
<em>0x1ca1058: clear 0x4000000, set 0x4000000
</em>0x1ca1058 = 0xff040000
<em>0x1ca1054: clear 0x10, set 0x10
</em>0x1ca1054 = 0x12
<em>0x1ca1050: clear 0x80000000, set 0x80000000
</em>0x1ca1050 = 0x97000000
<em>0x1ca1054: clear 0xf000000, set 0xf000000
</em>0x1ca1054 = 0xf000012
dphy_enable: end
panel_reset: start
Configure PD23 for Output
<em>0x1c20874: clear 0x70000000, set 0x10000000
</em>0x1c20874 = 0x17711177
Set PD23 to High
<em>0x1c2087c: clear 0x800000, set 0x800000
</em>0x1c2087c = 0x9c0000
wait for initialization
panel_reset: end
panel_init: start
writeDcs: len=4
b9 f1 12 83
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=4
composeLongPacket: channel=0, cmd=0x39, len=4
packet: len=10
39 04 00 2c b9 f1 12 83
84 5d
<em>0x1ca0300: clear 0xffffffff, set 0x2c000439
</em>0x1ca0304: clear 0xffffffff, set 0x8312f1b9
<em>0x1ca0308: clear 0xffffffff, set 0x5d84
</em>0x1ca0200: clear 0xff, set 0x9
<em>0x1ca0010: clear 0x1, set 0x0
</em>0x1ca0010: clear 0x1, set 0x1
writeDcs: len=28
ba 33 81 05 f9 0e 0e 20
00 00 00 00 00 00 00 44
25 00 91 0a 00 00 02 4f
11 00 00 37
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=28
composeLongPacket: channel=0, cmd=0x39, len=28
packet: len=34
39 1c 00 2f ba 33 81 05
f9 0e 0e 20 00 00 00 00
00 00 00 44 25 00 91 0a
00 00 02 4f 11 00 00 37
2c e2
<em>0x1ca0300: clear 0xffffffff, set 0x2f001c39
</em>0x1ca0304: clear 0xffffffff, set 0x58133ba
<em>0x1ca0308: clear 0xffffffff, set 0x200e0ef9
</em>0x1ca030c: clear 0xffffffff, set 0x0
<em>0x1ca0310: clear 0xffffffff, set 0x44000000
</em>0x1ca0314: clear 0xffffffff, set 0xa910025
<em>0x1ca0318: clear 0xffffffff, set 0x4f020000
</em>0x1ca031c: clear 0xffffffff, set 0x37000011
<em>0x1ca0320: clear 0xffffffff, set 0xe22c
</em>0x1ca0200: clear 0xff, set 0x21
<em>0x1ca0010: clear 0x1, set 0x0
</em>0x1ca0010: clear 0x1, set 0x1
writeDcs: len=5
b8 25 22 20 03
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=5
composeLongPacket: channel=0, cmd=0x39, len=5
packet: len=11
39 05 00 36 b8 25 22 20
03 03 72
<em>0x1ca0300: clear 0xffffffff, set 0x36000539
</em>0x1ca0304: clear 0xffffffff, set 0x202225b8
<em>0x1ca0308: clear 0xffffffff, set 0x720303
</em>0x1ca0200: clear 0xff, set 0xa
<em>0x1ca0010: clear 0x1, set 0x0
</em>0x1ca0010: clear 0x1, set 0x1
writeDcs: len=11
b3 10 10 05 05 03 ff 00
00 00 00
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=11
composeLongPacket: channel=0, cmd=0x39, len=11
packet: len=17
39 0b 00 2c b3 10 10 05
05 03 ff 00 00 00 00 6f
bc
<em>0x1ca0300: clear 0xffffffff, set 0x2c000b39
</em>0x1ca0304: clear 0xffffffff, set 0x51010b3
<em>0x1ca0308: clear 0xffffffff, set 0xff0305
</em>0x1ca030c: clear 0xffffffff, set 0x6f000000
<em>0x1ca0310: clear 0xffffffff, set 0xbc
</em>0x1ca0200: clear 0xff, set 0x10
<em>0x1ca0010: clear 0x1, set 0x0
</em>0x1ca0010: clear 0x1, set 0x1
writeDcs: len=10
c0 73 73 50 50 00 c0 08
70 00
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=10
composeLongPacket: channel=0, cmd=0x39, len=10
packet: len=16
39 0a 00 36 c0 73 73 50
50 00 c0 08 70 00 1b 6a
<em>0x1ca0300: clear 0xffffffff, set 0x36000a39
</em>0x1ca0304: clear 0xffffffff, set 0x507373c0
<em>0x1ca0308: clear 0xffffffff, set 0x8c00050
</em>0x1ca030c: clear 0xffffffff, set 0x6a1b0070
<em>0x1ca0200: clear 0xff, set 0xf
</em>0x1ca0010: clear 0x1, set 0x0
<em>0x1ca0010: clear 0x1, set 0x1
writeDcs: len=2
bc 4e
mipi_dsi_dcs_write: channel=0, cmd=0x15, len=2
composeShortPacket: channel=0, cmd=0x15, len=2
packet: len=4
15 bc 4e 35
</em>0x1ca0300: clear 0xffffffff, set 0x354ebc15
<em>0x1ca0200: clear 0xff, set 0x3
</em>0x1ca0010: clear 0x1, set 0x0
<em>0x1ca0010: clear 0x1, set 0x1
writeDcs: len=2
cc 0b
mipi_dsi_dcs_write: channel=0, cmd=0x15, len=2
composeShortPacket: channel=0, cmd=0x15, len=2
packet: len=4
15 cc 0b 22
</em>0x1ca0300: clear 0xffffffff, set 0x220bcc15
<em>0x1ca0200: clear 0xff, set 0x3
</em>0x1ca0010: clear 0x1, set 0x0
<em>0x1ca0010: clear 0x1, set 0x1
writeDcs: len=2
b4 80
mipi_dsi_dcs_write: channel=0, cmd=0x15, len=2
composeShortPacket: channel=0, cmd=0x15, len=2
packet: len=4
15 b4 80 22
</em>0x1ca0300: clear 0xffffffff, set 0x2280b415
<em>0x1ca0200: clear 0xff, set 0x3
</em>0x1ca0010: clear 0x1, set 0x0
<em>0x1ca0010: clear 0x1, set 0x1
writeDcs: len=4
b2 f0 12 f0
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=4
composeLongPacket: channel=0, cmd=0x39, len=4
packet: len=10
39 04 00 2c b2 f0 12 f0
51 86
</em>0x1ca0300: clear 0xffffffff, set 0x2c000439
<em>0x1ca0304: clear 0xffffffff, set 0xf012f0b2
</em>0x1ca0308: clear 0xffffffff, set 0x8651
<em>0x1ca0200: clear 0xff, set 0x9
</em>0x1ca0010: clear 0x1, set 0x0
<em>0x1ca0010: clear 0x1, set 0x1
writeDcs: len=15
e3 00 00 0b 0b 10 10 00
00 00 00 ff 00 c0 10
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=15
composeLongPacket: channel=0, cmd=0x39, len=15
packet: len=21
39 0f 00 0f e3 00 00 0b
0b 10 10 00 00 00 00 ff
00 c0 10 36 0f
</em>0x1ca0300: clear 0xffffffff, set 0xf000f39
<em>0x1ca0304: clear 0xffffffff, set 0xb0000e3
</em>0x1ca0308: clear 0xffffffff, set 0x10100b
<em>0x1ca030c: clear 0xffffffff, set 0xff000000
</em>0x1ca0310: clear 0xffffffff, set 0x3610c000
<em>0x1ca0314: clear 0xffffffff, set 0xf
</em>0x1ca0200: clear 0xff, set 0x14
<em>0x1ca0010: clear 0x1, set 0x0
</em>0x1ca0010: clear 0x1, set 0x1
writeDcs: len=6
c6 01 00 ff ff 00
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=6
composeLongPacket: channel=0, cmd=0x39, len=6
packet: len=12
39 06 00 30 c6 01 00 ff
ff 00 8e 25
<em>0x1ca0300: clear 0xffffffff, set 0x30000639
</em>0x1ca0304: clear 0xffffffff, set 0xff0001c6
<em>0x1ca0308: clear 0xffffffff, set 0x258e00ff
</em>0x1ca0200: clear 0xff, set 0xb
<em>0x1ca0010: clear 0x1, set 0x0
</em>0x1ca0010: clear 0x1, set 0x1
writeDcs: len=13
c1 74 00 32 32 77 f1 ff
ff cc cc 77 77
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=13
composeLongPacket: channel=0, cmd=0x39, len=13
packet: len=19
39 0d 00 13 c1 74 00 32
32 77 f1 ff ff cc cc 77
77 69 e4
<em>0x1ca0300: clear 0xffffffff, set 0x13000d39
</em>0x1ca0304: clear 0xffffffff, set 0x320074c1
<em>0x1ca0308: clear 0xffffffff, set 0xfff17732
</em>0x1ca030c: clear 0xffffffff, set 0x77ccccff
<em>0x1ca0310: clear 0xffffffff, set 0xe46977
</em>0x1ca0200: clear 0xff, set 0x12
<em>0x1ca0010: clear 0x1, set 0x0
</em>0x1ca0010: clear 0x1, set 0x1
writeDcs: len=3
b5 07 07
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=3
composeLongPacket: channel=0, cmd=0x39, len=3
packet: len=9
39 03 00 09 b5 07 07 7b
b3
<em>0x1ca0300: clear 0xffffffff, set 0x9000339
</em>0x1ca0304: clear 0xffffffff, set 0x7b0707b5
<em>0x1ca0308: clear 0xffffffff, set 0xb3
</em>0x1ca0200: clear 0xff, set 0x8
<em>0x1ca0010: clear 0x1, set 0x0
</em>0x1ca0010: clear 0x1, set 0x1
writeDcs: len=3
b6 2c 2c
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=3
composeLongPacket: channel=0, cmd=0x39, len=3
packet: len=9
39 03 00 09 b6 2c 2c 55
04
<em>0x1ca0300: clear 0xffffffff, set 0x9000339
</em>0x1ca0304: clear 0xffffffff, set 0x552c2cb6
<em>0x1ca0308: clear 0xffffffff, set 0x4
</em>0x1ca0200: clear 0xff, set 0x8
<em>0x1ca0010: clear 0x1, set 0x0
</em>0x1ca0010: clear 0x1, set 0x1
writeDcs: len=4
bf 02 11 00
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=4
composeLongPacket: channel=0, cmd=0x39, len=4
packet: len=10
39 04 00 2c bf 02 11 00
b5 e9
<em>0x1ca0300: clear 0xffffffff, set 0x2c000439
</em>0x1ca0304: clear 0xffffffff, set 0x1102bf
<em>0x1ca0308: clear 0xffffffff, set 0xe9b5
</em>0x1ca0200: clear 0xff, set 0x9
<em>0x1ca0010: clear 0x1, set 0x0
</em>0x1ca0010: clear 0x1, set 0x1
writeDcs: len=64
e9 82 10 06 05 a2 0a a5
12 31 23 37 83 04 bc 27
38 0c 00 03 00 00 00 0c
00 03 00 00 00 75 75 31
88 88 88 88 88 88 13 88
64 64 20 88 88 88 88 88
88 02 88 00 00 00 00 00
00 00 00 00 00 00 00 00
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=64
composeLongPacket: channel=0, cmd=0x39, len=64
packet: len=70
39 40 00 25 e9 82 10 06
05 a2 0a a5 12 31 23 37
83 04 bc 27 38 0c 00 03
00 00 00 0c 00 03 00 00
00 75 75 31 88 88 88 88
88 88 13 88 64 64 20 88
88 88 88 88 88 02 88 00
00 00 00 00 00 00 00 00
00 00 00 00 65 03
<em>0x1ca0300: clear 0xffffffff, set 0x25004039
</em>0x1ca0304: clear 0xffffffff, set 0x61082e9
<em>0x1ca0308: clear 0xffffffff, set 0xa50aa205
</em>0x1ca030c: clear 0xffffffff, set 0x37233112
<em>0x1ca0310: clear 0xffffffff, set 0x27bc0483
</em>0x1ca0314: clear 0xffffffff, set 0x3000c38
<em>0x1ca0318: clear 0xffffffff, set 0xc000000
</em>0x1ca031c: clear 0xffffffff, set 0x300
<em>0x1ca0320: clear 0xffffffff, set 0x31757500
</em>0x1ca0324: clear 0xffffffff, set 0x88888888
<em>0x1ca0328: clear 0xffffffff, set 0x88138888
</em>0x1ca032c: clear 0xffffffff, set 0x88206464
<em>0x1ca0330: clear 0xffffffff, set 0x88888888
</em>0x1ca0334: clear 0xffffffff, set 0x880288
<em>0x1ca0338: clear 0xffffffff, set 0x0
</em>0x1ca033c: clear 0xffffffff, set 0x0
<em>0x1ca0340: clear 0xffffffff, set 0x0
</em>0x1ca0344: clear 0xffffffff, set 0x365
<em>0x1ca0200: clear 0xff, set 0x45
</em>0x1ca0010: clear 0x1, set 0x0
<em>0x1ca0010: clear 0x1, set 0x1
writeDcs: len=62
ea 02 21 00 00 00 00 00
00 00 00 00 00 02 46 02
88 88 88 88 88 88 64 88
13 57 13 88 88 88 88 88
88 75 88 23 14 00 00 02
00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 03
0a a5 00 00 00 00
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=62
composeLongPacket: channel=0, cmd=0x39, len=62
packet: len=68
39 3e 00 1a ea 02 21 00
00 00 00 00 00 00 00 00
00 02 46 02 88 88 88 88
88 88 64 88 13 57 13 88
88 88 88 88 88 75 88 23
14 00 00 02 00 00 00 00
00 00 00 00 00 00 00 00
00 00 00 03 0a a5 00 00
00 00 24 1b
</em>0x1ca0300: clear 0xffffffff, set 0x1a003e39
<em>0x1ca0304: clear 0xffffffff, set 0x2102ea
</em>0x1ca0308: clear 0xffffffff, set 0x0
<em>0x1ca030c: clear 0xffffffff, set 0x0
</em>0x1ca0310: clear 0xffffffff, set 0x2460200
<em>0x1ca0314: clear 0xffffffff, set 0x88888888
</em>0x1ca0318: clear 0xffffffff, set 0x88648888
<em>0x1ca031c: clear 0xffffffff, set 0x88135713
</em>0x1ca0320: clear 0xffffffff, set 0x88888888
<em>0x1ca0324: clear 0xffffffff, set 0x23887588
</em>0x1ca0328: clear 0xffffffff, set 0x2000014
<em>0x1ca032c: clear 0xffffffff, set 0x0
</em>0x1ca0330: clear 0xffffffff, set 0x0
<em>0x1ca0334: clear 0xffffffff, set 0x0
</em>0x1ca0338: clear 0xffffffff, set 0x3000000
<em>0x1ca033c: clear 0xffffffff, set 0xa50a
</em>0x1ca0340: clear 0xffffffff, set 0x1b240000
<em>0x1ca0200: clear 0xff, set 0x43
</em>0x1ca0010: clear 0x1, set 0x0
<em>0x1ca0010: clear 0x1, set 0x1
writeDcs: len=35
e0 00 09 0d 23 27 3c 41
35 07 0d 0e 12 13 10 12
12 18 00 09 0d 23 27 3c
41 35 07 0d 0e 12 13 10
12 12 18
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=35
composeLongPacket: channel=0, cmd=0x39, len=35
packet: len=41
39 23 00 20 e0 00 09 0d
23 27 3c 41 35 07 0d 0e
12 13 10 12 12 18 00 09
0d 23 27 3c 41 35 07 0d
0e 12 13 10 12 12 18 93
bf
</em>0x1ca0300: clear 0xffffffff, set 0x20002339
<em>0x1ca0304: clear 0xffffffff, set 0xd0900e0
</em>0x1ca0308: clear 0xffffffff, set 0x413c2723
<em>0x1ca030c: clear 0xffffffff, set 0xe0d0735
</em>0x1ca0310: clear 0xffffffff, set 0x12101312
<em>0x1ca0314: clear 0xffffffff, set 0x9001812
</em>0x1ca0318: clear 0xffffffff, set 0x3c27230d
<em>0x1ca031c: clear 0xffffffff, set 0xd073541
</em>0x1ca0320: clear 0xffffffff, set 0x1013120e
<em>0x1ca0324: clear 0xffffffff, set 0x93181212
</em>0x1ca0328: clear 0xffffffff, set 0xbf
<em>0x1ca0200: clear 0xff, set 0x28
</em>0x1ca0010: clear 0x1, set 0x0
<em>0x1ca0010: clear 0x1, set 0x1
writeDcs: len=1
11
mipi_dsi_dcs_write: channel=0, cmd=0x5, len=1
composeShortPacket: channel=0, cmd=0x5, len=1
packet: len=4
05 11 00 36
</em>0x1ca0300: clear 0xffffffff, set 0x36001105
<em>0x1ca0200: clear 0xff, set 0x3
</em>0x1ca0010: clear 0x1, set 0x0
<em>0x1ca0010: clear 0x1, set 0x1
writeDcs: len=1
29
mipi_dsi_dcs_write: channel=0, cmd=0x5, len=1
composeShortPacket: channel=0, cmd=0x5, len=1
packet: len=4
05 29 00 1c
</em>0x1ca0300: clear 0xffffffff, set 0x1c002905
<em>0x1ca0200: clear 0xff, set 0x3
</em>0x1ca0010: clear 0x1, set 0x0
<em>0x1ca0010: clear 0x1, set 0x1
panel_init: end
start_dsi: start
Start HSC
</em>0x1ca0048 = 0xf02
Commit
<em>0x1ca0010: clear 0x1, set 0x1
</em>0x1ca0010 = 0x30001
Instruction Function Lane
<em>0x1ca0020: clear 0x10, set 0x0
</em>0x1ca0020 = 0xf
Start HSD
<em>0x1ca0048 = 0x63f07006
Commit
</em>0x1ca0010: clear 0x1, set 0x1
<em>0x1ca0010 = 0x30001
start_dsi: end
de2_init: start
Set High Speed SRAM to DMA Mode
</em>0x1c00004 = 0x0
Set Display Engine PLL to 297 MHz
<em>0x1c20048 = 0x81001701
Wait for Display Engine PLL to be stable
Set Special Clock to Display Engine PLL
</em>0x1c20104: clear 0x87000000, set 0x81000000
<em>0x1c20104 = 0x81000000
Enable AHB for Display Engine: De-Assert Display Engine
</em>0x1c202c4: clear 0x1000, set 0x1000
<em>0x1c202c4 = 0x1008
Enable AHB for Display Engine: Pass Display Engine
</em>0x1c20064: clear 0x1000, set 0x1000
<em>0x1c20064 = 0x1008
Enable Clock for MIXER0: SCLK Clock Pass
</em>0x1000000: clear 0x1, set 0x1
<em>0x1000000 = 0x1
Enable Clock for MIXER0: HCLK Clock Reset Off
</em>0x1000008: clear 0x1, set 0x1
<em>0x1000008 = 0x1
Enable Clock for MIXER0: HCLK Clock Pass
</em>0x1000004: clear 0x1, set 0x1
<em>0x1000004 = 0x1
Route MIXER0 to TCON0
</em>0x1000010: clear 0x1, set 0x0
<em>0x1000010 = 0x0
Clear MIXER0 Registers: GLB, BLD, OVL_V, OVL_UI
</em>0x1100000 = 0x0
to <em>0x1105fff = 0x0
Disable MIXER0 VSU
</em>0x1120000 = 0x0
Disable MIXER0 Undocumented
<em>0x1130000 = 0x0
Disable MIXER0 UI_SCALER1
</em>0x1140000 = 0x0
Disable MIXER0 UI_SCALER2
<em>0x1150000 = 0x0
Disable MIXER0 FCE
</em>0x11a0000 = 0x0
Disable MIXER0 BWS
<em>0x11a2000 = 0x0
Disable MIXER0 LTI
</em>0x11a4000 = 0x0
Disable MIXER0 PEAKING
<em>0x11a6000 = 0x0
Disable MIXER0 ASE
</em>0x11a8000 = 0x0
Disable MIXER0 FCC
<em>0x11aa000 = 0x0
Disable MIXER0 DRC
</em>0x11b0000 = 0x0
Enable MIXER0
<em>0x1100000 = 0x1
de2_init: end
renderGraphics: start
initUiBlender: start
Set Blender Background
</em>0x1101088 = 0xff000000
Set Blender Pre-Multiply
<em>0x1101084 = 0x0
initUiBlender: end
initUiChannel: start
Channel 1: Set Overlay (720 x 1440)
</em>0x1103000 = 0xff000405
<em>0x1103010 = 0x4012c000
</em>0x110300c = 0xb40
<em>0x1103004 = 0x59f02cf
</em>0x1103088 = 0x59f02cf
<em>0x1103008 = 0x0
Channel 1: Set Blender Output
</em>0x110108c = 0x59f02cf
<em>0x110000c = 0x59f02cf
Channel 1: Set Blender Input Pipe 0 (720 x 1440)
</em>0x1101008 = 0x59f02cf
<em>0x1101004 = 0xff000000
</em>0x110100c = 0x0
<em>0x1101090 = 0x3010301
Channel 1: Disable Scaler
</em>0x1140000 = 0x0
initUiChannel: end
initUiChannel: start
Channel 2: Set Overlay (600 x 600)
<em>0x1104000 = 0xff000005
</em>0x1104010 = 0x40521000
<em>0x110400c = 0x960
</em>0x1104004 = 0x2570257
<em>0x1104088 = 0x2570257
</em>0x1104008 = 0x0
Channel 2: Set Blender Input Pipe 1 (600 x 600)
<em>0x1101018 = 0x2570257
</em>0x1101014 = 0xff000000
<em>0x110101c = 0x340034
</em>0x1101094 = 0x3010301
Channel 2: Disable Scaler
<em>0x1150000 = 0x0
initUiChannel: end
initUiChannel: start
Channel 3: Set Overlay (720 x 1440)
</em>0x1105000 = 0x7f000005
<em>0x1105010 = 0x40681000
</em>0x110500c = 0xb40
<em>0x1105004 = 0x59f02cf
</em>0x1105088 = 0x59f02cf
<em>0x1105008 = 0x0
Channel 3: Set Blender Input Pipe 2 (720 x 1440)
</em>0x1101028 = 0x59f02cf
<em>0x1101024 = 0xff000000
</em>0x110102c = 0x0
<em>0x1101098 = 0x3010301
Channel 3: Disable Scaler
</em>0x1160000 = 0x0
initUiChannel: end
applySettings: start
Set Blender Route
<em>0x1101080 = 0x321
Enable Blender Pipes
</em>0x1101000 = 0x701
Apply Settings
*0x1100008 = 0x1
applySettings: end
renderGraphics: end
test_render: end
HELLO ZIG ON PINEPHONE!
test_zig: start
Testing Compose Short Packet (Without Parameter)...
composeShortPacket: channel=0, cmd=0x5, len=1
Result:
05 11 00 36
Testing Compose Short Packet (With Parameter)...
composeShortPacket: channel=0, cmd=0x15, len=2
Result:
15 bc 4e 35
Testing Compose Long Packet...
composeLongPacket: channel=0, cmd=0x39, len=64
Result:
39 40 00 25 e9 82 10 06
05 a2 0a a5 12 31 23 37
83 04 bc 27 38 0c 00 03
00 00 00 0c 00 03 00 00
00 75 75 31 88 88 88 88
88 88 13 88 64 64 20 88
88 88 88 88 88 02 88 00
00 00 00 00 00 00 00 00
00 00 00 00 65 03
test_zig: end
nsh>
nsh>
```
Testing Zig Display Engine Driver on PinePhone
See <a>"p-boot Display Code"</a>
```text
DRAM: 2048 MiB
Trying to boot from MMC1
NOTICE: BL31: v2.2(release):v2.2-904-gf9ea3a629
NOTICE: BL31: Built : 15:32:12, Apr 9 2020
NOTICE: BL31: Detected Allwinner A64/H64/R18 SoC (1689)
NOTICE: BL31: Found U-Boot DTB at 0x4064410, model: PinePhone
NOTICE: PSCI: System suspend is unavailable
U-Boot 2020.07 (Nov 08 2020 - 00:15:12 +0100)
DRAM: 2 GiB
MMC: Device 'mmc@1c11000': seq 1 is in use by 'mmc@1c10000'
mmc@1c0f000: 0, mmc@1c10000: 2, mmc@1c11000: 1
Loading Environment from FAT... *** Warning - bad CRC, using default environment
starting USB...
No working controllers found
Hit any key to stop autoboot: 0
switch to partitions #0, OK
mmc0 is current device
Scanning mmc 0:1...
Found U-Boot script /boot.scr
653 bytes read in 3 ms (211.9 KiB/s)
Executing script at 4fc00000
gpio: pin 114 (gpio 114) value is 1
220236 bytes read in 14 ms (15 MiB/s)
Uncompressed size: 10268672 = 0x9CB000
36162 bytes read in 5 ms (6.9 MiB/s)
1078500 bytes read in 50 ms (20.6 MiB/s)
Flattened Device Tree blob at 4fa00000
Booting using the fdt blob at 0x4fa00000
Loading Ramdisk to 49ef8000, end 49fff4e4 ... OK
Loading Device Tree to 0000000049eec000, end 0000000049ef7d41 ... OK
Starting kernel ...
HELLO NUTTX ON PINEPHONE!
- Ready to Boot CPU
- Boot from EL2
- Boot from EL1
- Boot to C runtime for OS Initialize
nx_start: Entry
up_allocate_heap: heap_start=0x0x40a4b000, heap_size=0x75b5000
arm64_gic_initialize: TODO: Init GIC for PinePhone
arm64_gic_initialize: CONFIG_GICD_BASE=0x1c81000
arm64_gic_initialize: CONFIG_GICR_BASE=0x1c82000
arm64_gic_initialize: GIC Version is 2
up_timer_initialize: up_timer_initialize: cp15 timer(s) running at 24.00MHz, cycle 24000
up_timer_initialize: _vector_table=0x400d7000
up_timer_initialize: Before writing: vbar_el1=0x40257000
up_timer_initialize: After writing: vbar_el1=0x400d7000
uart_register: Registering /dev/console
uart_register: Registering /dev/ttyS0
work_start_highpri: Starting high-priority kernel worker thread(s)
nx_start_application: Starting init thread
lib_cxx_initialize: _sinit: 0x400d7000 _einit: 0x400d7000 _stext: 0x40080000 _etext: 0x400d8000
nsh: sysinit: fopen failed: 2
nshn:x _msktfaarttf:s :C PcUo0m:m aBnedg innonti nfgo uInddl
e
L
oNoupt
t
Shell (NSH) NuttX-11.0.0-RC2
nsh> hello
task_spawn: name=hello entry=0x4009d490 file_actions=0x40a50580 attr=0x40a50588 argv=0x40a506d0
spawn_execattrs: Setting policy=2 priority=100 for pid=3
ABHello, World!!
ph_cfg1_reg=0x7177
ph_data_reg=0x400
pd_cfg2_reg=0x77711177
pd_data_reg=0x1c0000
tcon0_init: start
PLL_VIDEO0
0x1c20010 = 0x81006207 (DMB)
PLL_MIPI
0x1c20040 = 0xc00000 (DMB)
udelay 100
0x1c20040 = 0x80c0071a (DMB)
TCON0 source MIPI_PLL
0x1c20118 = 0x80000000 (DMB)
Clock on
0x1c20064 = 0x8 (DMB)
Reset off
0x1c202c4 = 0x8 (DMB)
Init lcdc: Disable tcon, Disable all interrupts
0x1c0c000 = 0x0 (DMB)
0x1c0c004 = 0x0
0x1c0c008 = 0x0
Set all io lines to tristate
0x1c0c08c = 0xffffffff
0x1c0c0f4 = 0xffffffff
mode set: DCLK = MIPI_PLL / 6
0x1c0c044 = 0x80000006
0x1c0c040 = 0x81000000
0x1c0c048 = 0x2cf059f
0x1c0c0f8 = 0x8
0x1c0c060 = 0x10010005
The datasheet says that this should be set higher than 20 * pixel cycle, but it's not clear what a pixel cycle is.
0x1c0c160 = 0x2f02cf
0x1c0c164 = 0x59f
0x1c0c168 = 0x1bc2000a
The Allwinner BSP has a comment that the period should be the display clock * 15, but uses an hardcoded 3000
0x1c0c1f0 = 0xbb80003
Enable the output on the pins
0x1c0c08c = 0xe0000000 (DMB)
enable tcon as a whole
setbits 0x1c0c000, 0x80000000 (DMB)
tcon0_init: end
dsi_init: start
display_board_init: start
assert reset: GPD(23), 0 // PD23 - LCD-RST (active low)
sunxi_gpio_set_cfgpin: pin=0x77, val=1
sunxi_gpio_set_cfgbank: bank_offset=119, val=1
clrsetbits 0x1c20874, 0xf0000000, 0x10000000
sunxi_gpio_output: pin=0x77, val=0
before: 0x1c2087c = 0x1c0000
after: 0x1c2087c = 0x1c0000 (DMB)
dldo1 3.3V
pmic_write: reg=0x15, val=0x1a
rsb_write: rt_addr=0x2d, reg_addr=0x15, value=0x1a
pmic_clrsetbits: reg=0x12, clr_mask=0x0, set_mask=0x8
rsb_read: rt_addr=0x2d, reg_addr=0x12
rsb_write: rt_addr=0x2d, reg_addr=0x12, value=0xd9
ldo_io0 3.3V
pmic_write: reg=0x91, val=0x1a
rsb_write: rt_addr=0x2d, reg_addr=0x91, value=0x1a
pmic_write: reg=0x90, val=0x3
rsb_write: rt_addr=0x2d, reg_addr=0x90, value=0x3
dldo2 1.8V
pmic_write: reg=0x16, val=0xb
rsb_write: rt_addr=0x2d, reg_addr=0x16, value=0xb
pmic_clrsetbits: reg=0x12, clr_mask=0x0, set_mask=0x10
rsb_read: rt_addr=0x2d, reg_addr=0x12
rsb_write: rt_addr=0x2d, reg_addr=0x12, value=0xd9
wait for power supplies and power-on init
udelay 15000
display_board_init: end
mipi dsi bus enable
setbits 0x1c20060, 0x2 (DMB)
setbits 0x1c202c0, 0x2 (DMB)
Enable the DSI block
struct reg_inst dsi_init_seq[] = {
.{ 0x0000, 0x00000001 }, // DMB
.{ 0x0010, 0x00030000 }, // DMB
.{ 0x0060, 0x0000000a }, // DMB
.{ 0x0078, 0x00000000 }, // DMB
inst_init
.{ 0x0020, 0x0000001f }, // DMB
.{ 0x0024, 0x10000001 }, // DMB
.{ 0x0028, 0x20000010 }, // DMB
.{ 0x002c, 0x2000000f }, // DMB
.{ 0x0030, 0x30100001 }, // DMB
.{ 0x0034, 0x40000010 }, // DMB
.{ 0x0038, 0x0000000f }, // DMB
.{ 0x003c, 0x5000001f }, // DMB
.{ 0x004c, 0x00560001 }, // DMB
.{ 0x02f8, 0x000000ff }, // DMB
get_video_start_delay
.{ 0x0014, 0x00005bc7 }, // DMB
setup_burst
.{ 0x007c, 0x10000007 }, // DMB
setup_inst_loop
.{ 0x0040, 0x30000002 }, // DMB
.{ 0x0044, 0x00310031 }, // DMB
.{ 0x0054, 0x00310031 }, // DMB
setup_format
.{ 0x0090, 0x1308703e }, // DMB
.{ 0x0098, 0x0000ffff }, // DMB
.{ 0x009c, 0xffffffff }, // DMB
.{ 0x0080, 0x00010008 }, // DMB
setup_timings
display_malloc: size=2330
.{ 0x000c, 0x00000000 }, // DMB
.{ 0x00b0, 0x12000021 }, // DMB
.{ 0x00b4, 0x01000031 }, // DMB
.{ 0x00b8, 0x07000001 }, // DMB
.{ 0x00bc, 0x14000011 }, // DMB
.{ 0x0018, 0x0011000a }, // DMB
.{ 0x001c, 0x05cd05a0 }, // DMB
.{ 0x00c0, 0x09004a19 }, // DMB
.{ 0x00c4, 0x50b40000 }, // DMB
.{ 0x00c8, 0x35005419 }, // DMB
.{ 0x00cc, 0x757a0000 }, // DMB
.{ 0x00d0, 0x09004a19 }, // DMB
.{ 0x00d4, 0x50b40000 }, // DMB
.{ 0x00e0, 0x0c091a19 }, // DMB
.{ 0x00e4, 0x72bd0000 }, // DMB
.{ 0x00e8, 0x1a000019 }, // DMB
.{ 0x00ec, 0xffff0000 }, // DMB
};
dphy_enable: start
150MHz (600 / 4)
0x1c20168 = 0x8203 (DMB)
0x1ca1004 = 0x10000000 (DMB)
0x1ca1010 = 0xa06000e (DMB)
0x1ca1014 = 0xa033207 (DMB)
0x1ca1018 = 0x1e (DMB)
0x1ca101c = 0x0 (DMB)
0x1ca1020 = 0x303 (DMB)
0x1ca1000 = 0x31 (DMB)
0x1ca104c = 0x9f007f00 (DMB)
0x1ca1050 = 0x17000000 (DMB)
0x1ca105c = 0x1f01555 (DMB)
0x1ca1054 = 0x2 (DMB)
udelay 5
0x1ca1058 = 0x3040000 (DMB)
udelay 1
update_bits 0x1ca1058, 0xf8000000, 0xf8000000 (DMB)
udelay 1
update_bits 0x1ca1058, 0x4000000, 0x4000000 (DMB)
udelay 1
update_bits 0x1ca1054, 0x10, 0x10 (DMB)
udelay 1
update_bits 0x1ca1050, 0x80000000, 0x80000000 (DMB)
update_bits 0x1ca1054, 0xf000000, 0xf000000 (DMB)
dphy_enable: end
deassert reset: GPD(23), 1 // PD23 - LCD-RST (active low)
sunxi_gpio_set_cfgpin: pin=0x77, val=1
sunxi_gpio_set_cfgbank: bank_offset=119, val=1
clrsetbits 0x1c20874, 0xf0000000, 0x10000000
sunxi_gpio_output: pin=0x77, val=1
before: 0x1c2087c = 0x1c0000
after: 0x1c2087c = 0x9c0000 (DMB)
wait for initialization
udelay 15000
struct reg_inst dsi_panel_init_seq[] = {
nuttx_panel_init
writeDcs: len=4
b9 f1 12 83
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=4
composeLongPacket: channel=0, cmd=0x39, len=4
packet: len=10
39 04 00 2c b9 f1 12 83
84 5d
modifyreg32: addr=0x300, val=0x2c000439
modifyreg32: addr=0x304, val=0x8312f1b9
modifyreg32: addr=0x308, val=0x00005d84
modifyreg32: addr=0x200, val=0x00000009
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=28
ba 33 81 05 f9 0e 0e 20
00 00 00 00 00 00 00 44
25 00 91 0a 00 00 02 4f
11 00 00 37
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=28
composeLongPacket: channel=0, cmd=0x39, len=28
packet: len=34
39 1c 00 2f ba 33 81 05
f9 0e 0e 20 00 00 00 00
00 00 00 44 25 00 91 0a
00 00 02 4f 11 00 00 37
2c e2
modifyreg32: addr=0x300, val=0x2f001c39
modifyreg32: addr=0x304, val=0x058133ba
modifyreg32: addr=0x308, val=0x200e0ef9
modifyreg32: addr=0x30c, val=0x00000000
modifyreg32: addr=0x310, val=0x44000000
modifyreg32: addr=0x314, val=0x0a910025
modifyreg32: addr=0x318, val=0x4f020000
modifyreg32: addr=0x31c, val=0x37000011
modifyreg32: addr=0x320, val=0x0000e22c
modifyreg32: addr=0x200, val=0x00000021
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=5
b8 25 22 20 03
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=5
composeLongPacket: channel=0, cmd=0x39, len=5
packet: len=11
39 05 00 36 b8 25 22 20
03 03 72
modifyreg32: addr=0x300, val=0x36000539
modifyreg32: addr=0x304, val=0x202225b8
modifyreg32: addr=0x308, val=0x00720303
modifyreg32: addr=0x200, val=0x0000000a
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=11
b3 10 10 05 05 03 ff 00
00 00 00
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=11
composeLongPacket: channel=0, cmd=0x39, len=11
packet: len=17
39 0b 00 2c b3 10 10 05
05 03 ff 00 00 00 00 6f
bc
modifyreg32: addr=0x300, val=0x2c000b39
modifyreg32: addr=0x304, val=0x051010b3
modifyreg32: addr=0x308, val=0x00ff0305
modifyreg32: addr=0x30c, val=0x6f000000
modifyreg32: addr=0x310, val=0x000000bc
modifyreg32: addr=0x200, val=0x00000010
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=10
c0 73 73 50 50 00 c0 08
70 00
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=10
composeLongPacket: channel=0, cmd=0x39, len=10
packet: len=16
39 0a 00 36 c0 73 73 50
50 00 c0 08 70 00 1b 6a
modifyreg32: addr=0x300, val=0x36000a39
modifyreg32: addr=0x304, val=0x507373c0
modifyreg32: addr=0x308, val=0x08c00050
modifyreg32: addr=0x30c, val=0x6a1b0070
modifyreg32: addr=0x200, val=0x0000000f
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=2
bc 4e
mipi_dsi_dcs_write: channel=0, cmd=0x15, len=2
composeShortPacket: channel=0, cmd=0x15, len=2
packet: len=4
15 bc 4e 35
modifyreg32: addr=0x300, val=0x354ebc15
modifyreg32: addr=0x200, val=0x00000003
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=2
cc 0b
mipi_dsi_dcs_write: channel=0, cmd=0x15, len=2
composeShortPacket: channel=0, cmd=0x15, len=2
packet: len=4
15 cc 0b 22
modifyreg32: addr=0x300, val=0x220bcc15
modifyreg32: addr=0x200, val=0x00000003
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=2
b4 80
mipi_dsi_dcs_write: channel=0, cmd=0x15, len=2
composeShortPacket: channel=0, cmd=0x15, len=2
packet: len=4
15 b4 80 22
modifyreg32: addr=0x300, val=0x2280b415
modifyreg32: addr=0x200, val=0x00000003
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=4
b2 f0 12 f0
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=4
composeLongPacket: channel=0, cmd=0x39, len=4
packet: len=10
39 04 00 2c b2 f0 12 f0
51 86
modifyreg32: addr=0x300, val=0x2c000439
modifyreg32: addr=0x304, val=0xf012f0b2
modifyreg32: addr=0x308, val=0x00008651
modifyreg32: addr=0x200, val=0x00000009
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=15
e3 00 00 0b 0b 10 10 00
00 00 00 ff 00 c0 10
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=15
composeLongPacket: channel=0, cmd=0x39, len=15
packet: len=21
39 0f 00 0f e3 00 00 0b
0b 10 10 00 00 00 00 ff
00 c0 10 36 0f
modifyreg32: addr=0x300, val=0x0f000f39
modifyreg32: addr=0x304, val=0x0b0000e3
modifyreg32: addr=0x308, val=0x0010100b
modifyreg32: addr=0x30c, val=0xff000000
modifyreg32: addr=0x310, val=0x3610c000
modifyreg32: addr=0x314, val=0x0000000f
modifyreg32: addr=0x200, val=0x00000014
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=6
c6 01 00 ff ff 00
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=6
composeLongPacket: channel=0, cmd=0x39, len=6
packet: len=12
39 06 00 30 c6 01 00 ff
ff 00 8e 25
modifyreg32: addr=0x300, val=0x30000639
modifyreg32: addr=0x304, val=0xff0001c6
modifyreg32: addr=0x308, val=0x258e00ff
modifyreg32: addr=0x200, val=0x0000000b
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=13
c1 74 00 32 32 77 f1 ff
ff cc cc 77 77
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=13
composeLongPacket: channel=0, cmd=0x39, len=13
packet: len=19
39 0d 00 13 c1 74 00 32
32 77 f1 ff ff cc cc 77
77 69 e4
modifyreg32: addr=0x300, val=0x13000d39
modifyreg32: addr=0x304, val=0x320074c1
modifyreg32: addr=0x308, val=0xfff17732
modifyreg32: addr=0x30c, val=0x77ccccff
modifyreg32: addr=0x310, val=0x00e46977
modifyreg32: addr=0x200, val=0x00000012
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=3
b5 07 07
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=3
composeLongPacket: channel=0, cmd=0x39, len=3
packet: len=9
39 03 00 09 b5 07 07 7b
b3
modifyreg32: addr=0x300, val=0x09000339
modifyreg32: addr=0x304, val=0x7b0707b5
modifyreg32: addr=0x308, val=0x000000b3
modifyreg32: addr=0x200, val=0x00000008
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=3
b6 2c 2c
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=3
composeLongPacket: channel=0, cmd=0x39, len=3
packet: len=9
39 03 00 09 b6 2c 2c 55
04
modifyreg32: addr=0x300, val=0x09000339
modifyreg32: addr=0x304, val=0x552c2cb6
modifyreg32: addr=0x308, val=0x00000004
modifyreg32: addr=0x200, val=0x00000008
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=4
bf 02 11 00
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=4
composeLongPacket: channel=0, cmd=0x39, len=4
packet: len=10
39 04 00 2c bf 02 11 00
b5 e9
modifyreg32: addr=0x300, val=0x2c000439
modifyreg32: addr=0x304, val=0x001102bf
modifyreg32: addr=0x308, val=0x0000e9b5
modifyreg32: addr=0x200, val=0x00000009
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=64
e9 82 10 06 05 a2 0a a5
12 31 23 37 83 04 bc 27
38 0c 00 03 00 00 00 0c
00 03 00 00 00 75 75 31
88 88 88 88 88 88 13 88
64 64 20 88 88 88 88 88
88 02 88 00 00 00 00 00
00 00 00 00 00 00 00 00
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=64
composeLongPacket: channel=0, cmd=0x39, len=64
packet: len=70
39 40 00 25 e9 82 10 06
05 a2 0a a5 12 31 23 37
83 04 bc 27 38 0c 00 03
00 00 00 0c 00 03 00 00
00 75 75 31 88 88 88 88
88 88 13 88 64 64 20 88
88 88 88 88 88 02 88 00
00 00 00 00 00 00 00 00
00 00 00 00 65 03
modifyreg32: addr=0x300, val=0x25004039
modifyreg32: addr=0x304, val=0x061082e9
modifyreg32: addr=0x308, val=0xa50aa205
modifyreg32: addr=0x30c, val=0x37233112
modifyreg32: addr=0x310, val=0x27bc0483
modifyreg32: addr=0x314, val=0x03000c38
modifyreg32: addr=0x318, val=0x0c000000
modifyreg32: addr=0x31c, val=0x00000300
modifyreg32: addr=0x320, val=0x31757500
modifyreg32: addr=0x324, val=0x88888888
modifyreg32: addr=0x328, val=0x88138888
modifyreg32: addr=0x32c, val=0x88206464
modifyreg32: addr=0x330, val=0x88888888
modifyreg32: addr=0x334, val=0x00880288
modifyreg32: addr=0x338, val=0x00000000
modifyreg32: addr=0x33c, val=0x00000000
modifyreg32: addr=0x340, val=0x00000000
modifyreg32: addr=0x344, val=0x00000365
modifyreg32: addr=0x200, val=0x00000045
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=62
ea 02 21 00 00 00 00 00
00 00 00 00 00 02 46 02
88 88 88 88 88 88 64 88
13 57 13 88 88 88 88 88
88 75 88 23 14 00 00 02
00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 03
0a a5 00 00 00 00
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=62
composeLongPacket: channel=0, cmd=0x39, len=62
packet: len=68
39 3e 00 1a ea 02 21 00
00 00 00 00 00 00 00 00
00 02 46 02 88 88 88 88
88 88 64 88 13 57 13 88
88 88 88 88 88 75 88 23
14 00 00 02 00 00 00 00
00 00 00 00 00 00 00 00
00 00 00 03 0a a5 00 00
00 00 24 1b
modifyreg32: addr=0x300, val=0x1a003e39
modifyreg32: addr=0x304, val=0x002102ea
modifyreg32: addr=0x308, val=0x00000000
modifyreg32: addr=0x30c, val=0x00000000
modifyreg32: addr=0x310, val=0x02460200
modifyreg32: addr=0x314, val=0x88888888
modifyreg32: addr=0x318, val=0x88648888
modifyreg32: addr=0x31c, val=0x88135713
modifyreg32: addr=0x320, val=0x88888888
modifyreg32: addr=0x324, val=0x23887588
modifyreg32: addr=0x328, val=0x02000014
modifyreg32: addr=0x32c, val=0x00000000
modifyreg32: addr=0x330, val=0x00000000
modifyreg32: addr=0x334, val=0x00000000
modifyreg32: addr=0x338, val=0x03000000
modifyreg32: addr=0x33c, val=0x0000a50a
modifyreg32: addr=0x340, val=0x1b240000
modifyreg32: addr=0x200, val=0x00000043
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=35
e0 00 09 0d 23 27 3c 41
35 07 0d 0e 12 13 10 12
12 18 00 09 0d 23 27 3c
41 35 07 0d 0e 12 13 10
12 12 18
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=35
composeLongPacket: channel=0, cmd=0x39, len=35
packet: len=41
39 23 00 20 e0 00 09 0d
23 27 3c 41 35 07 0d 0e
12 13 10 12 12 18 00 09
0d 23 27 3c 41 35 07 0d
0e 12 13 10 12 12 18 93
bf
modifyreg32: addr=0x300, val=0x20002339
modifyreg32: addr=0x304, val=0x0d0900e0
modifyreg32: addr=0x308, val=0x413c2723
modifyreg32: addr=0x30c, val=0x0e0d0735
modifyreg32: addr=0x310, val=0x12101312
modifyreg32: addr=0x314, val=0x09001812
modifyreg32: addr=0x318, val=0x3c27230d
modifyreg32: addr=0x31c, val=0x0d073541
modifyreg32: addr=0x320, val=0x1013120e
modifyreg32: addr=0x324, val=0x93181212
modifyreg32: addr=0x328, val=0x000000bf
modifyreg32: addr=0x200, val=0x00000028
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=1
11
mipi_dsi_dcs_write: channel=0, cmd=0x5, len=1
composeShortPacket: channel=0, cmd=0x5, len=1
packet: len=4
05 11 00 36
modifyreg32: addr=0x300, val=0x36001105
modifyreg32: addr=0x200, val=0x00000003
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=1
29
mipi_dsi_dcs_write: channel=0, cmd=0x5, len=1
composeShortPacket: channel=0, cmd=0x5, len=1
packet: len=4
05 29 00 1c
modifyreg32: addr=0x300, val=0x1c002905
modifyreg32: addr=0x200, val=0x00000003
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
};
dsi_start DSI_START_HSC
.{ 0x0048, 0x00000f02 }, // DMB
.{ MAGIC_COMMIT, 0 }, // DMB
dsi_update_bits: 0x01ca0020 : 0000001f -> (00000010) 00000000 (DMB)
udelay 1000
dsi_start DSI_START_HSD
.{ 0x0048, 0x63f07006 }, // DMB
.{ MAGIC_COMMIT, 0 }, // DMB
dsi_init: end
de2_init
Set SRAM for video use
0x1c00004 = 0x0 (DMB)
Setup DE2 PLL
clock_set_pll_de: clk=297000000
PLL10 rate = 24000000 * n / m
0x1c20048 = 0x81001701 (DMB)
while (!(readl(0x1c20048) & 0x10000000))
Enable DE2 special clock
clrsetbits 0x1c20104, 0x3000000, 0x81000000
Enable DE2 ahb
setbits 0x1c202c4, 0x1000
setbits 0x1c20064, 0x1000
Enable clock for mixer 0, set route MIXER0->TCON0
setbits 0x1000000, 0x1
setbits 0x1000008, 0x1
setbits 0x1000004, 0x1
clrbits 0x1000010, 0x1
Clear all registers
0x1100000 to 0x1105fff = 0x0
0x1120000 = 0x0
0x1130000 = 0x0
0x1140000 = 0x0
0x1150000 = 0x0
0x11a0000 = 0x0
0x11a2000 = 0x0
0x11a4000 = 0x0
0x11a6000 = 0x0
0x11a8000 = 0x0
0x11aa000 = 0x0
0x11b0000 = 0x0
Enable mixer
0x1100000 = 0x1 (DMB)
backlight_enable: pct=0x5a
1.0 has incorrectly documented non-presence of PH10, the circuit is in fact the same as on 1.1+
configure pwm: GPL(10), GPL_R_PWM
sunxi_gpio_set_cfgpin: pin=0x16a, val=2
sunxi_gpio_set_cfgbank: bank_offset=362, val=2
clrsetbits 0x1f02c04, 0xf00, 0x200
clrbits 0x1f03800, 0x40 (DMB)
0x1f03804 = 0x4af0437 (DMB)
0x1f03800 = 0x5f (DMB)
enable backlight: GPH(10), 1
sunxi_gpio_set_cfgpin: pin=0xea, val=1
sunxi_gpio_set_cfgbank: bank_offset=234, val=1
clrsetbits 0x1c20900, 0xf00, 0x100
sunxi_gpio_output: pin=0xea, val=1
before: 0x1c2090c = 0x400
after: 0x1c2090c = 0x400 (DMB)
test_render
initUiBlender
Configure Blender
<em>0x1101088 = 0xff000000
</em>0x1101084 = 0x0
initUiChannel
Channel 1: Set Overlay (720 x 1440)
<em>0x1103000 = 0xff000405
</em>0x1103010 = 0x400fd524
<em>0x110300c = 0xb40
</em>0x1103004 = 0x59f02cf
<em>0x1103088 = 0x59f02cf
</em>0x1103008 = 0x0
Channel 1: Set Blender Output
<em>0x110108c = 0x59f02cf
</em>0x110000c = 0x59f02cf
Channel 1: Set Blender Input Pipe 0 (720 x 1440)
<em>0x1101008 = 0x59f02cf
</em>0x1101004 = 0xff000000
<em>0x110100c = 0x0
</em>0x1101090 = 0x3010301
Channel 1: Disable Scaler
<em>0x1140000 = 0x0
initUiChannel
Channel 2: Set Overlay (600 x 600)
</em>0x1104000 = 0xff000005
<em>0x1104010 = 0x404f1d24
</em>0x110400c = 0x960
<em>0x1104004 = 0x2570257
</em>0x1104088 = 0x2570257
<em>0x1104008 = 0x0
Channel 2: Set Blender Input Pipe 1 (600 x 600)
</em>0x1101018 = 0x2570257
<em>0x1101014 = 0xff000000
</em>0x110101c = 0x340034
<em>0x1101094 = 0x3010301
Channel 2: Disable Scaler
</em>0x1150000 = 0x0
initUiChannel
Channel 3: Set Overlay (720 x 1440)
<em>0x1105000 = 0x7f000005
</em>0x1105010 = 0x40651624
<em>0x110500c = 0xb40
</em>0x1105004 = 0x59f02cf
<em>0x1105088 = 0x59f02cf
</em>0x1105008 = 0x0
Channel 3: Set Blender Input Pipe 2 (720 x 1440)
<em>0x1101028 = 0x59f02cf
</em>0x1101024 = 0xff000000
<em>0x110102c = 0x0
</em>0x1101098 = 0x3010301
Channel 3: Disable Scaler
<em>0x1160000 = 0x0
applySettings
Set BLD Route and BLD FColor Control
</em>0x1101080 = 0x321
<em>0x1101000 = 0x701
Apply Settings
</em>0x1100008 = 0x1
HELLO ZIG ON PINEPHONE!
Testing Compose Short Packet (Without Parameter)...
composeShortPacket: channel=0, cmd=0x5, len=1
Result:
05 11 00 36
Testing Compose Short Packet (With Parameter)...
composeShortPacket: channel=0, cmd=0x15, len=2
Result:
15 bc 4e 35
Testing Compose Long Packet...
composeLongPacket: channel=0, cmd=0x39, len=64
Result:
39 40 00 25 e9 82 10 06
05 a2 0a a5 12 31 23 37
83 04 bc 27 38 0c 00 03
00 00 00 0c 00 03 00 00
00 75 75 31 88 88 88 88
88 88 13 88 64 64 20 88
88 88 88 88 88 02 88 00
00 00 00 00 00 00 00 00
00 00 00 00 65 03
nsh>
nsh>
```
Testing Zig Display Engine Driver on QEMU
```text
+ aarch64-none-elf-gcc -v
Using built-in specs.
COLLECT_GCC=aarch64-none-elf-gcc
COLLECT_LTO_WRAPPER=/Applications/ArmGNUToolchain/11.3.rel1/aarch64-none-elf/bin/../libexec/gcc/aarch64-none-elf/11.3.1/lto-wrapper
Target: aarch64-none-elf
Configured with: /Volumes/data/jenkins/workspace/GNU-toolchain/arm-11/src/gcc/configure --target=aarch64-none-elf --prefix=/Volumes/data/jenkins/workspace/GNU-toolchain/arm-11/build-aarch64-none-elf/install --with-gmp=/Volumes/data/jenkins/workspace/GNU-toolchain/arm-11/build-aarch64-none-elf/host-tools --with-mpfr=/Volumes/data/jenkins/workspace/GNU-toolchain/arm-11/build-aarch64-none-elf/host-tools --with-mpc=/Volumes/data/jenkins/workspace/GNU-toolchain/arm-11/build-aarch64-none-elf/host-tools --with-isl=/Volumes/data/jenkins/workspace/GNU-toolchain/arm-11/build-aarch64-none-elf/host-tools --disable-shared --disable-nls --disable-threads --disable-tls --enable-checking=release --enable-languages=c,c++,fortran --with-newlib --with-gnu-as --with-gnu-ld --with-sysroot=/Volumes/data/jenkins/workspace/GNU-toolchain/arm-11/build-aarch64-none-elf/install/aarch64-none-elf --with-pkgversion='Arm GNU Toolchain 11.3.Rel1' --with-bugurl=https://bugs.linaro.org/
Thread model: single
Supported LTO compression algorithms: zlib
gcc version 11.3.1 20220712 (Arm GNU Toolchain 11.3.Rel1)
+ zig version
0.10.0-dev.2351+b64a1d5ab
+ build_zig
+ pushd ../pinephone-nuttx
~/gicv2/nuttx/pinephone-nuttx ~/gicv2/nuttx/nuttx
+ git pull
remote: Enumerating objects: 5, done.
remote: Counting objects: 100% (5/5), done.
remote: Compressing objects: 100% (1/1), done.
remote: Total 3 (delta 2), reused 3 (delta 2), pack-reused 0
Unpacking objects: 100% (3/3), done.
From https://github.com/lupyuen/pinephone-nuttx
4f24434..3bc128f main -> origin/main
Updating 4f24434..3bc128f
Fast-forward
render.zig | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
+ zig build-obj --verbose-cimport -target aarch64-freestanding-none -mcpu cortex_a53 -isystem /Users/Luppy/gicv2/nuttx/nuttx/include -I /Users/Luppy/gicv2/nuttx/apps/include render.zig
info(compilation): C import output: zig-cache/o/bdba45dc794911501be5991bbd50b924/cimport.zig
info(compilation): C import output: zig-cache/o/4d99b86faf008804574b7c60caf78668/cimport.zig
+ cp render.o /Users/Luppy/gicv2/nuttx/apps/examples/null/null_main.c.Users.Luppy.gicv2.nuttx.apps.examples.null.o
+ popd
~/gicv2/nuttx/nuttx
+ make -j
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/apps'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/libs/libxx'
make[1]: 'libxx.a' is up to date.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/libs/libxx'
make[2]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/builtin'
make[2]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/examples/null'
make[2]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/nshlib'
make[2]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/system/nsh'
make[2]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/platform'
make[2]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/system/system'
make[2]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/system/readline'
make[2]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/examples/hello'
make[2]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/testing/getprime'
make[2]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/testing/ostest'
make[2]: Nothing to be done for 'depend'.
make[2]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/testing/ostest'
make[2]: Nothing to be done for 'depend'.
make[2]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/examples/hello'
make[2]: Nothing to be done for 'depend'.
make[2]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/testing/getprime'
make[2]: Nothing to be done for 'depend'.
make[2]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/builtin'
make[2]: Nothing to be done for 'depend'.
make[2]: Nothing to be done for 'depend'.
make[2]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/platform'
make[2]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/system/system'
make[2]: Nothing to be done for 'depend'.
make[2]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/examples/null'
make[2]: Nothing to be done for 'depend'.
make[2]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/nshlib'
make[2]: Nothing to be done for 'depend'.
make[2]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/system/nsh'
make[2]: Nothing to be done for 'depend'.
make[2]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/system/readline'
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/sched'
make[1]: Nothing to be done for 'depend'.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/sched'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/drivers'
make[1]: Nothing to be done for 'depend'.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/drivers'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/boards'
make[1]: Nothing to be done for 'depend'.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/boards'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/arch/arm64/src'
make[1]: Nothing to be done for 'depend'.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/arch/arm64/src'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/fs'
make[1]: Nothing to be done for 'depend'.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/fs'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/binfmt'
make[1]: Nothing to be done for 'depend'.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/binfmt'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/libs/libc'
make[1]: Nothing to be done for 'depend'.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/libs/libc'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/mm'
make[1]: Nothing to be done for 'depend'.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/mm'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/libs/libxx'
make[1]: Nothing to be done for 'depend'.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/libs/libxx'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/sched'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/drivers'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/libs/libc'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/boards'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/mm'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/arch/arm64/src'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/apps'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/fs'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/binfmt'
make[1]: 'libboards.a' is up to date.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/boards'
make[1]: 'libdrivers.a' is up to date.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/drivers'
make[1]: 'libmm.a' is up to date.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/mm'
make[1]: 'libsched.a' is up to date.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/sched'
make[1]: 'libbinfmt.a' is up to date.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/binfmt'
make[1]: 'libfs.a' is up to date.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/fs'
rm -f /Users/Luppy/gicv2/nuttx/apps/libapps.a
make /Users/Luppy/gicv2/nuttx/apps/libapps.a
make[1]: 'libarch.a' is up to date.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/arch/arm64/src'
make[2]: Entering directory '/Users/Luppy/gicv2/nuttx/apps'
make[1]: 'libc.a' is up to date.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/libs/libc'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/builtin'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/system/readline'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/nshlib'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/examples/hello'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/platform'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/system/nsh'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/examples/null'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/testing/getprime'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/system/system'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/testing/ostest'
make[3]: Nothing to be done for 'all'.
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/platform'
make[3]: Nothing to be done for 'all'.
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/examples/null'
make[3]: Nothing to be done for 'all'.
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/system/readline'
make[3]: Nothing to be done for 'all'.
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/system/nsh'
make[3]: Nothing to be done for 'all'.
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/builtin'
make[3]: Nothing to be done for 'all'.
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/examples/hello'
make[3]: Nothing to be done for 'all'.
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/system/system'
make[3]: Nothing to be done for 'all'.
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/testing/getprime'
make[3]: Nothing to be done for 'all'.
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/nshlib'
make[3]: Nothing to be done for 'all'.
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/testing/ostest'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/builtin'
AR (add): libapps.a builtin_list.c.Users.Luppy.gicv2.nuttx.apps.builtin.o exec_builtin.c.Users.Luppy.gicv2.nuttx.apps.builtin.o
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/builtin'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/examples/hello'
AR (add): libapps.a hello_main.c.Users.Luppy.gicv2.nuttx.apps.examples.hello.o
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/examples/hello'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/examples/null'
AR (add): libapps.a null_main.c.Users.Luppy.gicv2.nuttx.apps.examples.null.o
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/examples/null'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/nshlib'
AR (add): libapps.a nsh_init.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_parse.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_console.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_script.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_system.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_command.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_fscmds.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_ddcmd.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_proccmds.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_mmcmds.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_timcmds.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_envcmds.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_syscmds.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_dbgcmds.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_session.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_fsutils.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_builtin.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_romfsetc.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_mntcmds.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_consolemain.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_printf.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_test.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/nshlib'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/platform'
AR (add): libapps.a dummy.c.Users.Luppy.gicv2.nuttx.apps.platform.o
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/platform'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/system/nsh'
AR (add): libapps.a nsh_main.c.Users.Luppy.gicv2.nuttx.apps.system.nsh.o sh_main.c.Users.Luppy.gicv2.nuttx.apps.system.nsh.o
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/system/nsh'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/system/readline'
AR (add): libapps.a readline.c.Users.Luppy.gicv2.nuttx.apps.system.readline.o readline_fd.c.Users.Luppy.gicv2.nuttx.apps.system.readline.o readline_common.c.Users.Luppy.gicv2.nuttx.apps.system.readline.o
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/system/readline'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/system/system'
AR (add): libapps.a system.c.Users.Luppy.gicv2.nuttx.apps.system.system.o
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/system/system'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/testing/getprime'
AR (add): libapps.a getprime_main.c.Users.Luppy.gicv2.nuttx.apps.testing.getprime.o
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/testing/getprime'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/testing/ostest'
AR (add): libapps.a getopt.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o dev_null.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o restart.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o sigprocmask.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o sighand.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o signest.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o fpu.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o setvbuf.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o tls.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o waitpid.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o cancel.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o cond.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o mutex.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o timedmutex.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o sem.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o semtimed.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o barrier.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o timedwait.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o pthread_rwlock.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o pthread_rwlock_cancel.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o specific.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o robust.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o roundrobin.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o mqueue.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o timedmqueue.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o posixtimer.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o vfork.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o ostest_main.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/testing/ostest'
make[2]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps'
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps'
IN: /Users/Luppy/gicv2/nuttx/apps/libapps.a -> staging/libapps.a
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/arch/arm64/src'
make[2]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/boards/arm64/qemu/qemu-a53/src'
make[2]: 'libboard.a' is up to date.
make[2]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/boards/arm64/qemu/qemu-a53/src'
LD: nuttx
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/arch/arm64/src'
CP: nuttx.hex
CP: nuttx.bin
+ aarch64-none-elf-size nuttx
text data bss dec hex filename
273955 12624 9782904 10069483 99a5eb nuttx
+ aarch64-none-elf-objdump -t -S --demangle --line-numbers --wide nuttx
+ qemu-system-aarch64 -smp 4 -cpu cortex-a53 -nographic -machine virt,virtualization=on,gic-version=2 -net none -chardev stdio,id=con,mux=on -serial chardev:con -mon chardev=con,mode=readline -kernel ./nuttx
- Ready to Boot CPU
- Boot from EL2
- Boot from EL1
- Boot to C runtime for OS Initialize
nx_start: Entry
up_allocate_heap: heap_start=0x0x40c1d000, heap_size=0x73e3000
arm64_gic_initialize: TODO: Init GIC for PinePhone
arm64_gic_initialize: CONFIG_GICD_BASE=0x8000000
arm64_gic_initialize: CONFIG_GICR_BASE=0x8010000
arm64_gic_initialize: GIC Version is 2
up_timer_initialize: up_timer_initialize: cp15 timer(s) running at 62.50MHz, cycle 62500
up_timer_initialize: _vector_table=0x402b5000
up_timer_initialize: Before writing: vbar_el1=0x402b5000
up_timer_initialize: After writing: vbar_el1=0x402b5000
uart_register: Registering /dev/console
uart_register: Registering /dev/ttyS0
work_start_highpri: Starting high-priority kernel worker thread(s)
nx_start_application: Starting init thread
lib_cxx_initialize: _sinit: 0x402b5000 _einit: 0x402b5000 _stext: 0x40280000 _etext: 0x402b6000
nsh: sysinit: fopen failed: 2
nsh: mkfatfs: command not found
NuttShell (NSH) NuttX-11.0.0-RC2
nsh> nx_start: CPU0: Beginning Idle Loop
nsh> hello
task_spawn: name=hello entry=0x4029b35c file_actions=0x40c22580 attr=0x40c22588 argv=0x40c226d0
spawn_execattrs: Setting policy=2 priority=100 for pid=3
Hello, World!!
test_render
initUiBlender
Configure Blender
<em>0x1101088 = 0xff000000
</em>0x1101084 = 0x0
initUiChannel
Channel 1: Set Overlay (720 x 1440)
<em>0x1103000 = 0xff000405
</em>0x1103010 = 0x402cf808
<em>0x110300c = 0xb40
</em>0x1103004 = 0x59f02cf
<em>0x1103088 = 0x59f02cf
</em>0x1103008 = 0x0
Channel 1: Set Blender Output
<em>0x110108c = 0x59f02cf
</em>0x110000c = 0x59f02cf
Channel 1: Set Blender Input Pipe 0 (720 x 1440)
<em>0x1101008 = 0x59f02cf
</em>0x1101004 = 0xff000000
<em>0x110100c = 0x0
</em>0x1101090 = 0x3010301
Channel 1: Disable Scaler
<em>0x1140000 = 0x0
initUiChannel
Channel 2: Set Overlay (600 x 600)
</em>0x1104000 = 0xff000005
<em>0x1104010 = 0x406c4008
</em>0x110400c = 0x960
<em>0x1104004 = 0x2570257
</em>0x1104088 = 0x2570257
<em>0x1104008 = 0x0
Channel 2: Set Blender Input Pipe 1 (600 x 600)
</em>0x1101018 = 0x2570257
<em>0x1101014 = 0xff000000
</em>0x110101c = 0x340034
<em>0x1101094 = 0x3010301
Channel 2: Disable Scaler
</em>0x1150000 = 0x0
initUiChannel
Channel 3: Set Overlay (720 x 1440)
<em>0x1105000 = 0x7f000005
</em>0x1105010 = 0x40823908
<em>0x110500c = 0xb40
</em>0x1105004 = 0x59f02cf
<em>0x1105088 = 0x59f02cf
</em>0x1105008 = 0x0
Channel 3: Set Blender Input Pipe 2 (720 x 1440)
<em>0x1101028 = 0x59f02cf
</em>0x1101024 = 0xff000000
<em>0x110102c = 0x0
</em>0x1101098 = 0x3010301
Channel 3: Disable Scaler
<em>0x1160000 = 0x0
applySettings
Set BLD Route and BLD FColor Control
</em>0x1101080 = 0x321
<em>0x1101000 = 0x701
Apply Settings
</em>0x1100008 = 0x1
nsh> qemu-system-aarch64: terminating on signal 2 from pid 93762 ()
* Terminal will be reused by tasks, press any key to close it.
```
Testing p-boot Display Engine on PinePhone
```text
DRAM: 2048 MiB
Trying to boot from MMC1
NOTICE: BL31: v2.2(release):v2.2-904-gf9ea3a629
NOTICE: BL31: Built : 15:32:12, Apr 9 2020
NOTICE: BL31: Detected Allwinner A64/H64/R18 SoC (1689)
NOTICE: BL31: Found U-Boot DTB at 0x4064410, model: PinePhone
NOTICE: PSCI: System suspend is unavailable
U-Boot 2020.07 (Nov 08 2020 - 00:15:12 +0100)
DRAM: 2 GiB
MMC: Device 'mmc@1c11000': seq 1 is in use by 'mmc@1c10000'
mmc@1c0f000: 0, mmc@1c10000: 2, mmc@1c11000: 1
Loading Environment from FAT... *** Warning - bad CRC, using default environment
starting USB...
No working controllers found
Hit any key to stop autoboot: 0
switch to partitions #0, OK
mmc0 is current device
Scanning mmc 0:1...
Found U-Boot script /boot.scr
653 bytes read in 3 ms (211.9 KiB/s)
Executing script at 4fc00000
gpio: pin 114 (gpio 114) value is 1
214451 bytes read in 12 ms (17 MiB/s)
Uncompressed size: 10240000 = 0x9C4000
36162 bytes read in 4 ms (8.6 MiB/s)
1078500 bytes read in 51 ms (20.2 MiB/s)
Flattened Device Tree blob at 4fa00000
Booting using the fdt blob at 0x4fa00000
Loading Ramdisk to 49ef8000, end 49fff4e4 ... OK
Loading Device Tree to 0000000049eec000, end 0000000049ef7d41 ... OK
Starting kernel ...
HELLO NUTTX ON PINEPHONE!
- Ready to Boot CPU
- Boot from EL2
- Boot from EL1
- Boot to C runtime for OS Initialize
nx_start: Entry
up_allocate_heap: heap_start=0x0x40a44000, heap_size=0x75bc000
arm64_gic_initialize: TODO: Init GIC for PinePhone
arm64_gic_initialize: CONFIG_GICD_BASE=0x1c81000
arm64_gic_initialize: CONFIG_GICR_BASE=0x1c82000
arm64_gic_initialize: GIC Version is 2
up_timer_initialize: up_timer_initialize: cp15 timer(s) running at 24.00MHz, cycle 24000
up_timer_initialize: _vector_table=0x400d2000
up_timer_initialize: Before writing: vbar_el1=0x40252000
up_timer_initialize: After writing: vbar_el1=0x400d2000
uart_register: Registering /dev/console
uart_register: Registering /dev/ttyS0
work_start_highpri: Starting high-priority kernel worker thread(s)
nx_start_application: Starting init thread
lib_cxx_initialize: _sinit: 0x400d2000 _einit: 0x400d2000 _stext: 0x40080000 _etext: 0x400d3000
nsh: sysinit: fopen failed: 2
nshn:x _msktfaarttf:s :C PcUo0m:m aBnedg innonti nfgo uInddl
e
L
oNoupt
t
Shell (NSH) NuttX-11.0.0-RC2
nsh> hello
task_spawn: name=hello entry=0x4009d2fc file_actions=0x40a49580 attr=0x40a49588 argv=0x40a496d0
spawn_execattrs: Setting policy=2 priority=100 for pid=3
ABHello, World!!
ph_cfg1_reg=0x7177
ph_data_reg=0x400
pd_cfg2_reg=0x77711177
pd_data_reg=0x1c0000
struct reg_inst dsi_init_seq[] = {
.{ 0x0000, 0x00000001 },
.{ 0x0010, 0x00030000 },
.{ 0x0060, 0x0000000a },
.{ 0x0078, 0x00000000 },
.{ 0x0020, 0x0000001f },
.{ 0x0024, 0x10000001 },
.{ 0x0028, 0x20000010 },
.{ 0x002c, 0x2000000f },
.{ 0x0030, 0x30100001 },
.{ 0x0034, 0x40000010 },
.{ 0x0038, 0x0000000f },
.{ 0x003c, 0x5000001f },
.{ 0x004c, 0x00560001 },
.{ 0x02f8, 0x000000ff },
.{ 0x0014, 0x00005bc7 },
.{ 0x007c, 0x10000007 },
.{ 0x0040, 0x30000002 },
.{ 0x0044, 0x00310031 },
.{ 0x0054, 0x00310031 },
.{ 0x0090, 0x1308703e },
.{ 0x0098, 0x0000ffff },
.{ 0x009c, 0xffffffff },
.{ 0x0080, 0x00010008 },
display_malloc: size=2330
.{ 0x000c, 0x00000000 },
.{ 0x00b0, 0x12000021 },
.{ 0x00b4, 0x01000031 },
.{ 0x00b8, 0x07000001 },
.{ 0x00bc, 0x14000011 },
.{ 0x0018, 0x0011000a },
.{ 0x001c, 0x05cd05a0 },
.{ 0x00c0, 0x09004a19 },
.{ 0x00c4, 0x50b40000 },
.{ 0x00c8, 0x35005419 },
.{ 0x00cc, 0x757a0000 },
.{ 0x00d0, 0x09004a19 },
.{ 0x00d4, 0x50b40000 },
.{ 0x00e0, 0x0c091a19 },
.{ 0x00e4, 0x72bd0000 },
.{ 0x00e8, 0x1a000019 },
.{ 0x00ec, 0xffff0000 },
};
struct reg_inst dsi_panel_init_seq[] = {
nuttx_panel_init
writeDcs: len=4
b9 f1 12 83
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=4
composeLongPacket: channel=0, cmd=0x39, len=4
packet: len=10
39 04 00 2c b9 f1 12 83
84 5d
modifyreg32: addr=0x300, val=0x2c000439
modifyreg32: addr=0x304, val=0x8312f1b9
modifyreg32: addr=0x308, val=0x00005d84
modifyreg32: addr=0x200, val=0x00000009
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=28
ba 33 81 05 f9 0e 0e 20
00 00 00 00 00 00 00 44
25 00 91 0a 00 00 02 4f
11 00 00 37
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=28
composeLongPacket: channel=0, cmd=0x39, len=28
packet: len=34
39 1c 00 2f ba 33 81 05
f9 0e 0e 20 00 00 00 00
00 00 00 44 25 00 91 0a
00 00 02 4f 11 00 00 37
2c e2
modifyreg32: addr=0x300, val=0x2f001c39
modifyreg32: addr=0x304, val=0x058133ba
modifyreg32: addr=0x308, val=0x200e0ef9
modifyreg32: addr=0x30c, val=0x00000000
modifyreg32: addr=0x310, val=0x44000000
modifyreg32: addr=0x314, val=0x0a910025
modifyreg32: addr=0x318, val=0x4f020000
modifyreg32: addr=0x31c, val=0x37000011
modifyreg32: addr=0x320, val=0x0000e22c
modifyreg32: addr=0x200, val=0x00000021
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=5
b8 25 22 20 03
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=5
composeLongPacket: channel=0, cmd=0x39, len=5
packet: len=11
39 05 00 36 b8 25 22 20
03 03 72
modifyreg32: addr=0x300, val=0x36000539
modifyreg32: addr=0x304, val=0x202225b8
modifyreg32: addr=0x308, val=0x00720303
modifyreg32: addr=0x200, val=0x0000000a
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=11
b3 10 10 05 05 03 ff 00
00 00 00
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=11
composeLongPacket: channel=0, cmd=0x39, len=11
packet: len=17
39 0b 00 2c b3 10 10 05
05 03 ff 00 00 00 00 6f
bc
modifyreg32: addr=0x300, val=0x2c000b39
modifyreg32: addr=0x304, val=0x051010b3
modifyreg32: addr=0x308, val=0x00ff0305
modifyreg32: addr=0x30c, val=0x6f000000
modifyreg32: addr=0x310, val=0x000000bc
modifyreg32: addr=0x200, val=0x00000010
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=10
c0 73 73 50 50 00 c0 08
70 00
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=10
composeLongPacket: channel=0, cmd=0x39, len=10
packet: len=16
39 0a 00 36 c0 73 73 50
50 00 c0 08 70 00 1b 6a
modifyreg32: addr=0x300, val=0x36000a39
modifyreg32: addr=0x304, val=0x507373c0
modifyreg32: addr=0x308, val=0x08c00050
modifyreg32: addr=0x30c, val=0x6a1b0070
modifyreg32: addr=0x200, val=0x0000000f
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=2
bc 4e
mipi_dsi_dcs_write: channel=0, cmd=0x15, len=2
composeShortPacket: channel=0, cmd=0x15, len=2
packet: len=4
15 bc 4e 35
modifyreg32: addr=0x300, val=0x354ebc15
modifyreg32: addr=0x200, val=0x00000003
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=2
cc 0b
mipi_dsi_dcs_write: channel=0, cmd=0x15, len=2
composeShortPacket: channel=0, cmd=0x15, len=2
packet: len=4
15 cc 0b 22
modifyreg32: addr=0x300, val=0x220bcc15
modifyreg32: addr=0x200, val=0x00000003
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=2
b4 80
mipi_dsi_dcs_write: channel=0, cmd=0x15, len=2
composeShortPacket: channel=0, cmd=0x15, len=2
packet: len=4
15 b4 80 22
modifyreg32: addr=0x300, val=0x2280b415
modifyreg32: addr=0x200, val=0x00000003
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=4
b2 f0 12 f0
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=4
composeLongPacket: channel=0, cmd=0x39, len=4
packet: len=10
39 04 00 2c b2 f0 12 f0
51 86
modifyreg32: addr=0x300, val=0x2c000439
modifyreg32: addr=0x304, val=0xf012f0b2
modifyreg32: addr=0x308, val=0x00008651
modifyreg32: addr=0x200, val=0x00000009
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=15
e3 00 00 0b 0b 10 10 00
00 00 00 ff 00 c0 10
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=15
composeLongPacket: channel=0, cmd=0x39, len=15
packet: len=21
39 0f 00 0f e3 00 00 0b
0b 10 10 00 00 00 00 ff
00 c0 10 36 0f
modifyreg32: addr=0x300, val=0x0f000f39
modifyreg32: addr=0x304, val=0x0b0000e3
modifyreg32: addr=0x308, val=0x0010100b
modifyreg32: addr=0x30c, val=0xff000000
modifyreg32: addr=0x310, val=0x3610c000
modifyreg32: addr=0x314, val=0x0000000f
modifyreg32: addr=0x200, val=0x00000014
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=6
c6 01 00 ff ff 00
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=6
composeLongPacket: channel=0, cmd=0x39, len=6
packet: len=12
39 06 00 30 c6 01 00 ff
ff 00 8e 25
modifyreg32: addr=0x300, val=0x30000639
modifyreg32: addr=0x304, val=0xff0001c6
modifyreg32: addr=0x308, val=0x258e00ff
modifyreg32: addr=0x200, val=0x0000000b
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=13
c1 74 00 32 32 77 f1 ff
ff cc cc 77 77
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=13
composeLongPacket: channel=0, cmd=0x39, len=13
packet: len=19
39 0d 00 13 c1 74 00 32
32 77 f1 ff ff cc cc 77
77 69 e4
modifyreg32: addr=0x300, val=0x13000d39
modifyreg32: addr=0x304, val=0x320074c1
modifyreg32: addr=0x308, val=0xfff17732
modifyreg32: addr=0x30c, val=0x77ccccff
modifyreg32: addr=0x310, val=0x00e46977
modifyreg32: addr=0x200, val=0x00000012
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=3
b5 07 07
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=3
composeLongPacket: channel=0, cmd=0x39, len=3
packet: len=9
39 03 00 09 b5 07 07 7b
b3
modifyreg32: addr=0x300, val=0x09000339
modifyreg32: addr=0x304, val=0x7b0707b5
modifyreg32: addr=0x308, val=0x000000b3
modifyreg32: addr=0x200, val=0x00000008
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=3
b6 2c 2c
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=3
composeLongPacket: channel=0, cmd=0x39, len=3
packet: len=9
39 03 00 09 b6 2c 2c 55
04
modifyreg32: addr=0x300, val=0x09000339
modifyreg32: addr=0x304, val=0x552c2cb6
modifyreg32: addr=0x308, val=0x00000004
modifyreg32: addr=0x200, val=0x00000008
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=4
bf 02 11 00
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=4
composeLongPacket: channel=0, cmd=0x39, len=4
packet: len=10
39 04 00 2c bf 02 11 00
b5 e9
modifyreg32: addr=0x300, val=0x2c000439
modifyreg32: addr=0x304, val=0x001102bf
modifyreg32: addr=0x308, val=0x0000e9b5
modifyreg32: addr=0x200, val=0x00000009
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=64
e9 82 10 06 05 a2 0a a5
12 31 23 37 83 04 bc 27
38 0c 00 03 00 00 00 0c
00 03 00 00 00 75 75 31
88 88 88 88 88 88 13 88
64 64 20 88 88 88 88 88
88 02 88 00 00 00 00 00
00 00 00 00 00 00 00 00
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=64
composeLongPacket: channel=0, cmd=0x39, len=64
packet: len=70
39 40 00 25 e9 82 10 06
05 a2 0a a5 12 31 23 37
83 04 bc 27 38 0c 00 03
00 00 00 0c 00 03 00 00
00 75 75 31 88 88 88 88
88 88 13 88 64 64 20 88
88 88 88 88 88 02 88 00
00 00 00 00 00 00 00 00
00 00 00 00 65 03
modifyreg32: addr=0x300, val=0x25004039
modifyreg32: addr=0x304, val=0x061082e9
modifyreg32: addr=0x308, val=0xa50aa205
modifyreg32: addr=0x30c, val=0x37233112
modifyreg32: addr=0x310, val=0x27bc0483
modifyreg32: addr=0x314, val=0x03000c38
modifyreg32: addr=0x318, val=0x0c000000
modifyreg32: addr=0x31c, val=0x00000300
modifyreg32: addr=0x320, val=0x31757500
modifyreg32: addr=0x324, val=0x88888888
modifyreg32: addr=0x328, val=0x88138888
modifyreg32: addr=0x32c, val=0x88206464
modifyreg32: addr=0x330, val=0x88888888
modifyreg32: addr=0x334, val=0x00880288
modifyreg32: addr=0x338, val=0x00000000
modifyreg32: addr=0x33c, val=0x00000000
modifyreg32: addr=0x340, val=0x00000000
modifyreg32: addr=0x344, val=0x00000365
modifyreg32: addr=0x200, val=0x00000045
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=62
ea 02 21 00 00 00 00 00
00 00 00 00 00 02 46 02
88 88 88 88 88 88 64 88
13 57 13 88 88 88 88 88
88 75 88 23 14 00 00 02
00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 03
0a a5 00 00 00 00
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=62
composeLongPacket: channel=0, cmd=0x39, len=62
packet: len=68
39 3e 00 1a ea 02 21 00
00 00 00 00 00 00 00 00
00 02 46 02 88 88 88 88
88 88 64 88 13 57 13 88
88 88 88 88 88 75 88 23
14 00 00 02 00 00 00 00
00 00 00 00 00 00 00 00
00 00 00 03 0a a5 00 00
00 00 24 1b
modifyreg32: addr=0x300, val=0x1a003e39
modifyreg32: addr=0x304, val=0x002102ea
modifyreg32: addr=0x308, val=0x00000000
modifyreg32: addr=0x30c, val=0x00000000
modifyreg32: addr=0x310, val=0x02460200
modifyreg32: addr=0x314, val=0x88888888
modifyreg32: addr=0x318, val=0x88648888
modifyreg32: addr=0x31c, val=0x88135713
modifyreg32: addr=0x320, val=0x88888888
modifyreg32: addr=0x324, val=0x23887588
modifyreg32: addr=0x328, val=0x02000014
modifyreg32: addr=0x32c, val=0x00000000
modifyreg32: addr=0x330, val=0x00000000
modifyreg32: addr=0x334, val=0x00000000
modifyreg32: addr=0x338, val=0x03000000
modifyreg32: addr=0x33c, val=0x0000a50a
modifyreg32: addr=0x340, val=0x1b240000
modifyreg32: addr=0x200, val=0x00000043
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=35
e0 00 09 0d 23 27 3c 41
35 07 0d 0e 12 13 10 12
12 18 00 09 0d 23 27 3c
41 35 07 0d 0e 12 13 10
12 12 18
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=35
composeLongPacket: channel=0, cmd=0x39, len=35
packet: len=41
39 23 00 20 e0 00 09 0d
23 27 3c 41 35 07 0d 0e
12 13 10 12 12 18 00 09
0d 23 27 3c 41 35 07 0d
0e 12 13 10 12 12 18 93
bf
modifyreg32: addr=0x300, val=0x20002339
modifyreg32: addr=0x304, val=0x0d0900e0
modifyreg32: addr=0x308, val=0x413c2723
modifyreg32: addr=0x30c, val=0x0e0d0735
modifyreg32: addr=0x310, val=0x12101312
modifyreg32: addr=0x314, val=0x09001812
modifyreg32: addr=0x318, val=0x3c27230d
modifyreg32: addr=0x31c, val=0x0d073541
modifyreg32: addr=0x320, val=0x1013120e
modifyreg32: addr=0x324, val=0x93181212
modifyreg32: addr=0x328, val=0x000000bf
modifyreg32: addr=0x200, val=0x00000028
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=1
11
mipi_dsi_dcs_write: channel=0, cmd=0x5, len=1
composeShortPacket: channel=0, cmd=0x5, len=1
packet: len=4
05 11 00 36
modifyreg32: addr=0x300, val=0x36001105
modifyreg32: addr=0x200, val=0x00000003
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=1
29
mipi_dsi_dcs_write: channel=0, cmd=0x5, len=1
composeShortPacket: channel=0, cmd=0x5, len=1
packet: len=4
05 29 00 1c
modifyreg32: addr=0x300, val=0x1c002905
modifyreg32: addr=0x200, val=0x00000003
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
};
.{ 0x0048, 0x00000f02 },
.{ MAGIC_COMMIT, 0 },
dsi_update_bits: 0x01ca0020 : 0000001f -> (00000010) 00000000
.{ 0x0048, 0x63f07006 },
.{ MAGIC_COMMIT, 0 },
Framebuffers:
fb0=0x4064a6ac, len=0xfd200
fb1=0x404eadac, len=0x57e40
fb2=0x400f65ac, len=0xfd200
display_commit
Configure Blender
BLD BkColor: 0x1101088 = 0xff000000
BLD Premultiply: 0x1101084 = 0x0
Channel 1: Set Overlay
UI Config Attr: 0x1103000 = 0xff000405
UI Config Top LAddr: 0x1103010 = 0x4064a6ac
UI Config Pitch: 0x110300c = 0xb40
UI Config Size: 0x1103004 = 0x59f02cf
UI Overlay Size: 0x1103088 = 0x59f02cf
IO Config Coord: 0x1103008 = 0x0
Channel 1: Set Blender Output
BLD Output Size: 0x110108c = 0x59f02cf
GLB Size: 0x110000c = 0x59f02cf
Channel 1: Set Blender Input Pipe 0
BLD Pipe InSize: 0x1101008 = 0x59f02cf
BLD Pipe FColor: 0x1101004 = 0xff000000
BLD Pipe Offset: 0x110100c = 0x0
BLD Pipe Mode: 0x1101090 = 0x3010301
Channel 1: Disable Scaler
Mixer: 0x1140000 = 0x0
Channel 2: Set Overlay
UI Config Attr: 0x1104000 = 0xff000005
UI Config Top LAddr: 0x1104010 = 0x404eadac
UI Config Pitch: 0x110400c = 0x960
UI Config Size: 0x1104004 = 0x2570257
UI Overlay Size: 0x1104088 = 0x2570257
IO Config Coord: 0x1104008 = 0x0
Channel 2: Set Blender Input Pipe 1
BLD Pipe InSize: 0x1101018 = 0x2570257
BLD Pipe FColor: 0x1101014 = 0xff000000
BLD Pipe Offset: 0x110101c = 0x340034
BLD Pipe Mode: 0x1101094 = 0x3010301
Channel 2: Disable Scaler
Mixer: 0x1150000 = 0x0
Channel 3: Set Overlay
UI Config Attr: 0x1105000 = 0xff000005
UI Config Top LAddr: 0x1105010 = 0x400f65ac
UI Config Pitch: 0x110500c = 0xb40
UI Config Size: 0x1105004 = 0x59f02cf
UI Overlay Size: 0x1105088 = 0x59f02cf
IO Config Coord: 0x1105008 = 0x0
Channel 3: Set Blender Input Pipe 2
BLD Pipe InSize: 0x1101028 = 0x59f02cf
BLD Pipe FColor: 0x1101024 = 0xff000000
BLD Pipe Offset: 0x110102c = 0x0
BLD Pipe Mode: 0x1101098 = 0x3010301
Channel 3: Disable Scaler
Mixer: 0x1160000 = 0x0
Set BLD Route and BLD FColor Control
BLD Route: 0x1101080 = 0x321 (DMB)
BLD FColor Control: 0x1101000 = 0x701 (DMB)
Apply Settings
GLB DBuff: 0x1100008 = 0x1 (DMB)
```
If we enable Channel 1 and disable Channels 2 and 3...
```text
display_commit
Configure Blender
BLD BkColor: 0x1101088 = 0xff000000
BLD Premultiply: 0x1101084 = 0x0
Channel 1: Set Overlay
UI Config Attr: 0x1103000 = 0xff000405
UI Config Top LAddr: 0x1103010 = 0x400f65ac
UI Config Pitch: 0x110300c = 0xb40
UI Config Size: 0x1103004 = 0x59f02cf
UI Overlay Size: 0x1103088 = 0x59f02cf
IO Config Coord: 0x1103008 = 0x0
Channel 1: Set Blender Output
BLD Output Size: 0x110108c = 0x59f02cf
GLB Size: 0x110000c = 0x59f02cf
Channel 1: Set Blender Input Pipe 0
BLD Pipe InSize: 0x1101008 = 0x59f02cf
BLD Pipe FColor: 0x1101004 = 0xff000000
BLD Pipe Offset: 0x110100c = 0x0
BLD Pipe Mode: 0x1101090 = 0x3010301
Channel 1: Disable Scaler
Mixer: 0x1140000 = 0x0
Channel 2: Disable Overlay and Pipe
UI Config Attr: 0x1104000 = 0x0
Channel 2: Disable Scaler
Mixer: 0x1150000 = 0x0
Channel 3: Disable Overlay and Pipe
UI Config Attr: 0x1105000 = 0x0
Channel 3: Disable Scaler
Mixer: 0x1160000 = 0x0
Set BLD Route and BLD FColor Control
BLD Route: 0x1101080 = 0x1
BLD FColor Control: 0x1101000 = 0x101
Apply Settings
GLB DBuff: 0x1100008 = 0x1
```
Testing NuttX Zig Driver for MIPI DSI on PinePhone
Testing our <a>NuttX Zig Driver for MIPI DSI</a> on PinePhone...
(Screen lights up and shows a test pattern)
```text
DRAM: 2048 MiB
Trying to boot from MMC1
NOTICE: BL31: v2.2(release):v2.2-904-gf9ea3a629
NOTICE: BL31: Built : 15:32:12, Apr 9 2020
NOTICE: BL31: Detected Allwinner A64/H64/R18 SoC (1689)
NOTICE: BL31: Found U-Boot DTB at 0x4064410, model: PinePhone
NOTICE: PSCI: System suspend is unavailable
U-Boot 2020.07 (Nov 08 2020 - 00:15:12 +0100)
DRAM: 2 GiB
MMC: Device 'mmc@1c11000': seq 1 is in use by 'mmc@1c10000'
mmc@1c0f000: 0, mmc@1c10000: 2, mmc@1c11000: 1
Loading Environment from FAT... *** Warning - bad CRC, using default environment
starting USB...
No working controllers found
Hit any key to stop autoboot: 0
switch to partitions #0, OK
mmc0 is current device
Scanning mmc 0:1...
Found U-Boot script /boot.scr
653 bytes read in 3 ms (211.9 KiB/s)
Executing script at 4fc00000
gpio: pin 114 (gpio 114) value is 1
207379 bytes read in 13 ms (15.2 MiB/s)
Uncompressed size: 4653056 = 0x470000
36162 bytes read in 4 ms (8.6 MiB/s)
1078500 bytes read in 50 ms (20.6 MiB/s)
Flattened Device Tree blob at 4fa00000
Booting using the fdt blob at 0x4fa00000
Loading Ramdisk to 49ef8000, end 49fff4e4 ... OK
Loading Device Tree to 0000000049eec000, end 0000000049ef7d41 ... OK
Starting kernel ...
HELLO NUTTX ON PINEPHONE!
- Ready to Boot CPU
- Boot from EL2
- Boot from EL1
- Boot to C runtime for OS Initialize
nx_start: Entry
up_allocate_heap: heap_start=0x0x404f0000, heap_size=0x7b10000
arm64_gic_initialize: TODO: Init GIC for PinePhone
arm64_gic_initialize: CONFIG_GICD_BASE=0x1c81000
arm64_gic_initialize: CONFIG_GICR_BASE=0x1c82000
arm64_gic_initialize: GIC Version is 2
up_timer_initialize: up_timer_initialize: cp15 timer(s) running at 24.00MHz, cycle 24000
up_timer_initialize: _vector_table=0x400d2000
up_timer_initialize: Before writing: vbar_el1=0x40252000
up_timer_initialize: After writing: vbar_el1=0x400d2000
uart_register: Registering /dev/console
uart_register: Registering /dev/ttyS0
work_start_highpri: Starting high-priority kernel worker thread(s)
nx_start_application: Starting init thread
lib_cxx_initialize: _sinit: 0x400d2000 _einit: 0x400d2000 _stext: 0x40080000 _etext: 0x400d3000
nsh: sysinit: fopen failed: 2
nshn:x _msktfaarttf:s :C PcUo0m:m aBnedg innonti nfgo uInddl
e
L
oNoupt
t
Shell (NSH) NuttX-11.0.0-RC2
nsh> hello
task_spawn: name=hello entry=0x4009ce64 file_actions=0x404f5580 attr=0x404f5588 argv=0x404f56d0
spawn_execattrs: Setting policy=2 priority=100 for pid=3
ABHello, World!!
ph_cfg1_reg=0x7177
ph_data_reg=0x400
pd_cfg2_reg=0x77711177
pd_data_reg=0x1c0000
struct reg_inst dsi_init_seq[] = {
.{ 0x0000, 0x00000001 },
.{ 0x0010, 0x00030000 },
.{ 0x0060, 0x0000000a },
.{ 0x0078, 0x00000000 },
.{ 0x0020, 0x0000001f },
.{ 0x0024, 0x10000001 },
.{ 0x0028, 0x20000010 },
.{ 0x002c, 0x2000000f },
.{ 0x0030, 0x30100001 },
.{ 0x0034, 0x40000010 },
.{ 0x0038, 0x0000000f },
.{ 0x003c, 0x5000001f },
.{ 0x004c, 0x00560001 },
.{ 0x02f8, 0x000000ff },
.{ 0x0014, 0x00005bc7 },
.{ 0x007c, 0x10000007 },
.{ 0x0040, 0x30000002 },
.{ 0x0044, 0x00310031 },
.{ 0x0054, 0x00310031 },
.{ 0x0090, 0x1308703e },
.{ 0x0098, 0x0000ffff },
.{ 0x009c, 0xffffffff },
.{ 0x0080, 0x00010008 },
display_malloc: size=2330
.{ 0x000c, 0x00000000 },
.{ 0x00b0, 0x12000021 },
.{ 0x00b4, 0x01000031 },
.{ 0x00b8, 0x07000001 },
.{ 0x00bc, 0x14000011 },
.{ 0x0018, 0x0011000a },
.{ 0x001c, 0x05cd05a0 },
.{ 0x00c0, 0x09004a19 },
.{ 0x00c4, 0x50b40000 },
.{ 0x00c8, 0x35005419 },
.{ 0x00cc, 0x757a0000 },
.{ 0x00d0, 0x09004a19 },
.{ 0x00d4, 0x50b40000 },
.{ 0x00e0, 0x0c091a19 },
.{ 0x00e4, 0x72bd0000 },
.{ 0x00e8, 0x1a000019 },
.{ 0x00ec, 0xffff0000 },
};
struct reg_inst dsi_panel_init_seq[] = {
nuttx_panel_init
writeDcs: len=4
b9 f1 12 83
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=4
composeLongPacket: channel=0, cmd=0x39, len=4
packet: len=10
39 04 00 2c b9 f1 12 83
84 5d
modifyreg32: addr=0x300, val=0x2c000439
modifyreg32: addr=0x304, val=0x8312f1b9
modifyreg32: addr=0x308, val=0x00005d84
modifyreg32: addr=0x200, val=0x00000009
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=28
ba 33 81 05 f9 0e 0e 20
00 00 00 00 00 00 00 44
25 00 91 0a 00 00 02 4f
11 00 00 37
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=28
composeLongPacket: channel=0, cmd=0x39, len=28
packet: len=34
39 1c 00 2f ba 33 81 05
f9 0e 0e 20 00 00 00 00
00 00 00 44 25 00 91 0a
00 00 02 4f 11 00 00 37
2c e2
modifyreg32: addr=0x300, val=0x2f001c39
modifyreg32: addr=0x304, val=0x058133ba
modifyreg32: addr=0x308, val=0x200e0ef9
modifyreg32: addr=0x30c, val=0x00000000
modifyreg32: addr=0x310, val=0x44000000
modifyreg32: addr=0x314, val=0x0a910025
modifyreg32: addr=0x318, val=0x4f020000
modifyreg32: addr=0x31c, val=0x37000011
modifyreg32: addr=0x320, val=0x0000e22c
modifyreg32: addr=0x200, val=0x00000021
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=5
b8 25 22 20 03
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=5
composeLongPacket: channel=0, cmd=0x39, len=5
packet: len=11
39 05 00 36 b8 25 22 20
03 03 72
modifyreg32: addr=0x300, val=0x36000539
modifyreg32: addr=0x304, val=0x202225b8
modifyreg32: addr=0x308, val=0x00720303
modifyreg32: addr=0x200, val=0x0000000a
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=11
b3 10 10 05 05 03 ff 00
00 00 00
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=11
composeLongPacket: channel=0, cmd=0x39, len=11
packet: len=17
39 0b 00 2c b3 10 10 05
05 03 ff 00 00 00 00 6f
bc
modifyreg32: addr=0x300, val=0x2c000b39
modifyreg32: addr=0x304, val=0x051010b3
modifyreg32: addr=0x308, val=0x00ff0305
modifyreg32: addr=0x30c, val=0x6f000000
modifyreg32: addr=0x310, val=0x000000bc
modifyreg32: addr=0x200, val=0x00000010
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=10
c0 73 73 50 50 00 c0 08
70 00
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=10
composeLongPacket: channel=0, cmd=0x39, len=10
packet: len=16
39 0a 00 36 c0 73 73 50
50 00 c0 08 70 00 1b 6a
modifyreg32: addr=0x300, val=0x36000a39
modifyreg32: addr=0x304, val=0x507373c0
modifyreg32: addr=0x308, val=0x08c00050
modifyreg32: addr=0x30c, val=0x6a1b0070
modifyreg32: addr=0x200, val=0x0000000f
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=2
bc 4e
mipi_dsi_dcs_write: channel=0, cmd=0x15, len=2
composeShortPacket: channel=0, cmd=0x15, len=2
packet: len=4
15 bc 4e 35
modifyreg32: addr=0x300, val=0x354ebc15
modifyreg32: addr=0x200, val=0x00000003
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=2
cc 0b
mipi_dsi_dcs_write: channel=0, cmd=0x15, len=2
composeShortPacket: channel=0, cmd=0x15, len=2
packet: len=4
15 cc 0b 22
modifyreg32: addr=0x300, val=0x220bcc15
modifyreg32: addr=0x200, val=0x00000003
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=2
b4 80
mipi_dsi_dcs_write: channel=0, cmd=0x15, len=2
composeShortPacket: channel=0, cmd=0x15, len=2
packet: len=4
15 b4 80 22
modifyreg32: addr=0x300, val=0x2280b415
modifyreg32: addr=0x200, val=0x00000003
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=4
b2 f0 12 f0
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=4
composeLongPacket: channel=0, cmd=0x39, len=4
packet: len=10
39 04 00 2c b2 f0 12 f0
51 86
modifyreg32: addr=0x300, val=0x2c000439
modifyreg32: addr=0x304, val=0xf012f0b2
modifyreg32: addr=0x308, val=0x00008651
modifyreg32: addr=0x200, val=0x00000009
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=15
e3 00 00 0b 0b 10 10 00
00 00 00 ff 00 c0 10
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=15
composeLongPacket: channel=0, cmd=0x39, len=15
packet: len=21
39 0f 00 0f e3 00 00 0b
0b 10 10 00 00 00 00 ff
00 c0 10 36 0f
modifyreg32: addr=0x300, val=0x0f000f39
modifyreg32: addr=0x304, val=0x0b0000e3
modifyreg32: addr=0x308, val=0x0010100b
modifyreg32: addr=0x30c, val=0xff000000
modifyreg32: addr=0x310, val=0x3610c000
modifyreg32: addr=0x314, val=0x0000000f
modifyreg32: addr=0x200, val=0x00000014
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=6
c6 01 00 ff ff 00
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=6
composeLongPacket: channel=0, cmd=0x39, len=6
packet: len=12
39 06 00 30 c6 01 00 ff
ff 00 8e 25
modifyreg32: addr=0x300, val=0x30000639
modifyreg32: addr=0x304, val=0xff0001c6
modifyreg32: addr=0x308, val=0x258e00ff
modifyreg32: addr=0x200, val=0x0000000b
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=13
c1 74 00 32 32 77 f1 ff
ff cc cc 77 77
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=13
composeLongPacket: channel=0, cmd=0x39, len=13
packet: len=19
39 0d 00 13 c1 74 00 32
32 77 f1 ff ff cc cc 77
77 69 e4
modifyreg32: addr=0x300, val=0x13000d39
modifyreg32: addr=0x304, val=0x320074c1
modifyreg32: addr=0x308, val=0xfff17732
modifyreg32: addr=0x30c, val=0x77ccccff
modifyreg32: addr=0x310, val=0x00e46977
modifyreg32: addr=0x200, val=0x00000012
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=3
b5 07 07
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=3
composeLongPacket: channel=0, cmd=0x39, len=3
packet: len=9
39 03 00 09 b5 07 07 7b
b3
modifyreg32: addr=0x300, val=0x09000339
modifyreg32: addr=0x304, val=0x7b0707b5
modifyreg32: addr=0x308, val=0x000000b3
modifyreg32: addr=0x200, val=0x00000008
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=3
b6 2c 2c
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=3
composeLongPacket: channel=0, cmd=0x39, len=3
packet: len=9
39 03 00 09 b6 2c 2c 55
04
modifyreg32: addr=0x300, val=0x09000339
modifyreg32: addr=0x304, val=0x552c2cb6
modifyreg32: addr=0x308, val=0x00000004
modifyreg32: addr=0x200, val=0x00000008
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=4
bf 02 11 00
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=4
composeLongPacket: channel=0, cmd=0x39, len=4
packet: len=10
39 04 00 2c bf 02 11 00
b5 e9
modifyreg32: addr=0x300, val=0x2c000439
modifyreg32: addr=0x304, val=0x001102bf
modifyreg32: addr=0x308, val=0x0000e9b5
modifyreg32: addr=0x200, val=0x00000009
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=64
e9 82 10 06 05 a2 0a a5
12 31 23 37 83 04 bc 27
38 0c 00 03 00 00 00 0c
00 03 00 00 00 75 75 31
88 88 88 88 88 88 13 88
64 64 20 88 88 88 88 88
88 02 88 00 00 00 00 00
00 00 00 00 00 00 00 00
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=64
composeLongPacket: channel=0, cmd=0x39, len=64
packet: len=70
39 40 00 25 e9 82 10 06
05 a2 0a a5 12 31 23 37
83 04 bc 27 38 0c 00 03
00 00 00 0c 00 03 00 00
00 75 75 31 88 88 88 88
88 88 13 88 64 64 20 88
88 88 88 88 88 02 88 00
00 00 00 00 00 00 00 00
00 00 00 00 65 03
modifyreg32: addr=0x300, val=0x25004039
modifyreg32: addr=0x304, val=0x061082e9
modifyreg32: addr=0x308, val=0xa50aa205
modifyreg32: addr=0x30c, val=0x37233112
modifyreg32: addr=0x310, val=0x27bc0483
modifyreg32: addr=0x314, val=0x03000c38
modifyreg32: addr=0x318, val=0x0c000000
modifyreg32: addr=0x31c, val=0x00000300
modifyreg32: addr=0x320, val=0x31757500
modifyreg32: addr=0x324, val=0x88888888
modifyreg32: addr=0x328, val=0x88138888
modifyreg32: addr=0x32c, val=0x88206464
modifyreg32: addr=0x330, val=0x88888888
modifyreg32: addr=0x334, val=0x00880288
modifyreg32: addr=0x338, val=0x00000000
modifyreg32: addr=0x33c, val=0x00000000
modifyreg32: addr=0x340, val=0x00000000
modifyreg32: addr=0x344, val=0x00000365
modifyreg32: addr=0x200, val=0x00000045
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=62
ea 02 21 00 00 00 00 00
00 00 00 00 00 02 46 02
88 88 88 88 88 88 64 88
13 57 13 88 88 88 88 88
88 75 88 23 14 00 00 02
00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 03
0a a5 00 00 00 00
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=62
composeLongPacket: channel=0, cmd=0x39, len=62
packet: len=68
39 3e 00 1a ea 02 21 00
00 00 00 00 00 00 00 00
00 02 46 02 88 88 88 88
88 88 64 88 13 57 13 88
88 88 88 88 88 75 88 23
14 00 00 02 00 00 00 00
00 00 00 00 00 00 00 00
00 00 00 03 0a a5 00 00
00 00 24 1b
modifyreg32: addr=0x300, val=0x1a003e39
modifyreg32: addr=0x304, val=0x002102ea
modifyreg32: addr=0x308, val=0x00000000
modifyreg32: addr=0x30c, val=0x00000000
modifyreg32: addr=0x310, val=0x02460200
modifyreg32: addr=0x314, val=0x88888888
modifyreg32: addr=0x318, val=0x88648888
modifyreg32: addr=0x31c, val=0x88135713
modifyreg32: addr=0x320, val=0x88888888
modifyreg32: addr=0x324, val=0x23887588
modifyreg32: addr=0x328, val=0x02000014
modifyreg32: addr=0x32c, val=0x00000000
modifyreg32: addr=0x330, val=0x00000000
modifyreg32: addr=0x334, val=0x00000000
modifyreg32: addr=0x338, val=0x03000000
modifyreg32: addr=0x33c, val=0x0000a50a
modifyreg32: addr=0x340, val=0x1b240000
modifyreg32: addr=0x200, val=0x00000043
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=35
e0 00 09 0d 23 27 3c 41
35 07 0d 0e 12 13 10 12
12 18 00 09 0d 23 27 3c
41 35 07 0d 0e 12 13 10
12 12 18
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=35
composeLongPacket: channel=0, cmd=0x39, len=35
packet: len=41
39 23 00 20 e0 00 09 0d
23 27 3c 41 35 07 0d 0e
12 13 10 12 12 18 00 09
0d 23 27 3c 41 35 07 0d
0e 12 13 10 12 12 18 93
bf
modifyreg32: addr=0x300, val=0x20002339
modifyreg32: addr=0x304, val=0x0d0900e0
modifyreg32: addr=0x308, val=0x413c2723
modifyreg32: addr=0x30c, val=0x0e0d0735
modifyreg32: addr=0x310, val=0x12101312
modifyreg32: addr=0x314, val=0x09001812
modifyreg32: addr=0x318, val=0x3c27230d
modifyreg32: addr=0x31c, val=0x0d073541
modifyreg32: addr=0x320, val=0x1013120e
modifyreg32: addr=0x324, val=0x93181212
modifyreg32: addr=0x328, val=0x000000bf
modifyreg32: addr=0x200, val=0x00000028
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=1
11
mipi_dsi_dcs_write: channel=0, cmd=0x5, len=1
composeShortPacket: channel=0, cmd=0x5, len=1
packet: len=4
05 11 00 36
modifyreg32: addr=0x300, val=0x36001105
modifyreg32: addr=0x200, val=0x00000003
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
writeDcs: len=1
29
mipi_dsi_dcs_write: channel=0, cmd=0x5, len=1
composeShortPacket: channel=0, cmd=0x5, len=1
packet: len=4
05 29 00 1c
modifyreg32: addr=0x300, val=0x1c002905
modifyreg32: addr=0x200, val=0x00000003
modifyreg32: addr=0x010, val=0x00000000
modifyreg32: addr=0x010, val=0x00000001
};
.{ 0x0048, 0x00000f02 },
.{ MAGIC_COMMIT, 0 },
dsi_update_bits: 0x01ca0020 : 0000001f -> (00000010) 00000000
.{ 0x0048, 0x63f07006 },
.{ MAGIC_COMMIT, 0 },
HELLO ZIG ON PINEPHONE!
Testing Compose Short Packet (Without Parameter)...
composeShortPacket: channel=0, cmd=0x5, len=1
Result:
05 11 00 36
Testing Compose Short Packet (With Parameter)...
composeShortPacket: channel=0, cmd=0x15, len=2
Result:
15 bc 4e 35
Testing Compose Long Packet...
composeLongPacket: channel=0, cmd=0x39, len=64
Result:
39 40 00 25 e9 82 10 06
05 a2 0a a5 12 31 23 37
83 04 bc 27 38 0c 00 03
00 00 00 0c 00 03 00 00
00 75 75 31 88 88 88 88
88 88 13 88 64 64 20 88
88 88 88 88 88 02 88 00
00 00 00 00 00 00 00 00
00 00 00 00 65 03
nsh>
nsh> uname -a
NuttX 11.0.0-RC2 a33f82d Oct 6 2022 19:36:13 arm64 qemu-a53
nsh>
nsh>
```
Testing NuttX Zig Driver for MIPI DSI on QEMU
Testing our <a>NuttX Zig Driver for MIPI DSI</a> on PinePhone...
```text
+ aarch64-none-elf-gcc -v
Using built-in specs.
COLLECT_GCC=aarch64-none-elf-gcc
COLLECT_LTO_WRAPPER=/Applications/ArmGNUToolchain/11.3.rel1/aarch64-none-elf/bin/../libexec/gcc/aarch64-none-elf/11.3.1/lto-wrapper
Target: aarch64-none-elf
Configured with: /Volumes/data/jenkins/workspace/GNU-toolchain/arm-11/src/gcc/configure --target=aarch64-none-elf --prefix=/Volumes/data/jenkins/workspace/GNU-toolchain/arm-11/build-aarch64-none-elf/install --with-gmp=/Volumes/data/jenkins/workspace/GNU-toolchain/arm-11/build-aarch64-none-elf/host-tools --with-mpfr=/Volumes/data/jenkins/workspace/GNU-toolchain/arm-11/build-aarch64-none-elf/host-tools --with-mpc=/Volumes/data/jenkins/workspace/GNU-toolchain/arm-11/build-aarch64-none-elf/host-tools --with-isl=/Volumes/data/jenkins/workspace/GNU-toolchain/arm-11/build-aarch64-none-elf/host-tools --disable-shared --disable-nls --disable-threads --disable-tls --enable-checking=release --enable-languages=c,c++,fortran --with-newlib --with-gnu-as --with-gnu-ld --with-sysroot=/Volumes/data/jenkins/workspace/GNU-toolchain/arm-11/build-aarch64-none-elf/install/aarch64-none-elf --with-pkgversion='Arm GNU Toolchain 11.3.Rel1' --with-bugurl=https://bugs.linaro.org/
Thread model: single
Supported LTO compression algorithms: zlib
gcc version 11.3.1 20220712 (Arm GNU Toolchain 11.3.Rel1)
+ zig version
0.10.0-dev.2351+b64a1d5ab
+ build_zig
+ pushd ../pinephone-nuttx
~/gicv2/nuttx/pinephone-nuttx ~/gicv2/nuttx/nuttx
+ git pull
Already up-to-date.
+ zig build-obj -target aarch64-freestanding-none -mcpu cortex_a53 -isystem /Users/Luppy/gicv2/nuttx/nuttx/include -I /Users/Luppy/gicv2/nuttx/apps/include display.zig
+ cp display.o /Users/Luppy/gicv2/nuttx/apps/examples/null/null_main.c.Users.Luppy.gicv2.nuttx.apps.examples.null.o
+ popd
~/gicv2/nuttx/nuttx
+ make -j
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/apps'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/libs/libxx'
make[1]: 'libxx.a' is up to date.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/libs/libxx'
make[2]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/examples/hello'
make[2]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/builtin'
make[2]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/examples/null'
make[2]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/system/system'
make[2]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/system/readline'
make[2]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/testing/getprime'
make[2]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/platform'
make[2]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/system/nsh'
make[2]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/nshlib'
make[2]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/testing/ostest'
make[2]: Nothing to be done for 'depend'.
make[2]: Nothing to be done for 'depend'.
make[2]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/nshlib'
make[2]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/system/system'
make[2]: Nothing to be done for 'depend'.
make[2]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/examples/hello'
make[2]: Nothing to be done for 'depend'.
make[2]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/system/readline'
make[2]: Nothing to be done for 'depend'.
make[2]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/testing/getprime'
make[2]: Nothing to be done for 'depend'.
make[2]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/examples/null'
make[2]: Nothing to be done for 'depend'.
make[2]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/platform'
make[2]: Nothing to be done for 'depend'.
make[2]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/builtin'
make[2]: Nothing to be done for 'depend'.
make[2]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/system/nsh'
make[2]: Nothing to be done for 'depend'.
make[2]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/testing/ostest'
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/sched'
make[1]: Nothing to be done for 'depend'.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/sched'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/drivers'
make[1]: Nothing to be done for 'depend'.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/drivers'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/boards'
make[1]: Nothing to be done for 'depend'.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/boards'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/arch/arm64/src'
make[1]: Nothing to be done for 'depend'.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/arch/arm64/src'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/fs'
make[1]: Nothing to be done for 'depend'.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/fs'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/binfmt'
make[1]: Nothing to be done for 'depend'.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/binfmt'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/libs/libc'
make[1]: Nothing to be done for 'depend'.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/libs/libc'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/mm'
make[1]: Nothing to be done for 'depend'.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/mm'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/libs/libxx'
make[1]: Nothing to be done for 'depend'.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/libs/libxx'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/sched'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/drivers'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/libs/libc'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/boards'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/mm'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/arch/arm64/src'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/apps'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/fs'
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/binfmt'
make[1]: 'libboards.a' is up to date.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/boards'
make[1]: 'libdrivers.a' is up to date.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/drivers'
make[1]: 'libmm.a' is up to date.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/mm'
make[1]: 'libsched.a' is up to date.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/sched'
make[1]: 'libfs.a' is up to date.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/fs'
make[1]: 'libbinfmt.a' is up to date.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/binfmt'
rm -f /Users/Luppy/gicv2/nuttx/apps/libapps.a
make /Users/Luppy/gicv2/nuttx/apps/libapps.a
make[1]: 'libarch.a' is up to date.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/arch/arm64/src'
make[2]: Entering directory '/Users/Luppy/gicv2/nuttx/apps'
make[1]: 'libc.a' is up to date.
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/libs/libc'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/builtin'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/nshlib'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/testing/getprime'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/examples/null'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/platform'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/examples/hello'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/system/system'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/testing/ostest'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/system/nsh'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/system/readline'
make[3]: Nothing to be done for 'all'.
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/examples/hello'
make[3]: Nothing to be done for 'all'.
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/builtin'
make[3]: Nothing to be done for 'all'.
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/platform'
make[3]: Nothing to be done for 'all'.
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/system/nsh'
make[3]: Nothing to be done for 'all'.
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/system/system'
make[3]: Nothing to be done for 'all'.
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/testing/ostest'
make[3]: Nothing to be done for 'all'.
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/nshlib'
make[3]: Nothing to be done for 'all'.
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/testing/getprime'
make[3]: Nothing to be done for 'all'.
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/examples/null'
make[3]: Nothing to be done for 'all'.
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/system/readline'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/builtin'
AR (add): libapps.a builtin_list.c.Users.Luppy.gicv2.nuttx.apps.builtin.o exec_builtin.c.Users.Luppy.gicv2.nuttx.apps.builtin.o
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/builtin'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/examples/hello'
AR (add): libapps.a hello_main.c.Users.Luppy.gicv2.nuttx.apps.examples.hello.o
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/examples/hello'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/examples/null'
AR (add): libapps.a null_main.c.Users.Luppy.gicv2.nuttx.apps.examples.null.o
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/examples/null'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/nshlib'
AR (add): libapps.a nsh_init.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_parse.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_console.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_script.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_system.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_command.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_fscmds.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_ddcmd.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_proccmds.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_mmcmds.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_timcmds.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_envcmds.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_syscmds.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_dbgcmds.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_session.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_fsutils.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_builtin.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_romfsetc.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_mntcmds.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_consolemain.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_printf.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o nsh_test.c.Users.Luppy.gicv2.nuttx.apps.nshlib.o
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/nshlib'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/platform'
AR (add): libapps.a dummy.c.Users.Luppy.gicv2.nuttx.apps.platform.o
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/platform'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/system/nsh'
AR (add): libapps.a nsh_main.c.Users.Luppy.gicv2.nuttx.apps.system.nsh.o sh_main.c.Users.Luppy.gicv2.nuttx.apps.system.nsh.o
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/system/nsh'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/system/readline'
AR (add): libapps.a readline.c.Users.Luppy.gicv2.nuttx.apps.system.readline.o readline_fd.c.Users.Luppy.gicv2.nuttx.apps.system.readline.o readline_common.c.Users.Luppy.gicv2.nuttx.apps.system.readline.o
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/system/readline'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/system/system'
AR (add): libapps.a system.c.Users.Luppy.gicv2.nuttx.apps.system.system.o
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/system/system'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/testing/getprime'
AR (add): libapps.a getprime_main.c.Users.Luppy.gicv2.nuttx.apps.testing.getprime.o
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/testing/getprime'
make[3]: Entering directory '/Users/Luppy/gicv2/nuttx/apps/testing/ostest'
AR (add): libapps.a getopt.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o dev_null.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o restart.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o sigprocmask.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o sighand.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o signest.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o fpu.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o setvbuf.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o tls.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o waitpid.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o cancel.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o cond.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o mutex.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o timedmutex.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o sem.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o semtimed.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o barrier.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o timedwait.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o pthread_rwlock.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o pthread_rwlock_cancel.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o specific.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o robust.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o roundrobin.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o mqueue.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o timedmqueue.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o posixtimer.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o vfork.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o ostest_main.c.Users.Luppy.gicv2.nuttx.apps.testing.ostest.o
make[3]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps/testing/ostest'
make[2]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps'
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/apps'
IN: /Users/Luppy/gicv2/nuttx/apps/libapps.a -> staging/libapps.a
make[1]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/arch/arm64/src'
make[2]: Entering directory '/Users/Luppy/gicv2/nuttx/nuttx/boards/arm64/qemu/qemu-a53/src'
make[2]: 'libboard.a' is up to date.
make[2]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/boards/arm64/qemu/qemu-a53/src'
LD: nuttx
make[1]: Leaving directory '/Users/Luppy/gicv2/nuttx/nuttx/arch/arm64/src'
CP: nuttx.hex
CP: nuttx.bin
+ aarch64-none-elf-size nuttx
text data bss dec hex filename
253075 12624 48504 314203 4cb5b nuttx
+ aarch64-none-elf-objdump -t -S --demangle --line-numbers --wide nuttx
+ qemu-system-aarch64 -smp 4 -cpu cortex-a53 -nographic -machine virt,virtualization=on,gic-version=2 -net none -chardev stdio,id=con,mux=on -serial chardev:con -mon chardev=con,mode=readline -kernel ./nuttx
- Ready to Boot CPU
- Boot from EL2
- Boot from EL1
- Boot to C runtime for OS Initialize
nx_start: Entry
up_allocate_heap: heap_start=0x0x402cf000, heap_size=0x7d31000
arm64_gic_initialize: TODO: Init GIC for PinePhone
arm64_gic_initialize: CONFIG_GICD_BASE=0x8000000
arm64_gic_initialize: CONFIG_GICR_BASE=0x8010000
arm64_gic_initialize: GIC Version is 2
up_timer_initialize: up_timer_initialize: cp15 timer(s) running at 62.50MHz, cycle 62500
up_timer_initialize: _vector_table=0x402b1000
up_timer_initialize: Before writing: vbar_el1=0x402b1000
up_timer_initialize: After writing: vbar_el1=0x402b1000
uart_register: Registering /dev/console
uart_register: Registering /dev/ttyS0
work_start_highpri: Starting high-priority kernel worker thread(s)
nx_start_application: Starting init thread
lib_cxx_initialize: _sinit: 0x402b1000 _einit: 0x402b1000 _stext: 0x40280000 _etext: 0x402b2000
nsh: sysinit: fopen failed: 2
nsh: mkfatfs: command not found
NuttShell (NSH) NuttX-11.0.0-RC2
nsh> nx_start: CPU0: Beginning Idle Loop
nsh> null
task_spawn: name=null entry=0x4029c9d0 file_actions=0x402d4580 attr=0x402d4588 argv=0x402d46d0
spawn_execattrs: Setting policy=2 priority=100 for pid=3
HELLO ZIG ON PINEPHONE!
Testing Compose Short Packet (Without Parameter)...
composeShortPacket: channel=0, cmd=0x5, len=1
Result:
05 11 00 36
Testing Compose Short Packet (With Parameter)...
composeShortPacket: channel=0, cmd=0x15, len=2
Result:
15 bc 4e 35
Testing Compose Long Packet...
composeLongPacket: channel=0, cmd=0x39, len=64
Result:
39 40 00 25 e9 82 10 06
05 a2 0a a5 12 31 23 37
83 04 bc 27 38 0c 00 03
00 00 00 0c 00 03 00 00
00 75 75 31 88 88 88 88
88 88 13 88 64 64 20 88
88 88 88 88 88 02 88 00
00 00 00 00 00 00 00 00
00 00 00 00 65 03
nsh> qemu-system-aarch64: terminating on signal 2 from pid 5928 ()
* Terminal will be reused by tasks, press any key to close it.
```
Testing p-boot Driver for MIPI DSI (with logging)
Testing <a>PinePhone p-boot Display Code</a> with logging...
```text
DRAM: 2048 MiB
Trying to boot from MMC1
NOTICE: BL31: v2.2(release):v2.2-904-gf9ea3a629
NOTICE: BL31: Built : 15:32:12, Apr 9 2020
NOTICE: BL31: Detected Allwinner A64/H64/R18 SoC (1689)
NOTICE: BL31: Found U-Boot DTB at 0x4064410, model: PinePhone
NOTICE: PSCI: System suspend is unavailable
U-Boot 2020.07 (Nov 08 2020 - 00:15:12 +0100)
DRAM: 2 GiB
MMC: Device 'mmc@1c11000': seq 1 is in use by 'mmc@1c10000'
mmc@1c0f000: 0, mmc@1c10000: 2, mmc@1c11000: 1
Loading Environment from FAT... *** Warning - bad CRC, using default environment
starting USB...
No working controllers found
Hit any key to stop autoboot: 0
switch to partitions #0, OK
mmc0 is current device
Scanning mmc 0:1...
Found U-Boot script /boot.scr
653 bytes read in 3 ms (211.9 KiB/s)
Executing script at 4fc00000
gpio: pin 114 (gpio 114) value is 1
205024 bytes read in 13 ms (15 MiB/s)
Uncompressed size: 4640768 = 0x46D000
36162 bytes read in 4 ms (8.6 MiB/s)
1078500 bytes read in 51 ms (20.2 MiB/s)
Flattened Device Tree blob at 4fa00000
Booting using the fdt blob at 0x4fa00000
Loading Ramdisk to 49ef8000, end 49fff4e4 ... OK
Loading Device Tree to 0000000049eec000, end 0000000049ef7d41 ... OK
Starting kernel ...
HELLO NUTTX ON PINEPHONE!
- Ready to Boot CPU
- Boot from EL2
- Boot from EL1
- Boot to C runtime for OS Initialize
nx_start: Entry
up_allocate_heap: heap_start=0x0x404ed000, heap_size=0x7b13000
arm64_gic_initialize: TODO: Init GIC for PinePhone
arm64_gic_initialize: CONFIG_GICD_BASE=0x1c81000
arm64_gic_initialize: CONFIG_GICR_BASE=0x1c82000
arm64_gic_initialize: GIC Version is 2
up_timer_initialize: up_timer_initialize: cp15 timer(s) running at 24.00MHz, cycle 24000
up_timer_initialize: _vector_table=0x400cf000
up_timer_initialize: Before writing: vbar_el1=0x4024f000
up_timer_initialize: After writing: vbar_el1=0x400cf000
uart_register: Registering /dev/console
uart_register: Registering /dev/ttyS0
work_start_highpri: Starting high-priority kernel worker thread(s)
nx_start_application: Starting init thread
lib_cxx_initialize: _sinit: 0x400cf000 _einit: 0x400cf000 _stext: 0x40080000 _etext: 0x400d0000
nsh: sysinit: fopen failed: 2
nshn:x _msktfaarttf:s :C PcUo0m:m aBnedg innonti nfgo uInddl
e
L
oNoupt
t
Shell (NSH) NuttX-11.0.0-RC2
nsh> hello
task_spawn: name=hello entry=0x4009cf58 file_actions=0x404f2580 attr=0x404f2588 argv=0x404f26d0
spawn_execattrs: Setting policy=2 priority=100 for pid=3
ABHello, World!!
ph_cfg1_reg=0x7177
ph_data_reg=0x400
pd_cfg2_reg=0x77711177
pd_data_reg=0x1c0000
struct reg_inst dsi_init_seq[] = {
.{ 0x0000, 0x00000001 },
.{ 0x0010, 0x00030000 },
.{ 0x0060, 0x0000000a },
.{ 0x0078, 0x00000000 },
.{ 0x0020, 0x0000001f },
.{ 0x0024, 0x10000001 },
.{ 0x0028, 0x20000010 },
.{ 0x002c, 0x2000000f },
.{ 0x0030, 0x30100001 },
.{ 0x0034, 0x40000010 },
.{ 0x0038, 0x0000000f },
.{ 0x003c, 0x5000001f },
.{ 0x004c, 0x00560001 },
.{ 0x02f8, 0x000000ff },
.{ 0x0014, 0x00005bc7 },
.{ 0x007c, 0x10000007 },
.{ 0x0040, 0x30000002 },
.{ 0x0044, 0x00310031 },
.{ 0x0054, 0x00310031 },
.{ 0x0090, 0x1308703e },
.{ 0x0098, 0x0000ffff },
.{ 0x009c, 0xffffffff },
.{ 0x0080, 0x00010008 },
display_malloc: size=2330
.{ 0x000c, 0x00000000 },
.{ 0x00b0, 0x12000021 },
.{ 0x00b4, 0x01000031 },
.{ 0x00b8, 0x07000001 },
.{ 0x00bc, 0x14000011 },
.{ 0x0018, 0x0011000a },
.{ 0x001c, 0x05cd05a0 },
.{ 0x00c0, 0x09004a19 },
.{ 0x00c4, 0x50b40000 },
.{ 0x00c8, 0x35005419 },
.{ 0x00cc, 0x757a0000 },
.{ 0x00d0, 0x09004a19 },
.{ 0x00d4, 0x50b40000 },
.{ 0x00e0, 0x0c091a19 },
.{ 0x00e4, 0x72bd0000 },
.{ 0x00e8, 0x1a000019 },
.{ 0x00ec, 0xffff0000 },
};
struct reg_inst dsi_panel_init_seq[] = {
mipi_dsi_dcs_write: long len=4
b9 f1 12 83
.{ 0x0300, 0x2c000439 },
header: 2c000439
display_zalloc: size=10
.{ 0x0304, 0x8312f1b9 },
.{ 0x0308, 0x00005d84 },
payload[0]: 8312f1b9
payload[1]: 00005d84
.{ 0x0200, 0x00000009 },
len: 9
.{ MAGIC_COMMIT, 0 },
mipi_dsi_dcs_write: long len=28
ba 33 81 05 f9 0e 0e 20
00 00 00 00 00 00 00 44
25 00 91 0a 00 00 02 4f
11 00 00 37
.{ 0x0300, 0x2f001c39 },
header: 2f001c39
display_zalloc: size=34
.{ 0x0304, 0x058133ba },
.{ 0x0308, 0x200e0ef9 },
.{ 0x030c, 0x00000000 },
.{ 0x0310, 0x44000000 },
.{ 0x0314, 0x0a910025 },
.{ 0x0318, 0x4f020000 },
.{ 0x031c, 0x37000011 },
.{ 0x0320, 0x0000e22c },
payload[0]: 058133ba
payload[1]: 200e0ef9
payload[2]: 00000000
payload[3]: 44000000
payload[4]: 0a910025
payload[5]: 4f020000
payload[6]: 37000011
payload[7]: 0000e22c
.{ 0x0200, 0x00000021 },
len: 33
.{ MAGIC_COMMIT, 0 },
mipi_dsi_dcs_write: long len=5
b8 25 22 20 03
.{ 0x0300, 0x36000539 },
header: 36000539
display_zalloc: size=11
.{ 0x0304, 0x202225b8 },
.{ 0x0308, 0x00720303 },
payload[0]: 202225b8
payload[1]: 00720303
.{ 0x0200, 0x0000000a },
len: 10
.{ MAGIC_COMMIT, 0 },
mipi_dsi_dcs_write: long len=11
b3 10 10 05 05 03 ff 00
00 00 00
.{ 0x0300, 0x2c000b39 },
header: 2c000b39
display_zalloc: size=17
.{ 0x0304, 0x051010b3 },
.{ 0x0308, 0x00ff0305 },
.{ 0x030c, 0x6f000000 },
.{ 0x0310, 0x000000bc },
payload[0]: 051010b3
payload[1]: 00ff0305
payload[2]: 6f000000
payload[3]: 000000bc
.{ 0x0200, 0x00000010 },
len: 16
.{ MAGIC_COMMIT, 0 },
mipi_dsi_dcs_write: long len=10
c0 73 73 50 50 00 c0 08
70 00
.{ 0x0300, 0x36000a39 },
header: 36000a39
display_zalloc: size=16
.{ 0x0304, 0x507373c0 },
.{ 0x0308, 0x08c00050 },
.{ 0x030c, 0x6a1b0070 },
payload[0]: 507373c0
payload[1]: 08c00050
payload[2]: 6a1b0070
.{ 0x0200, 0x0000000f },
len: 15
.{ MAGIC_COMMIT, 0 },
mipi_dsi_dcs_write: short len=2
bc 4e
.{ 0x0300, 0x354ebc15 },
header: 354ebc15
.{ 0x0200, 0x00000003 },
len: 3
.{ MAGIC_COMMIT, 0 },
mipi_dsi_dcs_write: short len=2
cc 0b
.{ 0x0300, 0x220bcc15 },
header: 220bcc15
.{ 0x0200, 0x00000003 },
len: 3
.{ MAGIC_COMMIT, 0 },
mipi_dsi_dcs_write: short len=2
b4 80
.{ 0x0300, 0x2280b415 },
header: 2280b415
.{ 0x0200, 0x00000003 },
len: 3
.{ MAGIC_COMMIT, 0 },
mipi_dsi_dcs_write: long len=4
b2 f0 12 f0
.{ 0x0300, 0x2c000439 },
header: 2c000439
display_zalloc: size=10
.{ 0x0304, 0xf012f0b2 },
.{ 0x0308, 0x00008651 },
payload[0]: f012f0b2
payload[1]: 00008651
.{ 0x0200, 0x00000009 },
len: 9
.{ MAGIC_COMMIT, 0 },
mipi_dsi_dcs_write: long len=15
e3 00 00 0b 0b 10 10 00
00 00 00 ff 00 c0 10
.{ 0x0300, 0x0f000f39 },
header: 0f000f39
display_zalloc: size=21
.{ 0x0304, 0x0b0000e3 },
.{ 0x0308, 0x0010100b },
.{ 0x030c, 0xff000000 },
.{ 0x0310, 0x3610c000 },
.{ 0x0314, 0x0000000f },
payload[0]: 0b0000e3
payload[1]: 0010100b
payload[2]: ff000000
payload[3]: 3610c000
payload[4]: 0000000f
.{ 0x0200, 0x00000014 },
len: 20
.{ MAGIC_COMMIT, 0 },
mipi_dsi_dcs_write: long len=6
c6 01 00 ff ff 00
.{ 0x0300, 0x30000639 },
header: 30000639
display_zalloc: size=12
.{ 0x0304, 0xff0001c6 },
.{ 0x0308, 0x258e00ff },
payload[0]: ff0001c6
payload[1]: 258e00ff
.{ 0x0200, 0x0000000b },
len: 11
.{ MAGIC_COMMIT, 0 },
mipi_dsi_dcs_write: long len=13
c1 74 00 32 32 77 f1 ff
ff cc cc 77 77
.{ 0x0300, 0x13000d39 },
header: 13000d39
display_zalloc: size=19
.{ 0x0304, 0x320074c1 },
.{ 0x0308, 0xfff17732 },
.{ 0x030c, 0x77ccccff },
.{ 0x0310, 0x00e46977 },
payload[0]: 320074c1
payload[1]: fff17732
payload[2]: 77ccccff
payload[3]: 00e46977
.{ 0x0200, 0x00000012 },
len: 18
.{ MAGIC_COMMIT, 0 },
mipi_dsi_dcs_write: long len=3
b5 07 07
.{ 0x0300, 0x09000339 },
header: 09000339
display_zalloc: size=9
.{ 0x0304, 0x7b0707b5 },
.{ 0x0308, 0x000000b3 },
payload[0]: 7b0707b5
payload[1]: 000000b3
.{ 0x0200, 0x00000008 },
len: 8
.{ MAGIC_COMMIT, 0 },
mipi_dsi_dcs_write: long len=3
b6 2c 2c
.{ 0x0300, 0x09000339 },
header: 09000339
display_zalloc: size=9
.{ 0x0304, 0x552c2cb6 },
.{ 0x0308, 0x00000004 },
payload[0]: 552c2cb6
payload[1]: 00000004
.{ 0x0200, 0x00000008 },
len: 8
.{ MAGIC_COMMIT, 0 },
mipi_dsi_dcs_write: long len=4
bf 02 11 00
.{ 0x0300, 0x2c000439 },
header: 2c000439
display_zalloc: size=10
.{ 0x0304, 0x001102bf },
.{ 0x0308, 0x0000e9b5 },
payload[0]: 001102bf
payload[1]: 0000e9b5
.{ 0x0200, 0x00000009 },
len: 9
.{ MAGIC_COMMIT, 0 },
mipi_dsi_dcs_write: long len=64
e9 82 10 06 05 a2 0a a5
12 31 23 37 83 04 bc 27
38 0c 00 03 00 00 00 0c
00 03 00 00 00 75 75 31
88 88 88 88 88 88 13 88
64 64 20 88 88 88 88 88
88 02 88 00 00 00 00 00
00 00 00 00 00 00 00 00
.{ 0x0300, 0x25004039 },
header: 25004039
display_zalloc: size=70
.{ 0x0304, 0x061082e9 },
.{ 0x0308, 0xa50aa205 },
.{ 0x030c, 0x37233112 },
.{ 0x0310, 0x27bc0483 },
.{ 0x0314, 0x03000c38 },
.{ 0x0318, 0x0c000000 },
.{ 0x031c, 0x00000300 },
.{ 0x0320, 0x31757500 },
.{ 0x0324, 0x88888888 },
.{ 0x0328, 0x88138888 },
.{ 0x032c, 0x88206464 },
.{ 0x0330, 0x88888888 },
.{ 0x0334, 0x00880288 },
.{ 0x0338, 0x00000000 },
.{ 0x033c, 0x00000000 },
.{ 0x0340, 0x00000000 },
.{ 0x0344, 0x00000365 },
payload[0]: 061082e9
payload[1]: a50aa205
payload[2]: 37233112
payload[3]: 27bc0483
payload[4]: 03000c38
payload[5]: 0c000000
payload[6]: 00000300
payload[7]: 31757500
payload[8]: 88888888
payload[9]: 88138888
payload[10]: 88206464
payload[11]: 88888888
payload[12]: 00880288
payload[13]: 00000000
payload[14]: 00000000
payload[15]: 00000000
payload[16]: 00000365
.{ 0x0200, 0x00000045 },
len: 69
.{ MAGIC_COMMIT, 0 },
mipi_dsi_dcs_write: long len=62
ea 02 21 00 00 00 00 00
00 00 00 00 00 02 46 02
88 88 88 88 88 88 64 88
13 57 13 88 88 88 88 88
88 75 88 23 14 00 00 02
00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 03
0a a5 00 00 00 00
.{ 0x0300, 0x1a003e39 },
header: 1a003e39
display_zalloc: size=68
.{ 0x0304, 0x002102ea },
.{ 0x0308, 0x00000000 },
.{ 0x030c, 0x00000000 },
.{ 0x0310, 0x02460200 },
.{ 0x0314, 0x88888888 },
.{ 0x0318, 0x88648888 },
.{ 0x031c, 0x88135713 },
.{ 0x0320, 0x88888888 },
.{ 0x0324, 0x23887588 },
.{ 0x0328, 0x02000014 },
.{ 0x032c, 0x00000000 },
.{ 0x0330, 0x00000000 },
.{ 0x0334, 0x00000000 },
.{ 0x0338, 0x03000000 },
.{ 0x033c, 0x0000a50a },
.{ 0x0340, 0x1b240000 },
payload[0]: 002102ea
payload[1]: 00000000
payload[2]: 00000000
payload[3]: 02460200
payload[4]: 88888888
payload[5]: 88648888
payload[6]: 88135713
payload[7]: 88888888
payload[8]: 23887588
payload[9]: 02000014
payload[10]: 00000000
payload[11]: 00000000
payload[12]: 00000000
payload[13]: 03000000
payload[14]: 0000a50a
payload[15]: 1b240000
.{ 0x0200, 0x00000043 },
len: 67
.{ MAGIC_COMMIT, 0 },
mipi_dsi_dcs_write: long len=35
e0 00 09 0d 23 27 3c 41
35 07 0d 0e 12 13 10 12
12 18 00 09 0d 23 27 3c
41 35 07 0d 0e 12 13 10
12 12 18
.{ 0x0300, 0x20002339 },
header: 20002339
display_zalloc: size=41
.{ 0x0304, 0x0d0900e0 },
.{ 0x0308, 0x413c2723 },
.{ 0x030c, 0x0e0d0735 },
.{ 0x0310, 0x12101312 },
.{ 0x0314, 0x09001812 },
.{ 0x0318, 0x3c27230d },
.{ 0x031c, 0x0d073541 },
.{ 0x0320, 0x1013120e },
.{ 0x0324, 0x93181212 },
.{ 0x0328, 0x000000bf },
payload[0]: 0d0900e0
payload[1]: 413c2723
payload[2]: 0e0d0735
payload[3]: 12101312
payload[4]: 09001812
payload[5]: 3c27230d
payload[6]: 0d073541
payload[7]: 1013120e
payload[8]: 93181212
payload[9]: 000000bf
.{ 0x0200, 0x00000028 },
len: 40
.{ MAGIC_COMMIT, 0 },
mipi_dsi_dcs_write: short len=1
11
.{ 0x0300, 0x36001105 },
header: 36001105
.{ 0x0200, 0x00000003 },
len: 3
.{ MAGIC_COMMIT, 0 },
mipi_dsi_dcs_write: short len=1
29
.{ 0x0300, 0x1c002905 },
header: 1c002905
.{ 0x0200, 0x00000003 },
len: 3
.{ MAGIC_COMMIT, 0 },
};
.{ 0x0048, 0x00000f02 },
.{ MAGIC_COMMIT, 0 },
dsi_update_bits: 0x01ca0020 : 0000001f -> (00000010) 00000000
.{ 0x0048, 0x63f07006 },
.{ MAGIC_COMMIT, 0 },
HELLO ZIG ON PINEPHONE!
mipi_dsi_dcs_write: channel=0, cmd=0x39, len=64
composeLongPacket: channel=0, cmd=0x39, len=64
computeCrc: len=64, crc=0x365
e9 82 10 06 05 a2 0a a5
12 31 23 37 83 04 bc 27
38 0c 00 03 00 00 00 0c
00 03 00 00 00 75 75 31
88 88 88 88 88 88 13 88
64 64 20 88 88 88 88 88
88 02 88 00 00 00 00 00
00 00 00 00 00 00 00 00
packet: len=70
39 40 00 25 e9 82 10 06
05 a2 0a a5 12 31 23 37
83 04 bc 27 38 0c 00 03
00 00 00 0c 00 03 00 00
00 75 75 31 88 88 88 88
88 88 13 88 64 64 20 88
88 88 88 88 88 02 88 00
00 00 00 00 00 00 00 00
00 00 00 00 65 03
modifyreg32: addr=0x300, val=0x25004039
modifyreg32: addr=0x304, val=0x061082e9
modifyreg32: addr=0x308, val=0xa50aa205
modifyreg32: addr=0x30c, val=0x37233112
modifyreg32: addr=0x310, val=0x27bc0483
modifyreg32: addr=0x314, val=0x03000c38
modifyreg32: addr=0x318, val=0x0c000000
modifyreg32: addr=0x31c, val=0x00000300
modifyreg32: addr=0x320, val=0x31757500
modifyreg32: addr=0x324, val=0x88888888
modifyreg32: addr=0x328, val=0x88138888
modifyreg32: addr=0x32c, val=0x88206464
modifyreg32: addr=0x330, val=0x88888888
modifyreg32: addr=0x334, val=0x00880288
modifyreg32: addr=0x338, val=0x00000000
modifyreg32: addr=0x33c, val=0x00000000
modifyreg32: addr=0x340, val=0x00000000
modifyreg32: addr=0x344, val=0x00000365
modifyreg32: addr=0x200, val=0x00000045
nsh>
nsh>
```
Testing p-boot Driver for MIPI DSI (without logging)
Testing <a>PinePhone p-boot Display Code</a> without logging...
```text
nsh> hello
task_spawn: name=hello entry=0x4009ce04 file_actions=0x404ea580 attr=0x404ea588 argv=0x404ea6d0
spawn_execattrs: Setting policy=2 priority=100 for pid=3
ABHello, World!!
ph_cfg1_reg=0x7177
ph_data_reg=0x400
pd_cfg2_reg=0x77711177
pd_data_reg=0x1c0000
struct reg_inst dsi_init_seq[] = {
{ 0x0000, 0x00000001 },
{ 0x0010, 0x00030000 },
{ 0x0060, 0x0000000a },
{ 0x0078, 0x00000000 },
{ 0x0020, 0x0000001f },
{ 0x0024, 0x10000001 },
{ 0x0028, 0x20000010 },
{ 0x002c, 0x2000000f },
{ 0x0030, 0x30100001 },
{ 0x0034, 0x40000010 },
{ 0x0038, 0x0000000f },
{ 0x003c, 0x5000001f },
{ 0x004c, 0x00560001 },
{ 0x02f8, 0x000000ff },
{ 0x0014, 0x00005bc7 },
{ 0x007c, 0x10000007 },
{ 0x0040, 0x30000002 },
{ 0x0044, 0x00310031 },
{ 0x0054, 0x00310031 },
{ 0x0090, 0x1308703e },
{ 0x0098, 0x0000ffff },
{ 0x009c, 0xffffffff },
{ 0x0080, 0x00010008 },
display_malloc: size=2330
{ 0x000c, 0x00000000 },
{ 0x00b0, 0x12000021 },
{ 0x00b4, 0x01000031 },
{ 0x00b8, 0x07000001 },
{ 0x00bc, 0x14000011 },
{ 0x0018, 0x0011000a },
{ 0x001c, 0x05cd05a0 },
{ 0x00c0, 0x09004a19 },
{ 0x00c4, 0x50b40000 },
{ 0x00c8, 0x35005419 },
{ 0x00cc, 0x757a0000 },
{ 0x00d0, 0x09004a19 },
{ 0x00d4, 0x50b40000 },
{ 0x00e0, 0x0c091a19 },
{ 0x00e4, 0x72bd0000 },
{ 0x00e8, 0x1a000019 },
{ 0x00ec, 0xffff0000 },
};
struct reg_inst dsi_panel_init_seq[] = {
{ 0x0300, 0x2c000439 },
display_zalloc: size=10
{ 0x0304, 0x8312f1b9 },
{ 0x0308, 0x00005d84 },
{ 0x0200, 0x00000009 },
{ MAGIC_COMMIT, 0 },
{ 0x0300, 0x2f001c39 },
display_zalloc: size=34
{ 0x0304, 0x058133ba },
{ 0x0308, 0x200e0ef9 },
{ 0x030c, 0x00000000 },
{ 0x0310, 0x44000000 },
{ 0x0314, 0x0a910025 },
{ 0x0318, 0x4f020000 },
{ 0x031c, 0x37000011 },
{ 0x0320, 0x0000e22c },
{ 0x0200, 0x00000021 },
{ MAGIC_COMMIT, 0 },
{ 0x0300, 0x36000539 },
display_zalloc: size=11
{ 0x0304, 0x202225b8 },
{ 0x0308, 0x00720303 },
{ 0x0200, 0x0000000a },
{ MAGIC_COMMIT, 0 },
{ 0x0300, 0x2c000b39 },
display_zalloc: size=17
{ 0x0304, 0x051010b3 },
{ 0x0308, 0x00ff0305 },
{ 0x030c, 0x6f000000 },
{ 0x0310, 0x000000bc },
{ 0x0200, 0x00000010 },
{ MAGIC_COMMIT, 0 },
{ 0x0300, 0x36000a39 },
display_zalloc: size=16
{ 0x0304, 0x507373c0 },
{ 0x0308, 0x08c00050 },
{ 0x030c, 0x6a1b0070 },
{ 0x0200, 0x0000000f },
{ MAGIC_COMMIT, 0 },
{ 0x0300, 0x354ebc15 },
{ 0x0200, 0x00000003 },
{ MAGIC_COMMIT, 0 },
{ 0x0300, 0x220bcc15 },
{ 0x0200, 0x00000003 },
{ MAGIC_COMMIT, 0 },
{ 0x0300, 0x2280b415 },
{ 0x0200, 0x00000003 },
{ MAGIC_COMMIT, 0 },
{ 0x0300, 0x2c000439 },
display_zalloc: size=10
{ 0x0304, 0xf012f0b2 },
{ 0x0308, 0x00008651 },
{ 0x0200, 0x00000009 },
{ MAGIC_COMMIT, 0 },
{ 0x0300, 0x0f000f39 },
display_zalloc: size=21
{ 0x0304, 0x0b0000e3 },
{ 0x0308, 0x0010100b },
{ 0x030c, 0xff000000 },
{ 0x0310, 0x3610c000 },
{ 0x0314, 0x0000000f },
{ 0x0200, 0x00000014 },
{ MAGIC_COMMIT, 0 },
{ 0x0300, 0x30000639 },
display_zalloc: size=12
{ 0x0304, 0xff0001c6 },
{ 0x0308, 0x258e00ff },
{ 0x0200, 0x0000000b },
{ MAGIC_COMMIT, 0 },
{ 0x0300, 0x13000d39 },
display_zalloc: size=19
{ 0x0304, 0x320074c1 },
{ 0x0308, 0xfff17732 },
{ 0x030c, 0x77ccccff },
{ 0x0310, 0x00e46977 },
{ 0x0200, 0x00000012 },
{ MAGIC_COMMIT, 0 },
{ 0x0300, 0x09000339 },
display_zalloc: size=9
{ 0x0304, 0x7b0707b5 },
{ 0x0308, 0x000000b3 },
{ 0x0200, 0x00000008 },
{ MAGIC_COMMIT, 0 },
{ 0x0300, 0x09000339 },
display_zalloc: size=9
{ 0x0304, 0x552c2cb6 },
{ 0x0308, 0x00000004 },
{ 0x0200, 0x00000008 },
{ MAGIC_COMMIT, 0 },
{ 0x0300, 0x2c000439 },
display_zalloc: size=10
{ 0x0304, 0x001102bf },
{ 0x0308, 0x0000e9b5 },
{ 0x0200, 0x00000009 },
{ MAGIC_COMMIT, 0 },
{ 0x0300, 0x25004039 },
display_zalloc: size=70
{ 0x0304, 0x061082e9 },
{ 0x0308, 0xa50aa205 },
{ 0x030c, 0x37233112 },
{ 0x0310, 0x27bc0483 },
{ 0x0314, 0x03000c38 },
{ 0x0318, 0x0c000000 },
{ 0x031c, 0x00000300 },
{ 0x0320, 0x31757500 },
{ 0x0324, 0x88888888 },
{ 0x0328, 0x88138888 },
{ 0x032c, 0x88206464 },
{ 0x0330, 0x88888888 },
{ 0x0334, 0x00880288 },
{ 0x0338, 0x00000000 },
{ 0x033c, 0x00000000 },
{ 0x0340, 0x00000000 },
{ 0x0344, 0x00000365 },
{ 0x0200, 0x00000045 },
{ MAGIC_COMMIT, 0 },
{ 0x0300, 0x1a003e39 },
display_zalloc: size=68
{ 0x0304, 0x002102ea },
{ 0x0308, 0x00000000 },
{ 0x030c, 0x00000000 },
{ 0x0310, 0x02460200 },
{ 0x0314, 0x88888888 },
{ 0x0318, 0x88648888 },
{ 0x031c, 0x88135713 },
{ 0x0320, 0x88888888 },
{ 0x0324, 0x23887588 },
{ 0x0328, 0x02000014 },
{ 0x032c, 0x00000000 },
{ 0x0330, 0x00000000 },
{ 0x0334, 0x00000000 },
{ 0x0338, 0x03000000 },
{ 0x033c, 0x0000a50a },
{ 0x0340, 0x1b240000 },
{ 0x0200, 0x00000043 },
{ MAGIC_COMMIT, 0 },
{ 0x0300, 0x20002339 },
display_zalloc: size=41
{ 0x0304, 0x0d0900e0 },
{ 0x0308, 0x413c2723 },
{ 0x030c, 0x0e0d0735 },
{ 0x0310, 0x12101312 },
{ 0x0314, 0x09001812 },
{ 0x0318, 0x3c27230d },
{ 0x031c, 0x0d073541 },
{ 0x0320, 0x1013120e },
{ 0x0324, 0x93181212 },
{ 0x0328, 0x000000bf },
{ 0x0200, 0x00000028 },
{ MAGIC_COMMIT, 0 },
{ 0x0300, 0x36001105 },
{ 0x0200, 0x00000003 },
{ MAGIC_COMMIT, 0 },
{ 0x0300, 0x1c002905 },
{ 0x0200, 0x00000003 },
{ MAGIC_COMMIT, 0 },
};
{ 0x0048, 0x00000f02 },
{ MAGIC_COMMIT, 0 },
dsi_update_bits: 0x01ca0020 : 0000001f -> (00000010) 00000000
{ 0x0048, 0x63f07006 },
{ MAGIC_COMMIT, 0 },
nsh>
```
Testing Zig on PinePhone
```text
DRAM: 2048 MiB
Trying to boot from MMC1
NOTICE: BL31: v2.2(release):v2.2-904-gf9ea3a629
NOTICE: BL31: Built : 15:32:12, Apr 9 2020
NOTICE: BL31: Detected Allwinner A64/H64/R18 SoC (1689)
NOTICE: BL31: Found U-Boot DTB at 0x4064410, model: PinePhone
NOTICE: PSCI: System suspend is unavailable
U-Boot 2020.07 (Nov 08 2020 - 00:15:12 +0100)
DRAM: 2 GiB
MMC: Device 'mmc@1c11000': seq 1 is in use by 'mmc@1c10000'
mmc@1c0f000: 0, mmc@1c10000: 2, mmc@1c11000: 1
Loading Environment from FAT... *** Warning - bad CRC, using default environment
starting USB...
No working controllers found
Hit any key to stop autoboot: 0
switch to partitions #0, OK
mmc0 is current device
Scanning mmc 0:1...
Found U-Boot script /boot.scr
653 bytes read in 3 ms (211.9 KiB/s)
Executing script at 4fc00000
gpio: pin 114 (gpio 114) value is 1
200596 bytes read in 12 ms (15.9 MiB/s)
Uncompressed size: 4624384 = 0x469000
36162 bytes read in 4 ms (8.6 MiB/s)
1078500 bytes read in 50 ms (20.6 MiB/s)
Flattened Device Tree blob at 4fa00000
Booting using the fdt blob at 0x4fa00000
Loading Ramdisk to 49ef8000, end 49fff4e4 ... OK
Loading Device Tree to 0000000049eec000, end 0000000049ef7d41 ... OK
Starting kernel ...
HELLO NUTTX ON PINEPHONE!
- Ready to Boot CPU
- Boot from EL2
- Boot from EL1
- Boot to C runtime for OS Initialize
nx_start: Entry
up_allocate_heap: heap_start=0x0x404e9000, heap_size=0x7b17000
arm64_gic_initialize: TODO: Init GIC for PinePhone
arm64_gic_initialize: CONFIG_GICD_BASE=0x1c81000
arm64_gic_initialize: CONFIG_GICR_BASE=0x1c82000
arm64_gic_initialize: GIC Version is 2
up_timer_initialize: up_timer_initialize: cp15 timer(s) running at 24.00MHz, cycle 24000
up_timer_initialize: _vector_table=0x400cc000
up_timer_initialize: Before writing: vbar_el1=0x4024c000
up_timer_initialize: After writing: vbar_el1=0x400cc000
uart_register: Registering /dev/console
uart_register: Registering /dev/ttyS0
work_start_highpri: Starting high-priority kernel worker thread(s)
nx_start_application: Starting init thread
lib_cxx_initialize: _sinit: 0x400cc000 _einit: 0x400cc000 _stext: 0x40080000 _etext: 0x400cd000
nsh: sysinit: fopen failed: 2
nshn:x _msktfaarttf:s :C PcUo0m:m aBnedg innonti nfgo uInddl
e
L
oNoupt
t
Shell (NSH) NuttX-11.0.0-RC2
nsh> null
task_spawn: name=null entry=0x4009d340 file_actions=0x404ee580 attr=0x404ee588 argv=0x404ee6d0
spawn_execattrs: Setting policy=2 priority=100 for pid=3
HELLO ZIG ON PINEPHONE!
mipi_dsi_dcs_write: channel=0, cmd=29, len=0
!ZIG PANIC!
nuttx_mipi_dsi_dcs_write not implemented™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™™
Stack Trace:
0x4009d7d4
0x4009d340
0x4009d2f4
0x4009d39c
0x4009d358
0x400852fc
nsh>
nsh>
```
Testing GIC Version 2 on PinePhone
```text
HELLO NUTTX ON PINEPHONE!
- Ready to Boot CPU
- Boot from EL2
- Boot from EL1
- Boot to C runtime for OS Initialize
nx_start: Entry
up_allocate_heap: heap_start=0x0x400c4000, heap_size=0x7f3c000
arm64_gic_initialize: TODO: Init GIC for PinePhone
arm64_gic_initialize: CONFIG_GICD_BASE=0x1c81000
arm64_gic_initialize: CONFIG_GICR_BASE=0x1c82000
arm64_gic_initialize: GIC Version is 2
up_timer_initialize: up_timer_initialize: cp15 timer(s) running at 24.00MHz, cycle 24000
up_timer_initialize: _vector_table=0x400a7000
up_timer_initialize: Before writing: vbar_el1=0x40227000
up_timer_initialize: After writing: vbar_el1=0x400a7000
uart_register: Registering /dev/console
uart_register: Registering /dev/ttyS0
work_start_highpri: Starting high-priority kernel worker thread(s)
nx_start_application: Starting init thread
lib_cxx_initialize: _sinit: 0x400a7000 _einit: 0x400a7000 _stext: 0x40080000 _etext: 0x400a8000
nsh: sysinit: fopen failed: 2
nshn:x _msktfaarttf:s :C PcUo0m:m aBnedg innonti nfgo uInddl
e?
L?
oNoupt
t?
Shell (NSH) NuttX-10.3.0-RC2
nsh> uname -a
NuttX 10.3.0-RC2 fc909c6-dirty Sep 1 2022 17:05:44 arm64 qemu-a53
nsh> helo
nsh: helo: command not found
nsh> help
help usage: help [-v] []
. cd dmesg help mount rmdir true xd
[ cp echo hexdump mv set truncate
? cmp exec kill printf sleep uname
basename dirname exit ls ps source umount
break dd false mkdir pwd test unset
cat df free mkrd rm time usleep
Builtin Apps:
getprime hello nsh ostest sh
nsh> hello
task_spawn: name=hello entry=0x4009b1a0 file_actions=0x400c9580 attr=0x400c9588 argv=0x400c96d0
spawn_execattrs: Setting policy=2 priority=100 for pid=3
Hello, World!!
nsh> ls /dev
/dev:
console
null
ram0
ram2
ttyS0
zero
nsh>
?[7mReally kill this window [y/n]?[27m
nsh>
```
Testing GIC Version 2 on QEMU
<code>text
- Ready to Boot CPU
- Boot from EL2
- Boot from EL1
- Boot to C runtime for OS Initialize
nx_start: Entry
up_allocate_heap: heap_start=0x0x402c4000, heap_size=0x7d3c000
arm64_gic_initialize: TODO: Init GIC for PinePhone
arm64_gic_initialize: CONFIG_GICD_BASE=0x8000000
arm64_gic_initialize: CONFIG_GICR_BASE=0x8010000
arm64_gic_initialize: GIC Version is 2
EFGHup_timer_initialize: up_timer_initialize: cp15 timer(s) running at 62.50MHz, cycle 62500
up_timer_initialize: ARM_ARCH_TIMER_IRQ=27
up_timer_initialize: arm64_arch_timer_compare_isr=0x4029b2ac
up_timer_initialize: irq_unexpected_isr=0x402823ec
up_timer_initialize: g_irqvector[0].handler=0x402823ec
up_timer_initialize: g_irqvector[1].handler=0x402823ec
up_timer_initialize: g_irqvector[2].handler=0x402823ec
up_timer_initialize: g_irqvector[3].handler=0x402823ec
up_timer_initialize: g_irqvector[4].handler=0x402823ec
up_timer_initialize: g_irqvector[5].handler=0x402823ec
up_timer_initialize: g_irqvector[6].handler=0x402823ec
up_timer_initialize: g_irqvector[7].handler=0x402823ec
up_timer_initialize: g_irqvector[8].handler=0x402823ec
up_timer_initialize: g_irqvector[9].handler=0x402823ec
up_timer_initialize: g_irqvector[10].handler=0x402823ec
up_timer_initialize: g_irqvector[11].handler=0x402823ec
up_timer_initialize: g_irqvector[12].handler=0x402823ec
up_timer_initialize: g_irqvector[13].handler=0x402823ec
up_timer_initialize: g_irqvector[14].handler=0x402823ec
up_timer_initialize: g_irqvector[15].handler=0x402823ec
up_timer_initialize: g_irqvector[16].handler=0x402823ec
up_timer_initialize: g_irqvector[17].handler=0x402823ec
up_timer_initialize: g_irqvector[18].handler=0x402823ec
up_timer_initialize: g_irqvector[19].handler=0x402823ec
up_timer_initialize: g_irqvector[20].handler=0x402823ec
up_timer_initialize: g_irqvector[21].handler=0x402823ec
up_timer_initialize: g_irqvector[22].handler=0x402823ec
up_timer_initialize: g_irqvector[23].handler=0x402823ec
up_timer_initialize: g_irqvector[24].handler=0x402823ec
up_timer_initialize: g_irqvector[25].handler=0x402823ec
up_timer_initialize: g_irqvector[26].handler=0x402823ec
up_timer_initialize: g_irqvector[27].handler=0x4029b2ac
up_timer_initialize: g_irqvector[28].handler=0x402823ec
up_timer_initialize: g_irqvector[29].handler=0x402823ec
up_timer_initialize: g_irqvector[30].handler=0x402823ec
up_timer_initialize: g_irqvector[31].handler=0x402823ec
up_timer_initialize: g_irqvector[32].handler=0x402823ec
up_timer_initialize: g_irqvector[33].handler=0x402823ec
up_timer_initialize: g_irqvector[34].handler=0x402823ec
up_timer_initialize: g_irqvector[35].handler=0x402823ec
up_timer_initialize: g_irqvector[36].handler=0x402823ec
up_timer_initialize: g_irqvector[37].handler=0x402823ec
up_timer_initialize: g_irqvector[38].handler=0x402823ec
up_timer_initialize: g_irqvector[39].handler=0x402823ec
up_timer_initialize: g_irqvector[40].handler=0x402823ec
up_timer_initialize: g_irqvector[41].handler=0x402823ec
up_timer_initialize: g_irqvector[42].handler=0x402823ec
up_timer_initialize: g_irqvector[43].handler=0x402823ec
up_timer_initialize: g_irqvector[44].handler=0x402823ec
up_timer_initialize: g_irqvector[45].handler=0x402823ec
up_timer_initialize: g_irqvector[46].handler=0x402823ec
up_timer_initialize: g_irqvector[47].handler=0x402823ec
up_timer_initialize: g_irqvector[48].handler=0x402823ec
up_timer_initialize: g_irqvector[49].handler=0x402823ec
up_timer_initialize: g_irqvector[50].handler=0x402823ec
up_timer_initialize: g_irqvector[51].handler=0x402823ec
up_timer_initialize: g_irqvector[52].handler=0x402823ec
up_timer_initialize: g_irqvector[53].handler=0x402823ec
up_timer_initialize: g_irqvector[54].handler=0x402823ec
up_timer_initialize: g_irqvector[55].handler=0x402823ec
up_timer_initialize: g_irqvector[56].handler=0x402823ec
up_timer_initialize: g_irqvector[57].handler=0x402823ec
up_timer_initialize: g_irqvector[58].handler=0x402823ec
up_timer_initialize: g_irqvector[59].handler=0x402823ec
up_timer_initialize: g_irqvector[60].handler=0x402823ec
up_timer_initialize: g_irqvector[61].handler=0x402823ec
up_timer_initialize: g_irqvector[62].handler=0x402823ec
up_timer_initialize: g_irqvector[63].handler=0x402823ec
up_timer_initialize: g_irqvector[64].handler=0x402823ec
up_timer_initialize: g_irqvector[65].handler=0x402823ec
up_timer_initialize: g_irqvector[66].handler=0x402823ec
up_timer_initialize: g_irqvector[67].handler=0x402823ec
up_timer_initialize: g_irqvector[68].handler=0x402823ec
up_timer_initialize: g_irqvector[69].handler=0x402823ec
up_timer_initialize: g_irqvector[70].handler=0x402823ec
up_timer_initialize: g_irqvector[71].handler=0x402823ec
up_timer_initialize: g_irqvector[72].handler=0x402823ec
up_timer_initialize: g_irqvector[73].handler=0x402823ec
up_timer_initialize: g_irqvector[74].handler=0x402823ec
up_timer_initialize: g_irqvector[75].handler=0x402823ec
up_timer_initialize: g_irqvector[76].handler=0x402823ec
up_timer_initialize: g_irqvector[77].handler=0x402823ec
up_timer_initialize: g_irqvector[78].handler=0x402823ec
up_timer_initialize: g_irqvector[79].handler=0x402823ec
up_timer_initialize: g_irqvector[80].handler=0x402823ec
up_timer_initialize: g_irqvector[81].handler=0x402823ec
up_timer_initialize: g_irqvector[82].handler=0x402823ec
up_timer_initialize: g_irqvector[83].handler=0x402823ec
up_timer_initialize: g_irqvector[84].handler=0x402823ec
up_timer_initialize: g_irqvector[85].handler=0x402823ec
up_timer_initialize: g_irqvector[86].handler=0x402823ec
up_timer_initialize: g_irqvector[87].handler=0x402823ec
up_timer_initialize: g_irqvector[88].handler=0x402823ec
up_timer_initialize: g_irqvector[89].handler=0x402823ec
up_timer_initialize: g_irqvector[90].handler=0x402823ec
up_timer_initialize: g_irqvector[91].handler=0x402823ec
up_timer_initialize: g_irqvector[92].handler=0x402823ec
up_timer_initialize: g_irqvector[93].handler=0x402823ec
up_timer_initialize: g_irqvector[94].handler=0x402823ec
up_timer_initialize: g_irqvector[95].handler=0x402823ec
up_timer_initialize: g_irqvector[96].handler=0x402823ec
up_timer_initialize: g_irqvector[97].handler=0x402823ec
up_timer_initialize: g_irqvector[98].handler=0x402823ec
up_timer_initialize: g_irqvector[99].handler=0x402823ec
up_timer_initialize: g_irqvector[100].handler=0x402823ec
up_timer_initialize: g_irqvector[101].handler=0x402823ec
up_timer_initialize: g_irqvector[102].handler=0x402823ec
up_timer_initialize: g_irqvector[103].handler=0x402823ec
up_timer_initialize: g_irqvector[104].handler=0x402823ec
up_timer_initialize: g_irqvector[105].handler=0x402823ec
up_timer_initialize: g_irqvector[106].handler=0x402823ec
up_timer_initialize: g_irqvector[107].handler=0x402823ec
up_timer_initialize: g_irqvector[108].handler=0x402823ec
up_timer_initialize: g_irqvector[109].handler=0x402823ec
up_timer_initialize: g_irqvector[110].handler=0x402823ec
up_timer_initialize: g_irqvector[111].handler=0x402823ec
up_timer_initialize: g_irqvector[112].handler=0x402823ec
up_timer_initialize: g_irqvector[113].handler=0x402823ec
up_timer_initialize: g_irqvector[114].handler=0x402823ec
up_timer_initialize: g_irqvector[115].handler=0x402823ec
up_timer_initialize: g_irqvector[116].handler=0x402823ec
up_timer_initialize: g_irqvector[117].handler=0x402823ec
up_timer_initialize: g_irqvector[118].handler=0x402823ec
up_timer_initialize: g_irqvector[119].handler=0x402823ec
up_timer_initialize: g_irqvector[120].handler=0x402823ec
up_timer_initialize: g_irqvector[121].handler=0x402823ec
up_timer_initialize: g_irqvector[122].handler=0x402823ec
up_timer_initialize: g_irqvector[123].handler=0x402823ec
up_timer_initialize: g_irqvector[124].handler=0x402823ec
up_timer_initialize: g_irqvector[125].handler=0x402823ec
up_timer_initialize: g_irqvector[126].handler=0x402823ec
up_timer_initialize: g_irqvector[127].handler=0x402823ec
up_timer_initialize: g_irqvector[128].handler=0x402823ec
up_timer_initialize: g_irqvector[129].handler=0x402823ec
up_timer_initialize: g_irqvector[130].handler=0x402823ec
up_timer_initialize: g_irqvector[131].handler=0x402823ec
up_timer_initialize: g_irqvector[132].handler=0x402823ec
up_timer_initialize: g_irqvector[133].handler=0x402823ec
up_timer_initialize: g_irqvector[134].handler=0x402823ec
up_timer_initialize: g_irqvector[135].handler=0x402823ec
up_timer_initialize: g_irqvector[136].handler=0x402823ec
up_timer_initialize: g_irqvector[137].handler=0x402823ec
up_timer_initialize: g_irqvector[138].handler=0x402823ec
up_timer_initialize: g_irqvector[139].handler=0x402823ec
up_timer_initialize: g_irqvector[140].handler=0x402823ec
up_timer_initialize: g_irqvector[141].handler=0x402823ec
up_timer_initialize: g_irqvector[142].handler=0x402823ec
up_timer_initialize: g_irqvector[143].handler=0x402823ec
up_timer_initialize: g_irqvector[144].handler=0x402823ec
up_timer_initialize: g_irqvector[145].handler=0x402823ec
up_timer_initialize: g_irqvector[146].handler=0x402823ec
up_timer_initialize: g_irqvector[147].handler=0x402823ec
up_timer_initialize: g_irqvector[148].handler=0x402823ec
up_timer_initialize: g_irqvector[149].handler=0x402823ec
up_timer_initialize: g_irqvector[150].handler=0x402823ec
up_timer_initialize: g_irqvector[151].handler=0x402823ec
up_timer_initialize: g_irqvector[152].handler=0x402823ec
up_timer_initialize: g_irqvector[153].handler=0x402823ec
up_timer_initialize: g_irqvector[154].handler=0x402823ec
up_timer_initialize: g_irqvector[155].handler=0x402823ec
up_timer_initialize: g_irqvector[156].handler=0x402823ec
up_timer_initialize: g_irqvector[157].handler=0x402823ec
up_timer_initialize: g_irqvector[158].handler=0x402823ec
up_timer_initialize: g_irqvector[159].handler=0x402823ec
up_timer_initialize: g_irqvector[160].handler=0x402823ec
up_timer_initialize: g_irqvector[161].handler=0x402823ec
up_timer_initialize: g_irqvector[162].handler=0x402823ec
up_timer_initialize: g_irqvector[163].handler=0x402823ec
up_timer_initialize: g_irqvector[164].handler=0x402823ec
up_timer_initialize: g_irqvector[165].handler=0x402823ec
up_timer_initialize: g_irqvector[166].handler=0x402823ec
up_timer_initialize: g_irqvector[167].handler=0x402823ec
up_timer_initialize: g_irqvector[168].handler=0x402823ec
up_timer_initialize: g_irqvector[169].handler=0x402823ec
up_timer_initialize: g_irqvector[170].handler=0x402823ec
up_timer_initialize: g_irqvector[171].handler=0x402823ec
up_timer_initialize: g_irqvector[172].handler=0x402823ec
up_timer_initialize: g_irqvector[173].handler=0x402823ec
up_timer_initialize: g_irqvector[174].handler=0x402823ec
up_timer_initialize: g_irqvector[175].handler=0x402823ec
up_timer_initialize: g_irqvector[176].handler=0x402823ec
up_timer_initialize: g_irqvector[177].handler=0x402823ec
up_timer_initialize: g_irqvector[178].handler=0x402823ec
up_timer_initialize: g_irqvector[179].handler=0x402823ec
up_timer_initialize: g_irqvector[180].handler=0x402823ec
up_timer_initialize: g_irqvector[181].handler=0x402823ec
up_timer_initialize: g_irqvector[182].handler=0x402823ec
up_timer_initialize: g_irqvector[183].handler=0x402823ec
up_timer_initialize: g_irqvector[184].handler=0x402823ec
up_timer_initialize: g_irqvector[185].handler=0x402823ec
up_timer_initialize: g_irqvector[186].handler=0x402823ec
up_timer_initialize: g_irqvector[187].handler=0x402823ec
up_timer_initialize: g_irqvector[188].handler=0x402823ec
up_timer_initialize: g_irqvector[189].handler=0x402823ec
up_timer_initialize: g_irqvector[190].handler=0x402823ec
up_timer_initialize: g_irqvector[191].handler=0x402823ec
up_timer_initialize: g_irqvector[192].handler=0x402823ec
up_timer_initialize: g_irqvector[193].handler=0x402823ec
up_timer_initialize: g_irqvector[194].handler=0x402823ec
up_timer_initialize: g_irqvector[195].handler=0x402823ec
up_timer_initialize: g_irqvector[196].handler=0x402823ec
up_timer_initialize: g_irqvector[197].handler=0x402823ec
up_timer_initialize: g_irqvector[198].handler=0x402823ec
up_timer_initialize: g_irqvector[199].handler=0x402823ec
up_timer_initialize: g_irqvector[200].handler=0x402823ec
up_timer_initialize: g_irqvector[201].handler=0x402823ec
up_timer_initialize: g_irqvector[202].handler=0x402823ec
up_timer_initialize: g_irqvector[203].handler=0x402823ec
up_timer_initialize: g_irqvector[204].handler=0x402823ec
up_timer_initialize: g_irqvector[205].handler=0x402823ec
up_timer_initialize: g_irqvector[206].handler=0x402823ec
up_timer_initialize: g_irqvector[207].handler=0x402823ec
up_timer_initialize: g_irqvector[208].handler=0x402823ec
up_timer_initialize: g_irqvector[209].handler=0x402823ec
up_timer_initialize: g_irqvector[210].handler=0x402823ec
up_timer_initialize: g_irqvector[211].handler=0x402823ec
up_timer_initialize: g_irqvector[212].handler=0x402823ec
up_timer_initialize: g_irqvector[213].handler=0x402823ec
up_timer_initialize: g_irqvector[214].handler=0x402823ec
up_timer_initialize: g_irqvector[215].handler=0x402823ec
up_timer_initialize: g_irqvector[216].handler=0x402823ec
up_timer_initialize: g_irqvector[217].handler=0x402823ec
up_timer_initialize: g_irqvector[218].handler=0x402823ec
up_timer_initialize: g_irqvector[219].handler=0x402823ec
AKLMNOPBIJQRQRuart_register: Registering /dev/console
QRuart_register: Registering /dev/ttyS0
QRAKLMNOPBIJQRQRQRwork_start_highpri: Starting high-priority kernel worker thread(s)
QRQRQRnx_start_application: StartinQRg init thread
QRQRQRlib_cxx_initialize: _sinit: 0x402a7000 _einit: 0x402a700QR0 _stext: 0x40280000 _etext: 0x402a8000
QRQRQRQRQRQRQRQnsh: sysinit: fopen failed: 2
QRQRQRQRQRQRQRQRQRQRQRQRQnsh: mkfatfs: command not found
QRQRQRQRQ
QNuttShell (NSH) NuttX-10.3.0-RC2
Qnsh> QQRnx_start: CPU0: Beginning Idle Loop
QRQRQRQRRRRRRR</code>
Boot Files for Manjaro Phosh on PinePhone
```text
[manjaro@manjaro-arm ~]$ ls -l /boot
total 38568
-rw-r--r-- 1 root root 1476 Jun 22 08:36 boot.scr
-rw-r--r-- 1 root root 1404 Apr 6 11:51 boot.txt
drwxr-xr-x 3 root root 4096 Oct 16 2021 dtbs
-rw-r--r-- 1 root root 20160520 Jul 3 14:56 Image
-rw-r--r-- 1 root root 8359044 Jul 3 14:56 Image.gz
-rw-r--r-- 1 root root 7327835 Jul 24 14:33 initramfs-linux.img
-rw-r--r-- 1 root root 722223 Apr 6 11:51 u-boot-sunxi-with-spl-pinephone-492.bin
-rw-r--r-- 1 root root 722223 Apr 6 11:51 u-boot-sunxi-with-spl-pinephone-528.bin
-rw-r--r-- 1 root root 722223 Apr 6 11:51 u-boot-sunxi-with-spl-pinephone-552.bin
-rw-r--r-- 1 root root 722223 Apr 6 11:51 u-boot-sunxi-with-spl-pinephone-592.bin
-rw-r--r-- 1 root root 722223 Apr 6 11:51 u-boot-sunxi-with-spl-pinephone-624.bin
[manjaro@manjaro-arm ~]$ ls -l /boot/dtbs
total 8
drwxr-xr-x 2 root root 8192 Jul 24 14:30 allwinner
[manjaro@manjaro-arm ~]$ ls -l /boot/dtbs/allwinner
total 1504
-rw-r--r-- 1 root root 13440 Jul 3 14:56 sun50i-a100-allwinner-perf1.dtb
-rw-r--r-- 1 root root 41295 Jul 3 14:56 sun50i-a64-amarula-relic.dtb
-rw-r--r-- 1 root root 41648 Jul 3 14:56 sun50i-a64-bananapi-m64.dtb
-rw-r--r-- 1 root root 40512 Jul 3 14:56 sun50i-a64-nanopi-a64.dtb
-rw-r--r-- 1 root root 39951 Jul 3 14:56 sun50i-a64-oceanic-5205-5inmfd.dtb
-rw-r--r-- 1 root root 41268 Jul 3 14:56 sun50i-a64-olinuxino.dtb
-rw-r--r-- 1 root root 41397 Jul 3 14:56 sun50i-a64-olinuxino-emmc.dtb
-rw-r--r-- 1 root root 42295 Jul 3 14:56 sun50i-a64-orangepi-win.dtb
-rw-r--r-- 1 root root 40316 Jul 3 14:56 sun50i-a64-pine64.dtb
-rw-r--r-- 1 root root 40948 Jul 3 14:56 sun50i-a64-pine64-lts.dtb
-rw-r--r-- 1 root root 40438 Jul 3 14:56 sun50i-a64-pine64-plus.dtb
-rw-r--r-- 1 root root 42979 Jul 3 14:56 sun50i-a64-pinebook.dtb
-rw-r--r-- 1 root root 53726 Jul 3 14:56 sun50i-a64-pinephone-1.0.dtb
-rw-r--r-- 1 root root 53753 Jul 3 14:56 sun50i-a64-pinephone-1.1.dtb
-rw-r--r-- 1 root root 53718 Jul 3 14:56 sun50i-a64-pinephone-1.2.dtb
-rw-r--r-- 1 root root 44110 Jul 3 14:56 sun50i-a64-pinetab.dtb
-rw-r--r-- 1 root root 44150 Jul 3 14:56 sun50i-a64-pinetab-early-adopter.dtb
-rw-r--r-- 1 root root 40816 Jul 3 14:56 sun50i-a64-sopine-baseboard.dtb
-rw-r--r-- 1 root root 42234 Jul 3 14:56 sun50i-a64-teres-i.dtb
-rw-r--r-- 1 root root 31407 Jul 3 14:56 sun50i-h5-bananapi-m2-plus.dtb
-rw-r--r-- 1 root root 32846 Jul 3 14:56 sun50i-h5-bananapi-m2-plus-v1.2.dtb
-rw-r--r-- 1 root root 31056 Jul 3 14:56 sun50i-h5-emlid-neutis-n5-devboard.dtb
-rw-r--r-- 1 root root 31277 Jul 3 14:56 sun50i-h5-libretech-all-h3-cc.dtb
-rw-r--r-- 1 root root 29939 Jul 3 14:56 sun50i-h5-libretech-all-h3-it.dtb
-rw-r--r-- 1 root root 31872 Jul 3 14:56 sun50i-h5-libretech-all-h5-cc.dtb
-rw-r--r-- 1 root root 29013 Jul 3 14:56 sun50i-h5-nanopi-neo2.dtb
-rw-r--r-- 1 root root 29704 Jul 3 14:56 sun50i-h5-nanopi-neo-plus2.dtb
-rw-r--r-- 1 root root 31401 Jul 3 14:56 sun50i-h5-nanopi-r1s-h5.dtb
-rw-r--r-- 1 root root 31082 Jul 3 14:56 sun50i-h5-orangepi-pc2.dtb
-rw-r--r-- 1 root root 29806 Jul 3 14:56 sun50i-h5-orangepi-prime.dtb
-rw-r--r-- 1 root root 29044 Jul 3 14:56 sun50i-h5-orangepi-zero-plus2.dtb
-rw-r--r-- 1 root root 29131 Jul 3 14:56 sun50i-h5-orangepi-zero-plus.dtb
-rw-r--r-- 1 root root 31911 Jul 3 14:56 sun50i-h6-beelink-gs1.dtb
-rw-r--r-- 1 root root 33042 Jul 3 14:56 sun50i-h6-orangepi-3.dtb
-rw-r--r-- 1 root root 30504 Jul 3 14:56 sun50i-h6-orangepi-lite2.dtb
-rw-r--r-- 1 root root 30287 Jul 3 14:56 sun50i-h6-orangepi-one-plus.dtb
-rw-r--r-- 1 root root 32368 Jul 3 14:56 sun50i-h6-pine-h64.dtb
-rw-r--r-- 1 root root 32882 Jul 3 14:56 sun50i-h6-pine-h64-model-b.dtb
-rw-r--r-- 1 root root 29544 Jul 3 14:56 sun50i-h6-tanix-tx6.dtb
-rw-r--r-- 1 root root 29305 Jul 3 14:56 sun50i-h6-tanix-tx6-mini.dtb
[manjaro@manjaro-arm ~]$ cat /boot/boot.txt
/boot/boot.txt
After modifying, run "pp-uboot-mkscr" to re-generate the U-Boot boot script.
This is the description of the GPIO lines used in this boot script:
GPIO #98 is PD2, or A64 ball W19, which controls the vibrator motor
GPIO #114 is PD18, or A64 ball AB13, which controls the red part of the multicolor LED
GPIO #115 is PD19, or A64 ball AB12, which controls the green part of the multicolor LED
GPIO #116 is PD20, or A64 ball AB11, which controls the blue part of the multicolor LED
gpio set 98
gpio set 114
Set root partition to the second partition of boot device
part uuid ${devtype} ${devnum}:1 uuid_boot
part uuid ${devtype} ${devnum}:2 uuid_root
setenv bootargs loglevel=4 console=tty0 console=${console} earlycon=uart,mmio32,0x01c28000 consoleblank=0 boot=PARTUUID=${uuid_boot} root=PARTUUID=${uuid_root} rw rootwait quiet audit=0 bootsplash.bootfile=bootsplash-themes/manjaro/bootsplash
if load ${devtype} ${devnum}:${distro_bootpart} ${kernel_addr_r} /Image; then
gpio clear 98
if load ${devtype} ${devnum}:${distro_bootpart} ${fdt_addr_r} /dtbs/${fdtfile}; then
if load ${devtype} ${devnum}:${distro_bootpart} ${ramdisk_addr_r} /initramfs-linux.img; then
gpio set 115
booti ${kernel_addr_r} ${ramdisk_addr_r}:${filesize} ${fdt_addr_r};
else
gpio set 116
booti ${kernel_addr_r} - ${fdt_addr_r};
fi;
fi;
fi
EOF
```
GIC Register Dump
Below is the dump of PinePhone's registers for <a>Arm Generic Interrupt Controller version 2</a>...
<code>text
HELLO NUTTX ON PINEPHONE!
- Ready to Boot CPU
- Boot from EL2
- Boot from EL1
- Boot to C runtime for OS Initialize
nx_start: Entry
up_allocate_heap: heap_start=0x0x400c4000, heap_size=0x7f3c000
arm64_gic_initialize: TODO: Init GIC for PinePhone
arm64_gic_initialize: GIC Version is 2
Earm_gic_dump: GIC: Entry arm_gic0_initialize NLINES=224
arm_gic_dump_cpu: CPU Interface Registers:
arm_gic_dump_cpu: ICR: 00000060 PMR: 000000f0 BPR: 00000003 IAR: 000003ff
arm_gic_dump_cpu: RPR: 000000ff HPIR: 000003ff ABPR: 00000000
arm_gic_dump_cpu: AIAR: 00000000 AHPIR: 00000000 IDR: 0202143b
arm_gic_dump_cpu: APR1: 00000000 APR2: 00000000 APR3: 00000000 APR4: 00000000
arm_gic_dump_cpu: NSAPR1: 00000000 NSAPR2: 00000000 NSAPR3: 00000000 NSAPR4: 00000000
arm_gic_dump_distributor: Distributor Registers:
arm_gic_dump_distributor: DCR: 00000000 ICTR: 0000fc66 IIDR: 0200143b?
arm_gic_dump32: ISR[01c81080]
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump32: ISER/ICER[01c81100]
arm_gic_dumpregs: 0000ffff 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump32: ISPR/ICPR[01c81200]
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump32: SAR/CAR[01c81300]
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump4: IPR[01c81400]
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump4: IPTR[01c81800]
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 00000000 00000000 01010100 01010101
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump16: ICFR[01c81c00]
arm_gic_dumpregs: aaaaaaaa 55540000 55555555 55555555
arm_gic_dumpregs: 55555555 55555555 55555555 55555555
arm_gic_dumpregs: 55555555 55555555 55555555 55555555
arm_gic_dumpregs: 55555555 55555555 00000000 00000000
arm_gic_dump32: PPSIR/SPISR[01c81d00]
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump32: NSACR[01c81e00]
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump8: SCPR/SSPR[01c81f10]
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump_distributor: PIDR[01c81fd0]:
arm_gic_dump_distributor: 00000004 00000000 00000000 00000000
arm_gic_dump_distributor: 00000090 000000b4 0000002b
arm_gic_dump_distributor: CIDR[01c81ff0]:
arm_gic_dump_distributor: 0000000d 000000f0 00000005 000000b1
arm_gic_dump: GIC: Exit arm_gic0_initialize NLINES=224
arm_gic_dump_cpu: CPU Interface Registers:
arm_gic_dump_cpu: ICR: 00000060 PMR: 000000f0 BPR: 00000003 IAR: 000003ff
arm_gic_dump_cpu: RPR: 000000ff HPIR: 000003ff ABPR: 00000000
arm_gic_dump_cpu: AIAR: 00000000 AHPIR: 00000000 IDR: 0202143b
arm_gic_dump_cpu: APR1: 00000000 APR2: 00000000 APR3: 00000000 APR4: 00000000
arm_gic_dump_cpu: NSAPR1: 00000000 NSAPR2: 00000000 NSAPR3: 00000000 NSAPR4: 00000000
arm_gic_dump_distributor: Distributor Registers:
arm_gic_dump_distributor: DCR: 00000000 ICTR: 0000fc66 IIDR: 0200143b?
arm_gic_dump32: ISR[01c81080]
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump32: ISER/ICER[01c81100]
arm_gic_dumpregs: 0000ffff 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump32: ISPR/ICPR[01c81200]
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump32: SAR/CAR[01c81300]
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump4: IPR[01c81400]
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dump4: IPTR[01c81800]
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 00000000 00000000 01010100 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dump16: ICFR[01c81c00]
arm_gic_dumpregs: aaaaaaaa 55540000 55555555 55555555
arm_gic_dumpregs: 55555555 55555555 55555555 55555555
arm_gic_dumpregs: 55555555 55555555 55555555 55555555
arm_gic_dumpregs: 55555555 55555555 00000000 00000000
arm_gic_dump32: PPSIR/SPISR[01c81d00]
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump32: NSACR[01c81e00]
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump8: SCPR/SSPR[01c81f10]
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump_distributor: PIDR[01c81fd0]:
arm_gic_dump_distributor: 00000004 00000000 00000000 00000000
arm_gic_dump_distributor: 00000090 000000b4 0000002b
arm_gic_dump_distributor: CIDR[01c81ff0]:
arm_gic_dump_distributor: 0000000d 000000f0 00000005 000000b1
FGarm_gic_dump: GIC: Entry arm_gic_initialize NLINES=224
arm_gic_dump_cpu: CPU Interface Registers:
arm_gic_dump_cpu: ICR: 00000060 PMR: 000000f0 BPR: 00000003 IAR: 000003ff
arm_gic_dump_cpu: RPR: 000000ff HPIR: 000003ff ABPR: 00000000
arm_gic_dump_cpu: AIAR: 00000000 AHPIR: 00000000 IDR: 0202143b
arm_gic_dump_cpu: APR1: 00000000 APR2: 00000000 APR3: 00000000 APR4: 00000000
arm_gic_dump_cpu: NSAPR1: 00000000 NSAPR2: 00000000 NSAPR3: 00000000 NSAPR4: 00000000
arm_gic_dump_distributor: Distributor Registers:
arm_gic_dump_distributor: DCR: 00000000 ICTR: 0000fc66 IIDR: 0200143b?
arm_gic_dump32: ISR[01c81080]
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump32: ISER/ICER[01c81100]
arm_gic_dumpregs: 0000ffff 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump32: ISPR/ICPR[01c81200]
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump32: SAR/CAR[01c81300]
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump4: IPR[01c81400]
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dump4: IPTR[01c81800]
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 00000000 00000000 01010100 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dump16: ICFR[01c81c00]
arm_gic_dumpregs: aaaaaaaa 55540000 55555555 55555555
arm_gic_dumpregs: 55555555 55555555 55555555 55555555
arm_gic_dumpregs: 55555555 55555555 55555555 55555555
arm_gic_dumpregs: 55555555 55555555 00000000 00000000
arm_gic_dump32: PPSIR/SPISR[01c81d00]
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump32: NSACR[01c81e00]
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump8: SCPR/SSPR[01c81f10]
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump_distributor: PIDR[01c81fd0]:
arm_gic_dump_distributor: 00000004 00000000 00000000 00000000
arm_gic_dump_distributor: 00000090 000000b4 0000002b
arm_gic_dump_distributor: CIDR[01c81ff0]:
arm_gic_dump_distributor: 0000000d 000000f0 00000005 000000b1
arm_gic_dump: GIC: Exit arm_gic_initialize NLINES=224
arm_gic_dump_cpu: CPU Interface Registers:
arm_gic_dump_cpu: ICR: 00000061 PMR: 000000f0 BPR: 00000007 IAR: 000003ff
arm_gic_dump_cpu: RPR: 000000ff HPIR: 000003ff ABPR: 00000000
arm_gic_dump_cpu: AIAR: 00000000 AHPIR: 00000000 IDR: 0202143b
arm_gic_dump_cpu: APR1: 00000000 APR2: 00000000 APR3: 00000000 APR4: 00000000
arm_gic_dump_cpu: NSAPR1: 00000000 NSAPR2: 00000000 NSAPR3: 00000000 NSAPR4: 00000000
arm_gic_dump_distributor: Distributor Registers:
arm_gic_dump_distributor: DCR: 00000001 ICTR: 0000fc66 IIDR: 0200143b?
arm_gic_dump32: ISR[01c81080]
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump32: ISER/ICER[01c81100]
arm_gic_dumpregs: 0000ffff 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump32: ISPR/ICPR[01c81200]
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump32: SAR/CAR[01c81300]
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump4: IPR[01c81400]
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 00000000 00000000 80000000 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dumpregs: 80808080 80808080 80808080 80808080
arm_gic_dump4: IPTR[01c81800]
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 00000000 00000000 01010100 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dumpregs: 01010101 01010101 01010101 01010101
arm_gic_dump16: ICFR[01c81c00]
arm_gic_dumpregs: aaaaaaaa 55540000 55555555 55555555
arm_gic_dumpregs: 55555555 55555555 55555555 55555555
arm_gic_dumpregs: 55555555 55555555 55555555 55555555
arm_gic_dumpregs: 55555555 55555555 00000000 00000000
arm_gic_dump32: PPSIR/SPISR[01c81d00]
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump32: NSACR[01c81e00]
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump8: SCPR/SSPR[01c81f10]
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dumpregs: 00000000 00000000 00000000 00000000
arm_gic_dump_distributor: PIDR[01c81fd0]:
arm_gic_dump_distributor: 00000004 00000000 00000000 00000000
arm_gic_dump_distributor: 00000090 000000b4 0000002b
arm_gic_dump_distributor: CIDR[01c81ff0]:
arm_gic_dump_distributor: 0000000d 000000f0 00000005 000000b1
Hup_timer_initialize: up_timer_initialize: cp15 timer(s) running at 24.00MHz, cycle 24000
AMarm_gic_dump: GIC: Exit up_prioritize_irq IRQ=27
arm_gic_dump_cpu: CPU Interface Registers:
arm_gic_dump_cpu: ICR: 00000061 PMR: 000000f0 BPR: 00000007 IAR: 000003ff
arm_gic_dump_cpu: RPR: 000000ff HPIR: 000003ff ABPR: 00000000
arm_gic_dump_cpu: AIAR: 00000000 AHPIR: 00000000 IDR: 0202143b
arm_gic_dump_cpu: APR1: 00000000 APR2: 00000000 APR3: 00000000 APR4: 00000000
arm_gic_dump_cpu: NSAPR1: 00000000 NSAPR2: 00000000 NSAPR3: 00000000 NSAPR4: 00000000
arm_gic_dump_distributor: Distributor Registers:
arm_gic_dump_distributor: DCR: 00000001 ICTR: 0000fc66 IIDR: 0200143b?
arm_gic_dump_distributor: ISR: 00000000 ISER: 0000ffff ISPR: 00000000 SAR: 00000000
arm_gic_dump_distributor: IPR: a0000000 IPTR: 01010100 ICFR: 55540000 SPISR: 00000000
arm_gic_dump_distributor: NSACR: 00000000 SCPR: 00000000
arm_gic_dump_distributor: PIDR[01c81fd0]:
arm_gic_dump_distributor: 00000004 00000000 00000000 00000000
arm_gic_dump_distributor: 00000090 000000b4 0000002b
arm_gic_dump_distributor: CIDR[01c81ff0]:
arm_gic_dump_distributor: 0000000d 000000f0 00000005 000000b1
NOPBIarm_gic_du</code> | [] |
https://avatars.githubusercontent.com/u/473672?v=4 | zeroman | fabioarnold/zeroman | 2022-04-24T10:09:29Z | null | master | 1 | 95 | 5 | 95 | https://api.github.com/repos/fabioarnold/zeroman/tags | - | [
"gamedev",
"games",
"webassembly",
"zig"
] | 231 | false | 2025-05-17T15:05:18Z | true | false | unknown | github | [] | Zero Man
A basic Mega Man clone with Zero as the main character.
Try it: https://zeroman.space
Building and running
Needs <a>Zig</a> master.
```bash
Get the source
$ git clone https://github.com/fabioarnold/zeroman
Build <code>zig-out/lib/main.wasm</code>
$ cd zeroman
$ zig build
Run an HTTP server
$ python3 -m http.server
``` | [] |
https://avatars.githubusercontent.com/u/3848910?v=4 | zigcli | jiacai2050/zigcli | 2022-09-20T14:39:58Z | A toolkit for building command lines programs in Zig. | main | 10 | 90 | 10 | 90 | https://api.github.com/repos/jiacai2050/zigcli/tags | MIT | [
"cli",
"lines-of-code",
"tree",
"zig",
"zig-package"
] | 255 | false | 2025-05-10T13:43:17Z | true | true | unknown | github | [
{
"commit": "refs",
"name": "curl",
"tar_url": "https://github.com/jiacai2050/zig-curl/archive/refs.tar.gz",
"type": "remote",
"url": "https://github.com/jiacai2050/zig-curl"
}
] | 404 | [
"https://github.com/zigcc/zig-cookbook"
] |
https://avatars.githubusercontent.com/u/47650457?v=4 | JETGPIO | Rubberazer/JETGPIO | 2022-04-23T20:08:29Z | C library to manage the GPIO header of the Nvidia Jetson boards | main | 0 | 86 | 16 | 86 | https://api.github.com/repos/Rubberazer/JETGPIO/tags | MIT | [
"gpio",
"gpio-pins",
"i2c",
"jetson",
"jetson-gpio",
"jetson-nano",
"jetson-orin",
"jetson-orin-agx",
"jetson-orin-nano",
"jetson-tx1",
"jetson-xavier-nx",
"lcd1602",
"mpu6050",
"nano",
"nx",
"orin",
"pwm",
"spi",
"zig"
] | 1,884 | false | 2025-05-15T14:10:51Z | false | false | unknown | github | [] | JETGPIO library
<a>UPDATE XAVIER NX NOW SUPPORTED IN BETA</a>.
This was possible thanks to <a>ELEKTRINA</a>, they donated the Xavier's dev kit that allowed me to develop the new version
C library to manage the GPIO header of the Nvidia JETSON boards
<strong><em>IMPORTANT NOTICE: The following applies to the Orin family only. This version of the library installs and works along a kernel module: <a>Jetclocks</a>. This provides extra functionality but the automatic installation process could clash with other tools that also perform automatic updates of the device tree, such as the famous jetson-io.py. In those cases the module can still be installed manually, check the Jetclocks repo for more information.
If you think this could be a problem, you will find the standalone version of JETGPIO with no kernel module here: <a>standalone JETGPIO</a></em></strong>
FUNCTIONALITY:
<ul>
<li>
Supported models:
</li>
<li>
JETSON NANO and TX1
</li>
<li>
JETSON ORIN NANO/NANO SUPER and ORIN NX
</li>
<li>
JETSON ORIN AGX
</li>
<li>
JETSON XAVIER NX
</li>
<li>
GPIO control of all the header pinout as input or output. Low latency, see also <a>The need for speed</a> below for some more information on this
</li>
<li>
Catching rising or falling edges in any header pin working as input. Timestamp of the event in nanoseconds in epoch format is provided
</li>
<li>
PWM (hardware) control on header pins 32, 33 on Nano and Xavier NX and also 15 on Orin Nano/NX, for Orin AGX the pins are: 13, 15 & 18
</li>
<li>
I2C serial communication over pins: 27 (SDA) & 28 (SCL) and 3 (SDA) & 5 (SCL)
</li>
<li>
SPI serial communication over pins: 19 (MOSI), 21 (MISO), 23 (SCK) & 24 (CS0) and 37 (MOSI), 22 (MISO), 13 (SCK) & 18 (CS0)
</li>
<li>
Orin family only, output clocks: Extperiph3 (pin 29) & Extperiph4 (31) in Orin Nano and Extperiph4 (pin 7) in Orin AGX
</li>
<li>
No need of previous kernel configuration, no need to change the device tree, no need to reconfigure via /opt/nvidia/jetson-io/jetson-io.py or the like
</li>
</ul>
INSTALLATION:
NOTICE: make install will automatically install the library and the kernel module but, if you have heavily tuned your: /boot/extlinux/extlinux.conf and device tree blob e.g. remove the default blob and so forth, the automatic module installation might fail, in those cases manual module installation is recommended, see instructions in: <a>Jetclocks</a>
Clone/download the content into any folder in your JETSON, cd to that folder and type:
<code>sudo make
sudo make install
</code>
If you have an Orin, you should reboot at this point to get all the functionality, also make install will print information on screen, keep an eye on that in case something is out of place. To uninstall the library:
<code>sudo make uninstall
</code>
HOW TO:
You will find code examples to learn how to use the library in both: EXAMPLES_C & EXAMPLES_C++ folders, the first one contains all the C examples, the second one contains the same examples ready to compile in C++. To compile the examples you will find instructions in the comment section at the top of each of the example files. I have also added a folder with examples in the Zig programming language to test interoperability.
<ul>
<li>
<a>jetgpio_example.c</a> & <a>jetgpio_example.cpp</a> show how to setup and use any of the pins as Inputs/Outputs, this will allow you to toggle pins from 0V (logic 0) to 3.3V (logic 1) or read the pin as an input where 3.3V at the pin is a logic 1. Note that when reading inputs, floating pins will throw unreliable results (as there is no actual input)
</li>
<li>
<a>jetgpio_edge.c</a> & <a>jetgpio_edge.cpp</a> show how to catch rising or falling edges in any pin working as Input, timestamp in epoch format in nanoseconds is provided
</li>
<li>
<a>jetgpio_PWM_example.c</a> & <a>jetgpio_PWM_example.cpp</a> show how to use the PWM funcionality at pin 32
</li>
<li>
<a>test_PWM.c</a> & <a>test_PWM.cpp</a> show again how to use the PWM funcionality with some LEDs connected and also capturing interruptions
</li>
<li>
<a>jetgpio_i2c_example.c</a> & <a>jetgpio_i2c_example.cpp</a> show how to use the i2c comms to talk to a MPU6050 gyroscope connected to i2c0 (pins 27 & 28)
</li>
<li>
<a>lcd_i2c.c</a> & <a>lcd_i2c.cpp</a> minimalistic example of how to show a message on the screen of a Freenove i2c 1602 LCD display connected to i2c1 (pins 3 & 5)
</li>
<li>
<a>spi_loop.c</a> & <a>spi_loop.cpp</a> show how to run a simple loop test on the SPI port(s) by connecting together pins 19 & 21 for port SPI1 and pins 22 & 37
for port SPI2
</li>
<li>
<a>jetgpio_extperiph.c</a> & <a>spi_loop.cpp</a> show how to source Extperiph4 to pin 31 in Orin Nano or pin 7 in Orin AGX
</li>
<li>
<a>ZIG Examples</a> just for the sake of it
</li>
</ul>
DOCUMENTATION:
<a>Some doxygen documentation here</a>. As a rule of thumb, the library functions names and usage mimic the ones of the pigpio library (which I recommend if you work with Raspberry Pis). Learnt a lot from that one
THE NEED FOR SPEED:
I created a couple of little programs to measure reaction time e.g. how fast an output pin turns from 0 to 1 (3.3v), or how fast a change to an input pin is detected by the library, a diagram of the physical setup is shown below, basically I set up pin 38 as an output and pin 40 as an input and connect both through a resistor to observe the interaction:
Compiling and running <a>jetgpio_round_trip.c</a> I am measuring the time from before executing the function that writes a logic 1 (3.3v) to pin 38 until the point when this is detected (by voltage level not edge interrupt) at pin 40. Here the intention is to measure the worst case scenario of a combination of 2 different actions:
<ul>
<li>a pin changes state from 0 to 1 (output)</li>
<li>a second pin detects a change on its state from 0 to 1 (input) being this change produced by the output pin</li>
</ul>
The results that I am getting for the round trip (total time to execute both actions) by running this program are:
| | Nano Classic | Orin Nano |
| :--- | :---: | ---: |
| Minimum | 1.3 us | 3.1 us ** |
| Maximum | 1.8 us | 4.2 us ** |
Compiling and running <a>jetgpio_speed_edge.c</a> I am trying to measure the time using a similar setup as described above, the difference here is that I am using the library function: gpioSetISRFunc() which basically goes through the linux gpio driver in order to catch rising and falling edges, the reason to use the linux driver for this has to do with the fact that catching interrupts from user space (this is a library after all) is basically 'problematic' for a number of reasons, in short, if driver performance and/or device tree stuff got in my way I would basically replace the current driver by my own, but that is beyond the scope of this library.
| | Nano Classic | Orin Nano |
| :--- | :---: | ---: |
| Minimum | 250 us | 200 us |
| Maximum | 700 us | 1000 us |
Note that this doesn't measure individual actions but the total time to execute both (round trip). It is clear that the timestamp produced by the linux driver is the one to blame for the slow reaction on detecting a change on the input pin, still interesting as there is no meaningful cpu waste as the hardware is producing the interrupt for us (no polling)
Compiling and running <a>jetgpio_output.c</a> I am writing high/low to pin 38 on a continuous loop, what I am getting on the oscilloscope are the following results:
| | Nano Classic | Orin Nano |
| :--- | :---: | ---: |
| Average | 0.6 us | 2 us ** |
**Yes, the new Orin has a slower response/higher latency than the old Jetson Nano, this is due to the fact that writing to some registers is being monitored by an external CPU called BPMP (Boot and Power Management Processor). This CPU is an addition to what is called CPU Complex (the 6 Arm A78A cores that are described on the Orin Nano/NX specs) and is completely independent from the main system, running its own firmware and with an independent device tree. Some of the tasks performed by this CPU are clock and power supply management for peripherals inside the SOM e.g. PWM, GPIO... but it also plays a "firewall" role, in other words before writing to some registers in the standard CPU Complex the writing instructions have to pass through this "firewall" making the whole thing slower. This extra, out of the system security manager can be very useful on some applications but it has obviously a downside. Again sorting this out goes beyond the scope of any user space application (library) and it would imply flashing the Orin after modifying stuff, which is something along with other things like modifying the device tree (and reflashing probably) that I wanted to avoid when I created this library.
JETSON NANO AND ORIN FAMILY PINOUT:
The library uses the typical 40 pin header numbering, taking the dev kit as reference so for instance pin 3 is I2C_2_SDA on Nano, I2C1_SDA on Orin Nano and I2C5_DAT on Orin AGX, pin 1 is 3.3 VDC power and so on. You can check the official NVIDIA pinmux configuration for reference or if not available you can use the ones below:
https://jetsonhacks.com/nvidia-jetson-nano-j41-header-pinout/
https://jetsonhacks.com/nvidia-jetson-orin-nano-gpio-header-pinout/
https://jetsonhacks.com/nvidia-jetson-agx-orin-gpio-header-pinout/
https://jetsonhacks.com/nvidia-jetson-xavier-nx-gpio-header-pinout/
The library has been tested on a Jetson Nano: tegra210 (TX1), on a Jetson Orin Nano, Orin AGX and also on a Xavier NX. | [] |
https://avatars.githubusercontent.com/u/80392719?v=4 | regz | ZigEmbeddedGroup/regz | 2022-03-02T05:52:27Z | Generate zig code from ATDF or SVD files for microcontrollers. | main | 27 | 85 | 28 | 85 | https://api.github.com/repos/ZigEmbeddedGroup/regz/tags | MIT | [
"arm",
"avr",
"embedded",
"mcu",
"microcontroller",
"svd",
"svd2zig",
"tooling",
"zig"
] | 6,236 | false | 2025-04-29T21:24:29Z | true | true | unknown | github | [
{
"commit": "4e80a167d6e13e09e0da77457310401084e758cc.tar.gz",
"name": "libxml2",
"tar_url": "https://github.com/mitchellh/zig-build-libxml2/archive/4e80a167d6e13e09e0da77457310401084e758cc.tar.gz.tar.gz",
"type": "remote",
"url": "https://github.com/mitchellh/zig-build-libxml2"
},
{
"co... | Archived
This repository has been moved into the <a>monorepo</a>
regz
<a></a>
regz is a Zig code generator for microcontrollers. Vendors often publish files
that have the details of special function registers, for ARM this is called a
"System View Description" (SVD), for AVR the format is called ATDF. This tool
outputs a single file for you to start interacting with the hardware:
```zig
const regs = @import("nrf52.zig").registers;
pub fn main() void {
regs.P0.PIN_CNF[17].modify(.{
.DIR = 1,
.INPUT = 1,
.PULL = 0,
.DRIVE = 0,
.SENSE = 0,
});
regs.P0.OUT.modify(.{ .PIN17 = 1 });
}
```
NOTE: just including that file is not enough to run code on a microcontroller,
this is a fairly low-level tool and it is intended that the generated code be
used with something like <a>microzig</a>.
One can get SVD files from your vendor, or another good place is
<a>posborne/cmsis-svd</a>,
it's a python based SVD parser and they have a large number of files available.
For ATDF you need to unzip the appropriate atpack from the
<a>registry</a>.
Building
regz targets zig master.
<code>git clone --recursive https://github.com/ZigEmbeddedGroup/regz.git
cd regz
zig build</code>
Using regz to generate code
Files provided may be either SVD or ATDF.
Provide path on command line:
<code>regz <path-to-svd> > my-chip.zig</code>
Provide schema via stdin, must specify the schema type:
<code>cat my-file.svd | regz --schema svd > my-chip.zig</code>
Does this work for RISC-V?
It seems that manufacturers are using SVD to represent registers on their
RISC-V based products despite it being an ARM standard. At best regz will
generate the register definitions without an interrupt table (for now), if you
run into problems issues will be warmly welcomed!
What about MSP430?
TI does have another type of XML-based register schema, it is also
unimplemented but planned for support.
Okay but I want [some other architecture/format]
The main idea is to target what LLVM can target, however Zig's C backend in
underway so it's likely more exotic architectures could be reached in the
future. If you know of any others we should look into, please make an issue!
Roadmap
<ul>
<li>SVD: mostly implemented and usable for mosts MCUs, but a few finishing touches in order to suss out any bugs:
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> nested clusters
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> order generated exactly as defined in schema
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> finalize derivation of different components
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> comprehensive suite of tests
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> RISC-V interrupt table generation
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> ATDF: AVR's register schema format
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> insert name of Texus Insturment's register schema format for MSP430</li>
</ul> | [
"https://github.com/marnix/microzig"
] |
https://avatars.githubusercontent.com/u/5870990?v=4 | zig-gobject | ianprime0509/zig-gobject | 2022-09-02T22:59:06Z | GObject bindings for Zig using GObject introspection | main | 25 | 79 | 11 | 79 | https://api.github.com/repos/ianprime0509/zig-gobject/tags | 0BSD | [
"bindings",
"gobject",
"gtk",
"gui",
"zig"
] | 6,817 | false | 2025-04-17T18:28:14Z | true | true | 0.14.0 | github | [
{
"commit": "master",
"name": "xml",
"tar_url": "https://github.com/ianprime0509/zig-xml/archive/master.tar.gz",
"type": "remote",
"url": "https://github.com/ianprime0509/zig-xml"
}
] | zig-gobject
Bindings for GObject-based libraries (such as GTK) generated using GObject
introspection data.
Usage
To use the bindings, find the <a>latest release of this
project</a> and add the
desired bindings artifact as a dependency in <code>build.zig.zon</code>. Then, the exposed
bindings can be used as modules. For example:
<code>zig
const gobject = b.dependency("gobject", .{});
exe.root_module.addImport("gtk", gobject.module("gtk4"));
exe.root_module.addImport("adw", gobject.module("adw1"));</code>
The binding generator and generated bindings are tested on Zig 0.14.0 and
master, though support for the latest master may temporarily regress when
breaking changes are made upstream.
Companion projects
<ul>
<li><a>zig-libintl</a> - libintl bindings
for Zig, which provide <code>gettext</code> functions for internationalization.</li>
<li><a>Nonograms</a> - a full application
written using these bindings.</li>
</ul>
Examples
There are several examples in the <code>example</code> directory, which is itself a
runnable project (depending on the <code>bindings</code> directory as a dependency). After
generating the bindings, the examples can be run using <code>zig build run</code> in the
<code>example</code> directory.
Development environment
The bindings generated by this project cover a wide variety of libraries, and it
can be annoying and inconvenient to install these libraries on a host system for
testing purposes. The best way to get a consistent environment for testing is to
use <a>Flatpak</a>:
<ol>
<li>Install <code>flatpak</code>.</li>
<li>Install the GNOME SDK: <code>flatpak install org.gnome.Sdk//48</code></li>
</ol>
The steps above only need to be done once per GNOME SDK version. To enter a
development environment:
<ol>
<li>Run <code>flatpak run --filesystem=home --share=network --share=ipc --socket=fallback-x11 --socket=wayland --device=dri --socket=session-bus org.gnome.Sdk//48</code></li>
<li><code>--filesystem=home</code> - makes the user's home directory available within the
container</li>
<li><code>--share=network</code> - allows network access (needed to fetch <code>build.zig.zon</code>
dependencies)</li>
<li><code>--share=ipc --socket=fallback-x11 --socket=wayland --device=dri</code> - allows
graphical display through X11 or Wayland</li>
<li><code>--socket=session-bus</code> - allows access to the session bus</li>
<li>For convenience, this command is available as a script in this repository:
<code>flatpak-env.sh</code>.</li>
<li>Within the spawned shell, you can use the latest master version of Zig
downloaded from ziglang.org. Since the downloaded Zig is statically linked,
it is usable within the Flatpak environment with no additional setup.</li>
</ol>
Running the binding generator
The binding generator can be invoked using <code>zig build codegen</code>, which accepts
several useful options and is described further below, or by building the
<code>translate-gir</code> binary using <code>zig build</code> and invoking it directly.
<code>zig build codegen</code> requires a set of modules to be used as input. The input
modules can be specified using <code>-Dmodules</code> to provide an explicit list of root
modules for codegen (the codegen process will also discover any necessary
dependencies): for example, <code>zig build codegen -Dmodules=Gtk-4.0</code> will generate
bindings for GTK 4 and anything else it depends on (Gio, GObject, GLib, and many
others).
Alternatively, if a Flatpak development environment is set up (see the section
above), a predefined GIR profile can be selected using <code>-Dgir-profile</code>, which
includes all the modules available in a specific GNOME SDK. The predefined
profiles track the latest two GNOME releases.
GIR files are assumed to be located in <code>/usr/share/gir-1.0</code> unless this is
overridden via <code>-Dgir-files-path</code>.
The bindings are generated to the <code>bindings</code> directory under the build prefix
(by default, <code>zig-out</code>).
Fixing broken GIR files
Sometimes, there are errors in GIR files which result in incorrect or incomplete
bindings. The codegen process can handle this via XSLT stylesheets, which are
named after the modules whose GIR files they correct. This project maintains
stylesheets fixing known GIR issues in <code>gir-fixes</code>.
The XSLT stylesheets are applied using the <code>xsltproc</code> program, which is part of
the libxslt project. At this time, this is a system command dependency; there is
no support yet for building xsltproc from source due to
https://github.com/ianprime0509/zig-libxml2/issues/1
Writing bindings by hand
While the binding generator is capable of generating good bindings from GIR
input, it is sometimes necessary or desirable to bypass GIR for everything
except build-related metadata (library dependencies, etc.) and write Zig
bindings by hand. This is the strategy taken for Cairo, using the Cairo bindings
in <code>binding-overrides</code>.
Any manual binding files present in <code>binding-overrides</code> will cause codegen of
bindings to be skipped for the corresponding modules, using the manual bindings
instead.
Running tests
<code>zig build test</code> will run the binding generator's tests. If bindings have been
generated, the <code>test</code> project directory contains a package depending on them
which runs tests on the generated bindings. The <code>zig build test</code> command in the
<code>test</code> project accepts the same <code>modules</code> and <code>gir-profile</code> options as the
codegen command to specify which modules to test (unlike codegen, the <code>modules</code>
option here specifies a complete list of modules to test: there is no discovery
and testing of dependency modules).
Further reading
<ul>
<li><a>Binding strategy</a></li>
</ul>
License
This project is released under the <a>Zero-Clause BSD
License</a>. The libraries exposed by the
generated bindings are subject to their own licenses. | [] |
https://avatars.githubusercontent.com/u/1519747?v=4 | ZigKit | kubkon/ZigKit | 2022-04-14T20:35:13Z | Zig bindings for low-level macOS frameworks | main | 2 | 76 | 1 | 76 | https://api.github.com/repos/kubkon/ZigKit/tags | MIT | [
"framework",
"macos",
"zig"
] | 21 | false | 2025-05-17T07:16:04Z | true | false | unknown | github | [] | ZigKit
Native Zig bindings for low-level macOS frameworks. | [] |
https://avatars.githubusercontent.com/u/99076655?v=4 | hello-algo-zig | coderonion/hello-algo-zig | 2022-12-28T12:11:11Z | Zig codes for the famous public project 《Hello, Algorithm》|《 Hello,算法 》 about data structures and algorithms. | main | 0 | 71 | 0 | 71 | https://api.github.com/repos/coderonion/hello-algo-zig/tags | MIT | [
"algorithm",
"algorithms",
"data-structure",
"data-structures",
"data-structures-and-algorithms",
"dsa",
"dynamic-programming",
"graph",
"hello-algo",
"leecode",
"linked-list",
"rust",
"search",
"sort",
"zig",
"ziglang"
] | 307 | false | 2025-05-20T03:00:20Z | true | false | unknown | github | [] | Hello-Algo-Zig
<ul>
<li><a><strong>Zig</strong></a> programming language codes for the famous public project <a>krahets/hello-algo</a> about data structures and algorithms.</li>
<li>Go read this great open access e-book now -> <a> hello-algo.com |《Hello, Algorithm》|《 Hello,算法 》</a>. </li>
</ul> | [] |
https://avatars.githubusercontent.com/u/1734672?v=4 | ziggysynth | sinshu/ziggysynth | 2022-09-29T08:01:37Z | A SoundFont MIDI synthesizer written in pure Zig | main | 0 | 71 | 3 | 71 | https://api.github.com/repos/sinshu/ziggysynth/tags | NOASSERTION | [
"audio",
"meltysynth",
"midi",
"soundfont",
"synthesizer",
"zig",
"ziglang"
] | 889 | false | 2025-03-16T05:14:54Z | true | false | unknown | github | [] | ZiggySynth
ZiggySynth is a SoundFont MIDI synthesizer written in pure Zig, ported from <a>MeltySynth for C#</a>.
Features
<ul>
<li>Suitable for both real-time and offline synthesis.</li>
<li>Support for standard MIDI files.</li>
<li>No dependencies other than the standard library.</li>
<li>All the functionality is in <a>a single file</a>.</li>
</ul>
Installation
<ul>
<li>Zig v0.14.x is required.</li>
<li>Copy <a>ziggysynth.zig</a> to your project.</li>
</ul>
Demo
https://www.youtube.com/watch?v=GQj3tF8OdPw
<a></a>
Examples
Some useful aliases:
<code>zig
const ziggysynth = @import("ziggysynth.zig");
const SoundFont = ziggysynth.SoundFont;
const Synthesizer = ziggysynth.Synthesizer;
const SynthesizerSettings = ziggysynth.SynthesizerSettings;
const MidiFile = ziggysynth.MidiFile;
const MidiFileSequencer = ziggysynth.MidiFileSequencer;</code>
An example code to synthesize a simple chord:
```zig
// Load the SoundFont.
var sf2 = try fs.cwd().openFile("TimGM6mb.sf2", .{});
defer sf2.close();
var sound_font = try SoundFont.init(allocator, sf2.reader());
defer sound_font.deinit();
// Create the synthesizer.
var settings = SynthesizerSettings.init(44100);
var synthesizer = try Synthesizer.init(allocator, &sound_font, &settings);
defer synthesizer.deinit();
// Play some notes (middle C, E, G).
synthesizer.noteOn(0, 60, 100);
synthesizer.noteOn(0, 64, 100);
synthesizer.noteOn(0, 67, 100);
// The output buffer (3 seconds).
const sample_count: usize = @intCast(3 * settings.sample_rate);
var left: []f32 = try allocator.alloc(f32, sample_count);
defer allocator.free(left);
var right: []f32 = try allocator.alloc(f32, sample_count);
defer allocator.free(right);
// Render the waveform.
synthesizer.render(left, right);
```
Another example code to synthesize a MIDI file:
```zig
// Load the SoundFont.
var sf2 = try fs.cwd().openFile("TimGM6mb.sf2", .{});
defer sf2.close();
var sound_font = try SoundFont.init(allocator, sf2.reader());
defer sound_font.deinit();
// Create the synthesizer.
var settings = SynthesizerSettings.init(44100);
var synthesizer = try Synthesizer.init(allocator, &sound_font, &settings);
defer synthesizer.deinit();
// Load the MIDI file.
var mid = try fs.cwd().openFile("flourish.mid", .{});
defer mid.close();
var midi_file = try MidiFile.init(allocator, mid.reader());
defer midi_file.deinit();
// Create the sequencer.
var sequencer = MidiFileSequencer.init(&synthesizer);
// Play the MIDI file.
sequencer.play(&midi_file, false);
// The output buffer.
const sample_count = @as(f64, @floatFromInt(settings.sample_rate)) * midi_file.getLength();
var left: []f32 = try allocator.alloc(f32, @intFromFloat(sample_count));
defer allocator.free(left);
var right: []f32 = try allocator.alloc(f32, @intFromFloat(sample_count));
defer allocator.free(right);
// Render the waveform.
sequencer.render(left, right);
```
Todo
<ul>
<li><strong>Wave synthesis</strong>
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> SoundFont reader
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Waveform generator
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Envelope generator
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Low-pass filter
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Vibrato LFO
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Modulation LFO</li>
<li><strong>MIDI message processing</strong>
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Note on/off
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Bank selection
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Modulation
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Volume control
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Pan
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Expression
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Hold pedal
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Program change
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Pitch bend
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Tuning</li>
<li><strong>Effects</strong>
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Reverb
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Chorus</li>
<li><strong>Other things</strong>
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Standard MIDI file support
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Performace optimization</li>
</ul>
License
ZiggySynth is available under <a>the MIT license</a>. | [] |
https://avatars.githubusercontent.com/u/2859122?v=4 | zgltf | kooparse/zgltf | 2022-03-26T07:43:15Z | A glTF parser for Zig codebase. | main | 4 | 68 | 18 | 68 | https://api.github.com/repos/kooparse/zgltf/tags | MIT | [
"gamedev",
"gltf",
"parser",
"zig"
] | 84 | false | 2025-05-13T20:15:20Z | true | true | 0.11.0 | github | [] | glTF parser for Zig codebase
This project is a glTF 2.0 parser written in Zig, aiming to replace the use of some C/C++ libraries. All glTF types are fully documented, so it comes nicely with IDE autocompletion, reducing
back and forth with the <a>specification</a>.
This library intends to mimic the glTF file structure in memory. Thereby it's designed around arrays and indexes instead of pointers as you may see in <code>cgltf</code> or other libraries. Also, it's the <strong>user's responsibility</strong> to load glTF files and their related binaries in memory.
Note: It's not as complete as the glTF specification yet, but because it's straightforward to add new parsed fields, we'll get new stuff incrementally and on-demand.
If you would like to contribute, don't hesitate! :)
Note: The main branch is for the latest Zig release (0.14.x).
Examples
```zig
const std = @import("std");
const Gltf = @import("zgltf");
const allocator = std.heap.page_allocator;
const print = std.debug.print;
pub fn main() void {
const buffer = try std.fs.cwd().readFileAllocOptions(
allocator,
"test-samples/rigged_simple/RiggedSimple.gltf",
512_000,
null,
4,
null
);
defer allocator.free(buf);
<code>var gltf = Self.init(allocator);
defer gltf.deinit();
try gltf.parse(buf);
for (gltf.nodes.items) |node| {
const message =
\\\ Node's name: {s}
\\\ Children count: {}
\\\ Have skin: {}
;
print(message, .{
node.name,
node.children.items.len,
node.skin != null,
});
}
// Or use the debufPrint method.
gltf.debugPrint();
</code>
}
```
Also you could easily load data from an <code>Accessor</code> with <code>getDataFromBufferView</code>:
```zig
const gltf = Gltf.init(allocator);
try gltf.parse(my_gltf_buf);
const bin = try std.fs.cwd().readFileAllocOptions(
allocator,
"test-samples/rigged_simple/RiggedSimple0.bin",
5_000_000,
null,
4,
null
);
defer allocator.free(buf);
var vertices = ArrayList(f32).init(allocator);
defer vertices.deinit();
const mesh = gltf.data.meshes.items[0];
for (mesh.primitives.items) |primitive| {
for (primitive.attributes.items) |attribute| {
switch (attribute) {
// Accessor for mesh vertices:
.position => |accessor_index| {
const accessor = gltf.data.accessors.items[accessor_index];
gltf.getDataFromBufferView(f32, &vertices, accessor, bin);
},
else => {}
}
}
}
```
Also, there is an <code>iterator</code> method that helps you pull data from accessors:
<code>zig
// ...
for (primitive.attributes.items) |attribute| {
switch (attribute) {
.position => |idx| {
const accessor = gltf.data.accessors.items[idx];
var it = accessor.iterator(f32, &gltf, gltf.glb_binary.?);
while (it.next()) |v| {
try vertices.append(.{
.pos = .{ v[0], v[1], v[2] },
.normal = .{ 1, 0, 0 },
.color = .{ 1, 1, 1, 1 },
.uv_x = 0,
.uv_y = 0,
});
}
},
.normal => |idx| {
const accessor = gltf.data.accessors.items[idx];
var it = accessor.iterator(f32, &gltf, gltf.glb_binary.?);
var i: u32 = 0;
while (it.next()) |n| : (i += 1) {
vertices.items[initial_vertex + i].normal = .{ n[0], n[1], n[2] };
}
},
else => {},
}
}</code>
Install
Note: <strong>Zig 0.11.x is required.</strong>
<code>zig
const zgltf = @import("path-to-zgltf/build.zig");
exe.addModule("zgltf", zgltf.module(b));</code>
Features
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> glTF 2.0 json file
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Scenes
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Nodes
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Buffers/BufferViews
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Meshes
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Images
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Materials
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Animations
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Skins
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Cameras
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Parse <code>glb</code> files
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Morth targets
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> Extras data
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> glTF writer
Also, we supports some glTF extensions:
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> khr_lights_punctual
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> khr_materials_emissive_strength
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> khr_materials_ior
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> khr_materials_transmission
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> khr_materials_volume
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> khr_materials_dispersion
Contributing to the project
Don’t be shy about shooting any questions you may have. If you are a beginner/junior, don’t hesitate, I will always encourage you. It’s a safe place here. Also, I would be very happy to receive any kind of pull requests, you will have (at least) some feedback/guidance rapidly.
Behind screens, there are human beings, living any sort of story. So be always kind and respectful, because we all sheer to learn new things. | [
"https://github.com/ashpil/moonshine"
] |
https://avatars.githubusercontent.com/u/499?v=4 | zini | judofyr/zini | 2022-08-04T17:05:58Z | Succinct data structures for Zig | main | 2 | 67 | 2 | 67 | https://api.github.com/repos/judofyr/zini/tags | 0BSD | [
"zig",
"zig-package"
] | 194 | false | 2025-04-25T06:09:52Z | true | true | 0.11.0 | github | [] | Zini
Zini (Zig + Mini) is a <a>Zig</a> library providing some succinct data structures:
<ul>
<li><code>zini.pthash</code>, a <a><strong>minimal perfect hash function</strong></a> construction algorithm, using less than 4 bits per element.</li>
<li><code>zini.ribbon</code>, a <strong>retrieval data structure</strong> (sometimes called a "static function") construction algorithm, having less than 1% overhead.</li>
<li><code>zini.CompactArray</code> stores n-bit numbers tightly packed, leaving no bits unused.
If the largest value in an array is <code>m</code> then you actually only need <code>n = log2(m) + 1</code> bits per element.
E.g. if the largest value is 270, you will get 7x compression using CompactArray over <code>[]u64</code> as it stores each element using only 9 bits (and 64 divided by 9 is roughly 7).</li>
<li><code>zini.DictArray</code> finds all distinct elements in the array, stores each once into a CompactArray (the dictionary), and creates a new CompactArray containing indexes into the dictionary.
This will give excellent compression if there's a lot of repetition in the original array.</li>
<li><code>zini.EliasFano</code> stores increasing 64-bit numbers in a compact manner.</li>
<li><code>zini.darray</code> provides constant-time support for the <code>select1(i)</code> operation which returns the <em>i</em>-th set bit in a <code>std.DynamicBitSetUnmanaged</code>.</li>
</ul>
Overview
PTHash, minimal perfect hash function
<code>zini.pthash</code> contains an implementation of <a>PTHash</a>, a <a>minimal perfect hash function</a> construction algorithm.
Given a set of <code>n</code> elements, with the only requirement being that you can hash them, it generates a hash function which maps each element to a distinct number between <code>0</code> and <code>n - 1</code>.
The generated hash function is extremely small, typically consuming less than <strong>4 <em>bits</em> per element</strong>, regardless of the size of the input type.
The algorithm provides multiple parameters to tune making it possible to optimize for (small) size, (short) construction time, or (short) lookup time.
To give a practical example:
In ~0.6 seconds Zini was able to create a hash function for /usr/share/dict/words containing 235886 words.
The resulting hash function required in total 865682 bits in memory.
This corresponds to 108.2 kB in total or 3.67 bits per word.
In comparison, the original file was 2.49 MB and compressing it with <code>gzip -9</code> only gets it down to 754 kB (which you can't use directly in memory without decompressing it).
It should of course be noted that they don't store the equivalent data as you can't use the generated hash function to determine if a word is present or not in the list.
The comparison is mainly useful to get a feeling of the magnitudes.
Bumped Ribbon Retrieval, a retrieval data structure
<code>zini.ribbon</code> contains an implementation of <a>Bumped Ribbon Retrieval</a> (<em>BuRR</em>), a retrieval data structure.
Given <code>n</code> keys (with the only requirement being that you can hash them) which each have an <code>r</code>-bit value, we'll build a data structure which will return the value for all of the <code>n</code> keys.
However, the keys are actually not stored (we're only using the hash) so if you ask for the value for an <em>unknown</em> key you will get a seemingly random answer; there's no way of knowing whether the key was present in the original dataset or not.
The theoretically minimal amount of space needed to store the <em>values</em> is <code>n * r</code> (we have <code>n</code> <code>r</code>-bit values after all).
We use the term "overhead" to refer to how much <em>extra</em> amount of data we need.
The Bumped Ribbon Retrieval will often have <strong>less than 1% overhead</strong>.
Usage
Zini is intended to be used as a library, but also ships the command-line tools <code>zini-pthash</code> and <code>zini-ribbon</code>.
As the documentation is a bit lacking it might be useful to look through <code>tools/zini-{pthash,ribbon}/main.zig</code> to understand how it's used.
```
USAGE
./zig-out/bin/zini-pthash [build | lookup]
COMMAND: build
Builds hash function for plain text file.
-i, --input
-o, --output
-c
-a, --alpha
-s, --seed
COMMAND: lookup
-i, --input
-k, --key
-b, --benchmark
```
And here's an example run of using <code>zini-pthash</code>.
```
Build zini-pthash:
$ zig build -Drelease-safe
Build a hash function:
$ ./zig-out/bin/zini-pthash build -i /usr/share/dict/words -o words.pth
Reading /usr/share/dict/words...
Building hash function...
Successfully built hash function:
seed: 12323441790160983030
bits: 865554
bits/n: 3.6693741892269993
Writing to words.pth
Look up an index in the hash function:
$ ./zig-out/bin/zini-pthash lookup -i words.pth --key hello
Reading words.pth...
Successfully loaded hash function:
seed: 12323441790160983030
bits: 865554
bits/n: 3.6693741892269993
Looking up key=hello:
112576
```
Acknowledgments
Zini is merely an implementation of existing algorithms and techniques already described in the literature:
<ul>
<li>The <a>PTHash</a> algorithm is described by Giulio Ermanno Pibiri and Roberto Trani in arXiv:2104.10402.</li>
<li>They also implemented PTHash as a C++ library in <a>https://github.com/jermp/pthash</a> under the MIT license.
Zini uses no code directly from that repository, but it has been an invaluable resource for understanding how to implement PTHash in practice.</li>
<li>The <a>BuRR</a> data structure is described by Peter C. Dillinger, Lorenz Hübschle-Schneider, Peter Sanders and Stefan Walzer in arXiv:2109.01892.</li>
</ul>
License
Zini is licensed under the <a>0BSD license</a>. | [
"https://github.com/LittleBigRefresh/FreshPresence"
] |
https://avatars.githubusercontent.com/u/4337696?v=4 | ws | nikneym/ws | 2022-11-23T16:22:22Z | WebSocket library for Zig ⚡ | main | 5 | 65 | 6 | 65 | https://api.github.com/repos/nikneym/ws/tags | MIT | [
"websocket",
"websockets",
"ws",
"zig",
"ziglang"
] | 278 | false | 2025-05-14T04:34:04Z | true | false | unknown | github | [] |
ws
a lightweight WebSocket library for Zig ⚡
Features
<ul>
<li>Only allocates for WebSocket handshake, message parsing and building does not allocate</li>
<li>Ease of use, can be used directly with <code>net.Stream</code></li>
<li>Does buffered reads and writes (can be used with any other reader/writer too)</li>
<li>Supports streaming output thanks to WebSocket fragmentation</li>
</ul>
Example
By default, ws uses the <code>Stream</code> interface of <code>net</code> namespace.
You can use your choice of stream through <code>ws.Client</code> interface.
```zig
test "Simple connection to :8080" {
const allocator = std.testing.allocator;
<code>var cli = try connect(allocator, try std.Uri.parse("ws://localhost:8080"), &.{
.{"Host", "localhost"},
.{"Origin", "http://localhost/"},
});
defer cli.deinit(allocator);
while (true) {
const msg = try cli.receive();
switch (msg.type) {
.text => {
std.debug.print("received: {s}\n", .{msg.data});
try cli.send(.text, msg.data);
},
.ping => {
std.debug.print("got ping! sending pong...\n", .{});
try cli.pong();
},
.close => {
std.debug.print("close", .{});
break;
},
else => {
std.debug.print("got {s}: {s}\n", .{@tagName(msg.type), msg.data});
},
}
}
try cli.close();
</code>
}
```
Planned
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> WebSocket server support
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> TLS support out of the box (tracks <code>std.crypto.tls.Client</code>)
<br/><input type='checkbox' class='w-4 h-4 text-green-500 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' checked disabled></input> Request & response headers
<br/><input type='checkbox' class='w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 rounded focus:ring-blue-500 dark:focus:ring-blue-600 dark:ring-offset-gray-800 focus:ring-2 dark:bg-gray-700 dark:border-gray-600' disabled></input> WebSocket Compression support
Acknowledgements
This library wouldn't be possible without these cool projects & posts:
* <a>truemedian/wz</a>
* <a>frmdstryr/zhp</a>
* <a>treeform/ws</a>
* <a>openmymind.net/WebSocket-Framing-Masking-Fragmentation-and-More</a>
* <a>Writing WebSocket servers</a>
License
MIT License, <a>check out</a>. | [] |
https://avatars.githubusercontent.com/u/43040593?v=4 | zig-dns | dantecatalfamo/zig-dns | 2022-10-31T02:21:03Z | Experimental DNS library implemented in zig | master | 3 | 63 | 4 | 63 | https://api.github.com/repos/dantecatalfamo/zig-dns/tags | MIT | [
"dns",
"dns-library",
"zig",
"zig-library"
] | 88 | false | 2025-05-15T01:47:12Z | true | false | unknown | github | [] | zig-dns
Experimental DNS library implemented in zig.
So far implements <a>RFC 1035</a> plus some updates.
The library itself has no dependencies, the CLI example uses <a><code>zig-network</code></a> to send and receive packets over the network.
<ul>
<li>Library: <code>src/dns.zig</code></li>
<li>CLI test: <code>src/main.zig</code></li>
</ul>
Features
<ul>
<li>Streaming interface</li>
<li>Parse DNS packets</li>
<li>Generate DNS packets</li>
<li>Print packet contents</li>
<li>Label compression</li>
</ul>
Currently supported record types
<ul>
<li>A - A host address</li>
<li>NS - An authoritative name server</li>
<li>MD - A mail destination (Obsolete)</li>
<li>MF - A mail forwarder (Obsolete)</li>
<li>CNAME - The canonical name for an alias</li>
<li>SOA - Marks the start of a zone of authority</li>
<li>MB - A mailbox domain name (Experimental)</li>
<li>MG - A mail group member (Experimental)</li>
<li>MR - A mail rename domain name (Experimental)</li>
<li>NULL - A byte array (Experimental)</li>
<li>WKS - A well known service description</li>
<li>PTR - A domain name pointer</li>
<li>HINFO - Host information</li>
<li>MINFO - Mailbox or mail list information</li>
<li>MX - Mail exchange</li>
<li>TXT - Text strings</li>
<li>RP - Responsible Person <a>RFC 1183</a></li>
<li>AAAA - An IPv6 host address <a>RFC 3596</a></li>
<li>LOC - Location information <a>RFC 1876</a></li>
<li>SRV - Service locator <a>RFC 2782</a></li>
<li>SSHFP - SSH Fingerprint <a>RFC 4255</a>, <a>RFC 6594</a></li>
<li>URI - Uniform Resource Identifier <a>RFC 7553</a></li>
</ul>
Interactive
For testing and development purposes you can call the library interactively from the command line.
<code>Usage: zig-dns <dns-server> <domain> <query-type></code>
Interactive Example
<code>$ zig-dns 1.1.1.1 www.lambda.cx A
Sending bytes: { 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 3, 119, 119, 119, 6, 108, 97, 109, 98, 100, 97, 2, 99, 120, 0, 0, 1, 0, 1 }
Query:
Message {
Header {
ID: 1
Response: false
OpCode: query
Authoritative Answer: false
Truncation: false
Recursion Desired: true
Recursion Available: false
Z: 0
Response Code: no_error
}
Questions {
Question {
Name: www.lambda.cx.
QType: A
QClass: IN
}
}
Ansewrs {
}
Authorities {
}
Additional {
}
}
Recv: { 0, 1, 129, 128, 0, 1, 0, 2, 0, 0, 0, 0, 3, 119, 119, 119, 6, 108, 97, 109, 98, 100, 97, 2, 99, 120, 0, 0, 1, 0, 1, 192, 12, 0, 5, 0, 1, 0, 0, 7, 8, 0, 2, 192, 16, 192, 16, 0, 1, 0, 1, 0, 0, 7, 8, 0, 4, 155, 138, 137, 134 }
Response:
Message {
Header {
ID: 1
Response: true
OpCode: query
Authoritative Answer: false
Truncation: false
Recursion Desired: true
Recursion Available: true
Z: 0
Response Code: no_error
}
Questions {
Question {
Name: www.lambda.cx.
QType: A
QClass: IN
}
}
Ansewrs {
Resource Record {
Name: www.lambda.cx.
Type: CNAME
Class: IN
TTL: 1800
Resource Data Length: 2
Resource Data: lambda.cx.
}
Resource Record {
Name: lambda.cx.
Type: A
Class: IN
TTL: 1800
Resource Data Length: 4
Resource Data: 155.138.137.134
}
}
Authorities {
}
Additional {
}
}</code>
Example Code
```zig
const std = @import("std");
const io = std.io;
const network = @import("network");
const dns = @import("zig-dns/src/dns.zig");
// [...] Main function, allocator, etc.
try network.init();
defer network.deinit();
const sock = try network.connectToHost(allocator, "8.8.8.8", 53, .udp);
defer sock.close();
const writer = sock.writer();
const message = try dns.createQuery(allocator, "lambda.cx", .A);
defer message.deinit();
var message_bytes = try message.to_bytes();
try writer.writeAll(message_bytes);
var recv = [_]u8{0} ** 1024;
const recv_size = try sock.receive(&recv);
const response = try dns.Message.from_bytes(allocator, recv[0..recv_size]);
defer response.deinit();
std.debug.print("Response:\n{any}\n", .{ response });
```
Output:
<code>Response:
Message {
Header {
ID: 1
Response: true
OpCode: query
Authoritative Answer: false
Truncation: false
Recursion Desired: true
Recursion Available: true
Z: 0
Response Code: no_error
}
Questions {
Question {
Name: www.lambda.cx.
QType: A
QClass: IN
}
}
Ansewrs {
Resource Record {
Name: www.lambda.cx.
Type: CNAME
Class: IN
TTL: 1800
Resource Data Length: 2
Resource Data: lambda.cx.
}
Resource Record {
Name: lambda.cx.
Type: A
Class: IN
TTL: 1800
Resource Data Length: 4
Resource Data: 155.138.137.134
}
}
Authorities {
}
Additional {
}
}</code>
Iterative Example
See <a>iterative.zig</a> as an example for how to use this library iteratively. | [] |
https://avatars.githubusercontent.com/u/175068426?v=4 | keylib | Zig-Sec/keylib | 2022-09-25T13:25:01Z | FIDO2/ PassKey compatible authentication library | master | 2 | 60 | 2 | 60 | https://api.github.com/repos/Zig-Sec/keylib/tags | MIT | [
"authentication",
"authenticator",
"ctap",
"ctap2",
"fido2",
"passkey",
"passkeys",
"webauthn",
"zig",
"zig-package",
"ziglang"
] | 1,050 | false | 2025-05-20T01:10:39Z | true | true | unknown | github | [
{
"commit": "refs",
"name": "zbor",
"tar_url": "https://github.com/r4gus/zbor/archive/refs.tar.gz",
"type": "remote",
"url": "https://github.com/r4gus/zbor"
},
{
"commit": "refs",
"name": "hidapi",
"tar_url": "https://github.com/r4gus/hidapi/archive/refs.tar.gz",
"type": "rem... | FIDO2 compatible authenticator and client library written in <a>Zig</a>. The authenticator part requires <strong>zero dynamic allocations</strong>.
<blockquote>
We track the latest stable release of Zig (<code>0.12.0</code>)
</blockquote>
If you want to see an example on how the library could be used, check out <a>PassKeeZ</a>.
| Zig version | keylib version |
|:-----------:|:--------------:|
| 0.13.0 | 0.5.0, 0.5.1, 0.5.2, 0.5.3 |
| 0.14.0 | 0.6.0 |
QA
What is FIDO2?
FIDO2 is a protocol designed for authentication purposes. It can be used as single factor (e.g., as a replacement for password based authentication) or as a second factor (e.g., instead of OTPs).
I've heard the term Passkey but what is that?
Passkey is a marketing term which is used to refer to a specific FIDO2 authenticator configuration. A authenticator can be configured to use so called discoverable credentials (also referred to as resident keys). Those credentials are stored somewhere on your device, e.g. in a encrypted database. Devices can also be protected by some form of user verification. This can be a PIN or a built in user verification method like a finger print scanner. Passkey refers to FIDO2 using discoverable credentials and some form of user verification.
Please note that this is only one interpretation of what PassKey means as the term itself is nowhere defined (see also [Passkeys's: A Shattered Dream](https://fy.blackhats.net.au/blog/2024-04-26-passkeys-a-shattered-dream/)).
How does it work?
FIDO2 uses asymmetric cryptography to ensure the authenticity of the user. A unique credential (key-pair) is created for each relying party (typically a web server) and bound to the relying party id (e.g., google.com). The private key stays on the authenticator and the public key is stored by the relying party. When a user wants to authenticate herself, the relying party sends a nonce (a random byte string meant to be only used once) and some other data, over the client (typically your web browser), to the authenticator. The authenticator looks up the required private key and signs the data with it. The generated signature can then be verified by the relying party using the corresponding public key.
What is the difference between FIDO2, PassKey and WebAuthn?
You might have noticed that FIDO2, PassKey and even WebAuthn are often used interchangeably by some articles and people which can be confusing, especially for people new to the protocol. Here is a short overview:
* `FIDO2` Protocol consisting of two sub-protocols: Client to Authenticator Protocol 2 (`CTAP2`) and Web Authentication (`WebAuthn`)
* `CTAP2` Specification that governs how a authenticator (e.g. YubiKey) should behave and how a authenticator and a client (e.g. web-browser) can communicate with each other.
* `WebAuthn` Specification that defines how web applications can use a authenticator for authentication. This includes the declaration of data structures and Java Script APIs.
* `PassKey`: A authenticator with a specific configuration (see above).
Why should I use FIDO2?
FIDO2 has a lot of advantages compared to passwords:
1. No secret information is shared, i.e. the private key stays on the authenticator or is protected, e.g. using key wrapping.
2. Each credential is bound to a relying party id (e.g. google.com), which makes social engineering attacks, like phishing websites, quite difficult (as long as the client verifies the relying party id properly).
3. Users don't have to be concerned with problems like password complexity.
4. If well implemented, FIDO2 provides a better user experience (e.g., faster logins).
5. A recent paper showed that with some adoptions, FIDO2 is ready for a post quantum world under certain conditions ([FIDO2, CTAP 2.1, and WebAuthn 2: Provable Security and Post-Quantum Instantiation, Cryptology ePrint Archive, Paper 2022/1029](https://eprint.iacr.org/2022/1029.pdf)).
Are there problems with FIDO2?
Yes, there are:
1. The two FIDO2 subprotocols (CTAP2 and WebAuthn) are way more difficult to implement, compared to password authentication.
2. There are more points of failure because you have three parties that are involved in the authentication process (authenticator, client, relying party).
3. Currently not all browsers support the CTAP2 protocol well (especially on Linux).
4. There is no way to verify that a client is trustworthy:
* Rogue clients may communicate with a authenticator without your consent
* Clients may display wrong information
5. The 4th layer introduced for Android, IOS, and Windows to connect authenticators and clients internally could be used as a man in the middle.
Does this library work with all browsers?
Answering this question isn't straightforward. The library, by its nature, is designed to be independent of any particular platform, meaning that you have the responsibility of supplying it with data for processing. To put it differently, you're in charge of creating a functional interface for communicating with a client, typically a web browser. On Linux, we offer a wrapper for the uhid interface, simplifying the process of presenting an application as a USB HID device with a Usage Page of F1D0 on the bus.
**There are known issues with older browsers (including Firefox)**. Newer browser versions should work fine. Tested with:
| Browser | Supported? | Tested version| Notes |
|:-------:|:----------:|:-------------:|:-----:|
| Cromium | ✅ | 119.0.6045.159 (Official Build) Arch Linux (64-bit) | |
| Brave | ✅ | Version 1.62.153 Chromium: 121.0.6167.85 (Official Build) (64-bit) | |
| Firefox | ✅ | 122.0 (64-bit) | |
| Opera | ✅ | version: 105.0.4970.16 chromium: 119.0.6045.159 | |
**Please let me know if you run into issues!**
Does this library implement the whole CTAP2 sepc?
No, we do not fully implement the entire [CTAP2](https://fidoalliance.org/specs/fido-v2.2-rd-20230321/fido-client-to-authenticator-protocol-v2.2-rd-20230321.html#intro) specification. In the initial version of this library, which can be found on GitHub, our aim was to remain completely platform-agnostic and cover most of the CTAP2 specification. However, this approach introduced complexities for both users and developers. The current version of this library strikes a balance between usability and feature completeness.
We offer support for operations like __authenticatorMakeCredential__, __authenticatorGetAssertion__, __authenticatorGetInfo__, and __authenticatorClientPin__, with built-in support for __user verification__ and the __pinUvAuth protocol__ (versions 1 and 2). You are responsible for handling data management tasks (such as secure storage, updates, and deletions), verifying user presence, and conducting user verification. These responsibilities are fulfilled by implementing the necessary callbacks used to instantiate an authenticator (refer to the "Getting Started" section for details).
Zero dynamic allocations?
The authenticator part of this library doesn't allocate any memory dynamically. This has some draw backs like a fixed
size for strings (e.g., rpId, user name, etc.) but also reduces the complexity of the code.
The authenticator example uses `88655` bytes of stack space when compiled with `-Doptimize=ReleaseSmall` on Linux (x86\_64).
> The authenticator example has been profiled using valgrind.
> * `zig build auth-example -Doptimize=ReleaseSmall`
> * `valgrind --tool=drd --show-stack-usage=yes ./zig-out/bin/authenticator`
> * Test page: [webauthn.io](https://webauthn.io/) - Register + Authentication
> `thread 1 finished and used 88655 bytes out of 8388608 on its stack.`
> `ThinkPad-X1-Yoga-3rd 6.5.0-35-generic #35~22.04.1-Ubuntu SMP PREEMPT_DYNAMIC x86_64 GNU/Linux`
Design
Getting Started
We maintain two examples on how to use the library:
<ul>
<li><code>authenticator</code> - <a>https://github.com/r4gus/keylib/blob/master/example/authenticator.zig</a><ul>
<li><strong>Please read the description at the top of the source code for instructions on how to setup uhid correctly</strong></li>
</ul>
</li>
<li><code>client</code> - <a>https://github.com/r4gus/keylib/blob/master/example/client.zig</a></li>
</ul>
Resources
<ul>
<li><a>CTAP2</a> - FIDO Alliance</li>
<li><a>WebAuthn</a> - W3C</li>
<li><a>CBOR RFC8949</a> - C. Bormann and P. Hoffman</li>
</ul>
<strong>FIDO2/Passkey test sites</strong>:
- <a>passkey.org</a>
- <a>webauthn.io</a>
Random Ideas
Protecting secrets using a PIN
Microcontrollers like the rp2040 allow the creation of cheap authenticators but they provide no means to somehow protect
secrets like master passwords, PINs, or credentials. One way one could securely store sensitive data is by making PIN
protection mandatory. Note that this is a tradeof and will render some counters (like the pin retry counter) useless if
an attacker has physical access to the chip, as one can not protect the counters from manipulation.
1. Your authenticator has PIN protection enabled by default, i.e. on first boot a default password is set. You should also
set the _force pin change_ flag to "encourge" the user to change his password.
2. Also on first boot, you create a master password which will encrypt all sensitive data using a AEAD cipher. The master
password itself is encrypted using a secret derived from the PIN.
3. Metadata like retry counters are not encrypted (make sure you __DONT__ store the PIN unencrypted!). This still allows
the blocking of a authenticator (in fact you should automatically reset the authenticator if the retry counter hits zero)
but an attack with physical access could potentially reset the counters giving him unlimited retries.
4. Make sure you disallow any operations on sensitive data without prior authentication (__alwaysUv__).
5. Make sure you only use PIN authentication.
6. During authentication you intercept the PIN hash (after decryption) and derive a deterministic secret from it
using a key derivation function of you choice (e.g. HKDF; but it must always be the same). This secret must have
the same lifetime as the pinUvAuthToken!
7. When the application requires a credential (or other sensitive data) you decrypt the master secret using the
derived secret and the decrypt the actual data with the master secret. If the application wants to overwrite data,
you decrypt the data, update it and the encrypt it using the master secret.
8. After you're done, make sure to overwrite any plain text information no longer required.
9. On pin change, just decrypt the master secret and then re-encrypt it using the secret derived
from the new PIN hash.
| [
"https://github.com/Zig-Sec/PassKeeZ"
] |
https://avatars.githubusercontent.com/u/39247043?v=4 | birth | davidgmbb/birth | 2022-02-12T15:08:43Z | A better operating system | main | 13 | 60 | 3 | 60 | https://api.github.com/repos/davidgmbb/birth/tags | BSD-3-Clause | [
"kernel",
"limine",
"osdev",
"x86-64",
"zig"
] | 14,456 | false | 2025-04-23T12:09:49Z | true | false | unknown | github | [] | [] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.