Skip to content

Commit 421ed88

Browse files
bugfix: ngx.req.start_time() corrupted nginx's cached time on freenginx.
ngx_stream_lua_ffi_req_start_time() (the freenginx branch) called ngx_timeofday() and then mutated *tp directly. ngx_timeofday() returns a pointer to ngx_cached_time, the global time cache shared by the entire worker, so the subtraction of (ngx_current_msec - r->session->start_time) silently rewound the clock for every subsequent ngx_timeofday() reader within the same event-loop tick (log timestamps, timer deadlines, etc.). Copy the cached time into a local ngx_time_t and do the arithmetic there. Mirrors the fix in lua-nginx-module.
1 parent 4fb91d9 commit 421ed88

1 file changed

Lines changed: 14 additions & 6 deletions

File tree

src/ngx_stream_lua_time.c

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -37,17 +37,25 @@ double
3737
ngx_stream_lua_ffi_req_start_time(ngx_stream_lua_request_t *r)
3838
{
3939
#if defined freenginx
40+
ngx_time_t start;
4041
ngx_time_t *tp;
42+
ngx_msec_t elapsed;
4143

44+
/* ngx_timeofday() returns a pointer to nginx's globally cached time;
45+
* mutating it would corrupt every other read of the current time
46+
* within this worker tick. Copy it locally instead. */
4247
tp = ngx_timeofday();
43-
tp->sec -= (ngx_current_msec - r->session->start_time) / 1000;
44-
tp->msec -= (ngx_current_msec - r->session->start_time) % 1000;
45-
if (tp->msec > NGX_MAX_INT_T_VALUE) {
46-
tp->msec += 1000;
47-
tp->sec -= 1;
48+
start = *tp;
49+
50+
elapsed = ngx_current_msec - r->session->start_time;
51+
start.sec -= elapsed / 1000;
52+
start.msec -= elapsed % 1000;
53+
if (start.msec > NGX_MAX_INT_T_VALUE) {
54+
start.msec += 1000;
55+
start.sec -= 1;
4856
}
4957

50-
return tp->sec + tp->msec / 1000.0;
58+
return start.sec + start.msec / 1000.0;
5159
#else
5260
return r->session->start_sec + r->session->start_msec / 1000.0;
5361
#endif

0 commit comments

Comments
 (0)