0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Crystalでgetexecpath(3)のバインディングを書いてみた

0
Last updated at Posted at 2026-11-30

この記事は、Crystal言語のshard(Rubyでいうgem)をつくってみたときの作業の控えです。提供する機能は、ELF実行ファイルのパス名を返す関数1つだけです。
以前Crystalに触ったのは2023年12月14日のCrystalをインストールしたかった (Guix)です。お手柔らかにお願いします。

リポジトリ:Codeberg

「お手元で動かしてみてください」と言いたいのですが、このライブラリの関数Getexecpath.execpathは、getexecpath(3)というCのライブラリ関数のバインディングです。これは2026年8月31日(最近!)にリリースされたOpenBSD 8.0から含まれる独自の関数です(参照:イノベーションのページ)。そのため、試していただくにはOpenBSD 8.0のインストールが必要となります。

それで、CrystalをOpenBSDにインストールしたいのですが……ご安心ください。なんと公式でパッケージが提供されています。ちなみに、既定の構成でポートを使う場合、ウェブページにあるやり方でもいいのかもしれませんが、臆見ではdoasを使わずに非特権ユーザで実行したほうがトラブルが少ないかもしれません。

使っていくCrystalのバージョンは以下です。どうやらリリースモードじゃないらしいです。特別おそいとかはありませんでしたが。

crystal version
# Crystal 1.21.0 [57cf7da50] (2026-07-16)
#
# The compiler was not built in release mode.
#
# LLVM: 22.1.8
# Default target: x86_64-unknown-openbsd8.0

getexecpath(3)

この関数が何をするかは冒頭に書いた通りで、この関数を呼び出すELF実行ファイルのパス名を返します。私用のPCをOpenBSD 8.0に更新したときに気になってCRubyやmrubyでいじっていたのですが、少なくともCRubyではいまひとつ用途が合ってなさそうでした。一方Crystalだと微粒子レベルで実用になる可能性があるかもしれません、プラットフォーム限定ながら。

詳しいことはmanページを参照していただきたいのですが、この関数はunistd.hヘッダで提供され、以下のようなシグネチャをしています。

int
getexecpath(char *buf, size_t bufsize);

使い方としては、まずbufsizeの大きさのbufを用意しておいて、引数に渡します。すると、そのバッファを実行パスで埋めてくれます。文字列の表現は典型的な、最後にヌル文字があるものです。返却される整数は結果の成否を表し、-1なら失敗です。失敗のときはerrnoを確かめれば詳しい原因を知れます。

わりと素朴ですね。メモリの確保もしなくてよさそうなのもグッドです。

どんなライブラリにするか

shard名はgetexecpathにします。モジュール名はGetexecpathです。提供する関数はexecpathの1つのみで、無引数の文字列を返します。こんな風に使います。

require "getexecpath"
Getexecpath.execpath #=> "/path/to/elf-file"

作業の様子

CrystalのCバインディングのつくりかたの正確なところ、基本的なところは、公式の文書を参照してください。今回の範囲では「lib」「fun」「to_unsafe」「Constants」を主に読みました。

実際の作業の流れはこんな感じです。

  1. crystal init lib getexecpathで雛形を生成
  2. crystal specでテストを走らせる→最初なので失敗
  3. spec/getexecpath_spec.crを書く
  4. src/getexecpath.crを書く
  5. 再びテストを走らせる→成功!

この工程について、部分的に補足します。

補足:テスト

最初の状態ではcrystal specが以下のように失敗します。

crystal spec
# F
#
# Failures:
#
#   1) Getexecpath works
#      Failure/Error: false.should eq(true)
#
#        Expected: true
#             got: false
#
#      # spec/getexecpath_spec.cr:7
#
# Finished in 371 microseconds
# 1 examples, 1 failures, 0 errors, 0 pending
#
# Failed examples:
#
# crystal spec spec/getexecpath_spec.cr:6 # Getexecpath works

今回の目標では、これを通すことにしましょう。テストケースは以下。

describe Getexecpath do
  it "works" do
    path = Getexecpath.execpath
    path.empty?.should be_false
    File.file?(path).should be_true
  end
end

実際のパスは絶対パスなので、ちょっと緩いですがこのくらいにしておきます。具体的な値はputs pathを書き入れてcrystal spec --verboseとすれば確認できます。

crystal spec --verbose
# Getexecpath
#   works/home/gemmaro/.cache/crystal/crystal-run-spec.tmp ←これ!
#   works
#
# Finished in 196 microseconds
# 1 examples, 0 failures, 0 errors, 0 pending

最終的にテストが通りました。やったね。

crystal spec 
# .
#
# Finished in 173 microseconds
# 1 examples, 0 failures, 0 errors, 0 pending

補足:実装

実装するときに雑多に思ったことを書きます。

C言語の定数はCrystal側で参照できないのかもしれません。野生のshardを見てもベタ書きしているようです。今回の場合、PATH_MAXをbufsizeの目安として使いますが、これは実際のヘッダファイルの値を見て決めうちしています。

Crystalの標準ライブラリはAPI文書を参照しました。Ruby的にありそうなものは大体あるのがいいですね。File.file?や、String.newや、Errno.value(これがCでのerrnoにあたります)や、Slice#to_unsafeなどです。

C言語の諸々の型がCrystalでどう対応しているかは、src/lib_c.crにあります。今回登場する型の対応は以下なので……

C Crystal
int LibC::Int
char LibC::Char
size_t LibC::SizeT

libでの宣言は次のようになります。

lib LibUnistd
  fun getexecpath(buf: LibC::Char*, bufsize: LibC::SizeT) : LibC::Int
end

補足:outって?

ドキュメントによると、outを引数の前につけることで、出力用のポインタの扱いが楽になるというもののようです。なんだかPerlの一部のサブルーチンみたいな見た目ですね。

open(my $fh, '<', "/path/to/file")

よさそうですが、今回は使えません。というのも、getexecpath(3)の第一引数は文字列としてのポインタであって、単一のcharを指すポインタではないからです。仮に以下とすると……

  def self.execpath
    if LibUnistd.getexecpath(out bytes, PATH_MAX) == -1
      case Errno.value
      when Errno::ENOENT
        raise Error.new("getexecpath: could not determine exec pathname")
      when Errno::ERANGE
        raise Error.new("getexecpath: too small bufsize")
      else
        raise Error.new("getexecpath: unexpected: #{Errno.value}")
      end
    end
    String.new(bytes.to_unsafe)
  end

以下のようなエラーになります。ちなみにUInt8はCharのエイリアス元です。

crystal spec
# Showing last frame. Use --error-trace for full trace.
#
# In src/getexecpath.cr:39:22
#
#  39 | String.new(bytes.to_unsafe)
#                        ^--------
# Error: undefined method 'to_unsafe' for UInt8

補足:どこでto_unsafeを使うの?

わかりませんが、つけ忘れるとエラーになることがあります。
例えば以下のように最後にStringをつくるところで付け忘れると……

  def self.execpath
    bytes = Bytes.new(PATH_MAX)
    if LibUnistd.getexecpath(bytes.to_unsafe, PATH_MAX) == -1
      case Errno.value
      when Errno::ENOENT
        raise Error.new("getexecpath: could not determine exec pathname")
      when Errno::ERANGE
        raise Error.new("getexecpath: too small bufsize")
      else
        raise Error.new("getexecpath: unexpected: #{Errno.value}")
      end
    end
    String.new(bytes) # ←to_unsafeがない!
  end

以下のようなエラーが出ます。Cの機能が触れたところはもれなく付けといたほうがよさそうです。

  1) Getexecpath works

       String contains null byte (ArgumentError)
         from /usr/local/lib/crystal/string.cr:5662:7 in 'check_no_null_byte'
         from /usr/local/lib/crystal/string.cr:5659:3 in 'check_no_null_byte'
         from /usr/local/lib/crystal/crystal/system/unix/file.cr:30:18 in 'info?'
         from /usr/local/lib/crystal/file.cr:199:5 in 'info?'
         from /usr/local/lib/crystal/file.cr:198:3 in 'info?'
         from /usr/local/lib/crystal/file.cr:329:15 in 'file?'
         from spec/getexecpath_spec.cr:29:5 in '->'
         from /usr/local/lib/crystal/spec/example.cr:50:13 in 'internal_run'
         from /usr/local/lib/crystal/spec/example.cr:38:16 in 'run'
         from /usr/local/lib/crystal/spec/context.cr:20:23 in 'internal_run'
         from /usr/local/lib/crystal/spec/context.cr:364:14 in 'run'
         from /usr/local/lib/crystal/spec/context.cr:20:23 in 'internal_run'
         from /usr/local/lib/crystal/spec/context.cr:173:7 in 'run'
         from /usr/local/lib/crystal/spec/dsl.cr:219:7 in 'execute_examples'
         from /usr/local/lib/crystal/spec/dsl.cr:194:13 in '->'
         from /usr/local/lib/crystal/crystal/at_exit_handlers.cr:26:17 in 'run'
         from /usr/local/lib/crystal/crystal/main.cr:64:14 in 'exit'
         from /usr/local/lib/crystal/crystal/main.cr:50:5 in 'main'
         from /usr/local/lib/crystal/crystal/system/unix/main.cr:9:3 in 'main'
         from /home/gemmaro/.cache/crystal/crystal-run-spec.tmp in '_start'

以上

この記事は以上です。なんだかCRubyやmrubyのC拡張というよりは、FFIの方に近い感じでしたね。

余談:本当はpledge(3)(とunveil(3))のバインディングの方がOpenBSDとしては有名どころなのですが、あろうことか既にあったのでやむなく今回の関数にしました。このshardを書くときはpledge.crやcr-cmark-gfmや、Awesome CrystalのC bindingsに挙がっているものを眺めたりしました。ありがたや。

使用許諾

Copyright (C) 2026 gemmaro

Copying and distribution of this file, with or without modification,
are permitted in any medium without royalty provided the copyright
notice and this notice are preserved. This file is offered as-is,
without any warranty.

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?