How to run a program without an operating system

Most users of the Windows operating system are accustomed to launching the desired application or game by double-clicking on a shortcut located on the desktop or by finding it in Start. Alternatively, you can open the folder in which it is installed and run the exe file from there.

Since launching applications this way may not always be suitable, in this article let's look at several different methods that can be used to launch a program from the command line.

First you need to open a console window. How to do this is described in detail in the article: calling the Windows command line.

Closing the program

With the application open, first save all open documents. Typically, the File>Save command is used for this. In some programs, you can click the application button and select Save As. Then close the application using one of the following methods:

  • click on the Close located in the upper right corner of the window and represented as a diagonal cross;
  • press the key combination to close the active open window;
  • Select File > Exit from the program menu

The application will end. If you haven't saved changes to any open document before closing the application, a window will appear asking if you want to save the document. Click the Save or Don't Save depending on whether you want to save your changes.

To save the document before closing the application, select File>Save and in the Save Document dialog box that appears, use the settings to give the file a name and specify the folder in which to save it.

Please note that the File>Exit command closes all open documents in the application. Use File>Close to close only the currently active document, leaving the application and other open documents open.

You shouldn't close one application to open or switch to another. To switch between open applications, press a key combination and use the arrow keys to navigate to that application (or to a document if the application you want to work in has multiple documents open).

Share.

More on the topic:

  • How to assign hot keys to quickly launch programs In the Windows operating system, developers have provided the ability for the user to assign hot keys to quickly open programs. If a program has a shortcut to launch it in [...]
  • Exchange of data between programs The Windows operating system is multitasking. This means that it can run multiple programs at the same time. Their number is limited only by the performance of the computer [...]
  • Programs for working with pictures in Windows Digital images are worked in special programs - graphic editors. Programs of this class are no less than text programs, and they are inconvenient to perform specific tasks in it. […]
  • How to properly format a flash drive on Windows and Mac If the flash drive starts to work unstable and some devices stop “seeing” it, it may be enough to format it to solve the problem. But it is important to understand that all the data […]
  • The best programs for cleaning your computer and optimizing Windows Sometimes there comes a time when a brand new and flying Windows turns into a slow tractor that dulls over the simplest tasks and forces the user to […]

How to run a program without an operating system

It so happened that in our article describing the PCI bus polling mechanism, the most important thing was not described in sufficient detail: how to run this code on real hardware? How to create your own boot disk? In this article we will answer all these questions in detail (partially these questions were discussed in the previous article, but for ease of reading we will allow ourselves a slight duplication of material). There are a huge number of descriptions and tutorials on the Internet about how to write your own mini-OS; there are even hundreds of ready-made small hobby OSes. One of the most worthy resources on this topic, which I would like to especially highlight, is the osdev.org portal. To complement the previous article about PCI (and the opportunity to write subsequent articles about the various functions that are present in any modern OS), we will describe step-by-step instructions for creating a boot disk with a familiar program in C. We tried to write in as much detail as possible so that everything is possible figure it out on your own.

So, the goal: with as little effort as possible, create your own bootable flash drive, which just prints the classic “Hello World” on the computer screen.

To be more precise, we need to “get into” protected mode with page addressing and interrupts disabled - the simplest mode of processor operation with familiar behavior for a simple console program. The smartest way to achieve this goal is to build a kernel that supports the multiboot format and boot it using the popular Grub boot loader. An alternative to this solution is to write your own volume boot record (VBR), which would load your own written loader. A decent bootloader, at a minimum, should be able to work with a disk, with a file system, and parse elf images. This means that you need to write a lot of assembly code, and a lot of code in C. In short, it’s easier to use Grub, which can already do everything you need.

Let's start with the fact that for further actions you need a certain set of compilers and utilities. The easiest way is to use some Linux (for example, Ubuntu), since it will already contain everything you need to create a bootable flash drive. If you are used to working on Windows, you can set up a virtual machine with Linux (using Virtual Box or VMware Workstation).

If you are using Linux Ubuntu, then first of all you need to install several utilities: 1. Grub. To do this we will use the command:

sudo apt-get install grub

2. Qemu. It is needed to quickly test and debug everything, for this the command is similar:

sudo apt-get install qemu

Now our plan looks like this: 1. Create a C program that prints a string on the screen. 2. build an image from it (kernel.bin) in miniboot format so that it is available for boot using GRUB. 3. create a boot disk image file and format it. 4. install Grub on this image. 5. copy the created program (kernel.bin) to disk. 6. burn the image to physical media or run it in qemu.

and the system boot process:

For everything to work, you will need to create several files and directories:

kernel.c Program code written in C. The program prints a message on the screen.
makefile Makefile, a script that does all the building of the program and creating the boot image.
linker.ld Linker script for the kernel.
loader.s Assembly code that is called by Grub and passes control to the main function from the C program.
include/ Folder with header files.
grub/ Folder with Grub files.
common/ General purpose folder. Including the implementation of printf.

Step 1. Creating the code for the target program (kernel):

Create a file kernel.c, which will contain the following code that prints a message on the screen:

#include "printf.h" #include "screen.h" #include "types.h" void main(void) { clear_screen(); printf("\n>>> Hello World!\n"); }

Everything here is familiar and simple. Adding the printf and clear_screen functions will be discussed further. In the meantime, we need to supplement this code with everything necessary so that it can be loaded by Grub. In order for the kernel to be in multiboot format, the first 8 kilobytes of the kernel image must contain the following structure:

0x1BADB002 = MAGIC Multiboot format signature
0x0 = FLAGS Flags that contain additional requirements for loading the kernel and parameters passed by the bootloader to the kernel (our program). In this case, all flags are cleared.
0xE4524FFE= -(MAGIC + FLAGS) Check sum.

If all the specified conditions are met, then Grub passes a pointer to the multiboot Information structure and the value 0x1BADB002 through the %eax and %ebx registers, respectively. The multiboot Information structure contains various information, including a list of loaded modules and their location, which may be needed for further booting of the system. In order for the program file to contain the necessary signatures, we will create a loader.s file with the following contents:

.text .global loader # making entry point visible to linker # setting up the Multiboot header — see GRUB docs for details .set FLAGS, 0x0 # this is the Multiboot 'flag' field .set MAGIC, 0x1BADB002 # 'magic number' lets bootloader find the header .set CHECKSUM, -(MAGIC + FLAGS) # checksum required .align 4 .long MAGIC .long FLAGS .long CHECKSUM # reserve initial kernel stack space .set STACKSIZE, 0x4000 # that is, 16k. .lcomm stack, STACKSIZE # reserve 16k stack .comm mbd, 4 # we will use this in kmain .comm magic, 4 # we will use this in kmain loader: movl $(stack + STACKSIZE), %esp # set up the stack movl %eax, magic # Multiboot magic number movl %ebx, mbd # Multiboot data structure call main # call C code cli hang: hlt # halt machine should kernel return jmp hang

Let's look at the code in more detail. This code, almost unchanged, is taken from wiki.osdev.org/Bare_Bones. Since gcc is used for compilation, GAS syntax is used. Let's take a closer look at what this code does.

.text All subsequent code will end up in the executable .text section. .global loader Declare the loader symbol visible to the linker. This is required because the linker will use the loader as an entry point. .set FLAGS, 0x0 # assign FLAGS = 0x0 .set MAGIC, 0x1BADB002 # assign MAGIC = 0x1BADB002 .set CHECKSUM, -(MAGIC + FLAGS) # assign CHECKSUM = -(MAGIC + FLAGS) .align 4 # align subsequent data to 4 bytes .long MAGIC # place the value of MAGIC at the current address .long FLAGS # place the value of FLAGS at the current address .long CHECKSUM # place the value of CHECKSUM at the current address This code generates a Multiboot format signature. The .set directive sets the value of a character to the expression to the right of the comma. The .align 4 directive aligns subsequent content to 4 bytes. The .long directive stores the value in the next four bytes. .set STACKSIZE, 0x4000 # set STACKSIZE = 0x4000 .lcomm stack, STACKSIZE # reserve STACKSIZE bytes. stack refers to the range .comm mbd, 4 # reserve 4 bytes for the mdb variable in the COMMON area .comm magic, 4 # reserve 4 bytes for the magic variable in the COMMON area Grub does not configure the stack during boot, and the first thing the kernel must do is configure stack, for this we reserve 0x4000(16Kb) bytes. The .lcomm directive reserves the number of bytes specified after the decimal point in the .bss section. The stack name will only be visible in the compiled file. The .comm directive does the same as .lcomm, but the symbol name will be declared globally. This means that by writing the following line in C code, we can use it. extern int magic

And now the last part:

loader: movl $(stack + STACKSIZE), %esp # initialize the stack movl %eax, magic # write %eax to the address magic movl %ebx, mbd # write %ebx to the address mbd call main # call the main function cli # disable interrupts from hardware hang: hlt # stop the processor until an interrupt occurs jmp hang # jump to the hang label

The first instruction stores the value at the top of the stack in the %esp register. Since the stack grows downwards, the address of the end of the range allocated for the stack is written to %esp. The next two instructions store in previously reserved 4-byte ranges the values ​​that Grub passes in the %eax, %ebx registers. Then the main function is called, which is already written in C. If this procedure returns, the processor will go into a loop.

Step 2. Preparing additional code for the program (system library):

Since the entire program is written from scratch, the printf function must be written from scratch. To do this, you need to prepare several files. Let's create a common and include folder:

mkdir common mkdir include

Let's create a file common\printf.c, which will contain an implementation of the familiar printf function. This entire file can be taken from the www.bitvisor.org project. Path to the file in the bitvisor sources: core/printf.c. In the printf.c file copied from bitvisor, for use in the target program you need to replace the lines:

#include "initfunc.h" #include "printf.h" #include "putchar.h" #include "spinlock.h" on lines: #include "types.h" #include "stdarg.h" #include "screen. h"

Then, remove the printf_init_global function and all its references in this file:

static void printf_init_global(void) { spinlock_init(&printf_lock); } INITFUNC("global0", printf_init_global);

Then remove the printf_lock variable and all references to it in this file:

static spinlock_t printf_lock; ... spinlock_lock (&printf_lock); ... spinlock_unlock (&printf_lock);

The printf function uses the putchar function, which also needs to be written. To do this, create a file common\screen.c with the following content:

#include "types.h" #define GREEN 0x2 #define MAX_COL 80 // Maximum number of columns #define MAX_ROW 25 // Maximum number of rows #define VRAM_SIZE (MAX_COL*MAX_ROW) // Size of screen, in short's #define DEF_VRAM_BASE 0xb8000 // Default base for video memory static unsigned char curr_col = 0;8) static unsigned char curr_row = 0; // Write character at current screen location #define PUT(c) ( ((unsigned short *) (DEF_VRAM_BASE)) \ [(curr_row * MAX_COL) + curr_col] = (GREEN << | (c)) // Place a character on next screen position static void cons_putc(int c) { switch (c) { case '\t': do { cons_putc(' '); } while ((curr_col %8) != 0); break; case '\r': curr_col = 0; break; case '\n': curr_row += 1; if (curr_row >= MAX_ROW) { curr_row = 0; } break; case '\b': if (curr_col > 0) { curr_col -= 1; PUT(' '); } break; default: PUT(c); curr_col += 1; if (curr_col >= MAX_COL) { curr_col = 0; curr_row += 1; if (curr_row >= MAX_ROW) { curr_row = 0; } } }; } void putchar( int c ) { if (c == '\n') cons_putc('\r'); cons_putc(c); } void clear_screen( void ) { curr_col = 0; curr_row = 0; int i; for (i = 0; i < VRAM_SIZE; i++) cons_putc(' '); curr_col = 0; curr_row = 0; }

The specified code contains simple logic for printing characters to the screen in text mode. In this mode, two bytes are used to record a character (one with the character code, the other with its attributes), written directly to the video memory displayed immediately on the screen and starting at address 0xB8000. The screen resolution is 80×25 characters. The character is directly printed using the PUT macro. Now only a few header files are missing: 1. The include\screen.h file. Declares the putchar function, which is used in the printf function. File contents:

#ifndef _SCREEN_H #define _SCREEN_H void clear_screen( void ); void putchar(int c); #endif

2. File include\printf.h. Declares the printf function, which is used in main. File contents:

#ifndef _PRINTF_H #define _PRINTF_H int printf (const char *format, ...); #endif

3. File include\stdarg.h. Declares functions for enumerating arguments, the number of which is not known in advance. The entire file is taken from the www.bitvisor.org project. Path to the file in the bitvisor project code: include\core\stdarg.h. 4. File include\types.h. Declares NULL and size_t. File contents:

#ifndef _TYPES_H #define _TYPES_H #define NULL 0 typedef unsigned int size_t; #endif Thus, the include and common folders contain the minimum system library code that any program needs.

Step 3: Create a script for the linker:

We create a file linker.ld, which will be used by the linker to generate the target program file (kernel.bin). The file should contain the following:

ENTRY (loader) LMA = 0x00100000; SECTIONS { . = LMA; .multiboot ALIGN (0x1000) : { loader.o( .text ) } .text ALIGN (0x1000) : { *(.text) } .rodata ALIGN (0x1000) : { *(.rodata*) } .data ALIGN (0x1000 ) : { *(.data) } .bss : { *(COMMON) *(.bss) } /DISCARD/ : { *(.comment) } }

The built-in function ENTRY() allows us to set the entry point for our kernel. It is to this address that grub will transfer control after loading the kernel. The linker will use this script to create a binary file in ELF format. An ELF file consists of a set of segments and sections. The list of segments is contained in the Program header table, the list of sections in the Section header table. The linker operates with sections, the image loader (in our case, GRUB) with segments.

As can be seen in the figure, segments consist of sections. One of the fields that describes a section is the virtual address where the section should be located at the time of execution. In fact, a segment has 2 fields that describe its location: the virtual address of the segment and the physical address of the segment. The virtual address of a segment is the virtual address of the first byte of the segment at the time the code is executed, the physical address of the segment is the physical address at which the segment should be loaded. For application programs, these addresses are always the same. Grub loads image segments by their physical address. Since Grub does not configure page addressing, the virtual address of a segment must match its physical address, since virtual memory is also not configured in our program.

SECTIONS Indicates that the following sections are described. . = LMA; This expression tells the linker that all subsequent sections are after the LMA address. ALIGN (0x1000) The above directive means that the section is aligned at 0x1000 bytes. .multiboot ALIGN (0x1000) : { loader.o( .text ) } A separate multiboot section, which includes the .text section from the loader.o file, is made to ensure that the multiboot format signature is included in the first 8kb of the kernel image. .bss : { *(COMMON) *(.bss) } *(COMMON) is the area in which memory is reserved by the .comm and .lcomm instructions. We place it in the .bss section. /DISCARD/ : { *(.comment) } All sections marked DISCARD are removed from the image. In this case, we remove the .comment section, which contains information about the linker version.

Now let's compile the code into a binary file using the following commands:

as -o loader.o loader.s gcc -Iinclude -Wall -fno-builtin -nostdinc -nostdlib -o kernel.o -c kernel.c gcc -Iinclude -Wall -fno-builtin -nostdinc -nostdlib -o printf.o -c common/printf.c gcc -Iinclude -Wall -fno-builtin -nostdinc -nostdlib -o screen.o -c common/screen.c ld -T linker.ld -o kernel.bin kernel.o screen.o printf .o loader.o Using objdump, let's look at what the kernel image looks like after linking: objdump -ph ./kernel.bin

As you can see, the sections in the image coincide with those that we described in the linker script. The linker formed 3 segments from the described sections. The first segment includes sections .multiboot, .text, .rodata and has a virtual and physical address of 0x00100000. The second segment contains the .data and .bss sections and is located at address 0x00104000. This means you are ready to load this file using Grub.

Step 4. Preparing the Grub bootloader: Create the grub folder:

mkdir grub

Copy into this folder several Grub files that are necessary to install it on the image (the following files exist if Grub is installed on the system). To do this you need to run the following commands:

cp /usr/lib/grub/i386-pc/stage1 ./grub/ cp /usr/lib/grub/i386-pc/stage2 ./grub/ cp /usr/lib/grub/i386-pc/fat_stage1_5 ./grub /

Create a file grub/menu.lst with the following content:

timeout 3 default 0 title mini_os root (hd0,0) kernel /kernel.bin

Step 5. Automate and create a boot image:

To automate the build process we will use the make utility. To do this, we will create a makefile that will compile the source code, build the kernel and create a boot image. The Makefile should have the following contents: CC=gcc CFLAGS=-Wall -fno-builtin -nostdinc -nostdlib LD=ld OBJFILES=\loader.o\common/printf.o\common/screen.o\kernel.o image: @echo "Creating hdd.img..." @dd if=/dev/zero of=./hdd.img bs=512 count=16065 1>/dev/NULL 2>&1 @echo "Creating bootable first FAT32 partition..." @losetup / dev/loop1 ./hdd.img @(echo c; echo u; echo n; echo p; echo 1; echo ; echo ; echo a; echo 1; echo t; echo c; echo w;) | fdisk /dev/loop1 1>/dev/NULL 2>&1 || true @echo "Mounting partition to /dev/loop2..." @losetup /dev/loop2 ./hdd.img \ --offset `echo \`fdisk -lu /dev/loop1 | sed -n 10p | awk '{print $$3}'\`*512 | bc` \ --sizelimit `echo \`fdisk -lu /dev/loop1 | sed -n 10p | awk '{print $$4}'\`*512 | bc` @losetup -d /dev/loop1 @echo “Format partition...” @mkdosfs /dev/loop2 @echo “Copy kernel and grub files on partition...” @mkdir -p tempdir @mount /dev/loop2 tempdir @mkdir tempdir /boot @cp -r grub tempdir/boot/ @cp kernel.bin tempdir/ @sleep 1 @umount /dev/loop2 @rm -r tempdir @losetup -d /dev/loop2 @echo “Installing GRUB...” @echo “ device (hd0) hdd.img \n \ root (hd0,0) \n \ setup (hd0) \n \ quit\n» | grub --batch 1>/dev/NULL @echo "Done!" all: kernel.bin rebuild: clean all .so: as -o [email protected] $< .co: $(CC) -Iinclude $(CFLAGS) -o [email protected] -c $< kernel.bin: $( OBJFILES) $(LD) -T linker.ld -o [email protected] $^ clean: rm -f $(OBJFILES) hdd.img kernel.bin
The file declares two main purposes: all - compiles the kernel, and image - which creates a boot disk. The all goal, like the usual makefile, contains subgoals .so and .co, which compile *.s and *.c files into object files (*.o), as well as a goal for generating kernel.bin, which calls the linker with the previously created script. These targets perform exactly the same commands that are specified in step 3. Of greatest interest here is the creation of a boot image hdd.img (target image). Let's look at how this happens step by step.

dd if=/dev/zero of=./hdd.img bs=512 count=16065 1>/dev/NULL 2>&1 This command creates an image with which further work will occur. The number of sectors was not chosen at random: 16065 = 255 * 63. By default, fdsik works with the disk as if it had CHS geometry, in which Headers (H) = 255, Sectors (S) = 63, and Cylinders (C) depends on disk size. Thus, the minimum disk size that the fdsik utility can work with, without changing the default geometry, is 512 * 255 * 63 * 1 = 8225280 bytes, where 512 is the sector size and 1 is the number of cylinders. Next, a partition table is created: losetup /dev/loop1 ./hdd.img (echo c; echo u; echo n; echo p; echo 1; echo ; echo ; echo a; echo 1; echo t; echo c; echo w; ) | fdisk /dev/loop1 1>/dev/NULL 2>&1 || true The first command mounts the hdd.img file to the block device /dev/loop1, allowing the file to be treated as a device. The second command creates a partition table on the /dev/loop1 device that contains 1 primary boot disk partition that occupies the entire disk, labeled FAT32. Then we format the created partition. To do this, you need to mount it as a block device and format it. losetup /dev/loop2 ./hdd.img \ —offset `echo \`fdisk -lu /dev/loop1 | sed -n 10p | awk '{print $$3}'\`*512 | bc` \ --sizelimit `echo \`fdisk -lu /dev/loop1 | sed -n 10p | awk '{print $$4}'\`*512 | bc` losetup -d /dev/loop1 The first command mounts the previously created partition to the /dev/loop2 device. The –offset option specifies the address of the beginning of the section, and –sizelimit specifies the address of the end of the section. Both options are obtained using the fdisk command. mkdosfs /dev/loop2 The mkdosfs utility formats the partition to the FAT32 file system. To directly build the kernel, the previously discussed commands in the classic makefile syntax are used. Now let's look at how to install GRUB on a partition: mkdir -p tempdir # creates a temporary directory mount /dev/loop2 tempdir # mounts the partition in the mkdir directory tempdir/boot # creates a /boot directory on the partition cp -r grub tempdir/boot/ # copy the grub folder in /boot cp kernel.bin tempdir/ # copies the kernel to the root of the partition sleep 1 # wait for Ubuntu umount /dev/loop2 # unmount the temporary folder rm -r tempdir # delete the temporary folder losetup -d /dev/loop2 # unmount the partition After completing the above commands, the image will be ready for GRUB installation. The following command installs GRUB into the MBR of the hdd.img disk image. echo "device (hd0) hdd.img \n \ root (hd0,0) \n \ setup (hd0) \n \ quit\n" | grub --batch 1>/dev/NULL

Everything is ready for testing!

Step 6. Launch:

To compile, use the command:

make all After which the kernel.bin file should appear. To create a bootable disk image, use the command: sudo make image As a result, the hdd.img file should appear. Now you can boot from the hdd.img disk image. You can check this using the following command: qemu -hda hdd.img -m 32 or: qemu-system-i386 -hda hdd.img

To check on a real machine, you need to dd this image to a flash drive and boot from it. For example with this command:

sudo dd if=./hdd.img of=/dev/sdb

To summarize, we can say that as a result of the actions taken, a set of source codes and scripts is obtained that allow us to conduct various experiments in the field of system programming. The first step has been taken towards the creation of system software such as hypervisors and operating systems.

Links to the following articles in the series: “ How to run a program without an operating system: part 2

" "
How to run a program without an operating system: part 3: Graphics
" "
How to run a program without an operating system: part 4. Parallel computing
" "
How to run a program without an operating system: part 5. Accessing the BIOS from the OS
" "
How to run a program without operating system: part 6. Support for working with disks with the FAT file system
"

How to open Windows Command Prompt?

Some of the console commands can only be executed from an administrator account. Therefore, it is better to immediately remember how to launch the interpreter with the maximum number of access rights to the system. In Windows 7/8/10 this is done simply:

  • Open "Search" in/near the "Start" menu.
  • Enter the search field "Command Prompt".
  • The search results will display the program we need. Right-click on it, then select “Run as administrator” from the drop-down menu.

But to perform simple commands, the Windows console can be launched without administrator rights. The easiest way to do this is as follows:

  • Press the "Win" and "R" keys on your keyboard.
  • The Run window will open.
  • Enter the cmd and click OK.

One way or another, the Windows Command Prompt system application will be launched and ready to execute user commands:

Rating
( 1 rating, average 5 out of 5 )
Did you like the article? Share with friends:
For any suggestions regarding the site: [email protected]
Для любых предложений по сайту: [email protected]