ish README

The project's README from github.com/ish-app/ish. As one markdown file: README.md.

iSH

Build Status goto counter fuck counter shit counter

A project to get a Linux shell running on iOS, using usermode x86 emulation and syscall translation.

For the current status of the project, check the issues tab, and the commit logs.

Hacking

This project has a git submodule, make sure to clone with --recurse-submodules or run git submodule update --init after cloning.

You'll need these things to build the project:

Build for iOS

Open the project in Xcode, open iSH.xcconfig, and change ROOT_BUNDLE_IDENTIFIER to something unique. You'll also need to update the development team ID in the project (not target!) build settings. Then click Run. There are scripts that should do everything else automatically. If you run into any problems, open an issue and I'll try to help.

Build command line tool for testing

To set up your environment, cd to the project and run meson build to create a build directory in build. Then cd to the build directory and run ninja.

To set up a self-contained Alpine linux filesystem, download the Alpine minirootfs tarball for i386 from the Alpine website and run ./tools/fakefsify, with the minirootfs tarball as the first argument and the name of the output directory as the second argument. Then you can run things inside the Alpine filesystem with ./ish -f alpine /bin/sh, assuming the output directory is called alpine. If tools/fakefsify doesn't exist for you in your build directory, that might be because it couldn't find libarchive on your system (see above for ways to install it.)

You can replace ish with tools/ptraceomatic to run the program in a real process and single step and compare the registers at each step. I use it for debugging. Requires 64-bit Linux 4.11 or later.

Logging

iSH has several logging channels which can be enabled at build time. By default, all of them are disabled. To enable them:

Available channels:

A note on the interpreter

Possibly the most interesting thing I wrote as part of iSH is the interpreter. It's not quite a JIT since it doesn't target machine code. Instead it generates an array of pointers to functions called gadgets, and each gadget ends with a tailcall to the next function; like the threaded code technique used by some Forth interpreters. The result is a speedup of roughly 3-5x compared to emulation using a simpler switch dispatch.

Unfortunately, I made the decision to write nearly all of the gadgets in assembly language. This was probably a good decision with regards to performance (though I'll never know for sure), but a horrible decision with regards to readability, maintainability, and my sanity. The amount of bullshit I've had to put up with from the compiler/assembler/linker is insane. It's like there's a demon in there that makes sure my code is sufficiently deformed, and if not, makes up stupid reasons why it shouldn't compile. In order to stay sane while writing this code, I've had to ignore best practices in code structure and naming. You'll find macros and variables with such descriptive names as ss and s and a. Assembler macros nested beyond belief. And to top it off, there are almost no comments.

So a warning: Long-term exposure to this code may cause loss of sanity, nightmares about GAS macros and linker errors, or any number of other debilitating side effects. This code is known to the State of California to cause cancer, birth defects, and reproductive harm.

ish (ish-app/ish)

Searching Database…

20.6K ·GitHub
Что это такое?iSH — это приложение с открытым исходным кодом для iOS, которое даёт вам Linux-оболочку на iPhone или iPad. Оно эмулирует процессор x86 в пользовательском режиме и транслирует системные вызовы Linux, поэтому программы командной строки Linux работают на iOS как есть.
Это приложение, которое я устанавливаю на iPhone, или что-то, что запускается на компьютере?Это обычное приложение для iOS: в README есть ссылки на страницу в App Store и на бета-версию в TestFlight, так что джейлбрейк не нужен. Есть ещё отдельная версия для командной строки, которую разработчики собирают и запускают на macOS или Linux для тестирования.
Что нужно установить, чтобы собрать проект?Python 3 с Meson, Ninja, Clang и LLD, а также sqlite3 и libarchive — на Mac это brew install llvm плюс brew install libarchive, а для самой сборки под iOS ещё и Xcode.
Это настоящая полноценная Linux-система, работающая на моём телефоне?Нет, только пользовательский режим: iSH эмулирует набор инструкций x86 и транслирует системные вызовы, так что вы получаете окружение Linux в пользовательском пространстве, а не загруженное ядро Linux. О том, что сейчас работает, README отсылает к вкладке issues и истории коммитов.
Есть ли от этого польза обычному человеку, или это только для тех, кто живёт в терминале?В первую очередь это для разработчиков и любителей Unix, которым нужна переносимая командная строка Linux, но проект ссылается на вики со справкой и обучающими материалами, так что любознательный новичок тоже в нём разберётся.
Работает ли это и на iPad, или только на iPhone?iSH — приложение для iOS, поэтому оно работает и на iPhone, и на iPad через App Store или TestFlight. Единственный другой способ его запустить — тестовая сборка для командной строки, которая компилируется на macOS или Linux.
Как именно устроена эмуляция внутри?Никакого JIT там нет. iSH генерирует массив указателей на функции, которые называются gadget'ами, и каждый gadget завершается хвостовым вызовом (tailcall) следующего — это тот же приём threaded code, который используют некоторые интерпретаторы Forth. Почти все эти gadget'ы написаны на ассемблере вручную.
Могу ли я запустить iSH на Mac или Linux для тестирования?Да. Выполните meson build, затем ninja внутри каталога сборки, преверите tar-архив Alpine minirootfs в файловую систему с помощью tools/fakefsify и запустите её командой ./ish -f alpine /bin/sh. Для отладки есть tools/ptraceomatic, который пошагово выполняет программу в реальном процессе и сравнивает регистры — ему требуется 64-битный Linux 4.11 или новее.
Какой дистрибутив Linux там реально работает?Проект построен вокруг Alpine Linux: вы скачиваете tar-архив Alpine minirootfs для i386 и с помощью tools/fakefsify превращаете его в самодостаточный каталог-файловую систему — именно внутри неё и работает оболочка.
Приятно ли работать с исходным кодом?Сам автор отговаривает: малопонятные имена вроде ss, s и a, ассемблерные макросы, вложенные до невозможности, и почти без комментариев. В README прямо сказано, что долгий контакт с этим кодом может привести к потере рассудка и кошмарам о макросах GAS и ошибках линковщика.
Creator
ish-app
Size
5.5 MB
Stars
20.6K
Age
9y
Commits · 90 Days