logo
podcast Podcast
get help Get Unstuck

Debugging a segmentation fault

What does it even mean?

Joel Clermont
Joel Clermont
2024-12-04

I was working with a client to clean up their policies and authorization logic.

One of the requests was to pull out common logic allowing "super admins" to do anything up out of each policy and into a global gate check.

Here is what the first version of that code looked like:

// in the AuthServiceProvide boot method
Gate::before(fn ($user) => $user->can('super-admin') ?: null);

Seems pretty simple, right? But there is a silly bug in this code.

As soon as I added it, I started getting 502 errors in my browser from nginx on every request. PHPUnit would fail with a segmentation fault. What is going on?

In basic terms, a segmentation fault is when our application tries to access memory it doesn't have access to and the OS jumps in and stops it.

There are many reasons why this can happen: hardware issues, a broken PHP build, incompatible extensions, and on and on.

But in our scenario, the code was working fine before, and this one line led to a segmentation fault. So how could this one line of code be responsible for accessing an invalid memory location?

I'd love to say I was calm and collected, and had a flash of inspiration. Nope, I was a little frustrated, and it was actually the client that pointed out the issue: infinite recursion.

But how?

I'm calling can() inside a Gate definition. can() is a gate check, and I'm calling it inside a gate check. Infinite loop! Out of memory! Segmentation fault!

This is what it should have been:

// in the AuthServiceProvide boot method
Gate::before(fn ($user) => $user->hasPermissionTo('super-admin') ?: null);

Now, I'm using the permission lookup from our package, and not calling the gate check inside the gate check.

Here to help,

Joel

P.S. Just because I write these tips each day does not mean I know everything. In fact, I learn a ton from other smart devs in our Mastering Laravel community.

Toss a coin in the jar if you found this helpful.
Want a tip like this in your inbox every weekday? Sign up below 👇🏼
email
No spam. Only real-world advice you can use.