Home | History | Annotate | Download | only in gcmole
      1 -- Copyright 2011 the V8 project authors. All rights reserved.
      2 -- Redistribution and use in source and binary forms, with or without
      3 -- modification, are permitted provided that the following conditions are
      4 -- met:
      5 --
      6 --     * Redistributions of source code must retain the above copyright
      7 --       notice, this list of conditions and the following disclaimer.
      8 --     * Redistributions in binary form must reproduce the above
      9 --       copyright notice, this list of conditions and the following
     10 --       disclaimer in the documentation and/or other materials provided
     11 --       with the distribution.
     12 --     * Neither the name of Google Inc. nor the names of its
     13 --       contributors may be used to endorse or promote products derived
     14 --       from this software without specific prior written permission.
     15 --
     16 -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     17 -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     18 -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
     19 -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
     20 -- OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     21 -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
     22 -- LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     23 -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     24 -- THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     25 -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
     26 -- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     27 
     28 -- This is main driver for gcmole tool. See README for more details.
     29 -- Usage: CLANG_BIN=clang-bin-dir lua tools/gcmole/gcmole.lua [arm|ia32|x64]
     30 
     31 local DIR = arg[0]:match("^(.+)/[^/]+$")
     32 
     33 local FLAGS = {
     34    -- Do not build gcsuspects file and reuse previously generated one.
     35    reuse_gcsuspects = false;
     36 
     37    -- Print commands to console before executing them.
     38    verbose = false;
     39 
     40    -- Perform dead variable analysis (generates many false positives).
     41    -- TODO add some sort of whiteliste to filter out false positives.
     42    dead_vars = false;
     43 
     44    -- When building gcsuspects whitelist certain functions as if they
     45    -- can be causing GC. Currently used to reduce number of false
     46    -- positives in dead variables analysis. See TODO for WHITELIST
     47    -- below.
     48    whitelist = true;
     49 }
     50 local ARGS = {}
     51 
     52 for i = 1, #arg do
     53    local flag = arg[i]:match "^%-%-([%w_-]+)$"
     54    if flag then
     55       local no, real_flag = flag:match "^(no)([%w_-]+)$"
     56       if real_flag then flag = real_flag end
     57 
     58       flag = flag:gsub("%-", "_")
     59       if FLAGS[flag] ~= nil then
     60          FLAGS[flag] = (no ~= "no")
     61       else
     62          error("Unknown flag: " .. flag)
     63       end
     64    else
     65       table.insert(ARGS, arg[i])
     66    end
     67 end
     68 
     69 local ARCHS = ARGS[1] and { ARGS[1] } or { 'ia32', 'arm', 'x64' }
     70 
     71 local io = require "io"
     72 local os = require "os"
     73 
     74 function log(...)
     75    io.stderr:write(string.format(...))
     76    io.stderr:write "\n"
     77 end
     78 
     79 -------------------------------------------------------------------------------
     80 -- Clang invocation
     81 
     82 local CLANG_BIN = os.getenv "CLANG_BIN"
     83 local CLANG_PLUGINS = os.getenv "CLANG_PLUGINS"
     84 
     85 if not CLANG_BIN or CLANG_BIN == "" then
     86    error "CLANG_BIN not set"
     87 end
     88 
     89 if not CLANG_PLUGINS or CLANG_PLUGINS == "" then
     90    CLANG_PLUGINS = DIR
     91 end
     92 
     93 local function MakeClangCommandLine(plugin, plugin_args, triple, arch_define)
     94    if plugin_args then
     95      for i = 1, #plugin_args do
     96         plugin_args[i] = "-plugin-arg-" .. plugin .. " " .. plugin_args[i]
     97      end
     98      plugin_args = " " .. table.concat(plugin_args, " ")
     99    end
    100    return CLANG_BIN .. "/clang -cc1 -load " .. CLANG_PLUGINS .. "/libgcmole.so"
    101       .. " -plugin "  .. plugin
    102       .. (plugin_args or "")
    103       .. " -triple " .. triple
    104       .. " -D" .. arch_define
    105       .. " -DENABLE_DEBUGGER_SUPPORT"
    106       .. " -DV8_I18N_SUPPORT"
    107       .. " -Isrc"
    108       .. " -Ithird_party/icu/source/common"
    109       .. " -Ithird_party/icu/source/i18n"
    110 end
    111 
    112 function InvokeClangPluginForEachFile(filenames, cfg, func)
    113    local cmd_line = MakeClangCommandLine(cfg.plugin,
    114                                          cfg.plugin_args,
    115                                          cfg.triple,
    116                                          cfg.arch_define)
    117    for _, filename in ipairs(filenames) do
    118       log("-- %s", filename)
    119       local action = cmd_line .. " src/" .. filename .. " 2>&1"
    120       if FLAGS.verbose then print('popen ', action) end
    121       local pipe = io.popen(action)
    122       func(filename, pipe:lines())
    123       local success = pipe:close()
    124       if not success then error("Failed to run: " .. action) end
    125    end
    126 end
    127 
    128 -------------------------------------------------------------------------------
    129 -- GYP file parsing
    130 
    131 local function ParseGYPFile()
    132    local f = assert(io.open("tools/gyp/v8.gyp"), "failed to open GYP file")
    133    local gyp = f:read('*a')
    134    f:close()
    135 
    136    local result = {}
    137 
    138    for condition, sources in
    139       gyp:gmatch "'sources': %[.-### gcmole%((.-)%) ###(.-)%]" do
    140       local files = {}
    141       for file in sources:gmatch "'%.%./%.%./src/([^']-%.cc)'" do
    142          table.insert(files, file)
    143       end
    144       result[condition] = files
    145    end
    146 
    147    return result
    148 end
    149 
    150 local function EvaluateCondition(cond, props)
    151    if cond == 'all' then return true end
    152 
    153    local p, v = cond:match "(%w+):(%w+)"
    154 
    155    assert(p and v, "failed to parse condition: " .. cond)
    156    assert(props[p] ~= nil, "undefined configuration property: " .. p)
    157 
    158    return props[p] == v
    159 end
    160 
    161 local function BuildFileList(sources, props)
    162    local list = {}
    163    for condition, files in pairs(sources) do
    164       if EvaluateCondition(condition, props) then
    165          for i = 1, #files do table.insert(list, files[i]) end
    166       end
    167    end
    168    return list
    169 end
    170 
    171 local sources = ParseGYPFile()
    172 
    173 local function FilesForArch(arch)
    174    return BuildFileList(sources, { os = 'linux',
    175                                    arch = arch,
    176                                    mode = 'debug',
    177                                    simulator = ''})
    178 end
    179 
    180 local mtConfig = {}
    181 
    182 mtConfig.__index = mtConfig
    183 
    184 local function config (t) return setmetatable(t, mtConfig) end
    185 
    186 function mtConfig:extend(t)
    187    local e = {}
    188    for k, v in pairs(self) do e[k] = v end
    189    for k, v in pairs(t) do e[k] = v end
    190    return config(e)
    191 end
    192 
    193 local ARCHITECTURES = {
    194    ia32 = config { triple = "i586-unknown-linux",
    195                    arch_define = "V8_TARGET_ARCH_IA32" },
    196    arm = config { triple = "i586-unknown-linux",
    197                   arch_define = "V8_TARGET_ARCH_ARM" },
    198    x64 = config { triple = "x86_64-unknown-linux",
    199                   arch_define = "V8_TARGET_ARCH_X64" }
    200 }
    201 
    202 -------------------------------------------------------------------------------
    203 -- GCSuspects Generation
    204 
    205 local gc, gc_caused, funcs
    206 
    207 local WHITELIST = {
    208    -- The following functions call CEntryStub which is always present.
    209    "MacroAssembler.*CallExternalReference",
    210    "MacroAssembler.*CallRuntime",
    211    "CompileCallLoadPropertyWithInterceptor",
    212    "CallIC.*GenerateMiss",
    213 
    214    -- DirectCEntryStub is a special stub used on ARM. 
    215    -- It is pinned and always present.
    216    "DirectCEntryStub.*GenerateCall",  
    217 
    218    -- TODO GCMole currently is sensitive enough to understand that certain 
    219    --      functions only cause GC and return Failure simulataneously. 
    220    --      Callsites of such functions are safe as long as they are properly 
    221    --      check return value and propagate the Failure to the caller.
    222    --      It should be possible to extend GCMole to understand this.
    223    "Heap.*AllocateFunctionPrototype",
    224 
    225    -- Ignore all StateTag methods.
    226    "StateTag",
    227 
    228    -- Ignore printing of elements transition.
    229    "PrintElementsTransition"
    230 };
    231 
    232 local function AddCause(name, cause)
    233    local t = gc_caused[name]
    234    if not t then
    235       t = {}
    236       gc_caused[name] = t
    237    end
    238    table.insert(t, cause)
    239 end
    240 
    241 local function resolve(name)
    242    local f = funcs[name]
    243 
    244    if not f then
    245       f = {}
    246       funcs[name] = f
    247 
    248       if name:match "Collect.*Garbage" then
    249          gc[name] = true
    250          AddCause(name, "<GC>")
    251       end
    252 
    253       if FLAGS.whitelist then
    254          for i = 1, #WHITELIST do
    255             if name:match(WHITELIST[i]) then
    256                gc[name] = false
    257             end
    258          end
    259       end
    260    end
    261 
    262     return f
    263 end
    264 
    265 local function parse (filename, lines)
    266    local scope
    267 
    268    for funcname in lines do
    269       if funcname:sub(1, 1) ~= '\t' then
    270          resolve(funcname)
    271          scope = funcname
    272       else
    273          local name = funcname:sub(2)
    274          resolve(name)[scope] = true
    275       end
    276    end
    277 end
    278 
    279 local function propagate ()
    280    log "** Propagating GC information"
    281 
    282    local function mark(from, callers)
    283       for caller, _ in pairs(callers) do
    284          if gc[caller] == nil then
    285             gc[caller] = true
    286             mark(caller, funcs[caller])
    287          end
    288          AddCause(caller, from)
    289       end
    290    end
    291 
    292    for funcname, callers in pairs(funcs) do
    293       if gc[funcname] then mark(funcname, callers) end
    294    end
    295 end
    296 
    297 local function GenerateGCSuspects(arch, files, cfg)
    298    -- Reset the global state.
    299    gc, gc_caused, funcs = {}, {}, {}
    300 
    301    log ("** Building GC Suspects for %s", arch)
    302    InvokeClangPluginForEachFile (files,
    303                                  cfg:extend { plugin = "dump-callees" },
    304                                  parse)
    305 
    306    propagate()
    307 
    308    local out = assert(io.open("gcsuspects", "w"))
    309    for name, value in pairs(gc) do if value then out:write (name, '\n') end end
    310    out:close()
    311 
    312    local out = assert(io.open("gccauses", "w"))
    313    out:write "GC = {"
    314    for name, causes in pairs(gc_caused) do
    315       out:write("['", name, "'] = {")
    316       for i = 1, #causes do out:write ("'", causes[i], "';") end
    317       out:write("};\n")
    318    end
    319    out:write "}"
    320    out:close()
    321 
    322    log ("** GCSuspects generated for %s", arch)
    323 end
    324 
    325 --------------------------------------------------------------------------------
    326 -- Analysis
    327 
    328 local function CheckCorrectnessForArch(arch)
    329    local files = FilesForArch(arch)
    330    local cfg = ARCHITECTURES[arch]
    331 
    332    if not FLAGS.reuse_gcsuspects then
    333       GenerateGCSuspects(arch, files, cfg)
    334    end
    335 
    336    local processed_files = 0
    337    local errors_found = false
    338    local function SearchForErrors(filename, lines)
    339       processed_files = processed_files + 1
    340       for l in lines do
    341          errors_found = errors_found or
    342             l:match "^[^:]+:%d+:%d+:" or
    343             l:match "error" or
    344             l:match "warning"
    345          print(l)
    346       end
    347    end
    348 
    349    log("** Searching for evaluation order problems%s for %s",
    350        FLAGS.dead_vars and " and dead variables" or "",
    351        arch)
    352    local plugin_args
    353    if FLAGS.dead_vars then plugin_args = { "--dead-vars" } end
    354    InvokeClangPluginForEachFile(files,
    355                                 cfg:extend { plugin = "find-problems",
    356                                              plugin_args = plugin_args },
    357                                 SearchForErrors)
    358    log("** Done processing %d files. %s",
    359        processed_files,
    360        errors_found and "Errors found" or "No errors found")
    361 
    362    return errors_found
    363 end
    364 
    365 local function SafeCheckCorrectnessForArch(arch)
    366    local status, errors = pcall(CheckCorrectnessForArch, arch)
    367    if not status then
    368       print(string.format("There was an error: %s", errors))
    369       errors = true
    370    end
    371    return errors
    372 end
    373 
    374 local errors = false
    375 
    376 for _, arch in ipairs(ARCHS) do
    377    if not ARCHITECTURES[arch] then
    378       error ("Unknown arch: " .. arch)
    379    end
    380 
    381    errors = SafeCheckCorrectnessForArch(arch, report) or errors
    382 end
    383 
    384 os.exit(errors and 1 or 0)
    385