Debian Codegraph @

devel-docs/memory_leaks.rst

raw
1 Apparent memory leaks
2 =====================
3
4 If you run Valgrind or another memory checker on a program that uses librsvg, or
5 ``rsvg-convert``, you may get false positives. This chapter explains why these occur by
6 giving some examples of false positives from Valgrind.
7
8 Note that there may be real memory leaks, and they should be fixed! This chapter just
9 explains why not everything that is reported as a memory leak is in fact a leak.
10
11 Example: false leak in fontconfig's code for ``FcPattern``
12 ----------------------------------------------------------
13
14 .. code-block::
15
16 $ valgrind --leak-check=full --track-origins=yes rsvg-convert -o foo.png foo.svg
17
18 ==5712== 5,378 (512 direct, 4,866 indirect) bytes in 1 blocks are definitely lost in loss record 1,463 of 1,487
19 ==5712== at 0x484D82F: realloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
20 ==5712== by 0x5577D88: FcPatternObjectInsertElt (fcpat.c:516)
21 ==5712== by 0x557BE08: FcPatternObjectAddWithBinding (fcpat.c:711)
22 ==5712== by 0x557315F: UnknownInlinedFun (fcpat.c:738)
23 ==5712== by 0x557315F: UnknownInlinedFun (fcpat.c:884)
24 ==5712== by 0x557315F: FcDefaultSubstitute (fcdefault.c:257)
25 ==5712== by 0x544E15D: UnknownInlinedFun (pangofc-fontmap.c:2066)
26 ==5712== by 0x544E15D: UnknownInlinedFun (pangofc-fontmap.c:2143)
27 ==5712== by 0x544E15D: pango_fc_font_map_load_fontset (pangofc-fontmap.c:2245)
28 ==5712== by 0x4D74FBC: UnknownInlinedFun (itemize.c:892)
29 ==5712== by 0x4D74FBC: UnknownInlinedFun (itemize.c:952)
30 ==5712== by 0x4D74FBC: pango_itemize_with_font (itemize.c:1564)
31 ==5712== by 0x4D880D1: pango_layout_check_lines.part.0.lto_priv.0 (pango-layout.c:4894)
32 ==5712== by 0x4D7D58D: UnknownInlinedFun (pango-layout.c:4786)
33 ==5712== by 0x4D7D58D: pango_layout_get_extents_internal.lto_priv.0 (pango-layout.c:2925)
34 ==5712== by 0x4D7D735: pango_layout_get_size (pango-layout.c:3166)
35 ==5712== by 0x6987FF: pango::auto::layout::Layout::size (layout.rs:321)
36 ==5712== by 0x542342: librsvg::text::MeasuredSpan::from_span (text.rs:357)
37 ==5712== by 0x33465C: librsvg::text::MeasuredChunk::from_chunk::{{closure}} (text.rs:146)
38
39 Fontconfig is a library to enumerate the system's fonts based on different configuration
40 parameters. It gets used by Pango, GNOME's library for text rendering, and in turn by
41 librsvg.
42
43 Is the report above a leak in fontconfig? No. Let's look at
44 ``FcPatternObjectInsertElt()``, the function that called ``realloc()`` in the stack
45 trace above. `From fccpat.c
46 <https://gitlab.freedesktop.org/fontconfig/fontconfig/-/blob/fd0753af/src/fcpat.c#L498-552>`_:
47
48 .. code-block:: c
49
50 int s = p->size + 16;
51 if (p->size)
52 {
53 FcPatternElt *e0 = FcPatternElts(p);
54 e = (FcPatternElt *) realloc (e0, s * sizeof (FcPatternElt));
55 if (!e) /* maybe it was mmapped */
56 {
57 e = malloc(s * sizeof (FcPatternElt));
58 if (e)
59 memcpy(e, e0, FcPatternObjectCount (p) * sizeof (FcPatternElt));
60 }
61 }
62 else
63 e = (FcPatternElt *) malloc (s * sizeof (FcPatternElt));
64 if (!e)
65 return FcFalse;
66 p->elts_offset = FcPtrToOffset (p, e);
67
68 The code inside the first ``if (p->size)`` essentially does a ``realloc()`` to resize an
69 existing array, or ``malloc()`` to allocate a new one. However, **that pointer is encoded
70 instead of stored plainly** in the last line: ``p->elts_offset = FcPtrToOffset (p, e)``.
71 If you look at the definition of `FcPtrToOffset
72 <https://gitlab.freedesktop.org/fontconfig/fontconfig/-/blob/fd0753af/src/fcint.h#L161>`_,
73 you will see that it encodes the pointer as the offset between a base location and the
74 pointer's location itself (``p`` and ``e`` respectively in the code above).
75
76 What Valgrind thinks is, "oh, they just allocated this memory and immediately obliterated
77 the pointer to it, so it must be a leak!". However, what actually happens is that
78 fontconfig doesn't store that pointer plainly, but mangles it somehow. Then it un-mangles
79 it with `FcPatternElts
80 <https://gitlab.freedesktop.org/fontconfig/fontconfig/-/blob/fd0753af/src/fcint.h#L232>`_
81 to access it, and frees the memory properly `later in FcPatternDestroy()
82 <https://gitlab.freedesktop.org/fontconfig/fontconfig/-/blob/fd0753af/src/fcpat.c#L439-443>`_.
83
84
85 Example: false leak in Rust's hashbrown crate
86 ---------------------------------------------
87
88 .. code-block::
89
90 $ valgrind --leak-check=full --track-origins=yes rsvg-convert -o foo.png foo.svg
91
92 ==5712== 708 bytes in 3 blocks are possibly lost in loss record 1,380 of 1,487
93 ==5712== at 0x48487B4: malloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
94 ==5712== by 0x79E17B: alloc::alloc::alloc (alloc.rs:87)
95 ==5712== by 0x79E316: alloc::alloc::Global::alloc_impl (alloc.rs:169)
96 ==5712== by 0x79E439: <alloc::alloc::Global as core::alloc::Allocator>::allocate (alloc.rs:229)
97 ==5712== by 0x784A57: hashbrown::raw::alloc::inner::do_alloc (alloc.rs:11)
98 ==5712== by 0x7C8ECD: hashbrown::raw::RawTableInner<A>::new_uninitialized (mod.rs:1086)
99 ==5712== by 0x7C926B: hashbrown::raw::RawTableInner<A>::fallible_with_capacity (mod.rs:1115)
100 ==5712== by 0x7CA2C5: hashbrown::raw::RawTableInner<A>::prepare_resize (mod.rs:1359)
101 ==5712== by 0x7C7424: hashbrown::raw::RawTable<T,A>::reserve_rehash (mod.rs:1432)
102 ==5712== by 0x7C7068: hashbrown::raw::RawTable<T,A>::reserve (mod.rs:652)
103 ==5712== by 0x7C81F5: hashbrown::raw::RawTable<T,A>::insert (mod.rs:731)
104 ==5712== by 0x77828B: hashbrown::map::HashMap<K,V,S,A>::insert (map.rs:1508)
105
106 Hashbrown is a Rust crate that implements an efficient hash table. Let's look at the code from `hashbrown::raw::RawTableInner<A>::new_uninitialized <https://github.com/rust-lang/hashbrown/blob/1d2c1a81d1b53285decbd64410a21a90112613d7/src/raw/mod.rs#L1080-L1085>`_:
107
108 .. code-block:: rust
109
110 let ptr: NonNull<u8> = match do_alloc(&alloc, layout) {
111 Ok(block) => block.cast(),
112 Err(_) => return Err(fallibility.alloc_err(layout)),
113 };
114
115 let ctrl = NonNull::new_unchecked(ptr.as_ptr().add(ctrl_offset));
116
117 First it calls ``do_alloc`` which is essentially ``malloc()`` underneath. Then, **it adds
118 an offset to the resulting ptr**, where it does ``ptr.as_ptr().add(ctrl_offset)``. You
119 can see a description of the actual layout `in the declaration of the ctrl field
120 <https://github.com/rust-lang/hashbrown/blob/1d2c1a81d1b53285decbd64410a21a90112613d7/src/raw/mod.rs#L374-L376>`_.
121 Similar to the example above for fontconfig, Valgrind sees that the code immediately
122 obliterates the only existing pointer to the newly-allocated memory, and thus thinks that
123 it leaks the corresponding memory.
124
125
126 Example: false leak in Rust's regex crate
127 -----------------------------------------
128
129 .. code-block::
130
131 $ valgrind --leak-check=full --track-origins=yes rsvg-convert -o foo.png foo.svg
132
133 ==5712== 42 bytes in 6 blocks are possibly lost in loss record 793 of 1,487
134 ==5712== at 0x48487B4: malloc (in /usr/libexec/valgrind/vgpreload_memcheck-amd64-linux.so)
135 ==5712== by 0xA99074: alloc (alloc.rs:87)
136 ==5712== by 0xA99074: alloc_impl (alloc.rs:169)
137 ==5712== by 0xA99074: allocate (alloc.rs:229)
138 ==5712== by 0xA99074: allocate_in<u8, alloc::alloc::Global> (raw_vec.rs:185)
139 ==5712== by 0xA99074: with_capacity_in<u8, alloc::alloc::Global> (raw_vec.rs:132)
140 ==5712== by 0xA99074: with_capacity_in<u8, alloc::alloc::Global> (mod.rs:609)
141 ==5712== by 0xA99074: to_vec<u8, alloc::alloc::Global> (slice.rs:227)
142 ==5712== by 0xA99074: to_vec<u8, alloc::alloc::Global> (slice.rs:176)
143 ==5712== by 0xA99074: to_vec_in<u8, alloc::alloc::Global> (slice.rs:501)
144 ==5712== by 0xA99074: clone<u8, alloc::alloc::Global> (mod.rs:2483)
145 ==5712== by 0xA99074: <alloc::string::String as core::clone::Clone>::clone (string.rs:1861)
146 ==5712== by 0x761A56: <T as alloc::borrow::ToOwned>::to_owned (borrow.rs:90)
147 ==5712== by 0x765986: <alloc::string::String as alloc::string::ToString>::to_string (string.rs:2486)
148 ==5712== by 0x7692DB: regex::compile::Compiler::c (compile.rs:373)
149 ==5712== by 0x76C748: regex::compile::Compiler::c_concat (compile.rs:532)
150 ==5712== by 0x769124: regex::compile::Compiler::c (compile.rs:384)
151 ==5712== by 0x76927B: regex::compile::Compiler::c (compile.rs:364)
152 ==5712== by 0x76E4B1: regex::compile::Compiler::c_repeat_zero_or_one (compile.rs:614)
153 ==5712== by 0x76E302: regex::compile::Compiler::c_repeat (compile.rs:592)
154 ==5712== by 0x769031: regex::compile::Compiler::c (compile.rs:388)
155 ==5712== by 0x76C748: regex::compile::Compiler::c_concat (compile.rs:532)
156
157 This is related to the example above for the hashbrown crate. The regex crate, for regular expressions, builds a hash table with the names of captures. It `allocates a string for the name of each capture and inserts it in a hash table <https://github.com/rust-lang/regex/blob/9ca3099/src/compile.rs#L371-L378>`_:
158
159 .. code-block:: rust
160
161 hir::GroupKind::CaptureName { index, ref name } => {
162 if index as usize >= self.compiled.captures.len() {
163 let n = name.to_string();
164 self.compiled.captures.push(Some(n.clone()));
165 self.capture_name_idx.insert(n, index as usize);
166 }
167 self.c_capture(2 * index as usize, &g.hir)
168 }
169
170 The allocation happens in ``name.to_string()``. Two lines below, the string gets inserted
171 into the ``self.capture_name_idx`` hash table.
172
173 By looking at the `declaration for the capture_name_idx field
174 <https://github.com/rust-lang/regex/blob/9ca3099/src/compile.rs#L35>`_, we see that it is
175 a ``HashMap<String, usize>``. However, that ``HashMap`` is in fact a hashbrown table, as
176 in the previous section. Since hashbrown uses a special encoding for its internal
177 pointers, Valgrind thinks that the original pointer to the string is lost.