How to HLT the program without using HLT - emu8086

How I can stop executing the program without HLT Written at the end of the code I have read that HLT can occur on there interrupt but I couldn't understand how

The HLT instruction does not actually terminate the program. As far as I can tell, its main use is putting the CPU in "idle" mode to reduce power consumption. But that only lasts until the next interrupt fires, then program execution will continue.
You should probably do a system call (a call into your OS), either to tell the OS to terminate your process, or to "yield" the processor (letting the OS HLT it for you in an appropriate fashion).
How exactly system calls work and which one you need depends on the OS your program is running on. On DOS, there's e.g. INT 21h (MOV AH, 4Ch; INT 21h will terminate your program IIRC), for Linux, look up "syscalls").
If you want to truly halt program execution, i.e. intentionally hang the computer, you can either:
enter into an infinite loop (here: JMP here), or
disable (maskable) interrupts using CLI, followed by HLT.
The second option might be more power efficient, however both are equally non-user friendly and probably somewhat pointless. :)
(Disclaimer: I haven't been doing system-level programming in a while, the above information might be a little rough around the edges.)

Related

Interrupt for a systemcall?

Hey guys just wanted to confirm that I correctly understand how a systemcall is invoked.
So if a programm needs access to a kernel functionality it loads the system call number into a register and calls a software interrupt(in linux 0x80).
Then the NVIC(or AVIC) makes the processor jump to the beginning of the interrupt handler and makes the cpu go into supervisor mode.
Then the interrupt handler gets the system call number and jumps to the kernel code that handles the system call.
In the end the programm goes back to its original state and continuous running.
It cannot work that way because interrupt vectors also have permission bits. If the user mode processes could just trigger an interrupt vector to jump into kernel mode, it would be able to break the system by triggering whatever fault it pleases.
Instead, on 32 bits x86, the int 0x80 interrupt is given a user mode permission so, when processes use it, they are still in user mode once the interrupt is started. The interrupt handler will then use the sysenter assembly instruction to jump into kernel mode. The sysenter instruction jumps to the address specified in a register set at boot from kernel mode.
The equivalent for 64 bits x86 is syscall. Actually, on x64 platforms, the syscall instruction is used directly by glibc and libstdc++.

Is there a way to add code to an infinite z80 assembly loop?

A while ago, I asked what the fastest infinite loop was on a TI-84. One of the answers I got involved using an assembly infinite loop with this code:
AsmPrgm
18FE
However, this is a bit impractical, because it can only be exited with the reset button and doesnt run anything inside it.
Is there a way to put TI-Basic code inside of this loop and/or make it exit conditionally?
Here is the link to the original question and answer:
What is the fastest infinite loop in TI-84+ Basic?
$18FE is jr -2, which loops two bytes backwards, in on itself. You'll want the additional logic to come after the start of the loop to let you escape (i.e. checking for button presses), then just have it loop back to that label. To do that, you'd need to adjust the $FE value, as that's the distance to jump. It's a signed 8-bit value, so make sure you get all your conditional code in, then branch back depending on the number of bytes you've used.
Regarding your original (linked) question, jr $ is not the fastest loop possible on Z80, as the fastest one is jp $ (actually jp (hl)), where $ denotes the address of the current instruction.
The fastest exitable loop could be done in three ways, depending on what is your definition of 'loop' is and how the loop should be exited:
Use the interrupts to quit abovementioned loop: in this case, you should unwind stack in the interrupt (remove return address) and jump elsewhere.
Use the loop like this:
​
IN reg,(C)
JP cc,$-2
where IN reg,(C) command also sets S (sign), Z (zero) and P/V (parity) flags depending on the value read from port and JP cc uses one of those flags to continue the loop or leave it.
Use the HALT and exit it naturally with the interrupt.
It is known that Z80 executes HALT by continuously fetching the same byte following HALT instruction from the memory, then ignoring it and doing that until the interrupt is caught. This behaviour could be described as looping until the interrupt is caught. The root cause for such behaviour is that Z80 naturally does DRAM refresh every opcode fetch and this way the refresh is kept during HALT execution.
You can definitely make assembly programs exit conditionally. The command C9 is return, so if you have a program consisting of only AsmPrgmC9, running it as an assembly program will have it instantly finish (it will look the same as running a program with nothing in it). If you want to end the loop when some condition is met, then you'll need to start learning assembly as the answer will widely vary on what that condition is and what OS version/calculator you're using.

how DOS executed multiple processes simultaneously?

DOS is always given as an example of single tasking operating system. However when a command is issued through command-line, control switches from the shell to the command and then switches back to shell when the command completes.Thus there are two processes executing simultaneously. Is there something wrong in my understanding ?
No, they weren't executing simultaneously.
COMMAND.COM had a resident portion that was in memory all the time and a transient portion that could be tossed out at will.
When you ran a program, it typically got loaded in place of the transient portion and then run. When the program exited, it did so by calling code in the resident portion which would then reload the transient portion if necessary and continue.
The fact that some of the code remained resident in no way means that it was "running". In a similar way, vast tracts of MS-DOS (the kernel) stayed continuously in memory yet they weren't "running", unless called explicitly by a non-kernel program.
Now there were things can could be said to run concurrently, DOS had plenty of TSR (terminate and stay resident) programs that would run, hook into an interrupt or DOS in some way, then exit but leaving some memory allocated (where its code was).
Then, in response to certain events, that code would be run. Perhaps one of the famous ones was Borland Sidekick which was a personal information manager that would pop up instantly with a keypress.
While the other process is running, the command line processor is not running: it is suspended. The only "multitasking" facility that was available in DOS was "Terminate and Stay Resident".
It doesnt matter whether you are running DOS or Windows or Linux or BSD or whatever on that processor it is all the same. At that period of time you for purposes of this discussion had a single execution unit, a single core executing the instructions, mostly in order. Makes no difference if those instructions wear the name DOS or Linux or windows. Just instructions.
Just like now as then when a windows program decides to terminate it tries to do it nicely with some flavor of exit call. When a linux program terminates it tries to do so nicely with some flavor of exit call to the system. And when a dos program terminates it tries to do so nicely with some flavor of exit call to the system. In a shell, command prompt, etc linux, windows, dos, that shell, which is a program itself, loads and branches to the program you have loaded and your program runs for a while and as mentioned tries to return to the prior program nicely with some flavor of exit. Just like when the shell you were running wants to return when it is done running it tries to do so nicely.
As with linux or windows, easier to see back then, you dont run anything "at the same time" or "in parallel" one instruction stream at a time. (today we have multiple execution units and/or cores that are designed to each be doing something in parallel with something managing them, so today you can actually say "in parallel") You want to switch "tasks" or "threads" or "processes" you needed an interrupt, that switched to you different code, an interrupt handler, and that handler could return to the same program that was interrupted or switch to another. You can put whatever name on it you want it is how you make things look like they are running at the same time. dos, linux, windows, etc, this is typically how you switch from one "program" or bit of code to another. linux and windows have their kernels and operating system behind them that was called during the interrupts, and dos had that as well (dos HAS that, dos is still alive you touch a dos machine every few days most likely (gas pump, atm machine, etc), dos is also still used in the development and testing of x86 motherboards/computers, nothing can compete with it as an embedded x86 platform, nothing has the freedom that dos has to do what you want, this is why bios upgrades are still distributed as a dos program). The interrupt handlers would give time slices to the various bios handlers and dos handlers. task/process/thread switching was not as designed or planned as an operating system like linux or windows, but it was there, for each version of dos there were rules you followed and you could switch tasks (tsrs are a popular term). Just talking to a floppy, hard disk, etc there was code involved in the whole process, it wasnt buried in the hardware, lots of things happened in parallel. no different than a hard disk controller driver in something more complicated like linux or windows. At least one, maybe some, non-microsoft dos clones could multitask.
The short answer, When you have a function bob() that calls a function ted().
int bob ( int something )
{
...some code
...more code
ted();
...some code
...more code
}
is bob() still running? Are they running in parallel? No, the bob() code is still there, somewhere, waiting for the ted() code to finish what it was doing and return. So long as ted() doesnt crash it will return and bob() can continue to execute. bob is suspended while ted executes. Not much different with a shell or command line in an more complicated operating system. There is some function somewhere that has loaded your program into memory and called it, it might be a fork or clone of a command line that you were running so that that command line can continue "in parallel" or the clone can continue in parallel. but the concept is the same.
The difference from a trivial C program like the one above is that the code above can be thought of being resolved at compile time where loading and running a program is definitely runtime, basically self modifying code, the program modifies memory then jumps to it. When it returns that code, cleans up, unwinds, and exits itself or waits for another command depending on the design. DOS was just very very simple, a bunch of system calls, combined with a bunch of BIOS calls, and a very simple command line that could load programs and do a small number of other commands. It didnt have any rules you couldnt get around (windows is a dos program), if the program you launched didnt want to return (you could at least at the time launch linux from dos through an intermediate dos program) well it kind of messes up your question of what happens when the program completes, well linux didnt return, it took over the system.

How can I interrupt MATLAB when it gets really really busy?

I'm running a long simulation in MATLAB that I've realized I need to stop and rerun. However, MATLAB is really into this calculation, and it's stopped responding. How can I interrupt this run without killing MATLAB?
(I realize this is a problem with many Windows programs, but it's really acute with MATLAB.)
Go to the command window, and hit Ctrl-C a lot. From my experience, on a single-core machine you do not have a chance, unless you do lots of output. On a multi-core or multi-processor machine, you'll probably stop it eventually, but it takes time.
See also http://www.mathworks.com/support/solutions/en/data/1-188VX/index.html
Added: it is a good practice to (1) save a snapshot of your workspace before running anything really long and (2) within a very long calculation, write some of the variables to a file from time to time, so that you can resume the calculation if it was interrupted (by power failure, e.g.).
How well MATLAB responds to CTRL-C rather depends on what it's doing. If it's in the middle of a BLAS or LAPACK call for example, it will not respond until that call returns. If you're in a block of code where lots of lines of MATLAB are being executed, you can expect CTRL-C to be more responsive.
I have got a very simple trick to pause (or stop) a non-responsive execution.
If my simulation is running a long loop I always do the following:
for ii = 1:N
do_stuff();
clear empty_script;
empty_script;
end
And then create a file empty_script.m containing the following:
%keyboard
Whenever I want to pause execution I open an external text editor and uncomment the line saying keyboard in empty_script.m. That leaves me in debugging mode where I can watch variables, modify stuff or even stop the program.
Another strategy for dealing with this problem is to introduce a very short pause somewhere in the calculation (especially in a FOR or WHILE loop), as in:
for ii = 1:N
do_stuff();
pause(0.1);
end
This increases the chances that your maniacal Ctrl-C'ing will actually stop it.
you can find the MATLAB process in the windows task manager and set the priority as high or low and let other program to have lower or higher priority. In my experience, it is an efficient way.
if you wont to stop and rerun then killing is not bad choise
Go to windows task manager-> Processes then fined MATLAB.exe and push the End Process button

What is INT 21h?

Inspired by this question
How can I force GDB to disassemble?
I wondered about the INT 21h as a concept. Now, I have some very rusty knowledge of the internals, but not so many details. I remember that in C64 you had regular Interrupts and Non Maskable Interrupts, but my knowledge stops here. Could you please give me some clue ? Is it a DOS related strategy ?
From here:
A multipurpose DOS interrupt used for various functions including reading the keyboard and writing to the console and printer. It was also used to read and write disks using the earlier File Control Block (FCB) method.
DOS can be thought of as a library used to provide a files/directories abstraction for the PC (-and a bit more). int 21h is a simple hardware "trick" that makes it easy to call code from this library without knowing in advance where it will be located in memory. Alternatively, you can think of this as the way to utilise the DOS API.
Now, the topic of software interrupts is a complex one, partly because the concepts evolved over time as Intel added features to the x86 family, while trying to remain compatible with old software. A proper explanation would take a few pages, but I'll try to be brief.
The main question is whether you are in real mode or protected mode.
Real mode is the simple, "original" mode of operation for the x86 processor. This is the mode that DOS runs in (when you run DOS programs under Windows, a real mode processor is virtualised, so within it the same rules apply). The currently running program has full control over the processor.
In real mode, there is a vector table that tells the processor which address to jump to for every interrupt from 0 to 255. This table is populated by the BIOS and DOS, as well as device drivers, and sometimes programs with special needs. Some of these interrupts can be generated by hardware (e.g. by a keypress). Others are generated by certain software conditions (e.g. divide by 0). Any of them can be generated by executing the int n instruction.
Programs can set/clear the "enable interrupts" flag; this flag affects hardware interrupts only and does not affect int instructions.
The DOS designers chose to use interrupt number 21h to handle DOS requests - the number is of no real significance: it was just an unused entry at the time. There are many others (number 10h is a BIOS-installed interrupt routine that deals with graphics, for instance). Also note that all this is for IBM PC compatibles only. x86 processors in say embedded systems may have their software and interrupt tables arranged quite differently!
Protected mode is the complex, "security-aware" mode that was introduced in the 286 processor and much extended on the 386. It provides multiple privilege levels. The OS must configure all of this (and if the OS gets it wrong, you have a potential security exploit). User programs are generally confined to a "minimal privilege" mode of operation, where trying to access hardware ports, or changing the interrupt flag, or accessing certain memory regions, halts the program and allows the OS to decide what to do (be it terminate the program or give the program what it seems to want).
Interrupt handling is made more complex. Suffice to say that generally, if a user program does a software interrupt, the interrupt number is not used as a vector into the interrupt table. Rather a general protection exception is generated and the OS handler for said exception may (if the OS is design this way) work out what the process wants and service the request. I'm pretty sure Linux and Windows have in the past (if not currently) used this sort of mechanism for their system calls. But there are other ways to achieve this, such as the SYSENTER instruction.
Ralph Brown's interrupt list contains a lot of information on which interrupt does what. int 21, like all others, supports a wide range of functionality depending on register values.
A non-HTML version of Ralph Brown's list is also available.
The INT instruction is a software interrupt. It causes a jump to a routine pointed to by an interrupt vector, which is a fixed location in memory. The advantage of the INT instruction is that is only 2 bytes long, as oposed to maybe 6 for a JMP, and that it can easily be re-directed by modifying the contents of the interrupt vector.
Int 0x21 is an x86 software interrupt - basically that means there is an interrupt table at a fixed point in memory listing the addresses of software interrupt functions. When an x86 CPU receives the interrupt opcode (or otherwise decides that a particular software interrupt should be executed), it references that table to execute a call to that point (the function at that point must use iret instead of ret to return).
It is possible to remap Int 0x21 and other software interrupts (even inside DOS though this can have negative side effects). One interesting software interrupt to map or chain is Int 0x1C (or 0x08 if you are careful), which is the system tick interrupt, called 18.2 times every second. This can be used to create "background" processes, even in single threaded real mode (the real mode process will be interrupted 18.2 times a second to call your interrupt function).
On the DOS operating system (or a system that is providing some DOS emulation, such as Windows console) Int 0x21 is mapped to what is effectively the DOS operating systems main "API". By providing different values to the AH register, different DOS functions can be executed such as opening a file (AH=0x3D) or printing to the screen (AH=0x09).
This is from the great The Art of Assembly Language Programming about interrupts:
On the 80x86, there are three types of events commonly known as
interrupts: traps, exceptions, and interrupts (hardware interrupts).
This chapter will describe each of these forms and discuss their
support on the 80x86 CPUs and PC compatible machines.
Although the terms trap and exception are often used synonymously, we
will use the term trap to denote a programmer initiated and expected
transfer of control to a special handler routine. In many respects, a
trap is nothing more than a specialized subroutine call. Many texts
refer to traps as software interrupts. The 80x86 int instruction is
the main vehicle for executing a trap. Note that traps are usually
unconditional; that is, when you execute an int instruction, control
always transfers to the procedure associated with the trap. Since
traps execute via an explicit instruction, it is easy to determine
exactly which instructions in a program will invoke a trap handling
routine.
Chapter 17 - Interrupt Structure and Interrupt Service Routines
(Almost) the whole DOS interface was made available as INT21h commands, with parameters in the various registers. It's a little trick, using a built-in-hardware table to jump to the right code. Also INT 33h was for the mouse.
It's a "software interrupt"; so not a hardware interrupt at all.
When an application invokes a software interrupt, that's essentially the same as its making a subroutine call, except that (unlike a subroutine call) the doesn't need to know the exact memory address of the code it's invoking.
System software (e.g. DOS and the BIOS) expose their APIs to the application as software interrupts.
The software interrupt is therefore a kind of dynamic-linking.
Actually, there are a lot of concepts here. Let's start with the basics.
An interrupt is a mean to request attention from the CPU, to interrupt the current program flow, jump to an interrupt handler (ISR - Interrupt Service Routine), do some work (usually by the OS kernel or a device driver) and then return.
What are some typical uses for interrupts?
Hardware interrupts: A device requests attention from the CPU by issuing an interrupt request.
CPU Exceptions: If some abnormal CPU condition happens, such as a division by zero, a page fault, ... the CPU jumps to the corresponding interrupt handler so the OS can do whatever it has to do (send a signal to a process, load a page from swap and update the TLB/page table, ...).
Software interrupts: Since an interrupt ends up calling the OS kernel, a simple way to implement system calls is to use interrupts. But you don't need to, in x86 you could use a call instruction to some structure (some kind of TSS IIRC), and on newer x86 there are SYSCALL / SYSENTER intructions.
CPUs decide where to jump to looking at a table (exception vectors, interrupt vectors, IVT in x86 real mode, IDT in x86 protected mode, ...). Some CPUs have a single vector for hardware interrupts, another one for exceptions and so on, and the ISR has to do some work to identify the originator of the interrupt. Others have lots of vectors, and jump directly to very specific ISRs.
x86 has 256 interrupt vectors. On original PCs, these were divided into several groups:
00-04 CPU exceptions, including NMI. With later CPUs (80186, 286, ...), this range expanded, overlapping with the following ranges.
08-0F These are hardware interrupts, usually referred as IRQ0-7. The PC-AT added IRQ8-15
10-1F BIOS calls. Conceptually, these can be considered system calls, since the BIOS is the part of DOS that depends on the concrete machine (that's how it was defined in CP/M).
20-2F DOS calls. Some of these are multiplexed, and offer multitude of functions. The main one is INT 21h, which offers most of DOS services.
30-FF The rest, for use by external drivers and user programs.