r/C_Programming • • 23d ago

Article Wrote a lightweight Linux dynamic file descriptor leak detector project in C using LD_PRELOAD. Looking for critiques and reviews.

I've written an LD_PRELOAD file descriptor leak tracker in C.

https://github.com/anu-icon/libfdhunt

Apart from memory leaks which get the most spotlight, file descriptor leaks is a long-standing problem in production environments, often causing service crashes.

While Valgrind has --track-fds=yes, running full binary translation can be overkill or too slow if you're working with timing-sensitive code.

Polling lsof or /proc/$PID/fd also misses transient descriptors that open and vanish.

This is highly useful since you don't need advanced tools and extra permissions, don't have to recompile or review entire large code bases to find the flaw.

Just LD_PRELOAD=./build/libfdhunt.so /path/to/your/program [args]

How it works under the hood:

For anyone interested in the implementation:

Symbol Interposition: It uses dlsym(RTLD_NEXT, ...) to wrap standard libc syscall wrappers (open, close, pipe2, socket, dup2, epoll_create1, etc.).

O(1) Flat Array Registry: Instead of using linked lists or calling malloc/free inside hot syscall paths (which invites lock contention and heap re-entrancy issues), it uses a flat array indexed directly by descriptor number (table[fd]). It sizes the table on demand using sysconf(_SC_OPEN_MAX) and guards slot flips with a single mutex.

Exit Hook: Leak reporting is wired into GCC's __attribute__((destructor)). When the binary exits normally, the library sweeps the table, skips standard streams (0, 1, 2), and reports active descriptors.

Design constraints and comparison & prior art is in the readme

Looking forward to critique.

AI usage declaration: This is not vibe-coded. It evolved over a month starting from using linked lists to tackle a similar problem.

AI was used for cross checking, calibrating, testing, scaffolding and some documentation

1 Upvotes

18 comments sorted by

•

u/AutoModerator 23d ago

Hi /u/icy-mist-01,

Your submission in r/C_Programming was filtered because it links to a git project.

You must edit the submission or respond to this comment with an explanation about how AI was involved in the creation of your project.

While AI-generated code is not disallowed, low-effort "slop" projects may be removed and it's likely that other users push back strongly on substantially AI-generated projects.

You can read more at How do I post my Project?


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

→ More replies (2)

2

u/didntplaymysummercar 23d ago

What about parsing output of strace? Doing it on your own child requires nothing special iirc.

-1

u/icy-mist-01 23d ago

Yeah we can surely do that, at least that's a generic sysadmin 101.
But strace brings in high performance runtime overhead due to the context switches at each syscall trace
With LD_PRELOAD it's just a function pointer wrapper.
That's why this excels. You record and lookup in an O(1) array - so near-native speed.
Also, think about issue inspection in container runtimes and CI pipelines. You'll never privliged access.
Mine works completely in unprivileged userspace, child or not.
Lastly it surely helps to get a simple neat o/p on your terminal just listing the FD leaks and types. You don't have to parse & interpret strace o/p.
Only thing I can think of is statically linked binaries where LD_PRELOAD won't work, and raw inline syscalls - which I've explained in the readme as design constraint.

But for any dynamic standard C library - which is what 99% of the cases are - this is a low overhead simple solution.

3

u/didntplaymysummercar 23d ago • Bravo

I asked since you listed prior art but strace was not there. That table also has broken inline math attempt.

1

u/icy-mist-01 23d ago

Ah ok.. Thank you! I've added strace and fixed the minor format typo

1

u/didntplaymysummercar 23d ago

Also (this is a nitpick because of my background but still) your PNG is very unoptimized, entire repo is 80K (K meaning 1000, not KiB.), PNG itself is over half that at 43K, but could be under 24K using oxipng on top settings

1

u/icy-mist-01 23d ago

Thank you for the feedback, optimized to 25k. Appreciate it.

2

u/pjf_cpp 19d ago

I haven't tried it but the idea sounds nice.

Valgrind has a few nice features. One issue is where you have code that does something like the following sequence

module1: fd1 = open() ... use fd1 ... close(fd1)

module2: fd2 = open() [recycles same fd number as module1 fd]

module1: use fd1 which refers to the wrong file

then there is an option which causes Valgrind to try to avoid recycling fds (which is the POSIX behaviour).

Also I guess that you don't handle the complex sycalls like fcntl and ioctl which can create fds.

1

u/icy-mist-01 19d ago

Thanks much for the suggestions. I'll add the feature to prevent FD recycling. This is similar to Bionic's fdsan which another user pointed out.

Will look into both fcntl() and ioctl() - but yes I think I mighty double check on ioctl() since certain functions are very driver/kernel version dependant.

2

u/pjf_cpp 19d ago

Look for ML_(record_fd_open_named) ML_(record_fd_open_with_given_name) ML_(record_fd_open_nameless) in the Valgrind source to have an idea of all of the places that we've identified the need (there are many since we support Linux FreeBSD Solaris and macOS). You can't copy our source (unless you switch to GPLv3) but this might help you identify functions that need wrapping.

Note that we work at the syscall level, not the libc function level. Usually they are the same but there may be some differences.

1

u/icy-mist-01 19d ago

Thank you for the guidance. Appreciated!

1

u/limitless_grow 23d ago

How about adding just something like this at the end of your main function:

#ifndef _WIN32
      int i = 256;

      while(i-- > 3)
      {
         int fd = dup(i);
         if(fd != -1)
         {
            close(fd);
            fprintf(stderr, "%s:%d : File descriptor #%d is still open!", __FILE__, __LINE__, i);
         }
      }
#endif

That's a trivial way to get a warning about open file descriptors at program termination.
Beside of that may cppcheck help to spot some leaks in code that's rarely executed.

2

u/laurentbercot 18d ago

Tip: fcntl(fd, F_GETFD) will check whether fd is open without allocating resources if it is. It's a faster, more convenient test. :-)

0

u/icy-mist-01 23d ago

Yup that's quick and dirty trick for tiny binaries and self study. It has a hardcoded limit of 256

This one's much more fleshed out and robust and meant to be used where you don't need to modify source code.

Static checkers like cppcheck are fine for basic usage

2

u/chrism239 23d ago

The hard-coded limit of 256 can be replaced by a call to getrlimit(RLIMIT_NOFILE, &limit)

0

u/[deleted] 20d ago

[deleted] — view deleted comment

1

u/icy-mist-01 19d ago edited 19d ago

First of all thank you for taking your time to go through it, and for this detailed resposne.

To be clear I used the phrase 'more robust' specifically in reply to the comment earlier, suggesting a hardcoded while (i-- > 3) dup(i) loop at the end of main(), not as a blanket sales pitch that LD_PRELOAD has zero flaws.
As with every one-man months-long effort projects, I'll keep working on and evolving this.

I'm already upfront about the architectural trade-offs in the README under 'Design constraints & caveats,' which explicitly calls out that direct syscall(2) invocations, raw assembly, and non-libc runtimes bypass dynamic interposition entirely.

What you mentioned about internal glibc calls functions like fopen or opendir is correct, bypass the public open hook internally, so unless those higher-level calls are wrapped too, they'll slip right through. At this point, I'm keeping that as a known limitations. For my specific goal and use-case here for most real scenarios, that's a conscious trradeoff.

For the more esoteric ones you mentioned, io_uring_setup and pidfd_open are actually already hooked in my code. Mach fileports are a macOS thing I think, this project is strictly Linux.

Agree on the open() then fdopen() then fclose() mismatch you said, will add those, thanks for that.

For the production aspect - the intention is not to use my libfdhunt preload permanently across the whole fleet. It's more for issue troubleshooting and diagnosis and isolating leaks about the problematic process - aimed at use on the dev/test box or a CI runner managing the same workload (where, say, valgrind is too slow to run under real load) so you can find out what's wrong in production.
So when you look at it from that perspective, I believe it's definitely production-grade useful.

But yes, what you mentioned about multithreaded destructor mechanism is defintinely worth considering. Things can get messy. I'll look into that.

However, I'll have to disagree on  "multiple processes sharing the same fd table"
I didn't include sharing an fd table across separate processes via raw clone() since the tracker lives in process memory, but almost no real-world code actually does that outside of threads.

And lastly, though I haven't looked into bionic's fdtrack or fdsan in that much detail before, appreciate for pointing that out. I'll add it to my comparison table. In fact, since my libfdhunt already hooks creation time, capturing the call stack via backtrace() andd storing it in the tracker table is already planned for the next version so the output points straight to the caller that opened it. In my plans for bettering this project.