Skip to content

Commit ce060da

Browse files
committed
Fix uninitialized t_l_req in --verbose FD mode
Move gettimeofday(&t_l_req) from command-mode-only block to just before the flock() loop, so it covers both command and FD paths. Previously, FD mode with --verbose read uninitialized stack memory, producing garbage like "took 1774858164251193 microseconds". Add regression test verifying verbose FD mode timing is sane (<1s).
1 parent 869738b commit ce060da

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

src/flock.c

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -265,10 +265,8 @@ int main(int argc, char *argv[]) {
265265
open_flags = O_WRONLY | O_NOCTTY | O_CREAT;
266266
}
267267

268-
if (verbose) {
269-
gettimeofday(&t_l_req, NULL);
268+
if (verbose)
270269
printf("flock: getting lock\n");
271-
}
272270
fd = open(filename, open_flags, 0666);
273271

274272
// directories don't like O_WRONLY (and sometimes O_CREAT)
@@ -314,6 +312,9 @@ int main(int argc, char *argv[]) {
314312
err(EX_OSERR, "could not set interval timer");
315313
}
316314

315+
if (verbose)
316+
gettimeofday(&t_l_req, NULL);
317+
317318
while (0 != flock(fd, type | block)) {
318319
switch (errno) {
319320
case EWOULDBLOCK: // non-blocking lock not available

t/default.bats

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -618,6 +618,16 @@ get_elapsed() {
618618
[[ "$result" == *"microseconds"* ]]
619619
}
620620

621+
@test "--verbose in fd mode reports sane timing" {
622+
# Regression: t_l_req was uninitialized in FD mode, producing
623+
# garbage like "took 1774858164251193 microseconds"
624+
result=$( (${FLOCK} --verbose 8) 8> ${LOCKFILE} 2>&1 )
625+
[[ "$result" == *"microseconds"* ]]
626+
# Extract the number and verify it's under 1 second (1000000 us)
627+
elapsed=$(echo "$result" | grep -o '[0-9]* microseconds' | grep -o '[0-9]*')
628+
[ "$elapsed" -lt 1000000 ]
629+
}
630+
621631
###############################################################################
622632
# Lock is released when holder exits
623633
###############################################################################

0 commit comments

Comments
 (0)