Compare commits

...
Author SHA1 Message Date
Florian Weimer 872743b638 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 15:03:58 +02:00
DJ Delorie c13121204a 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)

(Adjusted sysdeps/unix/sysv/linux/Makefile for lack of reformatting.)
2026-05-02 15:03:35 +02:00
Florian Weimer 7abd383d43 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 22:33:17 +02:00
Xi Ruoyao 4561d6af9f 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 20:23:32 +02:00
Carlos O'Donell d549918c84 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 20:23:32 +02:00
Carlos O'Donell fe7ce8f574 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 20:23:32 +02:00
Florian Weimer 1dca88cfab 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 20:23:32 +02:00
Florian Weimer 51eeaa8bf0 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 20:23:32 +02:00
Adhemerval Zanella e97cfe2293 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:28:10 -03:00
Carlos O'Donell a6bf47887f 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:39 -05:00
Siddhesh Poyarekar fb6b882217 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:36:38 +01:00
Sunil K Pandey 466f6e2bb5 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:58:45 -08:00
Sachin Monga e4e28edc78 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:28:27 -05:00
Jiamei Xie 945cb7d935 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:32 +00:00
H.J. Lu 99338e3841 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:20:07 +01:00
Florian Weimer b8717fb2d5 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:58:27 +02:00
Florian Weimer 81188fb7df 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:57:51 +02:00
Florian Weimer 5bec8bd46f 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:57:48 +02:00
Adhemerval Zanella 05fc7da007 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:57:29 +02:00
Florian Weimer 8071618725 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:52:30 +02:00
Florian Weimer 902680a6fd 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:48:27 +02:00
Florian Weimer d0e60bebb3 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:48:27 +02:00
Siddhesh Poyarekar 909ec8415c 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:48:27 +02:00
Florian Weimer 9403232d98 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:02:10 +02:00
Florian Weimer 02809c23a3 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:45:02 +02:00
Florian Weimer 59273e870f 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:45:02 +02:00
Florian Weimer 1721d69cc7 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:45:02 +02:00
Adhemerval Zanella 2ef7850279 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:45:02 +02:00
Wilco Dijkstra 03e0cad3a0 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 15:04:26 +00:00
Wilco Dijkstra 4f3b4e7b52 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 15:04:26 +00:00
Wilco Dijkstra c0aebc61b0 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 15:04:24 +00:00
Wilco Dijkstra eb2d69db2d 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 15:03:30 +00:00
Wilco Dijkstra 2c9bfcf3ed 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 15:03:30 +00:00
Wilco Dijkstra 37243ba10a 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 15:03:28 +00:00
Wilco Dijkstra 4909fb4d96 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 15:03:04 +00:00
Siddhesh Poyarekar 0487893d5c 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:34:21 -05:00
Carlos O'Donell b33ecb069b 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)

 # Conflicts:
 #	assert/Makefile
 (Missing __libc_assert_fail)
2025-02-13 13:32:59 -05:00
H.J. Lu d5eee9726d 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:15:28 +08:00
Florian Weimer 7971add7ee 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)

Conflict in sysdeps/posix/libc_fatal.c due to missing cleanup after
backtrace removal.
2025-01-22 18:30:43 +01:00
Yu Chien Peter Lin e943a75e58 nptl: Convert tst-setuid2 to test-driver
Use <support/test-driver.c> and replace pthread calls to its xpthread
equivalents.

Signed-off-by: Yu Chien Peter Lin <peterlin@andestech.com>
Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit 365b3af67e)
2025-01-11 12:43:37 -08:00
Yu Chien Peter Lin 1164f18399 support: Add xpthread_cond_signal wrapper
Signed-off-by: Yu Chien Peter Lin <peterlin@andestech.com>
Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit 3bea50ccbc)
2025-01-11 12:43:24 -08:00
Florian Weimer 53b3a3a26f 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-11 08:19:41 -08:00
Florian Weimer daa48c814b 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-11 08:19:21 -08:00
H.J. Lu f739705944 sysdeps/x86/Makefile: Split and sort tests
Put each test on a separate line and sort tests.

(cherry picked from commit 7e03e0de7e)
2025-01-10 08:49:54 -08:00
Noah Goldstein 27296daa25 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-10 08:49:42 -08:00
Szabolcs Nagy 147a830307 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-10 08:49:31 -08:00
H.J. Lu f1c33665e5 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-10 08:49:19 -08:00
H.J. Lu 78a9a50bf2 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-10 08:49:05 -08:00
H.J. Lu f3a9a9facc 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-10 08:48:56 -08:00
H.J. Lu d3bc49260c 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-10 08:48:46 -08:00
H.J. Lu abfa5410a0 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-10 08:48:30 -08:00
Florian Weimer fbcde5ea46 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 19:07:38 +01:00
Michael Jeanson 314419978f 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:08:55 +00:00
Michael Jeanson b1f62861bf 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:08:55 +00:00
Florian Weimer b3b68740cf 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:16:26 +01:00
Siddhesh Poyarekar 485b2a773d 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:18:17 +02:00
Maciej W. Rozycki c3a3240b64 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:59 -04:00
Maciej W. Rozycki 43b9069a58 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:57 -04:00
Siddhesh Poyarekar e76e84dfcb 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 20:25:10 -04:00
Siddhesh Poyarekar 86ad51cc6f 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 20:25:10 -04:00
Siddhesh Poyarekar 5a9f74b6f4 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 20:25:10 -04:00
Maciej W. Rozycki 6484b76fa3 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 20:25:09 -04:00
Maciej W. Rozycki ac048a43f4 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 20:24:46 -04:00
Andreas Schwab 09f2d9f1da 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:48:10 +02:00
Florian Weimer b81776b941 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:58 +02:00
Florian Weimer b41034cebf 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:15:36 +02:00
H.J. Lu 26e2759e59 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 16:59:32 +02:00
H.J. Lu ab482a557d 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 16:59:32 +02:00
Frédéric Bérat 45cfbf015f 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 16:59:26 +02:00
Florian Weimer 3d252f17b8 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:37:50 +02:00
Florian Weimer 789addc412 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:38:07 +02:00
Florian Weimer 4987404a5f 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:37:35 +02:00
Samuel Thibault e47b88d2fb aio: Fix freeing memory
The content of the pool array is initialized only until pool_size,
pointers between pool_size and pool_max_size were not initialized by the
realloc call in get_elem so they should not be freed.

This fixes aio tests crashing at their termination on GNU/Hurd.

(cherry picked from commit 0cee4aa92f)
2024-07-20 20:52:40 +02:00
Stafford Horne f908fa07c6 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)
2024-07-20 19:30:25 +02:00
Florian Weimer b0471d1605 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:59:45 +02:00
Adhemerval Zanella bce1d80721 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:25:28 +02:00
Michael Jeanson 72f4c0533c 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:25:28 +02:00
Joseph Myers 61da55a07f 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:25:24 +02:00
Stefan Liebler a70c55a91b 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:30:45 +02:00
H.J. Lu ee65bc1df6 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:06:15 -07:00
Florian Weimer 6c9e370891 elf: Disable some subtests of ifuncmain1, ifuncmain5 for !PIE
(cherry picked from commit 9cc9d61ee1)
2024-05-02 23:18:23 +02:00
Florian Weimer ce639236ca 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 20:51:28 +02:00
Florian Weimer 85242ed63a 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 19:30:48 +02:00
Florian Weimer eeeaf0fe2d 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 19:30:48 +02:00
Adhemerval Zanella 5b48737556 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 19:30:48 +02:00
H.J. Lu d31c4d38a3 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:22:37 -07:00
Florian Weimer b674246369 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:42:42 +02:00
Florian Weimer f205b3af56 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:42:42 +02:00
Florian Weimer c34f470a61 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:42:42 +02:00
Florian Weimer caa3151ca4 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:42:42 +02:00
Charles FolandAdhemerval Zanella 4ed98540a7 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:44 -03:00
Florian Weimer 78ad1b1b0d 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 10:34:10 +02:00
Wilco Dijkstra 24de733967 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 17:08:03 +01:00
Szabolcs Nagy b77e357bf9 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:53:05 +01:00
Andreas Schwab 88e96e7b5f 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:52:55 +01:00
Wilco Dijkstra 5a5211b438 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:52:39 +01:00
Wilco Dijkstra 1da0176152 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:51:34 +01:00
Wilco Dijkstra f9ae26cbbe 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:50:46 +01:00
Wilco Dijkstra 6bb4121873 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:49:14 +01:00
Wilco Dijkstra 3bac018a98 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:47:51 +01:00
Joseph Myers aaa0fc324d 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:47:23 +01:00
Wilco Dijkstra f45608f6d7 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:46:36 +01:00
Wilco Dijkstra 600098c58a AArch64: Improve strrchr
Use shrn for narrowing the mask which simplifies code and speeds up small
strings.  Unroll the first search loop to improve performance on large
strings.

Reviewed-by: Szabolcs Nagy <szabolcs.nagy@arm.com>
(cherry picked from commit 55599d4804)
2024-04-08 16:46:23 +01:00
Wilco Dijkstra 7cbcc95927 AArch64: Optimize strnlen
Optimize strnlen using the shrn instruction and improve the main loop.
Small strings are around 10% faster, large strings are 40% faster on
modern CPUs.

Reviewed-by: Szabolcs Nagy <szabolcs.nagy@arm.com>
(cherry picked from commit ad098893ba)
2024-04-08 16:46:11 +01:00
Wilco Dijkstra daa13ed0ac AArch64: Optimize strlen
Optimize strlen by unrolling the main loop.  Large strings are 64% faster on
modern CPUs.

Reviewed-by: Szabolcs Nagy <szabolcs.nagy@arm.com>
(cherry picked from commit 03c8ce5000)
2024-04-08 16:45:59 +01:00
Wilco Dijkstra 90d9b8897b AArch64: Optimize strcpy
Unroll the main loop.  Large strings are around 20% faster on modern CPUs.

Reviewed-by: Szabolcs Nagy <szabolcs.nagy@arm.com>
(cherry picked from commit 349e48c01e)
2024-04-08 16:45:50 +01:00
Wilco Dijkstra 8ee69bd2df AArch64: Improve strchrnul
Unroll the main loop, which improves performance slightly.

Reviewed-by: Szabolcs Nagy <szabolcs.nagy@arm.com>
(cherry picked from commit 09ebd8549b)
2024-04-08 16:45:31 +01:00
Wilco Dijkstra 2e4cdcbd35 AArch64: Optimize strchr
Simplify calculation of the mask using shrn.  Unroll the main loop.
Small strings are 20% faster on modern CPUs.

Reviewed-by: Szabolcs Nagy <szabolcs.nagy@arm.com>
(cherry picked from commit 51541a2297)
2024-04-08 16:45:20 +01:00
Wilco Dijkstra ef62fc2223 AArch64: Improve strlen_asimd
Use shrn for the mask, merge tst+bne into cbnz, and tweak code alignment.
Performance improves slightly as a result.

Reviewed-by: Szabolcs Nagy <szabolcs.nagy@arm.com>
(cherry picked from commit 1bbb1a2022)
2024-04-08 16:42:24 +01:00
Wilco Dijkstra 1296aa9b0b AArch64: Optimize memrchr
Optimize the main loop - large strings are 43% faster on modern CPUs.

Reviewed-by: Szabolcs Nagy <szabolcs.nagy@arm.com>
(cherry picked from commit 0077624177)
2024-04-08 16:42:14 +01:00
Wilco Dijkstra 34424b6770 AArch64: Optimize memchr
Optimize the main loop - large strings are 40% faster on modern CPUs.

Reviewed-by: Szabolcs Nagy <szabolcs.nagy@arm.com>
(cherry picked from commit ce758d4f06)
2024-04-08 16:42:04 +01:00
Wilco Dijkstra 0cbe0b1a47 aarch64: Use memcpy_simd as the default memcpy
Since __memcpy_simd is the fastest memcpy on almost all cores, replace
the generic memcpy with it.  If SVE is available, a SVE memcpy will be
used by default (including for Neoverse N2).

(cherry picked from commit e6f3fe362f)
2024-04-08 16:41:52 +01:00
Wilco Dijkstra 9627bbbc1c aarch64: Cleanup memset ifunc
Cleanup memset ifunc selectors. The A64FX memset relies on a ZVA size of
256, so add an explicit check.

(cherry picked from commit a8e72913fe)
2024-04-08 16:41:36 +01:00
Wilco Dijkstra c21dfb3018 AArch64: Fix typo in sve configure check (BZ# 29394)
Fix a typo in the SVE configure check. This fixes [BZ# 29394].

(cherry picked from commit 12182ba18d)
2024-04-08 16:41:23 +01:00
Florian Weimer 1b85f77f43 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: 54e812100d
2024-03-18 18:16:29 +01:00
Stefan Liebler b204650058 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:16:29 +01:00
Florian Weimer 54e812100d 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:45:24 +01:00
Paul Eggert e24f8e6b35 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:45:19 +01:00
Andreas Schwab 4d4ba8bae4 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:25:59 -03:00
Adhemerval Zanella 8e99cc76a2 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 10:01:23 -03:00
Adhemerval Zanella ec6aaab3e1 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:21 -03:00
Daniel Cederman 2853e541c5 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 08:54:36 -03:00
Adhemerval Zanella f4171ba5e5 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 08:53:58 -03:00
Adhemerval Zanella b233c44964 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 08:53:33 -03:00
Andreas Larsson d5e88bbf59 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:28 -03:00
Sunil K Pandey c54d08756c 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:49:44 -08:00
Arjun Shankar b9b7d6a27a 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:57:01 +01:00
Arjun Shankar 2bc9d7c002 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:57:01 +01:00
Arjun Shankar d1a83b6767 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:57:01 +01:00
H.J. Lu cc5b5da135 NEWS: Mention bug fixes for 29039/30745/30843 2023-12-23 07:17:41 -08:00
H.J. Lu 5dfafca33c 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 07:13:36 -08:00
H.J. Lu 6a1168279d 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 07:11:29 -08:00
Hector Martin 882a991620 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:38:54 +00:00
Florian Weimer 88d5d70b1e Revert "elf: Move l_init_called_next to old place of l_text_end in link map"
This reverts commit f441cb9a70.

Reason for revert: Preserve internal ABI.
2023-10-19 09:29:42 +02:00
Florian Weimer dc3b5b9048 Revert "elf: Always call destructors in reverse constructor order (bug 30785)"
This reverts commit 5d83a52a49.

Reason for revert: Incompatibility with existing applications.
2023-10-18 14:31:02 +02:00
Florian Weimer ad96b55325 Revert "elf: Remove unused l_text_end field from struct link_map"
This reverts commit 9f0d3bb2e3.

Reason for revert: Preserve ABI after revert of commit 5d83a52a4.
2023-10-18 14:30:00 +02:00
Siddhesh Poyarekar 22955ad851 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:40:33 -04:00
Siddhesh Poyarekar 32957eb6a8 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 13:11:52 -04:00
Romain Geissler 856bac55f9 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 13:11:46 -04:00
Siddhesh Poyarekar a9728f798e 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 18:24:58 -04:00
Aurelien Jarno 0ae2afe45e 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-15 21:31:05 +02:00
Florian Weimer 4ea972b7ed 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:37:57 +02:00
Florian Weimer f441cb9a70 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:36:04 +02:00
Florian Weimer 9f0d3bb2e3 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:36:04 +02:00
Florian Weimer 5d83a52a49 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:36:01 +02:00
Florian Weimer f33ffef089 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:35:47 +02:00
Florian Weimer b6c7135576 elf: Introduce to _dl_call_fini
This consolidates the destructor invocations from _dl_fini and
dlclose.  Remove the micro-optimization that avoids
calling _dl_call_fini if they are no destructors (as dlclose is quite
expensive anyway).  The debug log message is now printed
unconditionally.

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
2023-09-11 09:35:47 +02:00
Noah Goldstein eb8bf044bd 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-09-05 17:17:01 -05:00
Noah Goldstein 64b184fd80 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-09-05 17:17:01 -05:00
Noah Goldstein 42c266a18f 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-09-05 17:17:01 -05:00
Noah Goldstein 2e74c90167 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-09-05 17:17:01 -05:00
Florian Weimer c36912f083 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 11:14:39 +02:00
Adhemerval Zanella 735cc66813 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:31:56 -03:00
Adhemerval Zanella 53b58a681d 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:43:17 -03:00
H.J. Lu 93bd77104c Document BZ #20975 fix 2023-05-23 16:45:03 -07:00
H.J. Lu 7df9a27656 __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:51 -07:00
Florian Weimer b7008a92f5 gmon: Revert addition of tunables to the manual
These tunables had to be removed over GLIBC_PRIVATE ABI stability
concerns.
2023-04-28 18:13:19 +02:00
Florian Weimer dee43b3460 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:12:17 +02:00
Simon Kissane 3c98431da5 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 16:18:02 +02:00
Simon Kissane 8920855c45 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 16:17:19 +02:00
Леонид Юрьев (Leonid Yuriev) 33909e5abc 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 16:17:00 +02:00
Adam Yi 48af2676a7 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 16:16:40 +02:00
Florian Weimer 95c5bddc9f 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:34:06 +02:00
Florian Weimer 6d42a86ad3 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:35:54 +02:00
H.J. Lu f3991fec80 x86: Check minimum/maximum of non_temporal_threshold [BZ #29953]
The minimum non_temporal_threshold is 0x4040.  non_temporal_threshold may
be set to less than the minimum value when the shared cache size isn't
available (e.g., in an emulator) or by the tunable.  Add checks for
minimum and maximum of non_temporal_threshold.

This fixes BZ #29953.

(cherry picked from commit 48b74865c6)
2023-03-15 08:23:56 -07:00
Vitaly Buka fb1bd9f003 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:13:52 -03:00
Florian Weimer 172f72e45e 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 18:21:51 +01:00
Andreas Schwab faf065fc4c 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 10:37:30 -03:00
Adhemerval Zanella d5aaece8a3 elf: Fix GL(dl_phdr) and GL(dl_phnum) for static builds [BZ #29864]
The 73fc4e28b9 refactor did not add the GL(dl_phdr) and
GL(dl_phnum) for static build, relying on the __ehdr_start symbol,
which is always added by the static linker, to get the correct values.

This is problematic in some ways:

  - The segment may see its in-memory size differ from its in-file
    size (or the binary may have holes).  The Linux has fixed is to
    provide concise values for both AT_PHDR and AT_PHNUM (commit
    0da1d5002745c - "fs/binfmt_elf: Fix AT_PHDR for unusual ELF files")

  - Some archs (alpha for instance) the hidden weak reference is not
    correctly pulled by the static linker and  __ehdr_start address
    end up being 0, which makes GL(dl_phdr) and GL(dl_phnum) have both
    invalid values (and triggering a segfault later on libc.so while
    accessing TLS variables).

The safer fix is to just restore the previous behavior to setup
GL(dl_phdr) and GL(dl_phnum) for static based on kernel auxv.  The
__ehdr_start fallback can also be simplified by not assuming weak
linkage (as for PIE).

The libc-static.c auxv init logic is moved to dl-support.c, since
the later is build without SHARED and then GLRO macro is defined
to access the variables directly.

The _dl_phdr is also assumed to be always non NULL, since an invalid
NULL values does not trigger TLS initialization (which is used in
various libc systems).

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

Reviewed-by: Florian Weimer <fweimer@redhat.com>
(cherry picked from commit 7e31d16651)
2023-02-03 10:58:23 -03:00
Siddhesh Poyarekar 56e00c5854 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 09:29:33 -05:00
Noah Goldstein 93967a2a7b x86: Prevent SIGSEGV in memcmp-sse2 when data is concurrently modified [BZ #29863]
In the case of INCORRECT usage of `memcmp(a, b, N)` where `a` and `b`
are concurrently modified as `memcmp` runs, there can be a SIGSEGV
in `L(ret_nonzero_vec_end_0)` because the sequential logic
assumes that `(rdx - 32 + rax)` is a positive 32-bit integer.

To be clear, this change does not mean the usage of `memcmp` is
supported.  The program behaviour is undefined (UB) in the
presence of data races, and `memcmp` is incorrect when the values
of `a` and/or `b` are modified concurrently (data race). This UB
may manifest itself as a SIGSEGV. That being said, if we can
allow the idiomatic use cases, like those in yottadb with
opportunistic concurrency control (OCC), to execute without a
SIGSEGV, at no cost to regular use cases, then we can aim to
minimize harm to those existing users.

The fix replaces a 32-bit `addl %edx, %eax` with the 64-bit variant
`addq %rdx, %rax`. The 1-extra byte of code size from using the
64-bit instruction doesn't contribute to overall code size as the
next target is aligned and has multiple bytes of `nop` padding
before it. As well all the logic between the add and `ret` still
fits in the same fetch block, so the cost of this change is
basically zero.

The relevant sequential logic can be seen in the following
pseudo-code:
```
    /*
     * rsi = a
     * rdi = b
     * rdx = len - 32
     */
    /* cmp a[0:15] and b[0:15]. Since length is known to be [17, 32]
    in this case, this check is also assumed to cover a[0:(31 - len)]
    and b[0:(31 - len)].  */
    movups  (%rsi), %xmm0
    movups  (%rdi), %xmm1
    PCMPEQ  %xmm0, %xmm1
    pmovmskb %xmm1, %eax
    subl    %ecx, %eax
    jnz L(END_NEQ)

    /* cmp a[len-16:len-1] and b[len-16:len-1].  */
    movups  16(%rsi, %rdx), %xmm0
    movups  16(%rdi, %rdx), %xmm1
    PCMPEQ  %xmm0, %xmm1
    pmovmskb %xmm1, %eax
    subl    %ecx, %eax
    jnz L(END_NEQ2)
    ret

L(END2):
    /* Position first mismatch.  */
    bsfl    %eax, %eax

    /* The sequential version is able to assume this value is a
    positive 32-bit value because the first check included bytes in
    range a[0:(31 - len)] and b[0:(31 - len)] so `eax` must be
    greater than `31 - len` so the minimum value of `edx` + `eax` is
    `(len - 32) + (32 - len) >= 0`. In the concurrent case, however,
    `a` or `b` could have been changed so a mismatch in `eax` less or
    equal than `(31 - len)` is possible (the new low bound is `(16 -
    len)`. This can result in a negative 32-bit signed integer, which
    when zero extended to 64-bits is a random large value this out
    out of bounds. */
    addl %edx, %eax

    /* Crash here because 32-bit negative number in `eax` zero
    extends to out of bounds 64-bit offset.  */
    movzbl  16(%rdi, %rax), %ecx
    movzbl  16(%rsi, %rax), %eax
```

This fix is quite simple, just make the `addl %edx, %eax` 64 bit (i.e
`addq %rdx, %rax`). This prevents the 32-bit zero extension
and since `eax` is still a low bound of `16 - len` the `rdx + rax`
is bound by `(len - 32) - (16 - len) >= -16`. Since we have a
fixed offset of `16` in the memory access this must be in bounds.

(cherry picked from commit b712be5264)
2023-01-11 18:21:23 -08:00
Florian Weimer e05036b194 time: Set daylight to 1 for matching DST/offset change (bug 29951)
The daylight variable is supposed to be set to 1 if DST is ever in
use for the current time zone.  But __tzfile_read used to do this:

  __daylight = rule_stdoff != rule_dstoff;

This check can fail to set __daylight to 1 if the DST and non-DST
offsets happen to be the same.

(cherry picked from commit 35141f304e)
2023-01-10 16:27:23 +01:00
Alan Modra dbd23eaca9 elf/tst-tlsopt-powerpc fails when compiled with -mcpu=power10 (BZ# 29776)
Supports pcrel addressing of TLS GOT entry.  Also tweak the non-pcrel
asm constraint to better reflect how the reg is used.

(cherry picked from commit 94628de778)
2023-01-10 16:26:37 +01:00
Adhemerval Zanella Netto 4f4d7a13ed x86: Fix -Os build (BZ #29576)
The compiler might transform __stpcpy calls (which are routed to
__builtin_stpcpy as an optimization) to strcpy and x86_64 strcpy
multiarch implementation does not build any working symbol due
ISA_SHOULD_BUILD not being evaluated for IS_IN(rtld).

Checked on x86_64-linux-gnu.
Reviewed-by: Carlos O'Donell <carlos@redhat.com>
Tested-by: Carlos O'Donell <carlos@redhat.com>

(cherry picked from commit 9dc4e29f63)
2022-12-28 17:47:18 -03:00
Adhemerval Zanella Netto 997d844a97 sunrpc: Suppress GCC -Os warning on user2netname
GCC with -Os warns that sprint might overflow:

  netname.c: In function ‘user2netname’:
  netname.c:51:28: error: ‘%s’ directive writing up to 255 bytes into a
  region of size between 239 and 249 [-Werror=format-overflow=]
     51 |   sprintf (netname, "%s.%d@%s", OPSYS, uid, dfltdom);
        |                            ^~               ~~~~~~~
  netname.c:51:3: note: ‘sprintf’ output between 8 and 273 bytes into a
  destination of size 256
     51 |   sprintf (netname, "%s.%d@%s", OPSYS, uid, dfltdom);
        |   ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  cc1: all warnings being treated as errors

However the code does test prior the sprintf call that dfltdom plus
the required extra space for OPSYS, uid, and extra character will not
overflow and return 0 instead.

Checked on x86_64-linux-gnu and i686-linux-gnu.
Reviewed-by: Carlos O'Donell <carlos@redhat.com>
Tested-by: Carlos O'Donell <carlos@redhat.com>

(cherry picked from commit 6128e82ebe)
2022-12-28 17:37:42 -03:00
Martin Jansa 4444be051c locale: prevent maybe-uninitialized errors with -Os [BZ #19444]
Fixes following error when building  with -Os:
| In file included from strcoll_l.c:43:
| strcoll_l.c: In function '__strcoll_l':
| ../locale/weight.h:31:26: error: 'seq2.back_us' may be used
uninitialized in this function [-Werror=maybe-uninitialized]
|    int_fast32_t i = table[*(*cpp)++];
|                           ^~~~~~~~~
| strcoll_l.c:304:18: note: 'seq2.back_us' was declared here
|    coll_seq seq1, seq2;
|                   ^~~~
| In file included from strcoll_l.c:43:
| ../locale/weight.h:31:26: error: 'seq1.back_us' may be used
uninitialized in this function [-Werror=maybe-uninitialized]
|    int_fast32_t i = table[*(*cpp)++];
|                           ^~~~~~~~~
| strcoll_l.c:304:12: note: 'seq1.back_us' was declared here
|    coll_seq seq1, seq2;
|             ^~~~
Reviewed-by: Carlos O'Donell <carlos@redhat.com>
Tested-by: Carlos O'Donell <carlos@redhat.com>

(cherry picked from commit c651f9da53)
2022-12-28 17:33:45 -03:00
Adhemerval Zanella Netto 4321cbc2af time: Use 64 bit time on tzfile
The tzfile_mtime is already compared to 64 bit time_t stat call.
Reviewed-by: DJ Delorie <dj@redhat.com>

(cherry picked from commit 4e21c20751)
2022-12-28 17:26:23 -03:00
Adhemerval Zanella Netto c1e080bc95 nscd: Use 64 bit time_t on libc nscd routines (BZ# 29402)
Although the nscd module is built with 64 bit time_t, the routines
linked direct to libc.so need to use the internal symbols.
Reviewed-by: DJ Delorie <dj@redhat.com>

(cherry picked from commit fa4a192778)
2022-12-28 17:26:22 -03:00
Adhemerval Zanella Netto fdcd20a55b nis: Build libnsl with 64 bit time_t
And remove the usage of glibc reserved names.
Reviewed-by: DJ Delorie <dj@redhat.com>

(cherry picked from commit 545eefc2f5)
2022-12-28 15:48:08 -03:00
Tulio Magno Quites Machado Filho 3aae843e9e Apply asm redirections in syslog.h before first use [BZ #27087]
Similar to d0fa09a770, but for syslog.h when _FORTIFY_SOURCE > 0.
Fixes [BZ #27087] by applying long double-related asm redirections
before using functions in bits/syslog.h.

Tested with build-many-glibcs.py.

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit 227df6243a)
2022-11-29 17:06:02 -03:00
Noah Goldstein fa196d06d3 x86: Fix wcsnlen-avx2 page cross length comparison [BZ #29591]
Previous implementation was adjusting length (rsi) to match
bytes (eax), but since there is no bound to length this can cause
overflow.

Fix is to just convert the byte-count (eax) to length by dividing by
sizeof (wchar_t) before the comparison.

Full check passes on x86-64 and build succeeds w/ and w/o multiarch.

(cherry picked from commit b0969fa53a)
2022-11-24 10:40:09 -08:00
Vladislav Khmelevsky 2ba9801d9f elf: Fix rtld-audit trampoline for aarch64
This patch fixes two problems with audit:

  1. The DL_OFFSET_RV_VPCS offset was mixed up with DL_OFFSET_RG_VPCS,
     resulting in x2 register value nulling in RG structure.

  2. We need to preserve the x8 register before function call, but
     don't have to save it's new value and restore it before return.

Anyway the final restore was using OFFSET_RV instead of OFFSET_RG value
which is wrong (althoug doesn't affect anything).

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit eb4181e9f4)
2022-11-22 10:45:11 -03:00
Florian Weimer 0f90d6204d Linux: Support __IPC_64 in sysvctl *ctl command arguments (bug 29771)
Old applications pass __IPC_64 as part of the command argument because
old glibc did not check for unknown commands, and passed through the
arguments directly to the kernel, without adding __IPC_64.
Applications need to continue doing that for old glibc compatibility,
so this commit enables this approach in current glibc.

For msgctl and shmctl, if no translation is required, make
direct system calls, as we did before the time64 changes.  If
translation is required, mask __IPC_64 from the command argument.

For semctl, the union-in-vararg argument handling means that
translation is needed on all architectures.

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit 22a46dee24)
2022-11-11 18:45:04 +01:00
Paul Eggert 70410f2286 mktime: improve heuristic for ca-1986 Indiana DST
This patch syncs mktime.c from Gnulib, fixing a
problem reported by Mark Krenz <https://bugs.gnu.org/48085>,
and it should fix BZ#29035 too.
* time/mktime.c (__mktime_internal): Be more generous about
accepting arguments with the wrong value of tm_isdst, by falling
back to a one-hour DST difference if we find no nearby DST that is
unusual.  This fixes a problem where "1986-04-28 00:00 EDT" was
rejected when TZ="America/Indianapolis" because the nearest DST
timestamp occurred in 1970, a temporal distance too great for the
old heuristic.  This also also narrows the search a bit, which
is a minor performance win.

(cherry picked from commit 83859e1115)
2022-11-08 22:46:32 -05:00
Sergei Trofimovich 36cc06341a Makerules: fix MAKEFLAGS assignment for upcoming make-4.4 [BZ# 29564]
make-4.4 will add long flags to MAKEFLAGS variable:

    * WARNING: Backward-incompatibility!
      Previously only simple (one-letter) options were added to the MAKEFLAGS
      variable that was visible while parsing makefiles.  Now, all options
      are available in MAKEFLAGS.

This causes locale builds to fail when long options are used:

    $ make --shuffle
    ...
    make  -C localedata install-locales
    make: invalid shuffle mode: '1662724426r'

The change fixes it by passing eash option via whitespace and dashes.
That way option is appended to both single-word form and whitespace
separated form.

While at it fixed --silent mode detection in $(MAKEFLAGS) by filtering
out --long-options. Otherwise options like --shuffle flag enable silent
mode unintentionally. $(silent-make) variable consolidates the checks.

Resolves: BZ# 29564

CC: Paul Smith <psmith@gnu.org>
CC: Siddhesh Poyarekar <siddhesh@gotplt.org>
Signed-off-by: Sergei Trofimovich <slyich@gmail.com>
Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit 2d7ed98add)
2022-11-08 22:46:32 -05:00
caiyinyu 2fce85f67c LoongArch: Fix ABI related macros in elf.h to keep consistent with binutils[1].
[1]:
https://sourceware.org/git/?p=binutils-gdb.git;a=commitdiff;h=c4a7e6b56218e1d5a858682186b542e2eae01a4a;hp=0d94a8735055432029237612a6eb9165db1ec9dd
[2]:
Reference: https://loongson.github.io/LoongArch-Documentation/LoongArch-ELF-ABI-EN.html#_e_flags_identifies_abi_type_and_version
2022-11-03 21:07:41 +08:00
Aurelien Jarno dd4131c832 linux: Fix fstatat on MIPSn64 (BZ #29730)
Commit 6e8a0aac2f ("time: Fix overflow itimer tests on 32-bit
systems") changed in_time_t_range to assume a 32-bit time_t. This broke
fstatat on MIPSn64 that was using it with a 64-bit time_t due to
difference between stat and stat64. This commit fix that by adding a
MIPSn64 specific version, which bypasses the EOVERFLOW tests.

Resolves: BZ #29730

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit 7457b7eef8)
2022-11-02 16:41:56 +01:00
Xi Ruoyao 4c6a78adda longlong.h: update from GCC for LoongArch clz/ctz support
Update longlong.h to GCC r13-3269.  Keep our local change (prefer https
for gnu.org URL).
2022-10-28 15:06:38 +08:00
Adhemerval Zanella a1dc0be03c elf: Reinstate on DL_DEBUG_BINDINGS _dl_lookup_symbol_x
The prelink removal done by 6628c742b2 wrongly removed the debug
support.

Checked on x86_64-linux-gnu.

(cherry picked from commit 891a7958a2)
2022-10-26 10:03:00 -03:00
Adhemerval Zanella 7b7dfbb0cb linux: Fix generic struct_stat for 64 bit time (BZ# 29657)
The generic Linux struct_stat misses the conditionals to use
bits/struct_stat_time64_helper.h in the __USE_TIME_BITS64 for
architecture that uses __TIMESIZE == 32 (currently csky and nios2).

Since newer ports should not support 32 bit time_t, the generic
implementation should be used as default.

For arm, hppa, and sh a copy of default struct_stat is added,
while for csky and nios a new one based on generic is used, along
with conditionals to use bits/struct_stat_time64_helper.h.

The default struct_stat is also replaced with the generic one.

Checked on aarch64-linux-gnu and arm-linux-gnueabihf.

(cherry picked from commit 7a6ca82f80)
2022-10-25 16:13:11 -03:00
Aurelien Jarno 9273b2d0e9 Avoid undefined behaviour in ibm128 implementation of llroundl (BZ #29488)
Detecting an overflow edge case depended on signed overflow of a long
long. Replace the additions and the overflow checks by
__builtin_add_overflow().

Reviewed-by: Tulio Magno Quites Machado Filho <tuliom@linux.ibm.com>
(cherry picked from commit 2b5478569e)
2022-10-24 20:57:57 +02:00
Michael Hudson-Doyle b357157361 Fix BZ #29463 in the ibm128 implementation of y1l too
Avoid moving code across SET_RESTORE_ROUNDL in order to fix
[BZ #29463].

Tested-by: Aurelien Jarno <aurelien@aurel32.net>
Reviewed-by: Aurelien Jarno <aurelien@aurel32.net>
Reviewed-by: Tulio Magno Quites Machado Filho <tuliom@linux.ibm.com>
(cherry picked from commit b6e37b7805)
2022-10-24 20:56:41 +02:00
Florian Weimer 19535f3b57 elf: Do not completely clear reused namespace in dlmopen (bug 29600)
The data in the _ns_debug member must be preserved, otherwise
_dl_debug_initialize enters an infinite loop.  To be conservative,
only clear the libc_map member for now, to fix bug 29528.

Fixes commit d0e357ff45
("elf: Call __libc_early_init for reused namespaces (bug 29528)"),
by reverting most of it.

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
Tested-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit 2c42257314)
2022-10-14 11:03:31 +02:00
Florian Weimer 908454129d nss: Use shared prefix in IPv4 address in tst-reload1
Otherwise, sorting based on the longest-matching prefix in
getaddrinfo can reorder the addresses in ways the test does not
expect, depending on the IPv4 address of the host.

Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit c02e29a0ba)
2022-10-13 14:28:28 +02:00
Florian Weimer 2681d38caf nss: Fix tst-nss-files-hosts-long on single-stack hosts (bug 24816)
getent implicitly passes AI_ADDRCONFIG to getaddrinfo by default.
Use --no-addrconfig to suppress that, so that both IPv4 and IPv6
lookups succeed even if the address family is not supported by the
host.

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit c75d20b5b2)
2022-10-13 14:28:25 +02:00
Florian Weimer 700d3281f9 nss: Implement --no-addrconfig option for getent
The ahosts, ahostsv4, ahostsv6 commands unconditionally pass
AI_ADDRCONFIG to getaddrinfo, which is not always desired.

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit a623f13adf)
2022-10-13 14:27:02 +02:00
Michael Hudson-Doyle 3e27919274 Ensure calculations happen with desired rounding mode in y1lf128
math/test-float128-y1 fails on x86_64 and ppc64el with gcc 12 and -O3,
because code inside a block guarded by SET_RESTORE_ROUNDL is being moved
after the rounding mode has been restored. Use math_force_eval to
prevent this (and insert some math_opt_barrier calls to prevent code
from being moved before the rounding mode is set).

Fixes #29463

Reviewed-By: Wilco Dijkstra <Wilco.Dijkstra@arm.com>
(cherry picked from commit 2b274fd8c9)
2022-10-09 13:05:19 +02:00
Siddhesh Poyarekar 2bd815d834 nscd: Drop local address tuple variable [BZ #29607]
When a request needs to be resent (e.g. due to insufficient buffer
space), the references to subsequent tuples in the local variable are
stale and should not be used.  This used to work by accident before, but
since 1d495912a it no longer does.  Instead of trying to reset it, just
let gethostbyname4_r write into TUMPBUF6 for us, thus maintaining a
consistent state at all times.  This is now consistent with what is done
in gaih_inet for getaddrinfo.

Resolves: BZ #29607
Reported-by: Holger Hoffstätte <holger@applied-asynchrony.com>
Tested-by: Holger Hoffstätte <holger@applied-asynchrony.com>
Reviewed-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit 6e33e5c4b7)
2022-10-04 18:43:50 -04:00
Aurelien Jarno 2d8ef784bd x86-64: Require BMI1/BMI2 for AVX2 strrchr and wcsrchr implementations
The AVX2 strrchr and wcsrchr implementation uses the 'blsmsk'
instruction which belongs to the BMI1 CPU feature and the 'shrx'
instruction, which belongs to the BMI2 CPU feature.

Fixes: df7e295d18 ("x86: Optimize {str|wcs}rchr-avx2")
Partially resolves: BZ #29611

Reviewed-by: Noah Goldstein  <goldstein.w.n@gmail.com>
(cherry picked from commit 7e8283170c)
2022-10-03 23:47:50 +02:00
Aurelien Jarno 923c3f3c37 x86-64: Require BMI2 and LZCNT for AVX2 memrchr implementation
The AVX2 memrchr implementation uses the 'shlxl' instruction, which
belongs to the BMI2 CPU feature and uses the 'lzcnt' instruction, which
belongs to the LZCNT CPU feature.

Fixes: af5306a735 ("x86: Optimize memrchr-avx2.S")
Partially resolves: BZ #29611

Reviewed-by: Noah Goldstein  <goldstein.w.n@gmail.com>
(cherry picked from commit 3c0c78afab)
2022-10-03 23:47:50 +02:00
Aurelien Jarno d9196d4f3f x86-64: Require BMI2 for AVX2 (raw|w)memchr implementations
The AVX2 memchr, rawmemchr and wmemchr implementations use the 'bzhi'
and 'sarx' instructions, which belongs to the BMI2 CPU feature.

Fixes: acfd088a19 ("x86: Optimize memchr-avx2.S")
Partially resolves: BZ #29611

Reviewed-by: Noah Goldstein  <goldstein.w.n@gmail.com>
(cherry picked from commit e3e7fab7fe)
2022-10-03 23:47:50 +02:00
Aurelien Jarno d8bf4388df x86-64: Require BMI2 for AVX2 wcs(n)cmp implementations
The AVX2 wcs(n)cmp implementations use the 'bzhi' instruction, which
belongs to the BMI2 CPU feature.

NB: It also uses the 'tzcnt' BMI1 instruction, but it is executed as BSF
as BSF if the CPU doesn't support TZCNT, and produces the same result
for non-zero input.

Partially fixes: b77b06e0e2 ("x86: Optimize strcmp-avx2.S")
Partially resolves: BZ #29611

Reviewed-by: Noah Goldstein  <goldstein.w.n@gmail.com>
(cherry picked from commit f31a5a884e)
2022-10-03 23:47:49 +02:00
Aurelien Jarno 29c577e0f5 x86-64: Require BMI2 for AVX2 strncmp implementation
The AVX2 strncmp implementations uses the 'bzhi' instruction, which
belongs to the BMI2 CPU feature.

NB: It also uses the 'tzcnt' BMI1 instruction, but it is executed as BSF
as BSF if the CPU doesn't support TZCNT, and produces the same result
for non-zero input.

Partially fixes: b77b06e0e2 ("x86: Optimize strcmp-avx2.S")
Partially resolves: BZ #29611

Reviewed-by: Noah Goldstein  <goldstein.w.n@gmail.com>
(cherry picked from commit fc7de1d9b9)
2022-10-03 23:47:49 +02:00
Aurelien Jarno 7afbd1e56a x86-64: Require BMI2 for AVX2 strcmp implementation
The AVX2 strcmp implementation uses the 'bzhi' instruction, which
belongs to the BMI2 CPU feature.

NB: It also uses the 'tzcnt' BMI1 instruction, but it is executed as BSF
as BSF if the CPU doesn't support TZCNT, and produces the same result
for non-zero input.

Partially fixes: b77b06e0e2 ("x86: Optimize strcmp-avx2.S")
Partially resolves: BZ #29611

Reviewed-by: Noah Goldstein  <goldstein.w.n@gmail.com>
(cherry picked from commit 4d64c64457)
2022-10-03 23:47:49 +02:00
Aurelien Jarno 46479e5d10 x86-64: Require BMI2 for AVX2 str(n)casecmp implementations
The AVX2 str(n)casecmp implementations use the 'bzhi' instruction, which
belongs to the BMI2 CPU feature.

NB: It also uses the 'tzcnt' BMI1 instruction, but it is executed as BSF
as BSF if the CPU doesn't support TZCNT, and produces the same result
for non-zero input.

Partially fixes: b77b06e0e2 ("x86: Optimize strcmp-avx2.S")
Partially resolves: BZ #29611

Reviewed-by: Noah Goldstein  <goldstein.w.n@gmail.com>
(cherry picked from commit 10f79d3670)
2022-10-03 23:47:49 +02:00
Aurelien Jarno 18bec23cbb x86: include BMI1 and BMI2 in x86-64-v3 level
The "System V Application Binary Interface AMD64 Architecture Processor
Supplement" mandates the BMI1 and BMI2 CPU features for the x86-64-v3
level.

Reviewed-by: Noah Goldstein  <goldstein.w.n@gmail.com>
(cherry picked from commit b80f16adbd)
2022-10-03 23:47:49 +02:00
John David Anglin cdc496eb55 hppa: undef __ASSUME_SET_ROBUST_LIST
QEMU does not support support set_robust_list. Thus, we need
to enable detection of set_robust_list system call.

Signed-off-by: John David Anglin <dave.anglin@bell.net>
2022-10-01 20:09:10 +00:00
John David Anglin d1d8379bff hppa: Fix initialization of dp register [BZ 29635]
After upgrading glibc to Debian 2.35-1, gdb faulted on
startup and dropped core in a function call in the main
application.  This was caused by not initializing the
global dp register for the main application early enough.

Restore the code to initialize dp in _dl_start_user.
It was removed when code was added to initialize dp in
elf_machine_runtime_setup.

Signed-off-by: John David Anglin <dave.anglin@bell.net>
2022-10-01 19:53:30 +00:00
Adhemerval Zanella 76e05613ee stdlib: Fix __getrandom_nocancel type and arc4random usage (BZ #29638)
Using an unsigned type prevents the fallback to be used if kernel
does not support getrandom syscall.

Checked on x86_64-linux-gnu.

Reviewed-by: Wilco Dijkstra  <Wilco.Dijkstra@arm.com>
(cherry picked from commit 13db9ee2cb)
2022-09-30 15:32:51 -03:00
Jörg Sonnenberger 227c903587 get_nscd_addresses: Fix subscript typos [BZ #29605]
Fix the subscript on air->family, which was accidentally set to COUNT
when it should have remained as I.

Resolves: BZ #29605

Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit c9226c03da)
2022-09-28 12:48:47 -04:00
Adhemerval Zanella 2628500f5d m68k: Enforce 4-byte alignment on internal locks (BZ #29537)
A new internal definition, __LIBC_LOCK_ALIGNMENT, is used to force
the 4-byte alignment only for m68k, other architecture keep the
natural alignment of the type used internally (and hppa does not
require 16-byte alignment for kernel-assisted CAS).

Reviewed-by: Florian Weimer <fweimer@redhat.com>
(cherry picked from commit aeb4d2e981)
2022-09-21 12:01:47 -03:00
Florian Weimer 52c037f357 gconv: Use 64-bit interfaces in gconv_parseconfdir (bug 29583)
It's possible that inode numbers are outside the 32-bit range.
The existing code only handles the in-libc case correctly, and
still uses the legacy interfaces when building iconv.

Suggested-by: Helge Deller <deller@gmx.de>
(cherry picked from commit f97905f246)
2022-09-21 12:12:52 +02:00
Florian Weimer da5f134f6d elf: Implement force_first handling in _dl_sort_maps_dfs (bug 28937)
The implementation in _dl_close_worker requires that the first
element of l_initfini is always this very map (“We are always the
zeroth entry, and since we don't include ourselves in the
dependency analysis start at 1.”).  Rather than fixing that
assumption, this commit adds an implementation of the force_first
argument to the new dependency sorting algorithm.  This also means
that the directly dlopen'ed shared object is always initialized last,
which is the least surprising behavior in the presence of cycles.

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit 1df71d32fe)
2022-09-20 11:06:05 +02:00
Florian Weimer d1241cf001 elf: Rename _dl_sort_maps parameter from skip to force_first
The new implementation will not be able to skip an arbitrary number
of objects.

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit dbb75513f5)
2022-09-20 11:04:44 +02:00
Florian Weimer 7a3f8c8a7a scripts/dso-ordering-test.py: Generate program run-time dependencies
The main program needs to depend on all shared objects, even objects
that have link-time dependencies among shared objects.  Filtering
out shared objects that already have an link-time dependencies is not
necessary here; make will do this automatically.

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
(cherry picked from commit 183d997372)
2022-09-20 11:04:44 +02:00
Javier Pello 4b95b6e8bb elf: Fix hwcaps string size overestimation
Commit dad90d5282 added glibc-hwcaps
support for LD_LIBRARY_PATH and, for this, it adjusted the total
string size required in _dl_important_hwcaps. However, in doing so
it inadvertently altered the calculation of the size required for
the power set strings, as the computation of the power set string
size depended on the first value assigned to the total variable,
which is later shifted, resulting in overallocation of string
space. Fix this now by using a different variable to hold the
string size required for glibc-hwcaps.

Signed-off-by: Javier Pello <devel@otheo.eu>
(cherry picked from commit a23820f605)
2022-09-15 14:44:49 +02:00
Florian Weimer df51334828 elf: Run tst-audit-tlsdesc, tst-audit-tlsdesc-dlopen everywhere
The test is valid for all TLS models, but we want to make a reasonable
effort to test the GNU2 model specifically.  For example, aarch64
defaults to GNU2, but does not have -mtls-dialect=gnu2, and the test
was not run there.

Suggested-by: Martin Coufal <mcoufal@redhat.com>
(cherry picked from commit dd2315a866)

Fixes early backport commit 924e4f3eaa
("elf: Call __libc_early_init for reused namespaces (bug 29528)");
it had a wrong conflict resolution.
2022-09-13 19:57:43 +02:00
Florian Weimer 5d885617ce NEWS: Note bug 12154 and bug 29305 as fixed 2022-09-13 13:22:27 +02:00
Florian Weimer a7fa604f30 resolv: Fix building tst-resolv-invalid-cname for earlier C standards
This fixes this compiler error:

tst-resolv-invalid-cname.c: In function ‘test_mode_to_string’:
tst-resolv-invalid-cname.c:164:10: error: label at end of compound statement
     case test_mode_num:
          ^~~~~~~~~~~~~

Fixes commit 9caf782276
("resolv: Add new tst-resolv-invalid-cname").

(cherry picked from commit d09aa4a172)
2022-09-13 12:56:24 +02:00
Florian Weimer c5cdb39c20 nss_dns: Rewrite _nss_dns_gethostbyname4_r using current interfaces
Introduce struct alloc_buffer to this function, and use it and
struct ns_rr_cursor in gaih_getanswer_slice.  Adjust gaih_getanswer
and gaih_getanswer_noaaaa accordingly.

Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit 1d495912a7)
2022-09-13 12:56:24 +02:00
Florian Weimer e2ec6a8db3 resolv: Add new tst-resolv-invalid-cname
This test checks resolution through CNAME chains that do not contain
host names (bug 12154).

Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit 9caf782276)
2022-09-13 12:56:24 +02:00
Florian Weimer 7a236dc44a nss_dns: In gaih_getanswer_slice, skip strange aliases (bug 12154)
If the name is not a host name, skip adding it to the result, instead
of reporting query failure.  This fixes bug 12154 for getaddrinfo.

This commit still keeps the old parsing code, and only adjusts when
a host name is copied.

Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit 32b599ac8c)
2022-09-13 12:56:24 +02:00
Florian Weimer 78c8ef21fa nss_dns: Rewrite getanswer_r to match getanswer_ptr (bug 12154, bug 29305)
Allocate the pointer arrays only at the end, when their sizes
are known.  This addresses bug 29305.

Skip over invalid names instead of failing lookups.  This partially
fixes bug 12154 (for gethostbyname, fixing getaddrinfo requires
different changes).

Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit d101d836e7)
2022-09-13 12:56:24 +02:00
Florian Weimer 5165080fec nss_dns: Remove remnants of IPv6 address mapping
res_use_inet6 always returns false since commit 3f8b44be0a
("resolv: Remove support for RES_USE_INET6 and the inet6 option").

Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit a7fc30b522)
2022-09-13 12:56:24 +02:00
Florian Weimer 77f523c473 nss_dns: Rewrite _nss_dns_gethostbyaddr2_r and getanswer_ptr
The simplification takes advantage of the split from getanswer_r.
It fixes various aliases issues, and optimizes NSS buffer usage.
The new DNS packet parsing helpers are used, too.

Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit e32547d661)
2022-09-13 12:56:24 +02:00
Florian Weimer b714ab7e3c nss_dns: Split getanswer_ptr from getanswer_r
And expand the use of name_ok and qtype in getanswer_ptr (the
former also in getanswer_r).

After further cleanups, not much code will be shared between the
two functions.

Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit 0dcc43e998)
2022-09-13 12:56:24 +02:00
Florian Weimer f0e9657067 resolv: Add DNS packet parsing helpers geared towards wire format
The public parser functions around the ns_rr record type produce
textual domain names, but usually, this is not what we need while
parsing DNS packets within glibc.  This commit adds two new helper
functions, __ns_rr_cursor_init and __ns_rr_cursor_next, for writing
packet parsers, and struct ns_rr_cursor, struct ns_rr_wire as
supporting types.

In theory, it is possible to avoid copying the owner name
into the rname field in __ns_rr_cursor_next, but this would need
more functions that work on compressed names.

Eventually, __res_context_send could be enhanced to preserve the
result of the packet parsing that is necessary for matching the
incoming UDP packets, so that this works does not have to be done
twice.

Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit 857c890d9b)
2022-09-13 12:56:24 +02:00
Florian Weimer adb69f8ffe resolv: Add internal __ns_name_length_uncompressed function
This function is useful for checking that the question name is
uncompressed (as it should be).

Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit 78b1a4f0e4)
2022-09-13 12:56:24 +02:00
Florian Weimer 20ec40a51d resolv: Add the __ns_samebinaryname function
During packet parsing, only the binary name is available.  If the name
equality check is performed before conversion to text, we can sometimes
skip the last step.

Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit 394085a34d)
2022-09-13 12:56:24 +02:00
Florian Weimer 3c9b4004e2 resolv: Add internal __res_binary_hnok function
During package parsing, only the binary representation is available,
and it is convenient to check that directly for conformance with host
name requirements.

Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit c79327bf00)
2022-09-13 12:56:24 +02:00
Florian Weimer bffc33e90e resolv: Add tst-resolv-aliases
Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit 87aa98aa80)
2022-09-13 12:56:24 +02:00
Florian Weimer 9d7eebde8f resolv: Add tst-resolv-byaddr for testing reverse lookup
Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit 0b99828d54)
2022-09-13 12:56:24 +02:00
Fabian Vogt c399271c10 nscd: Fix netlink cache invalidation if epoll is used [BZ #29415]
Processes cache network interface information such as whether IPv4 or IPv6
are enabled. This is only checked again if the "netlink timestamp" provided
by nscd changed, which is triggered by netlink socket activity.

However, in the epoll handler for the netlink socket, it was missed to
assign the new timestamp to the nscd database. The handler for plain poll
did that properly, copy that over.

This bug caused that e.g. processes which started before network
configuration got unusuable addresses from getaddrinfo, like IPv6 only even
though only IPv4 is available:
https://gitlab.freedesktop.org/NetworkManager/NetworkManager/-/issues/1041

It's a bit hard to reproduce, so I verified this by checking the timestamp
on calls to __check_pf manually. Without this patch it's stuck at 1, now
it's increasing on network changes as expected.

Signed-off-by: Fabian Vogt <fvogt@suse.de>
(cherry picked from commit 02ca25fef2)
2022-09-06 18:34:18 +02:00
Siddhesh Poyarekar b46412fb17 Add NEWS entry for CVE-2022-39046
(cherry picked from commit 76fe56020e)
2022-09-06 09:36:54 -04:00
Adhemerval Zanella 645d94808a syslog: Remove extra whitespace between timestamp and message (BZ#29544)
The rfc3164 clear states that a single space character must follow
the timestamp field.

Checked on x86_64-linux-gnu.
2022-09-05 09:50:03 -03:00
Adhemerval Zanella b3736d1a3c elf: Restore how vDSO dependency is printed with LD_TRACE_LOADED_OBJECTS (BZ #29539)
The d7703d3176 changed how vDSO like
dependencies are printed, instead of just the name and address it
follows other libraries mode and prints 'name => path'.

Unfortunately, this broke some ldd consumer that uses the output to
filter out the program's dependencies.  For instance CMake
bundleutilities module [1], where GetPrequirite uses the regex to filter
out 'name => path' [2].

This patch restore the previous way to print just the name and the
mapping address.

Checked on x86_64-linux-gnu.

[1] https://github.com/Kitware/CMake/tree/master/Tests/BundleUtilities
[2] https://github.com/Kitware/CMake/blob/master/Modules/GetPrerequisites.cmake#L733

Reviewed-by: Florian Weimer <fweimer@redhat.com>
(cherry picked from commit 1e903124ce)
2022-08-31 09:10:53 -03:00
Raphael Moreira Zinsly 3c791f2031 Apply asm redirections in wchar.h before first use
Similar to d0fa09a770, but for wchar.h.  Fixes [BZ #27087] by applying
all long double related asm redirections before using functions in
bits/wchar2.h.
Moves the function declarations from wcsmbs/bits/wchar2.h to a new file
wcsmbs/bits/wchar2-decl.h that will be included first in wcsmbs/wchar.h.

Tested with build-many-glibcs.py.
Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>

(cherry picked from commit c7509d49c4)
2022-08-31 09:03:41 +02:00
Florian Weimer 924e4f3eaa elf: Call __libc_early_init for reused namespaces (bug 29528)
libc_map is never reset to NULL, neither during dlclose nor on a
dlopen call which reuses the namespace structure.  As a result, if a
namespace is reused, its libc is not initialized properly.  The most
visible result is a crash in the <ctype.h> functions.

To prevent similar bugs on namespace reuse from surfacing,
unconditionally initialize the chosen namespace to zero using memset.

(cherry picked from commit d0e357ff45)
2022-08-30 16:31:03 +02:00
Adhemerval Zanella b0e7888d1f syslog: Fix large messages (BZ#29536)
The a583b6add4 change did not handle large messages that
would require a heap allocation correctly, where the message itself
is not take in consideration.

This patch fixes it and extend the tst-syslog to check for large
messages as well.

Checked on x86_64-linux-gnu.

Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit 52a5be0df4)
2022-08-30 09:03:14 -03:00
Florian Weimer 3bd3c612e9 Linux: Fix enum fsconfig_command detection in <sys/mount.h>
The #ifdef FSOPEN_CLOEXEC check did not work because the macro
was always defined in this header prior to the check, so that
the <linux/mount.h> contents did not matter.

Fixes commit 774058d729
("linux: Fix sys/mount.h usage with kernel headers").

(cherry picked from commit 2955ef4b7c)
2022-08-24 10:01:29 -03:00
Adhemerval Zanella bb1e8b0ca9 linux: Fix sys/mount.h usage with kernel headers
Now that kernel exports linux/mount.h and includes it on linux/fs.h,
its definitions might clash with glibc exports sys/mount.h.  To avoid
the need to rearrange the Linux header to be always after glibc one,
the glibc sys/mount.h is changed to:

  1. Undefine the macros also used as enum constants.  This covers prior
     inclusion of <linux/mount.h> (for instance MS_RDONLY).

  2. Include <linux/mount.h> based on the usual __has_include check
     (needs to use __has_include ("linux/mount.h") to paper over GCC
     bugs.

  3. Define enum fsconfig_command only if FSOPEN_CLOEXEC is not defined.
     (FSOPEN_CLOEXEC should be a very close proxy.)

  4. Define struct mount_attr if MOUNT_ATTR_SIZE_VER0 is not defined.
     (Added in the same commit on the Linux side.)

This patch also adds some tests to check if including linux/fs.h and
linux/mount.h after and before sys/mount.h does work.

Checked on x86_64-linux-gnu.

Reviewed-by: Florian Weimer <fweimer@redhat.com>
(cherry picked from commit 774058d729)
2022-08-24 10:01:29 -03:00
Adhemerval Zanella d48813227b linux: Use compile_c_snippet to check linux/mount.h availability
Checked on x86_64-linux-gnu.

Reviewed-by: Florian Weimer <fweimer@redhat.com>
(cherry picked from commit e1226cdc6b)
2022-08-24 10:01:29 -03:00
Adhemerval Zanella 4dad97e2a2 linux: Mimic kernel defition for BLOCK_SIZE
To avoid possible warnings if the kernel header is included before
sys/mount.h.

Reviewed-by: Florian Weimer <fweimer@redhat.com>
(cherry picked from commit c68b6044bc)
2022-08-24 10:01:29 -03:00
Adhemerval Zanella 1cc5513114 linux: Use compile_c_snippet to check linux/pidfd.h availability
Instead of tying to a specific kernel version.

Checked on x86_64-linux-gnu.

Reviewed-by: Florian Weimer <fweimer@redhat.com>
(cherry picked from commit 1542019b69)
2022-08-24 10:01:29 -03:00
Adhemerval Zanella 0062e7dd1c glibcextract.py: Add compile_c_snippet
It might be used on tests to check if a snippet build with the provided
compiler and flags.

Reviewed-by: Florian Weimer <fweimer@redhat.com>
(cherry picked from commit 841afa116e)
2022-08-24 10:01:27 -03:00
Arjun Shankar 5c62874f42 NEWS: Add entry for bug 28846 2022-08-22 18:21:49 +02:00
Arjun Shankar d13a7a6f10 socket: Check lengths before advancing pointer in CMSG_NXTHDR
The inline and library functions that the CMSG_NXTHDR macro may expand
to increment the pointer to the header before checking the stride of
the increment against available space.  Since C only allows incrementing
pointers to one past the end of an array, the increment must be done
after a length check.  This commit fixes that and includes a regression
test for CMSG_FIRSTHDR and CMSG_NXTHDR.

The Linux, Hurd, and generic headers are all changed.

Tested on Linux on armv7hl, i686, x86_64, aarch64, ppc64le, and s390x.

[BZ #28846]

Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
(cherry picked from commit 9c443ac455)
2022-08-22 16:32:13 +02:00
Florian Weimer 8b139cd4f1 alpha: Fix generic brk system call emulation in __brk_call (bug 29490)
The kernel special-cases the zero argument for alpha brk, and we can
use that to restore the generic Linux error handling behavior.

Fixes commit b57ab258c1 ("Linux:
Introduce __brk_call for invoking the brk system call").

(cherry picked from commit e7ad26ee3c)
2022-08-22 11:11:02 +02:00
Florian Weimer e982657073 Linux: Terminate subprocess on late failure in tst-pidfd (bug 29485)
Reviewed-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit f82e05ebb2)
2022-08-16 07:30:25 +02:00
Noah Goldstein 302bc33bc5 elf: Replace strcpy call with memcpy [BZ #29454]
GCC normally does this optimization for us in
strlen_pass::handle_builtin_strcpy but only for optimized
build. To avoid needing to include strcpy.S in the rtld build to
support the debug build, just do the optimization by hand.

(cherry picked from commit 483cfe1a6a)
2022-08-11 22:11:14 +08:00
Joseph Myers ac47d8f6cf Update syscall lists for Linux 5.19
Linux 5.19 has no new syscalls, but enables memfd_secret in the uapi
headers for RISC-V.  Update the version number in syscall-names.list
to reflect that it is still current for 5.19 and regenerate the
arch-syscall.h headers with build-many-glibcs.py update-syscalls.

Tested with build-many-glibcs.py.

(cherry picked from commit fccadcdf5b)
2022-08-05 23:46:44 +02:00
Florian Weimer c74bb93cfd dlfcn: Pass caller pointer to static dlopen implementation (bug 29446)
Fixes commit 0c1c3a771e ("dlfcn: Move
dlopen into libc").

(cherry picked from commit ed0185e412)
2022-08-04 17:57:11 +02:00
H.J. Lu 33f1b4c145 wcsmbs: Add missing test-c8rtomb/test-mbrtoc8 dependency
Make test-c8rtomb.out and test-mbrtoc8.out depend on $(gen-locales) for

  xsetlocale (LC_ALL, "de_DE.UTF-8");
  xsetlocale (LC_ALL, "zh_HK.BIG5-HKSCS");

Reviewed-by: Sunil K Pandey <skpgkp2@gmail.com>
Reviewed-by: Carlos O'Donell <carlos@redhat.com>
(cherry picked from commit e03f5ccd6c)
2022-08-01 10:02:06 -03:00
Tom Honermann c3fda489cf stdlib: Suppress gcc diagnostic that char8_t is a keyword in C++20 in uchar.h.
gcc 13 issues the following diagnostic for the uchar.h header when the
-Wc++20-compat option is enabled in C++ modes that do not enable char8_t
as a builtin type (C++17 and earlier by default; subject to _GNU_SOURCE
and the gcc -f[no-]char8_t option).
  warning: identifier ‘char8_t’ is a keyword in C++20 [-Wc++20-compat]
This change modifies the uchar.h header to suppress the diagnostic through
the use of '#pragma GCC diagnostic' directives for gcc 10 and later (the
-Wc++20-compat option was added in gcc version 10).  Unfortunately, a bug
in gcc currently prevents those directives from having the intended effect
as reported at https://gcc.gnu.org/PR106423.  A patch for that issue has
been submitted and is available in the email thread archive linked below.
  https://gcc.gnu.org/pipermail/gcc-patches/2022-July/598736.html

(cherry picked from commit 825f84f133)
2022-08-01 10:02:00 -03:00
390 changed files with 11216 additions and 3945 deletions
+24 -5
View File
@@ -43,6 +43,22 @@ else
$(error objdir must be defined by the build-directory Makefile)
endif
# Did we request 'make -s' run? "yes" or "no".
# Starting from make-4.4 MAKEFLAGS now contains long
# options like '--shuffle'. To detect presence of 's'
# we pick first word with short options. Long options
# are guaranteed to come after whitespace. We use '-'
# prefix to always have a word before long options
# even if no short options were passed.
# Typical MAKEFLAGS values to watch for:
# "rs --shuffle=42" (silent)
# " --shuffle" (not silent)
ifeq ($(findstring s, $(firstword -$(MAKEFLAGS))),)
silent-make := no
else
silent-make := yes
endif
# Root of the sysdeps tree.
sysdep_dir := $(..)sysdeps
export sysdep_dir := $(sysdep_dir)
@@ -569,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 =
@@ -868,7 +887,7 @@ endif
# Use 64 bit time_t support for installed programs
installed-modules = nonlib nscd lddlibc4 ldconfig locale_programs \
iconvprogs libnss_files libnss_compat libnss_db libnss_hesiod \
libutil libpcprofile libSegFault
libutil libpcprofile libSegFault libnsl
+extra-time-flags = $(if $(filter $(installed-modules),\
$(in-module)),-D_TIME_BITS=64 -D_FILE_OFFSET_BITS=64)
@@ -917,7 +936,7 @@ endif
# umpteen zillion filenames along with it (we use `...' instead)
# but we don't want this echoing done when the user has said
# he doesn't want to see commands echoed by using -s.
ifneq "$(findstring s,$(MAKEFLAGS))" "" # if -s
ifeq ($(silent-make),yes) # if -s
+cmdecho := echo >/dev/null
else # not -s
+cmdecho := echo
+2 -2
View File
@@ -794,7 +794,7 @@ endif
# Maximize efficiency by minimizing the number of rules.
.SUFFIXES: # Clear the suffix list. We don't use suffix rules.
# Don't define any builtin rules.
MAKEFLAGS := $(MAKEFLAGS)r
MAKEFLAGS := $(MAKEFLAGS) -r
# Generic rule for making directories.
%/:
@@ -811,7 +811,7 @@ MAKEFLAGS := $(MAKEFLAGS)r
.PRECIOUS: $(foreach l,$(libtypes),$(patsubst %,$(common-objpfx)$l,c))
# Use the verbose option of ar and tar when not running silently.
ifeq "$(findstring s,$(MAKEFLAGS))" "" # if not -s
ifeq ($(silent-make),no) # if not -s
verbose := v
else # -s
verbose :=
+117
View File
@@ -5,6 +5,123 @@ 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.36.1
Major new features:
* The getent tool now supports the --no-addrconfig option. The output of
getent with --no-addrconfig may contain addresses of families not
configured on the current host i.e. as-if you had not passed
AI_ADDRCONFIG to getaddrinfo calls.
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-2022-39046: When the syslog function is passed a crafted input
string larger than 1024 bytes, it reads uninitialized memory from the
heap and prints it to the target log file, potentially revealing a
portion of the contents of the heap.
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:
[12154] Do not fail DNS resolution for CNAMEs which are not host names
[20975] Deferred cancellation triggers in __check_pf and looses lock leading to deadlock
[24816] Fix tst-nss-files-hosts-long on single-stack hosts
[27576] gmon: improve mcount overflow handling
[27821] ungetc: Fix backup buffer leak on program exit
[28846] CMSG_NXTHDR may trigger -Wstrict-overflow warning
[29039] Corrupt DTV after reuse of a TLS module ID following dlclose with unused TLS
[29444] gmon: Fix allocated buffer overflow (bug 29444)
[29864] libc: __libc_start_main() should obtain program headers
address (_dl_phdr) from the auxv, not the ELF header.
[29305] Conserve NSS buffer space during DNS packet parsing
[29402] nscd: nscd: No such file or directory
[29415] nscd: Fix netlink cache invalidation if epoll is used
[28937] New DSO dependency sorter does not put new map first if in a cycle
[29446] _dlopen now ignores dl_caller argument in static mode
[29485] Linux: Terminate subprocess on late failure in tst-pidfd
[29490] alpha: New __brk_call implementation is broken
[29463] math/test-float128-y1 fails on x86_64
[29488] test-ibm128-llround fails on ppc64el when built with gcc-12 and -O2
or higher
[29528] elf: Call __libc_early_init for reused namespaces
[29537] libc: [2.34 regression]: Alignment issue on m68k when using
[29539] libc: LD_TRACE_LOADED_OBJECTS changed how vDSO library are
[29576] build: librtld.os: in function `_dl_start_profile':
(.text+0x9444): undefined reference to `strcpy'
[29583] Use 64-bit interfaces in gconv_parseconfdir
[29600] Do not completely clear reused namespace in dlmopen
[29607] nscd repeatably crashes calling __strlen_avx2 when hosts cache is
enabled
[29638] libc: stdlib: arc4random fallback is never used
[29657] libc: Incorrect struct stat for 64-bit time on linux/generic
platforms
[29730] broken y2038 support in fstatat on MIPS N64
[29771] Restore IPC_64 support in sysvipc *ctl functions
[29776] elf/tst-tlsopt-powerpc fails when compiled with -mcpu=power10
[29951] time: Set daylight to 1 for matching DST/offset change
[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
[30151] gshadow: Matching sgetsgent, sgetsgent_r ERANGE handling
[30163] posix: Fix system blocks SIGCHLD erroneously
[30305] x86_64: Fix asm constraints in feraiseexcept
[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
[30804] F_GETLK, F_SETLK, and F_SETLKW value change for powerpc64 with
-D_FILE_OFFSET_BITS=64
[30842] Stack read overflow in getaddrinfo in no-aaaa mode (CVE-2023-4527)
[30843] potential use-after-free in getcanonname (CVE-2023-4806)
[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.36
Major new features:
+20 -4
View File
@@ -22,10 +22,23 @@ subdir := assert
include ../Makeconfig
headers := assert.h
headers := \
assert.h
# headers
routines := assert assert-perr __assert
tests := test-assert test-assert-perr tst-assert-c++ tst-assert-g++
routines := \
__assert \
assert \
assert-perr \
# routines
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
@@ -33,7 +46,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>
+33 -7
View File
@@ -245,6 +245,12 @@ struct cmsghdr
+ CMSG_ALIGN (sizeof (struct cmsghdr)))
#define CMSG_LEN(len) (CMSG_ALIGN (sizeof (struct cmsghdr)) + (len))
/* Given a length, return the additional padding necessary such that
len + __CMSG_PADDING(len) == CMSG_ALIGN (len). */
#define __CMSG_PADDING(len) ((sizeof (size_t) \
- ((len) & (sizeof (size_t) - 1))) \
& (sizeof (size_t) - 1))
extern struct cmsghdr *__cmsg_nxthdr (struct msghdr *__mhdr,
struct cmsghdr *__cmsg) __THROW;
#ifdef __USE_EXTERN_INLINES
@@ -254,18 +260,38 @@ extern struct cmsghdr *__cmsg_nxthdr (struct msghdr *__mhdr,
_EXTERN_INLINE struct cmsghdr *
__NTH (__cmsg_nxthdr (struct msghdr *__mhdr, struct cmsghdr *__cmsg))
{
/* We may safely assume that __cmsg lies between __mhdr->msg_control and
__mhdr->msg_controllen because the user is required to obtain the first
cmsg via CMSG_FIRSTHDR, set its length, then obtain subsequent cmsgs
via CMSG_NXTHDR, setting lengths along the way. However, we don't yet
trust the value of __cmsg->cmsg_len and therefore do not use it in any
pointer arithmetic until we check its value. */
unsigned char * __msg_control_ptr = (unsigned char *) __mhdr->msg_control;
unsigned char * __cmsg_ptr = (unsigned char *) __cmsg;
size_t __size_needed = sizeof (struct cmsghdr)
+ __CMSG_PADDING (__cmsg->cmsg_len);
/* The current header is malformed, too small to be a full header. */
if ((size_t) __cmsg->cmsg_len < sizeof (struct cmsghdr))
/* The kernel header does this so there may be a reason. */
return (struct cmsghdr *) 0;
/* There isn't enough space between __cmsg and the end of the buffer to
hold the current cmsg *and* the next one. */
if (((size_t)
(__msg_control_ptr + __mhdr->msg_controllen - __cmsg_ptr)
< __size_needed)
|| ((size_t)
(__msg_control_ptr + __mhdr->msg_controllen - __cmsg_ptr
- __size_needed)
< __cmsg->cmsg_len))
return (struct cmsghdr *) 0;
/* Now, we trust cmsg_len and can use it to find the next header. */
__cmsg = (struct cmsghdr *) ((unsigned char *) __cmsg
+ CMSG_ALIGN (__cmsg->cmsg_len));
if ((unsigned char *) (__cmsg + 1) > ((unsigned char *) __mhdr->msg_control
+ __mhdr->msg_controllen)
|| ((unsigned char *) __cmsg + CMSG_ALIGN (__cmsg->cmsg_len)
> ((unsigned char *) __mhdr->msg_control + __mhdr->msg_controllen)))
/* No more entries. */
return (struct cmsghdr *) 0;
return __cmsg;
}
#endif /* Use `extern inline'. */
+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
-21
View File
@@ -262,28 +262,7 @@ LIBC_START_MAIN (int (*main) (int, char **, char ** MAIN_AUXVEC_DECL),
}
# endif
_dl_aux_init (auxvec);
if (GL(dl_phdr) == NULL)
# endif
{
/* 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.
So we can set up _dl_phdr and _dl_phnum even without any
information from auxv. */
extern const ElfW(Ehdr) __ehdr_start
# if BUILD_PIE_DEFAULT
__attribute__ ((visibility ("hidden")));
# else
__attribute__ ((weak, visibility ("hidden")));
if (&__ehdr_start != NULL)
# endif
{
assert (__ehdr_start.e_phentsize == sizeof *GL(dl_phdr));
GL(dl_phdr) = (const void *) &__ehdr_start + __ehdr_start.e_phoff;
GL(dl_phnum) = __ehdr_start.e_phnum;
}
}
__tunables_init (__environ);
+12 -13
View File
@@ -118,19 +118,18 @@ __libc_setup_tls (void)
__tls_pre_init_tp ();
/* Look through the TLS segment if there is any. */
if (_dl_phdr != NULL)
for (phdr = _dl_phdr; phdr < &_dl_phdr[_dl_phnum]; ++phdr)
if (phdr->p_type == PT_TLS)
{
/* Remember the values we need. */
memsz = phdr->p_memsz;
filesz = phdr->p_filesz;
initimage = (void *) phdr->p_vaddr + main_map->l_addr;
align = phdr->p_align;
if (phdr->p_align > max_align)
max_align = phdr->p_align;
break;
}
for (phdr = _dl_phdr; phdr < &_dl_phdr[_dl_phnum]; ++phdr)
if (phdr->p_type == PT_TLS)
{
/* Remember the values we need. */
memsz = phdr->p_memsz;
filesz = phdr->p_filesz;
initimage = (void *) phdr->p_vaddr + main_map->l_addr;
align = phdr->p_align;
if (phdr->p_align > max_align)
max_align = phdr->p_align;
break;
}
/* Calculate the size of the static TLS surplus, with 0 auditors. */
_dl_tls_static_surplus_init (0);
+1 -1
View File
@@ -90,7 +90,7 @@ compat_symbol (libdl, ___dlopen, dlopen, GLIBC_2_1);
void *
__dlopen (const char *file, int mode, void *dl_caller)
{
return dlopen_implementation (file, mode, RETURN_ADDRESS (0));
return dlopen_implementation (file, mode, dl_caller);
}
void *
+75 -16
View File
@@ -53,6 +53,7 @@ routines = \
# profiled libraries.
dl-routines = \
dl-call-libc-early-init \
dl-call_fini \
dl-close \
dl-debug \
dl-debug-symbols \
@@ -176,6 +177,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)
@@ -271,6 +273,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 \
@@ -374,6 +377,8 @@ tests += \
tst-align \
tst-align2 \
tst-align3 \
tst-audit-tlsdesc \
tst-audit-tlsdesc-dlopen \
tst-audit1 \
tst-audit2 \
tst-audit8 \
@@ -408,6 +413,7 @@ tests += \
tst-dlmopen4 \
tst-dlmopen-dlerror \
tst-dlmopen-gethostbyname \
tst-dlmopen-twice \
tst-dlopenfail \
tst-dlopenfail-2 \
tst-dlopenrpath \
@@ -435,6 +441,7 @@ tests += \
tst-p_align1 \
tst-p_align2 \
tst-p_align3 \
tst-recursive-tls \
tst-relsort1 \
tst-ro-dynamic \
tst-rtld-run-static \
@@ -497,6 +504,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 \
@@ -508,6 +517,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 \
@@ -631,6 +644,7 @@ ifeq ($(run-built-tests),yes)
tests-special += \
$(objpfx)noload-mem.out \
$(objpfx)tst-ldconfig-X.out \
$(objpfx)tst-ldconfig-p.out \
$(objpfx)tst-leaks1-mem.out \
$(objpfx)tst-rtld-help.out \
# tests-special
@@ -765,6 +779,8 @@ modules-names += \
tst-alignmod3 \
tst-array2dep \
tst-array5dep \
tst-audit-tlsdesc-mod1 \
tst-audit-tlsdesc-mod2 \
tst-audit11mod1 \
tst-audit11mod2 \
tst-audit12mod1 \
@@ -798,6 +814,7 @@ modules-names += \
tst-auditmanymod7 \
tst-auditmanymod8 \
tst-auditmanymod9 \
tst-auditmod-tlsdesc \
tst-auditmod1 \
tst-auditmod9a \
tst-auditmod9b \
@@ -834,6 +851,9 @@ modules-names += \
tst-dlmopen1mod \
tst-dlmopen-dlerror-mod \
tst-dlmopen-gethostbyname-mod \
tst-dlmopen-twice-mod1 \
tst-dlmopen-twice-mod2 \
tst-dlopen-sgid-mod \
tst-dlopenfaillinkmod \
tst-dlopenfailmod1 \
tst-dlopenfailmod2 \
@@ -866,6 +886,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 \
@@ -990,23 +1027,8 @@ modules-names += tst-gnu2-tls1mod
$(objpfx)tst-gnu2-tls1: $(objpfx)tst-gnu2-tls1mod.so
tst-gnu2-tls1mod.so-no-z-defs = yes
CFLAGS-tst-gnu2-tls1mod.c += -mtls-dialect=gnu2
endif # $(have-mtls-dialect-gnu2)
tests += tst-audit-tlsdesc tst-audit-tlsdesc-dlopen
modules-names += tst-audit-tlsdesc-mod1 tst-audit-tlsdesc-mod2 tst-auditmod-tlsdesc
$(objpfx)tst-audit-tlsdesc: $(objpfx)tst-audit-tlsdesc-mod1.so \
$(objpfx)tst-audit-tlsdesc-mod2.so \
$(shared-thread-library)
CFLAGS-tst-audit-tlsdesc-mod1.c += -mtls-dialect=gnu2
CFLAGS-tst-audit-tlsdesc-mod2.c += -mtls-dialect=gnu2
$(objpfx)tst-audit-tlsdesc-dlopen: $(shared-thread-library)
$(objpfx)tst-audit-tlsdesc-dlopen.out: $(objpfx)tst-audit-tlsdesc-mod1.so \
$(objpfx)tst-audit-tlsdesc-mod2.so
$(objpfx)tst-audit-tlsdesc-mod1.so: $(objpfx)tst-audit-tlsdesc-mod2.so
$(objpfx)tst-audit-tlsdesc.out: $(objpfx)tst-auditmod-tlsdesc.so
tst-audit-tlsdesc-ENV = LD_AUDIT=$(objpfx)tst-auditmod-tlsdesc.so
$(objpfx)tst-audit-tlsdesc-dlopen.out: $(objpfx)tst-auditmod-tlsdesc.so
tst-audit-tlsdesc-dlopen-ENV = LD_AUDIT=$(objpfx)tst-auditmod-tlsdesc.so
endif
ifeq (yes,$(have-protected-data))
modules-names += tst-protected1moda tst-protected1modb
tests += tst-protected1a tst-protected1b
@@ -2410,6 +2432,11 @@ $(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)
# 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.
@@ -2967,3 +2994,35 @@ $(objpfx)tst-tls-allocation-failure-static-patched.out: \
grep -q '^Fatal glibc error: Cannot allocate TLS block$$' $@ \
&& grep -q '^status: 127$$' $@; \
$(evaluate-test)
$(objpfx)tst-audit-tlsdesc: $(objpfx)tst-audit-tlsdesc-mod1.so \
$(objpfx)tst-audit-tlsdesc-mod2.so \
$(shared-thread-library)
ifeq (yes,$(have-mtls-dialect-gnu2))
# The test is valid for all TLS types, but we want to exercise GNU2
# TLS if possible.
CFLAGS-tst-audit-tlsdesc-mod1.c += -mtls-dialect=gnu2
CFLAGS-tst-audit-tlsdesc-mod2.c += -mtls-dialect=gnu2
endif
$(objpfx)tst-audit-tlsdesc-dlopen: $(shared-thread-library)
$(objpfx)tst-audit-tlsdesc-dlopen.out: $(objpfx)tst-audit-tlsdesc-mod1.so \
$(objpfx)tst-audit-tlsdesc-mod2.so
$(objpfx)tst-audit-tlsdesc-mod1.so: $(objpfx)tst-audit-tlsdesc-mod2.so
$(objpfx)tst-audit-tlsdesc.out: $(objpfx)tst-auditmod-tlsdesc.so
tst-audit-tlsdesc-ENV = LD_AUDIT=$(objpfx)tst-auditmod-tlsdesc.so
$(objpfx)tst-audit-tlsdesc-dlopen.out: $(objpfx)tst-auditmod-tlsdesc.so
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
@@ -845,7 +845,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 -2
View File
@@ -509,8 +509,9 @@ _dl_load_cache_lookup (const char *name)
we are accessing. Therefore we must make the copy of the
mapping data without using malloc. */
char *temp;
temp = alloca (strlen (best) + 1);
strcpy (temp, best);
size_t best_len = strlen (best) + 1;
temp = alloca (best_len);
memcpy (temp, best, best_len);
return __strdup (temp);
}
+50
View File
@@ -0,0 +1,50 @@
/* Invoke DT_FINI and DT_FINI_ARRAY callbacks.
Copyright (C) 1996-2022 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 <ldsodefs.h>
#include <sysdep.h>
void
_dl_call_fini (void *closure_map)
{
struct link_map *map = closure_map;
/* When debugging print a message first. */
if (__glibc_unlikely (GLRO(dl_debug_mask) & DL_DEBUG_IMPCALLS))
_dl_debug_printf ("\ncalling fini: %s [%lu]\n\n", map->l_name, map->l_ns);
/* Make sure nothing happens if we are called twice. */
map->l_init_called = 0;
ElfW(Dyn) *fini_array = map->l_info[DT_FINI_ARRAY];
if (fini_array != NULL)
{
ElfW(Addr) *array = (ElfW(Addr) *) (map->l_addr
+ fini_array->d_un.d_ptr);
size_t sz = (map->l_info[DT_FINI_ARRAYSZ]->d_un.d_val
/ sizeof (ElfW(Addr)));
while (sz-- > 0)
((fini_t) array[sz]) ();
}
/* Next try the old-style destructor. */
ElfW(Dyn) *fini = map->l_info[DT_FINI];
if (fini != NULL)
DL_CALL_DT_FINI (map, ((void *) map->l_addr + fini->d_un.d_ptr));
}
+2 -42
View File
@@ -36,11 +36,6 @@
#include <dl-unmap-segments.h>
/* Type of the constructor functions. */
typedef void (*fini_t) (void);
/* Special l_idx value used to indicate which objects remain loaded. */
#define IDX_STILL_USED -1
@@ -110,31 +105,6 @@ remove_slotinfo (size_t idx, struct dtv_slotinfo_list *listp, size_t disp,
return false;
}
/* Invoke dstructors for CLOSURE (a struct link_map *). Called with
exception handling temporarily disabled, to make errors fatal. */
static void
call_destructors (void *closure)
{
struct link_map *map = closure;
if (map->l_info[DT_FINI_ARRAY] != NULL)
{
ElfW(Addr) *array =
(ElfW(Addr) *) (map->l_addr
+ map->l_info[DT_FINI_ARRAY]->d_un.d_ptr);
unsigned int sz = (map->l_info[DT_FINI_ARRAYSZ]->d_un.d_val
/ sizeof (ElfW(Addr)));
while (sz-- > 0)
((fini_t) array[sz]) ();
}
/* Next try the old-style destructor. */
if (map->l_info[DT_FINI] != NULL)
DL_CALL_DT_FINI (map, ((void *) map->l_addr
+ map->l_info[DT_FINI]->d_un.d_ptr));
}
void
_dl_close_worker (struct link_map *map, bool force)
{
@@ -280,17 +250,7 @@ _dl_close_worker (struct link_map *map, bool force)
half-cooked objects. Temporarily disable exception
handling, so that errors are fatal. */
if (imap->l_init_called)
{
/* When debugging print a message first. */
if (__builtin_expect (GLRO(dl_debug_mask) & DL_DEBUG_IMPCALLS,
0))
_dl_debug_printf ("\ncalling fini: %s [%lu]\n\n",
imap->l_name, nsid);
if (imap->l_info[DT_FINI_ARRAY] != NULL
|| imap->l_info[DT_FINI] != NULL)
_dl_catch_exception (NULL, call_destructors, imap);
}
_dl_catch_exception (NULL, _dl_call_fini, imap);
#ifdef SHARED
/* Auditing checkpoint: we remove an object. */
@@ -743,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)
+1 -37
View File
@@ -21,11 +21,6 @@
#include <ldsodefs.h>
#include <elf-initfini.h>
/* Type of the constructor functions. */
typedef void (*fini_t) (void);
void
_dl_fini (void)
{
@@ -116,38 +111,7 @@ _dl_fini (void)
if (l->l_init_called)
{
/* Make sure nothing happens if we are called twice. */
l->l_init_called = 0;
/* Is there a destructor function? */
if (l->l_info[DT_FINI_ARRAY] != NULL
|| (ELF_INITFINI && l->l_info[DT_FINI] != NULL))
{
/* When debugging print a message first. */
if (__builtin_expect (GLRO(dl_debug_mask)
& DL_DEBUG_IMPCALLS, 0))
_dl_debug_printf ("\ncalling fini: %s [%lu]\n\n",
DSO_FILENAME (l->l_name),
ns);
/* First see whether an array is given. */
if (l->l_info[DT_FINI_ARRAY] != NULL)
{
ElfW(Addr) *array =
(ElfW(Addr) *) (l->l_addr
+ l->l_info[DT_FINI_ARRAY]->d_un.d_ptr);
unsigned int i = (l->l_info[DT_FINI_ARRAYSZ]->d_un.d_val
/ sizeof (ElfW(Addr)));
while (i-- > 0)
((fini_t) array[i]) ();
}
/* Next try the old-style destructor. */
if (ELF_INITFINI && l->l_info[DT_FINI] != NULL)
DL_CALL_DT_FINI
(l, l->l_addr + l->l_info[DT_FINI]->d_un.d_ptr);
}
_dl_call_fini (l);
#ifdef SHARED
/* Auditing checkpoint: another object closed. */
_dl_audit_objclose (l);
+5 -3
View File
@@ -193,7 +193,7 @@ _dl_important_hwcaps (const char *glibc_hwcaps_prepend,
/* Each hwcaps subdirectory has a GLIBC_HWCAPS_PREFIX string prefix
and a "/" suffix once stored in the result. */
hwcaps_counts.maximum_length += strlen (GLIBC_HWCAPS_PREFIX) + 1;
size_t total = (hwcaps_counts.count * (strlen (GLIBC_HWCAPS_PREFIX) + 1)
size_t hwcaps_sz = (hwcaps_counts.count * (strlen (GLIBC_HWCAPS_PREFIX) + 1)
+ hwcaps_counts.total_length);
/* Count the number of bits set in the masked value. */
@@ -229,11 +229,12 @@ _dl_important_hwcaps (const char *glibc_hwcaps_prepend,
assert (m == cnt);
/* Determine the total size of all strings together. */
size_t total;
if (cnt == 1)
total += temp[0].len + 1;
total = temp[0].len + 1;
else
{
total += temp[0].len + temp[cnt - 1].len + 2;
total = temp[0].len + temp[cnt - 1].len + 2;
if (cnt > 2)
{
total <<= 1;
@@ -255,6 +256,7 @@ _dl_important_hwcaps (const char *glibc_hwcaps_prepend,
/* This is the overall result, including both glibc-hwcaps
subdirectories and the legacy hwcaps subdirectories using the
power set construction. */
total += hwcaps_sz;
struct r_strlenpair *overall_result
= malloc (*sz * sizeof (*result) + total);
if (overall_result == NULL)
+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. */
+17
View File
@@ -854,6 +854,23 @@ _dl_lookup_symbol_x (const char *undef_name, struct link_map *undef_map,
if (__glibc_unlikely (current_value.m->l_used == 0))
current_value.m->l_used = 1;
if (__glibc_unlikely (GLRO(dl_debug_mask) & DL_DEBUG_BINDINGS))
{
const char *reference_name = undef_map->l_name;
_dl_debug_printf ("binding file %s [%lu] to %s [%lu]: %s symbol `%s'",
DSO_FILENAME (reference_name),
undef_map->l_ns,
DSO_FILENAME (current_value.m->l_name),
current_value.m->l_ns,
protected ? "protected" : "normal", undef_name);
if (version)
_dl_debug_printf_c (" [%s]\n", version->name);
else
_dl_debug_printf_c ("\n");
}
*ref = current_value.s;
return LOOKUP_VALUE (current_value.m);
}
+5 -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);
@@ -850,6 +850,7 @@ no more namespaces available for dlmopen()"));
++GL(dl_nns);
}
GL(dl_ns)[nsid].libc_map = NULL;
_dl_debug_update (nsid)->r_state = RT_CONSISTENT;
}
/* Never allow loading a DSO in a namespace which is empty. Such
+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);
+29 -15
View File
@@ -27,12 +27,12 @@
If FOR_FINI is true, this is called for finishing an object. */
static void
_dl_sort_maps_original (struct link_map **maps, unsigned int nmaps,
unsigned int skip, bool for_fini)
bool force_first, bool for_fini)
{
/* Allows caller to do the common optimization of skipping the first map,
usually the main binary. */
maps += skip;
nmaps -= skip;
maps += force_first;
nmaps -= force_first;
/* A list of one element need not be sorted. */
if (nmaps <= 1)
@@ -182,8 +182,9 @@ dfs_traversal (struct link_map ***rpo, struct link_map *map,
static void
_dl_sort_maps_dfs (struct link_map **maps, unsigned int nmaps,
unsigned int skip __attribute__ ((unused)), bool for_fini)
bool force_first, bool for_fini)
{
struct link_map *first_map = maps[0];
for (int i = nmaps - 1; i >= 0; i--)
maps[i]->l_visited = 0;
@@ -208,14 +209,6 @@ _dl_sort_maps_dfs (struct link_map **maps, unsigned int nmaps,
Adjusting the order so that maps[0] is last traversed naturally avoids
this problem.
Further, the old "optimization" of skipping the main object at maps[0]
from the call-site (i.e. _dl_sort_maps(maps+1,nmaps-1)) is in general
no longer valid, since traversing along object dependency-links
may "find" the main object even when it is not included in the initial
order (e.g. a dlopen()'ed shared object can have circular dependencies
linked back to itself). In such a case, traversing N-1 objects will
create a N-object result, and raise problems.
To summarize, just passing in the full list, and iterating from back
to front makes things much more straightforward. */
@@ -274,6 +267,27 @@ _dl_sort_maps_dfs (struct link_map **maps, unsigned int nmaps,
}
memcpy (maps, rpo, sizeof (struct link_map *) * nmaps);
/* Skipping the first object at maps[0] is not valid in general,
since traversing along object dependency-links may "find" that
first object even when it is not included in the initial order
(e.g., a dlopen'ed shared object can have circular dependencies
linked back to itself). In such a case, traversing N-1 objects
will create a N-object result, and raise problems. Instead,
force the object back into first place after sorting. This naive
approach may introduce further dependency ordering violations
compared to rotating the cycle until the first map is again in
the first position, but as there is a cycle, at least one
violation is already present. */
if (force_first && maps[0] != first_map)
{
int i;
for (i = 0; maps[i] != first_map; ++i)
;
assert (i < nmaps);
memmove (&maps[1], maps, i * sizeof (maps[0]));
maps[0] = first_map;
}
}
void
@@ -286,7 +300,7 @@ _dl_sort_maps_init (void)
void
_dl_sort_maps (struct link_map **maps, unsigned int nmaps,
unsigned int skip, bool for_fini)
bool force_first, bool for_fini)
{
/* It can be tempting to use a static function pointer to store and call
the current selected sorting algorithm routine, but experimentation
@@ -296,9 +310,9 @@ _dl_sort_maps (struct link_map **maps, unsigned int nmaps,
input cases. A simple if-case with direct function calls appears to
be the fastest. */
if (__glibc_likely (GLRO(dl_dso_sort_algo) == dso_sort_algorithm_original))
_dl_sort_maps_original (maps, nmaps, skip, for_fini);
_dl_sort_maps_original (maps, nmaps, force_first, for_fini);
else
_dl_sort_maps_dfs (maps, nmaps, skip, for_fini);
_dl_sort_maps_dfs (maps, nmaps, force_first, for_fini);
}
#endif /* HAVE_TUNABLES. */
+47 -34
View File
@@ -255,6 +255,25 @@ _dl_aux_init (ElfW(auxv_t) *av)
for (int i = 0; i < array_length (auxv_values); ++i)
auxv_values[i] = 0;
_dl_parse_auxv (av, auxv_values);
_dl_phdr = (void*) auxv_values[AT_PHDR];
_dl_phnum = auxv_values[AT_PHNUM];
if (_dl_phdr == NULL)
{
/* 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.
So we can set up _dl_phdr and _dl_phnum even without any
information from auxv. */
extern const ElfW(Ehdr) __ehdr_start attribute_hidden;
assert (__ehdr_start.e_phentsize == sizeof *GL(dl_phdr));
_dl_phdr = (const void *) &__ehdr_start + __ehdr_start.e_phoff;
_dl_phnum = __ehdr_start.e_phnum;
}
assert (_dl_phdr != NULL);
}
#endif
@@ -266,8 +285,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);
@@ -275,6 +292,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",
@@ -296,25 +329,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
@@ -323,20 +337,19 @@ _dl_non_dynamic_init (void)
if (_dl_platform != NULL)
_dl_platformlen = strlen (_dl_platform);
if (_dl_phdr != NULL)
for (const ElfW(Phdr) *ph = _dl_phdr; ph < &_dl_phdr[_dl_phnum]; ++ph)
switch (ph->p_type)
{
/* Check if the stack is nonexecutable. */
case PT_GNU_STACK:
_dl_stack_flags = ph->p_flags;
break;
for (const ElfW(Phdr) *ph = _dl_phdr; ph < &_dl_phdr[_dl_phnum]; ++ph)
switch (ph->p_type)
{
/* Check if the stack is nonexecutable. */
case PT_GNU_STACK:
_dl_stack_flags = ph->p_flags;
break;
case PT_GNU_RELRO:
_dl_main_map.l_relro_addr = ph->p_vaddr;
_dl_main_map.l_relro_size = ph->p_memsz;
break;
}
case PT_GNU_RELRO:
_dl_main_map.l_relro_addr = ph->p_vaddr;
_dl_main_map.l_relro_size = ph->p_memsz;
break;
}
call_function_static_weak (_dl_find_object_init);
+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
@@ -169,4 +169,17 @@ glibc {
default: 2
}
}
gmon {
minarcs {
type: INT_32
minval: 50
default: 50
}
maxarcs {
type: INT_32
minval: 50
default: 1048576
}
}
}
+7
View File
@@ -64,3 +64,10 @@ output: b>a>{}<a<b
tst-bz15311: {+a;+e;+f;+g;+d;%d;-d;-g;-f;-e;-a};a->b->c->d;d=>[ba];c=>a;b=>e=>a;c=>f=>b;d=>g=>c
output(glibc.rtld.dynamic_sort=1): {+a[d>c>b>a>];+e[e>];+f[f>];+g[g>];+d[];%d(b(e(a()))a()g(c(a()f(b(e(a()))))));-d[];-g[];-f[];-e[];-a[<a<c<d<g<f<b<e];}
output(glibc.rtld.dynamic_sort=2): {+a[d>c>b>a>];+e[e>];+f[f>];+g[g>];+d[];%d(b(e(a()))a()g(c(a()f(b(e(a()))))));-d[];-g[];-f[];-e[];-a[<g<f<a<b<c<d<e];}
# Test that even in the presence of dependency loops involving dlopen'ed
# object, that object is initialized last (and not unloaded prematurely).
# Final destructor order is indeterminate due to the cycle.
tst-bz28937: {+a;+b;-b;+c;%c};a->a1;a->a2;a2->a;b->b1;c->a1;c=>a1
output(glibc.rtld.dynamic_sort=1): {+a[a2>a1>a>];+b[b1>b>];-b[<b<b1];+c[c>];%c(a1());}<a<a2<c<a1
output(glibc.rtld.dynamic_sort=2): {+a[a2>a1>a>];+b[b1>b>];-b[<b<b1];+c[c>];%c(a1());}<a2<a<c<a1
+8 -2
View File
@@ -1215,6 +1215,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
@@ -4085,8 +4088,11 @@ enum
#define R_NDS32_TLS_DESC 119
/* LoongArch ELF Flags */
#define EF_LARCH_ABI 0x07
#define EF_LARCH_ABI_LP64D 0x03
#define EF_LARCH_ABI_MODIFIER_MASK 0x07
#define EF_LARCH_ABI_SOFT_FLOAT 0x01
#define EF_LARCH_ABI_SINGLE_FLOAT 0x02
#define EF_LARCH_ABI_DOUBLE_FLOAT 0x03
#define EF_LARCH_OBJABI_V1 0x40
/* LoongArch specific dynamic relocations */
#define R_LARCH_NONE 0
+13
View File
@@ -19,7 +19,14 @@ typedef int (*foo_p) (void);
#endif
foo_p foo_ptr = foo;
/* Address-significant access to protected symbols is not supported in
position-dependent mode on several architectures because GCC
generates relocations that assume that the address is local to the
main program. */
#ifdef __PIE__
foo_p foo_procted_ptr = foo_protected;
#endif
extern foo_p get_foo_p (void);
extern foo_p get_foo_hidden_p (void);
@@ -37,12 +44,16 @@ main (void)
if ((*foo_ptr) () != -1)
abort ();
#ifdef __PIE__
if (foo_procted_ptr != foo_protected)
abort ();
#endif
if (foo_protected () != 0)
abort ();
#ifdef __PIE__
if ((*foo_procted_ptr) () != 0)
abort ();
#endif
p = get_foo_p ();
if (p != foo)
@@ -55,8 +66,10 @@ main (void)
abort ();
p = get_foo_protected_p ();
#ifdef __PIE__
if (p != foo_protected)
abort ();
#endif
if (ret_foo_protected != 0 || (*p) () != ret_foo_protected)
abort ();
+9
View File
@@ -14,12 +14,19 @@ get_foo (void)
return foo;
}
/* Address-significant access to protected symbols is not supported in
position-dependent mode on several architectures because GCC
generates relocations that assume that the address is local to the
main program. */
#ifdef __PIE__
foo_p
__attribute__ ((noinline))
get_foo_protected (void)
{
return foo_protected;
}
#endif
int
main (void)
@@ -30,9 +37,11 @@ main (void)
if ((*p) () != -1)
abort ();
#ifdef __PIE__
p = get_foo_protected ();
if ((*p) () != 0)
abort ();
#endif
return 0;
}
+1 -1
View File
@@ -52,7 +52,7 @@ $(objpfx)rtld-libc.a: $(foreach dir,$(rtld-subdirs),\
mv -f $@T $@
# Use the verbose option of ar and tar when not running silently.
ifeq "$(findstring s,$(MAKEFLAGS))" "" # if not -s
ifeq ($(silent-make),no) # if not -s
verbose := v
else # -s
verbose :=
+63 -27
View File
@@ -791,6 +791,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);
@@ -1293,6 +1295,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
@@ -1762,33 +1818,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)
@@ -2122,6 +2152,12 @@ dl_main (const ElfW(Phdr) *phdr,
if (l->l_faked)
/* The library was not found. */
_dl_printf ("\t%s => not found\n", l->l_libname->name);
else if (strcmp (l->l_libname->name, l->l_name) == 0)
/* Print vDSO like libraries without duplicate name. Some
consumers depend of this format. */
_dl_printf ("\t%s (0x%0*Zx)\n", l->l_libname->name,
(int) sizeof l->l_map_start * 2,
(size_t) l->l_map_start);
else
_dl_printf ("\t%s => %s (0x%0*Zx)\n",
DSO_FILENAME (l->l_libname->name),
+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);
+37
View File
@@ -0,0 +1,37 @@
/* Initialization of libc after dlmopen/dlclose/dlmopen (bug 29528). Module 1.
Copyright (C) 2022 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>
static void __attribute__ ((constructor))
init (void)
{
puts ("info: tst-dlmopen-twice-mod1.so loaded");
fflush (stdout);
}
static void __attribute__ ((destructor))
fini (void)
{
puts ("info: tst-dlmopen-twice-mod1.so about to be unloaded");
fflush (stdout);
}
/* Large allocation. The second module does not have this, so it
should load libc at a different address. */
char large_allocate[16 * 1024 * 1024];
+50
View File
@@ -0,0 +1,50 @@
/* Initialization of libc after dlmopen/dlclose/dlmopen (bug 29528). Module 2.
Copyright (C) 2022 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 <ctype.h>
#include <stdio.h>
static void __attribute__ ((constructor))
init (void)
{
puts ("info: tst-dlmopen-twice-mod2.so loaded");
fflush (stdout);
}
static void __attribute__ ((destructor))
fini (void)
{
puts ("info: tst-dlmopen-twice-mod2.so about to be unloaded");
fflush (stdout);
}
int
run_check (void)
{
puts ("info: about to call isalpha");
fflush (stdout);
volatile char ch = 'a';
if (!isalpha (ch))
{
puts ("error: isalpha ('a') is not true");
fflush (stdout);
return 1;
}
return 0;
}
+54
View File
@@ -0,0 +1,54 @@
/* Initialization of libc after dlmopen/dlclose/dlmopen (bug 29528). Main.
Copyright (C) 2022 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 <support/check.h>
#include <support/xdlfcn.h>
/* Run the test multiple times, to check finding a new namespace while
another namespace is already in use. This used to trigger bug 29600. */
static void
recurse (int depth)
{
if (depth == 0)
return;
printf ("info: running at depth %d\n", depth);
void *handle = xdlmopen (LM_ID_NEWLM, "tst-dlmopen-twice-mod1.so",
RTLD_NOW);
xdlclose (handle);
handle = xdlmopen (LM_ID_NEWLM, "tst-dlmopen-twice-mod2.so", RTLD_NOW);
int (*run_check) (void) = xdlsym (handle, "run_check");
TEST_COMPARE (run_check (), 0);
recurse (depth - 1);
xdlclose (handle);
}
static int
do_test (void)
{
/* First run the test without nesting. */
recurse (1);
/* Then with nesting. The constant needs to be less than the
internal DL_NNS namespace constant. */
recurse (10);
return 0;
}
#include <support/test-driver.c>
+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
+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);
}
+23 -2
View File
@@ -1,4 +1,5 @@
# Copyright (C) 1995-2022 Free Software Foundation, Inc.
# 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>
+8 -8
View File
@@ -29,14 +29,14 @@
# define isspace(__c) __isspace_l ((__c), _nl_C_locobj_ptr)
# define asprintf __asprintf
# define opendir __opendir
# define readdir __readdir
# define readdir64 __readdir64
# define closedir __closedir
# define mempcpy __mempcpy
# define struct_stat struct __stat64_t64
# define lstat __lstat64_time64
# define struct_stat64 struct __stat64_t64
# define lstat64 __lstat64_time64
# define feof_unlocked __feof_unlocked
#else
# define struct_stat struct stat
# define struct_stat64 struct stat64
#endif
/* Name of the file containing the module information in the directories
@@ -148,8 +148,8 @@ gconv_parseconfdir (const char *prefix, const char *dir, size_t dir_len)
DIR *confdir = opendir (buf);
if (confdir != NULL)
{
struct dirent *ent;
while ((ent = readdir (confdir)) != NULL)
struct dirent64 *ent;
while ((ent = readdir64 (confdir)) != NULL)
{
if (ent->d_type != DT_REG && ent->d_type != DT_UNKNOWN)
continue;
@@ -161,12 +161,12 @@ gconv_parseconfdir (const char *prefix, const char *dir, size_t dir_len)
&& strcmp (ent->d_name + len - strlen (suffix), suffix) == 0)
{
char *conf;
struct_stat st;
struct_stat64 st;
if (asprintf (&conf, "%s/%s", buf, ent->d_name) < 0)
continue;
if (ent->d_type != DT_UNKNOWN
|| (lstat (conf, &st) != -1 && S_ISREG (st.st_mode)))
|| (lstat64 (conf, &st) != -1 && S_ISREG (st.st_mode)))
found |= read_conf_file (conf, dir, dir_len);
free (conf);
+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>
+106
View File
@@ -55,6 +55,12 @@ int __ns_name_ntop (const unsigned char *, char *, size_t) __THROW;
int __ns_name_unpack (const unsigned char *, const unsigned char *,
const unsigned char *, unsigned char *, size_t) __THROW;
/* Like ns_samename, but for uncompressed binary names. Return true
if the two arguments compare are equal as case-insensitive domain
names. */
_Bool __ns_samebinaryname (const unsigned char *, const unsigned char *)
attribute_hidden;
#define ns_msg_getflag(handle, flag) \
(((handle)._flags & _ns_flagdata[flag].mask) >> _ns_flagdata[flag].shift)
@@ -89,5 +95,105 @@ libc_hidden_proto (__ns_name_unpack)
extern __typeof (ns_samename) __libc_ns_samename;
libc_hidden_proto (__libc_ns_samename)
/* Packet parser helper functions. */
/* Verify that P points to an uncompressed domain name in wire format.
On success, return the length of the encoded name, including the
terminating null byte. On failure, return -1 and set errno. EOM
must point one past the last byte in the packet. */
int __ns_name_length_uncompressed (const unsigned char *p,
const unsigned char *eom) attribute_hidden;
/* Iterator over the resource records in a DNS packet. */
struct ns_rr_cursor
{
/* These members are not changed after initialization. */
const unsigned char *begin; /* First byte of packet. */
const unsigned char *end; /* One past the last byte of the packet. */
const unsigned char *first_rr; /* First resource record (or packet end). */
/* Advanced towards the end while reading the packet. */
const unsigned char *current;
};
/* Returns the RCODE field from the DNS header. */
static inline int
ns_rr_cursor_rcode (const struct ns_rr_cursor *c)
{
return c->begin[3] & 0x0f; /* Lower 4 bits at offset 3. */
}
/* Returns the length of the answer section according to the DNS header. */
static inline int
ns_rr_cursor_ancount (const struct ns_rr_cursor *c)
{
return c->begin[6] * 256 + c->begin[7]; /* 16 bits at offset 6. */
}
/* Returns the length of the authority (name server) section according
to the DNS header. */
static inline int
ns_rr_cursor_nscount (const struct ns_rr_cursor *c)
{
return c->begin[8] * 256 + c->begin[9]; /* 16 bits at offset 8. */
}
/* Returns the length of the additional data section according to the
DNS header. */
static inline int
ns_rr_cursor_adcount (const struct ns_rr_cursor *c)
{
return c->begin[10] * 256 + c->begin[11]; /* 16 bits at offset 10. */
}
/* Returns a pointer to the uncompressed question name in wire
format. */
static inline const unsigned char *
ns_rr_cursor_qname (const struct ns_rr_cursor *c)
{
return c->begin + 12; /* QNAME starts right after the header. */
}
/* Returns the question type of the first and only question. */
static inline const int
ns_rr_cursor_qtype (const struct ns_rr_cursor *c)
{
/* 16 bits 4 bytes back from the first RR header start. */
return c->first_rr[-4] * 256 + c->first_rr[-3];
}
/* Returns the clss of the first and only question (usally C_IN). */
static inline const int
ns_rr_cursor_qclass (const struct ns_rr_cursor *c)
{
/* 16 bits 2 bytes back from the first RR header start. */
return c->first_rr[-2] * 256 + c->first_rr[-1];
}
/* Initializes *C to cover the packet [BUF, BUF+LEN). Returns false
if LEN is less than sizeof (*HD), if the packet does not contain a
full (uncompressed) question, or if the question count is not 1. */
_Bool __ns_rr_cursor_init (struct ns_rr_cursor *c,
const unsigned char *buf, size_t len)
attribute_hidden;
/* Like ns_rr, but the record owner name is not decoded into text format. */
struct ns_rr_wire
{
unsigned char rname[NS_MAXCDNAME]; /* Owner name of the record. */
uint16_t rtype; /* Resource record type (T_*). */
uint16_t rclass; /* Resource record class (C_*). */
uint32_t ttl; /* Time-to-live field. */
const unsigned char *rdata; /* Start of resource record data. */
uint16_t rdlength; /* Length of the data at rdata, in bytes. */
};
/* Attempts to parse the record at C into *RR. On success, return
true, and C is advanced past the record, and RR->rdata points to
the record data. On failure, errno is set to EMSGSIZE, and false
is returned. */
_Bool __ns_rr_cursor_next (struct ns_rr_cursor *c, struct ns_rr_wire *rr)
attribute_hidden;
# endif /* !_ISOMAC */
#endif
+1
View File
@@ -0,0 +1 @@
#include <wcsmbs/bits/wchar2-decl.h>
+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
{
+3
View File
@@ -70,5 +70,8 @@ libc_hidden_proto (__libc_res_nameinquery)
extern __typeof (__res_queriesmatch) __libc_res_queriesmatch;
libc_hidden_proto (__libc_res_queriesmatch)
/* Variant of res_hnok which operates on binary (but uncompressed) names. */
bool __res_binary_hnok (const unsigned char *dn) attribute_hidden;
# endif /* _RESOLV_H_ && !_ISOMAC */
#endif
-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
@@ -529,8 +529,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)
+7
View File
@@ -27,7 +27,14 @@ findidx (const int32_t *table,
const unsigned char *extra,
const unsigned char **cpp, size_t len)
{
/* With GCC 8 when compiling with -Os the compiler warns that
seq1.back_us and seq2.back_us might be used uninitialized.
This uninitialized use is impossible for the same reason
as described in comments in locale/weightwc.h. */
DIAG_PUSH_NEEDS_COMMENT;
DIAG_IGNORE_Os_NEEDS_COMMENT (8, "-Wmaybe-uninitialized");
int32_t i = table[*(*cpp)++];
DIAG_POP_NEEDS_COMMENT;
const unsigned char *cp;
const unsigned char *usrc;
+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
@@ -937,7 +937,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);
+5 -3
View File
@@ -4949,7 +4949,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;
@@ -4960,8 +4960,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)
@@ -175,6 +178,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)
+14 -4
View File
@@ -24,6 +24,20 @@
extern void __syslog_chk (int __pri, int __flag, const char *__fmt, ...)
__attribute__ ((__format__ (__printf__, 3, 4)));
#ifdef __USE_MISC
extern void __vsyslog_chk (int __pri, int __flag, const char *__fmt,
__gnuc_va_list __ap)
__attribute__ ((__format__ (__printf__, 3, 0)));
#endif
#include <bits/floatn.h>
#if defined __LDBL_COMPAT || __LDOUBLE_REDIRECTS_TO_FLOAT128_ABI == 1
# include <bits/syslog-ldbl.h>
#endif
/* The following functions must be used only after applying all asm
redirections, e.g. long double asm redirections. */
#ifdef __va_arg_pack
__fortify_function void
syslog (int __pri, const char *__fmt, ...)
@@ -37,10 +51,6 @@ syslog (int __pri, const char *__fmt, ...)
#ifdef __USE_MISC
extern void __vsyslog_chk (int __pri, int __flag, const char *__fmt,
__gnuc_va_list __ap)
__attribute__ ((__format__ (__printf__, 3, 0)));
__fortify_function void
vsyslog (int __pri, const char *__fmt, __gnuc_va_list __ap)
{
-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)))
+5 -5
View File
@@ -205,11 +205,11 @@ extern void vsyslog (int __pri, const char *__fmt, __gnuc_va_list __ap)
/* Define some macros helping to catch buffer overflows. */
#if __USE_FORTIFY_LEVEL > 0 && defined __fortify_function
# include <bits/syslog.h>
#endif
#include <bits/floatn.h>
#if defined __LDBL_COMPAT || __LDOUBLE_REDIRECTS_TO_FLOAT128_ABI == 1
# include <bits/syslog-ldbl.h>
#else
# include <bits/floatn.h>
# if defined __LDBL_COMPAT || __LDOUBLE_REDIRECTS_TO_FLOAT128_ABI == 1
# include <bits/syslog-ldbl.h>
# endif
#endif
__END_DECLS

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