Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit fa3c354

Browse files
committed
lib/utmp.c: Optimised number of allocations
Instead of using up to three allocation every time when get_current_utmp() function is called, the maximum a single allocation is used. A minor code optimisation is applied: the match by "line" is not checked if entry matched by PID has been already found. Fixes: 8417765 (14-07-2025; "lib/utmp.c: Fix umtp entry search") Signed-off-by: Evgeny Grin (Karlson2k) <[email protected]>
1 parent a6620a9 commit fa3c354

1 file changed

Lines changed: 20 additions & 24 deletions

File tree

lib/utmp.c

Lines changed: 20 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -150,8 +150,8 @@ static /*@null@*/ /*@only@*/struct utmpx *
150150
get_current_utmp(pid_t main_pid)
151151
{
152152
struct utmpx *ut;
153-
struct utmpx *ut_by_pid = NULL;
154-
struct utmpx *ut_by_line = NULL;
153+
struct utmpx *ut_copy = NULL;
154+
bool ut_copy_is_by_line_only = false;
155155

156156
setutxent();
157157

@@ -162,38 +162,34 @@ get_current_utmp(pid_t main_pid)
162162
continue;
163163

164164
if (main_pid == ut->ut_pid) {
165-
if (is_my_tty(ut->ut_line))
165+
bool has_tty_match;
166+
167+
has_tty_match = is_my_tty(ut->ut_line);
168+
169+
if (NULL == ut_copy) {
170+
ut_copy = XMALLOC(1, struct utmpx);
171+
*ut_copy = *ut;
172+
} else if ( has_tty_match
173+
|| ut_copy_is_by_line_only)
174+
*ut_copy = *ut;
175+
176+
if (has_tty_match)
166177
break; /* Perfect match, stop the search */
167178

168-
if (NULL == ut_by_pid) {
169-
ut_by_pid = XMALLOC(1, struct utmpx);
170-
*ut_by_pid = *ut;
171-
}
179+
ut_copy_is_by_line_only = false; /* Match by PID */
172180

173-
} else if ( (NULL == ut_by_line)
181+
} else if ( (NULL == ut_copy)
174182
&& (LOGIN_PROCESS == ut->ut_type) /* Be more picky when matching by 'ut_line' only */
175183
&& (is_my_tty(ut->ut_line))) {
176-
ut_by_line = XMALLOC(1, struct utmpx);
177-
*ut_by_line = *ut;
184+
ut_copy = XMALLOC(1, struct utmpx);
185+
*ut_copy = *ut;
186+
ut_copy_is_by_line_only = true;
178187
}
179188
}
180189

181-
if (NULL == ut)
182-
ut = ut_by_pid ?: ut_by_line;
183-
184-
if (NULL != ut) {
185-
struct utmpx *ut_copy;
186-
187-
ut_copy = XMALLOC(1, struct utmpx);
188-
memcpy(ut_copy, ut, sizeof(*ut));
189-
ut = ut_copy;
190-
}
191-
192-
free (ut_by_line);
193-
free (ut_by_pid);
194190
endutxent();
195191

196-
return ut;
192+
return ut_copy;
197193
}
198194

199195

0 commit comments

Comments
 (0)