├── example ├── test │ ├── test_helper.exs │ └── demo_test.exs ├── .formatter.exs ├── mix.lock ├── lib │ └── demo │ │ ├── application.ex │ │ ├── nif.ex │ │ └── demo.ex ├── README.md ├── mix.exs ├── .gitignore ├── Makefile └── c_src │ └── demo_nif.cpp ├── .formatter.exs ├── lib ├── nif_call.ex ├── nif.ex ├── mix │ └── tasks │ │ └── nif_call.put_header.ex └── runner.ex ├── .gitignore ├── mix.exs ├── mix.lock ├── .github └── workflows │ └── ci.yml ├── README.md ├── nif_call.h └── LICENSE /example/test/test_helper.exs: -------------------------------------------------------------------------------- 1 | ExUnit.start() 2 | -------------------------------------------------------------------------------- /example/test/demo_test.exs: -------------------------------------------------------------------------------- 1 | defmodule DemoTest do 2 | use ExUnit.Case 3 | doctest Demo, except: [iterate: 2] 4 | end 5 | -------------------------------------------------------------------------------- /.formatter.exs: -------------------------------------------------------------------------------- 1 | # Used by "mix format" 2 | [ 3 | inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] 4 | ] 5 | -------------------------------------------------------------------------------- /example/.formatter.exs: -------------------------------------------------------------------------------- 1 | # Used by "mix format" 2 | [ 3 | inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"] 4 | ] 5 | -------------------------------------------------------------------------------- /lib/nif_call.ex: -------------------------------------------------------------------------------- 1 | defmodule NifCall do 2 | def run(name, to_be_called, fun) do 3 | tag = NifCall.Runner.register(name, to_be_called) 4 | 5 | fun.(tag) 6 | end 7 | end 8 | -------------------------------------------------------------------------------- /example/mix.lock: -------------------------------------------------------------------------------- 1 | %{ 2 | "elixir_make": {:hex, :elixir_make, "0.9.0", "6484b3cd8c0cee58f09f05ecaf1a140a8c97670671a6a0e7ab4dc326c3109726", [:mix], [], "hexpm", "db23d4fd8b757462ad02f8aa73431a426fe6671c80b200d9710caf3d1dd0ffdb"}, 3 | } 4 | -------------------------------------------------------------------------------- /lib/nif.ex: -------------------------------------------------------------------------------- 1 | defmodule NifCall.NIF do 2 | @moduledoc false 3 | 4 | defmacro __using__(using_opts) do 5 | funcname = Keyword.get(using_opts, :on_evaluated, :nif_call_evaluated) 6 | 7 | quote do 8 | def unquote(:"#{funcname}")(_from_ref, _results), do: :erlang.nif_error(:not_loaded) 9 | end 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /example/lib/demo/application.ex: -------------------------------------------------------------------------------- 1 | defmodule Demo.Application do 2 | @moduledoc false 3 | 4 | use Application 5 | 6 | @impl true 7 | def start(_type, _args) do 8 | children = [ 9 | {NifCall.Runner, 10 | runner_opts: [nif_module: Demo.NIF, on_evaluated: :nif_call_evaluated], name: Demo.Runner} 11 | ] 12 | 13 | opts = [strategy: :one_for_one, name: Demo.Supervisor] 14 | Supervisor.start_link(children, opts) 15 | end 16 | end 17 | -------------------------------------------------------------------------------- /example/README.md: -------------------------------------------------------------------------------- 1 | # NifCall 2 | 3 | **TODO: Add description** 4 | 5 | ## Installation 6 | 7 | If [available in Hex](https://hex.pm/docs/publish), the package can be installed 8 | by adding `nif_call` to your list of dependencies in `mix.exs`: 9 | 10 | ```elixir 11 | def deps do 12 | [ 13 | {:nif_call, "~> 0.2.0"} 14 | ] 15 | end 16 | ``` 17 | 18 | Documentation can be generated with [ExDoc](https://github.com/elixir-lang/ex_doc) 19 | and published on [HexDocs](https://hexdocs.pm). Once published, the docs can 20 | be found at . 21 | 22 | -------------------------------------------------------------------------------- /example/mix.exs: -------------------------------------------------------------------------------- 1 | defmodule Demo.MixProject do 2 | use Mix.Project 3 | 4 | def project do 5 | [ 6 | app: :demo, 7 | version: "0.1.0", 8 | elixir: "~> 1.14", 9 | start_permanent: Mix.env() == :prod, 10 | deps: deps(), 11 | compilers: [:elixir_make] ++ Mix.compilers() 12 | ] 13 | end 14 | 15 | def application do 16 | [ 17 | extra_applications: [:logger], 18 | mod: {Demo.Application, []} 19 | ] 20 | end 21 | 22 | defp deps do 23 | [ 24 | {:elixir_make, "~> 0.9", runtime: false}, 25 | {:nif_call, path: ".."} 26 | ] 27 | end 28 | end 29 | -------------------------------------------------------------------------------- /example/lib/demo/nif.ex: -------------------------------------------------------------------------------- 1 | defmodule Demo.NIF do 2 | @moduledoc false 3 | 4 | use NifCall.NIF, on_evaluated: :nif_call_evaluated 5 | 6 | @on_load :load_nif 7 | def load_nif do 8 | nif_file = ~c"#{:code.priv_dir(:demo)}/nif" 9 | 10 | case :erlang.load_nif(nif_file, 0) do 11 | :ok -> :ok 12 | {:error, {:reload, _}} -> :ok 13 | {:error, reason} -> IO.puts("Failed to load nif: #{inspect(reason)}") 14 | end 15 | end 16 | 17 | def add_one(_arg, _tag), do: :erlang.nif_error(:not_loaded) 18 | def iterate(_arg, _tag), do: :erlang.nif_error(:not_loaded) 19 | def callback_throws(_arg, _tag), do: :erlang.nif_error(:not_loaded) 20 | end 21 | -------------------------------------------------------------------------------- /example/.gitignore: -------------------------------------------------------------------------------- 1 | # The directory Mix will write compiled artifacts to. 2 | /_build/ 3 | 4 | # If you run "mix test --cover", coverage assets end up here. 5 | /cover/ 6 | 7 | # The directory Mix downloads your dependencies sources to. 8 | /deps/ 9 | 10 | # Where third-party dependencies like ExDoc output generated docs. 11 | /doc/ 12 | 13 | # Ignore .fetch files in case you like to edit your project deps locally. 14 | /.fetch 15 | 16 | # If the VM crashes, it generates a dump, let's ignore it too. 17 | erl_crash.dump 18 | 19 | # Also ignore archive artifacts (built via "mix archive.build"). 20 | *.ez 21 | 22 | # Ignore package tarball (built via "mix hex.build"). 23 | demo-*.tar 24 | 25 | # Temporary files, for example, from tests. 26 | /tmp/ 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # The directory Mix will write compiled artifacts to. 2 | /_build/ 3 | 4 | # If you run "mix test --cover", coverage assets end up here. 5 | /cover/ 6 | 7 | # The directory Mix downloads your dependencies sources to. 8 | /deps/ 9 | 10 | # Where third-party dependencies like ExDoc output generated docs. 11 | /doc/ 12 | 13 | # Ignore .fetch files in case you like to edit your project deps locally. 14 | /.fetch 15 | 16 | # If the VM crashes, it generates a dump, let's ignore it too. 17 | erl_crash.dump 18 | 19 | # Also ignore archive artifacts (built via "mix archive.build"). 20 | *.ez 21 | 22 | # Ignore package tarball (built via "mix hex.build"). 23 | nif_call-*.tar 24 | 25 | # Temporary files, for example, from tests. 26 | /tmp/ 27 | 28 | .DS_Store 29 | 30 | .elixir_ls 31 | 32 | /example/c_src/nif_call.h 33 | -------------------------------------------------------------------------------- /example/Makefile: -------------------------------------------------------------------------------- 1 | PRIV_DIR = $(MIX_APP_PATH)/priv 2 | BUILD_DIR = $(MIX_APP_PATH)/build 3 | NIF_SO = $(PRIV_DIR)/nif.so 4 | 5 | CFLAGS = -fPIC -I$(ERTS_INCLUDE_DIR) -Wall -std=c++17 -O3 6 | LDFLAGS = -shared 7 | 8 | UNAME_S = $(shell uname -s) 9 | ifeq ($(UNAME_S), Darwin) 10 | LDFLAGS += -flat_namespace -undefined dynamic_lookup 11 | endif 12 | 13 | SOURCES = c_src/demo_nif.cpp 14 | OBJECTS = $(patsubst c_src/%.cpp,$(BUILD_DIR)/%.o,$(SOURCES)) 15 | 16 | all: $(NIF_SO) 17 | @ echo > /dev/null 18 | 19 | $(PRIV_DIR): 20 | @ mkdir -p $(PRIV_DIR) 21 | 22 | $(BUILD_DIR): 23 | @ mkdir -p $(BUILD_DIR) 24 | 25 | $(BUILD_DIR)/%.o: c_src/%.cpp 26 | $(CXX) $(CFLAGS) -c $< -o $@ 27 | 28 | $(NIF_SO): $(PRIV_DIR) $(BUILD_DIR) $(OBJECTS) 29 | $(CXX) $(CFLAGS) $(OBJECTS) -o $(NIF_SO) $(LDFLAGS) 30 | 31 | clean: 32 | @rm -rf $(PRIV_DIR) 33 | @rm -rf $(BUILD_DIR) 34 | 35 | .PHONY: all clean 36 | -------------------------------------------------------------------------------- /mix.exs: -------------------------------------------------------------------------------- 1 | defmodule NifCall.MixProject do 2 | use Mix.Project 3 | 4 | @app :nif_call 5 | @version "0.2.0" 6 | @github_url "https://github.com/cocoa-xu/nif_call" 7 | 8 | def project do 9 | [ 10 | app: @app, 11 | version: @version, 12 | elixir: "~> 1.14", 13 | start_permanent: Mix.env() == :prod, 14 | deps: deps(), 15 | package: package(), 16 | docs: docs(), 17 | description: "Call Erlang/Elixir functions from NIF and use the returned value in NIF." 18 | ] 19 | end 20 | 21 | def application do 22 | [ 23 | extra_applications: [:logger] 24 | ] 25 | end 26 | 27 | defp docs do 28 | [ 29 | source_ref: "v#{@version}", 30 | source_url: @github_url, 31 | extras: [ 32 | "README.md" 33 | ] 34 | ] 35 | end 36 | 37 | defp deps do 38 | [ 39 | {:ex_doc, ">= 0.0.0", only: :docs, runtime: false} 40 | ] 41 | end 42 | 43 | defp package() do 44 | [ 45 | name: to_string(@app), 46 | files: ~w( 47 | lib 48 | mix.exs 49 | nif_call.h 50 | README* 51 | LICENSE* 52 | ), 53 | licenses: ["Apache-2.0"], 54 | links: %{"GitHub" => @github_url} 55 | ] 56 | end 57 | end 58 | -------------------------------------------------------------------------------- /lib/mix/tasks/nif_call.put_header.ex: -------------------------------------------------------------------------------- 1 | defmodule Mix.Tasks.NifCall.PutHeader do 2 | @shortdoc "Put bundled nif_call.h header file into the project" 3 | 4 | @moduledoc """ 5 | A task responsible for putting the bundled nif_call.h header file into the project. 6 | """ 7 | 8 | use Mix.Task 9 | 10 | require Logger 11 | 12 | @switches [ 13 | dir: :string, 14 | overwrite: :boolean 15 | ] 16 | 17 | @nif_call_h File.read!(Path.expand(Path.join([__DIR__, "../../..", "nif_call.h"]))) 18 | @impl true 19 | def run(flags) when is_list(flags) do 20 | {options, _args, _invalid} = OptionParser.parse(flags, strict: @switches) 21 | target_dir = Keyword.get(options, :dir, "c_src") 22 | overwrite? = Keyword.get(options, :overwrite, false) 23 | 24 | filepath = Path.join(target_dir, "nif_call.h") 25 | exists? = File.exists?(filepath) 26 | 27 | cond do 28 | exists? && !overwrite? -> 29 | Logger.warning( 30 | "nif_call.h already exists in #{target_dir}, please use --overwrite to overwrite the existing file." 31 | ) 32 | 33 | exists? -> 34 | Logger.info( 35 | "nif_call.h already exists in #{target_dir}, overwriting it with the bundled nif_call.h." 36 | ) 37 | 38 | true -> 39 | File.write!(filepath, @nif_call_h) 40 | Logger.info("nif_call.h has been put into #{target_dir}.") 41 | end 42 | 43 | :ok 44 | end 45 | end 46 | -------------------------------------------------------------------------------- /example/lib/demo/demo.ex: -------------------------------------------------------------------------------- 1 | defmodule Demo do 2 | @moduledoc false 3 | 4 | @doc """ 5 | Add 1 to the `value` in NIF and send the intermediate result to 6 | Elixir for further processing using the `callback` function. 7 | 8 | The result of the `callback` function is returned as the final result. 9 | 10 | ## Example 11 | 12 | iex> Demo.add_one(1, fn result -> result * 2 end) 13 | 4 14 | 15 | ## Example when the callback function throws an exception 16 | 17 | iex> Demo.add_one(1, fn val -> 18 | ...> throw {val, :oh_nooooo} 19 | ...> end) 20 | {:throw, {2, :oh_nooooo}} 21 | 22 | ## Examples when the callback function raises an exception 23 | 24 | iex> Demo.add_one(1, fn val -> 25 | ...> raise RuntimeError, "cannot use this value: \#{val}" 26 | ...> end) 27 | {:error, %RuntimeError{message: "cannot use this value: 2"}} 28 | 29 | """ 30 | def add_one(value, callback) do 31 | NifCall.run(Demo.Runner, callback, fn tag -> 32 | Demo.NIF.add_one(value, tag) 33 | end) 34 | end 35 | 36 | @doc """ 37 | Send an initial value to NIF and NIF will send intermediate results to 38 | the `callback` function in Elixir. This function returns either 39 | 40 | - `{:cont, new_value}` to continue the iteration in NIF with the new value 41 | - `{:done, result}` to indicate the NIF to stop the iteration and return the final result 42 | 43 | In this demo, the NIF function will multiply the value by 2 in each iteration, and 44 | we further add 1 to every intermediate result in the callback unless the intermediate 45 | result is greater than 42. 46 | 47 | ## Examples 48 | 49 | iex> Demo.iterate(1, fn 50 | ...> val when val <= 42 -> 51 | ...> {:cont, val + 1} 52 | ...> val -> 53 | ...> {:done, val} 54 | ...> end) 55 | 62 56 | 57 | """ 58 | def iterate(initial_value, callback) do 59 | NifCall.run(Demo.Runner, callback, fn tag -> 60 | Demo.NIF.iterate(initial_value, tag) 61 | end) 62 | end 63 | end 64 | -------------------------------------------------------------------------------- /mix.lock: -------------------------------------------------------------------------------- 1 | %{ 2 | "earmark_parser": {:hex, :earmark_parser, "1.4.41", "ab34711c9dc6212dda44fcd20ecb87ac3f3fce6f0ca2f28d4a00e4154f8cd599", [:mix], [], "hexpm", "a81a04c7e34b6617c2792e291b5a2e57ab316365c2644ddc553bb9ed863ebefa"}, 3 | "elixir_make": {:hex, :elixir_make, "0.9.0", "6484b3cd8c0cee58f09f05ecaf1a140a8c97670671a6a0e7ab4dc326c3109726", [:mix], [], "hexpm", "db23d4fd8b757462ad02f8aa73431a426fe6671c80b200d9710caf3d1dd0ffdb"}, 4 | "ex_doc": {:hex, :ex_doc, "0.35.1", "de804c590d3df2d9d5b8aec77d758b00c814b356119b3d4455e4b8a8687aecaf", [:mix], [{:earmark_parser, "~> 1.4.39", [hex: :earmark_parser, repo: "hexpm", optional: false]}, {:makeup_c, ">= 0.1.0", [hex: :makeup_c, repo: "hexpm", optional: true]}, {:makeup_elixir, "~> 0.14 or ~> 1.0", [hex: :makeup_elixir, repo: "hexpm", optional: false]}, {:makeup_erlang, "~> 0.1 or ~> 1.0", [hex: :makeup_erlang, repo: "hexpm", optional: false]}, {:makeup_html, ">= 0.1.0", [hex: :makeup_html, repo: "hexpm", optional: true]}], "hexpm", "2121c6402c8d44b05622677b761371a759143b958c6c19f6558ff64d0aed40df"}, 5 | "makeup": {:hex, :makeup, "1.2.1", "e90ac1c65589ef354378def3ba19d401e739ee7ee06fb47f94c687016e3713d1", [:mix], [{:nimble_parsec, "~> 1.4", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "d36484867b0bae0fea568d10131197a4c2e47056a6fbe84922bf6ba71c8d17ce"}, 6 | "makeup_elixir": {:hex, :makeup_elixir, "1.0.0", "74bb8348c9b3a51d5c589bf5aebb0466a84b33274150e3b6ece1da45584afc82", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}, {:nimble_parsec, "~> 1.2.3 or ~> 1.3", [hex: :nimble_parsec, repo: "hexpm", optional: false]}], "hexpm", "49159b7d7d999e836bedaf09dcf35ca18b312230cf901b725a64f3f42e407983"}, 7 | "makeup_erlang": {:hex, :makeup_erlang, "1.0.1", "c7f58c120b2b5aa5fd80d540a89fdf866ed42f1f3994e4fe189abebeab610839", [:mix], [{:makeup, "~> 1.0", [hex: :makeup, repo: "hexpm", optional: false]}], "hexpm", "8a89a1eeccc2d798d6ea15496a6e4870b75e014d1af514b1b71fa33134f57814"}, 8 | "nimble_parsec": {:hex, :nimble_parsec, "1.4.0", "51f9b613ea62cfa97b25ccc2c1b4216e81df970acd8e16e8d1bdc58fef21370d", [:mix], [], "hexpm", "9c565862810fb383e9838c1dd2d7d2c437b3d13b267414ba6af33e50d2d1cf28"}, 9 | } 10 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | 9 | jobs: 10 | macos: 11 | name: macOS (${{ matrix.elixir }}, ${{ matrix.otp }}) 12 | runs-on: macos-14 13 | defaults: 14 | run: 15 | working-directory: example 16 | env: 17 | MIX_ENV: test 18 | strategy: 19 | fail-fast: false 20 | matrix: 21 | elixir: ["1.15.4", "1.16.2"] 22 | otp: ["25.3.2.15"] 23 | include: 24 | - elixir: "1.16.2" 25 | lint: true 26 | 27 | steps: 28 | - name: Checkout 29 | uses: actions/checkout@v4 30 | 31 | - name: Setup Elixir and Erlang 32 | id: setup 33 | run: | 34 | curl -fsSO https://elixir-lang.org/install.sh 35 | sh install.sh elixir@${{ matrix.elixir }} otp@${{ matrix.otp }} 36 | 37 | OTP_VERSION="${{ matrix.otp }}" 38 | OTP_MAJOR="${OTP_VERSION%%.*}" 39 | export OTP_PATH=$HOME/.elixir-install/installs/otp/${OTP_VERSION}/bin 40 | export ELIXIR_PATH=$HOME/.elixir-install/installs/elixir/${{ matrix.elixir }}-otp-${OTP_MAJOR}/bin 41 | 42 | echo "path=${OTP_PATH}:${ELIXIR_PATH}" >> $GITHUB_OUTPUT 43 | echo "${OTP_PATH}" >> $GITHUB_PATH 44 | echo "${ELIXIR_PATH}" >> $GITHUB_PATH 45 | 46 | - name: Setup Mix 47 | run: | 48 | mix local.hex --force 49 | mix local.rebar --force 50 | 51 | - name: Install dependencies 52 | run: | 53 | export PATH="${{ steps.setup.outputs.path }}:${PATH}" 54 | mix deps.get 55 | 56 | - name: Compile and check warnings 57 | run: | 58 | export PATH="${{ steps.setup.outputs.path }}:${PATH}" 59 | mix nif_call.put_header --overwrite 60 | mix compile --warnings-as-errors 61 | 62 | - name: Check formatting 63 | if: ${{ matrix.lint }} 64 | run: | 65 | export PATH="${{ steps.setup.outputs.path }}:${PATH}" 66 | mix format --check-formatted 67 | 68 | - name: Run tests 69 | run: | 70 | export PATH="${{ steps.setup.outputs.path }}:${PATH}" 71 | mix test --warnings-as-errors 72 | -------------------------------------------------------------------------------- /lib/runner.ex: -------------------------------------------------------------------------------- 1 | defmodule NifCall.Runner do 2 | use GenServer 3 | 4 | defstruct [:nif_module, :on_evaluated, :refs, :monitors] 5 | 6 | def start_link(opts) do 7 | GenServer.start_link(__MODULE__, opts[:runner_opts], opts) 8 | end 9 | 10 | def register(name, function) when is_function(function, 1) do 11 | GenServer.call(name, {:register, self(), function}, :infinity) 12 | end 13 | 14 | def unregister(name, {_pid, ref}) do 15 | GenServer.call(name, {:unregister, ref}, :infinity) 16 | end 17 | 18 | def init(opts) do 19 | opts = Keyword.validate!(opts, [:nif_module, on_evaluated: :nif_call_evaluated]) 20 | 21 | {:ok, 22 | %__MODULE__{nif_module: opts[:nif_module], on_evaluated: opts[:on_evaluated], refs: %{}, monitors: %{}}} 23 | end 24 | 25 | def handle_call({:register, owner, function}, _from, state) do 26 | ref = Process.monitor(owner) 27 | {:reply, {self(), ref}, %{state | refs: Map.put(state.refs, ref, function)}} 28 | end 29 | 30 | def handle_call({:unregister, ref}, _from, state) do 31 | Process.demonitor(ref, [:flush]) 32 | {:reply, :ok, %{state | refs: Map.delete(state.refs, ref)}} 33 | end 34 | 35 | def handle_info({:DOWN, ref, _, _, _}, state) when is_map_key(state.monitors, ref) do 36 | {:noreply, %{state | refs: Map.delete(state.refs, state.monitors[ref]), monitors: Map.delete(state.monitors, ref)}} 37 | end 38 | 39 | def handle_info({:DOWN, ref, _, _, _}, state) do 40 | {:noreply, %{state | refs: Map.delete(state.refs, ref)}} 41 | end 42 | 43 | def handle_info({:execute, resource, ref, args}, state) do 44 | function = Map.fetch!(state.refs, ref) 45 | 46 | task = 47 | Task.async(fn -> 48 | try do 49 | apply(state.nif_module, state.on_evaluated, [ 50 | resource, 51 | {:ok, apply(function, List.wrap(args))} 52 | ]) 53 | catch 54 | kind, reason -> 55 | apply(state.nif_module, state.on_evaluated, [resource, {kind, reason}]) 56 | end 57 | end) 58 | 59 | {:noreply, %{state | monitors: Map.put(state.monitors, task.ref, ref)}} 60 | end 61 | 62 | def handle_info({{:eval, resource}, _, _, _, reason}, state) do 63 | if reason != :normal do 64 | apply(state.nif_module, :nif_call_evaluated, [resource, {:exit, reason}]) 65 | end 66 | 67 | {:noreply, state} 68 | end 69 | 70 | def handle_info({ref, _}, state) when is_map_key(state.monitors, ref) do 71 | {:noreply, state} 72 | end 73 | end 74 | -------------------------------------------------------------------------------- /example/c_src/demo_nif.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define NIF_CALL_NAMESPACE demo 5 | #define NIF_CALL_IMPLEMENTATION 6 | #include "nif_call.h" 7 | 8 | // ------ demo 1 start ------ 9 | 10 | static ERL_NIF_TERM add_one(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { 11 | ErlNifSInt64 a; 12 | ERL_NIF_TERM tag = argv[1]; 13 | 14 | if (!enif_get_int64(env, argv[0], &a)) return enif_make_badarg(env); 15 | ERL_NIF_TERM result_term = enif_make_int64(env, a + 1); 16 | 17 | NifCallResult result = make_nif_call(env, tag, result_term); 18 | return result.is_ok() ? result.get_value() : enif_make_tuple2(env, result.get_kind(), result.get_err()); 19 | } 20 | 21 | // ------ demo 1 end ------ 22 | 23 | // ------ demo 2 start ------ 24 | 25 | static ERL_NIF_TERM kAtomCont; 26 | static ERL_NIF_TERM kAtomDone; 27 | 28 | static ERL_NIF_TERM iterate(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { 29 | ErlNifSInt64 a; 30 | ERL_NIF_TERM iterate_val = argv[0]; 31 | ERL_NIF_TERM tag = argv[1]; 32 | 33 | while (true) { 34 | if (!enif_get_int64(env, iterate_val, &a)) return enif_make_badarg(env); 35 | ERL_NIF_TERM val = enif_make_int64(env, a * 2); 36 | 37 | NifCallResult result = make_nif_call(env, tag, val); 38 | if (!result.is_ok()) return enif_make_tuple2(env, result.get_kind(), result.get_err()); 39 | 40 | ERL_NIF_TERM callback_result = result.get_value(); 41 | const ERL_NIF_TERM *tuple_elements = NULL; 42 | int tuple_arity = 0; 43 | if (!enif_get_tuple(env, callback_result, &tuple_arity, &tuple_elements) || tuple_arity != 2) return enif_make_badarg(env); 44 | 45 | if (enif_compare(tuple_elements[0], kAtomCont) == 0) { 46 | iterate_val = tuple_elements[1]; 47 | } else if (enif_compare(tuple_elements[0], kAtomDone) == 0) { 48 | return enif_make_copy(env, tuple_elements[1]); 49 | } else { 50 | return enif_make_badarg(env); 51 | } 52 | } 53 | } 54 | 55 | // ------ demo 2 end ------ 56 | 57 | static int on_load(ErlNifEnv *env, void **, ERL_NIF_TERM) { 58 | // constants for demo 2 59 | kAtomCont = enif_make_atom(env, "cont"); 60 | kAtomDone = enif_make_atom(env, "done"); 61 | 62 | // initialize nif_call 63 | return nif_call_onload(env); 64 | } 65 | 66 | static ErlNifFunc nif_functions[] = { 67 | // NIF functions that calls Elixir functions have to be marked as dirty 68 | // either ERL_NIF_DIRTY_JOB_CPU_BOUND or ERL_NIF_DIRTY_JOB_IO_BOUND 69 | {"add_one", 2, add_one, ERL_NIF_DIRTY_JOB_CPU_BOUND}, 70 | {"iterate", 2, iterate, ERL_NIF_DIRTY_JOB_CPU_BOUND}, 71 | 72 | // inject nif_call functions 73 | // `nif_call_evaluated` is the name of the callback function that will be called by nif_call 74 | NIF_CALL_NIF_FUNC(nif_call_evaluated), 75 | }; 76 | 77 | ERL_NIF_INIT(Elixir.Demo.NIF, nif_functions, on_load, NULL, NULL, NULL); 78 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # nif_call 2 | 3 | [![Hex.pm](https://img.shields.io/hexpm/v/nif_call.svg?style=flat&color=blue)](https://hex.pm/packages/nif_call) 4 | 5 | Call Erlang/Elixir functions from NIF. 6 | 7 | ## Usage 8 | 9 | ### 1. Add `nif_call` as a dependency 10 | 11 | Add `nif_call` as a dependency in your `mix.exs` file. 12 | 13 | ```elixir 14 | defp deps do 15 | [ 16 | {:nif_call, "~> 0.2"} 17 | ] 18 | end 19 | ``` 20 | 21 | ### 2. Get the header file 22 | 23 | It's recommended to use the `nif_call`'s mix task to get the bundled header file. Assuming you're currently in the root directory of your project, run the following command: 24 | 25 | ```bash 26 | mix nif_call.put_header 27 | ``` 28 | 29 | By default, the header file will be put in the `c_src` directory. It may look like this: 30 | 31 | ```bash 32 | . 33 | ├── Makefile 34 | ├── c_src 35 | │ ├── demo_nif.cpp 36 | │ └── nif_call.h <-- From this repository 37 | ├── lib 38 | │ └── demo 39 | │ ├── application.ex 40 | │ └── demo.ex 41 | ├── mix.exs 42 | └── mix.lock 43 | ``` 44 | 45 | You can also change the directory by passing the `--dir` option. 46 | 47 | ```bash 48 | mix nif_call.put_header --dir lib/nif_call 49 | ``` 50 | 51 | If there's already a `nif_call.h` file in the target directory, you may want to overwrite it by passing the `--overwrite` option. 52 | 53 | ```bash 54 | mix nif_call.put_header --overwrite 55 | ``` 56 | 57 | ### 3. Add runner processes to your supervision tree 58 | 59 | In applications that use `nif_call`, you need to add runner processes to the supervision tree. The runner processes are responsible for evaluating the Elixir functions called from NIF. In this demo project, we will add a runner process named `Demo.Runner` by adding the following code to the `lib/demo/application.ex` file. 60 | 61 | ```elixir 62 | {NifCall.Runner, runner_opts: [nif_module: Demo.NIF, on_evaluated: :nif_call_evaluated], name: Demo.Runner} 63 | ``` 64 | 65 | The `application.ex` file should look like this: 66 | 67 | ```elixir 68 | defmodule Demo.Application do 69 | @moduledoc false 70 | 71 | use Application 72 | 73 | @impl true 74 | def start(_type, _args) do 75 | children = [ 76 | {NifCall.Runner, 77 | runner_opts: [nif_module: Demo.NIF, on_evaluated: :nif_call_evaluated], name: Demo.Runner} 78 | ] 79 | 80 | opts = [strategy: :one_for_one, name: Demo.Supervisor] 81 | Supervisor.start_link(children, opts) 82 | end 83 | end 84 | ``` 85 | 86 | 87 | `Demo.NIF` is the module that contains your NIF functions. The `on_evaluated` option is the name of the callback function that will be called by `nif_call` to send the evaluated result back to the caller. The default name is `nif_call_evaluated`. 88 | 89 | To send the evaluated result back to the caller, `nif_call` needs to inject one NIF function to do that. 90 | 91 | ```elixir 92 | # lib/demo/nif.ex 93 | defmodule Demo.NIF do 94 | use NifCall.NIF 95 | end 96 | ``` 97 | 98 | If you have changed the name of the callback function for the runner process, you need to specify it in the `on_evaluated` option. 99 | 100 | ```elixir 101 | # lib/demo/nif.ex 102 | defmodule Demo.NIF do 103 | use NifCall.NIF, on_evaluated: :my_evaluated 104 | end 105 | ``` 106 | 107 | ### 4. Prepare C code 108 | 109 | In your NIF code, include `nif_call.h` and define the `NIF_CALL_IMPLEMENTATION` macro before including it. 110 | 111 | ```c 112 | // c_src/demo_nif.cpp 113 | #define NIF_CALL_IMPLEMENTATION 114 | #include "nif_call.h" 115 | ``` 116 | 117 | And remember to initialize nif_call in the `onload` function. 118 | 119 | ```c 120 | // c_src/demo_nif.cpp 121 | static int on_load(ErlNifEnv *env, void **, ERL_NIF_TERM) { 122 | // initialize nif_call 123 | return nif_call_onload(env); 124 | } 125 | ``` 126 | 127 | Lastly, inject the NIF function: 128 | 129 | ```c 130 | // c_src/demo_nif.cpp 131 | static ErlNifFunc nif_functions[] = { 132 | // ... your other NIF functions 133 | 134 | // inject nif_call functions 135 | // `nif_call_evaluated` is the name of the callback function that will be called by nif_call 136 | NIF_CALL_NIF_FUNC(nif_call_evaluated), 137 | 138 | // of course, you can change the name of the callback function 139 | // but remember to change it in the Elixir code as well 140 | // NIF_CALL_NIF_FUNC(my_evaluated), 141 | }; 142 | ``` 143 | 144 | ### 5. Call Erlang/Elixir functions from NIF 145 | 146 | Let's try to implement a simple function that adds 1 to the given value and sends the intermediate result to Elixir for further processing. The result of the Elixir callback function is returned as the final result. 147 | 148 | Firstly, implement the `add_one` function in the Elixir code. 149 | 150 | ```elixir 151 | # lib/demo/demo.ex 152 | defmodule Demo do 153 | @doc """ 154 | Add 1 to the `value` in NIF and send the intermediate result to 155 | Elixir for further processing using the `callback` function. 156 | 157 | The result of the `callback` function is returned as the final result. 158 | 159 | ## Examples 160 | 161 | iex> Demo.add_one(1, fn result -> result * 2 end) 162 | 4 163 | 164 | """ 165 | def add_one(value, callback) do 166 | # remember to change the name of the Evaluator module if you have changed it 167 | # and pass both the evaluator and the callback function to the NIF 168 | evaluator = Process.whereis(Demo.Evaluator) 169 | Demo.NIF.add_one(value, evaluator, callback) 170 | end 171 | def add_one(value, callback) do 172 | # Use `NifCall.run/3` to call the NIF function 173 | # 174 | # - The second argument is the callback function that will be called from the NIF 175 | # 176 | # - The third argument is the function that can invoke somes NIF functions, 177 | # this is where you normally call the NIF function 178 | # 179 | # notice that the third argument is a function that takes a `tag` as an argument 180 | # the `tag` is used as a reference to the callback function in your `Demo.Runner` process 181 | NifCall.run(Demo.Runner, callback, fn tag -> 182 | Demo.NIF.add_one(value, tag) 183 | end) 184 | end 185 | end 186 | ``` 187 | 188 | After that, implement the `add_one` function in the NIF C code. 189 | 190 | ```c 191 | // c_src/demo_nif.cpp 192 | static ERL_NIF_TERM add_one(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { 193 | ErlNifSInt64 a; 194 | ERL_NIF_TERM tag = argv[1]; 195 | 196 | if (!enif_get_int64(env, argv[0], &a)) return enif_make_badarg(env); 197 | ERL_NIF_TERM result_term = enif_make_int64(env, a + 1); 198 | 199 | // send the intermediate result to Elixir for further processing 200 | // `make_nif_call` will return the result of the callback function 201 | // which is the final result in this case 202 | NifCallResult result = make_nif_call(env, tag, result_term); 203 | return result.is_ok() ? result.get_value() : enif_make_tuple2(env, enif_make_atom(env, "error"), result.get_err()); 204 | } 205 | ``` 206 | 207 | Most importantly, don't forget to add the NIF function to the `nif_functions` array, and **they have to be marked as dirty NIF functions**. 208 | 209 | ```c 210 | // c_src/demo_nif.cpp 211 | static ErlNifFunc nif_functions[] = { 212 | // ... your other NIF functions 213 | 214 | // inject nif_call functions 215 | NIF_CALL_NIF_FUNC(nif_call_evaluated), 216 | 217 | // add the NIF function 218 | // NIF functions that calls Elixir functions have to be marked as dirty 219 | // either ERL_NIF_DIRTY_JOB_CPU_BOUND or ERL_NIF_DIRTY_JOB_IO_BOUND 220 | {"add_one", 3, add_one, ERL_NIF_DIRTY_JOB_CPU_BOUND}, 221 | }; 222 | ``` 223 | 224 | Now, you can call the `add_one` function from Elixir. 225 | 226 | ```elixir 227 | iex> Demo.add_one(1, fn result -> result * 2 end) 228 | 4 229 | ``` 230 | 231 | Congratulations! You have successfully called an Elixir function from NIF. 232 | -------------------------------------------------------------------------------- /nif_call.h: -------------------------------------------------------------------------------- 1 | #ifndef NIF_CALL_H 2 | #define NIF_CALL_H 3 | 4 | #pragma once 5 | 6 | #include 7 | 8 | #ifdef NIF_CALL_NAMESPACE 9 | #define NIF_CALL_CAT(A, B) A##B 10 | #define NIF_CALL_SYMBOL(A, B) NIF_CALL_CAT(A, B) 11 | 12 | #define NifCallCallbackNifRes NIF_CALL_SYMBOL(NIF_CALL_NAMESPACE, NifCallCallbackNifRes) 13 | #define nif_call_onload NIF_CALL_SYMBOL(NIF_CALL_NAMESPACE, nif_call_onload) 14 | #define prepare_nif_call NIF_CALL_SYMBOL(NIF_CALL_NAMESPACE, prepare_nif_call) 15 | #define make_nif_call NIF_CALL_SYMBOL(NIF_CALL_NAMESPACE, make_nif_call) 16 | #define nif_call_evaluated NIF_CALL_SYMBOL(NIF_CALL_NAMESPACE, nif_call_evaluated) 17 | #define destruct_nif_call_res NIF_CALL_SYMBOL(NIF_CALL_NAMESPACE, destruct_nif_call_res) 18 | #endif 19 | 20 | #define NIF_CALL_NIF_FUNC(name) \ 21 | {#name, 2, nif_call_evaluated, 0} 22 | 23 | #ifndef NIF_CALL_IMPLEMENTATION 24 | 25 | struct NifCallCallbackNifRes; 26 | static int nif_call_onload(ErlNifEnv *env); 27 | static NifCallCallbackNifRes * prepare_nif_call(ErlNifEnv* env); 28 | static ERL_NIF_TERM make_nif_call(ErlNifEnv* caller_env, ERL_NIF_TERM tag, ERL_NIF_TERM args); 29 | static ERL_NIF_TERM nif_call_evaluated(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]); 30 | static void destruct_nif_call_res(ErlNifEnv *, void *obj); 31 | 32 | #else 33 | 34 | struct NifCallCallbackNifRes { 35 | static ErlNifResourceType *type; 36 | static ERL_NIF_TERM kAtomOK; 37 | static ERL_NIF_TERM kAtomError; 38 | static ERL_NIF_TERM kAtomNil; 39 | static ERL_NIF_TERM kAtomENOMEM; 40 | static ERL_NIF_TERM kAtomExecute; 41 | static ERL_NIF_TERM kAtomCallerEnv; 42 | static ERL_NIF_TERM kAtomNotTag; 43 | static ERL_NIF_TERM kAtomInvalidRunner; 44 | static ERL_NIF_TERM kAtomInvalidRunnerReply; 45 | static ERL_NIF_TERM kAtomRunnerIsDown; 46 | 47 | ErlNifEnv * msg_env; 48 | ErlNifMutex *mtx = NULL; 49 | ErlNifCond *cond = NULL; 50 | 51 | ERL_NIF_TERM return_value; 52 | bool return_value_set; 53 | }; 54 | 55 | struct NifCallResult { 56 | bool err; 57 | 58 | // `kind` can be one of these atoms: 59 | // - `ok` 60 | // - `error` 61 | // - `exit` 62 | // - `throw` 63 | ERL_NIF_TERM kind; 64 | ERL_NIF_TERM value; 65 | 66 | bool is_ok() { 67 | return !err; 68 | } 69 | 70 | ERL_NIF_TERM get_kind() { 71 | return kind; 72 | } 73 | 74 | ERL_NIF_TERM get_value() { 75 | return value; 76 | } 77 | 78 | ERL_NIF_TERM get_err() { 79 | return value; 80 | } 81 | 82 | static NifCallResult ok(ERL_NIF_TERM value) { 83 | NifCallResult res; 84 | res.err = false; 85 | res.value = value; 86 | return res; 87 | } 88 | 89 | static NifCallResult error(ERL_NIF_TERM value) { 90 | NifCallResult res; 91 | res.err = true; 92 | res.kind = NifCallCallbackNifRes::kAtomError; 93 | res.value = value; 94 | return res; 95 | } 96 | 97 | static NifCallResult error(ERL_NIF_TERM kind, ERL_NIF_TERM value) { 98 | NifCallResult res; 99 | res.err = true; 100 | res.kind = kind; 101 | res.value = value; 102 | return res; 103 | } 104 | }; 105 | 106 | ErlNifResourceType * NifCallCallbackNifRes::type = NULL; 107 | ERL_NIF_TERM NifCallCallbackNifRes::kAtomOK; 108 | ERL_NIF_TERM NifCallCallbackNifRes::kAtomError; 109 | ERL_NIF_TERM NifCallCallbackNifRes::kAtomNil; 110 | ERL_NIF_TERM NifCallCallbackNifRes::kAtomENOMEM; 111 | ERL_NIF_TERM NifCallCallbackNifRes::kAtomExecute; 112 | ERL_NIF_TERM NifCallCallbackNifRes::kAtomCallerEnv; 113 | ERL_NIF_TERM NifCallCallbackNifRes::kAtomNotTag; 114 | ERL_NIF_TERM NifCallCallbackNifRes::kAtomInvalidRunner; 115 | ERL_NIF_TERM NifCallCallbackNifRes::kAtomInvalidRunnerReply; 116 | ERL_NIF_TERM NifCallCallbackNifRes::kAtomRunnerIsDown; 117 | 118 | NifCallCallbackNifRes * prepare_nif_call(ErlNifEnv* env) { 119 | NifCallCallbackNifRes *res = (NifCallCallbackNifRes *)enif_alloc_resource(NifCallCallbackNifRes::type, sizeof(NifCallCallbackNifRes)); 120 | if (!res) return NULL; 121 | memset(res, 0, sizeof(NifCallCallbackNifRes)); 122 | 123 | res->msg_env = enif_alloc_env(); 124 | if (!res->msg_env) { 125 | enif_release_resource(res); 126 | return NULL; 127 | } 128 | 129 | res->mtx = enif_mutex_create((char *)"nif_call_mutex"); 130 | if (!res->mtx) { 131 | enif_free_env(res->msg_env); 132 | enif_release_resource(res); 133 | return NULL; 134 | } 135 | 136 | res->cond = enif_cond_create((char *)"nif_call_cond"); 137 | if (!res->cond) { 138 | enif_free_env(res->msg_env); 139 | enif_mutex_destroy(res->mtx); 140 | enif_release_resource(res); 141 | return NULL; 142 | } 143 | 144 | res->return_value_set = false; 145 | res->return_value = NifCallCallbackNifRes::kAtomNil; 146 | 147 | return res; 148 | } 149 | 150 | static NifCallResult make_nif_call(ErlNifEnv* caller_env, ERL_NIF_TERM tag, ERL_NIF_TERM args) { 151 | NifCallCallbackNifRes *callback_res = prepare_nif_call(caller_env); 152 | if (!callback_res) { 153 | return NifCallResult::error(NifCallCallbackNifRes::kAtomENOMEM); 154 | } 155 | 156 | int arity = 0; 157 | const ERL_NIF_TERM * tag_container = NULL; 158 | if (!enif_get_tuple(caller_env, tag, &arity, &tag_container) || arity != 2 || !enif_is_pid(caller_env, tag_container[0])) { 159 | return NifCallResult::error(NifCallCallbackNifRes::kAtomNotTag); 160 | } 161 | 162 | ErlNifPid evaluator; 163 | if (!enif_get_local_pid(caller_env, tag_container[0], &evaluator)) { 164 | return NifCallResult::error(NifCallCallbackNifRes::kAtomInvalidRunner); 165 | } 166 | 167 | ERL_NIF_TERM callback_term = enif_make_resource(caller_env, (void *)callback_res); 168 | enif_send(caller_env, &evaluator, callback_res->msg_env, enif_make_copy(callback_res->msg_env, enif_make_tuple4(caller_env, 169 | NifCallCallbackNifRes::kAtomExecute, 170 | callback_term, 171 | tag_container[1], 172 | args 173 | ))); 174 | 175 | enif_mutex_lock(callback_res->mtx); 176 | while (!callback_res->return_value_set) { 177 | enif_cond_wait(callback_res->cond, callback_res->mtx); 178 | if (enif_is_process_alive(caller_env, &evaluator) == 0) { 179 | enif_mutex_unlock(callback_res->mtx); 180 | return NifCallResult::error(NifCallCallbackNifRes::kAtomRunnerIsDown); 181 | } 182 | } 183 | enif_mutex_unlock(callback_res->mtx); 184 | 185 | ERL_NIF_TERM return_value = enif_make_copy(caller_env, callback_res->return_value); 186 | enif_release_resource(callback_res); 187 | 188 | arity = 0; 189 | const ERL_NIF_TERM * val_container = NULL; 190 | if (!enif_get_tuple(caller_env, return_value, &arity, &val_container) || arity != 2) { 191 | return NifCallResult::error(NifCallCallbackNifRes::kAtomInvalidRunnerReply); 192 | } 193 | 194 | if (enif_compare(val_container[0], NifCallCallbackNifRes::kAtomOK) == 0) { 195 | return NifCallResult::ok(val_container[1]); 196 | } 197 | 198 | return NifCallResult::error(val_container[0], val_container[1]); 199 | } 200 | 201 | static ERL_NIF_TERM nif_call_evaluated(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) { 202 | NifCallCallbackNifRes *res = NULL; 203 | if (!enif_get_resource(env, argv[0], NifCallCallbackNifRes::type, (void **)&res)) return enif_make_badarg(env); 204 | 205 | res->return_value = enif_make_copy(res->msg_env, argv[1]); 206 | res->return_value_set = true; 207 | enif_cond_signal(res->cond); 208 | 209 | return NifCallCallbackNifRes::kAtomOK; 210 | } 211 | 212 | static void destruct_nif_call_res(ErlNifEnv *, void *obj) { 213 | NifCallCallbackNifRes *res = (NifCallCallbackNifRes *)obj; 214 | if (res->cond) { 215 | enif_cond_destroy(res->cond); 216 | res->cond = NULL; 217 | } 218 | if (res->mtx) { 219 | enif_mutex_destroy(res->mtx); 220 | res->mtx = NULL; 221 | } 222 | if (res->msg_env) { 223 | enif_free_env(res->msg_env); 224 | res->msg_env = NULL; 225 | } 226 | } 227 | 228 | static int nif_call_onload(ErlNifEnv *env) { 229 | static int loaded = 0; 230 | if (loaded) return 0; 231 | 232 | ErlNifResourceType *rt; 233 | rt = enif_open_resource_type(env, "Elixir.NifCall.NIF", "NifCallCallbackNifRes", destruct_nif_call_res, ERL_NIF_RT_CREATE, NULL); 234 | if (!rt) return -1; 235 | NifCallCallbackNifRes::type = rt; 236 | 237 | NifCallCallbackNifRes::kAtomOK = enif_make_atom(env, "ok"); 238 | NifCallCallbackNifRes::kAtomError = enif_make_atom(env, "error"); 239 | NifCallCallbackNifRes::kAtomNil = enif_make_atom(env, "nil"); 240 | NifCallCallbackNifRes::kAtomENOMEM = enif_make_atom(env, "enomem"); 241 | NifCallCallbackNifRes::kAtomExecute = enif_make_atom(env, "execute"); 242 | 243 | // https://www.erlang.org/doc/apps/erts/erl_nif.html#enif_self 244 | // https://www.erlang.org/doc/apps/erts/erl_nif#proc_bound_env 245 | NifCallCallbackNifRes::kAtomCallerEnv = enif_make_atom(env, "not_in_process_bound_env"); 246 | 247 | NifCallCallbackNifRes::kAtomNotTag = enif_make_atom(env, "not_tag"); 248 | NifCallCallbackNifRes::kAtomInvalidRunner = enif_make_atom(env, "invalid_runner"); 249 | NifCallCallbackNifRes::kAtomInvalidRunnerReply = enif_make_atom(env, "invalid_runner_reply"); 250 | NifCallCallbackNifRes::kAtomRunnerIsDown = enif_make_atom(env, "runner_is_down"); 251 | 252 | loaded = 1; 253 | return 0; 254 | } 255 | 256 | #endif 257 | 258 | #endif // NIF_CALL_H 259 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------