(root)/
glibc-2.38/
string/
tst-strerror-fail.c
       1  /* Check that strerror, strerror_l do not return NULL on  failure (bug 30555).
       2     Copyright (C) 2023 Free Software Foundation, Inc.
       3     This file is part of the GNU C Library.
       4  
       5     The GNU C Library is free software; you can redistribute it and/or
       6     modify it under the terms of the GNU Lesser General Public
       7     License as published by the Free Software Foundation; either
       8     version 2.1 of the License, or (at your option) any later version.
       9  
      10     The GNU C Library is distributed in the hope that it will be useful,
      11     but WITHOUT ANY WARRANTY; without even the implied warranty of
      12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
      13     Lesser General Public License for more details.
      14  
      15     You should have received a copy of the GNU Lesser General Public
      16     License along with the GNU C Library; if not, see
      17     <https://www.gnu.org/licenses/>.  */
      18  
      19  
      20  #include <locale.h>
      21  #include <stdbool.h>
      22  #include <stdlib.h>
      23  #include <string.h>
      24  #include <support/check.h>
      25  #include <support/namespace.h>
      26  #include <support/xdlfcn.h>
      27  
      28  /* Interposed malloc that can be used to inject allocation failures.  */
      29  
      30  static volatile bool fail_malloc;
      31  
      32  void *
      33  malloc (size_t size)
      34  {
      35    if (fail_malloc)
      36      return NULL;
      37  
      38    static void *(*original_malloc) (size_t);
      39    if (original_malloc == NULL)
      40      original_malloc = xdlsym (RTLD_NEXT, "malloc");
      41    return original_malloc (size);
      42  }
      43  
      44  /* Callbacks for the actual tests.  Use fork to run both tests with a
      45     clean state.  */
      46  
      47  static void
      48  test_strerror (void *closure)
      49  {
      50    fail_malloc = true;
      51    const char *s = strerror (999);
      52    fail_malloc = false;
      53    TEST_COMPARE_STRING (s, "Unknown error");
      54  }
      55  
      56  static void
      57  test_strerror_l (void *closure)
      58  {
      59    locale_t loc = newlocale (LC_ALL, "C", (locale_t) 0);
      60    TEST_VERIFY (loc != (locale_t) 0);
      61    fail_malloc = true;
      62    const char *s = strerror_l (999, loc);
      63    fail_malloc = false;
      64    TEST_COMPARE_STRING (s, "Unknown error");
      65    freelocale (loc);
      66  }
      67  
      68  static int
      69  do_test (void)
      70  {
      71    support_isolate_in_subprocess (test_strerror, NULL);
      72    support_isolate_in_subprocess (test_strerror_l, NULL);
      73  
      74    return 0;
      75  }
      76  
      77  #include <support/test-driver.c>