davidpritchard.org

An MMXXIV mmixx

· Music

Helluva year, was 2025. Had to do something while the world burned; I elected to run a lot and curate these 2024 tracks.

Of these, I’ve seen a few live over the last few years: Thievery Corporation, City of the Sun, Great Lake Swimmers, Harry Manx, La Force and Milky Chance. Three of them played within a mile of my house, thanks in part to the amazing Red Bird Music.

  1. new jackson. si si si. electronic, 2024.

  2. fred again.. & baby keam. leavemealone. drum & bass, 2022.

  3. jamie xx feat. the avalanches. all you children. electronic, 2024.

  4. thievery corporation. letter to the editor. dub, 2017.

  5. city of the sun. sica. rock, 2023.

  6. daughter. dandelion. rock, 2023.

  7. nilüfer yanya. stabilise. pop, 2021.

  8. foals. mountain at my gates. rock, 2015.

  9. great lake swimmers. flight paths. folk, 2023.

  10. harry manx. coat of mail. folk, 2002.

  11. billie eilish. tv. pop, 2022.

  12. slowdive. shanty. rock, 2023.

  13. la force. outrun the sun. rock, 2023.

  14. hologramme. karkoram. downtempo, 2021.

  15. aera. line of conception. acid jazz, 2022.

  16. bicep feat. clara la san. water. trance, 2022.

  17. aphex twin. minipops 67 [120.2] [source field mix]. experimental, 2014.

  18. james blake. asking to break. pop, 2023.

  19. the marías. no one noticed. pop, 2024.

  20. håkon kornstadt & bugge wesseltoft. yellow is the colour. jazz, 2001.

  21. milky chance & fatoumata diawara. flicker in the dark. pop, 2022.

  22. marbert rocel. dance slow [joakim’s blood moon remix]. acid jazz, 2019.

  23. lazerhawk. king of the streets. synthwave, 2013.

  24. d4vd. leave her. pop, 2024.

  25. sunpalace. rude movements. acid jazz, 2014.

  26. acemo. new love. ambient, 2024.

  27. leon vynehall. midnight on the rainbow road (BAB 5). downtempo, 2015.

  28. else. you. downtempo, 2017.

  29. ross from friends. epiphany. house, 2019.

  30. squarepusher. detroit people mover. ambient, 2020.

  31. svaneborg kardyb. cycles. rock, 2024.

The running groove

· Uncategorized

Bike commuting was my thing. I might do a 5k run once or twice a month, but that was it.

But then I moved to Old Ottawa South and took a job in Kanata. The bike commute would be 50km roundtrip - really not viable. Time was increasingly short, and running has the best “bang for the buck” in terms of the calorie burn per minute. And my neighbourhood is a running dream: between the two banks of the Rideau River and the Rideau Canal, I can pick any of eight great routes for a run, with almost zero traffic lights to manage. The canal is even ploughed down to pavement for the entire winter.

So: I gave running a more serious shot. I ditched my old “barefoot” shoes and the whimsical evolutionary running story that inspired them. I ramped up to a run every week, and then more.

Tamarack Race Day in May 2024 marked my first 10km since the high school cross-country team. It was really a blast - a very friendly, party atmosphere with a huge crowd of runners. I followed that up with a daily run in June, then pushed on to try the “Commander’s Challenge” (5k + 10k, back-to-back) at the Army Run in September.

And so - running is now my main hobby. At 2-3 runs per week at the moment, it’s a pretty reasonable time commitment, though that’ll rise if I go for the half marathon this spring.

The stress relief and sleep improvements are amazing, especially in these… trying political moments. The other motivator is to “model” good exercise/anxiety/sleep management for the kids - which seems to be working; H decided to make track & field her main sport this year.

So finally - I’ve made quite a bit of progress in my total distance and pace over the year. A few fun stats:

202220232024
Total distance190 km360 km857 km
Best 5 km time28:0624:2923:01
Best 5 km pace5:37/km4:54/km4:36/km
Number of 10km+ runs0123

Intervals mix

· Uncategorized

My exercise shifted this year. To date, I’ve mostly been a cyclist, with a bit of running, swimming or cross-country skiing from time-to-time. And I’ve mostly cycled for transportation: commuting or grocery shopping, with the exercise as a side benefit but not the main purpose.

But the last 18 months have been more about running. More on that in a separate post. One of the triggers was an upgrade from regular AirPods - which constantly fell out of my ears if I sweated at all - to AirPods Pro that actually stay in, connected to music playing on my watch. Suddenly, regular running to less monotonous. I could imagine running further, 60 minutes. Or faster.

And so: this mix is a bit more upbeat. Not quite “DJ Tiësto trance rave maxxed out”, but I’ll admit I’ve run to that too.

Part 1

  1. hologramme. aphrodite. electronic, 2023.

  2. justice. pleasure x newjack x civilization (www). house, 2018.

  3. the brothers macklovitch & a-trak feat. leven kali. give love to get some. r&b, 2020.

  4. elle varner feat. j. cole. only want to give it to you. r&b, 2012.

  5. the strike boys. everybody. dub, 2004.

  6. il:lo feat. brain blake. reine. downtempo, 2015.

  7. squarepusher. oberlove. experimental, 2020.

  8. lanark artefax. touch absence. ambient, 2017.

  9. caroline polachek. welcome to my island. pop, 2023.

  10. jordana & tv girl. summer’s over. pop, 2021.

  11. the smile. thin thing. rock, 2022.

  12. hemlocke springs. sever the blight. pop, 2023.

  13. jennylee. tickles. pop, 2021.

  14. sufjan stevens. the owl and the tanager. folk, 2010.

  15. jeremy olander. steps. techno, 2007.

  16. tsha feat. clementine douglas. dancing in the shadows. house, 2022.

  17. sub focus. calling for a sign. drum & bass, 2023.

  18. pola & bryson, goddard. & lens feat. javeon. way up. drum & bass, 2023.

Part 2

  1. the chemical brothers. goodbye. big beat, 2023.

  2. charli xcx. lightning. dance, 2022.

  3. machinedrum feat. kučka. violet. experimental, 2023.

  4. beastie boys. ok. hip hop, 2011.

  5. wax motif & riordan. la samba. house, 2023.

  6. lionel boy. loop. r&b, 2022.

  7. peaking lights. soft escape [moonman mix]. dub, 2020.

  8. dj minx. let it ride. house, 2023.

  9. ver:west. 5 seconds before sunrise. trance, 2020.

  10. jex opolis. mt. belzoni. downtempo, 2017.

  11. otik. subaru dreams. downtempo, 2023.

  12. shigeto. detroit, pt. 1. ambient, 2013.

  13. slowdive. kisses. pop, 2023.

  14. sally shapiro. rent. pop, 2023.

  15. bootleg rascal. head in the clouds. pop, 2016.

  16. asian dub foundation. culture move. dub, 1998.

  17. orbital feat. the little pest. you are the frequency. techno, 2023.

  18. roland tings. lights on the headland. techno, 2020.

  19. quantic. time is the enemy. acid jazz, 2001.

  20. gotan project. época. downtempo, 2001.

  21. taylor swift. safe & sound [taylor’s version]. folk, 2012.

The commuter listen

· Music · 2 comments

As of May 2022, I started driving to my job at Apple, three days a week. Initially, I was using our ancient beige Camry (2001), which I’d delayed repairing and had a godawful loud engine noise. I was holding out on repairs, expecting we’d get an electric vehicle (Chevy Bolt) we’d queued for a few months earlier. Eventually, I gave up on the Bolt, discovered the Camry repairs were trivial and I finally got to listen to music while driving. And then in February, a Bolt finally arrived and I could hear music on a genuinely nice audio system.

So this was my commuter soundtrack. I’ve grown a little tired of music for the time being - moved on to podcasts (like this movie show) and audiobooks for a bit. But I’ll be back to the music again before long.

Part 1

  1. yeah yeah yeahs. burning. rock, 2022.

  2. catfish & the bottlemen. kathleen. rock, 2014.

  3. friendly fires. kiss of life. rock, 2009.

  4. eight and a half. wait up. rock, 2012.

  5. maddie zahm. blind spot. folk, 2021.

  6. luna li. what you’re thinking. pop, 2022.

  7. cut copy. running in the grass. downtempo, 2022.

  8. simian mobile disco. i believe. electronic, 2007.

  9. cannons. bad dream. pop, 2021.

  10. kyle dixon & michael stein. escape. synthwave, 2017.

  11. waveshaper. future vision. synthwave, 2016.

  12. the rapture. i need your love. pop, 2003.

  13. bonobo. ketto. downtempo, 2006.

  14. beach house. only you know. rock, 2022.

  15. khruangbin & leon bridges. mariella. rock, 2022.

  16. jeremy steig. howling for judy. jazz, 1969.

  17. cotonete. super vilain wants love [dj deep & romain poncet remix]. acid jazz, 2020.

  18. the avalanches. take care in your dreaming. downtempo, 2020.

  19. prince innocence. forever & ever. rock, 2020.

  20. cigarettes after sex. pistol. downtempo, 2022.

Part 2

  1. widowspeak. the good ones. folk, 2020.

  2. lord huron. meet me in the woods. rock, 2015.

  3. johnny marr. spirit power and soul. rock, 2022.

  4. solange. losing you. r&b, 2012.

  5. empress of. save me. pop, 2022.

  6. warpaint. champion. rock, 2022.

  7. billie eilish. happier than ever. rock, 2021.

  8. yung lean & fka twigs. bliss. alternative, 2022.

  9. childish gambino. algorhythm. alternative, 2020.

  10. beyoncé. break my soul. pop, 2022.

  11. coma feat. dillon. beyond you and me. house, 2022.

  12. odesza feat. bettye lavette. the last goodbye. electronic, 2022.

  13. plaid. clock. ambient, 2016.

  14. com truise. … of your fake dimension. synthwave, 2017.

  15. robert parker. sweet nothings. synthwave, 2016.

  16. youngblood. 5 seconds of summer. pop, 2018.

  17. the weeknd. out of time. r&b, 2022.

  18. troublemakers. chez roger boite funk. acid jazz, 2001.

Soundtrack to Capstone a Pandemic

· Music

So there was a pandemic. During which I listened to my last mix, over and over again; as I jogged the exact same riverside route, and my misfitted left-ear AirPod kept falling out.

And I continued listening, and accumulating tracks. For various reasons™, I couldn’t listen to my accumulating list until recently; so the music here wasn’t exactly a soundtrack to the pandemic for me. But now, I’ve finally assembled it.

This one’s in three parts: a two-disc 2020-21 set, and a 2022 set coming up next. Traditionally, I’ve limited myself to the ~100 minutes of a CD; but whatever, let’s go with three full hours, and so we get digressively long tracks like Venice Bitch, Beau Mot Plage and America.

The primary consumer of these mixes is… me, let’s be honest. And one of the main benefits is a bunch of links I can click to find the artists’ full albums in Apple Music. So… no more obsessive MP3ing, relevelling and mixing with ancient 2004 Audacity builds.

part 1

  1. hologramme feat. fakear. felicity [fakear remix]. downtempo, 2020.

  2. kilder & jamal bucanon. what i won’t do. pop, 2020.

  3. alfie templeman. shady. pop, 2021

  4. grandson. dirty. pop, 2020.

  5. 347aidan. dancing in my room. pop, 2020.

  6. frank ocean. pink + white. r&b, 2016.

  7. washed out. too late. downtempo, 2020.

  8. caribou. lime. pop, 2020.

  9. mount kimbie. four years and one day. electronic, 2017.

  10. moderat. animal trails. experimental, 2016.

  11. luke howard. bear story i [ben lukas boysen rework]. techno, 2019.

  12. billie eilish. everything i wanted. pop, 2019.

  13. allan rayman. rose. pop, 2018.

  14. massive attack. paradise circus [gui boratto remix]. downtempo, 2010.

  15. donna missal. (to me) your face is love. pop, 2021.

  16. art school girlfriend. diving. rock, 2019.

  17. lana del rey. venice bitch. pop, 2019.

  18. flume feat. toro y moi. the difference. rock, 2020.

  19. new jackson. romancecar. downtempo, 2019.

  20. aurora. cure for me. house, 2022.

  21. shire t. burnin’ jungle. pop, 2021.

part 2

  1. e.vax. manila. acid jazz, 2022.

  2. against all logic. you (forever). experimental, 2022.

  3. the midnight. neon medusa. synthwave, 2021.

  4. gorgon city & drama. you’ve done enough. house, 2021.

  5. jordan rakei. family. r&b, 2021.

  6. james blake. retrograde. r&b, 2013.

  7. tsha. me you. techno, 2019.

  8. major lazer & nucleya feat. rashmeet kaur. jadi buti. dub, 2020.

  9. rae & christian. ready to roll [bushy remix]. acid jazz, 2002.

  10. soul square feat. pfel & atom. live and uncut. hip hop, 2010.

  11. isolée. beau mot plage [freedom reform, pt. 1 & 2]. acid jazz, 1999.

  12. plants and animals. sacrifice. rock, 2020.

  13. i break horses. silence. rock, 2020.

  14. clairo. zinnias. folk, 2021.

  15. arlo parks. sophie. pop, 2019.

  16. thievery corporation feat. gunjan. doors of perception. dub, 2005.

  17. mac ayres. jumping off the moon. r&b, 2019.

  18. fink. hard believer. blues, 2014.

  19. handsome boy modeling school feat. roisin & j-live. the truth. hip hop, 1999.

  20. girl in red. midnight love. pop, 2020.

  21. booka shade & kaktus einarsson. perfect in a way. techno, 2020.

  22. sufjan stevens. america. rock, 2020.

C++ Stack Traces on UWP

· C++, windows · 1 comment

In early 2019, I was working on an app (Mental Canvas Draw) that was in private beta on the Windows Store. There was a nice, robust system to show you which crashes were most common your app. Then suddenly - it disappeared, and instead there was a big stream of “Unknown” class crashes.

This caused much wailing and gnashing of teeth. I assumed that it would be fixed. Microsoft had recently acquired HockeyApp and was revamping it into Visual Studio AppCenter. Surely that would provide a replacement! Six months passed, a year passed, two years passed, and… nothing for C++ users. (I understand that AppCenter provides a solution for C# users.)

Some wailing

Some gnashing of teeth

That app was released widely in March 2021, and I realized an important fact: if you have a large volume of users and/or crashes, you get a valid list of stack traces! There seems to be something about the level of usage per package version that’s important. For <100 crashes per version, I get 0% stack traces; for <250 I get very few; and for the version with 750 crashes I get good (64%) stack traces.

Sample sizeFilter Type% Unknown% Stack Traces
1,051None50%50%
750Package version36%64%
485OS version54%46%
316OS version34%66%
234Package version86%14%
110OS version50%50%
100OS version99%1%
66Package version100%0%

Even for the “higher usage” package version, however, I’m still not getting solid data on the “rare” crash types - just the frequent crashes.

So… what’s to be done? We don’t have access to any off-the-shelf Win32 crash reporting tools, as the necessary APIs are all blocked off from UWP apps. There’s no easy way to get a minidump. There might be some really elaborate solution involving Project Reunion APIs to monitor the UWP process from Win32-land, but I haven’t explored those technologies much, and I’m not confident that the Win32 code gets sufficient privilege to dig deep on the UWP process’ behaviour.

But… UWP apps do have access to one key API: CaptureStackBackTrace.

A bare bones solution

A full-fledged crash handling and stack trace solution is quite complicated: running in a separate guard process to sidestep any memory/stack corruption; multiple threads; full analysis of both the app portion of the stack trace and the system (Windows) portion. My main needs were more narrow, and I built a solution focused on that

  • Single thread: only show stack of active (crashing) thread
  • App portion of stack is critical; system/Windows portion is desirable, but less important
  • Severe memory corruption doesn’t need to be handled initially
  • Only handle C++/CX and x64. It probably works for other situations, but that’s all I’ve tested to date.

With those criteria, I came up with a five-part solution:

  1. Pre-crash: log system info to disk
  2. Crash time: set a callback to get notified, and capture stack to disk
  3. Next app startup: transmit log+stack trace to server
  4. [OPTIONAL] Server: symbolify stack trace
  5. [OPTIONAL] Server: aggregate results

Let’s take a quick look at each piece.

Log System Info

When the crash happens, we want to do the bare minimum necessary. Memory may be corrupted and we want to avoid crashing while trying to log the crash. So: we log system information to disk at startup, prior to any crash happening. We particularly need the app version and the operating system version in order to be able to symbolify the stack trace, and the date/time of the session; but of course other data (screen size, RAM available, graphics driver versions, etc.) may also be relevant.

Crash Capture: Callback on Crash

There are several potential mechanisms to get notified on crashes:

  • Assertion failures (if enabled in production): it’s easy enough to write a custom assertion macro that captures __LINE__ and__FILE__ to get the source location of a failure, and it can then also trigger capture of a stack trace.
  • Invalid memory access: the best bet seems to be __try / __catch / _set_se_translator for Windows Structured Exception Handling (SEH)

These were also options, but didn’t seem to actually get called for relevant situations like null pointer dereferences:

  • A different SEH Win32 C API: SetUnhandledExceptionFilter

  • UWP event handlers: Windows::ApplicationModel::Core::CoreApplication::UnhandledErrorDetected and Windows::UI::Xaml::UnhandledException

What is SEH? It’s a C API that handles hardware exceptions on x86/x64 chips; while it uses the __try and __catch keywords, it’s not about software exceptions (either C++ or managed code). There’s some good discussion of it in the CrashRpt documentation. It’s a key part of Microsoft’s own error reporting mechanism, from the Dr. Watson era through to today. (I believe the rough data path is SEH → Windows Error Reporting (WER) → Microsoft-hosted database → Windows Store stack traces.) There are all sorts of complicated nuances to how it works, and I’ve understood… relatively few of them. I just use the _set_se_translator function as a hook to:

  • Get called when a crash happens, on the crashing thread.
  • Grab a stack trace and record it (typically skipping the first 8 frames that are in VCRUNTIME and NTDLL)
  • Also grab and record the exception type (EXCEPTION_ACCESS_VIOLATION, EXCEPTION_STACK_OVERFLOW, etc.)

A single call to _set_se_translator appears to be sufficient to get a callback when any thread crashes. (Which is the main reason I use it instead of __try / __catch or _set_terminate, which have to be applied on a per-thread basis.)

The actual implementation is pretty straightforward:

#include <eh.h>

void se_trans_func( unsigned int u, _EXCEPTION_POINTERS *pExp) {
  // Skip 8 stack frames - we usually see the ones below.
  // 00:MyApp.exe+0x009a7b98		(this function)
  // 01 .. 05:VCRUNTIME140D_APP.dll
  // 06 .. 08:ntdll.dll
  Char *backTrace =GetBackTrace(8);
  Str desc;
  switch (u) {
  case EXCEPTION_ACCESS_VIOLATION:
    desc = L"ACCESS_VIOLATION";	     break;
  case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
    desc = L"ARRAY_BOUNDS_EXCEEDED"; break;
  // ... etc. ...
  case EXCEPTION_STACK_OVERFLOW:
    desc = L"STACK_OVERFLOW";        break;
  default:
    desc = StrPrintf(TEXT("%d"), u); break;
  }

  LogPrintf(L"Structured Exception Handling failure type %s. Stack trace:\n%s\n"),
    desc.Data(), backTrace);
  delete[] backTrace;

  // A bit irrelevant... we mostly just want the stack trace.
  throw L”Hardware exception”;
}

App::App() {
  // ...
  _set_se_translator(se_trans_func);
  // ...
}

Crash Capture: Record Stack Trace

From a UWP app, we don’t have access to many Win32 APIs - but we can call CaptureStackBackTrace. If we combine that with calls to RtlPcToFileHeader and GetModuleName, then we can get the module name (EXE and DLL filename) and the offset within that module for each entry in the stack trace. Unlike conventional Win32 crash handlers, we cannot symbolify at crash time. We get a module-relative offset:

myapp.exe+0x00001234

Rather than the symbolified (actual function name and signature) with a function-relative offset:

myapp.exe crashyFunction(int, const std::string &) + 0x0000001a

Or even better, with source filenames and line numbers:

myapp.exe crashyFunction(int, const std::string &) + 0x0000001a
myapp.cpp:465

In theory, you could try to walk the module’s PE header data manually with an IMAGE_DOS_HEADER to get the IMAGE_EXPORT_DIRECTORY for the exported symbols from each module. But in practice, we need non-exported private function names, for both trace entries in our code and in Windows DLLs.

So - there’s no API call to do the symbolification locally in-app. We’ll have to do it out-of-app with the help of a server. Given that situation, we just dump the CaptureStackBackTrace outputs to disk, and let the app merrily crash.

The actual capture code looks like this:

Str GetBackTrace(int SkipFrames)
{
  constexpr uint TRACE_MAX_STACK_FRAMES = 99;
  void *stack[TRACE_MAX_STACK_FRAMES];
  ULONG hash;
  const int numFrames = CaptureStackBackTrace(SkipFrames + 1, TRACE_MAX_STACK_FRAMES, stack, &hash);
  Str result = StrPrintf(L"Stack hash: 0x%08lx\n", hash);
  for (int i = 0; i < numFrames; ++i) {
    void *moduleBaseVoid = nullptr;
    RtlPcToFileHeader(stack[i], &moduleBaseVoid);
    auto moduleBase = (const unsigned char *)moduleBaseVoid;
    constexpr auto MODULE_BUF_SIZE = 4096U;
    wchar_t modulePath[MODULE_BUF_SIZE];
    const wchar_t *moduleFilename = modulePath;
    if (moduleBase != nullptr) {
      GetModuleFileName((HMODULE)moduleBase, modulePath, MODULE_BUF_SIZE);
      int moduleFilenamePos = Str(modulePath).FindLastOf(L"\\");
      if (moduleFilenamePos >= 0)
        moduleFilename += moduleFilenamePos + 1;
      result += StrPrintf(L"%02d:%s+0x%08lx\n"), i, moduleFilename, 
        (uint32)((unsigned char *)stack[i] - moduleBase));
     }
     else
       result += StrPrintf(L"%02d:%s+0x%016llx\n"), i, moduleFilename, 
         (uint64)stack[i]);
   }
   return result;
}

Next App Startup: Transmit Log

The UWP lifecycle APIs let us detect whether the last run of the app had a clean exit. We can use that to detect a crash, and transmit the recorded log to our server for symbolification. It does mean that we don’t get crashes immediately, and we may miss crashes if the user doesn’t restart the app. But in practice, this is largely acceptable.

We do try to capture the app version and crash date/time in our log, as the version and date may be different by the time the log is transmitted.

[OPTIONAL] Symbolify Stack Trace

The server is - by necessity - a Windows VM listening to HTTPS requests.

On the server, we maintain a set of PDB files for each app version (extracted from the .msixpackage zip file). At present, we only handle x64 and not ARM64 crashes.

We also maintain a set of key system DLLs for each major (semiannual) Windows release. We don’t try to keep the DLLs for each minor release, as that’s basically a Herculean task.

When a log file comes in, we:

  • Parse the log to retrieve the app version and Windows version
  • Match up the relevant PDB file and directory of Windows system DLLs
  • For each line of the stack trace, detect whether it’s in our app or a system DLL
  • Run CDB.EXE to convert the module name + offset to a function name, offset, source filename and line number. The inspiration for this came from Raymond Chen’s oldnewthing blog.

The heart of this is the call to CDB, which looks like this:

export CDB=/mnt/c/Progra\~2/Windows\ Kits/10/Debuggers/x64/cdb.exe
# Typical raw output, prior to sed expressions:
#   MyApp!MyApp::App::CrashyFunction+0x25fb
#   [C:\Users\MyUser\source\myapp\MyApp.cpp @ 757]:
# Sed expressions simplify it to:
#   App::CrashyFunction+0x25fb [MyApp.cpp @ 757]
"$CDB" -lines -z myapp.exe -c "u $entry; q" -y \
  "cache*c:\\Symbols;srv*https://msdl.microsoft.com/download/symbols"\
  | grep -m 1 -A 1 "^0:000>" \
  | tail -1 \
  | sed 's/:$//;' \
  | sed 's/MyApp:://g;' \
  | sed 's/\[[^@[]*\\\([A-Za-z0-9_.]*.\(h\|cpp\) @ \)/\[\1/g'

For Windows system DLL entries, we can choose a $SYS32DIR to match the client’s Windows version, and then change the -z argument to

-z $SYS32DIR\\$DLLFILENAME

This ensures that CDB uses the client’s Windows version to decide which symbols to retrieve for the DLL, rather than the normal behaviour, which would use the server VM’s Windows version. We’ll still get a fair bit of mismatch - as we usually don’t have the DLLs that precisely match the client’s Windows version.

If there’s some way to specify a Windows version when telling CDB about the symbol server - let me know! That would be a huge timesaver.

[OPTIONAL] Aggregate results

Ideally, we want to build a database of all stack traces, merge duplicates, and present a ranked list of the most common crashes over (say) a month, and a graph of the crash frequency of any given bug per day.

But I haven’t actually implemented this yet. For this purpose, an off-the-shelf tool will probably suffice - a service like Sentry or Visual Studio App Center would do the trick, and both accept submission of crash data via an API.

What if we don’t symbolify?

If you want a simpler solution: you can easily use the module name + module-relative offset in a Visual Studio debugger session to manually find the source location. This makes it painstaking to analyze each individual crash, but might be acceptable if you maintain a very low crash rate in your app. I took this route through 2019, but added stack trace capture by 2020 and finally built out the symbolification code in 2021 when it became obvious that Microsoft wasn’t going to fix this themselves.

Conclusion

So - this is a very bare bones process for detecting crashes, capturing a C++ stack trace, transmitting to a server and determining filename + line numbers for each entry in the stack trace.

I … still really wish Microsoft would just re-enable this code in the Microsoft Store. For the life of me, I can’t understand why they turned it off. They must still be collecting all this information in the WER database for their own use, and just not exposing it to developers.

Pitfalls mixing PPL+await

· C++, windows

Imagine you have a C++/CX codebase with a lot of asynchronous logic written using the classic Parallel Patterns Library (PPL) tasks:

task<void> FooAsync(StorageFolder ^folder) {
  return create_task(folder->TryGetItemAsync(L"foo.txt"))
    .then([](IStorageItem ^item) {
      // do some stuff, cast to a file, etc.
    });
}

It’s all running on the UI thread, so it’s in a Single Threaded Apartment, and each task in your chain of .then() continuations is guaranteed to also be on the UI thread.

Now, you learn about Microsoft’s relatively new co_await feature, recently accepted in an adapted form in the C++20 spec. So you start using it:

task<void> FooAsyncCo(StorageFolder ^folder) {
  IStorageItem ^item =
    co_await folder->TryGetItemAsync(L"foo.txt");
  // do some stuff, cast to a file, etc.
}

So far so good: all code inside FooAsyncCo() also runs on the UI thread, nice and clean.

Finally, you integrate a little of this co_await code into your heavily PPL codebase. Helpfully, co_await returns a task, just like your existing async PPL method. Another developer sees that you have a bunch of methods returning task and decides to start building on that API using PPL:

FooAsyncCo().then([]() {
  // more stuff, after coroutine.
  // KABOOM. Running on a threadpool thread, *not* the UI thread.
  // We accidentally busted out of the STA.
});

Uh-oh. When you mix the two async approaches… things break. And none of the documentation - or honestly anything I’ve read on the web to date - gives any hint of this issue.

Not A Fix

Well… let’s see. The docs do give us one tip: a task chain is only guaranteed to remain inside the Single Threaded Apartment if the chain starts with an IAsyncAction or IAsyncOperation

The UI of a UWP app runs in a single-threaded apartment (STA). A task whose lambda returns either an IAsyncAction or IAsyncOperation is apartment-aware. If the task is created in the STA, then all of its continuations will run also run in it by default, unless you specify otherwise. In other words, the entire task chain inherits apartment-awareness from the parent task. This behavior helps simplify interactions with UI controls, which can only be accessed from the STA.

Asynchronous programming in C++/CX: Managing the Thread Context

Well… TryGetItemAsync does return an IAsyncOperation. That would appear to be the root task in the chain… so coroutines must be treated differently, with the coroutine itself being the root.

Well, what if we tried making the coroutine return an IAsyncAction?

IAsyncAction ^FooAsyncCoAction(StorageFolder ^folder) {
  return create_async([folder]() -> task<void> {
    // KABOOM - this is now out of the apartment.
    IStorageItem ^item =
      co_await folder->TryGetItemAsync(L"foo.txt");
    // do some stuff, cast to a file, etc.
  });
}
create_task(FooAsyncCo())
.then([]() {
  // more stuff, after coroutine.
  // ok now!
});

No dice. Now the coroutine runs off-thread, while the continuation runs correctly on the UI thread.

Two Actual Fixes

With a little more reading, I found Raymond Chen’s blog post about PPL and apartment-aware tasks. That led to this successful solution:

task<void> completed_apartment_aware_task() {
  return create_task(create_async([](){}));
}

completed_apartment_aware_task()
.then(FooAsyncCo)
.then([]() {
  // Ok!
});

This one actually works. By rooting the PPL chain in an IAsyncAction, the rest of the chain retains apartment awareness, and everything stays on the UI thread.

And I’d earlier found a different but more fragile solution:

create_task(FooAsyncCo, task_continuation_context::use_current())
.then([]() {
  // Ok!
});

While this works, it’s… a bit hard to tell whether the root task, or the continuation, or what-all needs use_current(), and it’s always felt fragile to me. And if it gets called from a threadpool thread, it’s unclear to the caller what happens with use_current().

Conclusion

I’ve got to say… this is a brutal pitfall. Any existing codebase is going to have a lot of PPL tasks in it, and wholesale migration to co_await isn’t going to happen all in one go, at least if there’s any conditional/loop/exception logic in the PPL-based code. Anyone who’s tried to migrate to co_await has probably run into this pitfall.

We haven’t adopted the completed_apartment_aware_task() as a root task throughout our codebase yet, but I’m hopeful that will at least offer a path forward. Just… still quite error-prone.

Keep Calm and Mix On

· Music · 1 comment

I listen to music while I work. I listen without lyrics. I mostly just consume what the Apple algorithm feeds me.

So, I’m not going to pretend any ownership over this list. It’s really just a “best of Apple music, 2018/19.” For the record, the stock playlists I prefer are: Untitled, Loops, Headspace, Living in the Library and Vibes.

But: at least I’m listening mostly to music from the past decade, and finding rock and r&b tracks that I like. The flavour of this mix is very low key, suitable to my mood when I put it together in February. It doesn’t really fit with the “brief relief from a coronavirus” that we’re going through now, but whatever.

I’ll be honest: no one else listens to these mixes. I make them mostly for myself, as a way to sift through the best things I’ve heard, take note of the artists I liked best, and branch out to their full albums and other work. The raw material for this mix is a solid 200 tracks that caught my eye, and it was fun to cull them down to this highlights list.

Download a zip of MP3s here, or listen with your favourite streaming service below.

  1. james blake feat. rosalía. barefoot in the park. pop, 2019.

  2. nicolas jaar. mi mujer. dub, 2010.

  3. maribou state. turnmills [edit]. downtempo, 2018.

  4. pantha du prince. bohemian forest. techno, 2010.

  5. chet faker. no diggity. r&b, 2012.

  6. calvin harris feat. frank ocean & migos. slide. r&b, 2017.

  7. allan rayman feat. jessie reyez. repeat. r&b, 2017.

  8. art school girlfriend. distance (blank). rock, 2018.

  9. alex lahey. am i doing it right? rock, 2019.

  10. cherry glazerr. daddi. rock, 2019.

  11. two people. something to talk about. trip hop, 2018.

  12. barr brothers. you would have to lose your mind. rock, 2017.

  13. ben howard. nica libres at dusk. rock, 2018.

  14. reuben bidez feat. molly parden. what you really wanted. folk, 2018.

  15. kimya dawson. tire swing. folk, 2006.

  16. wildes. illuminate. rock, 2016.

  17. dusted. all i am. rock, 2018.

  18. bearcubs. do you feel. electronic, 2018.

  19. velvet negroni. crybaby. electronic, 2018.

  20. manila killa & mansionair. wake up call. pop, 2018.

  21. bicep. vale. techno, 2017.

  22. major lazer feat. amber coffman. get free. dancehall, 2012.

  23. floating points. anasickmodular. acid jazz, 2019.

  24. martin nonstatic. innermost structure. ambient, 2017.

  25. orbital. tiny foldable cities [edit]. techno, 2018.

  26. dining rooms. you [quantic soul orchestra version]. acid jazz, 2004.

  27. alex lustig feat. akacia. in the end. pop, 2018.

A Windows to iOS Port

· ios, User Interface, windows

My main activity of 2019 was a port of the Mental Canvas 3D drawing tool from Windows to iOS. About 75% of my effort was user interface code, maybe 15% on graphics and 10% other platform issues.

What’s interesting about our porting approach? Well, it’s just an unusual mix:

  • It’s a UWP (Universal Windows Platform) app. UWP was Microsoft’s effort to modernize Win32 and add iOS mobile paradigms, so it is already touch-centric, relatively sandboxed and has a more mobile-like lifecycle
  • We didn’t use React Native, Flutter, Electron, Xamarin, Qt or even Fuschia’s namesake Pink. We just… wrote some native code. And a lightweight abstraction layer.
  • We completed the porting effort in seven months, with three developers.
  • We stayed with the MVVM architecture that is the norm on Windows. Many iOS developers would call that… exceptionally ok
  • We didn’t use the latest and greatest Swift tools, just plain old C++11 and Objective-C for the most part. We didn’t switch to SwiftUI when it was released half way through our port.

What combination of circumstances led to this approach? Mostly just a real life constraint: a desire to rewrite/redesign as little working code as possible, and keep the codebase’s size down.

  1. Starting Point
  2. UI Framework Choice
  3. Restructuring the UI Thread
  4. Lightweight iOS Bindings
  5. What About SwiftUI?
  6. Incremental Porting
  7. The Upshot: Code Reuse

Continue reading

Metal Memory Debugging

· Graphics, ios

At Mental Canvas, Dave Burke and I recently resolved a memory leak bug in our iOS app using the Metal graphics libraries. Memory management on Metal has had a few good WWDC talks but has surprisingly little chatter on the web, so I thought I’d share our process and findings.

  1. The issue: a transient memory spike
  2. iOS / iPadOS memory limits
  3. Forming hypotheses
  4. Tools at hand
  5. Findings
  6. Conclusion
  7. References

The issue: a transient memory spike

Our sketching app does a lot of rendering to intermediate, offscreen textures. In the process, we generate (and quickly discard) a lot of intermediate textures. A lot of that rendering happens in a continuous batch on a dedicated thread, without yielding execution back to the operating system.

A consequence of that behavior: our memory footprint grows rapidly until we hit the critical threshold — on a 3 GB iPad Air, about 1.8 GB — and then iOS summarily kills the app. From our app’s perspective, memory footprint is only growing gradually, as most of the memory usage is temporary intermediate rendertargets; they should be freed and available for reuse. But from the operating system’s perspective, it considers all of those temporaries to still be in use.

Which led us to the question: why? And how do we figure out which temporaries are leaking, and which Metal flag / call will allow us to return that data to the operating system?

Continue reading