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

Possible leaking file descriptor in Infer.get_from_path/1,2 #10

Closed
smaximov opened this issue Nov 16, 2023 · 1 comment
Closed

Possible leaking file descriptor in Infer.get_from_path/1,2 #10

smaximov opened this issue Nov 16, 2023 · 1 comment

Comments

@smaximov
Copy link

smaximov commented Nov 16, 2023

Consider the implementation of Infer.get_from_path/1,2:

infer/lib/infer.ex

Lines 46 to 53 in 65beb86

@spec get_from_path(binary()) :: Infer.Type.t() | nil
def get_from_path(path, byte_size \\ 2048) do
with {:ok, io_device} <- :file.open(path, [:read, :binary]),
{:ok, binary} <- :file.read(io_device, byte_size) do
:file.close(io_device)
Enum.find(@matchers, & &1.matcher.(binary))
end
end

If :file.read/2 returns anything other than {:ok, data}, the file won't be closed. One possible solution is to use File.open/3 with a function as an argument because it ensures the file will be closed even in case of error:

def get_from_path(path, byte_size \\ 2048) do
  result = File.open(path, [:binary, :read], fn io_device ->
    case IO.binread(io_device, byte_size) do
      binary when is_binary(binary) -> Enum.find(@matchers, & &1.matcher.(binary)) 
      _other -> nil
    end
  end)

  case result do
    {:ok, %Infer.Type{} = type} -> type
    _other -> nil
  end
end

(this implementation would also fix #9)

@daskycodes
Copy link
Owner

Closed in #13

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants