Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

Broadening compiler checks for buffer overflows in _FORTIFY_SOURCE

April 16, 2021
Siddhesh Poyarekar
Related topics:
C, C#, C++LinuxSecurity
Related products:
Red Hat Enterprise Linux

    Buffer overruns are by far the most common vulnerability in C or C++ programs, and a number of techniques have come up over the years to detect overruns early and abort execution. The _FORTIFY_SOURCE macro, provided by the GNU C Library, helps mitigate a number of these overruns and is widely deployed in Red Hat Enterprise Linux. This article on the Red Hat Security blog is a good introduction to _FORTIFY_SOURCE.

    In the GNU C Library's 2.33 release, we added a new level for _FORTIFY_SOURCE to improve the protections the macro provides. Here we take a closer look at the internals of _FORTIFY_SOURCE in GCC and explore the need for this new level.

    _FORTIFY_SOURCE under the hood

    The _FORTIFY_SOURCE macro replaces some common functions with fortified wrappers that check whether the size of the destination buffer in those functions is large enough to handle the input data. If the check fails, the program aborts, and the users are saved from what could have been an exploitable buffer overflow. The actual implementation of a fortified wrapper function has a lot of glibc-isms, but it is conceptually a wrapper for wmemcpy that looks like the following:

    extern inline wchar_t *
    __attribute__ ((always_inline))
    wmemcpy (wchar_t *__restrict __s1, const wchar_t *__restrict __s2, size_t __n)
    {
      if (__builtin_object_size (__s1, 0) != (size_t) -1)
        return __wmemcpy_chk (__s1, __s2, __n,
                              __builtin_object_size (__s1, 0) / sizeof (wchar_t));
      return __original_wmemcpy (__s1, __s2, __n);
    }
    

    The GNU C Library implements similar fortified wrappers for a number of functions. Some wrappers look slightly different; for example, the memcpy wrapper unconditionally calls a builtin named __builtin___memcpy_chk. Those built-ins also evaluate to roughly the wrapper function just shown.

    The cornerstone: __builtin_object_size

    As the sample source code shows, the core functionality of _FORTIFY_SOURCE is based around the __builtin_object_size builtin. This builtin evaluates objects that the first argument (which is a pointer) points to and returns an estimate for the size of the object. Based on the second argument to the builtin, the size may be a minimum estimate or a maximum estimate. If the builtin fails to deduce the object size, then it either returns (size_t)0 or (size_t)-1 depending on whether the minimum or maximum estimate is requested.

    The compiler translates the wrapper to either a call to __wmmcpy_chk or to the original wmemcpy, denoted by __original_wmemcpy in the example above. Most importantly, the compiler optimizes away the __builtin_object_size comparison because it is a constant expression: __builtin_object_size always returns a constant. If __builtin_object_size is unable to deduce a constant object size, the compiler falls back to the default implementation wmemcpy.

    Validate before you leap

    The checking variant of wmemcpy—i.e., __wmemcpy_chk—is trivially implemented as follows:

    wchar_t *
    __wmemcpy_chk (wchar_t *s1, const wchar_t *s2, size_t n, size_t ns1)
    {
      if (__glibc_unlikely (ns1 < n))
        __chk_fail ();
      return (wchar_t *) memcpy ((char *) s1, (char *) s2, n * sizeof (wchar_t));
    }
    

    where __chk_fail aborts the program. At first glance, this looks slow because it adds a condition to every call. However, glibc lays out the performance-sensitive functions in a way that the overhead at runtime is constant, and in practice negligible.

    In the very long term, everything is dynamic

    The obvious extension to this functionality is to allow __builtin_object_size to return non-constant results. That idea eventually took the form of a new builtin called __builtin_dynamic_object_size, implemented in LLVM 9. This builtin intends to be a drop-in replacement for __builtin_object_size, although there some differences. Like __builtin_object_size, the new builtin attempts to evaluate the size of the object to a constant. If the object size is not constant, the builtin tries to deduce an expression that evaluates the size of the object. If even that is not possible, it bails out and returns (size_t)-1 or (size_t)0. Overall, this allows more cases where the size of an object can be known well enough to do something useful with it at runtime.

    A third fortification level

    With glibc 2.33, this support materialized into an actual hardening feature in the form of a new fortification level: _FORTIFY_SOURCE=3. This fortification level widens coverage of cases that _FORTIFY_SOURCE can catch. For example, the following function:

    size_t add_size;
    size_t multiplier;
    
    void *
    do_something (void *in, size_t insz, size_t sz)
    {
      void *buf = malloc ((sz + add_size) * multiplier);
    
      memcpy (buf, in, insz);
    
      return buf;
    }
    

    when built with _FORTIFY_SOURCE=2, does not result in a call to the fortified version of memcpy (i.e., __memcpy_chk). As a result, cases where insz may be bigger than the size of buf slip through.

    With _FORTIFY_SOURCE=3, though, __builtin_dynamic_object_size can evaluate to (sz + add_size) * multiplier. With this expression, the compiler can generate a call to __memcpy_chk and allow fortification. This promises to significantly widen fortification coverage to include cases where the compiler can see the non-constant expression for object size. This is a great improvement, but we decided against implementing this at _FORTIFY_SOURCE level 2.

    Runtime overhead in _FORTIFY_SOURCE=3

    Earlier _FORTIFY_SOURCE levels rely on constant object sizes; because of this, the runtime overhead is negligible. _FORTIFY_SOURCE=3, however, changes that because expressions used to compute the object size can be arbitrarily complex. Complex expressions can add arbitrarily more runtime overhead. Further, consider the possibility of do_something in the previous example being called in a loop; the overhead gets magnified. This was a good enough reason to not sneak this new functionality in under the hood. The new level lets developers tinker around with it and decide whether the overhead was acceptable for their use case.

    What's next for _FORTIFY_SOURCE

    GCC support for __builtin_dynamic_object_size or equivalent functionality is in progress. At the moment this is available only when building applications with LLVM. There are some unspecified corner cases with __builtin_dynamic_object_size that may result in avoidable performance overheads. We hope to iron those out with the GCC implementation and feed it back into LLVM, thus making both implementations consistent and performant.

    _FORTIFY_SOURCE=3 begins a shift in design for source fortification as we accept variable performance overheads for the checking. This also adds potential for additional coverage in the future as compilers get smarter at deducing object sizes. This is hopefully just the beginning!

    Last updated: October 14, 2022

    Recent Posts

    • Red Hat Enterprise Linux 10.2 and 9.8: Top features for developers

    • What GPU kernels mean for your distributed inference

    • Debugging image mode with Red Hat OpenShift 4.20: A practical guide

    • EvalHub: Because "looks good to me" isn't a benchmark

    • SQL Server HA on RHEL: Meet Pacemaker HA Agent v2 (tech preview)

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Build

    • Developer Sandbox
    • Developer tools
    • Interactive tutorials
    • API catalog

    Quicklinks

    • Learning resources
    • E-books
    • Cheat sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site status dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2026 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Chat Support

    Please log in with your Red Hat account to access chat support.