[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Using native libraries in bash scripts
From: |
Tavis Ormandy |
Subject: |
Using native libraries in bash scripts |
Date: |
Fri, 10 Jul 2020 09:30:16 -0700 |
User-agent: |
MicroPlanet-Gravity/3.0.6 |
I thought this group might be interested in a fun project
I worked on a few years ago. It's a module for bash that
lets scripts load and interact with shared libraries.
https://github.com/taviso/ctypes.sh/wiki
Naturally, everything about this is non-portable, bash-
specific, and probably off-topic... it's just for fun :)
I saw a thread about calculating crc32 in bash, with
ctypes.sh you could do this:
$ dlopen libz.so
0x7ffff626a860
$ buf="string to check"
$ dlcall -r long crc32 long:0 "$buf" ${#buf}
long:1206832624
Looks correct!
You can create structures and unions too, which lets you
interact with more complex apis.
The Python ctypes module requires you to define all the
structs manually, but in most cases ctypes.sh can create
them for you automatically! This sounds crazy, but it
usually works.
Here is an example, automatically creating a struct stat:
$ struct -m statbuf stat passwd
Now $statbuf is a pointer that you can pass to native
APIs. It just looks like this in bash:
$ echo $statbuf
pointer:0x7f6ebb82e9a0
And $passwd is a bash associative array that contains all
the structure members, so ${passwd[st_ino]} would be the
inode number.
Here is an example, pass $statbuf to stat() and get it
filled in (on Linux the name of the symbol is __xstat).
$ dlcall __xstat 0 "/etc/passwd" $statbuf
# This copies the native values into the bash array so you
# can examine them in your script.
$ unpack $statbuf passwd
$ echo ${passwd[st_size]}
long:1639
I guess most people have used something like the dialog
command to make interactive shell scripts, but ctypes.sh
lets you use all of the ncurses API, or even the GTK+ API.
I ported the GTK+3 Hello World to bash, here's the
original C version:
https://developer.gnome.org/gtk3/stable/gtk-getting-
started.html
And here's my bash port:
http://github.com/taviso/ctypes.sh/blob/master/test/gtk.sh
This also makes some things possible that you normally
couldn't do in shell. For example, I don't think there's
any way to service multiple file descriptors efficiently
in bash, you would have to use `read -u $i -t 0` in a busy
loop.
With ctypes.sh, you can have access to things like the
select() system call.
There are more examples here:
https://github.com/taviso/ctypes.sh/tree/master/test
Tavis.
--
_o)
/\\ _o) _o)
_\_V _( ) _( ) :wq!
[Prev in Thread] |
Current Thread |
[Next in Thread] |
- Using native libraries in bash scripts,
Tavis Ormandy <=