Содержание
- How to fix Cannot execute binary file: exec format error?
- Check the architecture
- Check the file
- Install GCC and Gfortran
- Uncompress the file
- Check file permissions
- Use Dos2unix
- How to Fix ‘cannot execute binary file: Exec format error’ on Ubuntu
- Method 1: Using the arch Command
- Method 2: Using the file Command
- Решение проблемы с ошибкой «bash: не удаётся запустить бинарный файл: Ошибка формата выполняемого файла»
- О разрядности дистрибутивов Linux и о программ
- Запуск ARM файлов в Linux
- Заключение
- Thread: cannot execute binary file: Exec format error
- cannot execute binary file: Exec format error
- Re: cannot execute binary file: Exec format error
- Re: cannot execute binary file: Exec format error
- Re: cannot execute binary file: Exec format error
How to fix Cannot execute binary file: exec format error?
Photo by Jivacore/Shutterstock.com
Linux has been reworked heavily since it first came out to the point that it’s no longer an OS for terminal kings. Just about everyone can use it now thanks to the much better user interfaces that we see in modern Linux distros. However, that doesn’t mean it can’t be frustrating at times.
In this article, we’re taking a look at the “cannot execute binary file: exec format error” issue and giving you a few solutions on how to get rid of the problem.
Check the architecture
The first thing you should do is ensure you’ve got the right bin file. Binary files made for 32-bit systems won’t work on 64-bit systems and vice-versa. You can check the architecture of any file by using the command below.
If the architecture doesn’t match between your file and the PC you’re running it on, try running the corresponding binary file for the matching architecture.
Check the file
Binary files can be run on Windows, Linux and macOS. However, binaries made for one OS won’t run on the others. Generally, these files have different file formats to help users distinguish between them. If you’re trying to run a binary file made for Windows on a Linux distro, it’s obviously not going to work.
If you must run the binary on Linux however, we recommend downloading Wine and using it to run the file. Wine is a compatibility layer capable of running Windows applications on POSIX-compliant operating systems, including Linux and macOS.
Install GCC and Gfortran
GCC and Gfortran are required for several binary files to compile and execute properly. You can install them by typing the command below in your terminal.
Now try running your binary file again and it should run without a problem — fixing the ‘cannot execute binary file’ error.
Uncompress the file
Sometimes binary files are compressed to make them easier to share over the internet. Try uncompressing the file to see if that helps you run it fine. Run the following commands on at a time.
Check file permissions
Another potential reason for your binary file not running could be that the user doesn’t have permission to change or read the file. You can fix this by typing the following command in the terminal.
Once the permissions are set, you can run the file by typing this.
Use Dos2unix
The Dos2unix command can sometimes help binaries made for DOS to run on UNIX systems. Try using the following command to see if your file runs or not.
If we’ve missed out on any fixes that helped you solve the ‘cannot execute binary file’ error, please comment down below with the fix.
Someone who writes/edits/shoots/hosts all things tech and when he’s not, streams himself racing virtual cars.
You can contact him here: [email protected]
Источник
How to Fix ‘cannot execute binary file: Exec format error’ on Ubuntu
While it shouldn’t happen when using the official apt-get repositories, if you download software off the Internet and run it then there’s a chance that you’ll see the dreaded bash: ./nameOfProgram: cannot execute binary file: Exec format error. This error, which is usually followed by bash: ./nameOfProgram.sh: Permission denied or something like it, indicates that Ubuntu wasn’t able to interface correctly with the binary you downloaded. This is because while it’s apparently a valid Linux binary, it’s designed for a different chipset than your kernel currently supports.
Most people using Ubuntu are on 32-bit or 64-bit processors based around a standard architecture that Intel released, regardless of who actually made their microchips. It’s important to remember that 64-bit processors can run in 32-bit mode, so if you’re getting this error even though you have a 64-bit processor there’s a chance you’re running a 32-bit version of Ubuntu. A few simple commands are all it takes to tell what your chip is operating as.
Method 1: Using the arch Command
If you’re not familiar with the type of microprocessor that you have installed on your machine, then you’ll first want to use the arch command from the command line. You’ll only see a single line of output returned to you after running this command. In many cases, you’ll see i686, which means that you’re on a 32-bit processor and therefore can’t run x86_64 binaries. If you instead see amd64 or something similar, then you’re on an x86_64 processor, and should at least theoretically be able to run most 32-bit and 64-bit binaries. Unlike Microsoft Windows, Ubuntu Linux actually contains the proper tools to permit users of 644-bit chipsets to run 16-bit Windows programs in their operating system in many cases as well.
These terms are still true even if you’re not actually using that particular model of microchip. For instance, i686 is how Linux refers to many 32-bit processors even if they aren’t actually Intel 80686 chips. Even if you’re using 64-bit Intel technology, arch might still call your processor an amd64 chip. This doesn’t indicate an error, and can be safely ignored. You can use cat /proc/cpuinfo or more /proc/cpuinfo to find out the exact type of processor you’re using. Since the lines in this file are long, you might want to push F11 before issuing it if you’re using a graphical terminal window. Users of a virtual console, especially those working with Ubuntu server, won’t have to worry quite as much.
You may see some other types of output, which might further restrict your options when it comes to running software. Ubuntu supported PowerPC architecture for the longest time, which is found in some workstations as well as many Classic Macintosh and older OS X Macintosh machines. You can actually still find Ubuntu repositories for these architectures, though they receive little support today. However, you more than likely won’t be able to run many Linux binaries you download from the Internet outside of the official repositories in this case. That doesn’t mean that Ubuntu doesn’t work on these machines, though you may want to look at the lighter Lubuntu distribution.
Method 2: Using the file Command
The file command identifies what different files contain, and it’s usually very accurate. Try identifying the file in question by typing file nameOfProgram to see if you get ELF 32-bit or ELF 64-bit as output. If it tells you that it’s an ELF 64-bit binary and you received i686 as output from the arch command, then there’s no way you can reasonably run it on your machine. If you’re on a 64-bit microprocessor running 32-bit Ubuntu, then you could technically reinstall the operating system, though this is a bit of an extreme step in order to run a single program.
There is also the very real possibility, however slight, that you might instead come across a binary that when you attempt to run it spews out junk characters to the terminal even if you’ve run a malware scan on it. These characters usually take the form of either lozenge-shaped blocks, or alternatively rectangular cubes that have numerical values in them. Some computer scientists call the latter tofu, and represent the Unicode values of characters that your currently installed typefaces won’t be able to display. If the terminal is displaying them like this, then you can rest assured that this is neither a font error nor anything having to do with malware. Rather, this is simply because the compiled microprocessor opcode inside of the binary is so alien to your system that it doesn’t know how to interpret some of the code.
The best way to fix this is to install the proper package for your architecture. If you’re installing packages from inside Ubuntu, then the apt-get system or the graphical Synaptic manager has you covered without any problems. If you’re downloading packages from another distribution, then you’ll need to find the right one for your architecture. Take, for example, Arch Linux’s listing of the gvim package. While the default package features the x86_64 architecture, there’s also one for the i686 chipset. This one will work on 32-bit machines that work with the Intel interrupt structure, but remember that the terms i686 and 32-bit are not mutually inclusive all the time since other chipsets Linux supports actually do feature their own 32-bit implementations.
Users exploring the whole GNU/Linux scene might come across binaries compiled for far more exotic technologies than these. Linux is truly a cross-platform code scene, so you’ll see OpenRISC, MIPS, SPARC, M32R, MN103, ARM, ARC, Alpha and many other standards binaries are compiled to work with. More than likely, you won’t be able to run any of these, though ARM is an extremely popular tablet and smartphone platform. It’s also the platform that the Raspberry Pi is based around, which means if you’re actually running Ubuntu on a mobile device or the Ubuntu MATE distribution for Raspberry Pi you’ll actually need these instead of Intel 32-bit or x86_64 binaries.
Источник
Решение проблемы с ошибкой «bash: не удаётся запустить бинарный файл: Ошибка формата выполняемого файла»
В операционной системе Linux при запуске скаченного файла, либо при запуске самостоятельно скомпилированного файла вы можете столкнуться с ошибкой:
Если у вас англоязычная локаль, то ошибка будет примерно такой:
bash: ./program: cannot execute binary file: Exec format error
В самой ошибке вместо /путь/до/файла и ./program будет указан путь до файла программы, который вы хотите запустить.
- Причинами данной ошибки могут быть:
- попытка запустить 64-битный файл на 32-битной системе
- файл скомпилирован для другой архитектуры (например, для ARM, а вы пытаетесь запустить его на ПК)
- вы пытаетесь выполнить не исполнимый файл, а ссылку
- файл размещён в совместной (shared) папке
Чтобы получить информацию о файле, который вы пытаетесь запустить, можно использовать утилиту file, после которой укажите путь до файла:
Здесь мы видим, что файл предназначен для 64-битной системы, об этом говорит запись 64-bit, для процессора с архитектурой x86-64.
Ещё один пример:
Этот файл для 32-битных систем, для процессора с архитектурой ARM EABI4.
Если вы не знаете, какой битности ваша система, то выполните команду:
Для 64-битных систем будет выведено x86_64, а для 32-битных – x86.
О разрядности дистрибутивов Linux и о программ
На компьютер с 32-битным процессором вы можете установить только 32-битную операционную систему и в ней запускать только 32-битные программы.
На компьютер с 64-битным процессором вы можете установить как 64-битную ОС, так и 32-битный Linux. В случае, если вы установили 64-битный дистрибутив Linux, то в нём вы можете запускать и 64-битные программы и 32-битные. А если вы установили 32-битный дистрибутив, то в нём возможно запускать только 32-битные программы.
Итак, если у вас 32-битная система, а файл для 64-битной системы или даже для ARM архитектуры, то у вас следующие варианты:
- скачать файл подходящей для вас битности и архитектуры
- если вы самостоятельно компилировали файл из исходного кода, то заново скомпилируйте для процессора вашей архитектуры
Запуск ARM файлов в Linux
Часто можно запустить исполнимые образы ARM на amd64 системах если установить пакеты binfmt-support, qemu, и qemu-user-static:
sudo apt install binfmt-support qemu qemu-user-static
Заключение
Итак, ошибка формата выполняемого файла с невозможностью запустить бинарный файл возникает из-за несоответствия программы операционной системе или архитектуре процессора. Эта проблема не должна возникать, если вы установили программу из исходных репозиториев (кроме случаев неправильной настройки источников репозитория). При возникновении этой проблемы поищите файл, подходящий для вашей архитектуры или скомпилируйте файл из исходных кодов под архитектуру вашей операционной системы.
Источник
Thread: cannot execute binary file: Exec format error
Thread Tools
Display
cannot execute binary file: Exec format error
Hi guys, I could really use some help.
I’m getting all kinds of problems with my installation of Ubunut today, everything was working perfectly for months until today. I came back home, tried to turn on my laptop, logged in and all I was able to see was my folders on my dekstop, no menu, no launcher, no top bar.
I solved this by running «setsid unity» however it only works until I reboot the laptop.
When I open my terminal I get this error
«bash: /home/matt/bin/ls: cannot execute binary file: Exec format error
/home/matt/bin/bash: 1: /home/matt/bin/bash: Syntax error: «(» unexpected»
Any other binary files I try to run return similar error.
The only thing I’ve done yesterday was install VirtualBox and Windows XP on it (already removed it).
I was also able to create a new user which seems to be working fine but I would really like to keep my old account and all its settings.
I’m running the latest Ubuntu 64bit
Any suggestions?
Re: cannot execute binary file: Exec format error
The system’s version of things like ‘ls’ and ‘bash’ should be in /bin — not /home/matt/bin
It sounds like you have placed some incompatible (e.g. 32-bit versus 64-bit, or ARM instead of ELF) binaries with these names into your /home/matt/bin directory, and those are being detected first because of the order of directories your PATH
Re: cannot execute binary file: Exec format error
Thanks for your answer,
I have only installed VirtualBox and ran the usual update and upgrade which I do every day / every other day.
All the system commands like ‘ls’, ‘uname’, ‘touch’ are located in /bin and only links to them are in my /home/matt/bin folder.
Nearly every command I have tried returns the same error.
Is it safe to move those files from /home/matt/bin directory to let’s say my desktop and move them back one by one to detect which one of them is giving the trouble or would that cause any more problems?
EDIT: I decided to rename all the «non links» binaries to filename.old. First try. busybox.old Opened the terminal and the error is gone, Going to reboot and see if the problem is gone. Thanks very much for your help steeldriver.
Last edited by Matt_Nona; July 13th, 2016 at 10:59 PM .
Re: cannot execute binary file: Exec format error
How and why did you create those links? that’s not a usual thing to do
Источник
I’m trying to run a program, but it gives an error:
bash: ./program: cannot execute binary file: Exec format error
The result of file program
was:
program: ELF-32-bit LSB executable, ARM, EABI4 version 1 (SYSV), dynamically linked (uses share libs), for GNU/LINUX 2.6.16, not stripped
How can I fix this?
I’m using Ubuntu 14.04.2 (amd64) with VMware. I also tried using Ubuntu i386, but the result was the same.
asked Jul 15, 2015 at 5:30
Soongeun HwangSoongeun Hwang
1,5012 gold badges9 silver badges4 bronze badges
1
You’re trying to run an executable compiled for an ARM architecture on an x86-64 architecture, which is much like asking your processor who only speaks English to take directions in Chinese.
If you need to run that executable you have two choices:
-
Get an x86-64 version of the executable (by any mean; if you’re unable to get an x86-64 version of the executable but you’re able to get its source code, you can try to recompile it on the virtual machine);
-
Install Ubuntu Server for ARM in place of Ubuntu 14.04.2 (amd64). This requires either a physical machine running on an ARM architecture or a virtualization software that can emulate it.
answered Jul 15, 2015 at 5:39
1
This can also occur if you attempt to run an x86-64 executable on a 32-bit platform.
In one specific instance, I downloaded Visual Studio Code and tried to run it on my Ubuntu installation, but I hadn’t realized that I had installed 32-bit Ubuntu in this VM. I got this error, but after downloading the 32-bit version, it ran without issue.
answered Sep 10, 2015 at 23:44
It is often possible to run an ARM executable image on an amd64 system if you install the binfmt-support
, qemu
, and qemu-user-static
packages:
sudo apt install binfmt-support qemu qemu-user-static
qemu
will then perform syscall emulation when you run the executable. This works for most ARM binaries but there are a few that may not run correctly.
answered Oct 27, 2016 at 6:41
Nathan OsmanNathan Osman
31.7k40 gold badges176 silver badges259 bronze badges
2
Such error may occur if all of the following are true:
- Executable is not a file but a link
- You run run it inside VM
- File is located in shared folder
- Your host is Windows.
If you got that file, let’s say, in archive — try to unpack it inside VM, in some directory inside virtual drive, not folder mapped to your host machine hard drive, for example /myNewDir/
wjandrea
13.8k4 gold badges46 silver badges95 bronze badges
answered Nov 13, 2015 at 22:22
PavelPavel
3531 gold badge3 silver badges10 bronze badges
1
If more than one java
is installed on the system this might happen and not set as default. On Ubuntu14.04 LTS I could get it resolved by executing following and choosing the java
I needed.
sudo update-alternatives --config java
[sudo] password for user:
update-alternatives: warning: /etc/alternatives/java has been changed (manually or by a script); switching to manual updates only
There are 2 choices for the alternative java (providing /usr/bin/java).
Selection Path Priority Status
------------------------------------------------------------
0 /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java 1071 auto mode
1 /usr/lib/jvm/java-7-openjdk-amd64/jre/bin/java 1071 manual mode
2 /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java 1069 manual mode
Press enter to keep the current choice[*], or type selection number: 2
update-alternatives: using /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java to provide /usr/bin/java (java) in manual mode
I choose 2 and set openjdk-8
as a default. Which did not show the Exec format error
.
Videonauth
32.7k16 gold badges103 silver badges119 bronze badges
answered Jun 6, 2016 at 13:43
You must compile your file using an appropriate CPU architecture (x86 for example) and copy the .exe file on your linux machine. Then you can install mono on your linux machine and issue the following command:
mono myprogram.exe
muru
189k52 gold badges460 silver badges711 bronze badges
answered Feb 28, 2016 at 19:49
1
This can also happen if the binary uses a libc implementation which is not libc, such as musl. These days this specific problem is most likely encountered when trying to run a binary with libc in a Docker container with an image based on alpine. There is nothing that can be done to the binary itself to support both environments, because the libc implementation must always be linked statically, i.e. built directly into the binary, for reasons.
answered Jul 16, 2019 at 16:44
I got this error trying to run a zip file containing an executable rather than extracting it and running the executable itself xD
In addition to the other answers offered here, I suppose there would be a lot of file types that aren’t intended to be executable which could cause this error.
answered May 19, 2020 at 6:05
1
This is another special case: WSL (Windows Subsystem for Linux) by default(!) only supports 64bit executables. I think this is a rather unusual behaviour, as normally there is a backwards compatibility.
(Even more special is that selecting 64bit in a formerly 32bit project of Windev won’t fix your issue. You need to start a new project, selecting 64bit right in the beginning. Tested on Windev 26. This IDE sucks, forced to use it because of working legacy code.)
answered Jul 21, 2022 at 23:23
PythoNicPythoNic
6761 gold badge5 silver badges15 bronze badges
2
Photo by Jivacore/Shutterstock.com
Linux has been reworked heavily since it first came out to the point that it’s no longer an OS for terminal kings. Just about everyone can use it now thanks to the much better user interfaces that we see in modern Linux distros. However, that doesn’t mean it can’t be frustrating at times.
In this article, we’re taking a look at the “cannot execute binary file: exec format error” issue and giving you a few solutions on how to get rid of the problem.
Also read: How to make a file executable in Linux?
Check the architecture
The first thing you should do is ensure you’ve got the right bin file. Binary files made for 32-bit systems won’t work on 64-bit systems and vice-versa. You can check the architecture of any file by using the command below.
file filename
If the architecture doesn’t match between your file and the PC you’re running it on, try running the corresponding binary file for the matching architecture.
Check the file
Binary files can be run on Windows, Linux and macOS. However, binaries made for one OS won’t run on the others. Generally, these files have different file formats to help users distinguish between them. If you’re trying to run a binary file made for Windows on a Linux distro, it’s obviously not going to work.
If you must run the binary on Linux however, we recommend downloading Wine and using it to run the file. Wine is a compatibility layer capable of running Windows applications on POSIX-compliant operating systems, including Linux and macOS.
Install GCC and Gfortran
GCC and Gfortran are required for several binary files to compile and execute properly. You can install them by typing the command below in your terminal.
sudo apt-get install gfortran && sudo apt-get install build-essential
Now try running your binary file again and it should run without a problem — fixing the ‘cannot execute binary file’ error.
Uncompress the file
Sometimes binary files are compressed to make them easier to share over the internet. Try uncompressing the file to see if that helps you run it fine. Run the following commands on at a time.
xz -d ./filename
chmod +x ./filename
./filename
Check file permissions
Another potential reason for your binary file not running could be that the user doesn’t have permission to change or read the file. You can fix this by typing the following command in the terminal.
chmod +x filename
Once the permissions are set, you can run the file by typing this.
./filename
Use Dos2unix
The Dos2unix command can sometimes help binaries made for DOS to run on UNIX systems. Try using the following command to see if your file runs or not.
dos2unix filename.bin
If we’ve missed out on any fixes that helped you solve the ‘cannot execute binary file’ error, please comment down below with the fix.
Also read: What does ./ mean in Linux?
Someone who writes/edits/shoots/hosts all things tech and when he’s not, streams himself racing virtual cars.
You can contact him here: [email protected]
Содержание
- Решение проблемы с ошибкой «bash: не удаётся запустить бинарный файл: Ошибка формата выполняемого файла»
- О разрядности дистрибутивов Linux и о программ
- Запуск ARM файлов в Linux
- Заключение
- Решение проблемы с ошибкой «bash: не удаётся запустить бинарный файл: Ошибка формата выполняемого файла»
- О разрядности дистрибутивов Linux и о программ
- Запуск ARM файлов в Linux
- Заключение
- Как запустить бинарный файл в Linux
- 8 ответов
- Cannot execute binary file error
- 2 Answers 2
- Not the answer you’re looking for? Browse other questions tagged linux or ask your own question.
- Related
- Hot Network Questions
- Subscribe to RSS
- How to run binary file in Linux
- 11 Answers 11
Решение проблемы с ошибкой «bash: не удаётся запустить бинарный файл: Ошибка формата выполняемого файла»
В операционной системе Linux при запуске скаченного файла, либо при запуске самостоятельно скомпилированного файла вы можете столкнуться с ошибкой:
Если у вас англоязычная локаль, то ошибка будет примерно такой:
Причинами данной ошибки могут быть:
Чтобы получить информацию о файле, который вы пытаетесь запустить, можно использовать утилиту file, после которой укажите путь до файла:
Здесь мы видим, что файл предназначен для 64-битной системы, об этом говорит запись 64-bit, для процессора с архитектурой x86-64.
Этот файл для 32-битных систем, для процессора с архитектурой ARM EABI4.
Если вы не знаете, какой битности ваша система, то выполните команду:
Для 64-битных систем будет выведено x86_64, а для 32-битных – x86.
О разрядности дистрибутивов Linux и о программ
На компьютер с 32-битным процессором вы можете установить только 32-битную операционную систему и в ней запускать только 32-битные программы.
На компьютер с 64-битным процессором вы можете установить как 64-битную ОС, так и 32-битный Linux. В случае, если вы установили 64-битный дистрибутив Linux, то в нём вы можете запускать и 64-битные программы и 32-битные. А если вы установили 32-битный дистрибутив, то в нём возможно запускать только 32-битные программы.
Итак, если у вас 32-битная система, а файл для 64-битной системы или даже для ARM архитектуры, то у вас следующие варианты:
Запуск ARM файлов в Linux
Часто можно запустить исполнимые образы ARM на amd64 системах если установить пакеты binfmt-support, qemu, и qemu-user-static:
Заключение
Итак, ошибка формата выполняемого файла с невозможностью запустить бинарный файл возникает из-за несоответствия программы операционной системе или архитектуре процессора. Эта проблема не должна возникать, если вы установили программу из исходных репозиториев (кроме случаев неправильной настройки источников репозитория). При возникновении этой проблемы поищите файл, подходящий для вашей архитектуры или скомпилируйте файл из исходных кодов под архитектуру вашей операционной системы.
Источник
Решение проблемы с ошибкой «bash: не удаётся запустить бинарный файл: Ошибка формата выполняемого файла»
В операционной системе Linux при запуске скаченного файла, либо при запуске самостоятельно скомпилированного файла вы можете столкнуться с ошибкой:
Если у вас англоязычная локаль, то ошибка будет примерно такой:
Причинами данной ошибки могут быть:
Чтобы получить информацию о файле, который вы пытаетесь запустить, можно использовать утилиту file, после которой укажите путь до файла:
Здесь мы видим, что файл предназначен для 64-битной системы, об этом говорит запись 64-bit, для процессора с архитектурой x86-64.
Этот файл для 32-битных систем, для процессора с архитектурой ARM EABI4.
Если вы не знаете, какой битности ваша система, то выполните команду:
Для 64-битных систем будет выведено x86_64, а для 32-битных – x86.
О разрядности дистрибутивов Linux и о программ
На компьютер с 32-битным процессором вы можете установить только 32-битную операционную систему и в ней запускать только 32-битные программы.
На компьютер с 64-битным процессором вы можете установить как 64-битную ОС, так и 32-битный Linux. В случае, если вы установили 64-битный дистрибутив Linux, то в нём вы можете запускать и 64-битные программы и 32-битные. А если вы установили 32-битный дистрибутив, то в нём возможно запускать только 32-битные программы.
Итак, если у вас 32-битная система, а файл для 64-битной системы или даже для ARM архитектуры, то у вас следующие варианты:
Запуск ARM файлов в Linux
Часто можно запустить исполнимые образы ARM на amd64 системах если установить пакеты binfmt-support, qemu, и qemu-user-static:
Заключение
Итак, ошибка формата выполняемого файла с невозможностью запустить бинарный файл возникает из-за несоответствия программы операционной системе или архитектуре процессора. Эта проблема не должна возникать, если вы установили программу из исходных репозиториев (кроме случаев неправильной настройки источников репозитория). При возникновении этой проблемы поищите файл, подходящий для вашей архитектуры или скомпилируйте файл из исходных кодов под архитектуру вашей операционной системы.
Источник
Как запустить бинарный файл в Linux
8 ответов
и если произойдет сбой, скажем, из-за разрешений, вы можете попробовать это перед выполнением
Надеюсь, это поможет
Возможно, вы скомпилировали бинарный файл с несовместимыми параметрами архитектуры на хосте сборки и хосте выполнения. Можете ли вы взглянуть на включенные настройки цели через
на вашем хосте сборки? В частности, переменная COLLECT_GCC_OPTIONS может дать вам ценную отладочную информацию. Затем взгляните на возможности процессора на хосте выполнения через
Если это не помогает, предоставьте выходные данные ldd commonKT как на хосте сборки, так и на хосте выполнения.
Я только что скомпилировал файл из источника C и установил его для запуска с помощью chmod. От gcc не было ни предупреждений, ни сообщений об ошибках.
Теперь я попытался создать объектный файл, вот так:
С другой стороны, таким образом, выходные данные команды file идентичны вашей:
Тогда как, если я правильно скомпилирую, его вывод будет намного длиннее.
Я говорю следующее: я подозреваю, что это как-то связано с тем, как вы компилируете и связываете свой код. Может быть, вы можете пролить свет на то, как вы это делаете?
Единственный способ, который подходит мне ):
Затем запустите его, написав
Если вы получили ошибку разрешения, вам может потребоваться запустить приложение с привилегиями root:
Если это не опечатка, как указывалось ранее, это может быть неправильными параметрами компилятора, такими как компиляция 64-битной под 32-битной. Это не должен быть набор инструментов.
полный путь для двоичного файла. Например: /home /vitaliy2034 /имя_бинального_файла. Или же используйте директиву «./+binary_file_name». ‘./’ в системе unix возвращает полный путь к каталогу, в котором вы открываете терминал (оболочку). Я надеюсь, что это помогает. Извините за мой английский язык)
Источник
Cannot execute binary file error
I just a ran simple hello world program in my linux it worked perfectly.when i supposed to ran same file in the hand held device (running on the linux os)i got the error like Cannot execute binary file error.i am completely new to linux.
can anybody help me?
2 Answers 2
Just because the OS is the same does not mean an executable will run. The binary file is composed of machine instructions the processor can understand. Moving back and forth between processors with the compatible instruction sets will normally work fine, but if they are not compatible the CPU will not be able to understand the instructions.
Most Intel processors use a x86 ISA (instruction set architecture), that your mobile processor is likely not compatible with.
Just a heads up because I had this problem but the b4-bit application for 32-bit OS didnt work for me. If your in linux you probably need a gcc compiler on the backend of terminal that might not be installed. If you dont have this Linux doesnt seem to know how to read the file.
Not the answer you’re looking for? Browse other questions tagged linux or ask your own question.
Hot Network Questions
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2022 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2022.10.15.40479
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источник
How to run binary file in Linux
11 Answers 11
If you get an error:
it’ll be because it was compiled using a tool chain that was for a different target to that which you’re attempting to run the binary on.
For example, if you compile ‘binary_name.c’ with arm-none-linux-gnueabi-gcc and try run the generated binary on an x86 machine, you will get the aforementioned error.
and if it fails say because of permissions, you could try this before executing it
It is possible that you compiled your binary with incompatible architecture settings on your build host vs. your execution host. Can you please have a look at the enabled target settings via
on your build host? In particular, the COLLECT_GCC_OPTIONS variable may give you valuable debug info. Then have a look at the CPU capabilities on your execution host via
If that doesn’t help, please provide the output of ldd commonKT on both build and execution host.
This is an answer to @craq :
I just compiled the file from C source and set it to be executable with chmod. There were no warning or error messages from gcc.
Now I’ve tried to just create the object file, like so:
( hello.c is a typical «Hello World» program.) But my error message is a bit different:
On the other hand, this way, the output of the file command is identical to yours:
Whereas if I compile correctly, its output is much longer.
What I am saying is: I suspect it has something to do with the way you compile and link your code. Maybe you can shed some light on how you do that?
Источник
The exec format error is a class of errors in the Unix-based operating systems that occurs when a user tries to run a binary file on its system originally intended to run on a different architecture. For example, when the user tries to execute a binary file originally compiled for the ARM (Advanced RISC Machine) on the x86 platform, an ‘exec format error’ is encountered. It is not in this particular case of arm and x86, but it could happen in any permutation of mismatched system architecture. In this article, we will look at this error in some detail and discuss some points that would help resolve this error.
Contents
- 1 What is Exec Format Error?
- 2 Exec Format Error Linux
- 3 Exec format error macOS
- 4 Exec format error java
- 5 Exec format error python
- 6 Exec format error docker
- 7 Exec format error raspberry pi
- 8 How to execute arm binary files on Linux
- 9 FAQs on Exec Format Error
- 9.1 What is the full form of RISC?
- 9.2 Why are arm processors used on mobile devices?
- 9.3 What is the difference between OpenJDK and OracleJDK?
- 10 Conclusion
- 11 Trending Now
What is Exec Format Error?
Different types of computer systems have different kinds of underlying architectures. Here, the term architecture means the circuitry and design of the CPU on how it handles and processes instructions and other computational tasks. System software and applications are compiled differently for a different architecture. Even the operating systems are designed specifically with a particular architecture in mind. There are two mainstream system architectures, The x86_64 and ARM. The x86_64 is mainly used in desktop computers and workstations, and ARM is used in mobile devices such as phones or tablets.
The x86_64 architecture can also be subdivided into 32bit and 64bits types. It represents the CPU’s memory handling capacity. Programs designed for ARM architecture can’t work on x86_64 systems and vice versa. But, the applications built for a 32bit machine can run on a 64bit. All combinations such as CPU architecture, Operating System build, and application design must come in to make everything work properly. And, If anything mismatches, an exec format error can show up.
If you are trying to run incompatible programs or scripts in the Linux environment that doesn’t support the intended architecture, you are more likely to receive an exec format error. Linux itself comes in various forms and flavors in different distros. It is available on both x86_64 and ARM architecture. The most common cause of users receiving exec format errors is when 64bit programs are made to run on 32bit systems. If you are facing this error for a particular program due to an architectural issue, here are a few things that you could do.
- Open the terminal emulator, enter the command uname -m, the m stands for machine. This command would output your system architecture. x86 -> 32 bit x86, x86_64 -> 64bit, arm64 -> ARM.
- After knowing the correct architecture of your system, try to find the your program for that type of compatibility. The 32bit versions of the 64bit programs are ususally available on the internet.
- If you are on a ARM system, then try to download the program through your default package manager as they usually have arm version of most of the programs availbale to install through official repositories.
Exec format error macOS
macOS also throws an exec format error when you execute a program or script intended for a different architecture. This is usually the case with older binary programs that do not work well on modern operating systems. There are ways to execute older OS programs using the zsh shell, but you will have to build the executable yourself.
Download the program’s source code (if available ) you wish to run. Compile the program for your system using macOS’s make compiler. You would have to download make first, part of apple developer tools. It can be downloaded from http://developer.apple.com/.
Exec format error java
Java is a multipurpose, multiplatform object-oriented programming language that is a part of the whole JDK (java development kit). If you are trying to compile a java file on your system but receiving an exec format error instead, then chances are you have installed an incompatible version of the Java JDK on your system. Follow the given step to install the compatible version of JDK on your Linux machine as per the system architecture.
- First check your system architecture using the uname -m command.
- Now Open your Web browser.
- Head to https://www.oracle.com/java/technologies/downloads/#jdk17-linux.
- Now download the compatible version from the download options available.
You could also install the compatible version of JDK on your Linux installation using the default package manager of your distribution. Use the dpkg package manager on Debian-based and Pacman package manager on Arch-based Linux to install the correct implementation of java on your system.
Exec format error python
Python throws an exception in the form of exec format error. The python subprocess library provides the ability to run shell commands through the python interpreter. If any incompatible command or program is encountered during the python script, the python interpreter throws an OS exception. If you are running bash shell scripts through the subprocess library, keep the following points in mind to avoid exec format errors in python.
- Add !/bin/sh in the top first line of your shell script file.
- Use os library’s path method to open your .sh file, instead of opening it directly.
- Make sure the script file has executable permission.
Exec format error docker
Docker is a software platform that provides operating system-level isolation environments called containers. The containers provide different separate development environments for specific projects or purposes. Users are reported to have been facing exec format errors while running the docker test command on their environment. This happens due to a missing statement in the script file. Run the following command to run the docker test without format error.
docker run -entrypoint="/bin/bash" -i test
Exec format error raspberry pi
Raspberry pi is a small form-factor mini computer. It is a small computer that runs on low voltage power and has an ARM processor installed on it. The exec format error is frequently encountered in the raspberry pi as people often try to execute x86_64 on raspberry pi’s arm processor.
To avoid this error on the raspberry pi you have two potential options. You could either download the pi-compatible arm binary executables from their official repositories or download the program’s source code and compile it yourself for your intended system architecture. Luckily, Rasberry pi comes with its package manager apt (advance packaging tool) that can be used to install arm binaries on your raspberry pi.
How to execute arm binary files on Linux
Arm binary files are not directly executable on x86_64 Linux. The file command is used in Linux to check the file type in Linux. You can check the type and architecture of your file using it. If you want to run the arm files natively on Linux, you could download a package such as qemu, which could run the native arm files on the x86_64 machine. Follow the given steps to download and install the qemu to execute arm binaries on Arch.
- Open the terminal. (ctrl + alt + t )
- type sudo pacman -S qemu.
- Enter the root password.
- Enter Y when prompted and let the download finish.
- After installation use the syntex qemu <filename> to execute the binary.
FAQs on Exec Format Error
What is the full form of RISC?
RISC is short for Reduced Instruction Set Cycle.
Why are arm processors used on mobile devices?
Because they are more power-efficient than their x86_64 counterparts.
What is the difference between OpenJDK and OracleJDK?
The OracleJDK is completely developed by the Oracle Corporation, and the OpenJDK is a community-driven and open-source version in which everyone contributes.
Conclusion
Different computer architectures have different executables binary files, and one type is not compatible with another. An exec format error occurs if the user tries to execute another file type in a different environment. In this article, we discussed why the error occurs. We gave instructions to install the compatible JDK to eradicate java-specific exec format errors and provided instructions on how to execute arm binaries on x86_64 Linux.
Trending Now
-
Resolve Error Code E4301 Using These 4 Exciting Methods
●October 20, 2022
-
15 Incredible Ways to Fix Paramount Plus Keeps Pausing Error
by Amal Santosh●October 20, 2022
-
5 Strategies to Fix Adobe Short Media Token Validation Error Invalid Signature
by Amal Santosh●October 11, 2022
-
Fix the Apple TV 4K Turns off by Itself with 7 Wonderful Ways
by Amal Santosh●October 11, 2022
When I login using SSH, all I can see is this…
-bash: /usr/bin/id: cannot execute binary file
-bash: [: : integer expression expected
I couldn’t do anything in here. Commands such as halt
, poweroff
, reboot
will return command not found
.
How can I fix this? I am using Debian Squeeze Linux
asked Jun 12, 2012 at 21:26
9
Usually that error message means Linux doesn’t recognize the file as a shell script or as an executable file.
Typically the cause is running an executable on the wrong architecture — if you try to run x86 executables on an ARM CPU, this message comes up.
Did /usr/bin/id
get overwritten, possibly?
answered Jun 13, 2012 at 3:07
LawrenceCLawrenceC
72k15 gold badges123 silver badges211 bronze badges
4
Try to run it using ./executablefilename instead of using sh executablefilename. It’s not a shell script after all.
answered Jun 13, 2012 at 1:27
RidDeBakTiYarRidDeBakTiYar
5563 gold badges6 silver badges10 bronze badges
1
The problem is running a binary for a different processor architecture.
You can use objdump (from binutils) to check architecture of binaries.
You can use uname to check architecture of a machine.
e.g. I encountered this error «cannot execute binary file» when installing FF.Communicator — a firefox plugin for chrome (so I can run pages that use java applets).
- objdump shows the binary is 64-bit elf64-x86-64
-
uname shows my machine is 32-bit i686
$ ./FF.Communicator
bash: ./FF.Communicator: cannot execute binary file
$ uname -mpio
i686 i686 i386 GNU/Linux
$ objdump -a ./FF.Communicator
./FF.Communicator: file format elf64-x86-64
./FF.Communicator -
objdump on a working binary on my machine shows it is 32-bit elf32-i386
$ objdump -a /bin/ls
/bin/ls: file format elf32-i386
Using these tools you can check architectures of machines and binaries — not just intel architectures but any processor.
For Mac OSX users, you can find out the architecture info of a specific file using the «file» command:
$ file filename_here
answered Jun 19, 2015 at 11:55
gaoithegaoithe
5114 silver badges8 bronze badges
I’m making some wild guesses here, but it looks like the following is happening:
- You log in over SSH, triggering
bash
to run your~/.profile
or~/.bashrc
to set up your environment for you (this is normal). - At some point it tries to execute
/bin/id
to get your uid, which fails, causing integer expression error, and terminating the script before it can set up your$PATH
. - Because your
$PATH
is not set, bash is only able to run commands with the full path specified.
Use export PATH=/bin:/usr/bin:/sbin:/usr/sbin
to fix the $PATH
issue until you can fix the root cause of /bin/id failing.
answered Jun 12, 2012 at 21:51
Darth AndroidDarth Android
37.5k5 gold badges94 silver badges111 bronze badges
This means that you are trying to execute a binary file using your bash script which is not intended to be run as you trying it to be. It is already a binary file and you are trying your $SHELL to parse and run it.
in a very simple example, if you try to run `w’ command like
$ bash w
/usr/bin/w: /usr/bin/w: cannot execute binary file
similarly you might be hitting the same method or as it looks from your code snippet.
While , for the remaining for your commands, Al these halt, shutdown , reboot etc commands are the root owned commands and need super-user prilveges to run and perform the required operation. normal users can’t run them
another explanation is that these commands are placed at /sbin/ and /usr/sbin , which might not be in your $PATH variable ( which is used to validate commands in your custody )
answered Oct 24, 2018 at 14:01
1
binary file consists of machine instructions the processor can understand.
Your operating system does not mean the same executable will run.
move back and forth between the processor instruction set compatible with will usually work well,
if they are not compatible CPU will not be able to understand instructions.
answered Jun 12, 2012 at 22:29
You are running wrong version of the installer, for example, 64bit machine and trying to install 32bit version of the installer.
answered Jul 25, 2018 at 8:43
While it shouldn’t happen when using the official apt-get repositories, if you download software off the Internet and run it then there’s a chance that you’ll see the dreaded bash: ./nameOfProgram: cannot execute binary file: Exec format error. This error, which is usually followed by bash: ./nameOfProgram.sh: Permission denied or something like it, indicates that Ubuntu wasn’t able to interface correctly with the binary you downloaded. This is because while it’s apparently a valid Linux binary, it’s designed for a different chipset than your kernel currently supports.
Most people using Ubuntu are on 32-bit or 64-bit processors based around a standard architecture that Intel released, regardless of who actually made their microchips. It’s important to remember that 64-bit processors can run in 32-bit mode, so if you’re getting this error even though you have a 64-bit processor there’s a chance you’re running a 32-bit version of Ubuntu. A few simple commands are all it takes to tell what your chip is operating as.
Method 1: Using the arch Command
If you’re not familiar with the type of microprocessor that you have installed on your machine, then you’ll first want to use the arch command from the command line. You’ll only see a single line of output returned to you after running this command. In many cases, you’ll see i686, which means that you’re on a 32-bit processor and therefore can’t run x86_64 binaries. If you instead see amd64 or something similar, then you’re on an x86_64 processor, and should at least theoretically be able to run most 32-bit and 64-bit binaries. Unlike Microsoft Windows, Ubuntu Linux actually contains the proper tools to permit users of 644-bit chipsets to run 16-bit Windows programs in their operating system in many cases as well.
These terms are still true even if you’re not actually using that particular model of microchip. For instance, i686 is how Linux refers to many 32-bit processors even if they aren’t actually Intel 80686 chips. Even if you’re using 64-bit Intel technology, arch might still call your processor an amd64 chip. This doesn’t indicate an error, and can be safely ignored. You can use cat /proc/cpuinfo or more /proc/cpuinfo to find out the exact type of processor you’re using. Since the lines in this file are long, you might want to push F11 before issuing it if you’re using a graphical terminal window. Users of a virtual console, especially those working with Ubuntu server, won’t have to worry quite as much.
You may see some other types of output, which might further restrict your options when it comes to running software. Ubuntu supported PowerPC architecture for the longest time, which is found in some workstations as well as many Classic Macintosh and older OS X Macintosh machines. You can actually still find Ubuntu repositories for these architectures, though they receive little support today. However, you more than likely won’t be able to run many Linux binaries you download from the Internet outside of the official repositories in this case. That doesn’t mean that Ubuntu doesn’t work on these machines, though you may want to look at the lighter Lubuntu distribution.
Method 2: Using the file Command
The file command identifies what different files contain, and it’s usually very accurate. Try identifying the file in question by typing file nameOfProgram to see if you get ELF 32-bit or ELF 64-bit as output. If it tells you that it’s an ELF 64-bit binary and you received i686 as output from the arch command, then there’s no way you can reasonably run it on your machine. If you’re on a 64-bit microprocessor running 32-bit Ubuntu, then you could technically reinstall the operating system, though this is a bit of an extreme step in order to run a single program.
There is also the very real possibility, however slight, that you might instead come across a binary that when you attempt to run it spews out junk characters to the terminal even if you’ve run a malware scan on it. These characters usually take the form of either lozenge-shaped blocks, or alternatively rectangular cubes that have numerical values in them. Some computer scientists call the latter tofu, and represent the Unicode values of characters that your currently installed typefaces won’t be able to display. If the terminal is displaying them like this, then you can rest assured that this is neither a font error nor anything having to do with malware. Rather, this is simply because the compiled microprocessor opcode inside of the binary is so alien to your system that it doesn’t know how to interpret some of the code.
The best way to fix this is to install the proper package for your architecture. If you’re installing packages from inside Ubuntu, then the apt-get system or the graphical Synaptic manager has you covered without any problems. If you’re downloading packages from another distribution, then you’ll need to find the right one for your architecture. Take, for example, Arch Linux’s listing of the gvim package. While the default package features the x86_64 architecture, there’s also one for the i686 chipset. This one will work on 32-bit machines that work with the Intel interrupt structure, but remember that the terms i686 and 32-bit are not mutually inclusive all the time since other chipsets Linux supports actually do feature their own 32-bit implementations.
Users exploring the whole GNU/Linux scene might come across binaries compiled for far more exotic technologies than these. Linux is truly a cross-platform code scene, so you’ll see OpenRISC, MIPS, SPARC, M32R, MN103, ARM, ARC, Alpha and many other standards binaries are compiled to work with. More than likely, you won’t be able to run any of these, though ARM is an extremely popular tablet and smartphone platform. It’s also the platform that the Raspberry Pi is based around, which means if you’re actually running Ubuntu on a mobile device or the Ubuntu MATE distribution for Raspberry Pi you’ll actually need these instead of Intel 32-bit or x86_64 binaries.
Kevin Arrows
Kevin is a dynamic and self-motivated information technology professional, with a Thorough knowledge of all facets pertaining to network infrastructure design, implementation and administration. Superior record of delivering simultaneous large-scale mission critical projects on time and under budget.