Compare commits

...
Author SHA1 Message Date
Florian Weimer 3d6b49f9fe Linux: Only define OPEN_TREE_* macros in <sys/mount.h> if undefined (bug 33921)
There is a conditional inclusion of <linux/mount.h> earlier in the file.
If that defines the macros, do not redefine them.  This addresses build
problems as the token sequence used by the UAPI macro definitions
changes between Linux versions.

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit d12b017cdd)
2026-05-02 14:47:33 +02:00
DJ Delorie e2aae83217 include: isolate __O_CLOEXEC flag for sys/mount.h and fcntl.h
Including sys/mount.h should not implicitly include fcntl.h
as that causes namespace pollution and conflicts with kernel
headers.  It only needs O_CLOEXEC for OPEN_TREE_CLOEXEC
(although it shouldn't need that, but it's defined that way)
so we provide that define (via a private version) separately.

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
Tested-by: Florian Weimer <fweimer@redhat.com>
(cherry picked from commit 419245719c)
2026-05-02 14:47:33 +02:00
Florian Weimer ba37b74652 Use pending character state in IBM1390, IBM1399 character sets (CVE-2026-4046)
Follow the example in iso-2022-jp-3.c and use the __count state
variable to store the pending character.  This avoids restarting
the conversion if the output buffer ends between two 4-byte UCS-4
code points, so that the assert reported in the bug can no longer
happen.

Even though the fix is applied to ibm1364.c, the change is only
effective for the two HAS_COMBINED codecs for IBM1390, IBM1399.

The test case was mostly auto-generated using
claude-4.6-opus-high-thinking, and composer-2-fast shows up in the
log as well.  During review, gpt-5.4-xhigh flagged that the original
version of the test case was not exercising the new character
flush logic.

This fixes bug 33980.

Assisted-by: LLM
Reviewed-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit d6f08d1cf0)
2026-04-21 21:37:36 +02:00
Xi Ruoyao 49a10f5ac7 elf: parse /proc/self/maps as the last resort to find the gap for tst-link-map-contiguous-ldso
The initialization process of libc.so calls mmap() several times and the
kernel may lay the maps into the gap.  If all pages in the gap are
occupied, the test would not be able to find the gap with mmap() and the
test would fail.

The failure reproduces most frequently on LoongArch because with the
commonly used page size (16 KiB) the gap only contains 4 pages and the
probability they are all occupied is not near to zero.

With the changes in the patch, a test run may output:

    info: ld.so link map is not contiguous
    info: object "/dev/zero" found at 0x7ffff1fe0000 - 0x7ffff1fe4000
    info: anonymous mapping found at 0x7ffff1fe4000 - 0x7ffff1fec000

Also take the chance to fix a mistake in the "object found at" message
which has puzzled me during the initial debug session.

Signed-off-by: Xi Ruoyao <xry111@xry111.site>
Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit aed8390a6a)
2026-03-30 19:43:05 +02:00
Carlos O'Donell d1c53ae189 resolv: Check hostname for validity (CVE-2026-4438)
The processed hostname in getanswer_ptr should be correctly checked to
avoid invalid characters from being allowed, including shell
metacharacters. It is a security issue to fail to check the returned
hostname for validity.

A regression test is added for invalid metacharacters and other cases
of invalid or valid characters.

No regressions on x86_64-linux-gnu.

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit e10977481f)
2026-03-30 19:43:05 +02:00
Carlos O'Donell 0cd6f8733d resolv: Count records correctly (CVE-2026-4437)
The answer section boundary was previously ignored, and the code in
getanswer_ptr would iterate past the last resource record, but not
beyond the end of the returned data.  This could lead to subsequent data
being interpreted as answer records, thus violating the DNS
specification.  Such resource records could be maliciously crafted and
hidden from other tooling, but processed by the glibc stub resolver and
acted upon by the application.  While we trust the data returned by the
configured recursive resolvers, we should not trust its format and
should validate it as required.  It is a security issue to incorrectly
process the DNS protocol.

A regression test is added for response section crossing.

No regressions on x86_64-linux-gnu.

Reviewed-by: Collin Funk <collin.funk1@gmail.com>
(cherry picked from commit 9f5f18aab4)
2026-03-30 19:43:05 +02:00
Florian Weimer 87ad92d0c7 posix: Run tst-wordexp-reuse-mem test
The test was not properly scheduled for execution with a Makefile
dependency.

Fixes commit 80cc58ea2d ("posix: Reset
wordexp_t fields with WRDE_REUSE (CVE-2025-15281 / BZ 33814").

(cherry picked from commit bed2db02f3)
2026-03-30 19:43:05 +02:00
Florian Weimer 3967aeb151 iconvdata: Fix invalid pointer arithmetic in ANSI_X3.110 module
The expression inptr + 1 can technically be invalid: if inptr == inend,
inptr may point one element past the end of an array.

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit e98bd0c54d)
2026-03-30 19:43:05 +02:00
Adhemerval Zanella ff2b172803 posix: Reset wordexp_t fields with WRDE_REUSE (CVE-2025-15281 / BZ 33814)
The wordexp fails to properly initialize the input wordexp_t when
WRDE_REUSE is used. The wordexp_t struct is properly freed, but
reuses the old wc_wordc value and updates the we_wordv in the
wrong position.  A later wordfree will then call free with an
invalid pointer.

Checked on x86_64-linux-gnu and i686-linux-gnu.

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit 80cc58ea2d)
2026-01-20 16:23:57 -03:00
Carlos O'Donell ddcaed5dfb resolv: Fix NSS DNS backend for getnetbyaddr (CVE-2026-0915)
The default network value of zero for net was never tested for and
results in a DNS query constructed from uninitialized stack bytes.
The solution is to provide a default query for the case where net
is zero.

Adding a test case for this was straight forward given the existence of
tst-resolv-network and if the test is added without the fix you observe
this failure:

FAIL: resolv/tst-resolv-network
original exit status 1
error: tst-resolv-network.c:174: invalid QNAME: \146\218\129\128
error: 1 test failures

With a random QNAME resulting from the use of uninitialized stack bytes.

After the fix the test passes.

Additionally verified using wireshark before and after to ensure
on-the-wire bytes for the DNS query were as expected.

No regressions on x86_64.

Reviewed-by: Florian Weimer <fweimer@redhat.com>
(cherry picked from commit e56ff82d50)
2026-01-16 09:32:18 -05:00
Siddhesh Poyarekar 7b913d41a0 memalign: reinstate alignment overflow check (CVE-2026-0861)
The change to cap valid sizes to PTRDIFF_MAX inadvertently dropped the
overflow check for alignment in memalign functions, _mid_memalign and
_int_memalign.  Reinstate the overflow check in _int_memalign, aligned
with the PTRDIFF_MAX change since that is directly responsible for the
CVE.  The missing _mid_memalign check is not relevant (and does not have
a security impact) and may need a different approach to fully resolve,
so it has been omitted.

CVE-Id: CVE-2026-0861
Vulnerable-Commit: 9bf8e29ca1
Reported-by: Igor Morgenstern, Aisle Research
Fixes: BZ #33796
Reviewed-by: Wilco Dijkstra <Wilco.Dijkstra@arm.com>
Signed-off-by: Siddhesh Poyarekar <siddhesh@gotplt.org>
(cherry picked from commit c9188d3337)
2026-01-16 10:28:50 +01:00
Sunil K Pandey e34115e6f9 nptl: Optimize trylock for high cache contention workloads (BZ #33704)
Check lock availability before acquisition to reduce cache line
bouncing.  Significantly improves trylock throughput on multi-core
systems under heavy contention.

Tested on x86_64.

Fixes BZ #33704.

Co-authored-by: Alex M Wells <alex.m.wells@intel.com>
Reviewed-by: Wilco Dijkstra  <Wilco.Dijkstra@arm.com>
(cherry picked from commit 63716823db)
2025-12-18 10:57:54 -08:00
Sachin Monga d18da0e1b5 ppc64le: Power 10 rawmemchr clobbers v20 (bug #33091)
Replace non-volatile(v20) by volatile(v17)
since v20 is not restored

Reviewed-by: Peter Bergner <bergner@tenstorrent.com>
(cherry picked from commit b59799f14f)
2025-11-27 11:14:42 -05:00
Jiamei Xie ba7c1682ea x86: fix wmemset ifunc stray '!' (bug 33542)
The ifunc selector for wmemset had a stray '!' in the
X86_ISA_CPU_FEATURES_ARCH_P(...) check:

  if (X86_ISA_CPU_FEATURE_USABLE_P (cpu_features, AVX2)
      && X86_ISA_CPU_FEATURES_ARCH_P (cpu_features,
                                      AVX_Fast_Unaligned_Load, !))

This effectively negated the predicate and caused the AVX2/AVX512
paths to be skipped, making the dispatcher fall back to the SSE2
implementation even on CPUs where AVX2/AVX512 are available. The
regression leads to noticeable throughput loss for wmemset.

Remove the stray '!' so the AVX_Fast_Unaligned_Load capability is
tested as intended and the correct AVX2/EVEX variants are selected.

Impact:
- On AVX2/AVX512-capable x86_64, wmemset no longer incorrectly
  falls back to SSE2; perf now shows __wmemset_evex/avx2 variants.

Testing:
- benchtests/bench-wmemset shows improved bandwidth across sizes.
- perf confirm the selected symbol is no longer SSE2.

Signed-off-by: xiejiamei <xiejiamei@hygon.com>
Signed-off-by: Li jing <lijing@hygon.cn>
Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit 4d86b6cdd8)
2025-11-04 12:23:17 +00:00
H.J. Lu df5072615e x86-64: Add GLIBC_ABI_DT_X86_64_PLT [BZ #33212]
When the linker -z mark-plt option is used to add DT_X86_64_PLT,
DT_X86_64_PLTSZ and DT_X86_64_PLTENT, the r_addend field of the
R_X86_64_JUMP_SLOT relocation stores the offset of the indirect
branch instruction.  However, glibc versions without the commit:

commit f8587a6189
Author: H.J. Lu <hjl.tools@gmail.com>
Date:   Fri May 20 19:21:48 2022 -0700

    x86-64: Ignore r_addend for R_X86_64_GLOB_DAT/R_X86_64_JUMP_SLOT

    According to x86-64 psABI, r_addend should be ignored for R_X86_64_GLOB_DAT
    and R_X86_64_JUMP_SLOT.  Since linkers always set their r_addends to 0, we
    can ignore their r_addends.

    Reviewed-by: Fangrui Song <maskray@google.com>

won't ignore the r_addend value in the R_X86_64_JUMP_SLOT relocation.
Such programs and shared libraries will fail at run-time randomly.

Add GLIBC_ABI_DT_X86_64_PLT version to indicate that glibc is compatible
with DT_X86_64_PLT.

The linker can add the glibc GLIBC_ABI_DT_X86_64_PLT version dependency
whenever -z mark-plt is passed to the linker.  The resulting programs and
shared libraries will fail to load at run-time against libc.so without the
GLIBC_ABI_DT_X86_64_PLT version, instead of fail randomly.

This fixes BZ #33212.

Signed-off-by: H.J. Lu <hjl.tools@gmail.com>
Reviewed-by: Sam James <sam@gentoo.org>
(cherry picked from commit 399384e0c8)
2025-08-15 23:19:27 +01:00
Florian Weimer d0d5736bbb elf: Handle ld.so with LOAD segment gaps in _dl_find_object (bug 31943)
Detect if ld.so not contiguous and handle that case in _dl_find_object.
Set l_find_object_processed even for initially loaded link maps,
otherwise dlopen of an initially loaded object adds it to
_dlfo_loaded_mappings (where maps are expected to be contiguous),
in addition to _dlfo_nodelete_mappings.

Test elf/tst-link-map-contiguous-ldso iterates over the loader
image, reading every word to make sure memory is actually mapped.
It only does that if the l_contiguous flag is set for the link map.
Otherwise, it finds gaps with mmap and checks that _dl_find_object
does not return the ld.so mapping for them.

The test elf/tst-link-map-contiguous-main does the same thing for
the libc.so shared object.  This only works if the kernel loaded
the main program because the glibc dynamic loader may fill
the gaps with PROT_NONE mappings in some cases, making it contiguous,
but accesses to individual words may still fault.

Test elf/tst-link-map-contiguous-libc is again slightly different
because the dynamic loader always fills the gaps with PROT_NONE
mappings, so a different form of probing has to be used.

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit 20681be149)
2025-08-14 09:29:52 +02:00
Florian Weimer f2d210447a elf: Extract rtld_setup_phdr function from dl_main
Remove historic binutils reference from comment and update
how this data is used by applications.

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit 2cac9559e0)
2025-08-14 09:29:22 +02:00
Florian Weimer 3963a5a093 elf: Do not add a copy of _dl_find_object to libc.so
This reduces code size and dependencies on ld.so internals from
libc.so.

Fixes commit f4c142bb9f
("arm: Use _dl_find_object on __gnu_Unwind_Find_exidx (BZ 31405)").

Reviewed-by: Adhemerval Zanella <adhemerval.zanella@linaro.org>
(cherry picked from commit 96429bcc91)
2025-08-14 09:29:22 +02:00
Adhemerval Zanella ba601ceeba arm: Use _dl_find_object on __gnu_Unwind_Find_exidx (BZ 31405)
Instead of __dl_iterate_phdr. On ARM dlfo_eh_frame/dlfo_eh_count
maps to PT_ARM_EXIDX vaddr start / length.

On a Neoverse N1 machine with 160 cores, the following program:

  $ cat test.c
  #include <stdlib.h>
  #include <pthread.h>
  #include <assert.h>

  enum {
    niter = 1024,
    ntimes = 128,
  };

  static void *
  tf (void *arg)
  {
    int a = (int) arg;

    for (int i = 0; i < niter; i++)
      {
        void *p[ntimes];
        for (int j = 0; j < ntimes; j++)
  	p[j] = malloc (a * 128);
        for (int j = 0; j < ntimes; j++)
  	free (p[j]);
      }

    return NULL;
  }

  int main (int argc, char *argv[])
  {
    enum { nthreads = 16 };
    pthread_t t[nthreads];

    for (int i = 0; i < nthreads; i ++)
      assert (pthread_create (&t[i], NULL, tf, (void *) i) == 0);

    for (int i = 0; i < nthreads; i++)
      {
        void *r;
        assert (pthread_join (t[i], &r) == 0);
        assert (r == NULL);
      }

    return 0;
  }
  $ arm-linux-gnueabihf-gcc -fsanitize=address test.c -o test

Improves from ~15s to 0.5s.

Checked on arm-linux-gnueabihf.

(cherry picked from commit f4c142bb9f)
2025-08-14 09:29:19 +02:00
Florian Weimer 58b768addb posix: Fix double-free after allocation failure in regcomp (bug 33185)
If a memory allocation failure occurs during bracket expression
parsing in regcomp, a double-free error may result.

Reported-by: Anastasia Belova <abelova@astralinux.ru>
Co-authored-by: Paul Eggert <eggert@cs.ucla.edu>
Reviewed-by: Andreas K. Huettel <dilfridge@gentoo.org>
(cherry picked from commit 7ea06e9940)
2025-07-24 09:51:33 +02:00
Florian Weimer ea179f9a37 Fix error reporting (false negatives) in SGID tests
And simplify the interface of support_capture_subprogram_self_sgid.

Use the existing framework for temporary directories (now with
mode 0700) and directory/file deletion.  Handle all execution
errors within support_capture_subprogram_self_sgid.  In particular,
this includes test failures because the invoked program did not
exit with exit status zero.  Existing tests that expect exit
status 42 are adjusted to use zero instead.

In addition, fix callers not to call exit (0) with test failures
pending (which may mask them, especially when running with --direct).

Fixes commit 35fc356fa3
("elf: Fix subprocess status handling for tst-dlopen-sgid (bug 32987)").

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit 3a3fb2ed83)
2025-06-20 11:43:09 +02:00
Florian Weimer 245dffa9ed support: Pick group in support_capture_subprogram_self_sgid if UID == 0
When running as root, it is likely that we can run under any group.
Pick a harmless group from /etc/group in this case.

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit 2f769cec44)
2025-06-20 11:43:09 +02:00
Siddhesh Poyarekar 9643281f9c support: Don't fail on fchown when spawning sgid processes
In some cases (e.g. when podman creates user containers), the only other
group assigned to the executing user is nobody and fchown fails with it
because the group is not mapped.  Do not fail the test in this case,
instead exit as unsupported.

Reported-by: Frédéric Bérat <fberat@redhat.com>
Tested-by: Frédéric Bérat <fberat@redhat.com>
Signed-off-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
Reviewed-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit 6286cca2cb)
2025-06-20 11:43:00 +02:00
Florian Weimer fba1c47cb5 elf: Fix subprocess status handling for tst-dlopen-sgid (bug 32987)
This should really move into support_capture_subprogram_self_sgid.

Reviewed-by: Sam James <sam@gentoo.org>
(cherry picked from commit 35fc356fa3)
2025-05-21 09:01:25 +02:00
Sunil K Pandey 0f4e5f764b x86_64: Fix typo in ifunc-impl-list.c.
Fix wcsncpy and wcpncpy typo in ifunc-impl-list.c.

Reviewed-by: H.J. Lu <hjl.tools@gmail.com>
(cherry picked from commit f2aeb6ff94)
2025-05-20 16:50:31 -07:00
Florian Weimer e8e6c54353 elf: Test case for bug 32976 (CVE-2025-4802)
Check that LD_LIBRARY_PATH is ignored for AT_SECURE statically
linked binaries, using support_capture_subprogram_self_sgid.

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit d8f7a79335)
2025-05-20 20:28:20 +02:00
Florian Weimer 1e29775735 support: Add support_record_failure_barrier
This can be used to stop execution after a TEST_COMPARE_BLOB
failure, for example.

(cherry picked from commit d0b8aa6de4)
2025-05-20 20:27:38 +02:00
Florian Weimer 5b1ea2a223 support: Use const char * argument in support_capture_subprogram_self_sgid
The function does not modify the passed-in string, so make this clear
via the prototype.

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit f0c09fe616)
2025-05-20 20:27:38 +02:00
Adhemerval Zanella 7403ede2d7 elf: Ignore LD_LIBRARY_PATH and debug env var for setuid for static
It mimics the ld.so behavior.

Checked on x86_64-linux-gnu.
Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>

(cherry picked from commit 5451fa962c)

Changes:

	git/elf/dl-support.c
	  (missing commit 55f41ef8de
	   ("elf: Remove LD_PROFILE for static binaries"))
2025-05-20 20:27:34 +02:00
Wilco Dijkstra 032545ebd3 math: Improve layout of exp/exp10 data
GCC aligns global data to 16 bytes if their size is >= 16 bytes.  This patch
changes the exp_data struct slightly so that the fields are better aligned
and without gaps.  As a result on targets that support them, more load-pair
instructions are used in exp.

The exp benchmark improves 2.5%, "144bits" by 7.2%, "768bits" by 12.7% on
Neoverse V2.

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit 5afaf99edb)
(cherry picked from commit 5a08d049dc)
2025-02-28 14:56:41 +00:00
Wilco Dijkstra b4a783aa30 AArch64: Use prefer_sve_ifuncs for SVE memset
Use prefer_sve_ifuncs for SVE memset just like memcpy.

Reviewed-by: Yury Khrustalev <yury.khrustalev@arm.com>
(cherry picked from commit 0f044be1da)
2025-02-28 14:56:41 +00:00
Wilco Dijkstra c747695762 AArch64: Add SVE memset
Add SVE memset based on the generic memset with predicated load for sizes < 16.
Unaligned memsets of 128-1024 are improved by ~20% on average by using aligned
stores for the last 64 bytes.  Performance of random memset benchmark improves
by ~2% on Neoverse V1.

Reviewed-by: Yury Khrustalev <yury.khrustalev@arm.com>
(cherry picked from commit 163b1bbb76)
2025-02-28 14:56:38 +00:00
Wilco Dijkstra 93e4b0796e math: Improve layout of expf data
GCC aligns global data to 16 bytes if their size is >= 16 bytes.  This patch
changes the exp2f_data struct slightly so that the fields are better aligned.
As a result on targets that support them, load-pair instructions accessing
poly_scaled and invln2_scaled are now 16-byte aligned.

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit 44fa9c1080)
2025-02-28 14:55:38 +00:00
Wilco Dijkstra 06eafb057a AArch64: Remove zva_128 from memset
Remove ZVA 128 support from memset - the new memset no longer
guarantees count >= 256, which can result in underflow and a
crash if ZVA size is 128 ([1]).  Since only one CPU uses a ZVA
size of 128 and its memcpy implementation was removed in commit
e162ab2bf1, remove this special
case too.

[1] https://sourceware.org/pipermail/libc-alpha/2024-November/161626.html

Reviewed-by: Andrew Pinski <quic_apinski@quicinc.com>
(cherry picked from commit a08d9a52f9)
2025-02-28 14:55:38 +00:00
Wilco Dijkstra 7d16ea8b42 AArch64: Optimize memset
Improve small memsets by avoiding branches and use overlapping stores.
Use DC ZVA for copies over 128 bytes.  Remove unnecessary code for ZVA sizes
other than 64 and 128.  Performance of random memset benchmark improves by 24%
on Neoverse N1.

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit cec3aef324)
2025-02-28 14:55:36 +00:00
Wilco Dijkstra 7feb4c414e AArch64: Improve generic strlen
Improve performance by handling another 16 bytes before entering the loop.
Use ADDHN in the loop to avoid SHRN+FMOV when it terminates.  Change final
size computation to avoid increasing latency.  On Neoverse V1 performance
of the random strlen benchmark improves by 4.6%.

Reviewed-by: Adhemerval Zanella <adhemerval.zanella@linaro.org>
(cherry picked from commit 3dc426b642)
2025-02-28 14:55:09 +00:00
Siddhesh Poyarekar b989519fe1 assert: Add test for CVE-2025-0395
Use the __progname symbol to override the program name to induce the
failure that CVE-2025-0395 describes.

This is related to BZ #32582

Signed-off-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit cdb9ba8419)
2025-02-13 13:14:25 -05:00
Carlos O'Donell 5288c29247 assert: Reformat Makefile.
Reflow all long lines adding comment terminators.
Sort all reflowed text using scripts/sort-makefile-lines.py.

No code generation changes observed in binary artifacts.
No regressions on x86_64 and i686.

(cherry picked from commit ebd928224a)
2025-02-13 13:13:57 -05:00
H.J. Lu 24d69e33fc stdlib: Test using setenv with updated environ [BZ #32588]
Add a test for setenv with updated environ.  Verify that BZ #32588 is
fixed.

Signed-off-by: H.J. Lu <hjl.tools@gmail.com>
Reviewed-by: Florian Weimer <fweimer@redhat.com>
(cherry picked from commit 8ab34497de)
2025-01-25 11:07:47 +08:00
Siddhesh Poyarekar a3d7865b09 Fix underallocation of abort_msg_s struct (CVE-2025-0395)
Include the space needed to store the length of the message itself, in
addition to the message string.  This resolves BZ #32582.

Signed-off-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
Reviewed: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit 68ee0f704c)
2025-01-22 17:11:54 +01:00
Stafford Horne 9083997843 misc: Add support for Linux uio.h RWF_NOAPPEND flag
In Linux 6.9 a new flag is added to allow for Per-io operations to
disable append mode even if a file was opened with the flag O_APPEND.
This is done with the new RWF_NOAPPEND flag.

This caused two test failures as these tests expected the flag 0x00000020
to be unused.  Adding the flag definition now fixes these tests on Linux
6.9 (v6.9-rc1).

  FAIL: misc/tst-preadvwritev2
  FAIL: misc/tst-preadvwritev64v2

This patch adds the flag, adjusts the test and adds details to
documentation.

Link: https://lore.kernel.org/all/20200831153207.GO3265@brightrain.aerifal.cx/
Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit 3db9d208dd)
2025-01-12 11:32:36 -08:00
Florian Weimer abe2bb2b47 elf: Support recursive use of dynamic TLS in interposed malloc
It turns out that quite a few applications use bundled mallocs that
have been built to use global-dynamic TLS (instead of the recommended
initial-exec TLS).  The previous workaround from
commit afe42e935b ("elf: Avoid some
free (NULL) calls in _dl_update_slotinfo") does not fix all
encountered cases unfortunatelly.

This change avoids the TLS generation update for recursive use
of TLS from a malloc that was called during a TLS update.  This
is possible because an interposed malloc has a fixed module ID and
TLS slot.  (It cannot be unloaded.)  If an initially-loaded module ID
is encountered in __tls_get_addr and the dynamic linker is already
in the middle of a TLS update, use the outdated DTV, thus avoiding
another call into malloc.  It's still necessary to update the
DTV to the most recent generation, to get out of the slow path,
which is why the check for recursion is needed.

The bookkeeping is done using a global counter instead of per-thread
flag because TLS access in the dynamic linker is tricky.

All this will go away once the dynamic linker stops using malloc
for TLS, likely as part of a change that pre-allocates all TLS
during pthread_create/dlopen.

Fixes commit d2123d6827 ("elf: Fix slow
tls access after dlopen [BZ #19924]").

Reviewed-by: Szabolcs Nagy <szabolcs.nagy@arm.com>
(cherry picked from commit 018f0fc3b8)
2025-01-10 19:57:39 -08:00
Florian Weimer 19d8959b4d elf: Avoid some free (NULL) calls in _dl_update_slotinfo
This has been confirmed to work around some interposed mallocs.  Here
is a discussion of the impact test ust/libc-wrapper/test_libc-wrapper
in lttng-tools:

  New TLS usage in libgcc_s.so.1, compatibility impact
  <https://inbox.sourceware.org/libc-alpha/8734v1ieke.fsf@oldenburg.str.redhat.com/>

Reportedly, this patch also papers over a similar issue when tcmalloc
2.9.1 is not compiled with -ftls-model=initial-exec.  Of course the
goal really should be to compile mallocs with the initial-exec TLS
model, but this commit appears to be a useful interim workaround.

Fixes commit d2123d6827 ("elf: Fix slow
tls access after dlopen [BZ #19924]").

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit afe42e935b)
2025-01-10 19:47:37 -08:00
Noah Goldstein 7d1c950582 x86/string: Fixup alignment of main loop in str{n}cmp-evex [BZ #32212]
The loop should be aligned to 32-bytes so that it can ideally run out
the DSB. This is particularly important on Skylake-Server where
deficiencies in it's DSB implementation make it prone to not being
able to run loops out of the DSB.

For example running strcmp-evex on 200Mb string:

32-byte aligned loop:
    - 43,399,578,766      idq.dsb_uops
not 32-byte aligned loop:
    - 6,060,139,704       idq.dsb_uops

This results in a 25% performance degradation for the non-aligned
version.

The fix is to just ensure the code layout is such that the loop is
aligned. (Which was previously the case but was accidentally dropped
in 84e7c46df).

NB: The fix was actually 64-byte alignment. This is because 64-byte
alignment generally produces more stable performance than 32-byte
aligned code (cache line crosses can affect perf), so if we are going
past 16-byte alignmnent, might as well go to 64. 64-byte alignment
also matches most other functions we over-align, so it creates a
common point of optimization.

Times are reported as ratio of Time_With_Patch /
Time_Without_Patch. Lower is better.

The values being reported is the geometric mean of the ratio across
all tests in bench-strcmp and bench-strncmp.

Note this patch is only attempting to improve the Skylake-Server
strcmp for long strings. The rest of the numbers are only to test for
regressions.

Tigerlake Results Strings <= 512:
    strcmp : 1.026
    strncmp: 0.949

Tigerlake Results Strings > 512:
    strcmp : 0.994
    strncmp: 0.998

Skylake-Server Results Strings <= 512:
    strcmp : 0.945
    strncmp: 0.943

Skylake-Server Results Strings > 512:
    strcmp : 0.778
    strncmp: 1.000

The 2.6% regression on TGL-strcmp is due to slowdowns caused by
changes in alignment of code handling small sizes (most on the
page-cross logic). These should be safe to ignore because 1) We
previously only 16-byte aligned the function so this behavior is not
new and was essentially up to chance before this patch and 2) this
type of alignment related regression on small sizes really only comes
up in tight micro-benchmark loops and is unlikely to have any affect
on realworld performance.

Reviewed-by: H.J. Lu <hjl.tools@gmail.com>
(cherry picked from commit 483443d321)
2025-01-09 21:31:34 -08:00
Noah Goldstein 7e84df6892 x86: Improve large memset perf with non-temporal stores [RHEL-29312]
Previously we use `rep stosb` for all medium/large memsets. This is
notably worse than non-temporal stores for large (above a
few MBs) memsets.
See:
https://docs.google.com/spreadsheets/d/1opzukzvum4n6-RUVHTGddV6RjAEil4P2uMjjQGLbLcU/edit?usp=sharing
For data using different stategies for large memset on ICX and SKX.

Using non-temporal stores can be up to 3x faster on ICX and 2x faster
on SKX. Historically, these numbers would not have been so good
because of the zero-over-zero writeback optimization that `rep stosb`
is able to do. But, the zero-over-zero writeback optimization has been
removed as a potential side-channel attack, so there is no longer any
good reason to only rely on `rep stosb` for large memsets. On the flip
size, non-temporal writes can avoid data in their RFO requests saving
memory bandwidth.

All of the other changes to the file are to re-organize the
code-blocks to maintain "good" alignment given the new code added in
the `L(stosb_local)` case.

The results from running the GLIBC memset benchmarks on TGL-client for
N=20 runs:

Geometric Mean across the suite New / Old EXEX256: 0.979
Geometric Mean across the suite New / Old EXEX512: 0.979
Geometric Mean across the suite New / Old AVX2   : 0.986
Geometric Mean across the suite New / Old SSE2   : 0.979

Most of the cases are essentially unchanged, this is mostly to show
that adding the non-temporal case didn't add any regressions to the
other cases.

The results on the memset-large benchmark suite on TGL-client for N=20
runs:

Geometric Mean across the suite New / Old EXEX256: 0.926
Geometric Mean across the suite New / Old EXEX512: 0.925
Geometric Mean across the suite New / Old AVX2   : 0.928
Geometric Mean across the suite New / Old SSE2   : 0.924

So roughly a 7.5% speedup. This is lower than what we see on servers
(likely because clients typically have faster single-core bandwidth so
saving bandwidth on RFOs is less impactful), but still advantageous.

Full test-suite passes on x86_64 w/ and w/o multiarch.
Reviewed-by: H.J. Lu <hjl.tools@gmail.com>

(cherry picked from commit 5bf0ab8057)
2025-01-09 21:30:45 -08:00
Gabi Falk b0eef2f27f x86_64: Fix missing wcsncat function definition without multiarch (x86-64-v4)
This code expects the WCSCAT preprocessor macro to be predefined in case
the evex implementation of the function should be defined with a name
different from __wcsncat_evex.  However, when glibc is built for
x86-64-v4 without multiarch support, sysdeps/x86_64/wcsncat.S defines
WCSNCAT variable instead of WCSCAT to build it as wcsncat.  Rename the
variable to WCSNCAT, as it is actually a better naming choice for the
variable in this case.

Reported-by: Kenton Groombridge
Link: https://bugs.gentoo.org/921945
Fixes: 64b8b6516b ("x86: Add evex optimized functions for the wchar_t strcpy family")
Signed-off-by: Gabi Falk <gabifalk@gmx.com>
Reviewed-by: Sunil K Pandey <skpgkp2@gmail.com>
(cherry picked from commit dd5f891c1a)
2025-01-09 21:29:12 -08:00
H.J. Lu ec40bb7938 sysdeps/x86/Makefile: Split and sort tests
Put each test on a separate line and sort tests.

(cherry picked from commit 7e03e0de7e)
2025-01-09 21:27:33 -08:00
Noah Goldstein f0c2fcce5f x86: Only align destination to 1x VEC_SIZE in memset 4x loop
Current code aligns to 2x VEC_SIZE. Aligning to 2x has no affect on
performance other than potentially resulting in an additional
iteration of the loop.
1x maintains aligned stores (the only reason to align in this case)
and doesn't incur any unnecessary loop iterations.
Reviewed-by: Sunil K Pandey <skpgkp2@gmail.com>

(cherry picked from commit 9469261cf1)
2025-01-09 21:25:24 -08:00
Szabolcs Nagy 0c6f7cd550 elf: Fix slow tls access after dlopen [BZ #19924]
In short: __tls_get_addr checks the global generation counter and if
the current dtv is older then _dl_update_slotinfo updates dtv up to the
generation of the accessed module. So if the global generation is newer
than generation of the module then __tls_get_addr keeps hitting the
slow dtv update path. The dtv update path includes a number of checks
to see if any update is needed and this already causes measurable tls
access slow down after dlopen.

It may be possible to detect up-to-date dtv faster.  But if there are
many modules loaded (> TLS_SLOTINFO_SURPLUS) then this requires at
least walking the slotinfo list.

This patch tries to update the dtv to the global generation instead, so
after a dlopen the tls access slow path is only hit once.  The modules
with larger generation than the accessed one were not necessarily
synchronized before, so additional synchronization is needed.

This patch uses acquire/release synchronization when accessing the
generation counter.

Note: in the x86_64 version of dl-tls.c the generation is only loaded
once, since relaxed mo is not faster than acquire mo load.

I have not benchmarked this. Tested by Adhemerval Zanella on aarch64,
powerpc, sparc, x86 who reported that it fixes the performance issue
of bug 19924.

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit d2123d6827)
2025-01-09 21:25:15 -08:00
H.J. Lu ec7c01efee x86: Check the lower byte of EAX of CPUID leaf 2 [BZ #30643]
The old Intel software developer manual specified that the low byte of
EAX of CPUID leaf 2 returned 1 which indicated the number of rounds of
CPUDID leaf 2 was needed to retrieve the complete cache information. The
newer Intel manual has been changed to that it should always return 1
and be ignored.  If the lower byte isn't 1, CPUID leaf 2 can't be used.
In this case, we ignore CPUID leaf 2 and use CPUID leaf 4 instead.  If
CPUID leaf 4 doesn't contain the cache information, cache information
isn't available at all.  This addresses BZ #30643.

(cherry picked from commit 1493622f4f)
2025-01-09 21:25:03 -08:00
H.J. Lu f2947239b6 x86_64: Add log1p with FMA
On Skylake, it changes log1p bench performance by:

        Before       After     Improvement
max     63.349       58.347       8%
min     4.448        5.651        -30%
mean    12.0674      10.336       14%

The minimum code path is

 if (hx < 0x3FDA827A)                          /* x < 0.41422  */
    {
      if (__glibc_unlikely (ax >= 0x3ff00000))           /* x <= -1.0 */
        {
	   ...
        }
      if (__glibc_unlikely (ax < 0x3e200000))           /* |x| < 2**-29 */
        {
          math_force_eval (two54 + x);          /* raise inexact */
          if (ax < 0x3c900000)                  /* |x| < 2**-54 */
            {
	      ...
            }
          else
            return x - x * x * 0.5;

FMA and non-FMA code sequences look similar.  Non-FMA version is slightly
faster.  Since log1p is called by asinh and atanh, it improves asinh
performance by:

        Before       After     Improvement
max     75.645       63.135       16%
min     10.074       10.071       0%
mean    15.9483      14.9089      6%

and improves atanh performance by:

        Before       After     Improvement
max     91.768       75.081       18%
min     15.548       13.883       10%
mean    18.3713      16.8011      8%

(cherry picked from commit a8ecb126d4)
2025-01-09 21:24:50 -08:00
H.J. Lu c0cae389fb x86_64: Add expm1 with FMA
On Skylake, it improves expm1 bench performance by:

        Before       After     Improvement
max     70.204       68.054       3%
min     20.709       16.2         22%
mean    22.1221      16.7367      24%

NB: Add

extern long double __expm1l (long double);
extern long double __expm1f128 (long double);

for __typeof (__expm1l) and __typeof (__expm1f128) when __expm1 is
defined since __expm1 may be expanded in their declarations which
causes the build failure.

(cherry picked from commit 1b214630ce)
2025-01-09 21:24:41 -08:00
H.J. Lu 3607863050 x86_64: Add log2 with FMA
On Skylake, it improves log2 bench performance by:

        Before       After     Improvement
max     208.779      63.827       69%
min     9.977        6.55         34%
mean    10.366       6.8191       34%

(cherry picked from commit f6b10ed8e9)
2025-01-09 21:24:29 -08:00
H.J. Lu d5ff2fa5af x86_64: Sort fpu/multiarch/Makefile
Sort Makefile variables using scripts/sort-makefile-lines.py.

No code generation changes observed in libm.  No regressions on x86_64.

(cherry picked from commit 881546979d)
2025-01-09 21:23:53 -08:00
Florian Weimer 71fca07505 x86: Avoid integer truncation with large cache sizes (bug 32470)
Some hypervisors report 1 TiB L3 cache size.  This results
in some variables incorrectly getting zeroed, causing crashes
in memcpy/memmove because invariants are violated.

(cherry picked from commit 61c3450db9)
2024-12-17 18:56:05 +01:00
Michael Jeanson b2ab6ce0f5 nptl: initialize cpu_id_start prior to rseq registration
When adding explicit initialization of rseq fields prior to
registration, I glossed over the fact that 'cpu_id_start' is also
documented as initialized by user-space.

While current kernels don't validate the content of this field on
registration, future ones could.

Signed-off-by: Michael Jeanson <mjeanson@efficios.com>
Reviewed-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
(cherry picked from commit d9f40387d3)
2024-12-06 16:05:27 +00:00
Michael Jeanson 4b2b81deb4 nptl: initialize rseq area prior to registration
Per the rseq syscall documentation, 3 fields are required to be
initialized by userspace prior to registration, they are 'cpu_id',
'rseq_cs' and 'flags'. Since we have no guarantee that 'struct pthread'
is cleared on all architectures, explicitly set those 3 fields prior to
registration.

Signed-off-by: Michael Jeanson <mjeanson@efficios.com>
Reviewed-by: Florian Weimer <fweimer@redhat.com>
(cherry picked from commit 97f60abd25)
2024-12-06 16:05:27 +00:00
Florian Weimer a4d9258090 elf: Change ldconfig auxcache magic number (bug 32231)
In commit c628c22963 (elf: Remove
ldconfig kernel version check), the layout of auxcache entries
changed because the osversion field was removed from
struct aux_cache_file_entry.  However, AUX_CACHEMAGIC was not
changed, so existing files are still used, potentially leading
to unintended ldconfig behavior.  This commit changes AUX_CACHEMAGIC,
so that the file is regenerated.

Reported-by: DJ Delorie <dj@redhat.com>
Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit 0a536f6e2f)
2024-10-29 10:01:33 +01:00
Siddhesh Poyarekar 0141e7c794 libio: Attempt wide backup free only for non-legacy code
_wide_data and _mode are not available in legacy code, so do not attempt
to free the wide backup buffer in legacy code.

Resolves: BZ #32137 and BZ #27821

Signed-off-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
Reviewed-by: Florian Weimer <fweimer@redhat.com>
(cherry picked from commit ae4d44b1d5)
2024-09-11 09:34:07 +02:00
Maciej W. Rozycki 3d0acc5b20 nptl: Use <support/check.h> facilities in tst-setuid3
Remove local FAIL macro in favor to FAIL_EXIT1 from <support/check.h>,
which provides equivalent reporting, with the name of the file and the
line number within of the failure site additionally included.  Remove
FAIL_ERR altogether and include ": %m" explicitly with the format string
supplied to FAIL_EXIT1 as there seems little value to have a separate
macro just for this.

Reviewed-by: DJ Delorie <dj@redhat.com>
(cherry picked from commit 8c98195af6)
2024-08-30 15:28:50 -04:00
Maciej W. Rozycki 5b853745fd posix: Use <support/check.h> facilities in tst-truncate and tst-truncate64
Remove local FAIL macro in favor to FAIL_RET from <support/check.h>,
which provides equivalent reporting, with the name of the file of the
failure site additionally included, for the tst-truncate-common core
shared between the tst-truncate and tst-truncate64 tests.

Reviewed-by: DJ Delorie <dj@redhat.com>
(cherry picked from commit fe47595504)
2024-08-30 15:28:48 -04:00
Siddhesh Poyarekar 5259c8f052 ungetc: Fix backup buffer leak on program exit [BZ #27821]
If a file descriptor is left unclosed and is cleaned up by _IO_cleanup
on exit, its backup buffer remains unfreed, registering as a leak in
valgrind.  This is not strictly an issue since (1) the program should
ideally be closing the stream once it's not in use and (2) the program
is about to exit anyway, so keeping the backup buffer around a wee bit
longer isn't a real problem.  Free it anyway to keep valgrind happy
when the streams in question are the standard ones, i.e. stdout, stdin
or stderr.

Also, the _IO_have_backup macro checks for _IO_save_base,
which is a roundabout way to check for a backup buffer instead of
directly looking for _IO_backup_base.  The roundabout check breaks when
the main get area has not been used and user pushes a char into the
backup buffer with ungetc.  Fix this to use the _IO_backup_base
directly.

Signed-off-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
Reviewed-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit 3e1d8d1d1d)
(cherry picked from commit b9f72bd5de)
2024-08-28 18:44:07 -04:00
Siddhesh Poyarekar 810fa2488c ungetc: Fix uninitialized read when putting into unused streams [BZ #27821]
When ungetc is called on an unused stream, the backup buffer is
allocated without the main get area being present.  This results in
every subsequent ungetc (as the stream remains in the backup area)
checking uninitialized memory in the backup buffer when trying to put a
character back into the stream.

Avoid comparing the input character with buffer contents when in backup
to avoid this uninitialized read.  The uninitialized read is harmless in
this context since the location is promptly overwritten with the input
character, thus fulfilling ungetc functionality.

Also adjust wording in the manual to drop the paragraph that says glibc
cannot do multiple ungetc back to back since with this change, ungetc
can actually do this.

Signed-off-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
Reviewed-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit cdf0f88f97)
(cherry picked from commit 804d3c8db7)
2024-08-28 18:44:07 -04:00
Siddhesh Poyarekar bb6cfec3dd Make tst-ungetc use libsupport
Signed-off-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
Reviewed-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit 3f7df7e757)
(cherry picked from commit 87a1968a72)
2024-08-28 18:44:07 -04:00
Maciej W. Rozycki 5784740194 stdio-common: Add test for vfscanf with matches longer than INT_MAX [BZ #27650]
Complement commit b03e4d7bd2 ("stdio: fix vfscanf with matches longer
than INT_MAX (bug 27650)") and add a test case for the issue, inspired
by the reproducer provided with the bug report.

This has been verified to succeed as from the commit referred and fail
beforehand.

As the test requires 2GiB of data to be passed around its performance
has been evaluated using a choice of systems and the execution time
determined to be respectively in the range of 9s for POWER9@2.166GHz,
24s for FU740@1.2GHz, and 40s for 74Kf@950MHz.  As this is on the verge
of and beyond the default timeout it has been increased by the factor of
8.  Regardless, following recent practice the test has been added to the
standard rather than extended set.

Reviewed-by: DJ Delorie <dj@redhat.com>
(cherry picked from commit 89cddc8a70)
(cherry picked from commit 99ffa84bdc)
2024-08-28 18:44:05 -04:00
Maciej W. Rozycki 6eb9420551 support: Add FAIL test failure helper
Add a FAIL test failure helper analogous to FAIL_RET, that does not
cause the current function to return, providing a standardized way to
report a test failure with a message supplied while permitting the
caller to continue executing, for further reporting, cleaning up, etc.

Update existing test cases that provide a conflicting definition of FAIL
by removing the local FAIL definition and then as follows:

- tst-fortify-syslog: provide a meaningful message in addition to the
  file name already added by <support/check.h>; 'support_record_failure'
  is already called by 'support_print_failure_impl' invoked by the new
  FAIL test failure helper.

- tst-ctype: no update to FAIL calls required, with the name of the file
  and the line number within of the failure site additionally included
  by the new FAIL test failure helper, and error counting plus count
  reporting upon test program termination also already provided by
  'support_record_failure' and 'support_report_failure' respectively,
  called by 'support_print_failure_impl' and 'adjust_exit_status' also
  respectively.  However in a number of places 'printf' is called and
  the error count adjusted by hand, so update these places to make use
  of FAIL instead.  And last but not least adjust the final summary just
  to report completion, with any error count following as reported by
  the test driver.

- test-tgmath2: no update to FAIL calls required, with the name of the
  file of the failure site additionally included by the new FAIL test
  failure helper.  Also there is no need to track the return status by
  hand as any call to FAIL will eventually cause the test case to return
  an unsuccesful exit status regardless of the return status from the
  test function, via a call to 'adjust_exit_status' made by the test
  driver.

Reviewed-by: DJ Delorie <dj@redhat.com>
(cherry picked from commit 1b97a9f23b)
(cherry picked from commit 28f358bc42)
2024-08-28 18:43:12 -04:00
Noah Goldstein f82e0922de x86: Fix bug in strchrnul-evex512 [BZ #32078]
Issue was we were expecting not matches with CHAR before the start of
the string in the page cross case.

The check code in the page cross case:
```
    and    $0xffffffffffffffc0,%rax
    vmovdqa64 (%rax),%zmm17
    vpcmpneqb %zmm17,%zmm16,%k1
    vptestmb %zmm17,%zmm17,%k0{%k1}
    kmovq  %k0,%rax
    inc    %rax
    shr    %cl,%rax
    je     L(continue)
```

expects that all characters that neither match null nor CHAR will be
1s in `rax` prior to the `inc`. Then the `inc` will overflow all of
the 1s where no relevant match was found.

This is incorrect in the page-cross case, as the
`vmovdqa64 (%rax),%zmm17` loads from before the start of the input
string.

If there are matches with CHAR before the start of the string, `rax`
won't properly overflow.

The fix is quite simple. Just replace:

```
    inc    %rax
    shr    %cl,%rax
```
With:
```
    sar    %cl,%rax
    inc    %rax
```

The arithmetic shift will clear any matches prior to the start of the
string while maintaining the signbit so the 1s can properly overflow
to zero in the case of no matches.
Reviewed-by: H.J. Lu <hjl.tools@gmail.com>

(cherry picked from commit 7da0886247)
2024-08-15 15:42:39 -07:00
Andreas Schwab 6e642a47fa Fix name space violation in fortify wrappers (bug 32052)
Rename the identifier sz to __sz everywhere.

Fixes: a643f60c53 ("Make sure that the fortified function conditionals are constant")
(cherry picked from commit 39ca997ab3)
(redone from scratch because of many conflicts)
2024-08-06 08:46:39 +02:00
Florian Weimer aca9c7d5de resolv: Fix tst-resolv-short-response for older GCC (bug 32042)
Previous GCC versions do not support the C23 change that
allows labels on declarations.

Reviewed-by: Adhemerval Zanella <adhemerval.zanella@linaro.org>
(cherry picked from commit ec119972cb)
2024-08-01 21:10:08 +02:00
H.J. Lu 590e58b652 Add mremap tests
Add tests for MREMAP_MAYMOVE and MREMAP_FIXED.  On Linux, also test
MREMAP_DONTUNMAP.

Signed-off-by: H.J. Lu <hjl.tools@gmail.com>
Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit ff0320bec2)
2024-08-01 17:00:54 +02:00
H.J. Lu aaed1cc9fc mremap: Update manual entry
Update mremap manual entry:

1. Change mremap to variadic.
2. Document MREMAP_FIXED and MREMAP_DONTUNMAP.

Signed-off-by: H.J. Lu <hjl.tools@gmail.com>
Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit cb2dee4ecc)
2024-08-01 17:00:54 +02:00
H.J. Lu 40fb943e12 linux: Update the mremap C implementation [BZ #31968]
Update the mremap C implementation to support the optional argument for
MREMAP_DONTUNMAP added in Linux 5.7 since it may not always be correct
to implement a variadic function as a non-variadic function on all Linux
targets.  Return MAP_FAILED and set errno to EINVAL for unknown flag bits.
This fixes BZ #31968.

Note: A test must be added when a new flag bit is introduced.

Signed-off-by: H.J. Lu <hjl.tools@gmail.com>
Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit 6c40cb0e9f)
2024-08-01 17:00:54 +02:00
Frédéric Bérat 88b3554ed9 tests: replace system by xsystem
With fortification enabled, system calls return result needs to be checked,
has it gets the __wur macro enabled.
Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>

(cherry picked from commit 8022fc7d51)
2024-08-01 17:00:51 +02:00
Florian Weimer 708f507e30 resolv: Track single-request fallback via _res._flags (bug 31476)
This avoids changing _res.options, which inteferes with change
detection as part of automatic reloading of /etc/resolv.conf.

Reviewed-by: DJ Delorie <dj@redhat.com>
(cherry picked from commit 868ab8923a)
2024-07-24 15:11:36 +02:00
Florian Weimer 3da1b0064a resolv: Do not wait for non-existing second DNS response after error (bug 30081)
In single-request mode, there is no second response after an error
because the second query has not been sent yet.  Waiting for it
introduces an unnecessary timeout.

Reviewed-by: DJ Delorie <dj@redhat.com>
(cherry picked from commit af625987d6)
2024-07-24 14:08:04 +02:00
Florian Weimer 40a1e1798b resolv: Allow short error responses to match any query (bug 31890)
Reviewed-by: DJ Delorie <dj@redhat.com>
(cherry picked from commit 691a3b2e9b)
2024-07-24 14:07:32 +02:00
Florian Weimer 7f769dd008 Linux: Make __rseq_size useful for feature detection (bug 31965)
The __rseq_size value is now the active area of struct rseq
(so 20 initially), not the full struct size including padding
at the end (32 initially).

Update misc/tst-rseq to print some additional diagnostics.

Reviewed-by: Michael Jeanson <mjeanson@efficios.com>
Reviewed-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
(cherry picked from commit 2e456ccf0c)
2024-07-16 17:24:53 +02:00
Adhemerval Zanella 643709c6ee elf: Make dl-rseq-symbols Linux only
And avoid a Hurd build failures.

Checked on x86_64-linux-gnu.

(cherry picked from commit 9fc639f654)
2024-07-16 17:24:53 +02:00
Michael Jeanson a858172cf9 nptl: fix potential merge of __rseq_* relro symbols
While working on a patch to add support for the extensible rseq ABI, we
came across an issue where a new 'const' variable would be merged with
the existing '__rseq_size' variable. We tracked this to the use of
'-fmerge-all-constants' which allows the compiler to merge identical
constant variables. This means that all 'const' variables in a compile
unit that are of the same size and are initialized to the same value can
be merged.

In this specific case, on 32 bit systems 'unsigned int' and 'ptrdiff_t'
are both 4 bytes and initialized to 0 which should trigger the merge.
However for reasons we haven't delved into when the attribute 'section
(".data.rel.ro")' is added to the mix, only variables of the same exact
types are merged. As far as we know this behavior is not specified
anywhere and could change with a new compiler version, hence this patch.

Move the definitions of these variables into an assembler file and add
hidden writable aliases for internal use. This has the added bonus of
removing the asm workaround to set the values on rseq registration.

Tested on Debian 12 with GCC 12.2.

Signed-off-by: Michael Jeanson <mjeanson@efficios.com>
Reviewed-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Reviewed-by: Florian Weimer <fweimer@redhat.com>
(cherry picked from commit 2b92982e23)
2024-07-16 17:24:53 +02:00
Joseph Myers 182f4a8c75 Add AT_RSEQ_* from Linux 6.3 to elf.h
Linux 6.3 adds constants AT_RSEQ_FEATURE_SIZE and AT_RSEQ_ALIGN; add
them to glibc's elf.h.  (Recall that, although elf.h is a
system-independent header, so far we've put AT_* constants there even
if Linux-specific, as discussed in bug 15794.  So rather than making
any attempt to fix that issue, the new constants are just added there
alongside the existing ones.)

Tested for x86_64.

(cherry picked from commit 8754a4133e)
2024-07-16 17:24:53 +02:00
Stefan Liebler 340ca2d514 s390x: Fix segfault in wcsncmp [BZ #31934]
The z13/vector-optimized wcsncmp implementation segfaults if n=1
and there is only one character (equal on both strings) before
the page end.  Then it loads and compares one character and misses
to check n again.  The following load fails.

This patch removes the extra load and compare of the first character
and just start with the loop which uses vector-load-to-block-boundary.
This code-path also checks n.

With this patch both tests are passing:
- the simplified one mentioned in the bugzilla 31934
- the full one in Florian Weimer's patch:
"manual: Document a GNU extension for strncmp/wcsncmp"
(https://patchwork.sourceware.org/project/glibc/patch/874j9eml6y.fsf@oldenburg.str.redhat.com/):
On s390x-linux-gnu (z16), the new wcsncmp test fails due to bug 31934.
Reviewed-by: Carlos O'Donell <carlos@redhat.com>

(cherry picked from commit 9b76514103)
2024-07-16 10:29:56 +02:00
H.J. Lu 3956fd48d3 Force DT_RPATH for --enable-hardcoded-path-in-tests
On Fedora 40/x86-64, linker enables --enable-new-dtags by default which
generates DT_RUNPATH instead of DT_RPATH.  Unlike DT_RPATH, DT_RUNPATH
only applies to DT_NEEDED entries in the executable and doesn't applies
to DT_NEEDED entries in shared libraries which are loaded via DT_NEEDED
entries in the executable.  Some glibc tests have libstdc++.so.6 in
DT_NEEDED, which has libm.so.6 in DT_NEEDED.  When DT_RUNPATH is generated,
/lib64/libm.so.6 is loaded for such tests.  If the newly built glibc is
older than glibc 2.36, these tests fail with

assert/tst-assert-c++: /export/build/gnu/tools-build/glibc-gitlab-release/build-x86_64-linux/libc.so.6: version `GLIBC_2.36' not found (required by /lib64/libm.so.6)
assert/tst-assert-c++: /export/build/gnu/tools-build/glibc-gitlab-release/build-x86_64-linux/libc.so.6: version `GLIBC_ABI_DT_RELR' not found (required by /lib64/libm.so.6)

Pass -Wl,--disable-new-dtags to linker when building glibc tests with
--enable-hardcoded-path-in-tests.  This fixes BZ #31719.

Signed-off-by: H.J. Lu <hjl.tools@gmail.com>
(cherry picked from commit 2dcaf70643)
2024-05-10 05:05:42 -07:00
Adam Yi f4de99ea83 hurd: fix build of tst-system.c
We made tst-system.c depend on pthread, but that requires linking with
$(shared-thread-library). It does not fail under Linux because the
variable expands to nothing under Linux, but it fails for Hurd.

I tested verified via cross-compiling that "make check" now works
for Hurd.

Signed-off-by: Adam Yi <ayi@janestreet.com>
Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit d03094649d)
2024-05-02 19:20:08 +02:00
Florian Weimer 90304900c3 nscd: Use time_t for return type of addgetnetgrentX
Using int may give false results for future dates (timeouts after the
year 2028).

Fixes commit 04a21e050d64a1193a6daab872bca2528bda44b ("CVE-2024-33601,
CVE-2024-33602: nscd: netgroup: Use two buffers in addgetnetgrentX
(bug 31680)").

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit 4bbca1a446)
2024-05-02 19:05:10 +02:00
Florian Weimer 36ef0d2f2f login: structs utmp, utmpx, lastlog _TIME_BITS independence (bug 30701)
These structs describe file formats under /var/log, and should not
depend on the definition of _TIME_BITS.  This is achieved by
defining __WORDSIZE_TIME64_COMPAT32 to 1 on 32-bit ports that
support 32-bit time_t values (where __time_t is 32 bits).

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit 9abdae94c7)
2024-05-02 17:48:45 +02:00
Florian Weimer 2a41cb9c71 login: Check default sizes of structs utmp, utmpx, lastlog
The default <utmp-size.h> is for ports with a 64-bit time_t.
Ports with a 32-bit time_t or with __WORDSIZE_TIME64_COMPAT32=1
need to override it.

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit 4d4da5aab9)
2024-05-02 17:48:45 +02:00
Adhemerval Zanella bcd2bf36b4 sparc: Remove 64 bit check on sparc32 wordsize (BZ 27574)
The sparc32 is always 32 bits.

Checked on sparcv9-linux-gnu.

(cherry picked from commit dd57f5e7b6)
2024-05-02 17:48:45 +02:00
H.J. Lu 1aa819a693 elf: Also compile dl-misc.os with $(rtld-early-cflags)
Also compile dl-misc.os with $(rtld-early-cflags) to avoid

Program received signal SIGILL, Illegal instruction.
0x00007ffff7fd36ea in _dl_strtoul (nptr=nptr@entry=0x7fffffffe2c9 "2",
    endptr=endptr@entry=0x7fffffffd728) at dl-misc.c:156
156	  bool positive = true;
(gdb) bt
 #0  0x00007ffff7fd36ea in _dl_strtoul (nptr=nptr@entry=0x7fffffffe2c9 "2",
    endptr=endptr@entry=0x7fffffffd728) at dl-misc.c:156
 #1  0x00007ffff7fdb1a9 in tunable_initialize (
    cur=cur@entry=0x7ffff7ffbc00 <tunable_list+2176>,
    strval=strval@entry=0x7fffffffe2c9 "2", len=len@entry=1)
    at dl-tunables.c:131
 #2  0x00007ffff7fdb3a2 in parse_tunables (valstring=<optimized out>)
    at dl-tunables.c:258
 #3  0x00007ffff7fdb5d9 in __GI___tunables_init (envp=0x7fffffffdd58)
    at dl-tunables.c:288
 #4  0x00007ffff7fe44c3 in _dl_sysdep_start (
    start_argptr=start_argptr@entry=0x7fffffffdcb0,
    dl_main=dl_main@entry=0x7ffff7fe5f80 <dl_main>)
    at ../sysdeps/unix/sysv/linux/dl-sysdep.c:110
 #5  0x00007ffff7fe5cae in _dl_start_final (arg=0x7fffffffdcb0) at rtld.c:494
 #6  _dl_start (arg=0x7fffffffdcb0) at rtld.c:581
 #7  0x00007ffff7fe4b38 in _start ()
(gdb)

when setting GLIBC_TUNABLES in glibc compiled with APX.
Reviewed-by: Florian Weimer <fweimer@redhat.com>

(cherry picked from commit 049b7684c9)
2024-04-25 08:21:54 -07:00
Florian Weimer 6e106dc214 CVE-2024-33601, CVE-2024-33602: nscd: netgroup: Use two buffers in addgetnetgrentX (bug 31680)
This avoids potential memory corruption when the underlying NSS
callback function does not use the buffer space to store all strings
(e.g., for constant strings).

Instead of custom buffer management, two scratch buffers are used.
This increases stack usage somewhat.

Scratch buffer allocation failure is handled by return -1
(an invalid timeout value) instead of terminating the process.
This fixes bug 31679.

Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit c04a21e050)
2024-04-25 15:40:34 +02:00
Florian Weimer a8070b3104 CVE-2024-33600: nscd: Avoid null pointer crashes after notfound response (bug 31678)
The addgetnetgrentX call in addinnetgrX may have failed to produce
a result, so the result variable in addinnetgrX can be NULL.
Use db->negtimeout as the fallback value if there is no result data;
the timeout is also overwritten below.

Also avoid sending a second not-found response.  (The client
disconnects after receiving the first response, so the data stream did
not go out of sync even without this fix.)  It is still beneficial to
add the negative response to the mapping, so that the client can get
it from there in the future, instead of going through the socket.

Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit b048a482f0)
2024-04-25 15:40:34 +02:00
Florian Weimer 5eea50c440 CVE-2024-33600: nscd: Do not send missing not-found response in addgetnetgrentX (bug 31678)
If we failed to add a not-found response to the cache, the dataset
point can be null, resulting in a null pointer dereference.

Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit 7835b00dbc)
2024-04-25 15:40:34 +02:00
Florian Weimer f75c298e74 CVE-2024-33599: nscd: Stack-based buffer overflow in netgroup cache (bug 31677)
Using alloca matches what other caches do.  The request length is
bounded by MAXKEYLEN.

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit 87801a8fd0)
2024-04-25 15:40:34 +02:00
Florian Weimer ae014a15b4 nptl: Fix tst-cancel30 on kernels without ppoll_time64 support
Fall back to ppoll if ppoll_time64 fails with ENOSYS.
Fixes commit 370da8a121 ("nptl: Fix
tst-cancel30 on sparc64").

Reviewed-by: Adhemerval Zanella <adhemerval.zanella@linaro.org>
(cherry picked from commit f4724843ad)
2024-04-23 21:20:40 +02:00
Charles FolandAdhemerval Zanella 89ce64b269 iconv: ISO-2022-CN-EXT: fix out-of-bound writes when writing escape sequence (CVE-2024-2961)
ISO-2022-CN-EXT uses escape sequences to indicate character set changes
(as specified by RFC 1922).  While the SOdesignation has the expected
bounds checks, neither SS2designation nor SS3designation have its;
allowing a write overflow of 1, 2, or 3 bytes with fixed values:
'$+I', '$+J', '$+K', '$+L', '$+M', or '$*H'.

Checked on aarch64-linux-gnu.

Co-authored-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
Reviewed-by: Carlos O'Donell <carlos@redhat.com>
Tested-by: Carlos O'Donell <carlos@redhat.com>

(cherry picked from commit f9dc609e06)
2024-04-17 14:04:51 -03:00
Florian Weimer 6eab323a3c powerpc: Fix ld.so address determination for PCREL mode (bug 31640)
This seems to have stopped working with some GCC 14 versions,
which clobber r2.  With other compilers, the kernel-provided
r2 value is still available at this point.

Reviewed-by: Peter Bergner <bergner@linux.ibm.com>
(cherry picked from commit 14e56bd4ce)
2024-04-14 09:11:12 +02:00
Wilco Dijkstra fb8f66c22d AArch64: Check kernel version for SVE ifuncs
Old Linux kernels disable SVE after every system call.  Calling the
SVE-optimized memcpy afterwards will then cause a trap to reenable SVE.
As a result, applications with a high use of syscalls may run slower with
the SVE memcpy.  This is true for kernels between 4.15.0 and before 6.2.0,
except for 5.14.0 which was patched.  Avoid this by checking the kernel
version and selecting the SVE ifunc on modern kernels.

Parse the kernel version reported by uname() into a 24-bit kernel.major.minor
value without calling any library functions.  If uname() is not supported or
if the version format is not recognized, assume the kernel is modern.

Tested-by: Florian Weimer <fweimer@redhat.com>
Reviewed-by: Szabolcs Nagy <szabolcs.nagy@arm.com>
(cherry picked from commit 2e94e2f5d2)
2024-04-08 16:26:21 +01:00
Szabolcs Nagy bbc290aad4 aarch64: fix check for SVE support in assembler
Due to GCC bug 110901 -mcpu can override -march setting when compiling
asm code and thus a compiler targetting a specific cpu can fail the
configure check even when binutils gas supports SVE.

The workaround is that explicit .arch directive overrides both -mcpu
and -march, and since that's what the actual SVE memcpy uses the
configure check should use that too even if the GCC issue is fixed
independently.

Reviewed-by: Florian Weimer <fweimer@redhat.com>
(cherry picked from commit 73c26018ed)
2024-04-08 16:25:05 +01:00
Andreas Schwab 882b7dc2ab aarch64: correct CFI in rawmemchr (bug 31113)
The .cfi_return_column directive changes the return column for the whole
FDE range.  But the actual intent is to tell the unwinder that the value
in x30 (lr) now resides in x15 after the move, and that is expressed by
the .cfi_register directive.

(cherry picked from commit 3f79842788)
2024-04-08 16:24:55 +01:00
Wilco Dijkstra 3dcb8fde81 AArch64: Remove Falkor memcpy
The latest implementations of memcpy are actually faster than the Falkor
implementations [1], so remove the falkor/phecda ifuncs for memcpy and
the now unused IS_FALKOR/IS_PHECDA defines.

[1] https://sourceware.org/pipermail/libc-alpha/2022-December/144227.html

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit 2f5524cc53)
2024-04-08 16:24:41 +01:00
Wilco Dijkstra cb48c2603a AArch64: Add memset_zva64
Add a specialized memset for the common ZVA size of 64 to avoid the
overhead of reading the ZVA size.  Since the code is identical to
__memset_falkor, remove the latter.

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit 3d7090f14b)
2024-04-08 16:24:27 +01:00
Wilco Dijkstra 455b1b2b7f AArch64: Cleanup emag memset
Cleanup emag memset - merge the memset_base64.S file, remove
the unused ZVA code (since it is disabled on emag).

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit 9627ab99b5)
2024-04-08 16:23:55 +01:00
Wilco Dijkstra e7f8117b60 AArch64: Cleanup ifuncs
Cleanup ifuncs.  Remove uses of libc_hidden_builtin_def, use ENTRY rather than
ENTRY_ALIGN, remove unnecessary defines and conditional compilation.  Rename
strlen_mte to strlen_generic.  Remove rtld-memset.

Reviewed-by: Szabolcs Nagy <szabolcs.nagy@arm.com>
(cherry picked from commit 9fd3409842)
2024-04-08 16:22:54 +01:00
Wilco Dijkstra 4c3985b4c8 AArch64: Add support for MOPS memcpy/memmove/memset
Add support for MOPS in cpu_features and INIT_ARCH.  Add ifuncs using MOPS for
memcpy, memmove and memset (use .inst for now so it works with all binutils
versions without needing complex configure and conditional compilation).

Reviewed-by: Szabolcs Nagy <szabolcs.nagy@arm.com>
(cherry picked from commit 2bd0017988)
2024-04-08 16:21:59 +01:00
Joseph Myers d0da4fb615 Add HWCAP2_MOPS from Linux 6.5 to AArch64 bits/hwcap.h
Linux 6.5 adds a new AArch64 HWCAP2 value, HWCAP2_MOPS.  Add it to
glibc's bits/hwcap.h.

Tested with build-many-glibcs.py for aarch64-linux-gnu.

(cherry picked from commit ff5d2abd18)
2024-04-08 16:21:42 +01:00
Wilco Dijkstra 314b731dd8 AArch64: Improve SVE memcpy and memmove
Improve SVE memcpy by copying 2 vectors if the size is small enough.
This improves performance of random memcpy by ~9% on Neoverse V1, and
33-64 byte copies are ~16% faster.

Reviewed-by: Szabolcs Nagy <szabolcs.nagy@arm.com>
(cherry picked from commit d2d3f3720c)
2024-04-08 16:21:08 +01:00
caiyinyu 6f28bfa4a0 LoongArch: Correct {__ieee754, _}_scalb -> {__ieee754, _}_scalbf 2024-03-22 09:30:39 +08:00
Florian Weimer 829b64598b linux: Use rseq area unconditionally in sched_getcpu (bug 31479)
Originally, nptl/descr.h included <sys/rseq.h>, but we removed that
in commit 2c6b4b272e ("nptl:
Unconditionally use a 32-byte rseq area").  After that, it was
not ensured that the RSEQ_SIG macro was defined during sched_getcpu.c
compilation that provided a definition.  This commit always checks
the rseq area for CPU number information before using the other
approaches.

This adds an unnecessary (but well-predictable) branch on
architectures which do not define RSEQ_SIG, but its cost is small
compared to the system call.  Most architectures that have vDSO
acceleration for getcpu also have rseq support.

Fixes: 2c6b4b272e
Fixes: 1d350aa060
Reviewed-by: Arjun Shankar <arjun@redhat.com>
(cherry picked from commit 7a76f21867)
Fixes: 9da8174362
2024-03-18 18:12:03 +01:00
Stefan Liebler a11c8d521d Include sys/rseq.h in tst-rseq-disable.c
Starting with commit 2c6b4b272e
"nptl: Unconditionally use a 32-byte rseq area", the testcase
misc/tst-rseq-disable is UNSUPPORTED as RSEQ_SIG is not defined.

The mentioned commit removes inclusion of sys/rseq.h in nptl/descr.h.
Thus just include sys/rseq.h in the tst-rseq-disable.c as also done
in tst-rseq.c and tst-rseq-nptl.c.
Reviewed-by: Florian Weimer <fweimer@redhat.com>

(cherry picked from commit 637aac2ae3)
2024-03-18 18:12:03 +01:00
Florian Weimer 9da8174362 nptl: Unconditionally use a 32-byte rseq area
If the kernel headers provide a larger struct rseq, we used that
size as the argument to the rseq system call.  As a result,
rseq registration would fail on older kernels which only accept
size 32.

(cherry picked from commit 2c6b4b272e)
2024-03-18 11:41:39 +01:00
Paul Eggert 08ac41cf08 make ‘struct pthread’ a complete type
* nptl/descr.h (struct pthread): Remove end_padding member, which
made this type incomplete.
(PTHREAD_STRUCT_END_PADDING): Stop using end_padding.

Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit 3edc4ff2ce)
2024-03-18 11:41:35 +01:00
Andreas Schwab 2fadb0d9b4 support: use 64-bit time_t (bug 30111)
Ensure to use 64-bit time_t in the test infrastructure.

(cherry picked from commit 3bfdc4e2bc)
2024-03-12 15:51:56 -03:00
Stefan Liebler 9a1bdd7df7 S390: Do not clobber r7 in clone [BZ #31402]
Starting with commit e57d8fc97b
"S390: Always use svc 0"
clone clobbers the call-saved register r7 in error case:
function or stack is NULL.

This patch restores the saved registers also in the error case.
Furthermore the existing test misc/tst-clone is extended to check
all error cases and that clone does not clobber registers in this
error case.

(cherry picked from commit 02782fd128)
Note: Added ia64 __clone2 call to tst-clone.c.
2024-02-27 11:05:29 +01:00
Adhemerval Zanella 23021eda75 malloc: Use __get_nprocs on arena_get2 (BZ 30945)
This restore the 2.33 semantic for arena_get2.  It was changed by
11a02b035b to avoid arena_get2 call malloc (back when __get_nproc
was refactored to use an scratch_buffer - 903bc7dcc2).  The
__get_nproc was refactored over then and now it also avoid to call
malloc.

The 11a02b035b did not take in consideration any performance
implication, which should have been discussed properly.  The
__get_nprocs_sched is still used as a fallback mechanism if procfs
and sysfs is not acessible.

Checked on x86_64-linux-gnu.
Reviewed-by: DJ Delorie <dj@redhat.com>

(cherry picked from commit 472894d2cf)
2024-02-12 09:56:44 -03:00
Adhemerval Zanella eee7525d35 arm: Remove wrong ldr from _dl_start_user (BZ 31339)
The commit 49d877a80b (arm: Remove
_dl_skip_args usage) removed the _SKIP_ARGS literal, which was
previously loader to r4 on loader _start.  However, the cleanup did not
remove the following 'ldr r4, [sl, r4]' on _dl_start_user, used to check
to skip the arguments after ld self-relocations.

In my testing, the kernel initially set r4 to 0, which makes the
ldr instruction just read the _GLOBAL_OFFSET_TABLE_.  However, since r4
is a callee-saved register; a different runtime might not zero
initialize it and thus trigger an invalid memory access.

Checked on arm-linux-gnu.

Reported-by: Adrian Ratiu <adrian.ratiu@collabora.com>
Reviewed-by: Szabolcs Nagy <szabolcs.nagy@arm.com>
(cherry picked from commit 1e25112dc0)
2024-02-05 15:43:27 -03:00
Daniel Cederman 8b849f70b3 sparc: Remove unwind information from signal return stubs [BZ #31244]
The functions were previously written in C, but were not compiled
with unwind information. The ENTRY/END macros includes .cfi_startproc
and .cfi_endproc which adds unwind information. This caused the
tests cleanup-8 and cleanup-10 in the GCC testsuite to fail.
This patch adds a version of the ENTRY/END macros without the
CFI instructions that can be used instead.

sigaction registers a restorer address that is located two instructions
before the stub function. This patch adds a two instruction padding to
avoid that the unwinder accesses the unwind information from the function
that the linker has placed right before it in memory. This fixes an issue
with pthread_cancel that caused tst-mutex8-static (and other tests) to fail.

Signed-off-by: Daniel Cederman <cederman@gaisler.com>
Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>

(cherry picked from commit 7bd06985c0)
2024-02-02 09:49:58 -03:00
Adhemerval Zanella 18da90677c sparc: Fix sparc64 memmove length comparison (BZ 31266)
The small counts copy bytes comparsion should be unsigned (as the
memmove size argument).  It fixes string/tst-memmove-overflow on
sparcv9, where the input size triggers an invalid code path.

Checked on sparc64-linux-gnu and sparcv9-linux-gnu.

(cherry picked from commit 926a4bdbb5)
2024-02-02 09:29:59 -03:00
Adhemerval Zanella 2ce7abef67 sparc64: Remove unwind information from signal return stubs [BZ#31244]
Similar to sparc32 fix, remove the unwind information on the signal
return stubs.  This fixes the regressions:

FAIL: nptl/tst-cancel24-static
FAIL: nptl/tst-cond8-static
FAIL: nptl/tst-mutex8-static
FAIL: nptl/tst-mutexpi8-static
FAIL: nptl/tst-mutexpi9

On sparc64-linux-gnu.

(cherry picked from commit 369efd8177)
2024-02-02 09:29:50 -03:00
Andreas Larsson 98ec3e004e sparc: Fix broken memset for sparc32 [BZ #31068]
Fixes commit a61933fe27 ("sparc: Remove bzero optimization") that
after moving code jumped to the wrong label 4.

Verfied by successfully running string/test-memset on sparc32.

Signed-off-by: Andreas Larsson <andreas@gaisler.com>
Signed-off-by: Ludwig Rydberg <ludwig.rydberg@gaisler.com>
Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit 578190b7e4)
2024-02-01 17:45:49 -03:00
Sunil K Pandey 5bbe7e0da5 x86_64: Optimize ffsll function code size.
Ffsll function randomly regress by ~20%, depending on how code gets
aligned in memory.  Ffsll function code size is 17 bytes.  Since default
function alignment is 16 bytes, it can load on 16, 32, 48 or 64 bytes
aligned memory.  When ffsll function load at 16, 32 or 64 bytes aligned
memory, entire code fits in single 64 bytes cache line.  When ffsll
function load at 48 bytes aligned memory, it splits in two cache line,
hence random regression.

Ffsll function size reduction from 17 bytes to 12 bytes ensures that it
will always fit in single 64 bytes cache line.

This patch fixes ffsll function random performance regression.

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit 9d94997b5f)
2024-01-31 18:42:43 -08:00
Sam James d97929eadc sysdeps: tst-bz21269: fix -Wreturn-type
Thanks to Andreas Schwab for reporting.

Fixes: 652b9fdb77
Signed-off-by: Sam James <sam@gentoo.org>
(cherry picked from commit 369f373057)
2024-01-31 10:59:09 +01:00
Sam James f7e97cea20 sysdeps: tst-bz21269: handle ENOSYS & skip appropriately
SYS_modify_ldt requires CONFIG_MODIFY_LDT_SYSCALL to be set in the kernel, which
some distributions may disable for hardening. Check if that's the case (unset)
and mark the test as UNSUPPORTED if so.

Reviewed-by: DJ Delorie <dj@redhat.com>
Signed-off-by: Sam James <sam@gentoo.org>
(cherry picked from commit 652b9fdb77)
2024-01-31 10:59:09 +01:00
Sam James 32450f6e8d sysdeps: tst-bz21269: fix test parameter
All callers pass 1 or 0x11 anyway (same meaning according to man page),
but still.

Reviewed-by: DJ Delorie <dj@redhat.com>
Signed-off-by: Sam James <sam@gentoo.org>
(cherry picked from commit e0b712dd91)
2024-01-31 10:59:09 +01:00
DJ Delorie 1d8bb622df i386: Use pthread_barrier for synchronization on tst-bz21269
So I was able to reproduce the hangs in the original source, and debug
it, and fix it.  In doing so, I realized that we can't use anything
complex to trigger the thread because that "anything" might also cause
the expected segfault and force everything out of sync again.

Here's what I ended up with, and it doesn't seem to hang where the
original one hung quite often (in a tight while..end loop).  The key
changes are:

1. Calls to futex are error checked, with retries, to ensure that the
   futexes are actually doing what they're supposed to be doing.  In the
   original code, nearly every futex call returned an error.

2. The main loop has checks for whether the thread ran or not, and
   "unlocks" the thread if it didn't (this is how the original source
   hangs).

Note: the usleep() is not for timing purposes, but just to give the
kernel an excuse to run the other thread at that time.  The test will
not hang without it, but is more likely to test the right bugfix
if the usleep() is present.

(cherry picked from commit 088136aa02)
2024-01-31 10:59:09 +01:00
Arjun Shankar 2b58cba076 syslog: Fix integer overflow in __vsyslog_internal (CVE-2023-6780)
__vsyslog_internal calculated a buffer size by adding two integers, but
did not first check if the addition would overflow.  This commit fixes
that.

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
Tested-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit ddf542da94)
2024-01-30 15:56:17 +01:00
Arjun Shankar 67062eccd9 syslog: Fix heap buffer overflow in __vsyslog_internal (CVE-2023-6779)
__vsyslog_internal used the return value of snprintf/vsnprintf to
calculate buffer sizes for memory allocation.  If these functions (for
any reason) failed and returned -1, the resulting buffer would be too
small to hold output.  This commit fixes that.

All snprintf/vsnprintf calls are checked for negative return values and
the function silently returns upon encountering them.

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit 7e5a0c286d)
2024-01-30 15:56:17 +01:00
Arjun Shankar 97a4292aa4 syslog: Fix heap buffer overflow in __vsyslog_internal (CVE-2023-6246)
__vsyslog_internal did not handle a case where printing a SYSLOG_HEADER
containing a long program name failed to update the required buffer
size, leading to the allocation and overflow of a too-small buffer on
the heap.  This commit fixes that.  It also adds a new regression test
that uses glibc.malloc.check.

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
Reviewed-by: Carlos O'Donell <carlos@redhat.com>
Tested-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit 6bd0e4efcc)
2024-01-30 15:56:17 +01:00
Adhemerval Zanella Netto 8b8a3f0aaf sunrpc: Fix netname build with older gcc
The -Wformat-overflow was added by gcc 8.
Reviewed-by: Carlos O'Donell <carlos@redhat.com>

(cherry picked from commit 0eb6b2725b)
2024-01-29 22:22:40 +01:00
Florian Weimer bd9f194c34 libio: Check remaining buffer size in _IO_wdo_write (bug 31183)
The multibyte character needs to fit into the remaining buffer space,
not the already-written buffer space.  Without the fix, we were never
moving the write pointer from the start of the buffer, always using
the single-character fallback buffer.

Fixes commit 04b76b5aa8 ("Don't error out writing
a multibyte character to an unbuffered stream (bug 17522)").

(cherry picked from commit ecc7c3deb9)
2024-01-02 14:39:31 +01:00
Andreas Schwab 9b90e763db getaddrinfo: translate ENOMEM to EAI_MEMORY (bug 31163)
When __resolv_context_get returns NULL due to out of memory, translate it
to a return value of EAI_MEMORY.

(cherry picked from commit 5eabdb6a6a)
2024-01-02 14:39:17 +01:00
H.J. Lu 0ca9ba3a9e NEWS: Mention bug fixes for 29039/30745/30843 2023-12-23 06:46:22 -08:00
H.J. Lu d052665f35 x86-64: Fix the tcb field load for x32 [BZ #31185]
_dl_tlsdesc_undefweak and _dl_tlsdesc_dynamic access the thread pointer
via the tcb field in TCB:

_dl_tlsdesc_undefweak:
        _CET_ENDBR
        movq    8(%rax), %rax
        subq    %fs:0, %rax
        ret

_dl_tlsdesc_dynamic:
	...
        subq    %fs:0, %rax
        movq    -8(%rsp), %rdi
        ret

Since the tcb field in TCB is a pointer, %fs:0 is a 32-bit location,
not 64-bit. It should use "sub %fs:0, %RAX_LP" instead.  Since
_dl_tlsdesc_undefweak returns ptrdiff_t and _dl_make_tlsdesc_dynamic
returns void *, RAX_LP is appropriate here for x32 and x86-64.  This
fixes BZ #31185.

(cherry picked from commit 81be2a61da)
2023-12-23 06:42:26 -08:00
H.J. Lu 8bd00f5b6d x86-64: Fix the dtv field load for x32 [BZ #31184]
On x32, I got

FAIL: elf/tst-tlsgap

$ gdb elf/tst-tlsgap
...
open tst-tlsgap-mod1.so

Thread 2 "tst-tlsgap" received signal SIGSEGV, Segmentation fault.
[Switching to LWP 2268754]
_dl_tlsdesc_dynamic () at ../sysdeps/x86_64/dl-tlsdesc.S:108
108		movq	(%rsi), %rax
(gdb) p/x $rsi
$4 = 0xf7dbf9005655fb18
(gdb)

This is caused by

_dl_tlsdesc_dynamic:
        _CET_ENDBR
        /* Preserve call-clobbered registers that we modify.
           We need two scratch regs anyway.  */
        movq    %rsi, -16(%rsp)
        movq    %fs:DTV_OFFSET, %rsi

Since the dtv field in TCB is a pointer, %fs:DTV_OFFSET is a 32-bit
location, not 64-bit.  Load the dtv field to RSI_LP instead of rsi.
This fixes BZ #31184.

(cherry picked from commit 3502440397)
2023-12-23 06:40:53 -08:00
Hector Martin 874d418697 elf: Fix TLS modid reuse generation assignment (BZ 29039)
_dl_assign_tls_modid() assigns a slotinfo entry for a new module, but
does *not* do anything to the generation counter. The first time this
happens, the generation is zero and map_generation() returns the current
generation to be used during relocation processing. However, if
a slotinfo entry is later reused, it will already have a generation
assigned. If this generation has fallen behind the current global max
generation, then this causes an obsolete generation to be assigned
during relocation processing, as map_generation() returns this
generation if nonzero. _dl_add_to_slotinfo() eventually resets the
generation, but by then it is too late. This causes DTV updates to be
skipped, leading to NULL or broken TLS slot pointers and segfaults.

Fix this by resetting the generation to zero in _dl_assign_tls_modid(),
so it behaves the same as the first time a slot is assigned.
_dl_add_to_slotinfo() will still assign the correct static generation
later during module load, but relocation processing will no longer use
an obsolete generation.

Note that slotinfo entry (aka modid) reuse typically happens after a
dlclose and only TLS access via dynamic tlsdesc is affected. Because
tlsdesc is optimized to use the optional part of static TLS, dynamic
tlsdesc can be avoided by increasing the glibc.rtld.optional_static_tls
tunable to a large enough value, or by LD_PRELOAD-ing the affected
modules.

Fixes bug 29039.

Reviewed-by: Szabolcs Nagy <szabolcs.nagy@arm.com>
(cherry picked from commit 3921c5b40f)
2023-12-22 14:37:46 +00:00
Adhemerval Zanella 5014fb12f4 elf: Fix wrong break removal from 8ee878592c
Reported-by: Alexander Monakov <amonakov@ispras.ru>
(cherry picked from commit 546a1ba664)
2023-12-07 11:20:56 -03:00
Florian Weimer 8e20aedfd7 Revert "elf: Move l_init_called_next to old place of l_text_end in link map"
This reverts commit 1a7cbe52c8.

Reason for revert: Preserve internal ABI.
2023-10-19 09:21:12 +02:00
Florian Weimer 55d3dfadf8 Revert "elf: Always call destructors in reverse constructor order (bug 30785)"
This reverts commit a7e34a6675.

Reason for revert: Incompatibility with existing applications.
2023-10-18 14:28:07 +02:00
Florian Weimer 512e30fd56 Revert "elf: Remove unused l_text_end field from struct link_map"
This reverts commit bdb594afa5.

Reason for revert: Preserve ABI after revert of commit a7e34a6675.
2023-10-18 14:27:31 +02:00
Siddhesh Poyarekar b4e23c75ae tunables: Terminate if end of input is reached (CVE-2023-4911)
The string parsing routine may end up writing beyond bounds of tunestr
if the input tunable string is malformed, of the form name=name=val.
This gets processed twice, first as name=name=val and next as name=val,
resulting in tunestr being name=name=val:name=val, thus overflowing
tunestr.

Terminate the parsing loop at the first instance itself so that tunestr
does not overflow.

This also fixes up tst-env-setuid-tunables to actually handle failures
correct and add new tests to validate the fix for this CVE.

Signed-off-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
Reviewed-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit 1056e5b4c3)
2023-10-02 15:39:10 -04:00
Andreas K. Hüttel 2dfd8c77b5 i686: Regenerate ulps
Linux dilfridge-amd64-stable 6.1.41-gentoo-dist #1 SMP PREEMPT_DYNAMIC Tue Jul 25 09:26:34 -00 2023 x86_64 AMD Ryzen 7 3700X 8-Core Processor AuthenticAMD GNU/Linux
32bit build on x86-64

Signed-off-by: Andreas K. Hüttel <dilfridge@gentoo.org>
2023-09-29 22:17:33 +02:00
Siddhesh Poyarekar 94ef701365 Document CVE-2023-4806 and CVE-2023-5156 in NEWS
These are tracked in BZ #30884 and BZ #30843.

Signed-off-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit fd134feba3)
2023-09-26 12:39:36 -04:00
Romain Geissler 4473d1b87d Fix leak in getaddrinfo introduced by the fix for CVE-2023-4806 [BZ #30843]
This patch fixes a very recently added leak in getaddrinfo.

This was assigned CVE-2023-5156.

Resolves: BZ #30884
Related: BZ #30842

Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit ec6b95c330)
2023-09-26 12:39:28 -04:00
Sajan Karumanchi 9d5c6e27ed x86: Fix for cache computation on AMD legacy cpus.
Some legacy AMD CPUs and hypervisors have the _cpuid_ '0x8000_001D'
set to Zero, thus resulting in zeroed-out computed cache values.
This patch reintroduces the old way of cache computation as a
fail-safe option to handle these exceptions.
Fixed 'level4_cache_size' value through handle_amd().

Reviewed-by: Premachandra Mallappa <premachandra.mallappa@amd.com>
Tested-by: Florian Weimer <fweimer@redhat.com>
(cherry picked from commit dcad5c8578)
2023-09-26 08:48:01 +02:00
Andreas Schwab 79310b45af x86/dl-cacheinfo: remove unsused parameter from handle_amd
Also replace an unreachable assert with __builtin_unreachable.

(cherry picked from commit 856bab7717)
2023-09-26 08:44:58 +02:00
Siddhesh Poyarekar 6529a7466c getaddrinfo: Fix use after free in getcanonname (CVE-2023-4806)
When an NSS plugin only implements the _gethostbyname2_r and
_getcanonname_r callbacks, getaddrinfo could use memory that was freed
during tmpbuf resizing, through h_name in a previous query response.

The backing store for res->at->name when doing a query with
gethostbyname3_r or gethostbyname2_r is tmpbuf, which is reallocated in
gethosts during the query.  For AF_INET6 lookup with AI_ALL |
AI_V4MAPPED, gethosts gets called twice, once for a v6 lookup and second
for a v4 lookup.  In this case, if the first call reallocates tmpbuf
enough number of times, resulting in a malloc, th->h_name (that
res->at->name refers to) ends up on a heap allocated storage in tmpbuf.
Now if the second call to gethosts also causes the plugin callback to
return NSS_STATUS_TRYAGAIN, tmpbuf will get freed, resulting in a UAF
reference in res->at->name.  This then gets dereferenced in the
getcanonname_r plugin call, resulting in the use after free.

Fix this by copying h_name over and freeing it at the end.  This
resolves BZ #30843, which is assigned CVE-2023-4806.

Signed-off-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit 973fe93a56)
2023-09-15 15:20:22 -04:00
Florian Weimer b752934602 CVE-2023-4527: Stack read overflow with large TCP responses in no-aaaa mode
Without passing alt_dns_packet_buffer, __res_context_search can only
store 2048 bytes (what fits into dns_packet_buffer).  However,
the function returns the total packet size, and the subsequent
DNS parsing code in _nss_dns_gethostbyname4_r reads beyond the end
of the stack-allocated buffer.

Fixes commit f282cdbe7f ("resolv: Implement no-aaaa
stub resolver option") and bug 30842.

(cherry picked from commit bd77dd7e73)
2023-09-13 14:15:22 +02:00
Florian Weimer 1a7cbe52c8 elf: Move l_init_called_next to old place of l_text_end in link map
This preserves all member offsets and the GLIBC_PRIVATE ABI
for backporting.
2023-09-11 09:31:22 +02:00
Florian Weimer bdb594afa5 elf: Remove unused l_text_end field from struct link_map
It is a left-over from commit 52a01100ad
("elf: Remove ad-hoc restrictions on dlopen callers [BZ #22787]").

When backporting commmit 6985865bc3
("elf: Always call destructors in reverse constructor order
(bug 30785)"), we can move the l_init_called_next field to this
place, so that the internal GLIBC_PRIVATE ABI does not change.

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
Tested-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit 53df2ce688)
2023-09-11 09:31:22 +02:00
Florian Weimer a7e34a6675 elf: Always call destructors in reverse constructor order (bug 30785)
The current implementation of dlclose (and process exit) re-sorts the
link maps before calling ELF destructors.  Destructor order is not the
reverse of the constructor order as a result: The second sort takes
relocation dependencies into account, and other differences can result
from ambiguous inputs, such as cycles.  (The force_first handling in
_dl_sort_maps is not effective for dlclose.)  After the changes in
this commit, there is still a required difference due to
dlopen/dlclose ordering by the application, but the previous
discrepancies went beyond that.

A new global (namespace-spanning) list of link maps,
_dl_init_called_list, is updated right before ELF constructors are
called from _dl_init.

In dl_close_worker, the maps variable, an on-stack variable length
array, is eliminated.  (VLAs are problematic, and dlclose should not
call malloc because it cannot readily deal with malloc failure.)
Marking still-used objects uses the namespace list directly, with
next and next_idx replacing the done_index variable.

After marking, _dl_init_called_list is used to call the destructors
of now-unused maps in reverse destructor order.  These destructors
can call dlopen.  Previously, new objects do not have l_map_used set.
This had to change: There is no copy of the link map list anymore,
so processing would cover newly opened (and unmarked) mappings,
unloading them.  Now, _dl_init (indirectly) sets l_map_used, too.
(dlclose is handled by the existing reentrancy guard.)

After _dl_init_called_list traversal, two more loops follow.  The
processing order changes to the original link map order in the
namespace.  Previously, dependency order was used.  The difference
should not matter because relocation dependencies could already
reorder link maps in the old code.

The changes to _dl_fini remove the sorting step and replace it with
a traversal of _dl_init_called_list.  The l_direct_opencount
decrement outside the loader lock is removed because it appears
incorrect: the counter manipulation could race with other dynamic
loader operations.

tst-audit23 needs adjustments to the changes in LA_ACT_DELETE
notifications.  The new approach for checking la_activity should
make it clearer that la_activty calls come in pairs around namespace
updates.

The dependency sorting test cases need updates because the destructor
order is always the opposite order of constructor order, even with
relocation dependencies or cycles present.

There is a future cleanup opportunity to remove the now-constant
force_first and for_fini arguments from the _dl_sort_maps function.

Fixes commit 1df71d32fe ("elf: Implement
force_first handling in _dl_sort_maps_dfs (bug 28937)").

Reviewed-by: DJ Delorie <dj@redhat.com>
(cherry picked from commit 6985865bc3)
2023-09-11 09:31:16 +02:00
Florian Weimer 3d24d1903d elf: Do not run constructors for proxy objects
Otherwise, the ld.so constructor runs for each audit namespace
and each dlmopen namespace.

(cherry picked from commit f6c8204fd7)
2023-09-11 09:30:44 +02:00
Aurelien Jarno be26b29262 io: Fix record locking contants for powerpc64 with __USE_FILE_OFFSET64
Commit 5f828ff824 ("io: Fix F_GETLK, F_SETLK, and F_SETLKW for
powerpc64") fixed an issue with the value of the lock constants on
powerpc64 when not using __USE_FILE_OFFSET64, but it ended-up also
changing the value when using __USE_FILE_OFFSET64 causing an API change.

Fix that by also checking that define, restoring the pre
4d0fe291ae commit values:

Default values:
- F_GETLK: 5
- F_SETLK: 6
- F_SETLKW: 7

With -D_FILE_OFFSET_BITS=64:
- F_GETLK: 12
- F_SETLK: 13
- F_SETLKW: 14

At the same time, it has been noticed that there was no test for io lock
with __USE_FILE_OFFSET64, so just add one.

Tested on x86_64-linux-gnu, i686-linux-gnu and
powerpc64le-unknown-linux-gnu.

Resolves: BZ #30804.
Co-authored-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
Signed-off-by: Aurelien Jarno <aurelien@aurel32.net>
(cherry picked from commit 434bf72a94)
2023-09-07 22:52:30 +02:00
Sergey Bugaev 0d500bfdc0 hurd: Make exception subcode a long
On EXC_BAD_ACCESS, exception subcode is used to pass the faulting memory
address, so it needs to be (at least) pointer-sized. Thus, make it into
a long. This matches the corresponding change in GNU Mach.
Message-Id: <20230319151017.531737-5-bugaevc@gmail.com>

(cherry picked from commit d8ee5d614b)
2023-08-29 23:17:58 +02:00
Noah Goldstein f94ff95e93 x86: Fix incorrect scope of setting shared_per_thread [BZ# 30745]
The:

```
    if (shared_per_thread > 0 && threads > 0)
      shared_per_thread /= threads;
```

Code was accidentally moved to inside the else scope.  This doesn't
match how it was previously (before af992e7abd).

This patch fixes that by putting the division after the `else` block.

(cherry picked from commit 084fb31bc2)
2023-08-28 15:02:19 -05:00
Noah Goldstein cc8243fb0b x86: Use 3/4*sizeof(per-thread-L3) as low bound for NT threshold.
On some machines we end up with incomplete cache information. This can
make the new calculation of `sizeof(total-L3)/custom-divisor` end up
lower than intended (and lower than the prior value). So reintroduce
the old bound as a lower bound to avoid potentially regressing code
where we don't have complete information to make the decision.
Reviewed-by: DJ Delorie <dj@redhat.com>

(cherry picked from commit 8b9a0af8ca)
2023-08-28 15:02:18 -05:00
Noah Goldstein 80a8c858a5 x86: Fix slight bug in shared_per_thread cache size calculation.
After:
```
    commit af992e7abd
    Author: Noah Goldstein <goldstein.w.n@gmail.com>
    Date:   Wed Jun 7 13:18:01 2023 -0500

        x86: Increase `non_temporal_threshold` to roughly `sizeof_L3 / 4`
```

Split `shared` (cumulative cache size) from `shared_per_thread` (cache
size per socket), the `shared_per_thread` *can* be slightly off from
the previous calculation.

Previously we added `core` even if `threads_l2` was invalid, and only
used `threads_l2` to divide `core` if it was present. The changed
version only included `core` if `threads_l2` was valid.

This change restores the old behavior if `threads_l2` is invalid by
adding the entire value of `core`.
Reviewed-by: DJ Delorie <dj@redhat.com>

(cherry picked from commit 47f7472178)
2023-08-28 15:02:18 -05:00
Noah Goldstein 1caf955269 x86: Increase non_temporal_threshold to roughly sizeof_L3 / 4
Current `non_temporal_threshold` set to roughly '3/4 * sizeof_L3 /
ncores_per_socket'. This patch updates that value to roughly
'sizeof_L3 / 4`

The original value (specifically dividing the `ncores_per_socket`) was
done to limit the amount of other threads' data a `memcpy`/`memset`
could evict.

Dividing by 'ncores_per_socket', however leads to exceedingly low
non-temporal thresholds and leads to using non-temporal stores in
cases where REP MOVSB is multiple times faster.

Furthermore, non-temporal stores are written directly to main memory
so using it at a size much smaller than L3 can place soon to be
accessed data much further away than it otherwise could be. As well,
modern machines are able to detect streaming patterns (especially if
REP MOVSB is used) and provide LRU hints to the memory subsystem. This
in affect caps the total amount of eviction at 1/cache_associativity,
far below meaningfully thrashing the entire cache.

As best I can tell, the benchmarks that lead this small threshold
where done comparing non-temporal stores versus standard cacheable
stores. A better comparison (linked below) is to be REP MOVSB which,
on the measure systems, is nearly 2x faster than non-temporal stores
at the low-end of the previous threshold, and within 10% for over
100MB copies (well past even the current threshold). In cases with a
low number of threads competing for bandwidth, REP MOVSB is ~2x faster
up to `sizeof_L3`.

The divisor of `4` is a somewhat arbitrary value. From benchmarks it
seems Skylake and Icelake both prefer a divisor of `2`, but older CPUs
such as Broadwell prefer something closer to `8`. This patch is meant
to be followed up by another one to make the divisor cpu-specific, but
in the meantime (and for easier backporting), this patch settles on
`4` as a middle-ground.

Benchmarks comparing non-temporal stores, REP MOVSB, and cacheable
stores where done using:
https://github.com/goldsteinn/memcpy-nt-benchmarks

Sheets results (also available in pdf on the github):
https://docs.google.com/spreadsheets/d/e/2PACX-1vS183r0rW_jRX6tG_E90m9qVuFiMbRIJvi5VAE8yYOvEOIEEc3aSNuEsrFbuXw5c3nGboxMmrupZD7K/pubhtml
Reviewed-by: DJ Delorie <dj@redhat.com>
Reviewed-by: Carlos O'Donell <carlos@redhat.com>

(cherry picked from commit af992e7abd)
2023-08-28 15:02:18 -05:00
Adhemerval Zanella 58f7431fd7 sparc: Fix la_symbind for bind-now (BZ 23734)
The sparc ABI has multiple cases on how to handle JMP_SLOT relocations,
(sparc_fixup_plt/sparc64_fixup_plt).  For BINDNOW, _dl_audit_symbind
will be responsible to setup the final relocation value; while for
lazy binding _dl_fixup/_dl_profile_fixup will call the audit callback
and tail cail elf_machine_fixup_plt (which will call
sparc64_fixup_plt).

This patch fixes by issuing the SPARC specific routine on bindnow and
forwarding the audit value to elf_machine_fixup_plt for lazy resolution.
It fixes the la_symbind for bind-now tests on sparc64 and sparcv9:

  elf/tst-audit24a
  elf/tst-audit24b
  elf/tst-audit24c
  elf/tst-audit24d

Checked on sparc64-linux-gnu and sparcv9-linux-gnu.
Tested-by: John Paul Adrian Glaubitz <glaubitz@physik.fu-berlin.de>

(cherry picked from commit dddc88587a)
2023-07-12 22:31:27 +02:00
Adhemerval Zanella 260d4b742b nptl: Fix tst-cancel30 on sparc64
As indicated by sparc kernel-features.h, even though sparc64 defines
__NR_pause,  it is not supported (ENOSYS).  Always use ppoll or the
64 bit time_t variant instead.

(cherry picked from commit 370da8a121)
2023-07-10 15:56:51 -03:00
Florian Weimer 3f4b4e2cdd elf: _dl_find_object may return 1 during early startup (bug 30515)
Success is reported with a 0 return value, and failure is -1.
Enhance the kitchen sink test elf/tst-audit28 to cover
_dl_find_object as well.

Fixes commit 5d28a8962d ("elf: Add _dl_find_object function")
and bug 30515.

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
Tested-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit 1bcfe0f732)
2023-07-07 10:46:46 +02:00
Siddhesh Poyarekar 0930ff8eb3 realloc: Limit chunk reuse to only growing requests [BZ #30579]
The trim_threshold is too aggressive a heuristic to decide if chunk
reuse is OK for reallocated memory; for repeated small, shrinking
allocations it leads to internal fragmentation and for repeated larger
allocations that fragmentation may blow up even worse due to the dynamic
nature of the threshold.

Limit reuse only when it is within the alignment padding, which is 2 *
size_t for heap allocations and a page size for mmapped allocations.
There's the added wrinkle of THP, but this fix ignores it for now,
pessimizing that case in favor of keeping fragmentation low.

This resolves BZ #30579.

Signed-off-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
Reported-by: Nicolas Dusart <nicolas@freedelity.be>
Reported-by: Aurelien Jarno <aurelien@aurel32.net>
Reviewed-by: Aurelien Jarno <aurelien@aurel32.net>
Tested-by: Aurelien Jarno <aurelien@aurel32.net>
(cherry picked from commit 2fb12bbd09)
2023-07-06 11:39:28 -04:00
John David Anglin 8dcb1a5181 hppa: xfail debug/tst-ssp-1 when have-ssp is yes (gcc-12 and later) 2023-07-01 22:26:15 +00:00
Adhemerval Zanella 3593050c27 io: Fix F_GETLK, F_SETLK, and F_SETLKW for powerpc64
Different than other 64 bit architectures, powerpc64 defines the
LFS POSIX lock constants  with values similar to 32 ABI, which
are meant to be used with fcntl64 syscall.  Since powerpc64 kABI
does not have fcntl, the constants are adjusted with the
FCNTL_ADJUST_CMD macro.

The 4d0fe291ae changed the logic of generic constants
LFS value are equal to the default values; which is now wrong
for powerpc64.

Fix the value by explicit define the previous glibc constants
(powerpc64 does not need to use the 32 kABI value, but it simplifies
the FCNTL_ADJUST_CMD which should be kept as compatibility).

Checked on powerpc64-linux-gnu and powerpc-linux-gnu.

(cherry picked from commit 5f828ff824)
2023-05-31 15:32:05 -03:00
Adhemerval Zanella e2974d26ce io: Fix record locking contants on 32 bit arch with 64 bit default time_t (BZ#30477)
For architecture with default 64 bit time_t support, the kernel
does not provide LFS and non-LFS values for F_GETLK, F_GETLK, and
F_GETLK (the default value used for 64 bit architecture are used).

This is might be considered an ABI break, but the currenct exported
values is bogus anyway.

The POSIX lockf is not affected since it is aliased to lockf64,
which already uses the LFS values.

Checked on i686-linux-gnu and the new tests on a riscv32.

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit 4d0fe291ae)
2023-05-30 09:54:05 -03:00
H.J. Lu 0e3e9dbb0e Document BZ #20975 fix 2023-05-23 16:44:01 -07:00
H.J. Lu f5d377c896 __check_pf: Add a cancellation cleanup handler [BZ #20975]
There are reports for hang in __check_pf:

https://github.com/JoeDog/siege/issues/4

It is reproducible only under specific configurations:

1. Large number of cores (>= 64) and large number of threads (> 3X of
the number of cores) with long lived socket connection.
2. Low power (frequency) mode.
3. Power management is enabled.

While holding lock, __check_pf calls make_request which calls __sendto
and __recvmsg.  Since __sendto and __recvmsg are cancellation points,
lock held by __check_pf won't be released and can cause deadlock when
thread cancellation happens in __sendto or __recvmsg.  Add a cancellation
cleanup handler for __check_pf to unlock the lock when cancelled by
another thread.  This fixes BZ #20975 and the siege hang issue.

(cherry picked from commit a443bd3fb2)
2023-05-23 11:43:08 -07:00
Joseph Myers b4f76ecc9e Ignore MAP_VARIABLE in tst-mman-consts.py
Linux 6.2 removed the hppa compatibility MAP_VARIABLE define.  That
means that, whether or not we remove it in glibc, it needs to be
ignored in tst-mman-consts.py (since this macro comparison
infrastructure expects that new kernel header versions only add new
macros, not remove old ones).

Tested with build-many-glibcs.py for hppa-linux-gnu (Linux 6.2
headers).

(cherry picked from commit 01e09ab057)
2023-05-17 11:32:17 +02:00
Florian Weimer 7c32cb7dd8 gmon: Revert addition of tunables to the manual
These tunables had to be removed over GLIBC_PRIVATE ABI stability
concerns.
2023-04-28 17:55:39 +02:00
Florian Weimer a908c18d47 gmon: Revert addition of tunables to preserve GLIBC_PRIVATE ABI
Otherwise, processes are likely to crash during concurrent updates
to a new glibc version on the stable release branch.

The test gmon/tst-mcount-overflow depends on those tunables, so
it has to be removed as well.
2023-04-28 17:07:53 +02:00
Simon Kissane ff3a71ec1f gmon: fix memory corruption issues [BZ# 30101]
V2 of this patch fixes an issue in V1, where the state was changed to ON not
OFF at end of _mcleanup. I hadn't noticed that (counterintuitively) ON=0 and
OFF=3, hence zeroing the buffer turned it back on. So set the state to OFF
after the memset.

1. Prevent double free, and reads from unallocated memory, when
   _mcleanup is (incorrectly) called two or more times in a row,
   without an intervening call to __monstartup; with this patch, the
   second and subsequent calls effectively become no-ops instead.
   While setting tos=NULL is minimal fix, safest action is to zero the
   whole gmonparam buffer.

2. Prevent memory leak when __monstartup is (incorrectly) called two
   or more times in a row, without an intervening call to _mcleanup;
   with this patch, the second and subsequent calls effectively become
   no-ops instead.

3. After _mcleanup, treat __moncontrol(1) as __moncontrol(0) instead.
   With zeroing of gmonparam buffer in _mcleanup, this stops the
   state incorrectly being changed to GMON_PROF_ON despite profiling
   actually being off. If we'd just done the minimal fix to _mcleanup
   of setting tos=NULL, there is risk of far worse memory corruption:
   kcount would point to deallocated memory, and the __profil syscall
   would make the kernel write profiling data into that memory,
   which could have since been reallocated to something unrelated.

4. Ensure __moncontrol(0) still turns off profiling even in error
   state. Otherwise, if mcount overflows and sets state to
   GMON_PROF_ERROR, when _mcleanup calls __moncontrol(0), the __profil
   syscall to disable profiling will not be invoked. _mcleanup will
   free the buffer, but the kernel will still be writing profiling
   data into it, potentially corrupted arbitrary memory.

Also adds a test case for (1). Issues (2)-(4) are not feasible to test.

Signed-off-by: Simon Kissane <skissane@gmail.com>
Reviewed-by: DJ Delorie <dj@redhat.com>
(cherry picked from commit bde1218720)
2023-04-28 13:48:40 +02:00
Simon Kissane d230623264 gmon: improve mcount overflow handling [BZ# 27576]
When mcount overflows, no gmon.out file is generated, but no message is printed
to the user, leaving the user with no idea why, and thinking maybe there is
some bug - which is how BZ 27576 ended up being logged. Print a message to
stderr in this case so the user knows what is going on.

As a comment in sys/gmon.h acknowledges, the hardcoded MAXARCS value is too
small for some large applications, including the test case in that BZ. Rather
than increase it, add tunables to enable MINARCS and MAXARCS to be overridden
at runtime (glibc.gmon.minarcs and glibc.gmon.maxarcs). So if a user gets the
mcount overflow error, they can try increasing maxarcs (they might need to
increase minarcs too if the heuristic is wrong in their case.)

Note setting minarcs/maxarcs too large can cause monstartup to fail with an
out of memory error. If you set them large enough, it can cause an integer
overflow in calculating the buffer size. I haven't done anything to defend
against that - it would not generally be a security vulnerability, since these
tunables will be ignored in suid/sgid programs (due to the SXID_ERASE default),
and if you can set GLIBC_TUNABLES in the environment of a process, you can take
it over anyway (LD_PRELOAD, LD_LIBRARY_PATH, etc). I thought about modifying
the code of monstartup to defend against integer overflows, but doing so is
complicated, and I realise the existing code is susceptible to them even prior
to this change (e.g. try passing a pathologically large highpc argument to
monstartup), so I decided just to leave that possibility in-place.

Add a test case which demonstrates mcount overflow and the tunables.

Document the new tunables in the manual.

Signed-off-by: Simon Kissane <skissane@gmail.com>
Reviewed-by: DJ Delorie <dj@redhat.com>
(cherry picked from commit 31be941e43)
2023-04-28 13:47:55 +02:00
Леонид Юрьев (Leonid Yuriev) 5d750495db gmon: Fix allocated buffer overflow (bug 29444)
The `__monstartup()` allocates a buffer used to store all the data
accumulated by the monitor.

The size of this buffer depends on the size of the internal structures
used and the address range for which the monitor is activated, as well
as on the maximum density of call instructions and/or callable functions
that could be potentially on a segment of executable code.

In particular a hash table of arcs is placed at the end of this buffer.
The size of this hash table is calculated in bytes as
   p->fromssize = p->textsize / HASHFRACTION;

but actually should be
   p->fromssize = ROUNDUP(p->textsize / HASHFRACTION, sizeof(*p->froms));

This results in writing beyond the end of the allocated buffer when an
added arc corresponds to a call near from the end of the monitored
address range, since `_mcount()` check the incoming caller address for
monitored range but not the intermediate result hash-like index that
uses to write into the table.

It should be noted that when the results are output to `gmon.out`, the
table is read to the last element calculated from the allocated size in
bytes, so the arcs stored outside the buffer boundary did not fall into
`gprof` for analysis. Thus this "feature" help me to found this bug
during working with https://sourceware.org/bugzilla/show_bug.cgi?id=29438

Just in case, I will explicitly note that the problem breaks the
`make test t=gmon/tst-gmon-dso` added for Bug 29438.
There, the arc of the `f3()` call disappears from the output, since in
the DSO case, the call to `f3` is located close to the end of the
monitored range.

Signed-off-by: Леонид Юрьев (Leonid Yuriev) <leo@yuriev.ru>

Another minor error seems a related typo in the calculation of
`kcountsize`, but since kcounts are smaller than froms, this is
actually to align the p->froms data.

Co-authored-by: DJ Delorie <dj@redhat.com>
Reviewed-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit 801af9fafd)
2023-04-28 13:47:28 +02:00
Adam Yi 78ab913eab posix: Fix system blocks SIGCHLD erroneously [BZ #30163]
Fix bug that SIGCHLD is erroneously blocked forever in the following
scenario:

1. Thread A calls system but hasn't returned yet
2. Thread B calls another system but returns

SIGCHLD would be blocked forever in thread B after its system() returns,
even after the system() in thread A returns.

Although POSIX does not require, glibc system implementation aims to be
thread and cancellation safe. This bug was introduced in
5fb7fc9635 when we moved reverting signal
mask to happen when the last concurrently running system returns,
despite that signal mask is per thread. This commit reverts this logic
and adds a test.

Signed-off-by: Adam Yi <ayi@janestreet.com>
Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit 436a604b7d)
2023-04-28 13:21:20 +02:00
Florian Weimer 9cc2f41e52 x86_64: Fix asm constraints in feraiseexcept (bug 30305)
The divss instruction clobbers its first argument, and the constraints
need to reflect that.  Fortunately, with GCC 12, generated code does
not actually change, so there is no externally visible bug.

Suggested-by: Jakub Jelinek <jakub@redhat.com>
Reviewed-by: Noah Goldstein <goldstein.w.n@gmail.com>
(cherry picked from commit 5d1ccdda7b)
2023-04-24 15:16:04 +02:00
Florian Weimer 97ad4c64b9 gshadow: Matching sgetsgent, sgetsgent_r ERANGE handling (bug 30151)
Before this change, sgetsgent_r did not set errno to ERANGE, but
sgetsgent only check errno, not the return value from sgetsgent_r.
Consequently, sgetsgent did not detect any error, and reported
success to the caller, without initializing the struct sgrp object
whose address was returned.

This commit changes sgetsgent_r to set errno as well.  This avoids
similar issues in applications which only change errno.

Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit 969e9733c7)
2023-04-24 14:15:36 +02:00
Sam James 1d63573f81 stdio-common: tests: don't double-define _FORTIFY_SOURCE
Exactly the same as 35bcb08eaa.

If using -D_FORITFY_SOURCE=3 (in my case, I've patched GCC to add
=3 instead of =2 (we've done =2 for years in Gentoo)), building
glibc tests will fail on tst-bz11319-fortify2 like:
```
<command-line>: error: "_FORTIFY_SOURCE" redefined [-Werror]
<built-in>: note: this is the location of the previous definition
cc1: all warnings being treated as errors
```

It's just because we're always setting -D_FORTIFY_SOURCE=2
rather than unsetting it first. If F_S is already 2, it's harmless,
but if it's another value (say, 1, or 3), the compiler will bawk.

(I'm not aware of a reason this couldn't be tested with =3,
but the toolchain support is limited for that (too new), and we want
to run the tests everywhere possible.)

As Siddhesh noted previously, we could implement some fallback
logic to determine the maximal F_S value supported by the toolchain,
which is a bit easier now that autoconf-archive has been updated for F_S=3
(https://github.com/autoconf-archive/autoconf-archive/pull/269), but let's
revisit this if it continues to crop up.

Signed-off-by: Sam James <sam@gentoo.org>
Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit ecf8ae6704)
2023-04-11 03:36:53 +01:00
Joan Bruguera 590d0e089b elf: Restore ldconfig libc6 implicit soname logic [BZ #30125]
While cleaning up old libc version support, the deprecated libc4 code was
accidentally kept in `implicit_soname`, instead of the libc6 code.

This causes additional symlinks to be created by `ldconfig` for libraries
without a soname, e.g. a library `libsomething.123.456.789` without a soname
will create a `libsomething.123` -> `libsomething.123.456.789` symlink.

As the libc6 version of the `implicit_soname` code is a trivial `xstrdup`,
just inline it and remove `implicit_soname` altogether.

Some further simplification looks possible (e.g. the call to `create_links`
looks like a no-op if `soname == NULL`, other than the verbose printfs), but
logic is kept as-is for now.

Fixes: BZ #30125
Fixes: 8ee878592c ("Assume only FLAG_ELF_LIBC6 suport")
Signed-off-by: Joan Bruguera <joanbrugueram@gmail.com>

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit 1b0ea8c5d8)
2023-02-20 11:54:45 -03:00
Vitaly Buka 790e504a17 stdlib: Undo post review change to 16adc58e73 [BZ #27749]
Post review removal of "goto restart" from
https://sourceware.org/pipermail/libc-alpha/2021-April/125470.html
introduced a bug when some atexit handers skipped.

Signed-off-by: Vitaly Buka <vitalybuka@google.com>

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit fd78cfa72e)
2023-02-20 10:16:22 -03:00
Florian Weimer d8e1a7590d elf: Smoke-test ldconfig -p against system /etc/ld.so.cache
The test is sufficient to detect the ldconfig bug fixed in
commit 9fe6f63638 ("elf: Fix 64 time_t
support for installed statically binaries").

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit 9fd63e3537)
2023-02-08 19:00:02 +01:00
Carlos O'Donell 6fe86ecd78 NEWS: Document CVE-2023-25139.
Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit 67c37737ed)
2023-02-07 18:24:41 -05:00
Carlos O'Donell 07b9521fc6 Account for grouping in printf width (bug 30068)
This is a partial fix for mishandling of grouping when formatting
integers.  It properly computes the width in the presence of grouping
characters when the width is larger than the number of significant
digits. The precision related issue is documented in bug 23432.

Co-authored-by: Andreas Schwab <schwab@suse.de>
(cherry picked from commit c980549cc6)
2023-02-07 18:23:20 -05:00
Andreas Schwab fb7b95dc47 Use 64-bit time_t interfaces in strftime and strptime (bug 30053)
Both functions use time_t only internally, so the ABI is not affected.

(cherry picked from commit 41349f6f67)
2023-02-07 11:03:27 -03:00
caiyinyu 9f8513dc64 LoongArch: Add new relocation types. 2023-02-03 09:43:23 +08:00
Siddhesh Poyarekar 020b43544a cdefs: Limit definition of fortification macros
Define the __glibc_fortify and other macros only when __FORTIFY_LEVEL >
0.  This has the effect of not defining these macros on older C90
compilers that do not have support for variable length argument lists.

Also trim off the trailing backslashes from the definition of
__glibc_fortify and __glibc_fortify_n macros.

Signed-off-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
Reviewed-by: Florian Weimer <fweimer@redhat.com>
(cherry picked from commit 2337e04e21)
2023-02-02 08:32:16 -05:00
302 changed files with 7007 additions and 2121 deletions
+6 -3
View File
@@ -585,10 +585,13 @@ link-libc-rpath-link = -Wl,-rpath-link=$(rpath-link)
# before the expansion of LDLIBS-* variables).
# Tests use -Wl,-rpath instead of -Wl,-rpath-link for
# build-hardcoded-path-in-tests.
# build-hardcoded-path-in-tests. Add -Wl,--disable-new-dtags to force
# DT_RPATH instead of DT_RUNPATH which only applies to DT_NEEDED entries
# in the executable and doesn't applies to DT_NEEDED entries in shared
# libraries which are loaded via DT_NEEDED entries in the executable.
ifeq (yes,$(build-hardcoded-path-in-tests))
link-libc-tests-rpath-link = $(link-libc-rpath)
link-test-modules-rpath-link = $(link-libc-rpath)
link-libc-tests-rpath-link = $(link-libc-rpath) -Wl,--disable-new-dtags
link-test-modules-rpath-link = $(link-libc-rpath) -Wl,--disable-new-dtags
else
link-libc-tests-rpath-link = $(link-libc-rpath-link)
link-test-modules-rpath-link =
+85
View File
@@ -5,6 +5,89 @@ See the end for copying conditions.
Please send GNU C library bug reports via <https://sourceware.org/bugzilla/>
using `glibc' in the "product" field.
Version 2.37.1
Deprecated and removed features, and other changes affecting compatibility:
* __rseq_size now denotes the size of the active rseq area (20 bytes
initially), not the size of struct rseq (32 bytes initially).
Security related changes:
CVE-2023-25139: When the printf family of functions is called with a
format specifier that uses an <apostrophe> (enable grouping) and a
minimum width specifier, the resulting output could be larger than
reasonably expected by a caller that computed a tight bound on the
buffer size. The resulting larger than expected output could result
in a buffer overflow in the printf family of functions.
CVE-2023-4527: If the system is configured in no-aaaa mode via
/etc/resolv.conf, getaddrinfo is called for the AF_UNSPEC address
family, and a DNS response is received over TCP that is larger than
2048 bytes, getaddrinfo may potentially disclose stack contents via
the returned address data, or crash.
CVE-2023-4806: When an NSS plugin only implements the
_gethostbyname2_r and _getcanonname_r callbacks, getaddrinfo could use
memory that was freed during buffer resizing, potentially causing a
crash or read or write to arbitrary memory.
CVE-2023-5156: The fix for CVE-2023-4806 introduced a memory leak when
an application calls getaddrinfo for AF_INET6 with AI_CANONNAME,
AI_ALL and AI_V4MAPPED flags set.
CVE-2023-4911: If a tunable of the form NAME=NAME=VAL is passed in the
environment of a setuid program and NAME is valid, it may result in a
buffer overflow, which could be exploited to achieve escalated
privileges. This flaw was introduced in glibc 2.34.
CVE-2025-0395: When the assert() function fails, it does not allocate
enough space for the assertion failure message string and size
information, which may lead to a buffer overflow if the message string
size aligns to page size.
GLIBC-SA-2026-0003: wordexp with WRDE_REUSE and WRDE_APPEND may return
uninitialized memory (CVE-2025-15281).
The following bugs are resolved with this release:
[20975] Deferred cancellation triggers in __check_pf and looses lock leading to deadlock
[27576] gmon: improve mcount overflow handling
[27821] ungetc: Fix backup buffer leak on program exit
[29039] Corrupt DTV after reuse of a TLS module ID following dlclose with unused TLS
[29444] gmon: Fix allocated buffer overflow (bug 29444)
[30053] time: strftime %s returns -1 after 2038 on 32 bits systems
[30081] resolv: Do not wait for non-existing second DNS response after error
[30101] gmon: fix memory corruption issues
[30125] dynamic-link: [regression, bisected] glibc-2.37 creates new
symlink for libraries without soname
[30151] gshadow: Matching sgetsgent, sgetsgent_r ERANGE handling
[30163] posix: Fix system blocks SIGCHLD erroneously
[30305] x86_64: Fix asm constraints in feraiseexcept
[30428] AMD cache size computation does not work for some CPUs, hypervisors
[30477] libc: [RISCV]: time64 does not work on riscv32
[30515] _dl_find_object incorrectly returns 1 during early startup
[30745] Slight bug in cache info codes for x86
[30842] Stack read overflow in getaddrinfo in no-aaaa mode (CVE-2023-4527)
[30843] potential use-after-free in getcanonname (CVE-2023-4806)
[31183] Wide stream buffer size reduced MB_LEN_MAX bytes after bug 17522 fix
[31184] FAIL: elf/tst-tlsgap
[31185] Incorrect thread point access in _dl_tlsdesc_undefweak and _dl_tlsdesc_dynamic
[31476] resolv: Track single-request fallback via _res._flags
[31890] resolv: Allow short error responses to match any DNS query
[31943] _dl_find_object can fail if ld.so contains gaps between load segments
[31965] rseq extension mechanism does not work as intended
[31968] mremap implementation in C does not handle arguments correctly
[32052] Name space violation in fortify wrappers
[32137] libio: Attempt wide backup free only for non-legacy code
[32231] elf: Change ldconfig auxcache magic number
[32470] x86: Avoid integer truncation with large cache sizes
[32582] Fix underallocation of abort_msg_s struct (CVE-2025-0395)
[32987] elf: Fix subprocess status handling for tst-dlopen-sgid
[33185] Fix double-free after allocation failure in regcomp
[33814] glob: wordexp with WRDE_REUSE and WRDE_APPEND may return
uninitialized memory
Version 2.37
Major new features:
@@ -105,6 +188,8 @@ The following bugs are resolved with this release:
coincides with offset change
[30039] stdio: __vsprintf_internal does not handle unspecified buffer
length in fortify mode
[30804] F_GETLK, F_SETLK, and F_SETLKW value change for powerpc64 with
-D_FILE_OFFSET_BITS=64
Version 2.36
+15 -3
View File
@@ -22,7 +22,9 @@ subdir := assert
include ../Makeconfig
headers := assert.h
headers := \
assert.h
# headers
routines := \
__assert \
@@ -30,7 +32,14 @@ routines := \
assert \
assert-perr \
# routines
tests := test-assert test-assert-perr tst-assert-c++ tst-assert-g++
tests := \
test-assert \
test-assert-perr \
tst-assert-c++ \
tst-assert-g++ \
tst-assert-sa-2025-0001 \
# tests
ifeq ($(have-cxx-thread_local),yes)
CFLAGS-tst-assert-c++.o = -std=c++11
@@ -38,7 +47,10 @@ LDLIBS-tst-assert-c++ = -lstdc++
CFLAGS-tst-assert-g++.o = -std=gnu++11
LDLIBS-tst-assert-g++ = -lstdc++
else
tests-unsupported += tst-assert-c++ tst-assert-g++
tests-unsupported += \
tst-assert-c++ \
tst-assert-g++ \
# tests-unsupported
endif
include ../Rules
+3 -1
View File
@@ -18,6 +18,7 @@
#include <assert.h>
#include <atomic.h>
#include <ldsodefs.h>
#include <libc-pointer-arith.h>
#include <libintl.h>
#include <stdio.h>
#include <stdlib.h>
@@ -64,7 +65,8 @@ __assert_fail_base (const char *fmt, const char *assertion, const char *file,
(void) __fxprintf (NULL, "%s", str);
(void) fflush (stderr);
total = (total + 1 + GLRO(dl_pagesize) - 1) & ~(GLRO(dl_pagesize) - 1);
total = ALIGN_UP (total + sizeof (struct abort_msg_s) + 1,
GLRO(dl_pagesize));
struct abort_msg_s *buf = __mmap (NULL, total, PROT_READ | PROT_WRITE,
MAP_ANON | MAP_PRIVATE, -1, 0);
if (__glibc_likely (buf != MAP_FAILED))
+92
View File
@@ -0,0 +1,92 @@
/* Test for CVE-2025-0395.
Copyright The GNU Toolchain Authors.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
/* Test that a large enough __progname does not result in a buffer overflow
when printing an assertion failure. This was CVE-2025-0395. */
#include <assert.h>
#include <inttypes.h>
#include <signal.h>
#include <stdbool.h>
#include <string.h>
#include <sys/mman.h>
#include <support/check.h>
#include <support/support.h>
#include <support/xstdio.h>
#include <support/xunistd.h>
extern const char *__progname;
int
do_test (int argc, char **argv)
{
support_need_proc ("Reads /proc/self/maps to add guards to writable maps.");
ignore_stderr ();
/* XXX assumes that the assert is on a 2 digit line number. */
const char *prompt = ": %s:99: do_test: Assertion `argc < 1' failed.\n";
int ret = fprintf (stderr, prompt, __FILE__);
if (ret < 0)
FAIL_EXIT1 ("fprintf failed: %m\n");
size_t pagesize = getpagesize ();
size_t namesize = pagesize - 1 - ret;
/* Alter the progname so that the assert message fills the entire page. */
char progname[namesize];
memset (progname, 'A', namesize - 1);
progname[namesize - 1] = '\0';
__progname = progname;
FILE *f = xfopen ("/proc/self/maps", "r");
char *line = NULL;
size_t len = 0;
uintptr_t prev_to = 0;
/* Pad the beginning of every writable mapping with a PROT_NONE map. This
ensures that the mmap in the assert_fail path never ends up below a
writable map and will terminate immediately in case of a buffer
overflow. */
while (xgetline (&line, &len, f))
{
uintptr_t from, to;
char perm[4];
sscanf (line, "%" SCNxPTR "-%" SCNxPTR " %c%c%c%c ",
&from, &to,
&perm[0], &perm[1], &perm[2], &perm[3]);
bool writable = (memchr (perm, 'w', 4) != NULL);
if (prev_to != 0 && from - prev_to > pagesize && writable)
xmmap ((void *) from - pagesize, pagesize, PROT_NONE,
MAP_ANONYMOUS | MAP_PRIVATE, 0);
prev_to = to;
}
xfclose (f);
assert (argc < 1);
return 0;
}
#define EXPECTED_SIGNAL SIGABRT
#define TEST_FUNCTION_ARGV do_test
#include <support/test-driver.c>
+4 -2
View File
@@ -21,7 +21,9 @@
#define __WORDSIZE32_PTRDIFF_LONG
/* Set to 1 in order to force time types to be 32 bits instead of 64 bits in
struct lastlog and struct utmp{,x} on 64-bit ports. This may be done in
struct lastlog and struct utmp{,x}. This may be done in
order to make 64-bit ports compatible with 32-bit ports. Set to 0 for
64-bit ports where the time types are 64-bits or for any 32-bit ports. */
64-bit ports where the time types are 64-bits and new 32-bit ports
where time_t is 64 bits, and there is no companion architecture with
32-bit time_t. */
#define __WORDSIZE_TIME64_COMPAT32
+57
View File
@@ -171,6 +171,7 @@ CFLAGS-.op += $(call elide-stack-protector,.op,$(elide-routines.os))
CFLAGS-.os += $(call elide-stack-protector,.os,$(all-rtld-routines))
# Add the requested compiler flags to the early startup code.
CFLAGS-dl-misc.os += $(rtld-early-cflags)
CFLAGS-dl-printf.os += $(rtld-early-cflags)
CFLAGS-dl-setup_hash.os += $(rtld-early-cflags)
CFLAGS-dl-sysdep.os += $(rtld-early-cflags)
@@ -266,6 +267,7 @@ tests-static-normal := \
tst-array1-static \
tst-array5-static \
tst-dl-iter-static \
tst-dlopen-sgid \
tst-dst-static \
tst-env-setuid \
tst-env-setuid-tunables \
@@ -433,6 +435,7 @@ tests += \
tst-p_align1 \
tst-p_align2 \
tst-p_align3 \
tst-recursive-tls \
tst-relsort1 \
tst-ro-dynamic \
tst-rtld-run-static \
@@ -495,6 +498,8 @@ tests-internal += \
tst-dl_find_object \
tst-dl_find_object-threads \
tst-dlmopen2 \
tst-link-map-contiguous-ldso \
tst-link-map-contiguous-libc \
tst-ptrguard1 \
tst-stackguard1 \
tst-tls-surplus \
@@ -506,6 +511,10 @@ tests-internal += \
unload2 \
# tests-internal
ifeq ($(build-hardcoded-path-in-tests),yes)
tests-internal += tst-link-map-contiguous-main
endif
tests-container += \
tst-dlopen-self-container \
tst-dlopen-tlsmodid-container \
@@ -626,6 +635,8 @@ ifeq ($(run-built-tests),yes)
tests-special += \
$(objpfx)noload-mem.out \
$(objpfx)tst-ldconfig-X.out \
$(objpfx)tst-ldconfig-p.out \
$(objpfx)tst-ldconfig-soname.out \
$(objpfx)tst-leaks1-mem.out \
$(objpfx)tst-rtld-help.out \
# tests-special
@@ -834,6 +845,7 @@ modules-names += \
tst-dlmopen-gethostbyname-mod \
tst-dlmopen-twice-mod1 \
tst-dlmopen-twice-mod2 \
tst-dlopen-sgid-mod \
tst-dlopenfaillinkmod \
tst-dlopenfailmod1 \
tst-dlopenfailmod2 \
@@ -858,6 +870,8 @@ modules-names += \
tst-initorderb2 \
tst-latepthreadmod \
tst-ldconfig-ld-mod \
tst-ldconfig-soname-lib-with-soname \
tst-ldconfig-soname-lib-without-soname \
tst-main1mod \
tst-nodelete2mod \
tst-nodelete-dlclose-dso \
@@ -866,6 +880,23 @@ modules-names += \
tst-null-argv-lib \
tst-p_alignmod-base \
tst-p_alignmod3 \
tst-recursive-tlsmallocmod \
tst-recursive-tlsmod0 \
tst-recursive-tlsmod1 \
tst-recursive-tlsmod2 \
tst-recursive-tlsmod3 \
tst-recursive-tlsmod4 \
tst-recursive-tlsmod5 \
tst-recursive-tlsmod6 \
tst-recursive-tlsmod7 \
tst-recursive-tlsmod8 \
tst-recursive-tlsmod9 \
tst-recursive-tlsmod10 \
tst-recursive-tlsmod11 \
tst-recursive-tlsmod12 \
tst-recursive-tlsmod13 \
tst-recursive-tlsmod14 \
tst-recursive-tlsmod15 \
tst-relsort1mod1 \
tst-relsort1mod2 \
tst-ro-dynamic-mod \
@@ -2396,6 +2427,22 @@ $(objpfx)tst-ldconfig-X.out : tst-ldconfig-X.sh $(objpfx)ldconfig
'$(run-program-env)' > $@; \
$(evaluate-test)
$(objpfx)tst-ldconfig-p.out : tst-ldconfig-p.sh $(objpfx)ldconfig
$(SHELL) $< '$(common-objpfx)' '$(test-wrapper-env)' \
'$(run-program-env)' > $@; \
$(evaluate-test)
LDFLAGS-tst-ldconfig-soname-lib-with-soname.so = \
-Wl,-soname,libtst-ldconfig-soname-lib-with-soname.so.1
$(objpfx)tst-ldconfig-soname.out : tst-ldconfig-soname.sh \
$(objpfx)ldconfig \
$(objpfx)tst-ldconfig-soname-lib-with-soname.so \
$(objpfx)tst-ldconfig-soname-lib-without-soname.so
$(SHELL) $< '$(common-objpfx)' '$(test-wrapper-env)' \
'$(run-program-env)' > $@; \
$(evaluate-test)
# Test static linking of all the libraries we can possibly link
# together. Note that in some configurations this may be less than the
# complete list of libraries we build but we try to maxmimize this list.
@@ -2969,3 +3016,13 @@ tst-audit-tlsdesc-dlopen-ENV = LD_AUDIT=$(objpfx)tst-auditmod-tlsdesc.so
$(objpfx)tst-dlmopen-twice.out: \
$(objpfx)tst-dlmopen-twice-mod1.so \
$(objpfx)tst-dlmopen-twice-mod2.so
$(objpfx)tst-recursive-tls: $(objpfx)tst-recursive-tlsmallocmod.so
# More objects than DTV_SURPLUS, to trigger DTV reallocation.
$(objpfx)tst-recursive-tls.out: \
$(patsubst %,$(objpfx)tst-recursive-tlsmod%.so, \
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15)
$(objpfx)tst-recursive-tlsmod%.os: tst-recursive-tlsmodN.c
$(compile-command.c) -DVAR=thread_$* -DFUNC=get_threadvar_$*
$(objpfx)tst-dlopen-sgid.out: $(objpfx)tst-dlopen-sgid-mod.so
+1 -1
View File
@@ -817,7 +817,7 @@ struct aux_cache_entry
struct aux_cache_entry *next;
};
#define AUX_CACHEMAGIC "glibc-ld.so.auxcache-1.0"
#define AUX_CACHEMAGIC "glibc-ld.so.auxcache-2.0"
struct aux_cache_file_entry
{
+3 -3
View File
@@ -176,8 +176,8 @@ rtld_hidden_def (_dl_audit_symbind_alt)
void
_dl_audit_symbind (struct link_map *l, struct reloc_result *reloc_result,
const ElfW(Sym) *defsym, DL_FIXUP_VALUE_TYPE *value,
lookup_t result)
const void *reloc, const ElfW(Sym) *defsym,
DL_FIXUP_VALUE_TYPE *value, lookup_t result, bool lazy)
{
bool for_jmp_slot = reloc_result == NULL;
@@ -259,7 +259,7 @@ _dl_audit_symbind (struct link_map *l, struct reloc_result *reloc_result,
}
if (flags & LA_SYMB_ALTVALUE)
DL_FIXUP_BINDNOW_RELOC (value, new_value, sym.st_value);
DL_FIXUP_BINDNOW_RELOC (l, reloc, value, new_value, sym.st_value, lazy);
}
void
+1 -1
View File
@@ -703,7 +703,7 @@ _dl_close_worker (struct link_map *map, bool force)
if (__glibc_unlikely (newgen == 0))
_dl_fatal_printf ("TLS generation counter wrapped! Please report as described in "REPORT_BUGS_TO".\n");
/* Can be read concurrently. */
atomic_store_relaxed (&GL(dl_tls_generation), newgen);
atomic_store_release (&GL(dl_tls_generation), newgen);
if (tls_free_end == GL(dl_tls_static_used))
GL(dl_tls_static_used) = tls_free_start;
+50 -30
View File
@@ -46,7 +46,7 @@ _dl_find_object_slow (void *pc, struct dl_find_object *result)
struct dl_find_object_internal internal;
_dl_find_object_from_map (l, &internal);
_dl_find_object_to_external (&internal, result);
return 1;
return 0;
}
/* Object not found. */
@@ -465,6 +465,37 @@ _dl_find_object (void *pc1, struct dl_find_object *result)
}
rtld_hidden_def (_dl_find_object)
/* Subroutine of _dlfo_process_initial to split out noncontigous link
maps. NODELETE is the number of used _dlfo_nodelete_mappings
elements. It is incremented as needed, and the new NODELETE value
is returned. */
static size_t
_dlfo_process_initial_noncontiguous_map (struct link_map *map,
size_t nodelete)
{
struct dl_find_object_internal dlfo;
_dl_find_object_from_map (map, &dlfo);
/* PT_LOAD segments for a non-contiguous link map are added to the
non-closeable mappings. */
const ElfW(Phdr) *ph = map->l_phdr;
const ElfW(Phdr) *ph_end = map->l_phdr + map->l_phnum;
for (; ph < ph_end; ++ph)
if (ph->p_type == PT_LOAD)
{
if (_dlfo_nodelete_mappings != NULL)
{
/* Second pass only. */
_dlfo_nodelete_mappings[nodelete] = dlfo;
ElfW(Addr) start = ph->p_vaddr + map->l_addr;
_dlfo_nodelete_mappings[nodelete].map_start = start;
_dlfo_nodelete_mappings[nodelete].map_end = start + ph->p_memsz;
}
++nodelete;
}
return nodelete;
}
/* _dlfo_process_initial is called twice. First to compute the array
sizes from the initial loaded mappings. Second to fill in the
bases and infos arrays with the (still unsorted) data. Returns the
@@ -476,29 +507,8 @@ _dlfo_process_initial (void)
size_t nodelete = 0;
if (!main_map->l_contiguous)
{
struct dl_find_object_internal dlfo;
_dl_find_object_from_map (main_map, &dlfo);
/* PT_LOAD segments for a non-contiguous are added to the
non-closeable mappings. */
for (const ElfW(Phdr) *ph = main_map->l_phdr,
*ph_end = main_map->l_phdr + main_map->l_phnum;
ph < ph_end; ++ph)
if (ph->p_type == PT_LOAD)
{
if (_dlfo_nodelete_mappings != NULL)
{
/* Second pass only. */
_dlfo_nodelete_mappings[nodelete] = dlfo;
_dlfo_nodelete_mappings[nodelete].map_start
= ph->p_vaddr + main_map->l_addr;
_dlfo_nodelete_mappings[nodelete].map_end
= _dlfo_nodelete_mappings[nodelete].map_start + ph->p_memsz;
}
++nodelete;
}
}
/* Contiguous case already handled in _dl_find_object_init. */
nodelete = _dlfo_process_initial_noncontiguous_map (main_map, nodelete);
size_t loaded = 0;
for (Lmid_t ns = 0; ns < GL(dl_nns); ++ns)
@@ -510,11 +520,22 @@ _dlfo_process_initial (void)
/* lt_library link maps are implicitly NODELETE. */
if (l->l_type == lt_library || l->l_nodelete_active)
{
if (_dlfo_nodelete_mappings != NULL)
/* Second pass only. */
_dl_find_object_from_map
(l, _dlfo_nodelete_mappings + nodelete);
++nodelete;
/* The kernel may have loaded ld.so with gaps. */
if (!l->l_contiguous
#ifdef SHARED
&& l == &GL(dl_rtld_map)
#endif
)
nodelete
= _dlfo_process_initial_noncontiguous_map (l, nodelete);
else
{
if (_dlfo_nodelete_mappings != NULL)
/* Second pass only. */
_dl_find_object_from_map
(l, _dlfo_nodelete_mappings + nodelete);
++nodelete;
}
}
else if (l->l_type == lt_loaded)
{
@@ -756,7 +777,6 @@ _dl_find_object_update_1 (struct link_map **loaded, size_t count)
/* Prefer newly loaded link map. */
assert (loaded_index1 > 0);
_dl_find_object_from_map (loaded[loaded_index1 - 1], dlfo);
loaded[loaded_index1 - 1]->l_find_object_processed = 1;
--loaded_index1;
}
+3 -1
View File
@@ -87,7 +87,7 @@ _dl_find_object_to_external (struct dl_find_object_internal *internal,
}
/* Extract the object location data from a link map and writes it to
*RESULT using relaxed MO stores. */
*RESULT using relaxed MO stores. Set L->l_find_object_processed. */
static void __attribute__ ((unused))
_dl_find_object_from_map (struct link_map *l,
struct dl_find_object_internal *result)
@@ -100,6 +100,8 @@ _dl_find_object_from_map (struct link_map *l,
atomic_store_relaxed (&result->eh_dbase, (void *) l->l_info[DT_PLTGOT]);
#endif
l->l_find_object_processed = 1;
for (const ElfW(Phdr) *ph = l->l_phdr, *ph_end = l->l_phdr + l->l_phnum;
ph < ph_end; ++ph)
if (ph->p_type == DLFO_EH_SEGMENT_TYPE)
+6 -2
View File
@@ -25,10 +25,14 @@
static void
call_init (struct link_map *l, int argc, char **argv, char **env)
{
/* Do not run constructors for proxy objects. */
if (l != l->l_real)
return;
/* If the object has not been relocated, this is a bug. The
function pointers are invalid in this case. (Executables do not
need relocation, and neither do proxy objects.) */
assert (l->l_real->l_relocated || l->l_real->l_type == lt_executable);
need relocation.) */
assert (l->l_relocated || l->l_type == lt_executable);
if (l->l_init_called)
/* This object is all done. */
+4 -4
View File
@@ -405,7 +405,7 @@ update_tls_slotinfo (struct link_map *new)
_dl_fatal_printf (N_("\
TLS generation counter wrapped! Please report this."));
/* Can be read concurrently. */
atomic_store_relaxed (&GL(dl_tls_generation), newgen);
atomic_store_release (&GL(dl_tls_generation), newgen);
/* We need a second pass for static tls data, because
_dl_update_slotinfo must not be run while calls to
@@ -422,8 +422,8 @@ TLS generation counter wrapped! Please report this."));
now, but we can delay updating the DTV. */
imap->l_need_tls_init = 0;
#ifdef SHARED
/* Update the slot information data for at least the
generation of the DSO we are allocating data for. */
/* Update the slot information data for the current
generation. */
/* FIXME: This can terminate the process on memory
allocation failure. It is not possible to raise
@@ -431,7 +431,7 @@ TLS generation counter wrapped! Please report this."));
_dl_update_slotinfo would have to be split into two
operations, similar to resize_scopes and update_scopes
above. This is related to bug 16134. */
_dl_update_slotinfo (imap->l_tls_modid);
_dl_update_slotinfo (imap->l_tls_modid, newgen);
#endif
dl_init_static_tls (imap);
+3 -3
View File
@@ -112,11 +112,11 @@ _dl_try_allocate_static_tls (struct link_map *map, bool optional)
if (map->l_real->l_relocated)
{
#ifdef SHARED
/* Update the DTV of the current thread. Note: GL(dl_load_tls_lock)
is held here so normal load of the generation counter is valid. */
if (__builtin_expect (THREAD_DTV()[0].counter != GL(dl_tls_generation),
0))
/* Update the slot information data for at least the generation of
the DSO we are allocating data for. */
(void) _dl_update_slotinfo (map->l_tls_modid);
(void) _dl_update_slotinfo (map->l_tls_modid, GL(dl_tls_generation));
#endif
dl_init_static_tls (map);
+3 -2
View File
@@ -139,7 +139,7 @@ _dl_fixup (
unsigned int init = atomic_load_acquire (&reloc_result->init);
if (init == 0)
{
_dl_audit_symbind (l, reloc_result, sym, &value, result);
_dl_audit_symbind (l, reloc_result, reloc, sym, &value, result, true);
/* Store the result for later runs. */
if (__glibc_likely (! GLRO(dl_bind_not)))
@@ -314,7 +314,8 @@ _dl_profile_fixup (
auditing libraries the possibility to change the value and
tell us whether further auditing is wanted. */
if (defsym != NULL && GLRO(dl_naudit) > 0)
_dl_audit_symbind (l, reloc_result, defsym, &value, result);
_dl_audit_symbind (l, reloc_result, reloc, defsym, &value, result,
true);
#endif
/* Store the result for later runs. */
+16 -21
View File
@@ -286,8 +286,6 @@ _dl_non_dynamic_init (void)
_dl_main_map.l_phdr = GL(dl_phdr);
_dl_main_map.l_phnum = GL(dl_phnum);
_dl_verbose = *(getenv ("LD_WARN") ?: "") == '\0' ? 0 : 1;
/* Set up the data structures for the system-supplied DSO early,
so they can influence _dl_init_paths. */
setup_vdso (NULL, NULL);
@@ -295,6 +293,22 @@ _dl_non_dynamic_init (void)
/* With vDSO setup we can initialize the function pointers. */
setup_vdso_pointers ();
if (__libc_enable_secure)
{
static const char unsecure_envvars[] =
UNSECURE_ENVVARS
;
const char *cp = unsecure_envvars;
while (cp < unsecure_envvars + sizeof (unsecure_envvars))
{
__unsetenv (cp);
cp = strchr (cp, '\0') + 1;
}
}
_dl_verbose = *(getenv ("LD_WARN") ?: "") == '\0' ? 0 : 1;
/* Initialize the data structures for the search paths for shared
objects. */
_dl_init_paths (getenv ("LD_LIBRARY_PATH"), "LD_LIBRARY_PATH",
@@ -316,25 +330,6 @@ _dl_non_dynamic_init (void)
_dl_profile_output
= &"/var/tmp\0/var/profile"[__libc_enable_secure ? 9 : 0];
if (__libc_enable_secure)
{
static const char unsecure_envvars[] =
UNSECURE_ENVVARS
;
const char *cp = unsecure_envvars;
while (cp < unsecure_envvars + sizeof (unsecure_envvars))
{
__unsetenv (cp);
cp = (const char *) __rawmemchr (cp, '\0') + 1;
}
#if !HAVE_TUNABLES
if (__access ("/etc/suid-debug", F_OK) != 0)
__unsetenv ("MALLOC_CHECK_");
#endif
}
#ifdef DL_PLATFORM_INIT
DL_PLATFORM_INIT;
#endif
+152 -60
View File
@@ -75,6 +75,31 @@
/* Default for dl_tls_static_optional. */
#define OPTIONAL_TLS 512
/* Used to count the number of threads currently executing dynamic TLS
updates. Used to avoid recursive malloc calls in __tls_get_addr
for an interposed malloc that uses global-dynamic TLS (which is not
recommended); see _dl_tls_allocate_active checks. This could be a
per-thread flag, but would need TLS access in the dynamic linker. */
unsigned int _dl_tls_threads_in_update;
static inline void
_dl_tls_allocate_begin (void)
{
atomic_fetch_add_relaxed (&_dl_tls_threads_in_update, 1);
}
static inline void
_dl_tls_allocate_end (void)
{
atomic_fetch_add_relaxed (&_dl_tls_threads_in_update, -1);
}
static inline bool
_dl_tls_allocate_active (void)
{
return atomic_load_relaxed (&_dl_tls_threads_in_update) > 0;
}
/* Compute the static TLS surplus based on the namespace count and the
TLS space that can be used for optimizations. */
static inline int
@@ -160,6 +185,7 @@ _dl_assign_tls_modid (struct link_map *l)
{
/* Mark the entry as used, so any dependency see it. */
atomic_store_relaxed (&runp->slotinfo[result - disp].map, l);
atomic_store_relaxed (&runp->slotinfo[result - disp].gen, 0);
break;
}
@@ -430,12 +456,18 @@ _dl_allocate_tls_storage (void)
size += TLS_PRE_TCB_SIZE;
#endif
/* Perform the allocation. Reserve space for the required alignment
and the pointer to the original allocation. */
/* Reserve space for the required alignment and the pointer to the
original allocation. */
size_t alignment = GLRO (dl_tls_static_align);
/* Perform the allocation. */
_dl_tls_allocate_begin ();
void *allocated = malloc (size + alignment + sizeof (void *));
if (__glibc_unlikely (allocated == NULL))
return NULL;
{
_dl_tls_allocate_end ();
return NULL;
}
/* Perform alignment and allocate the DTV. */
#if TLS_TCB_AT_TP
@@ -471,6 +503,8 @@ _dl_allocate_tls_storage (void)
result = allocate_dtv (result);
if (result == NULL)
free (allocated);
_dl_tls_allocate_end ();
return result;
}
@@ -488,6 +522,7 @@ _dl_resize_dtv (dtv_t *dtv, size_t max_modid)
size_t newsize = max_modid + DTV_SURPLUS;
size_t oldsize = dtv[-1].counter;
_dl_tls_allocate_begin ();
if (dtv == GL(dl_initial_dtv))
{
/* This is the initial dtv that was either statically allocated in
@@ -507,6 +542,7 @@ _dl_resize_dtv (dtv_t *dtv, size_t max_modid)
if (newp == NULL)
oom ();
}
_dl_tls_allocate_end ();
newp[0].counter = newsize;
@@ -681,7 +717,9 @@ allocate_dtv_entry (size_t alignment, size_t size)
if (powerof2 (alignment) && alignment <= _Alignof (max_align_t))
{
/* The alignment is supported by malloc. */
_dl_tls_allocate_begin ();
void *ptr = malloc (size);
_dl_tls_allocate_end ();
return (struct dtv_pointer) { ptr, ptr };
}
@@ -693,7 +731,10 @@ allocate_dtv_entry (size_t alignment, size_t size)
/* Perform the allocation. This is the pointer we need to free
later. */
_dl_tls_allocate_begin ();
void *start = malloc (alloc_size);
_dl_tls_allocate_end ();
if (start == NULL)
return (struct dtv_pointer) {};
@@ -721,57 +762,57 @@ allocate_and_init (struct link_map *map)
struct link_map *
_dl_update_slotinfo (unsigned long int req_modid)
_dl_update_slotinfo (unsigned long int req_modid, size_t new_gen)
{
struct link_map *the_map = NULL;
dtv_t *dtv = THREAD_DTV ();
/* The global dl_tls_dtv_slotinfo array contains for each module
index the generation counter current when the entry was created.
/* CONCURRENCY NOTES:
The global dl_tls_dtv_slotinfo_list array contains for each module
index the generation counter current when that entry was updated.
This array never shrinks so that all module indices which were
valid at some time can be used to access it. Before the first
use of a new module index in this function the array was extended
appropriately. Access also does not have to be guarded against
modifications of the array. It is assumed that pointer-size
values can be read atomically even in SMP environments. It is
possible that other threads at the same time dynamically load
code and therefore add to the slotinfo list. This is a problem
since we must not pick up any information about incomplete work.
The solution to this is to ignore all dtv slots which were
created after the one we are currently interested. We know that
dynamic loading for this module is completed and this is the last
load operation we know finished. */
unsigned long int idx = req_modid;
valid at some time can be used to access it. Concurrent loading
and unloading of modules can update slotinfo entries or extend
the array. The updates happen under the GL(dl_load_tls_lock) and
finish with the release store of the generation counter to
GL(dl_tls_generation) which is synchronized with the load of
new_gen in the caller. So updates up to new_gen are synchronized
but updates for later generations may not be.
Here we update the thread dtv from old_gen (== dtv[0].counter) to
new_gen generation. For this, each dtv[i] entry is either set to
an unallocated state (set), or left unmodified (nop). Where (set)
may resize the dtv first if modid i >= dtv[-1].counter. The rules
for the decision between (set) and (nop) are
(1) If slotinfo entry i is concurrently updated then either (set)
or (nop) is valid: TLS access cannot use dtv[i] unless it is
synchronized with a generation > new_gen.
Otherwise, if the generation of slotinfo entry i is gen and the
loaded module for this entry is map then
(2) If gen <= old_gen then do (nop).
(3) If old_gen < gen <= new_gen then
(3.1) if map != 0 then (set)
(3.2) if map == 0 then either (set) or (nop).
Note that (1) cannot be reliably detected, but since both actions
are valid it does not have to be. Only (2) and (3.1) cases need
to be distinguished for which relaxed mo access of gen and map is
enough: their value is synchronized when it matters.
Note that a relaxed mo load may give an out-of-thin-air value since
it is used in decisions that can affect concurrent stores. But this
should only happen if the OOTA value causes UB that justifies the
concurrent store of the value. This is not expected to be an issue
in practice. */
struct dtv_slotinfo_list *listp = GL(dl_tls_dtv_slotinfo_list);
while (idx >= listp->len)
if (dtv[0].counter < new_gen)
{
idx -= listp->len;
listp = listp->next;
}
if (dtv[0].counter < listp->slotinfo[idx].gen)
{
/* CONCURRENCY NOTES:
Here the dtv needs to be updated to new_gen generation count.
This code may be called during TLS access when GL(dl_load_tls_lock)
is not held. In that case the user code has to synchronize with
dlopen and dlclose calls of relevant modules. A module m is
relevant if the generation of m <= new_gen and dlclose of m is
synchronized: a memory access here happens after the dlopen and
before the dlclose of relevant modules. The dtv entries for
relevant modules need to be updated, other entries can be
arbitrary.
This e.g. means that the first part of the slotinfo list can be
accessed race free, but the tail may be concurrently extended.
Similarly relevant slotinfo entries can be read race free, but
other entries are racy. However updating a non-relevant dtv
entry does not affect correctness. For a relevant module m,
max_modid >= modid of m. */
size_t new_gen = listp->slotinfo[idx].gen;
size_t total = 0;
size_t max_modid = atomic_load_relaxed (&GL(dl_tls_max_dtv_idx));
assert (max_modid >= req_modid);
@@ -784,31 +825,33 @@ _dl_update_slotinfo (unsigned long int req_modid)
{
size_t modid = total + cnt;
/* Later entries are not relevant. */
/* Case (1) for all later modids. */
if (modid > max_modid)
break;
size_t gen = atomic_load_relaxed (&listp->slotinfo[cnt].gen);
/* Case (1). */
if (gen > new_gen)
/* Not relevant. */
continue;
/* If the entry is older than the current dtv layout we
know we don't have to handle it. */
/* Case (2) or (1). */
if (gen <= dtv[0].counter)
continue;
/* Case (3) or (1). */
/* If there is no map this means the entry is empty. */
struct link_map *map
= atomic_load_relaxed (&listp->slotinfo[cnt].map);
/* Check whether the current dtv array is large enough. */
if (dtv[-1].counter < modid)
{
/* Case (3.2) or (1). */
if (map == NULL)
continue;
/* Resize the dtv. */
/* Resizing the dtv aborts on failure: bug 16134. */
dtv = _dl_resize_dtv (dtv, max_modid);
assert (modid <= dtv[-1].counter);
@@ -819,10 +862,21 @@ _dl_update_slotinfo (unsigned long int req_modid)
}
/* If there is currently memory allocate for this
dtv entry free it. */
dtv entry free it. Note: this is not AS-safe. */
/* XXX Ideally we will at some point create a memory
pool. */
free (dtv[modid].pointer.to_free);
/* Avoid calling free on a null pointer. Some mallocs
incorrectly use dynamic TLS, and depending on how the
free function was compiled, it could call
__tls_get_addr before the null pointer check in the
free implementation. Checking here papers over at
least some dynamic TLS usage by interposed mallocs. */
if (dtv[modid].pointer.to_free != NULL)
{
_dl_tls_allocate_begin ();
free (dtv[modid].pointer.to_free);
_dl_tls_allocate_end ();
}
dtv[modid].pointer.val = TLS_DTV_UNALLOCATED;
dtv[modid].pointer.to_free = NULL;
@@ -914,9 +968,9 @@ tls_get_addr_tail (GET_ADDR_ARGS, dtv_t *dtv, struct link_map *the_map)
static struct link_map *
__attribute_noinline__
update_get_addr (GET_ADDR_ARGS)
update_get_addr (GET_ADDR_ARGS, size_t gen)
{
struct link_map *the_map = _dl_update_slotinfo (GET_ADDR_MODULE);
struct link_map *the_map = _dl_update_slotinfo (GET_ADDR_MODULE, gen);
dtv_t *dtv = THREAD_DTV ();
void *p = dtv[GET_ADDR_MODULE].pointer.val;
@@ -946,12 +1000,29 @@ __tls_get_addr (GET_ADDR_ARGS)
dtv_t *dtv = THREAD_DTV ();
/* Update is needed if dtv[0].counter < the generation of the accessed
module. The global generation counter is used here as it is easier
to check. Synchronization for the relaxed MO access is guaranteed
by user code, see CONCURRENCY NOTES in _dl_update_slotinfo. */
module, but the global generation counter is easier to check (which
must be synchronized up to the generation of the accessed module by
user code doing the TLS access so relaxed mo read is enough). */
size_t gen = atomic_load_relaxed (&GL(dl_tls_generation));
if (__glibc_unlikely (dtv[0].counter != gen))
return update_get_addr (GET_ADDR_PARAM);
{
if (_dl_tls_allocate_active ()
&& GET_ADDR_MODULE < _dl_tls_initial_modid_limit)
/* This is a reentrant __tls_get_addr call, but we can
satisfy it because it's an initially-loaded module ID.
These TLS slotinfo slots do not change, so the
out-of-date generation counter does not matter. However,
if not in a TLS update, still update_get_addr below, to
get off the slow path eventually. */
;
else
{
/* Update DTV up to the global generation, see CONCURRENCY NOTES
in _dl_update_slotinfo. */
gen = atomic_load_acquire (&GL(dl_tls_generation));
return update_get_addr (GET_ADDR_PARAM, gen);
}
}
void *p = dtv[GET_ADDR_MODULE].pointer.val;
@@ -960,7 +1031,7 @@ __tls_get_addr (GET_ADDR_ARGS)
return (char *) p + GET_ADDR_OFFSET;
}
#endif
#endif /* SHARED */
/* Look up the module's TLS block as for __tls_get_addr,
@@ -1009,6 +1080,25 @@ _dl_tls_get_addr_soft (struct link_map *l)
return data;
}
size_t _dl_tls_initial_modid_limit;
void
_dl_tls_initial_modid_limit_setup (void)
{
struct dtv_slotinfo_list *listp = GL(dl_tls_dtv_slotinfo_list);
size_t idx;
for (idx = 0; idx < listp->len; ++idx)
{
struct link_map *l = listp->slotinfo[idx].map;
if (l == NULL
/* The object can be unloaded, so its modid can be
reassociated. */
|| !(l->l_type == lt_executable || l->l_type == lt_library))
break;
}
_dl_tls_initial_modid_limit = idx;
}
void
_dl_add_to_slotinfo (struct link_map *l, bool do_add)
@@ -1041,9 +1131,11 @@ _dl_add_to_slotinfo (struct link_map *l, bool do_add)
the first slot. */
assert (idx == 0);
_dl_tls_allocate_begin ();
listp = (struct dtv_slotinfo_list *)
malloc (sizeof (struct dtv_slotinfo_list)
+ TLS_SLOTINFO_SURPLUS * sizeof (struct dtv_slotinfo));
_dl_tls_allocate_end ();
if (listp == NULL)
{
/* We ran out of memory while resizing the dtv slotinfo list. */
+10 -7
View File
@@ -187,11 +187,7 @@ parse_tunables (char *tunestr, char *valstring)
/* If we reach the end of the string before getting a valid name-value
pair, bail out. */
if (p[len] == '\0')
{
if (__libc_enable_secure)
tunestr[off] = '\0';
return;
}
break;
/* We did not find a valid name-value pair before encountering the
colon. */
@@ -251,9 +247,16 @@ parse_tunables (char *tunestr, char *valstring)
}
}
if (p[len] != '\0')
p += len + 1;
/* We reached the end while processing the tunable string. */
if (p[len] == '\0')
break;
p += len + 1;
}
/* Terminate tunestr before we leave. */
if (__libc_enable_secure)
tunestr[off] = '\0';
}
#endif
+13
View File
@@ -170,4 +170,17 @@ glibc {
default: 2
}
}
gmon {
minarcs {
type: INT_32
minval: 50
default: 50
}
maxarcs {
type: INT_32
minval: 50
default: 1048576
}
}
}
+4 -2
View File
@@ -154,7 +154,8 @@ elf_dynamic_do_Rel (struct link_map *map, struct r_scope_elem *scope[],
= RESOLVE_MAP (map, scope, &sym, rversion,
ELF_MACHINE_JMP_SLOT);
if (sym != NULL)
_dl_audit_symbind (map, NULL, sym, r_addr_arg, sym_map);
_dl_audit_symbind (map, NULL, r, sym, r_addr_arg, sym_map,
false);
}
#endif
}
@@ -200,7 +201,8 @@ elf_dynamic_do_Rel (struct link_map *map, struct r_scope_elem *scope[],
(struct r_found_version *) NULL,
ELF_MACHINE_JMP_SLOT);
if (sym != NULL)
_dl_audit_symbind (map, NULL , sym,r_addr_arg, sym_map);
_dl_audit_symbind (map, NULL, r, sym,r_addr_arg, sym_map,
false);
}
# endif
}
+43
View File
@@ -1223,6 +1223,9 @@ typedef struct
#define AT_HWCAP2 26 /* More machine-dependent hints about
processor capabilities. */
#define AT_RSEQ_FEATURE_SIZE 27 /* rseq supported feature size. */
#define AT_RSEQ_ALIGN 28 /* rseq allocation alignment. */
#define AT_EXECFN 31 /* Filename of executable. */
/* Pointer to the global system page used for system calls and other
@@ -4159,6 +4162,46 @@ enum
#define R_LARCH_GNU_VTINHERIT 57
#define R_LARCH_GNU_VTENTRY 58
/* reserved 59-63 */
#define R_LARCH_B16 64
#define R_LARCH_B21 65
#define R_LARCH_B26 66
#define R_LARCH_ABS_HI20 67
#define R_LARCH_ABS_LO12 68
#define R_LARCH_ABS64_LO20 69
#define R_LARCH_ABS64_HI12 70
#define R_LARCH_PCALA_HI20 71
#define R_LARCH_PCALA_LO12 72
#define R_LARCH_PCALA64_LO20 73
#define R_LARCH_PCALA64_HI12 74
#define R_LARCH_GOT_PC_HI20 75
#define R_LARCH_GOT_PC_LO12 76
#define R_LARCH_GOT64_PC_LO20 77
#define R_LARCH_GOT64_PC_HI12 78
#define R_LARCH_GOT_HI20 79
#define R_LARCH_GOT_LO12 80
#define R_LARCH_GOT64_LO20 81
#define R_LARCH_GOT64_HI12 82
#define R_LARCH_TLS_LE_HI20 83
#define R_LARCH_TLS_LE_LO12 84
#define R_LARCH_TLS_LE64_LO20 85
#define R_LARCH_TLS_LE64_HI12 86
#define R_LARCH_TLS_IE_PC_HI20 87
#define R_LARCH_TLS_IE_PC_LO12 88
#define R_LARCH_TLS_IE64_PC_LO20 89
#define R_LARCH_TLS_IE64_PC_HI12 90
#define R_LARCH_TLS_IE_HI20 91
#define R_LARCH_TLS_IE_LO12 92
#define R_LARCH_TLS_IE64_LO20 93
#define R_LARCH_TLS_IE64_HI12 94
#define R_LARCH_TLS_LD_PC_HI20 95
#define R_LARCH_TLS_LD_HI20 96
#define R_LARCH_TLS_GD_PC_HI20 97
#define R_LARCH_TLS_GD_HI20 98
#define R_LARCH_32_PCREL 99
#define R_LARCH_RELAX 100
/* ARC specific declarations. */
/* Processor specific flags for the Ehdr e_flags field. */
+2 -2
View File
@@ -616,7 +616,7 @@ manual_link (char *library)
goto out;
}
if (soname == NULL)
soname = implicit_soname (libname, flag);
soname = xstrdup (libname);
create_links (real_path, path, libname, soname);
free (soname);
out:
@@ -849,7 +849,7 @@ search_dir (const struct dir_entry *entry)
}
if (soname == NULL)
soname = implicit_soname (direntry->d_name, flag);
soname = xstrdup (direntry->d_name);
/* A link may just point to itself. */
if (is_link)
+1
View File
@@ -107,6 +107,7 @@ process_elf_file (const char *file_name, const char *lib, int *flag,
case PT_INTERP:
program_interpreter = (char *) (file_contents + segment->p_offset);
check_ptr (program_interpreter);
break;
case PT_GNU_PROPERTY:
/* The NT_GNU_PROPERTY_TYPE_0 note must be aligned to 4 bytes
-19
View File
@@ -166,24 +166,5 @@ process_file (const char *real_file_name, const char *file_name,
return ret;
}
/* Returns made up soname if lib doesn't have explicit DT_SONAME. */
char *
implicit_soname (const char *lib, int flag)
{
char *soname = xstrdup (lib);
/* Aout files don't have a soname, just return the name
including the major number. */
char *major = strstr (soname, ".so.");
if (major)
{
char *dot = strstr (major + 4, ".");
if (dot)
*dot = '\0';
}
return soname;
}
/* Get architecture specific version of process_elf_file. */
#include <readelflib.c>
+57 -27
View File
@@ -792,6 +792,8 @@ init_tls (size_t naudit)
_dl_fatal_printf ("\
cannot allocate TLS data structures for initial thread\n");
_dl_tls_initial_modid_limit_setup ();
/* Store for detection of the special case by __tls_get_addr
so it knows not to pass this dtv to the normal realloc. */
GL(dl_initial_dtv) = GET_DTV (tcbp);
@@ -1291,6 +1293,60 @@ rtld_setup_main_map (struct link_map *main_map)
return has_interp;
}
/* Set up the program header information for the dynamic linker
itself. It can be accessed via _r_debug and dl_iterate_phdr
callbacks, and it is used by _dl_find_object. */
static void
rtld_setup_phdr (void)
{
/* Starting from binutils-2.23, the linker will define the magic
symbol __ehdr_start to point to our own ELF header if it is
visible in a segment that also includes the phdrs. */
const ElfW(Ehdr) *rtld_ehdr = &__ehdr_start;
assert (rtld_ehdr->e_ehsize == sizeof *rtld_ehdr);
assert (rtld_ehdr->e_phentsize == sizeof (ElfW(Phdr)));
const ElfW(Phdr) *rtld_phdr = (const void *) rtld_ehdr + rtld_ehdr->e_phoff;
GL(dl_rtld_map).l_phdr = rtld_phdr;
GL(dl_rtld_map).l_phnum = rtld_ehdr->e_phnum;
GL(dl_rtld_map).l_contiguous = 1;
/* The linker may not have produced a contiguous object. The kernel
will load the object with actual gaps (unlike the glibc loader
for shared objects, which always produces a contiguous mapping).
See similar logic in rtld_setup_main_map above. */
{
ElfW(Addr) expected_load_address = 0;
for (const ElfW(Phdr) *ph = rtld_phdr; ph < &rtld_phdr[rtld_ehdr->e_phnum];
++ph)
if (ph->p_type == PT_LOAD)
{
ElfW(Addr) mapstart = ph->p_vaddr & ~(GLRO(dl_pagesize) - 1);
if (GL(dl_rtld_map).l_contiguous && expected_load_address != 0
&& expected_load_address != mapstart)
GL(dl_rtld_map).l_contiguous = 0;
ElfW(Addr) allocend = ph->p_vaddr + ph->p_memsz;
/* The next expected address is the page following this load
segment. */
expected_load_address = ((allocend + GLRO(dl_pagesize) - 1)
& ~(GLRO(dl_pagesize) - 1));
}
}
/* PT_GNU_RELRO is usually the last phdr. */
size_t cnt = rtld_ehdr->e_phnum;
while (cnt-- > 0)
if (rtld_phdr[cnt].p_type == PT_GNU_RELRO)
{
GL(dl_rtld_map).l_relro_addr = rtld_phdr[cnt].p_vaddr;
GL(dl_rtld_map).l_relro_size = rtld_phdr[cnt].p_memsz;
break;
}
}
/* Adjusts the contents of the stack and related globals for the user
entry point. The ld.so processed skip_args arguments and bumped
_dl_argv and _dl_argc accordingly. Those arguments are removed from
@@ -1760,33 +1816,7 @@ dl_main (const ElfW(Phdr) *phdr,
++GL(dl_ns)[LM_ID_BASE]._ns_nloaded;
++GL(dl_load_adds);
/* Starting from binutils-2.23, the linker will define the magic symbol
__ehdr_start to point to our own ELF header if it is visible in a
segment that also includes the phdrs. If that's not available, we use
the old method that assumes the beginning of the file is part of the
lowest-addressed PT_LOAD segment. */
/* Set up the program header information for the dynamic linker
itself. It is needed in the dl_iterate_phdr callbacks. */
const ElfW(Ehdr) *rtld_ehdr = &__ehdr_start;
assert (rtld_ehdr->e_ehsize == sizeof *rtld_ehdr);
assert (rtld_ehdr->e_phentsize == sizeof (ElfW(Phdr)));
const ElfW(Phdr) *rtld_phdr = (const void *) rtld_ehdr + rtld_ehdr->e_phoff;
GL(dl_rtld_map).l_phdr = rtld_phdr;
GL(dl_rtld_map).l_phnum = rtld_ehdr->e_phnum;
/* PT_GNU_RELRO is usually the last phdr. */
size_t cnt = rtld_ehdr->e_phnum;
while (cnt-- > 0)
if (rtld_phdr[cnt].p_type == PT_GNU_RELRO)
{
GL(dl_rtld_map).l_relro_addr = rtld_phdr[cnt].p_vaddr;
GL(dl_rtld_map).l_relro_size = rtld_phdr[cnt].p_memsz;
break;
}
rtld_setup_phdr ();
/* Add the dynamic linker to the TLS list if it also uses TLS. */
if (GL(dl_rtld_map).l_tls_blocksize != 0)
+11
View File
@@ -71,6 +71,17 @@ la_version (unsigned int current)
TEST_VERIFY (dladdr1 (&_exit, &info, &extra_info, RTLD_DL_LINKMAP) != 0);
TEST_VERIFY (extra_info == handle);
/* Check _dl_find_object. */
struct dl_find_object dlfo;
TEST_COMPARE (_dl_find_object (__builtin_return_address (0), &dlfo), 0);
/* "ld.so" is seen with --enable-hardcoded-path-in-tests. */
if (strcmp (basename (dlfo.dlfo_link_map->l_name), "ld.so") != 0)
TEST_COMPARE_STRING (basename (dlfo.dlfo_link_map->l_name), LD_SO);
TEST_COMPARE (_dl_find_object (dlsym (handle, "environ"), &dlfo), 0);
TEST_COMPARE_STRING (basename (dlfo.dlfo_link_map->l_name), LIBC_SO);
TEST_COMPARE (_dl_find_object ((void *) 1, &dlfo), -1);
TEST_COMPARE (_dl_find_object ((void *) -1, &dlfo), -1);
/* Verify that dlmopen creates a new namespace. */
void *dlmopen_handle = xdlmopen (LM_ID_NEWLM, LIBC_SO, RTLD_NOW);
TEST_VERIFY (dlmopen_handle != handle);
+1
View File
@@ -0,0 +1 @@
/* Opening this object should not succeed. */
+106
View File
@@ -0,0 +1,106 @@
/* Test case for ignored LD_LIBRARY_PATH in static startug (bug 32976).
Copyright (C) 2025 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
#include <dlfcn.h>
#include <gnu/lib-names.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <support/capture_subprocess.h>
#include <support/check.h>
#include <support/support.h>
#include <support/temp_file.h>
#include <support/test-driver.h>
#include <sys/wait.h>
#include <unistd.h>
/* This is the name of our test object. Use a custom module for
testing, so that this object does not get picked up from the system
path. */
static const char dso_name[] = "tst-dlopen-sgid-mod.so";
/* Used to mark the recursive invocation. */
static const char magic_argument[] = "run-actual-test";
static int
do_test (void)
{
/* Pathname of the directory that receives the shared objects this
test attempts to load. */
char *libdir = support_create_temp_directory ("tst-dlopen-sgid-");
/* This is supposed to be ignored and stripped. */
TEST_COMPARE (setenv ("LD_LIBRARY_PATH", libdir, 1), 0);
/* Copy of libc.so.6. */
{
char *from = xasprintf ("%s/%s", support_objdir_root, LIBC_SO);
char *to = xasprintf ("%s/%s", libdir, LIBC_SO);
add_temp_file (to);
support_copy_file (from, to);
free (to);
free (from);
}
/* Copy of the test object. */
{
char *from = xasprintf ("%s/elf/%s", support_objdir_root, dso_name);
char *to = xasprintf ("%s/%s", libdir, dso_name);
add_temp_file (to);
support_copy_file (from, to);
free (to);
free (from);
}
free (libdir);
support_capture_subprogram_self_sgid (magic_argument);
return 0;
}
static void
alternative_main (int argc, char **argv)
{
if (argc == 2 && strcmp (argv[1], magic_argument) == 0)
{
if (getgid () == getegid ())
/* This can happen if the file system is mounted nosuid. */
FAIL_UNSUPPORTED ("SGID failed: GID and EGID match (%jd)\n",
(intmax_t) getgid ());
/* Should be removed due to SGID. */
TEST_COMPARE_STRING (getenv ("LD_LIBRARY_PATH"), NULL);
TEST_VERIFY (dlopen (dso_name, RTLD_NOW) == NULL);
{
const char *message = dlerror ();
TEST_COMPARE_STRING (message,
"tst-dlopen-sgid-mod.so:"
" cannot open shared object file:"
" No such file or directory");
}
support_record_failure_barrier ();
exit (EXIT_SUCCESS);
}
}
#define PREPARE alternative_main
#include <support/test-driver.c>
+22 -15
View File
@@ -52,6 +52,8 @@ const char *teststrings[] =
"glibc.malloc.perturb=0x800:not_valid.malloc.check=2:glibc.malloc.mmap_threshold=4096",
"glibc.not_valid.check=2:glibc.malloc.mmap_threshold=4096",
"not_valid.malloc.check=2:glibc.malloc.mmap_threshold=4096",
"glibc.malloc.mmap_threshold=glibc.malloc.mmap_threshold=4096",
"glibc.malloc.check=2",
"glibc.malloc.garbage=2:glibc.maoc.mmap_threshold=4096:glibc.malloc.check=2",
"glibc.malloc.check=4:glibc.malloc.garbage=2:glibc.maoc.mmap_threshold=4096",
":glibc.malloc.garbage=2:glibc.malloc.check=1",
@@ -70,6 +72,8 @@ const char *resultstrings[] =
"glibc.malloc.perturb=0x800:glibc.malloc.mmap_threshold=4096",
"glibc.malloc.mmap_threshold=4096",
"glibc.malloc.mmap_threshold=4096",
"glibc.malloc.mmap_threshold=glibc.malloc.mmap_threshold=4096",
"",
"",
"",
"",
@@ -84,11 +88,18 @@ test_child (int off)
const char *val = getenv ("GLIBC_TUNABLES");
#if HAVE_TUNABLES
printf (" [%d] GLIBC_TUNABLES is %s\n", off, val);
fflush (stdout);
if (val != NULL && strcmp (val, resultstrings[off]) == 0)
return 0;
if (val != NULL)
printf ("[%d] Unexpected GLIBC_TUNABLES VALUE %s\n", off, val);
printf (" [%d] Unexpected GLIBC_TUNABLES VALUE %s, expected %s\n",
off, val, resultstrings[off]);
else
printf (" [%d] GLIBC_TUNABLES environment variable absent\n", off);
fflush (stdout);
return 1;
#else
@@ -116,32 +127,28 @@ do_test (int argc, char **argv)
if (ret != 0)
exit (1);
exit (EXIT_SUCCESS);
return 0;
}
else
{
int ret = 0;
/* Spawn tests. */
for (int i = 0; i < array_length (teststrings); i++)
{
char buf[INT_BUFSIZE_BOUND (int)];
printf ("Spawned test for %s (%d)\n", teststrings[i], i);
printf ("[%d] Spawned test for %s\n", i, teststrings[i]);
snprintf (buf, sizeof (buf), "%d\n", i);
fflush (stdout);
if (setenv ("GLIBC_TUNABLES", teststrings[i], 1) != 0)
exit (1);
{
printf (" [%d] Failed to set GLIBC_TUNABLES: %m", i);
support_record_failure ();
continue;
}
int status = support_capture_subprogram_self_sgid (buf);
/* Bail out early if unsupported. */
if (WEXITSTATUS (status) == EXIT_UNSUPPORTED)
return EXIT_UNSUPPORTED;
ret |= status;
support_capture_subprogram_self_sgid (buf);
}
return ret;
return 0;
}
}
+2 -8
View File
@@ -104,20 +104,14 @@ do_test (int argc, char **argv)
if (ret != 0)
exit (1);
exit (EXIT_SUCCESS);
return 0;
}
else
{
if (test_parent () != 0)
exit (1);
int status = support_capture_subprogram_self_sgid (SETGID_CHILD);
if (WEXITSTATUS (status) == EXIT_UNSUPPORTED)
return EXIT_UNSUPPORTED;
if (!WIFEXITED (status))
FAIL_EXIT1 ("Unexpected exit status %d from child process\n", status);
support_capture_subprogram_self_sgid (SETGID_CHILD);
return 0;
}
+77
View File
@@ -0,0 +1,77 @@
#!/bin/sh
# Test that ldconfig -p prints something useful.
# Copyright (C) 2023 Free Software Foundation, Inc.
# This file is part of the GNU C Library.
# The GNU C Library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# The GNU C Library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with the GNU C Library; if not, see
# <https://www.gnu.org/licenses/>.
# Check that the newly built ldconfig -p can dump the system
# /etc/ld.so.cache file. This should always work even if the ABIs are
# not compatible, except in a cross-endian build (that presumably
# involves emulation when running ldconfig).
common_objpfx=$1
test_wrapper_env=$2
run_program_env=$3
if ! test -r /etc/ld.so.cache; then
echo "warning: /etc/ld.so.cache does not exist, test skipped"
exit 77
fi
testout="${common_objpfx}elf/tst-ldconfig-p.out"
# Truncate file.
: > "$testout"
${test_wrapper_env} \
${run_program_env} \
${common_objpfx}elf/ldconfig -p \
$testroot/lib >>"$testout" 2>>"$testout"
status=$?
echo "info: ldconfig exit status: $status" >>"$testout"
errors=0
case $status in
(0)
if head -n 1 "$testout" | \
grep -q "libs found in cache \`/etc/ld.so.cache'\$" ; then
echo "info: initial string found" >>"$testout"
else
echo "error: initial string not found" >>"$testout"
errors=1
fi
if grep -q "^ libc\.so\..* => " "$testout"; then
echo "info: libc.so.* string found" >>"$testout"
else
echo "error: libc.so.* string not found" >>"$testout"
errors=1
fi
;;
(1)
if head -n 1 "$testout" | \
grep -q ": Cache file has wrong endianness\.$" ; then
echo "info: cache file has wrong endianess" >> "$testout"
else
echo "error: unexpected ldconfig error message" >> "$testout"
errors=1
fi
;;
(*)
echo "error: unexpected exit status" >> "$testout"
errors=1
;;
esac
exit $errors
@@ -0,0 +1 @@
/* This file intentionally left blank */
@@ -0,0 +1 @@
/* This file intentionally left blank */
+49
View File
@@ -0,0 +1,49 @@
#!/bin/sh
# Test that ldconfig creates symlinks according to the library's soname
# (and in particular, does not create symlinks for libraries without a soname)
# Copyright (C) 2000-2023 Free Software Foundation, Inc.
# Copyright The GNU Toolchain Authors.
# This file is part of the GNU C Library.
# The GNU C Library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# The GNU C Library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with the GNU C Library; if not, see
# <https://www.gnu.org/licenses/>.
set -ex
common_objpfx=$1
test_wrapper_env=$2
run_program_env=$3
testroot="${common_objpfx}elf/bug30125-test-directory"
cleanup () {
rm -rf "$testroot"
}
trap cleanup 0
rm -rf "$testroot"
mkdir -p $testroot/lib
cp "${common_objpfx}elf/tst-ldconfig-soname-lib-with-soname.so" \
$testroot/lib/libtst-ldconfig-soname-lib-with-soname.so.1.2.3
cp "${common_objpfx}elf/tst-ldconfig-soname-lib-without-soname.so" \
$testroot/lib/libtst-ldconfig-soname-lib-without-soname.so.1.2.3
${test_wrapper_env} \
${run_program_env} \
${common_objpfx}elf/ldconfig -vn $testroot/lib
LINKS=$(cd $testroot/lib && find . -type l)
if [ "$LINKS" != "./libtst-ldconfig-soname-lib-with-soname.so.1" ]; then
echo "error: $0 - extra symlinks found"
exit 1
fi
+158
View File
@@ -0,0 +1,158 @@
/* Check that _dl_find_object behavior matches up with gaps.
Copyright (C) 2025 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
#include <dlfcn.h>
#include <gnu/lib-names.h>
#include <inttypes.h>
#include <link.h>
#include <stdbool.h>
#include <stdio.h>
#include <support/check.h>
#include <support/support.h>
#include <support/xdlfcn.h>
#include <support/xunistd.h>
#include <support/xstdio.h>
#include <sys/mman.h>
#include <unistd.h>
/* Slow path in case we cannot find a gap with mmap (when the runtime has
mapped all the pages in the gap for some reason). */
static bool
find_gap_with_proc_self_map (const struct link_map *l)
{
int pagesize = getpagesize ();
support_need_proc ("Reads /proc/self/maps to find gap in ld.so mapping");
/* Parse /proc/self/maps and find all the mappings in the ld.so range
but not from ld.so. */
FILE *f = xfopen ("/proc/self/maps", "r");
char *line = NULL, *path_ldso = NULL;
size_t len;
bool found = false;
while (xgetline (&line, &len, f))
{
uintptr_t from, to;
char *path = NULL;
int r = sscanf (line, "%" SCNxPTR "-%" SCNxPTR "%*s%*s%*s%*s%ms",
&from, &to, &path);
TEST_VERIFY (r == 2 || r == 3);
TEST_COMPARE (from % pagesize, 0);
TEST_COMPARE (to % pagesize, 0);
if (path_ldso == NULL && l->l_map_start == from)
{
TEST_COMPARE (r, 3);
path_ldso = path;
continue;
}
if (from > l->l_map_start && to < l->l_map_end
&& (r == 2 || (path_ldso != NULL && strcmp (path, path_ldso))))
{
if (r == 2)
printf ("info: anonymous mapping found at 0x%" PRIxPTR " - 0x%"
PRIxPTR "\n", from, to);
else
printf ("info: object \"%s\" found at 0x%" PRIxPTR " - 0x%"
PRIxPTR "\n", path, from, to);
found = true;
}
free (path);
}
free (path_ldso);
free (line);
xfclose (f);
return found;
}
static int
do_test (void)
{
struct link_map *l = xdlopen (LD_SO, RTLD_NOW);
if (!l->l_contiguous)
{
puts ("info: ld.so link map is not contiguous");
/* Try to find holes by probing with mmap. */
int pagesize = getpagesize ();
bool gap_found = false;
ElfW(Addr) addr = l->l_map_start;
TEST_COMPARE (addr % pagesize, 0);
while (addr < l->l_map_end)
{
void *expected = (void *) addr;
void *ptr = xmmap (expected, 1, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1);
struct dl_find_object dlfo;
int dlfo_ret = _dl_find_object (expected, &dlfo);
if (ptr == expected)
{
if (dlfo_ret < 0)
{
TEST_COMPARE (dlfo_ret, -1);
printf ("info: hole without mapping data found at %p\n", ptr);
}
else
FAIL ("object \"%s\" found in gap at %p",
dlfo.dlfo_link_map->l_name, ptr);
gap_found = true;
}
else if (dlfo_ret == 0)
{
if ((void *) dlfo.dlfo_link_map != (void *) l)
{
printf ("info: object \"%s\" found at %p\n",
dlfo.dlfo_link_map->l_name, expected);
gap_found = true;
}
}
else
TEST_COMPARE (dlfo_ret, -1);
xmunmap (ptr, 1);
addr += pagesize;
}
if (!gap_found && !find_gap_with_proc_self_map (l))
FAIL ("no ld.so gap found");
}
else
{
puts ("info: ld.so link map is contiguous");
/* Assert that ld.so is truly contiguous in memory. */
volatile long int *p = (volatile long int *) l->l_map_start;
volatile long int *end = (volatile long int *) l->l_map_end;
while (p < end)
{
*p;
++p;
}
}
xdlclose (l);
return 0;
}
#include <support/test-driver.c>
+57
View File
@@ -0,0 +1,57 @@
/* Check that the entire libc.so program image is readable if contiguous.
Copyright (C) 2025 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
#include <gnu/lib-names.h>
#include <link.h>
#include <support/check.h>
#include <support/xdlfcn.h>
#include <support/xunistd.h>
#include <sys/mman.h>
#include <unistd.h>
static int
do_test (void)
{
struct link_map *l = xdlopen (LIBC_SO, RTLD_NOW);
/* The dynamic loader fills holes with PROT_NONE mappings. */
if (!l->l_contiguous)
FAIL_EXIT1 ("libc.so link map is not contiguous");
/* Direct probing does not work because not everything is readable
due to PROT_NONE mappings. */
int pagesize = getpagesize ();
ElfW(Addr) addr = l->l_map_start;
TEST_COMPARE (addr % pagesize, 0);
while (addr < l->l_map_end)
{
void *expected = (void *) addr;
void *ptr = xmmap (expected, 1, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1);
if (ptr == expected)
FAIL ("hole in libc.so memory image after %lu bytes",
(unsigned long int) (addr - l->l_map_start));
xmunmap (ptr, 1);
addr += pagesize;
}
xdlclose (l);
return 0;
}
#include <support/test-driver.c>
+45
View File
@@ -0,0 +1,45 @@
/* Check that the entire main program image is readable if contiguous.
Copyright (C) 2025 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
#include <link.h>
#include <support/check.h>
#include <support/xdlfcn.h>
static int
do_test (void)
{
struct link_map *l = xdlopen ("", RTLD_NOW);
if (!l->l_contiguous)
FAIL_UNSUPPORTED ("main link map is not contiguous");
/* This check only works if the kernel loaded the main program. The
dynamic loader replaces gaps with PROT_NONE mappings, resulting
in faults. */
volatile long int *p = (volatile long int *) l->l_map_start;
volatile long int *end = (volatile long int *) l->l_map_end;
while (p < end)
{
*p;
++p;
}
xdlclose (l);
return 0;
}
#include <support/test-driver.c>
+60
View File
@@ -0,0 +1,60 @@
/* Test with interposed malloc with dynamic TLS.
Copyright (C) 2024 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
#include <array_length.h>
#include <stdio.h>
#include <support/check.h>
#include <support/xdlfcn.h>
/* Defined in tst-recursive-tlsmallocmod.so. */
extern __thread unsigned int malloc_subsytem_counter;
static int
do_test (void)
{
/* 16 is large enough to exercise the DTV resizing case. */
void *handles[16];
for (unsigned int i = 0; i < array_length (handles); ++i)
{
/* Re-use the TLS slot for module 0. */
if (i > 0)
xdlclose (handles[0]);
char soname[30];
snprintf (soname, sizeof (soname), "tst-recursive-tlsmod%u.so", i);
handles[i] = xdlopen (soname, RTLD_NOW);
if (i > 0)
{
handles[0] = xdlopen ("tst-recursive-tlsmod0.so", RTLD_NOW);
int (*fptr) (void) = xdlsym (handles[0], "get_threadvar_0");
/* May trigger TLS storage allocation using malloc. */
TEST_COMPARE (fptr (), 0);
}
}
for (unsigned int i = 0; i < array_length (handles); ++i)
xdlclose (handles[i]);
printf ("info: malloc subsystem calls: %u\n", malloc_subsytem_counter);
TEST_VERIFY (malloc_subsytem_counter > 0);
return 0;
}
#include <support/test-driver.c>
+64
View File
@@ -0,0 +1,64 @@
/* Interposed malloc with dynamic TLS.
Copyright (C) 2024 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
#include <stdlib.h>
#include <dlfcn.h>
__thread unsigned int malloc_subsytem_counter;
static __typeof (malloc) *malloc_fptr;
static __typeof (free) *free_fptr;
static __typeof (calloc) *calloc_fptr;
static __typeof (realloc) *realloc_fptr;
static void __attribute__ ((constructor))
init (void)
{
malloc_fptr = dlsym (RTLD_NEXT, "malloc");
free_fptr = dlsym (RTLD_NEXT, "free");
calloc_fptr = dlsym (RTLD_NEXT, "calloc");
realloc_fptr = dlsym (RTLD_NEXT, "realloc");
}
void *
malloc (size_t size)
{
++malloc_subsytem_counter;
return malloc_fptr (size);
}
void
free (void *ptr)
{
++malloc_subsytem_counter;
return free_fptr (ptr);
}
void *
calloc (size_t a, size_t b)
{
++malloc_subsytem_counter;
return calloc_fptr (a, b);
}
void *
realloc (void *ptr, size_t size)
{
++malloc_subsytem_counter;
return realloc_fptr (ptr, size);
}
+28
View File
@@ -0,0 +1,28 @@
/* Test module with global-dynamic TLS. Used to trigger DTV reallocation.
Copyright (C) 2024 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
/* Compiled with VAR and FUNC set via -D. FUNC requires some
relocation against TLS variable VAR. */
__thread int VAR;
int
FUNC (void)
{
return VAR;
}
+4 -1
View File
@@ -26,6 +26,8 @@
#include <tls.h>
#include <unistd.h>
#include <support/xstdlib.h>
static const char *command;
static bool child;
static uintptr_t stack_chk_guard_copy;
@@ -108,7 +110,8 @@ do_test (void)
dup2 (fds[1], 2);
close (fds[1]);
system (command);
xsystem (command);
exit (0);
}
+22 -1
View File
@@ -1,4 +1,5 @@
# Copyright (C) 1995-2023 Free Software Foundation, Inc.
# Copyright The GNU Toolchain Authors.
# This file is part of the GNU C Library.
# The GNU C Library is free software; you can redistribute it and/or
@@ -25,7 +26,7 @@ include ../Makeconfig
headers := sys/gmon.h sys/gmon_out.h sys/profil.h
routines := gmon mcount profil sprofil prof-freq
tests = tst-sprofil tst-gmon
tests = tst-sprofil tst-gmon tst-mcleanup
ifeq ($(build-profile),yes)
tests += tst-profile-static
tests-static += tst-profile-static
@@ -56,6 +57,14 @@ ifeq ($(run-built-tests),yes)
tests-special += $(objpfx)tst-gmon-gprof.out
endif
CFLAGS-tst-mcleanup.c := -fno-omit-frame-pointer -pg
tst-mcleanup-no-pie = yes
CRT-tst-mcleanup := $(csu-objpfx)g$(start-installed-name)
tst-mcleanup-ENV := GMON_OUT_PREFIX=$(objpfx)tst-mcleanup.data
ifeq ($(run-built-tests),yes)
tests-special += $(objpfx)tst-mcleanup.out
endif
CFLAGS-tst-gmon-static.c := $(PIE-ccflag) -fno-omit-frame-pointer -pg
CRT-tst-gmon-static := $(csu-objpfx)g$(static-start-installed-name)
tst-gmon-static-no-pie = yes
@@ -103,6 +112,18 @@ $(objpfx)tst-gmon.out: clean-tst-gmon-data
clean-tst-gmon-data:
rm -f $(objpfx)tst-gmon.data.*
$(objpfx)tst-mcount-overflow.o: clean-tst-mcount-overflow-data
clean-tst-mcount-overflow-data:
rm -f $(objpfx)tst-mcount-overflow.data.*
$(objpfx)tst-mcount-overflow-check.out: tst-mcount-overflow-check.sh $(objpfx)tst-mcount-overflow.out
$(SHELL) $< $(objpfx)tst-mcount-overflow > $@; \
$(evaluate-test)
$(objpfx)tst-mcleanup.out: clean-tst-mcleanup-data
clean-tst-mcleanup-data:
rm -f $(objpfx)tst-mcleanup.data.*
$(objpfx)tst-gmon-gprof.out: tst-gmon-gprof.sh $(objpfx)tst-gmon.out
$(SHELL) $< $(GPROF) $(objpfx)tst-gmon $(objpfx)tst-gmon.data.* > $@; \
$(evaluate-test)
+31 -12
View File
@@ -97,11 +97,8 @@ __moncontrol (int mode)
{
struct gmonparam *p = &_gmonparam;
/* Don't change the state if we ran into an error. */
if (p->state == GMON_PROF_ERROR)
return;
if (mode)
/* Treat start request as stop if error or gmon not initialized. */
if (mode && p->state != GMON_PROF_ERROR && p->tos != NULL)
{
/* start */
__profil((void *) p->kcount, p->kcountsize, p->lowpc, s_scale);
@@ -111,7 +108,9 @@ __moncontrol (int mode)
{
/* stop */
__profil(NULL, 0, 0, 0);
p->state = GMON_PROF_OFF;
/* Don't change the state if we ran into an error. */
if (p->state != GMON_PROF_ERROR)
p->state = GMON_PROF_OFF;
}
}
libc_hidden_def (__moncontrol)
@@ -124,6 +123,19 @@ __monstartup (u_long lowpc, u_long highpc)
int o;
char *cp;
struct gmonparam *p = &_gmonparam;
long int minarcs, maxarcs;
/* No tunables, we use hardcoded defaults */
minarcs = MINARCS;
maxarcs = MAXARCS;
/*
* If we are incorrectly called twice in a row (without an
* intervening call to _mcleanup), ignore the second call to
* prevent leaking memory.
*/
if (p->tos != NULL)
return;
/*
* round lowpc and highpc to multiples of the density we're using
@@ -132,6 +144,8 @@ __monstartup (u_long lowpc, u_long highpc)
p->lowpc = ROUNDDOWN(lowpc, HISTFRACTION * sizeof(HISTCOUNTER));
p->highpc = ROUNDUP(highpc, HISTFRACTION * sizeof(HISTCOUNTER));
p->textsize = p->highpc - p->lowpc;
/* This looks like a typo, but it's here to align the p->froms
section. */
p->kcountsize = ROUNDUP(p->textsize / HISTFRACTION, sizeof(*p->froms));
p->hashfraction = HASHFRACTION;
p->log_hashfraction = -1;
@@ -142,12 +156,12 @@ __monstartup (u_long lowpc, u_long highpc)
instead of integer division. Precompute shift amount. */
p->log_hashfraction = ffs(p->hashfraction * sizeof(*p->froms)) - 1;
}
p->fromssize = p->textsize / HASHFRACTION;
p->fromssize = ROUNDUP(p->textsize / HASHFRACTION, sizeof(*p->froms));
p->tolimit = p->textsize * ARCDENSITY / 100;
if (p->tolimit < MINARCS)
p->tolimit = MINARCS;
else if (p->tolimit > MAXARCS)
p->tolimit = MAXARCS;
if (p->tolimit < minarcs)
p->tolimit = minarcs;
else if (p->tolimit > maxarcs)
p->tolimit = maxarcs;
p->tossize = p->tolimit * sizeof(struct tostruct);
cp = calloc (p->kcountsize + p->fromssize + p->tossize, 1);
@@ -440,9 +454,14 @@ _mcleanup (void)
{
__moncontrol (0);
if (_gmonparam.state != GMON_PROF_ERROR)
if (_gmonparam.state != GMON_PROF_ERROR && _gmonparam.tos != NULL)
write_gmon ();
/* free the memory. */
free (_gmonparam.tos);
/* reset buffer to initial state for safety */
memset(&_gmonparam, 0, sizeof _gmonparam);
/* somewhat confusingly, ON=0, OFF=3 */
_gmonparam.state = GMON_PROF_OFF;
}
+5
View File
@@ -41,6 +41,10 @@ static char sccsid[] = "@(#)mcount.c 8.1 (Berkeley) 6/4/93";
#include <atomic.h>
#include <not-cancel.h>
#include <unistd.h>
#define ERR(s) __write_nocancel (STDERR_FILENO, s, sizeof (s) - 1)
/*
* mcount is called on entry to each function compiled with the profiling
* switch set. _mcount(), which is declared in a machine-dependent way
@@ -170,6 +174,7 @@ done:
return;
overflow:
p->state = GMON_PROF_ERROR;
ERR("mcount: call graph buffer size limit exceeded, gmon.out will not be generated\n");
return;
}
+4 -2
View File
@@ -111,6 +111,8 @@ extern struct __bb *__bb_head;
* Always allocate at least this many tostructs. This
* hides the inadequacy of the ARCDENSITY heuristic, at least
* for small programs.
*
* Value can be overridden at runtime by glibc.gmon.minarcs tunable.
*/
#define MINARCS 50
@@ -124,8 +126,8 @@ extern struct __bb *__bb_head;
* Used to be max representable value of ARCINDEX minus 2, but now
* that ARCINDEX is a long, that's too large; we don't really want
* to allow a 48 gigabyte table.
* The old value of 1<<16 wasn't high enough in practice for large C++
* programs; will 1<<20 be adequate for long? FIXME
*
* Value can be overridden at runtime by glibc.gmon.maxarcs tunable.
*/
#define MAXARCS (1 << 20)
+31
View File
@@ -0,0 +1,31 @@
/* Test program for repeated invocation of _mcleanup
Copyright The GNU Toolchain Authors.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
/* Intentionally calls _mcleanup() twice: once manually, it will be
called again as an atexit handler. This is incorrect use of the API,
but the point of the test is to make sure we don't crash when the
API is misused in this way. */
#include <sys/gmon.h>
int
main (void)
{
_mcleanup();
return 0;
}
+45
View File
@@ -0,0 +1,45 @@
#!/bin/sh
# Test expected messages generated when mcount overflows
# Copyright (C) 2017-2023 Free Software Foundation, Inc.
# Copyright The GNU Toolchain Authors.
# This file is part of the GNU C Library.
# The GNU C Library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# The GNU C Library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public
# License along with the GNU C Library; if not, see
# <https://www.gnu.org/licenses/>.
LC_ALL=C
export LC_ALL
set -e
exec 2>&1
program="$1"
check_msg() {
if ! grep -q "$1" "$program.out"; then
echo "FAIL: expected message not in output: $1"
exit 1
fi
}
check_msg 'monstartup: maxarcs < minarcs, setting maxarcs = minarcs'
check_msg 'mcount: call graph buffer size limit exceeded, gmon.out will not be generated'
for data_file in $1.data.*; do
if [ -f "$data_file" ]; then
echo "FAIL: expected no data files, but found $data_file"
exit 1
fi
done
echo PASS
+72
View File
@@ -0,0 +1,72 @@
/* Test program to trigger mcount overflow in profiling collection.
Copyright (C) 2017-2023 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
/* Program with sufficiently complex, yet pointless, call graph
that it will trigger an mcount overflow, when you set the
minarcs/maxarcs tunables to very low values. */
#define PREVENT_TAIL_CALL asm volatile ("")
/* Calls REP(n) macro 16 times, for n=0..15.
* You need to define REP(n) before using this.
*/
#define REPS \
REP(0) REP(1) REP(2) REP(3) REP(4) REP(5) REP(6) REP(7) \
REP(8) REP(9) REP(10) REP(11) REP(12) REP(13) REP(14) REP(15)
/* Defines 16 leaf functions named f1_0 to f1_15 */
#define REP(n) \
__attribute__ ((noinline, noclone, weak)) void f1_##n (void) {};
REPS
#undef REP
/* Calls all 16 leaf functions f1_* in succession */
__attribute__ ((noinline, noclone, weak)) void
f2 (void)
{
# define REP(n) f1_##n();
REPS
# undef REP
PREVENT_TAIL_CALL;
}
/* Defines 16 functions named f2_0 to f2_15, which all just call f2 */
#define REP(n) \
__attribute__ ((noinline, noclone, weak)) void \
f2_##n (void) { f2(); PREVENT_TAIL_CALL; };
REPS
#undef REP
__attribute__ ((noinline, noclone, weak)) void
f3 (int count)
{
for (int i = 0; i < count; ++i)
{
/* Calls f1_0(), f2_0(), f1_1(), f2_1(), f3_0(), etc */
# define REP(n) f1_##n(); f2_##n();
REPS
# undef REP
}
}
int
main (void)
{
f3 (1000);
return 0;
}
+1 -1
View File
@@ -26,7 +26,7 @@ headers = gshadow.h
routines = getsgent getsgnam sgetsgent fgetsgent putsgent \
getsgent_r getsgnam_r sgetsgent_r fgetsgent_r
tests = tst-gshadow tst-putsgent tst-fgetsgent_r
tests = tst-gshadow tst-putsgent tst-fgetsgent_r tst-sgetsgent
CFLAGS-getsgent_r.c += -fexceptions
CFLAGS-getsgent.c += -fexceptions
+4 -1
View File
@@ -61,7 +61,10 @@ __sgetsgent_r (const char *string, struct sgrp *resbuf, char *buffer,
buffer[buflen - 1] = '\0';
sp = strncpy (buffer, string, buflen);
if (buffer[buflen - 1] != '\0')
return ERANGE;
{
__set_errno (ERANGE);
return ERANGE;
}
}
else
sp = (char *) string;
+69
View File
@@ -0,0 +1,69 @@
/* Test large input for sgetsgent (bug 30151).
Copyright (C) 2023 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
#include <gshadow.h>
#include <stddef.h>
#include <support/check.h>
#include <support/support.h>
#include <support/xmemstream.h>
#include <stdlib.h>
static int
do_test (void)
{
/* Create a shadow group with 1000 members. */
struct xmemstream mem;
xopen_memstream (&mem);
const char *passwd = "k+zD0nucwfxAo3sw1NXUj6K5vt5M16+X0TVGdE1uFvq5R8V7efJ";
fprintf (mem.out, "group-name:%s::m0", passwd);
for (int i = 1; i < 1000; ++i)
fprintf (mem.out, ",m%d", i);
xfclose_memstream (&mem);
/* Call sgetsgent. */
char *input = mem.buffer;
struct sgrp *e = sgetsgent (input);
TEST_VERIFY_EXIT (e != NULL);
TEST_COMPARE_STRING (e->sg_namp, "group-name");
TEST_COMPARE_STRING (e->sg_passwd, passwd);
/* No administrators. */
TEST_COMPARE_STRING (e->sg_adm[0], NULL);
/* Check the members list. */
for (int i = 0; i < 1000; ++i)
{
char *member = xasprintf ("m%d", i);
TEST_COMPARE_STRING (e->sg_mem[i], member);
free (member);
}
TEST_COMPARE_STRING (e->sg_mem[1000], NULL);
/* Check that putsgent brings back the input string. */
xopen_memstream (&mem);
TEST_COMPARE (putsgent (e, mem.out), 0);
xfclose_memstream (&mem);
/* Compare without the trailing '\n' that putsgent added. */
TEST_COMPARE (mem.buffer[mem.length - 1], '\n');
mem.buffer[mem.length - 1] = '\0';
TEST_COMPARE_STRING (mem.buffer, input);
free (mem.buffer);
free (input);
return 0;
}
#include <support/test-driver.c>
+1 -1
View File
@@ -31,7 +31,7 @@ _S_catch_exception_raise (mach_port_t port,
mach_msg_type_number_t codeCnt
#else /* Vanilla Mach 3.0 interface. */
integer_t exception,
integer_t code, integer_t subcode
integer_t code, long_integer_t subcode
#endif
)
{
+3 -2
View File
@@ -51,9 +51,10 @@ struct hurd_signal_preemptor; /* <hurd/sigpreempt.h> */
struct hurd_signal_detail
{
/* Codes from origination Mach exception_raise message. */
integer_t exc, exc_code, exc_subcode;
integer_t exc, exc_code;
long_integer_t exc_subcode;
/* Sigcode as passed or computed from exception codes. */
integer_t code;
long_integer_t code;
/* Error code as passed or extracted from exception codes. */
error_t error;
};
+1 -1
View File
@@ -45,7 +45,7 @@ _hurdsig_fault_catch_exception_raise (mach_port_t port,
mach_msg_type_number_t codeCnt
#else /* Vanilla Mach 3.0 interface. */
integer_t exception,
integer_t code, integer_t subcode
integer_t code, long_integer_t subcode
#endif
)
{
+6 -1
View File
@@ -75,7 +75,8 @@ ifeq (yes,$(build-shared))
tests = bug-iconv1 bug-iconv2 tst-loading tst-e2big tst-iconv4 bug-iconv4 \
tst-iconv6 bug-iconv5 bug-iconv6 tst-iconv7 bug-iconv8 bug-iconv9 \
bug-iconv10 bug-iconv11 bug-iconv12 tst-iconv-big5-hkscs-to-2ucs4 \
bug-iconv13 bug-iconv14 bug-iconv15
bug-iconv13 bug-iconv14 bug-iconv15 \
tst-iconv-iso-2022-cn-ext tst-bug33980
ifeq ($(have-thread-library),yes)
tests += bug-iconv3
endif
@@ -330,6 +331,10 @@ $(objpfx)bug-iconv14.out: $(addprefix $(objpfx), $(gconv-modules)) \
$(addprefix $(objpfx),$(modules.so))
$(objpfx)bug-iconv15.out: $(addprefix $(objpfx), $(gconv-modules)) \
$(addprefix $(objpfx),$(modules.so))
$(objpfx)tst-iconv-iso-2022-cn-ext.out: $(addprefix $(objpfx), $(gconv-modules)) \
$(addprefix $(objpfx),$(modules.so))
$(objpfx)tst-bug33980.out: $(addprefix $(objpfx), $(gconv-modules)) \
$(addprefix $(objpfx),$(modules.so))
$(objpfx)iconv-test.out: run-iconv-test.sh \
$(addprefix $(objpfx), $(gconv-modules)) \
+1 -1
View File
@@ -407,7 +407,7 @@ static const char from_ucs4[][2] =
is also available. */ \
uint32_t ch2; \
\
if (inptr + 1 >= inend) \
if (inend - inptr <= 1) \
{ \
/* The second character is not available. */ \
result = __GCONV_INCOMPLETE_INPUT; \
+55 -15
View File
@@ -67,12 +67,29 @@
/* Since this is a stateful encoding we have to provide code which resets
the output state to the initial state. This has to be done during the
flushing. */
flushing. For the to-internal direction (FROM_DIRECTION is true),
there may be a pending character that needs flushing. */
#define EMIT_SHIFT_TO_INIT \
if ((data->__statep->__count & ~7) != sb) \
{ \
if (FROM_DIRECTION) \
data->__statep->__count &= 7; \
{ \
uint32_t ch = data->__statep->__count >> 7; \
if (__glibc_unlikely (ch != 0)) \
{ \
if (__glibc_unlikely (outend - outbuf < 4)) \
status = __GCONV_FULL_OUTPUT; \
else \
{ \
put32u (outbuf, ch); \
outbuf += 4; \
/* Clear character and db bit. */ \
data->__statep->__count &= 7; \
} \
} \
else \
data->__statep->__count &= 7; \
} \
else \
{ \
/* We are not in the initial state. To switch back we have \
@@ -99,11 +116,13 @@
*curcsp = save_curcs
/* Current codeset type. */
/* Current codeset type. The bit is stored in the __count variable of
the conversion state. If the db bit is set, bit 7 and above store
a pending UCS-4 code point if non-zero. */
enum
{
sb = 0,
db = 64
sb = 0, /* Single byte mode. */
db = 64 /* Double byte mode. */
};
@@ -119,21 +138,29 @@ enum
} \
else \
{ \
/* This is a combined character. Make sure we have room. */ \
if (__glibc_unlikely (outptr + 8 > outend)) \
{ \
result = __GCONV_FULL_OUTPUT; \
break; \
} \
\
const struct divide *cmbp \
= &DB_TO_UCS4_COMB[ch - __TO_UCS4_COMBINED_MIN]; \
assert (cmbp->res1 != 0 && cmbp->res2 != 0); \
\
put32 (outptr, cmbp->res1); \
outptr += 4; \
put32 (outptr, cmbp->res2); \
outptr += 4; \
\
/* See whether we have room for the second character. */ \
if (outend - outptr >= 4) \
{ \
put32 (outptr, cmbp->res2); \
outptr += 4; \
} \
else \
{ \
/* Otherwise store only the first character now, and \
put the second one into the queue. */ \
curcs |= cmbp->res2 << 7; \
inptr += 2; \
/* Tell the caller why we terminate the loop. */ \
result = __GCONV_FULL_OUTPUT; \
break; \
} \
} \
}
#else
@@ -153,7 +180,20 @@ enum
#define LOOPFCT FROM_LOOP
#define BODY \
{ \
uint32_t ch = *inptr; \
uint32_t ch; \
\
ch = curcs >> 7; \
if (__glibc_unlikely (ch != 0)) \
{ \
put32 (outptr, ch); \
outptr += 4; \
/* Remove the pending character, but preserve state bits. */ \
curcs &= (1 << 7) - 1; \
continue; \
} \
\
/* Otherwise read the next input byte. */ \
ch = *inptr; \
\
if (__builtin_expect (ch, 0) == SO) \
{ \
+12
View File
@@ -574,6 +574,12 @@ DIAG_IGNORE_Os_NEEDS_COMMENT (5, "-Wmaybe-uninitialized");
{ \
const char *escseq; \
\
if (outptr + 4 > outend) \
{ \
result = __GCONV_FULL_OUTPUT; \
break; \
} \
\
assert (used == CNS11643_2_set); /* XXX */ \
escseq = "*H"; \
*outptr++ = ESC; \
@@ -587,6 +593,12 @@ DIAG_IGNORE_Os_NEEDS_COMMENT (5, "-Wmaybe-uninitialized");
{ \
const char *escseq; \
\
if (outptr + 4 > outend) \
{ \
result = __GCONV_FULL_OUTPUT; \
break; \
} \
\
assert ((used >> 5) >= 3 && (used >> 5) <= 7); \
escseq = "+I+J+K+L+M" + ((used >> 5) - 3) * 2; \
*outptr++ = ESC; \
+153
View File
@@ -0,0 +1,153 @@
/* Test for bug 33980: combining characters in IBM1390/IBM1399.
Copyright (C) 2026 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
#include <alloc_buffer.h>
#include <errno.h>
#include <iconv.h>
#include <stdbool.h>
#include <string.h>
#include <support/check.h>
#include <support/next_to_fault.h>
#include <support/support.h>
/* Run iconv in a loop with a small output buffer of OUTBUFSIZE bytes
starting at OUTBUF. OUTBUF should be right before an unmapped page
so that writing past the end will fault. Skip SHIFT bytes at the
start of the input and output, to exercise different buffer
alignment. TRUNCATE indicates skipped bytes at the end of
input (0 and 1 a valid). */
static void
test_one (const char *encoding, unsigned int shift, unsigned int truncate,
char *outbuf, size_t outbufsize)
{
/* In IBM1390 and IBM1399, the DBCS code 0xECB5 expands to two
Unicode code points when translated. */
static char input[] =
{
/* 8 letters X. */
0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7, 0xe7,
/* SO, 0xECB5, SI: shift to DBCS, special character, shift back. */
0x0e, 0xec, 0xb5, 0x0f
};
/* Expected output after UTF-8 conversion. */
static char expected[] =
{
'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X',
/* U+304B (HIRAGANA LETTER KA). */
0xe3, 0x81, 0x8b,
/* U+309A (COMBINING KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK). */
0xe3, 0x82, 0x9a
};
iconv_t cd = iconv_open ("UTF-8", encoding);
TEST_VERIFY_EXIT (cd != (iconv_t) -1);
char result_storage[64];
struct alloc_buffer result_buf
= alloc_buffer_create (result_storage, sizeof (result_storage));
char *inptr = &input[shift];
size_t inleft = sizeof (input) - shift - truncate;
while (inleft > 0)
{
char *outptr = outbuf;
size_t outleft = outbufsize;
size_t inleft_before = inleft;
size_t ret = iconv (cd, &inptr, &inleft, &outptr, &outleft);
size_t produced = outptr - outbuf;
alloc_buffer_copy_bytes (&result_buf, outbuf, produced);
if (ret == (size_t) -1 && errno == E2BIG)
{
if (produced == 0 && inleft == inleft_before)
{
/* Output buffer too small to make progress. This is
expected for very small output buffer sizes. */
TEST_VERIFY_EXIT (outbufsize < 3);
break;
}
continue;
}
if (ret == (size_t) -1)
FAIL_EXIT1 ("%s (outbufsize %zu): iconv: %m", encoding, outbufsize);
break;
}
/* Flush any pending state (e.g. a buffered combined character).
With outbufsize < 3, we could not store the first character, so
the second character did not become pending, and there is nothing
to flush. */
{
char *outptr = outbuf;
size_t outleft = outbufsize;
size_t ret = iconv (cd, NULL, NULL, &outptr, &outleft);
TEST_VERIFY_EXIT (ret == 0);
size_t produced = outptr - outbuf;
alloc_buffer_copy_bytes (&result_buf, outbuf, produced);
/* Second flush does not provide more data. */
outptr = outbuf;
outleft = outbufsize;
ret = iconv (cd, NULL, NULL, &outptr, &outleft);
TEST_VERIFY_EXIT (ret == 0);
TEST_VERIFY (outptr == outbuf);
}
TEST_VERIFY_EXIT (!alloc_buffer_has_failed (&result_buf));
size_t result_used
= sizeof (result_storage) - alloc_buffer_size (&result_buf);
if (outbufsize >= 3)
{
TEST_COMPARE (inleft, 0);
TEST_COMPARE (result_used, sizeof (expected) - shift);
TEST_COMPARE_BLOB (result_storage, result_used,
&expected[shift], sizeof (expected) - shift);
}
else
/* If the buffer is too small, only the leading X could be converted. */
TEST_COMPARE (result_used, 8 - shift);
TEST_VERIFY_EXIT (iconv_close (cd) == 0);
}
static int
do_test (void)
{
struct support_next_to_fault ntf
= support_next_to_fault_allocate (8);
for (int shift = 0; shift <= 8; ++shift)
for (int truncate = 0; truncate < 2; ++truncate)
for (size_t outbufsize = 1; outbufsize <= 8; outbufsize++)
{
char *outbuf = ntf.buffer + ntf.length - outbufsize;
test_one ("IBM1390", shift, truncate, outbuf, outbufsize);
test_one ("IBM1399", shift, truncate, outbuf, outbufsize);
}
support_next_to_fault_free (&ntf);
return 0;
}
#include <support/test-driver.c>
+128
View File
@@ -0,0 +1,128 @@
/* Verify ISO-2022-CN-EXT does not write out of the bounds.
Copyright (C) 2024 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <iconv.h>
#include <sys/mman.h>
#include <support/xunistd.h>
#include <support/check.h>
#include <support/support.h>
/* The test sets up a two memory page buffer with the second page marked
PROT_NONE to trigger a fault if the conversion writes beyond the exact
expected amount. Then we carry out various conversions and precisely
place the start of the output buffer in order to trigger a SIGSEGV if the
process writes anywhere between 1 and page sized bytes more (only one
PROT_NONE page is setup as a canary) than expected. These tests exercise
all three of the cases in ISO-2022-CN-EXT where the converter must switch
character sets and may run out of buffer space while doing the
operation. */
static int
do_test (void)
{
iconv_t cd = iconv_open ("ISO-2022-CN-EXT", "UTF-8");
TEST_VERIFY_EXIT (cd != (iconv_t) -1);
char *ntf;
size_t ntfsize;
char *outbufbase;
{
int pgz = getpagesize ();
TEST_VERIFY_EXIT (pgz > 0);
ntfsize = 2 * pgz;
ntf = xmmap (NULL, ntfsize, PROT_READ | PROT_WRITE, MAP_PRIVATE
| MAP_ANONYMOUS, -1);
xmprotect (ntf + pgz, pgz, PROT_NONE);
outbufbase = ntf + pgz;
}
/* Check if SOdesignation escape sequence does not trigger an OOB write. */
{
char inbuf[] = "\xe4\xba\xa4\xe6\x8d\xa2";
for (int i = 0; i < 9; i++)
{
char *inp = inbuf;
size_t inleft = sizeof (inbuf) - 1;
char *outp = outbufbase - i;
size_t outleft = i;
TEST_VERIFY_EXIT (iconv (cd, &inp, &inleft, &outp, &outleft)
== (size_t) -1);
TEST_COMPARE (errno, E2BIG);
TEST_VERIFY_EXIT (iconv (cd, NULL, NULL, NULL, NULL) == 0);
}
}
/* Same as before for SS2designation. */
{
char inbuf[] = "\xe3\xb4\xbd";
for (int i = 0; i < 14; i++)
{
char *inp = inbuf;
size_t inleft = sizeof (inbuf) - 1;
char *outp = outbufbase - i;
size_t outleft = i;
TEST_VERIFY_EXIT (iconv (cd, &inp, &inleft, &outp, &outleft)
== (size_t) -1);
TEST_COMPARE (errno, E2BIG);
TEST_VERIFY_EXIT (iconv (cd, NULL, NULL, NULL, NULL) == 0);
}
}
/* Same as before for SS3designation. */
{
char inbuf[] = "\xe5\x8a\x84";
for (int i = 0; i < 14; i++)
{
char *inp = inbuf;
size_t inleft = sizeof (inbuf) - 1;
char *outp = outbufbase - i;
size_t outleft = i;
TEST_VERIFY_EXIT (iconv (cd, &inp, &inleft, &outp, &outleft)
== (size_t) -1);
TEST_COMPARE (errno, E2BIG);
TEST_VERIFY_EXIT (iconv (cd, NULL, NULL, NULL, NULL) == 0);
}
}
TEST_VERIFY_EXIT (iconv_close (cd) != -1);
xmunmap (ntf, ntfsize);
return 0;
}
#include <support/test-driver.c>
+4
View File
@@ -278,6 +278,10 @@ struct link_map
/* List of object in order of the init and fini calls. */
struct link_map **l_initfini;
/* Linked list of objects in reverse ELF constructor execution
order. Head of list is stored in _dl_init_called_list. */
struct link_map *l_init_called_next;
/* List of the dependencies introduced through symbol binding. */
struct link_map_reldeps
{
-4
View File
@@ -14,10 +14,6 @@ libc_hidden_proto (__get_nprocs_conf)
extern int __get_nprocs (void);
libc_hidden_proto (__get_nprocs)
/* Return the number of available processors which the process can
be scheduled. */
extern int __get_nprocs_sched (void) attribute_hidden;
/* Return number of physical pages of memory in the system. */
extern long int __get_phys_pages (void);
libc_hidden_proto (__get_phys_pages)
+4 -1
View File
@@ -59,6 +59,7 @@ routines := \
ftw64-time64 \
closefrom close_range
others := pwd
test-srcs := ftwtest ftwtest-time64
tests := test-utime test-stat test-stat2 test-lfs tst-getcwd \
@@ -80,7 +81,9 @@ tests := test-utime test-stat test-stat2 test-lfs tst-getcwd \
tst-utimensat \
tst-closefrom \
tst-close_range \
tst-ftw-bz28126
tst-ftw-bz28126 \
tst-fcntl-lock \
tst-fcntl-lock-lfs
tests-time64 := \
tst-fcntl-time64 \
+4
View File
@@ -18,6 +18,10 @@
#include <errno.h>
#include <fcntl.h>
#ifndef __O_CLOEXEC
# error __O_CLOEXEC not defined by fcntl.h/cloexec.h
#endif
/* Perform file control operations on FD. */
int
__fcntl (int fd, int cmd, ...)
+2
View File
@@ -0,0 +1,2 @@
#define _FILE_OFFSET_BITS 64
#include <io/tst-fcntl-lock.c>
+97
View File
@@ -0,0 +1,97 @@
/* Test for advisory record locking.
Copyright (C) 2023 Free Software Foundation, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <https://www.gnu.org/licenses/>.
*/
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
/* This is essentially the POSIX lockf. */
static int
fcntl_lockf (int fd, int cmd, off_t len)
{
struct flock fl = {
.l_type = F_WRLCK,
.l_whence = SEEK_CUR,
.l_len = len
};
switch (cmd)
{
case F_TEST:
fl.l_type = F_RDLCK;
if (fcntl (fd, F_GETLK, &fl) < 0)
return -1;
if (fl.l_type == F_UNLCK || fl.l_pid == getpid ())
return 0;
errno = EACCES;
return -1;
case F_ULOCK:
fl.l_type = F_UNLCK;
return fcntl (fd, F_SETLK, &fl);
case F_LOCK:
return fcntl (fd, F_SETLKW, &fl);
case F_TLOCK:
return fcntl (fd, F_SETLK, &fl);
}
errno = EINVAL;
return -1;
}
static int
fcntl64_lockf (int fd, int cmd, off64_t len64)
{
struct flock64 fl64 = {
.l_type = F_WRLCK,
.l_whence = SEEK_CUR,
.l_len = len64
};
switch (cmd)
{
case F_TEST:
fl64.l_type = F_RDLCK;
if (fcntl64 (fd, F_GETLK64, &fl64) < 0)
return -1;
if (fl64.l_type == F_UNLCK || fl64.l_pid == getpid ())
return 0;
errno = EACCES;
return -1;
case F_ULOCK:
fl64.l_type = F_UNLCK;
return fcntl64 (fd, F_SETLK64, &fl64);
case F_LOCK:
return fcntl64 (fd, F_SETLKW64, &fl64);
case F_TLOCK:
return fcntl64 (fd, F_SETLK64, &fl64);
}
errno = EINVAL;
return -1;
}
#define TST_LOCKFD "tst-fcntl-lock."
#define LOCKF fcntl_lockf
#define LOCKF64 fcntl64_lockf
#include "tst-lockf.c"
+34 -24
View File
@@ -24,13 +24,23 @@
#include <support/capture_subprocess.h>
#include <support/check.h>
#ifndef TST_LOCKFD
# define TST_LOCKFD "tst-lockfd."
#endif
#ifndef LOCKF
# define LOCKF lockf
#endif
#ifndef LOCKF64
# define LOCKF64 lockf64
#endif
static char *temp_filename;
static int temp_fd;
static void
do_prepare (int argc, char **argv)
{
temp_fd = create_temp_file ("tst-lockfd.", &temp_filename);
temp_fd = create_temp_file (TST_LOCKFD, &temp_filename);
TEST_VERIFY_EXIT (temp_fd != -1);
}
#define PREPARE do_prepare
@@ -40,22 +50,22 @@ do_test_child_lockf (void *closure)
{
/* Check if parent has [0, 1024) locked. */
TEST_COMPARE (lseek (temp_fd, 0, SEEK_SET), 0);
TEST_COMPARE (lockf (temp_fd, F_TLOCK, 1024), -1);
TEST_COMPARE (LOCKF (temp_fd, F_TLOCK, 1024), -1);
TEST_COMPARE (errno, EAGAIN);
TEST_COMPARE (lockf (temp_fd, F_TEST, 1024), -1);
TEST_COMPARE (LOCKF (temp_fd, F_TEST, 1024), -1);
TEST_COMPARE (errno, EACCES);
/* Also Check if parent has last 1024 bytes locked. */
TEST_COMPARE (lseek (temp_fd, INT32_MAX-1024, SEEK_SET), INT32_MAX-1024);
TEST_COMPARE (lockf (temp_fd, F_TEST, 1024), -1);
TEST_COMPARE (LOCKF (temp_fd, F_TEST, 1024), -1);
/* And try to lock [1024, 2048). */
TEST_COMPARE (lseek (temp_fd, 1024, SEEK_SET), 1024);
TEST_COMPARE (lockf (temp_fd, F_LOCK, 1024), 0);
TEST_COMPARE (LOCKF (temp_fd, F_LOCK, 1024), 0);
/* Check if non-LFS interface cap access to 32-bif off_t. */
TEST_COMPARE (lseek64 (temp_fd, (off64_t)INT32_MAX, SEEK_SET),
(off64_t)INT32_MAX);
TEST_COMPARE (lockf64 (temp_fd, F_TEST, 1024), 0);
TEST_COMPARE (LOCKF64 (temp_fd, F_TEST, 1024), 0);
}
static void
@@ -63,32 +73,32 @@ do_test_child_lockf64 (void *closure)
{
/* Check if parent has [0, 1024) locked. */
TEST_COMPARE (lseek64 (temp_fd, 0, SEEK_SET), 0);
TEST_COMPARE (lockf64 (temp_fd, F_TLOCK, 1024), -1);
TEST_COMPARE (LOCKF64 (temp_fd, F_TLOCK, 1024), -1);
TEST_COMPARE (errno, EAGAIN);
TEST_COMPARE (lockf64 (temp_fd, F_TEST, 1024), -1);
TEST_COMPARE (LOCKF64 (temp_fd, F_TEST, 1024), -1);
TEST_COMPARE (errno, EACCES);
/* Also Check if parent has last 1024 bytes locked. */
TEST_COMPARE (lseek64 (temp_fd, INT32_MAX-1024, SEEK_SET), INT32_MAX-1024);
TEST_COMPARE (lockf64 (temp_fd, F_TEST, 1024), -1);
TEST_COMPARE (LOCKF64 (temp_fd, F_TEST, 1024), -1);
/* And try to lock [1024, 2048). */
TEST_COMPARE (lseek64 (temp_fd, 1024, SEEK_SET), 1024);
TEST_COMPARE (lockf64 (temp_fd, F_LOCK, 1024), 0);
TEST_COMPARE (LOCKF64 (temp_fd, F_LOCK, 1024), 0);
/* And also [INT32_MAX, INT32_MAX+1024). */
{
off64_t off = (off64_t)INT32_MAX;
TEST_COMPARE (lseek64 (temp_fd, off, SEEK_SET), off);
TEST_COMPARE (lockf64 (temp_fd, F_LOCK, 1024), 0);
TEST_COMPARE (LOCKF64 (temp_fd, F_LOCK, 1024), 0);
}
/* Check if [INT32_MAX+1024, INT64_MAX) is locked. */
{
off64_t off = (off64_t)INT32_MAX+1024;
TEST_COMPARE (lseek64 (temp_fd, off, SEEK_SET), off);
TEST_COMPARE (lockf64 (temp_fd, F_TLOCK, 1024), -1);
TEST_COMPARE (LOCKF64 (temp_fd, F_TLOCK, 1024), -1);
TEST_COMPARE (errno, EAGAIN);
TEST_COMPARE (lockf64 (temp_fd, F_TEST, 1024), -1);
TEST_COMPARE (LOCKF64 (temp_fd, F_TEST, 1024), -1);
TEST_COMPARE (errno, EACCES);
}
}
@@ -97,38 +107,38 @@ static int
do_test (void)
{
/* Basic tests to check if a lock can be obtained and checked. */
TEST_COMPARE (lockf (temp_fd, F_LOCK, 1024), 0);
TEST_COMPARE (lockf (temp_fd, F_LOCK, INT32_MAX), 0);
TEST_COMPARE (lockf (temp_fd, F_TLOCK, 1024), 0);
TEST_COMPARE (lockf (temp_fd, F_TEST, 1024), 0);
TEST_COMPARE (LOCKF (temp_fd, F_LOCK, 1024), 0);
TEST_COMPARE (LOCKF (temp_fd, F_LOCK, INT32_MAX), 0);
TEST_COMPARE (LOCKF (temp_fd, F_TLOCK, 1024), 0);
TEST_COMPARE (LOCKF (temp_fd, F_TEST, 1024), 0);
TEST_COMPARE (lseek (temp_fd, 1024, SEEK_SET), 1024);
TEST_COMPARE (lockf (temp_fd, F_ULOCK, 1024), 0);
TEST_COMPARE (LOCKF (temp_fd, F_ULOCK, 1024), 0);
/* Parent process should have ([0, 1024), [2048, INT32_MAX)) ranges locked. */
{
struct support_capture_subprocess result;
result = support_capture_subprocess (do_test_child_lockf, NULL);
support_capture_subprocess_check (&result, "lockf", 0, sc_allow_none);
support_capture_subprocess_check (&result, "LOCKF", 0, sc_allow_none);
}
if (sizeof (off_t) != sizeof (off64_t))
{
/* Check if previously locked regions with LFS symbol. */
TEST_COMPARE (lseek (temp_fd, 0, SEEK_SET), 0);
TEST_COMPARE (lockf64 (temp_fd, F_LOCK, 1024), 0);
TEST_COMPARE (lockf64 (temp_fd, F_TLOCK, 1024), 0);
TEST_COMPARE (lockf64 (temp_fd, F_TEST, 1024), 0);
TEST_COMPARE (LOCKF64 (temp_fd, F_LOCK, 1024), 0);
TEST_COMPARE (LOCKF64 (temp_fd, F_TLOCK, 1024), 0);
TEST_COMPARE (LOCKF64 (temp_fd, F_TEST, 1024), 0);
/* Lock region [INT32_MAX+1024, INT64_MAX). */
off64_t off = (off64_t)INT32_MAX + 1024;
TEST_COMPARE (lseek64 (temp_fd, off, SEEK_SET), off);
TEST_COMPARE (lockf64 (temp_fd, F_LOCK, 1024), 0);
TEST_COMPARE (LOCKF64 (temp_fd, F_LOCK, 1024), 0);
/* Parent process should have ([0, 1024), [2048, INT32_MAX),
[INT32_MAX+1024, INT64_MAX)) ranges locked. */
{
struct support_capture_subprocess result;
result = support_capture_subprocess (do_test_child_lockf64, NULL);
support_capture_subprocess_check (&result, "lockf", 0, sc_allow_none);
support_capture_subprocess_check (&result, "LOCKF", 0, sc_allow_none);
}
}
+20 -20
View File
@@ -208,12 +208,12 @@ extern char *__REDIRECT (__fgets_chk_warn,
__fortify_function __wur __fortified_attr_access (__write_only__, 1, 2) char *
fgets (char *__restrict __s, int __n, FILE *__restrict __stream)
{
size_t sz = __glibc_objsize (__s);
if (__glibc_safe_or_unknown_len (__n, sizeof (char), sz))
size_t __sz = __glibc_objsize (__s);
if (__glibc_safe_or_unknown_len (__n, sizeof (char), __sz))
return __fgets_alias (__s, __n, __stream);
if (__glibc_unsafe_len (__n, sizeof (char), sz))
return __fgets_chk_warn (__s, sz, __n, __stream);
return __fgets_chk (__s, sz, __n, __stream);
if (__glibc_unsafe_len (__n, sizeof (char), __sz))
return __fgets_chk_warn (__s, __sz, __n, __stream);
return __fgets_chk (__s, __sz, __n, __stream);
}
extern size_t __REDIRECT (__fread_alias,
@@ -232,12 +232,12 @@ __fortify_function __wur size_t
fread (void *__restrict __ptr, size_t __size, size_t __n,
FILE *__restrict __stream)
{
size_t sz = __glibc_objsize0 (__ptr);
if (__glibc_safe_or_unknown_len (__n, __size, sz))
size_t __sz = __glibc_objsize0 (__ptr);
if (__glibc_safe_or_unknown_len (__n, __size, __sz))
return __fread_alias (__ptr, __size, __n, __stream);
if (__glibc_unsafe_len (__n, __size, sz))
return __fread_chk_warn (__ptr, sz, __size, __n, __stream);
return __fread_chk (__ptr, sz, __size, __n, __stream);
if (__glibc_unsafe_len (__n, __size, __sz))
return __fread_chk_warn (__ptr, __sz, __size, __n, __stream);
return __fread_chk (__ptr, __sz, __size, __n, __stream);
}
#ifdef __USE_GNU
@@ -254,12 +254,12 @@ extern char *__REDIRECT (__fgets_unlocked_chk_warn,
__fortify_function __wur __fortified_attr_access (__write_only__, 1, 2) char *
fgets_unlocked (char *__restrict __s, int __n, FILE *__restrict __stream)
{
size_t sz = __glibc_objsize (__s);
if (__glibc_safe_or_unknown_len (__n, sizeof (char), sz))
size_t __sz = __glibc_objsize (__s);
if (__glibc_safe_or_unknown_len (__n, sizeof (char), __sz))
return __fgets_unlocked_alias (__s, __n, __stream);
if (__glibc_unsafe_len (__n, sizeof (char), sz))
return __fgets_unlocked_chk_warn (__s, sz, __n, __stream);
return __fgets_unlocked_chk (__s, sz, __n, __stream);
if (__glibc_unsafe_len (__n, sizeof (char), __sz))
return __fgets_unlocked_chk_warn (__s, __sz, __n, __stream);
return __fgets_unlocked_chk (__s, __sz, __n, __stream);
}
#endif
@@ -281,8 +281,8 @@ __fortify_function __wur size_t
fread_unlocked (void *__restrict __ptr, size_t __size, size_t __n,
FILE *__restrict __stream)
{
size_t sz = __glibc_objsize0 (__ptr);
if (__glibc_safe_or_unknown_len (__n, __size, sz))
size_t __sz = __glibc_objsize0 (__ptr);
if (__glibc_safe_or_unknown_len (__n, __size, __sz))
{
# ifdef __USE_EXTERN_INLINES
if (__builtin_constant_p (__size)
@@ -307,9 +307,9 @@ fread_unlocked (void *__restrict __ptr, size_t __size, size_t __n,
# endif
return __fread_unlocked_alias (__ptr, __size, __n, __stream);
}
if (__glibc_unsafe_len (__n, __size, sz))
return __fread_unlocked_chk_warn (__ptr, sz, __size, __n, __stream);
return __fread_unlocked_chk (__ptr, sz, __size, __n, __stream);
if (__glibc_unsafe_len (__n, __size, __sz))
return __fread_unlocked_chk_warn (__ptr, __sz, __size, __n, __stream);
return __fread_unlocked_chk (__ptr, __sz, __size, __n, __stream);
}
#endif
+5 -2
View File
@@ -4,6 +4,7 @@
#include <stdlib.h>
#include <string.h>
#include <support/xstdlib.h>
static char *fname;
@@ -35,14 +36,16 @@ do_test (void)
char buffer[1024];
snprintf (buffer, sizeof (buffer), "echo 'From foo@bar.com' > %s", fname);
system (buffer);
xsystem (buffer);
f = fopen (fname, "r");
fseek (f, 0, SEEK_END);
o = ftello (f);
fseek (f, 0, SEEK_SET);
fflush (f);
snprintf (buffer, sizeof (buffer), "echo 'From bar@baz.edu' >> %s", fname);
system (buffer);
xsystem (buffer);
fseek (f, o, SEEK_SET);
if (fgets (buffer, 1024, f) == NULL)
exit (1);
+7 -1
View File
@@ -635,7 +635,7 @@ _IO_sputbackc (FILE *fp, int c)
{
int result;
if (fp->_IO_read_ptr > fp->_IO_read_base
if (fp->_IO_read_ptr > fp->_IO_read_base && !_IO_in_backup (fp)
&& (unsigned char)fp->_IO_read_ptr[-1] == (unsigned char)c)
{
fp->_IO_read_ptr--;
@@ -796,6 +796,12 @@ _IO_unbuffer_all (void)
legacy = 1;
#endif
/* Free up the backup area if it was ever allocated. */
if (_IO_have_backup (fp))
_IO_free_backup_area (fp);
if (!legacy && fp->_mode > 0 && _IO_have_wbackup (fp))
_IO_free_wbackup_area (fp);
if (! (fp->_flags & _IO_UNBUFFERED)
/* Iff stream is un-orientated, it wasn't used. */
&& (legacy || fp->_mode != 0))
+2 -2
View File
@@ -530,8 +530,8 @@ extern void _IO_old_init (FILE *fp, int flags) __THROW;
((__fp)->_wide_data->_IO_write_base \
= (__fp)->_wide_data->_IO_write_ptr = __p, \
(__fp)->_wide_data->_IO_write_end = (__ep))
#define _IO_have_backup(fp) ((fp)->_IO_save_base != NULL)
#define _IO_have_wbackup(fp) ((fp)->_wide_data->_IO_save_base != NULL)
#define _IO_have_backup(fp) ((fp)->_IO_backup_base != NULL)
#define _IO_have_wbackup(fp) ((fp)->_wide_data->_IO_backup_base != NULL)
#define _IO_in_backup(fp) ((fp)->_flags & _IO_IN_BACKUP)
#define _IO_have_markers(fp) ((fp)->_markers != NULL)
#define _IO_blen(fp) ((fp)->_IO_buf_end - (fp)->_IO_buf_base)
+1 -1
View File
@@ -55,7 +55,7 @@ _IO_wdo_write (FILE *fp, const wchar_t *data, size_t to_do)
char mb_buf[MB_LEN_MAX];
char *write_base, *write_ptr, *buf_end;
if (fp->_IO_write_ptr - fp->_IO_write_base < sizeof (mb_buf))
if (fp->_IO_buf_end - fp->_IO_write_ptr < sizeof (mb_buf))
{
/* Make sure we have room for at least one multibyte
character. */
+9 -31
View File
@@ -21,6 +21,8 @@
#include <stdio.h>
#include <string.h>
#include <support/check.h>
static const char lower[] = "abcdefghijklmnopqrstuvwxyz";
static const char upper[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
@@ -53,19 +55,11 @@ static struct classes
#define nclasses (sizeof (classes) / sizeof (classes[0]))
#define FAIL(str, args...) \
{ \
printf (" " str "\n", ##args); \
++errors; \
}
static int
do_test (void)
{
const char *cp;
const char *cp2;
int errors = 0;
char *inpline = NULL;
size_t inplinelen = 0;
char *resline = NULL;
@@ -394,11 +388,8 @@ punct = %04x alnum = %04x\n",
{
if (((__ctype_b[(unsigned int) *inp] & classes[n].mask) != 0)
!= (*resp != '0'))
{
printf (" is%s('%c' = '\\x%02x') %s true\n", inpline,
*inp, *inp, *resp == '1' ? "not" : "is");
++errors;
}
FAIL (" is%s('%c' = '\\x%02x') %s true\n", inpline,
*inp, *inp, *resp == '1' ? "not" : "is");
++inp;
++resp;
}
@@ -408,11 +399,8 @@ punct = %04x alnum = %04x\n",
while (*inp != '\0')
{
if (tolower (*inp) != *resp)
{
printf (" tolower('%c' = '\\x%02x') != '%c'\n",
*inp, *inp, *resp);
++errors;
}
FAIL (" tolower('%c' = '\\x%02x') != '%c'\n",
*inp, *inp, *resp);
++inp;
++resp;
}
@@ -422,11 +410,8 @@ punct = %04x alnum = %04x\n",
while (*inp != '\0')
{
if (toupper (*inp) != *resp)
{
printf (" toupper('%c' = '\\x%02x') != '%c'\n",
*inp, *inp, *resp);
++errors;
}
FAIL (" toupper('%c' = '\\x%02x') != '%c'\n",
*inp, *inp, *resp);
++inp;
++resp;
}
@@ -436,14 +421,7 @@ punct = %04x alnum = %04x\n",
}
if (errors != 0)
{
printf (" %d error%s for `%s' locale\n\n\n", errors,
errors == 1 ? "" : "s", setlocale (LC_ALL, NULL));
return 1;
}
printf (" No errors for `%s' locale\n\n\n", setlocale (LC_ALL, NULL));
printf ("Completed testing for `%s' locale\n\n\n", setlocale (LC_ALL, NULL));
return 0;
}
+3 -1
View File
@@ -44,7 +44,9 @@ subdir-dirs = programs
vpath %.c programs
tests := tst-utmp tst-utmpx tst-grantpt tst-ptsname tst-getlogin tst-updwtmpx \
tst-pututxline-lockfail tst-pututxline-cache
tst-pututxline-lockfail tst-pututxline-cache tst-utmp-size tst-utmp-size-64
CFLAGS-tst-utmp-size-64.c += -D_FILE_OFFSET_BITS=64 -D_TIME_BITS=64
# Empty compatibility library for old binaries.
extra-libs := libutil
+2
View File
@@ -0,0 +1,2 @@
/* The on-disk layout must not change in time64 mode. */
#include "tst-utmp-size.c"
+33
View File
@@ -0,0 +1,33 @@
/* Check expected sizes of struct utmp, struct utmpx, struct lastlog.
Copyright (C) 2024 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
#include <utmp.h>
#include <utmpx.h>
#include <utmp-size.h>
static int
do_test (void)
{
_Static_assert (sizeof (struct utmp) == UTMP_SIZE, "struct utmp size");
_Static_assert (sizeof (struct utmpx) == UTMP_SIZE, "struct utmpx size");
_Static_assert (sizeof (struct lastlog) == LASTLOG_SIZE,
"struct lastlog size");
return 0;
}
#include <support/test-driver.c>
+1 -1
View File
@@ -934,7 +934,7 @@ arena_get2 (size_t size, mstate avoid_arena)
narenas_limit = mp_.arena_max;
else if (narenas > mp_.arena_test)
{
int n = __get_nprocs_sched ();
int n = __get_nprocs ();
if (n >= 1)
narenas_limit = NARENAS_FROM_NCORES (n);
+20 -11
View File
@@ -3398,16 +3398,23 @@ __libc_realloc (void *oldmem, size_t bytes)
if (__glibc_unlikely (mtag_enabled))
*(volatile char*) oldmem;
/* Return the chunk as is whenever possible, i.e. there's enough usable space
but not so much that we end up fragmenting the block. We use the trim
threshold as the heuristic to decide the latter. */
size_t usable = musable (oldmem);
if (bytes <= usable
&& (unsigned long) (usable - bytes) <= mp_.trim_threshold)
return oldmem;
/* chunk corresponding to oldmem */
const mchunkptr oldp = mem2chunk (oldmem);
/* Return the chunk as is if the request grows within usable bytes, typically
into the alignment padding. We want to avoid reusing the block for
shrinkages because it ends up unnecessarily fragmenting the address space.
This is also why the heuristic misses alignment padding for THP for
now. */
size_t usable = musable (oldmem);
if (bytes <= usable)
{
size_t difference = usable - bytes;
if ((unsigned long) difference < 2 * sizeof (INTERNAL_SIZE_T)
|| (chunk_is_mmapped (oldp) && difference <= GLRO (dl_pagesize)))
return oldmem;
}
/* its size */
const INTERNAL_SIZE_T oldsize = chunksize (oldp);
@@ -4940,7 +4947,7 @@ _int_memalign (mstate av, size_t alignment, size_t bytes)
nb = checked_request2size (bytes);
if (nb == 0)
if (nb == 0 || alignment > PTRDIFF_MAX)
{
__set_errno (ENOMEM);
return NULL;
@@ -4951,8 +4958,10 @@ _int_memalign (mstate av, size_t alignment, size_t bytes)
request, and then possibly free the leading and trailing space.
*/
/* Call malloc with worst case padding to hit alignment. */
/* Call malloc with worst case padding to hit alignment. ALIGNMENT is a
power of 2, so it tops out at (PTRDIFF_MAX >> 1) + 1, leaving plenty of
space to add MINSIZE and whatever checked_request2size adds to BYTES to
get NB. Consequently, total below also does not overflow. */
m = (char *) (_int_malloc (av, nb + alignment + MINSIZE));
if (m == 0)
+2 -8
View File
@@ -151,7 +151,6 @@ test_large_allocations (size_t size)
}
static long pagesize;
/* This function tests the following aligned memory allocation functions
using several valid alignments and precedes each allocation test with a
@@ -170,8 +169,8 @@ test_large_aligned_allocations (size_t size)
/* All aligned memory allocation functions expect an alignment that is a
power of 2. Given this, we test each of them with every valid
alignment from 1 thru PAGESIZE. */
for (align = 1; align <= pagesize; align *= 2)
alignment for the type of ALIGN, i.e. until it wraps to 0. */
for (align = 1; align > 0; align <<= 1)
{
test_setup ();
#if __GNUC_PREREQ (7, 0)
@@ -264,11 +263,6 @@ do_test (void)
DIAG_IGNORE_NEEDS_COMMENT (7, "-Walloc-size-larger-than=");
#endif
/* Aligned memory allocation functions need to be tested up to alignment
size equivalent to page size, which should be a power of 2. */
pagesize = sysconf (_SC_PAGESIZE);
TEST_VERIFY_EXIT (powerof2 (pagesize));
/* Loop 1: Ensure that all allocations with SIZE close to SIZE_MAX, i.e.
in the range (SIZE_MAX - 2^14, SIZE_MAX], fail.
+39 -7
View File
@@ -1339,6 +1339,10 @@ will fail and set @code{errno} to @code{EAGAIN} if the operation would block.
@item RWF_APPEND
Per-IO synchronization as if the file was opened with @code{O_APPEND} flag.
@item RWF_NOAPPEND
This flag allows an offset to be honored, even if the file was opened with
@code{O_APPEND} flag.
@end vtable
When the source file is compiled with @code{_FILE_OFFSET_BITS == 64} the
@@ -1777,7 +1781,7 @@ There is no existing mapping in at least part of the given region.
@end deftypefun
@deftypefun {void *} mremap (void *@var{address}, size_t @var{length}, size_t @var{new_length}, int @var{flag})
@deftypefun {void *} mremap (void *@var{address}, size_t @var{length}, size_t @var{new_length}, int @var{flag}, ... /* void *@var{new_address} */)
@standards{GNU, sys/mman.h}
@safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
@@ -1786,12 +1790,40 @@ area. @var{address} and @var{length} must cover a region entirely mapped
in the same @code{mmap} statement. A new mapping with the same
characteristics will be returned with the length @var{new_length}.
One option is possible, @code{MREMAP_MAYMOVE}. If it is given in
@var{flags}, the system may remove the existing mapping and create a new
one of the desired length in another location.
Possible flags are
The address of the resulting mapping is returned, or @math{-1}. Possible
error codes include:
@table @code
@item MREMAP_MAYMOVE
If it is given in @var{flags}, the system may remove the existing mapping
and create a new one of the desired length in another location.
@item MREMAP_FIXED
If it is given in @var{flags}, @code{mremap} accepts a fifth argument,
@code{void *new_address}, which specifies a page-aligned address to
which the mapping must be moved. Any previous mapping at the address
range specified by @var{new_address} and @var{new_size} is unmapped.
@code{MREMAP_FIXED} must be used together with @code{MREMAP_MAYMOVE}.
@item MREMAP_DONTUNMAP
If it is given in @var{flags}, @code{mremap} accepts a fifth argument,
@code{void *new_address}, which specifies a page-aligned address. Any
previous mapping at the address range specified by @var{new_address} and
@var{new_size} is unmapped. If @var{new_address} is @code{NULL}, the
kernel chooses the page-aligned address at which to create the mapping.
Otherwise, the kernel takes it as a hint about where to place the mapping.
The mapping at the address range specified by @var{old_address} and
@var{old_size} isn't unmapped.
@code{MREMAP_DONTUNMAP} must be used together with @code{MREMAP_MAYMOVE}.
@var{old_size} must be the same as @var{new_size}. This flag bit is
Linux-specific.
@end table
The address of the resulting mapping is returned, or @code{MAP_FAILED}.
Possible error codes include:
@table @code
@@ -1800,7 +1832,7 @@ There is no existing mapping in at least part of the original region, or
the region covers two or more distinct mappings.
@item EINVAL
The address given is misaligned or inappropriate.
Any arguments are inappropriate, including unknown @var{flags} values.
@item EAGAIN
The region has pages locked, and if extended it would exceed the
+3 -5
View File
@@ -1474,11 +1474,9 @@ program; usually @code{ungetc} is used only to unread a character that
was just read from the same stream. @Theglibc{} supports this
even on files opened in binary mode, but other systems might not.
@Theglibc{} only supports one character of pushback---in other
words, it does not work to call @code{ungetc} twice without doing input
in between. Other systems might let you push back multiple characters;
then reading from the stream retrieves the characters in the reverse
order that they were pushed.
@Theglibc{} supports pushing back multiple characters; subsequently
reading from the stream retrieves the characters in the reverse order
that they were pushed.
Pushing back characters doesn't alter the file; only the internal
buffering for the stream is affected. If a file positioning function
+6 -2
View File
@@ -1020,8 +1020,12 @@ This variable is either zero (if restartable sequence registration
failed or has been disabled) or the size of the restartable sequence
registration. This can be different from the size of @code{struct rseq}
if the kernel has extended the size of the registration. If
registration is successful, @code{__rseq_size} is at least 32 (the
initial size of @code{struct rseq}).
registration is successful, @code{__rseq_size} is at least 20 (the
initially active size of @code{struct rseq}).
Previous versions of @theglibc{} set this to 32 even if the kernel only
supported the initial area of 20 bytes because the value included unused
padding at the end of the restartable sequence area.
@end deftypevar
@deftypevar {unsigned int} __rseq_flags
+1 -1
View File
@@ -502,7 +502,7 @@ This tunable is specific to powerpc, powerpc64 and powerpc64le.
@deftp Tunable glibc.cpu.name
The @code{glibc.cpu.name=xxx} tunable allows the user to tell @theglibc{} to
assume that the CPU is @code{xxx} where xxx may have one of these values:
@code{generic}, @code{falkor}, @code{thunderxt88}, @code{thunderx2t99},
@code{generic}, @code{thunderxt88}, @code{thunderx2t99},
@code{thunderx2t99p1}, @code{ares}, @code{emag}, @code{kunpeng},
@code{a64fx}.
+3 -10
View File
@@ -24,6 +24,8 @@
#include <string.h>
#include <tgmath.h>
#include <support/check.h>
//#define DEBUG
typedef complex float cfloat;
@@ -87,13 +89,6 @@ enum
int count;
int counts[Tlast][C_last];
#define FAIL(str) \
do \
{ \
printf ("%s failure on line %d\n", (str), __LINE__); \
result = 1; \
} \
while (0)
#define TEST_TYPE_ONLY(expr, rettype) \
do \
{ \
@@ -133,8 +128,6 @@ int counts[Tlast][C_last];
int
test_cos (const int Vint4, const long long int Vllong4)
{
int result = 0;
TEST (cos (vfloat1), float, cos);
TEST (cos (vdouble1), double, cos);
TEST (cos (vldouble1), ldouble, cos);
@@ -152,7 +145,7 @@ test_cos (const int Vint4, const long long int Vllong4)
TEST (cos (Vcdouble1), cdouble, cos);
TEST (cos (Vcldouble1), cldouble, cos);
return result;
return 0;
}
int
+8 -2
View File
@@ -90,7 +90,7 @@ tests := tst-dirname tst-tsearch tst-fdset tst-mntent tst-hsearch \
tst-preadvwritev2 tst-preadvwritev64v2 tst-warn-wide \
tst-ldbl-warn tst-ldbl-error tst-dbl-efgcvt tst-ldbl-efgcvt \
tst-mntent-autofs tst-syscalls tst-mntent-escape tst-select \
tst-ioctl
tst-ioctl tst-mremap1 tst-mremap2
tests-time64 := \
tst-select-time64 \
@@ -115,7 +115,10 @@ tests-special += $(objpfx)tst-error1-mem.out \
$(objpfx)tst-allocate_once-mem.out
endif
tests-container := tst-syslog
tests-container := \
tst-syslog \
tst-syslog-long-progname \
# tests-container
CFLAGS-select.c += -fexceptions -fasynchronous-unwind-tables
CFLAGS-tsearch.c += $(uses-callbacks)
@@ -177,6 +180,9 @@ $(objpfx)tst-allocate_once-mem.out: $(objpfx)tst-allocate_once.out
$(common-objpfx)malloc/mtrace $(objpfx)tst-allocate_once.mtrace > $@; \
$(evaluate-test)
tst-syslog-long-progname-ENV = GLIBC_TUNABLES=glibc.malloc.check=3 \
LD_PRELOAD=libc_malloc_debug.so.0
$(objpfx)tst-select: $(librt)
$(objpfx)tst-select-time64: $(librt)
$(objpfx)tst-pselect: $(librt)
-6
View File
@@ -44,12 +44,6 @@ weak_alias (__get_nprocs, get_nprocs)
link_warning (get_nprocs, "warning: get_nprocs will always return 1")
int
__get_nprocs_sched (void)
{
return 1;
}
long int
__get_phys_pages (void)
{
+4 -2
View File
@@ -152,6 +152,7 @@
# define __glibc_objsize(__o) __bos (__o)
#endif
#if __USE_FORTIFY_LEVEL > 0
/* Compile time conditions to choose between the regular, _chk and _chk_warn
variants. These conditions should get evaluated to constant and optimized
away. */
@@ -187,7 +188,7 @@
? __ ## f ## _alias (__VA_ARGS__) \
: (__glibc_unsafe_len (__l, __s, __osz) \
? __ ## f ## _chk_warn (__VA_ARGS__, __osz) \
: __ ## f ## _chk (__VA_ARGS__, __osz))) \
: __ ## f ## _chk (__VA_ARGS__, __osz)))
/* Fortify function f, where object size argument passed to f is the number of
elements and not total size. */
@@ -197,7 +198,8 @@
? __ ## f ## _alias (__VA_ARGS__) \
: (__glibc_unsafe_len (__l, __s, __osz) \
? __ ## f ## _chk_warn (__VA_ARGS__, (__osz) / (__s)) \
: __ ## f ## _chk (__VA_ARGS__, (__osz) / (__s)))) \
: __ ## f ## _chk (__VA_ARGS__, (__osz) / (__s))))
#endif
#if __GNUC_PREREQ (4,3)
# define __warnattr(msg) __attribute__((__warning__ (msg)))
+65 -25
View File
@@ -41,6 +41,7 @@ static char sccsid[] = "@(#)syslog.c 8.4 (Berkeley) 3/18/94";
#include <sys/uio.h>
#include <sys/un.h>
#include <syslog.h>
#include <limits.h>
static int LogType = SOCK_DGRAM; /* type of socket connection */
static int LogFile = -1; /* fd for log */
@@ -122,8 +123,9 @@ __vsyslog_internal (int pri, const char *fmt, va_list ap,
{
/* Try to use a static buffer as an optimization. */
char bufs[1024];
char *buf = NULL;
size_t bufsize = 0;
char *buf = bufs;
size_t bufsize;
int msgoff;
int saved_errno = errno;
@@ -175,29 +177,55 @@ __vsyslog_internal (int pri, const char *fmt, va_list ap,
#define SYSLOG_HEADER_WITHOUT_TS(__pri, __msgoff) \
"<%d>: %n", __pri, __msgoff
int l;
int l, vl;
if (has_ts)
l = __snprintf (bufs, sizeof bufs,
SYSLOG_HEADER (pri, timestamp, &msgoff, pid));
else
l = __snprintf (bufs, sizeof bufs,
SYSLOG_HEADER_WITHOUT_TS (pri, &msgoff));
if (0 <= l && l < sizeof bufs)
if (l < 0)
goto out;
char *pos;
size_t len;
if (l < sizeof bufs)
{
va_list apc;
va_copy (apc, ap);
/* Restore errno for %m format. */
__set_errno (saved_errno);
int vl = __vsnprintf_internal (bufs + l, sizeof bufs - l, fmt, apc,
mode_flags);
if (0 <= vl && vl < sizeof bufs - l)
buf = bufs;
bufsize = l + vl;
va_end (apc);
/* At this point, there is still a chance that we can print the
remaining part of the log into bufs and use that. */
pos = bufs + l;
len = sizeof (bufs) - l;
}
else
{
buf = NULL;
/* We already know that bufs is too small to use for this log message.
The next vsnprintf into bufs is used only to calculate the total
required buffer length. We will discard bufs contents and allocate
an appropriately sized buffer later instead. */
pos = bufs;
len = sizeof (bufs);
}
{
va_list apc;
va_copy (apc, ap);
/* Restore errno for %m format. */
__set_errno (saved_errno);
vl = __vsnprintf_internal (pos, len, fmt, apc, mode_flags);
va_end (apc);
if (vl < 0 || vl >= INT_MAX - l)
goto out;
if (vl >= len)
buf = NULL;
bufsize = l + vl;
}
if (buf == NULL)
{
@@ -207,25 +235,37 @@ __vsyslog_internal (int pri, const char *fmt, va_list ap,
/* Tell the cancellation handler to free this buffer. */
clarg.buf = buf;
int cl;
if (has_ts)
__snprintf (buf, l + 1,
SYSLOG_HEADER (pri, timestamp, &msgoff, pid));
cl = __snprintf (buf, l + 1,
SYSLOG_HEADER (pri, timestamp, &msgoff, pid));
else
__snprintf (buf, l + 1,
SYSLOG_HEADER_WITHOUT_TS (pri, &msgoff));
cl = __snprintf (buf, l + 1,
SYSLOG_HEADER_WITHOUT_TS (pri, &msgoff));
if (cl != l)
goto out;
va_list apc;
va_copy (apc, ap);
__vsnprintf_internal (buf + l, bufsize - l + 1, fmt, apc,
mode_flags);
cl = __vsnprintf_internal (buf + l, bufsize - l + 1, fmt, apc,
mode_flags);
va_end (apc);
if (cl != vl)
goto out;
}
else
{
int bl;
/* Nothing much to do but emit an error message. */
bufsize = __snprintf (bufs, sizeof bufs,
"out of memory[%d]", __getpid ());
bl = __snprintf (bufs, sizeof bufs,
"out of memory[%d]", __getpid ());
if (bl < 0 || bl >= sizeof bufs)
goto out;
bufsize = bl;
buf = bufs;
msgoff = 0;
}
}
+46
View File
@@ -0,0 +1,46 @@
/* Test mremap with MREMAP_MAYMOVE.
Copyright (C) 2024 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
#include <errno.h>
#include <sys/mman.h>
#include <support/xstdlib.h>
#include <support/xunistd.h>
#include <support/check.h>
#include <support/test-driver.h>
static int
do_test (void)
{
size_t old_size = getpagesize ();
char *old_addr = xmmap (NULL, old_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1);
old_addr[0] = 1;
old_addr[old_size - 1] = 2;
/* Test MREMAP_MAYMOVE. */
size_t new_size = old_size + old_size;
char *new_addr = mremap (old_addr, old_size, new_size, MREMAP_MAYMOVE);
TEST_VERIFY_EXIT (new_addr != MAP_FAILED);
new_addr[0] = 1;
new_addr[new_size - 1] = 2;
xmunmap (new_addr, new_size);
return 0;
}
#include <support/test-driver.c>
+54
View File
@@ -0,0 +1,54 @@
/* Test mremap with MREMAP_FIXED.
Copyright (C) 2024 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
#include <errno.h>
#include <sys/mman.h>
#include <support/xstdlib.h>
#include <support/xunistd.h>
#include <support/test-driver.h>
#include <mremap-failure.h>
static int
do_test (void)
{
size_t old_size = getpagesize ();
size_t new_size = old_size + old_size;
char *old_addr = xmmap (NULL, old_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1);
old_addr[0] = 1;
old_addr[old_size - 1] = 2;
char *fixed_addr = xmmap (NULL, new_size, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1);
fixed_addr[0] = 1;
fixed_addr[new_size - 1] = 2;
/* Test MREMAP_FIXED. */
char *new_addr = mremap (old_addr, old_size, new_size,
MREMAP_FIXED | MREMAP_MAYMOVE,
fixed_addr);
if (new_addr == MAP_FAILED)
return mremap_failure_exit (errno);
new_addr[0] = 1;
new_addr[new_size - 1] = 2;
xmunmap (new_addr, new_size);
return 0;
}
#include <support/test-driver.c>
+4 -1
View File
@@ -34,8 +34,11 @@
#ifndef RWF_APPEND
# define RWF_APPEND 0
#endif
#ifndef RWF_NOAPPEND
# define RWF_NOAPPEND 0
#endif
#define RWF_SUPPORTED (RWF_HIPRI | RWF_DSYNC | RWF_SYNC | RWF_NOWAIT \
| RWF_APPEND)
| RWF_APPEND | RWF_NOAPPEND)
/* Generic uio_lim.h does not define IOV_MAX. */
#ifndef IOV_MAX
+39
View File
@@ -0,0 +1,39 @@
/* Test heap buffer overflow in syslog with long __progname (CVE-2023-6246)
Copyright (C) 2023 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
#include <syslog.h>
#include <string.h>
extern char * __progname;
static int
do_test (void)
{
char long_progname[2048];
memset (long_progname, 'X', sizeof (long_progname) - 1);
long_progname[sizeof (long_progname) - 1] = '\0';
__progname = long_progname;
syslog (LOG_INFO, "Hello, World!");
return 0;
}
#include <support/test-driver.c>
+19 -7
View File
@@ -34,7 +34,6 @@
#include <bits/types/res_state.h>
#include <kernel-features.h>
#include <tls-internal-struct.h>
#include <sys/rseq.h>
#include <internal-sigset.h>
#ifndef TCB_ALIGNMENT
@@ -405,14 +404,27 @@ struct pthread
/* Used on strsignal. */
struct tls_internal_t tls_state;
/* rseq area registered with the kernel. */
struct rseq rseq_area;
/* This member must be last. */
char end_padding[];
/* rseq area registered with the kernel. Use a custom definition
here to isolate from kernel struct rseq changes. The
implementation of sched_getcpu needs acccess to the cpu_id field;
the other fields are unused and not included here. */
union
{
struct
{
uint32_t cpu_id_start;
uint32_t cpu_id;
uint64_t rseq_cs;
uint32_t flags;
};
char pad[32]; /* Original rseq area size. */
} rseq_area __attribute__ ((aligned (32)));
/* Amount of end padding, if any, in this structure.
This definition relies on rseq_area being last. */
#define PTHREAD_STRUCT_END_PADDING \
(sizeof (struct pthread) - offsetof (struct pthread, end_padding))
(sizeof (struct pthread) - offsetof (struct pthread, rseq_area) \
+ sizeof ((struct pthread) {}.rseq_area))
} __attribute ((aligned (TCB_ALIGNMENT)));
static inline bool
+6 -2
View File
@@ -48,7 +48,8 @@ ___pthread_mutex_trylock (pthread_mutex_t *mutex)
return 0;
}
if (lll_trylock (mutex->__data.__lock) == 0)
if (atomic_load_relaxed (&(mutex->__data.__lock)) == 0
&& lll_trylock (mutex->__data.__lock) == 0)
{
/* Record the ownership. */
mutex->__data.__owner = id;
@@ -71,7 +72,10 @@ ___pthread_mutex_trylock (pthread_mutex_t *mutex)
/*FALL THROUGH*/
case PTHREAD_MUTEX_ADAPTIVE_NP:
case PTHREAD_MUTEX_ERRORCHECK_NP:
if (lll_trylock (mutex->__data.__lock) != 0)
/* Mutex type is already loaded, lock check overhead should
be minimal. */
if (atomic_load_relaxed (&(mutex->__data.__lock)) != 0
|| lll_trylock (mutex->__data.__lock) != 0)
break;
/* Record the ownership. */
+2 -1
View File
@@ -43,7 +43,8 @@ tf (void *arg)
{
char *cmd = xasprintf ("%s --direct --sem %s --pidfile %s",
command, semfilename, pidfilename);
system (cmd);
if (system (cmd))
FAIL_EXIT1("system call unexpectedly returned");
/* This call should never return. */
return NULL;
}
+4 -1
View File
@@ -27,6 +27,8 @@
#include <tls.h>
#include <unistd.h>
#include <support/xstdlib.h>
static const char *command;
static bool child;
static uintptr_t stack_chk_guard_copy;
@@ -138,7 +140,8 @@ do_test (void)
dup2 (fds[1], 2);
close (fds[1]);
system (command);
xsystem (command);
exit (0);
}
+137 -112
View File
@@ -23,6 +23,7 @@
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
#include <scratch_buffer.h>
#include "../inet/netgroup.h"
#include "nscd.h"
@@ -65,6 +66,16 @@ struct dataset
char strdata[0];
};
/* Send a notfound response to FD. Always returns -1 to indicate an
ephemeral error. */
static time_t
send_notfound (int fd)
{
if (fd != -1)
TEMP_FAILURE_RETRY (send (fd, &notfound, sizeof (notfound), MSG_NOSIGNAL));
return -1;
}
/* Sends a notfound message and prepares a notfound dataset to write to the
cache. Returns true if there was enough memory to allocate the dataset and
returns the dataset in DATASETP, total bytes to write in TOTALP and the
@@ -83,8 +94,7 @@ do_notfound (struct database_dyn *db, int fd, request_header *req,
total = sizeof (notfound);
timeout = time (NULL) + db->negtimeout;
if (fd != -1)
TEMP_FAILURE_RETRY (send (fd, &notfound, total, MSG_NOSIGNAL));
send_notfound (fd);
dataset = mempool_alloc (db, sizeof (struct dataset) + req->key_len, 1);
/* If we cannot permanently store the result, so be it. */
@@ -109,11 +119,78 @@ do_notfound (struct database_dyn *db, int fd, request_header *req,
return cacheable;
}
struct addgetnetgrentX_scratch
{
/* This is the result that the caller should use. It can be NULL,
point into buffer, or it can be in the cache. */
struct dataset *dataset;
struct scratch_buffer buffer;
/* Used internally in addgetnetgrentX as a staging area. */
struct scratch_buffer tmp;
/* Number of bytes in buffer that are actually used. */
size_t buffer_used;
};
static void
addgetnetgrentX_scratch_init (struct addgetnetgrentX_scratch *scratch)
{
scratch->dataset = NULL;
scratch_buffer_init (&scratch->buffer);
scratch_buffer_init (&scratch->tmp);
/* Reserve space for the header. */
scratch->buffer_used = sizeof (struct dataset);
static_assert (sizeof (struct dataset) < sizeof (scratch->tmp.__space),
"initial buffer space");
memset (scratch->tmp.data, 0, sizeof (struct dataset));
}
static void
addgetnetgrentX_scratch_free (struct addgetnetgrentX_scratch *scratch)
{
scratch_buffer_free (&scratch->buffer);
scratch_buffer_free (&scratch->tmp);
}
/* Copy LENGTH bytes from S into SCRATCH. Returns NULL if SCRATCH
could not be resized, otherwise a pointer to the copy. */
static char *
addgetnetgrentX_append_n (struct addgetnetgrentX_scratch *scratch,
const char *s, size_t length)
{
while (true)
{
size_t remaining = scratch->buffer.length - scratch->buffer_used;
if (remaining >= length)
break;
if (!scratch_buffer_grow_preserve (&scratch->buffer))
return NULL;
}
char *copy = scratch->buffer.data + scratch->buffer_used;
memcpy (copy, s, length);
scratch->buffer_used += length;
return copy;
}
/* Copy S into SCRATCH, including its null terminator. Returns false
if SCRATCH could not be resized. */
static bool
addgetnetgrentX_append (struct addgetnetgrentX_scratch *scratch, const char *s)
{
if (s == NULL)
s = "";
return addgetnetgrentX_append_n (scratch, s, strlen (s) + 1) != NULL;
}
/* Caller must initialize and free *SCRATCH. If the return value is
negative, this function has sent a notfound response. */
static time_t
addgetnetgrentX (struct database_dyn *db, int fd, request_header *req,
const char *key, uid_t uid, struct hashentry *he,
struct datahead *dh, struct dataset **resultp,
void **tofreep)
struct datahead *dh, struct addgetnetgrentX_scratch *scratch)
{
if (__glibc_unlikely (debug_level > 0))
{
@@ -132,14 +209,10 @@ addgetnetgrentX (struct database_dyn *db, int fd, request_header *req,
char *key_copy = NULL;
struct __netgrent data;
size_t buflen = MAX (1024, sizeof (*dataset) + req->key_len);
size_t buffilled = sizeof (*dataset);
char *buffer = NULL;
size_t nentries = 0;
size_t group_len = strlen (key) + 1;
struct name_list *first_needed
= alloca (sizeof (struct name_list) + group_len);
*tofreep = NULL;
if (netgroup_database == NULL
&& !__nss_database_get (nss_database_netgroup, &netgroup_database))
@@ -147,12 +220,10 @@ addgetnetgrentX (struct database_dyn *db, int fd, request_header *req,
/* No such service. */
cacheable = do_notfound (db, fd, req, key, &dataset, &total, &timeout,
&key_copy);
goto writeout;
goto maybe_cache_add;
}
memset (&data, '\0', sizeof (data));
buffer = xmalloc (buflen);
*tofreep = buffer;
first_needed->next = first_needed;
memcpy (first_needed->name, key, group_len);
data.needed_groups = first_needed;
@@ -195,8 +266,8 @@ addgetnetgrentX (struct database_dyn *db, int fd, request_header *req,
while (1)
{
int e;
status = getfct.f (&data, buffer + buffilled,
buflen - buffilled - req->key_len, &e);
status = getfct.f (&data, scratch->tmp.data,
scratch->tmp.length, &e);
if (status == NSS_STATUS_SUCCESS)
{
if (data.type == triple_val)
@@ -204,68 +275,10 @@ addgetnetgrentX (struct database_dyn *db, int fd, request_header *req,
const char *nhost = data.val.triple.host;
const char *nuser = data.val.triple.user;
const char *ndomain = data.val.triple.domain;
size_t hostlen = strlen (nhost ?: "") + 1;
size_t userlen = strlen (nuser ?: "") + 1;
size_t domainlen = strlen (ndomain ?: "") + 1;
if (nhost == NULL || nuser == NULL || ndomain == NULL
|| nhost > nuser || nuser > ndomain)
{
const char *last = nhost;
if (last == NULL
|| (nuser != NULL && nuser > last))
last = nuser;
if (last == NULL
|| (ndomain != NULL && ndomain > last))
last = ndomain;
size_t bufused
= (last == NULL
? buffilled
: last + strlen (last) + 1 - buffer);
/* We have to make temporary copies. */
size_t needed = hostlen + userlen + domainlen;
if (buflen - req->key_len - bufused < needed)
{
buflen += MAX (buflen, 2 * needed);
/* Save offset in the old buffer. We don't
bother with the NULL check here since
we'll do that later anyway. */
size_t nhostdiff = nhost - buffer;
size_t nuserdiff = nuser - buffer;
size_t ndomaindiff = ndomain - buffer;
char *newbuf = xrealloc (buffer, buflen);
/* Fix up the triplet pointers into the new
buffer. */
nhost = (nhost ? newbuf + nhostdiff
: NULL);
nuser = (nuser ? newbuf + nuserdiff
: NULL);
ndomain = (ndomain ? newbuf + ndomaindiff
: NULL);
*tofreep = buffer = newbuf;
}
nhost = memcpy (buffer + bufused,
nhost ?: "", hostlen);
nuser = memcpy ((char *) nhost + hostlen,
nuser ?: "", userlen);
ndomain = memcpy ((char *) nuser + userlen,
ndomain ?: "", domainlen);
}
char *wp = buffer + buffilled;
wp = memmove (wp, nhost ?: "", hostlen);
wp += hostlen;
wp = memmove (wp, nuser ?: "", userlen);
wp += userlen;
wp = memmove (wp, ndomain ?: "", domainlen);
wp += domainlen;
buffilled = wp - buffer;
if (!(addgetnetgrentX_append (scratch, nhost)
&& addgetnetgrentX_append (scratch, nuser)
&& addgetnetgrentX_append (scratch, ndomain)))
return send_notfound (fd);
++nentries;
}
else
@@ -317,8 +330,8 @@ addgetnetgrentX (struct database_dyn *db, int fd, request_header *req,
}
else if (status == NSS_STATUS_TRYAGAIN && e == ERANGE)
{
buflen *= 2;
*tofreep = buffer = xrealloc (buffer, buflen);
if (!scratch_buffer_grow (&scratch->tmp))
return send_notfound (fd);
}
else if (status == NSS_STATUS_RETURN
|| status == NSS_STATUS_NOTFOUND
@@ -348,13 +361,20 @@ addgetnetgrentX (struct database_dyn *db, int fd, request_header *req,
{
cacheable = do_notfound (db, fd, req, key, &dataset, &total, &timeout,
&key_copy);
goto writeout;
goto maybe_cache_add;
}
total = buffilled;
/* Capture the result size without the key appended. */
total = scratch->buffer_used;
/* Make a copy of the key. The scratch buffer must not move after
this point. */
key_copy = addgetnetgrentX_append_n (scratch, key, req->key_len);
if (key_copy == NULL)
return send_notfound (fd);
/* Fill in the dataset. */
dataset = (struct dataset *) buffer;
dataset = scratch->buffer.data;
timeout = datahead_init_pos (&dataset->head, total + req->key_len,
total - offsetof (struct dataset, resp),
he == NULL ? 0 : dh->nreloads + 1,
@@ -363,11 +383,7 @@ addgetnetgrentX (struct database_dyn *db, int fd, request_header *req,
dataset->resp.version = NSCD_VERSION;
dataset->resp.found = 1;
dataset->resp.nresults = nentries;
dataset->resp.result_len = buffilled - sizeof (*dataset);
assert (buflen - buffilled >= req->key_len);
key_copy = memcpy (buffer + buffilled, key, req->key_len);
buffilled += req->key_len;
dataset->resp.result_len = total - sizeof (*dataset);
/* Now we can determine whether on refill we have to create a new
record or not. */
@@ -398,7 +414,7 @@ addgetnetgrentX (struct database_dyn *db, int fd, request_header *req,
if (__glibc_likely (newp != NULL))
{
/* Adjust pointer into the memory block. */
key_copy = (char *) newp + (key_copy - buffer);
key_copy = (char *) newp + (key_copy - (char *) dataset);
dataset = memcpy (newp, dataset, total + req->key_len);
cacheable = true;
@@ -410,14 +426,12 @@ addgetnetgrentX (struct database_dyn *db, int fd, request_header *req,
}
if (he == NULL && fd != -1)
{
/* We write the dataset before inserting it to the database
since while inserting this thread might block and so would
unnecessarily let the receiver wait. */
writeout:
/* We write the dataset before inserting it to the database since
while inserting this thread might block and so would
unnecessarily let the receiver wait. */
writeall (fd, &dataset->resp, dataset->head.recsize);
}
maybe_cache_add:
if (cacheable)
{
/* If necessary, we also propagate the data to disk. */
@@ -441,7 +455,7 @@ addgetnetgrentX (struct database_dyn *db, int fd, request_header *req,
}
out:
*resultp = dataset;
scratch->dataset = dataset;
return timeout;
}
@@ -462,6 +476,9 @@ addinnetgrX (struct database_dyn *db, int fd, request_header *req,
if (user != NULL)
key = (char *) rawmemchr (key, '\0') + 1;
const char *domain = *key++ ? key : NULL;
struct addgetnetgrentX_scratch scratch;
addgetnetgrentX_scratch_init (&scratch);
if (__glibc_unlikely (debug_level > 0))
{
@@ -477,12 +494,8 @@ addinnetgrX (struct database_dyn *db, int fd, request_header *req,
group, group_len,
db, uid);
time_t timeout;
void *tofree;
if (result != NULL)
{
timeout = result->head.timeout;
tofree = NULL;
}
timeout = result->head.timeout;
else
{
request_header req_get =
@@ -491,7 +504,10 @@ addinnetgrX (struct database_dyn *db, int fd, request_header *req,
.key_len = group_len
};
timeout = addgetnetgrentX (db, -1, &req_get, group, uid, NULL, NULL,
&result, &tofree);
&scratch);
result = scratch.dataset;
if (timeout < 0)
goto out;
}
struct indataset
@@ -502,24 +518,26 @@ addinnetgrX (struct database_dyn *db, int fd, request_header *req,
= (struct indataset *) mempool_alloc (db,
sizeof (*dataset) + req->key_len,
1);
struct indataset dataset_mem;
bool cacheable = true;
if (__glibc_unlikely (dataset == NULL))
{
cacheable = false;
dataset = &dataset_mem;
/* The alloca is safe because nscd_run_worker verfies that
key_len is not larger than MAXKEYLEN. */
dataset = alloca (sizeof (*dataset) + req->key_len);
}
datahead_init_pos (&dataset->head, sizeof (*dataset) + req->key_len,
sizeof (innetgroup_response_header),
he == NULL ? 0 : dh->nreloads + 1, result->head.ttl);
he == NULL ? 0 : dh->nreloads + 1,
result == NULL ? db->negtimeout : result->head.ttl);
/* Set the notfound status and timeout based on the result from
getnetgrent. */
dataset->head.notfound = result->head.notfound;
dataset->head.notfound = result == NULL || result->head.notfound;
dataset->head.timeout = timeout;
dataset->resp.version = NSCD_VERSION;
dataset->resp.found = result->resp.found;
dataset->resp.found = result != NULL && result->resp.found;
/* Until we find a matching entry the result is 0. */
dataset->resp.result = 0;
@@ -567,7 +585,9 @@ addinnetgrX (struct database_dyn *db, int fd, request_header *req,
goto out;
}
if (he == NULL)
/* addgetnetgrentX may have already sent a notfound response. Do
not send another one. */
if (he == NULL && dataset->resp.found)
{
/* We write the dataset before inserting it to the database
since while inserting this thread might block and so would
@@ -601,7 +621,7 @@ addinnetgrX (struct database_dyn *db, int fd, request_header *req,
}
out:
free (tofree);
addgetnetgrentX_scratch_free (&scratch);
return timeout;
}
@@ -611,11 +631,12 @@ addgetnetgrentX_ignore (struct database_dyn *db, int fd, request_header *req,
const char *key, uid_t uid, struct hashentry *he,
struct datahead *dh)
{
struct dataset *ignore;
void *tofree;
time_t timeout = addgetnetgrentX (db, fd, req, key, uid, he, dh,
&ignore, &tofree);
free (tofree);
struct addgetnetgrentX_scratch scratch;
addgetnetgrentX_scratch_init (&scratch);
time_t timeout = addgetnetgrentX (db, fd, req, key, uid, he, dh, &scratch);
addgetnetgrentX_scratch_free (&scratch);
if (timeout < 0)
timeout = 0;
return timeout;
}
@@ -659,5 +680,9 @@ readdinnetgr (struct database_dyn *db, struct hashentry *he,
.key_len = he->len
};
return addinnetgrX (db, -1, &req, db->data + he->key, he->owner, he, dh);
time_t timeout = addinnetgrX (db, -1, &req, db->data + he->key, he->owner,
he, dh);
if (timeout < 0)
timeout = 0;
return timeout;
}
+33 -2
View File
@@ -81,6 +81,7 @@ tests-container := \
tst-nss-test3 \
tst-reload1 \
tst-reload2 \
tst-nss-gai-hv2-canonname \
# tests-container
# Tests which need libdl
@@ -144,7 +145,17 @@ libnss_compat-inhibit-o = $(filter-out .os,$(object-suffixes))
ifeq ($(build-static-nss),yes)
tests-static += tst-nss-static
endif
extra-test-objs += nss_test1.os nss_test2.os nss_test_errno.os
extra-test-objs += nss_test1.os nss_test2.os nss_test_errno.os \
nss_test_gai_hv2_canonname.os
ifeq ($(run-built-tests),yes)
ifneq (no,$(PERL))
tests-special += $(objpfx)mtrace-tst-nss-gai-hv2-canonname.out
endif
endif
generated += mtrace-tst-nss-gai-hv2-canonname.out \
tst-nss-gai-hv2-canonname.mtrace
include ../Rules
@@ -179,12 +190,16 @@ rtld-tests-LDFLAGS += -Wl,--dynamic-list=nss_test.ver
libof-nss_test1 = extramodules
libof-nss_test2 = extramodules
libof-nss_test_errno = extramodules
libof-nss_test_gai_hv2_canonname = extramodules
$(objpfx)/libnss_test1.so: $(objpfx)nss_test1.os $(link-libc-deps)
$(build-module)
$(objpfx)/libnss_test2.so: $(objpfx)nss_test2.os $(link-libc-deps)
$(build-module)
$(objpfx)/libnss_test_errno.so: $(objpfx)nss_test_errno.os $(link-libc-deps)
$(build-module)
$(objpfx)/libnss_test_gai_hv2_canonname.so: \
$(objpfx)nss_test_gai_hv2_canonname.os $(link-libc-deps)
$(build-module)
$(objpfx)nss_test2.os : nss_test1.c
# Use the nss_files suffix for these objects as well.
$(objpfx)/libnss_test1.so$(libnss_files.so-version): $(objpfx)/libnss_test1.so
@@ -194,10 +209,14 @@ $(objpfx)/libnss_test2.so$(libnss_files.so-version): $(objpfx)/libnss_test2.so
$(objpfx)/libnss_test_errno.so$(libnss_files.so-version): \
$(objpfx)/libnss_test_errno.so
$(make-link)
$(objpfx)/libnss_test_gai_hv2_canonname.so$(libnss_files.so-version): \
$(objpfx)/libnss_test_gai_hv2_canonname.so
$(make-link)
$(patsubst %,$(objpfx)%.out,$(tests) $(tests-container)) : \
$(objpfx)/libnss_test1.so$(libnss_files.so-version) \
$(objpfx)/libnss_test2.so$(libnss_files.so-version) \
$(objpfx)/libnss_test_errno.so$(libnss_files.so-version)
$(objpfx)/libnss_test_errno.so$(libnss_files.so-version) \
$(objpfx)/libnss_test_gai_hv2_canonname.so$(libnss_files.so-version)
ifeq (yes,$(have-thread-library))
$(objpfx)tst-cancel-getpwuid_r: $(shared-thread-library)
@@ -206,6 +225,17 @@ endif
$(objpfx)tst-nss-files-alias-leak.out: $(objpfx)/libnss_files.so
$(objpfx)tst-nss-files-alias-truncated.out: $(objpfx)/libnss_files.so
tst-nss-gai-hv2-canonname-ENV = \
MALLOC_TRACE=$(objpfx)tst-nss-gai-hv2-canonname.mtrace \
LD_PRELOAD=$(common-objpfx)/malloc/libc_malloc_debug.so
$(objpfx)mtrace-tst-nss-gai-hv2-canonname.out: \
$(objpfx)tst-nss-gai-hv2-canonname.out
{ test -r $(objpfx)tst-nss-gai-hv2-canonname.mtrace \
|| ( echo "tst-nss-gai-hv2-canonname.mtrace does not exist"; exit 77; ) \
&& $(common-objpfx)malloc/mtrace \
$(objpfx)tst-nss-gai-hv2-canonname.mtrace; } > $@; \
$(evaluate-test)
# Disable DT_RUNPATH on NSS tests so that the glibc internal NSS
# functions can load testing NSS modules via DT_RPATH.
LDFLAGS-tst-nss-test1 = -Wl,--disable-new-dtags
@@ -214,3 +244,4 @@ LDFLAGS-tst-nss-test3 = -Wl,--disable-new-dtags
LDFLAGS-tst-nss-test4 = -Wl,--disable-new-dtags
LDFLAGS-tst-nss-test5 = -Wl,--disable-new-dtags
LDFLAGS-tst-nss-test_errno = -Wl,--disable-new-dtags
LDFLAGS-tst-nss-test_gai_hv2_canonname = -Wl,--disable-new-dtags

Some files were not shown because too many files have changed in this diff Show More