Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add pass for generating API methods with a function pointer parameter #303

Merged
merged 3 commits into from
Jun 27, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/generator/context.jl
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,9 @@ function create_context(headers::Vector, args::Vector=String[], options::Dict=Di
push!(ctx.passes, Codegen())
push!(ctx.passes, CodegenMacro())
# push!(ctx.passes, CodegenPostprocessing())
if get(general_options, "add_fptr_methods", false)
push!(ctx.passes, AddFPtrMethods())
end
if get(general_options, "auto_mutability", false)
push!(ctx.passes, TweakMutability())
end
Expand Down
36 changes: 36 additions & 0 deletions src/generator/passes.jl
Original file line number Diff line number Diff line change
Expand Up @@ -756,6 +756,42 @@ function (x::TweakMutability)(dag::ExprDAG, options::Dict)
return dag
end

"""
AddFPtrMethods <: AbstractPass
This pass adds a method definition for each function prototype method which `ccall`s into a library.

The generated method allows the use of a function pointer to `ccall` into directly, instead
of relying on a library to give the pointer via a symbol look up. This is useful for libraries that
use runtime loaders to dynamically resolve function pointers for API calls.
"""
struct AddFPtrMethods <: AbstractPass end

function (::AddFPtrMethods)(dag::ExprDAG, options::Dict)
codegen_options = get(options, "codegen", Dict())
use_ccall_macro = get(codegen_options, "use_ccall_macro", false)
for node in dag.nodes
node.type isa FunctionProto || continue
ex = copy(first(node.exprs))
call = ex.args[1]
push!(call.args, :fptr)
body = ex.args[findfirst(x -> Base.is_expr(x, :block), ex.args)]
stmt_idx = if use_ccall_macro
findfirst(x -> Base.is_expr(x, :macrocall) && x.args[1] == Symbol("@ccall"), body.args)
else
findfirst(x -> Base.is_expr(x, :call) && x.args[1] == :ccall, body.args)
end
stmt = body.args[stmt_idx]
if use_ccall_macro
typeassert = stmt.args[findfirst(x -> Base.is_expr(x, :(::)), stmt.args)]
call = typeassert.args[findfirst(x -> Base.is_expr(x, :call), typeassert.args)]
call.args[1] = Expr(:$, :fptr)
else
stmt.args[2] = :fptr
end
push!(node.exprs, ex)
end
end

const DEFAULT_AUDIT_FUNCTIONS = [
audit_library_name,
sanity_check,
Expand Down