Linux architecture x86 64

Ассемблер для Linux. Архитектура x86-64 для прикладного программиста (книга)

На канале Old Programmer продолжение книги о программирование на языке ассемблера в операционной системе Linux. Материал будут выходить регулярно до осени, когда я должен закончить книгу о GAS .

Архитектура x86-64 для прикладного программиста

Как уже было отмечено в первой главе ( см. например, параграфы 1.1 и параграф 1.4 ) память процессора состоит из регистров. При выполнении программы происходит обмен данными между оперативной памятью и регистрами. Есть две причины почему такой обмен необходим:

1. Количество команд, которые выполняются над данными, хранящимися в регистрах, больше, чем над данными, хранящимися в оперативной памяти. Например среди команд x86-64 нет команды сложения двух операндов, когда оба хранятся в оперативной памяти. Но есть команды сложения когда оба операнда находятся в регистрах или один операнд находится в регистре, а другой в оперативной памяти.

2. Операции над данными в регистрах выполняются быстрее аналогичных операций над данными в оперативной памяти.

Поскольку количество регистров не велико, то приходится постоянно перебрасывать данные из памяти в регистры и обратно.

В параграфе 1.7 мы довольно подробно рассмотрели вопрос о том, как числа хранятся в памяти. Ячейки оперативной памяти имеют однобайтовый размер, но для удобства они могут объединяться в 2 байта, 4 байта и 8 байтов. Соответственно и на ассемблере можно оперировать одно-, двух-, четырех- и восьмибайтовыми числами. Есть некоторые различия в том, как это происходит с данными, хранящимися в регистрах и данными, хранящимися в ячейках памяти. В этом параграфе мы рассмотрим регистровую память, а в следующем параграфе (2.2) будем говорить об оперативной памяти.

Обратимся к рисунку 7. На нем представлена вся архитектура процессоров x86-64, знания о которой необходимы прикладному программисту, пишущему на языке ассемблера. Программист, использующий в своей работе ассемблер, должен знать регистры процессора, их свойства и команды процессора. В первую очередь нам будут нужны регистры общего назначения (GPR — General-Purpose Registers). Именно они в большей части и используются при программировании на ассемблере. Мультимедийным регистрам (регистрам чисел с плавающей точкой) и регистрам расширения SSE будут посвящены отдельные главы. SSE — Streaming SIMD Extensions, т.е. потоковое SIMD расширение процессора. SIMD это Single Instruction, Multiple Data, т.е. одна конструкция и много данных. Кроме того, отдельно будет рассмотрен регистр флагов, необходимый для проверки условий, а также для выполнения некоторых других операций. Регистр указателя на команду rip содержит всегда адрес следующей выполняемой процессором команды. Обычно программно к нему напрямую не обращаются.

И так нас будут интересовать регистры общего назначения, которые на рисунке находятся в левом столбце. Заметим, что эти регистры также имеют свою собственную структуру. Фактически каждый из них состоит из нескольких регистров. Их структура представлена в таблице 1. Рассмотрим, например, регистр rcx . Его длина составляет 8 байтов (64-бита). Однако у отдельных частей регистра имеются свои названия и к ним можно обращаться как к самостоятельным регистрам: есх — регистр обозначает первые 4 байта регистра rcx , регистр cx — первые два байта регистра rcx (обычно это называют словом), наконец можно получить доступ к старшему ( ch ) и младшему ( cl ) байту слова. Заметим в этой связи, что к старшему байту слова можно получить прямой доступ только у регистров rax , rbx , rcx , rdx (см. таблицу 1).

Читайте также:  Linux command line timing

Мы можем писать команды передачи данных из одного регистра в другой, но с учетом их размеров. Например, можно написать

mov %rcx, %r8 # переслать данное из регистра rcx в регистр r8
mov %ah, %r15b # переслать данное из регистра ah в младший байт регистра r15

Подписываемся на мой канал Old Programmer , пишем свои комментарии и ждем новых статей об ассемблере .

Источник

How to detect 386, amd64, arm, or arm64 OS architecture via shell/bash

I’m looking for a POSIX shell/bash command to determine if the OS architecture is 386 , amd64 , arm , or arm64 ?

6 Answers 6

@YoloPerdiem they’re the same in the specific case that I was mentioning (Raspberry), but according to your link dpkg —print-architecture would be more accurate as the question is about OS architecture.

prints values such as x86_64 , i686 , arm , or aarch64 .

@Justin 64-bit was introduced in ARM v8, so armv7l means 32-bit little-endian ARM. That being said, if you’re on an RPi3: the processor is actually 64-bit, but if your OS is in 32-bit mode it reports an older model.

This works great on macOS until you have the terminal app running through Rosetta. it will return x86_64.

I went with the following:

architecture="" case $(uname -m) in i386) architecture="386" ;; i686) architecture="386" ;; x86_64) architecture="amd64" ;; arm) dpkg --print-architecture | grep -q "arm64" && architecture="arm64" || architecture="arm" ;; esac 

While you’re at it, you might as well collapse the first two branches in your case logic to i386 | i686) architecture=»386″ ;; It’s always good to include a catch-all branch at the end, too, to the effect of *) echo «Unable to determine system architecture.»; exit 1 ;;

@DUzun: That’s correct, x86_64 and amd64 are basically synonyms. AMD developed the ISA initially, then Intel implemented it, so some software still uses «amd64» as the architecture name. This is unrelated to whether your AMD64 CPU was sold by Intel, AMD, Via, Zhaoxin, or is emulated by QEMU or Bochs or whatever on totally different hardware. See The most correct way to refer to 32-bit and 64-bit versions of programs for x86-related CPUs?

Читайте также:  User group others linux

Источник

How to find the processor / chip architecture on Linux

uname -m gives you back i686 or x86_64 depending on 32-bit or 64-bit Intel CPU, but I don’t have access to machines on non-Intel architectures.

x86_64 or amd64 would be 64-bit. i386, i486, i586, and i686 are 32-bit. Keep in mind however that those values are merely a reflection of the target the kernel was compiled for and not necessarily what the CPU is capable of.

6 Answers 6

To display kernel architecture: uname -p

To display extended CPU details: cat /proc/cpuinfo

uname (with any options) will only show the kernel architecture, not the physical CPU architecture. In other words, it will show which CPU the kernel was compiled for. But that could show i386 even when running on a x86_64 CPU.

which returns output like this:

Architecture: i686 CPU op-mode(s): 32-bit, 64-bit Byte Order: Little Endian CPU(s): 2 On-line CPU(s) list: 0,1 Thread(s) per core: 1 Core(s) per socket: 2 Socket(s): 1 Vendor ID: GenuineIntel CPU family: 6 Model: 23 Stepping: 6 CPU MHz: 2670.000 BogoMIPS: 5320.13 L1d cache: 32K L1i cache: 32K L2 cache: 3072K 

To only get the architecture:

I’m surprised no one suggested uname -m . On my laptop, this gives armv7l , while uname -a gives me a monstrous two lines of text.

A concise command producing information about the current machine is hostnamectl . Example output:

Static hostname: xxxx Icon name: computer-laptop Chassis: laptop Boot ID: b3a1f952c514411c8c4xxxxxxxxxxxx Operating System: Ubuntu 14.04.3 LTS Kernel: Linux 3.19.0-43-generic Architecture: x86_64 

It gives you the most basic information about your machine. Other commands like uname , lsb_release , or lscpu return more specific information.

Источник

How to find architecture of my PC and Ubuntu?

Can someone please explain to me why both i386 & i686 ? What exactly is my PC architecture and what version of Ubuntu am I using (32bit or 64bit)?

is this a complete output from uname -a? I assume some fields like the kernel-name, kernel-version etc are missing.

5 Answers 5

Open a terminal try using uname -m command. This should show you the OS architecture.

If it gives any output like ix86 , where x is 3,4,5 or 6, Your OS is 32bit.

You can also see the Ubuntu architecture by Opening «System monitor» and going in the System tab.

enter image description here

Difference between hardware platform and Processor type:

There is a difference between the hardware platform (which is given by -i switch) to the CPU type (given by -p switch).

The hardware platform tells us which architecture the kernel is built for (may be optimized though for later versions). It can be a i386.

Читайте также:  Kali linux install exe

However the Processor type refers to the actual processor type of your machine such as i686 (P4 and later builds).

Thanks to Schotty of this this page. Here is an answer from Unix stackexchange site on the same topic, though I didn’t find the language enough clear (completely my fault).

On uname -m , it says i686,what does this mean? and my system monitor window says «Release 11.10(oneiric) Kernel Linux 3.0.0-26-generic GNOME 3.2.1» It doesn’t specifies any thing,like one shown in your pic.

@Ubunu_beginner, i386 and i686 are both part of the x86 family of processors. They just refer to the specific age of the processor platform. i386 is an older platform (early 90s?) used back when 386 processors were used in machines. Then this was upgraded to 486 processors, which was the same basic instruction set as 386 just faster and newer. 586 was another upgraded and was when the term Pentium started floating around. Eventually all of these got encapsulated into the x86 architecture name. i686 just refers to the 6th generation of x86 architecture.

@frank Thank you. Actually it was the gnome-system-monitor before gnome migrated to version 3. And I forgot the theme name. But You can use same system monitor by installing mate-system-monitor application

Use Anwar’s answer to find the architecture.

Now here is the explanation for your second part of the question.

Below is the uname output: In my case I have installed a 32 bit version. Both i386 and i686 refer 32 bit version. uname will return x86_64 in case if it is a 64 bit version.

$ uname -a Linux devav2 3.2.0-30-generic-pae #48-Ubuntu SMP Fri Aug 24 17:14:09 UTC 2012 i686 i686 i386 GNU/Linux 
  • Linux(-s) — OS/Kernel name
  • devav2(-n) — hostname
  • 3.2.0-30-generic-pae (-r) — kernel release
  • 48-Ubuntu SMP Fri Aug 24 17:14:09 UTC 2012 (-v) — Kernel version with time and SMP stands for symmetric multiprocessing, which means you have multiprocessor support
  • i686(-m) — Machine hardware name
  • i686(-p) — processor type
  • i386(-i) — hardware platform
  • GNU/LINUX(-o) — Operating System name

Below is grabbed from uname —help page which might help you to understand more about it.

 -a, --all print all information, in the following order, except omit -p and -i if unknown: -s, --kernel-name print the kernel name -n, --nodename print the network node hostname -r, --kernel-release print the kernel release -v, --kernel-version print the kernel version -m, --machine print the machine hardware name -p, --processor print the processor type or "unknown" -i, --hardware-platform print the hardware platform or "unknown" -o, --operating-system print the operating system 

Источник

Оцените статью
Adblock
detector