Zig self-hosted backend lowers a seq_cst @atomicRmw(.Xchg) with a discarded result to a plain mov

Finding codegen bugs for atomic operations is fun! I’ll note that I am not a Zig developer. I don’t write code in the language, and I don’t work on the language. I’m just some guy who decided to learn a bit about it.

The Zig programming language has two compilers that are widely used: one generates LLVM IR that libLLVM then builds into native code, and the other is a self-hosted compiler which eschews LLVM and does its own codegen.

It’s important to note that the self-hosted compiler is only currently (as of late October 2026) used on x86_64 Debug targets. All other targets use the LLVM backend by default.

_ = @atomicRmw(u32, p, .Xchg, 1, .seq_cst); is a sequentially consistent exchange. On x86 that is xchg with a memory operand, which is implicitly locked and is a full barrier. When the result is discarded, Zig’s self-hosted x86_64 backend emits a plain mov store instead. A plain store on x86 lets a later load be reordered before it (StoreLoad), so the operation loses its seq_cst ordering. Any build that uses the self-hosted x86_64 backend is affected. That backend is the default for -O Debug on x86_64-linux, and -fno-llvm selects it explicitly.

The same backend emits xchg when the result is used. So does a lock acquired by testing the exchange’s return value, which is not affected. Zig’s LLVM backend and gcc emit xchg in both cases.

This affects softwhare when: code discards the exchange’s result, and then relies on access of a different variable to be executed by the processor after that xchg. An example could be code sets its own flag, then reads another thread’s flag.

Affected: Zig 0.16.0 (Fedora 44 package), 0.17.0 and (current at the time) master 0.18.0-dev.367+187d0bf9e (commit 187d0bf9e483, 2026-10-19), all with the self-hosted x86_64 backend (the default for -O Debug -target x86_64-linux). The LLVM backend (-fllvm) is not affected.

Reproducing the codegen bug

In order to see the codegen bug, you can build a small source file and disassemble it:

export fn xchg_unused(p: *u32) void {
    _ = @atomicRmw(u32, p, .Xchg, 1, .seq_cst);    // BUG: result discarded -> plain mov
}
export fn xchg_used(p: *u32) u32 {                 // control
    return @atomicRmw(u32, p, .Xchg, 1, .seq_cst);
}

We can then compare the result with some C code built with a variety of different toolchains, but gcc -O0 gives us the closest result to the self-hosted Zig compiler’s output.

void xchg_unused(unsigned *p) { (void)__atomic_exchange_n(p, 1, __ATOMIC_SEQ_CST); }

The (annotated) gcc output for the C code looks like this:

+ x86_64-linux-gnu-gcc -O0 -c /repro/src/xchg.c -o /tmp/xchg/gcc-O0/xchg.o
+ cd /tmp/xchg/gcc-O0 && x86_64-linux-gnu-objdump -d --no-addresses --disassemble=xchg_unused xchg.o > xchg_unused.objdump
<xchg_unused>:
	55                   	push   %rbp
	48 89 e5             	mov    %rsp,%rbp
	48 89 7d f8          	mov    %rdi,-0x8(%rbp)
	48 8b 45 f8          	mov    -0x8(%rbp),%rax
	ba 01 00 00 00       	mov    $0x1,%edx
	87 10                	xchg   %edx,(%rax)      # opcode 87: xchg, implicitly locked: correct
	90                   	nop
	5d                   	pop    %rbp
	c3                   	ret
RESULT[gcc -O0 (16.2.1)]: OK, 1 locked/fencing instruction(s)

While we can see the difference in the code generated by the Zig compiler below, annotated as to where the bug is:

+ /opt/zig-0.17.0/zig build-obj /repro/src/xchg.zig -target x86_64-linux -O Debug -femit-bin=/tmp/xchg/zig-0.17.0/xchg.o
+ cd /tmp/xchg/zig-0.17.0 && x86_64-linux-gnu-objdump -d --no-addresses --disassemble=xchg_unused xchg.o > xchg_unused.objdump
+ diff -u /tmp/xchg/gcc-O0/xchg_unused.objdump /tmp/xchg/zig-0.17.0/xchg_unused.objdump
@@ -7,10 +7,12 @@
 <xchg_unused>:
 	55                   	push   %rbp
 	48 89 e5             	mov    %rsp,%rbp
-	48 89 7d f8          	mov    %rdi,-0x8(%rbp)
-	48 8b 45 f8          	mov    -0x8(%rbp),%rax
-	ba 01 00 00 00       	mov    $0x1,%edx
-	87 10                	xchg   %edx,(%rax)      # gcc: the locked exchange…
-	90                   	nop
+	53                   	push   %rbx
+	48 83 ec 08          	sub    $0x8,%rsp
+	48 89 3c 24          	mov    %rdi,(%rsp)
+	be 01 00 00 00       	mov    $0x1,%esi
+	89 37                	mov    %esi,(%rdi)      # …Zig: opcode 89, a plain store, and no lock or fence anywhere
+	48 8d 65 f8          	lea    -0x8(%rbp),%rsp
+	5b                   	pop    %rbx
 	5d                   	pop    %rbp
 	c3                   	ret
RESULT[zig-0.17.0]: BUG, no xchg, lock or mfence: the exchange is a plain store

While there’s a bunch of boilerplate around function entry/exit that differs between the two, the xchg and mov are fairly visible in the middle. If we diff the output of the xchg_used and xchg_unused from the self-hosted Zig compiler, we remove the boiler plate delta:

+ diff -u /tmp/xchg/zig-0.17.0/xchg_unused.objdump /tmp/xchg/zig-0.17.0/xchg_used.objdump
-<xchg_unused>:
+<xchg_used>:
 …
 	be 01 00 00 00       	mov    $0x1,%esi
-	89 37                	mov    %esi,(%rdi)
+	87 37                	xchg   %esi,(%rdi)
+	89 f0                	mov    %esi,%eax

Reproducing at runtime

Since it is always a pile of fun to reproduce concurrency bugs, catching this at runtime means running a bunch of iterations and looking for a fail condition. The following does that, with two threads:

//   thread A: exchange(x, 1) seq_cst; r1 = load(y) seq_cst
//   thread B: exchange(y, 1) seq_cst; r2 = load(x) seq_cst
//
// seq_cst forbids r1 == 0 and r2 == 0 together: whichever exchange comes first in the
// single total order is visible to the other thread's load. The program counts how often
// both loads read 0 in three trials:
//
//   relaxed    monotonic store, then monotonic load. Both-zero is allowed here, and is what
//              x86 does for a plain `mov` store followed by a load. Shows the test can see it.
//   discarded  seq_cst exchange, result discarded. The bug: the self-hosted x86_64 backend
//              emits a plain `mov`, so this behaves like `relaxed`.
//   used       seq_cst exchange, result used. Control: emitted as `xchg`, never both-zero.
//
// Exits 1 if both-zero was seen in either seq_cst trial.
const std = @import("std");

const iterations = 1_000_000;

var x: u32 = 0;
var y: u32 = 0;
var go: u32 = 0; // iteration the threads should run next; set by main
var done: u32 = 0; // threads that finished the current iteration

const Mode = enum { relaxed, discarded, used };

fn Worker(comptime mode: Mode) type {
    return struct {
        fn run(mine: *u32, other: *u32, seen: *u32, old: *u32) void {
            var i: u32 = 1;
            while (i <= iterations) : (i += 1) {
                while (@atomicLoad(u32, &go, .acquire) != i) std.atomic.spinLoopHint();
                switch (mode) {
                    .relaxed => @atomicStore(u32, mine, 1, .monotonic),
                    .discarded => _ = @atomicRmw(u32, mine, .Xchg, 1, .seq_cst), // BUG: plain `mov`
                    .used => old.* = @atomicRmw(u32, mine, .Xchg, 1, .seq_cst), // control: `xchg`
                }
                seen.* = @atomicLoad(u32, other, if (mode == .relaxed) .monotonic else .seq_cst);
                _ = @atomicRmw(u32, &done, .Add, 1, .acq_rel);
            }
        }
    };
}

fn trial(comptime mode: Mode) !u32 {
    const W = Worker(mode);
    var r1: u32 = 0;
    var r2: u32 = 0;
    var old1: u32 = 0;
    var old2: u32 = 0;
    go = 0;
    done = 0;
    const a = try std.Thread.spawn(.{}, W.run, .{ &x, &y, &r1, &old1 });
    const b = try std.Thread.spawn(.{}, W.run, .{ &y, &x, &r2, &old2 });
    var both_zero: u32 = 0;
    var i: u32 = 1;
    while (i <= iterations) : (i += 1) {
        @atomicStore(u32, &x, 0, .seq_cst);
        @atomicStore(u32, &y, 0, .seq_cst);
        @atomicStore(u32, &go, i, .release); // start both threads
        while (@atomicLoad(u32, &done, .acquire) != 2 * i) std.atomic.spinLoopHint();
        if (r1 == 0 and r2 == 0) both_zero += 1; // forbidden in the two seq_cst trials
    }
    a.join();
    b.join();
    return both_zero;
}

pub fn main() !void {
    const relaxed = try trial(.relaxed);
    const discarded = try trial(.discarded);
    const used = try trial(.used);
    std.debug.print("relaxed store+load (allowed):        both loads read 0 in {d} of {d} iterations\n", .{ relaxed, iterations });
    std.debug.print("seq_cst xchg, result discarded:      both loads read 0 in {d} of {d} iterations\n", .{ discarded, iterations });
    std.debug.print("seq_cst xchg, result used (control): both loads read 0 in {d} of {d} iterations\n", .{ used, iterations });
    if (discarded != 0 or used != 0) std.process.exit(1);
}

This will reproduce on x86-64 systems fairly easily. I’ll note that I didn’t get qemu to reproduce when doing usermode emulation on an aarch64 host, so be sure to try on a real x86-64 system (and almost certainly a multi-core one). Below, we have the output of running the binary produced by the self hosted Zig compiler, and then the output of the binary built with the LLVM based one:


    sb-0.17.0 Worker(.discarded): 89 3e   mov    %edi,(%rsi)      # self-hosted: plain store
    sb-0.17.0 Worker(.used): 87 3e        xchg   %edi,(%rsi)
    sb-0.17.0-llvm Worker(.discarded): 87 16   xchg   %edx,(%rsi) # LLVM: xchg either way
+ /tmp/sb/sb-0.17.0
relaxed store+load (allowed):        both loads read 0 in 96990 of 1000000 iterations
seq_cst xchg, result discarded:      both loads read 0 in 128430 of 1000000 iterations   # forbidden, seen 13% of the time
seq_cst xchg, result used (control): both loads read 0 in 0 of 1000000 iterations
RESULT[sb-0.17.0]: BUG, both loads read 0 under seq_cst

+ /tmp/sb/sb-0.17.0-llvm
relaxed store+load (allowed):        both loads read 0 in 41808 of 1000000 iterations
seq_cst xchg, result discarded:      both loads read 0 in 0 of 1000000 iterations      # same source, LLVM backend
seq_cst xchg, result used (control): both loads read 0 in 0 of 1000000 iterations
RESULT[sb-0.17.0-llvm]: OK, seq_cst ordering held

I’ve reproduced this with the 0.16 version shipped in Fedora 44, the upstream 0.17 binaries, and upstream nightly build 0.18.0-dev.367+187d0bf9e.

Okay, but get Volume 3A of the Intel® 64 and IA-32 Architectures Software Developer’s Manual nerdy with me

Specifically, “11.2.2 Memory Ordering in P6 and More Recent Processor Families” in the Intel® 64 and IA-32 Architectures Software Developer’s Manual Volume 3A has two relevant rules:

  1. “Reads may be reordered with older writes to different locations but not with older writes to the same location.” This is what the plain mov allows: a later load can complete before the store is visible to other processors.
  2. “Reads or writes cannot be reordered with I/O instructions, locked instructions, or serializing instructions.” This is what a locked instruction guarantees, and seq_cst requires it.

The Zig language appears to have a big TODO in their language documentation around Atomics, and the std documentation for what the enum is for AtomicOrder. The upstream LLVM docs are rather complete.

“Additionally, the code generator must enforce ordering between SequentiallyConsistent stores followed by SequentiallyConsistent loads” – https://llvm.org/docs/Atomics.html#sequentiallyconsistent

Did I report this upstream?

No, because doing so would be a violation of the Code of Conduct. Specifically, let’s look at the LLM/AI policy part:

Since I used an LLM to help me learn a bit about Zig and how it works, and then got it to help isolate this down, the “No LLMs for finding bugs” undoubtedly applies. Later on, there’s also the explicit example of unacceptable behavior being “Discussing this Code of Conduct“.

I’ve written this up because others may find it interesting, and maybe this helps someone debug their concurrent Zig application at some point.

Swift code for talking to the Shotwell database

A flashback to a few years in the past, this has sat as a draft for too long. See previously: Getting your photos out of Shotwell and Every time I program a Mac…

So…. what does the code to read the Shotwell database look like?

First, we’re going to have to import some of the modules we need:

import Foundation
import SQLite3
import SwiftUI
import Photos

I forget what SwiftUI here is for… I think it’s for my bit of integration with the UI I have.

From here I can start to model the bits of the Shotwell database that I’ll possibly need, but using more idiomatic Swift than raw SQL queries in random places. This is what I ended up for having information about a Photo:

class ShotwellPhotoInfo : Codable, Identifiable, Hashable {
    static func == (lhs: ShotwellPhotoInfo, rhs: ShotwellPhotoInfo) -> Bool {
        return lhs.id == rhs.id
    }
    
    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }
    
    var id : Int32 = 0
    var filename : String = ""
    var translated_filename : String = ""
    var orientation : Int32 = 0
    var original_orientation : Int32 = 0
    var import_id : Int32 = 0
    var event_id : Int32 = 0
    var event : ShotwellEventInfo?
    var transformations : String = ""
    var md5 : String = ""
    var flags: Int32 = 0
    var rating: Int32 = 0
    var title: String = ""
    var raw_backlinks : String = ""
    var backlinks : ShotwellBacklinks?
    var comment : String = ""
    var has_gps : Bool = false
    var gps_lat : Double = 0.0
    var gps_lon : Double = 0.0
}

The comparison function is just comparing the id, which since that’s a primary key in the database, are unique. The hash function also just acts on id because of this.

The translated_filename is not in the Shotwell database, but rather for me to do various transformations on the filename in the shotwell database so that I can actually find the file. The natural translation is going to be for wherever I have mounted my photos, but there were some other weirdness likely due to some symlinks and such I’ve had.

The Shotwell Database Architecture documentation says this:

  • backlinks are persistent links to container objects, i.e. Events and Tags. These are used when a Photo has been removed from one (for example, it’s been trashed or marked offline). If the Photo is returned to the main heap of photos (i.e. untrashed), these backlinks are used to restore its connections to the containers.
https://wiki.gnome.org/Apps/Shotwell/Architecture/Database

So it appears that Backlinks may be rather useful to find out everything I need to know about a Photo that I am looking to import. Thus, we will need to model Events and Tags as well, which are familiar concepts from the Shotwell UI.

Since there are Tags in Shotwell, I need to model them as well:

class ShotwellTag : Codable, Identifiable, Hashable {
    static func == (lhs: ShotwellTag, rhs: ShotwellTag) -> Bool {
        return lhs.id == rhs.id
    }
    
    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }
    let id : Int32
    let name : String
    let photo_id_list : [Int32]
    let time_created : Int32
    let photos : [ShotwellPhotoInfo]
    init(id: Int32, name: String, photo_id_list: [Int32], time_created: Int32, photos: [ShotwellPhotoInfo]) {
        self.id = id
        self.name = name
        self.photo_id_list = photo_id_list
        self.time_created = time_created
        self.photos = photos
    }
}

Again, we have an id as a primary key, and the photos in a tag are referenced as a list of IDs.

For an Event, this is what I ended up with:

struct ShotwellEventInfo : Codable, Identifiable {
    let id : Int32
    let name : String
    let primary_photo_id : Int32
    let time_created : Int32
    let primary_source_id : Int32
    let comment : String
}

and for backlinks:

class ShotwellBacklinks : Codable {
    var tag : [ShotwellTag?] = []
    var event : [String] = []
    var other : [String] = []
}

But as for just getting some basic information out of the database? That we can start off with by having a class for opening it, and run some simple queries, and even display them in the UI just to prove we can.

class ShotwellDatabase {
    var db: OpaquePointer?
    var import_query: OpaquePointer?
    var dbPath : String?
    
    struct db_version {
        var schema_version: Int32 = 0
        var app_version: String = ""
        init() {
            schema_version = 0
            app_version = ""
        }
    }
    
    func open_db(shotwellDB: String) -> Bool {
        dbPath = shotwellDB
        if sqlite3_open(shotwellDB, &db) == SQLITE_OK {
            print("Opened Shotwell Database!")
        }
        return db != nil
    }
    
    func get_db_version() -> db_version {
        let query = "SELECT schema_version, app_version FROM VersionTable"
        var queryStatement: OpaquePointer?
        var r = db_version()
        
        if sqlite3_prepare_v2(db, query, -1, &queryStatement, nil) == SQLITE_OK {
            if sqlite3_step(queryStatement) == SQLITE_ROW {
                r.schema_version = sqlite3_column_int(queryStatement, 0)
                
                guard let app_version = sqlite3_column_text(queryStatement, 1) else {
                    print("Couldn't get app version")
                    r.app_version = ""
                    return r
                }
                
                r.app_version = String(cString: app_version)
            }
        }
        return r
    }

The database version is more about just verifying I could link things together than anything actually useful. Continuing the ShotwellDatabase class, getting the total number of photos is pretty easy (added to the ShotwellDatabase class above):

    
    func get_photos_count() -> Int64 {
        let query = "SELECT COUNT(id) FROM PhotoTable"
        var queryStatement: OpaquePointer?

        if sqlite3_prepare_v2(db, query, -1, &queryStatement, nil) == SQLITE_OK {
            if sqlite3_step(queryStatement) == SQLITE_ROW {
                return sqlite3_column_int64(queryStatement, 0)
            }
        }
        return 0
    }

Again, that’s mostly just useful for some nice “oh look, I linked up the UI to the database” rather than anything of use (although progress bars may want to use it).

So, now that we can talk to the database, we can go and set things up to iterate over all the photos and load them up into memory. I’m not doing anything too fancy here as this is all very quick and dirty, and was literally the first time writing any Swift code.

The below code starts by opening the Database, then get_next_photo will iterate over everything before done_all_photos can close things up. The commented out block of code below does something pretty neat, and that’s print out a JSON representation of our photo. I found this incredibly easy to set up in Swift.

    func start_get_all_photos() -> OpaquePointer? {
        var db: OpaquePointer?
        if sqlite3_open(dbPath, &db) == SQLITE_OK {
            print("Opened Shotwell Database!")
        }
        start_import(db: db)
        return db
    }
    func get_next_photo(db: OpaquePointer?) -> ShotwellPhotoInfo? {
        var photo: ShotwellPhotoInfo?
            do {
                photo = db_get_next_photo(db: db)
                if photo != nil {
/*                    let encoder = JSONEncoder()
                    encoder.outputFormatting = .prettyPrinted
                    let jsonData = try encoder.encode(photo)
                    let jsonString = String(data: jsonData, encoding: .utf8)!
                    photo_info = jsonString
                    print(jsonString)
                    do_some_photo_things()
                    progress += 1 */
                    all_photos[photo!.id] = photo
                }
            } catch { print(error) }
        return photo
    }
    func done_all_photos(db: OpaquePointer?) {
        sqlite3_close(db)
    }

For parsing that row, I have the following class:

class ShotwellPhotoInfo : Codable, Identifiable, Hashable {
    static func == (lhs: ShotwellPhotoInfo, rhs: ShotwellPhotoInfo) -> Bool {
        return lhs.id == rhs.id
    }
    
    func hash(into hasher: inout Hasher) {
        hasher.combine(id)
    }
    
    var id : Int32 = 0
    var filename : String = ""
    var translated_filename : String = ""
    var orientation : Int32 = 0
    var original_orientation : Int32 = 0
    var import_id : Int32 = 0
    var event_id : Int32 = 0
    var event : ShotwellEventInfo?
    var transformations : String = ""
    var md5 : String = ""
    var flags: Int32 = 0
    var rating: Int32 = 0
    var title: String = ""
    var raw_backlinks : String = ""
    var backlinks : ShotwellBacklinks?
    var comment : String = ""
    var has_gps : Bool = false
    var gps_lat : Double = 0.0
    var gps_lon : Double = 0.0
}

and function in the ShotwellDatabase class:

    func db_get_next_photo(db: OpaquePointer?) -> ShotwellPhotoInfo? {
        var r = ShotwellPhotoInfo()
        if sqlite3_step(import_query) == SQLITE_ROW {
            r.id = sqlite3_column_int(import_query, 0)
            r.filename = String(cString: sqlite3_column_text(import_query, 1))
            r.orientation = sqlite3_column_int(import_query, 2)
            r.original_orientation = sqlite3_column_int(import_query, 3)
            r.import_id = sqlite3_column_int(import_query, 4)
            r.event_id = sqlite3_column_int(import_query, 5)
// FIXME:            r.event = get_event_info(db: db, id: r.event_id)
            let transformation = sqlite3_column_text(import_query, 6)
            if let t = transformation {
                r.transformations = String(cString: t)
            }
            let md5 = sqlite3_column_text(import_query, 7)
            if let t = md5 {
                r.md5 = String(cString: t)
            }
            r.flags = sqlite3_column_int(import_query, 8)
            r.rating = sqlite3_column_int(import_query, 9)
            let title = sqlite3_column_text(import_query, 10)
            if let t = title {
                r.title = String(cString: t)
            }
            let backlinks = sqlite3_column_text(import_query, 11)
            if let t = backlinks {
                r.raw_backlinks = String(cString: t)
                r.backlinks = process_backlinks(all_backlinks: r.raw_backlinks)
            }
            let comment = sqlite3_column_text(import_query, 12)
            if let t = comment {
                r.comment = String(cString: t)
            }
            r.has_gps = sqlite3_column_int(import_query, 13) != 0
            r.gps_lat = sqlite3_column_double(import_query, 14)
            r.gps_lon = sqlite3_column_double(import_query, 15)
        } else {
            return nil
        }
        return r
    }

So with that combined, I ended up with my global var all_photos: [Int32: ShotwellPhotoInfo] = [:] containing all the photos in the shotwell database able to be looked up by ID. I’m sure there’s a more idiomatic way to do this in Swift… but the learning as I went, and need to only ever run this once certainly encouraged me to take some shortcuts.

There’s two interesting bits in that code. There’s the process_backlinks function, which does the thing of processing this giant text string that Shotwell stores that points the photo back to everywhere it has been referenced, as well as the FIXME around event information. I ended up giving up on translating Events, as these were never something I used much.

Parsing the backlinks I did with this:

    func process_backlinks(all_backlinks : String) -> ShotwellBacklinks {
        var r = ShotwellBacklinks()
        let backlinks = all_backlinks.split(separator: "\n").map( {String($0)})
        
        for backlink in backlinks {
            let kv = backlink.split(separator: "=")
            switch kv.first {
            case "tag":
                let tag_ids = kv[1].split(separator: "|").map( {Int32($0)})
                for tag_id in tag_ids {
                    if tag_id != nil {
                        if tag_id! > 0 {
                            r.tag.append(all_tags[tag_id!])
                        }
                    }
                }
                break
            case "event":
                let events = kv[1].split(separator: "|").map( {String($0)})
                r.event = events
                break
            default:
                r.other.append(contentsOf: kv.map({String($0)}))
            }
        }
        
        return r
    }

and the very simple ShotwellBacklinks class:

class ShotwellBacklinks : Codable {
    var tag : [ShotwellTag?] = []
    var event : [String] = []
    var other : [String] = []
}

But to start to get a view as to what Tags exist in the shotwell database, we can just go through the TagTable in the Shotwell SQLite database (added to the ShotwellDatabase class above):

    func get_all_tags() {
        var db: OpaquePointer?
        if sqlite3_open(dbPath, &db) == SQLITE_OK {
            print("Opened Shotwell Database!")
        }
        let query = "SELECT id, name, photo_id_list, time_created FROM TagTable"
        var q : OpaquePointer?
        
        if sqlite3_prepare_v2(db, query, -1, &q, nil) != SQLITE_OK {
            print("Failed to prepare query")
            assert(false)
        }
        
        while sqlite3_step(q) == SQLITE_ROW {
            let r = tag_row_to_ShotwellTag(q: q)
            
            all_tags[r.id] = r
            for photo_id in r.photo_id_list {
                photoToTags[photo_id]?.append(r)
            }
        }
        sqlite3_finalize(q)
        sqlite3_close(db)
    }

I did the hacky thing and just added var all_tags: [Int32: ShotwellTag] = [:] as a global variable, that I then used in the UI element showing them (well… via a wrapper, but that’s how that goes).

We just now need the tag_row_to_ShotwellTag that’s called above:

    func tag_row_to_ShotwellTag(q: OpaquePointer?) -> ShotwellTag {
        let id = sqlite3_column_int(q, 0)
        let c_name = sqlite3_column_text(q, 1)
        let c_photo_id_list = sqlite3_column_text(q, 2)
        let time_created = sqlite3_column_int(q, 3  )
        var name : String = ""
        var photo_id_list : [Int32] = []
        var photos : [ShotwellPhotoInfo] = []
        
        if let c_name = c_name {
            name = String(cString: c_name)
        }
        
        if let c_photo_id_list = c_photo_id_list {
            let photo_ids = String(cString: c_photo_id_list).split(separator: ",")
            photo_id_list.reserveCapacity(photo_ids.count)
            for photo_id in photo_ids {
                if photo_id.hasPrefix("thumb") {
                    var id = photo_id
                    id.removeFirst(5)
                    photo_id_list.append(Int32(id, radix: 16)!)
                    let photo = all_photos[Int32(id, radix: 16)!]
                    if photo == nil {
                        print("Couldn't find photo id " + id)
                    } else {
                        photos.append(photo!)
                    }
                } else {
                    print("UNKNOWN PREFIX FOR " + photo_id)
                }
            }
        }
        return ShotwellTag(id: id, name: name, photo_id_list: photo_id_list, time_created: time_created, photos: photos)
    }