kernelsauce / turbo

Turbo is a framework built for LuaJIT 2 to simplify the task of building fast and scalable network applications. It uses a event-driven, non-blocking, no thread design to deliver excellent performance and minimal footprint to high-load applications while also providing excellent support for embedded uses.
http://turbo.readthedocs.io/
Apache License 2.0
525 stars 84 forks source link

ffi.gc is called with the wrong paramter #363

Open fengyd2006 opened 1 year ago

fengyd2006 commented 1 year ago

Recently I met a segment fault issue ,and finally found that when calling get_url_field in turbo httputils.lua, ffi.gc is called with the wrong paramter. ffi.gc(htpurl, ffi.C.free) htpurl is a temporary pointer, which goes out of scope and will eventually be collected. It should be changed to ffi.gc(self.http_parser_url, ffi.C.free) and put it after: self.http_parser_url = ffi.cast("struct http_parser_url *", htpurl)

function httputil.HTTPParser:parse_url(url)
    if type(url) ~= "string" then
        error("URL parameter is not a string")
    end
    local htpurl = ffi.C.malloc(ffi.sizeof("struct http_parser_url"))
    if htpurl == nil then
        error("Could not allocate memory")
    end
    ffi.gc(htpurl, ffi.C.free)
    self.http_parser_url = ffi.cast("struct http_parser_url *", htpurl)
    local rc = libturbo_parser.http_parser_parse_url(
        url,
        url:len(),
        0,
        self.http_parser_url)
    if rc ~= 0 then
       error("Could not parse URL")
    end
    if not self.url then
        self.url = url
    end
end
seclorum commented 1 year ago

Is it not enough to just move the ffi.gc(htpurl, ffi.C.free) before self.url assignment at the end?

Also, not sure what the effect of garbage collecting a struct http_parser_url * is going to be in that context, that was probably rightly not ffi.gc()'ed originally ..

kernelsauce commented 1 year ago

Thanks for reporting I will fix this.