chromium-legacy: Chromium Legacy occasionally induces a kernel panic: kqueue_scan_continue: - invalid wait_result

I’ve been avoiding reporting this, because I feel like it’s going to be impossible to fix. 😦

Occasionally while using Chromium Legacy, OS X kernel panics with a distinctive backtrace. The backtrace implicates Chromium Helper, and I’ve never seen the panic occur when I’m not using Chromium. I’ve observed this on my desktop and laptop running 10.9, as have others on MacRumors. I think it may happen more often on Macs with less memory?

A log is attached. Notably, I have so far never managed to capture a panic while I had keepsyms enabled, I’d like to capture one at some point.

Kernel_2022-01-11-182654_Jonathans-MacBook-Air.panic.zip


Everything beyond this point is speculation, and probably useless, due to my limited understanding of C. But, I’m going to include it anyway. 😃

I’m technically running XNU version 2422.115.15, which doesn’t appear to be open source, but the closest version with source available is 2422.115.4. The file being referenced in the log is here: https://opensource.apple.com/source/xnu/xnu-2422.115.4/bsd/kern/kern_event.c.auto.html

The line numbers don’t match up, possibly because of the tiny version mismatch, but I assume this is the referenced function:

static void
kqueue_scan_continue(void *data, wait_result_t wait_result)
{
	thread_t self = current_thread();
	uthread_t ut = (uthread_t)get_bsdthread_info(self);
	struct _kqueue_scan * cont_args = &ut->uu_kevent.ss_kqueue_scan;
	struct kqueue *kq = (struct kqueue *)data;
	int error;
	int count;

	/* convert the (previous) wait_result to a proper error */
	switch (wait_result) {
	case THREAD_AWAKENED:
		kqlock(kq);
		error = kqueue_process(kq, cont_args->call, cont_args, &count,
		    current_proc());
		if (error == 0 && count == 0) {
			wait_queue_assert_wait((wait_queue_t)kq->kq_wqs,
			    KQ_EVENT, THREAD_ABORTSAFE, cont_args->deadline);
			kq->kq_state |= KQ_SLEEP;
			kqunlock(kq);
			thread_block_parameter(kqueue_scan_continue, kq);
			/* NOTREACHED */
		}
		kqunlock(kq);
		break;
	case THREAD_TIMED_OUT:
		error = EWOULDBLOCK;
		break;
	case THREAD_INTERRUPTED:
		error = EINTR;
		break;
	default:
		panic("%s: - invalid wait_result (%d)", __func__,
		    wait_result);
		error = 0;
	}

	/* call the continuation with the results */
	assert(cont_args->cont != NULL);
	(cont_args->cont)(kq, cont_args->data, error);
}

So, the switch statement expects the wait_result parameter to be either THREAD_AWAKENED, THREAD_TIMED_OUT, or THREAD_INTERRUPTED. If it’s none of these—as appears to be the case for us—it panics with our error, “invalid wait result”.

So, what is being passed in as wait_result? Well, it’s printing as the number “3”, but I don’t know enough C to understand how these integers are mapped to their human-readable names. However, note that a fourth option has been added to this switch statement in newer versions of XNU: https://opensource.apple.com/source/xnu/xnu-7195.81.3/bsd/kern/kern_event.c.auto.html

	case THREAD_RESTART:
		error = EBADF;
		break;

I’m going to hazard a guess that when the kernel panics, kqueue_scan_continue is getting called with a value of THREAD_RESTART in the wait_resultparameter, which is understood on new versions of XNU but not the older ones we’re using. Is there any way to catch and handle this?

About this issue

  • Original URL
  • State: open
  • Created 5 years ago
  • Comments: 96 (5 by maintainers)

Commits related to this issue

Most upvoted comments

@Wowfunhappy sorry for the late response.

I’m just trying to figure out where that wait_result value could be coming from. I find it so weird that XNU is returning a value that didn’t exist yet

Note that even in the older xnu version, THREAD_RESTART was still a valid defined value for wait_result_t. In fact, you can see that it is returned in wait_queue_assert_wait64 of osfmk/kern/wait_queue.c when the queue becomes invalid. The difference is that in this older kernel version, kqueue scan did not properly handle this, and just panicked instead of returning EBADF.

I agree that this seems way too obvious an omission to be a bug. But I can’t think of any other explanation at the moment (that said, my knowledge here is very slim). I think the first step might be to see if we can create a scenario that can reliably reproduce this. Based on my current understanding, it seems like the conditions for triggering would look like:

  • Have one process call kqueue to create a new fd for event queue, and then call kevent to wait upon it

  • While that happens, another process closes the fd

  • Based on what’s described above, this would generate a THREAD_RESTART condition in the wait queue code which would bubble up to kqueue_scan and cause the panic.

But this seems way too obvious and easy to trigger, so I’m still skeptical that this is actually what’s happening.

As it turns out, compiling XNU is shockingly easy and the build itself takes only a few minutes to complete

I see you’re following the “Kernel Shaman’s” build instructions? I’m not quite sure why there would be a difference in size assuming that both are release builds, but it’s possible that apple internal builds have some other ifdefs set during compile, or the kernel version is different? This wouldn’t explain why the hackintosh kernels match in size though…

That’s also why I’m personally partial to the “hotpatch via kext” approach. That way you introduce only the minimal difference necessary.

I was on 10.9.4 because I never realised that it wasn’t the latest Mavericks 😂😂😂 I kind a skimmed through the end of the issue and didn’t spot the workaround, I’ll update to 10.9.5 and try it, will report back after some testing.

Quick heads up that Apple also released further updates after the base 10.9.5 which don’t change the version number, you want 10.9.5 build 13F1911. I’m pretty sure the updater will prompt you, but if not, install: https://support.apple.com/kb/dl1886?locale=en_US

@fhgwright

Please don’t. Kernel patches should never be installed without the user’s express permission. Patching the kernel, either in an application, or in something which represents itself as an application updater, is a really extreme violation of the principle of least surprise.

The preference pane does ask for permission!

Screen Shot 2022-09-17 at 8 34 57 PM

The installation is “automatic” in the sense that, if the user says yes, it’s done in one click.

Let me know if you think the above message isn’t clear enough. I am trying to be respectful of the user. However, I don’t think leaving users with kernel panics is particularly respectful either!

While it’s true that there’s a kernel bug at work here, as a practical matter, coming up with a userspace workaround would be much more user-friendly

I 100% agree! At the moment, however, I don’t think anyone working on Chromium Legacy has the time or expertise to come up with a userspace fix. This is the best that krackers and I can do. If you have the expertise to fix the problem in userspace, please contribute, that would be wonderful!

there must be something in Chromium which changed from an “old way” to a “new way” of doing something.

My current best guess (which could definitely still be wrong) is that it’s https://bugs.chromium.org/p/chromium/issues/detail?id=932175

How much of an advantage is there in the “new way”? I.e., how important is it to use the “new way” when it doesn’t cause trouble, rather than reverting unconditionally?

It sounds like it’s not such a huge advantage. Most users are not exhausting file descriptors. However…

How wide is the scope of the difference? I.e., if there were a patch to revert to the “old way”, how maintainable would such a patch be?

Wide enough that Bluebox wasn’t able to do it. https://github.com/blueboxd/chromium-legacy/issues/44#issuecomment-1086776672

And a “proper” kernel update should involve building from source, rather than applying some kludgy on-the-fly binary patch.

Already done!

https://github.com/blueboxd/chromium-legacy/issues/44#issuecomment-1019278490

This kernel is for 10.9.5, but you could easily apply the fix to whichever kernel you’d like. It’s literally a three line change.

The problem is that the open source release of XNU is incomplete. Most notably, custom kernels are unable to log into iMessage. This is why we created a kext to patch the memory at runtime instead.

@Wowfunhappy

If I don’t discover any new issues in the next week or so, I’m going to add this to my Preference Pane, so it gets installed automatically for anyone who uses that. I don’t know if it makes sense to incorporate this into the Chromium Legacy app directly, but you are of course welcome to it.

Please don’t. Kernel patches should never be installed without the user’s express permission. Patching the kernel, either in an application, or in something which represents itself as an application updater, is a really extreme violation of the principle of least surprise.

While it’s true that there’s a kernel bug at work here, as a practical matter, coming up with a userspace workaround would be much more user-friendly, given that:

  1. AFAIK this has never been triggered by any application other than Chromium Legacy.
  2. It was never triggered by any supported release of Chrome.
  3. AIUI, the kernel fix still leads to an application crash, so an application-level fix is also needed, anyway.

Given item 3, the kernel patch on test systems could be useful in identifying the combination of syscalls that provokes the bug. And assuming that the offending code doesn’t provide any new capability, there must be something in Chromium which changed from an “old way” to a “new way” of doing something. Once that difference can be figured out, the next questions are:

  1. How much of an advantage is there in the “new way”? I.e., how important is it to use the “new way” when it doesn’t cause trouble, rather than reverting unconditionally?
  2. How wide is the scope of the difference? I.e., if there were a patch to revert to the “old way”, how maintainable would such a patch be?

It would certainly be useful to also have a kernel fix for users who want a more robust kernel and are willing to install a kernel update, but it would be best to avoid making that a requirement for avoiding this bug. And a “proper” kernel update should involve building from source, rather than applying some kludgy on-the-fly binary patch. Some work would be needed to identify the correct sources to use as a starting point, though fortunately that needs to be done only once for any given abandoned OS version.

The kext has been updated with compatibility for 32-bit Lion.

https://gist.github.com/Wowfunhappy/8212f5bea4c601ac9a6297789f232321

(The strategy for finding the kernel base address works fine in 32 bit, but is pointless because Lion lacks KASLR.)

@krackers …y’know what, that might be all it is, I forgot I was literally searching for a header called “MH_MAGIC_64” 🤦‍♂️. I’ll take another look.

Recompiling isn’t a problem, I can just lipo together two different binaries that technically have different code. (It does make the built cycle a bit more annoying unless I also take the time to automate that.)

Oh one more crucial defensive check you can do is add the two following asserts:

kqueue_scan_continue_panic_end_location == kqueue_scan_continue_panic_start_location + sizeof(search_bytes)
kqueue_scan_continue_panic_start_location + sizeof(replacement_bytes) + extra_space_to_fill ==  kqueue_scan_continue_panic_end_location

It’s also possible that chromium is calling into a system framework/api which then makes use of kqueue in this manner. Can we run chrome under gdb or with dtrace to figure out where the kevent syscall is being made?

Tangential thing Completely unrelated, but if you like reading tales about old versions of chrome and patching things, did you know that newer version of chrome actually fixed (well more like worked-around) a coretext bug in 10.9? Under very rare and infrequent conditions (usually when rendering CJK text + emoji, but not deterministically) coretext shaper will get stuck when using AAT font, and just go in an infinite loop.

You can see in https://github.com/harfbuzz/harfbuzz/blob/main/src/hb-coretext.cc#L187

that google actually discovered this issue and added a workaround to coretext in v58 or so. But this workaround is not perfect, and there are still conditions which cause this (seems to be a combination of emoji and kanji characters from what I’ve seen). I actually went a wild chase some time back trying to see if I could fix this myself by hooking and hotpatching that function to determine which parameters caused coretext to crash. I could have recompiled Chromium but figuring out how to build chromium seemed harder than just hotpatching. In fact even figuring out how to parse the crash dump format from non-debug builds (minidump format) was quite an exercise.

As you know, for security chrome divides the main browser process from the helper processes, which are spawned from a different binary. SIMBL works fine to inject into the main chrome process (surprisingly, Chrome is alright with the injection. I would have thought that they do crazy tricks to avoid process injection like in windows, but seems like not.), but since chrome helper does not load any cocoa libraries we cannot simbl inject into that. We can’t add dylib to the helper binary because it is codesigned with CS_RESTRICT (and removing codesign here seemed like a bad idea) since there are some entitlements it needs I think, but helper binary also loads chrome framework dylib (manually via dlopen actually, not via usual dynamic linking), so we can actually modify that chrome framework without tripping any security issues. I tried this and it worked, but changing signature does prevent some keychain related things from working which I didn’t like.

I finally realized that what I really want is to use mach_inject automatically for every helper process spawned. Newer versions of macforge do this, but for 10.9 mysimbl only does traditional osax injection.

(Btw, @wowfunhappy I noticed many of your plugins usually done via insert_dylib approach, you should consider packaging as a simbl plugin instead since it’s much easier to enable/disable and you don’t break signatures).

Continue tangential thing So I thought some more and realized that to do `mach_inject` we only really a way to look for pid of spawned process. Turns out that chrome launches the helper via `posix_spawnp`, and we can hook this call via standard patching techniques. So in my mind I constructed this wacky chain where I'd simble inject into the main chrome process, then hotpatch to interpose `posix_spawnp`, then take the pid result from that call and call `mach_inject` to inject a blob into the helper, and the injected blob would finally hotpatch `harfbuzz_shape`.

_Of course after more thinking I realized this was absolutely insane and I just removed the problematic emoji that was triggering the crash from my webpage. _

EDIT: Fwiw I just realized a way to do this is via DYLD_INSERT_LIBRARIES, it automatically gets propagated to all spawned child processes, and does not break code signing. You can then use mach_override or any other plt hooking library.

Oh so back to how newer version of Chromium fixed it. Turns out that newer versions of harfbuzz don’t call into CoreText at all to shape AAT fonts, so we sidestep this problem entirely. Very fortunate, and it probably also avoids a whole class of security vulnerabilities. Anyway, thank you for reading.

@Wowfunhappy

Yes, Lilu will work since it has support for patching kernel functions as well. But I don’t like it here because I don’t think using Lilu is going to give us any strong benefit that we could not have ourselves by copying a few header files for useful functions. And the Lilu only takes care of boilerplate, but we must still bring core logic. And that too we’d have to learn the Lilu API so the benefits of having boilerplate taking care of is negated. I think it’s much simpler and more understandable to just make vanilla kext?

But, I also need to step back for a moment—I’m not sure what we’re trying to accomplish here. Even without Lilu, I wouldn’t feel comfortable recommending a patch like this to most Chromium Legacy users.

End result will be to create a kext that users can just place in /Library/Extensions or whatever to hotpatch kernel on the fly. Will only work for users with same kernel version that you based offsets on though, other kernel versions people will have to recompile kext with their own offset. It’s also fun for learning, but yes it is a bit more work to do than just recompiling xnu. Up to you whether the pain of occasional kernel panic is worth spending a few weekends trying to create a kext though. Happy to provide guidance along the way. I edited previous repose https://github.com/blueboxd/chromium-legacy/issues/44#issuecomment-1048316473 with some concrete starting steps if you’ve decided to take this route.

How useful do we think this logging data will be? Do we actually have a chance of fixing this properly in user-space?

To be honest, I don’t know. If we can determine for sure that it is caused by a freed kqueue fd, then we need to take next step to figure out why the fd is being freed. This would involve adding some logging code in Chromium (maybe in destructor for messagepump?). If we verify that is indeed the cause, then next step would be to create some work around where we try to only free the kqueue after we ensure no thread is blocked waiting on one. We could try to make that change now itself but to me seems like the effort required to figure out how to implement this (would have to study exactly what type of event to send to interrupt existing kqueue wait) combined with effort to recompile chromium is much more than doing the kext.

Other option is if you can try to find commits involving messagepump we can try to see if one of them might be responsible, but this is more of a shot in the dark compared to the kernel patch which we know will work. If you’re optimizing for time spent vs. reward then the kernel patch approach seems to be a surer bet.

@Wowfunhappy Assumption 1 isn’t necessarily true. If we use the working hypothesis that the kpanic is caused by attempting to use an invalid (freed) kqueue, then you’d also have to search for references for code which uses MessagePump, since when that instance goes out of scope its destructor will free the kqueue fd.

There’s also exactly 1 other place where THREAD_RESTART is signalled, and that’s in some sephamore related method. If the kpanic is triggered by that, then we’re really in a pickle since that would mean the root cause might not even be strictly related to kqueue operations.

Do those (macOS 10.11 Chrome users) actually exist? 😉

I mean, anecdotally, I’ve seen several of them in the wild! I even helped a third grade schoolteacher add the Let’s Encrypt certificate to Keychain Access last fall.

This may well be an kernel bug†, but I don’t think it’s happening in official versions of Chrome. A kernel panic is more difficult to overlook than a missing email, and this one appears to happen to all Chromium Legacy users sooner or later, albeit very infrequently. I don’t see how Google, with all of their users and analytics, wouldn’t know about this problem if it existed.

It seems much more likely to me that https://github.com/blueboxd/chromium-legacy/commit/e0cff58db7f41e2b0b68e058ec49a98f215265c5 is culpable, somehow…


† Technically, my understanding is that any instance of a userspace application triggering a kernel panic is generally considered a kernel bug, since userspace shouldn’t be able to take down the kernel.

…well, for what it’s worth, I decided to build a custom kernel. As it turns out, compiling XNU is shockingly easy and the build itself takes only a few minutes to complete. The only tricky part was that I had to install Xcode 5.0.2; later versions did not appear to work.

The only source change is that I added the THREAD_RESTART case to kqueue_scan_continue, which sets error = EBADF as in newer versions of XNU.

I am (a bit nervously) going to try using this on my main machine. A half hour in, nothing catastrophic has happened so far.

The kernel is attached in case anyone else on Mavericks wants to try it, but I am not necessarily recommending that anyone do so. If you do use it, make sure at minimum to have a secondary partition available to restore your original kernel should the need arise. Remember that you will need to clear the kernel cache on your first boot with the new kernel.

@krackers Do you have any idea why this kernel would be only 8,257,152 bytes, when the original kernel and every custom Hackintosh kernel I’ve checked is 8,394,688 bytes? It’s weirding me out.

XNU-2422.115.4-THREAD_RESTART add-JA-v2022…01.22.zip