# QNX 8.0 Codelab: From Bare QEMU Boot to Deterministic Real-Time IPC, Hardened IFS & CI WCET Gates

> **Estimated Time:** 15 minutes  
> **Target Platforms:** QNX SDP 8.0 on QEMU `x86_64` (4-core SMP) & Raspberry Pi 5 (`aarch64le`)  
> **Interactive Companion Studio:** [https://ngominhtam1998.github.io/qnx-pulse/](https://ngominhtam1998.github.io/qnx-pulse/) (Tab 04 — Interactive 6-Step Codelab)  
> **Repository:** [https://github.com/ngominhtam1998/qnx-pulse](https://github.com/ngominhtam1998/qnx-pulse)

---

## What You Will Build & Prove

In safety-critical automotive ADAS and medical robotics systems running on **QNX SDP 8.0**, a single misconfigured channel flag (`_NTO_CHF_FIXED_PRIORITY`) or unhardened `mkifs` buildfile can silently turn an **18 µs** real-time brake command into a **4,820 µs Priority Inversion failure**.

In this 6-step hands-on codelab, you will:

1. Boot **QNX Everywhere / SDP 8.0** cleanly on a 4-core SMP QEMU `x86_64` target with serial debugging.
2. Compile a **least-privilege QNX 8.0 real-time IPC microservice** using `procmgr_ability()`, UID/GID drop, `ChannelCreate`, `MsgSend`/`MsgReceive`/`MsgReply`, and structured `slog2f()`.
3. Lint and harden an **instrumented `.build` image (`procnto-smp-instr`)** and generate a matching **`.secpol` security policy**.
4. Capture live target telemetry (`tracelogger`, `traceprinter`, `pidin threads`, and `slog2info`).
5. Reproduce and visually diagnose a **4,820 µs Priority Inversion** (`9.6×` WCET budget breach) caused by medium-priority preemption on `CPU 0`.
6. Apply QNX 8.0 native **Microkernel Priority Inheritance (`ChannelCreate(0)`)**, prove the **99.6% latency drop (`4,820 µs → 18 µs`)**, and enforce it automatically in **CI/CD** with `qnx-pulse`.

---

## Prerequisites

- **Node.js `>= 20`** (zero external npm packages required for QNX-PULSE!)
- **QNX Software Development Platform (SDP) 8.0** (free for non-commercial use via QNX Everywhere) + QEMU (`qemu-system-x86_64`) for live target compilation/booting
- Clone this repo:
  ```bash
  git clone https://github.com/ngominhtam1998/qnx-pulse.git
  cd qnx-pulse
  npm test   # Verify all 10 unit & integration tests pass locally
  npm start  # Launch QNX-PULSE Host Studio on http://127.0.0.1:4175
  ```

---

## Step 1: Boot QNX Everywhere 8.0 on QEMU `x86_64` (2 min)

Source your QNX SDP 8.0 environment so `qcc`, `mkifs`, `mkqnximage`, and `secpol` are on your `PATH`:

```bash
source ~/qnx800/qnxsdp-env.sh
qcc -V
```

Verify you can generate a standard QEMU `x86_64` QNX 8.0 VM image via `mkqnximage`:

```bash
mkqnximage --type=qemu --arch=x86_64 --build
```

> **QNX 8.0 Engineering Tip:** When building a custom Multiboot `.ifs` for QEMU `x86_64`, **always** pass `-D 8250` to `startup-x86` inside `[virtual=x86_64,multiboot] boot = { ... }`. Without `-D 8250`, launching QEMU with `-serial stdio` leaves the serial terminal completely blank during early kernel initialization.

---

## Step 2: Build the Least-Privilege QNX 8.0 Real-Time IPC Microservice (3 min)

Open [`qnx-target/qnx8_rt_sensor_ipc.c`](qnx-target/qnx8_rt_sensor_ipc.c). It implements a realistic **ADAS Sensor → Brake Actuator** microservice following QNX 8.0 least-privilege defense-in-depth:

1. **Structured Telemetry Registration (`slog2_register`):** Registers a dedicated `rt_ipc` buffer with `slogger2` so WCET breaches (`rtt_us > 500`) log immediately as `SLOG2_ERROR` (Sev 2).
2. **Ability Lockdown (`procmgr_ability`) + Non-Root Drop:** Permits bounded `PROCMGR_AID_PRIORITY` for deterministic scheduling while permanently denying and locking `PROCMGR_AID_REBOOT`, `PROCMGR_AID_SPAWN_SETUID`, and `PROCMGR_AID_MEM_PHYS` before dropping from `UID 0` to `1000:1000`:

```c
int rc = procmgr_ability(
    0,
    PROCMGR_ADN_NONROOT | PROCMGR_AOP_ALLOW | PROCMGR_AOP_INHERIT_NO,
    PROCMGR_AID_PRIORITY,
    PROCMGR_ADN_NONROOT | PROCMGR_AOP_DENY | PROCMGR_AOP_LOCK,
    PROCMGR_AID_REBOOT,
    PROCMGR_AID_SPAWN_SETUID,
    PROCMGR_AID_MEM_PHYS,
    PROCMGR_AID_EOL
);
setgid(1000);
setuid(1000);
```

3. **Synchronous Message Passing (`ChannelCreate` / `MsgReceive` / `MsgSend` / `MsgReply`):** Supports both QNX native Priority Inheritance (`ChannelCreate(0)`) and the `--no-inherit` bug mode (`ChannelCreate(_NTO_CHF_FIXED_PRIORITY)`).

Cross-compile with `qcc` via the provided [`qnx-target/Makefile`](qnx-target/Makefile):

```bash
# For QEMU x86_64:
make -C qnx-target ARCH=x86_64 all

# Or for Raspberry Pi 5 (aarch64le):
make -C qnx-target ARCH=aarch64le all
```

---

## Step 3: Lint & Harden Your `mkifs` `.build` Manifest + `.secpol` Policy (3 min)

Before flashing an image, engineers frequently hit subtle `mkifs` syntax or security pitfalls:

| Rule ID | Severity | Real QNX 8.0 Pitfall | Fix |
| --- | --- | --- | --- |
| `MKIFS-001` | CRITICAL | Spaces around `=` inside `[virtual = x86_64]` | Remove spaces: `[virtual=x86_64,multiboot]` |
| `MKIFS-002` | CRITICAL | Unclosed `{ ... }` block | Close every `boot` / `init` block |
| `MKIFS-003` | CRITICAL | `tracelogger` included with plain `procnto-smp` | Boot `procnto-smp-instr` (instrumented microkernel) |
| `MKIFS-004` | HIGH | Services started before `slogger2` + `waitfor /dev/slog2` | Start `slogger2 -U 21:21 &` and `waitfor /dev/slog2 4` first |
| `MKIFS-005` | HIGH | Custom binaries packaged as `uid=0` without `secpolpush` | Use `[uid=1000 gid=1000 perms=0555]` + `secpolpush` |
| `MKIFS-006` | HIGH | World-writable `perms=0777` | Restrict binaries to `perms=0555` / `0755` |
| `MKIFS-007` | MEDIUM | Missing `startup-x86 -D 8250` on QEMU x86_64 | Add `-D 8250` for serial console output |
| `MKIFS-008` | MEDIUM | Duplicate target paths in IFS | Keep every IFS path unique |
| `MKIFS-009` | MEDIUM | Missing `/bin/sh` or `pidin` | Package shell & `pidin` for target diagnostics |
| `MKIFS-010` | MEDIUM | `slogger2` running as `uid=0` | Launch `slogger2 -U 21:21 &` |

Inspect and lint our hardened manifest [`qnx-target/qnx8_qemu_x86_64.build`](qnx-target/qnx8_qemu_x86_64.build):

```bash
node src/cli.js lint --buildfile qnx-target/qnx8_qemu_x86_64.build
```

Expected output: `Score 100/100 (PASS) | Kernel: procnto-smp-instr | Arch: x86_64`.  
Next, open **Tab 02 (`mkifs & secpol Hardening Linter`)** in QNX-PULSE Studio and click **"Load Broken Buildfile (9 Issues)"** to see all 9 real defects caught live, along with the auto-generated least-privilege `.secpol` policy matching [`qnx-target/sensor_policy.secpol`](qnx-target/sensor_policy.secpol).

Build and boot the hardened IFS image on QEMU:

```bash
make -C qnx-target ARCH=x86_64 ifs
make -C qnx-target ARCH=x86_64 qemu
```

---

## Step 4: Capture Live Kernel Telemetry on Target (2 min)

Inside the QNX 8.0 target shell, capture the three synchronized diagnostic bundles:

```sh
# 1. Record 5 seconds of instrumented microkernel SAT events
tracelogger -n 1 -s 5 -f /tmp/adas_brake.kev &

# 2. Start actuator server (buggy mode: --no-inherit) & run sensor client burst
/usr/bin/qnx8_rt_sensor_ipc --no-inherit &
/usr/bin/qnx8_rt_sensor_ipc client 41001 1 50

# 3. Export human-readable telemetry for QNX-PULSE
traceprinter -f /tmp/adas_brake.kev > /tmp/adas_brake_trace.txt
pidin threads > /tmp/adas_pidin.txt
slog2info > /tmp/adas_slog2.txt
```

Transfer the three `.txt` files to your host workstation (or use the bundled authentic captures in [`samples/`](samples/)).

---

## Step 5: Reproduce & Diagnose the 4,820 µs Priority Inversion Bug (3 min)

Run `qnx-pulse` CLI against the `--no-inherit` ADAS telemetry capture with a `500 µs` WCET budget:

```bash
node src/cli.js audit \
  --buildfile qnx-target/qnx8_qemu_x86_64.build \
  --trace samples/adas_brake_trace.txt \
  --pidin samples/adas_pidin.txt \
  --slog2 samples/adas_slog2.txt \
  --wcet-us 500
```

**What QNX-PULSE catches immediately (Exit Code `1` — FAIL):**

- **IPC `seq=4` Max WCET = `4,820 µs`** (`9.6×` over the `500 µs` budget) and **`seq=7` = `1,940 µs`**.
- **Root Cause (SMP Priority Inversion on CPU 0):**
  1. High-priority `adas_brake_ctl` (PID `41002`, prio **`58`**) sends `MSG_SENDV` to `actuator_srv` (PID `41001`, base prio **`20`**) and blocks in `REPLY`.
  2. Because `--no-inherit` passed `_NTO_CHF_FIXED_PRIORITY` to `ChannelCreate()`, QNX did **not** boost `actuator_srv` to prio `58`.
  3. Medium-priority `lidar_diag_bg` (PID `41009`, prio **`35`**) preempts `actuator_srv` on **CPU 0** for **`4,790 µs`**, starving the brake-by-wire controller!
- **`slog2info` Correlation:** Automatically links Sev 2 `WCET_BREACH seq=4 rtt_us=4820` directly to IPC transaction `#4`.

Open **Tab 01 (`RTOS Trace & IPC Timeline`)** in QNX-PULSE Studio and click **"Focus Inversion Window"** to zoom straight into the red-hatched `6.10 ms → 10.92 ms` preemption window on `CPU 0`.

> **Bonus Check — IPC Deadlock Cycle Detection:** Switch the top preset to **Surgical 1kHz (Deadlock)** and open **Tab 03 (`pidin Deadlock & slog2 Correlator`)** to see QNX-PULSE's Wait-For Graph DFS detector uncover a live circular blocking deadlock (`force_cal_daemon(52010) --[REPLY]--> safety_watchdog(52011) --[SEND]--> force_cal_daemon(52010)`) correlated with a `slog2` Sev 1 `CRITICAL` watchdog timeout!

---

## Step 6: Apply QNX Native Priority Inheritance (`18 µs`) & Automate CI Gate (2 min)

Remove `--no-inherit` (`_NTO_CHF_FIXED_PRIORITY`) so `actuator_srv` creates a standard QNX 8.0 channel:

```c
// Deterministic QNX 8.0 Priority Inheritance (enabled by default with flags = 0):
int chid = ChannelCreate(0);
```

Now when `adas_brake_ctl` (prio `58`) calls `MsgSend()`, the QNX 8.0 microkernel **atomically boosts `actuator_srv` from prio `20` → `58`** for the duration of `MsgReceive()` → `MsgReply()`. Medium-priority `lidar_diag_bg` (prio `35`) can no longer preempt `CPU 0` until the brake command completes!

Re-run the QNX-PULSE CI audit on the fixed telemetry and export a Markdown compliance artifact:

```bash
node src/cli.js audit \
  --buildfile qnx-target/qnx8_qemu_x86_64.build \
  --trace samples/adas_fixed_trace.txt \
  --pidin samples/adas_fixed_pidin.txt \
  --slog2 samples/adas_fixed_slog2.txt \
  --wcet-us 500 \
  --out qnx_audit_report.md
```

### Before vs. After Verification

| Metric | Buggy (`_NTO_CHF_FIXED_PRIORITY`) | Fixed (`ChannelCreate(0)`) | Improvement |
| --- | --- | --- | --- |
| **Max Observed WCET** | `4,820 µs` (FAIL) | **`18 µs` (PASS)** | **-99.6% latency** |
| **p99 IPC Round-Trip** | `4,820 µs` | **`18 µs`** | **267× faster** |
| **WCET Breaches (> 500 µs)** | `2` | **`0`** | Eliminated |
| **SMP Priority Inversions** | `2` | **`0`** | Eliminated |
| **CI Gate Exit Code** | `1` (Blocks PR) | **`0` (Passes PR)** | Fail-closed RTOS CI |

### Wire QNX-PULSE Into GitHub Actions

```yaml
- name: QNX 8.0 Real-Time WCET & Hardening Gate
  run: |
    node src/cli.js audit \
      --buildfile qnx-target/qnx8_qemu_x86_64.build \
      --trace artifacts/traceprinter.txt \
      --pidin artifacts/pidin.txt \
      --slog2 artifacts/slog2info.txt \
      --wcet-us 500 \
      --out qnx_rtos_audit.md
```

---

## Summary

You have completed the full QNX SDP 8.0 deterministic engineering workflow — from least-privilege `procmgr_ability()` + `mkifs`/`secpol` hardening, to live SMP kernel trace visualization, priority-inversion root-cause analysis, IPC deadlock graph detection, and fail-closed CI/CD gating.
